diff --git a/README.md b/README.md index d3f7437..457cea1 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,9 @@ agents through SQL and a CLI. Nothing leaves the machine. - **Nudges** (toasts, never added to the model's context): a call re-wrote the prompt cache, with the reason (a compaction, a model switch, idle past the cache's lifetime, or a change at the start of the request, which is worth a look); the context passed 200k. +- **`/quantext`:** opens or closes a pane with the session's last 50 messages (nudges, `/clear-tools` results, + viewer steps), newest first, so a toast you missed is still there. While the pane is closed, the status line + counts the new ones (`· 2 new`). - **`/clear-tools [outputs] [keep N]`:** compacts by replacing old tool calls (their inputs) and old tool outputs with short stubs instead of a summary, in one pass, so the prompt cache is written once. `outputs` clears only the outputs; `keep N` leaves the last N whole. Also as `/compact tools [outputs] [keep N]`. The next call diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 36cbcd2..2263f6a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -227,7 +227,7 @@ Each step ends with tests, and later steps never reach below the layer they depe | 6 | **Query layer + CLI**: `qx ingest`, `qx sessions`, `qx call`, `qx sql` with views | 1 | An agent answers "top tool outputs by lifetime cost" with `qx sql` | | 7 | **API + engine process**: HTTP JSON + SSE, Host check, single instance, idle exit | 1 | SSE fires on a new call; a second start reuses the running engine | | 8 | **Live context viewer**: reuse the eduagent visualiser components with a read-only Claude Code adapter; the teaching features above | 1 | A running session updates in the browser call by call; meets the UX bar | -| 9 | **Mod**: status line, nudges, `/clear-tools` from in-process `usage`; `/quantext view` starts the engine and opens the viewer | 1 | Works on a fresh Claude Code install; harness features work with no Node or Bun | +| 9 | **Mod**: status line, nudges (kept in the `/quantext` pane), `/clear-tools` from in-process `usage`; `/quantext view` starts the engine and opens the viewer | 1 | Works on a fresh Claude Code install; harness features work with no Node or Bun | | 10 | **Agent surface**: schema docs, a skill, MCP later | **2** | The reviewer questions are answered and checked in the viewer | Code from the earlier prototype (the Python parser and incremental store, pricing, the mod widget) is ported inside diff --git a/packages/mod/src/live.ts b/packages/mod/src/live.ts index eec1757..702814c 100644 --- a/packages/mod/src/live.ts +++ b/packages/mod/src/live.ts @@ -29,14 +29,19 @@ export async function updateLive($: EngineInterface, fn: (l: Live) => Live): Pro export const inputOf = (u: TurnUsage): number => u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens; -/** `qx $14.46 · ctx 333k · cache 60%`; undefined before the first measurement. */ -export function statusLabel(l: Live): string | undefined { - if (l.ctx === 0) return undefined; +/** + * `qx $14.46 · ctx 333k · cache 60% · 2 new`, the last part while messages came with the pane closed; + * undefined before the first measurement and with nothing new. + */ +export function statusLabel(l: Live, fresh = 0): string | undefined { + const news = fresh > 0 ? [`${fresh} new`] : []; + if (l.ctx === 0) return news.length > 0 ? `qx ${news.join("")}` : undefined; const total = l.read + l.input; const parts = [ ...(l.usd === undefined ? [] : [usd(l.usd)]), `ctx ${tokens(l.ctx)}`, ...(total > 0 ? [`cache ${Math.round((100 * l.read) / total)}%`] : []), + ...news, ]; return `qx ${parts.join(" · ")}`; } diff --git a/packages/mod/src/messages.ts b/packages/mod/src/messages.ts new file mode 100644 index 0000000..3a5d29d --- /dev/null +++ b/packages/mod/src/messages.ts @@ -0,0 +1,85 @@ +/** + * The mod's messages: each one a toast, and kept, newest first, for the pane that bare `/quantext` opens and + * closes. A toast lasts seconds; the pane keeps the session's newest 50. While the pane is closed the footer + * counts the new ones. + */ +import type { EngineInterface, RenderElement, RenderInput } from "claude-code"; +import { atom, read, update } from "claude-code"; +import type { Messages } from "../types/index.js"; + +export const PANE = "quantext"; +const TITLE = "Quantext"; +const KEEP = 50; +/** Inline above the prompt the frame grows with its rows: there only the newest few. */ +const INLINE = 5; +const EMPTY: Messages = { list: [], unread: 0 }; +// Change the tag when a message's fields change: it declines what an earlier version stored. +const messages = atom({ plugin: "quantext", key: "messages" } as const, EMPTY, { shape: "messages-1" }); + +/** Whether the pane is on screen; a failed look counts as closed, so a message counts as new. */ +async function paneIsShown($: EngineInterface): Promise { + try { + return (await $.ui.panes()).some((p) => p.id === PANE && p.isPlaced && p.isShown); + } catch (error) { + $.ui.log(`quantext: could not list the panes: ${String(error)}`, { to: "debug" }); + return false; + } +} + +/** Shows `text` as a toast and keeps it for the pane. */ +export async function say($: EngineInterface, text: string): Promise { + $.ui.toast(text); + const at = await $.clock.now(); + const seen = await paneIsShown($); + await update($, messages, (m) => ({ + list: [{ at, text }, ...m.list].slice(0, KEEP), + unread: seen ? 0 : m.unread + 1, + })); +} + +/** How many messages came while the pane was closed. */ +export async function unread($: EngineInterface): Promise { + return (await read($, messages)).unread; +} + +/** Opens the pane, or closes it when it is open; answers what it did, for the command's reply. */ +export async function togglePane($: EngineInterface): Promise { + if ((await $.ui.panes()).some((p) => p.id === PANE)) { + await $.ui.close({ id: PANE }); + return "quantext: messages pane closed."; + } + const opened = await $.ui.open({ id: PANE, title: TITLE }); + await update($, messages, (m) => ({ ...m, unread: 0 })); + return opened.isPlaced + ? "quantext: messages pane opened; /quantext again closes it." + : `quantext: the messages pane waits to be drawn (${opened.reason}).`; +} + +/** `14:05`, in the person's time zone. */ +function clockTime(at: number): string { + const d = new Date(at); + return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`; +} + +/** `h` with a component tag: `h` is typed for every tag (a string too), so it may answer a bare string or null. */ +const el = (...args: Parameters): RenderElement => h(...args) as RenderElement; + +/** Draws the pane: one row per message, its time, then its words without the "quantext: " the title says. */ +export async function drawPane($: EngineInterface, e: RenderInput<"Pane">): Promise { + const { Box, Text } = $.ui.resolve(e); + const { list } = await read($, messages); + if (list.length === 0) return el(Text, { dimColor: true }, "No messages yet. Quantext's toasts land here."); + const shown = e.props.placement === "inline" ? list.slice(0, INLINE) : list; + return el( + Box, + { flexDirection: "column" }, + ...shown.map((m) => + el( + Box, + { flexDirection: "row", gap: 1 }, + el(Text, { dimColor: true }, clockTime(m.at)), + el(Text, { wrap: "wrap" }, m.text.replace(/^quantext: /, "")), + ), + ), + ); +} diff --git a/packages/mod/src/register.ts b/packages/mod/src/register.ts index b780c08..b57bbe0 100644 --- a/packages/mod/src/register.ts +++ b/packages/mod/src/register.ts @@ -1,8 +1,9 @@ -/** The Quantext mod: a footer label and nudges from in-process usage, /clear-tools, /quantext view. */ +/** The Quantext mod: a footer label and nudges from in-process usage, a messages pane, /clear-tools, /quantext view. */ import type { EngineInterface, Register } from "claude-code"; import type { ClearArgs } from "./clear-tools.ts"; import { clearRequest, clearTools, clearWhat, compactArgs, parseClearArgs, USAGE } from "./clear-tools.ts"; import { EMPTY, inputOf, readLive, statusLabel, updateLive } from "./live.ts"; +import { drawPane, PANE, say, togglePane, unread } from "./messages.ts"; import { CACHE_TTL_MS, cacheBreakNudge, cacheHeld, contextNudge } from "./nudges.ts"; import { openViewer } from "./viewer.ts"; @@ -16,7 +17,7 @@ async function clearNow($: EngineInterface, a: ClearArgs): Promise { await $.command.run({ command: "compact", args }); } catch (error) { const why = error instanceof Error ? error.message : String(error); - $.ui.toast(`/clear-tools failed: ${why}; try /compact ${args}`); + await say($, `/clear-tools failed: ${why}; try /compact ${args}`); } } @@ -57,8 +58,8 @@ export const register: Register = (on) => { }); await $.command.register({ name: "quantext", - description: "Quantext: open the live context viewer (starts the engine when it is not running)", - argumentHint: "view", + description: "Quantext: open or close the messages pane; view: open the live context viewer", + argumentHint: "[view]", }); if (e.isInteractive) remeasureSoon($); // show the context before the first call return started; @@ -82,7 +83,7 @@ export const register: Register = (on) => { ...(e.cost === undefined ? {} : { usd: e.cost.usd }), bigCtxNudged: l.bigCtxNudged || nudge !== undefined, })); - if (nudge !== undefined) $.ui.toast(nudge); + if (nudge !== undefined) await say($, nudge); return r; }); @@ -106,17 +107,18 @@ export const register: Register = (on) => { lastCtx: inputOf(u), model: u.model, })); - if (nudge !== undefined) $.ui.toast(nudge); + if (nudge !== undefined) await say($, nudge); return r; }); on("command.run", { command: "quantext" }, async ($, e) => { - if (e.args.trim().toLowerCase() !== "view") return { text: "Usage: /quantext view" }; + const arg = e.args.trim().toLowerCase(); + if (arg === "") return { text: await togglePane($) }; + if (arg !== "view") return { text: "Usage: /quantext (the messages pane) or /quantext view (the viewer)" }; // The flow waits up to ~11 s, past a hook's budget: it runs from a timer and answers with toasts. $.clock.after( 0, - () => - void openViewer($).catch((error: unknown) => $.ui.toast(`quantext: /quantext view failed: ${String(error)}`)), + () => void openViewer($).catch((error: unknown) => say($, `quantext: /quantext view failed: ${String(error)}`)), ); return { text: "quantext: opening the viewer…" }; }); @@ -137,7 +139,7 @@ export const register: Register = (on) => { await updateLive($, (l) => ({ ...l, bigCtxNudged: false, compacted: true })); remeasureSoon($); } - if (note !== undefined) $.ui.toast(note); // after the update, so a failed clear shows no "Cleared" + if (note !== undefined) await say($, note); // after the update, so a failed clear shows no "Cleared" return r; }).catch((_$, e, next) => { // A failed clear must not fall back to a paid summary; any other failure leaves it to Claude Code. @@ -155,9 +157,11 @@ export const register: Register = (on) => { return r; }); + on("ui.render", { component: "Pane", requestId: PANE }, ($, e) => drawPane($, e)); + // Appends to the footer's mode labels, so the labels of other plugins stay. on("ui.render", { component: "SessionMode" }, async ($, e, next) => { - const label = statusLabel(await readLive($)); + const label = statusLabel(await readLive($), await unread($)); if (label === undefined) return next(e); return next({ ...e, props: { ...e.props, modes: [...e.props.modes, label] } }); }); diff --git a/packages/mod/src/viewer.ts b/packages/mod/src/viewer.ts index 516b836..72ae6c8 100644 --- a/packages/mod/src/viewer.ts +++ b/packages/mod/src/viewer.ts @@ -3,9 +3,11 @@ * runs (or when the one found does not serve the viewer's page: it is stopped first), and open the viewer. The engine is started only here, never by itself (ARCHITECTURE "Starting the * engine"). Each step's outcome reaches the person as a toast. */ + import type { EngineInterface } from "claude-code"; import type { EngineAddress } from "./engine-file.ts"; import { engineUrl, parseEngineFile, parseEngineVersion, parseHealth, printable } from "./engine-file.ts"; +import { say } from "./messages.ts"; import { INSTALL_HINT, MIN_BUN, MIN_NODE, meetsVersion } from "./runtime.ts"; /** How long one `/health` may take: a local engine answers in milliseconds. */ @@ -140,23 +142,24 @@ async function openUrl($: EngineInterface, url: string, cwd: string): Promise { const home = await $.env.get("HOME"); if (home === undefined || home === "") { - $.ui.toast("quantext: HOME is not set, so the engine's folder (~/.quantext) cannot be found."); + await say($, "quantext: HOME is not set, so the engine's folder (~/.quantext) cannot be found."); return; } const dataDir = `${home}/.quantext`; const engineDir = `${$.plugin.root}/engine`; const version = await bundledVersion($, engineDir); if (version === undefined) { - $.ui.toast("quantext: this plugin has no bundled engine (engine/); reinstall it."); + await say($, "quantext: this plugin has no bundled engine (engine/); reinstall it."); return; } let found = await findEngine($, dataDir, version); if (found.kind === "same" && !(await servesPage($, found.port))) { const { pid } = found; - $.ui.toast(`quantext: the engine (pid ${pid}) does not serve the viewer; starting it again…`); + await say($, `quantext: the engine (pid ${pid}) does not serve the viewer; starting it again…`); if (!(await stopEngine($, dataDir, version, pid, engineDir))) { - $.ui.toast( + await say( + $, `quantext: the engine (pid ${pid}) does not serve the viewer and did not stop; ` + `stop it (kill -9 ${pid}), then run /quantext view again.`, ); @@ -167,33 +170,34 @@ export async function openViewer($: EngineInterface): Promise { if (found.kind === "none") { const runtime = await findRuntime($, engineDir); if (runtime === undefined) { - $.ui.toast(INSTALL_HINT); + await say($, INSTALL_HINT); return; } - $.ui.toast("quantext: starting the engine…"); + await say($, "quantext: starting the engine…"); const log = `${dataDir}/engine.log`; const argv = ["sh", "-c", START_SCRIPT, runtime, `${engineDir}/engine.js`, log, dataDir]; const started = await tryRun($, argv, engineDir); if (started?.exitCode !== 0) { const why = printable(started?.stderr.trim() ?? "").slice(0, STDERR_SHOWN) || "sh did not run"; - $.ui.toast(`quantext: the engine could not be started (${why}).`); + await say($, `quantext: the engine could not be started (${why}).`); return; } found = await waitForEngine($, dataDir, version); if (found.kind === "none") { - $.ui.toast(`quantext: the engine did not answer within ${START_TIMEOUT_MS / 1000} s; see ${log}`); + await say($, `quantext: the engine did not answer within ${START_TIMEOUT_MS / 1000} s; see ${log}`); return; } } if (found.kind === "other") { - $.ui.toast( + await say( + $, `quantext: an engine of version ${found.version} (pid ${found.pid}) runs; this plugin brings ${version}. ` + `Stop it (kill ${found.pid}), then run /quantext view again.`, ); return; } const opened = await openUrl($, found.url, engineDir); - $.ui.toast(`quantext: the viewer is at ${found.url}${opened ? "" : " (open it in a browser)"}`); + await say($, `quantext: the viewer is at ${found.url}${opened ? "" : " (open it in a browser)"}`); } /** The bundled engine's version, or undefined when the plugin has no engine. */ diff --git a/packages/mod/test/messages.test.ts b/packages/mod/test/messages.test.ts new file mode 100644 index 0000000..db54fce --- /dev/null +++ b/packages/mod/test/messages.test.ts @@ -0,0 +1,140 @@ +import type { On } from "claude-code"; +import type { Engine } from "claude-code/testing"; +import { expect, test } from "claude-code/testing"; +import { command, draw, footer, stepper, toasts, usage } from "./kit.ts"; + +const MINUTE = 60_000; +const LOST = /^cache lost after 1 min, with no compaction or model switch/; + +const pane = (placement: "dock" | "inline" = "dock") => + ({ + plugin: "quantext", + component: "Pane", + requestId: "quantext", + surface: "terminal", + props: { + title: "Quantext", + isFocused: false, + bodyColumns: 40, + placement, + scroll: { offset: 0, bodyRows: 20 }, + view: {}, + }, + }) as const; + +/** The engine's record of this plugin's panes, as `$.ui.open`, `close` and `panes` keep it. */ +function panes(on: On): Set { + const open = new Set(); + on("ui.open", (_$, e) => { + open.add(e.id); + return { value: { isPlaced: true } }; + }); + on("ui.close", (_$, e) => { + open.delete(e.id); + return { value: undefined }; + }); + on("ui.panes", () => ({ + value: [...open].map((id) => ({ id, title: "Quantext", isShown: true, isFocused: false, isPlaced: true })), + })); + return open; +} + +/** `lose($, n)`: n more cache losses, one minute apart, each one a nudge. Made before the test's first `$` call. */ +function losses(on: On) { + const { step, clock } = stepper(on); + let i = 0; + return async ($: Engine, n: number) => { + if (i === 0) await step($, usage(300_000, 1_000)); + for (let k = 0; k < n; k++, i++) { + await clock.advance(MINUTE); + await step($, usage(0, 301_000 + i)); + } + }; +} + +/** The words of each row of the pane, top to bottom, with no time. */ +async function rows($: Engine, placement: "dock" | "inline" = "dock"): Promise { + const ui = await $.ui.mount(pane(placement)); + const found = await ui.findAll({ type: "Text" }); + await ui.unmount(); + return found.map((t) => t.text ?? "").filter((t) => !/^\d\d:\d\d$/.test(t)); +} + +test("a nudge is still a toast, and it stays in the pane after the toast is gone", async ($, on) => { + const lose = losses(on); + const seen = toasts(on); + await lose($, 1); + expect(seen).toHaveLength(1); + const [row] = await rows($); + expect(row).toMatch(LOST); // without the "quantext: " the pane's title already says +}); + +test("the pane shows the newest message first, each with its time", async ($, on) => { + const lose = losses(on); + toasts(on); + await lose($, 2); + const ui = await $.ui.mount(pane()); + const texts = (await ui.findAll({ type: "Text" })).map((t) => t.text ?? ""); + await ui.unmount(); + expect(texts.filter((t) => /^\d\d:\d\d$/.test(t))).toHaveLength(2); + const words = texts.filter((t) => !/^\d\d:\d\d$/.test(t)); + expect(words[0]).toContain("301k tokens"); // 301,001: the second loss + expect(words[0]).not.toBe(words[1]); +}); + +test("the pane keeps the newest 50 messages", async ($, on) => { + const lose = losses(on); + toasts(on); + await lose($, 53); + expect(await rows($)).toHaveLength(50); +}); + +test("inline above the prompt, where the frame grows with its rows, the pane shows the newest 5", async ($, on) => { + const lose = losses(on); + toasts(on); + await lose($, 8); + expect(await rows($, "inline")).toHaveLength(5); +}); + +test("with no message yet, the pane says so", async ($) => { + expect(await rows($)).toEqual(["No messages yet. Quantext's toasts land here."]); +}); + +test("/quantext opens the pane, and a second /quantext closes it", async ($, on) => { + const open = panes(on); + const first = await $.command.run(command("quantext")); + expect([...open]).toEqual(["quantext"]); + expect(first.text).toMatch(/pane/); + await $.command.run(command("quantext")); + expect([...open]).toEqual([]); +}); + +test("the footer counts the messages shown while the pane was closed, until /quantext opens it", async ($, on) => { + const lose = losses(on); + const modes = footer(on); + panes(on); + toasts(on); + await lose($, 2); + await draw($); + expect(modes().at(-1)).toBe("qx 2 new"); // no context measured yet: the count alone + await $.command.run(command("quantext")); + await draw($); + expect(modes().at(-1)).not.toMatch(/new/); + await lose($, 1); // the pane is open: the person sees it there + await draw($); + expect(modes().at(-1)).not.toMatch(/new/); +}); + +test("the messages stay after a /clear", async ($, on) => { + const lose = losses(on); + toasts(on); + on("session.end", (_$, e) => ({ sessionId: e.sessionId })); + await lose($, 1); + await $.session.end({ reason: "clear", sessionId: "s1", resume: {} } as never); + expect(await rows($)).toHaveLength(1); +}); + +test("/quantext with anything but view says how to use it", async ($) => { + const r = await $.command.run(command("quantext", "nope")); + expect(r.text).toBe("Usage: /quantext (the messages pane) or /quantext view (the viewer)"); +}); diff --git a/packages/mod/test/remeasure.test.ts b/packages/mod/test/remeasure.test.ts index d68326a..35be345 100644 --- a/packages/mod/test/remeasure.test.ts +++ b/packages/mod/test/remeasure.test.ts @@ -47,7 +47,7 @@ test("the context is counted again once a compaction has landed", async ($, on) await $.session.compact({ trigger: "auto", messages: [{ role: "user", text: "hi", toolUses: [] }] } as never); await clock.advance(1_000); await draw($); - expect(modes()).toEqual(["qx $2.00 · ctx 25k"]); + expect(modes()).toEqual(["qx $2.00 · ctx 25k · 1 new"]); // 1 new: the large-context nudge at 300k }); test("a compaction made ahead of time (precompute) or a subagent's does not count again", async ($, on) => { @@ -72,5 +72,5 @@ test("after /clear the figures start over from a new count", async ($, on) => { await $.session.end({ reason: "clear", sessionId: "s1", resume: {} } as never); await clock.advance(1_000); await draw($); - expect(modes()).toEqual(["qx $2.00 · ctx 18k"]); + expect(modes()).toEqual(["qx $2.00 · ctx 18k · 1 new"]); // 1 new: the large-context nudge at 300k }); diff --git a/packages/mod/test/status-line.test.ts b/packages/mod/test/status-line.test.ts index c4ffc43..6729139 100644 --- a/packages/mod/test/status-line.test.ts +++ b/packages/mod/test/status-line.test.ts @@ -10,7 +10,8 @@ test("the label shows the harness's cost, the context and the cache hit rate, be await measure($, 333_000, 14.456); await draw($, ["stash 3"]); // 30k of the 50k input tokens were read from the cache - expect(modes()).toEqual(["stash 3", "qx $14.46 · ctx 333k · cache 60%"]); + // 1 new: the large-context nudge at 333k, shown while the messages pane was closed + expect(modes()).toEqual(["stash 3", "qx $14.46 · ctx 333k · cache 60% · 1 new"]); }); test("subagent calls do not count toward the cache rate", async ($, on) => { diff --git a/packages/mod/test/viewer.test.ts b/packages/mod/test/viewer.test.ts index 9697028..ba53c76 100644 --- a/packages/mod/test/viewer.test.ts +++ b/packages/mod/test/viewer.test.ts @@ -248,10 +248,11 @@ test("a plugin without its bundled engine says so", async ($, on) => { expect(w.toasts).toEqual(["quantext: this plugin has no bundled engine (engine/); reinstall it."]); }); -test("/quantext alone, or with other words, answers its usage", async ($, on) => { +test("/quantext with other words answers its usage and starts nothing", async ($, on) => { const w = world(on); - expect((await $.command.run(command("quantext"))).text).toBe("Usage: /quantext view"); - expect((await $.command.run(command("quantext", "open now"))).text).toBe("Usage: /quantext view"); + expect((await $.command.run(command("quantext", "open now"))).text).toBe( + "Usage: /quantext (the messages pane) or /quantext view (the viewer)", + ); await w.settle(); expect(w.argvs).toEqual([]); }); diff --git a/packages/mod/types/index.d.ts b/packages/mod/types/index.d.ts index b826739..4daa6c4 100644 --- a/packages/mod/types/index.d.ts +++ b/packages/mod/types/index.d.ts @@ -20,8 +20,14 @@ export type Live = { hourCache: boolean; }; +/** One message the mod showed as a toast: when (ms since the epoch) and its words. */ +export type Message = { at: number; text: string }; + +/** The session's messages for the pane, newest first, and how many came while the pane was closed. */ +export type Messages = { list: Message[]; unread: number }; + declare module "claude-code" { interface PluginState { - quantext: { live: Live }; + quantext: { live: Live; messages: Shaped }; } }