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

use-thread-composer-state.ts

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