Open History to see the last commit
1import {
2 AuthFilesystemReadScope,
3 EnvironmentId,
4 ThreadId,
5 type AuthSessionState,
6} from "@t3tools/contracts";
7import { AsyncResult } from "effect/reactivity";
8import { createElement, isValidElement, type ReactNode } from "react";
9import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
10
11function deferred<T>() {
12 let resolve!: (value: T | PromiseLike<T>) => void;
13 const promise = new Promise<T>((resolvePromise) => {
14 resolve = resolvePromise;
15 });
16 return { promise, resolve };
17}
18
19const state = vi.hoisted(() => ({
20 sessions: new Map<string, Pick<AuthSessionState, "authenticated" | "scopes">>(),
21 mint: vi.fn(),
22 download: vi.fn(),
23 png: vi.fn(),
24 showMenu: vi.fn(),
25 openFile: vi.fn(),
26 clipboard: vi.fn(),
27 menuFinished: null as (() => void) | null,
28}));
29
30vi.mock("react", async (importOriginal) => ({
31 ...(await importOriginal<typeof import("react")>()),
32 useCallback: <A,>(callback: A) => callback,
33 useRef: <A,>(current: A) => ({ current }),
34 useState: <A,>(initial: A) => [initial, () => {}],
35}));
36vi.mock("../../hooks/useCopyToClipboard", () => ({ writeTextToClipboard: vi.fn() }));
37vi.mock("../../localApi", () => ({
38 readLocalApi: () => ({ contextMenu: { show: state.showMenu } }),
39}));
40vi.mock("../../state/assets", () => ({ assetEnvironment: { createUrl: {} } }));
41vi.mock("../../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => state.mint }));
42vi.mock("../../state/session", () => ({
43 environmentSession: { sessionStateAtom: (environmentId: string) => environmentId },
44 readPreparedConnection: () => ({ httpBaseUrl: "https://host.test" }),
45}));
46vi.mock("../../state/query", () => ({
47 useEnvironmentQuery: (environmentId: string) => ({
48 data: state.sessions.get(environmentId) ?? null,
49 error: null,
50 }),
51}));
52vi.mock("../../rpc/atomRegistry", () => ({
53 appAtomRegistry: {
54 get: (environmentId: string) => {
55 const session = state.sessions.get(environmentId);
56 return session === undefined ? AsyncResult.initial() : AsyncResult.success(session);
57 },
58 },
59}));
60vi.mock("./mediaContent", () => ({ downloadMedia: state.download, readMediaPng: state.png }));
61vi.mock("../ui/tooltip", () => ({
62 Tooltip: "Tooltip",
63 TooltipTrigger: "TooltipTrigger",
64 TooltipPopup: "TooltipPopup",
65}));
66vi.mock("../ui/toast", () => ({
67 stackedThreadToast: <A,>(toast: A) => toast,
68 toastManager: {
69 add: (toast: { type: string }) => {
70 if (toast.type !== "loading") state.menuFinished?.();
71 return "toast";
72 },
73 update: () => state.menuFinished?.(),
74 },
75}));
76
77import { MediaActions, useMediaActions, type MediaActionSource } from "./MediaActions";
78
79const environmentId = EnvironmentId.make("media-environment");
80const otherEnvironmentId = EnvironmentId.make("other-environment");
81const threadId = ThreadId.make("media-thread");
82const granted: Pick<AuthSessionState, "authenticated" | "scopes"> = {
83 authenticated: true,
84 scopes: [AuthFilesystemReadScope],
85};
86const denied: Pick<AuthSessionState, "authenticated" | "scopes"> = {
87 authenticated: true,
88 scopes: [],
89};
90
91function hostSource(_tag: "workspace-file" | "media-file" = "media-file"): MediaActionSource {
92 return {
93 kind: "image",
94 name: "image.png",
95 src: null,
96 asset: { environmentId, resource: { _tag, threadId, path: "/repo/image.png" } },
97 reference: { kind: "file", path: "/repo/image.png", relativePath: "image.png" },
98 onOpenFile: state.openFile,
99 };
100}
101
102function openMenu(source: MediaActionSource) {
103 const find = (node: ReactNode): ((event: unknown) => void) | undefined => {
104 if (Array.isArray(node)) return node.map(find).find((handler) => handler !== undefined);
105 if (!isValidElement<{ children?: ReactNode; onContextMenu?: (event: unknown) => void }>(node))
106 return undefined;
107 return node.props.onContextMenu ?? find(node.props.children);
108 };
109 const handler = find(MediaActions({ source, children: createElement("img") }));
110 if (!handler) throw new Error("Media menu handler missing");
111 handler({
112 defaultPrevented: false,
113 preventDefault() {},
114 stopPropagation() {},
115 currentTarget: { getBoundingClientRect: () => ({ left: 0, bottom: 0 }) },
116 clientX: 1,
117 clientY: 1,
118 });
119}
120
121beforeEach(() => {
122 state.sessions.clear();
123 state.sessions.set(environmentId, denied);
124 state.mint
125 .mockReset()
126 .mockResolvedValue(AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 }));
127 state.download.mockReset().mockResolvedValue(undefined);
128 state.png.mockReset().mockResolvedValue(new Blob(["png"], { type: "image/png" }));
129 state.showMenu.mockReset().mockResolvedValue(null);
130 state.openFile.mockReset();
131 state.menuFinished = null;
132 class TestClipboardItem {
133 constructor(readonly items: Record<string, Promise<Blob>>) {}
134 }
135 state.clipboard.mockReset().mockImplementation(async (items: TestClipboardItem[]) => {
136 await Promise.all(items.flatMap((item) => Object.values(item.items)));
137 });
138 vi.stubGlobal("ClipboardItem", TestClipboardItem);
139 vi.stubGlobal("navigator", { clipboard: { write: state.clipboard } });
140});
141
142afterEach(() => vi.unstubAllGlobals());
143
144it.each(["workspace-file", "media-file"] as const)(
145 "waits for the %s grant before enabling host menu actions",
146 (_tag) => {
147 for (const [session, disabled] of [
148 [null, true],
149 [granted, false],
150 [denied, true],
151 ] as const) {
152 if (session === null) state.sessions.delete(environmentId);
153 else state.sessions.set(environmentId, session);
154 openMenu(hostSource(_tag));
155
156 const items = state.showMenu.mock.lastCall![0];
157 expect(items).toEqual(
158 expect.arrayContaining([
159 expect.objectContaining({ id: "save", disabled }),
160 expect.objectContaining({ id: "copy-image", disabled }),
161 expect.objectContaining({ id: "open-file", disabled }),
162 ]),
163 );
164 expect(items).toContainEqual({ id: "copy-full-path", label: "Copy full path" });
165 }
166 expect(state.mint).not.toHaveBeenCalled();
167 expect(state.download).not.toHaveBeenCalled();
168 },
169);
170
171it("keeps nonhost menu actions available with pending or denied host grants", () => {
172 const sources: MediaActionSource[] = [
173 { kind: "image", name: "image.png", src: "https://cdn.test/image.png" },
174 { kind: "image", name: "image.png", src: "blob:local-image" },
175 {
176 kind: "image",
177 name: "image.png",
178 src: null,
179 asset: { environmentId, resource: { _tag: "attachment", attachmentId: "upload" } },
180 },
181 ];
182 for (const session of [null, denied]) {
183 if (session === null) state.sessions.delete(environmentId);
184 else state.sessions.set(environmentId, session);
185 for (const source of sources) {
186 openMenu(source);
187 expect(state.showMenu.mock.lastCall![0]).toEqual(
188 expect.arrayContaining([
189 expect.objectContaining({ id: "save", disabled: false }),
190 expect.objectContaining({ id: "copy-image", disabled: false }),
191 ]),
192 );
193 }
194 }
195});
196
197it.each(["workspace-file", "media-file"] as const)(
198 "disables denied %s byte actions and prevents imperative requests",
199 async (_tag) => {
200 const source = hostSource(_tag);
201 openMenu(source);
202 expect(state.showMenu).toHaveBeenCalledWith(
203 expect.arrayContaining([
204 expect.objectContaining({ id: "save", disabled: true }),
205 expect.objectContaining({ id: "copy-image", disabled: true }),
206 expect.objectContaining({ id: "open-file", disabled: true }),
207 ]),
208 { x: 1, y: 1 },
209 );
210 await expect(useMediaActions(source).save()).rejects.toThrow("cannot read host files");
211 await expect(useMediaActions(source).copyImage()).rejects.toThrow("cannot read host files");
212 expect(state.mint).not.toHaveBeenCalled();
213 expect(state.download).not.toHaveBeenCalled();
214 expect(state.clipboard).not.toHaveBeenCalled();
215 },
216);
217
218it.each(["save", "copy-image", "open-file"])(
219 "rechecks access when %s is selected from an already open native menu",
220 async (action) => {
221 state.sessions.set(environmentId, granted);
222 const choice = deferred<string>();
223 const completed = deferred<void>();
224 state.showMenu.mockReturnValue(choice.promise);
225 state.menuFinished = () => completed.resolve();
226 state.openFile.mockImplementation(() => completed.resolve());
227 openMenu(hostSource());
228
229 state.sessions.set(environmentId, denied);
230 choice.resolve(action);
231 await completed.promise;
232
233 expect(state.mint).not.toHaveBeenCalled();
234 expect(state.download).not.toHaveBeenCalled();
235 expect(state.clipboard).not.toHaveBeenCalled();
236 expect(state.openFile).not.toHaveBeenCalled();
237 },
238);
239
240it("reenables the menu and a retained action when file access is gained", async () => {
241 const actions = useMediaActions(hostSource());
242 state.sessions.set(environmentId, granted);
243 openMenu(hostSource());
244
245 await actions.save();
246
247 expect(state.download).toHaveBeenCalledOnce();
248 expect(state.showMenu).toHaveBeenCalledWith(
249 expect.arrayContaining([expect.objectContaining({ id: "save", disabled: false })]),
250 expect.anything(),
251 );
252});
253
254it.each([false, true])("uses the media environment's grant (allowed: %s)", async (allowed) => {
255 state.sessions.set(environmentId, allowed ? granted : denied);
256 state.sessions.set(otherEnvironmentId, allowed ? denied : granted);
257
258 await useMediaActions(hostSource())
259 .save()
260 .catch(() => {});
261
262 expect(state.mint).toHaveBeenCalledTimes(allowed ? 1 : 0);
263 expect(state.download).toHaveBeenCalledTimes(allowed ? 1 : 0);
264});
265
266it("stops before downloading if access is revoked while minting the URL", async () => {
267 state.sessions.set(environmentId, granted);
268 state.mint.mockImplementation(async () => {
269 state.sessions.set(environmentId, denied);
270 return AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 });
271 });
272
273 await expect(useMediaActions(hostSource()).save()).rejects.toThrow("cannot read host files");
274
275 expect(state.download).not.toHaveBeenCalled();
276});
277
278it("lets the server authorize an explicit action before the grant resolves", async () => {
279 state.sessions.delete(environmentId);
280
281 await useMediaActions(hostSource()).save();
282
283 expect(state.mint).toHaveBeenCalledOnce();
284 expect(state.download).toHaveBeenCalledOnce();
285});
286
287it("saves uploaded attachments without filesystem access", async () => {
288 await useMediaActions({
289 kind: "image",
290 name: "image.png",
291 src: null,
292 asset: { environmentId, resource: { _tag: "attachment", attachmentId: "upload" } },
293 }).save();
294
295 expect(state.mint).toHaveBeenCalledOnce();
296 expect(state.download).toHaveBeenCalledOnce();
297});
298
299it.each(["https://cdn.test/image.png", "blob:local-image"])(
300 "saves direct media without a host grant: %s",
301 async (src) => {
302 await useMediaActions({ kind: "image", name: "image.png", src }).save();
303
304 expect(state.mint).not.toHaveBeenCalled();
305 expect(state.download).toHaveBeenCalledWith(src, "image.png");
306 },
307);