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}));
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}));
103vi.mock("./projects", () => ({ environmentProjects: {} }));
104vi.mock("./workspace", () => ({ workspaceConnections: {} }));
105vi.mock("./server", async () => {
106 const { Atom } = await import("effect/reactivity");
107 return { serverEnvironment: { configValueAtom: Atom.family(() => Atom.make(null)) } };
108});
109vi.mock("./git", () => ({ gitEnvironment: {} }));
110vi.mock("./threads", () => ({ threadEnvironment: {} }));
111vi.mock("./use-atom-command", () => ({ useAtomCommand: () => async () => undefined }));
112vi.mock("./session", async () => {
113 const { Atom } = await import("effect/reactivity");
114 const Option = await import("effect/Option");
115 return {
116 readEnvironmentScope: () => native.canOperate,
117 useEnvironmentsWithScope: () => new Set(["environment-1"]),
118 environmentSession: {
119 preparedConnectionValueAtom: Atom.family(() =>
120 Atom.make(Option.some({ httpBaseUrl: "https://environment.example/" })),
121 ),
122 },
123 };
124});
125vi.mock("./attachments", () => ({
126 attachmentEnvironment: { createUploadUrl: native.mint, remove: native.remove },
127}));
128vi.mock("./assets", () => ({ assetEnvironment: { createUrl: (input: unknown) => input } }));
129vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({
130 ...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()),
131 createEnvironmentRpcCommand: () => Symbol("rpc-command"),
132 executeAtomQuery: async (
133 _registry: unknown,
134 query: { input: { resource: { attachmentId: string } } },
135 ) =>
136 native.server.get(query.input.resource.attachmentId)
137 ? { _tag: "Success", value: {} }
138 : { _tag: "Failure", error: { _tag: "AssetAttachmentNotFoundError" } },
139 runAtomCommand: async (
140 _registry: unknown,
141 command: unknown,
142 target: { input: { attachmentId?: string } },
143 ) => {
144 if (command === native.mint) {
145 const id = `pending-${++native.nextId}`;
146 native.server.set(id, null);
147 return {
148 _tag: "Success",
149 value: { attachmentId: id, relativeUrl: `/upload/${id}`, expiresAt: 1 },
150 };
151 }
152 if (command === native.remove && target.input.attachmentId) {
153 native.deleted.push(target.input.attachmentId);
154 native.server.delete(target.input.attachmentId);
155 return { _tag: "Success", value: undefined };
156 }
157 throw new Error("Unexpected RPC command");
158 },
159}));
160vi.mock("./use-thread-outbox", async () => {
161 const { Atom } = await import("effect/reactivity");
162 return {
163 editingQueuedMessageIdsAtom: Atom.make<Record<string, boolean>>({}).pipe(Atom.keepAlive),
164 dispatchingQueuedMessageIdAtom: Atom.make<Record<string, string>>({}).pipe(Atom.keepAlive),
165 useThreadOutboxMessages: () =>
166 appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
167 threadOutboxShellStatusesAtom: Atom.make(new Map()),
168 };
169});
170
171import {
172 composerAttachmentUploadBlockReason,
173 composerAttachmentsStillUploading,
174 composerAttachmentUploadKey,
175} from "../lib/composerAttachmentUploadQueue";
176import type { DraftComposerAttachment } from "../lib/composerImages";
177import { Atom } from "effect/reactivity";
178import { appAtomRegistry } from "./atom-registry";
179import {
180 composerAttachmentUploadRequests,
181 composerAttachmentUploadsAtom,
182 createComposerAttachmentUploadWorker,
183} from "./composer-attachment-uploads";
184import {
185 enqueueThreadOutboxMessage,
186 flushThreadOutbox,
187 threadOutboxManager,
188} from "./thread-outbox";
189import type { QueuedThreadMessage } from "./thread-outbox-model";
190import * as drafts from "./use-composer-drafts";
191import { prepareQueuedMessageAttachments } from "./threadOutboxDelivery";
192
193const environmentId = EnvironmentId.make("environment-1");
194const draftKey = "environment-1:thread-1";
195const draftsUri = "file:///documents/composer-drafts/drafts.json";
196const config = { environment: { capabilities: { attachmentUploads: true } } };
197const image: DraftComposerAttachment = {
198 id: "image-1",
199 type: "image",
200 name: "photo.png",
201 mimeType: "image/png",
202 sizeBytes: 3,
203 dataUrl: "data:image/png;base64,YWJj",
204 previewUri: "data:image/png;base64,YWJj",
205};
206let disposeWorker: (() => void) | undefined;
207
208const requestsAtom = Atom.make((get) =>
209 composerAttachmentUploadRequests({
210 drafts: get(drafts.composerDraftUploadSourcesAtom),
211 queuedMessagesByThreadKey: get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
212 connectedEnvironmentIds: new Set([environmentId]),
213 operableEnvironmentIds: new Set([environmentId]),
214 serverConfigs: new Map([[environmentId, config]]),
215 }),
216);
217
218function worker() {
219 const { queue, dispose } = createComposerAttachmentUploadWorker(requestsAtom);
220 disposeWorker = dispose;
221 return queue;
222}
223
224function sendInput() {
225 return {
226 environmentId,
227 attachments: drafts.getComposerDraftSnapshot(draftKey).attachments,
228 connected: true,
229 serverConfig: config,
230 states: appAtomRegistry.get(composerAttachmentUploadsAtom),
231 };
232}
233
234function queuedMessage(): QueuedThreadMessage {
235 return {
236 environmentId,
237 threadId: ThreadId.make("thread-1"),
238 messageId: MessageId.make("message-1"),
239 commandId: CommandId.make("command-1"),
240 text: "Look at this",
241 attachments: drafts.getComposerDraftSnapshot(draftKey).attachments,
242 createdAt: "2026-10-17T00:00:00.000Z",
243 };
244}
245
246beforeEach(async () => {
247 vi.spyOn(console, "warn").mockImplementation(() => {});
248 native.files.clear();
249 native.server.clear();
250 native.deleted.length = 0;
251 native.fault = null;
252 native.canOperate = true;
253 native.nextId = 0;
254 native.nextUuid = 0;
255 native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":{}}'));
256 drafts.resetComposerDraftsLoadState();
257 appAtomRegistry.set(drafts.composerDraftsAtom, {
258 [draftKey]: { text: "Look at this", attachments: [image] },
259 });
260 appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {});
261 await drafts.flushComposerDrafts();
262 await threadOutboxManager.load();
263 native.transfer.mockReset();
264 native.transfer.mockImplementation(async (uri, url, options) => {
265 const bytes = native.files.get(uri)!;
266 options.onProgress?.({ bytesSent: bytes.length, totalBytes: bytes.length });
267 native.server.set(url.split("/").at(-1)!, bytes);
268 return { status: 204 };
269 });
270});
271
272afterEach(async () => {
273 disposeWorker?.();
274 disposeWorker = undefined;
275 native.fault = null;
276 native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":{}}'));
277 drafts.resetComposerDraftsLoadState();
278 await drafts.flushComposerDrafts();
279 await flushThreadOutbox();
280 vi.restoreAllMocks();
281});
282
283function uploadState() {
284 return appAtomRegistry.get(composerAttachmentUploadsAtom)[
285 composerAttachmentUploadKey(environmentId, image.id)
286 ];
287}
288
289it.each(["decode", "write"] as const)(
290 "keeps an accepted upload ready when the draft %s fails",
291 async (fault) => {
292 native.fault = fault;
293 if (fault === "decode")
294 native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":'));
295 drafts.resetComposerDraftsLoadState();
296 const queue = worker();
297 await queue.settled();
298 expect(uploadState()).toEqual({ status: "ready" });
299 expect(native.deleted).toEqual([]);
300 expect(composerAttachmentUploadBlockReason(sendInput())).toBeNull();
301 expect(composerAttachmentsStillUploading(sendInput())).toBe(false);
302
303 const message = queuedMessage();
304 expect(message.attachments[0]?.uploadedAttachmentId).toBe("pending-1");
305 await enqueueThreadOutboxMessage(message);
306 const prepared = await prepareQueuedMessageAttachments(message, true);
307 expect(prepared.status).toBe("ready");
308 if (prepared.status !== "ready") throw new Error("Outbox preparation abandoned");
309 expect(prepared.prepared.pendingAttachmentIds).toEqual(["pending-1"]);
310 expect(native.transfer).toHaveBeenCalledTimes(1);
311 },
312);
313
314it.each(["http", "permission"] as const)(
315 "keeps a real %s upload failure blocking Send",
316 async (failure) => {
317 if (failure === "http") native.transfer.mockResolvedValueOnce({ status: 503 });
318 if (failure === "permission") native.canOperate = false;
319 const queue = worker();
320 await queue.settled();
321 expect(composerAttachmentUploadBlockReason(sendInput())).toBe(
322 "Retry or remove the failed attachment",
323 );
324 expect([...native.server.values()]).toEqual([]);
325 },
326);
327
328it("keeps an unexpected draft flush error blocking Send", async () => {
329 vi.spyOn(drafts, "flushComposerDrafts").mockRejectedValueOnce(
330 new Error("Unexpected flush defect"),
331 );
332 const queue = worker();
333 await queue.settled();
334 expect(composerAttachmentUploadBlockReason(sendInput())).toBe(
335 "Retry or remove the failed attachment",
336 );
337 expect(native.deleted).toEqual(["pending-1"]);
338});