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

A run page shows its log live from /events and opens no EventSource of its own #2851

Parked opened this
Closed without merging

scout/forge:scout/2843-a-run-page-shows-its-log-live-from-event → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +88 −23
src/web/client.ts +37 −19
@@ -224,7 +224,6 @@ export const studioRunJs = /* js */ `
224224 (function () {
225225 var log = document.getElementById('run-log');
226226 if (!log) return;
227 var url = log.getAttribute('data-stream');
228227 var who = log.getAttribute('data-who') || 'agent';
229228 var cap = parseInt(log.getAttribute('data-cap') || '0', 10) || 0;
230229 var pulse = document.getElementById('run-pulse');
@@ -360,28 +359,47 @@ export const studioRunJs = /* js */ `
360359 });
361360 }
362361
363 if (!url || typeof EventSource === 'undefined') return;
364 var source = new EventSource(url);
362 // The page opens no stream of its own: the shared /events connection
363 // (liveRegionsJs) carries this run's lines as run.log frames, handed on as
364 // forge:run-log, and its state change as the run.finished event.
365 var runId = log.getAttribute('data-run');
366 if (!runId) return;
367 var logUrl = log.getAttribute('data-log');
365368 var empty = document.getElementById('run-empty');
366 var seeded = false;
367 source.addEventListener('line', function (event) {
368 if (!seeded) {
369 if (event.lastEventId === '1') {
370 Array.prototype.slice.call(log.querySelectorAll('.ln:not(#run-pulse)')).forEach(function (el) { log.removeChild(el); });
371 }
372 seeded = true;
373 if (empty) empty.hidden = true;
374 }
375 var text = event.data;
376 try { var parsed = JSON.parse(text); if (typeof parsed === 'string') text = parsed; } catch (err) {}
369 // Lines on the page: those the server drew from the file, then each added
370 // here. A catch-up read of the file adds only what is past that count, and
371 // frames wait for it, so a line is never drawn twice.
372 var have = parseInt(log.getAttribute('data-seen') || '-1', 10);
373 var catching = false;
374 function put(text) {
375 if (empty) empty.hidden = true;
377376 add(draw(text));
377 have++;
378378 if (/^(\\$ |test-shards: |\\(fail\\) |\u2500\u2500 shard )/.test(text)) stepsSoon();
379 }
380 function catchUp() {
381 if (have < 0 || !logUrl || !window.fetch || catching) return;
382 catching = true;
383 fetch(logUrl, { credentials: 'same-origin' })
384 .then(function (r) { return r.ok ? r.text() : ''; })
385 .then(function (body) {
386 var all = body.split('\n');
387 if (all[all.length - 1] === '') all.pop();
388 all.slice(have).forEach(put);
389 })
390 .catch(function () {})
391 .then(function () { catching = false; });
392 }
393 document.addEventListener('forge:live', function (e) { if (e.detail && e.detail.state === 'open') catchUp(); });
394 document.addEventListener('forge:run-log', function (e) {
395 var d = e.detail;
396 if (!d || d.run !== runId || catching || !Array.isArray(d.lines)) return;
397 d.lines.forEach(function (l) { if (typeof l === 'string') put(l); });
379398 });
380 source.addEventListener('done', function (event) {
381 source.close();
382 var run;
383 try { run = JSON.parse(event.data); } catch (err) { return; }
384 paint(run);
399 document.addEventListener('forge:event', function (e) {
400 var d = e.detail;
401 if (!d || d.kind !== 'run.finished' || !d.payload || d.payload.runId !== runId) return;
402 paint(d.payload);
385403 if (stepsTimer) { window.clearTimeout(stepsTimer); stepsTimer = 0; }
386404 steps();
387405 if (steer) {
src/web/studio/log.ts +5
@@ -59,6 +59,9 @@ export function logBox(opts: {
5959 cap: number;
6060 lines: readonly string[];
6161 stream?: string;
62 /** A run still going, read live from the shared /events stream: its id,
63 * where the plain log is read to catch up, and how many lines are drawn. */
64 live?: { run: string; log: string; seen?: number };
6265 pulse?: boolean;
6366 className?: string;
6467 extra?: Html;
@@ -75,6 +78,8 @@ export function logBox(opts: {
7578 data-who="${opts.who}"
7679 data-cap="${opts.cap}"
7780 ${opts.stream ? html`data-stream="${opts.stream}"` : null}
81 ${opts.live ? html`data-run="${opts.live.run}" data-log="${opts.live.log}"` : null}
82 ${opts.live?.seen !== undefined ? html`data-seen="${opts.live.seen}"` : null}
7883 >
7984 ${when(
8085 hidden > 0,
src/web/studio/run.ts +15 −4
@@ -25,7 +25,7 @@ import { getUserById } from "../../core/users.ts";
2525 import { repoDir } from "../../git/repos.ts";
2626 import type { Ctx } from "../../http/context.ts";
2727 import { crumbsFor, repoBase, repoHeader, repoPalette } from "../chrome.ts";
28 import { studioRunJs } from "../client.ts";
28 import { liveRegionsJs, studioRunJs } from "../client.ts";
2929 import { html, raw, when, type Html } from "../html.ts";
3030 import { runLine } from "../describe.ts";
3131 import { page } from "../layout.ts";
@@ -107,7 +107,7 @@ export async function runView(
107107 const all = ctx.url.searchParams.get("all") === "1";
108108 const held = listHeldSecrets(db, run.id);
109109 const carried = carriedBy(db, run.id);
110 const stream = `/api/v1/repos/${repo.ownerName}/${repo.name}/runs/${run.id}/log?follow=1`;
110 const logPath = `/api/v1/repos/${repo.ownerName}/${repo.name}/runs/${run.id}/log`;
111111
112112 // The pull this run's tell has become, once one exists: the tell itself
113113 // when the run is already a pull's own (feedback, a failed check, a
@@ -308,7 +308,18 @@ export async function runView(
308308 lines,
309309 allHref: `${base}/runs/${run.id}?all=1`,
310310 truncated,
311 ...(unfinished ? { stream } : {}),
311 // Lines come from the shared /events stream; `seen` lets the page
312 // tell what it already drew from what it missed before connecting
313 // (only knowable when the file was read whole).
314 ...(unfinished
315 ? {
316 live: {
317 run: run.id,
318 log: logPath,
319 ...(truncated ? {} : { seen: lines.length }),
320 },
321 }
322 : {}),
312323 pulse: run.state === "running",
313324 extra: html`<button type="button" class="run-jump" id="run-jump" hidden>
314325 newer below
@@ -383,7 +394,7 @@ export async function runView(
383394 crumbs: crumbsFor(repo),
384395 palette: repoPalette(ctx, repo),
385396 body,
386 scriptJs: studioRunJs,
397 scriptJs: `${liveRegionsJs}\n${studioRunJs}`,
387398 // The no-script half of a live log: with JavaScript off, the page
388399 // refreshes itself while the run is going (`layout.ts` writes it inside
389400 // `<noscript>`, so a browser running the stream above never reloads).
test/studio-runs.test.ts +31
@@ -520,6 +520,37 @@ describe("working: a run's own page in the studio", () => {
520520 expect(page).not.toContain("?mode=dev");
521521 });
522522
523 test("a running run's page reads its log from the one /events stream and opens no other", async () => {
524 const run = createRun(app.db, {
525 repoId: repo.id,
526 kind: "agent",
527 actorId: scoutId,
528 reason: "assigned",
529 });
530 claimRun(app.db, run.id);
531 appendRunLog(app.config.dataDir, run.id, "first");
532 appendRunLog(app.config.dataDir, run.id, "second");
533
534 const page = await (
535 await get(`/alice/engine/runs/${run.id}`, writerCookie)
536 ).text();
537 // Every EventSource the page's HTML and script open is /events.
538 const opened = [...page.matchAll(/new EventSource\(([^,;]*)/g)].map(
539 (m) => m[1]!,
540 );
541 expect(opened.length).toBeGreaterThan(0);
542 for (const arg of opened) expect(arg).toStartWith("'/events");
543 expect(page).not.toContain("follow=1");
544 expect(page).not.toContain("data-stream=");
545 // The run's frames arrive on that connection; the file's lines are
546 // counted so none is drawn twice.
547 expect(page).toContain("'run.log'");
548 expect(page).toContain("forge:run-log");
549 expect(page).toContain(`data-run="${run.id}"`);
550 expect(page).toContain('data-seen="2"');
551 expect(page).toContain(">second<");
552 });
553
523554 test("a long transcript holds its last window, and the whole of it is one step deeper at ?all=1", async () => {
524555 const run = createRun(app.db, {
525556 repoId: repo.id,

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs