Open History to see the last commit
1import * as Dialog from "../components/ui/Dialog";
2import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
3import { readEnvironmentScope } from "./session";
4import type { ComposerTextPaste } from "../native/T3ComposerEditor.types";
5import { useAtomValue } from "@effect/atom-react";
6import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
7import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff";
8import {
9 deriveProviderSubagentStatus,
10 deriveRunlessWorkStartedAt,
11 deriveThreadActivityRun,
12 deriveThreadRuntime,
13 threadRuntimeHasInterruptibleRun,
14} from "@t3tools/client-runtime/state/thread-execution";
15import { useCallback, useEffect, useMemo, useRef, useState } from "react";
16
17import {
18 CommandId,
19 DEFAULT_PROVIDER_INTERACTION_MODE,
20 MessageId,
21 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
22 PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
23 type EnvironmentId,
24 type ModelSelection,
25 type ProviderInteractionMode,
26 type RuntimeMode,
27 type ThreadId,
28} from "@t3tools/contracts";
29import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
30import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
31import { nextPastedTextFileName, pastedTextDisposition } from "@t3tools/client-runtime/text-paste";
32import {
33 parseCodexFeedbackCommand,
34 submitCodexFeedback,
35 type CodexFeedbackSubmission,
36} from "@t3tools/client-runtime/state/threads";
37import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
38import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLegacy";
39import { composerContextSendBlockReason, reidentifyComposerContext } from "../lib/composerContext";
40import { uuidv4 } from "../lib/uuid";
41
42import { makeQueuedMessageMetadata } from "../lib/commandMetadata";
43import {
44 describeUnavailableModelSelection,
45 isModelSelectionUnavailable,
46} from "../lib/modelOptions";
47import { resolveProviderInteractionMode } from "./legacy-plan-mode";
48import {
49 convertPastedImagesToAttachments,
50 createPastedTextComposerAttachment,
51 pasteComposerClipboard,
52 pickComposerFiles,
53 pickComposerMedia,
54 removePersistedComposerAttachmentFile,
55} from "../lib/composerImages";
56import type { DraftComposerImageAttachment } from "../lib/composerImages";
57import { scopedThreadKey } from "../lib/scopedEntities";
58import { buildThreadFeed } from "../lib/threadActivity";
59import { acknowledgedThreadMessagesAtom } from "./acknowledged-thread-messages";
60import { appendPendingThreadMessages } from "../features/threads/pending-thread-feed";
61import { threadAllowsProviderSwitch } from "./thread-provider-switching";
62import { appAtomRegistry } from "../state/atom-registry";
63import { pendingThreadCreationMessage } from "./pending-thread-creation";
64import {
65 composerAttachmentUploadBlockReason,
66 composerAttachmentUploadsAtom,
67} from "../state/composer-attachment-uploads";
68import {
69 appendComposerDraftAttachments,
70 captureComposerDraftInsertion,
71 countComposerDraftAttachmentsAfterSelection,
72 insertComposerDraftText,
73 insertComposerDraftContext,
74 clearComposerDraftContent,
75 composerDraftsAtom,
76 composerContextImportsAtom,
77 ensureComposerDraftsLoaded,
78 getComposerDraftSnapshot,
79 mergeComposerDraftContent,
80 removeComposerDraftAttachment,
81 scheduleUnusedComposerAttachmentCleanup,
82 setComposerDraftText,
83 updateComposerDraftSettings,
84 useComposerDraft,
85} from "./use-composer-drafts";
86import {
87 resolveComposerDispatchMode,
88 type ActiveTurnComposerAction,
89} from "@t3tools/client-runtime/state/composer-dispatch";
90import { Atom } from "effect/reactivity";
91import { AsyncResult } from "effect/reactivity";
92import { prepareTurnAttachments } from "../lib/attachmentUpload";
93import { DEFAULT_FOLLOW_UP_BEHAVIOR } from "../lib/followUpBehavior";
94import { mobilePreferencesAtom } from "./preferences";
95import { environmentThreadDetails } from "./threads";
96import {
97 endQueuedRunEdit,
98 getQueuedRunEdit,
99 queuedEditDraftKey,
100 removeQueuedRunEditAttachment,
101 resolveQueuedEditPayload,
102 useQueuedRunEdit,
103} from "./queued-run-edit";
104import { setPendingConnectionError } from "../state/use-remote-environment-registry";
105import { clearThreadComposerError, setThreadComposerError } from "./thread-composer-error";
106import {
107 useSelectedThreadProjection,
108 useSelectedThreadVisibleTurnItems,
109} from "../state/use-thread-detail";
110import { useThreadSelection } from "../state/use-thread-selection";
111import { enqueueThreadOutboxMessage } from "./thread-outbox";
112import { dispatchingQueuedMessageIdAtom, useThreadOutboxMessages } from "./use-thread-outbox";
113import { threadEnvironment } from "./threads";
114import { useAtomCommand } from "./use-atom-command";
115
116const EMPTY_QUEUE_WORKFLOW_ATOM = Atom.make<null>(null).pipe(
117 Atom.withLabel("mobile-thread-queue-workflow:empty"),
118);
119
120export function appendReviewCommentToDraft(input: {
121 readonly environmentId: EnvironmentId;
122 readonly threadId: ThreadId;
123 readonly text: string;
124 readonly attachments?: ReadonlyArray<DraftComposerImageAttachment>;
125}): void {
126 const threadKey = scopedThreadKey(input.environmentId, input.threadId);
127 const upgraded = upgradeLegacyContextMessage(input.text);
128 if (
129 !insertComposerDraftContext(
130 threadKey,
131 reidentifyComposerContext(upgraded.text, upgraded.records, uuidv4),
132 )
133 ) {
134 Dialog.alert("Too many context items", "Remove some context from the draft and try again.");
135 return;
136 }
137 if (input.attachments && input.attachments.length > 0) {
138 // Capped: a review comment is new content, not a send-failure restore, so
139 // it must not push the draft over the send limit. Overflow is released.
140 const rejectedCount = appendComposerDraftAttachments(threadKey, input.attachments, {
141 appendReference: true,
142 });
143 if (rejectedCount > 0) {
144 setPendingConnectionError(
145 `${rejectedCount} comment attachment${rejectedCount === 1 ? " was" : "s were"} not added. Messages can contain at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments.`,
146 );
147 }
148 }
149}
150
151/**
152 * Which draft the composer is editing right now. While a queued message is
153 * being edited the composer is pointed at that edit's own draft, so typing,
154 * attaching, and pasting never touch the user's draft for the thread.
155 * Resolved per call rather than captured, so a callback created before the
156 * edit began still writes to the right place.
157 */
158function activeComposerDraftKey(thread: {
159 readonly environmentId: EnvironmentId;
160 readonly id: ThreadId;
161}): string {
162 const threadKey = scopedThreadKey(thread.environmentId, thread.id);
163 const edit = getQueuedRunEdit(threadKey);
164 return edit === null ? threadKey : queuedEditDraftKey(threadKey, edit.runId);
165}
166
167export function useThreadDraftForThread(input: {
168 readonly environmentId?: EnvironmentId;
169 readonly threadId?: ThreadId;
170}) {
171 const threadKey =
172 input.environmentId && input.threadId
173 ? scopedThreadKey(input.environmentId, input.threadId)
174 : null;
175 const draft = useComposerDraft(threadKey);
176
177 return {
178 draftMessage: draft.text,
179 draftAttachments: draft.attachments,
180 };
181}
182
183export function useThreadComposerState() {
184 const {
185 selectedThread: selectedThreadShell,
186 selectedThreadCreation,
187 selectedThreadDetailRef,
188 selectedEnvironmentRuntime,
189 } = useThreadSelection();
190 const selectedThreadProjection = useSelectedThreadProjection();
191 const selectedThreadVisibleTurnItems = useSelectedThreadVisibleTurnItems();
192 const composerDrafts = useAtomValue(composerDraftsAtom);
193 const acknowledgedMessages = useAtomValue(acknowledgedThreadMessagesAtom);
194 const queuedMessagesByThreadKey = useThreadOutboxMessages();
195 const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
196 const [feedbackSubmissionsByThreadKey, setFeedbackSubmissionsByThreadKey] = useState<
197 Record<string, ReadonlyArray<CodexFeedbackSubmission>>
198 >({});
199 const uploadThreadFeedback = useAtomCommand(threadEnvironment.uploadFeedback, {
200 reportFailure: false,
201 });
202 const editQueuedRun = useAtomCommand(threadEnvironment.editQueuedRun, {
203 label: "edit queued message",
204 reportFailure: false,
205 });
206 const [isSavingQueuedEdit, setIsSavingQueuedEdit] = useState(false);
207 const savingQueuedEditRef = useRef(false);
208 const pastedTextFileNamesRef = useRef<{ threadKey: string | null; names: Set<string> }>({
209 threadKey: null,
210 names: new Set(),
211 });
212 const reservePastedTextFileName = useCallback(
213 (threadKey: string, existingNames: ReadonlyArray<string>) => {
214 if (pastedTextFileNamesRef.current.threadKey !== threadKey) {
215 pastedTextFileNamesRef.current = { threadKey, names: new Set() };
216 }
217 const names = pastedTextFileNamesRef.current.names;
218 for (const name of existingNames) names.add(name);
219 const nextName = nextPastedTextFileName([...names]);
220 names.add(nextName);
221 return nextName;
222 },
223 [],
224 );
225
226 useEffect(() => {
227 ensureComposerDraftsLoaded();
228 }, []);
229
230 const selectedThreadKey = selectedThreadShell
231 ? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id)
232 : null;
233 // The creation entry is the thread itself (rendered as the first message),
234 // not a follow-up waiting behind it.
235 const selectedThreadQueuedMessages = useMemo(
236 () =>
237 selectedThreadKey
238 ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []).filter(
239 (message) => message.creation === undefined,
240 )
241 : [],
242 [queuedMessagesByThreadKey, selectedThreadKey],
243 );
244 const feedbackSubmissions = useMemo(
245 () => (selectedThreadKey ? (feedbackSubmissionsByThreadKey[selectedThreadKey] ?? []) : []),
246 [feedbackSubmissionsByThreadKey, selectedThreadKey],
247 );
248 const dismissFeedback = useCallback(
249 (id: MessageId) => {
250 if (!selectedThreadKey) return;
251 setFeedbackSubmissionsByThreadKey((current) => ({
252 ...current,
253 [selectedThreadKey]: (current[selectedThreadKey] ?? []).filter((entry) => entry.id !== id),
254 }));
255 },
256 [selectedThreadKey],
257 );
258 const selectedThreadMessages = selectedThreadProjection?.projection.messages;
259 const selectedThreadAttempts = selectedThreadProjection?.projection.attempts;
260 const selectedThreadNodes = selectedThreadProjection?.projection.nodes;
261 // A thread whose creation has not delivered its turn yet: the prompt only
262 // exists in the outbox, so it is appended to whatever the server has. The
263 // detail is usually present but empty during a worktree checkout, so this
264 // cannot be an either/or with the loaded messages.
265 const pendingCreationMessage = selectedThreadCreation?.message ?? null;
266 const selectedThreadFeed = useMemo(() => {
267 const pendingCreation =
268 pendingCreationMessage !== null &&
269 !selectedThreadMessages?.some((message) => message.id === pendingCreationMessage.messageId)
270 ? [pendingThreadCreationMessage(pendingCreationMessage)]
271 : [];
272 const feed = buildThreadFeed(selectedThreadVisibleTurnItems, {
273 anchoredMessages: pendingCreation,
274 attempts: selectedThreadAttempts,
275 nodes: selectedThreadNodes,
276 });
277 const pendingAcknowledgments = acknowledgedMessages.filter(
278 (message) =>
279 scopedThreadKey(message.environmentId, message.threadId) === selectedThreadKey &&
280 !selectedThreadQueuedMessages.some((queued) => queued.messageId === message.messageId),
281 );
282 if (pendingAcknowledgments.length === 0) return feed;
283 return appendPendingThreadMessages(feed, feed, pendingAcknowledgments).map((entry) =>
284 entry.pendingMessage ? { ...entry, acknowledged: true } : entry,
285 );
286 }, [
287 selectedThreadMessages,
288 selectedThreadAttempts,
289 selectedThreadNodes,
290 selectedThreadVisibleTurnItems,
291 pendingCreationMessage,
292 selectedThreadKey,
293 selectedThreadQueuedMessages,
294 acknowledgedMessages,
295 ]);
296 useEffect(() => {
297 const echoedIds = new Set(selectedThreadMessages?.map((message) => message.id));
298 if (acknowledgedMessages.some((message) => echoedIds.has(message.messageId))) {
299 appAtomRegistry.set(
300 acknowledgedThreadMessagesAtom,
301 appAtomRegistry
302 .get(acknowledgedThreadMessagesAtom)
303 .filter((message) => !echoedIds.has(message.messageId)),
304 );
305 }
306 }, [acknowledgedMessages, selectedThreadMessages]);
307
308 const preferencesResult = useAtomValue(mobilePreferencesAtom);
309 const followUpBehavior = AsyncResult.isSuccess(preferencesResult)
310 ? (preferencesResult.value.followUpBehavior ?? DEFAULT_FOLLOW_UP_BEHAVIOR)
311 : DEFAULT_FOLLOW_UP_BEHAVIOR;
312 // Steering needs a live provider turn the adapter can interrupt; the queue
313 // workflow already derives that from the session's capabilities.
314 const queueWorkflow = useAtomValue(
315 selectedThreadDetailRef === null
316 ? EMPTY_QUEUE_WORKFLOW_ATOM
317 : environmentThreadDetails.queueWorkflowAtom(selectedThreadDetailRef),
318 );
319 const canSteerActiveTurn = queueWorkflow?.canPromoteToSteer === true;
320 const queuedRunEdit = useQueuedRunEdit(selectedThreadKey);
321 const composerDraftKey =
322 selectedThreadKey === null
323 ? null
324 : queuedRunEdit === null
325 ? selectedThreadKey
326 : queuedEditDraftKey(selectedThreadKey, queuedRunEdit.runId);
327 // Content follows the composer's current draft; the model and mode pickers
328 // stay bound to the thread's own draft, which is what they write to.
329 const editedDraft = composerDraftKey ? composerDrafts[composerDraftKey] : null;
330 const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
331 const draftMessage = editedDraft?.text ?? "";
332 const draftAttachments = editedDraft?.attachments ?? [];
333 const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
334 const selectedThread = selectedThreadShell;
335 const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null;
336 const pendingHandoff = useMemo(
337 () =>
338 resolvePendingHandoff(
339 selectedThreadProjection?.projection,
340 modelSelection,
341 selectedEnvironmentRuntime?.serverConfig?.providers ?? [],
342 ),
343 [modelSelection, selectedThreadProjection, selectedEnvironmentRuntime?.serverConfig?.providers],
344 );
345 const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null;
346 const selectedProvider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
347 (provider) => provider.instanceId === modelSelection?.instanceId,
348 );
349 const interactionMode = selectedThread
350 ? resolveProviderInteractionMode(
351 selectedProvider,
352 selectedDraft?.interactionMode ?? selectedThread.interactionMode,
353 )
354 : null;
355 // Whether the model picker may leave this thread's provider. Derived here
356 // because the projection already drives this hook; the composer only needs
357 // the answer, not a subscription to every projection update.
358 const canSwitchThreadProvider = useMemo(
359 () =>
360 threadAllowsProviderSwitch({
361 thread: selectedThreadShell,
362 projection: selectedThreadProjection?.projection,
363 }),
364 [selectedThreadProjection, selectedThreadShell],
365 );
366 const selectedThreadRuntime = useMemo(
367 () =>
368 selectedThreadProjection
369 ? deriveThreadRuntime(selectedThreadProjection.projection)
370 : (selectedThreadShell?.runtime ?? null),
371 [selectedThreadProjection, selectedThreadShell?.runtime],
372 );
373 const selectedThreadActivityRun = useMemo(
374 () =>
375 selectedThreadProjection
376 ? deriveThreadActivityRun(selectedThreadProjection.projection)
377 : (selectedThreadShell?.latestRun ?? null),
378 [selectedThreadProjection, selectedThreadShell?.latestRun],
379 );
380
381 const isCompacting = useMemo(() => {
382 const queuedCompact = selectedThreadQueuedMessages.some(
383 (message) =>
384 message.messageId === dispatchingQueuedMessageId &&
385 message.text.trim().toLowerCase() === "/compact" &&
386 message.attachments.length === 0,
387 );
388 if (queuedCompact) return true;
389 const activeRunId = selectedThreadRuntime?.activeRunId;
390 if (!activeRunId || !threadRuntimeIsActive(selectedThreadRuntime)) return false;
391 const compactMessage = selectedThreadVisibleTurnItems.findLast(
392 ({ item }) =>
393 item.runId === activeRunId &&
394 item.type === "user_message" &&
395 item.text.trim().toLowerCase() === "/compact" &&
396 item.attachments.length === 0,
397 );
398 if (!compactMessage) return false;
399 return !selectedThreadVisibleTurnItems.some(
400 ({ item }) =>
401 item.runId === activeRunId &&
402 item.type === "compaction" &&
403 (item.status === "completed" || item.status === "failed"),
404 );
405 }, [
406 dispatchingQueuedMessageId,
407 selectedThreadQueuedMessages,
408 selectedThreadRuntime,
409 selectedThreadVisibleTurnItems,
410 ]);
411
412 const runlessWorkStartedAt = useMemo(
413 () =>
414 selectedThreadProjection
415 ? deriveRunlessWorkStartedAt(selectedThreadProjection.projection)
416 : null,
417 [selectedThreadProjection],
418 );
419 const activeWorkStartedAt = useMemo(() => {
420 if (!selectedThreadShell) {
421 return null;
422 }
423 return (
424 resolveThreadWorkingStartedAt({
425 latestRun: selectedThreadActivityRun,
426 runtime: selectedThreadRuntime,
427 }) ?? runlessWorkStartedAt
428 );
429 }, [selectedThreadActivityRun, runlessWorkStartedAt, selectedThreadRuntime, selectedThreadShell]);
430 const runlessWorkActive = runlessWorkStartedAt !== null;
431
432 const providerSubagentStatus = useMemo(
433 () =>
434 selectedThreadProjection
435 ? deriveProviderSubagentStatus(selectedThreadProjection.projection)
436 : null,
437 [selectedThreadProjection],
438 );
439
440 // The run can start, or be cancelled from another client, while its message
441 // is open in the composer. Leave edit mode rather than saving into a run the
442 // server will refuse, and keep whatever was typed if there is room for it.
443 const selectedThreadRuns = selectedThreadProjection?.projection.runs;
444 const editedRunId = queuedRunEdit?.runId ?? null;
445 useEffect(() => {
446 if (selectedThreadKey === null || editedRunId === null || selectedThreadRuns === undefined) {
447 return;
448 }
449 if (savingQueuedEditRef.current) return;
450 const stillQueued = selectedThreadRuns.some(
451 (run) => run.id === editedRunId && run.status === "queued",
452 );
453 if (stillQueued) return;
454 const editDraftKey = queuedEditDraftKey(selectedThreadKey, editedRunId);
455 const editDraft = getComposerDraftSnapshot(editDraftKey);
456 const threadDraft = getComposerDraftSnapshot(selectedThreadKey);
457 const keepable =
458 editDraft.text.trim().length > 0 &&
459 threadDraft.text.trim().length === 0 &&
460 threadDraft.attachments.length === 0;
461 if (keepable) {
462 void mergeComposerDraftContent(selectedThreadKey, {
463 text: editDraft.text,
464 attachments: editDraft.attachments,
465 ...(editDraft.context ? { context: editDraft.context } : {}),
466 });
467 }
468 endQueuedRunEdit(selectedThreadKey, { deferAttachmentCleanup: keepable });
469 setThreadComposerError(
470 selectedThreadKey,
471 keepable
472 ? "That message already started. Your edit is back in the composer."
473 : "That message already started, so the edit was discarded.",
474 );
475 }, [editedRunId, selectedThreadKey, selectedThreadRuns]);
476
477 const activeThreadBusy = threadRuntimeIsActive(selectedThreadRuntime);
478 const interruptibleRunId = threadRuntimeHasInterruptibleRun(selectedThreadRuntime)
479 ? (selectedThreadRuntime?.activeRunId ?? null)
480 : null;
481
482 const cancelQueuedRunEdit = useCallback(() => {
483 if (selectedThreadKey === null || savingQueuedEditRef.current) return;
484 endQueuedRunEdit(selectedThreadKey);
485 }, [selectedThreadKey]);
486
487 const onRemoveQueuedEditAttachment = useCallback(
488 (attachmentId: string) => {
489 if (selectedThreadKey === null) return;
490 removeQueuedRunEditAttachment(selectedThreadKey, attachmentId);
491 },
492 [selectedThreadKey],
493 );
494
495 const saveQueuedRunEdit = useCallback(async () => {
496 const thread = selectedThreadShell;
497 if (!thread || savingQueuedEditRef.current) return;
498 const threadKey = scopedThreadKey(thread.environmentId, thread.id);
499 const edit = getQueuedRunEdit(threadKey);
500 if (edit === null) return;
501 const draft = getComposerDraftSnapshot(queuedEditDraftKey(threadKey, edit.runId));
502 const text = draft.text.trim();
503 if (text.length === 0) {
504 // The server rejects an empty queued message, attachments or not.
505 Dialog.alert("Add a message", "A queued message cannot be left empty.");
506 return;
507 }
508 if (
509 edit.existingAttachments.length + draft.attachments.length >
510 PROVIDER_SEND_TURN_MAX_ATTACHMENTS
511 ) {
512 Dialog.alert(
513 "Too many attachments",
514 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
515 );
516 return;
517 }
518 savingQueuedEditRef.current = true;
519 setIsSavingQueuedEdit(true);
520 try {
521 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
522 const prepared = await prepareTurnAttachments({
523 environmentId: thread.environmentId,
524 attachments: draft.attachments,
525 supportsImageUploads: capabilities?.attachmentUploads === true,
526 });
527 if (prepared.status !== "ready") return;
528 const payload = resolveQueuedEditPayload({
529 edit,
530 draftContext: draft.context,
531 draftAttachments: draft.attachments,
532 uploaded: prepared.attachments,
533 });
534 const result = await editQueuedRun({
535 environmentId: thread.environmentId,
536 input: {
537 threadId: thread.id,
538 runId: edit.runId,
539 text,
540 edit: {
541 messageId: edit.messageId,
542 attachments: payload.attachments,
543 ...(payload.context ? { context: payload.context } : {}),
544 },
545 },
546 });
547 if (result._tag !== "Success") {
548 Dialog.alert(
549 "Could not save the queued message",
550 "It may have already started. Your edit is still in the composer.",
551 );
552 return;
553 }
554 endQueuedRunEdit(threadKey, { deferAttachmentCleanup: true });
555 scheduleUnusedComposerAttachmentCleanup(draft.attachments);
556 } finally {
557 savingQueuedEditRef.current = false;
558 setIsSavingQueuedEdit(false);
559 }
560 }, [editQueuedRun, selectedEnvironmentRuntime?.serverConfig, selectedThreadShell]);
561
562 const onSendMessage = useCallback(
563 async (followUpOverride?: ActiveTurnComposerAction) => {
564 if (
565 selectedThreadShell &&
566 selectedEnvironmentRuntime?.connectionState === "connected" &&
567 !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
568 )
569 return null;
570 if (!selectedThreadShell) {
571 return null;
572 }
573 // The server has not created this thread yet. Queuing a follow-up against
574 // its id would strand the message: if the creation is rejected the thread
575 // never appears and the drain drops the orphan. The composer disables its
576 // send button too; this guard also covers the editor's submit key.
577 if (selectedThreadCreation !== null) {
578 return null;
579 }
580
581 // Editing a queued message repurposes the composer: the send button saves
582 // the edit in place instead of enqueuing a new message.
583 const editKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
584 if (getQueuedRunEdit(editKey) !== null) {
585 await saveQueuedRunEdit();
586 return null;
587 }
588
589 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
590 const draft = getComposerDraftSnapshot(threadKey);
591 if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
592 const thread = selectedThreadShell;
593 const text = draft.text.trim();
594 const attachments = draft.attachments;
595 if (
596 composerAttachmentUploadBlockReason({
597 environmentId: selectedThreadShell.environmentId,
598 attachments,
599 connected: selectedEnvironmentRuntime?.connectionState === "connected",
600 serverConfig: selectedEnvironmentRuntime?.serverConfig ?? null,
601 states: appAtomRegistry.get(composerAttachmentUploadsAtom),
602 }) !== null
603 )
604 return null;
605 if (text.length === 0 && attachments.length === 0) {
606 return null;
607 }
608 // A send-failure restore appends with allowOverflow so it never drops the
609 // user's files, which can leave the draft over the cap. Sending it anyway
610 // would enqueue a message that outbox recovery rejects forever, so block
611 // here until the user removes attachments.
612 if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
613 Dialog.alert(
614 "Too many attachments",
615 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
616 );
617 return null;
618 }
619
620 const contextBlockReason = composerContextSendBlockReason(draft.context);
621 if (contextBlockReason) {
622 Dialog.alert("Too much context", contextBlockReason);
623 return null;
624 }
625
626 const modelSelection = draft.modelSelection ?? thread.modelSelection;
627 const serverConfig = selectedEnvironmentRuntime?.serverConfig;
628 if (
629 selectedEnvironmentRuntime?.connectionState === "connected" &&
630 isModelSelectionUnavailable(serverConfig, modelSelection, thread.projectId)
631 ) {
632 const { title, detail } = describeUnavailableModelSelection(
633 serverConfig,
634 modelSelection,
635 thread.projectId,
636 );
637 Dialog.alert(title, detail);
638 return null;
639 }
640 const provider = serverConfig?.providers.find(
641 (entry) => entry.instanceId === modelSelection.instanceId,
642 );
643 const feedbackCommand =
644 attachments.length === 0 && provider?.driver === "codex"
645 ? parseCodexFeedbackCommand(text)
646 : null;
647 if (feedbackCommand) {
648 if (!readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope))
649 return null;
650 if (thread.activeProviderThreadId === null) {
651 Dialog.alert("Start a Codex thread first", "Send a message before you submit feedback.");
652 return null;
653 }
654 const metadata = makeQueuedMessageMetadata();
655 await submitCodexFeedback({
656 submission: {
657 id: MessageId.make(metadata.messageId),
658 command: text,
659 createdAt: metadata.createdAt,
660 },
661 clearDraft: () => clearComposerDraftContent(threadKey),
662 onUpdate: (submission) => {
663 setFeedbackSubmissionsByThreadKey((current) => {
664 const existing = current[threadKey] ?? [];
665 const found = existing.some((entry) => entry.id === submission.id);
666 return {
667 ...current,
668 [threadKey]: found
669 ? existing.map((entry) => (entry.id === submission.id ? submission : entry))
670 : [...existing, submission],
671 };
672 });
673 },
674 upload: () =>
675 uploadThreadFeedback({
676 environmentId: thread.environmentId,
677 input: { threadId: thread.id, ...feedbackCommand },
678 }),
679 });
680 return null;
681 }
682
683 // Resolved here rather than at drain time: the outbox can deliver minutes
684 // later, and the choice belongs to the moment the user pressed send.
685 // Steering travels as "auto" so a turn that ends in the meantime degrades
686 // to a queued run on the server instead of failing the delivery and
687 // bouncing the message back into the draft.
688 const followUpAction = resolveComposerDispatchMode({
689 running: activeThreadBusy && canSteerActiveTurn,
690 alternateModifier: followUpOverride !== undefined && followUpOverride !== followUpBehavior,
691 activeTurnDefault: followUpBehavior,
692 });
693 // A send while the worktree is still being set up waits behind that setup,
694 // so the server can hold it if the setup ends without a worktree.
695 // Before detail loads, the shell's latest run can be a queued follow-up
696 // while its runtime still reports the setup.
697 const setupRunning = [selectedThreadActivityRun?.status, selectedThreadRuntime?.status].some(
698 (status) => status === "preparing" || status === "starting",
699 );
700 const followUpDispatchMode = setupRunning
701 ? "queue"
702 : followUpAction === "auto"
703 ? null
704 : followUpAction === "queue"
705 ? "queue"
706 : "auto";
707
708 const metadata = makeQueuedMessageMetadata();
709 const messageId = MessageId.make(metadata.messageId);
710 // A new send supersedes the reason the previous one bounced back.
711 clearThreadComposerError(threadKey);
712 // Enqueue publishes the queued atom synchronously (the durable write
713 // happens behind it), so clearing the draft here gives send feedback on
714 // the tap frame instead of after file I/O. If the write fails the message
715 // is rolled out of the queue and the content is merged back into the
716 // draft, preserving anything typed since.
717 const enqueuePromise = enqueueThreadOutboxMessage({
718 environmentId: selectedThreadShell.environmentId,
719 threadId: selectedThreadShell.id,
720 messageId,
721 commandId: CommandId.make(metadata.commandId),
722 text,
723 attachments,
724 context: draft.context,
725 modelSelection,
726 runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
727 interactionMode: resolveProviderInteractionMode(
728 provider,
729 draft.interactionMode ?? thread.interactionMode,
730 ),
731 ...(followUpDispatchMode === null ? {} : { dispatchMode: followUpDispatchMode }),
732 createdAt: metadata.createdAt,
733 });
734 clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
735 enqueuePromise.then(
736 () => scheduleUnusedComposerAttachmentCleanup(attachments),
737 (error: unknown) => {
738 // Restore text via merge (idempotent) but attachments via the uncapped
739 // append: the merge path slots existing attachments first and truncates
740 // at the send limit, which would silently drop this message's images if
741 // the user attached new ones while the write was in flight.
742 void mergeComposerDraftContent(threadKey, {
743 text,
744 context: draft.context,
745 attachments: [],
746 });
747 appendComposerDraftAttachments(threadKey, attachments, { allowOverflow: true });
748 setThreadComposerError(
749 threadKey,
750 error instanceof Error ? error.message : "Failed to save the queued message.",
751 );
752 },
753 );
754 return messageId;
755 },
756 [
757 activeThreadBusy,
758 canSteerActiveTurn,
759 followUpBehavior,
760 saveQueuedRunEdit,
761 selectedEnvironmentRuntime?.connectionState,
762 selectedEnvironmentRuntime?.serverConfig,
763 selectedThreadActivityRun?.status,
764 selectedThreadCreation,
765 selectedThreadRuntime?.status,
766 selectedThreadShell,
767 uploadThreadFeedback,
768 ],
769 );
770
771 const onChangeDraftMessage = useCallback(
772 (value: string) => {
773 if (!selectedThreadShell) {
774 return;
775 }
776
777 const threadKey = activeComposerDraftKey(selectedThreadShell);
778 setComposerDraftText(threadKey, value);
779 },
780 [selectedThreadShell],
781 );
782
783 const onPickDraftMedia = useCallback(async () => {
784 if (!selectedThreadShell) {
785 return;
786 }
787
788 const threadKey = activeComposerDraftKey(selectedThreadShell);
789 const insertion = captureComposerDraftInsertion(threadKey);
790 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
791 const result = await pickComposerMedia({
792 existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
793 maxVideoBytes:
794 capabilities?.attachmentUploads === true
795 ? capabilities.fileAttachments?.maxUploadBytes
796 : undefined,
797 });
798 const rejectedCount = appendComposerDraftAttachments(threadKey, result.attachments, {
799 appendReference: true,
800 insertion,
801 });
802 const problems = [
803 ...(result.error ? [result.error] : []),
804 ...(rejectedCount > 0
805 ? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`]
806 : []),
807 ];
808 if (problems.length > 0) {
809 Dialog.alert("Could not attach photo or video", problems.join("\n\n"));
810 }
811 }, [composerDrafts, selectedEnvironmentRuntime?.serverConfig, selectedThreadShell]);
812
813 const onPickDraftFiles = useCallback(async () => {
814 if (!selectedThreadShell) {
815 return;
816 }
817 const maxBytes =
818 selectedEnvironmentRuntime?.serverConfig?.environment.capabilities.fileAttachments
819 ?.maxUploadBytes;
820 if (maxBytes === undefined) {
821 Dialog.alert("Could not attach file", "This server does not support file attachments.");
822 return;
823 }
824
825 const threadKey = activeComposerDraftKey(selectedThreadShell);
826 const insertion = captureComposerDraftInsertion(threadKey);
827 // pickComposerFiles clamps the advertised limit to the contract maximum.
828 const result = await pickComposerFiles({
829 existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
830 maxBytes,
831 });
832 const rejectedCount = appendComposerDraftAttachments(threadKey, result.files, {
833 appendReference: true,
834 insertion,
835 });
836 // The picker error and the live-cap rejection can both happen in one
837 // pick; report both in a single alert.
838 const problems = [
839 ...(result.error ? [result.error] : []),
840 ...(rejectedCount > 0
841 ? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`]
842 : []),
843 ];
844 if (problems.length > 0) {
845 Dialog.alert("Could not attach file", problems.join("\n\n"));
846 }
847 }, [composerDrafts, selectedEnvironmentRuntime?.serverConfig, selectedThreadShell]);
848
849 const onPasteIntoDraft = useCallback(async () => {
850 if (!selectedThreadShell) {
851 return;
852 }
853
854 const threadKey = activeComposerDraftKey(selectedThreadShell);
855 const insertion = captureComposerDraftInsertion(threadKey);
856 const result = await pasteComposerClipboard({
857 existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
858 });
859 const rejectedPasteCount = appendComposerDraftAttachments(threadKey, result.images, {
860 appendReference: true,
861 insertion,
862 });
863 if (result.text) {
864 const currentDraft = getComposerDraftSnapshot(threadKey);
865 const currentAttachments = currentDraft.attachments;
866 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
867 const advertisedMax =
868 capabilities?.attachmentUploads === true
869 ? capabilities.fileAttachments?.maxUploadBytes
870 : undefined;
871 const maxBytes =
872 advertisedMax === undefined ? null : clampFileAttachmentUploadBytes(advertisedMax);
873 const wouldExceedInputLimit =
874 currentDraft.text.length -
875 (currentDraft.text === insertion.text
876 ? Math.max(0, insertion.end - insertion.start)
877 : 0) +
878 result.text.length >
879 PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
880 const shouldFold =
881 pastedTextDisposition({
882 text: result.text,
883 wouldExceedInputLimit,
884 canAttach: true,
885 }) === "attachment";
886 const canAttach =
887 maxBytes !== null &&
888 countComposerDraftAttachmentsAfterSelection(threadKey, insertion) <
889 PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
890 new TextEncoder().encode(result.text).byteLength <= maxBytes;
891 if (shouldFold && canAttach && maxBytes !== null) {
892 try {
893 const attachment = await createPastedTextComposerAttachment({
894 text: result.text,
895 name: reservePastedTextFileName(
896 threadKey,
897 currentAttachments.map((item) => item.name),
898 ),
899 maxBytes,
900 });
901 // Same reference the pasted images above get: a folded paste is only visible
902 // as its chip until the message is sent.
903 if (
904 appendComposerDraftAttachments(threadKey, [attachment], {
905 appendReference: true,
906 insertion,
907 }) > 0
908 ) {
909 await removePersistedComposerAttachmentFile(attachment.fileUri);
910 setPendingConnectionError(
911 `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
912 );
913 }
914 } catch (error) {
915 setPendingConnectionError(
916 error instanceof Error ? error.message : "Could not attach pasted text.",
917 );
918 }
919 } else if (shouldFold && !wouldExceedInputLimit) {
920 insertComposerDraftText(threadKey, result.text, insertion);
921 } else if (shouldFold) {
922 setPendingConnectionError(
923 wouldExceedInputLimit
924 ? "Pasted text is too large for this message. Remove some text or an attachment, then paste again."
925 : "Could not attach pasted text. Remove an attachment or use a smaller paste, then try again.",
926 );
927 } else {
928 insertComposerDraftText(threadKey, result.text, insertion);
929 }
930 }
931 if (result.error) {
932 setPendingConnectionError(result.error);
933 } else if (rejectedPasteCount > 0) {
934 setPendingConnectionError(
935 `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
936 );
937 }
938 }, [
939 composerDrafts,
940 reservePastedTextFileName,
941 selectedEnvironmentRuntime?.serverConfig,
942 selectedThreadShell,
943 ]);
944
945 const onNativePasteImages = useCallback(
946 async (uris: ReadonlyArray<string>) => {
947 if (!selectedThreadShell || uris.length === 0) {
948 return;
949 }
950
951 const threadKey = activeComposerDraftKey(selectedThreadShell);
952 const insertion = captureComposerDraftInsertion(threadKey);
953 try {
954 const images = await convertPastedImagesToAttachments({
955 uris,
956 existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
957 });
958 if (images.length > 0) {
959 appendComposerDraftAttachments(threadKey, images, { appendReference: true, insertion });
960 }
961 } catch (error) {
962 console.error("[native paste] error converting images", {
963 environmentId: selectedThreadShell.environmentId,
964 threadId: selectedThreadShell.id,
965 uriCount: uris.length,
966 ...safeErrorLogAttributes(error),
967 });
968 }
969 },
970 [composerDrafts, selectedThreadShell],
971 );
972
973 const onNativePasteText = useCallback(
974 async (paste: ComposerTextPaste) => {
975 if (!selectedThreadShell) return;
976 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
977 const advertisedMax =
978 capabilities?.attachmentUploads === true
979 ? capabilities.fileAttachments?.maxUploadBytes
980 : undefined;
981 if (advertisedMax === undefined) return;
982
983 const threadKey = activeComposerDraftKey(selectedThreadShell);
984 const insertion = { text: paste.value, ...paste.selection };
985 const currentAttachments = getComposerDraftSnapshot(threadKey).attachments;
986 try {
987 const attachment = await createPastedTextComposerAttachment({
988 text: paste.text,
989 name: reservePastedTextFileName(
990 threadKey,
991 currentAttachments.map((item) => item.name),
992 ),
993 maxBytes: clampFileAttachmentUploadBytes(advertisedMax),
994 });
995 // The chip is how a folded paste stays visible: without it the attachment is in the
996 // draft but nothing in the composer says so until the message is sent. Web folds
997 // through its ordinary attach path, which always writes a reference; match that.
998 const rejectedCount = appendComposerDraftAttachments(threadKey, [attachment], {
999 appendReference: true,
1000 insertion,
1001 });
1002 if (rejectedCount > 0) {
1003 await removePersistedComposerAttachmentFile(attachment.fileUri);
1004 setPendingConnectionError(
1005 `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
1006 );
1007 }
1008 } catch (error) {
1009 setPendingConnectionError(
1010 error instanceof Error ? error.message : "Could not attach pasted text.",
1011 );
1012 }
1013 },
1014 [
1015 composerDrafts,
1016 reservePastedTextFileName,
1017 selectedEnvironmentRuntime?.serverConfig,
1018 selectedThreadShell,
1019 ],
1020 );
1021
1022 const onRemoveDraftImage = useCallback(
1023 (imageId: string) => {
1024 if (!selectedThreadShell) {
1025 return;
1026 }
1027
1028 const threadKey = activeComposerDraftKey(selectedThreadShell);
1029 removeComposerDraftAttachment(threadKey, imageId);
1030 },
1031 [selectedThreadShell],
1032 );
1033
1034 const onUpdateModelSelection = useCallback(
1035 (value: ModelSelection) => {
1036 if (!selectedThreadKey) {
1037 return;
1038 }
1039 const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
1040 (candidate) => candidate.instanceId === value.instanceId,
1041 );
1042 updateComposerDraftSettings(selectedThreadKey, {
1043 modelSelection: value,
1044 ...(provider?.showInteractionModeToggle === false
1045 ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
1046 : {}),
1047 });
1048 },
1049 [selectedEnvironmentRuntime?.serverConfig, selectedThreadKey],
1050 );
1051
1052 const onUpdateRuntimeMode = useCallback(
1053 (value: RuntimeMode) => {
1054 if (!selectedThreadKey) {
1055 return;
1056 }
1057 updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
1058 },
1059 [selectedThreadKey],
1060 );
1061
1062 const onUpdateInteractionMode = useCallback(
1063 (value: ProviderInteractionMode) => {
1064 if (!selectedThreadKey) {
1065 return;
1066 }
1067 const modelSelection =
1068 getComposerDraftSnapshot(selectedThreadKey).modelSelection ??
1069 selectedThread?.modelSelection;
1070 const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
1071 (candidate) => candidate.instanceId === modelSelection?.instanceId,
1072 );
1073 updateComposerDraftSettings(selectedThreadKey, {
1074 interactionMode: resolveProviderInteractionMode(provider, value),
1075 });
1076 },
1077 [selectedEnvironmentRuntime?.serverConfig, selectedThread?.modelSelection, selectedThreadKey],
1078 );
1079
1080 return {
1081 feedbackSubmissions,
1082 dismissFeedback,
1083 selectedThreadFeed,
1084 selectedThreadActivityRun,
1085 selectedThreadQueueCount,
1086 selectedThreadQueuedMessages,
1087 dispatchingQueuedMessageId,
1088 activeWorkStartedAt,
1089 runlessWorkActive,
1090 providerSubagentStatus,
1091 isCompacting,
1092 draftMessage,
1093 draftAttachments,
1094 composerDraftKey,
1095 followUpBehavior,
1096 canSteerActiveTurn,
1097 queuedRunEdit,
1098 isSavingQueuedEdit,
1099 cancelQueuedRunEdit,
1100 onRemoveQueuedEditAttachment,
1101 modelSelection,
1102 pendingHandoff,
1103 canSwitchThreadProvider,
1104 runtimeMode,
1105 interactionMode,
1106 activeThreadBusy,
1107 interruptibleRunId,
1108 onChangeDraftMessage,
1109 onPickDraftMedia,
1110 onPickDraftFiles,
1111 onPasteIntoDraft,
1112 onNativePasteImages,
1113 onNativePasteText,
1114 onRemoveDraftImage,
1115 onSendMessage,
1116 onUpdateModelSelection,
1117 onUpdateRuntimeMode,
1118 onUpdateInteractionMode,
1119 };
1120}