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

use-thread-composer-state.ts

777 lines29.1 KB

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 }
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);
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 };
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 });
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 ) => {
505 if (
506 selectedThreadShell &&
507 selectedEnvironmentRuntime?.connectionState === "connected" &&
508 !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
509 )
510 return null;
511 if (!selectedThreadShell) {
512 return null;
513 }
514 // Before thread creation succeeds, follow-ups could become orphaned and be dropped by the drain.
515 if (selectedThreadCreation !== null) {
516 return null;
517 }
518​
519 const editKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
520 if (getQueuedRunEdit(editKey) !== null) {
521 await saveQueuedRunEdit();
522 return null;
523 }
524​
525 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
526 const draft = getComposerDraftSnapshot(threadKey);
527 if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
528 const thread = selectedThreadShell;
529 const text = draft.text.trim();
530 const attachments = draft.attachments;
531 if (
532 composerAttachmentUploadBlockReason({
533 environmentId: selectedThreadShell.environmentId,
534 attachments,
535 connected: selectedEnvironmentRuntime?.connectionState === "connected",
536 serverConfig: selectedEnvironmentRuntime?.serverConfig ?? null,
537 states: appAtomRegistry.get(composerAttachmentUploadsAtom),
538 }) !== null
539 )
540 return null;
541 if (text.length === 0 && attachments.length === 0) {
542 return null;
543 }
544 // Recovery preserves over-cap attachments; require trimming or outbox delivery would reject indefinitely.
545 if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
546 Dialog.alert(
547 "Too many attachments",
548 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
549 );
550 return null;
551 }
552​
553 const contextBlockReason = composerContextSendBlockReason(draft.context);
554 if (contextBlockReason) {
555 Dialog.alert("Too much context", contextBlockReason);
556 return null;
557 }
558​
559 const modelSelection = draft.modelSelection ?? thread.modelSelection;
560 const serverConfig = selectedEnvironmentRuntime?.serverConfig;
561 if (
562 selectedEnvironmentRuntime?.connectionState === "connected" &&
563 isModelSelectionUnavailable(serverConfig, modelSelection, thread.projectId)
564 ) {
565 const { title, detail } = describeUnavailableModelSelection(
566 serverConfig,
567 modelSelection,
568 thread.projectId,
569 );
570 Dialog.alert(title, detail);
571 return null;
572 }
573 const provider = serverConfig?.providers.find(
574 (entry) => entry.instanceId === modelSelection.instanceId,
575 );
576 const feedbackCommand =
577 attachments.length === 0 && provider?.driver === "codex"
578 ? parseCodexFeedbackCommand(text)
579 : null;
580 if (feedbackCommand) {
581 if (!readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope))
582 return null;
583 if (thread.activeProviderThreadId === null) {
584 Dialog.alert("Start a Codex thread first", "Send a message before you submit feedback.");
585 return null;
586 }
587 const metadata = makeQueuedMessageMetadata();
588 await submitCodexFeedback({
589 submission: {
590 id: MessageId.make(metadata.messageId),
591 command: text,
592 createdAt: metadata.createdAt,
593 },
594 clearDraft: () => clearComposerDraftContent(threadKey),
595 onUpdate: (submission) => {
596 setFeedbackSubmissionsByThreadKey((current) => {
597 const existing = current[threadKey] ?? [];
598 const found = existing.some((entry) => entry.id === submission.id);
599 return {
600 ...current,
601 [threadKey]: found
602 ? existing.map((entry) => (entry.id === submission.id ? submission : entry))
603 : [...existing, submission],
604 };
605 });
606 },
607 upload: () =>
608 uploadThreadFeedback({
609 environmentId: thread.environmentId,
610 input: { threadId: thread.id, ...feedbackCommand },
611 }),
612 });
613 return null;
614 }
615​
616 if (beforeDispatch !== undefined) {
617 const response = await beforeDispatch(
618 text,
619 attachments.length > 0 || draft.context !== undefined,
620 );
621 if (!response) return null;
622 // A context paste still landing, or any draft or settings change while approvals were
623 // declined, means this snapshot is no longer what the user sent.
624 if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
625 const current = getComposerDraftSnapshot(threadKey);
626 if (
627 current.text !== draft.text ||
628 JSON.stringify(current.context) !== JSON.stringify(draft.context) ||
629 JSON.stringify(current.modelSelection) !== JSON.stringify(draft.modelSelection) ||
630 current.runtimeMode !== draft.runtimeMode ||
631 current.interactionMode !== draft.interactionMode ||
632 current.attachments.length !== attachments.length ||
633 current.attachments.some((attachment, index) => attachment.id !== attachments[index]?.id)
634 )
635 return null;
636 if (response === "responded") {
637 clearComposerDraftContent(threadKey);
638 return null;
639 }
640 }
641​
642 // Resolve at send time because outbox delivery may be delayed.
643 // Steering uses "auto" so an ended turn queues a run instead of restoring the draft.
644 // An approval redirect must steer the waiting turn instead of queueing behind it.
645 const activeTurnDefault = beforeDispatch !== undefined ? "steer" : followUpBehavior;
646 const followUpAction = resolveComposerDispatchMode({
647 running: activeThreadBusy && canSteerActiveTurn,
648 alternateModifier: followUpOverride !== undefined && followUpOverride !== activeTurnDefault,
649 activeTurnDefault,
650 });
651 const setupRunning = [selectedThreadActivityRun?.status, selectedThreadRuntime?.status].some(
652 (status) => status === "preparing" || status === "starting",
653 );
654 const followUpDispatchMode = setupRunning
655 ? "queue"
656 : followUpAction === "auto"
657 ? null
658 : followUpAction === "queue"
659 ? "queue"
660 : "auto";
661​
662 const metadata = makeQueuedMessageMetadata();
663 const messageId = MessageId.make(metadata.messageId);
664 clearThreadComposerError(threadKey);
665 const enqueuePromise = enqueueThreadOutboxMessage({
666 environmentId: selectedThreadShell.environmentId,
667 threadId: selectedThreadShell.id,
668 messageId,
669 commandId: CommandId.make(metadata.commandId),
670 text,
671 attachments,
672 context: draft.context,
673 modelSelection,
674 runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
675 interactionMode: resolveProviderInteractionMode(
676 provider,
677 draft.interactionMode ?? thread.interactionMode,
678 ),
679 ...(followUpDispatchMode === null ? {} : { dispatchMode: followUpDispatchMode }),
680 createdAt: metadata.createdAt,
681 });
682 clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
683 enqueuePromise.then(
684 () => scheduleUnusedComposerAttachmentCleanup(attachments),
685 (error: unknown) => {
686 // Restore with uncapped append; capped merge could drop attachments added during the failed write.
687 void mergeComposerDraftContent(threadKey, {
688 text,
689 context: draft.context,
690 attachments: [],
691 });
692 appendComposerDraftAttachments(threadKey, attachments, { allowOverflow: true });
693 setThreadComposerError(
694 threadKey,
695 error instanceof Error ? error.message : "Failed to save the queued message.",
696 );
697 },
698 );
699 return messageId;
700 };
701​
702 const onChangeDraftMessage = (value: string) => {
703 if (!selectedThreadShell) {
704 return;
705 }
706​
707 const threadKey = activeComposerDraftKey(selectedThreadShell);
708 setComposerDraftText(threadKey, value);
709 };
710​
711 const { onPickDraftMedia, onPickDraftFiles, onNativePasteImages, onNativePasteText } =
712 useComposerAttachmentActions({
713 draftKey: selectedThreadShell ? activeComposerDraftKey(selectedThreadShell) : null,
714 serverConfig: selectedEnvironmentRuntime?.serverConfig,
715 });
716​
717 const onRemoveDraftImage = (imageId: string) => {
718 if (!selectedThreadShell) {
719 return;
720 }
721​
722 const threadKey = activeComposerDraftKey(selectedThreadShell);
723 removeComposerDraftAttachment(threadKey, imageId);
724 };
725​
726 const onUpdateInteractionMode = (value: ProviderInteractionMode) => {
727 if (!selectedThreadKey) {
728 return;
729 }
730 const modelSelection =
731 getComposerDraftSnapshot(selectedThreadKey).modelSelection ?? selectedThread?.modelSelection;
732 const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
733 (candidate) => candidate.instanceId === modelSelection?.instanceId,
734 );
735 updateComposerDraftSettings(selectedThreadKey, {
736 interactionMode: resolveProviderInteractionMode(provider, value),
737 });
738 };
739​
740 return {
741 feedbackSubmissions,
742 dismissFeedback,
743 selectedThreadFeed,
744 selectedThreadActivityRun,
745 selectedThreadQueueCount,
746 selectedThreadQueuedMessages,
747 dispatchingQueuedMessageId,
748 activeWorkStartedAt,
749 runlessWorkActive,
750 providerSubagentStatus,
751 isCompacting,
752 composerDraftKey,
753 followUpBehavior,
754 canSteerActiveTurn,
755 queueHeld,
756 resumableRunId,
757 queuedRunEdit,
758 isSavingQueuedEdit,
759 cancelQueuedRunEdit,
760 onRemoveQueuedEditAttachment,
761 modelSelection,
762 pendingHandoff,
763 canSwitchThreadProvider,
764 runtimeMode,
765 interactionMode,
766 activeThreadBusy,
767 interruptibleRunId,
768 onChangeDraftMessage,
769 onPickDraftMedia,
770 onPickDraftFiles,
771 onNativePasteImages,
772 onNativePasteText,
773 onRemoveDraftImage,
774 onSendMessage,
775 onUpdateInteractionMode,
776 };