diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index cc080ceab5..b51683e405 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -248,6 +248,13 @@ details.carddetail dd { margin: 0; overflow-wrap: anywhere; } .qblock .qremaining { color: #e3b341; font-size: 12px; } .skel { border: 1px dashed #30363d; border-radius: 8px; padding: 14px 12px; margin: 8px 0; color: #8b949e; background: #0d1117; } .orderctl { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin: 8px 0; font-size: 12.5px; color: #8b949e; } +.bulkbar { border: 1px solid #30363d; border-radius: 8px; padding: 10px 12px; margin: 10px 0; background: #0d1117; display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } +.bulkbar select, .bulkbar input[type="text"] { background: #161b22; color: #e6edf3; border: 1px solid #30363d; border-radius: 6px; padding: 7px 9px; font: inherit; min-height: 44px; } +.bulkpickline { margin: 8px 0 -4px; font-size: 12.5px; color: #8b949e; } +.bulkpickline input { width: 18px; height: 18px; vertical-align: -3px; } +.bulkreview { flex-basis: 100%; border-top: 1px dashed #30363d; padding-top: 8px; } +.bulkreview ul { margin: 6px 0; padding-left: 20px; max-height: 240px; overflow: auto; } +.bulkresults { flex-basis: 100%; font-size: 13px; } .orderctl .aform { margin: 0; } .stripcard .restore-note { font-size: 12.5px; } .badge.stale { background: #d2992233; border-color: #d29922; color: #e3b341; } @@ -2547,6 +2554,310 @@ function needsOrderHtml(act: AttentionAct | undefined): string { return `
Needs-you list order: ${esc(labels[order])}${actboxHtml({ identities: act.identities }, form)}
`; } + +/** #1277: the per-card bulk-triage pick for one queue card. Renders + * only when the action surface is up (identities present); a card + * whose own controls are disabled (stale tier source) gets a disabled + * pick, so it cannot be submitted against an unconfirmed item. */ +function bulkPickHtml( + objectRef: string, + title: string, + act: AttentionAct | undefined, + disabledReason?: string, +): string { + if (!act?.identities) return ""; + return `
`; +} + +function bulkSnoozeOptions(): string { + const now = new Date(); + const tonight = new Date(now); + tonight.setHours(23, 59, 0, 0); + const tomorrow = new Date(now); + tomorrow.setDate(tomorrow.getDate() + 1); + tomorrow.setHours(9, 0, 0, 0); + const nextWeek = new Date(now); + nextWeek.setDate(nextWeek.getDate() + 7); + nextWeek.setHours(9, 0, 0, 0); + return ``; +} + +/** #1277: the bulk triage bar for the Needs-you queues — one verb + * applied to every picked card, with a review step that lists every + * selected item + the chosen action before anything is submitted. + * Submission goes to POST /api/actions/batch (BULK_SCRIPT below); + * each item lands as its own attributed action record. */ +function bulkBarHtml(act: AttentionAct | undefined): string { + if (!act?.identities) return ""; + return `
Bulk triage${authorSelectHtml(act.identities)}0 selected
`; +} + +/** + * The client side of bulk triage (#1277): delegated listeners in the + * COMMENT_SCRIPT/ACTION_SCRIPT pattern, so Datastar fragment swaps + * keep working. Review builds nothing server-side; confirm POSTs one + * action object per picked card to /api/actions/batch and renders + * the per-item results — succeeded picks clear, failed picks stay + * checked (their items remain in Needs-you) with the error named. + */ +const BULK_SCRIPT = ``; + export function renderAttention( view: AttentionView, coverage: SourceCoverage[], @@ -2562,7 +2873,7 @@ export function renderAttention( ${sections.header}${sections.queues}${sections.sessions}`, provenance, "/attention", - act?.identities ? ACTION_SCRIPT + COMMENT_SCRIPT : "", + act?.identities ? ACTION_SCRIPT + COMMENT_SCRIPT + BULK_SCRIPT : "", detail ? freshnessChips(detail, ["orchestration", "attention", "registry"]) : "", ); } @@ -2669,7 +2980,7 @@ export function attentionSections( const cs = partition(objectRef, e.title ?? e.sessionId, act?.actionsByObject?.get(objectRef)); if (cs.suppressed) continue; drewCardsList.push({ - html: sessionCard(e, children, 0, counts, sessionAct), + html: bulkPickHtml(objectRef, e.title ?? e.sessionId, act) + sessionCard(e, children, 0, counts, sessionAct), sinceMs: Date.parse(e.lastActivityAt ?? "") || 0, seenMs: Date.parse(e.lastActivityAt ?? "") || 0, rank: 5, @@ -2679,8 +2990,9 @@ export function attentionSections( const objectRef = tierItemObjectRef(item); const cs = partition(objectRef, item.title, act?.actionsByObject?.get(objectRef)); if (cs.suppressed) continue; + const drewAct = tierAct(item); drewCardsList.push({ - html: tierItemCard(item, "Why you", counts, tierAct(item)), + html: bulkPickHtml(objectRef, item.title, act, drewAct.disabledReason) + tierItemCard(item, "Why you", counts, drewAct), sinceMs: Date.parse(item.since) || 0, seenMs: Date.parse(item.lastSeenAt) || 0, rank: item.horizon ? (HORIZON_RANK[item.horizon] ?? 5) : 5, @@ -2702,13 +3014,14 @@ export function attentionSections( const objectRef = sessionObjectRef(e.sessionId); const cs = partition(objectRef, e.title ?? e.sessionId, act?.actionsByObject?.get(objectRef)); if (cs.suppressed) continue; - orchCardsList.push(sessionCard(e, children, 0, counts, sessionAct)); + orchCardsList.push(bulkPickHtml(objectRef, e.title ?? e.sessionId, act) + sessionCard(e, children, 0, counts, sessionAct)); } for (const item of view.orchestratorExtra) { const objectRef = tierItemObjectRef(item); const cs = partition(objectRef, item.title, act?.actionsByObject?.get(objectRef)); if (cs.suppressed) continue; - orchCardsList.push(tierItemCard(item, "Why the fleet", counts, tierAct(item))); + const orchAct = tierAct(item); + orchCardsList.push(bulkPickHtml(objectRef, item.title, act, orchAct.disabledReason) + tierItemCard(item, "Why the fleet", counts, orchAct)); } // Store-only suppressed refs: items the publisher no longer lists // (their dismissal was applied and they left the tiers) stay visible @@ -2753,7 +3066,7 @@ ${delegationDefault}`; const hiddenStrip = hiddenList.length ? `
Dismissed / done by you (${hiddenList.length}) — hidden from the queues; restore any of them to re-review or add a note${hiddenList.map((e) => stripCardHtml(e, act?.identities)).join("")}
` : ""; - const queues = `${needsOrderHtml(act)}

Needs User (${drewCount})${sectionStamp}

${drewCards} + const queues = `${bulkBarHtml(act)}${needsOrderHtml(act)}

Needs User (${drewCount})${sectionStamp}

${drewCards} ${snoozedStrip}${hiddenStrip}

Needs Orchestrator (${orchCount})${sectionStamp}

The orchestration job (#899) reviews this queue and pushes work back into motion; it escalates to the user queue only what truly needs the user.

${orchCards}`; const sessionCards = roots.length ? roots.map((e) => sessionCard(e, children, 0, counts, sessionAct)).join("") @@ -2786,7 +3099,7 @@ ${attentionFragment("sessions", skel("sessions"))}`; body, provenance, "/attention", - ACTION_SCRIPT + COMMENT_SCRIPT, + ACTION_SCRIPT + COMMENT_SCRIPT + BULK_SCRIPT, detail ? freshnessChips(detail, ["orchestration", "attention", "registry"]) : "", ); } diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index cd78a45807..e3f4260ff5 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -608,6 +608,70 @@ async function handler(req: Request): Promise { return json({ error: `invalid action: ${err instanceof Error ? err.message : err}` }, 400); } } + // #1277: bulk triage — one mediated batch, validated and appended + // item by item under the exact single-action rules above. Every + // accepted item becomes its OWN attributed audit entry (never one + // opaque batch record), so the batch is recoverable from the + // entries themselves; every rejected item is reported by ref with + // its error and appends nothing, so a partial batch never silently + // drops work — the failed items simply remain in Needs-you. + if (req.method === "POST" && path === "/api/actions/batch") { + try { + const body = (await readJsonBody(req)) as { actions?: unknown }; + if (!Array.isArray(body.actions) || body.actions.length === 0 || body.actions.length > 100) { + return json({ error: "actions must be an array of 1-100 action objects" }, 400); + } + const entries: unknown[] = body.actions; + // The published-item checks (#1291/#1293) need the section once, + // not once per item. + const section = entries.some( + (a) => typeof a === "object" && a !== null && (a as { kind?: unknown }).kind === "triage", + ) + ? await source.orchestration().catch(() => null) + : null; + const results: { + index: number; + objectRef: string | null; + ok: boolean; + action?: unknown; + deduped?: boolean; + error?: string; + }[] = []; + for (const [index, raw] of entries.entries()) { + const objectRef = + typeof raw === "object" && raw !== null && typeof (raw as { objectRef?: unknown }).objectRef === "string" + ? (raw as { objectRef: string }).objectRef + : null; + const parsed = validateNewAction(raw); + if (!parsed.ok) { + results.push({ index, objectRef, ok: false, error: parsed.error }); + continue; + } + if (parsed.value.kind === "triage" && section) { + const problem = checkActionAgainstItem(parsed.value, findTierItem(section, parsed.value.objectRef), Date.now()); + if (problem) { + results.push({ index, objectRef, ok: false, error: problem }); + continue; + } + } + try { + const { action, created } = await actionsStore.add(parsed.value); + results.push({ index, objectRef, ok: true, action, ...(created ? {} : { deduped: true }) }); + } catch (err) { + results.push({ + index, + objectRef, + ok: false, + error: `action persistence failed: ${err instanceof Error ? err.message : err}`, + }); + } + } + const recorded = results.filter((r) => r.ok).length; + return json({ results, recorded, failed: results.length - recorded }, 200); + } catch (err) { + return json({ error: `invalid batch: ${err instanceof Error ? err.message : err}` }, 400); + } + } if (req.method === "POST" && path === "/api/actions/result") { try { const body = (await readJsonBody(req)) as { id?: unknown; outcome?: unknown; byRun?: unknown; note?: unknown }; diff --git a/pm-stack/aggregator/test/actions.test.ts b/pm-stack/aggregator/test/actions.test.ts index a3776afbf3..2610330787 100644 --- a/pm-stack/aggregator/test/actions.test.ts +++ b/pm-stack/aggregator/test/actions.test.ts @@ -331,6 +331,26 @@ describe("attention action controls (#1152/#1156)", () => { expect(html).toContain("/api/actions"); // ACTION_SCRIPT is on the page }); + test("bulk triage (#1277): queue cards carry picks and the bulk bar posts to /api/actions/batch", async () => { + const src = fixtureSource(); + const view = buildAttention(await src.attention(), SECTION, NOW); + const html = renderAttention(view, await src.coverage(), src.provenance(), undefined, undefined, { + identities, + actionsByObject: new Map(), + }); + expect(html).toContain('id="bulkbar"'); + expect(html).toContain('class="bulkpick"'); + expect(html).toContain('data-object="orch:goal_plaid"'); + expect(html).toContain("Review batch"); + expect(html).toContain("/api/actions/batch"); // BULK_SCRIPT is on the page + // Without identities there is no action surface \u2014 and no bulk bar. + const anon = renderAttention(view, await src.coverage(), src.provenance(), undefined, undefined, { + actionsByObject: new Map(), + }); + expect(anon).not.toContain('id="bulkbar"'); + expect(anon).not.toContain('class="bulkpick"'); + }); + test("stale tier source: section-item controls disabled with reason; session items stay enabled", async () => { const src = fixtureSource(); // A stale section still serves its last-published items — exactly @@ -592,4 +612,62 @@ describe("actions HTTP round-trip (fixture consumer)", () => { expect(list.actions.length).toBeGreaterThanOrEqual(1); expect(list.pending).toEqual({ triage: 0, statusRequests: 0, session: 0, preference: 0 }); }); + + test("POST /api/actions/batch: mixed batch records valid items individually, reports failures by ref (#1277)", async () => { + const mk = (clientToken: string, over: Record = {}) => ({ + clientToken, + kind: "triage", + verb: "acknowledge", + objectRef: "orch:bulk-ok", + author: drew, + payload: {}, + ...over, + }); + const res = await post("/api/actions/batch", { + actions: [ + mk("ct-batch-ok-1"), + mk("ct-batch-ok-2", { objectRef: "orch:bulk-ok-2" }), + mk("ct-batch-bad-1", { objectRef: "orch:bulk-bad", verb: "snooze", payload: {} }), // snooze without until + mk("ct-batch-bad-2", { objectRef: "orch:bulk-bad-2", verb: "explode" }), + ], + }); + expect(res.status).toBe(200); + const body = (await res.json()) as { + results: { index: number; objectRef: string | null; ok: boolean; action?: DashAction; error?: string }[]; + recorded: number; + failed: number; + }; + expect(body.recorded).toBe(2); + expect(body.failed).toBe(2); + expect(body.results.map((r) => r.ok)).toEqual([true, true, false, false]); + expect(body.results[2].objectRef).toBe("orch:bulk-bad"); + expect(body.results[2].error).toContain("until"); + expect(body.results[3].error).toContain("verb"); + // Each accepted item is its OWN store entry (no opaque batch record). + const ids = body.results.filter((r) => r.ok).map((r) => r.action!.id); + expect(new Set(ids).size).toBe(2); + const stored = (await (await fetch(`http://127.0.0.1:${port}/api/actions.json?kind=triage`)).json()) as { + actions: DashAction[]; + }; + expect(stored.actions.filter((a) => a.objectRef === "orch:bulk-ok").length).toBe(1); + expect(stored.actions.filter((a) => a.objectRef === "orch:bulk-ok-2").length).toBe(1); + // Failed items appended nothing \u2014 they remain in Needs-you. + expect(stored.actions.some((a) => a.objectRef === "orch:bulk-bad")).toBe(false); + expect(stored.actions.some((a) => a.objectRef === "orch:bulk-bad-2")).toBe(false); + // A repost of the same clientToken dedupes per item, not per batch. + const repost = await post("/api/actions/batch", { actions: [mk("ct-batch-ok-1")] }); + const repostBody = (await repost.json()) as { results: { ok: boolean; deduped?: boolean }[]; recorded: number }; + expect(repostBody.recorded).toBe(1); + expect(repostBody.results[0].deduped).toBe(true); + const after = (await (await fetch(`http://127.0.0.1:${port}/api/actions.json?kind=triage`)).json()) as { + actions: DashAction[]; + }; + expect(after.actions.filter((a) => a.objectRef === "orch:bulk-ok").length).toBe(1); + }); + + test("POST /api/actions/batch rejects malformed envelopes with 400", async () => { + expect((await post("/api/actions/batch", {})).status).toBe(400); + expect((await post("/api/actions/batch", { actions: [] })).status).toBe(400); + expect((await post("/api/actions/batch", { actions: "nope" })).status).toBe(400); + }); });