@devries-cameron20 / t3code-1 / commits / 120dbb062d
Fork 0

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

fix(mobile): recover incoming shares after interrupted writes (#22115)

Co-authored-by: GPT-6.1 Sol <noreply@openai.com> Co-authored-by: maria-rcks <maria@kuuro.net>

Victor Vogel committed Oct 30, 2026 at 15:36 UTC 120dbb062ded0a262e04c4dfe6b77a1c68db609c
2 files changed +243 -20
apps/mobile/src/features/sharing/incoming-share-storage.test.ts
+202 -10
@@ -2,18 +2,84 @@ import { afterEach, describe, expect, it } from "@effect/vitest";
2 import { vi } from "vite-plus/test";
3
4 const fileSystemMocks = vi.hoisted(() => {
5 - let entries: File[] = [];
5 + const files = new Map<string, string>();
6 + let failNextWrite = false;
7 + let failRelocationTo = "";
8 + let snapshots: Map<string, string>[] | undefined;
9 + const record = () => snapshots?.push(new Map(files));
10
11 class File {
8 - readonly exists = true;
12 + name: string;
13 + readonly parentDirectory: Directory;
14 + readonly contents: string;
15
10 - constructor(
11 - readonly name: string,
12 - private readonly contents: string,
13 - ) {}
16 + constructor(parent: string | Directory, nameOrContents: string) {
17 + this.name = typeof parent === "string" ? parent : nameOrContents;
18 + this.parentDirectory = typeof parent === "string" ? new Directory() : parent;
19 + this.contents = typeof parent === "string" ? nameOrContents : "";
20 + }
21 +
22 + get exists(): boolean {
23 + return files.has(this.name);
24 + }
25 +
26 + create(): void {
27 + files.set(this.name, "");
28 + record();
29 + }
30 +
31 + async write(contents: string): Promise<void> {
32 + files.set(this.name, contents.slice(0, 1));
33 + record();
34 + if (failNextWrite) {
35 + failNextWrite = false;
36 + throw new Error("interrupted write");
37 + }
38 + files.set(this.name, contents);
39 + record();
40 + }
41 +
42 + copySync(destination: File): void {
43 + files.delete(destination.name);
44 + record();
45 + files.set(destination.name, files.get(this.name)!.slice(0, 1));
46 + record();
47 + if (destination.name.endsWith(failRelocationTo) && failRelocationTo) {
48 + failRelocationTo = "";
49 + throw new Error("copy failed after partial destination write");
50 + }
51 + files.set(destination.name, files.get(this.name)!);
52 + record();
53 + }
54 +
55 + moveSync(destination: File): void {
56 + // Expo removes the destination before attempting the native move.
57 + files.delete(destination.name);
58 + record();
59 + if (destination.name.endsWith(failRelocationTo) && failRelocationTo) {
60 + failRelocationTo = "";
61 + throw new Error("move failed after destination removal");
62 + }
63 + // Android can fall back to copy-and-delete after native moves fail.
64 + files.set(destination.name, files.get(this.name)!.slice(0, 1));
65 + record();
66 + if (failRelocationTo === "partial") {
67 + failRelocationTo = "";
68 + throw new Error("move failed during fallback copy");
69 + }
70 + files.set(destination.name, files.get(this.name)!);
71 + files.delete(this.name);
72 + this.name = destination.name;
73 + record();
74 + }
75 +
76 + delete(): void {
77 + files.delete(this.name);
78 + record();
79 + }
80
81 async text(): Promise<string> {
16 - return this.contents;
82 + return files.get(this.name)!;
83 }
84 }
85
@@ -21,15 +87,31 @@ const fileSystemMocks = vi.hoisted(() => {
87 create(): void {}
88
89 list(): ReadonlyArray<File> {
24 - return entries;
90 + return [...files].map(([name, contents]) => new File(name, contents));
91 }
92 }
93
94 return {
95 Directory,
96 File,
97 + failNextWrite() {
98 + failNextWrite = true;
99 + },
100 + failRelocationTo(suffix: string) {
101 + failRelocationTo = suffix;
102 + },
103 + trackOperations() {
104 + snapshots = [];
105 + return snapshots;
106 + },
107 setEntries(next: File[]) {
32 - entries = next;
108 + files.clear();
109 + for (const file of next) {
110 + files.set(file.name, file.contents);
111 + }
112 + failNextWrite = false;
113 + failRelocationTo = "";
114 + snapshots = undefined;
115 },
116 };
117 });
@@ -40,7 +122,12 @@ vi.mock("expo-file-system", () => ({
122 Paths: { document: "/documents" },
123 }));
124
43 -import { loadIncomingShareDrafts } from "./incoming-share-storage";
125 +import {
126 + IncomingShareStorageError,
127 + loadIncomingShareDrafts,
128 + removeIncomingShareDraft,
129 + writeIncomingShareDraft,
130 +} from "./incoming-share-storage";
131
132 const VALID_DRAFT = {
133 schemaVersion: 1,
@@ -67,4 +154,109 @@ describe("incoming share storage", () => {
154 await expect(loadIncomingShareDrafts()).resolves.toEqual([VALID_DRAFT]);
155 expect(warning).toHaveBeenCalledOnce();
156 });
157 +
158 + it.each(["write", "partial"])("retries an interrupted initial %s", async (failure) => {
159 + if (failure === "write") fileSystemMocks.failNextWrite();
160 + else fileSystemMocks.failRelocationTo(failure);
161 +
162 + await expect(writeIncomingShareDraft(VALID_DRAFT)).rejects.toMatchObject({
163 + operation: "write",
164 + shareId: VALID_DRAFT.id,
165 + });
166 + vi.spyOn(console, "warn").mockImplementation(() => undefined);
167 + await expect(loadIncomingShareDrafts()).resolves.toEqual([]);
168 +
169 + await writeIncomingShareDraft(VALID_DRAFT);
170 + await expect(loadIncomingShareDrafts({ strict: true })).resolves.toEqual([VALID_DRAFT]);
171 + });
172 +
173 + it("preserves a saved share when its reservation write fails and allows retrying", async () => {
174 + await writeIncomingShareDraft(VALID_DRAFT);
175 + const reserved = {
176 + ...VALID_DRAFT,
177 + destination: { environmentId: "env-1", projectId: "project-1" },
178 + };
179 + fileSystemMocks.failNextWrite();
180 +
181 + await expect(writeIncomingShareDraft(reserved)).rejects.toBeInstanceOf(
182 + IncomingShareStorageError,
183 + );
184 + await expect(loadIncomingShareDrafts({ strict: true })).resolves.toEqual([VALID_DRAFT]);
185 +
186 + await writeIncomingShareDraft(reserved);
187 + await expect(loadIncomingShareDrafts({ strict: true })).resolves.toEqual([reserved]);
188 + });
189 +
190 + it("removes staging and backup files after a successful replacement", async () => {
191 + await writeIncomingShareDraft(VALID_DRAFT);
192 + const updated = { ...VALID_DRAFT, text: "Updated" };
193 +
194 + await writeIncomingShareDraft(updated);
195 +
196 + expect(new fileSystemMocks.Directory().list().map((file) => file.name)).toEqual([
197 + `${VALID_DRAFT.id}.json`,
198 + ]);
199 + await expect(loadIncomingShareDrafts({ strict: true })).resolves.toEqual([updated]);
200 + });
201 +
202 + it("keeps a successful replacement when backup cleanup fails", async () => {
203 + await writeIncomingShareDraft(VALID_DRAFT);
204 + const updated = { ...VALID_DRAFT, text: "Updated" };
205 + vi.spyOn(fileSystemMocks.File.prototype, "delete").mockImplementationOnce(() => {
206 + throw new Error("backup cleanup failed");
207 + });
208 +
209 + await expect(writeIncomingShareDraft(updated)).resolves.toBeUndefined();
210 +
211 + expect(new fileSystemMocks.File(`${VALID_DRAFT.id}.json.bak`, "").exists).toBe(true);
212 + expect(new fileSystemMocks.File(`${VALID_DRAFT.id}.json.tmp`, "").exists).toBe(false);
213 + await expect(loadIncomingShareDrafts({ strict: true })).resolves.toEqual([updated]);
214 + });
215 +
216 + it.each([".bak", ".json", "partial"])(
217 + "recovers after a failed replacement of %s",
218 + async (suffix) => {
219 + await writeIncomingShareDraft(VALID_DRAFT);
220 + fileSystemMocks.failRelocationTo(suffix);
221 +
222 + await expect(
223 + writeIncomingShareDraft({ ...VALID_DRAFT, text: "Updated" }),
224 + ).rejects.toBeInstanceOf(IncomingShareStorageError);
225 + await expect(loadIncomingShareDrafts({ strict: true })).resolves.toEqual([VALID_DRAFT]);
226 +
227 + // A second failed write must not damage a backup left by the failed move.
228 + fileSystemMocks.failNextWrite();
229 + await expect(writeIncomingShareDraft(VALID_DRAFT)).rejects.toBeInstanceOf(
230 + IncomingShareStorageError,
231 + );
232 + await expect(loadIncomingShareDrafts({ strict: true })).resolves.toEqual([VALID_DRAFT]);
233 + fileSystemMocks.failRelocationTo(".json");
234 + await expect(writeIncomingShareDraft(VALID_DRAFT)).rejects.toBeInstanceOf(
235 + IncomingShareStorageError,
236 + );
237 + await expect(loadIncomingShareDrafts({ strict: true })).resolves.toEqual([VALID_DRAFT]);
238 + await writeIncomingShareDraft(VALID_DRAFT);
239 + await removeIncomingShareDraft(VALID_DRAFT.id);
240 + await expect(loadIncomingShareDrafts({ strict: true })).resolves.toEqual([]);
241 + },
242 + );
243 +
244 + it("loads one complete share after interruption at each replacement operation", async () => {
245 + await writeIncomingShareDraft(VALID_DRAFT);
246 + const updated = { ...VALID_DRAFT, text: "Updated" };
247 + const snapshots = fileSystemMocks.trackOperations();
248 + await writeIncomingShareDraft(updated);
249 +
250 + for (const snapshot of snapshots) {
251 + fileSystemMocks.setEntries(
252 + [...snapshot].map(([name, contents]) => new fileSystemMocks.File(name, contents)),
253 + );
254 + const loaded = await loadIncomingShareDrafts({ strict: true });
255 + expect(loaded).toHaveLength(1);
256 + expect([VALID_DRAFT, updated]).toContainEqual(loaded[0]);
257 + await removeIncomingShareDraft(VALID_DRAFT.id);
258 + await expect(loadIncomingShareDrafts({ strict: true })).resolves.toEqual([]);
259 + }
260 + expect(snapshots.length).toBeGreaterThan(0);
261 + });
262 });
apps/mobile/src/features/sharing/incoming-share-storage.ts
+41 -10
@@ -1,4 +1,5 @@
1 import * as Schema from "effect/Schema";
2 +import type { File } from "expo-file-system";
3
4 import { decodeIncomingShareDraft, type IncomingShareDraft } from "./incoming-share-model";
5
@@ -28,9 +29,23 @@ async function getDirectory() {
29 return directory;
30 }
31
31 -async function getFile(shareId: string) {
32 +async function getFile(shareId: string, suffix = "") {
33 const { File } = await import("expo-file-system");
33 - return new File(await getDirectory(), fileName(shareId));
34 + return new File(await getDirectory(), `${fileName(shareId)}${suffix}`);
35 +}
36 +
37 +async function readSavedDraft(file: File) {
38 + try {
39 + return { file, draft: decodeIncomingShareDraft(JSON.parse(await file.text()) as unknown) };
40 + } catch (cause) {
41 + const { File } = await import("expo-file-system");
42 + const backup = new File(file.parentDirectory, `${file.name}.bak`);
43 + if (!backup.exists) throw cause;
44 + return {
45 + file: backup,
46 + draft: decodeIncomingShareDraft(JSON.parse(await backup.text()) as unknown),
47 + };
48 + }
49 }
50
51 export async function loadIncomingShareDrafts(options?: {
@@ -40,11 +55,14 @@ export async function loadIncomingShareDrafts(options?: {
55 const { File } = await import("expo-file-system");
56 const drafts: IncomingShareDraft[] = [];
57 for (const entry of (await getDirectory()).list()) {
43 - if (!(entry instanceof File) || !entry.name.endsWith(".json")) {
58 + if (!(entry instanceof File)) continue;
59 + if (entry.name.endsWith(".json.bak")) {
60 + if (new File(entry.parentDirectory, entry.name.slice(0, -4)).exists) continue;
61 + } else if (!entry.name.endsWith(".json")) {
62 continue;
63 }
64 try {
47 - drafts.push(decodeIncomingShareDraft(JSON.parse(await entry.text()) as unknown));
65 + drafts.push((await readSavedDraft(entry)).draft);
66 } catch (cause) {
67 const error = new IncomingShareStorageError({ operation: "load", shareId: null, cause });
68 if (options?.strict) {
@@ -65,10 +83,22 @@ export async function loadIncomingShareDrafts(options?: {
83 export async function writeIncomingShareDraft(draft: IncomingShareDraft): Promise<void> {
84 try {
85 const file = await getFile(draft.id);
68 - if (!file.exists) {
69 - file.create({ intermediates: true, overwrite: true });
86 + const backup = await getFile(draft.id, ".bak");
87 + const temp = await getFile(draft.id, ".tmp");
88 + // Inbox mutations are serialized, so each share can reuse its staging path.
89 + temp.create({ intermediates: true, overwrite: true });
90 + await temp.write(JSON.stringify(draft));
91 + // Expo can remove or partially copy the destination before a move fails.
92 + if (file.exists) {
93 + const saved = await readSavedDraft(file).catch(() => undefined);
94 + if (!saved || saved.file === file) file.copySync(backup, { overwrite: true });
95 + }
96 + temp.moveSync(file, { overwrite: true });
97 + try {
98 + if (backup.exists) backup.delete();
99 + } catch {
100 + // The installed JSON is authoritative even if backup cleanup fails.
101 }
71 - await file.write(JSON.stringify(draft));
102 } catch (cause) {
103 throw new IncomingShareStorageError({ operation: "write", shareId: draft.id, cause });
104 }
@@ -76,9 +106,10 @@ export async function writeIncomingShareDraft(draft: IncomingShareDraft): Promis
106
107 export async function removeIncomingShareDraft(shareId: string): Promise<void> {
108 try {
79 - const file = await getFile(shareId);
80 - if (file.exists) {
81 - file.delete();
109 + // Delete the backup first so a failed removal cannot resurrect a consumed share.
110 + for (const suffix of [".tmp", ".bak", ""]) {
111 + const file = await getFile(shareId, suffix);
112 + if (file.exists) file.delete();
113 }
114 } catch (cause) {
115 throw new IncomingShareStorageError({ operation: "remove", shareId, cause });