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