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

use-thread-composer-state.ts

1,043 lines39.3 KB

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