Public: anyone can read this; the crew can change it.
`forge runs` lists what the crew is doing on the repository of the folder you are in: running and recent runs, with state, agent and cost #7367
mason/forge:mason/7353-forge-runs-lists-what-the-crew-is-doing → main 5 commits fork 2 threads · 2 unresolved
10 files
changed +459
−19
README.md +6
| @@ -311,6 +311,7 @@ forge sync --ff # fast-forward clean repos, and only those | ||
| 311 | 311 | forge pin owner/name # ask the workbench to keep this one here |
| 312 | 312 | forge ls # what is here, and how stale |
| 313 | 313 | forge open owner/name --web # the page, in a browser |
| 314 | forge runs # what the crew is doing on this folder's repo | |
| 314 | 315 | forge asks # what waits on you, most important first |
| 315 | 316 | forge asks --repo owner/name # only that repository's; --json for the API's answer |
| 316 | 317 | |
| @@ -326,6 +327,11 @@ and left exactly as you left it. | ||
| 326 | 327 | `origin` was edited to anywhere else is fetched without the token, and its row |
| 327 | 328 | says `no token sent`. |
| 328 | 329 | |
| 330 | `forge runs` reads the repository this folder's `origin` points at (or | |
| 331 | `--repo owner/name`) and prints its last ten runs: state, agent, `#N`, title, | |
| 332 | age and cost. `--json` prints the forge's rows unchanged, each carrying | |
| 333 | `agent`, `number` and `title` beside the run's own fields. | |
| 334 | ||
| 329 | 335 | `forge` with no arguments opens the local UI on the same runtime as the SSH |
| 330 | 336 | one: the library of clones, then a lazygit-shaped working-tree screen — |
| 331 | 337 | `space` stages, `enter` opens the hunks, `s` stages one, `c` commits, `P` |
src/cli/api.ts +22
| @@ -191,6 +191,28 @@ export class ForgeApi { | ||
| 191 | 191 | ); |
| 192 | 192 | } |
| 193 | 193 | |
| 194 | /** | |
| 195 | * A repository's runs, newest first, exactly as the forge lists them — | |
| 196 | * `forge runs --json` prints these rows unchanged, so nothing is dropped. | |
| 197 | */ | |
| 198 | async runs( | |
| 199 | owner: string, | |
| 200 | name: string, | |
| 201 | limit: number, | |
| 202 | ): Promise<ApiResult<Record<string, unknown>[]>> { | |
| 203 | const out = await this.call<{ items?: unknown }>( | |
| 204 | `/api/v1/repos/${encode(owner)}/${encode(name)}/runs?limit=${limit}`, | |
| 205 | ); | |
| 206 | if (!out.ok) return out; | |
| 207 | const items = out.value.items; | |
| 208 | if (!Array.isArray(items)) return ok([]); | |
| 209 | return ok( | |
| 210 | items.filter( | |
| 211 | (x): x is Record<string, unknown> => typeof x === "object" && x !== null, | |
| 212 | ), | |
| 213 | ); | |
| 214 | } | |
| 215 | ||
| 194 | 216 | /** |
| 195 | 217 | * What waits on the user, most consequential first (`GET /api/v1/asks`). |
| 196 | 218 | * A row of a kind this client has never heard of is kept, not dropped: it |
src/cli/args.ts +27
| @@ -86,6 +86,33 @@ export function parseDuration(text: string | undefined): number | undefined { | ||
| 86 | 86 | } |
| 87 | 87 | } |
| 88 | 88 | |
| 89 | /** | |
| 90 | * `owner/name` from a git remote URL — `https://host/o/n.git`, | |
| 91 | * `ssh://git@host:2222/o/n.git` or `git@host:o/n.git`: the last two path | |
| 92 | * segments, `.git` dropped. Anything else is undefined, never a guess. | |
| 93 | */ | |
| 94 | export function repoFromRemote( | |
| 95 | url: string | null | undefined, | |
| 96 | ): { owner: string; name: string } | undefined { | |
| 97 | if (url === null || url === undefined) return undefined; | |
| 98 | const text = url.trim(); | |
| 99 | let path: string; | |
| 100 | const scp = /^[^/@:]+@[^/:]+:(.+)$/.exec(text); | |
| 101 | if (scp !== null) path = scp[1]!; | |
| 102 | else { | |
| 103 | try { | |
| 104 | path = new URL(text).pathname; | |
| 105 | } catch { | |
| 106 | return undefined; | |
| 107 | } | |
| 108 | } | |
| 109 | const parts = path.replace(/\/+$/, "").split("/"); | |
| 110 | const name = parts.pop()?.replace(/\.git$/, ""); | |
| 111 | const owner = parts.pop(); | |
| 112 | if (owner === undefined || name === undefined) return undefined; | |
| 113 | return parseRepoRef(`${owner}/${name}`); | |
| 114 | } | |
| 115 | ||
| 89 | 116 | /** `owner/name`, rejected as a pair rather than guessed at. */ |
| 90 | 117 | export function parseRepoRef( |
| 91 | 118 | text: string | undefined, |
src/cli/main.ts +95 −1
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | * forge sync clone what is missing, fetch the rest, report |
| 8 | 8 | * forge status the same report without touching the network |
| 9 | 9 | * forge asks what waits on you, most important first |
| 10 | * forge runs what the crew is doing on this folder's repo | |
| 10 | 11 | * |
| 11 | 12 | * Everything here is a thin shell around three modules: `api.ts` talks to the |
| 12 | 13 | * workbench, `sync.ts` decides what should be on disk, `report.ts` prints it. |
| @@ -14,7 +15,13 @@ | ||
| 14 | 15 | * an exit code — so a script can branch on the result without parsing text. |
| 15 | 16 | */ |
| 16 | 17 | |
| 17 | import { parseArgs, parseDuration, parseRepoRef, type Args } from "./args.ts"; | |
| 18 | import { | |
| 19 | parseArgs, | |
| 20 | parseDuration, | |
| 21 | parseRepoRef, | |
| 22 | repoFromRemote, | |
| 23 | type Args, | |
| 24 | } from "./args.ts"; | |
| 18 | 25 | import { ForgeApi, type Ask } from "./api.ts"; |
| 19 | 26 | import { |
| 20 | 27 | clearConfig, |
| @@ -36,6 +43,7 @@ import { | ||
| 36 | 43 | type RepoReport, |
| 37 | 44 | type SyncReport, |
| 38 | 45 | } from "./sync.ts"; |
| 46 | import { remoteUrl } from "../git/local.ts"; | |
| 39 | 47 | import { G } from "../tui/term/screen.ts"; |
| 40 | 48 | import { trackText } from "../tui/local/common.ts"; |
| 41 | 49 | import { displayWidth, pad, truncate } from "../tui/term/width.ts"; |
| @@ -101,6 +109,8 @@ export async function main(argv: readonly string[]): Promise<number> { | ||
| 101 | 109 | return openRepo(out, args); |
| 102 | 110 | case "asks": |
| 103 | 111 | return asks(out, args); |
| 112 | case "runs": | |
| 113 | return runs(out, args); | |
| 104 | 114 | case "ui": |
| 105 | 115 | return openTui(out, args); |
| 106 | 116 | default: |
| @@ -130,6 +140,9 @@ function usage(out: Out): void { | ||
| 130 | 140 | out.line( |
| 131 | 141 | b(" forge asks") + " [--repo owner/name] [--json]", |
| 132 | 142 | ); |
| 143 | out.line( | |
| 144 | b(" forge runs") + " [--repo owner/name] [--json]", | |
| 145 | ); | |
| 133 | 146 | out.line(); |
| 134 | 147 | out.line( |
| 135 | 148 | out.paint(` config ${configPath()} root ${rootDir()}`, out.c.faint), |
| @@ -494,6 +507,87 @@ function onlyRepo(raw: unknown, repo: string): unknown { | ||
| 494 | 507 | }; |
| 495 | 508 | } |
| 496 | 509 | |
| 510 | // ── runs ───────────────────────────────────────────────────────────────── | |
| 511 | ||
| 512 | const RUNS_SHOWN = 10; | |
| 513 | ||
| 514 | /** | |
| 515 | * What the crew is doing here: the last runs of the repository this folder | |
| 516 | * is a clone of (its `origin`), or of `--repo owner/name`. | |
| 517 | */ | |
| 518 | async function runs(out: Out, args: Args): Promise<number> { | |
| 519 | const named = args.value("repo"); | |
| 520 | const ref = | |
| 521 | named === undefined | |
| 522 | ? repoFromRemote(await remoteUrl(process.cwd())) | |
| 523 | : parseRepoRef(named); | |
| 524 | if (ref === undefined) { | |
| 525 | out.err( | |
| 526 | named === undefined | |
| 527 | ? "forge runs: this folder has no origin naming owner/name — pass --repo owner/name" | |
| 528 | : "forge runs: --repo expects owner/name", | |
| 529 | ); | |
| 530 | return EXIT.usage; | |
| 531 | } | |
| 532 | const loaded = await requireConfig(out); | |
| 533 | if (typeof loaded === "number") return loaded; | |
| 534 | const api = new ForgeApi(loaded.url, loaded.token); | |
| 535 | const result = await api.runs(ref.owner, ref.name, RUNS_SHOWN); | |
| 536 | if (!result.ok) { | |
| 537 | out.err(`forge runs: ${result.error.message}`); | |
| 538 | return result.error.status === 401 ? EXIT.notConfigured : EXIT.failed; | |
| 539 | } | |
| 540 | if (args.flag("json")) { | |
| 541 | out.line(JSON.stringify(result.value)); | |
| 542 | return EXIT.ok; | |
| 543 | } | |
| 544 | if (result.value.length === 0) { | |
| 545 | out.line(`no runs on ${ref.owner}/${ref.name} yet`); | |
| 546 | return EXIT.ok; | |
| 547 | } | |
| 548 | out.table( | |
| 549 | [ | |
| 550 | { header: "STATE" }, | |
| 551 | { header: "AGENT", max: 20 }, | |
| 552 | { header: "#", align: "right" }, | |
| 553 | { header: "TITLE", max: 56 }, | |
| 554 | { header: "AGE", align: "right" }, | |
| 555 | { header: "COST", align: "right" }, | |
| 556 | ], | |
| 557 | result.value.map((r) => { | |
| 558 | const state = text(r["state"]); | |
| 559 | const number = r["number"]; | |
| 560 | const cost = r["costUsd"]; | |
| 561 | return [ | |
| 562 | cell(state, stateColor(out, state)), | |
| 563 | cell(text(r["agent"]) || text(r["kind"]), out.c.fg), | |
| 564 | cell(typeof number === "number" ? `#${number}` : "", out.c.mutedFg), | |
| 565 | cell(text(r["title"]) || text(r["summary"]), out.c.fg), | |
| 566 | cell(age(r["createdAt"]), out.c.faint), | |
| 567 | cell(typeof cost === "number" && cost > 0 ? `$${cost.toFixed(2)}` : "", out.c.mutedFg), | |
| 568 | ]; | |
| 569 | }), | |
| 570 | ); | |
| 571 | return EXIT.ok; | |
| 572 | } | |
| 573 | ||
| 574 | function stateColor(out: Out, state: string): Out["c"]["fg"] { | |
| 575 | if (state === "running") return out.c.accent; | |
| 576 | if (state === "ok") return out.c.success; | |
| 577 | if (state === "failed") return out.c.danger; | |
| 578 | if (state === "queued") return out.c.attn; | |
| 579 | return out.c.mutedFg; | |
| 580 | } | |
| 581 | ||
| 582 | function text(value: unknown): string { | |
| 583 | return typeof value === "string" ? value : ""; | |
| 584 | } | |
| 585 | ||
| 586 | function age(value: unknown): string { | |
| 587 | const when = typeof value === "string" ? new Date(value) : null; | |
| 588 | return when === null || Number.isNaN(when.getTime()) ? "" : since(when); | |
| 589 | } | |
| 590 | ||
| 497 | 591 | // ── the terminal UI ────────────────────────────────────────────────────── |
| 498 | 592 | |
| 499 | 593 | async function openTui(out: Out, args: Args): Promise<number> { |
src/contract/openapi/routes/getApiV1ReposOwnerNameRuns.ts +1 −1
| @@ -1,3 +1,3 @@ | ||
| 1 | 1 | import { REPO, type Route } from "../shared.ts"; |
| 2 | 2 | |
| 3 | export const route: Route = { method: "get", path: `${REPO}/runs`, summary: "List a repository's runs, newest first: { items, next_cursor }; kind deploy or agent, env an environment name, limit 1 to 200 (default 50), cursor a run id; a stranger's runs carry no cost, turns, agent session or node", auth: false, query: { kind: "string", env: "string", limit: "integer", cursor: "string" } }; | |
| 3 | export const route: Route = { method: "get", path: `${REPO}/runs`, summary: "List a repository's runs, newest first: { items, next_cursor }, each row naming its agent, number and title; kind deploy or agent, env an environment name, limit 1 to 200 (default 50), cursor a run id; a stranger's runs carry no cost, turns, agent session or node", auth: false, query: { kind: "string", env: "string", limit: "integer", cursor: "string" } }; |
src/core/run_labels.ts added +52
| @@ -0,0 +1,52 @@ | ||
| 1 | /** | |
| 2 | * What a run is called: who worked it, which issue or pull it is about, and | |
| 3 | * that issue's title. One place, so the runs page (`web/pages/runs.ts`) and | |
| 4 | * the API's runs list — and so `forge runs` — cannot drift on it. Both | |
| 5 | * lookups are one grouped read for a whole page of runs. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | import { getIssuesByIds, type Issue } from "./issues.ts"; | |
| 10 | import type { Run } from "./runs.ts"; | |
| 11 | import { getUsersByIds, type User } from "./users.ts"; | |
| 12 | ||
| 13 | export interface LabelledRun extends Run { | |
| 14 | /** The agent's username for an agent run; whoever triggered it otherwise. */ | |
| 15 | readonly agent: string | null; | |
| 16 | /** The issue or pull number, or a preview's pull from its env name. */ | |
| 17 | readonly number: number | null; | |
| 18 | readonly title: string | null; | |
| 19 | } | |
| 20 | ||
| 21 | /** The pull a preview environment is for, from its name; production has none. */ | |
| 22 | export function envNumber(env: string): number | undefined { | |
| 23 | if (!env.startsWith("pull-")) return undefined; | |
| 24 | const n = Number(env.slice(5)); | |
| 25 | return Number.isInteger(n) && n > 0 ? n : undefined; | |
| 26 | } | |
| 27 | ||
| 28 | /** Every actor the runs name, in one read. */ | |
| 29 | export function runActors(db: Database, runs: readonly Run[]): Map<string, User> { | |
| 30 | return getUsersByIds(db, runs.map((run) => run.actorId ?? "").filter(Boolean)); | |
| 31 | } | |
| 32 | ||
| 33 | /** Every pull or issue the runs are about, in one read. */ | |
| 34 | export function runIssues(db: Database, runs: readonly Run[]): Map<string, Issue> { | |
| 35 | return getIssuesByIds(db, runs.map((run) => run.issueId ?? "").filter(Boolean)); | |
| 36 | } | |
| 37 | ||
| 38 | /** The runs as the API lists them: each row with its agent, number and title. */ | |
| 39 | export function labelRuns(db: Database, runs: readonly Run[]): LabelledRun[] { | |
| 40 | const users = runActors(db, runs); | |
| 41 | const issues = runIssues(db, runs); | |
| 42 | return runs.map((run) => { | |
| 43 | const issue = run.issueId === null ? undefined : issues.get(run.issueId); | |
| 44 | const actor = run.actorId === null ? undefined : users.get(run.actorId); | |
| 45 | return { | |
| 46 | ...run, | |
| 47 | agent: actor?.username ?? null, | |
| 48 | number: issue?.number ?? envNumber(run.env) ?? null, | |
| 49 | title: issue?.title ?? null, | |
| 50 | }; | |
| 51 | }); | |
| 52 | } |
src/http/api.ts +5 −1
| @@ -209,6 +209,7 @@ import { | ||
| 209 | 209 | type User, |
| 210 | 210 | } from "../core/users.ts"; |
| 211 | 211 | import { isPinned } from "../core/pins.ts"; |
| 212 | import { labelRuns } from "../core/run_labels.ts"; | |
| 212 | 213 | import { diffCommit } from "../git/diff.ts"; |
| 213 | 214 | import { runGit } from "../git/env.ts"; |
| 214 | 215 | import { appLimitWords, appsOwnedBy } from "../actions/app_limit.ts"; |
| @@ -4643,7 +4644,10 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 4643 | 4644 | if (!runs.ok) return notFound(); |
| 4644 | 4645 | // Already as this reader may see them (`runForReader`): a stranger's |
| 4645 | 4646 | // runs carry no cost, turns, agent session or node. |
| 4646 | return timePhase(ctx.request, "render", () => json(paged(runs.value, limit, (r) => r.id))); | |
| 4647 | // Each row names its agent, number and title (`run_labels.ts`). | |
| 4648 | return timePhase(ctx.request, "render", () => | |
| 4649 | json(paged(labelRuns(ctx.app.db, runs.value), limit, (r) => r.id)), | |
| 4650 | ); | |
| 4647 | 4651 | }); |
| 4648 | 4652 | |
| 4649 | 4653 | router.add("GET", "/api/v1/repos/:owner/:name/runs/:id", (ctx) => { |
src/web/pages/runs.ts +7 −16
| @@ -20,16 +20,17 @@ import { | ||
| 20 | 20 | runLog, |
| 21 | 21 | steerRepoRun, |
| 22 | 22 | } from "../../actions/runs.ts"; |
| 23 | import { getIssuesByIds, type Issue } from "../../core/issues.ts"; | |
| 23 | import type { Issue } from "../../core/issues.ts"; | |
| 24 | 24 | import { |
| 25 | 25 | canRead, |
| 26 | 26 | canSeeOwnerFacts, |
| 27 | 27 | getRepoById, |
| 28 | 28 | type Repo, |
| 29 | 29 | } from "../../core/repos.ts"; |
| 30 | import { envNumber, runActors, runIssues } from "../../core/run_labels.ts"; | |
| 30 | 31 | import { getRun, type Run, type RunKind } from "../../core/runs.ts"; |
| 31 | 32 | import { getUsage, issueUsage } from "../../core/usage.ts"; |
| 32 | import { getUsersByIds, type User } from "../../core/users.ts"; | |
| 33 | import type { User } from "../../core/users.ts"; | |
| 33 | 34 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; |
| 34 | 35 | import type { Ctx } from "../../http/context.ts"; |
| 35 | 36 | import { loadRepo, notFoundPage, repoBase, signInFirst } from "../chrome.ts"; |
| @@ -50,10 +51,6 @@ import { | ||
| 50 | 51 | |
| 51 | 52 | // ---- words ---- |
| 52 | 53 | |
| 53 | /** The pull a preview environment is for, from its name; production has none. */ | |
| 54 | const envNumber = (env: string): number | undefined => | |
| 55 | env.startsWith("pull-") ? Number(env.slice(5)) : undefined; | |
| 56 | ||
| 57 | 54 | /** |
| 58 | 55 | * What a run is, in a few words, naming the pull or issue it is about: |
| 59 | 56 | * `Deploy production`, `Deploy preview #3 Say hello`, `bot on #1 Do a |
| @@ -205,20 +202,14 @@ export function durationText(run: Run): string | undefined { | ||
| 205 | 202 | return `${Math.floor(minutes / 60)}h ${minutes % 60}m`; |
| 206 | 203 | } |
| 207 | 204 | |
| 208 | /** Every actor the runs name, in one read. */ | |
| 205 | /** Every actor the runs name, in one read (`core/run_labels.ts`). */ | |
| 209 | 206 | export function actorsFor(ctx: Ctx, runs: readonly Run[]): Map<string, User> { |
| 210 | return getUsersByIds( | |
| 211 | ctx.app.db, | |
| 212 | runs.map((run) => run.actorId ?? "").filter(Boolean), | |
| 213 | ); | |
| 207 | return runActors(ctx.app.db, runs); | |
| 214 | 208 | } |
| 215 | 209 | |
| 216 | /** Every pull or issue the runs are about, in one read. */ | |
| 210 | /** Every pull or issue the runs are about, in one read (`core/run_labels.ts`). */ | |
| 217 | 211 | export function issuesFor(ctx: Ctx, runs: readonly Run[]): Map<string, Issue> { |
| 218 | return getIssuesByIds( | |
| 219 | ctx.app.db, | |
| 220 | runs.map((run) => run.issueId ?? "").filter(Boolean), | |
| 221 | ); | |
| 212 | return runIssues(ctx.app.db, runs); | |
| 222 | 213 | } |
| 223 | 214 | |
| 224 | 215 | /** The run's title, with both grouped reads resolved. */ |
test/api-runs-labels.test.ts added +75
| @@ -0,0 +1,75 @@ | ||
| 1 | /** | |
| 2 | * The API's runs list names each row's agent, number and title (#7353), so | |
| 3 | * `forge runs` answers in one request; the rest of the row is unchanged. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 6 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { createRepo } from "../src/actions/repos.ts"; | |
| 11 | import { createIssue } from "../src/core/issues.ts"; | |
| 12 | import { createRun } from "../src/core/runs.ts"; | |
| 13 | import { createSession } from "../src/core/sessions.ts"; | |
| 14 | import { createUser } from "../src/core/users.ts"; | |
| 15 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 16 | import { quietLogs } from "./helpers/globals.ts"; | |
| 17 | ||
| 18 | quietLogs(); | |
| 19 | ||
| 20 | let dataDir: string; | |
| 21 | let app: App; | |
| 22 | let servers: Servers; | |
| 23 | let cookie = ""; | |
| 24 | let issueNumber = 0; | |
| 25 | ||
| 26 | const cells = process.env["FORGE_CELLS"]; | |
| 27 | ||
| 28 | beforeAll(async () => { | |
| 29 | process.env["FORGE_CELLS"] = "off"; | |
| 30 | dataDir = await mkdtemp(join(tmpdir(), "forge-api-runs-labels-")); | |
| 31 | app = createApp({ dataDir, port: 0 }); | |
| 32 | servers = await serve(app); | |
| 33 | const made = await createUser(app.db, { | |
| 34 | origin: "seed", | |
| 35 | trusted: true, | |
| 36 | username: "alice", | |
| 37 | email: "[email protected]", | |
| 38 | password: "a-good-passphrase", | |
| 39 | adminIfFirst: true, | |
| 40 | }); | |
| 41 | if (!made.ok) throw new Error(String(made.error)); | |
| 42 | const alice = made.value; | |
| 43 | cookie = `forge_session=${createSession(app.db, alice.id).token}`; | |
| 44 | const repo = await createRepo(app, alice, { name: "r", visibility: "public" }); | |
| 45 | if (!repo.ok) throw new Error(String(repo.error)); | |
| 46 | const made2 = createIssue(app.db, { repoId: repo.value.id, authorId: alice.id, title: "Say hello" }); | |
| 47 | if (!made2.ok) throw new Error(String(made2.error)); | |
| 48 | const issue = made2.value; | |
| 49 | issueNumber = issue.number; | |
| 50 | createRun(app.db, { repoId: repo.value.id, kind: "deploy", env: "production" }); | |
| 51 | createRun(app.db, { repoId: repo.value.id, kind: "deploy", env: "pull-41" }); | |
| 52 | createRun(app.db, { repoId: repo.value.id, kind: "agent", issueId: issue.id, actorId: alice.id }); | |
| 53 | }); | |
| 54 | afterAll(async () => { | |
| 55 | await servers.stop(); | |
| 56 | app.close(); | |
| 57 | if (cells === undefined) delete process.env["FORGE_CELLS"]; | |
| 58 | else process.env["FORGE_CELLS"] = cells; | |
| 59 | await rm(dataDir, { recursive: true, force: true }); | |
| 60 | }); | |
| 61 | ||
| 62 | test("each run row carries agent, number and title beside its own fields", async () => { | |
| 63 | const res = await fetch(`${servers.url}/api/v1/repos/alice/r/runs`, { headers: { cookie } }); | |
| 64 | expect(res.status).toBe(200); | |
| 65 | const rows = ((await res.json()) as { items: Record<string, unknown>[] }).items; | |
| 66 | const labels = rows.map((r) => [r["kind"], r["agent"], r["number"], r["title"]]); | |
| 67 | expect(labels).toContainEqual(["agent", "alice", issueNumber, "Say hello"]); | |
| 68 | expect(labels).toContainEqual(["deploy", null, 41, null]); | |
| 69 | expect(labels).toContainEqual(["deploy", null, null, null]); | |
| 70 | for (const r of rows) { | |
| 71 | expect(typeof r["id"]).toBe("string"); | |
| 72 | expect(typeof r["state"]).toBe("string"); | |
| 73 | expect(typeof r["createdAt"]).toBe("string"); | |
| 74 | } | |
| 75 | }); |
test/cli-runs.test.ts added +169
| @@ -0,0 +1,169 @@ | ||
| 1 | /** | |
| 2 | * `forge runs` (#7353): the CLI as a shell runs it — a process, an | |
| 3 | * environment, a folder — against a fake forge that records what it was | |
| 4 | * asked and answers the runs list. | |
| 5 | */ | |
| 6 | ||
| 7 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { repoFromRemote } from "../src/cli/args.ts"; | |
| 12 | import { gitClientEnv } from "./helpers/git-client.ts"; | |
| 13 | ||
| 14 | const CLI = new URL("../src/cli/main.ts", import.meta.url).pathname; | |
| 15 | ||
| 16 | const minute = 60_000; | |
| 17 | const ROWS = [ | |
| 18 | { | |
| 19 | id: "r1", | |
| 20 | kind: "agent", | |
| 21 | state: "running", | |
| 22 | agent: "mason", | |
| 23 | number: 7353, | |
| 24 | title: "forge runs lists what the crew is doing", | |
| 25 | summary: "", | |
| 26 | costUsd: 1.234, | |
| 27 | createdAt: new Date(Date.now() - 3 * minute).toISOString(), | |
| 28 | }, | |
| 29 | { | |
| 30 | id: "r2", | |
| 31 | kind: "check", | |
| 32 | state: "failed", | |
| 33 | agent: "alice", | |
| 34 | number: 12, | |
| 35 | title: null, | |
| 36 | summary: "check failed in 9s", | |
| 37 | costUsd: 0, | |
| 38 | createdAt: new Date(Date.now() - 2 * 60 * minute).toISOString(), | |
| 39 | }, | |
| 40 | ]; | |
| 41 | ||
| 42 | let server: ReturnType<typeof Bun.serve>; | |
| 43 | let base = ""; | |
| 44 | let dir = ""; | |
| 45 | const asked: string[] = []; | |
| 46 | ||
| 47 | beforeAll(async () => { | |
| 48 | server = Bun.serve({ | |
| 49 | port: 0, | |
| 50 | fetch(req) { | |
| 51 | const url = new URL(req.url); | |
| 52 | asked.push(`${url.pathname}${url.search}`); | |
| 53 | if (req.headers.get("authorization") === "Bearer stale") | |
| 54 | return Response.json({ error: "unauthorized", message: "token expired" }, { status: 401 }); | |
| 55 | if (url.pathname === "/api/v1/repos/alice/app/runs") | |
| 56 | return Response.json({ items: ROWS, next_cursor: null }); | |
| 57 | if (url.pathname === "/api/v1/repos/alice/empty/runs") | |
| 58 | return Response.json({ items: [], next_cursor: null }); | |
| 59 | return Response.json({ error: "not_found", message: "not found" }, { status: 404 }); | |
| 60 | }, | |
| 61 | }); | |
| 62 | base = `http://127.0.0.1:${server.port}`; | |
| 63 | dir = await mkdtemp(join(tmpdir(), "forge-cli-runs-")); | |
| 64 | const git = (args: string[]) => | |
| 65 | Bun.spawnSync(["git", ...args], { cwd: dir, env: gitClientEnv() }); | |
| 66 | git(["init", "-q"]); | |
| 67 | git(["remote", "add", "origin", `${base}/alice/app.git`]); | |
| 68 | }); | |
| 69 | ||
| 70 | afterAll(async () => { | |
| 71 | server.stop(true); | |
| 72 | await rm(dir, { recursive: true, force: true }); | |
| 73 | }); | |
| 74 | ||
| 75 | async function forge( | |
| 76 | args: string[], | |
| 77 | env: Record<string, string> = {}, | |
| 78 | ): Promise<{ code: number; out: string; err: string }> { | |
| 79 | const proc = Bun.spawn(["bun", CLI, "runs", ...args], { | |
| 80 | cwd: dir, | |
| 81 | env: { | |
| 82 | PATH: process.env["PATH"] ?? "", | |
| 83 | HOME: dir, | |
| 84 | FORGE_CONFIG_DIR: join(dir, ".config"), | |
| 85 | FORGE_KEYCHAIN: "0", | |
| 86 | FORGE_URL: base, | |
| 87 | FORGE_TOKEN: "t", | |
| 88 | ...gitClientEnv(), | |
| 89 | ...env, | |
| 90 | }, | |
| 91 | stdout: "pipe", | |
| 92 | stderr: "pipe", | |
| 93 | }); | |
| 94 | const [out, err, code] = await Promise.all([ | |
| 95 | new Response(proc.stdout).text(), | |
| 96 | new Response(proc.stderr).text(), | |
| 97 | proc.exited, | |
| 98 | ]); | |
| 99 | return { code, out, err }; | |
| 100 | } | |
| 101 | ||
| 102 | test("the folder's origin names the repository, and the last 10 are asked for", async () => { | |
| 103 | asked.length = 0; | |
| 104 | const got = await forge([]); | |
| 105 | expect(got.code).toBe(0); | |
| 106 | expect(asked).toEqual(["/api/v1/repos/alice/app/runs?limit=10"]); | |
| 107 | }); | |
| 108 | ||
| 109 | test("rows print in aligned columns: state, agent, #N, title, age, cost — no colour into a pipe", async () => { | |
| 110 | const got = await forge(["--repo", "alice/app"]); | |
| 111 | expect(got.code).toBe(0); | |
| 112 | expect(got.out).not.toContain("\x1b["); | |
| 113 | const lines = got.out.trimEnd().split("\n"); | |
| 114 | expect(lines).toHaveLength(3); | |
| 115 | expect(lines[0]).toMatch(/^STATE\s+AGENT\s+#\s+TITLE\s+AGE\s+COST$/); | |
| 116 | expect(lines[1]).toMatch(/^running\s+mason\s+#7353\s+forge runs lists what the crew is doing\s+3m\s+\$1\.23$/); | |
| 117 | // No title: the run's own summary says what it was; no cost, no column text. | |
| 118 | expect(lines[2]).toMatch(/^failed\s+alice\s+#12\s+check failed in 9s\s+2h$/); | |
| 119 | // Aligned: every row's title starts where the header's does. | |
| 120 | const at = lines[0]!.indexOf("TITLE"); | |
| 121 | expect(lines[1]!.indexOf("forge runs")).toBe(at); | |
| 122 | expect(lines[2]!.indexOf("check failed")).toBe(at); | |
| 123 | }); | |
| 124 | ||
| 125 | test("--json prints the API's rows unchanged", async () => { | |
| 126 | const got = await forge(["--repo", "alice/app", "--json"]); | |
| 127 | expect(got.code).toBe(0); | |
| 128 | expect(JSON.parse(got.out)).toEqual(ROWS); | |
| 129 | }); | |
| 130 | ||
| 131 | test("an empty list says so", async () => { | |
| 132 | const got = await forge(["--repo", "alice/empty"]); | |
| 133 | expect(got.code).toBe(0); | |
| 134 | expect(got.out).toBe("no runs on alice/empty yet\n"); | |
| 135 | }); | |
| 136 | ||
| 137 | test("an unknown repository prints the API's words and fails", async () => { | |
| 138 | const got = await forge(["--repo", "alice/nope"]); | |
| 139 | expect(got.code).toBe(1); | |
| 140 | expect(got.err).toBe("forge runs: not found\n"); | |
| 141 | expect(got.out).toBe(""); | |
| 142 | }); | |
| 143 | ||
| 144 | test("a refused token, or no sign-in at all, exits as not configured", async () => { | |
| 145 | const stale = await forge(["--repo", "alice/app"], { FORGE_TOKEN: "stale" }); | |
| 146 | expect(stale.code).toBe(3); | |
| 147 | expect(stale.err).toBe("forge runs: token expired\n"); | |
| 148 | const none = await forge(["--repo", "alice/app"], { FORGE_URL: "", FORGE_TOKEN: "" }); | |
| 149 | expect(none.code).toBe(3); | |
| 150 | expect(none.err).toContain("not signed in"); | |
| 151 | }); | |
| 152 | ||
| 153 | test("a bad --repo is a usage error, before any request", async () => { | |
| 154 | asked.length = 0; | |
| 155 | const got = await forge(["--repo", "nope"]); | |
| 156 | expect(got.code).toBe(2); | |
| 157 | expect(asked).toEqual([]); | |
| 158 | }); | |
| 159 | ||
| 160 | test("a remote URL names owner/name in every spelling git takes", () => { | |
| 161 | const want = { owner: "alice", name: "app" }; | |
| 162 | expect(repoFromRemote("https://forge.example/alice/app.git")).toEqual(want); | |
| 163 | expect(repoFromRemote("https://forge.example/alice/app")).toEqual(want); | |
| 164 | expect(repoFromRemote("ssh://[email protected]:2222/alice/app.git")).toEqual(want); | |
| 165 | expect(repoFromRemote("[email protected]:alice/app.git")).toEqual(want); | |
| 166 | expect(repoFromRemote("https://forge.example/app.git")).toBeUndefined(); | |
| 167 | expect(repoFromRemote("not a url")).toBeUndefined(); | |
| 168 | expect(repoFromRemote(null)).toBeUndefined(); | |
| 169 | }); |
new above
offline
This was
parseRepoRef's doc comment, and it is now left aboverepoFromRemote's doc block (two JSDoc blocks in a row;parseRepoRefhas none). Move it back to just aboveexport function parseRepoRef.