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

use-thread-composer-state.ts

1,092 lines42.0 KB

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