Open History to see the last commit
1import {
2 AuthOrchestrationOperateScope,
3 EnvironmentId,
4 ThreadId,
5 type ContextMenuItem,
6} from "@t3tools/contracts";
7import { AsyncResult } from "effect/reactivity";
8import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
9
10import type { ThreadActionMenuId } from "../components/threadActionMenu.logic";
11
12function deferred<T>() {
13 let resolve!: (value: T) => void;
14 const promise = new Promise<T>((complete) => {
15 resolve = complete;
16 });
17 return { promise, resolve };
18}
19
20const state = vi.hoisted(() => ({
21 granted: new Set<string>(),
22 effects: [] as string[],
23 completed: deferred<void>(),
24 show: vi.fn<
25 (
26 items: ReadonlyArray<ContextMenuItem<ThreadActionMenuId>>,
27 position: { x: number; y: number },
28 ) => Promise<ThreadActionMenuId | null>
29 >(),
30}));
31
32function recordEffect(action: string) {
33 state.effects.push(action);
34 state.completed.resolve();
35}
36
37vi.mock("../components/CustomSnoozeDialog", () => ({ requestCustomSnooze: vi.fn() }));
38vi.mock("react", () => ({
39 useCallback: (callback: unknown) => callback,
40 useMemo: (factory: () => unknown) => factory(),
41}));
42vi.mock("@tanstack/react-router", () => ({
43 useRouter: () => ({ navigate: async () => recordEffect("project-settings") }),
44}));
45vi.mock("../state/session", () => ({
46 readEnvironmentScope: (environmentId: string, scope: string) =>
47 scope === AuthOrchestrationOperateScope && state.granted.has(environmentId),
48 readEnvironmentScopeDenied: (environmentId: string) => !state.granted.has(environmentId),
49}));
50vi.mock("../state/entities", () => ({
51 readEnvironmentServerConfigLoaded: () => true,
52 readEnvironmentSupportsAutoSettleOptOut: () => true,
53 readThreadShell: () => ({
54 id: "thread",
55 environmentId: "secondary",
56 projectId: "project",
57 title: "Thread",
58 branch: "main",
59 worktreePath: null,
60 runtime: null,
61 latestRun: null,
62 }),
63 useProjects: () => [{ id: "project", environmentId: "secondary" }],
64}));
65vi.mock("../state/environments", () => ({ usePrimaryEnvironmentId: () => "primary" }));
66vi.mock("../state/threads", () => ({ threadEnvironment: { updateMetadata: "metadata" } }));
67vi.mock("../state/use-atom-command", () => ({
68 useAtomCommand: () => async () => {
69 recordEffect("metadata");
70 return AsyncResult.success(undefined);
71 },
72}));
73vi.mock("../localApi", () => ({
74 readLocalApi: () => ({
75 contextMenu: { show: state.show, close: () => {} },
76 dialogs: {
77 confirm: async () => {
78 recordEffect("confirm");
79 return false;
80 },
81 },
82 }),
83}));
84vi.mock("@t3tools/client-runtime/state/project-grouping", () => ({
85 deriveLogicalProjectKeyFromSettings: () => "project",
86 derivePhysicalProjectKey: () => "project",
87 selectProjectGroupingSettings: () => ({}),
88}));
89vi.mock("../sidebarProjectGrouping", () => ({
90 buildPhysicalToLogicalProjectKeyMap: () => new Map(),
91}));
92vi.mock("../uiStateStore", () => ({
93 useUiStateStore: (select: (store: unknown) => unknown) =>
94 select({
95 markThreadUnread: () => recordEffect("mark-unread"),
96 }),
97}));
98vi.mock("../components/ui/toast", () => ({
99 stackedThreadToast: (toast: unknown) => toast,
100 toastManager: { add: () => state.completed.resolve() },
101}));
102vi.mock("../components/Sidebar.snooze", () => ({
103 resolveSnoozePresets: () => [
104 { id: "hour", label: "In 1 hour", whenLabel: "3 PM", snoozedUntil: "2099-01-01T00:00:00Z" },
105 ],
106 snoozeWakeDescription: () => "later",
107}));
108vi.mock("./useCopyToClipboard", () => ({
109 useCopyToClipboard: () => ({ copyToClipboard: () => recordEffect("copy") }),
110}));
111vi.mock("./useHandleNewThread", () => ({
112 useNewThreadHandler: () => async () => recordEffect("draft"),
113}));
114vi.mock("./useSettings", () => ({
115 useClientSettings: (select: (settings: unknown) => unknown) =>
116 select({
117 confirmThreadDelete: true,
118 confirmThreadArchive: true,
119 timestampFormat: "12-hour",
120 }),
121}));
122vi.mock("./useThreadActions", () => ({
123 canTurnThreadIntoProject: () => false,
124 useThreadActions: () =>
125 Object.fromEntries(
126 [
127 "markThreadUnread",
128 "settleThread",
129 "unsettleThread",
130 "snoozeThread",
131 "unsnoozeThread",
132 "pinThread",
133 "confirmAndUnpinThread",
134 "archiveThread",
135 "deleteThread",
136 ].map((action) => [
137 action,
138 async () => {
139 recordEffect(action === "markThreadUnread" ? "mark-unread" : action);
140 return AsyncResult.success(undefined);
141 },
142 ]),
143 ),
144}));
145
146import { useThreadActionMenu } from "./useThreadActionMenu";
147
148const target = {
149 environmentId: EnvironmentId.make("secondary"),
150 threadId: ThreadId.make("thread"),
151};
152const position = { x: 10, y: 20 };
153const createMenu = (options: { readonly onFind?: (threadRef: typeof target) => void } = {}) =>
154 useThreadActionMenu({
155 threadRef: target,
156 projectCwd: "/project",
157 onStartRename: () => recordEffect("rename"),
158 onFind: options.onFind,
159 canShareWithGuest: false,
160 });
161
162beforeEach(() => {
163 state.granted = new Set(["primary"]);
164 state.effects = [];
165 state.completed = deferred<void>();
166 state.show.mockReset().mockResolvedValue(null);
167});
168
169describe("thread menu permissions", () => {
170 it.each(["rename", "regenerate-title", "delete", "pin", "settle", "archive"] as const)(
171 "%s rechecks after the native menu closes",
172 async (action) => {
173 state.granted.add("secondary");
174 const choice = deferred<ThreadActionMenuId | null>();
175 state.show.mockReturnValue(choice.promise);
176 createMenu().openMenu(position);
177 state.granted.delete("secondary");
178 choice.resolve(action);
179 await state.completed.promise;
180 expect(state.effects).toEqual([]);
181 },
182 );
183
184 it("offers find only to a header that can open it, without task permission", async () => {
185 createMenu().openMenu(position);
186 expect(state.show.mock.calls[0]![0].some((item) => item.id === "find")).toBe(false);
187 state.show.mockResolvedValue("find");
188 const onFind = vi.fn(() => recordEffect("find"));
189 createMenu({ onFind }).openMenu(position);
190 await state.completed.promise;
191 const items = state.show.mock.calls[1]![0];
192 expect(items[0]).toMatchObject({ id: "find", label: "Find in thread" });
193 expect(items[0]?.disabled).not.toBe(true);
194 expect(state.effects).toEqual(["find"]);
195 expect(onFind).toHaveBeenCalledExactlyOnceWith(target);
196 });
197});