Public: anyone can read this; the crew can change it.

Observability 6: a Grafana-like view bar on top - time range, compare, variables - and a grid that fills #16865

opened this in answer to

Merged 45h 4m ago, live in production

mason/forge:mason/3695-observability-6-a-grafana-like-view-bar → main 0 commits fork 2 threads · 2 unresolved

  • Merged. mason/3695-observability-6-a-grafana-like-view-bar was merged into main as 2aecd66.

Review

Sign in to review this change.
13 files changed +306 −32
docs/design/areas/boards.md +4
@@ -44,3 +44,7 @@ One question, one answer. The page is the home's column and head, then the quest
4444 ## The list and a board's management (#9815)
4545
4646 `boardsList` is a `bd-block` "Your boards" with one tile per board (title, charts, range), or one plain sentence when there are none; the make-a-board form is a closed `disclosure` under it. Under a board, Panels, Add a panel and Board are folds. The panels in the grid keep their `card` shape.
47
48 ## The view bar (`.vbar`, #3695)
49
50 Top of a board, above the grid: two `seg()` controls of links, the time range (1h, 6h, 24h, 7d, 30d, All) and Live/Paused, and, when the address changed either, a "Back to the saved view" link. Each link is this board's address with `?range=` and `?live=`: a view is a link, never a saved setting, and the board's file keeps its own range and refresh (the "Board" fold under the grid is where those are saved). `.vbar` is a wrapping flex row with a 12px gap; the link is a 44px target. Row actions inside `.bd` (Pin to home, Up, Down) are always visible. Compare and variables are not here yet.
docs/features/boards-live.md +4
@@ -13,3 +13,7 @@ A board whose **Live** setting is on (`refresh` anything but `off`) opens one ev
1313 - **In the terminal**: open the board from the Boards screen (`src/tui/screens/boards.ts`). While it is open, a panel that moved says `live HH:MM:SSZ: N points moved · latest X` under its data line, fed by the same frames (`deltaOf` in `src/boards/delta.ts`).
1414
1515 The stream is `src/web/pages/boards-stream.ts`, which sends the frames and carries the client that draws them.
16
17 ## The view bar (#3695)
18
19 At the top of a board: the time range (1h, 6h, 24h, 7d, 30d, All) and Live / Paused. Each is a link to the same board with `?range=` or `?live=` in the address, so a view is shared as a link and nothing is saved; "Back to the saved view" drops it. The range and refresh the board's file keeps are saved under "Board" at the bottom. The stream takes the same `?range=`. Compare to previous, custom ranges and variables are not built yet. In the terminal the same view is two keys on the board screen (`src/tui/screens/boards.ts`): `v` steps the range (1h, 6h, 24h, 7d, 30d, All) and `l` flips Live and Paused; the line under the title says "a view, not saved" and nothing is written. `g` still edits the saved range.
src/boards/panel_data.ts +1 −1
@@ -12,7 +12,7 @@ import { drawChart, usesSeries, type Cell, type Chart, type Mark } from "./chart
1212 import { BUCKETS, MAX_STEP, oldestTime, runQuery, type Answer, type Bucket, type Row } from "./query.ts";
1313 import type { Board, Panel } from "./store.ts";
1414
15 export const RANGE_MS = { "1h": 3_600_000, "24h": 86_400_000, "7d": 604_800_000, "30d": 2_592_000_000 } as const;
15 export const RANGE_MS = { "1h": 3_600_000, "6h": 21_600_000, "24h": 86_400_000, "7d": 604_800_000, "30d": 2_592_000_000 } as const;
1616 /** The steps a panel picks from on its own, in seconds: 1 min to a week. */
1717 export const STEPS = [60, 120, 300, 600, 900, 1800, 3600, 7200, 10_800, 21_600, 43_200, 86_400, 604_800] as const;
1818 /** About one point per two pixels of a chart's plot: more says nothing a reader can see. */
src/boards/store.ts +1 −1
@@ -17,7 +17,7 @@ export const BOARDS_OWNER = "forge";
1717 export const BOARDS_REPO = "boards";
1818 const BRANCH = "main";
1919
20 export const RANGES = ["1h", "24h", "7d", "30d", "all"] as const;
20 export const RANGES = ["1h", "6h", "24h", "7d", "30d", "all"] as const;
2121 export const REFRESHES = ["off", "10s", "1m"] as const;
2222 export type Range = (typeof RANGES)[number];
2323 export type Refresh = (typeof REFRESHES)[number];
src/boards/view_bar.ts added +48
@@ -0,0 +1,48 @@
1 /**
2 * A board's view, as the address says it (#3695): `?range=` and `?live=`. A view is a link, never a
3 * saved setting: the board's file keeps its own range and refresh, and the view only overrides
4 * them for whoever opened the link. Plain strings in, plain data out; anything unknown is ignored,
5 * so a stale link shows the board as saved.
6 */
7 import { RANGES, type Board, type Range } from "./store.ts";
8
9 export type View = {
10 /** The range asked for, or null to use the board's own. */
11 range: Range | null;
12 /** Live asked for on (`1`) or off (`0`), or null to use the board's own. */
13 live: boolean | null;
14 };
15
16 export function readView(search: URLSearchParams): View {
17 const r = search.get("range") ?? "";
18 const l = search.get("live");
19 return {
20 range: (RANGES as readonly string[]).includes(r) ? (r as Range) : null,
21 live: l === "1" ? true : l === "0" ? false : null,
22 };
23 }
24
25 /** The board as this view shows it: the same panels over the view's range. */
26 export const viewed = (board: Board, view: View): Board => ({
27 ...board,
28 range: view.range ?? board.range,

?live=1 on a board saved as off becomes 10s here, but the stream address drops live, so boardStream sees off. The page promises a stream the server may not feed. Pass live to the stream, or have the stream ignore the saved refresh, and test it.

29 refresh: view.live === null ? board.refresh : view.live ? (board.refresh === "off" ? "10s" : board.refresh) : "off",
30 });
31
32 /**
33 * The range after `range` in the bar's order, round to the first: the terminal's one key for it.
34 */
35 export const nextRange = (range: Range): Range => RANGES[(RANGES.indexOf(range) + 1) % RANGES.length]!;
36
37 /**
38 * The address of `path` with the view's choices (only those asked), then `extra` (`wait=1`, say),
39 * all built as one query.
40 */
41 export function viewHref(path: string, view: View, extra: Readonly<Record<string, string>> = {}): string {
42 const q = new URLSearchParams();
43 if (view.range !== null) q.set("range", view.range);
44 if (view.live !== null) q.set("live", view.live ? "1" : "0");
45 for (const [k, v] of Object.entries(extra)) q.set(k, v);
46 const s = q.toString();
47 return s === "" ? path : `${path}?${s}`;
48 }
src/flow/pages.ts +3 −3
@@ -23,7 +23,7 @@ import { FRESH_MS, isDue, isKept, keeps, ownWriteAt, servedAtOnce } from "./keep
2323 import { forgeCeiling } from "./ceiling.ts";
2424 import type { PanelViewer } from "./panel_cache.ts";
2525 import type { Params } from "../boards/params.ts";
26 import type { Stored } from "../boards/store.ts";
26 import type { Range, Stored } from "../boards/store.ts";
2727 import type { PipelineKey } from "./pipeline.ts";
2828 import { pagesConfig, readAppPicture, readPagePicture, type AppJob, type AppPicture, type BoardPicture, type BoardsPicture, type FlowPicture, type PageJob, type PagesEnv, type Picture, type PictureOf, type QueryPicture } from "./pages_read.ts";
outdated

A second import from ../boards/store.ts; merge it into the Stored import above.

2929 import type { PagesAnswer, PagesAsk } from "./pages_worker.ts";
@@ -413,8 +413,8 @@ export function keepPages(app: App, owners: readonly string[], repos: readonly R
413413 const BOARD_FRESH_MS = 30_000;
414414
415415 /** One board and its panels' rows; undefined before its first reading is in. `board` is null when there is no such board. */
416 export function boardPicture(app: App, slug: string, waitMs = PAGE_WAIT_MS, now = Date.now(), asking: Asking = {}): Promise<BoardPicture | Failed | undefined> {
417 return pictureOf(app, `board:${slug}`, { kind: "board", slug, now, boardsSince: changed.get(app.db) ?? 0 }, waitMs, { freshMs: BOARD_FRESH_MS, ...asking });
416 export function boardPicture(app: App, slug: string, waitMs = PAGE_WAIT_MS, now = Date.now(), asking: Asking = {}, range?: Range): Promise<BoardPicture | Failed | undefined> {
417 return pictureOf(app, range === undefined ? `board:${slug}` : `board:${slug}:${range}`, { kind: "board", slug, now, boardsSince: changed.get(app.db) ?? 0, ...(range === undefined ? {} : { range }) }, waitMs, { freshMs: BOARD_FRESH_MS, ...asking });
418418 }
419419
420420 /** One query of the data page; undefined before its first reading is in. */
src/flow/pages_read.ts +7 −1
@@ -102,6 +102,11 @@ export interface BoardJob {
102102 readonly now: number;
103103 /** A board was changed at this time: a picture read before it is not this board any more. */
104104 readonly boardsSince: number;
105 /**
106 * A view's range (the address's `?range=`): the panels are read over it; the saved board is
107 * untouched.
108 */
109 readonly range?: Board["range"];
105110 }
106111 /** One question of the data page, as its form says it: a chart's rows, or (`params.rows`) the rows behind one point. */
107112 export interface QueryJob {
@@ -334,7 +339,8 @@ export async function readBoardPicture(env: PagesEnv, job: BoardJob): Promise<Bo
334339 const t0 = performance.now();
335340 const board = (await readBoard(env.reposRoot, job.slug)) ?? null;
336341 const marks = board === null ? [] : releaseMarks(env.db);
337 const panels = board === null ? [] : board.panels.map((panel) => drawnPanel(panel, panelData(env.db, board, panel, {}, job.now), marks));
342 const seen = board === null || job.range === undefined ? board : { ...board, range: job.range };
343 const panels = board === null || seen === null ? [] : board.panels.map((panel) => drawnPanel(panel, panelData(env.db, seen, panel, {}, job.now), marks));
338344 return { at: job.now, ms: performance.now() - t0, board, panels };
339345 }
340346
src/tui/screens/boards.ts +44 −14
@@ -18,6 +18,7 @@ import { formatValue } from "../../boards/chart.ts";
1818 import { watchBoard, type Frame } from "../../boards/live_hub.ts";
1919 import { panelData, type PanelData } from "../../boards/panel_data.ts";
2020 import { RANGES, type Board } from "../../boards/store.ts";
21 import { nextRange, viewed, type View } from "../../boards/view_bar.ts";
2122 import { listPinned, movePinned, pinPanel, unpinPanel } from "../../actions/board-pins.ts";
2223 import { boardRefusal, changeBoard, deleteBoard, duplicateBoard, listAllBoards, makeBoard, showBoard, type BoardError } from "../../actions/boards.ts";
2324 import type { Ctx, Screen } from "../app/app.ts";
@@ -79,10 +80,10 @@ export function dataLine(d: PanelData): string {
7980 * A board, panel by panel, as lines of text; the panel at `at` is marked, a
8081 * pinned one says so, and each panel with its `data` read says what it holds.
8182 */
82 export function boardLines(board: Board, at = -1, pinned: readonly string[] = [], data: readonly PanelData[] = [], moved: ReadonlyMap<number, string> = new Map()): string[] {
83 export function boardLines(board: Board, at = -1, pinned: readonly string[] = [], data: readonly PanelData[] = [], moved: ReadonlyMap<number, string> = new Map(), viewing = false): string[] {
8384 const lines = [
8485 plain(board.title),
85 `range ${board.range} · refresh ${board.refresh} · ${plural(board.panels.length, "panel")}`,
86 `range ${board.range} · refresh ${board.refresh} · ${plural(board.panels.length, "panel")}${viewing ? " · a view, not saved" : ""}`,
8687 ];
8788 for (const [i, p] of board.panels.entries()) {
8889 const query = Object.entries(p.query)
@@ -115,14 +116,22 @@ export function boardScreen(ctx: Ctx, f: Session, slug: string, first: Board): S
115116 let asking: { readonly index: number; readonly title: string } | undefined;
116117 // The gate is `changeBoard`'s, read once as the list's is.
117118 const mayEdit = f.user?.isAdmin === true && f.user.kind !== "agent";
119 /**
120 * The range and live asked for with `v` and `l`: a view of this screen, never written to the
121 * board.
122 */
123 let view: View = { range: null, live: null };
124 const shown = (): Board => viewed(board, view);
125 const viewing = (): boolean => view.range !== null || view.live !== null;
118126 let lines = boardLines(board, at, pinned);
119127 const moved = new Map<number, string>();
120128 const read = async (): Promise<void> => {
121129 const listed = await listPinned(f.app, f.user);
122130 pinned = listed.ok ? listed.value.filter((p) => p.slug === slug).map((p) => p.title) : [];
123131 // Only an admin person reaches this screen (`showBoard` let them in), as `panelData` asks.
124 data = board.panels.map((p) => panelData(f.app.db, board, p));
125 lines = boardLines(board, at, pinned, data, moved);
132 const seen = shown();
133 data = seen.panels.map((p) => panelData(f.app.db, seen, p));
134 lines = boardLines(seen, at, pinned, data, moved, viewing());
126135 ctx.invalidate();
127136 };
128137 /** Pin the marked panel, or unpin it when it is; `by` moves a pinned one in the home order. */
@@ -165,11 +174,36 @@ export function boardScreen(ctx: Ctx, f: Session, slug: string, first: Board): S
165174 await reload(index);
166175 ctx.toast(done.ok ? "panel removed" : refusal(done.error), done.ok ? "success" : "danger");
167176 });
177 /**
178 * Follow the board's frames while the view is live, and stop when it is not (or the screen goes).
179 */
180 let stopWatch: (() => void) | undefined;
181 let leaving: AbortSignal | undefined;
182 const follow = (): void => {
183 stopWatch?.();
184 stopWatch = undefined;
185 const seen = shown();
186 if (seen.refresh === "off" || !mayEdit || leaving === undefined || leaving.aborted) return;
187 stopWatch = watchBoard(f.app, slug, seen, (frame) => {
188 seen.panels.forEach((_, i) => {
189 const words = liveWords(frame, i);
190 if (words !== undefined) moved.set(i, words);
191 });
192 runAsync(ctx, read);
193 }).stop;
194 };
195 /** Change the view (not the board's file) and read the panels over it. */
196 const look = (next: View): void => {
197 view = next;
198 moved.clear();
199 follow();
200 runAsync(ctx, read);
201 };
168202 return {
169203 title: plain(board.title),
170204 get keys() {
171205 return [
172 binding(["j", "k"], "scroll"), binding(["[", "]"], "panel"), binding(["p"], "pin / unpin"),
206 binding(["j", "k"], "scroll"), binding(["v"], "view range"), binding(["l"], "live / paused"), binding(["[", "]"], "panel"), binding(["p"], "pin / unpin"),
173207 binding(["<", ">"], "move pin"),
174208 ...(mayEdit && board.panels.length > 0 ? [binding(["x"], "remove panel")] : []),
175209 binding(["esc", "q"], "back"),
@@ -177,15 +211,9 @@ export function boardScreen(ctx: Ctx, f: Session, slug: string, first: Board): S
177211 },
178212 async load(signal) {
179213 await read();
180 if (board.refresh === "off" || !mayEdit || signal.aborted) return;
181 const watch = watchBoard(f.app, slug, board, (frame) => {
182 board.panels.forEach((_, i) => {
183 const words = liveWords(frame, i);
184 if (words !== undefined) moved.set(i, words);
185 });
186 runAsync(ctx, read);
187 });
188 signal.addEventListener("abort", watch.stop, { once: true });
214 leaving = signal;
215 follow();
216 signal.addEventListener("abort", () => stopWatch?.(), { once: true });
189217 },
190218 render(area, s) {
191219 const c = ctx.theme.c;
@@ -219,6 +247,8 @@ export function boardScreen(ctx: Ctx, f: Session, slug: string, first: Board): S
219247 lines = boardLines(board, at, pinned, data, moved);
220248 return true;
221249 }
250 if (e.key === "v") return look({ ...view, range: nextRange(shown().range) }), true;
251 if (e.key === "l") return look({ ...view, live: shown().refresh === "off" }), true;
222252 if (e.key === "p") return act(), true;
223253 if (e.key === "<" || e.key === ">") return act(e.key === ">" ? 1 : -1), true;
224254 if (e.key === "esc" || e.key === "q") {
src/web/pages/boards-stream.ts +4 −2
@@ -7,6 +7,7 @@
77 */
88 import { boardPicture, isFailed } from "../../flow/pages.ts";
99 import { watchBoard } from "../../boards/live_hub.ts";
10 import { readView, viewed } from "../../boards/view_bar.ts";
1011 import { isSlug } from "../../boards/store.ts";
1112 import type { Ctx } from "../../http/context.ts";
1213 import { eventStream } from "../../http/sse.ts";
@@ -16,9 +17,10 @@ export async function boardStream(ctx: Ctx): Promise<Response> {
1617 const u = ctx.auth.user;
1718 const slug = ctx.params.slug ?? "";
1819 if (u?.isAdmin !== true || u.kind === "agent" || !isSlug(slug)) return notFoundPage(ctx);
19 const picture = await boardPicture(ctx.app, slug);
20 const view = readView(ctx.url.searchParams);
21 const picture = await boardPicture(ctx.app, slug, undefined, undefined, undefined, view.range ?? undefined);
2022 if (picture === undefined || isFailed(picture) || picture.board === null) return notFoundPage(ctx);
21 const board = picture.board;
23 const board = viewed(picture.board, view);
2224
2325 return eventStream(ctx.app, ctx.request, (emit, _close, ready) => {
2426 const watch = watchBoard(ctx.app, slug, board, (frame) => {
src/web/pages/boards-view.ts +32 −10
@@ -20,7 +20,8 @@ import { notFoundPage, signInFirst } from "../chrome.ts";
2020 import { html, when, type Html } from "../html.ts";
2121 import { BOARD_SLUG, maintenanceStrip } from "./maintenance_board.ts";
2222 import { page } from "../layout.ts";
23 import { btn, chartFrame, confirmAction, field, selectField } from "../ui.ts";
23 import { btn, chartFrame, confirmAction, field, selectField, seg } from "../ui.ts";
24 import { readView, viewed, viewHref, type View } from "../../boards/view_bar.ts";
2425 import { emptyList } from "../empty_words.ts";
2526 import { fold, reading, readingFailed, readingJs } from "../figure.ts";
2627 import { formatValue } from "../../boards/chart.ts";
@@ -70,13 +71,13 @@ export function drawPanel(
7071 }
7172
7273 /** The grid: each panel as drawn, naming the stream when the board is live. */
73 function grid(app: App, slug: string, board: Board, panels: readonly PanelDrawn[]): Html {
74 function grid(app: App, slug: string, board: Board, panels: readonly PanelDrawn[], view: View): Html {
7475 return html`<section
7576 class="bgrid"
7677 id="board-grid"
7778 ${board.refresh === "off"
7879 ? null
79 : html`data-stream="/boards/${slug}/stream"`}
80 : html`data-stream="${viewHref(`/boards/${slug}/stream`, view)}"`}
8081 >
8182 ${board.panels.length === 0
8283 ? html`<p class="muted bp-w3">This board has no panel yet. Add the first one under "Add a panel" below, or pin a chart from <a href="/boards/data">Explore the data</a>.</p>`
@@ -172,8 +173,26 @@ export async function boardsList(ctx: Ctx): Promise<Response> {
172173 return response;
173174 }
174175
176 /**
177 * The view bar at the top of a board: the range and live, each a link to this same board with the
178 * choice in its address, so a view is shared by link and nothing is saved (#3695).
179 */
180 function viewBar(slug: string, board: Board, view: View): Html {
181 const here = `/boards/${slug}`;
182 const range: string = board.range;
183 const live = board.refresh !== "off";
184 return html`<div class="vbar" id="board-view">
185 <nav aria-label="Time range">${seg(RANGES.map((r) => ({ label: r === "all" ? "All" : r, href: viewHref(here, { ...view, range: r }), current: r === range })))}</nav>
186 <nav aria-label="Live">${seg([
187 { label: "Live", href: viewHref(here, { ...view, live: true }), current: live },
188 { label: "Paused", href: viewHref(here, { ...view, live: false }), current: !live },
189 ])}</nav>
190 ${view.range === null && view.live === null ? null : html`<a class="small" href="${here}">Back to the saved view</a>`}
191 </div>`;
192 }
193
175194 /** A board's range as words. */
176 const RANGE_WORDS: Readonly<Record<Board["range"], string>> = { "1h": "The last hour", "24h": "The last 24 hours", "7d": "The last 7 days", "30d": "The last 30 days", all: "All of time" };
195 const RANGE_WORDS: Readonly<Record<Board["range"], string>> = { "1h": "The last hour", "6h": "The last 6 hours", "24h": "The last 24 hours", "7d": "The last 7 days", "30d": "The last 30 days", all: "All of time" };
177196
178197 function panelForm(slug: string, op: string, p: Panel | undefined, index: number, fields: Html): Html {
179198 const id = op === "edit" ? `panel-${String(index)}` : "panel-new";
@@ -246,13 +265,14 @@ export async function boardShow(ctx: Ctx): Promise<Response> {
246265 const slug = ctx.params.slug ?? "";
247266 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
248267 if (denied(ctx) || !isSlug(slug)) return notFoundPage(ctx);
268 const view = readView(ctx.url.searchParams);
249269 // What a "Reading…" page asks: it answers when the worker has the board, and draws nothing.
250270 if (ctx.url.searchParams.has("wait")) {
251 return waitAnswer(await boardPicture(ctx.app, slug, LONG_WAIT_MS));
271 return waitAnswer(await boardPicture(ctx.app, slug, LONG_WAIT_MS, undefined, undefined, view.range ?? undefined));
252272 }
253273 // The board's file and every panel's rows are read by a worker and kept: no query and no git on
254274 // this thread.
255 const picture = await timePhaseAsync(ctx.request, "picture", () => boardPicture(ctx.app, slug));
275 const picture = await timePhaseAsync(ctx.request, "picture", () => boardPicture(ctx.app, slug, undefined, undefined, undefined, view.range ?? undefined));
256276 if (picture === undefined || isFailed(picture)) {
257277 return page({
258278 ctx,
@@ -260,13 +280,14 @@ export async function boardShow(ctx: Ctx): Promise<Response> {
260280 wide: true,
261281 body: html`<div class="hf bd"><header class="hf-head"><div class="hf-title"><h1>Boards</h1></div>
262282 <nav class="bd-nav" aria-label="Elsewhere">${btn("All boards", { href: "/boards", variant: "ghost" })}</nav></header>
263 <section class="bd-now">${picture === undefined ? reading("Reading this board's charts…", `/boards/${slug}?wait=1`, `/boards/${slug}`) : readingFailed(picture.failed, `/boards/${slug}`)}</section></div>`,
283 <section class="bd-now">${picture === undefined ? reading("Reading this board's charts…", viewHref(`/boards/${slug}`, view, { wait: "1" }), viewHref(`/boards/${slug}`, view)) : readingFailed(picture.failed, `/boards/${slug}`)}</section></div>`,
264284 ...(picture === undefined ? { scriptJs: readingJs } : {}),
265285 });
266286 }
267287 if (picture.board === null) return notFoundPage(ctx);
268 const board = picture.board;
269 const panels = timePhase(ctx.request, "grid", () => grid(ctx.app, slug, board, picture.panels));
288 const saved = picture.board;
289 const board = viewed(saved, view);
290 const panels = timePhase(ctx.request, "grid", () => grid(ctx.app, slug, board, picture.panels, view));
270291 const rendering = performance.now();
271292 const n = board.panels.length;
272293 const response = page({
@@ -278,9 +299,10 @@ export async function boardShow(ctx: Ctx): Promise<Response> {
278299 <div class="hf-title"><h1>${board.title}</h1><p class="hf-live muted">${String(n)} ${n === 1 ? "chart" : "charts"} over ${RANGE_WORDS[board.range].toLowerCase()}. Times are UTC. ${board.refresh === "off" ? null : html`<span id="board-live" class="num" role="status" data-state="idle">Moves as events arrive.</span>`}</p></div>
279300 <nav class="bd-nav" aria-label="Elsewhere">${btn("All boards", { href: "/boards", variant: "ghost" })}${btn("Explore the data", { href: "/boards/data", variant: "ghost" })}</nav>
280301 </header>
302 ${viewBar(slug, board, view)}
281303 ${slug === BOARD_SLUG ? maintenanceStrip(ctx.app.db) : null}
282304 ${panels}
283 ${manage(slug, board, queryFields(readParams(ctx.url.searchParams)), listPins(ctx.app.db, ctx.auth.user?.id ?? ""))}
305 ${manage(slug, saved, queryFields(readParams(ctx.url.searchParams)), listPins(ctx.app.db, ctx.auth.user?.id ?? ""))}
284306 </div>`,
285307 scriptJs: boardStreamJs + chartHoverJs,
286308 });
src/web/style/components.ts +4
@@ -1190,6 +1190,10 @@ a[data-palette] { display: none; }
11901190 .bp-foot { margin: auto 0 0; gap: 16px; font-size: var(--fs-min); color: var(--muted-fg); }
11911191 .bp-foot > a { display: inline-flex; align-items: center; min-height: 44px; }
11921192 @media (hover: hover) and (pointer: fine) { .bp-foot > a:hover { color: var(--accent); } }
1193 .vbar { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; margin: 0 0 12px; }
1194 .vbar > a { display: inline-flex; align-items: center; min-height: 44px; color: var(--muted-fg); }
1195 /* A board's own row actions stay in view: ten invisible buttons a row leave a gap. */
1196 .bd .row-actions { opacity: 1; }
11931197 .bp-w2 { flex: 2 1 calc(66.667% - 4px); }
11941198 .bp-w3 { flex: 1 1 100%; }
11951199 @media (min-width: 720px) {
test/boards-store.test.ts +16
@@ -202,6 +202,22 @@ describe("/boards", () => {
202202 expect((await post("/boards/fleet-health/settings", { range: "weeks", refresh: "10s" })).headers.get("set-cookie")).toContain("danger");
203203 });
204204
205 test("the view bar: a range or live in the address is a view, and nothing is saved (#3695)", async () => {
206 const before = (await readBoard(app.reposRoot, "fleet-health"))!;
207 const body = await (await asAdmin("/boards/fleet-health?range=1h&live=0")).text();
208 expect(body).toContain('id="board-view"');
209 expect(body).toMatch(/<a\s+href="\/boards\/fleet-health\?range=6h&(amp;)?live=0"/);
210 expect(body).toMatch(/aria-current="page"\s*>1h</);
211 expect(body).toContain("over the last hour");
212 expect(body).toContain("Back to the saved view");
213 expect(body).not.toContain("data-stream=");
214 const live = await (await asAdmin("/boards/fleet-health?range=7d&live=1")).text();
215 expect(live).toContain('data-stream="/boards/fleet-health/stream?range=7d&amp;live=1"');
216 // A range this board does not know is the board as saved.
217 expect(await (await asAdmin("/boards/fleet-health?range=never")).text()).not.toContain("Back to the saved view");
218 expect((await readBoard(app.reposRoot, "fleet-health"))!).toEqual(before);
219 });
220
205221 test("make, rename, move, add, edit, remove, duplicate and delete through the forms", async () => {
206222 const made = await post("/boards/new", { title: "Scratch <b>" });
207223 expect(made.headers.get("location")).toBe("/boards/scratch-b");
test/boards-view-bar.test.ts added +138
@@ -0,0 +1,138 @@
1 /**
2 * The view bar's reads (#3695): a range asked for in the address reads the panels over it (6h is
3 * a range), and is its own cache entry; a live view of a board saved as off names a stream that
4 * is fed; the terminal's `v` and `l` change the view and never the board's file.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { showBoard, writeBoard } from "../src/actions/boards.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { panelData, RANGE_MS } from "../src/boards/panel_data.ts";
13 import type { Board, Panel } from "../src/boards/store.ts";
14 import { nextRange, viewHref } from "../src/boards/view_bar.ts";
15 import { createRun } from "../src/core/runs.ts";
16 import { createToken } from "../src/core/tokens.ts";
17 import { createUser, type User } from "../src/core/users.ts";
18 import { boardPicture, isFailed } from "../src/flow/pages.ts";
19 import { serve } from "../src/http/server.ts";
20 import { createForgeApp } from "../src/tui/forge.ts";
21 import { boardScreen } from "../src/tui/screens/boards.ts";
22 import { headlessTerminal } from "../src/tui/term/terminal.ts";
23 import { quietLogs } from "./helpers/globals.ts";
24 import { settleApp } from "./helpers/tui.ts";
25
26 quietLogs();
27
28 const panel: Panel = { title: "Runs", chart: "number", query: { source: "runs", aggregate: "count" }, w: 1, h: 1 };
29 let dir: string;
30 let app: App;
31 let carol: User;
32 let token = "";
33 let servers: Awaited<ReturnType<typeof serve>>;
34
35 beforeAll(async () => {
36 dir = await mkdtemp(join(tmpdir(), "forge-boards-view-bar-"));
37 app = createApp({ dataDir: dir, port: 0 });
38 servers = await serve(app);
39 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "carol", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
40 if (!made.ok) throw new Error(made.error);
41 carol = made.value;
42 token = createToken(app.db, carol.id, "t", "admin").token;
43 app.db.run("INSERT INTO repo (id, owner_id, name) VALUES ('r1', ?, 'app')", [carol.id]);
44 const wrote = await writeBoard(app, carol, "quiet", { title: "Quiet", range: "7d", refresh: "off", panels: [panel] });
45 if (!wrote.ok) throw new Error(JSON.stringify(wrote.error));
46 }, 30_000);
47
48 afterAll(async () => {
49 await servers.stop?.();
50 app.close();
51 await rm(dir, { recursive: true, force: true });
52 });
53
54 describe("the view bar's reads", () => {
55 test("6h is a range: its window is six hours, and a run three hours old is inside it and outside 1h", () => {
56 expect(RANGE_MS["6h"] as number).toBe(6 * 3_600_000);
57 const run = createRun(app.db, { repoId: "r1", kind: "check" });
58 app.db.run("UPDATE run SET created_at = ? WHERE id = ?", [new Date(Date.now() - 3 * 3_600_000).toISOString(), run.id]);
59 const count = (range: Board["range"]) => {
60 const d = panelData(app.db, { title: "Q", range, refresh: "off", panels: [panel] }, panel);
61 return d.ok ? d.rows[0]?.value ?? 0 : -1;
62 };
63 expect(count("1h")).toBe(0);
64 expect(count("6h")).toBe(1);
65 });
66
67 test("a range in the address is its own cached reading, not the board's", async () => {
68 const read = async (range?: Board["range"]) => {
69 const p = await boardPicture(app, "quiet", 5000, Date.now(), {}, range);
70 if (p === undefined || isFailed(p)) throw new Error("no picture");
71 return JSON.stringify(p.panels);
72 };
73 const short = await read("1h");
74 const six = await read("6h");
75 expect(six).not.toBe(short);
76 // Asked again, each is its own: neither was overwritten by the other.
77 expect(await read("1h")).toBe(short);
78 expect(await read("6h")).toBe(six);
79 });
80
81 test("the wait address is one query, with the view first", () => {
82 expect(viewHref("/boards/x", { range: "6h", live: true }, { wait: "1" })).toBe("/boards/x?range=6h&live=1&wait=1");
83 expect(viewHref("/boards/x", { range: null, live: null }, { wait: "1" })).toBe("/boards/x?wait=1");
84 expect(viewHref("/boards/x", { range: null, live: null })).toBe("/boards/x");
85 });
86
87 test("the ranges cycle in the bar's order and come round", () => {
88 expect(nextRange("1h")).toBe("6h");
89 expect(nextRange("all")).toBe("1h");
90 });
91 });
92
93 describe("a live view of a board saved as off", () => {
94 test("the page names a stream with live=1, and that stream is fed", async () => {
95 const page = await (await fetch(`${servers.url}/boards/quiet?live=1`, { headers: { authorization: `Bearer ${token}` } })).text();
96 expect(page).toContain('data-stream="/boards/quiet/stream?live=1"');
97 const stop = new AbortController();
98 const res = await fetch(`${servers.url}/boards/quiet/stream?live=1`, { headers: { authorization: `Bearer ${token}` }, signal: stop.signal });
99 const reader = res.body!.getReader();
100 const first = await reader.read();
101 expect(new TextDecoder().decode(first.value)).toContain("event: hello");
102 createRun(app.db, { repoId: "r1", kind: "check" });
103 app.bus.append({ kind: "run.queued", repoId: "r1", payload: {} });
104 let text = "";
105 const end = Date.now() + 3000;
106 while (!text.includes("event: panels") && Date.now() < end) {
107 const got = await Promise.race([reader.read(), new Promise<null>((r) => setTimeout(() => r(null), 500))]);
108 if (got !== null && !got.done) text += new TextDecoder().decode(got.value);
109 }
110 expect(text).toContain("event: panels");
111 stop.abort();
112 });
113 });
114
115 describe("the terminal's view", () => {
116 test("v cycles the range and l the live, as a view: the board's file keeps what it had", async () => {
117 const shown = await showBoard(app, carol, "quiet");
118 if (!shown.ok) throw new Error("no board");
119 const terminal = headlessTerminal(120, 30);
120 const { app: tui, session } = createForgeApp(app, { sshUsername: "carol", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: carol }, { terminal, exitHooks: false });
121 tui.start();
122 tui.ctx.push(boardScreen(tui.ctx, session, "quiet", shown.value));
123 await settleApp(tui);
124 expect(tui.screen.toText()).toContain("range 7d · refresh off");
125 terminal.feed("v");
126 await settleApp(tui);
127 expect(tui.screen.toText()).toContain("range 30d · refresh off · 1 panel · a view, not saved");
128 terminal.feed("l");
129 await settleApp(tui);
130 expect(tui.screen.toText()).toContain("range 30d · refresh 10s");
131 terminal.feed("l");
132 await settleApp(tui);
133 expect(tui.screen.toText()).toContain("refresh off");
134 tui.stop?.();
135 const after = await showBoard(app, carol, "quiet");
136 expect(after.ok && [after.value.range, after.value.refresh]).toEqual(["7d", "off"]);
137 });
138 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs