Files
pi2d/web/src/features/chat/prompt-history.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

321 lines
12 KiB
TypeScript

/**
* Prompt input history — readline-style recall in the composer (↑ / ↓, `<C-p>` /
* `<C-n>`), scoped per workspace.
*
* This is the web console's port of pi2.nvim's `pi.prompt_history`, split the
* same way so both surfaces behave identically and both halves are unit-testable
* without a DOM.
*
* ## Who owns the text
*
* The **plugin owns the archive**. Every prompt is recorded by pi2.nvim when it
* is sent (`Store:add` inside `Chat:_send_message`), whichever surface sent it,
* and the console reads it back through the daemon's live-only relay
* (`GET /api/v1/workspaces/:id/prompt-history`, `docs/protocol.md` §3.1.1). Two
* consequences worth being explicit about:
*
* * nvim and the browser recall the same prompts, and so does every device paired
* to this daemon — one archive, one order, one dedupe rule;
* * the read never spawns an nvim. A workspace with no live plugin answers
* `supported: false`, and the console falls back to its browser-local mirror.
*
* The **mirror** (this file, `localStorage`) exists for that fallback and for
* version skew: a daemon older than the endpoint 404s, a plugin older than the
* `promptHistory` capability reports `supported: false`, and recall keeps
* working from what this browser recorded. It is written on every send, so it can
* only ever be behind the plugin, never authoritative.
*
* The **cursor** (position + stashed draft) is always this composer's own state
* ({@link PromptHistoryNav}) — no surface shares it, and no server sees it.
*
* ## Scoping
*
* `{ [workspaceId]: string[] }`, oldest entry first. nvim scopes history by the
* workspace cwd; the console's analogue is the workspace id every session
* carries, so a second session in the same workspace recalls the same prompts and
* another workspace starts clean. The mirror keeps the 40 most recently used
* workspaces ({@link WORKSPACE_LIMIT}) so a long-lived profile cannot grow
* without bound.
*
* Entries are mirrored verbatim (multi-line prompts included) and compared
* verbatim; only the blankness check trims. Every mirror read and write tolerates
* a missing, corrupt or unwritable `localStorage` (Safari private mode, quota):
* the feature degrades to "no mirror", never to a broken composer.
*/
/** `localStorage` key holding `{ [workspaceId]: string[] }`. */
export const PROMPT_HISTORY_KEY = "pi2-prompt-history";
/** Entries kept per workspace in the mirror; matches pi2.nvim's `prompt.history.max`. */
export const HISTORY_LIMIT = 500;
/**
* Workspaces kept in the mirror. Recall only ever needs the workspace the user is
* in; this bound exists so the key cannot grow forever. pi2.nvim keeps one file
* per workspace and never prunes; a browser shares a single ~5 MB budget.
*/
export const WORKSPACE_LIMIT = 40;
/** Bucket for a session with no workspace id (a `tmp-*` row before it settles). */
export const DEFAULT_SCOPE = "default";
type Document = Record<string, string[]>;
/**
* Everything recall needs from wherever the entries live. The composer only ever
* talks to this, so the plugin relay and the browser mirror are interchangeable.
*/
export interface PromptHistorySource {
/** Entries to show, oldest first, newest last. Called on every recall step. */
entries(): readonly string[];
/** Record a prompt that was just sent. */
remember(text: string): void;
}
/**
* Which bucket a session's history lives in. Falls back to
* {@link DEFAULT_SCOPE} so a session that has not been bound to a workspace yet
* still recalls *something* instead of silently losing the entry.
*/
export function historyScope(workspaceId: string | null | undefined): string {
const id = typeof workspaceId === "string" ? workspaceId.trim() : "";
return id === "" ? DEFAULT_SCOPE : id;
}
function storage(): Storage | undefined {
try {
return typeof localStorage === "undefined" ? undefined : localStorage;
} catch {
// Accessing `localStorage` can throw (Safari private mode, blocked cookies).
return undefined;
}
}
/** Parse the whole mirror document; anything unusable means "no mirror". */
function readDocument(): Document {
const store = storage();
if (store === undefined) return {};
try {
const raw = store.getItem(PROMPT_HISTORY_KEY);
const parsed: unknown = raw === null ? null : JSON.parse(raw);
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return {};
const out: Document = {};
for (const [scope, value] of Object.entries(parsed as Record<string, unknown>)) {
if (!Array.isArray(value)) continue;
const entries = value.filter((entry): entry is string => typeof entry === "string");
if (entries.length) out[scope] = entries;
}
return out;
} catch {
return {};
}
}
function writeDocument(document: Document): void {
const store = storage();
if (store === undefined) return;
try {
// Object key order is the LRU: `remember` re-inserts the touched scope so
// it moves to the tail, and the oldest scopes are dropped past the cap.
const scopes = Object.keys(document);
const kept =
scopes.length > WORKSPACE_LIMIT ? scopes.slice(scopes.length - WORKSPACE_LIMIT) : scopes;
const trimmed: Document = {};
for (const scope of kept) {
const entries = document[scope];
if (entries !== undefined && entries.length) trimmed[scope] = entries;
}
if (Object.keys(trimmed).length === 0) {
store.removeItem(PROMPT_HISTORY_KEY);
return;
}
store.setItem(PROMPT_HISTORY_KEY, JSON.stringify(trimmed));
} catch {
// Quota or private mode: recall still works for this page's lifetime.
}
}
/** Copy of one workspace's mirrored entries, oldest first. */
export function readPromptHistory(scope: string): string[] {
const entries = readDocument()[scope];
return entries === undefined ? [] : entries.slice();
}
/**
* The readline rules for one incoming entry, shared by the mirror and the
* optimistic update of the remote cache: blank input is ignored, a repeat of the
* newest entry is skipped, the oldest falls off past {@link HISTORY_LIMIT}.
*
* @returns the resulting entries (a new array), oldest first.
*/
export function appendEntry(entries: readonly string[], text: string): string[] {
if (typeof text !== "string" || text.trim() === "") return entries.slice();
if (entries[entries.length - 1] === text) return entries.slice();
const next = [...entries, text];
return next.length > HISTORY_LIMIT ? next.slice(next.length - HISTORY_LIMIT) : next;
}
/**
* Mirror a submitted prompt into `localStorage`. Mirrors pi2.nvim's `Store:add`:
* blank input is ignored, an entry identical to the newest one is skipped
* (readline consecutive dedupe — a non-consecutive repeat *is* kept).
*
* @returns the resulting entries, oldest first.
*/
export function rememberPrompt(scope: string, text: string): string[] {
const document = readDocument();
const current = document[scope] ?? [];
const entries = appendEntry(current, text);
// "Unchanged" must be judged on the content, not the length: a full list that
// accepts one more entry and drops the oldest has the same length (this slipped
// once — the mirror silently stopped recording after 500 prompts).
const unchanged =
entries.length === current.length &&
entries[entries.length - 1] === current[current.length - 1];
if (unchanged) return current.slice();
// Re-insert so this scope becomes the most recently used one.
delete document[scope];
document[scope] = entries;
writeDocument(document);
return entries.slice();
}
/** Drop one workspace's mirrored history. */
export function clearPromptHistory(scope: string): void {
const document = readDocument();
if (!(scope in document)) return;
delete document[scope];
writeDocument(document);
}
/**
* Overwrite one workspace's mirror with a snapshot taken from the plugin.
*
* The mirror is the fallback, and a fallback that only knows about prompts typed
* *in this browser* is a poor one: without this, losing the plugin (or opening a
* daemon that predates the endpoint) would recall nothing even though nvim had
* the history a second ago. So every successful relay read refreshes the mirror,
* and the fallback starts from the last known state instead of empty.
*
* This never makes the mirror authoritative — a supported relay always wins at
* read time — and the LRU bookkeeping is the same as {@link rememberPrompt}.
*/
export function replacePromptHistory(scope: string, entries: readonly string[]): void {
const document = readDocument();
const capped = appendEntryWindow(entries);
if (capped.length === 0) {
clearPromptHistory(scope);
return;
}
delete document[scope];
document[scope] = capped;
writeDocument(document);
}
/** Keep only usable entries, capped to the newest {@link HISTORY_LIMIT}. */
function appendEntryWindow(entries: readonly string[]): string[] {
const usable = entries.filter((entry) => typeof entry === "string" && entry.trim() !== "");
return usable.length > HISTORY_LIMIT ? usable.slice(usable.length - HISTORY_LIMIT) : usable;
}
/** The browser-local mirror as a source (also the fallback when the relay is cold). */
export function localPromptHistorySource(scope: string): PromptHistorySource {
return {
entries: () => readPromptHistory(scope),
remember: (text) => {
rememberPrompt(scope, text);
},
};
}
/**
* A source backed by a caller-owned list (the plugin relay's cached entries) with
* an explicit `remember` hook. The getter is re-read on every recall step, so a
* refetch or an optimistic append is visible without rebuilding the cursor.
*/
export function relayedPromptHistorySource(
entries: () => readonly string[],
remember: (text: string) => void,
): PromptHistorySource {
return { entries, remember };
}
/**
* The transient recall cursor for one composer.
*
* `index` is the position in the archive: `null` means "not browsing" — the
* textarea shows the user's own draft. `prev()` enters browsing and stashes the
* draft; walking back down past the newest entry restores it and leaves browsing.
* A composer that shares a workspace with another (two tabs, two sessions) keeps
* its own cursor: only the archive is shared.
*
* The source is queried on every step, so entries recorded elsewhere (another
* browser, nvim, a refetch that landed mid-browse) are recallable immediately.
*/
export class PromptHistoryNav {
private readonly source: PromptHistorySource;
private index: number | null = null;
private draft = "";
constructor(source: PromptHistorySource) {
this.source = source;
}
/**
* Step toward older entries. The first call stashes `draft` (what the user
* was typing) so the walk back down can restore it.
*
* @returns the entry to show, or `null` when there is nothing older.
*/
prev(draft = ""): string | null {
const entries = this.source.entries();
const size = entries.length;
if (size === 0) return null;
if (this.index === null) {
this.draft = draft;
this.index = size;
return entries[size - 1] ?? null;
}
if (this.index > 1) {
this.index -= 1;
return entries[this.index - 1] ?? null;
}
// Already at the oldest entry: no change.
return null;
}
/**
* Step toward newer entries, then out of browsing (restoring the stashed
* draft) once the newest entry has been passed.
*
* @returns the entry to show, or `null` when not browsing.
*/
next(): string | null {
if (this.index === null) return null;
const entries = this.source.entries();
const size = entries.length;
if (this.index < size) {
this.index += 1;
return entries[this.index - 1] ?? null;
}
const draft = this.draft;
this.reset();
return draft;
}
/** Whether the composer is currently showing an entry from the archive. */
navigating(): boolean {
return this.index !== null;
}
/**
* Leave browsing. Called after a send and whenever the user edits the text
* by hand — otherwise a later ↓ would overwrite their typing with a stale
* entry.
*/
reset(): void {
this.index = null;
this.draft = "";
}
}