Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

use-thread-composer-state.ts

1,106 lines42.3 KB

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