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

Talk's live workspace shows its own speed: edit-to-preview and Test what I touched, each with its p95 against its target #17378

opened this

Merged 31h 22m ago, live in production

scout/forge:scout/17374-talk-s-live-workspace-shows-its-own-spee → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/17374-talk-s-live-workspace-shows-its-own-spee was merged into main as 20a1488.

Review

Sign in to review this change.
13 files changed +442 −22
docs/design/areas/talk.md +1
@@ -112,6 +112,7 @@ Prior art: Claude and ChatGPT (one centred column, the person's words in a quiet
112112 - `.talk-addr-pick`: the address bar as a switcher, a `<form method="get">` in the same muted pill: a repository `<select>`, a branch `<select>` after a `▸` (the default branch for Live, each open pull's head branch), a path `<input>`; with the script a pick swaps the pane in place, without it the form's `.talk-addr-go` button (hidden under `:root.js`) sends it.
113113 - `.talk-dev-status`: the workspace's status in a muted pill after the address: Starting, Live, Reloading, or a bold Error (its file and line in the `title`, with what to do next; the terminal prints them in the line); `data-dev-status` carries the state (`paneStatus`, `src/actions/dev_workspace.ts`).
114114 - `.talk-pane-info`: one muted line under the bar: for a pull's preview who made it, its number and title, checks and review, and a link to the pull; for Live the default branch and what last landed (`paneInfo`, the terminal prints the same).
115 - `.talk-pane-loop`: one muted line under the info line: the loop's p95s beside their targets ("reload 0.4 s · tests 48 s · targets 1 s and 2 min"), a warning `badge` (`data-variant=attn`) naming one over its target; drawn only once a sample exists (`loopLine`, the terminal prints the same).
115116 - `.talk-pane-fell`: one line when a picked pull's preview is gone: "#N landed: Live has it now."
116117 - `.talk-diff-change`: in Diff, one pull this conversation's work led to: a `<details>` whose summary links the pull and says landed, open or closed, the newest open.
117118 - `.talk-crew-fold`: the crew's block while it works, a `<details>` whose summary is its one working line; folded, the fold is kept per conversation. A hold or a failure is drawn without it, so it can never be folded away.
docs/features/talk-workspace.md +5 −1
@@ -32,7 +32,11 @@ A workspace's changes are a **working tree**, not a commit per write (`src/actio
3232 - **Diff tab:** over the commits, the uncommitted files as a diff against the branch's tip, with **Commit** (one commit, your message) and **Discard**.
3333 - **Terminal:** the `p` view says `Not committed yet: N files on <branch>` and has the same three actions: `e` saves a file live (path, then its text on one line, `\n` for a line break), `C` commits with your message, `X` discards.
3434
35 Not yet: the dev server reading the working tree, so the dev frame does not reload from uncommitted files.
35 A live save also lays the file into the checkout of your live dev cell for that branch (`reachCell`, symlinks never written through), so its hot reload sees it. Not yet: a commit-less save with no dev cell running only reaches the Diff and Test tabs.
36
37 ## The loop's speed (#17374)
38
39 The bar shows how long the loop takes, as p95 over the last 50 samples beside its target: `reload 0.4 s · tests 48 s · targets 1 s and 2 min` (`src/core/loop_samples.ts`). **Reload** is edit-to-preview: from a live save (Code tab or Talk's `write_file` with `live`) that reached the dev cell to the frame asking the dev server for its document again (`src/web/pages/talk_dev.ts`); only an app whose hot reload reloads the page (a full document request after the save) gives a sample; one that swaps modules in place gives none, and a save the frame does not follow within 10 seconds is dropped, so a later navigation is not counted as a reload. **Tests** is the wall time of each Test what I touched run that ran tests, passed or failed. The targets in the line come from `TARGETS_MS`, not from this text. Over its target, a figure gets a warning badge naming it (not red). Samples live in memory and in `<data>/dev/loop-samples.json`, written after the request. The terminal's `p` view prints the same `Loop:` line (`src/tui/screens/talk_chats.ts`), and the MCP `pane` tool answers it as `loop` (`reload`, `tests`, each `p95Ms`, `samples`, `targetMs`, `over`, plus `words`).
3640
3741 ## Test what I touched, and Open pull (#17121, W3)
3842
src/actions/touched_run.ts +5 −18
@@ -9,7 +9,7 @@
99
1010 import { createHash } from "node:crypto";
1111 import { existsSync } from "node:fs";
12 import { lstat, mkdir, readdir } from "node:fs/promises";
12 import { mkdir, readdir } from "node:fs/promises";
1313 import { basename, dirname, join } from "node:path";
1414 import type { App } from "../app.ts";
1515 import { appsRuntime } from "../apps/runtime_registry.ts";
@@ -24,7 +24,9 @@ import { editsOf } from "../core/working_tree.ts";
2424 import { isSafeRef, isSafeTreePath } from "../git/guard.ts";
2525 import { repoDir } from "../git/repos.ts";
2626 import { err, ok, type Result } from "../kernel/result.ts";
27 import { recordLoop } from "../core/loop_samples.ts";
2728 import { requireWriter } from "./access.ts";
29 import { noLinkUnder } from "./link_free.ts";
2830 import { impactIn, planTouched, type TouchedFile, type TouchedPlan } from "./touched_plan.ts";
2931
3032 /** What a run says of itself. `error`: it could not be run at all. */
@@ -96,23 +98,6 @@ async function testFilesIn(dir: string): Promise<string[]> {
9698 return out;
9799 }
98100
99 /**
100 * True when no segment of `rel` under `dir` is a symlink (a branch can commit one that points out
101 * of the checkout; the string check of `isSafeTreePath` cannot see it). Missing segments are fine.
102 */
103 async function noLinkUnder(dir: string, rel: string): Promise<boolean> {
104 let at = dir;
105 for (const part of rel.split("/")) {
106 at = join(at, part);
107 try {
108 if ((await lstat(at)).isSymbolicLink()) return false;
109 } catch {
110 return true;
111 }
112 }
113 return true;
114 }
115
116101 /**
117102 * The checkout of this person's test runs for `branch`: synced to the tip, the working tree laid
118103 * over it. Gives what each touched file was at the tip beside what it is now.
@@ -226,6 +211,8 @@ export async function startTouched(app: App, actor: User | undefined, repo: Repo
226211 }
227212 // Names that passed SAFE_TEST only: nothing a person typed reaches the command.
228213 const tested = await run1(`bun test ${run.plan.files.join(" ")}`, say, abort.signal);
214 // Wall time of the whole run, with whether it passed: the loop's p95 reads these.
215 recordLoop(app, "tests", Date.now() - run.startedAt, tested.ok);
229216 finish(tested.ok ? "green" : "red");
230217 })().catch((cause: unknown) => {
231218 say(cause instanceof Error ? cause.message : "The run stopped.");
src/actions/working_tree.ts +28
@@ -5,7 +5,12 @@
55 * so both doors say the same.
66 */
77
8 import { mkdir } from "node:fs/promises";
9 import { dirname, join } from "node:path";
810 import type { App } from "../app.ts";
11 import { devCellsOf } from "../apps/dev_cell.ts";
12 import { devKey } from "../apps/dev_launch.ts";
13 import { noLinkUnder } from "./link_free.ts";
914 import { commitIdentity } from "../core/commit_identity.ts";
1015 import type { Repo } from "../core/repos.ts";
1116 import type { User } from "../core/users.ts";
@@ -60,9 +65,32 @@ export async function saveWorking(app: App, actor: User | undefined, repo: Repo,
6065 const known = editsOf(app.db, writer.value.id, repo.id, branch);
6166 if (known.length >= WORKING_FILES_MAX && !known.some((e) => e.path === path)) return err("too_many");
6267 saveEdit(app.db, writer.value.id, repo.id, branch, path, content);
68 reachCell(app, writer.value.id, repo.id, branch, path, content);
6369 return ok({ files: editCount(app.db, writer.value.id, repo.id, branch) });
6470 }
6571
72 /**
73 * Lay a saved file into the checkout of this person's live dev cell for the branch, so its hot
74 * reload sees it, and start the edit-to-preview clock (the frame's next document request stops it,
75 * `talk_dev.ts`). Off the request's path: the write is not awaited. No live cell, nothing to do.
76 */
77 function reachCell(app: App, userId: string, repoId: string, branch: string, path: string, content: string): void {
78 const cell = devCellsOf(app).get(devKey(userId, repoId, branch));
79 if (cell === undefined || cell.state !== "live" || cell.dir === undefined) return;
80 const dir = cell.dir;
81 cell.wroteAt = Date.now();
82 void (async () => {
83 if (!(await noLinkUnder(dir, path))) {
84 delete cell.wroteAt;
85 return;
86 }
87 await mkdir(dirname(join(dir, path)), { recursive: true });
88 await Bun.write(join(dir, path), content);
89 })().catch(() => {
90 delete cell.wroteAt;
91 });
92 }
93
6694 /**
6795 * The working tree against the branch's tip: what a commit now would add. Empty when nothing
6896 * changed.
src/apps/dev_cell.ts +2
@@ -52,6 +52,8 @@ export interface DevCell {
5252 /** The checkout's commit last synced; a newer tip is synced into it so the server reloads. */
5353 oid?: string;
5454 dir?: string;
55 /** When a live save was last written into the checkout and the frame has not yet reloaded. */
56 wroteAt?: number;
5557 /** A sync of the checkout is under way. */
5658 syncing?: boolean;
5759 /** A push landed while it was syncing: sync once more after. */
src/core/loop_samples.ts added +106
@@ -0,0 +1,106 @@
1 /**
2 * How long Talk's live loop takes (#17374): edit-to-preview (a save that reached the dev cell, to
3 * the frame asking for its document again) and Test what I touched (wall time, and whether it
4 * passed). The last 50 of each are kept per forge, in memory, and mirrored to one small file under
5 * the data directory so a restart keeps them. Recording is a push and a fire-and-forget write: it
6 * is never on a request's way. Plain data in, plain data out, so the page, the terminal and the
7 * `pane` tool say the same.
8 */
9
10 import { existsSync, readFileSync } from "node:fs";
11 import { join } from "node:path";
12 import type { App } from "../app.ts";
13 import { heldOf } from "../perf/held.ts";
14 import { p95 } from "../rules/budget_rerun.ts";
15
16 /** The newest samples a p95 is read over. */
17 export const SAMPLES_MAX = 50;
18 /** What each loop is held to: a reload within a second, the tests within two minutes. */
19 export const TARGETS_MS = { reload: 1000, tests: 120_000 } as const;
20
21 export type LoopKind = keyof typeof TARGETS_MS;
22
23 export interface LoopSample {
24 readonly ms: number;
25 /** Tests only: the run passed. */
26 readonly passed?: boolean;
27 }
28
29 export interface LoopFigure {
30 readonly kind: LoopKind;
31 /** p95 over the newest samples, in ms; undefined until one is recorded. */
32 readonly p95Ms: number | undefined;
33 readonly samples: number;
34 readonly targetMs: number;
35 readonly over: boolean;
36 }
37
38 export interface LoopReading {
39 readonly reload: LoopFigure;
40 readonly tests: LoopFigure;
41 /** Just the figures: "reload 0.4 s · tests 48 s". */
42 readonly shown: string;
43 /** "reload 0.4 s · tests 48 s", with what is over named; empty until a sample exists. */
44 readonly words: string;
45 /** The targets in words, from `TARGETS_MS`: "targets 1 s and 2 min". */
46 readonly targets: string;
47 }
48
49 type Held = Record<LoopKind, LoopSample[]>;
50 const held = new WeakMap<object, Held>();
51 const file = (app: App): string => join(app.config.dataDir, "dev", "loop-samples.json");
52
53 function heldOfApp(app: App): Held {
54 let h = held.get(app);
55 if (h !== undefined) return h;
56 h = { reload: [], tests: [] };
57 try {
58 if (existsSync(file(app))) {
59 const parsed = JSON.parse(readFileSync(file(app), "utf8")) as Partial<Record<LoopKind, unknown>>;
60 for (const kind of Object.keys(TARGETS_MS) as LoopKind[]) {
61 const rows = parsed[kind];
62 if (!Array.isArray(rows)) continue;
63 for (const r of rows.slice(-SAMPLES_MAX)) {
64 const row = r as { ms?: unknown; passed?: unknown };
65 if (typeof row.ms === "number" && Number.isFinite(row.ms) && row.ms >= 0) h[kind].push(kind === "tests" ? { ms: row.ms, passed: row.passed === true } : { ms: row.ms });
66 }
67 }
68 }
69 } catch {
70 // An unreadable file starts the samples again; nothing depends on them.
71 }
72 const mine = h;
73 held.set(app, mine);
74 heldOf(app).add("loop samples", () => mine.reload.length + mine.tests.length);
75 return mine;
76 }
77
78 /** Record one sample; the file is rewritten after, off the caller's path. */
79 export function recordLoop(app: App, kind: LoopKind, ms: number, passed?: boolean): void {
80 if (!Number.isFinite(ms) || ms < 0) return;
81 const h = heldOfApp(app);
82 h[kind].push(kind === "tests" ? { ms: Math.round(ms), passed: passed === true } : { ms: Math.round(ms) });
83 if (h[kind].length > SAMPLES_MAX) h[kind].shift();
84 void Bun.write(file(app), JSON.stringify(h)).catch(() => undefined);
85 }
86
87 const figure = (kind: LoopKind, rows: readonly LoopSample[]): LoopFigure => {
88 const at = p95(rows.map((r) => r.ms));
89 return { kind, p95Ms: at, samples: rows.length, targetMs: TARGETS_MS[kind], over: at !== undefined && at > TARGETS_MS[kind] };
90 };
91
92 const span = (ms: number): string => (ms >= 60_000 && ms % 60_000 === 0 ? `${String(ms / 60_000)} min` : `${String(Math.round(ms / 100) / 10)} s`);
93
94 const secs = (ms: number): string => (ms < 10_000 ? (Math.round(ms / 100) / 10).toFixed(1) : String(Math.round(ms / 1000)));
95
96 /** The loop's p95s over the newest samples, with the words both doors say. */
97 export function loopReading(app: App): LoopReading {
98 const h = heldOfApp(app);
99 const reload = figure("reload", h.reload);
100 const tests = figure("tests", h.tests);
101 const part = (f: LoopFigure, name: string): string | undefined => (f.p95Ms === undefined ? undefined : `${name} ${secs(f.p95Ms)} s`);
102 const shown = [part(reload, "reload"), part(tests, "tests")].filter((s): s is string => s !== undefined);
103 const over = [reload, tests].filter((f) => f.over).map((f) => `${f.kind} is over its ${secs(f.targetMs)} s target`);
104 const targets = `targets ${span(TARGETS_MS.reload)} and ${span(TARGETS_MS.tests)}`;
105 return { reload, tests, targets, shown: shown.join(" · "), words: shown.length === 0 ? "" : `${shown.join(" · ")}${over.length === 0 ? "" : ` (${over.join(", ")})`}` };
106 }
src/http/mcp/tools/pane.ts +3 −1
@@ -1,9 +1,10 @@
11 import { PANE_PATH_REFUSAL, panePath, TRY_MAX, workspaceOf } from "../../../actions/talk_workspace.ts";
2 import { loopReading } from "../../../core/loop_samples.ts";
23 import { bad, good, str, type Tool } from "../shared.ts";
34
45 export const tool: Tool = {
56 name: "pane",
6 doc: "`{ repo, path?, version?: \"preview\" | \"live\", try? }`: in Talk, open the pane beside the chat on that app at `path` (on its own address), with \"Try: <try>\" above it; answers the address it frames",
7 doc: "`{ repo, path?, version?: \"preview\" | \"live\", try? }`: in Talk, open the pane beside the chat on that app at `path` (on its own address), with \"Try: <try>\" above it; answers the address it frames and the loop's p95s (`loop`: reload and tests, over the last 50, with targets)",
78 description: "Open Talk's preview pane on an app at a path, with what to try.",
89 inputSchema: {
910 type: "object",
@@ -36,6 +37,7 @@ export const tool: Tool = {
3637 ...(ws.shows === undefined ? {} : { pull: ws.shows }),
3738 url: url ?? null,
3839 try: said,
40 loop: loopReading(ctx.app),
3941 says: url === undefined ? `Nothing of ${ws.name} runs yet: the pane shows the crew until it does.` : `The pane shows ${where} at ${url}.${said === "" ? "" : ` Try: ${said}`}`,
4042 });
4143 },
src/tui/screens/talk_chats.ts +2
@@ -35,6 +35,7 @@ import { filesOf, receiptIssues, repoOf, steerOf, stepOf } from "../../core/talk
3535 import { cardsPlaced, holdsCard, plainVoice } from "../../core/talk_voice.ts";
3636 import { setTalkDisplay, talkDisplay } from "../../core/settings.ts";
3737 import { talkDisplayScreen } from "./talk_display.ts";
38 import { loopReading } from "../../core/loop_samples.ts";
3839 import { commitWorking, discardWorking, openForEdit, saveWorking, uncommittedLine, workingWords } from "../../actions/working_tree.ts";
3940 import { startTouched, touchedLines, touchedRun, TOUCHED_WORDS } from "../../actions/touched_run.ts";
4041 import { openWorkingPull, workPullWords } from "../../actions/work_pull.ts";
@@ -370,6 +371,7 @@ function chatScreen(f: Session, ctx: Ctx, chat: Conversation, hit?: string): Scr
370371 `Status: ${((st) => (st.state === "error" ? `${st.word}; ask the crew to fix it` : st.word))(paneStatus({ url, dev, crew: paneCrew(f.app.db, f.app.config.dataDir, ws.repo.id, f.user, { runs: mayReadRuns(f.app, f.user, ws.repo), logs: false }) }))}`,
371372 `Dev server: ${dev === undefined ? `not running; d starts ${branch} with hot reload` : `${dev.state} on ${branch}; d stops it`}${dev?.state === "live" ? ` (the page frames it, sandboxed: sign-in and forms that post do not work in it; it holds ${devBudgetWords()})` : ""}`,
372373 ...(fell === undefined ? [] : [fell]),
374 ...((r) => (r.words === "" ? [] : [`Loop: ${r.words}; ${r.targets}`]))(loopReading(f.app)),
outdated

Same literal "targets 1 s and 2 min" as the page; take it from loop_samples.ts. The terminal's Loop: line has no test.

373375 // The working tree, as the Diff tab says it: changed here, not a commit until asked (#17120).
374376 ...(buildHere === undefined || f.user === undefined ? [] : uncommittedLine(f.app, f.user, ws.repo, buildHere.branch)),
375377 // Test what I touched, as the Diff tab streams it (#17121): T runs it, P opens the pull.
src/web/pages/talk_dev.ts +20
@@ -13,6 +13,7 @@
1313
1414 import { devBranch, startDev, stopDev } from "../../actions/dev_workspace.ts";
1515 import { devIdentityHeaders } from "../../apps/dev_budget.ts";
16 import { recordLoop } from "../../core/loop_samples.ts";
1617 import { devCellsOf } from "../../apps/dev_cell.ts";
1718 import { canWrite, getRepo, getRepoById } from "../../core/repos.ts";
1819 import { getUserById } from "../../core/users.ts";
@@ -32,6 +33,19 @@ const WORDS: Record<string, string> = {
3233 no_app: "This repository is not an app: it has no forge.json app section to run.",
3334 };
3435
36 /**
37 * A write the frame has not asked its document for within this long is not a reload: no sample. An
38 * app whose hot reload swaps modules in place never asks, so a short window keeps a later
39 * navigation from being counted as the reload.
40 */
41 const RELOAD_STALE_MS = 10_000;
42
43 /** The request is a page load of the frame (a document), not one of its scripts or images. */
44 const isDocument = (request: Request): boolean => {
45 const dest = request.headers.get("sec-fetch-dest");
46 return dest === null ? (request.headers.get("accept") ?? "").includes("text/html") : dest === "iframe" || dest === "document";
47 };
48
3549 /**
3650 * POST /talk/dev — `repo` (owner/name), `pull` (the pull shown, or empty for the default branch),
3751 * `act` (start or stop).
@@ -90,6 +104,12 @@ export async function talkDevFrame(ctx: Ctx): Promise<Response> {
90104 void devCellsOf(ctx.app).stopOf(cell.userId, cell.repoId);
91105 return notFoundPage(ctx, { plain: true, noEcho: true });
92106 }
107 // The frame asking for its document again after a live save is the reload the loop times.
108 if (cell.wroteAt !== undefined && isDocument(ctx.request)) {
109 const took = Date.now() - cell.wroteAt;
110 delete cell.wroteAt;
111 if (took <= RELOAD_STALE_MS) recordLoop(ctx.app, "reload", took);
112 }
93113 const rest = (ctx.params["path"] ?? "").replace(/^\/+/, "");
94114 if (rest.split("/").some((s) => s === ".." || s.includes("\\") || s.includes("\0"))) return notFoundPage(ctx, { plain: true, noEcho: true });
95115 const headers = new Headers();
src/web/pages/talk_preview.ts +15 −2
@@ -30,7 +30,8 @@ import { workLineHtml } from "../talk_lines.ts";
3030 import type { Ctx } from "../../http/context.ts";
3131 import { html, raw, type Html } from "../html.ts";
3232 import { emptyLine } from "../empty_words.ts";
33 import { btn, icon, iconBtn } from "../ui.ts";
33 import { badge, btn, icon, iconBtn } from "../ui.ts";
34 import { loopReading } from "../../core/loop_samples.ts";
3435 import type { ChatBuild } from "../../core/chat_build.ts";
3536 import { codeView, diffView } from "../talk_code.ts";
3637 import { togetherHtml } from "../together.ts";
@@ -160,6 +161,7 @@ export async function talkPane(ctx: Ctx, user: User, name: string | undefined, w
160161 ${url === undefined ? null : btn(icon("external"), { href: url, label: `Open ${name} on its own`, title: "Open on its own", variant: "ghost", external: true, extra: "btn-icon" })}
161162 </div>
162163 <p class="talk-pane-info small muted" data-pane-info>${paneInfo(ctx.app.db, ws.repo, ws.shows)}${ws.shows === undefined ? null : html` · <a href="/${name}/pulls/${String(ws.shows)}">the pull</a>`}${devFrame === undefined ? null : html` · The dev server runs in a sandboxed frame: sign-in and forms that post do not work in it. It holds ${devBudgetWords()}.`}</p>
164 ${loopLine(ctx)}
163165 ${togetherHtml(ctx.app.db, ws.repo, user, "live")}
164166 ${fellLine}
165167 ${panel}
@@ -167,6 +169,17 @@ export async function talkPane(ctx: Ctx, user: User, name: string | undefined, w
167169 };
168170 }
169171
172 /**
173 * The loop's two p95s beside their targets ("reload 0.4 s · tests 48 s"); one over its target is a
174 * warning badge naming it. Nothing is drawn before a sample exists.
175 */
176 function loopLine(ctx: Ctx): Html | null {
177 const r = loopReading(ctx.app);
178 if (r.words === "") return null;
179 const over = [r.reload, r.tests].filter((f) => f.over);
180 return html`<p class="talk-pane-loop small muted" data-pane-loop>${r.shown} · ${r.targets}${over.map((f) => html` ${badge(`${f.kind} over target`, { tone: "attn" })}`)}</p>`;
outdated

Hardcoded "targets 1 s and 2 min" duplicates TARGETS_MS and the terminal's copy: derive it from loop_samples.ts. This badge branch (principle 5, the warning tone, naming the figure) is also untested: render the page with an over-target sample.

181 }
182
170183 /** Where the app's production answers, as a bare origin: what `frame-src` names before its first deploy. */
171184 function productionOrigin(ctx: Ctx, repoId: string): string | undefined {
172185 const record = getAppByRepo(ctx.app.db, repoId);
@@ -264,7 +277,7 @@ export const paneCss = /* css */ `
264277 .talk-dev-status[data-dev-status="error"] { font-weight: 600; }
265278 @media (forced-colors: active) { .talk-addr-pick :is(select, input):focus-visible { outline: 2px solid CanvasText; } }
266279 :root.js .talk-addr-go { display: none; }
267 .talk-pane-info, .talk-pane-fell { margin: 0 0 8px; overflow-wrap: anywhere; }
280 .talk-pane-info, .talk-pane-fell, .talk-pane-loop { margin: 0 0 8px; overflow-wrap: anywhere; }
268281 /* On a phone the switcher takes a row of its own under the tabs, each picker a share of it. */
269282 @media (max-width: 30rem) { .talk-addr:not(.talk-addr-pick) { display: none; } .talk-addr-pick { order: 1; flex-basis: 100%; } .talk-addr-pick select { flex: 1; max-width: none; } .talk-addr-pick input { flex: 0 1 6rem; } }
270283 @media (prefers-reduced-motion: reduce) { .talk-frame { transition: none; } }
test/loop-doors.test.ts added +95
@@ -0,0 +1,95 @@
1 /**
2 * Both doors draw the loop's speed (#17374): the page's `data-pane-loop` line with a warning badge
3 * naming a figure over its target, and the terminal pane's `Loop:` line. Each fails without it.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, readFile, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createRepo } from "../src/actions/repos.ts";
10 import { createApp, type App } from "../src/app.ts";
11 import { appendTurn, createConversation } from "../src/core/conversations.ts";
12 import { loopReading, recordLoop } from "../src/core/loop_samples.ts";
13 import { createUser, type User } from "../src/core/users.ts";
14 import type { Ctx } from "../src/http/context.ts";
15 import { createForgeApp } from "../src/tui/forge.ts";
16 import { headlessTerminal } from "../src/tui/term/terminal.ts";
17 import { talkPane } from "../src/web/pages/talk_preview.ts";
18 import { pollUntil } from "./helpers/poll.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20 import { promote } from "./helpers/members.ts";
21 import { settleApp } from "./helpers/tui.ts";
22
23 quietLogs();
24
25 let dir: string;
26 let app: App;
27 let ada: User;
28 let ctx: Ctx;
29 let name: string;
30
31 beforeAll(async () => {
32 dir = await mkdtemp(join(tmpdir(), "forge-loop-doors-"));
33 app = createApp({ dataDir: dir, port: 0 });
34 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "ada", email: "[email protected]", password: "a-good-passphrase" });
35 if (!made.ok) throw new Error(made.error);
36 promote(app.db, made.value);
37 ada = made.value;
38 ctx = { app, url: new URL("http://forge.test/talk") } as Ctx;
39 const repo = await createRepo(app, ada, { name: "fast", visibility: "public" });
40 if (!repo.ok) throw new Error(String(repo.error));
41 name = "ada/fast";
42 });
43
44 afterAll(async () => {
45 app.close();
46 await rm(dir, { recursive: true, force: true });
47 });
48
49 const page = async (): Promise<string> => (await talkPane(ctx, ada, name, new Map(), "preview")).html.text;
50
51 test("the page draws nothing before a sample, the line when under target, and a badge naming the figure over it", async () => {
52 expect(await page()).not.toContain("data-pane-loop");
53 recordLoop(app, "reload", 400);
54 const under = await page();
55 expect(under).toContain("data-pane-loop");
56 expect(under).toContain(`reload 0.4 s · ${loopReading(app).targets}`);
57 expect(under).toContain("targets 1 s and 2 min");
58 expect(under).not.toContain('data-variant="attn"');
59 recordLoop(app, "reload", 2500);
60 const over = await page();
61 expect(over).toContain('data-variant="attn"');
62 expect(over).toContain("reload over target");
63 expect(over).not.toContain("tests over target");
64 });
65
66 test("the terminal's p view prints the Loop line with the same targets", async () => {
67 const chat = createConversation(app.db, ada.id);
68 if (!chat.ok) throw new Error(chat.error);
69 appendTurn(app.db, ada.id, chat.value.id, { role: "tool", text: `mcp__forge__read_file ${JSON.stringify({ repo: name, path: "a" })}` });
70 const terminal = headlessTerminal(160, 30);
71 const { app: tui } = createForgeApp(app, { sshUsername: "ada", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: ada }, { terminal, exitHooks: false });
72 tui.start();
73 for (const k of [":", "Conversations", "\r", "\r", "p"]) {
74 terminal.feed(k);
75 await settleApp(tui);
76 }
77 const text = tui.screen.toText();
78 tui.stop();
79 expect(text).toContain("Loop: reload 2.5 s");
80 expect(text).toContain(loopReading(app).targets);
81 });
82
83 test("the targets phrase comes from TARGETS_MS and the docs say the same", async () => {
84 expect(loopReading(app).targets).toBe("targets 1 s and 2 min");
85 expect(await readFile(join(import.meta.dir, "../docs/features/talk-workspace.md"), "utf8")).toContain(loopReading(app).targets);
86 });
87
88 test("samples survive a restart through loop-samples.json", async () => {
89 recordLoop(app, "tests", 48_000, true);
90 await pollUntil(async () => (await Bun.file(join(dir, "dev", "loop-samples.json")).exists()) && (await readFile(join(dir, "dev", "loop-samples.json"), "utf8")).includes("48000"), "the file written", 5000);
91 const again = createApp({ dataDir: dir, port: 0 });
92 expect(loopReading(again).tests.p95Ms).toBe(48_000);
93 expect(loopReading(again).reload.samples).toBe(2);
94 again.close();
95 });
test/loop-samples.test.ts added +141
@@ -0,0 +1,141 @@
1 /**

Missing: a page test for .talk-pane-loop with and without an over-target figure, and a terminal test for the Loop: line. Persistence across a restart (loop-samples.json) is also untested.

2 * Talk's loop shows its own speed (#17374). Hand calculation: the nearest-rank p95 of 1..20 is the
3 * 19th value, 19; of 1..100 it is 95; with 51 samples only the newest 50 count.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, readFile, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { commitToBranch } from "../src/actions/repos.ts";
10 import { startTouched, touchedRun, type Exec } from "../src/actions/touched_run.ts";
11 import { saveWorking } from "../src/actions/working_tree.ts";
12 import { devCellsOf } from "../src/apps/dev_cell.ts";
13 import { devKey } from "../src/apps/dev_launch.ts";
14 import { createApp, type App } from "../src/app.ts";
15 import { loopReading, recordLoop, SAMPLES_MAX } from "../src/core/loop_samples.ts";
16 import { p95 } from "../src/rules/budget_rerun.ts";
17 import { createRepo, type Repo } from "../src/core/repos.ts";
18 import { createToken } from "../src/core/tokens.ts";
19 import { createUser, type User } from "../src/core/users.ts";
20 import { serve, type Servers } from "../src/http/server.ts";
21 import { err, ok as good } from "../src/kernel/result.ts";
22 import { pollUntil } from "./helpers/poll.ts";
23 import { quietLogs } from "./helpers/globals.ts";
24
25 quietLogs();
26
27 const ok = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
28 if (!r.ok) throw new Error(JSON.stringify(r.error));
29 return r.value;
30 };
31
32 let dataDir: string;
33 let app: App;
34 let servers: Servers;
35 let ada: User;
36 let repo: Repo;
37 let token: string;
38 let fake: ReturnType<typeof Bun.serve>;
39
40 beforeAll(async () => {
41 dataDir = await mkdtemp(join(tmpdir(), "forge-loop-"));
42 app = createApp({ dataDir, port: 0 });
43 servers = await serve(app);
44 fake = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => new Response("<p>app</p>", { headers: { "content-type": "text/html" } }) });
45 ada = ok(await createUser(app.db, { origin: "seed", trusted: true, username: "ada", email: "[email protected]", password: "a-good-passphrase" }));
46 repo = ok(await createRepo(app.db, app.reposRoot, { ownerId: ada.id, name: "fast", visibility: "public" }));
47 ok(await commitToBranch(app, ada, repo, { message: "seed", files: [{ path: "src/a.ts", content: "export const a = 1;\n" }, { path: "test/a.test.ts", content: "// a\n" }] }));
48 ok(await commitToBranch(app, ada, repo, { branch: "work", message: "branch", files: [{ path: "src/a.ts", content: "export const a = 1;\n" }] }));
49 token = createToken(app.db, ada.id, "rw", "rw").token;
50 }, 30_000);
51
52 afterAll(async () => {
53 fake?.stop(true);
54 servers?.stop();
55 app?.close();
56 await rm(dataDir, { recursive: true, force: true });
57 });
58
59 test("p95 is the nearest rank, over the newest 50", () => {
60 expect(p95([])).toBeUndefined();
61 expect(p95(Array.from({ length: 20 }, (_, i) => 20 - i))).toBe(19);
62 expect(p95(Array.from({ length: 100 }, (_, i) => i + 1))).toBe(95);
63 expect(p95([7])).toBe(7);
64 const other = createApp({ dataDir: join(dataDir, "other"), port: 0 });
65 for (let i = 1; i <= SAMPLES_MAX + 1; i++) recordLoop(other, "reload", i * 10);
66 // 51 recorded: the first fell off, so the 50 are 20..510 and the 48th is 20 + 47*10 = 490.
67 expect(loopReading(other).reload.samples).toBe(50);
68 expect(loopReading(other).reload.p95Ms).toBe(490);
69 other.close();
70 });
71
72 test("the words give both figures, and name only the one over its target", () => {
73 const a = createApp({ dataDir: join(dataDir, "words"), port: 0 });
74 expect(loopReading(a).words).toBe("");
75 recordLoop(a, "reload", 400);
76 recordLoop(a, "tests", 48_000, true);
77 expect(loopReading(a).words).toBe("reload 0.4 s · tests 48 s");
78 expect(loopReading(a).reload.over).toBe(false);
79 recordLoop(a, "reload", 1500);
80 const r = loopReading(a);
81 expect(r.reload.over).toBe(true);
82 expect(r.tests.over).toBe(false);
83 expect(r.words).toBe("reload 1.5 s · tests 48 s (reload is over its 1.0 s target)");
84 a.close();
85 });
86
87 test("a test run records its wall time, passed or not", async () => {
88 ok(await saveWorking(app, ada, repo, "work", "src/a.ts", "export const a = 2;\n"));
89 const before = loopReading(app).tests.samples;
90 const pass: Exec = async () => good(undefined);
91 ok(await startTouched(app, ada, repo, "work", pass));
92 await touchedRun(app, ada, repo, "work")!.done;
93 expect(loopReading(app).tests.samples).toBe(before + 1);
94 const fail: Exec = async () => err("failed");
95 ok(await startTouched(app, ada, repo, "work", fail));
96 await touchedRun(app, ada, repo, "work")!.done;
97 expect(loopReading(app).tests.samples).toBe(before + 2);
98 });
99
100 test("a save that reaches the dev cell is timed to the frame's next document, and the tool says so", async () => {
101 const dir = await mkdtemp(join(tmpdir(), "forge-loop-cell-"));
102 const cell = devCellsOf(app).ensure(devKey(ada.id, repo.id, "work"), ada.id, repo.id, async () => good({ port: fake.port!, exited: new Promise<void>(() => {}), recent: () => [], stop: async () => {}, dir }));
103 cell.branch = "work";
104 await pollUntil(() => cell.state === "live", "the cell live", 5000);
105 const before = loopReading(app).reload.samples;
106 ok(await saveWorking(app, ada, repo, "work", "src/a.ts", "export const a = 3;\n"));
107 await pollUntil(async () => (await Bun.file(join(dir, "src/a.ts")).exists()) && (await readFile(join(dir, "src/a.ts"), "utf8")) === "export const a = 3;\n", "the file in the checkout", 5000);
108 // A script of the frame is not a reload; its document is.
109 await fetch(`${servers.url}/talk/dev/${cell.token}/app.js`, { headers: { "sec-fetch-dest": "script" } });
110 expect(loopReading(app).reload.samples).toBe(before);
111 expect((await fetch(`${servers.url}/talk/dev/${cell.token}/`, { headers: { "sec-fetch-dest": "iframe" } })).status).toBe(200);
112 expect(loopReading(app).reload.samples).toBe(before + 1);
113 // One save is one sample: the next document request records nothing.
114 await fetch(`${servers.url}/talk/dev/${cell.token}/`, { headers: { "sec-fetch-dest": "iframe" } });
115 expect(loopReading(app).reload.samples).toBe(before + 1);
116 const res = await fetch(`${servers.url}/mcp`, {
117 method: "POST",
118 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` },
119 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "pane", arguments: { repo: "ada/fast" } } }),
120 });
121 const body = (await res.json()) as { result: { content: { text: string }[] } };
122 const loop = (JSON.parse(body.result.content[0]!.text) as { loop: { words: string; reload: { samples: number } } }).loop;
123 expect(loop.words).toContain("reload ");
124 expect(loop.reload.samples).toBe(before + 1);
125 await devCellsOf(app).stop(devKey(ada.id, repo.id, "work"));
126 await rm(dir, { recursive: true, force: true });
127 });
128
129 test("a save the frame does not follow within 10 s is dropped: a later navigation is no reload", async () => {
130 const dir = await mkdtemp(join(tmpdir(), "forge-loop-stale-"));
131 const cell = devCellsOf(app).ensure(devKey(ada.id, repo.id, "work"), ada.id, repo.id, async () => good({ port: fake.port!, exited: new Promise<void>(() => {}), recent: () => [], stop: async () => {}, dir }));
132 cell.branch = "work";
133 await pollUntil(() => cell.state === "live", "the cell live", 5000);
134 const before = loopReading(app).reload.samples;
135 cell.wroteAt = Date.now() - 11_000;
136 expect((await fetch(`${servers.url}/talk/dev/${cell.token}/`, { headers: { "sec-fetch-dest": "iframe" } })).status).toBe(200);
137 expect(loopReading(app).reload.samples).toBe(before);
138 expect(cell.wroteAt).toBeUndefined();
139 await devCellsOf(app).stop(devKey(ada.id, repo.id, "work"));
140 await rm(dir, { recursive: true, force: true });
141 });

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

Keyboard shortcuts

Docs