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 { useRef, useState } from "react";
17
18import {
19 CommandId,
20 DEFAULT_PROVIDER_INTERACTION_MODE,
21 MessageId,
22 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
23 type EnvironmentId,
24 type ModelSelection,
25 type ProviderInteractionMode,
26 type ServerProvider,
27 type ThreadId,
28} from "@t3tools/contracts";
29
30import {
31 parseCodexFeedbackCommand,
32 submitCodexFeedback,
33 type CodexFeedbackSubmission,
34} from "@t3tools/client-runtime/state/threads";
35import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
36import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLegacy";
37import { composerContextSendBlockReason, reidentifyComposerContext } from "../lib/composerContext";
38import { uuidv4 } from "../lib/uuid";
39
40import { makeQueuedMessageMetadata } from "../lib/commandMetadata";
41import {
42 describeUnavailableModelSelection,
43 isModelSelectionUnavailable,
44} from "../lib/modelOptions";
45import { resolveProviderInteractionMode } from "./legacy-plan-mode";
46
47import type { DraftComposerImageAttachment } from "../lib/composerImages";
48import { scopedThreadKey } from "../lib/scopedEntities";
49import { buildThreadFeed, createThreadFeedCache } from "../lib/threadActivity";
50import { acknowledgedThreadMessagesAtom } from "./acknowledged-thread-messages";
51import {
52 appendPendingThreadMessages,
53 selectPendingAcknowledgedMessages,
54} from "../features/threads/pending-thread-feed";
55import { threadAllowsProviderSwitch } from "./thread-provider-switching";
56import { appAtomRegistry } from "../state/atom-registry";
57import { pendingThreadCreationMessage } from "./pending-thread-creation";
58import {
59 composerAttachmentUploadBlockReason,
60 composerAttachmentUploadsAtom,
61} from "../state/composer-attachment-uploads";
62import {
63 appendComposerDraftAttachments,
64 insertComposerDraftContext,
65 clearComposerDraft,
66 clearComposerDraftContent,
67 composerContextImportsAtom,
68 getComposerDraftSnapshot,
69 mergeComposerDraftContent,
70 removeComposerDraftAttachment,
71 scheduleUnusedComposerAttachmentCleanup,
72 setComposerDraftText,
73 updateComposerDraftSettings,
74 useComposerDraft,
75 useComposerDraftSettings,
76} from "./use-composer-drafts";
77import {
78 resolveComposerDispatchMode,
79 type ActiveTurnComposerAction,
80} from "@t3tools/client-runtime/state/composer-dispatch";
81import { Atom } from "effect/reactivity";
82import { AsyncResult } from "effect/reactivity";
83import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
84import { prepareTurnAttachments } from "../lib/attachmentUpload";
85import { DEFAULT_FOLLOW_UP_BEHAVIOR } from "../lib/followUpBehavior";
86import { mobilePreferencesAtom } from "./preferences";
87import { environmentThreadDetails } from "./threads";
88import {
89 endQueuedRunEdit,
90 getQueuedRunEdit,
91 queuedEditDraftKey,
92 removeQueuedRunEditAttachment,
93 resolveQueuedEditPayload,
94 startQueuedRunEditSave,
95 useQueuedRunEdit,
96} from "./queued-run-edit";
97import { setPendingConnectionError } from "../state/use-remote-environment-registry";
98import { clearThreadComposerError, setThreadComposerError } from "./thread-composer-error";
99import {
100 useSelectedThreadProjection,
101 useSelectedThreadVisibleTurnItems,
102} from "../state/use-thread-detail";
103import { useThreadSelection } from "../state/use-thread-selection";
104import { enqueueThreadOutboxMessage } from "./thread-outbox";
105import { dispatchingQueuedMessageIdAtom, useThreadOutboxMessages } from "./use-thread-outbox";
106import { threadEnvironment } from "./threads";
107import { useAtomCommand } from "./use-atom-command";
108
109const EMPTY_QUEUE_WORKFLOW_ATOM = Atom.make<null>(null).pipe(
110 Atom.withLabel("mobile-thread-queue-workflow:empty"),
111);
112const EMPTY_CHECKPOINT_SUMMARIES_ATOM = Atom.make<ReadonlyArray<ThreadCheckpointSummary>>([]);
113const EMPTY_THREAD_SEQUENCE_ATOM = Atom.make(0);
114
115export function appendReviewCommentToDraft(input: {
116 readonly environmentId: EnvironmentId;
117 readonly threadId: ThreadId;
118 readonly text: string;
119 readonly attachments?: ReadonlyArray<DraftComposerImageAttachment>;
120}): void {
121 const threadKey = scopedThreadKey(input.environmentId, input.threadId);
122 const upgraded = upgradeLegacyContextMessage(input.text);
123 if (
124 !insertComposerDraftContext(
125 threadKey,
126 reidentifyComposerContext(upgraded.text, upgraded.records, uuidv4),
127 )
128 ) {
129 Dialog.alert("Too many context items", "Remove some context from the draft and try again.");
130 return;
131 }
132 if (input.attachments && input.attachments.length > 0) {
133 const rejectedCount = appendComposerDraftAttachments(threadKey, input.attachments, {
134 appendReference: true,
135 });
136 if (rejectedCount > 0) {
137 setPendingConnectionError(
138 `${rejectedCount} comment attachment${rejectedCount === 1 ? " was" : "s were"} not added. Messages can contain at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments.`,
139 );
140 }
141 }
142}
143
144/** Resolve per call so callbacks created before editing still target the current draft. */
145function activeComposerDraftKey(thread: {
146 readonly environmentId: EnvironmentId;
147 readonly id: ThreadId;
148}): string {
149 const threadKey = scopedThreadKey(thread.environmentId, thread.id);
150 const edit = getQueuedRunEdit(threadKey);
151 return edit === null ? threadKey : queuedEditDraftKey(threadKey, edit.runId);
152}
153
154export function useThreadDraftForThread(input: {
155 readonly environmentId?: EnvironmentId;
156 readonly threadId?: ThreadId;
157}) {
158 const threadKey =
159 input.environmentId && input.threadId
160 ? scopedThreadKey(input.environmentId, input.threadId)
161 : null;
162 const draft = useComposerDraft(threadKey);
163
164 return {
165 draftMessage: draft.text,
166 draftAttachments: draft.attachments,
167 };
168}
169
170/** A provider without the interaction-mode toggle runs in the default mode. */
171export function updateThreadDraftModelSelection(
172 threadKey: string,
173 value: ModelSelection,
174 providers: ReadonlyArray<ServerProvider>,
175): void {
176 const provider = providers.find((candidate) => candidate.instanceId === value.instanceId);
177 updateComposerDraftSettings(threadKey, {
178 modelSelection: value,
179 ...(provider?.showInteractionModeToggle === false
180 ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
181 : {}),
182 });
183}
184
185export function useThreadComposerState() {
186 const {
187 selectedThread: selectedThreadShell,
188 selectedThreadCreation,
189 selectedThreadDetailRef,
190 selectedEnvironmentRuntime,
191 } = useThreadSelection();
192 const selectedThreadProjection = useSelectedThreadProjection();
193 const selectedThreadVisibleTurnItems = useSelectedThreadVisibleTurnItems();
194 const acknowledgedMessages = useAtomValue(acknowledgedThreadMessagesAtom);
195 const queuedMessagesByThreadKey = useThreadOutboxMessages();
196 const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
197 const [feedbackSubmissionsByThreadKey, setFeedbackSubmissionsByThreadKey] = useState<
198 Record<string, ReadonlyArray<CodexFeedbackSubmission>>
199 >({});
200 const uploadThreadFeedback = useAtomCommand(threadEnvironment.uploadFeedback, {
201 reportFailure: false,
202 });
203 const editQueuedRun = useAtomCommand(threadEnvironment.editQueuedRun, {
204 label: "edit queued message",
205 reportFailure: false,
206 });
207 const [isSavingQueuedEdit, setIsSavingQueuedEdit] = useState(false);
208 const savingQueuedEditRef = useRef(false);
209
210 const selectedThreadKey = selectedThreadShell
211 ? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id)
212 : null;
213 const selectedThreadQueuedMessages = selectedThreadKey
214 ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []).filter(
215 (message) => message.creation === undefined,
216 )
217 : [];
218 const feedbackSubmissions = selectedThreadKey
219 ? (feedbackSubmissionsByThreadKey[selectedThreadKey] ?? [])
220 : [];
221 const dismissFeedback = (id: MessageId) => {
222 if (!selectedThreadKey) return;
223 setFeedbackSubmissionsByThreadKey((current) => ({
224 ...current,
225 [selectedThreadKey]: (current[selectedThreadKey] ?? []).filter((entry) => entry.id !== id),
226 }));
227 };
228 const selectedThreadMessages = selectedThreadProjection?.projection.messages;
229 const selectedThreadAttempts = selectedThreadProjection?.projection.attempts;
230 const selectedThreadNodes = selectedThreadProjection?.projection.nodes;
231 const selectedThreadSequence = useAtomValue(
232 selectedThreadDetailRef === null
233 ? EMPTY_THREAD_SEQUENCE_ATOM
234 : environmentThreadDetails.sequenceAtom(selectedThreadDetailRef),
235 );
236 const checkpointSummaries = useAtomValue(
237 selectedThreadDetailRef === null
238 ? EMPTY_CHECKPOINT_SUMMARIES_ATOM
239 : environmentThreadDetails.checkpointSummariesAtom(selectedThreadDetailRef),
240 );
241 // A thread whose creation has not delivered its turn yet: the prompt only
242 // exists in the outbox, so it is appended to whatever the server has. The
243 // detail is usually present but empty during a worktree checkout, so this
244 // cannot be an either/or with the loaded messages.
245 const pendingCreationMessage = selectedThreadCreation?.message ?? null;
246 const [feedCache] = useState(createThreadFeedCache);
247 const selectedThreadFeed = (() => {
248 const pendingCreation =
249 pendingCreationMessage !== null &&
250 !selectedThreadMessages?.some((message) => message.id === pendingCreationMessage.messageId)
251 ? [pendingThreadCreationMessage(pendingCreationMessage)]
252 : [];
253 const feed = buildThreadFeed(selectedThreadVisibleTurnItems, {
254 anchoredMessages: pendingCreation,
255 attempts: selectedThreadAttempts,
256 nodes: selectedThreadNodes,
257 checkpointSummaries,
258 cache: feedCache,
259 });
260 const pendingAcknowledgments = selectPendingAcknowledgedMessages(acknowledgedMessages, {
261 threadKey: selectedThreadKey,
262 queuedMessages: selectedThreadQueuedMessages,
263 sequence: selectedThreadSequence,
264 projectedMessages: selectedThreadMessages,
265 });
266 if (pendingAcknowledgments.length === 0) return feed;
267 return appendPendingThreadMessages(feed, feed, pendingAcknowledgments).map((entry) =>
268 entry.pendingMessage ? { ...entry, acknowledged: true } : entry,
269 );
270 })();
271
272 const preferencesResult = useAtomValue(mobilePreferencesAtom);
273 const followUpBehavior = AsyncResult.isSuccess(preferencesResult)
274 ? (preferencesResult.value.followUpBehavior ?? DEFAULT_FOLLOW_UP_BEHAVIOR)
275 : DEFAULT_FOLLOW_UP_BEHAVIOR;
276 const queueWorkflow = useAtomValue(
277 selectedThreadDetailRef === null
278 ? EMPTY_QUEUE_WORKFLOW_ATOM
279 : environmentThreadDetails.queueWorkflowAtom(selectedThreadDetailRef),
280 );
281 const queuedRunEdit = useQueuedRunEdit(selectedThreadKey);
282 const composerDraftKey =
283 selectedThreadKey === null
284 ? null
285 : queuedRunEdit === null
286 ? selectedThreadKey
287 : queuedEditDraftKey(selectedThreadKey, queuedRunEdit.runId);
288 const selectedDraft = useComposerDraftSettings(selectedThreadKey);
289 const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
290 const selectedThread = selectedThreadShell;
291 const modelSelection = selectedDraft.modelSelection ?? selectedThread?.modelSelection ?? null;
292 const serverConfig = selectedEnvironmentRuntime?.serverConfig;
293 const pendingHandoff = resolvePendingHandoff(
294 selectedThreadProjection?.projection,
295 isModelSelectionUnavailable(serverConfig, modelSelection, selectedThread?.projectId ?? null)
296 ? null
297 : modelSelection,
298 serverConfig?.providers ?? [],
299 );
300 const runtimeMode = selectedDraft.runtimeMode ?? selectedThread?.runtimeMode ?? null;
301 const selectedProvider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
302 (provider) => provider.instanceId === modelSelection?.instanceId,
303 );
304 const interactionMode = selectedThread
305 ? resolveProviderInteractionMode(
306 selectedProvider,
307 selectedDraft.interactionMode ?? selectedThread.interactionMode,
308 )
309 : null;
310 const canSwitchThreadProvider = threadAllowsProviderSwitch({
311 thread: selectedThreadShell,
312 projection: selectedThreadProjection?.projection,
313 });
314 const selectedThreadRuntime = selectedThreadProjection
315 ? deriveThreadRuntime(selectedThreadProjection.projection)
316 : (selectedThreadShell?.runtime ?? null);
317 const selectedThreadActivityRun = selectedThreadProjection
318 ? deriveThreadActivityRun(selectedThreadProjection.projection)
319 : (selectedThreadShell?.latestRun ?? null);
320
321 const isCompacting = (() => {
322 const queuedCompact = selectedThreadQueuedMessages.some(
323 (message) =>
324 message.messageId === dispatchingQueuedMessageId &&
325 message.text.trim().toLowerCase() === "/compact" &&
326 message.attachments.length === 0,
327 );
328 if (queuedCompact) return true;
329 const activeRunId = selectedThreadRuntime?.activeRunId;
330 if (!activeRunId || !threadRuntimeIsActive(selectedThreadRuntime)) return false;
331 if (
332 selectedThreadVisibleTurnItems.some(
333 ({ item }) =>
334 item.runId === activeRunId && item.type === "compaction" && item.status === "running",
335 )
336 ) {
337 return true;
338 }
339 const compactMessage = selectedThreadVisibleTurnItems.findLast(
340 ({ item }) =>
341 item.runId === activeRunId &&
342 item.type === "user_message" &&
343 item.text.trim().toLowerCase() === "/compact" &&
344 item.attachments.length === 0,
345 );
346 if (!compactMessage) return false;
347 return !selectedThreadVisibleTurnItems.some(
348 ({ item }) =>
349 item.runId === activeRunId &&
350 item.type === "compaction" &&
351 (item.status === "completed" ||
352 item.status === "failed" ||
353 item.status === "interrupted" ||
354 item.status === "cancelled"),
355 );
356 })();
357 // A compacting turn cannot take steering input, so follow-ups queue meanwhile.
358 const canSteerActiveTurn = queueWorkflow?.canPromoteToSteer === true && !isCompacting;
359 // A stop or a restart holds the queue, completion wakes included, until it
360 // is resumed; the queue sheet lists only the user's own messages.
361 const queueHeld = queueWorkflow?.isHeld === true;
362
363 const runlessWorkStartedAt = selectedThreadProjection
364 ? deriveRunlessWorkStartedAt(selectedThreadProjection.projection)
365 : null;
366 const activeWorkStartedAt = (() => {
367 if (!selectedThreadShell) {
368 return null;
369 }
370 return (
371 resolveThreadWorkingStartedAt({
372 latestRun: selectedThreadActivityRun,
373 runtime: selectedThreadRuntime,
374 }) ?? runlessWorkStartedAt
375 );
376 })();
377 const runlessWorkActive = runlessWorkStartedAt !== null;
378
379 const providerSubagentStatus = selectedThreadProjection
380 ? deriveProviderSubagentStatus(selectedThreadProjection.projection)
381 : null;
382
383 const activeThreadBusy = threadRuntimeIsActive(selectedThreadRuntime);
384 const interruptibleRunId = threadRuntimeHasInterruptibleRun(selectedThreadRuntime)
385 ? (selectedThreadRuntime?.activeRunId ?? null)
386 : null;
387
388 const cancelQueuedRunEdit = () => {
389 if (selectedThreadKey === null || savingQueuedEditRef.current) return;
390 endQueuedRunEdit(selectedThreadKey);
391 };
392
393 const onRemoveQueuedEditAttachment = (attachmentId: string) => {
394 if (selectedThreadKey === null) return;
395 removeQueuedRunEditAttachment(selectedThreadKey, attachmentId);
396 };
397
398 const saveQueuedRunEdit = async () => {
399 const thread = selectedThreadShell;
400 if (!thread || savingQueuedEditRef.current) return;
401 const threadKey = scopedThreadKey(thread.environmentId, thread.id);
402 const edit = getQueuedRunEdit(threadKey);
403 if (edit === null) return;
404 const draft = getComposerDraftSnapshot(queuedEditDraftKey(threadKey, edit.runId));
405 const text = draft.text.trim();
406 if (text.length === 0) {
407 Dialog.alert("Add a message", "A queued message cannot be left empty.");
408 return;
409 }
410 if (
411 edit.existingAttachments.length + draft.attachments.length >
412 PROVIDER_SEND_TURN_MAX_ATTACHMENTS
413 ) {
414 Dialog.alert(
415 "Too many attachments",
416 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
417 );
418 return;
419 }
420 const finishSave = startQueuedRunEditSave(threadKey);
421 if (finishSave === null) return;
422 savingQueuedEditRef.current = true;
423 setIsSavingQueuedEdit(true);
424 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
425 const prepared = await settlePromise(() =>
426 prepareTurnAttachments({
427 environmentId: thread.environmentId,
428 attachments: draft.attachments,
429 supportsImageUploads: capabilities !== undefined,
430 }),
431 );
432 if (AsyncResult.isFailure(prepared)) {
433 savingQueuedEditRef.current = false;
434 setIsSavingQueuedEdit(false);
435 finishSave(false);
436 const error = squashAtomCommandFailure(prepared);
437 Dialog.alert(
438 "Could not save the queued message",
439 error instanceof Error ? error.message : "Your edit is still in the composer.",
440 );
441 return;
442 }
443 if (prepared.value.status !== "ready") {
444 savingQueuedEditRef.current = false;
445 setIsSavingQueuedEdit(false);
446 finishSave(false);
447 return;
448 }
449 const payload = resolveQueuedEditPayload({
450 edit,
451 draftContext: draft.context,
452 draftAttachments: draft.attachments,
453 uploaded: prepared.value.attachments,
454 });
455 const result = await editQueuedRun({
456 environmentId: thread.environmentId,
457 input: {
458 threadId: thread.id,
459 runId: edit.runId,
460 text,
461 edit: {
462 messageId: edit.messageId,
463 attachments: payload.attachments,
464 ...(payload.context ? { context: payload.context } : {}),
465 },
466 },
467 });
468 savingQueuedEditRef.current = false;
469 setIsSavingQueuedEdit(false);
470 if (result._tag !== "Success") {
471 // The run left the queue during the save; its exit already told the composer what happened.
472 if (!finishSave(false)) return;
473 Dialog.alert(
474 "Could not save the queued message",
475 "It may have already started. Your edit is still in the composer.",
476 );
477 return;
478 }
479 // False when the edit was cancelled or begun again meanwhile; its draft is the newer edit's.
480 if (finishSave(true)) {
481 clearComposerDraft(queuedEditDraftKey(threadKey, edit.runId), {
482 deferAttachmentCleanup: true,
483 });
484 }
485 scheduleUnusedComposerAttachmentCleanup(draft.attachments);
486 };
487
488 const onSendMessage = async (
489 followUpOverride?: ActiveTurnComposerAction,
490 beforeDispatch?: (
491 text: string,
492 hasAttachmentsOrContext: boolean,
493 ) => Promise<boolean | "responded">,
494 ) => {
495 if (
496 selectedThreadShell &&
497 selectedEnvironmentRuntime?.connectionState === "connected" &&
498 !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
499 )
500 return null;
501 if (!selectedThreadShell) {
502 return null;
503 }
504 // Before thread creation succeeds, follow-ups could become orphaned and be dropped by the drain.
505 if (selectedThreadCreation !== null) {
506 return null;
507 }
508
509 const editKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
510 if (getQueuedRunEdit(editKey) !== null) {
511 await saveQueuedRunEdit();
512 return null;
513 }
514
515 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
516 const draft = getComposerDraftSnapshot(threadKey);
517 if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
518 const thread = selectedThreadShell;
519 const text = draft.text.trim();
520 const attachments = draft.attachments;
521 if (
522 composerAttachmentUploadBlockReason({
523 environmentId: selectedThreadShell.environmentId,
524 attachments,
525 connected: selectedEnvironmentRuntime?.connectionState === "connected",
526 serverConfig: selectedEnvironmentRuntime?.serverConfig ?? null,
527 states: appAtomRegistry.get(composerAttachmentUploadsAtom),
528 }) !== null
529 )
530 return null;
531 if (text.length === 0 && attachments.length === 0) {
532 return null;
533 }
534 // Recovery preserves over-cap attachments; require trimming or outbox delivery would reject indefinitely.
535 if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
536 Dialog.alert(
537 "Too many attachments",
538 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
539 );
540 return null;
541 }
542
543 const contextBlockReason = composerContextSendBlockReason(draft.context);
544 if (contextBlockReason) {
545 Dialog.alert("Too much context", contextBlockReason);
546 return null;
547 }
548
549 const modelSelection = draft.modelSelection ?? thread.modelSelection;
550 const serverConfig = selectedEnvironmentRuntime?.serverConfig;
551 if (
552 selectedEnvironmentRuntime?.connectionState === "connected" &&
553 isModelSelectionUnavailable(serverConfig, modelSelection, thread.projectId)
554 ) {
555 const { title, detail } = describeUnavailableModelSelection(
556 serverConfig,
557 modelSelection,
558 thread.projectId,
559 );
560 Dialog.alert(title, detail);
561 return null;
562 }
563 const provider = serverConfig?.providers.find(
564 (entry) => entry.instanceId === modelSelection.instanceId,
565 );
566 const feedbackCommand =
567 attachments.length === 0 && provider?.driver === "codex"
568 ? parseCodexFeedbackCommand(text)
569 : null;
570 if (feedbackCommand) {
571 if (!readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope))
572 return null;
573 if (thread.activeProviderThreadId === null) {
574 Dialog.alert("Start a Codex thread first", "Send a message before you submit feedback.");
575 return null;
576 }
577 const metadata = makeQueuedMessageMetadata();
578 await submitCodexFeedback({
579 submission: {
580 id: MessageId.make(metadata.messageId),
581 command: text,
582 createdAt: metadata.createdAt,
583 },
584 clearDraft: () => clearComposerDraftContent(threadKey),
585 onUpdate: (submission) => {
586 setFeedbackSubmissionsByThreadKey((current) => {
587 const existing = current[threadKey] ?? [];
588 const found = existing.some((entry) => entry.id === submission.id);
589 return {
590 ...current,
591 [threadKey]: found
592 ? existing.map((entry) => (entry.id === submission.id ? submission : entry))
593 : [...existing, submission],
594 };
595 });
596 },
597 upload: () =>
598 uploadThreadFeedback({
599 environmentId: thread.environmentId,
600 input: { threadId: thread.id, ...feedbackCommand },
601 }),
602 });
603 return null;
604 }
605
606 if (beforeDispatch !== undefined) {
607 const response = await beforeDispatch(
608 text,
609 attachments.length > 0 || draft.context !== undefined,
610 );
611 if (!response) return null;
612 // A context paste still landing, or any draft or settings change while approvals were
613 // declined, means this snapshot is no longer what the user sent.
614 if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
615 const current = getComposerDraftSnapshot(threadKey);
616 if (
617 current.text !== draft.text ||
618 JSON.stringify(current.context) !== JSON.stringify(draft.context) ||
619 JSON.stringify(current.modelSelection) !== JSON.stringify(draft.modelSelection) ||
620 current.runtimeMode !== draft.runtimeMode ||
621 current.interactionMode !== draft.interactionMode ||
622 current.attachments.length !== attachments.length ||
623 current.attachments.some((attachment, index) => attachment.id !== attachments[index]?.id)
624 )
625 return null;
626 if (response === "responded") {
627 clearComposerDraftContent(threadKey);
628 return null;
629 }
630 }
631
632 // Resolve at send time because outbox delivery may be delayed.
633 // Steering uses "auto" so an ended turn queues a run instead of restoring the draft.
634 // An approval redirect must steer the waiting turn instead of queueing behind it.
635 const activeTurnDefault = beforeDispatch !== undefined ? "steer" : followUpBehavior;
636 const followUpAction = resolveComposerDispatchMode({
637 running: activeThreadBusy && canSteerActiveTurn,
638 alternateModifier: followUpOverride !== undefined && followUpOverride !== activeTurnDefault,
639 activeTurnDefault,
640 });
641 const setupRunning = [selectedThreadActivityRun?.status, selectedThreadRuntime?.status].some(
642 (status) => status === "preparing" || status === "starting",
643 );
644 const followUpDispatchMode = setupRunning
645 ? "queue"
646 : followUpAction === "auto"
647 ? null
648 : followUpAction === "queue"
649 ? "queue"
650 : "auto";
651
652 const metadata = makeQueuedMessageMetadata();
653 const messageId = MessageId.make(metadata.messageId);
654 clearThreadComposerError(threadKey);
655 const enqueuePromise = enqueueThreadOutboxMessage({
656 environmentId: selectedThreadShell.environmentId,
657 threadId: selectedThreadShell.id,
658 messageId,
659 commandId: CommandId.make(metadata.commandId),
660 text,
661 attachments,
662 context: draft.context,
663 modelSelection,
664 runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
665 interactionMode: resolveProviderInteractionMode(
666 provider,
667 draft.interactionMode ?? thread.interactionMode,
668 ),
669 ...(followUpDispatchMode === null ? {} : { dispatchMode: followUpDispatchMode }),
670 createdAt: metadata.createdAt,
671 });
672 clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
673 enqueuePromise.then(
674 () => scheduleUnusedComposerAttachmentCleanup(attachments),
675 (error: unknown) => {
676 // Restore with uncapped append; capped merge could drop attachments added during the failed write.
677 void mergeComposerDraftContent(threadKey, {
678 text,
679 context: draft.context,
680 attachments: [],
681 });
682 appendComposerDraftAttachments(threadKey, attachments, { allowOverflow: true });
683 setThreadComposerError(
684 threadKey,
685 error instanceof Error ? error.message : "Failed to save the queued message.",
686 );
687 },
688 );
689 return messageId;
690 };
691
692 const onChangeDraftMessage = (value: string) => {
693 if (!selectedThreadShell) {
694 return;
695 }
696
697 const threadKey = activeComposerDraftKey(selectedThreadShell);
698 setComposerDraftText(threadKey, value);
699 };
700
701 const { onPickDraftMedia, onPickDraftFiles, onNativePasteImages, onNativePasteText } =
702 useComposerAttachmentActions({
703 draftKey: selectedThreadShell ? activeComposerDraftKey(selectedThreadShell) : null,
704 serverConfig: selectedEnvironmentRuntime?.serverConfig,
705 });
706
707 const onRemoveDraftImage = (imageId: string) => {
708 if (!selectedThreadShell) {
709 return;
710 }
711
712 const threadKey = activeComposerDraftKey(selectedThreadShell);
713 removeComposerDraftAttachment(threadKey, imageId);
714 };
715
716 const onUpdateInteractionMode = (value: ProviderInteractionMode) => {
717 if (!selectedThreadKey) {
718 return;
719 }
720 const modelSelection =
721 getComposerDraftSnapshot(selectedThreadKey).modelSelection ?? selectedThread?.modelSelection;
722 const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
723 (candidate) => candidate.instanceId === modelSelection?.instanceId,
724 );
725 updateComposerDraftSettings(selectedThreadKey, {
726 interactionMode: resolveProviderInteractionMode(provider, value),
727 });
728 };
729
730 return {
731 feedbackSubmissions,
732 dismissFeedback,
733 selectedThreadFeed,
734 selectedThreadActivityRun,
735 selectedThreadQueueCount,
736 selectedThreadQueuedMessages,
737 dispatchingQueuedMessageId,
738 activeWorkStartedAt,
739 runlessWorkActive,
740 providerSubagentStatus,
741 isCompacting,
742 composerDraftKey,
743 followUpBehavior,
744 canSteerActiveTurn,
745 queueHeld,
746 queuedRunEdit,
747 isSavingQueuedEdit,
748 cancelQueuedRunEdit,
749 onRemoveQueuedEditAttachment,
750 modelSelection,
751 pendingHandoff,
752 canSwitchThreadProvider,
753 runtimeMode,
754 interactionMode,
755 activeThreadBusy,
756 interruptibleRunId,
757 onChangeDraftMessage,
758 onPickDraftMedia,
759 onPickDraftFiles,
760 onNativePasteImages,
761 onNativePasteText,
762 onRemoveDraftImage,
763 onSendMessage,
764 onUpdateInteractionMode,
765 };
766}