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

use-thread-composer-state.ts

915 lines34.5 KB

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