Open History to see the last commit
1import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2import * as Cause from "effect/Cause";
3import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4
5import { useThreadActions } from "./useThreadActions";
6import { threadEnvironment } from "../state/threads";
7import { toastManager } from "../components/ui/toast";
8import { useThreadUndoNotice } from "./showThreadUndoNotice";
9
10const commands = vi.hoisted(() => ({
11 pin: vi.fn(),
12 unpin: vi.fn(),
13 archive: vi.fn(),
14 unarchive: vi.fn(),
15 settle: vi.fn(),
16 unsettle: vi.fn(),
17 snooze: vi.fn(),
18 unsnooze: vi.fn(),
19}));
20const router = vi.hoisted(() => ({
21 navigate: vi.fn(async () => {}),
22 state: { matches: [{ params: {} as Record<string, string> }] },
23}));
24vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
25vi.mock("../state/session", async (original) => ({
26 ...(await original<typeof import("../state/session")>()),
27 readEnvironmentScope: () => true,
28}));
29vi.mock("react", async (original) => ({
30 ...(await original<typeof import("react")>()),
31 useCallback: (callback: unknown) => callback,
32 useMemo: (create: () => unknown) => create(),
33 useRef: (value: unknown) => ({ current: value }),
34}));
35vi.mock("@tanstack/react-router", () => ({ useRouter: () => router }));
36vi.mock("./useSettings", () => ({ useClientSettings: () => false }));
37vi.mock("./useHandleNewThread", () => ({ useNewThreadHandler: () => vi.fn() }));
38vi.mock("../composerDraftStore", () => ({ useComposerDraftStore: () => vi.fn() }));
39vi.mock("../terminalUiStateStore", () => ({ useTerminalUiStateStore: () => vi.fn() }));
40vi.mock("../uiStateStore", () => ({ useUiStateStore: () => vi.fn() }));
41vi.mock("../lib/archivedThreadsState", () => ({ refreshArchivedThreadsForEnvironment: vi.fn() }));
42const threadShell = vi.hoisted(() => ({
43 title: "Thread",
44 pinOrderKey: "a0",
45 pinnedAt: null as string | null,
46 snoozedUntil: null as string | null,
47 projectId: "project",
48 environmentId: "undo-env",
49 session: null,
50}));
51vi.mock("../state/entities", async (original) => ({
52 ...(await original<typeof import("../state/entities")>()),
53 readEnvironmentSupportsPinning: () => true,
54 readEnvironmentSupportsPinReorder: () => true,
55 readEnvironmentSupportsSettlement: () => true,
56 readEnvironmentSupportsSnooze: () => true,
57 readThreadShell: () => threadShell,
58}));
59vi.mock("../state/use-atom-command", () => ({
60 useAtomCommand: (command: unknown) => {
61 switch (command) {
62 case threadEnvironment.pin:
63 return commands.pin;
64 case threadEnvironment.unpin:
65 return commands.unpin;
66 case threadEnvironment.archive:
67 return commands.archive;
68 case threadEnvironment.unarchive:
69 return commands.unarchive;
70 case threadEnvironment.settle:
71 return commands.settle;
72 case threadEnvironment.unsettle:
73 return commands.unsettle;
74 case threadEnvironment.snooze:
75 return commands.snooze;
76 case threadEnvironment.unsnooze:
77 return commands.unsnooze;
78 default:
79 return vi.fn();
80 }
81 },
82}));
83
84const target = {
85 environmentId: EnvironmentId.make("undo-env"),
86 threadId: ThreadId.make("thread"),
87};
88function currentUndo() {
89 const notice = useThreadUndoNotice.getState().notice;
90 expect(notice).not.toBeNull();
91 return notice!.undo;
92}
93
94beforeEach(() => {
95 vi.useFakeTimers();
96 for (const command of Object.values(commands)) {
97 command.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
98 }
99 router.navigate.mockClear();
100 router.state.matches[0]!.params = {};
101 threadShell.pinnedAt = null;
102 threadShell.snoozedUntil = null;
103});
104afterEach(() => {
105 vi.runAllTimers();
106 vi.useRealTimers();
107 vi.restoreAllMocks();
108});
109
110describe("concurrent thread action Undo", () => {
111 it.each([
112 ["settleThread", "settle", "unsettle", "Settled"],
113 ["snoozeThread", "snooze", "unsnooze", "Snoozed"],
114 ["unpinThread", "unpin", "pin", "Unpinned"],
115 ["archiveThread", "archive", "unarchive", "Archived"],
116 ] as const)(
117 "%s retains one undo for concurrent successful requests",
118 async (handler, action, inverse, notice) => {
119 const actions = useThreadActions();
120 const run = () =>
121 handler === "snoozeThread"
122 ? actions.snoozeThread(target, "2099-01-01T09:00:00.000Z")
123 : actions[handler](target);
124 await Promise.all([run(), run()]);
125 expect(commands[action]).toHaveBeenCalledTimes(2);
126 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: notice, count: 1 });
127 await currentUndo()();
128 expect(commands[inverse]).toHaveBeenCalledOnce();
129 },
130 );
131});
132
133describe("unpin Undo", () => {
134 it("restores the original snooze after restoring the pin", async () => {
135 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
136 threadShell.snoozedUntil = "2030-01-01T09:00:00.000Z";
137 await useThreadActions().unpinThread(target);
138 await currentUndo()();
139 expect(commands.pin).toHaveBeenCalledExactlyOnceWith({
140 environmentId: target.environmentId,
141 input: { threadId: target.threadId, orderKey: "a0" },
142 });
143 expect(commands.snooze).toHaveBeenCalledExactlyOnceWith({
144 environmentId: target.environmentId,
145 input: { threadId: target.threadId, snoozedUntil: threadShell.snoozedUntil },
146 });
147 expect(commands.pin.mock.invocationCallOrder[0]).toBeLessThan(
148 commands.snooze.mock.invocationCallOrder[0]!,
149 );
150 });
151
152 it("restores the pin without an already expired snooze", async () => {
153 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
154 threadShell.snoozedUntil = "2000-01-01T09:00:00.000Z";
155 await useThreadActions().unpinThread(target);
156 await currentUndo()();
157 expect(commands.pin).toHaveBeenCalledOnce();
158 expect(commands.snooze).not.toHaveBeenCalled();
159 });
160
161 it("ignores an old notice across hook instances and still restores the latest unpin", async () => {
162 const sidebar = useThreadActions();
163 const header = useThreadActions();
164 await sidebar.unpinThread(target);
165 const staleUndo = currentUndo();
166 await header.pinThread(target, { orderKey: "a1" });
167 await header.unpinThread(target);
168 const latestUndo = currentUndo();
169 await staleUndo();
170 expect(commands.pin).toHaveBeenCalledTimes(1);
171 await latestUndo();
172 expect(commands.pin).toHaveBeenCalledTimes(2);
173 expect(commands.pin).toHaveBeenLastCalledWith({
174 environmentId: target.environmentId,
175 input: { threadId: target.threadId, orderKey: "a0" },
176 });
177 await latestUndo();
178 expect(commands.pin).toHaveBeenCalledTimes(2);
179 });
180});
181
182describe("archive Undo", () => {
183 it("unarchives and returns to the thread when archiving left it", async () => {
184 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
185 router.state.matches[0]!.params = {
186 environmentId: target.environmentId,
187 threadId: target.threadId,
188 };
189 const actions = useThreadActions();
190 await actions.archiveThread(target);
191 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Archived", count: 1 });
192 expect(add).not.toHaveBeenCalled();
193 await currentUndo()();
194 expect(commands.unarchive).toHaveBeenCalledExactlyOnceWith({
195 environmentId: target.environmentId,
196 input: { threadId: target.threadId },
197 });
198 expect(router.navigate).toHaveBeenCalledWith(
199 expect.objectContaining({
200 to: "/$environmentId/$threadId",
201 params: { environmentId: target.environmentId, threadId: target.threadId },
202 }),
203 );
204 });
205});
206
207describe("settle and snooze Undo", () => {
208 it("un-settles from the notice and expires the Undo after a manual un-settle", async () => {
209 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
210 const actions = useThreadActions();
211 await actions.settleThread(target);
212 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Settled", count: 1 });
213 expect(add).not.toHaveBeenCalled();
214 const undo = currentUndo();
215 await actions.unsettleThread(target);
216 await undo();
217 expect(commands.unsettle).toHaveBeenCalledOnce();
218 });
219
220 it("re-pins and re-snoozes a thread that settling had cleared", async () => {
221 const snoozedUntil = "2030-01-01T09:00:00.000Z";
222 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
223 threadShell.snoozedUntil = snoozedUntil;
224 const actions = useThreadActions();
225 await actions.settleThread(target);
226 await currentUndo()();
227 expect(commands.unsettle).toHaveBeenCalledOnce();
228 expect(commands.pin).toHaveBeenCalledExactlyOnceWith({
229 environmentId: target.environmentId,
230 input: { threadId: target.threadId, orderKey: "a0" },
231 });
232 expect(commands.snooze).toHaveBeenCalledExactlyOnceWith({
233 environmentId: target.environmentId,
234 input: { threadId: target.threadId, snoozedUntil },
235 });
236 });
237
238 it("stops settle restoration if restoring the pin fails", async () => {
239 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
240 threadShell.snoozedUntil = "2030-01-01T09:00:00.000Z";
241 commands.pin.mockResolvedValue({ _tag: "Failure", cause: Cause.fail(new Error("Pin failed")) });
242 vi.spyOn(toastManager, "add").mockReturnValue("toast");
243 await useThreadActions().settleThread(target);
244 await currentUndo()();
245 expect(commands.unsettle).toHaveBeenCalledOnce();
246 expect(commands.pin).toHaveBeenCalledOnce();
247 expect(commands.snooze).not.toHaveBeenCalled();
248 });
249
250 it("expires an older unpin Undo when the thread is settled", async () => {
251 const actions = useThreadActions();
252 await actions.unpinThread(target);
253 const staleUnpinUndo = currentUndo();
254 await actions.settleThread(target);
255 await staleUnpinUndo();
256 expect(commands.pin).not.toHaveBeenCalled();
257 });
258
259 // regression: #12972 the sidebar undo notice must reverse a snooze
260 it("wakes the thread from the snooze notice", async () => {
261 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
262 const actions = useThreadActions();
263 await actions.snoozeThread(target, "2100-01-01T00:00:00.000Z");
264 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Snoozed", count: 1 });
265 expect(add).not.toHaveBeenCalled();
266 await currentUndo()();
267 expect(commands.unsnooze).toHaveBeenCalledExactlyOnceWith({
268 environmentId: target.environmentId,
269 input: { threadId: target.threadId, reason: "user" },
270 });
271 });
272});