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