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

useThreadActions.permissions.test.ts

369 lines13.6 KB

1import {
2 AuthOrchestrationOperateScope,
3 AuthSourceControlWriteScope,
4 EnvironmentId,
5 ProjectId,
6 ThreadId,
7 type ScopedThreadRef,
8} from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import { AsyncResult } from "effect/reactivity";
11import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
12​
13import { scopedThreadKey } from "@t3tools/client-runtime/environment";
14import { useDiffPanelStore } from "../diffPanelStore";
15import { browserMiniPlayerSource, usePreviewMiniPlayerStore } from "../previewMiniPlayerStore";
16import { useRightPanelStore } from "../rightPanelStore";
17​
18function deferred<T>() {
19 let resolve!: (value: T) => void;
20 const promise = new Promise<T>((complete) => {
21 resolve = complete;
22 });
23 return { promise, resolve };
25​
26const state = vi.hoisted(() => ({
27 scopes: new Map<string, Set<string>>(),
28 threads: [] as {
29 environmentId: EnvironmentId;
30 id: ThreadId;
31 projectId: ProjectId;
32 title: string;
33 worktreePath: string | null;
34 session: { status: "ready" | "stopped" } | null;
35 latestTurn: null;
36 }[],
37 requests: [] as { action: string; environmentId: string; input: { threadId?: string } }[],
38 localEffects: [] as string[],
39 confirm: vi.fn<(message: string) => Promise<boolean>>(),
40 toasts: [] as string[],
41 afterRequest: undefined as ((action: string) => void) | undefined,
42 sessionLookupFails: false,
43}));
44​
45vi.mock("react", () => ({
46 useCallback: (callback: unknown) => callback,
47 useMemo: (factory: () => unknown) => factory(),
48 useRef: (current: unknown) => ({ current }),
49}));
50vi.mock("@tanstack/react-router", () => ({
51 useRouter: () => ({ state: { location: { href: "/" }, matches: [] }, navigate: async () => {} }),
52}));
53vi.mock("../state/session", () => ({
54 environmentSession: { sessionStateAtom: "session" },
55 readEnvironmentScope: (environmentId: string, scope: string) =>
56 state.scopes.get(environmentId)?.has(scope) === true,
57}));
58vi.mock("../state/use-atom-command", () => ({
59 useAtomCommand:
60 (action: string) =>
61 async (request: { environmentId: string; input: { threadId?: string } }) => {
62 state.requests.push({ action, ...request });
63 const scope =
64 action === "removeWorktree" ? AuthSourceControlWriteScope : AuthOrchestrationOperateScope;
65 if (!state.scopes.get(request.environmentId)?.has(scope)) {
66 return AsyncResult.failure(Cause.fail(new Error("Server denied the request")));
67 }
68 state.afterRequest?.(action);
69 return AsyncResult.success(undefined);
70 },
71}));
72vi.mock("../state/use-atom-query-runner", () => ({
73 useAtomQueryRunner: () => async (environmentId: string) =>
74 state.sessionLookupFails
75 ? AsyncResult.failure(Cause.fail(new Error("Session lookup failed")))
76 : AsyncResult.success({
77 authenticated: true,
78 scopes: [...(state.scopes.get(environmentId) ?? [])],
79 auth: { serverUpdateScope: "environment:maintain" },
80 }),
81}));
82vi.mock("../state/threads", () => ({
83 threadEnvironment: Object.fromEntries(
84 [
85 "archive",
86 "unarchive",
87 "delete",
88 "settle",
89 "unsettle",
90 "pin",
91 "unpin",
92 "reorderPin",
93 "snooze",
94 "unsnooze",
95 "stopSession",
96 ].map((action) => [action, action]),
97 ),
98}));
99vi.mock("../state/vcs", () => ({
100 vcsEnvironment: { removeWorktree: "removeWorktree", refreshStatus: "refreshStatus" },
101}));
102vi.mock("../state/entities", () => ({
103 readEnvironmentServerConfigLoaded: () => true,
104 readThreadShell: (ref: ScopedThreadRef) =>
105 state.threads.find(
106 (thread) => thread.environmentId === ref.environmentId && thread.id === ref.threadId,
107 ) ?? null,
108 readThreadShells: () => state.threads,
109 readEnvironmentThreadRefs: (environmentId: EnvironmentId) =>
110 state.threads
111 .filter((thread) => thread.environmentId === environmentId)
112 .map((thread) => ({ environmentId, threadId: thread.id })),
113 readProject: () => ({ workspaceRoot: "/project" }),
114}));
115vi.mock("../components/Sidebar.logic", () => ({
116 getFallbackThreadIdAfterDelete: () => null,
117 pinOrderKeyBetween: () => "a",
118}));
119vi.mock("../composerDraftStore", () => ({
120 useComposerDraftStore: (select: (store: unknown) => unknown) =>
121 select({
122 clearDraftThread: () => state.localEffects.push("clear-draft"),
123 clearProjectDraftThreadById: () => state.localEffects.push("clear-project-draft"),
124 }),
125}));
126vi.mock("../terminalUiStateStore", () => ({
127 useTerminalUiStateStore: (select: (store: unknown) => unknown) =>
128 select({
129 clearTerminalUiState: () => state.localEffects.push("clear-terminal-ui"),
130 }),
131}));
132vi.mock("../uiStateStore", () => ({
133 useUiStateStore: (select: (store: unknown) => unknown) =>
134 select({
135 markThreadVisited: () => state.localEffects.push("mark-visited"),
136 }),
137}));
138vi.mock("../lib/archivedThreadsState", () => ({
139 refreshArchivedThreadsForEnvironment: () => state.localEffects.push("refresh-archive"),
140}));
141vi.mock("../lib/composerDraftUploads", () => ({
142 releaseComposerDraftUploads: () => state.localEffects.push("release-uploads"),
143}));
144vi.mock("../localApi", () => ({
145 readLocalApi: () => ({ dialogs: { confirm: state.confirm } }),
146}));
147vi.mock("../threadRoutes", () => ({
148 resolveThreadRouteRef: () => null,
149 buildThreadRouteParams: (ref: ScopedThreadRef) => ref,
150}));
151vi.mock("../components/ui/toast", () => ({
152 stackedThreadToast: (toast: unknown) => toast,
153 toastManager: {
154 add: (toast: { title?: string }) => {
155 if (toast.title) state.toasts.push(toast.title);
156 },
157 },
158}));
159vi.mock("./useHandleNewThread", () => ({ useNewThreadHandler: () => async () => {} }));
160vi.mock("./useSettings", () => ({
161 useClientSettings: (select: (settings: unknown) => unknown) =>
162 select({
163 sidebarThreadSortOrder: "createdAt",
164 confirmThreadDelete: true,
165 confirmThreadUnpin: true,
166 }),
167}));
168​
169import { useThreadActions } from "./useThreadActions";
170​
171function seedThreadPanelState(ref: ScopedThreadRef) {
172 useRightPanelStore.getState().show(ref);
173 useDiffPanelStore.getState().selectGitScope(ref, "branch");
174 usePreviewMiniPlayerStore.getState().open(ref, browserMiniPlayerSource("tab"));
176​
177function threadPanelStatePresence(ref: ScopedThreadRef) {
178 const key = scopedThreadKey(ref);
179 return {
180 rightPanel: key in useRightPanelStore.getState().byThreadKey,
181 diffPanel: key in useDiffPanelStore.getState().byThreadKey,
182 miniPlayer: key in usePreviewMiniPlayerStore.getState().byThreadKey,
183 };
185const panelStateKept = { rightPanel: true, diffPanel: true, miniPlayer: true };
186const panelStateCleared = { rightPanel: false, diffPanel: false, miniPlayer: false };
187​
188const primary = EnvironmentId.make("primary");
189const secondary = EnvironmentId.make("secondary");
190const target = { environmentId: secondary, threadId: ThreadId.make("thread") };
191type ThreadActions = ReturnType<typeof useThreadActions>;
192const operations = [
193 {
194 name: "archive",
195 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.archiveThread(ref),
196 },
197 {
198 name: "unarchive",
199 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.unarchiveThread(ref),
200 },
201 {
202 name: "settle",
203 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.settleThread(ref),
204 },
205 {
206 name: "unsettle",
207 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.unsettleThread(ref),
208 },
209 {
210 name: "snooze",
211 run: (actions: ThreadActions, ref: ScopedThreadRef) =>
212 actions.snoozeThread(ref, "2099-01-01T00:00:00Z"),
213 },
214 {
215 name: "unsnooze",
216 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.unsnoozeThread(ref),
217 },
218 { name: "pin", run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.pinThread(ref) },
219 {
220 name: "unpin",
221 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.unpinThread(ref),
222 },
223 {
224 name: "reorderPin",
225 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.reorderPinnedThread(ref, "b"),
226 },
227] as const;
228​
229beforeEach(() => {
230 state.scopes = new Map([
231 [primary, new Set([AuthOrchestrationOperateScope])],
232 [secondary, new Set<string>()],
233 ]);
234 state.threads = [
235 {
236 environmentId: secondary,
237 id: target.threadId,
238 projectId: ProjectId.make("project"),
239 title: "Thread",
240 worktreePath: null,
241 session: null,
242 latestTurn: null,
243 },
244 ];
245 state.requests = [];
246 state.localEffects = [];
247 state.confirm.mockReset().mockResolvedValue(true);
248 state.toasts = [];
249 state.afterRequest = undefined;
250 state.sessionLookupFails = false;
251 useRightPanelStore.setState(useRightPanelStore.getInitialState(), true);
252 useDiffPanelStore.setState(useDiffPanelStore.getInitialState(), true);
253 usePreviewMiniPlayerStore.setState(usePreviewMiniPlayerStore.getInitialState(), true);
254});
255​
256describe("thread action permissions", () => {
257 it.each(operations)("$name requires the target environment's grant", async ({ run }) => {
258 const result = await run(useThreadActions(), target);
259 expect(result._tag).toBe("Failure");
260 expect(state.requests).toEqual([]);
261 expect(state.localEffects).toEqual([]);
262 });
263​
264 it.each(operations)("$name rechecks a retained callback after revocation", async ({ run }) => {
265 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
266 const actions = useThreadActions();
267 state.scopes.get(secondary)!.clear();
268 await run(actions, target);
269 expect(state.requests).toEqual([]);
270 });
271​
272 it.each(operations)(
273 "$name works after the target gains only task permission",
274 async ({ name, run }) => {
275 const actions = useThreadActions();
276 state.scopes.get(primary)!.clear();
277 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
278 expect((await run(actions, target))._tag).toBe("Success");
279 expect(state.requests).toEqual([
280 expect.objectContaining({ action: name, environmentId: secondary }),
281 ]);
282 },
283 );
284​
285 it.each(["confirmAndDeleteThread", "confirmAndUnpinThread"] as const)(
286 "%s blocks a forbidden confirmation",
287 async (action) => {
288 await useThreadActions()[action](target);
289 expect(state.confirm).not.toHaveBeenCalled();
290 expect(state.requests).toEqual([]);
291 },
292 );
293​
294 it.each(["confirmAndDeleteThread", "confirmAndUnpinThread"] as const)(
295 "%s rechecks after the confirmation",
296 async (action) => {
297 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
298 const confirmation = deferred<boolean>();
299 state.confirm.mockReturnValue(confirmation.promise);
300 const result = useThreadActions()[action](target);
301 expect(state.confirm).toHaveBeenCalledOnce();
302 state.scopes.get(secondary)!.clear();
303 confirmation.resolve(true);
304 await result;
305 expect(state.requests).toEqual([]);
306 expect(state.localEffects).toEqual([]);
307 },
308 );
309​
310 it("deletes an archived thread only with its own environment's grant", async () => {
311 state.threads = [];
312 seedThreadPanelState(target);
313 const actions = useThreadActions();
314 await actions.deleteThread(target);
315 expect(state.requests).toEqual([]);
316 expect(threadPanelStatePresence(target)).toEqual(panelStateKept);
317 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
318 expect((await actions.deleteThread(target))._tag).toBe("Success");
319 expect(state.requests).toEqual([
320 expect.objectContaining({ action: "delete", environmentId: secondary }),
321 ]);
322 expect(threadPanelStatePresence(target)).toEqual(panelStateCleared);
323 });
324​
325 it("stops before delete and local cleanup when permission is revoked during session stop", async () => {
326 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
327 state.threads[0]!.session = { status: "ready" };
328 state.afterRequest = () => state.scopes.get(secondary)!.clear();
329 seedThreadPanelState(target);
330 expect((await useThreadActions().deleteThread(target))._tag).toBe("Failure");
331 expect(state.requests.map((request) => request.action)).toEqual(["stopSession"]);
332 expect(state.localEffects).toEqual([]);
333 expect(threadPanelStatePresence(target)).toEqual(panelStateKept);
334 });
335​
336 it.each([
337 { reason: "without source-control permission", sessionLookupFails: false },
338 { reason: "when the permission lookup fails", sessionLookupFails: true },
339 ])("deletes a worktree thread and keeps its worktree $reason", async ({ sessionLookupFails }) => {
340 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
341 state.threads[0]!.worktreePath = "/worktrees/thread";
342 state.sessionLookupFails = sessionLookupFails;
343 seedThreadPanelState(target);
344 expect((await useThreadActions().deleteThread(target))._tag).toBe("Success");
345 expect(state.confirm).not.toHaveBeenCalled();
346 expect(state.requests.map((request) => request.action)).toEqual(["stopSession", "delete"]);
347 expect(state.localEffects).toContain("clear-terminal-ui");
348 expect(threadPanelStatePresence(target)).toEqual(panelStateCleared);
349 });
350​
351 it("does not request worktree removal after its grant is revoked during delete", async () => {
352 state.scopes
353 .get(secondary)!
354 .add(AuthOrchestrationOperateScope)
355 .add(AuthSourceControlWriteScope);
356 state.threads[0]!.worktreePath = "/worktrees/thread";
357 state.afterRequest = () => state.scopes.get(secondary)!.delete(AuthSourceControlWriteScope);
358 const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
359 try {
360 const result = await useThreadActions().deleteThread(target);
361 expect(result._tag).toBe("Success");
362 expect(state.requests.map((request) => request.action)).toEqual(["stopSession", "delete"]);
363 expect(state.toasts).toContain("Failed to delete worktree");
364 expect(state.localEffects).toContain("clear-terminal-ui");
365 } finally {
366 consoleError.mockRestore();
367 }
368 });
369});