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