From 096086a8b49ac96dcfe788d6efb95df55bf5a938 Mon Sep 17 00:00:00 2001 From: Kaleb Dickerson Date: Tue, 1 Dec 2026 22:30:18 +0000 Subject: [PATCH 1/7] pi: remove transcript timestamps and latency stamps Drops the transcript-timestamps extension, its /stamp command, and the transcript-stamp layout. The native image decorator keeps its own unload test. --- .../extensions/transcript-stamp/layout.ts | 96 ----------------- .pi/agent/extensions/transcript-timestamps.ts | 94 ---------------- .pi/tests/native-transcript.test.mjs | 53 ++++----- .pi/tests/transcript-stamp.test.mjs | 101 ------------------ 4 files changed, 18 insertions(+), 326 deletions(-) delete mode 100644 .pi/agent/extensions/transcript-stamp/layout.ts delete mode 100644 .pi/agent/extensions/transcript-timestamps.ts delete mode 100644 .pi/tests/transcript-stamp.test.mjs diff --git a/.pi/agent/extensions/transcript-stamp/layout.ts b/.pi/agent/extensions/transcript-stamp/layout.ts deleted file mode 100644 index 631c6cc..0000000 --- a/.pi/agent/extensions/transcript-stamp/layout.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { AssistantMessageComponent, UserMessageComponent, type Theme } from "@earendil-works/pi-coding-agent"; -import { visibleWidth } from "@earendil-works/pi-tui"; -import { registerTranscriptDecoration } from "../native-transcript/insertion.ts"; - -type ChatMessage = { role: string; timestamp: number }; -type AssistantState = { - lastMessage?: ChatMessage & { content: { type: string; text?: string }[] }; - isStreaming?: boolean; - outputPad?: number; -}; - -export function withStamp( - lines: readonly string[], width: number, pad: number, label: string, style: (label: string) => string, user: boolean, -): readonly string[] { - const size = visibleWidth(label); - const column = width - pad - size; - if (!lines.length || !label || column < 0) return lines; - const last = lines.at(-1)!; - // Replace only terminal padding. Preserve SGR, shell zone markers and cached source rows. - const padding = / +(?=(?:\x1b\[[0-9;:]*m)*$)/.exec(last); - if (padding && !/\x1b(?:_G|\]1337;|P)/.test(last)) { - const start = visibleWidth(last.slice(0, padding.index)); - if (start + (user ? 0 : 2) <= column) { - const row = last.slice(0, padding.index) + " ".repeat(column - start) + style(label) + - " ".repeat(pad) + last.slice(padding.index + padding[0].length); - return [...lines.slice(0, -1), row]; - } - } - return user ? lines : [...lines, " ".repeat(column) + style(label)]; -} - -// How a message's stamp was placed, reused while its last row, the width and the label stay the same. -type Placement = { readonly key: string; readonly style: unknown; readonly how: "none" | "replace" | "append"; readonly row: string }; -const placements = new WeakMap(); -const withCachedStamp = ( - owner: object, lines: string[], width: number, pad: number, label: string, style: (label: string) => string, user: boolean, -): string[] => { - const key = `${width}\0${pad}\0${label}\0${lines.at(-1) ?? ""}`; - let placed = placements.get(owner); - if (placed?.key !== key || placed.style !== style) { - const out = withStamp(lines, width, pad, label, style, user); - placed = out === lines ? { key, style, how: "none", row: "" } - : out.length > lines.length ? { key, style, how: "append", row: out.at(-1)! } - : { key, style, how: "replace", row: out.at(-1)! }; - placements.set(owner, placed); - } - if (placed.how === "none") return lines; - return placed.how === "append" ? [...lines, placed.row] : [...lines.slice(0, -1), placed.row]; -}; - -export function mountTranscriptStamps(theme: () => Theme | undefined, format: (timestamp: number, width: number, assistant: boolean) => string) { - // A new style per theme, so cached stamps follow theme changes. - let styled: { theme: Theme | undefined; dim: (text: string) => string } | undefined; - const dimStyle = () => { - const th = theme(); - const cached = styled; - if (cached && cached.theme === th) return cached.dim; - const dim = (text: string) => th?.fg("dim", text) ?? text; - styled = { theme: th, dim }; - return dim; - }; - let active = true; - const removeInsertion = registerTranscriptDecoration("transcript-timestamps", ({ message }) => { - if (message.role !== "user") return; - const { timestamp } = message; - return { - afterInsert(nativeRows) { - for (const child of nativeRows) { - if (!(child instanceof UserMessageComponent)) continue; - const render = child.render; - child.render = function (width) { - const lines = render.call(this, width); - if (!active) return lines; - const pad = (this as unknown as { outputPad?: number }).outputPad ?? 1; - return withCachedStamp(this, lines, width, pad, format(timestamp, width - pad, false), dimStyle(), true); - }; - } - }, - }; - }); - // Pi creates live assistant components outside the chat insertion path. - const assistant = AssistantMessageComponent.prototype; - const renderAssistant = assistant.render; - const render: typeof assistant.render = function (this: AssistantMessageComponent, width) { - const lines = renderAssistant.call(this, width); - const { lastMessage, isStreaming, outputPad = 1 } = this as unknown as AssistantState; - if (!active || isStreaming || !lastMessage?.content.some(part => part.type === "text" && part.text?.trim())) return lines; - return withCachedStamp(this, lines, width, outputPad, format(lastMessage.timestamp, width - outputPad, true), dimStyle(), false); - }; - if (typeof renderAssistant === "function") assistant.render = render; - return () => { - active = false; - removeInsertion(); - if (assistant.render === render) assistant.render = renderAssistant; - }; -} diff --git a/.pi/agent/extensions/transcript-timestamps.ts b/.pi/agent/extensions/transcript-timestamps.ts deleted file mode 100644 index a34b657..0000000 --- a/.pi/agent/extensions/transcript-timestamps.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { getAgentDir, type ExtensionAPI, type Theme } from "@earendil-works/pi-coding-agent"; -import { readFileSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; -import { mountTranscriptStamps } from "./transcript-stamp/layout.ts"; -import { showToast } from "./toast/api.ts"; - -const entryType = "local-transcript-timestamp"; -const clock = new Intl.DateTimeFormat(undefined, { - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - hourCycle: "h23", -}); - -type Stamp = { timestamp: number; latencyMs: number }; -const hasText = (part: { type: string; text?: string }): boolean => - part.type === "text" && Boolean(part.text?.trim()); - -export default function (pi: ExtensionAPI) { - const settingsPath = join(getAgentDir(), "transcript-timestamps.json"); - let settings = { showTimestamps: true, showLatency: false }; - try { - const saved = JSON.parse(readFileSync(settingsPath, "utf8")); - settings = { showTimestamps: saved?.showTimestamps !== false, showLatency: saved?.showLatency === true }; - } catch {} - - let timing: Stamp | undefined; - let getTheme: (() => Theme) | undefined; - const latencies = new Map(); - - pi.registerCommand("stamp", { - description: "Configure transcript display: /stamp [timestamps|latency] [on|off]", - getArgumentCompletions: prefix => ["timestamps on", "timestamps off", "latency on", "latency off"] - .filter(option => option.startsWith(prefix.trimStart())) - .map(option => ({ value: option, label: option })), - handler: async (args, ctx) => { - const option = /^(timestamps|latency)\s+(on|off)$/.exec(args.trim()); - if (!option) { - ctx.ui.notify(`Timestamps ${settings.showTimestamps ? "on" : "off"} · response latency ${settings.showLatency ? "on" : "off"}. Use /stamp [timestamps|latency] [on|off].`, "info"); - return; - } - const enabled = option[2] === "on"; - const timestamps = option[1] === "timestamps"; - const next = { ...settings, [timestamps ? "showTimestamps" : "showLatency"]: enabled }; - try { - writeFileSync(settingsPath, JSON.stringify(next) + "\n"); - settings = next; - showToast(pi.events, { title: "Stamp", message: `${timestamps ? "Timestamps" : "Response latency"} ${enabled ? "on" : "off"}`, key: `stamp:${option[1]}` }); - } catch (error) { - showToast(pi.events, { title: "Stamp", message: `Could not save timestamp settings: ${error}`, tone: "error", key: "stamp:error" }); - } - }, - }); - - const restore = (entries: { type: string; customType?: string; data?: unknown }[]) => { - latencies.clear(); - for (const entry of entries) { - if (entry.type !== "custom" || entry.customType !== entryType || typeof entry.data !== "object" || !entry.data) continue; - const { timestamp, latencyMs } = entry.data as Partial; - if (typeof timestamp === "number" && typeof latencyMs === "number" && Number.isFinite(latencyMs) && latencyMs >= 0) { - latencies.set(timestamp, latencyMs); - } - } - }; - // Pi can rebuild the transcript before binding session_start on reload and resume. - const unmount = mountTranscriptStamps(() => getTheme?.(), (timestamp, width, assistant) => { - if (!Number.isFinite(new Date(timestamp).getTime())) return ""; - const label = settings.showTimestamps ? clock.format(timestamp) : ""; - const latency = assistant && settings.showLatency ? latencies.get(timestamp) : undefined; - const detail = latency === undefined ? "" : `${(latency / 1000).toFixed(2)}s`; - const combined = [label, detail].filter(Boolean).join(" · "); - return combined.length <= width ? combined : label; - }); - pi.on("session_start", (_event, ctx) => { - if (ctx.mode !== "tui") return unmount(); - getTheme = () => ctx.ui.theme; - restore(ctx.sessionManager.getBranch()); - }); - pi.on("session_tree", (_event, ctx) => restore(ctx.sessionManager.getBranch())); - pi.on("session_shutdown", unmount); - pi.on("message_start", ({ message }) => { - if (message.role === "assistant") timing = undefined; - }); - pi.on("message_update", ({ message }, ctx) => { - if (ctx.mode !== "tui" || message.role !== "assistant" || timing || !message.content.some(hasText)) return; - const { timestamp } = message; - timing = { timestamp, latencyMs: Math.max(0, Date.now() - timestamp) }; - latencies.set(timestamp, timing.latencyMs); - }); - pi.on("turn_end", ({ message }) => { - if (message.role === "assistant" && timing?.timestamp === message.timestamp) pi.appendEntry(entryType, timing); - timing = undefined; - }); -} diff --git a/.pi/tests/native-transcript.test.mjs b/.pi/tests/native-transcript.test.mjs index 84d8d27..feab58d 100644 --- a/.pi/tests/native-transcript.test.mjs +++ b/.pi/tests/native-transcript.test.mjs @@ -4,7 +4,6 @@ import { InteractiveMode, UserMessageComponent, getMarkdownTheme, initTheme } fr import { Container, Text, resetCapabilitiesCache, setCapabilities, stripTerminalSequences } from '@earendil-works/pi-tui'; import { mountTranscriptImages } from '../agent/extensions/image-chips/transcript.ts'; import { registerTranscriptDecoration } from '../agent/extensions/native-transcript/insertion.ts'; -import { mountTranscriptStamps } from '../agent/extensions/transcript-stamp/layout.ts'; const noop = () => {}; const rows = (component) => component.render(48).map(stripTerminalSequences); @@ -23,6 +22,7 @@ function makeChat(getShowImages = () => false) { getShowImages, getImageWidthCells: () => 32, getNotices: () => ({}), + getShowCacheMissNotices: () => false, } } }, editor: { addToHistory: (text) => history.push(text) }, footer: { invalidate: noop }, @@ -95,41 +95,24 @@ test('a failing decorator does not prevent native insertion or other decorations assert.throws(() => chat.addMessageToChat(message), /native failed/); }); -for (const first of ['images', 'stamps']) { - test(`native image and stamp decorators work alone after unloading ${first} first`, (t) => { - initTheme('dark', false); - const original = InteractiveMode.prototype.addMessageToChat; - const mount = { - images: () => mountTranscriptImages(paint), - stamps: () => mountTranscriptStamps(paint, String), - }; - const offFirst = mount[first](); - t.after(offFirst); - const shared = InteractiveMode.prototype.addMessageToChat; - const offSecond = mount[first === 'images' ? 'stamps' : 'images'](); - t.after(offSecond); - assert.equal(InteractiveMode.prototype.addMessageToChat, shared); - const { chat } = makeChat(); - chat.addMessageToChat(imageOnly); - const [native, preview] = chat.chatContainer.children; - assert.ok(native instanceof UserMessageComponent); - const stamped = rows(native); - assert.match(stamped.join('\n'), /\[Image 1\]/); - assert.match(stamped.at(-1), /1234 $/); - assert.deepEqual(rows(preview), []); +test('the native image decorator restores Pi after unloading', (t) => { + initTheme('dark', false); + const original = InteractiveMode.prototype.addMessageToChat; + const off = mountTranscriptImages(paint); + t.after(off); + const { chat } = makeChat(); + chat.addMessageToChat(imageOnly); + const [native, preview] = chat.chatContainer.children; + assert.ok(native instanceof UserMessageComponent); + assert.match(rows(native).join('\n'), /\[Image 1\]/); + assert.deepEqual(rows(preview), []); - chat.chatContainer.clear(); - offFirst(); - assert.equal(InteractiveMode.prototype.addMessageToChat, shared); - chat.addMessageToChat(imageOnly); - assert.equal(chat.chatContainer.children.length, first === 'images' ? 0 : 2); - assert.doesNotMatch(rows(chat.chatContainer).join('\n'), /1234/); - chat.addMessageToChat({ role: 'user', content: 'Plain text', timestamp: 1234 }); - assert.equal(rows(chat.chatContainer).join('\n').includes('1234'), first === 'images'); - offSecond(); - assert.equal(InteractiveMode.prototype.addMessageToChat, original); - }); -} + chat.chatContainer.clear(); + off(); + assert.equal(InteractiveMode.prototype.addMessageToChat, original); + chat.addMessageToChat(imageOnly); + assert.equal(chat.chatContainer.children.length, 0); +}); test('live and replayed user attachments render previews with nonduplicated fallbacks', async (t) => { initTheme('dark', false); diff --git a/.pi/tests/transcript-stamp.test.mjs b/.pi/tests/transcript-stamp.test.mjs deleted file mode 100644 index 8d7ee2a..0000000 --- a/.pi/tests/transcript-stamp.test.mjs +++ /dev/null @@ -1,101 +0,0 @@ -import assert from 'node:assert/strict'; -import { test } from 'node:test'; -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { AssistantMessageComponent, InteractiveMode, getMarkdownTheme, initTheme } from '@earendil-works/pi-coding-agent'; -import { Container, stripTerminalSequences, visibleWidth } from '@earendil-works/pi-tui'; -import { mountTranscriptStamps, withStamp } from '../agent/extensions/transcript-stamp/layout.ts'; -import stamp from '../agent/extensions/transcript-timestamps.ts'; - -test('stamps use existing space, preserve terminal escapes and fall back to one row', () => { - const styled = text => `\x1b[90m${text}\x1b[39m`; - const zone = '\x1b]133;B\x07'; - const user = [zone + '\x1b[44m' + ' '.repeat(20) + '\x1b[49m']; - const [row] = withStamp(user, 20, 1, '13:00:00', styled, true); - assert.equal(row, zone + '\x1b[44m' + ' '.repeat(11) + styled('13:00:00') + ' \x1b[49m'); - assert.equal(visibleWidth(row), 20); - assert.equal(withStamp(user, 7, 1, '13:00:00', styled, true), user); - const full = [' 表示 👩‍💻 hello world ']; - assert.deepEqual(withStamp(full, 22, 1, '13:00:00', styled, false).map(stripTerminalSequences), [full[0], ' 13:00:00']); -}); - -test('real Pi message components render compact stamps and restore their original behavior on unload', () => { - initTheme('dark', false); - const render = InteractiveMode.prototype.addMessageToChat; - const unmount = mountTranscriptStamps(() => ({ fg: (_color, text) => text }), - (timestamp, _width, assistant) => `${timestamp}${assistant ? ' · 0.50s' : ''}`); - const chat = { - chatContainer: new Container(), - getUserMessageText: message => message.content, - getMarkdownThemeWithSettings: getMarkdownTheme, - getMarkdownTransformers: () => [], - }; - const userMessage = { role: 'user', timestamp: 1234, content: 'Hello' }; - const assistantMessage = { role: 'assistant', timestamp: 5678, content: [{ type: 'text', text: 'Hi' }], stopReason: 'stop' }; - try { - InteractiveMode.prototype.addMessageToChat.call(chat, userMessage); - InteractiveMode.prototype.addMessageToChat.call(chat, assistantMessage); - const [user, assistant] = chat.chatContainer.children; - const rows = component => component.render(40).map(stripTerminalSequences); - assert.equal(rows(user).length, 3); - assert.match(rows(user).at(-1), /^ +1234 $/); - assert.equal(rows(assistant).length, 2); - assert.match(rows(assistant).at(-1), /^ Hi +5678 · 0\.50s $/); - const streaming = new AssistantMessageComponent(); - streaming.updateContent(assistantMessage, true); - assert.doesNotMatch(rows(streaming).join('\n'), /5678/); - streaming.updateContent(assistantMessage, false); - assert.match(rows(streaming).at(-1), /5678 · 0\.50s/); - } finally { - unmount(); - } - assert.equal(InteractiveMode.prototype.addMessageToChat, render); - assert.doesNotMatch(chat.chatContainer.children[0].render(40).join('\n'), /1234/); -}); - -test('/stamp controls clock and latency independently and saves both settings', async t => { - const dir = mkdtempSync(join(tmpdir(), 'pi-stamp-')); - const previousDir = process.env.PI_CODING_AGENT_DIR; - process.env.PI_CODING_AGENT_DIR = dir; - t.after(() => { - if (previousDir === undefined) delete process.env.PI_CODING_AGENT_DIR; - else process.env.PI_CODING_AGENT_DIR = previousDir; - rmSync(dir, { recursive: true, force: true }); - }); - const config = join(dir, 'transcript-timestamps.json'); - writeFileSync(config, JSON.stringify({ showLatency: true })); - initTheme('dark', false); - const handlers = {}, notices = []; - let command; - const timestamp = Date.UTC(2026, 0, 1); - stamp({ on: (name, fn) => { handlers[name] = fn; }, registerCommand: (_name, options) => { command = options; } }); - const ctx = { - mode: 'tui', - sessionManager: { getBranch: () => [{ type: 'custom', customType: 'local-transcript-timestamp', data: { timestamp, latencyMs: 500 } }] }, - ui: { theme: { fg: (_color, text) => text }, notify: text => notices.push(text) }, - }; - t.after(() => handlers.session_shutdown()); - // Pi can populate the transcript before session_start after a reload. - const chat = { - chatContainer: new Container(), - getUserMessageText: message => message.content, - getMarkdownThemeWithSettings: getMarkdownTheme, - getMarkdownTransformers: () => [], - }; - InteractiveMode.prototype.addMessageToChat.call(chat, { role: 'user', timestamp, content: 'Hello' }); - const reply = new AssistantMessageComponent({ role: 'assistant', timestamp, content: [{ type: 'text', text: 'Hi' }] }); - handlers.session_start({ reason: 'reload' }, ctx); - const lastRow = (component = reply) => stripTerminalSequences(component.render(40).at(-1)).trimEnd(); - assert.match(lastRow(chat.chatContainer.children[0]), /\d\d:\d\d:\d\d$/); - await command.handler('', ctx); - assert.match(notices.at(-1), /Timestamps on · response latency on/); - assert.match(lastRow(), /\d\d:\d\d:\d\d · 0\.50s$/); - await command.handler('timestamps off', ctx); - assert.match(lastRow(), /Hi +0\.50s$/); - await command.handler('latency off', ctx); - assert.equal(lastRow(), ' Hi'); - await command.handler('timestamps on', ctx); - assert.match(lastRow(), /\d\d:\d\d:\d\d$/); - assert.deepEqual(JSON.parse(readFileSync(config, 'utf8')), { showTimestamps: true, showLatency: false }); -}); From 4aca193079f4c4045b720dfd25e588ae1a9c70b7 Mon Sep 17 00:00:00 2001 From: Kaleb Dickerson Date: Tue, 1 Dec 2026 22:30:18 +0000 Subject: [PATCH 2/7] pi: review dashboard: Markdown tab, live refresh, inline images, stable port - Context, Code, and Markdown are separate tabs; the status link opens review.page (default Markdown). - Open pages follow the worktree: a conditional snapshot check runs every 3 s, on tab focus, and after Pi answers a draft. - Markdown images are embedded as data URIs from inside the worktree. - Snapshot building yields to the event loop; responses are gzipped, assets are fingerprinted, and connections stay open for tunnelled use. - The server picks a port derived from the working directory so a forward survives restarts. - Submitted reviews and questions render as a Quiet Transcript notice. --- .pi/agent/extensions/review/README.md | 10 +- .pi/agent/extensions/review/context.html | 4 +- .pi/agent/extensions/review/context.js | 13 +- .pi/agent/extensions/review/index.html | 9 +- .pi/agent/extensions/review/index.ts | 29 ++- .pi/agent/extensions/review/notice.ts | 92 ++++++++++ .pi/agent/extensions/review/review.css | 12 ++ .pi/agent/extensions/review/review.js | 170 +++++++++++++++--- .pi/agent/extensions/review/server.ts | 102 +++++++++-- .pi/agent/extensions/review/session.js | 5 +- .pi/agent/extensions/review/sources.ts | 99 +++++++--- .../extensions/review/test/images.test.ts | 21 +++ .../extensions/review/test/notice.test.ts | 42 +++++ .../extensions/review/test/review.test.ts | 40 ++++- .../extensions/review/test/session.test.ts | 8 + .pi/agent/extensions/review/transcript.ts | 28 +++ .pi/tests/slash-completions.test.mjs | 10 +- 17 files changed, 609 insertions(+), 85 deletions(-) create mode 100644 .pi/agent/extensions/review/notice.ts create mode 100644 .pi/agent/extensions/review/test/images.test.ts create mode 100644 .pi/agent/extensions/review/test/notice.test.ts create mode 100644 .pi/agent/extensions/review/transcript.ts diff --git a/.pi/agent/extensions/review/README.md b/.pi/agent/extensions/review/README.md index 54ba505..cbd670d 100644 --- a/.pi/agent/extensions/review/README.md +++ b/.pi/agent/extensions/review/README.md @@ -10,7 +10,7 @@ Requires Pi 1.6.1+, Node 22.19+, and Git. Pull request reviews also require a re npm ci --omit=dev --prefix ~/.pi/agent/extensions/review ``` -Put this directory at `~/.pi/agent/extensions/review` (a symlink works), then restart Pi or run `/reload`. Run `/dashboard` (or `/review`) and click **Open ↗** in the terminal status to open Review; Context is linked from its header. If your terminal does not support clickable links, run `/dashboard url` or `/review url` and open the full URL, including its `#` fragment. Keep the URL private: it grants access to the dashboard. An open tab reconnects at the same URL after `/clear` or `/new`; drafts, review messages, and content inspection reset. `/dashboard stop` closes both tabs’ listener and clears the terminal status. +Put this directory at `~/.pi/agent/extensions/review` (a symlink works), then restart Pi or run `/reload`. Run `/dashboard` (or `/review`) and click **Open ↗** in the terminal status. It opens Markdown by default; set `review.page` in `settings.json` to `"context"`, `"code"`, or `"markdown"` to open a different page. The page header switches between them. `/dashboard url` prints the same link. If your terminal does not support clickable links, run `/dashboard url` or `/review url` and open the full URL, including its `#` fragment. Keep the URL private: it grants access to the dashboard. An open tab reconnects at the same URL after `/clear` or `/new`; drafts, review messages, and content inspection reset. `/dashboard stop` closes both tabs’ listener and clears the terminal status. ## Context @@ -22,15 +22,15 @@ Put this directory at `~/.pi/agent/extensions/review` (a symlink works), then re ## Review - **Worktree:** Pick the worktree Pi started in, a linked Git worktree, or a repository discovered under Pi’s working directory. The rescan button updates the list. Markdown can also use a non-Git working directory. -- **Find files:** Browse folders in **Tree** view or switch to **List**. Use **Files** to hide or show the side panel, and **Review** to collapse the Review to Pi panel; the toggle keeps the draft count visible. **Find file** (`Ctrl`/`⌘` + `K` or `/`) searches changed files or Markdown documents in the current worktree and still works with the panel hidden. Type an abbreviation or parts of the path; use the arrow keys and Enter to open a result. +- **Find files:** Browse folders in **Tree** view or switch to **List**. Use **Files** to hide or show the side panel, and **Review** to collapse the Review to Pi panel; the toggle keeps the draft count visible. Each panel also has its own collapse button at the top, which stays in view while you scroll; a hidden panel leaves a small tab on its edge of the page to bring it back. **Find file** (`Ctrl`/`⌘` + `K` or `/`) searches changed files or Markdown documents in the current worktree and still works with the panel hidden. Type an abbreviation or parts of the path; use the arrow keys and Enter to open a result. - **Code:** Choose unstaged changes (including untracked files), enter a commit ref, or enter a GitHub PR number. View unified or split diffs. Select an old or new line, or Shift-click a second line for a range. - **Markdown:** Pick a document, select text within a rendered block, or click **+** to comment on the whole block. Fenced code blocks with a recognized language tag are syntax-highlighted. Switch to **Source** to see the Markdown as written. The page URL records the worktree and open document (`?&ws=&md=`), so a reload or copied link reopens it, and each worktree reopens in the mode and document it was last viewed in. - **Wrap lines:** On by default in both diff layouts, Markdown source, and rendered code blocks. Uncheck it to scroll long lines horizontally. - **Text size:** Choose **Small**, **Default**, **Large**, or **Extra large** for diffs and Markdown (rendered and source). The browser remembers text size and line wrapping for the current review URL. -- **Ask Pi** sends a question immediately or queues it if Pi is busy. **Submit review** collects the target’s drafts and an optional overall note into one message. Replies appear under **View conversation** and in the terminal. Nothing is posted to GitHub. -- **Refresh** loads a fresh snapshot. If an anchor changed, reattach it to a new excerpt or remove the draft. Drafts survive a browser reload or close and last until the review server stops or the Pi session ends. +- **Ask Pi** sends a question immediately or queues it if Pi is busy. **Submit review** collects the target’s drafts and an optional overall note into one message. Replies appear under **View conversation** and in the terminal. Nothing is posted to GitHub. In the terminal transcript, each message is drawn as a compact `review` notice (target, comment count, note preview; Ctrl+O expands the comments and quoted excerpts) instead of raw JSON; the model still receives the full prompt. The notice uses `transcript.ts`, so it needs Pi's native transcript hook (`native-transcript/insertion.ts`). +- Unstaged changes and Markdown update on their own every few seconds while the tab is visible; commits and PRs update when Pi finishes a message. Updates wait while you have text selected or a dialog open. Reopening a view, or switching back from Context, shows its last snapshot at once and then checks it against the worktree. **Refresh** loads a fresh snapshot right away. If an anchor changed, reattach it to a new excerpt or remove the draft. Drafts survive a browser reload or close and last until the review server stops or the Pi session ends. -The server listens on loopback only. If a port forwarder such as Rex opens the review on a different localhost port, keep the original `#` fragment in the forwarded URL. Each response closes its connection, so a forwarder never reuses a socket the server has dropped. Every request has a 15-second deadline; reads retry once, and anything still stalled shows an error instead of loading forever. The browser reads review data and saves drafts; only Pi, acting on your submitted instructions, can edit project files. Binary files and large or unavailable patches are labeled rather than rendered. +The server listens on loopback only. Each working directory gets the same port every time (in the 30000–32767 range, moving to the next free one if it is taken), so a port forward to it only needs setting up once; the `#` token still changes on every start. If a port forwarder such as Rex opens the review on a different localhost port, keep the original `#` fragment in the forwarded URL. Connections stay open and idle ones are never closed, so a forwarder never reuses a socket the server has dropped and repeat requests skip the cost of opening a new tunneled connection. Every request has a 15-second deadline; reads retry once, and anything still stalled shows an error instead of loading forever. The browser reads review data and saves drafts; only Pi, acting on your submitted instructions, can edit project files. Binary files and large or unavailable patches are labeled rather than rendered. Markdown images that point to files inside the worktree (PNG, JPEG, GIF, WebP, SVG, AVIF; up to 4 MB each and 12 MB per document) are embedded in the page. Remote, missing, or oversized images show their alt text. ## Appearance diff --git a/.pi/agent/extensions/review/context.html b/.pi/agent/extensions/review/context.html index c62fbb6..16799de 100644 --- a/.pi/agent/extensions/review/context.html +++ b/.pi/agent/extensions/review/context.html @@ -7,6 +7,8 @@ + + @@ -17,7 +19,7 @@ - +

Context

What’s in context now, and what each request actually processed.

diff --git a/.pi/agent/extensions/review/context.js b/.pi/agent/extensions/review/context.js index 73ed43f..949d16a 100644 --- a/.pi/agent/extensions/review/context.js +++ b/.pi/agent/extensions/review/context.js @@ -3,9 +3,16 @@ import { createSessionFetch } from './session.js'; const $ = id => document.getElementById(id); const capability = location.hash.slice(1); -const sessionFetch = createSessionFetch(capability); -$('review-link').hash = capability; -$('review-link').search = location.search; +const sessionFetch = createSessionFetch(capability, { epoch: document.querySelector('meta[name=pi-session]')?.content }); +// Code and Markdown links return to the view the review page last recorded in the query. +{ + const [folder, ...rest] = location.search.slice(1).split('&'); + const pick = keys => rest.filter(part => !keys.some(key => part.startsWith(`${key}=`))); + const md = rest.find(part => part.startsWith('md=')); + $('code-link').search = `?${[folder, ...pick(['md', 'view']), 'view=code'].join('&')}`; + $('markdown-link').search = `?${[folder, ...pick(['md', 'view']), md ?? 'md='].join('&')}`; + $('code-link').hash = $('markdown-link').hash = capability; +} // The query starts with the launch folder's name; the review page appends its view after `&`. const dir = decodeURIComponent(location.search.slice(1).split('&')[0]); if (dir) document.title = `${dir} · ${document.title}`; diff --git a/.pi/agent/extensions/review/index.html b/.pi/agent/extensions/review/index.html index 468a262..9e2c604 100644 --- a/.pi/agent/extensions/review/index.html +++ b/.pi/agent/extensions/review/index.html @@ -7,6 +7,9 @@ + + + @@ -14,16 +17,18 @@
Pi Dashboard
Connecting to Pi…
- +
-
+

Loading worktrees…

+ +
diff --git a/.pi/agent/extensions/review/index.ts b/.pi/agent/extensions/review/index.ts index 075c797..eaf41f7 100644 --- a/.pi/agent/extensions/review/index.ts +++ b/.pi/agent/extensions/review/index.ts @@ -20,20 +20,33 @@ function appearanceDefaults(pi: ExtensionAPI) { }; } -export default function (pi: ExtensionAPI) { +const pages = { context: 'Context', code: 'Code', markdown: 'Markdown' } as const; +type Page = keyof typeof pages; +const isPage = (value: unknown): value is Page => typeof value === 'string' && Object.hasOwn(pages, value); +// `review.page` in settings.json picks the page the status link opens; Markdown by default. +function dashboardPage(pi: ExtensionAPI): Page { + const page = ((pi.getSettings() as Record).review as Record | undefined)?.page; + return isPage(page) ? page : 'markdown'; +} + +export default async function (pi: ExtensionAPI) { let live: ReviewServer | undefined; let opening: Promise | undefined; let shuttingDown = false; const context = createContextView(); - // The link opens Review; Context is one click away in the page header. - const linkFor = (cwd: string) => live?.url.replace('/#', `/?${encodeURIComponent(basename(cwd) || cwd)}#`); + const linkFor = (cwd: string, page: Page) => { + const dir = encodeURIComponent(basename(cwd) || cwd); + const query = page === 'code' ? `${dir}&view=code` : page === 'markdown' ? `${dir}&md=` : dir; + return live?.url.replace('/#', `${page === 'context' ? '/context' : '/'}?${query}#`); + }; + let unmountTranscript: (() => void) | undefined; pi.on('context_with_system', event => { if (live) context.observe(event.messages); }); pi.on('session_tree', () => { context.reset(); }); pi.on('session_compact', () => { context.clearObservation(); }); function paint(ctx: ExtensionContext) { if (!ctx.hasUI) return; - const url = linkFor(ctx.cwd); + const url = linkFor(ctx.cwd, dashboardPage(pi)); const latest = live?.delivery?.latest(); const label = latest ? `${latest.kind === 'ask' ? 'Question' : 'Review'} ${latest.state === 'running' || latest.state === 'answered' ? 'sent' : latest.state}` : 'Ready'; if (ctx.mode !== 'tui') { @@ -87,7 +100,7 @@ export default function (pi: ExtensionAPI) { if (!ctx.hasUI) return; const action = args.trim(); if (action === 'stop') { await (await release(ctx))?.close(); return; } - if (action === 'url') { ctx.ui.notify(linkFor(ctx.cwd) ?? `Run /${page} to start the dashboard.`, 'info'); return; } + if (action === 'url') { ctx.ui.notify(linkFor(ctx.cwd, dashboardPage(pi)) ?? `Run /${page} to start the dashboard.`, 'info'); return; } if (action) { ctx.ui.notify(`Usage: /${page}, /${page} url, or /${page} stop`, 'warning'); return; } if (shuttingDown) return; if (live) { paint(ctx); return; } @@ -110,6 +123,7 @@ export default function (pi: ExtensionAPI) { pi.on('agent_settled', event => { live?.delivery?.agentSettled(event.aborted); }); pi.on('session_shutdown', async (event, ctx) => { shuttingDown = true; + unmountTranscript?.(); const server = await release(ctx); if (!server) return; if (event.reason !== 'new') { await server.close(); return; } @@ -120,4 +134,9 @@ export default function (pi: ExtensionAPI) { timer.unref(); processState[handoffKey] = { server, target: event.targetSessionFile, timer }; }); + // Pi's modules are only resolvable inside Pi, so load the transcript renderer here rather than at import time. + unmountTranscript = (await import('./transcript.ts').catch(error => { + if ((error as { code?: string }).code === 'ERR_MODULE_NOT_FOUND') return undefined; + throw error; + }))?.mountReviewTranscript(pi); } diff --git a/.pi/agent/extensions/review/notice.ts b/.pi/agent/extensions/review/notice.ts new file mode 100644 index 0000000..e76f94b --- /dev/null +++ b/.pi/agent/extensions/review/notice.ts @@ -0,0 +1,92 @@ +import type { TranscriptNotice } from '../quiet-transcript/api.ts'; + +type ReviewComment = { + path: string; + oldPath?: string; + start?: number; + end?: number; + side?: string; + excerpt?: string; + selection?: string; + comment?: string; +}; +export type ReviewDetails = { + kind: 'question' | 'submission'; + target: string; + note: string; + comments: readonly ReviewComment[]; +}; + +const header = /^Pi review (question|submission) \[[0-9a-f]+\]\n/; +const isRecord = (value: unknown): value is Record => typeof value === 'object' && value !== null; +const optionalString = (value: unknown) => typeof value === 'string' ? value : undefined; +const optionalNumber = (value: unknown) => typeof value === 'number' ? value : undefined; + +function parseComment(value: unknown): ReviewComment | undefined { + if (!isRecord(value) || typeof value.path !== 'string') return undefined; + return { + path: value.path, oldPath: optionalString(value.oldPath), side: optionalString(value.side), + start: optionalNumber(value.start), end: optionalNumber(value.end), + excerpt: optionalString(value.excerpt), selection: optionalString(value.selection) || undefined, comment: optionalString(value.comment), + }; +} + +function targetLabel(target: unknown): string { + if (!isRecord(target)) return ''; + if (target.mode === 'markdown') return optionalString(target.path) ?? 'markdown'; + const ref = optionalString(target.ref); + switch (target.source) { + case 'unstaged': return 'unstaged changes'; + case 'pr': return ref ? `PR #${ref}` : 'pull request'; + case 'commit': return ref ? `commit ${ref.slice(0, 8)}` : 'commit'; + default: return ''; + } +} + +/** Parse the prompt the dashboard sends; anything else keeps Pi's native row. */ +export function parseReviewPrompt(text: string): ReviewDetails | undefined { + const match = header.exec(text); + const json = match && text.split('\n\n').slice(1).join('\n\n'); + if (!match || !json) return undefined; + try { + const body: unknown = JSON.parse(json); + if (!isRecord(body) || !Array.isArray(body.comments)) return undefined; + const comments = body.comments.map(parseComment); + if (comments.some(comment => !comment)) return undefined; + return { + kind: match[1] === 'question' ? 'question' : 'submission', + target: targetLabel(body.target), + note: typeof body.note === 'string' ? body.note.trim() : '', + comments: comments.filter((comment): comment is ReviewComment => !!comment), + }; + } catch { return undefined; } +} + +const location = ({ path, start, end }: ReviewComment) => + start === undefined ? path : `${path}:${start}${end !== undefined && end !== start ? `–${end}` : ''}`; +const quote = (text: string) => text.split('\n').map(line => `> ${line}`).join('\n'); +const fence = (text: string) => { + const ticks = '`'.repeat(Math.max(3, ...[...text.matchAll(/`+/g)].map(m => m[0].length + 1))); + return `${ticks}\n${text}\n${ticks}`; +}; + +export function describeReview({ kind, target, note, comments }: ReviewDetails): TranscriptNotice { + const count = `${comments.length} ${comments.length === 1 ? 'comment' : 'comments'}`; + const first = comments[0]; + const paths = [...new Set(comments.map(c => c.path))]; + return { + status: kind === 'question' ? 'question' : 'submitted', + tone: 'success', + fields: [target, kind === 'submission' ? count : first && location(first)], + preview: note || comments.find(c => c.comment)?.comment, + details: paths.length > 1 ? [`${paths.length} files`] : undefined, + markdown: [ + note && (kind === 'question' ? `**${note}**` : note), + ...comments.map(c => [ + `**${location(c)}**`, + (c.selection ?? c.excerpt) && fence((c.selection ?? c.excerpt)!), + c.comment && quote(c.comment), + ].filter(Boolean).join('\n\n')), + ].filter(Boolean).join('\n\n---\n\n'), + }; +} diff --git a/.pi/agent/extensions/review/review.css b/.pi/agent/extensions/review/review.css index c12a2dd..10cdb1b 100644 --- a/.pi/agent/extensions/review/review.css +++ b/.pi/agent/extensions/review/review.css @@ -32,3 +32,15 @@ dialog{background:var(--panel);border:1px solid #414955;border-radius:12px;color @media(max-width:990px){.layout{--file-width:171px;--rail-width:210px}.sidebar{padding-inline:6px}.rail{padding-inline:9px}.hero{flex-wrap:wrap}.controls{justify-content:flex-start}.card-bar{flex-wrap:wrap}.ln{padding-right:4px}.diff{--diff-gutter:27px;--diff-sign:15px;--split-gutter:25px;--split-sign:13px}} @media(max-width:810px){.layout{grid-template-columns:var(--file-width) minmax(0,1fr)}.layout[data-files-hidden]{grid-template-columns:minmax(0,1fr)}.layout[data-files-hidden] .rail{grid-column:1}.rail{grid-column:2;border-left:0;border-top:1px solid var(--line);padding:15px}.sidebar{grid-row:span 2}.rail-inner{position:static;max-height:none}.toolbar{gap:7px}.hero{margin-bottom:15px}.top .status>span:nth-child(2){display:none}} @media(max-width:550px){.layout{display:block}.sidebar{padding:8px 12px;border-right:0;border-bottom:1px solid var(--line)}.sidebar-inner{position:static;gap:5px}.file-nav{max-height:32dvh}.sidebar-note{display:none}.top{height:52px}.toolbar{flex-wrap:wrap;padding-inline:12px}.top{padding-inline:12px}.target{gap:5px}.top .badge{display:none}.top .ghost{padding-inline:4px}main{padding-top:14px;padding-bottom:22px}.card-bar .tabs button{padding-inline:6px}.source{padding-right:4px}.diff{--diff-font-size:11px}.document .block-add{opacity:1}} +.document img{display:block;max-width:100%;height:auto;margin:0 0 12px;border-radius:4px}.document .image-missing{color:var(--muted);font-style:italic} + +#main[aria-busy=true]{opacity:.6;cursor:progress;transition:opacity .15s .12s} + +.label-row{display:flex;align-items:center;gap:6px;min-width:0} +.rail-head .icon-btn{margin-left:auto} +.edge-tab{position:fixed;top:30vh;z-index:5;width:22px;height:44px;padding:0;display:grid;place-items:center;background:var(--panel);color:var(--muted);border:1px solid var(--line);cursor:pointer} +.edge-tab[hidden]{display:none} +.edge-tab:hover{background:var(--lift);color:inherit} +.edge-files{left:0;border-left:0;border-radius:0 8px 8px 0} +.edge-rail{right:0;border-right:0;border-radius:8px 0 0 8px} +.edge-tab svg{width:14px;height:14px} diff --git a/.pi/agent/extensions/review/review.js b/.pi/agent/extensions/review/review.js index d59a63b..f51b18b 100644 --- a/.pi/agent/extensions/review/review.js +++ b/.pi/agent/extensions/review/review.js @@ -29,9 +29,10 @@ const tag = (text, style = '') => `${esc(text)} items.map(([id, label, symbol]) => button(action, label, symbol, '', `data-value="${id}" aria-pressed="${id === current}"`)).join(''); const where = a => a.kind === 'file' ? `${a.path} · file` : `${a.path} · ${a.kind === 'diff' ? `${a.side} ` : ''}L${a.start}${a.end === a.start ? '' : `–${a.end}`}`; const capability = location.hash.slice(1); -const sessionFetch = createSessionFetch(capability); +const sessionFetch = createSessionFetch(capability, { epoch: document.querySelector('meta[name=pi-session]')?.content }); $('context-link').hash = capability; $('context-link').search = location.search; +$('code-link').hash = $('markdown-link').hash = capability; // The query is `?[&ws=][&md=]`, so a reload or a shared link reopens the same view. const [dirPart = '', ...viewParts] = location.search.slice(1).split('&'); const dir = decodeURIComponent(dirPart); @@ -80,7 +81,14 @@ const viewed = () => state.visited.get(state.current?.key) ?? new Set(); const selectedPath = () => data()?.mode === 'markdown' ? data().path : activeFile()?.path; const pendingMessage = () => state.messages.find(m => m.state === 'queued' || m.state === 'running'); const codeMode = () => state.mode === 'code'; -const filePaths = () => codeMode() ? data()?.files?.map(f => f.path) ?? [] : state.docs; +const changedPaths = new WeakMap(); +const filePaths = () => { + const snap = data(); + if (!codeMode()) return state.docs; + if (!snap?.files) return []; + if (!changedPaths.has(snap)) changedPaths.set(snap, snap.files.map(f => f.path)); + return changedPaths.get(snap); +}; const currentPath = () => codeMode() ? state.file : state.path; const folderKey = path => JSON.stringify([state.workspace?.id, state.mode, path]); function connected(text, live) { $('connection').textContent = text; $('signal').dataset.connected = String(live); } @@ -113,12 +121,15 @@ function renderToolbar() { ${button('rescan', '', 'refresh', 'icon-btn', 'aria-label="Rescan worktrees" title="Rescan worktrees"')} ${state.mode === 'code' ? `` : ''} ${state.mode === 'code' && state.source !== 'unstaged' ? `
` : ''}`; - $('modes').hidden = !w; - $('modes').innerHTML = tabs([['code','Code','diff'], ['markdown','Markdown','doc']], state.mode, 'mode'); - if (w && !w.git) $('modes').querySelector('[data-value=code]').disabled = true; + $('code-link').hidden = !!w && !w.git; + for (const [link, mode] of [[$('code-link'), 'code'], [$('markdown-link'), 'markdown']]) { + if (state.mode === mode) link.setAttribute('aria-current', 'page'); else link.removeAttribute('aria-current'); + } } $('navigation-controls').innerHTML = `${button('toggle-files','Files','panel','btn','aria-controls="files-panel"')}${button('find-file','Find file','search','btn','title="Find file (Ctrl/⌘+K or /)" aria-keyshortcuts="Control+K Meta+K /"')}${button('toggle-rail','Review','rail','btn','aria-controls="rail-panel"')}`; $('appearance-control').innerHTML = button('appearance','','sun','icon-btn','aria-label="Appearance" title="Appearance"'); +$('files-edge').innerHTML = icon('panel'); +$('rail-edge').innerHTML = icon('rail'); function syncFilePanel() { const hidden = preferences.filesHidden === true; $('layout').toggleAttribute('data-files-hidden', hidden); @@ -126,6 +137,7 @@ function syncFilePanel() { const toggle = $('navigation-controls').querySelector('[data-act=toggle-files]'); toggle.setAttribute('aria-expanded', String(!hidden)); toggle.title = hidden ? 'Show file panel' : 'Hide file panel'; + $('files-edge').hidden = !hidden; } syncFilePanel(); // The draft count stays on the toggle so collapsing the panel doesn't hide pending drafts. @@ -136,6 +148,7 @@ function syncRailPanel() { const toggle = $('navigation-controls').querySelector('[data-act=toggle-rail]'); toggle.setAttribute('aria-expanded', String(!hidden)); toggle.title = hidden ? 'Show review panel' : 'Hide review panel'; + $('rail-edge').hidden = !hidden; toggle.innerHTML = `${icon('rail')}Review${count ? ` ${tag(String(count), 'amber')}` : ''}`; } syncRailPanel(); @@ -143,6 +156,9 @@ function pathLabel(path, withDir) { const {dir, name} = fileInfo(path); return `${esc(name)}${withDir && dir ? `${esc(dir)}` : ''}`; } +let fillFolder = () => {}; +let lastTree = { paths: null, tree: null }; +const treeFor = paths => lastTree.paths === paths ? lastTree.tree : (lastTree = { paths, tree: fileTree(paths) }).tree; function renderSidebar() { const w = state.workspace, paths = filePaths(), current = currentPath(); const scroll = $('files')?.scrollTop ?? 0; @@ -152,12 +168,20 @@ function renderSidebar() { const list = preferences.fileView === 'list'; drafts().forEach(d => counts.set(d.anchor.path, (counts.get(d.anchor.path) ?? 0) + 1)); const file = (path, withDir) => ``; + // Collapsed folders render their contents when first opened, so large trees stay cheap to draw. const grouped = (node, depth) => [...node.folders.values()].map(folder => { const expanded = folderStates.get(folderKey(folder.path)) ?? (depth === 0 || current?.startsWith(folder.path)); - return `
${icon('chevron')}${icon('folder')}${esc(folder.name)}
${grouped(folder, depth + 1)}
`; + return `
${icon('chevron')}${icon('folder')}${esc(folder.name)}
${expanded ? grouped(folder, depth + 1) : ''}
`; }).join('') + node.files.map(({path}) => file(path, false)).join(''); - const rows = list ? paths.map(path => file(path, true)).join('') : grouped(fileTree(paths), 0); - $('sidebar').innerHTML = `
${codeMode() ? 'Changed files' : 'Documents'} · ${paths.length}
${tabs([['tree','Tree',null], ['list','List',null]], list ? 'list' : 'tree', 'file-view')}
+ const tree = list ? undefined : treeFor(paths); + fillFolder = (path, depth, items) => { + let node = tree; + for (const part of path.split('/').slice(0, -1)) node = node?.folders.get(part); + if (node) items.innerHTML = grouped(node, depth + 1); + items.removeAttribute('data-lazy'); + }; + const rows = list ? paths.map(path => file(path, true)).join('') : grouped(tree, 0); + $('sidebar').innerHTML = `
${button('toggle-files','','panel','icon-btn','aria-label="Hide file panel" title="Hide file panel" aria-controls="files-panel" aria-expanded="true"')}
${codeMode() ? 'Changed files' : 'Documents'} · ${paths.length}
${tabs([['tree','Tree',null], ['list','List',null]], list ? 'list' : 'tree', 'file-view')}
`; $('files').scrollTop = scroll; @@ -168,7 +192,7 @@ function renderRail() { const message = state.messages.at(-1); const busy = !!pendingMessage(); syncRailPanel(); - $('rail').innerHTML = `

Review to Pi

${tag(`${count} ${count === 1 ? 'draft' : 'drafts'}`, count ? 'amber' : '')}
+ $('rail').innerHTML = `

Review to Pi

${tag(`${count} ${count === 1 ? 'draft' : 'drafts'}`, count ? 'amber' : '')}${button('toggle-rail','','rail','icon-btn','aria-label="Hide review panel" title="Hide review panel" aria-controls="rail-panel" aria-expanded="true"')}

Drafts stay in this Pi session. Nothing is posted to GitHub.

${stale ? `
${stale} ${stale === 1 ? 'draft needs' : 'drafts need'} reattaching or removing before sending.
` : ''}
${drafts().map(d => `
@@ -281,46 +305,110 @@ function reconcile(d) { const quote = quoteFor(d.anchor); return quote !== undefined && quote === d.quote && quote.length < 4000 ? { ...d, snapshot: data().id } : { ...d, stale: true }; } -async function load({ refresh = false, documents = false } = {}) { +// `keep` leaves the current view on screen, dimmed and inert, until the next one is ready. +async function load({ refresh = false, documents = false, keep = refresh } = {}) { if (state.pending) return; controller?.abort(); controller = new AbortController(); const { signal } = controller; const previous = state.current?.data.id; + const kept = keep && !!state.current; state.current = null; state.error = ''; state.loading = true; state.reattach = null; resetSelection(); - render(); + if (kept) busy(true); else render(); const w = state.workspace; if (!w) return; try { + // A remembered document loads alongside the document list instead of after it. + const fetchSnapshot = target => (!refresh && takePrefetch(w, target)) || api('snapshot', {workspace:w.id, target, cached:!refresh}, signal); + const early = state.mode === 'markdown' && state.path && (documents || refresh) ? Object.assign(fetchSnapshot(currentTarget()), {path: state.path}) : undefined; + early?.catch(() => {}); if (state.mode === 'markdown' && (documents || refresh)) { state.docs = await api('documents', {workspace:w.id, fresh:!!refresh}, signal); if (signal.aborted) return; if (!state.docs.includes(state.path)) state.path = state.docs[0] ?? null; } syncView(); - const target = state.mode === 'code' ? { mode: 'code', source: state.source, ref: state.refs[state.source] ?? '' } : { mode: 'markdown', path: state.path }; - if (target.mode === 'markdown' ? !target.path : target.source === 'pr' && !target.ref) return; - const result = await api('snapshot', {workspace:w.id, target}, signal); + const target = currentTarget(); + if (!target) return; + const result = await (early && state.path === early.path ? early : fetchSnapshot(target)); if (signal.aborted) return; state.current = result; const snap = result.data; if (snap.mode === 'code' && !snap.files.some(f => f.path === state.file)) state.file = snap.files[0]?.path; result.drafts = result.drafts.map(reconcile); if (refresh) toast(previous === snap.id ? 'Snapshot is up to date.' : 'Snapshot refreshed.'); + // A remembered snapshot shows at once; confirm it against the worktree right after. + if (result.cached) queueMicrotask(() => void sync()); } catch (error) { if (!signal.aborted) state.error = error.message; } finally { if (!signal.aborted) { state.loading = false; + busy(false); render(); $('finder')?.dispatchEvent(new Event('input')); } } } +function busy(on) { + $('main').inert = on; + if (on) $('main').setAttribute('aria-busy', 'true'); else $('main').removeAttribute('aria-busy'); +} +// Hovering a document starts loading it, so the click usually finds it ready. +const prefetched = new Map(); +const prefetchKey = (w, target) => target.mode === 'markdown' ? `${w.id}\0${target.path}` : undefined; +function prefetch(path) { + const w = state.workspace, target = { mode: 'markdown', path }; + const key = prefetchKey(w, target); + if (!w || codeMode() || path === state.path || prefetched.has(key)) return; + const request = api('snapshot', {workspace:w.id, target, cached:true}); + request.catch(() => prefetched.delete(key)); + prefetched.set(key, request); + if (prefetched.size > 6) prefetched.delete(prefetched.keys().next().value); + setTimeout(() => { if (prefetched.get(key) === request) prefetched.delete(key); }, 15_000); +} +function takePrefetch(w, target) { + const key = prefetchKey(w, target), request = key && prefetched.get(key); + if (request) prefetched.delete(key); + return request; +} +$('sidebar').addEventListener('pointerover', e => { + const row = e.target.closest?.('.file-row[data-act=file]'); + if (row) prefetch(row.dataset.value); +}); +function currentTarget() { + const target = state.mode === 'code' ? { mode: 'code', source: state.source, ref: state.refs[state.source] ?? '' } : { mode: 'markdown', path: state.path }; + return (target.mode === 'markdown' ? !target.path : target.source === 'pr' && !target.ref) ? undefined : target; +} +// Unstaged changes and Markdown follow the worktree; commits and PRs update when Pi finishes a message. +const followsWorktree = () => state.mode === 'markdown' || state.source === 'unstaged'; +let syncing = false; +const userBusy = () => state.loading || state.pending || state.reattach || state.selection || $('dialog').open || !!getSelection()?.toString(); +async function sync() { + const current = state.current, w = state.workspace, target = currentTarget(); + if (syncing || !current || !w || !target || document.hidden || userBusy()) return; + syncing = true; + try { + const result = await api('snapshot', {workspace:w.id, target, known:current.data.id}); + if (state.current !== current || result.unchanged || result.data.id === current.data.id || userBusy()) return; + const snap = result.data; + if (snap.mode === 'code' && !snap.files.some(f => f.path === state.file)) state.file = snap.files[0]?.path; + const before = current.drafts.filter(d => d.stale).length; + state.current = result; + result.drafts = result.drafts.map(reconcile); + const stale = state.current.drafts.filter(d => d.stale).length; + render(); + if (stale > before) toast(`${stale} ${stale === 1 ? 'draft needs' : 'drafts need'} reattaching after the file changed.`); + } catch { + // A later tick or Refresh retries; the connection status reports outages. + } finally { syncing = false; } +} +setInterval(() => { if (followsWorktree()) void sync(); }, 3000); +document.addEventListener('visibilitychange', () => { if (!document.hidden) void sync(); }); function fileAnchor() { return { kind: 'file', path: selectedPath() }; } function mdAnchor(index, selection = '') { const block = data().blocks[index]; @@ -359,7 +447,11 @@ function openFile(path) { folderStates.set(folderKey(folder), true); } if (codeMode()) { state.file = path; render(); } - else if (state.path !== path || !data()) { state.path = path; void load(); } + else if (state.path !== path || !data()) { + state.path = path; + for (const row of $('sidebar').querySelectorAll('.file-row[aria-current]')) row.setAttribute('aria-current', String(row.dataset.value === path)); + void load({keep:true}); + } else renderSidebar(); } function openFinder() { @@ -558,6 +650,9 @@ function syncView() { const search = `?${[dirPart, ...view].join('&')}`; if (search !== location.search) history.replaceState(history.state, '', `${search}${location.hash}`); $('context-link').search = search; + const named = view.filter(part => part.startsWith('ws=')); + $('code-link').search = `?${[dirPart, ...named, 'view=code'].join('&')}`; + $('markdown-link').search = `?${[dirPart, ...named, `md=${encodeURIComponent(path ?? '').replaceAll('%2F', '/')}`].join('&')}`; } function setWorkspace(w, view = savedViews()[w.id]) { state.workspace = w; @@ -567,6 +662,15 @@ function setWorkspace(w, view = savedViews()[w.id]) { renderToolbar(); void load({documents:true}); } +// Code and Markdown are pages of the dashboard that switch in place; modified clicks still open a new tab. +for (const [id, mode] of [['code-link', 'code'], ['markdown-link', 'markdown']]) $(id).addEventListener('click', e => { + if (e.defaultPrevented || e.button || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return; + e.preventDefault(); + if (state.pending || state.mode === mode || !state.workspace) return; + state.mode = mode; + renderToolbar(); + void load({documents:true}); +}); document.addEventListener('change', e => { if (e.target.id === 'wrap-lines') { savePreference('wrapLines', e.target.checked); @@ -607,6 +711,8 @@ document.addEventListener('click', async e => { const details = btn.parentElement; details.open = !details.open; folderStates.set(folderKey(value), details.open); + const items = details.querySelector(':scope > .folder-items'); + if (details.open && items.hasAttribute('data-lazy')) fillFolder(value, Number(btn.dataset.depth), items); return; } if (act === 'rescan') { @@ -616,7 +722,6 @@ document.addEventListener('click', async e => { } catch (error) { toast(error.message); } return; } - if (act === 'mode') { state.mode = value; renderToolbar(); void load({documents:true}); $('modes').querySelector('[aria-pressed=true]').focus(); return; } if (act === 'refresh') { void load({refresh:true}); return; } if (act === 'messages') { modal('Conversation in Pi', '
'); paintMessages(); return; } if (act === 'file') { @@ -647,21 +752,44 @@ async function poll() { try { const messages = await api('messages'); if (JSON.stringify(messages) !== JSON.stringify(state.messages)) { + const finished = messages.some(m => (m.state === 'answered' || m.state === 'failed') && state.messages.find(o => o.id === m.id)?.state !== m.state); state.messages = messages; + if (finished) void sync(); renderRail(); paintMessages(); } connected(pendingMessage() ? `Pi session · ${pendingMessage().state}` : 'Pi session connected', true); } catch { connected('Pi session disconnected', false); } setTimeout(poll, pendingMessage() ? 1000 : 3000); } +// The worktree list and appearance defaults from this tab's last visit, so a reload or a return from +// Context starts loading the view without waiting for them; the fresh copies replace them when they arrive. +const bootKey = 'pi-dashboard.boot'; +function rememberedBoot() { + try { const value = JSON.parse(sessionStorage.getItem(bootKey) ?? 'null'); return Array.isArray(value?.workspaces) && value.workspaces.length ? value : undefined; } catch { return undefined; } +} +function openLinkedView() { + // A view in the URL wins over the remembered one for its worktree. + const named = linkedView.get('ws'), linked = named === null ? state.workspaces[0] : state.workspaces.find(w => w.name === named); + const fromUrl = linked && (linkedView.has('md') ? { mode: 'markdown', path: linkedView.get('md') || null } : named !== null || linkedView.get('view') === 'code' ? { mode: 'code' } : undefined); + if (linked && fromUrl) setWorkspace(linked, fromUrl); else setWorkspace(state.workspaces[0]); +} +let started = false; async function start() { + const remembered = started ? undefined : rememberedBoot(); + started = true; + if (remembered) { + state.workspaces = remembered.workspaces; appearanceDefaults = remembered.appearance ?? {}; + applyAppearance(); + openLinkedView(); + } try { - [state.workspaces, appearanceDefaults] = await Promise.all([api('workspaces'), api('appearance')]); + const [workspaces, defaults] = await Promise.all([api('workspaces'), api('appearance')]); + try { sessionStorage.setItem(bootKey, JSON.stringify({ workspaces, appearance: defaults })); } catch {} + appearanceDefaults = defaults; applyAppearance(); - // A view in the URL wins over the remembered one for its worktree. - const named = linkedView.get('ws'), linked = named === null ? state.workspaces[0] : state.workspaces.find(w => w.name === named); - const fromUrl = linked && (linkedView.has('md') ? { mode: 'markdown', path: linkedView.get('md') || null } : named !== null ? { mode: 'code' } : undefined); - if (linked && fromUrl) setWorkspace(linked, fromUrl); else setWorkspace(state.workspaces[0]); + const current = remembered && workspaces.find(w => w.id === state.workspace?.id); + state.workspaces = workspaces; + if (current) { state.workspace = current; renderToolbar(); } else openLinkedView(); void poll(); } catch (error) { connected('Not connected', false); diff --git a/.pi/agent/extensions/review/server.ts b/.pi/agent/extensions/review/server.ts index 2e9279e..b2e685e 100644 --- a/.pi/agent/extensions/review/server.ts +++ b/.pi/agent/extensions/review/server.ts @@ -1,6 +1,8 @@ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto'; import { readFile } from 'node:fs/promises'; -import { createServer, type IncomingMessage, type ServerResponse } from 'node:http'; +import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'; +import { promisify } from 'node:util'; +import { constants as zlib, gzip } from 'node:zlib'; import { createReviewDelivery, DeliveryRejected, type DeliveryPort, type ReviewDelivery } from './delivery.ts'; import { diffQuote, type Side } from './diff.ts'; import { discover, documents, snapshot, type Snapshot, type Target, type Workspace } from './sources.ts'; @@ -128,6 +130,8 @@ function createReviewSession(...[cwd, port, defaults = {}, context]: SessionBind sendJson(res, status, value); } const snapshots = new Map(); + // The newest snapshot ID for each target key. + const latest = new Map(); const drafts = new Map(); const delivery = createReviewDelivery(port); let submittedTarget: string | undefined; @@ -204,14 +208,23 @@ function createReviewSession(...[cwd, port, defaults = {}, context]: SessionBind if (req.url === '/api/snapshot') { const workspace = await getWorkspace(body.workspace), target = parseTarget(body.target); const key = createHash('sha256').update(JSON.stringify([workspace.id, target])).digest('hex').slice(0, 24); + // Opening a page may show the last snapshot of this target at once; the page then syncs in the background. + const recent = body.cached === true ? snapshots.get(latest.get(key) ?? '') : undefined; + if (recent) { + const list = drafts.get(key) ?? []; + return reply(res, 200, { key, data: recent.data, drafts: list, version: draftVersion(list), cached: true }); + } const cancelled = new AbortController(); res.once('close', () => cancelled.abort()); - const data = await bounded(() => snapshot(workspace, target, AbortSignal.any([abort.signal, cancelled.signal]))); + const data = await bounded(() => snapshot(workspace, target, AbortSignal.any([abort.signal, cancelled.signal]), id => snapshots.get(id)?.data)); ensureActive(); if (!snapshots.has(data.id) && snapshots.size >= 8) snapshots.delete(snapshots.keys().next().value!); snapshots.delete(data.id); snapshots.set(data.id, { key, workspace, target, data }); + latest.set(key, data.id); const list = drafts.get(key) ?? []; + // A caller that already has this snapshot only needs to know it is current. + if (body.known === data.id) return reply(res, 200, { key, unchanged: true, drafts: list, version: draftVersion(list) }); return reply(res, 200, { key, data, drafts: list, version: draftVersion(list) }); } if (req.url !== '/api/drafts' && req.url !== '/api/send') throw new HttpError(404, 'Not found.'); @@ -264,33 +277,63 @@ function createReviewSession(...[cwd, port, defaults = {}, context]: SessionBind } return { + epoch, handle, delivery, dispose: () => { abort.abort(); delivery.dispose(); - snapshots.clear(); drafts.clear(); submittedTarget = undefined; + snapshots.clear(); latest.clear(); drafts.clear(); submittedTarget = undefined; }, }; } +const tagOf = (data: Buffer) => createHash('sha256').update(data).digest('base64url').slice(0, 16); +// Rewrite asset references to carry their content hash. Leaf modules come first so an importer's hash covers its imports. +async function versionedAssets() { + const files: string[] = Object.values(assets).map(([file]) => file); + const raw = new Map(await Promise.all(files.map(async file => [file, (await readFile(new URL(file, import.meta.url))).toString('utf8')] as const))); + const done = new Map(); + const version = (file: string): Buffer => { + const cached = done.get(file); + if (cached) return cached; + const text = raw.get(file)!.replace(/(from '\.\/|(?:href|src)="\/)([\w-]+\.(?:js|css))(?=['"])/g, (match, lead: string, name: string) => + raw.has(name) && name !== file ? `${lead}${name}?v=${tagOf(version(name))}` : match); + const data = Buffer.from(text); + done.set(file, data); + return data; + }; + return files.map(version); +} + +// A directory keeps the same port across restarts, so a port forward to it only needs setting up once. The +// range sits below the OS's ephemeral ports, so it doesn't collide with other programs' random ports; a +// taken port moves to the next, and the last resort is any free port. +const portBase = 30000, portSpan = 2700, portTries = 8; +export function preferredPorts(root: string): number[] { + const start = createHash('sha256').update(root).digest().readUInt32BE(0) % portSpan; + return [...Array.from({ length: portTries }, (_, i) => portBase + (start + i) % portSpan), 0]; +} +const listen = (server: Server, port: number) => new Promise((resolve, reject) => { + server.once('error', reject); + server.listen({ host: '127.0.0.1', port }, () => { server.off('error', reject); resolve(); }); +}); + export async function startReviewServer(...binding: SessionBinding): Promise { const capability = randomBytes(24).toString('base64url'); const auth = Buffer.from(`Bearer ${capability}`); - const assetData = await Promise.all(Object.values(assets).map(([file]) => readFile(new URL(file, import.meta.url)))); + const assetData = await versionedAssets(); + const assetTags = assetData.map(data => `"${tagOf(data)}"`); let session: ReturnType | undefined = createReviewSession(...binding); function detach() { session?.dispose(); session = undefined; } async function handle(req: IncomingMessage, res: ServerResponse) { - // One request per connection: port forwarders (such as Rex) pool upstream sockets and don't notice when - // an idle keep-alive socket is closed, so a request sent on it hangs. - res.setHeader('Connection', 'close'); res.setHeader('Cache-Control', 'no-store'); res.setHeader('X-Content-Type-Options', 'nosniff'); res.setHeader('Referrer-Policy', 'no-referrer'); - res.setHeader('Content-Security-Policy', "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'"); + res.setHeader('Content-Security-Policy', "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src data:; base-uri 'none'; frame-ancestors 'none'; form-action 'none'"); const { host, origin } = req.headers; // Port forwarders can present a different loopback address to the browser. const authority = host?.match(loopbackAuthority); @@ -301,7 +344,18 @@ export async function startReviewServer(...binding: SessionBinding): Promise', `\n `)) : assetData[index]!; + const etag = epoch ? `"${tagOf(body)}"` : assetTags[index]!; + // Pages link assets by content hash, so a versioned asset never changes; pages themselves revalidate. + const versioned = !html && new URLSearchParams(req.url?.split('?')[1]).get('v') === assetTags[index]!.slice(1, -1); + res.setHeader('Cache-Control', versioned ? 'private, max-age=31536000, immutable' : 'no-cache'); + res.setHeader('ETag', etag); + if (req.headers['if-none-match'] === etag) { res.writeHead(304).end(); return; } + send(res, 200, { 'Content-Type': type }, body).catch(() => res.destroy()); return; } const header = Buffer.from(req.headers.authorization ?? ''); @@ -317,11 +371,19 @@ export async function startReviewServer(...binding: SessionBinding): Promise((resolve, reject) => { - server.once('error', reject); - server.listen({ host: '127.0.0.1', port: 0 }, () => { server.off('error', reject); resolve(); }); - }); + // Port forwarders (such as Rex) pool upstream sockets and don't notice when an idle one is closed, so a + // request sent on it hangs. Never time out idle connections; opening one through a tunnel costs far more + // than a request on an open one. + server.keepAliveTimeout = 0; + server.maxConnections = 64; + for (const port of preferredPorts(binding[0])) { + try { + await listen(server, port); + break; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'EADDRINUSE') throw error; + } + } const address = server.address(); if (!address || typeof address === 'string') throw new Error('Could not determine the review server address.'); return { @@ -336,6 +398,16 @@ export async function startReviewServer(...binding: SessionBinding): Promise, body: Buffer) { + const accepts = /\bgzip\b/.test(String(res.req?.headers['accept-encoding'] ?? '')); + if (!accepts || body.length < gzipFloor) { res.writeHead(status, headers).end(body); return; } + const packed = await compress(body, { level: zlib.Z_BEST_SPEED }); + if (!res.destroyed) res.writeHead(status, { ...headers, 'Content-Encoding': 'gzip', Vary: 'Accept-Encoding' }).end(packed); +} function sendJson(res: ServerResponse, status: number, value: unknown) { - res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' }).end(JSON.stringify(value)); + send(res, status, { 'Content-Type': 'application/json; charset=utf-8' }, Buffer.from(JSON.stringify(value))).catch(() => res.destroy()); } diff --git a/.pi/agent/extensions/review/session.js b/.pi/agent/extensions/review/session.js index 9cfc17e..f8824c0 100644 --- a/.pi/agent/extensions/review/session.js +++ b/.pi/agent/extensions/review/session.js @@ -6,9 +6,10 @@ export class TimeoutError extends Error {} // Every request gets a deadline, so a connection that stalls (for example in a port forwarder) // surfaces as an error instead of a page stuck loading. Read-only requests are retried once. -export function createSessionFetch(capability, { timeoutMs = requestTimeoutMs } = {}) { +// `epoch` is the session the page was served under, when the page carries one. +export function createSessionFetch(capability, { timeoutMs = requestTimeoutMs, epoch: initial } = {}) { const authorization = { Authorization: `Bearer ${capability}` }; - let epoch, reloading = false; + let epoch = initial ? Promise.resolve(initial) : undefined, reloading = false; const timed = async (url, { signal, retry, ...options }) => { const deadline = AbortSignal.timeout(timeoutMs); try { diff --git a/.pi/agent/extensions/review/sources.ts b/.pi/agent/extensions/review/sources.ts index bc7776e..2aabf92 100644 --- a/.pi/agent/extensions/review/sources.ts +++ b/.pi/agent/extensions/review/sources.ts @@ -2,7 +2,7 @@ import { execFile } from 'node:child_process'; import { createHash } from 'node:crypto'; import { constants } from 'node:fs'; import { open, readdir, realpath, stat } from 'node:fs/promises'; -import { basename, extname, isAbsolute, join, relative, sep } from 'node:path'; +import { basename, extname, isAbsolute, join, posix, relative, sep } from 'node:path'; import { promisify } from 'node:util'; import hljs from 'highlight.js/lib/common'; import { marked, Renderer } from 'marked'; @@ -113,7 +113,7 @@ const within = (root: string, path: string) => { const rel = relative(root, path); return rel !== '' && rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel); }; -async function readWorkingFile(root: string, path: string, limit: number) { +async function readWorkingBytes(root: string, path: string, limit: number) { const requested = join(root, path); const resolved = await realpath(requested).catch(() => undefined); if (!resolved || !within(root, resolved) || resolved !== requested) throw new Error('File is missing or is a symbolic link.'); @@ -130,16 +130,59 @@ async function readWorkingFile(root: string, path: string, limit: number) { n += bytesRead; } if (n !== stat.size) throw new Error('File changed while reading. Refresh to retry.'); - const bytes = buffer.subarray(0, n); - if (bytes.includes(0)) throw new Error('Binary file.'); - try { return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes); } - catch { throw new Error('File is not UTF-8 text.'); } + return buffer.subarray(0, n); } finally { await handle.close(); } } +async function readWorkingFile(root: string, path: string, limit: number) { + const bytes = await readWorkingBytes(root, path, limit); + if (bytes.includes(0)) throw new Error('Binary file.'); + try { return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes); } + catch { throw new Error('File is not UTF-8 text.'); } +} + +// Images are inlined as data URIs: the browser can't send the dashboard's bearer token with . +const imageTypes: Record = { + '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml', '.avif': 'image/avif', +}; +const imageLimit = 4 * 1024 * 1024, imagesLimit = 12 * 1024 * 1024; +export type ImageSources = ReadonlyMap; + +/** Workspace-relative path for a Markdown image reference, or undefined for remote, absolute, or escaping ones. */ +export function imagePath(document: string, href: string): string | undefined { + if (/^[a-z][a-z\d+.-]*:|^\/\/|^\//i.test(href)) return undefined; + let decoded: string; + try { decoded = decodeURI(href.replace(/[?#].*$/, '')); } catch { return undefined; } + const path = posix.normalize(posix.join(posix.dirname(document.split(sep).join('/')), decoded)); + return path && path !== '.' && !path.startsWith('../') && path !== '..' && imageTypes[extname(path).toLowerCase()] ? path : undefined; +} + +async function loadImages(workspace: Workspace, document: string, source: string): Promise> { + const hrefs = new Set(); + marked.walkTokens(marked.lexer(source, markdownOptions), token => { if (token.type === 'image') hrefs.add(token.href); }); + const images = new Map(); + let remaining = imagesLimit; + for (const href of hrefs) { + const path = imagePath(document, href); + if (!path || remaining <= 0) continue; + try { + const bytes = await readWorkingBytes(workspace.root, path.split('/').join(sep), Math.min(imageLimit, remaining)); + remaining -= bytes.length; + images.set(href, `data:${imageTypes[extname(path).toLowerCase()]};base64,${bytes.toString('base64')}`); + } catch { /* Missing or oversized images render as their alt text. */ } + } + return images; +} const markdownOptions = { gfm: true, breaks: false }; -function markdownRenderer() { +const escapeAttr = (value: string) => value.replace(/[&<>"']/g, c => `&#${c.charCodeAt(0)};`); +function markdownRenderer(images: ImageSources) { const renderer = new Renderer(); + renderer.image = ({ href, title, text }) => { + const src = images.get(href); + const alt = escapeAttr(text); + if (!src) return `[image: ${alt || escapeAttr(href)}]`; + return `${alt}`; + }; const plainCode = renderer.code.bind(renderer); let budget = 96 * 1024; renderer.code = token => { @@ -154,20 +197,22 @@ function markdownRenderer() { return renderer; } const sanitize = (html: string) => sanitizeHtml(html, { - allowedTags: [...sanitizeHtml.defaults.allowedTags, 'del', 's', 'input'], - allowedAttributes: { a: ['href', 'title', 'target', 'rel'], code: ['class'], span: ['class'], ol: ['start'], input: ['type', 'disabled', 'checked'] }, - allowedClasses: { code: ['hljs', /^language-[\w+-]+$/], span: [/^hljs-[\w-]+$/, /^[\w-]+_+$/] }, - allowedSchemes: ['http', 'https', 'mailto'], allowProtocolRelative: false, + allowedTags: [...sanitizeHtml.defaults.allowedTags, 'del', 's', 'input', 'img'], + allowedAttributes: { a: ['href', 'title', 'target', 'rel'], code: ['class'], span: ['class'], ol: ['start'], input: ['type', 'disabled', 'checked'], img: ['src', 'alt', 'title'] }, + allowedClasses: { code: ['hljs', /^language-[\w+-]+$/], span: [/^hljs-[\w-]+$/, /^[\w-]+_+$/, 'image-missing'] }, + allowedSchemes: ['http', 'https', 'mailto'], allowedSchemesByTag: { img: ['data'] }, allowProtocolRelative: false, transformTags: { a: sanitizeHtml.simpleTransform('a', { target: '_blank', rel: 'noopener noreferrer' }), input: (_tag, attrs) => ({ tagName: 'input', attribs: { type: 'checkbox', disabled: '', ...(attrs.checked !== undefined ? {checked: ''} : {}) } }), }, - exclusiveFilter: frame => frame.tag === 'a' && !/^(?:https?:\/\/|mailto:)/i.test(frame.attribs.href ?? '') ? 'excludeTag' : false, + exclusiveFilter: frame => frame.tag === 'a' && !/^(?:https?:\/\/|mailto:)/i.test(frame.attribs.href ?? '') ? 'excludeTag' + // Only images the renderer inlined survive; raw HTML and remote sources are dropped. + : frame.tag === 'img' && !/^data:image\//.test(frame.attribs.src ?? ''), }); -export function renderBlocks(source: string): Block[] { +export function renderBlocks(source: string, images: ImageSources = new Map()): Block[] { const tokens = marked.lexer(source, markdownOptions); - const options = { ...markdownOptions, renderer: markdownRenderer() }; + const options = { ...markdownOptions, renderer: markdownRenderer(images) }; const blocks: Block[] = []; let offset = 0, line = 1; for (const token of tokens) { @@ -265,8 +310,10 @@ function highlightedLines(source: string, language: string): string[] { }).split('\n'); } -function highlightDiffs(files: Change[]) { - let budget = 512 * 1024; +// Highlighting is the costliest step of a snapshot; yield between chunks so the server keeps answering other requests. +const yieldEvery = 32 * 1024; +async function highlightDiffs(files: Change[], signal: AbortSignal) { + let budget = 512 * 1024, sinceYield = 0; for (const file of files) for (const side of ['new', 'old'] as const) { const path = side === 'old' ? file.oldPath ?? file.path : file.path; const language = extname(path).slice(1).toLowerCase(); @@ -277,6 +324,12 @@ function highlightDiffs(files: Change[]) { const source = rows.map(row => row.text).join('\n'); if (source.length > Math.min(budget, 64 * 1024)) continue; budget -= source.length; + sinceYield += source.length; + if (sinceYield > yieldEvery) { + sinceYield = 0; + await new Promise(resolve => setImmediate(resolve)); + signal.throwIfAborted(); + } const lines = highlightedLines(source, language); if (lines.length !== rows.length) continue; rows.forEach((row, i) => { row.html ??= lines[i]; }); @@ -284,11 +337,14 @@ function highlightDiffs(files: Change[]) { } } -export async function snapshot(workspace: Workspace, target: Target, signal: AbortSignal): Promise { +// `reuse` returns an already-built snapshot with the same ID, skipping highlighting and rendering. +export async function snapshot(workspace: Workspace, target: Target, signal: AbortSignal, reuse: (id: string) => Snapshot | undefined = () => undefined): Promise { if (target.mode === 'code') { if (!workspace.git) throw new Error('Select a Git worktree for code review.'); const data = await codeChanges(workspace, target, signal); const id = digest([workspace.id, target, data]); + const built = reuse(id); + if (built) return built; let remaining = 24_000; for (const file of data.files) { let rows = 0; @@ -302,12 +358,15 @@ export async function snapshot(workspace: Workspace, target: Target, signal: Abo return true; }); } - highlightDiffs(data.files); + await highlightDiffs(data.files, signal); return { id, mode: 'code', ...data }; } if (!(await isDocument(workspace, target.path, signal))) throw new Error('This document isn’t available in the selected worktree.'); const source = (await readWorkingFile(workspace.root, target.path, 384 * 1024)).replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n'); - const blocks = renderBlocks(source); - const id = digest([workspace.id, target, source]); + const images = await loadImages(workspace, target.path, source); + const id = digest([workspace.id, target, source, [...images.values()].map(digest)]); + const built = reuse(id); + if (built) return built; + const blocks = renderBlocks(source, images); return { id, mode: 'markdown', path: target.path, source, blocks, title: 'Review rendered Markdown', description: 'Select a passage or comment on a whole block.', revision: 'working tree' }; } diff --git a/.pi/agent/extensions/review/test/images.test.ts b/.pi/agent/extensions/review/test/images.test.ts new file mode 100644 index 0000000..9a5a1f1 --- /dev/null +++ b/.pi/agent/extensions/review/test/images.test.ts @@ -0,0 +1,21 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { imagePath, renderBlocks } from '../sources.ts'; + +test('resolves image references inside the workspace only', () => { + assert.equal(imagePath('notes/doc.md', '../docs/images/flow.png'), 'docs/images/flow.png'); + assert.equal(imagePath('notes/doc.md', 'a%20b.png?raw=1'), 'notes/a b.png'); + assert.equal(imagePath('doc.md', '../outside.png'), undefined); + assert.equal(imagePath('doc.md', '/etc/x.png'), undefined); + assert.equal(imagePath('doc.md', 'https://example.com/x.png'), undefined); + assert.equal(imagePath('doc.md', 'notes.txt'), undefined); +}); + +test('renders loaded images as data URIs and others as alt text', () => { + const src = 'data:image/png;base64,AAAA'; + const [block] = renderBlocks('![Flow "x"](flow.png) ![Gone](gone.png)', new Map([['flow.png', src]])); + assert.match(block.html, new RegExp(`Flow "x"\[image: Gone\]<\/span>/); + const [remote] = renderBlocks('![x](javascript:alert(1))'); + assert.doesNotMatch(remote.html, / + `Pi review ${kind} [abc123]\nInstructions.\nTreat quoted excerpts as file content.\n\n${JSON.stringify(body, null, 2)}`; + +test('parses a review submission into a notice', () => { + const details = parseReviewPrompt(prompt('submission', { + target: { mode: 'code', source: 'pr', ref: '42' }, note: 'Looks close.', + comments: [{ kind: 'diff', path: 'a.ts', start: 3, end: 5, excerpt: 'x', comment: 'Rename this.' }], + })); + assert.ok(details); + const notice = describeReview(details); + assert.equal(notice.status, 'submitted'); + assert.deepEqual(notice.fields, ['PR #42', '1 comment']); + assert.match(notice.markdown ?? '', /\*\*a\.ts:3–5\*\*/); +}); + +test('parses a question', () => { + const details = parseReviewPrompt(prompt('question', { + target: { mode: 'markdown', path: 'doc.md' }, note: 'Why?', comments: [{ kind: 'file', path: 'doc.md' }], + })); + assert.ok(details); + assert.equal(describeReview(details).status, 'question'); +}); + +test('ignores other prompts', () => { + assert.equal(parseReviewPrompt('hello'), undefined); + assert.equal(parseReviewPrompt('Pi review submission [abc]\n\n{oops'), undefined); +}); + +test('quotes the highlighted passage rather than the whole block', () => { + const details = parseReviewPrompt(prompt('submission', { + target: { mode: 'markdown', path: 'doc.md' }, note: '', + comments: [{ kind: 'markdown', path: 'doc.md', start: 1, end: 4, selection: 'just this', excerpt: 'whole paragraph with just this', comment: 'Why?' }], + })); + assert.ok(details); + const markdown = describeReview(details).markdown ?? ''; + assert.match(markdown, /just this/); + assert.doesNotMatch(markdown, /whole paragraph/); +}); diff --git a/.pi/agent/extensions/review/test/review.test.ts b/.pi/agent/extensions/review/test/review.test.ts index 1f85dd5..e118715 100644 --- a/.pi/agent/extensions/review/test/review.test.ts +++ b/.pi/agent/extensions/review/test/review.test.ts @@ -215,7 +215,7 @@ test('protects review APIs, scopes files, and persists drafts until session shut const {base,raw,api} = client(server.url); const page = await raw('/'); assert.equal(page.status, 200); - assert.equal(page.headers.get('connection'), 'close'); + assert.equal(page.headers.get('connection'), 'keep-alive'); assert.equal((await raw('/api/workspaces', undefined, {authorization:'Bearer bad'})).status, 401); assert.equal((await raw('/api/workspaces', undefined, {Origin:'https://different.example'})).status, 403); const badHost = await new Promise(resolve => request(new URL('/api/workspaces', base), {headers:{Host:'elsewhere.invalid'}}, r=>{r.resume(); resolve(r.statusCode);}).end()); @@ -306,7 +306,7 @@ test('dashboard and review share a listener, keep review delivery, and revoke th setStatus:(key:string,text?:string)=>{assert.equal(key,'pi-dashboard'); status=text;}, setWidget:(_key:string,content?:string[])=>{widget=content;}, }}; - review({getSettings:()=>({review:{theme:'mocha',markdownTheme:'paper',ignored:'not sent'}}), registerCommand:(name:string, {handler}: {handler:(...args: any[])=>any})=>handlers.set(name,handler), on:(name:string,fn:(...args: any[])=>any)=>handlers.set(name,fn), sendUserMessage:(text:string,options:unknown)=>{assert.deepEqual(options,{deliverAs:'followUp'}); sends.push(text);}} as unknown as Parameters[0]); + review({getSettings:()=>({review:{theme:'mocha',markdownTheme:'paper',ignored:'not sent',page:'nope'}}), registerCommand:(name:string, {handler}: {handler:(...args: any[])=>any})=>handlers.set(name,handler), on:(name:string,fn:(...args: any[])=>any)=>handlers.set(name,fn), sendUserMessage:(text:string,options:unknown)=>{assert.deepEqual(options,{deliverAs:'followUp'}); sends.push(text);}} as unknown as Parameters[0]); const run = handlers.get('review')!, dashboard = handlers.get('dashboard')!; t.after(() => dashboard('stop',ctx)); await dashboard('',ctx); @@ -317,9 +317,9 @@ test('dashboard and review share a listener, keep review delivery, and revoke th assert.ok(url); assert.equal(widget, undefined); assert.equal(new URL(url).pathname, '/'); - assert.equal(new URL(url).search, '?repo'); + assert.equal(new URL(url).search, '?repo&md='); await dashboard('url',ctx); - assert.equal(notifications.at(-1),url); + assert.equal(notifications.at(-1), url); await run('',{...ctx,mode:'rpc'}); assert.deepEqual(widget, ['Dashboard · Ready', url]); await run('',ctx); @@ -423,3 +423,35 @@ test('fresh sessions keep the URL but isolate drafts, inspection grants, and del await fresh.shutdown('quit'); await assert.rejects(next.raw('/')); }); + +test('pages carry the session epoch and link assets by content hash', async t => { + const {root} = await fixture(t); + const server = await startReviewServer(root, idlePi); + t.after(server.close); + const base = new URL(server.url); + const page = await (await fetch(new URL('/', base))).text(); + assert.equal(page.match(/name="pi-session" content="(\w+)"/)?.[1], await client(server.url).epoch()); + const script = page.match(/src="(\/review\.js\?v=[\w-]+)"/)?.[1]; + assert.ok(script); + const versioned = await fetch(new URL(script, base)); + assert.match(versioned.headers.get('cache-control') ?? '', /immutable/); + assert.match(await versioned.text(), /from '\.\/session\.js\?v=[\w-]+'/); + const plain = await fetch(new URL('/review.js', base)); + assert.equal(plain.headers.get('cache-control'), 'no-cache'); + assert.equal((await fetch(new URL('/review.js', base), {headers:{'If-None-Match':plain.headers.get('etag')!}})).status, 304); +}); + +test('keeps a directory on the same port and falls back to a free one when it is taken', async t => { + const { root } = await fixture(t); + const { preferredPorts } = await import('../server.ts'); + const ports = preferredPorts('/work/a'); + assert.deepEqual(ports, preferredPorts('/work/a')); + assert.equal(new Set(ports).size, ports.length); + assert.equal(ports.at(-1), 0); + assert.ok(ports.slice(0, -1).every(p => p >= 30000 && p < 32768)); + const first = await startReviewServer(root, idlePi); + const second = await startReviewServer(root, idlePi); + t.after(() => { void first.close(); void second.close(); }); + assert.equal(Number(new URL(first.url).port), preferredPorts(root)[0]); + assert.notEqual(new URL(first.url).port, new URL(second.url).port); +}); diff --git a/.pi/agent/extensions/review/test/session.test.ts b/.pi/agent/extensions/review/test/session.test.ts index 022a9d2..971c141 100644 --- a/.pi/agent/extensions/review/test/session.test.ts +++ b/.pi/agent/extensions/review/test/session.test.ts @@ -40,3 +40,11 @@ test('retries a stalled read once and reports a stalled write as a timeout', asy await assert.rejects(pending, (error: Error) => error.name === 'AbortError'); assert.equal(seen.get('/api/documents'), 1); }); + +test('uses the epoch the page was served with instead of asking for one', async t => { + const seen = await stallingServer(t); + const sessionFetch = createSessionFetch('cap', { timeoutMs: 150, epoch: 'page' }); + const read = await sessionFetch('workspaces'); + assert.deepEqual(await read.json(), { path: '/api/workspaces', epoch: 'page' }); + assert.equal(seen.get('/api/session'), undefined); +}); diff --git a/.pi/agent/extensions/review/transcript.ts b/.pi/agent/extensions/review/transcript.ts new file mode 100644 index 0000000..2bd1c76 --- /dev/null +++ b/.pi/agent/extensions/review/transcript.ts @@ -0,0 +1,28 @@ +import type { AgentMessage } from '@earendil-works/pi-agent-core'; +import type { ExtensionAPI } from '@earendil-works/pi-coding-agent'; +import { registerTranscriptDecoration } from '../native-transcript/insertion.ts'; +import { createTranscriptNoticeRenderer } from '../quiet-transcript/api.ts'; +import { describeReview, parseReviewPrompt, type ReviewDetails } from './notice.ts'; + +const reviewMessageType = 'review:message'; + +const textOf = (message: AgentMessage) => message.role !== 'user' ? '' + : typeof message.content === 'string' ? message.content + : message.content.flatMap(part => part.type === 'text' ? [part.text] : []).join(''); + +/** Draw the dashboard's prompt as a notice. The model still receives the original text. */ +export function mountReviewTranscript(pi: ExtensionAPI): () => void { + pi.registerMessageRenderer(reviewMessageType, + createTranscriptNoticeRenderer('review', ({ details }) => details && describeReview(details))); + return registerTranscriptDecoration('review', ({ message, displayMessage }) => { + if (message.role !== 'user' || displayMessage.role !== 'user') return; + const text = textOf(message); + const details = parseReviewPrompt(text); + if (!details) return; + return { + displayMessage: { + role: 'custom', customType: reviewMessageType, content: text, display: true, details, timestamp: message.timestamp, + }, + }; + }); +} diff --git a/.pi/tests/slash-completions.test.mjs b/.pi/tests/slash-completions.test.mjs index 552a27f..52d89ad 100644 --- a/.pi/tests/slash-completions.test.mjs +++ b/.pi/tests/slash-completions.test.mjs @@ -5,14 +5,13 @@ import md from '../agent/extensions/md-viewer/index.ts'; import stash from '../agent/extensions/prompt-stash.ts'; import review from '../agent/extensions/review/index.ts'; import stock from '../agent/extensions/stock.ts'; -import stamp from '../agent/extensions/transcript-timestamps.ts'; const commands = []; const pi = { - on() {}, registerShortcut() {}, registerEntryRenderer() {}, + on() {}, registerShortcut() {}, registerEntryRenderer() {}, registerMessageRenderer() {}, registerCommand: (name, options) => commands.push({ name, ...options }), }; -for (const extension of [md, stash, review, stock, stamp]) extension(pi); +for (const extension of [md, stash, review, stock]) extension(pi); const provider = new CombinedAutocompleteProvider(commands, process.cwd()); const suggest = line => provider.getSuggestions([line], 0, line.length, { signal: new AbortController().signal }); const values = async line => (await suggest(line))?.items.map(item => item.value) ?? []; @@ -30,10 +29,7 @@ test('/md suggests actions and style presets without restricting file paths', as assert.deepEqual(await values('/md notes/README.md'), []); }); -test('/stamp and /stock suggest supported options', async () => { - assert.deepEqual(await values('/stamp '), ['timestamps on', 'timestamps off', 'latency on', 'latency off']); - assert.equal(await complete('/stamp timestamps of'), '/stamp timestamps off'); - assert.equal(await complete('/stamp latency of'), '/stamp latency off'); +test('/stock suggests supported options', async () => { assert.equal(await complete('/stock OF'), '/stock off'); assert.deepEqual(await values('/stock AAPL'), []); }); From 3d5011e8aef8b9f30053f8d259ff503832587420 Mon Sep 17 00:00:00 2001 From: Kaleb Dickerson Date: Tue, 1 Dec 2026 22:30:18 +0000 Subject: [PATCH 3/7] pi: session-prs status notice --- .pi/agent/extensions/session-prs/README.md | 8 +++--- .pi/agent/extensions/session-prs/events.ts | 17 +++--------- .pi/agent/extensions/session-prs/index.ts | 19 +++++++------ .../extensions/session-prs/status-notice.ts | 19 +++++++++++++ .pi/agent/extensions/session-prs/view.ts | 27 ++++++++++++------- .pi/tests/session-prs-status.test.ts | 22 +++++++++++++++ .pi/tests/session-prs-view.test.mjs | 16 +++++++++++ .pi/tests/session-prs.test.mjs | 20 +++++++------- 8 files changed, 103 insertions(+), 45 deletions(-) create mode 100644 .pi/agent/extensions/session-prs/status-notice.ts create mode 100644 .pi/tests/session-prs-status.test.ts diff --git a/.pi/agent/extensions/session-prs/README.md b/.pi/agent/extensions/session-prs/README.md index 2bafa51..9d4619b 100644 --- a/.pi/agent/extensions/session-prs/README.md +++ b/.pi/agent/extensions/session-prs/README.md @@ -1,6 +1,6 @@ # Session PRs -Tracks pull requests for a Pi session through a `pr` tool the agent calls, shows them in a quiet widget, and tells the agent when one needs attention. Rows look like `PR · owner/repo#42 ↗ · open · CI passed · Title`. On narrow terminals the title and secondary details give way to the clickable PR number. +Tracks pull requests for a Pi session through a `pr` tool the agent calls, shows them in a quiet widget, and tells the agent when one needs attention. Rows look like `PR · owner/repo#42 ↗ · open · CI passed · approved · Title`. When GitHub reports a review decision, the row shows `approved`, `review required`, or `changes requested`. On narrow terminals the title and secondary details give way to the clickable PR number. ## `pr` tool @@ -14,11 +14,9 @@ The tool description and prompt guidelines tell the agent to track right after c ## Status messages -Open PRs (and PRs of unknown state) are polled once a minute in the terminal, on session start, and when navigating `/tree`. Merged and closed PRs are not polled. A `session-prs.status.v1` message is queued for the next turn (it never starts a turn on its own) when: +Open PRs (and PRs of unknown state) are polled once a minute in the terminal, on session start, and when navigating `/tree`. Merged and closed PRs are not polled. A `session-prs.status.v1` message is queued for the next turn (it never starts a turn on its own) when a PR is merged or closed. The message tells the agent to call `pr untrack`, and each is sent once per session, including across reloads. CI and review changes only update the widget. -* a PR is merged or closed — the message tells the agent to call `pr untrack`; each is sent once per session, including across reloads -* CI starts failing on a PR whose earlier status was known -* changes are requested on a PR whose earlier review status was known +In the transcript it renders as a Quiet Transcript notice, `▸ pr · merged · owner/repo#42 · Title`, and expanding it shows the URL. The agent receives the full text. If GitHub is unreachable the widget keeps its last known status. diff --git a/.pi/agent/extensions/session-prs/events.ts b/.pi/agent/extensions/session-prs/events.ts index c303fae..6caf260 100644 --- a/.pi/agent/extensions/session-prs/events.ts +++ b/.pi/agent/extensions/session-prs/events.ts @@ -1,6 +1,6 @@ import { ciOutcome, clean, type Metadata } from './view.ts'; -export type PrEvent = 'merged' | 'closed' | 'ci-failed' | 'changes-requested'; +export type PrEvent = 'merged' | 'closed'; export const urlPattern = /^https:\/\/[A-Za-z0-9.-]+\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]*$/; const shorthand = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)#([1-9][0-9]*)$/; @@ -19,16 +19,9 @@ export const prLabel = (url: string): string => { return `${owner}/${repo}#${number}`; }; -/** Events that `next` shows relative to `prev`. Terminal states always report; the rest need a known prior snapshot. */ -export const detectEvents = (prev: Metadata | undefined, next: Metadata): PrEvent[] => { - if (next.state === 'MERGED') return ['merged']; - if (next.state === 'CLOSED') return ['closed']; - const events: PrEvent[] = []; - if (!prev) return events; - if (ciOutcome(next.statusCheckRollup) === 'failed' && ciOutcome(prev.statusCheckRollup) !== 'failed') events.push('ci-failed'); - if (next.reviewDecision === 'CHANGES_REQUESTED' && prev.reviewDecision !== 'CHANGES_REQUESTED') events.push('changes-requested'); - return events; -}; +/** The terminal state a PR has reached, if any. */ +export const detectEvent = ({ state }: Metadata): PrEvent | undefined => + state === 'MERGED' ? 'merged' : state === 'CLOSED' ? 'closed' : undefined; export const eventMessage = (url: string, event: PrEvent): string => { const label = prLabel(url); @@ -36,8 +29,6 @@ export const eventMessage = (url: string, event: PrEvent): string => { switch (event) { case 'merged': return `${label} was merged. It is no longer polled. ${untrack}`; case 'closed': return `${label} was closed without merging. It is no longer polled. ${untrack}`; - case 'ci-failed': return `CI failed on ${label}. Inspect the failing checks if you own this PR.`; - case 'changes-requested': return `Changes were requested on ${label}. Review the feedback if you own this PR.`; } }; diff --git a/.pi/agent/extensions/session-prs/index.ts b/.pi/agent/extensions/session-prs/index.ts index 84d281a..aa55914 100644 --- a/.pi/agent/extensions/session-prs/index.ts +++ b/.pi/agent/extensions/session-prs/index.ts @@ -1,10 +1,11 @@ import { execFile } from 'node:child_process'; import { StringEnum } from '@earendil-works/pi-ai'; -import { truncateToWidth, Text } from '@earendil-works/pi-tui'; +import { truncateToWidth } from '@earendil-works/pi-tui'; import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent'; import { Type } from 'typebox'; -import { detectEvents, eventMessage, parsePrTarget, prLabel, summarize, urlPattern, type PrEvent } from './events.ts'; +import { detectEvent, eventMessage, parsePrTarget, prLabel, summarize, urlPattern, type PrEvent } from './events.ts'; import { renderPrRow, type Metadata } from './view.ts'; +import { renderPrStatus, type PrStatusDetails } from './status-notice.ts'; const TRACK = 'session-prs.track.v1'; const UNTRACK = 'session-prs.untrack.v1'; @@ -71,16 +72,19 @@ export default function sessionPrs(pi: ExtensionAPI) { if (nudged.has(key)) return; nudged.add(key); pi.sendMessage( - { customType: STATUS, content: eventMessage(url, event), display: true, details: { url, event } }, + { + customType: STATUS, content: eventMessage(url, event), display: true, + details: { url, event, title: meta.get(url)?.title } satisfies PrStatusDetails, + }, { deliverAs: 'nextTurn' }, ); }; const apply = (url: string, data: Metadata, notify: boolean) => { - const previous = meta.get(url); meta.set(url, data); draw(); - if (notify) for (const event of detectEvents(previous, data)) nudge(url, event); + const event = notify ? detectEvent(data) : undefined; + if (event) nudge(url, event); }; /** Fetches current status for a tracked PR. Resolves false when GitHub could not be read. */ @@ -143,7 +147,7 @@ export default function sessionPrs(pi: ExtensionAPI) { label: 'PR', description: [ 'Track pull requests for this session. Tracked PRs show in a status widget for the user and are polled every minute;', - 'when one is merged or closed, or CI fails or changes are requested, a status message arrives in the transcript.', + 'when one is merged or closed, a status message arrives in the transcript.', 'Actions: track (url) starts tracking an existing PR; untrack (url) stops; refresh (url optional) fetches current state, CI and review status for one tracked PR or all of them.', 'Call track right after creating or being handed any PR you own or are shepherding, and untrack once it is merged or closed.', ].join(' '), @@ -181,8 +185,7 @@ export default function sessionPrs(pi: ExtensionAPI) { }, }); - pi.registerMessageRenderer(STATUS, (message, { outputPad }, theme) => - new Text(theme.fg('dim', 'PR · ') + theme.fg('muted', String(message.content)), outputPad, 0)); + pi.registerMessageRenderer(STATUS, renderPrStatus); pi.registerCommand('prs', { description: '[refresh|clear] — Refresh session PRs or dismiss the widget', diff --git a/.pi/agent/extensions/session-prs/status-notice.ts b/.pi/agent/extensions/session-prs/status-notice.ts new file mode 100644 index 0000000..5f9a39d --- /dev/null +++ b/.pi/agent/extensions/session-prs/status-notice.ts @@ -0,0 +1,19 @@ +import { createTranscriptNoticeRenderer } from '../quiet-transcript/api.ts'; +import { prLabel, urlPattern, type PrEvent } from './events.ts'; + +export type PrStatusDetails = { url: string; event: PrEvent; title?: string }; + +const presentation = { + merged: { status: 'merged', tone: 'success' }, + closed: { status: 'closed', tone: 'muted' }, +} as const satisfies Record; + +/** `▸ pr · merged · owner/repo#N · title`; expanded adds the URL. */ +export const renderPrStatus = createTranscriptNoticeRenderer('pr', ({ details }) => { + if (!details || !urlPattern.test(details.url) || !(details.event in presentation)) return; + return { + ...presentation[details.event], + fields: [prLabel(details.url), details.title], + details: [details.url], + }; +}); diff --git a/.pi/agent/extensions/session-prs/view.ts b/.pi/agent/extensions/session-prs/view.ts index 4cc4cdc..b1e0e10 100644 --- a/.pi/agent/extensions/session-prs/view.ts +++ b/.pi/agent/extensions/session-prs/view.ts @@ -8,7 +8,7 @@ export type Metadata = { state?: string; isDraft?: boolean; statusCheckRollup?: { conclusion?: string; state?: string }[]; - reviewDecision?: string; + reviewDecision?: string | null; }; export const clean = (value: unknown) => typeof value === 'string' @@ -35,6 +35,12 @@ const ciField = (checks: Metadata['statusCheckRollup']): Field | undefined => { if (outcome === 'pending') return ['dim', 'CI pending']; }; +const reviewField = (decision: Metadata['reviewDecision']): Field | undefined => { + if (decision === 'APPROVED') return ['success', 'approved']; + if (decision === 'CHANGES_REQUESTED') return ['warning', 'changes requested']; + if (decision === 'REVIEW_REQUIRED') return ['muted', 'review required']; +}; + export function renderPrRow(url: string, metadata?: Metadata, width = Infinity, theme?: Pick): string { if (width < 1) return ''; const fg = (color: Color, text: string) => theme?.fg(color, text) ?? text; @@ -50,18 +56,21 @@ export function renderPrRow(url: string, metadata?: Metadata, width = Infinity, let room = width - visibleWidth(row); const state = metadata?.isDraft && metadata.state === 'OPEN' ? 'draft' : clean(metadata?.state).toLowerCase(); const ci = ciField(metadata?.statusCheckRollup); + const review = reviewField(metadata?.reviewDecision); const fields: Field[] = []; if (state) fields.push([state === 'merged' ? 'success' : 'muted', state]); if (ci) fields.push(ci); - const cost = ([, text]: Field) => visibleWidth(separator + text); - // Keep a failure visible when there is only room for one status field. - const fitting = ci?.[0] === 'error' && cost(ci) <= room && fields.reduce((sum, field) => sum + cost(field), 0) > room - ? [ci] : fields; - for (const field of fitting) { - if (cost(field) > room) continue; - row += sep + fg(...field); - room -= cost(field); + if (review) fields.push(review); + // Budget for failed checks and requested changes first, but keep the usual display order. + const priority = ([color]: Field) => color === 'error' ? 0 : color === 'warning' ? 1 : 2; + const fitting = new Set(); + for (const field of fields.toSorted((a, b) => priority(a) - priority(b))) { + const cost = visibleWidth(separator + field[1]); + if (cost > room) continue; + fitting.add(field); + room -= cost; } + for (const field of fields) if (fitting.has(field)) row += sep + fg(...field); const title = clean(metadata?.title); if (title && room > visibleWidth(separator) + 1) { row += sep + fg('muted', truncateToWidth(title, Math.min(160, room - visibleWidth(separator)), '…')); diff --git a/.pi/tests/session-prs-status.test.ts b/.pi/tests/session-prs-status.test.ts new file mode 100644 index 0000000..57afda6 --- /dev/null +++ b/.pi/tests/session-prs-status.test.ts @@ -0,0 +1,22 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import type { Theme } from '@earendil-works/pi-coding-agent'; +import { renderPrStatus, type PrStatusDetails } from '../agent/extensions/session-prs/status-notice.ts'; + +const theme = { fg: (_color: string, text: string) => text } as Theme; +const url = 'https://github.com/acme/dots/pull/19'; +const render = (details: Partial = {}, expanded = false) => + renderPrStatus({ + role: 'custom', customType: 'session-prs.status.v1', display: true, timestamp: 0, + content: 'acme/dots#19 was merged.', details: { url, event: 'merged', title: 'Pi: codemode view', ...details }, + }, { expanded, outputPad: 1, keyText: () => '', keyHint: () => '' }, theme)?.render(80); + +test('PR status renders as a quiet notice heading', () => { + assert.deepEqual(render(), [' ▸ pr · merged · acme/dots#19 · Pi: codemode view']); + assert.deepEqual(render({}, true), [' ▾ pr · merged · acme/dots#19 · Pi: codemode view', ` ╰ ${url}`]); + assert.deepEqual(render({ event: 'closed', title: undefined }), [' ▸ pr · closed · acme/dots#19']); +}); + +test('PR status without valid details falls back to the default renderer', () => { + assert.equal(render({ url: 'not a url' }), undefined); +}); diff --git a/.pi/tests/session-prs-view.test.mjs b/.pi/tests/session-prs-view.test.mjs index ea953ea..f79aaa1 100644 --- a/.pi/tests/session-prs-view.test.mjs +++ b/.pi/tests/session-prs-view.test.mjs @@ -18,6 +18,22 @@ test('PR rows use semantic theme roles and label state without relying on color' assert.equal(stripTerminalSequences(renderPrRow(url, { state: 'MERGED', isDraft: true })), 'PR · acme/repo#42 ↗ · merged'); }); +test('PR rows show GitHub review decisions as compact status fields', () => { + const render = reviewDecision => stripTerminalSequences(renderPrRow(url, { state: 'OPEN', reviewDecision, title })); + assert.equal(render('APPROVED'), `PR · acme/repo#42 ↗ · open · approved · ${title}`); + assert.equal(render('REVIEW_REQUIRED'), `PR · acme/repo#42 ↗ · open · review required · ${title}`); + assert.equal(render('CHANGES_REQUESTED'), `PR · acme/repo#42 ↗ · open · changes requested · ${title}`); + for (const noDecision of [null, '', 'UNKNOWN']) { + assert.equal(render(noDecision), `PR · acme/repo#42 ↗ · open · ${title}`); + } +}); + +test('requested changes stay visible on a narrow row when checks are not failing', () => { + const row = renderPrRow(url, { ...failed, statusCheckRollup: [{ state: 'PENDING' }], reviewDecision: 'CHANGES_REQUESTED' }, 40); + assert.equal(stripTerminalSequences(row), 'PR · acme/repo#42 ↗ · changes requested'); + assert.equal(getOsc8LinkAtColumn(row, 5), url); +}); + test('narrow PR rows drop secondary details before losing the clickable identity', () => { const at = width => stripTerminalSequences(renderPrRow(url, failed, width)); assert.equal(at(34), 'PR · acme/repo#42 ↗ · CI failed'); diff --git a/.pi/tests/session-prs.test.mjs b/.pi/tests/session-prs.test.mjs index 4ae09e0..1df8be0 100644 --- a/.pi/tests/session-prs.test.mjs +++ b/.pi/tests/session-prs.test.mjs @@ -3,7 +3,7 @@ import { test } from 'node:test'; import { mkdtempSync, writeFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { detectEvents, parsePrTarget, summarize } from '../agent/extensions/session-prs/events.ts'; +import { detectEvent, parsePrTarget, summarize } from '../agent/extensions/session-prs/events.ts'; import extension from '../agent/extensions/session-prs/index.ts'; const url = 'https://github.com/acme/repo/pull/42'; @@ -16,13 +16,11 @@ test('parsePrTarget', () => { assert.equal(parsePrTarget('nope'), undefined); }); -test('detectEvents', () => { - assert.deepEqual(detectEvents(undefined, { state: 'MERGED' }), ['merged']); - assert.deepEqual(detectEvents(undefined, { state: 'CLOSED' }), ['closed']); - assert.deepEqual(detectEvents(undefined, { state: 'OPEN', statusCheckRollup: fail }), []); - assert.deepEqual(detectEvents({ state: 'OPEN', statusCheckRollup: pass }, { state: 'OPEN', statusCheckRollup: fail }), ['ci-failed']); - assert.deepEqual(detectEvents({ state: 'OPEN', statusCheckRollup: fail }, { state: 'OPEN', statusCheckRollup: fail }), []); - assert.deepEqual(detectEvents({ state: 'OPEN' }, { state: 'OPEN', reviewDecision: 'CHANGES_REQUESTED' }), ['changes-requested']); +test('detectEvent', () => { + assert.equal(detectEvent({ state: 'MERGED' }), 'merged'); + assert.equal(detectEvent({ state: 'CLOSED' }), 'closed'); + assert.equal(detectEvent({ state: 'OPEN', statusCheckRollup: fail }), undefined); + assert.equal(detectEvent({ state: 'OPEN', reviewDecision: 'CHANGES_REQUESTED' }), undefined); assert.match(summarize(url, { title: 'T', state: 'OPEN', statusCheckRollup: pass, reviewDecision: 'APPROVED' }), /acme\/repo#42 · open · CI passed · review: approved · T/); }); @@ -48,7 +46,7 @@ const harness = (state) => { const tick = () => new Promise(r => setTimeout(r, 150)); test('track, refresh, untrack via tool', async () => { - const h = harness({ state: 'OPEN', statusCheckRollup: pass }); + const h = harness({ state: 'OPEN', statusCheckRollup: pass, reviewDecision: 'REVIEW_REQUIRED' }); try { await h.handlers.session_start({}, h.ctx); const t = h.tool(); @@ -56,9 +54,11 @@ test('track, refresh, untrack via tool', async () => { const tracked = await t.execute('1', { action: 'track', url: 'acme/repo#42' }); assert.match(tracked.content[0].text, /Tracking acme\/repo#42 · open · CI passed/); assert.deepEqual(h.entries.map(e => e.customType), ['session-prs.track.v1']); - h.setState({ state: 'OPEN', statusCheckRollup: fail }); + assert.match(h.widgets.at(-1)[0], /open · CI passed · review required/); + h.setState({ state: 'OPEN', statusCheckRollup: fail, reviewDecision: 'APPROVED' }); const refreshed = await t.execute('2', { action: 'refresh' }); assert.match(refreshed.content[0].text, /CI failed/); + assert.match(h.widgets.at(-1)[0], /open · CI failed · approved/); assert.equal(h.messages.length, 0); const untracked = await t.execute('3', { action: 'untrack', url }); assert.match(untracked.content[0].text, /Stopped tracking/); From 1678aacf9c91216598b2abacb5876bc3d4cf7786 Mon Sep 17 00:00:00 2001 From: Kaleb Dickerson Date: Tue, 1 Dec 2026 22:30:19 +0000 Subject: [PATCH 4/7] pi: quiet-transcript call renderer and bash wrapping updates --- .pi/agent/extensions/quiet-transcript.ts | 4 +- .../quiet-transcript/call-renderer.ts | 51 +++++++++++--- .../extensions/quiet-transcript/call-store.ts | 11 +-- .../extensions/quiet-transcript/config.ts | 2 + .pi/tests/quiet-call-renderer.test.ts | 70 ++++++++++++++++++- 5 files changed, 122 insertions(+), 16 deletions(-) diff --git a/.pi/agent/extensions/quiet-transcript.ts b/.pi/agent/extensions/quiet-transcript.ts index d1e77a9..9e1ee4d 100644 --- a/.pi/agent/extensions/quiet-transcript.ts +++ b/.pi/agent/extensions/quiet-transcript.ts @@ -17,7 +17,9 @@ // highlights: { [toolName]: boolean } (override success previews in Highlights) // lead: "icon" | "dot" | "icon+dot" | "bar" // levels: { [toolName]: "persistent" | "inline" | "inline-until-done" | "minimal" | "hidden" | "native" } -// inline-until-done folds when the next call appears or the run settles; persistent keeps its block; native keeps the tool's renderer. +// inline stays open until the run settles. inline-until-done keeps running calls and the latest inlineKeep calls +// open until the run settles. persistent keeps its block; native keeps the tool's renderer. +// inlineKeep: recent inline-until-done calls kept open during a run (default 3) // levels.thinking uses the same modes; inline-until-done folds when the assistant message finishes. // levels.bash: "native" also keeps Pi's frame for user shell commands (! and !!). // skillReads: label SKILL.md reads as skill calls (display only; uses the read level) diff --git a/.pi/agent/extensions/quiet-transcript/call-renderer.ts b/.pi/agent/extensions/quiet-transcript/call-renderer.ts index 92b9e83..c4c9b70 100644 --- a/.pi/agent/extensions/quiet-transcript/call-renderer.ts +++ b/.pi/agent/extensions/quiet-transcript/call-renderer.ts @@ -77,6 +77,7 @@ const oneLine = (s: string): string => s.replace(/\s+/g, " ").trim(); const OUTPUT_ROWS = 12; const READ_PREVIEW_ROWS = 3; const HIGHLIGHT_ROWS = 6; +const SHORT_OUTPUT_ROWS = 5; const outputRail = (th: Theme, last: boolean): string => th.fg("borderMuted", last ? "╰ " : "│ "); const sep = (th: Theme): string => th.fg("borderMuted", " · "); @@ -122,16 +123,17 @@ export const createCallRenderer = ( const levelOf = (name: string) => toolLevel(config, name); const showsLiveBlock = (c: Call): boolean => { const level = levelOf(c.name); - return level === "inline" || (level === "inline-until-done" && (isActive(c) || transcript.isLatest(c.id))); + return level === "inline" || + (level === "inline-until-done" && (isActive(c) || transcript.isRecent(c.id, config.inlineKeep))); }; - // Standalone live blocks split the compact runs on either side. - const liveGroups = (ids: readonly string[]): string[][] => { + // Standalone blocks split the compact runs on either side. + const splitGroups = (ids: readonly string[], isBlock: (c: Call) => boolean): string[][] => { const out: string[][] = []; let run: string[] | undefined; for (const id of ids) { const call = transcript.getCall(id); - if (call && showsLiveBlock(call)) { + if (call && isBlock(call)) { out.push([id]); run = undefined; } else { @@ -405,6 +407,34 @@ export const createCallRenderer = ( return withRight(d, title + args + tail, right); }; + // A shell call's header shows the whole command, wrapped under where it starts. + // Outside Expanded the command shows at most COMMAND_ROWS rows. The rail runs down the continuation rows and ends + // on the last one when no output follows. + const COMMAND_ROWS = 2; + const wrappedCommandHeader = (d: Draw, c: Call, indent: string, full: boolean, more: boolean): string[] => { + const { th } = d; + const title = `${indent}${leadFor(th, c)} ${toolTitle(th, c)} `; + const meta = metaOf(c); + const tail = meta ? th.fg("error", ` · ${meta}`) : ""; + const right = rightOf(th, c); + const command = stripTerminalSequences(str(c.args.command) ?? "").trim().replaceAll("\t", " "); + const room = leftRoom(d, right) - visibleWidth(d.pad + title); + if (!command || room < 8) return [callHeader(d, c, indent)]; + const wrapped = command.split("\n").flatMap((line) => wrapTextWithAnsi(highlight(line, "bash"), room)); + const rows = full || wrapped.length <= COMMAND_ROWS ? wrapped : wrapped.slice(0, COMMAND_ROWS); + if (rows.length < wrapped.length) rows[rows.length - 1] = truncateToWidth(rows.at(-1)!, room - 2, "") + th.fg("dim", " …"); + const align = " ".repeat(Math.max(0, visibleWidth(title) - visibleWidth(indent) - 2)); + const lines = rows.map((row, i) => { + const last = i === rows.length - 1; + const text = row + (last ? tail : ""); + return i === 0 + ? withRight(d, title + text, right) + : fit(d, `${indent}${outputRail(th, last && !more)}${align}${text}`); + }); + // In Expanded a blank rail row separates a multi-row command from its output, as for codemode. + return full && rows.length > 1 && more ? [...lines, fit(d, `${indent}${outputRail(th, false)}`)] : lines; + }; + const summaryTitle = (th: Theme, icon: string, label?: string): string => th.fg("muted", label ? `${icon} ${label}` : icon); @@ -616,8 +646,11 @@ export const createCallRenderer = ( const output = view === "highlights" && body.length && c.status !== "fail" ? "" : stripTerminalSequences(c.output).trimEnd().replaceAll("\t", " "); const room = Math.max(1, d.width - visibleWidth(d.pad + indent) - 2); const lines = output ? wrapTextWithAnsi(output, room) : []; - const cap = maxRows ?? (kindOf(c.name) === "read" && c.status !== "fail" ? READ_PREVIEW_ROWS : OUTPUT_ROWS); - const tail = full ? lines : lines.slice(-cap); + const kind = kindOf(c.name); + const cap = maxRows ?? (kind === "read" && c.status !== "fail" ? READ_PREVIEW_ROWS + : kind === "bash" || kind === "codemode" ? SHORT_OUTPUT_ROWS : OUTPUT_ROWS); + // Expanded bash shows the whole command and the tail of its output. + const tail = full && kind !== "bash" ? lines : lines.slice(-(full ? OUTPUT_ROWS : cap)); const hidden = lines.length - tail.length; // A blank rail row separates the body from the output. const rest = tail.length || hidden > 0; @@ -625,7 +658,9 @@ export const createCallRenderer = ( fit(d, `${indent}${outputRail(th, i === all.length - 1 && !rest)}${l}`)); return [ // The body draws the call itself, so the header skips its one-line summary. - callHeader(d, c, indent, !body.length), + ...(kind === "bash" && !body.length + ? wrappedCommandHeader(d, c, indent, full, tail.length > 0) + : [callHeader(d, c, indent, !body.length)]), ...bodyRows, ...(hidden > 0 ? [fit(d, `${indent}${outputRail(th, false)}${th.fg("dim", `… ${hidden} earlier lines`)}`)] : []), ...tail.map((l, i) => fit(d, `${indent}${outputRail(th, i === tail.length - 1)}${th.fg(c.status === "fail" ? "error" : "muted", l)}`)), @@ -870,7 +905,7 @@ export const createCallRenderer = ( } if (showsLiveBlock(self)) return standalone(); - const run = liveGroups(ids).find((g) => g.includes(id)) ?? [id]; + const run = splitGroups(ids, showsLiveBlock).find((g) => g.includes(id)) ?? [id]; if (run[0] !== id) return []; return runLines(d, getCalls(run), view); }; diff --git a/.pi/agent/extensions/quiet-transcript/call-store.ts b/.pi/agent/extensions/quiet-transcript/call-store.ts index 64fd35a..e54aa03 100644 --- a/.pi/agent/extensions/quiet-transcript/call-store.ts +++ b/.pi/agent/extensions/quiet-transcript/call-store.ts @@ -22,8 +22,8 @@ export type CallView = { readonly getThought: (id: string) => string | undefined; // Thinking from a later message that folds back into this call because no reply text came between them. readonly getThoughtAfter: (id: string) => string | undefined; - // Whether no visible call follows this one in the transcript yet. - readonly isLatest: (id: string) => boolean; + // Whether the call is among the `count` most recent inline-until-done calls. + readonly isRecent: (id: string, count: number) => boolean; readonly getSegment: (id: string) => { readonly ids: readonly string[]; readonly live: boolean } | undefined; }; @@ -197,11 +197,14 @@ export const createCallStore = (levelOf: (name: string) => Level, now = Date.now getCall: (id) => calls.get(id), getThought: (id) => thoughts.get(id), getThoughtAfter: (id) => thoughtsAfter.get(id), - isLatest(id) { + isRecent(id, count) { + let seen = 0; for (const items of [streaming, committed]) { for (let i = items.length - 1; i >= 0; i--) { const item = items[i]!; - if (item.t === "call" && levelOf(item.name) !== "hidden") return item.id === id; + if (item.t !== "call" || levelOf(item.name) !== "inline-until-done") continue; + if (item.id === id) return seen < count; + if (++seen >= count) return false; } } return false; diff --git a/.pi/agent/extensions/quiet-transcript/config.ts b/.pi/agent/extensions/quiet-transcript/config.ts index 0b24603..6c734b6 100644 --- a/.pi/agent/extensions/quiet-transcript/config.ts +++ b/.pi/agent/extensions/quiet-transcript/config.ts @@ -10,6 +10,7 @@ export type Config = { readonly levels: Readonly>; readonly highlights: ReadonlyMap; readonly skillReads: boolean; + readonly inlineKeep: number; readonly diffLines: number; readonly writeLines: number; }; @@ -44,6 +45,7 @@ export const readConfig = (raw: unknown): Config => { levels, highlights, skillReads: o.skillReads === true, + inlineKeep: Math.max(1, num(o.inlineKeep, 3)), diffLines: num(o.diffLines, 20), writeLines: num(o.writeLines, 8), }; diff --git a/.pi/tests/quiet-call-renderer.test.ts b/.pi/tests/quiet-call-renderer.test.ts index 3562f06..b0aec35 100644 --- a/.pi/tests/quiet-call-renderer.test.ts +++ b/.pi/tests/quiet-call-renderer.test.ts @@ -9,6 +9,7 @@ import { readConfig, toolLevel, type ToolView } from '../agent/extensions/quiet- const th = { fg: (_role: string, text: string) => text, bold: (text: string) => text, + italic: (text: string) => text, colors: { userMessageBg: { kind: 'indexed', index: 0 }, toolDiffAdded: { kind: 'indexed', index: 2 }, @@ -26,8 +27,8 @@ const observation = (toolCallId: string, args: Readonly> const result = (text: string) => ({ content: [{ type: 'text', text }], details: undefined }); const plain = (rows: readonly string[]) => rows.map(stripTerminalSequences).join('\n'); -test('an inline-until-done preview splits live summaries and folds back when it finishes', () => { - const config = readConfig({ levels: { example: 'inline-until-done' } }); +test('a one-call window folds the previous preview when a newer eligible call appears', () => { + const config = readConfig({ inlineKeep: 1, levels: { example: 'inline-until-done' } }); const store = createCallStore((name) => toolLevel(config, name), () => 0); const { drawCall } = createCallRenderer(config, store.view, new Map(), () => 0); const draw = (id: string, view: ToolView = 'collapsed') => plain(drawCall(id, layout, view)); @@ -45,12 +46,75 @@ test('an inline-until-done preview splits live summaries and folds back when it assert.match(draw('after'), /read/); store.observeRender('example', inline, result('FINAL BODY')); + assert.match(draw('example'), /FINAL BODY/); + + const next = { ...response, content: [...response.content, tool('next', 'example')] }; + store.updateAssistant(next, false); + store.observeRender('example', observation('next', {}), result('NEW BODY')); assert.match(draw('before'), /read 2.*example/); assert.equal(draw('example'), ''); assert.equal(draw('after'), ''); + assert.match(draw('next'), /NEW BODY/); + store.finishAssistant(next, false); + store.settleRun(); + assert.match(draw('before'), /read 2.*example 2/); + assert.equal(draw('next'), ''); + assert.match(draw('before', 'expanded'), /FIRST BODY[\s\S]*FINAL BODY[\s\S]*LAST BODY[\s\S]*NEW BODY/); +}); + +test('the default window keeps three eligible calls open only during the current turn', () => { + const config = readConfig({ levels: { example: 'inline-until-done', ordinary: 'inline' } }); + const store = createCallStore((name) => toolLevel(config, name)); + const { drawCall } = createCallRenderer(config, store.view, new Map()); + const calls = [tool('a', 'example'), tool('b', 'example'), tool('c', 'example'), tool('d', 'example'), + tool('x', 'ordinary'), tool('y', 'ordinary')]; + const response = { role: 'assistant', content: calls }; + const hasOutput = (id: string) => plain(drawCall(id, layout, 'collapsed')).includes(`BODY ${id}`); + const visible = () => calls.filter(({ id }) => hasOutput(id)).map(({ id }) => id); + + store.startRun(); + store.startMessage(response, false); + for (const { id, name } of calls) store.observeRender(name, observation(id, {}), result(`BODY ${id}`)); + assert.deepEqual(visible(), ['b', 'c', 'd', 'x', 'y']); store.finishAssistant(response, false); store.settleRun(); - assert.match(draw('before', 'expanded'), /FIRST BODY[\s\S]*FINAL BODY[\s\S]*LAST BODY/); + assert.deepEqual(visible(), []); + + const user = { role: 'user' }; + const followup = { role: 'assistant', content: [{ type: 'thinking', thinking: 'Check the next call' }, tool('e', 'example')] }; + store.startRun(); + store.startMessage(user, false); + store.startMessage(followup, false); + store.observeRender('example', observation('e', {}), result('BODY e')); + assert.deepEqual(visible(), []); + assert.equal(hasOutput('e'), true); + + store.restoreBranch([response, user, followup].map((message) => ({ type: 'message', message }))); + assert.deepEqual(visible(), []); + assert.equal(hasOutput('e'), false); + assert.match(plain(drawCall('e', layout, 'expanded')), /Check the next call[\s\S]*BODY e/); +}); + +test('live codemode keeps the Bash-sized output tail without shortening its script preview', () => { + const config = readConfig({ levels: { codemode: 'inline-until-done', bash: 'inline-until-done' } }); + const store = createCallStore((name) => toolLevel(config, name)); + const script = Array.from({ length: 10 }, (_, i) => `script-${i + 1}`); + const output = Array.from({ length: 14 }, (_, i) => `result-${i + 1}`); + const { drawCall } = createCallRenderer(config, store.view, new Map([['codemode', { + body: (_call, { maxRows }) => script.slice(0, maxRows), + }]])); + const response = { role: 'assistant', content: [tool('code', 'codemode'), tool('shell', 'bash')] }; + store.startRun(); + store.startMessage(response, false); + store.observeRender('codemode', observation('code', {}), result(output.join('\n'))); + store.observeRender('bash', observation('shell', { command: 'show results' }), result(output.join('\n'))); + const live = plain(drawCall('code', layout, 'collapsed')); + const shownResults = (text: string) => text.match(/\bresult-\d+\b/g); + assert.deepEqual(live.match(/\bscript-\d+\b/g), script); + assert.deepEqual(shownResults(live), output.slice(-5)); + assert.deepEqual(shownResults(plain(drawCall('shell', layout, 'collapsed'))), output.slice(-5)); + assert.match(live, /9 earlier lines/); + assert.deepEqual(shownResults(plain(drawCall('code', layout, 'expanded'))), output); }); test('persistent write previews keep their own block, line caps, and the configured key hint', () => { From 3604ca37d2a788cd5ac69b38650da12a57a590a8 Mon Sep 17 00:00:00 2001 From: Kaleb Dickerson Date: Tue, 1 Dec 2026 22:30:19 +0000 Subject: [PATCH 5/7] pi: CPU and RAM readout in the turn summary row Configured with turnUsage.systemStats; hidden while a turn runs. --- .pi/agent/extensions/composer-layout.ts | 2 +- .../composer-layout/dock-spacing.ts | 23 ++++- .pi/agent/extensions/composer-layout/roles.ts | 3 +- .pi/agent/extensions/turn-usage.ts | 96 ++++++++++++++++++- 4 files changed, 118 insertions(+), 6 deletions(-) diff --git a/.pi/agent/extensions/composer-layout.ts b/.pi/agent/extensions/composer-layout.ts index b323037..7928ee1 100644 --- a/.pi/agent/extensions/composer-layout.ts +++ b/.pi/agent/extensions/composer-layout.ts @@ -56,7 +56,7 @@ export default function (pi: ExtensionAPI) { const docked = isWorking(); const statusRows = renderStatus.call(status, width); const parts = children.map((child) => child.render?.(width) ?? []); - const segments = layoutDock(children, parts, docked ? statusRows : [], !docked && isDockBlank(statusRows.at(-1))); + const segments = layoutDock(children, parts, docked ? statusRows : [], !docked && isDockBlank(statusRows.at(-1)), width); // Use the same positions for paint and mouse dispatch. above.mouseLayout = { width, diff --git a/.pi/agent/extensions/composer-layout/dock-spacing.ts b/.pi/agent/extensions/composer-layout/dock-spacing.ts index c0816ea..cf4becf 100644 --- a/.pi/agent/extensions/composer-layout/dock-spacing.ts +++ b/.pi/agent/extensions/composer-layout/dock-spacing.ts @@ -1,4 +1,5 @@ -import { dockActivity, dockFill, dockQueue, dockTurnSummary, type DockWidget } from './roles.ts'; +import { visibleWidth } from '@earendil-works/pi-tui'; +import { dockActivity, dockFill, dockQueue, dockTrailing, dockTurnSummary, type DockWidget } from './roles.ts'; export const isDockBlank = (line: string | undefined) => line !== undefined && line.replace(/\x1b\[[0-9;:]*m/g, '').trim() === ''; @@ -34,17 +35,37 @@ const flushLeft = (line: string) => line.replace(/^((?:\x1b\[[0-9;:]*m)*) /, '$1 */ export function layoutDock( children: readonly DockWidget[], parts: readonly (readonly string[])[], working: readonly string[], statusEndsWithGap: boolean, + width = Infinity, ): DockSegment[] { const placed: { rank: Rank; segment: DockSegment }[] = []; + // A trailing widget's right-aligned text joins the turn summary row when both fit on one line. + const trailing: string[] = []; children.forEach((child, index) => { if (index === 0) return; const rows = parts[index] ?? []; + if (child[dockTrailing]) { + const line = trimBlank(rows)[0]?.replace(/^ +/, ''); + if (line) trailing.push(line); + return; + } const rank = rankOf(child, rows); placed.push({ rank, segment: { source: index, rows: rank === 'fill' ? rows : trimBlank(rows) } }); }); const workingRows = trimBlank(working).map(flushLeft); if (workingRows.length) placed.push({ rank: 'working', segment: { source: 'working', rows: workingRows } }); placed.sort((a, b) => RANKS.indexOf(a.rank) - RANKS.indexOf(b.rank)); + for (const line of trailing) { + const host = placed.findLast(({ rank, segment }) => rank === 'summary' && segment.rows.length > 0); + const row = host?.segment.rows.at(-1); + const gap = row === undefined ? 0 : width - visibleWidth(row) - visibleWidth(line); + if (host && row !== undefined && gap >= 2) { + host.segment = { ...host.segment, rows: [...host.segment.rows.slice(0, -1), row + ' '.repeat(gap) + line] }; + } else { + const own = ' '.repeat(Math.max(0, width - visibleWidth(line))) + line; + const at = placed.findIndex(({ rank }) => RANKS.indexOf(rank) > RANKS.indexOf('summary')); + placed.splice(at === -1 ? placed.length : at, 0, { rank: 'summary', segment: { source: 'gap', rows: [own] } }); + } + } const out: DockSegment[] = []; let previous: Rank | undefined; diff --git a/.pi/agent/extensions/composer-layout/roles.ts b/.pi/agent/extensions/composer-layout/roles.ts index 95b93bc..f48c072 100644 --- a/.pi/agent/extensions/composer-layout/roles.ts +++ b/.pi/agent/extensions/composer-layout/roles.ts @@ -1,6 +1,7 @@ export const dockFill = Symbol.for('kaleb.pi.dock-fill'); export const dockActivity = Symbol.for('kaleb.pi.dock-activity'); export const dockTurnSummary = Symbol.for('kaleb.pi.dock-turn-summary'); +export const dockTrailing = Symbol.for('kaleb.pi.dock-trailing'); export const dockQueue = Symbol.for('kaleb.pi.dock-queue'); -export type DockWidget = { [dockFill]?: true; [dockActivity]?: true; [dockTurnSummary]?: true; [dockQueue]?: true }; +export type DockWidget = { [dockFill]?: true; [dockActivity]?: true; [dockTurnSummary]?: true; [dockQueue]?: true; [dockTrailing]?: true }; diff --git a/.pi/agent/extensions/turn-usage.ts b/.pi/agent/extensions/turn-usage.ts index 54719b2..22bda04 100644 --- a/.pi/agent/extensions/turn-usage.ts +++ b/.pi/agent/extensions/turn-usage.ts @@ -1,11 +1,100 @@ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; -import { truncateToWidth } from "@earendil-works/pi-tui"; -import { dockTurnSummary } from "./composer-layout/roles.ts"; +import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui"; +import { readFileSync } from "node:fs"; +import { cpus, freemem, loadavg, totalmem } from "node:os"; +import { dockTrailing, dockTurnSummary } from "./composer-layout/roles.ts"; const key = "turn-usage"; +const statsKey = "turn-usage-system"; const tokens = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1 }); const newTurn = () => ({ startedAt: performance.now(), input: 0, output: 0, cacheRead: 0 }); +// ── system stats: a right-aligned readout that joins the summary row (or the working line) when it fits ── + +const statsMetrics = ["cpu", "ram", "load"] as const; +type Metric = (typeof statsMetrics)[number]; +type StatsConfig = { readonly enabled: boolean; readonly intervalMs: number; readonly show: readonly Metric[] }; +type Cpu = { readonly busy: number; readonly total: number }; +type Sample = { readonly cpu?: number; readonly ram?: { readonly used: number; readonly total: number }; readonly load: number }; + +// `turnUsage.systemStats` in settings.json: `false` hides it; an object sets `intervalSeconds` (default 2, at least 1) +// and `show` (any of "cpu", "ram", "load"; default cpu and ram, in the order given). On by default. +export function readStatsConfig(raw: unknown): StatsConfig { + const r = (raw && typeof raw === "object" ? raw : {}) as Record; + const show = Array.isArray(r.show) ? [...new Set(r.show.filter((m): m is Metric => statsMetrics.includes(m as Metric)))] : ["cpu", "ram"] as Metric[]; + const seconds = typeof r.intervalSeconds === "number" && Number.isFinite(r.intervalSeconds) ? Math.max(1, r.intervalSeconds) : 2; + return { enabled: raw !== false, intervalMs: seconds * 1000, show }; +} + +// Cumulative CPU time: /proc/stat on Linux, Node's per-core counters elsewhere. +function readCpu(): Cpu { + try { + const [, ...fields] = readFileSync("/proc/stat", "utf8").split("\n", 1)[0]!.trim().split(/\s+/); + const n = fields.map(Number); + const total = n.slice(0, 8).reduce((a, b) => a + b, 0); + return { busy: total - (n[3] ?? 0) - (n[4] ?? 0), total }; + } catch { + const t = cpus().reduce((acc, c) => ({ idle: acc.idle + c.times.idle, all: acc.all + Object.values(c.times).reduce((a, b) => a + b, 0) }), { idle: 0, all: 0 }); + return { busy: t.all - t.idle, total: t.all }; + } +} + +// "Available" memory counts reclaimable cache as free, matching what `free` and htop call used. +function readRam(): { used: number; total: number } { + try { + const info = readFileSync("/proc/meminfo", "utf8"); + const kb = (name: string) => Number(new RegExp(`^${name}:\\s+(\\d+)`, "m").exec(info)?.[1]); + const total = kb("MemTotal") * 1024, available = kb("MemAvailable") * 1024; + if (total > 0 && available >= 0) return { used: total - available, total }; + } catch { /* fall through */ } + return { used: totalmem() - freemem(), total: totalmem() }; +} + +const percent = (before: Cpu, now: Cpu) => now.total > before.total ? Math.round(100 * (now.busy - before.busy) / (now.total - before.total)) : undefined; +const gb = (bytes: number) => bytes / 2 ** 30 >= 10 ? Math.round(bytes / 2 ** 30) : +(bytes / 2 ** 30).toFixed(1); + +// Longest first; the caller takes the first that fits. +function statsVariants(sample: Sample, show: readonly Metric[]): string[] { + const parts = (detail: boolean) => show.flatMap(metric => { + if (metric === "cpu") return sample.cpu === undefined ? [] : [`cpu ${sample.cpu}%`]; + if (metric === "load") return [`load ${sample.load.toFixed(1)}`]; + if (!sample.ram) return []; + const pct = Math.round(100 * sample.ram.used / sample.ram.total); + return [detail ? `ram ${pct}% (${gb(sample.ram.used)}/${gb(sample.ram.total)}G)` : `ram ${pct}%`]; + }).join(" · "); + return [...new Set([parts(true), parts(false)])].filter(Boolean); +} + +function showStats(pi: ExtensionAPI, ctx: ExtensionContext, running: () => boolean) { + ctx.ui.setWidget(statsKey, undefined); + if (ctx.mode !== "tui") return; + const config = readStatsConfig(((pi.getSettings() as Record).turnUsage as Record | undefined)?.systemStats); + if (!config.enabled || config.show.length === 0) return; + ctx.ui.setWidget(statsKey, (tui, theme) => { + let before = readCpu(); + let sample: Sample = { ram: readRam(), load: loadavg()[0]! }; + const timer = setInterval(() => { + const now = readCpu(); + sample = { cpu: percent(before, now), ram: readRam(), load: loadavg()[0]! }; + before = now; + tui.requestRender(); + }, config.intervalMs); + timer.unref(); + return { + [dockTrailing]: true as const, + render(width) { + if (running()) return []; + const line = statsVariants(sample, config.show).find(v => visibleWidth(v) <= width); + if (!line) return []; + const hot = (sample.cpu ?? 0) >= 90 || (sample.ram ? sample.ram.used / sample.ram.total >= 0.9 : false); + return [" ".repeat(width - visibleWidth(line)) + theme.fg(hot ? "warning" : "dim", truncateToWidth(line, width))]; + }, + invalidate() {}, + dispose() { clearInterval(timer); }, + }; + }, { placement: "aboveEditor" }); +} + function showSummary(ctx: ExtensionContext, variants: string[] = []) { const entry = ctx.sessionManager.getBranch().findLast(e => e.type === "message" && e.message.role === "user"); const at = entry?.type === "message" && entry.message.role === "user" ? entry.message.timestamp : undefined; @@ -34,7 +123,8 @@ export default function (pi: ExtensionAPI) { turn = undefined; if (ctx.mode === "tui") showSummary(ctx); }; - pi.on("session_start", restore); + pi.on("session_start", (event, ctx) => { restore(event, ctx); showStats(pi, ctx, () => turn !== undefined); }); + pi.on("session_shutdown", (_event, ctx) => { if (ctx.mode === "tui") ctx.ui.setWidget(statsKey, undefined); }); pi.on("session_tree", restore); pi.on("agent_start", (_event, ctx) => { From af3e5b21010f3757c29a2c5b5da32ccf97af9ddb Mon Sep 17 00:00:00 2001 From: Kaleb Dickerson Date: Tue, 1 Dec 2026 22:30:19 +0000 Subject: [PATCH 6/7] pi: kill from the work dock and agents defaultModel --- .pi/agent/extensions/agents/config.ts | 9 +- .pi/agent/extensions/agents/index.ts | 4 +- .../extensions/agents/test/registry.test.ts | 4 +- .pi/agent/extensions/work-dock-processes.ts | 39 ++++++++ .pi/agent/extensions/work-dock/api.ts | 2 + .pi/agent/extensions/work-dock/index.ts | 25 ++++- .../work-dock/test/process-provider.test.ts | 94 ++++++++++++++++++ .../extensions/work-dock/test/roster.test.ts | 98 +++++++++++++++++++ 8 files changed, 270 insertions(+), 5 deletions(-) create mode 100644 .pi/agent/extensions/work-dock/test/process-provider.test.ts create mode 100644 .pi/agent/extensions/work-dock/test/roster.test.ts diff --git a/.pi/agent/extensions/agents/config.ts b/.pi/agent/extensions/agents/config.ts index 4ea32c7..1c47d63 100644 --- a/.pi/agent/extensions/agents/config.ts +++ b/.pi/agent/extensions/agents/config.ts @@ -8,6 +8,8 @@ export type ActivitySettings = { }; export type AgentSettings = { + /** Model for agents whose request and definition name none; the parent's model when absent. */ + defaultModel?: string; maxDepth: number; maxLiveRuns: number; activityWidget: ActivitySettings; @@ -35,7 +37,12 @@ export const parseAgentSettings = (value: unknown): AgentSettings => { if (layout !== "off" && layout !== "inline" && layout !== "stacked") { throw new Error('activityWidget.outputLayout must be "off", "inline", or "stacked"'); } + const { defaultModel } = config; + if (defaultModel !== undefined && (typeof defaultModel !== "string" || !defaultModel.trim())) { + throw new Error("defaultModel must be a nonempty string"); + } return { + ...(defaultModel === undefined ? {} : { defaultModel: defaultModel.trim() }), maxDepth: integer(config.maxDepth, "maxDepth", 2, 1), maxLiveRuns: integer(config.maxLiveRuns, "maxLiveRuns", 4, 1), activityWidget: { @@ -46,7 +53,7 @@ export const parseAgentSettings = (value: unknown): AgentSettings => { }; export const loadAgentSettings = (agentDir: string): AgentSettings => { - const path = join(agentDir, "extensions", "agents", "config.json"); + const path = join(agentDir, "agents.json"); try { return parseAgentSettings(JSON.parse(readFileSync(path, "utf8"))); } catch (error) { diff --git a/.pi/agent/extensions/agents/index.ts b/.pi/agent/extensions/agents/index.ts index 010c59d..af1b776 100644 --- a/.pi/agent/extensions/agents/index.ts +++ b/.pi/agent/extensions/agents/index.ts @@ -67,7 +67,8 @@ export default function agents(pi: ExtensionAPI) { break; } }, - spawn: (request) => createChild(request, agentDir, (deny): ExtensionFactory => (childPi) => { + spawn: (request) => createChild( + { ...request, definition: { ...request.definition, model: request.definition.model ?? settings.defaultModel } }, agentDir, (deny): ExtensionFactory => (childPi) => { registerAgentTools(childPi, { runtime: () => instance, definitions: () => loaded.definitions, parentId: request.run.id, deny, canLaunch: request.run.depth < settings.maxDepth, ask: request.ask, @@ -85,6 +86,7 @@ export default function agents(pi: ExtensionAPI) { })), subscribe: instance.registry.subscribe, inspect: (id, inspector) => inspectAgent(inspector, source, id), + kill(id) { instance.stop(id); }, }); current = { runtime: instance, async dispose() { dock(); activity(); await instance.shutdown(); } }; }); diff --git a/.pi/agent/extensions/agents/test/registry.test.ts b/.pi/agent/extensions/agents/test/registry.test.ts index bfac34c..3fd1a47 100644 --- a/.pi/agent/extensions/agents/test/registry.test.ts +++ b/.pi/agent/extensions/agents/test/registry.test.ts @@ -25,7 +25,9 @@ test("runtime and preview settings have validated defaults and overrides", () => assert.deepEqual(parseAgentSettings({ maxLiveRuns: 7, maxDepth: 3, activityWidget: { outputLayout: "inline", stackedPreviewLines: 5 } }), { maxDepth: 3, maxLiveRuns: 7, activityWidget: { outputLayout: "inline", stackedPreviewLines: 5 }, }); - for (const invalid of [{ maxLiveRuns: 0 }, { maxDepth: 2.5 }, { activityWidget: { stackedPreviewLines: 6 } }, { activityWidget: { outputLayout: "hidden" } }, { activityWidget: null }]) { + assert.equal(parseAgentSettings({ defaultModel: " p/m " }).defaultModel, "p/m"); + assert.equal("defaultModel" in parseAgentSettings({}), false); + for (const invalid of [{ defaultModel: "" }, { defaultModel: 3 }, { maxLiveRuns: 0 }, { maxDepth: 2.5 }, { activityWidget: { stackedPreviewLines: 6 } }, { activityWidget: { outputLayout: "hidden" } }, { activityWidget: null }]) { assert.throws(() => parseAgentSettings(invalid)); } }); diff --git a/.pi/agent/extensions/work-dock-processes.ts b/.pi/agent/extensions/work-dock-processes.ts index cadad8a..e12a9bb 100644 --- a/.pi/agent/extensions/work-dock-processes.ts +++ b/.pi/agent/extensions/work-dock-processes.ts @@ -9,6 +9,39 @@ type OutputLine = { text: string; type: "stdout" | "stderr" }; const live = new Set(["running", "terminating", "terminate_timeout"]); const tailLines = 500; +type KillResult = { ok: true } | { ok: false; reason?: string }; +type KillPayload = { + id: string; + signal: "SIGTERM" | "SIGKILL"; + timeoutMs: number; + reply(result: KillResult): void; +}; + +function requestProcessStop(events: ExtensionAPI["events"], id: string, signal: KillPayload["signal"], timeoutMs: number): Promise { + return new Promise((resolve, reject) => { + let settled = false; + const timer = setTimeout(() => { + if (settled) return; + settled = true; + resolve(false); + }, timeoutMs + 2000); + timer.unref?.(); + const reply = (result: KillResult) => { + if (settled) return; + settled = true; + clearTimeout(timer); + if (result.ok) resolve(true); + else reject(new Error(result.reason ?? "Could not kill process")); + }; + try { + events.emit("processes:command:kill", { id, signal, timeoutMs, reply } satisfies KillPayload); + } catch (error) { + clearTimeout(timer); + reject(error); + } + }); +} + export default function processesProvider(pi: ExtensionAPI) { let dispose: (() => void) | undefined; pi.on("session_start", (_event, ctx) => { @@ -37,6 +70,12 @@ export default function processesProvider(pi: ExtensionAPI) { const process = processes.find(({ id }) => id === processId); if (process) await inspect(process, viewContext); }, + async kill(processId) { + const process = processes.find(({ id }) => id === processId); + if (!process || !live.has(process.status)) return false; + const force = process.status === "terminate_timeout"; + return requestProcessStop(pi.events, process.id, force ? "SIGKILL" : "SIGTERM", force ? 200 : 3000); + }, }); const retry = setTimeout(() => { if (!received) refresh(); diff --git a/.pi/agent/extensions/work-dock/api.ts b/.pi/agent/extensions/work-dock/api.ts index e7897a6..c4e7482 100644 --- a/.pi/agent/extensions/work-dock/api.ts +++ b/.pi/agent/extensions/work-dock/api.ts @@ -19,6 +19,8 @@ export type DockProvider = { snapshot(): readonly DockRow[]; subscribe(onChange: () => void): () => void; inspect?(rowId: string, ctx: ExtensionContext): void | Promise; + /** Return false if this row does not support kill; throw if the action fails. */ + kill?(rowId: string, ctx: ExtensionContext): boolean | void | Promise; }; export type CollectProviders = { add(provider: DockProvider): void }; diff --git a/.pi/agent/extensions/work-dock/index.ts b/.pi/agent/extensions/work-dock/index.ts index 0a1883a..c6a91c6 100644 --- a/.pi/agent/extensions/work-dock/index.ts +++ b/.pi/agent/extensions/work-dock/index.ts @@ -1,8 +1,9 @@ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; -import { isKeyRelease, matchesKey, truncateToWidth, visibleWidth, type TUI } from "@earendil-works/pi-tui"; +import { isKeyRelease, isKeyRepeat, matchesKey, truncateToWidth, visibleWidth, type TUI } from "@earendil-works/pi-tui"; import { stripVTControlCharacters } from "node:util"; import { CHANGED, COLLECT, type CollectProviders, type DockProvider, type DockRow } from "./api.ts"; import { getComposer, getFocus, type Composer } from "../composer/focus.ts"; +import { showToast } from "../toast/api.ts"; const SEP = " · "; const clean = (text: string) => stripVTControlCharacters(text).replace(/[\p{Cc}\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/gu, " ").replace(/\s+/gu, " ").trim(); @@ -80,6 +81,22 @@ const mount = (pi: ExtensionAPI, ctx: ExtensionContext) => { let composer: Composer | undefined; let expanded = false; let inspecting = false; + const killing = new Set(); + const kill = async ({ key, row, provider }: Row) => { + if (killing.has(key)) return; + killing.add(key); + const label = clean(row.label) || clean(provider.singular); + const notify = (message: string, tone: "warning" | "error") => { + if (mounted) showToast(pi.events, { title: "Work Dock", key: "work-dock:kill", message, tone }); + }; + try { + if (!provider.kill || await provider.kill(row.id, ctx) === false) notify(`Kill is not available for ${label}.`, "warning"); + } catch (error) { + notify(`Could not kill ${label}: ${clean(error instanceof Error ? error.message : String(error))}`, "error"); + } finally { + killing.delete(key); + } + }; const canOpen = () => { const current = getComposer(tui); return !!current && ctx.ui.getEditorText() === "" && current.getText() === "" && @@ -119,6 +136,10 @@ const mount = (pi: ExtensionAPI, ctx: ExtensionContext) => { if (matchesKey(data, "up")) selected = Math.max(0, selected - 1); else if (matchesKey(data, "down")) selected = Math.min(rows.length - 1, selected + 1); else if (matchesKey(data, "enter")) { const row = rows[selected]; if (row) void inspect(row); } + else if (matchesKey(data, "x")) { + const row = rows[selected]; + if (expanded && !inspecting && !isKeyRepeat(data) && row) void kill(row); + } else if (matchesKey(data, "escape")) close(); else if (matchesKey(data, "ctrl+c") || matchesKey(data, "ctrl+d")) { const editor = composer; @@ -152,7 +173,7 @@ const mount = (pi: ExtensionAPI, ctx: ExtensionContext) => { }); const inspectHint = rows[selected]?.provider.inspect ? " · Enter inspect" : ""; const scroll = rows.length > limit ? `${selected + 1}/${rows.length} · ` : ""; - return [theme.fg("text", "main"), ...lines, theme.fg("dim", `${scroll}↑↓ select${inspectHint} · Esc back`)] + return [theme.fg("text", "main"), ...lines, theme.fg("dim", `${scroll}↑↓ select${inspectHint} · x kill · Esc back`)] .map((line) => truncateToWidth(line, width)); }, }; diff --git a/.pi/agent/extensions/work-dock/test/process-provider.test.ts b/.pi/agent/extensions/work-dock/test/process-provider.test.ts new file mode 100644 index 0000000..05f3a0f --- /dev/null +++ b/.pi/agent/extensions/work-dock/test/process-provider.test.ts @@ -0,0 +1,94 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; +import processesProvider from "../../work-dock-processes.ts"; +import { COLLECT, type CollectProviders, type DockProvider } from "../api.ts"; + +type Listener = (payload: unknown) => void; +class FakeEvents { + private listeners = new Map>(); + on(event: string, listener: Listener) { + const listeners = this.listeners.get(event) ?? new Set(); + listeners.add(listener); + this.listeners.set(event, listeners); + return () => listeners.delete(listener); + } + emit(event: string, payload?: unknown) { + for (const listener of this.listeners.get(event) ?? []) listener(payload); + } +} + +function setup(status: string) { + const events = new FakeEvents(); + const lifecycle = new Map void)[]>(); + events.on("processes:request:list", (payload) => { + (payload as { reply(data: unknown[]): void }).reply([{ id: "proc-1", name: "dev server", status }]); + }); + const pi = { + events, + on(event: string, listener: (event: unknown, ctx: ExtensionContext) => void) { + const handlers = lifecycle.get(event) ?? []; + handlers.push(listener); + lifecycle.set(event, handlers); + }, + } as unknown as ExtensionAPI; + processesProvider(pi); + const ctx = { hasUI: true, mode: "rpc", ui: { setWidget() {} } } as unknown as ExtensionContext; + for (const listener of lifecycle.get("session_start") ?? []) listener({}, ctx); + let provider: DockProvider | undefined; + events.emit(COLLECT, { add(value: DockProvider) { provider = value; } } satisfies CollectProviders); + const shutdown = () => { + for (const listener of lifecycle.get("session_shutdown") ?? []) listener({}, ctx); + }; + return { events, ctx, provider: () => provider, shutdown }; +} + +test("managed process stop uses the graceful kill command and waits for its async reply", async () => { + const { events, ctx, provider, shutdown } = setup("running"); + let command: { id: string; signal: string; timeoutMs: number; reply(result: { ok: true } | { ok: false; reason?: string }): void } | undefined; + events.on("processes:command:kill", (payload) => { command = payload as typeof command; }); + + const stop = provider()?.kill?.("proc-1", ctx); + assert.ok(stop instanceof Promise); + assert.deepEqual(command && { id: command.id, signal: command.signal, timeoutMs: command.timeoutMs }, { + id: "proc-1", signal: "SIGTERM", timeoutMs: 3000, + }); + command?.reply({ ok: true }); + assert.equal(await stop, true); + shutdown(); +}); + +test("managed processes in terminate timeout use SIGKILL with a short timeout", async () => { + const { events, ctx, provider, shutdown } = setup("terminate_timeout"); + let command: { signal: string; timeoutMs: number; reply(result: { ok: true } | { ok: false; reason?: string }): void } | undefined; + events.on("processes:command:kill", (payload) => { command = payload as typeof command; }); + + const stop = provider()?.kill?.("proc-1", ctx); + assert.ok(stop instanceof Promise); + assert.deepEqual(command && { signal: command.signal, timeoutMs: command.timeoutMs }, { signal: "SIGKILL", timeoutMs: 200 }); + command?.reply({ ok: true }); + assert.equal(await stop, true); + shutdown(); +}); + +test("process-stop failures report the backend reason without repeating the process id", async () => { + const { events, ctx, provider, shutdown } = setup("running"); + let command: { reply(result: { ok: true } | { ok: false; reason?: string }): void } | undefined; + events.on("processes:command:kill", (payload) => { command = payload as typeof command; }); + + const stop = provider()?.kill?.("proc-1", ctx); + assert.ok(stop instanceof Promise); + command?.reply({ ok: false, reason: "timeout" }); + await assert.rejects(stop, { message: "timeout" }); + shutdown(); +}); + +test("returns false when no managed-process stop handler is available", async (t) => { + t.mock.timers.enable({ apis: ["setTimeout"] }); + const { ctx, provider, shutdown } = setup("running"); + const stop = provider()?.kill?.("proc-1", ctx); + assert.ok(stop instanceof Promise); + shutdown(); + t.mock.timers.tick(5000); + assert.equal(await stop, false); +}); diff --git a/.pi/agent/extensions/work-dock/test/roster.test.ts b/.pi/agent/extensions/work-dock/test/roster.test.ts new file mode 100644 index 0000000..00d3f63 --- /dev/null +++ b/.pi/agent/extensions/work-dock/test/roster.test.ts @@ -0,0 +1,98 @@ +import assert from "node:assert/strict"; +import { EventEmitter } from "node:events"; +import { test } from "node:test"; +import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"; +import { visibleWidth } from "@earendil-works/pi-tui"; +import { toastChannel, type ToastRequest } from "../../toast/api.ts"; +import { publishDockProvider, type DockProvider } from "../api.ts"; +import workDock from "../index.ts"; + +const setup = (kill?: DockProvider["kill"]) => { + const bus = new EventEmitter(); + const hooks = new EventEmitter(); + const events = { + emit: (channel: string, payload: unknown) => { bus.emit(channel, payload); }, + on: (channel: string, listener: (payload: unknown) => void) => { + bus.on(channel, listener); + return () => { bus.off(channel, listener); }; + }, + }; + const toasts: ToastRequest[] = []; + bus.on(toastChannel, (toast: ToastRequest) => toasts.push(toast)); + type Component = { handleInput(data: string): void; render?(width: number): string[] }; + let draft = ""; + const composer = { getText: () => draft, setText() {}, handleInput(data: string) { draft += data; } }; + let focus: Component = composer; + let widget: Component | undefined; + let terminalInput: ((data: string) => { consume: boolean } | undefined) | undefined; + const tui = { terminal: { rows: 40 }, requestRender() {}, hasOverlay: () => false, + getFocusedComponent: () => focus, setFocus: (component: Component) => { focus = component; } }; + const theme = { fg: (_tone: string, label: string) => label }; + const ctx = { mode: "tui", hasUI: true, ui: { + setWidget(_id: string, create?: (tui: unknown, theme: unknown) => Component) { widget = create?.(tui, theme); }, + getEditorText: () => composer.getText(), + onTerminalInput(listener: typeof terminalInput) { terminalInput = listener; return () => { terminalInput = undefined; }; }, + } } as unknown as ExtensionContext; + const withdraw = publishDockProvider(events, { + id: "tests", singular: "job", plural: "jobs", subscribe: () => () => {}, kill, + snapshot: () => [ + { id: "first", label: "one", status: "running" }, + { id: "second", label: "二番", status: "running" }, + ], + }); + workDock({ events, on: hooks.on.bind(hooks) } as unknown as ExtensionAPI); + hooks.emit("session_start", {}, ctx); + return { + press(data: string) { if (!terminalInput?.(data)?.consume) focus.handleInput(data); }, + clearDraft() { draft = ""; }, + frame(width: number) { return widget?.render?.(width) ?? []; }, + draft: () => draft, toasts, ctx, + close() { hooks.emit("session_shutdown"); withdraw(); }, + }; +}; + +const down = "\x1b[B"; + +test("x kills the selected row only when the roster is focused and skips duplicate requests in flight", async (t) => { + const calls: Array<[string, ExtensionContext]> = []; + const pending = Promise.withResolvers(); + const dock = setup((id, ctx) => { calls.push([id, ctx]); return pending.promise; }); + t.after(dock.close); + dock.press("x"); + assert.equal(dock.draft(), "x"); + assert.deepEqual(calls, []); + dock.clearDraft(); + dock.press(down); + dock.press(down); + assert.match(dock.frame(80).join("\n"), /› 二番[^\n]*running[\s\S]*x kill/); + assert.ok(dock.frame(15).every((line) => visibleWidth(line) <= 15)); + dock.press("\x1b[120;1:2u"); // Kitty key repeat. + assert.deepEqual(calls, []); + dock.press("x"); + dock.press("x"); + assert.deepEqual(calls, [["second", dock.ctx]]); + pending.resolve(); + await pending.promise; + assert.deepEqual(dock.toasts, []); +}); + +test("x shows an unsupported toast for a missing handler or a handler that declines the row", async (t) => { + for (const kill of [undefined, async () => false]) { + const dock = setup(kill); + t.after(dock.close); + dock.press(down); + dock.press("x"); + await Promise.resolve(); + assert.deepEqual(dock.toasts, [{ title: "Work Dock", key: "work-dock:kill", message: "Kill is not available for one.", tone: "warning" }]); + } +}); + +test("x reports kill failures without closing the roster", async (t) => { + const dock = setup(async () => { throw new Error("already exited"); }); + t.after(dock.close); + dock.press(down); + dock.press("x"); + await Promise.resolve(); + assert.deepEqual(dock.toasts, [{ title: "Work Dock", key: "work-dock:kill", message: "Could not kill one: already exited", tone: "error" }]); + assert.match(dock.frame(80).join("\n"), /› one/); +}); From 58c1ef97b7144f86679955464b0bfddf764158c1 Mon Sep 17 00:00:00 2001 From: Kaleb Dickerson Date: Tue, 1 Dec 2026 22:30:23 +0000 Subject: [PATCH 7/7] pi: update extension docs and settings ask_user_question stays persistent, codemode shows inline-until-done, and the extensions catalog covers the new behavior. --- .gitignore | 1 - .pi/agent/extensions/COMPOSITION.md | 9 ++++--- .pi/agent/extensions/README.md | 41 ++++++++++++++--------------- .pi/agent/settings.json | 6 ++--- 4 files changed, 29 insertions(+), 28 deletions(-) diff --git a/.gitignore b/.gitignore index 37992d6..bb64983 100644 --- a/.gitignore +++ b/.gitignore @@ -11,4 +11,3 @@ **/flake.lock .nvim/ -/.pi/agent/extensions/agents/config.json diff --git a/.pi/agent/extensions/COMPOSITION.md b/.pi/agent/extensions/COMPOSITION.md index 3690b67..440312b 100644 --- a/.pi/agent/extensions/COMPOSITION.md +++ b/.pi/agent/extensions/COMPOSITION.md @@ -30,9 +30,12 @@ Use a unique provider ID and stable row IDs within that provider. Return only rows that belong in the live roster, in display order. Update state before notifying subscribers. A `parentId` refers to another row from the same provider. An optional `inspect(rowId, ctx)` opens the provider's detail view; -if it opens an overlay, await dismissal so the dock can restore focus. Call -the function returned by `publishDockProvider` if you need to withdraw the -provider. RPC clients get the collapsed counts only. +if it opens an overlay, await dismissal so the dock can restore focus. +An optional `kill(rowId, ctx)` runs the provider's stop action. Return +`false` if the row does not support it, return normally on success, and +throw on failure. The dock shows a toast for unsupported actions and failures. +Call the function returned by `publishDockProvider` to withdraw the provider. +RPC clients get the collapsed counts only. ## Quiet Transcript: publish presentation hints diff --git a/.pi/agent/extensions/README.md b/.pi/agent/extensions/README.md index 06e7635..44202da 100644 --- a/.pi/agent/extensions/README.md +++ b/.pi/agent/extensions/README.md @@ -16,7 +16,6 @@ Local extensions for Pi. Stow links `.pi/agent` to `~/.pi/agent`, so these load | [codemode-view](#codemode-view) | Transcript | Formatted, highlighted codemode scripts under quiet-transcript rows | | [code-blocks](#code-blocks) | Transcript | Fenced code block style and table header color | | [image-chips](#image-chips) | Transcript | Pasted image paths become `[Image N]` chips and attachments | -| [transcript-timestamps](#transcript-timestamps) | Transcript | Clock time and response latency beside messages; `/stamp` | | [trim-output](#trim-output) | Transcript | Drops invisible trailing spaces from rendered lines | | [toast](#toast) | Transcript | Transient bottom-right notices; `/toast` | | [composer](#composer-helper-not-an-extension) | Composer | Helper only: decorator host and focus helpers | @@ -30,7 +29,7 @@ Local extensions for Pi. Stow links `.pi/agent` to `~/.pi/agent`, so these load | [clear](#clear) | Composer | `/clear` as an alias for `/new` | | [cursor-footer](#cursor-footer) | Footer & status | Footer: model, context %, statuses, cwd, branch, MCP health | | [dashboard](#dashboard) | Footer & status | Boxed startup header | -| [turn-usage](#turn-usage) | Footer & status | Per-turn token, cache, time summary above the composer | +| [turn-usage](#turn-usage) | Footer & status | Per-turn token, cache, time summary and CPU / RAM readout above the composer | | [stock](#stock) | Footer & status | `/stock` intraday chart widget | | [work-dock](#work-dock) | Dock & agents | Shared roster of live agents and processes below the composer | | [work-dock-processes](#work-dock-processes) | Dock & agents | Publishes `pi-processes` processes to the dock | @@ -46,7 +45,7 @@ Local extensions for Pi. Stow links `.pi/agent` to `~/.pi/agent`, so these load | [shell-guard](#shell-guard) | Misc | Approval prompt for destructive shell commands | | [no-update-nag](#no-update-nag) | Misc | Silences startup update checks | -Helper-only directories (no default export, imported by the extensions that own them): `composer/`, `composer-layout/`, `native-transcript/`, `toast/`, `transcript-stamp/`, and the non-`index.ts` files inside each extension directory. `processes.json` is data, covered under [work-dock-processes](#work-dock-processes). +Helper-only directories (no default export, imported by the extensions that own them): `composer/`, `composer-layout/`, `native-transcript/`, `toast/`, and the non-`index.ts` files inside each extension directory. `processes.json` is data, covered under [work-dock-processes](#work-dock-processes). Two names to keep apart: `dashboard.ts` is the startup header; the `/dashboard` command comes from [review](#review). @@ -85,6 +84,7 @@ Leaving Expanded through Pi's own toggle lands on Collapsed. | `lead` | `icon`, `dot`, `icon+dot`, `bar` | `icon` | – | | `levels` | `{ [tool]: level }`, see below | see below | see below | | `skillReads` | `true` labels `SKILL.md` reads as `skill` (display only; uses the `read` level) | `false` | `true` | +| `inlineKeep` | number of recent `inline-until-done` tool calls to keep open during a run (at least 1) | `3` | – | | `diffLines` | preview cap for edit blocks | `20` | `8` | | `writeLines` | preview cap for write blocks | `8` | – | @@ -96,7 +96,7 @@ Invalid values fall back to the default. | --- | --- | | `persistent` | The call keeps its own block after the run and separates the summaries on either side | | `inline` | Block stays open until the run settles, then folds into the summary | -| `inline-until-done` | Open while running and until the next call appears or the run settles, then folds | +| `inline-until-done` | Running calls and the `inlineKeep` most recent calls at this level stay open during the run. New calls at this level fold older finished calls into the summary. All calls fold when the run settles | | `minimal` | Folded into the shared summary | | `hidden` | Not shown | | `native` | Pi's own renderer for that tool | @@ -105,17 +105,19 @@ Invalid values fall back to the default. Default levels: `edit`, `write`, `ask_user_question` → `inline`; `thinking` → `inline-until-done`. -Set here: `edit` and `write` `persistent`; `todo` `hidden`; `thinking`, `web_search`, `bash` `inline-until-done`; `ask_user_question`, `codemode` `inline`. +Set here: `edit`, `write`, and `ask_user_question` `persistent`; `todo` `hidden`; `thinking`, `web_search`, `bash`, and `codemode` `inline-until-done`. + +Bash blocks wrap the command under their header: up to 2 rows and the last 5 output rows, or in Expanded the whole command and the last 12 output rows. Related Pi settings in use: `hideThinkingBlock: true` (Pi's own thinking block is hidden; `levels.thinking` draws thinking inline instead). ### codemode-view -`codemode-view/index.ts`. Publishes a Quiet Transcript presentation for the `codemode` tool: the script (formatted with prettier once its call is complete, syntax highlighted) and the nested tool calls under the row header. Highlights previews successful scripts; Expanded shows the whole script, every nested call, and the full output. +`codemode-view/index.ts`. Publishes a Quiet Transcript presentation for the `codemode` tool: the script (formatted with prettier once its call is complete, syntax highlighted) and the nested tool calls under the row header. Live blocks show the last five output rows, like Bash. Highlights previews successful scripts; Expanded shows the whole script, every nested call, and the full output. - Setup: `npm install` in `codemode-view/` (prettier). Without it, scripts are shown unformatted. - Disable: delete `codemode-view/`; codemode rows revert to header plus output. -- Uses the `levels.codemode` setting from quiet-transcript (set here: `inline`). +- Uses the `levels.codemode` setting from quiet-transcript (set here: `inline-until-done`). ### code-blocks @@ -139,14 +141,6 @@ Related Pi settings in use: `hideThinkingBlock: true` (Pi's own thinking block i - Transcript previews are drawn only when Pi's `terminal.showImages` is on (set here: `false`, so only chip labels show); `terminal.imageWidthCells` (set here: `60`) sets preview width. - Disable: delete `image-chips/`. -### transcript-timestamps - -`transcript-timestamps.ts` + `transcript-stamp/layout.ts` (helper) + `native-transcript/insertion.ts` (shared helper). Clock time on user and assistant messages, optionally with the time to the first assistant text. Latency is saved in the session as `local-transcript-timestamp` entries. - -- Commands: `/stamp [timestamps|latency] [on|off]`; with no valid argument it reports the current state. -- Settings: stored in `~/.pi/agent/transcript-timestamps.json` (not in dotfiles), not `settings.json`. Keys `showTimestamps` (default `true`) and `showLatency` (default `false`). Currently both `false`. -- Disable: delete the file, or `/stamp timestamps off`. - ### trim-output `trim-output.ts`. Removes trailing plain spaces (that show nothing) from every rendered line, to cut terminal output on full redraws. Leaves lines with backgrounds, inverse, underline, strike, or images alone. Patches `tui.render`. No settings. @@ -169,7 +163,7 @@ Several of these attach through the shared decorator host in `composer/api.ts`; ### composer-layout -`composer-layout.ts` + `composer-layout/` (`roles.ts`, `dock-spacing.ts`, helpers). Lays out widgets above the composer in shared slots (`dockFill`, `dockActivity`, `dockTurnSummary`, `dockQueue`) and moves Pi's live working line into that dock. TUI only. Patches sibling render functions; a zero-row widget under the editor is how it finds them. Used by md-viewer, agents, work-dock-processes, turn-usage, steer-queue. +`composer-layout.ts` + `composer-layout/` (`roles.ts`, `dock-spacing.ts`, helpers). Lays out widgets above the composer in shared slots (`dockFill`, `dockActivity`, `dockTurnSummary`, `dockQueue`; `dockTrailing` text joins the turn summary row when it fits) and moves Pi's live working line into that dock. TUI only. Patches sibling render functions; a zero-row widget under the editor is how it finds them. Used by md-viewer, agents, work-dock-processes, turn-usage, steer-queue. - Disable: delete `composer-layout.ts` (widgets then stack in Pi's default order). Delete `composer-layout/` only if you also remove everything that imports `roles.ts`. @@ -243,7 +237,11 @@ Context % turns yellow at 70% and red at 90%. When a router model answers with a ### turn-usage -`turn-usage.ts`. After each run, a dim line above the composer: `12K in · 1.2K out · cache 80% · 4.2s · 3m ago`, shortened to fit. Clears when the next run starts; after an abort or on resume it shows only the age of the last user message. No settings. +`turn-usage.ts`. After each run, a dim line above the composer: `12K in · 1.2K out · cache 80% · 4.2s · 3m ago`, shortened to fit. Clears when the next run starts; after an abort or on resume it shows only the age of the last user message. + +A dim, right-aligned `cpu 12% · ram 34% (42/124G)` readout shares the turn summary row when both fit, and takes its own row otherwise. It is hidden while a turn is running. It turns the warning colour at 90% CPU or RAM. Reads `/proc` on Linux (RAM counts reclaimable cache as free) and Node's `os` counters elsewhere. + +- Settings (`turnUsage.systemStats`): `false` hides the readout (default on). An object sets `intervalSeconds` (default `2`, minimum `1`) and `show`, which picks and orders readouts from `"cpu"`, `"ram"`, `"load"` (default `["cpu", "ram"]`). ### stock @@ -257,7 +255,7 @@ Work Dock has two states: a collapsed one-line count below the composer, and an `work-dock/index.ts` (+ `api.ts`, `inspector.ts`, `process-activity.ts`). Collects rows from published providers and shows counts like `2 agents · 1 process` below the composer. RPC clients get the collapsed counts only. -- Keys: with the composer empty, **↓** or **←** opens the roster. `↑`/`↓` select, **Enter** inspects the row (if the provider supports it), **Esc** goes back, `Ctrl+C`/`Ctrl+D` close. +- With the composer empty, **↓** or **←** opens the roster. Use **↑**/**↓** to select, **Enter** to inspect, and **x** to stop the selected item. You’ll see a toast if the item doesn’t support stopping. **Esc**, `Ctrl+C`, and `Ctrl+D` close the roster. - Inspector keys: `Tab` (or `←`/`→`) switches Output / Details, `↑`/`↓`, `PageUp`/`PageDown`, `Ctrl+U`/`Ctrl+D`, `Home`/`End` scroll (scrolling up pauses following; `End` resumes), `Ctrl+O` toggles the provider's view when offered, `Esc` goes back. - No settings. Delete the directory and `agents` / `work-dock-processes` lose their dock (both import `work-dock/api.ts`; delete or edit them too). @@ -275,10 +273,11 @@ Work Dock has two states: a collapsed one-line count below the composer, and an - Tools registered: `agent`, `agent_message`, `agent_status`, `agent_stop`, `agent_reply`, `contact_supervisor`. Children get a subset (`contact_supervisor` for asking the parent; `agent` only while below `maxDepth`). Children have built-in `bash` but do not load or share `pi-processes`. - Commands: `/agents` browses runs and definitions (`←`/`→`/`Tab` switch tab, `↑`/`↓` select, `Enter` opens a run, `Esc` closes). - Definitions: Markdown files with front matter (`name`, `description`, optional `model`, `thinking`, `deny`) in `~/.pi/agent/agents/` and, in trusted projects, `/.pi/agents/`. A built-in `delegate` agent always exists. Duplicate names within one scope are dropped with a warning. -- Settings: `~/.pi/agent/extensions/agents/config.json` (not `settings.json`; absent by default): +- Settings: `~/.pi/agent/agents.json` (not `settings.json`; absent by default): | Key | Default | | --- | --- | +| `defaultModel` | unset (children use the parent's model); `provider/model` or a unique model ID. Precedence: the call's `model`, the definition's `model`, then this | | `maxLiveRuns` | `4`, across the session including waiting and nested runs | | `maxDepth` | `2` (main session is depth `0`) | | `activityWidget.outputLayout` | `off`; `stacked` shows a preview under each run, `inline` one line at the row end | @@ -300,7 +299,7 @@ Work Dock has two states: a collapsed one-line count below the composer, and an ### review -`review/index.ts` + modules (server, web UI, tests). Starts a loopback web dashboard for the current session: context-window usage and composition, and code (unstaged, commit ref, GitHub PR) and Markdown review with draft comments sent back to Pi. Footer status `dashboard · · Open ↗` links to it. Full usage in [review/README.md](review/README.md). +`review/index.ts` + modules (server, web UI, tests). Starts a loopback web dashboard for the current session: context-window usage and composition, and code (unstaged, commit ref, GitHub PR) and Markdown review with draft comments sent back to Pi. Footer status `dashboard · · Open ↗` links to Markdown (`review.page` = `context`, `code` or `markdown` picks the page). Full usage in [review/README.md](review/README.md). - Commands: `/dashboard` and `/review` start (or show) the server; `url` prints the full URL (keep it private; it grants access); `stop` closes it. - Settings (`review`, optional; not set here): `theme` (`mocha` default, `graphite`, `paper`, `system`), `markdownTheme` (`cursor` default, `inherit`, `graphite`, `mocha`, `paper`). @@ -324,7 +323,7 @@ Work Dock has two states: a collapsed one-line count below the composer, and an ### session-prs -`session-prs/index.ts` + `events.ts`, `view.ts`. Registers a `pr` tool (`track`, `untrack`, `refresh`) that the agent calls with a PR URL or `owner/repo#N`, and shows tracked PRs as quiet rows, e.g. `PR · owner/repo#42 ↗ · open · CI passed · Title`. Open PRs are polled once a minute; a merged/closed PR, newly failing CI, or requested changes queues a `session-prs.status.v1` message for the next turn. A successful bash `gh pr create` is tracked automatically. Details in [session-prs/README.md](session-prs/README.md). +`session-prs/index.ts` + `events.ts`, `view.ts`, `status-notice.ts`. Registers a `pr` tool (`track`, `untrack`, `refresh`) that the agent calls with a PR URL or `owner/repo#N`, and shows tracked PRs as quiet rows, e.g. `PR · owner/repo#42 ↗ · open · CI passed · approved · Title`. Open PRs are polled once a minute; a merged or closed PR queues a `session-prs.status.v1` message for the next turn, shown as `▸ pr · merged · owner/repo#42 · Title`. A successful bash `gh pr create` is tracked automatically. Details in [session-prs/README.md](session-prs/README.md). - Commands: `/prs` or `/prs refresh` fetches status; `/prs clear` dismisses the widget on the current branch. - Setup: `gh` authenticated for the PR's host. Tracking is stored in session entries. diff --git a/.pi/agent/settings.json b/.pi/agent/settings.json index c417aab..d64e829 100644 --- a/.pi/agent/settings.json +++ b/.pi/agent/settings.json @@ -48,10 +48,10 @@ "write": "persistent", "todo": "hidden", "thinking": "inline-until-done", - "ask_user_question": "inline", + "ask_user_question": "persistent", "web_search": "inline-until-done", "bash": "inline-until-done", - "codemode": "inline" + "codemode": "inline-until-done" }, "diffLines": 8 }, @@ -72,4 +72,4 @@ "openai-codex/gpt-6-luna": "high" }, "defaultProjectTrust": "always" -} \ No newline at end of file +}