@devries-cameron20 / t3code-1 / commits / c15a793282
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(mobile): remove orphaned temp files after atomic write failures (#20736)

Kevin Rajan committed Oct 18, 2026 at 14:33 UTC c15a793282f349ede0d6b9e4492bb32906979b29
2 files changed +124 -3
apps/mobile/src/lib/atomic-file.test.ts new
+111
@@ -0,0 +1,111 @@
1 +import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
2 +
3 +const files = new Map<string, { text: string; deleted: boolean }>();
4 +const failMode = vi.hoisted(() => ({
5 + current: "none" as "none" | "write" | "move",
6 + cleanupFails: false,
7 +}));
8 +
9 +vi.mock("expo-file-system", () => ({
10 + File: class {
11 + readonly uri: string;
12 + readonly name: string;
13 + readonly parentDirectory: { readonly uri: string };
14 +
15 + constructor(parent: string | { readonly uri: string }, name?: string) {
16 + const parentUri = typeof parent === "string" ? parent : parent.uri;
17 + this.uri = name ? `${parentUri}/${name}` : parentUri;
18 + this.name = name ?? this.uri.split("/").at(-1) ?? "file";
19 + this.parentDirectory = { uri: parentUri };
20 + }
21 +
22 + get exists(): boolean {
23 + return files.has(this.uri) && files.get(this.uri)?.deleted === false;
24 + }
25 +
26 + create(): void {
27 + files.set(this.uri, { text: "", deleted: false });
28 + }
29 +
30 + async write(text: string): Promise<void> {
31 + await Promise.resolve(); // Exercise asynchronous file-write rejection.
32 + if (failMode.current === "write") throw new Error("disk full");
33 + files.set(this.uri, { text, deleted: false });
34 + }
35 +
36 + moveSync(destination: { readonly uri: string }): void {
37 + if (failMode.current === "move") throw new Error("rename failed");
38 + const entry = files.get(this.uri);
39 + if (!entry) throw new Error("missing staged file");
40 + files.set(destination.uri, entry);
41 + files.delete(this.uri);
42 + }
43 +
44 + delete(): void {
45 + if (failMode.cleanupFails) throw new Error("cleanup failed");
46 + if (!files.has(this.uri)) throw new Error("missing file");
47 + files.delete(this.uri);
48 + }
49 + },
50 +}));
51 +
52 +import { writeFileAtomically } from "./atomic-file";
53 +import { File as ExpoFile } from "expo-file-system";
54 +
55 +const DIRECTORY_URI = "file:///documents/thread-outbox";
56 +
57 +function tempFileUris(): Array<string> {
58 + return [...files.keys()].filter(
59 + (uri) => uri.startsWith(`${DIRECTORY_URI}/`) && uri.endsWith(".tmp"),
60 + );
61 +}
62 +
63 +function makeFile(name: string): ExpoFile {
64 + return new ExpoFile(DIRECTORY_URI, name);
65 +}
66 +
67 +describe("writeFileAtomically", () => {
68 + beforeEach(() => {
69 + files.clear();
70 + failMode.current = "none";
71 + failMode.cleanupFails = false;
72 + });
73 +
74 + it("lands contents at the final path and leaves no temp file behind", async () => {
75 + const file = makeFile("message.json");
76 + await writeFileAtomically(file, '{"ok":true}');
77 + expect(files.get(file.uri)?.text).toBe('{"ok":true}');
78 + expect(tempFileUris()).toEqual([]);
79 + });
80 +
81 + it("removes its staging file when the write fails", async () => {
82 + failMode.current = "write";
83 + const file = makeFile("message.json");
84 + await expect(writeFileAtomically(file, '{"ok":true}')).rejects.toThrow("disk full");
85 + expect(tempFileUris()).toEqual([]);
86 + });
87 +
88 + it("removes its staging file when the rename fails", async () => {
89 + failMode.current = "move";
90 + const file = makeFile("message.json");
91 + await expect(writeFileAtomically(file, '{"ok":true}')).rejects.toThrow("rename failed");
92 + expect(tempFileUris()).toEqual([]);
93 + expect(files.has(file.uri)).toBe(false);
94 + });
95 +
96 + it("preserves the original error when cleanup also fails", async () => {
97 + failMode.current = "write";
98 + failMode.cleanupFails = true;
99 + const file = makeFile("message.json");
100 + await expect(writeFileAtomically(file, "{}")).rejects.toThrow("disk full");
101 + });
102 +
103 + it("does not accumulate a temp file per retry", async () => {
104 + failMode.current = "write";
105 + const file = makeFile("message.json");
106 + for (let attempt = 0; attempt < 3; attempt += 1) {
107 + await expect(writeFileAtomically(file, '{"ok":true}')).rejects.toThrow();
108 + }
109 + expect(tempFileUris()).toEqual([]);
110 + });
111 +});
apps/mobile/src/lib/atomic-file.ts
+13 -3
@@ -5,12 +5,22 @@ let tempFileSequence = 0;
5 /**
6 * Each write stages through its own temp file so concurrent writers to the same
7 * destination cannot move or clobber each other's staging file mid-flight.
8 + * A failed write must clean up its own staging file so retries do not leak it.
9 */
10 export async function writeFileAtomically(file: File, contents: string): Promise<void> {
11 const { File: FileConstructor } = await import("expo-file-system");
12 tempFileSequence += 1;
13 const temp = new FileConstructor(file.parentDirectory, `${file.name}.${tempFileSequence}.tmp`);
13 - temp.create({ intermediates: true, overwrite: true });
14 - await temp.write(contents);
15 - temp.moveSync(file, { overwrite: true });
14 + try {
15 + temp.create({ intermediates: true, overwrite: true });
16 + await temp.write(contents);
17 + temp.moveSync(file, { overwrite: true });
18 + } catch (error) {
19 + try {
20 + if (temp.exists) temp.delete();
21 + } catch {
22 + // Preserve the original write failure even if best-effort cleanup fails.
23 + }
24 + throw error;
25 + }
26 }