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 if (
338 selectedThreadVisibleTurnItems.some(
339 ({ item }) =>
340 item.runId === activeRunId && item.type === "compaction" && item.status === "running",
341 )
342 ) {
343 return true;
344 }
345 const compactMessage = selectedThreadVisibleTurnItems.findLast(
346 ({ item }) =>
347 item.runId === activeRunId &&
348 item.type === "user_message" &&
349 item.text.trim().toLowerCase() === "/compact" &&
350 item.attachments.length === 0,
351 );
352 if (!compactMessage) return false;
353 return !selectedThreadVisibleTurnItems.some(
354 ({ item }) =>
355 item.runId === activeRunId &&
356 item.type === "compaction" &&
357 (item.status === "completed" ||
358 item.status === "failed" ||
359 item.status === "interrupted" ||
360 item.status === "cancelled"),
361 );
362 })();
363 // A compacting turn cannot take steering input, so follow-ups queue meanwhile.
364 const canSteerActiveTurn = queueWorkflow?.canPromoteToSteer === true && !isCompacting;
365 // A stop or a restart holds the queue, completion wakes included, until it
366 // is resumed; the queue sheet lists only the user's own messages.
367 const queueHeld = queueWorkflow?.isHeld === true;
368
369 const runlessWorkStartedAt = selectedThreadProjection
370 ? deriveRunlessWorkStartedAt(selectedThreadProjection.projection)
371 : null;
372 const activeWorkStartedAt = (() => {
373 if (!selectedThreadShell) {
374 return null;
375 }
376 return (
377 resolveThreadWorkingStartedAt({
378 latestRun: selectedThreadActivityRun,
379 runtime: selectedThreadRuntime,
380 }) ?? runlessWorkStartedAt
381 );
382 })();
383 const runlessWorkActive = runlessWorkStartedAt !== null;
384
385 const providerSubagentStatus = selectedThreadProjection
386 ? deriveProviderSubagentStatus(selectedThreadProjection.projection)
387 : null;
388
389 const selectedThreadRuns = selectedThreadProjection?.projection.runs;
390 const editedRunId = queuedRunEdit?.runId ?? null;
391 useEffect(() => {
392 if (selectedThreadKey === null || editedRunId === null || selectedThreadRuns === undefined) {
393 return;
394 }
395 if (savingQueuedEditRef.current) return;
396 const stillQueued = selectedThreadRuns.some(
397 (run) => run.id === editedRunId && run.status === "queued",
398 );
399 if (stillQueued) return;
400 const editDraftKey = queuedEditDraftKey(selectedThreadKey, editedRunId);
401 const editDraft = getComposerDraftSnapshot(editDraftKey);
402 const threadDraft = getComposerDraftSnapshot(selectedThreadKey);
403 const keepable =
404 editDraft.text.trim().length > 0 &&
405 threadDraft.text.trim().length === 0 &&
406 threadDraft.attachments.length === 0;
407 if (keepable) {
408 void mergeComposerDraftContent(selectedThreadKey, {
409 text: editDraft.text,
410 attachments: editDraft.attachments,
411 ...(editDraft.context ? { context: editDraft.context } : {}),
412 });
413 }
414 endQueuedRunEdit(selectedThreadKey, { deferAttachmentCleanup: keepable });
415 setThreadComposerError(
416 selectedThreadKey,
417 keepable
418 ? "That message already started. Your edit is back in the composer."
419 : "That message already started, so the edit was discarded.",
420 );
421 }, [editedRunId, selectedThreadKey, selectedThreadRuns]);
422
423 const activeThreadBusy = threadRuntimeIsActive(selectedThreadRuntime);
424 const interruptibleRunId = threadRuntimeHasInterruptibleRun(selectedThreadRuntime)
425 ? (selectedThreadRuntime?.activeRunId ?? null)
426 : null;
427
428 const cancelQueuedRunEdit = () => {
429 if (selectedThreadKey === null || savingQueuedEditRef.current) return;
430 endQueuedRunEdit(selectedThreadKey);
431 };
432
433 const onRemoveQueuedEditAttachment = (attachmentId: string) => {
434 if (selectedThreadKey === null) return;
435 removeQueuedRunEditAttachment(selectedThreadKey, attachmentId);
436 };
437
438 const saveQueuedRunEdit = async () => {
439 const thread = selectedThreadShell;
440 if (!thread || savingQueuedEditRef.current) return;
441 const threadKey = scopedThreadKey(thread.environmentId, thread.id);
442 const edit = getQueuedRunEdit(threadKey);
443 if (edit === null) return;
444 const draft = getComposerDraftSnapshot(queuedEditDraftKey(threadKey, edit.runId));
445 const text = draft.text.trim();
446 if (text.length === 0) {
447 // The server rejects an empty queued message, attachments or not.
448 Dialog.alert("Add a message", "A queued message cannot be left empty.");
449 return;
450 }
451 if (
452 edit.existingAttachments.length + draft.attachments.length >
453 PROVIDER_SEND_TURN_MAX_ATTACHMENTS
454 ) {
455 Dialog.alert(
456 "Too many attachments",
457 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
458 );
459 return;
460 }
461 savingQueuedEditRef.current = true;
462 setIsSavingQueuedEdit(true);
463 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
464 const prepared = await settlePromise(() =>
465 prepareTurnAttachments({
466 environmentId: thread.environmentId,
467 attachments: draft.attachments,
468 supportsImageUploads: capabilities?.attachmentUploads === true,
469 }),
470 );
471 if (AsyncResult.isFailure(prepared)) {
472 savingQueuedEditRef.current = false;
473 setIsSavingQueuedEdit(false);
474 const error = squashAtomCommandFailure(prepared);
475 Dialog.alert(
476 "Could not save the queued message",
477 error instanceof Error ? error.message : "Your edit is still in the composer.",
478 );
479 return;
480 }
481 if (prepared.value.status !== "ready") {
482 savingQueuedEditRef.current = false;
483 setIsSavingQueuedEdit(false);
484 return;
485 }
486 const payload = resolveQueuedEditPayload({
487 edit,
488 draftContext: draft.context,
489 draftAttachments: draft.attachments,
490 uploaded: prepared.value.attachments,
491 });
492 const result = await editQueuedRun({
493 environmentId: thread.environmentId,
494 input: {
495 threadId: thread.id,
496 runId: edit.runId,
497 text,
498 edit: {
499 messageId: edit.messageId,
500 attachments: payload.attachments,
501 ...(payload.context ? { context: payload.context } : {}),
502 },
503 },
504 });
505 savingQueuedEditRef.current = false;
506 setIsSavingQueuedEdit(false);
507 if (result._tag !== "Success") {
508 Dialog.alert(
509 "Could not save the queued message",
510 "It may have already started. Your edit is still in the composer.",
511 );
512 return;
513 }
514 endQueuedRunEdit(threadKey, { deferAttachmentCleanup: true });
515 scheduleUnusedComposerAttachmentCleanup(draft.attachments);
516 };
517
518 const onSendMessage = async (followUpOverride?: ActiveTurnComposerAction) => {
519 if (
520 selectedThreadShell &&
521 selectedEnvironmentRuntime?.connectionState === "connected" &&
522 !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
523 )
524 return null;
525 if (!selectedThreadShell) {
526 return null;
527 }
528 // The server has not created this thread yet. Queuing a follow-up against
529 // its id would strand the message: if the creation is rejected the thread
530 // never appears and the drain drops the orphan. The composer disables its
531 if (selectedThreadCreation !== null) {
532 return null;
533 }
534
535 const editKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
536 if (getQueuedRunEdit(editKey) !== null) {
537 await saveQueuedRunEdit();
538 return null;
539 }
540
541 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
542 const draft = getComposerDraftSnapshot(threadKey);
543 if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
544 const thread = selectedThreadShell;
545 const text = draft.text.trim();
546 const attachments = draft.attachments;
547 if (
548 composerAttachmentUploadBlockReason({
549 environmentId: selectedThreadShell.environmentId,
550 attachments,
551 connected: selectedEnvironmentRuntime?.connectionState === "connected",
552 serverConfig: selectedEnvironmentRuntime?.serverConfig ?? null,
553 states: appAtomRegistry.get(composerAttachmentUploadsAtom),
554 }) !== null
555 )
556 return null;
557 if (text.length === 0 && attachments.length === 0) {
558 return null;
559 }
560 // A send-failure restore appends with allowOverflow so it never drops the
561 // user's files, which can leave the draft over the cap. Sending it anyway
562 // would enqueue a message that outbox recovery rejects forever, so block
563 // here until the user removes attachments.
564 if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
565 Dialog.alert(
566 "Too many attachments",
567 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
568 );
569 return null;
570 }
571
572 const contextBlockReason = composerContextSendBlockReason(draft.context);
573 if (contextBlockReason) {
574 Dialog.alert("Too much context", contextBlockReason);
575 return null;
576 }
577
578 const modelSelection = draft.modelSelection ?? thread.modelSelection;
579 const serverConfig = selectedEnvironmentRuntime?.serverConfig;
580 if (
581 selectedEnvironmentRuntime?.connectionState === "connected" &&
582 isModelSelectionUnavailable(serverConfig, modelSelection, thread.projectId)
583 ) {
584 const { title, detail } = describeUnavailableModelSelection(
585 serverConfig,
586 modelSelection,
587 thread.projectId,
588 );
589 Dialog.alert(title, detail);
590 return null;
591 }
592 const provider = serverConfig?.providers.find(
593 (entry) => entry.instanceId === modelSelection.instanceId,
594 );
595 const feedbackCommand =
596 attachments.length === 0 && provider?.driver === "codex"
597 ? parseCodexFeedbackCommand(text)
598 : null;
599 if (feedbackCommand) {
600 if (!readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope))
601 return null;
602 if (thread.activeProviderThreadId === null) {
603 Dialog.alert("Start a Codex thread first", "Send a message before you submit feedback.");
604 return null;
605 }
606 const metadata = makeQueuedMessageMetadata();
607 await submitCodexFeedback({
608 submission: {
609 id: MessageId.make(metadata.messageId),
610 command: text,
611 createdAt: metadata.createdAt,
612 },
613 clearDraft: () => clearComposerDraftContent(threadKey),
614 onUpdate: (submission) => {
615 setFeedbackSubmissionsByThreadKey((current) => {
616 const existing = current[threadKey] ?? [];
617 const found = existing.some((entry) => entry.id === submission.id);
618 return {
619 ...current,
620 [threadKey]: found
621 ? existing.map((entry) => (entry.id === submission.id ? submission : entry))
622 : [...existing, submission],
623 };
624 });
625 },
626 upload: () =>
627 uploadThreadFeedback({
628 environmentId: thread.environmentId,
629 input: { threadId: thread.id, ...feedbackCommand },
630 }),
631 });
632 return null;
633 }
634
635 // Resolved here rather than at drain time: the outbox can deliver minutes
636 // later, and the choice belongs to the moment the user pressed send.
637 // Steering travels as "auto" so a turn that ends in the meantime degrades
638 // to a queued run on the server instead of failing the delivery and
639 // bouncing the message back into the draft.
640 const followUpAction = resolveComposerDispatchMode({
641 running: activeThreadBusy && canSteerActiveTurn,
642 alternateModifier: followUpOverride !== undefined && followUpOverride !== followUpBehavior,
643 activeTurnDefault: followUpBehavior,
644 });
645 const setupRunning = [selectedThreadActivityRun?.status, selectedThreadRuntime?.status].some(
646 (status) => status === "preparing" || status === "starting",
647 );
648 const followUpDispatchMode = setupRunning
649 ? "queue"
650 : followUpAction === "auto"
651 ? null
652 : followUpAction === "queue"
653 ? "queue"
654 : "auto";
655
656 const metadata = makeQueuedMessageMetadata();
657 const messageId = MessageId.make(metadata.messageId);
658 clearThreadComposerError(threadKey);
659 const enqueuePromise = enqueueThreadOutboxMessage({
660 environmentId: selectedThreadShell.environmentId,
661 threadId: selectedThreadShell.id,
662 messageId,
663 commandId: CommandId.make(metadata.commandId),
664 text,
665 attachments,
666 context: draft.context,
667 modelSelection,
668 runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
669 interactionMode: resolveProviderInteractionMode(
670 provider,
671 draft.interactionMode ?? thread.interactionMode,
672 ),
673 ...(followUpDispatchMode === null ? {} : { dispatchMode: followUpDispatchMode }),
674 createdAt: metadata.createdAt,
675 });
676 clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
677 enqueuePromise.then(
678 () => scheduleUnusedComposerAttachmentCleanup(attachments),
679 (error: unknown) => {
680 // Restore text via merge (idempotent) but attachments via the uncapped
681 // append: the merge path slots existing attachments first and truncates
682 // at the send limit, which would silently drop this message's images if
683 // the user attached new ones while the write was in flight.
684 void mergeComposerDraftContent(threadKey, {
685 text,
686 context: draft.context,
687 attachments: [],
688 });
689 appendComposerDraftAttachments(threadKey, attachments, { allowOverflow: true });
690 setThreadComposerError(
691 threadKey,
692 error instanceof Error ? error.message : "Failed to save the queued message.",
693 );
694 },
695 );
696 return messageId;
697 };
698
699 const onChangeDraftMessage = (value: string) => {
700 if (!selectedThreadShell) {
701 return;
702 }
703
704 const threadKey = activeComposerDraftKey(selectedThreadShell);
705 setComposerDraftText(threadKey, value);
706 };
707
708 const onPickDraftMedia = async () => {
709 if (!selectedThreadShell) {
710 return;
711 }
712
713 const threadKey = activeComposerDraftKey(selectedThreadShell);
714 const insertion = captureComposerDraftInsertion(threadKey);
715 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
716 const result = await pickComposerMedia({
717 existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
718 maxVideoBytes:
719 capabilities?.attachmentUploads === true
720 ? capabilities.fileAttachments?.maxUploadBytes
721 : undefined,
722 });
723 const rejectedCount = appendComposerDraftAttachments(threadKey, result.attachments, {
724 appendReference: true,
725 insertion,
726 });
727 const problems = [
728 ...(result.error ? [result.error] : []),
729 ...(rejectedCount > 0
730 ? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`]
731 : []),
732 ];
733 if (problems.length > 0) {
734 Dialog.alert("Could not attach photo or video", problems.join("\n\n"));
735 }
736 };
737
738 const onPickDraftFiles = async () => {
739 if (!selectedThreadShell) {
740 return;
741 }
742 const maxBytes =
743 selectedEnvironmentRuntime?.serverConfig?.environment.capabilities.fileAttachments
744 ?.maxUploadBytes;
745 if (maxBytes === undefined) {
746 Dialog.alert("Could not attach file", "This server does not support file attachments.");
747 return;
748 }
749
750 const threadKey = activeComposerDraftKey(selectedThreadShell);
751 const insertion = captureComposerDraftInsertion(threadKey);
752 const result = await pickComposerFiles({
753 existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
754 maxBytes,
755 });
756 const rejectedCount = appendComposerDraftAttachments(threadKey, result.files, {
757 appendReference: true,
758 insertion,
759 });
760 const problems = [
761 ...(result.error ? [result.error] : []),
762 ...(rejectedCount > 0
763 ? [`You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`]
764 : []),
765 ];
766 if (problems.length > 0) {
767 Dialog.alert("Could not attach file", problems.join("\n\n"));
768 }
769 };
770
771 const onPasteIntoDraft = async () => {
772 if (!selectedThreadShell) {
773 return;
774 }
775
776 const threadKey = activeComposerDraftKey(selectedThreadShell);
777 const insertion = captureComposerDraftInsertion(threadKey);
778 const result = await pasteComposerClipboard({
779 existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
780 });
781 const rejectedPasteCount = appendComposerDraftAttachments(threadKey, result.images, {
782 appendReference: true,
783 insertion,
784 });
785 if (result.text) {
786 const currentDraft = getComposerDraftSnapshot(threadKey);
787 const currentAttachments = currentDraft.attachments;
788 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
789 const advertisedMax =
790 capabilities?.attachmentUploads === true
791 ? capabilities.fileAttachments?.maxUploadBytes
792 : undefined;
793 const maxBytes =
794 advertisedMax === undefined ? null : clampFileAttachmentUploadBytes(advertisedMax);
795 const wouldExceedInputLimit =
796 currentDraft.text.length -
797 (currentDraft.text === insertion.text
798 ? Math.max(0, insertion.end - insertion.start)
799 : 0) +
800 result.text.length >
801 PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
802 const shouldFold =
803 pastedTextDisposition({
804 text: result.text,
805 wouldExceedInputLimit,
806 canAttach: true,
807 }) === "attachment";
808 const canAttach =
809 maxBytes !== null &&
810 countComposerDraftAttachmentsAfterSelection(threadKey, insertion) <
811 PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
812 new TextEncoder().encode(result.text).byteLength <= maxBytes;
813 if (shouldFold && canAttach && maxBytes !== null) {
814 try {
815 const attachment = await createPastedTextComposerAttachment({
816 text: result.text,
817 name: reservePastedTextFileName(
818 threadKey,
819 currentAttachments.map((item) => item.name),
820 ),
821 maxBytes,
822 });
823 if (
824 appendComposerDraftAttachments(threadKey, [attachment], {
825 appendReference: true,
826 insertion,
827 }) > 0
828 ) {
829 await removePersistedComposerAttachmentFile(attachment.fileUri);
830 setPendingConnectionError(
831 `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
832 );
833 }
834 } catch (error) {
835 setPendingConnectionError(
836 error instanceof Error ? error.message : "Could not attach pasted text.",
837 );
838 }
839 } else if (shouldFold && !wouldExceedInputLimit) {
840 insertComposerDraftText(threadKey, result.text, insertion);
841 } else if (shouldFold) {
842 setPendingConnectionError(
843 wouldExceedInputLimit
844 ? "Pasted text is too large for this message. Remove some text or an attachment, then paste again."
845 : "Could not attach pasted text. Remove an attachment or use a smaller paste, then try again.",
846 );
847 } else {
848 insertComposerDraftText(threadKey, result.text, insertion);
849 }
850 }
851 if (result.error) {
852 setPendingConnectionError(result.error);
853 } else if (rejectedPasteCount > 0) {
854 setPendingConnectionError(
855 `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
856 );
857 }
858 };
859
860 const onNativePasteImages = async (uris: ReadonlyArray<string>) => {
861 if (!selectedThreadShell || uris.length === 0) {
862 return;
863 }
864
865 const threadKey = activeComposerDraftKey(selectedThreadShell);
866 const insertion = captureComposerDraftInsertion(threadKey);
867 try {
868 const images = await convertPastedImagesToAttachments({
869 uris,
870 existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
871 });
872 if (images.length > 0) {
873 appendComposerDraftAttachments(threadKey, images, { appendReference: true, insertion });
874 }
875 } catch (error) {
876 console.error("[native paste] error converting images", {
877 environmentId: selectedThreadShell.environmentId,
878 threadId: selectedThreadShell.id,
879 uriCount: uris.length,
880 ...safeErrorLogAttributes(error),
881 });
882 }
883 };
884
885 const onNativePasteText = async (paste: ComposerTextPaste) => {
886 if (!selectedThreadShell) return;
887 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
888 const advertisedMax =
889 capabilities?.attachmentUploads === true
890 ? capabilities.fileAttachments?.maxUploadBytes
891 : undefined;
892 if (advertisedMax === undefined) return;
893
894 const threadKey = activeComposerDraftKey(selectedThreadShell);
895 const insertion = { text: paste.value, ...paste.selection };
896 const currentAttachments = getComposerDraftSnapshot(threadKey).attachments;
897 try {
898 const attachment = await createPastedTextComposerAttachment({
899 text: paste.text,
900 name: reservePastedTextFileName(
901 threadKey,
902 currentAttachments.map((item) => item.name),
903 ),
904 maxBytes: clampFileAttachmentUploadBytes(advertisedMax),
905 });
906 const rejectedCount = appendComposerDraftAttachments(threadKey, [attachment], {
907 appendReference: true,
908 insertion,
909 });
910 if (rejectedCount > 0) {
911 await removePersistedComposerAttachmentFile(attachment.fileUri);
912 setPendingConnectionError(
913 `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
914 );
915 }
916 } catch (error) {
917 setPendingConnectionError(
918 error instanceof Error ? error.message : "Could not attach pasted text.",
919 );
920 }
921 };
922
923 const onRemoveDraftImage = (imageId: string) => {
924 if (!selectedThreadShell) {
925 return;
926 }
927
928 const threadKey = activeComposerDraftKey(selectedThreadShell);
929 removeComposerDraftAttachment(threadKey, imageId);
930 };
931
932 const onUpdateModelSelection = (value: ModelSelection) => {
933 if (!selectedThreadKey) {
934 return;
935 }
936 const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
937 (candidate) => candidate.instanceId === value.instanceId,
938 );
939 updateComposerDraftSettings(selectedThreadKey, {
940 modelSelection: value,
941 ...(provider?.showInteractionModeToggle === false
942 ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
943 : {}),
944 });
945 };
946
947 const onUpdateRuntimeMode = (value: RuntimeMode) => {
948 if (!selectedThreadKey) {
949 return;
950 }
951 updateComposerDraftSettings(selectedThreadKey, { runtimeMode: value });
952 };
953
954 const onUpdateInteractionMode = (value: ProviderInteractionMode) => {
955 if (!selectedThreadKey) {
956 return;
957 }
958 const modelSelection =
959 getComposerDraftSnapshot(selectedThreadKey).modelSelection ?? selectedThread?.modelSelection;
960 const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
961 (candidate) => candidate.instanceId === modelSelection?.instanceId,
962 );
963 updateComposerDraftSettings(selectedThreadKey, {
964 interactionMode: resolveProviderInteractionMode(provider, value),
965 });
966 };
967
968 return {
969 feedbackSubmissions,
970 dismissFeedback,
971 selectedThreadFeed,
972 selectedThreadActivityRun,
973 selectedThreadQueueCount,
974 selectedThreadQueuedMessages,
975 dispatchingQueuedMessageId,
976 activeWorkStartedAt,
977 runlessWorkActive,
978 providerSubagentStatus,
979 isCompacting,
980 composerDraftKey,
981 followUpBehavior,
982 canSteerActiveTurn,
983 queueHeld,
984 queuedRunEdit,
985 isSavingQueuedEdit,
986 cancelQueuedRunEdit,
987 onRemoveQueuedEditAttachment,
988 modelSelection,
989 pendingHandoff,
990 canSwitchThreadProvider,
991 runtimeMode,
992 interactionMode,
993 activeThreadBusy,
994 interruptibleRunId,
995 onChangeDraftMessage,
996 onPickDraftMedia,
997 onPickDraftFiles,
998 onPasteIntoDraft,
999 onNativePasteImages,
1000 onNativePasteText,
1001 onRemoveDraftImage,
1002 onSendMessage,
1003 onUpdateModelSelection,
1004 onUpdateRuntimeMode,
1005 onUpdateInteractionMode,
1006 };
1007}