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
@@ -1,5 +1,5 @@
|
||||
import type { ModelRef, SessionState, ThinkingLevel } from "@protocol/types";
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Icon } from "@/components/icons";
|
||||
@@ -13,6 +13,7 @@ import { promptImage, type PromptImage, type PromptMode } from "./commands";
|
||||
import type { ModelGroup } from "./data";
|
||||
import { withCurrentModel } from "./data";
|
||||
import { THINKING_LEVELS } from "./format";
|
||||
import { historyScope, localPromptHistorySource, PromptHistoryNav, type PromptHistorySource } from "./prompt-history";
|
||||
import type { Attachment } from "./store";
|
||||
|
||||
export interface ComposerProps {
|
||||
@@ -42,6 +43,13 @@ export interface ComposerProps {
|
||||
queuedCount?: number;
|
||||
onSetModel: (model: ModelRef) => void;
|
||||
onSetThinking: (level: ThinkingLevel) => void;
|
||||
/**
|
||||
* Where ↑/↓ recall reads from and where a send is recorded. `pages/chat.tsx`
|
||||
* passes the plugin-backed feed (`usePromptHistory`) so nvim and the browser
|
||||
* share one archive; without it the composer falls back to the browser-local
|
||||
* mirror for this session's workspace.
|
||||
*/
|
||||
history?: PromptHistorySource;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
}
|
||||
@@ -67,6 +75,7 @@ export function Composer({
|
||||
queuedCount,
|
||||
onSetModel,
|
||||
onSetThinking,
|
||||
history,
|
||||
disabled = false,
|
||||
className,
|
||||
}: ComposerProps) {
|
||||
@@ -78,6 +87,21 @@ export function Composer({
|
||||
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
|
||||
const fileRef = useRef<HTMLInputElement | null>(null);
|
||||
|
||||
/**
|
||||
* Prompt recall (↑/↓) — see `prompt-history.ts`. The entries come from the
|
||||
* injected feed (the plugin relay, or the browser mirror as fallback); the
|
||||
* cursor is this composer's own, and is rebuilt when the source changes so a
|
||||
* session switch or a lost plugin never carries a stranger's position over.
|
||||
*/
|
||||
const fallbackSource = useMemo(
|
||||
() => localPromptHistorySource(historyScope(session?.workspaceId)),
|
||||
[session?.workspaceId],
|
||||
);
|
||||
const source = history ?? fallbackSource;
|
||||
const navRef = useRef<{ source: PromptHistorySource; nav: PromptHistoryNav } | null>(null);
|
||||
/** Set by a recall so the layout effect can park the caret after the entry. */
|
||||
const caretToEnd = useRef(false);
|
||||
|
||||
const enabled = Boolean(session) && connected && !disabled;
|
||||
const busy = session ? session.status === "busy" || session.status === "compacting" : false;
|
||||
const queue = session?.queue ?? [];
|
||||
@@ -104,6 +128,13 @@ export function Composer({
|
||||
const max = 5 * 24;
|
||||
element.style.height = `${Math.min(element.scrollHeight, max)}px`;
|
||||
element.style.overflowY = element.scrollHeight > max ? "auto" : "hidden";
|
||||
if (caretToEnd.current) {
|
||||
// A recall replaced the whole value: keep typing after the entry
|
||||
// instead of wherever the caret happened to be in the old draft.
|
||||
caretToEnd.current = false;
|
||||
const end = element.value.length;
|
||||
element.setSelectionRange(end, end);
|
||||
}
|
||||
}, [text]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -111,12 +142,81 @@ export function Composer({
|
||||
textareaRef.current?.focus({ preventScroll: true });
|
||||
}, [enabled]);
|
||||
|
||||
/** This composer's recall cursor, rebuilt when the source changes identity. */
|
||||
function historyNav(): PromptHistoryNav {
|
||||
if (navRef.current === null || navRef.current.source !== source) {
|
||||
navRef.current = { source, nav: new PromptHistoryNav(source) };
|
||||
}
|
||||
return navRef.current.nav;
|
||||
}
|
||||
|
||||
/** Replace the draft with an archived prompt (or the stashed draft). */
|
||||
function recall(direction: "prev" | "next"): boolean {
|
||||
const nav = historyNav();
|
||||
const entry = direction === "prev" ? nav.prev(text) : nav.next();
|
||||
if (entry === null) return false;
|
||||
caretToEnd.current = true;
|
||||
setText(entry);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enter sends. ↑/↓ recall once there is nowhere left to move the caret, the
|
||||
* way pi2.nvim's prompt buffer does it; `<C-p>`/`<C-n>` are the readline
|
||||
* aliases and always recall. Anything else stays a plain textarea key.
|
||||
*/
|
||||
function handleKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
|
||||
// A composing IME owns ↑/↓ (candidate list) and Enter (commit).
|
||||
if (event.nativeEvent.isComposing) return;
|
||||
|
||||
if (event.key === "Enter" && !event.shiftKey) {
|
||||
event.preventDefault();
|
||||
submit();
|
||||
return;
|
||||
}
|
||||
|
||||
const modifier = event.ctrlKey || event.metaKey;
|
||||
if (modifier && !event.altKey && !event.shiftKey) {
|
||||
const direction = event.key === "p" ? "prev" : event.key === "n" ? "next" : null;
|
||||
if (direction === null) return;
|
||||
event.preventDefault();
|
||||
recall(direction);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.key !== "ArrowUp" && event.key !== "ArrowDown") return;
|
||||
if (modifier || event.altKey || event.shiftKey) return;
|
||||
|
||||
// A selection means the user is editing a fragment, not recalling.
|
||||
const element = event.currentTarget;
|
||||
const { selectionStart, selectionEnd } = element;
|
||||
if (selectionStart === null || selectionEnd === null) return;
|
||||
if (selectionStart !== selectionEnd) return;
|
||||
|
||||
if (event.key === "ArrowUp") {
|
||||
// Only from the first logical line: inside a multi-line entry ↑ still
|
||||
// moves the caret (nvim's `<Up>` rule).
|
||||
if (text.slice(0, selectionStart).includes("\n")) return;
|
||||
if (recall("prev")) event.preventDefault();
|
||||
return;
|
||||
}
|
||||
|
||||
// ↓ recalls from the last logical line, and always while browsing, so the
|
||||
// first ↓ out of a recalled prompt is never swallowed by a caret move.
|
||||
const atLastLine = !text.slice(selectionEnd).includes("\n");
|
||||
if (!atLastLine && !historyNav().navigating()) return;
|
||||
if (recall("next")) event.preventDefault();
|
||||
}
|
||||
|
||||
function submit(mode?: PromptMode) {
|
||||
const trimmed = text.trim();
|
||||
if (!trimmed || !enabled) return;
|
||||
const images = attachments.map(({ mimeType, data }) => ({ mimeType, data }));
|
||||
setText("");
|
||||
setAttachments([]);
|
||||
// Record the send and leave recall, exactly like pi2.nvim's prompt buffer.
|
||||
source.remember(trimmed);
|
||||
historyNav().reset();
|
||||
// A busy session queues the message as a follow-up; idle sends a plain prompt.
|
||||
onSend(trimmed, images, mode ?? (busy ? "follow_up" : undefined));
|
||||
}
|
||||
@@ -218,12 +318,13 @@ export function Composer({
|
||||
aria-label={t("chat.composerAria")}
|
||||
data-testid="composer-input"
|
||||
disabled={!enabled}
|
||||
onChange={(event) => setText(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing) return;
|
||||
event.preventDefault();
|
||||
submit();
|
||||
onChange={(event) => {
|
||||
setText(event.target.value);
|
||||
// A manual edit ends recall, so a later ↓ cannot clobber
|
||||
// the user's typing with a stale entry.
|
||||
historyNav().reset();
|
||||
}}
|
||||
onKeyDown={handleKeyDown}
|
||||
/>
|
||||
<div className="composer__bar">
|
||||
<button
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||
|
||||
import { ApiError, api, type PromptHistoryResponse } from "@/lib/api";
|
||||
|
||||
import {
|
||||
appendEntry,
|
||||
HISTORY_LIMIT,
|
||||
historyScope,
|
||||
type PromptHistorySource,
|
||||
readPromptHistory,
|
||||
relayedPromptHistorySource,
|
||||
rememberPrompt,
|
||||
replacePromptHistory,
|
||||
} from "./prompt-history";
|
||||
|
||||
/**
|
||||
* Prompt input history, fed by the plugin (`docs/protocol.md` §3.1.1) with the
|
||||
* browser mirror as fallback.
|
||||
*
|
||||
* The split matters, so it is explicit here:
|
||||
*
|
||||
* * **the entries** belong to pi2.nvim. Every prompt is recorded there on send,
|
||||
* whichever surface sent it, so the web console and nvim recall the same list
|
||||
* and so does every device paired to this daemon. The daemon relays one
|
||||
* live-only read per workspace; it stores nothing.
|
||||
* * **the mirror** (`localStorage`, `prompt-history.ts`) keeps recall working when
|
||||
* the relay cannot answer: no plugin connected (`live: false`), a plugin older
|
||||
* than the `promptHistory` capability (`supported: false`), a daemon older than
|
||||
* the endpoint (`404`), or an offline browser. It is written on every send, so
|
||||
* it is at worst behind the plugin — never authoritative.
|
||||
* * **the cursor** stays with the composer (`PromptHistoryNav`); nothing here
|
||||
* tries to persist a position.
|
||||
*
|
||||
* The query is deliberately cheap: one workspace-scoped read, cached by
|
||||
* react-query, refreshed on focus and invalidated by nothing else. It never
|
||||
* causes a spawn — the daemon answers `live: false` instead of booting an nvim.
|
||||
*/
|
||||
|
||||
/** Entries asked of the plugin; matches the daemon's default for the endpoint. */
|
||||
export const PROMPT_HISTORY_FETCH_LIMIT = 200;
|
||||
|
||||
/** react-query key prefix; one query per workspace. */
|
||||
export const PROMPT_HISTORY_QUERY = "prompt-history";
|
||||
|
||||
export interface PromptHistoryFeed {
|
||||
/** What the composer recalls from and records into. */
|
||||
source: PromptHistorySource;
|
||||
/** The plugin answered: the entries come from nvim, not from the mirror. */
|
||||
remote: boolean;
|
||||
/** The relay reported a connected plugin (it may still be unable to answer). */
|
||||
live: boolean;
|
||||
}
|
||||
|
||||
/** Keep only strings, drop blanks, keep the newest {@link HISTORY_LIMIT}. */
|
||||
export function normalizeEntries(value: unknown): string[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
const entries = value.filter((entry): entry is string => typeof entry === "string" && entry.trim() !== "");
|
||||
return entries.length > HISTORY_LIMIT ? entries.slice(entries.length - HISTORY_LIMIT) : entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* History feed for one workspace.
|
||||
*
|
||||
* @param workspaceId the workspace whose archive to recall from (undefined =>
|
||||
* nothing is fetched and the mirror bucket is `default`).
|
||||
* @param enabled false while unpaired/offline; the composer then recalls from the
|
||||
* mirror only.
|
||||
*/
|
||||
export function usePromptHistory(workspaceId: string | undefined, enabled: boolean): PromptHistoryFeed {
|
||||
const scope = historyScope(workspaceId);
|
||||
const queryClient = useQueryClient();
|
||||
const query = useQuery({
|
||||
queryKey: [PROMPT_HISTORY_QUERY, workspaceId],
|
||||
queryFn: ({ signal }) =>
|
||||
api.promptHistory(workspaceId ?? "", { limit: PROMPT_HISTORY_FETCH_LIMIT, signal }),
|
||||
enabled: enabled && Boolean(workspaceId),
|
||||
staleTime: 30_000,
|
||||
// A daemon older than the endpoint 404s it: a permanent "no relay", so it
|
||||
// must not burn retries (and must not surface as an error anywhere).
|
||||
retry: (attempts, error) => !(error instanceof ApiError && error.status === 404) && attempts < 1,
|
||||
});
|
||||
|
||||
const live = query.data?.live === true;
|
||||
const remote = live && query.data?.supported === true;
|
||||
const entries = useMemo(
|
||||
() => (remote ? normalizeEntries(query.data?.entries) : []),
|
||||
[remote, query.data],
|
||||
);
|
||||
|
||||
// The getter below must see the newest list (a refetch landing mid-browse, or
|
||||
// the optimistic append after a send) without rebuilding the nav cursor.
|
||||
const entriesRef = useRef<readonly string[]>(entries);
|
||||
entriesRef.current = entries;
|
||||
|
||||
// Refresh the fallback with what the plugin just told us, so losing it (or
|
||||
// moving to a daemon that predates the endpoint) still recalls this history
|
||||
// instead of starting from whatever only this browser typed.
|
||||
useEffect(() => {
|
||||
if (remote) replacePromptHistory(scope, entries);
|
||||
}, [remote, entries, scope]);
|
||||
|
||||
const remember = useCallback(
|
||||
(text: string) => {
|
||||
// Always keep the mirror warm: it becomes the source the moment this
|
||||
// workspace loses its plugin, and on an old daemon it is the only copy.
|
||||
rememberPrompt(scope, text);
|
||||
if (!remote || workspaceId === undefined) return;
|
||||
// Optimistic append so ↑ right after a send recalls it immediately.
|
||||
queryClient.setQueryData<PromptHistoryResponse>(
|
||||
[PROMPT_HISTORY_QUERY, workspaceId],
|
||||
(current) => {
|
||||
if (current === undefined) return current;
|
||||
return { ...current, entries: appendEntry(normalizeEntries(current.entries), text) };
|
||||
},
|
||||
);
|
||||
},
|
||||
[remote, scope, workspaceId, queryClient],
|
||||
);
|
||||
|
||||
const source = useMemo<PromptHistorySource>(
|
||||
() =>
|
||||
relayedPromptHistorySource(
|
||||
() => (remote ? entriesRef.current : readPromptHistory(scope)),
|
||||
remember,
|
||||
),
|
||||
[remote, remember, scope],
|
||||
);
|
||||
|
||||
return { source, remote, live };
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
/**
|
||||
* 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 = "";
|
||||
}
|
||||
}
|
||||
@@ -305,6 +305,23 @@ export interface ModelsResponse {
|
||||
pendingReason?: "fetching" | "no-instance" | "no-live-session";
|
||||
}
|
||||
|
||||
/**
|
||||
* `GET /api/v1/workspaces/:id/prompt-history` (docs/protocol.md §3.1.1).
|
||||
*
|
||||
* `live` is "a plugin for this workspace is connected", `supported` is "and it
|
||||
* advertised the `promptHistory` capability". The composer recalls from the
|
||||
* browser mirror unless both are true, so a cold workspace, an old plugin or an
|
||||
* old daemon all degrade to the same working fallback instead of an error.
|
||||
*/
|
||||
export interface PromptHistoryResponse {
|
||||
v?: number;
|
||||
workspaceId?: string;
|
||||
live?: boolean;
|
||||
supported?: boolean;
|
||||
/** Oldest first, newest last; unvalidated here (the caller normalizes). */
|
||||
entries?: unknown;
|
||||
}
|
||||
|
||||
/** One sampled filesystem (daemon ≥ 0.1.8; older daemons only send the scalars). */
|
||||
export interface DiskUsage {
|
||||
/** Filesystem boundary, e.g. `/`, `/home`, `/mnt/data`. */
|
||||
@@ -386,6 +403,15 @@ export const api = {
|
||||
},
|
||||
attention: (workspaceId: string, signal?: AbortSignal) =>
|
||||
request<unknown[]>(`/api/v1/attention?workspaceId=${encodeURIComponent(workspaceId)}`, { signal }),
|
||||
promptHistory: (workspaceId: string, options: { limit?: number; signal?: AbortSignal } = {}) => {
|
||||
const params = new URLSearchParams();
|
||||
if (options.limit !== undefined) params.set("limit", String(options.limit));
|
||||
const query = params.size ? `?${params.toString()}` : "";
|
||||
return request<PromptHistoryResponse>(
|
||||
`/api/v1/workspaces/${encodeURIComponent(workspaceId)}/prompt-history${query}`,
|
||||
{ signal: options.signal },
|
||||
);
|
||||
},
|
||||
devices: (signal?: AbortSignal) => request<DeviceInfo[]>("/api/v1/devices", { signal }),
|
||||
revokeDevice: (deviceId: string, signal?: AbortSignal) =>
|
||||
request<void>(`/api/v1/devices/${encodeURIComponent(deviceId)}`, { method: "DELETE", signal }),
|
||||
|
||||
@@ -37,6 +37,7 @@ import { useSessionHistory } from "@/features/chat/history";
|
||||
import { ChatLayout } from "@/features/chat/layout";
|
||||
import { MessageStream } from "@/features/chat/message-stream";
|
||||
import { onSessionMigration, replaceChatUrl } from "@/features/chat/migration";
|
||||
import { usePromptHistory } from "@/features/chat/prompt-history-feed";
|
||||
import { DispatchModal, RenameDialog, TaskOutputModal, type DispatchInput } from "@/features/chat/modals";
|
||||
import { SessionTray } from "@/features/chat/session-tray";
|
||||
import { sessionTitle } from "@/features/chat/session-title";
|
||||
@@ -143,6 +144,10 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
|
||||
active?.workspaceId ?? workspaceId,
|
||||
);
|
||||
const models = useChatModels(workspaceId, paired);
|
||||
// Composer ↑/↓ recall: the plugin owns the archive, the daemon relays a
|
||||
// live-only read, and the browser mirror covers a cold workspace or an old
|
||||
// plugin. Never spawns an nvim (see docs/prompt-history.md).
|
||||
const promptHistory = usePromptHistory(workspaceId, paired);
|
||||
const workspace = workspaces.find((item) => item.workspaceId === workspaceId);
|
||||
// pi2.nvim's placeholder vocabulary, and the display title of the routed
|
||||
// session: name → first message → `(unnamed)`. Never the session id.
|
||||
@@ -724,6 +729,7 @@ function ChatExperience({ sessionId }: { sessionId?: string }) {
|
||||
connected={connected}
|
||||
paired={paired}
|
||||
sending={sending}
|
||||
history={promptHistory.source}
|
||||
onSend={(text, images, mode) => void handleSend(text, images, mode)}
|
||||
onAbort={() => {
|
||||
setSending(null);
|
||||
|
||||
@@ -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