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

use-thread-composer-state.ts

942 lines36.3 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 { compactBeforeSendTokens } from "@t3tools/client-runtime/state/context-window";
7import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
8import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
9import { threadSteersDuringCompaction } from "@t3tools/client-runtime/state/thread-workflows";
10import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff";
11import {
12 announcedRun,
13 isDetailBehindShell,
14} from "@t3tools/client-runtime/state/thread-activity-announcement";
15import {
16 deriveProviderSubagentStatus,
17 deriveProviderExtensionStatuses,
18 deriveResumableRunId,
19 deriveLatestThreadRun,
20 deriveRunlessWorkStartedAt,
21 deriveThreadActivityRun,
22 deriveThreadRuntime,
23 threadRuntimeHasInterruptibleRun,
24} from "@t3tools/client-runtime/state/thread-execution";
25import { useEffect, useRef, useState } from "react";
26​
27import {
28 CommandId,
29 DEFAULT_PROVIDER_INTERACTION_MODE,
30 MessageId,
31 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
32 type EnvironmentId,
33 type ModelSelection,
34 type RuntimeMode,
35 type ScopedThreadRef,
36 type ThreadId,
37} from "@t3tools/contracts";
38​
39import {
40 parseCodexFeedbackCommand,
41 submitCodexFeedback,
42 type CodexFeedbackSubmission,
43} from "@t3tools/client-runtime/state/threads";
44import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
45import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLegacy";
46import { restoreAttachmentOnlyBootstrapPrompt } from "@t3tools/shared/composerContextReferences";
47import { composerContextSendBlockReason, reidentifyComposerContext } from "../lib/composerContext";
48import { uuidv4 } from "../lib/uuid";
49import { useNowMinuteMs } from "../lib/clock";
50​
51import { makeQueuedMessageMetadata } from "../lib/commandMetadata";
52import {
53 describeUnavailableModelSelection,
54 isModelSelectionUnavailable,
55} from "../lib/modelOptions";
56​
57import type { DraftComposerImageAttachment } from "../lib/composerImages";
58import { scopedThreadKey } from "../lib/scopedEntities";
59import { buildThreadFeed, createThreadFeedCache } from "../lib/threadActivity";
60import {
61 acknowledgedThreadMessagesAtom,
62 pruneCaughtUpAcknowledgedThreadMessages,
63} from "./acknowledged-thread-messages";
64import {
65 appendPendingThreadMessages,
66 selectPendingAcknowledgedMessages,
67} from "../features/threads/pending-thread-feed";
68import { threadAllowsProviderSwitch } from "./thread-provider-switching";
69import { appAtomRegistry } from "./atom-registry";
70import { pendingThreadCreationMessage } from "./pending-thread-creation";
71import {
72 composerAttachmentUploadBlockReason,
73 composerAttachmentUploadsAtom,
74} from "./composer-attachment-uploads";
75import {
76 appendComposerDraftAttachments,
77 insertComposerDraftContext,
78 clearComposerDraft,
79 clearComposerDraftContent,
80 composerContextImportsAtom,
81 getComposerDraftSnapshot,
82 isFreshSessionPending,
83 mergeComposerDraftContent,
84 removeComposerDraftAttachment,
85 scheduleUnusedComposerAttachmentCleanup,
86 setComposerDraftText,
87 setFreshSessionPending,
88 useComposerDraft,
89 useComposerDraftSettings,
90} from "./use-composer-drafts";
91import { isClearComposerCommand, parseSideChatCommand } from "@t3tools/shared/composerTrigger";
92import { orchestrationV2WorktreePending } from "@t3tools/shared/orchestrationV2ThreadError";
93import {
94 compactionBlocksSteering,
95 resolveComposerDispatchMode,
96 type ActiveTurnComposerAction,
97} from "@t3tools/client-runtime/state/composer-dispatch";
98import { Atom } from "effect/reactivity";
99import { AsyncResult } from "effect/reactivity";
100import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
101import { prepareTurnAttachments } from "../lib/attachmentUpload";
102import { DEFAULT_FOLLOW_UP_BEHAVIOR } from "../lib/followUpBehavior";
103import { mobilePreferencesAtom } from "./preferences";
104import { environmentThreadDetails } from "./threads";
105import {
106 endQueuedRunEdit,
107 getQueuedRunEdit,
108 queuedEditDraftKey,
109 removeQueuedRunEditAttachment,
110 resolveQueuedEditPayload,
111 startQueuedRunEditSave,
112 useQueuedRunEdit,
113} from "./queued-run-edit";
114import { setPendingConnectionError } from "./use-remote-environment-registry";
115import { clearThreadComposerError, setThreadComposerError } from "./thread-composer-error";
116import {
117 useSelectedThreadProjection,
118 useSelectedThreadVisibleTurnItems,
119} from "./use-thread-detail";
120import { useThreadSelection } from "./use-thread-selection";
121import { enqueueThreadOutboxMessage } from "./thread-outbox";
122import { dispatchingQueuedMessageIdAtom, useThreadOutboxMessages } from "./use-thread-outbox";
123import { threadEnvironment } from "./threads";
124import { useAtomCommand } from "./use-atom-command";
125​
126const EMPTY_QUEUE_WORKFLOW_ATOM = Atom.make<null>(null).pipe(
127 Atom.withLabel("mobile-thread-queue-workflow:empty"),
128);
129// Threads whose next send keeps the full history instead of compacting first.
130const fullHistoryThreadKeysAtom = Atom.make<Readonly<Record<string, true>>>({}).pipe(
131 Atom.keepAlive,
132);
133​
134function setKeepFullHistory(threadKey: string, keep: boolean) {
135 const { [threadKey]: kept, ...rest } = appAtomRegistry.get(fullHistoryThreadKeysAtom);
136 if ((kept === true) === keep) return;
137 appAtomRegistry.set(fullHistoryThreadKeysAtom, keep ? { ...rest, [threadKey]: true } : rest);
139​
140const EMPTY_CHECKPOINT_SUMMARIES_ATOM = Atom.make<ReadonlyArray<ThreadCheckpointSummary>>([]);
141const EMPTY_THREAD_SEQUENCE_ATOM = Atom.make(0);
142​
143export function appendReviewCommentToDraft(input: {
144 readonly environmentId: EnvironmentId;
145 readonly threadId: ThreadId;
146 readonly text: string;
147 readonly attachments?: ReadonlyArray<DraftComposerImageAttachment>;
148}): void {
149 const threadKey = scopedThreadKey(input.environmentId, input.threadId);
150 const upgraded = upgradeLegacyContextMessage(input.text);
151 if (
152 !insertComposerDraftContext(
153 threadKey,
154 reidentifyComposerContext(upgraded.text, upgraded.records, uuidv4),
155 )
156 ) {
157 Dialog.alert("Too many context items", "Remove some context from the draft and try again.");
158 return;
159 }
160 if (input.attachments && input.attachments.length > 0) {
161 const rejectedCount = appendComposerDraftAttachments(threadKey, input.attachments, {
162 appendReference: true,
163 });
164 if (rejectedCount > 0) {
165 setPendingConnectionError(
166 `${rejectedCount} comment attachment${rejectedCount === 1 ? " was" : "s were"} not added. Messages can contain at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments.`,
167 );
168 }
169 }
171​
172/** Resolve per call so callbacks created before editing still target the current draft. */
173function activeComposerDraftKey(thread: {
174 readonly environmentId: EnvironmentId;
175 readonly id: ThreadId;
176}): string {
177 const threadKey = scopedThreadKey(thread.environmentId, thread.id);
178 const edit = getQueuedRunEdit(threadKey);
179 return edit === null ? threadKey : queuedEditDraftKey(threadKey, edit.runId);
181​
182export function useThreadDraftForThread(input: {
183 readonly environmentId?: EnvironmentId;
184 readonly threadId?: ThreadId;
185}) {
186 const threadKey =
187 input.environmentId && input.threadId
188 ? scopedThreadKey(input.environmentId, input.threadId)
189 : null;
190 const draft = useComposerDraft(threadKey);
191​
192 return {
193 draftMessage: draft.text,
194 draftContext: draft.context,
195 draftAttachments: draft.attachments,
196 };
198​
199export function useThreadComposerState(input: {
200 /** Forks the thread into a side chat that gets `prompt`; resolves false when it did not start. */
201 readonly startSideChat: (
202 source: ScopedThreadRef,
203 prompt: string,
204 settings: { readonly runtimeMode: RuntimeMode; readonly modelSelection: ModelSelection },
205 ) => Promise<boolean>;
206}) {
207 const {
208 selectedThread: selectedThreadShell,
209 selectedThreadCreation,
210 selectedThreadDetailRef,
211 selectedEnvironmentRuntime,
212 } = useThreadSelection();
213 const selectedThreadProjection = useSelectedThreadProjection();
214 const selectedThreadVisibleTurnItems = useSelectedThreadVisibleTurnItems();
215 const acknowledgedMessages = useAtomValue(acknowledgedThreadMessagesAtom);
216 const queuedMessagesByThreadKey = useThreadOutboxMessages();
217 const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
218 const [feedbackSubmissionsByThreadKey, setFeedbackSubmissionsByThreadKey] = useState<
219 Record<string, ReadonlyArray<CodexFeedbackSubmission>>
220 >({});
221 const uploadThreadFeedback = useAtomCommand(threadEnvironment.uploadFeedback, {
222 reportFailure: false,
223 });
224 const editQueuedRun = useAtomCommand(threadEnvironment.editQueuedRun, {
225 label: "edit queued message",
226 reportFailure: false,
227 });
228 const [isSavingQueuedEdit, setIsSavingQueuedEdit] = useState(false);
229 const savingQueuedEditRef = useRef(false);
230 const startingSideChatRef = useRef(false);
231​
232 const selectedThreadKey = selectedThreadShell
233 ? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id)
234 : null;
235 const selectedThreadQueuedMessages = selectedThreadKey
236 ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []).filter(
237 (message) => message.creation === undefined,
238 )
239 : [];
240 const feedbackSubmissions = selectedThreadKey
241 ? (feedbackSubmissionsByThreadKey[selectedThreadKey] ?? [])
242 : [];
243 const dismissFeedback = (id: MessageId) => {
244 if (!selectedThreadKey) return;
245 setFeedbackSubmissionsByThreadKey((current) => ({
246 ...current,
247 [selectedThreadKey]: (current[selectedThreadKey] ?? []).filter((entry) => entry.id !== id),
248 }));
249 };
250 const selectedThreadMessages = selectedThreadProjection?.projection.messages;
251 const selectedThreadAttempts = selectedThreadProjection?.projection.attempts;
252 const selectedThreadNodes = selectedThreadProjection?.projection.nodes;
253 const selectedThreadSequence = useAtomValue(
254 selectedThreadDetailRef === null
255 ? EMPTY_THREAD_SEQUENCE_ATOM
256 : environmentThreadDetails.sequenceAtom(selectedThreadDetailRef),
257 );
258 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- prunes the app-wide acknowledged atom when the mounted thread catches up
259 useEffect(() => {
260 if (selectedThreadKey === null || acknowledgedMessages.length === 0) return;
261 pruneCaughtUpAcknowledgedThreadMessages(selectedThreadKey, {
262 sequence: selectedThreadSequence,
263 messages: selectedThreadMessages,
264 });
265 }, [acknowledgedMessages, selectedThreadKey, selectedThreadSequence, selectedThreadMessages]);
266 const checkpointSummaries = useAtomValue(
267 selectedThreadDetailRef === null
268 ? EMPTY_CHECKPOINT_SUMMARIES_ATOM
269 : environmentThreadDetails.checkpointSummariesAtom(selectedThreadDetailRef),
270 );
271 // A thread whose creation has not delivered its turn yet: the prompt only
272 // exists in the outbox, so it is appended to whatever the server has. The
273 // detail is usually present but empty during a worktree checkout, so this
274 // cannot be an either/or with the loaded messages.
275 const pendingCreationMessage = selectedThreadCreation?.message ?? null;
276 const [feedCache] = useState(createThreadFeedCache);
277 const selectedThreadFeed = (() => {
278 const pendingCreation =
279 pendingCreationMessage !== null &&
280 !selectedThreadMessages?.some((message) => message.id === pendingCreationMessage.messageId)
281 ? [pendingThreadCreationMessage(pendingCreationMessage)]
282 : [];
283 const feed = buildThreadFeed(selectedThreadVisibleTurnItems, {
284 anchoredMessages: pendingCreation,
285 attempts: selectedThreadAttempts,
286 nodes: selectedThreadNodes,
287 checkpointSummaries,
288 cache: feedCache,
289 });
290 const pendingAcknowledgments = selectPendingAcknowledgedMessages(acknowledgedMessages, {
291 threadKey: selectedThreadKey,
292 queuedMessages: selectedThreadQueuedMessages,
293 sequence: selectedThreadSequence,
294 projectedMessages: selectedThreadMessages,
295 });
296 if (pendingAcknowledgments.length === 0) return feed;
297 return appendPendingThreadMessages(feed, feed, pendingAcknowledgments).map((entry) =>
298 entry.pendingMessage ? { ...entry, acknowledged: true } : entry,
299 );
300 })();
301​
302 const preferencesResult = useAtomValue(mobilePreferencesAtom);
303 const followUpBehavior = AsyncResult.isSuccess(preferencesResult)
304 ? (preferencesResult.value.followUpBehavior ?? DEFAULT_FOLLOW_UP_BEHAVIOR)
305 : DEFAULT_FOLLOW_UP_BEHAVIOR;
306 const queueWorkflow = useAtomValue(
307 selectedThreadDetailRef === null
308 ? EMPTY_QUEUE_WORKFLOW_ATOM
309 : environmentThreadDetails.queueWorkflowAtom(selectedThreadDetailRef),
310 );
311 const queuedRunEdit = useQueuedRunEdit(selectedThreadKey);
312 const composerDraftKey =
313 selectedThreadKey === null
314 ? null
315 : queuedRunEdit === null
316 ? selectedThreadKey
317 : queuedEditDraftKey(selectedThreadKey, queuedRunEdit.runId);
318 const selectedDraft = useComposerDraftSettings(selectedThreadKey);
319 const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
320 const selectedThread = selectedThreadShell;
321 const modelSelection = selectedDraft.modelSelection ?? selectedThread?.modelSelection ?? null;
322 const serverConfig = selectedEnvironmentRuntime?.serverConfig;
323 const pendingHandoff = resolvePendingHandoff(
324 selectedThreadProjection?.projection,
325 isModelSelectionUnavailable(serverConfig, modelSelection, selectedThread?.projectId ?? null)
326 ? null
327 : modelSelection,
328 serverConfig?.providers ?? [],
329 );
330 const runtimeMode = selectedDraft.runtimeMode ?? selectedThread?.runtimeMode ?? null;
331 // Plan mode is not offered to users; every send runs in build mode.
332 const interactionMode = selectedThread ? DEFAULT_PROVIDER_INTERACTION_MODE : null;
333 const canSwitchThreadProvider = threadAllowsProviderSwitch({
334 thread: selectedThreadShell,
335 projection: selectedThreadProjection?.projection,
336 });
337 const selectedThreadRuntime = selectedThreadProjection
338 ? deriveThreadRuntime(selectedThreadProjection.projection)
339 : (selectedThreadShell?.runtime ?? null);
340 const selectedThreadActivityRun = selectedThreadProjection
341 ? deriveThreadActivityRun(selectedThreadProjection.projection)
342 : (selectedThreadShell?.latestRun ?? null);
343 const selectedThreadAnnouncedRun = announcedRun(
344 selectedThreadActivityRun,
345 selectedThreadProjection?.projection.runs ?? [],
346 );
347 const selectedThreadDetailBehindShell = isDetailBehindShell(
348 selectedThreadProjection ? deriveLatestThreadRun(selectedThreadProjection.projection) : null,
349 selectedThreadShell?.latestRun ?? null,
350 );
351​
352 const activeRunId =
353 selectedThreadRuntime?.activeRunId && threadRuntimeIsActive(selectedThreadRuntime)
354 ? selectedThreadRuntime.activeRunId
355 : null;
356 const compactCommandIsActive = (() => {
357 const queuedCompact = selectedThreadQueuedMessages.some(
358 (message) =>
359 message.messageId === dispatchingQueuedMessageId &&
360 message.text.trim().toLowerCase() === "/compact" &&
361 message.attachments.length === 0,
362 );
363 if (queuedCompact) return true;
364 if (!activeRunId) return false;
365 const compactMessage = selectedThreadVisibleTurnItems.findLast(
366 ({ item }) =>
367 item.runId === activeRunId &&
368 item.type === "user_message" &&
369 item.text.trim().toLowerCase() === "/compact" &&
370 item.attachments.length === 0,
371 );
372 if (!compactMessage) return false;
373 return !selectedThreadVisibleTurnItems.some(
374 ({ item }) =>
375 item.runId === activeRunId &&
376 item.type === "compaction" &&
377 (item.status === "completed" ||
378 item.status === "failed" ||
379 item.status === "interrupted" ||
380 item.status === "cancelled"),
381 );
382 })();
383 const compactionRunning =
384 activeRunId !== null &&
385 selectedThreadVisibleTurnItems.some(
386 ({ item }) =>
387 item.runId === activeRunId && item.type === "compaction" && item.status === "running",
388 );
389 const isCompacting = compactCommandIsActive || compactionRunning;
390 const compactionBlocksSteer = compactionBlocksSteering({
391 compactCommandIsActive,
392 compactionRunning,
393 steersDuringCompaction: threadSteersDuringCompaction(selectedThreadProjection?.projection),
394 run: selectedThreadProjection?.projection.runs.find((run) => run.id === activeRunId),
395 messages: selectedThreadMessages,
396 });
397 const canSteerActiveTurn = queueWorkflow?.canPromoteToSteer === true && !compactionBlocksSteer;
398 // A stop or a restart holds the queue, completion wakes included, until it
399 // is resumed; the queue sheet lists only the user's own messages.
400 const queueHeld = queueWorkflow?.isHeld === true;
401 const resumableRunId = selectedThreadProjection
402 ? deriveResumableRunId(selectedThreadProjection.projection, selectedThreadRuntime)
403 : null;
404​
405 const runlessWorkStartedAt = selectedThreadProjection
406 ? deriveRunlessWorkStartedAt(selectedThreadProjection.projection)
407 : null;
408 const activeWorkStartedAt = (() => {
409 if (!selectedThreadShell) {
410 return null;
411 }
412 return (
413 resolveThreadWorkingStartedAt({
414 latestRun: selectedThreadActivityRun,
415 runtime: selectedThreadRuntime,
416 }) ?? runlessWorkStartedAt
417 );
418 })();
419 const runlessWorkActive = runlessWorkStartedAt !== null;
420​
421 const providerSubagentStatus = selectedThreadProjection
422 ? deriveProviderSubagentStatus(selectedThreadProjection.projection)
423 : null;
424​
425 const activeThreadBusy = threadRuntimeIsActive(selectedThreadRuntime);
426 const resumeCompactionTokens = (selection: ModelSelection | null, text: string, now: string) =>
427 selectedEnvironmentRuntime?.connectionState === "connected" &&
428 selectedThreadProjection !== null &&
429 serverConfig != null &&
430 selection !== null
431 ? compactBeforeSendTokens({
432 projection: selectedThreadProjection.projection,
433 visibleTurnItems: selectedThreadVisibleTurnItems,
434 selection,
435 providers: serverConfig.providers,
436 settings: serverConfig.settings,
437 text,
438 threadIdle:
439 !activeThreadBusy &&
440 !runlessWorkActive &&
441 !isCompacting &&
442 selectedThreadQueuedMessages.length === 0,
443 now,
444 })
445 : null;
446 const nowMinuteMs = useNowMinuteMs();
447 const compactTokens =
448 selectedDraft.freshContext === true
449 ? null
450 : resumeCompactionTokens(modelSelection, "", new Date(nowMinuteMs).toISOString());
451 const fullHistoryThreadKeys = useAtomValue(fullHistoryThreadKeysAtom);
452 const keepFullHistory =
453 selectedThreadKey !== null && fullHistoryThreadKeys[selectedThreadKey] === true;
454 const interruptibleRunId = threadRuntimeHasInterruptibleRun(selectedThreadRuntime)
455 ? (selectedThreadRuntime?.activeRunId ?? null)
456 : null;
457​
458 const cancelQueuedRunEdit = () => {
459 if (selectedThreadKey === null || savingQueuedEditRef.current) return;
460 endQueuedRunEdit(selectedThreadKey);
461 };
462​
463 const onRemoveQueuedEditAttachment = (attachmentId: string) => {
464 if (selectedThreadKey === null) return;
465 removeQueuedRunEditAttachment(selectedThreadKey, attachmentId);
466 };
467​
468 const saveQueuedRunEdit = async () => {
469 const thread = selectedThreadShell;
470 if (!thread || savingQueuedEditRef.current) return;
471 const threadKey = scopedThreadKey(thread.environmentId, thread.id);
472 const edit = getQueuedRunEdit(threadKey);
473 if (edit === null) return;
474 const draft = getComposerDraftSnapshot(queuedEditDraftKey(threadKey, edit.runId));
475 const text = draft.text.trim();
476 if (
477 text.length === 0 &&
478 edit.existingAttachments.length === 0 &&
479 draft.attachments.length === 0
480 ) {
481 Dialog.alert("Add a message", "A queued message cannot be left empty.");
482 return;
483 }
484 if (
485 edit.existingAttachments.length + draft.attachments.length >
486 PROVIDER_SEND_TURN_MAX_ATTACHMENTS
487 ) {
488 Dialog.alert(
489 "Too many attachments",
490 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
491 );
492 return;
493 }
494 const finishSave = startQueuedRunEditSave(threadKey);
495 if (finishSave === null) return;
496 savingQueuedEditRef.current = true;
497 setIsSavingQueuedEdit(true);
498 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
499 const prepared = await settlePromise(() =>
500 prepareTurnAttachments({
501 environmentId: thread.environmentId,
502 attachments: draft.attachments,
503 supportsImageUploads: capabilities !== undefined,
504 }),
505 );
506 if (AsyncResult.isFailure(prepared)) {
507 savingQueuedEditRef.current = false;
508 setIsSavingQueuedEdit(false);
509 finishSave(false);
510 const error = squashAtomCommandFailure(prepared);
511 Dialog.alert(
512 "Could not save the queued message",
513 error instanceof Error ? error.message : "Your edit is still in the composer.",
514 );
515 return;
516 }
517 if (prepared.value.status !== "ready") {
518 savingQueuedEditRef.current = false;
519 setIsSavingQueuedEdit(false);
520 finishSave(false);
521 return;
522 }
523 const payload = resolveQueuedEditPayload({
524 edit,
525 draftContext: draft.context,
526 draftAttachments: draft.attachments,
527 uploaded: prepared.value.attachments,
528 });
529 const result = await editQueuedRun({
530 environmentId: thread.environmentId,
531 input: {
532 threadId: thread.id,
533 runId: edit.runId,
534 text: restoreAttachmentOnlyBootstrapPrompt(text, payload.attachments.length > 0),
535 edit: {
536 messageId: edit.messageId,
537 attachments: payload.attachments,
538 ...(payload.context ? { context: payload.context } : {}),
539 },
540 },
541 });
542 savingQueuedEditRef.current = false;
543 setIsSavingQueuedEdit(false);
544 if (result._tag !== "Success") {
545 // The run left the queue during the save; its exit already told the composer what happened.
546 if (!finishSave(false)) return;
547 Dialog.alert(
548 "Could not save the queued message",
549 "It may have already started. Your edit is still in the composer.",
550 );
551 return;
552 }
553 // False when the edit was cancelled or begun again meanwhile; its draft is the newer edit's.
554 if (finishSave(true)) {
555 clearComposerDraft(queuedEditDraftKey(threadKey, edit.runId), {
556 deferAttachmentCleanup: true,
557 });
558 }
559 scheduleUnusedComposerAttachmentCleanup(draft.attachments);
560 };
561​
562 const onSendMessage = async (
563 followUpOverride?: ActiveTurnComposerAction,
564 beforeDispatch?: (
565 text: string,
566 hasAttachmentsOrContext: boolean,
567 ) => Promise<boolean | "responded">,
568 onWillEnqueue?: () => void,
569 ) => {
570 if (
571 selectedThreadShell &&
572 selectedEnvironmentRuntime?.connectionState === "connected" &&
573 !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
574 )
575 return null;
576 if (!selectedThreadShell) {
577 return null;
578 }
579 // Before thread creation succeeds, follow-ups could become orphaned and be dropped by the drain.
580 if (selectedThreadCreation !== null) {
581 return null;
582 }
583​
584 const editKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
585 if (getQueuedRunEdit(editKey) !== null) {
586 await saveQueuedRunEdit();
587 return null;
588 }
589​
590 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
591 const draft = getComposerDraftSnapshot(threadKey);
592 if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
593 const thread = selectedThreadShell;
594 const text = draft.text.trim();
595 const attachments = draft.attachments;
596 if (
597 composerAttachmentUploadBlockReason({
598 environmentId: selectedThreadShell.environmentId,
599 attachments,
600 connected: selectedEnvironmentRuntime?.connectionState === "connected",
601 serverConfig: selectedEnvironmentRuntime?.serverConfig ?? null,
602 states: appAtomRegistry.get(composerAttachmentUploadsAtom),
603 }) !== null
604 )
605 return null;
606 if (text.length === 0 && attachments.length === 0) {
607 return null;
608 }
609 const modelSelection = draft.modelSelection ?? thread.modelSelection;
610 const serverConfig = selectedEnvironmentRuntime?.serverConfig;
611 const modelUnavailable =
612 selectedEnvironmentRuntime?.connectionState === "connected" &&
613 isModelSelectionUnavailable(serverConfig, modelSelection, thread.projectId);
614 const alertModelUnavailable = () => {
615 const { title, detail } = describeUnavailableModelSelection(
616 serverConfig,
617 modelSelection,
618 thread.projectId,
619 );
620 Dialog.alert(title, detail);
621 };
622 // A redirect's text answers its approval, so `/side` there is that text, not the command.
623 const sideChatCommand = beforeDispatch === undefined ? parseSideChatCommand(text) : null;
624 if (sideChatCommand) {
625 if (sideChatUnavailableReason !== null) {
626 Dialog.alert("Side chat not started", sideChatUnavailableReason);
627 } else if (attachments.length > 0 || (draft.context?.records.length ?? 0) > 0) {
628 Dialog.alert(
629 "Side chats take text only",
630 "Remove the attachments and context, then send it again.",
631 );
632 } else if (sideChatCommand.prompt.length === 0) {
633 Dialog.alert("Ask a side question", "Type the question after /side, then send it.");
634 } else if (modelUnavailable) {
635 alertModelUnavailable();
636 } else if (!startingSideChatRef.current) {
637 startingSideChatRef.current = true;
638 const started = await input
639 .startSideChat(
640 { environmentId: thread.environmentId, threadId: thread.id },
641 sideChatCommand.prompt,
642 {
643 runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
644 modelSelection,
645 },
646 )
647 .finally(() => {
648 startingSideChatRef.current = false;
649 });
650 // Clear only what was sent; the draft may have changed while the side chat started.
651 const current = getComposerDraftSnapshot(threadKey);
652 if (
653 started &&
654 current.text === draft.text &&
655 current.attachments.length === 0 &&
656 (current.context?.records.length ?? 0) === 0
657 ) {
658 clearComposerDraftContent(threadKey);
659 }
660 }
661 return null;
662 }
663 // A redirect's text answers its approval, so /clear there is that text, not the command.
664 if (
665 beforeDispatch === undefined &&
666 selectedEnvironmentRuntime?.serverConfig?.environment.capabilities.freshContext === true &&
667 thread.latestRun != null &&
668 attachments.length === 0 &&
669 draft.context === undefined &&
670 isClearComposerCommand(text)
671 ) {
672 setFreshSessionPending(threadKey, true);
673 clearComposerDraftContent(threadKey);
674 return null;
675 }
676 // Recovery preserves over-cap attachments; require trimming or outbox delivery would reject indefinitely.
677 if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
678 Dialog.alert(
679 "Too many attachments",
680 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
681 );
682 return null;
683 }
684​
685 const contextBlockReason = composerContextSendBlockReason(draft.context);
686 if (contextBlockReason) {
687 Dialog.alert("Too much context", contextBlockReason);
688 return null;
689 }
690​
691 if (modelUnavailable) {
692 alertModelUnavailable();
693 return null;
694 }
695 const provider = serverConfig?.providers.find(
696 (entry) => entry.instanceId === modelSelection.instanceId,
697 );
698 const feedbackCommand =
699 attachments.length === 0 && provider?.driver === "codex"
700 ? parseCodexFeedbackCommand(text)
701 : null;
702 if (feedbackCommand) {
703 if (!readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope))
704 return null;
705 if (thread.activeProviderThreadId === null) {
706 Dialog.alert("Start a Codex thread first", "Send a message before you submit feedback.");
707 return null;
708 }
709 const metadata = makeQueuedMessageMetadata();
710 await submitCodexFeedback({
711 submission: {
712 id: MessageId.make(metadata.messageId),
713 command: text,
714 createdAt: metadata.createdAt,
715 },
716 clearDraft: () => clearComposerDraftContent(threadKey),
717 onUpdate: (submission) => {
718 setFeedbackSubmissionsByThreadKey((current) => {
719 const existing = current[threadKey] ?? [];
720 const found = existing.some((entry) => entry.id === submission.id);
721 return {
722 ...current,
723 [threadKey]: found
724 ? existing.map((entry) => (entry.id === submission.id ? submission : entry))
725 : [...existing, submission],
726 };
727 });
728 },
729 upload: () =>
730 uploadThreadFeedback({
731 environmentId: thread.environmentId,
732 input: { threadId: thread.id, ...feedbackCommand },
733 }),
734 });
735 return null;
736 }
737​
738 if (beforeDispatch !== undefined) {
739 const response = await beforeDispatch(
740 text,
741 attachments.length > 0 || draft.context !== undefined,
742 );
743 if (!response) return null;
744 // A context paste still landing, or any draft or settings change while approvals were
745 // declined, means this snapshot is no longer what the user sent.
746 if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
747 const current = getComposerDraftSnapshot(threadKey);
748 if (
749 current.text !== draft.text ||
750 JSON.stringify(current.context) !== JSON.stringify(draft.context) ||
751 JSON.stringify(current.modelSelection) !== JSON.stringify(draft.modelSelection) ||
752 current.runtimeMode !== draft.runtimeMode ||
753 current.interactionMode !== draft.interactionMode ||
754 current.attachments.length !== attachments.length ||
755 current.attachments.some((attachment, index) => attachment.id !== attachments[index]?.id)
756 )
757 return null;
758 if (response === "responded") {
759 clearComposerDraftContent(threadKey);
760 return null;
761 }
762 }
763​
764 // Resolve at send time because outbox delivery may be delayed.
765 // Steering uses "auto" so an ended turn queues a run instead of restoring the draft.
766 // An approval redirect must steer the waiting turn instead of queueing behind it.
767 const activeTurnDefault = beforeDispatch !== undefined ? "steer" : followUpBehavior;
768 const followUpAction = resolveComposerDispatchMode({
769 running: activeThreadBusy && canSteerActiveTurn,
770 alternateModifier: followUpOverride !== undefined && followUpOverride !== activeTurnDefault,
771 activeTurnDefault,
772 });
773 const setupRunning = [selectedThreadActivityRun?.status, selectedThreadRuntime?.status].some(
774 (status) => status === "preparing" || status === "starting",
775 );
776 const followUpDispatchMode = setupRunning
777 ? "queue"
778 : followUpAction === "auto"
779 ? null
780 : followUpAction === "queue"
781 ? "queue"
782 : "auto";
783​
784 // A redirect belongs to the approval it answers; the armed session waits for the next message.
785 const freshContext = beforeDispatch === undefined && isFreshSessionPending(threadKey);
786 const metadata = makeQueuedMessageMetadata();
787 // A fresh session drops the context a compaction would summarize. Only a send the notice
788 // announced compacts, since the notice's minute clock can trail the exact deadline.
789 const compactBeforeSend =
790 compactTokens !== null &&
791 !freshContext &&
792 followUpDispatchMode === null &&
793 appAtomRegistry.get(fullHistoryThreadKeysAtom)[threadKey] !== true &&
794 resumeCompactionTokens(modelSelection, text, metadata.createdAt) !== null;
795 const messageId = MessageId.make(metadata.messageId);
796 onWillEnqueue?.();
797 clearThreadComposerError(threadKey);
798 const enqueuePromise = enqueueThreadOutboxMessage({
799 environmentId: selectedThreadShell.environmentId,
800 threadId: selectedThreadShell.id,
801 messageId,
802 commandId: CommandId.make(metadata.commandId),
803 text,
804 attachments,
805 context: draft.context,
806 modelSelection,
807 runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
808 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
809 ...(compactBeforeSend
810 ? { compactBeforeSend, dispatchMode: "queue" as const }
811 : followUpDispatchMode === null
812 ? {}
813 : { dispatchMode: followUpDispatchMode }),
814 ...(freshContext ? { freshContext: true } : {}),
815 createdAt: metadata.createdAt,
816 });
817 clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
818 if (freshContext) setFreshSessionPending(threadKey, false);
819 enqueuePromise.then(
820 () => {
821 setKeepFullHistory(threadKey, false);
822 scheduleUnusedComposerAttachmentCleanup(attachments);
823 },
824 (error: unknown) => {
825 // Restore with uncapped append; capped merge could drop attachments added during the failed write.
826 void mergeComposerDraftContent(threadKey, {
827 text,
828 context: draft.context,
829 attachments: [],
830 });
831 appendComposerDraftAttachments(threadKey, attachments, { allowOverflow: true });
832 if (freshContext) setFreshSessionPending(threadKey, true);
833 setThreadComposerError(
834 threadKey,
835 error instanceof Error ? error.message : "Failed to save the queued message.",
836 );
837 },
838 );
839 return messageId;
840 };
841​
842 // Side chats do not nest or start from subagents, and need a server that forks them.
843 const sideChatUnavailableReason = (() => {
844 const serverConfig = selectedEnvironmentRuntime?.serverConfig;
845 if (selectedThreadShell?.lineage.sideChat === true)
846 return "Side chats cannot start side chats.";
847 if (selectedThreadShell?.lineage.relationshipToParent === "subagent") {
848 return "Subagent threads cannot start side chats.";
849 }
850 if (!selectedThreadShell || !serverConfig) {
851 return "Side chats are not ready yet. Try again in a moment.";
852 }
853 if (serverConfig.environment.capabilities.sideChats !== true) {
854 return "Update this environment's T3 Code server to use side chats.";
855 }
856 if (selectedThreadCreation !== null) return "Side chats start after the first message.";
857 if (
858 orchestrationV2WorktreePending(
859 selectedThreadShell.worktreePath ?? null,
860 selectedThreadProjection?.projection.runs ?? [],
861 )
862 ) {
863 return "Available once the thread's worktree is set up.";
864 }
865 return null;
866 })();
867​
868 const onChangeDraftMessage = (value: string) => {
869 if (!selectedThreadShell) {
870 return;
871 }
872​
873 const threadKey = activeComposerDraftKey(selectedThreadShell);
874 setComposerDraftText(threadKey, value);
875 };
876​
877 const { onPickDraftMedia, onPickDraftFiles, onNativePasteImages, onNativePasteText } =
878 useComposerAttachmentActions({
879 draftKey: selectedThreadShell ? activeComposerDraftKey(selectedThreadShell) : null,
880 serverConfig: selectedEnvironmentRuntime?.serverConfig,
881 });
882​
883 const onRemoveDraftImage = (imageId: string) => {
884 if (!selectedThreadShell) {
885 return;
886 }
887​
888 const threadKey = activeComposerDraftKey(selectedThreadShell);
889 removeComposerDraftAttachment(threadKey, imageId);
890 };
891​
892 return {
893 feedbackSubmissions,
894 dismissFeedback,
895 selectedThreadFeed,
896 selectedThreadActivityRun,
897 selectedThreadAnnouncedRun,
898 selectedThreadDetailBehindShell,
899 selectedThreadQueueCount,
900 selectedThreadQueuedMessages,
901 dispatchingQueuedMessageId,
902 activeWorkStartedAt,
903 runlessWorkActive,
904 extensionStatuses: deriveProviderExtensionStatuses(
905 selectedThreadProjection?.projection ?? null,
906 ),
907 providerSubagentStatus,
908 isCompacting,
909 compactBeforeSend:
910 compactTokens === null || selectedThreadKey === null
911 ? null
912 : {
913 tokens: compactTokens,
914 keepFullHistory,
915 toggleKeepFullHistory: () => setKeepFullHistory(selectedThreadKey, !keepFullHistory),
916 },
917 composerDraftKey,
918 followUpBehavior,
919 canSteerActiveTurn,
920 queueHeld,
921 resumableRunId,
922 queuedRunEdit,
923 isSavingQueuedEdit,
924 cancelQueuedRunEdit,
925 onRemoveQueuedEditAttachment,
926 modelSelection,
927 pendingHandoff,
928 canSwitchThreadProvider,
929 runtimeMode,
930 interactionMode,
931 activeThreadBusy,
932 interruptibleRunId,
933 onChangeDraftMessage,
934 onPickDraftMedia,
935 onPickDraftFiles,
936 onNativePasteImages,
937 onNativePasteText,
938 onRemoveDraftImage,
939 onSendMessage,
940 sideChatUnavailableReason,
941 };