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

use-thread-composer-state.ts

897 lines34.5 KB

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