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