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