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

Charts default to the forge's own repository for someone who works on none, and refusals say why (#16464) #16480

Merged opened this

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

Merged

voice/charts → main 0 commits

  • Merged. voice/charts was merged into main as c08e5b3.

Review

Sign in to review this change.
3 files changed +82 −16
src/http/mcp/tools/show.ts +13 −5
@@ -1,5 +1,16 @@
11 import { bad, good, str, type Tool } from "../shared.ts";
2 import { readWidget, searchWidgets } from "../../../widgets/registry.ts";
2 import { storedText } from "../../../kernel/blocked.ts";
3 import { readWidget, searchWidgets, type WidgetRefusal } from "../../../widgets/registry.ts";
4
5 /** Each refusal in words that name what to do, or which role draws it. */
6 const REFUSED: Record<WidgetRefusal, string> = {
7 no_widget: "no widget by that name: call show with no widget to list them",
8 not_found: "no such repository you may read (owner/name)",
9 invalid: "the arguments are outside the widget's schema: call show with no widget to read them",
10 forge_admin: "this graph is the forge admin's: it draws for an admin's account, or for an agent the admin granted telemetry",
11 // Whose it is to give, and the ask, through the one helper (docs/features/blocked-by.md).
12 repo_admin: storedText("an app's traffic is shown to its repository's admins, and you are not one of them.", "the repository's owner", "make you one"),
13 };
314
415 export const tool: Tool = {
516 name: "show",
@@ -17,10 +28,7 @@ export const tool: Tool = {
1728 return good({ widgets: searchWidgets(str(args["query"])).map((w) => ({ name: w.name, title: w.title, description: w.description, renderer: w.renderer, args: w.args })) });
1829 const given = typeof args["args"] === "object" && args["args"] !== null && !Array.isArray(args["args"]) ? (args["args"] as Record<string, unknown>) : {};
1930 const read = readWidget(ctx.app, user, name, given);
20 if (!read.ok)
21 return read.error === "not_found"
22 ? bad("not_found", "no such widget, or no such repository you may read: call show with no widget to list them")
23 : bad("invalid", "the arguments are outside the widget's schema: call show with no widget to read them");
31 if (!read.ok) return bad(read.error === "forge_admin" || read.error === "repo_admin" ? "forbidden" : read.error === "invalid" ? "invalid" : "not_found", REFUSED[read.error]);
2432 const { widget, data, says } = read.value;
2533 // The kept item (http/mcp.ts keeps it for a conversation and hands the agent its handle).
2634 return { ok: true, value: { widget: widget.name, title: widget.title, says }, card: { widget: { name: widget.name, renderer: widget.renderer, title: widget.title, data } } };
src/widgets/registry.ts +28 −6
@@ -20,6 +20,7 @@ import { withUnit } from "../core/talk_voice.ts";
2020 import type { Database } from "bun:sqlite";
2121 import { canAdmin, canRead, getRepo, getReposByIds, everyWritableRepoId, type Repo } from "../core/repos.ts";
2222 import { getAppByRepo, listApps } from "../core/apps.ts";
23 import { forgeSource } from "../settings/forge_source.ts";
2324
2425 /** The forge's renderers a widget may name. */
2526 export const RENDERERS = ["chart"] as const;
@@ -183,8 +184,11 @@ export const DATA_SCHEMA: Readonly<Record<Renderer, Schema>> = {
183184 },
184185 };
185186
186 /** Why a widget did not answer: the usual ambiguity for what the person may not read. */
187 export type WidgetRefusal = "not_found" | "invalid";
187 /**
188 * Why a widget did not answer: `not_found` keeps the usual ambiguity for what the person may not
189 * read; what they may read but not draw names the role it needs (`forge_admin`, `repo_admin`).
190 */
191 export type WidgetRefusal = "not_found" | "no_widget" | "invalid" | "forge_admin" | "repo_admin";
188192
189193 export interface Widget {
190194 readonly name: string;
@@ -223,6 +227,13 @@ export const SCOPE_ARGS = {
223227 },
224228 } as const satisfies Record<string, Schema>;
225229
230 /** The forge's own repository (`settings/forge_source.ts`), when `user` may read it. */
231 function forgeOwn(app: App, user: User | undefined): Repo | undefined {
232 const [owner = "", name = ""] = (forgeSource(app.db, app.config.forgeRepo) ?? "").split("/");
233 const repo = owner === "" || name === "" ? undefined : getRepo(app.db, owner, name);
234 return repo !== undefined && canRead(app.db, repo, user) ? repo : undefined;
235 }
236
226237 /**
227238 * The repositories a widget reads, as ids: the one named, when the person may read it, else
228239 * `not_found`, whether it is missing or hidden; or every one they work on (their own, their teams',
@@ -235,7 +246,15 @@ export function scopeOf(
235246 args: Readonly<Record<string, unknown>>,
236247 ): Result<{ repoIds: string[]; where: string }, "not_found"> {
237248 const named = typeof args["repo"] === "string" ? args["repo"] : undefined;
238 if (named === undefined) return ok({ repoIds: everyWritableRepoId(app.db, user), where: "every repository you work on" });
249 if (named === undefined) {
250 const mine = everyWritableRepoId(app.db, user);
251 // Someone who works on no repository (a voice client's own account) sees the forge's own
252 // repository, when they may read it, rather than an empty chart.
253 const own = mine.length === 0 ? forgeOwn(app, user) : undefined;
254 return own === undefined
255 ? ok({ repoIds: mine, where: "every repository you work on" })
256 : ok({ repoIds: [own.id], where: `${own.ownerName}/${own.name}, the forge's own repository (you work on none)` });
257 }
239258 const [owner = "", name = ""] = named.split("/");
240259 const repo = getRepo(app.db, owner, name);
241260 return repo !== undefined && canRead(app.db, repo, user)
@@ -351,7 +370,8 @@ const compute: Widget = {
351370 },
352371 read(app, user, args) {
353372 const reader = telemetryReader(app, user);
354 if (reader === undefined || user === undefined) return err("not_found");
373 if (user === undefined) return err("not_found");
374 if (reader === undefined) return err("forge_admin");
355375 noteRead(app, user, reader, "history");
356376 const hours = typeof args["hours"] === "number" ? args["hours"] : 24;
357377 const metric = METRICS[args["metric"] === "memory" || args["metric"] === "load" ? args["metric"] : "cpu"];
@@ -454,7 +474,9 @@ const traffic: Widget = {
454474 const [owner = "", name = ""] = named.split("/");
455475 const repo = getRepo(app.db, owner, name);
456476 const record = repo === undefined ? undefined : getAppByRepo(app.db, repo.id);
457 if (record === undefined || !administers(app.db, repo, user)) return err("not_found");
477 if (repo === undefined || record === undefined || !canRead(app.db, repo, user)) return err("not_found");
478 // A repository they read with an app they do not administer: say whose it is to see.
479 if (!administers(app.db, repo, user)) return err("repo_admin");
458480 apps = [{ id: record.id, name: record.slug }];
459481 }
460482 const { days, since } = windowOf(args);
@@ -530,7 +552,7 @@ export function readWidget(
530552 args: Readonly<Record<string, unknown>>,
531553 ): Result<{ widget: Widget; data: WidgetData; says: string }, WidgetRefusal> {
532554 const widget = widgetNamed(name);
533 if (widget === undefined) return err("not_found");
555 if (widget === undefined) return err("no_widget");
534556 if (validate(widget.args, args) !== undefined) return err("invalid");
535557 const read = widget.read(app, user, args);
536558 if (!read.ok) return read;
test/widgets.test.ts +41 −5
@@ -6,6 +6,7 @@
66 * counts what happened, day by day, only on repositories the person may read; and `show` in Talk
77 * keeps what it drew under a handle the page draws.
88 */
9 import { setForgeSource } from "../src/settings/forge_source.ts";
910 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
1011 import { mkdtemp, rm } from "node:fs/promises";
1112 import { tmpdir } from "node:os";
@@ -210,8 +211,8 @@ describe("compute", () => {
210211 expect(lines[2]).toContain("1 core now");
211212 });
212213
213 test("only who may read the machine draws it: anyone else is not found", () => {
214 expect(readWidget(app, bob, "compute", {})).toEqual({ ok: false, error: "not_found" });
214 test("only who may read the machine draws it: anyone else is told it is the forge admin's (#16464)", () => {
215 expect(readWidget(app, bob, "compute", {})).toEqual({ ok: false, error: "forge_admin" });
215216 expect(readWidget(app, undefined, "compute", {})).toEqual({ ok: false, error: "not_found" });
216217 expect(readWidget(app, alice, "compute", { hours: 100 })).toEqual({ ok: false, error: "invalid" });
217218 });
@@ -228,6 +229,22 @@ describe("shipping", () => {
228229 expect(chart("shipping", bob, { days: 7 }).says).toBe("No pulls merged in the last 7 days on every repository you work on.");
229230 });
230231
232 test("someone who works on no repository sees the forge's own, when they read it, not an empty chart (#16464)", () => {
233 setForgeSource(app.db, "alice/open", alice.id);
234 try {
235 const own = chart("shipping", bob, { days: 7 });
236 expect(own.data.series[0]!.values.reduce((a, b) => a + b, 0)).toBe(3);
237 expect(own.says).toContain("on alice/open, the forge's own repository (you work on none)");
238 // A private one bob cannot read is never his default.
239 setForgeSource(app.db, "alice/closed", alice.id);
240 expect(chart("shipping", bob, { days: 7 }).says).toBe("No pulls merged in the last 7 days on every repository you work on.");
241 // Whoever works on something keeps their own.
242 expect(chart("shipping", alice, { days: 7 }).data.series[0]!.values.reduce((a, b) => a + b, 0)).toBe(4);
243 } finally {
244 setForgeSource(app.db, null, alice.id);
245 }
246 });
247
231248 test("every repository the person works on is every one, not the newest hundred: the oldest, busiest repository still counts", () => {
232249 // 120 newer repositories of alice's beside `open`, her oldest with the merges and checks: a
233250 // newest-first page of 100 left `open` out and counted none of its work (#16330 in production).
@@ -273,7 +290,11 @@ describe("traffic", () => {
273290 expect(says).toBe("You administer no app: an app's traffic is shown to its repository's admins.");
274291 // Not even named as unmeasured: the public apps they read (openapp, quiet) and dana's siteapp.
275292 for (const slug of ["openapp", "quiet", "siteapp", "closedapp"]) expect(JSON.stringify(data) + says).not.toContain(slug);
276 for (const repo of ["studio/site", "alice/open", "alice/closed"]) expect(readWidget(app, who, "traffic", { repo })).toEqual({ ok: false, error: "not_found" });
293 // A repository they read is said to be its admins' to see (#16464); one they cannot read
294 // stays not found, as one that does not exist.
295 for (const repo of ["studio/site", "alice/open"])
296 expect(readWidget(app, who, "traffic", { repo })).toEqual({ ok: false, error: who === dana || repo === "alice/open" ? "repo_admin" : "not_found" });
297 expect(readWidget(app, who, "traffic", { repo: "alice/closed" })).toEqual({ ok: false, error: "not_found" });
277298 }
278299 expect(canRead(app.db, getRepo(app.db, "studio", "site")!, dana)).toBe(true);
279300 // A repository with no app is not found, as one that does not exist.
@@ -466,8 +487,23 @@ describe("each widget answers in its own shape, and only what the person may rea
466487 });
467488 }
468489
469 test("an unknown widget is not found", () => {
470 expect(readWidget(app, alice, "no_such_widget", {})).toEqual({ ok: false, error: "not_found" });
490 test("an unknown widget is said to be no widget, apart from a repository not found", () => {
491 expect(readWidget(app, alice, "no_such_widget", {})).toEqual({ ok: false, error: "no_widget" });
492 });
493
494 test("show says each refusal in words that name the role or the next call, never \"no such widget\" for a role", async () => {
495 const show = async (who: User, args: Record<string, unknown>): Promise<string> => {
496 const res = await fetch(`${servers.url}/mcp`, {
497 method: "POST",
498 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${createToken(app.db, who.id, "t", "ro").token}` },
499 body: JSON.stringify({ jsonrpc: "2.0", id: 9, method: "tools/call", params: { name: "show", arguments: args } }),
500 });
501 return ((await res.json()) as { result: { content: { text: string }[] } }).result.content[0]!.text;
502 };
503 expect(await show(bob, { widget: "compute" })).toStartWith("forbidden: this graph is the forge admin's");
504 expect(await show(bob, { widget: "traffic", args: { repo: "alice/open" } })).toStartWith("forbidden: an app's traffic is shown to its repository's admins");
505 expect(await show(bob, { widget: "traffic", args: { repo: "alice/closed" } })).toStartWith("not_found: no such repository you may read");
506 expect(await show(bob, { widget: "nope" })).toStartWith("not_found: no widget by that name");
471507 });
472508 });
473509

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs