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

use-thread-composer-state.ts

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