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

use-thread-composer-state.ts

1,092 lines41.7 KB

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