From 04c89ef01fc258c91c899a37ea59ecd402caabc7 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:26:14 +0000 Subject: [PATCH] New dashboard Items page behind ui_v2: needs an answer, started, handled automatically and not started, ordered by weight and work rank; Backlog and closed views; security, held outside, stuck, duplicates and area filters; word and meaning search; ticked items fill the command box with the list form and run through /api/commands. Unclear answers count per item on Home and Items, which follow a new workflow-events topic that does not wake the planner --- src/dash/api/index.ts | 2 + src/dash/api/items.ts | 2 +- src/dash/api/maintain.ts | 209 ++++++++++++- src/live.ts | 2 + src/runner/autopilot.ts | 2 +- test/maintain-items.test.ts | 23 ++ web/src/api/client.ts | 7 + web/src/api/http.ts | 6 +- web/src/api/mock/maintainMock.ts | 86 ++++- web/src/api/topics.ts | 5 +- web/src/api/types.ts | 65 ++++ web/src/modules/maintain/items/index.tsx | 18 ++ web/src/modules/maintain/items/views.tsx | 382 +++++++++++++++++++++++ web/src/registry/index.ts | 6 +- 14 files changed, 794 insertions(+), 21 deletions(-) create mode 100644 test/maintain-items.test.ts create mode 100644 web/src/modules/maintain/items/index.tsx create mode 100644 web/src/modules/maintain/items/views.tsx diff --git a/src/dash/api/index.ts b/src/dash/api/index.ts index c30df50d..d6b6886c 100644 --- a/src/dash/api/index.ts +++ b/src/dash/api/index.ts @@ -474,6 +474,8 @@ export function apiRoutes(opts: ApiOptions = {}): Route[] { post("/api/mcp/tokens/revoke", mcp.revoke), // The new dashboard (ui_v2). scoped(get("/api/maintain/home", maintain.home)), + // The new Items page: four lists of the open items, the Backlog or the closed items, with filters and search. + scoped(get("/api/maintain/items", maintain.items)), get("/api/me/settings", userSettings.settings), { method: "PUT", pattern: "/api/me/settings", handler: ok(userSettings.setSettings) }, get("/api/runners", runners.list), diff --git a/src/dash/api/items.ts b/src/dash/api/items.ts index 4477e3dd..5fe3fdc5 100644 --- a/src/dash/api/items.ts +++ b/src/dash/api/items.ts @@ -48,7 +48,7 @@ const hitsScored = (db: Db, fts: Search) => db.k.selectFrom( .as("m")) .select(["m.rid", (eb) => eb.fn.min("m.score").as("score")]).groupBy("m.rid"); -const textCond = (db: Db, fts: Search): Cond => (eb) => eb(kx.rowid("items", "i"), "in", hitRids(db, fts)); +export const textCond = (db: Db, fts: Search): Cond => (eb) => eb(kx.rowid("items", "i"), "in", hitRids(db, fts)); const STATUSES: SettledStatus[] = ["settled", "waiting", "disagree", "unclassified"]; const STATES: Record = { open: "OPEN", closed: "CLOSED", merged: "MERGED" }; diff --git a/src/dash/api/maintain.ts b/src/dash/api/maintain.ts index a55e5be5..cc225caa 100644 --- a/src/dash/api/maintain.ts +++ b/src/dash/api/maintain.ts @@ -2,14 +2,15 @@ // (src/workflow/store.ts) of the repos the reader may see, narrowed to the picked project. An item needs an answer when its // recommendation is open or its last answer was unclear; it counts for the reader only where they may act on the repo // (mayRunRepo: operators on every repo, maintainers where GitHub grants write). Text is built by src/workflow/status.ts. -import type { MaintainHome, MaintainRow, MaintainRunnerLine } from "../../../web/src/api/types.ts"; +import type { Expression, SelectQueryBuilder, SqlBool } from "kysely"; +import type { MaintainHome, MaintainItemGroup, MaintainItemRow, MaintainItems, MaintainItemsFilter, MaintainItemsShow, MaintainRow, MaintainRunnerLine } from "../../../web/src/api/types.ts"; import { t } from "../../i18n/index.ts"; import { listHelpers } from "../../remote/helpers.ts"; import { inferenceMode } from "../../remote/mode.ts"; import { readyRunners } from "../../remote/queue-view.ts"; import { stateLine, weightLabel } from "../../workflow/status.ts"; import { liveWorkflows } from "../../workflow/store.ts"; -import type { ItemWorkflow } from "../../workflow/types.ts"; +import type { ItemWorkflow, WorkflowEventKind } from "../../workflow/types.ts"; import { mayRunRepo } from "../repo-access.ts"; import type { Req } from "../types.ts"; import { problems } from "./home.ts"; @@ -17,27 +18,38 @@ import { stopped } from "./needs.ts"; import { canSeeInternals } from "./staff.ts"; import { hiddenRepos, visibleRepos } from "./visible.ts"; import type { Db } from "../../db/index.ts"; -import { inList, refIn } from "../../db/kx.ts"; +import { inList, refIn, type AnyEb } from "../../db/kx.ts"; +import { parseSearch } from "../../db/search.ts"; +import { latestRun, settledOnExpr, settledTable } from "../../classify/settled.ts"; +import { groupHeldExpr } from "../../dupes/held.ts"; +import { quietExprFor } from "../../security/quiet.ts"; +import { statusFromItem } from "../../core/item-status.ts"; +import type { PlanView } from "../../core/plan-cache.ts"; +import { WEIGHT_NORMAL } from "../../workflow/types.ts"; +import { HttpError } from "../server/util.ts"; +import { itemState } from "./shown.ts"; +import { textCond } from "./items.ts"; +import { readerOf, statusFor } from "./reader.ts"; +import { phaseExpr, type ItemPhase, type ItemStatus } from "./home-types.ts"; -/** Workflow ids whose latest event is an unclear answer. */ -async function unclear(db: Db, ids: number[]): Promise> { - if (!ids.length) return new Set(); - const rows = await db.all(db.k.selectFrom("main.workflow_events").select(["workflow_id", "kind"]).where(inList(db, "workflow_id", ids)).orderBy("id")); - const last = new Map(); - for (const r of rows) if (r.workflow_id !== null) last.set(r.workflow_id, r.kind); - return new Set([...last].filter(([, kind]) => kind === "ambiguous").map(([id]) => id)); +/** The kind of each item's latest workflow event, keyed `repo#number`, for items of `repos`. */ +async function lastEvents(db: Db, repos: string[]): Promise> { + if (!repos.length) return new Map(); + const rows = await db.all(db.k.selectFrom("main.workflow_events as e").select(["e.repo", "e.number", "e.kind"]) + .where("e.id", "in", (eb) => eb.selectFrom("main.workflow_events as m").select((m) => m.fn.max("m.id").as("id")).where(inList(db, "m.repo", repos)).groupBy(["m.repo", "m.number"]))); + return new Map(rows.map((r) => [`${r.repo}#${r.number}`, r.kind as WorkflowEventKind])); } async function rowsOf(db: Db, wfs: ItemWorkflow[]): Promise { if (!wfs.length) return []; - const [unclearIds, items] = await Promise.all([ - unclear(db, wfs.map((w) => w.id)), + const [last, items] = await Promise.all([ + lastEvents(db, [...new Set(wfs.map((w) => w.repo))]), db.all(db.k.selectFrom("main.items as i").select(["i.repo", "i.number", "i.title", "i.author"]).where(refIn(db, "i", wfs.map((w) => [w.repo, w.number] as const)))), ]); const byRef = new Map(items.map((i) => [`${i.repo}#${i.number}`, i])); return wfs.map((w) => { const it = byRef.get(`${w.repo}#${w.number}`); - const isUnclear = unclearIds.has(w.id); + const isUnclear = last.get(`${w.repo}#${w.number}`) === "ambiguous"; const open = w.state === "recommending" && w.rec !== null; return { repo: w.repo, number: w.number, kind: w.kind, title: it?.title ?? `${w.repo}#${w.number}`, author: it?.author ?? null, entry: w.entry, @@ -80,3 +92,174 @@ export async function home(db: Db, req: Req): Promise { const mine = rows.filter((r) => !needs.includes(r) && (byMe(r.startedBy) || byMe(r.approvedBy) || byMe(r.stoppedBy))); return { needs, mine, waiting: [], running: [], runner, attention }; } + +// ---- GET /api/maintain/items: the new Items page ------------------------------------------------------------------------ +// Open items of the repos the reader may see, in four lists (groupOf), each ordered by priority: the workflow weight, then the +// work rank (src/rank). A started item's line comes from its workflow row; an item nobody started shows the pipeline's status +// line (the plan view), veiled for the reader as on every other list. Grouping runs here over the open items' narrow columns; +// only the rows sent are read in full. Closed items are read newest first, one page at a time. + +/** Plan phases in which AutoCraft works an item that nobody started. */ +const WORKING_PHASES: ReadonlySet = new Set(["Review", "Fixing", "Verifying", "In queue"]); +const SHOWS: readonly MaintainItemsShow[] = ["open", "backlog", "closed"]; +const FILTERS: readonly MaintainItemsFilter[] = ["security", "outside", "stuck", "duplicates"]; +const STAFF_FILTERS: readonly MaintainItemsFilter[] = ["security", "stuck"]; +const GROUPS: readonly MaintainItemGroup[] = ["needs", "started", "automatic", "rest", "backlog", "done"]; +const NO_AREA = "none"; +const LIMIT_DEFAULT = 50; +const LIMIT_MAX = 500; +const REFS_MAX = 100; + +/** Which list an item goes in. An answer awaited comes first, then a live workflow; a Backlog item leaves the active lists. */ +export function groupOf(x: { open: boolean; live: boolean; waits: boolean; backlog: boolean; phase: ItemPhase }): MaintainItemGroup { + if (!x.open) return "done"; + if (x.waits) return "needs"; + if (x.live) return "started"; + if (x.backlog) return "backlog"; + return WORKING_PHASES.has(x.phase) ? "automatic" : "rest"; +} + +/** Whether an item waits for an answer: its live workflow has an open recommendation, or the last thing said to it was unclear. */ +export const waitsForAnswer = (wf: Pick | null, lastEvent: WorkflowEventKind | undefined): boolean => + lastEvent === "ambiguous" || (wf !== null && wf.state === "recommending" && wf.rec !== null); + +const listParam = (q: URLSearchParams, key: string): string[] => q.getAll(key).flatMap((v) => v.split(",")).map((s) => s.trim()).filter(Boolean); + +type Cond = (eb: AnyEb) => Expression; +type Base = { repo: string; number: number; kind: string; state: string; title: string | null; author: string | null; updated_at: string | null; merged_at: string | null; closed_at: string | null; score: number | null; phase: ItemPhase; plan_state: string | null; plan_item_state: string | null }; +type Placed = Base & { group: MaintainItemGroup; wf: ItemWorkflow | null; unclear: boolean }; + +const PLAN_BACKLOG = new Set(["backlog", "held-backlog"]); + +export async function items(db: Db, req: Req): Promise { + const q = req.query; + const show = (q.get("show") ?? "open") as MaintainItemsShow; + if (!SHOWS.includes(show)) throw new HttpError(400, "show must be open, backlog or closed"); + const staff = canSeeInternals(req); + const filters = listParam(q, "filter") as MaintainItemsFilter[]; + for (const f of filters) { + if (!FILTERS.includes(f)) throw new HttpError(400, "filter must be security, outside, stuck or duplicates"); + if (!staff && STAFF_FILTERS.includes(f)) throw new HttpError(403, "only operators and maintainers filter by security findings or stuck items"); + } + const areas = listParam(q, "area"); + const text = (q.get("q") ?? "").trim(); + const fts = text ? parseSearch(text) : null; + const refs = listParam(q, "refs").slice(0, REFS_MAX); + const refPairs = refs.map((r) => [r.slice(0, r.lastIndexOf("#")), Number(r.slice(r.lastIndexOf("#") + 1))] as const); + if (refPairs.some(([repo, n]) => !repo || !Number.isInteger(n))) throw new HttpError(400, "refs must be repo#number"); + const sort = q.get("sort") ?? "priority"; + if (sort !== "priority" && sort !== "updated") throw new HttpError(400, "sort must be priority or updated"); + const limit = Math.min(LIMIT_MAX, Math.max(1, Number(q.get("limit")) || LIMIT_DEFAULT)); + const counts = Object.fromEntries(GROUPS.map((g) => [g, 0])) as Record; + + const visible = await visibleRepos(db, req); + if (!visible.length || (q.has("refs") && !refPairs.length)) return { rows: [], counts }; + const run = filters.includes("security") ? await latestRun(db) : null; + if (run) await settledTable(db, run); + + const conds: Cond[] = [() => inList(db, "i.repo", visible), (eb) => (show === "closed" ? eb("i.state", "<>", "OPEN") : eb("i.state", "=", "OPEN"))]; + if (refPairs.length) conds.push(() => refIn(db, "i", refPairs)); + if (fts) conds.push(textCond(db, fts)); + const same = (eb: AnyEb, t: string) => eb.and([eb(eb.ref(`${t}.repo`), "=", eb.ref("i.repo")), eb(eb.ref(`${t}.number`), "=", eb.ref("i.number"))]); + for (const f of filters) { + if (f === "outside") conds.push((eb) => eb.exists(eb.selectFrom("main.outside_holds as oh").select(eb.lit(1).as("one")).where((w) => same(w, "oh")))); + if (f === "stuck") conds.push((eb) => eb.exists(eb.selectFrom("main.liveness_items as li").select(eb.lit(1).as("one")).where((w) => same(w, "li")).where("li.verdict", "=", "stuck"))); + if (f === "duplicates") conds.push((eb) => groupHeldExpr(db, eb, "i")); + if (f === "security") conds.push((eb) => eb.and([ + eb.exists(eb.selectFrom("main.item_settled as s").select(eb.lit(1).as("one")).where((w) => settledOnExpr(w, run, "s")).where("s.security", "=", 1)), + eb.not(quietExprFor(db, eb, "i.repo", "i.number")), + ])); + } + if (areas.length) { + const named = areas.filter((a) => a !== NO_AREA); + conds.push((eb) => eb.or([ + ...(named.length ? [eb.exists(eb.selectFrom("main.item_areas as ia").select(eb.lit(1).as("one")).where((w) => same(w, "ia")).where("ia.area", "in", named))] : []), + ...(areas.includes(NO_AREA) ? [eb.not(eb.exists(eb.selectFrom("main.item_areas as ia").select(eb.lit(1).as("one")).where((w) => same(w, "ia")).where("ia.area", "is not", null)))] : []), + ])); + } + + const base = db.k.selectFrom("main.items as i") + .leftJoin("main.item_plans as p", (j) => j.onRef("p.repo", "=", "i.repo").onRef("p.number", "=", "i.number")) + .leftJoin("main.item_rank as r", (j) => j.onRef("r.repo", "=", "i.repo").onRef("r.number", "=", "i.number")); + const where = >(qb: QB): QB => conds.reduce((acc, c) => acc.where(c) as QB, qb); + const cols = (qb: typeof base) => qb.select(["i.repo", "i.number", "i.kind", "i.state", "i.title", "i.author", "i.updated_at", "i.merged_at", "i.closed_at", "r.score", + "p.state as plan_state", "p.item_state as plan_item_state", (eb) => phaseExpr(db, eb).as("phase")]); + + let placed: Placed[]; + if (show === "closed") { + const [n, got] = await Promise.all([ + db.get(where(base.select((eb) => eb.fn.countAll().as("n")))), + db.all(where(cols(base)).orderBy((eb) => eb.fn.coalesce("i.updated_at", eb.val("")), "desc").orderBy("i.repo").orderBy("i.number", "desc").limit(refPairs.length ? REFS_MAX : limit)), + ]); + counts.done = Number(n?.n ?? 0); + placed = (got as Base[]).map((b) => ({ ...b, group: "done", wf: null, unclear: false })); + } else { + const [got, live, last] = await Promise.all([db.all(where(cols(base))) as Promise, liveWorkflows(db), lastEvents(db, visible)]); + const wfOf = new Map(live.map((w) => [`${w.repo}#${w.number}`, w])); + placed = got.map((b) => { + const key = `${b.repo}#${b.number}`; + const wf = wfOf.get(key) ?? null; + const ev = last.get(key); + const waits = waitsForAnswer(wf, ev); + const backlog = ev === "backlog" || PLAN_BACKLOG.has(b.plan_state ?? "") || b.plan_item_state === "held-backlog"; + return { ...b, wf, unclear: ev === "ambiguous", group: groupOf({ open: true, live: wf !== null, waits, backlog, phase: b.phase }) }; + }).filter((p) => (show === "backlog" ? p.group === "backlog" : p.group !== "backlog")); + for (const p of placed) counts[p.group]++; + } + + // Semantic hits keep their order; otherwise the heaviest first, then the work rank, then the latest change. + const hitAt = new Map(refs.map((r, i) => [r, i])); + const updated = (a: Placed, b: Placed) => ((a.updated_at ?? "") < (b.updated_at ?? "") ? 1 : (a.updated_at ?? "") > (b.updated_at ?? "") ? -1 : 0); + const order = (a: Placed, b: Placed): number => { + if (hitAt.size) return (hitAt.get(`${a.repo}#${a.number}`) ?? 0) - (hitAt.get(`${b.repo}#${b.number}`) ?? 0); + if (sort === "updated") return updated(a, b); + return (b.wf?.weight ?? WEIGHT_NORMAL) - (a.wf?.weight ?? WEIGHT_NORMAL) || (b.score ?? -1) - (a.score ?? -1) || updated(a, b) || a.repo.localeCompare(b.repo) || b.number - a.number; + }; + const page = GROUPS.flatMap((g) => placed.filter((p) => p.group === g).sort(order).slice(0, limit)); + return { rows: await itemRows(db, req, page, staff), counts }; +} + +/** The rows sent: status lines, signals and whether the reader may send commands on each repo. */ +async function itemRows(db: Db, req: Req, page: Placed[], staff: boolean): Promise { + if (!page.length) return []; + const pairs = page.map((p) => [p.repo, p.number] as const); + const repos = [...new Set(page.map((p) => p.repo))]; + const [views, outside, stuck, dupes, areas, reader, may] = await Promise.all([ + db.all(db.k.selectFrom("main.item_plans as p").select(["p.repo", "p.number", "p.view"]).where(refIn(db, "p", pairs))), + db.all(db.k.selectFrom("main.outside_holds as o").select(["o.repo", "o.number"]).where(refIn(db, "o", pairs))), + staff ? db.all(db.k.selectFrom("main.liveness_items as l").select(["l.repo", "l.number"]).where(refIn(db, "l", pairs)).where("l.verdict", "=", "stuck")) : [], + db.all(db.k.selectFrom("main.items as i").select(["i.repo", "i.number"]).where(refIn(db, "i", pairs)).where((eb) => groupHeldExpr(db, eb, "i"))), + db.all(db.k.selectFrom("main.item_areas as a").select(["a.repo", "a.number", "a.area"]).where(refIn(db, "a", pairs)).where("a.area", "is not", null)), + readerOf(db, req), + req.user.role === "viewer" ? repos.map(() => false) : Promise.all(repos.map((r) => mayRunRepo(req.user, r))), + ]); + const key = (r: { repo: string; number: number }) => `${r.repo}#${r.number}`; + const keys = (rs: { repo: string; number: number }[]) => new Set(rs.map(key)); + const [outsideSet, stuckSet, dupeSet] = [keys(outside), keys(stuck), keys(dupes)]; + const areaOf = new Map(areas.map((a) => [key(a), a.area])); + const viewOf = new Map(views.map((v) => [key(v), v.view])); + const mayRepo = new Map(repos.map((r, i) => [r, may[i]!])); + return page.map((p): MaintainItemRow => { + const wf = p.wf; + let status: ItemStatus | null = null; + if (!wf) { + let view: PlanView | undefined; + try { view = viewOf.has(key(p)) ? (JSON.parse(viewOf.get(key(p))!) as PlanView) : undefined; } catch { /* a malformed view counts as none */ } + status = view?.status ? statusFor(reader, p.repo, p.number, view.status) : statusFromItem(p, p.updated_at ?? ""); + } + return { + repo: p.repo, number: p.number, kind: p.kind === "pr" ? "pr" : "issue", state: itemState(p.state), title: p.title ?? `${p.repo}#${p.number}`, author: p.author, + group: p.group, line: wfLine(wf, p.unclear), status, blocked: wf?.state === "blocked", weight: wf ? weightLabel(wf.weight) : null, + startedBy: wf?.startedBy ?? null, approvedBy: wf?.approvedBy ?? null, stoppedBy: wf?.stoppedBy ?? null, + duplicate: dupeSet.has(key(p)), outside: outsideSet.has(key(p)), stuck: stuckSet.has(key(p)), area: areaOf.get(key(p)) ?? null, + may: mayRepo.get(p.repo) ?? false, updatedAt: p.updated_at ?? "", + }; + }); +} + +/** As on Home: an unclear last answer, else a started item's open recommendation or where it stands; null for an unstarted item. */ +function wfLine(wf: ItemWorkflow | null, unclear: boolean): string | null { + if (unclear) return t("Waiting for a clear answer"); + if (!wf) return null; + return wf.state === "recommending" && wf.rec !== null ? wf.rec.text : stateLine(wf); +} diff --git a/src/live.ts b/src/live.ts index 5f187151..83feac5d 100644 --- a/src/live.ts +++ b/src/live.ts @@ -72,6 +72,8 @@ export const TOPIC_TABLES: Record = { fasttrack: [{ table: "fast_track" }], // Started items of the maintainer workflow: entry, approval, weight, plan, blocker, recommendation. Planner input. workflows: [{ table: "item_workflows" }], + // What people said to items of the maintainer workflow: an unclear answer lives only here. Lists only; not planner input. + "workflow-events": [{ table: "workflow_events" }], // An operator released an outside-author item from its hold: the planner plans for it at once. outside: [{ table: "outside_released" }, { table: "stage_trips", when: "new.stage = 'outside-surge'" }], // The planner's Plan cache; its own output, so the planner does not plan again for it. diff --git a/src/runner/autopilot.ts b/src/runner/autopilot.ts index 2e3f3f6b..24965c4a 100644 --- a/src/runner/autopilot.ts +++ b/src/runner/autopilot.ts @@ -243,7 +243,7 @@ function repoAllows(plans: PlanSet, repo: string, want: Want): boolean { } /** Topics whose changes call for a plan: content the stages read. Job logs, usage, agent runs, sandbox environments and tasks, audit entries the item-trace bookkeeping and the limits topic (its tables are already read through the jobs topic) do not. */ -export const INPUT_TOPICS = TOPICS.filter((t) => !["jobs", "usage", "agents", "envs", "tasks", "workspaces", "access", "github", "plans", "trace", "flow", "limits", "claims", "conversation-includes", "decision-choices", "held-followups", "decision-snooze", "security", "discord", "discord-links", "downloads", "build-features", "pr-builds", "nightly", "remote-helpers", "remote-queue", "rank-inputs"].includes(t)); +export const INPUT_TOPICS = TOPICS.filter((t) => !["jobs", "usage", "agents", "envs", "tasks", "workspaces", "access", "github", "plans", "trace", "flow", "limits", "claims", "conversation-includes", "decision-choices", "held-followups", "decision-snooze", "security", "discord", "discord-links", "downloads", "build-features", "pr-builds", "nightly", "remote-helpers", "remote-queue", "rank-inputs", "workflow-events"].includes(t)); /** User-local mode: the Task Runners that could take calls (takerSignature). Work a pool left for want of a taker waits on it. */ const takersOf = async (db: Db): Promise => { diff --git a/test/maintain-items.test.ts b/test/maintain-items.test.ts new file mode 100644 index 00000000..7e55f553 --- /dev/null +++ b/test/maintain-items.test.ts @@ -0,0 +1,23 @@ +// The new Items page's lists (src/dash/api/maintain.ts): what needs an answer, and what the Backlog takes out of the active lists. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { groupOf, waitsForAnswer } from "../src/dash/api/maintain.ts"; + +test("an open recommendation or an unclear answer needs an answer; a Backlog item leaves the active lists", () => { + const rec = { text: "Fix 1, then merge?", parts: { fix: [1], drop: [] }, merges: true }; + const at = (x: { live?: boolean; waits?: boolean; backlog?: boolean }) => + groupOf({ open: true, live: false, waits: false, backlog: false, phase: "Review", ...x }); + + const recommending = waitsForAnswer({ state: "recommending", rec }, "started"); + assert.equal(at({ live: true, waits: recommending }), "needs"); + // An unclear answer counts whether or not the item was started, and wins over a running workflow. + assert.equal(at({ waits: waitsForAnswer(null, "ambiguous") }), "needs"); + assert.equal(at({ live: true, waits: waitsForAnswer({ state: "running", rec: null }, "ambiguous") }), "needs"); + // A later event clears it. + assert.equal(at({ live: true, waits: waitsForAnswer({ state: "running", rec: null }, "answered") }), "started"); + + const active = ["needs", "started", "automatic", "rest"]; + assert.ok(active.includes(at({}))); + assert.equal(at({ backlog: true }), "backlog"); + assert.ok(!active.includes(groupOf({ open: true, live: false, waits: false, backlog: true, phase: "Triage" }))); +}); diff --git a/web/src/api/client.ts b/web/src/api/client.ts index 3a00a358..d3c4ba6d 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -21,6 +21,9 @@ import type { DiscordSetup, Home, MaintainHome, + MaintainItems, + MaintainItemsQuery, + MaintainCommandResult, OpenDecisionCounts, ItemPageData, ItemStatusFilter, @@ -250,6 +253,10 @@ export interface Api { maintain: { /** Home: what waits for the reader's answer, what they started, their Task Runner line and problems; the page's project narrows it. */ home(): Promise; + /** Items: four lists of the open items (or the Backlog, or the closed items) with filters, search and the priority order; the page's project narrows it. */ + items(query: MaintainItemsQuery): Promise; + /** Sends a command written in the dashboard's box; the list form (`merge:` then items) names the items. */ + command(text: string): Promise; }; /** The item page's AutoCraft and GitHub sides: status, reviews with earlier ones, result cards, history, GitHub's own sections. `since` as for `itemTrace`. */ itemPage(repo: RepoName, number: number, since?: string): Promise; diff --git a/web/src/api/http.ts b/web/src/api/http.ts index 0c791c3e..5338641d 100644 --- a/web/src/api/http.ts +++ b/web/src/api/http.ts @@ -193,7 +193,11 @@ export function createHttpApi(): Api { items: (f) => get(`/api/items${itemQuery(f)}`), progress: () => get("/api/progress"), home: () => get("/api/home"), - maintain: { home: () => get("/api/maintain/home") }, + maintain: { + home: () => get("/api/maintain/home"), + items: (q) => get(`/api/maintain/items${qs({ ...q, filters: undefined, filter: q.filters?.join(","), areas: undefined, area: q.areas?.join(","), refs: q.refs?.join(",") })}`), + command: (text) => post("/api/commands", { text }), + }, itemPage: (repo, number, since) => get(`/api/items/${encodeURIComponent(repo)}/${number}/page${qs({ since })}`), itemPeek: (repo, number) => get(`/api/items/${encodeURIComponent(repo)}/${encodeURIComponent(String(number))}/peek`), itemStatusList: (f) => get(`/api/items/status${qs({ q: f.q, phase: f.phase, kind: f.kind, repo: f.repo?.join(","), area: f.area?.join(","), discord: f.discord ? "1" : undefined, cursor: f.cursor })}`), diff --git a/web/src/api/mock/maintainMock.ts b/web/src/api/mock/maintainMock.ts index 7ada9662..51ee34e3 100644 --- a/web/src/api/mock/maintainMock.ts +++ b/web/src/api/mock/maintainMock.ts @@ -1,6 +1,6 @@ -// The new Home's mock read: started items of several repos, so each role sees what it may act on. +// The new Home's and Items page's mock reads: started items of several repos, so each role sees what it may act on. import type { Api } from "../client"; -import type { MaintainHome, MaintainRow, User } from "../types"; +import type { ItemPhase, MaintainCommandResult, MaintainHome, MaintainItemGroup, MaintainItemRow, MaintainItems, MaintainItemsQuery, MaintainRow, User } from "../types"; import { requestProject } from "../scope"; import { NOW } from "./fixtures"; @@ -18,9 +18,91 @@ const ROWS: MaintainRow[] = [ row({ repo: "photocraft", number: 840, title: "Selection tools: four changes", author: "pixel-wrangler", line: "Waiting: batch", entry: "merge", startedBy: "ochre-fox", approvedBy: "ochre-fox", updatedAt: ago(30) }), ]; +// ---- Items ---- + +type ItemSeed = Partial & Pick & { phase?: ItemPhase; waiting?: string | null; next?: string | null; rank?: number; sec?: boolean }; +const item = (s: ItemSeed): ItemSeed => s; +const ITEMS: ItemSeed[] = [ + ...ROWS.map((r, i) => item({ ...r, group: r.waits ? "needs" : "started", rank: 40 - i })), + item({ repo: "photocraft", number: 851, title: "Brush size slider jumps on high-DPI screens", author: "larkspur-dev", group: "automatic", phase: "In queue", waiting: "CI on the PR (4 of 5 checks done)", next: "merge when CI is green", area: "Canvas", rank: 30 }), + item({ repo: "designcraft", number: 461, title: "Guides menu shows twice after reload", author: "sable-ui", group: "automatic", phase: "Review", waiting: null, next: "review the PR", area: "Canvas", rank: 22 }), + item({ repo: "pdfcraft", number: 1204, kind: "issue", title: "Crash when placing an encrypted PDF page", author: "brushstroke42", group: "automatic", phase: "Fixing", waiting: null, next: "write the fix", area: "PDF import", rank: 35, sec: true }), + item({ repo: "photocraft", number: 866, kind: "issue", title: "Exported PNG loses the colour profile", author: "night-owl-77", group: "rest", phase: "Triage", rank: 28, area: "Export" }), + item({ repo: "photocraft", number: 867, kind: "issue", title: "Exported PNG drops the embedded colour profile", author: "palette-jo", group: "rest", phase: "Held", waiting: "the duplicate question", duplicate: true, area: "Export", rank: 27 }), + item({ repo: "wordcraft", number: 241, title: "Add a word count to the status bar", author: "first-timer-9", group: "rest", phase: "Held", waiting: "the author's daily limit", outside: true, area: "Text", rank: 12 }), + item({ repo: "filmcraft", number: 318, title: "Timeline thumbnails flicker while scrubbing", author: "quietgrid", group: "rest", phase: "Waiting for a person", waiting: "an answer to the scope question", stuck: true, rank: 18 }), + item({ repo: "deckcraft", number: 90, kind: "issue", title: "Speaker view should show the next slide", author: "rhea-m", group: "rest", phase: "Triage", rank: 8 }), + item({ repo: "vectorcraft", number: 512, title: "Boolean union leaves a hairline gap", author: "pixel-wrangler", group: "rest", phase: "Pipeline off", rank: 15, area: "Canvas" }), + item({ repo: "photocraft", number: 702, kind: "issue", title: "Support JPEG XL import", author: "brushstroke42", group: "backlog", phase: "Held", waiting: "the Backlog", rank: 5 }), + item({ repo: "designcraft", number: 390, title: "Ruler units follow the document setting", author: "sable-ui", group: "done", state: "merged", phase: "Merged", rank: 0 }), +]; + +const ZERO: Record = { needs: 0, started: 0, automatic: 0, rest: 0, backlog: 0, done: 0 }; +const ORDER: MaintainItemGroup[] = ["needs", "started", "automatic", "rest", "backlog", "done"]; +const WEIGHTS: Record = { urgent: 10, high: 8, low: 2 }; + +function itemsFor(me: User, query: MaintainItemsQuery): MaintainItems { + const repo = requestProject(); + const show = query.show ?? "open"; + const staff = me.role !== "viewer"; + if (!staff && query.filters?.some((f) => f === "security" || f === "stuck")) throw new Error("only operators and maintainers filter by security findings or stuck items"); + const text = query.q?.trim().toLowerCase(); + const hits = query.refs; + const shown = ITEMS.filter((s) => { + if (repo && s.repo !== repo) return false; + if (show === "closed" ? s.group !== "done" : show === "backlog" ? s.group !== "backlog" : s.group === "done" || s.group === "backlog") return false; + if (text && !`${s.repo}#${s.number} ${s.title}`.toLowerCase().includes(text)) return false; + if (hits && !hits.includes(`${s.repo}#${s.number}`)) return false; + for (const f of query.filters ?? []) { + if (f === "security" && !s.sec) return false; + if (f === "outside" && !s.outside) return false; + if (f === "stuck" && !s.stuck) return false; + if (f === "duplicates" && !s.duplicate) return false; + } + if (query.areas?.length && !query.areas.some((a) => (a === "none" ? !s.area : a === s.area))) return false; + return true; + }); + const weight = (s: ItemSeed) => (s.weight ? (WEIGHTS[s.weight] ?? 5) : 5); + const order = (a: ItemSeed, b: ItemSeed) => + query.sort === "updated" ? (b.updatedAt ?? "").localeCompare(a.updatedAt ?? "") : weight(b) - weight(a) || (b.rank ?? 0) - (a.rank ?? 0); + const counts = { ...ZERO }; + for (const s of shown) counts[s.group]++; + const limit = query.limit ?? 50; + const rows = ORDER.flatMap((g) => shown.filter((s) => s.group === g).sort(order).slice(0, limit)).map((s): MaintainItemRow => { + const started = s.group === "needs" || s.group === "started"; + const { phase, waiting, next, rank: _r, sec: _s, ...rest } = s; + return { + kind: "pr", state: "open", author: null, line: null, status: null, blocked: false, weight: null, startedBy: null, approvedBy: null, stoppedBy: null, + duplicate: false, outside: false, area: null, updatedAt: ago(60 + (s.number % 300)), ...rest, + ...(started ? {} : { status: { phase: phase ?? "Triage", waiting: staff ? (waiting ?? null) : null, next: next ?? null, since: ago(90) } }), + stuck: staff && !!s.stuck, + may: me.runRepos.includes(s.repo), + }; + }); + return { rows, counts }; +} + +function commandFor(me: User, text: string): MaintainCommandResult { + const m = /^([^:\n]+):([\s\S]*)$/.exec(text.trim()); + const refs = m ? m[2]!.split(/[\s,]+/).filter(Boolean) : []; + const words = (m ? m[1]! : text).trim(); + if (!m || !refs.length || !/^(review|fix-up|implement|merge|backlog|close|stop)\b/i.test(words)) { + const line = `Not run: "${text.trim().split("\n")[0]}" is not clear. Write a command, then a colon and the items, e.g. "merge: photocraft#123".`; + return { items: [], lines: [line] }; + } + const items = refs.map((ref) => { + const [repo, n] = ref.split("#"); + const ok = me.runRepos.includes(repo ?? ""); + return { repo: repo ?? "", number: Number(n), outcome: ok ? ("run" as const) : ("refused" as const), line: ok ? `${ref}: ${words} (by ${me.login})` : `${me.login} has no write access to ${repo}.`, workflowId: ok ? 1 : null }; + }); + return { items, lines: items.map((i) => i.line) }; +} + export function createMaintainMock(me: User): Pick { return { maintain: { + items: (query) => new Promise((r, j) => setTimeout(() => { try { r(structuredClone(itemsFor(me, query))); } catch (e) { j(e); } }, 60)), + command: (text) => new Promise((r) => setTimeout(() => r(commandFor(me, text)), 120)), async home(): Promise { const repo = requestProject(); const rows = ROWS.filter((r) => !repo || r.repo === repo); diff --git a/web/src/api/topics.ts b/web/src/api/topics.ts index bd185df3..029b47d8 100644 --- a/web/src/api/topics.ts +++ b/web/src/api/topics.ts @@ -7,7 +7,7 @@ */ export type Topic = | "repos" | "sync" | "items" | "ranks" | "stages" | "flow" | "checks" | "classify" | "dupes" | "decisions" | "reviews" | "queue" | "jobs" | "usage" | "accounts" | "agents" - | "envs" | "tasks" | "workspaces" | "actions" | "fixes" | "verify" | "postmerge" | "access" | "settings" | "trace" | "github" | "fasttrack" | "outside" | "plans" | "conversations" | "held-followups" | "conversation-includes" | "decision-choices" | "decision-snooze" | "steps" | "mainci" | "limits" | "claims" | "preapprovals" | "security" | "discord" | "discord-links" | "downloads" | "build-features" | "pr-builds" | "nightly" | "remote-helpers" | "remote-queue" | "workflows"; + | "envs" | "tasks" | "workspaces" | "actions" | "fixes" | "verify" | "postmerge" | "access" | "settings" | "trace" | "github" | "fasttrack" | "outside" | "plans" | "conversations" | "held-followups" | "conversation-includes" | "decision-choices" | "decision-snooze" | "steps" | "mainci" | "limits" | "claims" | "preapprovals" | "security" | "discord" | "discord-links" | "downloads" | "build-features" | "pr-builds" | "nightly" | "remote-helpers" | "remote-queue" | "workflows" | "workflow-events"; /** What moves an item's queue position (src/rank/position.ts), for every query that carries the badge. */ const withSlot = (...topics: Topic[]): Topic[] => [...new Set([...topics, "steps", "repos"])]; @@ -30,7 +30,8 @@ const RULES: [prefix: string, topics: Topic[]][] = [ ["items-status:", withSlot("items", "stages", "flow", "classify", "decisions", "plans", "pr-builds", "verify")], // The Live board: jobs, model calls (their progress lines too), build tasks (each step's log) and integration batches. ["live", ["jobs", "agents", "tasks", "queue", "remote-helpers", "accounts"]], - ["maintain-home", ["workflows", "items", "remote-helpers", "access", "settings", "decisions", "plans", "jobs", "limits", "accounts", "security", "repos"]], + ["maintain-items:", ["workflows", "workflow-events", "items", "plans", "ranks", "classify", "dupes", "decisions", "access", "security", "repos"]], + ["maintain-home", ["workflows", "workflow-events", "items", "remote-helpers", "access", "settings", "decisions", "plans", "jobs", "limits", "accounts", "security", "repos"]], ["home", withSlot("decisions", "decision-snooze", "plans", "jobs", "limits", "accounts", "settings", "queue", "items", "mainci", "github", "usage", "security")], // One opened event row: its detail reads what the timeline does; the run, task and decision behind it read one table each. ["item-trace-detail:", TRACE], diff --git a/web/src/api/types.ts b/web/src/api/types.ts index 11cf6ee4..f6f8d707 100644 --- a/web/src/api/types.ts +++ b/web/src/api/types.ts @@ -3335,3 +3335,68 @@ export interface MaintainHome { runner: MaintainRunnerLine | null; attention: HomeProblem[]; } + +// ---- the new Items page (GET /api/maintain/items) ---- + +/** + * Which list an item is in: `needs` (an open recommendation or an unclear last answer), `started` (a live workflow), `automatic` + * (AutoCraft works it without anyone picking it: review, fix, verify or merge queue), `rest` (open, nothing running), `backlog` + * (open, nothing planned) and `done` (merged or closed). + */ +export type MaintainItemGroup = "needs" | "started" | "automatic" | "rest" | "backlog" | "done"; +export type MaintainItemsShow = "open" | "backlog" | "closed"; +/** `security` and `stuck` are for operators and maintainers. */ +export type MaintainItemsFilter = "security" | "outside" | "stuck" | "duplicates"; + +export interface MaintainItemRow { + repo: RepoName; + number: number; + kind: "pr" | "issue"; + state: ItemState; + title: string; + author: string | null; + group: MaintainItemGroup; + /** A started item's line (the open recommendation, an unclear-answer note or where it stands), already translated; null otherwise. */ + line: string | null; + /** The pipeline's status line of an item nobody started; null for a started item. */ + status: ItemStatus | null; + blocked: boolean; + /** The weight word or `weight n`; null for the normal weight. */ + weight: string | null; + startedBy: string | null; + approvedBy: string | null; + stoppedBy: string | null; + duplicate: boolean; + /** Held for model work because its author is outside the team. */ + outside: boolean; + /** Nothing moves it (the liveness check); always false for viewers. */ + stuck: boolean; + area: string | null; + /** The reader may send commands on its repo. */ + may: boolean; + updatedAt: string; +} + +export interface MaintainItemsQuery { + show?: MaintainItemsShow; + filters?: MaintainItemsFilter[]; + areas?: string[]; + q?: string; + /** `repo#n` of semantic search hits, best first: only these, in this order within each group. */ + refs?: string[]; + sort?: "priority" | "updated"; + /** Rows per group at most. */ + limit?: number; +} + +/** Rows in group order (needs, started, automatic, rest; or backlog; or done), each group cut at the query's limit; `counts` has every match. */ +export interface MaintainItems { + rows: MaintainItemRow[]; + counts: Record; +} + +/** What a command did to each item, and the lines to show the sender (confirmation, ambiguity or refusal). */ +export interface MaintainCommandResult { + items: { repo: string; number: number; outcome: "run" | "ambiguous" | "refused"; line: string; workflowId: number | null }[]; + lines: string[]; +} diff --git a/web/src/modules/maintain/items/index.tsx b/web/src/modules/maintain/items/index.tsx new file mode 100644 index 00000000..edfb6d22 --- /dev/null +++ b/web/src/modules/maintain/items/index.tsx @@ -0,0 +1,18 @@ +// The new dashboard's Items page (ui_v2): what needs an answer, what was started, what AutoCraft works by itself and the rest, +// with filters, search and a command box for several items at once. +import type { FeatureModule } from "../../../registry/types"; +import { lazyView } from "../../../registry/lazyView"; +import { t } from "../../../../../src/i18n/index.ts"; + +const ItemsView = lazyView(() => import("./views"), "ItemsView"); + +export const maintainItemsModule: FeatureModule = { + id: "maintain-items", + permission: "viewer", + commands: [{ id: "go-items", keys: "g i", label: t("Go to items"), group: "Go to" }], + routes: [ + { path: "items", scoped: true, view: { id: "maintain-items", title: t("Items"), phone: ItemsView, panels: [{ id: "main", title: t("Items"), component: ItemsView, defaultSize: 100 }] } }, + // Links to the classic browser's filter view open the same page. + { path: "items/filters", scoped: true, view: { id: "maintain-items-filters", title: t("Items"), phone: ItemsView, panels: [{ id: "main", title: t("Items"), component: ItemsView, defaultSize: 100 }] } }, + ], +}; diff --git a/web/src/modules/maintain/items/views.tsx b/web/src/modules/maintain/items/views.tsx new file mode 100644 index 00000000..aab044de --- /dev/null +++ b/web/src/modules/maintain/items/views.tsx @@ -0,0 +1,382 @@ +// Items: four lists of the open items (needs an answer, started, handled automatically, not started), or the Backlog, or the +// closed items. Filters and search live in the URL. People who may send commands tick items to fill the command box with the +// list form (`merge:` then one item per line) and run it for all of them at once. +import { useEffect, useMemo, useRef, useState } from "react"; +import { Link, useSearchParams } from "react-router-dom"; +import { TerminalIcon } from "@phosphor-icons/react"; +import { t } from "../../../../../src/i18n/index.ts"; +import { useApi, useQuery } from "../../../api/client"; +import { usePageProject } from "../../../api/scope"; +import type { MaintainCommandResult, MaintainItemGroup, MaintainItemRow, MaintainItemsFilter, MaintainItemsQuery, MaintainItemsShow } from "../../../api/types"; +import { itemPath } from "../../../lib/links"; +import { useUser } from "../../../shell/UserContext"; +import { Badge } from "../../../ui/atoms/Badge"; +import { Button } from "../../../ui/atoms/Button"; +import { Chip } from "../../../ui/atoms/Chip"; +import { ItemIcon } from "../../../ui/atoms/ItemIcon"; +import { Pending } from "../../../ui/atoms/Pending"; +import { Select } from "../../../ui/atoms/Select"; +import { Textarea } from "../../../ui/atoms/Textarea"; +import { SearchField } from "../../../ui/molecules/SearchField"; +import { Segmented } from "../../../ui/molecules/Segmented"; +import { cn } from "../../../ui/cn"; +import type { ViewProps } from "../../../registry/types"; + +const PAGE = 50; +const SEARCH_DELAY_MS = 350; +const refOf = (r: { repo: string; number: number }) => `${r.repo}#${r.number}`; + +/** The command box text with `refs` as its item list: the words before the colon stay, the list after it is replaced. */ +export function withItems(text: string, refs: string[]): string { + const colon = text.indexOf(":"); + const head = (colon >= 0 ? text.slice(0, colon) : text).trimEnd(); + return refs.length ? `${head}:\n${refs.join("\n")}` : head; +} + +function groupTitle(g: MaintainItemGroup, viewer: boolean): string { + switch (g) { + case "needs": return viewer ? t("Waiting for a maintainer") : t("Needs an answer"); + case "started": return t("Started"); + case "automatic": return t("Handled automatically"); + case "rest": return t("Not started"); + case "backlog": return t("Backlog"); + case "done": return t("Closed and merged"); + } +} + +/** Who started it and whether it is approved for merge. */ +function byLine(r: MaintainItemRow): string | null { + if (!r.startedBy) return null; + const started = t("started by {login}", { login: r.startedBy }); + if (r.stoppedBy) return t("{started}, stopped by {login}", { started, login: r.stoppedBy }); + return t("{started}, {approved}", { started, approved: r.approvedBy ? t("approved by {login}", { login: r.approvedBy }) : t("not approved") }); +} + +/** The row's one status line: the workflow's line, or the pipeline's status for an item nobody started. */ +function RowLine({ r }: { r: MaintainItemRow }) { + const by = byLine(r); + return ( +
+ {r.weight && ( + + {r.weight} + + )} + {r.blocked && {t("Blocker")} · } + {r.line !== null ? ( + {r.line} + ) : r.status ? ( + + {r.status.phase} + {r.status.waiting && · {t("waiting for {what}", { what: r.status.waiting })}} + + ) : null} + {by && · {by}} +
+ ); +} + +/** Duplicate, held for an outside author, stuck and the area, after the ref and author. */ +function Signals({ r }: { r: MaintainItemRow }) { + return ( + <> + {r.duplicate && {t("Duplicate")}} + {r.outside && {t("Held (outside)")}} + {r.stuck && {t("Stuck")}} + {r.area && {r.area}} + + ); +} + +function ItemRow({ r, picking, picked, onPick }: { r: MaintainItemRow; picking: boolean; picked: boolean; onPick: (on: boolean) => void }) { + const ref = refOf(r); + return ( +
  • + {picking && ( + + )} + +
    + + {r.title} + +
    + {ref} + {r.author && <> · {r.author}} + +
    + +
    +
  • + ); +} + +function Group({ group, rows, total, viewer, picking, picked, onPick, onMore }: { + group: MaintainItemGroup; rows: MaintainItemRow[]; total: number; viewer: boolean; picking: boolean; + picked: Set; onPick: (refs: string[], on: boolean) => void; onMore: () => void; +}) { + if (!rows.length) return null; + const title = groupTitle(group, viewer); + const mine = rows.filter((r) => r.may).map(refOf); + const all = mine.length > 0 && mine.every((r) => picked.has(r)); + return ( +
    +
    + {picking && mine.length > 0 && ( + + )} +

    + {title} ({total}) +

    +
    +
      + {rows.map((r) => ( + onPick([refOf(r)], on)} /> + ))} +
    + {total > rows.length && ( + + )} +
    + ); +} + +/** The command box: free text in the same words as on GitHub and Discord; the reply lines show what ran and what was unclear. */ +function CommandBox({ text, setText, onDone }: { text: string; setText: (s: string) => void; onDone: (r: MaintainCommandResult) => void }) { + const api = useApi(); + const [busy, setBusy] = useState(false); + const [result, setResult] = useState(null); + const [error, setError] = useState(null); + const box = useRef(null); + const run = async () => { + if (!text.trim() || busy) return; + setBusy(true); + setError(null); + try { + const r = await api.maintain.command(text); + setResult(r); + onDone(r); + } catch (e) { + setResult(null); + setError((e as Error).message); + } finally { + setBusy(false); + } + }; + return ( +
    + +