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