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

One inbox: On you and Needs you become one list with one word, and an agent's pull waits for its reviewer before it reaches the owner #1530

Closed opened this in answer to
Closed without merging

scout/forge:scout/1135-one-inbox-on-you-and-needs-you-become-on → main 9 commits fork 4 threads · 4 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
26 files changed +875 −216
docs/STUDIO.md +17 −1
@@ -344,11 +344,27 @@ at its ceiling, an issue the breaker parked, and an autonomous app whose
344344 planner declined its direction — answered by a comment on the direction
345345 issue, which is also what the board's line above its regions offers), and, for a site admin only, one card per sentence of the
346346 forge's health (`needs` in `/api/v1/health`). What counts as an ask is
347 defined once, in `src/web/studio/asks.ts`: the header's **Asks** count, the
347 defined once, in `src/web/studio/asks.ts`: the header's **Inbox** count, the
348348 page, the dashboard's _Needs you_ link and the phone notifier all read it,
349349 so the numbers agree. It is server-rendered and every button is a form post,
350350 so it works without JavaScript.
351351
352 It is one inbox (#1135): what is assigned to the viewer joins the asks in
353 the same list and the same count, and every row says what it waits for and
354 from whom (`waitingFor`: _ready to land_, _a decision_, _waiting for your
355 review_, _assigned to you_). An agent's green pull whose reviewer has not
356 answered is the reviewer's, not the viewer's: it sits under **The crew's**
357 as _waiting for juniper's review_ (uncounted) and moves to the viewer's part
358 when a verdict lands or the review lapses; a green pull that conflicts with
359 main sits there too, as _conflicts with main_. `/live/on-you`,
360 `/api/v1/asks` and the MCP `asks` serve the same list.
361
362 The terminal's dashboard shows the same list: its **Inbox · N** card reads
363 `askLinesFor`, `assignedLinesFor` and `crewLinesFor`, one row each with its
364 `waitingFor`, the crew's part after the counted rows and not counted. The
365 phone notifier tells about asks and assigned work (the header's count minus
366 the forge's own needs, which it tells separately).
367
352368 ## What you asked for
353369
354370 `/asked` (`askedPage`, `src/web/studio/asked_page.ts`) is the other
scripts/gate.ts +2
@@ -29,6 +29,8 @@ export const GATE: readonly string[] = [
2929 "test/apps-idle.test.ts",
3030 "test/body-limits.test.ts",
3131 "test/chaos.test.ts",
32 "test/inbox.test.ts",
33 "test/tui-inbox.test.ts",
3234 "test/fuzz-found.test.ts",
3335 "test/fuzz-parsers.test.ts",
3436 "test/attach-look.test.ts",
src/core/asks.ts added +82
@@ -0,0 +1,82 @@
1 /**
2 * The one inbox, in plain data: what each row waits for and from whom
3 * (`waitingFor`), and the work assigned to a person that belongs in it.
4 * The decisions themselves are classified in `web/studio/asks.ts`; this is
5 * the vocabulary and the assigned part, with no page and no request in it.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { listAssignedTo, type Issue } from "./issues.ts";
10 import {
11 canRead,
12 getReposByIds,
13 listReposVisibleTo,
14 type Repo,
15 } from "./repos.ts";
16 import { mutedRepos } from "./interactions.ts";
17 import { mayView } from "./sealed.ts";
18 import type { User } from "./users.ts";
19
20 /** Whose move it is: the owner's to act on now, or the crew's to finish first. */
21 export type Part = "yours" | "crew";
22
23 /** The words a row says it waits for, one per cause. */
24 export const WAITING_FOR = {
25 /** A green pull the viewer may land. */
26 ready: "ready to land",
27 /** An agent's green pull whose reviewer is out, or lapsed or absent. */
28 yourReview: "waiting for your review",
29 decision: "a decision",
30 assigned: "assigned to you",
31 conflicts: "conflicts with main",
32 } as const;
33
34 /** What a pull waits for while a reviewer of the crew has not yet answered. */
35 export const reviewOf = (reviewer: string): string =>
36 `waiting for ${reviewer}'s review`;
37
38 /** What an agent's pull waits for once a reviewer has asked for changes. */
39 export const changesOf = (reviewer: string): string =>
40 `changes requested by ${reviewer}`;
41
42 /**
outdated

Filter muted repositories here, so the page, the count, the API, MCP, the notifier and the terminal all see the same list. onYouRows can still report what it held back as silenced.

43 * Open issues and pulls assigned to the viewer, anywhere they can see, except
44 * in repositories they muted: every door (page, count, API, phone, terminal)
45 * shows this one list. `silenced` collects the muted repositories held back;
46 * `visibleRepos` spares a second visibility query when the caller has one.
47 */
48 export function assignedToYou(
49 db: Database,
50 user: User,
51 opts: { visibleRepos?: readonly Repo[]; silenced?: Map<string, Repo> } = {},
52 ): { repo: Repo; issue: Issue }[] {
53 const assigned = listAssignedTo(db, user.id, 20);
54 if (assigned.length === 0) return [];
55 const repos = getReposByIds(
56 db,
57 assigned.map((issue) => issue.repoId),
58 );
59 // `listAssignedTo` has no visibility filter of its own (an assignment can
60 // outlive the access that made it), so each repo needs a real `canRead`.
61 // `listReposVisibleTo` answers the common case with one query for the
62 // whole page; `canRead` only runs for the rare repo it did not reach.
63 const visible = new Set(
64 (opts.visibleRepos ?? listReposVisibleTo(db, user, { limit: 200 })).map(
65 (repo) => repo.id,
66 ),
67 );
68 const muted = mutedRepos(db, user.id);
69 const out: { repo: Repo; issue: Issue }[] = [];
70 for (const issue of assigned) {
71 const repo = repos.get(issue.repoId);
72 if (!repo) continue;
73 if (!visible.has(repo.id) && !canRead(db, repo, user)) continue;
74 if (!mayView(db, repo, issue, user)) continue;
75 if (muted.has(repo.id)) {
76 opts.silenced?.set(repo.id, repo);
77 continue;
78 }
79 out.push({ repo, issue });
80 }
81 return out;
82 }
src/crew/notify.ts +7 −1
@@ -30,7 +30,7 @@ import { getUserSetting, setUserSetting } from "../core/settings.ts";
3030 import { getUserById } from "../core/users.ts";
3131 import { landedLines } from "../core/watches.ts";
3232 import { err, ok, type Result } from "../kernel/result.ts";
33 import { askLinesFor } from "../web/studio/asks.ts";
33 import { askLinesFor, assignedLinesFor } from "../web/studio/asks.ts";
3434
3535 const KEY = "notify_url";
3636 export const MAX_URL = 200;
@@ -197,6 +197,12 @@ export function startNotifier(app: App, options: NotifyOptions): Notifier {
197197 // to itself.
198198 const asks: { line: string; items: readonly string[]; link?: string }[] = [
199199 ...askLinesFor(app.db, user).map((a) => ({ line: a.line, items: a.items })),
200 // The header counts assigned work, so the phone does too.
201 ...assignedLinesFor(app.db, user).map((a) => ({

Same bug here: the phone is told about assigned work in a repository the owner muted. Muting should silence it.

202 line: a.line,
203 items: [a.id],
204 link: a.link,
205 })),
200206 ...newAccountLines(app.db, user, now()),
201207 ...landedLines(app.db, user, now()),
202208 ...mailCeilingLines(app, user, now()),
src/crew/review.ts +32
@@ -286,6 +286,38 @@ export function waitsForPerson(
286286 : undefined;
287287 }
288288
289 /**
290 * The reviewer an agent's pull is waiting for, while its review is still
291 * the crew's to give: the crew has a reviewer, no verdict is on the head,
292 * the review has not lapsed, and nobody holds the pull. Undefined once a
293 * verdict lands (approval or changes requested), the review lapses, or
294 * there was never a reviewer — from then on the pull is a person's. Names
295 * the reviewer the pull was sent to, else the crew's first.
296 */
297 export function awaitedReviewer(
298 db: Database,
299 repoId: string,
300 pull: Pull,
301 now = new Date(),
302 known?: readonly Agent[],
303 ): Agent | undefined {
304 if (!pull.authorIsAgent || getHold(db, pull.id) !== undefined) return undefined;
305 const reviewers = known ?? reviewersOf(db, repoId);
306 if (reviewers.length === 0) return undefined;
307 const seen = reviewSummary(db, pull.id, pull.headOid);
308 if (seen.approvals > 0 || seen.changesRequested > 0) return undefined;
309 const history = reviewAttempts(db, pull);
310 if (history !== undefined && stageOf(history, now) === "lapsed")
311 return undefined;
312 const sent = db
313 .query<{ actor_id: string | null }, [string]>(
314 `SELECT actor_id FROM run WHERE issue_id = ?1 AND kind = 'agent' AND reason = 'review'
315 ORDER BY created_at DESC, id DESC LIMIT 1`,
316 )
317 .get(pull.id)?.actor_id;
318 return reviewers.find((r) => r.user.id === sent) ?? reviewers[0];
319 }
320
289321 /**
290322 * Move review along on this green head: send it to the right reviewer
291323 * when it is due (`reviewStage`), and say where it stands. `none` when
src/http/mcp.ts +1 −1
@@ -418,7 +418,7 @@ const TOOLS: readonly Tool[] = [
418418 {
419419 name: "asks",
420420 description:
421 "What waits on you, most consequential first: each row names the decision, its options and what happens if nobody acts, and why it ranks where it does (security, money, held-up work, then age). Rows of one kind in one app are collapsed with their item ids. Also the forge's own needs (for a site admin) and the last 7 days' asks raised, acted on, dismissed and gone by themselves.",
421 "What waits on you, most consequential first: each row names the decision, its options and what happens if nobody acts, and why it ranks where it does (security, money, held-up work, then age). Rows of one kind in one app are collapsed with their item ids. Each row carries `waitingFor` ('ready to land', 'a decision', 'waiting for your review') and `part`; the same answer lists `crew` (pulls waiting for a named reviewer's review, or conflicting with main: not yours yet), `assigned` ('assigned to you'), and `inbox`, all of them as one list. Also the forge's own needs (for a site admin) and the last 7 days' asks raised, acted on, dismissed and gone by themselves.",
422422 inputSchema: { type: "object", properties: {} },
423423 writes: false,
424424 run(ctx, user) {
src/tui/screens/dashboard.ts +70 −48
@@ -17,7 +17,11 @@
1717 import { forgeNeeds } from "../../actions/health.ts";
1818 import { mayView } from "../../core/sealed.ts";
1919 import { pinRepo, unpinRepo } from "../../actions/origins.ts";
20 import { listAssignedTo, type Issue } from "../../core/issues.ts";
20 import {
21 askLinesFor,
22 assignedLinesFor,
23 crewLinesFor,
24 } from "../../web/studio/asks.ts";
2125 import { listPins, pinnedRepoIds, type Pin } from "../../core/pins.ts";
2226 import { listOrgsForUser } from "../../core/orgs.ts";
2327 import {
@@ -39,10 +43,8 @@ import { card, emptyState } from "../ui/widgets.ts";
3943 import type { Session } from "../session.ts";
4044 import {
4145 Filter,
42 ISSUE_MARK,
4346 ListState,
4447 PIN_MARK,
45 PULL_MARK,
4648 confirmScreen,
4749 countsColumn,
4850 metaOf,
@@ -70,14 +72,20 @@ type PaneId = "repos" | "onyou" | "machine";
7072
7173 const TITLES: Readonly<Record<PaneId, string>> = {
7274 repos: "Repositories",
73 onyou: "On you",
75 onyou: "Inbox",
7476 machine: "On your machine",
7577 };
7678
77 /** An issue or a pull assigned to the viewer, with the repository it is in. */
79 /**
80 * One row of the inbox, the same list the web home shows: what is on the
81 * viewer (asks and assigned work, counted) and then the crew's part (not).
82 */
7883 interface OnYouItem {
79 readonly issue: Issue;
80 readonly repo: Repo;
84 readonly title: string;
85 readonly meta: string;
86 readonly waitingFor: string;
87 readonly counted: boolean;
88 readonly open: () => void;
8189 }
8290
8391 /** The `tab` order, whichever of these the frame had room for. */
@@ -122,26 +130,58 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
122130 };
123131
124132 /**
125 * What is assigned to the viewer, open, newest first. The rows come from
126 * one query and the repositories from one grouped read; `canRead` is the
127 * same filter every list applies, so an assignment in a repository this
128 * account has since lost cannot appear here.
133 * The inbox, from the data the web page is made from: asks, then assigned
134 * work, then the crew's part. The queries apply `canRead` and `mayView`
135 * themselves, so a repository this account has lost cannot appear here.
129136 */
130137 const assignedToMe = (): OnYouItem[] => {
131 if (f.user === undefined) return [];
132 const issues = listAssignedTo(f.db, f.user.id, 50);
133 const byId = getReposByIds(
134 f.db,
135 issues.map((issue) => issue.repoId),
138 const user = f.user;
139 if (user === undefined) return [];
140 const repoOf = (ids: readonly string[]) => getReposByIds(f.db, ids);
141 const visible = all;
142 const asks = askLinesFor(f.db, user, visible).map(
143 (a): OnYouItem => ({
144 title: a.line,
145 meta: a.waitingFor,
146 waitingFor: a.waitingFor,
147 counted: true,
148 open: () => openOnWeb(f, ctx, a.link, "What needs you"),
149 }),
136150 );
137 return issues.flatMap((issue) => {
138 const repo = byId.get(issue.repoId);
139 return repo !== undefined &&
140 canRead(f.db, repo, f.user) &&
141 mayView(f.db, repo, issue, f.user)
142 ? [{ issue, repo }]
143 : [];
144 });
151 const assigned = assignedLinesFor(f.db, user);

Same bug in the terminal's Inbox · N: it counts and lists muted repositories' assigned work, while the web page hides it. The two doors should show the same list.

152 const crew = crewLinesFor(f.db, user, visible);
153 const repos = repoOf([...assigned, ...crew].map((r) => r.repoId));
154 const pullOf = (r: { repoId: string; number: number }, kind: string) => () => {
155 const repo = repos.get(r.repoId);
156 if (repo === undefined) return;
157 const src = local(f, repo);
158 ctx.push(
159 kind === "pull"
160 ? pullScreen(f, ctx, src, r.number)
161 : issueScreen(f, ctx, src, r.number),
162 );
163 };
164 return [
165 ...asks,
166 ...assigned.map(
167 (r): OnYouItem => ({
168 title: r.line,
169 meta: r.waitingFor,
170 waitingFor: r.waitingFor,
171 counted: true,
172 open: pullOf(r, r.issueKind),
173 }),
174 ),
175 ...crew.map(
176 (r): OnYouItem => ({
177 title: `crew · ${r.line}`,
178 meta: r.waitingFor,
179 waitingFor: r.waitingFor,
180 counted: false,
181 open: pullOf(r, "pull"),
182 }),
183 ),
184 ];
145185 };
146186
147187 /** Yours with an empty filter; anything you can see once you type —
@@ -220,15 +260,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
220260 );
221261 };
222262
223 const openAssigned = (item: OnYouItem | undefined): void => {
224 if (item === undefined) return;
225 const src = local(f, item.repo);
226 ctx.push(
227 item.issue.kind === "pull"
228 ? pullScreen(f, ctx, src, item.issue.number)
229 : issueScreen(f, ctx, src, item.issue.number),
230 );
231 };
263 const openAssigned = (item: OnYouItem | undefined): void => item?.open();
232264
233265 /** `enter` on whatever the focused pane's cursor is on. */
234266 const openHere = (): void => {
@@ -367,15 +399,16 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
367399
368400 // ---- the panes ----
369401
370 /** The inbox: what is assigned to this account, across every repository. */
402 /** The inbox: what asks you or is assigned to you, then the crew's part (uncounted). */
371403 function drawOnYou(s: Surface, r: Rect, c: Tokens, set: IconSet): void {
372404 const on = focus === "onyou";
405 const count = onYou.filter((item) => item.counted).length;
373406 const inner = card(s, r, c, {
374 title: `${icon("person", set)} ${TITLES.onyou}`,
407 title: `${icon("person", set)} ${TITLES.onyou} · ${count}`,
375408 focused: on,
376409 });
377410 if (onYou.length === 0) {
378 note(s, inner, c, ["Nothing is assigned to you."]);
411 note(s, inner, c, ["Nothing is waiting on you."]);
379412 return;
380413 }
381414 drawList(
@@ -383,18 +416,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
383416 inner,
384417 c,
385418 at("onyou"),
386 onYou.map((item): ListRow => {
387 const mark =
388 set === "nerd"
389 ? icon(item.issue.kind === "pull" ? "pull" : "issue", set)
390 : item.issue.kind === "pull"
391 ? PULL_MARK
392 : ISSUE_MARK;
393 return {
394 title: `${mark} #${item.issue.number} ${item.issue.title}`,
395 meta: `${item.repo.ownerName}/${item.repo.name}`,
396 };
397 }),
419 onYou.map((item): ListRow => ({ title: item.title, meta: item.meta })),
398420 on,
399421 );
400422 hitList(ctx, inner, at("onyou"), onYou.length, {
src/web/client.ts +3
@@ -1881,7 +1881,10 @@ export const liveRegionsJs = /* js */ `
18811881 if (same(mine.innerHTML, theirs.innerHTML)) return;
18821882 // A disclosure the reader opened stays open across the swap.
18831883 var opened = Array.prototype.map.call(mine.querySelectorAll('details[id][open]'), function (d) { return d.id; });
1884 // So do the boxes ticked for a bulk step.
1885 var ticked = Array.prototype.map.call(mine.querySelectorAll('input.ask-pick:checked'), function (c) { return c.value; });
18841886 mine.innerHTML = theirs.innerHTML;
1887 if (ticked.length) Array.prototype.forEach.call(mine.querySelectorAll('input.ask-pick'), function (c) { if (ticked.indexOf(c.value) >= 0) c.checked = true; });
18851888 opened.forEach(function (i) { var d = document.getElementById(i); if (d) d.open = true; });
18861889 Array.prototype.forEach.call(theirs.attributes, function (a) { if (a.name !== 'id') mine.setAttribute(a.name, a.value); });
18871890 mine.dispatchEvent(new CustomEvent('forge:swapped', { bubbles: true }));
src/web/layout.ts +2 −2
@@ -160,7 +160,7 @@ export function asksLink(ctx: Ctx): Html {
160160 data-size="sm"
161161 href="/#needs-you"
162162 title="${count === 0 ? "All fine" : `${count} need you`}"
163 >Asks${count === 0 ? null : pill(count, "accent")}</a
163 >Inbox${count === 0 ? null : pill(count, "accent")}</a
164164 >`;
165165 }
166166
@@ -280,7 +280,7 @@ const STATIC_PALETTE: PaletteItem[] = [
280280 { t: "Apps", h: "/apps", c: "Go to" },
281281 { t: "Explore", h: "/explore", c: "Go to" },
282282 { t: "Map", h: "/map", c: "Go to" },
283 { t: "Asks you", h: "/#needs-you", c: "Go to" },
283 { t: "Inbox", h: "/#needs-you", c: "Go to" },
284284 { t: "What you asked for", h: "/asked", c: "Go to" },
285285 { t: "Front page", h: "/front", c: "Go to" },
286286 { t: "New app", h: "/apps/new", c: "Create" },
src/web/pages/site.ts +23 −79
@@ -8,20 +8,18 @@
88 * typed still in it. A dead end that loses input is a bug, not a message.
99 */
1010
11 import { mayView } from "../../core/sealed.ts";
11 import { assignedToYou, WAITING_FOR } from "../../core/asks.ts";
1212 import { signOutHere } from "../../actions/signins.ts";
1313 import { clientAddress } from "../../http/peer.ts";
1414 import { verifyEmail } from "../../actions/verify.ts";
1515 import { STRANGER_MAX } from "../../http/limits.ts";
1616 import { createRepo } from "../../actions/repos.ts";
1717 import { signUp } from "../../actions/users.ts";
18 import { listAssignedTo, type Issue } from "../../core/issues.ts";
18 import { type Issue } from "../../core/issues.ts";
1919 import { accessAllows, listOrgsForUser, orgAccess } from "../../core/orgs.ts";
2020 import { listPins } from "../../core/pins.ts";
2121 import {
22 canRead,
2322 getReposByIds,
24 listReposVisibleTo,
2523 type Repo,
2624 } from "../../core/repos.ts";
2725 import { createSession } from "../../core/sessions.ts";
@@ -29,9 +27,7 @@ import { hasAnyUser, verifyPassword, type User } from "../../core/users.ts";
2927 import { isThemeName } from "../../design/themes.ts";
3028 import { cookieValue, crossOrigin, type Ctx } from "../../http/context.ts";
3129 import { studioDoor, studioHome } from "../studio/home.ts";
32 import { homeTop, onYouBulk } from "../studio/asks_page.ts";
33 import { latestUndoable } from "../../actions/asks_bulk.ts";
34 import { mutedRepos } from "../../core/interactions.ts";
30 import { homeTop } from "../studio/asks_page.ts";
3531 import { edgeLoginUrl } from "../../http/edge.ts";
3632 import { sshCommand } from "../../ssh/command.ts";
3733 import { hostOf, pageHead, signInFirst } from "../chrome.ts";
@@ -165,96 +161,44 @@ export function downloadsCard(ctx: Ctx, user: User): Html {
165161 const threadPath = (repo: Repo, issue: Issue): string =>
166162 `/${repo.ownerName}/${repo.name}/${issue.kind === "pull" ? "pulls" : "issues"}/${issue.number}`;
167163
168 /** Open issues and pulls assigned to the viewer, anywhere they can see. */
169 export function onYouCard(ctx: Ctx, user: User): Html | undefined {
170 const db = ctx.app.db;
171 const assigned = listAssignedTo(db, user.id, 20);
172 if (assigned.length === 0) return undefined;
173 const repos = getReposByIds(
174 db,
175 assigned.map((issue) => issue.repoId),
176 );
177 // `listAssignedTo` has no visibility filter of its own (an assignment can
178 // outlive the access that made it), so each repo needs a real `canRead`.
179 // Checking it straight would cost one query per row for any repo the
180 // viewer does not own outright — `canRead` resolves org ownership from
181 // the database. `listReposVisibleTo` answers the common case with one
182 // query for the whole page; `canRead` only runs for the rare repo it
183 // did not reach (its own cap), so the cost stays flat as rows grow.
184 const visible = new Set(
185 listReposVisibleTo(db, user, { limit: 200 }).map((repo) => repo.id),
186 );
187 const muted = mutedRepos(db, user.id);
188 const shown: { issue: Issue; repo: Repo }[] = [];
189 // Muted repositories that hold work assigned to the viewer: said, never silent.
164 /**
165 * What is assigned to the viewer, as the inbox's rows (`assignedToYou`). With
166 * `boxes` each row carries a box for the asks' bulk form. Muted repositories
167 * hold their work back from the rows and come back as `silenced`: said, never
168 * silent.
169 */
170 export function onYouRows(
171 ctx: Ctx,
172 user: User,
173 boxes = false,
174 ): { rows: Html[]; shown: { issue: Issue; repo: Repo }[]; silenced: Repo[] } {
190175 const silenced = new Map<string, Repo>();
191 for (const issue of assigned) {
192 const repo = repos.get(issue.repoId);
193 if (!repo) continue;
194 if (!visible.has(repo.id) && !canRead(db, repo, user)) continue;
195 if (!mayView(db, repo, issue, user)) continue;
196 if (muted.has(repo.id)) {
197 silenced.set(repo.id, repo);
198 continue;
199 }
200 shown.push({ issue, repo });
201 }
202 // Two or more can be given one move: a box each, and one form for the set.
203 const bulk = shown.length >= 2;
204 const rows = shown.map(({ issue, repo }) =>
176 const shown = assignedToYou(ctx.app.db, user, { silenced });
177 const rows = shown.map(({ repo, issue }) =>
205178 row({
206 ...(bulk ? {} : { href: threadPath(repo, issue), nav: true as const }),
179 ...(boxes ? {} : { href: threadPath(repo, issue), nav: true as const }),
207180 state: "open",
208 lead: bulk
181 lead: boxes
209182 ? html`<input
210183 type="checkbox"
211184 class="ask-pick"
212185 name="item"
213186 value="issue:${issue.id}"
214 form="onyou-bulk"
187 form="asks-bulk"
215188 data-repo="${repo.id}"
216189 data-kind="${issue.kind}"
217190 aria-label="Select ${issue.title}"
218191 />`
219192 : icon(issue.kind === "pull" ? "pull" : "issue"),
220 title: bulk
193 title: boxes
221194 ? html`<a href="${threadPath(repo, issue)}">${issue.title}</a>`
222195 : issue.title,
223196 titleAttr: issue.title,
224 meta: html`${repo.ownerName}/${repo.name} #${issue.number} · updated
225 ${time(issue.updatedAt)}`,
197 meta: html`${WAITING_FOR.assigned} · ${repo.ownerName}/${repo.name}
198 #${issue.number} · updated ${time(issue.updatedAt)}`,
226199 }),
227200 );
228 if (rows.length === 0 && silenced.size === 0) return undefined;
229 const last = latestUndoable(ctx.app, user);
230 const byKind = [...new Set(shown.map((s) => s.issue.kind))].map((k) => ({
231 id: k,
232 label: k === "pull" ? "Pulls" : "Issues",
233 }));
234 const byRepo = [...new Map(shown.map((s) => [s.repo.id, s.repo])).values()].map(
235 (r) => ({ id: r.id, label: `${r.ownerName}/${r.name}` }),
236 );
237 return listCard(rows, {
238 head: html`${icon("user")}
239 <h2>On you</h2>`,
240 ...(bulk || last !== undefined || silenced.size > 0
241 ? {
242 foot: onYouBulk(
243 byKind,
244 byRepo,
245 last === undefined
246 ? undefined
247 : {
248 id: last.id,
249 verb: last.verb,
250 done: last.rows.filter((r) => r.outcome === "ok").length,
251 },
252 bulk,
253 [...silenced.values()].map((r) => ({ id: r.id, label: `${r.ownerName}/${r.name}` })),
254 ),
255 }
256 : {}),
257 });
201 return { rows, shown, silenced: [...silenced.values()] };
258202 }
259203
260204 export function orgsCard(ctx: Ctx, user: User): Html {
src/web/studio/asks.ts +168 −17
@@ -9,7 +9,7 @@
99
1010 import type { Database } from "bun:sqlite";
1111 import { previewEnv } from "../../apps/data.ts";
12 import { crewForRepos } from "../../core/agents.ts";
12 import { crewForRepos, type Agent } from "../../core/agents.ts";
1313 import { appsRuntime } from "../../apps/runtime.ts";
1414 import { appsForRepos, getAppByRepo, listApps } from "../../core/apps.ts";
1515 import { latestDecision, stopStands } from "../../core/decisions.ts";
@@ -33,7 +33,7 @@ import {
3333 ownerFactRepoIds,
3434 type Repo,
3535 } from "../../core/repos.ts";
36 import { listReviews } from "../../core/reviews.ts";
36 import { latestReviewByAuthor, listReviews } from "../../core/reviews.ts";
3737 import {
3838 activeRunFor,
3939 automaticRunsSince,
@@ -48,7 +48,8 @@ import {
4848 import { breakerParked, WAITING_NOTES } from "../../crew/breaker.ts";
4949 import { CHECK_FAILED_LIMIT } from "../../crew/dispatch.ts";
5050 import { isStalePull, mergesAgainSince } from "../../crew/stale_asks.ts";
51 import { waitsForPerson, type ReviewWait } from "../../crew/review.ts";
51 import { awaitedReviewer, reviewersOf, waitsForPerson, type ReviewWait } from "../../crew/review.ts";
52 import { assignedToYou, changesOf, reviewOf, WAITING_FOR, type Part } from "../../core/asks.ts";
5253 import type { Ctx } from "../../http/context.ts";
5354 import { vitals } from "../../kernel/vitals.ts";
5455 import { repoBase } from "../chrome.ts";
@@ -110,6 +111,8 @@ export interface Decision {
110111 * direction issue the planner declined. */
111112 readonly issue?: Issue | undefined;
112113 readonly who: string;
114 /** What it waits for, from whom: "ready to land", "a decision" (`WAITING_FOR`). */
115 readonly waitingFor: string;
113116 /** Three sentences at most: what, why, what happens next. */
114117 readonly says: string;
115118 /** The same in one clause, for a row. */
@@ -214,6 +217,8 @@ interface AskCandidate {
214217 * differently for a person's own change than for the crew's (below).
215218 * Absent for "paused", which names no author at all. */
216219 readonly authorIsAgent?: boolean;
220 /** For "look": the reviewer who asked for changes on this head, if one did. */
221 readonly changesBy?: string;
217222 /** For "review": why the agent's change waits for a person, and since when. */
218223 readonly reviewWait?: ReviewWait;
219224 /** For "stopped": how many automatic tries, and whether the decider itself stopped it. */
@@ -223,6 +228,19 @@ interface AskCandidate {
223228 readonly decline?: { readonly runId: string; readonly words: string };
224229 }
225230
231 /**
232 * A pull that is the crew's to finish before it is the viewer's: a
233 * reviewer of the crew has not answered, or it no longer merges as it stands.
234 */
235 export interface CrewWait {
236 readonly id: string;
237 readonly repo: Repo;
238 readonly pull: Pull;
239 readonly waitingFor: string;
240 /** Since when: the head's check, or the last time it was found conflicted. */
241 readonly since: string;
242 }
243
226244 /**
227245 * Open pulls the viewer may land, sorted into what asks them: stopped (red
228246 * past the crew's own limit since a person last spoke — the crew's own
@@ -238,6 +256,7 @@ function askCandidatesFor(
238256 db: Database,
239257 user: User | undefined,
240258 allRepos: readonly Repo[],
259 waits?: CrewWait[],
241260 ): AskCandidate[] {
242261 const out: AskCandidate[] = [];
243262 if (!user) return out;
@@ -259,6 +278,12 @@ function askCandidatesFor(
259278 db,
260279 pulls.map((p) => p.id),
261280 );
281 const reviewers = new Map<string, Agent[]>();
282 const reviewersFor = (repoId: string): Agent[] => {
283 let list = reviewers.get(repoId);
284 if (list === undefined) reviewers.set(repoId, (list = reviewersOf(db, repoId)));
285 return list;
286 };
262287 for (const issue of pulls) {
263288 const repo = byId.get(issue.repoId)!;
264289 const pull = joined.get(issue.id);
@@ -268,6 +293,39 @@ function askCandidatesFor(
268293 if (held.get(issue.id)?.heldBy === user.id) continue;
269294 const check = checks.get(issue.id);
270295 const who = issue.authorName;
296 // A green pull that no longer merges as it stands cannot be landed:
297 // bringing it up to date is the crew's work, not a person's decision.
298 if (
299 check?.state === "ok" &&
300 issue.authorIsAgent &&
301 isStalePull(db, pull.id, pull.headOid)
302 ) {
303 waits?.push({
304 id: `conflicts:${pull.id}`,
305 repo,
306 pull,
307 waitingFor: WAITING_FOR.conflicts,
308 since: check.createdAt,
309 });
310 continue;
311 }
312 // An agent's green pull whose reviewer has not answered is the
313 // reviewer's, not the owner's: it reaches the owner when the review
314 // lands, or lapses (`waitsForPerson`).
315 const reviewer =
316 check?.state === "ok" && reviewersFor(repo.id).length > 0
317 ? awaitedReviewer(db, repo.id, pull, new Date(), reviewersFor(repo.id))
318 : undefined;
319 if (reviewer !== undefined) {
320 waits?.push({
321 id: `review-by:${pull.id}`,
322 repo,
323 pull,
324 waitingFor: reviewOf(reviewer.user.username),
325 since: check!.createdAt,
326 });
327 continue;
328 }
271329 // The crew is on it: that is working, not a question for a person.
272330 if (activeRunFor(db, "agent", issue.id) !== undefined) continue;
273331 if (check?.state === "failed") {
@@ -298,8 +356,7 @@ function askCandidatesFor(
298356 } else if (
299357 check?.state === "ok" &&
300358 repo.autonomy !== "autonomous" &&
301 // A green pull that no longer merges as it stands cannot be shipped:
302 // bringing it up to date is work, not a person's decision.
359 // A person's stale pull is not asked about, as it was before.
303360 !isStalePull(db, pull.id, pull.headOid)
304361 ) {
305362 // Autonomous repositories look at their own green pulls: the decider,
@@ -316,11 +373,11 @@ function askCandidatesFor(
316373 pull,
317374 who,
318375 authorIsAgent: issue.authorIsAgent,
376 ...changesOn(db, pull),
319377 });
320378 } else if (
321379 check?.state === "ok" &&
322 repo.autonomy === "autonomous" &&
323 !isStalePull(db, pull.id, pull.headOid)
380 repo.autonomy === "autonomous"
324381 ) {
325382 // An autonomous repository lands its own green pulls once reviewed;
326383 // an agent's change with no reviewer, or whose review lapsed, waits
@@ -536,20 +593,33 @@ function scoredFor(
536593 user: User | undefined,
537594 repos: readonly Repo[],
538595 now = Date.now(),
596 waits?: CrewWait[],
539597 ): Scored[] {
540 const asks = askCandidatesFor(db, user, repos);
598 const asks = askCandidatesFor(db, user, repos, waits);
541599 const scores = consequencesOf(db, asks, now);
542600 return asks.map((a) => ({ ...a, consequence: scores.get(a.id)! }));
543601 }
544602
603 /** The pulls the crew finishes before they reach the viewer: the other part of the inbox. */
604 export function crewWaitsFor(
605 db: Database,
606 user: User | undefined,
607 repos: readonly Repo[],
608 ): CrewWait[] {
609 const crew: CrewWait[] = [];
610 askCandidatesFor(db, user, repos, crew);
611 return crew;
612 }
613
545614 /** What asks the viewer now: candidates, less what they set aside. */
546615 function waitingOn(
547616 db: Database,
548617 user: User | undefined,
549618 repos: readonly Repo[],
619 waits?: CrewWait[],
550620 ): Scored[] {
551621 if (!user) return [];
552 return notDismissed(db, user, scoredFor(db, user, repos));
622 return notDismissed(db, user, scoredFor(db, user, repos, undefined, waits));
553623 }
554624
555625 /** How an ask that is no longer asked ended, when nobody dismissed it. */
@@ -646,6 +716,14 @@ function lineOf(c: AskCandidate): string {
646716 : `"${title}" is green, waiting for your look`;
647717 }
648718
719 /** What an ask of this kind waits for, in the inbox's one vocabulary. */
720 export const waitingForKind = (kind: DecisionKind): string =>
721 kind === "look"
722 ? WAITING_FOR.ready
723 : kind === "review"
724 ? WAITING_FOR.yourReview
725 : WAITING_FOR.decision;
726
649727 /** Why an agent's change waits for a person's review, in a clause. */
650728 const reviewWhy = (wait: ReviewWait | undefined): string =>
651729 wait?.why === "rounds"
@@ -682,6 +760,7 @@ export const askAnchor = (id: string): string => id.replace(/[^a-z0-9-]/g, "-");
682760 export function askLinesFor(
683761 db: Database,
684762 user: User,
763 visible?: readonly Repo[],
685764 ): {
686765 id: string;
687766 line: string;
@@ -696,10 +775,15 @@ export function askLinesFor(
696775 words: AskWords;
697776 /** Why it ranks where it does; rows come most consequential first. */
698777 consequence: Consequence;
778 /** What it waits for, from whom (`WAITING_FOR`). */
779 waitingFor: string;
780 /** Whose move: always the viewer's here; the crew's part is `crewLinesFor`. */
781 part: Part;
699782 }[] {
700 const repos = listReposVisibleTo(db, user, { limit: 200 });
783 const repos = visible ?? listReposVisibleTo(db, user, { limit: 200 });
701784 return askRows(waitingOn(db, user, repos)).map((row) => {
702785 const base = `/${row.repo.ownerName}/${row.repo.name}`;
786 const changesBy = row.items.length === 1 ? row.items[0]!.changesBy : undefined;
703787 const about = {
704788 id: row.id,
705789 kind: row.kind,
@@ -707,6 +791,11 @@ export function askLinesFor(
707791 items: row.items.map((c) => c.id),
708792 words: ASK_WORDS[row.kind],
709793 consequence: row.consequence,
794 waitingFor:
795 row.kind === "look" && changesBy !== undefined
796 ? changesOf(changesBy)
797 : waitingForKind(row.kind),
798 part: "yours" as Part,
710799 };
711800 const only = row.items.length === 1 ? row.items[0]! : undefined;
712801 if (only === undefined)
@@ -734,6 +823,48 @@ export function askLinesFor(
734823 });
735824 }
736825
826 /** Who asked for changes on a pull's current head, as a candidate's field. */
827 function changesOn(db: Database, pull: Pull): { changesBy?: string } {
828 if (!pull.authorIsAgent) return {};
829 for (const review of latestReviewByAuthor(db, pull.id).values()) {
830 if (review.state !== "changes_requested" || review.commitOid !== pull.headOid) continue;
831 const name = getUserById(db, review.authorId)?.username;
832 if (name !== undefined) return { changesBy: name };
833 }
834 return {};
835 }
836
837 /** The crew's part of the inbox as data: pulls waiting for a reviewer, or for a rebase. */
838 export function crewLinesFor(db: Database, user: User, visible?: readonly Repo[]) {
839 const repos = visible ?? listReposVisibleTo(db, user, { limit: 200 });
840 return crewWaitsFor(db, user, repos).map((w) => ({
841 id: w.id,
842 part: "crew" as Part,
843 kind: "crew" as const,
844 waitingFor: w.waitingFor,
845 line: `${w.repo.name}: "${w.pull.title}" — ${w.waitingFor}`,
846 link: `/${w.repo.ownerName}/${w.repo.name}/changes/${w.pull.number}`,
847 number: w.pull.number,
848 repoId: w.repo.id,
849 since: w.since,
850 }));
851 }
852
853 /** The assigned part of the inbox as data. */
854 export function assignedLinesFor(db: Database, user: User) {
855 return assignedToYou(db, user).map(({ repo, issue }) => ({
856 id: `assigned:${issue.id}`,
857 part: "yours" as Part,
858 kind: "assigned" as const,
859 issueKind: issue.kind,
860 waitingFor: WAITING_FOR.assigned,
861 line: `${repo.name}: "${issue.title}" is assigned to you`,
862 link: `/${repo.ownerName}/${repo.name}/${issue.kind === "pull" ? "pulls" : "issues"}/${issue.number}`,
863 number: issue.number,
864 repoId: repo.id,
865 }));
866 }
867
737868 /**
738869 * The decisions waiting on the viewer, worded and pictured. A change's own
739870 * page passes `evenDismissed`: setting an ask aside quiets the lists, never
@@ -742,12 +873,12 @@ export function askLinesFor(
742873 export function decisionsFor(
743874 ctx: Ctx,
744875 allRepos: readonly Repo[],
745 options: { evenDismissed?: boolean } = {},
876 options: { evenDismissed?: boolean; crew?: CrewWait[] } = {},
746877 ): Decision[] {
747878 const db = ctx.app.db;
748879 const candidates = options.evenDismissed
749 ? scoredFor(db, ctx.auth.user, allRepos)
750 : waitingOn(db, ctx.auth.user, allRepos);
880 ? scoredFor(db, ctx.auth.user, allRepos, undefined, options.crew)
881 : waitingOn(db, ctx.auth.user, allRepos, options.crew);
751882 // The pictures, in one read: a green pull's row leads with its preview.
752883 const repoIds = [...new Set(candidates.map((c) => c.repo.id))];
753884 const records = appsForRepos(db, repoIds);
@@ -769,7 +900,7 @@ export function decisionsFor(
769900 look && lookUrl(repoBase(repo), look)
770901 );
771902 };
772 const worded = (c: Scored): Omit<Decision, "consequence"> => {
903 const worded = (c: Scored): Omit<Decision, "consequence" | "waitingFor"> => {
773904 if (c.kind === "parked" && c.issue)
774905 return {
775906 kind: "parked",
@@ -846,7 +977,14 @@ export function decisionsFor(
846977 short: `at its $${dollars(c.repo.autonomyCeilingUsd)} ceiling until 00:00 UTC`,
847978 };
848979 };
849 return candidates.map((c) => ({ ...worded(c), consequence: c.consequence }));
980 return candidates.map((c) => ({
981 ...worded(c),
982 waitingFor:
983 c.kind === "look" && c.changesBy !== undefined
984 ? changesOf(c.changesBy)
985 : waitingForKind(c.kind),
986 consequence: c.consequence,
987 }));
850988 }
851989 /** The id of the form a row's own button submits (see `decisionForm`). */
852990 const askFormId = (d: Decision): string => `ask-${d.id}`;
@@ -969,7 +1107,8 @@ export function askCountFor(ctx: Ctx, user: User | undefined): number {
9691107 const repos = listReposVisibleTo(ctx.app.db, user, { limit: 200 });
9701108 return (
9711109 askRows(waitingOn(ctx.app.db, user, repos)).length +
972 forgeNeedsFor(ctx, user).length
1110 forgeNeedsFor(ctx, user).length +
1111 assignedToYou(ctx.app.db, user, { visibleRepos: repos }).length
outdated

This counts assigned work in muted repositories, which the page hides (onYouRows filters mutedRepos). The header's count then disagrees with the list. Apply the mute filter in assignedToYou, or in a shared helper.

9731112 );
9741113 }
9751114
@@ -988,8 +1127,20 @@ export function askSentence(count: number): string {
9881127 */
9891128 export function asksAnswer(ctx: Ctx, user: User) {
9901129 const since = new Date(Date.now() - 7 * 86_400_000).toISOString();
1130 const rows = askLinesFor(ctx.app.db, user);
1131 const crew = crewLinesFor(ctx.app.db, user);
1132 const assigned = assignedLinesFor(ctx.app.db, user);
9911133 return {
992 rows: askLinesFor(ctx.app.db, user),
1134 rows,
1135 crew,
1136 assigned,
1137 // The one list: the viewer's part first, then the crew's, each row
1138 // saying what it waits for and from whom.
1139 inbox: [
1140 ...rows.map((r) => ({ part: r.part, waitingFor: r.waitingFor, line: r.line, link: r.link, kind: r.kind })),
1141 ...assigned.map((r) => ({ part: r.part, waitingFor: r.waitingFor, line: r.line, link: r.link, kind: r.kind })),
1142 ...crew.map((r) => ({ part: r.part, waitingFor: r.waitingFor, line: r.line, link: r.link, kind: r.kind })),
1143 ],
9931144 forge: forgeNeedsFor(ctx, user),
9941145 measure: { days: 7, ...askMeasure(ctx.app.db, user.id, since) },
9951146 };
src/web/studio/asks_page.ts +64 −31
@@ -9,6 +9,7 @@
99
1010 import {
1111 applyAsksBulk,
12 latestUndoable,
1213 BULK_MAX,
1314 ownAsksOperation,
1415 undoAsksBulk,
@@ -22,13 +23,16 @@ import type { User } from "../../core/users.ts";
2223 import { onYouAnswer, studioHome } from "./home.ts";
2324 import { notFoundPage, repoBase, signInFirst } from "../chrome.ts";
2425 import { field, readForm } from "../form.ts";
26 import { assignedToYou, WAITING_FOR } from "../../core/asks.ts";
2527 import { listReposVisibleTo } from "../../core/repos.ts";
28 import { onYouRows } from "../pages/site.ts";
2629 import { html, type Html } from "../html.ts";
2730 import { redirect } from "../layout.ts";
2831 import { btn, card, icon, row } from "../ui.ts";
2932 import {
3033 askAnchor,
3134 askRows,
35 type CrewWait,
3236 askSentence,
3337 ASK_WORDS,
3438 ROW_PLURAL,
@@ -192,7 +196,7 @@ function decisionCard(ctx: Ctx, d: Decision, picked: ReadonlySet<string>): Html
192196 head: html`${pick(d, picked)}
193197 <h2>${title}</h2>
194198 <span class="ask-meta muted small"
195 ><b class="ask-kind">${KIND_LABEL[d.kind]}</b>${d.repo.ownerName}/${d.repo.name}</span
199 ><b class="ask-kind">${KIND_LABEL[d.kind]}</b>${d.repo.ownerName}/${d.repo.name} · ${d.waitingFor}</span
196200 >`,
197201 },
198202 );
@@ -301,17 +305,23 @@ export function needsYouSection(
301305 top?: AsksTop,
302306 ): { body: Html; scriptJs: string } {
303307 const picked = top?.picked ?? new Set<string>();
308 // One pass over the open pulls yields both the asks and the crew's waits.
309 const crew: CrewWait[] = [];
304310 const decisions = decisionsFor(
305311 ctx,
306312 listReposVisibleTo(ctx.app.db, user, { limit: 200 }),
313 { crew },
307314 );
308315 const needs = forgeNeedsFor(ctx, user);
309316 const rows = askRows(decisions);
310 const count = rows.length + needs.length;
311 if (count === 0 && top === undefined)
317 const pickableDecisions = decisions.filter((d) => BULK_KINDS.has(d.kind));
318 const own = onYouRows(ctx, user, pickableDecisions.length + assignedToYou(ctx.app.db, user).length >= 2);
319 const assigned = own.rows;
320 const count = rows.length + needs.length + assigned.length;
321 if (count === 0 && crew.length === 0 && own.silenced.length === 0 && top === undefined)
312322 return {
313323 body: html`<h2 id="asks-sentence" class="sr-only">${askSentence(0)}</h2>`,
314 scriptJs: "",
324 scriptJs: SELECT_JS,
315325 };
316326 // The forge's own health first, then the few asks that matter most;
317327 // the rest are one tap away, in the same order. A phone shows fewer
@@ -321,7 +331,8 @@ export function needsYouSection(
321331 const first = rows.slice(0, ASKS_SHOWN_PHONE);
322332 const middle = rows.slice(ASKS_SHOWN_PHONE, ASKS_SHOWN);
323333 const rest = rows.slice(ASKS_SHOWN);
324 const pickable = decisions.filter((d) => BULK_KINDS.has(d.kind)).length;
334 const pickable = pickableDecisions.length + own.shown.length;
335 const last = latestUndoable(ctx.app, user);
325336 const more = (id: string, n: number, inner: Html): Html =>
326337 html`<details id="${id}">
327338 <summary>${n} more</summary>
@@ -349,8 +360,8 @@ export function needsYouSection(
349360 : html`<form id="asks-bulk" method="post" action="/asks/bulk" class="bar">
350361 ${pickControls(
351362 "asks-bulk",
352 [...new Map(decisions.filter((d) => BULK_KINDS.has(d.kind)).map((d) => [d.kind, { id: d.kind, label: ASK_KIND_WORDS[d.kind] ?? d.kind }])).values()],
353 [...new Map(decisions.filter((d) => BULK_KINDS.has(d.kind)).map((d) => [d.repo.id, { id: d.repo.id, label: `${d.repo.ownerName}/${d.repo.name}` }])).values()],
363 uniq([...pickableDecisions.map((d) => ({ id: d.kind, label: ASK_KIND_WORDS[d.kind] ?? d.kind })), ...own.shown.map((s) => ({ id: s.issue.kind, label: s.issue.kind === "pull" ? "Pulls" : "Issues" }))]),
364 uniq([...pickableDecisions.map((d) => d.repo), ...own.shown.map((s) => s.repo)].map((r) => ({ id: r.id, label: `${r.ownerName}/${r.name}` }))),
354365 )}
355366 <select name="action" class="input" aria-label="What to do with the selected asks">
356367 ${ASK_VERBS.map(
@@ -361,11 +372,46 @@ export function needsYouSection(
361372 ${reasonInput(top?.reason)} ${btn("Preview", { size: "sm" })}
362373 <span class="muted small">on the selected asks</span>
363374 </form>`}
364 ${decisions.map((d) => decisionForm(d))}
375 ${assigned.length === 0
376 ? null
377 : card(html`<ul class="list">${assigned}</ul>`, {
378 id: "assigned",
379 pad: false,
380 head: html`${icon("user")}
381 <h2>${WAITING_FOR.assigned}</h2>`,
382 })}
383 ${inboxNotes(
384 last === undefined
385 ? undefined
386 : { id: last.id, verb: last.verb, done: last.rows.filter((r) => r.outcome === "ok").length },
387 own.silenced.map((r) => ({ id: r.id, label: `${r.ownerName}/${r.name}` })),
388 )}
389 ${crewPart(crew)} ${decisions.map((d) => decisionForm(d))}
365390 </section>`;
366391 return { body, scriptJs: SELECT_JS };
367392 }
368393
394 /** The crew's part: what waits for a reviewer or a rebase before it reaches you, never counted. */
395 const crewPart = (crew: readonly CrewWait[]): Html | null =>
396 crew.length === 0
397 ? null
398 : html`<details id="crew-part" class="crew-part">
399 <summary>The crew's · ${crew.length}</summary>
400 <ul class="list">
401 ${crew.map((w) =>
402 row({
403 href: changeHref(repoBase(w.repo), w.pull.number),
404 nav: true,
405 lead: icon("pull"),
406 title: w.pull.title,
407 titleAttr: w.pull.title,
408 meta: html`${w.waitingFor} · ${w.repo.ownerName}/${w.repo.name}
409 #${w.pull.number}`,
410 }),
411 )}
412 </ul>
413 </details>`;
414
369415 /** The home with a bulk step's preview or receipt on top of what needs
370416 * you — where every bulk answer lands. */
371417 async function asksScreen(ctx: Ctx, top: AsksTop): Promise<Response> {
@@ -385,11 +431,10 @@ const VERB_WORDS: Readonly<Record<string, string>> = {
385431 replan: "Hand back to the planner",
386432 };
387433
388 /** What the asks below can be given in one move; mute is the On you card's. */
389 const ASK_VERBS = ["decline", "ship", "close", "replan"] as const;
434 /** What the asks and the work assigned to you can be given in one move. */
435 const ASK_VERBS = ["decline", "ship", "close", "replan", "mute"] as const;
390436
391 /** What the On you card's set can be given. */
392 const CARD_VERBS = ["close", "mute", "ship"] as const;
437 const uniq = <T extends { id: string }>(xs: readonly T[]): T[] => [...new Map(xs.map((x) => [x.id, x])).values()];
393438
394439 /** One reason, written on each pull or issue closed. */
395440 const reasonInput = (value = ""): Html =>
@@ -429,16 +474,14 @@ export function pickControls(
429474 }
430475
431476 /**
432 * The On you card's one form: a verb for the set, one reason, one request.
433 * `receipt` is the day's undo link for the last set acted on.
477 * The day's undo link for the last set acted on, and the repositories muted
478 * out of the inbox with the way back: said, never silent.
434479 */
435 export function onYouBulk(
436 kinds: readonly { id: string; label: string }[],
437 repos: readonly { id: string; label: string }[],
480 export function inboxNotes(
438481 receipt: { id: string; verb: string; done: number } | undefined,
439 withForm = true,
440 muted: readonly { id: string; label: string }[] = [],
441 ): Html {
482 muted: readonly { id: string; label: string }[],
483 ): Html | null {
484 if (receipt === undefined && muted.length === 0) return null;
442485 return html`${muted.length === 0
443486 ? null
444487 : html`<form class="bar" method="post" action="/asks/listen">
@@ -454,17 +497,7 @@ export function onYouBulk(
454497 <span class="small">${VERB_WORDS[receipt.verb] ?? receipt.verb}: ${receipt.done} done</span>
455498 ${btn("Undo", { size: "sm" })}
456499 <span class="muted small">kept for a day</span>
457 </form>`}
458 ${withForm
459 ? html`<form id="onyou-bulk" method="post" action="/asks/bulk" class="bar" data-bulk>
460 <input type="hidden" name="apply" value="1" />
461 ${pickControls("onyou-bulk", kinds, repos)}
462 <select name="action" class="input" aria-label="What to do with the selected">
463 ${CARD_VERBS.map((v) => html`<option value="${v}">${VERB_WORDS[v]}</option>`)}
464 </select>
465 ${reasonInput()} ${btn("Do it", { size: "sm" })}
466 </form>`
467 : null}`;
500 </form>`}`;
468501 }
469502
470503 const shown = (v: FleetValue): string =>
src/web/studio/change.ts +2
@@ -9,6 +9,7 @@
99 * bigger.
1010 */
1111
12 import { WAITING_FOR } from "../../core/asks.ts";
1213 import { mayEditIssue } from "../../actions/issues.ts";
1314 import { marksByName, type Mark } from "../../core/marks.ts";
1415 import { mayView } from "../../core/sealed.ts";
@@ -434,6 +435,7 @@ async function changeConversation(
434435 ? {
435436 kind: "look",
436437 id: `own:${pull.id}`,
438 waitingFor: conflicted ? WAITING_FOR.conflicts : WAITING_FOR.ready,
437439 repo,
438440 pull,
439441 who: pull.authorName,
src/web/studio/home.ts +10 −8
@@ -40,7 +40,6 @@ import {
4040 } from "../ui.ts";
4141 import {
4242 downloadsCard,
43 onYouCard,
4443 orgsCard,
4544 terminalCard,
4645 } from "../pages/site.ts";
@@ -53,9 +52,9 @@ import { everydayCard } from "../pages/everyday.ts";
5352 import { nextStepsCard } from "../pages/next-steps.ts";
5453 import { spawnedOrg } from "../../spawn/claim.ts";
5554
56 /** The events that can change what is on you. */
55 /** The events that can change what is in your inbox. */
5756 const ON_YOU_LIVE =
58 "issue.assigned,pull.assigned,issue.closed,pull.closed,issue.reopened,pull.reopened,pull.merged,fleet.operated";
57 "issue.assigned,pull.assigned,issue.closed,pull.closed,issue.reopened,pull.reopened,pull.merged,pull.reviewed,run.finished,fleet.operated";
5958 /** The events that can change how an app on the rail is. */
6059 const APPS_LIVE = "app.serving,app.stopped,run.finished";
6160 /** How many of your apps the rail names before "All apps". */
@@ -125,14 +124,17 @@ const appsRegion = (ctx: Ctx, user: User): Html =>
125124 ${yourApps(ctx, user)}
126125 </div>`;
127126
128 const onYouRegion = (ctx: Ctx, user: User, note?: string): Html =>
127 // The inbox is one list, so it is one live region. A bulk step's preview or
128 // receipt sits on top of it only on the page that asked, so that page does
129 // not refresh it from under the person reading.
130 const onYouRegion = (ctx: Ctx, user: User, inbox?: Html, note?: string): Html =>
129131 html`<div
130132 id="live-on-you"
131133 data-live="${ON_YOU_LIVE}"
132134 data-live-src="/live/on-you"
133135 >
134136 ${note === undefined ? null : html`<p class="small" role="status">${note}</p>`}
135 ${onYouCard(ctx, user) ?? null}
137 ${inbox ?? needsYouSection(ctx, user).body}
136138 </div>`;
137139
138140 // GET /live/apps — your apps alone, for the region that shows them.
@@ -147,7 +149,7 @@ export function liveAppsFragment(ctx: Ctx): Response {
147149 * region as it is now and the top bar's Asks link with its new count.
148150 */
149151 export function onYouAnswer(ctx: Ctx, user: User, note?: string): Response {
150 return fragment(html`<div>${onYouRegion(ctx, user, note)}${asksLink(ctx)}</div>`);
152 return fragment(html`<div>${onYouRegion(ctx, user, undefined, note)}${asksLink(ctx)}</div>`);
151153 }
152154
153155 // GET /live/on-you — what is on the viewer, alone.
@@ -191,7 +193,8 @@ export async function studioHome(
191193 ${homeTabs("feed")}
192194 <div class="dash">
193195 <div class="dash-main stack">
194 ${needsYou.body} ${composer(ctx, user)}
196 ${top === undefined ? onYouRegion(ctx, user, needsYou.body) : needsYou.body}
197 ${composer(ctx, user)}
195198 <div class="bar feed-head">
196199 <span class="spacer"></span>
197200 <a class="small muted" href="/asked">What you asked for</a>
@@ -207,7 +210,6 @@ export async function studioHome(
207210 user.isAdmin || appRepos.length > 0 ? crewKeyNote(ctx) : null
208211 }
209212 ${appsRegion(ctx, user)}
210 ${onYouRegion(ctx, user)}
211213 ${terminalCard(ctx)} ${downloadsCard(ctx, user)}
212214 ${orgsCard(ctx, user)}
213215 </aside>
test/asks-bulk.test.ts +10 −8
@@ -21,7 +21,8 @@ import { getAgentByName, setCrewRole } from "../src/core/agents.ts";
2121 import { getIssueById, listComments, type Issue } from "../src/core/issues.ts";
2222 import { assignIssue } from "../src/actions/issues.ts";
2323 import { mutedRepos, recordInteraction, removeMutes } from "../src/core/interactions.ts";
24 import { onYouCard } from "../src/web/pages/site.ts";
24 import { needsYouSection } from "../src/web/studio/asks_page.ts";
25 import { onYouRows } from "../src/web/pages/site.ts";
2526 import { getPull, type Pull } from "../src/core/pulls.ts";
2627 import type { Repo } from "../src/core/repos.ts";
2728 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
@@ -635,12 +636,12 @@ describe("acting on many asks at once", () => {
635636 expect(assignIssue(app, alice, open, issue, alice).ok).toBe(true);
636637 }
637638 const ctx = (user: User) => ({ app, auth: { user } }) as never;
638 const card = (user: User) => onYouCard(ctx(user), user)?.text ?? "";
639 const card = (user: User) => onYouRows(ctx(user), user, true).rows.map((r) => r.text).join("");
639640 expect(card(alice)).toContain("On you one");
640641 // The card offers the set: a box each, the kinds, one form.
641 expect(card(alice)).toContain('form="onyou-bulk"');
642 expect(card(alice)).toContain('form="asks-bulk"');
642643 expect(card(alice)).toContain('value="issue:' + a.id + '"');
643 expect(card(alice)).toContain("data-pick");
644 expect(needsYouSection(ctx(alice), alice).body.text).toContain("data-pick");
644645 const done = await api(aliceRw, "/api/v1/asks/bulk", {
645646 action: "mute",
646647 items: [`issue:${a.id}`, `issue:${b.id}`],
@@ -714,7 +715,8 @@ describe("acting on many asks at once", () => {
714715 const b = await greenPull(open, "Muted two");
715716 for (const pull of [a, b])
716717 expect(assignIssue(app, alice, open, getIssueById(app.db, pull.id)!, alice).ok).toBe(true);
717 const card = () => onYouCard({ app, auth: { user: alice } } as never, alice)?.text ?? "";
718 const body = () => needsYouSection({ app, auth: { user: alice } } as never, alice).body.text;
719 const card = () => onYouRows({ app, auth: { user: alice } } as never, alice).rows.map((r) => r.text).join("");
718720 expect(card()).not.toContain("muted");
719721 const done = await api(aliceRw, "/api/v1/asks/bulk", {
720722 action: "mute",
@@ -723,8 +725,8 @@ describe("acting on many asks at once", () => {
723725 });
724726 expect(done.status).toBe(201);
725727 // Past the day's undo, the card still says it, and offers the way back.
726 expect(card()).toContain("1 repository muted");
727 expect(card()).toContain('action="/asks/listen"');
728 expect(body()).toContain("1 repository muted");
729 expect(body()).toContain('action="/asks/listen"');
728730 const headers = { cookie: `${aliceCookie}; forge_mode=studio`, origin: servers.url };
729731 const res = await fetch(`${servers.url}/asks/listen`, {
730732 method: "POST",
@@ -735,7 +737,7 @@ describe("acting on many asks at once", () => {
735737 expect(res.status).toBe(303);
736738 expect(mutedRepos(app.db, alice.id).has(open.id)).toBe(false);
737739 expect(card()).toContain("Muted one");
738 expect(card()).not.toContain("repository muted");
740 expect(body()).not.toContain("repository muted");
739741 });
740742 test("on the card, a refusal answers 422 with its message, and a partial set says what was not done", async () => {
741743 const a = await greenPull(open, "Refuse one");
test/asks-expiry.test.ts +1 −1
@@ -47,7 +47,7 @@ describe("asks that expire, hold and collapse", () => {
4747 const sentence = (page: string): string =>
4848 /<h2 id="asks-sentence"[^>]*>([^<]*)<\/h2>/.exec(page)?.[1] ?? "";
4949 const headerCount = (page: string): number =>
50 Number(/>Asks<span class="pill"[^>]*>(\d+)</.exec(page)?.[1] ?? 0);
50 Number(/>Inbox<span class="pill"[^>]*>(\d+)</.exec(page)?.[1] ?? 0);
5151
5252 /** A run's timestamps are milliseconds: let one tick pass between acts. */
5353 const tick = () => Bun.sleep(5);
test/asks.test.ts +1 −1
@@ -55,7 +55,7 @@ describe("the asks page", () => {
5555
5656 /** The number the header's link carries, or 0 when it carries none. */
5757 const headerCount = (page: string): number =>
58 Number(/>Asks<span class="pill"[^>]*>(\d+)</.exec(page)?.[1] ?? 0);
58 Number(/>Inbox<span class="pill"[^>]*>(\d+)</.exec(page)?.[1] ?? 0);
5959
6060 const sentence = (page: string): string =>
6161 /<h2 id="asks-sentence"[^>]*>([^<]*)<\/h2>/.exec(page)?.[1] ?? "";
test/home-feed.test.ts +4 −4
@@ -277,14 +277,14 @@ describe("home is the feed", () => {
277277 expect(assignIssue(app, alice, repo, issue, alice).ok).toBe(true);
278278 const text = await (await get("/", aliceCookie)).text();
279279 const card = text.slice(text.indexOf('id="live-on-you"')).replace(/\s+/g, " ");
280 expect(card).toContain("On you");
280 expect(card).toContain("assigned to you");
281281 expect(card).toContain(`value="issue:${one.value.id}"`);
282282 expect(card).toContain(`value="issue:${two.value.id}"`);
283 expect((card.match(/form="onyou-bulk"/g) ?? []).length).toBeGreaterThanOrEqual(2);
283 expect((card.match(/form="asks-bulk"/g) ?? []).length).toBeGreaterThanOrEqual(2);
284284 expect(card).toContain('data-pick="all"');
285285 expect(card).toContain("data-pick-repo");
286286 expect(card).toContain('<option value="' + garden.id + '">alice/garden</option>');
287 expect(card).toContain('id="onyou-bulk"');
287 expect(card).toContain('id="asks-bulk"');
288288 expect(card).toContain('action="/asks/bulk"');
289289 expect(card).toContain('name="reason"');
290290 expect(card).toContain(">Mute repository<");
@@ -294,6 +294,6 @@ describe("home is the feed", () => {
294294 expect(text).toContain('id="asks-link"');
295295 // Alone, a single row stays a plain link.
296296 const bobCard = await (await get("/", bobCookie)).text();
297 expect(bobCard).not.toContain('id="onyou-bulk"');
297 expect(bobCard).not.toContain('id="asks-bulk"');
298298 });
299299 });
test/inbox.test.ts added +223
@@ -0,0 +1,223 @@
1 /**
2 * The one inbox: an agent's green pull waits in the crew's part while its
3 * reviewer has not answered, moves to the owner's when the review lands,
4 * and a conflicted pull says so. Assigned work shares the list and the count.
5 */
6
7 import { afterAll, beforeAll, describe, 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 { createApp, type App } from "../src/app.ts";
12 import { addToCrew, createAgent } from "../src/actions/crew.ts";
13 import { signUp } from "../src/actions/users.ts";
14 import { openPull } from "../src/actions/pulls.ts";
15 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
16 import { recordInteraction } from "../src/core/interactions.ts";
17 import { onYouRows } from "../src/web/pages/site.ts";
18 import { setCrewRole } from "../src/core/agents.ts";
19 import { submitReview } from "../src/core/reviews.ts";
20 import { createIssue, setAssignee, setIssueState } from "../src/core/issues.ts";
21 import type { Repo } from "../src/core/repos.ts";
22 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
23 import { getUserByName } from "../src/core/users.ts";
24 import { sweepStaleAsks } from "../src/crew/stale_asks.ts";
25 import { askCountFor, asksAnswer, assignedLinesFor } from "../src/web/studio/asks.ts";
26 import { needsYouSection } from "../src/web/studio/asks_page.ts";
27 import type { Ctx } from "../src/http/context.ts";
28 import { quietLogs } from "./helpers/globals.ts";
29
30 quietLogs();
31
32 const PASSWORD = "a-long-inbox-passphrase";
33
34 describe("the one inbox", () => {
35 let dataDir = "";
36 let app: App;
37 let repo: Repo;
38
39 const alice = () => getUserByName(app.db, "alice")!;
40 const ctx = (): Ctx =>
41 ({
42 app,
43 auth: { user: alice() },
44 url: new URL("http://forge.test/"),
45 request: new Request("http://forge.test/"),
46 }) as unknown as Ctx;
47 /** The inbox section as the home renders it, whitespace collapsed. */
48 const home = async (): Promise<string> =>
49 needsYouSection(ctx(), alice()).body.toString().replace(/\s+/g, " ");
50 const answer = () => asksAnswer(ctx(), alice());
51
52 const greenPull = async (branch: string, title: string, file = `${branch}.md`, author = getUserByName(app.db, "bot")!) => {
53 await commitToBranch(app, alice(), repo, {
54 branch,
55 base: "main",
56 message: title,
57 files: [{ path: file, content: `${title}\n` }],
58 });
59 const opened = await openPull(app, author, repo, {
60 title,
61 body: "",
62 baseBranch: "main",
63 headBranch: branch,
64 });
65 if (!opened.ok) throw new Error(String(opened.error));
66 const pull = opened.value;
67 const run = createRun(app.db, {
68 repoId: repo.id,
69 kind: "check",
70 issueId: pull.id,
71 env: `pull-${pull.number}`,
72 commitOid: pull.headOid,
73 reason: "pull",
74 });
75 claimRun(app.db, run.id);
76 finishRun(app.db, run.id, { state: "ok", summary: "ok" });
77 return pull;
78 };
79
80 beforeAll(async () => {
81 dataDir = await mkdtemp(join(tmpdir(), "forge-inbox-"));
82 app = createApp({ dataDir, port: 0 });
83 const joined = await signUp(app, {
84 username: "alice",
85 email: "[email protected]",
86 password: PASSWORD,
87 });
88 if (!joined.ok) throw new Error(String(joined.error));
89 const made = await createRepo(app, alice(), { name: "garden", visibility: "public" });
90 if (!made.ok) throw new Error(String(made.error));
91 repo = made.value;
92 await commitToBranch(app, alice(), repo, {
93 message: "seed",
94 files: [{ path: "README.md", content: "# garden\n" }],
95 });
96 await createAgent(app, alice(), { username: "bot" });
97 addToCrew(app, alice(), repo, "bot");
98 await createAgent(app, alice(), { username: "juniper" });
99 addToCrew(app, alice(), repo, "juniper");
100 const juniper = getUserByName(app.db, "juniper")!;
101 setCrewRole(app.db, repo.id, juniper.id, "reviewer");
102 }, 30_000);
103
104 afterAll(async () => {
105 await rm(dataDir, { recursive: true, force: true });
106 });
107
108 test("an agent's green pull with no review is the crew's, then the owner's once approved", async () => {
109 const pull = await greenPull("bot/1-thing", "Bot did a thing");
110 let page = await home();
111 expect(page).toContain("The crew's · 1");
112 expect(page).toContain("waiting for juniper&#39;s review");
113 expect(page).not.toContain(`id="ask-look:${pull.id}"`);
114 let list = await answer();
115 expect(list.rows).toHaveLength(0);
116 expect(list.crew[0]?.waitingFor).toBe("waiting for juniper's review");
117 expect(list.crew[0]?.part).toBe("crew");
118 expect(list.inbox.map((r) => r.part)).toEqual(["crew"]);
119 expect(page).toContain("All fine");
120 expect(askCountFor(ctx(), alice())).toBe(0);
121
122 const juniper = getUserByName(app.db, "juniper")!;
123 submitReview(app.db, {
124 issueId: pull.id,
125 authorId: juniper.id,
126 state: "approved",
127 commitOid: pull.headOid,
128 });
129 page = await home();
130 expect(page).not.toContain("The crew's");
131 expect(page).toContain(`id="ask-look:${pull.id}"`);
132 expect(page).toContain("ready to land");
133 list = await answer();
134 expect(list.crew).toHaveLength(0);
135 expect(list.rows[0]?.waitingFor).toBe("ready to land");
136 expect(list.rows[0]?.part).toBe("yours");
137 expect(page).toContain("1 thing needs you");
138 // Two looks in one repository are one row; the next test reads its own pull alone.
139 setIssueState(app.db, pull.id, "closed");
140 });
141
142 test("a reviewer who declines hands the pull to the owner too", async () => {
143 const pull = await greenPull("bot/2-other", "Bot did another");
144 expect(await home()).not.toContain(`id="ask-look:${pull.id}"`);
145 const juniper = getUserByName(app.db, "juniper")!;
146 submitReview(app.db, {
147 issueId: pull.id,
148 authorId: juniper.id,
149 state: "changes_requested",
150 commitOid: pull.headOid,
151 });
152 const page = await home();
153 expect(page).toContain(`id="ask-look:${pull.id}"`);
154 expect((await answer()).rows.find((r) => r.link.endsWith(`/${pull.number}`))?.waitingFor).toBe(
155 "changes requested by juniper",
156 );
157 });
158
159 test("a person's own conflicting pull is not the crew's", async () => {
160 const pull = await greenPull("alice/4-mine", "Alice clashes", "README.md", alice());
161 await commitToBranch(app, alice(), repo, {
162 message: "main edits readme again",
163 files: [{ path: "README.md", content: "# garden, main again\n" }],
164 });
165 await sweepStaleAsks(app);
166 const list = await answer();
167 expect(list.crew.map((r) => r.link)).not.toContain(
168 `/${repo.ownerName}/${repo.name}/changes/${pull.number}`,
169 );
170 });
171
172 test("a conflicted pull says conflicts with main, and is not the owner's to land", async () => {
173 const pull = await greenPull("bot/3-clash", "Bot clashes", "README.md");
174 await commitToBranch(app, alice(), repo, {
175 message: "main edits readme",
176 files: [{ path: "README.md", content: "# garden, main\n" }],
177 });
178 await sweepStaleAsks(app);
179 const page = await home();
180 expect(page).not.toContain(`id="ask-look:${pull.id}"`);
181 expect(page).toContain("conflicts with main");
182 expect((await answer()).crew.map((r) => r.waitingFor)).toContain("conflicts with main");
183 });
184
185 test("assigned work is in the same list and the same count", async () => {
186 const before = (await answer()).inbox.length;
187 const made = createIssue(app.db, {
188 repoId: repo.id,
189 authorId: alice().id,
190 title: "Water the beds",
191 });
192 if (!made.ok) throw new Error(String(made.error));
193 setAssignee(app.db, made.value.id, alice().id);
194 const list = await answer();
195 expect(list.assigned[0]?.waitingFor).toBe("assigned to you");
196 expect(list.inbox.length).toBe(before + 1);
197 const page = await home();
198 expect(page).toContain("Water the beds");
199 expect(askCountFor(ctx(), alice())).toBe(2);
200 });
201
202 test("select-all ships with the page even when nothing could be ticked yet, so a live refresh keeps it", () => {
203 expect(needsYouSection(ctx(), alice()).scriptJs).toContain("data-select-all");
204 });
205
206 test("a muted repository's assigned work leaves the count, the API, the phone and the terminal alike", async () => {
207 expect(assignedLinesFor(app.db, alice()).length).toBe(1);
208 const count = askCountFor(ctx(), alice());
209 recordInteraction(app.db, {
210 viewerId: alice().id,
211 itemId: repo.id,
212 kind: "muted",
213 repoId: repo.id,
214 actorId: null,
215 });
216 expect(askCountFor(ctx(), alice())).toBe(count - 1);
217 expect((await answer()).assigned.length).toBe(0);
218 expect(assignedLinesFor(app.db, alice()).length).toBe(0);
219 const own = onYouRows(ctx(), alice());
220 expect(own.rows.length).toBe(0);
221 expect(own.silenced.map((r) => r.id)).toEqual([repo.id]);
222 });
223 });
test/notify.test.ts +26
@@ -12,6 +12,7 @@ import { announceRun } from "../src/actions/runs.ts";
1212 import { openPull } from "../src/actions/pulls.ts";
1313 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
1414 import type { Repo } from "../src/core/repos.ts";
15 import { createIssue, setAssignee } from "../src/core/issues.ts";
1516 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
1617 import { createUser, type User } from "../src/core/users.ts";
1718 import { serve, type Servers } from "../src/http/server.ts";
@@ -159,6 +160,31 @@ describe("notify", () => {
159160 for (let i = 5; i < 20; i++) await greenPull(i, `Pull ${i}`);
160161 expect(posts.length - before).toBe(9);
161162 });
163
164 test("work assigned to a person is told too, since the header counts it", async () => {
165 const made = createIssue(app.db, {
166 repoId: repo.id,
167 authorId: bob.id,
168 title: "Oil the hinges",
169 });
170 if (!made.ok) throw new Error(String(made.error));
171 setAssignee(app.db, made.value.id, alice.id);
172 clock += 2 * 3_600_000;
173 const before = posts.length;
174 const run = createRun(app.db, {
175 repoId: repo.id,
176 kind: "check",
177 env: "main",
178 commitOid: "1".repeat(40),
179 reason: "push",
180 });
181 claimRun(app.db, run.id);
182 announceRun(app, finishRun(app.db, run.id, { state: "ok", summary: "ok" })!);
183 await notifier.settled();
184 const told = posts.slice(before).filter((p) => p.url === URL_A);
185 expect(told).toHaveLength(1);
186 expect(told[0]!.body).toContain("Oil the hinges");
187 });
162188 });
163189
164190 describe("the notify URL", () => {
test/tui-code.test.ts +2 −2
@@ -369,8 +369,8 @@ describe("the terminal, around the workspace", () => {
369369 const told = openIssue(forge, alice, repo, { title: "Realtime beacon" });
370370 if (!told.ok) throw new Error("open failed");
371371 expect(assignIssue(forge, alice, repo, told.value, alice).ok).toBe(true);
372 await h.until("Realtime beacon");
373 expect(h.text()).toContain("Realtime beacon");
372 await h.until("assigned to you");
373 expect(h.text()).toContain("Realtime be");
374374 } finally {
375375 h.stop();
376376 }
test/tui-inbox.test.ts added +113
@@ -0,0 +1,113 @@
1 /**
2 * The terminal's dashboard shows the same inbox as the web home: assigned
3 * work and asks in one counted list, an agent's unreviewed green pull in the
4 * crew's part, each row saying what it waits for.
5 */
6
7 import { afterAll, beforeAll, describe, 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 { addToCrew, createAgent } from "../src/actions/crew.ts";
12 import { openPull } from "../src/actions/pulls.ts";
13 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
14 import { signUp } from "../src/actions/users.ts";
15 import { createApp, type App } from "../src/app.ts";
16 import { setCrewRole } from "../src/core/agents.ts";
17 import { createIssue, setAssignee } from "../src/core/issues.ts";
18 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
19 import { getUserByName } from "../src/core/users.ts";
20 import { createForgeApp } from "../src/tui/forge.ts";
21 import { headlessTerminal } from "../src/tui/term/terminal.ts";
22 import { quietLogs } from "./helpers/globals.ts";
23 import { settleApp } from "./helpers/tui.ts";
24
25 quietLogs();
26
27 describe("the dashboard's inbox", () => {
28 let dataDir = "";
29 let app: App;
30
31 beforeAll(async () => {
32 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-inbox-"));
33 app = createApp({ dataDir, port: 0 });
34 const joined = await signUp(app, {
35 username: "alice",
36 email: "[email protected]",
37 password: "a-long-inbox-passphrase",
38 });
39 if (!joined.ok) throw new Error(String(joined.error));
40 const alice = getUserByName(app.db, "alice")!;
41 const made = await createRepo(app, alice, { name: "garden", visibility: "public" });
42 if (!made.ok) throw new Error(String(made.error));
43 const repo = made.value;
44 await commitToBranch(app, alice, repo, {
45 message: "seed",
46 files: [{ path: "README.md", content: "# garden\n" }],
47 });
48 await createAgent(app, alice, { username: "bot" });
49 addToCrew(app, alice, repo, "bot");
50 await createAgent(app, alice, { username: "juniper" });
51 addToCrew(app, alice, repo, "juniper");
52 setCrewRole(app.db, repo.id, getUserByName(app.db, "juniper")!.id, "reviewer");
53 await commitToBranch(app, alice, repo, {
54 branch: "bot/1-thing",
55 base: "main",
56 message: "Bot did a thing",
57 files: [{ path: "thing.md", content: "thing\n" }],
58 });
59 const opened = await openPull(app, getUserByName(app.db, "bot")!, repo, {
60 title: "Bot did a thing",
61 body: "",
62 baseBranch: "main",
63 headBranch: "bot/1-thing",
64 });
65 if (!opened.ok) throw new Error(String(opened.error));
66 const run = createRun(app.db, {
67 repoId: repo.id,
68 kind: "check",
69 issueId: opened.value.id,
70 env: `pull-${opened.value.number}`,
71 commitOid: opened.value.headOid,
72 reason: "pull",
73 });
74 claimRun(app.db, run.id);
75 finishRun(app.db, run.id, { state: "ok", summary: "ok" });
76 const issue = createIssue(app.db, {
77 repoId: repo.id,
78 authorId: alice.id,
79 title: "Water the beds",
80 });
81 if (!issue.ok) throw new Error(String(issue.error));
82 setAssignee(app.db, issue.value.id, alice.id);
83 }, 30_000);
84
85 afterAll(async () => {
86 app.close();
87 await rm(dataDir, { recursive: true, force: true });
88 });
89
90 test("assigned work is counted and the unreviewed agent pull waits in the crew's part", async () => {
91 const terminal = headlessTerminal(140, 32);
92 const { app: tui } = createForgeApp(
93 app,
94 {
95 sshUsername: "alice",
96 remoteAddress: "127.0.0.1",
97 fingerprint: "SHA256:test",
98 user: getUserByName(app.db, "alice")!,
99 },
100 { terminal, exitHooks: false },
101 );
102 tui.start();
103 await settleApp(tui);
104 const text = tui.screen.toText();
105 tui.stop();
106 expect(text).toContain("Inbox · 1");
107 expect(text).toContain("Water the beds");
108 expect(text).toContain("assigned to you");
109 expect(text).toContain("crew");
110 expect(text).toContain("waiting for juniper's review");
111 expect(text).not.toContain("Nothing is assigned to you");
112 });
113 });
test/tui-mouse.test.ts +3 −3
@@ -187,7 +187,7 @@ describe("the pointer", () => {
187187 body: "at dusk",
188188 });
189189 if (!issue.ok) throw new Error("issue failed");
190 // On alice, so the dashboard's "On you" pane has a row to click.
190 // On alice, so the dashboard's "Inbox" pane has a row to click.
191191 if (!assignIssue(forge, alice, repo, issue.value, alice).ok)
192192 throw new Error("assign failed");
193193 });
@@ -274,10 +274,10 @@ describe("the pointer", () => {
274274 const h = boot();
275275 try {
276276 await h.settle();
277 const onYou = h.rowOf("On you");
277 const onYou = h.rowOf("Inbox");
278278 expect(onYou).toBeGreaterThan(0);
279279 // The card's first row is one below its title.
280 await h.click(h.rows()[onYou]!.indexOf("On you"), onYou + 1);
280 await h.click(h.rows()[onYou]!.indexOf("Inbox"), onYou + 1);
281281 await h.settle();
282282 // Focus moved: the repo list no longer holds the cursor, and `enter`
283283 // now opens *what the row is about* — the issue, not the repo it
test/tui-screens.test.ts +1 −1
@@ -212,7 +212,7 @@ describe("the terminal UI, against a real forge", () => {
212212 const text = h.text();
213213 expect(text).toContain("alice/lighthouse");
214214 expect(text).toContain("alice/vault");
215 expect(text).toContain("On you");
215 expect(text).toContain("Inbox");
216216 expect(text).toContain("find a repository");
217217 // What happened is the web feed's job now (#636).
218218 expect(text).not.toContain("Recent activity");
test/tui-size.test.ts +5 −5
@@ -189,24 +189,24 @@ describe("the terminal lays out for the terminal it is in", () => {
189189 try {
190190 const at = (what: string): number =>
191191 h.lines().findIndex((line) => line.includes(what));
192 expect(at("On you")).toBe(at("find a repository"));
192 expect(at("Inbox")).toBe(at("find a repository"));
193193 expect(at("On your machine")).toBeGreaterThan(-1);
194194
195195 await h.resize(TWO_PANE_COLS - 1, 40);
196196 // Stacked: what is on you is a card under the list, and the machine
197197 // card waits for a wider window rather than crowd a column.
198 expect(at("On you")).toBeGreaterThan(at("alice/lighthouse"));
198 expect(at("Inbox")).toBeGreaterThan(at("alice/lighthouse"));
199199 expect(at("On your machine")).toBe(-1);
200200 // And `tab` reaches exactly what is drawn: on you, then back.
201201 const c = theme("dark").c;
202202 await h.press("tab");
203 expect(h.app.screen.styleAt(0, at("On you")).fg).toBe(c.accent);
203 expect(h.app.screen.styleAt(0, at("Inbox")).fg).toBe(c.accent);
204204 await h.press("tab");
205 expect(h.app.screen.styleAt(0, at("On you")).fg).not.toBe(c.accent);
205 expect(h.app.screen.styleAt(0, at("Inbox")).fg).not.toBe(c.accent);
206206
207207 // Too short to stack: the repositories have the whole body.
208208 await h.resize(80, 12);
209 expect(at("On you")).toBe(-1);
209 expect(at("Inbox")).toBe(-1);
210210 expect(at("alice/lighthouse")).toBeGreaterThan(-1);
211211 } finally {
212212 h.stop();
test/web-apps.test.ts +3 −3
@@ -817,15 +817,15 @@ describe("apps, runs and the crew on the web", () => {
817817 );
818818 if (check?.state !== "ok") expect(page).toContain("Waiting on checks.");
819819
820 // On you: assigned to the viewer, the pull shows on the dashboard.
820 // The inbox: assigned to the viewer, the pull shows on the home.
821821 const assigned = await web(alice, `/alice/hello/pulls/${number}/assignee`, {
822822 form: { assignee: "alice" },
823823 });
824824 expect(assigned.status).toBe(303);
825825 const dash = await bodyOf(alice, "/");
826 expect(dash).toContain("<h2>On you</h2>");
826 expect(dash).toContain("assigned to you");
827827 expect(dash).toContain("Say hello");
828 expect(await bodyOf(bob, "/")).not.toContain("<h2>On you</h2>");
828 expect(await bodyOf(bob, "/")).not.toContain("assigned to you");
829829
830830 // Needs you: a pull the crew opened, in a repository alice can write.
831831 expect(addToCrew(app, aliceUser, hello, "bot").ok).toBe(true);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs