The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 08:00 UTC
refactor(web): move queued-message editing out of ChatView (#20304)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 16, 2026 at 17:39 UTC
4a7083f2b7bc020185b6531988064a407d982434
3 files changed
+391
-269
apps/web/src/components/ChatView.tsx
+44
-269
@@ -11,7 +11,7 @@ import {
11
import * as DateTime from "effect/DateTime";
12
import { restorePlanFollowUpComposer } from "./ChatView.logic";
13
import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";
14
-import { prepareQueuedEditAttachments, recoverQueuedMessageEdit } from "./chat/queuedMessageEdit";
14
+import { useQueuedRunEdit } from "./chat/useQueuedRunEdit";
15
import {
16
isPaintOnlyThreadTimeline,
17
peekHeldThreadTimeline,
@@ -51,7 +51,6 @@ import {
51
CommandId,
52
DEFAULT_MODEL,
53
isProviderNativeSubagentThread,
54
- type ChatAttachment as ContractChatAttachment,
54
EnvironmentAuthorizationError,
55
type EnvironmentId,
56
type MessageId,
@@ -462,11 +461,7 @@ import {
461
shouldShowThreadErrorBanner,
462
ThreadErrorBanner,
463
} from "./chat/ThreadErrorBanner";
465
-import {
466
- QueuedRunsControl,
467
- type QueuedRunsControlHandle,
468
- type EditQueuedRunRequest,
469
-} from "./chat/QueuedRunsControl";
464
+import { QueuedRunsControl, type QueuedRunsControlHandle } from "./chat/QueuedRunsControl";
465
import { useLinkedThreadPullRequest } from "./ThreadStatusIndicators";
466
import type { ComposerBannerStackItem } from "./chat/ComposerBannerStack";
467
import { ThreadStatusLine } from "./chat/ThreadStatusLine";
@@ -957,11 +952,7 @@ function makeThreadErrorSetter(input: {
952
};
953
}
954
960
-/** Draft id for editing a queued run of `threadRef`. */
961
-function makeQueuedEditDraftTarget(threadRef: ScopedThreadRef) {
962
- return (runId: RunId) => DraftId.make(`queued-edit:${scopedThreadKey(threadRef)}:${runId}`);
963
-}
964
-
955
+/** Why the model picker should disable a model, or null when it can be chosen. */
956
function makeModelDisabledReason(
957
context: Omit<
958
Parameters<typeof getStartedThreadModelChangeBlockReason>[0],
@@ -1067,24 +1058,8 @@ export default function ChatView(props: ChatViewProps) {
1058
() => new Map(environments.map((environment) => [environment.environmentId, environment])),
1059
[environments],
1060
);
1070
- const [editingQueuedRun, setEditingQueuedRun] = useState<{
1071
- readonly threadId: ThreadId;
1072
- readonly runId: RunId;
1073
- readonly messageId: MessageId;
1074
- readonly originalText: string;
1075
- readonly existingAttachments: ReadonlyArray<ContractChatAttachment>;
1076
- readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined;
1077
- } | null>(null);
1078
- const queuedEditDraftTargetFor = useMemo(
1079
- () => makeQueuedEditDraftTarget(routeThreadRef),
1080
- [routeThreadRef],
1081
- );
1061
const baseComposerDraftTarget: ScopedThreadRef | DraftId =
1062
routeKind === "server" ? routeThreadRef : props.draftId;
1084
- const composerDraftTarget: ScopedThreadRef | DraftId =
1085
- editingQueuedRun === null
1086
- ? baseComposerDraftTarget
1087
- : queuedEditDraftTargetFor(editingQueuedRun.runId);
1063
const draftThread = useComposerDraftStore((store) =>
1064
routeKind === "server"
1065
? store.getDraftSessionByRef(routeThreadRef)
@@ -1099,6 +1074,19 @@ export default function ChatView(props: ChatViewProps) {
1074
});
1075
const serverThreadProjection = useThreadProjection(routeThreadDetailRef);
1076
const serverProjection = serverThreadProjection?.projection ?? null;
1077
+ const promptRef = useRef("");
1078
+ const localComposerRef = useRef<ChatComposerHandle | null>(null);
1079
+ const composerRef = useComposerHandleContext() ?? localComposerRef;
1080
+ const queuedRunEdit = useQueuedRunEdit({
1081
+ environmentId,
1082
+ routeThreadRef,
1083
+ threadDraftTarget: baseComposerDraftTarget,
1084
+ activeThreadId: serverThread !== null || draftThread !== null ? threadId : null,
1085
+ serverProjection,
1086
+ promptRef,
1087
+ composerRef,
1088
+ });
1089
+ const composerDraftTarget = queuedRunEdit.draftTarget;
1090
const reportedModelSelection = serverProjection
1091
? deriveReportedModelSelection(serverProjection)
1092
: null;
@@ -1223,12 +1211,9 @@ export default function ChatView(props: ChatViewProps) {
1211
const setLogicalProjectDraftThreadId = useComposerDraftStore(
1212
(store) => store.setLogicalProjectDraftThreadId,
1213
);
1226
- const promptRef = useRef("");
1214
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
1215
const composerFilesRef = useRef<ComposerFileAttachment[]>([]);
1216
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>([]);
1230
- const localComposerRef = useRef<ChatComposerHandle | null>(null);
1231
- const composerRef = useComposerHandleContext() ?? localComposerRef;
1217
const branchToolbarRef = useRef<BranchToolbarHandle>(null);
1218
const pasteAsTextShortcutUntilRef = useRef(0);
1219
const [restingComposerControlsHost, setRestingComposerControlsHost] =
@@ -3650,112 +3635,7 @@ export default function ChatView(props: ChatViewProps) {
3635
}
3636
};
3637
const sendAppMessageStable = useStableCallback(sendAppMessage);
3653
- const editQueuedRunCommand = useAtomCommand(threadEnvironment.editQueuedRun, {
3654
- reportFailure: false,
3655
- });
3638
const queuedRunsControlRef = useRef<QueuedRunsControlHandle>(null);
3657
- const queuedEditSaveInFlightRef = useRef(false);
3658
- const [isSavingQueuedEdit, setIsSavingQueuedEdit] = useState(false);
3659
- const queuedEditImageResources = useMemo(
3660
- () =>
3661
- (editingQueuedRun?.existingAttachments ?? [])
3662
- .filter((attachment) => attachment.type === "image")
3663
- .map((attachment) => ({ _tag: "attachment" as const, attachmentId: attachment.id })),
3664
- [editingQueuedRun],
3665
- );
3666
- const queuedEditImageUrls = useAssetUrls(environmentId, queuedEditImageResources);
3667
- const composerEditingQueuedAttachments = useMemo(() => {
3668
- if (editingQueuedRun === null) return null;
3669
- const urlByAttachmentId = new Map(
3670
- queuedEditImageResources.map((resource, index) => [
3671
- resource.attachmentId,
3672
- queuedEditImageUrls[index] ?? null,
3673
- ]),
3674
- );
3675
- return editingQueuedRun.existingAttachments.map((attachment) => ({
3676
- attachment,
3677
- url: urlByAttachmentId.get(attachment.id) ?? null,
3678
- }));
3679
- }, [editingQueuedRun, queuedEditImageResources, queuedEditImageUrls]);
3680
- const beginEditingQueuedRun = (request: EditQueuedRunRequest) => {
3681
- if (!activeThread) return;
3682
- if (editingQueuedRun !== null && editingQueuedRun.runId !== request.runId) {
3683
- clearComposerDraftContent(queuedEditDraftTargetFor(editingQueuedRun.runId));
3684
- }
3685
- const target = queuedEditDraftTargetFor(request.runId);
3686
- clearComposerDraftContent(target);
3687
- setComposerDraftPrompt(target, request.text);
3688
- setEditingQueuedRun({
3689
- threadId: activeThread.id,
3690
- runId: request.runId,
3691
- messageId: request.messageId,
3692
- originalText: request.text,
3693
- existingAttachments: request.attachments,
3694
- context: serverProjection?.messages.find((message) => message.id === request.messageId)
3695
- ?.context,
3696
- });
3697
- scheduleComposerFocus();
3698
- };
3699
- const beginEditingQueuedRunStable = useStableCallback(beginEditingQueuedRun);
3700
- const cancelEditingQueuedRun = () => {
3701
- if (editingQueuedRun === null) return;
3702
- clearComposerDraftContent(queuedEditDraftTargetFor(editingQueuedRun.runId));
3703
- setEditingQueuedRun(null);
3704
- scheduleComposerFocus();
3705
- };
3706
- const cancelEditingQueuedRunStable = useStableCallback(cancelEditingQueuedRun);
3707
- const removeEditingQueuedAttachment = (attachmentId: string) => {
3708
- setEditingQueuedRun((current) =>
3709
- current === null
3710
- ? current
3711
- : {
3712
- ...current,
3713
- existingAttachments: current.existingAttachments.filter(
3714
- (attachment) => attachment.id !== attachmentId,
3715
- ),
3716
- },
3717
- );
3718
- };
3719
- const removeEditingQueuedAttachmentStable = useStableCallback(removeEditingQueuedAttachment);
3720
- useEffect(() => {
3721
- if (editingQueuedRun === null) return;
3722
- if (activeThread?.id !== editingQueuedRun.threadId) {
3723
- setEditingQueuedRun(null);
3724
- return;
3725
- }
3726
- if (serverProjection === null) return;
3727
- const run = serverProjection.runs.find((candidate) => candidate.id === editingQueuedRun.runId);
3728
- if (run !== undefined && run.status === "queued") return;
3729
- const recovery = recoverQueuedMessageEdit({
3730
- editTarget: queuedEditDraftTargetFor(editingQueuedRun.runId),
3731
- threadTarget: baseComposerDraftTarget,
3732
- originalText: editingQueuedRun.originalText,
3733
- });
3734
- if (recovery === "kept") {
3735
- toastManager.add(
3736
- stackedThreadToast({
3737
- type: "info",
3738
- title: "Queued message is no longer queued",
3739
- description: "Your unsaved edit was kept in the composer.",
3740
- }),
3741
- );
3742
- } else if (recovery === "discarded") {
3743
- toastManager.add(
3744
- stackedThreadToast({
3745
- type: "warning",
3746
- title: "Queued message is no longer queued",
3747
- description: "Your unsaved edit was discarded.",
3748
- }),
3749
- );
3750
- }
3751
- setEditingQueuedRun(null);
3752
- }, [
3753
- activeThread?.id,
3754
- baseComposerDraftTarget,
3755
- editingQueuedRun,
3756
- queuedEditDraftTargetFor,
3757
- serverProjection,
3758
- ]);
3639
const addTerminalContextToDraft = (selection: TerminalContextSelection) => {
3640
composerRef.current?.addTerminalContext(selection);
3641
};
@@ -7482,128 +7362,21 @@ export default function ChatView(props: ChatViewProps) {
7362
previewAnnotationContextReference(directAnnotation.annotation),
7363
])
7364
: promptRef.current;
7485
- if (editingQueuedRun !== null) {
7486
- if (queuedEditSaveInFlightRef.current) return;
7487
- const editText = promptForSend.trim();
7488
- const newEditImages = [...composerImages];
7489
- const newEditFiles = [...composerFiles];
7490
- const newEditAttachments = [...newEditImages, ...newEditFiles];
7491
- if (
7492
- editingQueuedRun.existingAttachments.length + newEditAttachments.length >
7493
- PROVIDER_SEND_TURN_MAX_ATTACHMENTS
7494
- ) {
7495
- setThreadError(
7496
- editingQueuedRun.threadId,
7497
- `A message can have at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments.`,
7498
- );
7499
- return;
7500
- }
7501
- if (
7502
- editText.length === 0 &&
7503
- editingQueuedRun.existingAttachments.length === 0 &&
7504
- newEditImages.length === 0 &&
7505
- newEditFiles.length === 0
7506
- ) {
7507
- return;
7508
- }
7509
- queuedEditSaveInFlightRef.current = true;
7510
- setIsSavingQueuedEdit(true);
7511
- try {
7512
- const uploads = await prepareQueuedEditAttachments({
7513
- existingAttachments: editingQueuedRun.existingAttachments,
7514
- images: newEditImages,
7515
- files: newEditFiles,
7516
- readImage: readFileAsDataUrl,
7517
- uploadFiles: async (files) => {
7518
- const validateFiles = () => {
7519
- const config =
7520
- appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId) ?? null;
7521
- const reason = fileAttachmentCapabilityBlockReason({
7522
- files,
7523
- attachmentUploadsCapabilityKnown: config !== null,
7524
- supportsAttachmentUploads:
7525
- config?.environment.capabilities.attachmentUploads === true,
7526
- maxFileAttachmentBytes:
7527
- config?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null,
7528
- });
7529
- if (reason !== null) throw new Error(reason);
7530
- };
7531
- validateFiles();
7532
- for (const file of files)
7533
- startAttachmentUpload({
7534
- environmentId,
7535
- image: file,
7536
- draftTarget: composerDraftTarget,
7537
- });
7538
- await awaitAttachmentUploads(files.map((file) => file.id));
7539
- validateFiles();
7540
- const uploaded = getUploadedAttachments({ environmentId, images: files });
7541
- if (uploaded === null) throw new Error("Retry or remove failed uploads before saving.");
7542
- return uploaded;
7543
- },
7544
- });
7545
- const result = await editQueuedRunCommand({
7546
- environmentId: activeThread.environmentId,
7547
- input: {
7548
- threadId: editingQueuedRun.threadId,
7549
- runId: editingQueuedRun.runId,
7550
- text: editText.length === 0 ? ATTACHMENT_ONLY_BOOTSTRAP_PROMPT : editText,
7551
- edit: {
7552
- messageId: editingQueuedRun.messageId,
7553
- attachments: uploads,
7554
- context: {
7555
- version: 1,
7556
- records: [
7557
- ...new Map(
7558
- [
7559
- ...(editingQueuedRun.context?.records ?? []).filter(
7560
- (record) =>
7561
- !("attachmentId" in record) ||
7562
- editingQueuedRun.existingAttachments.some(
7563
- (attachment) => attachment.id === record.attachmentId,
7564
- ),
7565
- ),
7566
- ...(buildMessageContext({
7567
- terminalContexts: composerTerminalContexts.filter(
7568
- (context) => context.text.trim().length > 0,
7569
- ),
7570
- reviewComments: composerReviewComments,
7571
- previewAnnotations: composerPreviewAnnotations,
7572
- threadContexts: composerThreadContexts,
7573
- attachments: newEditAttachments.map((attachment, index) => ({
7574
- attachment,
7575
- attachmentId:
7576
- uploads[editingQueuedRun.existingAttachments.length + index]?.id ??
7577
- attachment.id,
7578
- })),
7579
- })?.records ?? []),
7580
- ].map((record) => [record.contextId, record] as const),
7581
- ).values(),
7582
- ],
7583
- },
7584
- },
7585
- },
7586
- });
7587
- if (result._tag === "Failure") {
7588
- setThreadError(editingQueuedRun.threadId, "Could not save the edited queued message.");
7589
- return;
7590
- }
7591
- setThreadError(editingQueuedRun.threadId, null);
7592
- releaseDraftAttachments(newEditAttachments);
7593
- promptRef.current = "";
7594
- clearComposerDraftContent(queuedEditDraftTargetFor(editingQueuedRun.runId));
7595
- composerRef.current?.resetCursorState();
7596
- setEditingQueuedRun(null);
7597
- scheduleComposerFocus();
7598
- } catch (error) {
7599
- setThreadError(
7600
- editingQueuedRun.threadId,
7601
- error instanceof Error ? error.message : "Could not save the edited queued message.",
7602
- );
7603
- } finally {
7604
- queuedEditSaveInFlightRef.current = false;
7605
- setIsSavingQueuedEdit(false);
7606
- }
7365
+ if (queuedRunEdit.isEditing) {
7366
+ // Edit mode repurposes the composer: sending saves the queued message
7367
+ // in place instead of dispatching a new turn.
7368
+ await queuedRunEdit.saveEdit(
7369
+ {
7370
+ prompt: promptForSend,
7371
+ images: composerImages,
7372
+ files: composerFiles,
7373
+ terminalContexts: composerTerminalContexts,
7374
+ reviewComments: composerReviewComments,
7375
+ previewAnnotations: composerPreviewAnnotations,
7376
+ threadContexts: composerThreadContexts,
7377
+ },
7378
+ setThreadError,
7379
+ );
7380
return;
7381
}
7382
const {
@@ -9125,16 +8898,16 @@ export default function ChatView(props: ChatViewProps) {
8898
environmentId={activeThread.environmentId}
8899
threadId={activeThread.id}
8900
optimisticMessages={optimisticUserMessages}
9128
- editingRunId={editingQueuedRun?.runId ?? null}
9129
- onEditQueuedRun={beginEditingQueuedRunStable}
9130
- onCancelEdit={cancelEditingQueuedRunStable}
8901
+ editingRunId={queuedRunEdit.editingRunId}
8902
+ onEditQueuedRun={queuedRunEdit.beginEdit}
8903
+ onCancelEdit={queuedRunEdit.cancelEdit}
8904
/>
8905
) : null,
8906
[
8907
activeThread,
9135
- beginEditingQueuedRunStable,
9136
- cancelEditingQueuedRunStable,
9137
- editingQueuedRun?.runId,
8908
+ queuedRunEdit.beginEdit,
8909
+ queuedRunEdit.cancelEdit,
8910
+ queuedRunEdit.editingRunId,
8911
isServerThread,
8912
keybindings,
8913
optimisticUserMessages,
@@ -9872,8 +9645,8 @@ export default function ChatView(props: ChatViewProps) {
9645
contextStrip={showComposerContextStrip || showComposerModelStrip}
9646
>
9647
<ComposerSurface.Host
9875
- inert={isSavingQueuedEdit}
9876
- aria-busy={isSavingQueuedEdit}
9648
+ inert={queuedRunEdit.isSaving}
9649
+ aria-busy={queuedRunEdit.isSaving}
9650
>
9651
<div className="relative z-10">
9652
{showProviderSubagentBar ? (
@@ -9937,7 +9710,7 @@ export default function ChatView(props: ChatViewProps) {
9710
(isSendBusy && !sendQueuesBehindSetup) ||
9711
(setupQueueSendThreadKey !== null &&
9712
setupQueueSendThreadKey === activeThreadKey) ||
9940
- isSavingQueuedEdit ||
9713
+ queuedRunEdit.isSaving ||
9714
isResuming
9715
}
9716
canResume={resumableRunId !== null || hasHeldQueuedRuns}
@@ -10061,8 +9834,10 @@ export default function ChatView(props: ChatViewProps) {
9834
setThreadError={setThreadError}
9835
onExpandImage={onExpandTimelineImageStable}
9836
onFileOpen={openFileAttachmentStable}
10064
- editingQueuedAttachments={composerEditingQueuedAttachments}
10065
- onRemoveEditingQueuedAttachment={removeEditingQueuedAttachmentStable}
9837
+ editingQueuedAttachments={queuedRunEdit.editingAttachments}
9838
+ onRemoveEditingQueuedAttachment={
9839
+ queuedRunEdit.removeEditingAttachment
9840
+ }
9841
/>
9842
)}
9843
</div>
apps/web/src/components/chat/useQueuedRunEdit.ts
new
+346
@@ -0,0 +1,346 @@
1
+import {
2
+ PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
3
+ type ChatAttachment,
4
+ type EnvironmentId,
5
+ type MessageId,
6
+ type OrchestrationMessageContext,
7
+ type OrchestrationV2ThreadProjection,
8
+ type PreviewAnnotationPayload,
9
+ type RunId,
10
+ type ScopedThreadRef,
11
+ type ThreadContextRecord,
12
+ type ThreadId,
13
+} from "@t3tools/contracts";
14
+import { scopedThreadKey } from "@t3tools/client-runtime/environment";
15
+import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
16
+import { useEffect, useRef, useState, type RefObject } from "react";
17
+import { useAssetUrls } from "../../assets/assetUrls";
18
+import {
19
+ DraftId,
20
+ useComposerDraftStore,
21
+ type ComposerFileAttachment,
22
+ type ComposerImageAttachment,
23
+ type ComposerThreadTarget,
24
+} from "../../composerDraftStore";
25
+import { useStableCallback } from "../../hooks/useStableCallback";
26
+import {
27
+ awaitAttachmentUploads,
28
+ getUploadedAttachments,
29
+ releaseDraftAttachments,
30
+ startAttachmentUpload,
31
+} from "../../lib/attachmentUploadQueue";
32
+import { buildMessageContext } from "../../lib/composerContextRecords";
33
+import { readFileAsDataUrl } from "../../lib/imageCompression";
34
+import type { TerminalContextDraft } from "../../lib/terminalContext";
35
+import type { ReviewCommentContext } from "../../reviewCommentContext";
36
+import { appAtomRegistry } from "../../rpc/atomRegistry";
37
+import { environmentServerConfigsAtom } from "../../state/server";
38
+import { threadEnvironment } from "../../state/threads";
39
+import { useAtomCommand } from "../../state/use-atom-command";
40
+import { stackedThreadToast, toastManager } from "../ui/toast";
41
+import type { ChatComposerHandle } from "./ChatComposer";
42
+import { fileAttachmentCapabilityBlockReason } from "./composerAttachmentFiles";
43
+import { prepareQueuedEditAttachments, recoverQueuedMessageEdit } from "./queuedMessageEdit";
44
+import type { EditQueuedRunRequest } from "./QueuedRunsControl";
45
+
46
+interface EditingQueuedRun {
47
+ readonly threadId: ThreadId;
48
+ readonly runId: RunId;
49
+ readonly messageId: MessageId;
50
+ readonly originalText: string;
51
+ readonly existingAttachments: ReadonlyArray<ChatAttachment>;
52
+ readonly context?: OrchestrationMessageContext | undefined;
53
+}
54
+
55
+/** What the composer holds when the user saves a queued-message edit. */
56
+export interface QueuedRunEditContent {
57
+ readonly prompt: string;
58
+ readonly images: ReadonlyArray<ComposerImageAttachment>;
59
+ readonly files: ReadonlyArray<ComposerFileAttachment>;
60
+ readonly terminalContexts: ReadonlyArray<TerminalContextDraft>;
61
+ readonly reviewComments: ReadonlyArray<ReviewCommentContext>;
62
+ readonly previewAnnotations: ReadonlyArray<PreviewAnnotationPayload>;
63
+ readonly threadContexts: ReadonlyArray<ThreadContextRecord>;
64
+}
65
+
66
+/** Draft id for editing a queued run of the route thread. */
67
+function queuedEditDraftTarget(routeThreadRef: ScopedThreadRef, runId: RunId) {
68
+ return DraftId.make(`queued-edit:${scopedThreadKey(routeThreadRef)}:${runId}`);
69
+}
70
+
71
+/** Uploads the edit's new attachments and saves it. Returns the error to show, or null. */
72
+async function submitQueuedRunEdit(input: {
73
+ readonly environmentId: EnvironmentId;
74
+ readonly draftTarget: ComposerThreadTarget;
75
+ readonly editing: EditingQueuedRun;
76
+ readonly content: QueuedRunEditContent;
77
+ readonly editQueuedRun: ReturnType<typeof useEditQueuedRunCommand>;
78
+}): Promise<string | null> {
79
+ const { environmentId, draftTarget, editing, content } = input;
80
+ const editText = content.prompt.trim();
81
+ const newAttachments = [...content.images, ...content.files];
82
+ const uploadFiles = async (files: ReadonlyArray<ComposerFileAttachment>) => {
83
+ const validateFiles = () => {
84
+ const config = appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId) ?? null;
85
+ const reason = fileAttachmentCapabilityBlockReason({
86
+ files,
87
+ attachmentUploadsCapabilityKnown: config !== null,
88
+ supportsAttachmentUploads: config?.environment.capabilities.attachmentUploads === true,
89
+ maxFileAttachmentBytes:
90
+ config?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null,
91
+ });
92
+ if (reason !== null) throw new Error(reason);
93
+ };
94
+ validateFiles();
95
+ for (const file of files) startAttachmentUpload({ environmentId, image: file, draftTarget });
96
+ await awaitAttachmentUploads(files.map((file) => file.id));
97
+ validateFiles();
98
+ const uploaded = getUploadedAttachments({ environmentId, images: files });
99
+ if (uploaded === null) throw new Error("Retry or remove failed uploads before saving.");
100
+ return uploaded;
101
+ };
102
+ try {
103
+ const uploads = await prepareQueuedEditAttachments({
104
+ existingAttachments: editing.existingAttachments,
105
+ images: content.images,
106
+ files: content.files,
107
+ readImage: readFileAsDataUrl,
108
+ uploadFiles,
109
+ });
110
+ // Kept records for removed attachments would point at nothing.
111
+ const keptRecords = (editing.context?.records ?? []).filter(
112
+ (record) =>
113
+ !("attachmentId" in record) ||
114
+ editing.existingAttachments.some((attachment) => attachment.id === record.attachmentId),
115
+ );
116
+ const newRecords =
117
+ buildMessageContext({
118
+ terminalContexts: content.terminalContexts.filter(
119
+ (context) => context.text.trim().length > 0,
120
+ ),
121
+ reviewComments: content.reviewComments,
122
+ previewAnnotations: content.previewAnnotations,
123
+ threadContexts: content.threadContexts,
124
+ attachments: newAttachments.map((attachment, index) => ({
125
+ attachment,
126
+ attachmentId: uploads[editing.existingAttachments.length + index]?.id ?? attachment.id,
127
+ })),
128
+ })?.records ?? [];
129
+ const result = await input.editQueuedRun({
130
+ environmentId,
131
+ input: {
132
+ threadId: editing.threadId,
133
+ runId: editing.runId,
134
+ text: editText.length === 0 ? ATTACHMENT_ONLY_BOOTSTRAP_PROMPT : editText,
135
+ edit: {
136
+ messageId: editing.messageId,
137
+ attachments: uploads,
138
+ context: {
139
+ version: 1,
140
+ records: [
141
+ ...new Map(
142
+ [...keptRecords, ...newRecords].map(
143
+ (record) => [record.contextId, record] as const,
144
+ ),
145
+ ).values(),
146
+ ],
147
+ },
148
+ },
149
+ },
150
+ });
151
+ return result._tag === "Failure" ? "Could not save the edited queued message." : null;
152
+ } catch (error) {
153
+ return error instanceof Error ? error.message : "Could not save the edited queued message.";
154
+ }
155
+}
156
+
157
+function useEditQueuedRunCommand() {
158
+ return useAtomCommand(threadEnvironment.editQueuedRun, { reportFailure: false });
159
+}
160
+
161
+/**
162
+ * Queued-message edit mode. While active, the composer is retargeted to a
163
+ * per-run edit draft so the user's in-progress draft on the thread survives
164
+ * untouched; `existingAttachments` tracks which stored attachments the edit
165
+ * keeps (removal is client state until save).
166
+ */
167
+export function useQueuedRunEdit(input: {
168
+ readonly environmentId: EnvironmentId;
169
+ readonly routeThreadRef: ScopedThreadRef;
170
+ readonly threadDraftTarget: ComposerThreadTarget;
171
+ // Null while the route has no thread yet; an edit needs one to target.
172
+ readonly activeThreadId: ThreadId | null;
173
+ readonly serverProjection: OrchestrationV2ThreadProjection | null;
174
+ readonly promptRef: { current: string };
175
+ readonly composerRef: RefObject<ChatComposerHandle | null>;
176
+}) {
177
+ const {
178
+ environmentId,
179
+ routeThreadRef,
180
+ threadDraftTarget,
181
+ activeThreadId,
182
+ serverProjection,
183
+ promptRef,
184
+ composerRef,
185
+ } = input;
186
+ const editQueuedRunCommand = useEditQueuedRunCommand();
187
+ const [editing, setEditing] = useState<EditingQueuedRun | null>(null);
188
+ const saveInFlightRef = useRef(false);
189
+ const [isSaving, setIsSaving] = useState(false);
190
+ // Navigating to another thread ends the edit; its draft stays for later.
191
+ if (editing !== null && activeThreadId !== editing.threadId) {
192
+ setEditing(null);
193
+ }
194
+ const draftTarget =
195
+ editing === null ? threadDraftTarget : queuedEditDraftTarget(routeThreadRef, editing.runId);
196
+
197
+ const imageResources = (editing?.existingAttachments ?? [])
198
+ .filter((attachment) => attachment.type === "image")
199
+ .map((attachment) => ({ _tag: "attachment" as const, attachmentId: attachment.id }));
200
+ const imageUrls = useAssetUrls(environmentId, imageResources);
201
+ const urlByAttachmentId = new Map(
202
+ imageResources.map((resource, index) => [resource.attachmentId, imageUrls[index] ?? null]),
203
+ );
204
+ const editingAttachments =
205
+ editing === null
206
+ ? null
207
+ : editing.existingAttachments.map((attachment) => ({
208
+ attachment,
209
+ url: urlByAttachmentId.get(attachment.id) ?? null,
210
+ }));
211
+
212
+ const focusComposerSoon = () => {
213
+ window.requestAnimationFrame(() => composerRef.current?.focusAtEnd());
214
+ };
215
+ const clearEditDraft = (runId: RunId) =>
216
+ useComposerDraftStore
217
+ .getState()
218
+ .clearComposerContent(queuedEditDraftTarget(routeThreadRef, runId));
219
+
220
+ const beginEdit = useStableCallback((request: EditQueuedRunRequest) => {
221
+ if (activeThreadId === null) return;
222
+ if (editing !== null && editing.runId !== request.runId) clearEditDraft(editing.runId);
223
+ const target = queuedEditDraftTarget(routeThreadRef, request.runId);
224
+ const store = useComposerDraftStore.getState();
225
+ store.clearComposerContent(target);
226
+ store.setPrompt(target, request.text);
227
+ setEditing({
228
+ threadId: activeThreadId,
229
+ runId: request.runId,
230
+ messageId: request.messageId,
231
+ originalText: request.text,
232
+ existingAttachments: request.attachments,
233
+ context: serverProjection?.messages.find((message) => message.id === request.messageId)
234
+ ?.context,
235
+ });
236
+ focusComposerSoon();
237
+ });
238
+ const cancelEdit = useStableCallback(() => {
239
+ if (editing === null) return;
240
+ clearEditDraft(editing.runId);
241
+ setEditing(null);
242
+ focusComposerSoon();
243
+ });
244
+ const removeEditingAttachment = useStableCallback((attachmentId: string) => {
245
+ setEditing((current) =>
246
+ current === null
247
+ ? current
248
+ : {
249
+ ...current,
250
+ existingAttachments: current.existingAttachments.filter(
251
+ (attachment) => attachment.id !== attachmentId,
252
+ ),
253
+ },
254
+ );
255
+ });
256
+
257
+ // Exit edit mode when the edited run leaves the queue (it started, or was
258
+ // cancelled from another client). A dirty edit moves into the thread's own
259
+ // draft when that draft is empty; otherwise it is dropped with a toast.
260
+ useEffect(() => {
261
+ if (editing === null || activeThreadId !== editing.threadId) return;
262
+ if (serverProjection === null) return;
263
+ const run = serverProjection.runs.find((candidate) => candidate.id === editing.runId);
264
+ if (run !== undefined && run.status === "queued") return;
265
+ const recovery = recoverQueuedMessageEdit({
266
+ editTarget: queuedEditDraftTarget(routeThreadRef, editing.runId),
267
+ threadTarget: threadDraftTarget,
268
+ originalText: editing.originalText,
269
+ });
270
+ if (recovery !== "clean") {
271
+ toastManager.add(
272
+ stackedThreadToast({
273
+ type: recovery === "kept" ? "info" : "warning",
274
+ title: "Queued message is no longer queued",
275
+ description:
276
+ recovery === "kept"
277
+ ? "Your unsaved edit was kept in the composer."
278
+ : "Your unsaved edit was discarded.",
279
+ }),
280
+ );
281
+ }
282
+ // oxlint-disable-next-line react/set-state-in-effect -- Leaving edit mode follows the draft recovery and toast above, which must run once after commit.
283
+ setEditing(null);
284
+ }, [activeThreadId, editing, routeThreadRef, serverProjection, threadDraftTarget]);
285
+
286
+ /**
287
+ * Saves the composer content into the queued message being edited. Reports
288
+ * failures through `setThreadError`, which callers own because the error
289
+ * banner lives with the thread.
290
+ */
291
+ const saveEdit = async (
292
+ content: QueuedRunEditContent,
293
+ setThreadError: (threadId: ThreadId, error: string | null) => void,
294
+ ) => {
295
+ if (editing === null || saveInFlightRef.current) return;
296
+ const newAttachments = [...content.images, ...content.files];
297
+ if (
298
+ editing.existingAttachments.length + newAttachments.length >
299
+ PROVIDER_SEND_TURN_MAX_ATTACHMENTS
300
+ ) {
301
+ setThreadError(
302
+ editing.threadId,
303
+ `A message can have at most ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments.`,
304
+ );
305
+ return;
306
+ }
307
+ if (
308
+ content.prompt.trim().length === 0 &&
309
+ editing.existingAttachments.length === 0 &&
310
+ newAttachments.length === 0
311
+ ) {
312
+ return;
313
+ }
314
+ saveInFlightRef.current = true;
315
+ setIsSaving(true);
316
+ const error = await submitQueuedRunEdit({
317
+ environmentId,
318
+ draftTarget,
319
+ editing,
320
+ content,
321
+ editQueuedRun: editQueuedRunCommand,
322
+ });
323
+ saveInFlightRef.current = false;
324
+ setIsSaving(false);
325
+ setThreadError(editing.threadId, error);
326
+ if (error !== null) return;
327
+ releaseDraftAttachments(newAttachments);
328
+ promptRef.current = "";
329
+ clearEditDraft(editing.runId);
330
+ composerRef.current?.resetCursorState();
331
+ setEditing(null);
332
+ focusComposerSoon();
333
+ };
334
+
335
+ return {
336
+ editingRunId: editing?.runId ?? null,
337
+ isEditing: editing !== null,
338
+ isSaving,
339
+ draftTarget,
340
+ editingAttachments,
341
+ beginEdit,
342
+ cancelEdit,
343
+ removeEditingAttachment,
344
+ saveEdit,
345
+ };
346
+}
vite.config.ts
+1
@@ -328,6 +328,7 @@ export default defineConfig({
328
files: [
329
"apps/web/src/components/PersistentThreadTerminals.tsx",
330
"apps/web/src/components/chat/usePendingThreadRequests.ts",
331
+ "apps/web/src/components/chat/useQueuedRunEdit.ts",
332
"apps/web/src/components/chat/useUsageLimitsPanel.ts",
333
"apps/web/src/components/terminal/**",
334
],