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