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 delete: vi.fn(),
16 settle: vi.fn(),
17 unsettle: vi.fn(),
18 snooze: vi.fn(),
19 unsnooze: vi.fn(),
20}));
21const router = vi.hoisted(() => ({
22 navigate: vi.fn(async () => {}),
23 state: { location: { href: "/" }, matches: [{ params: {} as Record<string, string> }] },
24}));
25vi.mock("../state/use-atom-query-runner", () => ({ useAtomQueryRunner: () => vi.fn() }));
26vi.mock("../state/session", async (original) => ({
27 ...(await original<typeof import("../state/session")>()),
28 readEnvironmentScope: () => true,
29}));
30vi.mock("react", async (original) => ({
31 ...(await original<typeof import("react")>()),
32 useCallback: (callback: unknown) => callback,
33 useMemo: (create: () => unknown) => create(),
34 useRef: (value: unknown) => ({ current: value }),
35}));
36vi.mock("@tanstack/react-router", () => ({ useRouter: () => router }));
37vi.mock("./useSettings", () => ({ useClientSettings: () => false }));
38vi.mock("./useHandleNewThread", () => ({
39 useNewThreadHandler: () => async () => {
40 router.state.location.href = "/draft/project";
41 },
42}));
43vi.mock("../composerDraftStore", () => ({ useComposerDraftStore: () => vi.fn() }));
44vi.mock("../lib/composerDraftUploads", () => ({ releaseComposerDraftUploads: vi.fn() }));
45vi.mock("../terminalUiStateStore", () => ({ useTerminalUiStateStore: () => vi.fn() }));
46vi.mock("../uiStateStore", () => ({ useUiStateStore: () => vi.fn() }));
47vi.mock("../lib/archivedThreadsState", () => ({ refreshArchivedThreadsForEnvironment: vi.fn() }));
48const threadShell = vi.hoisted(() => ({
49 title: "Thread",
50 pinOrderKey: "a0",
51 pinnedAt: null as string | null,
52 snoozedUntil: null as string | null,
53 projectId: "project",
54 environmentId: "undo-env",
55 session: null,
56}));
57// Archived rows have no loaded shell, so deleting one takes the unresolved path.
58const shellLoaded = vi.hoisted(() => ({ current: true }));
59vi.mock("../state/entities", async (original) => ({
60 ...(await original<typeof import("../state/entities")>()),
61 readEnvironmentServerConfigLoaded: () => true,
62 readThreadShell: () => (shellLoaded.current ? threadShell : null),
63}));
64vi.mock("../state/use-atom-command", () => ({
65 useAtomCommand: (command: unknown) => {
66 switch (command) {
67 case threadEnvironment.pin:
68 return commands.pin;
69 case threadEnvironment.unpin:
70 return commands.unpin;
71 case threadEnvironment.archive:
72 return commands.archive;
73 case threadEnvironment.unarchive:
74 return commands.unarchive;
75 case threadEnvironment.delete:
76 return commands.delete;
77 case threadEnvironment.settle:
78 return commands.settle;
79 case threadEnvironment.unsettle:
80 return commands.unsettle;
81 case threadEnvironment.snooze:
82 return commands.snooze;
83 case threadEnvironment.unsnooze:
84 return commands.unsnooze;
85 default:
86 return vi.fn();
87 }
88 },
89}));
90
91const target = {
92 environmentId: EnvironmentId.make("undo-env"),
93 threadId: ThreadId.make("thread"),
94};
95function currentUndo() {
96 const notice = useThreadUndoNotice.getState().notice;
97 expect(notice).not.toBeNull();
98 return notice!.undo;
99}
100
101beforeEach(() => {
102 vi.useFakeTimers();
103 for (const command of Object.values(commands)) {
104 command.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
105 }
106 router.navigate.mockClear();
107 router.state.location.href = "/";
108 router.state.matches[0]!.params = {};
109 threadShell.pinnedAt = null;
110 threadShell.snoozedUntil = null;
111 shellLoaded.current = true;
112});
113afterEach(() => {
114 vi.runAllTimers();
115 vi.useRealTimers();
116 vi.restoreAllMocks();
117});
118
119describe("concurrent thread action Undo", () => {
120 it.each([
121 ["settleThread", "settle", "unsettle", "Settled"],
122 ["snoozeThread", "snooze", "unsnooze", "Snoozed"],
123 ["unpinThread", "unpin", "pin", "Unpinned"],
124 ["archiveThread", "archive", "unarchive", "Archived"],
125 ] as const)(
126 "%s retains one undo for concurrent successful requests",
127 async (handler, action, inverse, notice) => {
128 const actions = useThreadActions();
129 const run = () =>
130 handler === "snoozeThread"
131 ? actions.snoozeThread(target, "2099-01-01T09:00:00.000Z")
132 : actions[handler](target);
133 await Promise.all([run(), run()]);
134 expect(commands[action]).toHaveBeenCalledTimes(2);
135 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: notice, count: 1 });
136 await currentUndo()();
137 expect(commands[inverse]).toHaveBeenCalledOnce();
138 },
139 );
140});
141
142describe("unpin Undo", () => {
143 it("restores the original snooze after restoring the pin", async () => {
144 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
145 threadShell.snoozedUntil = "2030-01-01T09:00:00.000Z";
146 await useThreadActions().unpinThread(target);
147 await currentUndo()();
148 expect(commands.pin).toHaveBeenCalledExactlyOnceWith({
149 environmentId: target.environmentId,
150 input: { threadId: target.threadId, orderKey: "a0" },
151 });
152 expect(commands.snooze).toHaveBeenCalledExactlyOnceWith({
153 environmentId: target.environmentId,
154 input: { threadId: target.threadId, snoozedUntil: threadShell.snoozedUntil },
155 });
156 expect(commands.pin.mock.invocationCallOrder[0]).toBeLessThan(
157 commands.snooze.mock.invocationCallOrder[0]!,
158 );
159 });
160
161 it("restores the pin without an already expired snooze", async () => {
162 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
163 threadShell.snoozedUntil = "2000-01-01T09:00:00.000Z";
164 await useThreadActions().unpinThread(target);
165 await currentUndo()();
166 expect(commands.pin).toHaveBeenCalledOnce();
167 expect(commands.snooze).not.toHaveBeenCalled();
168 });
169
170 it("ignores an old notice across hook instances and still restores the latest unpin", async () => {
171 const sidebar = useThreadActions();
172 const header = useThreadActions();
173 await sidebar.unpinThread(target);
174 const staleUndo = currentUndo();
175 await header.pinThread(target, { orderKey: "a1" });
176 await header.unpinThread(target);
177 const latestUndo = currentUndo();
178 await staleUndo();
179 expect(commands.pin).toHaveBeenCalledTimes(1);
180 await latestUndo();
181 expect(commands.pin).toHaveBeenCalledTimes(2);
182 expect(commands.pin).toHaveBeenLastCalledWith({
183 environmentId: target.environmentId,
184 input: { threadId: target.threadId, orderKey: "a0" },
185 });
186 await latestUndo();
187 expect(commands.pin).toHaveBeenCalledTimes(2);
188 });
189});
190
191describe("archive Undo", () => {
192 it("unarchives and returns to the thread when archiving left it", async () => {
193 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
194 router.state.matches[0]!.params = {
195 environmentId: target.environmentId,
196 threadId: target.threadId,
197 };
198 const actions = useThreadActions();
199 await actions.archiveThread(target);
200 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Archived", count: 1 });
201 expect(add).not.toHaveBeenCalled();
202 await currentUndo()();
203 expect(commands.unarchive).toHaveBeenCalledExactlyOnceWith({
204 environmentId: target.environmentId,
205 input: { threadId: target.threadId },
206 });
207 expect(router.navigate).toHaveBeenCalledWith(
208 expect.objectContaining({
209 to: "/$environmentId/$threadId",
210 params: { environmentId: target.environmentId, threadId: target.threadId },
211 }),
212 );
213 });
214});
215
216describe("archive navigation", () => {
217 it.each([
218 { destination: "/undo-env/thread", expected: "/draft/project" },
219 { destination: "/undo-env/other-thread", expected: "/undo-env/other-thread" },
220 { destination: "/settings", expected: "/settings" },
221 ])("ends at $expected after opening $destination while archiving", async (route) => {
222 router.state.location.href = "/undo-env/thread";
223 router.state.matches[0]!.params = {
224 environmentId: target.environmentId,
225 threadId: target.threadId,
226 };
227 let finishArchive!: () => void;
228 commands.archive.mockReturnValue(
229 new Promise((resolve) => {
230 finishArchive = () => resolve({ _tag: "Success", value: undefined });
231 }),
232 );
233 const archived = useThreadActions().archiveThread(target);
234 router.state.location.href = route.destination;
235 finishArchive();
236 expect((await archived)._tag).toBe("Success");
237 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Archived" });
238 expect(router.state.location.href).toBe(route.expected);
239 });
240});
241
242describe("settle and snooze Undo", () => {
243 it("un-settles from the notice and expires the Undo after a manual un-settle", async () => {
244 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
245 const actions = useThreadActions();
246 await actions.settleThread(target);
247 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Settled", count: 1 });
248 expect(add).not.toHaveBeenCalled();
249 const undo = currentUndo();
250 await actions.unsettleThread(target);
251 await undo();
252 expect(commands.unsettle).toHaveBeenCalledOnce();
253 });
254
255 it("re-pins and re-snoozes a thread that settling had cleared", async () => {
256 const snoozedUntil = "2030-01-01T09:00:00.000Z";
257 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
258 threadShell.snoozedUntil = snoozedUntil;
259 const actions = useThreadActions();
260 await actions.settleThread(target);
261 await currentUndo()();
262 expect(commands.unsettle).toHaveBeenCalledOnce();
263 expect(commands.pin).toHaveBeenCalledExactlyOnceWith({
264 environmentId: target.environmentId,
265 input: { threadId: target.threadId, orderKey: "a0" },
266 });
267 expect(commands.snooze).toHaveBeenCalledExactlyOnceWith({
268 environmentId: target.environmentId,
269 input: { threadId: target.threadId, snoozedUntil },
270 });
271 });
272
273 it("stops settle restoration if restoring the pin fails", async () => {
274 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
275 threadShell.snoozedUntil = "2030-01-01T09:00:00.000Z";
276 commands.pin.mockResolvedValue({ _tag: "Failure", cause: Cause.fail(new Error("Pin failed")) });
277 vi.spyOn(toastManager, "add").mockReturnValue("toast");
278 await useThreadActions().settleThread(target);
279 await currentUndo()();
280 expect(commands.unsettle).toHaveBeenCalledOnce();
281 expect(commands.pin).toHaveBeenCalledOnce();
282 expect(commands.snooze).not.toHaveBeenCalled();
283 });
284
285 it("expires an older unpin Undo when the thread is settled", async () => {
286 const actions = useThreadActions();
287 await actions.unpinThread(target);
288 const staleUnpinUndo = currentUndo();
289 await actions.settleThread(target);
290 await staleUnpinUndo();
291 expect(commands.pin).not.toHaveBeenCalled();
292 });
293
294 // regression: #12972 the sidebar undo notice must reverse a snooze
295 it("wakes the thread from the snooze notice", async () => {
296 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
297 const actions = useThreadActions();
298 await actions.snoozeThread(target, "2100-01-01T00:00:00.000Z");
299 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Snoozed", count: 1 });
300 expect(add).not.toHaveBeenCalled();
301 await currentUndo()();
302 expect(commands.unsnooze).toHaveBeenCalledExactlyOnceWith({
303 environmentId: target.environmentId,
304 input: { threadId: target.threadId, reason: "user" },
305 });
306 });
307});
308
309describe("archive and delete Undo expiry", () => {
310 const otherThread = { environmentId: target.environmentId, threadId: ThreadId.make("other") };
311 const otherEnvironment = {
312 environmentId: EnvironmentId.make("other-env"),
313 threadId: target.threadId,
314 };
315 const failure = { _tag: "Failure", cause: Cause.fail(new Error("Request failed")) };
316
317 describe.each(["archiveThread", "deleteThread"] as const)("%s", (lifecycle) => {
318 it.each([
319 ["settleThread", "unsettle"],
320 ["snoozeThread", "unsnooze"],
321 ["unpinThread", "pin"],
322 ] as const)(
323 "expires an earlier %s Undo for that thread only, across hook instances",
324 async (handler, inverse) => {
325 const sidebar = useThreadActions();
326 const header = useThreadActions();
327 for (const ref of [otherThread, otherEnvironment, target]) {
328 await (handler === "snoozeThread"
329 ? sidebar.snoozeThread(ref, "2099-01-01T09:00:00.000Z")
330 : sidebar[handler](ref));
331 }
332 const staleUndo = currentUndo();
333 await header[lifecycle](target);
334 await staleUndo();
335 expect(commands[inverse]).toHaveBeenCalledTimes(2);
336 expect(commands[inverse]).not.toHaveBeenCalledWith(
337 expect.objectContaining({
338 environmentId: target.environmentId,
339 input: expect.objectContaining({ threadId: target.threadId }),
340 }),
341 );
342 },
343 );
344
345 it("keeps the earlier Undo when the request fails", async () => {
346 const actions = useThreadActions();
347 await actions.settleThread(target);
348 commands[lifecycle === "archiveThread" ? "archive" : "delete"].mockResolvedValue(failure);
349 await actions[lifecycle](target);
350 expect(useThreadUndoNotice.getState().notice).toMatchObject({ action: "Settled" });
351 await currentUndo()();
352 expect(commands.unsettle).toHaveBeenCalledOnce();
353 });
354 });
355
356 it.each([true, false])(
357 "expires the Archived Undo when deleting with shell loaded: %s",
358 async (loaded) => {
359 const actions = useThreadActions();
360 await actions.archiveThread(target);
361 const staleUndo = currentUndo();
362 shellLoaded.current = loaded;
363 await actions.deleteThread(target);
364 expect(useThreadUndoNotice.getState().notice).toBeNull();
365 await staleUndo();
366 expect(commands.unarchive).not.toHaveBeenCalled();
367 },
368 );
369});