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 composerAttachmentUploadKey,
7 composerDraftEnvironmentId,
8 createComposerAttachmentUploadQueue,
9 type ComposerAttachmentUploadRequest,
10 type ComposerAttachmentUploadState,
11} from "./composerAttachmentUploadQueue";
12
13const environmentId = EnvironmentId.make("environment-1");
14function request(id: string, environment = environmentId): ComposerAttachmentUploadRequest {
15 return {
16 environmentId: environment,
17 attachment: {
18 id,
19 type: "file",
20 name: `${id}.pdf`,
21 mimeType: "application/pdf",
22 sizeBytes: 42,
23 fileUri: `file:///documents/${id}.pdf`,
24 },
25 };
26}
27
28describe("composer attachment upload queue", () => {
29 it("bounds concurrency, deduplicates updates, and drains all attachments", async () => {
30 const gates = new Map<string, ReturnType<typeof Promise.withResolvers<boolean>>>();
31 const fourthStarted = Promise.withResolvers<void>();
32 const firstThreeStarted = Promise.withResolvers<void>();
33 let active = 0;
34 let maximum = 0;
35 const upload = vi.fn(async (input: ComposerAttachmentUploadRequest) => {
36 active += 1;
37 maximum = Math.max(maximum, active);
38 const gate = Promise.withResolvers<boolean>();
39 gates.set(input.attachment.id, gate);
40 if (gates.size === 3) firstThreeStarted.resolve();
41 if (gates.size === 4) fourthStarted.resolve();
42 try {
43 return await gate.promise;
44 } finally {
45 active -= 1;
46 }
47 });
48 const queue = createComposerAttachmentUploadQueue({ upload, onChange: () => {} });
49 const requests = [request("one"), request("two"), request("three"), request("four")];
50 queue.sync(requests);
51 queue.sync(requests);
52 await firstThreeStarted.promise;
53 expect(upload).toHaveBeenCalledTimes(3);
54 gates.get("one")!.resolve(true);
55 await fourthStarted.promise;
56 for (const gate of gates.values()) gate.resolve(true);
57 await queue.settled();
58 queue.sync(requests);
59 await queue.settled();
60 expect(maximum).toBe(3);
61 expect(upload).toHaveBeenCalledTimes(4);
62 queue.dispose();
63 });
64
65 it("cancels on disconnect and resumes from the same local draft on reconnect", async () => {
66 const started = Promise.withResolvers<void>();
67 let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
68 let signal: AbortSignal | undefined;
69 const upload = vi.fn(
70 async (_request: ComposerAttachmentUploadRequest, currentSignal: AbortSignal) => {
71 signal = currentSignal;
72 started.resolve();
73 return new Promise<boolean>((resolve) =>
74 currentSignal.addEventListener("abort", () => resolve(false), { once: true }),
75 );
76 },
77 );
78 const queue = createComposerAttachmentUploadQueue({
79 upload,
80 onChange: (next) => {
81 states = next;
82 },
83 });
84 const local = request("offline-draft");
85 queue.sync([local]);
86 await started.promise;
87 queue.sync([]);
88 await queue.settled();
89 expect(signal?.aborted).toBe(true);
90 expect(states).toEqual({});
91 upload.mockResolvedValueOnce(true);
92 queue.sync([local]);
93 await queue.settled();
94 expect(upload.mock.calls[1]?.[0]).toBe(local);
95 expect(states[composerAttachmentUploadKey(environmentId, local.attachment.id)]).toEqual({
96 status: "ready",
97 });
98 expect(local.attachment).toMatchObject({ fileUri: "file:///documents/offline-draft.pdf" });
99 queue.dispose();
100 });
101
102 it("ignores a late completion after removal or environment switch", async () => {
103 const gate = Promise.withResolvers<boolean>();
104 const started = Promise.withResolvers<void>();
105 let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
106 const upload = vi.fn(async () => {
107 started.resolve();
108 return gate.promise;
109 });
110 const queue = createComposerAttachmentUploadQueue({
111 upload,
112 onChange: (next) => {
113 states = next;
114 },
115 });
116 queue.sync([request("photo")]);
117 await started.promise;
118 upload.mockResolvedValueOnce(true);
119 const other = EnvironmentId.make("environment-2");
120 queue.sync([request("photo", other)]);
121 gate.resolve(true);
122 await queue.settled();
123 expect(states).toEqual({ [composerAttachmentUploadKey(other, "photo")]: { status: "ready" } });
124 queue.sync([]);
125 expect(states).toEqual({});
126 queue.dispose();
127 });
128
129 it("restarts a re-added attachment after its aborted transfer finishes settling", async () => {
130 const firstStarted = Promise.withResolvers<void>();
131 const firstSettled = Promise.withResolvers<boolean>();
132 const secondStarted = Promise.withResolvers<void>();
133 const secondSettled = Promise.withResolvers<boolean>();
134 let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
135 let firstSignal: AbortSignal | undefined;
136 const upload = vi.fn(async (_request: ComposerAttachmentUploadRequest, signal: AbortSignal) => {
137 if (!firstSignal) {
138 firstSignal = signal;
139 firstStarted.resolve();
140 return firstSettled.promise;
141 }
142 secondStarted.resolve();
143 return secondSettled.promise;
144 });
145 const queue = createComposerAttachmentUploadQueue({
146 upload,
147 onChange: (next) => {
148 states = next;
149 },
150 });
151 const local = request("re-added");
152 queue.sync([local]);
153 await firstStarted.promise;
154 queue.sync([]);
155 queue.sync([local]);
156 expect(firstSignal?.aborted).toBe(true);
157 expect(upload).toHaveBeenCalledOnce();
158 firstSettled.resolve(false);
159 await secondStarted.promise;
160 expect(upload).toHaveBeenCalledTimes(2);
161 secondSettled.resolve(true);
162 await queue.settled();
163 expect(states[composerAttachmentUploadKey(environmentId, local.attachment.id)]).toEqual({
164 status: "ready",
165 });
166 queue.dispose();
167 });
168
169 it("keeps failures stable until retry and reports bounded progress", async () => {
170 let states: Readonly<Record<string, ComposerAttachmentUploadState>> = {};
171 const progress: number[] = [];
172 const upload = vi.fn(
173 async (
174 _request: ComposerAttachmentUploadRequest,
175 _signal: AbortSignal,
176 report: (value: number) => void,
177 ): Promise<boolean> => {
178 report(0.12);
179 report(0.13);
180 report(1.1);
181 throw new Error("Server unavailable");
182 },
183 );
184 const queue = createComposerAttachmentUploadQueue({
185 upload,
186 onChange: (next) => {
187 states = next;
188 const state = next[composerAttachmentUploadKey(environmentId, "file")];
189 if (state?.status === "uploading") progress.push(state.progress);
190 },
191 });
192 queue.sync([request("file")]);
193 await queue.settled();
194 queue.sync([request("file")]);
195 expect(upload).toHaveBeenCalledOnce();
196 expect(states[composerAttachmentUploadKey(environmentId, "file")]).toEqual({
197 status: "failed",
198 reason: "Server unavailable",
199 });
200 expect(progress).toEqual([0, 0.1, 1]);
201 upload.mockImplementationOnce(async () => true);
202 queue.retry(environmentId, "file");
203 await queue.settled();
204 expect(states[composerAttachmentUploadKey(environmentId, "file")]).toEqual({ status: "ready" });
205 queue.dispose();
206 });
207
208 it("does not spin when an upload's draft was abandoned before persistence", async () => {
209 const upload = vi.fn(async () => false);
210 const queue = createComposerAttachmentUploadQueue({ upload, onChange: () => {} });
211 queue.sync([request("discarded")]);
212 await queue.settled();
213 expect(upload).toHaveBeenCalledOnce();
214 queue.dispose();
215 });
216});
217
218describe("draft upload scope and offline submission", () => {
219 it("resolves thread, new-task, and queued-task drafts without crossing environments", () => {
220 expect(composerDraftEnvironmentId("environment-1:thread", [])).toBe(environmentId);
221 expect(composerDraftEnvironmentId("new-task:environment-1:project", [])).toBe(environmentId);
222 expect(
223 composerDraftEnvironmentId("pending-task:message", [{ messageId: "message", environmentId }]),
224 ).toBe(environmentId);
225 expect(composerDraftEnvironmentId("pending-task:missing", [])).toBeNull();
226 const colonEnvironment = EnvironmentId.make("a:vcs-status:b");
227 expect(composerDraftEnvironmentId(`${colonEnvironment}:thread`, [])).toBe(colonEnvironment);
228 expect(composerDraftEnvironmentId(`new-task:${colonEnvironment}:project`, [])).toBe(
229 colonEnvironment,
230 );
231 });
232
233 it("allows offline queuing while a connected composer waits for upload or retry", () => {
234 const key = composerAttachmentUploadKey(environmentId, "file");
235 const input = {
236 environmentId,
237 attachments: [request("file").attachment],
238 connected: true,
239 serverConfig: {
240 environment: {
241 capabilities: { attachmentUploads: true, fileAttachments: { maxUploadBytes: 1024 } },
242 },
243 },
244 states: {},
245 };
246 expect(composerAttachmentUploadBlockReason(input)).toBe("Attachment still uploading");
247 expect(composerAttachmentUploadBlockReason({ ...input, connected: false })).toBeNull();
248 expect(
249 composerAttachmentUploadBlockReason({
250 ...input,
251 states: { [key]: { status: "failed", reason: "Offline" } },
252 }),
253 ).toBe("Retry or remove the failed attachment");
254 expect(
255 composerAttachmentUploadBlockReason({ ...input, states: { [key]: { status: "ready" } } }),
256 ).toBeNull();
257 });
258});