mirror of
https://github.com/storytold/autocraft.git
synced 2026-11-28 09:09:57 +01:00
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
This commit is contained in:
1 parent
078b22a827
commit
04c89ef01f
14 files changed
+794
-21
No files matched your search
@@ -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),
|
||||
|
||||
@@ -48,7 +48,7 @@ const hitsScored = (db: Db, fts: Search) => db.k.selectFrom(
|
||||
.as("m"))
|
||||
.select(["m.rid", (eb) => eb.fn.min<number>("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<string, string> = { open: "OPEN", closed: "CLOSED", merged: "MERGED" };
|
||||
|
||||
+196
-13
@@ -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<Set<number>> {
|
||||
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<number, string>();
|
||||
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<Map<string, WorkflowEventKind>> {
|
||||
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<MaintainRow[]> {
|
||||
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<MaintainHome> {
|
||||
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<ItemPhase> = 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<ItemWorkflow, "state" | "rec"> | 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<SqlBool>;
|
||||
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<MaintainItems> {
|
||||
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<MaintainItemGroup, number>;
|
||||
|
||||
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 extends SelectQueryBuilder<any, any, any>>(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<number>().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<Base[]>, 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<MaintainItemRow[]> {
|
||||
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);
|
||||
}
|
||||
@@ -72,6 +72,8 @@ export const TOPIC_TABLES: Record<string, Source[]> = {
|
||||
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.
|
||||
|
||||
@@ -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<string> => {
|
||||
|
||||
@@ -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" })));
|
||||
});
|
||||
@@ -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<MaintainHome>;
|
||||
/** 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<MaintainItems>;
|
||||
/** Sends a command written in the dashboard's box; the list form (`merge:` then items) names the items. */
|
||||
command(text: string): Promise<MaintainCommandResult>;
|
||||
};
|
||||
/** 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<ItemPageData | ItemPageUnchanged>;
|
||||
|
||||
+5
-1
@@ -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 })}`),
|
||||
|
||||
@@ -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<MaintainItemRow> & Pick<MaintainItemRow, "repo" | "number" | "title" | "group"> & { 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<MaintainItemGroup, number> = { needs: 0, started: 0, automatic: 0, rest: 0, backlog: 0, done: 0 };
|
||||
const ORDER: MaintainItemGroup[] = ["needs", "started", "automatic", "rest", "backlog", "done"];
|
||||
const WEIGHTS: Record<string, number> = { 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<Api, "maintain"> {
|
||||
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<MaintainHome> {
|
||||
const repo = requestProject();
|
||||
const rows = ROWS.filter((r) => !repo || r.repo === repo);
|
||||
|
||||
@@ -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<Topic>([...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],
|
||||
|
||||
@@ -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<MaintainItemGroup, number>;
|
||||
}
|
||||
|
||||
/** 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[];
|
||||
}
|
||||
@@ -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 }] } },
|
||||
],
|
||||
};
|
||||
@@ -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 (
|
||||
<div className="mt-1 line-clamp-2 text-sm">
|
||||
{r.weight && (
|
||||
<Badge tone={r.weight === "urgent" ? "bad" : r.weight === "low" ? "neutral" : "warn"} className="mr-1.5">
|
||||
{r.weight}
|
||||
</Badge>
|
||||
)}
|
||||
{r.blocked && <span className="text-bad">{t("Blocker")} · </span>}
|
||||
{r.line !== null ? (
|
||||
<span className={r.group === "needs" ? "font-medium text-accent-ink" : "text-ink/80"}>{r.line}</span>
|
||||
) : r.status ? (
|
||||
<span className="text-ink/80">
|
||||
<span className="font-medium">{r.status.phase}</span>
|
||||
{r.status.waiting && <span className="text-ink/70"> · {t("waiting for {what}", { what: r.status.waiting })}</span>}
|
||||
</span>
|
||||
) : null}
|
||||
{by && <span className="text-ink/70"> · {by}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Duplicate, held for an outside author, stuck and the area, after the ref and author. */
|
||||
function Signals({ r }: { r: MaintainItemRow }) {
|
||||
return (
|
||||
<>
|
||||
{r.duplicate && <Badge tone="warn" className="ml-1.5">{t("Duplicate")}</Badge>}
|
||||
{r.outside && <Badge tone="warn" className="ml-1.5">{t("Held (outside)")}</Badge>}
|
||||
{r.stuck && <Badge tone="bad" className="ml-1.5">{t("Stuck")}</Badge>}
|
||||
{r.area && <Badge className="ml-1.5">{r.area}</Badge>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ItemRow({ r, picking, picked, onPick }: { r: MaintainItemRow; picking: boolean; picked: boolean; onPick: (on: boolean) => void }) {
|
||||
const ref = refOf(r);
|
||||
return (
|
||||
<li className="relative flex items-start gap-3 px-3 py-3 hover:bg-ink/[0.025]">
|
||||
{picking && (
|
||||
<label className="relative z-10 -my-2 -ml-2 flex size-11 shrink-0 cursor-pointer items-center justify-center md:-my-1 md:size-8">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="size-4 accent-accent"
|
||||
checked={picked}
|
||||
disabled={!r.may}
|
||||
onChange={(e) => onPick(e.target.checked)}
|
||||
aria-label={t("Select {ref}", { ref })}
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
<ItemIcon kind={r.kind} state={r.state} className="mt-0.5" tip={false} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<Link to={itemPath(r.repo, r.number)} className="block rounded text-md font-medium leading-snug after:absolute after:inset-0 hover:underline">
|
||||
{r.title}
|
||||
</Link>
|
||||
<div className="mt-0.5 text-xs text-ink/70">
|
||||
<span className="code">{ref}</span>
|
||||
{r.author && <> · {r.author}</>}
|
||||
<Signals r={r} />
|
||||
</div>
|
||||
<RowLine r={r} />
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function Group({ group, rows, total, viewer, picking, picked, onPick, onMore }: {
|
||||
group: MaintainItemGroup; rows: MaintainItemRow[]; total: number; viewer: boolean; picking: boolean;
|
||||
picked: Set<string>; 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 (
|
||||
<section aria-label={title} className="flex flex-col gap-1">
|
||||
<div className="mt-2 flex min-h-8 items-center gap-2">
|
||||
{picking && mine.length > 0 && (
|
||||
<label className="-ml-1 flex size-11 shrink-0 cursor-pointer items-center justify-center md:size-8">
|
||||
<input type="checkbox" className="size-4 accent-accent" checked={all} onChange={(e) => onPick(mine, e.target.checked)} aria-label={t("Select all in {group}", { group: title })} />
|
||||
</label>
|
||||
)}
|
||||
<h2 className="text-sm font-semibold text-ink/70">
|
||||
{title} <span className="num font-normal">({total})</span>
|
||||
</h2>
|
||||
</div>
|
||||
<ul className="divide-y divide-line rounded-lg border border-line bg-panel">
|
||||
{rows.map((r) => (
|
||||
<ItemRow key={refOf(r)} r={r} picking={picking} picked={picked.has(refOf(r))} onPick={(on) => onPick([refOf(r)], on)} />
|
||||
))}
|
||||
</ul>
|
||||
{total > rows.length && (
|
||||
<Button variant="ghost" onClick={onMore} className="self-start max-md:h-11">
|
||||
{t("Show more ({n} not shown)", { n: total - rows.length })}
|
||||
</Button>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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<MaintainCommandResult | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const box = useRef<HTMLTextAreaElement>(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 (
|
||||
<section aria-label={t("Command")} className="flex flex-col gap-2 rounded-lg border border-line-strong bg-raised p-3">
|
||||
<label htmlFor="items-command" className="text-sm font-medium">
|
||||
{t("Command")}
|
||||
</label>
|
||||
<Textarea
|
||||
id="items-command"
|
||||
ref={box}
|
||||
value={text}
|
||||
rows={Math.min(8, Math.max(3, text.split("\n").length + 1))}
|
||||
placeholder={"merge:\nphotocraft#123\nphotocraft#456"}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
// A list filled from the ticks starts with its colon: the words go in front of it.
|
||||
onFocus={(e) => text.startsWith(":") && e.currentTarget.setSelectionRange(0, 0)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
|
||||
e.preventDefault();
|
||||
void run();
|
||||
}
|
||||
}}
|
||||
className="code text-sm"
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="primary" onClick={() => void run()} loading={busy} disabled={!text.trim()} className="max-md:h-11">
|
||||
{t("Run")}
|
||||
</Button>
|
||||
</div>
|
||||
<div aria-live="polite" className="flex flex-col gap-1 empty:hidden">
|
||||
{error && <p className="text-sm text-bad">{error}</p>}
|
||||
{result?.lines.map((l, i) => (
|
||||
<p key={i} className={cn("text-sm", result.items.length && result.items.every((x) => x.outcome === "run") ? "text-ink/80" : "text-warn")}>
|
||||
{l}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const SHOWS: MaintainItemsShow[] = ["open", "backlog", "closed"];
|
||||
const FILTERS: MaintainItemsFilter[] = ["security", "outside", "stuck", "duplicates"];
|
||||
const filterLabel = (f: MaintainItemsFilter): string =>
|
||||
f === "security" ? t("Security") : f === "outside" ? t("Held (outside)") : f === "stuck" ? t("Stuck") : t("Duplicates");
|
||||
|
||||
/** The page's state in the URL: show, sort, filter, area, q and by (words or meaning). */
|
||||
function useItemsUrl() {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const setAll = (changes: Record<string, string | null>) =>
|
||||
setParams((p) => {
|
||||
const n = new URLSearchParams(p);
|
||||
for (const [k, v] of Object.entries(changes)) {
|
||||
if (v) n.set(k, v);
|
||||
else n.delete(k);
|
||||
}
|
||||
return n;
|
||||
}, { replace: true });
|
||||
const set = (k: string, v: string | null) => setAll({ [k]: v });
|
||||
const show = (SHOWS as string[]).includes(params.get("show") ?? "") ? (params.get("show") as MaintainItemsShow) : "open";
|
||||
const filters = (params.get("filter")?.split(",") ?? []).filter((f): f is MaintainItemsFilter => (FILTERS as string[]).includes(f));
|
||||
return {
|
||||
show, filters,
|
||||
sort: params.get("sort") === "updated" ? ("updated" as const) : ("priority" as const),
|
||||
area: params.get("area") ?? "",
|
||||
q: params.get("q") ?? "",
|
||||
meaning: params.get("by") === "meaning",
|
||||
set, setAll,
|
||||
};
|
||||
}
|
||||
|
||||
export function ItemsView(_: ViewProps) {
|
||||
const user = useUser();
|
||||
const viewer = user.role === "viewer";
|
||||
const project = usePageProject();
|
||||
const url = useItemsUrl();
|
||||
const [typed, setTyped] = useState(url.q);
|
||||
const [limit, setLimit] = useState(PAGE);
|
||||
const [picked, setPicked] = useState<Set<string>>(new Set());
|
||||
const [cmdOpen, setCmdOpen] = useState(false);
|
||||
const [cmd, setCmd] = useState("");
|
||||
const writes = !viewer && user.runRepos.length > 0;
|
||||
|
||||
// The URL follows the typing after a pause; a search by meaning embeds the text, so it waits the same.
|
||||
useEffect(() => {
|
||||
if (typed === url.q) return;
|
||||
const id = setTimeout(() => url.set("q", typed.trim() || null), SEARCH_DELAY_MS);
|
||||
return () => clearTimeout(id);
|
||||
}, [typed]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const query: MaintainItemsQuery = useMemo(() => ({
|
||||
show: url.show, sort: url.sort, filters: url.filters.filter((f) => !viewer || (f !== "security" && f !== "stuck")), areas: url.area ? [url.area] : [], limit,
|
||||
...(url.q && !url.meaning ? { q: url.q } : {}),
|
||||
}), [url.show, url.sort, url.filters.join(","), url.area, url.q, url.meaning, limit, viewer]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
const semantic = url.meaning && url.q.trim() ? url.q.trim() : null;
|
||||
const { data, error } = useQuery(`maintain-items:${JSON.stringify(query)}:${semantic ?? ""}`, async (a) => {
|
||||
if (!semantic) return a.maintain.items(query);
|
||||
const hits = await a.semanticSearch(semantic);
|
||||
if (!hits.length) return { rows: [], counts: { needs: 0, started: 0, automatic: 0, rest: 0, backlog: 0, done: 0 } };
|
||||
return a.maintain.items({ ...query, refs: hits.map(refOf) });
|
||||
});
|
||||
const { data: areaList } = useQuery(`areas:${project ?? ""}`, (a) => a.areas.get(project!), { enabled: !!project });
|
||||
const areas = project && areaList?.repo === project ? areaList.areas.map((a) => a.name) : [];
|
||||
|
||||
const pick = (refs: string[], on: boolean) => {
|
||||
const next = new Set(picked);
|
||||
for (const r of refs) if (on) next.add(r); else next.delete(r);
|
||||
setPicked(next);
|
||||
setCmd(withItems(cmd, [...next]));
|
||||
if (next.size) setCmdOpen(true);
|
||||
};
|
||||
const done = (r: MaintainCommandResult) => {
|
||||
if (r.items.length && r.items.every((x) => x.outcome === "run")) {
|
||||
setPicked(new Set());
|
||||
setCmd("");
|
||||
}
|
||||
};
|
||||
const toggleFilter = (f: MaintainItemsFilter) => {
|
||||
const next = url.filters.includes(f) ? url.filters.filter((x) => x !== f) : [...url.filters, f];
|
||||
url.set("filter", next.join(",") || null);
|
||||
};
|
||||
const narrowed = url.filters.length > 0 || !!url.area || !!url.q || url.show !== "open";
|
||||
const clear = () => {
|
||||
setTyped("");
|
||||
url.setAll({ filter: null, area: null, q: null, show: null });
|
||||
};
|
||||
|
||||
const groups: MaintainItemGroup[] = url.show === "closed" ? ["done"] : url.show === "backlog" ? ["backlog"] : ["needs", "started", "automatic", "rest"];
|
||||
return (
|
||||
<div className="h-full overflow-y-auto">
|
||||
<div className="mx-auto flex max-w-[768px] flex-col gap-3 px-4 pb-10 pt-5 md:px-6">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<h1 className="text-xl font-semibold">{t("Items")}</h1>
|
||||
{writes && (
|
||||
<Button icon={TerminalIcon} aria-expanded={cmdOpen} onClick={() => setCmdOpen(!cmdOpen)} className="max-md:h-11">
|
||||
{picked.size ? t("Command ({n} selected)", { n: picked.size }) : t("Command")}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{writes && cmdOpen && <CommandBox text={cmd} setText={setCmd} onDone={done} />}
|
||||
<div className="flex flex-col gap-2 md:flex-row md:items-center">
|
||||
<SearchField value={typed} onChange={setTyped} onSubmit={(v) => url.set("q", v.trim() || null)} label={t("Search items")} placeholder={t("Search issues and pull requests")} />
|
||||
<Segmented
|
||||
label={t("Search by")}
|
||||
value={url.meaning ? "meaning" : "words"}
|
||||
onChange={(v) => url.set("by", v === "meaning" ? "meaning" : null)}
|
||||
options={[{ value: "words", label: t("Words") }, { value: "meaning", label: t("Meaning") }]}
|
||||
className="shrink-0 flex-nowrap"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2 md:flex md:flex-wrap">
|
||||
<Select value={url.show} onChange={(e) => url.set("show", e.target.value === "open" ? null : e.target.value)} aria-label={t("Show")} className="w-full max-md:h-11 md:w-auto">
|
||||
<option value="open">{t("Open")}</option>
|
||||
<option value="backlog">{t("Backlog")}</option>
|
||||
<option value="closed">{t("Closed and merged")}</option>
|
||||
</Select>
|
||||
<Select value={url.sort} onChange={(e) => url.set("sort", e.target.value === "priority" ? null : e.target.value)} aria-label={t("Sort")} className="w-full max-md:h-11 md:w-auto">
|
||||
<option value="priority">{t("Priority")}</option>
|
||||
<option value="updated">{t("Recently updated")}</option>
|
||||
</Select>
|
||||
{areas.length > 0 && (
|
||||
<Select value={url.area} onChange={(e) => url.set("area", e.target.value || null)} aria-label={t("Area")} className="w-full max-md:h-11 md:w-auto">
|
||||
<option value="">{t("All areas")}</option>
|
||||
{areas.map((a) => (
|
||||
<option key={a} value={a}>
|
||||
{a}
|
||||
</option>
|
||||
))}
|
||||
<option value="none">{t("No area")}</option>
|
||||
</Select>
|
||||
)}
|
||||
</div>
|
||||
<div className="-mx-4 flex gap-2 overflow-x-auto px-4 pb-1 md:mx-0 md:flex-wrap md:px-0" role="group" aria-label={t("Filters")}>
|
||||
{FILTERS.filter((f) => !viewer || (f !== "security" && f !== "stuck")).map((f) => (
|
||||
<Chip key={f} active={url.filters.includes(f)} aria-pressed={url.filters.includes(f)} className="shrink-0 max-md:h-11" onClick={() => toggleFilter(f)}>
|
||||
{filterLabel(f)}
|
||||
</Chip>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{!data ? (
|
||||
<Pending error={error} />
|
||||
) : data.rows.length === 0 ? (
|
||||
<div className="flex flex-col items-start gap-3 rounded-lg border border-line px-4 py-6">
|
||||
<p className="text-md">{narrowed ? t("No items match.") : t("No open items.")}</p>
|
||||
{narrowed && <Button onClick={clear}>{t("Clear filters and search")}</Button>}
|
||||
</div>
|
||||
) : (
|
||||
groups.map((g) => (
|
||||
<Group
|
||||
key={g}
|
||||
group={g}
|
||||
rows={data.rows.filter((r) => r.group === g)}
|
||||
total={data.counts[g]}
|
||||
viewer={viewer}
|
||||
picking={writes && cmdOpen}
|
||||
picked={picked}
|
||||
onPick={pick}
|
||||
onMore={() => setLimit(limit + PAGE)}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -33,11 +33,15 @@ import { securityModule } from "../modules/security";
|
||||
import { homeModule } from "../modules/home";
|
||||
import { hubModule } from "../modules/hub";
|
||||
import { maintainHomeModule } from "../modules/maintain/home";
|
||||
import { maintainItemsModule } from "../modules/maintain/items";
|
||||
|
||||
export const classicModules: FeatureModule[] = [homeModule, hubModule, nowModule, flowModule, needsModule, nextModule, agentsModule, envsModule, workspacesModule, ratesModule, itemModule, progressModule, itemsModule, activityModule, contributorsModule, classifiersModule, costModule, downloadsModule, reposModule, accessModule, githubAppModule, discordModule, auditModule, aboutModule, connectModule, pipelineModule, promptsModule, similarModule, accountsModule, inferenceModule, mainCiModule, nightlyModule, stuckModule, batchModule, securityModule];
|
||||
|
||||
/** Classic modules the new dashboard's own pages replace. */
|
||||
const replacedInV2: FeatureModule[] = [homeModule, itemsModule];
|
||||
|
||||
/** The new dashboard: its own Home; the classic views serve the pages the new dashboard has not replaced yet. */
|
||||
export const v2Modules: FeatureModule[] = [maintainHomeModule, ...classicModules.filter((m) => m !== homeModule)];
|
||||
export const v2Modules: FeatureModule[] = [maintainHomeModule, maintainItemsModule, ...classicModules.filter((m) => !replacedInV2.includes(m))];
|
||||
|
||||
/** Every module of either dashboard, for preloading code. */
|
||||
export const allModules: FeatureModule[] = [...new Set([...classicModules, ...v2Modules])];
|
||||
|
||||
Reference in new issue
Block a user