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.
This commit is contained in:
1 parent
32292873f9
commit
b8f1fca5bd
11 files changed
+1324
-6
No files matched your search
@@ -2,6 +2,7 @@ import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { Composer, type ComposerProps } from "@/features/chat/composer";
|
||||
import { readPromptHistory, rememberPrompt } from "@/features/chat/prompt-history";
|
||||
import { setLanguage } from "@/lib/i18n";
|
||||
import { sessionFixture } from "./chat-fixtures";
|
||||
|
||||
@@ -215,3 +216,196 @@ describe("composer", () => {
|
||||
expect(screen.queryByText(/prototype demo only/i)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Prompt recall (↑/↓), the web port of pi2.nvim's prompt-buffer history. The
|
||||
* store/nav contract itself is covered in `prompt-history.test.ts`; here we
|
||||
* only pin the keyboard rules the composer adds on top of it.
|
||||
*/
|
||||
describe("composer prompt history", () => {
|
||||
/** Place a collapsed caret, so the ArrowUp/ArrowDown line rule is explicit. */
|
||||
function caretAt(element: HTMLTextAreaElement, at: number): void {
|
||||
element.setSelectionRange(at, at);
|
||||
}
|
||||
|
||||
function input(): HTMLTextAreaElement {
|
||||
return screen.getByTestId("composer-input") as HTMLTextAreaElement;
|
||||
}
|
||||
|
||||
it("recalls older prompts on ArrowUp and the draft past the newest", () => {
|
||||
rememberPrompt("w1", "first");
|
||||
rememberPrompt("w1", "second");
|
||||
renderComposer(sessionFixture({ status: "idle" }));
|
||||
const textarea = input();
|
||||
|
||||
fireEvent.change(textarea, { target: { value: "my draft" } });
|
||||
caretAt(textarea, 0);
|
||||
|
||||
// A recall swallows the key (the caret must not also move).
|
||||
expect(fireEvent.keyDown(textarea, { key: "ArrowUp" })).toBe(false);
|
||||
expect(textarea).toHaveValue("second");
|
||||
expect(fireEvent.keyDown(textarea, { key: "ArrowUp" })).toBe(false);
|
||||
expect(textarea).toHaveValue("first");
|
||||
// At the oldest entry the key is left to the caret again.
|
||||
expect(fireEvent.keyDown(textarea, { key: "ArrowUp" })).toBe(true);
|
||||
expect(textarea).toHaveValue("first");
|
||||
|
||||
fireEvent.keyDown(textarea, { key: "ArrowDown" });
|
||||
expect(textarea).toHaveValue("second");
|
||||
// Past the newest entry the in-progress draft is restored.
|
||||
fireEvent.keyDown(textarea, { key: "ArrowDown" });
|
||||
expect(textarea).toHaveValue("my draft");
|
||||
// Recall is over: ↓ is a plain caret move again.
|
||||
expect(fireEvent.keyDown(textarea, { key: "ArrowDown" })).toBe(true);
|
||||
expect(textarea).toHaveValue("my draft");
|
||||
});
|
||||
|
||||
it("leaves ArrowUp to the caret inside a multi-line draft", () => {
|
||||
rememberPrompt("w1", "old prompt");
|
||||
renderComposer(sessionFixture({ status: "idle" }));
|
||||
const textarea = input();
|
||||
const draft = "line1\nline2";
|
||||
|
||||
fireEvent.change(textarea, { target: { value: draft } });
|
||||
// Caret on the second line: ↑ must move the caret, not recall.
|
||||
caretAt(textarea, draft.length);
|
||||
expect(fireEvent.keyDown(textarea, { key: "ArrowUp" })).toBe(true);
|
||||
expect(textarea).toHaveValue(draft);
|
||||
|
||||
// Caret on the first line: ↑ recalls.
|
||||
caretAt(textarea, 0);
|
||||
expect(fireEvent.keyDown(textarea, { key: "ArrowUp" })).toBe(false);
|
||||
expect(textarea).toHaveValue("old prompt");
|
||||
});
|
||||
|
||||
it("leaves ArrowDown to the caret above the last line", () => {
|
||||
rememberPrompt("w1", "archived");
|
||||
renderComposer(sessionFixture({ status: "idle" }));
|
||||
const textarea = input();
|
||||
const draft = "draft\ntail";
|
||||
|
||||
fireEvent.change(textarea, { target: { value: draft } });
|
||||
caretAt(textarea, 2); // still on the first line
|
||||
expect(fireEvent.keyDown(textarea, { key: "ArrowDown" })).toBe(true);
|
||||
expect(textarea).toHaveValue(draft);
|
||||
});
|
||||
|
||||
it("walks back out of a recalled multi-line entry from its last line", () => {
|
||||
rememberPrompt("w1", "line1\nline2");
|
||||
renderComposer(sessionFixture({ status: "idle" }));
|
||||
const textarea = input();
|
||||
|
||||
fireEvent.change(textarea, { target: { value: "draft" } });
|
||||
caretAt(textarea, 0);
|
||||
expect(fireEvent.keyDown(textarea, { key: "ArrowUp" })).toBe(false);
|
||||
expect(textarea).toHaveValue("line1\nline2");
|
||||
// The caret is parked on the entry's last line, so ↓ leaves recall.
|
||||
expect(fireEvent.keyDown(textarea, { key: "ArrowDown" })).toBe(false);
|
||||
expect(textarea).toHaveValue("draft");
|
||||
});
|
||||
|
||||
it("always recalls on Ctrl+P / Ctrl+N", () => {
|
||||
rememberPrompt("w1", "alpha");
|
||||
rememberPrompt("w1", "beta");
|
||||
renderComposer(sessionFixture({ status: "idle" }));
|
||||
const textarea = input();
|
||||
|
||||
fireEvent.change(textarea, { target: { value: "draft text" } });
|
||||
caretAt(textarea, 3); // mid-line: the caret rule does not apply
|
||||
|
||||
fireEvent.keyDown(textarea, { key: "p", ctrlKey: true });
|
||||
expect(textarea).toHaveValue("beta");
|
||||
fireEvent.keyDown(textarea, { key: "p", ctrlKey: true });
|
||||
expect(textarea).toHaveValue("alpha");
|
||||
fireEvent.keyDown(textarea, { key: "n", ctrlKey: true });
|
||||
expect(textarea).toHaveValue("beta");
|
||||
fireEvent.keyDown(textarea, { key: "n", ctrlKey: true });
|
||||
expect(textarea).toHaveValue("draft text");
|
||||
});
|
||||
|
||||
it("moves the caret to the end of a recalled prompt", () => {
|
||||
rememberPrompt("w1", "remembered prompt");
|
||||
renderComposer(sessionFixture({ status: "idle" }));
|
||||
const textarea = input();
|
||||
|
||||
fireEvent.keyDown(textarea, { key: "ArrowUp" });
|
||||
expect(textarea).toHaveValue("remembered prompt");
|
||||
expect(textarea.selectionStart).toBe("remembered prompt".length);
|
||||
expect(textarea.selectionEnd).toBe("remembered prompt".length);
|
||||
});
|
||||
|
||||
it("ends recall when the user edits by hand", () => {
|
||||
rememberPrompt("w1", "older");
|
||||
rememberPrompt("w1", "newer");
|
||||
renderComposer(sessionFixture({ status: "idle" }));
|
||||
const textarea = input();
|
||||
|
||||
fireEvent.keyDown(textarea, { key: "ArrowUp" });
|
||||
expect(textarea).toHaveValue("newer");
|
||||
fireEvent.change(textarea, { target: { value: "newer, edited" } });
|
||||
caretAt(textarea, "newer, edited".length);
|
||||
|
||||
// No longer browsing: ↓ must not replace the edit with a stale entry.
|
||||
expect(fireEvent.keyDown(textarea, { key: "ArrowDown" })).toBe(true);
|
||||
expect(textarea).toHaveValue("newer, edited");
|
||||
// ↓ again starts from the newest entry, not from where recall stopped.
|
||||
expect(fireEvent.keyDown(textarea, { key: "ArrowUp" })).toBe(false);
|
||||
expect(textarea).toHaveValue("newer");
|
||||
});
|
||||
|
||||
it("remembers each send in its own workspace, trimmed and deduped", () => {
|
||||
const { onSend, unmount } = renderComposer(sessionFixture({ status: "idle" }));
|
||||
const textarea = input();
|
||||
|
||||
fireEvent.change(textarea, { target: { value: " padded " } });
|
||||
fireEvent.keyDown(textarea, { key: "Enter" });
|
||||
expect(onSend).toHaveBeenCalledWith("padded", [], undefined);
|
||||
expect(readPromptHistory("w1")).toEqual(["padded"]);
|
||||
unmount();
|
||||
|
||||
// Another workspace shares no history…
|
||||
const other = renderComposer(sessionFixture({ status: "idle", workspaceId: "w2" }));
|
||||
fireEvent.change(input(), { target: { value: "from w2" } });
|
||||
fireEvent.keyDown(input(), { key: "Enter" });
|
||||
expect(other.onSend).toHaveBeenCalledWith("from w2", [], undefined);
|
||||
expect(readPromptHistory("w2")).toEqual(["from w2"]);
|
||||
expect(readPromptHistory("w1")).toEqual(["padded"]);
|
||||
other.unmount();
|
||||
|
||||
// …and the first one still recalls its own send.
|
||||
renderComposer(sessionFixture({ status: "idle" }));
|
||||
expect(fireEvent.keyDown(input(), { key: "ArrowUp" })).toBe(false);
|
||||
expect(input()).toHaveValue("padded");
|
||||
});
|
||||
|
||||
it("does not let an IME own-up compose recall its candidate list", () => {
|
||||
rememberPrompt("w1", "archived");
|
||||
renderComposer(sessionFixture({ status: "idle" }));
|
||||
const textarea = input();
|
||||
|
||||
fireEvent.change(textarea, { target: { value: "nihao" } });
|
||||
caretAt(textarea, 5);
|
||||
expect(fireEvent.keyDown(textarea, { key: "ArrowUp", isComposing: true })).toBe(true);
|
||||
expect(textarea).toHaveValue("nihao");
|
||||
});
|
||||
|
||||
it("recalls from an injected feed and records sends into it", () => {
|
||||
// `pages/chat.tsx` injects the plugin-backed feed; the composer must neither
|
||||
// read the mirror nor decide where a send is recorded.
|
||||
const entries: string[] = ["typed in nvim"];
|
||||
const remember = vi.fn((text: string) => entries.push(text));
|
||||
const { onSend } = renderComposer(sessionFixture({ status: "idle" }), {
|
||||
history: { entries: () => entries, remember },
|
||||
});
|
||||
const textarea = input();
|
||||
|
||||
expect(fireEvent.keyDown(textarea, { key: "ArrowUp" })).toBe(false);
|
||||
expect(textarea).toHaveValue("typed in nvim");
|
||||
|
||||
fireEvent.keyDown(textarea, { key: "Enter" });
|
||||
expect(onSend).toHaveBeenCalledWith("typed in nvim", [], undefined);
|
||||
expect(remember).toHaveBeenCalledWith("typed in nvim");
|
||||
// The mirror stays untouched: the injected feed owns the archive now.
|
||||
expect(readPromptHistory("w1")).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,169 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,230 @@
|
||||
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}`);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user