From a450604d8f4ed1dcd7e84e0c114d9addde136c60 Mon Sep 17 00:00:00 2001 From: Justin Parker Date: Tue, 3 Nov 2026 10:22:08 -0800 Subject: [PATCH] Make terminal a button that expands the collapsed agent panel AI Assisted --- .agents-docs/AGENTS-architecture.md | 2 +- plan2code-app/ui/app.js | 17 ++++++ scripts/test-app-meter.mjs | 11 ++++ scripts/test-web-console-page-session.mjs | 58 ++++++++++++++++++++ src/web-console/public/app-bridge.js | 3 +- src/web-console/public/index.html | 2 +- src/web-console/public/screens/core.js | 37 +++++++++++-- src/web-console/public/state.js | 3 + src/web-console/public/styles/responsive.css | 9 +-- 9 files changed, 131 insertions(+), 11 deletions(-) diff --git a/.agents-docs/AGENTS-architecture.md b/.agents-docs/AGENTS-architecture.md index 6ca1bbe..3cdcf03 100644 --- a/.agents-docs/AGENTS-architecture.md +++ b/.agents-docs/AGENTS-architecture.md @@ -447,7 +447,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web | `public/meter.js` | PURE, imports only `skills.js`: the session meter. `WEIGHTS` (the events that are not a skill's own launch, merged with each skill's `weight` from `skills.js`; its keys are also `RUN_EVENTS`, the `run` events `post` accepts), `LAUNCH_COUNTED` (workflows whose launch itself scores), the built-phase sizing (`TASK_EVENTS`, the keys of `TASK_BONUS`: `implement-phase` +0 and `implement-review-phase` +1; `isTaskCount()` accepts a whole `tasks` from 1 to `MAX_TASKS` 999; `runPoints()` scores such a run `ceil(tasks / TASKS_PER_POINT)` (3) plus its bonus, and any other run its `WEIGHTS` value), `ANSWERS_PER_POINT` 2 (`answer` entries score per skill run, `floor(count / 2)`), `breakdownFrom()` (the click-the-ring list: one row per scoring entry plus one answers row per skill run), `pointsFrom()` (the count, its sum, folded from `ledger.ndjson` and deduplicated by id, never stored), `levelFor()` with `YELLOW_AT` 5 / `RED_AT` 10, `ringFraction()` (full at `RING_FULL` 15), `WORDS`, `tooltipFor()`, `RED_BANNER` and `meterView()` | | `public/mentions.js` | PURE, no imports: the `@name` popover's logic — `mentionAt()` finds an `@partial` at the caret, `matchNames()` filters the workspace names, `applyMention()` splices a pick in and returns the new caret. Used by the Ask box, notes and text answers | | `public/favicon.js` | The tab icon's status bar. `faviconState({ mood, spin })` (PURE) maps the call `renderStatus()` makes for Planny's line to `busy` (the spinning ring), `ready` (`point`), `attention` (`adrift`, `gone`, or `work` without the ring — the stale line) or `plain` (`done`, `happy`); a finished screen gets no special case, so one still offering a press points and lights `ready` (the desktop app's taskbar dot follows), a stranded press is `attention`, and only all done or paused is `plain`; `faviconSvg()` is `FAVICON_BODY` (kept equal to `favicon.svg` by a test) plus a bar along the bottom edge in the `FAVICON_COLORS` color (busy dashed on a white strip, so the states differ by pattern; the rest solid); `setFavicon()` swaps both `` hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from `say()` in `renderStatus()`, which runs every second | -| `public/app-bridge.js` | The messages the page posts to the desktop app that frames it. `framed()` is true inside a frame; `tellApp(kind, extra)` posts `{ plan2code: kind }`, a named request with no free text: `looks` (the highlight's dark shades, from `applyLooks()`, for the app bar's buttons), `agent-continue` (the in-app **continue** button on the Not running line: the app types the keystrokes `continueKeys()` in `plan2code-app/ui/meter.js` names into the agent's terminal, `continue` and Enter, then under Claude Code its send-now chord ctrl+x ctrl+s, so a word queued behind a stuck turn is delivered) `new-session` (the meter popover's New Session: the app presses its own bar button, confirm and all) and `activities-full` (`{ on }`, an Activities game going in or out of full screen: the app lays the console's frame over its bar and terminal and puts the window in full screen, and out of it only if it put it there; `taskbarSwitch()` checks the boolean, and the window permissions are in `capabilities/default.json`). Nothing outside a frame | +| `public/app-bridge.js` | The messages the page posts to the desktop app that frames it. `framed()` is true inside a frame; `tellApp(kind, extra)` posts `{ plan2code: kind }`, a named request with no free text: `looks` (the highlight's dark shades, from `applyLooks()`, for the app bar's buttons), `agent-continue` (the in-app **continue** button on the Not running line: the app types the keystrokes `continueKeys()` in `plan2code-app/ui/meter.js` names into the agent's terminal, `continue` and Enter, then under Claude Code its send-now chord ctrl+x ctrl+s, so a word queued behind a stuck turn is delivered), `terminal-open` (the in-app **terminal** button, shown in place of the word in every What to check line while the app's terminal panel is collapsed: the app presses the panel's own Collapse/View button, and only when collapsed; the app tells the page the panel's state with `terminal-state` `{ collapsed }` on the page's `console-ready` and on every change, heard through `onAppMessage` into `page.terminalCollapsed`), `new-session` (the meter popover's New Session: the app presses its own bar button, confirm and all) and `activities-full` (`{ on }`, an Activities game going in or out of full screen: the app lays the console's frame over its bar and terminal and puts the window in full screen, and out of it only if it put it there; `taskbarSwitch()` checks the boolean, and the window permissions are in `capabilities/default.json`). Nothing outside a frame | | `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table, one entry per non-null `subagents` field in `skills.js`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max, strength }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20, `strength` not one of `STRENGTHS`; `strength` is `balanced`, `thrifty`, `best` or `session`, missing reads as `balanced`, saved per project and skill in each `subagents.json` entry and sent as a `Helper strength:` line in the "on" block), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, the `cmd-*.mjs` files, `patches.mjs`, `settings.mjs`, the page and the tests; in `SERVABLE` and preloaded | | `handoffs.mjs` | the handoff store, the only code that names, lists, marks, deletes and sweeps handoffs, all in `~/.plan2code/handoffs/` (`PLAN2CODE_HANDOFFS_DIR` for tests; `PLAN2CODE_NOW` pins its clock): `newHandoff()` claims `YYYY-MM-DD-HHmm-handoff` (`-2`, `-3` on a clash, the `.json` created exclusively) and writes only `.json` (`{ v: 1, id, title, worktree, project, spec, workflow, skill, written, fromStop, usedAt }`), the agent writing `.md`; `listHandoffs(worktree)` (unused, same worktree, `.md` present, newest first, title and Next task read off the document); `readHandoffMeta()`, `markHandoffUsed()`; `removeHandoff()` (`HANDOFF_ID` only, regular files, never a link, realpath inside the folder, throws on any refusal); `staleHandoffs()` / `removeHandoffs()` for the sweep | | `notepads.mjs` | the notebook store (the feature is named Notebook; its code, routes and storage folder keep the name `notepad`), the only code that names, reads, writes and removes notebooks, one per folder Plan2Code runs in, in `~/.plan2code/notepads/-<12 hex>/` (`PLAN2CODE_NOTEPADS_DIR` for tests), split into named tabs: `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order, last, tabs: { id: { name, created, sent? } } }`) and `tabs//note.md` with `tabs//images/`. `notepadKey()` (the folder's basename slug and the first 12 hex of `sha256(foldKey(folder))`), `listTabs()` / `defaultTabId()`, `readNotepad(folder, tab)` (never creates or writes anything; `{ tabs, last, tab }` with the tab's `text`, `savedAt` and `images` repeated at the top), the tab changes `createTab()` / `renameTab()` / `reorderTabs()` / `setLastTab()` / `deleteTab()` (index first, then the folder; names pass `normalizeTabName()`, `TAB_NAME_MAX` 40, any case compared by `nameKey()`, `NOTEPAD_MAX_TABS` 20), `saveNote(folder, tab, text)` (1 MB cap, atomic), `addImage()` / `addThumb()` / `removeImage()` (JPEG bytes only, 200 pictures per tab, UUID names), `imagePath()` (regular files whose realpath stays inside the folder), `staleNotepads(now, maxAgeMs)` (the real folders directly under it named like a key, never a link or a file, whose newest file is at least `maxAgeMs` old, as `{ key, folder, path }` with `folder` from `meta.json` or null), `removeNotepad(key)` (the key checked against `NOTEPAD_KEY_RE`, the path kept inside the notepads folder by `path.relative`, a link refused, then the whole folder removed; User Preferences, Cleanup is its only caller) and `NotepadError` (`code` and `status`, turned into `{ error }` by the `/notepad` routes). **Migration:** a notepad in the first shape (`note.md` and `images/` at the top) reads as one virtual tab, Notes (`LEGACY_TAB_ID`), and writes nothing; its first write moves the files into `tabs//` and writes `tabs.json` last, every step safe to run again after a crash. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders on the next write. Every write runs under a `notepad.lock` in the notepad's folder. The agent CLI never imports it: nothing in a notepad reaches the agent | diff --git a/plan2code-app/ui/app.js b/plan2code-app/ui/app.js index c9c3a27..8d2eb0b 100644 --- a/plan2code-app/ui/app.js +++ b/plan2code-app/ui/app.js @@ -654,6 +654,18 @@ function applyPaneLayout() { termCollapseBtn.textContent = paneCollapsed ? 'View Agent Terminal' : 'Collapse'; termCollapseBtn.setAttribute('aria-pressed', String(paneCollapsed)); updateBadge(); + tellTerminalState(); +} + +// The console page's What to check lines make "terminal" a button while the +// pane is collapsed, so the page hears the state on its hello (`force`) and +// whenever it changes, never on every drag of the handle. +let toldCollapsed = null; + +function tellTerminalState(force = false) { + if (!force && toldCollapsed === paneCollapsed) return; + toldCollapsed = paneCollapsed; + if (frame.contentWindow) frame.contentWindow.postMessage({ plan2code: 'terminal-state', collapsed: paneCollapsed }, '*'); } function savePaneSettings() { @@ -750,6 +762,7 @@ window.addEventListener('message', (event) => { // The Desktop app switch in its User Preferences shows what app.json holds. const on = !appState || appState.taskbarSignal !== false; event.source.postMessage({ plan2code: 'taskbar-state', on }, '*'); + tellTerminalState(true); } else if (kind === 'attention') { const signal = attentionSignal(event.data); if (signal) invoke('set_attention', { signal }).catch(() => {}); @@ -766,6 +779,10 @@ window.addEventListener('message', (event) => { if (on !== null) setGameFull(on); } else if (kind === 'agent-continue') { typeContinue(); + } else if (kind === 'terminal-open') { + // The status line's terminal button: expands a collapsed pane, the same + // way its own button does (focus and the saved setting included). + if (paneCollapsed) termCollapseBtn.click(); } else if (kind === 'new-session') { // The bar's own button, so the press is confirmed exactly the same way. if (!restartBtn.hidden) restartBtn.click(); diff --git a/scripts/test-app-meter.mjs b/scripts/test-app-meter.mjs index abecdd3..57db58f 100644 --- a/scripts/test-app-meter.mjs +++ b/scripts/test-app-meter.mjs @@ -85,6 +85,17 @@ test("app.js types the continue button's keystrokes through continueKeys, for th assert.doesNotMatch(typeContinue, /data: 'continue'/, "no hand-typed word left beside it"); }); +// The console page's What to check lines make "terminal" a button while the +// pane is collapsed (core.js renderStatus), so it must hear the pane's state. +test("app.js tells the console page whether the terminal pane is collapsed, and expands only a collapsed pane on terminal-open", () => { + const layout = APP_JS.slice(APP_JS.indexOf("function applyPaneLayout"), APP_JS.indexOf("function savePaneSettings")); + assert.match(layout, /updateBadge\(\);\s+tellTerminalState\(\);\s+\}/, "every layout change is told"); + assert.match(layout, /plan2code: 'terminal-state', collapsed: paneCollapsed/, "a named message with one boolean"); + assert.match(layout, /if \(!force && toldCollapsed === paneCollapsed\) return;/, "only a change is told, not every drag"); + assert.match(APP_JS, /plan2code: 'taskbar-state', on \}, '\*'\);\s+tellTerminalState\(true\);/, "the page hears it on its hello"); + assert.match(APP_JS, /kind === 'terminal-open'\) \{[^}]*if \(paneCollapsed\) termCollapseBtn\.click\(\);/, "the pane's own button expands it"); +}); + test("the bar reads project menu, New Session, agent menu, with both menus outside the scrolling row", () => { const row = INDEX_HTML.slice(INDEX_HTML.indexOf('
'), INDEX_HTML.indexOf('
row.indexOf(`id="${id}"`); diff --git a/scripts/test-web-console-page-session.mjs b/scripts/test-web-console-page-session.mjs index 80f0662..f1e0809 100644 --- a/scripts/test-web-console-page-session.mjs +++ b/scripts/test-web-console-page-session.mjs @@ -330,6 +330,64 @@ test("under the app, the not running line's continue is a button that asks the a assert.ok(await press.isDisabled(), "held off, so a double press does not type it twice"); }); +// The app's word on its terminal panel, from a real window standing in as the +// parent (onAppMessage hears the parent only). Keeps FAKE_APP_FRAME's record. +async function tellTerminal(s, collapsed) { + await s.page.evaluate((c) => { + if (!window.__app) { + const frame = document.createElement("iframe"); + document.body.append(frame); + const app = frame.contentWindow; + app.postMessage = (m) => window.__toApp.push(m); + Object.defineProperty(window, "parent", { configurable: true, get: () => app }); + window.__app = app; + } + dispatchEvent(new MessageEvent("message", { data: { plan2code: "terminal-state", collapsed: c }, source: window.__app })); + }, collapsed); +} + +test("under the app with the terminal panel collapsed, terminal in every What to check line is a button that asks the app to expand it", async (t) => { + const s = await openSession(await suite.browser(), { + t, + workflow: "implement", + clock: true, + payload: { headline: { stage: "Phase 1", cleared: 0, total: 3 }, agent: { status: "working", activity: "Task 1 of 3: the reader" } }, + env: { PLAN2CODE_IN_APP: "1" }, + init: FAKE_APP_FRAME, + }); + const press = s.page.locator("#agent-text .agent-terminal-btn"); + await lineSays(s, /Task 1 of 3: the reader/); + await tellTerminal(s, true); + assert.equal(await press.count(), 0, "the plain working line has no button"); + + // Quiet for 30 s: the approval hint. + await s.page.clock.fastForward(40_000); + await lineSays(s, /waiting on an approval in the terminal panel/); + assert.equal(await press.textContent(), "terminal"); + await press.click(); + await until(async () => (await toApp(s, "terminal-open")).length === 1, 5000); + assert.deepEqual(await toApp(s, "terminal-open"), [{ plan2code: "terminal-open" }], "a named request, nothing else in it"); + + // Quiet for two minutes: the stale line, then the panel opens. + await s.page.clock.fastForward(100_000); + await lineSays(s, /^Still working on it\./); + assert.equal(await press.count(), 1, "the stale line carries the button"); + await tellTerminal(s, false); + await until(async () => (await press.count()) === 0, 5000); + assert.match(await textOf(statusLine(s)), /check your terminal/, "expanded, the word is plain again"); + + // Nobody listening, panel collapsed again: the not running line. + await tellTerminal(s, true); + await s.page.clock.setSystemTime(Date.now()); + s.post({ items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name." }], agent: { status: "waiting" } }); + await lineSays(s, /^Your turn: 1 question waiting\./); + assert.equal(await press.count(), 0, "the your-turn line has no button"); + await s.page.clock.fastForward(200_000); + await lineSays(s, /^Plan2Code is not running right now\./); + assert.equal(await press.count(), 1, "the not running line carries the button"); + assert.equal(await s.page.locator("#agent-text .agent-key-btn").textContent(), "continue", "continue keeps its own button"); +}); + // The app's webview opens no new windows, so a link off the page asks the // console to open it in the default browser instead, and says where to paste // it when that fails. diff --git a/src/web-console/public/app-bridge.js b/src/web-console/public/app-bridge.js index 8db9109..d38947a 100644 --- a/src/web-console/public/app-bridge.js +++ b/src/web-console/public/app-bridge.js @@ -26,7 +26,8 @@ export function linkLeavesPage(href, origin) { /** * Call `handler(data)` for each `{ plan2code: kind, ... }` message the frame's * parent sends, and for nothing from anywhere else (another frame, the page - * itself). The app's only answer today is `taskbar-state`. + * itself). The app sends `taskbar-state`, `terminal-state` and the loop's + * answers (wireLoopMessages). */ export function onAppMessage(kind, handler) { window.addEventListener("message", (event) => { diff --git a/src/web-console/public/index.html b/src/web-console/public/index.html index 14ab399..e4dfc9d 100644 --- a/src/web-console/public/index.html +++ b/src/web-console/public/index.html @@ -1095,7 +1095,7 @@
You see
Not running (Planny gray and still).
Likely cause
Plan2Code has not checked in for a few minutes.
-
Do this
Look at the terminal. If it is idle, type continue there.
Look at the terminal panel. If it is idle, press continue in the line beside Planny, which types it there for you.
+
Do this
Look at the terminal. If it is idle, type continue there.
Look at the terminal panel. If it is idle, press continue in the line beside Planny, which types it there for you. Panel collapsed? Press terminal in that line to expand it.
  • diff --git a/src/web-console/public/screens/core.js b/src/web-console/public/screens/core.js index c1d6839..0684513 100644 --- a/src/web-console/public/screens/core.js +++ b/src/web-console/public/screens/core.js @@ -68,7 +68,7 @@ import { renderBriefButton, renderDoc, renderOverview } from "./docs.js"; import { board, renderGitBoard, resetBoard } from "./git-host.js"; import { renderWorkspace, tellFolderIssues } from "./workspace.js"; import { openHelpOn } from "./help-dialog.js"; -import { linkLeavesPage, startNewSession, tellApp } from "../app-bridge.js"; +import { linkLeavesPage, onAppMessage, startNewSession, tellApp } from "../app-bridge.js"; import { askOfflineFlipped, askState, declineOpen, renderAside, renderAsk, renderSubagents, renderSubagentsButton } from "./ask.js"; import { renderHandoff, renderLoopEnd, renderHomeButton, renderStopButton, renderStopControls, renderStopping, stopInProgress, stopWarning } from "./ending.js"; import { renderNotepadButton } from "./notepad.js"; @@ -1175,6 +1175,22 @@ function continueButton() { return btn; } +// Under the app with its terminal panel collapsed (the app's `terminal-state`), +// "terminal" in a What to check line is a button asking the app to expand it. +function terminalButton(word) { + const btn = el("button", "agent-terminal-btn", word); + btn.type = "button"; + btn.title = "Expand the agent terminal panel"; + btn.addEventListener("click", () => tellApp("terminal-open")); + return btn; +} + +// A line's plain text with its first "terminal" turned into terminalButton(). +function withTerminalButton(part) { + const word = /\bterminal\b/.exec(part); + return [document.createTextNode(part.slice(0, word.index)), terminalButton(word[0]), document.createTextNode(part.slice(word.index + word[0].length))]; +} + // The favicon state last told to the app (attention.rs turns it into the // taskbar's dot). Told only when it changes, never on every status redraw. let lastAttention = null; @@ -1204,11 +1220,17 @@ export function renderStatus() { moodVar = Math.floor(Math.random() * MOOD_VARIANTS[mood]); } bot.setAttribute("class", `planny is-${mood} v${moodVar}`); - const shown = check ? `${line}|check` : line; + const terminalLink = Boolean(check && page.inApp && page.terminalCollapsed); + const shown = check ? `${line}|check${terminalLink ? "|terminal" : ""}` : line; if (text.dataset.line !== shown) { text.dataset.line = shown; - const parts = line.split(/\*\*(.+?)\*\*/).map((part, i) => { - if (i % 2 === 0) return document.createTextNode(part); + let linked = !terminalLink; + const parts = line.split(/\*\*(.+?)\*\*/).flatMap((part, i) => { + if (i % 2 === 0) { + if (linked || !/\bterminal\b/.test(part)) return document.createTextNode(part); + linked = true; + return withTerminalButton(part); + } // Under the app the terminal is in the same window, so the word to // type is a button that types it there instead. if (page.inApp && part === "continue") return continueButton(); @@ -2153,6 +2175,13 @@ export function wireChrome() { tellAttention("plain"); }); + // The app says whether its terminal panel is collapsed, on the page's hello + // and on every change; the status line's terminal button follows it. + onAppMessage("terminal-state", (data) => { + page.terminalCollapsed = data.collapsed === true; + renderStatus(); + }); + // Under the app, a link off the page goes to the default browser through // the console: the app's window opens no new ones, so the click alone would // do nothing. Capture phase, ahead of any handler on the link itself. diff --git a/src/web-console/public/state.js b/src/web-console/public/state.js index 7099553..3170bba 100644 --- a/src/web-console/public/state.js +++ b/src/web-console/public/state.js @@ -111,6 +111,9 @@ export const page = { // false until the first frame lands, same as every other flag here, and // from an older server that sends none. inApp: false, + // The app's terminal panel is collapsed (its `terminal-state`): the status + // line's What to check lines then make "terminal" a button that expands it. + terminalCollapsed: false, // The Implementation Loop, as the desktop app drives it: `loop` is the // state's `{ driving: true }` or null (it locks the page, selectors.js // loopDriving); `loopFacts` is what the app answered to `loop-facts` diff --git a/src/web-console/public/styles/responsive.css b/src/web-console/public/styles/responsive.css index b949742..ac6c11c 100644 --- a/src/web-console/public/styles/responsive.css +++ b/src/web-console/public/styles/responsive.css @@ -118,15 +118,16 @@ color: var(--accent); font-weight: 700; } -/* Under the app, the word is a button that types it into the agent's terminal. */ -.agent-key-btn { +/* Under the app, the word is a button that types it into the agent's terminal; + "terminal" itself, while the app's panel is collapsed, expands it. */ +.agent-key-btn, .agent-terminal-btn { font: inherit; font-weight: 700; color: var(--accent); background: var(--accent-soft); border: 1px solid var(--accent-line); border-radius: 6px; padding: 0 6px; cursor: pointer; } -.agent-key-btn:hover:not(:disabled) { border-color: var(--accent); } +.agent-key-btn:hover:not(:disabled), .agent-terminal-btn:hover { border-color: var(--accent); } .agent-key-btn:disabled { opacity: 0.55; cursor: default; } -.agent-key-btn:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; } +.agent-key-btn:focus-visible, .agent-terminal-btn:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; } /* "What to check", beside the quiet and Not running lines. A link in a button's clothes. */ .status-help {