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

A run cancelled from the page shows 'stopped' with the time and who stopped it, on the run's own page #13493

Merged opened this

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

Merged

mason/forge:mason/13457-a-run-cancelled-from-the-page-shows-stop → main 2 commits fork 2 threads · 2 unresolved

  • Merged. mason/13457-a-run-cancelled-from-the-page-shows-stop was merged into main as 18b9f9c.

Review

Sign in to review this change.
8 files changed +191 −8
docs/features/run-state.md +1
@@ -2,6 +2,7 @@
22
33 - **One function**: `runState` (`src/runs/state.ts`) names a run *waiting, working, needs input, failed, done* or *silent* from its row, its last sign of life and its plan — never from anything the run says about itself. The runs API rows carry it as `shown`; the runs tab and home badges read it.
44 - **Silent**: a running agent run with no log line and no plan update for 10 minutes. One `silent` flow alarm names the one silent longest (home, /boards, the notifier). Signs of life are kept in memory (`runs/activity.ts`); a run started before this process booted is measured from its start. Because the signs are in this process's memory only, during a roll a run that is logging to the other process, or one logging from before a restart, can read silent falsely; the alarm is then a prompt to look, not a verdict.
5 - **Stopped by a person** (#13457): a run someone cancels from its page reads *Stopped by alice, 2 minutes ago* — one sentence (`stoppedWords`, `src/runs/cancelled.ts`) on the run page, its feed row (kept a post, never folded as a quiet run) and the terminal's run log — in the quiet colour, never red. A run that ended on its own first keeps its real end.
56 - **Repeat stop**: more than 3 agent runs on one issue in 10 minutes, whatever each said (`crew/repeat.ts`), parks the issue with one note and raises one `repeat` alarm; nothing starts until a person who directs the crew speaks.
67 - **Plan**: a run keeps up to 12 checklist items on its issue, replaced whole each time: `PUT /api/v1/repos/:owner/:name/issues/:number/plan` `{ items: [{ text, done? }], ask? }`, the MCP tool `keep_plan`, shown on the issue page and in `GET …/issues/:number` as `plan`. `ask` marks the run *needs input* until the next update. Only the agent with a run going on that issue may set its plan (a writer's or another run's call is refused, `forbidden`). Not an event: it is progress, like a log.
78 - **Runs tab count** is `runningCount`: running agent runs and checks, the sum of the pipeline's building, review and checking stages.
src/feed/items.ts +13
@@ -32,6 +32,7 @@ import { getRunErrorLine } from "../core/runs.ts";
3232 import { getUserById, type User } from "../core/users.ts";
3333 import { watchedBy } from "../core/watches.ts";
3434 import { CLOG_NOTE_WINDOW_MS, flattenNote } from "../flow/clog_note.ts";
35 import { stoppedWords } from "../runs/cancelled.ts";
3536 import { chooseCandidates } from "./choose.ts";
3637 import type { Foldable } from "./fold.ts";
3738 import { writeStamp } from "../core/write_clock.ts";
@@ -676,6 +677,18 @@ function fromEvent(
676677 ? `${link}?all=1#L${errorAt}`
677678 : link;
678679 const failure = errorLine === "" ? summary : errorLine;
680 // A person's stop is a calm ending, in the run page's own sentence (#13457).
681 const stopped = stoppedWords(
682 { state: String(p["state"] ?? ""), summary: typeof p["summary"] === "string" ? p["summary"] : "" },
683 e.createdAt,
684 );
685 if (stopped !== undefined)
686 return {
687 ...common,
688 kind: "run",
689 link,
690 what: `${/^[aeiou]/.test(kind) ? "an" : "a"} ${kind} run${subject}: ${stopped}`,
691 };
679692 if (kind === "agent" && cost >= COST_FLOOR_USD && ownerFacts)
680693 return {
681694 ...common,
src/feed/quiet.ts +7 −4
@@ -1,15 +1,17 @@
11 /**
22 * Quiet runs: an agent run that finished without failing and left nothing
3 * behind — no push (to the repository or the agent's fork), no pull, no comment, no issue — is noise above the posts
4 * that matter. The run's own record says so: its agent, and the window it
5 * worked in, against what that agent wrote to the repository in that window.
6 * A run the record cannot find is never called quiet.
3 * behind — no push (to the repository or the agent's fork), no pull, no comment, no issue — is
4 * noise above the posts that matter. The run's own record says so: its agent, and the window it
5 * worked in, against what that agent wrote to the repository in that window. A run the record
6 * cannot find is never called quiet, nor one a person stopped: they asked for that ending, so it
7 * keeps its post (#13457).
78 */
89
910 import type { Database } from "bun:sqlite";
1011 import type { ForgeEvent } from "../core/events.ts";
1112 import { getForkOf } from "../core/repos.ts";
1213 import { getRunsByIds } from "../core/runs.ts";
14 import { stoppedBy } from "../runs/cancelled.ts";
1315
1416 /** What an agent leaves behind that is worth a post of its own. */
1517 const LEFT_BEHIND = [
@@ -57,6 +59,7 @@ export function quietRunEventIds(
5759 run === undefined ||
5860 run.kind !== "agent" ||
5961 run.state === "failed" ||
62 stoppedBy(run) !== undefined ||
6063 run.actorId === null ||
6164 run.startedAt === null ||
6265 run.finishedAt === null
src/runs/cancelled.ts +33 −1
@@ -4,8 +4,16 @@
44 * down, ends the run's log with that same line, so the log's last word says
55 * the run was cancelled and by whom. A run cancelled any other way (its
66 * pull landed, a budget, a restart) keeps the summary its own path writes.
7 *
8 * A person's stop reads as a calm ending (#13457): "Stopped by alice, 2
9 * minutes ago", the one sentence the run page, the feed row and the
10 * terminal's run log all say. A run that ended on its own just before the
11 * stop keeps its real end: `cancelRun` only marks a queued or running row,
12 * so its summary never says a person stopped it.
713 */
814
15 import { agoWords } from "../kernel/ago.ts";
16
917 const PREFIX = "cancelled by ";
1018
1119 /** The summary and the log's last line for a run `username` cancelled. */
@@ -17,9 +25,33 @@ export const cancelledBy = (username: string): string => `${PREFIX}${username}`;
1725 */
1826 export function cancelledLine(
1927 row: { readonly state: string; readonly summary: string } | undefined,
28 ): string | undefined {
29 return stoppedBy(row) === undefined ? undefined : row!.summary;
30 }
31
32 /** The name of the person who stopped the run, or nothing when nobody did. */
33 export function stoppedBy(
34 row: { readonly state: string; readonly summary: string } | undefined,
2035 ): string | undefined {
2136 if (row === undefined || row.state !== "cancelled") return undefined;
2237 return row.summary.startsWith(PREFIX) && row.summary.length > PREFIX.length
23 ? row.summary
38 ? row.summary.slice(PREFIX.length)
2439 : undefined;
2540 }
41
42 /**
43 * "Stopped by alice, 2 minutes ago" for a run a person stopped, `at` being
44 * when it stopped (the row's `finishedAt`, or the event's own time); nothing
45 * for any other run, so the caller keeps the summary it already shows.
46 */
47 export function stoppedWords(
48 row: { readonly state: string; readonly summary: string } | undefined,
49 at: string | null,
50 now: number = Date.now(),
51 ): string | undefined {
52 const name = stoppedBy(row);
53 if (name === undefined) return undefined;
54 return at === null || !Number.isFinite(Date.parse(at))
55 ? `Stopped by ${name}`
56 : `Stopped by ${name}, ${agoWords(at, now)}`;
57 }
src/tui/screens/runlog.ts +2 −1
@@ -17,6 +17,7 @@ import { truncate } from "../term/width.ts";
1717 import { fill, len, split } from "../ui/layout.ts";
1818 import { emptyState } from "../ui/widgets.ts";
1919 import { subscribeRunLog } from "../../runs/log.ts";
20 import { stoppedWords } from "../../runs/cancelled.ts";
2021 import { Scroll, live, openOnWeb } from "./common.ts";
2122 import { costText, envLabel, runTone } from "./runwords.ts";
2223 import { jobSandboxWords } from "../../checks/placement.ts";
@@ -116,7 +117,7 @@ export function runLogScreen(
116117 const state = [
117118 run.state,
118119 run.kind === "deploy" ? `deploy ${envLabel(run.env)}` : run.kind,
119 run.summary,
120 stoppedWords(run, run.finishedAt) ?? run.summary,

No test covers this line. Add a runlog screen test (cancelled-by run) that fails if it is reverted.

120121 costText(run.costUsd),
121122 isLive(run.state) ? "live" : "",
122123 ]
src/web/studio/run.ts +18 −1
@@ -22,6 +22,8 @@ import { getPull, openPullsClosing } from "../../core/pulls.ts";
2222 import { canSeeOwnerFacts, type Repo } from "../../core/repos.ts";
2323 import { getRepoRun } from "../../actions/runs.ts";
2424 import { runCardPath } from "../og/path.ts";
25 import { stoppedBy } from "../../runs/cancelled.ts";
26 import { agoWords } from "../../kernel/ago.ts";
2527 import { isTerminal, type Run } from "../../core/runs.ts";
2628 import { listHeldSecrets } from "../../core/run_secret.ts";
2729 import { getUserById } from "../../core/users.ts";
@@ -78,6 +80,21 @@ export function vitalsBlock(
7880 return run.kind === "check" && !logHidden ? vitalsTable(looks) : html``;
7981 }
8082
83 /**
84 * The stop sentence `stoppedWords` says, with its time in a `<time>` that
85 * holds the exact instant (#13457): the words stay the same, a hover and a
86 * screen reader get the real moment rather than a relative one gone stale.
87 */
88 function stoppedLine(run: Run): Html | undefined {
89 const name = stoppedBy(run);
90 if (name === undefined) return undefined;
91 const at = run.finishedAt === null ? Number.NaN : Date.parse(run.finishedAt);
92 if (!Number.isFinite(at)) return html`Stopped by ${name}`;
93 const iso = new Date(at).toISOString();
94 const exact = `${iso.slice(0, 16).replace("T", " ")} UTC`;
95 return html`Stopped by ${name}, <time datetime="${iso}" title="${exact}">${agoWords(iso)}</time>`;
96 }
97
8198 /**
8299 * GET /:owner/:name/runs/:id: who is on it, the tell it came from, the
83100 * commit a deploy or a check is about, how long it has gone and what it has
@@ -200,7 +217,7 @@ export async function runView(
200217 >`,
201218 )}
202219 </div>
203 <p class="mt" id="run-summary">${run.summary}</p>
220 <p class="mt" id="run-summary">${stoppedLine(run) ?? run.summary}</p>
204221 ${when(wayIn(ctx.app, ctx.auth.user, run.summary, repo), (way) => html`<div class="small" id="run-way">${blockedWay(way)}</div>`)}
205222 ${when(
206223 carried.length > 0,
test/run-stopped-words.test.ts added +105
@@ -0,0 +1,105 @@
1 /**
2 * A run a person stopped reads as a calm ending (#13457): "Stopped by
3 * <name>, <time>" on the run's own page and on its feed row, in the quiet
4 * colour, never the danger red; a run that ended on its own keeps its end.
5 */
6 import { afterAll, beforeAll, describe, 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 { cancelRepoRun } from "../src/actions/runs.ts";
11 import { createRepo } from "../src/actions/repos.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
14 import { createSession } from "../src/core/sessions.ts";
15 import { createUser } from "../src/core/users.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { cancelledBy, cancelledLine, stoppedBy, stoppedWords } from "../src/runs/cancelled.ts";
18
19 describe("the stop sentence", () => {
20 const at = "2026-11-15T10:00:00.000Z";
21 const now = Date.parse(at) + 3 * 60_000;
22
23 test("names who stopped it and when", () => {
24 const row = { state: "cancelled", summary: cancelledBy("alice") };
25 expect(stoppedBy(row)).toBe("alice");
26 expect(stoppedWords(row, at, now)).toBe("Stopped by alice, 3 minutes ago");
27 expect(stoppedWords(row, null, now)).toBe("Stopped by alice");
28 expect(cancelledLine(row)).toBe("cancelled by alice");
29 });
30
31 test("says nothing for a run nobody stopped", () => {
32 expect(stoppedWords({ state: "cancelled", summary: "the pull landed" }, at, now)).toBeUndefined();
33 expect(stoppedWords({ state: "ok", summary: cancelledBy("alice") }, at, now)).toBeUndefined();
34 expect(stoppedWords({ state: "cancelled", summary: "cancelled by " }, at, now)).toBeUndefined();
35 });
36 });
37
38 describe("a run stopped from the page", () => {
39 let dataDir: string;
40 let app: App;
41 let servers: Servers;
42 let cookie: string;
43 let stoppedId: string;
44 let endedId: string;
45
46 beforeAll(async () => {
47 dataDir = await mkdtemp(join(tmpdir(), "forge-run-stopped-"));
48 app = createApp({ dataDir, port: 0 });
49 servers = await serve(app);
50 const u = await createUser(app.db, {
51 origin: "seed", trusted: true, username: "alice",
52 email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true,
53 });
54 if (!u.ok) throw new Error(u.error);
55 cookie = `forge_session=${createSession(app.db, u.value.id).token}`;
56 const made = await createRepo(app, u.value, { name: "garden", visibility: "public" });
57 if (!made.ok) throw new Error(String(made.error));
58 const repo = made.value;
59
60 const run = createRun(app.db, { repoId: repo.id, kind: "agent", actorId: u.value.id });
61 stoppedId = run.id;
62 claimRun(app.db, run.id);
63 const stopped = cancelRepoRun(app, u.value, repo, run.id);
64 if (!stopped.ok) throw new Error(String(stopped.error));
65
66 // Ended on its own just before the stop: the stop is refused, the real end stays.
67 const other = createRun(app.db, { repoId: repo.id, kind: "agent", actorId: u.value.id });
68 endedId = other.id;
69 claimRun(app.db, other.id);
70 finishRun(app.db, other.id, { state: "ok", summary: "watered the plants" });
71 const late = cancelRepoRun(app, u.value, repo, other.id);
72 if (late.ok) throw new Error("a finished run was cancelled");
73 });
74
75 afterAll(async () => {
76 servers.stop();
77 app.close();
78 await rm(dataDir, { recursive: true, force: true });
79 });
80
81 test("the run page says who stopped it and when, in the quiet colour", async () => {
82 const text = await (await fetch(`${servers.url}/alice/garden/runs/${stoppedId}`, { headers: { cookie } })).text();
83 const summary = text.match(/<p class="mt" id="run-summary">(.*?)<\/p>/s)?.[1] ?? "";
84 // The words are the sentence the feed and the terminal say; the time holds the exact instant.
85 expect(summary.replace(/<[^>]*>/g, "")).toBe("Stopped by alice, just now");
86 const time = summary.match(/<time datetime="([^"]+)" title="([^"]+)">just now<\/time>/);
87 expect(time).not.toBeNull();
88 expect(Number.isFinite(Date.parse(time![1]!))).toBe(true);
89 expect(time![2]).toBe(`${time![1]!.slice(0, 16).replace("T", " ")} UTC`);
90 const badge = text.match(/<span[^>]*id="run-word"[^>]*>/)?.[0] ?? "";
91 expect(badge).toContain('data-variant="secondary"');
92 expect(badge).not.toContain("danger");
93 });
94
95 test("the feed row uses the same sentence", async () => {
96 const text = await (await fetch(`${servers.url}/feed`, { headers: { cookie: `${cookie}; forge_mode=studio` } })).text();
97 expect(text).toContain("an agent run: Stopped by alice, just now");
98 });
99
100 test("a run that ended on its own before the stop shows its real end", async () => {
101 const text = await (await fetch(`${servers.url}/alice/garden/runs/${endedId}`, { headers: { cookie } })).text();
102 expect(text).toContain(`id="run-summary">watered the plants</p>`);
103 expect(text).not.toContain("Stopped by");
104 });
105 });
test/tui-runlog.test.ts +12 −1
@@ -4,7 +4,7 @@ import { mkdtemp, rm } from "node:fs/promises";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import { appendFileSync } from "node:fs";
7 import { announceRun } from "../src/actions/runs.ts";
7 import { announceRun, cancelRepoRun } from "../src/actions/runs.ts";
88 import { createRepo } from "../src/actions/repos.ts";
99 import { createApp, type App as Forge } from "../src/app.ts";
1010 import { claimRun, createRun, finishRun, noteRunProgress } from "../src/core/runs.ts";
@@ -75,6 +75,17 @@ test("a finished run shows its state and its last 200 lines, at the end", async
7575 expect(app.screen.toText()).not.toContain("\nline-100\n");
7676 });
7777
78 test("a run a person stopped says who stopped it on its state line (#13457)", async () => {
79 const run = createRun(forge.db, { repoId: repo.id, kind: "agent" });
80 claimRun(forge.db, run.id);
81 const stopped = cancelRepoRun(forge, alice, repo, run.id);
82 if (!stopped.ok) throw new Error(String(stopped.error));
83 const app = await open(alice, run.id);
84 const text = app.screen.toText();
85 expect(text).toContain("Stopped by alice, just now");
86 expect(text).not.toContain("cancelled by alice");
87 });
88
7889 test("a check that ran as a Job says, under its state, that its wall rests on the cluster too (#13251)", async () => {
7990 const run = createRun(forge.db, { repoId: repo.id, kind: "check" });
8091 claimRun(forge.db, run.id);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs