@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 413 lines 14.1 KB
Raw
1 import { AtomRegistry } from "effect/reactivity";
2 import { describe, expect, it, vi } from "vite-plus/test";
3
4 import type { DraftComposerAttachment } from "../../lib/composerImages";
5 import type { IncomingShareDraft } from "../sharing/incoming-share-model";
6 import { undoComposerDraftMergeState, type ComposerDraft } from "../../state/use-composer-drafts";
7 import {
8 makeIncomingShareImports,
9 type ShareImportDeps,
10 type ShareImportPhase,
11 type ShareImportTarget,
12 transitionShareImport,
13 } from "./incomingShareImport";
14
15 const destination = { environmentId: "env-1", projectId: "project-1" };
16 const edited: ComposerDraft = { text: "typed after the undo", attachments: [] };
17
18 /** The draft store's own undo, applied to the test's draft map. */
19 function undoInto(
20 drafts: Map<string, ComposerDraft>,
21 draftKey: string,
22 snapshot: ComposerDraft,
23 merged: ComposerDraft,
24 ): void {
25 const next = undoComposerDraftMergeState(Object.fromEntries(drafts), draftKey, snapshot, merged);
26 drafts.clear();
27 for (const [key, draft] of Object.entries(next)) drafts.set(key, draft);
28 }
29
30 function mergeInto(
31 drafts: Map<string, ComposerDraft>,
32 draftKey: string,
33 content: {
34 readonly text: string;
35 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
36 },
37 ): void {
38 const existing = drafts.get(draftKey) ?? { text: "", attachments: [] };
39 drafts.set(draftKey, {
40 text: `${existing.text}\n${content.text}`,
41 attachments: [...existing.attachments, ...content.attachments],
42 });
43 }
44
45 function fileAttachment(id: string): DraftComposerAttachment {
46 return {
47 id,
48 type: "file",
49 name: `${id}.txt`,
50 mimeType: "text/plain",
51 sizeBytes: 4,
52 fileUri: `file:///${id}.txt`,
53 };
54 }
55
56 function share(attachments: ReadonlyArray<DraftComposerAttachment> = []): IncomingShareDraft {
57 return {
58 schemaVersion: 1,
59 id: "share-1",
60 createdAt: "2026-01-01T00:00:00.000Z",
61 text: "shared text",
62 attachments,
63 warnings: [],
64 };
65 }
66
67 function importTarget(overrides: Partial<ShareImportTarget> = {}): ShareImportTarget {
68 return {
69 flowKey: "flow-a",
70 routeKey: "route-a",
71 draftKey: "draft-a",
72 destination,
73 shareId: "share-1",
74 ...overrides,
75 };
76 }
77
78 function setup(overrides: Partial<ShareImportDeps> = {}) {
79 const drafts = new Map<string, ComposerDraft>([["draft-a", { text: "mine", attachments: [] }]]);
80 const inbox = new Map<string, IncomingShareDraft>([["share-1", share()]]);
81 const calls: Array<string> = [];
82 const registry = overrides.registry ?? AtomRegistry.make();
83 const deps: ShareImportDeps = {
84 registry,
85 getShare: (shareId) => inbox.get(shareId) ?? null,
86 reserve: vi.fn(async () => {
87 calls.push("reserve");
88 }),
89 release: vi.fn(async () => {
90 calls.push("release");
91 }),
92 consume: vi.fn(async () => {
93 calls.push("consume");
94 }),
95 readDraft: (draftKey) => drafts.get(draftKey) ?? { text: "", attachments: [] },
96 undoMerge: vi.fn(async (draftKey, snapshot, merged) => {
97 calls.push("undo");
98 undoInto(drafts, draftKey, snapshot, merged);
99 }),
100 mergeIntoDraft: vi.fn(async (draftKey, content) => {
101 calls.push("merge");
102 mergeInto(drafts, draftKey, content);
103 return { skippedAttachmentCount: 0 };
104 }),
105 selectAttachments: (incoming) => ({
106 status: "ready",
107 attachments: incoming.attachments,
108 warnings: [],
109 }),
110 releaseUnusedAttachments: vi.fn(),
111 onWarnings: vi.fn(),
112 onImportFailure: vi.fn(),
113 onCancelFailure: vi.fn(),
114 leave: vi.fn(),
115 ...overrides,
116 };
117 const imports = makeIncomingShareImports(deps);
118 const watch = (target: ShareImportTarget) => {
119 const atom = imports.phaseAtom(target);
120 const unmount = registry.mount(atom);
121 registry.get(atom);
122 return { phase: (): ShareImportPhase => registry.get(atom), unmount };
123 };
124 return { imports, deps, drafts, inbox, calls, watch, registry };
125 }
126
127 describe("transitionShareImport", () => {
128 it("only cancels or retries from a failure, and keeps terminal phases terminal", () => {
129 expect(transitionShareImport("attaching", "cancel")).toBe("attaching");
130 expect(transitionShareImport("failed", "start")).toBe("reserving");
131 expect(transitionShareImport("cancelling", "cancelFailed")).toBe("failed");
132 expect(transitionShareImport("done", "start")).toBe("done");
133 expect(transitionShareImport("cancelled", "start")).toBe("cancelled");
134 });
135 });
136
137 describe("incoming share imports", () => {
138 it("reserves, attaches and consumes once, releasing files the draft did not keep", async () => {
139 const kept = fileAttachment("kept");
140 const skipped = fileAttachment("skipped");
141 const { deps, calls, drafts, inbox, imports, watch } = setup({
142 selectAttachments: () => ({ status: "ready", attachments: [kept], warnings: ["too big"] }),
143 });
144 inbox.set("share-1", share([kept, skipped]));
145 const target = importTarget();
146 const watched = watch(target);
147
148 expect(watched.phase()).toBe("reserving");
149 await imports.settled(target);
150 expect(watched.phase()).toBe("done");
151
152 expect(calls).toEqual(["reserve", "merge", "consume"]);
153 expect(drafts.get("draft-a")?.attachments).toEqual([kept]);
154 expect(deps.releaseUnusedAttachments).toHaveBeenCalledWith([skipped]);
155 expect(deps.onWarnings).toHaveBeenCalledWith(["too big"]);
156 });
157
158 it("runs once when its atom node is removed and rebuilt", async () => {
159 const { imports, deps } = setup();
160 const tasks: Array<() => void> = [];
161 const registry = AtomRegistry.make({
162 scheduleTask: (task) => {
163 tasks.push(task);
164 return () => undefined;
165 },
166 });
167 const atom = imports.phaseAtom(importTarget());
168
169 registry.get(atom);
170 tasks.splice(0).forEach((task) => task());
171 expect(registry.getNodes().size).toBe(0);
172 const unmount = registry.mount(atom);
173 await imports.settled(importTarget());
174 expect(registry.get(atom)).toBe("done");
175 unmount();
176
177 expect(deps.reserve).toHaveBeenCalledTimes(1);
178 expect(deps.consume).toHaveBeenCalledTimes(1);
179 });
180
181 it("cancel after a failed consume restores the draft, releases the reservation and leaves", async () => {
182 const { deps, calls, drafts, watch, imports } = setup({
183 consume: vi.fn(async () => {
184 throw new Error("disk full");
185 }),
186 });
187 const target = importTarget();
188 const watched = watch(target);
189 await imports.settled(target);
190 expect(watched.phase()).toBe("failed");
191 expect(deps.onImportFailure).toHaveBeenCalledWith(target, new Error("disk full"));
192
193 await imports.cancel(target);
194
195 expect(watched.phase()).toBe("cancelled");
196 expect(calls).toEqual(["reserve", "merge", "undo", "release"]);
197 expect(drafts.get("draft-a")).toEqual({ text: "mine", attachments: [] });
198 // Unconsumed: the inbox still owns the files.
199 expect(deps.releaseUnusedAttachments).not.toHaveBeenCalled();
200 expect(deps.leave).toHaveBeenCalledWith(target);
201 });
202
203 it("a failed cancel can be retried and keeps the original backup", async () => {
204 let releaseAttempts = 0;
205 const { deps, drafts, watch, imports } = setup({
206 consume: vi.fn(async () => {
207 throw new Error("disk full");
208 }),
209 release: vi.fn(async () => {
210 releaseAttempts += 1;
211 if (releaseAttempts === 1) throw new Error("locked");
212 }),
213 });
214 const target = importTarget();
215 const watched = watch(target);
216 await imports.settled(target);
217 expect(watched.phase()).toBe("failed");
218
219 await imports.cancel(target);
220 expect(watched.phase()).toBe("failed");
221 expect(deps.onCancelFailure).toHaveBeenCalledWith(target, new Error("locked"));
222 expect(deps.leave).not.toHaveBeenCalled();
223
224 await imports.cancel(target);
225 expect(watched.phase()).toBe("cancelled");
226 expect(deps.undoMerge).toHaveBeenCalledTimes(1);
227 expect(drafts.get("draft-a")).toEqual({ text: "mine", attachments: [] });
228 expect(deps.leave).toHaveBeenCalledTimes(1);
229 });
230
231 it("stops before consuming once its route leaves the stack", async () => {
232 const mergeStarted = Promise.withResolvers<void>();
233 const merged = Promise.withResolvers<{ readonly skippedAttachmentCount: number }>();
234 const { deps, imports, watch } = setup({
235 mergeIntoDraft: () => {
236 mergeStarted.resolve();
237 return merged.promise;
238 },
239 });
240 const watched = watch(importTarget());
241 await mergeStarted.promise;
242 expect(watched.phase()).toBe("attaching");
243
244 const pruned = imports.prune(new Set(["flow-b"]));
245 merged.resolve({ skippedAttachmentCount: 0 });
246 await pruned;
247
248 expect(deps.consume).not.toHaveBeenCalled();
249 expect(deps.onImportFailure).not.toHaveBeenCalled();
250 watched.unmount();
251 });
252
253 const userChanges = [
254 ["edited", (drafts: Map<string, ComposerDraft>) => drafts.set("draft-a", edited), edited],
255 ["deleted", (drafts: Map<string, ComposerDraft>) => drafts.delete("draft-a"), undefined],
256 ] as const;
257
258 it.each(userChanges)(
259 "a retried cancel keeps a draft the user %s after the undo was shown",
260 async (_change, change, expected) => {
261 let undoAttempts = 0;
262 const { deps, drafts, watch, imports } = setup({
263 consume: vi.fn(async () => {
264 throw new Error("disk full");
265 }),
266 // Like undoComposerDraftMerge: publishes, then fails to persist.
267 undoMerge: vi.fn(
268 async (draftKey: string, snapshot: ComposerDraft, merged: ComposerDraft) => {
269 undoAttempts += 1;
270 undoInto(drafts, draftKey, snapshot, merged);
271 if (undoAttempts === 1) throw new Error("write failed");
272 },
273 ),
274 });
275 const target = importTarget();
276 const watched = watch(target);
277 await imports.settled(target);
278 await imports.cancel(target);
279 expect(deps.onCancelFailure).toHaveBeenCalledWith(target, new Error("write failed"));
280
281 change(drafts);
282 await imports.cancel(target);
283
284 expect(watched.phase()).toBe("cancelled");
285 expect(drafts.get("draft-a")).toEqual(expected);
286 expect(deps.release).toHaveBeenCalledTimes(1);
287 },
288 );
289
290 it("cancel undoes the import after an upload finished on its attachment", async () => {
291 const file = fileAttachment("file");
292 const { drafts, inbox, watch, imports } = setup({
293 consume: vi.fn(async () => {
294 throw new Error("disk full");
295 }),
296 });
297 inbox.set("share-1", share([file]));
298 const target = importTarget();
299 watch(target);
300 await imports.settled(target);
301
302 const merged = drafts.get("draft-a");
303 drafts.set("draft-a", {
304 text: merged?.text ?? "",
305 attachments: [{ ...file, uploadedAttachmentId: "uploaded-1" }],
306 });
307 await imports.cancel(target);
308
309 expect(drafts.get("draft-a")).toEqual({ text: "mine", attachments: [] });
310 });
311
312 it.each(userChanges)(
313 "cancel keeps a draft the user %s after a merge that published but failed to persist",
314 async (_change, change, expected) => {
315 const { drafts, watch, imports } = setup({
316 // Like mergeComposerDraftContent: publishes, then fails to persist.
317 mergeIntoDraft: vi.fn(async (draftKey, content) => {
318 mergeInto(drafts, draftKey, content);
319 throw new Error("write failed");
320 }),
321 });
322 const target = importTarget();
323 const watched = watch(target);
324 await imports.settled(target);
325 expect(watched.phase()).toBe("failed");
326
327 change(drafts);
328 await imports.cancel(target);
329
330 expect(watched.phase()).toBe("cancelled");
331 expect(drafts.get("draft-a")).toEqual(expected);
332 },
333 );
334
335 it("cancel after a merge that published but failed to persist removes the merged share", async () => {
336 const { drafts, watch, imports } = setup({
337 mergeIntoDraft: vi.fn(async (draftKey, content) => {
338 mergeInto(drafts, draftKey, content);
339 throw new Error("write failed");
340 }),
341 });
342 const target = importTarget();
343 watch(target);
344 await imports.settled(target);
345
346 await imports.cancel(target);
347
348 expect(drafts.get("draft-a")).toEqual({ text: "mine", attachments: [] });
349 });
350
351 it("a failed import keeps its cancel after its route left, and reports a failed undo", async () => {
352 const { calls, deps, imports, watch } = setup({
353 consume: vi.fn(async () => {
354 throw new Error("disk full");
355 }),
356 release: vi.fn(async () => {
357 throw new Error("locked");
358 }),
359 });
360 const target = importTarget();
361 const watched = watch(target);
362 await imports.settled(target);
363 expect(watched.phase()).toBe("failed");
364 watched.unmount();
365 await imports.prune(new Set());
366
367 await imports.cancel(target);
368
369 expect(calls).toEqual(["reserve", "merge", "undo"]);
370 expect(deps.onCancelFailure).toHaveBeenCalledWith(target, new Error("locked"));
371 expect(deps.leave).not.toHaveBeenCalled();
372 });
373
374 it("a route switching drafts abandons the in-flight import", async () => {
375 const reserved = Promise.withResolvers<void>();
376 const { deps, imports, watch } = setup({
377 reserve: vi.fn().mockReturnValueOnce(reserved.promise).mockResolvedValue(undefined),
378 });
379 watch(importTarget()).unmount();
380 const secondTarget = importTarget({ draftKey: "draft-b" });
381 const second = watch(secondTarget);
382 reserved.resolve();
383
384 await imports.settled(secondTarget);
385 expect(second.phase()).toBe("done");
386 expect(deps.mergeIntoDraft).toHaveBeenCalledTimes(1);
387 expect(deps.mergeIntoDraft).toHaveBeenCalledWith("draft-b", expect.anything());
388 });
389
390 it("stays in flight for its route after the screen stops rendering its target", async () => {
391 const mergeStarted = Promise.withResolvers<void>();
392 const merged = Promise.withResolvers<{ readonly skippedAttachmentCount: number }>();
393 const { imports, registry, watch } = setup({
394 mergeIntoDraft: () => {
395 mergeStarted.resolve();
396 return merged.promise;
397 },
398 });
399 const inFlight = imports.inFlightAtom("flow-a");
400 const unmountInFlight = registry.mount(inFlight);
401 const target = importTarget();
402 const watched = watch(target);
403 await mergeStarted.promise;
404
405 watched.unmount();
406 expect(registry.get(inFlight)).toBe(true);
407
408 merged.resolve({ skippedAttachmentCount: 0 });
409 await imports.settled(target);
410 expect(registry.get(inFlight)).toBe(false);
411 unmountInFlight();
412 });
413 });