Open History to see the last commit
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 ...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()),
140 createEnvironmentRpcCommand: () => Symbol("rpc-command"),
141 executeAtomQuery: async (
142 _registry: unknown,
143 query: { input: { resource: { attachmentId: string } } },
144 ) =>
145 native.server.get(query.input.resource.attachmentId)
146 ? { _tag: "Success", value: {} }
147 : { _tag: "Failure", error: { _tag: "AssetAttachmentNotFoundError" } },
148 runAtomCommand: async (
149 _registry: unknown,
150 command: unknown,
151 target: { input: { attachmentId?: string } },
152 ) => {
153 if (command === native.mint) {
154 const id = `pending-${++native.nextId}`;
155 native.server.set(id, null);
156 return {
157 _tag: "Success",
158 value: { attachmentId: id, relativeUrl: `/upload/${id}`, expiresAt: 1 },
159 };
160 }
161 if (command === native.remove && target.input.attachmentId) {
162 native.deleted.push(target.input.attachmentId);
163 native.server.delete(target.input.attachmentId);
164 return { _tag: "Success", value: undefined };
165 }
166 throw new Error("Unexpected RPC command");
167 },
168}));
169vi.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});
179vi.mock("./use-remote-environment-registry", () => ({
180 useRemoteConnectionStatus: () => ({
181 connectedEnvironments: [{ environmentId: "environment-1", connectionState: "connected" }],
182 }),
183}));
184
185import {
186 composerAttachmentUploadBlockReason,
187 composerAttachmentsStillUploading,
188 composerAttachmentUploadKey,
189} from "../lib/composerAttachmentUploadQueue";
190import type { DraftComposerAttachment } from "../lib/composerImages";
191import { appAtomRegistry } from "./atom-registry";
192import {
193 composerAttachmentUploadsAtom,
194 useComposerAttachmentUploadWorker,
195} from "./composer-attachment-uploads";
196import {
197 enqueueThreadOutboxMessage,
198 flushThreadOutbox,
199 threadOutboxManager,
200} from "./thread-outbox";
201import type { QueuedThreadMessage } from "./thread-outbox-model";
202import * as drafts from "./use-composer-drafts";
203import { prepareQueuedMessageAttachments } from "./use-thread-outbox-drain";
204
205const environmentId = EnvironmentId.make("environment-1");
206const draftKey = "environment-1:thread-1";
207const draftsUri = "file:///documents/composer-drafts/drafts.json";
208const config = { environment: { capabilities: { attachmentUploads: true } } };
209const 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};
218let disposeWorker: (() => void) | undefined;
219
220function 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
229function 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
239function 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
251beforeEach(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
277afterEach(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
288function uploadState() {
289 return appAtomRegistry.get(composerAttachmentUploadsAtom)[
290 composerAttachmentUploadKey(environmentId, image.id)
291 ];
292}
293
294it.each(["decode", "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
319it.each(["http", "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 === "permission") native.canOperate = false;
324 const queue = worker();
325 await queue.settled();
326 expect(composerAttachmentUploadBlockReason(sendInput())).toBe(
327 "Retry or remove the failed attachment",
328 );
329 expect([...native.server.values()]).toEqual([]);
330 },
331);
332
333it("keeps an unexpected draft flush error blocking Send", async () => {
334 vi.spyOn(drafts, "flushComposerDrafts").mockRejectedValueOnce(
335 new Error("Unexpected flush defect"),
336 );
337 const queue = worker();
338 await queue.settled();
339 expect(composerAttachmentUploadBlockReason(sendInput())).toBe(
340 "Retry or remove the failed attachment",
341 );
342 expect(native.deleted).toEqual(["pending-1"]);
343});