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

The terminal lists a repository's labels, makes one and deletes one with a confirm, as MCP `repo_labels` does #7280

Parked opened this
Closed without merging

scout/forge:scout/7255-the-terminal-lists-a-repository-s-labels → main 5 commits fork 5 threads · 5 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +359 −1
README.md +4
@@ -263,6 +263,10 @@ opened with it says "proposed by child … from …" on every tab of the pull's
263263 page, in the terminal's pull view, and as `proposal` in the pull's JSON
264264 (`GET …/pulls/:number`, and MCP's `pull` tool). `GET …/pulls/:number?diff=0` reads the pull without its diff (and skips computing it); `diff` is `0` or `1`, default `1`, and anything else answers 422. `GET …/issues?fields=brief` lists issues with only number, kind, title, state, labels, assignee, author, originAuthor, authorIsAgent, createdAt and updatedAt (and `untrusted` where it applies); no bodies or comments. `fields` is `brief` or left out, and anything else answers 422 `invalid_fields`. `GET …/repos/:owner/:name/events` answers `{ items, next_cursor }`, newest first, `limit` 1 to 200 (default 50) and `cursor` from `next_cursor` (anything else is a 422); it used to answer a bare array of every event, so a client that read the array reads `items` now. A request reads at most 1,000 events, so when most of them are hidden from the reader a page can come back short with a `next_cursor`: keep following it until it is null. MCP's `events` tool answers the same. `GET …/repos/:owner/:name/branches` answers `{ items, next_cursor }` in the order it always had, `limit` 1 to 200 (default 50) and `cursor` the `next_cursor` of the page before (the name of the last branch on it); anything else is a 422, and a cursor naming a branch deleted between two requests is `invalid_cursor`, so start over. It used to answer a bare array, so a client that read the array reads `items` now. `GET …/repos/:owner/:name/forks`, `…/labels` and `…/hooks` answer `{ items, next_cursor }` too, in the order they always had, `limit` 1 to 200 (default 50) and `cursor` the `next_cursor` of the page before (the id of the last row on it); anything else is a 422, and a cursor naming a row deleted between two requests is `invalid_cursor`, so start over. They used to answer a bare array, so a client that read the array reads `items` now.
265265
266 ### Labels in the terminal
267
268 `:` → "Labels in a repository" (or "Labels" in a repository's own palette) lists the labels with their colour chips and how many open issues and pulls carry each; it follows changes made on the web or through MCP. For a repository's admin, `n` takes "name hex" (for example `bug d73a4a`) and `d` deletes the selected label after a confirm naming how many issues and pulls lose it; a reader sees the list alone. Same actions as `repo_labels`.
269
266270 ### Proposing to a parent forge
267271
268272 A spawned forge can offer its change to its parent with a proposal token, and an admin sets how it follows the parent. Details, API, MCP and terminal doors: [`docs/FOLLOWING.md`](docs/FOLLOWING.md#proposing-to-a-parent-forge).
src/core/issues.ts +17
@@ -857,6 +857,23 @@ export function listLabels(db: Database, repoId: string): Label[] {
857857 .all(repoId);
858858 }
859859
860 /** How many issues and pulls carry each label of a repo: `open` of them still open. */
861 export function labelUse(
862 db: Database,
863 repoId: string,
864 ): Map<string, { open: number; all: number }> {
865 const rows = db
866 .query<
867 { id: string; open: number; all: number },
868 [string]
869 >(`SELECT label.id AS id, COALESCE(SUM(issue.state = 'open'), 0) AS open, COUNT(issue.id) AS "all"

This join counts pulls as well as issues, but the confirm says "N issues lose it". Either name the kind correctly in the wording or filter by kind here.

870 FROM label LEFT JOIN issue_label ON issue_label.label_id = label.id
871 LEFT JOIN issue ON issue.id = issue_label.issue_id
872 WHERE label.repo_id = ?1 GROUP BY label.id`)
873 .all(repoId);
874 return new Map(rows.map((r) => [r.id, { open: r.open, all: r.all }]));
875 }
876
860877 export function setIssueLabels(
861878 db: Database,
862879 issueId: string,
src/tui/forge.ts +6
@@ -82,6 +82,7 @@ import { releasesScreen } from "./screens/releases.ts";
8282 import { mayRead } from "../release/gate.ts";
8383 import { fileHoldsPrompt } from "./screens/fileholds.ts";
8484 import { stalledScreen } from "./screens/stalled.ts";
85 import { labelsScreen } from "./screens/labels.ts";
8586 import { issuesScreen, newIssueScreen } from "./screens/issues.ts";
8687 import { limbsScreen } from "./screens/limbs.ts";
8788 import { newPullScreen } from "./screens/newpull.ts";
@@ -125,6 +126,11 @@ const REPO_VERBS: readonly {
125126 title: "Milestones in a repository",
126127 open: (f, ctx, repo) => limbsScreen(f, ctx, repo),
127128 },
129 {
130 id: "labels",
131 title: "Labels in a repository",
132 open: (f, ctx, repo) => labelsScreen(f, ctx, repo),
133 },
128134 { id: "new-issue", title: "New issue", open: newIssueScreen },
129135 { id: "new-pull", title: "New pull request", open: newPullScreen },
130136 {
src/tui/screens/labels.ts added +148
@@ -0,0 +1,148 @@
1 /**
2 * A repository's labels, the terminal's door to the labels page and MCP
3 * `repo_labels`: each label as its chip with how many open issues carry it.
4 * `n` makes one and `d` deletes the selected one after a confirm, both through
5 * the actions, so who may and what a bad one is told are theirs. Only an admin
6 * of the repository is offered the two keys.
7 */
8
9 import { LABEL_WORDS } from "../../actions/label_words.ts";
10 import { createLabel, deleteLabel } from "../../actions/repos.ts";
11 import { labelUse, listLabels, type Label } from "../../core/issues.ts";
12 import { canAdmin, type Repo } from "../../core/repos.ts";
13 import type { Ctx, Screen } from "../app/app.ts";
14 import { binding } from "../app/keys.ts";
15 import type { Command } from "../app/palette.ts";
16 import type { Session } from "../session.ts";
17 import { style } from "../term/style.ts";
18 import { truncate } from "../term/width.ts";
19 import { fill, len, split } from "../ui/layout.ts";
20 import { emptyState, labelChip } from "../ui/widgets.ts";
21 import { ListState, confirmScreen, live, plural, promptScreen } from "./common.ts";
22
23 /** "name ffcc00": the colour is the last word, the name is the rest. */
24 export function parseLabel(text: string): { name: string; color: string } | undefined {
25 const m = /^(.+?)\s+#?([0-9a-fA-F]{6})$/.exec(text.trim());
26 return m === null ? undefined : { name: m[1]!, color: m[2]! };
27 }
28
29 export function labelsCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] {
30 if (repo === undefined) return [];
31 return [
32 {
33 id: "labels",
34 title: `${repo.ownerName}/${repo.name} — Labels`,
35 hint: "list, make, delete",
36 run: () => ctx.push(labelsScreen(f, ctx, repo)),
37 },
38 ];
39 }
40
41 export function labelsScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
42 const state = new ListState();
43 let labels: Label[] = [];
44 let use = labelUse(f.db, repo.id);
45 const admin = () => f.user !== undefined && canAdmin(f.db, repo, f.user);
46 const read = (): void => {
47 labels = listLabels(f.db, repo.id);
48 use = labelUse(f.db, repo.id);
49 state.clamp(labels.length);
50 ctx.invalidate();
51 };
52 read();
53 const self: Screen = {
54 title: "Labels",
55 get keys() {
56 return [
57 binding(["j", "k"], "move"),
58 ...(admin() ? [binding(["n"], "new label"), binding(["d"], "delete")] : []),
59 binding(["esc", "q"], "close"),
60 ];
61 },

This screen only reads on load, so a change made on the web, through MCP or in another terminal does not show here. Subscribe with live(f, signal, { repoId: repo.id, kinds: ["label.created","label.updated","label.deleted"] }, read) as limbs.ts does.

62 load(signal) {
63 live(f, signal, { repoId: repo.id, kinds: ["label.created", "label.updated", "label.deleted"] }, read);
64 read();
65 return Promise.resolve();
66 },
67 render(area, s) {
68 const c = ctx.theme.c;
69 const [head, body] = split(area, "v", [len(1), fill(1)]);
70 s.text(
71 head!.x,
72 head!.y,
73 truncate(`${repo.ownerName}/${repo.name} · ${plural(labels.length, "label")}`, head!.w),
74 style(c.mutedFg, c.bg),
75 head!.x + head!.w,
76 );
77 if (labels.length === 0) {
78 emptyState(s, body!, c, {
79 title: "No labels yet",
80 ...(admin() ? { body: "Press n to make one." } : {}),
81 });
outdated

High: rows past body.h are never drawn, but the cursor can still move onto them, and then d deletes a label that is off the screen. Use state.window(body!.h, labels.length) and draw from that offset.

82 return;
83 }
84 const from = state.window(body!.h, labels.length);
85 labels.slice(from, from + body!.h).forEach((l, i) => {
86 const y = body!.y + i;
87 const right = body!.x + body!.w;
88 const sel = from + i === state.index;
89 s.text(body!.x, y, sel ? "▸" : " ", style(c.fg, c.bg), right);
90 const end = labelChip(s, body!.x + 2, y, c, { text: truncate(l.name, 30), color: l.color }, right);
91 s.text(end + 2, y, `#${l.color} ${use.get(l.id)?.open ?? 0} open`, style(c.mutedFg, c.bg), right);
92 });
93 },
94 key(e) {
95 if (e.key === "esc" || e.key === "q") {
96 ctx.pop();
97 return true;
98 }
99 if (e.key === "n" && admin()) {
100 ctx.push(
101 promptScreen(ctx, self, {
102 title: "New label",
103 label: "Name, then six hex digits",
104 placeholder: "bug d73a4a",
105 onSubmit: (text) => {
106 const parsed = parseLabel(text);
107 if (parsed === undefined) return LABEL_WORDS.shape;
108 const made = createLabel(f.app, f.user, repo, parsed.name, parsed.color);
109 if (!made.ok)
110 return made.error === "taken"
111 ? "A label with that name already exists."
112 : made.error === "invalid"
113 ? LABEL_WORDS.shape
114 : "You cannot change this repository's labels.";
115 read();
116 ctx.toast(`Created the label ${made.value.name}.`);
117 return undefined;
118 },
119 }),
120 );
121 return true;
122 }
123 if (e.key === "d" && admin()) {
124 const label = labels[state.index];
125 if (label === undefined) return true;
126 const n = use.get(label.id)?.all ?? 0;
127 ctx.push(
128 confirmScreen(ctx, self, {
129 title: "Delete label",
130 body: [`Delete ${label.name}? ${n === 0 ? "No issue carries it." : `${n} ${n === 1 ? "issue or pull loses" : "issues and pulls lose"} it.`}`],
131 actions: [{ label: "Delete", variant: "danger" }, { label: "Cancel" }],
132 selected: 1,
133 onChoose: (choice) => {
134 if (choice !== 0) return;
135 const gone = deleteLabel(f.app, f.user, repo, label.id);

Any failed delete says "No such label." Map the error (not found vs forbidden) as the create path does.

136 read();
137 ctx.toast(gone.ok ? `Deleted the label ${label.name}.` : "No such label, or you are not this repository's admin.", gone.ok ? "default" : "danger");
138 },
139 }),
140 );
141 return true;
142 }
143 state.key(e, labels.length);
144 return true;
145 },
146 };
147 return self;
148 }
src/tui/screens/workspace.ts +2
@@ -122,6 +122,7 @@ import { reportCommands } from "./report.ts";
122122 import { reportsCommands } from "./reports.ts";
123123 import { tellCommands } from "./tell.ts";
124124 import { workingCommands } from "./working.ts";
125 import { labelsCommands } from "./labels.ts";
125126 import { yoursCommands } from "./yours.ts";
126127 import { visionCommands } from "./vision.ts";
127128 import { appEnvCommands } from "./appenv.ts";
@@ -1287,6 +1288,7 @@ export function workspaceScreen(
12871288 ...reportCommands(f, ctx, () => screen, repo),
12881289 ...reportsCommands(f, ctx, repo),
12891290 ...noteCommands(f, ctx, () => screen, repo),
1291 ...labelsCommands(f, ctx, repo),
12901292 ...yoursCommands(f, ctx, repo),
12911293 ...visionCommands(f, ctx, repo),
12921294 ...appEnvCommands(f, ctx, repo),
test/tui-labels.test.ts added +177
@@ -0,0 +1,177 @@
1 /**
2 * A repository's labels in the terminal: the list with its chips and open
3 * counts, `n` makes one through createLabel, `d` deletes after a confirm that
4 * names the issues that lose it, and a reader is offered neither key.
5 */
6 import { afterAll, beforeAll, beforeEach, 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 { openIssue } from "../src/actions/issues.ts";
11 import { createLabel, createRepo, deleteLabel } from "../src/actions/repos.ts";
12 import { createApp, type App as Forge } from "../src/app.ts";
13 import { listLabels, setIssueLabels } from "../src/core/issues.ts";
14 import type { Repo } from "../src/core/repos.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { createForgeApp } from "../src/tui/forge.ts";
17 import { labelsScreen, parseLabel } from "../src/tui/screens/labels.ts";
18 import { headlessTerminal } from "../src/tui/term/terminal.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20 import { settleApp } from "./helpers/tui.ts";
21
22 quietLogs();
23
24 describe("labels in the terminal", () => {
25 let dir: string;
26 let forge: Forge;
27 let alice: User;
28 let bob: User;
29 let repo: Repo;
30 let issueId: string;
31
32 function open(user: User) {
33 const terminal = headlessTerminal(110, 24);
34 const { app, session } = createForgeApp(
35 forge,
36 { sshUsername: "t", remoteAddress: "127.0.0.1", user },
37 { terminal, exitHooks: false },
38 );
39 app.start();
40 app.ctx.push(labelsScreen(session, app.ctx, repo));
41 const type = async (text: string) => {
42 for (const ch of text) {
43 app.dispatch({ type: "key", key: ch, ctrl: false, alt: false, shift: false });
44 await settleApp(app);
45 }
46 };
47 const esc = async () => {
48 app.dispatch({ type: "key", key: "esc", ctrl: false, alt: false, shift: false });
49 await settleApp(app);
50 };
51 const enter = async () => {
52 app.dispatch({ type: "key", key: "enter", ctrl: false, alt: false, shift: false });
53 await settleApp(app);
54 };
55 const ready = () => settleApp(app);
56 return { ready, text: () => app.screen.toText(), type, enter, esc, stop: () => app.stop() };
57 }
58
59 beforeAll(async () => {
60 dir = await mkdtemp(join(tmpdir(), "forge-tui-labels-"));
61 forge = createApp({ dataDir: dir, port: 0 });
62 const users: User[] = [];
63 for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) {
64 const made = await createUser(forge.db, {
65 origin: "seed",
66 trusted: true,
67 username,
68 email: `${username}@forge.local`,
69 password: "a-good-passphrase",
70 adminIfFirst,
71 });
72 if (!made.ok) throw new Error(made.error);
73 users.push(made.value);
74 }
75 [alice, bob] = users as [User, User];
76 const made = await createRepo(forge, alice, { name: "site", visibility: "public" });
77 if (!made.ok) throw new Error(made.error);
78 repo = made.value;
79 const issue = openIssue(forge, alice, repo, { title: "It breaks" });
80 if (!issue.ok) throw new Error(issue.error);
81 issueId = issue.value.id;
82 });
83
84 // Each test starts from the same one label, "bug", carried by one issue.
85 beforeEach(() => {
86 for (const l of listLabels(forge.db, repo.id)) deleteLabel(forge, alice, repo, l.id);
87 const bug = createLabel(forge, alice, repo, "bug", "d73a4a");
88 if (!bug.ok) throw new Error(bug.error);
89 setIssueLabels(forge.db, issueId, [bug.value.id]);
90 });
91
92 afterAll(async () => {
93 forge.db.close();
94 await rm(dir, { recursive: true, force: true });
95 });
96
97 test("parseLabel takes the colour from the last word", () => {
98 expect(parseLabel("good first issue #00FF00")).toEqual({ name: "good first issue", color: "00FF00" });
99 expect(parseLabel("bug")).toBeUndefined();
100 expect(parseLabel("bug 12345")).toBeUndefined();
101 });
102
103 test("lists each label with its open count", async () => {
104 const t = open(alice);
105 await t.ready();
106 const text = t.text();
107 expect(text).toContain("bug");
108 expect(text).toContain("1 open");
109 expect(text).toContain("n new label");
110 t.stop();
111 });
112
113 test("a bad colour says the words and makes nothing; a good one makes the label", async () => {
114 const t = open(alice);
115 await t.type("n");
116 await t.type("urgent zzz");
117 await t.enter();
118 expect(t.text()).toContain("A label needs a name and a six-digit hex color.");
119 expect(listLabels(forge.db, repo.id).map((l) => l.name)).toEqual(["bug"]);
120 await t.esc();
121 await t.type("n");
122 await t.type("bug aabbcc");
123 await t.enter();
124 expect(t.text()).toContain("already exists");
125 await t.esc();
126 t.stop();
127 const u = open(alice);
128 await u.type("n");
129 await u.type("urgent 00ff00");
130 await u.enter();
131 expect(listLabels(forge.db, repo.id).map((l) => l.name)).toEqual(["bug", "urgent"]);
132 expect(u.text()).toContain("urgent");
133 u.stop();
134 });
135
136 test("d confirms with the issues that lose the label, then deletes", async () => {
137 const t = open(alice);
138 await t.type("d");
139 expect(t.text()).toContain("1 issue or pull loses it");
140 await t.enter(); // Cancel is the default
141 expect(listLabels(forge.db, repo.id).map((l) => l.name)).toContain("bug");
142 await t.type("d");
143 await t.type("h");
144 await t.enter();
145 expect(listLabels(forge.db, repo.id).map((l) => l.name)).toEqual([]);
146 t.stop();
147 });
148
149 test("a label made elsewhere appears, and the cursor never leaves the screen", async () => {
150 const t = open(alice);
151 await t.ready();
152 for (let i = 0; i < 30; i++) createLabel(forge, alice, repo, `extra-${String(i).padStart(2, "0")}`, "112233");
153 await Bun.sleep(150);
154 await t.ready();
155 expect(t.text()).toContain("extra-00");
156 for (let i = 0; i < 31; i++) await t.type("j");
157 const names = listLabels(forge.db, repo.id).map((l) => l.name);
158 const last = names[names.length - 1]!;
159 expect(t.text()).toContain(last);
160 await t.type("d");
161 expect(t.text()).toContain(`Delete ${last}?`);
162 t.stop();
163 });
164
165 test("a reader sees the list alone", async () => {
166 const t = open(bob);
167 await t.ready();
168 expect(t.text()).toContain("bug");
169 expect(t.text()).not.toContain("new label");
170 await t.type("n");
171 await t.type("d");
172 expect(t.text()).not.toContain("New label");
173 expect(t.text()).not.toContain("Delete label");
174 expect(listLabels(forge.db, repo.id).length).toBe(1);
175 t.stop();
176 });
177 });
test/tui-notes.test.ts +5 −1
@@ -86,6 +86,10 @@ describe("notes from the app, in the terminal", () => {
8686 expect(await palette(bob, plain, [":", "Tell the"])).not.toContain("Tell the builders");
8787 });
8888
89 test("the repository palette offers its labels", async () => {
90 expect(await palette(bob, notes, [":", "Labels"])).toContain("alice/notes — Labels");
91 });
92
8993 test("a note files a from-app issue as the person", async () => {
9094 const text = await palette(bob, notes, [":", "Tell the", "\r", ..."the logo is blurry".split(""), "\r"]);
9195 expect(text).toContain("Sent");
@@ -112,7 +116,7 @@ describe("notes from the app, in the terminal", () => {
112116 test("the admin lists the banned senders and unbans one; a reader has no such row", async () => {
113117 const record = getAppBySlug(app.db, "notes")!;
114118 expect(isBanned(app.db, record.id, `u:${bob.id}`)).toBe(true);
115 expect(await palette(bob, notes, [":"])).not.toContain("Banned senders");
119 expect(await palette(bob, notes, [":", "Banned"])).not.toContain("Banned senders");
116120 const listed = await palette(alice, notes, [":", "Banned", "\r"]);
117121 expect(listed).toContain("@bob");
118122 expect(await palette(bob, notes, [":", "Banned", "\r"])).not.toContain("Unban");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs