Files
pi2d/web/tests/prompt-history.test.ts
T
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

231 lines
8.3 KiB
TypeScript

import { beforeEach, describe, expect, it } from "vitest";
import {
appendEntry,
clearPromptHistory,
DEFAULT_SCOPE,
HISTORY_LIMIT,
historyScope,
localPromptHistorySource,
PROMPT_HISTORY_KEY,
PromptHistoryNav,
readPromptHistory,
relayedPromptHistorySource,
rememberPrompt,
WORKSPACE_LIMIT,
} from "@/features/chat/prompt-history";
/** Seed one workspace without going through the composer. */
function seed(scope: string, ...entries: string[]): void {
for (const entry of entries) rememberPrompt(scope, entry);
}
function writeRaw(value: string): void {
localStorage.setItem(PROMPT_HISTORY_KEY, value);
}
beforeEach(() => {
localStorage.clear();
});
describe("prompt history: store", () => {
it("starts empty", () => {
expect(readPromptHistory("w1")).toEqual([]);
});
it("stores entries newest-last", () => {
seed("w1", "one", "two");
expect(readPromptHistory("w1")).toEqual(["one", "two"]);
});
it("ignores empty and whitespace-only entries", () => {
seed("w1", "", " ", "\n\t ");
expect(readPromptHistory("w1")).toEqual([]);
});
it("dedupes consecutive duplicates but keeps a non-consecutive repeat", () => {
seed("w1", "same", "same", "other", "same");
expect(readPromptHistory("w1")).toEqual(["same", "other", "same"]);
});
it("preserves multi-line entries", () => {
seed("w1", "line1\nline2\nline3");
expect(readPromptHistory("w1")).toEqual(["line1\nline2\nline3"]);
});
it("drops the oldest entry past the cap", () => {
for (let index = 1; index <= HISTORY_LIMIT + 5; index += 1) rememberPrompt("w1", `e${index}`);
const entries = readPromptHistory("w1");
expect(entries).toHaveLength(HISTORY_LIMIT);
expect(entries[0]).toBe("e6");
expect(entries[entries.length - 1]).toBe(`e${HISTORY_LIMIT + 5}`);
});
it("isolates workspaces", () => {
seed("w1", "from-w1");
expect(readPromptHistory("w2")).toEqual([]);
});
it("drops the least recently used workspace past the cap", () => {
for (let index = 0; index < WORKSPACE_LIMIT; index += 1) seed(`w${index}`, `p${index}`);
// Touch the oldest again: it must survive the next trim, `w1` must not.
seed("w0", "again");
seed("new", "fresh");
expect(readPromptHistory("w0")).toEqual(["p0", "again"]);
expect(readPromptHistory("w1")).toEqual([]);
expect(readPromptHistory("new")).toEqual(["fresh"]);
expect(readPromptHistory("w2")).toEqual(["p2"]);
});
it("clears one workspace only", () => {
seed("w1", "keep");
seed("w2", "drop");
clearPromptHistory("w2");
expect(readPromptHistory("w1")).toEqual(["keep"]);
expect(readPromptHistory("w2")).toEqual([]);
expect(localStorage.getItem(PROMPT_HISTORY_KEY)).toContain("keep");
});
it("removes the key entirely when the last workspace is cleared", () => {
seed("w1", "only");
clearPromptHistory("w1");
expect(localStorage.getItem(PROMPT_HISTORY_KEY)).toBeNull();
});
it("tolerates corrupt storage and foreign shapes", () => {
writeRaw("{ this is not json ]");
expect(readPromptHistory("w1")).toEqual([]);
expect(rememberPrompt("w1", "recovered")).toEqual(["recovered"]);
writeRaw(JSON.stringify({ w1: "not-listed", w2: [1, "kept", null], w3: [] }));
expect(readPromptHistory("w1")).toEqual([]);
expect(readPromptHistory("w2")).toEqual(["kept"]);
expect(readPromptHistory("w3")).toEqual([]);
writeRaw(JSON.stringify(["not", "a", "document"]));
expect(readPromptHistory("w1")).toEqual([]);
});
it("round-trips through the stored document", () => {
seed("w1", "alpha", "multi\nline");
const raw = localStorage.getItem(PROMPT_HISTORY_KEY);
expect(raw).not.toBeNull();
expect(JSON.parse(raw ?? "{}")).toEqual({ w1: ["alpha", "multi\nline"] });
});
});
describe("prompt history: scope", () => {
it("uses the workspace id, else the default bucket", () => {
expect(historyScope("ws-abc")).toBe("ws-abc");
expect(historyScope(" ws-abc ")).toBe("ws-abc");
expect(historyScope("")).toBe(DEFAULT_SCOPE);
expect(historyScope(null)).toBe(DEFAULT_SCOPE);
expect(historyScope(undefined)).toBe(DEFAULT_SCOPE);
});
});
describe("prompt history: navigation", () => {
/** Cursor over the browser mirror — the fallback source. */
function localNav(scope = "w1"): PromptHistoryNav {
return new PromptHistoryNav(localPromptHistorySource(scope));
}
it("returns null on an empty store", () => {
const nav = localNav();
expect(nav.prev("draft")).toBeNull();
expect(nav.navigating()).toBe(false);
});
it("walks toward older entries and stashes the draft", () => {
seed("w1", "one", "two", "three");
const nav = localNav();
expect(nav.prev("draft")).toBe("three");
expect(nav.navigating()).toBe(true);
expect(nav.prev()).toBe("two");
expect(nav.prev()).toBe("one");
// At the oldest entry: no further change, still browsing.
expect(nav.prev()).toBeNull();
expect(nav.navigating()).toBe(true);
});
it("walks back and restores the stashed draft at the present", () => {
seed("w1", "one", "two");
const nav = localNav();
expect(nav.prev("my draft")).toBe("two");
expect(nav.prev()).toBe("one");
expect(nav.next()).toBe("two");
// Past the newest entry: the draft comes back and recall ends.
expect(nav.next()).toBe("my draft");
expect(nav.navigating()).toBe(false);
});
it("is a no-op when not navigating", () => {
seed("w1", "one");
expect(localNav().next()).toBeNull();
});
it("starts from the newest entry again after a reset", () => {
seed("w1", "one");
const nav = localNav();
nav.prev("draft");
nav.reset();
expect(nav.navigating()).toBe(false);
expect(nav.prev("x")).toBe("one");
});
it("keeps one cursor per composer over a shared store", () => {
seed("w1", "one", "two");
const a = localNav();
const b = localNav();
expect(a.prev("draft-a")).toBe("two");
expect(a.prev()).toBe("one");
expect(b.navigating()).toBe(false);
expect(b.prev("draft-b")).toBe("two");
expect(a.prev()).toBeNull();
expect(b.next()).toBe("draft-b");
});
it("sees entries added to the store by another composer", () => {
seed("w1", "one");
const nav = localNav();
rememberPrompt("w1", "two");
expect(nav.prev("draft")).toBe("two");
expect(nav.prev()).toBe("one");
});
it("navigates a relayed source and re-reads it on every step", () => {
let entries: string[] = ["one"];
const nav = new PromptHistoryNav(relayedPromptHistorySource(() => entries, () => {}));
expect(nav.prev("draft")).toBe("one");
// An entry recorded elsewhere (nvim, another device) becomes reachable
// without rebuilding the cursor: the source is read on every step.
entries = ["one", "two"];
expect(nav.next()).toBe("two");
expect(nav.next()).toBe("draft");
expect(nav.navigating()).toBe(false);
});
});
describe("prompt history: readline rules", () => {
it("appends, skips a repeated newest entry, and keeps a non-consecutive repeat", () => {
expect(appendEntry([], "a")).toEqual(["a"]);
expect(appendEntry(["a"], "a")).toEqual(["a"]);
expect(appendEntry(["a"], "b")).toEqual(["a", "b"]);
expect(appendEntry(["a", "b"], "a")).toEqual(["a", "b", "a"]);
});
it("ignores blank input and preserves multi-line prompts", () => {
expect(appendEntry(["a"], " ")).toEqual(["a"]);
expect(appendEntry([], "l1\nl2")).toEqual(["l1\nl2"]);
});
it("caps the list at the newest history limit", () => {
let entries: string[] = [];
for (let index = 1; index <= HISTORY_LIMIT + 3; index += 1) entries = appendEntry(entries, `e${index}`);
expect(entries).toHaveLength(HISTORY_LIMIT);
expect(entries[0]).toBe("e4");
expect(entries[entries.length - 1]).toBe(`e${HISTORY_LIMIT + 3}`);
});
});