Open History to see the last commit
1import { CommandId, EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
2import { expect, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import { afterEach, beforeEach, vi } from "vite-plus/test";
5
6type UploadOptions = {
7 signal: AbortSignal;
8 onProgress?: (progress: { bytesSent: number; totalBytes: number }) => void;
9};
10type DraftFault = "decode" | "read" | "write" | null;
11
12const native = vi.hoisted(() => ({
13 files: new Map<string, Uint8Array>(),
14 server: new Map<string, Uint8Array | null>(),
15 deleted: [] as string[],
16 fault: null as DraftFault,
17 canOperate: true,
18 nextId: 0,
19 nextUuid: 0,
20 mint: Symbol("mint"),
21 remove: Symbol("remove"),
22 transfer:
23 vi.fn<(uri: string, url: string, options: UploadOptions) => Promise<{ status: number }>>(),
24}));
25
26vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
27vi.mock("@effect/atom-react", () => ({
28 useAtomValue: (atom: Parameters<typeof appAtomRegistry.get>[0]) => appAtomRegistry.get(atom),
29}));
30vi.mock("expo-file-system", () => {
31 const uriOf = (parent: string | { uri: string }) =>
32 typeof parent === "string" ? parent : parent.uri;
33 class Directory {
34 readonly uri: string;
35 constructor(parent: string | { uri: string }, name?: string) {
36 this.uri = [uriOf(parent), name].filter(Boolean).join("/");
37 }
38 create() {}
39 list() {
40 return [...native.files.keys()]
41 .filter((uri) => uri.startsWith(`${this.uri}/`))
42 .map((uri) => new File(uri));
43 }
44 }
45 class File {
46 readonly uri: string;
47 readonly name: string;
48 readonly parentDirectory: Directory;
49 constructor(parent: string | { uri: string }, name?: string) {
50 this.uri = [uriOf(parent), name].filter(Boolean).join("/");
51 this.name = this.uri.split("/").at(-1)!;
52 this.parentDirectory = new Directory(this.uri.slice(0, this.uri.lastIndexOf("/")));
53 }
54 get exists() {
55 return native.files.has(this.uri);
56 }
57 create() {
58 native.files.set(this.uri, new Uint8Array());
59 }
60 async text() {
61 if (native.fault === "read" && this.uri.endsWith("/composer-drafts/drafts.json")) {
62 throw new Error("EACCES: drafts.json");
63 }
64 return Buffer.from(native.files.get(this.uri)!).toString("utf8");
65 }
66 write(value: string, options?: { encoding?: string }) {
67 if (native.fault === "write" && this.uri.includes("/composer-drafts/")) {
68 throw new Error("ENOSPC");
69 }
70 native.files.set(
71 this.uri,
72 Buffer.from(value, options?.encoding === "base64" ? "base64" : "utf8"),
73 );
74 }
75 moveSync(destination: File) {
76 native.files.set(destination.uri, native.files.get(this.uri)!);
77 native.files.delete(this.uri);
78 }
79 delete() {
80 native.files.delete(this.uri);
81 }
82 upload(url: string, options: UploadOptions) {
83 return native.transfer(this.uri, url, options);
84 }
85 }
86 return {
87 Directory,
88 File,
89 Paths: { document: new Directory("file:///documents"), cache: new Directory("file:///cache") },
90 UploadType: { BINARY_CONTENT: 0 },
91 };
92});
93vi.mock("../lib/uuid", () => ({
94 uuidv4: () => `upload-${++native.nextUuid}`,
95 randomHex: () => "abcd",
96}));
97vi.mock("../features/sharing/incoming-share-storage", () => ({
98 loadIncomingShareDrafts: async () => [],
99}));
100vi.mock("./entities", () => ({
101 useProjects: () => [],
102 useServerConfigs: () => new Map([["environment-1", config]]),
103 useThreadShells: () => [],
104 useVisibleThreadShells: () => [],
105}));
106vi.mock("./projects", () => ({ environmentProjects: {} }));
107vi.mock("./workspace", async () => {
108 const { Atom } = await import("effect/reactivity");
109 return {
110 workspaceConnections: { environmentsAtom: Atom.make([{ environmentId: "environment-1" }]) },
111 };
112});
113vi.mock("./server", async () => {
114 const { Atom } = await import("effect/reactivity");
115 return { serverEnvironment: { configValueAtom: Atom.family(() => Atom.make(null)) } };
116});
117vi.mock("./git", () => ({ gitEnvironment: {} }));
118vi.mock("./threads", () => ({ threadEnvironment: {} }));
119vi.mock("./use-atom-command", () => ({ useAtomCommand: () => async () => undefined }));
120vi.mock("./session", async () => {
121 const { Atom } = await import("effect/reactivity");
122 const Option = await import("effect/Option");
123 return {
124 readEnvironmentScope: () => native.canOperate,
125 useEnvironmentsWithScope: () => new Set(["environment-1"]),
126 environmentSession: {
127 preparedConnectionValueAtom: Atom.family(() =>
128 Atom.make(Option.some({ httpBaseUrl: "https://environment.example/" })),
129 ),
130 },
131 };
132});
133vi.mock("./attachments", () => ({
134 attachmentEnvironment: { createUploadUrl: native.mint, remove: native.remove },
135}));
136vi.mock("./assets", () => ({ assetEnvironment: { createUrl: (input: unknown) => input } }));
137vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({
138 ...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()),
139 createEnvironmentRpcCommand: () => Symbol("rpc-command"),
140 executeAtomQuery: async (
141 _registry: unknown,
142 query: { input: { resource: { attachmentId: string } } },
143 ) =>
144 native.server.get(query.input.resource.attachmentId)
145 ? { _tag: "Success", value: {} }
146 : (await import("effect/reactivity")).AsyncResult.failure(
147 (await import("effect/Cause")).fail({ _tag: "AssetAttachmentNotFoundError" }),
148 ),
149 runAtomCommand: async (
150 _registry: unknown,
151 command: unknown,
152 target: { input: { attachmentId?: string } },
153 ) => {
154 if (command === native.mint) {
155 const id = `pending-${++native.nextId}`;
156 native.server.set(id, null);
157 return {
158 _tag: "Success",
159 value: { attachmentId: id, relativeUrl: `/upload/${id}`, expiresAt: 1 },
160 };
161 }
162 if (command === native.remove && target.input.attachmentId) {
163 native.deleted.push(target.input.attachmentId);
164 native.server.delete(target.input.attachmentId);
165 return { _tag: "Success", value: undefined };
166 }
167 throw new Error("Unexpected RPC command");
168 },
169}));
170vi.mock("./use-thread-outbox", async () => {
171 const { Atom } = await import("effect/reactivity");
172 return {
173 editingQueuedMessageIdsAtom: Atom.make<Record<string, boolean>>({}).pipe(Atom.keepAlive),
174 dispatchingQueuedMessageIdsAtom: Atom.make<Record<string, true>>({}).pipe(Atom.keepAlive),
175 useThreadOutboxMessages: () =>
176 appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
177 retryingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive),
178 threadOutboxShellStatusesAtom: Atom.make(new Map()),
179 };
180});
181
182import {
183 composerAttachmentUploadBlockReason,
184 composerAttachmentsStillUploading,
185 composerAttachmentUploadKey,
186} from "../lib/composerAttachmentUploadQueue";
187import type { DraftComposerAttachment } from "../lib/composerImages";
188import { Atom } from "effect/reactivity";
189import { appAtomRegistry } from "./atom-registry";
190import {
191 composerAttachmentUploadRequests,
192 composerAttachmentUploadsAtom,
193 createComposerAttachmentUploadWorker,
194} from "./composer-attachment-uploads";
195import {
196 enqueueThreadOutboxMessage,
197 flattenQueuedThreadMessages,
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 "./threadOutboxDelivery";
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: {} } };
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
220const requestsAtom = Atom.make((get) =>
221 composerAttachmentUploadRequests({
222 drafts: get(drafts.composerDraftUploadSourcesAtom),
223 queuedMessagesByThreadKey: get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
224 editingQueuedMessageIds: {},
225 knownEnvironmentIds: [environmentId],
226 connectedEnvironmentIds: new Set([environmentId]),
227 operableEnvironmentIds: new Set([environmentId]),
228 serverConfigs: new Map([[environmentId, config]]),
229 }),
230);
231
232function worker() {
233 const { queue, dispose } = createComposerAttachmentUploadWorker(requestsAtom);
234 disposeWorker = dispose;
235 return queue;
236}
237
238function sendInput() {
239 return {
240 environmentId,
241 attachments: drafts.getComposerDraftSnapshot(draftKey).attachments,
242 connected: true,
243 serverConfig: config,
244 states: appAtomRegistry.get(composerAttachmentUploadsAtom),
245 };
246}
247
248function queuedMessage(): QueuedThreadMessage {
249 return {
250 environmentId,
251 threadId: ThreadId.make("thread-1"),
252 messageId: MessageId.make("message-1"),
253 commandId: CommandId.make("command-1"),
254 text: "Look at this",
255 attachments: drafts.getComposerDraftSnapshot(draftKey).attachments,
256 createdAt: "2026-10-17T00:00:00.000Z",
257 };
258}
259
260beforeEach(async () => {
261 vi.spyOn(console, "warn").mockImplementation(() => {});
262 native.files.clear();
263 native.server.clear();
264 native.deleted.length = 0;
265 native.fault = null;
266 native.canOperate = true;
267 native.nextId = 0;
268 native.nextUuid = 0;
269 native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":{}}'));
270 drafts.resetComposerDraftsLoadState();
271 appAtomRegistry.set(drafts.composerDraftsAtom, {
272 [draftKey]: { text: "Look at this", attachments: [image] },
273 });
274 appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {});
275 await drafts.flushComposerDrafts();
276 await threadOutboxManager.load();
277 native.transfer.mockReset();
278 native.transfer.mockImplementation(async (uri, url, options) => {
279 const bytes = native.files.get(uri)!;
280 options.onProgress?.({ bytesSent: bytes.length, totalBytes: bytes.length });
281 native.server.set(url.split("/").at(-1)!, bytes);
282 return { status: 204 };
283 });
284});
285
286afterEach(async () => {
287 disposeWorker?.();
288 disposeWorker = undefined;
289 native.fault = null;
290 native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":{}}'));
291 drafts.resetComposerDraftsLoadState();
292 await drafts.flushComposerDrafts();
293 await flushThreadOutbox();
294 vi.restoreAllMocks();
295});
296
297function uploadState() {
298 return appAtomRegistry.get(composerAttachmentUploadsAtom)[
299 composerAttachmentUploadKey(environmentId, image.id)
300 ];
301}
302
303it.effect.each(["decode", "write"] as const)(
304 "keeps an accepted upload ready when the draft %s fails",
305 (fault) =>
306 Effect.gen(function* () {
307 native.fault = fault;
308 if (fault === "decode")
309 native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":'));
310 drafts.resetComposerDraftsLoadState();
311 const queue = worker();
312 yield* Effect.promise(() => queue.settled());
313 expect(uploadState()).toEqual({ status: "ready" });
314 expect(native.deleted).toEqual([]);
315 expect(composerAttachmentUploadBlockReason(sendInput())).toBeNull();
316 expect(composerAttachmentsStillUploading(sendInput())).toBe(false);
317
318 const message = queuedMessage();
319 expect(message.attachments[0]?.uploadedAttachmentId).toBe("pending-1");
320 yield* Effect.promise(() => enqueueThreadOutboxMessage(message));
321 const prepared = yield* prepareQueuedMessageAttachments(message);
322 expect(prepared.status).toBe("ready");
323 if (prepared.status !== "ready") throw new Error("Outbox preparation abandoned");
324 expect(prepared.prepared.pendingAttachmentIds).toEqual(["pending-1"]);
325 expect(native.transfer).toHaveBeenCalledTimes(1);
326 }),
327);
328
329it.effect("uploads again at send time when the server swept a finished upload", () =>
330 Effect.gen(function* () {
331 const queue = worker();
332 yield* Effect.promise(() => queue.settled());
333 expect(uploadState()).toEqual({ status: "ready" });
334 // The server sweeps pending uploads nothing claimed, here while the draft sat unsent.
335 native.server.delete("pending-1");
336
337 const message = queuedMessage();
338 yield* Effect.promise(() => enqueueThreadOutboxMessage(message));
339 const prepared = yield* prepareQueuedMessageAttachments(message);
340 expect(prepared.status).toBe("ready");
341 if (prepared.status !== "ready") throw new Error("Outbox preparation abandoned");
342 expect(prepared.prepared.pendingAttachmentIds).toEqual(["pending-2"]);
343 expect(native.transfer).toHaveBeenCalledTimes(2);
344 }),
345);
346
347it("keeps an upload running when its message is sent mid-upload and records it on the message", async () => {
348 const transferStarted = Promise.withResolvers<void>();
349 const finishTransfer = Promise.withResolvers<{ status: number }>();
350 native.transfer.mockImplementationOnce(async (uri, url) => {
351 native.server.set(url.split("/").at(-1)!, native.files.get(uri)!);
352 transferStarted.resolve();
353 return finishTransfer.promise;
354 });
355 const queue = worker();
356 await transferStarted.promise;
357
358 // Send enqueues the message, then clears the draft that owned the upload.
359 await enqueueThreadOutboxMessage(queuedMessage());
360 drafts.clearComposerDraftContent(draftKey, { deferAttachmentCleanup: true });
361 finishTransfer.resolve({ status: 204 });
362 await queue.settled();
363
364 expect(native.transfer).toHaveBeenCalledOnce();
365 expect(native.deleted).toEqual([]);
366 const [queued] = flattenQueuedThreadMessages(
367 appAtomRegistry.get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
368 );
369 expect(queued?.attachments[0]?.uploadedAttachmentId).toBe("pending-1");
370});
371
372it.each(["http", "permission"] as const)(
373 "keeps a real %s upload failure blocking Send",
374 async (failure) => {
375 if (failure === "http") native.transfer.mockResolvedValueOnce({ status: 503 });
376 if (failure === "permission") native.canOperate = false;
377 const queue = worker();
378 await queue.settled();
379 expect(composerAttachmentUploadBlockReason(sendInput())).toBe(
380 "Retry or remove the failed attachment",
381 );
382 expect([...native.server.values()]).toEqual([]);
383 },
384);
385
386it("keeps an unexpected draft flush error blocking Send", async () => {
387 vi.spyOn(drafts, "flushComposerDrafts").mockRejectedValueOnce(
388 new Error("Unexpected flush defect"),
389 );
390 const queue = worker();
391 await queue.settled();
392 expect(composerAttachmentUploadBlockReason(sendInput())).toBe(
393 "Retry or remove the failed attachment",
394 );
395 // The server sweeps pending uploads nothing claims; a retry uploads again.
396 expect(native.deleted).toEqual([]);
397});
398
399it("uploads draft attachments for threads whose ids contain colons", () => {
400 const keys = [
401 "environment-1:thread-1",
402 "environment-1:thread:mcp:namespace:key:0",
403 "environment-1:command-1:fork",
404 "environment-1:thread-1~queued-edit~run:1",
405 ];
406 const requests = composerAttachmentUploadRequests({
407 drafts: Object.fromEntries(keys.map((key) => [key, { attachments: [{ ...image, id: key }] }])),
408 queuedMessagesByThreadKey: {},
409 editingQueuedMessageIds: {},
410 knownEnvironmentIds: [environmentId],
411 connectedEnvironmentIds: new Set([environmentId]),
412 operableEnvironmentIds: new Set([environmentId]),
413 serverConfigs: new Map([[environmentId, config]]),
414 });
415 expect(requests.map((request) => [request.attachment.id, request.environmentId])).toEqual(
416 keys.map((key) => [key, environmentId]),
417 );
418});
419
420it("does not upload a disconnected colon environment's draft to its connected prefix", () => {
421 const connected = EnvironmentId.make("a");
422 const disconnected = EnvironmentId.make("a:vcs-status:b");
423 const requests = composerAttachmentUploadRequests({
424 drafts: { [`${disconnected}:thread-1`]: { attachments: [image] } },
425 queuedMessagesByThreadKey: {},
426 editingQueuedMessageIds: {},
427 knownEnvironmentIds: [connected, disconnected],
428 connectedEnvironmentIds: new Set([connected]),
429 operableEnvironmentIds: new Set([connected]),
430 serverConfigs: new Map([[connected, config]]),
431 });
432 expect(requests).toEqual([]);
433});