From 5912e3ec30c8f92430de14088f99069d25243ca6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 08:08:35 -0600 Subject: [PATCH 1/5] feat(pm-stack): Trends: merged, features by project, issues and tasks, by day, read by Cloudflare A Trends screen: pull requests merged by kind, features merged by project with the features themselves, issues and bugs opened against closed, the time from opened to merged, and tasks finished, over 7, 14, 30 or 90 days, each set against the same time before. Whoever serves the app reads it: GitHub's history a page at a time ("everything changed since"), kept by day in its own storage and kept up from where it stopped; the queue's finished tasks by one indexed read. No machine is asked. Cloudflare's own clock reads the history on while somebody looks at the screen. Charts are a small kit any screen can use (public/charts.js), and Trends is the first page that is a module of its own (public/pages). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01YLT5K1QVuzZjfWGFhXSSNF --- pm-stack/console/edge/src/direct.ts | 22 +- pm-stack/console/edge/src/edge.ts | 50 +- pm-stack/console/public/app.css | 256 +++++++++ pm-stack/console/public/app.js | 30 +- pm-stack/console/public/charts.js | 418 +++++++++++++++ pm-stack/console/public/files.json | 22 +- pm-stack/console/public/look.js | 11 +- pm-stack/console/public/pages/index.js | 28 + pm-stack/console/public/pages/trends.js | 164 ++++++ pm-stack/console/public/themes.css | 21 + pm-stack/console/public/ui.js | 44 ++ pm-stack/console/scripts/edge-smoke.ts | 65 +++ pm-stack/console/src/reads.ts | 11 +- pm-stack/console/src/server.ts | 15 +- pm-stack/console/src/trends.ts | 465 +++++++++++++++++ pm-stack/console/test/charts.test.ts | 424 +++++++++++++++ pm-stack/console/test/console.test.ts | 68 ++- pm-stack/console/test/direct.test.ts | 21 + pm-stack/console/test/dom.ts | 77 +++ pm-stack/console/test/edge.test.ts | 124 +++++ pm-stack/console/test/look.test.ts | 9 +- pm-stack/console/test/pages.test.ts | 241 +++++++++ pm-stack/console/test/sw.test.ts | 8 + pm-stack/console/test/trends.test.ts | 666 ++++++++++++++++++++++++ 24 files changed, 3230 insertions(+), 30 deletions(-) create mode 100644 pm-stack/console/public/charts.js create mode 100644 pm-stack/console/public/pages/index.js create mode 100644 pm-stack/console/public/pages/trends.js create mode 100644 pm-stack/console/public/ui.js create mode 100644 pm-stack/console/src/trends.ts create mode 100644 pm-stack/console/test/charts.test.ts create mode 100644 pm-stack/console/test/dom.ts create mode 100644 pm-stack/console/test/pages.test.ts create mode 100644 pm-stack/console/test/trends.test.ts diff --git a/pm-stack/console/edge/src/direct.ts b/pm-stack/console/edge/src/direct.ts index 2316345657..30d034cfd0 100644 --- a/pm-stack/console/edge/src/direct.ts +++ b/pm-stack/console/edge/src/direct.ts @@ -24,6 +24,7 @@ import { Ops, type Fetch, type Run, type RunResult } from "../../src/ops.ts"; import { Plan } from "../../src/plan.ts"; import { timed } from "../../src/timed.ts"; import { Work } from "../../src/work.ts"; +import { memoryShelf, type Shelf, Trends } from "../../src/trends.ts"; /** Sections the edge reads itself. */ export const DIRECT_READ_SECTIONS = ["board", "prs", "priorities", "asks", "census", "done"] as const; @@ -87,6 +88,9 @@ export interface DirectSecrets { github?: GitHubMemory; /** The clock, where a test sets it. */ now?: () => number; + /** Where the history behind the Trends screen is kept. Without it, + * it is kept in memory and read again when the object next starts. */ + shelf?: Shelf; } const GITHUB_API = "https://api.github.com"; @@ -591,7 +595,11 @@ async function ghApi( }; } // A list asked for before is asked for by its tag. - const had = write ? undefined : await memory?.get(url); + // An address with a time in it ("everything changed since…") is asked + // once and never again in those words: keeping its answer would only + // push out the answers that are asked for again. + const moving = /[?&]since=/.test(url); + const had = write || moving ? undefined : await memory?.get(url); let got: { res: Awaited>; text: string; whole: boolean }; try { // The answer and its body, within the time; and no timer left @@ -675,7 +683,9 @@ async function ghApi( // empty answer this once; kept under GitHub's tag it would be the // answer every time GitHub said "not modified" after. const etag = res.headers?.get("etag") ?? null; - if (etag && whole) await memory.set(url, { etag, text }); + if (moving) { + // Not kept (see above). + } else if (etag && whole) await memory.set(url, { etag, text }); else await memory.delete(url); } return { code: 0, stdout: text, stderr: "" }; @@ -752,6 +762,7 @@ export interface DirectClasses { ops: Ops; work: Work; plan: Plan; + trends: Trends; } /** The console's own classes, wired for the edge. They are made once @@ -778,7 +789,12 @@ export function directClasses(edge: EdgeConfig, options: DirectOptions): DirectC const ops = new Ops(config, edgeRun(config, options, fetchImpl), options.seen ? queueFetch : fetchImpl); const clock = options.now ? () => new Date((options.now as () => number)()) : undefined; const work = new Work(ops, undefined, clock); - return { ops, work, plan: new Plan(ops, work, clock) }; + return { + ops, + work, + plan: new Plan(ops, work, clock), + trends: new Trends(ops, options.shelf ?? memoryShelf(), clock), + }; } /** Whether a request of the queue store may change something: any diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index 4c7b7e9d75..9b1b0f6ca3 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -172,6 +172,13 @@ export const SILENT_MS = 10 * 60_000; /** With nobody looking, what the edge reads itself and tells the owner * about is read again this often. */ const OWN_CLOCK_MS = 60_000; +/** While somebody looks at the Trends screen, the object's own clock + * reads its history on: this many pages each minute until it has been + * read to its end, then what changed, this often. */ +const TRENDS_EVERY_MS = 30 * 60_000; +const TRENDS_PAGES_A_WAKE = 2; +/** It does that for this long after the screen was last asked for. */ +const TRENDS_WATCHED_MS = 24 * 60 * 60_000; /** While the app is connected, how often this side wakes to read again * what has gone stale (each list by its own age), so that what changed * is said to the app without the app asking. */ @@ -345,6 +352,11 @@ export class Edge { private shown = new Set(); /** When what the owner is told about was last read by the clock. */ private clockAt = 0; + /** When the history behind the Trends screen was last read on by the clock. */ + private trendsAt = 0; + /** When the Trends screen was last asked for (kept, so that an + * object started again still knows somebody looks at it). */ + private trendsSeen: number | null = null; /** This side's latest calls of GitHub and the queue store, numbered. */ private outward: (Outward & { n: number })[] = []; private outwardN = 0; @@ -1544,6 +1556,10 @@ export class Edge { fetchImpl: this.direct?.fetchImpl as never, now: this.now, github: this.github, + shelf: { + get: async (key) => ((await this.kv.get(`trend:${key}`)) as string | undefined) ?? null, + put: (key, text) => this.kv.put(`trend:${key}`, text), + }, seen: (call) => { this.outward.push({ ...call, n: ++this.outwardN }); if (this.outward.length > OUTWARD_KEPT) this.outward.splice(0, this.outward.length - OUTWARD_KEPT); @@ -2115,6 +2131,14 @@ export class Edge { // the first of either. const due = await this.heldDue(cfg); if (due !== null) wakes.push(Math.max(now + 1000, due)); + // The history behind the Trends screen is read on by this side's + // own clock while somebody looks at that screen: a minute after + // its last look until it is whole, then half an hour after it was + // last read to its end. With nobody looking it does not wake for it. + const trends = (await this.trendsWatched(now)) ? this.mine(cfg)?.trends : undefined; + if (trends) { + wakes.push(Math.max(now + 1000, this.trendsAt + this.ownClockMs, await trends.dueAt(TRENDS_EVERY_MS))); + } if (wakes.length > 0) await this.setAlarm(Math.min(...wakes)); } @@ -2144,6 +2168,12 @@ export class Edge { }); } + /** Somebody has looked at the Trends screen within the last day. */ + private async trendsWatched(now: number): Promise { + if (this.trendsSeen === null) this.trendsSeen = Number((await this.kv.get("trendsSeen")) ?? 0) || 0; + return this.trendsSeen > 0 && now - this.trendsSeen < TRENDS_WATCHED_MS; + } + /** This side reads something the owner is told about, and a device * is there to be told: it has to wake by itself to read it. */ private async clockWanted(cfg: EdgeConfig | null): Promise { @@ -2183,6 +2213,17 @@ export class Edge { for (let look = 0; look < 2; look++) await this.docs.current(this.ownedTold(cfg), CLOCK_WAIT_MS); await this.tell(cfg).catch((error) => console.error(`pm-edge: notify: ${(error as Error).message}`)); } + // The history behind the Trends screen, while somebody looks at + // that screen (within the last day): read on a little each minute + // until it has been read to its end, then kept up every half hour, + // so the screen has it when it is next opened. No machine is asked. + const trends = (await this.trendsWatched(now)) ? this.mine(cfg)?.trends : undefined; + if (trends && now - this.trendsAt >= this.ownClockMs && (await trends.due(TRENDS_EVERY_MS))) { + this.trendsAt = now; + await trends + .advance(TRENDS_PAGES_A_WAKE) + .catch((error) => console.error(`pm-edge: trends: ${(error as Error).message}`)); + } // The app is connected: what this side reads itself and has gone // stale is read again (each list by its own age; one that has not // changed costs nothing), and a change is said to the app as the @@ -2437,7 +2478,14 @@ export class Edge { const from = this.outwardN; let read: unknown; try { - read = await platformRead(seg, url.searchParams, mine.ops, mine.plan); + read = await platformRead(seg, url.searchParams, mine.ops, mine.plan, mine.trends); + // Somebody looks at Trends: for a day after, its history is + // read on by this side's own clock (see `alarm`). + if (seg.length === 1 && seg[0] === "trends") { + this.trendsSeen = this.now(); + await this.kv.put("trendsSeen", this.trendsSeen); + await this.schedule(cfg); + } } catch (error) { // Refused here: a machine has its own way in, and a read may // be asked twice. Anything else is said as it is; so is this, diff --git a/pm-stack/console/public/app.css b/pm-stack/console/public/app.css index e473123275..cbb1a93fde 100644 --- a/pm-stack/console/public/app.css +++ b/pm-stack/console/public/app.css @@ -14,6 +14,17 @@ --bad: #f85149; /* Text on that red: white on it was 3.4 to 1. */ --bad-ink: #1a0405; + /* What a chart tells its series apart by (public/charts.js): a fixed + order of colours, chosen so that neighbours in it can be told apart + by people who see colour differently, and stepped for a dark page. + The light page's steps are below. They are not the status colours + above and are never used for them. */ + --series-1: #3987e5; + --series-2: #d95926; + --series-3: #199e70; + --series-4: #c98500; + --series-5: #d55181; + --series-6: #0ca30c; --tab-h: 62px; --top-h: 52px; /* How it looks beyond its colours, each set by an attribute on this @@ -49,6 +60,12 @@ --warn: #8a5a00; --bad: #c5222c; --bad-ink: #ffffff; + --series-1: #2a78d6; + --series-2: #eb6834; + --series-3: #1baf7a; + --series-4: #eda100; + --series-5: #e87ba4; + --series-6: #008300; } } * { @@ -835,3 +852,242 @@ input[type="radio"] { margin-top: calc(10px * var(--space)); flex-wrap: wrap; } + +/* ---- charts --------------------------------------------------------- */ +/* Drawn by public/charts.js, which says the rules. A mark takes its + series' colour from its class; words and numbers stay in the text's. */ +.kpis { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); + gap: calc(10px * var(--space)); + margin-bottom: calc(10px * var(--space)); +} +.kpi { + display: flex; + flex-direction: column; + gap: calc(2px * var(--space)); + padding: calc(12px * var(--space)); + background: var(--panel); + border: var(--edge) solid var(--line); + border-radius: calc(12px * var(--round)); +} +.kpi-label, +.kpi-delta { + font-size: 0.78rem; + color: var(--quiet); +} +.kpi-value { + font-size: 1.6rem; + font-weight: 650; + line-height: 1.15; +} +.kpi-delta.up { + color: var(--good); +} +.kpi-delta.down { + color: var(--warn); +} +.spark { + display: block; + width: 100%; + height: auto; + margin-top: calc(4px * var(--space)); +} +.spark .ln { + fill: none; + stroke: var(--quiet); + stroke-width: 1.5; + stroke-linejoin: round; + stroke-linecap: round; +} +.spark .dot { + fill: var(--accent); +} +figure.chart { + margin: 0 0 calc(10px * var(--space)); +} +.readout { + display: flex; + flex-wrap: wrap; + gap: calc(2px * var(--space)) calc(12px * var(--space)); + min-height: 1.4em; + font-size: 0.85rem; + color: var(--quiet); +} +.readout b, +.legend b { + color: var(--text); + font-weight: 650; +} +.plot { + display: block; + width: 100%; + max-width: 640px; + height: auto; + /* A finger moving across it reads the days; up and down still scrolls. */ + touch-action: pan-y; + outline: none; +} +.plot:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} +.plot .grid { + stroke: var(--line); + stroke-width: 1; +} +.plot .hair { + stroke: var(--quiet); + stroke-width: 1; +} +.plot .tick { + fill: var(--quiet); + font-size: 9.5px; +} +.plot .ln { + fill: none; + stroke-width: 2; + stroke-linejoin: round; + stroke-linecap: round; +} +.plot .wash { + opacity: 0.1; +} +.plot .dot.ring { + stroke: var(--panel); + stroke-width: 2; +} +/* Today is not over. */ +.plot .col.partial { + opacity: 0.55; +} +.plot.choosing .col { + opacity: 0.4; +} +.plot.choosing .col.on { + opacity: 1; +} +.s1 { + fill: var(--series-1); +} +.s2 { + fill: var(--series-2); +} +.s3 { + fill: var(--series-3); +} +.s4 { + fill: var(--series-4); +} +.s5 { + fill: var(--series-5); +} +.s6 { + fill: var(--series-6); +} +.so { + fill: var(--quiet); +} +.ln.s1 { + stroke: var(--series-1); +} +.ln.s2 { + stroke: var(--series-2); +} +.ln.s3 { + stroke: var(--series-3); +} +.ln.s4 { + stroke: var(--series-4); +} +.ln.s5 { + stroke: var(--series-5); +} +.ln.s6 { + stroke: var(--series-6); +} +.ln.so { + stroke: var(--quiet); +} +/* The mark of a series beside its name: a block for columns, a stroke + for lines. */ +.sw { + display: inline-block; + width: 10px; + height: 10px; + margin-right: calc(5px * var(--space)); + border-radius: calc(2px * var(--round)); + background: var(--quiet); +} +.sw.ln { + width: 14px; + height: 3px; + vertical-align: middle; +} +.sw.s1 { + background: var(--series-1); +} +.sw.s2 { + background: var(--series-2); +} +.sw.s3 { + background: var(--series-3); +} +.sw.s4 { + background: var(--series-4); +} +.sw.s5 { + background: var(--series-5); +} +.sw.s6 { + background: var(--series-6); +} +.legend { + display: flex; + flex-wrap: wrap; + gap: calc(4px * var(--space)) calc(14px * var(--space)); + margin: calc(6px * var(--space)) 0 0; + padding: 0; + list-style: none; + font-size: 0.8rem; + color: var(--quiet); +} +.figures summary, +.fold summary { + display: flex; + align-items: center; + gap: calc(6px * var(--space)); + min-height: 36px; + cursor: pointer; +} +.figures summary { + font-size: 0.8rem; + color: var(--quiet); +} +.figures .scroll { + max-height: 260px; + overflow: auto; +} +.figures table { + border-collapse: collapse; + font-size: 0.8rem; + font-variant-numeric: tabular-nums; +} +.figures th, +.figures td { + padding: calc(3px * var(--space)) calc(12px * var(--space)) calc(3px * var(--space)) 0; + border-bottom: var(--edge) solid var(--line); + text-align: right; + font-weight: 400; + white-space: nowrap; +} +.figures thead th { + color: var(--quiet); +} +.figures th:first-child { + text-align: left; +} +/* A card that opens: a project and the features it merged. */ +.fold .link { + margin-top: calc(6px * var(--space)); +} diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index cf221844da..406638fb2f 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -4,6 +4,9 @@ // // The page draws from three documents the server keeps ready (core, // questions, ops), so moving between sections never waits on a fetch. +import { h } from "./ui.js"; +import { PAGES } from "./pages/index.js"; + const API = "/console/api/"; // Without a page (the tests import the small functions) nothing is found. const $ = (id) => (typeof document === "undefined" ? null : document.getElementById(id)); @@ -15,22 +18,6 @@ const keptEl = $("kept"); // ---- small helpers ----------------------------------------------------- -function h(tag, attrs, ...kids) { - const el = document.createElement(tag); - for (const [k, v] of Object.entries(attrs || {})) { - if (v === false || v === null || v === undefined) continue; - if (k.startsWith("on")) el.addEventListener(k.slice(2), v); - else if (k === "class") el.className = v; - else if (v === true) el.setAttribute(k, ""); - else el.setAttribute(k, v); - } - for (const kid of kids.flat(Infinity)) { - if (kid === null || kid === undefined || kid === false) continue; - el.append(kid.nodeType ? kid : document.createTextNode(String(kid))); - } - return el; -} - function icon(d) { const NS = "http://www.w3.org/2000/svg"; const s = document.createElementNS(NS, "svg"); @@ -1647,6 +1634,8 @@ function viewMore() { const ops = docs.ops || {}; const b = docs.core.board || { counts: {} }; const tile = (to, title, sub) => h("button", { class: "tile", onclick: () => go(to) }, title, h("span", {}, sub)); + // The pages that are modules of their own say which part they go in. + const pageTiles = (group) => PAGES.filter((page) => page.group === group).map((page) => tile(page.route, page.title, page.says)); const out = [ h("h2", {}, "Plan"), h( @@ -1655,6 +1644,7 @@ function viewMore() { tile("more/roadmap", "Roadmap", "id, fleet, atlas, PM stack: built, in progress, planned"), tile("more/bugs", "Bugs", "report one; see what is open and what was fixed"), tile("more/intake", "Intake", "every note, bug and change you sent, and where it went"), + pageTiles("Plan"), ), h("h2", {}, "Operations"), h( @@ -1673,6 +1663,7 @@ function viewMore() { tile("more/platform", "Platform", "every Worker: what it does, whether it is in service, how it is deployed"), tile("more/device", "On this device", "what is kept here to send, and what it shows with no connection"), Look ? tile("more/look", "Appearance", lookCounts()) : null, + pageTiles("Operations"), tile("more/releases", "Releases", "what is deployed, the Android app, and putting either out again"), ), ]; @@ -3707,6 +3698,13 @@ const VIEWS = { "more/bugs": ["Bugs", viewBugs], "more/intake": ["Intake", viewIntake], }; +/** What a page that is a module of its own (public/pages) is handed: + * the app's own parts, so that it reads, acts and moves about the same + * way as every screen written here. */ +const app = { api, freshly, act, go, toast, empty, ago, sheet, newId, redraw: () => draw() }; +for (const page of PAGES) VIEWS[page.route] = [page.title, (sub) => page.view(sub, app), page.doc]; +/** Every screen's address, for the tests. */ +export const routesKnown = () => Object.keys(VIEWS); let route = "now"; let drawSeq = 0; /** The screen whose content the view holds, once it has been drawn. */ diff --git a/pm-stack/console/public/charts.js b/pm-stack/console/public/charts.js new file mode 100644 index 0000000000..655091e0fe --- /dev/null +++ b/pm-stack/console/public/charts.js @@ -0,0 +1,418 @@ +// Charts, for any screen that has numbers over time: columns stacked by +// what they are made of, lines, and the tile that is one number. +// +// The rules they are drawn by (the same on every screen, so a chart +// here is read like a chart there): +// +// - colour says which series a mark belongs to and nothing else. The +// series colours are the theme's own (--series-1 to --series-6 in +// app.css, a fixed order chosen so that neighbours can be told +// apart by people who see colour differently); "everything else" is +// always grey. A series keeps its colour whatever else is shown. +// - words and numbers are never written in a series colour: a mark of +// the colour sits beside them. +// - two or more series always have a legend, with each one's total. +// - one scale to a chart. Two measures are two charts. +// - a column is at most 24 wide, has a gap from its neighbour, a gap +// between its parts, and a rounded top; a line is 2 wide. +// - pointing at, tapping or arrowing to a day says that day's numbers +// in the line under the title: every series at once, the number +// first. Nothing is only in that line: the table under each chart +// has every number. +// - today is not over, so its column is drawn fainter. +// +// The sums are plain functions (tested by hand-worked numbers); the +// drawing is SVG elements with classes. Nothing writes a style. +import { h, s } from "./ui.js"; + +/** The drawing's own units: it is scaled to the width it is given. */ +const W = 360; +const H = 172; +const PLOT = { x: 34, y: 10, w: 320, h: 128 }; +const GAP = 2; +const BAR_MAX = 24; + +/** The smallest clean number (1, 2, 2.5 or 5 times a power of ten) that + * is at least `value`: the top of a scale. Nothing to show is a scale + * to 1 (a chart of zeros still has an axis). */ +export function niceMax(value) { + if (!(value > 0)) return 1; + const power = 10 ** Math.floor(Math.log10(value)); + for (const step of [1, 2, 2.5, 5, 10]) { + if (step * power >= value) return step * power; + } + return 10 * power; +} + +/** A count as it is written: in full under ten thousand, then 12.9K, 4.2M. */ +export function compact(n) { + if (n === null || n === undefined || Number.isNaN(n)) return "–"; + const abs = Math.abs(n); + if (abs < 10_000) return Number.isInteger(n) ? n.toLocaleString("en-US") : String(Math.round(n * 10) / 10); + if (abs < 1_000_000) return `${Math.round(n / 100) / 10}K`; + return `${Math.round(n / 100_000) / 10}M`; +} + +/** Minutes as a person says them: 45 min, 3.5 h, 2.1 d. */ +export function minutesSaid(minutes) { + if (minutes === null || minutes === undefined) return "–"; + if (minutes < 90) return `${Math.round(minutes)} min`; + if (minutes < 36 * 60) return `${Math.round(minutes / 6) / 10} h`; + return `${Math.round(minutes / 144) / 10} d`; +} + +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; +const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; +/** "24 Nov", from a date (the days here are UTC days). */ +export const dayShort = (date) => `${Number(date.slice(8, 10))} ${MONTHS[Number(date.slice(5, 7)) - 1]}`; +/** "Tue 24 Nov". */ +export const dayLong = (date) => `${WEEKDAYS[new Date(`${date}T00:00:00Z`).getUTCDay()]} ${dayShort(date)}`; + +/** The days in groups of `size`, counted back from the last day so that + * the newest group is whole; the oldest may be short. Each group is the + * places of its days in the list. A size of 1 is the days themselves. */ +export function groupsOf(count, size) { + const groups = []; + for (let end = count; end > 0; end -= size) groups.unshift([Math.max(0, end - size), end]); + return groups; +} + +/** A series added up group by group. */ +export const rollUp = (values, groups) => groups.map(([from, to]) => values.slice(from, to).reduce((sum, v) => sum + (v ?? 0), 0)); + +/** The total of a series over its last `days` places, and over the same + * number before them (null when there are not that many before). */ +export function windowTotals(values, days) { + const n = values.length; + const sum = (from, to) => values.slice(Math.max(0, from), Math.max(0, to)).reduce((total, v) => total + (v ?? 0), 0); + return { now: sum(n - days, n), before: n >= days * 2 ? sum(n - days * 2, n - days) : null }; +} + +/** How a total stands against the one before it. `tone` is "up", + * "down" or "" (level, or nothing to set it against). */ +export function deltaSaid(now, before) { + if (before === null || before === undefined) return { text: "", tone: "" }; + if (before === 0) return now === 0 ? { text: "level", tone: "" } : { text: `▲ from none`, tone: "up" }; + const change = Math.round(((now - before) / before) * 100); + if (change === 0) return { text: "level", tone: "" }; + return change > 0 ? { text: `▲ ${change}%`, tone: "up" } : { text: `▼ ${-change}%`, tone: "down" }; +} + +/** Where each column of a stacked chart goes and how tall each of its + * parts is. `series` is a list of lists of numbers, bottom first; `max` + * is the top of the scale. A part with something in it is at least 1 + * tall, and every part but the top one gives up `GAP` to the gap above + * it. */ +export function stackGeometry(series, max, plot = PLOT) { + const count = series[0]?.length ?? 0; + const band = count > 0 ? plot.w / count : plot.w; + const width = Math.max(1, Math.min(BAR_MAX, band - GAP)); + const columns = []; + for (let i = 0; i < count; i++) { + const present = series.map((values, k) => [k, values[i] ?? 0]).filter(([, v]) => v > 0); + let cursor = plot.y + plot.h; + const parts = present.map(([k, value], at) => { + const raw = (value / max) * plot.h; + const top = at === present.length - 1; + const height = Math.max(1, raw - (top ? 0 : GAP)); + const part = { series: k, value, y: cursor - height, h: height, top }; + cursor -= raw; + return part; + }); + columns.push({ x: plot.x + i * band + (band - width) / 2, w: width, total: present.reduce((sum, [, v]) => sum + v, 0), parts }); + } + return { band, columns }; +} + +/** The points of a line: one for each place that has a number. A place + * with none (null) breaks the line there, so the result is a list of + * runs. */ +export function lineRuns(values, max, plot = PLOT) { + const count = values.length; + const step = count > 1 ? plot.w / (count - 1) : 0; + const runs = []; + let run = []; + values.forEach((value, i) => { + if (value === null || value === undefined) { + if (run.length) runs.push(run); + run = []; + return; + } + run.push({ i, x: plot.x + (count > 1 ? i * step : plot.w / 2), y: plot.y + plot.h - (Math.min(value, max) / max) * plot.h }); + }); + if (run.length) runs.push(run); + return runs; +} + +/** Which place a pointer is over: its x across the drawing, as a share + * of the drawing's width, to the nearest place. */ +export function placeAt(share, count, plot = PLOT, between = true) { + if (count <= 0) return -1; + const x = share * W - plot.x; + const at = between ? Math.floor(x / (plot.w / count)) : Math.round(count > 1 ? x / (plot.w / (count - 1)) : 0); + return Math.max(0, Math.min(count - 1, at)); +} + +// ---- drawing ------------------------------------------------------------ + +const slotClass = (slot) => (slot === "other" ? "so" : `s${slot}`); + +/** A column's part with a rounded top (the top of its column). */ +function roundedTop(x, y, w, hh) { + const r = Math.min(4, w / 2, hh); + return `M${x},${y + hh}V${y + r}Q${x},${y} ${x + r},${y}H${x + w - r}Q${x + w},${y} ${x + w},${y + r}V${y + hh}Z`; +} + +/** The scale's lines and numbers, and the days along the bottom. */ +function frame(max, labels, between, format = compact) { + const out = []; + for (const share of [0, 0.5, 1]) { + const y = PLOT.y + PLOT.h - share * PLOT.h; + out.push(s("line", { class: "grid", x1: PLOT.x, x2: PLOT.x + PLOT.w, y1: y, y2: y })); + out.push(s("text", { class: "tick", x: PLOT.x - 5, y: y + 3.5, "text-anchor": "end" }, format(max * share))); + } + const count = labels.length; + const at = (i) => (between ? PLOT.x + (i + 0.5) * (PLOT.w / count) : PLOT.x + (count > 1 ? (i * PLOT.w) / (count - 1) : PLOT.w / 2)); + const shown = count <= 1 ? [0] : count <= 8 ? [0, count - 1] : [0, Math.floor((count - 1) / 2), count - 1]; + for (const i of shown) { + const anchor = i === 0 ? "start" : i === count - 1 ? "end" : "middle"; + const x = i === 0 ? PLOT.x : i === count - 1 ? PLOT.x + PLOT.w : at(i); + out.push(s("text", { class: "tick", x, y: H - 8, "text-anchor": anchor }, labels[i])); + } + return out; +} + +/** The line under a chart's title: what is pointed at, every series at once. */ +function readoutLine() { + const el = h("p", { class: "readout", role: "status", "aria-live": "polite" }); + const say = (lead, items) => { + // A space between each, so that read aloud they are separate words + // (on the screen the row's own gap keeps them apart). + el.replaceChildren( + h("b", {}, lead), + ...items.flatMap((item) => [" ", h("span", { class: "read" }, item.slot === undefined ? null : h("i", { class: `sw ${slotClass(item.slot)}` }), h("b", {}, item.value), ` ${item.name}`)]), + ); + }; + return { el, say }; +} + +/** The names of the series, each with a mark of its colour and its total. */ +function legend(series, line) { + return h( + "ul", + { class: "legend" }, + series.map((one) => h("li", {}, h("i", { class: `sw ${line ? "ln " : ""}${slotClass(one.slot)}` }), `${one.name} `, h("b", {}, one.total))), + ); +} + +/** Every number of a chart, as a table: what the chart shows, for a + * reader who cannot see it or wants the figures. */ +function tableOf(labels, series, format = compact) { + return h( + "details", + { class: "figures" }, + h("summary", {}, "The numbers"), + h( + "div", + { class: "scroll" }, + h( + "table", + {}, + h("thead", {}, h("tr", {}, h("th", { scope: "col" }, "When"), series.map((one) => h("th", { scope: "col" }, one.name)))), + h( + "tbody", + {}, + labels.map((label, i) => h("tr", {}, h("th", { scope: "row" }, label), series.map((one) => h("td", {}, format(one.values[i]))))), + ), + ), + ), + ); +} + +/** Pointing, tapping and the arrow keys choose a place; leaving lets go. */ +function choosing(svg, count, between, choose) { + let at = -1; + const set = (next) => { + if (next === at) return; + at = next; + choose(at); + }; + const from = (event) => { + const box = svg.getBoundingClientRect(); + if (box.width <= 0) return; + set(placeAt((event.clientX - box.left) / box.width, count, PLOT, between)); + }; + svg.addEventListener("pointermove", from); + svg.addEventListener("pointerdown", from); + svg.addEventListener("pointerleave", (event) => { + // A finger lifted leaves the day it chose on show; a mouse moved away lets go. + if (event.pointerType === "mouse") set(-1); + }); + svg.addEventListener("blur", () => set(-1)); + svg.addEventListener("keydown", (event) => { + const move = { ArrowLeft: -1, ArrowRight: 1 }[event.key]; + if (move !== undefined) set(Math.max(0, Math.min(count - 1, (at < 0 ? (move > 0 ? -1 : count) : at) + move))); + else if (event.key === "Home") set(0); + else if (event.key === "End") set(count - 1); + else if (event.key === "Escape") set(-1); + else return; + event.preventDefault(); + }); +} + +/** Columns stacked by what they are made of. + * + * title what the chart is of + * labels one for each column, short ("24 Nov") + * long one for each column, as said in the line under the title + * series [{ name, slot, values }], bottom first; slot is 1 to 6, or "other" + * unit what a column's total is of ("merged") + * partial the last column is not over yet (today) + */ +export function stackedColumns({ title, note = "", labels, long, series, unit, partial = false }) { + const shown = series.filter((one) => one.values.some((v) => v > 0)); + const drawn = shown.length > 0 ? shown : series.slice(0, 1); + const totals = labels.map((_, i) => drawn.reduce((sum, one) => sum + (one.values[i] ?? 0), 0)); + const max = niceMax(Math.max(0, ...totals)); + const { columns } = stackGeometry( + drawn.map((one) => one.values), + max, + ); + const readout = readoutLine(); + const whole = totals.reduce((sum, v) => sum + v, 0); + const rest = () => readout.say(`${compact(whole)} ${unit}`, []); + const groups = columns.map((column, i) => + s( + "g", + { class: `col${partial && i === columns.length - 1 ? " partial" : ""}` }, + column.parts.map((part) => + part.top + ? s("path", { class: slotClass(drawn[part.series].slot), d: roundedTop(column.x, part.y, column.w, part.h) }) + : s("rect", { class: slotClass(drawn[part.series].slot), x: column.x, y: part.y, width: column.w, height: part.h }), + ), + ), + ); + const svg = s( + "svg", + { class: "plot", viewBox: `0 0 ${W} ${H}`, role: "img", tabindex: "0", "aria-label": `${title}. ${compact(whole)} ${unit} in all. The arrow keys read each column.` }, + frame(max, labels, true), + groups, + ); + choosing(svg, columns.length, true, (at) => { + groups.forEach((g, i) => g.classList.toggle("on", i === at)); + svg.classList.toggle("choosing", at >= 0); + if (at < 0) return rest(); + readout.say( + `${long[at]} · ${compact(totals[at])}${partial && at === columns.length - 1 ? " so far" : ""}`, + drawn.length > 1 ? drawn.map((one) => ({ slot: one.slot, value: compact(one.values[at] ?? 0), name: one.name })) : [], + ); + }); + rest(); + const withTotals = drawn.map((one) => ({ ...one, total: compact(one.values.reduce((sum, v) => sum + (v ?? 0), 0)) })); + return h( + "figure", + { class: "card chart" }, + h("figcaption", {}, h("h3", {}, title), note ? h("p", { class: "meta" }, note) : null), + readout.el, + svg, + drawn.length > 1 ? legend(withTotals, false) : null, + tableOf(long, drawn.length > 1 ? [...drawn, { name: "All", values: totals }] : drawn), + ); +} + +/** Lines over time. One series is drawn with a wash under it and needs + * no legend (the title says what it is); `format` writes its numbers. */ +export function lineChart({ title, note = "", labels, long, series, format = compact, unit = "" }) { + const all = series.flatMap((one) => one.values).filter((v) => v !== null && v !== undefined); + const max = niceMax(Math.max(0, ...all)); + const readout = readoutLine(); + // At rest: each series' figure for the whole of what is shown, where it was given one. + const rest = () => + readout.say( + `${labels.length} days`, + series.filter((one) => one.total !== undefined).map((one) => ({ slot: one.slot, value: one.total, name: series.length > 1 ? one.name : unit })), + ); + const marks = []; + const dots = []; + for (const one of series) { + const runs = lineRuns(one.values, max); + const cls = slotClass(one.slot); + for (const run of runs) { + const d = run.map((p, i) => `${i ? "L" : "M"}${Math.round(p.x * 100) / 100},${Math.round(p.y * 100) / 100}`).join(""); + if (series.length === 1 && run.length > 1) { + const base = PLOT.y + PLOT.h; + marks.push(s("path", { class: `wash ${cls}`, d: `${d}L${run[run.length - 1].x},${base}L${run[0].x},${base}Z` })); + } + // A run of one day is a dot; of more, a line. + if (run.length > 1) marks.push(s("path", { class: `ln ${cls}`, d })); + else marks.push(s("circle", { class: `dot ${cls}`, cx: run[0].x, cy: run[0].y, r: 2.5 })); + } + // The dot that follows the place chosen; it starts on the last number. + const lastRun = runs[runs.length - 1]; + const end = lastRun ? lastRun[lastRun.length - 1] : null; + const dot = s("circle", { class: `dot ring ${cls}`, cx: end ? end.x : -20, cy: end ? end.y : -20, r: 4 }); + dots.push({ dot, runs, end }); + marks.push(dot); + } + const hair = s("line", { class: "hair", x1: -9, x2: -9, y1: PLOT.y, y2: PLOT.y + PLOT.h }); + const svg = s( + "svg", + { class: "plot", viewBox: `0 0 ${W} ${H}`, role: "img", tabindex: "0", "aria-label": `${title}. The arrow keys read each day.` }, + frame(max, labels, false, format), + hair, + marks, + ); + choosing(svg, labels.length, false, (at) => { + for (const { dot, runs, end } of dots) { + const point = at < 0 ? end : runs.flat().find((p) => p.i === at); + dot.setAttribute("cx", String(point ? point.x : -20)); + dot.setAttribute("cy", String(point ? point.y : -20)); + } + const x = at < 0 ? -9 : PLOT.x + (labels.length > 1 ? (at * PLOT.w) / (labels.length - 1) : PLOT.w / 2); + hair.setAttribute("x1", String(x)); + hair.setAttribute("x2", String(x)); + if (at < 0) return rest(); + readout.say( + long[at], + series.map((one) => ({ slot: one.slot, value: format(one.values[at]), name: series.length > 1 ? one.name : unit })), + ); + }); + rest(); + return h( + "figure", + { class: "card chart" }, + h("figcaption", {}, h("h3", {}, title), note ? h("p", { class: "meta" }, note) : null), + readout.el, + svg, + series.length > 1 ? legend(series, true) : null, + tableOf(long, series, format), + ); +} + +/** A row of the numbers a screen leads with. Each: what it is, the + * number, how it stands against the time before (an arrow and a figure, + * never colour alone), and the shape of its days. */ +export function statTiles(tiles) { + return h( + "div", + { class: "kpis" }, + tiles.map((tile) => { + const values = tile.spark ?? []; + const max = niceMax(Math.max(0, ...values)); + const plot = { x: 1, y: 2, w: 98, h: 20 }; + const run = lineRuns(values, max, plot)[0] ?? []; + const d = run.map((p, i) => `${i ? "L" : "M"}${Math.round(p.x * 10) / 10},${Math.round(p.y * 10) / 10}`).join(""); + const end = run[run.length - 1]; + return h( + "div", + { class: "kpi" }, + h("span", { class: "kpi-label" }, tile.label), + h("b", { class: "kpi-value" }, tile.value), + tile.delta?.text ? h("span", { class: `kpi-delta ${tile.delta.tone}` }, `${tile.delta.text} ${tile.against}`) : h("span", { class: "kpi-delta" }, tile.against ?? ""), + run.length > 1 + ? s("svg", { class: "spark", viewBox: "0 0 100 24", "aria-hidden": "true" }, s("path", { class: "ln", d }), s("circle", { class: "dot", cx: end.x, cy: end.y, r: 2 })) + : null, + ); + }), + ); +} diff --git a/pm-stack/console/public/files.json b/pm-stack/console/public/files.json index 3b8d321fc7..08b159efed 100644 --- a/pm-stack/console/public/files.json +++ b/pm-stack/console/public/files.json @@ -1,5 +1,5 @@ { - "about": "Every file the app is made of, named once. The laptop's service (src/server.ts) and the Worker (edge/src/edge.ts) serve exactly these, the Worker's build (edge/build.mjs) ships exactly these, and the service worker (public/sw.js) keeps them for when there is no connection. A new file for the app is a line here and nothing else. 'kept' says when the service worker keeps a copy: 'installed' is at once, so the app opens offline after one visit; 'used' is when the page first asks for it (a typeface nobody chose is never fetched); 'never' is the service worker itself, which the browser keeps.", + "about": "Every file the app is made of, named once. The laptop's service (src/server.ts) and the Worker (edge/src/edge.ts) serve exactly these, the Worker's build (edge/build.mjs) ships exactly these, and the service worker (public/sw.js) keeps them for when there is no connection. A new file for the app is a line here and nothing else (a new page is its file under pages/, a line in pages/index.js, and a line here). 'kept' says when the service worker keeps a copy: 'installed' is at once, so the app opens offline after one visit; 'used' is when the page first asks for it (a typeface nobody chose is never fetched); 'never' is the service worker itself, which the browser keeps.", "page": "index.html", "files": [ { @@ -17,6 +17,26 @@ "type": "text/javascript; charset=utf-8", "kept": "installed" }, + { + "path": "ui.js", + "type": "text/javascript; charset=utf-8", + "kept": "installed" + }, + { + "path": "charts.js", + "type": "text/javascript; charset=utf-8", + "kept": "installed" + }, + { + "path": "pages/index.js", + "type": "text/javascript; charset=utf-8", + "kept": "installed" + }, + { + "path": "pages/trends.js", + "type": "text/javascript; charset=utf-8", + "kept": "installed" + }, { "path": "app.css", "type": "text/css; charset=utf-8", diff --git a/pm-stack/console/public/look.js b/pm-stack/console/public/look.js index 64d06d4aef..e221273608 100644 --- a/pm-stack/console/public/look.js +++ b/pm-stack/console/public/look.js @@ -2,8 +2,9 @@ // of its text, the room around things, how round the corners are, and // whether anything moves. // -// Each choice is one attribute on the page's root element (data-theme, -// data-font, data-size, data-space, data-corners, data-motion) and the +// Each choice is one attribute on the page's root element (data-theme +// and with it data-scheme, data-font, data-size, data-space, +// data-corners, data-motion) and the // style sheets do the rest: themes.css has a block of colours for each // theme, look.css a rule for each of the others. Nothing here writes a // style, so the page's content policy stays as strict as it is. @@ -180,8 +181,12 @@ * device. */ function attrs(settings, systemDark) { const s = normal(settings); + const theme = themeFor(s, systemDark); return { - "data-theme": themeFor(s, systemDark), + "data-theme": theme, + // Whether that theme is a dark or a light one: what is drawn in + // colours of its own (the charts' series) has a set for each. + "data-scheme": schemeOf(theme), "data-font": s.font, "data-size": s.size, "data-space": s.space, diff --git a/pm-stack/console/public/pages/index.js b/pm-stack/console/public/pages/index.js new file mode 100644 index 0000000000..05ba781a86 --- /dev/null +++ b/pm-stack/console/public/pages/index.js @@ -0,0 +1,28 @@ +// The app's pages that are modules of their own. +// +// A page is one file in this folder that exports what it is: +// +// export default { +// route: "more/trends", // where it lives: under More +// title: "Trends", // the heading, and its tile on More +// group: "Plan", // which part of More its tile is in +// says: "…", // the line on its tile +// view(sub, app) { … }, // the screen: a list of elements +// }; +// +// `view` is given what follows the route in the address (more/trends/30 +// gives "30") and the app's own parts: `app.api(path)` reads (and the +// service worker keeps the answer for when there is no connection), +// `app.freshly(path)` marks a read as asked for again when the owner +// pressed refresh, `app.act(kind, args, said, button)` does something +// (kept on the device and sent when there is a connection, like every +// action), `app.go(route)`, `app.toast(text)`, `app.empty(text)`, +// `app.ago(iso)`. It builds with `h` from ../ui.js and the classes in +// app.css, and charts from ../charts.js. +// +// To add a page: write its file, add it to PAGES here, and name the +// file in ../files.json. The tests check all three agree, and the app +// gives it its route, its tile and its copy for offline. +import trends from "./trends.js"; + +export const PAGES = [trends]; diff --git a/pm-stack/console/public/pages/trends.js b/pm-stack/console/public/pages/trends.js new file mode 100644 index 0000000000..1f8592f738 --- /dev/null +++ b/pm-stack/console/public/pages/trends.js @@ -0,0 +1,164 @@ +// Trends: what the fleet got done, day by day. Pull requests merged and +// what they were, features by project with the features themselves, +// issues opened against issues closed, how long a pull request waits, +// and tasks finished. Read by whoever serves the app from GitHub and the +// queue's store (src/trends.ts); no machine is needed for any of it. +import { compact, dayLong, dayShort, deltaSaid, groupsOf, lineChart, minutesSaid, rollUp, stackedColumns, statTiles, windowTotals } from "../charts.js"; +import { h } from "../ui.js"; + +const WINDOWS = [ + [7, "7 days"], + [14, "14 days"], + [30, "30 days"], + [90, "90 days"], +]; +/** The window last chosen, while the app is open. */ +let chosen = 30; + +/** Which colour each kind of pull request and each project is drawn in. + * Fixed: a kind or a project is the same colour in every window. */ +const KIND_SERIES = [ + ["feat", "features", 1], + ["fix", "fixes", 2], + ["docs", "docs", 3], + ["test", "tests", 4], + ["other", "everything else", "other"], +]; +const PROJECT_SLOTS = { id: 1, fleet: 2, atlas: 3, "pm-stack": 4, mcpx: 5, other: "other" }; + +const middle = (values) => { + const sorted = values.filter((v) => v !== null && v !== undefined).sort((a, b) => a - b); + if (sorted.length === 0) return null; + const mid = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; +}; + +/** The document as the screen draws it: the window's days (the same + * number before them are only for setting a total against), by the day + * up to a month and by the week beyond, with each chart's series. */ +export function shape(doc) { + const n = Math.min(doc.window, doc.days.length); + const first = doc.days.length - n; + const cut = (values) => values.slice(first); + const days = cut(doc.days); + const weekly = n > 31; + const groups = groupsOf(n, weekly ? 7 : 1); + const columns = (values) => rollUp(cut(values), groups); + const labels = groups.map(([, to]) => dayShort(days[to - 1])); + const long = groups.map(([from, to]) => (weekly ? `${dayShort(days[from])} to ${dayShort(days[to - 1])}` : dayLong(days[from]))); + const against = `on the ${n} days before`; + const kpi = (label, values) => { + const totals = windowTotals(values, n); + return { label, value: compact(totals.now), delta: deltaSaid(totals.now, totals.before), against: totals.before === null ? `in ${n} days` : against, spark: cut(values) }; + }; + const featuresAll = doc.days.map((_, i) => doc.projects.reduce((sum, p) => sum + (doc.features.projects[p.id]?.[i] ?? 0), 0)); + const typical = middle(cut(doc.merged.minutes)); + const tasks = "error" in doc.tasks ? null : doc.tasks; + const kpis = [kpi("Pull requests merged", doc.merged.all), kpi("Features merged", featuresAll), kpi("Issues closed", doc.issues.closed)]; + if (tasks) kpis.push(kpi("Tasks finished", tasks.all)); + kpis.push({ label: "Open to merged, typically", value: minutesSaid(typical), against: "the middle pull request", spark: cut(doc.merged.minutes).map((v) => v ?? 0) }); + const taskKinds = tasks ? [...tasks.kinds].sort((a, b) => (a.kind === "other" ? 1 : b.kind === "other" ? -1 : a.kind < b.kind ? -1 : 1)) : []; + let slot = 0; + const sum = (values) => cut(values).reduce((total, v) => total + (v ?? 0), 0); + return { + n, + days, + weekly, + labels, + long, + dayLabels: days.map(dayShort), + dayLong: days.map(dayLong), + kpis, + mergedByKind: KIND_SERIES.map(([id, name, s]) => ({ name, slot: s, values: columns(doc.merged.kinds[id] ?? []) })), + featuresByProject: doc.projects.map((p) => ({ name: p.title, slot: PROJECT_SLOTS[p.id] ?? "other", values: columns(doc.features.projects[p.id] ?? []) })), + issues: [ + { name: "opened", slot: 2, values: cut(doc.issues.opened), total: compact(sum(doc.issues.opened)) }, + { name: "closed", slot: 1, values: cut(doc.issues.closed), total: compact(sum(doc.issues.closed)) }, + ], + bugs: [ + { name: "reported", slot: 2, values: cut(doc.bugs.opened), total: compact(sum(doc.bugs.opened)) }, + { name: "fixed", slot: 1, values: cut(doc.bugs.closed), total: compact(sum(doc.bugs.closed)) }, + ], + minutes: [{ name: "open to merged", slot: 1, values: cut(doc.merged.minutes), total: minutesSaid(typical) }], + tasks: tasks ? taskKinds.map((k) => ({ name: k.kind, slot: k.kind === "other" ? "other" : ++slot, values: columns(k.days) })) : null, + tasksSince: tasks?.since ?? null, + // Each project that merged a feature in the window, the most first. + features: doc.projects + .map((p) => ({ id: p.id, title: p.title, slot: PROJECT_SLOTS[p.id] ?? "other", count: sum(doc.features.projects[p.id] ?? []), latest: doc.features.latest[p.id] ?? [] })) + .filter((p) => p.count > 0) + .sort((a, b) => b.count - a.count || (a.title < b.title ? -1 : 1)), + }; +} + +/** What has to be said before the charts: history still being read, + * something that could not be read, and whose days these are. */ +export function notes(doc) { + const out = []; + if (!doc.history.whole) { + out.push(`The history is still being read from GitHub. It has reached ${dayLong(doc.history.readTo.slice(0, 10))}: counts after that are not all in yet. It reads on by itself; ↻ reads on now.`); + } + if (doc.partial && doc.why) out.push(doc.why); + return out; +} + +async function view(sub, app) { + const days = WINDOWS.some(([d]) => String(d) === sub) ? Number(sub) : chosen; + chosen = days; + const doc = await app.api(app.freshly(`trends?days=${days}`)); + const sh = shape(doc); + const per = sh.weekly ? "by week" : "by day"; + const today = sh.weekly ? "This week is still going." : "Today is still going."; + const out = [ + h( + "div", + { class: "seg", role: "group", "aria-label": "How far back" }, + WINDOWS.map(([d, label]) => h("button", { "aria-pressed": String(d === days), onclick: () => app.go(`more/trends/${d}`) }, label)), + ), + ...notes(doc).map((text) => h("div", { class: "card flag" }, h("p", { class: "meta" }, text))), + statTiles(sh.kpis), + stackedColumns({ title: `Pull requests merged, ${per}`, note: `By what the title says each is. ${today}`, labels: sh.labels, long: sh.long, series: sh.mergedByKind, unit: "merged", partial: true }), + stackedColumns({ title: `Features merged, ${per}, by project`, note: "A pull request whose title begins feat, under the project its scope belongs to.", labels: sh.labels, long: sh.long, series: sh.featuresByProject, unit: "features", partial: true }), + ]; + if (sh.features.length > 0) { + out.push(h("h2", {}, `Features merged in ${sh.n} days, by project`)); + for (const project of sh.features) { + out.push( + h( + "details", + { class: "card fold", open: project === sh.features[0] }, + h("summary", {}, h("i", { class: `sw s${project.slot === "other" ? "o" : project.slot}` }), h("b", {}, project.title), ` ${compact(project.count)}`), + project.latest.map((f) => h("a", { class: "link", href: f.url, target: "_blank", rel: "noopener" }, f.title, h("span", {}, `#${f.number} · merged ${app.ago(f.at)}`))), + project.count > project.latest.length ? h("p", { class: "meta" }, `The latest ${project.latest.length} of ${compact(project.count)}.`) : null, + ), + ); + } + } + out.push( + lineChart({ title: "Issues opened and closed, by day", note: "Closed above opened is the backlog going down.", labels: sh.dayLabels, long: sh.dayLong, series: sh.issues }), + lineChart({ title: "Bugs reported and fixed, by day", labels: sh.dayLabels, long: sh.dayLong, series: sh.bugs }), + lineChart({ title: "From opened to merged, by day", note: "The middle pull request of each day: half waited less, half more.", labels: sh.dayLabels, long: sh.dayLong, series: sh.minutes, format: minutesSaid, unit: "typically" }), + ); + if (sh.tasks) { + out.push( + stackedColumns({ + title: `Tasks finished, ${per}`, + note: sh.tasksSince && sh.tasksSince > sh.days[0] ? `By kind. The queue has them from ${dayLong(sh.tasksSince)}. ${today}` : `By kind. ${today}`, + labels: sh.labels, + long: sh.long, + series: sh.tasks, + unit: "finished", + partial: true, + }), + ); + } + out.push(h("p", { class: "meta" }, `Days are UTC days.${doc.history.readAt ? ` GitHub's history was last read ${app.ago(doc.history.readAt)}.` : ""}`)); + return out; +} + +export default { + route: "more/trends", + title: "Trends", + group: "Plan", + says: "merged, features by project, issues and tasks, day by day", + view, +}; diff --git a/pm-stack/console/public/themes.css b/pm-stack/console/public/themes.css index 64ecbbd162..a7bf4cf291 100644 --- a/pm-stack/console/public/themes.css +++ b/pm-stack/console/public/themes.css @@ -564,3 +564,24 @@ --bad: #b00020; --bad-ink: #ffffff; } + +/* ---- what a chart tells its series apart by --------------------------- */ +/* A set for a dark theme and a set for a light one (look.js says which + the chosen theme is). The same six hues in the same order, each + stepped for its page. */ +[data-scheme="dark"] { + --series-1: #3987e5; + --series-2: #d95926; + --series-3: #199e70; + --series-4: #c98500; + --series-5: #d55181; + --series-6: #0ca30c; +} +[data-scheme="light"] { + --series-1: #2a78d6; + --series-2: #eb6834; + --series-3: #1baf7a; + --series-4: #eda100; + --series-5: #e87ba4; + --series-6: #008300; +} diff --git a/pm-stack/console/public/ui.js b/pm-stack/console/public/ui.js new file mode 100644 index 0000000000..585badd139 --- /dev/null +++ b/pm-stack/console/public/ui.js @@ -0,0 +1,44 @@ +// The two things every screen is built with: an element, and a drawn +// (SVG) element. A screen is a list of elements made with these and the +// app's classes (app.css), so that one screen's card, chip, row or +// button is every other screen's. +// +// Nothing here writes a style: what an element looks like is its class. + +/** An element. `attrs` are its attributes: `class` is its classes, a + * name starting "on" is a listener, true is an attribute with no value, + * and false, null or undefined is no attribute. `kids` are elements or + * text, however nested; nothing (null, undefined, false) is left out. */ +export function h(tag, attrs, ...kids) { + const el = document.createElement(tag); + for (const [k, v] of Object.entries(attrs || {})) { + if (v === false || v === null || v === undefined) continue; + if (k.startsWith("on")) el.addEventListener(k.slice(2), v); + else if (k === "class") el.className = v; + else if (v === true) el.setAttribute(k, ""); + else el.setAttribute(k, v); + } + for (const kid of kids.flat(Infinity)) { + if (kid === null || kid === undefined || kid === false) continue; + el.append(kid.nodeType ? kid : document.createTextNode(String(kid))); + } + return el; +} + +const SVG = "http://www.w3.org/2000/svg"; + +/** A drawn element (svg, g, rect, path, line, text…), made the same + * way. Numbers are written to two places, which is finer than a screen. */ +export function s(tag, attrs, ...kids) { + const el = document.createElementNS(SVG, tag); + for (const [k, v] of Object.entries(attrs || {})) { + if (v === false || v === null || v === undefined) continue; + if (k.startsWith("on")) el.addEventListener(k.slice(2), v); + else el.setAttribute(k, typeof v === "number" ? String(Math.round(v * 100) / 100) : v === true ? "" : v); + } + for (const kid of kids.flat(Infinity)) { + if (kid === null || kid === undefined || kid === false) continue; + el.append(kid.nodeType ? kid : document.createTextNode(String(kid))); + } + return el; +} diff --git a/pm-stack/console/scripts/edge-smoke.ts b/pm-stack/console/scripts/edge-smoke.ts index ee0d1aea5f..6af674774e 100644 --- a/pm-stack/console/scripts/edge-smoke.ts +++ b/pm-stack/console/scripts/edge-smoke.ts @@ -155,6 +155,8 @@ deps.link = link; const seen: string[] = []; /** What reached the stand-ins for GitHub and the queue store, and with * what: the Worker's own reads, made in its runtime. */ +/** How often the history behind the Trends screen was asked of GitHub. */ +const historyAsked = { n: 0 }; const outside: { to: "github" | "queue"; path: string; @@ -279,6 +281,30 @@ const server = Bun.serve({ }, ]); } + if ( + path === "repos/developing-today/code/issues" && + url.searchParams.get("state") === "all" && + url.searchParams.has("since") + ) { + // Everything changed at or after a time, oldest change first: + // what the history behind the Trends screen asks. One feature + // merged an hour ago. + historyAsked.n++; + const at = new Date(Date.now() - 3_600_000).toISOString().replace(/\.\d+Z$/, "Z"); + const all = [ + { + number: 43, + title: "feat(pm-stack): a smoke feature", + created_at: at, + updated_at: at, + closed_at: at, + state: "closed", + labels: [], + pull_request: { merged_at: at }, + }, + ]; + return Response.json(all.filter((item) => item.updated_at >= (url.searchParams.get("since") ?? ""))); + } if (path === "repos/developing-today/code/issues" && url.searchParams.get("state") === "closed") { // What GitHub lists as closed: a pull request merged an hour ago // and an issue closed two hours ago, as it sends them. @@ -525,8 +551,47 @@ try { appFiles.files.length > 20 && wrong.length === 0, wrong.join("; "), ); + const unlisted = await asOwner("/console/fonts/licences/inter.txt"); check("a file the list does not name is not served", unlisted.status !== 200, String(unlisted.status)); + + // Trends: the Worker reads GitHub's history and the queue's store + // itself, keeps what it read in its own storage, and answers from + // that. Only this runtime has that storage and that fetch. + const trendsRes = await asOwner("/console/api/trends?days=7"); + const trends = (await trendsRes.json()) as { + window?: number; + days?: string[]; + history?: { whole: boolean }; + merged?: { all: number[]; kinds: { feat: number[] } }; + features?: { latest: Record }; + tasks?: { all?: number[] }; + }; + const sumOf = (list: number[] | undefined) => (list ?? []).reduce((total, n) => total + n, 0); + check( + "Trends is read by the Worker itself: GitHub's history a page at a time, the queue's finished tasks, by day", + trendsRes.status === 200 && + trends.window === 7 && + trends.days?.length === 14 && + trends.history?.whole === true && + sumOf(trends.merged?.all) === 1 && + sumOf(trends.merged?.kinds.feat) === 1 && + trends.features?.latest["pm-stack"]?.[0]?.number === 43 && + trends.features?.latest["pm-stack"]?.[0]?.title === "a smoke feature" && + Array.isArray(trends.tasks?.all), + JSON.stringify(trends).slice(0, 300), + ); + const askedOnce = historyAsked.n; + const trendsAgain = await asOwner("/console/api/trends?days=30"); + const again30 = (await trendsAgain.json()) as { window?: number; merged?: { all: number[] } }; + check( + "asked again at once it answers from what it kept: GitHub is not asked a second time", + trendsAgain.status === 200 && + again30.window === 30 && + sumOf(again30.merged?.all) === 1 && + historyAsked.n === askedOnce, + `asked GitHub ${historyAsked.n} time(s)`, + ); const onceId = "11111111-1111-4111-8111-111111111111"; const didFirst = (await (await actAsOwner("push.class", { class: "trouble", on: false }, onceId)).json()) as { result?: Record; diff --git a/pm-stack/console/src/reads.ts b/pm-stack/console/src/reads.ts index 33adfd225f..c19b043bea 100644 --- a/pm-stack/console/src/reads.ts +++ b/pm-stack/console/src/reads.ts @@ -7,10 +7,17 @@ // agents, the dashboard's questions) is not here, and is asked of one. import type { Ops } from "./ops.ts"; import type { Plan } from "./plan.ts"; +import type { Trends } from "./trends.ts"; /** The answer to `GET /console/api/`, or undefined when that is * not one of these reads. */ -export async function platformRead(seg: string[], query: URLSearchParams, ops: Ops, plan: Plan): Promise { +export async function platformRead( + seg: string[], + query: URLSearchParams, + ops: Ops, + plan: Plan, + trends?: Trends, +): Promise { // `fresh=1` is the reader pressing refresh: asked again now, not // answered from the last minute's read. const fresh = query.get("fresh") === "1"; @@ -37,6 +44,8 @@ export async function platformRead(seg: string[], query: URLSearchParams, ops: O return plan.bugs(fresh); case "intake": return plan.intakeList(fresh); + case "trends": + return trends ? trends.read(query.get("days"), fresh) : undefined; } } if (seg.length === 2 && seg[0] === "prs") return ops.pr(seg[1]); diff --git a/pm-stack/console/src/server.ts b/pm-stack/console/src/server.ts index 26f7b45988..71e953627a 100644 --- a/pm-stack/console/src/server.ts +++ b/pm-stack/console/src/server.ts @@ -42,6 +42,7 @@ import { platformRead } from "./reads.ts"; import { contact, Push } from "./push.ts"; import { Named } from "./named.ts"; import { EdgeLink } from "./sync.ts"; +import { memoryShelf, Trends } from "./trends.ts"; import { Work } from "./work.ts"; import appFiles from "../public/files.json"; @@ -106,6 +107,18 @@ function file(req: Request, name: string, type: string): Response { export { assetLinks, type Phones }; +/** The history behind the Trends screen, for these dependencies: made + * once and kept (in memory: a machine reads it again when it starts). */ +const trendsKept = new WeakMap(); +function trendsOf(deps: Deps): Trends { + let trends = trendsKept.get(deps); + if (!trends) { + trends = new Trends(deps.ops, memoryShelf()); + trendsKept.set(deps, trends); + } + return trends; +} + /** The plan's reader for these dependencies: the one given, or one made * from the same `ops` and `work` and kept. */ const plans = new WeakMap(); @@ -317,7 +330,7 @@ export async function handle(req: Request, deps: Deps, peer: string | null = nul } // What needs only GitHub and the queue store: the same code // answers these at the edge without this machine. - const read = await platformRead(seg, query, ops, planOf(deps)); + const read = await platformRead(seg, query, ops, planOf(deps), trendsOf(deps)); if (read !== undefined) return json(read); if (seg.length === 2 && seg[0] === "doc" && deps.docs && DOC_NAMES.includes(seg[1] as DocName)) { return docResponse(req, await deps.docs.doc(seg[1] as DocName), gzipped); diff --git a/pm-stack/console/src/trends.ts b/pm-stack/console/src/trends.ts new file mode 100644 index 0000000000..259878b51b --- /dev/null +++ b/pm-stack/console/src/trends.ts @@ -0,0 +1,465 @@ +// Trends: what was opened, merged, closed and finished, day by day. +// +// Two sources, both read by whoever serves the app (Cloudflare, or a +// machine): GitHub for issues and pull requests, the queue store for +// tasks. Neither needs the other, and neither needs a machine. +// +// GitHub has no "how many merged each day" to ask for, so the history +// is read once and kept. GitHub's list of issues takes a time and +// answers with everything changed at or after it, oldest change first: +// read from ninety days back, a page at a time, each page's last change +// is where the next page starts. That is every issue and pull request +// touched since, each seen at least once in its present state, however +// they change while being read. Once the list has been read to its end +// it is kept up by asking from the same place again: only what changed +// since comes back. What is kept is small: per day, the numbers of what +// was opened and closed, and for a merged pull request what its title +// says it is. +// +// The queue store is asked each time: one read of the finishing events +// by day, which it has an index for. +import { OpError } from "./errors.ts"; +import type { Ops } from "./ops.ts"; + +/** Where the history is kept: texts under names. Cloudflare's own + * storage there; memory on a machine (which reads it again when it + * starts, and is not what the app is served from). */ +export interface Shelf { + get(key: string): Promise; + put(key: string, text: string): Promise; +} + +export function memoryShelf(): Shelf & { keys: () => string[] } { + const kept = new Map(); + return { + get: async (key) => kept.get(key) ?? null, + put: async (key, text) => void kept.set(key, text), + keys: () => [...kept.keys()].sort(), + }; +} + +/** How far back the history goes. */ +export const HISTORY_DAYS = 90; +/** GitHub's largest page. */ +const PAGE = 100; +/** How many pages one read of the screen waits for. The rest is read + * in the background (Cloudflare's own clock) or by the next read. */ +export const PAGES_A_READ = 3; +/** History read to its end is asked about again after this long. */ +export const FRESH_FOR_MS = 5 * 60_000; +/** The windows the screen offers, in days. */ +export const WINDOWS = [7, 14, 30, 90] as const; +const TITLE_CHARS = 110; +/** How many of a project's latest features are listed. */ +const FEATURES_LISTED = 12; +/** How many kinds of task get a series of their own. */ +const TASK_KINDS = 5; + +/** What a merged pull request is, by the first word of its title. */ +export const KINDS = ["feat", "fix", "docs", "test", "other"] as const; +export type Kind = (typeof KINDS)[number]; +const CONVENTIONAL: Record = { + feat: "feat", + feature: "feat", + fix: "fix", + bugfix: "fix", + hotfix: "fix", + docs: "docs", + doc: "docs", + test: "test", + tests: "test", + chore: "other", + refactor: "other", + perf: "other", + ci: "other", + build: "other", + style: "other", + revert: "other", +}; + +/** The projects a pull request is counted under, by its title's scope. + * The first four are the capabilities the plan is kept by; a scope none + * of these claims is "other". The order is the order they are shown + * and coloured in, and it does not change with what is in the window. */ +export const PROJECTS: { id: string; title: string; scope: RegExp }[] = [ + { id: "id", title: "id", scope: /^(id|id[-/].+|pkgs\/id.*)$/ }, + { + id: "fleet", + title: "Fleet", + scope: /^(fleet|fleet[-/].+|queue|queue[-/].+|claimant|laptop-agent|opencode.*|lane|lanes|babysitter|route.*)$/, + }, + { id: "atlas", title: "Atlas", scope: /^atlas([-/].+)?$/ }, + { id: "pm-stack", title: "PM stack", scope: /^(pm|pm[-/].+|aggregator|console|android|dashboard)$/ }, + { id: "mcpx", title: "mcpx", scope: /^mcpx([-/].+)?$/ }, + { id: "other", title: "Everything else", scope: /^/ }, +]; + +/** A title in parts: `feat(pm-stack): the words` is a feature of + * pm-stack; `id-pg: the words` names its scope and not its kind; a + * title that is only words is neither. Two kinds joined (`test+docs`) + * is the first. */ +export function titleParts(title: string): { kind: Kind; scope: string; words: string } { + const text = String(title ?? "").trim(); + const typed = /^([A-Za-z]+)(?:\+[A-Za-z]+)*(?:\(([^)]*)\))?!?:\s+(.*)$/s.exec(text); + if (typed && Object.hasOwn(CONVENTIONAL, typed[1].toLowerCase())) { + return { + kind: CONVENTIONAL[typed[1].toLowerCase()], + scope: (typed[2] ?? "").trim().toLowerCase(), + words: typed[3], + }; + } + const scoped = /^([A-Za-z0-9][A-Za-z0-9._/-]{0,39}):\s+(.*)$/s.exec(text); + if (scoped) return { kind: "other", scope: scoped[1].toLowerCase(), words: scoped[2] }; + return { kind: "other", scope: "", words: text }; +} + +/** The project a scope belongs to. */ +export function projectOf(scope: string): string { + const s = scope.trim().toLowerCase(); + if (s === "") return "other"; + return (PROJECTS.find((p) => p.scope.test(s)) ?? PROJECTS[PROJECTS.length - 1]).id; +} + +/** A merged pull request as kept: what it is, whose it is, how long it + * was open in minutes, the time of day it merged, and its words (kept + * for a feature only: those are the ones listed). */ +type Merged = [kind: Kind, project: string, minutes: number, at: string, words?: string]; +/** A day as kept: the numbers of the issues and pull requests opened + * and closed on it (a number is in a list once, however often its issue + * is read), and the pull requests merged on it. */ +export interface Day { + io: number[]; + ic: number[]; + bo: number[]; + bc: number[]; + po: number[]; + px: number[]; + pm: Record; +} +const emptyDay = (): Day => ({ io: [], ic: [], bo: [], bc: [], po: [], px: [], pm: {} }); + +interface Meta { + /** The first day the history covers. */ + from: string; + /** Everything changed before this has been read. */ + cursor: string; + /** The list has been read to its end at least once. */ + whole: boolean; + /** When it was last read to its end. */ + readAt: string | null; +} + +/** An issue or a pull request, as GitHub's list of issues gives it. */ +interface Item { + number: number; + title?: string; + created_at?: string; + updated_at?: string; + closed_at?: string | null; + state?: string; + labels?: ({ name?: string } | string)[]; + pull_request?: { merged_at?: string | null } | null; +} + +const dayOf = (iso: string) => iso.slice(0, 10); +const add = (list: number[], n: number) => { + if (!list.includes(n)) list.push(n); +}; +const isBug = (item: Item) => + (item.labels ?? []).some((l) => ["kind/bug", "bug"].includes(typeof l === "string" ? l : (l.name ?? ""))); + +/** One item put into the days it belongs to. `day` gives the day to + * write on. Reading the same item again changes nothing; reading it + * after it changed adds what is new. An issue closed, opened again and + * closed on a later day stays counted on the first as well: what was + * true of a day is not taken back. */ +export function fold(item: Item, from: string, day: (date: string) => Day): void { + const n = Number(item.number); + if (!Number.isInteger(n) || n <= 0) return; + const pr = item.pull_request !== undefined && item.pull_request !== null; + const created = item.created_at ?? ""; + if (created && dayOf(created) >= from) { + add(pr ? day(dayOf(created)).po : day(dayOf(created)).io, n); + if (!pr && isBug(item)) add(day(dayOf(created)).bo, n); + } + const merged = pr ? (item.pull_request?.merged_at ?? null) : null; + if (merged) { + if (dayOf(merged) < from) return; + const parts = titleParts(item.title ?? ""); + const minutes = created ? Math.max(0, Math.round((Date.parse(merged) - Date.parse(created)) / 60_000)) : 0; + const record: Merged = [parts.kind, projectOf(parts.scope), minutes, merged.slice(11, 16)]; + if (parts.kind === "feat") record.push(parts.words.slice(0, TITLE_CHARS)); + day(dayOf(merged)).pm[String(n)] = record; + return; + } + const closed = item.state === "closed" ? (item.closed_at ?? null) : null; + if (!closed || dayOf(closed) < from) return; + if (pr) add(day(dayOf(closed)).px, n); + else { + add(day(dayOf(closed)).ic, n); + if (isBug(item)) add(day(dayOf(closed)).bc, n); + } +} + +/** The middle of some numbers, or null of none. */ +export function median(values: number[]): number | null { + if (values.length === 0) return null; + const sorted = [...values].sort((a, b) => a - b); + const mid = Math.floor(sorted.length / 2); + return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2; +} + +/** The days of a window ending today, oldest first, as UTC dates. */ +export function daysBack(today: string, count: number): string[] { + const end = Date.parse(`${today}T00:00:00Z`); + return Array.from({ length: count }, (_, i) => + new Date(end - (count - 1 - i) * 86_400_000).toISOString().slice(0, 10), + ); +} + +const P = "CASE WHEN json_valid(t.payload) THEN t.payload ELSE '{}' END"; +/** Tasks finished, by the day of their last finishing and their kind: + * each task once, and only while it still stands as done. The same + * events, by the same index, as the Done screen counts (src/work.ts). */ +export const TASKS_BY_DAY_SQL = `SELECT day, kind, count(*) AS n FROM ( + SELECT t.id AS id, substr(max(e.created_at),1,10) AS day, coalesce(json_extract(${P},'$.kind'),'') AS kind + FROM events e CROSS JOIN tasks t ON t.id = e.task_id + WHERE e.kind IN ('completed','staleness_autocomplete') AND e.created_at >= ? AND t.queue = ? AND t.status = 'done' + GROUP BY t.id +) GROUP BY day, kind ORDER BY day ASC, n DESC, kind ASC`; + +export interface TrendsDoc { + /** The window asked for, in days; `days` covers twice that (or all + * there is), so the window can be set against the one before it. */ + window: number; + days: string[]; + today: string; + history: { from: string; whole: boolean; readTo: string; readAt: string | null }; + projects: { id: string; title: string }[]; + merged: { + all: number[]; + kinds: Record; + projects: Record; + /** The middle time from opening to merging, in minutes; null on a day nothing merged. */ + minutes: (number | null)[]; + }; + features: { + projects: Record; + latest: Record; + }; + issues: { opened: number[]; closed: number[] }; + bugs: { opened: number[]; closed: number[] }; + prs: { opened: number[]; closed: number[] }; + tasks: { all: number[]; kinds: { kind: string; days: number[] }[]; since: string | null } | { error: string }; + /** Something could not be read just now: what is shown is what was kept. */ + partial?: boolean; + why?: string; +} + +export class Trends { + private reading: Promise | null = null; + + constructor( + private ops: Ops, + private shelf: Shelf, + private clock: () => Date = () => new Date(), + ) {} + + private get repo(): string { + return this.ops.cfg.repo; + } + + private async meta(): Promise { + const text = await this.shelf.get("meta"); + if (text) { + try { + const m = JSON.parse(text) as Meta; + if (typeof m.from === "string" && typeof m.cursor === "string") { + return { from: m.from, cursor: m.cursor, whole: m.whole === true, readAt: m.readAt ?? null }; + } + } catch { + // Not what was written: start again. + } + } + const from = new Date(this.clock().getTime() - HISTORY_DAYS * 86_400_000).toISOString().slice(0, 10); + return { from, cursor: `${from}T00:00:00Z`, whole: false, readAt: null }; + } + + private async day(date: string): Promise { + const text = await this.shelf.get(`day:${date}`); + if (!text) return emptyDay(); + try { + return { ...emptyDay(), ...(JSON.parse(text) as Partial) }; + } catch { + return emptyDay(); + } + } + + /** When the history next wants reading on: now (0) while it has not + * been read to its end, otherwise `every` after it last was. */ + async dueAt(every = FRESH_FOR_MS): Promise { + const m = await this.meta(); + return m.whole && m.readAt !== null ? Date.parse(m.readAt) + every : 0; + } + + /** Whether the history wants reading on: it has not been read to its + * end, or that was a while ago. */ + async due(staleMs = FRESH_FOR_MS): Promise { + return this.clock().getTime() >= (await this.dueAt(staleMs)); + } + + /** Read on from where the last read stopped, at most `pages` pages. + * One at a time: a second caller waits for the first and gets what it + * got. A page that could not be read stops it where it is, with + * everything before that kept. */ + advance(pages = PAGES_A_READ): Promise { + if (!this.reading) { + this.reading = this.readOn(pages).finally(() => { + this.reading = null; + }); + } + return this.reading; + } + + private async readOn(pages: number): Promise { + const meta = await this.meta(); + const open = new Map(); + const touched = new Set(); + const save = async () => { + for (const date of touched) await this.shelf.put(`day:${date}`, JSON.stringify(open.get(date))); + touched.clear(); + await this.shelf.put("meta", JSON.stringify(meta)); + }; + try { + for (let page = 0; page < pages; page++) { + const path = `repos/${this.repo}/issues?state=all&sort=updated&direction=asc&since=${meta.cursor}&per_page=${PAGE}`; + const items = (await this.ops.gh([path])) as Item[] | null; + if (!Array.isArray(items)) throw new OpError(502, "GitHub's list of issues was not a list"); + // The days this page writes on, read first. + const dates = new Set(); + for (const item of items) fold(item, meta.from, (date) => (dates.add(date), emptyDay())); + for (const date of dates) if (!open.has(date)) open.set(date, await this.day(date)); + for (const item of items) { + fold(item, meta.from, (date) => { + touched.add(date); + return open.get(date) as Day; + }); + } + const last = items.length > 0 ? (items[items.length - 1].updated_at ?? "") : ""; + if (items.length < PAGE) { + // The end of the list: everything changed up to now is read. + if (last > meta.cursor) meta.cursor = last; + meta.whole = true; + meta.readAt = this.clock().toISOString(); + break; + } + // A whole page that ends where it began (a hundred things + // changed in one second) would be read for ever: step past it. + meta.cursor = + last > meta.cursor ? last : new Date(Date.parse(meta.cursor) + 1000).toISOString().replace(".000Z", "Z"); + await save(); + } + } finally { + // What was read before a failure is kept. + await save(); + } + return meta; + } + + /** The document the Trends screen draws: `window` days, set against + * the same number before them. */ + async read(asked: string | null, fresh = false): Promise { + const window = (WINDOWS as readonly number[]).includes(Number(asked)) ? Number(asked) : 30; + let why: string | undefined; + if (fresh || (await this.due())) { + try { + await this.advance(); + } catch (error) { + why = `GitHub's history could not be read on: ${(error as Error).message}`; + } + } + const meta = await this.meta(); + const today = this.clock().toISOString().slice(0, 10); + const days = daysBack(today, Math.min(window * 2, HISTORY_DAYS)).filter((d) => d >= meta.from); + const kept = await Promise.all(days.map((d) => this.day(d))); + const zeros = () => days.map(() => 0); + const kinds = Object.fromEntries(KINDS.map((k) => [k, zeros()])) as Record; + const projects = Object.fromEntries(PROJECTS.map((p) => [p.id, zeros()])); + const featured = Object.fromEntries(PROJECTS.map((p) => [p.id, zeros()])); + const latest: TrendsDoc["features"]["latest"] = Object.fromEntries(PROJECTS.map((p) => [p.id, []])); + const minutes: (number | null)[] = []; + const inWindow = days.length - Math.min(window, days.length); + kept.forEach((day, i) => { + const merged = Object.entries(day.pm); + minutes.push(median(merged.map(([, m]) => m[2]))); + for (const [number, [kind, project, , at, words]] of merged) { + kinds[KINDS.includes(kind) ? kind : "other"][i]++; + const p = Object.hasOwn(projects, project) ? project : "other"; + projects[p][i]++; + if (kind !== "feat") continue; + featured[p][i]++; + if (i >= inWindow) { + latest[p].push({ + number: Number(number), + title: words ?? "", + at: `${days[i]}T${at}:00Z`, + url: `https://github.com/${this.repo}/pull/${number}`, + }); + } + } + }); + for (const list of Object.values(latest)) { + list.sort((a, b) => (a.at < b.at ? 1 : a.at > b.at ? -1 : b.number - a.number)); + list.length = Math.min(list.length, FEATURES_LISTED); + } + let tasks: TrendsDoc["tasks"]; + try { + const rows = (await this.ops.sql(TASKS_BY_DAY_SQL, [`${days[0] ?? today}T00:00:00Z`, this.ops.cfg.queue])) as { + day: string; + kind: string; + n: number; + }[]; + const at = new Map(days.map((d, i) => [d, i])); + const totals = new Map(); + for (const r of rows) totals.set(r.kind, (totals.get(r.kind) ?? 0) + Number(r.n)); + const named = [...totals.entries()] + .filter(([kind]) => kind !== "") + .sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)) + .slice(0, TASK_KINDS) + .map(([kind]) => kind); + const series = new Map([...named, "other"].map((kind) => [kind, zeros()])); + const all = zeros(); + for (const r of rows) { + const i = at.get(r.day); + if (i === undefined) continue; + all[i] += Number(r.n); + (series.get(named.includes(r.kind) ? r.kind : "other") as number[])[i] += Number(r.n); + } + tasks = { + all, + kinds: [...series.entries()] + .filter(([, list]) => list.some((n) => n > 0)) + .map(([kind, list]) => ({ kind, days: list })), + since: rows.length > 0 ? rows[0].day : null, + }; + } catch (error) { + tasks = { error: (error as Error).message }; + why = why ?? `The queue's finished tasks could not be read: ${(error as Error).message}`; + } + const count = (pick: (day: Day) => number[]) => kept.map((day) => pick(day).length); + return { + window, + days, + today, + history: { from: meta.from, whole: meta.whole, readTo: meta.cursor, readAt: meta.readAt }, + projects: PROJECTS.map(({ id, title }) => ({ id, title })), + merged: { all: kept.map((day) => Object.keys(day.pm).length), kinds, projects, minutes }, + features: { projects: featured, latest }, + issues: { opened: count((d) => d.io), closed: count((d) => d.ic) }, + bugs: { opened: count((d) => d.bo), closed: count((d) => d.bc) }, + prs: { opened: count((d) => d.po), closed: count((d) => d.px) }, + tasks, + ...(why === undefined ? {} : { partial: true, why }), + }; + } +} diff --git a/pm-stack/console/test/charts.test.ts b/pm-stack/console/test/charts.test.ts new file mode 100644 index 0000000000..d6406778e7 --- /dev/null +++ b/pm-stack/console/test/charts.test.ts @@ -0,0 +1,424 @@ +// The charts: their sums, and what they draw. +// +// Oracles: every number is worked out by hand in the comment beside it. +// What is drawn is read back from a stand-in page (test/dom.ts) that +// remembers elements, attributes and listeners; the rules it is held to +// are the ones written at the top of public/charts.js. That a browser +// draws it as meant was looked at in Chromium on the laptop, in a dark +// theme and a light one (see the design record). +import { expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { + compact, + dayLong, + dayShort, + deltaSaid, + groupsOf, + lineChart, + lineRuns, + minutesSaid, + niceMax, + placeAt, + rollUp, + stackedColumns, + stackGeometry, + statTiles, + windowTotals, +} from "../public/charts.js"; +import { type El, page } from "./dom.ts"; + +test("the top of a scale is the next clean number", () => { + for (const [value, top] of [ + [0, 1], + [-3, 1], + [1, 1], + [3, 5], + [7, 10], + [12, 20], + [23, 25], + [26, 50], + [99, 100], + [100, 100], + [101, 200], + [250, 250], + [0.4, 0.5], + [1288, 2000], + ]) { + expect([value, niceMax(value)]).toEqual([value, top]); + } +}); + +test("numbers, minutes and days as they are written", () => { + expect([0, 999, 1284, 9999, 12_940, 4_200_000, 2.5].map(compact)).toEqual([ + "0", + "999", + "1,284", + "9,999", + "12.9K", + "4.2M", + "2.5", + ]); + expect([compact(null), compact(undefined), compact(Number.NaN)]).toEqual(["–", "–", "–"]); + // 90 minutes is an hour and a half; 36 hours is a day and a half. + expect([45, 89, 90, 210, 2159, 2160, 14_400].map(minutesSaid)).toEqual([ + "45 min", + "89 min", + "1.5 h", + "3.5 h", + "36 h", + "1.5 d", + "10 d", + ]); + expect(minutesSaid(null)).toBe("–"); + // The 24th of November 2026 is a Tuesday; the 1st, a Sunday. + expect([dayShort("2026-11-24"), dayLong("2026-11-24"), dayLong("2026-11-01"), dayShort("2026-01-05")]).toEqual([ + "24 Nov", + "Tue 24 Nov", + "Sun 1 Nov", + "5 Jan", + ]); +}); + +test("days in groups counted back from the newest, and a series added up by them", () => { + expect(groupsOf(14, 7)).toEqual([ + [0, 7], + [7, 14], + ]); + // Ten days in sevens: the newest seven are whole, the oldest three are what is left. + expect(groupsOf(10, 7)).toEqual([ + [0, 3], + [3, 10], + ]); + expect(groupsOf(3, 1)).toEqual([ + [0, 1], + [1, 2], + [2, 3], + ]); + expect(groupsOf(0, 7)).toEqual([]); + expect( + rollUp( + [1, 2, 3, 4, 5], + [ + [0, 2], + [2, 5], + ], + ), + ).toEqual([3, 12]); + expect(rollUp([1, null, 3], [[0, 3]])).toEqual([4]); +}); + +test("a total and the one before it, and how one stands against the other", () => { + expect(windowTotals([1, 2, 3, 4], 2)).toEqual({ now: 7, before: 3 }); + // Three days cannot hold two before the last two. + expect(windowTotals([1, 2, 3], 2)).toEqual({ now: 5, before: null }); + expect(windowTotals([], 7)).toEqual({ now: 0, before: null }); + expect(deltaSaid(110, 100)).toEqual({ text: "▲ 10%", tone: "up" }); + expect(deltaSaid(90, 100)).toEqual({ text: "▼ 10%", tone: "down" }); + expect(deltaSaid(100, 100)).toEqual({ text: "level", tone: "" }); + // Under half a percent either way is level. + expect(deltaSaid(1004, 1000)).toEqual({ text: "level", tone: "" }); + expect(deltaSaid(5, 0)).toEqual({ text: "▲ from none", tone: "up" }); + expect(deltaSaid(0, 0)).toEqual({ text: "level", tone: "" }); + expect(deltaSaid(5, null)).toEqual({ text: "", tone: "" }); + expect(deltaSaid(0, 40)).toEqual({ text: "▼ 100%", tone: "down" }); +}); + +test("where the columns of a stack go, and how tall their parts are", () => { + const plot = { x: 0, y: 0, w: 100, h: 100 }; + // Two columns in 100: a band of 50 each; a column is 24 at most, so 13 in from its band's edge. + const g = stackGeometry( + [ + [10, 0], + [10, 20], + ], + 20, + plot, + ); + expect(g.band).toBe(50); + expect(g.columns.map((c) => [c.x, c.w, c.total])).toEqual([ + [13, 24, 20], + [63, 24, 20], + ]); + // First column: the bottom part is half the height (50) less the gap of 2 above it; the top part is its whole 50. + expect(g.columns[0].parts).toEqual([ + { series: 0, value: 10, y: 52, h: 48, top: false }, + { series: 1, value: 10, y: 0, h: 50, top: true }, + ]); + // Second column: one part, the whole height, and it is the top. + expect(g.columns[1].parts).toEqual([{ series: 1, value: 20, y: 0, h: 100, top: true }]); + // Something small beside something large is still there to see: at least 1 tall. + const small = stackGeometry([[1], [999]], 1000, plot).columns[0].parts[0]; + expect([small.h, small.y]).toEqual([1, 99]); + // Thirty columns in 320: each band 10.67, each column 8.67 (a gap of 2 between neighbours). + const thirty = stackGeometry([Array(30).fill(1)], 1, { x: 34, y: 10, w: 320, h: 128 }); + expect(Math.round(thirty.columns[0].w * 100) / 100).toBe(8.67); + expect(Math.round((thirty.columns[1].x - thirty.columns[0].x - thirty.columns[0].w) * 100) / 100).toBe(2); + // Nothing to draw is no columns, and a column of nothing has no parts. + expect(stackGeometry([], 1, plot).columns).toEqual([]); + expect(stackGeometry([[0]], 1, plot).columns[0].parts).toEqual([]); +}); + +test("the points of a line, broken where a day has no number", () => { + const plot = { x: 0, y: 0, w: 90, h: 100 }; + expect(lineRuns([0, 10, null, 5], 10, plot)).toEqual([ + [ + { i: 0, x: 0, y: 100 }, + { i: 1, x: 30, y: 0 }, + ], + [{ i: 3, x: 90, y: 50 }], + ]); + // One day sits in the middle; a number over the top of the scale is drawn at the top. + expect(lineRuns([5], 10, plot)).toEqual([[{ i: 0, x: 45, y: 50 }]]); + expect(lineRuns([20], 10, plot)[0][0].y).toBe(0); + expect(lineRuns([null, null], 10, plot)).toEqual([]); +}); + +test("which day a pointer is over", () => { + // The drawing is 360 across and its plot runs from 34 for 320. Half way across is 180: 146 into the plot. + // Ten columns of 32: 146 is in the fifth (place 4). + expect(placeAt(0.5, 10)).toBe(4); + // Ten points 35.6 apart: 146 is nearest the fifth (142). + expect(placeAt(0.5, 10, undefined, false)).toBe(4); + // Off either end is the first or the last, and no days is no place. + expect([placeAt(0, 10), placeAt(1, 10), placeAt(-1, 10), placeAt(2, 10)]).toEqual([0, 9, 0, 9]); + expect(placeAt(0.5, 0)).toBe(-1); + expect(placeAt(0.5, 1, undefined, false)).toBe(0); +}); + +const text = (el: El) => el.textContent.replace(/\s+/g, " ").trim(); + +test("stacked columns: a column a day, today fainter, a legend with totals, the numbers as a table, and each day said when chosen", () => { + page(); + const chart = stackedColumns({ + title: "Pull requests merged, by day", + note: "By what the title says each is.", + labels: ["22 Nov", "23 Nov", "24 Nov"], + long: ["Sun 22 Nov", "Mon 23 Nov", "Tue 24 Nov"], + series: [ + { name: "features", slot: 1, values: [3, 0, 2] }, + { name: "fixes", slot: 2, values: [1, 4, 0] }, + { name: "docs", slot: 3, values: [0, 0, 0] }, + { name: "everything else", slot: "other", values: [0, 1, 1] }, + ], + unit: "merged", + partial: true, + }) as unknown as El; + expect(chart.tag).toBe("figure"); + expect(text(chart.find("h3")[0])).toBe("Pull requests merged, by day"); + const columns = chart.find(".col"); + expect(columns.length).toBe(3); + expect(columns.map((c) => c.classList.contains("partial"))).toEqual([false, false, true]); + // Each part is drawn in its series' class and no other colour; the top of each column is the rounded one. + expect(columns[0].kids.map((k) => [(k as El).tag, (k as El).className])).toEqual([ + ["rect", "s1"], + ["path", "s2"], + ]); + expect(columns[2].kids.map((k) => [(k as El).tag, (k as El).className])).toEqual([ + ["rect", "s1"], + ["path", "so"], + ]); + // The scale: the tallest day is 5, so it runs 0, 2.5, 5. + expect(chart.find(".tick").map(text).slice(0, 3)).toEqual(["0", "2.5", "5"]); + // The series with nothing in it (docs) is not drawn, named or coloured; the others keep their own colours. + const legend = chart.find(".legend")[0]; + expect(legend.find("li").map(text)).toEqual(["features 5", "fixes 5", "everything else 2"]); + expect(legend.find(".sw").map((sw) => sw.className)).toEqual(["sw s1", "sw s2", "sw so"]); + // At rest the line under the title says the whole. + const readout = chart.find(".readout")[0]; + expect(text(readout)).toBe("12 merged"); + // The table has every number, and the total. + const rows = chart + .find("tbody")[0] + .find("tr") + .map((tr) => tr.kids.map((k) => text(k as El))); + expect(chart.find("thead")[0].find("th").map(text)).toEqual(["When", "features", "fixes", "everything else", "All"]); + expect(rows).toEqual([ + ["Sun 22 Nov", "3", "1", "0", "4"], + ["Mon 23 Nov", "0", "4", "1", "5"], + ["Tue 24 Nov", "2", "0", "1", "3"], + ]); + // Arrowing to a day says it: the number first, every series at once. Today is "so far". + const svg = chart.find("svg")[0]; + expect(svg.attrs.tabindex).toBe("0"); + expect(svg.attrs["aria-label"]).toBe( + "Pull requests merged, by day. 12 merged in all. The arrow keys read each column.", + ); + expect(svg.fire("keydown", { key: "ArrowRight" })).toBe(true); + expect(text(readout)).toBe("Sun 22 Nov · 4 3 features 1 fixes 0 everything else"); + expect(columns.map((c) => c.classList.contains("on"))).toEqual([true, false, false]); + expect(svg.classList.contains("choosing")).toBe(true); + svg.fire("keydown", { key: "End" }); + expect(text(readout)).toBe("Tue 24 Nov · 3 so far 2 features 0 fixes 1 everything else"); + svg.fire("keydown", { key: "ArrowRight" }); // already the last + expect(columns.map((c) => c.classList.contains("on"))).toEqual([false, false, true]); + svg.fire("keydown", { key: "ArrowLeft" }); + expect(text(readout).startsWith("Mon 23 Nov · 5")).toBe(true); + // A pointer two thirds across is over the second column of three; a finger lifted leaves it; a mouse moved off lets go. + svg.fire("pointermove", { clientX: 200 }); + expect(text(readout).startsWith("Mon 23 Nov")).toBe(true); + svg.fire("pointermove", { clientX: 40 }); + expect(text(readout).startsWith("Sun 22 Nov")).toBe(true); + svg.fire("pointerleave", { pointerType: "touch" }); + expect(text(readout).startsWith("Sun 22 Nov")).toBe(true); + svg.fire("pointerleave", { pointerType: "mouse" }); + expect(text(readout)).toBe("12 merged"); + expect(svg.classList.contains("choosing")).toBe(false); + // Another key is not taken from the page. + expect(svg.fire("keydown", { key: "Tab" })).toBe(false); + svg.fire("keydown", { key: "Home" }); + svg.fire("keydown", { key: "Escape" }); + expect(text(readout)).toBe("12 merged"); +}); + +test("one series needs no legend, and a chart of nothing still has its frame", () => { + page(); + const one = stackedColumns({ + title: "Tasks", + labels: ["a", "b"], + long: ["A", "B"], + series: [{ name: "finished", slot: 1, values: [2, 3] }], + unit: "finished", + }) as unknown as El; + expect(one.find(".legend")).toEqual([]); + expect(one.find("thead")[0].find("th").map(text)).toEqual(["When", "finished"]); + one.find("svg")[0].fire("keydown", { key: "Home" }); + expect(text(one.find(".readout")[0])).toBe("A · 2"); + const none = stackedColumns({ + title: "Nothing yet", + labels: ["a"], + long: ["A"], + series: [ + { name: "x", slot: 1, values: [0] }, + { name: "y", slot: 2, values: [0] }, + ], + unit: "merged", + }) as unknown as El; + expect(text(none.find(".readout")[0])).toBe("0 merged"); + expect(none.find(".col").length).toBe(1); + expect(none.find(".tick").map(text).slice(0, 3)).toEqual(["0", "0.5", "1"]); +}); + +test("lines: a legend for two, a wash and no legend for one, a dot that follows the day chosen, and gaps left as gaps", () => { + page(); + const two = lineChart({ + title: "Issues opened and closed, by day", + labels: ["22 Nov", "23 Nov", "24 Nov"], + long: ["Sun 22 Nov", "Mon 23 Nov", "Tue 24 Nov"], + series: [ + { name: "opened", slot: 2, values: [4, 2, 6], total: "12" }, + { name: "closed", slot: 1, values: [1, 5, 3], total: "9" }, + ], + }) as unknown as El; + expect(two.find(".legend")[0].find("li").map(text)).toEqual(["opened 12", "closed 9"]); + expect( + two + .find(".legend")[0] + .find(".sw") + .map((sw) => sw.className), + ).toEqual(["sw ln s2", "sw ln s1"]); + expect(two.find(".wash")).toEqual([]); + expect(two.find("path").map((p) => p.className)).toEqual(["ln s2", "ln s1"]); + const readout = two.find(".readout")[0]; + expect(text(readout)).toBe("3 days 12 opened 9 closed"); + const svg = two.find("svg")[0]; + // Each line ends on a dot ringed in the card's colour, on its last number: the scale tops out at 10, + // so 6 is 60% up a plot 128 tall from 138: y 61.2; 3 is at 99.6. Both at the right edge, 354. + const dots = two.find(".ring"); + expect(dots.map((d) => [d.attrs.cx, d.attrs.cy])).toEqual([ + ["354", "61.2"], + ["354", "99.6"], + ]); + svg.fire("keydown", { key: "Home" }); + expect(text(readout)).toBe("Sun 22 Nov 4 opened 1 closed"); + // The dots moved to the first day, at the plot's left edge, and the hairline with them. + expect(dots.map((d) => d.attrs.cx)).toEqual(["34", "34"]); + expect(two.find(".hair")[0].attrs.x1).toBe("34"); + svg.fire("blur"); + expect(text(readout)).toBe("3 days 12 opened 9 closed"); + expect(dots.map((d) => d.attrs.cx)).toEqual(["354", "354"]); + expect(Number(two.find(".hair")[0].attrs.x1)).toBeLessThan(0); + + const one = lineChart({ + title: "From opened to merged, by day", + labels: ["a", "b", "c", "d"], + long: ["A", "B", "C", "D"], + series: [{ name: "open to merged", slot: 1, values: [30, null, 90, 120], total: "1.5 h" }], + format: minutesSaid, + unit: "typically", + }) as unknown as El; + expect(one.find(".legend")).toEqual([]); + // The first day stands alone (a dot); the last two are a line with a wash under it. + expect(one.find(".wash").length).toBe(1); + expect(one.all((el) => el.tag === "circle" && !el.classList.contains("ring")).length).toBe(1); + expect(text(one.find(".readout")[0])).toBe("4 days 1.5 h typically"); + one.find("svg")[0].fire("keydown", { key: "ArrowRight" }); + expect(text(one.find(".readout")[0])).toBe("A 30 min typically"); + one.find("svg")[0].fire("keydown", { key: "ArrowRight" }); + // A day with no number says so, and the dot leaves the plot. + expect(text(one.find(".readout")[0])).toBe("B – typically"); + expect(Number(one.find(".ring")[0].attrs.cx)).toBeLessThan(0); + // The scale is written the way the numbers are. + expect(one.find(".tick").map(text).slice(0, 3)).toEqual(["0 min", "1.7 h", "3.3 h"]); + // The table too. + expect(one.find("tbody")[0].find("td").map(text)).toEqual(["30 min", "–", "1.5 h", "2 h"]); +}); + +test("the leading numbers: what each is, the number, how it stands, and the shape of its days", () => { + page(); + const tiles = statTiles([ + { + label: "Pull requests merged", + value: "2,930", + delta: { text: "▲ 12%", tone: "up" }, + against: "on the 7 days before", + spark: [1, 3, 2, 5], + }, + { + label: "Issues closed", + value: "40", + delta: { text: "▼ 8%", tone: "down" }, + against: "on the 7 days before", + spark: [2, 1], + }, + { label: "Tasks finished", value: "7", delta: { text: "", tone: "" }, against: "in 3 days", spark: [7] }, + ]) as unknown as El; + const each = tiles.find(".kpi"); + expect(each.map((t) => text(t))).toEqual([ + "Pull requests merged2,930▲ 12% on the 7 days before", + "Issues closed40▼ 8% on the 7 days before", + "Tasks finished7in 3 days", + ]); + // Up and down are said by the arrow and the figure; the class only adds the colour. + expect(each.map((t) => t.find(".kpi-delta")[0].className)).toEqual(["kpi-delta up", "kpi-delta down", "kpi-delta"]); + // A shape needs two days. + expect(each.map((t) => t.find("svg").length)).toEqual([1, 1, 0]); +}); + +test("a chart writes no colour and no style of its own: marks take a class, and the classes take the theme's series", () => { + const source = readFileSync(new URL("../public/charts.js", import.meta.url), "utf8"); + expect(source).not.toMatch(/#[0-9a-fA-F]{3,8}\b/); + expect(source).not.toMatch(/\.style\b|"style"|\bfill: |\bstroke: /); + const css = readFileSync(new URL("../public/app.css", import.meta.url), "utf8"); + const themes = readFileSync(new URL("../public/themes.css", import.meta.url), "utf8"); + for (let n = 1; n <= 6; n++) { + expect(css).toContain(`.s${n} {\n fill: var(--series-${n});`); + expect(css).toContain(`.ln.s${n} {\n stroke: var(--series-${n});`); + expect(css).toContain(`.sw.s${n} {\n background: var(--series-${n});`); + } + // "Everything else" is grey, in the theme's own. + expect(css).toContain(".so {\n fill: var(--quiet);"); + // The series colours: six, in the order they were checked in (blue, orange, aqua, yellow, magenta, + // green: neighbours told apart under every kind of colour vision), stepped for a dark page and a + // light one. The app's own :root has the same two sets as the themes' sheet. + const dark = ["#3987e5", "#d95926", "#199e70", "#c98500", "#d55181", "#0ca30c"]; + const light = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300"]; + const set = (text: string) => [...text.matchAll(/--series-(\d): (#[0-9a-f]{6});/g)].map((m) => m[2]); + const block = (text: string, from: string) => text.slice(text.indexOf(from), text.indexOf("}", text.indexOf(from))); + expect(set(block(themes, '[data-scheme="dark"]'))).toEqual(dark); + expect(set(block(themes, '[data-scheme="light"]'))).toEqual(light); + expect(set(block(css, ":root {"))).toEqual(dark); + expect(set(block(css.slice(css.indexOf("@media (prefers-color-scheme: light)")), ":root {"))).toEqual(light); + // They are not the status colours of any theme's... of the app's own two, at least. + for (const status of ["--good: #3fb950", "--warn: #d29922", "--bad: #f85149"]) expect(css).toContain(status); + expect(dark).not.toContain("#3fb950"); +}); diff --git a/pm-stack/console/test/console.test.ts b/pm-stack/console/test/console.test.ts index f803fcef5f..02da008153 100644 --- a/pm-stack/console/test/console.test.ts +++ b/pm-stack/console/test/console.test.ts @@ -1166,6 +1166,62 @@ describe("HTTP surface", () => { expect((await handle(get("/elsewhere"), alone)).status).toBe(404); }); + test("a machine answers Trends too, with the same reader, through the fleet binary; and it remembers what it read between asks", async () => { + // GitHub's list of issues as the fleet binary gives it: one pull request merged and one issue filed. + const r = recorder((argv) => { + if (argv[1] === "gh" && argv[3].includes("/issues?state=all&sort=updated&direction=asc&since=")) { + return JSON.stringify([ + { + number: 41, + title: "feat(fleet): a lane", + created_at: "2026-11-20T10:00:00Z", + updated_at: "2026-11-20T11:00:00Z", + closed_at: "2026-11-20T11:00:00Z", + state: "closed", + labels: [], + pull_request: { merged_at: "2026-11-20T11:00:00Z" }, + }, + { + number: 42, + title: "A bug", + created_at: "2026-11-21T10:00:00Z", + updated_at: "2026-11-21T10:00:00Z", + closed_at: null, + state: "open", + labels: [{ name: "kind/bug" }], + }, + ]); + } + return argv[1] === "secrets" ? "token\n" : "{}"; + }); + const d = deps("owner", r); + const res = await handle(get("/console/api/trends?days=90"), d); + expect(res.status).toBe(200); + const doc = (await res.json()) as { + window: number; + days: string[]; + history: { whole: boolean }; + merged: { all: number[]; projects: Record }; + bugs: { opened: number[] }; + features: { latest: Record }; + }; + expect([doc.window, doc.history.whole]).toEqual([90, true]); + const at = (day: string) => doc.days.indexOf(day); + // (The days end today, so these two are shown only while they are within ninety days of it.) + if (at("2026-11-20") >= 0) { + expect([doc.merged.all[at("2026-11-20")], doc.merged.projects.fleet[at("2026-11-20")]]).toEqual([1, 1]); + expect(doc.bugs.opened[at("2026-11-21")]).toBe(1); + expect(doc.features.latest.fleet.map((f) => f.number)).toEqual([41]); + } + const asked = () => r.calls.filter((c) => c.argv[1] === "gh" && c.argv[3].includes("since=")).length; + expect(asked()).toBe(1); + // Asked again at once, GitHub is not: the same reader is kept, with what it read. + expect((await handle(get("/console/api/trends?days=7"), d)).status).toBe(200); + expect(asked()).toBe(1); + // Not the owner: no trends. + expect((await handle(get("/console/api/trends"), deps(403, r))).status).toBe(403); + }); + test("the app's files are named in one list, and this service, the Worker's build and the page all go by it", async () => { // public/files.json is the one place a file of the app is named. // The oracle for "is everything there" is what the page and its @@ -1194,15 +1250,23 @@ describe("HTTP surface", () => { for (const m of read(`public/${sheet}`).matchAll(/url\("\/console\/([^"]+)"\)/g)) asked.add(m[1]); } for (const script of named.filter((n) => n.endsWith(".js"))) { + // What it imports is found from where it is: "./x.js" beside it, "../x.js" above. for (const m of read(`public/${script}`).matchAll( - /(?:^import [^"\n]*|importScripts\()"(?:\.\/|\/console\/)([^"]+)"/gm, + /(?:^import [^"\n]*|importScripts\()"(\.{1,2}\/[^"]+|\/console\/[^"]+)"/gm, )) - asked.add(m[1]); + asked.add(new URL(m[1], `https://pm.example/console/${script}`).pathname.replace("/console/", "")); } expect([...asked].filter((name) => !named.includes(name))).toEqual([]); // The page asks for its style sheets, the look, the outbox and the app (and the icon). for (const must of ["app.css", "themes.css", "look.css", "look.js", "outbox.js", "app.js", "icon.svg"]) expect([...asked]).toContain(must); + // And what the app's script imports, and what those import. + for (const must of ["ui.js", "pages/index.js", "pages/trends.js", "charts.js"]) expect([...asked]).toContain(must); + // A script the app imports is needed to open it: kept from the start. + for (const name of asked) { + if (name.endsWith(".js")) + expect([name, list.files.find((f) => f.path === name)?.kept]).toEqual([name, "installed"]); + } // Everything the page needs to open is kept from the start; a // typeface is kept when used; the worker itself never. const keptWhen = Object.fromEntries(list.files.map((f) => [f.path, f.kept])); diff --git a/pm-stack/console/test/direct.test.ts b/pm-stack/console/test/direct.test.ts index 0596694d3d..b223608b21 100644 --- a/pm-stack/console/test/direct.test.ts +++ b/pm-stack/console/test/direct.test.ts @@ -634,6 +634,27 @@ describe("what the edge remembers of GitHub", () => { expect(g.state.bodiless).toBe(0); }); + test("a question with a time in it is asked once and never the same again: its answer is not kept, and keeps nothing else out", async () => { + // The history behind the Trends screen asks "everything changed + // since