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