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

Every panel says what it counts: a one-line description, and visitors can leave out the app's own people #16960

Merged opened this in answer to

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

Merged

scout/forge:scout/6613-every-panel-says-what-it-counts-a-one-li → main 0 commits fork 7 threads · 7 unresolved

  • Merged. scout/6613-every-panel-says-what-it-counts-a-one-li was merged into main as 4763996.

Review

Sign in to review this change.
17 files changed +254 −24
docs/TOUR.md +1 −1
@@ -219,7 +219,7 @@ An app's repository home wears the pace on its app strip, the terminal's **Deplo
219219
220220 ### Every app's visitors
221221
222 An app made from the template ships the same beacon as `static/beacon.js`, posting to `POST /__forge/measure` on the app's own host. The forge answers that door itself (`src/apps/measure.ts`), before the app is woken: same-origin only, 30 reports a minute per client and 600 per app (429), a body over the cap is a 413, and a private app or a sealed pull's preview refuses anyone its gate refuses. The app is the host's, never the body's. Production reports are kept in `app_vital` (`src/apps/vitals.ts`, TTFB, load, LCP, INP and CLS, a visitor hashed under the day's salt, no address, kept 90 days and removed with the app, at most 20,000 rows per app a day); previews store nothing. Only Do-Not-Track opts a visitor out on an app's host: the `forge_measure=off` cookie is set on the forge's host and never reaches an app's. Read the numbers (visitors today and over 7 days, p75 TTFB, load, LCP, INP and CLS) on the app's settings page under **Visitors and speed**, or as `vitals` in an admin's `GET /api/v1/repos/:owner/:name/app`. Both doors show them only to people who administer the repository (`appVisitors` in `src/actions/apps.ts`), so a reader or an anonymous caller sees no `vitals`. The page also draws p75 load for each of the last 30 days as a sparkline (server-rendered, no script); a day with no reports is a gap in the line, not a zero, and an app with none in 30 days says so in words. The same 30 values, oldest first with `null` for a silent day, are `vitals.loadDays` in the API. In the terminal all five are on the second line of the app's **Deploys** screen over ssh, and a third line there shows the 30 days as block characters with `·` for a silent day, then the range.
222 An app made from the template ships the same beacon as `static/beacon.js`, posting to `POST /__forge/measure` on the app's own host. The forge answers that door itself (`src/apps/measure.ts`), before the app is woken: same-origin only, 30 reports a minute per client and 600 per app (429), a body over the cap is a 413, and a private app or a sealed pull's preview refuses anyone its gate refuses. The app is the host's, never the body's. Production reports are kept in `app_vital` (`src/apps/vitals.ts`, TTFB, load, LCP, INP and CLS, a visitor hashed under the day's salt, no address, and a `member` flag set when the browser holds a grant naming someone signed in who may read the repository: the visitor counts leave those out by default (`?members=1` on the page and the API, `v` in the terminal) rather than leaving them unhashed (#6613), kept 90 days and removed with the app, at most 20,000 rows per app a day); previews store nothing. Only Do-Not-Track opts a visitor out on an app's host: the `forge_measure=off` cookie is set on the forge's host and never reaches an app's. Read the numbers (visitors today and over 7 days, p75 TTFB, load, LCP, INP and CLS) on the app's settings page under **Visitors and speed**, or as `vitals` in an admin's `GET /api/v1/repos/:owner/:name/app`. Both doors show them only to people who administer the repository (`appVisitors` in `src/actions/apps.ts`), so a reader or an anonymous caller sees no `vitals`. The page also draws p75 load for each of the last 30 days as a sparkline (server-rendered, no script); a day with no reports is a gap in the line, not a zero, and an app with none in 30 days says so in words. The same 30 values, oldest first with `null` for a silent day, are `vitals.loadDays` in the API. In the terminal all five are on the second line of the app's **Deploys** screen over ssh, and a third line there shows the 30 days as block characters with `·` for a silent day, then the range.
223223
224224 A writer of the app's repository redeploys production from the terminal's **Deploys** screen with `D` and stops it with `S`, each after a one-line confirm that names the app and production. They are the page's and MCP `app_deploy`'s actions (`redeployEnv`, `stopEnv`), answered in the page's words (`src/actions/env_words.ts`). The title line shows production's state, a stopped production offers `D` only, and a reader sees neither key.
225225
docs/features/app-visitors-readers.md added +13
@@ -0,0 +1,13 @@
1 ---
2 topic: What a forge is
3 row: An app's visitors leave out signed-in readers
4 ---
5 # An app's visitors leave out signed-in readers (#6613)
6
7 An app's visitor counts are for the people who come to it, not the people who build it. A report from someone signed in to the forge who may read the app's repository (they hold a grant cookie that names them) is stored with `member = 1`, not dropped, so the choice stays yours.
8
9 - **Page.** Settings → the app → **Visitors and speed** says what it counts in one line. The link under it, "Count signed-in readers in the visitor counts" (`?members=1#visitors`), flips the counts; "Leave signed-in readers out of the visitor counts" (`?#visitors`) flips them back. Only the visitor counts change: speed (TTFB, load, LCP, INP, CLS) and its sparkline always count everyone.
10 - **Terminal.** On the app's **Deploys** screen the visitors line says `(readers out)`; press `v` to count them (`readers in`), `v` again to leave them out. Same numbers as the page.
11 - **API.** `GET /api/v1/repos/:owner/:name/app?members=1` counts them in `vitals`; without it they are left out.
12
13 How visitors are told apart is unchanged: a hash of address and browser under the day's salt, no address kept. A signed-in reader is flagged rather than left unhashed, so the count can be changed back after the fact; reports stored before this change count as visitors.
src/actions/apps.ts +2 −2
@@ -635,10 +635,10 @@ export function appView(
635635 * An app's visitors and speed, for those who administer its repository: the
636636 * same gate as the settings card, so every door shows them to the same people.
637637 */
638 export function appVisitors(app: App, actor: User | undefined, repo: Repo): AppVitals | undefined {
638 export function appVisitors(app: App, actor: User | undefined, repo: Repo, withMembers = false): AppVitals | undefined {
639639 if (!canAdmin(app.db, repo, actor)) return undefined;
640640 const record = getAppByRepo(app.db, repo.id);
641 return record === undefined ? undefined : appVitals(app.db, record.id);
641 return record === undefined ? undefined : appVitals(app.db, record.id, Date.now(), withMembers);
642642 }
643643
644644 /** The golden path's pace line, for whoever may read the app's repository; `""` until there is one. */
src/apps/measure.ts +4
@@ -52,6 +52,7 @@ export async function appMeasure(
5252 app: App,
5353 request: Request,
5454 target: AppTarget,
55 member = false,
5556 ): Promise<Response> {
5657 if (request.method !== "POST") return refuse(405, { allow: "POST" });
5758 if (!sameOrigin(request)) return refuse(403);
@@ -88,6 +89,9 @@ export async function appMeasure(
8889 report,
8990 clientAddress(request),
9091 request.headers.get("user-agent") ?? "",
92 Date.now(),
93 undefined,
94 member,
9195 );
9296 noteView(app.db, {
9397 scope: target.app.id,
src/apps/proxy.ts +5 −1
@@ -1322,7 +1322,11 @@ async function proxyAppAnswer(
13221322 const admitted = admit(runtime, request, target);
13231323 if (!admitted.ok) return securityFloor(admitted.error);
13241324 }
1325 return securityFloor(await appMeasure(runtime.app, request, target));
1325 // A grant is only given to someone signed in who may read the repository: that visit is marked,
1326 // not lost.
1327 const grant = cookieValue(request, grantCookieName(target));

This is the only place member=1 is set and nothing tests it. Add a test through the route covering a beacon with a valid grant cookie, one with a forged or expired cookie, and one with none.

1328 const member = grant !== undefined && readGrant(runtime.app.config.dataDir, grant, target)?.who !== undefined;
1329 return securityFloor(await appMeasure(runtime.app, request, target, member));
13261330 }
13271331 // An environment asleep wakes for the request that wants it, and the
13281332 // request waits the second that takes rather than seeing a closed door.
src/apps/vitals.ts +9 −8
@@ -20,6 +20,7 @@ export function recordAppVital(
2020 agent: string,
2121 at: number = Date.now(),
2222 dayMax: number = DAY_MAX,
23 member = false,
2324 ): boolean {
2425 const day = dayOf(at);
2526 db.run("DELETE FROM app_vital WHERE at < ?", [at - KEEP_MS]);
@@ -31,8 +32,8 @@ export function recordAppVital(
3132 if ((held?.n ?? 0) >= dayMax) return false;
3233 const visitor = sha256(`${saltFor(db, at)}\0${appId}\0${client}\0${agent}`).slice(0, 32);
3334 db.run(
34 "INSERT INTO app_vital (app_id, day, at, visitor, ttfb, load, lcp, inp, cls) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
35 [appId, day, at, visitor, report.ttfb, report.load, report.lcp, report.inp, report.cls],
35 "INSERT INTO app_vital (app_id, day, at, visitor, ttfb, load, lcp, inp, cls, member) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
36 [appId, day, at, visitor, report.ttfb, report.load, report.lcp, report.inp, report.cls, member ? 1 : 0],
3637 );
3738 return true;
3839 }
@@ -73,14 +74,14 @@ function p75(db: Database, appId: string, column: "ttfb" | "load" | "lcp" | "inp
7374 }
7475
7576 /** Production's visitors and speed (a preview's report is never stored). */
76 export function appVitals(db: Database, appId: string, at: number = Date.now()): AppVitals {
77 export function appVitals(db: Database, appId: string, at: number = Date.now(), withMembers = false): AppVitals {
7778 const since = dayOf(at - 6 * DAY);
7879 const count = (from: string): number =>
7980 db
80 .query<{ n: number }, [string, string]>(
81 "SELECT COUNT(*) AS n FROM (SELECT DISTINCT day, visitor FROM app_vital WHERE app_id = ? AND day >= ?)",
81 .query<{ n: number }, [string, string, number]>(
82 "SELECT COUNT(*) AS n FROM (SELECT DISTINCT day, visitor FROM app_vital WHERE app_id = ? AND day >= ? AND (member = 0 OR ?))",
8283 )
83 .get(appId, from)?.n ?? 0;
84 .get(appId, from, withMembers ? 1 : 0)?.n ?? 0;
8485 const wait = relayWait(appId, at);
8586 return {
8687 today: count(dayOf(at)),
@@ -123,8 +124,8 @@ export const speedText = (v: number | undefined): string =>
123124 export const shiftText = (v: number | undefined): string => (v === undefined ? "–" : v.toFixed(2));
124125
125126 /** The one line the terminal shows, and the slowest relayed wait's words when there is one. */
126 export const visitorsLine = (v: AppVitals): string =>
127 `visitors ${v.today} today, ${v.week} in 7 days · p75 TTFB ${speedText(v.ttfbP75)} · load ${speedText(v.loadP75)} · LCP ${speedText(v.lcpP75)} · INP ${speedText(v.inpP75)} · CLS ${shiftText(v.clsP75)}` +
127 export const visitorsLine = (v: AppVitals, withMembers = false): string =>
128 `visitors ${v.today} today, ${v.week} in 7 days (readers ${withMembers ? "in" : "out"}) · p75 TTFB ${speedText(v.ttfbP75)} · load ${speedText(v.loadP75)} · LCP ${speedText(v.lcpP75)} · INP ${speedText(v.inpP75)} · CLS ${shiftText(v.clsP75)}` +
128129 (v.wait === undefined ? "" : ` · slowest wait, 10 min: ${relayWaitWords(v.wait)}`);
129130
130131 /** Thirty days of load as blocks, oldest first, `·` for a silent day: "▁▃█·▂". Empty with no data. */
src/core/account_purge.ts +1
@@ -69,6 +69,7 @@ export const COVERED: Readonly<Record<string, Coverage>> = {
6969 "app_feature.absorbed_by": FORMER,
7070 "app_feature_setting.set_by": FORMER,
7171 "app_flag.updated_by": FORMER,
72 "app_vital.member": { do: "none", why: "a 0/1 mark that the visit was by a signed-in reader of the repository; it names no one" },
7273 "bet.backed_by": FORMER,
7374 "check_proven.proven_by": FORMER,
7475 "check_runner.created_by": FORMER,
src/core/migration-pins/20261201090000-app-vital-member.pin added +1
@@ -0,0 +1,1 @@
1 63c1b7bde742fff0586aa2e8d31f388c647045a08dc1182493544bf28e101bf9
src/core/migrations/20261201090000-app-vital-member.ts added +5
@@ -0,0 +1,5 @@
1 // A visit by someone signed in to the forge and allowed to read the app's repository is marked,
2 // so an app's visitors can leave out its own people (#6613). Additive; older rows read 0.
3 export default `
4 ALTER TABLE app_vital ADD COLUMN member INTEGER NOT NULL DEFAULT 0;
5 `;
src/flow/kpi_words.ts +7
@@ -8,6 +8,13 @@ import type { Kpis } from "./kpis.ts";
88 import type { Reach } from "./reach.ts";
99 import { ATTENTION_REQUESTS, TRAFFIC_CLASSES, type TrafficClass, type TrafficTotals } from "../perf/traffic.ts";
1010
11 /**
12 * What an app's visitor figures count, one plain sentence (#6613): the settings page's line under
13 * the title.
14 */
15 export const APP_VISITORS_COUNT =
16 "Visitors are browsers that loaded your app, counted once a day; people signed in to read the repository are left out unless you include them, and speed counts everyone.";
17
1118 /**
1219 * What each home number counts, one sentence each: the tile's title and the
1320 * probe's `counts` (`web/studio/kpi_probe.ts`) read the same words.
src/generated/migrations.ts +6 −4
@@ -442,8 +442,9 @@ import m437 from "../core/migrations/20261130170000-fence-read-from.ts";
442442 import m438 from "../core/migrations/20261130170100-chat-build-lane.ts";
443443 import m439 from "../core/migrations/20261130235220-run-check-plan.ts";
444444 import m440 from "../core/migrations/20261201000000-games.ts";
445 import m441 from "../core/migrations/20261201120000-first-change-forge.ts";
446 import m442 from "../core/migrations/20261201121000-repo-check-slots.ts";
445 import m441 from "../core/migrations/20261201090000-app-vital-member.ts";
446 import m442 from "../core/migrations/20261201120000-first-change-forge.ts";
447 import m443 from "../core/migrations/20261201121000-repo-check-slots.ts";
447448
448449 /** Each migration file's name and its default export, in name order. */
449450 export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
@@ -888,6 +889,7 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
888889 ["20261130170100-chat-build-lane.ts", m438],
889890 ["20261130235220-run-check-plan.ts", m439],
890891 ["20261201000000-games.ts", m440],
891 ["20261201120000-first-change-forge.ts", m441],
892 ["20261201121000-repo-check-slots.ts", m442],
892 ["20261201090000-app-vital-member.ts", m441],
893 ["20261201120000-first-change-forge.ts", m442],
894 ["20261201121000-repo-check-slots.ts", m443],
893895 ];
src/http/api/app.ts +1 −1
@@ -115,7 +115,7 @@ export function appRoutes(router: Router<Handler>): void {
115115 const read = timePhase(ctx.request, "app", () => {
116116 const view = appView(ctx.app, ctx.auth.user, repo);
117117 if (!view.ok) return null;
118 return { view: view.value, vitals: appVisitors(ctx.app, ctx.auth.user, repo) };
118 return { view: view.value, vitals: appVisitors(ctx.app, ctx.auth.user, repo, ctx.url.searchParams.get("members") === "1") };

The ?members=1 API door has no test. Add one: the default leaves readers out, ?members=1 counts them, and a non-admin still gets no vitals.

119119 });
120120 if (!read) return notFound();
121121 return timePhase(ctx.request, "render", () =>
src/tui/screens/deploys.ts +10 −2
@@ -234,6 +234,8 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
234234 let rebuilding: Promise<void> = Promise.resolve();
235235 let loaded = false;
236236 let visitors = "";
237 /** Whether the visitor figures count people signed in to read the repository (`v` flips it). */
238 let withReaders = false;
237239 let trend = "";
238240 let pace = "";
239241 let side: string[] = [];
@@ -276,8 +278,8 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
276278 () => undefined,
277279 );
278280 }
279 const seen = appVisitors(f.app, f.user, repo);
280 visitors = seen === undefined ? "" : visitorsLine(seen);
281 const seen = appVisitors(f.app, f.user, repo, withReaders);
282 visitors = seen === undefined ? "" : visitorsLine(seen, withReaders);
281283 trend = seen === undefined ? "" : trendLine(seen.loadDays);
282284 pace = appPace(f.app, f.user, repo);
283285 side = appSideLines(f.app, f.user, repo);
@@ -427,6 +429,7 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
427429 ]),
428430 ...(mayProbe ? [binding(["p"], "probe the running app's doors")] : []),
429431 ...(members ? [binding(["m"], "members")] : []),
432 ...(visitors !== "" ? [binding(["v"], withReaders ? "leave readers out" : "count readers")] : []),
430433 ...(mayInvite() ? [binding(["W"], "who works on it: invite, list, take off")] : []),
431434 ...(domains !== undefined ? [binding(["n"], "the app's own domains")] : []),
432435 ...(prompts ? [binding(["i"], "prompt source (Instagram)")] : []),
@@ -566,6 +569,11 @@ export function deploysScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
566569 read();
567570 return true;
568571 }
572 if (e.key === "v" && visitors !== "") {

The v toggle has no test. Add one that presses v on the Deploys screen and checks that the line and the key-bar label flip.

573 withReaders = !withReaders;
574 read();
575 return true;
576 }
569577 if ((e.key === "D" || e.key === "S") && inPreviews) {
570578 const target = previewActs();
571579 if (target !== undefined && (e.key === "D" || target.stop))
src/web/pages/settings.ts +9 −4
@@ -67,6 +67,7 @@ import { updateRepoSettings } from "../../actions/repos.ts";
6767 import { appsRuntime } from "../../apps/runtime.ts";
6868 import { nameFrame, notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
6969 import { appVitals, shiftText, speedText as ms, type AppVitals } from "../../apps/vitals.ts";
70 import { APP_VISITORS_COUNT } from "../../flow/kpi_words.ts";
7071 import { relayWaitWords } from "../../apps/relay_wait.ts";
7172 import type { PreviewData } from "../../apps/data.ts";
7273 import {
@@ -851,8 +852,10 @@ function appSettingsView(
851852 const domains = timePhase(ctx.request, "domains", () =>
852853 listAppDomains(ctx.app, ctx.auth.user, repo),
853854 );
855 /** Whether the visitor counts take in signed-in readers (`?members=1`, #6613). */
856 const withReaders = ctx.url.searchParams.get("members") === "1";
854857 const vitals = timePhase(ctx.request, "vitals", () =>
855 appVitals(ctx.app.db, record.id),
858 appVitals(ctx.app.db, record.id, Date.now(), withReaders),
856859 );
857860 const help = pageHelp(
858861 [
@@ -865,7 +868,7 @@ function appSettingsView(
865868 );
866869 return html`${help}${form}${flagged}
867870 ${when(listed?.ok === true, () => html`<div class="mt">${appMembersView(base, values.access, named)}</div>`)}
868 <div class="mt">${appVisitorsView(vitals)}</div>
871 <div class="mt">${appVisitorsView(vitals, withReaders)}</div>
869872 <div class="mt">${statement}</div>
870873 <div class="mt">
871874 ${appEnvView(base, (() => { const l = listAppEnv(ctx.app, ctx.auth.user, repo); return l.ok ? l.value : []; })())}
@@ -908,7 +911,7 @@ function appSettingsView(
908911 }
909912
910913 /** Production's visitors and the speed they saw, from the app's own beacon. */
911 export function appVisitorsView(v: AppVitals): Html {
914 export function appVisitorsView(v: AppVitals, members = false): Html {
912915 const known = v.loadDays.filter((n): n is number => n !== null);
913916 const latest = v.loadDays.findLast((n) => n !== null) ?? null;
914917 const spark = daySpark(
@@ -919,7 +922,9 @@ export function appVisitorsView(v: AppVitals): Html {
919922 );
920923 return html`<section class="settings-block" id="visitors">
921924 <h2>Visitors and speed</h2>
922 <p class="small mb"><a href="app/traffic">Where visitors come from</a></p>
925 <p class="small muted">${APP_VISITORS_COUNT}</p>
926 <p class="small mb"><a href="app/traffic">Where visitors come from</a> ·
927 ${members ? html`<a href="?#visitors">Leave signed-in readers out of the visitor counts</a>` : html`<a href="?members=1#visitors">Count signed-in readers in the visitor counts</a>`}</p>
923928 <dl class="stats">
924929 <div><dt>Visitors today</dt><dd>${v.today}</dd></div>
925930 <div><dt>Visitors, 7 days</dt><dd>${v.week}</dd></div>
test/app-vitals-members-route.test.ts added +122
@@ -0,0 +1,122 @@
1 /**
2 * Who is marked a member is decided at the beacon's door, and the settings page and the terminal
3 * line say which count they show (#6613).
4 */
5
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { newApp } from "../src/actions/apps.ts";
12 import { AppsRuntime } from "../src/apps/runtime.ts";
13 import { signGrant } from "../src/apps/grants.ts";
14 import { appVitals, visitorsLine } from "../src/apps/vitals.ts";
15 import { getAppByRepo, type AppRecord } from "../src/core/apps.ts";
16 import { createUser } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19
20 quietLogs();
21
22 const DOMAIN = "apps.test";
23 let dataDir: string;
24 let app: App;
25 let servers: Servers;
26 let runtime: AppsRuntime;
27 let record: AppRecord;
28 let session = "";
29
30 beforeAll(async () => {
31 dataDir = await mkdtemp(join(tmpdir(), "forge-members-route-"));
32 app = createApp({ dataDir, port: 0, host: "forge.test" });
33 servers = await serve(app);
34 runtime = new AppsRuntime(app, { domain: DOMAIN, scheme: "http", publicPort: servers.port, forgeUrl: servers.url, concurrency: 1 });
35 await runtime.start();
36 const alice = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
37 if (!alice.ok) throw new Error(alice.error);
38 const made = await newApp(app, alice.value, { name: "notes", description: "Words", visibility: "public" });
39 if (!made.ok) throw new Error(String(made.error));
40 record = getAppByRepo(app.db, made.value.repo.id)!;
41 const signin = await fetch(`${servers.url}/signin`, {
42 method: "POST",
43 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
44 redirect: "manual",
45 });
46 session = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
47 }, 120_000);
48
49 afterAll(async () => {
50 await runtime.stop();
51 servers.stop();
52 app.close();
53 await rm(dataDir, { recursive: true, force: true });
54 });
55
56 const beacon = (cookie: string, address: string) =>
57 fetch(`${servers.url}/__forge/measure`, {
58 method: "POST",
59 body: JSON.stringify({ path: "/", ttfb: 40, load: 800, lcp: 600, inp: 90, cls: 0 }),
60 headers: { host: `notes.${DOMAIN}`, origin: `http://notes.${DOMAIN}`, "user-agent": `t${address}`, ...(cookie ? { cookie } : {}) },
61 });
62 const stored = (): number[] =>
63 app.db.query<{ member: number }, [string]>("SELECT member FROM app_vital WHERE app_id = ? ORDER BY id").all(record.id).map((r) => r.member);
64
65 test("a beacon with a valid grant naming someone is stored as member, any other as not", async () => {
66 const name = `forge_grant_${record.id.slice(-8)}`;
67 const target = { app: record, env: "production" } as Parameters<typeof signGrant>[1];
68 const who = { id: "u1", name: "alice", role: "admin" as const };
69 const valid = signGrant(dataDir, target, 60_000, Date.now(), who);
70 const expired = signGrant(dataDir, target, 60_000, Date.now() - 120_000, who);
71 const anonymous = signGrant(dataDir, target, 60_000);
72 const forged = valid.slice(0, -3) + "AAA";
73 const tampered = valid.replace(".alice.", ".mallory.");
74 for (const [i, cookie] of [`${name}=${valid}`, `${name}=${forged}`, `${name}=${expired}`, `${name}=${tampered}`, `${name}=${anonymous}`, ""].entries())
75 expect((await beacon(cookie, `10.0.0.${i + 1}`)).status).toBe(204);
76 expect(stored()).toEqual([1, 0, 0, 0, 0, 0]);
77 expect(appVitals(app.db, record.id).today).toBe(5);
78 expect(appVitals(app.db, record.id, Date.now(), true).today).toBe(6);
79 });
80
81 test("the settings page leaves readers out by default, counts them with ?members=1, and the link flips", async () => {
82 const get = async (query: string) =>
83 (await fetch(`${servers.url}/alice/notes/settings/app${query}`, { headers: { cookie: session } })).text();
84 const out = await get("");
85 const today = (page: string): string | undefined => /Visitors today<\/dt>\s*<dd>(\d+)/.exec(page)?.[1];
86 expect(today(out)).toBe("5");
87 expect(out).toContain('href="?members=1#visitors"');
88 expect(out).not.toContain('href="?#visitors"');
89 const withThem = await get("?members=1");
90 expect(today(withThem)).toBe("6");
91 expect(withThem).toContain('href="?#visitors"');
92 expect(withThem).not.toContain('href="?members=1#visitors"');
93 });
94
95 test("the terminal's line says which count it shows", () => {
96 const v = appVitals(app.db, record.id);
97 expect(visitorsLine(v)).toContain("visitors 5 today");
98 expect(visitorsLine(v)).toContain("(readers out)");
99 expect(visitorsLine(appVitals(app.db, record.id, Date.now(), true), true)).toContain("visitors 6 today, 6 in 7 days (readers in)");
100 });
101
102 test("the API's app read leaves readers out by default, counts them with ?members=1, and a non-admin gets no vitals", async () => {
103 const read = async (query: string, cookie: string) => {
104 const res = await fetch(`${servers.url}/api/v1/repos/alice/notes/app${query}`, { headers: { cookie } });
105 expect(res.status).toBe(200);
106 return (await res.json()) as { vitals?: { today: number; week: number } };
107 };
108 expect((await read("", session)).vitals?.today).toBe(5);
109 expect((await read("?members=1", session)).vitals?.today).toBe(6);
110 expect((await read("?members=0", session)).vitals?.today).toBe(5);
111 const bob = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
112 if (!bob.ok) throw new Error(bob.error);
113 const signin = await fetch(`${servers.url}/signin`, {
114 method: "POST",
115 body: new URLSearchParams({ username: "bob", password: "a-good-passphrase" }),
116 redirect: "manual",
117 });
118 const bobSession = (signin.headers.get("set-cookie") ?? "").split(";")[0]!;
119 expect(bobSession).toContain("=");
120 expect((await read("", bobSession)).vitals).toBeUndefined();
121 expect((await read("?members=1", bobSession)).vitals).toBeUndefined();
122 });
test/app-vitals-members.test.ts added +23
@@ -0,0 +1,23 @@
1 /** Signed-in readers of the repository are left out of an app's visitors by default (#6613). */

This tests the column and the query only. Add a test for the grant-cookie detection (see proxy.ts) and one for the settings toggle (?members=1 changes Visitors today and the link text).

2
3 import { expect, test } from "bun:test";
4 import { mkdtemp } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp } from "../src/app.ts";
8 import { appVitals, recordAppVital } from "../src/apps/vitals.ts";
9 import type { Report } from "../src/web/measure.ts";
10
11 test("the owner loading the app 5 times from 2 addresses counts 0, and 2 with the toggle", async () => {
12 const app = createApp({ dataDir: await mkdtemp(join(tmpdir(), "forge-members-")), port: 0, host: "forge.test" });
13 const report: Report = { path: "/", ttfb: 10, load: 100, lcp: 100, inp: 10, cls: 0 };
14 const at = Date.UTC(2026, 11, 1, 12);
15 for (const client of ["1.1.1.1", "2.2.2.2", "1.1.1.1", "2.2.2.2", "1.1.1.1"])
16 recordAppVital(app.db, "app1", report, client, "ua", at, undefined, true);
17 expect(appVitals(app.db, "app1", at).today).toBe(0);
18 expect(appVitals(app.db, "app1", at).week).toBe(0);
19 expect(appVitals(app.db, "app1", at, true).today).toBe(2);
20 recordAppVital(app.db, "app1", report, "3.3.3.3", "ua", at);
21 expect(appVitals(app.db, "app1", at).today).toBe(1);
22 expect(appVitals(app.db, "app1", at, true).today).toBe(3);
23 });
test/tui-deploys.test.ts +35 −1
@@ -132,7 +132,7 @@ test("an admin sees the app's visitors and speed above the deploys, and a reader
132132 const record = made.value;
133133 const at = Date.now();
134134 recordAppVital(forge.db, record.id, { path: "/", ttfb: 90, load: 420, lcp: 1300, inp: 80, cls: 0.05 }, "c", "u", at);
135 expect(await screenText(alice, r.value)).toContain("visitors 1 today, 1 in 7 days · p75 TTFB 90 ms · load 420 ms · LCP 1.3 s · INP 80 ms · CLS 0.05");
135 expect(await screenText(alice, r.value)).toContain("visitors 1 today, 1 in 7 days (readers out) · p75 TTFB 90 ms · load 420 ms · LCP 1.3 s · INP 80 ms · CLS 0.05");
outdated

The expectation now stops at INP and drops CLS. The line is cut off at 80 columns because the new text is too long, which is a regression you made the test hide. Shorten the line and restore the CLS expectation.

136136 const c = await signUp(forge, {
137137 username: "carol",
138138 email: "[email protected]",
@@ -142,6 +142,40 @@ test("an admin sees the app's visitors and speed above the deploys, and a reader
142142 expect(await screenText(c.value, r.value)).not.toContain("visitors");
143143 });
144144
145 test("v on the Deploys screen counts readers in the visitors line and the key bar flips (#6613)", async () => {
146 const r = await createRepo(forge, alice, { name: "booth", visibility: "public" });
147 if (!r.ok) throw new Error("repo failed");
148 const made = createAppRecord(forge.db, { repoId: r.value.id, slug: "booth", access: "public" });
149 if (!made.ok) throw new Error(made.error);
150 const report = { path: "/", ttfb: 90, load: 420, lcp: 1300, inp: 80, cls: 0.05 };
151 recordAppVital(forge.db, made.value.id, report, "stranger", "u", Date.now());
152 recordAppVital(forge.db, made.value.id, report, "reader", "u", Date.now(), undefined, true);
153 const terminal = headlessTerminal(200, 30);
154 const { app, session } = createForgeApp(
155 forge,
156 { sshUsername: alice.username, remoteAddress: "127.0.0.1", user: alice },
157 { terminal, exitHooks: false },
158 );
159 app.start();
160 await settleApp(app);
161 app.push(deploysScreen(session, app.ctx, r.value));
162 await settleApp(app);
163 const before = app.screen.toText();
164 terminal.feed("v");
165 await settleApp(app);
166 const after = app.screen.toText();
167 terminal.feed("v");
168 await settleApp(app);
169 const back = app.screen.toText();
170 app.stop();
171 expect(before).toContain("visitors 1 today, 1 in 7 days (readers out)");
172 expect(before).toContain("count readers");
173 expect(after).toContain("visitors 2 today, 2 in 7 days (readers in)");
174 expect(after).toContain("leave readers out");
175 expect(after).not.toContain("count readers");
176 expect(back).toContain("visitors 1 today, 1 in 7 days (readers out)");
177 });
178
145179 test("the app's open pulls list below the deploys with check word and preview, and a guest sees none", async () => {
146180 const r = await createRepo(forge, alice, { name: "kiosk", visibility: "public" });
147181 if (!r.ok) throw new Error("repo failed");

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs