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

After New app, land on a page that shows the app coming alive #22

Closed opened this
Closed without merging

scout/forge:scout/13-after-new-app-land-on-a-page-that-shows → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
3 files changed +342 −19
src/web/live.ts +96 −1
@@ -5,7 +5,8 @@
55 * - on a comment for the thread you're viewing, fetches the new comments and
66 * appends them, so a conversation updates as people type;
77 * - on any other relevant activity, reveals a "new activity" pill that
8 * reloads on click.
8 * reloads on click — or, for the app landing page, swaps its live block
9 * in place instead, and tails a run's log into it line by line.
910 * Every page works without this; it is pure enhancement.
1011 *
1112 * Announcements are a count, not the text: the polite live region says "2 new
@@ -34,6 +35,14 @@ export interface LiveConfig {
3435 number?: number;
3536 /** Id of the last comment already on the page (for the ?after= fetch). */
3637 lastCommentId?: string;
38 /**
39 * The app landing page: instead of a "new activity" pill, swap `#app-live`
40 * in place from `${repo}/app?fragment=1` when a relevant event lands — the
41 * pull and its preview appear the moment they exist, with no reload. An
42 * unfinished run's own log stream, when given, is tailed live into
43 * `#app-log`.
44 */
45 app?: { runStream?: string };
3746 }
3847
3948 /** The config element, the polite status line, and the (hidden) activity pill. */
@@ -46,6 +55,10 @@ export function liveMount(config: LiveConfig): Html {
4655 data-thread="${config.thread ?? ""}"
4756 data-number="${config.number ?? ""}"
4857 data-last="${config.lastCommentId ?? ""}"
58 ${config.app ? html`data-app="1"` : null}
59 ${config.app?.runStream
60 ? html`data-run-stream="${config.app.runStream}"`
61 : null}
4962 ></div>
5063 <p
5164 class="live-status"
@@ -66,10 +79,20 @@ export const liveClientJs = /* js */ `
6679 var thread = cfg.getAttribute('data-thread');
6780 var number = cfg.getAttribute('data-number');
6881 var lastId = cfg.getAttribute('data-last') || '';
82 var appMode = cfg.getAttribute('data-app') === '1';
83 var runStream = cfg.getAttribute('data-run-stream') || '';
6984 var pill = document.getElementById('live-pill');
7085 var status = document.getElementById('live-status');
7186 var conv = document.getElementById('conversation');
7287
88 // The app landing page's no-script half polls the whole page; a script
89 // that can update it in place must retire that poll, or the two would
90 // fight over the same seconds.
91 if (appMode || runStream) {
92 var meta = document.querySelector('meta[http-equiv="refresh"]');
93 if (meta) meta.remove();
94 }
95
7396 // A count, not a reload. Yanking the page out from under a reader to show
7497 // them something new is the one thing a live list must never do.
7598 var fresh = 0;
@@ -117,12 +140,30 @@ export const liveClientJs = /* js */ `
117140 .catch(function () {});
118141 }
119142
143 // The landing page swaps its whole live block from the same route it
144 // first rendered from, sandboxed CSP and all (see \`fragment()\`): a pull
145 // opening, a preview coming up, an environment redeploying all land the
146 // instant the event does, with nothing torn out from under a reader.
147 function refreshApp() {
148 var block = document.getElementById('app-live');
149 if (!block) return;
150 fetch(repo + '/app?fragment=1', { headers: { accept: 'text/html' } })
151 .then(function (r) { return r.ok ? r.text() : ''; })
152 .then(function (text) {
153 if (!text) return;
154 block.innerHTML = text;
155 if (status) status.textContent = 'Updated';
156 })
157 .catch(function () {});
158 }
159
120160 function onEvent(e) {
121161 var data;
122162 try { data = JSON.parse(e.data); } catch (_) { return; }
123163 if (relevant(data) && conv && (data.kind === thread + '.commented')) {
124164 appendNew();
125165 } else if (relevant(data) || !thread) {
166 if (appMode) { refreshApp(); return; }
126167 showPill();
127168 if (status) status.textContent = 'New activity on this page';
128169 }
@@ -146,5 +187,59 @@ export const liveClientJs = /* js */ `
146187 var es = new EventSource(at + '/stream');
147188 KINDS.forEach(function (k) { es.addEventListener(k, onEvent); });
148189 });
190
191 // The landing page's own agent run, tailed into a fixed-height box that
192 // scrolls itself — \`.run-log\`, the run page's own class, so the two look
193 // alike. Lines land, the run finishing swaps the whole block (above) to
194 // pick up its state, a pull, a preview.
195 if (runStream) {
196 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 )/;
197 function drawLine(text, who) {
198 var el = document.createElement('div');
199 var w = document.createElement('span');
200 w.className = 'who';
201 var t = document.createElement('span');
202 t.className = 'txt';
203 if (text.indexOf('you: ') === 0) {
204 el.className = 'ln ln-you'; w.textContent = 'you'; t.textContent = text.slice(5);
205 } else if (text.indexOf('\\u2192 ') === 0) {
206 var rest = text.slice(2), at = rest.indexOf(' ');
207 el.className = 'ln ln-tool'; w.textContent = '';
208 var b = document.createElement('b');
209 b.textContent = at === -1 ? rest : rest.slice(0, at);
210 t.appendChild(b);
211 t.appendChild(document.createTextNode(at === -1 ? '' : ' ' + rest.slice(at + 1)));
212 } else if (FORGE.test(text)) {
213 el.className = 'ln ln-forge'; w.textContent = 'forge'; t.textContent = text;
214 } else {
215 el.className = 'ln ln-say'; w.textContent = who; t.textContent = text;
216 }
217 el.appendChild(w); el.appendChild(t);
218 return el;
219 }
220 var seeded = false;
221 var es2 = new EventSource(runStream);
222 es2.addEventListener('line', function (event) {
223 var log = document.getElementById('app-log');
224 if (!log) return;
225 if (!seeded) {
226 if (event.lastEventId === '1') log.querySelectorAll('.ln').forEach(function (el) { el.remove(); });
227 seeded = true;
228 var emptyNote = document.getElementById('app-log-empty');
229 if (emptyNote) emptyNote.hidden = true;
230 }
231 var text = event.data;
232 try { var parsed = JSON.parse(text); if (typeof parsed === 'string') text = parsed; } catch (err) {}
233 var pulse = document.getElementById('app-log-pulse');
234 log.insertBefore(drawLine(text, log.getAttribute('data-who') || 'agent'), pulse);
235 log.scrollTop = log.scrollHeight;
236 });
237 es2.addEventListener('done', function () {
238 es2.close();
239 var pulse = document.getElementById('app-log-pulse');
240 if (pulse) pulse.remove();
241 refreshApp();
242 });
243 }
149244 })();
150245 `;
src/web/pages/apps.ts +141 −18
@@ -20,12 +20,13 @@ import {
2020 stopEnv,
2121 } from "../../actions/apps.ts";
2222 import { listAllAgents, listCrew } from "../../actions/crew.ts";
23 import { listRepoRuns, runLog } from "../../actions/runs.ts";
2324 import { planningAvailable } from "../../crew/plan.ts";
24 import { listRepoRuns } from "../../actions/runs.ts";
2525 import { envPull, previewEnv, type EnvName } from "../../apps/data.ts";
2626 import { appsRuntime, type EnvStatus } from "../../apps/runtime.ts";
2727 import { appHostSuffix } from "../../apps/host.ts";
2828 import { appsForRepos, type AppRecord } from "../../core/apps.ts";
29 import { getIssue, type Issue } from "../../core/issues.ts";
2930 import { accessAllows, listOrgsForUser, orgAccess } from "../../core/orgs.ts";
3031 import type { Pull } from "../../core/pulls.ts";
3132 import {
@@ -35,7 +36,7 @@ import {
3536 listReposVisibleTo,
3637 type Repo,
3738 } from "../../core/repos.ts";
38 import { isTerminal } from "../../core/runs.ts";
39 import { isTerminal, type Run } from "../../core/runs.ts";
3940 import type { User } from "../../core/users.ts";
4041 import type { Ctx } from "../../http/context.ts";
4142 import { resolveAppHostname } from "../../apps/proxy.ts";
@@ -51,7 +52,7 @@ import {
5152 } from "../chrome.ts";
5253 import { field, readForm } from "../form.ts";
5354 import { html, when, type Html } from "../html.ts";
54 import { flashTo, page, redirect } from "../layout.ts";
55 import { flashTo, fragment, page, redirect } from "../layout.ts";
5556 import { liveClientJs, liveMount } from "../live.ts";
5657 import {
5758 badge,
@@ -64,13 +65,14 @@ import {
6465 icon,
6566 listCard,
6667 row,
68 runStateBadge,
6769 selectField,
6870 sha,
6971 time,
7072 userLink,
7173 field as formField,
7274 } from "../ui.ts";
73 import { actorsFor, issuesFor, runRow } from "./runs.ts";
75 import { actorsFor, issuesFor, logLine, runRow, runTitleFrom } from "./runs.ts";
7476
7577 // ---- what the viewer can see ----
7678
@@ -405,19 +407,19 @@ export async function newAppSubmit(ctx: Ctx): Promise<Response> {
405407 422,
406408 );
407409 }
408 const { repo, app: record, issue, plan } = made.value;
409 const url = appsRuntime(ctx.app)?.urlFor(record, "production");
410 const first =
411 url === undefined
412 ? `${repo.name} is an app, but nothing is serving apps on this forge.`
413 : `${repo.name} is starting at ${url}.`;
410 const { repo, issue, plan } = made.value;
414411 const second =
415412 issue === undefined || issue.assigneeName === null
416413 ? ""
417414 : plan
418415 ? ` ${plan.agent} was picked for #${issue.number} — ${plan.summary}`
419416 : ` #${issue.number} is assigned to ${issue.assigneeName}.`;
420 return flashTo(ctx, repoBase(repo), { message: `${first}${second}` });
417 // Straight to the app page: production coming up, the first issue and who
418 // has it, and the agent's log, all on one page instead of a flash three
419 // clicks from any of them.
420 return flashTo(ctx, `${repoBase(repo)}/app`, {
421 message: `${repo.name} is starting.${second}`,
422 });
421423 }
422424
423425 // ---- the repo home's strip ----
@@ -537,6 +539,73 @@ function envCard(base: string, env: EnvStatus, writer: boolean): Html {
537539 );
538540 }
539541
542 /** How many of an agent run's most recent lines the landing page shows. */
543 const AGENT_LOG_TAIL = 12;
544
545 /** The golden path's first issue, and who has it — a repository's own #1. */
546 function firstIssueCard(base: string, issue: Issue): Html {
547 return card(
548 html`<p>
549 <a href="${base}/issues/${issue.number}"
550 >#${issue.number} ${issue.title}</a
551 >
552 </p>
553 <p class="muted small">
554 ${issue.assigneeName === null
555 ? "Nobody has it yet."
556 : html`${userLink(issue.assigneeName)} has it.`}
557 </p>`,
558 {
559 head: html`${icon("issue")}
560 <h2>First issue</h2>`,
561 },
562 );
563 }
564
565 /**
566 * The crew's most recent agent run, and its most recent lines — a fixed-
567 * height box that scrolls itself (`.run-log`, the run page's own class), so
568 * the transcript never shifts the rest of the page as it fills in. Tailed
569 * live by `live.ts` while the run goes; the full transcript is a click away.
570 */
571 function agentLogCard(
572 base: string,
573 run: Run,
574 title: string,
575 lines: readonly string[],
576 who: string,
577 ): Html {
578 return card(
579 html`${when(
580 lines.length === 0,
581 () =>
582 html`<p class="muted small" id="app-log-empty">
583 Nothing has been logged yet.
584 </p>`,
585 )}
586 <div class="run-log" id="app-log" data-who="${who}">
587 ${lines.map((l) => logLine(l, who))}
588 ${when(
589 run.state === "running",
590 () =>
591 html`<div class="ln ln-pulse" id="app-log-pulse">
592 <span class="who">${who}</span
593 ><span class="txt"><i></i><i></i><i></i></span>
594 </div>`,
595 )}
596 </div>`,
597 {
598 extra: "env-card",
599 head: html`${icon("bot")}
600 <h2><a href="${base}/runs/${run.id}">${title}</a></h2>
601 ${runStateBadge(run.state, "agent")}`,
602 foot: html`<a href="${base}/runs/${run.id}"
603 >Full run ${icon("chevronRight")}</a
604 >`,
605 },
606 );
607 }
608
540609 // GET /:owner/:name/app
541610 export function appPage(ctx: Ctx): Response {
542611 const repo = loadRepo(ctx);
@@ -574,8 +643,46 @@ export function appPage(ctx: Ctx): Response {
574643 runs.map((run) => runRow(base, run, actors, issues)),
575644 { head: runsHead },
576645 );
577 // Something still moving is news the live pill announces; the page is
578 // never pulled out from under a reader.
646
647 // The golden path's first issue: a repository's own #1, and who has it.
648 const first = getIssue(ctx.app.db, repo.id, 1);
649 const firstIssue =
650 first === undefined || first.kind !== "issue"
651 ? undefined
652 : firstIssueCard(base, first);
653
654 // The crew's most recent agent run and its most recent lines — its own
655 // read, since a busy deploy history could push the one agent run that
656 // matters off the mixed-kind list above.
657 const agentListed = listRepoRuns(ctx.app, ctx.auth.user, repo, {
658 kind: "agent",
659 limit: 1,
660 });
661 const agentRun = agentListed.ok ? agentListed.value[0] : undefined;
662 const agentLog =
663 agentRun === undefined
664 ? undefined
665 : (() => {
666 const found = runLog(ctx.app, ctx.auth.user, repo, agentRun.id);
667 const who =
668 (agentRun.actorId === null
669 ? undefined
670 : actors.get(agentRun.actorId))?.username ?? "agent";
671 return agentLogCard(
672 base,
673 agentRun,
674 runTitleFrom(agentRun, actors, issues),
675 found.ok ? found.value.lines.slice(-AGENT_LOG_TAIL) : [],
676 who,
677 );
678 })();
679 const runStream =
680 agentRun !== undefined && !isTerminal(agentRun.state)
681 ? `/api/v1/repos/${repo.ownerName}/${repo.name}/runs/${agentRun.id}/log?follow=1`
682 : undefined;
683
684 // Something still moving is why the no-script page refreshes itself; with
685 // a script, the live block below updates in place instead (`live.ts`).
579686 const moving =
580687 envs.some((env) => env.state === "deploying") ||
581688 runs.some((run) => !isTerminal(run.state));
@@ -603,6 +710,18 @@ export function appPage(ctx: Ctx): Response {
603710 ${envs.map((env) => envCard(base, env, writer))}
604711 </div>`;
605712
713 // Everything that changes as the app comes alive — an environment
714 // deploying, the first issue getting an assignee, the crew's own words —
715 // is one block: `#app-live` swaps it in place (`live.ts`), and this is
716 // what `?fragment=1` answers with, so the two can never drift apart.
717 const liveBlock = html`${environmentsBlock}
718 ${when(firstIssue, (c) => html`<div class="mt">${c}</div>`)}
719 ${when(agentLog, (c) => html`<div class="mt">${c}</div>`)}
720 <div class="mt">${runsCard}</div>`;
721
722 if (ctx.url.searchParams.get("fragment") === "1")
723 return fragment(liveBlock);
724
606725 const about = card(
607726 html`<dl>
608727 <dt>Hostname</dt>
@@ -669,13 +788,13 @@ export function appPage(ctx: Ctx): Response {
669788
670789 const body = html`${repoHeader(ctx, repo, "app", { compact: true })}
671790 <div class="split">
672 <div>
673 ${environmentsBlock}
674 <div class="mt">${runsCard}</div>
675 </div>
791 <div id="app-live">${liveBlock}</div>
676792 <aside>${about} ${crewCard}</aside>
677793 </div>
678 ${when(moving, () => liveMount({ repo: base }))}`;
794 ${liveMount({
795 repo: base,
796 app: { ...(runStream ? { runStream } : {}) },
797 })}`;
679798
680799 return page({
681800 ctx,
@@ -684,6 +803,10 @@ export function appPage(ctx: Ctx): Response {
684803 palette: repoPalette(repo),
685804 body,
686805 scriptJs: liveClientJs,
806 // The no-script half of a live app page: while something moves, the
807 // page refreshes itself; the script above removes this the moment it
808 // runs and takes over in place (`live.ts`).
809 ...(moving ? { refresh: { seconds: 5 } } : {}),
687810 });
688811 }
689812
test/web.test.ts +105
@@ -3,6 +3,7 @@ import { mkdtemp, rm } from "node:fs/promises";
33 import { tmpdir } from "node:os";
44 import { join } from "node:path";
55 import { createApp, type App } from "../src/app.ts";
6 import { AppsRuntime } from "../src/apps/runtime.ts";
67 import { health } from "../src/http/health.ts";
78 import { serve, type Servers } from "../src/http/server.ts";
89 import { escapeHtml, html, raw, when } from "../src/web/html.ts";
@@ -304,6 +305,110 @@ describe("web pages end to end", () => {
304305 });
305306 });
306307
308 describe("the app landing page", () => {
309 let dataDir: string;
310 let app: App;
311 let servers: Servers;
312 let runtime: AppsRuntime;
313 let base: string;
314 let cookie = "";
315 const DOMAIN = "apps.test";
316
317 beforeAll(async () => {
318 dataDir = await mkdtemp(join(tmpdir(), "forge-applanding-"));
319 app = createApp({ dataDir, port: 0 });
320 servers = await serve(app);
321 runtime = new AppsRuntime(app, {
322 domain: DOMAIN,
323 scheme: "http",
324 publicPort: servers.port,
325 forgeUrl: servers.url,
326 concurrency: 2,
327 });
328 await runtime.start();
329 base = servers.url;
330 const signup = await fetch(`${base}/signup`, {
331 method: "POST",
332 body: new URLSearchParams({
333 username: "ada",
334 email: "[email protected]",
335 password: "analytical-engine",
336 }),
337 redirect: "manual",
338 });
339 cookie = (signup.headers.get("set-cookie") ?? "").split(";")[0]!;
340 }, 30_000);
341
342 afterAll(async () => {
343 servers.stop();
344 app.close();
345 await rm(dataDir, { recursive: true, force: true });
346 });
347
348 test("New app lands on the app page, naming production's URL and the run; a stranger gets not-found", async () => {
349 const agentMade = await fetch(`${base}/settings/crew`, {
350 method: "POST",
351 headers: { cookie },
352 body: new URLSearchParams({
353 username: "bot",
354 model: "",
355 brief: "Be brief.",
356 }),
357 redirect: "manual",
358 });
359 expect(agentMade.status).toBe(303);
360
361 const created = await fetch(`${base}/apps/new`, {
362 method: "POST",
363 headers: { cookie },
364 body: new URLSearchParams({
365 owner: "ada",
366 name: "recipes",
367 description: "Build a recipe box",
368 visibility: "private",
369 agent: "bot",
370 }),
371 redirect: "manual",
372 });
373 expect(created.status).toBe(303);
374 expect(created.headers.get("location")).toBe("/ada/recipes/app");
375
376 // Production comes up from the scaffold in the background; give it a
377 // moment before asking what it serves.
378 let appText = "";
379 for (let i = 0; i < 100; i++) {
380 appText = await (
381 await fetch(`${base}/ada/recipes/app`, { headers: { cookie } })
382 ).text();
383 if (appText.includes(`recipes.${DOMAIN}`)) break;
384 await Bun.sleep(100);
385 }
386 expect(appText).toContain(`recipes.${DOMAIN}`); // production's URL
387 expect(appText).toContain("#1 Build recipes"); // the first issue
388 expect(appText).toContain(">bot<"); // …and who has it
389 expect(appText).toContain('id="app-live"');
390
391 // The same block a live swap fetches, sandboxed and without the chrome
392 // around it.
393 const liveFragment = await fetch(`${base}/ada/recipes/app?fragment=1`, {
394 headers: { cookie, accept: "text/html" },
395 });
396 expect(liveFragment.headers.get("content-security-policy")).toContain(
397 "sandbox",
398 );
399 const fragText = await liveFragment.text();
400 expect(fragText).toContain("#1 Build recipes");
401 expect(fragText).not.toContain("<html");
402
403 // A stranger gets the same not-found the rest of a private repo gives —
404 // on the page and on the fragment a live swap would ask for.
405 expect((await fetch(`${base}/ada/recipes/app`)).status).toBe(404);
406 expect((await fetch(`${base}/ada/recipes/app?fragment=1`)).status).toBe(
407 404,
408 );
409 }, 30_000);
410 });
411
307412 describe("themes", () => {
308413 let dataDir: string;
309414 let app: App;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs