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

main
ts 139 lines 5.27 KB
Raw
1 import {
2 AssetWorkspaceAssetNotFoundError,
3 AuthFilesystemReadScope,
4 EnvironmentAuthorizationError,
5 EnvironmentId,
6 ThreadId,
7 type AuthSessionState,
8 } from "@t3tools/contracts";
9 import * as Cause from "effect/Cause";
10 import { Atom, AsyncResult } from "effect/reactivity";
11 import { beforeEach, expect, it, vi } from "vite-plus/test";
12
13 const state = vi.hoisted(() => ({
14 session: null as Pick<AuthSessionState, "authenticated" | "scopes"> | null,
15 phase: "connected" as "connected" | "offline",
16 assetAtom: {},
17 mint: vi.fn(),
18 assetQuery: vi.fn(),
19 executeQuery: vi.fn(),
20 preparedConnectionAtom: null as unknown,
21 }));
22
23 vi.mock("react", () => ({ useCallback: <A>(callback: A) => callback }));
24 vi.mock("@effect/atom-react", () => ({
25 useAtomMount: () => undefined,
26 useAtomSubscribe: () => undefined,
27 useAtomValue: (atom: unknown) =>
28 atom === state.assetAtom
29 ? AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 })
30 : AsyncResult.initial(false),
31 }));
32 vi.mock("./session", () => ({
33 environmentSession: {
34 sessionStateAtom: () => ({}),
35 preparedConnectionValueAtom: () => state.preparedConnectionAtom,
36 },
37 usePreparedConnection: () => ({ _tag: "Some", value: { httpBaseUrl: "https://host.test" } }),
38 }));
39 vi.mock("./presentation", () => ({
40 useEnvironmentPresentation: () => ({
41 isReady: true,
42 presentation: { connection: { phase: state.phase, error: null } },
43 }),
44 }));
45 vi.mock("./query", () => ({
46 useEnvironmentQuery: () => ({ data: state.session, error: null }),
47 }));
48 vi.mock("./projectClones", () => ({ environmentProjectCloneListAtom: () => null }));
49 vi.mock("../connection/runtime", () => ({ connectionAtomRuntime: {} }));
50 vi.mock("../connection/catalog", () => ({
51 environmentCatalog: { sessionGenerationAtom: () => null },
52 }));
53 vi.mock("@t3tools/client-runtime/state/assets", async (importOriginal) => ({
54 ...(await importOriginal<typeof import("@t3tools/client-runtime/state/assets")>()),
55 createAssetEnvironmentAtoms: () => ({ createUrl: state.assetQuery }),
56 }));
57 vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({
58 ...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()),
59 executeAtomQuery: state.executeQuery,
60 }));
61 vi.mock("./use-atom-query-runner", () => ({ useAtomQueryRunner: () => state.mint }));
62 vi.mock("gt-react-native", async (importOriginal) => {
63 const gt = await importOriginal<typeof import("gt-react-native")>();
64 return { ...gt, useMessages: () => gt.mFallback };
65 });
66
67 import { refreshAssetUrl, useRefreshAssetUrl, useAssetUrlState } from "./assets";
68
69 const environmentId = EnvironmentId.make("asset-environment");
70 const threadId = ThreadId.make("asset-thread");
71 const resource = { _tag: "media-file", threadId, path: "/repo/image.png" } as const;
72
73 beforeEach(() => {
74 state.session = null;
75 state.phase = "connected";
76 state.assetQuery.mockReset().mockReturnValue(state.assetAtom);
77 state.mint
78 .mockReset()
79 .mockResolvedValue(AsyncResult.success({ relativeUrl: "/api/assets/image.png", expiresAt: 1 }));
80 });
81
82 it.each(["workspace-file", "media-file"] as const)(
83 "keeps %s loading until its file grant resolves",
84 (_tag) => {
85 expect(useAssetUrlState(environmentId, { ...resource, _tag })).toEqual({ _tag: "Loading" });
86 expect(state.assetQuery).not.toHaveBeenCalled();
87
88 state.session = { authenticated: true, scopes: [AuthFilesystemReadScope] };
89 expect(useAssetUrlState(environmentId, { ...resource, _tag })).toEqual({
90 _tag: "Success",
91 expiresAt: 1,
92 url: "https://host.test/api/assets/image.png",
93 });
94 },
95 );
96
97 it("hides host assets with a denied grant while preserving attachments", () => {
98 state.session = { authenticated: true, scopes: [] };
99 expect(useAssetUrlState(environmentId, resource)).toEqual({
100 _tag: "Failure",
101 reason: "missing-file-access",
102 });
103 expect(state.assetQuery).not.toHaveBeenCalled();
104 expect(useAssetUrlState(environmentId, { _tag: "attachment", attachmentId: "upload" })).toEqual({
105 _tag: "Success",
106 expiresAt: 1,
107 url: "https://host.test/api/assets/image.png",
108 });
109 });
110
111 it("lets the server authorize an explicit refresh before the client grant loads", async () => {
112 await expect(useRefreshAssetUrl(environmentId, resource)()).resolves.toBe(
113 "https://host.test/api/assets/image.png",
114 );
115 expect(state.mint).toHaveBeenCalledWith({ environmentId, input: { resource } });
116
117 const denied = new EnvironmentAuthorizationError({
118 message: "This connection cannot read host files.",
119 requiredScope: AuthFilesystemReadScope,
120 });
121 state.mint.mockResolvedValue(AsyncResult.failure(Cause.fail(denied)));
122 await expect(useRefreshAssetUrl(environmentId, resource)()).resolves.toBeNull();
123 });
124
125 it("rejects with the server's error and resolves null only without a connection", async () => {
126 const missing = new AssetWorkspaceAssetNotFoundError({
127 resource,
128 checkedPath: "/repo/missing.png",
129 });
130 state.executeQuery.mockResolvedValue(AsyncResult.failure(Cause.fail(missing)));
131 state.preparedConnectionAtom = Atom.make({
132 _tag: "Some",
133 value: { httpBaseUrl: "https://host.test" },
134 });
135 await expect(refreshAssetUrl(environmentId, resource)).rejects.toBe(missing);
136
137 state.preparedConnectionAtom = Atom.make({ _tag: "None" });
138 await expect(refreshAssetUrl(environmentId, resource)).resolves.toBeNull();
139 });