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 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 retryingQueuedMessageIdsAtom: Atom.make({}).pipe(Atom.keepAlive),
174 threadOutboxShellStatusesAtom: Atom.make(new Map()),
175 };
176});
177
178import {
179 composerAttachmentUploadBlockReason,
180 composerAttachmentsStillUploading,
181 composerAttachmentUploadKey,
182} from "../lib/composerAttachmentUploadQueue";
183import type { DraftComposerAttachment } from "../lib/composerImages";
184import { Atom } from "effect/reactivity";
185import { appAtomRegistry } from "./atom-registry";
186import {
187 composerAttachmentUploadRequests,
188 composerAttachmentUploadsAtom,
189 createComposerAttachmentUploadWorker,
190} from "./composer-attachment-uploads";
191import {
192 enqueueThreadOutboxMessage,
193 flushThreadOutbox,
194 threadOutboxManager,
195} from "./thread-outbox";
196import type { QueuedThreadMessage } from "./thread-outbox-model";
197import * as drafts from "./use-composer-drafts";
198import { prepareQueuedMessageAttachments } from "./threadOutboxDelivery";
199
200const environmentId = EnvironmentId.make("environment-1");
201const draftKey = "environment-1:thread-1";
202const draftsUri = "file:///documents/composer-drafts/drafts.json";
203const config = { environment: { capabilities: {} } };
204const image: DraftComposerAttachment = {
205 id: "image-1",
206 type: "image",
207 name: "photo.png",
208 mimeType: "image/png",
209 sizeBytes: 3,
210 dataUrl: "data:image/png;base64,YWJj",
211 previewUri: "data:image/png;base64,YWJj",
212};
213let disposeWorker: (() => void) | undefined;
214
215const requestsAtom = Atom.make((get) =>
216 composerAttachmentUploadRequests({
217 drafts: get(drafts.composerDraftUploadSourcesAtom),
218 queuedMessagesByThreadKey: get(threadOutboxManager.queuedMessagesByThreadKeyAtom),
219 knownEnvironmentIds: [environmentId],
220 connectedEnvironmentIds: new Set([environmentId]),
221 operableEnvironmentIds: new Set([environmentId]),
222 serverConfigs: new Map([[environmentId, config]]),
223 }),
224);
225
226function worker() {
227 const { queue, dispose } = createComposerAttachmentUploadWorker(requestsAtom);
228 disposeWorker = dispose;
229 return queue;
230}
231
232function sendInput() {
233 return {
234 environmentId,
235 attachments: drafts.getComposerDraftSnapshot(draftKey).attachments,
236 connected: true,
237 serverConfig: config,
238 states: appAtomRegistry.get(composerAttachmentUploadsAtom),
239 };
240}
241
242function queuedMessage(): QueuedThreadMessage {
243 return {
244 environmentId,
245 threadId: ThreadId.make("thread-1"),
246 messageId: MessageId.make("message-1"),
247 commandId: CommandId.make("command-1"),
248 text: "Look at this",
249 attachments: drafts.getComposerDraftSnapshot(draftKey).attachments,
250 createdAt: "2026-10-17T00:00:00.000Z",
251 };
252}
253
254beforeEach(async () => {
255 vi.spyOn(console, "warn").mockImplementation(() => {});
256 native.files.clear();
257 native.server.clear();
258 native.deleted.length = 0;
259 native.fault = null;
260 native.canOperate = true;
261 native.nextId = 0;
262 native.nextUuid = 0;
263 native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":{}}'));
264 drafts.resetComposerDraftsLoadState();
265 appAtomRegistry.set(drafts.composerDraftsAtom, {
266 [draftKey]: { text: "Look at this", attachments: [image] },
267 });
268 appAtomRegistry.set(threadOutboxManager.queuedMessagesByThreadKeyAtom, {});
269 await drafts.flushComposerDrafts();
270 await threadOutboxManager.load();
271 native.transfer.mockReset();
272 native.transfer.mockImplementation(async (uri, url, options) => {
273 const bytes = native.files.get(uri)!;
274 options.onProgress?.({ bytesSent: bytes.length, totalBytes: bytes.length });
275 native.server.set(url.split("/").at(-1)!, bytes);
276 return { status: 204 };
277 });
278});
279
280afterEach(async () => {
281 disposeWorker?.();
282 disposeWorker = undefined;
283 native.fault = null;
284 native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":{}}'));
285 drafts.resetComposerDraftsLoadState();
286 await drafts.flushComposerDrafts();
287 await flushThreadOutbox();
288 vi.restoreAllMocks();
289});
290
291function uploadState() {
292 return appAtomRegistry.get(composerAttachmentUploadsAtom)[
293 composerAttachmentUploadKey(environmentId, image.id)
294 ];
295}
296
297it.each(["decode", "write"] as const)(
298 "keeps an accepted upload ready when the draft %s fails",
299 async (fault) => {
300 native.fault = fault;
301 if (fault === "decode")
302 native.files.set(draftsUri, Buffer.from('{"schemaVersion":1,"drafts":'));
303 drafts.resetComposerDraftsLoadState();
304 const queue = worker();
305 await queue.settled();
306 expect(uploadState()).toEqual({ status: "ready" });
307 expect(native.deleted).toEqual([]);
308 expect(composerAttachmentUploadBlockReason(sendInput())).toBeNull();
309 expect(composerAttachmentsStillUploading(sendInput())).toBe(false);
310
311 const message = queuedMessage();
312 expect(message.attachments[0]?.uploadedAttachmentId).toBe("pending-1");
313 await enqueueThreadOutboxMessage(message);
314 const prepared = await prepareQueuedMessageAttachments(message);
315 expect(prepared.status).toBe("ready");
316 if (prepared.status !== "ready") throw new Error("Outbox preparation abandoned");
317 expect(prepared.prepared.pendingAttachmentIds).toEqual(["pending-1"]);
318 expect(native.transfer).toHaveBeenCalledTimes(1);
319 },
320);
321
322it.each(["http", "permission"] as const)(
323 "keeps a real %s upload failure blocking Send",
324 async (failure) => {
325 if (failure === "http") native.transfer.mockResolvedValueOnce({ status: 503 });
326 if (failure === "permission") native.canOperate = false;
327 const queue = worker();
328 await queue.settled();
329 expect(composerAttachmentUploadBlockReason(sendInput())).toBe(
330 "Retry or remove the failed attachment",
331 );
332 expect([...native.server.values()]).toEqual([]);
333 },
334);
335
336it("keeps an unexpected draft flush error blocking Send", async () => {
337 vi.spyOn(drafts, "flushComposerDrafts").mockRejectedValueOnce(
338 new Error("Unexpected flush defect"),
339 );
340 const queue = worker();
341 await queue.settled();
342 expect(composerAttachmentUploadBlockReason(sendInput())).toBe(
343 "Retry or remove the failed attachment",
344 );
345 expect(native.deleted).toEqual(["pending-1"]);
346});
347
348it("uploads draft attachments for threads whose ids contain colons", () => {
349 const keys = [
350 "environment-1:thread-1",
351 "environment-1:thread:mcp:namespace:key:0",
352 "environment-1:command-1:fork",
353 "environment-1:thread-1~queued-edit~run:1",
354 ];
355 const requests = composerAttachmentUploadRequests({
356 drafts: Object.fromEntries(keys.map((key) => [key, { attachments: [{ ...image, id: key }] }])),
357 queuedMessagesByThreadKey: {},
358 knownEnvironmentIds: [environmentId],
359 connectedEnvironmentIds: new Set([environmentId]),
360 operableEnvironmentIds: new Set([environmentId]),
361 serverConfigs: new Map([[environmentId, config]]),
362 });
363 expect(requests.map((request) => [request.attachment.id, request.environmentId])).toEqual(
364 keys.map((key) => [key, environmentId]),
365 );
366});
367
368it("does not upload a disconnected colon environment's draft to its connected prefix", () => {
369 const connected = EnvironmentId.make("a");
370 const disconnected = EnvironmentId.make("a:vcs-status:b");
371 const requests = composerAttachmentUploadRequests({
372 drafts: { [`${disconnected}:thread-1`]: { attachments: [image] } },
373 queuedMessagesByThreadKey: {},
374 knownEnvironmentIds: [connected, disconnected],
375 connectedEnvironmentIds: new Set([connected]),
376 operableEnvironmentIds: new Set([connected]),
377 serverConfigs: new Map([[connected, config]]),
378 });
379 expect(requests).toEqual([]);
380});