Files
pi2d/web/tests/chat.prompt-history-feed.test.tsx
yuez b8f1fca5bd feat(web): recall prompt history from the plugin with a browser fallback
The composer's ↑/↓ history is the web port of pi2.nvim's prompt buffer, so it
has to walk the archive nvim walks — not a copy of it. Three tiers: the plugin
owns the text, the daemon relays one live-only read, the browser keeps a mirror.

- `features/chat/prompt-history.ts`: the readline rules (`appendEntry`: blank
  ignored, consecutive dedupe, newest 500), the `localStorage` mirror
  (`pi2-prompt-history`, per workspace, 40 workspaces LRU), the
  `PromptHistorySource` seam, and `PromptHistoryNav` — the per-composer cursor
  with a stashed draft, independent positions, and a reset on edit/send
- `features/chat/prompt-history-feed.ts`: `usePromptHistory(workspaceId)` reads
  `GET /workspaces/:id/prompt-history`, appends a send optimistically, refreshes
  the mirror from every successful read, and falls back to the mirror whenever
  the relay cannot answer (no plugin, no capability, a 404 from an older daemon,
  an offline browser). One workspace-scoped read per page, never per keystroke.
- composer: ↑ recalls from the first line, ↓ from the last line or while
  browsing, `<C-p>`/`<C-n>` always recall; an IME composition and a text
  selection keep their keys; the caret lands at the end of a recalled prompt and
  a manual edit ends recall
- fixes a mirror bug found while testing it: a full list that accepts one more
  entry and drops the oldest has the same length, so the old "unchanged" check
  silently stopped recording after 500 prompts
- `docs/prompt-history.md` records the tiers, the key map, the storage contract
  and what is deliberately not shared yet (cross-host, history without nvim);
  the UI mock server answers the new endpoint so the visual harness stays honest

Version skew is boring by design: an old daemon (404) or an old plugin (no
capability) keeps recall working from the mirror.
2026-11-02 11:12:41 +08:00

170 lines
6.7 KiB
TypeScript

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { act, render, waitFor } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import {
normalizeEntries,
type PromptHistoryFeed,
PROMPT_HISTORY_FETCH_LIMIT,
usePromptHistory,
} from "@/features/chat/prompt-history-feed";
import { readPromptHistory, rememberPrompt } from "@/features/chat/prompt-history";
import { mockApi } from "./helpers/api-mock";
const PATH = "/api/v1/workspaces/w1/prompt-history";
/**
* Mount the hook and keep the newest snapshot. The feed is a plain object, so the
* tests assert on it directly instead of through rendered markup (the composer is
* the only consumer that renders anything).
*/
function renderFeed(workspaceId: string | undefined, enabled = true) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: 0, refetchOnWindowFocus: false } },
});
const feeds: PromptHistoryFeed[] = [];
function Probe() {
feeds.push(usePromptHistory(workspaceId, enabled));
return <div data-testid="feed" />;
}
const utils = render(
<QueryClientProvider client={queryClient}>
<Probe />
</QueryClientProvider>,
);
const feed = (): PromptHistoryFeed => {
const current = feeds[feeds.length - 1];
if (!current) throw new Error("the probe never rendered");
return current;
};
return { ...utils, queryClient, feed };
}
const remote = (body: Record<string, unknown>) => [{ method: "GET" as const, path: PATH, handler: () => ({ body }) }];
describe("prompt history feed: relayed from the plugin", () => {
it("recalls the plugin's entries when it is live and capable", async () => {
const fetchMock = mockApi(
remote({
v: 1,
workspaceId: "w1",
live: true,
supported: true,
entries: ["oldest", "middle", "newest"],
}),
);
const { feed } = renderFeed("w1");
await waitFor(() => expect(feed().remote).toBe(true));
expect(feed().live).toBe(true);
expect(feed().source.entries()).toEqual(["oldest", "middle", "newest"]);
// One cheap workspace-scoped read, no per-keystroke traffic.
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(String((fetchMock.mock.calls[0]?.[0] as RequestInfo))).toContain(
`limit=${PROMPT_HISTORY_FETCH_LIMIT}`,
);
});
it("records a send into the mirror and appends it optimistically", async () => {
mockApi(
remote({ v: 1, workspaceId: "w1", live: true, supported: true, entries: ["first"] }),
);
const { feed } = renderFeed("w1");
await waitFor(() => expect(feed().remote).toBe(true));
act(() => feed().source.remember("second"));
// Recall sees it without waiting for a refetch…
await waitFor(() => expect(feed().source.entries()).toEqual(["first", "second"]));
// …and the fallback mirror is warm for the moment the plugin goes away.
expect(readPromptHistory("w1")).toEqual(["first", "second"]);
});
it("drops unusable entries from the relay payload", async () => {
mockApi(
remote({
live: true,
supported: true,
entries: ["keep", 7, null, " ", "also keep"],
}),
);
const { feed } = renderFeed("w1");
await waitFor(() => expect(feed().remote).toBe(true));
expect(feed().source.entries()).toEqual(["keep", "also keep"]);
});
it("refreshes the fallback mirror from the relay", async () => {
mockApi(
remote({ v: 1, workspaceId: "w1", live: true, supported: true, entries: ["typed in nvim"] }),
);
const { feed } = renderFeed("w1");
await waitFor(() => expect(feed().remote).toBe(true));
// The plugin's history is now the fallback's starting point, so a lost
// plugin (or an older daemon) still recalls what nvim recorded.
await waitFor(() => expect(readPromptHistory("w1")).toEqual(["typed in nvim"]));
});
});
describe("prompt history feed: browser mirror fallback", () => {
it("falls back when no plugin is connected for the workspace", async () => {
rememberPrompt("w1", "from this browser");
mockApi(remote({ v: 1, workspaceId: "w1", live: false, supported: false, entries: [] }));
const { feed } = renderFeed("w1");
await waitFor(() => expect(feed().live).toBe(false));
expect(feed().remote).toBe(false);
expect(feed().source.entries()).toEqual(["from this browser"]);
});
it("falls back when the live plugin is older than the capability", async () => {
rememberPrompt("w1", "mirror only");
mockApi(remote({ v: 1, workspaceId: "w1", live: true, supported: false, entries: [] }));
const { feed } = renderFeed("w1");
await waitFor(() => expect(feed().live).toBe(true));
expect(feed().remote).toBe(false);
expect(feed().source.entries()).toEqual(["mirror only"]);
});
it("falls back when the daemon predates the endpoint (404), without retrying", async () => {
rememberPrompt("w1", "mirror only");
const fetchMock = mockApi([
{ method: "GET", path: PATH, handler: () => ({ status: 404, body: { code: "E_NOT_FOUND" } }) },
]);
const { feed } = renderFeed("w1");
await waitFor(() => expect(fetchMock).toHaveBeenCalled());
// A 404 is a permanent "no relay", not a transient failure: one attempt.
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(feed().remote).toBe(false);
expect(feed().source.entries()).toEqual(["mirror only"]);
});
it("keeps working unpaired: no fetch, mirror only", () => {
const fetchMock = mockApi([]);
rememberPrompt("default", "offline draft");
const { feed } = renderFeed("", false);
expect(fetchMock).not.toHaveBeenCalled();
expect(feed().remote).toBe(false);
expect(feed().source.entries()).toEqual(["offline draft"]);
});
});
describe("normalizeEntries", () => {
it("keeps only non-blank strings", () => {
expect(normalizeEntries(undefined)).toEqual([]);
expect(normalizeEntries("nope")).toEqual([]);
expect(normalizeEntries(["a", 1, null, " ", "b"])).toEqual(["a", "b"]);
});
it("keeps the newest entries when the payload is long", () => {
const many = Array.from({ length: 600 }, (_, index) => `e${index}`);
const entries = normalizeEntries(many);
expect(entries).toHaveLength(500);
expect(entries[entries.length - 1]).toBe("e599");
});
});