Open History to see the last commit
1import { useComposerAttachmentActions } from "./use-composer-attachment-actions";
2import * as Dialog from "../components/ui/Dialog";
3import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
4import { readEnvironmentScope } from "./session";
5import { useAtomValue } from "@effect/atom-react";
6import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
7import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
8import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff";
9import {
10 deriveProviderSubagentStatus,
11 deriveRunlessWorkStartedAt,
12 deriveThreadActivityRun,
13 deriveThreadRuntime,
14 threadRuntimeHasInterruptibleRun,
15} from "@t3tools/client-runtime/state/thread-execution";
16import { useEffect, useRef, useState } from "react";
17
18import {
19 CommandId,
20 DEFAULT_PROVIDER_INTERACTION_MODE,
21 MessageId,
22 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
23 PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
24 type EnvironmentId,
25 type ModelSelection,
26 type ProviderInteractionMode,
27 type RuntimeMode,
28 type ThreadId,
29} from "@t3tools/contracts";
30import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
31import { nextPastedTextFileName, pastedTextDisposition } from "@t3tools/client-runtime/text-paste";
32import {
33 parseCodexFeedbackCommand,
34 submitCodexFeedback,
35 type CodexFeedbackSubmission,
36} from "@t3tools/client-runtime/state/threads";
37import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
38import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLegacy";
39import { composerContextSendBlockReason, reidentifyComposerContext } from "../lib/composerContext";
40import { uuidv4 } from "../lib/uuid";
41
42import { makeQueuedMessageMetadata } from "../lib/commandMetadata";
43import {
44 describeUnavailableModelSelection,
45 isModelSelectionUnavailable,
46} from "../lib/modelOptions";
47import { resolveProviderInteractionMode } from "./legacy-plan-mode";
48import {
49 createPastedTextComposerAttachment,
50 pasteComposerClipboard,
51 removePersistedComposerAttachmentFile,
52} from "../lib/composerImages";
53import type { DraftComposerImageAttachment } from "../lib/composerImages";
54import { scopedThreadKey } from "../lib/scopedEntities";
55import { buildThreadFeed, createThreadFeedCache } from "../lib/threadActivity";
56import { acknowledgedThreadMessagesAtom } from "./acknowledged-thread-messages";
57import { appendPendingThreadMessages } from "../features/threads/pending-thread-feed";
58import { threadAllowsProviderSwitch } from "./thread-provider-switching";
59import { appAtomRegistry } from "../state/atom-registry";
60import { pendingThreadCreationMessage } from "./pending-thread-creation";
61import {
62 composerAttachmentUploadBlockReason,
63 composerAttachmentUploadsAtom,
64} from "../state/composer-attachment-uploads";
65import {
66 appendComposerDraftAttachments,
67 captureComposerDraftInsertion,
68 countComposerDraftAttachmentsAfterSelection,
69 insertComposerDraftText,
70 insertComposerDraftContext,
71 clearComposerDraftContent,
72 composerContextImportsAtom,
73 ensureComposerDraftsLoaded,
74 getComposerDraftSnapshot,
75 mergeComposerDraftContent,
76 removeComposerDraftAttachment,
77 scheduleUnusedComposerAttachmentCleanup,
78 setComposerDraftText,
79 updateComposerDraftSettings,
80 useComposerDraft,
81 useComposerDraftSettings,
82} from "./use-composer-drafts";
83import {
84 resolveComposerDispatchMode,
85 type ActiveTurnComposerAction,
86} from "@t3tools/client-runtime/state/composer-dispatch";
87import { Atom } from "effect/reactivity";
88import { AsyncResult } from "effect/reactivity";
89import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
90import { prepareTurnAttachments } from "../lib/attachmentUpload";
91import { DEFAULT_FOLLOW_UP_BEHAVIOR } from "../lib/followUpBehavior";
92import { mobilePreferencesAtom } from "./preferences";
93import { environmentThreadDetails } from "./threads";
94import {
95 endQueuedRunEdit,
96 getQueuedRunEdit,
97 queuedEditDraftKey,
98 removeQueuedRunEditAttachment,
99 resolveQueuedEditPayload,
100 useQueuedRunEdit,
101} from "./queued-run-edit";
102import { setPendingConnectionError } from "../state/use-remote-environment-registry";
103import { clearThreadComposerError, setThreadComposerError } from "./thread-composer-error";
104import {
105 useSelectedThreadProjection,
106 useSelectedThreadVisibleTurnItems,
107} from "../state/use-thread-detail";
108import { useThreadSelection } from "../state/use-thread-selection";
109import { enqueueThreadOutboxMessage } from "./thread-outbox";
110import { dispatchingQueuedMessageIdAtom, useThreadOutboxMessages } from "./use-thread-outbox";
111import { threadEnvironment } from "./threads";
112import { useAtomCommand } from "./use-atom-command";
113
114const EMPTY_QUEUE_WORKFLOW_ATOM = Atom.make<null>(null).pipe(
115 Atom.withLabel("mobile-thread-queue-workflow:empty"),
116);
117const EMPTY_CHECKPOINT_SUMMARIES_ATOM = Atom.make<ReadonlyArray<ThreadCheckpointSummary>>([]);
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 Dialog.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 const rejectedCount = appendComposerDraftAttachments(threadKey, input.attachments, {
138 appendReference: true,
139 });
140 if (rejectedCount > 0) {
141 setPendingConnectionError(
142 `${rejectedCount} comment attachment${rejectedCount === 1 ? " was" : "s were"} not added. Messages can contain at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments.`,
143 );
144 }
145 }
146}
147
148/**
149 * Resolved per call rather than captured, so a callback created before the
150 * edit began still writes to the right place.
151 */
152function activeComposerDraftKey(thread: {
153 readonly environmentId: EnvironmentId;
154 readonly id: ThreadId;
155}): string {
156 const threadKey = scopedThreadKey(thread.environmentId, thread.id);
157 const edit = getQueuedRunEdit(threadKey);
158 return edit === null ? threadKey : queuedEditDraftKey(threadKey, edit.runId);
159}
160
161export function useThreadDraftForThread(input: {
162 readonly environmentId?: EnvironmentId;
163 readonly threadId?: ThreadId;
164}) {
165 const threadKey =
166 input.environmentId && input.threadId
167 ? scopedThreadKey(input.environmentId, input.threadId)
168 : null;
169 const draft = useComposerDraft(threadKey);
170
171 return {
172 draftMessage: draft.text,
173 draftAttachments: draft.attachments,
174 };
175}
176
177export function useThreadComposerState() {
178 const {
179 selectedThread: selectedThreadShell,
180 selectedThreadCreation,
181 selectedThreadDetailRef,
182 selectedEnvironmentRuntime,
183 } = useThreadSelection();
184 const selectedThreadProjection = useSelectedThreadProjection();
185 const selectedThreadVisibleTurnItems = useSelectedThreadVisibleTurnItems();
186 const acknowledgedMessages = useAtomValue(acknowledgedThreadMessagesAtom);
187 const queuedMessagesByThreadKey = useThreadOutboxMessages();
188 const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
189 const [feedbackSubmissionsByThreadKey, setFeedbackSubmissionsByThreadKey] = useState<
190 Record<string, ReadonlyArray<CodexFeedbackSubmission>>
191 >({});
192 const uploadThreadFeedback = useAtomCommand(threadEnvironment.uploadFeedback, {
193 reportFailure: false,
194 });
195 const editQueuedRun = useAtomCommand(threadEnvironment.editQueuedRun, {
196 label: "edit queued message",
197 reportFailure: false,
198 });
199 const [isSavingQueuedEdit, setIsSavingQueuedEdit] = useState(false);
200 const savingQueuedEditRef = useRef(false);
201 const pastedTextFileNamesRef = useRef<{ threadKey: string | null; names: Set<string> }>({
202 threadKey: null,
203 names: new Set(),
204 });
205 const reservePastedTextFileName = (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 useEffect(() => {
217 ensureComposerDraftsLoaded();
218 }, []);
219
220 const selectedThreadKey = selectedThreadShell
221 ? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id)
222 : null;
223 const selectedThreadQueuedMessages = selectedThreadKey
224 ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []).filter(
225 (message) => message.creation === undefined,
226 )
227 : [];
228 const feedbackSubmissions = selectedThreadKey
229 ? (feedbackSubmissionsByThreadKey[selectedThreadKey] ?? [])
230 : [];
231 const dismissFeedback = (id: MessageId) => {
232 if (!selectedThreadKey) return;
233 setFeedbackSubmissionsByThreadKey((current) => ({
234 ...current,
235 [selectedThreadKey]: (current[selectedThreadKey] ?? []).filter((entry) => entry.id !== id),
236 }));
237 };
238 const selectedThreadMessages = selectedThreadProjection?.projection.messages;
239 const selectedThreadAttempts = selectedThreadProjection?.projection.attempts;
240 const selectedThreadNodes = selectedThreadProjection?.projection.nodes;
241 const checkpointSummaries = useAtomValue(
242 selectedThreadDetailRef === null
243 ? EMPTY_CHECKPOINT_SUMMARIES_ATOM
244 : environmentThreadDetails.checkpointSummariesAtom(selectedThreadDetailRef),
245 );
246 // A thread whose creation has not delivered its turn yet: the prompt only
247 // exists in the outbox, so it is appended to whatever the server has. The
248 // detail is usually present but empty during a worktree checkout, so this
249 // cannot be an either/or with the loaded messages.
250 const pendingCreationMessage = selectedThreadCreation?.message ?? null;
251 const [feedCache] = useState(createThreadFeedCache);
252 const selectedThreadFeed = (() => {
253 const pendingCreation =
254 pendingCreationMessage !== null &&
255 !selectedThreadMessages?.some((message) => message.id === pendingCreationMessage.messageId)
256 ? [pendingThreadCreationMessage(pendingCreationMessage)]
257 : [];
258 const feed = buildThreadFeed(selectedThreadVisibleTurnItems, {
259 anchoredMessages: pendingCreation,
260 attempts: selectedThreadAttempts,
261 nodes: selectedThreadNodes,
262 checkpointSummaries,
263 cache: feedCache,
264 });
265 const pendingAcknowledgments = acknowledgedMessages.filter(
266 (message) =>
267 scopedThreadKey(message.environmentId, message.threadId) === selectedThreadKey &&
268 !selectedThreadQueuedMessages.some((queued) => queued.messageId === message.messageId),
269 );
270 if (pendingAcknowledgments.length === 0) return feed;
271 return appendPendingThreadMessages(feed, feed, pendingAcknowledgments).map((entry) =>
272 entry.pendingMessage ? { ...entry, acknowledged: true } : entry,
273 );
274 })();
275 useEffect(() => {
276 const echoedIds = new Set(selectedThreadMessages?.map((message) => message.id));
277 if (acknowledgedMessages.some((message) => echoedIds.has(message.messageId))) {
278 appAtomRegistry.set(
279 acknowledgedThreadMessagesAtom,
280 appAtomRegistry
281 .get(acknowledgedThreadMessagesAtom)
282 .filter((message) => !echoedIds.has(message.messageId)),
283 );
284 }
285 }, [acknowledgedMessages, selectedThreadMessages]);
286
287 const preferencesResult = useAtomValue(mobilePreferencesAtom);
288 const followUpBehavior = AsyncResult.isSuccess(preferencesResult)
289 ? (preferencesResult.value.followUpBehavior ?? DEFAULT_FOLLOW_UP_BEHAVIOR)
290 : DEFAULT_FOLLOW_UP_BEHAVIOR;
291 const queueWorkflow = useAtomValue(
292 selectedThreadDetailRef === null
293 ? EMPTY_QUEUE_WORKFLOW_ATOM
294 : environmentThreadDetails.queueWorkflowAtom(selectedThreadDetailRef),
295 );
296 const queuedRunEdit = useQueuedRunEdit(selectedThreadKey);
297 const composerDraftKey =
298 selectedThreadKey === null
299 ? null
300 : queuedRunEdit === null
301 ? selectedThreadKey
302 : queuedEditDraftKey(selectedThreadKey, queuedRunEdit.runId);
303 const selectedDraft = useComposerDraftSettings(selectedThreadKey);
304 const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
305 const selectedThread = selectedThreadShell;
306 const modelSelection = selectedDraft.modelSelection ?? selectedThread?.modelSelection ?? null;
307 const serverConfig = selectedEnvironmentRuntime?.serverConfig;
308 const pendingHandoff = resolvePendingHandoff(
309 selectedThreadProjection?.projection,
310 isModelSelectionUnavailable(serverConfig, modelSelection, selectedThread?.projectId ?? null)
311 ? null
312 : modelSelection,
313 serverConfig?.providers ?? [],
314 );
315 const runtimeMode = selectedDraft.runtimeMode ?? selectedThread?.runtimeMode ?? null;
316 const selectedProvider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
317 (provider) => provider.instanceId === modelSelection?.instanceId,
318 );
319 const interactionMode = selectedThread
320 ? resolveProviderInteractionMode(
321 selectedProvider,
322 selectedDraft.interactionMode ?? selectedThread.interactionMode,
323 )
324 : null;
325 const canSwitchThreadProvider = threadAllowsProviderSwitch({
326 thread: selectedThreadShell,
327 projection: selectedThreadProjection?.projection,
328 });
329 const selectedThreadRuntime = selectedThreadProjection
330 ? deriveThreadRuntime(selectedThreadProjection.projection)
331 : (selectedThreadShell?.runtime ?? null);
332 const selectedThreadActivityRun = selectedThreadProjection
333 ? deriveThreadActivityRun(selectedThreadProjection.projection)
334 : (selectedThreadShell?.latestRun ?? null);
335
336 const isCompacting = (() => {
337 const queuedCompact = selectedThreadQueuedMessages.some(
338 (message) =>
339 message.messageId === dispatchingQueuedMessageId &&
340 message.text.trim().toLowerCase() === "/compact" &&
341 message.attachments.length === 0,
342 );
343 if (queuedCompact) return true;
344 const activeRunId = selectedThreadRuntime?.activeRunId;
345 if (!activeRunId || !threadRuntimeIsActive(selectedThreadRuntime)) return false;
346 if (
347 selectedThreadVisibleTurnItems.some(
348 ({ item }) =>
349 item.runId === activeRunId && item.type === "compaction" && item.status === "running",
350 )
351 ) {
352 return true;
353 }
354 const compactMessage = selectedThreadVisibleTurnItems.findLast(
355 ({ item }) =>
356 item.runId === activeRunId &&
357 item.type === "user_message" &&
358 item.text.trim().toLowerCase() === "/compact" &&
359 item.attachments.length === 0,
360 );
361 if (!compactMessage) return false;
362 return !selectedThreadVisibleTurnItems.some(
363 ({ item }) =>
364 item.runId === activeRunId &&
365 item.type === "compaction" &&
366 (item.status === "completed" ||
367 item.status === "failed" ||
368 item.status === "interrupted" ||
369 item.status === "cancelled"),
370 );
371 })();
372 // A compacting turn cannot take steering input, so follow-ups queue meanwhile.
373 const canSteerActiveTurn = queueWorkflow?.canPromoteToSteer === true && !isCompacting;
374 // A stop or a restart holds the queue, completion wakes included, until it
375 // is resumed; the queue sheet lists only the user's own messages.
376 const queueHeld = queueWorkflow?.isHeld === true;
377
378 const runlessWorkStartedAt = selectedThreadProjection
379 ? deriveRunlessWorkStartedAt(selectedThreadProjection.projection)
380 : null;
381 const activeWorkStartedAt = (() => {
382 if (!selectedThreadShell) {
383 return null;
384 }
385 return (
386 resolveThreadWorkingStartedAt({
387 latestRun: selectedThreadActivityRun,
388 runtime: selectedThreadRuntime,
389 }) ?? runlessWorkStartedAt
390 );
391 })();
392 const runlessWorkActive = runlessWorkStartedAt !== null;
393
394 const providerSubagentStatus = selectedThreadProjection
395 ? deriveProviderSubagentStatus(selectedThreadProjection.projection)
396 : null;
397
398 const selectedThreadRuns = selectedThreadProjection?.projection.runs;
399 const editedRunId = queuedRunEdit?.runId ?? null;
400 useEffect(() => {
401 if (selectedThreadKey === null || editedRunId === null || selectedThreadRuns === undefined) {
402 return;
403 }
404 if (savingQueuedEditRef.current) return;
405 const stillQueued = selectedThreadRuns.some(
406 (run) => run.id === editedRunId && run.status === "queued",
407 );
408 if (stillQueued) return;
409 const editDraftKey = queuedEditDraftKey(selectedThreadKey, editedRunId);
410 const editDraft = getComposerDraftSnapshot(editDraftKey);
411 const threadDraft = getComposerDraftSnapshot(selectedThreadKey);
412 const keepable =
413 editDraft.text.trim().length > 0 &&
414 threadDraft.text.trim().length === 0 &&
415 threadDraft.attachments.length === 0;
416 if (keepable) {
417 void mergeComposerDraftContent(selectedThreadKey, {
418 text: editDraft.text,
419 attachments: editDraft.attachments,
420 ...(editDraft.context ? { context: editDraft.context } : {}),
421 });
422 }
423 endQueuedRunEdit(selectedThreadKey, { deferAttachmentCleanup: keepable });
424 setThreadComposerError(
425 selectedThreadKey,
426 keepable
427 ? "That message already started. Your edit is back in the composer."
428 : "That message already started, so the edit was discarded.",
429 );
430 }, [editedRunId, selectedThreadKey, selectedThreadRuns]);
431
432 const activeThreadBusy = threadRuntimeIsActive(selectedThreadRuntime);
433 const interruptibleRunId = threadRuntimeHasInterruptibleRun(selectedThreadRuntime)
434 ? (selectedThreadRuntime?.activeRunId ?? null)
435 : null;
436
437 const cancelQueuedRunEdit = () => {
438 if (selectedThreadKey === null || savingQueuedEditRef.current) return;
439 endQueuedRunEdit(selectedThreadKey);
440 };
441
442 const onRemoveQueuedEditAttachment = (attachmentId: string) => {
443 if (selectedThreadKey === null) return;
444 removeQueuedRunEditAttachment(selectedThreadKey, attachmentId);
445 };
446
447 const saveQueuedRunEdit = async () => {
448 const thread = selectedThreadShell;
449 if (!thread || savingQueuedEditRef.current) return;
450 const threadKey = scopedThreadKey(thread.environmentId, thread.id);
451 const edit = getQueuedRunEdit(threadKey);
452 if (edit === null) return;
453 const draft = getComposerDraftSnapshot(queuedEditDraftKey(threadKey, edit.runId));
454 const text = draft.text.trim();
455 if (text.length === 0) {
456 // The server rejects an empty queued message, attachments or not.
457 Dialog.alert("Add a message", "A queued message cannot be left empty.");
458 return;
459 }
460 if (
461 edit.existingAttachments.length + draft.attachments.length >
462 PROVIDER_SEND_TURN_MAX_ATTACHMENTS
463 ) {
464 Dialog.alert(
465 "Too many attachments",
466 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
467 );
468 return;
469 }
470 savingQueuedEditRef.current = true;
471 setIsSavingQueuedEdit(true);
472 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
473 const prepared = await settlePromise(() =>
474 prepareTurnAttachments({
475 environmentId: thread.environmentId,
476 attachments: draft.attachments,
477 supportsImageUploads: capabilities?.attachmentUploads === true,
478 }),
479 );
480 if (AsyncResult.isFailure(prepared)) {
481 savingQueuedEditRef.current = false;
482 setIsSavingQueuedEdit(false);
483 const error = squashAtomCommandFailure(prepared);
484 Dialog.alert(
485 "Could not save the queued message",
486 error instanceof Error ? error.message : "Your edit is still in the composer.",
487 );
488 return;
489 }
490 if (prepared.value.status !== "ready") {
491 savingQueuedEditRef.current = false;
492 setIsSavingQueuedEdit(false);
493 return;
494 }
495 const payload = resolveQueuedEditPayload({
496 edit,
497 draftContext: draft.context,
498 draftAttachments: draft.attachments,
499 uploaded: prepared.value.attachments,
500 });
501 const result = await editQueuedRun({
502 environmentId: thread.environmentId,
503 input: {
504 threadId: thread.id,
505 runId: edit.runId,
506 text,
507 edit: {
508 messageId: edit.messageId,
509 attachments: payload.attachments,
510 ...(payload.context ? { context: payload.context } : {}),
511 },
512 },
513 });
514 savingQueuedEditRef.current = false;
515 setIsSavingQueuedEdit(false);
516 if (result._tag !== "Success") {
517 Dialog.alert(
518 "Could not save the queued message",
519 "It may have already started. Your edit is still in the composer.",
520 );
521 return;
522 }
523 endQueuedRunEdit(threadKey, { deferAttachmentCleanup: true });
524 scheduleUnusedComposerAttachmentCleanup(draft.attachments);
525 };
526
527 const onSendMessage = async (
528 followUpOverride?: ActiveTurnComposerAction,
529 beforeDispatch?: (
530 text: string,
531 hasAttachmentsOrContext: boolean,
532 ) => Promise<boolean | "responded">,
533 ) => {
534 if (
535 selectedThreadShell &&
536 selectedEnvironmentRuntime?.connectionState === "connected" &&
537 !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
538 )
539 return null;
540 if (!selectedThreadShell) {
541 return null;
542 }
543 // The server has not created this thread yet. Queuing a follow-up against
544 // its id would strand the message: if the creation is rejected the thread
545 // never appears and the drain drops the orphan. The composer disables its
546 if (selectedThreadCreation !== null) {
547 return null;
548 }
549
550 const editKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
551 if (getQueuedRunEdit(editKey) !== null) {
552 await saveQueuedRunEdit();
553 return null;
554 }
555
556 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
557 const draft = getComposerDraftSnapshot(threadKey);
558 if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
559 const thread = selectedThreadShell;
560 const text = draft.text.trim();
561 const attachments = draft.attachments;
562 if (
563 composerAttachmentUploadBlockReason({
564 environmentId: selectedThreadShell.environmentId,
565 attachments,
566 connected: selectedEnvironmentRuntime?.connectionState === "connected",
567 serverConfig: selectedEnvironmentRuntime?.serverConfig ?? null,
568 states: appAtomRegistry.get(composerAttachmentUploadsAtom),
569 }) !== null
570 )
571 return null;
572 if (text.length === 0 && attachments.length === 0) {
573 return null;
574 }
575 // A send-failure restore appends with allowOverflow so it never drops the
576 // user's files, which can leave the draft over the cap. Sending it anyway
577 // would enqueue a message that outbox recovery rejects forever, so block
578 // here until the user removes attachments.
579 if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
580 Dialog.alert(
581 "Too many attachments",
582 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
583 );
584 return null;
585 }
586
587 const contextBlockReason = composerContextSendBlockReason(draft.context);
588 if (contextBlockReason) {
589 Dialog.alert("Too much context", contextBlockReason);
590 return null;
591 }
592
593 const modelSelection = draft.modelSelection ?? thread.modelSelection;
594 const serverConfig = selectedEnvironmentRuntime?.serverConfig;
595 if (
596 selectedEnvironmentRuntime?.connectionState === "connected" &&
597 isModelSelectionUnavailable(serverConfig, modelSelection, thread.projectId)
598 ) {
599 const { title, detail } = describeUnavailableModelSelection(
600 serverConfig,
601 modelSelection,
602 thread.projectId,
603 );
604 Dialog.alert(title, detail);
605 return null;
606 }
607 const provider = serverConfig?.providers.find(
608 (entry) => entry.instanceId === modelSelection.instanceId,
609 );
610 const feedbackCommand =
611 attachments.length === 0 && provider?.driver === "codex"
612 ? parseCodexFeedbackCommand(text)
613 : null;
614 if (feedbackCommand) {
615 if (!readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope))
616 return null;
617 if (thread.activeProviderThreadId === null) {
618 Dialog.alert("Start a Codex thread first", "Send a message before you submit feedback.");
619 return null;
620 }
621 const metadata = makeQueuedMessageMetadata();
622 await submitCodexFeedback({
623 submission: {
624 id: MessageId.make(metadata.messageId),
625 command: text,
626 createdAt: metadata.createdAt,
627 },
628 clearDraft: () => clearComposerDraftContent(threadKey),
629 onUpdate: (submission) => {
630 setFeedbackSubmissionsByThreadKey((current) => {
631 const existing = current[threadKey] ?? [];
632 const found = existing.some((entry) => entry.id === submission.id);
633 return {
634 ...current,
635 [threadKey]: found
636 ? existing.map((entry) => (entry.id === submission.id ? submission : entry))
637 : [...existing, submission],
638 };
639 });
640 },
641 upload: () =>
642 uploadThreadFeedback({
643 environmentId: thread.environmentId,
644 input: { threadId: thread.id, ...feedbackCommand },
645 }),
646 });
647 return null;
648 }
649
650 if (beforeDispatch !== undefined) {
651 const response = await beforeDispatch(
652 text,
653 attachments.length > 0 || draft.context !== undefined,
654 );
655 if (!response) return null;
656 // A context paste still landing, or any draft or settings change while approvals were
657 // declined, means this snapshot is no longer what the user sent.
658 if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
659 const current = getComposerDraftSnapshot(threadKey);
660 if (
661 current.text !== draft.text ||
662 JSON.stringify(current.context) !== JSON.stringify(draft.context) ||
663 JSON.stringify(current.modelSelection) !== JSON.stringify(draft.modelSelection) ||
664 current.runtimeMode !== draft.runtimeMode ||
665 current.interactionMode !== draft.interactionMode ||
666 current.attachments.length !== attachments.length ||
667 current.attachments.some((attachment, index) => attachment.id !== attachments[index]?.id)
668 )
669 return null;
670 if (response === "responded") {
671 clearComposerDraftContent(threadKey);
672 return null;
673 }
674 }
675
676 // Resolved here rather than at drain time: the outbox can deliver minutes
677 // later, and the choice belongs to the moment the user pressed send.
678 // Steering travels as "auto" so a turn that ends in the meantime degrades
679 // to a queued run on the server instead of failing the delivery and
680 // bouncing the message back into the draft.
681 // A redirect declined approvals to steer the waiting turn, not to queue behind it.
682 const activeTurnDefault = beforeDispatch !== undefined ? "steer" : followUpBehavior;
683 const followUpAction = resolveComposerDispatchMode({
684 running: activeThreadBusy && canSteerActiveTurn,
685 alternateModifier: followUpOverride !== undefined && followUpOverride !== activeTurnDefault,
686 activeTurnDefault,
687 });
688 const setupRunning = [selectedThreadActivityRun?.status, selectedThreadRuntime?.status].some(
689 (status) => status === "preparing" || status === "starting",
690 );
691 const followUpDispatchMode = setupRunning
692 ? "queue"
693 : followUpAction === "auto"
694 ? null
695 : followUpAction === "queue"
696 ? "queue"
697 : "auto";
698
699 const metadata = makeQueuedMessageMetadata();
700 const messageId = MessageId.make(metadata.messageId);
701 clearThreadComposerError(threadKey);
702 const enqueuePromise = enqueueThreadOutboxMessage({
703 environmentId: selectedThreadShell.environmentId,
704 threadId: selectedThreadShell.id,
705 messageId,
706 commandId: CommandId.make(metadata.commandId),
707 text,
708 attachments,
709 context: draft.context,
710 modelSelection,
711 runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
712 interactionMode: resolveProviderInteractionMode(
713 provider,
714 draft.interactionMode ?? thread.interactionMode,
715 ),
716 ...(followUpDispatchMode === null ? {} : { dispatchMode: followUpDispatchMode }),
717 createdAt: metadata.createdAt,
718 });
719 clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
720 enqueuePromise.then(
721 () => scheduleUnusedComposerAttachmentCleanup(attachments),
722 (error: unknown) => {
723 // Restore text via merge (idempotent) but attachments via the uncapped
724 // append: the merge path slots existing attachments first and truncates
725 // at the send limit, which would silently drop this message's images if
726 // the user attached new ones while the write was in flight.
727 void mergeComposerDraftContent(threadKey, {
728 text,
729 context: draft.context,
730 attachments: [],
731 });
732 appendComposerDraftAttachments(threadKey, attachments, { allowOverflow: true });
733 setThreadComposerError(
734 threadKey,
735 error instanceof Error ? error.message : "Failed to save the queued message.",
736 );
737 },
738 );
739 return messageId;
740 };
741
742 const onChangeDraftMessage = (value: string) => {
743 if (!selectedThreadShell) {
744 return;
745 }
746
747 const threadKey = activeComposerDraftKey(selectedThreadShell);
748 setComposerDraftText(threadKey, value);
749 };
750
751 const { onPickDraftMedia, onPickDraftFiles, onNativePasteImages, onNativePasteText } =
752 useComposerAttachmentActions({
753 draftKey: selectedThreadShell ? activeComposerDraftKey(selectedThreadShell) : null,
754 serverConfig: selectedEnvironmentRuntime?.serverConfig,
755 });
756
757 const onPasteIntoDraft = async () => {
758 if (!selectedThreadShell) {
759 return;
760 }
761
762 const threadKey = activeComposerDraftKey(selectedThreadShell);
763 const insertion = captureComposerDraftInsertion(threadKey);
764 const result = await pasteComposerClipboard({
765 existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
766 });
767 const rejectedPasteCount = appendComposerDraftAttachments(threadKey, result.images, {
768 appendReference: true,
769 insertion,
770 });
771 if (result.text) {
772 const currentDraft = getComposerDraftSnapshot(threadKey);
773 const currentAttachments = currentDraft.attachments;
774 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
775 const advertisedMax =
776 capabilities?.attachmentUploads === true
777 ? capabilities.fileAttachments?.maxUploadBytes
778 : undefined;
779 const maxBytes =
780 advertisedMax === undefined ? null : clampFileAttachmentUploadBytes(advertisedMax);
781 const wouldExceedInputLimit =
782 currentDraft.text.length -
783 (currentDraft.text === insertion.text
784 ? Math.max(0, insertion.end - insertion.start)
785 : 0) +
786 result.text.length >
787 PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
788 const shouldFold =
789 pastedTextDisposition({
790 text: result.text,
791 wouldExceedInputLimit,
792 canAttach: true,
793 }) === "attachment";
794 const canAttach =
795 maxBytes !== null &&
796 countComposerDraftAttachmentsAfterSelection(threadKey, insertion) <
797 PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
798 new TextEncoder().encode(result.text).byteLength <= maxBytes;
799 if (shouldFold && canAttach && maxBytes !== null) {
800 try {
801 const attachment = await createPastedTextComposerAttachment({
802 text: result.text,
803 name: reservePastedTextFileName(
804 threadKey,
805 currentAttachments.map((item) => item.name),
806 ),
807 maxBytes,
808 });
809 if (
810 appendComposerDraftAttachments(threadKey, [attachment], {
811 appendReference: true,
812 insertion,
813 }) > 0
814 ) {
815 await removePersistedComposerAttachmentFile(attachment.fileUri);
816 setPendingConnectionError(
817 `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
818 );
819 }
820 } catch (error) {
821 setPendingConnectionError(
822 error instanceof Error ? error.message : "Could not attach pasted text.",
823 );
824 }
825 } else if (shouldFold && !wouldExceedInputLimit) {
826 insertComposerDraftText(threadKey, result.text, insertion);
827 } else if (shouldFold) {
828 setPendingConnectionError(
829 wouldExceedInputLimit
830 ? "Pasted text is too large for this message. Remove some text or an attachment, then paste again."
831 : "Could not attach pasted text. Remove an attachment or use a smaller paste, then try again.",
832 );
833 } else {
834 insertComposerDraftText(threadKey, result.text, insertion);
835 }
836 }
837 if (result.error) {
838 setPendingConnectionError(result.error);
839 } else if (rejectedPasteCount > 0) {
840 setPendingConnectionError(
841 `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
842 );
843 }
844 };
845
846 const onRemoveDraftImage = (imageId: string) => {
847 if (!selectedThreadShell) {
848 return;
849 }
850
851 const threadKey = activeComposerDraftKey(selectedThreadShell);
852 removeComposerDraftAttachment(threadKey, imageId);
853 };
854
855 const onUpdateModelSelection = (value: ModelSelection) => {
856 if (!selectedThreadKey) {
857 return;
858 }
859 const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
860 (candidate) => candidate.instanceId === value.instanceId,
861 );
862 updateComposerDraftSettings(selectedThreadKey, {
863 modelSelection: value,
864 ...(provider?.showInteractionModeToggle === false
865 ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
866 : {}),
867 });
868 };
869
870 const onUpdateRuntimeMode = (value: RuntimeMode) => {
871 if (!selectedThreadKey) {
872 return;
873 }
874 updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
875 };
876
877 const onUpdateInteractionMode = (value: ProviderInteractionMode) => {
878 if (!selectedThreadKey) {
879 return;
880 }
881 const modelSelection =
882 getComposerDraftSnapshot(selectedThreadKey).modelSelection ?? selectedThread?.modelSelection;
883 const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
884 (candidate) => candidate.instanceId === modelSelection?.instanceId,
885 );
886 updateComposerDraftSettings(selectedThreadKey, {
887 interactionMode: resolveProviderInteractionMode(provider, value),
888 });
889 };
890
891 return {
892 feedbackSubmissions,
893 dismissFeedback,
894 selectedThreadFeed,
895 selectedThreadActivityRun,
896 selectedThreadQueueCount,
897 selectedThreadQueuedMessages,
898 dispatchingQueuedMessageId,
899 activeWorkStartedAt,
900 runlessWorkActive,
901 providerSubagentStatus,
902 isCompacting,
903 composerDraftKey,
904 followUpBehavior,
905 canSteerActiveTurn,
906 queueHeld,
907 queuedRunEdit,
908 isSavingQueuedEdit,
909 cancelQueuedRunEdit,
910 onRemoveQueuedEditAttachment,
911 modelSelection,
912 pendingHandoff,
913 canSwitchThreadProvider,
914 runtimeMode,
915 interactionMode,
916 activeThreadBusy,
917 interruptibleRunId,
918 onChangeDraftMessage,
919 onPickDraftMedia,
920 onPickDraftFiles,
921 onPasteIntoDraft,
922 onNativePasteImages,
923 onNativePasteText,
924 onRemoveDraftImage,
925 onSendMessage,
926 onUpdateModelSelection,
927 onUpdateRuntimeMode,
928 onUpdateInteractionMode,
929 };
930}