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

The map is a space: full screen, pan and pinch-zoom, semantic zoom from pillars to pulls, time as a dimension #10453

Parked opened this in answer to
Closed without merging

scout/forge:scout/10444-the-map-is-a-space-full-screen-pan-and-p → main 4 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +1175 −0
docs/design/audit.md +1
@@ -67,6 +67,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
6767 - `/pipeline` — `pages/pipeline.ts` · the four steps a change follows (check, review, land, live), for a newcomer · a pull page's step line, `/flow` · none seen.
6868 - `/packs` — `pages/packs.ts` · the premade forges this forge ships, what each brings, how to deploy it and how a stranger helps build its apps · the user menu, the signed-out menu, the palette · none seen; uses the shared card, list and button components.
6969 - `/map` — `pages/map.ts` (1,806 lines) · the dependency map of work across the forge · `/board`, issue dependency lists, `/:owner/:name/map` · colours 3, sizes 12: the largest private vocabulary.
70 - `/map/space` — `pages/space.ts` · the map as one full-screen canvas: pan, pinch, semantic zoom, a 7-day replay · the link on `/map` · none seen; its own full-screen controls, styles in the page.
7071 - `/audit` — `pages/audit.ts` · every app's contract, who can do what · the app page's one-line policy · none seen. Names the audit of apps, not this document.
7172 - `/repos` — `pages/my-repos.ts` · the repositories you may write, from the account menu · `/` (your apps), `/:owner` (a profile's repositories) · none seen.
7273 - `/releases` — `pages/releases.ts` · the forge's kept releases and rollback · `/settings/backups` (both are "go back") · none seen.
docs/features/map-space.md added +12
@@ -0,0 +1,12 @@
1 # The map as a space (`/map/space`)
2
3 The map, full screen: one canvas of every pillar and issue you can see, which you move through rather than read.
4
5 - **Move.** Drag (or one finger) to pan; wheel, pinch, `+`/`-` (also with ⌘/Ctrl) to zoom around the pointer; arrows pan; double-click zooms in. `0` or **Fit** shows everything; `N` or **Now** returns to the present. The view is in the address (`#x,y,zoom[,minutes-ago]`), so a link is a view. The page is `touch-action: none` and `overscroll-behavior: none`: nothing scrolls under the map.
6 - **Semantic zoom.** Out: each pillar is a region sized by its items, with its open count, a progress bar (landed this week) and ▲ when something landed in the last day. In: a region's items sit in four clusters named by state: waiting, building, in review, landed. Further in: each issue is a card with its number, title, its pull, and the crew member on it. Detail appears as you zoom; labels keep a readable size. Tap a region to fly into it, an issue for its links.
7 - **Time.** The slider replays the last 7 days: items appear when opened, move to *landed* when closed, and crew members move between the issues their runs were on. **Now** is live: any `issue.*`, `pull.*` or `run.*` event refetches the picture once it settles. A replay in the past is left alone.
8 - **Crew.** Scout, Mason, Torque (any agent with a run) are drawn on the issue they are working; tap one to see what they're on.
9
10 Regions are pillars (`core/pillars.ts`) where a repository has them, else the repository. "Building" is an issue with a running agent run; "in review" an issue an open pull closes (or an open pull that closes nothing); the rest of the open work is "waiting" (ready and blocked are not told apart here: the list map does that).
11
12 Data: `GET /api/v1/map/space`, columnar (`src/web/space_data.ts`): open issues and the week's closes, the week's agent runs. Drawing: one canvas, `src/web/space_client.ts` (no dependencies; the page ships the function's own source). Not drawn: checks per pull (the pull's number and link are), issues closed more than 7 days ago.
src/contract/openapi/routes/getApiV1MapSpace.ts added +3
@@ -0,0 +1,3 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = { method: "get", path: "/api/v1/map/space", summary: "The map as a space: every issue the caller can see by region, with the last seven days of times and crew runs, as columns", auth: false };
src/contract/openapi/routes/index.ts +1
@@ -92,6 +92,7 @@ export { route as getApiV1Health } from "./getApiV1Health.ts";
9292 export { route as getApiV1Here } from "./getApiV1Here.ts";
9393 export { route as getApiV1Keeper } from "./getApiV1Keeper.ts";
9494 export { route as getApiV1Map } from "./getApiV1Map.ts";
95 export { route as getApiV1MapSpace } from "./getApiV1MapSpace.ts";
9596 export { route as getApiV1MigrateJob } from "./getApiV1MigrateJob.ts";
9697 export { route as getApiV1MigrateJobStream } from "./getApiV1MigrateJobStream.ts";
9798 export { route as getApiV1OpenapiJson } from "./getApiV1OpenapiJson.ts";
src/http/api.ts +7
@@ -241,6 +241,7 @@ import {
241241 } from "../core/decisions.ts";
242242 import { forReader } from "../crew/handover.ts";
243243 import { globalMapJson } from "../web/pages/global-map.ts";
244 import { spaceJson } from "../web/pages/space.ts";
244245 import { mapJson, marksFor, withoutDone } from "../web/pages/map.ts";
245246 import { roadmapOf } from "../web/roadmap.ts";
246247 import { cachedMap } from "../web/map_snapshot.ts";
@@ -2425,6 +2426,12 @@ export function apiRoutes(router: Router<Handler>): void {
24252426 return timePhase(ctx.request, "render", () => json(graph));
24262427 });
24272428
2429 // The map as one space: items by region with times, for the full-screen view.
2430 router.add("GET", "/api/v1/map/space", (ctx) => {
2431 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
2432 return json(spaceJson(ctx.app, ctx.auth.user));
2433 });
2434
24282435 // The decision ledger: what the crew's decider answered and what came of
24292436 // it, newest first, with the week summed up per kind.
24302437 router.add("GET", "/api/v1/repos/:owner/:name/decisions", (ctx) => {
src/http/server.ts +2
@@ -229,6 +229,7 @@ import { tellPage } from "../web/studio/tell.ts";
229229 import { issuePicture } from "../web/studio/picture.ts";
230230 import { tellHerePage } from "../web/studio/tell_here.ts";
231231 import { globalMapPage } from "../web/pages/global-map.ts";
232 import { spacePage } from "../web/pages/space.ts";
232233 import { mapPage } from "../web/pages/map.ts";
233234 import { firstSubmit } from "../web/pages/first.ts";
234235 import { nextPage, nextSubmit } from "../web/pages/next.ts";
@@ -908,6 +909,7 @@ export function buildRouter(): Router<Handler> {
908909 router.add("GET", "/migrate/jobs/:job", migrationJobPage);
909910 // Every app on one canvas; a literal route, so it must sit above /:owner.
910911 router.add("GET", "/map", globalMapPage);
912 router.add("GET", "/map/space", spacePage);
911913 // The pipeline moved to a panel on /boards (#2774); the old address follows it. Literal, above /:owner.
912914 // /flow is the week's valves (#8698); a query string is an old pipeline drill, which went to /boards.
913915 router.add("GET", "/flow", flowPage);
src/web/pages/global-map.ts +4
@@ -314,6 +314,10 @@ export function globalMapPage(ctx: Ctx): Response {
314314 const body = html`${pageHead("Map", {
315315 sub: "Every app you can see, laid out by what waits for what. The top edge of each lane is ready now; a ringed card is where the crew is.",
316316 })}
317 <p class="small">
318 <a href="/map/space">Open the map as a space</a>: full screen, pan and
319 zoom from pillars to issues, and replay the week.
320 </p>
317321 ${nextThings(lanes)}
318322 <div id="lanes" data-live="${LIVE_KINDS}">
319323 ${lanes.length === 0
src/web/pages/space.ts added +131
@@ -0,0 +1,131 @@
1 /**
2 * GET /map/space — the map as a space you move through: the whole window is
3 * one canvas of every pillar and issue the viewer can see, panned and zoomed
4 * with finger, wheel or key, replayed over the last seven days with a
5 * scrubber. The first paint is server-rendered (the regions as a list, and
6 * the data inline), the drawing is `space_client.ts`'s. GET
7 * /api/v1/map/space is the same data, for the live refresh and for agents.
8 */
9
10 import type { App } from "../../app.ts";
11 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
12 import type { User } from "../../core/users.ts";
13 import type { Ctx } from "../../http/context.ts";
14 import { signInFirst } from "../chrome.ts";
15 import { liveRegionsJs } from "../client.ts";
16 import { html, raw } from "../html.ts";
17 import { page } from "../layout.ts";
18 import { inlineJson, spaceData, type SpaceData } from "../space_data.ts";
19 import { spaceClient } from "../space_client.ts";
20 import { LIVE_KINDS } from "./map.ts";
21
22 const css = `
23 html,body{overscroll-behavior:none;margin:0;background:var(--bg);color:var(--fg)}
24 .space{position:fixed;inset:0;overflow:hidden}
25 .space canvas{position:absolute;inset:0;width:100%;height:100%;touch-action:none;display:block;cursor:grab}
26 .space-bar{position:absolute;left:8px;right:8px;bottom:max(8px,env(safe-area-inset-bottom));display:flex;gap:8px;align-items:center;flex-wrap:wrap;background:var(--card);border:1px solid var(--border);border-radius:12px;padding:8px 10px}
27 .space-top{position:absolute;left:8px;top:max(8px,env(safe-area-inset-top));display:flex;gap:6px;align-items:center}
28 .space button,.space a.btn{font:inherit;font-size:14px;min-height:40px;min-width:40px;padding:0 12px;border-radius:10px;border:1px solid var(--border-strong);background:var(--card);color:var(--fg);text-decoration:none;display:inline-flex;align-items:center;justify-content:center;cursor:pointer}
29 .space button:focus-visible,.space a:focus-visible,.space input:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
30 .space-bar input[type=range]{flex:1;min-width:140px;min-height:40px}
31 .space-clock{min-width:64px;font-variant-numeric:tabular-nums;color:var(--muted-fg)}
32 .space-panel{position:absolute;right:8px;top:max(8px,env(safe-area-inset-top));max-width:min(340px,calc(100% - 16px));background:var(--card);border:1px solid var(--border-strong);border-radius:12px;padding:10px 12px;display:grid;gap:4px;font-size:14px}
33 .space-panel a{color:var(--accent)}
34 .space-panel[hidden]{display:none}
35 .space-regions{position:absolute;left:-9999px;width:1px;height:1px;overflow:hidden}
36 @media (prefers-reduced-motion:reduce){.space canvas{cursor:default}}
37 `;
38
39 const boot = `
40 (function(){
41 var root = document.getElementById('space');
42 var canvas = document.getElementById('space-canvas');
43 var data = JSON.parse(document.getElementById('space-data').textContent);
44 var ui = {
45 fit: document.getElementById('space-fit'), now: document.getElementById('space-now'),
46 zoomIn: document.getElementById('space-in'), zoomOut: document.getElementById('space-out'),
47 slider: document.getElementById('space-time'), play: document.getElementById('space-play'),
48 label: document.getElementById('space-clock'), panel: document.getElementById('space-panel')
49 };
50 var cs = getComputedStyle(document.documentElement);
51 function token(name) { return cs.getPropertyValue(name).trim(); }
52 var palette = { bg: token('--bg'), fg: token('--fg'), muted: token('--muted-fg'),
53 waiting: token('--muted-fg'), building: token('--attn'), review: token('--accent'), landed: token('--success') };
54 var api = spaceClient(canvas, data, {
55 palette: palette,
56 width: window.innerWidth, height: window.innerHeight, dpr: window.devicePixelRatio || 1,
57 hash: location.hash, ui: ui, win: window,
58 reload: function () {
59 return fetch('/api/v1/map/space', { credentials: 'same-origin', headers: { accept: 'application/json' } })
60 .then(function (r) { return r.ok ? r.json() : null; });
61 }
62 });
63 root.setAttribute('data-ready', '1');
64 window.__space = api;
65 })();
66 `;
67
68 /** The page's script: the client function's own source, then the boot. */
69 export const spaceScript = `${liveRegionsJs}\nvar spaceClient = ${spaceClient.toString()};\n${boot}`;
70
71 export function spacePage(ctx: Ctx): Response {
72 const viewer = ctx.auth.user;
73 if (!viewer) return signInFirst(ctx);
74 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
75 const started = performance.now();
76 const data = spaceData(ctx.app, viewer);
77 notePhase(ctx.request, "data", performance.now() - started);
78 const open = new Array<number>(data.regions.length).fill(0);
79 const landed = new Array<number>(data.regions.length).fill(0);
80 data.region.forEach((r, i) => {
81 if (data.state[i] === 3) landed[r] = (landed[r] ?? 0) + 1;
82 else open[r] = (open[r] ?? 0) + 1;
83 });
84 const body = html`<div
85 class="space"
86 id="space"
87 data-live="${LIVE_KINDS}"
88 role="application"
89 aria-label="The map as a space. Drag to pan, pinch or scroll to zoom, plus and minus to zoom, 0 to fit, N for now."
90 >
91 <canvas id="space-canvas"></canvas>
92 <nav class="space-regions" aria-label="Pillars">
93 <ul>
94 ${data.regions.map(
95 (r, i) => html`<li>${r.name}: ${open[i]} open, ${landed[i]} landed this week</li>`,
96 )}
97 </ul>
98 </nav>
99 <div class="space-top">
100 <a class="btn" href="/map" aria-label="Back to the list map">←</a>
101 <button type="button" id="space-fit" title="Fit everything (0)">Fit</button>
102 <button type="button" id="space-now" title="Back to now (N)">Now</button>
103 <button type="button" id="space-out" aria-label="Zoom out" title="Zoom out (-)">−</button>
104 <button type="button" id="space-in" aria-label="Zoom in" title="Zoom in (+)">+</button>
105 </div>
106 <div class="space-panel" id="space-panel" hidden></div>
107 <div class="space-bar">
108 <button type="button" id="space-play">Replay</button>
109 <input type="range" id="space-time" min="0" max="1000" value="1000" aria-label="Time: the last 7 days" />
110 <span class="space-clock" id="space-clock" aria-live="polite">now</span>
111 </div>
112 <script type="application/json" id="space-data">${raw(inlineJson(data))}</script>
113 </div>`;
114 const renderStart = performance.now();
115 const response = page({
116 ctx,
117 title: "Map space",
118 body,
119 bare: true,
120 theme: "dark",
121 styleCss: css,
122 scriptJs: spaceScript,
123 });
124 notePhase(ctx.request, "render", performance.now() - renderStart);
125 return response;
126 }
127
128 /** GET /api/v1/map/space. */
129 export function spaceJson(app: App, viewer: User | undefined): SpaceData {
130 return spaceData(app, viewer);
131 }
src/web/space_client.ts added +596
@@ -0,0 +1,596 @@
1 // @ts-nocheck -- browser source, shipped as text and typed by its tests, not by the compiler (arrays are indexed in hot loops).
2 /**
3 * The space's client: one self-contained function, served to the page as its
4 * source (`spaceClient.toString()`, see `pages/space.ts`) and run in a bun
5 * test against a stub canvas, so the first draw of the whole forge is
6 * measured with the real counts. It touches nothing outside its arguments:
7 * no imports, no module state.
8 *
9 * `data` is `SpaceData` (space_data.ts). `opts`: `width`, `height`, `dpr`;
10 * `view` (a parsed hash, or none for "fit"); `ui` and `win`, only when
11 * running in a page: the elements to bind and the window to listen on.
12 * Returns the parts a test (or the page's live channel) needs.
13 */
14 export function spaceClient(
15 canvas: any,
16 data0: any,
17 opts: any,
18 ): any {
19 const STATE_NAMES = ["waiting", "building", "review", "landed"];
20 const P = opts.palette || {};
21 // waiting, building, in review, landed: the page's own tokens (`--muted-fg`, `--attn`, `--accent`, `--success`).
22 const COLORS = [P.waiting, P.building, P.review, P.landed];
23 const CELL_W = 3;
24 const MAX_S = 400;
25 const MIN_S = 0.02;
26 let data = data0;
27 let width = opts.width;
28 let height = opts.height;
29 let dpr = opts.dpr || 1;
30 const ctx = canvas.getContext("2d");
31 const ui = opts.ui || {};
32 const win = opts.win;
33
34 // ---- the model: positions for the instant being shown -------------------
35 let regionsBox: any[] = [];
36 let X: Float32Array = new Float32Array(0);
37 let Y: Float32Array = new Float32Array(0);
38 let ST: Int8Array = new Int8Array(0);
39 let sums: any[] = [];
40 let crew: any[] = [];
41 let world = { x: 0, y: 0, w: 1, h: 1 };
42 let t = -1; // ms after `since`; -1 is live
43
44 function span() {
45 return Math.max(1, data.now - data.since);
46 }
47 function at() {
48 return t < 0 ? span() : t;
49 }
50
51 /** Regions packed in shelves, biggest first, sized by their items. */
52 function packRegions() {
53 const n = data.regions.length;
54 const total = new Array(n).fill(0);
55 for (let i = 0; i < data.region.length; i++) total[data.region[i]]++;
56 const g = 2;
57 const boxes: any[] = [];
58 for (let r = 0; r < n; r++) {
59 const N = Math.max(1, total[r]);
60 const c = Math.max(1, Math.ceil(Math.sqrt(N / CELL_W)));
61 const rows = Math.max(1, Math.ceil(N / c));
62 const qw = CELL_W * c;
63 boxes.push({
64 r, c, rows, qw, qh: rows, g, total: total[r],
65 w: 2 * qw + 3 * g, h: 3 + 2 * rows + 3 * g, x: 0, y: 0,
66 });
67 }
68 boxes.sort((a, b) => b.total - a.total || a.r - b.r);
69 let area = 0;
70 for (const b of boxes) area += (b.w + 6) * (b.h + 6);
71 const rowW = Math.max(boxes.length ? boxes[0].w : 1, Math.sqrt(area) * 1.3);
72 let x = 0, y = 0, rowH = 0, maxX = 0;
73 for (const b of boxes) {
74 if (x > 0 && x + b.w > rowW) { x = 0; y += rowH + 6; rowH = 0; }
75 b.x = x; b.y = y;
76 x += b.w + 6;
77 rowH = Math.max(rowH, b.h);
78 maxX = Math.max(maxX, x);
79 }
80 regionsBox = [];
81 for (const b of boxes) regionsBox[b.r] = b;
82 world = { x: -3, y: -3, w: Math.max(1, maxX) + 3, h: y + rowH + 6 };
83 }
84
85 /** Where each item is, and which state it is in, at the shown instant. */
86 function place() {
87 const n = data.title.length;
88 if (X.length !== n) { X = new Float32Array(n); Y = new Float32Array(n); ST = new Int8Array(n); }
89 const live = t < 0 || t >= span() - 1000;
90 const when = at();
91 const fill = new Int32Array(Math.max(1, regionsBox.length) * 4);
92 sums = regionsBox.map(() => ({ open: 0, landed: 0, recent: 0, counts: [0, 0, 0, 0] }));
93 const building = new Set<number>();
94 crew = [];
95 if (!live) {
96 for (const r of data.runs) if (r.from <= when && (r.to < 0 || r.to >= when)) building.add(r.item);
97 }
98 for (let i = 0; i < n; i++) {
99 let s = -1;
100 if (data.created[i] <= when) {
101 if (data.closed[i] >= 0 && data.closed[i] <= when) s = 3;
102 else if (live) s = data.state[i] === 3 ? 0 : data.state[i];
103 else s = building.has(i) ? 1 : data.pull[i] > 0 && data.state[i] === 2 ? 2 : 0;
104 }
105 ST[i] = s;
106 if (s < 0) continue;
107 const r = data.region[i];
108 const b = regionsBox[r];
109 const slot = fill[r * 4 + s]++;
110 const col = slot % b.c;
111 const row = (slot - col) / b.c;
112 X[i] = b.x + b.g + (s & 1) * (b.qw + b.g) + CELL_W * col;
113 Y[i] = b.y + 3 + b.g + (s >> 1) * (b.qh + b.g) + row;
114 const m = sums[r];
115 m.counts[s]++;
116 if (s === 3) {
117 m.landed++;
118 if (when - data.closed[i] < 86400000) m.recent++;
119 } else m.open++;
120 }
121 for (const r of data.runs) {
122 if (r.from <= when && (r.to < 0 ? live : r.to >= when) && ST[r.item] >= 0) {
123 if (!crew.some((c) => c.who === r.who)) crew.push({ who: r.who, item: r.item, summary: r.summary });
124 }
125 }
126 }
127
128 // ---- the view -----------------------------------------------------------
129 const view = { cx: 0, cy: 0, s: 1 };
130 function clampView() {
131 view.s = Math.min(MAX_S, Math.max(MIN_S, view.s));
132 view.cx = Math.min(world.x + world.w, Math.max(world.x, view.cx));
133 view.cy = Math.min(world.y + world.h, Math.max(world.y, view.cy));
134 }
135 function fitView() {
136 const pad = 24;
137 view.s = Math.min((width - pad * 2) / world.w, (height - pad * 2) / world.h);
138 view.cx = world.x + world.w / 2;
139 view.cy = world.y + world.h / 2;
140 clampView();
141 }
142 const sx = (wx: number) => (wx - view.cx) * view.s + width / 2;
143 const sy = (wy: number) => (wy - view.cy) * view.s + height / 2;
144 const wx = (px: number) => (px - width / 2) / view.s + view.cx;
145 const wy = (py: number) => (py - height / 2) / view.s + view.cy;
146
147 // ---- drawing ------------------------------------------------------------
148 function text(str: string, x: number, y: number, px: number, color: string, weight?: string) {
149 ctx.font = (weight || "400") + " " + px + "px system-ui, sans-serif";
150 ctx.fillStyle = color;
151 ctx.fillText(str, x, y);
152 }
153 function fit(str: string, px: number, avail: number) {
154 const max = Math.floor(avail / (px * 0.56));
155 if (max < 2) return "";
156 return str.length <= max ? str : str.slice(0, max - 1) + "…";
157 }
158 function wrap(str: string, px: number, avail: number, lines: number) {
159 const max = Math.max(4, Math.floor(avail / (px * 0.56)));
160 const out: string[] = [];
161 const words = str.split(" ");
162 let line = "";
163 for (const w of words) {
164 if (line && (line + " " + w).length > max) {
165 out.push(line); line = w;
166 if (out.length === lines - 1) break;
167 } else line = line ? line + " " + w : w;
168 }
169 const used = out.join(" ").length;
170 const rest = out.length === lines - 1 ? str.slice(used).trim() : line;
171 out.push(fit(rest, px, avail));
172 return out;
173 }
174
175 /** A translucent backing in the page's background colour, so text over cells stays readable. */
176 function back(paint: any, alpha: number) {
177 ctx.globalAlpha = alpha;
178 ctx.fillStyle = P.bg;
179 paint();
180 ctx.globalAlpha = 1;
181 }
182
183 let drawn = { cells: 0, level: 0 };
184 function level() {
185 return view.s < 1.4 ? 0 : view.s < 14 ? 1 : 2;
186 }
187
188 function draw() {
189 const W = width, H = height;
190 ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
191 ctx.fillStyle = P.bg;
192 ctx.fillRect(0, 0, W, H);
193 ctx.textBaseline = "top";
194 const lv = level();
195 const s = view.s;
196 // Regions; their headings are drawn last, over the cells.
197 const headers: any[] = [];
198 for (let r = 0; r < regionsBox.length; r++) {
199 const b = regionsBox[r];
200 if (!b) continue;
201 const x = sx(b.x), y = sy(b.y), w = b.w * s, h = b.h * s;
202 if (x > W || y > H || x + w < 0 || y + h < 0) continue;
203 const col = "#" + data.regions[r].color;
204 ctx.globalAlpha = lv === 0 ? 0.38 : 0.14;
205 ctx.fillStyle = col;
206 ctx.fillRect(x, y, w, h);
207 ctx.globalAlpha = 1;
208 ctx.strokeStyle = col;
209 ctx.lineWidth = 1;
210 ctx.strokeRect(x + 0.5, y + 0.5, w - 1, h - 1);
211 const m = sums[r];
212 const done = m.landed / Math.max(1, m.landed + m.open);
213 // The header stays a readable size: it is laid on the region's top edge.
214 const hp = Math.min(18, Math.max(11, 3 * s * 0.6));
215 const hh = Math.min(h, Math.max(hp * 2 + 12, 3 * s));
216 headers.push(() => {
217 if (w > 56) back(() => ctx.fillRect(x, y, w, hh), 0.55);
218 if (w > 56) {
219 text(fit(data.regions[r].name, hp, w - 12), x + 6, y + 5, hp, P.fg, "600");
220 if (hh > hp * 2 + 6) {
221 const long = w > 150;
222 const line = long
223 ? m.open + " open · " + m.landed + " landed" + (m.recent > 0 ? " ▲ moving" : " · still")
224 : m.open + " open" + (m.recent > 0 ? " ▲" : "");
225 text(fit(line, hp - 2, w - 12), x + 6, y + 7 + hp, hp - 2, P.muted);
226 }
227 // Progress.
228 ctx.fillStyle = P.muted;
229 ctx.globalAlpha = 0.35;
230 ctx.fillRect(x + 6, y + hh - 4, w - 12, 3);
231 ctx.globalAlpha = 1;
232 ctx.fillStyle = COLORS[3];
233 ctx.fillRect(x + 6, y + hh - 4, (w - 12) * done, 3);
234 }
235 if (w <= 56 && w >= 12) {
236 // Too narrow for the name: its first word (`P3`), on a backing, still readable.
237 const short = data.regions[r].name.split(" ")[0];
238 back(() => ctx.fillRect(x, y, Math.max(w, 24), 16), 0.8);
239 text(short, x + 3, y + 2, 11, P.fg, "600");
240 }
241 if (lv === 0 && w > 56 && h > 120) {
242 const big = Math.min(48, w / 4);
243 text(String(m.open), x + 6, y + hh + 6, big, P.fg, "700");
244 }
245 });
246 }
247 // Cells.
248 let cells = 0;
249 if (lv > 0 || s >= 0.8) {
250 const cw = CELL_W * s;
251 const gap = Math.min(1, cw * 0.15);
252 const n = data.title.length;
253 for (let k = 0; k < 4; k++) {
254 ctx.fillStyle = COLORS[k];
255 for (let i = 0; i < n; i++) {
256 if (ST[i] !== k) continue;
257 const x = sx(X[i]), y = sy(Y[i]);
258 if (x > W || y > H || x + cw < 0 || y + s < 0) continue;
259 cells++;
260 if (lv < 2) ctx.fillRect(x, y, Math.max(1, cw - gap), Math.max(1, s - gap));
261 else {
262 ctx.globalAlpha = 0.22;
263 ctx.fillRect(x + 1, y + 1, cw - 2, s - 2);
264 ctx.globalAlpha = 1;
265 ctx.fillRect(x + 1, y + 1, 3, s - 2);
266 }
267 }
268 }
269 // Quadrant labels.
270 if (lv >= 1) {
271 for (let r = 0; r < regionsBox.length; r++) {
272 const b = regionsBox[r];
273 if (!b || sx(b.x + b.w) < 0 || sx(b.x) > W || sy(b.y + b.h) < 0 || sy(b.y) > H) continue;
274 for (let k = 0; k < 4; k++) {
275 const qx = sx(b.x + b.g + (k & 1) * (b.qw + b.g));
276 const qy = sy(b.y + 3 + b.g + (k >> 1) * (b.qh + b.g));
277 if (b.qw * s < 70) continue;
278 const lp = Math.min(14, Math.max(10, s * 0.7));
279 back(() => ctx.fillRect(qx, qy - lp - 4, Math.min(b.qw * s, 120), lp + 4), 0.7);
280 text(STATE_NAMES[k] + " " + sums[r].counts[k], qx + 3, qy - lp - 2, lp, COLORS[k], "600");
281 }
282 }
283 }
284 // Item text, when the cell is big enough to hold it.
285 if (lv === 2) {
286 const np = Math.min(13, Math.max(9, s * 0.45));
287 for (let i = 0; i < n; i++) {
288 if (ST[i] < 0) continue;
289 const x = sx(X[i]), y = sy(Y[i]);
290 if (x > W || y > H || x + cw < 0 || y + s < 0) continue;
291 text("#" + data.number[i], x + 7, y + 3, np, P.fg, "600");
292 if (s >= 30) {
293 const lines = s >= 56 ? 3 : 1;
294 const avail = cw - 14;
295 const tl = s >= 30 ? wrap(data.title[i], np, avail, lines) : [];
296 for (let j = 0; j < tl.length; j++) text(tl[j], x + 7, y + 3 + np * (j + 1.3), np, P.fg);
297 if (s >= 56 && data.pull[i] > 0) text("pull #" + data.pull[i], x + 7, y + s - np - 4, np - 1, COLORS[2]);
298 }
299 }
300 }
301 }
302 for (const h of headers) h();
303 // Crew.
304 for (const c of crew) {
305 const x = sx(X[c.item] + CELL_W / 2), y = sy(Y[c.item] + 0.5);
306 if (x < -40 || y < -40 || x > W + 40 || y > H + 40) continue;
307 const rad = 11;
308 ctx.beginPath();
309 ctx.arc(x, y, rad + 3, 0, 6.2832);
310 back(() => ctx.fill(), 0.85);
311 ctx.beginPath();
312 ctx.arc(x, y, rad, 0, 6.2832);
313 ctx.fillStyle = P.building;
314 ctx.fill();
315 ctx.textAlign = "center";
316 text(c.who.slice(0, 1).toUpperCase(), x, y - 6, 13, P.bg, "700");
317 text(c.who, x, y + rad + 5, 11, P.fg, "600");
318 ctx.textAlign = "left";
319 }
320 drawn = { cells, level: lv };
321 if (ui.label) ui.label.textContent = clock();
322 }
323
324 function clock() {
325 if (t < 0) return "now";
326 const ago = span() - t;
327 const h = Math.round(ago / 3600000);
328 return h < 1 ? "just now" : h < 48 ? h + " h ago" : Math.round(h / 24) + " d ago";
329 }
330
331 // ---- state & scheduling -------------------------------------------------
332 let dirty = false;
333 function invalidate() {
334 if (dirty) return;
335 dirty = true;
336 if (win) win.requestAnimationFrame(() => { dirty = false; draw(); });
337 else { dirty = false; draw(); }
338 }
339 function setTime(ms: number) {
340 t = ms >= span() - 1000 ? -1 : Math.max(0, ms);
341 place();
342 if (ui.slider) ui.slider.value = String(Math.round((at() / span()) * 1000));
343 invalidate();
344 saveSoon();
345 }
346 function setData(next: any) {
347 data = next;
348 packRegions();
349 place();
350 invalidate();
351 }
352
353 let animating = 0;
354 function goTo(cx: number, cy: number, s: number) {
355 const from = { cx: view.cx, cy: view.cy, s: view.s };
356 const to = { cx, cy, s: Math.min(MAX_S, Math.max(MIN_S, s)) };
357 if (!win) { view.cx = to.cx; view.cy = to.cy; view.s = to.s; clampView(); invalidate(); return; }
358 const start = win.performance.now();
359 const id = ++animating;
360 const step = (now: number) => {
361 if (id !== animating) return;
362 const k = Math.min(1, (now - start) / 260);
363 const e = 1 - Math.pow(1 - k, 3);
364 view.cx = from.cx + (to.cx - from.cx) * e;
365 view.cy = from.cy + (to.cy - from.cy) * e;
366 view.s = Math.exp(Math.log(from.s) + (Math.log(to.s) - Math.log(from.s)) * e);
367 clampView();
368 draw();
369 saveSoon();
370 if (k < 1) win.requestAnimationFrame(step);
371 };
372 win.requestAnimationFrame(step);
373 }
374 function zoomAt(px: number, py: number, factor: number) {
375 animating++;
376 const bx = wx(px), by = wy(py);
377 view.s = Math.min(MAX_S, Math.max(MIN_S, view.s * factor));
378 view.cx = bx - (px - width / 2) / view.s;
379 view.cy = by - (py - height / 2) / view.s;
380 clampView();
381 invalidate();
382 saveSoon();
383 }
384 function fitAnimated() {
385 const keep = { ...view };
386 fitView();
387 const to = { ...view };
388 Object.assign(view, keep);
389 goTo(to.cx, to.cy, to.s);
390 }
391
392 // ---- the address --------------------------------------------------------
393 let saveTimer = 0;
394 function saveSoon() {
395 if (!win || saveTimer) return;
396 saveTimer = win.setTimeout(() => {
397 saveTimer = 0;
398 const h = "#" + view.cx.toFixed(1) + "," + view.cy.toFixed(1) + "," + view.s.toFixed(3) + (t < 0 ? "" : "," + Math.round((span() - t) / 60000));
399 try { win.history.replaceState(null, "", h); } catch (e) { /* a sandboxed frame */ }
400 }, 200);
401 }
402 function parseHash(h: string) {
403 const m = /^#(-?\d{1,6}(?:\.\d{1,3})?),(-?\d{1,6}(?:\.\d{1,3})?),(\d{1,3}(?:\.\d{1,4})?)(?:,(\d{1,6}))?$/.exec(h || "");
404 if (!m) return null;
405 return { cx: +m[1], cy: +m[2], s: +m[3], ago: m[4] === undefined ? -1 : +m[4] };
406 }
407
408 // ---- picking ------------------------------------------------------------
409 function itemAt(px: number, py: number) {
410 const x = wx(px), y = wy(py);
411 for (let i = 0; i < ST.length; i++) {
412 if (ST[i] >= 0 && x >= X[i] && x < X[i] + CELL_W && y >= Y[i] && y < Y[i] + 1) return i;
413 }
414 return -1;
415 }
416 function regionAt(px: number, py: number) {
417 const x = wx(px), y = wy(py);
418 for (const b of regionsBox) if (b && x >= b.x && x < b.x + b.w && y >= b.y && y < b.y + b.h) return b;
419 return null;
420 }
421 function crewAt(px: number, py: number) {
422 for (const c of crew) {
423 const dx = sx(X[c.item] + CELL_W / 2) - px, dy = sy(Y[c.item] + 0.5) - py;
424 if (dx * dx + dy * dy < 20 * 20) return c;
425 }
426 return null;
427 }
428 function say(html: any) {
429 if (!ui.panel) return;
430 ui.panel.textContent = "";
431 if (!html) { ui.panel.hidden = true; return; }
432 for (const part of html) ui.panel.appendChild(part);
433 ui.panel.hidden = false;
434 }
435 function el(tag: string, txt: string, attrs?: any) {
436 const e = win.document.createElement(tag);
437 e.textContent = txt;
438 if (attrs) for (const k in attrs) e.setAttribute(k, attrs[k]);
439 return e;
440 }
441 function describe(i: number) {
442 const repo = data.repos[data.repo[i]];
443 const who = crew.filter((c) => c.item === i).map((c) => c.who);
444 const parts = [
445 el("strong", "#" + data.number[i] + " " + data.title[i]),
446 el("div", repo + " · " + STATE_NAMES[ST[i]] + (data.pull[i] > 0 ? " · pull #" + data.pull[i] : "")),
447 ];
448 if (who.length) parts.push(el("div", "Crew: " + who.join(", ")));
449 // The path is made of the repository's own name: `owner/name`, validated server-side.
450 parts.push(el("a", "Open the issue", { href: "/" + repo + "/issues/" + data.number[i] }));
451 if (data.pull[i] > 0) parts.push(el("a", "Open the pull", { href: "/" + repo + "/pulls/" + data.pull[i] }));
452 say(parts);
453 }
454 function pick(px: number, py: number) {
455 const c = crewAt(px, py);
456 if (c) {
457 say([el("strong", c.who + " is on #" + data.number[c.item]), el("div", data.title[c.item]), el("div", c.summary || "working")]);
458 goTo(X[c.item] + CELL_W / 2, Y[c.item] + 0.5, Math.max(view.s, 40));
459 return;
460 }
461 if (view.s >= 3) {
462 const i = itemAt(px, py);
463 if (i >= 0) { describe(i); if (view.s < 40) goTo(X[i] + CELL_W / 2, Y[i] + 0.5, 60); return; }
464 }
465 const b = regionAt(px, py);
466 if (b) {
467 say([el("strong", data.regions[b.r].name), el("div", sums[b.r].open + " open · " + sums[b.r].landed + " landed in 7 days")]);
468 if (view.s < 20) goTo(b.x + b.w / 2, b.y + b.h / 2, Math.min(Math.max(view.s * 3, 2.2), Math.min(width / b.w, height / b.h) * 0.92));
469 } else say(null);
470 }
471
472 // ---- input --------------------------------------------------------------
473 function bind() {
474 const pointers = new Map<number, { x: number; y: number }>();
475 let moved = 0, downAt = 0, pinch: any = null;
476 const local = (e: any) => {
477 const r = canvas.getBoundingClientRect();
478 return { x: e.clientX - r.left, y: e.clientY - r.top };
479 };
480 canvas.addEventListener("pointerdown", (e: any) => {
481 animating++;
482 const p = local(e);
483 pointers.set(e.pointerId, p);
484 try { canvas.setPointerCapture(e.pointerId); } catch (err) { /* synthetic */ }
485 moved = 0; downAt = e.timeStamp;
486 if (pointers.size === 2) {
487 const [a, b] = [...pointers.values()];
488 pinch = { d: Math.hypot(a.x - b.x, a.y - b.y) || 1, s: view.s, mx: (a.x + b.x) / 2, my: (a.y + b.y) / 2 };
489 pinch.wx = wx(pinch.mx); pinch.wy = wy(pinch.my);
490 }
491 });
492 canvas.addEventListener("pointermove", (e: any) => {
493 const prev = pointers.get(e.pointerId);
494 if (!prev) return;
495 const p = local(e);
496 pointers.set(e.pointerId, p);
497 if (pointers.size === 1) {
498 view.cx -= (p.x - prev.x) / view.s;
499 view.cy -= (p.y - prev.y) / view.s;
500 moved += Math.abs(p.x - prev.x) + Math.abs(p.y - prev.y);
501 } else if (pinch && pointers.size === 2) {
502 const [a, b] = [...pointers.values()];
503 const d = Math.hypot(a.x - b.x, a.y - b.y) || 1;
504 const mx = (a.x + b.x) / 2, my = (a.y + b.y) / 2;
505 view.s = Math.min(MAX_S, Math.max(MIN_S, pinch.s * d / pinch.d));
506 view.cx = pinch.wx - (mx - width / 2) / view.s;
507 view.cy = pinch.wy - (my - height / 2) / view.s;
508 moved += 99;
509 }
510 clampView();
511 invalidate();
512 saveSoon();
513 });
514 const up = (e: any) => {
515 const p = pointers.get(e.pointerId);
516 pointers.delete(e.pointerId);
517 if (pointers.size < 2) pinch = null;
518 if (p && pointers.size === 0 && moved < 8 && e.timeStamp - downAt < 500 && e.type === "pointerup") pick(p.x, p.y);
519 };
520 canvas.addEventListener("pointerup", up);
521 canvas.addEventListener("pointercancel", up);
522 canvas.addEventListener("wheel", (e: any) => {
523 e.preventDefault();
524 const p = local(e);
525 const k = e.ctrlKey ? 0.01 : 0.0015;
526 zoomAt(p.x, p.y, Math.exp(-e.deltaY * k));
527 }, { passive: false });
528 canvas.addEventListener("dblclick", (e: any) => { const p = local(e); zoomAt(p.x, p.y, 2); });
529 win.addEventListener("keydown", (e: any) => {
530 const tag = e.target && e.target.tagName;
531 if (tag === "TEXTAREA" || (tag === "INPUT" && e.target.type !== "range")) return;
532 const k = e.key;
533 if (k === "+" || k === "=") { e.preventDefault(); zoomAt(width / 2, height / 2, 1.4); }
534 else if (k === "-" || k === "_") { e.preventDefault(); zoomAt(width / 2, height / 2, 1 / 1.4); }
535 else if (e.metaKey || e.ctrlKey || e.altKey) return;
536 else if (k === "0" || k === "f") fitAnimated();
537 else if (k === "n") setTime(span());
538 else if (k === "ArrowLeft" && tag !== "INPUT") { view.cx -= 80 / view.s; clampView(); invalidate(); saveSoon(); }
539 else if (k === "ArrowRight" && tag !== "INPUT") { view.cx += 80 / view.s; clampView(); invalidate(); saveSoon(); }
540 else if (k === "ArrowUp") { view.cy -= 80 / view.s; clampView(); invalidate(); saveSoon(); }
541 else if (k === "ArrowDown") { view.cy += 80 / view.s; clampView(); invalidate(); saveSoon(); }
542 else if (k === "Escape") say(null);
543 });
544 win.addEventListener("resize", () => resize(win.innerWidth, win.innerHeight, win.devicePixelRatio || 1));
545 if (ui.fit) ui.fit.addEventListener("click", fitAnimated);
546 if (ui.now) ui.now.addEventListener("click", () => { setTime(span()); });
547 if (ui.zoomIn) ui.zoomIn.addEventListener("click", () => zoomAt(width / 2, height / 2, 1.5));
548 if (ui.zoomOut) ui.zoomOut.addEventListener("click", () => zoomAt(width / 2, height / 2, 1 / 1.5));
549 if (ui.slider) ui.slider.addEventListener("input", () => setTime((+ui.slider.value / 1000) * span()));
550 let playing = 0;
551 if (ui.play) {
552 ui.play.addEventListener("click", () => {
553 if (playing) { win.clearInterval(playing); playing = 0; ui.play.textContent = "Replay"; return; }
554 let ms = 0;
555 ui.play.textContent = "Pause";
556 playing = win.setInterval(() => {
557 ms += span() / 150;
558 if (ms >= span()) { win.clearInterval(playing); playing = 0; ui.play.textContent = "Replay"; setTime(span()); return; }
559 setTime(ms);
560 }, 80);
561 });
562 }
563 // The live channel: any change to the work asks for the picture again,
564 // once, when it settles; a replay in the past is left where it is.
565 let refetch = 0;
566 win.document.addEventListener("forge:event", () => {
567 if (t >= 0 || refetch || !opts.reload) return;
568 refetch = win.setTimeout(() => {
569 refetch = 0;
570 opts.reload().then((d: any) => { if (d) setData(d); }).catch(() => {});
571 }, 800);
572 });
573 }
574
575 function resize(w: number, h: number, ratio: number) {
576 width = w; height = h; dpr = ratio;
577 canvas.width = Math.round(w * ratio);
578 canvas.height = Math.round(h * ratio);
579 invalidate();
580 }
581
582 // ---- start ---------------------------------------------------------------
583 packRegions();
584 const start = opts.view || parseHash(opts.hash || "");
585 if (start && start.ago >= 0) t = Math.max(0, span() - start.ago * 60000);
586 place();
587 fitView();
588 if (start) { view.cx = start.cx; view.cy = start.cy; view.s = start.s; clampView(); }
589 if (win) { bind(); resize(width, height, dpr); } else draw();
590
591 return {
592 draw, setData, setTime, fitView, zoomAt, pick, place, parseHash,
593 view, pos: (i: number) => ({ x: X[i], y: Y[i] }), get stats() { return drawn; }, get crew() { return crew; }, get sums() { return sums; },
594 get state() { return ST; },
595 };
596 }
src/web/space_data.ts added +182
@@ -0,0 +1,182 @@
1 /**
2 * The space's data: what `/map/space` and `/api/v1/map/space` draw. Plain
3 * data out, columnar so twelve thousand issues stay small on the wire: one
4 * array per field, an item's index is its position in each. Every read
5 * respects the viewer (visible repositories, sealed scope); nothing here is
6 * kept, so a write shows on the next read.
7 *
8 * What it holds: each open issue, and each one that closed in the last
9 * `SPACE_DAYS` days (so time can be replayed), grouped into regions — a
10 * pillar where the repository has pillars, the repository where not — the
11 * agent runs of the same window (where the crew was, and when), and the
12 * moment of the read.
13 */
14
15 import type { Database } from "bun:sqlite";
16 import type { App } from "../app.ts";
17 import { pillarView } from "../core/pillars.ts";
18 import { closesFromBody } from "../core/pulls.ts";
19 import { listReposVisibleTo, type Repo } from "../core/repos.ts";
20 import { sealedScope } from "../core/sealed.ts";
21 import type { User } from "../core/users.ts";
22
23 export const SPACE_DAYS = 7;
24 /** More than the forge has issues open; a bound, not a target. */
25 export const SPACE_MAX_ITEMS = 40_000;
26 const TITLE_MAX = 90;
27
28 /** What an item is at "now". Replay works out the rest from times. */
29 export const STATES = ["waiting", "building", "review", "landed"] as const;
30 export type SpaceState = (typeof STATES)[number];
31
32 export interface SpaceData {
33 /** The read, in ms since the epoch; every time below is ms after `since`. */
34 readonly now: number;
35 readonly since: number;
36 readonly regions: { name: string; color: string }[];
37 /** Per item: region index, repo index, state index, number, title. */
38 readonly region: number[];
39 readonly repo: number[];
40 readonly state: number[];
41 readonly number: number[];
42 readonly title: string[];
43 /** Per item: created, closed (-1 while open), both ms after `since`; a created before the window is 0. */
44 readonly created: number[];
45 readonly closed: number[];
46 /** Per item: the pull that closes it (0 for none). */
47 readonly pull: number[];
48 readonly repos: string[];
49 /** Agent runs: who, which item (index), from and to (ms after `since`; to is -1 while going). */
50 readonly runs: { who: string; item: number; from: number; to: number; summary: string }[];
51 }
52
53 const COLOURS = ["b4533a", "a8742a", "6f7f2e", "2f7d5b", "2b7a8c", "3f67b1", "6b55b5", "a14b86"];
54
55 interface Row {
56 id: string;
57 repo_id: string;
58 number: number;
59 kind: string;
60 title: string;
61 body: string;
62 state: string;
63 created_at: string;
64 closed_at: string | null;
65 }
66
67 function scopeSql(scope: ReturnType<typeof sealedScope>): { sql: string; args: string[] } {
68 if (scope.sealed) return { sql: "", args: [] };
69 if (scope.sealedBy) return { sql: "AND (sealed = 0 OR author_id = ?)", args: [scope.sealedBy] };
70 return { sql: "AND sealed = 0", args: [] };
71 }
72
73 const COLS =
74 "id, repo_id, number, kind, title, CASE WHEN kind = 'pull' THEN body ELSE '' END AS body, state, created_at, closed_at";
75 /** The reads, kept by name so a test can ask the planner about each (they walk issue_repo_state and run_repo). */
76 export const OPEN_SQL = (scope: string) =>
77 `SELECT ${COLS} FROM issue WHERE repo_id = ? AND state = 'open' ${scope}`;
78 export const DONE_SQL = (scope: string) =>
79 `SELECT ${COLS} FROM issue WHERE repo_id = ? AND state = 'closed' AND kind = 'issue' AND closed_at >= ? ${scope}`;
80 export const RUNS_SQL = `SELECT run.issue_id, user.username AS actor, run.state, run.created_at, run.started_at, run.finished_at, run.summary
81 FROM run LEFT JOIN user ON user.id = run.actor_id
82 WHERE run.repo_id = ? AND run.kind = 'agent' ORDER BY run.id DESC LIMIT 400`;
83
84 /** Open issues and pulls, and what closed since `sinceIso`, of one repository: walks issue_repo_state. */
85 function rowsOf(db: Database, repo: Repo, scope: ReturnType<typeof sealedScope>, sinceIso: string): Row[] {
86 const s = scopeSql(scope);
87 const open = db
88 .query<Row, string[]>(OPEN_SQL(s.sql))
89 .all(repo.id, ...s.args);
90 const done = db
91 .query<Row, string[]>(
92 DONE_SQL(s.sql),
93 )
94 .all(repo.id, sinceIso, ...s.args);
95 return [...open, ...done];
96 }
97
98 export function spaceData(app: App, viewer: User | undefined, now = new Date()): SpaceData {
99 const db = app.db;
100 const nowMs = now.getTime();
101 const since = nowMs - SPACE_DAYS * 86_400_000;
102 const sinceIso = new Date(since).toISOString();
103 const repos = listReposVisibleTo(db, viewer, { limit: 200, withoutArchived: true });
104 const out = {
105 region: [] as number[], repo: [] as number[], state: [] as number[], number: [] as number[],
106 title: [] as string[], created: [] as number[], closed: [] as number[], pull: [] as number[],
107 };
108 const regions: { name: string; color: string }[] = [];
109 const regionIx = new Map<string, number>();
110 const repoNames: string[] = [];
111 const itemOf = new Map<string, number>();
112 const runs: { who: string; issueId: string; from: number; to: number; summary: string }[] = [];
113
114 for (const repo of repos) {
115 const scope = sealedScope(db, repo, viewer);
116 const rows = rowsOf(db, repo, scope, sinceIso);
117 if (rows.length === 0 || out.title.length >= SPACE_MAX_ITEMS) continue;
118 const repoIx = repoNames.push(`${repo.ownerName}/${repo.name}`) - 1;
119 const view = rows.some((r) => r.state === "open") ? pillarView(db, repo, now) : undefined;
120 const regionFor = (id: string): number => {
121 const pillar = view?.of.get(id);
122 const key = pillar ?? `${repo.ownerName}/${repo.name}`;
123 let ix = regionIx.get(key);
124 if (ix === undefined) {
125 ix = regions.push({ name: key, color: COLOURS[regions.length % COLOURS.length]! }) - 1;
126 regionIx.set(key, ix);
127 }
128 return ix;
129 };
130 // An open pull names the issues it closes: they are in review.
131 const reviewing = new Map<number, number>();
132 for (const r of rows) {
133 if (r.kind === "pull" && r.state === "open") {
134 for (const n of closesFromBody(r.body)) reviewing.set(n, r.number);
135 }
136 }
137 const active = new Set<string>();
138 for (const run of db
139 .query<{ issue_id: string | null; actor: string | null; state: string; created_at: string; started_at: string | null; finished_at: string | null; summary: string }, [string]>(
140 RUNS_SQL,
141 )
142 .all(repo.id)) {
143 if (run.issue_id === null || run.actor === null) continue;
144 const from = Date.parse(run.started_at ?? run.created_at);
145 const going = run.state === "running" || run.state === "queued";
146 const to = going ? nowMs : Date.parse(run.finished_at ?? run.created_at);
147 if (!(to >= since) || run.started_at === null) continue;
148 if (run.state === "running") active.add(run.issue_id);
149 runs.push({ who: run.actor, issueId: run.issue_id, from: Math.max(0, from - since), to: going ? -1 : to - since, summary: run.summary.slice(0, 120) });
150 }
151 for (const r of rows) {
152 if (r.kind === "pull" && r.state === "open") {
153 // A pull is the card of the issue it closes; one that closes nothing stands alone.
154 if (closesFromBody(r.body).length > 0) continue;
155 }
156 const created = Date.parse(r.created_at);
157 const closedAt = r.closed_at === null ? -1 : Date.parse(r.closed_at) - since;
158 const st =
159 r.state === "closed" ? 3 : active.has(r.id) ? 1 : reviewing.has(r.number) || r.kind === "pull" ? 2 : 0;
160 itemOf.set(r.id, out.title.length);
161 out.region.push(regionFor(r.id));
162 out.repo.push(repoIx);
163 out.state.push(st);
164 out.number.push(r.number);
165 out.title.push(r.title.slice(0, TITLE_MAX));
166 out.created.push(Math.max(0, created - since));
167 out.closed.push(closedAt);
168 out.pull.push(reviewing.get(r.number) ?? (r.kind === "pull" ? r.number : 0));
169 }
170 }
171 const placed: SpaceData["runs"] = [];
172 for (const run of runs) {
173 const item = itemOf.get(run.issueId);
174 if (item !== undefined) placed.push({ who: run.who, item, from: run.from, to: run.to, summary: run.summary });
175 }
176 return { now: nowMs, since, regions, repos: repoNames, ...out, runs: placed };
177 }
178
179 /** JSON safe inside a `<script type="application/json">`: no `<`, no line separators. */
180 export function inlineJson(value: unknown): string {
181 return JSON.stringify(value).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
182 }
test/no-polling.test.ts +1
@@ -11,6 +11,7 @@ import { Glob } from "bun";
1111 const ALLOWED: Record<string, { allow: string[]; why: string }> = {
1212 "src/web/sw.ts": { allow: ['http-equiv="refresh"'], why: "the restart page: the forge is down, so there is no /events to hear" },
1313 "src/web/pages/talk.ts": { allow: ["setInterval"], why: "server side: the stream of one turn watches the run's row, which has no event to hear" },
14 "src/web/space_client.ts": { allow: ["setInterval"], why: "the replay button steps the scrubber on the viewer's own clock; it draws, it never fetches" },
1415 "src/web/client.ts": { allow: ["data-live-every", "setInterval"], why: "the data-live-every mechanism itself, and clocks that only redraw text" },
1516 };
1617
test/space-client.test.ts added +128
@@ -0,0 +1,128 @@
1 /** The space's client: first draw of the whole forge, semantic zoom, time. */
2 import { expect, test } from "bun:test";
3 import { spaceClient } from "../src/web/space_client.ts";
4
5 const DAY = 86_400_000;
6
7 /** About the real forge: 12k issues in a dozen pillars, a week of closes, three crew. */
8 function forge(n = 12_000) {
9 const now = Date.UTC(2026, 10, 9, 12);
10 const since = now - 7 * DAY;
11 const d: any = {
12 now, since, regions: [], repos: ["trevato/forge", "alice/notes"],
13 region: [], repo: [], state: [], number: [], title: [], created: [], closed: [], pull: [], runs: [],
14 };
15 for (let r = 0; r < 12; r++) d.regions.push({ name: `P${r} Pillar ${r}`, color: "3f67b1" });
16 for (let i = 0; i < n; i++) {
17 const closed = i % 3 === 0;
18 d.region.push((i * 7) % 12);
19 d.repo.push(i % 2);
20 d.state.push(closed ? 3 : i % 11 === 0 ? 1 : i % 5 === 0 ? 2 : 0);
21 d.number.push(i + 1);
22 d.title.push(`Issue number ${i + 1}: something the crew should do about the thing`);
23 d.created.push(Math.floor((i / n) * 5 * DAY));
24 d.closed.push(closed ? Math.floor(5 * DAY + (i / n) * 2 * DAY) : -1);
25 d.pull.push(i % 5 === 0 ? i + 1 : 0);
26 }
27 for (const [who, item] of [["scout", 1], ["mason", 2], ["torque", 4]] as const)
28 d.runs.push({ who, item, from: 6 * DAY, to: -1, summary: `${who} is on it` });
29 return d;
30 }
31
32 function stub() {
33 const texts: string[] = [];
34 let fills = 0;
35 const ctx: any = new Proxy({}, {
36 get(_t, k) {
37 if (k === "fillText") return (s: string) => texts.push(s);
38 if (k === "fillRect") return () => fills++;
39 return () => {};
40 },
41 set: () => true,
42 });
43 const canvas: any = { getContext: () => ctx, width: 0, height: 0 };
44 return { canvas, texts, fills: () => fills };
45 }
46
47 test("the first draw of twelve thousand issues is under 300 ms", () => {
48 const data = forge();
49 const { canvas } = stub();
50 const started = performance.now();
51 const api = spaceClient(canvas, data, { width: 390, height: 844, dpr: 3 });
52 const took = performance.now() - started;
53 expect(data.title.length).toBe(12_000);
54 expect(took).toBeLessThan(300);
55 expect(api.sums.reduce((n: number, s: any) => n + s.open + s.landed, 0)).toBe(12_000);
56 });
57
58 test("the source the page ships runs on its own", () => {
59 const { canvas } = stub();
60 const make = new Function(`return (${spaceClient.toString()})`)();
61 const api = make(canvas, forge(500), { width: 800, height: 600, dpr: 1 });
62 expect(api.sums.length).toBe(12);
63 });
64
65 test("zoomed out: regions with their counts; in: states named; further: titles", () => {
66 const data = forge(3000);
67 const s = stub();
68 const api = spaceClient(s.canvas, data, { width: 1200, height: 800, dpr: 1 });
69 api.view.s = 0.4;
70 s.texts.length = 0;
71 api.draw();
72 expect(api.stats.level).toBe(0);
73 expect(s.texts).toContain("P0");
74 api.view.s = 1.2;
75 s.texts.length = 0;
76 api.draw();
77 expect(s.texts.some((t) => t.startsWith("P0 "))).toBe(true);
78 expect(s.texts.some((t) => t.includes(" open"))).toBe(true);
79 expect(api.stats.level).toBe(0);
80 expect(s.texts.some((t) => t.startsWith("waiting"))).toBe(false);
81 expect(s.texts.some((t) => t.startsWith("Issue number"))).toBe(false);
82
83 api.view.s = 5;
84 s.texts.length = 0;
85 api.draw();
86 expect(api.stats.level).toBe(1);
87 expect(s.texts.some((t) => t.startsWith("waiting"))).toBe(true);
88 expect(s.texts.some((t) => t.startsWith("landed"))).toBe(true);
89 expect(s.texts.some((t) => t.startsWith("Issue number"))).toBe(false);
90
91 // Onto one issue, torque's: number, title, its pull, and the crew member.
92 const p = api.pos(4);
93 api.view.s = 60;
94 api.view.cx = p.x + 1.5;
95 api.view.cy = p.y + 0.5;
96 s.texts.length = 0;
97 api.draw();
98 expect(api.stats.level).toBe(2);
99 expect(s.texts).toContain("#5");
100 expect(s.texts.some((t) => t.startsWith("Issue number 5"))).toBe(true);
101 expect(s.texts).toContain("torque");
102 });
103
104 test("time: a replay hides what did not exist yet and moves things to landed", () => {
105 const data = forge(3000);
106 const s = stub();
107 const api = spaceClient(s.canvas, data, { width: 1200, height: 800, dpr: 1 });
108 const total = (a: any) => a.sums.reduce((n: number, x: any) => n + x.open + x.landed, 0);
109 const landed = (a: any) => a.sums.reduce((n: number, x: any) => n + x.landed, 0);
110 const nowLanded = landed(api);
111 api.setTime(1 * DAY);
112 expect(total(api)).toBeLessThan(3000);
113 expect(landed(api)).toBeLessThan(nowLanded);
114 expect(api.crew.length).toBe(0);
115 api.setTime(7 * DAY);
116 expect(landed(api)).toBe(nowLanded);
117 expect(api.crew.map((c: any) => c.who).sort()).toEqual(["mason", "scout", "torque"]);
118 });
119
120 test("the address: a hash is the view, and only a plain one", () => {
121 const s = stub();
122 const api = spaceClient(s.canvas, forge(100), { width: 800, height: 600, dpr: 1, hash: "#10.5,20.5,3.25" });
123 expect(api.view.s).toBe(3.25);
124 const bad = spaceClient(s.canvas, forge(100), { width: 800, height: 600, dpr: 1, hash: "#<script>" });
125 expect(bad.view.s).not.toBe(3.25);
126 expect(api.parseHash("#1,2,3,60")).toEqual({ cx: 1, cy: 2, s: 3, ago: 60 });
127 expect(api.parseHash("#1,2")).toBeNull();
128 });
test/space-page.test.ts added +107
@@ -0,0 +1,107 @@
1 /** `/map/space` and its data: what the viewer sees, escaped, and nothing more. */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtempSync, rmSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { openIssue } from "../src/actions/issues.ts";
7 import { createRepo } from "../src/actions/repos.ts";
8 import { createApp, type App } from "../src/app.ts";
9 import { setIssueState } from "../src/core/issues.ts";
10 import { createUser } from "../src/core/users.ts";
11 import { serve, type Servers } from "../src/http/server.ts";
12 import { DONE_SQL, OPEN_SQL, RUNS_SQL } from "../src/web/space_data.ts";
13 import { quietLogs } from "./helpers/globals.ts";
14
15 quietLogs();
16
17 let root = "";
18 let app: App;
19 let servers: Servers;
20 const cookies: Record<string, string> = {};
21
22 async function signIn(name: string): Promise<string> {
23 const res = await fetch(`${servers.url}/signin`, {
24 method: "POST",
25 headers: { origin: servers.url },
26 body: new URLSearchParams({ username: name, password: "a-good-passphrase" }),
27 redirect: "manual",
28 });
29 return (res.headers.get("set-cookie") ?? "").split(";")[0]!;
30 }
31
32 beforeAll(async () => {
33 root = mkdtempSync(join(tmpdir(), "forge-space-"));
34 app = createApp({ dataDir: root, port: 0 });
35 const users: Record<string, any> = {};
36 for (const name of ["alice", "bob"]) {
37 const u = await createUser(app.db, {
38 origin: "seed", trusted: true, username: name, email: `${name}@forge.local`,
39 password: "a-good-passphrase", adminIfFirst: name === "alice",
40 });
41 if (!u.ok) throw new Error(u.error);
42 users[name] = u.value;
43 }
44 const secret = await createRepo(app, users.alice, { name: "secret", visibility: "private" });
45 const open = await createRepo(app, users.alice, { name: "notes", visibility: "public" });
46 if (!secret.ok || !open.ok) throw new Error("repo");
47 await openIssue(app, users.alice, secret.value, { title: "Private plan" });
48 await openIssue(app, users.alice, open.value, { title: "Open </script><b>work" });
49 const done = await openIssue(app, users.alice, open.value, { title: "Landed today" });
50 if (!done.ok) throw new Error(done.error);
51 setIssueState(app.db, done.value.id, "closed");
52 servers = await serve(app);
53 cookies.alice = await signIn("alice");
54 cookies.bob = await signIn("bob");
55 });
56
57 afterAll(() => {
58 servers?.stop?.();
59 rmSync(root, { recursive: true, force: true });
60 });
61
62 test("signed out, the space asks for a sign-in", async () => {
63 const res = await fetch(`${servers.url}/map/space`, { redirect: "manual" });
64 expect(res.status).not.toBe(200);
65 });
66
67 test("the page is a full-window canvas with the data inline and escaped", async () => {
68 const res = await fetch(`${servers.url}/map/space`, { headers: { cookie: cookies.alice! } });
69 expect(res.status).toBe(200);
70 const body = await res.text();
71 expect(body).toContain('id="space-canvas"');
72 expect(body).toContain('id="space-time"');
73 expect(body).toContain('id="space-fit"');
74 expect(body).toContain('id="space-now"');
75 expect(body).toContain("application/json");
76 expect(body).not.toContain("</script><b>work");
77 expect(res.headers.get("content-security-policy")).toBeTruthy();
78 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
79 });
80
81 test("the data holds open work and this week's landings, for who may see them", async () => {
82 const get = async (who: string) =>
83 (await (await fetch(`${servers.url}/api/v1/map/space`, { headers: { cookie: cookies[who]! } })).json()) as any;
84 const a = await get("alice");
85 expect(a.title).toContain("Private plan");
86 expect(a.title).toContain("Open </script><b>work");
87 const landed = a.title.indexOf("Landed today");
88 expect(a.state[landed]).toBe(3);
89 expect(a.closed[landed]).toBeGreaterThan(0);
90 const b = await get("bob");
91 expect(b.title).not.toContain("Private plan");
92 expect(b.title).toContain("Landed today");
93 });
94
95 test("the reads walk an index, never the table", () => {
96 for (const sql of [OPEN_SQL("AND sealed = 0"), DONE_SQL("AND sealed = 0"), RUNS_SQL]) {
97 const n = (sql.match(/\?/g) ?? []).length;
98 const plan = app.db
99 .query(`EXPLAIN QUERY PLAN ${sql}`)
100 .all(...Array.from({ length: n }, () => "x"))
101 .map((r) => (r as { detail: string }).detail);
102 for (const line of plan) {
103 expect(line).not.toMatch(/^SCAN (?!.*USING (COVERING )?INDEX)/);
104 expect(line).not.toContain("TEMP B-TREE");
105 }
106 }
107 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs