Public: anyone can read this; the crew can change it.
Talk answers which app gets the most traffic and what shipped #16360
Check · Review · Land · Live done — Landed and live in production.
talk/traffic → main 0 commits
9 files
changed +267
−24
docs/features/talk-voice.md +2 −1
| @@ -57,7 +57,8 @@ A widget is a name, a title, one line telling the agent what it shows, the rende | ||
| 57 | 57 | `checks` and `shipping` take `repo` (`owner/name`; without it, every repository you work on: your own and your teams') and `days` (1 to 90, default 14, today included), and count only what you may read. |
| 58 | 58 | |
| 59 | 59 | - `checks` (chart): checks that passed and failed each day. |
| 60 | - `shipping` (chart): pulls merged each day. | |
| 60 | - `shipping` (chart): pulls merged each day. Asked what shipped, the agent calls `pulls { brief: true, days }` with no `repo`, which lists merged pulls per repository across every one you may read: the busiest ten, and the rest counted. | |
| 61 | - `traffic` (chart): page views and visits per app, from the page-view beacon of the app template (`apps/measure.ts`, `traffic_view`), crawlers left out; without `repo`, every app whose repository you administer, ranked; with it, that app each day. Visitor numbers are the owner's: the gate is the app traffic page's (an admin of the repository), so a member who only writes to it, or anyone else, is told they administer no app, and an app they name is not found. A visit is one visitor on one day (the visitor hash is salted daily); only counts leave the server, never a hash, address or path. An app with no beacon rows in the window is named in the sentence ("built outside the template or never visited"), so a zero is never read as nobody using it. Raw requests to an app are not counted. | |
| 61 | 62 | - `compute` (chart): the machine and the forge's own process by the hour, CPU cores, or `metric` `memory` (GiB) or `load`, over `hours` (1 to 72, default 24). Its values are levels, so its legend and the terminal say the value now, not a sum. Only who may read the machine's figures draws it: a forge admin, or an agent granted `telemetry:read`. |
| 62 | 63 | |
| 63 | 64 | Asked for a graph, a chart, usage, throughput or how the server is doing, the agent calls `show` with these (its brief says so). |
src/core/pulls.ts +12 −8
| @@ -1662,24 +1662,28 @@ export const MERGED_DAYS_MAX = 90; | ||
| 1662 | 1662 | * Pulls merged into these repositories each UTC day, the last `days` with today, oldest first: the |
| 1663 | 1663 | * series a chart of shipping draws from (`pulls` with `brief`, the `shipping` widget). One read |
| 1664 | 1664 | * through `pull_merged` (a range on `merged_at`) for every repository at once, days counted in |
| 1665 | * code. A sealed pull is not counted. | |
| 1665 | * code. A sealed pull is not counted. `byRepo` is the same merges counted per repository id; | |
| 1666 | * `"every"` counts every repository, for a caller that keeps only the ones its reader may read. | |
| 1666 | 1667 | */ |
| 1667 | export function mergedPerDay(db: Database, repoIds: readonly string[], days: number, now: number = Date.now()): { days: string[]; merged: number[] } { | |
| 1668 | export function mergedPerDay(db: Database, repoIds: readonly string[] | "every", days: number, now: number = Date.now()): { days: string[]; merged: number[]; byRepo: Map<string, number> } { | |
| 1668 | 1669 | const today = Math.floor(now / 86_400_000); |
| 1669 | 1670 | const labels = Array.from({ length: days }, (_, i) => new Date((today - days + 1 + i) * 86_400_000).toISOString().slice(0, 10)); |
| 1670 | 1671 | const counts = new Map(labels.map((d) => [d, 0])); |
| 1672 | const byRepo = new Map<string, number>(); | |
| 1671 | 1673 | const rows = db |
| 1672 | .query<{ at: string }, [string, string]>( | |
| 1673 | `SELECT p.merged_at AS at FROM pull p INDEXED BY pull_merged JOIN issue i ON i.id = p.issue_id | |
| 1674 | WHERE p.merged_at >= ?2 AND i.repo_id IN (SELECT value FROM json_each(?1)) AND i.sealed = 0`, | |
| 1674 | .query<{ at: string; repoId: string }, [string, string]>( | |
| 1675 | `SELECT p.merged_at AS at, i.repo_id AS repoId FROM pull p INDEXED BY pull_merged JOIN issue i ON i.id = p.issue_id | |
| 1676 | WHERE p.merged_at >= ?2 AND (?1 = 'every' OR i.repo_id IN (SELECT value FROM json_each(?1))) AND i.sealed = 0`, | |
| 1675 | 1677 | ) |
| 1676 | .all(JSON.stringify(repoIds), `${labels[0]!}T00:00:00.000Z`); | |
| 1678 | .all(repoIds === "every" ? "every" : JSON.stringify(repoIds), `${labels[0]!}T00:00:00.000Z`); | |
| 1677 | 1679 | for (const r of rows) { |
| 1678 | 1680 | const day = r.at.slice(0, 10); |
| 1679 | 1681 | const n = counts.get(day); |
| 1680 | if (n !== undefined) counts.set(day, n + 1); | |
| 1682 | if (n === undefined) continue; | |
| 1683 | counts.set(day, n + 1); | |
| 1684 | byRepo.set(r.repoId, (byRepo.get(r.repoId) ?? 0) + 1); | |
| 1681 | 1685 | } |
| 1682 | return { days: labels, merged: labels.map((d) => counts.get(d)!) }; | |
| 1686 | return { days: labels, merged: labels.map((d) => counts.get(d)!), byRepo }; | |
| 1683 | 1687 | } |
| 1684 | 1688 | |
| 1685 | 1689 | /** |
src/core/talk_voice.ts +6 −1
| @@ -652,10 +652,15 @@ const dayWord = (d: string): string => { | ||
| 652 | 652 | |
| 653 | 653 | /** |
| 654 | 654 | * A kept widget as the terminal prints it, in the same data the page draws: a chart as one line of |
| 655 | * block characters a series (one scale for all, its total after it) over the days it spans. | |
| 655 | * block characters a series (one scale for all, its total after it) over the days it spans; a chart | |
| 656 | * across names, not days (apps ranked by `traffic`), as one line a name with each series' value. | |
| 656 | 657 | */ |
| 657 | 658 | export function widgetLines(w: KeptWidget): string[] { |
| 658 | 659 | const d = w.data; |
| 660 | if (d.x.length > 0 && !d.x.every((l) => /^\d{4}-\d{2}-\d{2}/.test(l))) { | |
| 661 | const named = Math.max(...d.x.map((l) => l.length)); | |
| 662 | return [w.title, ...d.x.map((l, i) => ` ${l.padEnd(named)} ${d.series.map((s) => `${s.name} ${(s.values[i] ?? 0).toLocaleString("en-US")}`).join(" · ")}`)]; | |
| 663 | } | |
| 659 | 664 | const width = Math.max(...d.series.map((s) => s.name.length)); |
| 660 | 665 | const top = Math.max(0, ...d.series.flatMap((s) => s.values)); |
| 661 | 666 | const span = d.x.length === 0 ? "no days" : `${dayWord(d.x[0]!)} to ${dayWord(d.x.at(-1)!)}`; |
src/crew/conversation_brief.ts +2 −1
| @@ -18,7 +18,8 @@ export const VOICE: readonly string[] = [ | ||
| 18 | 18 | "Open with the answer in one or two sentences. Then go as deep as the question deserves: when they ask why or how, or to go deeper, explain in full, and put detail they did not ask for inside a fold (a line `<details><summary>Title</summary>`, the detail, then a line `</details>`). A rule of theirs about length is about that opening and about noise, never a limit on depth they ask for.", |
| 19 | 19 | "Be brief and direct: say the thing, then stop; no preamble, no recap of what they said, no closing summary. Be the same every time: the same ask gets the same kind of answer, in the same order (what you did or found, what it means, what is next), and the same words for the same things, so they can rely on you without rereading. Spend invention where the work needs it (a name, a design, a way round a problem) and say that you chose, never on the form of the answer.", |
| 20 | 20 | "Show the forge's results, do not retell them: a tool answer that ends with a line naming a shown result (`Shown result c7`) can be drawn for the person as the forge returned it by writing a line that is exactly `::show c7`, at the margin, outside any code fence. Say in a sentence what it shows and what to look at; never copy its rows into prose, and say an empty result in a clause instead of showing it.", |
| 21 | "When the person asks for a graph or a chart, or how the server, compute, usage, shipping or throughput is doing, call `show` with the widget that draws it (`compute` for the machine's CPU, memory or load; `shipping` for pulls merged per day; `checks` for checks; `show` with no widget lists them) and place its result; never describe a series in prose or say you cannot draw it before you have called `show`.", | |
| 21 | "When the person asks for a graph or a chart, or how the server, compute, usage, shipping or throughput is doing, call `show` with the widget that draws it (`compute` for the machine's CPU, memory or load; `shipping` for pulls merged per day; `checks` for checks; `traffic` for page views and visits per app; `show` with no widget lists them) and place its result; never describe a series in prose or say you cannot draw it before you have called `show`.", | |
| 22 | "When they ask which app gets the most traffic, how many visitors an app has or whether anyone uses it, call `show` with `traffic` (with `repo` for one app) and say its sentence as it is, the apps it names with no page-view data included: such an app is unmeasured, never unused. When they ask what shipped, call `pulls` with `brief: true` and `days` and no `repo`: it lists merged pulls per repository across everything they may read.", | |
| 22 | 23 | "The pane beside the chat shows the app you work on; `pane` points it: once a change you asked the crew for has deployed, call `pane` with the app, the path of the changed screen and one short sentence of what to try there (\"Press Start, then lose a life\"), and do the same when they ask where to test or to see a page. Never point it at an app they did not ask about.", |
| 23 | 24 | "When a choice is small and can be undone, pick the sensible default and do it, then say in one line what you picked and how to change it; ask only when the choices lead to work that is costly to redo or cannot be undone.", |
| 24 | 25 | "A short message after a change is a correction to the last thing you changed (\"nah, rounder buttons\"): apply it there and keep everything else as it is.", |
src/http/mcp/tools/pulls.ts +38 −7
| @@ -1,5 +1,5 @@ | ||
| 1 | 1 | import { refTip } from "../../../git/read.ts"; |
| 2 | import { canRead, getReposByIds } from "../../../core/repos.ts"; | |
| 2 | import { canRead, getReposByIds, readableRepoIds } from "../../../core/repos.ts"; | |
| 3 | 3 | import { mayView, sealedScope } from "../../../core/sealed.ts"; |
| 4 | 4 | import { listReviewsFor, reviewSummariesFor } from "../../../core/reviews.ts"; |
| 5 | 5 | import { movedSinceApproval } from "../../../core/approval_at.ts"; |
| @@ -14,9 +14,9 @@ import { good, bad, limitArg, type Args, type Answer, type Tool, REPO_ARG, repoA | ||
| 14 | 14 | |
| 15 | 15 | export const tool: Tool = { |
| 16 | 16 | name: "pulls", |
| 17 | doc: "`{ repo?, state?, limit?, cursor? }`: without `repo`, every open pull you may read, oldest first, as `{ pulls, next_cursor }` (limit 1-200, default 50): `repo`, `number`, `title`, `check`, `verdict` (approved, changes_requested or none) and `gate` (what holds it, or null; the `why` module's cause); with `repo`, a repository's pulls, newest first, one brief line each: `number`, `title`, `author`, `head`, `check` (state), `approvals`, `movedSinceApproval` (the approval was given for a head or base that has since moved), `changesRequested`, `mergeable` (null once closed), `waitsFor` (`pull`'s `line`, or null); `state` open (default) or closed, `limit` 1-50 (default 20); no bodies, no diffs. `{ repo, brief: true, days? }` (1-90, default 14): pulls merged each UTC day, `{ repo, days: [YYYY-MM-DD], merged: [n] }`, oldest first, to chart shipping", | |
| 17 | doc: "`{ repo?, state?, limit?, cursor? }`: without `repo`, every open pull you may read, oldest first, as `{ pulls, next_cursor }` (limit 1-200, default 50): `repo`, `number`, `title`, `check`, `verdict` (approved, changes_requested or none) and `gate` (what holds it, or null); with `repo`, its pulls, newest first, one line each: `number`, `title`, `author`, `head`, `check` (state), `approvals`, `movedSinceApproval` (approved, then the head or base moved), `changesRequested`, `mergeable` (null once closed), `waitsFor` (`pull`'s `line`, or null); `state` open (default) or closed, `limit` 1-50 (default 20). `{ repo, brief: true, days? }` (1-90, default 14): pulls merged each UTC day, `{ repo, days: [YYYY-MM-DD], merged: [n] }`, oldest first, to chart shipping; without `repo`: what shipped where you may read, `{ since, days, merged, repos: [{ repo, merged }] (top 10), others }`", | |
| 18 | 18 | description: |
| 19 | "A repository's pulls, newest first; no `repo`: all open pulls you may read, oldest first.", | |
| 19 | "A repo's pulls, newest first; no `repo`: all open ones you may read, oldest first; `brief`, no `repo`: merged per repo.", | |
| 20 | 20 | inputSchema: { |
| 21 | 21 | type: "object", |
| 22 | 22 | properties: { |
| @@ -32,13 +32,14 @@ export const tool: Tool = { | ||
| 32 | 32 | async run(ctx, user, args) { |
| 33 | 33 | if (args["brief"] !== undefined && typeof args["brief"] !== "boolean") return bad("invalid_brief", "brief is true or false"); |
| 34 | 34 | if (args["brief"] === true) { |
| 35 | if (args["repo"] === undefined) return bad("invalid", "brief counts one repository's merged pulls: name `repo`"); | |
| 36 | const repo = repoArg(ctx, user, args); | |
| 37 | if (isAnswer(repo)) return repo; | |
| 38 | 35 | const days = args["days"] ?? 14; |
| 39 | 36 | if (typeof days !== "number" || !Number.isInteger(days) || days < 1 || days > MERGED_DAYS_MAX) |
| 40 | 37 | return bad("invalid", `days is a whole number from 1 to ${MERGED_DAYS_MAX}`); |
| 41 | return good({ repo: `${repo.ownerName}/${repo.name}`, ...mergedPerDay(ctx.app.db, [repo.id], days) }); | |
| 38 | if (args["repo"] === undefined) return shipped(ctx, user, days); | |
| 39 | const repo = repoArg(ctx, user, args); | |
| 40 | if (isAnswer(repo)) return repo; | |
| 41 | const { days: labels, merged } = mergedPerDay(ctx.app.db, [repo.id], days); | |
| 42 | return good({ repo: `${repo.ownerName}/${repo.name}`, days: labels, merged }); | |
| 42 | 43 | } |
| 43 | 44 | if (args["repo"] === undefined) return pile(ctx, user, args); |
| 44 | 45 | const repo = repoArg(ctx, user, args); |
| @@ -80,6 +81,36 @@ export const tool: Tool = { | ||
| 80 | 81 | }, |
| 81 | 82 | }; |
| 82 | 83 | |
| 84 | /** How many repositories `shipped` names before it counts the rest. */ | |
| 85 | const SHIPPED_TOP = 10; | |
| 86 | ||
| 87 | /** | |
| 88 | * What shipped: pulls merged in the last `days` across every repository the caller may read, the | |
| 89 | * busiest first, the first `SHIPPED_TOP` named and the rest counted. One range read of the merges | |
| 90 | * (`mergedPerDay`), then the readable ones kept (`readableRepoIds`): a private repository the caller | |
| 91 | * may not read is neither named nor counted. | |
| 92 | */ | |
| 93 | function shipped(ctx: Ctx, user: User, days: number): Answer { | |
| 94 | const db = ctx.app.db; | |
| 95 | const { days: labels, byRepo } = mergedPerDay(db, "every", days); | |
| 96 | const readable = readableRepoIds(db, user, [...byRepo.keys()]); | |
| 97 | const names = getReposByIds(db, [...readable]); | |
| 98 | const ranked = [...readable] | |
| 99 | .flatMap((id) => { | |
| 100 | const repo = names.get(id); | |
| 101 | return repo === undefined ? [] : [{ repo: `${repo.ownerName}/${repo.name}`, merged: byRepo.get(id)! }]; | |
| 102 | }) | |
| 103 | .sort((a, b) => b.merged - a.merged || a.repo.localeCompare(b.repo)); | |
| 104 | const rest = ranked.slice(SHIPPED_TOP); | |
| 105 | return good({ | |
| 106 | since: labels[0]!, | |
| 107 | days, | |
| 108 | merged: ranked.reduce((n, r) => n + r.merged, 0), | |
| 109 | repos: ranked.slice(0, SHIPPED_TOP), | |
| 110 | others: { repos: rest.length, merged: rest.reduce((n, r) => n + r.merged, 0) }, | |
| 111 | }); | |
| 112 | } | |
| 113 | ||
| 83 | 114 | /** Every open pull the caller may read, oldest first, one page: no git, no per-pull query beyond the check. */ |
| 84 | 115 | function pile(ctx: Ctx, user: User, args: Args): Answer { |
| 85 | 116 | const db = ctx.app.db; |
src/http/mcp/tools/show.ts +1 −1
| @@ -4,7 +4,7 @@ import { readWidget, searchWidgets } from "../../../widgets/registry.ts"; | ||
| 4 | 4 | export const tool: Tool = { |
| 5 | 5 | name: "show", |
| 6 | 6 | doc: "`{ widget?, args?, query? }`: draw a widget (a graph of the forge's data) read as you, and in Talk get its handle for `::show cN`; with no `widget`, the widgets matching `query` with their arguments", |
| 7 | description: "Graph the forge's own data: compute usage, throughput, checks. No widget: list them.", | |
| 7 | description: "Graph the forge's own data: compute usage, throughput, checks, app traffic. No widget: list them.", | |
| 8 | 8 | inputSchema: { |
| 9 | 9 | type: "object", |
| 10 | 10 | properties: { widget: { type: "string" }, args: { type: "object" }, query: { type: "string" } }, |
src/widgets/registry.ts +101 −2
| @@ -18,7 +18,8 @@ import { mergedPerDay } from "../core/pulls.ts"; | ||
| 18 | 18 | import { historyBrief } from "../system/telemetry.ts"; |
| 19 | 19 | import { withUnit } from "../core/talk_voice.ts"; |
| 20 | 20 | import type { Database } from "bun:sqlite"; |
| 21 | import { canRead, getRepo, everyWritableRepoId } from "../core/repos.ts"; | |
| 21 | import { canAdmin, canRead, getRepo, getReposByIds, everyWritableRepoId, type Repo } from "../core/repos.ts"; | |
| 22 | import { getAppByRepo, listApps } from "../core/apps.ts"; | |
| 22 | 23 | |
| 23 | 24 | /** The forge's renderers a widget may name. */ |
| 24 | 25 | export const RENDERERS = ["chart"] as const; |
| @@ -402,8 +403,106 @@ const shipping: Widget = { | ||
| 402 | 403 | }, |
| 403 | 404 | }; |
| 404 | 405 | |
| 406 | /** | |
| 407 | * Each visit to these apps since an instant: one row per visitor, from the page-view beacon's rows | |
| 408 | * (`traffic_view`, scope = the app's id). The visitor hash is salted afresh each day, so one hash | |
| 409 | * is one visit (one visitor on one day); it is grouped on here and never returned. One walk of | |
| 410 | * `traffic_view_scope_visitor_at` per app, in its order, so the grouping needs no sort. | |
| 411 | */ | |
| 412 | export const visitsSince = (db: Database, appIds: readonly string[], since: number): { scope: string; at: number; views: number; scraper: number }[] => | |
| 413 | db | |
| 414 | .query<{ scope: string; at: number; views: number; scraper: number }, [string, number]>( | |
| 415 | `SELECT scope, MIN(at) AS at, COUNT(*) AS views, MAX(scraper) AS scraper FROM traffic_view INDEXED BY traffic_view_scope_visitor_at | |
| 416 | WHERE scope IN (SELECT value FROM json_each(?1)) AND at >= ?2 GROUP BY scope, visitor`, | |
| 417 | ) | |
| 418 | .all(JSON.stringify(appIds), since); | |
| 419 | ||
| 420 | /** Whether `user` administers `repo`: the one gate for an app's traffic. */ | |
| 421 | const administers = (db: Database, repo: Repo | undefined, user: User | undefined): boolean => | |
| 422 | repo !== undefined && user !== undefined && canAdmin(db, repo, user); | |
| 423 | ||
| 424 | /** How many names a sentence lists before it says how many more. */ | |
| 425 | const NAMED = 10; | |
| 426 | const visitsSaid = (n: number): string => `${said(n)} visit${n === 1 ? "" : "s"}`; | |
| 427 | const listed = (names: readonly string[]): string => | |
| 428 | names.length <= NAMED ? names.join(", ") : `${names.slice(0, NAMED).join(", ")} and ${names.length - NAMED} more`; | |
| 429 | ||
| 430 | /** | |
| 431 | * Who uses the apps: page views and visits each app's pages reported through the template's beacon | |
| 432 | * (`apps/measure.ts`), crawlers left out. Across every app the person administers, ranked; or | |
| 433 | * one app's views and visits each day. Visitor numbers are the owner's: the gate is the app traffic | |
| 434 | * page's (`web/pages/sources.ts`, an admin of the repository), and an app anyone else names is not | |
| 435 | * found. Counts only: no visitor, address or path leaves the server. An | |
| 436 | * app with no rows in the window is named, never ranked as unused: the beacon is the template's, | |
| 437 | * so an app built without it, or one nobody opened with scripts on, reports nothing. | |
| 438 | */ | |
| 439 | const traffic: Widget = { | |
| 440 | name: "traffic", | |
| 441 | title: "App traffic", | |
| 442 | description: | |
| 443 | "Page views and visits per app you administer, ranked; with `repo`, that app each day. For: which app gets the most traffic, how many visitors, anyone using it.", | |
| 444 | renderer: "chart", | |
| 445 | args: { type: "object", additionalProperties: false, properties: SCOPE_ARGS }, | |
| 446 | read(app, user, args) { | |
| 447 | const named = typeof args["repo"] === "string" ? args["repo"] : undefined; | |
| 448 | let apps: { id: string; name: string }[]; | |
| 449 | if (named === undefined) { | |
| 450 | const all = listApps(app.db); | |
| 451 | const repos = getReposByIds(app.db, all.map((a) => a.repoId)); | |
| 452 | apps = all.filter((a) => administers(app.db, repos.get(a.repoId), user)).map((a) => ({ id: a.id, name: a.slug })); | |
| 453 | } else { | |
| 454 | const [owner = "", name = ""] = named.split("/"); | |
| 455 | const repo = getRepo(app.db, owner, name); | |
| 456 | const record = repo === undefined ? undefined : getAppByRepo(app.db, repo.id); | |
| 457 | if (record === undefined || !administers(app.db, repo, user)) return err("not_found"); | |
| 458 | apps = [{ id: record.id, name: record.slug }]; | |
| 459 | } | |
| 460 | const { days, since } = windowOf(args); | |
| 461 | const over = `the last ${days.length} days`; | |
| 462 | const rows = apps.length === 0 ? [] : visitsSince(app.db, apps.map((a) => a.id), Date.parse(since)); | |
| 463 | const people = rows.filter((r) => r.scraper === 0); | |
| 464 | const crawled = rows.reduce((n, r) => n + (r.scraper === 0 ? 0 : r.views), 0); | |
| 465 | const crawlers = crawled === 0 ? "crawlers left out" : `${said(crawled)} crawler views left out`; | |
| 466 | const heard = new Set(rows.map((r) => r.scope)); | |
| 467 | const silent = apps.filter((a) => !heard.has(a.id)).map((a) => a.name); | |
| 468 | const unheard = silent.length === 0 ? "" : ` No page-view beacon data for ${listed(silent)} (built outside the template or never visited).`; | |
| 469 | if (named !== undefined) { | |
| 470 | const at = (r: { at: number }) => new Date(r.at).toISOString(); | |
| 471 | const by = perDay(days, ["views", "visits"] as const, people.flatMap((r) => [{ at: at(r), series: "views" as const, value: r.views }, { at: at(r), series: "visits" as const }])); | |
| 472 | const total = by.views.reduce((a, b) => a + b, 0); | |
| 473 | const best = by.views.indexOf(Math.max(...by.views)); | |
| 474 | return ok({ | |
| 475 | data: { kind: "bar", x: [...days], unit: "views", series: [{ name: "Views", values: by.views }, { name: "Visits", values: by.visits }] }, | |
| 476 | says: | |
| 477 | (total === 0 | |
| 478 | ? `No page views of ${apps[0]!.name} in ${over} (${crawlers}).` | |
| 479 | : `${apps[0]!.name} had ${said(total)} page views in ${visitsSaid(people.length)} in ${over} (${crawlers}); the most on ${days[best]} (${said(by.views[best]!)}).`) + unheard, | |
| 480 | }); | |
| 481 | } | |
| 482 | const per = new Map<string, { views: number; visits: number }>(); | |
| 483 | for (const r of people) { | |
| 484 | const t = per.get(r.scope) ?? { views: 0, visits: 0 }; | |
| 485 | per.set(r.scope, { views: t.views + r.views, visits: t.visits + 1 }); | |
| 486 | } | |
| 487 | const ranked = apps | |
| 488 | .map((a) => ({ name: a.name, ...(per.get(a.id) ?? { views: 0, visits: 0 }) })) | |
| 489 | .filter((a) => a.views > 0) | |
| 490 | .sort((a, b) => b.views - a.views || a.name.localeCompare(b.name)); | |
| 491 | const top = ranked.slice(0, NAMED); | |
| 492 | const rest = ranked.length - top.length; | |
| 493 | return ok({ | |
| 494 | data: { kind: "bar", x: top.map((a) => a.name), unit: "views", series: [{ name: "Views", values: top.map((a) => a.views) }, { name: "Visits", values: top.map((a) => a.visits) }] }, | |
| 495 | says: | |
| 496 | (apps.length === 0 | |
| 497 | ? "You administer no app: an app's traffic is shown to its repository's admins." | |
| 498 | : top.length === 0 | |
| 499 | ? `No page views of any app you administer in ${over} (${crawlers}).` | |
| 500 | : `Page views by app in ${over} (${crawlers}): ${top.map((a) => `${a.name} ${said(a.views)} in ${visitsSaid(a.visits)}`).join(", ")}${rest === 0 ? "" : `; ${rest} more with fewer`}.`) + unheard, | |
| 501 | }); | |
| 502 | }, | |
| 503 | }; | |
| 405 | 504 | /** Every widget, by name. */ |
| 406 | export const WIDGETS: readonly Widget[] = [checks, compute, shipping]; | |
| 505 | export const WIDGETS: readonly Widget[] = [checks, compute, shipping, traffic]; | |
| 407 | 506 | |
| 408 | 507 | export const widgetNamed = (name: string): Widget | undefined => |
| 409 | 508 | WIDGETS.find((w) => w.name === name); |
test/mcp-pulls.test.ts +12 −2
| @@ -191,7 +191,7 @@ test("an approval given for a base that has since moved says so", async () => { | ||
| 191 | 191 | expect((await labPulls("rita")).find((p) => p.head === "asked").movedSinceApproval).toBe(false); |
| 192 | 192 | }); |
| 193 | 193 | |
| 194 | test("brief counts the pulls merged each day, small enough to chart, and refuses without a repo", async () => { | |
| 194 | test("brief counts the pulls merged each day, small enough to chart; without a repo, what shipped per repository the caller may read", async () => { | |
| 195 | 195 | // Two of svc's pulls merged, one today and one two days ago; the third day has none. |
| 196 | 196 | const day = 86_400_000; |
| 197 | 197 | const ids = app.db.query<{ id: string }, []>("SELECT i.id FROM issue i JOIN repo r ON r.id = i.repo_id WHERE r.name = 'svc' AND i.kind = 'pull' ORDER BY i.number").all(); |
| @@ -206,6 +206,16 @@ test("brief counts the pulls merged each day, small enough to chart, and refuses | ||
| 206 | 206 | const weeks = await pulls(tok["ada"]!, { repo: "ada/svc", brief: true }); |
| 207 | 207 | expect(weeks.value.days).toHaveLength(14); |
| 208 | 208 | expect(Buffer.byteLength(JSON.stringify(weeks.value))).toBeLessThan(400); |
| 209 | expect((await pulls(tok["ada"]!, { brief: true })).error).toContain("repo"); | |
| 209 | // Without a repository: what shipped, per repository, across what the caller may read. One of | |
| 210 | // the private vault's pulls merged yesterday: ada, its owner, counts it; rita may not read it, so | |
| 211 | // it is neither named nor counted for her. | |
| 212 | const vault = app.db.query<{ id: string }, []>("SELECT i.id FROM issue i JOIN repo r ON r.id = i.repo_id WHERE r.name = 'vault' AND i.kind = 'pull' ORDER BY i.number").all(); | |
| 213 | app.db.query("UPDATE pull SET merged_at = ?2 WHERE issue_id = ?1").run(vault[0]!.id, new Date(Date.now() - day).toISOString()); | |
| 214 | const all = await pulls(tok["ada"]!, { brief: true, days: 7 }); | |
| 215 | expect(all.value).toEqual({ since: new Date(Date.now() - 6 * day).toISOString().slice(0, 10), days: 7, merged: 3, repos: [{ repo: "ada/svc", merged: 2 }, { repo: "ada/vault", merged: 1 }], others: { repos: 0, merged: 0 } }); | |
| 216 | const stranger = await pulls(tok["rita"]!, { brief: true, days: 7 }); | |
| 217 | expect(stranger.value).toMatchObject({ merged: 2, repos: [{ repo: "ada/svc", merged: 2 }] }); | |
| 218 | expect(JSON.stringify(stranger.value)).not.toContain("vault"); | |
| 219 | expect((await pulls(tok["ada"]!, { brief: true, days: 0 })).error).toBeTruthy(); | |
| 210 | 220 | expect((await pulls(tok["ada"]!, { repo: "ada/svc", brief: true, days: 91 })).error).toBeTruthy(); |
| 211 | 221 | }); |
test/widgets.test.ts +93 −1
| @@ -12,8 +12,10 @@ import { tmpdir } from "node:os"; | ||
| 12 | 12 | import { join } from "node:path"; |
| 13 | 13 | import { createRepo } from "../src/actions/repos.ts"; |
| 14 | 14 | import { createApp, type App } from "../src/app.ts"; |
| 15 | import { createApp as createAppRecord } from "../src/core/apps.ts"; | |
| 16 | import { addTeamMember, createOrg, createTeam } from "../src/core/orgs.ts"; | |
| 15 | 17 | import { appendTurn, createConversation } from "../src/core/conversations.ts"; |
| 16 | import type { Repo } from "../src/core/repos.ts"; | |
| 18 | import { canRead, getRepo, type Repo } from "../src/core/repos.ts"; | |
| 17 | 19 | import { createSession } from "../src/core/sessions.ts"; |
| 18 | 20 | import { cardsOf, plainVoice, recordWidget, widgetLines } from "../src/core/talk_voice.ts"; |
| 19 | 21 | import { createToken } from "../src/core/tokens.ts"; |
| @@ -35,9 +37,13 @@ let app: App; | ||
| 35 | 37 | let servers: Servers; |
| 36 | 38 | let alice: User; |
| 37 | 39 | let bob: User; |
| 40 | let dana: User; | |
| 38 | 41 | let open: Repo; |
| 39 | 42 | let closed: Repo; |
| 40 | 43 | |
| 44 | /** The beacon's daily-salted visitor hashes: none may leave the server. */ | |
| 45 | const VISITORS = ["a1b2c3d4e5f60718293a4b5c6d7e8f90", "b1b2c3d4e5f60718293a4b5c6d7e8f90", "c1b2c3d4e5f60718293a4b5c6d7e8f90", "d1b2c3d4e5f60718293a4b5c6d7e8f90", "e1b2c3d4e5f60718293a4b5c6d7e8f90"] as const; | |
| 46 | ||
| 41 | 47 | const DAY = 86_400_000; |
| 42 | 48 | /** An instant `back` days before now, at noon UTC so it never crosses a day. */ |
| 43 | 49 | const ago = (back: number) => new Date(Math.floor(Date.now() / DAY) * DAY - back * DAY + DAY / 2).toISOString(); |
| @@ -89,6 +95,36 @@ beforeAll(async () => { | ||
| 89 | 95 | await merged(open, 0, 2); |
| 90 | 96 | await merged(open, 3, 3); |
| 91 | 97 | await merged(closed, 1, 4); |
| 98 | // Apps and their page views, as the beacon writes them (`traffic_view`): `openapp` had 4 views | |
| 99 | // in 2 visits today and 2 in 1 two days ago, and a crawler's 5 today; the private `closedapp` | |
| 100 | // 4 in 1 today; `quiet` (a public app) reported nothing. | |
| 101 | const appOf = (repo: Repo, slug: string) => { | |
| 102 | const made = createAppRecord(app.db, { repoId: repo.id, slug, access: "public" }); | |
| 103 | if (!made.ok) throw new Error(made.error); | |
| 104 | return made.value.id; | |
| 105 | }; | |
| 106 | const openApp = appOf(open, "openapp"); | |
| 107 | const closedApp = appOf(closed, "closedapp"); | |
| 108 | appOf(await made("quiet", "public"), "quiet"); | |
| 109 | // studio/site: an organization's app; dana writes to it through a team and administers nothing. | |
| 110 | dana = await mk("dana"); | |
| 111 | const studio = createOrg(app.db, "studio", alice.id); | |
| 112 | if (!studio.ok) throw new Error(studio.error); | |
| 113 | const writers = createTeam(app.db, studio.value.id, "writers", "write"); | |
| 114 | if (!writers.ok) throw new Error(writers.error); | |
| 115 | addTeamMember(app.db, writers.value, dana.id); | |
| 116 | const site = await createRepo(app, alice, { name: "site", visibility: "private", owner: "studio" }); | |
| 117 | if (!site.ok) throw new Error(String(site.error)); | |
| 118 | appOf(site.value, "siteapp"); | |
| 119 | const view = app.db.query("INSERT INTO traffic_view (scope, day, at, visitor, path, scraper) VALUES (?1, ?2, ?3, ?4, '/secret-path', ?5)"); | |
| 120 | const views = (scope: string, back: number, visitor: string, n: number, scraper = 0) => { | |
| 121 | for (let i = 0; i < n; i++) view.run(scope, ago(back).slice(0, 10), Date.parse(ago(back)) + i, visitor, scraper); | |
| 122 | }; | |
| 123 | views(openApp, 0, VISITORS[0], 3); | |
| 124 | views(openApp, 0, VISITORS[1], 1); | |
| 125 | views(openApp, 2, VISITORS[2], 2); | |
| 126 | views(openApp, 0, VISITORS[3], 5, 1); | |
| 127 | views(closedApp, 0, VISITORS[4], 4); | |
| 92 | 128 | }, 30_000); |
| 93 | 129 | afterAll(async () => { |
| 94 | 130 | servers.stop(); |
| @@ -204,6 +240,60 @@ describe("shipping", () => { | ||
| 204 | 240 | }); |
| 205 | 241 | }); |
| 206 | 242 | |
| 243 | describe("traffic", () => { | |
| 244 | const unheard = (names: string) => ` No page-view beacon data for ${names} (built outside the template or never visited).`; | |
| 245 | ||
| 246 | test("every app the person may read, ranked by page views, crawlers left out, and an app with no beacon data named", () => { | |
| 247 | const { data, says } = chart("traffic", alice, { days: 7 }); | |
| 248 | expect(data.x).toEqual(["openapp", "closedapp"]); | |
| 249 | expect(data.series.map((s) => [s.name, s.values])).toEqual([["Views", [6, 4]], ["Visits", [3, 1]]]); | |
| 250 | expect(says).toBe(`Page views by app in the last 7 days (5 crawler views left out): openapp 6 in 3 visits, closedapp 4 in 1 visit.${unheard("quiet, siteapp")}`); | |
| 251 | }); | |
| 252 | ||
| 253 | test("the terminal prints a ranked chart as one line an app, every series' value beside it", () => { | |
| 254 | const { data } = chart("traffic", alice, { days: 7 }); | |
| 255 | expect(widgetLines({ name: "traffic", renderer: "chart", title: "App traffic", data })).toEqual(["App traffic", " openapp Views 6 · Visits 3", " closedapp Views 4 · Visits 1"]); | |
| 256 | }); | |
| 257 | ||
| 258 | test("one app each day: its views and its visits", () => { | |
| 259 | const { data, says } = chart("traffic", alice, { repo: "alice/open", days: 7 }); | |
| 260 | expect(data.x).toEqual(dayLabels(7)); | |
| 261 | expect(data.series.map((s) => [s.name, s.values])).toEqual([["Views", [0, 0, 0, 0, 2, 0, 4]], ["Visits", [0, 0, 0, 0, 1, 0, 2]]]); | |
| 262 | expect(says).toBe(`openapp had 6 page views in 3 visits in the last 7 days (5 crawler views left out); the most on ${dayLabels(1)[0]} (4).`); | |
| 263 | expect(chart("traffic", alice, { repo: "alice/quiet", days: 7 }).says).toBe(`No page views of quiet in the last 7 days (crawlers left out).${unheard("quiet")}`); | |
| 264 | }); | |
| 265 | ||
| 266 | test("traffic is the admins': a member who writes to the repository and a stranger get none, named or counted", () => { | |
| 267 | expect(chart("traffic", alice, { days: 7 }).says).toContain("siteapp"); | |
| 268 | // dana writes to studio/site through a team, so she reads it, and administers nothing; bob | |
| 269 | // reads alice/open, which is public; neither administers an app, nor does someone signed out. | |
| 270 | for (const who of [dana, bob, undefined]) { | |
| 271 | const { data, says } = chart("traffic", who, { days: 7 }); | |
| 272 | expect(data.x).toEqual([]); | |
| 273 | expect(says).toBe("You administer no app: an app's traffic is shown to its repository's admins."); | |
| 274 | // Not even named as unmeasured: the public apps they read (openapp, quiet) and dana's siteapp. | |
| 275 | 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" }); | |
| 277 | } | |
| 278 | expect(canRead(app.db, getRepo(app.db, "studio", "site")!, dana)).toBe(true); | |
| 279 | // A repository with no app is not found, as one that does not exist. | |
| 280 | expect(readWidget(app, alice, "traffic", { repo: "alice/newer-0" })).toEqual({ ok: false, error: "not_found" }); | |
| 281 | }); | |
| 282 | ||
| 283 | test("only counts leave the server: no visitor hash and no path, in the widget or in show's answer", async () => { | |
| 284 | const answers = [readWidget(app, alice, "traffic", {}), readWidget(app, alice, "traffic", { repo: "alice/open" })]; | |
| 285 | const res = await fetch(`${servers.url}/mcp`, { | |
| 286 | method: "POST", | |
| 287 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${createToken(app.db, alice.id, "t", "ro").token}` }, | |
| 288 | body: JSON.stringify({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "show", arguments: { widget: "traffic", args: {} } } }), | |
| 289 | }); | |
| 290 | const text = JSON.stringify(answers) + (await res.text()); | |
| 291 | expect(text).toContain("openapp"); | |
| 292 | for (const v of VISITORS) expect(text).not.toContain(v.slice(0, 8)); | |
| 293 | expect(text).not.toContain("secret-path"); | |
| 294 | }); | |
| 295 | }); | |
| 296 | ||
| 207 | 297 | describe("the words that lead to a graph", () => { |
| 208 | 298 | test("show and the widgets are found by what a person asks: graph, compute, usage, throughput, how is the server", () => { |
| 209 | 299 | const described = showTool.description.toLowerCase(); |
| @@ -211,6 +301,8 @@ describe("the words that lead to a graph", () => { | ||
| 211 | 301 | expect(searchWidgets("compute usage").map((w) => w.name)).toEqual(["compute"]); |
| 212 | 302 | expect(searchWidgets("how is the server").map((w) => w.name)).toEqual(["compute"]); |
| 213 | 303 | expect(searchWidgets("shipping throughput").map((w) => w.name)).toEqual(["shipping"]); |
| 304 | for (const asked of ["most traffic", "visitors", "anyone using"]) expect(searchWidgets(asked).map((w) => w.name)).toEqual(["traffic"]); | |
| 305 | expect(showTool.description).toContain("app traffic"); | |
| 214 | 306 | expect(searchWidgets("graph").map((w) => w.name).sort()).toEqual(["compute", "shipping"]); |
| 215 | 307 | // The brief sends a request for a graph to show, never to prose. |
| 216 | 308 | expect(VOICE.join(" ")).toContain("When the person asks for a graph or a chart, or how the server, compute, usage, shipping or throughput is doing, call `show`"); |
new above
offline