Skip to content

Commit 44a5883

Browse files
shivamhwpPR Batch Testertrahaneclaude
authored
fix(mobile): a failed draft save no longer blocks sending an uploaded attachment (#21101)
Co-authored-by: PR Batch Tester <[email protected]> Co-authored-by: Tejas Rahane <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent c1f9d20 commit 44a5883

2 files changed

Lines changed: 353 additions & 1 deletion

File tree

Lines changed: 345 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,345 @@
1+
import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
2+
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
3+
4+
type UploadOptions = {
5+
signal: AbortSignal;
6+
onProgress?: (progress: { bytesSent: number; totalBytes: number }) => void;
7+
};
8+
type DraftFault = "decode" | "read" | "write" | null;
9+
10+
const native = vi.hoisted(() => ({
11+
files: new Map<string, Uint8Array>(),
12+
server: new Map<string, Uint8Array | null>(),
13+
deleted: [] as string[],
14+
fault: null as DraftFault,
15+
canOperate: true,
16+
nextId: 0,
17+
nextUuid: 0,
18+
mint: Symbol("mint"),
19+
remove: Symbol("remove"),
20+
transfer:
21+
vi.fn<(uri: string, url: string, options: UploadOptions) => Promise<{ status: number }>>(),
22+
effects: [] as Array<() => void | (() => void)>,
23+
queueRef: {
24+
current: null as ReturnType<
25+
typeof import("../lib/composerAttachmentUploadQueue").createComposerAttachmentUploadQueue
26+
> | null,
27+
},
28+
}));
29+
30+
vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
31+
vi.mock("react", async (importOriginal) => ({
32+
...(await importOriginal<typeof import("react")>()),
33+
useEffect: (effect: () => void | (() => void)) => native.effects.push(effect),
34+
useRef: () => native.queueRef,
35+
}));
36+
vi.mock("@effect/atom-react", () => ({
37+
useAtomValue: (atom: Parameters<typeof appAtomRegistry.get>[0]) => appAtomRegistry.get(atom),
38+
}));
39+
vi.mock("expo-file-system", () => {
40+
const uriOf = (parent: string | { uri: string }) =>
41+
typeof parent === "string" ? parent : parent.uri;
42+
class Directory {
43+
readonly uri: string;
44+
constructor(parent: string | { uri: string }, name?: string) {
45+
this.uri = [uriOf(parent), name].filter(Boolean).join("/");
46+
}
47+
create() {}
48+
list() {
49+
return [...native.files.keys()]
50+
.filter((uri) => uri.startsWith(`${this.uri}/`))
51+
.map((uri) => new File(uri));
52+
}
53+
}
54+
class File {
55+
readonly uri: string;
56+
readonly name: string;
57+
readonly parentDirectory: Directory;
58+
constructor(parent: string | { uri: string }, name?: string) {
59+
this.uri = [uriOf(parent), name].filter(Boolean).join("/");
60+
this.name = this.uri.split("/").at(-1)!;
61+
this.parentDirectory = new Directory(this.uri.slice(0, this.uri.lastIndexOf("/")));
62+
}
63+
get exists() {
64+
return native.files.has(this.uri);
65+
}
66+
create() {
67+
native.files.set(this.uri, new Uint8Array());
68+
}
69+
async text() {
70+
if (native.fault === "read" && this.uri.endsWith("/composer-drafts/drafts.json")) {
71+
throw new Error("EACCES: drafts.json");
72+
}
73+
return Buffer.from(native.files.get(this.uri)!).toString("utf8");
74+
}
75+
write(value: string, options?: { encoding?: string }) {
76+
if (native.fault === "write" && this.uri.includes("/composer-drafts/")) {
77+
throw new Error("ENOSPC");
78+
}
79+
native.files.set(
80+
this.uri,
81+
Buffer.from(value, options?.encoding === "base64" ? "base64" : "utf8"),
82+
);
83+
}
84+
moveSync(destination: File) {
85+
native.files.set(destination.uri, native.files.get(this.uri)!);
86+
native.files.delete(this.uri);
87+
}
88+
delete() {
89+
native.files.delete(this.uri);
90+
}
91+
upload(url: string, options: UploadOptions) {
92+
return native.transfer(this.uri, url, options);
93+
}
94+
}
95+
return {
96+
Directory,
97+
File,
98+
Paths: { document: new Directory("file:///documents"), cache: new Directory("file:///cache") },
99+
UploadType: { BINARY_CONTENT: 0 },
100+
};
101+
});
102+
vi.mock("../lib/uuid", () => ({
103+
uuidv4: () => `upload-${++native.nextUuid}`,
104+
randomHex: () => "abcd",
105+
}));
106+
vi.mock("../features/sharing/incoming-share-storage", () => ({
107+
loadIncomingShareDrafts: async () => [],
108+
}));
109+
vi.mock("./entities", () => ({
110+
useProjects: () => [],
111+
useServerConfigs: () => new Map([["environment-1", config]]),
112+
useThreadShells: () => [],
113+
}));
114+
vi.mock("./server", async () => {
115+
const { Atom } = await import("effect/reactivity");
116+
return { serverEnvironment: { configValueAtom: Atom.family(() => Atom.make(null)) } };
117+
});
118+
vi.mock("./git", () => ({ gitEnvironment: {} }));
119+
vi.mock("./threads", () => ({ threadEnvironment: {} }));
120+
vi.mock("./use-atom-command", () => ({ useAtomCommand: () => async () => undefined }));
121+
vi.mock("./session", async () => {
122+
const { Atom } = await import("effect/reactivity");
123+
const Option = await import("effect/Option");
124+
return {
125+
readEnvironmentScope: () => native.canOperate,
126+
useEnvironmentsWithScope: () => new Set(["environment-1"]),
127+
environmentSession: {
128+
preparedConnectionValueAtom: Atom.family(() =>
129+
Atom.make(Option.some({ httpBaseUrl: "https://environment.example/" })),
130+
),
131+
},
132+
};
133+
});
134+
vi.mock("./attachments", () => ({
135+
attachmentEnvironment: { createUploadUrl: native.mint, remove: native.remove },
136+
}));
137+
vi.mock("./assets", () => ({ assetEnvironment: { createUrl: (input: unknown) => input } }));
138+
vi.mock("@t3tools/client-runtime/state/runtime", () => ({
139+
createEnvironmentRpcCommand: () => Symbol("rpc-command"),
140+
executeAtomQuery: async (
141+
_registry: unknown,
142+
query: { input: { resource: { attachmentId: string } } },
143+
) =>
144+
native.server.get(query.input.resource.attachmentId)
145+
? { _tag: "Success", value: {} }
146+
: { _tag: "Failure", error: { _tag: "AssetAttachmentNotFoundError" } },
147+
runAtomCommand: async (
148+
_registry: unknown,
149+
command: unknown,
150+
target: { input: { attachmentId?: string } },
151+
) => {
152+
if (command === native.mint) {
153+
const id = `pending-${++native.nextId}`;
154+
native.server.set(id, null);
155+
return {
156+
_tag: "Success",
157+
value: { attachmentId: id, relativeUrl: `/upload/${id}`, expiresAt: 1 },
158+
};
159+
}
160+
if (command === native.remove && target.input.attachmentId) {
161+
native.deleted.push(target.input.attachmentId);
162+
native.server.delete(target.input.attachmentId);
163+
return { _tag: "Success", value: undefined };
164+
}
165+
throw new Error("Unexpected RPC command");
166+
},
167+
squashAtomCommandFailure: (result: { error: unknown }) => result.error,
168+
}));
169+
vi.mock("./use-thread-outbox", async () => {
170+
const { Atom } = await import("effect/reactivity");
171+
return {
172+
editingQueuedMessageIdsAtom: Atom.make<Record<string, boolean>>({}).pipe(Atom.keepAlive),
173+
dispatchingQueuedMessageIdAtom: Atom.make<Record<string, string>>({}).pipe(Atom.keepAlive),
174+
useThreadOutboxMessages: () =>
175+
appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
176+
useThreadOutboxShellStatuses: () => new Map(),
177+
};
178+
});
179+
vi.mock("./use-remote-environment-registry", () => ({
180+
useRemoteConnectionStatus: () => ({
181+
connectedEnvironments: [{ environmentId: "environment-1", connectionState: "connected" }],
182+
}),
183+
}));
184+
185+
import {
186+
composerAttachmentUploadBlockReason,
187+
composerAttachmentsStillUploading,
188+
composerAttachmentUploadKey,
189+
} from "../lib/composerAttachmentUploadQueue";
190+
import type { DraftComposerAttachment } from "../lib/composerImages";
191+
import { appAtomRegistry } from "./atom-registry";
192+
import {
193+
composerAttachmentUploadsAtom,
194+
useComposerAttachmentUploadWorker,
195+
} from "./composer-attachment-uploads";
196+
import {
197+
enqueueThreadOutboxMessage,
198+
flushThreadOutbox,
199+
threadOutboxManager,
200+
} from "./thread-outbox";
201+
import type { QueuedThreadMessage } from "./thread-outbox-model";
202+
import * as drafts from "./use-composer-drafts";
203+
import { prepareQueuedMessageAttachments } from "./use-thread-outbox-drain";
204+
205+
const environmentId = EnvironmentId.make("environment-1");
206+
const draftKey = "environment-1:thread-1";
207+
const draftsUri = "file:///documents/composer-drafts/drafts.json";
208+
const config = { environment: { capabilities: { attachmentUploads: true } } };
209+
const image: DraftComposerAttachment = {
210+
id: "image-1",
211+
type: "image",
212+
name: "photo.png",
213+
mimeType: "image/png",
214+
sizeBytes: 3,
215+
dataUrl: "data:image/png;base64,YWJj",
216+
previewUri: "data:image/png;base64,YWJj",
217+
};
218+
let disposeWorker: (() => void) | undefined;
219+
220+
function worker() {
221+
native.effects = [];
222+
useComposerAttachmentUploadWorker();
223+
disposeWorker = native.effects[0]!() ?? undefined;
224+
const queue = native.queueRef.current!;
225+
native.effects[1]!();
226+
return queue;
227+
}
228+
229+
function sendInput() {
230+
return {
231+
environmentId,
232+
attachments: drafts.getComposerDraftSnapshot(draftKey).attachments,
233+
connected: true,
234+
serverConfig: config,
235+
states: appAtomRegistry.get(composerAttachmentUploadsAtom),
236+
};
237+
}
238+
239+
function queuedMessage(): QueuedThreadMessage {
240+
return {
241+
environmentId,
242+
threadId: ThreadId.make("thread-1"),
243+
messageId: MessageId.make("message-1"),
244+
commandId: CommandId.make("command-1"),
245+
text: "Look at this",
246+
attachments: drafts.getComposerDraftSnapshot(draftKey).attachments,
247+
createdAt: "2026-10-17T00:00:00.000Z",
248+
};
249+
}
250+
251+
beforeEach(async () => {
252+
vi.spyOn(console, "warn").mockImplementation(() => {});
253+
native.files.clear();
254+
native.server.clear();
255+
native.deleted.length = 0;
256+
native.fault = null;
257+
native.canOperate = true;
258+
native.nextId = 0;
259+
native.nextUuid = 0;
260+
native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":{}}'));
261+
drafts.resetComposerDraftsLoadState();
262+
appAtomRegistry.set(drafts.composerDraftsAtom, {
263+
[draftKey]: { text: "Look at this", attachments: [image] },
264+
});
265+
appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {});
266+
await drafts.flushComposerDrafts();
267+
await threadOutboxManager.load();
268+
native.transfer.mockReset();
269+
native.transfer.mockImplementation(async (uri, url, options) => {
270+
const bytes = native.files.get(uri)!;
271+
options.onProgress?.({ bytesSent: bytes.length, totalBytes: bytes.length });
272+
native.server.set(url.split("/").at(-1)!, bytes);
273+
return { status: 204 };
274+
});
275+
});
276+
277+
afterEach(async () => {
278+
disposeWorker?.();
279+
disposeWorker = undefined;
280+
native.fault = null;
281+
native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":{}}'));
282+
drafts.resetComposerDraftsLoadState();
283+
await drafts.flushComposerDrafts();
284+
await flushThreadOutbox();
285+
vi.restoreAllMocks();
286+
});
287+
288+
function uploadState() {
289+
return appAtomRegistry.get(composerAttachmentUploadsAtom)[
290+
composerAttachmentUploadKey(environmentId, image.id)
291+
];
292+
}
293+
294+
it.each(["decode", "read", "write"] as const)(
295+
"keeps an accepted upload ready when the draft %s fails",
296+
async (fault) => {
297+
native.fault = fault;
298+
if (fault === "decode")
299+
native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":'));
300+
drafts.resetComposerDraftsLoadState();
301+
const queue = worker();
302+
await queue.settled();
303+
expect(uploadState()).toEqual({ status: "ready" });
304+
expect(native.deleted).toEqual([]);
305+
expect(composerAttachmentUploadBlockReason(sendInput())).toBeNull();
306+
expect(composerAttachmentsStillUploading(sendInput())).toBe(false);
307+
308+
const message = queuedMessage();
309+
expect(message.attachments[0]?.uploadedAttachmentId).toBe("pending-1");
310+
await enqueueThreadOutboxMessage(message);
311+
const prepared = await prepareQueuedMessageAttachments(message, true);
312+
expect(prepared.status).toBe("ready");
313+
if (prepared.status !== "ready") throw new Error("Outbox preparation abandoned");
314+
expect(prepared.prepared.pendingAttachmentIds).toEqual(["pending-1"]);
315+
expect(native.transfer).toHaveBeenCalledTimes(1);
316+
},
317+
);
318+
319+
it.each(["http", "network", "permission"] as const)(
320+
"keeps a real %s upload failure blocking Send",
321+
async (failure) => {
322+
if (failure === "http") native.transfer.mockResolvedValueOnce({ status: 503 });
323+
if (failure === "network")
324+
native.transfer.mockRejectedValueOnce(new Error("Network unavailable"));
325+
if (failure === "permission") native.canOperate = false;
326+
const queue = worker();
327+
await queue.settled();
328+
expect(composerAttachmentUploadBlockReason(sendInput())).toBe(
329+
"Retry or remove the failed attachment",
330+
);
331+
expect([...native.server.values()]).toEqual([]);
332+
},
333+
);
334+
335+
it("keeps an unexpected draft flush error blocking Send", async () => {
336+
vi.spyOn(drafts, "flushComposerDrafts").mockRejectedValueOnce(
337+
new Error("Unexpected flush defect"),
338+
);
339+
const queue = worker();
340+
await queue.settled();
341+
expect(composerAttachmentUploadBlockReason(sendInput())).toBe(
342+
"Retry or remove the failed attachment",
343+
);
344+
expect(native.deleted).toEqual(["pending-1"]);
345+
});

‎apps/mobile/src/state/composer-attachment-uploads.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { useServerConfigs } from "./entities";
1818
import { flattenQueuedThreadMessages, threadOutboxManager } from "./thread-outbox";
1919
import { useThreadOutboxMessages } from "./use-thread-outbox";
2020
import {
21+
ComposerDraftPersistenceError,
2122
composerDraftsAtom,
2223
ensureComposerDraftsLoaded,
2324
flushComposerDrafts,
@@ -94,7 +95,13 @@ export function useComposerAttachmentUploadWorker() {
9495
}
9596
}
9697
if (!retained) return "abandon";
97-
await flushComposerDrafts();
98+
// The reference is already in the in-memory draft, and Send copies it into the
99+
// outbox, which saves on its own. A failed draft save only costs a re-upload after
100+
// a restart, so it must not fail an upload the server already accepted.
101+
await flushComposerDrafts().catch((error: unknown) => {
102+
if (!(error instanceof ComposerDraftPersistenceError)) throw error;
103+
console.warn("[composer-attachments] could not save the uploaded reference", error);
104+
});
98105
return "persisted";
99106
},
100107
});

0 commit comments

Comments
 (0)