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