@devries-cameron20 / t3code Mirror · read-only / commits / 8cb551a3ce
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 21, 14:45 UTC

fix(web): saved files show external edits after a failed reload (#36664)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Wout Stiens committed Nov 14, 2026 at 12:32 UTC 8cb551a3cec68767054b67b790b8293ac1e7859a
4 files changed +246 -33
apps/web/src/components/files/projectFilesQueryState.ts
+6 -15
@@ -15,7 +15,6 @@ import { appAtomRegistry } from "~/rpc/atomRegistry";
15 import { useFilesystemReadAccess } from "~/state/filesystem";
16 import { projectEnvironment } from "~/state/projects";
17 import { useProjectPathSearch } from "~/state/queries";
18 -import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
18 import { revisionedQuery } from "~/state/revisionedQuery";
19
20 const EMPTY_PROJECT_FILE_PATH = "";
@@ -92,7 +91,7 @@ export function setProjectFileQueryData(
91 unsavedFileMounts.set(atom, appAtomRegistry.mount(atom));
92 }
93 appAtomRegistry.set(atom, {
95 - confirmedAgainst: undefined,
94 + saved: false,
95 data: {
96 relativePath,
97 contents,
@@ -128,7 +127,7 @@ export function getUnsavedProjectFileQueryData(
127 relativePath: string,
128 ): ProjectReadFileResult | null {
129 const optimistic = appAtomRegistry.get(optimisticFileAtom(environmentId, cwd, relativePath));
131 - return optimistic?.confirmedAgainst === undefined ? (optimistic?.data ?? null) : null;
130 + return !optimistic?.saved ? (optimistic?.data ?? null) : null;
131 }
132
133 export function confirmProjectFileQueryData(
@@ -142,21 +141,13 @@ export function confirmProjectFileQueryData(
141 if (optimisticFile?.data.contents !== contents) return false;
142
143 const queryAtom = getProjectFileQueryAtom(environmentId, cwd, relativePath);
145 - const confirmed = {
144 + appAtomRegistry.set(atom, {
145 ...optimisticFile,
147 - confirmedAgainst: appAtomRegistry.get(queryAtom),
148 - };
149 - appAtomRegistry.set(atom, confirmed);
146 + saved: true,
147 + confirmingQuery: queryAtom,
148 + });
149 releaseUnsavedFile(atom);
150 appAtomRegistry.refresh(queryAtom);
152 - void executeAtomQuery(appAtomRegistry, queryAtom, {
153 - reportDefect: false,
154 - reportFailure: false,
155 - }).then((result) => {
156 - if (result._tag === "Success" && appAtomRegistry.get(atom) === confirmed) {
157 - appAtomRegistry.set(atom, null);
158 - }
159 - });
151 return true;
152 }
153
packages/client-runtime/src/state/projectCommands.test.ts
+106 -1
@@ -3,6 +3,7 @@ import {
3 AuthFilesystemWriteScope,
4 EnvironmentId,
5 ProjectId,
6 + ProjectReadFileError,
7 ProjectReadFileInput,
8 ProjectReadFileResult,
9 ThreadId,
@@ -49,7 +50,7 @@ const makeHarness = Effect.fn("TestProjectCommands.makeHarness")(function* () {
50 const metadataRequests: string[][] = [];
51 const file = { byteLength: 5 };
52 const readResponse = {
52 - wait: Effect.void as Effect.Effect<void>,
53 + wait: Effect.void as Effect.Effect<void, ProjectReadFileError>,
54 missing: false,
55 };
56 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
@@ -146,6 +147,110 @@ const makeHarness = Effect.fn("TestProjectCommands.makeHarness")(function* () {
147 });
148
149 describe("writeFile metadata", () => {
150 + it.effect("retires a saved overlay after an equal read succeeds, preserving newer drafts", () =>
151 + Effect.gen(function* () {
152 + const h = yield* makeHarness();
153 + const target = { environmentId: ENVIRONMENT_ID, cwd: "/repo", relativePath: "foo" };
154 + const query = h.commands.readFile({
155 + environmentId: ENVIRONMENT_ID,
156 + input: { cwd: target.cwd, relativePath: target.relativePath },
157 + });
158 + h.registry.mount(query);
159 + const read = () => AtomRegistry.getResult(h.registry, query, { suspendOnWaiting: true });
160 + const original = yield* read();
161 + const overlay = h.commands.optimisticFile(target);
162 + h.registry.mount(overlay);
163 + const saved = { ...original, contents: "saved" };
164 + h.registry.set(overlay, { data: saved, saved: true, confirmingQuery: query });
165 + h.readResponse.wait = Effect.fail(
166 + new ProjectReadFileError({
167 + cwd: "/repo",
168 + relativePath: "foo",
169 + failure: "operation_failed",
170 + }),
171 + );
172 + h.registry.refresh(query);
173 + yield* Effect.exit(read());
174 + expect(h.registry.get(overlay)?.data.contents).toBe("saved");
175 +
176 + h.readResponse.wait = Effect.void;
177 + h.registry.refresh(query);
178 + const refreshed = yield* read();
179 + // The production query shares equal file values across this failed confirmation.
180 + expect(refreshed).toBe(original);
181 + expect(h.registry.get(overlay)).toBeNull();
182 +
183 + h.registry.set(overlay, { data: { ...saved, contents: "newer draft" }, saved: false });
184 + h.registry.refresh(query);
185 + yield* read();
186 + expect(h.registry.get(overlay)?.data.contents).toBe("newer draft");
187 + }),
188 + );
189 +
190 + it.effect.each([true, false])(
191 + "keeps a saved overlay when an older read uses different allowMissing options (confirmation: %s)",
192 + (allowMissing) =>
193 + Effect.gen(function* () {
194 + const h = yield* makeHarness();
195 + const target = { environmentId: ENVIRONMENT_ID, cwd: "/repo", relativePath: "foo" };
196 + const query = h.commands.readFile({
197 + environmentId: ENVIRONMENT_ID,
198 + input: {
199 + cwd: target.cwd,
200 + relativePath: target.relativePath,
201 + ...(allowMissing ? { allowMissing: true } : {}),
202 + },
203 + });
204 + const otherQuery = h.commands.readFile({
205 + environmentId: ENVIRONMENT_ID,
206 + input: {
207 + cwd: target.cwd,
208 + relativePath: target.relativePath,
209 + ...(!allowMissing ? { allowMissing: true } : {}),
210 + },
211 + });
212 + const read = (atom: typeof query) =>
213 + AtomRegistry.getResult(h.registry, atom, { suspendOnWaiting: true });
214 + h.registry.mount(query);
215 + const original = yield* read(query);
216 + const overlay = h.commands.optimisticFile(target);
217 + h.registry.mount(overlay);
218 + const started = yield* Deferred.make<void>();
219 + const release = yield* Deferred.make<void>();
220 + h.readResponse.wait = Deferred.succeed(started, undefined).pipe(
221 + Effect.andThen(Deferred.await(release)),
222 + );
223 + h.registry.mount(otherQuery);
224 + const olderRead = yield* read(otherQuery).pipe(Effect.forkChild);
225 + yield* Deferred.await(started);
226 + h.registry.set(overlay, {
227 + data: { ...original, contents: "saved" },
228 + saved: true,
229 + confirmingQuery: query,
230 + });
231 + h.readResponse.wait = Effect.fail(
232 + new ProjectReadFileError({
233 + cwd: target.cwd,
234 + relativePath: target.relativePath,
235 + failure: "operation_failed",
236 + }),
237 + );
238 + h.registry.refresh(query);
239 + yield* Effect.exit(read(query));
240 + expect(h.registry.get(overlay)?.data.contents).toBe("saved");
241 +
242 + yield* Deferred.succeed(release, undefined);
243 + yield* Fiber.join(olderRead);
244 + expect(h.registry.get(overlay)?.data.contents).toBe("saved");
245 + expect(Option.getOrNull(AsyncResult.value(h.registry.get(query)))).toBe(original);
246 +
247 + h.readResponse.wait = Effect.void;
248 + h.registry.refresh(query);
249 + expect(yield* read(query)).toBe(original);
250 + expect(h.registry.get(overlay)).toBeNull();
251 + }),
252 + );
253 +
254 it.effect("preserves optional read results without seeding metadata for an absent file", () =>
255 Effect.gen(function* () {
256 const h = yield* makeHarness();
packages/client-runtime/src/state/projectCommands.ts
+33 -17
@@ -37,10 +37,16 @@ export type {
37 UpdateProjectInput,
38 } from "../operations/commands.ts";
39
40 -export interface OptimisticProjectFile {
40 +export type OptimisticProjectFile = {
41 readonly data: ProjectReadFileResult;
42 - readonly confirmedAgainst: object | null | undefined;
43 -}
42 +} & (
43 + | { readonly saved: false }
44 + | {
45 + readonly saved: true;
46 + /** Only this query's next successful answer can replace the saved contents. */
47 + readonly confirmingQuery: Atom.Atom<unknown>;
48 + }
49 +);
50
51 export interface OptimisticProjectFileTarget {
52 readonly environmentId: EnvironmentId;
@@ -86,6 +92,29 @@ export function createProjectEnvironmentAtoms<R, E>(
92 Atom.withLabel(`environment-data:projects:optimistic-file:${key}`),
93 ),
94 );
95 + const readFile = createEnvironmentRpcQueryAtomFamily(runtime, {
96 + label: "environment-data:projects:read-file",
97 + tag: WS_METHODS.projectsReadFile,
98 + staleTimeMs: 30_000,
99 + idleTtlMs: 5 * 60_000,
100 + onAnswer: (target, _value, registry): Effect.Effect<void> =>
101 + Effect.sync(() => {
102 + const atom = optimisticFileFamily(
103 + optimisticProjectFileKey({ environmentId: target.environmentId, ...target.input }),
104 + );
105 + const overlay = registry.get(atom);
106 + if (overlay?.saved && overlay.confirmingQuery === readFile(target))
107 + registry.set(atom, null);
108 + }),
109 + execute: (input) =>
110 + fileMetadata.seedAfterRead(
111 + request(WS_METHODS.projectsReadFile, input),
112 + (result, isCurrent) =>
113 + result.exists === false
114 + ? Effect.void
115 + : fileMetadata.rememberFile(input.cwd, result, isCurrent),
116 + ),
117 + });
118 const projectConcurrency = {
119 mode: "serial" as const,
120 key: ({ environmentId, input }: { environmentId: string; input: { projectId: string } }) =>
@@ -133,20 +162,7 @@ export function createProjectEnvironmentAtoms<R, E>(
162 tag: WS_METHODS.projectsListIgnoredFiles,
163 staleTimeMs: 15_000,
164 }),
136 - readFile: createEnvironmentRpcQueryAtomFamily(runtime, {
137 - label: "environment-data:projects:read-file",
138 - tag: WS_METHODS.projectsReadFile,
139 - staleTimeMs: 30_000,
140 - idleTtlMs: 5 * 60_000,
141 - execute: (input) =>
142 - fileMetadata.seedAfterRead(
143 - request(WS_METHODS.projectsReadFile, input),
144 - (result, isCurrent) =>
145 - result.exists === false
146 - ? Effect.void
147 - : fileMetadata.rememberFile(input.cwd, result, isCurrent),
148 - ),
149 - }),
165 + readFile,
166 optimisticFile: (target: OptimisticProjectFileTarget) =>
167 optimisticFileFamily(optimisticProjectFileKey(target)),
168 create: createEnvironmentCommand(runtime, {
scripts/scenarios/saved-file-shows-external-edit.e2e.ts new
+101
@@ -0,0 +1,101 @@
1 +/// <reference lib="dom" />
2 +// The DOM lib types the functions this scenario runs in the page.
3 +import { expect } from "e2e";
4 +import * as Effect from "effect/Effect";
5 +import * as FileSystem from "effect/FileSystem";
6 +
7 +import { runPromise, test, WEB } from "./t3.ts";
8 +
9 +const chmod = (path: string, mode: number) =>
10 + runPromise(Effect.flatMap(FileSystem.FileSystem, (fs) => fs.chmod(path, mode)));
11 +
12 +test(
13 + "A saved file shows a later external edit after its post-save read failed",
14 + WEB,
15 + async ({ t3, app, browser, screen }) => {
16 + // Logs each file RPC's outcome in order, so the test can wait for the read after the save.
17 + await browser.addInitScript(() => {
18 + const log: Array<string> = [];
19 + const tags = new Map<string, string>();
20 + const watched = new WeakSet<WebSocket>();
21 + Object.assign(window, { fileRpcLog: log });
22 + const send = WebSocket.prototype.send;
23 + WebSocket.prototype.send = function (data) {
24 + if (typeof data === "string") {
25 + for (const message of [JSON.parse(data)].flat()) {
26 + if (message?._tag === "Request") tags.set(String(message.id), message.tag);
27 + }
28 + }
29 + if (!watched.has(this)) {
30 + watched.add(this);
31 + this.addEventListener("message", (event) => {
32 + if (typeof event.data !== "string") return;
33 + for (const message of [JSON.parse(event.data)].flat()) {
34 + const tag = message?._tag === "Exit" ? tags.get(String(message.requestId)) : null;
35 + if (tag?.startsWith("projects.")) log.push(`${tag}:${message.exit._tag}`);
36 + }
37 + });
38 + }
39 + return send.call(this, data);
40 + };
41 + });
42 + const loggedAfter = (after: string, entry: string) =>
43 + browser.evaluate(
44 + ({ after, entry }) => {
45 + const log = (window as unknown as { fileRpcLog: Array<string> }).fileRpcLog;
46 + const start = log.lastIndexOf(after);
47 + return start >= 0 && log.indexOf(entry, start + 1) > start;
48 + },
49 + { after, entry },
50 + );
51 + // The file tree and editor render in shadow roots that locators do not reach.
52 + const openTreeRow = (path: string) =>
53 + browser.evaluate((path) => {
54 + for (const host of document.querySelectorAll("*")) {
55 + const row = host.shadowRoot?.querySelector<HTMLElement>(`[data-item-path="${path}"]`);
56 + if (row) {
57 + row.click();
58 + return true;
59 + }
60 + }
61 + return false;
62 + }, path);
63 + const editorText = () =>
64 + browser.evaluate(() => {
65 + for (const host of document.querySelectorAll("*")) {
66 + const content = host.shadowRoot?.querySelector("[data-content]");
67 + if (content) return content.textContent ?? "";
68 + }
69 + return null;
70 + });
71 +
72 + const project = await t3.project("demo", { "notes.txt": "before save" });
73 + const notes = `${project}/notes.txt`;
74 + const thread = await t3.thread({ project, title: "Notes", messages: ["first"] });
75 + await t3.open(thread);
76 + await expect(screen.getByText("first fixture turn complete", { exact: false })).toBeVisible();
77 + await screen.getByRole("button", "Toggle right panel").tap();
78 + await screen.getByText("Files").tap();
79 + await expect.poll(() => openTreeRow("notes.txt")).toBe(true);
80 + await expect.poll(editorText).toContain("before save");
81 +
82 + // Requires a non-root server and in-place writes: autosave succeeds, confirmation read fails.
83 + await chmod(notes, 0o200);
84 + await browser.keyboard.press("ControlOrMeta+a");
85 + await browser.keyboard.type("saved draft");
86 + await expect
87 + .poll(() => loggedAfter("projects.writeFile:Success", "projects.readFile:Failure"))
88 + .toBe(true);
89 +
90 + await chmod(notes, 0o644);
91 + await runPromise(
92 + Effect.flatMap(FileSystem.FileSystem, (fs) => fs.writeFileString(notes, "external update")),
93 + );
94 + await screen.getByRole("button", "Refresh workspace files").tap();
95 + await expect
96 + .poll(() => loggedAfter("projects.readFile:Failure", "projects.readFile:Success"))
97 + .toBe(true);
98 + await app.screenshot("after-external-edit");
99 + await expect.poll(editorText).toContain("external update");
100 + },
101 +);