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 readEnvironmentServerConfigLoaded: () => true,
54 readThreadShell: () => threadShell,
55}));
56vi.mock("../state/use-atom-command", () => ({
57 useAtomCommand: (command: unknown) => {
58 switch (command) {
59 case threadEnvironment.pin:
60 return commands.pin;
61 case threadEnvironment.unpin:
62 return commands.unpin;
63 case threadEnvironment.archive:
64 return commands.archive;
65 case threadEnvironment.unarchive:
66 return commands.unarchive;
67 case threadEnvironment.settle:
68 return commands.settle;
69 case threadEnvironment.unsettle:
70 return commands.unsettle;
71 case threadEnvironment.snooze:
72 return commands.snooze;
73 case threadEnvironment.unsnooze:
74 return commands.unsnooze;
75 default:
76 return vi.fn();
77 }
78 },
79}));
80
81const target = {
82 environmentId: EnvironmentId.make("undo-env"),
83 threadId: ThreadId.make("thread"),
84};
85function currentUndo() {
86 const notice = useThreadUndoNotice.getState().notice;
87 expect(notice).not.toBeNull();
88 return notice!.undo;
89}
90
91beforeEach(() => {
92 vi.useFakeTimers();
93 for (const command of Object.values(commands)) {
94 command.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
95 }
96 router.navigate.mockClear();
97 router.state.matches[0]!.params = {};
98 threadShell.pinnedAt = null;
99 threadShell.snoozedUntil = null;
100});
101afterEach(() => {
102 vi.runAllTimers();
103 vi.useRealTimers();
104 vi.restoreAllMocks();
105});
106
107describe("concurrent thread action Undo", () => {
108 it.each([
109 ["settleThread", "settle", "unsettle", "Settled"],
110 ["snoozeThread", "snooze", "unsnooze", "Snoozed"],
111 ["unpinThread", "unpin", "pin", "Unpinned"],
112 ["archiveThread", "archive", "unarchive", "Archived"],
113 ] as const)(
114 "%s retains one undo for concurrent successful requests",
115 async (handler, action, inverse, notice) => {
116 const actions = useThreadActions();
117 const run = () =>
118 handler === "snoozeThread"
119 ? actions.snoozeThread(target, "2099-01-01T09:00:00.000Z")
120 : actions[handler](target);
121 await Promise.all([run(), run()]);
122 expect(commands[action]).toHaveBeenCalledTimes(2);
123 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: notice, count: 1 });
124 await currentUndo()();
125 expect(commands[inverse]).toHaveBeenCalledOnce();
126 },
127 );
128});
129
130describe("unpin Undo", () => {
131 it("restores the original snooze after restoring the pin", async () => {
132 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
133 threadShell.snoozedUntil = "2030-01-01T09:00:00.000Z";
134 await useThreadActions().unpinThread(target);
135 await currentUndo()();
136 expect(commands.pin).toHaveBeenCalledExactlyOnceWith({
137 environmentId: target.environmentId,
138 input: { threadId: target.threadId, orderKey: "a0" },
139 });
140 expect(commands.snooze).toHaveBeenCalledExactlyOnceWith({
141 environmentId: target.environmentId,
142 input: { threadId: target.threadId, snoozedUntil: threadShell.snoozedUntil },
143 });
144 expect(commands.pin.mock.invocationCallOrder[0]).toBeLessThan(
145 commands.snooze.mock.invocationCallOrder[0]!,
146 );
147 });
148
149 it("restores the pin without an already expired snooze", async () => {
150 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
151 threadShell.snoozedUntil = "2000-01-01T09:00:00.000Z";
152 await useThreadActions().unpinThread(target);
153 await currentUndo()();
154 expect(commands.pin).toHaveBeenCalledOnce();
155 expect(commands.snooze).not.toHaveBeenCalled();
156 });
157
158 it("ignores an old notice across hook instances and still restores the latest unpin", async () => {
159 const sidebar = useThreadActions();
160 const header = useThreadActions();
161 await sidebar.unpinThread(target);
162 const staleUndo = currentUndo();
163 await header.pinThread(target, { orderKey: "a1" });
164 await header.unpinThread(target);
165 const latestUndo = currentUndo();
166 await staleUndo();
167 expect(commands.pin).toHaveBeenCalledTimes(1);
168 await latestUndo();
169 expect(commands.pin).toHaveBeenCalledTimes(2);
170 expect(commands.pin).toHaveBeenLastCalledWith({
171 environmentId: target.environmentId,
172 input: { threadId: target.threadId, orderKey: "a0" },
173 });
174 await latestUndo();
175 expect(commands.pin).toHaveBeenCalledTimes(2);
176 });
177});
178
179describe("archive Undo", () => {
180 it("unarchives and returns to the thread when archiving left it", async () => {
181 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
182 router.state.matches[0]!.params = {
183 environmentId: target.environmentId,
184 threadId: target.threadId,
185 };
186 const actions = useThreadActions();
187 await actions.archiveThread(target);
188 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Archived", count: 1 });
189 expect(add).not.toHaveBeenCalled();
190 await currentUndo()();
191 expect(commands.unarchive).toHaveBeenCalledExactlyOnceWith({
192 environmentId: target.environmentId,
193 input: { threadId: target.threadId },
194 });
195 expect(router.navigate).toHaveBeenCalledWith(
196 expect.objectContaining({
197 to: "/$environmentId/$threadId",
198 params: { environmentId: target.environmentId, threadId: target.threadId },
199 }),
200 );
201 });
202});
203
204describe("settle and snooze Undo", () => {
205 it("un-settles from the notice and expires the Undo after a manual un-settle", async () => {
206 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
207 const actions = useThreadActions();
208 await actions.settleThread(target);
209 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Settled", count: 1 });
210 expect(add).not.toHaveBeenCalled();
211 const undo = currentUndo();
212 await actions.unsettleThread(target);
213 await undo();
214 expect(commands.unsettle).toHaveBeenCalledOnce();
215 });
216
217 it("re-pins and re-snoozes a thread that settling had cleared", async () => {
218 const snoozedUntil = "2030-01-01T09:00:00.000Z";
219 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
220 threadShell.snoozedUntil = snoozedUntil;
221 const actions = useThreadActions();
222 await actions.settleThread(target);
223 await currentUndo()();
224 expect(commands.unsettle).toHaveBeenCalledOnce();
225 expect(commands.pin).toHaveBeenCalledExactlyOnceWith({
226 environmentId: target.environmentId,
227 input: { threadId: target.threadId, orderKey: "a0" },
228 });
229 expect(commands.snooze).toHaveBeenCalledExactlyOnceWith({
230 environmentId: target.environmentId,
231 input: { threadId: target.threadId, snoozedUntil },
232 });
233 });
234
235 it("stops settle restoration if restoring the pin fails", async () => {
236 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
237 threadShell.snoozedUntil = "2030-01-01T09:00:00.000Z";
238 commands.pin.mockResolvedValue({ _tag: "Failure", cause: Cause.fail(new Error("Pin failed")) });
239 vi.spyOn(toastManager, "add").mockReturnValue("toast");
240 await useThreadActions().settleThread(target);
241 await currentUndo()();
242 expect(commands.unsettle).toHaveBeenCalledOnce();
243 expect(commands.pin).toHaveBeenCalledOnce();
244 expect(commands.snooze).not.toHaveBeenCalled();
245 });
246
247 it("expires an older unpin Undo when the thread is settled", async () => {
248 const actions = useThreadActions();
249 await actions.unpinThread(target);
250 const staleUnpinUndo = currentUndo();
251 await actions.settleThread(target);
252 await staleUnpinUndo();
253 expect(commands.pin).not.toHaveBeenCalled();
254 });
255
256 // regression: #12972 the sidebar undo notice must reverse a snooze
257 it("wakes the thread from the snooze notice", async () => {
258 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
259 const actions = useThreadActions();
260 await actions.snoozeThread(target, "2100-01-01T00:00:00.000Z");
261 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Snoozed", count: 1 });
262 expect(add).not.toHaveBeenCalled();
263 await currentUndo()();
264 expect(commands.unsnooze).toHaveBeenCalledExactlyOnceWith({
265 environmentId: target.environmentId,
266 input: { threadId: target.threadId, reason: "user" },
267 });
268 });
269});