import { act, createElement } from "react"; import { createRoot } from "react-dom/client"; import { SWRConfig } from "swr"; import { expect, it, vi } from "vitest"; import type { AgentApiClient, AgentSessionPage } from "@/features/agent"; import { useAgentHistory } from "./use-agent-history"; import { WorkbenchSessionProvider } from "./workbench-session-provider"; it("keeps a late history refresh in its original project cache", async () => { const clock = vi.spyOn(Date, "now").mockReturnValue(100); const root = createRoot(document.createElement("div")); const page = (id: string): AgentSessionPage => ({ sessions: [{ id, title: id, createdAt: 1, updatedAt: 1, purpose: "ordinary_chat" }], hasMore: false, nextCursor: null }); let finish!: (page: AgentSessionPage) => void; const first = vi.fn().mockResolvedValueOnce(page("project-a-original")).mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; })); const second = vi.fn(async () => page("project-b-only")); const clients = { a: { listSessionPage: first }, b: { listSessionPage: second } } as unknown as Record<"a" | "b", AgentApiClient>; let history!: ReturnType; function Probe({ scope }: { scope: "a" | "b" }) { history = useAgentHistory(clients[scope], scope); return null; } const swrCache = new Map(); const render = (scope: "a" | "b") => root.render(createElement(WorkbenchSessionProvider, null, createElement(SWRConfig, { value: { provider: () => swrCache, dedupingInterval: 0 } }, createElement(Probe, { scope })))); try { await act(async () => render("a")); expect(history.recentSessions[0]?.id).toBe("project-a-original"); clock.mockReturnValue(61_000); let pending!: Promise; await act(async () => { pending = history.ensure(); }); await act(async () => render("b")); await act(async () => { finish(page("project-a-late-result")); await pending; }); expect(history.sessions.map((session) => session.id)).toEqual(["project-b-only"]); expect(second).toHaveBeenCalledTimes(1); } finally { await act(async () => root.unmount()); clock.mockRestore(); } });