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

main
tsx 270 lines 9.88 KB
Raw
1 import { act, useEffect, useState } from "react";
2 import { createRoot } from "react-dom/client";
3 import { expect, it, vi } from "vite-plus/test";
4 import {
5 AssetWorkspaceAssetNotFoundError,
6 EnvironmentId,
7 SOURCE_CONTROL_MEDIA_ASSET,
8 ThreadId,
9 } from "@t3tools/contracts";
10
11 const harness = vi.hoisted(() => ({
12 refreshAssetUrl:
13 vi.fn<(environmentId: string, resource: { url: string }) => Promise<string | null>>(),
14 alert: vi.fn(),
15 previews: [] as unknown[],
16 mounts: 0,
17 presentationFinished: false,
18 }));
19
20 vi.mock("../../state/assets", () => ({ refreshAssetUrl: harness.refreshAssetUrl }));
21 vi.mock("../../lib/localAttachmentPreview", () => ({ loadLocalAttachmentPreview: vi.fn() }));
22 vi.mock("../../lib/attachmentDownload", () => ({
23 downloadAndShareAttachment: vi.fn(),
24 nativeViewerErrorMessage: () => "",
25 shareLocalAttachment: vi.fn(),
26 }));
27 vi.mock("../../lib/previewPresentation", () => ({ usePreviewPresentation: () => {} }));
28 vi.mock("./Dialog", () => ({ alert: harness.alert }));
29 vi.mock("./Button", () => ({ Button: () => null }));
30 vi.mock("./SheetHeader", () => ({ SheetHeader: () => null }));
31 vi.mock("./AppText", () => ({ AppText: () => null }));
32 vi.mock("../PdfPreview", () => ({ PdfPreview: () => null }));
33 vi.mock("../MediaPreviewHeader", () => ({ MediaPreviewHeader: () => null }));
34 vi.mock("../../state/mediaActions", () => ({ useMediaActions: () => ({ actions: [] }) }));
35 vi.mock("react-native", () => ({ Modal: () => null, View: () => null }));
36 vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ top: 0 }) }));
37 vi.mock("react-native-image-viewing", () => ({
38 default: function ImageViewing(props: {
39 images: readonly { uri?: string }[];
40 imageIndex: number;
41 }) {
42 useState(() => harness.mounts++);
43 harness.previews.push({
44 kind: "image",
45 images: props.images,
46 selectedIndex: props.imageIndex,
47 });
48 return null;
49 },
50 }));
51
52 import { FilePreviewModal as AndroidFilePreviewModal } from "./FilePreviewModal.android";
53 import type { FilePreviewItem, FilePreviewViewerProps } from "./FilePreviewModal.types";
54 import { FilePreviewSession } from "./FilePreviewSession";
55
56 function Viewer(props: FilePreviewViewerProps) {
57 useState(() => harness.mounts++);
58 harness.previews.push(props.source);
59 const { onPresent } = props;
60 // Stands in for the native presentation starting.
61 useEffect(() => onPresent?.(() => harness.presentationFinished), [onPresent]);
62 return null;
63 }
64
65 const environmentId = EnvironmentId.make("environment");
66 const image = (url: string): FilePreviewItem => ({
67 kind: "image",
68 environmentId,
69 resource: { _tag: SOURCE_CONTROL_MEDIA_ASSET, cwd: "/repo", url },
70 });
71
72 async function openGallery(
73 selected: FilePreviewItem,
74 gallery: readonly FilePreviewItem[],
75 progressiveGallery: boolean,
76 ) {
77 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
78 harness.previews.length = 0;
79 harness.mounts = 0;
80 harness.alert.mockClear();
81 const root = createRoot(document.createElement("div"));
82 const onRequestClose = vi.fn();
83 const source = { ...selected, gallery };
84 await act(async () =>
85 root.render(
86 progressiveGallery ? (
87 <FilePreviewSession
88 source={source}
89 onRequestClose={onRequestClose}
90 progressiveGallery
91 Viewer={Viewer}
92 />
93 ) : (
94 <AndroidFilePreviewModal source={source} onRequestClose={onRequestClose} />
95 ),
96 ),
97 );
98 return { onRequestClose, [Symbol.asyncDispose]: () => act(async () => root.unmount()) };
99 }
100
101 it.each([true, false])(
102 "keeps the gallery stable while a sibling is still resolving (progressive: %s)",
103 async (progressiveGallery) => {
104 const slow = Promise.withResolvers<string>();
105 harness.refreshAssetUrl.mockImplementation(async (_environmentId, resource) =>
106 resource.url.endsWith("slow.png") ? slow.promise : "https://signed.test/a.png",
107 );
108 const selected = image("https://github.com/a.png");
109 await using _preview = await openGallery(
110 selected,
111 [image("https://github.com/slow.png"), selected],
112 progressiveGallery,
113 );
114
115 if (progressiveGallery) {
116 expect(harness.previews.at(-1)).toMatchObject({
117 kind: "image",
118 selectedIndex: 1,
119 images: [
120 expect.not.objectContaining({ uri: expect.anything() }),
121 { uri: "https://signed.test/a.png" },
122 ],
123 });
124 } else {
125 expect(harness.previews).toEqual([]);
126 }
127 await act(async () => slow.resolve("https://signed.test/slow.png"));
128 expect(harness.previews.at(-1)).toMatchObject({
129 selectedIndex: 1,
130 images: [{ uri: "https://signed.test/slow.png" }, { uri: "https://signed.test/a.png" }],
131 });
132 expect(harness.mounts).toBe(1);
133 },
134 );
135
136 it.each([
137 // The progressive viewer already gave the missing image a page; a viewer that waits opens without it.
138 [
139 true,
140 1,
141 [{ failed: true }, { uri: "https://signed.test/a.png" }, { uri: "https://signed.test/c.png" }],
142 ],
143 [false, 0, [{ uri: "https://signed.test/a.png" }, { uri: "https://signed.test/c.png" }]],
144 ])(
145 "opens the gallery when a sibling cannot be resolved (progressive: %s)",
146 async (progressiveGallery, selectedIndex, images) => {
147 harness.refreshAssetUrl.mockImplementation(async (_environmentId, resource) => {
148 if (resource.url.endsWith("missing.png")) throw new Error("not found");
149 return `https://signed.test/${resource.url.split("/").pop()}`;
150 });
151 const selected = image("https://github.com/a.png");
152 await using preview = await openGallery(
153 selected,
154 [image("https://github.com/missing.png"), selected, image("https://github.com/c.png")],
155 progressiveGallery,
156 );
157
158 expect(preview.onRequestClose).not.toHaveBeenCalled();
159 expect(harness.alert).not.toHaveBeenCalled();
160 expect(harness.previews.at(-1)).toEqual({
161 kind: "image",
162 selectedIndex,
163 images: images.map((page) => expect.objectContaining(page)),
164 });
165 },
166 );
167
168 it("closes the preview when the selected image cannot be resolved", async () => {
169 harness.refreshAssetUrl.mockImplementation(async (_environmentId, resource) => {
170 if (resource.url.endsWith("missing.png")) throw new Error("not found");
171 return `https://signed.test/${resource.url.split("/").pop()}`;
172 });
173 const selected = image("https://github.com/missing.png");
174 await using preview = await openGallery(
175 selected,
176 [image("https://github.com/a.png"), selected],
177 true,
178 );
179
180 expect(preview.onRequestClose).toHaveBeenCalledOnce();
181 expect(harness.alert).toHaveBeenCalledOnce();
182 });
183
184 it("names the checked path when the server cannot find the file", async () => {
185 const resource = {
186 _tag: "media-file" as const,
187 threadId: ThreadId.make("thread"),
188 path: "v2/extended/duo-color-3-extended-FINAL.png",
189 };
190 const checkedPath = "/repo/v2/extended/duo-color-3-extended-FINAL.png";
191 harness.refreshAssetUrl.mockRejectedValue(
192 new AssetWorkspaceAssetNotFoundError({ resource, checkedPath }),
193 );
194 const selected: FilePreviewItem = { kind: "image", environmentId, resource };
195 await using preview = await openGallery(selected, [selected], false);
196
197 expect(preview.onRequestClose).toHaveBeenCalledOnce();
198 expect(harness.alert).toHaveBeenCalledWith(
199 "Could not open preview",
200 expect.stringContaining(checkedPath),
201 );
202 expect(harness.alert.mock.calls[0]?.[1]).not.toMatch(/reconnect/i);
203 });
204
205 it.each([
206 // Handed to native but not yet started there, or still on screen.
207 ["image", false, 1],
208 ["image", true, 2],
209 // A PDF is still resolving here, so its viewer never presented and a re-render must not restart it.
210 ["pdf", true, 1],
211 ] as const)(
212 "a re-tap of the open %s restarts the preview only once its native viewer closed (closed: %s)",
213 async (kind, finished, starts) => {
214 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
215 harness.presentationFinished = finished;
216 harness.mounts = 0;
217 harness.refreshAssetUrl.mockReset();
218 if (kind === "image") harness.refreshAssetUrl.mockResolvedValue("https://signed.test/a.png");
219 else harness.refreshAssetUrl.mockReturnValue(new Promise(() => {}));
220 const selected: FilePreviewItem = { ...image("https://github.com/a.png"), kind };
221 const root = createRoot(document.createElement("div"));
222 await using _root = { [Symbol.asyncDispose]: () => act(async () => root.unmount()) };
223 const render = () =>
224 act(async () =>
225 root.render(
226 <FilePreviewSession
227 source={{ ...selected, gallery: [selected] }}
228 onRequestClose={() => {}}
229 progressiveGallery
230 Viewer={Viewer}
231 />,
232 ),
233 );
234 await render();
235 await render();
236 expect(harness.refreshAssetUrl).toHaveBeenCalledTimes(starts);
237 },
238 );
239
240 it("does not carry a presented viewer over to a different item that is still resolving", async () => {
241 (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
242 harness.presentationFinished = true;
243 harness.refreshAssetUrl.mockReset();
244 harness.refreshAssetUrl.mockImplementation((_environmentId, resource) =>
245 resource.url.endsWith("a.png")
246 ? Promise.resolve("https://signed.test/a.png")
247 : new Promise(() => {}),
248 );
249 const shown = image("https://github.com/a.png");
250 const resolving: FilePreviewItem = { ...image("https://github.com/b.pdf"), kind: "pdf" };
251 const root = createRoot(document.createElement("div"));
252 await using _root = { [Symbol.asyncDispose]: () => act(async () => root.unmount()) };
253 const render = (item: FilePreviewItem) =>
254 act(async () =>
255 root.render(
256 <FilePreviewSession
257 source={{ ...item, gallery: [item] }}
258 onRequestClose={() => {}}
259 progressiveGallery
260 Viewer={Viewer}
261 />,
262 ),
263 );
264 await render(shown);
265 await render(resolving);
266 await render(resolving);
267 expect(
268 harness.refreshAssetUrl.mock.calls.filter(([, r]) => r.url.endsWith("b.pdf")),
269 ).toHaveLength(1);
270 });