Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ChatMarkdown.permissions.browser.test.tsx

271 lines9.2 KB

1import {
2 AuthOrchestrationOperateScope,
3 EnvironmentId,
4 ProjectId,
5 ThreadId,
6 type AuthEnvironmentScope,
7 type EditorId,
8 type ThreadLinkedPullRequest,
9} from "@t3tools/contracts";
10import { AsyncResult } from "effect/reactivity";
11import { expect, it, vi } from "vite-plus/test";
12​
13import { act, render } from "../../test/render";
14import { useRightPanelStore } from "../rightPanelStore";
15​
16const state = vi.hoisted(() => ({
17 allowed: true,
18 listeners: new Set<() => void>(),
19 openEditor: vi.fn(),
20 updateMetadata: vi.fn(),
21 search: vi.fn(),
22 choose: vi.fn(),
23 openFile: vi.fn(),
24 openExternal: vi.fn(),
25 copy: vi.fn(),
26 linkedPullRequest: null as ThreadLinkedPullRequest | null,
27}));
28​
29vi.mock(import("../state/use-atom-query-runner"), async (original) => ({
30 ...(await original()),
31 useAtomQueryRunner: (() => state.search) as never,
32}));
33vi.mock(import("../state/use-atom-command"), async (original) => {
34 const { threadEnvironment } = await import("../state/threads");
35 return {
36 ...(await original()),
37 useAtomCommand: ((command: unknown) =>
38 command === threadEnvironment.updateMetadata
39 ? state.updateMetadata
40 : state.openEditor) as never,
41 };
42});
43vi.mock(import("../state/session"), async (original) => {
44 const { useSyncExternalStore } = await import("react");
45 const readEnvironmentScope = (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
46 id !== null &&
47 (scope !== AuthOrchestrationOperateScope || id !== threadRef.environmentId || state.allowed);
48 return {
49 ...(await original()),
50 readEnvironmentScope,
51 useEnvironmentScope: (id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
52 useSyncExternalStore(
53 (listener) => {
54 state.listeners.add(listener);
55 return () => state.listeners.delete(listener);
56 },
57 () => readEnvironmentScope(id, scope),
58 ),
59 };
60});
61vi.mock(import("../state/server"), async (original) => {
62 const actual = await original();
63 const { Atom } = await import("effect/reactivity");
64 const config = Atom.make(() => serverConfig);
65 return {
66 ...actual,
67 serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => config) as never },
68 environmentServerConfigsAtom: Atom.make(
69 () => new Map([[threadRef.environmentId, serverConfig]]),
70 ) as never,
71 };
72});
73vi.mock(import("../state/entities"), async (original) => ({
74 ...(await original()),
75 readThreadShell: (() => ({ linkedPullRequest: state.linkedPullRequest })) as never,
76 useProjects: (() => [
77 { id: linkedPullRequest.projectId, environmentId: threadRef.environmentId },
78 ]) as never,
79}));
80vi.mock(import("../remoteOpen"), async (original) => ({
81 ...(await original()),
82 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never,
83}));
84vi.mock(import("../hooks/useLocalStorage"), async (original) => ({
85 ...(await original()),
86 useLocalStorage: (() => ["vscode", vi.fn()]) as never,
87 getLocalStorageItem: (() => "vscode") as never,
88}));
89vi.mock(import("../localApi"), async (original) => ({
90 ...(await original()),
91 readLocalApi: () =>
92 ({
93 contextMenu: { show: state.choose },
94 shell: { openExternal: state.openExternal },
95 }) as never,
96}));
97vi.mock(import("@t3tools/client-runtime/change-request-links"), async (original) => ({
98 ...(await original()),
99 resolvePullRequestPreviewTarget: () => null,
100 findProjectForChangeRequest: ((projects: readonly { id: ProjectId }[]) => projects[0]) as never,
101}));
102​
103import ChatMarkdown from "./ChatMarkdown";
104​
105const threadRef = {
106 environmentId: EnvironmentId.make("selected"),
107 threadId: ThreadId.make("thread"),
108};
109const linkedPullRequest: ThreadLinkedPullRequest = {
110 projectId: ProjectId.make("project"),
111 repository: "example/repo",
112 number: 42,
113 url: "https://github.com/example/repo/pull/42",
114};
115const serverConfig = {
116 availableEditors: ["vscode", "file-manager"] as readonly EditorId[],
117 shellRevealInFileManager: true,
118 shellRevealInFileManagerKind: "xdg-open",
119 environment: { platform: { os: "linux" }, capabilities: { threadPullRequestLinking: true } },
120};
121​
122function setup() {
123 using stack = new DisposableStack();
124 state.allowed = true;
125 state.listeners.clear();
126 state.linkedPullRequest = null;
127 state.openEditor.mockReset().mockResolvedValue(AsyncResult.success(undefined));
128 state.updateMetadata.mockReset().mockResolvedValue(AsyncResult.success(undefined));
129 state.search.mockReset().mockResolvedValue(AsyncResult.success({ entries: [] }));
130 state.choose.mockReset().mockResolvedValue(null);
131 state.openFile.mockReset();
132 state.openExternal.mockReset().mockResolvedValue(undefined);
133 state.copy.mockReset().mockResolvedValue(undefined);
134 const { openFile } = useRightPanelStore.getState();
135 useRightPanelStore.setState({ openFile: state.openFile });
136 stack.defer(() => useRightPanelStore.setState({ openFile }));
137 stack.use(vi.spyOn(navigator.clipboard, "writeText").mockImplementation(state.copy));
138 stack.use(
139 vi.spyOn(navigator.clipboard, "write").mockImplementation(async (items) => {
140 const item = items[0]!;
141 await state.copy(await (await item.getType("text/plain")).text());
142 }),
143 );
144 return stack.move();
146​
147async function renderMarkdown(text: string) {
148 const screen = await render(<ChatMarkdown cwd="/work" threadRef={threadRef} text={text} />);
149 const anchor = () => screen.container.querySelector("a")!;
150 return Object.assign(screen, {
151 anchor,
152 openContextMenu: () =>
153 act(async () => {
154 anchor().dispatchEvent(
155 new MouseEvent("contextmenu", {
156 bubbles: true,
157 cancelable: true,
158 clientX: 10,
159 clientY: 10,
160 }),
161 );
162 }),
163 });
165​
166function offeredActions() {
167 return state.choose.mock.lastCall![0].map((item: { id: string }) => item.id);
169​
170async function setAllowed(allowed: boolean) {
171 await act(async () => {
172 state.allowed = allowed;
173 for (const listener of state.listeners) listener();
174 });
176​
177it("removes host actions after revocation while keeping file preview and copying", async () => {
178 using _setup = setup();
179 await using screen = await renderMarkdown("[Readme](docs/readme.md)");
180 await screen.openContextMenu();
181 expect(offeredActions()).toEqual(["open", "reveal", "copy-relative", "copy-full"]);
182 await setAllowed(false);
183 state.choose.mockResolvedValue("copy-full");
184 await screen.openContextMenu();
185 expect(offeredActions()).toEqual(["copy-relative", "copy-full"]);
186 await vi.waitFor(() => expect(state.copy).toHaveBeenCalledWith("/work/docs/readme.md"));
187 await act(async () => screen.anchor().click());
188 expect(state.openFile).toHaveBeenCalledWith(threadRef, "docs/readme.md", undefined);
189 expect(state.openEditor).not.toHaveBeenCalled();
190});
191​
192it("does not launch an editor after revocation during a native context menu", async () => {
193 using _setup = setup();
194 let choose: (action: string) => void = () => {
195 throw new Error("Menu not opened");
196 };
197 state.choose.mockImplementationOnce(
198 () =>
199 new Promise<string>((resolve) => {
200 choose = resolve;
201 }),
202 );
203 await using screen = await renderMarkdown("[Readme](docs/readme.md)");
204 await screen.openContextMenu();
205 expect(offeredActions()).toContain("open");
206 await act(async () => {
207 state.allowed = false;
208 choose("open");
209 });
210 expect(state.openEditor).not.toHaveBeenCalled();
211});
212​
213it("does not reveal a file after revocation during its workspace lookup", async () => {
214 using _setup = setup();
215 let finishLookup: () => void = () => {
216 throw new Error("Lookup not started");
217 };
218 state.search.mockImplementationOnce(
219 () =>
220 new Promise((resolve) => {
221 finishLookup = () => resolve(AsyncResult.success({ entries: [] }));
222 }),
223 );
224 state.choose.mockResolvedValue("reveal");
225 await using screen = await renderMarkdown("[Readme](readme.md)");
226 await screen.openContextMenu();
227 expect(state.search).toHaveBeenCalledOnce();
228 await act(async () => {
229 state.allowed = false;
230 finishLookup();
231 });
232 expect(state.openEditor).not.toHaveBeenCalled();
233});
234​
235it.each(["link-to-thread", "unlink-from-thread"])(
236 "rechecks %s after a native context menu returns",
237 async (action) => {
238 using _setup = setup();
239 state.linkedPullRequest = action === "unlink-from-thread" ? linkedPullRequest : null;
240 let choose: (action: string) => void = () => {
241 throw new Error("Menu not opened");
242 };
243 state.choose.mockImplementationOnce(
244 () =>
245 new Promise<string>((resolve) => {
246 choose = resolve;
247 }),
248 );
249 await using screen = await renderMarkdown(`[Review](${linkedPullRequest.url})`);
250 await screen.openContextMenu();
251 expect(offeredActions()).toContain(action);
252 await act(async () => {
253 state.allowed = false;
254 choose(action);
255 });
256 expect(state.updateMetadata).not.toHaveBeenCalled();
257​
258 await setAllowed(true);
259 state.choose.mockResolvedValue(action);
260 await screen.openContextMenu();
261 await vi.waitFor(() =>
262 expect(state.updateMetadata).toHaveBeenCalledExactlyOnceWith({
263 environmentId: threadRef.environmentId,
264 input: {
265 threadId: threadRef.threadId,
266 linkedPullRequest: action === "link-to-thread" ? linkedPullRequest : null,
267 },
268 }),
269 );
270 },
271);