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

use-thread-composer-state.ts

1,082 lines41.2 KB

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