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

Live time: the run page works again, and every clock counts in the browser (#16458) #16475

opened this

Check · Review · Land · Live — It conflicts with its base. Next: builder, it conflicts with its base.

Conflicts with main

fix/live-time → main 2 commits

Review

Sign in to review this change.
28 files changed +438 −171
docs/design/size-budget.json +16 −16
@@ -1,30 +1,30 @@
11 {
22 "/": {
3 "js": 22016,
3 "js": 22784,
44 "css": 48640
55 },
66 "/explore": {
7 "js": 21760,
7 "js": 22528,
88 "css": 48640
99 },
1010 "/map": {
11 "js": 28672,
11 "js": 29952,
1212 "css": 50304
1313 },
1414 "/:owner/:name": {
15 "js": 38400,
15 "js": 39424,
1616 "css": 48640
1717 },
1818 "/changelog": {
19 "js": 26880,
19 "js": 27904,
2020 "css": 48640
2121 },
2222 "/:owner/:name/next": {
23 "js": 23296,
23 "js": 24320,
2424 "css": 49024
2525 },
2626 "/:owner/:name/space": {
27 "js": 30208,
27 "js": 31488,
2828 "css": 49792
2929 },
3030 "/:owner/:name/space.json": {
@@ -32,31 +32,31 @@
3232 "css": 0
3333 },
3434 "/maintenance": {
35 "js": 21760,
35 "js": 22528,
3636 "css": 48640
3737 },
3838 "/pricing": {
39 "js": 21760,
39 "js": 22528,
4040 "css": 48640
4141 },
4242 "/forges/new": {
43 "js": 21760,
43 "js": 22528,
4444 "css": 48640
4545 },
4646 "/claim": {
47 "js": 24320,
47 "js": 25344,
4848 "css": 48640
4949 },
5050 "/templates": {
51 "js": 21760,
51 "js": 22528,
5252 "css": 48640
5353 },
5454 "/system": {
55 "js": 23808,
55 "js": 24576,
5656 "css": 48640
5757 },
5858 "/feed": {
59 "js": 36352,
59 "js": 37376,
6060 "css": 48640
6161 },
6262 "/board": {
@@ -64,7 +64,7 @@
6464 "css": 48640
6565 },
6666 "/fleet": {
67 "js": 21760,
67 "js": 22528,
6868 "css": 48640
6969 },
7070 "/talk": {
@@ -72,7 +72,7 @@
7272 "css": 56064
7373 },
7474 "/:owner/:name/pulls/:number": {
75 "js": 32000,
75 "js": 32768,
7676 "css": 48640
7777 }
7878 }
src/actions/runs.ts +4
@@ -61,6 +61,10 @@ export function runPayload(run: Run): Record<string, unknown> {
6161 summary: run.summary,
6262 costUsd: run.costUsd,
6363 turns: run.turns,
64 // The small live state a page patches from the event itself (step 1 of the sync path, #16458):
65 // when it started, so its clock counts from there, and when it ended, so the clock stops there.
66 startedAt: run.startedAt,
67 finishedAt: run.finishedAt,
6468 ...(run.placement === "job" ? { placement: run.placement, node: run.node } : {}),
6569 ...(run.issueId === null ? {} : { issueId: run.issueId }),
6670 };
src/core/talk_work.ts +17 −3
@@ -339,6 +339,11 @@ export interface WorkLine {
339339 * not.
340340 */
341341 readonly wall?: { readonly repo: string; readonly number: number };
342 /**
343 * When the run working it started, while its line ends "for N min.": a page counts that on from
344 * here (`workLineHtml`), so the words never wait on the server to move.
345 */
346 readonly since?: string;
342347 }
343348
344349 /** The prefix every hold is logged with (`crew/dispatch.ts`, `crew/week_hold.ts`, `crew/bet_cap.ts`, `checks/scheduler.ts`). */
@@ -457,9 +462,15 @@ export function workLineFor(db: Database, dataDir: string, issue: Issue, now: nu
457462 const run = issue.state === "closed" ? null : lastRun(db, issue);
458463 const hold = run?.state === "queued" ? holdNow(db, dataDir, run.id) : undefined;
459464 if (hold !== undefined) return holdWords(hold, holdReader(db, issue.repoId, reader));
460 return wallLine(db, issue, run, reader) ?? { says: workLine(db, issue, now) };
465 const walled = wallLine(db, issue, run, reader);
466 if (walled !== undefined) return walled;
467 const says = workLine(db, issue, now);
468 return run?.state === "running" && run.started_at !== null && FOR_MINUTES.test(says) ? { says, since: run.started_at } : { says };
461469 }
462470
471 /** The tail `forMinutes` gives a working line, which a page draws as a count. */
472 export const FOR_MINUTES = / for \d+ min\.$/;
473
463474 /**
464475 * The pull its run pushed, when the access wall holds it on its head (#7847): what it would open,
465476 * in the wall's own words, and for a reader who may answer, the pull to answer it on.
@@ -610,7 +621,7 @@ export interface RunsSeen {
610621 export function paneCrew(db: Database, dataDir: string, repoId: string, reader: User | undefined, seen: RunsSeen): PaneCrew | undefined {
611622 if (!seen.runs) return undefined;
612623 const run = db
613 .query<{ id: string; state: string; actor_id: string | null; issue: number | null }, [string]>("SELECT r.id, r.state, r.actor_id, i.number AS issue FROM run r LEFT JOIN issue i ON i.id = r.issue_id WHERE r.repo_id = ?1 AND r.kind = 'agent' ORDER BY r.id DESC LIMIT 1")
624 .query<{ id: string; state: string; actor_id: string | null; started_at: string | null; issue: number | null }, [string]>("SELECT r.id, r.state, r.actor_id, r.started_at, i.number AS issue FROM run r LEFT JOIN issue i ON i.id = r.issue_id WHERE r.repo_id = ?1 AND r.kind = 'agent' ORDER BY r.id DESC LIMIT 1")
614625 .get(repoId);
615626 if (run === null) return undefined;
616627 const steps: CrewItem[] = seen.logs
@@ -629,7 +640,10 @@ export function paneCrew(db: Database, dataDir: string, repoId: string, reader:
629640 const hold = holdNow(db, dataDir, run.id);
630641 return hold === undefined ? { ...at, state: "queued", line: { says: "Queued for the crew: it starts when a builder is free." } } : { ...at, state: "queued", held: true, line: holdWords(hold, holdReader(db, repoId, reader)) };
631642 }
632 if (run.state === "running") return { ...at, state: "running", line: { says: `${who === "the crew" ? "The crew" : who} is working.` } };
643 if (run.state === "running") {
644 const says = `${who === "the crew" ? "The crew" : who} is working${forMinutes(run.started_at, Date.now())}.`;
645 return { ...at, state: "running", line: run.started_at === null ? { says } : { says, since: run.started_at } };
646 }
633647 if (run.state === "ok") return { ...at, state: "ok", line: { says: "The crew finished this run." } };
634648 return { ...at, state: "failed", line: { says: "The crew's run did not finish." } };
635649 }
src/web/asset.ts +17
@@ -21,6 +21,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, s
2121 import { join } from "node:path";
2222 import { sha256 } from "../kernel/hash.ts";
2323 import { encodeOnce, MIN_BYTES, negotiate } from "../http/compress.ts";
24 import { defect } from "../kernel/error.ts";
2425 import { createLog } from "../kernel/log.ts";
2526 import { beaconJs } from "./beacon.ts";
2627 import { shellJs } from "./client.ts";
@@ -265,6 +266,7 @@ export function pageScriptAsset(js: string, dataDir?: string): FileAsset {
265266 const key = sha256(body);
266267 let asset = pageScripts.get(key);
267268 if (asset === undefined) {
269 parses(body);
268270 asset = fileAsset("page", "js", body, "text/javascript; charset=utf-8");
269271 remember(key, asset);
270272 }
@@ -272,6 +274,21 @@ export function pageScriptAsset(js: string, dataDir?: string): FileAsset {
272274 return asset;
273275 }
274276
277 /**
278 * A page script is composed from many template strings, where one unescaped `\n` is a real line
279 * break inside a JavaScript string and the whole script dies in the browser without a word on the
280 * server: the run page was dead for days so (#16477). Each composed script is compiled once, never
281 * run; one that does not parse fails every test that renders it, and is said loudly in production.
282 */
283 function parses(body: string): void {
284 try {
285 new Function(body);
286 } catch (error) {
287 if (process.env["NODE_ENV"] === "test") defect("page_script_syntax", `a page script does not parse: ${String(error)}`);
288 log.error("web.page_script_does_not_parse", { error: String(error) });
289 }
290 }
291
275292 function remember(key: string, asset: FileAsset): void {
276293 pageScripts.set(key, asset);
277294 pageScriptsByName.set(asset.name, asset);
src/web/client.ts +40 −69
@@ -16,6 +16,7 @@ import { actNowJs } from "./act_now.ts";
1616 import { FORM_BUSY_JS } from "./form_busy.ts";
1717 import { pickJs } from "./pick.ts";
1818 import { foldJs } from "./fold.ts";
19 import { liveTimeJs } from "./live_time_client.ts";
1920 import { imageViewJs } from "./render/image.ts";
2021 import { STAGE_BADGE_JS } from "./stage-row.ts";
2122 import { overlayHostJs } from "./overlay_host.ts";
@@ -124,35 +125,6 @@ export const mirrorJs = /* js */ `
124125 * so a third live log never grows a third copy of it —
125126 * interpolated inline, so \`who\` closes over whichever script uses it.
126127 */
127 /**
128 * The clock beside a run's own log: elapsed time ticks while it goes, and
129 * stops at "took" — under ten seconds in tenths, matching \`durationText\`
130 * (\`pages/runs.ts\`) exactly, since the two paint the very same number
131 * first server-side, then live; a mismatched rounding here would flicker
132 * the instant this script takes over. Used by \`studioRunJs\`.
133 */
134 const elapsedTickJs = /* js */ `
135 function tick() {
136 var elapsed = document.getElementById('run-elapsed');
137 if (!elapsed) return;
138 var started = Date.parse(elapsed.getAttribute('data-started') || '');
139 if (!started) return;
140 var finished = Date.parse(elapsed.getAttribute('data-finished') || '');
141 var end = finished || Date.now();
142 var ms = Math.max(0, end - started);
143 var text;
144 if (ms < 10000) {
145 text = (ms / 1000).toFixed(1) + 's';
146 } else {
147 var s = Math.round(ms / 1000);
148 text = s < 60 ? s + 's' : s < 3600 ? Math.floor(s / 60) + 'm ' + (s % 60) + 's' : Math.floor(s / 3600) + 'h ' + Math.floor((s % 3600) / 60) + 'm';
149 }
150 elapsed.textContent = (finished ? 'took ' : 'running for ') + text;
151 }
152 var clock = window.setInterval(tick, 100);
153 tick();
154 `;
155
156128 const logLineJs = /* js */ `
157129 var FORGE = /^(claude:|done:|failed:|paused|declined:|cloning |branch |forked |pushing |push refused|clone kept|nothing to propose|opened pull|updated pull|committed the|could not|checking out|deploy |data: |\\$ |session |the session|interrupted|passed in|install |test |start |ready |process |timing: )/;
158130 function line(kind, speaker, fill, variant) {
@@ -266,8 +238,29 @@ export const studioRunJs = /* js */ `
266238 if (cancel) cancel.hidden = true;
267239 if (stop) stop.hidden = true;
268240 if (pulse && pulse.parentNode) pulse.parentNode.removeChild(pulse);
241 clockFrom(run);
242 }
243
244 // The run's clock, from the event's own fields (step 1 of the sync path): counting from its
245 // start once it starts, stopped at its end once it ends; the one clock (live_time_client.ts)
246 // draws the words. A run that started while the page was open gets its clock then.
247 function clockFrom(run) {
269248 var elapsed = document.getElementById('run-elapsed');
270 if (elapsed && !elapsed.getAttribute('data-finished')) elapsed.setAttribute('data-finished', new Date().toISOString());
249 if (!elapsed || !run.startedAt) return;
250 var counted = elapsed.querySelector('time[data-count]');
251 if (!counted) {
252 counted = document.createElement('time');
253 counted.setAttribute('data-count', 'elapsed');
254 counted.setAttribute('datetime', run.startedAt);
255 elapsed.textContent = 'running for ';
256 elapsed.appendChild(counted);
257 elapsed.hidden = false;
258 }
259 if (run.state !== 'queued' && run.state !== 'running' && !counted.getAttribute('data-end')) {
260 counted.setAttribute('data-end', run.finishedAt || new Date().toISOString());
261 if (elapsed.firstChild && elapsed.firstChild.nodeType === 3) elapsed.firstChild.textContent = 'took ';
262 }
263 if (window.forgeTimes) window.forgeTimes();
271264 }
272265
273266 ${logLineJs}
@@ -280,8 +273,6 @@ export const studioRunJs = /* js */ `
280273 if (follow) toEnd(); else if (jump) jump.hidden = false;
281274 }
282275
283 ${elapsedTickJs}
284
285276 // A check's step rows are server-derived from the log; when a line that
286277 // can move them lands (a command's echo, the shard runner's banner or a
287278 // shard header) or the run ends, the rows are fetched again and swapped in.
@@ -371,7 +362,7 @@ export const studioRunJs = /* js */ `
371362 fetch(logUrl, { credentials: 'same-origin' })
372363 .then(function (r) { return r.ok ? r.text() : ''; })
373364 .then(function (body) {
374 var all = body.split('\n');
365 var all = body.split('\\n');
375366 if (all[all.length - 1] === '') all.pop();
376367 all.slice(have).forEach(put);
377368 })
@@ -391,7 +382,15 @@ export const studioRunJs = /* js */ `
391382 });
392383 document.addEventListener('forge:event', function (e) {
393384 var d = e.detail;
394 if (!d || d.kind !== 'run.finished' || !d.payload || d.payload.runId !== runId) return;
385 if (!d || !d.payload || d.payload.runId !== runId) return;
386 if (d.kind === 'run.started') {
387 var word = document.getElementById('run-word');
388 if (word) { var w = studioWord(d.payload); word.setAttribute('data-word', w); word.setAttribute('data-variant', variantFor(w)); word.textContent = w; }
389 if (live) live.setAttribute('data-state', d.payload.state);
390 clockFrom(d.payload);
391 return;
392 }
393 if (d.kind !== 'run.finished') return;
395394 paint(d.payload);
396395 if (stepsTimer) { window.clearTimeout(stepsTimer); stepsTimer = 0; }
397396 steps();
@@ -402,8 +401,6 @@ export const studioRunJs = /* js */ `
402401 var t = steer.querySelector('textarea');
403402 if (t) t.placeholder = 'Tell ' + who + ' for its next run';
404403 }
405 window.clearInterval(clock);
406 tick();
407404 });
408405 })();
409406 `;
@@ -2317,7 +2314,7 @@ const shellCore = /* js */ `
23172314 `;
23182315
23192316 /** The shell and the one script that makes actions answer at once (`act_now.ts`). */
2320 export const shellJs = `${shellCore}\n${actNowJs}\n${pickJs}\n${foldJs}\n${FORM_BUSY_JS}`;
2317 export const shellJs = `${shellCore}\n${actNowJs}\n${pickJs}\n${foldJs}\n${FORM_BUSY_JS}\n${liveTimeJs}`;
23212318
23222319 /**
23232320 * Live regions. A page marks the parts of itself that change while it is
@@ -2339,42 +2336,16 @@ export const boardJs = /* js */ `
23392336 if (!board) return;
23402337 var doc = document;
23412338
2342 // ---- clocks: the corner, every run's elapsed, every relative time ----
2339 // ---- the corner clock; every run's elapsed and relative time is the one clock's ----
23432340 var clock = doc.getElementById('board-clock');
23442341 function two(n) { return (n < 10 ? '0' : '') + n; }
2345 function span(s) {
2346 return s < 60 ? s + 's'
2347 : s < 3600 ? Math.floor(s / 60) + 'm ' + two(s % 60) + 's'
2348 : Math.floor(s / 3600) + 'h ' + two(Math.floor((s % 3600) / 60)) + 'm';
2349 }
2350 // The same words the server used, so a swap never changes a row's voice.
2351 function ago(s) {
2352 if (s < 60) return 'just now';
2353 if (s < 3600) return Math.floor(s / 60) + 'm ago';
2354 if (s < 86400) return Math.floor(s / 3600) + 'h ago';
2355 if (s < 86400 * 30) return Math.floor(s / 86400) + 'd ago';
2356 if (s < 86400 * 365) return Math.floor(s / (86400 * 30)) + 'mo ago';
2357 return Math.floor(s / (86400 * 365)) + 'y ago';
2358 }
23592342 function tick() {
2360 var now = Date.now();
2361 if (clock) {
2362 var d = new Date(now);
2363 clock.textContent = two(d.getHours()) + ':' + two(d.getMinutes());
2364 clock.setAttribute('datetime', d.toISOString());
2365 }
2366 Array.prototype.forEach.call(board.querySelectorAll('[data-started]'), function (el) {
2367 var t = Date.parse(el.getAttribute('data-started') || '');
2368 if (t) el.textContent = span(Math.max(0, Math.round((now - t) / 1000)));
2369 });
2370 Array.prototype.forEach.call(board.querySelectorAll('time[datetime]'), function (el) {
2371 if (el === clock) return;
2372 var t = Date.parse(el.getAttribute('datetime') || '');
2373 if (t) el.textContent = ago(Math.max(0, (now - t) / 1000));
2374 });
2343 if (!clock) return;
2344 var d = new Date();
2345 clock.textContent = two(d.getHours()) + ':' + two(d.getMinutes());
2346 clock.setAttribute('datetime', d.toISOString());
23752347 }
2376 // One interval for the page, set once: each tick reads whatever cards are
2377 // on the wall right then, so a swap never arms a second clock.
2348 // The corner's minute, read once a second: one interval for the page, set once.
23782349 window.setInterval(tick, 1000);
23792350 tick();
23802351 // A swapped region carries fresh rows: their clocks start at once, and
src/web/live.ts +6 −1
@@ -440,7 +440,12 @@ export const liveClientJs = /* js */ `
440440 function movesPull(data) {
441441 if (thread !== 'pull' || !data || !data.payload) return false;
442442 if (data.kind === 'pull.merged') return String(data.payload.number) === String(number);
443 if (data.kind.indexOf('run.') === 0) return data.payload.env === 'pull-' + number;
443 if (data.kind.indexOf('run.') === 0) {
444 // A crew run on this pull (its issue is the pull) moves the line that says who works on it.
445 var on = document.querySelector('#pull-check [data-crew-on]');
446 if (data.payload.kind === 'agent') return !!on && data.payload.issueId === on.getAttribute('data-crew-on');
447 return data.payload.env === 'pull-' + number;
448 }
444449 if (data.kind === 'app.serving') {
445450 return data.payload.env === 'production' && !!head && data.payload.commitOid === head;
446451 }
src/web/live_time_client.ts added +64
@@ -0,0 +1,64 @@
1 /**
2 * The one clock in the browser (#16458): every `<time datetime data-count>` the server drew
3 * (`time()` in `time_element.ts`) is redrawn from its own timestamp, so a counter never waits on
4 * the server to move and never skips a second.
5 *
6 * - `data-count="elapsed"` counts up: 9s, 1m 05s, 2h 04m (`elapsedWords`); `data-end` stops it.
7 * - `data-count="span"` is the flow's age: 45s, 12m, 3h 5m (`flow/pipeline.ts` span).
8 * - `data-count="ago"` is relative words: just now, 4m ago (`timeAgo`).
9 *
10 * Seconds are counted on the wall clock (`floor(now) - floor(start)`), and the next redraw is set
11 * for just past the next wall-clock second at which any shown text changes: once a second while a
12 * count shows seconds, else at the next minute it crosses. A hidden tab draws nothing and holds no
13 * timer; showing it draws at once. Display only: nothing here fetches, so the no-polling rule
14 * holds (`test/no-polling.test.ts`). Without the script the server's words stand.
15 */
16 export const liveTimeFormatsJs = /* js */ `
17 function forgeTwo(n) { return n < 10 ? '0' + n : '' + n; }
18 function forgeElapsed(s) { return s < 60 ? s + 's' : s < 3600 ? Math.floor(s / 60) + 'm ' + forgeTwo(s % 60) + 's' : Math.floor(s / 3600) + 'h ' + forgeTwo(Math.floor(s % 3600 / 60)) + 'm'; }
19 function forgeSpan(s) {
20 var m = Math.floor(s / 60), h = Math.floor(m / 60);
21 return s < 60 ? s + 's' : m < 60 ? m + 'm' : h < 48 ? (m % 60 ? h + 'h ' + m % 60 + 'm' : h + 'h') : Math.floor(h / 24) + 'd ' + h % 24 + 'h';
22 }
23 function forgeAgo(s) {
24 var m = Math.floor(s / 60), h = Math.floor(m / 60), d = Math.floor(h / 24), mo = Math.floor(d / 30);
25 return s < 60 ? 'just now' : m < 60 ? m + 'm ago' : h < 24 ? h + 'h ago' : d < 30 ? d + 'd ago' : mo < 12 ? mo + 'mo ago' : Math.floor(mo / 12) + 'y ago';
26 }
27 `;
28
29 /**
30 * The clock itself. The next redraw is one second on while any count shows seconds (an elapsed
31 * under an hour, a span under a minute), else when the soonest count crosses its next minute.
32 */
33 export const liveTimeJs = /* js */ `
34 (function () {
35 if (window.forgeTimes) return;
36 ${liveTimeFormatsJs}
37 var doc = document, timer = 0, W = { elapsed: forgeElapsed, span: forgeSpan, ago: forgeAgo };
38 function draw() {
39 timer = 0;
40 var now = Math.floor(Date.now() / 1000), next = 0;
41 Array.prototype.forEach.call(doc.querySelectorAll('time[data-count]'), function (el) {
42 var k = el.getAttribute('data-count'), from = Date.parse(el.getAttribute('datetime') || ''), end = Date.parse(el.getAttribute('data-end') || '');
43 if (!W[k] || !from) return;
44 var s = Math.max(0, (end ? Math.floor(end / 1000) : now) - Math.floor(from / 1000)), t = W[k](s);
45 if (el.textContent !== t) el.textContent = t;
46 if (end) return;
47 var wait = (k === 'elapsed' && s < 3600) || (k === 'span' && s < 60) ? 1 : 60 - s % 60;
48 if (!next || wait < next) next = wait;
49 });
50 if (next && !doc.hidden) timer = setTimeout(draw, next * 1000 - Date.now() % 1000 + 5);
51 }
52 function again() { clearTimeout(timer); timer = 0; if (!doc.hidden) draw(); }
53 window.forgeTimes = again;
54 doc.addEventListener('visibilitychange', again);
55 // Whatever puts a counted time on the page (a stream's swap, a script's row), it counts at once.
56 if (window.MutationObserver) new MutationObserver(function (ms) {
57 for (var i = 0; i < ms.length; i++) for (var j = 0; j < ms[i].addedNodes.length; j++) {
58 var n = ms[i].addedNodes[j];
59 if (n.nodeType === 1 && (n.matches('time[data-count]') || n.querySelector('time[data-count]'))) return again();
60 }
61 }).observe(doc.documentElement, { childList: true, subtree: true });
62 if (doc.readyState === 'loading') doc.addEventListener('DOMContentLoaded', again); else again();
63 })();
64 `;
src/web/pages/board.ts +1 −4
@@ -765,10 +765,7 @@ async function working(ctx: Ctx, scope: BoardScope): Promise<Html> {
765765 () => html` · <span class="num">${money(run.costUsd)}</span>`,
766766 )}`,
767767 ],
768 trail: html`${wordBadge(word)}<span
769 class="num"
770 data-started="${at(run)}"
771 ></span>`,
768 trail: html`${wordBadge(word)}<span class="num">${time(at(run), { count: "elapsed" })}</span>`,
772769 });
773770 });
774771 return region(
src/web/pages/board_style.ts +1 −1
@@ -20,7 +20,7 @@ export const boardCss = /* css */ `
2020 #returns-graph { display: inline-flex; align-items: center; min-height: 44px; padding-inline: 8px; }
2121 .board #board-live { display: inline-flex; align-items: center; }
2222 .board #board-clock { min-width: 5ch; text-align: right; }
23 .board [data-started] { min-width: 7ch; text-align: right; }
23 .board [data-count="elapsed"] { min-width: 7ch; text-align: right; }
2424 .board-grid { flex: 1; display: grid; gap: var(--pad); padding: 16px var(--pad) var(--pad); min-height: 0; }
2525 .board-region { min-width: 0; min-height: 0; display: flex; flex-direction: column; gap: 12px; }
2626 .board-region > h2 { display: flex; align-items: center; gap: 8px; margin: 0; }
src/web/pages/home_flow.ts +4 −4
@@ -104,12 +104,12 @@ const query = (only: string | null, mine = false): string => `${only === null ?
104104 const waitsOf = (url: URL): boolean => url.searchParams.get("waits") === "me";
105105
106106 /**
107 * A stretch of time as a clock the page keeps: the words the server uses, redrawn by the page's
108 * script on any event.
107 * A stretch of time as a clock the page keeps: the words the server uses, then counted on in the
108 * browser from its timestamp (`live_time_client.ts`), never waiting on an event.
109109 */
110110 function age(iso: string, now: number): Html {
111111 const at = Date.parse(iso);
112 return time(new Date(at).toISOString(), { class: "hf-age", text: span(now - at) });
112 return time(new Date(at).toISOString(), { class: "hf-age", text: span(now - at), count: "span" });
113113 }
114114
115115 const TONE_WORD = {
@@ -339,7 +339,7 @@ export function stripRegion(picture: LanePicture, viewer: StripViewer, dataDir:
339339 ${fig("Median open to landed", lead === null ? "—" : duration(lead * 3_600_000), lead === null ? "nothing landed in 24 hours" : `median of ${count(strip!.lead.landed)} ${strip!.lead.landed === 1 ? "change" : "changes"}, 24 hours`, "/boards")}
340340 ${fig("Crew running", b.slots === 0 ? count(b.running) : `${count(b.running)} of ${count(b.slots)}`, b.slots === 0 ? "no builder slots set" : idle === null ? "builders at work now" : `idle: ${idle.word}`, idle === null ? "/settings/crew" : idle.href)}
341341 ${fig("Week used", week === null ? "—" : week.value, week === null ? "the week is not read yet" : week.note, "/settings/crew", null, week?.attn === true ? "attn" : null)}
342 ${fig("Live version", version === UNSTAMPED ? "—" : version, html`live ${time(BOOTED, { class: "hf-age-ago", text: span(now - Date.parse(BOOTED)) })} · ${proof.text}`, "/releases", null, proof.tone)}
342 ${fig("Live version", version === UNSTAMPED ? "—" : version, html`live ${time(BOOTED, { class: "hf-age-ago", text: span(now - Date.parse(BOOTED)), count: "span" })} · ${proof.text}`, "/releases", null, proof.tone)}
343343 </div>
344344 </section>`;
345345 }
src/web/pages/home_flow_client.ts +2 −28
@@ -30,29 +30,7 @@ export const homeFlowJs = /* js */ `
3030 var doc = document;
3131 var calm = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
3232
33 // ---- clocks: the same words the server used (flow/pipeline.ts span) ----
34 function span(ms) {
35 var s = Math.max(0, Math.round(ms / 1000));
36 if (s < 60) return s + 's';
37 var m = Math.floor(s / 60);
38 if (m < 60) return m + 'm';
39 var h = Math.floor(m / 60);
40 if (h < 48) return m % 60 === 0 ? h + 'h' : h + 'h ' + (m % 60) + 'm';
41 return Math.floor(h / 24) + 'd ' + (h % 24) + 'h';
42 }
43 var lastClock = 0;
44 function clocks(force) {
45 var now = Date.now();
46 // Events come in bursts: the clocks are drawn at most every few seconds.
47 if (!force && now - lastClock < 4000) return;
48 lastClock = now;
49 Array.prototype.forEach.call(root.querySelectorAll('time[datetime]'), function (el) {
50 var t = Date.parse(el.getAttribute('datetime') || '');
51 if (!t) return;
52 var text = span(now - t);
53 if (el.textContent !== text) el.textContent = text;
54 });
55 }
33 // Every age on the page is a <time data-count> the one clock redraws (live_time_client.ts).
5634
5735 // ---- moving: where every tile was, in page coordinates ----
5836 var seen = {};
@@ -88,13 +66,10 @@ export const homeFlowJs = /* js */ `
8866 }
8967 doc.addEventListener('forge:swapped', function (e) {
9068 var lane = e.target && e.target.closest ? e.target.closest('.lane') : null;
91 clocks(true);
9269 if (lane) glide(lane); else remember();
9370 afterSwap();
9471 });
95 doc.addEventListener('forge:event', function () { clocks(false); });
96 doc.addEventListener('visibilitychange', function () { if (!doc.hidden) clocks(true); });
97 window.addEventListener('pageshow', function () { clocks(true); });
72 window.addEventListener('pageshow', function () { if (window.forgeTimes) window.forgeTimes(); });
9873
9974 // ---- the dot: whether the stream is connected ----
10075 var live = doc.getElementById('hf-live');
@@ -329,6 +304,5 @@ export const homeFlowJs = /* js */ `
329304 // A lane's "Show all N" is the disclose behavior (behaviors.ts); the lane keeps data-open through every redraw.
330305 root.setAttribute('data-js', '');
331306 remember();
332 clocks(true);
333307 })();
334308 ${speakJs}`;
src/web/pages/home_table.ts +1 −1
@@ -86,7 +86,7 @@ const TONE_DOT = {
8686 function age(iso: string | null, now: number): Html {
8787 if (iso === null) return html`<span class="muted">—</span>`;
8888 const at = Date.parse(iso);
89 return time(new Date(at).toISOString(), { class: "hf-age", text: span(now - at) });
89 return time(new Date(at).toISOString(), { class: "hf-age", text: span(now - at), count: "span" });
9090 }
9191
9292 const HEAD: Record<Column, string> = {
src/web/pages/pull.ts +9 −1
@@ -364,7 +364,7 @@ export function checksLine(
364364 ${run ? queuedPhrase(run.createdAt) : "queued"}${place === "" ? "" : `, ${place}`}</span
365365 >${link}`
366366 : check.state === "running"
367 ? html`<span class="now">${icon("loader")}${words ?? "Check running"}</span
367 ? html`<span class="now">${icon("loader")}${run?.kind === "check" && run.state === "running" ? runningWords(run, progress) : (words ?? "Check running")}</span
368368 >${link}`
369369 : check.state === "cancelled"
370370 ? html`<span>${icon("ban")}Check cancelled</span>${link}`
@@ -392,6 +392,14 @@ export function checksLine(
392392 </p>`;
393393 }
394394
395 /**
396 * A running check's words with its length counting in the browser (`live_time_client.ts`), from
397 * its start, every second: the line itself is fetched again only when the run says something.
398 */
399 function runningWords(run: { readonly startedAt: string | null; readonly createdAt: string }, progress: string): Html {
400 return html`Check running · ${time(run.startedAt ?? run.createdAt, { count: "elapsed" })}${progress === "" ? "" : ` · ${progress}`}`;
401 }
402
395403 /** One muted line when the merge queue holds the pull as red alone; nothing otherwise. */
396404 export function redAloneLine(mark: RedMark | undefined): Html {
397405 if (mark === undefined) return html``;
src/web/studio/change.ts +30
@@ -9,6 +9,7 @@
99 * bigger.
1010 */
1111
12 import type { Database } from "bun:sqlite";
1213 import { pausedSentence } from "../../crew/paused_now.ts";
1314 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1415 import { cardPath } from "../og/path.ts";
@@ -486,6 +487,7 @@ async function pullPanels(ctx: Ctx, repo: Repo, pull: Pull, spent: Spent = newSp
486487 const checkLine = html`<p
487488 class="studio-pull-check"
488489 data-head="${pull.mergedOid ?? pull.headOid}"
490 data-crew-on="${pull.id}"
489491 >
490492 ${wordDot(word)}
491493 <span class="word-text" data-pull-word>${word === "told" ? "open" : word}</span>
@@ -501,6 +503,7 @@ async function pullPanels(ctx: Ctx, repo: Repo, pull: Pull, spent: Spent = newSp
501503 html`<span class="sep" aria-hidden="true">·</span
502504 ><a href="${base}/runs/${d.id}">deploy ${d.commitOid.slice(0, 7)}</a>`,
503505 )}
506 ${when(tick(spent, "checks", () => crewOn(db, pull.id)), (c) => crewLine(base, c))}
504507 </p>`;
505508
506509 const preview = tick(spent, "preview", () =>
@@ -521,6 +524,33 @@ async function pullPanels(ctx: Ctx, repo: Repo, pull: Pull, spent: Spent = newSp
521524 };
522525 }
523526
527 /** The crew's run on this pull now, queued or working: who, and since when. */
528 interface CrewOn { readonly id: string; readonly state: "queued" | "running"; readonly who: string; readonly since: string }
529
530 function crewOn(db: Database, pullId: string): CrewOn | undefined {
531 const row = db
532 .query<{ id: string; state: "queued" | "running"; who: string | null; since: string }, [string]>(
533 `SELECT r.id, r.state, u.username AS who, COALESCE(r.started_at, r.created_at) AS since FROM run r
534 LEFT JOIN user u ON u.id = r.actor_id
535 WHERE r.issue_id = ?1 AND r.kind = 'agent' AND r.state IN ('queued', 'running')
536 ORDER BY r.id DESC LIMIT 1`,
537 )
538 .get(pullId);
539 return row === null ? undefined : { id: row.id, state: row.state, who: row.who ?? "the crew", since: row.since };
540 }
541
542 /**
543 * The line a pull says while the crew works on it (#16458): who, counting from when it started
544 * (`time()`'s elapsed, redrawn each second in the browser), and its run. It moves with the run's
545 * own events: the page's live client fetches the state again on any agent run on this pull.
546 */
547 function crewLine(base: string, c: CrewOn): Html {
548 return html`<span class="sep" aria-hidden="true">·</span
549 ><a href="${base}/runs/${c.id}" data-crew-run="${c.id}"
550 >${c.state === "running" ? html`${c.who} is working on it · ${time(c.since, { count: "elapsed" })}` : html`queued for ${c.who}`}</a
551 >`;
552 }
553
524554 /**
525555 * GET /:owner/:name/pulls/:number/state — the check line and the Preview
526556 * card, bare. The page's live client fetches it when the change merges, when
src/web/studio/run.ts +7 −11
@@ -220,17 +220,13 @@ export async function runView(
220220 >${run.turns} turn${run.turns === 1 ? "" : "s"}</span
221221 >`,
222222 )}
223 ${when(
224 duration,
225 (d) =>
226 html`<span
227 class="num"
228 id="run-elapsed"
229 data-started="${run.startedAt ?? ""}"
230 data-finished="${run.finishedAt ?? ""}"
231 >${run.finishedAt === null ? "running for" : "took"} ${d}</span
232 >`,
233 )}
223 ${duration === undefined
224 ? html`<span class="num" id="run-elapsed" hidden></span>`
225 : html`<span class="num" id="run-elapsed"
226 >${run.finishedAt === null || run.startedAt === null
227 ? html`running for ${run.startedAt === null ? duration : time(run.startedAt, { count: "elapsed" })}`
228 : html`took ${duration}`}</span
229 >`}
234230 </div>
235231 <p class="mt" id="run-summary">${stoppedLine(run) ?? run.summary}${when(run.state === "cancelled", () => endedTail(run, word === "stopping"))}</p>
236232 ${when(wayIn(ctx.app, ctx.auth.user, run.summary, repo), (way) => html`<div class="small" id="run-way">${blockedWay(way)}</div>`)}
src/web/talk_peek.ts +2 −2
@@ -20,7 +20,7 @@ import { notePhase, takeSessionTime } from "../core/route_timing.ts";
2020 import { fragment } from "./layout.ts";
2121 import { liveCrewRows } from "../actions/crew_now.ts";
2222 import { crewLine } from "./crew_now.ts";
23 import { workLine, workLineFor, type WorkLine } from "../core/talk_work.ts";
23 import { FOR_MINUTES, workLine, workLineFor, type WorkLine } from "../core/talk_work.ts";
2424
2525 /** The paths a peek reads: a repository, or one of its issues or pulls. */
2626 const PEEK =
@@ -212,7 +212,7 @@ export const peekCss = /* css */ `
212212 * without the script.
213213 */
214214 export const workLineHtml = (l: WorkLine): Html =>
215 html`${l.says}${l.change === undefined ? null : html` <a href="${l.change.href}">${l.change.words}</a>`}${l.wall === undefined ? null : wallAnswers(l.wall)}`;
215 html`${l.since === undefined ? l.says : html`${l.says.replace(FOR_MINUTES, "")} for ${time(l.since, { count: "elapsed" })}.`}${l.change === undefined ? null : html` <a href="${l.change.href}">${l.change.words}</a>`}${l.wall === undefined ? null : wallAnswers(l.wall)}`;
216216
217217 /** "Allow it" and "Send it back", each its own form: the answer is in the form, never a query. */
218218 const wallAnswers = (w: { readonly repo: string; readonly number: number }): Html => {
src/web/time_element.ts +23 −3
@@ -23,13 +23,33 @@ export function timeAgo(iso: string): string {
2323 * `date` words it as the calendar day (`2026-12-02`), for an instant ahead
2424 * of now, which "ago" cannot name.
2525 */
26 export function time(iso: string, opts: { date?: boolean; text?: string; class?: string } = {}): Html {
26 export function time(iso: string, opts: { date?: boolean; text?: string; class?: string; count?: Count; end?: string | null } = {}): Html {
2727 const parsed = Date.parse(iso);
2828 if (Number.isNaN(parsed)) return html``;
2929 const at = new Date(parsed);
3030 const exact = `${at.toISOString().slice(0, 16).replace("T", " ")} UTC`;
3131 const cls = opts.class === undefined ? html`` : html` class="${opts.class}"`;
32 return html`<time${cls} datetime="${at.toISOString()}" title="${exact}"
33 >${opts.text ?? (opts.date === true ? at.toISOString().slice(0, 10) : timeAgo(iso))}</time
32 // Relative words move on their own (`live_time_client.ts`); a count keeps counting from here.
33 const count = opts.count ?? (opts.text === undefined && opts.date !== true ? "ago" : undefined);
34 const end = opts.end === undefined || opts.end === null || Number.isNaN(Date.parse(opts.end)) ? undefined : new Date(Date.parse(opts.end)).toISOString();
35 const counting = count === undefined ? html`` : end === undefined ? html` data-count="${count}"` : html` data-count="${count}" data-end="${end}"`;
36 const words = opts.text ?? (opts.date === true ? at.toISOString().slice(0, 10) : count === "elapsed" ? elapsedWords((end === undefined ? Date.now() : Date.parse(end)) - parsed) : timeAgo(iso));
37 return html`<time${cls} datetime="${at.toISOString()}" title="${exact}"${counting}
38 >${words}</time
3439 >`;
3540 }
41
42 /**
43 * How the one clock in the browser redraws a `<time>` (`live_time_client.ts`): `ago` as relative
44 * words, `span` as the flow's age, `elapsed` counting up until `end`.
45 */
46 export type Count = "ago" | "span" | "elapsed";
47
48 /** A running length as it counts: 9s, 1m 05s, 2h 04m (the browser's `forgeElapsed`, word for word). */
49 export function elapsedWords(ms: number): string {
50 const s = Math.max(0, Math.floor(ms / 1000));
51 const two = (n: number) => (n < 10 ? `0${String(n)}` : String(n));
52 if (s < 60) return `${String(s)}s`;
53 if (s < 3600) return `${String(Math.floor(s / 60))}m ${two(s % 60)}s`;
54 return `${String(Math.floor(s / 3600))}h ${two(Math.floor((s % 3600) / 60))}m`;
55 }
test/board.test.ts +1 −1
@@ -256,7 +256,7 @@ describe("the board", () => {
256256 expect(working.indexOf("on the cart")).toBeLessThan(
257257 working.indexOf("Make the notes page load"),
258258 );
259 expect(working).toContain(`data-started="${queued.createdAt}"`);
259 expect(working).toMatch(new RegExp(`<time datetime="${queued.createdAt}"[^>]*data-count="elapsed"`));
260260 expect(working).toContain(`/alice/shop/runs/${running.id}`);
261261 expect(working).toContain("on what you said");
262262 expect(working).toContain("building it");
test/feed-age.test.ts +1 −1
@@ -16,7 +16,7 @@ describe("feed item age", () => {
1616 test("reads as a short relative age beside the exact time", () => {
1717 setSystemTime(hours(3));
1818 const text = feedCard(item).text;
19 expect(text).toMatch(/<time datetime="2026-03-04T05:06:07\.000Z"\s+title="2026-03-04 05:06 UTC"\s*>3h ago<\/time/);
19 expect(text).toMatch(/<time datetime="2026-03-04T05:06:07\.000Z"\s+title="2026-03-04 05:06 UTC" data-count="ago"\s*>3h ago<\/time/);
2020 });
2121
2222 test("is rendered from the clock at render time, never frozen", () => {
test/feed-post-byline.test.ts +1 −1
@@ -51,7 +51,7 @@ afterAll(async () => {
5151 });
5252
5353 const get = async (path: string) => (await fetch(`${servers.url}${path}`, { headers: { cookie } })).text();
54 const stamps = (html: string) => [...html.matchAll(/<time datetime="([^"]+)"\s+title="([^"]+)"\s*>([^<]*)<\/time/g)];
54 const stamps = (html: string) => [...html.matchAll(/<time datetime="([^"]+)"\s+title="([^"]+)"(?: data-count="ago")?\s*>([^<]*)<\/time/g)];
5555
5656 test("the feed card names the author and the age on one line, and the thread shows the same time", async () => {
5757 const feed = await get("/feed");
test/fixtures/milestones-golden.html +20 −20
@@ -23,7 +23,7 @@
2323 value="45"
2424 aria-label="Milestone 0000: 45 of 49 done"
2525 ></progress>
26 4 open · 15 merged in 7 days · moved <time datetime="T" title="T"
26 4 open · 15 merged in 7 days · moved <time datetime="T" title="T" data-count="ago"
2727 >AGO</time
2828 ></span>
2929 </span>
@@ -61,7 +61,7 @@
6161 value="45"
6262 aria-label="Milestone 0001: 45 of 49 done"
6363 ></progress>
64 4 open · 15 merged in 7 days · moved <time datetime="T" title="T"
64 4 open · 15 merged in 7 days · moved <time datetime="T" title="T" data-count="ago"
6565 >AGO</time
6666 ></span>
6767 </span>
@@ -111,7 +111,7 @@
111111 value="45"
112112 aria-label="Milestone 0002: 45 of 49 done"
113113 ></progress>
114 4 open · 15 merged in 7 days · moved <time datetime="T" title="T"
114 4 open · 15 merged in 7 days · moved <time datetime="T" title="T" data-count="ago"
115115 >AGO</time
116116 ></span>
117117 </span>
@@ -161,7 +161,7 @@
161161 value="45"
162162 aria-label="Milestone 0003: 45 of 49 done"
163163 ></progress>
164 4 open · 15 merged in 7 days · moved <time datetime="T" title="T"
164 4 open · 15 merged in 7 days · moved <time datetime="T" title="T" data-count="ago"
165165 >AGO</time
166166 ></span>
167167 </span>
@@ -211,7 +211,7 @@
211211 value="45"
212212 aria-label="Milestone 0004: 45 of 49 done"
213213 ></progress>
214 4 open · 15 merged in 7 days · moved <time datetime="T" title="T"
214 4 open · 15 merged in 7 days · moved <time datetime="T" title="T" data-count="ago"
215215 >AGO</time
216216 ></span>
217217 </span>
@@ -261,7 +261,7 @@
261261 value="45"
262262 aria-label="Milestone 0005: 45 of 49 done"
263263 ></progress>
264 4 open · 15 merged in 7 days · moved <time datetime="T" title="T"
264 4 open · 15 merged in 7 days · moved <time datetime="T" title="T" data-count="ago"
265265 >AGO</time
266266 ></span>
267267 </span>
@@ -311,7 +311,7 @@
311311 value="45"
312312 aria-label="Milestone 0006: 45 of 49 done"
313313 ></progress>
314 4 open · 15 merged in 7 days · moved <time datetime="T" title="T"
314 4 open · 15 merged in 7 days · moved <time datetime="T" title="T" data-count="ago"
315315 >AGO</time
316316 ></span>
317317 </span>
@@ -361,7 +361,7 @@
361361 value="45"
362362 aria-label="Milestone 0007: 45 of 49 done"
363363 ></progress>
364 4 open · 15 merged in 7 days · moved <time datetime="T" title="T"
364 4 open · 15 merged in 7 days · moved <time datetime="T" title="T" data-count="ago"
365365 >AGO</time
366366 ></span>
367367 </span>
@@ -411,7 +411,7 @@
411411 value="45"
412412 aria-label="Milestone 0008: 45 of 49 done"
413413 ></progress>
414 4 open · 15 merged in 7 days · moved <time datetime="T" title="T"
414 4 open · 15 merged in 7 days · moved <time datetime="T" title="T" data-count="ago"
415415 >AGO</time
416416 ></span>
417417 </span>
@@ -461,7 +461,7 @@
461461 value="45"
462462 aria-label="Milestone 0009: 45 of 49 done"
463463 ></progress>
464 4 open · 15 merged in 7 days · moved <time datetime="T" title="T"
464 4 open · 15 merged in 7 days · moved <time datetime="T" title="T" data-count="ago"
465465 >AGO</time
466466 ></span>
467467 </span>
@@ -511,7 +511,7 @@
511511 value="45"
512512 aria-label="Milestone 0010: 45 of 49 done"
513513 ></progress>
514 4 open · 15 merged in 7 days · moved <time datetime="T" title="T"
514 4 open · 15 merged in 7 days · moved <time datetime="T" title="T" data-count="ago"
515515 >AGO</time
516516 ></span>
517517 </span>
@@ -561,7 +561,7 @@
561561 value="45"
562562 aria-label="Milestone 0011: 45 of 49 done"
563563 ></progress>
564 4 open · 15 merged in 7 days · moved <time datetime="T" title="T"
564 4 open · 15 merged in 7 days · moved <time datetime="T" title="T" data-count="ago"
565565 >AGO</time
566566 ></span>
567567 </span>
@@ -611,7 +611,7 @@
611611 value="45"
612612 aria-label="Milestone 0012: 45 of 49 done"
613613 ></progress>
614 4 open · 15 merged in 7 days · moved <time datetime="T" title="T"
614 4 open · 15 merged in 7 days · moved <time datetime="T" title="T" data-count="ago"
615615 >AGO</time
616616 ></span>
617617 </span>
@@ -661,7 +661,7 @@
661661 value="45"
662662 aria-label="Milestone 0013: 45 of 49 done"
663663 ></progress>
664 4 open · 15 merged in 7 days · moved <time datetime="T" title="T"
664 4 open · 15 merged in 7 days · moved <time datetime="T" title="T" data-count="ago"
665665 >AGO</time
666666 ></span>
667667 </span>
@@ -711,7 +711,7 @@
711711 value="45"
712712 aria-label="Milestone 0014: 45 of 49 done"
713713 ></progress>
714 4 open · 15 merged in 7 days · moved <time datetime="T" title="T"
714 4 open · 15 merged in 7 days · moved <time datetime="T" title="T" data-count="ago"
715715 >AGO</time
716716 ></span>
717717 </span>
@@ -761,7 +761,7 @@
761761 value="45"
762762 aria-label="Milestone 0015: 45 of 49 done"
763763 ></progress>
764 4 open · 15 merged in 7 days · moved <time datetime="T" title="T"
764 4 open · 15 merged in 7 days · moved <time datetime="T" title="T" data-count="ago"
765765 >AGO</time
766766 ></span>
767767 </span>
@@ -811,7 +811,7 @@
811811 value="45"
812812 aria-label="Milestone 0016: 45 of 49 done"
813813 ></progress>
814 4 open · 15 merged in 7 days · moved <time datetime="T" title="T"
814 4 open · 15 merged in 7 days · moved <time datetime="T" title="T" data-count="ago"
815815 >AGO</time
816816 ></span>
817817 </span>
@@ -861,7 +861,7 @@
861861 value="45"
862862 aria-label="Milestone 0017: 45 of 49 done"
863863 ></progress>
864 4 open · 15 merged in 7 days · moved <time datetime="T" title="T"
864 4 open · 15 merged in 7 days · moved <time datetime="T" title="T" data-count="ago"
865865 >AGO</time
866866 ></span>
867867 </span>
@@ -911,7 +911,7 @@
911911 value="45"
912912 aria-label="Milestone 0018: 45 of 49 done"
913913 ></progress>
914 4 open · 15 merged in 7 days · moved <time datetime="T" title="T"
914 4 open · 15 merged in 7 days · moved <time datetime="T" title="T" data-count="ago"
915915 >AGO</time
916916 ></span>
917917 </span>
@@ -961,7 +961,7 @@
961961 value="45"
962962 aria-label="Milestone 0019: 45 of 49 done"
963963 ></progress>
964 4 open · 15 merged in 7 days · moved <time datetime="T" title="T"
964 4 open · 15 merged in 7 days · moved <time datetime="T" title="T" data-count="ago"
965965 >AGO</time
966966 ></span>
967967 </span>
test/live-time.test.ts added +70
@@ -0,0 +1,70 @@
1 /**
2 * The one clock in the browser (#16458): the server draws `<time datetime data-count>` and the
3 * script counts on from the timestamp. The browser's words must be the server's, word for word, or
4 * the first redraw would change what a person just read; and the script is display only.
5 */
6 import { describe, expect, test } from "bun:test";
7 import { span } from "../src/flow/pipeline.ts";
8 import { shellJs } from "../src/web/client.ts";
9 import { liveTimeFormatsJs, liveTimeJs } from "../src/web/live_time_client.ts";
10 import { elapsedWords, time, timeAgo } from "../src/web/time_element.ts";
11
12 type Words = (s: number) => string;
13 const browser = new Function(`${liveTimeFormatsJs}; return { elapsed: forgeElapsed, span: forgeSpan, ago: forgeAgo };`)() as Record<"elapsed" | "span" | "ago", Words>;
14
15 /** Seconds across every unit's edges: each second to two hours, then sparser to years. */
16 const SECONDS = [
17 ...Array.from({ length: 7300 }, (_, i) => i),
18 ...Array.from({ length: 2000 }, (_, i) => 7300 + i * 997),
19 ...Array.from({ length: 400 }, (_, i) => 2_000_000 + i * 86_399),
20 ];
21
22 describe("the browser's words are the server's", () => {
23 test("elapsed", () => {
24 for (const s of SECONDS) expect(browser.elapsed(s)).toBe(elapsedWords(s * 1000));
25 expect([5, 65, 3605].map(browser.elapsed)).toEqual(["5s", "1m 05s", "1h 00m"]);
26 });
27
28 test("span, the flow's age", () => {
29 for (const s of SECONDS) expect(browser.span(s)).toBe(span(s * 1000));
30 });
31
32 test("ago, the relative words", () => {
33 const now = Date.now();
34 // Half a second off each edge, so the moment the server reads does not cross one.
35 for (const s of SECONDS) expect(browser.ago(s)).toBe(timeAgo(new Date(now - s * 1000 - 500).toISOString()));
36 });
37 });
38
39 describe("time() draws what the clock counts", () => {
40 const at = "2026-11-25T20:00:00.000Z";
41
42 test("relative words count as ago; a calendar day or given words do not count", () => {
43 expect(String(time(at))).toContain('data-count="ago"');
44 expect(String(time(at, { date: true }))).not.toContain("data-count");
45 expect(String(time(at, { text: "then" }))).not.toContain("data-count");
46 });
47
48 test("an elapsed count says its length now, and one with an end stops there", () => {
49 const stopped = String(time(at, { count: "elapsed", end: "2026-11-25T20:01:05.900Z" }));
50 expect(stopped).toContain('data-count="elapsed" data-end="2026-11-25T20:01:05.900Z"');
51 expect(stopped).toContain(">1m 05s</time");
52 expect(String(time(at, { count: "span", text: "4m" }))).toMatch(/data-count="span"\s*>4m<\/time/);
53 });
54 });
55
56 describe("the clock is display only, on every page", () => {
57 test("it is in the shell every page loads", () => {
58 expect(shellJs).toContain(liveTimeJs);
59 });
60
61 test("it fetches nothing, reloads nothing, holds no interval, and stops while the tab is hidden", () => {
62 expect(liveTimeJs).not.toMatch(/fetch\s*\(|XMLHttpRequest|EventSource|location\.reload|setInterval/);
63 expect(liveTimeJs).toContain("doc.hidden");
64 expect(liveTimeJs).toContain("visibilitychange");
65 });
66
67 test("it parses", () => {
68 expect(() => new Function(liveTimeJs)).not.toThrow();
69 });
70 });
test/milestones-golden.test.ts +1 −1
@@ -64,7 +64,7 @@ function normalise(htmlText: string): string {
6464 .slice(start, end)
6565 .replaceAll(servers.url, "http://ORIGIN")
6666 .replace(/nonce="[^"]*"/g, 'nonce="NONCE"')
67 .replace(/(<time datetime=")[^"]*(" title=")[^"]*("\s*>)[^<]*(<\/time\s*>)/g, "$1T$2T$3AGO$4")
67 .replace(/(<time datetime=")[^"]*(" title=")[^"]*("(?: data-count="ago")?\s*>)[^<]*(<\/time\s*>)/g, "$1T$2T$3AGO$4")
6868 .replace(/\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z/g, "TIME");
6969 }
7070
test/no-polling.test.ts +5
@@ -2,6 +2,11 @@
22 * No forge page reloads or refetches on a timer, beyond a named allowlist.
33 * Pages learn of change from /events; a timer is allowed only where there is
44 * no event to hear, and each such file says why here.
5 *
6 * Counting is not polling: every elapsed and relative time is one clock in the browser
7 * (`src/web/live_time_client.ts`, #16458) that redraws `<time data-count>` text from its own
8 * timestamp on a `setTimeout` set for the next second that changes it, fetches nothing, and stops
9 * while the tab is hidden; `test/live-time.test.ts` holds it to that.
510 */
611
712 import { describe, expect, test } from "bun:test";
test/page-script-parses.test.ts added +19
@@ -0,0 +1,19 @@
1 /**
2 * A page script is composed from template strings, where one unescaped `\n` is a real line break
3 * inside a JavaScript string: the run page's script did not parse from 11-21 to 11-25 and the page
4 * sat frozen with no word on the server (#16477). Every composed script is compiled when first
5 * built; one that does not parse fails here and in every test that renders it.
6 */
7 import { expect, test } from "bun:test";
8 import { pageScriptAsset } from "../src/web/asset.ts";
9 import { studioRunJs } from "../src/web/client.ts";
10
11 test("the run page's script parses", () => {
12 expect(() => new Function(studioRunJs)).not.toThrow();
13 expect(() => pageScriptAsset(studioRunJs)).not.toThrow();
14 });
15
16 test("a composed page script that does not parse is refused where it is built", () => {
17 expect(() => pageScriptAsset("var all = body.split('\n');")).toThrow(/does not parse/);
18 expect(() => pageScriptAsset("var all = body.split('\\n');")).not.toThrow();
19 });
test/pull-crew-line.test.ts added +73
@@ -0,0 +1,73 @@
1 /**
2 * A pull says when the crew works on it (#16458): queued, then who and for how long (a counted
3 * `<time>`), then nothing once the run ends. The state fragment says the same, so the page's live
4 * client moves it on the run's own events.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { openPull } from "../src/actions/pulls.ts";
11 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import type { Pull } from "../src/core/pulls.ts";
14 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
15 import { createSession } from "../src/core/sessions.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18
19 let dir: string;
20 let app: App;
21 let servers: Servers;
22 let alice: User;
23 let pull: Pull;
24 let repoId: string;
25 let cookie = "";
26
27 beforeAll(async () => {
28 dir = await mkdtemp(join(tmpdir(), "forge-pull-crew-"));
29 app = createApp({ dataDir: dir, port: 0 });
30 servers = await serve(app);
31 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
32 if (!made.ok) throw new Error(made.error);
33 alice = made.value;
34 const repo = await createRepo(app, alice, { name: "shop", visibility: "public" });
35 if (!repo.ok) throw new Error(String(repo.error));
36 repoId = repo.value.id;
37 await commitToBranch(app, alice, repo.value, { message: "start", files: [{ path: "README.md", content: "# shop\n" }] });
38 await commitToBranch(app, alice, repo.value, { message: "fix", branch: "fix", files: [{ path: "README.md", content: "# shop!\n" }] });
39 const opened = await openPull(app, alice, repo.value, { title: "Fix", baseBranch: "main", headBranch: "fix" });
40 if (!opened.ok) throw new Error(String(opened.error));
41 pull = opened.value;
42 cookie = `forge_session=${createSession(app.db, alice.id).token}`;
43 });
44
45 afterAll(async () => {
46 servers.stop();
47 app.close();
48 await rm(dir, { recursive: true, force: true });
49 });
50
51 const line = async (path: string) => {
52 const html = await (await fetch(`${servers.url}/alice/shop/pulls/${pull.number}${path}`, { headers: { cookie } })).text();
53 return /<a href="[^"]*" data-crew-run="[^"]+"\s*>([\s\S]*?)<\/a\s*>/.exec(html)?.[1]?.replace(/\s+/g, " ").trim();
54 };
55
56 test("queued, then working with a counted length, then gone; the page and its state fragment agree", async () => {
57 expect(await line("")).toBeUndefined();
58 const run = createRun(app.db, { repoId, kind: "agent", issueId: pull.id, actorId: alice.id, reason: "review" });
59 expect(await line("")).toBe("queued for alice");
60 claimRun(app.db, run.id);
61 for (const path of ["", "/state"]) {
62 const said = await line(path);
63 expect(said).toMatch(/^alice is working on it · <time datetime="[^"]+" title="[^"]+" data-count="elapsed"\s*>\d+s<\/time\s*>$/);
64 }
65 finishRun(app.db, run.id, { state: "ok", summary: "Done." });
66 expect(await line("")).toBeUndefined();
67 });
68
69 test("a run on another pull or issue is not this pull's line", async () => {
70 const other = createRun(app.db, { repoId, kind: "agent", actorId: alice.id, reason: "issue" });
71 claimRun(app.db, other.id);
72 expect(await line("")).toBeUndefined();
73 });
test/templates-alive.test.ts +1 −1
@@ -57,7 +57,7 @@ test("recency renders from `recent` alone, and not at all when it is not passed
5757 test("a template with history says when it last changed; one without says so; a built-in says nothing", async () => {
5858 const text = await (await fetch(`${servers.url}/templates`)).text();
5959 const row = (id: string) => text.split(`data-template="${id}"`)[1]!.split("</li>")[0]!;
60 expect(row("tess/lively-kit")).toMatch(/updated <time datetime="[^"]+" title="[^"]+ UTC"\s*>3d ago<\/time/);
60 expect(row("tess/lively-kit")).toMatch(/updated <time datetime="[^"]+" title="[^"]+ UTC" data-count="ago"\s*>3d ago<\/time/);
6161 expect(row("tess/quiet-kit")).toContain(NO_CHANGES_YET);
6262 expect(row("tess/quiet-kit")).not.toContain("1970");
6363 expect(row("starter")).not.toContain(NO_CHANGES_YET);
test/time-element.test.ts +2 −2
@@ -25,7 +25,7 @@ const TIME_ELEMENT = /<time\b[^>]*\bdatetime="[^"]+"[^>]*\btitle="[^"]+"[^>]*>[\
2525 describe("the time helper", () => {
2626 test("emits datetime and the exact UTC title around the relative words", () => {
2727 const out = time(at).text;
28 expect(out).toMatch(/<time datetime="[^"]+"\s+title="\d{4}-\d\d-\d\d \d\d:\d\d UTC"\s*>3m ago<\/time\s*>/);
28 expect(out).toMatch(/<time datetime="[^"]+"\s+title="\d{4}-\d\d-\d\d \d\d:\d\d UTC" data-count="ago"\s*>3m ago<\/time\s*>/);
2929 });
3030 test("a bad instant emits nothing rather than a bare string", () => {
3131 expect(time("nope").text).toBe("");
@@ -95,7 +95,7 @@ describe("rendered pages", () => {
9595
9696 test("the upstream history's age is a <time>", async () => {
9797 const body = await (await fetch(`${servers.url}/amy/r/settings`, { headers: { cookie } })).text();
98 expect(body).toMatch(/data-following-history[\s\S]*?<time datetime="[^"]+" title="[^"]+"\s*>2h ago<\/time/);
98 expect(body).toMatch(/data-following-history[\s\S]*?<time datetime="[^"]+" title="[^"]+" data-count="ago"\s*>2h ago<\/time/);
9999 });
100100 });
101101

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs