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

Run pages and boards update over the same stream; no forge page polls on a timer #2795

Parked opened this
Closed without merging

scout/forge:scout/2722-run-pages-and-boards-update-over-the-sam → main 3 commits fork 6 threads · 6 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
34 files changed +470 −310
docs/APPS.md +2 −2
@@ -914,8 +914,8 @@ numbers as a table beside it. The selection is `?repo=owner/name`,
914914 repeated; absent, it is every repository you can write that spent in the
915915 last 14 days. A run counts in the bucket it ended in. Past eight
916916 repositories the smallest spenders share one grey series, "N others".
917 The page redraws every 30 seconds while it is open, and at once on a
918 `forge:fleet-op` event, so an operation's effect shows within a minute.
917 The graph is a live region: it redraws when a run ends or a usage row
918 lands on the event stream (`run.*`, `usage.*`), with no timer.
919919 The same numbers are `GET /fleet/graph.csv` and `GET /api/v1/fleet/graph`;
920920 spend is the owner's fact, so a repository you cannot write is dropped
921921 and counted with the names that do not exist, never told apart.
docs/STUDIO.md +9 −6
@@ -308,8 +308,8 @@ the tell it came from (linking to it), how long it has gone and what it has
308308 cost, and its state in the studio's own word. The transcript is the page's
309309 body, tailing live with a fixed-height scrolling area and a cap on how many
310310 lines it holds — a long agent run never grows the page without bound; with
311 JavaScript off the page still shows what was logged and refreshes itself
312 while the run is in flight. Once the tell has become a pull, its preview is
311 JavaScript off the page still shows what was logged; it never refreshes
312 itself. Once the tell has become a pull, its preview is
313313 on the page as soon as it exists — this is the page someone sits on while
314314 waiting for a change to become visible. Steer and Stop are here for anyone
315315 who can write, through the very same routes and checks dev's page uses.
@@ -408,10 +408,13 @@ so a card that is answered goes and a new one arrives without a reload.
408408
409409 ### Live regions
410410
411 A page with a script never reloads itself: the `meta refresh` some pages
412 carry is the no-script fallback, written inside `<noscript>` so a browser
413 running the script never even schedules it (removing the tag afterwards
414 would not cancel a refresh the parser had already set). Every live region
411 No forge page polls on a timer or reloads itself (#2722,
412 `test/no-polling.test.ts` scans `src/web` for it). The only `meta refresh` is
413 a delayed redirect to somewhere else. What the server clocks, such as the
414 machine sampler, reaches a tab as a *pulse* (`src/core/pulse.ts`): an
415 id-less frame on `/events`, sent to an admin's tab only, which a region
416 lists in `data-live` like an event kind (`board.sampled` draws a refreshing
417 board). Every live region
415418 listens to one `EventSource` (`/events`,
416419 everything the viewer may see) and works like this:
417420
src/boards/sampler.ts +2
@@ -22,6 +22,7 @@
2222 import { readFileSync } from "node:fs";
2323 import { join } from "node:path";
2424 import type { App } from "../app.ts";
25 import { BOARD_SAMPLED, pulse } from "../core/pulse.ts";
2526 import { cellCounters, type CellCounter } from "../apps/contain.ts";
2627 import { FINE_MS, record, type Point } from "./ring.ts";
2728 import { readHwmon, readTopology, temperatures } from "./thermal.ts";
@@ -215,6 +216,7 @@ export function startSampler(
215216 const next = readCounters(paths, cells(), now);
216217 record(app.db, pointsOf(prev, next), now);
217218 prev = next;
219 pulse(BOARD_SAMPLED);
218220 } catch (error) {
219221 app.log.warn("machine sample failed", { error: String(error) });
220222 }
src/checks/progress.ts +4
@@ -31,6 +31,10 @@ const FAIL_COUNT = /^\s*(\d+) fail$/;
3131 const fileCount = (names: string): number =>
3232 names.split(" ").filter((n) => n !== "").length;
3333
34 /** A line after which the count moved: a shard finished (live `done`, or a batched header with its exit). */
35 export const isShardReport = (line: string): boolean =>
36 SHARD_DONE.test(line) || (SHARD_OPEN.test(line) && line.includes("(exit"));
37
3438 export function parseShardProgress(lines: readonly string[]): CheckProgress {
3539 const out: CheckProgress = {};
3640 // The files of the shard whose lines are being read; counted once its
src/checks/service.ts +6 −1
@@ -58,6 +58,8 @@ import { transact } from "../kernel/db.ts";
5858 import { createLog } from "../kernel/log.ts";
5959 import { holdLease, STALE_AFTER_MS } from "../runs/lease.ts";
6060 import { appendRunLog } from "../runs/log.ts";
61 import { RUN_PROGRESS, pulse } from "../core/pulse.ts";
62 import { isShardReport } from "./progress.ts";
6163 import { runningLimitSentence, runningRuns } from "../settings/quotas.ts";
6264 import { exportTree, readFileAt } from "../apps/checkout.ts";
6365 import { parseCheck } from "../apps/manifest.ts";
@@ -476,8 +478,11 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
476478 if (!claimed) return;
477479 const lease = holdLease(app.db, run.id);
478480 announceRun(app, claimed);
479 const write = (line: string): void =>
481 const write = (line: string): void => {
480482 appendRunLog(app.config.dataDir, run.id, line);
483 // A finished shard moves the checks line's count; say so to its readers.
484 if (isShardReport(line)) pulse(RUN_PROGRESS, repo.id);
485 };
481486 if (options.label !== undefined)
482487 write(`forge ${options.label} — checked in its parent's lane`);
483488 const started = Date.now();
src/core/pulse.ts added +42
@@ -0,0 +1,42 @@
1 /**
2 * Pulses: news that is not an event. A sample taken on a timer is not
3 * history, so it is never a row in the outbox; it is a name passed to whoever
4 * is listening right now. The viewer stream (`http/sse.ts`) hands a pulse to
5 * the tabs that may hear it, and a region that lists the pulse's kind in its
6 * `data-live` refetches. That is how a page stays current without a timer of
7 * its own: the server has the one clock, the tab has none.
8 */
9
10 export type PulseListener = (kind: string, repoId?: string) => void;
11
12 const listeners = new Set<PulseListener>();
13
14 /**
15 * Tell every listener that `kind` just happened. With a `repoId` the news is
16 * about that repository and goes to whoever may read it; without, it is the
17 * machine's and goes to admin people. A listener that throws is dropped from this call only.
18 */
19 export function pulse(kind: string, repoId?: string): void {
20 for (const listener of [...listeners]) {
21 try {
22 listener(kind, repoId);
23 } catch {
24 // one broken tab never starves the others
25 }
26 }
27 }
28
29 /** Hear every pulse until the returned function is called. */
30 export function onPulse(listener: PulseListener): () => void {
31 listeners.add(listener);
32 return () => listeners.delete(listener);
33 }
34
35 /** The pulse a board's panels are drawn from: the machine sampler took a reading. */
36 export const BOARD_SAMPLED = "board.sampled";
37
38 /** The snapshot in flight landed more of itself (or began, or ended): the Backups page's progress line moved. */
39 export const SNAPSHOT_PROGRESS = "snapshot.progress";
40
41 /** A check's shard reported: the files-and-tests count on the pull's checks line moved. */
42 export const RUN_PROGRESS = "run.progress";
src/http/sse.ts +23 −1
@@ -21,6 +21,7 @@ import { listEvents, listEventsVisibleTo } from "../core/events.ts";
2121 import { audienceFilter } from "../core/event_audience.ts";
2222 import { canRead, getRepoById } from "../core/repos.ts";
2323 import type { ForgeEvent } from "../core/events.ts";
24 import { onPulse } from "../core/pulse.ts";
2425
2526 const HEARTBEAT_MS = 25_000;
2627
@@ -224,11 +225,32 @@ export function viewerStream(
224225 for (const event of missed)
225226 if (meant(event)) emit("forge", named(event), event.id);
226227 }
227 return app.bus.subscribe((event: ForgeEvent) => {
228 const stopBus = app.bus.subscribe((event: ForgeEvent) => {
228229 if (event.repoId === null || !visible(event.repoId)) return;
229230 if (!meant(event)) return;
230231 emit("forge", named(event), event.id);
231232 });
233 // Pulses (`core/pulse.ts`) are not history: no id, nothing to replay, and
234 // only the people whose pages are drawn from them (boards are an admin
235 // person's) hear them.
236 const hears = viewer?.isAdmin === true && viewer.kind !== "agent";
237 const stopPulse = hears
238 ? onPulse((kind, repoId) => {
239 if (repoId === undefined) emit("forge", { id: "", kind, repo: null, payload: {}, at: new Date().toISOString() });
240 })
241 : () => {};
242 // A repository's pulse (a shard reported) goes to whoever may read it.
243 const stopRepoPulse = onPulse((kind, repoId) => {
244 if (repoId === undefined || !visible(repoId)) return;
245 const repo = getRepoById(app.db, repoId);
246 if (repo === undefined) return;
247 emit("forge", { id: "", kind, repo: `${repo.ownerName}/${repo.name}`, payload: {}, at: new Date().toISOString() });
248 });
249 return () => {
250 stopBus();
251 stopPulse();
252 stopRepoPulse();
253 };
232254 });
233255 }
234256
src/snapshot/service.ts +4
@@ -11,6 +11,7 @@
1111 */
1212
1313 import type { App } from "../app.ts";
14 import { pulse, SNAPSHOT_PROGRESS } from "../core/pulse.ts";
1415 import { createLog } from "../kernel/log.ts";
1516 import { firstSeen, reportVerdict, seedFirstSeen } from "./verdict.ts";
1617 import {
@@ -152,6 +153,7 @@ export function startSnapshots(
152153 const store = current();
153154 if (store === undefined) throw new Nowhere();
154155 running = { objects: 0, bytes: 0, elapsedMs: 0 };
156 pulse(SNAPSHOT_PROGRESS);
155157 const manifest = await takeSnapshot(
156158 {
157159 db: app.db,
@@ -161,11 +163,13 @@ export function startSnapshots(
161163 passphrase: options.passphrase,
162164 onLand: (p) => {
163165 running = p;
166 pulse(SNAPSHOT_PROGRESS);
164167 },
165168 },
166169 store,
167170 ).finally(() => {
168171 running = undefined;
172 pulse(SNAPSHOT_PROGRESS);
169173 });
170174 await pruneSnapshots(store, KEEP);
171175 return manifest;
src/web/client.ts +8 −20
@@ -10,6 +10,7 @@
1010 * behaviour that a page depends on to be usable.
1111 */
1212
13 import { mayRedraw } from "./live-gate.ts";
1314 import { paletteHelpersJs } from "./palette.ts";
1415
1516 /**
@@ -1935,6 +1936,7 @@ export const boardJs = /* js */ `
19351936 `;
19361937
19371938 export const liveRegionsJs = /* js */ `
1939 ${mayRedraw.toString()}
19381940 (function () {
19391941 var regions = document.querySelectorAll('[data-live]');
19401942 if (regions.length === 0 || typeof EventSource === 'undefined') return;
@@ -1979,8 +1981,6 @@ export const liveRegionsJs = /* js */ `
19791981 mine.innerHTML = theirs.innerHTML;
19801982 opened.forEach(function (i) { var d = document.getElementById(i); if (d) d.open = true; });
19811983 Array.prototype.forEach.call(theirs.attributes, function (a) { if (a.name !== 'id') mine.setAttribute(a.name, a.value); });
1982 if (!theirs.hasAttribute('data-live-every')) mine.removeAttribute('data-live-every');
1983 arm(mine);
19841984 mine.dispatchEvent(new CustomEvent('forge:swapped', { bubbles: true }));
19851985 });
19861986 }
@@ -2074,7 +2074,12 @@ export const liveRegionsJs = /* js */ `
20742074 var hit = false;
20752075 Array.prototype.forEach.call(document.querySelectorAll('[data-live]'), function (region) {
20762076 var patterns = (region.getAttribute('data-live') || '').split(',').map(function (p) { return p.trim(); }).filter(Boolean);
2077 if (region.id && matches(patterns, data.kind, data.repo, region)) { due[region.id] = true; hit = true; }
2077 if (!region.id || !matches(patterns, data.kind, data.repo, region)) return;
2078 // A region with its own pace (data-live-min) skips a pulse that comes sooner.
2079 var min = Number(region.getAttribute('data-live-min')) || 0;
2080 if (!mayRedraw(region.__drawn || 0, Date.now(), min)) return;
2081 region.__drawn = Date.now();
2082 due[region.id] = true; hit = true;
20782083 });
20792084 // Events come in bursts — a run starts, its check queues, a deploy
20802085 // begins — and one fetch answers the burst: never sooner than a beat
@@ -2082,23 +2087,6 @@ export const liveRegionsJs = /* js */ `
20822087 if (hit && timer === null)
20832088 timer = setTimeout(refresh, Math.max(600, last + MIN_GAP - Date.now()));
20842089 }
2085 // A region with data-live-every="<seconds>" is also due on that beat, for
2086 // what no event announces; it rides the same fetch, etag and swap.
2087 // The beat lasts as long as the region asks for it: a swap that drops the
2088 // attribute ends it, and one that brings it (a check starting) begins it.
2089 var beats = {};
2090 function arm(r) {
2091 var s = parseInt(r.getAttribute('data-live-every'), 10);
2092 if (!r.id) return;
2093 if (!(s > 0)) {
2094 if (beats[r.id]) { window.clearInterval(beats[r.id]); delete beats[r.id]; }
2095 return;
2096 }
2097 if (beats[r.id]) return;
2098 var id = r.id;
2099 beats[id] = window.setInterval(function () { due[id] = true; if (timer === null) timer = setTimeout(refresh, 0); }, s * 1000);
2100 }
2101 Array.prototype.forEach.call(document.querySelectorAll('[data-live-every]'), arm);
21022090 connect();
21032091 // Back online: reconnect from the last id and look at every region once,
21042092 // in case the replay window no longer reaches back that far.
src/web/fleet-graph.ts +6 −41
@@ -13,10 +13,9 @@
1313 * the `--series-N` tokens in `src/design/themes.ts`. Text is sized here in
1414 * viewBox units, beside the geometry it has to fit, not in the stylesheet.
1515 *
16 * `fleetGraphSection` carries `data-src`: the client script below fetches
17 * it every 30 s while the tab is visible, and at once on a
18 * `forge:fleet-op` event, so an operation's effect is drawn within a minute
19 * without a reload. The fragment route returns this same section.
16 * `fleetGraphSection` is a live region (`liveRegionsJs`): a run that ends or
17 * a usage row that lands on the one event stream refetches `data-src`, the
18 * fragment route, which returns this same section. No timer.
2019 */
2120
2221 import type {
@@ -36,9 +35,6 @@ const AXIS = 18;
3635 const SVG_H = TOP + SPEND_H + GAP + RUNS_H + AXIS;
3736 const PLOT_W = SVG_W - LEFT - RIGHT;
3837
39 /** How often the open page redraws on its own, in ms. */
40 export const FLEET_GRAPH_REFRESH_MS = 30_000;
41
4238 /** The smallest 1, 2, 2.5 or 5 × 10ⁿ at or above `v`; `floor` when v is 0. */
4339 export function niceCeiling(v: number, floor: number): number {
4440 if (!(v > 0)) return floor;
@@ -221,7 +217,8 @@ export function fleetGraphSection(graph: FleetGraph): Html {
221217 return html`<section
222218 class="fleet-graph"
223219 id="fleet-graph"
224 data-src="/fleet/graph/live${q === "" ? "" : `?${q}`}"
220 data-live="run.finished,usage.*"
outdated

run. now also matches the run.progress pulse sent on every finished shard. That refetches the graph for every shard of every readable repository, though spend only moves when a run ends. List the terminal run kinds and usage. instead.

221 data-live-src="/fleet/graph/live${q === "" ? "" : `?${q}`}"
225222 data-at="${graph.at}"
226223 >
227224 ${graph.repos.length === 0
@@ -254,39 +251,7 @@ export function fleetGraphSection(graph: FleetGraph): Html {
254251 <time datetime="${graph.at}">${graph.at.slice(11, 16)} UTC</time>. A
255252 run counts in the UTC hour or day it ended; spend is the provider's
256253 reported cost in US dollars. The newest bar is still filling. Redrawn
257 every ${FLEET_GRAPH_REFRESH_MS / 1000} s while open.
254 when a run ends while open.
258255 </p>
259256 </section>`;
260257 }
261
262 /** The redraw: fetch the fragment, swap the section; pure enhancement. */
263 export const fleetGraphClientJs = /* js */ `
264 (function () {
265 var busy = false;
266 function redraw() {
267 var el = document.getElementById('fleet-graph');
268 if (!el || busy) return;
269 var src = el.getAttribute('data-src');
270 if (!src) return;
271 busy = true;
272 fetch(src, { credentials: 'same-origin', headers: { accept: 'text/html' } })
273 .then(function (r) { return r.ok ? r.text() : null; })
274 .then(function (text) {
275 if (text === null) return;
276 var doc = new DOMParser().parseFromString(text, 'text/html');
277 var next = doc.getElementById('fleet-graph');
278 var now = document.getElementById('fleet-graph');
279 if (next && now) now.replaceWith(document.importNode(next, true));
280 })
281 .catch(function () {})
282 .then(function () { busy = false; });
283 }
284 setInterval(function () {
285 if (document.visibilityState === 'visible') redraw();
286 }, ${FLEET_GRAPH_REFRESH_MS});
287 document.addEventListener('visibilitychange', function () {
288 if (document.visibilityState === 'visible') redraw();
289 });
290 document.addEventListener('forge:fleet-op', redraw);
291 })();
292 `;
src/web/layout.ts +9 −26
@@ -106,19 +106,13 @@ export interface PageOptions {
106106 /** Extra palette rows for this page's context (a repo's own tabs). */
107107 palette?: PaletteItem[];
108108 /**
109 * The JavaScript-free half of a page that changes on its own: a
110 * `<meta http-equiv="refresh">`, optionally to somewhere else. Only a page
111 * whose content is genuinely still moving should set it — a refresh a
112 * reader did not ask for steals their scroll position and their selection.
113 *
114 * A plain refresh (no `url`) is written inside `<noscript>`: a browser
115 * running the page's script never parses it, so the script's stream is
116 * the only thing moving the page. Removing the element afterwards would
117 * not do — a refresh is scheduled the moment the parser meets the tag,
118 * and the timer outlives the element. A refresh that leads somewhere
119 * (`url`) is a redirect and stays in force either way.
109 * A `<meta http-equiv="refresh">` that leads somewhere else: a redirect
110 * after a delay (a finished mirror lands on its repository). Never a
111 * reload: no forge page polls on a timer, a page that is still moving is
112 * patched in place over the event stream, and `refreshMeta` refuses to
113 * write one (test/no-polling.test.ts).
120114 */
121 refresh?: { seconds: number; url?: string };
115 refresh?: { seconds: number; url: string };
122116 /**
123117 * No topbar, no footer, no page width: a page that is the whole window
124118 * (the board). The overlays stay, so the palette is still one chord away.
@@ -530,20 +524,9 @@ function pageDescription(options: PageOptions): string {
530524 return line.length <= 200 ? line : `${line.slice(0, 197).trimEnd()}…`;
531525 }
532526
533 /**
534 * The `<meta http-equiv="refresh">` for `PageOptions.refresh`. A redirect
535 * (`url`) is a bare tag; a reload is wrapped in `<noscript>`, so only a
536 * browser with no script ever schedules it.
537 */
538 export function refreshMeta(r: { seconds: number; url?: string }): Html {
539 if (r.url !== undefined)
540 return html`<meta
541 http-equiv="refresh"
542 content="${r.seconds}; url=${r.url}"
543 />`;
544 return html`<noscript
545 ><meta http-equiv="refresh" content="${String(r.seconds)}"
546 /></noscript>`;
527 /** The `<meta http-equiv="refresh">` for `PageOptions.refresh`: a delayed redirect, never a reload. */
528 export function refreshMeta(r: { seconds: number; url: string }): Html {
529 return html`<meta http-equiv="refresh" content="${r.seconds}; url=${r.url}" />`;
547530 }
548531
549532 export function page(options: PageOptions, status = 200): Response {
src/web/live-gate.ts added +17
@@ -0,0 +1,17 @@
1 /**
2 * How often a live region may redraw: a region that carries `data-live-min`
3 * (milliseconds) skips an event that comes sooner than that after its last
4 * redraw. The board's 10s and 1m choices are this number; the sampler's
5 * pulse comes at its own pace, and the region decides how much of it to show.
6 * Written as a plain function so the page's script embeds it as it is and a
7 * test calls the same code.
8 */
9 export function mayRedraw(lastAt: number, now: number, minMs: number): boolean {
10 // A little slack: pulses and timers drift, and a reading 59.9 s after the
11 // last one must not push a one-minute board to the next reading.
12 return !(minMs > 0) || now - lastAt >= minMs - 2000;
13 }
14
15 /** Milliseconds a board's refresh setting stands for; 0 is no limit. */
16 export const refreshMs = (refresh: string): number =>
17 refresh === "10s" ? 10_000 : refresh === "1m" ? 60_000 : 0;
src/web/pages/backups.ts +6 −5
@@ -31,6 +31,8 @@ import { lastSnapshotOutcome } from "../../snapshot/outcome.ts";
3131 import type { Ctx } from "../../http/context.ts";
3232 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
3333 import { field, readForm, type Form } from "../form.ts";
34 import { liveRegionsJs } from "../client.ts";
35 import { SNAPSHOT_PROGRESS } from "../../core/pulse.ts";
3436 import { html, when, type Html } from "../html.ts";
3537 import { flashTo, page, redirect } from "../layout.ts";
3638 import { btn, card, empty, fileSize, icon, row, time } from "../ui.ts";
@@ -42,11 +44,11 @@ function requireAdmin(ctx: Ctx): Response | undefined {
4244 return undefined;
4345 }
outdated

With moving gone, nothing moves the "A snapshot is being taken … N objects" line while a snapshot runs, so it is reload-only. Make it a live region on an admin-only pulse or event from the snapshot loop (/events already routes machine pulses to admins only). Or document it as reload-to-see.

4446
45 function shell(ctx: Ctx, body: Html, moving = false): Response {
47 function shell(ctx: Ctx, body: Html): Response {
4648 return page({
4749 ctx,
4850 title: "Backups",
49 ...(moving ? { refresh: { seconds: 5 } } : {}),
51 scriptJs: liveRegionsJs,
5052 body: html`<div class="page-head"><h1>Backups</h1></div>
5153 ${settingsLayout(
5254 accountSections("backups", { admin: true }),
@@ -296,7 +298,7 @@ bun run src/snapshot/restore.ts ${snapshots[0].name} /path/to/empty/data</pre>`
296298 fourteen.
297299 </p>
298300 ${keyNote(svc.wraps, snapshots[0])}
299 ${when(
301 <div id="backups-progress" data-live="${SNAPSHOT_PROGRESS}">${when(
300302 svc.progress(),
301303 (p) =>
302304 html`<p class="backups-progress">
@@ -304,7 +306,7 @@ bun run src/snapshot/restore.ts ${snapshots[0].name} /path/to/empty/data</pre>`
304306 ${fileSize(p.bytes)} so far, ${Math.round(p.elapsedMs / 1000)} s
305307 in.
306308 </p>`,
307 )}
309 )}</div>
308310 ${when(
309311 failing,
310312 (f) =>
@@ -379,7 +381,6 @@ bun run src/snapshot/restore.ts ${snapshots[0].name} /path/to/empty/data</pre>`
379381 )
380382 }
381383 ${form}`,
382 svc.progress() !== undefined,
383384 );
384385 }
385386
src/web/pages/boards-view.ts +6 −6
@@ -3,16 +3,18 @@
33 * grid with each panel's chart and, under it, the panels' management (edit,
44 * move, remove) and the board's own (rename, range, refresh, duplicate,
55 * delete). The grid is a live region with an address of its own
6 * (`/boards/:slug/live`): a board that refreshes is refetched on its beat by
7 * the same swap the wall uses, no client framework. Every form posts to
6 * (`/boards/:slug/live`): a board that refreshes is refetched when the sampler
7 * takes a reading (a pulse on the one event stream) by the same swap the wall uses, no client framework. Every form posts to
88 * `boards-edit.ts`. Anyone but a person who is an admin gets the not-found page.
99 */
1010 import { listAllBoards, showBoard } from "../../actions/boards.ts";
1111 import { CHART_NAMES } from "../../boards/chart.ts";
1212 import { MAX_H, MAX_PANELS, MAX_TITLE, MAX_W, RANGES, REFRESHES, type Board, type Panel } from "../../boards/store.ts";
1313 import type { App } from "../../app.ts";
14 import { BOARD_SAMPLED } from "../../core/pulse.ts";
1415 import type { Ctx } from "../../http/context.ts";
1516 import { liveRegionsJs } from "../client.ts";
17 import { refreshMs } from "../live-gate.ts";
1618 import { notFoundPage } from "../chrome.ts";
1719 import { html, raw, when, type Html } from "../html.ts";
1820 import { fragment, page } from "../layout.ts";
@@ -20,7 +22,6 @@ import { btn, card, empty } from "../ui.ts";
2022 import { cellsOf, chartBox, paramsOf, queryFields, readParams, runFor } from "./boards.ts";
2123
2224 const RANGE_MS = { "1h": 3_600_000, "24h": 86_400_000, "7d": 604_800_000, "30d": 2_592_000_000 } as const;
23 const EVERY = { "10s": 10, "1m": 60 } as const;
2425
2526 const option = (value: string, selected: boolean) =>
2627 html`<option value="${value}" ${selected ? raw("selected") : null}>${value}</option>`;
@@ -47,13 +48,12 @@ function drawPanel(app: App, board: Board, panel: Panel): Html {
4748
4849 /** The grid alone: what the page shows and what the live address answers with. */
4950 function grid(app: App, slug: string, board: Board): Html {
50 const every = board.refresh === "off" ? null : EVERY[board.refresh];
5151 return html`<section
5252 class="bgrid"
5353 id="board-grid"
54 ${every === null
54 ${board.refresh === "off"
outdated

This region now redraws on every board.sampled pulse (every 15 s), whatever board.refresh says. 10s and 1m behave the same, so the setting is a lie. Collapse the setting to on/off, or have the region honour its interval: carry it as data, and let the swap skip a pulse that comes sooner than that.

5555 ? null
56 : html`data-live="board.none" data-live-src="/boards/${slug}/live" data-live-every="${String(every)}"`}
56 : html`data-live="${BOARD_SAMPLED}" data-live-src="/boards/${slug}/live" data-live-min="${String(refreshMs(board.refresh))}"`}
5757 >
5858 ${board.panels.length === 0
5959 ? html`<p class="muted">No panels yet. Add one below.</p>`
src/web/pages/browse.ts +7 −11
@@ -1031,10 +1031,9 @@ export function stageList(job: MirrorJob, streamUrl: string): Html {
10311031 /**
10321032 * GET /settings/origins/:id/mirror/:job — a mirror, while it happens.
10331033 *
1034 * With no JavaScript this is a page that refreshes itself every two seconds
1035 * and stops when the job stops. With JavaScript it subscribes to the job's
1036 * own event stream and the checklist moves without a reload. Both render the
1037 * same markup, and the page is correct if the script never arrives.
1034 * With JavaScript it subscribes to the job's own event stream and the
1035 * checklist moves without a reload; nothing polls. Without it the page is the
1036 * job as it stood, and a reload shows where it got to.
10381037 */
10391038 export function mirrorJobPage(ctx: Ctx): Response {
10401039 const denied = accountOnly(ctx);
@@ -1084,8 +1083,7 @@ export function mirrorJobPage(ctx: Ctx): Response {
10841083 </div>`
10851084 : html`<p class="muted small mt">
10861085 This keeps going if you close the page — come back to this link and
1087 it will say where it got to. No JavaScript? This page refreshes
1088 itself every couple of seconds.
1086 it will say where it got to.
10891087 </p>`;
10901088
10911089 // Only a job still going refreshes or streams: a finished one is a page
@@ -1094,11 +1092,9 @@ export function mirrorJobPage(ctx: Ctx): Response {
10941092 return page({
10951093 ctx,
10961094 title: `Mirroring ${job.fullName}`,
1097 ...(running
1098 ? { refresh: { seconds: 2 } }
1099 : job.stage === "done" && mirror !== undefined
1100 ? { refresh: { seconds: 1, url: mirror } }
1101 : {}),
1095 ...(!running && job.stage === "done" && mirror !== undefined
1096 ? { refresh: { seconds: 1, url: mirror } }
1097 : {}),
11021098 body: html`<div class="page-head">
11031099 <h1>Mirroring ${job.fullName}</h1>
11041100 <span class="spacer"></span>
src/web/pages/fleet-graph.ts +2 −2
@@ -17,11 +17,11 @@ import {
1717 import type { Ctx } from "../../http/context.ts";
1818 import { signInFirst } from "../chrome.ts";
1919 import {
20 fleetGraphClientJs,
2120 fleetGraphSection,
2221 selectionQuery,
2322 } from "../fleet-graph.ts";
2423 import { html } from "../html.ts";
24 import { liveRegionsJs } from "../client.ts";
2525 import { fragment, page } from "../layout.ts";
2626 import { btn } from "../ui.ts";
2727
@@ -82,7 +82,7 @@ export function fleetGraphPage(ctx: Ctx): Response {
8282 ${asked.ok ? "" : asked.error}
8383 </p>`
8484 : fleetGraphSection(graph)}`,
85 scriptJs: fleetGraphClientJs,
85 scriptJs: liveRegionsJs,
8686 },
8787 graph === undefined ? 422 : 200,
8888 );
src/web/pages/migrate.ts +34 −26
@@ -392,38 +392,47 @@ function stageRows(job: MirrorJob): Html {
392392 }
393393
394394 /**
395 * GET /migrate/jobs/:job — the clone, while it happens. It refreshes itself
396 * every two seconds until the job stops; done, it lands on the repository
395 * GET /migrate/jobs/:job — the clone, while it happens. It follows the job's
396 * event stream until the job stops; done, it lands on the repository
397397 * with what happened as the flash. A failure stays, with the reason and the
398398 * way back to the form.
399399 */
400400 /**
401 * The job's page keeps itself current without reloading: every two seconds
402 * it asks for itself and swaps the stages in place; when the job is done
403 * the answer is the repository's page, and the browser goes there. Without
404 * a script the meta refresh does the same, a whole page at a time.
401 * The job's page follows the job's own event stream: each stage paints the
402 * moment it happens, and the last one (done or failed) loads the page once
403 * more, which the server answers with the repository or the reason. No
404 * timer, no refetch. The stream's address comes out of the DOM.
405405 */
406406 const migrateJobJs = /* js */ `
407407 (function () {
408408 var box = document.getElementById('migrate-job');
409 if (!box || !window.fetch) return;
410 function tick() {
411 fetch(location.href, { headers: { accept: 'text/html' }, credentials: 'same-origin', redirect: 'follow' })
412 .then(function (r) {
413 if (r.redirected) { location.href = r.url; return null; }
414 return r.ok ? r.text() : null;
415 })
416 .then(function (text) {
417 if (text === null) return;
418 var fresh = new DOMParser().parseFromString(text.replace(/<(style)[^>]*>[\\s\\S]*?<\\/\\1>/gi, ''), 'text/html');
419 var theirs = fresh.getElementById('migrate-job');
420 if (theirs && theirs.innerHTML !== box.innerHTML) box.innerHTML = theirs.innerHTML;
421 if (!fresh.querySelector('meta[http-equiv="refresh"]')) return; // failed, or over: the page stopped asking
422 setTimeout(tick, 2000);
423 })
424 .catch(function () { setTimeout(tick, 4000); });
425 }
426 setTimeout(tick, 2000);
409 if (!box || typeof EventSource === 'undefined') return;
410 var url = box.getAttribute('data-stream');
411 if (!url) return;
412 var rows = Array.prototype.slice.call(box.querySelectorAll('li[data-stage-name]'));
413 var order = rows.map(function (li) { return li.getAttribute('data-stage-name'); });
414 var glyph = { done: '\\u25CF', now: '\\u25D0', todo: '\\u25CB' };
415 var source = new EventSource(url);
416 ['creating', 'fetching', 'crew', 'done', 'failed'].forEach(function (stage) {
417 source.addEventListener('migrate.' + stage, function (event) {
418 var job;
419 try { job = JSON.parse(event.data); } catch (err) { return; }
420 if (job.stage === 'done' || job.stage === 'failed') {
421 source.close();
422 location.replace(location.pathname);
423 return;
424 }
425 var at = order.indexOf(job.stage);
426 rows.forEach(function (li, i) {
427 var state = i < at ? 'done' : i === at ? 'now' : 'todo';
428 li.setAttribute('data-state', state);
429 var dot = li.querySelector('.stage-dot');
430 if (dot) dot.textContent = glyph[state];
431 var note = li.querySelector('.stage-detail');
432 if (note) note.textContent = state === 'now' ? (job.detail || '') : '';
433 });
434 });
435 });
427436 })();
428437 `;
429438
@@ -440,10 +449,9 @@ export function migrationJobPage(ctx: Ctx): Response {
440449 return page({
441450 ctx,
442451 title: `Migrating ${job.fullName}`,
443 ...(failed ? {} : { refresh: { seconds: 2 } }),
444452 scriptJs: migrateJobJs,
445453 body: html`${pageHead(`Migrating ${job.fullName}`)}
446 <div class="narrow-wide" id="migrate-job">
454 <div class="narrow-wide" id="migrate-job" ${failed ? null : html`data-stream="/api/v1/migrate/${job.id}/stream"`}>
447455 ${card(stageRows(job), {
448456 head: html`${icon("download")}
449457 <h2>${job.fullName}</h2>`,
src/web/pages/pull.ts +2 −6
@@ -272,15 +272,11 @@ export function checksLine(
272272 : waiting
273273 ? html`<span>${icon("lock")}${WAITING_WORDS}</span>`
274274 : html`<span>${icon("clock")}No checks on this head yet</span>`;
275 // Its own address: an event or the beat fetches this line, not the page.
276 // While a check runs there is no event for a finished shard, so it also
277 // asks on a beat.
275 // Its own address: an event fetches this line, not the page.
278276 const live =
279277 liveSrc === ""
280278 ? null
281 : html`id="live-checks" data-live="run.*" data-live-src="${liveSrc}"${
282 check.state === "running" || check.state === "queued" ? html` data-live-every="5"` : null
283 }`;
279 : html`id="live-checks" data-live="run.*" data-live-src="${liveSrc}"`;

With the beat gone, nothing refetches this line while a check runs, because a finished shard has no event. The file and test counts freeze until the run ends. That is a visible regression on the page the owner waits on. Pulse or emit when a shard reports, and add that kind here.

284280 return html`<p class="checks-line" ${live}>
285281 ${body}${against}${when(
286282 tier !== "",
src/web/studio/app.ts +3 −12
@@ -274,12 +274,8 @@ export async function studioApp(
274274 // ---- the app itself ----
275275 // `deployTailing` says the head card is tailing production's own deploy,
276276 // narrowly — just the "Now" panel's empty-state words below care about
277 // that distinction. `tailing` says the head card carries any live tail at
278 // all, deploy or a running app's own output (`studio/previews.ts`'s
279 // `productionTail`, #284) — the no-script refresh below must keep the
280 // page moving for either, not only for an agent run's tail beside a "Now"
281 // row.
282 const { head, previews, deployTailing, tailing } = appPanels(
277 // that distinction.
278 const { head, previews, deployTailing } = appPanels(
283279 ctx,
outdated

This comment still describes "the no-script refresh below". This pull removed that refresh, and tailing, which the comment explains, is no longer read here. Trim it to the deployTailing sentence. Then drop tailing from appPanels' return and running from nowCard's (now.ts:74, :330): nothing uses them now.

284280 repo,
285281 record,
@@ -323,7 +319,7 @@ export async function studioApp(
323319 </form>`;
324320
325321 // ---- now: one row per thing, in the five words (studio/now.ts) ----
326 const { card: now, running } = await nowCard(ctx, repo, record, {
322 const { card: now } = await nowCard(ctx, repo, record, {
327323 openPulls,
328324 builderCount: builders.length,
329325 ownerFacts,
@@ -507,10 +503,5 @@ export async function studioApp(
507503 palette: repoPalette(ctx, repo),
508504 body,
509505 scriptJs: `${liveClientJs}\n${liveRegionsJs}\n${appTailJs}`,
510 // The no-script half of the tail: with JavaScript off, the page
511 // refreshes itself while the crew's run goes, the way the run's own page
512 // does; a browser running the script streams lines instead and never
513 // reloads (`layout.ts` writes the refresh inside `<noscript>`).
514 ...(running || tailing ? { refresh: { seconds: 5 } } : {}),
515506 });
516507 }
src/web/studio/now.ts +2 −2
@@ -71,7 +71,7 @@ export async function nowCard(
7171 /** Whether the head card is tailing production's own deploy. */
7272 deployTailing: boolean;
7373 },
74 ): Promise<{ card: Html; running: boolean }> {
74 ): Promise<{ card: Html }> {
7575 const db = ctx.app.db;
7676 const base = repoBase(repo);
7777 const { openPulls, builderCount, ownerFacts, wordCtx, deployTailing } = o;
@@ -327,7 +327,7 @@ export async function nowCard(
327327 <span class="spacer"></span>
328328 ${btn("Every run", { href: `${base}/runs`, size: "sm" })}`,
329329 });
330 return { card: now, running: activeRun !== undefined };
330 return { card: now };
331331 }
332332
333333 // GET /:owner/:name/app/now — the card alone, for the region that shows it.
src/web/studio/previews.ts −2
@@ -284,7 +284,6 @@ export function appPanels(
284284 head: Html;
285285 previews: Html | null;
286286 deployTailing: boolean;
287 tailing: boolean;
288287 } {
289288 const db = ctx.app.db;
290289 const base = repoBase(repo);
@@ -347,7 +346,6 @@ export function appPanels(
347346 head,
348347 previews,
349348 deployTailing: tail.deploying,
350 tailing: tail.box !== undefined,
351349 };
352350 }
353351
src/web/studio/run.ts −4
@@ -384,9 +384,5 @@ export async function runView(
384384 palette: repoPalette(ctx, repo),
385385 body,
386386 scriptJs: studioRunJs,

#2722's first done item asks for run logs to patch from the one /events stream per tab. This page still opens its own per-run log stream, and the app page opens several. Do it here, or split it into a linked issue that #2722 waits on.

387 // The no-script half of a live log: with JavaScript off, the page
388 // refreshes itself while the run is going (`layout.ts` writes it inside
389 // `<noscript>`, so a browser running the stream above never reloads).
390 ...(unfinished ? { refresh: { seconds: 5 } } : {}),
391387 });
392388 }
test/boards-store.test.ts +2 −1
@@ -172,7 +172,8 @@ describe("/boards", () => {
172172 const saved = await post("/boards/fleet-health/settings", { range: "24h", refresh: "10s" });
173173 expect(saved.status).toBe(303);
174174 const body = await (await asAdmin("/boards/fleet-health")).text();
175 expect(body).toContain('data-live-every="10"');
175 expect(body).toContain('data-live="board.sampled"');
176 expect(body).not.toContain("data-live-every");
176177 expect(body).toContain('data-live-src="/boards/fleet-health/live"');
177178 const live = await asAdmin("/boards/fleet-health/live");
178179 expect(live.status).toBe(200);
test/credentials.test.ts +1 −1
@@ -324,7 +324,7 @@ describe("the board", () => {
324324 expect(page.slice(crewAt, apartAt)).toContain("platform (env)");
325325 expect(page.slice(crewAt, apartAt)).not.toContain("trevato-espo");
326326 expect(page.slice(apartAt)).toContain("trevato-espo");
327 expect(page).toContain('data-live="run.*,usage.*"');
327 expect(page).toContain('data-live="run.finished,usage.*"');
328328 expect(page).toContain('data-by="byKind"');
329329 expect(page).toContain("The 10 costliest runs");
330330
test/fleet-graph.test.ts +1 −1
@@ -291,7 +291,7 @@ describe("the graph", () => {
291291 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
292292 const body = await res.text();
293293 expect(body).toContain('id="fleet-graph"');
294 expect(body).toContain('data-src="/fleet/graph/live?repo=alice%2Ftwo"');
294 expect(body).toContain('data-live-src="/fleet/graph/live?repo=alice%2Ftwo"');
295295 expect(body).toContain('data-repo="alice/two"');
296296 expect(body).toContain("Last 24 hours");
297297 expect(body).toContain("in the UTC hour or day it ended");
test/live-pages.test.ts +4 −98
@@ -180,104 +180,10 @@ describe("live browsing pages", () => {
180180 });
181181 });
182182
183 describe("the beat of a region with data-live-every", () => {
184 type Attrs = Record<string, string>;
185 const region = (attrs: Attrs, html: string) => {
186 const r = {
187 id: attrs["id"] ?? "",
188 attrs: { ...attrs },
189 innerHTML: html,
190 getAttribute: (n: string) => r.attrs[n] ?? null,
191 hasAttribute: (n: string) => n in r.attrs,
192 setAttribute: (n: string, v: string) => void (r.attrs[n] = v),
193 removeAttribute: (n: string) => void delete r.attrs[n],
194 get attributes() {
195 return Object.entries(r.attrs).map(([name, value]) => ({ name, value }));
196 },
197 querySelector: () => null,
198 querySelectorAll: () => [],
199 contains: () => false,
200 dispatchEvent: () => true,
201 };
202 return r;
203 };
204
205 /** Runs the script against a fake page; `answers` are the fragments the server gives, in order. */
206 const run = async (js: string, answers: Attrs[]) => {
207 const mine = region(
208 { id: "live-checks", "data-live": "run.*", "data-live-src": "/x/checks-line", "data-live-every": "5" },
209 "running",
210 );
211 let n = 0;
212 let fragment = region({ id: "live-checks" }, "");
213 const timers: Array<() => void> = [];
214 const intervals = new Map<number, () => void>();
215 const cleared: number[] = [];
216 let nextId = 1;
217 const doc = {
218 hidden: false,
219 activeElement: null,
220 querySelectorAll: (sel: string) =>
221 sel === "[data-live-every]"
222 ? "data-live-every" in mine.attrs ? [mine] : []
223 : sel === "[data-live]" ? [mine] : [],
224 getElementById: (id: string) => (id === "live-checks" ? mine : null),
225 createElement: () => ({
226 set innerHTML(_: string) {},
227 content: { querySelector: () => null, getElementById: () => fragment },
228 }),
229 dispatchEvent: () => true,
230 addEventListener: () => {},
231 };
232 const win = {
233 setInterval: (f: () => void) => (intervals.set(nextId, f), nextId++),
234 clearInterval: (id: number) => (intervals.delete(id), void cleared.push(id)),
235 addEventListener: () => {},
236 };
237 class ES {
238 addEventListener() {}
239 close() {}
240 }
241 const fake = {
242 document: doc,
243 window: win,
244 location: { href: "http://x/page" },
245 EventSource: ES,
246 CustomEvent: class {},
247 DOMParser: class {},
248 setTimeout: (f: () => void) => (timers.push(f), 0),
249 clearTimeout: () => {},
250 fetch: async () => {
251 fragment = region(answers[n++] ?? {}, "changed " + n);
252 return { status: 200, ok: true, headers: { get: () => null }, text: async () => "" };
253 },
254 };
255 try { new Function(...Object.keys(fake), js)(...Object.values(fake)); } catch (e) { console.log("ERR", e); }
256 const beat = async () => {
257 for (const f of [...intervals.values()]) f();
258 while (timers.length > 0) timers.shift()!();
259 await new Promise((r) => setTimeout(r, 0));
260 };
261 return { mine, intervals, cleared, beat };
262 };
263
264 test("a swap without the attribute clears the beat and the region stops asking", async () => {
183 describe("no beat", () => {
184 test("a region never asks on a timer of its own: events and pulses are the only cause", async () => {
265185 const { liveRegionsJs } = await import("../src/web/client.ts");
266 const { mine, intervals, cleared, beat } = await run(liveRegionsJs, [{}]);
267 expect(intervals.size).toBe(1);
268 await beat();
269 expect(cleared.length).toBe(1);
270 expect(intervals.size).toBe(0);
271 expect(mine.hasAttribute("data-live-every")).toBe(false);
272 });
273
274 test("a swap that brings the attribute arms one beat, and a repeat does not arm a second", async () => {
275 const { liveRegionsJs } = await import("../src/web/client.ts");
276 const every = { "data-live-every": "5" };
277 const { intervals, cleared, beat } = await run(liveRegionsJs, [every, every]);
278 await beat();
279 await beat();
280 expect(intervals.size).toBe(1);
281 expect(cleared.length).toBe(0);
186 expect(liveRegionsJs).not.toContain("data-live-every");
187 expect(liveRegionsJs).not.toContain("setInterval");
282188 });
283189 });
test/no-polling.test.ts added +241
@@ -0,0 +1,241 @@
1 /**
2 * No forge page polls on a timer (#2722): what moves a page is an event on
3 * the one stream, a pulse the server sends (`core/pulse.ts`), or a click.
4 * The scan reads src/web for the ways a page could ask on a clock, the
5 * stream carries the sampler's pulse to an admin and to nobody else, and a
6 * migration job page follows its job's stream instead of fetching itself.
7 */
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, readdir, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { createUser } from "../src/core/users.ts";
14 import { BOARD_SAMPLED, pulse } from "../src/core/pulse.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16
17 const WEB = new URL("../src/web/", import.meta.url).pathname;
18
19 async function sources(dir: string): Promise<{ path: string; text: string }[]> {
20 const out: { path: string; text: string }[] = [];
21 for (const entry of await readdir(dir, { withFileTypes: true })) {
22 const path = join(dir, entry.name);
23 if (entry.isDirectory()) {
24 if (entry.name !== "vendor") out.push(...(await sources(path)));
25 } else if (entry.name.endsWith(".ts")) out.push({ path: path.slice(WEB.length), text: await Bun.file(path).text() });
26 }
27 return out;
28 }
29
30 describe("src/web asks on no clock", () => {
31 test("no region beats, and no meta refresh reloads", async () => {
32 for (const { path, text } of await sources(WEB)) {
33 if (path === "client.ts" || path === "layout.ts") {
34 // The shell may mention the attribute only to say it is gone.
35 expect(text).not.toMatch(/getAttribute\('data-live-every'\)/);
36 } else expect(text).not.toContain("data-live-every");
37 // A meta refresh is written in layout.ts (a redirect with a url) and by
38 // the service worker's static "restarting" page, which has no forge
39 // page behind it to patch.
40 if (path !== "layout.ts" && path !== "sw.ts") expect(text).not.toContain('http-equiv="refresh"');
41 }
42 });
43
44 test("the only intervals are clocks that fetch nothing", async () => {
45 for (const { path, text } of await sources(WEB)) {
46 for (const m of text.matchAll(/setInterval\(([^)]*)/g)) {
47 // `window.setInterval(tick, 1000)`: the callback is a named clock.
48 expect(`${path}: ${m[1]}`).toMatch(/^client\.ts: tick, /);
49 }
50 }
51 const client = (await sources(WEB)).find((s) => s.path === "client.ts")!.text;
52 for (const m of client.matchAll(/function tick\(\) \{([\s\S]*?)\n \}/g)) {
53 expect(m[1]).not.toMatch(/fetch\(|location\.reload|EventSource/);
54 }
55 });
56
57 test("no script reschedules a fetch of itself", async () => {
58 for (const { path, text } of await sources(WEB)) {
59 expect(`${path}: ${/setTimeout\(\s*(tick|poll|ask)\b[^)]*\)/.test(text)}`).toBe(
60 // The device-flow sign-in waits on a person at another provider; the
61 // server has no event to send for it (client.ts pollJs).
62 path === "client.ts" ? `${path}: true` : `${path}: false`,
63 );
64 }
65 });
66 });
67
68 describe("the sampler's pulse and the migration page", () => {
69 let dataDir: string;
70 let app: App;
71 let servers: Servers;
72 let admin = "";
73 let other = "";
74 const signIn = async (username: string): Promise<string> => {
75 const res = await fetch(`${servers.url}/signin`, {
76 method: "POST",
77 redirect: "manual",
78 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
79 body: new URLSearchParams({ username, password: "a-good-passphrase" }),
80 });
81 return (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
82 };
83
84 beforeAll(async () => {
85 dataDir = await mkdtemp(join(tmpdir(), "forge-nopoll-"));
86 app = createApp({ dataDir, port: 0 });
87 servers = await serve(app);
88 for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) {
89 const u = await createUser(app.db, {
90 origin: "seed", trusted: true, username, email: `${username}@forge.local`,
91 password: "a-good-passphrase", adminIfFirst,
92 });
93 if (!u.ok) throw new Error(u.error);
94 }
95 admin = await signIn("alice");
96 other = await signIn("bob");
97 });
98
99 afterAll(async () => {
100 servers.stop();
101 app.close();
102 await rm(dataDir, { recursive: true, force: true });
103 });
104
105 const heard = async (cookie: string): Promise<string> => {
106 const res = await fetch(`${servers.url}/events`, { headers: { cookie } });
107 const reader = res.body!.getReader();
108 const decoder = new TextDecoder();
109 let text = "";
110 const stop = setTimeout(() => void reader.cancel(), 400);
111 pulse(BOARD_SAMPLED);
112 try {
113 for (;;) {
114 const { value, done } = await reader.read();
115 if (done) break;
116 text += decoder.decode(value);
117 if (text.includes(BOARD_SAMPLED)) break;
118 }
119 } catch {
120 // cancelled: nothing arrived
121 }
122 clearTimeout(stop);
123 await reader.cancel().catch(() => {});
124 return text;
125 };
126
127 test("an admin's tab hears the sample on /events, without an id to replay", async () => {
128 const text = await heard(admin);
129 expect(text).toContain("event: forge");
130 expect(text).toContain(`"kind":"${BOARD_SAMPLED}"`);
131 expect(text).not.toContain("id: ");
132 });
133
134 test("another signed-in person's tab does not", async () => {
135 expect(await heard(other)).not.toContain(BOARD_SAMPLED);
136 });
137
138 test("the migration job page opens its job's stream and carries no refresh", async () => {
139 const { createJob, advance } = await import("../src/origins/jobs.ts");
140 const alice = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'alice'").get()!;
141 const job = createJob("", "octo/thing", { kind: "migrate", actorId: alice.id });
142 advance(job.id, { stage: "fetching", detail: "cloning" });
143 const res = await fetch(`${servers.url}/migrate/jobs/${job.id}`, { headers: { cookie: admin } });
144 expect(res.status).toBe(200);
145 const body = await res.text();
146 expect(body).toContain(`data-stream="/api/v1/migrate/${job.id}/stream"`);
147 expect(body).toContain("new EventSource(url)");
148 expect(body).not.toContain('http-equiv="refresh"');
149 expect(body).not.toContain("setTimeout");
150 expect(body).not.toContain("fetch(location.href");
151 });
152 });
153
154 describe("a board honours its refresh interval", () => {
155 test("a one-minute board skips the sampler's pulses that come sooner", async () => {
156 const { mayRedraw, refreshMs } = await import("../src/web/live-gate.ts");
157 const min = refreshMs("1m");
158 expect(min).toBe(60_000);
159 // Pulses every 15 s (FINE_MS): only about every fourth one redraws.
160 let drawn = 0;
161 let last = 0;
162 for (let t = 15_000; t <= 300_000; t += 15_000) {
163 if (mayRedraw(last, t, min)) { drawn++; last = t; }
164 }
165 expect(drawn).toBe(5);
166 expect(mayRedraw(0, 15_000, refreshMs("10s"))).toBe(true);
167 expect(mayRedraw(1_000, 2_000, 0)).toBe(true);
168 });
169
170 test("the board's region carries its interval and the script embeds the gate", async () => {
171 const { liveRegionsJs } = await import("../src/web/client.ts");
172 expect(liveRegionsJs).toContain("function mayRedraw");
173 expect(liveRegionsJs).toContain("data-live-min");
174 });
175 });
176
177 describe("a shard landing reaches a tab that can read the repo", () => {
178 test("isShardReport names the lines after which the count moved", async () => {
179 const { isShardReport } = await import("../src/checks/progress.ts");
180 expect(isShardReport("── shard 1/4 done (exit 0, 3.2s)")).toBe(true);
181 expect(isShardReport("── shard 1/4 (exit 0, 3.2s): a.test.ts b.test.ts")).toBe(true);
182 expect(isShardReport("── shard 1/4: a.test.ts")).toBe(false);
183 expect(isShardReport(" 12 pass")).toBe(false);
184 });
185
186 test("a repo pulse goes to a reader of that repo and to nobody else", async () => {
187 const dataDir = await mkdtemp(join(tmpdir(), "forge-shard-"));
188 const app = createApp({ dataDir, port: 0 });
189 const servers = await serve(app);
190 try {
191 for (const [username, adminIfFirst] of [["alice", true], ["bob", false], ["carol", false]] as const) {
192 const u = await createUser(app.db, {
193 origin: "seed", trusted: true, username, email: `${username}@forge.local`,
194 password: "a-good-passphrase", adminIfFirst,
195 });
196 if (!u.ok) throw new Error(u.error);
197 }
198 const cookie = async (username: string): Promise<string> => {
199 const res = await fetch(`${servers.url}/signin`, {
200 method: "POST", redirect: "manual",
201 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
202 body: new URLSearchParams({ username, password: "a-good-passphrase" }),
203 });
204 return (res.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
205 };
206 const { createRepo } = await import("../src/core/repos.ts");
207 const owner = app.db.query<{ id: string }, []>("SELECT id FROM user WHERE username = 'bob'").get()!;
208 const made = await createRepo(app.db, app.reposRoot, { ownerId: owner.id, name: "secret", visibility: "private" });
209 if (!made.ok) throw new Error(made.error);
210 const repo = made.value;
211 const { RUN_PROGRESS } = await import("../src/core/pulse.ts");
212 const listen = async (who: string): Promise<string> => {
213 const res = await fetch(`${servers.url}/events`, { headers: { cookie: await cookie(who) } });
214 const reader = res.body!.getReader();
215 const decoder = new TextDecoder();
216 let text = "";
217 const stop = setTimeout(() => void reader.cancel(), 500);
218 setTimeout(() => pulse(RUN_PROGRESS, repo.id), 100);
219 try {
220 for (;;) {
221 const { value, done } = await reader.read();
222 if (done) break;
223 text += decoder.decode(value);
224 if (text.includes(RUN_PROGRESS)) break;
225 }
226 } catch {
227 // cancelled
228 }
229 clearTimeout(stop);
230 await reader.cancel().catch(() => {});
231 return text;
232 };
233 expect(await listen("bob")).toContain(`"kind":"${RUN_PROGRESS}"`);
234 expect(await listen("carol")).not.toContain(RUN_PROGRESS);
235 } finally {
236 servers.stop();
237 app.close();
238 await rm(dataDir, { recursive: true, force: true });
239 }
240 });
241 });
test/pull-checks-line-route.test.ts +7 −7
@@ -110,7 +110,7 @@ test("a viewer who can gets the line, without counts until the log has them", as
110110 const text = await res.text();
111111 expect(text).toContain('id="live-checks"');
112112 expect(text).toContain("Check running");
113 expect(text).toContain('data-live-every="5"');
113 expect(text).not.toContain("data-live-every");
114114 expect(text).not.toContain(" files");
115115 });
116116
@@ -134,13 +134,13 @@ test("the page that draws the line also ships the script that drives it", async
134134 expect(res.status).toBe(200);
135135 const text = await res.text();
136136 expect(text).toContain('id="live-checks"');
137 expect(text).toContain('data-live-every="5"');
138 // liveRegionsJs reads data-live-src and arms the beat; liveClientJs alone does not.
137 expect(text).not.toContain("data-live-every");
138 // liveRegionsJs reads data-live-src and swaps on an event; liveClientJs alone does not.
139139 expect(text).toContain("data-live-src");
140 expect(text).toContain("function arm(");
140 expect(text).toContain("function pull(");
141141 });
142142
143 test("once the check has passed, the line has no beat, no counts, and reads as passed", async () => {
143 test("once the check has passed, the line has no counts, and reads as passed", async () => {
144144 app.db.run("UPDATE run SET state = 'ok', finished_at = ? WHERE id = ?", [
145145 new Date().toISOString(),
146146 runId,
@@ -161,7 +161,7 @@ test("the change page the owner lands on draws the same live line, with the coun
161161 expect(res.status).toBe(200);
162162 const text = await res.text();
163163 expect(text).toContain('id="live-checks"');
164 expect(text).toContain('data-live-every="5"');
164 expect(text).not.toContain("data-live-every");
165165 expect(text).toContain("2 of 170 files · 500 passed, 0 failed");
166 expect(text).toContain("function arm(");
166 expect(text).toContain("function pull(");
167167 });
test/refresh-meta.test.ts +4 −14
@@ -1,23 +1,13 @@
11 /**
2 * A page that changes on its own carries a `meta refresh` for browsers with
3 * no script. A browser running the page's script must never schedule it: a
4 * refresh is set the moment the parser meets the tag, and removing the tag
5 * afterwards does not cancel it — which is how a live run page threw away
6 * the reader's scroll every five seconds. So the reload is written inside
7 * `<noscript>`, and only a redirect (`url`) stands on its own.
2 * A `meta refresh` is a redirect, never a reload: no forge page polls on a
3 * timer. A page that is still moving is patched in place over the event
4 * stream (test/no-polling.test.ts scans for the rest).
85 */
96 import { describe, expect, test } from "bun:test";
107 import { refreshMeta } from "../src/web/layout.ts";
118
129 describe("the refresh meta", () => {
13 test("a reload is for browsers without a script only", () => {
14 const tag = String(refreshMeta({ seconds: 5 })).replace(/\s+/g, " ");
15 expect(tag).toMatch(
16 /^<noscript ?><meta http-equiv="refresh" content="5" ?\/><\/noscript>$/,
17 );
18 });
19
20 test("a redirect stays in force with or without a script", () => {
10 test("a redirect after a delay is all it writes", () => {
2111 const tag = String(refreshMeta({ seconds: 1, url: "/trevato/forge" }));
2212 expect(tag).toContain('content="1; url=/trevato/forge"');
2313 expect(tag).not.toContain("noscript");
test/snapshot-destination.test.ts +3 −1
@@ -171,7 +171,9 @@ describe("the snapshot destination", () => {
171171 html = await page();
172172 }
173173 expect(html).toContain("A snapshot is being taken");
174 expect(html).toContain("http-equiv=\"refresh\"");
174 expect(html).not.toContain("http-equiv=\"refresh\"");
175 // It moves on the snapshot loop's pulse, not on a reload.
176 expect(html).toContain('id="backups-progress" data-live="snapshot.progress"');
175177 expect(html).toMatch(/[1-9]\d* objects/);
176178 await taking;
177179 expect(await page()).not.toContain("A snapshot is being taken");
test/studio-runs.test.ts +7 −8
@@ -943,8 +943,8 @@ describe("the app's page tails the crew's log while it works", () => {
943943 expect(page).not.toContain(">line 0<");
944944 expect(page).toContain(">line 8<");
945945 expect(page).toContain("Holding the last 6 lines here");
946 // No script, no problem: the page keeps refreshing while the run goes.
947 expect(page).toContain('http-equiv="refresh"');
946 // Nothing polls: the page never refreshes itself while the run goes.
947 expect(page).not.toContain('http-equiv="refresh"');
948948
949949 const stream = await get(
950950 `/api/v1/repos/alice/engine/runs/${run.id}/log?follow=1`,
@@ -1135,9 +1135,9 @@ describe("the app's page tails the deploy that is bringing it alive", () => {
11351135 `data-stream="/api/v1/repos/alice/kindling/runs/${deployRun.id}/log?follow=1"`,
11361136 );
11371137 expect(page).toContain("install …");
1138 // No script, no problem: the page keeps refreshing while the deploy
1139 // goes — the actual meta tag, not just the script's own selector text.
1140 expect(page).toMatch(/<meta\s+http-equiv="refresh"/);
1138 // The page never refreshes itself while the deploy goes — the actual
1139 // meta tag, not just the script's own selector text.
1140 expect(page).not.toMatch(/<meta\s+http-equiv="refresh"/);
11411141 // Issue #163: the deploy is plainly going, in the head card above — "Now"
11421142 // does not also claim nothing is happening, and it does not open a
11431143 // second stream of the same lines to say so.
@@ -1208,8 +1208,7 @@ describe("the app's page tails the deploy that is bringing it alive", () => {
12081208 expect(page).toContain('id="app-run-tail"');
12091209 expect(page).not.toContain('class="run-log');
12101210 expect(page).toContain("Production is quiet");
1211 // Still nothing to fetch — the page keeps polling in case that changes.
1212 expect(page).toMatch(/<meta\s+http-equiv="refresh"/);
1211 expect(page).not.toMatch(/<meta\s+http-equiv="refresh"/);
12131212 });
12141213 });
12151214
@@ -1355,7 +1354,7 @@ describe("the app's page tails production's own output while it runs (#284)", ()
13551354 expect(page).not.toContain(">serving request 0<");
13561355 expect(page).toContain(">serving request 8<");
13571356 expect(page).toContain("Holding the last 6 lines here");
1358 expect(page).toMatch(/<meta\s+http-equiv="refresh"/);
1357 expect(page).not.toMatch(/<meta\s+http-equiv="refresh"/);
13591358
13601359 // Issue #284's own point: the run this reads from is long finished —
13611360 // the tail follows the env that points at it, not the run's own state.
test/web-apps.test.ts +2 −2
@@ -360,7 +360,7 @@ describe("apps, runs and the crew on the web", () => {
360360 // forge's own words ("checking out …") are marked as such.
361361 expect(page).toContain('class="ln ln-forge"');
362362 expect(page).toContain('id="run-elapsed"');
363 // The stream and the no-script refresh exist only while it is going.
363 // The stream exists only while it is going; the page never refreshes itself.
364364 // Match the real <meta> / data-stream= attributes — not the same
365365 // strings inside studioRunJs (a bare includes("http-equiv=…") stays
366366 // true after the meta is gone because the script still quotes it).
@@ -380,7 +380,7 @@ describe("apps, runs and the crew on the web", () => {
380380 const after = isGoing();
381381 if (before === after) {
382382 expect(html.includes("data-stream=")).toBe(before);
383 expect(hasMetaRefresh(html)).toBe(before);
383 expect(hasMetaRefresh(html)).toBe(false);
384384 break;
385385 }
386386 if (Date.now() >= deadline) {
test/web-browse.test.ts +2 −2
@@ -493,8 +493,8 @@ describe("browsing an origin repository on the web", () => {
493493 ]) {
494494 expect(running).toContain(stage);
495495 }
496 // The no-JavaScript half: it refreshes itself while the job runs.
497 expect(running).toContain('http-equiv="refresh"');
496 // Nothing polls: the stream below moves the checklist.
497 expect(running).not.toContain('http-equiv="refresh"');
498498 // The enhancement is a static script under the strict CSP — the job it
499499 // watches arrives as a data attribute, never interpolated into the code.
500500 expect(running).toContain(
test/web-origins.test.ts +2 −2
@@ -242,7 +242,7 @@ describe("origins on the web", () => {
242242 expect(html).not.toContain("not-the-right-token");
243243 });
244244
245 test("a job page streams and refreshes only while the job runs; a failed one stands, with the reason and a retry", async () => {
245 test("a job page streams only while the job runs; a failed one stands, with the reason and a retry", async () => {
246246 const id = listOrigins(app.db, getUserByName(app.db, "alice")!.id)[0]!.id;
247247 const running = createJob(id, "octo/still-going");
248248 const live = await (
@@ -251,7 +251,7 @@ describe("origins on the web", () => {
251251 expect(live).toContain(
252252 `data-stream="/api/v1/user/origins/${id}/mirror/${running.id}/stream"`,
253253 );
254 expect(live).toMatch(/<meta[^>]*http-equiv="refresh"/);
254 expect(live).not.toMatch(/<meta[^>]*http-equiv="refresh"/);
255255 advance(running.id, {
256256 stage: "failed",
257257 detail: "",

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs