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

use-thread-composer-state.ts

1,009 lines37.6 KB

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