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
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 };
24}
25
26const state = vi.hoisted(() => ({
27 serverConfig: { shellThreadFamilies: false },
28 familyLookupFails: false,
29 scopes: new Map<string, Set<string>>(),
30 threads: [] as {
31 environmentId: EnvironmentId;
32 id: ThreadId;
33 projectId: ProjectId;
34 title: string;
35 worktreePath: string | null;
36 lineage: {
37 parentThreadId: ThreadId | null;
38 relationshipToParent: "fork" | null;
39 rootThreadId: ThreadId;
40 sideChat?: boolean;
41 };
42 session: { status: "ready" | "stopped" } | null;
43 latestTurn: null;
44 }[],
45 familyThreads: [] as {
46 id: ThreadId;
47 lineage: { parentThreadId: ThreadId | null; sideChat?: boolean };
48 }[],
49 requests: [] as { action: string; environmentId: string; input: { threadId?: string } }[],
50 localEffects: [] as string[],
51 confirm: vi.fn<(message: string) => Promise<boolean>>(),
52 toasts: [] as string[],
53 afterRequest: undefined as ((action: string) => void) | undefined,
54 sessionLookupFails: false,
55}));
56
57vi.mock("react", () => ({
58 useCallback: (callback: unknown) => callback,
59 useMemo: (factory: () => unknown) => factory(),
60 useRef: (current: unknown) => ({ current }),
61}));
62vi.mock("@tanstack/react-router", () => ({
63 useRouter: () => ({
64 state: { location: { href: "/" }, matches: [] },
65 history: { subscribe: () => () => {} },
66 navigate: async () => {},
67 }),
68}));
69vi.mock("../state/session", () => ({
70 environmentSession: { sessionStateAtom: "session" },
71 readEnvironmentScope: (environmentId: string, scope: string) =>
72 state.scopes.get(environmentId)?.has(scope) === true,
73 readEnvironmentScopeDenied: (environmentId: string, scope: string) =>
74 state.scopes.get(environmentId)?.has(scope) !== true,
75}));
76vi.mock("../state/use-atom-command", () => ({
77 useAtomCommand:
78 (action: string) =>
79 async (request: { environmentId: string; input: { threadId?: string } }) => {
80 state.requests.push({ action, ...request });
81 const scope =
82 action === "removeWorktree" ? AuthSourceControlWriteScope : AuthOrchestrationOperateScope;
83 if (!state.scopes.get(request.environmentId)?.has(scope)) {
84 return AsyncResult.failure(Cause.fail(new Error("Server denied the request")));
85 }
86 state.afterRequest?.(action);
87 return AsyncResult.success(undefined);
88 },
89}));
90vi.mock("../state/use-atom-query-runner", () => ({
91 useAtomQueryRunner: (family: unknown) => async (environmentId: string) =>
92 family === "threadFamily"
93 ? state.familyLookupFails
94 ? AsyncResult.failure(Cause.fail(new Error("Family lookup failed")))
95 : AsyncResult.success({ threads: state.familyThreads })
96 : state.sessionLookupFails
97 ? AsyncResult.failure(Cause.fail(new Error("Session lookup failed")))
98 : AsyncResult.success({
99 authenticated: true,
100 scopes: [...(state.scopes.get(environmentId) ?? [])],
101 auth: { serverUpdateScope: "environment:maintain" },
102 }),
103}));
104vi.mock("../state/orchestration", () => ({
105 orchestrationEnvironment: { threadFamily: "threadFamily" },
106}));
107vi.mock("../state/server", async (importOriginal) => {
108 const actual = await importOriginal<typeof import("../state/server")>();
109 const { Atom } = await import("effect/reactivity");
110 return {
111 ...actual,
112 environmentServerConfigsAtom: Atom.make(new Map([["secondary", state.serverConfig]])),
113 };
114});
115vi.mock("../state/threads", () => ({
116 threadEnvironment: Object.fromEntries(
117 [
118 "archive",
119 "unarchive",
120 "delete",
121 "settle",
122 "unsettle",
123 "pin",
124 "unpin",
125 "reorderPin",
126 "snooze",
127 "unsnooze",
128 "stopSession",
129 ].map((action) => [action, action]),
130 ),
131}));
132vi.mock("../state/vcs", () => ({
133 vcsEnvironment: { removeWorktree: "removeWorktree", refreshStatus: "refreshStatus" },
134}));
135vi.mock("../state/entities", () => ({
136 readEnvironmentServerConfigLoaded: () => true,
137 readThreadShell: (ref: ScopedThreadRef) =>
138 state.threads.find(
139 (thread) => thread.environmentId === ref.environmentId && thread.id === ref.threadId,
140 ) ?? null,
141 readThreadShells: () => state.threads,
142 readEnvironmentThreadRefs: (environmentId: EnvironmentId) =>
143 state.threads
144 .filter((thread) => thread.environmentId === environmentId)
145 .map((thread) => ({ environmentId, threadId: thread.id })),
146 readProject: () => ({ workspaceRoot: "/project" }),
147 readDelegatedUnderParent: () => new Set(),
148}));
149vi.mock("../components/Sidebar.logic", () => ({
150 getFallbackThreadIdAfterDelete: () => null,
151 pinOrderKeyBetween: () => "a",
152}));
153vi.mock("../composerDraftStore", () => ({
154 useComposerDraftStore: (select: (store: unknown) => unknown) =>
155 select({
156 clearDraftThread: (ref: ScopedThreadRef) =>
157 state.localEffects.push(`clear-draft:${ref.threadId}`),
158 clearProjectDraftThreadById: () => state.localEffects.push("clear-project-draft"),
159 }),
160}));
161vi.mock("../terminalUiStateStore", () => ({
162 useTerminalUiStateStore: (select: (store: unknown) => unknown) =>
163 select({
164 clearTerminalUiState: () => state.localEffects.push("clear-terminal-ui"),
165 }),
166}));
167vi.mock("../uiStateStore", () => ({
168 useUiStateStore: (select: (store: unknown) => unknown) =>
169 select({
170 markThreadVisited: () => state.localEffects.push("mark-visited"),
171 }),
172}));
173vi.mock("../lib/archivedThreadsState", () => ({
174 refreshArchivedThreadsForEnvironment: () => state.localEffects.push("refresh-archive"),
175}));
176vi.mock("../lib/composerDraftUploads", () => ({
177 releaseComposerDraftUploads: (ref: ScopedThreadRef) =>
178 state.localEffects.push(`release-uploads:${ref.threadId}`),
179}));
180vi.mock("../localApi", () => ({
181 readLocalApi: () => ({ dialogs: { confirm: state.confirm } }),
182}));
183vi.mock("../threadRoutes", () => ({
184 resolveThreadRouteRef: () => null,
185 buildThreadRouteParams: (ref: ScopedThreadRef) => ref,
186}));
187vi.mock("../components/ui/toast", () => ({
188 stackedThreadToast: (toast: unknown) => toast,
189 toastManager: {
190 add: (toast: { title?: string }) => {
191 if (toast.title) state.toasts.push(toast.title);
192 },
193 },
194}));
195vi.mock("./useHandleNewThread", () => ({ useNewThreadHandler: () => async () => {} }));
196vi.mock("./useSettings", () => ({
197 useClientSettings: (select: (settings: unknown) => unknown) =>
198 select({
199 sidebarThreadSortOrder: "createdAt",
200 confirmThreadDelete: true,
201 confirmThreadUnpin: true,
202 }),
203}));
204
205import { useThreadActions } from "./useThreadActions";
206
207function seedThreadPanelState(ref: ScopedThreadRef) {
208 useRightPanelStore.getState().show(ref);
209 useDiffPanelStore.getState().selectGitScope(ref, "branch");
210 usePreviewMiniPlayerStore.getState().open(ref, browserMiniPlayerSource("tab"));
211}
212
213function threadPanelStatePresence(ref: ScopedThreadRef) {
214 const key = scopedThreadKey(ref);
215 return {
216 rightPanel: key in useRightPanelStore.getState().byThreadKey,
217 diffPanel: key in useDiffPanelStore.getState().byThreadKey,
218 miniPlayer: key in usePreviewMiniPlayerStore.getState().byThreadKey,
219 };
220}
221const panelStateKept = { rightPanel: true, diffPanel: true, miniPlayer: true };
222const panelStateCleared = { rightPanel: false, diffPanel: false, miniPlayer: false };
223
224const primary = EnvironmentId.make("primary");
225const secondary = EnvironmentId.make("secondary");
226const target = { environmentId: secondary, threadId: ThreadId.make("thread") };
227type ThreadActions = ReturnType<typeof useThreadActions>;
228const operations = [
229 {
230 name: "archive",
231 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.archiveThread(ref),
232 },
233 {
234 name: "unarchive",
235 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.unarchiveThread(ref),
236 },
237 {
238 name: "settle",
239 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.settleThread(ref),
240 },
241 {
242 name: "unsettle",
243 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.unsettleThread(ref),
244 },
245 {
246 name: "snooze",
247 run: (actions: ThreadActions, ref: ScopedThreadRef) =>
248 actions.snoozeThread(ref, "2099-01-01T00:00:00Z"),
249 },
250 {
251 name: "unsnooze",
252 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.unsnoozeThread(ref),
253 },
254 { name: "pin", run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.pinThread(ref) },
255 {
256 name: "unpin",
257 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.unpinThread(ref),
258 },
259 {
260 name: "reorderPin",
261 run: (actions: ThreadActions, ref: ScopedThreadRef) => actions.reorderPinnedThread(ref, "b"),
262 },
263] as const;
264
265beforeEach(() => {
266 state.serverConfig.shellThreadFamilies = false;
267 state.familyLookupFails = false;
268 state.familyThreads = [];
269 state.scopes = new Map([
270 [primary, new Set([AuthOrchestrationOperateScope])],
271 [secondary, new Set<string>()],
272 ]);
273 state.threads = [
274 {
275 environmentId: secondary,
276 id: target.threadId,
277 projectId: ProjectId.make("project"),
278 title: "Thread",
279 worktreePath: null,
280 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: target.threadId },
281 session: null,
282 latestTurn: null,
283 },
284 ];
285 state.requests = [];
286 state.localEffects = [];
287 state.confirm.mockReset().mockResolvedValue(true);
288 state.toasts = [];
289 state.afterRequest = undefined;
290 state.sessionLookupFails = false;
291 useRightPanelStore.setState(useRightPanelStore.getInitialState(), true);
292 useDiffPanelStore.setState(useDiffPanelStore.getInitialState(), true);
293 usePreviewMiniPlayerStore.setState(usePreviewMiniPlayerStore.getInitialState(), true);
294});
295
296describe("thread action permissions", () => {
297 it.each(operations)("$name requires the target environment's grant", async ({ run }) => {
298 const result = await run(useThreadActions(), target);
299 expect(result._tag).toBe("Failure");
300 expect(state.requests).toEqual([]);
301 expect(state.localEffects).toEqual([]);
302 });
303
304 it.each(operations)("$name rechecks a retained callback after revocation", async ({ run }) => {
305 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
306 const actions = useThreadActions();
307 state.scopes.get(secondary)!.clear();
308 await run(actions, target);
309 expect(state.requests).toEqual([]);
310 });
311
312 it.each(operations)(
313 "$name works after the target gains only task permission",
314 async ({ name, run }) => {
315 const actions = useThreadActions();
316 state.scopes.get(primary)!.clear();
317 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
318 expect((await run(actions, target))._tag).toBe("Success");
319 expect(state.requests).toEqual([
320 expect.objectContaining({ action: name, environmentId: secondary }),
321 ]);
322 },
323 );
324
325 it.each(["confirmAndDeleteThread", "confirmAndUnpinThread"] as const)(
326 "%s blocks a forbidden confirmation",
327 async (action) => {
328 await useThreadActions()[action](target);
329 expect(state.confirm).not.toHaveBeenCalled();
330 expect(state.requests).toEqual([]);
331 },
332 );
333
334 it.each(["confirmAndDeleteThread", "confirmAndUnpinThread"] as const)(
335 "%s rechecks after the confirmation",
336 async (action) => {
337 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
338 const confirmation = deferred<boolean>();
339 state.confirm.mockReturnValue(confirmation.promise);
340 const result = useThreadActions()[action](target);
341 expect(state.confirm).toHaveBeenCalledOnce();
342 state.scopes.get(secondary)!.clear();
343 confirmation.resolve(true);
344 await result;
345 expect(state.requests).toEqual([]);
346 expect(state.localEffects).toEqual([]);
347 },
348 );
349
350 it("names an archived thread in its delete confirmation and preserves it on cancel", async () => {
351 state.threads = [];
352 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
353 state.confirm.mockResolvedValue(false);
354 await useThreadActions().confirmAndDeleteThread(target, "Archived release notes");
355 expect(state.confirm).toHaveBeenCalledWith(
356 expect.stringContaining('Delete thread "Archived release notes"?'),
357 { variant: "destructive" },
358 );
359 expect(state.requests).toEqual([]);
360 });
361
362 it("deletes an archived thread only with its own environment's grant", async () => {
363 state.serverConfig.shellThreadFamilies = true;
364 state.familyThreads = [
365 {
366 id: ThreadId.make("side-chat"),
367 lineage: { parentThreadId: target.threadId, sideChat: true },
368 },
369 { id: ThreadId.make("fork"), lineage: { parentThreadId: target.threadId } },
370 {
371 id: ThreadId.make("other-side-chat"),
372 lineage: { parentThreadId: ThreadId.make("other-parent"), sideChat: true },
373 },
374 ];
375 state.threads = [];
376 seedThreadPanelState(target);
377 const actions = useThreadActions();
378 await actions.deleteThread(target);
379 expect(state.requests).toEqual([]);
380 expect(threadPanelStatePresence(target)).toEqual(panelStateKept);
381 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
382 expect((await actions.deleteThread(target))._tag).toBe("Success");
383 expect(state.requests).toEqual([
384 expect.objectContaining({ action: "delete", environmentId: secondary }),
385 ]);
386 expect(threadPanelStatePresence(target)).toEqual(panelStateCleared);
387 expect(state.localEffects).toEqual([
388 "release-uploads:thread",
389 "clear-draft:thread",
390 "release-uploads:side-chat",
391 "clear-draft:side-chat",
392 "refresh-archive",
393 "clear-terminal-ui",
394 ]);
395 expect(state.localEffects).not.toContain("clear-draft:fork");
396 expect(state.localEffects).not.toContain("clear-draft:other-side-chat");
397
398 // The family read only finds drafts to clear; it never blocks the delete.
399 state.familyLookupFails = true;
400 state.requests = [];
401 state.localEffects = [];
402 expect((await actions.deleteThread(target))._tag).toBe("Success");
403 expect(state.requests).toEqual([
404 expect.objectContaining({ action: "delete", environmentId: secondary }),
405 ]);
406 expect(state.localEffects).toContain("clear-draft:thread");
407 });
408
409 it("stops before delete and local cleanup when permission is revoked during session stop", async () => {
410 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
411 state.threads[0]!.session = { status: "ready" };
412 state.afterRequest = () => state.scopes.get(secondary)!.clear();
413 seedThreadPanelState(target);
414 expect((await useThreadActions().deleteThread(target))._tag).toBe("Failure");
415 expect(state.requests.map((request) => request.action)).toEqual(["stopSession"]);
416 expect(state.localEffects).toEqual([]);
417 expect(threadPanelStatePresence(target)).toEqual(panelStateKept);
418 });
419
420 it.each([
421 { reason: "without source-control permission", sessionLookupFails: false },
422 { reason: "when the permission lookup fails", sessionLookupFails: true },
423 ])("deletes a worktree thread and keeps its worktree $reason", async ({ sessionLookupFails }) => {
424 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
425 state.threads[0]!.worktreePath = "/worktrees/thread";
426 state.sessionLookupFails = sessionLookupFails;
427 seedThreadPanelState(target);
428 expect((await useThreadActions().deleteThread(target))._tag).toBe("Success");
429 expect(state.confirm).not.toHaveBeenCalled();
430 expect(state.requests.map((request) => request.action)).toEqual(["stopSession", "delete"]);
431 expect(state.localEffects).toContain("clear-terminal-ui");
432 expect(threadPanelStatePresence(target)).toEqual(panelStateCleared);
433 });
434
435 it("offers to delete the worktree that only its side chats share", async () => {
436 state.scopes
437 .get(secondary)!
438 .add(AuthOrchestrationOperateScope)
439 .add(AuthSourceControlWriteScope);
440 state.threads[0]!.worktreePath = "/worktrees/thread";
441 state.threads.push({
442 ...state.threads[0]!,
443 id: ThreadId.make("side-chat"),
444 lineage: {
445 parentThreadId: target.threadId,
446 relationshipToParent: "fork",
447 rootThreadId: target.threadId,
448 sideChat: true,
449 },
450 });
451 expect((await useThreadActions().deleteThread(target))._tag).toBe("Success");
452 expect(state.confirm).toHaveBeenCalledOnce();
453 expect(state.requests.map((request) => request.action)).toEqual([
454 "stopSession",
455 "delete",
456 "removeWorktree",
457 "refreshStatus",
458 ]);
459 });
460
461 it("clears the drafts of the side chats deleted with it", async () => {
462 state.scopes.get(secondary)!.add(AuthOrchestrationOperateScope);
463 const parent = state.threads[0]!;
464 state.threads.push(
465 {
466 ...parent,
467 id: ThreadId.make("side-chat"),
468 lineage: { ...parent.lineage, parentThreadId: parent.id, sideChat: true },
469 },
470 {
471 ...parent,
472 id: ThreadId.make("fork"),
473 lineage: { ...parent.lineage, parentThreadId: parent.id },
474 },
475 );
476 expect((await useThreadActions().deleteThread(target))._tag).toBe("Success");
477 expect(state.localEffects).toEqual(
478 expect.arrayContaining(["release-uploads:side-chat", "clear-draft:side-chat"]),
479 );
480 expect(state.localEffects).not.toContain("clear-draft:fork");
481 });
482
483 it("does not request worktree removal after its grant is revoked during delete", async () => {
484 state.scopes
485 .get(secondary)!
486 .add(AuthOrchestrationOperateScope)
487 .add(AuthSourceControlWriteScope);
488 state.threads[0]!.worktreePath = "/worktrees/thread";
489 state.afterRequest = () => state.scopes.get(secondary)!.delete(AuthSourceControlWriteScope);
490 const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
491 try {
492 const result = await useThreadActions().deleteThread(target);
493 expect(result._tag).toBe("Success");
494 expect(state.requests.map((request) => request.action)).toEqual(["stopSession", "delete"]);
495 expect(state.toasts).toContain("Failed to delete worktree");
496 expect(state.localEffects).toContain("clear-terminal-ui");
497 } finally {
498 consoleError.mockRestore();
499 }
500 });
501});