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

use-thread-composer-state.ts

872 lines32.8 KB

1import { useComposerAttachmentActions } from "./use-composer-attachment-actions";
2import * as Dialog from "../components/ui/Dialog";
3import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
4import { readEnvironmentScope } from "./session";
5import { useAtomValue } from "@effect/atom-react";
6import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
7import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
8import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff";
9import {
10 deriveProviderSubagentStatus,
11 deriveRunlessWorkStartedAt,
12 deriveThreadActivityRun,
13 deriveThreadRuntime,
14 threadRuntimeHasInterruptibleRun,
15} from "@t3tools/client-runtime/state/thread-execution";
16import { useRef, useState } from "react";
17​
18import {
19 CommandId,
20 DEFAULT_PROVIDER_INTERACTION_MODE,
21 MessageId,
22 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
23 PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
24 type EnvironmentId,
25 type ModelSelection,
26 type ProviderInteractionMode,
27 type ServerProvider,
28 type ThreadId,
29} from "@t3tools/contracts";
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 createPastedTextComposerAttachment,
50 pasteComposerClipboard,
51 removePersistedComposerAttachmentFile,
52} from "../lib/composerImages";
53import type { DraftComposerImageAttachment } from "../lib/composerImages";
54import { scopedThreadKey } from "../lib/scopedEntities";
55import { buildThreadFeed, createThreadFeedCache } from "../lib/threadActivity";
56import { acknowledgedThreadMessagesAtom } from "./acknowledged-thread-messages";
57import {
58 appendPendingThreadMessages,
59 selectPendingAcknowledgedMessages,
60} 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 clearComposerDraft,
75 clearComposerDraftContent,
76 composerContextImportsAtom,
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 startQueuedRunEditSave,
104 useQueuedRunEdit,
105} from "./queued-run-edit";
106import { setPendingConnectionError } from "../state/use-remote-environment-registry";
107import { clearThreadComposerError, setThreadComposerError } from "./thread-composer-error";
108import {
109 useSelectedThreadProjection,
110 useSelectedThreadVisibleTurnItems,
111} from "../state/use-thread-detail";
112import { useThreadSelection } from "../state/use-thread-selection";
113import { enqueueThreadOutboxMessage } from "./thread-outbox";
114import { dispatchingQueuedMessageIdAtom, useThreadOutboxMessages } from "./use-thread-outbox";
115import { threadEnvironment } from "./threads";
116import { useAtomCommand } from "./use-atom-command";
117​
118const EMPTY_QUEUE_WORKFLOW_ATOM = Atom.make<null>(null).pipe(
119 Atom.withLabel("mobile-thread-queue-workflow:empty"),
120);
121const EMPTY_CHECKPOINT_SUMMARIES_ATOM = Atom.make<ReadonlyArray<ThreadCheckpointSummary>>([]);
122​
123export function appendReviewCommentToDraft(input: {
124 readonly environmentId: EnvironmentId;
125 readonly threadId: ThreadId;
126 readonly text: string;
127 readonly attachments?: ReadonlyArray<DraftComposerImageAttachment>;
128}): void {
129 const threadKey = scopedThreadKey(input.environmentId, input.threadId);
130 const upgraded = upgradeLegacyContextMessage(input.text);
131 if (
132 !insertComposerDraftContext(
133 threadKey,
134 reidentifyComposerContext(upgraded.text, upgraded.records, uuidv4),
135 )
136 ) {
137 Dialog.alert("Too many context items", "Remove some context from the draft and try again.");
138 return;
139 }
140 if (input.attachments && input.attachments.length > 0) {
141 const rejectedCount = appendComposerDraftAttachments(threadKey, input.attachments, {
142 appendReference: true,
143 });
144 if (rejectedCount > 0) {
145 setPendingConnectionError(
146 `${rejectedCount} comment attachment${rejectedCount === 1 ? " was" : "s were"} not added. Messages can contain at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments.`,
147 );
148 }
149 }
151​
152/** Resolve per call so callbacks created before editing still target the current draft. */
153function activeComposerDraftKey(thread: {
154 readonly environmentId: EnvironmentId;
155 readonly id: ThreadId;
156}): string {
157 const threadKey = scopedThreadKey(thread.environmentId, thread.id);
158 const edit = getQueuedRunEdit(threadKey);
159 return edit === null ? threadKey : queuedEditDraftKey(threadKey, edit.runId);
161​
162export function useThreadDraftForThread(input: {
163 readonly environmentId?: EnvironmentId;
164 readonly threadId?: ThreadId;
165}) {
166 const threadKey =
167 input.environmentId && input.threadId
168 ? scopedThreadKey(input.environmentId, input.threadId)
169 : null;
170 const draft = useComposerDraft(threadKey);
171​
172 return {
173 draftMessage: draft.text,
174 draftAttachments: draft.attachments,
175 };
177​
178/** A provider without the interaction-mode toggle runs in the default mode. */
179export function updateThreadDraftModelSelection(
180 threadKey: string,
181 value: ModelSelection,
182 providers: ReadonlyArray<ServerProvider>,
183): void {
184 const provider = providers.find((candidate) => candidate.instanceId === value.instanceId);
185 updateComposerDraftSettings(threadKey, {
186 modelSelection: value,
187 ...(provider?.showInteractionModeToggle === false
188 ? { interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE }
189 : {}),
190 });
192​
193export function useThreadComposerState() {
194 const {
195 selectedThread: selectedThreadShell,
196 selectedThreadCreation,
197 selectedThreadDetailRef,
198 selectedEnvironmentRuntime,
199 } = useThreadSelection();
200 const selectedThreadProjection = useSelectedThreadProjection();
201 const selectedThreadVisibleTurnItems = useSelectedThreadVisibleTurnItems();
202 const acknowledgedMessages = useAtomValue(acknowledgedThreadMessagesAtom);
203 const queuedMessagesByThreadKey = useThreadOutboxMessages();
204 const dispatchingQueuedMessageId = useAtomValue(dispatchingQueuedMessageIdAtom);
205 const [feedbackSubmissionsByThreadKey, setFeedbackSubmissionsByThreadKey] = useState<
206 Record<string, ReadonlyArray<CodexFeedbackSubmission>>
207 >({});
208 const uploadThreadFeedback = useAtomCommand(threadEnvironment.uploadFeedback, {
209 reportFailure: false,
210 });
211 const editQueuedRun = useAtomCommand(threadEnvironment.editQueuedRun, {
212 label: "edit queued message",
213 reportFailure: false,
214 });
215 const [isSavingQueuedEdit, setIsSavingQueuedEdit] = useState(false);
216 const savingQueuedEditRef = useRef(false);
217 const pastedTextFileNamesRef = useRef<{ threadKey: string | null; names: Set<string> }>({
218 threadKey: null,
219 names: new Set(),
220 });
221 const reservePastedTextFileName = (threadKey: string, existingNames: ReadonlyArray<string>) => {
222 if (pastedTextFileNamesRef.current.threadKey !== threadKey) {
223 pastedTextFileNamesRef.current = { threadKey, names: new Set() };
224 }
225 const names = pastedTextFileNamesRef.current.names;
226 for (const name of existingNames) names.add(name);
227 const nextName = nextPastedTextFileName([...names]);
228 names.add(nextName);
229 return nextName;
230 };
231​
232 const selectedThreadKey = selectedThreadShell
233 ? scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id)
234 : null;
235 const selectedThreadQueuedMessages = selectedThreadKey
236 ? (queuedMessagesByThreadKey[selectedThreadKey] ?? []).filter(
237 (message) => message.creation === undefined,
238 )
239 : [];
240 const feedbackSubmissions = selectedThreadKey
241 ? (feedbackSubmissionsByThreadKey[selectedThreadKey] ?? [])
242 : [];
243 const dismissFeedback = (id: MessageId) => {
244 if (!selectedThreadKey) return;
245 setFeedbackSubmissionsByThreadKey((current) => ({
246 ...current,
247 [selectedThreadKey]: (current[selectedThreadKey] ?? []).filter((entry) => entry.id !== id),
248 }));
249 };
250 const selectedThreadMessages = selectedThreadProjection?.projection.messages;
251 const selectedThreadAttempts = selectedThreadProjection?.projection.attempts;
252 const selectedThreadNodes = selectedThreadProjection?.projection.nodes;
253 const checkpointSummaries = useAtomValue(
254 selectedThreadDetailRef === null
255 ? EMPTY_CHECKPOINT_SUMMARIES_ATOM
256 : environmentThreadDetails.checkpointSummariesAtom(selectedThreadDetailRef),
257 );
258 // A thread whose creation has not delivered its turn yet: the prompt only
259 // exists in the outbox, so it is appended to whatever the server has. The
260 // detail is usually present but empty during a worktree checkout, so this
261 // cannot be an either/or with the loaded messages.
262 const pendingCreationMessage = selectedThreadCreation?.message ?? null;
263 const [feedCache] = useState(createThreadFeedCache);
264 const selectedThreadFeed = (() => {
265 const pendingCreation =
266 pendingCreationMessage !== null &&
267 !selectedThreadMessages?.some((message) => message.id === pendingCreationMessage.messageId)
268 ? [pendingThreadCreationMessage(pendingCreationMessage)]
269 : [];
270 const feed = buildThreadFeed(selectedThreadVisibleTurnItems, {
271 anchoredMessages: pendingCreation,
272 attempts: selectedThreadAttempts,
273 nodes: selectedThreadNodes,
274 checkpointSummaries,
275 cache: feedCache,
276 });
277 const pendingAcknowledgments = selectPendingAcknowledgedMessages(acknowledgedMessages, {
278 threadKey: selectedThreadKey,
279 queuedMessages: selectedThreadQueuedMessages,
280 projectedMessages: selectedThreadMessages,
281 });
282 if (pendingAcknowledgments.length === 0) return feed;
283 return appendPendingThreadMessages(feed, feed, pendingAcknowledgments).map((entry) =>
284 entry.pendingMessage ? { ...entry, acknowledged: true } : entry,
285 );
286 })();
287​
288 const preferencesResult = useAtomValue(mobilePreferencesAtom);
289 const followUpBehavior = AsyncResult.isSuccess(preferencesResult)
290 ? (preferencesResult.value.followUpBehavior ?? DEFAULT_FOLLOW_UP_BEHAVIOR)
291 : DEFAULT_FOLLOW_UP_BEHAVIOR;
292 const queueWorkflow = useAtomValue(
293 selectedThreadDetailRef === null
294 ? EMPTY_QUEUE_WORKFLOW_ATOM
295 : environmentThreadDetails.queueWorkflowAtom(selectedThreadDetailRef),
296 );
297 const queuedRunEdit = useQueuedRunEdit(selectedThreadKey);
298 const composerDraftKey =
299 selectedThreadKey === null
300 ? null
301 : queuedRunEdit === null
302 ? selectedThreadKey
303 : queuedEditDraftKey(selectedThreadKey, queuedRunEdit.runId);
304 const selectedDraft = useComposerDraftSettings(selectedThreadKey);
305 const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
306 const selectedThread = selectedThreadShell;
307 const modelSelection = selectedDraft.modelSelection ?? selectedThread?.modelSelection ?? null;
308 const serverConfig = selectedEnvironmentRuntime?.serverConfig;
309 const pendingHandoff = resolvePendingHandoff(
310 selectedThreadProjection?.projection,
311 isModelSelectionUnavailable(serverConfig, modelSelection, selectedThread?.projectId ?? null)
312 ? null
313 : modelSelection,
314 serverConfig?.providers ?? [],
315 );
316 const runtimeMode = selectedDraft.runtimeMode ?? selectedThread?.runtimeMode ?? null;
317 const selectedProvider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
318 (provider) => provider.instanceId === modelSelection?.instanceId,
319 );
320 const interactionMode = selectedThread
321 ? resolveProviderInteractionMode(
322 selectedProvider,
323 selectedDraft.interactionMode ?? selectedThread.interactionMode,
324 )
325 : null;
326 const canSwitchThreadProvider = threadAllowsProviderSwitch({
327 thread: selectedThreadShell,
328 projection: selectedThreadProjection?.projection,
329 });
330 const selectedThreadRuntime = selectedThreadProjection
331 ? deriveThreadRuntime(selectedThreadProjection.projection)
332 : (selectedThreadShell?.runtime ?? null);
333 const selectedThreadActivityRun = selectedThreadProjection
334 ? deriveThreadActivityRun(selectedThreadProjection.projection)
335 : (selectedThreadShell?.latestRun ?? null);
336​
337 const isCompacting = (() => {
338 const queuedCompact = selectedThreadQueuedMessages.some(
339 (message) =>
340 message.messageId === dispatchingQueuedMessageId &&
341 message.text.trim().toLowerCase() === "/compact" &&
342 message.attachments.length === 0,
343 );
344 if (queuedCompact) return true;
345 const activeRunId = selectedThreadRuntime?.activeRunId;
346 if (!activeRunId || !threadRuntimeIsActive(selectedThreadRuntime)) return false;
347 if (
348 selectedThreadVisibleTurnItems.some(
349 ({ item }) =>
350 item.runId === activeRunId && item.type === "compaction" && item.status === "running",
351 )
352 ) {
353 return true;
354 }
355 const compactMessage = selectedThreadVisibleTurnItems.findLast(
356 ({ item }) =>
357 item.runId === activeRunId &&
358 item.type === "user_message" &&
359 item.text.trim().toLowerCase() === "/compact" &&
360 item.attachments.length === 0,
361 );
362 if (!compactMessage) return false;
363 return !selectedThreadVisibleTurnItems.some(
364 ({ item }) =>
365 item.runId === activeRunId &&
366 item.type === "compaction" &&
367 (item.status === "completed" ||
368 item.status === "failed" ||
369 item.status === "interrupted" ||
370 item.status === "cancelled"),
371 );
372 })();
373 // A compacting turn cannot take steering input, so follow-ups queue meanwhile.
374 const canSteerActiveTurn = queueWorkflow?.canPromoteToSteer === true && !isCompacting;
375 // A stop or a restart holds the queue, completion wakes included, until it
376 // is resumed; the queue sheet lists only the user's own messages.
377 const queueHeld = queueWorkflow?.isHeld === true;
378​
379 const runlessWorkStartedAt = selectedThreadProjection
380 ? deriveRunlessWorkStartedAt(selectedThreadProjection.projection)
381 : null;
382 const activeWorkStartedAt = (() => {
383 if (!selectedThreadShell) {
384 return null;
385 }
386 return (
387 resolveThreadWorkingStartedAt({
388 latestRun: selectedThreadActivityRun,
389 runtime: selectedThreadRuntime,
390 }) ?? runlessWorkStartedAt
391 );
392 })();
393 const runlessWorkActive = runlessWorkStartedAt !== null;
394​
395 const providerSubagentStatus = selectedThreadProjection
396 ? deriveProviderSubagentStatus(selectedThreadProjection.projection)
397 : null;
398​
399 const activeThreadBusy = threadRuntimeIsActive(selectedThreadRuntime);
400 const interruptibleRunId = threadRuntimeHasInterruptibleRun(selectedThreadRuntime)
401 ? (selectedThreadRuntime?.activeRunId ?? null)
402 : null;
403​
404 const cancelQueuedRunEdit = () => {
405 if (selectedThreadKey === null || savingQueuedEditRef.current) return;
406 endQueuedRunEdit(selectedThreadKey);
407 };
408​
409 const onRemoveQueuedEditAttachment = (attachmentId: string) => {
410 if (selectedThreadKey === null) return;
411 removeQueuedRunEditAttachment(selectedThreadKey, attachmentId);
412 };
413​
414 const saveQueuedRunEdit = async () => {
415 const thread = selectedThreadShell;
416 if (!thread || savingQueuedEditRef.current) return;
417 const threadKey = scopedThreadKey(thread.environmentId, thread.id);
418 const edit = getQueuedRunEdit(threadKey);
419 if (edit === null) return;
420 const draft = getComposerDraftSnapshot(queuedEditDraftKey(threadKey, edit.runId));
421 const text = draft.text.trim();
422 if (text.length === 0) {
423 Dialog.alert("Add a message", "A queued message cannot be left empty.");
424 return;
425 }
426 if (
427 edit.existingAttachments.length + draft.attachments.length >
428 PROVIDER_SEND_TURN_MAX_ATTACHMENTS
429 ) {
430 Dialog.alert(
431 "Too many attachments",
432 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
433 );
434 return;
435 }
436 const finishSave = startQueuedRunEditSave(threadKey);
437 if (finishSave === null) return;
438 savingQueuedEditRef.current = true;
439 setIsSavingQueuedEdit(true);
440 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
441 const prepared = await settlePromise(() =>
442 prepareTurnAttachments({
443 environmentId: thread.environmentId,
444 attachments: draft.attachments,
445 supportsImageUploads: capabilities?.attachmentUploads === true,
446 }),
447 );
448 if (AsyncResult.isFailure(prepared)) {
449 savingQueuedEditRef.current = false;
450 setIsSavingQueuedEdit(false);
451 finishSave(false);
452 const error = squashAtomCommandFailure(prepared);
453 Dialog.alert(
454 "Could not save the queued message",
455 error instanceof Error ? error.message : "Your edit is still in the composer.",
456 );
457 return;
458 }
459 if (prepared.value.status !== "ready") {
460 savingQueuedEditRef.current = false;
461 setIsSavingQueuedEdit(false);
462 finishSave(false);
463 return;
464 }
465 const payload = resolveQueuedEditPayload({
466 edit,
467 draftContext: draft.context,
468 draftAttachments: draft.attachments,
469 uploaded: prepared.value.attachments,
470 });
471 const result = await editQueuedRun({
472 environmentId: thread.environmentId,
473 input: {
474 threadId: thread.id,
475 runId: edit.runId,
476 text,
477 edit: {
478 messageId: edit.messageId,
479 attachments: payload.attachments,
480 ...(payload.context ? { context: payload.context } : {}),
481 },
482 },
483 });
484 savingQueuedEditRef.current = false;
485 setIsSavingQueuedEdit(false);
486 if (result._tag !== "Success") {
487 // The run left the queue during the save; its exit already told the composer what happened.
488 if (!finishSave(false)) return;
489 Dialog.alert(
490 "Could not save the queued message",
491 "It may have already started. Your edit is still in the composer.",
492 );
493 return;
494 }
495 // False when the edit was cancelled or begun again meanwhile; its draft is the newer edit's.
496 if (finishSave(true)) {
497 clearComposerDraft(queuedEditDraftKey(threadKey, edit.runId), {
498 deferAttachmentCleanup: true,
499 });
500 }
501 scheduleUnusedComposerAttachmentCleanup(draft.attachments);
502 };
503​
504 const onSendMessage = async (
505 followUpOverride?: ActiveTurnComposerAction,
506 beforeDispatch?: (
507 text: string,
508 hasAttachmentsOrContext: boolean,
509 ) => Promise<boolean | "responded">,
510 ) => {
511 if (
512 selectedThreadShell &&
513 selectedEnvironmentRuntime?.connectionState === "connected" &&
514 !readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope)
515 )
516 return null;
517 if (!selectedThreadShell) {
518 return null;
519 }
520 // Before thread creation succeeds, follow-ups could become orphaned and be dropped by the drain.
521 if (selectedThreadCreation !== null) {
522 return null;
523 }
524​
525 const editKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
526 if (getQueuedRunEdit(editKey) !== null) {
527 await saveQueuedRunEdit();
528 return null;
529 }
530​
531 const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
532 const draft = getComposerDraftSnapshot(threadKey);
533 if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
534 const thread = selectedThreadShell;
535 const text = draft.text.trim();
536 const attachments = draft.attachments;
537 if (
538 composerAttachmentUploadBlockReason({
539 environmentId: selectedThreadShell.environmentId,
540 attachments,
541 connected: selectedEnvironmentRuntime?.connectionState === "connected",
542 serverConfig: selectedEnvironmentRuntime?.serverConfig ?? null,
543 states: appAtomRegistry.get(composerAttachmentUploadsAtom),
544 }) !== null
545 )
546 return null;
547 if (text.length === 0 && attachments.length === 0) {
548 return null;
549 }
550 // Recovery preserves over-cap attachments; require trimming or outbox delivery would reject indefinitely.
551 if (attachments.length > PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
552 Dialog.alert(
553 "Too many attachments",
554 `Remove attachments until there are at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS}.`,
555 );
556 return null;
557 }
558​
559 const contextBlockReason = composerContextSendBlockReason(draft.context);
560 if (contextBlockReason) {
561 Dialog.alert("Too much context", contextBlockReason);
562 return null;
563 }
564​
565 const modelSelection = draft.modelSelection ?? thread.modelSelection;
566 const serverConfig = selectedEnvironmentRuntime?.serverConfig;
567 if (
568 selectedEnvironmentRuntime?.connectionState === "connected" &&
569 isModelSelectionUnavailable(serverConfig, modelSelection, thread.projectId)
570 ) {
571 const { title, detail } = describeUnavailableModelSelection(
572 serverConfig,
573 modelSelection,
574 thread.projectId,
575 );
576 Dialog.alert(title, detail);
577 return null;
578 }
579 const provider = serverConfig?.providers.find(
580 (entry) => entry.instanceId === modelSelection.instanceId,
581 );
582 const feedbackCommand =
583 attachments.length === 0 && provider?.driver === "codex"
584 ? parseCodexFeedbackCommand(text)
585 : null;
586 if (feedbackCommand) {
587 if (!readEnvironmentScope(selectedThreadShell.environmentId, AuthOrchestrationOperateScope))
588 return null;
589 if (thread.activeProviderThreadId === null) {
590 Dialog.alert("Start a Codex thread first", "Send a message before you submit feedback.");
591 return null;
592 }
593 const metadata = makeQueuedMessageMetadata();
594 await submitCodexFeedback({
595 submission: {
596 id: MessageId.make(metadata.messageId),
597 command: text,
598 createdAt: metadata.createdAt,
599 },
600 clearDraft: () => clearComposerDraftContent(threadKey),
601 onUpdate: (submission) => {
602 setFeedbackSubmissionsByThreadKey((current) => {
603 const existing = current[threadKey] ?? [];
604 const found = existing.some((entry) => entry.id === submission.id);
605 return {
606 ...current,
607 [threadKey]: found
608 ? existing.map((entry) => (entry.id === submission.id ? submission : entry))
609 : [...existing, submission],
610 };
611 });
612 },
613 upload: () =>
614 uploadThreadFeedback({
615 environmentId: thread.environmentId,
616 input: { threadId: thread.id, ...feedbackCommand },
617 }),
618 });
619 return null;
620 }
621​
622 if (beforeDispatch !== undefined) {
623 const response = await beforeDispatch(
624 text,
625 attachments.length > 0 || draft.context !== undefined,
626 );
627 if (!response) return null;
628 // A context paste still landing, or any draft or settings change while approvals were
629 // declined, means this snapshot is no longer what the user sent.
630 if (appAtomRegistry.get(composerContextImportsAtom)[threadKey]) return null;
631 const current = getComposerDraftSnapshot(threadKey);
632 if (
633 current.text !== draft.text ||
634 JSON.stringify(current.context) !== JSON.stringify(draft.context) ||
635 JSON.stringify(current.modelSelection) !== JSON.stringify(draft.modelSelection) ||
636 current.runtimeMode !== draft.runtimeMode ||
637 current.interactionMode !== draft.interactionMode ||
638 current.attachments.length !== attachments.length ||
639 current.attachments.some((attachment, index) => attachment.id !== attachments[index]?.id)
640 )
641 return null;
642 if (response === "responded") {
643 clearComposerDraftContent(threadKey);
644 return null;
645 }
646 }
647​
648 // Resolve at send time because outbox delivery may be delayed.
649 // Steering uses "auto" so an ended turn queues a run instead of restoring the draft.
650 // An approval redirect must steer the waiting turn instead of queueing behind it.
651 const activeTurnDefault = beforeDispatch !== undefined ? "steer" : followUpBehavior;
652 const followUpAction = resolveComposerDispatchMode({
653 running: activeThreadBusy && canSteerActiveTurn,
654 alternateModifier: followUpOverride !== undefined && followUpOverride !== activeTurnDefault,
655 activeTurnDefault,
656 });
657 const setupRunning = [selectedThreadActivityRun?.status, selectedThreadRuntime?.status].some(
658 (status) => status === "preparing" || status === "starting",
659 );
660 const followUpDispatchMode = setupRunning
661 ? "queue"
662 : followUpAction === "auto"
663 ? null
664 : followUpAction === "queue"
665 ? "queue"
666 : "auto";
667​
668 const metadata = makeQueuedMessageMetadata();
669 const messageId = MessageId.make(metadata.messageId);
670 clearThreadComposerError(threadKey);
671 const enqueuePromise = enqueueThreadOutboxMessage({
672 environmentId: selectedThreadShell.environmentId,
673 threadId: selectedThreadShell.id,
674 messageId,
675 commandId: CommandId.make(metadata.commandId),
676 text,
677 attachments,
678 context: draft.context,
679 modelSelection,
680 runtimeMode: draft.runtimeMode ?? thread.runtimeMode,
681 interactionMode: resolveProviderInteractionMode(
682 provider,
683 draft.interactionMode ?? thread.interactionMode,
684 ),
685 ...(followUpDispatchMode === null ? {} : { dispatchMode: followUpDispatchMode }),
686 createdAt: metadata.createdAt,
687 });
688 clearComposerDraftContent(threadKey, { deferAttachmentCleanup: true });
689 enqueuePromise.then(
690 () => scheduleUnusedComposerAttachmentCleanup(attachments),
691 (error: unknown) => {
692 // Restore with uncapped append; capped merge could drop attachments added during the failed write.
693 void mergeComposerDraftContent(threadKey, {
694 text,
695 context: draft.context,
696 attachments: [],
697 });
698 appendComposerDraftAttachments(threadKey, attachments, { allowOverflow: true });
699 setThreadComposerError(
700 threadKey,
701 error instanceof Error ? error.message : "Failed to save the queued message.",
702 );
703 },
704 );
705 return messageId;
706 };
707​
708 const onChangeDraftMessage = (value: string) => {
709 if (!selectedThreadShell) {
710 return;
711 }
712​
713 const threadKey = activeComposerDraftKey(selectedThreadShell);
714 setComposerDraftText(threadKey, value);
715 };
716​
717 const { onPickDraftMedia, onPickDraftFiles, onNativePasteImages, onNativePasteText } =
718 useComposerAttachmentActions({
719 draftKey: selectedThreadShell ? activeComposerDraftKey(selectedThreadShell) : null,
720 serverConfig: selectedEnvironmentRuntime?.serverConfig,
721 });
722​
723 const onPasteIntoDraft = async () => {
724 if (!selectedThreadShell) {
725 return;
726 }
727​
728 const threadKey = activeComposerDraftKey(selectedThreadShell);
729 const insertion = captureComposerDraftInsertion(threadKey);
730 const result = await pasteComposerClipboard({
731 existingCount: countComposerDraftAttachmentsAfterSelection(threadKey, insertion),
732 });
733 const rejectedPasteCount = appendComposerDraftAttachments(threadKey, result.images, {
734 appendReference: true,
735 insertion,
736 });
737 if (result.text) {
738 const currentDraft = getComposerDraftSnapshot(threadKey);
739 const currentAttachments = currentDraft.attachments;
740 const capabilities = selectedEnvironmentRuntime?.serverConfig?.environment.capabilities;
741 const advertisedMax =
742 capabilities?.attachmentUploads === true
743 ? capabilities.fileAttachments?.maxUploadBytes
744 : undefined;
745 const maxBytes =
746 advertisedMax === undefined ? null : clampFileAttachmentUploadBytes(advertisedMax);
747 const wouldExceedInputLimit =
748 currentDraft.text.length -
749 (currentDraft.text === insertion.text
750 ? Math.max(0, insertion.end - insertion.start)
751 : 0) +
752 result.text.length >
753 PROVIDER_SEND_TURN_MAX_INPUT_CHARS;
754 const shouldFold =
755 pastedTextDisposition({
756 text: result.text,
757 wouldExceedInputLimit,
758 canAttach: true,
759 }) === "attachment";
760 const canAttach =
761 maxBytes !== null &&
762 countComposerDraftAttachmentsAfterSelection(threadKey, insertion) <
763 PROVIDER_SEND_TURN_MAX_ATTACHMENTS &&
764 new TextEncoder().encode(result.text).byteLength <= maxBytes;
765 if (shouldFold && canAttach && maxBytes !== null) {
766 try {
767 const attachment = await createPastedTextComposerAttachment({
768 text: result.text,
769 name: reservePastedTextFileName(
770 threadKey,
771 currentAttachments.map((item) => item.name),
772 ),
773 maxBytes,
774 });
775 if (
776 appendComposerDraftAttachments(threadKey, [attachment], {
777 appendReference: true,
778 insertion,
779 }) > 0
780 ) {
781 await removePersistedComposerAttachmentFile(attachment.fileUri);
782 setPendingConnectionError(
783 `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
784 );
785 }
786 } catch (error) {
787 setPendingConnectionError(
788 error instanceof Error ? error.message : "Could not attach pasted text.",
789 );
790 }
791 } else if (shouldFold && !wouldExceedInputLimit) {
792 insertComposerDraftText(threadKey, result.text, insertion);
793 } else if (shouldFold) {
794 setPendingConnectionError(
795 wouldExceedInputLimit
796 ? "Pasted text is too large for this message. Remove some text or an attachment, then paste again."
797 : "Could not attach pasted text. Remove an attachment or use a smaller paste, then try again.",
798 );
799 } else {
800 insertComposerDraftText(threadKey, result.text, insertion);
801 }
802 }
803 if (result.error) {
804 setPendingConnectionError(result.error);
805 } else if (rejectedPasteCount > 0) {
806 setPendingConnectionError(
807 `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
808 );
809 }
810 };
811​
812 const onRemoveDraftImage = (imageId: string) => {
813 if (!selectedThreadShell) {
814 return;
815 }
816​
817 const threadKey = activeComposerDraftKey(selectedThreadShell);
818 removeComposerDraftAttachment(threadKey, imageId);
819 };
820​
821 const onUpdateInteractionMode = (value: ProviderInteractionMode) => {
822 if (!selectedThreadKey) {
823 return;
824 }
825 const modelSelection =
826 getComposerDraftSnapshot(selectedThreadKey).modelSelection ?? selectedThread?.modelSelection;
827 const provider = selectedEnvironmentRuntime?.serverConfig?.providers.find(
828 (candidate) => candidate.instanceId === modelSelection?.instanceId,
829 );
830 updateComposerDraftSettings(selectedThreadKey, {
831 interactionMode: resolveProviderInteractionMode(provider, value),
832 });
833 };
834​
835 return {
836 feedbackSubmissions,
837 dismissFeedback,
838 selectedThreadFeed,
839 selectedThreadActivityRun,
840 selectedThreadQueueCount,
841 selectedThreadQueuedMessages,
842 dispatchingQueuedMessageId,
843 activeWorkStartedAt,
844 runlessWorkActive,
845 providerSubagentStatus,
846 isCompacting,
847 composerDraftKey,
848 followUpBehavior,
849 canSteerActiveTurn,
850 queueHeld,
851 queuedRunEdit,
852 isSavingQueuedEdit,
853 cancelQueuedRunEdit,
854 onRemoveQueuedEditAttachment,
855 modelSelection,
856 pendingHandoff,
857 canSwitchThreadProvider,
858 runtimeMode,
859 interactionMode,
860 activeThreadBusy,
861 interruptibleRunId,
862 onChangeDraftMessage,
863 onPickDraftMedia,
864 onPickDraftFiles,
865 onPasteIntoDraft,
866 onNativePasteImages,
867 onNativePasteText,
868 onRemoveDraftImage,
869 onSendMessage,
870 onUpdateInteractionMode,
871 };