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

composer-attachment-uploads.test.ts

379 lines13.4 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", async () => {
106 const { Atom } = await import("effect/reactivity");
107 return {
108 workspaceConnections: { environmentsAtom: Atom.make([{ environmentId: "environment-1" }]) },
109 };
110});
111vi.mock("./server", async () => {
112 const { Atom } = await import("effect/reactivity");
113 return { serverEnvironment: { configValueAtom: Atom.family(() => Atom.make(null)) } };
114});
115vi.mock("./git", () => ({ gitEnvironment: {} }));
116vi.mock("./threads", () => ({ threadEnvironment: {} }));
117vi.mock("./use-atom-command", () => ({ useAtomCommand: () => async () => undefined }));
118vi.mock("./session", async () => {
119 const { Atom } = await import("effect/reactivity");
120 const Option = await import("effect/Option");
121 return {
122 readEnvironmentScope: () => native.canOperate,
123 useEnvironmentsWithScope: () => new Set(["environment-1"]),
124 environmentSession: {
125 preparedConnectionValueAtom: Atom.family(() =>
126 Atom.make(Option.some({ httpBaseUrl: "https://environment.example/" })),
127 ),
128 },
129 };
130});
131vi.mock("./attachments", () => ({
132 attachmentEnvironment: { createUploadUrl: native.mint, remove: native.remove },
133}));
134vi.mock("./assets", () => ({ assetEnvironment: { createUrl: (input: unknown) => input } }));
135vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({
136 ...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()),
137 createEnvironmentRpcCommand: () => Symbol("rpc-command"),
138 executeAtomQuery: async (
139 _registry: unknown,
140 query: { input: { resource: { attachmentId: string } } },
141 ) =>
142 native.server.get(query.input.resource.attachmentId)
143 ? { _tag: "Success", value: {} }
144 : { _tag: "Failure", error: { _tag: "AssetAttachmentNotFoundError" } },
145 runAtomCommand: async (
146 _registry: unknown,
147 command: unknown,
148 target: { input: { attachmentId?: string } },
149 ) => {
150 if (command === native.mint) {
151 const id = `pending-${++native.nextId}`;
152 native.server.set(id, null);
153 return {
154 _tag: "Success",
155 value: { attachmentId: id, relativeUrl: `/upload/${id}`, expiresAt: 1 },
156 };
157 }
158 if (command === native.remove && target.input.attachmentId) {
159 native.deleted.push(target.input.attachmentId);
160 native.server.delete(target.input.attachmentId);
161 return { _tag: "Success", value: undefined };
162 }
163 throw new Error("Unexpected RPC command");
164 },
165}));
166vi.mock("./use-thread-outbox", async () => {
167 const { Atom } = await import("effect/reactivity");
168 return {
169 editingQueuedMessageIdsAtom: Atom.make<Record<string, boolean>>({}).pipe(Atom.keepAlive),
170 dispatchingQueuedMessageIdAtom: Atom.make<Record<string, string>>({}).pipe(Atom.keepAlive),
171 useThreadOutboxMessages: () =>
172 appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
173 threadOutboxShellStatusesAtom: Atom.make(new Map()),
174 };
175});
176​
177import {
178 composerAttachmentUploadBlockReason,
179 composerAttachmentsStillUploading,
180 composerAttachmentUploadKey,
181} from "../lib/composerAttachmentUploadQueue";
182import type { DraftComposerAttachment } from "../lib/composerImages";
183import { Atom } from "effect/reactivity";
184import { appAtomRegistry } from "./atom-registry";
185import {
186 composerAttachmentUploadRequests,
187 composerAttachmentUploadsAtom,
188 createComposerAttachmentUploadWorker,
189} from "./composer-attachment-uploads";
190import {
191 enqueueThreadOutboxMessage,
192 flushThreadOutbox,
193 threadOutboxManager,
194} from "./thread-outbox";
195import type { QueuedThreadMessage } from "./thread-outbox-model";
196import * as drafts from "./use-composer-drafts";
197import { prepareQueuedMessageAttachments } from "./threadOutboxDelivery";
198​
199const environmentId = EnvironmentId.make("environment-1");
200const draftKey = "environment-1:thread-1";
201const draftsUri = "file:///documents/composer-drafts/drafts.json";
202const config = { environment: { capabilities: {} } };
203const image: DraftComposerAttachment = {
204 id: "image-1",
205 type: "image",
206 name: "photo.png",
207 mimeType: "image/png",
208 sizeBytes: 3,
209 dataUrl: "data:image/png;base64,YWJj",
210 previewUri: "data:image/png;base64,YWJj",
211};
212let disposeWorker: (() => void) | undefined;
213​
214const requestsAtom = Atom.make((get) =>
215 composerAttachmentUploadRequests({
216 drafts: get(drafts.composerDraftUploadSourcesAtom),
217 queuedMessagesByThreadKey: get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
218 knownEnvironmentIds: [environmentId],
219 connectedEnvironmentIds: new Set([environmentId]),
220 operableEnvironmentIds: new Set([environmentId]),
221 serverConfigs: new Map([[environmentId, config]]),
222 }),
223);
224​
225function worker() {
226 const { queue, dispose } = createComposerAttachmentUploadWorker(requestsAtom);
227 disposeWorker = dispose;
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", "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);
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", "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 === "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​
335it("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});
346​
347it("uploads draft attachments for threads whose ids contain colons", () => {
348 const keys = [
349 "environment-1:thread-1",
350 "environment-1:thread:mcp:namespace:key:0",
351 "environment-1:command-1:fork",
352 "environment-1:thread-1~queued-edit~run:1",
353 ];
354 const requests = composerAttachmentUploadRequests({
355 drafts: Object.fromEntries(keys.map((key) => [key, { attachments: [{ ...image, id: key }] }])),
356 queuedMessagesByThreadKey: {},
357 knownEnvironmentIds: [environmentId],
358 connectedEnvironmentIds: new Set([environmentId]),
359 operableEnvironmentIds: new Set([environmentId]),
360 serverConfigs: new Map([[environmentId, config]]),
361 });
362 expect(requests.map((request) => [request.attachment.id, request.environmentId])).toEqual(
363 keys.map((key) => [key, environmentId]),
364 );
365});
366​
367it("does not upload a disconnected colon environment's draft to its connected prefix", () => {
368 const connected = EnvironmentId.make("a");
369 const disconnected = EnvironmentId.make("a:vcs-status:b");
370 const requests = composerAttachmentUploadRequests({
371 drafts: { [`${disconnected}:thread-1`]: { attachments: [image] } },
372 queuedMessagesByThreadKey: {},
373 knownEnvironmentIds: [connected, disconnected],
374 connectedEnvironmentIds: new Set([connected]),
375 operableEnvironmentIds: new Set([connected]),
376 serverConfigs: new Map([[connected, config]]),
377 });
378 expect(requests).toEqual([]);
379});