Skip to content

Commit 597f74c

Browse files
fix(web): a stale queued-edit save no longer clears a newer edit
#24972 moved queued-message edits into a shared store so they survive navigation, but the save lock stayed in the chat view. Repro: 1. Start a slow save of a queued edit. 2. Navigate away from the thread. 3. Come back and edit the same message again. 4. The first save finishes, clears the newer edit's draft and ends it. The remounted view had a fresh lock, and the finishing save only knew the thread key, not which edit it belonged to. The queued-run edit store now owns saves. startSave claims the open edit (one save at a time, exposed through savingAtom for isSaving) and returns a finisher bound to that edit's identity. When the save settles after its edit was ended or begun again, the finisher changes nothing and returns false, so the hook leaves the newer edit and its draft alone. This replaces suspendExitWatch/resumeExitWatch; the rest of the design is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent b76a110 commit 597f74c

4 files changed

Lines changed: 139 additions & 40 deletions

File tree

‎apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx‎

Lines changed: 44 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,16 @@ async function beginChangedEdit(hook: { current: HookResult | null }) {
126126
);
127127
}
128128

129+
const savedContent = (prompt: string) => ({
130+
prompt,
131+
images: [],
132+
files: [],
133+
terminalContexts: [],
134+
reviewComments: [],
135+
previewAnnotations: [],
136+
threadContexts: [],
137+
});
138+
129139
const promptOf = (ref: ScopedThreadRef) =>
130140
useComposerDraftStore.getState().getComposerDraft(ref)?.prompt ?? "";
131141

@@ -169,18 +179,7 @@ describe("useQueuedRunEdit", () => {
169179
await beginChangedEdit(hook);
170180

171181
// 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"), () => {});
184183
await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
185184
// The server applied the edit and then started the run; the projection
186185
// reports the start before the edit's acknowledgement arrives.
@@ -192,4 +191,37 @@ describe("useQueuedRunEdit", () => {
192191
expect(requireHook(hook).isEditing).toBe(false);
193192
expect(promptOf(THREAD_A)).toBe("");
194193
});
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+
});
195227
});

‎apps/web/src/components/chat/useQueuedRunEdit.ts‎

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import {
1919
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2020
import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
2121
import { Atom } from "effect/reactivity";
22-
import { useRef, useState, type RefObject } from "react";
22+
import type { RefObject } from "react";
2323
import { useAssetUrls } from "../../assets/assetUrls";
2424
import {
2525
DraftId,
@@ -193,8 +193,7 @@ export function useQueuedRunEdit(input: {
193193
const editKey = scopedThreadKey(routeThreadRef);
194194
const storedEdit = useAtomValue(queuedRunEdits.atom)[editKey] ?? null;
195195
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;
198197
const draftTarget =
199198
editing === null ? threadDraftTarget : queuedEditDraftTarget(routeThreadRef, editing.runId);
200199

@@ -299,7 +298,7 @@ export function useQueuedRunEdit(input: {
299298
content: QueuedRunEditContent,
300299
setThreadError: (threadId: ThreadId, error: string | null) => void,
301300
) => {
302-
if (editing === null || saveInFlightRef.current) return;
301+
if (editing === null || isSaving) return;
303302
const newAttachments = [...content.images, ...content.files];
304303
if (
305304
editing.existingAttachments.length + newAttachments.length >
@@ -318,29 +317,25 @@ export function useQueuedRunEdit(input: {
318317
) {
319318
return;
320319
}
321-
saveInFlightRef.current = true;
322-
setIsSaving(true);
323320
// 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;
325323
const error = await submitQueuedRunEdit({
326324
environmentId,
327325
draftTarget,
328326
editing,
329327
content,
330328
editQueuedRun: editQueuedRunCommand,
331329
});
332-
saveInFlightRef.current = false;
333-
setIsSaving(false);
334330
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;
339333
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;
340336
promptRef.current = "";
341337
clearEditDraft(editing.runId);
342338
composerRef.current?.resetCursorState();
343-
queuedRunEdits.end(editKey);
344339
focusComposerSoon();
345340
};
346341

‎packages/client-runtime/src/queuedRunEdit.test.ts‎

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -78,13 +78,50 @@ describe("makeQueuedRunEditStore", () => {
7878
it("holds the exit during a save and replays it when the save fails", () => {
7979
const { registry, runs, store, exits, begin } = setup();
8080
begin();
81-
store.suspendExitWatch("env:thread");
81+
const finishSave = store.startSave("env:thread");
8282
registry.set(runs, []);
8383
expect(exits).toEqual([]);
84-
store.resumeExitWatch("env:thread");
84+
expect(finishSave?.(false)).toBe(true);
8585
expect(exits).toHaveLength(1);
8686
});
8787

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+
88125
// The runs read the thread's detail, a live server subscription; a thread
89126
// with no edit open must not keep it.
90127
it("holds the thread's runs only while an edit is open and watching", () => {
@@ -122,10 +159,10 @@ describe("makeQueuedRunEditStore", () => {
122159
expect(mounted).toBe(0);
123160

124161
begin();
125-
store.suspendExitWatch("env:thread");
162+
const finishSave = store.startSave("env:thread");
126163
settle();
127164
expect(mounted).toBe(0);
128-
store.resumeExitWatch("env:thread");
165+
finishSave?.(false);
129166
expect(mounted).toBe(1);
130167

131168
registry.set(source, []);

‎packages/client-runtime/src/queuedRunEdit.ts‎

Lines changed: 45 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
/**
22
* A queued-message edit ends on save, cancel, or when its run leaves the queue.
33
* 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.
56
*/
67
import type { RunId } from "@t3tools/contracts";
78
import { Atom, type AtomRegistry } from "effect/reactivity";
@@ -67,6 +68,14 @@ interface ExitWatch<E> {
6768
cancel: (() => void) | null;
6869
}
6970

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+
7079
export function makeQueuedRunEditStore<E extends { readonly runId: RunId }>(options: {
7180
readonly registry: AtomRegistry.AtomRegistry;
7281
readonly label: string;
@@ -76,8 +85,22 @@ export function makeQueuedRunEditStore<E extends { readonly runId: RunId }>(opti
7685
Atom.keepAlive,
7786
Atom.withLabel(options.label),
7887
);
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.
7993
const watches = new Map<string, ExitWatch<E>>();
8094

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+
81104
const get = (threadKey: string | null): E | null =>
82105
threadKey === null ? null : (registry.get(atom)[threadKey] ?? null);
83106

@@ -118,10 +141,13 @@ export function makeQueuedRunEditStore<E extends { readonly runId: RunId }>(opti
118141
if (watch === undefined) return;
119142
unsubscribe(watch);
120143
watches.delete(threadKey);
144+
setSaving(threadKey, false);
121145
};
122146

123147
return {
124148
atom,
149+
/** Thread keys whose edit has a save in flight. */
150+
savingAtom,
125151
get,
126152
/**
127153
* 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
151177
write(threadKey, null);
152178
},
153179
/**
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.
156183
*/
157-
suspendExitWatch(threadKey: string) {
184+
startSave(threadKey: string): FinishQueuedRunEditSave | null {
158185
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+
};
165200
},
166201
};
167202
}

0 commit comments

Comments
 (0)