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