Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

composerContextClipboard.test.ts

299 lines11.0 KB

1import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
2import {
3 COMPOSER_CONTEXT_MAX_RECORDS,
4 ComposerContextId,
5 EnvironmentId,
6 ThreadId,
7} from "@t3tools/contracts";
8import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
9import {
10 collectComposerContextReferences,
11 formatComposerContextReference,
12} from "@t3tools/shared/composerContextReferences";
13​
14const mocks = vi.hoisted(() => ({
15 execute: vi.fn(),
16 download: vi.fn(),
17 persist: vi.fn(),
18 remove: vi.fn(),
19 local: vi.fn(),
20 preview: vi.fn(),
21 dispose: vi.fn(),
22 sequence: 0,
23}));
24vi.mock("expo", () => ({ requireNativeModule: vi.fn() }));
25vi.mock("expo-file-system", () => ({
26 File: class {
27 size = 42;
28 },
29}));
30vi.mock("../state/atom-registry", () => ({
31 appAtomRegistry: {
32 get: () => ({ _tag: "Some", value: { httpBaseUrl: "https://source.example" } }),
33 },
34}));
35vi.mock("../state/session", () => ({
36 environmentSession: { preparedConnectionValueAtom: vi.fn() },
37}));
38vi.mock("../state/assets", () => ({ assetEnvironment: { createUrl: (value: unknown) => value } }));
39vi.mock("../state/use-composer-drafts", () => ({
40 waitForComposerDraftsLoaded: async () => {},
41 findLocalComposerClipboardAttachment: mocks.local,
42}));
43vi.mock("@t3tools/client-runtime/state/runtime", () => ({
44 executeAtomQuery: mocks.execute,
45 squashAtomCommandFailure: () => new Error("offline"),
46}));
47vi.mock("./attachmentDownload", () => ({ downloadAttachmentForPreview: mocks.download }));
48vi.mock("./localAttachmentPreview", () => ({ loadLocalAttachmentPreview: mocks.preview }));
49vi.mock("./composerImages", () => ({
50 persistComposerAttachmentFile: mocks.persist,
51 removePersistedComposerAttachmentFile: mocks.remove,
52}));
53vi.mock("./uuid", () => ({ uuidv4: () => `import-${++mocks.sequence}` }));
54​
55import { importComposerContextClipboard } from "./composerContextClipboard";
56import { createComposerContextHistory } from "./composerContext";
57​
58const image = {
59 version: 1 as const,
60 kind: "image" as const,
61 contextId: ComposerContextId.make("image-source"),
62 label: "Checkout",
63 name: "checkout.png",
64 mimeType: "image/png",
65 sizeBytes: 7,
66 attachmentId: "source-file",
67};
68const terminal = {
69 version: 1 as const,
70 kind: "terminal" as const,
71 contextId: ComposerContextId.make("terminal-source"),
72 label: "Build",
73 terminalId: "main",
74 terminalLabel: "Terminal",
75 lineStart: 1,
76 lineEnd: 1,
77 text: "Build failed",
78};
79const clipboard = {
80 text: "![Checkout](t3-context://v1/image/image-source) [Build](t3-context://v1/terminal/terminal-source)",
81 fragment: encodeComposerContextFragment({
82 version: 1,
83 source: { environmentId: EnvironmentId.make("source") },
84 records: [image, terminal],
85 })!,
86 html: "",
87};
88​
89const localThread = {
90 version: 1 as const,
91 kind: "thread" as const,
92 contextId: ComposerContextId.make("thread_local-thread"),
93 label: "Local discussion",
94 environmentId: EnvironmentId.make("destination"),
95 threadId: ThreadId.make("local-thread"),
96 title: "Local discussion",
97};
98const foreignThread = {
99 ...localThread,
100 contextId: ComposerContextId.make("thread_foreign-thread"),
101 label: "Remote discussion",
102 environmentId: EnvironmentId.make("source"),
103 threadId: ThreadId.make("foreign-thread"),
104 title: "Remote discussion",
105};
106const mixedRecords = [foreignThread, localThread, terminal, image];
107const mixedClipboard = {
108 text: `Compare these findings: ${mixedRecords.map(formatComposerContextReference).join(" ")} before changing anything.`,
109 fragment: encodeComposerContextFragment({
110 version: 1,
111 source: { environmentId: EnvironmentId.make("source") },
112 records: [
113 ...mixedRecords,
114 {
115 ...foreignThread,
116 contextId: ComposerContextId.make("thread_uncopied-thread"),
117 threadId: ThreadId.make("uncopied-thread"),
118 title: "Not in the copied selection",
119 },
120 ],
121 })!,
122 html: "",
123};
124​
125beforeEach(() => {
126 vi.clearAllMocks();
127 mocks.sequence = 0;
128 mocks.local.mockReturnValue(undefined);
129 mocks.execute.mockResolvedValue({ _tag: "Success", value: { relativeUrl: "/assets/source" } });
130 mocks.download.mockResolvedValue({ uri: "file:///download.png", dispose: mocks.dispose });
131 mocks.persist.mockResolvedValue("file:///owned.png");
132 mocks.remove.mockResolvedValue(undefined);
133});
134​
135describe("mobile context clipboard imports", () => {
136 it("copies original bytes and rewrites file bindings using a signal without throwIfAborted", async () => {
137 const signal = { aborted: false } as AbortSignal;
138 const result = await importComposerContextClipboard(clipboard, 0, signal);
139 expect(result?.failures).toEqual([]);
140 expect(result?.attachments[0]).toMatchObject({ fileUri: "file:///owned.png", sizeBytes: 42 });
141 expect(result?.context.records[0]).toMatchObject({
142 contextId: "import-1",
143 attachmentId: result?.attachments[0]?.id,
144 });
145 expect(result?.context.records[1]).toMatchObject({ text: "Build failed" });
146 expect(result?.text).toContain("/image/import-1)");
147 expect(mocks.dispose).toHaveBeenCalledOnce();
148 });
149​
150 it("keeps failed attachment references visibly unavailable without dropping text context", async () => {
151 mocks.download.mockRejectedValue(new Error("source disconnected"));
152 const result = await importComposerContextClipboard(clipboard, 0, new AbortController().signal);
153 expect(result?.attachments).toEqual([]);
154 expect(result?.failures).toEqual(["checkout.png"]);
155 expect(result?.text).toContain("/image/import-1)");
156 expect(result?.context.records).toEqual([{ ...terminal, contextId: "import-2" }]);
157 });
158​
159 it("releases a newly owned file if the destination closes during its copy", async () => {
160 const controller = new AbortController();
161 mocks.persist.mockImplementationOnce(async () => {
162 controller.abort();
163 return "file:///owned.png";
164 });
165 await expect(importComposerContextClipboard(clipboard, 0, controller.signal)).rejects.toThrow(
166 "cancelled",
167 );
168 expect(mocks.remove).toHaveBeenCalledWith("file:///owned.png");
169 expect(mocks.dispose).toHaveBeenCalledOnce();
170 });
171​
172 it("can copy an image before its source upload completes", async () => {
173 mocks.local.mockReturnValue({
174 id: "source-file",
175 type: "image",
176 dataUrl: "data:image/png;base64,YWJj",
177 previewUri: "data:image/png;base64,YWJj",
178 name: "checkout.png",
179 mimeType: "image/png",
180 sizeBytes: 3,
181 });
182 const result = await importComposerContextClipboard(clipboard, 0, new AbortController().signal);
183 expect(result?.attachments[0]).toMatchObject({
184 dataUrl: "data:image/png;base64,YWJj",
185 uploadedAttachmentId: undefined,
186 });
187 expect(mocks.execute).not.toHaveBeenCalled();
188 expect(mocks.download).not.toHaveBeenCalled();
189 });
190​
191 it("pastes local threads, text context and files at the cap after excluding foreign threads", async () => {
192 const result = await importComposerContextClipboard(
193 mixedClipboard,
194 0,
195 new AbortController().signal,
196 COMPOSER_CONTEXT_MAX_RECORDS - 3,
197 EnvironmentId.make("destination"),
198 );
199 expect(result).not.toBeNull();
200 expect(result!.context.records).toEqual([
201 { ...localThread, contextId: expect.any(String) },
202 { ...terminal, contextId: expect.any(String) },
203 { ...image, contextId: expect.any(String), attachmentId: result!.attachments[0]!.id },
204 ]);
205 expect(result!.attachments).toEqual([
206 expect.objectContaining({ name: image.name, fileUri: "file:///owned.png" }),
207 ]);
208 expect(result!.failures).toEqual([]);
209 expect(result!.skippedThreads).toEqual([foreignThread.title]);
210 const references = collectComposerContextReferences(result!.text);
211 expect(references.map((reference) => reference.label)).toEqual(
212 mixedRecords.map((record) => record.label),
213 );
214 expect(result!.context.records.map((record) => record.contextId)).toEqual(
215 references.slice(1).map((reference) => reference.contextId),
216 );
217 expect(
218 references.every(
219 (reference) => !mixedRecords.some((record) => record.contextId === reference.contextId),
220 ),
221 ).toBe(true);
222 expect(
223 result!.context.records.some((record) => record.contextId === references[0]!.contextId),
224 ).toBe(false);
225 expect(result!.text).toMatch(/^Compare these findings: .* before changing anything\.$/);
226​
227 const restoreHistory = createComposerContextHistory();
228 restoreHistory(formatComposerContextReference(foreignThread), {
229 version: 1,
230 records: [foreignThread],
231 });
232 expect(restoreHistory(`${result!.text} Next step`, result!.context)).toEqual(result!.context);
233​
234 mocks.download.mockClear();
235 await expect(
236 importComposerContextClipboard(
237 mixedClipboard,
238 0,
239 new AbortController().signal,
240 COMPOSER_CONTEXT_MAX_RECORDS - 2,
241 EnvironmentId.make("destination"),
242 ),
243 ).rejects.toThrow("Remove some context");
244 expect(mocks.download).not.toHaveBeenCalled();
245 });
246​
247 // regression: #18322 don't send or paste attached threads a machine can't read
248 it("reports foreign threads and failed files together while keeping the rest of a paste", async () => {
249 mocks.download.mockRejectedValueOnce(new Error("source disconnected"));
250 const result = await importComposerContextClipboard(
251 mixedClipboard,
252 0,
253 new AbortController().signal,
254 0,
255 EnvironmentId.make("destination"),
256 );
257 expect(result).not.toBeNull();
258 expect(result!.context.records).toEqual([
259 { ...localThread, contextId: expect.any(String) },
260 { ...terminal, contextId: expect.any(String) },
261 ]);
262 expect(result!.attachments).toEqual([]);
263 expect(result!.failures).toEqual([image.name]);
264 expect(result!.skippedThreads).toEqual([foreignThread.title]);
265 const references = collectComposerContextReferences(result!.text);
266 expect(references.map((reference) => reference.label)).toEqual(
267 mixedRecords.map((record) => record.label),
268 );
269 expect(
270 references
271 .filter(
272 (reference) =>
273 !result!.context.records.some((record) => record.contextId === reference.contextId),
274 )
275 .map((reference) => reference.label),
276 ).toEqual([foreignThread.label, image.label]);
277 expect(result!.text).toMatch(/^Compare these findings: .* before changing anything\.$/);
278 });
279​
280 it("preserves both machines' thread references when pasting without a destination", async () => {
281 const result = await importComposerContextClipboard(
282 mixedClipboard,
283 0,
284 new AbortController().signal,
285 );
286 expect(result).not.toBeNull();
287 expect(result!.context.records).toEqual([
288 { ...foreignThread, contextId: expect.any(String) },
289 { ...localThread, contextId: expect.any(String) },
290 { ...terminal, contextId: expect.any(String) },
291 { ...image, contextId: expect.any(String), attachmentId: result!.attachments[0]!.id },
292 ]);
293 expect(result!.attachments).toHaveLength(1);
294 expect(result!.failures).toEqual([]);
295 expect(
296 collectComposerContextReferences(result!.text).map((reference) => reference.contextId),
297 ).toEqual(result!.context.records.map((record) => record.contextId));
298 });
299});