Open History to see the last commit
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: " [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("releases its files if cancelled after the last copy finishes", async () => {
173 const controller = new AbortController();
174 mocks.dispose.mockImplementationOnce(() => controller.abort());
175 const imageOnly = {
176 text: "",
177 fragment: encodeComposerContextFragment({
178 version: 1,
179 source: { environmentId: EnvironmentId.make("source") },
180 records: [image],
181 })!,
182 html: "",
183 };
184 await expect(importComposerContextClipboard(imageOnly, 0, controller.signal)).rejects.toThrow(
185 "cancelled",
186 );
187 expect(mocks.remove).toHaveBeenCalledWith("file:///owned.png");
188 });
189
190 it("can copy an image before its source upload completes", async () => {
191 mocks.local.mockReturnValue({
192 id: "source-file",
193 type: "image",
194 dataUrl: "data:image/png;base64,YWJj",
195 previewUri: "data:image/png;base64,YWJj",
196 name: "checkout.png",
197 mimeType: "image/png",
198 sizeBytes: 3,
199 });
200 const result = await importComposerContextClipboard(clipboard, 0, new AbortController().signal);
201 expect(result?.attachments[0]).toMatchObject({
202 dataUrl: "data:image/png;base64,YWJj",
203 uploadedAttachmentId: undefined,
204 });
205 expect(mocks.execute).not.toHaveBeenCalled();
206 expect(mocks.download).not.toHaveBeenCalled();
207 });
208
209 it("pastes local threads, text context and files at the cap after excluding foreign threads", async () => {
210 const result = await importComposerContextClipboard(
211 mixedClipboard,
212 0,
213 new AbortController().signal,
214 COMPOSER_CONTEXT_MAX_RECORDS - 3,
215 EnvironmentId.make("destination"),
216 );
217 expect(result).not.toBeNull();
218 expect(result!.context.records).toEqual([
219 { ...localThread, contextId: expect.any(String) },
220 { ...terminal, contextId: expect.any(String) },
221 { ...image, contextId: expect.any(String), attachmentId: result!.attachments[0]!.id },
222 ]);
223 expect(result!.attachments).toEqual([
224 expect.objectContaining({ name: image.name, fileUri: "file:///owned.png" }),
225 ]);
226 expect(result!.failures).toEqual([]);
227 expect(result!.skippedThreads).toEqual([foreignThread.title]);
228 const references = collectComposerContextReferences(result!.text);
229 expect(references.map((reference) => reference.label)).toEqual(
230 mixedRecords.map((record) => record.label),
231 );
232 expect(result!.context.records.map((record) => record.contextId)).toEqual(
233 references.slice(1).map((reference) => reference.contextId),
234 );
235 expect(
236 references.every(
237 (reference) => !mixedRecords.some((record) => record.contextId === reference.contextId),
238 ),
239 ).toBe(true);
240 expect(
241 result!.context.records.some((record) => record.contextId === references[0]!.contextId),
242 ).toBe(false);
243 expect(result!.text).toMatch(/^Compare these findings: .* before changing anything\.$/);
244
245 const restoreHistory = createComposerContextHistory();
246 restoreHistory(formatComposerContextReference(foreignThread), {
247 version: 1,
248 records: [foreignThread],
249 });
250 expect(restoreHistory(`${result!.text} Next step`, result!.context)).toEqual(result!.context);
251
252 mocks.download.mockClear();
253 await expect(
254 importComposerContextClipboard(
255 mixedClipboard,
256 0,
257 new AbortController().signal,
258 COMPOSER_CONTEXT_MAX_RECORDS - 2,
259 EnvironmentId.make("destination"),
260 ),
261 ).rejects.toThrow("Remove some context");
262 expect(mocks.download).not.toHaveBeenCalled();
263 });
264
265 // regression: #18322 don't send or paste attached threads a machine can't read
266 it("reports foreign threads and failed files together while keeping the rest of a paste", async () => {
267 mocks.download.mockRejectedValueOnce(new Error("source disconnected"));
268 const result = await importComposerContextClipboard(
269 mixedClipboard,
270 0,
271 new AbortController().signal,
272 0,
273 EnvironmentId.make("destination"),
274 );
275 expect(result).not.toBeNull();
276 expect(result!.context.records).toEqual([
277 { ...localThread, contextId: expect.any(String) },
278 { ...terminal, contextId: expect.any(String) },
279 ]);
280 expect(result!.attachments).toEqual([]);
281 expect(result!.failures).toEqual([image.name]);
282 expect(result!.skippedThreads).toEqual([foreignThread.title]);
283 const references = collectComposerContextReferences(result!.text);
284 expect(references.map((reference) => reference.label)).toEqual(
285 mixedRecords.map((record) => record.label),
286 );
287 expect(
288 references
289 .filter(
290 (reference) =>
291 !result!.context.records.some((record) => record.contextId === reference.contextId),
292 )
293 .map((reference) => reference.label),
294 ).toEqual([foreignThread.label, image.label]);
295 expect(result!.text).toMatch(/^Compare these findings: .* before changing anything\.$/);
296 });
297
298 it("preserves both machines' thread references when pasting without a destination", async () => {
299 const result = await importComposerContextClipboard(
300 mixedClipboard,
301 0,
302 new AbortController().signal,
303 );
304 expect(result).not.toBeNull();
305 expect(result!.context.records).toEqual([
306 { ...foreignThread, contextId: expect.any(String) },
307 { ...localThread, contextId: expect.any(String) },
308 { ...terminal, contextId: expect.any(String) },
309 { ...image, contextId: expect.any(String), attachmentId: result!.attachments[0]!.id },
310 ]);
311 expect(result!.attachments).toHaveLength(1);
312 expect(result!.failures).toEqual([]);
313 expect(
314 collectComposerContextReferences(result!.text).map((reference) => reference.contextId),
315 ).toEqual(result!.context.records.map((record) => record.contextId));
316 });
317});