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