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