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: (atom: unknown) =>
33 atom === "environments"
34 ? []
35 : { _tag: "Some", value: { httpBaseUrl: "https://source.example" } },
36 },
37}));
38vi.mock("../state/workspace", () => ({
39 workspaceConnections: { environmentsAtom: "environments" },
40}));
41vi.mock("../state/session", () => ({
42 environmentSession: { preparedConnectionValueAtom: vi.fn() },
43}));
44vi.mock("../state/assets", () => ({ assetEnvironment: { createUrl: (value: unknown) => value } }));
45vi.mock("../state/threads", () => ({
46 environmentThreadShells: { threadShellAtom: (value: unknown) => value },
47}));
48vi.mock("../state/use-composer-drafts", () => ({
49 waitForComposerDraftsLoaded: async () => {},
50 findLocalComposerClipboardAttachment: mocks.local,
51}));
52vi.mock("@t3tools/client-runtime/state/runtime", () => ({
53 executeAtomQuery: mocks.execute,
54 squashAtomCommandFailure: () => new Error("offline"),
55}));
56vi.mock("./attachmentDownload", () => ({ downloadAttachmentForPreview: mocks.download }));
57vi.mock("./localAttachmentPreview", () => ({ loadLocalAttachmentPreview: mocks.preview }));
58vi.mock("./composerImages", () => ({
59 persistComposerAttachmentFile: mocks.persist,
60 removePersistedComposerAttachmentFile: mocks.remove,
61}));
62vi.mock("./uuid", () => ({ uuidv4: () => `import-${++mocks.sequence}` }));
63
64import { importComposerContextClipboard } from "./composerContextClipboard";
65import { createComposerContextHistory } from "./composerContext";
66
67const image = {
68 version: 1 as const,
69 kind: "image" as const,
70 contextId: ComposerContextId.make("image-source"),
71 label: "Checkout",
72 name: "checkout.png",
73 mimeType: "image/png",
74 sizeBytes: 7,
75 attachmentId: "source-file",
76 source: {
77 kind: "snap-shot" as const,
78 capturedAt: "2026-01-01T00:00:00.000Z",
79 appName: "Finder",
80 windowTitle: "Downloads",
81 accessibleText: "Downloads",
82 },
83};
84const terminal = {
85 version: 1 as const,
86 kind: "terminal" as const,
87 contextId: ComposerContextId.make("terminal-source"),
88 label: "Build",
89 terminalId: "main",
90 terminalLabel: "Terminal",
91 lineStart: 1,
92 lineEnd: 1,
93 text: "Build failed",
94};
95const clipboard = {
96 text: " [Build](t3-context://v1/terminal/terminal-source)",
97 fragment: encodeComposerContextFragment({
98 version: 1,
99 source: { environmentId: EnvironmentId.make("source") },
100 records: [image, terminal],
101 })!,
102 html: "",
103};
104
105const localThread = {
106 version: 1 as const,
107 kind: "thread" as const,
108 contextId: ComposerContextId.make("thread_local-thread"),
109 label: "Local discussion",
110 environmentId: EnvironmentId.make("destination"),
111 threadId: ThreadId.make("local-thread"),
112 title: "Local discussion",
113};
114const foreignThread = {
115 ...localThread,
116 contextId: ComposerContextId.make("thread_foreign-thread"),
117 label: "Remote discussion",
118 environmentId: EnvironmentId.make("source"),
119 threadId: ThreadId.make("foreign-thread"),
120 title: "Remote discussion",
121};
122const mixedRecords = [foreignThread, localThread, terminal, image];
123const mixedClipboard = {
124 text: `Compare these findings: ${mixedRecords.map(formatComposerContextReference).join(" ")} before changing anything.`,
125 fragment: encodeComposerContextFragment({
126 version: 1,
127 source: { environmentId: EnvironmentId.make("source") },
128 records: [
129 ...mixedRecords,
130 {
131 ...foreignThread,
132 contextId: ComposerContextId.make("thread_uncopied-thread"),
133 threadId: ThreadId.make("uncopied-thread"),
134 title: "Not in the copied selection",
135 },
136 ],
137 })!,
138 html: "",
139};
140
141beforeEach(() => {
142 vi.clearAllMocks();
143 mocks.sequence = 0;
144 mocks.local.mockReturnValue(undefined);
145 mocks.execute.mockResolvedValue({ _tag: "Success", value: { relativeUrl: "/assets/source" } });
146 mocks.download.mockResolvedValue({ uri: "file:///download.png", dispose: mocks.dispose });
147 mocks.persist.mockResolvedValue("file:///owned.png");
148 mocks.remove.mockResolvedValue(undefined);
149});
150
151describe("mobile context clipboard imports", () => {
152 it("copies original bytes and rewrites file bindings using a signal without throwIfAborted", async () => {
153 const signal = { aborted: false } as AbortSignal;
154 const result = await importComposerContextClipboard(clipboard, 0, signal);
155 expect(result?.failures).toEqual([]);
156 expect(result?.attachments[0]).toMatchObject({
157 fileUri: "file:///owned.png",
158 sizeBytes: 42,
159 source: image.source,
160 });
161 expect(result?.context.records[0]).toMatchObject({
162 contextId: "import-1",
163 attachmentId: result?.attachments[0]?.id,
164 });
165 expect(result?.context.records[1]).toMatchObject({ text: "Build failed" });
166 expect(result?.text).toContain("/image/import-1)");
167 expect(mocks.dispose).toHaveBeenCalledOnce();
168 });
169
170 it("reuses an attachment the destination already sends instead of copying it", async () => {
171 mocks.download.mockRejectedValue(new Error("source disconnected"));
172 const result = await importComposerContextClipboard(
173 clipboard,
174 0,
175 new AbortController().signal,
176 0,
177 EnvironmentId.make("source"),
178 new Map(),
179 new Set([image.attachmentId]),
180 );
181 expect(mocks.download).not.toHaveBeenCalled();
182 expect(result?.failures).toEqual([]);
183 expect(result?.attachments).toEqual([]);
184 expect(result?.context.records[0]).toMatchObject({ attachmentId: image.attachmentId });
185 });
186
187 it("keeps failed attachment references visibly unavailable without dropping text context", async () => {
188 mocks.download.mockRejectedValue(new Error("source disconnected"));
189 const result = await importComposerContextClipboard(clipboard, 0, new AbortController().signal);
190 expect(result?.attachments).toEqual([]);
191 expect(result?.failures).toEqual(["checkout.png"]);
192 expect(result?.text).toContain("/image/import-1)");
193 expect(result?.context.records).toEqual([{ ...terminal, contextId: "import-2" }]);
194 });
195
196 it("releases a newly owned file if the destination closes during its copy", async () => {
197 const controller = new AbortController();
198 mocks.persist.mockImplementationOnce(async () => {
199 controller.abort();
200 return "file:///owned.png";
201 });
202 await expect(importComposerContextClipboard(clipboard, 0, controller.signal)).rejects.toThrow(
203 "cancelled",
204 );
205 expect(mocks.remove).toHaveBeenCalledWith("file:///owned.png");
206 expect(mocks.dispose).toHaveBeenCalledOnce();
207 });
208
209 it("releases its files if cancelled after the last copy finishes", async () => {
210 const controller = new AbortController();
211 mocks.dispose.mockImplementationOnce(() => controller.abort());
212 const imageOnly = {
213 text: "",
214 fragment: encodeComposerContextFragment({
215 version: 1,
216 source: { environmentId: EnvironmentId.make("source") },
217 records: [image],
218 })!,
219 html: "",
220 };
221 await expect(importComposerContextClipboard(imageOnly, 0, controller.signal)).rejects.toThrow(
222 "cancelled",
223 );
224 expect(mocks.remove).toHaveBeenCalledWith("file:///owned.png");
225 });
226
227 it("can copy an image before its source upload completes", async () => {
228 mocks.local.mockReturnValue({
229 id: "source-file",
230 type: "image",
231 dataUrl: "data:image/png;base64,YWJj",
232 previewUri: "data:image/png;base64,YWJj",
233 name: "checkout.png",
234 mimeType: "image/png",
235 sizeBytes: 3,
236 });
237 const result = await importComposerContextClipboard(clipboard, 0, new AbortController().signal);
238 expect(result?.attachments[0]).toMatchObject({
239 dataUrl: "data:image/png;base64,YWJj",
240 uploadedAttachmentId: undefined,
241 });
242 expect(mocks.execute).not.toHaveBeenCalled();
243 expect(mocks.download).not.toHaveBeenCalled();
244 });
245
246 it("pastes local threads, text context and files at the cap after excluding foreign threads", async () => {
247 const result = await importComposerContextClipboard(
248 mixedClipboard,
249 0,
250 new AbortController().signal,
251 COMPOSER_CONTEXT_MAX_RECORDS - 3,
252 EnvironmentId.make("destination"),
253 );
254 expect(result).not.toBeNull();
255 expect(result!.context.records).toEqual([
256 { ...localThread, contextId: expect.any(String) },
257 { ...terminal, contextId: expect.any(String) },
258 { ...image, contextId: expect.any(String), attachmentId: result!.attachments[0]!.id },
259 ]);
260 expect(result!.attachments).toEqual([
261 expect.objectContaining({ name: image.name, fileUri: "file:///owned.png" }),
262 ]);
263 expect(result!.failures).toEqual([]);
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(result!.context.records.map((record) => record.contextId)).toEqual(
270 references.slice(1).map((reference) => reference.contextId),
271 );
272 expect(
273 references.every(
274 (reference) => !mixedRecords.some((record) => record.contextId === reference.contextId),
275 ),
276 ).toBe(true);
277 expect(
278 result!.context.records.some((record) => record.contextId === references[0]!.contextId),
279 ).toBe(false);
280 expect(result!.text).toMatch(/^Compare these findings: .* before changing anything\.$/);
281
282 const restoreHistory = createComposerContextHistory();
283 restoreHistory(formatComposerContextReference(foreignThread), {
284 version: 1,
285 records: [foreignThread],
286 });
287 expect(restoreHistory(`${result!.text} Next step`, result!.context)).toEqual(result!.context);
288
289 mocks.download.mockClear();
290 await expect(
291 importComposerContextClipboard(
292 mixedClipboard,
293 0,
294 new AbortController().signal,
295 COMPOSER_CONTEXT_MAX_RECORDS - 2,
296 EnvironmentId.make("destination"),
297 ),
298 ).rejects.toThrow("Remove some context");
299 expect(mocks.download).not.toHaveBeenCalled();
300 });
301
302 // regression: #18322 don't send or paste attached threads a machine can't read
303 it("reports foreign threads and failed files together while keeping the rest of a paste", async () => {
304 mocks.download.mockRejectedValueOnce(new Error("source disconnected"));
305 const result = await importComposerContextClipboard(
306 mixedClipboard,
307 0,
308 new AbortController().signal,
309 0,
310 EnvironmentId.make("destination"),
311 );
312 expect(result).not.toBeNull();
313 expect(result!.context.records).toEqual([
314 { ...localThread, contextId: expect.any(String) },
315 { ...terminal, contextId: expect.any(String) },
316 ]);
317 expect(result!.attachments).toEqual([]);
318 expect(result!.failures).toEqual([image.name]);
319 expect(result!.skippedThreads).toEqual([foreignThread.title]);
320 const references = collectComposerContextReferences(result!.text);
321 expect(references.map((reference) => reference.label)).toEqual(
322 mixedRecords.map((record) => record.label),
323 );
324 expect(
325 references
326 .filter(
327 (reference) =>
328 !result!.context.records.some((record) => record.contextId === reference.contextId),
329 )
330 .map((reference) => reference.label),
331 ).toEqual([foreignThread.label, image.label]);
332 expect(result!.text).toMatch(/^Compare these findings: .* before changing anything\.$/);
333 });
334
335 it("keeps a thread from a machine the destination links to", async () => {
336 const result = await importComposerContextClipboard(
337 mixedClipboard,
338 0,
339 new AbortController().signal,
340 0,
341 EnvironmentId.make("destination"),
342 new Map([[foreignThread.environmentId, "Source"]]),
343 );
344 expect(result!.skippedThreads).toEqual([]);
345 expect(result!.context.records.filter((record) => record.kind === "thread")).toEqual([
346 { ...foreignThread, contextId: expect.any(String) },
347 { ...localThread, contextId: expect.any(String) },
348 ]);
349 });
350
351 it("preserves both machines' thread references when pasting without a destination", async () => {
352 const result = await importComposerContextClipboard(
353 mixedClipboard,
354 0,
355 new AbortController().signal,
356 );
357 expect(result).not.toBeNull();
358 expect(result!.context.records).toEqual([
359 { ...foreignThread, contextId: expect.any(String) },
360 { ...localThread, contextId: expect.any(String) },
361 { ...terminal, contextId: expect.any(String) },
362 { ...image, contextId: expect.any(String), attachmentId: result!.attachments[0]!.id },
363 ]);
364 expect(result!.attachments).toHaveLength(1);
365 expect(result!.failures).toEqual([]);
366 expect(
367 collectComposerContextReferences(result!.text).map((reference) => reference.contextId),
368 ).toEqual(result!.context.records.map((record) => record.contextId));
369 });
370
371 it("pastes a thread link as a chip only where the destination's agent reads its machine", async () => {
372 const text = [
373 "https://app.t3.codes/threads/destination/local-thread",
374 "<t3-thread://v2/source/foreign-thread>",
375 ].join(" ");
376 const result = await importComposerContextClipboard(
377 { text, fragment: "", html: "" },
378 0,
379 new AbortController().signal,
380 0,
381 EnvironmentId.make("destination"),
382 );
383 const [record] = result!.context.records;
384 expect(record).toMatchObject({
385 kind: "thread",
386 environmentId: "destination",
387 threadId: "local-thread",
388 });
389 expect(result!.text).toBe(
390 `[Thread](t3-context://v1/thread/${record!.contextId}) <t3-thread://v2/source/foreign-thread>`,
391 );
392 expect(
393 await importComposerContextClipboard(
394 { text: "plain text", fragment: "", html: "" },
395 0,
396 new AbortController().signal,
397 ),
398 ).toBeNull();
399 });
400});