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 { beforeEach, expect, it, vi } from "vite-plus/test";
9
10const state = vi.hoisted(() => ({
11 sessions: new Map<string, Pick<AuthSessionState, "authenticated" | "scopes">>(),
12 refresh: vi.fn(),
13 download: vi.fn(),
14 downloadPreview: vi.fn(),
15 saveImage: vi.fn(),
16 shareLocal: vi.fn(),
17 shareDraft: vi.fn(),
18 navigate: vi.fn(),
19 copy: vi.fn(),
20}));
21
22vi.mock("react", () => ({
23 useEffect: () => {},
24 useRef: <A>(current: A) => ({ current }),
25 useState: <A>(initial: A) => [initial, () => {}],
26}));
27vi.mock("react-native", () => ({ Alert: { alert: vi.fn() } }));
28vi.mock("gt-react-native", async (importOriginal) => {
29 const gt = await importOriginal<typeof import("gt-react-native")>();
30 // The testing entry renders the English source with no provider and no React.
31 const sourceGT = await gt.getGT();
32 return { ...gt, useGT: () => sourceGT, useMessages: () => gt.mFallback };
33});
34vi.mock("@react-navigation/native", () => ({
35 useNavigation: () => ({ navigate: state.navigate }),
36}));
37vi.mock("./markdownLinks", () => ({
38 normalizeNativeMarkdownUrl: (uri: string) => uri,
39}));
40vi.mock("../state/assets", () => ({
41 useRefreshAssetUrl: (environmentId: string, resource: unknown) => () =>
42 state.refresh(environmentId, resource),
43}));
44vi.mock("../state/session", () => ({
45 environmentSession: { sessionStateAtom: (environmentId: string) => environmentId },
46}));
47vi.mock("../state/query", () => ({
48 useEnvironmentQuery: (environmentId: string) => ({
49 data: state.sessions.get(environmentId) ?? null,
50 error: null,
51 }),
52}));
53vi.mock("../state/atom-registry", () => ({
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}));
61vi.mock("./attachmentDownload", () => ({
62 downloadAndShareAttachment: state.download,
63 downloadAttachmentForPreview: state.downloadPreview,
64 shareLocalAttachment: state.shareLocal,
65}));
66vi.mock("./saveImageToLibrary", () => ({
67 canSaveImageToLibrary: (mimeType: string) => mimeType === "image/png",
68 saveImageToLibrary: state.saveImage,
69}));
70vi.mock("expo-haptics", () => ({
71 notificationAsync: async () => {},
72 NotificationFeedbackType: { Success: "success" },
73}));
74vi.mock("./copyTextWithHaptic", () => ({ copyTextWithHaptic: state.copy }));
75vi.mock("./localAttachmentPreview", () => ({
76 loadLocalAttachmentPreview: async () => ({ share: state.shareDraft, dispose: vi.fn() }),
77}));
78
79import { useMediaActions } from "../state/mediaActions";
80import type { MediaActionsSource } from "./mediaActionsSource";
81
82const environmentId = EnvironmentId.make("media-environment");
83const otherEnvironmentId = EnvironmentId.make("other-environment");
84const threadId = ThreadId.make("media-thread");
85const granted: Pick<AuthSessionState, "authenticated" | "scopes"> = {
86 authenticated: true,
87 scopes: [AuthFilesystemReadScope],
88};
89const denied: Pick<AuthSessionState, "authenticated" | "scopes"> = {
90 authenticated: true,
91 scopes: [],
92};
93
94function hostSource(_tag: "workspace-file" | "media-file" = "media-file"): MediaActionsSource {
95 return {
96 environmentId,
97 threadId,
98 resource: { _tag, threadId, path: "/repo/image.png" },
99 reference: { kind: "file", path: "/repo/image.png", relativePath: "image.png" },
100 name: "image.png",
101 mimeType: "image/png",
102 };
103}
104
105beforeEach(() => {
106 state.sessions.clear();
107 state.sessions.set(environmentId, denied);
108 state.refresh.mockReset().mockResolvedValue("https://host.test/image.png");
109 state.download.mockReset().mockResolvedValue(undefined);
110 state.downloadPreview.mockReset();
111 state.saveImage.mockReset().mockResolvedValue(undefined);
112 state.shareLocal.mockReset().mockResolvedValue(undefined);
113 state.shareDraft.mockReset().mockResolvedValue(undefined);
114 state.navigate.mockReset();
115 state.copy.mockReset();
116});
117
118it.each(["workspace-file", "media-file"] as const)(
119 "blocks denied %s sharing and file opening while preserving path copying",
120 async (_tag) => {
121 const media = useMediaActions(hostSource(_tag));
122 await media.share();
123 media.actions.find(({ id }) => id === "open-file")!.run();
124 media.actions.find(({ id }) => id === "copy-full-path")!.run();
125
126 expect(state.refresh).not.toHaveBeenCalled();
127 expect(state.download).not.toHaveBeenCalled();
128 expect(state.navigate).not.toHaveBeenCalled();
129 expect(state.copy).toHaveBeenCalledWith("/repo/image.png");
130 expect(media.actions.find(({ id }) => id === "save")?.disabled).toBe(true);
131 expect(media.actions.find(({ id }) => id === "save-image")?.disabled).toBe(true);
132 expect(media.actions.find(({ id }) => id === "open-file")?.disabled).toBe(true);
133 },
134);
135
136it("rechecks a retained menu action after revocation", async () => {
137 state.sessions.set(environmentId, granted);
138 const media = useMediaActions(hostSource());
139 state.sessions.set(environmentId, denied);
140
141 await media.share();
142 media.actions.find(({ id }) => id === "open-file")!.run();
143
144 expect(state.refresh).not.toHaveBeenCalled();
145 expect(state.navigate).not.toHaveBeenCalled();
146});
147
148it("reenables sharing after gaining access while preserving a retained callback", async () => {
149 const media = useMediaActions(hostSource());
150 state.sessions.set(environmentId, granted);
151
152 await media.share();
153
154 expect(state.download).toHaveBeenCalledOnce();
155 expect(useMediaActions(hostSource()).actions.find(({ id }) => id === "save")?.disabled).toBe(
156 false,
157 );
158});
159
160it.each([false, true])("uses the media environment's grant (allowed: %s)", async (allowed) => {
161 state.sessions.set(environmentId, allowed ? granted : denied);
162 state.sessions.set(otherEnvironmentId, allowed ? denied : granted);
163
164 await useMediaActions(hostSource()).share();
165
166 expect(state.refresh).toHaveBeenCalledTimes(allowed ? 1 : 0);
167 expect(state.download).toHaveBeenCalledTimes(allowed ? 1 : 0);
168});
169
170it("stops before downloading if access is revoked while the URL is refreshed", async () => {
171 state.sessions.set(environmentId, granted);
172 state.refresh.mockImplementation(async () => {
173 state.sessions.set(environmentId, denied);
174 return "https://host.test/image.png";
175 });
176
177 await useMediaActions(hostSource()).share();
178
179 expect(state.refresh).toHaveBeenCalledOnce();
180 expect(state.download).not.toHaveBeenCalled();
181});
182
183it("lets an unresolved grant be authorized by an explicit server request", async () => {
184 state.sessions.delete(environmentId);
185
186 await useMediaActions(hostSource()).share();
187
188 expect(state.refresh).toHaveBeenCalledOnce();
189 expect(state.download).toHaveBeenCalledOnce();
190});
191
192it.each(["https://cdn.test/image.png", "file:///device/image.png"])(
193 "shares direct media without a host grant: %s",
194 async (uri) => {
195 await useMediaActions({ uri, name: "image.png", mimeType: "image/png" }).share();
196
197 expect(state.refresh).not.toHaveBeenCalled();
198 expect(uri.startsWith("file:") ? state.shareLocal : state.download).toHaveBeenCalledOnce();
199 },
200);
201
202it("saves a host image from its downloaded file, then removes the file", async () => {
203 state.sessions.set(environmentId, granted);
204 const disposed = Promise.withResolvers<void>();
205 state.downloadPreview.mockResolvedValue({
206 uri: "file:///cache/image.png",
207 dispose: disposed.resolve,
208 });
209
210 useMediaActions(hostSource())
211 .actions.find(({ id }) => id === "save-image")!
212 .run();
213 await disposed.promise;
214
215 expect(state.downloadPreview).toHaveBeenCalledWith(
216 expect.objectContaining({ url: "https://host.test/image.png" }),
217 );
218 expect(state.saveImage).toHaveBeenCalledWith("file:///cache/image.png", "image/png", "image.png");
219});