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

composer-attachment-uploads.test.ts

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