diff --git a/dashboard/e2e/audit-plans.spec.ts b/dashboard/e2e/audit-plans.spec.ts index 2755a39e..54f2b873 100644 --- a/dashboard/e2e/audit-plans.spec.ts +++ b/dashboard/e2e/audit-plans.spec.ts @@ -23,11 +23,17 @@ function task(id: string, title: string, status: string, order: number, extra: R }; } +const counts = (c: Partial>) => ({ draft: 0, queued: 0, working: 0, needs_you: 0, failed: 0, in_review: 0, merged: 0, dropped: 0, ...c }); + const PLANS = [ - plan("PLANA", "Add a class schedule page", "draft"), - plan("PLANB", "Retry the sync job", "executing"), - plan("PLANC", "Move billing to the new API", "waiting"), - plan("PLAND", "Clean up old flags", "done"), + plan("PLANA", "Add a class schedule page", "draft", { state: "drafting", summary: "3 tasks to review, 1 dropped", counts: counts({ draft: 3, dropped: 1 }) }), + plan("PLANB", "Retry the sync job", "executing", { + state: "running", summary: "1 of 3 merged, 1 in review, 1 working", counts: counts({ merged: 1, in_review: 1, working: 1 }), cost_usd: 14.2, attempts: 4, last_activity_at: NOW, + }), + plan("PLANC", "Move billing to the new API", "executing", { + state: "needs_you", summary: "2 of 5 merged, 1 needs you, 1 failed, 1 in review", needs_count: 2, counts: counts({ merged: 2, needs_you: 1, failed: 1, in_review: 1 }), cost_usd: 61.9, attempts: 11, + }), + plan("PLAND", "Clean up old flags", "done", { state: "done", summary: "2 of 2 merged", counts: counts({ merged: 2 }), cost_usd: 5.1, attempts: 2 }), ]; const TEMPLATES = [ @@ -59,21 +65,77 @@ interface Backend { openspecMissing: boolean; /** Bodies of every write, "METHOD /path" → body, in order. */ writes: { call: string; body: unknown }[]; + /** The detail answer's criteria, needs and estimate. */ + criteria: unknown[]; + needs: unknown[]; + estimate: unknown; } function freshTasks() { return [ - task("T1", "Add the schedule table", "draft", 0), - task("T2", "Show the schedule on the page", "rejected", 1), - task("T3", "Wire the schedule API", "failed", 2), - task("T4", "Write the tests", "approved", 3, { depends_on: "T1" }), + task("T1", "Add the schedule table", "draft", 0, { state: "draft" }), + task("T2", "Show the schedule on the page", "rejected", 1, { state: "dropped", state_detail: "Dropped by a-person" }), + task("T3", "Wire the schedule API", "draft", 2, { state: "draft" }), + task("T4", "Write the tests", "draft", 3, { state: "draft", depends_on: "T1" }), + ]; +} + +const ESTIMATE = { tasks: 3, runs_low: 3, runs_high: 4, cost_low: 6.3, cost_high: 19.8, per_run_low: 2.1, per_run_high: 4.95, sample: 40 }; + +const pr = (n: number, tone: string, extra: Record = {}) => ({ + number: n, url: `https://github.com/your-team/web/pull/${n}`, repo: "your-team/web", state: "open", checks: "passed", review: "none", tone, run_id: `RUN${n}`, ...extra, +}); + +/** A plan at work: one merged, one in review, one needing a person, one failed, one still a draft. */ +function runningTasks() { + return [ + task("T1", "Add the schedule table", "filed", 0, { + state: "merged", state_detail: "Pull request #41 merged", attempts: 1, cost_usd: 3.4, ticket_filed: true, covers: ["C1"], + runs: [{ run_id: "RUN41", status: "merged", created_at: NOW, cost_usd: 3.4 }], prs: [pr(41, "merged", { state: "merged", additions: 120, deletions: 8 })], + issue_url: "https://github.com/your-team/web/issues/40", issue_number: 40, + }), + task("T2", "Show the schedule on the page", "filed", 1, { + state: "in_review", state_detail: "Checks are still running on `9f1c2ab`.", attempts: 1, cost_usd: 4.1, ticket_filed: true, covers: ["C2"], + runs: [{ run_id: "RUN52", status: "completed", created_at: NOW, cost_usd: 4.1 }], + prs: [pr(52, "waiting", { checks: "running", additions: 64, deletions: 3 })], + }), + task("T3", "Wire the schedule API", "filed", 2, { + state: "needs_you", state_detail: "Approve pull request #53", attempts: 2, cost_usd: 9.8, ticket_filed: true, + runs: [{ run_id: "RUN50", status: "retried", created_at: NOW, cost_usd: 5.0 }, { run_id: "RUN53", status: "completed", created_at: NOW, cost_usd: 4.8 }], + prs: [pr(53, "waiting", { review: "waiting", additions: 210, deletions: 41 }), pr(50, "closed", { state: "closed" })], + drift: [{ kind: "scope", detail: "The pull request changes files outside the task's planned scope: src/billing/charge.ts", by: "agent" }], + }), + task("T4", "Write the tests", "filed", 3, { + state: "failed", state_detail: "Run timed out (exceeded execution time limit).", state_reason: "Run timed out (exceeded execution time limit).", + attempts: 1, cost_usd: 2.2, ticket_filed: true, runs: [{ run_id: "RUN60", status: "failed", created_at: NOW, cost_usd: 2.2 }], prs: [], + }), + task("T5", "Add the print view", "draft", 4, { state: "draft", created_at: NOW, drift: [{ kind: "added", detail: "Added after the plan was approved", by: "person" }] }), ]; } +const RUNNING_NEEDS = [ + { task_id: "T3", kind: "approval", ask: "Approve pull request #53", detail: "This repo's auto-merge setting requires an approving review from a person before Coderhelm merges.", url: "https://github.com/your-team/web/pull/53", run_id: "RUN53", action: "open_pr" }, + { task_id: "T4", kind: "failed", ask: "Task \"Write the tests\" failed", detail: "Run timed out (exceeded execution time limit).", run_id: "RUN60", action: "retry" }, + { task_id: "", kind: "approve_rest", ask: "Approve or drop the 1 task still in draft", action: "approve" }, +]; + +const RUNNING_CRITERIA = [ + { id: "C1", text: "The schedule table stores classes by day", tasks: ["T1"], met: true, evidence: [{ task_id: "T1", run_id: "RUN41", state: "proven", words: "proven", by: "tests with and without the change", tests: ["schedule.test.ts"] }] }, + { id: "C2", text: "The page shows today's classes by default", tasks: ["T2"], met: false, evidence: [{ task_id: "T2", run_id: "RUN52", state: "not_run", words: "not run yet" }] }, + { id: "C3", text: "The page says when a class is full", tasks: [], met: false, evidence: [] }, +]; + +const RUNNING_PLAN = { + status: "executing", state: "needs_you", summary: "1 of 5 merged, 1 needs you, 1 failed, 1 in review, 1 in draft", + counts: counts({ merged: 1, needs_you: 1, failed: 1, in_review: 1, draft: 1 }), needs_count: 3, cost_usd: 19.5, attempts: 5, + criteria_met: 1, criteria_count: 3, executed_at: NOW, executed_by: "a-person", last_activity_at: NOW, +}; + async function mockApi(page: Page, init: Partial = {}): Promise { const db: Backend = { calls: [], plansEmpty: false, plansFail: false, templatesEmpty: false, planStatus: 200, slowPlan: false, - tasks: freshTasks(), chatBody: null, chatPosts: 0, created: null, usedQueries: [], planExtra: {}, openspecMissing: false, writes: [], ...init, + tasks: freshTasks(), chatBody: null, chatPosts: 0, created: null, usedQueries: [], planExtra: {}, openspecMissing: false, writes: [], + criteria: [], needs: [], estimate: ESTIMATE, ...init, }; const json = (route: Route, body: unknown, status = 200) => route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) }); @@ -175,7 +237,10 @@ async function mockApi(page: Page, init: Partial = {}): Promise setTimeout(r, 1500)); - return json(route, { ...plan(one[1], "Add a class schedule page", "draft", { chat_id: "chat-1", ...db.planExtra }), task_count: db.tasks.length, tasks: db.tasks }); + return json(route, { + ...plan(one[1], "Add a class schedule page", "draft", { chat_id: "chat-1", state: "drafting", summary: "3 tasks to review, 1 dropped", ...db.planExtra }), + task_count: db.tasks.length, tasks: db.tasks, criteria: db.criteria, needs: db.needs, estimate: db.estimate, + }); } const taskOne = p.match(/^\/api\/plans\/\w+\/tasks\/(\w+)$/); if (taskOne && (m === "PUT" || m === "DELETE")) return route.fulfill({ status: 200, body: "" }); @@ -187,8 +252,23 @@ async function mockApi(page: Page, init: Partial = {}): Promise (t.task_id === approve[1] ? { ...t, status: "approved" } : t)); - return route.fulfill({ status: 200, body: "" }); + // The plan runs and stays open: the approved task is queued, the rest are still drafts. + db.tasks = db.tasks.map((t) => (t.task_id === approve[1] ? { ...t, status: "queued", state: "queued", state_detail: "Waiting to file its ticket" } : t)); + const drafts = db.tasks.filter((t) => (t as { state?: string }).state === "draft").length; + db.planExtra = { ...db.planExtra, status: "executing", state: "running", summary: `0 of ${db.tasks.length} merged, 1 queued, ${drafts} in draft` }; + db.needs = drafts ? [{ task_id: "", kind: "approve_rest", ask: `Approve or drop the ${drafts} tasks still in draft`, action: "approve" }] : []; + return json(route, { dispatched: true, task_id: approve[1] }); + } + if (/^\/api\/plans\/\w+\/approve-and-execute$/.test(p) && m === "POST") { + const n = db.tasks.filter((t) => (t as { state?: string }).state === "draft").length; + db.tasks = db.tasks.map((t) => ((t as { state?: string }).state === "draft" ? { ...t, status: "queued", state: "queued" } : t)); + db.needs = []; + db.planExtra = { ...db.planExtra, status: "executing", state: "running" }; + return json(route, { status: "executing", tasks_queued: n }); + } + if (/^\/api\/runs\/\w+\/retry$/.test(p) && m === "POST") { + db.writes.push({ call: `${m} ${p}`, body: null }); + return json(route, { status: "queued" }); } if (/^\/api\/plans\/\w+\/openspec$/.test(p)) { if (db.openspecMissing) return route.fulfill({ status: 404, body: "" }); @@ -227,53 +307,70 @@ async function shot(page: Page, name: string) { await page.setViewportSize({ width: 1280, height: 800 }); } -test("plans list shows plain status words and keeps New plan while a plan runs", async ({ page }) => { +test("plans list shows each plan's progress by state, what needs you, and the cost", async ({ page }) => { const errors = watchConsole(page); await mockApi(page); await page.goto("/plans/"); await expect(page.getByRole("heading", { name: "Plans", exact: true })).toBeVisible(); await expect(page.getByRole("link", { name: "Add a class schedule page" })).toBeVisible(); - await expect(page.getByRole("list", { name: "Plans" }).getByText("Running", { exact: true })).toBeVisible(); - // A plan is running: it is pinned to the top of the list, and New plan stays. + const list = page.getByRole("list", { name: "Plans" }); + await expect(list.getByText("Running", { exact: true })).toBeVisible(); + // A running plan sits above a draft one; New plan stays. await expect(page.getByRole("link", { name: "New plan" })).toBeVisible(); - await expect(page.getByTestId("plan-row").first()).toHaveAttribute("data-status", "executing"); + const first = page.getByTestId("plan-row").first(); + await expect(first).toHaveAttribute("data-status", "running"); + await expect(first).toContainText("1 of 3 merged, 1 in review, 1 working"); + await expect(first).toContainText("$14.20"); + await expect(first.getByTestId("state-bar")).toHaveAttribute("aria-label", "Tasks: 1 merged, 1 in review, 1 working"); + // No description clutter on a row. + await expect(list).not.toContainText("Why: retry the sync job"); await shot(page, "plans-list"); expect(errors).toEqual([]); }); -test("Load more sends the cursor encoded, so the next page arrives", async ({ page }) => { +test("Load more sends the cursor encoded; a plan that needs you says how many things", async ({ page }) => { const errors = watchConsole(page); const db = await mockApi(page); await page.goto("/plans/"); await page.getByRole("button", { name: "Load more" }).click(); await expect(page.getByRole("link", { name: "Clean up old flags" })).toBeVisible(); - await expect(page.getByRole("list", { name: "Plans" }).getByText("Waiting on a merge")).toBeVisible(); expect(db.calls).toContain("GET /api/plans?cursor=PLAN%23PLANB"); await expect(page.getByRole("button", { name: "Load more" })).toHaveCount(0); + // Needs you is pinned first, with its count. + const first = page.getByTestId("plan-row").first(); + await expect(first).toHaveAttribute("data-status", "needs_you"); + await expect(first.getByTestId("needs-count")).toHaveText("2 need you"); + await expect(page.getByRole("list", { name: "Plans" }).getByText("Waiting on a merge")).toHaveCount(0); + await shot(page, "plans-list-all"); expect(errors).toEqual([]); }); -test("plans toolbar: status toggles with counts and a search, kept in the address", async ({ page }) => { +test("plans toolbar: Active counts running plans, Needs you and Done are their own, kept in the address", async ({ page }) => { const errors = watchConsole(page); await mockApi(page); await page.goto("/plans/"); const list = page.getByRole("list", { name: "Plans" }); - await expect(list.getByRole("listitem")).toHaveCount(2); + await page.getByRole("button", { name: "Load more" }).click(); + await expect(list.getByRole("listitem")).toHaveCount(4); const toggles = page.getByRole("group", { name: "Show plans" }); - await expect(toggles.getByRole("button", { name: /^All\s*2$/ })).toHaveAttribute("aria-pressed", "true"); + await expect(toggles.getByRole("button", { name: /^All\s*4$/ })).toHaveAttribute("aria-pressed", "true"); + await expect(toggles.getByRole("button", { name: /^Active\s*1$/ })).toBeVisible(); + await expect(toggles.getByRole("button", { name: /^Needs you\s*1$/ })).toBeVisible(); + await expect(toggles.getByRole("button", { name: /^Done\s*1$/ })).toBeVisible(); await toggles.getByRole("button", { name: /^Active/ }).click(); await expect(page).toHaveURL(/status=active/); await expect(list.getByRole("listitem")).toHaveCount(1); await expect(list.getByRole("link", { name: "Retry the sync job" })).toBeVisible(); - await page.goBack(); - await expect(list.getByRole("listitem")).toHaveCount(2); + await toggles.getByRole("button", { name: /^Done/ }).click(); + await expect(list.getByRole("link", { name: "Clean up old flags" })).toBeVisible(); + await toggles.getByRole("button", { name: /^All/ }).click(); await page.getByRole("searchbox", { name: "Search plans" }).fill("class schedule"); await expect(page).toHaveURL(/q=class/); await expect(list.getByRole("listitem")).toHaveCount(1); await page.getByRole("searchbox", { name: "Search plans" }).fill("nothing like this"); await expect(page.getByText(/No plans match/)).toBeVisible(); await page.getByRole("button", { name: "Clear filters" }).first().click(); - await expect(list.getByRole("listitem")).toHaveCount(2); + await expect(list.getByRole("listitem")).toHaveCount(4); expect(errors).toEqual([]); }); @@ -298,91 +395,78 @@ test("plans list error offers a retry that works", async ({ page }) => { expect(errors).toEqual([]); }); -test("plan detail reads as a document: one summary line, one action, the plan, the rest folded", async ({ page }) => { +test("a draft plan: one status line, the estimate before starting, criteria, tasks, the spec folded below", async ({ page }) => { const errors = watchConsole(page); - await mockApi(page); + await mockApi(page, { criteria: RUNNING_CRITERIA.map((c) => ({ ...c, met: false, evidence: [] })) }); await page.goto("/plans/detail/?id=PLANA"); await expect(page.getByRole("heading", { level: 1, name: "Add a class schedule page" })).toBeVisible(); - // One line says where the plan stands. const summary = page.getByRole("list", { name: "About this plan" }); - await expect(summary).toContainText("Draft"); + await expect(summary).toContainText("Drafting"); + await expect(summary).toContainText("3 tasks to review, 1 dropped"); await expect(summary).toContainText("your-team/web"); - await expect(summary).toContainText("4 tasks, 1 to review"); await expect(summary).toContainText("Sends to GitHub issues"); - // One primary action in the top bar; the rarely used ones sit in More. + // What starting costs, before the button is pressed. + await expect(page.getByTestId("plan-estimate")).toHaveText( + "Approving all 3 tasks starts 3 to 4 runs, about $6.30 to $19.80 from your team's last 40 runs.", + ); const header = page.getByTestId("page-actions"); - await expect(header.getByRole("button", { name: "Approve all and start" })).toBeVisible(); - await expect(header.getByRole("button", { name: "Save as template" })).toHaveCount(0); - await expect(header.getByRole("button", { name: "Delete" })).toHaveCount(0); + await expect(header.getByRole("button", { name: "Approve and start" })).toBeVisible(); await header.getByRole("button", { name: "More" }).click(); await expect(page.getByRole("menuitem")).toHaveText(["Save as template", "Download the spec", "Delete plan"]); await page.keyboard.press("Escape"); - // The document and its section list. + // In order: what done means, the tasks, the spec, details. const nav = page.getByRole("navigation", { name: "On this page" }); - await expect(nav.getByRole("link")).toHaveText(["Overview", "Tasks4", "Spec", "Details"]); - await expect(page.getByRole("heading", { level: 2, name: "Overview" })).toBeVisible(); + await expect(nav.getByRole("link")).toHaveText(["What done means3", "Tasks4", "Spec", "Details"]); + await expect(page.getByTestId("criteria-count")).toContainText("3 criteria, 0 proven"); + await expect(page.getByTestId("criterion")).toHaveCount(3); + // The spec sits below the tasks, open while the plan is a draft. await expect(page.getByText("Why: add a class schedule page")).toBeVisible(); await expect(page.getByRole("heading", { level: 3, name: "Proposal" })).toBeVisible(); - await expect(page.getByText("Members ask for the class schedule on the web.")).toBeVisible(); - // The design and requirements are folded behind "Technical plan". - await expect(page.getByRole("button", { name: "Copy design.md" })).toBeHidden(); - await page.getByText("Technical plan").click(); - await expect(page.getByRole("button", { name: "Copy design.md" })).toBeVisible(); - // Tasks are a checklist: a mark, a number, a title, a status word. const tasks = page.getByRole("list", { name: "Tasks" }); await expect(tasks.getByTestId("task")).toHaveCount(4); - await expect(tasks.getByRole("img", { name: "Failed" })).toBeVisible(); - await expect(tasks.getByRole("img", { name: "Skipped" })).toBeVisible(); - await expect(tasks.getByTestId("task").nth(2).getByRole("button", { name: "Retry" })).toBeVisible(); + await expect(tasks.getByRole("img", { name: "Dropped" })).toBeVisible(); await expect(tasks.getByTestId("task").nth(3)).toContainText("after 1"); - // No filters for a short plan; details are folded. - await expect(page.getByRole("searchbox", { name: "Search tasks" })).toHaveCount(0); - await expect(page.getByRole("group", { name: "Destination" })).toBeHidden(); - await expect(page.getByText("Do add the schedule table")).toHaveCount(0); + await expect(tasks.getByTestId("task").nth(0).getByRole("button", { name: "Approve", exact: true })).toBeVisible(); + await expect(page.getByTestId("needs-strip")).toHaveCount(0); await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur()); await shot(page, "plans-detail"); expect(errors).toEqual([]); }); -test("a long plan gets task search and status filters, including failed", async ({ page }) => { +test("Approve and start says what it starts and costs, then starts", async ({ page }) => { const errors = watchConsole(page); - const many = [ - ...freshTasks(), - task("T5", "Add the empty state", "draft", 4), - task("T6", "Add the loading state", "draft", 5), - task("T7", "Link the page from the menu", "draft", 6), - ]; - await mockApi(page, { tasks: many }); + const db = await mockApi(page); await page.goto("/plans/detail/?id=PLANA"); - const tasks = page.getByRole("list", { name: "Tasks" }); - await expect(tasks.getByTestId("task")).toHaveCount(7); - const failed = page.getByRole("group", { name: "Show tasks" }).getByRole("button", { name: "Failed (1)" }); - await failed.click(); - await expect(failed).toHaveAttribute("aria-pressed", "true"); - await expect(tasks.getByTestId("task")).toHaveCount(1); - await expect(tasks).toContainText("Wire the schedule API"); - await failed.click(); - await page.getByRole("searchbox", { name: "Search tasks" }).fill("loading"); - await expect(tasks.getByTestId("task")).toHaveCount(1); - await page.getByRole("searchbox", { name: "Search tasks" }).fill("nothing like it"); - await expect(page.getByText("No tasks match.")).toBeVisible(); + await page.getByTestId("page-actions").getByRole("button", { name: "Approve and start" }).click(); + const dialog = page.getByRole("alertdialog", { name: "Approve and start 3 tasks?" }); + await expect(dialog).toContainText("3 to 4 runs, about $6.30 to $19.80"); + await dialog.getByRole("button", { name: "Approve and start" }).click(); + await expect.poll(() => db.writes.map((w) => w.call)).toContain("POST /api/plans/PLANA/approve-and-execute"); expect(errors).toEqual([]); }); -test("approving a task updates in place instead of blanking the page", async ({ page }) => { +test("approving one task starts it and leaves the other drafts approvable", async ({ page }) => { const errors = watchConsole(page); const db = await mockApi(page); await page.goto("/plans/detail/?id=PLANA"); const heading = page.getByRole("heading", { level: 1, name: "Add a class schedule page" }); await expect(heading).toBeVisible(); + await page.getByRole("list", { name: "Tasks" }).getByTestId("task").first().getByRole("button", { name: "Approve", exact: true }).click(); + const dialog = page.getByRole("alertdialog", { name: "Approve and start this task?" }); + await expect(dialog).toContainText("Runs like it cost about $2.10 to $4.95. The plan stays open for its other tasks."); db.slowPlan = true; - await page.getByRole("button", { name: "Approve", exact: true }).click(); + await dialog.getByRole("button", { name: "Approve and start" }).click(); // While the reload is in flight, the plan stays on screen. await page.waitForTimeout(400); await expect(heading).toBeVisible(); - await expect(page.getByRole("list", { name: "Tasks" })).toContainText("Wire the schedule API"); - await expect(page.getByRole("list", { name: "Tasks" }).getByRole("img", { name: "Approved" })).toHaveCount(2); expect(db.writes).toContainEqual({ call: "POST /api/plans/PLANA/tasks/T1/approve", body: null }); + const tasks = page.getByRole("list", { name: "Tasks" }); + await expect(tasks.getByRole("img", { name: "Queued" })).toHaveCount(1); + // The plan runs and stays open: the two drafts still have their buttons, + // and the strip asks for them by name. + await expect(page.getByRole("list", { name: "About this plan" })).toContainText("Running"); + await expect(tasks.getByRole("button", { name: "Approve and start" })).toHaveCount(2); + await expect(page.getByTestId("needs-item")).toHaveText(/Approve or drop the 2 tasks still in draft/); expect(errors).toEqual([]); }); @@ -392,7 +476,7 @@ test("a task opens to what it says; edit sends only what changed, add sends the await page.goto("/plans/detail/?id=PLANA"); await page.getByRole("button", { name: "Show details of Add the schedule table" }).click(); await expect(page.getByText("Do add the schedule table")).toBeVisible(); - await expect(page.getByText("Done when")).toBeVisible(); + await expect(page.getByText("Done when", { exact: true })).toBeVisible(); await expect(page.getByRole("button", { name: "Remove task Add the schedule table" })).toBeVisible(); await shot(page, "plans-detail-task-open"); await page.getByRole("button", { name: "Edit", exact: true }).click(); @@ -429,27 +513,138 @@ test("the destination sits in Details; the summary line opens it", async ({ page expect(errors).toEqual([]); }); -test("a finished plan leads with its PR and lists its runs and PRs as rows", async ({ page }) => { +test("the Needs you strip names each exact ask with its button", async ({ page }) => { + const errors = watchConsole(page); + const db = await mockApi(page, { planExtra: RUNNING_PLAN, tasks: runningTasks(), needs: RUNNING_NEEDS, criteria: RUNNING_CRITERIA }); + await page.goto("/plans/detail/?id=PLANA"); + const summary = page.getByRole("list", { name: "About this plan" }); + await expect(summary).toContainText("Needs you"); + await expect(summary).toContainText("1 of 5 merged, 1 needs you, 1 failed, 1 in review, 1 in draft"); + await expect(summary).toContainText("$19.50 over 5 runs"); + // The top action goes to what needs you. + await expect(page.getByTestId("page-actions").getByRole("link", { name: "3 need you" })).toHaveAttribute("href", "#needs"); + const strip = page.getByTestId("needs-strip"); + const items = strip.getByTestId("needs-item"); + await expect(items).toHaveCount(3); + await expect(items.nth(0)).toContainText("3.Approve pull request #53"); + await expect(items.nth(0)).toContainText("requires an approving review from a person"); + await expect(items.nth(0).getByRole("link", { name: /Approve #53/ })).toHaveAttribute("href", "https://github.com/your-team/web/pull/53"); + await expect(items.nth(0).getByRole("link", { name: "Open run" })).toHaveAttribute("href", /RUN53/); + // A failed task says why, and Retry confirms with what a run costs. + await expect(items.nth(1)).toContainText("Run timed out (exceeded execution time limit)."); + await items.nth(1).getByRole("button", { name: "Retry" }).click(); + const dialog = page.getByRole("alertdialog", { name: 'Retry "Write the tests"?' }); + await expect(dialog).toContainText("It starts a new run. Runs like it cost about $2.10 to $4.95."); + await dialog.getByRole("button", { name: "Retry" }).click(); + // Its ticket was filed: the run is retried, no second ticket. + await expect.poll(() => db.writes.map((w) => w.call)).toContain("POST /api/runs/RUN60/retry"); + expect(db.writes.map((w) => w.call)).not.toContain("POST /api/plans/PLANA/tasks/T4/force-run"); + await expect(items.nth(2)).toContainText("Approve or drop the 1 task still in draft"); + await expect(items.nth(2).getByRole("button", { name: "Approve the rest" })).toBeVisible(); + // Handled: the strip goes. + db.needs = []; + await page.reload(); + await expect(page.getByRole("heading", { level: 1, name: "Add a class schedule page" })).toBeVisible(); + await expect(page.getByTestId("needs-strip")).toHaveCount(0); + expect(errors).toEqual([]); +}); + +test("each task shows its pull requests as chips coloured by checks and review, with attempts, cost and drift", async ({ page }) => { + const errors = watchConsole(page); + await mockApi(page, { planExtra: RUNNING_PLAN, tasks: runningTasks(), needs: RUNNING_NEEDS, criteria: RUNNING_CRITERIA }); + await page.goto("/plans/detail/?id=PLANA"); + const rows = page.getByRole("list", { name: "Tasks" }).getByTestId("task"); + await expect(rows).toHaveCount(5); + const chip = (row: number, n: number) => rows.nth(row).getByTestId("pr-chip").filter({ hasText: `#${n}` }); + await expect(chip(0, 41)).toHaveAttribute("data-tone", "merged"); + await expect(chip(0, 41)).toHaveAccessibleName(/Pull request #41, merged, 120 lines added and 8 removed/); + await expect(chip(1, 52)).toHaveAttribute("data-tone", "waiting"); + await expect(chip(1, 52)).toHaveAccessibleName(/checks running/); + await expect(chip(2, 53)).toHaveAttribute("data-tone", "waiting"); + await expect(chip(2, 53)).toHaveAccessibleName(/checks pass, waiting on a review/); + await expect(chip(2, 50)).toHaveAttribute("data-tone", "closed"); + await expect(rows.nth(2)).toContainText("2 attempts"); + await expect(rows.nth(2)).toContainText("$9.80"); + await expect(rows.nth(2).getByTestId("drift-mark")).toHaveText("Out of scope"); + await expect(rows.nth(4).getByTestId("drift-mark")).toHaveText("Added"); + // A merged task is faded and marked merged; a failed one says why and offers Retry and Drop. + await expect(rows.nth(0).getByRole("img", { name: "Merged" })).toBeVisible(); + await expect(rows.nth(3)).toContainText("Run timed out"); + await expect(rows.nth(3).getByRole("button", { name: "Retry" })).toBeVisible(); + await expect(rows.nth(3).getByRole("button", { name: "Drop" })).toBeVisible(); + // The draft added after approval can still be approved. + await expect(rows.nth(4).getByRole("button", { name: "Approve and start" })).toBeVisible(); + // Opening a task lists every attempt. + await page.getByRole("button", { name: "Show details of Wire the schedule API" }).click(); + await expect(page.getByRole("link", { name: "Attempt 2" })).toHaveAttribute("href", /RUN53/); + await expect(page.getByRole("link", { name: "Attempt 1" })).toHaveAttribute("href", /RUN50/); + await expect(page.getByText("Changed since approval")).toBeVisible(); + // Once the plan runs, the spec is folded below the work. + await expect(page.getByText("Why: add a class schedule page")).toBeHidden(); + await page.getByTestId("plan-spec").locator("summary").first().click(); + await expect(page.getByText("Why: add a class schedule page")).toBeVisible(); + // Criteria with their evidence. + await expect(page.getByTestId("criteria-count")).toContainText("3 criteria, 1 proven"); + await expect(page.getByTestId("criteria-count")).toBeVisible(); + await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur()); + await shot(page, "plans-detail-running"); + expect(errors).toEqual([]); +}); + +test("a long plan is grouped by state, finished work folded, and what is open is remembered", async ({ page }) => { + const errors = watchConsole(page); + const many = [ + ...runningTasks(), + ...[6, 7, 8, 9].map((i) => + task(`T${i}`, `Merged step ${i}`, "filed", i, { state: "merged", state_detail: `Pull request #${i + 70} merged`, prs: [pr(i + 70, "merged", { state: "merged" })] }), + ), + ]; + await mockApi(page, { planExtra: RUNNING_PLAN, tasks: many, needs: RUNNING_NEEDS }); + await page.goto("/plans/detail/?id=PLANA"); + await expect(page.getByTestId("task-group-needs_you")).toBeVisible(); + // Needs you first, merged last and folded. + const groups = page.locator("[data-testid^=task-group-]"); + await expect(groups.first()).toHaveAttribute("data-testid", "task-group-needs_you"); + await expect(groups.last()).toHaveAttribute("data-testid", "task-group-merged"); + const merged = page.getByTestId("task-group-merged"); + await expect(merged.getByTestId("task")).toHaveCount(0); + await merged.getByRole("button", { expanded: false }).click(); + await expect(merged.getByTestId("task")).toHaveCount(5); + await page.getByRole("button", { name: "Show details of Write the tests" }).click(); + await expect(page.getByTestId("task-reason")).toContainText("Run timed out"); + // Reloaded, the same group is open and the same task too. + await page.reload(); + await expect(page.getByTestId("task-group-merged").getByTestId("task")).toHaveCount(5); + await expect(page.getByTestId("task-reason")).toContainText("Run timed out"); + await page.getByRole("searchbox", { name: "Search tasks" }).fill("print"); + await expect(page.locator("[data-testid=task]")).toHaveCount(1); + expect(errors).toEqual([]); +}); + +test("a plan reads Done only when every task merged or was dropped", async ({ page }) => { const errors = watchConsole(page); await mockApi(page, { - planExtra: { status: "done", destination: "jira", executed_at: NOW, executed_by: "a-person" }, + planExtra: { status: "done", state: "done", summary: "1 of 2 merged, 1 dropped", counts: counts({ merged: 1, dropped: 1 }), cost_usd: 3.4, attempts: 1, destination: "jira", executed_at: NOW, executed_by: "a-person" }, tasks: [ - task("T1", "Add the schedule table", "done", 0, { run_id: "RUN1", pr_url: "https://github.com/your-team/web/pull/41", jira_ticket_key: "WEB-12", jira_ticket_url: "https://your-team.atlassian.net/browse/WEB-12" }), - task("T2", "Show the schedule on the page", "rejected", 1), + task("T1", "Add the schedule table", "filed", 0, { + state: "merged", state_detail: "Pull request #41 merged", ticket_filed: true, prs: [pr(41, "merged", { state: "merged" })], + runs: [{ run_id: "RUN41", status: "merged", created_at: NOW, cost_usd: 3.4 }], jira_ticket_key: "WEB-12", jira_ticket_url: "https://your-team.atlassian.net/browse/WEB-12", + }), + task("T2", "Show the schedule on the page", "rejected", 1, { state: "dropped" }), ], + estimate: null, }); await page.goto("/plans/detail/?id=PLANA"); - const header = page.getByTestId("page-actions"); - await expect(header.getByRole("link", { name: /Open PR/ })).toHaveAttribute("href", "https://github.com/your-team/web/pull/41"); - await expect(page.getByRole("list", { name: "About this plan" })).toContainText("1 of 2 done"); - await expect(page.getByRole("progressbar", { name: "Tasks done" })).toHaveAttribute("aria-valuenow", "1"); - const work = page.getByRole("list", { name: "Runs and PRs" }); - await expect(work.getByRole("link", { name: "Add the schedule table" })).toHaveAttribute("href", /\/runs\/detail\/?\?id=RUN1/); - await expect(work.getByRole("link", { name: "PR #41" })).toBeVisible(); - await expect(page.getByRole("list", { name: "Tasks" }).getByRole("link", { name: "WEB-12" })).toBeVisible(); - // A started plan has nothing to approve. - await expect(page.getByRole("button", { name: "Approve all and start" })).toHaveCount(0); - await expect(page.getByRole("button", { name: "Approve", exact: true })).toHaveCount(0); + const summary = page.getByRole("list", { name: "About this plan" }); + await expect(summary).toContainText("Done"); + await expect(summary).toContainText("1 of 2 merged, 1 dropped"); + await expect(page.getByTestId("state-bar")).toHaveAttribute("aria-label", "Tasks: 1 merged, 1 dropped"); + // Nothing left to approve or act on. + await expect(page.getByRole("button", { name: "Approve and start" })).toHaveCount(0); + await expect(page.getByTestId("needs-strip")).toHaveCount(0); + await expect(page.getByRole("list", { name: "Tasks" }).getByTestId("pr-chip")).toHaveAttribute("data-tone", "merged"); + await page.getByRole("button", { name: "Show details of Add the schedule table" }).click(); + await expect(page.getByRole("link", { name: "WEB-12" })).toBeVisible(); await shot(page, "plans-detail-done"); expect(errors).toEqual([]); }); @@ -470,7 +665,7 @@ test("on a phone the plan's main action is in view, not in a menu", async ({ pag await page.setViewportSize({ width: 390, height: 844 }); await mockApi(page); await page.goto("/plans/detail/?id=PLANA"); - const approve = page.getByRole("button", { name: "Approve all and start" }); + const approve = page.getByTestId("page-actions").getByRole("button", { name: "Approve and start" }); await expect(approve).toBeVisible(); const box = await approve.boundingBox(); expect(box && box.x >= 0 && box.x + box.width <= 390).toBe(true); diff --git a/dashboard/src/app/plans/detail/criteria.tsx b/dashboard/src/app/plans/detail/criteria.tsx new file mode 100644 index 00000000..613d0171 --- /dev/null +++ b/dashboard/src/app/plans/detail/criteria.tsx @@ -0,0 +1,80 @@ +"use client"; + +import Link from "next/link"; +import { useState } from "react"; +import type { PlanCriterion, Task } from "@/lib/api"; +import { StatusText, type StatusLook } from "@/components/list"; +import { focusRing } from "@/components/ui"; + +// The plan's success criteria above its tasks: what done means, each with +// the tasks that cover it and what the work shows for it (the run's criteria +// trace). A long list folds to its count line once the plan runs. + +const FOLD_OVER = 6; + +const PROOF: Record = { + proven: { label: "Proven", tone: "success" }, + not_the_ticket: { label: "Passes without the change", tone: "waiting" }, + failing: { label: "Fails", tone: "danger" }, + missing: { label: "No test", tone: "waiting" }, + unverified: { label: "Unverified", tone: "waiting" }, + not_run: { label: "Not run yet", tone: "neutral" }, +}; + +function look(c: PlanCriterion): StatusLook { + if (c.met) return PROOF.proven; + const worst = ["failing", "missing", "not_the_ticket", "unverified", "not_run"].find((s) => c.evidence.some((e) => e.state === s)); + return worst ? PROOF[worst] : { label: "No evidence yet", tone: "muted" }; +} + +export function CriteriaList({ criteria, tasks, folded }: { criteria: PlanCriterion[]; tasks: Task[]; folded: boolean }) { + const [open, setOpen] = useState(!folded || criteria.length <= FOLD_OVER); + if (criteria.length === 0) { + return

No criteria written. Add "Done when" lines to the tasks, and each one is checked against the work.

; + } + const met = criteria.filter((c) => c.met).length; + const number = (id: string) => tasks.findIndex((t) => t.task_id === id) + 1; + return ( +
+ + {open && ( +
    + {criteria.map((c) => { + const ev = c.evidence[0]; + return ( +
  1. +
    + {c.id} + {c.text} + {c.tasks.length > 0 && ( + + task {c.tasks.map((t) => number(t)).filter((n) => n > 0).join(", ")} + + )} + {ev?.by &&

    {ev.by}{ev.tests && ev.tests.length > 0 ? `: ${ev.tests.join(", ")}` : ""}

    } +
    +
    + + {ev?.run_id && ( + + Proof + + )} +
    +
  2. + ); + })} +
+ )} +
+ ); +} diff --git a/dashboard/src/app/plans/detail/needs.tsx b/dashboard/src/app/plans/detail/needs.tsx new file mode 100644 index 00000000..f5d00219 --- /dev/null +++ b/dashboard/src/app/plans/detail/needs.tsx @@ -0,0 +1,106 @@ +"use client"; + +import Link from "next/link"; +import type { NeedsItem, Task } from "@/lib/api"; +import { ExternalLinkIcon } from "@/components/icons"; +import { buttonClass } from "@/components/ui"; + +// What waits on a person, at the top of the plan, each row the exact ask: +// the run's question, the pull request to review or merge, the checks +// Coderhelm could not fix, the task that failed and why, the drafts left. +// A row goes away once it is handled: the list comes from the work itself. + +const small = buttonClass("secondary", "sm"); +const primarySmall = buttonClass("primary", "sm"); + +export interface NeedsActions { + busy: string | null; + retry: (task: Task) => void; + drop: (taskId: string) => void; + approveRest: () => void; +} + +export function NeedsStrip({ + items, + tasks, + actions, +}: { + items: NeedsItem[]; + tasks: Task[]; + actions: NeedsActions; +}) { + if (items.length === 0) return null; + const number = (id: string) => tasks.findIndex((t) => t.task_id === id) + 1; + return ( +
+

+ Needs you + {items.length} +

+
    + {items.map((n, i) => { + const task = tasks.find((t) => t.task_id === n.task_id); + const busy = (a: string) => actions.busy === `${n.task_id}:${a}`; + return ( +
  • +
    +

    + {task && {number(task.task_id)}.} + {n.ask} +

    + {n.detail &&

    {n.detail}

    } +
    +
    + {n.action === "approve" && ( + + )} + {n.action === "answer" && n.run_id && ( + + Answer + + )} + {(n.action === "open_pr" || n.action === "open_link") && n.url && ( + + {prWord(n)} + + (opens in a new tab) + + )} + {n.action === "retry" && task && ( + <> + + + + )} + {n.run_id && n.action !== "answer" && ( + + Open run + + )} +
    +
  • + ); + })} +
+
+ ); +} + +function prWord(n: NeedsItem): string { + const num = n.url?.match(/\/pull\/(\d+)/)?.[1]; + const what = n.kind === "merge" ? "Merge" : n.kind === "approval" ? "Approve" : n.kind === "checks" ? "See checks on" : "Review"; + return num ? `${what} #${num}` : `${what} the pull request`; +} diff --git a/dashboard/src/app/plans/detail/page.tsx b/dashboard/src/app/plans/detail/page.tsx index e99a731c..6182ef03 100644 --- a/dashboard/src/app/plans/detail/page.tsx +++ b/dashboard/src/app/plans/detail/page.tsx @@ -4,7 +4,7 @@ import { Suspense, useEffect, useState, useCallback, type ReactNode } from "reac import { useSearchParams, useRouter } from "next/navigation"; import Link from "next/link"; import { WorkUsedLine } from "@/components/work-used"; -import { api, type Plan, type Task, type Repo, type Openspec, errorStatus } from "@/lib/api"; +import { api, type FullPlan, type Task, type Repo, type Openspec, type PlanEstimate, errorStatus } from "@/lib/api"; import { useToast } from "@/components/toast"; import { useConfirm } from "@/components/confirm-dialog"; import { Skeleton } from "@/components/skeleton"; @@ -12,19 +12,23 @@ import { Markdown } from "@/components/markdown"; import { Callout } from "@/components/callout"; import { Page, PageHeader } from "@/components/page"; import { SectionNav, type NavSection } from "@/components/section-nav"; -import { ExternalLinkIcon } from "@/components/icons"; -import { List, ListRow, StatusText, Time, TONES } from "@/components/list"; +import { ChevronRightIcon, ExternalLinkIcon } from "@/components/icons"; +import { StatusText, Time, TONES } from "@/components/list"; import { focusRing, linkButton, primaryButton, secondaryButton } from "@/components/ui"; -import { planStatusLook, taskStatusLook } from "../status"; +import { money, moneyRange, planState, planStatusLook, StateBar, taskState } from "../status"; import { TaskChecklist, type NewTask, type TaskActions } from "./tasks"; +import { NeedsStrip } from "./needs"; +import { CriteriaList } from "./criteria"; import { SpecDocument, downloadOpenspec } from "./spec"; import { PlanDetails, destinationWords } from "./details"; import { SaveTemplateDialog } from "./template-dialog"; -// A plan reads as a document: its title and one summary line, the one thing -// to do next, then the plan itself (what and why, the tasks as a checklist, -// the written spec) with a section list beside it on wide screens. Runs and -// PRs it opened are list rows; everything rarely needed sits in Details. +// A plan page in the order a person needs it: the goal and one status line +// with the main action; what needs them, each the exact ask; what done means +// with the evidence so far; the tasks, each with its state, pull requests, +// attempts and cost; then the written spec, folded. Every state comes from +// the runs and pull requests, so the page never says Done before the work +// merged. export default function PlanDetailPage() { return ( @@ -57,7 +61,18 @@ function SkeletonBody() { ); } -type FullPlan = Plan & { tasks: Task[] }; +/** "about 3 to 4 runs, $6 to $14, from your last 40 runs", or what is known. */ +function estimateWords(e: PlanEstimate | null | undefined, tasks: number): string { + const runs = !e || e.runs_low === e.runs_high ? `${tasks} run${tasks === 1 ? "" : "s"}` : `${e.runs_low} to ${e.runs_high} runs`; + if (!e || e.sample === 0) return `${runs}; there is no run history yet to estimate the cost from`; + return `${runs}, about ${moneyRange(e.cost_low, e.cost_high)} from your team's last ${e.sample} runs`; +} + +/** One run's cost, for Retry and Start now. */ +function perRunWords(e: PlanEstimate | null | undefined): string { + if (!e || e.sample === 0) return "It starts a new run."; + return `It starts a new run. Runs like it cost about ${moneyRange(e.per_run_low, e.per_run_high)}.`; +} function PlanDetail() { const searchParams = useSearchParams(); @@ -77,6 +92,8 @@ function PlanDetail() { const [writingSpec, setWritingSpec] = useState(false); const [templateOpen, setTemplateOpen] = useState(false); const [detailsOpen, setDetailsOpen] = useState(false); + // The spec is read while the plan is a draft, then folds below the work. + const [specOpen, setSpecOpen] = useState(null); const { toast } = useToast(); const { confirm } = useConfirm(); @@ -119,16 +136,15 @@ function PlanDetail() { }; }, [planId, loaded]); - // Auto-poll when tasks are queued or running + // Keep reading while work is open: each read derives the states again. + const open = !!plan && ["running", "needs_you", "stalled"].includes(planState(plan)); useEffect(() => { - if (!plan) return; - const hasActive = plan.tasks.some((t) => t.status === "queued" || t.status === "running" || t.status === "waiting"); - if (!hasActive && plan.status !== "executing" && plan.status !== "waiting") return; + if (!open) return; const interval = setInterval(() => { api.getPlan(planId).then(setPlan).catch(() => {}); - }, 5000); + }, 10_000); return () => clearInterval(interval); - }, [plan, planId]); + }, [open, planId]); /** Runs one task action with its busy mark, a toast, and a reload. */ const taskAction = async (key: string, run: () => Promise, ok: string, fail: string | ((e: unknown) => string)) => { @@ -146,25 +162,42 @@ function PlanDetail() { } }; + const estimate = plan?.estimate; + const started = !!plan && planState(plan) !== "drafting"; + const actions: TaskActions = { busy, - approve: (id) => - void taskAction(`${id}:approve`, () => api.approveTask(planId, id), "Approved. Coderhelm will start it next.", (e) => + approve: async (id) => { + // Approving a task starts its run now: say what that costs first. + const ok = await confirm({ + title: "Approve and start this task?", + message: `${perRunWords(estimate)} The plan stays open for its other tasks.`, + confirmLabel: "Approve and start", + }); + if (!ok) return; + void taskAction(`${id}:approve`, () => api.approveTask(planId, id), "Approved. Its run starts now.", (e) => e instanceof Error ? e.message : "Couldn't approve the task. Try again.", - ), - reject: (id) => void taskAction(`${id}:reject`, () => api.rejectTask(planId, id), "Task skipped", "Couldn't skip the task. Try again."), + ); + }, + drop: (id) => void taskAction(`${id}:drop`, () => api.rejectTask(planId, id), "Task dropped", "Couldn't drop the task. Try again."), remove: (id) => void taskAction(`${id}:delete`, () => api.deleteTask(planId, id), "Task removed", "Couldn't remove the task. Try again."), - retry: (id) => void taskAction(`${id}:retry`, () => api.forceRunTask(planId, id), "Trying the task again", "Couldn't retry the task. Try again."), + retry: async (task: Task) => { + const ok = await confirm({ title: `Retry "${task.title}"?`, message: perRunWords(estimate), confirmLabel: "Retry" }); + if (!ok) return; + const last = task.runs?.[task.runs.length - 1]?.run_id ?? task.run_id; + // A task whose ticket was filed retries its run; one that never filed + // its ticket files it again. + const run = last && task.ticket_filed ? () => api.retryRun(last) : () => api.forceRunTask(planId, task.task_id); + void taskAction(`${task.task_id}:retry`, run, "Trying the task again", "Couldn't retry the task. Try again."); + }, forceRun: async (id) => { - setBusy(id); - // Optimistic: move to queued immediately - setPlan((prev) => (prev ? { ...prev, tasks: prev.tasks.map((t) => (t.task_id === id ? { ...t, status: "queued" } : t)) } : prev)); - try { - await api.forceRunTask(planId, id); - } catch { - refresh(); - } - setBusy(null); + const ok = await confirm({ + title: "Start this task now?", + message: `It runs before the task it waits on has merged. ${perRunWords(estimate)}`, + confirmLabel: "Start now", + }); + if (!ok) return; + void taskAction(`${id}:force`, () => api.forceRunTask(planId, id), "Starting the task", "Couldn't start the task. Try again."); }, setDependency: async (id, val) => { // Optimistic update to avoid page flash @@ -203,6 +236,13 @@ function PlanDetail() { }; const handleExecute = async () => { + const drafts = plan?.tasks.filter((x) => taskState(x) === "draft").length ?? 0; + const ok = await confirm({ + title: `Approve and start ${drafts} task${drafts === 1 ? "" : "s"}?`, + message: `This starts ${estimateWords(estimate, drafts)}. Each task's state follows its run and pull request until it merges.`, + confirmLabel: "Approve and start", + }); + if (!ok) return; setExecuting(true); try { const result = await api.approveAllAndExecute(planId); @@ -289,17 +329,18 @@ function PlanDetail() { } const tasks = plan.tasks; - const isDraft = plan.status === "draft"; - const draftCount = tasks.filter((t) => t.status === "draft").length; - const doneCount = tasks.filter((t) => t.status === "done").length; - const worked = tasks.filter((t) => t.run_id || t.pr_url); - const prs = tasks.filter((t) => t.pr_url); + const state = planState(plan); + const isDraft = state === "drafting"; + const draftCount = tasks.filter((t) => taskState(t) === "draft").length; + const needs = plan.needs ?? []; + const criteria = plan.criteria ?? []; + const readyPrs = tasks.flatMap((t) => (t.prs ?? []).filter((p) => p.tone === "ready")); const repoNames = [...new Set([plan.repo, ...tasks.map((t) => t.repo)].filter((r): r is string => !!r))]; const sections: NavSection[] = [ - ...(plan.description ? [{ id: "overview", label: "Overview" }] : []), + ...(needs.length > 0 ? [{ id: "needs", label: "Needs you", count: needs.length }] : []), + { id: "criteria", label: "What done means", count: criteria.length || undefined }, { id: "tasks", label: "Tasks", count: tasks.length }, - ...(worked.length > 0 ? [{ id: "work", label: "Runs and PRs", count: worked.length }] : []), { id: "spec", label: "Spec" }, { id: "details", label: "Details" }, ]; @@ -309,25 +350,25 @@ function PlanDetail() { if (isDraft && draftCount > 0) { primary = ( ); - } else if (prs.length === 1) { + } else if (needs.length > 0) { + primary = ( + + {needs.length} need{needs.length === 1 ? "s" : ""} you + + ); + } else if (readyPrs.length > 0) { primary = ( - - Open PR + + Merge PR #{readyPrs[0].number} (opens in a new tab) ); - } else if (prs.length > 1) { - primary = ( - - See {prs.length} PRs - - ); } const more = [ @@ -342,20 +383,17 @@ function PlanDetail() {
  • - +
  • - {repoNames.length > 0 && ( -
  • - {repoNames.length === 1 ? repoNames[0] : `${repoNames.length} repos`} +
  • {plan.summary || `${tasks.length} task${tasks.length === 1 ? "" : "s"}`}
  • + {(plan.cost_usd ?? 0) > 0 && ( +
  • + {money(plan.cost_usd)} over {plan.attempts ?? 0} run{plan.attempts === 1 ? "" : "s"}
  • )} -
  • - {tasks.length === 0 - ? "No tasks" - : isDraft - ? `${tasks.length} task${tasks.length === 1 ? "" : "s"}${draftCount > 0 && draftCount < tasks.length ? `, ${draftCount} to review` : ""}` - : `${doneCount} of ${tasks.length} done`} -
  • + {repoNames.length > 0 && ( +
  • {repoNames.length === 1 ? repoNames[0] : `${repoNames.length} repos`}
  • + )}
  • {isDraft ? (
  • - {plan.created_at && ( + {plan.last_activity_at ? ( +
  • + Last activity
  • + ) : plan.created_at ? (
  • Created
  • - )} + ) : null}
- {!isDraft && tasks.length > 0 && ( -
-
-
+ {!isDraft && } + {isDraft && draftCount > 0 && ( +

+ Approving all {draftCount} task{draftCount === 1 ? "" : "s"} starts {estimateWords(estimate, draftCount)}. +

+ )} + {state === "stalled" && ( +

Nothing has moved on this plan for 3 days. Its open tasks are below.

)}
- {plan.description && ( - -
- {plan.description} -
-
- )} + void handleExecute(), + }} + /> + + + + 0 - ? "Approve tasks one at a time, or approve them all and start. Approving the last one starts the plan." - : undefined + ? "Approve them all and start, or approve one at a time: the plan stays open for the rest either way." + : state === "running" || state === "stalled" + ? "To steer a task while it works, comment on its pull request or answer on its run page." + : undefined } > - + - {worked.length > 0 && ( - - - {worked.map((t) => ( - - {prLabel(t.pr_url)} - - ), - ]} - /> - ))} - - - )} - - - - +
+
{ + const o = (e.currentTarget as HTMLDetailsElement).open; + if (o !== (specOpen ?? isDraft)) setSpecOpen(o); + }} + > + + +

+ Spec +

+ what and why, as written +
+
+ {plan.description && ( +
+ {plan.description} +
+ )} + +
+
+
:". */ busy: string | null; approve: (taskId: string) => void; - reject: (taskId: string) => void; + drop: (taskId: string) => void; remove: (taskId: string) => void; - retry: (taskId: string) => void; + retry: (task: Task) => void; forceRun: (taskId: string) => void; setDependency: (taskId: string, dependsOn: string) => void; save: (taskId: string, edit: Partial) => Promise; @@ -46,326 +50,442 @@ const taskFields = (t: Task): NewTask => ({ depends_on: t.depends_on ?? "", }); -/** Tasks above this get a search box and status filters. */ -const FILTER_OVER = 6; +/** Tasks above this are grouped by state, with a search box. */ +const GROUP_OVER = 8; const quietButton = buttonClass("secondary", "sm"); const ghostSmall = buttonClass("ghost", "sm"); +/** A value kept per plan in this browser; never needed for the page to work. */ +function useRemembered(key: string, initial: T): [T, (v: T) => void] { + const [v, setV] = useState(initial); + useEffect(() => { + try { + const raw = window.localStorage.getItem(key); + if (raw !== null) setV(JSON.parse(raw) as T); + } catch { + /* storage blocked: start fresh */ + } + }, [key]); + const set = (next: T) => { + setV(next); + try { + window.localStorage.setItem(key, JSON.stringify(next)); + } catch { + /* storage blocked */ + } + }; + return [v, set]; +} + export function TaskChecklist({ + planId, tasks, planRepo, - draft, + started, repos, actions, }: { + planId: string; tasks: Task[]; planRepo: string; - /** The plan has not started: tasks can be approved, skipped, edited, added. */ - draft: boolean; + /** The plan has started: drafts are still approved from their rows. */ + started: boolean; repos: Repo[]; actions: TaskActions; }) { - const [openId, setOpenId] = useState(null); + const [openId, setOpenId] = useRemembered(`plan:${planId}:open-task`, null); + const [folded, setFolded] = useRemembered(`plan:${planId}:folded`, ["merged", "dropped"]); const [editingId, setEditingId] = useState(null); const [query, setQuery] = useState(""); - const [filters, setFilters] = useState>(new Set()); const [adding, setAdding] = useState(false); - const filtering = tasks.length > FILTER_OVER; + const grouped = tasks.length > GROUP_OVER; const q = query.trim().toLowerCase(); - const shown = tasks.filter((t) => { - if (!filtering) return true; - if (q && !t.title.toLowerCase().includes(q) && !t.description?.toLowerCase().includes(q)) return false; - if (filters.size > 0 && !filters.has(t.status)) return false; - return true; - }); + const shown = tasks.filter((t) => !q || t.title.toLowerCase().includes(q) || t.description?.toLowerCase().includes(q)); const number = (id: string) => tasks.findIndex((t) => t.task_id === id) + 1; + const row = (task: Task) => ( + { + setOpenId(o ? task.task_id : null); + if (!o) setEditingId(null); + }} + editing={editingId === task.task_id} + setEditing={(e) => setEditingId(e ? task.task_id : null)} + /> + ); + return (
- {filtering && ( -
- setQuery(e.target.value)} - className={inputClass} - /> -
- {TASK_ORDER.map((s) => { - const count = tasks.filter((t) => t.status === s).length; - if (count === 0) return null; - const on = filters.has(s); - return ( + {grouped && ( + setQuery(e.target.value)} + className={inputClass} + /> + )} + + {tasks.length === 0 ? ( + {!started ? "Add the first one below." : "This plan has no tasks."} + ) : shown.length === 0 ? ( + setQuery("")} /> + ) : grouped ? ( +
+ {TASK_ORDER.map((s) => { + const inGroup = shown.filter((t) => taskState(t) === s); + if (inGroup.length === 0) return null; + const look = taskStatusLook(s); + const isFolded = folded.includes(s) && !q; + return ( +
- ); - })} - {filters.size > 0 && ( - - )} -
+ {!isFolded && {inGroup.map(row)}} +
+ ); + })}
+ ) : ( + {shown.map(row)} )} - {tasks.length === 0 ? ( - {draft ? "Add the first one below." : "This plan has no tasks."} - ) : shown.length === 0 ? ( - { setQuery(""); setFilters(new Set()); }} /> + {adding ? ( +
+ setAdding(false)} + onSubmit={async (v) => { + const ok = await actions.add(v); + if (ok) setAdding(false); + return ok; + }} + /> + {started &&

Added after approval: the task is marked as added, and starts as a draft.

} +
) : ( - - {shown.map((task) => { - const others = tasks.filter((t) => t.task_id !== task.task_id); - const dep = task.depends_on ? tasks.find((t) => t.task_id === task.depends_on) : undefined; - const look = taskStatusLook(task.status); - const editing = editingId === task.task_id; - const busy = (a: string) => actions.busy === `${task.task_id}:${a}`; - return ( - } - title={ - <> - {number(task.task_id)}. - {task.title} - - } - titleText={task.title} - quiet={task.status === "rejected" || task.status === "done"} - meta={[ - , - task.issue_url && ( - - Issue #{task.issue_number} - - ), - task.jira_ticket_url && ( - - {task.jira_ticket_key} - - ), - dep && after {number(dep.task_id)}, - task.repo && task.repo !== planRepo && ( - - in {task.repo.split("/").pop()} - - ), - ]} - actions={ - - } - open={openId === task.task_id} - onOpenChange={(o) => { - setOpenId(o ? task.task_id : null); - if (!o) setEditingId(null); - }} - detailsFor={`details of ${task.title}`} - details={ - editing ? ( - setEditingId(null)} - onSubmit={async (v) => { - // Only what changed is sent, as before. - const was = taskFields(task); - const edit = Object.fromEntries( - (Object.keys(v) as (keyof NewTask)[]).filter((k) => v[k] !== was[k]).map((k) => [k, v[k]]), - ) as Partial; - const ok = await actions.save(task.task_id, edit); - if (ok) setEditingId(null); - return ok; - }} - /> - ) : ( - <> - {task.description ? ( -
- {task.description} -
- ) : ( -

No description.

- )} - {task.acceptance_criteria && ( - -
- {task.acceptance_criteria} -
-
- )} - {task.status === "waiting" && dep && ( -

Starts when the PR for task {number(dep.task_id)} merges.

- )} - {task.approved_by &&

Approved by {task.approved_by}

} - {draft && ( -
- {others.length > 0 && ( - + )} +
+ + +
+
+ )} + + ) + } + /> ); } /** The one or two buttons a task needs right now, beside its row. */ function RowActions({ task, - draft, + state, + started, actions, busy, }: { task: Task; - draft: boolean; + state: TaskState; + started: boolean; actions: TaskActions; busy: (a: string) => boolean; }) { const any = !!actions.busy; - if (task.status === "failed") { + if (state === "failed") { return ( - + <> + + + ); } - if (task.status === "waiting" && task.depends_on) { + if (state === "queued" && task.status === "waiting" && task.depends_on) { return ( ); } - if (!draft) return null; - if (task.status === "draft") { + if (state === "draft") { return ( <> - - ); } - if (task.status === "approved") { - return ( - - ); - } - if (task.status === "rejected") { + if (state === "dropped" && (task.runs ?? []).length === 0) { return ( ); } return null; } -/** The checklist mark: an empty box, a tick, a cross, or a pulsing dot. */ -export function TaskMark({ status }: { status: string }) { - const look = taskStatusLook(status); +/** The row's mark: an empty box, a tick, a cross, or a pulsing dot. */ +export function TaskMark({ state }: { state: string }) { + const look = taskStatusLook(state); const box = "inline-flex h-4 w-4 items-center justify-center rounded border"; const glyph = (d: string, cls: string) => ( @@ -373,31 +493,28 @@ export function TaskMark({ status }: { status: string }) { ); let mark; - switch (status) { - case "done": - mark = {glyph("M3.5 8.5l3 3 6-7", "text-emerald-300")}; - break; - case "approved": - mark = {glyph("M3.5 8.5l3 3 6-7", "text-sky-300/80")}; + switch (state) { + case "merged": + mark = {glyph("M3.5 8.5l3 3 6-7", "text-violet-200")}; break; case "failed": mark = {glyph("M5 5l6 6M11 5l-6 6", "text-red-300")}; break; - case "rejected": - mark = {glyph("M4.5 8h7", "text-zinc-500")}; + case "dropped": + mark = {glyph("M4.5 8h7", "text-zinc-400")}; + break; + case "needs_you": + mark = {glyph("M8 4v5M8 11.5v.5", "text-orange-300")}; + break; + case "draft": + mark = ; break; - case "running": - case "queued": - case "waiting": - case "issue_created": + default: mark = ( - - + + ); - break; - default: - mark = ; } return ( diff --git a/dashboard/src/app/plans/page.tsx b/dashboard/src/app/plans/page.tsx index 47a6d4ae..a99634f2 100644 --- a/dashboard/src/app/plans/page.tsx +++ b/dashboard/src/app/plans/page.tsx @@ -15,24 +15,31 @@ import { ListToolbar, LoadMore, StatusText, + TONES, useListParams, usePagedList, useTeamRepos, } from "@/components/list"; -import { planStatusLook } from "./status"; +import { money, planState, planStatusLook, StateBar } from "./status"; -// The status toggles: each is one plan status. +// The toggles: each is a set of plan states. A plan is Active while its work +// runs (or sits stalled); Needs you when a task asks a person something, +// failed, or drafts are left once the rest finished; Done only when every +// task merged or was dropped. const TABS = [ - { value: "all", label: GROUP_LABEL.all, status: "" }, - { value: "active", label: GROUP_LABEL.active, status: "executing", tone: "live" }, - { value: "waiting", label: GROUP_LABEL.waiting, status: "waiting", tone: "waiting" }, - { value: "draft", label: "Draft", status: "draft", tone: "neutral" }, - { value: "done", label: GROUP_LABEL.done, status: "done", tone: "success" }, + { value: "all", label: GROUP_LABEL.all, states: [] as string[] }, + { value: "active", label: GROUP_LABEL.active, states: ["running", "stalled"], tone: "live" }, + { value: "needs_you", label: "Needs you", states: ["needs_you"], tone: "attention" }, + { value: "drafting", label: "Drafting", states: ["drafting"], tone: "neutral" }, + { value: "done", label: GROUP_LABEL.done, states: ["done"], tone: "success" }, ] as const; +// Needs you first, then running work, then the rest by date. +const RANK: Record = { needs_you: 0, running: 1, stalled: 2, drafting: 3, done: 4 }; + function planMatches(plan: Plan, q: string): boolean { if (!q) return true; - const hay = [plan.title, plan.description, plan.repo].filter(Boolean).join(" ").toLowerCase(); + const hay = [plan.title, plan.description, plan.repo, plan.summary].filter(Boolean).join(" ").toLowerCase(); return q .toLowerCase() .split(/\s+/) @@ -49,6 +56,7 @@ export default function PlansPageWithParams() { function PlansPage() { const [params, setParams] = useListParams({ q: "", status: "all", repo: "" }); + const inTab = (p: Plan, states: readonly string[]) => states.length === 0 || states.includes(planState(p)); const q = params.q.trim(); const tab = TABS.find((t) => t.value === params.status) ?? TABS[0]; const repo = params.repo; @@ -60,10 +68,11 @@ function PlansPage() { // Search and repo first, so the toggle counts say what each would show. const matched = useMemo(() => plans.filter((p) => planMatches(p, q) && (!repo || p.repo === repo)), [plans, q, repo]); - // A running plan is pinned to the top: it is the one people come back to. - const shown = (tab.status ? matched.filter((p) => p.status === tab.status) : matched) + // What needs a person is pinned to the top, then running work. + const shown = matched + .filter((p) => inTab(p, tab.states)) .slice() - .sort((a, b) => Number(b.status === "executing") - Number(a.status === "executing")); + .sort((a, b) => (RANK[planState(a)] ?? 9) - (RANK[planState(b)] ?? 9)); const filtered = !!(q || repo || tab.value !== "all"); const clear = () => setParams({ q: "", status: "all", repo: "" }); @@ -71,7 +80,7 @@ function PlansPage() { New plan @@ -95,7 +104,7 @@ function PlansPage() { options: TABS.map((t) => ({ value: t.value, label: t.label, - count: t.status ? matched.filter((p) => p.status === t.status).length : matched.length, + count: matched.filter((p) => inTab(p, t.states)).length, tone: "tone" in t ? t.tone : undefined, })), }} @@ -118,7 +127,7 @@ function PlansPage() { } > - A plan splits a bigger change into small steps. Coderhelm builds them one at a time, and you approve each one. + A plan splits a bigger change into tasks. You approve them, Coderhelm builds each one, and the plan is done when every task merged. ) : shown.length === 0 ? ( @@ -127,23 +136,37 @@ function PlansPage() { ) : ( {shown.map((plan) => { - const look = planStatusLook(plan.status); + const state = planState(plan); + const look = planStatusLook(state); + const needs = plan.needs_count ?? 0; return ( {money(plan.cost_usd)} : null, !repo ? plan.repo || null : null, - plan.task_count ? `${plan.task_count} task${plan.task_count === 1 ? "" : "s"}` : null, ]} - summary={plainSummary(plan.description)} - chips={} - time={plan.created_at} - /> + chips={ + <> + {needs > 0 && ( + + {needs} need{needs === 1 ? "s" : ""} you + + )} + + + } + time={plan.last_activity_at || plan.created_at} + > + {plan.counts && state !== "drafting" && } +
); })}
@@ -153,9 +176,3 @@ function PlansPage() { ); } - -/** A plan's description as one plain line: links become "link" so a row never shows a raw URL. */ -function plainSummary(text: string | null | undefined): string | undefined { - if (!text) return undefined; - return text.replace(/https?:\/\/\S+/g, "(link)").replace(/[#*`>]/g, "").replace(/\s+/g, " ").trim() || undefined; -} diff --git a/dashboard/src/app/plans/status.tsx b/dashboard/src/app/plans/status.tsx index 378342b9..f37b0399 100644 --- a/dashboard/src/app/plans/status.tsx +++ b/dashboard/src/app/plans/status.tsx @@ -1,73 +1,174 @@ -import { TONES, type StatusLook } from "@/components/list/status"; +import { TONES, type StatusLook, type Tone } from "@/components/list/status"; +import type { Plan, PrChip as PrChipData, Task, TaskCounts, TaskState } from "@/lib/api"; +import { focusRing } from "@/components/ui"; -// Plain-word status pills for plans and their tasks. The API sends status -// words like "rejected" or "waiting"; people see what they mean. +// Where a plan and its tasks stand, in plain words and the shared list tones. +// The states come from the API, derived from the runs and pull requests +// (never from a ticket being filed): a plan is Done only when every task +// merged or was dropped. const PILL = "inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium whitespace-nowrap"; -// Plans use the shared list tones (components/list/status), so "Running" is -// the same colour here as on Runs. const PLAN: Record = { - draft: { label: "Draft", tone: "neutral" }, - executing: { label: "Running", tone: "live", live: true }, - waiting: { label: "Waiting on a merge", tone: "waiting" }, + drafting: { label: "Drafting", tone: "neutral" }, + running: { label: "Running", tone: "live", live: true }, + needs_you: { label: "Needs you", tone: "attention" }, done: { label: "Done", tone: "success" }, + stalled: { label: "Stalled", tone: "waiting" }, }; -/** How a plan's status looks in a list; unknown statuses read as plain words. */ -export function planStatusLook(status: string): StatusLook { - return PLAN[status] ?? { label: words(status), tone: "neutral" }; +/** A plan's state; older answers without one read from the older word. */ +export function planState(plan: Pick): string { + if (plan.state) return plan.state; + if (plan.status === "draft") return "drafting"; + // An older "done" was written when tickets were filed, not when work merged. + return "running"; +} + +/** How a plan's state looks in a list or a header. */ +export function planStatusLook(state: string): StatusLook { + return PLAN[state] ?? PLAN[planState({ status: state })] ?? { label: words(state), tone: "neutral" }; +} + +export function PlanStatusPill({ state }: { state: string }) { + const s = planStatusLook(state); + return {s.label}; } -export const TASK: Record = { - draft: { label: "Draft", style: "bg-zinc-800 text-zinc-400 border-zinc-700", dot: "bg-zinc-700", border: "border-l-zinc-700" }, - approved: { label: "Approved", style: "bg-green-500/10 text-green-400 border-green-500/20", dot: "bg-green-500/60", border: "border-l-green-500/50" }, - rejected: { label: "Skipped", style: "bg-zinc-800 text-zinc-500 border-zinc-700", dot: "bg-zinc-600", border: "border-l-zinc-600" }, - queued: { label: "Queued", style: "bg-yellow-500/10 text-yellow-400 border-yellow-500/20", dot: "bg-yellow-500/60", border: "border-l-yellow-500/50" }, - running: { label: "Running", style: "bg-blue-500/10 text-blue-400 border-blue-500/20", dot: "bg-blue-500", border: "border-l-blue-500" }, - waiting: { label: "Waiting", style: "bg-orange-500/10 text-orange-400 border-orange-500/20", dot: "bg-orange-500/60", border: "border-l-orange-500/50" }, - failed: { label: "Failed", style: "bg-red-500/10 text-red-400 border-red-500/20", dot: "bg-red-500/70", border: "border-l-red-500/60" }, - issue_created: { label: "Issue opened", style: "bg-blue-500/10 text-blue-300 border-blue-500/20", dot: "bg-blue-400/60", border: "border-l-blue-400/50" }, - done: { label: "Done", style: "bg-emerald-500/10 text-emerald-400 border-emerald-500/20", dot: "bg-emerald-500", border: "border-l-emerald-500" }, +/** Task states in the order people act on them (the groups and filters). */ +export const TASK_ORDER: TaskState[] = ["needs_you", "failed", "in_review", "working", "queued", "draft", "merged", "dropped"]; + +const TASK_LOOK: Record = { + draft: { label: "Draft", tone: "neutral" }, + queued: { label: "Queued", tone: "queued", live: true }, + working: { label: "Working", tone: "live", live: true }, + needs_you: { label: "Needs you", tone: "attention" }, + failed: { label: "Failed", tone: "danger" }, + in_review: { label: "In review", tone: "waiting" }, + merged: { label: "Merged", tone: "merged" }, + dropped: { label: "Dropped", tone: "muted" }, }; -/** Task statuses in the order the filter chips show them. */ -export const TASK_ORDER = ["draft", "approved", "rejected", "queued", "running", "waiting", "failed", "issue_created", "done"]; +/** A task's state; older answers without one read from the row's own word. */ +export function taskState(task: Pick): TaskState { + if (task.state && task.state in TASK_LOOK) return task.state as TaskState; + switch (task.status) { + case "draft": + return "draft"; + case "rejected": + return "dropped"; + case "failed": + return "failed"; + case "running": + return "working"; + default: + return "queued"; + } +} + +export function taskStatusLook(state: string): StatusLook { + return TASK_LOOK[state as TaskState] ?? { label: words(state), tone: "neutral" }; +} + +/** Finished: nothing more happens on it, so its row is faded. */ +export function taskFinished(state: string): boolean { + return state === "merged" || state === "dropped"; +} function words(status: string): string { const s = (status || "unknown").replace(/_/g, " "); return s.charAt(0).toUpperCase() + s.slice(1); } -export function taskInfo(status: string) { - return TASK[status] ?? { ...TASK.draft, label: words(status) }; +/** "$12.40", "$0.30", or "under $0.01". */ +export function money(v: number | null | undefined): string { + const n = v ?? 0; + if (n > 0 && n < 0.01) return "under $0.01"; + return `$${n.toFixed(2)}`; } -export function PlanStatusPill({ status }: { status: string }) { - const s = planStatusLook(status); - return {s.label}; +/** "$3 to $9" from an estimate's low and high. */ +export function moneyRange(low: number, high: number): string { + const r = (n: number) => `$${n.toFixed(2)}`; + return Math.abs(high - low) < 0.005 ? r(low) : `${r(low)} to ${r(high)}`; } -export function TaskStatusPill({ status }: { status: string }) { - const s = taskInfo(status); - return {s.label}; +// The colour of a pull request chip: green ready to merge, yellow waiting on +// checks or a review, red failing, purple merged, grey closed or draft. +const CHIP_TONE: Record = { + ready: "success", + waiting: "waiting", + failing: "danger", + merged: "merged", + closed: "muted", +}; + +/** What the chip's colour means, in words, for its hover text and screen readers. */ +export function chipWords(pr: PrChipData): string { + if (pr.state === "merged") return "merged"; + if (pr.state === "closed") return "closed without merging"; + const parts: string[] = []; + if (pr.state === "draft") parts.push("draft"); + parts.push( + pr.checks === "passed" + ? "checks pass" + : pr.checks === "failed" + ? "checks fail" + : pr.checks === "running" + ? "checks running" + : "checks not reported", + ); + if (pr.review === "approved") parts.push("approved"); + else if (pr.review === "changes_requested") parts.push("changes requested"); + else if (pr.review === "waiting") parts.push("waiting on a review"); + if (pr.tone === "ready") parts.push("ready to merge"); + return parts.join(", "); } -// A task's status as the shared list tones, for the checklist mark and the -// status word on a task row. -const TASK_TONE: Record = { - draft: { label: "Draft", tone: "neutral" }, - approved: { label: "Approved", tone: "queued", live: false }, - rejected: { label: "Skipped", tone: "muted" }, - queued: { label: "Queued", tone: "queued" }, - running: { label: "Running", tone: "live", live: true }, - waiting: { label: "Waiting on a merge", tone: "waiting" }, - failed: { label: "Failed", tone: "danger" }, - issue_created: { label: "Issue opened", tone: "attention" }, - done: { label: "Done", tone: "success" }, -}; +/** A pull request number coloured by where it stands, with its size. */ +export function PrChip({ pr }: { pr: PrChipData }) { + const tone = TONES[CHIP_TONE[pr.tone] ?? "neutral"]; + const what = chipWords(pr); + const size = pr.additions != null && pr.deletions != null ? ` +${pr.additions} -${pr.deletions}` : ""; + return ( + + + ); +} + +const BAR_ORDER: TaskState[] = ["merged", "in_review", "working", "queued", "needs_you", "failed", "draft", "dropped"]; -/** How a task's status reads on its row; unknown statuses read as plain words. */ -export function taskStatusLook(status: string): StatusLook { - return TASK_TONE[status] ?? { label: words(status), tone: "neutral" }; +/** The tasks by state as one thin bar: merged first, then the work still open. */ +export function StateBar({ counts, className = "" }: { counts: TaskCounts | null | undefined; className?: string }) { + if (!counts) return null; + const total = BAR_ORDER.reduce((n, s) => n + (counts[s] ?? 0), 0); + if (total === 0) return null; + const said = BAR_ORDER.filter((s) => (counts[s] ?? 0) > 0) + .map((s) => `${counts[s]} ${taskStatusLook(s).label.toLowerCase()}`) + .join(", "); + return ( +
+ {BAR_ORDER.map((s) => { + const n = counts[s] ?? 0; + if (!n) return null; + return ; + })} +
+ ); } diff --git a/dashboard/src/lib/api.ts b/dashboard/src/lib/api.ts index c15615f1..0b2eca98 100644 --- a/dashboard/src/lib/api.ts +++ b/dashboard/src/lib/api.ts @@ -819,7 +819,7 @@ export const api = { body: JSON.stringify(body), }), getPlan: (planId: string) => - request(`/api/plans/${planId}`), + request(`/api/plans/${planId}`), updatePlan: ( planId: string, body: Partial<{ @@ -3024,13 +3024,97 @@ export interface TeamInfo { current: boolean; } +/** Where a plan stands, from its tasks' work. */ +export type PlanState = "drafting" | "running" | "needs_you" | "done" | "stalled"; +/** Where a task stands, from its runs and pull requests. */ +export type TaskState = "draft" | "queued" | "working" | "needs_you" | "failed" | "in_review" | "merged" | "dropped"; + +/** How many tasks are in each state. */ +export type TaskCounts = Record; + +/** A pull request as a chip, coloured by its checks and review. */ +export interface PrChip { + number: number; + url: string; + repo: string; + state: "open" | "draft" | "merged" | "closed" | string; + checks: "passed" | "failed" | "running" | "unknown" | string; + review: "approved" | "changes_requested" | "waiting" | "none" | string; + tone: "ready" | "waiting" | "failing" | "merged" | "closed" | string; + additions?: number; + deletions?: number; + run_id: string; +} + +/** Something a person has to do for the plan to go on: the exact ask. */ +export interface NeedsItem { + task_id: string; + kind: "answer" | "review" | "approval" | "checks" | "merge" | "failed" | "closed_pr" | "approve_rest" | string; + ask: string; + detail?: string; + url?: string; + run_id?: string; + action: "answer" | "open_pr" | "open_link" | "retry" | "approve" | string; +} + +/** A change to the plan after it was approved, or work outside a task's scope. */ +export interface PlanDrift { + kind: "added" | "changed" | "dropped" | "scope" | string; + detail: string; + by?: "agent" | "person" | string; + by_name?: string; + at?: string; +} + +/** One attempt at a task. */ +export interface TaskRun { + run_id: string; + status: string; + created_at: string; + cost_usd: number; +} + +/** A success criterion with what the work shows for it. */ +export interface PlanCriterion { + id: string; + text: string; + tasks: string[]; + met: boolean; + evidence: { task_id: string; run_id: string; state: string; words: string; by?: string; tests?: string[] }[]; +} + +/** What starting tasks, or retrying one, is expected to take. */ +export interface PlanEstimate { + tasks: number; + runs_low: number; + runs_high: number; + cost_low: number; + cost_high: number; + per_run_low: number; + per_run_high: number; + /** Finished runs the numbers come from; 0 = no history yet. */ + sample: number; +} + export interface Plan { plan_id: string; title: string; description: string; repo: string; destination?: "github" | "jira" | string; + /** The older word (draft, executing, done); read `state`. */ status: "draft" | "executing" | "waiting" | "done" | string; + state?: PlanState | string | null; + /** "2 of 5 merged, 1 needs you, 1 in review". */ + summary?: string | null; + counts?: TaskCounts | null; + needs_count?: number; + cost_usd?: number | null; + attempts?: number | null; + criteria_met?: number | null; + criteria_count?: number | null; + last_activity_at?: string | null; + success_criteria?: string[] | null; task_count: number; tokens_in?: number; tokens_out?: number; @@ -3076,7 +3160,29 @@ export interface Task { rejected_at?: string; rejected_by?: string; created_at: string; -} + state?: TaskState | string | null; + /** What it is doing, waits on, or what blocks it. */ + state_detail?: string | null; + /** Why it failed. */ + state_reason?: string | null; + attempts?: number | null; + cost_usd?: number | null; + runs?: TaskRun[] | null; + prs?: PrChip[] | null; + needs?: NeedsItem | null; + drift?: PlanDrift[] | null; + covers?: string[] | null; + ticket_filed?: boolean | null; + last_activity_at?: string | null; +} + +/** A plan with its tasks, criteria, what waits on people and the start estimate. */ +export type FullPlan = Plan & { + tasks: Task[]; + criteria?: PlanCriterion[]; + needs?: NeedsItem[]; + estimate?: PlanEstimate | null; +}; export interface TaskTemplate { title: string; diff --git a/dashboard/src/lib/openapi-fields.ts b/dashboard/src/lib/openapi-fields.ts index c1487bad..cc314974 100644 --- a/dashboard/src/lib/openapi-fields.ts +++ b/dashboard/src/lib/openapi-fields.ts @@ -2,7 +2,7 @@ // docs/api/openapi.json. Do not edit; run `npm run openapi:fields` instead. /** The platform commit this was generated from. */ -export const OPENAPI_REF = "b60be33c1bad33dcbbd883c3442096a6cf4e937c"; +export const OPENAPI_REF = "26f64e8cec0e615f55dea85025ec44989e7ef9ad"; /** The fields each public API schema has. */ export interface OpenApiFields { @@ -14,7 +14,7 @@ export interface OpenApiFields { CiUploadResult: "ok"; CodegenEnvMissing: "command" | "repo" | "vars"; CreateEndpointBody: "description" | "enabled" | "events" | "url"; - CreatePlan: "description" | "destination" | "repo" | "tasks" | "title"; + CreatePlan: "description" | "destination" | "repo" | "success_criteria" | "tasks" | "title"; CreatedEndpoint: "endpoint" | "secret"; CreatedPlan: "plan_id"; CustomRoleRef: "id" | "name"; @@ -38,13 +38,14 @@ export interface OpenApiFields { Me: "api_key" | "auth_provider" | "avatar_url" | "capabilities" | "custom_role" | "email" | "flags" | "github_login" | "mfa_enabled" | "platform_admin" | "role" | "status" | "team_id" | "user_id"; MeApiKey: "created_by" | "expires_at" | "id" | "name" | "rate_limit_per_minute"; MeFlags: "plugins"; - NewPlanTask: "acceptance_criteria" | "description" | "destination" | "jira_project" | "repo" | "title"; + NeedsYou: "action" | "ask" | "detail" | "kind" | "run_id" | "task_id" | "url"; + NewPlanTask: "acceptance_criteria" | "covers" | "description" | "destination" | "jira_project" | "repo" | "title"; OverviewFile: "description" | "path"; - Plan: "chat_id" | "created_at" | "description" | "destination" | "executed_at" | "executed_by" | "mcp_servers" | "plan_id" | "repo" | "status" | "task_count" | "title" | "tokens_in" | "tokens_out" | "updated_at"; + Plan: "attempts" | "chat_id" | "cost_usd" | "counts" | "created_at" | "criteria_count" | "criteria_met" | "description" | "destination" | "executed_at" | "executed_by" | "last_activity_at" | "mcp_servers" | "needs_count" | "plan_id" | "repo" | "state" | "status" | "success_criteria" | "summary" | "task_count" | "title" | "tokens_in" | "tokens_out" | "updated_at"; PlanDestination: never; PlanExecution: "status" | "tasks_queued"; - PlanTask: "acceptance_criteria" | "approved_at" | "approved_by" | "created_at" | "depends_on" | "description" | "destination" | "issue_number" | "issue_url" | "jira_project" | "jira_ticket_key" | "jira_ticket_url" | "order" | "plan_id" | "pr_url" | "rejected_at" | "rejected_by" | "repo" | "run_id" | "status" | "task_id" | "title"; - PlanWithTasks: "chat_id" | "created_at" | "description" | "destination" | "executed_at" | "executed_by" | "mcp_servers" | "plan_id" | "repo" | "status" | "task_count" | "tasks" | "title" | "tokens_in" | "tokens_out" | "updated_at"; + PlanTask: "acceptance_criteria" | "approved_at" | "approved_by" | "attempts" | "cost_usd" | "covers" | "created_at" | "depends_on" | "description" | "destination" | "drift" | "issue_number" | "issue_url" | "jira_project" | "jira_ticket_key" | "jira_ticket_url" | "last_activity_at" | "needs" | "order" | "plan_id" | "pr_url" | "prs" | "rejected_at" | "rejected_by" | "repo" | "run_id" | "runs" | "state" | "state_detail" | "state_reason" | "status" | "task_id" | "ticket_filed" | "title"; + PlanWithTasks: "attempts" | "chat_id" | "cost_usd" | "counts" | "created_at" | "criteria" | "criteria_count" | "criteria_met" | "description" | "destination" | "estimate" | "executed_at" | "executed_by" | "last_activity_at" | "mcp_servers" | "needs" | "needs_count" | "plan_id" | "repo" | "state" | "status" | "success_criteria" | "summary" | "task_count" | "tasks" | "title" | "tokens_in" | "tokens_out" | "updated_at"; PlansPage: "next" | "next_cursor" | "plans"; Point: "deliveries" | "end" | "failed" | "ok" | "p50_ms" | "p95_ms" | "previous_deliveries" | "start" | "success_rate"; PushedCommit: "message" | "sha"; @@ -65,16 +66,19 @@ export interface OpenApiFields { RotateBody: "overlap_hours"; RotatedSecret: "previous_secret_expires_at" | "secret"; RoundIncomplete: "at" | "can_resume" | "files" | "kind" | "number" | "pushed" | "reason" | "summary" | "wip_branch"; - Run: "answers" | "answers_url" | "applied_standards" | "branch" | "branches" | "cache_read_tokens" | "cache_write_tokens" | "checks" | "close_reason" | "closed_at" | "closed_by" | "closed_from" | "codegen_env_missing" | "continued_run_id" | "cost_usd" | "covered_by" | "created_at" | "current_pass" | "draft_hold" | "duration_s" | "error" | "files_modified" | "fix_location" | "github_wait" | "lesson" | "mcp_servers" | "merge_standing" | "outside_change_report" | "pass_history" | "policy_approval" | "policy_note" | "pr_number" | "pr_numbers" | "pr_review" | "pr_review_comments" | "pr_url" | "pr_urls" | "preview" | "progress_notes" | "prs" | "questions" | "questions_url" | "repo" | "round_incomplete" | "run_id" | "sign_in_prompts" | "status" | "stop_kind" | "ticket_id" | "ticket_source" | "title" | "tokens_in" | "tokens_out" | "tooling_failure" | "trigger" | "updated_at" | "waiting_line" | "waiting_on"; + Run: "answers" | "answers_url" | "applied_standards" | "branch" | "branches" | "cache_read_tokens" | "cache_write_tokens" | "checks" | "close_reason" | "closed_at" | "closed_by" | "closed_from" | "codegen_env_missing" | "continued_run_id" | "cost_usd" | "covered_by" | "created_at" | "current_pass" | "draft_hold" | "duration_s" | "error" | "exploration" | "files_modified" | "fix_location" | "github_wait" | "lesson" | "mcp_servers" | "merge_standing" | "outside_change_report" | "pass_history" | "policy_approval" | "policy_note" | "pr_number" | "pr_numbers" | "pr_review" | "pr_review_comments" | "pr_url" | "pr_urls" | "preview" | "progress_notes" | "prs" | "questions" | "questions_url" | "repo" | "round_incomplete" | "run_id" | "sign_in_prompts" | "status" | "stop_kind" | "ticket_id" | "ticket_source" | "title" | "tokens_in" | "tokens_out" | "tooling_failure" | "traceability" | "trigger" | "updated_at" | "waiting_line" | "waiting_on"; RunActionResult: "status"; RunAnswer: "answer" | "answered_at" | "author" | "question" | "question_id"; RunCheck: "completed_at" | "conclusion" | "name" | "required" | "started_at" | "state" | "url"; RunCheckCounts: "failed" | "passed" | "queued" | "running" | "skipped"; RunChecks: "counts" | "items" | "sha"; + RunCodeMapRefresh: "commit" | "missed" | "rebuilt" | "reused" | "why"; + RunCoderExploration: "calls_before_first_write" | "map_commit" | "tool_calls"; RunCoveredBy: "author" | "carried" | "note" | "number" | "open_items" | "outcome" | "own" | "reason" | "repo" | "superseded" | "title" | "url"; RunCoveredCarried: "branch" | "commits" | "files" | "head" | "rebuilt"; RunDraftHold: "kind" | "pr_number" | "reasons" | "since" | "summary"; RunDraftHoldReason: "todo" | "what"; + RunExploration: "code_map" | "coder"; RunMergeStanding: "code" | "link" | "needs_person" | "next" | "text"; RunNote: "message" | "timestamp"; RunPass: "pass" | "started_at"; @@ -86,6 +90,10 @@ export interface OpenApiFields { RunSummary: "cost_usd" | "created_at" | "current_pass" | "duration_s" | "pr_number" | "pr_url" | "repo" | "run_id" | "status" | "ticket_id" | "ticket_source" | "title" | "tokens_in" | "tokens_out" | "trigger"; RunSupersededPr: "closed" | "closed_by" | "number" | "repo" | "title" | "url"; RunToolingFailure: "command" | "error" | "tried"; + RunTrace: "head" | "rows"; + RunTraceCode: "path" | "symbols"; + RunTraceProof: "by" | "detail" | "state"; + RunTraceRow: "code" | "criterion" | "page" | "proof" | "source" | "tests"; RunTrigger: "by" | "kind" | "label" | "ref" | "ref_url"; RunWaitingOn: "action" | "detail" | "since" | "url"; RunsPage: "next" | "runs" | "scanned"; @@ -93,6 +101,8 @@ export interface OpenApiFields { SessionStep: "at" | "detail" | "text"; SnsEnvelope: "Message" | "MessageId" | "Signature" | "SignatureVersion" | "SigningCertURL" | "Subject" | "SubscribeURL" | "Timestamp" | "TopicArn" | "Type"; SourceRow: "deliveries" | "direction" | "failed" | "failed_series" | "ok" | "p50_ms" | "p95_ms" | "previous_deliveries" | "previous_success_rate" | "series" | "source" | "success_rate"; + StartEstimate: "cost_high" | "cost_low" | "per_run_high" | "per_run_low" | "runs_high" | "runs_low" | "sample" | "tasks"; + TaskCounts: "draft" | "dropped" | "failed" | "in_review" | "merged" | "needs_you" | "queued" | "working"; Totals: "deliveries" | "failed" | "handled" | "ignored" | "p50_ms" | "p95_ms" | "p99_ms" | "retried" | "retried_ok" | "retries" | "success_rate"; TriggerKind: never; UpdateEndpointBody: "description" | "enabled" | "events" | "url"; diff --git a/docs/content/docs/getting-started/plans.mdx b/docs/content/docs/getting-started/plans.mdx index 018e63da..336c5e6e 100644 --- a/docs/content/docs/getting-started/plans.mdx +++ b/docs/content/docs/getting-started/plans.mdx @@ -1,9 +1,9 @@ --- title: Plans -description: Describe a bigger change in your own words; CoderHelm reads your code and drafts a plan of tickets you can edit before anything runs. +description: Describe a bigger change in your own words; CoderHelm drafts a plan of tasks, and each task's state follows its runs and pull requests until it merges. --- -A **plan** turns a change too big for one ticket into an ordered list of tasks. Each task becomes a GitHub issue or a Jira ticket, and each one becomes a run. +A **plan** turns a change too big for one ticket into an ordered list of tasks. Each task you approve becomes a GitHub issue or a Jira ticket, and that ticket's runs and pull requests are the task's work. A plan is done when every task has merged or been dropped, never when its tickets are filed. ## Make a plan @@ -15,11 +15,64 @@ A **plan** turns a change too big for one ticket into an ordered list of tasks. You can also start from a **template**: save a plan you like as a template, then reuse it from **Templates**. -## Approve and run +## Approve and start -Open the plan. It has an overview, the tasks, the runs and pull requests made from it, a spec, and a list of what the chat looked at. +A draft plan shows what starting it takes before anything runs: the number of runs and a cost range, read from your team's recent runs. -- **Approve all and start** creates every ticket and starts the runs in order. -- Or approve tasks one by one. Approving the last one starts the plan. +- **Approve and start** approves every draft task and starts them, in order. A task that runs after another starts when that task's pull request merges. +- Or approve tasks one at a time from their rows. Each one starts right away, and the plan stays open for the rest: the drafts left keep their **Approve** and **Drop** buttons, and the plan lists them under **Needs you** until you approve or drop them. -Nothing is created in GitHub or Jira, and no code changes, until you approve. +Every way of starting work checks your team's run budget first. Nothing is created in GitHub or Jira, and no code changes, until you approve. + +## What the plan page shows + +In order: + +1. **The goal and one status line**: the plan's state, a count line such as "2 of 5 merged, 1 needs you, 1 in review", what its runs have cost, and the one thing to do next. +2. **Needs you**, only when something does. Each row is the exact ask with its button: answer the run's question, review or approve pull request #53, look at checks CoderHelm could not fix, retry or drop a task that failed (with its reason), approve the drafts that are left. A row goes away once it is handled. +3. **What done means**: the plan's success criteria, each with the tasks that cover it and what the work shows for it, read from the criteria trace of the task's run (proven, no test, fails, not run yet). Without a list of its own, a plan's criteria are its tasks' "Done when" lines. +4. **Tasks**: each with its state, its pull requests as chips, its attempts and what they cost. Finished tasks are faded. A plan with more than eight tasks is grouped by state, with what needs you first and merged work folded; the page remembers which groups and task you had open. +5. **Spec**: the plan's description and written spec, open while the plan is a draft and folded below the work once it runs. + +## Task states + +| State | What it means | +| --- | --- | +| Draft | Not approved yet. | +| Queued | Approved and waiting: on the task it runs after, on its ticket being filed, or on its run to start. | +| Working | Its run is working. | +| Needs you | Its run asks a person for something: an answer, a review, an approval, a merge, or checks it could not fix. | +| Failed | Its run failed with no pull request left open, was cancelled, or its pull request closed without merging. The reason is shown. | +| In review | A pull request is open and the next step is CoderHelm's or the checks', not yours. | +| Merged | A pull request of the task merged. | +| Dropped | You dropped the task, or closed its run on purpose. | + +Filing the ticket is a fact on the task, not a state. Every attempt counts: a task that took several runs lists each one, with its cost. + +A plan is **Drafting** until a task is approved, then **Running**. It **Needs you** when a task does, when a task failed, or when drafts are left once the rest finished. It is **Done** when every task merged or was dropped, and **Stalled** when work is open and nothing has moved for 3 days. + +## Pull request chips + +Each pull request shows its number, coloured by where it stands, with its size once GitHub reports it: + +- **Green**: checks pass and nothing waits on a review: ready to merge. +- **Yellow**: checks are running, or it waits on a review or an approval. +- **Red**: checks fail, or a review asked for changes. +- **Purple**: merged. +- **Grey**: closed without merging. + +## Changes after approval + +A task added, changed or dropped after the plan was approved is marked, with who made the change: a person, or CoderHelm. A pull request that changes files outside the paths its task names, or whose run moved an out-of-scope item into scope, is marked **Out of scope**. + +## Retry and Start now + +**Retry** on a failed task asks first and says what a run costs. When the task's ticket was filed, its run is retried; when the ticket could not be filed, it is filed again. **Start now** runs a waiting task before the task it waits on has merged, also after a confirmation with the cost. + +## Steering a task while it works + +The plan page has no message box yet. To steer a task while it works, comment on its pull request, or answer on its run page when it asks you something. CoderHelm picks the comment up from the pull request. + +## Plans made before this + +Plans written before task states followed the work are read again the first time the plans list or the plan opens: each task is linked to its ticket's runs and pull requests, and its state is worked out from them. Nothing else about the plan changes. diff --git a/docs/content/release-notes.md b/docs/content/release-notes.md index ef6daecd..d8052b2b 100644 --- a/docs/content/release-notes.md +++ b/docs/content/release-notes.md @@ -6,6 +6,12 @@ pull requests that shipped it. Leave out CI, pins and dependency bumps. The page groups releases by day: one heading per day, each release a subheading under it. --> +## November 21, 2026: plans tell the truth about the work + +- **A task's state follows its runs and pull requests.** Filing a task's ticket no longer marks it done, and a plan is done only when every task merged or was dropped. Each task is Draft, Queued, Working, Needs you, Failed (with its reason), In review, Merged or Dropped, and lists every attempt with its cost. Runs started from a plan task now name their plan and task, and plans made before this are linked to their runs and read again the first time they open. ([platform #800](https://github.com/CoderHelm/coderhelm-platform/pull/800), [dashboard #467](https://github.com/CoderHelm/coderhelm/pull/467)) +- **Approving one task never ends the plan.** The plan runs with its approved tasks and stays open: the drafts left keep their buttons and are listed under Needs you. Approve and start shows the expected runs and cost range first, Retry and Start now ask with the cost, and every way of starting work checks the run budget. ([platform #800](https://github.com/CoderHelm/coderhelm-platform/pull/800), [dashboard #467](https://github.com/CoderHelm/coderhelm/pull/467)) +- **The plan page in the order you need it.** The goal and a count line come first, then a Needs you strip with each exact ask and its button, the success criteria with their evidence, and the tasks with their pull requests as chips coloured by checks and review, attempts, cost and marks for changes after approval. The spec folds below once the plan runs. The plans list shows each plan's progress by state, what needs you and its cost, and Active counts the plans that are really running. ([dashboard #467](https://github.com/CoderHelm/coderhelm/pull/467)) + ## November 19, 2026: sign in with Microsoft and Okta - **Sign in with Microsoft.** Work, school and personal Microsoft accounts can sign in, on CoderHelm's cloud and on self-hosted installs that add their own Entra app registration. CoderHelm checks Microsoft's signature, the account's own tenant, the nonce and the expiry, and takes the email only when Microsoft says its domain is verified. The button shows only where it is set up. ([#793](https://github.com/CoderHelm/coderhelm-platform/pull/793), [dashboard #463](https://github.com/CoderHelm/coderhelm/pull/463)) diff --git a/src/content/site.ts b/src/content/site.ts index 96727c70..c594f245 100644 --- a/src/content/site.ts +++ b/src/content/site.ts @@ -303,7 +303,7 @@ const home: Page = { }, { title: "Plans you approve", - text: "Describe the work in the dashboard. CoderHelm streams a plan, and each task you approve becomes an issue and a run, in order.", + text: "Describe the work in the dashboard. CoderHelm streams a plan, each task you approve becomes an issue and a run, and the plan shows what needs you until every task merged.", href: "/pull-requests/#plans", mini: "plans", }, @@ -589,7 +589,7 @@ const pullRequests: Page = { blocks: [ { type: "p", - text: "In the dashboard, describe what you want to build. CoderHelm streams a plan as it reasons, searching your code and the MCP servers you connected for the details. Approve it and each task becomes a GitHub issue and a run, in order.", + text: "In the dashboard, describe what you want to build. CoderHelm streams a plan as it reasons, searching your code and the MCP servers you connected for the details. Approve it and each task becomes a GitHub issue and a run, in order. Each task's state follows its runs and pull requests, the plan lists what needs you, and it is done only when every task merged.", }, ], },