The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | AuthFilesystemReadScope, |
| 3 | EnvironmentId, |
| 4 | ThreadId, |
| 5 | type AuthSessionState, |
| 6 | } from "@t3tools/contracts"; |
| 7 | import { AsyncResult } from "effect/reactivity"; |
| 8 | import { createElement, isValidElement, type ReactNode } from "react"; |
| 9 | import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test"; |
| 10 | |
| 11 | function 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 | |
| 19 | const 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 | copyText: vi.fn(), |
| 28 | menuFinished: null as (() => void) | null, |
| 29 | })); |
| 30 | |
| 31 | vi.mock("react", async (importOriginal) => ({ |
| 32 | ...(await importOriginal<typeof import("react")>()), |
| 33 | useCallback: <A,>(callback: A) => callback, |
| 34 | useRef: <A,>(current: A) => ({ current }), |
| 35 | useState: <A,>(initial: A) => [initial, () => {}], |
| 36 | })); |
| 37 | vi.mock("../../hooks/useCopyToClipboard", () => ({ writeTextToClipboard: state.copyText })); |
| 38 | vi.mock("../../localApi", () => ({ |
| 39 | readLocalApi: () => ({ contextMenu: { show: state.showMenu } }), |
| 40 | })); |
| 41 | vi.mock("../../state/assets", () => ({ assetEnvironment: { createUrl: {} } })); |
| 42 | vi.mock("../../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => state.mint })); |
| 43 | vi.mock("../../state/session", () => ({ |
| 44 | environmentSession: { sessionStateAtom: (environmentId: string) => environmentId }, |
| 45 | readPreparedConnection: () => ({ httpBaseUrl: "https://host.test" }), |
| 46 | })); |
| 47 | vi.mock("../../state/query", () => ({ |
| 48 | useEnvironmentQuery: (environmentId: string) => ({ |
| 49 | data: state.sessions.get(environmentId) ?? null, |
| 50 | error: null, |
| 51 | }), |
| 52 | })); |
| 53 | vi.mock("../../rpc/atomRegistry", () => ({ |
| 54 | appAtomRegistry: { |
| 55 | get: (environmentId: string) => { |
| 56 | const session = state.sessions.get(environmentId); |
| 57 | return session === undefined ? AsyncResult.initial() : AsyncResult.success(session); |
| 58 | }, |
| 59 | }, |
| 60 | })); |
| 61 | vi.mock("./mediaContent", () => ({ downloadMedia: state.download, readMediaPng: state.png })); |
| 62 | vi.mock("../ui/tooltip", () => ({ |
| 63 | Tooltip: "Tooltip", |
| 64 | TooltipTrigger: "TooltipTrigger", |
| 65 | TooltipPopup: "TooltipPopup", |
| 66 | })); |
| 67 | vi.mock("../ui/toast", () => ({ |
| 68 | stackedThreadToast: <A,>(toast: A) => toast, |
| 69 | toastManager: { |
| 70 | add: (toast: { type: string }) => { |
| 71 | if (toast.type !== "loading") state.menuFinished?.(); |
| 72 | return "toast"; |
| 73 | }, |
| 74 | update: () => state.menuFinished?.(), |
| 75 | }, |
| 76 | })); |
| 77 | |
| 78 | import { MediaActions, useMediaActions, type MediaActionSource } from "./MediaActions"; |
| 79 | |
| 80 | const environmentId = EnvironmentId.make("media-environment"); |
| 81 | const threadId = ThreadId.make("media-thread"); |
| 82 | const granted: Pick<AuthSessionState, "authenticated" | "scopes"> = { |
| 83 | authenticated: true, |
| 84 | scopes: [AuthFilesystemReadScope], |
| 85 | }; |
| 86 | const denied: Pick<AuthSessionState, "authenticated" | "scopes"> = { |
| 87 | authenticated: true, |
| 88 | scopes: [], |
| 89 | }; |
| 90 | |
| 91 | function 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 | |
| 102 | function 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 | |
| 121 | beforeEach(() => { |
| 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.copyText.mockReset().mockResolvedValue(true); |
| 132 | state.menuFinished = null; |
| 133 | class TestClipboardItem { |
| 134 | constructor(readonly items: Record<string, Promise<Blob>>) {} |
| 135 | } |
| 136 | state.clipboard.mockReset().mockImplementation(async (items: TestClipboardItem[]) => { |
| 137 | await Promise.all(items.flatMap((item) => Object.values(item.items))); |
| 138 | }); |
| 139 | vi.stubGlobal("ClipboardItem", TestClipboardItem); |
| 140 | vi.stubGlobal("navigator", { clipboard: { write: state.clipboard } }); |
| 141 | }); |
| 142 | |
| 143 | afterEach(() => vi.unstubAllGlobals()); |
| 144 | |
| 145 | it.each(["workspace-file", "media-file"] as const)( |
| 146 | "disables denied %s byte actions and prevents imperative requests", |
| 147 | async (_tag) => { |
| 148 | const source = hostSource(_tag); |
| 149 | openMenu(source); |
| 150 | expect(state.showMenu).toHaveBeenCalledWith( |
| 151 | expect.arrayContaining([ |
| 152 | expect.objectContaining({ id: "save", disabled: true }), |
| 153 | expect.objectContaining({ id: "copy-image", disabled: true }), |
| 154 | expect.objectContaining({ id: "open-file", disabled: true }), |
| 155 | ]), |
| 156 | { x: 1, y: 1 }, |
| 157 | ); |
| 158 | await expect(useMediaActions(source).save()).rejects.toThrow("cannot read host files"); |
| 159 | await expect(useMediaActions(source).copyImage()).rejects.toThrow("cannot read host files"); |
| 160 | expect(state.mint).not.toHaveBeenCalled(); |
| 161 | expect(state.download).not.toHaveBeenCalled(); |
| 162 | expect(state.clipboard).not.toHaveBeenCalled(); |
| 163 | }, |
| 164 | ); |
| 165 | |
| 166 | it.each(["save", "copy-image", "open-file"])( |
| 167 | "rechecks access when %s is selected from an already open native menu", |
| 168 | async (action) => { |
| 169 | state.sessions.set(environmentId, granted); |
| 170 | const choice = deferred<string>(); |
| 171 | const completed = deferred<void>(); |
| 172 | state.showMenu.mockReturnValue(choice.promise); |
| 173 | state.menuFinished = () => completed.resolve(); |
| 174 | state.openFile.mockImplementation(() => completed.resolve()); |
| 175 | openMenu(hostSource()); |
| 176 | |
| 177 | state.sessions.set(environmentId, denied); |
| 178 | choice.resolve(action); |
| 179 | await completed.promise; |
| 180 | |
| 181 | expect(state.mint).not.toHaveBeenCalled(); |
| 182 | expect(state.download).not.toHaveBeenCalled(); |
| 183 | expect(state.clipboard).not.toHaveBeenCalled(); |
| 184 | expect(state.openFile).not.toHaveBeenCalled(); |
| 185 | }, |
| 186 | ); |