Skip to content

Commit a371e6e

Browse files
fix(web): switching a file between markdown and the editor no longer saves a draft twice
Each file surface (the editor and rendered markdown) built its own save coordinator in useFileSaveCoordinator, set up in an effect and recovering unsaved drafts in a second effect. Switching surfaces with an edit pending disposed the old coordinator, which flushed the draft, and the new one read the same still-unconfirmed draft from the query cache and wrote it again. Save sessions now live in a keyed store (fileSaveSessions.ts), one per file. Each surface holds a lease on its file's session with one explicit effect (useFileSaveSession); React runs every unmount cleanup before mount setups in a commit, so the last surface to leave flushes before the next one recovers. A session created while that flush is in flight skips the draft it is writing, and picks it back up if that flush fails. Regaining write access is a registry subscription on the session state instead of a re-render-driven effect. Effects: useFileSaveCoordinator.ts 2 -> 0 (file deleted, along with its render-phase setState that rebuilt the session on identity change); fileSaveSessions.ts 0 -> 1 (the lease); FilePreviewPanel.tsx unchanged at 3. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 5522180 commit a371e6e

6 files changed

Lines changed: 453 additions & 286 deletions

File tree

‎apps/web/src/components/files/FilePreviewPanel.tsx‎

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ import {
117117
shouldShowFileExplorer,
118118
workspaceAssetResource,
119119
} from "./filePreviewMode";
120-
import { useFileSaveCoordinator } from "./useFileSaveCoordinator";
120+
import { changeFileSaveSession, useFileSaveSession } from "./fileSaveSessions";
121121
import { revisionedQuery } from "~/state/revisionedQuery";
122122
import {
123123
getOptimisticProjectFileQueryData,
@@ -675,12 +675,8 @@ function EditableFileSurface({
675675
};
676676
const surfaceRef = useRef<HTMLDivElement>(null);
677677
const selectionFrameRef = useRef<number | null>(null);
678-
const saveCoordinator = useFileSaveCoordinator({
679-
environmentId,
680-
cwd,
681-
relativePath,
682-
onPendingChange,
683-
});
678+
const saveTarget = { environmentId, cwd, relativePath };
679+
useFileSaveSession(saveTarget, onPendingChange);
684680
// Retain file identity for echoed editor changes; only external changes replace the editor's draft.
685681
const [externalFile, setExternalFile] = useState(() =>
686682
editableFileContents(environmentId, cwd, relativePath, contents),
@@ -709,7 +705,7 @@ function EditableFileSurface({
709705
if (file.contents === getProjectFileContents(environmentId, cwd, relativePath)) return;
710706
setEditedContents(file.contents);
711707
setProjectFileQueryData(environmentId, cwd, relativePath, file.contents);
712-
saveCoordinator.change(file.contents);
708+
changeFileSaveSession(saveTarget, file.contents);
713709
if (!nextLineAnnotations) return;
714710
const remapped = remapFileCommentAnnotations(nextLineAnnotations);
715711
// The editor hands back the array it was given until an edit moves an annotation.
@@ -926,12 +922,8 @@ function RenderedMarkdownSurface({
926922
readOnly: boolean;
927923
workspaceMutationId: string | null;
928924
}) {
929-
const saveCoordinator = useFileSaveCoordinator({
930-
environmentId,
931-
cwd,
932-
relativePath,
933-
onPendingChange,
934-
});
925+
const saveTarget = { environmentId, cwd, relativePath };
926+
useFileSaveSession(saveTarget, onPendingChange);
935927

936928
return (
937929
<ScrollArea className="min-h-0 flex-1">
@@ -951,7 +943,7 @@ function RenderedMarkdownSurface({
951943
const nextContents = setMarkdownTaskChecked(currentContents, markerOffset, checked);
952944
if (nextContents === currentContents) return;
953945
setProjectFileQueryData(environmentId, cwd, relativePath, nextContents);
954-
saveCoordinator.change(nextContents);
946+
changeFileSaveSession(saveTarget, nextContents);
955947
}
956948
}
957949
/>
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import { render, fakeTimers } from "../../../test/render";
2+
import { EnvironmentId } from "@t3tools/contracts";
3+
import { AsyncResult } from "effect/reactivity";
4+
import { StrictMode } from "react";
5+
import { describe, expect, it, vi } from "vite-plus/test";
6+
7+
const { runAtomCommand, getUnsavedFile } = vi.hoisted(() => ({
8+
runAtomCommand: vi.fn(),
9+
getUnsavedFile: vi.fn(),
10+
}));
11+
vi.mock(import("@t3tools/client-runtime/state/runtime"), async (original) => ({
12+
...(await original()),
13+
runAtomCommand: runAtomCommand as never,
14+
}));
15+
vi.mock(import("~/state/session"), async (original) => ({
16+
...(await original()),
17+
readEnvironmentScope: () => true,
18+
}));
19+
vi.mock(import("./projectFilesQueryState"), async (original) => ({
20+
...(await original()),
21+
confirmProjectFileQueryData: () => true,
22+
getUnsavedProjectFileQueryData: getUnsavedFile,
23+
}));
24+
25+
import { changeFileSaveSession, useFileSaveSession } from "./fileSaveSessions";
26+
27+
const target = {
28+
environmentId: EnvironmentId.make("file-save-sessions-browser"),
29+
cwd: "/workspace",
30+
relativePath: "README.md",
31+
};
32+
const onPendingChange = vi.fn();
33+
34+
// The editor and rendered-markdown surfaces are different component types, so
35+
// switching between them unmounts one session holder and mounts another.
36+
function EditorSurface() {
37+
useFileSaveSession({ ...target }, onPendingChange);
38+
return <div>editor</div>;
39+
}
40+
function MarkdownSurface() {
41+
useFileSaveSession({ ...target }, onPendingChange);
42+
return <div>markdown</div>;
43+
}
44+
45+
describe("file save sessions in React", () => {
46+
it("writes a pending draft once when the file switches surfaces under StrictMode", async () => {
47+
let finishWrite = () => {};
48+
runAtomCommand.mockReset().mockImplementation(
49+
() =>
50+
new Promise((resolve) => {
51+
finishWrite = () => resolve(AsyncResult.success(undefined));
52+
}),
53+
);
54+
getUnsavedFile.mockReset().mockReturnValue(null);
55+
await using screen = await render(
56+
<StrictMode>
57+
<EditorSurface />
58+
</StrictMode>,
59+
{ router: false }, // no routes involved; the surfaces are bare effect hosts
60+
);
61+
using _timers = fakeTimers();
62+
// An edit lands in the query cache, unconfirmed until its write settles.
63+
getUnsavedFile.mockReturnValue({ contents: "draft" });
64+
changeFileSaveSession(target, "draft");
65+
66+
await screen.rerender(
67+
<StrictMode>
68+
<MarkdownSurface />
69+
</StrictMode>,
70+
);
71+
finishWrite();
72+
getUnsavedFile.mockReturnValue(null);
73+
await vi.runAllTimersAsync();
74+
75+
expect(runAtomCommand.mock.calls.map(([, , request]) => request)).toEqual([
76+
{
77+
environmentId: target.environmentId,
78+
input: { cwd: "/workspace", relativePath: "README.md", contents: "draft" },
79+
},
80+
]);
81+
expect(onPendingChange).toHaveBeenLastCalledWith("README.md", false);
82+
});
83+
});
Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
import { EnvironmentId } from "@t3tools/contracts";
2+
import { Cause } from "effect";
3+
import { AsyncResult } from "effect/reactivity";
4+
import { describe, expect, it, vi } from "vite-plus/test";
5+
6+
import {
7+
createFileSaveSessions,
8+
type FileSaveSessionDeps,
9+
type FileSaveTarget,
10+
} from "./fileSaveSessions";
11+
12+
const target: FileSaveTarget = {
13+
environmentId: EnvironmentId.make("file-save-sessions"),
14+
cwd: "/workspace",
15+
relativePath: "file.txt",
16+
};
17+
18+
function setup() {
19+
vi.useFakeTimers();
20+
const state = {
21+
writable: true,
22+
unsaved: null as string | null,
23+
onWritable: [] as Array<() => void>,
24+
};
25+
const persist = vi.fn<FileSaveSessionDeps["persist"]>(async () => AsyncResult.success(undefined));
26+
const confirm = vi.fn((_target: FileSaveTarget, _contents: string) => true);
27+
const onPendingChange = vi.fn();
28+
const sessions = createFileSaveSessions({
29+
debounceMs: 500,
30+
canPersist: () => state.writable,
31+
subscribeWritable: (_target, onWritable) => {
32+
state.onWritable.push(onWritable);
33+
return () => {
34+
state.onWritable = state.onWritable.filter((listener) => listener !== onWritable);
35+
};
36+
},
37+
persist,
38+
confirm,
39+
readUnsaved: () => state.unsaved,
40+
});
41+
const writes = () => persist.mock.calls.map(([written, contents]) => [written, contents]);
42+
return {
43+
state,
44+
sessions,
45+
persist,
46+
confirm,
47+
onPendingChange,
48+
writes,
49+
[Symbol.dispose]: () => vi.useRealTimers(),
50+
};
51+
}
52+
53+
describe("file save sessions", () => {
54+
it("debounces edits and clears the pending marker once confirmed", async () => {
55+
using h = setup();
56+
h.sessions.acquire(target, h.onPendingChange);
57+
h.sessions.change(target, "a");
58+
h.sessions.change(target, "ab");
59+
expect(h.onPendingChange).toHaveBeenLastCalledWith("file.txt", true);
60+
await vi.advanceTimersByTimeAsync(500);
61+
expect(h.writes()).toEqual([[target, "ab"]]);
62+
expect(h.onPendingChange).toHaveBeenLastCalledWith("file.txt", false);
63+
});
64+
65+
it("flushes on the last release and drops edits from retired editors", async () => {
66+
using h = setup();
67+
const releaseFirst = h.sessions.acquire(target, h.onPendingChange);
68+
const releaseSecond = h.sessions.acquire(target, h.onPendingChange);
69+
h.sessions.change(target, "pending edit");
70+
releaseFirst();
71+
expect(h.persist).not.toHaveBeenCalled();
72+
releaseSecond();
73+
h.sessions.change(target, "stale editor contents");
74+
await vi.runAllTimersAsync();
75+
expect(h.writes()).toEqual([[target, "pending edit"]]);
76+
expect(h.onPendingChange).toHaveBeenLastCalledWith("file.txt", false);
77+
});
78+
79+
it("gives a replaced file a fresh session and flushes the old one", async () => {
80+
using h = setup();
81+
const other = { ...target, relativePath: "other.txt" };
82+
const release = h.sessions.acquire(target, h.onPendingChange);
83+
h.sessions.change(target, "old file edit");
84+
release();
85+
h.sessions.acquire(other, h.onPendingChange);
86+
h.sessions.change(target, "stale editor contents");
87+
h.sessions.change(other, "new file edit");
88+
await vi.runAllTimersAsync();
89+
expect(h.writes()).toEqual([
90+
[target, "old file edit"],
91+
[other, "new file edit"],
92+
]);
93+
});
94+
95+
it("resumes an unsaved draft when a session is created", async () => {
96+
using h = setup();
97+
h.state.unsaved = "pending draft";
98+
h.sessions.acquire(target, h.onPendingChange);
99+
expect(h.onPendingChange).toHaveBeenLastCalledWith("file.txt", true);
100+
await vi.advanceTimersByTimeAsync(500);
101+
expect(h.writes()).toEqual([[target, "pending draft"]]);
102+
});
103+
104+
it("does not queue a draft that a retired session is still writing", async () => {
105+
using h = setup();
106+
let finishWrite = () => {};
107+
h.persist.mockImplementationOnce(
108+
() =>
109+
new Promise((resolve) => {
110+
finishWrite = () => resolve(AsyncResult.success(undefined));
111+
}),
112+
);
113+
const release = h.sessions.acquire(target, h.onPendingChange);
114+
h.sessions.change(target, "draft");
115+
h.state.unsaved = "draft";
116+
release();
117+
// A StrictMode ref replay reacquires while the flush is in flight.
118+
h.sessions.acquire(target, h.onPendingChange);
119+
finishWrite();
120+
await vi.runAllTimersAsync();
121+
expect(h.writes()).toEqual([[target, "draft"]]);
122+
});
123+
124+
it("stops notifying a surface's listener once it releases a shared session", async () => {
125+
using h = setup();
126+
const retiredListener = vi.fn();
127+
const release = h.sessions.acquire(target, retiredListener);
128+
h.sessions.acquire(target, h.onPendingChange);
129+
release();
130+
h.sessions.change(target, "edit");
131+
await vi.runAllTimersAsync();
132+
expect(retiredListener).not.toHaveBeenCalled();
133+
expect(h.onPendingChange).toHaveBeenLastCalledWith("file.txt", false);
134+
});
135+
136+
it("requeues a draft whose retired flush failed on the live session", async () => {
137+
using h = setup();
138+
let failWrite = () => {};
139+
h.persist.mockImplementationOnce(
140+
() =>
141+
new Promise((resolve) => {
142+
failWrite = () => resolve(AsyncResult.failure(Cause.fail("offline")));
143+
}),
144+
);
145+
const release = h.sessions.acquire(target, h.onPendingChange);
146+
h.sessions.change(target, "draft");
147+
h.state.unsaved = "draft";
148+
release();
149+
h.sessions.acquire(target, h.onPendingChange);
150+
failWrite();
151+
await vi.runAllTimersAsync();
152+
expect(h.writes()).toEqual([
153+
[target, "draft"],
154+
[target, "draft"],
155+
]);
156+
expect(h.onPendingChange).toHaveBeenLastCalledWith("file.txt", false);
157+
});
158+
159+
it("keeps edits pending while unwritable and resumes them when access returns", async () => {
160+
using h = setup();
161+
h.sessions.acquire(target, h.onPendingChange);
162+
h.state.writable = false;
163+
h.sessions.change(target, "pending edit");
164+
h.state.unsaved = "pending edit";
165+
await vi.runAllTimersAsync();
166+
expect(h.persist).not.toHaveBeenCalled();
167+
expect(h.onPendingChange).toHaveBeenLastCalledWith("file.txt", true);
168+
169+
h.state.writable = true;
170+
for (const onWritable of h.state.onWritable) onWritable();
171+
await vi.advanceTimersByTimeAsync(500);
172+
expect(h.writes()).toEqual([[target, "pending edit"]]);
173+
expect(h.onPendingChange).toHaveBeenLastCalledWith("file.txt", false);
174+
});
175+
176+
it("skips recovery while unwritable and stops watching access after release", async () => {
177+
using h = setup();
178+
h.state.writable = false;
179+
h.state.unsaved = "pending draft";
180+
const release = h.sessions.acquire(target, h.onPendingChange);
181+
expect(h.onPendingChange).not.toHaveBeenCalled();
182+
release();
183+
expect(h.state.onWritable).toEqual([]);
184+
await vi.runAllTimersAsync();
185+
expect(h.persist).not.toHaveBeenCalled();
186+
});
187+
});

0 commit comments

Comments
 (0)