Open History to see the last commit
1import { EnvironmentId } from "@t3tools/contracts";
2import { describe, expect, it, vi } from "vite-plus/test";
3
4import {
5 composerAttachmentUploadBlockReason,
6 composerAttachmentsStillUploading,
7 composerAttachmentUploadKey,
8 composerDraftEnvironmentId,
9 createComposerAttachmentUploadQueue,
10 type ComposerAttachmentUploadRequest,
11 type ComposerAttachmentUploadState,
12} from "./composerAttachmentUploadQueue";
13
14const environmentId = EnvironmentId.make("environment-1");
15function request(id: string, environment = environmentId): ComposerAttachmentUploadRequest {
16 return {
17 environmentId: environment,
18 attachment: {
19 id,
20 type: "file",
21 name: `${id}.pdf`,
22 mimeType: "application/pdf",
23 sizeBytes: 42,
24 fileUri: `file:///documents/${id}.pdf`,
25 },
26 };
27}
28
29describe("composer attachment upload queue", () => {
30 it("bounds concurrency, deduplicates updates, and drains all attachments", async () => {
31 const gates = new Map<string, ReturnType<typeof Promise.withResolvers<boolean>>>();
32 const fourthStarted = Promise.withResolvers<void>();
33 const firstThreeStarted = Promise.withResolvers<void>();
34 let active = 0;
35 let maximum = 0;
36 const upload = vi.fn(async (input: ComposerAttachmentUploadRequest) => {
37 active += 1;
38 maximum = Math.max(maximum, active);
39 const gate = Promise.withResolvers<boolean>();
40 gates.set(input.attachment.id, gate);
41 if (gates.size === 3) firstThreeStarted.resolve();
42 if (gates.size === 4) fourthStarted.resolve();
43 try {
44 return await gate.promise;
45 } finally {
46 active -= 1;
47 }
48 });
49 const queue = createComposerAttachmentUploadQueue({ upload, onChange: () => {} });
50 const requests = [request("one"), request("two"), request("three"), request("four")];
51 queue.sync(requests);
52 queue.sync(requests);
53 await firstThreeStarted.promise;
54 expect(upload).toHaveBeenCalledTimes(3);
55 gates.get("one")!.resolve(true);
56 await fourthStarted.promise;
57 for (const gate of gates.values()) gate.resolve(true);
58 await queue.settled();
59 queue.sync(requests);
60 await queue.settled();
61 expect(maximum).toBe(3);
62 expect(upload).toHaveBeenCalledTimes(4);
63 queue.dispose();
64 });
65
66 it("cancels on disconnect and resumes from the same local draft on reconnect", async () => {
67 const started = Promise.withResolvers<void>();
68 let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
69 let signal: AbortSignal | undefined;
70 const upload = vi.fn(
71 async (_request: ComposerAttachmentUploadRequest, currentSignal: AbortSignal) => {
72 signal = currentSignal;
73 started.resolve();
74 return new Promise<boolean>((resolve) =>
75 currentSignal.addEventListener("abort", () => resolve(false), { once: true }),
76 );
77 },
78 );
79 const queue = createComposerAttachmentUploadQueue({
80 upload,
81 onChange: (next) => {
82 states = next;
83 },
84 });
85 const local = request("offline-draft");
86 queue.sync([local]);
87 await started.promise;
88 queue.sync([]);
89 await queue.settled();
90 expect(signal?.aborted).toBe(true);
91 expect(states).toEqual({});
92 upload.mockResolvedValueOnce(true);
93 queue.sync([local]);
94 await queue.settled();
95 expect(upload.mock.calls[1]?.[0]).toBe(local);
96 expect(states[composerAttachmentUploadKey(environmentId, local.attachment.id)]).toEqual({
97 status: "ready",
98 });
99 expect(local.attachment).toMatchObject({ fileUri: "file:///documents/offline-draft.pdf" });
100 queue.dispose();
101 });
102
103 it("ignores a late completion after removal or environment switch", async () => {
104 const gate = Promise.withResolvers<boolean>();
105 const started = Promise.withResolvers<void>();
106 let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
107 const upload = vi.fn(async () => {
108 started.resolve();
109 return gate.promise;
110 });
111 const queue = createComposerAttachmentUploadQueue({
112 upload,
113 onChange: (next) => {
114 states = next;
115 },
116 });
117 queue.sync([request("photo")]);
118 await started.promise;
119 upload.mockResolvedValueOnce(true);
120 const other = EnvironmentId.make("environment-2");
121 queue.sync([request("photo", other)]);
122 gate.resolve(true);
123 await queue.settled();
124 expect(states).toEqual({ [composerAttachmentUploadKey(other, "photo")]: { status: "ready" } });
125 queue.sync([]);
126 expect(states).toEqual({});
127 queue.dispose();
128 });
129
130 it("restarts a re-added attachment after its aborted transfer finishes settling", async () => {
131 const firstStarted = Promise.withResolvers<void>();
132 const firstSettled = Promise.withResolvers<boolean>();
133 const secondStarted = Promise.withResolvers<void>();
134 const secondSettled = Promise.withResolvers<boolean>();
135 let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
136 let firstSignal: AbortSignal | undefined;
137 const upload = vi.fn(async (_request: ComposerAttachmentUploadRequest, signal: AbortSignal) => {
138 if (!firstSignal) {
139 firstSignal = signal;
140 firstStarted.resolve();
141 return firstSettled.promise;
142 }
143 secondStarted.resolve();
144 return secondSettled.promise;
145 });
146 const queue = createComposerAttachmentUploadQueue({
147 upload,
148 onChange: (next) => {
149 states = next;
150 },
151 });
152 const local = request("re-added");
153 queue.sync([local]);
154 await firstStarted.promise;
155 queue.sync([]);
156 queue.sync([local]);
157 expect(firstSignal?.aborted).toBe(true);
158 expect(upload).toHaveBeenCalledOnce();
159 firstSettled.resolve(false);
160 await secondStarted.promise;
161 expect(upload).toHaveBeenCalledTimes(2);
162 secondSettled.resolve(true);
163 await queue.settled();
164 expect(states[composerAttachmentUploadKey(environmentId, local.attachment.id)]).toEqual({
165 status: "ready",
166 });
167 queue.dispose();
168 });
169
170 it("keeps failures stable until retry and reports bounded progress", async () => {
171 let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
172 const progress: number[] = [];
173 const upload = vi.fn(
174 async (
175 _request: ComposerAttachmentUploadRequest,
176 _signal: AbortSignal,
177 report: (value: number) => void,
178 ): Promise<boolean> => {
179 report(0.12);
180 report(0.13);
181 report(1.1);
182 throw new Error("Server unavailable");
183 },
184 );
185 const queue = createComposerAttachmentUploadQueue({
186 upload,
187 onChange: (next) => {
188 states = next;
189 const state = next[composerAttachmentUploadKey(environmentId, "file")];
190 if (state?.status === "uploading") progress.push(state.progress);
191 },
192 });
193 queue.sync([request("file")]);
194 await queue.settled();
195 queue.sync([request("file")]);
196 expect(upload).toHaveBeenCalledOnce();
197 expect(states[composerAttachmentUploadKey(environmentId, "file")]).toEqual({
198 status: "failed",
199 reason: "Server unavailable",
200 });
201 expect(progress).toEqual([0, 0.1, 1]);
202 upload.mockImplementationOnce(async () => true);
203 queue.retry(environmentId, "file");
204 await queue.settled();
205 expect(states[composerAttachmentUploadKey(environmentId, "file")]).toEqual({ status: "ready" });
206 queue.dispose();
207 });
208
209 it("does not spin when an upload's draft was abandoned before persistence", async () => {
210 const upload = vi.fn(async () => false);
211 const queue = createComposerAttachmentUploadQueue({ upload, onChange: () => {} });
212 queue.sync([request("discarded")]);
213 await queue.settled();
214 expect(upload).toHaveBeenCalledOnce();
215 queue.dispose();
216 });
217});
218
219describe("draft upload scope and offline submission", () => {
220 it("resolves thread, new-task, and queued-task drafts without crossing environments", () => {
221 expect(composerDraftEnvironmentId("environment-1:thread", [])).toBe(environmentId);
222 expect(composerDraftEnvironmentId("new-task:environment-1:project", [])).toBe(environmentId);
223 expect(
224 composerDraftEnvironmentId("pending-task:message", [{ messageId: "message", environmentId }]),
225 ).toBe(environmentId);
226 expect(composerDraftEnvironmentId("pending-task:missing", [])).toBeNull();
227 const colonEnvironment = EnvironmentId.make("a:vcs-status:b");
228 expect(composerDraftEnvironmentId(`${colonEnvironment}:thread`, [])).toBe(colonEnvironment);
229 expect(composerDraftEnvironmentId(`new-task:${colonEnvironment}:project`, [])).toBe(
230 colonEnvironment,
231 );
232 });
233
234 it("reads an id-keyed new-task draft's environment from its project stamp", () => {
235 const stamped = {
236 project: {
237 environmentId,
238 projectId: "project" as never,
239 createdAt: "2026-09-05T00:00:00.000Z",
240 },
241 };
242 expect(composerDraftEnvironmentId("new-task:abc123-def456", [], stamped)).toBe(environmentId);
243 // An id-keyed draft that lost its stamp belongs to nobody: uploads must
244 // not start and sign-out must not sweep it into some other environment.
245 expect(composerDraftEnvironmentId("new-task:abc123-def456", [])).toBeNull();
246 // The stamp wins over a legacy-looking key when both are present.
247 expect(composerDraftEnvironmentId("new-task:environment-2:project", [], stamped)).toBe(
248 environmentId,
249 );
250 });
251
252 it("only a failed upload blocks sending; an in-flight one queues instead", () => {
253 const key = composerAttachmentUploadKey(environmentId, "file");
254 const input = {
255 environmentId,
256 attachments: [request("file").attachment],
257 connected: true,
258 serverConfig: {
259 environment: {
260 capabilities: { attachmentUploads: true, fileAttachments: { maxUploadBytes: 1024 } },
261 },
262 },
263 states: {},
264 };
265 // Not started yet and mid-transfer both let the send through as a queued
266 // message; the outbox drain finishes (or redoes) the upload.
267 expect(composerAttachmentUploadBlockReason(input)).toBeNull();
268 expect(composerAttachmentsStillUploading(input)).toBe(true);
269 expect(
270 composerAttachmentsStillUploading({
271 ...input,
272 states: { [key]: { status: "uploading", progress: 0.6 } },
273 }),
274 ).toBe(true);
275 expect(composerAttachmentUploadBlockReason({ ...input, connected: false })).toBeNull();
276 expect(
277 composerAttachmentUploadBlockReason({
278 ...input,
279 states: { [key]: { status: "failed", reason: "Offline" } },
280 }),
281 ).toBe("Retry or remove the failed attachment");
282 expect(
283 composerAttachmentsStillUploading({
284 ...input,
285 states: { [key]: { status: "failed", reason: "Offline" } },
286 }),
287 ).toBe(false);
288 expect(
289 composerAttachmentUploadBlockReason({ ...input, states: { [key]: { status: "ready" } } }),
290 ).toBeNull();
291 expect(
292 composerAttachmentsStillUploading({ ...input, states: { [key]: { status: "ready" } } }),
293 ).toBe(false);
294 // Attachments the environment cannot accept never count as uploading.
295 expect(composerAttachmentsStillUploading({ ...input, serverConfig: null })).toBe(false);
296 });
297});