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

The forge toolbar says who is working on this app right now, from the running record #15690

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/15683-the-forge-toolbar-says-who-is-working-on → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/15683-the-forge-toolbar-says-who-is-working-on was merged into main as c207496.

Review

Sign in to review this change.
5 files changed +191 −28
src/apps/crew.ts +70 −18
@@ -12,11 +12,14 @@ import { mayDirectCrew } from "../crew/direct.ts";
1212 import { timePhase } from "../core/route_timing.ts";
1313 import { getIssue } from "../core/issues.ts";
1414 import { canRead, canWrite, getRepoById } from "../core/repos.ts";
15 import { workingAgentRuns } from "../core/runs.ts";
15 import { leaseLapsed, workingAgentRuns } from "../core/runs.ts";
16 import { STALE_AFTER_MS } from "../runs/lease.ts";
1617 import { mayView, mayViewId } from "../core/sealed.ts";
1718 import { getUserById, isActive } from "../core/users.ts";
1819
1920 export type CrewNow = { who: string; url: string };
21 /** What the pill is told: the working line, or `nobody` with no run to link. */
22 export type CrewLine = { who: string; url?: string };
2023
2124 export function crewNow(
2225 db: Database,
@@ -27,7 +30,37 @@ export function crewNow(
2730 /** When given, the reads are named on it: `app`, `pull`, `working`. */
2831 request?: Request,
2932 ): CrewNow | undefined {
30 return crewAll(db, forgeUrl, app, env, viewerId, request)[0];
33 const line = crewLine(db, forgeUrl, app, env, viewerId, request);
34 if (line?.url === undefined) return undefined;
35 return { who: line.who, url: line.url };
36 }
37
38 /**
39 * The pill's line: who is working, or `nobody` only when this viewer may read
40 * the repository (and the pull) and no run at all is live, one on a sealed
41 * issue included. Nothing when the viewer cannot know.
42 */
43 export function crewLine(
44 db: Database,
45 forgeUrl: string,
46 app: AppRecord,
47 env: string,
48 viewerId: string | undefined,
49 request?: Request,
50 ): CrewLine | undefined {
51 const all = crewRead(db, forgeUrl, app, env, viewerId, request);
52 if (all === undefined) return undefined;
53 const first = all[0];
54 if (first === undefined) return { who: "nobody" };
55 return { who: foldNames(all.map((c) => c.who)), url: first.url };
56 }
57
58 /** One name, "a and b", or "a and 2 more": the distinct names of whoever is working, folded. */
59 export function foldNames(names: readonly string[]): string {
60 const [a, b, ...rest] = [...new Set(names)];
61 if (a === undefined) return "";
62 if (b === undefined) return a;
63 return rest.length === 0 ? `${a} and ${b}` : `${a} and ${rest.length + 1} more`;
3164 }
3265
3366 /** Everyone working on the app now, by the same rules as `crewNow`. */
@@ -39,9 +72,24 @@ export function crewAll(
3972 viewerId: string | undefined,
4073 request?: Request,
4174 ): CrewNow[] {
75 return crewRead(db, forgeUrl, app, env, viewerId, request) ?? [];
76 }
77
78 /**
79 * The crew this viewer may see, or undefined when they cannot know it all (no read, or a hidden
80 * live run).
81 */
82 function crewRead(
83 db: Database,
84 forgeUrl: string,
85 app: AppRecord,
86 env: string,
87 viewerId: string | undefined,
88 request?: Request,
89 ): CrewNow[] | undefined {
4290 const phase = <T>(name: string, work: () => T): T =>
4391 request === undefined ? work() : timePhase(request, name, work);
44 if (viewerId === undefined) return [];
92 if (viewerId === undefined) return undefined;
4593 const seen = phase("app", () => {
4694 const viewer = getUserById(db, viewerId);
4795 const repo = getRepoById(db, app.repoId);
@@ -49,29 +97,33 @@ export function crewAll(
4997 if (!canRead(db, repo, viewer)) return undefined;
5098 return { viewer, repo };
5199 });
52 if (seen === undefined) return [];
100 if (seen === undefined) return undefined;
53101 const { viewer, repo } = seen;
54102 const number = /^pull-(\d+)$/.exec(env)?.[1];
55 if (number === undefined && env !== "production") return [];
103 if (number === undefined && env !== "production") return undefined;
56104 const pulled = phase("pull", () => {
57105 if (number === undefined) return { issueId: undefined };
58106 const pull = getIssue(db, repo.id, Number(number));
59107 if (pull === undefined || !mayView(db, repo, pull, viewer)) return undefined;
60108 return { issueId: pull.id as string | undefined };
61109 });
62 if (pulled === undefined) return [];
63 // A run on a sealed issue is not the viewer's to know of.
64 return phase("working", () =>
65 workingAgentRuns(db, repo.id, pulled.issueId)
66 .filter((r) => mayViewId(db, repo, r.issueId, viewer))
67 .map((run) => {
68 const actor = run.actorId === null ? undefined : getUserById(db, run.actorId);
69 return {
70 who: actor?.username ?? "the crew",
71 url: new URL(`/${repo.ownerName}/${repo.name}/runs/${run.id}`, forgeUrl).href,
72 };
73 }),
74 );
110 if (pulled === undefined) return undefined;
111 return phase("working", () => {
112 // A run whose lease lapsed is a process that went away, not work in progress.
113 const live = workingAgentRuns(db, repo.id, pulled.issueId).filter(
114 (r) => !leaseLapsed(r, STALE_AFTER_MS),
115 );
116 // A run on a sealed issue is not the viewer's to know of.
117 const mine = live.filter((r) => mayViewId(db, repo, r.issueId, viewer));
118 if (mine.length === 0 && live.length > 0) return undefined;
119 return mine.map((run) => {
120 const actor = run.actorId === null ? undefined : getUserById(db, run.actorId);
121 return {
122 who: actor?.username ?? "the crew",
123 url: new URL(`/${repo.ownerName}/${repo.name}/runs/${run.id}`, forgeUrl).href,
124 };
125 });
126 });
75127 }
76128
77129 /**
src/apps/proxy.ts +2 −2
@@ -54,7 +54,7 @@ import {
5454 type EnvName,
5555 } from "./data.ts";
5656 import type { AppsRuntime, EnvStatus } from "./runtime.ts";
57 import { crewNow, tellLink, yoursLink } from "./crew.ts";
57 import { crewLine, crewNow, tellLink, yoursLink } from "./crew.ts";
5858 import { sideOf, type Side } from "./side.ts";
5959 import { feedback, mintProof } from "./feedback.ts";
6060 import { carryPeer, clientBucket, nameClient } from "../http/peer.ts";
@@ -1039,7 +1039,7 @@ export async function proxyApp(
10391039 ? undefined
10401040 : readGrant(runtime.app.config.dataDir, cookie, target);
10411041 });
1042 const crew = crewNow(
1042 const crew = crewLine(
10431043 runtime.app.db,
10441044 runtime.options.forgeUrl,
10451045 target.app,
src/apps/toolbar.ts +8 −6
@@ -508,13 +508,15 @@ const toolbarSource = `(function () {
508508 }
509509 } catch (e) {}
510510 }
511 if (typeof c.who !== "string" || typeof c.url !== "string") return;
512 var u = new URL(c.url);
513 if (u.origin !== forge) return;
514 var a = document.createElement("a");
511 if (typeof c.who !== "string") return;
512 var a = document.createElement(c.url ? "a" : "div");
513 if (c.url) {
514 var u = new URL(c.url);
515 if (u.origin !== forge) return;
516 a.rel = "noopener";
517 a.href = u.href;
518 }
515519 a.textContent = c.who + " is working on this";
516 a.rel = "noopener";
517 a.href = u.href;
518520 a.style.cssText = LS;
519521 crew.appendChild(a);
520522 })
test/apps-crew-pill.test.ts +57 −2
@@ -11,7 +11,7 @@ import { tmpdir } from "node:os";
1111 import { join } from "node:path";
1212 import { createApp, type App } from "../src/app.ts";
1313 import { newApp } from "../src/actions/apps.ts";
14 import { crewNow } from "../src/apps/crew.ts";
14 import { crewLine, crewNow } from "../src/apps/crew.ts";
1515 import { signGrant, type AppTarget } from "../src/apps/proxy.ts";
1616 import { AppsRuntime } from "../src/apps/runtime.ts";
1717 import { toolbarJs } from "../src/apps/toolbar.ts";
@@ -19,7 +19,7 @@ import { getAppByRepo, type AppRecord } from "../src/core/apps.ts";
1919 import { createIssue } from "../src/core/issues.ts";
2020 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
2121 import { setSealed } from "../src/core/sealed.ts";
22 import { createUser } from "../src/core/users.ts";
22 import { createUser, getUserById } from "../src/core/users.ts";
2323 import { serve, type Servers } from "../src/http/server.ts";
2424 import { quietLogs } from "./helpers/globals.ts";
2525
@@ -130,6 +130,61 @@ describe("the crew line", () => {
130130 expect(now("production")).toBeUndefined();
131131 });
132132
133 test("several names fold, one name stays, and a lapsed run is not shown as working (#15683)", () => {
134 const a = start(pullId);
135 expect(now("production")!.who).toBe("scout");
136 const b = createRun(app.db, { repoId, kind: "agent", issueId: pullId, actorId: bob, reason: "assigned" });
137 claimRun(app.db, b.id);
138 expect(now("production")!.who).toBe("bob and scout");
139 const c = createRun(app.db, { repoId, kind: "agent", issueId: pullId, actorId: alice, reason: "assigned" });
140 claimRun(app.db, c.id);
141 expect(now("production")!.who).toBe("alice and 2 more");
142 app.db.query("UPDATE run SET heartbeat_at = '2000-01-01T00:00:00.000Z' WHERE state = 'running'").run();
143 expect(now("production")).toBeUndefined();
144 for (const r of [a, b, c]) end(r.id);
145 });
146
147 const crewJson = async (record: AppRecord, id: string, name: string, label = "notes") => {
148 const target = { app: record, env: "production" } as AppTarget;
149 const grant = signGrant(dataDir, target, 60_000, Date.now(), { id, name, role: "admin" });
150 const res = await fetch(`${servers.url}/__forge/crew`, {
151 headers: { host: `${label}.${DOMAIN}`, cookie: `forge_grant_${record.id.slice(-8)}=${grant}` },
152 });
153 return (await res.json()) as { who?: string; url?: string; idle?: number };
154 };
155
156 test("a reader who may read the repository is told nobody is working, with no run to link", async () => {
157 expect(await crewJson(record, alice, "alice")).toMatchObject({ who: "nobody" });
158 expect((await crewJson(record, alice, "alice")).url).toBeUndefined();
159 const run = start(pullId);
160 const live = await crewJson(record, alice, "alice");
161 expect(live.who).toBe("scout");
162 expect(live.url).toContain(run.id);
163 end(run.id);
164 });
165
166 test("a reader who cannot read the repository is never told nobody, with a run live or not", async () => {
167 const made = await newApp(app, getUserById(app.db, alice)!, {
168 name: "vault",
169 description: "x",
170 visibility: "private",
171 });
172 if (!made.ok) throw new Error(String(made.error));
173 const vault = getAppByRepo(app.db, made.value.repo.id)!;
174 const run = createRun(app.db, { repoId: vault.repoId, kind: "agent", actorId: scout, reason: "assigned" });
175 claimRun(app.db, run.id);
176 expect(crewLine(app.db, forge, vault, "production", bob)).toBeUndefined();
177 end(run.id);
178 expect(crewLine(app.db, forge, vault, "production", bob)).toBeUndefined();
179 });
180
181 test("a live run the reader may not see is not 'nobody'", async () => {
182 const run = start(sealedId);
183 expect(await crewJson(record, bob, "bob")).not.toHaveProperty("who");
184 expect((await crewJson(record, alice, "alice")).who).toBe("scout");
185 end(run.id);
186 });
187
133188 test("a preview shows only the run on its own pull, and it ends", () => {
134189 const run = start(pullId);
135190 expect(now(`pull-${pullNumber}`)!.who).toBe("scout");
test/apps-toolbar-crew-line.test.ts added +54
@@ -0,0 +1,54 @@
1 /**
2 * The pill's crew line (#15683) run against a stub document: a working line is a link to the run,
3 * "nobody" is plain text with no link, a foreign link and a missing name draw nothing.
4 */
5 import { expect, test } from "bun:test";
6 import { toolbarJs } from "../src/apps/toolbar.ts";
7
8 interface El { tag: string; children: El[]; [k: string]: any }
9 const make = (tag: string): El => ({
10 tag, style: {}, children: [], listeners: {}, textContent: "", value: "",
11 setAttribute() {}, removeAttribute() {},
12 appendChild(c: El) { this.children.push(c); return c; },
13 append() {}, addEventListener() {}, attachShadow() { return make("shadow"); },
14 });
15
16 /** Boot the pill with the crew route answering `body`; returns the lines it drew. */
17 async function lines(body: object) {
18 const created: El[] = [];
19 const doc = {
20 currentScript: { dataset: { forge: "https://forge.test", app: "notes", env: "production", in: "1" } },
21 createElement: (tag: string) => { const e = make(tag); created.push(e); return e; },
22 addEventListener() {},
23 referrer: "",
24 body: { appendChild() {} },
25 };
26 const fetcher = (url: string) =>
27 url === "/__forge/crew" ? Promise.resolve({ ok: true, json: async () => body }) : new Promise(() => {});
28 new Function("window", "document", "URL", "localStorage", "fetch", "location", toolbarJs)(
29 { innerWidth: 400, innerHeight: 800, addEventListener() {} }, doc, URL, {}, fetcher,
30 { href: "https://notes.test/", pathname: "/", search: "", origin: "https://notes.test", protocol: "https:" },
31 );
32 for (let i = 0; i < 20; i++) await Promise.resolve();
33 return created.filter((e) => /is working on this$/.test(e.textContent));
34 }
35
36 test("idle: a div that says nobody, with no link", async () => {
37 const [line, ...more] = await lines({ who: "nobody" });
38 expect(more).toEqual([]);
39 expect(line!.tag).toBe("div");
40 expect(line!.textContent).toBe("nobody is working on this");
41 expect(line!.href).toBeUndefined();
42 });
43
44 test("working: a link to the run, the name as text", async () => {
45 const [line] = await lines({ who: "<b>scout</b> and 2 more", url: "https://forge.test/a/b/runs/1" });
46 expect(line!.tag).toBe("a");
47 expect(line!.href).toBe("https://forge.test/a/b/runs/1");
48 expect(line!.textContent).toBe("<b>scout</b> and 2 more is working on this");
49 });
50
51 test("a link off the forge's origin, and a body without a name, draw nothing", async () => {
52 expect(await lines({ who: "scout", url: "https://evil.test/x" })).toEqual([]);
53 expect(await lines({})).toEqual([]);
54 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs