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

use-thread-composer-state.ts

1,020 lines38.2 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 (followUpOverride?: ActiveTurnComposerAction) => {
532 if (
533 selectedThreadShell &&
534 selectedEnvironmentRuntime?.connectionState === "connected" &&
535 !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
536 )
537 return null;
538 if (!selectedThreadShell) {
539 return null;
540 }
541 // The server has not created this thread yet. Queuing a follow-up against
542 // its id would strand the message: if the creation is rejected the thread
543 // never appears and the drain drops the orphan. The composer disables its
544 if (selectedThreadCreation !== null) {
545 return null;
546 }
547​
548 const editKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
549 if (getQueuedRunEdit(editKey) !== null) {
550 await saveQueuedRunEdit();
551 return null;
552 }
553​
554 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
555 const draft = getComposerDraftSnapshot(threadKey);
556 if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
557 const thread = selectedThreadShell;
558 const text = draft.text.trim();
559 const attachments = draft.attachments;
560 if (
561 composerAttachmentUploadBlockReason({
562 environmentId: selectedThreadShell.environmentId,
563 attachments,
564 connected: selectedEnvironmentRuntime?.connectionState === "connected",
565 serverConfig: selectedEnvironmentRuntime?.serverConfig ?? null,
566 states: appAtomRegistry.get(composerAttachmentUploadsAtom),
567 }) !== null
568 )
569 return null;
570 if (text.length === 0 && attachments.length === 0) {
571 return null;
572 }
573 // A send-failure restore appends with allowOverflow so it never drops the
574 // user's files, which can leave the draft over the cap. Sending it anyway
575 // would enqueue a message that outbox recovery rejects forever, so block
576 // here until the user removes attachments.
577 if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
578 Dialog.alert(
579 "Too many attachments",
580 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
581 );
582 return null;
583 }
584​
585 const contextBlockReason = composerContextSendBlockReason(draft.context);
586 if (contextBlockReason) {
587 Dialog.alert("Too much context", contextBlockReason);
588 return null;
589 }
590​
591 const modelSelection = draft.modelSelection ?? thread.modelSelection;
592 const serverConfig = selectedEnvironmentRuntime?.serverConfig;
593 if (
594 selectedEnvironmentRuntime?.connectionState === "connected" &&
595 isModelSelectionUnavailable(serverConfig, modelSelection, thread.projectId)
596 ) {
597 const { title, detail } = describeUnavailableModelSelection(
598 serverConfig,
599 modelSelection,
600 thread.projectId,
601 );
602 Dialog.alert(title, detail);
603 return null;
604 }
605 const provider = serverConfig?.providers.find(
606 (entry) => entry.instanceId === modelSelection.instanceId,
607 );
608 const feedbackCommand =
609 attachments.length === 0 && provider?.driver === "codex"
610 ? parseCodexFeedbackCommand(text)
611 : null;
612 if (feedbackCommand) {
613 if (!readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope))
614 return null;
615 if (thread.activeProviderThreadId === null) {
616 Dialog.alert("Start a Codex thread first", "Send a message before you submit feedback.");
617 return null;
618 }
619 const metadata = makeQueuedMessageMetadata();
620 await submitCodexFeedback({
621 submission: {
622 id: MessageId.make(metadata.messageId),
623 command: text,
624 createdAt: metadata.createdAt,
625 },
626 clearDraft: () => clearComposerDraftContent(threadKey),
627 onUpdate: (submission) => {
628 setFeedbackSubmissionsByThreadKey((current) => {
629 const existing = current[threadKey] ?? [];
630 const found = existing.some((entry) => entry.id === submission.id);
631 return {
632 ...current,
633 [threadKey]: found
634 ? existing.map((entry) => (entry.id === submission.id ? submission : entry))
635 : [...existing, submission],
636 };
637 });
638 },
639 upload: () =>
640 uploadThreadFeedback({
641 environmentId: thread.environmentId,
642 input: { threadId: thread.id, ...feedbackCommand },
643 }),
644 });
645 return null;
646 }
647​
648 // Resolved here rather than at drain time: the outbox can deliver minutes
649 // later, and the choice belongs to the moment the user pressed send.
650 // Steering travels as "auto" so a turn that ends in the meantime degrades
651 // to a queued run on the server instead of failing the delivery and
652 // bouncing the message back into the draft.
653 const followUpAction = resolveComposerDispatchMode({
654 running: activeThreadBusy && canSteerActiveTurn,
655 alternateModifier: followUpOverride !== undefined && followUpOverride !== followUpBehavior,
656 activeTurnDefault: followUpBehavior,
657 });
658 const setupRunning = [selectedThreadActivityRun?.status, selectedThreadRuntime?.status].some(
659 (status) => status === "preparing" || status === "starting",
660 );
661 const followUpDispatchMode = setupRunning
662 ? "queue"
663 : followUpAction === "auto"
664 ? null
665 : followUpAction === "queue"
666 ? "queue"
667 : "auto";
668​
669 const metadata = makeQueuedMessageMetadata();
670 const messageId = MessageId.make(metadata.messageId);
671 clearThreadComposerError(threadKey);
672 const enqueuePromise = enqueueThreadOutboxMessage({
673 environmentId: selectedThreadShell.environmentId,
674 threadId: selectedThreadShell.id,
675 messageId,
676 commandId: CommandId.make(metadata.commandId),
677 text,
678 attachments,
679 context: draft.context,
680 modelSelection,
681 runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
682 interactionMode: resolveProviderInteractionMode(
683 provider,
684 draft.interactionMode ?? thread.interactionMode,
685 ),
686 ...(followUpDispatchMode === null ? {} : { dispatchMode: followUpDispatchMode }),
687 createdAt: metadata.createdAt,
688 });
689 clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
690 enqueuePromise.then(
691 () => scheduleUnusedComposerAttachmentCleanup(attachments),
692 (error: unknown) => {
693 // Restore text via merge (idempotent) but attachments via the uncapped
694 // append: the merge path slots existing attachments first and truncates
695 // at the send limit, which would silently drop this message's images if
696 // the user attached new ones while the write was in flight.
697 void mergeComposerDraftContent(threadKey, {
698 text,
699 context: draft.context,
700 attachments: [],
701 });
702 appendComposerDraftAttachments(threadKey, attachments, { allowOverflow: true });
703 setThreadComposerError(
704 threadKey,
705 error instanceof Error ? error.message : "Failed to save the queued message.",
706 );
707 },
708 );
709 return messageId;
710 };
711​
712 const onChangeDraftMessage = (value: string) => {
713 if (!selectedThreadShell) {
714 return;
715 }
716​
717 const threadKey = activeComposerDraftKey(selectedThreadShell);
718 setComposerDraftText(threadKey, value);
719 };
720​
721 const onPickDraftMedia = async () => {
722 if (!selectedThreadShell) {
723 return;
724 }
725​
726 const threadKey = activeComposerDraftKey(selectedThreadShell);
727 const insertion = captureComposerDraftInsertion(threadKey);
728 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
729 const result = await pickComposerMedia({
730 existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
731 maxVideoBytes:
732 capabilities?.attachmentUploads === true
733 ? capabilities.fileAttachments?.maxUploadBytes
734 : undefined,
735 });
736 const rejectedCount = appendComposerDraftAttachments(threadKey, result.attachments, {
737 appendReference: true,
738 insertion,
739 });
740 const problems = [
741 ...(result.error ? [result.error] : []),
742 ...(rejectedCount > 0
743 ? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`]
744 : []),
745 ];
746 if (problems.length > 0) {
747 Dialog.alert("Could not attach photo or video", problems.join("\n\n"));
748 }
749 };
750​
751 const onPickDraftFiles = async () => {
752 if (!selectedThreadShell) {
753 return;
754 }
755 const maxBytes =
756 selectedEnvironmentRuntime?.serverConfig?.environment.capabilities.fileAttachments
757 ?.maxUploadBytes;
758 if (maxBytes === undefined) {
759 Dialog.alert("Could not attach file", "This server does not support file attachments.");
760 return;
761 }
762​
763 const threadKey = activeComposerDraftKey(selectedThreadShell);
764 const insertion = captureComposerDraftInsertion(threadKey);
765 const result = await pickComposerFiles({
766 existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
767 maxBytes,
768 });
769 const rejectedCount = appendComposerDraftAttachments(threadKey, result.files, {
770 appendReference: true,
771 insertion,
772 });
773 const problems = [
774 ...(result.error ? [result.error] : []),
775 ...(rejectedCount > 0
776 ? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`]
777 : []),
778 ];
779 if (problems.length > 0) {
780 Dialog.alert("Could not attach file", problems.join("\n\n"));
781 }
782 };
783​
784 const onPasteIntoDraft = async () => {
785 if (!selectedThreadShell) {
786 return;
787 }
788​
789 const threadKey = activeComposerDraftKey(selectedThreadShell);
790 const insertion = captureComposerDraftInsertion(threadKey);
791 const result = await pasteComposerClipboard({
792 existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
793 });
794 const rejectedPasteCount = appendComposerDraftAttachments(threadKey, result.images, {
795 appendReference: true,
796 insertion,
797 });
798 if (result.text) {
799 const currentDraft = getComposerDraftSnapshot(threadKey);
800 const currentAttachments = currentDraft.attachments;
801 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
802 const advertisedMax =
803 capabilities?.attachmentUploads === true
804 ? capabilities.fileAttachments?.maxUploadBytes
805 : undefined;
806 const maxBytes =
807 advertisedMax === undefined ? null : clampFileAttachmentUploadBytes(advertisedMax);
808 const wouldExceedInputLimit =
809 currentDraft.text.length -
810 (currentDraft.text === insertion.text
811 ? Math.max(0, insertion.end - insertion.start)
812 : 0) +
813 result.text.length >
814 PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
815 const shouldFold =
816 pastedTextDisposition({
817 text: result.text,
818 wouldExceedInputLimit,
819 canAttach: true,
820 }) === "attachment";
821 const canAttach =
822 maxBytes !== null &&
823 countComposerDraftAttachmentsAfterSelection(threadKey, insertion) <
824 PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
825 new TextEncoder().encode(result.text).byteLength <= maxBytes;
826 if (shouldFold && canAttach && maxBytes !== null) {
827 try {
828 const attachment = await createPastedTextComposerAttachment({
829 text: result.text,
830 name: reservePastedTextFileName(
831 threadKey,
832 currentAttachments.map((item) => item.name),
833 ),
834 maxBytes,
835 });
836 if (
837 appendComposerDraftAttachments(threadKey, [attachment], {
838 appendReference: true,
839 insertion,
840 }) > 0
841 ) {
842 await removePersistedComposerAttachmentFile(attachment.fileUri);
843 setPendingConnectionError(
844 `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
845 );
846 }
847 } catch (error) {
848 setPendingConnectionError(
849 error instanceof Error ? error.message : "Could not attach pasted text.",
850 );
851 }
852 } else if (shouldFold && !wouldExceedInputLimit) {
853 insertComposerDraftText(threadKey, result.text, insertion);
854 } else if (shouldFold) {
855 setPendingConnectionError(
856 wouldExceedInputLimit
857 ? "Pasted text is too large for this message. Remove some text or an attachment, then paste again."
858 : "Could not attach pasted text. Remove an attachment or use a smaller paste, then try again.",
859 );
860 } else {
861 insertComposerDraftText(threadKey, result.text, insertion);
862 }
863 }
864 if (result.error) {
865 setPendingConnectionError(result.error);
866 } else if (rejectedPasteCount > 0) {
867 setPendingConnectionError(
868 `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
869 );
870 }
871 };
872​
873 const onNativePasteImages = async (uris: ReadonlyArray<string>) => {
874 if (!selectedThreadShell || uris.length === 0) {
875 return;
876 }
877​
878 const threadKey = activeComposerDraftKey(selectedThreadShell);
879 const insertion = captureComposerDraftInsertion(threadKey);
880 try {
881 const images = await convertPastedImagesToAttachments({
882 uris,
883 existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
884 });
885 if (images.length > 0) {
886 appendComposerDraftAttachments(threadKey, images, { appendReference: true, insertion });
887 }
888 } catch (error) {
889 console.error("[native paste] error converting images", {
890 environmentId: selectedThreadShell.environmentId,
891 threadId: selectedThreadShell.id,
892 uriCount: uris.length,
893 ...safeErrorLogAttributes(error),
894 });
895 }
896 };
897​
898 const onNativePasteText = async (paste: ComposerTextPaste) => {
899 if (!selectedThreadShell) return;
900 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
901 const advertisedMax =
902 capabilities?.attachmentUploads === true
903 ? capabilities.fileAttachments?.maxUploadBytes
904 : undefined;
905 if (advertisedMax === undefined) return;
906​
907 const threadKey = activeComposerDraftKey(selectedThreadShell);
908 const insertion = { text: paste.value, ...paste.selection };
909 const currentAttachments = getComposerDraftSnapshot(threadKey).attachments;
910 try {
911 const attachment = await createPastedTextComposerAttachment({
912 text: paste.text,
913 name: reservePastedTextFileName(
914 threadKey,
915 currentAttachments.map((item) => item.name),
916 ),
917 maxBytes: clampFileAttachmentUploadBytes(advertisedMax),
918 });
919 const rejectedCount = appendComposerDraftAttachments(threadKey, [attachment], {
920 appendReference: true,
921 insertion,
922 });
923 if (rejectedCount > 0) {
924 await removePersistedComposerAttachmentFile(attachment.fileUri);
925 setPendingConnectionError(
926 `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
927 );
928 }
929 } catch (error) {
930 setPendingConnectionError(
931 error instanceof Error ? error.message : "Could not attach pasted text.",
932 );
933 }
934 };
935​
936 const onRemoveDraftImage = (imageId: string) => {
937 if (!selectedThreadShell) {
938 return;
939 }
940​
941 const threadKey = activeComposerDraftKey(selectedThreadShell);
942 removeComposerDraftAttachment(threadKey, imageId);
943 };
944​
945 const onUpdateModelSelection = (value: ModelSelection) => {
946 if (!selectedThreadKey) {
947 return;
948 }
949 const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
950 (candidate) => candidate.instanceId === value.instanceId,
951 );
952 updateComposerDraftSettings(selectedThreadKey, {
953 modelSelection: value,
954 ...(provider?.showInteractionModeToggle === false
955 ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
956 : {}),
957 });
958 };
959​
960 const onUpdateRuntimeMode = (value: RuntimeMode) => {
961 if (!selectedThreadKey) {
962 return;
963 }
964 updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
965 };
966​
967 const onUpdateInteractionMode = (value: ProviderInteractionMode) => {
968 if (!selectedThreadKey) {
969 return;
970 }
971 const modelSelection =
972 getComposerDraftSnapshot(selectedThreadKey).modelSelection ?? selectedThread?.modelSelection;
973 const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
974 (candidate) => candidate.instanceId === modelSelection?.instanceId,
975 );
976 updateComposerDraftSettings(selectedThreadKey, {
977 interactionMode: resolveProviderInteractionMode(provider, value),
978 });
979 };
980​
981 return {
982 feedbackSubmissions,
983 dismissFeedback,
984 selectedThreadFeed,
985 selectedThreadActivityRun,
986 selectedThreadQueueCount,
987 selectedThreadQueuedMessages,
988 dispatchingQueuedMessageId,
989 activeWorkStartedAt,
990 runlessWorkActive,
991 providerSubagentStatus,
992 isCompacting,
993 composerDraftKey,
994 followUpBehavior,
995 canSteerActiveTurn,
996 queueHeld,
997 queuedRunEdit,
998 isSavingQueuedEdit,
999 cancelQueuedRunEdit,
1000 onRemoveQueuedEditAttachment,
1001 modelSelection,
1002 pendingHandoff,
1003 canSwitchThreadProvider,
1004 runtimeMode,
1005 interactionMode,
1006 activeThreadBusy,
1007 interruptibleRunId,
1008 onChangeDraftMessage,
1009 onPickDraftMedia,
1010 onPickDraftFiles,
1011 onPasteIntoDraft,
1012 onNativePasteImages,
1013 onNativePasteText,
1014 onRemoveDraftImage,
1015 onSendMessage,
1016 onUpdateModelSelection,
1017 onUpdateRuntimeMode,
1018 onUpdateInteractionMode,
1019 };