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

main
tsx 276 lines 9.99 KB
Raw
1 import { threadContextRecord } from "@t3tools/shared/composerContextReferences";
2 import { useEffect } from "react";
3 import {
4 type ComposerContextRecord,
5 ComposerContextId,
6 EnvironmentId,
7 ThreadId,
8 } from "@t3tools/contracts";
9 import { expect, it, vi } from "vite-plus/test";
10
11 import { act, render, stubGlobal } from "../../../test/render";
12 import { DraftId, useComposerDraftStore } from "../../composerDraftStore";
13 import { formatInlineContextReference } from "../../lib/composerContextReferences";
14 import { rememberCopiedComposerAttachments } from "../../lib/copiedComposerAttachments";
15 import { pendingDraftWork } from "./pendingDraftWork";
16 import { useComposerContextImport } from "./useComposerContextImport";
17
18 vi.mock("~/state/use-atom-query-runner", async (importOriginal) => ({
19 ...(await importOriginal<typeof import("~/state/use-atom-query-runner")>()),
20 useAtomQueryRunner: () => async () => ({ _tag: "Success", value: { relativeUrl: "/file" } }),
21 }));
22 vi.mock("../../state/use-atom-command", async (importOriginal) => ({
23 ...(await importOriginal<typeof import("../../state/use-atom-command")>()),
24 useAtomCommand: () => () => {},
25 }));
26 vi.mock("~/state/session", async (importOriginal) => ({
27 ...(await importOriginal<typeof import("~/state/session")>()),
28 readPreparedConnection: () => ({ httpBaseUrl: "http://localhost" }),
29 }));
30
31 type ImportInput = Parameters<typeof useComposerContextImport>[0];
32 type Importer = ReturnType<typeof useComposerContextImport>;
33
34 function Harness({ input, ready }: { input: ImportInput; ready: (value: Importer) => void }) {
35 const importer = useComposerContextImport(input);
36 useEffect(() => ready(importer));
37 return null;
38 }
39
40 function deferred<T>() {
41 let resolve!: (value: T) => void;
42 const promise = new Promise<T>((fulfill) => {
43 resolve = fulfill;
44 });
45 return { promise, resolve };
46 }
47
48 it.each([
49 { kind: "file", edit: "delete" },
50 { kind: "image", edit: "delete" },
51 { kind: "image", edit: "retain" },
52 { kind: "file", edit: "undo" },
53 { kind: "file", edit: "retain" },
54 { kind: "file", edit: "switch" },
55 { kind: "file", edit: "cached" },
56 { kind: "file", edit: "question" },
57 { kind: "image", edit: "question" },
58 { kind: "image", edit: "annotation" },
59 { kind: "image", edit: "delete-annotation" },
60 ] as const)("settles a delayed $kind import after $edit", async ({ kind, edit }) => {
61 const target = DraftId.make(`clipboard-${kind}-${edit}`);
62 const store = useComposerDraftStore.getState();
63 using _draft = { [Symbol.dispose]: () => store.clearComposerContent(target) };
64 const sourceEnvironmentId = EnvironmentId.make("clipboard-source");
65 rememberCopiedComposerAttachments(
66 sourceEnvironmentId,
67 edit === "cached"
68 ? new Map([["source-attachment", new File(["notes"], "notes.txt")]])
69 : new Map(),
70 );
71 using _copy = {
72 [Symbol.dispose]: () => rememberCopiedComposerAttachments(sourceEnvironmentId, new Map()),
73 };
74 const promptRef = { current: "" };
75 const downloaded = deferred<Response>();
76 const requested = deferred<void>();
77 const settled = deferred<void>();
78 const input = {
79 environmentId: EnvironmentId.make("clipboard-target"),
80 linkedEnvironments: new Map(),
81 activeThread: undefined,
82 activeThreadId: null,
83 composerDraftTarget: target,
84 attachmentDraftTarget: target,
85 attachmentTargetKey: target,
86 attachmentTargetKeyRef: { current: target },
87 questionAttachmentTarget: edit === "question" ? target : null,
88 pendingUserInputs: [],
89 composerContextRecords: new Map(),
90 composerImages: [],
91 composerFilesRef: { current: [] },
92 pendingThreadImportsRef: { current: new Map() },
93 promptRef,
94 addComposerFilesToDraft: (files: Parameters<typeof store.addFiles>[1]) =>
95 store.addFiles(target, files, { appendReference: edit !== "question" }),
96 } satisfies ImportInput & { promptRef: { current: string } };
97 let importer!: Importer;
98 await using _screen = await render(
99 <Harness
100 input={input}
101 ready={(value) => {
102 importer = value;
103 }}
104 />,
105 );
106 const end = pendingDraftWork.end.bind(pendingDraftWork);
107 using _settled = vi.spyOn(pendingDraftWork, "end").mockImplementation((key) => {
108 end(key);
109 settled.resolve();
110 });
111 using _fetch = stubGlobal("fetch", () => {
112 requested.resolve();
113 return downloaded.promise;
114 });
115 const contextId = ComposerContextId.make(`${kind}_source`);
116 const attachmentFields = {
117 version: 1 as const,
118 contextId,
119 label: "notes.txt",
120 attachmentId: "source-attachment",
121 name: "notes.txt",
122 mimeType: kind === "file" ? "text/plain" : "image/png",
123 sizeBytes: 5,
124 };
125 const attachment = (
126 kind === "file"
127 ? { ...attachmentFields, kind: "file" as const }
128 : {
129 ...attachmentFields,
130 kind: "image" as const,
131 source: {
132 kind: "snap-shot" as const,
133 appName: "Finder",
134 windowTitle: "Downloads",
135 capturedAt: "2026-01-01T00:00:00.000Z",
136 accessibleText: "Downloads",
137 },
138 }
139 ) satisfies ComposerContextRecord;
140 const annotation = {
141 version: 1,
142 kind: "preview-annotation",
143 contextId: ComposerContextId.make("preview-annotation_source"),
144 label: "Page annotation",
145 annotationId: "source",
146 pageUrl: "http://localhost/page",
147 pageTitle: "Page",
148 comment: "Check this",
149 targetSummary: "Page",
150 styleChanges: [],
151 screenshotContextId: contextId,
152 } satisfies ComposerContextRecord;
153 const annotated = edit === "annotation" || edit === "delete-annotation";
154 let pastedPrompt = "";
155 await act(async () => {
156 const remapped = importer.importContextRecords(
157 annotated ? [attachment, annotation] : [attachment],
158 sourceEnvironmentId,
159 );
160 pastedPrompt = formatInlineContextReference({
161 kind: annotated ? "preview-annotation" : kind,
162 contextId: remapped.get(annotated ? annotation.contextId : contextId)!,
163 label: annotated ? "Page annotation" : "notes.txt",
164 });
165 if (edit === "question") pastedPrompt = "Question answer";
166 promptRef.current = pastedPrompt;
167 store.setPrompt(target, pastedPrompt);
168 if (edit !== "cached") await requested.promise;
169 });
170 if (edit !== "cached") expect(pendingDraftWork.has(target)).toBe(true);
171 await act(() => {
172 if (
173 edit !== "annotation" &&
174 edit !== "retain" &&
175 edit !== "cached" &&
176 edit !== "question" &&
177 edit !== "switch"
178 ) {
179 promptRef.current = "Keep this edit";
180 store.setPrompt(target, promptRef.current);
181 }
182 if (edit === "undo") {
183 promptRef.current = pastedPrompt;
184 store.setPrompt(target, pastedPrompt);
185 }
186 if (edit === "switch") input.attachmentTargetKeyRef.current = DraftId.make("other-draft");
187 });
188 await act(async () => {
189 downloaded.resolve(new Response("notes", { headers: { "Content-Type": attachment.mimeType } }));
190 await settled.promise;
191 });
192 expect(pendingDraftWork.has(target)).toBe(false);
193 const draft = store.getComposerDraft(target)!;
194 expect(draft.prompt).toBe(promptRef.current);
195 const attachments = kind === "file" ? draft.files : draft.images;
196 if (kind === "image" && edit === "retain")
197 expect(draft.images[0]?.source).toEqual(
198 attachment.kind === "image" ? attachment.source : undefined,
199 );
200 expect(attachments.map((file) => file.name)).toEqual(
201 edit === "undo" ||
202 edit === "retain" ||
203 edit === "annotation" ||
204 edit === "cached" ||
205 edit === "question"
206 ? ["notes.txt"]
207 : [],
208 );
209 });
210
211 it.each(["same", "other-environment"] as const)(
212 "preserves thread identity across repeated pastes: %s",
213 async (variant) => {
214 const otherEnvironment = variant === "other-environment";
215 const target = DraftId.make(`thread-collision-${variant}`);
216 const store = useComposerDraftStore.getState();
217 using _draft = { [Symbol.dispose]: () => store.clearComposerContent(target) };
218 const environmentId = EnvironmentId.make("thread-source");
219 const otherEnvironmentId = EnvironmentId.make("other-thread-source");
220 const first = threadContextRecord(
221 { environmentId, threadId: ThreadId.make("same-id") },
222 "First",
223 );
224 const pasted = otherEnvironment
225 ? threadContextRecord(
226 { environmentId: otherEnvironmentId, threadId: first.threadId },
227 "Second",
228 )
229 : first;
230 store.addThreadContexts(target, [first], { appendReference: false });
231 let importer!: Importer;
232 await using _screen = await render(
233 <Harness
234 input={{
235 environmentId,
236 linkedEnvironments: new Map([[otherEnvironmentId, "Other machine"]]),
237 activeThread: undefined,
238 activeThreadId: null,
239 composerDraftTarget: target,
240 attachmentDraftTarget: target,
241 attachmentTargetKey: target,
242 attachmentTargetKeyRef: { current: target },
243 questionAttachmentTarget: null,
244 pendingUserInputs: [],
245 composerContextRecords: new Map([[first.contextId, { kind: "thread", record: first }]]),
246 composerImages: [],
247 composerFilesRef: { current: [] },
248 pendingThreadImportsRef: { current: new Map() },
249 promptRef: { current: "" },
250 addComposerFilesToDraft: () => [],
251 }}
252 ready={(value) => {
253 importer = value;
254 }}
255 />,
256 );
257 let importedId: string | undefined;
258 await act(() => {
259 importedId = importer
260 .importContextRecords([pasted], pasted.environmentId, target)
261 .get(pasted.contextId);
262 });
263 const records = store.getComposerDraft(target)!.threadContexts;
264 expect(records.find((record) => record.contextId === importedId)).toMatchObject({
265 environmentId: pasted.environmentId,
266 threadId: pasted.threadId,
267 });
268 expect(records).toHaveLength(otherEnvironment ? 2 : 1);
269 expect(records[0]).toEqual(first);
270 await act(() => {
271 const repeated = importer.importContextRecords([pasted], pasted.environmentId, target);
272 expect(repeated.get(pasted.contextId)).toBe(importedId);
273 });
274 expect(store.getComposerDraft(target)!.threadContexts).toEqual(records);
275 },
276 );