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 #1353

Closed opened this in answer to
Closed without merging

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

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
22 files changed +831 −204
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
src/core/asks.ts added +68
@@ -0,0 +1,68 @@
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 { mayView } from "./sealed.ts";
17 import type { User } from "./users.ts";
18
19 /** Whose move it is: the owner's to act on now, or the crew's to finish first. */
20 export type Part = "yours" | "crew";
21
22 /** The words a row says it waits for, one per cause. */
23 export const WAITING_FOR = {
24 /** A green pull the viewer may land. */
25 ready: "ready to land",
26 /** An agent's green pull whose reviewer is out, or lapsed or absent. */
27 yourReview: "waiting for your review",
28 decision: "a decision",
29 assigned: "assigned to you",
30 conflicts: "conflicts with main",
31 } as const;
32
33 /** What a pull waits for while a reviewer of the crew has not yet answered. */
34 export const reviewOf = (reviewer: string): string =>
35 `waiting for ${reviewer}'s review`;
36
37 /** What an agent's pull waits for once a reviewer has asked for changes. */
38 export const changesOf = (reviewer: string): string =>
39 `changes requested by ${reviewer}`;
40
41 /** Open issues and pulls assigned to the viewer, anywhere they can see. */
42 export function assignedToYou(
43 db: Database,
44 user: User,
45 ): { repo: Repo; issue: Issue }[] {
46 const assigned = listAssignedTo(db, user.id, 20);
47 if (assigned.length === 0) return [];
48 const repos = getReposByIds(
49 db,
50 assigned.map((issue) => issue.repoId),
51 );
52 // `listAssignedTo` has no visibility filter of its own (an assignment can
53 // outlive the access that made it), so each repo needs a real `canRead`.
54 // `listReposVisibleTo` answers the common case with one query for the
55 // whole page; `canRead` only runs for the rare repo it did not reach.
56 const visible = new Set(
57 listReposVisibleTo(db, user, { limit: 200 }).map((repo) => repo.id),
58 );
59 const out: { repo: Repo; issue: Issue }[] = [];
60 for (const issue of assigned) {
61 const repo = repos.get(issue.repoId);
62 if (!repo) continue;
63 if (!visible.has(repo.id) && !canRead(db, repo, user)) continue;
64 if (!mayView(db, repo, issue, user)) continue;
65 out.push({ repo, issue });
66 }
67 return out;
68 }
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) => ({
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 && reviewStage(history.greenAt, history.attempts, 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 +69 −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,57 @@ 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 asks = askLinesFor(f.db, user).map(
142 (a): OnYouItem => ({
143 title: a.line,
144 meta: a.waitingFor,
145 waitingFor: a.waitingFor,
146 counted: true,
147 open: () => openOnWeb(f, ctx, a.link, "What needs you"),
148 }),
136149 );
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 });
150 const assigned = assignedLinesFor(f.db, user);
151 const crew = crewLinesFor(f.db, user);
152 const repos = repoOf([...assigned, ...crew].map((r) => r.repoId));
153 const pullOf = (r: { repoId: string; number: number }, kind: string) => () => {
154 const repo = repos.get(r.repoId);
155 if (repo === undefined) return;
156 const src = local(f, repo);
157 ctx.push(
158 kind === "pull"
159 ? pullScreen(f, ctx, src, r.number)
160 : issueScreen(f, ctx, src, r.number),
161 );
162 };
163 return [
164 ...asks,
165 ...assigned.map(
166 (r): OnYouItem => ({
167 title: r.line,
outdated

Don't infer the kind from the URL. Have assignedLinesFor return issue.kind and branch on that.

168 meta: r.waitingFor,
169 waitingFor: r.waitingFor,
170 counted: true,
171 open: pullOf(r, r.issueKind),
172 }),
173 ),
174 ...crew.map(
175 (r): OnYouItem => ({
176 title: `crew · ${r.line}`,
177 meta: r.waitingFor,
178 waitingFor: r.waitingFor,
179 counted: false,
180 open: pullOf(r, "pull"),
181 }),
182 ),
183 ];
145184 };
146185
147186 /** Yours with an empty filter; anything you can see once you type —
@@ -220,15 +259,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
220259 );
221260 };
222261
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 };
262 const openAssigned = (item: OnYouItem | undefined): void => item?.open();
232263
233264 /** `enter` on whatever the focused pane's cursor is on. */
234265 const openHere = (): void => {
@@ -367,15 +398,16 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
367398
368399 // ---- the panes ----
369400
370 /** The inbox: what is assigned to this account, across every repository. */
401 /** The inbox: what asks you or is assigned to you, then the crew's part (uncounted). */
371402 function drawOnYou(s: Surface, r: Rect, c: Tokens, set: IconSet): void {
372403 const on = focus === "onyou";
404 const count = onYou.filter((item) => item.counted).length;
373405 const inner = card(s, r, c, {
374 title: `${icon("person", set)} ${TITLES.onyou}`,
406 title: `${icon("person", set)} ${TITLES.onyou} · ${count}`,
375407 focused: on,
376408 });
377409 if (onYou.length === 0) {
378 note(s, inner, c, ["Nothing is assigned to you."]);
410 note(s, inner, c, ["Nothing is waiting on you."]);
379411 return;
380412 }
381413 drawList(
@@ -383,18 +415,7 @@ export function dashboardScreen(f: Session, ctx: Ctx): Screen {
383415 inner,
384416 c,
385417 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 }),
418 onYou.map((item): ListRow => ({ title: item.title, meta: item.meta })),
398419 on,
399420 );
400421 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 +28 −78
@@ -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,8 +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";
30 import { homeTop } from "../studio/asks_page.ts";
3431 import { mutedRepos } from "../../core/interactions.ts";
3532 import { edgeLoginUrl } from "../../http/edge.ts";
3633 import { sshCommand } from "../../ssh/command.ts";
@@ -165,96 +162,49 @@ export function downloadsCard(ctx: Ctx, user: User): Html {
165162 const threadPath = (repo: Repo, issue: Issue): string =>
166163 `/${repo.ownerName}/${repo.name}/${issue.kind === "pull" ? "pulls" : "issues"}/${issue.number}`;
167164
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.
165 /**
166 * What is assigned to the viewer, as the inbox's rows (`assignedToYou`). With
167 * `boxes` each row carries a box for the asks' bulk form. Muted repositories
168 * hold their work back from the rows and come back as `silenced`: said, never
169 * silent.
170 */
171 export function onYouRows(
172 ctx: Ctx,
173 user: User,
174 boxes = false,
175 ): { rows: Html[]; shown: { issue: Issue; repo: Repo }[]; silenced: Repo[] } {
176 const muted = mutedRepos(ctx.app.db, user.id);
190177 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 }) =>
178 const shown = assignedToYou(ctx.app.db, user).filter(({ repo }) => {
179 if (!muted.has(repo.id)) return true;
180 silenced.set(repo.id, repo);
181 return false;
182 });
183 const rows = shown.map(({ repo, issue }) =>
205184 row({
206 ...(bulk ? {} : { href: threadPath(repo, issue), nav: true as const }),
185 ...(boxes ? {} : { href: threadPath(repo, issue), nav: true as const }),
207186 state: "open",
208 lead: bulk
187 lead: boxes
209188 ? html`<input
210189 type="checkbox"
211190 class="ask-pick"
212191 name="item"
213192 value="issue:${issue.id}"
214 form="onyou-bulk"
193 form="asks-bulk"
215194 data-repo="${repo.id}"
216195 data-kind="${issue.kind}"
217196 aria-label="Select ${issue.title}"
218197 />`
219198 : icon(issue.kind === "pull" ? "pull" : "issue"),
220 title: bulk
199 title: boxes
221200 ? html`<a href="${threadPath(repo, issue)}">${issue.title}</a>`
222201 : issue.title,
223202 titleAttr: issue.title,
224 meta: html`${repo.ownerName}/${repo.name} #${issue.number} · updated
225 ${time(issue.updatedAt)}`,
203 meta: html`${WAITING_FOR.assigned} · ${repo.ownerName}/${repo.name}
204 #${issue.number} · updated ${time(issue.updatedAt)}`,
226205 }),
227206 );
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 });
207 return { rows, shown, silenced: [...silenced.values()] };
258208 }
259209
260210 export function orgsCard(ctx: Ctx, user: User): Html {
src/web/studio/asks.ts +166 −16
@@ -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;
outdated

High: missing issue.authorIsAgent guard. A person's own conflicting pull lands in "The crew's", where nothing will ever pick it up. Limit the branch to agent pulls and test the person-authored case.

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({
outdated

awaitedReviewer makes 4–5 queries per green pull (getHold, reviewersOf, reviewSummary, reviewAttempts ×2, the run lookup). The function above already batch-loads held and checks for all pulls. Call reviewersOf once per repo, outside the loop, and skip the call when the repo has no reviewer.

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"
@@ -696,10 +774,15 @@ export function askLinesFor(
696774 words: AskWords;
697775 /** Why it ranks where it does; rows come most consequential first. */
698776 consequence: Consequence;
777 /** What it waits for, from whom (`WAITING_FOR`). */
778 waitingFor: string;
779 /** Whose move: always the viewer's here; the crew's part is `crewLinesFor`. */
780 part: Part;
699781 }[] {
700782 const repos = listReposVisibleTo(db, user, { limit: 200 });
701783 return askRows(waitingOn(db, user, repos)).map((row) => {
702784 const base = `/${row.repo.ownerName}/${row.repo.name}`;
785 const changesBy = row.items.length === 1 ? row.items[0]!.changesBy : undefined;
703786 const about = {
704787 id: row.id,
705788 kind: row.kind,
@@ -707,6 +790,11 @@ export function askLinesFor(
707790 items: row.items.map((c) => c.id),
708791 words: ASK_WORDS[row.kind],
709792 consequence: row.consequence,
793 waitingFor:
794 row.kind === "look" && changesBy !== undefined
795 ? changesOf(changesBy)
796 : waitingForKind(row.kind),
797 part: "yours" as Part,
710798 };
711799 const only = row.items.length === 1 ? row.items[0]! : undefined;
712800 if (only === undefined)
@@ -734,6 +822,48 @@ export function askLinesFor(
734822 });
735823 }
736824
825 /** Who asked for changes on a pull's current head, as a candidate's field. */
826 function changesOn(db: Database, pull: Pull): { changesBy?: string } {
827 if (!pull.authorIsAgent) return {};
828 for (const review of latestReviewByAuthor(db, pull.id).values()) {
829 if (review.state !== "changes_requested" || review.commitOid !== pull.headOid) continue;
830 const name = getUserById(db, review.authorId)?.username;
831 if (name !== undefined) return { changesBy: name };
832 }
833 return {};
834 }
835
836 /** The crew's part of the inbox as data: pulls waiting for a reviewer, or for a rebase. */
837 export function crewLinesFor(db: Database, user: User) {
838 const repos = listReposVisibleTo(db, user, { limit: 200 });
839 return crewWaitsFor(db, user, repos).map((w) => ({
840 id: w.id,
841 part: "crew" as Part,
842 kind: "crew" as const,
843 waitingFor: w.waitingFor,
844 line: `${w.repo.name}: "${w.pull.title}" — ${w.waitingFor}`,
845 link: `/${w.repo.ownerName}/${w.repo.name}/changes/${w.pull.number}`,
846 number: w.pull.number,
847 repoId: w.repo.id,
848 since: w.since,
849 }));
850 }
851
852 /** The assigned part of the inbox as data. */
853 export function assignedLinesFor(db: Database, user: User) {
854 return assignedToYou(db, user).map(({ repo, issue }) => ({
855 id: `assigned:${issue.id}`,
856 part: "yours" as Part,
857 kind: "assigned" as const,
858 issueKind: issue.kind,
859 waitingFor: WAITING_FOR.assigned,
860 line: `${repo.name}: "${issue.title}" is assigned to you`,
861 link: `/${repo.ownerName}/${repo.name}/${issue.kind === "pull" ? "pulls" : "issues"}/${issue.number}`,
862 number: issue.number,
863 repoId: repo.id,
864 }));
865 }
866
737867 /**
738868 * The decisions waiting on the viewer, worded and pictured. A change's own
739869 * page passes `evenDismissed`: setting an ask aside quiets the lists, never
@@ -742,12 +872,12 @@ export function askLinesFor(
742872 export function decisionsFor(
743873 ctx: Ctx,
744874 allRepos: readonly Repo[],
745 options: { evenDismissed?: boolean } = {},
875 options: { evenDismissed?: boolean; crew?: CrewWait[] } = {},
746876 ): Decision[] {
747877 const db = ctx.app.db;
748878 const candidates = options.evenDismissed
749 ? scoredFor(db, ctx.auth.user, allRepos)
750 : waitingOn(db, ctx.auth.user, allRepos);
879 ? scoredFor(db, ctx.auth.user, allRepos, undefined, options.crew)
880 : waitingOn(db, ctx.auth.user, allRepos, options.crew);
751881 // The pictures, in one read: a green pull's row leads with its preview.
752882 const repoIds = [...new Set(candidates.map((c) => c.repo.id))];
753883 const records = appsForRepos(db, repoIds);
@@ -769,7 +899,7 @@ export function decisionsFor(
769899 look && lookUrl(repoBase(repo), look)
770900 );
771901 };
772 const worded = (c: Scored): Omit<Decision, "consequence"> => {
902 const worded = (c: Scored): Omit<Decision, "consequence" | "waitingFor"> => {
773903 if (c.kind === "parked" && c.issue)
774904 return {
775905 kind: "parked",
@@ -846,7 +976,14 @@ export function decisionsFor(
846976 short: `at its $${dollars(c.repo.autonomyCeilingUsd)} ceiling until 00:00 UTC`,
847977 };
848978 };
849 return candidates.map((c) => ({ ...worded(c), consequence: c.consequence }));
979 return candidates.map((c) => ({
980 ...worded(c),
981 waitingFor:
982 c.kind === "look" && c.changesBy !== undefined
983 ? changesOf(c.changesBy)
984 : waitingForKind(c.kind),
985 consequence: c.consequence,
986 }));
850987 }
851988 /** The id of the form a row's own button submits (see `decisionForm`). */
852989 const askFormId = (d: Decision): string => `ask-${d.id}`;
@@ -969,7 +1106,8 @@ export function askCountFor(ctx: Ctx, user: User | undefined): number {
9691106 const repos = listReposVisibleTo(ctx.app.db, user, { limit: 200 });
9701107 return (
9711108 askRows(waitingOn(ctx.app.db, user, repos)).length +
972 forgeNeedsFor(ctx, user).length
1109 forgeNeedsFor(ctx, user).length +
1110 assignedToYou(ctx.app.db, user).length
9731111 );
9741112 }
9751113
@@ -988,8 +1126,20 @@ export function askSentence(count: number): string {
9881126 */
9891127 export function asksAnswer(ctx: Ctx, user: User) {
9901128 const since = new Date(Date.now() - 7 * 86_400_000).toISOString();
1129 const rows = askLinesFor(ctx.app.db, user);
1130 const crew = crewLinesFor(ctx.app.db, user);
1131 const assigned = assignedLinesFor(ctx.app.db, user);
9911132 return {
992 rows: askLinesFor(ctx.app.db, user),
1133 rows,
1134 crew,
1135 assigned,
1136 // The one list: the viewer's part first, then the crew's, each row
1137 // saying what it waits for and from whom.
1138 inbox: [
1139 ...rows.map((r) => ({ part: r.part, waitingFor: r.waitingFor, line: r.line, link: r.link, kind: r.kind })),
1140 ...assigned.map((r) => ({ part: r.part, waitingFor: r.waitingFor, line: r.line, link: r.link, kind: r.kind })),
1141 ...crew.map((r) => ({ part: r.part, waitingFor: r.waitingFor, line: r.line, link: r.link, kind: r.kind })),
1142 ],
9931143 forge: forgeNeedsFor(ctx, user),
9941144 measure: { days: 7, ...askMeasure(ctx.app.db, user.id, since) },
9951145 };
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";
outdated

run.finished now re-renders the whole inbox, bulk form included. Bulk-select ticks are lost on every swap unless the checkbox has focus. Preserve checked ids across the swap, or leave this event off.

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"

On a live refresh, /live/on-you renders needsYouSection(...).body and drops its scriptJs. Once the region swaps, select-all on the bulk form stops working. Either keep the script in the static page outside the region, or have the fragment carry it.

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 +203
@@ -0,0 +1,203 @@
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 { setCrewRole } from "../src/core/agents.ts";
17 import { submitReview } from "../src/core/reviews.ts";
18 import { createIssue, setAssignee, setIssueState } from "../src/core/issues.ts";
19 import type { Repo } from "../src/core/repos.ts";
20 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
21 import { getUserByName } from "../src/core/users.ts";
22 import { sweepStaleAsks } from "../src/crew/stale_asks.ts";
23 import { askCountFor, asksAnswer } from "../src/web/studio/asks.ts";
24 import { needsYouSection } from "../src/web/studio/asks_page.ts";
25 import type { Ctx } from "../src/http/context.ts";
26 import { quietLogs } from "./helpers/globals.ts";
27
28 quietLogs();
29
30 const PASSWORD = "a-long-inbox-passphrase";
31
32 describe("the one inbox", () => {
33 let dataDir = "";
34 let app: App;
35 let repo: Repo;
36
37 const alice = () => getUserByName(app.db, "alice")!;
38 const ctx = (): Ctx =>
39 ({
40 app,
41 auth: { user: alice() },
42 url: new URL("http://forge.test/"),
43 request: new Request("http://forge.test/"),
44 }) as unknown as Ctx;
45 /** The inbox section as the home renders it, whitespace collapsed. */
46 const home = async (): Promise<string> =>
47 needsYouSection(ctx(), alice()).body.toString().replace(/\s+/g, " ");
48 const answer = () => asksAnswer(ctx(), alice());
49
50 const greenPull = async (branch: string, title: string, file = `${branch}.md`, author = getUserByName(app.db, "bot")!) => {
51 await commitToBranch(app, alice(), repo, {
52 branch,
53 base: "main",
54 message: title,
55 files: [{ path: file, content: `${title}\n` }],
56 });
57 const opened = await openPull(app, author, repo, {
58 title,
59 body: "",
60 baseBranch: "main",
61 headBranch: branch,
62 });
63 if (!opened.ok) throw new Error(String(opened.error));
64 const pull = opened.value;
65 const run = createRun(app.db, {
66 repoId: repo.id,
67 kind: "check",
68 issueId: pull.id,
69 env: `pull-${pull.number}`,
70 commitOid: pull.headOid,
71 reason: "pull",
72 });
73 claimRun(app.db, run.id);
74 finishRun(app.db, run.id, { state: "ok", summary: "ok" });
75 return pull;
76 };
77
78 beforeAll(async () => {
79 dataDir = await mkdtemp(join(tmpdir(), "forge-inbox-"));
80 app = createApp({ dataDir, port: 0 });
81 const joined = await signUp(app, {
82 username: "alice",
83 email: "[email protected]",
84 password: PASSWORD,
85 });
86 if (!joined.ok) throw new Error(String(joined.error));
87 const made = await createRepo(app, alice(), { name: "garden", visibility: "public" });
88 if (!made.ok) throw new Error(String(made.error));
89 repo = made.value;
90 await commitToBranch(app, alice(), repo, {
91 message: "seed",
92 files: [{ path: "README.md", content: "# garden\n" }],
93 });
94 await createAgent(app, alice(), { username: "bot" });
95 addToCrew(app, alice(), repo, "bot");
96 await createAgent(app, alice(), { username: "juniper" });
97 addToCrew(app, alice(), repo, "juniper");
98 const juniper = getUserByName(app.db, "juniper")!;
99 setCrewRole(app.db, repo.id, juniper.id, "reviewer");
100 }, 30_000);
101
102 afterAll(async () => {
103 await rm(dataDir, { recursive: true, force: true });
104 });
105
106 test("an agent's green pull with no review is the crew's, then the owner's once approved", async () => {
107 const pull = await greenPull("bot/1-thing", "Bot did a thing");
108 let page = await home();
109 expect(page).toContain("The crew's · 1");
110 expect(page).toContain("waiting for juniper&#39;s review");
111 expect(page).not.toContain(`id="ask-look:${pull.id}"`);
112 let list = await answer();
113 expect(list.rows).toHaveLength(0);
114 expect(list.crew[0]?.waitingFor).toBe("waiting for juniper's review");
115 expect(list.crew[0]?.part).toBe("crew");
116 expect(list.inbox.map((r) => r.part)).toEqual(["crew"]);
117 expect(page).toContain("All fine");
118 expect(askCountFor(ctx(), alice())).toBe(0);
119
120 const juniper = getUserByName(app.db, "juniper")!;
121 submitReview(app.db, {
122 issueId: pull.id,
123 authorId: juniper.id,
124 state: "approved",
125 commitOid: pull.headOid,
126 });
127 page = await home();
128 expect(page).not.toContain("The crew's");
129 expect(page).toContain(`id="ask-look:${pull.id}"`);
130 expect(page).toContain("ready to land");
131 list = await answer();
132 expect(list.crew).toHaveLength(0);
133 expect(list.rows[0]?.waitingFor).toBe("ready to land");
134 expect(list.rows[0]?.part).toBe("yours");
135 expect(page).toContain("1 thing needs you");
136 // Two looks in one repository are one row; the next test reads its own pull alone.
137 setIssueState(app.db, pull.id, "closed");
138 });
139
140 test("a reviewer who declines hands the pull to the owner too", async () => {
141 const pull = await greenPull("bot/2-other", "Bot did another");
142 expect(await home()).not.toContain(`id="ask-look:${pull.id}"`);
143 const juniper = getUserByName(app.db, "juniper")!;
144 submitReview(app.db, {
145 issueId: pull.id,
146 authorId: juniper.id,
147 state: "changes_requested",
148 commitOid: pull.headOid,
outdated

After changes_requested, the owner sees this pull as "ready to land". The reviewer just said it isn't. Give it its own waitingFor (or keep it with the crew), and assert the wording here.

149 });
150 const page = await home();
151 expect(page).toContain(`id="ask-look:${pull.id}"`);
152 expect((await answer()).rows.find((r) => r.link.endsWith(`/${pull.number}`))?.waitingFor).toBe(
153 "changes requested by juniper",
154 );
155 });
156
157 test("a person's own conflicting pull is not the crew's", async () => {
158 const pull = await greenPull("alice/4-mine", "Alice clashes", "README.md", alice());
159 await commitToBranch(app, alice(), repo, {
160 message: "main edits readme again",
161 files: [{ path: "README.md", content: "# garden, main again\n" }],
162 });
163 await sweepStaleAsks(app);
164 const list = await answer();
165 expect(list.crew.map((r) => r.link)).not.toContain(
166 `/${repo.ownerName}/${repo.name}/changes/${pull.number}`,
167 );
168 });
169
170 test("a conflicted pull says conflicts with main, and is not the owner's to land", async () => {
171 const pull = await greenPull("bot/3-clash", "Bot clashes", "README.md");
172 await commitToBranch(app, alice(), repo, {
173 message: "main edits readme",
174 files: [{ path: "README.md", content: "# garden, main\n" }],
175 });
176 await sweepStaleAsks(app);
177 const page = await home();
178 expect(page).not.toContain(`id="ask-look:${pull.id}"`);
179 expect(page).toContain("conflicts with main");
180 expect((await answer()).crew.map((r) => r.waitingFor)).toContain("conflicts with main");
181 });
182
183 test("assigned work is in the same list and the same count", async () => {
184 const before = (await answer()).inbox.length;
185 const made = createIssue(app.db, {
186 repoId: repo.id,
187 authorId: alice().id,
188 title: "Water the beds",
189 });
190 if (!made.ok) throw new Error(String(made.error));
191 setAssignee(app.db, made.value.id, alice().id);
192 const list = await answer();
193 expect(list.assigned[0]?.waitingFor).toBe("assigned to you");
194 expect(list.inbox.length).toBe(before + 1);
195 const page = await home();
196 expect(page).toContain("Water the beds");
197 expect(askCountFor(ctx(), alice())).toBe(2);
198 });
199
200 test("select-all ships with the page even when nothing could be ticked yet, so a live refresh keeps it", () => {
201 expect(needsYouSection(ctx(), alice()).scriptJs).toContain("data-select-all");
202 });
203 });
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-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-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/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