Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useThreadActions.undo.test.ts

233 lines8.9 KB

1import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3​
4import { useThreadActions } from "./useThreadActions";
5import { threadEnvironment } from "../state/threads";
6import { toastManager } from "../components/ui/toast";
7​
8const commands = vi.hoisted(() => ({
9 pin: vi.fn(),
10 unpin: vi.fn(),
11 archive: vi.fn(),
12 unarchive: vi.fn(),
13 settle: vi.fn(),
14 unsettle: vi.fn(),
15 snooze: vi.fn(),
16 unsnooze: vi.fn(),
17}));
18const router = vi.hoisted(() => ({
19 navigate: vi.fn(async () => {}),
20 state: { matches: [{ params: {} as Record<string, string> }] },
21}));
22vi.mock("react", async (original) => ({
23 ...(await original<typeof import("react")>()),
24 useCallback: (callback: unknown) => callback,
25 useMemo: (create: () => unknown) => create(),
26 useRef: (value: unknown) => ({ current: value }),
27}));
28vi.mock("@tanstack/react-router", () => ({ useRouter: () => router }));
29vi.mock("./useSettings", () => ({ useClientSettings: () => false }));
30vi.mock("./useHandleNewThread", () => ({ useNewThreadHandler: () => vi.fn() }));
31vi.mock("../composerDraftStore", () => ({ useComposerDraftStore: () => vi.fn() }));
32vi.mock("../terminalUiStateStore", () => ({ useTerminalUiStateStore: () => vi.fn() }));
33vi.mock("../uiStateStore", () => ({ useUiStateStore: () => vi.fn() }));
34vi.mock("../lib/archivedThreadsState", () => ({ refreshArchivedThreadsForEnvironment: vi.fn() }));
35const threadShell = vi.hoisted(() => ({
36 title: "Thread",
37 pinOrderKey: "a0",
38 pinnedAt: null as string | null,
39 snoozedUntil: null as string | null,
40 projectId: "project",
41 environmentId: "undo-env",
42 session: null,
43}));
44vi.mock("../state/entities", async (original) => ({
45 ...(await original<typeof import("../state/entities")>()),
46 readEnvironmentSupportsPinning: () => true,
47 readEnvironmentSupportsPinReorder: () => true,
48 readEnvironmentSupportsSettlement: () => true,
49 readEnvironmentSupportsSnooze: () => true,
50 readThreadShell: () => threadShell,
51}));
52vi.mock("../state/use-atom-command", () => ({
53 useAtomCommand: (command: unknown) => {
54 switch (command) {
55 case threadEnvironment.pin:
56 return commands.pin;
57 case threadEnvironment.unpin:
58 return commands.unpin;
59 case threadEnvironment.archive:
60 return commands.archive;
61 case threadEnvironment.unarchive:
62 return commands.unarchive;
63 case threadEnvironment.settle:
64 return commands.settle;
65 case threadEnvironment.unsettle:
66 return commands.unsettle;
67 case threadEnvironment.snooze:
68 return commands.snooze;
69 case threadEnvironment.unsnooze:
70 return commands.unsnooze;
71 default:
72 return vi.fn();
73 }
74 },
75}));
76​
77const target = {
78 environmentId: EnvironmentId.make("undo-env"),
79 threadId: ThreadId.make("thread"),
80};
81const event = {} as Parameters<NonNullable<React.ComponentProps<"button">["onClick"]>>[0];
82​
83function undoOf(
84 add: { mock: { calls: Array<[Parameters<typeof toastManager.add>[0]]> } },
85 index: number,
86) {
87 const onClick = add.mock.calls[index]?.[0].actionProps?.onClick;
88 expect(onClick).toBeTypeOf("function");
89 return () => onClick?.(event);
91​
92beforeEach(() => {
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(() => vi.restoreAllMocks());
102​
103describe("unpin Undo", () => {
104 it("ignores an old toast across hook instances and still restores the latest unpin", async () => {
105 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
106 vi.spyOn(toastManager, "close").mockImplementation(() => {});
107 const sidebar = useThreadActions();
108 const header = useThreadActions();
109 await sidebar.unpinThread(target);
110 const staleUndo = undoOf(add, 0);
111 await header.pinThread(target, { orderKey: "a1" });
112 await header.unpinThread(target);
113 const latestUndo = undoOf(add, 1);
114 await staleUndo();
115 expect(commands.pin).toHaveBeenCalledTimes(1);
116 await latestUndo();
117 expect(commands.pin).toHaveBeenCalledTimes(2);
118 expect(commands.pin).toHaveBeenLastCalledWith({
119 environmentId: target.environmentId,
120 input: { threadId: target.threadId, orderKey: "a0" },
121 });
122 await latestUndo();
123 expect(commands.pin).toHaveBeenCalledTimes(2);
124 });
125});
126​
127describe("archive Undo", () => {
128 it("unarchives and returns to the thread when archiving left it", async () => {
129 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
130 vi.spyOn(toastManager, "close").mockImplementation(() => {});
131 router.state.matches[0]!.params = {
132 environmentId: target.environmentId,
133 threadId: target.threadId,
134 };
135 const actions = useThreadActions();
136 await actions.archiveThread(target);
137 expect(add).toHaveBeenCalledWith(expect.objectContaining({ title: "Thread archived" }));
138 await undoOf(add, 0)();
139 expect(commands.unarchive).toHaveBeenCalledExactlyOnceWith({
140 environmentId: target.environmentId,
141 input: { threadId: target.threadId },
142 });
143 expect(router.navigate).toHaveBeenCalledWith(
144 expect.objectContaining({
145 to: "/$environmentId/$threadId",
146 params: { environmentId: target.environmentId, threadId: target.threadId },
147 }),
148 );
149 });
150​
151 it("stays put when the archived thread was not open", async () => {
152 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
153 vi.spyOn(toastManager, "close").mockImplementation(() => {});
154 const actions = useThreadActions();
155 await actions.archiveThread(target);
156 await undoOf(add, 0)();
157 expect(commands.unarchive).toHaveBeenCalledOnce();
158 expect(router.navigate).not.toHaveBeenCalled();
159 });
160​
161 it("shows no Undo when the archive failed", async () => {
162 commands.archive.mockResolvedValue({ _tag: "Failure", cause: new Error("nope") });
163 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
164 await useThreadActions().archiveThread(target);
165 expect(add).not.toHaveBeenCalled();
166 });
167});
168​
169describe("settle and snooze Undo", () => {
170 it("un-settles from the toast and expires the Undo after a manual un-settle", async () => {
171 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
172 vi.spyOn(toastManager, "close").mockImplementation(() => {});
173 const actions = useThreadActions();
174 await actions.settleThread(target);
175 expect(add).toHaveBeenCalledWith(expect.objectContaining({ title: "Thread settled" }));
176 const undo = undoOf(add, 0);
177 await actions.unsettleThread(target);
178 await undo();
179 expect(commands.unsettle).toHaveBeenCalledOnce();
180 });
181​
182 it("re-pins and re-snoozes a thread that settling had cleared", async () => {
183 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
184 vi.spyOn(toastManager, "close").mockImplementation(() => {});
185 const snoozedUntil = "2030-01-01T09:00:00.000Z";
186 threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";
187 threadShell.snoozedUntil = snoozedUntil;
188 const actions = useThreadActions();
189 await actions.settleThread(target);
190 await undoOf(add, 0)();
191 expect(commands.unsettle).toHaveBeenCalledOnce();
192 expect(commands.pin).toHaveBeenCalledExactlyOnceWith({
193 environmentId: target.environmentId,
194 input: { threadId: target.threadId, orderKey: "a0" },
195 });
196 expect(commands.snooze).toHaveBeenCalledExactlyOnceWith({
197 environmentId: target.environmentId,
198 input: { threadId: target.threadId, snoozedUntil },
199 });
200 });
201​
202 it("expires an older unpin Undo when the thread is settled", async () => {
203 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
204 vi.spyOn(toastManager, "close").mockImplementation(() => {});
205 const actions = useThreadActions();
206 await actions.unpinThread(target);
207 const staleUnpinUndo = undoOf(add, 0);
208 await actions.settleThread(target);
209 await staleUnpinUndo();
210 expect(commands.pin).not.toHaveBeenCalled();
211 });
212​
213 it("stays silent for batch settles", async () => {
214 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
215 await useThreadActions().settleThread(target, { undoToast: false });
216 expect(add).not.toHaveBeenCalled();
217 });
218​
219 it("wakes the thread from the snooze toast", async () => {
220 const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");
221 vi.spyOn(toastManager, "close").mockImplementation(() => {});
222 const actions = useThreadActions();
223 await actions.snoozeThread(target, new Date(Date.now() + 60_000).toISOString());
224 expect(add).toHaveBeenCalledWith(
225 expect.objectContaining({ title: expect.stringMatching(/^Snoozed until /) }),
226 );
227 await undoOf(add, 0)();
228 expect(commands.unsnooze).toHaveBeenCalledExactlyOnceWith({
229 environmentId: target.environmentId,
230 input: { threadId: target.threadId, reason: "user" },
231 });
232 });
233});