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

use-thread-composer-state.ts

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