From 55965b247ba901274c89cd204144ec0d55477e1c Mon Sep 17 00:00:00 2001 From: Trefor Southwell <48591903+springfall2008@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:02:52 +0000 Subject: [PATCH 1/3] docs: board toolbar design and plan Co-Authored-By: Claude Opus 5.5 --- .../plans/2026-11-26-web-ui-toolbar.md | 37 +++++++++++++++++ .../specs/2026-11-26-web-ui-toolbar-design.md | 40 +++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-26-web-ui-toolbar.md create mode 100644 docs/superpowers/specs/2026-11-26-web-ui-toolbar-design.md diff --git a/docs/superpowers/plans/2026-11-26-web-ui-toolbar.md b/docs/superpowers/plans/2026-11-26-web-ui-toolbar.md new file mode 100644 index 0000000..e9279ab --- /dev/null +++ b/docs/superpowers/plans/2026-11-26-web-ui-toolbar.md @@ -0,0 +1,37 @@ +# Web UI board toolbar — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Move the board actions (pause/resume/stop/restart, intent limit, add hint/intent/amendment) from the goal's drawer to a toolbar on the Board tab, leaving only node-specific shortcuts in the drawer. + +**Architecture:** Browser only. A new `web/public/toolbar.js` mounted by `board.js` under the status strip reuses the form and control building blocks from `forms.js` / `controls.js` and the pure rules in `writes.js`. The strip's intent limit becomes an inline editor. No server or skill change. + +**Tech Stack:** plain ES modules, Deno for lint/format/unit tests. + +**Spec:** `docs/superpowers/specs/2026-11-26-web-ui-toolbar-design.md` + +## Global Constraints + +- Same routes and payloads as today (`POST /api/hints`, `/intents`, `/amendments`, `/boards/control`); toolbar hints and intents send no `about` / `from`. +- Controls shown only when valid for the goal's state (`controlActions` in `writes.js`); Stop confirms inline with focus on Cancel; no browser dialogs. +- After a successful write: clear the form, say "Added — it will appear in the graph shortly", `pollNow()`. After a 409 from a control: re-read state and re-render. +- Never `window`; never `innerHTML` with untrusted text; pure modules `// @ts-check`, no DOM; `deno task check` lints/formats `web/public`. +- Board view only (not a tag view, not Browse). + +## Review Focus + +1. Switching boards while a toolbar panel or Stop confirmation is open must close it and never send for the old board. +2. A write from the toolbar and a write from a drawer shortcut in flight at once must each report on their own form. +3. The inline limit editor: Enter saves once; Escape and blur cancel; an invalid value shows the existing message without sending. + +### Task 1: Board toolbar + +**Files:** Create `web/public/toolbar.js`. Modify `web/public/board.js` (mount the toolbar under the strip; make the +strip's limit an inline editor; close panels on board switch), `web/public/drawer.js` / `forms.js` / `controls.js` +(goal drawer read-only; drawer keeps only the two collapsed shortcuts), `web/public/style.css`, `README.md` (Web UI +section: where the controls are now). Tests: `tests/unit/web-public.test.ts` for any new pure helper. + +- [ ] Step 1: implement per the spec. +- [ ] Step 2: `deno task check && deno task test:unit` PASS. +- [ ] Step 3: local smoke (local stack only; your own server on `WEB_PORT=8788`): each toolbar action and both drawer shortcuts post the expected body; a board switch closes an open panel. +- [ ] Step 4: commit `feat(web): board toolbar for hints, intents, amendments and run controls`. diff --git a/docs/superpowers/specs/2026-11-26-web-ui-toolbar-design.md b/docs/superpowers/specs/2026-11-26-web-ui-toolbar-design.md new file mode 100644 index 0000000..9e56f01 --- /dev/null +++ b/docs/superpowers/specs/2026-11-26-web-ui-toolbar-design.md @@ -0,0 +1,40 @@ +# Web UI: board toolbar — design (small change) + +Status: approved in conversation, 2026-11-26. Changes where the controls from +`2026-11-26-web-ui-hints-intents-design.md` live; no server change. + +## Why + +The person found Add hint, Add intent, Add amendment and the run controls buried: they sat in the goal node's drawer +below the progress block and goal text, and Add hint at the bottom of every node's drawer. They are board actions, so +they belong on the Board tab's bar, where the person is already looking. + +## What changes + +- **Toolbar** on the Board tab, a row directly under the status strip, shown only for a board view (not a tag view): + - State controls valid for the goal's state: **Pause lead** (running) or **Resume lead** (paused); **Stop…** + (running or paused), confirmed inline under the toolbar with focus on Cancel; **Restart** (stopped, not done), + followed by "Now run `board-runner run ` again to restart the workers." + - **+ Hint**, **+ Intent** (running or paused), **+ Amendment** (not done). Each opens its form in one panel under the + toolbar; only one panel is open at a time; Escape or the same button closes it. A hint or intent added here is + board-wide (no `about` / `from`). +- **Intent limit** in the status strip: "Intents 14 of 20" — the limit is a button; clicking it turns it into a small + input (number or `none`) with Enter to save, Escape to cancel, and the note about the board file's `max_intents` as a + tooltip. A done board shows it as plain text. +- **Drawer** keeps only node-specific shortcuts, at the bottom of the Memory tab, collapsed to one line each until + clicked: "Hint about this node" on any board node (`about` = node), and "Try next from this fact" on facts (an intent + with `from` = the fact) while running or paused. +- **Goal drawer** becomes read-only again: progress block, goal text, the amendments list. Its Controls, Add intent and + Add amendment move to the toolbar. +- Everything else is unchanged: same routes and payloads, same pure rules in `writes.js`, same `pollNow()` after a + write, same 409 handling (re-read state, re-render), same in-flight disabling, `textContent` only, no browser dialogs. + +## Approaches + +The person picked the toolbar over keeping the forms in the drawer; a separate "Board" drawer tab was not considered +needed. One sensible way. + +## Left to the builder + +Toolbar styling and wrapping at narrow widths; module boundaries (a `toolbar.js` reusing `forms.js` / `controls.js` +building blocks is expected). From bcf05abd14edb3e36fc1c75c97ce9f9d1a32ee40 Mon Sep 17 00:00:00 2001 From: Trefor Southwell <48591903+springfall2008@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:17:01 +0000 Subject: [PATCH 2/3] feat(web): board toolbar for hints, intents, amendments and run controls The board's actions move from the goal's drawer to a toolbar under the status strip on a board view: the run controls valid for the goal's state (Stop confirmed inline, focus on Cancel), and + Hint, + Intent and + Amendment opening one panel at a time. Hints and intents added there are board-wide. The strip's intent limit edits in place (Enter saves once; Escape and blur cancel). The drawer keeps two collapsed shortcuts, "Hint about this node" and "Try next from this fact"; the goal drawer is read-only, and its amendment list redraws after each poll. Each board's toolbar is built afresh, so a switch closes any panel and nothing drawn for one board sends for another. Co-Authored-By: Claude Opus 5.5 --- README.md | 63 ++++--- tests/unit/web-public.test.ts | 33 ++++ web/public/app.js | 7 +- web/public/board.js | 52 +++++- web/public/controls.js | 208 ++++++--------------- web/public/drawer.js | 18 +- web/public/forms.js | 125 ++++++++----- web/public/sending.js | 8 +- web/public/style.css | 89 +++++++-- web/public/toolbar.js | 341 ++++++++++++++++++++++++++++++++++ web/public/writes.js | 31 +++- 11 files changed, 723 insertions(+), 252 deletions(-) create mode 100644 web/public/toolbar.js diff --git a/README.md b/README.md index be60e41..9377a7d 100644 --- a/README.md +++ b/README.md @@ -219,44 +219,55 @@ see [Development](#development). - **Drawer:** click a node for three tabs. **Memory** has the full content, tags, scope and claim. For an intent it starts with "Starting point": what it builds on and the latest measurement before it. For a fact it shows the result first, and for the goal the progress fields and latest measurement. **Links** lists links in and out, and clicking - one selects that node. **Worker log** is described next. On a board, the Memory tab also has the write forms - described in "Writing to a board". + one selects that node. **Worker log** is described next. On a board, the Memory tab also ends with the node's + shortcuts described in "Writing to a board". ### Writing to a board -On the Board tab, the Memory tab of a node's drawer has forms below its content. A form is disabled while its request -is in flight. On success it clears, says "Added — it will appear in the graph shortly" and polls the graph at once. On -failure it shows the server's error. If the board is over 400 nodes, the page warns that what you add may not appear. - -- **Add hint**, on every node. It is advice for the lead, read at its next round. On an intent, fact or hint it links - to that node. On the goal, conclusion, progress or rules node it links to nothing and applies to the whole board. A - hint is allowed in any board state. -- **Add intent**, on the goal and on facts, while the board is running or paused. Write what a worker should try, and - optionally "Done when" and "Give up when". Left empty, they become "a fact reporting what trying this showed" and - "it cannot be done within the board's rules; record an inconclusive fact". On a fact, the intent is linked - `derived-from` it. The form shows how many intents the board has used out of `Max intents`. A person's intent is - accepted even over the limit, and the lead never drops it as pointless: only a fact closes it. -- **Add amendment**, on the goal, in any state but done. An amendment is a sub-goal or fallback, such as "if 20% is +A board's actions are on the Board tab, in a **toolbar** directly under the status strip (on a board, not on a tag's +graph): the run controls, then **+ Hint**, **+ Intent** and **+ Amendment**. Each of those three opens its form in a +panel under the toolbar. Only one panel is open at a time, and Escape or the same button closes it. Switching boards +closes it. A hint or intent added from the toolbar is for the whole board, linked to no node. + +The drawer keeps only what is about one node, at the bottom of its Memory tab, each collapsed to one line until you +click it: **Hint about this node** on any node of the board but the goal, and **Try next from this fact** on a fact +while the board is running or paused. The goal's drawer is read-only: its progress, the goal text and the list of the +board's amendments. + +A form is disabled while its request is in flight. On success it clears, says "Added — it will appear in the graph +shortly" and polls the graph at once. On failure it shows the server's error. If the board is over 400 nodes, the page +warns that what you add may not appear. + +- **Hints.** A hint is advice for the lead, read at its next round. From the toolbar it applies to the whole board. + From "Hint about this node" on an intent, fact or hint it links to that node; on a conclusion, progress, rules or + amendment node it links to nothing and applies to the whole board. A hint is allowed in any board state. +- **Intents**, while the board is running or paused. Write what a worker should try, and optionally "Done when" and + "Give up when". Left empty, they become "a fact reporting what trying this showed" and "it cannot be done within the + board's rules; record an inconclusive fact". From "Try next from this fact", the intent is linked `derived-from` + that fact. The form shows how many intents the board has used out of `Max intents`. A person's intent is accepted + even over the limit, and the lead never drops it as pointless: only a fact closes it. +- **+ Amendment**, in any state but done. An amendment is a sub-goal or fallback, such as "if 20% is out of reach, 15% is acceptable, as long as X is unchanged". The goal stays as written, and the lead reads every amendment with it, the newer winning a conflict. A fallback applies only once the goal's own target is out of reach. Without `[measure]`, meeting it concludes the board as done, citing the amendment. With `[measure]`, the runner's - measurement stays the arbiter, so the lead stops with `Stopped: amended target met (amendment )`. The drawer - lists the board's amendments. -- **Controls**, on the goal. Each changes the goal memory in the database, so it works for a board run on any - machine. Only the buttons valid for the goal's state are shown. + measurement stays the arbiter, so the lead stops with `Stopped: amended target met (amendment )`. The goal's + drawer lists the board's amendments. +- **Run controls**, at the start of the toolbar. Each changes the goal memory in the database, so it works for a board + run on any machine. Only the buttons valid for the goal's state are shown. - **Pause lead** (while running) swaps `state:running` for `state:paused`. The lead plans nothing new and writes nothing, but keeps its claim and ends each round with `BOARD-LEAD paused`. Workers finish what they hold and take intents that are already open, including ones you add. The runner keeps going and asks the lead for a round every 2 minutes, so **Resume lead** is seen within about that time. - - **Stop** (while running or paused) sets `state:stopped`, after a confirmation in the page that focuses Cancel. - Workers end at their next step, and the runner lets running workers finish, then exits. + - **Stop…** (while running or paused) sets `state:stopped`, after a confirmation under the toolbar that focuses + Cancel. Workers end at their next step, and the runner lets running workers finish, then exits. - **Restart** (when stopped) sets `state:running` again and says to run `board-runner run ` again to start the workers. It is not offered when the goal is done. - - **Intent limit** shows the goal's `Max intents` and saves a whole number, or `none`. Saving rewrites that line and - keeps the rest of the goal. Once the count of intents reaches a lowered limit, the lead plans no more, and it stops - the board once no intent is open. Raising it on a board that stopped at its limit sets it running again, as `/blackboard resume` does, with - the same note to run the runner again. A higher `max_intents` in the board file raises it again on the next - `board-runner run`. + - **Intent limit** is in the status strip: in "Intents 14 of 20" the limit is a button. Click it to edit the goal's + `Max intents` in place, type a whole number or `none`, and press Enter to save; Escape, or clicking away, cancels. + A done board shows it as plain text. Saving rewrites that line and keeps the rest of the goal. Once the count of + intents reaches a lowered limit, the lead plans no more, and it stops the board once no intent is open. Raising it + on a board that stopped at its limit sets it running again, as `/blackboard resume` does, with the same note to + run the runner again. A higher `max_intents` in the board file raises it again on the next `board-runner run`. The browser sends only text and the node it is about. The server builds every word of the template, every tag and every link, and folds line breaks in your text to spaces so no field can forge another line. The same writes are available in diff --git a/tests/unit/web-public.test.ts b/tests/unit/web-public.test.ts index 2e5bc5a..afb677f 100644 --- a/tests/unit/web-public.test.ts +++ b/tests/unit/web-public.test.ts @@ -34,12 +34,14 @@ import { hintLinks, intentUsage, limitText, + maxText, needsRunAgain, offersIntent, parseLimit, PRODUCE_DEFAULT, refusedState, TEXT_MAX, + toolbarOffers, } from '../../web/public/writes.js'; import * as server from '../../supabase/functions/_shared/board-writes.ts'; @@ -329,6 +331,37 @@ Deno.test('controlActions offers only the buttons valid in each state, as the se assertEquals(Object.keys(ACTION_LABELS).sort(), [...server.BOARD_ACTIONS].sort()); }); +Deno.test('toolbarOffers: controls per state, intents while running or paused, amendments and limit unless done', () => { + const offers = (state: string | null) => toolbarOffers(state); + assertEquals(offers('running'), { + controls: ['pause', 'stop'], + hint: true, + intent: true, + amendment: true, + limit: true, + }); + assertEquals(offers('paused'), { + controls: ['resume', 'stop'], + hint: true, + intent: true, + amendment: true, + limit: true, + }); + assertEquals(offers('stopped'), { controls: ['restart'], hint: true, intent: false, amendment: true, limit: true }); + assertEquals(offers('done'), { controls: [], hint: true, intent: false, amendment: false, limit: false }); + assertEquals(offers(null), { controls: [], hint: true, intent: false, amendment: true, limit: true }); + // The toolbar's + Intent follows the same rule as the drawer's intent on the goal. + for (const state of ['running', 'paused', 'stopped', 'done', null]) { + assertEquals(offers(state).intent, offersIntent(['kind:goal'], state)); + } +}); + +Deno.test('maxText names the limit the strip shows', () => { + assertEquals(maxText(20), '20'); + assertEquals(maxText('none'), 'no limit'); + assertEquals(maxText(null), 'unknown'); +}); + Deno.test('intentUsage says how many intents of the limit the board has used', () => { assertEquals(intentUsage(3, 5), 'This board has used 3 of 5 intents.'); assertEquals(intentUsage(5, 5), 'This board has used 5 of 5 intents. Yours is still accepted.'); diff --git a/web/public/app.js b/web/public/app.js index a039337..a5b14e5 100644 --- a/web/public/app.js +++ b/web/public/app.js @@ -1,7 +1,7 @@ // The app shell: the Browse | Board tabs, hash routing, and the shared node/row selection. import { mountBoard } from './board.js'; import { mountBrowse } from './browse.js'; -import { closeDrawer, openDrawer } from './drawer.js'; +import { closeDrawer, openDrawer, refreshDrawer } from './drawer.js'; import { parseHash, tagHash } from './route.js'; const tabs = { @@ -20,7 +20,7 @@ let shownKey = ''; /** * Open the drawer from the Board graph, which knows the shown board and the short names of its nodes. On a board - * view (not a tag view) the drawer also gets what its write forms need. + * view (not a tag view) the drawer also gets what its shortcuts need. * @param {string} id */ function onBoardSelect(id) { @@ -36,7 +36,8 @@ function onBoardSelect(id) { } const browse = { mounted: false }; -const board = mountBoard(panels.board, { onSelect: onBoardSelect }); +// After each graph poll the drawer redraws what it takes from the graph, such as the goal's list of amendments. +const board = mountBoard(panels.board, { onSelect: onBoardSelect, onPoll: refreshDrawer }); /** @param {'browse' | 'board'} which */ function showTab(which) { diff --git a/web/public/board.js b/web/public/board.js index 4598a41..f02e392 100644 --- a/web/public/board.js +++ b/web/public/board.js @@ -1,4 +1,5 @@ -// The Board tab: the board picker, the status strip, and the live graph of one board or one tag. +// The Board tab: the board picker, the status strip, the board toolbar (`toolbar.js`), and the live graph of one board +// or one tag. import { ApiError, getJson, NOT_SIGNED_IN } from './api.js'; import { diffGraph } from './diff.js'; import { clock, h, option } from './dom.js'; @@ -7,6 +8,7 @@ import { kindOf, shortName, stateOf } from './names.js'; import { connState, nextDelay, POLL_MS, STALE_MS } from './poll.js'; import { boardHash } from './route.js'; import { boardStatus } from './status.js'; +import { createToolbar } from './toolbar.js'; /** * @typedef {{ kind: 'board'; scope: string; board: string } | { kind: 'tag'; tag: string }} Target @@ -38,7 +40,7 @@ const STATES = ['running', 'paused', 'stopped', 'done']; /** * @param {Element} el - * @param {{ onSelect(id: string): void }} opts + * @param {{ onSelect(id: string): void; onPoll?(): void }} opts `onPoll` runs after each graph poll that lands * @returns {{ showBoard(scope: string, board: string): void; showTag(tag: string): void; * nameOf(id: string): string | null; nodes(): any[]; progressText(): string; status(): ShownStatus | null; * pollNow(): Promise }} @@ -57,7 +59,12 @@ export function mountBoard(el, opts) { // Only the notices are announced: the strip changes its refresh time on every poll. notices.setAttribute('aria-live', 'polite'); const graphEl = h('div', 'graph'); - el.replaceChildren(bar, strip, notices, graphEl); + const toolbar = createToolbar({ + pollNow: () => pollNow(), + status: () => shownStatus(), + nodes: () => loop?.prev?.nodes ?? [], + }); + el.replaceChildren(bar, strip, toolbar.el, notices, graphEl); let view = null; let viewError = ''; @@ -128,6 +135,22 @@ export function mountBoard(el, opts) { /** @param {string} text @param {string} [cls] */ const item = (text, cls) => h('span', cls ? `item ${cls}` : 'item', text); + /** + * Put `parts` in the strip. The toolbar's intent limit item stays where it is rather than being taken out and put + * back, so the limit box keeps focus while the strip redraws around it on each poll. + * @param {Node[]} parts + */ + function placeStrip(parts) { + const i = parts.indexOf(toolbar.limit); + if (i < 0 || toolbar.limit.parentNode !== strip) { + strip.replaceChildren(...parts); + return; + } + for (const c of [...strip.childNodes]) if (c !== toolbar.limit) c.remove(); + toolbar.limit.before(...parts.slice(0, i)); + toolbar.limit.after(...parts.slice(i + 1)); + } + /** @param {Loop} me */ function renderStrip(me) { const t = me.target; @@ -135,13 +158,14 @@ export function mountBoard(el, opts) { const parts = []; if (t.kind === 'board') { const status = boardStatus(nodes, me.goalText, me.progressText); - const max = status.maxIntents === 'none' ? 'no limit' : status.maxIntents ?? 'unknown'; const state = status.state ?? 'unknown'; + // The toolbar draws "Intents n of max" itself, with the limit as a button that edits it. + toolbar.update(me.prev ? { ...status, truncated: !!me.prev.truncated } : null); parts.push( item(`${t.board} · ${t.scope}`, 'name'), item(`State: ${state}`, STATES.includes(state) ? `state state-${state}` : 'state'), item(`Round ${status.round ?? 'unknown'}`), - item(`Intents ${status.intents} of ${max}`), + toolbar.limit, item(`Best: ${status.best ?? 'unknown'}`, 'best'), ); } else { @@ -149,7 +173,7 @@ export function mountBoard(el, opts) { } if (me.refreshed) parts.push(item(`refreshed ${clock(me.refreshed)}`)); parts.push(connItem(connState(me.conn, me.refreshed, Date.now()))); - strip.replaceChildren(...parts); + placeStrip(parts); const msgs = viewError ? [viewError] : []; if (me.prev && t.kind === 'board' && !nodes.some((/** @type {any} */ n) => kindOf(n.tags) === 'intent')) { @@ -191,6 +215,8 @@ export function mountBoard(el, opts) { function signOut() { signedOut = true; if (loop) cancel(loop); + // Nothing more can be written; the toolbar goes, and the strip's limit becomes plain text. + toolbar.show(null); strip.replaceChildren(...[...strip.children].filter((c) => !c.classList.contains('conn')), connItem('signed-out')); notices.replaceChildren(h('p', 'notice error', NOT_SIGNED_IN)); } @@ -269,6 +295,7 @@ export function mountBoard(el, opts) { if (ok) me.error = null; me.delay = nextDelay(me.delay, ok); renderStrip(me); + if (ok) opts.onPoll?.(); // A write landed while this poll was in flight, so it may predate the write: poll again at once. const again = me.again; me.again = false; @@ -309,6 +336,8 @@ export function mountBoard(el, opts) { /** @param {Target} target */ function start(target) { if (loop) cancel(loop); + // A panel or Stop confirmation open for the old board closes, and the new board's toolbar is built afresh. + toolbar.show(target.kind === 'board' ? { scope: target.scope, board: target.board } : null); view?.clear(); /** @type {Loop} */ const me = { @@ -340,6 +369,12 @@ export function mountBoard(el, opts) { tick(me); } + /** @returns {ShownStatus | null} */ + function shownStatus() { + if (!loop?.prev || loop.target.kind !== 'board') return null; + return { ...boardStatus(loop.prev.nodes, loop.goalText, loop.progressText), truncated: !!loop.prev.truncated }; + } + loadBoards(); strip.replaceChildren(item('Choose a board to watch it live.')); @@ -356,10 +391,7 @@ export function mountBoard(el, opts) { /** The full content of the shown board's progress memory, or '' when it is not loaded. */ progressText: () => loop?.progressText ?? '', /** The strip's numbers for the shown board, or null for a tag graph or before the first poll. */ - status: () => { - if (!loop?.prev || loop.target.kind !== 'board') return null; - return { ...boardStatus(loop.prev.nodes, loop.goalText, loop.progressText), truncated: !!loop.prev.truncated }; - }, + status: () => shownStatus(), pollNow, }; } diff --git a/web/public/controls.js b/web/public/controls.js index f44d515..dd8d638 100644 --- a/web/public/controls.js +++ b/web/public/controls.js @@ -1,38 +1,31 @@ -// The goal drawer's board controls: Pause lead, Resume lead, Stop (confirmed in the page first) and Restart, each -// offered only in a state it is valid from, and the intent limit box. Each acts on the goal memory through -// `POST /boards/control`, so it reaches a board run on any machine. +// The board run controls' building blocks, for the Board tab's toolbar (`toolbar.js`): Stop's in-page confirmation +// and sending one control (Pause lead, Resume lead, Stop, Restart or the intent limit). Each acts on the goal memory +// through `POST /boards/control`, so it reaches a board run on any machine. import { postJson } from './api.js'; import { h } from './dom.js'; import { stateOf } from './names.js'; -import { runWrite, say, statusLine } from './sending.js'; +import { runWrite, say } from './sending.js'; import { parseStatus } from './status.js'; -import { - ACTION_LABELS, - controlActions, - controlDone, - limitText, - needsRunAgain, - parseLimit, - refusedState, - RUN_AGAIN, -} from './writes.js'; +import { controlDone, needsRunAgain, refusedState, RUN_AGAIN } from './writes.js'; /** * @typedef {import('../../supabase/functions/_shared/types.ts').Memory} Memory * @typedef {import('./sending.js').Hooks} Hooks + * @typedef {import('./sending.js').Control} Control * @typedef {import('./writes.js').Action} Action - * @typedef {import('./board.js').ShownStatus} ShownStatus - * @typedef {{ scope: string; board: string; pollNow(): Promise; status(): ShownStatus | null }} ControlCtx + * @typedef {{ scope: string; board: string; pollNow(): Promise }} ControlCtx + * @typedef {{ kind: 'done'; state: string | null; max: number | 'none' | null; polled: Promise } + * | { kind: 'refused'; state: string | null } + * | { kind: 'failed' } + * | { kind: 'gone' }} ControlOutcome `done` carries the goal as the server left it; `refused` the state the server + * named, after the graph was re-read; `gone` means the caller moved on and nothing was said */ -/** States the state line colours. */ -const STATES = ['running', 'paused', 'stopped', 'done']; - /** * @param {string} text * @param {string} [className] */ -function button(text, className = '') { +export function button(text, className = '') { const b = /** @type {HTMLButtonElement} */ (h('button', className, text)); b.type = 'button'; return b; @@ -44,147 +37,62 @@ function runAgain() { } /** - * @param {Memory} goal - * @param {ControlCtx} ctx - * @param {Hooks} hooks - * @param {(state: string | null) => void} onState told the goal's state after each control that changed it - * @returns {HTMLElement} + * Stop's confirmation: the question, Stop board and Cancel. The caller focuses Cancel when it shows it, so a repeated + * or reflexive Enter on "Stop…" does not confirm it. + * @returns {{ el: HTMLElement; stopNow: HTMLButtonElement; cancel: HTMLButtonElement }} */ -export function goalControls(goal, ctx, hooks, onState) { - let state = stateOf(goal.tags); - let max = parseStatus(goal.content, '').maxIntents; - - const box = h('section', 'write-box controls'); - const stateLine = h('p', 'controls-state'); - const buttons = h('div', 'controls-buttons'); - const confirm = h('div', 'controls-confirm'); - confirm.hidden = true; +export function stopConfirm() { + const el = h('div', 'controls-confirm'); const stopNow = button('Stop board', 'danger'); const cancel = button('Cancel', 'secondary'); - const confirmRow = h('div', 'controls-buttons'); - confirmRow.append(stopNow, cancel); - confirm.append( + const row = h('div', 'controls-buttons'); + row.append(stopNow, cancel); + el.append( h( 'p', '', 'Stop this board? Workers end at their next step, and the runner lets running workers finish, then exits.', ), - confirmRow, + row, ); + return { el, stopNow, cancel }; +} - const limit = /** @type {HTMLFormElement} */ (h('form', 'controls-limit')); - const input = /** @type {HTMLInputElement} */ (h('input')); - input.type = 'text'; - input.inputMode = 'numeric'; - input.size = 6; - input.placeholder = 'none'; - input.setAttribute('aria-label', 'Max intents'); - const save = button('Save'); - save.type = 'submit'; - const limitRow = h('div', 'controls-buttons'); - limitRow.append(h('span', 'write-label', 'Intent limit'), input, save); - limit.append( - limitRow, - h( - 'p', - 'note', - 'A whole number, or none. A higher max_intents in the board file raises it again on the next board-runner run.', - ), +/** + * Send one control with `controls` disabled, and say on `line` what happened. When the server refuses it because the + * board moved on since the page last looked (another tab, the lead, a person elsewhere), the graph is re-read first, + * so the caller can offer what is valid now. + * @param {{ action?: Action; maxIntents?: number | 'none' }} body + * @param {Action | 'limit'} what + * @param {string | null} before the goal's state the caller showed + * @param {Control[]} controls + * @param {HTMLElement} line + * @param {Hooks} hooks + * @param {ControlCtx} ctx + * @returns {Promise} + */ +export async function sendControl(body, what, before, controls, line, hooks, ctx) { + const r = await runWrite( + controls, + line, + hooks, + ctx, + () => postJson('/boards/control', { scope: ctx.scope, board: ctx.board, ...body }), ); - - const line = statusLine(); - box.append(h('h3', 'write-title', 'Controls'), stateLine, buttons, confirm, limit, line); - - /** Every control the box has now, so a request disables them all. */ - const all = () => /** @type {import('./sending.js').Control[]} */ ([...box.querySelectorAll('button, input')]); - - function render() { - const known = state !== null && STATES.includes(state); - stateLine.replaceChildren( - 'State: ', - h('span', known ? `state state-${state}` : 'state', state ?? 'unknown'), - ); - const actions = controlActions(state); - buttons.replaceChildren( - ...actions.map((a) => { - const b = button(ACTION_LABELS[a]); - b.addEventListener('click', () => (a === 'stop' ? askStop() : send({ action: a }, a))); - return b; - }), - ); - if (actions.length === 0) { - buttons.append(h('p', 'note', state === 'done' ? 'This board is done.' : 'No controls for this state.')); + if (!hooks.live()) return { kind: 'gone' }; + if (!r.ok) { + const refused = refusedState(r.error); + if (refused) { + await ctx.pollNow(); + if (!hooks.live()) return { kind: 'gone' }; } - buttons.hidden = false; - confirm.hidden = true; - limit.hidden = state === 'done'; - input.value = limitText(max); + say(line, 'error', r.error); + return refused ? { kind: 'refused', state: refused.state } : { kind: 'failed' }; } - - function askStop() { - buttons.hidden = true; - confirm.hidden = false; - // Cancel, not Stop board: a repeated or reflexive Enter on "Stop…" must not confirm it. - cancel.focus(); - } - - cancel.addEventListener('click', () => { - confirm.hidden = true; - buttons.hidden = false; - }); - stopNow.addEventListener('click', () => send({ action: 'stop' }, 'stop')); - - limit.addEventListener('submit', (e) => { - e.preventDefault(); - if (save.disabled) return; - const v = parseLimit(input.value); - if (!v.ok) say(line, 'error', v.error); - else send({ maxIntents: v.value }, 'limit'); - }); - - /** - * @param {{ action?: Action; maxIntents?: number | 'none' }} body - * @param {Action | 'limit'} what - */ - async function send(body, what) { - const before = state; - const r = await runWrite( - all(), - line, - hooks, - ctx, - () => postJson('/boards/control', { scope: ctx.scope, board: ctx.board, ...body }), - ); - if (!hooks.live()) return; - if (!r.ok) { - // A refused Stop leaves the confirmation open; put the buttons back. - confirm.hidden = true; - buttons.hidden = false; - const refused = refusedState(r.error); - if (refused) { - // The board moved on since this drawer was drawn (another tab, the lead, a person elsewhere): re-read it so - // the buttons offer what is valid now. - await ctx.pollNow(); - if (!hooks.live()) return; - state = refused.state; - const shown = ctx.status(); - if (shown && shown.state === state) max = shown.maxIntents; - render(); - onState(state); - } - say(line, 'error', r.error); - return; - } - const g = /** @type {{ goal: Memory }} */ (r.result).goal; - state = stateOf(g.tags); - max = parseStatus(g.content, '').maxIntents; - render(); - onState(state); - const text = controlDone(what, before, state); - if (needsRunAgain(before, state)) say(line, 'ok', `${text} `, ...runAgain()); - else say(line, 'ok', text); - } - - render(); - return box; + const g = /** @type {{ goal: Memory }} */ (r.result).goal; + const state = stateOf(g.tags); + const text = controlDone(what, before, state); + if (needsRunAgain(before, state)) say(line, 'ok', `${text} `, ...runAgain()); + else say(line, 'ok', text); + return { kind: 'done', state, max: parseStatus(g.content, '').maxIntents, polled: r.polled }; } diff --git a/web/public/drawer.js b/web/public/drawer.js index 4b63cea..79d1b15 100644 --- a/web/public/drawer.js +++ b/web/public/drawer.js @@ -17,7 +17,8 @@ import { kindOf, shortName, verdictOf, workerLabel } from './names.js'; * progressText?: () => string; * status?: () => import('./board.js').ShownStatus | null; * pollNow?: () => Promise; - * }} DrawerCtx `scope`, `status` and `pollNow` come only from the Board tab's board view, and turn on the write forms + * }} DrawerCtx `scope`, `status` and `pollNow` come only from the Board tab's board view, and turn on the drawer's + * shortcuts and the goal's amendments * @typedef {'memory' | 'links' | 'log'} TabName * @typedef {import('./names.js').Verdict} Verdict */ @@ -38,6 +39,8 @@ let seq = 0; let wanted = 'memory'; /** @type {{ el: HTMLElement; setActive(on: boolean): void; destroy(): void } | null} */ let log = null; +/** What the shown memory redraws after each graph poll, such as the goal's amendments; each open starts it empty. */ +let onGraph = /** @type {(() => void)[]} */ ([]); function build() { const root = h('aside', 'drawer'); @@ -115,10 +118,16 @@ function stopLog() { /** Close the drawer and stop any log polling. */ export function closeDrawer() { seq++; + onGraph = []; stopLog(); if (ui) ui.root.hidden = true; } +/** Redraw what the shown memory draws from the graph, after a graph poll. */ +export function refreshDrawer() { + for (const refresh of onGraph) refresh(); +} + /** * Show one memory in the drawer, replacing whatever it showed. * @param {string} id @@ -128,6 +137,7 @@ export function closeDrawer() { export async function openDrawer(id, ctx) { ui ??= build(); const my = ++seq; + onGraph = []; stopLog(); ui.root.hidden = false; ui.root.dataset.id = id; @@ -284,7 +294,11 @@ function memoryPanel(m, ctx, my) { out.push(h('div', 'drawer-content', m.content)); const { board, scope, nodes, status, pollNow } = ctx; if (board && scope && nodes && status && pollNow) { - const hooks = { live: () => my === seq, open: (/** @type {string} */ id) => openDrawer(id, ctx) }; + const hooks = { + live: () => my === seq, + open: (/** @type {string} */ id) => openDrawer(id, ctx), + onGraph: (/** @type {() => void} */ refresh) => onGraph.push(() => my === seq && refresh()), + }; out.push(...writeSection(m, { board, scope, nodes, status, pollNow }, hooks)); } return out; diff --git a/web/public/forms.js b/web/public/forms.js index 1670d40..4912127 100644 --- a/web/public/forms.js +++ b/web/public/forms.js @@ -1,11 +1,10 @@ -// The drawer's write forms, on the Board tab only: Add hint on every node, Add intent on the goal and on facts while -// the board runs, and on the goal its amendments, Add amendment and the board controls (`controls.js`). Every form is -// disabled while its request is in flight; success clears it and polls the graph at once; failure shows the server's -// text. All text goes in through textContent. +// The write forms: Add hint, Add intent and Add amendment, opened from the Board tab's toolbar (`toolbar.js`) for the +// whole board, and the drawer's two shortcuts, "Hint about this node" and "Try next from this fact", with the goal +// drawer's list of amendments. Every form is disabled while its request is in flight; success clears it and polls the +// graph at once; failure shows the server's text. All text goes in through textContent. import { postJson } from './api.js'; -import { goalControls } from './controls.js'; import { h } from './dom.js'; -import { kindOf, shortName, stateOf } from './names.js'; +import { kindOf, shortName } from './names.js'; import { runWrite, say, statusLine } from './sending.js'; import { field } from './status.js'; import { @@ -52,10 +51,10 @@ function textField(label, opts) { } /** - * A form box: a title, its fields, an optional note, a submit button and a status line. `body` gives the request + * A form box: an optional title, its fields, an optional note, a submit button and a status line. `body` gives the request * body from the trimmed values, or a reason to send nothing. * @param {{ - * title: string; + * title?: string; * fields: { el: HTMLElement; input: HTMLInputElement | HTMLTextAreaElement }[]; * notes?: HTMLElement[]; * submit: string; @@ -71,7 +70,8 @@ function writeForm(spec, ctx, hooks) { const button = /** @type {HTMLButtonElement} */ (h('button', '', spec.submit)); button.type = 'submit'; const line = statusLine(); - form.append(h('h3', 'write-title', spec.title), ...spec.fields.map((f) => f.el), ...(spec.notes ?? [])); + if (spec.title) form.append(h('h3', 'write-title', spec.title)); + form.append(...spec.fields.map((f) => f.el), ...(spec.notes ?? [])); const row = h('div', 'write-actions'); row.append(button, line); form.append(row); @@ -86,6 +86,8 @@ function writeForm(spec, ctx, hooks) { } const r = await runWrite([...inputs, button], line, hooks, ctx, () => postJson(spec.path, body)); if (!hooks.live()) return; + // Disabling the form while it sent dropped the focus; put it back in the form, so Escape and typing still reach it. + if (!form.contains(document.activeElement) && document.activeElement === document.body) focusForm(form); if (!r.ok) { say(line, 'error', r.error); return; @@ -106,29 +108,43 @@ function writeForm(spec, ctx, hooks) { const EMPTY = 'Write something first.'; -/** @param {Memory} m @param {WriteCtx} ctx @param {Hooks} hooks */ -function hintForm(m, ctx, hooks) { +/** + * Add hint: about a node from the drawer's shortcut, or for the whole board from the toolbar. + * @param {Memory | null} about the node, or null for a board-wide hint with no `about` + * @param {WriteCtx} ctx + * @param {Hooks} hooks + */ +export function hintForm(about, ctx, hooks) { const text = textField('Hint', { multiline: true, max: TEXT_MAX, placeholder: 'something the workers should know' }); - const where = hintLinks(m.tags) - ? `Linked to this ${kindOf(m.tags)}.` + const where = about === null + ? 'Board-wide: advice for the lead, read at its next round.' + : hintLinks(about.tags) + ? `Linked to this ${kindOf(about.tags)}.` : 'Board-wide: on this memory a hint links to nothing.'; return writeForm( { - title: 'Add hint', + ...(about === null ? { title: 'Add hint' } : {}), fields: [text], notes: [h('p', 'note', where)], submit: 'Add hint', path: '/hints', - body: ([t]) => (t ? { scope: ctx.scope, board: ctx.board, text: t, about: m.id } : EMPTY), + body: ([t]) => { + if (!t) return EMPTY; + return { scope: ctx.scope, board: ctx.board, text: t, ...(about === null ? {} : { about: about.id }) }; + }, }, ctx, hooks, ); } -/** @param {Memory} m @param {WriteCtx} ctx @param {Hooks} hooks */ -function intentForm(m, ctx, hooks) { - const onFact = kindOf(m.tags) === 'fact'; +/** + * Add intent: from a fact through the drawer's "Try next from this fact", or for the whole board from the toolbar. + * @param {Memory | null} from the fact it builds on, or null for an intent with no `from` + * @param {WriteCtx} ctx + * @param {Hooks} hooks + */ +export function intentForm(from, ctx, hooks) { const fields = [ textField('Try', { multiline: true, max: TEXT_MAX, placeholder: 'what a worker should try' }), textField('Done when (optional)', { max: FIELD_MAX, placeholder: PRODUCE_DEFAULT }), @@ -141,10 +157,10 @@ function intentForm(m, ctx, hooks) { }; refresh(); const notes = [usage]; - if (onFact) notes.unshift(h('p', 'note', 'It builds on this fact.')); + if (from) notes.unshift(h('p', 'note', 'It builds on this fact.')); const form = writeForm( { - title: 'Add intent', + ...(from ? {} : { title: 'Add intent' }), fields, notes, submit: 'Add intent', @@ -157,7 +173,7 @@ function intentForm(m, ctx, hooks) { text, ...(produce ? { produce } : {}), ...(giveUp ? { giveUp } : {}), - ...(onFact ? { from: m.id } : {}), + ...(from ? { from: from.id } : {}), }; }, // The count moves once the poll that follows the write has drawn the new intent. @@ -170,8 +186,8 @@ function intentForm(m, ctx, hooks) { return form; } -/** @param {WriteCtx} ctx @param {Hooks} hooks @param {() => void} added called once the new amendment is drawn */ -function amendmentForm(ctx, hooks, added) { +/** Add amendment, from the toolbar. @param {WriteCtx} ctx @param {Hooks} hooks */ +export function amendmentForm(ctx, hooks) { const text = textField('Amendment', { multiline: true, max: TEXT_MAX, @@ -185,8 +201,6 @@ function amendmentForm(ctx, hooks, added) { submit: 'Add amendment', path: '/amendments', body: ([t]) => (t ? { scope: ctx.scope, board: ctx.board, text: t } : EMPTY), - // The list moves once the poll that follows the write has drawn the new amendment. - after: (polled) => polled.then(() => hooks.live() && added()), }, ctx, hooks, @@ -194,16 +208,21 @@ function amendmentForm(ctx, hooks, added) { } /** - * The board's amendments from the shown graph, each opening in the drawer; `refresh` redraws it from the graph. + * The board's amendments from the shown graph, each opening in the drawer. It redraws after each graph poll that + * changes the list, so an amendment added from the toolbar or by a session elsewhere appears here. * @param {WriteCtx} ctx * @param {Hooks} hooks - * @returns {{ el: HTMLElement; refresh(): void }} + * @returns {HTMLElement} */ function amendmentList(ctx, hooks) { const box = h('section', 'drawer-amendments'); + let drawn = ''; const refresh = () => { - box.replaceChildren(h('h3', 'write-title', 'Amendments')); const list = amendmentsOf(ctx.nodes()); + const key = list.map((n) => `${n.id}\n${n.snippet ?? n.content ?? ''}`).join('\n\n'); + if (key === drawn && box.childElementCount) return; + drawn = key; + box.replaceChildren(h('h3', 'write-title', 'Amendments')); if (list.length === 0) box.append(h('p', 'note', 'None yet.')); for (const n of list) { const text = n.snippet ?? n.content ?? ''; @@ -222,11 +241,37 @@ function amendmentList(ctx, hooks) { } }; refresh(); - return { el: box, refresh }; + hooks.onGraph?.(refresh); + return box; } /** - * The write forms for a memory of the shown board, below its content; none for a memory of another scope or board. + * Focus a form's first text box. + * @param {HTMLFormElement} form + */ +export function focusForm(form) { + const box = /** @type {HTMLElement | null} */ (form.querySelector('textarea, input')); + box?.focus(); +} + +/** + * One drawer shortcut: a line that opens to its form, focusing the form's first box. + * @param {string} label + * @param {HTMLFormElement} form + */ +function shortcut(label, form) { + const box = /** @type {HTMLDetailsElement} */ (h('details', 'drawer-shortcut')); + box.append(h('summary', '', label), form); + box.addEventListener('toggle', () => { + if (box.open) focusForm(form); + }); + return box; +} + +/** + * What the Memory tab adds below a memory of the shown board: on the goal, its amendments (the goal drawer is + * otherwise read-only; the board's actions are on the toolbar); on any other node, "Hint about this node", and on a + * fact while the board is running or paused, "Try next from this fact". Nothing for a memory of another scope or board. * @param {Memory} m * @param {WriteCtx} ctx * @param {Hooks} hooks @@ -234,23 +279,13 @@ function amendmentList(ctx, hooks) { */ export function writeSection(m, ctx, hooks) { if (m.scope !== ctx.scope || !m.tags.includes(`board:${ctx.board}`)) return []; + const kind = kindOf(m.tags); + if (kind === 'goal') return [amendmentList(ctx, hooks)]; const out = []; if (ctx.status()?.truncated) out.push(h('p', 'notice', TRUNCATED)); - const kind = kindOf(m.tags); - if (kind === 'goal') { - const intent = intentForm(m, ctx, hooks); - const amendments = amendmentList(ctx, hooks); - const amend = amendmentForm(ctx, hooks, amendments.refresh); - /** @param {string | null} state */ - const show = (state) => { - intent.hidden = !offersIntent(m.tags, state); - amend.hidden = state === 'done'; - }; - show(stateOf(m.tags)); - out.push(amendments.el, goalControls(m, ctx, hooks, show), intent, amend); - } else if (kind === 'fact' && offersIntent(m.tags, ctx.status()?.state ?? null)) { - out.push(intentForm(m, ctx, hooks)); + out.push(shortcut('Hint about this node', hintForm(m, ctx, hooks))); + if (kind === 'fact' && offersIntent(m.tags, ctx.status()?.state ?? null)) { + out.push(shortcut('Try next from this fact', intentForm(m, ctx, hooks))); } - out.push(hintForm(m, ctx, hooks)); return out; } diff --git a/web/public/sending.js b/web/public/sending.js index ab65420..ef9dc0a 100644 --- a/web/public/sending.js +++ b/web/public/sending.js @@ -1,10 +1,12 @@ -// Sending one write from the drawer: its controls disabled while in flight, a status line saying what happened, and +// Sending one write from the toolbar or the drawer: its controls disabled while in flight, a status line saying what happened, and // an immediate graph poll once it lands. import { ApiError, NOT_SIGNED_IN } from './api.js'; import { h } from './dom.js'; /** - * @typedef {{ live(): boolean; open(id: string): void }} Hooks `live` is false once the drawer shows something else + * @typedef {{ live(): boolean; open(id: string): void; onGraph?(refresh: () => void): void }} Hooks `live` is false + * once the drawer shows something else, or the toolbar another board; `onGraph`, where given, runs `refresh` after + * each graph poll while `live` * @typedef {HTMLButtonElement | HTMLInputElement | HTMLTextAreaElement} Control * @typedef {{ ok: true; result: any; polled: Promise } | { ok: false; error: string }} Outcome `polled` settles * once the graph poll that follows the write has finished @@ -38,7 +40,7 @@ export function say(line, tone, ...parts) { /** * Send one write with `controls` disabled until it settles, saying so on `line`. Controls come back on only while the - * drawer still shows this memory; a finished write polls the graph either way. + * drawer or toolbar still shows what they belong to; a finished write polls the graph either way. * @param {Control[]} controls * @param {HTMLElement} line * @param {Hooks} hooks diff --git a/web/public/style.css b/web/public/style.css index 09d074d..fa71106 100644 --- a/web/public/style.css +++ b/web/public/style.css @@ -279,6 +279,60 @@ main { color: var(--ok); } +/* the board toolbar, under the strip, and the strip's intent limit editor */ + +.toolbar-row { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px 16px; +} + +.toolbar-group { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; +} + +.toolbar-group .note { + margin: 0; +} + +.toolbar-row .write-status { + flex: 1 1 16em; + min-width: 0; +} + +.toolbar-panel { + max-width: 44em; +} + +.toolbar-panel .notice { + margin-top: 6px; +} + +.toolbar-panel .write-box, +.toolbar-panel .controls-confirm { + margin: 6px 0 0; +} + +.limit { + white-space: nowrap; +} + +.limit-button { + padding: 0 4px; + border-style: dashed; + background: transparent; + font-size: inherit; +} + +.limit-input { + width: 6em; + padding: 0 4px; +} + .notices:empty { display: none; } @@ -576,10 +630,6 @@ main { border-radius: 4px; } -.write-box.controls { - border-left: 3px solid var(--accent); -} - .write-title { margin: 0 0 6px; font-size: 13px; @@ -637,15 +687,10 @@ main { color: var(--muted); } -.write-status code, -.controls-limit code { +.write-status code { font: 12px ui-monospace, Menlo, monospace; } -.controls-state { - margin: 0 0 6px; -} - .controls-confirm { padding: 6px 8px; border-left: 3px solid var(--bad); @@ -656,8 +701,28 @@ main { margin: 0 0 6px; } -.controls-limit { - margin-top: 8px; +.drawer-shortcut { + margin: 10px 0 0; + border: 1px solid var(--line); + border-radius: 4px; + background: var(--bg); +} + +.drawer-shortcut > summary { + padding: 6px 10px; + cursor: pointer; + color: var(--muted); +} + +.drawer-shortcut[open] > summary { + color: var(--text); +} + +.drawer-shortcut > .write-box { + margin: 0; + border: 0; + border-top: 1px solid var(--line); + border-radius: 0 0 4px 4px; } button.danger { diff --git a/web/public/toolbar.js b/web/public/toolbar.js new file mode 100644 index 0000000..8ffafcb --- /dev/null +++ b/web/public/toolbar.js @@ -0,0 +1,341 @@ +// The Board tab's toolbar, a row under the status strip on a board view (never a tag view): the run controls valid for +// the goal's state, Stop confirmed in the page with focus on Cancel; + Hint, + Intent and + Amendment, each opening its +// form in the one panel under the row; and the strip's intent limit, which edits in place. A hint or intent added here +// is board-wide. Every part is built afresh for each board, so nothing drawn for one board can send for another. +import { button, sendControl, stopConfirm } from './controls.js'; +import { h } from './dom.js'; +import { amendmentForm, focusForm, hintForm, intentForm } from './forms.js'; +import { say, statusLine } from './sending.js'; +import { ACTION_LABELS, LIMIT_NOTE, limitText, maxText, parseLimit, toolbarOffers, TRUNCATED } from './writes.js'; + +/** + * @typedef {import('./board.js').ShownStatus} ShownStatus + * @typedef {import('./writes.js').AmendmentNode} AmendmentNode + * @typedef {import('./writes.js').Action} Action + * @typedef {'hint' | 'intent' | 'amendment' | 'stop'} PanelName + * @typedef {{ + * el: HTMLElement; + * update(status: ShownStatus | null): void; + * end(): void; + * }} Session one board's toolbar; `end` makes it inert for good + */ + +/** + * @param {{ pollNow(): Promise; status(): ShownStatus | null; nodes(): AmendmentNode[] }} board the Board tab's + * shown graph + * @returns {{ + * el: HTMLElement; + * limit: HTMLElement; + * show(target: { scope: string; board: string } | null): void; + * update(status: ShownStatus | null): void; + * }} `el` goes under the strip and `limit` in it; `show` starts a board (or none), closing anything open, and + * `update` takes the strip's numbers after each poll (null before the first) + */ +export function createToolbar(board) { + const el = h('div', 'toolbar'); + el.hidden = true; + const limit = h('span', 'item limit'); + /** @type {Session | null} */ + let current = null; + + /** @param {{ scope: string; board: string } | null} target */ + function show(target) { + current?.end(); + current = target ? session(target.scope, target.board, el, limit, board) : null; + el.replaceChildren(...(current ? [current.el] : [])); + el.hidden = true; + } + + return { el, limit, show, update: (status) => current?.update(status) }; +} + +/** + * @param {string} scope + * @param {string} name the board + * @param {HTMLElement} outer the toolbar row's container, shown once the first poll has landed + * @param {HTMLElement} limit the strip's "Intents n of max" item + * @param {{ pollNow(): Promise; status(): ShownStatus | null; nodes(): AmendmentNode[] }} board + * @returns {Session} + */ +function session(scope, name, outer, limit, board) { + let live = true; + const hooks = { live: () => live, open: () => {} }; + // Once this board is no longer shown, nothing here polls or reads the next board's graph. + const ctx = { + scope, + board: name, + pollNow: () => (live ? board.pollNow() : Promise.resolve()), + status: () => (live ? board.status() : null), + nodes: () => (live ? board.nodes() : []), + }; + + /** The goal's state and limit as this toolbar shows them, and the strip's numbers. */ + let state = /** @type {string | null} */ (null); + let max = /** @type {number | 'none' | null} */ (null); + let intents = 0; + let truncated = false; + let known = false; + /** Controls sent whose follow-up poll has not landed: a poll that began before one may still say the old state. */ + let hold = 0; + /** The state the buttons were drawn for, so a poll that changes nothing leaves focus where it is. */ + let drawn = /** @type {string | null | undefined} */ (undefined); + /** @type {PanelName | null} */ + let open = null; + let editing = false; + let saving = false; + + const el = h('div', 'toolbar-box'); + const row = h('div', 'toolbar-row'); + const controls = h('div', 'toolbar-group'); + const adds = h('div', 'toolbar-group'); + const line = statusLine(); + /** @type {HTMLButtonElement | null} */ + let stopButton = null; + + /** @param {string} text @param {PanelName} panel */ + const toggle = (text, panel) => { + const b = button(text, 'secondary'); + b.setAttribute('aria-expanded', 'false'); + b.addEventListener('click', () => (open === panel ? close() : openPanel(panel))); + return b; + }; + const toggles = { + hint: toggle('+ Hint', 'hint'), + intent: toggle('+ Intent', 'intent'), + amendment: toggle('+ Amendment', 'amendment'), + }; + adds.append(toggles.hint, toggles.intent, toggles.amendment); + row.append(controls, adds, line); + + const confirm = stopConfirm(); + const forms = { + hint: hintForm(null, ctx, hooks), + intent: intentForm(null, ctx, hooks), + amendment: amendmentForm(ctx, hooks), + }; + const panels = { ...forms, stop: confirm.el }; + const notice = h('p', 'notice', TRUNCATED); + const panelBox = h('div', 'toolbar-panel'); + panelBox.append(notice, ...Object.values(panels)); + el.append(row, panelBox); + + const limitPrefix = document.createTextNode(''); + const limitButton = button('', 'limit-button'); + limitButton.title = `Change the intent limit. ${LIMIT_NOTE}`; + const limitInput = /** @type {HTMLInputElement} */ (h('input', 'limit-input')); + limitInput.type = 'text'; + limitInput.inputMode = 'numeric'; + limitInput.size = 6; + limitInput.placeholder = 'none'; + limitInput.title = LIMIT_NOTE; + limitInput.setAttribute('aria-label', 'Max intents'); + + /** Every run control there is now, so a control in flight disables them all. */ + const controlEls = () => /** @type {import('./sending.js').Control[]} */ ([ + ...controls.querySelectorAll('button'), + confirm.stopNow, + confirm.cancel, + limitButton, + limitInput, + ]); + + // ── panels ─────────────────────────────────────────────────────── + + function drawPanels() { + for (const [k, p] of Object.entries(panels)) p.hidden = k !== open; + notice.hidden = !truncated || open === null || open === 'stop'; + panelBox.hidden = open === null; + for (const [k, b] of Object.entries(toggles)) b.setAttribute('aria-expanded', String(k === open)); + stopButton?.setAttribute('aria-expanded', String(open === 'stop')); + } + + /** @param {PanelName} panel */ + function openPanel(panel) { + open = panel; + drawPanels(); + if (panel === 'stop') confirm.cancel.focus(); + else focusForm(forms[panel]); + } + + /** @param {boolean} [refocus] put focus back on the button that opened the panel */ + function close(refocus = false) { + const was = open; + open = null; + drawPanels(); + if (!refocus || was === null) return; + const b = was === 'stop' ? stopButton : toggles[was]; + if (b?.isConnected && !b.hidden) b.focus(); + } + + // Escape anywhere in the toolbar closes the open panel, or cancels Stop. + el.addEventListener('keydown', (e) => { + if (e.key !== 'Escape' || open === null) return; + e.preventDefault(); + // The drawer closes on Escape too; this one is the toolbar's. + e.stopPropagation(); + close(true); + }); + confirm.cancel.addEventListener('click', () => close(true)); + confirm.stopNow.addEventListener('click', () => sendCtl({ action: 'stop' }, 'stop')); + + // ── run controls ───────────────────────────────────────────────── + + function draw() { + const offers = toolbarOffers(state); + if (drawn !== state) { + drawn = state; + stopButton = null; + controls.replaceChildren( + ...offers.controls.map((a) => { + const b = button(ACTION_LABELS[a]); + if (a === 'stop') { + stopButton = b; + b.addEventListener('click', () => (open === 'stop' ? close() : openPanel('stop'))); + } else b.addEventListener('click', () => sendCtl({ action: a }, a)); + return b; + }), + ); + if (offers.controls.length === 0) { + controls.append(h('span', 'note', state === 'done' ? 'This board is done.' : 'No controls for this state.')); + } + toggles.intent.hidden = !offers.intent; + toggles.amendment.hidden = !offers.amendment; + // A panel the new state does not offer closes. + if ( + (open === 'stop' && !offers.controls.includes('stop')) || (open === 'intent' && !offers.intent) || + (open === 'amendment' && !offers.amendment) + ) close(); + else drawPanels(); + } else drawPanels(); + drawLimit(); + } + + /** + * @param {{ action?: Action; maxIntents?: number | 'none' }} body + * @param {Action | 'limit'} what + */ + async function sendCtl(body, what) { + hold++; + const out = await sendControl(body, what, state, controlEls(), line, hooks, ctx); + if (out.kind === 'gone') return; + try { + settleControl(out, what); + } finally { + // The button pressed may have gone with the old state, or been disabled while it sent: keep focus in the bar. + if (document.activeElement === document.body && what !== 'limit') { + /** @type {HTMLElement | null} */ (controls.querySelector('button'))?.focus(); + } + } + } + + /** + * @param {import('./controls.js').ControlOutcome} out + * @param {Action | 'limit'} what + */ + function settleControl(out, what) { + if (open === 'stop') close(); + if (out.kind === 'done') { + state = out.state; + max = out.max; + if (what === 'limit') endEdit(true); + draw(); + // Until the poll that follows lands, a poll begun before the write could draw the old state back. + out.polled.finally(() => { + hold--; + if (live) update(board.status()); + }); + return; + } + hold--; + if (out.kind === 'refused') { + // The board moved on and the graph has been re-read: offer what is valid now. + state = out.state; + const shown = board.status(); + if (shown && shown.state === state) max = shown.maxIntents; + if (what === 'limit') endEdit(true); + draw(); + } else if (what === 'limit' && editing) limitInput.focus(); + } + + // ── intent limit, in the strip ─────────────────────────────────── + + function drawLimit() { + if (editing) return; + limitPrefix.textContent = `Intents ${intents} of `; + const text = maxText(max); + if (live && known && toolbarOffers(state).limit) { + limitButton.textContent = text; + if (limit.lastChild !== limitButton || limit.firstChild !== limitPrefix) { + limit.replaceChildren(limitPrefix, limitButton); + } + } else limit.replaceChildren(`Intents ${intents} of ${text}`); + } + + function startEdit() { + if (editing || !live) return; + editing = true; + limitInput.value = limitText(max); + limit.replaceChildren(limitPrefix, limitInput); + limitInput.focus(); + limitInput.select(); + } + + /** @param {boolean} refocus */ + function endEdit(refocus) { + if (!editing) return; + editing = false; + drawLimit(); + if (refocus && limitButton.isConnected) limitButton.focus(); + } + + limitButton.addEventListener('click', startEdit); + limitInput.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { + e.preventDefault(); + if (!saving) endEdit(true); + } else if (e.key === 'Enter') { + e.preventDefault(); + if (saving || limitInput.disabled) return; + const v = parseLimit(limitInput.value); + if (!v.ok) { + say(line, 'error', v.error); + return; + } + saving = true; + sendCtl({ maxIntents: v.value }, 'limit').finally(() => (saving = false)); + } + }); + // Leaving the box cancels, except while its value is being saved. + limitInput.addEventListener('blur', () => { + if (!saving) endEdit(false); + }); + + // ── poll results ───────────────────────────────────────────────── + + /** @param {ShownStatus | null} status */ + function update(status) { + if (!live) return; + if (status) { + known = true; + intents = status.intents; + truncated = status.truncated; + if (hold === 0) { + state = status.state; + max = status.maxIntents; + } + } + outer.hidden = !known; + if (known) draw(); + else drawLimit(); + } + + function end() { + live = false; + editing = false; + open = null; + drawLimit(); + } + + drawPanels(); + return { el, update, end }; +} diff --git a/web/public/writes.js b/web/public/writes.js index e2511f8..9ccbd0a 100644 --- a/web/public/writes.js +++ b/web/public/writes.js @@ -1,5 +1,6 @@ // @ts-check -// The rules of the drawer's write forms and board controls: which are offered when, and their fixed wording. No DOM. +// The rules of the board toolbar, the drawer's shortcuts and the board controls: which are offered when, and their +// fixed wording. No DOM. import { kindOf } from './names.js'; /** @typedef {'pause' | 'resume' | 'stop' | 'restart'} Action */ @@ -18,6 +19,10 @@ export const GIVE_UP_DEFAULT = "it cannot be done within the board's rules; reco export const TEXT_MAX = 2000; export const FIELD_MAX = 500; +/** The intent limit editor's tooltip. */ +export const LIMIT_NOTE = + 'A whole number, or none. A higher max_intents in the board file raises it again on the next board-runner run.'; + /** Kinds a hint is linked to; a hint on any other node is board-wide. */ const HINT_LINKS = ['intent', 'fact', 'hint']; @@ -60,6 +65,30 @@ export function controlActions(state) { return []; } +/** + * What the Board tab's toolbar offers in a goal state: the controls valid in it, + Hint always, + Intent while running + * or paused, + Amendment and the intent limit editor in any state but done. + * @param {string | null} state + * @returns {{ controls: Action[]; hint: boolean; intent: boolean; amendment: boolean; limit: boolean }} + */ +export function toolbarOffers(state) { + return { + controls: controlActions(state), + hint: true, + intent: state === 'running' || state === 'paused', + amendment: state !== 'done', + limit: state !== 'done', + }; +} + +/** + * The strip's text for the goal's `Max intents`, which the limit editor opens on. + * @param {number | 'none' | null} max + */ +export function maxText(max) { + return max === 'none' ? 'no limit' : max === null ? 'unknown' : String(max); +} + /** * The line above Add intent, with the status strip's own counts. * @param {number} used intents the graph draws From 7a19c9333aa99873f44c92cc933157d25b4a59d1 Mon Sep 17 00:00:00 2001 From: Trefor Southwell <48591903+springfall2008@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:24:35 +0000 Subject: [PATCH 3/3] fix(web): toolbar review fixes Co-Authored-By: Claude Opus 5.5 --- README.md | 4 ++-- web/public/board.js | 9 +++++++-- web/public/forms.js | 4 ++-- web/public/sending.js | 4 ++-- web/public/style.css | 4 ---- web/public/toolbar.js | 5 ++++- 6 files changed, 17 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 9377a7d..f5060d7 100644 --- a/README.md +++ b/README.md @@ -238,10 +238,10 @@ A form is disabled while its request is in flight. On success it clears, says "A shortly" and polls the graph at once. On failure it shows the server's error. If the board is over 400 nodes, the page warns that what you add may not appear. -- **Hints.** A hint is advice for the lead, read at its next round. From the toolbar it applies to the whole board. +- **+ Hint.** A hint is advice for the lead, read at its next round. From the toolbar it applies to the whole board. From "Hint about this node" on an intent, fact or hint it links to that node; on a conclusion, progress, rules or amendment node it links to nothing and applies to the whole board. A hint is allowed in any board state. -- **Intents**, while the board is running or paused. Write what a worker should try, and optionally "Done when" and +- **+ Intent**, while the board is running or paused. Write what a worker should try, and optionally "Done when" and "Give up when". Left empty, they become "a fact reporting what trying this showed" and "it cannot be done within the board's rules; record an inconclusive fact". From "Try next from this fact", the intent is linked `derived-from` that fact. The form shows how many intents the board has used out of `Max intents`. A person's intent is accepted diff --git a/web/public/board.js b/web/public/board.js index f02e392..7071ddf 100644 --- a/web/public/board.js +++ b/web/public/board.js @@ -294,8 +294,13 @@ export function mountBoard(el, opts) { me.conn = ok ? 'live' : 'retrying'; if (ok) me.error = null; me.delay = nextDelay(me.delay, ok); - renderStrip(me); - if (ok) opts.onPoll?.(); + // A throw in the strip, the toolbar or the poll hook must not stop the loop or leave `pollNow` waiters hanging. + try { + renderStrip(me); + if (ok) opts.onPoll?.(); + } catch { + console.error('Board strip update failed'); + } // A write landed while this poll was in flight, so it may predate the write: poll again at once. const again = me.again; me.again = false; diff --git a/web/public/forms.js b/web/public/forms.js index 4912127..5d03969 100644 --- a/web/public/forms.js +++ b/web/public/forms.js @@ -51,8 +51,8 @@ function textField(label, opts) { } /** - * A form box: an optional title, its fields, an optional note, a submit button and a status line. `body` gives the request - * body from the trimmed values, or a reason to send nothing. + * A form box: an optional title, its fields, an optional note, a submit button and a status line. `body` gives the + * request body from the trimmed values, or a reason to send nothing. * @param {{ * title?: string; * fields: { el: HTMLElement; input: HTMLInputElement | HTMLTextAreaElement }[]; diff --git a/web/public/sending.js b/web/public/sending.js index ef9dc0a..c33797d 100644 --- a/web/public/sending.js +++ b/web/public/sending.js @@ -1,5 +1,5 @@ -// Sending one write from the toolbar or the drawer: its controls disabled while in flight, a status line saying what happened, and -// an immediate graph poll once it lands. +// Sending one write from the toolbar or the drawer: its controls disabled while in flight, a status line saying what +// happened, and an immediate graph poll once it lands. import { ApiError, NOT_SIGNED_IN } from './api.js'; import { h } from './dom.js'; diff --git a/web/public/style.css b/web/public/style.css index fa71106..1a7e4b2 100644 --- a/web/public/style.css +++ b/web/public/style.css @@ -665,10 +665,6 @@ main { gap: 6px 8px; } -.controls-buttons .note { - margin: 0; -} - .write-status { margin: 0; font-size: 13px; diff --git a/web/public/toolbar.js b/web/public/toolbar.js index 8ffafcb..b623f94 100644 --- a/web/public/toolbar.js +++ b/web/public/toolbar.js @@ -260,6 +260,8 @@ function session(scope, name, outer, limit, board) { // ── intent limit, in the strip ─────────────────────────────────── function drawLimit() { + // A poll that shows a state with no limit to edit closes an open editor, unless its value is being saved. + if (editing && !saving && !(live && known && toolbarOffers(state).limit)) editing = false; if (editing) return; limitPrefix.textContent = `Intents ${intents} of `; const text = maxText(max); @@ -295,7 +297,8 @@ function session(scope, name, outer, limit, board) { if (!saving) endEdit(true); } else if (e.key === 'Enter') { e.preventDefault(); - if (saving || limitInput.disabled) return; + // A held Enter repeats: it must not open the editor from the button and then save it. + if (e.repeat || saving || limitInput.disabled) return; const v = parseLimit(limitInput.value); if (!v.ok) { say(line, 'error', v.error);