@devries-cameron20 / t3code Mirror · read-only / commits / dd2842f238
Fork 0

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 22, 17:00 UTC

fix(web): a stale queued-edit save no longer clears a newer edit (#25128)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 25, 2026 at 16:24 UTC dd2842f238e415e030c990c1950a9c45cf827de4
4 files changed +139 -40
apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx
+44 -12
@@ -126,6 +126,16 @@ async function beginChangedEdit(hook: { current: HookResult | null }) {
126 );
127 }
128
129 +const savedContent = (prompt: string) => ({
130 + prompt,
131 + images: [],
132 + files: [],
133 + terminalContexts: [],
134 + reviewComments: [],
135 + previewAnnotations: [],
136 + threadContexts: [],
137 +});
138 +
139 const promptOf = (ref: ScopedThreadRef) =>
140 useComposerDraftStore.getState().getComposerDraft(ref)?.prompt ?? "";
141
@@ -169,18 +179,7 @@ describe("useQueuedRunEdit", () => {
179 await beginChangedEdit(hook);
180
181 // Not inside act(): act would hold the projection update until the save settles.
172 - const saved = requireHook(hook).saveEdit(
173 - {
174 - prompt: "changed",
175 - images: [],
176 - files: [],
177 - terminalContexts: [],
178 - reviewComments: [],
179 - previewAnnotations: [],
180 - threadContexts: [],
181 - },
182 - () => {},
183 - );
182 + const saved = requireHook(hook).saveEdit(savedContent("changed"), () => {});
183 await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
184 // The server applied the edit and then started the run; the projection
185 // reports the start before the edit's acknowledgement arrives.
@@ -192,4 +191,37 @@ describe("useQueuedRunEdit", () => {
191 expect(requireHook(hook).isEditing).toBe(false);
192 expect(promptOf(THREAD_A)).toBe("");
193 });
194 +
195 + it("leaves a newer edit alone when a save from before navigation finishes", async () => {
196 + const { hook } = setup();
197 + let finishSave: (result: { readonly _tag: "Success" }) => void = () => {};
198 + mocks.editQueuedRun.mockReturnValue(
199 + new Promise((resolve) => {
200 + finishSave = resolve;
201 + }),
202 + );
203 + await using screen = await render(view(THREAD_A, "queued", hook));
204 + await beginChangedEdit(hook);
205 + // Not inside act(): act would hold the rerenders until the save settles.
206 + const saved = requireHook(hook).saveEdit(savedContent("changed"), () => {});
207 + await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
208 +
209 + // Leaving the thread unmounts the chat view; coming back mounts a new one.
210 + await screen.rerender(<AppAtomRegistryProvider>{null}</AppAtomRegistryProvider>);
211 + await screen.rerender(view(THREAD_A, "queued", hook));
212 + expect(requireHook(hook).isSaving).toBe(true);
213 + await beginChangedEdit(hook);
214 + await act(() =>
215 + useComposerDraftStore.getState().setPrompt(requireHook(hook).draftTarget, "newer"),
216 + );
217 +
218 + finishSave({ _tag: "Success" });
219 + await act(() => saved);
220 +
221 + expect(requireHook(hook).editingRunId).toBe(RUN);
222 + expect(requireHook(hook).isSaving).toBe(false);
223 + expect(
224 + useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt,
225 + ).toBe("newer");
226 + });
227 });
apps/web/src/components/chat/useQueuedRunEdit.ts
+9 -14
@@ -19,7 +19,7 @@ import {
19 import { scopedThreadKey } from "@t3tools/client-runtime/environment";
20 import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
21 import { Atom } from "effect/reactivity";
22 -import { useRef, useState, type RefObject } from "react";
22 +import type { RefObject } from "react";
23 import { useAssetUrls } from "../../assets/assetUrls";
24 import {
25 DraftId,
@@ -193,8 +193,7 @@ export function useQueuedRunEdit(input: {
193 const editKey = scopedThreadKey(routeThreadRef);
194 const storedEdit = useAtomValue(queuedRunEdits.atom)[editKey] ?? null;
195 const editing = activeThreadId === null ? null : storedEdit;
196 - const saveInFlightRef = useRef(false);
197 - const [isSaving, setIsSaving] = useState(false);
196 + const isSaving = useAtomValue(queuedRunEdits.savingAtom)[editKey] === true;
197 const draftTarget =
198 editing === null ? threadDraftTarget : queuedEditDraftTarget(routeThreadRef, editing.runId);
199
@@ -299,7 +298,7 @@ export function useQueuedRunEdit(input: {
298 content: QueuedRunEditContent,
299 setThreadError: (threadId: ThreadId, error: string | null) => void,
300 ) => {
302 - if (editing === null || saveInFlightRef.current) return;
301 + if (editing === null || isSaving) return;
302 const newAttachments = [...content.images, ...content.files];
303 if (
304 editing.existingAttachments.length + newAttachments.length >
@@ -318,10 +317,9 @@ export function useQueuedRunEdit(input: {
317 ) {
318 return;
319 }
321 - saveInFlightRef.current = true;
322 - setIsSaving(true);
320 // The save's result decides the edit's fate, even if the run starts meanwhile.
324 - queuedRunEdits.suspendExitWatch(editKey);
321 + const finishSave = queuedRunEdits.startSave(editKey);
322 + if (finishSave === null) return;
323 const error = await submitQueuedRunEdit({
324 environmentId,
325 draftTarget,
@@ -329,18 +327,15 @@ export function useQueuedRunEdit(input: {
327 content,
328 editQueuedRun: editQueuedRunCommand,
329 });
332 - saveInFlightRef.current = false;
333 - setIsSaving(false);
330 setThreadError(editing.threadId, error);
335 - if (error !== null) {
336 - queuedRunEdits.resumeExitWatch(editKey);
337 - return;
338 - }
331 + const current = finishSave(error === null);
332 + if (error !== null) return;
333 releaseDraftAttachments(newAttachments);
334 + // The edit was cancelled or begun again while this save ran; its drafts are the newer edit's.
335 + if (!current) return;
336 promptRef.current = "";
337 clearEditDraft(editing.runId);
338 composerRef.current?.resetCursorState();
343 - queuedRunEdits.end(editKey);
339 focusComposerSoon();
340 };
341
packages/client-runtime/src/queuedRunEdit.test.ts
+41 -4
@@ -78,13 +78,50 @@ describe("makeQueuedRunEditStore", () => {
78 it("holds the exit during a save and replays it when the save fails", () => {
79 const { registry, runs, store, exits, begin } = setup();
80 begin();
81 - store.suspendExitWatch("env:thread");
81 + const finishSave = store.startSave("env:thread");
82 registry.set(runs, []);
83 expect(exits).toEqual([]);
84 - store.resumeExitWatch("env:thread");
84 + expect(finishSave?.(false)).toBe(true);
85 expect(exits).toHaveLength(1);
86 });
87
88 + it("allows one save at a time and ends the edit when it succeeds", () => {
89 + const { registry, store, begin } = setup();
90 + begin();
91 + const finishSave = store.startSave("env:thread");
92 + expect(registry.get(store.savingAtom)).toEqual({ "env:thread": true });
93 + expect(store.startSave("env:thread")).toBeNull();
94 + expect(finishSave?.(true)).toBe(true);
95 + expect(store.get("env:thread")).toBeNull();
96 + expect(registry.get(store.savingAtom)).toEqual({});
97 + });
98 +
99 + it("leaves an edit begun again during a save to that edit", () => {
100 + const { registry, runs, store, exits, begin } = setup();
101 + begin();
102 + const finishStale = store.startSave("env:thread");
103 + begin();
104 + store.update("env:thread", (edit) => ({ ...edit, text: "newer" }));
105 + expect(registry.get(store.savingAtom)).toEqual({});
106 +
107 + expect(finishStale?.(true)).toBe(false);
108 + expect(finishStale?.(false)).toBe(false);
109 + expect(store.get("env:thread")).toEqual({ runId: RUN, text: "newer" });
110 + registry.set(runs, []);
111 + expect(exits).toEqual([{ threadKey: "env:thread", text: "newer" }]);
112 + });
113 +
114 + it("does not revive a cancelled edit when its save fails", () => {
115 + const { registry, runs, store, exits, begin } = setup();
116 + begin();
117 + const finishSave = store.startSave("env:thread");
118 + store.end("env:thread");
119 + expect(finishSave?.(false)).toBe(false);
120 + registry.set(runs, []);
121 + expect(exits).toEqual([]);
122 + expect(registry.get(store.savingAtom)).toEqual({});
123 + });
124 +
125 // The runs read the thread's detail, a live server subscription; a thread
126 // with no edit open must not keep it.
127 it("holds the thread's runs only while an edit is open and watching", () => {
@@ -122,10 +159,10 @@ describe("makeQueuedRunEditStore", () => {
159 expect(mounted).toBe(0);
160
161 begin();
125 - store.suspendExitWatch("env:thread");
162 + const finishSave = store.startSave("env:thread");
163 settle();
164 expect(mounted).toBe(0);
128 - store.resumeExitWatch("env:thread");
165 + finishSave?.(false);
166 expect(mounted).toBe(1);
167
168 registry.set(source, []);
packages/client-runtime/src/queuedRunEdit.ts
+45 -10
@@ -1,7 +1,8 @@
1 /**
2 * A queued-message edit ends on save, cancel, or when its run leaves the queue.
3 * The store owns one watcher per edit, so "run left the queue" is handled exactly
4 - * once, when the projection reports it, wherever the user is in the app.
4 + * once, when the projection reports it, wherever the user is in the app. It also
5 + * owns the edit's save, because a save outlives the view that started it.
6 */
7 import type { RunId } from "@t3tools/contracts";
8 import { Atom, type AtomRegistry } from "effect/reactivity";
@@ -67,6 +68,14 @@ interface ExitWatch<E> {
68 cancel: (() => void) | null;
69 }
70
71 +/**
72 + * Settles a save started with `startSave`. Returns false, changing nothing,
73 + * when the edit the save started from was ended or begun again meanwhile; the
74 + * caller must then leave the edit's drafts alone. Otherwise success ends the
75 + * edit and failure resumes its exit watch.
76 + */
77 +export type FinishQueuedRunEditSave = (succeeded: boolean) => boolean;
78 +
79 export function makeQueuedRunEditStore<E extends { readonly runId: RunId }>(options: {
80 readonly registry: AtomRegistry.AtomRegistry;
81 readonly label: string;
@@ -76,8 +85,22 @@ export function makeQueuedRunEditStore<E extends { readonly runId: RunId }>(opti
85 Atom.keepAlive,
86 Atom.withLabel(options.label),
87 );
88 + const savingAtom = Atom.make<Readonly<Record<string, true>>>({}).pipe(
89 + Atom.keepAlive,
90 + Atom.withLabel(`${options.label}-saving`),
91 + );
92 + // Each begin creates a new watch, so the watch is the edit's identity.
93 const watches = new Map<string, ExitWatch<E>>();
94
95 + const setSaving = (threadKey: string, saving: boolean) => {
96 + const current = registry.get(savingAtom);
97 + if (threadKey in current === saving) return;
98 + const next = { ...current };
99 + if (saving) next[threadKey] = true;
100 + else delete next[threadKey];
101 + registry.set(savingAtom, next);
102 + };
103 +
104 const get = (threadKey: string | null): E | null =>
105 threadKey === null ? null : (registry.get(atom)[threadKey] ?? null);
106
@@ -118,10 +141,13 @@ export function makeQueuedRunEditStore<E extends { readonly runId: RunId }>(opti
141 if (watch === undefined) return;
142 unsubscribe(watch);
143 watches.delete(threadKey);
144 + setSaving(threadKey, false);
145 };
146
147 return {
148 atom,
149 + /** Thread keys whose edit has a save in flight. */
150 + savingAtom,
151 get,
152 /**
153 * Starts an edit, replacing any edit already open on the thread. When the
@@ -151,17 +177,26 @@ export function makeQueuedRunEditStore<E extends { readonly runId: RunId }>(opti
177 write(threadKey, null);
178 },
179 /**
154 - * Holds the exit transition while a save is in flight; the save's own
155 - * result decides the edit's fate.
180 + * Claims the open edit for a save, or returns null when there is no edit
181 + * or a save already holds it. The exit watch pauses so the save's result
182 + * decides the edit's fate.
183 */
157 - suspendExitWatch(threadKey: string) {
184 + startSave(threadKey: string): FinishQueuedRunEditSave | null {
185 const watch = watches.get(threadKey);
159 - if (watch !== undefined) unsubscribe(watch);
160 - },
161 - /** Resumes after a failed save, handling an exit that happened meanwhile. */
162 - resumeExitWatch(threadKey: string) {
163 - const watch = watches.get(threadKey);
164 - if (watch !== undefined && watch.cancel === null) subscribe(threadKey, watch);
186 + if (watch === undefined || threadKey in registry.get(savingAtom)) return null;
187 + setSaving(threadKey, true);
188 + unsubscribe(watch);
189 + return (succeeded) => {
190 + if (watches.get(threadKey) !== watch) return false;
191 + if (succeeded) {
192 + stopWatch(threadKey);
193 + write(threadKey, null);
194 + } else {
195 + setSaving(threadKey, false);
196 + subscribe(threadKey, watch);
197 + }
198 + return true;
199 + };
200 },
201 };
202 }