Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

composer-attachment-uploads.test.ts

347 lines12.2 KB

1import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
2import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
3​
4type UploadOptions = {
5 signal: AbortSignal;
6 onProgress?: (progress: { bytesSent: number; totalBytes: number }) => void;
7};
8type DraftFault = "decode" | "read" | "write" | null;
9​
10const 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​
30vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
31vi.mock("react", async (importOriginal) => ({
32 ...(await importOriginal<typeof import("react")>()),
33 useEffect: (effect: () => void | (() => void)) => native.effects.push(effect),
34 useRef: () => native.queueRef,
35}));
36vi.mock("@effect/atom-react", () => ({
37 useAtomValue: (atom: Parameters<typeof appAtomRegistry.get>[0]) => appAtomRegistry.get(atom),
38}));
39vi.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});
102vi.mock("../lib/uuid", () => ({
103 uuidv4: () => `upload-${++native.nextUuid}`,
104 randomHex: () => "abcd",
105}));
106vi.mock("../features/sharing/incoming-share-storage", () => ({
107 loadIncomingShareDrafts: async () => [],
108}));
109vi.mock("./entities", () => ({
110 useProjects: () => [],
111 useServerConfigs: () => new Map([["environment-1", config]]),
112 useThreadShells: () => [],
113}));
114vi.mock("./server", async () => {
115 const { Atom } = await import("effect/reactivity");
116 return { serverEnvironment: { configValueAtom: Atom.family(() => Atom.make(null)) } };
117});
118vi.mock("./git", () => ({ gitEnvironment: {} }));
119vi.mock("./threads", () => ({ threadEnvironment: {} }));
120vi.mock("./use-atom-command", () => ({ useAtomCommand: () => async () => undefined }));
121vi.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});
134vi.mock("./attachments", () => ({
135 attachmentEnvironment: { createUploadUrl: native.mint, remove: native.remove },
136}));
137vi.mock("./assets", () => ({ assetEnvironment: { createUrl: (input: unknown) => input } }));
138vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({
139 // The worker settles uploads with the real settlePromise and squashAtomCommandFailure;
140 // only the RPC transport is substituted.
141 ...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()),
142 createEnvironmentRpcCommand: () => Symbol("rpc-command"),
143 executeAtomQuery: async (
144 _registry: unknown,
145 query: { input: { resource: { attachmentId: string } } },
146 ) =>
147 native.server.get(query.input.resource.attachmentId)
148 ? { _tag: "Success", value: {} }
149 : { _tag: "Failure", error: { _tag: "AssetAttachmentNotFoundError" } },
150 runAtomCommand: async (
151 _registry: unknown,
152 command: unknown,
153 target: { input: { attachmentId?: string } },
154 ) => {
155 if (command === native.mint) {
156 const id = `pending-${++native.nextId}`;
157 native.server.set(id, null);
158 return {
159 _tag: "Success",
160 value: { attachmentId: id, relativeUrl: `/upload/${id}`, expiresAt: 1 },
161 };
162 }
163 if (command === native.remove && target.input.attachmentId) {
164 native.deleted.push(target.input.attachmentId);
165 native.server.delete(target.input.attachmentId);
166 return { _tag: "Success", value: undefined };
167 }
168 throw new Error("Unexpected RPC command");
169 },
170}));
171vi.mock("./use-thread-outbox", async () => {
172 const { Atom } = await import("effect/reactivity");
173 return {
174 editingQueuedMessageIdsAtom: Atom.make<Record<string, boolean>>({}).pipe(Atom.keepAlive),
175 dispatchingQueuedMessageIdAtom: Atom.make<Record<string, string>>({}).pipe(Atom.keepAlive),
176 useThreadOutboxMessages: () =>
177 appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
178 useThreadOutboxShellStatuses: () => new Map(),
179 };
180});
181vi.mock("./use-remote-environment-registry", () => ({
182 useRemoteConnectionStatus: () => ({
183 connectedEnvironments: [{ environmentId: "environment-1", connectionState: "connected" }],
184 }),
185}));
186​
187import {
188 composerAttachmentUploadBlockReason,
189 composerAttachmentsStillUploading,
190 composerAttachmentUploadKey,
191} from "../lib/composerAttachmentUploadQueue";
192import type { DraftComposerAttachment } from "../lib/composerImages";
193import { appAtomRegistry } from "./atom-registry";
194import {
195 composerAttachmentUploadsAtom,
196 useComposerAttachmentUploadWorker,
197} from "./composer-attachment-uploads";
198import {
199 enqueueThreadOutboxMessage,
200 flushThreadOutbox,
201 threadOutboxManager,
202} from "./thread-outbox";
203import type { QueuedThreadMessage } from "./thread-outbox-model";
204import * as drafts from "./use-composer-drafts";
205import { prepareQueuedMessageAttachments } from "./use-thread-outbox-drain";
206​
207const environmentId = EnvironmentId.make("environment-1");
208const draftKey = "environment-1:thread-1";
209const draftsUri = "file:///documents/composer-drafts/drafts.json";
210const config = { environment: { capabilities: { attachmentUploads: true } } };
211const image: DraftComposerAttachment = {
212 id: "image-1",
213 type: "image",
214 name: "photo.png",
215 mimeType: "image/png",
216 sizeBytes: 3,
217 dataUrl: "data:image/png;base64,YWJj",
218 previewUri: "data:image/png;base64,YWJj",
219};
220let disposeWorker: (() => void) | undefined;
221​
222function worker() {
223 native.effects = [];
224 useComposerAttachmentUploadWorker();
225 disposeWorker = native.effects[0]!() ?? undefined;
226 const queue = native.queueRef.current!;
227 native.effects[1]!();
228 return queue;
230​
231function sendInput() {
232 return {
233 environmentId,
234 attachments: drafts.getComposerDraftSnapshot(draftKey).attachments,
235 connected: true,
236 serverConfig: config,
237 states: appAtomRegistry.get(composerAttachmentUploadsAtom),
238 };
240​
241function queuedMessage(): QueuedThreadMessage {
242 return {
243 environmentId,
244 threadId: ThreadId.make("thread-1"),
245 messageId: MessageId.make("message-1"),
246 commandId: CommandId.make("command-1"),
247 text: "Look at this",
248 attachments: drafts.getComposerDraftSnapshot(draftKey).attachments,
249 createdAt: "2026-10-17T00:00:00.000Z",
250 };
252​
253beforeEach(async () => {
254 vi.spyOn(console, "warn").mockImplementation(() => {});
255 native.files.clear();
256 native.server.clear();
257 native.deleted.length = 0;
258 native.fault = null;
259 native.canOperate = true;
260 native.nextId = 0;
261 native.nextUuid = 0;
262 native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":{}}'));
263 drafts.resetComposerDraftsLoadState();
264 appAtomRegistry.set(drafts.composerDraftsAtom, {
265 [draftKey]: { text: "Look at this", attachments: [image] },
266 });
267 appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {});
268 await drafts.flushComposerDrafts();
269 await threadOutboxManager.load();
270 native.transfer.mockReset();
271 native.transfer.mockImplementation(async (uri, url, options) => {
272 const bytes = native.files.get(uri)!;
273 options.onProgress?.({ bytesSent: bytes.length, totalBytes: bytes.length });
274 native.server.set(url.split("/").at(-1)!, bytes);
275 return { status: 204 };
276 });
277});
278​
279afterEach(async () => {
280 disposeWorker?.();
281 disposeWorker = undefined;
282 native.fault = null;
283 native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":{}}'));
284 drafts.resetComposerDraftsLoadState();
285 await drafts.flushComposerDrafts();
286 await flushThreadOutbox();
287 vi.restoreAllMocks();
288});
289​
290function uploadState() {
291 return appAtomRegistry.get(composerAttachmentUploadsAtom)[
292 composerAttachmentUploadKey(environmentId, image.id)
293 ];
295​
296it.each(["decode", "read", "write"] as const)(
297 "keeps an accepted upload ready when the draft %s fails",
298 async (fault) => {
299 native.fault = fault;
300 if (fault === "decode")
301 native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":'));
302 drafts.resetComposerDraftsLoadState();
303 const queue = worker();
304 await queue.settled();
305 expect(uploadState()).toEqual({ status: "ready" });
306 expect(native.deleted).toEqual([]);
307 expect(composerAttachmentUploadBlockReason(sendInput())).toBeNull();
308 expect(composerAttachmentsStillUploading(sendInput())).toBe(false);
309​
310 const message = queuedMessage();
311 expect(message.attachments[0]?.uploadedAttachmentId).toBe("pending-1");
312 await enqueueThreadOutboxMessage(message);
313 const prepared = await prepareQueuedMessageAttachments(message, true);
314 expect(prepared.status).toBe("ready");
315 if (prepared.status !== "ready") throw new Error("Outbox preparation abandoned");
316 expect(prepared.prepared.pendingAttachmentIds).toEqual(["pending-1"]);
317 expect(native.transfer).toHaveBeenCalledTimes(1);
318 },
319);
320​
321it.each(["http", "network", "permission"] as const)(
322 "keeps a real %s upload failure blocking Send",
323 async (failure) => {
324 if (failure === "http") native.transfer.mockResolvedValueOnce({ status: 503 });
325 if (failure === "network")
326 native.transfer.mockRejectedValueOnce(new Error("Network unavailable"));
327 if (failure === "permission") native.canOperate = false;
328 const queue = worker();
329 await queue.settled();
330 expect(composerAttachmentUploadBlockReason(sendInput())).toBe(
331 "Retry or remove the failed attachment",
332 );
333 expect([...native.server.values()]).toEqual([]);
334 },
335);
336​
337it("keeps an unexpected draft flush error blocking Send", async () => {
338 vi.spyOn(drafts, "flushComposerDrafts").mockRejectedValueOnce(
339 new Error("Unexpected flush defect"),
340 );
341 const queue = worker();
342 await queue.settled();
343 expect(composerAttachmentUploadBlockReason(sendInput())).toBe(
344 "Retry or remove the failed attachment",
345 );
346 expect(native.deleted).toEqual(["pending-1"]);
347});