Python
Request cards: staffing by role, work items, lead decision, team update, two-tone
Devika Verma80e948946836
diff --git a/surfaces/gui/src/components/ApprovalCard.tsx b/surfaces/gui/src/components/ApprovalCard.tsxindex 53ce1c71..f07b9885 100644--- a/surfaces/gui/src/components/ApprovalCard.tsx+++ b/surfaces/gui/src/components/ApprovalCard.tsx@@ -3,6 +3,7 @@ import { getI18n, useTranslation } from "react-i18next";import type { ApprovalDecision, Item } from "../types";import { humanizeApprovalTitle, type HumanLine } from "../humanize";import { Icon } from "./Icon";+import { leadDecisionFromArgs, WorkerDecisionCard } from "./WorkerDecisionCard";export function shortArgs(args: any): string {if (!args || typeof args !== "object") return "";@@ -420,9 +421,13 @@ export function ApprovalCard({runTask,compact = false,autoApprove = false,+ onAnswerWorkerCall,}: {item: ApprovalItem;onApprove: (decision: ApprovalDecision) => void;+ // decide_worker_call only: answer the WORKER'S waiting call directly (the human+ // overriding the lead). Without it the override only declines the lead's decision.+ onAnswerWorkerCall?: (callId: string, resolution: "allow" | "deny") => void;// Present when this approval was raised inside an automation run — unlocks the// task-persistent "Allow every time" (in-app only, §25).runTask?: { id: string; title: string } | null;@@ -433,6 +438,23 @@ export function ApprovalCard({}) {const { t } = useTranslation();const [peek, setPeek] = useState(false);+ // A lead's decision on a worker's call has its own card: the generic one asked the+ // human to "Allow" a denial of a command it never showed.+ if (item.name === "decide_worker_call" && !item.resolved) {+ const decision = leadDecisionFromArgs(item.args);+ return (+ <WorkerDecisionCard+ decision={decision}+ workerCall={item.workerCall}+ compact={compact}+ onFollow={() => onApprove("once")}+ onOverride={() => {+ onAnswerWorkerCall?.(decision.callId, decision.decision === "deny" ? "allow" : "deny");+ onApprove("deny");+ }}+ />+ );+ }const title = humanizeApprovalTitle(item.name, item.args);const scope = scopeNote(item.name, item.args, item.category, item.mcpDestination);const grants = item.name === "create_scheduled_task" ? permissionLines(item.args) : [];@@ -449,7 +471,7 @@ export function ApprovalCard({) : null;// Quiet, not a warning: the reviewer hesitating is context, not danger.const reviewerUnsure = item.reviewerUnsure ? (- <div className="text-[12px] text-muted mt-1" data-testid="approval-reviewer-unsure">+ <div className="text-meta text-muted mt-1" data-testid="approval-reviewer-unsure">{t("approval.reviewer_unsure", { note: item.reviewerUnsure })}</div>) : null;diff --git a/surfaces/gui/src/components/BoardWakeCard.test.tsx b/surfaces/gui/src/components/BoardWakeCard.test.tsxnew file mode 100644index 00000000..07b78fcf--- /dev/null+++ b/surfaces/gui/src/components/BoardWakeCard.test.tsx@@ -0,0 +1,63 @@+// The team update card (the digest that woke a lead). Owner 2026-09-17: "I had a hard+// time understanding what's there" — so: action first and in words, grouped by work item,+// note previews in place, and `waiting` rows are first-class. Payloads: gallery states.+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";++import type { MessageSource } from "../api";+import { statePayload } from "../gallery/states";+import { BoardWakeCard } from "./BoardWakeCard";++const source = (id: string) => statePayload("board-wake", id).source as MessageSource;++describe("BoardWakeCard", () => {+ afterEach(cleanup);++ it("summarises what needs action in words, the rest as a count", () => {+ render(<BoardWakeCard source={source("waiting-and-review")} />);+ expect(screen.getByTestId("boardwake-card").textContent).toContain("Team update");+ expect(screen.getByTestId("boardwake-summary").textContent).toBe(+ "checks is waiting on a decision · #4 is ready for review · 3 more",+ );+ expect(screen.queryByTestId("boardwake-body")).toBeNull(); // collapsed by default+ });++ it("says plain 'N updates' when nothing needs action", () => {+ render(<BoardWakeCard source={source("routine")} />);+ expect(screen.getByTestId("boardwake-summary").textContent).toBe("3 updates");+ });++ it("groups by work item, the pressing item and line first, ids stripped from actors", () => {+ render(<BoardWakeCard source={source("waiting-and-review")} />);+ fireEvent.click(screen.getByTestId("boardwake-toggle"));+ const groups = [...screen.getByTestId("boardwake-body").children].map((g) => g.getAttribute("data-testid"));+ expect(groups).toEqual(["boardwake-group-5", "boardwake-group-4", "boardwake-group-chat"]);+ const five = screen.getByTestId("boardwake-group-5");+ expect(five.textContent).toContain("Waiting on a decision");+ const lines = [...five.querySelectorAll(".boardwake-line-text")].map((l) => l.textContent);+ expect(lines).toEqual(["checks is waiting on a decision to run a command", "nia commented"]);+ // the engine's filler line is dropped from the waiting call's preview+ expect(five.textContent).not.toContain("requires approval");+ expect(five.textContent).toContain("cp src/invoices.ts");+ const four = screen.getByTestId("boardwake-group-4");+ expect(four.textContent).toContain("swe-lead commented");+ expect(four.textContent).not.toContain("3fbd018c");+ expect(four.textContent).toContain("nia handed it off for review");+ });++ it("previews notes in place and expands a long one with More", () => {+ render(<BoardWakeCard source={source("waiting-and-review")} />);+ fireEvent.click(screen.getByTestId("boardwake-toggle"));+ const four = screen.getByTestId("boardwake-group-4");+ const note = [...four.querySelectorAll(".boardwake-note")].find((n) => n.textContent?.includes("Done on branch"))!;+ expect(note.className).toContain("clamped");+ fireEvent.click(note.parentElement!.querySelector("button")!);+ expect(note.className).not.toContain("clamped");+ });++ it("still renders an update without structured rows (old server)", () => {+ render(<BoardWakeCard source={source("minimal")} />);+ fireEvent.click(screen.getByTestId("boardwake-toggle"));+ expect(screen.getByTestId("boardwake-body").textContent).toContain("Board wake");+ });+});diff --git a/surfaces/gui/src/components/BoardWakeCard.tsx b/surfaces/gui/src/components/BoardWakeCard.tsxindex 661e53ea..02c3f741 100644--- a/surfaces/gui/src/components/BoardWakeCard.tsx+++ b/surfaces/gui/src/components/BoardWakeCard.tsx@@ -1,91 +1,173 @@-// BoardWakeCard — a board wake in the lead's transcript, collapsed to ONE line by-// default (owner ruling 2026-08-16): most of the time the user just wants the-// feel that something is happening. Click to expand into per-event rows; long-// hand-off comments hide behind a per-row "show hand-off". NOT the connector-// card: a connector message is a foreign message, a board wake is a report —-// different shape, different affordances (they only share the visual family).+// A team update: the digest that woke a lead (the board's events since its last turn),+// shown in the transcript. Collapsed by default — it is a report, not a message to read+// (owner ask 2026-08-16).+//+// Redesigned 2026-09-17 (owner: "I had a hard time understanding what's there"):+// · named "Team update", not the internal "board wake";+// · the summary says what needs ACTION, in words ("checks is waiting on a decision ·+// #4 is ready for review · 3 more"), not a count per event type;+// · expanded, events are grouped by work item with a status label, each line a plain+// sentence with a two-line preview of its note (no click per row);+// · `waiting` rows — a worker waiting on the lead's decision — are first-class (they+// used to render as a bare title);+// · neutral border; actor ids lose their ":session" suffix.import { useState } from "react";import type { TFunction } from "i18next";import { useTranslation } from "react-i18next";import type { BoardWakeRow, MessageSource } from "../api";import { Icon } from "./Icon";-// Summary buckets → plural-aware catalog keys ("1 review", "2 reviews", …).-const WAKE_COUNT_KEYS: Record<string, string> = {- review: "board.wake_review",- blocked: "board.wake_blocked",- canceled: "board.wake_canceled",- move: "board.wake_move",- filing: "board.wake_filing",- claim: "board.wake_claim",- assignment: "board.wake_assignment",- comment: "board.wake_comment",- chat: "board.wake_chat_message",-};+// A note past this length (or with a line break) clamps to two lines with More/Less.+const NOTE_CLAMP_CHARS = 170;-function summarize(t: TFunction, rows: BoardWakeRow[]): { text: string; attention: boolean } {- const counts: Record<string, number> = {};- const bump = (key: string) => (counts[key] = (counts[key] || 0) + 1);- for (const row of rows) {- if (row.kind === "moved" && row.to === "review") bump("review");- else if (row.kind === "moved" && row.to === "blocked") bump("blocked");- else if (row.kind === "moved" && row.to === "canceled") bump("canceled");- else if (row.kind === "moved") bump("move");- else if (row.kind === "filed") bump("filing");- else if (row.kind === "claimed") bump("claim");- else if (row.kind === "assigned") bump("assignment");- else if (row.kind === "comment") bump("comment");- else if (row.kind === "chat") bump("chat");- }- const parts = Object.entries(counts).map(([bucket, n]) =>- t(WAKE_COUNT_KEYS[bucket], { count: n })- );- // reviews/blocked demand a decision — those tint the collapsed line amber- const attention = (counts.review || 0) + (counts.blocked || 0) > 0;- return { text: parts.join(", ") || t("board.wake_update"), attention };+const actorName = (actor: string | undefined, t: TFunction) =>+ (actor || t("teamupdate.someone")).split(":")[0];++// "<who> is waiting on a decision to <do what>" — one whole sentence per kind of call.+function toolPhrase(who: string, tool: string | undefined, t: TFunction): string {+ if (tool === "run_shell") return t("teamupdate.waiting_run_command", { who });+ if (tool && /^(write_file|replace_in_file|apply_patch|apply_unified_diff)$/.test(tool))+ return t("teamupdate.waiting_change_file", { who });+ return tool ? t("teamupdate.waiting_use_tool", { who, tool }) : t("teamupdate.waiting_act", { who });}-function rowText(t: TFunction, row: BoardWakeRow): string {- const item = row.item != null ? `#${row.item}` : "";- const title = row.title ? ` ${row.title}` : "";- const ref = `${item}${title}`;+// What a row says, as a sentence about its item.+function rowSentence(row: BoardWakeRow, t: TFunction): string {+ const who = actorName(row.actor, t);switch (row.kind) {case "moved":- return t("board.wake_moved", { ref, to: row.to, actor: row.actor });+ if (row.to === "review") return t("teamupdate.moved_review", { who });+ if (row.to === "blocked") return t("teamupdate.moved_blocked", { who });+ if (row.to === "done") return t("teamupdate.moved_done", { who });+ if (row.to === "in_progress") return t("teamupdate.moved_in_progress", { who });+ return t("teamupdate.moved_to", { who, state: String(row.to || "").replace(/_/g, " ") });case "filed":- return t("board.wake_filed", { ref, actor: row.actor });+ return t("teamupdate.filed", { who });case "claimed":- return t("board.wake_claimed", { ref, actor: row.actor });+ return t("teamupdate.claimed", { who });case "assigned":- return t("board.wake_assigned", { ref });+ return t("teamupdate.assigned");case "comment":- return t("board.wake_commented", { ref, actor: row.actor });+ return t("teamupdate.commented", { who });+ case "waiting":+ return toolPhrase(who, row.tool, t);case "chat":- return t("board.wake_chat", { actor: row.actor });+ return who;default:- return ref;+ return `${who}: ${row.kind}`;}}-function stateDot(row: BoardWakeRow): string {- if (row.kind === "moved" && row.to === "review") return "board-dot review";- if (row.kind === "moved" && row.to === "blocked") return "board-dot blocked";- if (row.kind === "moved" && row.to === "done") return "board-dot done";- if (row.kind === "claimed" || row.kind === "assigned") return "board-dot work";- return "board-dot idle";+// The engine's boilerplate first line says nothing; the rest is the call itself.+const cleanNote = (row: BoardWakeRow) =>+ (row.note || "").replace(/^requires approval\n?/, "").trim();++// Status of an item as far as this update tells: the most pressing thing wins.+// `label` is an i18n KEY, resolved where it renders ("" = no label).+type Status = { rank: number; label: string; dot: string };+const STATUS: Record<string, Status> = {+ waiting: { rank: 0, label: "teamupdate.status_waiting", dot: "board-dot blocked" },+ blocked: { rank: 1, label: "board.state_blocked", dot: "board-dot blocked" },+ review: { rank: 2, label: "teamupdate.status_review", dot: "board-dot review" },+ in_progress: { rank: 3, label: "board.state_in_progress", dot: "board-dot work" },+ claimed: { rank: 3, label: "teamupdate.status_claimed", dot: "board-dot work" },+ assigned: { rank: 3, label: "teamupdate.status_assigned", dot: "board-dot work" },+ done: { rank: 4, label: "board.state_done", dot: "board-dot done" },+ filed: { rank: 5, label: "teamupdate.status_new", dot: "board-dot idle" },+ other: { rank: 6, label: "", dot: "board-dot idle" },+};++function statusOf(row: BoardWakeRow): Status {+ if (row.kind === "waiting") return STATUS.waiting;+ if (row.kind === "moved") return STATUS[String(row.to)] ?? STATUS.other;+ return STATUS[row.kind] ?? STATUS.other;+}++interface Group {+ key: string;+ item?: number | null;+ title: string;+ status: Status;+ rows: BoardWakeRow[];+}++function groupRows(rows: BoardWakeRow[]): { items: Group[]; chat: BoardWakeRow[] } {+ const items: Group[] = [];+ const chat: BoardWakeRow[] = [];+ for (const row of rows) {+ if (row.kind === "chat") {+ chat.push(row);+ continue;+ }+ const key = row.item != null ? `#${row.item}` : `?${row.title || ""}`;+ let g = items.find((x) => x.key === key);+ if (!g) {+ g = { key, item: row.item, title: row.title || "", status: STATUS.other, rows: [] };+ items.push(g);+ }+ g.rows.push(row);+ if (!g.title && row.title) g.title = row.title;+ const s = statusOf(row);+ if (s.rank < g.status.rank) g.status = s;+ }+ // Inside an item too: the line that needs action leads, the rest keep their order.+ for (const g of items) {+ const at = new Map(g.rows.map((r, i) => [r, i]));+ g.rows.sort((a, b) => Math.min(statusOf(a).rank, 3) - Math.min(statusOf(b).rank, 3) || at.get(a)! - at.get(b)!);+ }+ // What needs action first; otherwise the order things happened in.+ const order = new Map(items.map((g, i) => [g, i]));+ items.sort((a, b) => a.status.rank - b.status.rank || order.get(a)! - order.get(b)!);+ return { items, chat };+}++// The collapsed line: what needs action, in words; everything else as a count.+function summarize(rows: BoardWakeRow[], t: TFunction): { phrases: string[]; attention: boolean } {+ const waiting = rows.filter((r) => r.kind === "waiting");+ const blocked = rows.filter((r) => r.kind === "moved" && r.to === "blocked");+ const review = rows.filter((r) => r.kind === "moved" && r.to === "review");+ const phrases: string[] = [];+ if (waiting.length === 1) phrases.push(t("teamupdate.sum_waiting_who", { who: actorName(waiting[0].actor, t) }));+ else if (waiting.length > 1) phrases.push(t("teamupdate.sum_waiting_workers", { n: waiting.length }));+ const items = (rs: BoardWakeRow[]) => [...new Set(rs.map((r) => r.item).filter((i) => i != null))];+ const b = items(blocked);+ if (b.length === 1) phrases.push(t("teamupdate.sum_blocked_item", { item: b[0] }));+ else if (b.length > 1) phrases.push(t("teamupdate.sum_blocked_items", { n: b.length }));+ const v = items(review);+ if (v.length === 1) phrases.push(t("teamupdate.sum_review_item", { item: v[0] }));+ else if (v.length > 1) phrases.push(t("teamupdate.sum_review_items", { n: v.length }));+ const attention = phrases.length > 0;+ const rest = rows.length - waiting.length - blocked.length - review.length;+ if (rest > 0)+ phrases.push(attention ? t("teamupdate.sum_more", { n: rest }) : t("teamupdate.sum_updates", { count: rest }));+ return { phrases: phrases.length ? phrases : [t("teamupdate.sum_fallback")], attention };+}++function Note({ text }: { text: string }) {+ const { t } = useTranslation();+ const [all, setAll] = useState(false);+ if (!text) return null;+ const long = text.length > NOTE_CLAMP_CHARS || text.includes("\n");+ return (+ <span className="boardwake-note-wrap">+ <span className={"boardwake-note" + (long && !all ? " clamped" : "")}>{text}</span>+ {long && (+ <button className="boardwake-note-toggle" onClick={() => setAll((v) => !v)}>+ {all ? t("teamupdate.less") : t("teamupdate.more")}+ </button>+ )}+ </span>+ );}export function BoardWakeCard({ source }: { source: MessageSource }) {const { t } = useTranslation();const [open, setOpen] = useState(false);- const [openNotes, setOpenNotes] = useState<Record<number, boolean>>({});const rows = source.board?.rows || [];- const { text, attention } = summarize(t, rows);+ const { phrases, attention } = summarize(rows, t);+ const { items, chat } = groupRows(rows);return (- <div- className={"boardwake" + (attention ? " attention" : "")}- data-testid="boardwake-card"- >+ <div className="boardwake" data-testid="boardwake-card"><buttonclassName="boardwake-head"data-testid="boardwake-toggle"@@ -93,8 +175,11 @@ export function BoardWakeCard({ source }: { source: MessageSource }) {aria-expanded={open}><Icon name="table" size={14} />- <span className="boardwake-title">{t("board.wake_title")}</span>- <span className="boardwake-summary">{text}</span>+ <span className="boardwake-title">{t("teamupdate.title")}</span>+ <span className="boardwake-summary" data-testid="boardwake-summary">+ {attention && <span className="board-dot review boardwake-attn" />}+ {phrases.join(" · ")}+ </span><span className="spacer" /><span className={"boardwake-chevron" + (open ? " open" : "")}><Icon name="chevronDown" size={13} />@@ -102,30 +187,41 @@ export function BoardWakeCard({ source }: { source: MessageSource }) {</button>{open && (<div className="boardwake-body" data-testid="boardwake-body">- {rows.map((row, i) => (- <div className="boardwake-row" key={i}>- <span className={stateDot(row)} />- <span className="boardwake-row-main">- <span className="boardwake-row-text">{rowText(t, row)}</span>- {row.note &&- (openNotes[i] ? (- <span className="boardwake-note">{row.note}</span>- ) : (- <button- className="boardwake-note-toggle"- onClick={() => setOpenNotes((s) => ({ ...s, [i]: true }))}- >- {row.kind === "chat" || row.kind === "comment"- ? t("board.wake_show_message")- : t("board.wake_show_handoff")}- </button>- ))}- </span>+ {items.map((g) => (+ <div className="boardwake-group" key={g.key} data-testid={`boardwake-group-${g.item ?? "x"}`}>+ <div className="boardwake-group-head">+ <span className={g.status.dot} />+ <span className="boardwake-group-title">+ {g.item != null && <b>#{g.item} </b>}+ {g.title}+ </span>+ {g.status.label && <span className="boardwake-status">{t(g.status.label)}</span>}+ </div>+ {g.rows.map((row, i) => (+ <div className="boardwake-line" key={i}>+ <span className="boardwake-line-text">{rowSentence(row, t)}</span>+ <Note text={cleanNote(row)} />+ </div>+ ))}</div>))}- {rows.length === 0 && (- <div className="boardwake-note">{source.text}</div>+ {chat.length > 0 && (+ <div className="boardwake-group" data-testid="boardwake-group-chat">+ <div className="boardwake-group-head">+ <span className="board-dot idle" />+ <span className="boardwake-group-title">+ <b>{t("teamupdate.team_chat")}</b>+ </span>+ </div>+ {chat.map((row, i) => (+ <div className="boardwake-line" key={i}>+ <span className="boardwake-line-text">{rowSentence(row, t)}</span>+ <Note text={cleanNote(row)} />+ </div>+ ))}+ </div>)}+ {rows.length === 0 && <div className="boardwake-note">{source.text}</div>}</div>)}</div>diff --git a/surfaces/gui/src/components/ConnectorMessageCard.tsx b/surfaces/gui/src/components/ConnectorMessageCard.tsxindex 2d2d961d..46d2af9b 100644--- a/surfaces/gui/src/components/ConnectorMessageCard.tsx+++ b/surfaces/gui/src/components/ConnectorMessageCard.tsx@@ -79,22 +79,22 @@ export function ConnectorMessageCard({><ConnectorBadge connector={{ logo: source.connector, brand_color: color }} size={20} title={entry.label} />{showIds ? (- <span className="font-mono text-[12px] text-faint">{ids}</span>+ <span className="font-mono text-meta text-faint">{ids}</span>) : (<>- <span className="text-[13px] font-semibold" style={{ color: "var(--brand)" }}>+ <span className="text-ui font-semibold" style={{ color: "var(--brand)" }}>{source.channel_name}</span><span className="text-faint">·</span>- <span className="text-[13px] font-medium">{source.sender_name}</span>- <span className="text-[11px] text-faint ml-0.5">{t("inbox.connector_via", { label: entry.label })}</span>+ <span className="text-ui font-medium">{source.sender_name}</span>+ <span className="text-label text-faint ml-0.5">{t("inbox.connector_via", { label: entry.label })}</span></>)}- <time className="ml-auto text-[11px] text-faint whitespace-nowrap" title={clockTime(source.ts)}>+ <time className="ml-auto text-label text-faint whitespace-nowrap" title={clockTime(source.ts)}>{relativeTime(source.ts, t)}</time></header>- <div className="px-3.5 py-2.5 text-[14px] leading-relaxed whitespace-pre-wrap">{source.text}</div>+ <div className="px-3.5 py-2.5 text-body leading-relaxed whitespace-pre-wrap">{source.text}</div></article>);}diff --git a/surfaces/gui/src/components/ConnectorRequestCard.tsx b/surfaces/gui/src/components/ConnectorRequestCard.tsxnew file mode 100644index 00000000..b5118f5e--- /dev/null+++ b/surfaces/gui/src/components/ConnectorRequestCard.tsx@@ -0,0 +1,95 @@+import { Trans, useTranslation } from "react-i18next";+import type { Item } from "../types";+import { Icon } from "./Icon";++type ConnReqItem = Extract<Item, { kind: "connreq" }>;++const LABELS: Record<string, string> = {+ github: "GitHub",+ slack: "Slack",+ telegram: "Telegram",+ linear: "Linear",+ jira: "Jira",+ gmail: "Gmail",+ notion: "Notion",+ hubspot: "HubSpot",+};++export function connectorLabel(id: string): string {+ return LABELS[id] || id.charAt(0).toUpperCase() + id.slice(1);+}++// Connector access is a human decision (spec §11.6). Two asks share this card:+// `request_connector` — the coworker would like a service connected ("Connect" opens the+// Connectors page; "I've connected it" resolves once the user has); `grant_connector` —+// a lead asks to give one of its workers a connector it does not have. Declining is a+// normal outcome: the coworker carries on and says what it could not do.+export function ConnectorRequestCard({+ item,+ onRespond,+ onOpenConnectors,+}: {+ item: ConnReqItem;+ onRespond: (approved: boolean) => void;+ onOpenConnectors?: () => void;+}) {+ const { t } = useTranslation();+ const label = connectorLabel(item.connector);+ const grant = item.request === "grant";+ return (+ <div className="dirreq-card" data-testid="connreq-card">+ <div className="dirreq-head">+ <Icon name="plug" size={16} className="ico" />+ <span>+ {grant ? (+ <Trans+ i18nKey="connreq.head_grant"+ values={{ worker: item.worker, label }}+ components={{ b: <b /> }}+ />+ ) : (+ <Trans i18nKey="connreq.head_connect" values={{ label }} components={{ b: <b /> }} />+ )}+ </span>+ </div>+ {item.reason && (+ <div className="dirreq-reason">+ <Trans+ i18nKey="toolreq.reason_line"+ values={{ reason: item.reason }}+ components={{ label: <span className="toolreq-label" /> }}+ />+ </div>+ )}+ <div className="toolreq-facts">+ <div className="toolreq-explain">+ {grant+ ? t("connreq.explain_grant", { worker: item.worker, label })+ : t("connreq.explain_connect")}+ </div>+ </div>+ <div className="dirreq-actions">+ <span className="spacer" />+ <button className="btn" data-testid="connreq-decline" onClick={() => onRespond(false)}>+ {t("approval.btn.not_now")}+ </button>+ {grant ? (+ <button className="btn primary" data-testid="connreq-grant" onClick={() => onRespond(true)}>+ {t("connreq.grant", { label })}+ </button>+ ) : (+ <>+ {onOpenConnectors && (+ <button className="btn" data-testid="connreq-open" onClick={onOpenConnectors}>+ {t("transcript.mcp_open_connectors")}+ </button>+ )}+ <button className="btn primary" data-testid="connreq-connected" onClick={() => onRespond(true)}>+ {t("connreq.connected")}+ </button>+ </>+ )}+ </div>+ </div>+ );+}diff --git a/surfaces/gui/src/components/InboxItemCard.gates.test.tsx b/surfaces/gui/src/components/InboxItemCard.gates.test.tsxnew file mode 100644index 00000000..57802ccb--- /dev/null+++ b/surfaces/gui/src/components/InboxItemCard.gates.test.tsx@@ -0,0 +1,255 @@+// Team and work-item gates parked in the Inbox (a lead on a box, or an unattended lead)+// render the SAME cards as the inline gates, and resolve with the full decision — the+// human's connector ticks and the chat flag — not a bare {approved, mode}+// (owner-hit 2026-09-16: the first SpaceSol team got no connectors and no chat).+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++import type { InboxItem } from "../api";+import { modeLabel } from "./Composer";+import { InboxItemCard } from "./InboxItemCard";++function planItem(data: Record<string, unknown>, title: string): InboxItem {+ return {+ id: "gate-1",+ session_id: "lead-sid",+ kind: "plan",+ title,+ body: "- swe-worker\n- test-worker",+ state: "pending",+ resolution: null,+ inbox: "default",+ created_at: "2026-09-16T00:00:00Z",+ resolved_at: null,+ visibility: "inbox",+ data,+ } as InboxItem;+}++describe("InboxItemCard — gates parked in the Inbox", () => {+ afterEach(cleanup);++ it("renders the staffing card for a team gate and resolves with ticks and the chat flag", () => {+ const onResolve = vi.fn();+ render(+ <InboxItemCard+ item={planItem(+ {+ gate: "team",+ members: [+ {+ persona: "swe-worker",+ name: "nia",+ reason: "builds it",+ connectors: ["github"],+ connector_reasons: { github: "pushes the branch" },+ },+ { persona: "test-worker", name: "checks", reason: "verifies it" },+ ],+ enable_chat: false,+ offer: { "swe-worker": ["github"], "test-worker": [] },+ },+ "Create this team?",+ )}+ onResolve={onResolve}+ />,+ );+ expect(screen.getByTestId("teamreq-card")).toBeTruthy();+ // The lead's suggestion arrives ticked, with its reason — no click needed.+ const github = screen.getByTestId("teamreq-connector-0-github") as HTMLInputElement;+ expect(github.checked).toBe(true);+ expect(screen.getByText("pushes the branch")).toBeTruthy();+ // Nothing else is connected: no expander, and the empty default set says so.+ expect(screen.queryByTestId("teamreq-add-0")).toBeNull();+ expect(screen.getByTestId("teamreq-row-1").textContent).toContain("none available");+ // The body repeats the card (it exists for Slack) — not printed above it.+ expect(screen.queryByText(/- swe-worker/)).toBeNull();+ fireEvent.click(screen.getByTestId("teamreq-chat-toggle"));+ fireEvent.click(screen.getByTestId("teamreq-approve"));+ expect(onResolve).toHaveBeenCalledTimes(1);+ const [id, resolution] = onResolve.mock.calls[0];+ expect(id).toBe("gate-1");+ const parsed = JSON.parse(resolution);+ expect(parsed.approved).toBe(true);+ expect(parsed.enable_chat).toBe(true);+ expect(parsed.members).toEqual([+ { persona: "swe-worker", name: "nia", connectors: ["github"] },+ { persona: "test-worker", name: "checks", connectors: [] },+ ]);+ });++ it("extends a worker beyond its default set: the lead's quoted ask and a human addition", () => {+ const onResolve = vi.fn();+ render(+ <InboxItemCard+ item={planItem(+ {+ gate: "team",+ members: [+ {+ persona: "swe-worker",+ name: "nia",+ reason: "builds it",+ // slack is connected nowhere on this machine — ignored outright+ connectors: ["jira", "slack"],+ connector_reasons: { jira: 'you asked: "Track the work in Jira"' },+ },+ ],+ offer: { "swe-worker": ["github"] },+ other_connected: ["jira", "linear"],+ },+ "Create this team?",+ )}+ onResolve={onResolve}+ />,+ );+ const beyond = screen.getByTestId("teamreq-beyond-0");+ expect(beyond.textContent).toContain("Beyond this worker's usual set");+ expect(beyond.textContent).toContain('you asked: "Track the work in Jira"');+ expect((screen.getByTestId("teamreq-connector-0-jira") as HTMLInputElement).checked).toBe(true);+ // No suggestion in the default set → unticked; an unconnected suggestion is not shown.+ expect((screen.getByTestId("teamreq-connector-0-github") as HTMLInputElement).checked).toBe(false);+ expect(screen.queryByTestId("teamreq-connector-0-slack")).toBeNull();+ // The expander lists what is left, unticked; ticking moves it into the group, ticked.+ expect(screen.queryByTestId("teamreq-connector-0-linear")).toBeNull();+ fireEvent.click(screen.getByTestId("teamreq-add-0"));+ const linear = screen.getByTestId("teamreq-connector-0-linear") as HTMLInputElement;+ expect(linear.checked).toBe(false);+ fireEvent.click(linear);+ expect(beyond.contains(screen.getByTestId("teamreq-connector-0-linear"))).toBe(true);+ expect((screen.getByTestId("teamreq-connector-0-linear") as HTMLInputElement).checked).toBe(true);+ // Nothing left to add → the expander goes away.+ expect(screen.queryByTestId("teamreq-add-0")).toBeNull();+ fireEvent.click(screen.getByTestId("teamreq-approve"));+ const parsed = JSON.parse(onResolve.mock.calls[0][1]);+ expect(parsed.members).toHaveLength(1);+ expect([...parsed.members[0].connectors].sort()).toEqual(["jira", "linear"]);+ });++ it("forwards each worker's chosen model in the resolution", () => {+ const onResolve = vi.fn();+ render(+ <InboxItemCard+ item={planItem(+ {+ gate: "team",+ members: [+ { persona: "swe-worker", name: "nia", resolved_model: "anthropic:claude-opus-4-8" },+ {+ persona: "test-worker",+ name: "checks",+ resolved_model: "anthropic:claude-sonnet-4-8",+ model_warning: "None of test-worker's recommended models can run here.",+ },+ ],+ offer: {},+ model_options: { "swe-worker": ["anthropic:claude-opus-4-8"], "test-worker": [] },+ runnable_models: [+ { id: "anthropic:claude-opus-4-8", label: "Claude Opus 4.8" },+ { id: "anthropic:claude-sonnet-4-8", label: "Claude Sonnet 4.8" },+ { id: "ollama:qwen3", label: "Qwen 3 (local)" },+ ],+ lead_model: "anthropic:claude-sonnet-4-8",+ },+ "Create this team?",+ )}+ onResolve={onResolve}+ />,+ );+ expect(screen.getByTestId("teamreq-model-warn-1")).toBeTruthy();+ fireEvent.change(screen.getByTestId("teamreq-model-1"), { target: { value: "ollama:qwen3" } });+ fireEvent.click(screen.getByTestId("teamreq-approve"));+ const parsed = JSON.parse(onResolve.mock.calls[0][1]);+ expect(parsed.members).toEqual([+ { persona: "swe-worker", name: "nia", connectors: [], model: "anthropic:claude-opus-4-8" },+ { persona: "test-worker", name: "checks", connectors: [], model: "ollama:qwen3" },+ ]);+ });++ it("does not print the plain body above a team or items gate card", () => {+ render(+ <InboxItemCard+ item={planItem(+ { gate: "team", members: [{ persona: "swe-worker", name: "nia" }], offer: {} },+ "Create this team?",+ )}+ onResolve={vi.fn()}+ />,+ );+ expect(screen.getByTestId("teamreq-card")).toBeTruthy();+ expect(screen.queryByText(/- swe-worker/)).toBeNull();+ expect(screen.queryByText(/- test-worker/)).toBeNull();+ cleanup();+ render(+ <InboxItemCard+ item={planItem({ gate: "items", items: [{ title: "Cap it", criteria: "capped" }] }, "Approve?")}+ onResolve={vi.fn()}+ />,+ );+ expect(screen.queryByText(/- swe-worker/)).toBeNull();+ });++ it("states the lead's real mode only when the gate carries it", () => {+ const data = { gate: "team", members: [{ persona: "swe-worker", name: "nia" }], offer: {} };+ render(<InboxItemCard item={planItem(data, "Create this team?")} onResolve={vi.fn()} />);+ expect(screen.queryByText(/Approvals follow the lead/)).toBeNull();+ expect(screen.queryByTestId("teamreq-approvals")).toBeNull();+ cleanup();+ render(+ <InboxItemCard+ item={planItem({ ...data, lead_mode: "auto-approve" }, "Create this team?")}+ onResolve={vi.fn()}+ />,+ );+ const line = screen.getByTestId("teamreq-approvals");+ expect(line.textContent).toContain("Approvals follow the lead");+ expect(line.textContent).toContain(modeLabel("auto-approve"));+ });++ it("renders the work-items card for an items gate and resolves with approved", () => {+ const onResolve = vi.fn();+ render(+ <InboxItemCard+ item={planItem(+ { gate: "items", items: [{ title: "Cap the backoff", criteria: "no wait exceeds maxDelayMs" }] },+ "Approve the proposed work items?",+ )}+ onResolve={onResolve}+ />,+ );+ expect(screen.getByTestId("itemsreq-card")).toBeTruthy();+ fireEvent.click(screen.getByTestId("itemsreq-approve"));+ expect(JSON.parse(onResolve.mock.calls[0][1])).toEqual({ approved: true, feedback: "" });+ });++ it("keeps the plain Approve/Reject for a plan gate without a payload", () => {+ const onResolve = vi.fn();+ render(<InboxItemCard item={planItem({}, "Approve the plan?")} onResolve={onResolve} />);+ expect(screen.queryByTestId("teamreq-card")).toBeNull();+ // A plain plan gate has no card of its own — its body still shows.+ expect(screen.getByText(/- swe-worker/)).toBeTruthy();+ fireEvent.click(screen.getByText("Approve"));+ expect(JSON.parse(onResolve.mock.calls[0][1])).toEqual({ approved: true, mode: "interactive" });+ });++ it("offers Install on a parked tool request and resolves with approved", () => {+ const onResolve = vi.fn();+ const item = {+ ...planItem({ tool: "gitleaks", installable: true, version: "8.30.1", summary: "scans for secrets", source: "github.com/gitleaks" }, "Install gitleaks?"),+ kind: "tool",+ body: "scan the git history for committed secrets",+ } as InboxItem;+ render(<InboxItemCard item={item} onResolve={onResolve} />);+ // It used to fall through to a lone "Dismiss", which the server reads as a decline.+ expect(screen.queryByText("Dismiss")).toBeNull();+ expect(screen.getByText(/scan the git history/)).toBeTruthy();+ fireEvent.click(screen.getByTestId("toolreq-install"));+ expect(JSON.parse(onResolve.mock.calls[0][1])).toEqual({ approved: true });+ cleanup();+ // No pinned build → Install stays disabled; declining is still a plain answer.+ render(<InboxItemCard item={{ ...item, data: { tool: "somescanner" } } as InboxItem} onResolve={onResolve} />);+ expect((screen.getByTestId("toolreq-install") as HTMLButtonElement).disabled).toBe(true);+ fireEvent.click(screen.getByTestId("toolreq-skip"));+ expect(JSON.parse(onResolve.mock.calls[1][1])).toEqual({ approved: false });+ });+});diff --git a/surfaces/gui/src/components/InboxItemCard.tsx b/surfaces/gui/src/components/InboxItemCard.tsxindex a173697f..3e9146a8 100644--- a/surfaces/gui/src/components/InboxItemCard.tsx+++ b/surfaces/gui/src/components/InboxItemCard.tsx@@ -1,6 +1,17 @@import { useState, type ReactNode } from "react";import { useTranslation } from "react-i18next";-import type { InboxItem } from "../api";+import { routeInboxItemLike, type InboxItem, type TeamMemberDecision } from "../api";+import {+ itemsGateResolution,+ teamGateResolution,+ teamItemFromPayload,+ toolItemFromPayload,+ workItemsItemFromPayload,+} from "../cardPayloads";+import { TeamRequestCard } from "./TeamRequestCard";+import { ToolRequestCard } from "./ToolRequestCard";+import { leadDecisionFromArgs, WorkerDecisionCard } from "./WorkerDecisionCard";+import { WorkItemsCard } from "./WorkItemsCard";import type { Item, QuestionOption } from "../types";import { humanizeApprovalTitle } from "../humanize";import {@@ -19,21 +30,21 @@ import {// options and single questions render exactly as before.// Shared styles (mock parity — same language as SourcesDrawer/PersonaView).-const SEC = "text-[11px] uppercase tracking-[0.05em] text-faint font-semibold";+const SEC = "text-label text-faint font-medium";const BTN_PRIMARY =- "px-3 py-1.5 rounded-lg bg-accent text-white text-[13px] font-medium hover:brightness-105 disabled:opacity-40 disabled:hover:brightness-100";+ "px-3 py-1.5 rounded-lg bg-accent text-white text-ui font-medium hover:brightness-105 disabled:opacity-40 disabled:hover:brightness-100";const BTN_BORDERED =- "px-3 py-1.5 rounded-lg border border-line bg-paper text-[13px] hover:border-lineStrong";+ "px-3 py-1.5 rounded-lg border border-line bg-paper text-ui hover:border-lineStrong";// §35 approval buttons: blue border for the primary, quiet Deny (matches ApprovalCard).const BTN_ACCENT =- "px-3 py-1.5 rounded-lg border border-accent text-accent text-[13px] font-semibold hover:bg-accentSoft";-const BTN_QUIET = "px-3 py-1.5 text-[13px] text-faint hover:text-danger";+ "px-3 py-1.5 rounded-lg border border-accent text-accent text-ui font-semibold hover:bg-accentSoft";+const BTN_QUIET = "px-3 py-1.5 text-ui text-faint hover:text-danger";const OPT_BASE =- "inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full border text-[13px] transition-colors";+ "inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full border text-ui transition-colors";const OPT_OFF = "border-line bg-paper text-ink hover:border-accent hover:bg-accentSoft/50";const OPT_ON = "border-accent bg-accentSoft text-accent font-medium";const INPUT =- "flex-1 min-w-0 rounded-lg bg-paper border border-line px-3 py-2 text-[13px] text-ink placeholder:text-faint outline-none focus:border-lineStrong";+ "flex-1 min-w-0 rounded-lg bg-paper border border-line px-3 py-2 text-ui text-ink placeholder:text-faint outline-none focus:border-lineStrong";// Rich options stack as full-width rows (pills can't hold a description line).const ROW_BASE = "w-full text-left rounded-lg border px-3 py-2 transition-colors";const ROW_OFF = "border-line bg-paper hover:border-accent hover:bg-accentSoft/50";@@ -136,7 +147,7 @@ function QuestionBlock({ spec, onAnswer }: { spec: QSpec; onAnswer: (a: string)const preview = previewIdx >= 0 ? options[previewIdx].preview : "";const recommendedTag = (- <span className="text-[11px] uppercase tracking-[0.04em] font-semibold text-ok bg-okSoft border border-okLine rounded-full px-1.5 py-px shrink-0">+ <span className="text-label font-medium text-ok bg-okSoft border border-okLine rounded-full px-1.5 py-px shrink-0">{t("inbox.recommended")}</span>);@@ -157,15 +168,15 @@ function QuestionBlock({ spec, onAnswer }: { spec: QSpec; onAnswer: (a: string)><spanclassName={- "flex items-center gap-2 text-[13px] " + (on ? "text-accent font-medium" : "text-ink font-medium")+ "flex items-center gap-2 text-ui " + (on ? "text-accent font-medium" : "text-ink font-medium")}>- {multi && on && <span className="text-accent text-[11px] leading-none">✓</span>}+ {multi && on && <span className="text-accent text-label leading-none">✓</span>}<span className="min-w-0 truncate">{o.label}</span>{o.recommended && recommendedTag}</span>{o.description && (- <span className="block text-[12px] text-muted mt-0.5 leading-snug">{o.description}</span>+ <span className="block text-meta text-muted mt-0.5 leading-snug">{o.description}</span>)}</button>);@@ -182,7 +193,7 @@ function QuestionBlock({ spec, onAnswer }: { spec: QSpec; onAnswer: (a: string){optionRows}<predata-testid="question-preview"- className="flex-1 min-w-0 rounded-lg border border-line bg-paper p-3 text-[12px] leading-relaxed font-mono whitespace-pre overflow-auto max-h-72 text-ink"+ className="flex-1 min-w-0 rounded-lg border border-line bg-paper p-3 text-meta leading-relaxed font-mono whitespace-pre overflow-auto max-h-72 text-ink">{preview}</pre>@@ -200,7 +211,7 @@ function QuestionBlock({ spec, onAnswer }: { spec: QSpec; onAnswer: (a: string)className={OPT_BASE + " " + (on ? OPT_ON : OPT_OFF)}onClick={() => pick(o)}>- {multi && on && <span className="text-accent text-[11px] leading-none">✓</span>}+ {multi && on && <span className="text-accent text-label leading-none">✓</span>}{o.label}</button>);@@ -277,7 +288,7 @@ function QuestionCard({<div className={SEC + " flex items-center gap-1.5"} data-testid={grouped ? "question-stepper" : undefined}>{grouped && step > 0 && (<button- className="text-faint hover:text-ink leading-none text-[13px]"+ className="text-faint hover:text-ink leading-none text-ui"title={t("inbox.previous_question")}aria-label={t("inbox.previous_question")}onClick={() => setStep(step - 1)}@@ -302,9 +313,9 @@ function QuestionCard({</>)}</div>- <div className="text-[14px] font-semibold mt-0.5 leading-snug">{spec.question}</div>+ <div className="text-body font-semibold mt-0.5 leading-snug">{spec.question}</div>{item.body ? (- <div className="text-[13px] text-muted mt-1 whitespace-pre-wrap">{item.body}</div>+ <div className="text-ui text-muted mt-1 whitespace-pre-wrap">{item.body}</div>) : null}{chip}{/* key={step} resets selection/text/hover state when the stepper advances */}@@ -318,16 +329,56 @@ export function InboxItemCard({onResolve,chip,compact,+ modelLabels,}: {item: InboxItem;onResolve: (id: string, resolution: string) => void;chip?: ReactNode; // optional "go to session" affordance (shown in the Inbox list, not inline)compact?: boolean;+ // Curated model display names, when the caller has them (the staffing card shows names).+ modelLabels?: Record<string, string>;}) {const { t } = useTranslation();const isQuestion = item.kind === "question";+ // Team and work-item gates render their own card below; the plain-text body repeats+ // it (it exists for Slack mirrors), so it is not printed above the card.+ const toolCard = item.kind === "tool" && typeof item.data?.tool === "string";+ const gateCard =+ toolCard ||+ (item.kind === "plan" &&+ ((item.data?.gate === "team" && Array.isArray(item.data.members)) ||+ (item.data?.gate === "items" && Array.isArray(item.data.items))));+ const frame = compact+ ? "max-w-3xl mx-auto mb-2.5 rounded-xl2 border border-lineStrong bg-panel px-4 py-3.5 shadow-[0_8px_24px_rgba(0,0,0,0.08)]"+ : "mb-2.5 rounded-xl2 border border-line bg-panel px-3.5 py-3";+ // A lead's decision on a worker's waiting call: its own card (see WorkerDecisionCard).+ // Following the lead approves the lead's tool call; overriding answers the worker's+ // call directly and declines the lead's.+ if (item.kind === "approval" && item.data?.tool === "decide_worker_call") {+ const decision = leadDecisionFromArgs(item.data.arguments);+ return (+ <div data-testid={`inbox-item-${item.id}`} className={frame}>+ <WorkerDecisionCard+ bare+ decision={decision}+ workerCall={item.data.worker_call}+ chip={chip}+ onFollow={() => onResolve(item.id, "allow")}+ onOverride={() => {+ if (decision.callId) {+ // The worker's item sits on the same machine as this one.+ routeInboxItemLike(decision.callId, { itemId: item.id, sessionId: item.session_id });+ onResolve(decision.callId, decision.decision === "deny" ? "allow" : "deny");+ }+ onResolve(item.id, "deny");+ }}+ />+ </div>+ );+ }return (<div+ data-testid={`inbox-item-${item.id}`}className={compact? "max-w-3xl mx-auto mb-2.5 rounded-xl2 border border-lineStrong bg-panel px-4 py-3.5 shadow-[0_8px_24px_rgba(0,0,0,0.08)]"@@ -351,7 +402,7 @@ export function InboxItemCard({item.data.mcp_destination,);return (- <span className={"text-[11px] whitespace-nowrap pt-0.5 " + (s.external ? "text-warnInk" : "text-faint")}>+ <span className={"text-label whitespace-nowrap pt-0.5 " + (s.external ? "text-warnInk" : "text-faint")}>{s.text}</span>);@@ -359,8 +410,14 @@ export function InboxItemCard({</div>) : isQuestion ? null : ( // QuestionCard owns its header + title (stepper needs them)<>- <div className={SEC}>{item.kind}</div>- <div className="text-[14px] font-semibold mt-0.5 leading-snug">{item.title}</div>+ {/* Gate cards say what they are themselves; "plan" / "tool" above the question was+ a second heading (owner catch 2026-09-17). */}+ {!gateCard && <div className={SEC}>{item.kind}</div>}+ {/* Inside its own session a gate card's heading is enough ("Creating a team of+ agents — 2 workers"); the question stays in the Inbox LIST, where it helps scanning. */}+ {!(gateCard && compact) && (+ <div className="text-body font-semibold mt-0.5 leading-snug">{item.title}</div>+ )}</>)}{item.kind === "approval" && item.data?.tool === "save_skill" ? (@@ -379,13 +436,13 @@ export function InboxItemCard({// envelope in an expandable block, never the one-line truncated preview// (the body, subsumed by this block, is skipped for this branch).<PreviewBlock text={JSON.stringify(item.data.arguments, null, 2)} />- ) : !isQuestion && item.body ? (- <div className="text-[13px] text-muted mt-1 whitespace-pre-wrap">{item.body}</div>+ ) : !isQuestion && item.body && !gateCard ? (+ <div className="text-ui text-muted mt-1 whitespace-pre-wrap">{item.body}</div>) : null}{/* A real (non-boilerplate) reason travels in data — the body may be skippedabove, and the reason must survive that (e.g. a reviewer-unsure note). */}{item.kind === "approval" && item.data?.reason ? (- <div className="text-[12px] text-muted mt-1">{item.data.reason}</div>+ <div className="text-meta text-muted mt-1">{item.data.reason}</div>) : null}{!isQuestion && chip}{item.kind === "approval" ? (@@ -447,6 +504,54 @@ export function InboxItemCard({{t("approval.deny")}</button></div>+ ) : item.kind === "connector" ? (+ <div className="flex items-center gap-2 mt-2.5">+ <button+ className={BTN_PRIMARY}+ onClick={() => onResolve(item.id, JSON.stringify({ approved: true }))}+ >+ {item.data?.request === "grant" ? t("inbox.grant") : t("misc.inbox_item.connected")}+ </button>+ <button+ className={BTN_BORDERED}+ onClick={() => onResolve(item.id, JSON.stringify({ approved: false }))}+ >+ {t("approval.btn.not_now")}+ </button>+ </div>+ ) : toolCard ? (+ // A parked tool request had no branch here and fell through to "Dismiss", which the+ // server reads as a decline — an unattended session could never get its scanner+ // (found in the card gallery, 2026-09-17). Same card and same answer as inline.+ <div className={(compact ? "" : "mt-2.5 ") + "gate-nested"}>+ <ToolRequestCard+ item={toolItemFromPayload({ ...item.data, name: item.data?.tool, reason: item.body })}+ onRespond={(approved: boolean) => onResolve(item.id, JSON.stringify({ approved }))}+ />+ </div>+ ) : item.kind === "plan" && item.data?.gate === "team" && Array.isArray(item.data.members) ? (+ // The staffing gate parked in the Inbox (a lead on a box, or an unattended session):+ // the SAME card as the inline one, so connectors and team chat are the human's call+ // here too — a bare Approve staffs workers with no connectors and no chat+ // (owner-hit 2026-09-16).+ <div className={(compact ? "" : "mt-2.5 ") + "gate-nested"}>+ <TeamRequestCard+ item={teamItemFromPayload(item.data)}+ modelLabels={modelLabels}+ onRespond={(approved: boolean, feedback?: string, enableChat?: boolean, members?: TeamMemberDecision[]) =>+ onResolve(item.id, teamGateResolution(approved, feedback, enableChat, members))+ }+ />+ </div>+ ) : item.kind === "plan" && item.data?.gate === "items" && Array.isArray(item.data.items) ? (+ <div className={(compact ? "" : "mt-2.5 ") + "gate-nested"}>+ <WorkItemsCard+ item={workItemsItemFromPayload(item.data)}+ onRespond={(approved: boolean, feedback?: string) =>+ onResolve(item.id, itemsGateResolution(approved, feedback))+ }+ />+ </div>) : item.kind === "plan" ? (<div className="flex items-center gap-2 mt-2.5"><buttondiff --git a/surfaces/gui/src/components/InboxView.tsx b/surfaces/gui/src/components/InboxView.tsxindex 9b2eb9a3..9ff3fd07 100644--- a/surfaces/gui/src/components/InboxView.tsx+++ b/surfaces/gui/src/components/InboxView.tsx@@ -31,14 +31,14 @@ const KIND_TABS: { key: string; labelKey: string }[] = [];const CHIP = (active: boolean) =>- "text-[12px] px-2.5 py-1 rounded-full border " ++ "text-meta px-2.5 py-1 rounded-full border " +(active? "border-accent text-accent bg-accentSoft": "border-line text-muted hover:border-lineStrong");// Page-level tabs (§28): underline style, one visual level ABOVE the filter chips.const TAB = (active: boolean) =>- "pb-2 -mb-px text-[13px] border-b-2 flex items-center gap-1.5 " ++ "pb-2 -mb-px text-ui border-b-2 flex items-center gap-1.5 " +(active? "text-ink font-medium border-accent": "text-muted border-transparent hover:text-ink");@@ -134,6 +134,11 @@ export function InboxView({<Icon name={icon} size={11} /></span><span className="inbox-chip-label">{label}</span>+ {it.machine_name && (+ <span className="text-label text-faint" title={`on ${it.machine_name}`}>+ ⌂ {it.machine_name}+ </span>+ )}{exists && <Icon name="chevronRight" size={13} className="inbox-chip-go" />}</button>);@@ -165,7 +170,7 @@ export function InboxView({>{tt("inbox.tab_pending")}{items.length > 0 && (- <span className="text-[11px] px-1.5 rounded-full bg-accentSoft text-accent leading-4">+ <span className="text-label px-1.5 rounded-full bg-accentSoft text-accent leading-4">{items.length}</span>)}@@ -177,7 +182,7 @@ export function InboxView({>{tt("inbox.tab_configure")}{unroutedCount > 0 && (- <span className="text-[11px] px-1.5 rounded-full bg-warnSoft text-warnInk leading-4">+ <span className="text-label px-1.5 rounded-full bg-warnSoft text-warnInk leading-4">⚠ {unroutedCount}</span>)}@@ -188,7 +193,7 @@ export function InboxView({<InboxConfigure />) : (<>- <div className="text-[12px] text-faint -mt-1 mb-4" data-testid="inbox-routing">+ <div className="text-meta text-faint -mt-1 mb-4" data-testid="inbox-routing">{routing ? (<span>{tt("inbox.also_delivered_to")}{" "}diff --git a/surfaces/gui/src/components/TeamChatView.tsx b/surfaces/gui/src/components/TeamChatView.tsxindex a0977b1b..42e02720 100644--- a/surfaces/gui/src/components/TeamChatView.tsx+++ b/surfaces/gui/src/components/TeamChatView.tsx@@ -29,14 +29,23 @@ function clock(ts: string): string {: d.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" });}-export function TeamChatView({ teamId, onClose }: { teamId: string; onClose: () => void }) {+export function TeamChatView({+ teamId,+ sessionId,+ onClose,+}: {+ teamId: string;+ // The lead session the team belongs to — routes the calls to its machine (spec §6).+ sessionId?: string;+ onClose: () => void;+}) {const { t } = useTranslation();const [chat, setChat] = useState<TeamChat | null>(null);const [draft, setDraft] = useState("");const [busy, setBusy] = useState(false);const bottom = useRef<HTMLDivElement | null>(null);- const load = () => getTeamChat(teamId).then(setChat).catch(() => {});+ const load = () => getTeamChat(teamId, sessionId).then(setChat).catch(() => {});useEffect(() => {load();const t = setInterval(load, 3000);@@ -58,7 +67,7 @@ export function TeamChatView({ teamId, onClose }: { teamId: string; onClose: ()if (!text || busy) return;setBusy(true);try {- await postTeamChat(teamId, text);+ await postTeamChat(teamId, text, sessionId);setDraft("");await load();} finally {diff --git a/surfaces/gui/src/components/TeamRequestCard.groups.test.tsx b/surfaces/gui/src/components/TeamRequestCard.groups.test.tsxnew file mode 100644index 00000000..e1693ffb--- /dev/null+++ b/surfaces/gui/src/components/TeamRequestCard.groups.test.tsx@@ -0,0 +1,110 @@+// Large teams (owner-ruled 2026-09-17): workers that share a role collapse into one line+// with one model and one set of connector ticks; "Show workers" opens the per-worker rows.+// Grouping is a view — the answer stays one decision per worker. Payloads come from the+// card gallery's state files.+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++import { teamItemFromPayload } from "../cardPayloads";+import { statePayload } from "../gallery/states";+import { TeamRequestCard } from "./TeamRequestCard";++const OPUS = "anthropic:claude-opus-4-8";+const SONNET = "anthropic:claude-sonnet-4-8";++function show(state: string) {+ const onRespond = vi.fn();+ render(<TeamRequestCard item={teamItemFromPayload(statePayload("team-request", state))} onRespond={onRespond} />);+ const approve = () => {+ fireEvent.click(screen.getByTestId("teamreq-approve"));+ return onRespond.mock.calls[0][3] as { persona: string; name: string; connectors: string[]; model?: string }[];+ };+ return { approve };+}++describe("TeamRequestCard — roles with several workers", () => {+ afterEach(cleanup);++ it("shows twenty-four workers as four role lines and still answers per worker", () => {+ const { approve } = show("twenty-four-workers");+ expect(screen.getByTestId("teamreq-card").textContent).toContain("24 workers · 4 roles");+ for (const role of ["swe-worker", "test-worker", "review-worker", "docs-worker"])+ expect(screen.getByTestId(`teamreq-group-${role}`)).toBeTruthy();+ expect(screen.getByTestId("teamreq-group-swe-worker").textContent).toContain("× 12");+ // No per-worker row until a role is opened.+ expect(screen.queryByTestId("teamreq-row-0")).toBeNull();+ // A fallback shared by the whole role sits on the role line.+ expect(screen.getByTestId("teamreq-group-warn-test-worker")).toBeTruthy();+ const members = approve();+ expect(members).toHaveLength(24);+ expect(members.filter((m) => m.persona === "swe-worker").every((m) => m.connectors.includes("github") && m.model === OPUS)).toBe(true);+ expect(members.filter((m) => m.persona === "test-worker").every((m) => m.connectors.length === 0)).toBe(true);+ });++ it("keeps the ordinary row for a role with one worker", () => {+ show("six-workers");+ expect(screen.getByTestId("teamreq-group-swe-worker")).toBeTruthy();+ expect(screen.getByTestId("teamreq-row-3").textContent).toContain("checks");+ expect(screen.queryByTestId("teamreq-group-test-worker")).toBeNull();+ });++ it("sets one model for the whole role from the role line", () => {+ const { approve } = show("twelve-workers");+ fireEvent.change(screen.getByTestId("teamreq-group-model-swe-worker"), { target: { value: SONNET } });+ const members = approve();+ expect(members.filter((m) => m.persona === "swe-worker").map((m) => m.model)).toEqual(Array(6).fill(SONNET));+ expect(members.filter((m) => m.persona === "review-worker").every((m) => m.model === OPUS)).toBe(true);+ });++ it("says when a role is mixed, and one click makes it uniform", () => {+ const { approve } = show("mixed-within-a-role");+ expect((screen.getByTestId("teamreq-group-model-swe-worker") as HTMLSelectElement).value).toBe("__mixed__");+ expect(screen.getByTestId("teamreq-group-tally-swe-worker").textContent).toBe(+ "4 on Claude Opus 4.8, 2 on Claude Sonnet 4.8",+ );+ const github = screen.getByTestId("teamreq-group-connector-swe-worker-github") as HTMLInputElement;+ expect(github.indeterminate).toBe(true);+ expect(screen.getByTestId("teamreq-group-partial-swe-worker-github").textContent).toBe("5 of 6");+ fireEvent.click(github); // some → all+ expect(screen.queryByTestId("teamreq-group-partial-swe-worker-github")).toBeNull();+ expect(github.checked).toBe(true);+ const members = approve();+ expect(members.filter((m) => m.persona === "swe-worker").every((m) => m.connectors.includes("github"))).toBe(true);+ // The lead's per-worker models were left alone.+ expect(members.filter((m) => m.model === SONNET && m.persona === "swe-worker")).toHaveLength(2);+ });++ it("unticks the whole role when every worker already holds the connector", () => {+ const { approve } = show("twelve-workers");+ fireEvent.click(screen.getByTestId("teamreq-group-connector-swe-worker-github"));+ expect(approve().filter((m) => m.persona === "swe-worker").every((m) => m.connectors.length === 0)).toBe(true);+ });++ it("opens a role to change one worker; the role line then reports the split", () => {+ const { approve } = show("twelve-workers");+ fireEvent.click(screen.getByTestId("teamreq-group-toggle-swe-worker"));+ expect(screen.getByTestId("teamreq-group-members-swe-worker").children).toHaveLength(6);+ fireEvent.change(screen.getByTestId("teamreq-model-2"), { target: { value: SONNET } });+ fireEvent.click(screen.getByTestId("teamreq-connector-2-github"));+ expect(screen.getByTestId("teamreq-group-tally-swe-worker").textContent).toBe(+ "5 on Claude Opus 4.8, 1 on Claude Sonnet 4.8",+ );+ expect(screen.getByTestId("teamreq-group-partial-swe-worker-github").textContent).toBe("5 of 6");+ const members = approve();+ expect(members[2]).toEqual({ persona: "swe-worker", name: "lena", connectors: [], model: SONNET });+ expect(members[1].model).toBe(OPUS);+ fireEvent.click(screen.getByTestId("teamreq-group-toggle-swe-worker"));+ expect(screen.queryByTestId("teamreq-group-members-swe-worker")).toBeNull();+ });++ it("adds a connector beyond the usual set for the whole role", () => {+ const { approve } = show("twelve-workers");+ fireEvent.click(screen.getByTestId("teamreq-group-add-test-worker"));+ fireEvent.click(screen.getByTestId("teamreq-group-connector-test-worker-linear"));+ expect(screen.getByTestId("teamreq-group-test-worker").textContent).toContain("Beyond this role's usual set");+ expect((screen.getByTestId("teamreq-group-connector-test-worker-linear") as HTMLInputElement).checked).toBe(true);+ const members = approve();+ expect(members.filter((m) => m.persona === "test-worker").every((m) => m.connectors.includes("linear"))).toBe(true);+ expect(members.filter((m) => m.persona === "swe-worker").some((m) => m.connectors.includes("linear"))).toBe(false);+ });+});diff --git a/surfaces/gui/src/components/TeamRequestCard.test.tsx b/surfaces/gui/src/components/TeamRequestCard.test.tsxnew file mode 100644index 00000000..4a2d9452--- /dev/null+++ b/surfaces/gui/src/components/TeamRequestCard.test.tsx@@ -0,0 +1,254 @@+// The staffing card's own dress: two-line worker rows, the note clamp, one-line buttons+// with the grant sentence in the primary button's title (worker-connector-grants spec §6).+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++import type { Item } from "../types";+import { TeamRequestCard } from "./TeamRequestCard";++type TeamReq = Extract<Item, { kind: "teamreq" }>;++const base: TeamReq = {+ kind: "teamreq",+ members: [{ persona: "swe-worker", name: "nia", model: "claude-opus-4-8", reason: "Implements the fix." }],+ offer: { "swe-worker": ["github"] },+};++describe("TeamRequestCard", () => {+ afterEach(cleanup);++ it("puts name, persona and model on one line and the reason on its own", () => {+ render(<TeamRequestCard item={base} onRespond={vi.fn()} />);+ const row = screen.getByTestId("teamreq-row-0");+ const who = row.querySelector(".teamreq-who");+ expect(who?.textContent).toBe("nia — swe-worker · claude-opus-4-8");+ const reason = row.querySelector(".teamreq-reason");+ expect(reason?.textContent).toBe("Implements the fix.");+ expect(who?.contains(reason as Node)).toBe(false);+ });++ it("labels the buttons Not now / Create team and moves the grant sentence into the title", () => {+ const onRespond = vi.fn();+ render(<TeamRequestCard item={base} onRespond={onRespond} />);+ const approve = screen.getByTestId("teamreq-approve");+ expect(approve.textContent).toBe("Create team");+ expect(approve.getAttribute("title")).toContain("Approving grants the lead create, assign & steer");+ expect(approve.getAttribute("title")).toContain("Workers get only the connectors you tick.");+ expect(screen.getByTestId("teamreq-card").textContent).not.toContain("Approving grants the lead");+ fireEvent.click(screen.getByText("Not now"));+ expect(onRespond).toHaveBeenCalledWith(false);+ });++ it("an unsuggested default connector starts unticked, with no reason; ticks ride the approval", () => {+ const onRespond = vi.fn();+ render(<TeamRequestCard item={base} onRespond={onRespond} />);+ const github = screen.getByTestId("teamreq-connector-0-github") as HTMLInputElement;+ expect(github.checked).toBe(false);+ expect(screen.getByTestId("teamreq-row-0").querySelector(".teamreq-connector-reason")).toBeNull();+ fireEvent.click(github);+ fireEvent.click(screen.getByTestId("teamreq-approve"));+ expect(onRespond).toHaveBeenCalledWith(true, undefined, false, [+ { persona: "swe-worker", name: "nia", connectors: ["github"] },+ ]);+ });++ it("a suggestion the human unticks is not granted, and stays listed", () => {+ const onRespond = vi.fn();+ render(+ <TeamRequestCard+ item={{+ ...base,+ members: [{ ...base.members[0], connectors: ["github", "jira"] }],+ other_connected: ["jira"],+ }}+ onRespond={onRespond}+ />,+ );+ fireEvent.click(screen.getByTestId("teamreq-connector-0-jira"));+ expect((screen.getByTestId("teamreq-connector-0-jira") as HTMLInputElement).checked).toBe(false);+ expect(screen.getByTestId("teamreq-beyond-0")).toBeTruthy();+ fireEvent.click(screen.getByTestId("teamreq-approve"));+ expect(onRespond.mock.calls[0][3]).toEqual([+ { persona: "swe-worker", name: "nia", connectors: ["github"] },+ ]);+ });++ it("an empty default set shows nothing when other connectors can still be added", () => {+ render(+ <TeamRequestCard+ item={{ ...base, offer: { "swe-worker": [] }, other_connected: ["linear"] }}+ onRespond={vi.fn()}+ />,+ );+ expect(screen.getByTestId("teamreq-row-0").textContent).not.toContain("none available");+ expect(screen.queryByTestId("teamreq-beyond-0")).toBeNull();+ expect(screen.getByTestId("teamreq-add-0")).toBeTruthy();+ });++ it("clamps a long note behind More / Less and leaves a short one alone", () => {+ const long = "Three workers cover the plan. ".repeat(12).trim();+ render(<TeamRequestCard item={{ ...base, note: long }} onRespond={vi.fn()} />);+ const note = screen.getByText(long);+ expect(note.className).toContain("clamped");+ const toggle = screen.getByTestId("teamreq-note-toggle");+ expect(toggle.textContent).toBe("More");+ fireEvent.click(toggle);+ expect(note.className).not.toContain("clamped");+ expect(toggle.textContent).toBe("Less");+ cleanup();+ render(<TeamRequestCard item={{ ...base, note: "Short note." }} onRespond={vi.fn()} />);+ expect(screen.queryByTestId("teamreq-note-toggle")).toBeNull();+ });++ // Worker models on the card: the picker exists only when the server lists what can run.+ const withModels: TeamReq = {+ ...base,+ members: [+ { ...base.members[0], model: "anthropic:claude-opus-4-8", resolved_model: "anthropic:claude-opus-4-8" },+ {+ persona: "test-worker",+ name: "checks",+ model: "openai:gpt-5.6-sol",+ resolved_model: "anthropic:claude-sonnet-4-8",+ model_warning: "None of test-worker's recommended models can run here — using the lead's model.",+ },+ ],+ offer: { "swe-worker": ["github"], "test-worker": [] },+ model_options: {+ "swe-worker": ["anthropic:claude-opus-4-8", "anthropic:claude-sonnet-4-8"],+ "test-worker": [],+ },+ runnable_models: [+ { id: "anthropic:claude-opus-4-8", label: "Claude Opus 4.8" },+ { id: "anthropic:claude-sonnet-4-8", label: "Claude Sonnet 4.8" },+ { id: "ollama:qwen3", label: "Qwen 3 (local)" },+ ],+ lead_model: "anthropic:claude-sonnet-4-8",+ };++ it("without runnable_models the model stays plain text and decisions carry no model", () => {+ const onRespond = vi.fn();+ render(+ <TeamRequestCard+ item={{ ...base, members: [{ ...base.members[0], resolved_model: "claude-opus-4-8" }] }}+ onRespond={onRespond}+ />,+ );+ expect(screen.queryByTestId("teamreq-model-0")).toBeNull();+ expect(screen.getByTestId("teamreq-row-0").querySelector(".teamreq-who")?.textContent).toBe(+ "nia — swe-worker · claude-opus-4-8",+ );+ fireEvent.click(screen.getByTestId("teamreq-approve"));+ expect(onRespond.mock.calls[0][3]).toEqual([{ persona: "swe-worker", name: "nia", connectors: [] }]);+ expect("model" in onRespond.mock.calls[0][3][0]).toBe(false);+ });++ it("offers recommended then other models, defaults to resolved_model, and sends a model per worker", () => {+ const onRespond = vi.fn();+ render(<TeamRequestCard item={withModels} onRespond={onRespond} />);+ const nia = screen.getByTestId("teamreq-model-0") as HTMLSelectElement;+ expect(nia.value).toBe("anthropic:claude-opus-4-8");+ const groups = [...nia.querySelectorAll("optgroup")];+ expect(groups.map((g) => g.getAttribute("label"))).toEqual([+ "Recommended for this worker",+ "Other models on this machine",+ ]);+ expect([...groups[0].querySelectorAll("option")].map((o) => o.textContent)).toEqual([+ "Claude Opus 4.8",+ "Claude Sonnet 4.8",+ ]);+ expect([...groups[1].querySelectorAll("option")].map((o) => o.textContent)).toEqual(["Qwen 3 (local)"]);+ // an empty recommended list drops that group; the fallback is still selected+ const checks = screen.getByTestId("teamreq-model-1") as HTMLSelectElement;+ expect(checks.value).toBe("anthropic:claude-sonnet-4-8");+ expect([...checks.querySelectorAll("optgroup")].map((g) => g.getAttribute("label"))).toEqual([+ "Other models on this machine",+ ]);+ expect(screen.queryByTestId("teamreq-model-note-0")).toBeNull();+ fireEvent.click(screen.getByTestId("teamreq-approve"));+ expect(onRespond.mock.calls[0][3]).toEqual([+ { persona: "swe-worker", name: "nia", connectors: [], model: "anthropic:claude-opus-4-8" },+ { persona: "test-worker", name: "checks", connectors: [], model: "anthropic:claude-sonnet-4-8" },+ ]);+ });++ it("keeps the select filled when the initial model is not among the options", () => {+ render(+ <TeamRequestCard+ item={{ ...withModels, members: [{ ...base.members[0], resolved_model: "openai:gpt-5.6-sol" }] }}+ onRespond={vi.fn()}+ />,+ );+ const sel = screen.getByTestId("teamreq-model-0") as HTMLSelectElement;+ expect(sel.value).toBe("openai:gpt-5.6-sol");+ // The name only (no provider prefix); the exact id is the select's hover text.+ expect(sel.options[0].textContent).toBe("gpt-5.6-sol");+ expect(sel.getAttribute("title")).toBe("openai:gpt-5.6-sol");+ expect(sel.options[0].parentElement).toBe(sel);+ });++ it("warns on a fallback model until the human picks another, which then rides the approval", () => {+ const onRespond = vi.fn();+ render(<TeamRequestCard item={withModels} onRespond={onRespond} />);+ expect(screen.queryByTestId("teamreq-model-warn-0")).toBeNull();+ const glyph = screen.getByTestId("teamreq-model-warn-1");+ expect(glyph.getAttribute("role")).toBe("img");+ expect(glyph.getAttribute("title")).toContain("recommended models can run here");+ expect(glyph.getAttribute("aria-label")).toBe(glyph.getAttribute("title"));+ // no recommended list → the warning covers it, no note+ expect(screen.queryByTestId("teamreq-model-note-1")).toBeNull();+ fireEvent.change(screen.getByTestId("teamreq-model-1"), { target: { value: "ollama:qwen3" } });+ expect(screen.queryByTestId("teamreq-model-warn-1")).toBeNull();+ // back on the fallback → the warning returns+ fireEvent.change(screen.getByTestId("teamreq-model-1"), { target: { value: "anthropic:claude-sonnet-4-8" } });+ expect(screen.getByTestId("teamreq-model-warn-1")).toBeTruthy();+ fireEvent.change(screen.getByTestId("teamreq-model-1"), { target: { value: "ollama:qwen3" } });+ fireEvent.click(screen.getByTestId("teamreq-approve"));+ expect(onRespond.mock.calls[0][3][1]).toEqual({+ persona: "test-worker",+ name: "checks",+ connectors: [],+ model: "ollama:qwen3",+ });+ });++ it("notes a pick outside the worker's recommended models", () => {+ render(<TeamRequestCard item={withModels} onRespond={vi.fn()} />);+ expect(screen.queryByTestId("teamreq-model-note-0")).toBeNull();+ fireEvent.change(screen.getByTestId("teamreq-model-0"), { target: { value: "ollama:qwen3" } });+ const note = screen.getByTestId("teamreq-model-note-0");+ expect(note.textContent).toBe("Not one of this worker's recommended models.");+ expect(screen.getByTestId("teamreq-row-0").querySelector(".teamreq-who")?.contains(note)).toBe(false);+ fireEvent.change(screen.getByTestId("teamreq-model-0"), { target: { value: "anthropic:claude-sonnet-4-8" } });+ expect(screen.queryByTestId("teamreq-model-note-0")).toBeNull();+ });++ it("prefers the live composer mode over the payload's, and hides the line when neither is known", () => {+ render(<TeamRequestCard item={{ ...base, lead_mode: "auto-approve" }} leadMode="interactive" onRespond={vi.fn()} />);+ expect(screen.getByTestId("teamreq-approvals").textContent).toContain("Ask for approval");+ cleanup();+ render(<TeamRequestCard item={base} onRespond={vi.fn()} />);+ expect(screen.queryByTestId("teamreq-approvals")).toBeNull();+ });++ it("shows the model's name; the provider and raw id stay in the hover text", () => {+ const item: TeamReq = { ...base, members: [{ ...base.members[0], model: "anthropic:claude-opus-4-8" }] };+ // No curated labels (the Inbox list): the id without its provider prefix.+ render(<TeamRequestCard item={item} onRespond={vi.fn()} />);+ let model = screen.getByTestId("teamreq-row-0").querySelector(".teamreq-model") as HTMLElement;+ expect(model.textContent).toBe(" · claude-opus-4-8");+ expect(model.getAttribute("title")).toBe("anthropic:claude-opus-4-8");+ cleanup();+ // Curated labels (the session view passes /v1/settings.model_labels): the name only.+ render(+ <TeamRequestCard+ item={item}+ modelLabels={{ "anthropic:claude-opus-4-8": "Claude Opus 4.8 · Anthropic" }}+ onRespond={vi.fn()}+ />,+ );+ model = screen.getByTestId("teamreq-row-0").querySelector(".teamreq-model") as HTMLElement;+ expect(model.textContent).toBe(" · Claude Opus 4.8");+ expect(model.getAttribute("title")).toBe("Claude Opus 4.8 · Anthropic (anthropic:claude-opus-4-8)");+ });+});diff --git a/surfaces/gui/src/components/TeamRequestCard.tsx b/surfaces/gui/src/components/TeamRequestCard.tsxindex 7c3b863a..8b77cd79 100644--- a/surfaces/gui/src/components/TeamRequestCard.tsx+++ b/surfaces/gui/src/components/TeamRequestCard.tsx@@ -1,43 +1,542 @@-// The staffing gate (agent teams, UX-030): a lead proposes its worker roster.-// Visible layer = the decisions (who — by callname — on what model, why); approving-// grants the lead create/assign/steer for this board — standing, revocable — and-// PRE-SPAWNS the worker sessions. The chat checkbox is the USER's call (default-// OFF, ⓘ per mock); no in-card reply surface: editing happens by replying.-import { useState } from "react";+// The staffing gate (agent teams, UX-030; worker-connector-grants spec §2, §6): a lead+// proposes its worker roster. Visible layer = the decisions (who — by callname — on what+// model, why), plus per worker the connectors it may use. A worker's declared connectors+// are its DEFAULT set: the lead's suggestion there arrives ticked, with its reason.+// Beyond the default set sits a second group — shown when the lead proposed something+// there (quoting the human's own words) or when the human adds one from everything else+// connected on the machine. The human's final ticks are what the worker gets.+// Approvals FOLLOW THE LEAD: the card states the lead's real mode (live from the+// composer inline; from the gate payload in the Inbox) and has no control of its own.+// Approving grants the lead create/assign/steer for this board — standing, revocable —+// and PRE-SPAWNS the worker sessions. The chat checkbox is the USER's call (default OFF,+// ⓘ per mock); no in-card reply surface: editing happens by replying.+// Models: when the server lists what can run on this machine (`runnable_models`), each+// worker's model is a quiet picker on line one — recommended models first, the rest+// after. A worker whose persona recommends nothing runnable arrives on the fallback with+// a warning glyph; the human's final pick per worker rides the approval. An older+// server sends no list, and the model stays plain text.+// Large teams (owner-ruled 2026-09-17): workers that share a role collapse into ONE line —+// a count, one model and one set of connector ticks for the whole role. "Show workers"+// opens the ordinary per-worker rows for a human who wants to split the role (progressive+// disclosure). A role whose workers differ says so on its line ("Mixed", "11 of 12")+// rather than opening by itself. State and the answer stay per worker: grouping is a view.+import { useState, type ReactNode } from "react";import { Trans, useTranslation } from "react-i18next";+import type { TeamMemberDecision } from "../api";import type { Item } from "../types";+import { modeLabel } from "./Composer";+import { connectorLabel } from "./ConnectorRequestCard";import { Icon } from "./Icon";+import { modelHover, modelName } from "../modelNames";++// Past this length the lead's note clamps to two lines with More/Less — the roster and+// the connector decisions are the card's subject, not the note.+const NOTE_CLAMP_CHARS = 140;++const MIXED = "__mixed__";++const WarnGlyph = () => (+ <svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true">+ <path d="M8 2.2 14.2 13H1.8Z" fill="var(--warn-soft)" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round" />+ <path d="M8 6.3v3.4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />+ <circle cx="8" cy="11.4" r="0.85" fill="currentColor" />+ </svg>+);export function TeamRequestCard({item,+ leadMode,+ modelLabels,onRespond,}: {item: Extract<Item, { kind: "teamreq" }>;- onRespond: (approved: boolean, feedback?: string, enableChat?: boolean) => void;+ // The lead session's CURRENT approval mode (App state) — rendered, never edited here.+ leadMode?: string;+ // Curated display names from /v1/settings (when the caller has them).+ modelLabels?: Record<string, string>;+ onRespond: (+ approved: boolean,+ feedback?: string,+ enableChat?: boolean,+ members?: TeamMemberDecision[],+ ) => void;}) {const { t } = useTranslation();const [chat, setChat] = useState(!!item.enable_chat);+ const [noteOpen, setNoteOpen] = useState(false);+ const [adding, setAdding] = useState<Record<number, boolean>>({});+ const other = item.other_connected ?? [];+ const offerFor = (persona: string) => item.offer?.[persona] ?? [];+ // What a worker may end up holding: its default set, or anything else connected here.+ const allowedFor = (persona: string) => {+ const offer = offerFor(persona);+ return [...offer, ...other.filter((c) => !offer.includes(c))];+ };+ // The lead's suggestions start ticked — minus anything not connected on this machine.+ const [ticked, setTicked] = useState<Record<number, string[]>>(() =>+ Object.fromEntries(+ item.members.map((m, i) => {+ const allowed = allowedFor(m.persona);+ return [i, [...new Set(m.connectors ?? [])].filter((c) => allowed.includes(c))];+ }),+ ),+ );+ // The "beyond" group per worker: the lead's out-of-default suggestions, then the+ // human's additions. An entry stays listed once shown, so unticking never hides it.+ const [beyond, setBeyond] = useState<Record<number, string[]>>(() =>+ Object.fromEntries(+ item.members.map((m, i) => {+ const offer = offerFor(m.persona);+ return [+ i,+ [...new Set(m.connectors ?? [])].filter((c) => !offer.includes(c) && other.includes(c)),+ ];+ }),+ ),+ );+ const toggle = (i: number, c: string) =>+ setTicked((cur) => {+ const have = cur[i] ?? [];+ return { ...cur, [i]: have.includes(c) ? have.filter((x) => x !== c) : [...have, c] };+ });+ const addBeyond = (i: number, c: string) => {+ setBeyond((cur) => ({ ...cur, [i]: [...(cur[i] ?? []), c] }));+ setTicked((cur) => ({ ...cur, [i]: [...(cur[i] ?? []).filter((x) => x !== c), c] }));+ };+ // Set one connector for several workers at once (a role line). Turning on a connector+ // outside a worker's usual set lists it in that worker's "beyond" group too.+ const setForWorkers = (idxs: number[], c: string, on: boolean) => {+ setTicked((cur) => {+ const next = { ...cur };+ for (const i of idxs) {+ const have = (next[i] ?? []).filter((x) => x !== c);+ next[i] = on ? [...have, c] : have;+ }+ return next;+ });+ if (on)+ setBeyond((cur) => {+ const next = { ...cur };+ for (const i of idxs)+ if (!offerFor(item.members[i].persona).includes(c) && !(next[i] ?? []).includes(c))+ next[i] = [...(next[i] ?? []), c];+ return next;+ });+ };+ // Roles in order of first appearance, each with the roster indexes of its workers.+ const groups: { persona: string; idxs: number[] }[] = [];+ item.members.forEach((m, i) => {+ const g = groups.find((x) => x.persona === m.persona);+ if (g) g.idxs.push(i);+ else groups.push({ persona: m.persona, idxs: [i] });+ });+ const [open, setOpen] = useState<Record<string, boolean>>({});+ const [groupAdding, setGroupAdding] = useState<Record<string, boolean>>({});+ const runnable = Array.isArray(item.runnable_models) ? item.runnable_models : null;+ const recommendedFor = (persona: string) => {+ const rec = item.model_options?.[persona];+ return Array.isArray(rec) ? rec : [];+ };+ // The model's NAME only; provider and raw id go in the hover text.+ const serverLabels = Object.fromEntries((runnable ?? []).map((r) => [r.id, r.label]));+ const labels = { ...serverLabels, ...(modelLabels ?? {}) };+ const modelLabelOf = (id: string) => modelName(id, labels);+ // Each worker's current model pick — starts on what the server resolved for it.+ const [picked, setPicked] = useState<Record<number, string>>(() =>+ Object.fromEntries(+ item.members.map((m, i) => [i, m.resolved_model || m.model || item.lead_model || ""]),+ ),+ );+ const decisions = (): TeamMemberDecision[] =>+ item.members.map((m, i) => {+ const allowed = allowedFor(m.persona);+ return {+ persona: m.persona,+ ...(m.name ? { name: m.name } : {}),+ connectors: (ticked[i] ?? []).filter((c) => allowed.includes(c)),+ ...(runnable && picked[i] ? { model: picked[i] } : {}),+ };+ });+ const mode = leadMode ?? item.lead_mode;+ const note = item.note || "";+ const noteLong = note.length > NOTE_CLAMP_CHARS;+ const connectorBox = (i: number, c: string, reason?: string) => (+ <label key={c} className="teamreq-connector">+ <input+ type="checkbox"+ data-testid={`teamreq-connector-${i}-${c}`}+ checked={(ticked[i] ?? []).includes(c)}+ onChange={() => toggle(i, c)}+ />+ <span>{connectorLabel(c)}</span>+ {reason && <span className="teamreq-connector-reason">{reason}</span>}+ </label>+ );+ const modelOptions = (persona: string, current: string) => {+ const recommended = runnable ? recommendedFor(persona) : [];+ const others = (runnable ?? []).map((r) => r.id).filter((id) => !recommended.includes(id));+ return (+ <>+ {current !== MIXED && !recommended.includes(current) && !others.includes(current) && (+ <option value={current}>{current ? modelLabelOf(current) : t("team.default_model")}</option>+ )}+ {recommended.length > 0 && (+ <optgroup label={t("team.models_recommended")}>+ {recommended.map((id) => (+ <option key={id} value={id}>+ {modelLabelOf(id)}+ </option>+ ))}+ </optgroup>+ )}+ {others.length > 0 && (+ <optgroup label={t("team.models_on_machine")}>+ {others.map((id) => (+ <option key={id} value={id}>+ {modelLabelOf(id)}+ </option>+ ))}+ </optgroup>+ )}+ </>+ );+ };+ const warningOf = (i: number) => {+ const m = item.members[i];+ return runnable && m.model_warning && (picked[i] ?? "") === (m.resolved_model ?? "") ? m.model_warning : "";+ };+ const memberRow = (i: number): ReactNode => {+ const m = item.members[i];+ const offer = offerFor(m.persona);+ const extra = beyond[i] ?? [];+ const addable = other.filter((c) => !offer.includes(c) && !extra.includes(c));+ const reasons = m.connector_reasons ?? {};+ const current = picked[i] ?? "";+ const recommended = runnable ? recommendedFor(m.persona) : [];+ const warn = warningOf(i);+ const offList = !!runnable && recommended.length > 0 && !recommended.includes(current);+ return (+ <div className="teamreq-row" key={i} data-testid={`teamreq-row-${i}`}>+ <span className="teamreq-diamond">◆</span>+ <span className="teamreq-body">+ <span className="teamreq-who">+ {m.name && <b className="teamreq-name">{m.name}</b>}+ {m.name ? " — " : ""}+ <code>{m.persona}</code>+ {runnable ? (+ <>+ <span className="teamreq-model"> · </span>+ <span className="teamreq-model-pick">+ <select+ className="teamreq-model-select"+ data-testid={`teamreq-model-${i}`}+ aria-label={t("team.model_for", { who: m.name || m.persona })}+ title={modelHover(current, labels)}+ value={current}+ onChange={(e) => setPicked((cur) => ({ ...cur, [i]: e.target.value }))}+ >+ {modelOptions(m.persona, current)}+ </select>+ </span>+ {warn && (+ <span+ className="teamreq-model-warn"+ data-testid={`teamreq-model-warn-${i}`}+ role="img"+ aria-label={warn}+ title={warn}+ >+ <WarnGlyph />+ </span>+ )}+ </>+ ) : (+ m.model && (+ <span className="teamreq-model" title={modelHover(m.model, labels)}>+ {" "}+ · {modelLabelOf(m.model)}+ </span>+ )+ )}+ </span>+ {offList && (+ <span className="teamreq-model-note" data-testid={`teamreq-model-note-${i}`}>+ {t("team.model_off_list_worker")}+ </span>+ )}+ {m.reason && <span className="teamreq-reason">{m.reason}</span>}+ <span className="teamreq-dials">+ {offer.length > 0 ? (+ <span className="teamreq-connectors">+ <span className="teamreq-dial-label">{t("persona.connectors")}</span>+ {offer.map((c) => connectorBox(i, c, reasons[c]))}+ </span>+ ) : extra.length === 0 && other.length === 0 ? (+ <span className="teamreq-connectors">+ <span className="teamreq-dial-label">{t("persona.connectors")}</span>+ <span className="teamreq-none">{t("team.none_available")}</span>+ </span>+ ) : null}+ {extra.length > 0 && (+ <span className="teamreq-connectors teamreq-beyond" data-testid={`teamreq-beyond-${i}`}>+ <span className="teamreq-dial-label">{t("team.beyond_worker")}</span>+ {extra.map((c) => connectorBox(i, c, reasons[c]))}+ </span>+ )}+ {addable.length > 0 && (+ <button+ className="teamreq-add"+ data-testid={`teamreq-add-${i}`}+ aria-expanded={!!adding[i]}+ onClick={() => setAdding((s) => ({ ...s, [i]: !s[i] }))}+ >+ {t("team.add_connector")}+ </button>+ )}+ {adding[i] && addable.length > 0 && (+ <span className="teamreq-connectors" data-testid={`teamreq-addlist-${i}`}>+ {addable.map((c) => (+ <label key={c} className="teamreq-connector">+ <input+ type="checkbox"+ data-testid={`teamreq-connector-${i}-${c}`}+ checked={false}+ onChange={() => addBeyond(i, c)}+ />+ <span>{connectorLabel(c)}</span>+ </label>+ ))}+ </span>+ )}+ </span>+ </span>+ </div>+ );+ };+ // One line for a whole role. Its controls set every worker of the role at once.+ const groupRow = (g: { persona: string; idxs: number[] }): ReactNode => {+ const { persona, idxs } = g;+ const n = idxs.length;+ const offer = offerFor(persona);+ const isOpen = !!open[persona];+ const names = idxs.map((i) => item.members[i].name || "").filter(Boolean);+ const reasonsSet = new Set(idxs.map((i) => item.members[i].reason || ""));+ const sharedReason = reasonsSet.size === 1 ? [...reasonsSet][0] : "";+ // Model: one value when the role agrees, otherwise a count per model.+ const models = idxs.map((i) => picked[i] ?? "");+ const uniform = models.every((x) => x === models[0]);+ const tally = [...new Set(models)].map((id) => {+ const count = models.filter((x) => x === id).length;+ const model = modelLabelOf(id);+ return model ? t("team.tally_model", { n: count, model }) : t("team.tally_default", { n: count });+ });+ const tallyText = tally.join(t("team.list_separator"));+ const recommended = runnable ? recommendedFor(persona) : [];+ const offList = !!runnable && uniform && recommended.length > 0 && !recommended.includes(models[0]);+ const warned = idxs.filter((i) => warningOf(i));+ const warn = warned.length+ ? warned.length < n+ ? t("team.warning_partial", { warning: warningOf(warned[0]), have: warned.length, n })+ : warningOf(warned[0])+ : "";+ // Connectors: the role's usual set, then anything beyond it that any worker holds.+ const extra = [...new Set(idxs.flatMap((i) => beyond[i] ?? []))];+ const addable = other.filter((c) => !offer.includes(c) && !extra.includes(c));+ const holders = (c: string) => idxs.filter((i) => (ticked[i] ?? []).includes(c));+ const sharedConnectorReason = (c: string) => {+ const rs = new Set(holders(c).map((i) => item.members[i].connector_reasons?.[c] || ""));+ return rs.size === 1 ? [...rs][0] : "";+ };+ const groupBox = (c: string) => {+ const have = holders(c).length;+ const reason = sharedConnectorReason(c);+ return (+ <label key={c} className="teamreq-connector">+ <input+ type="checkbox"+ data-testid={`teamreq-group-connector-${persona}-${c}`}+ checked={have === n}+ ref={(el) => {+ if (el) el.indeterminate = have > 0 && have < n;+ }}+ onChange={() => setForWorkers(idxs, c, have !== n)}+ />+ <span>{connectorLabel(c)}</span>+ {have > 0 && have < n && (+ <span className="teamreq-partial" data-testid={`teamreq-group-partial-${persona}-${c}`}>+ {t("team.partial", { have, n })}+ </span>+ )}+ {reason && <span className="teamreq-connector-reason">{reason}</span>}+ </label>+ );+ };+ // Sits at the end of the last connectors line, so a role stays three lines tall.+ const addButton = addable.length > 0 && (+ <button+ className="teamreq-add teamreq-add-inline"+ data-testid={`teamreq-group-add-${persona}`}+ aria-expanded={!!groupAdding[persona]}+ onClick={() => setGroupAdding((cur) => ({ ...cur, [persona]: !cur[persona] }))}+ >+ {t("team.add_another")}+ </button>+ );+ return (+ <div className="teamreq-group" key={persona} data-testid={`teamreq-group-${persona}`}>+ <div className="teamreq-row teamreq-group-row">+ <span className="teamreq-diamond">◆</span>+ <span className="teamreq-body">+ <span className="teamreq-who">+ <code>{persona}</code>+ <b className="teamreq-count">× {n}</b>+ {runnable ? (+ <>+ <span className="teamreq-model">·</span>+ <span className="teamreq-model-pick">+ <select+ className="teamreq-model-select"+ data-testid={`teamreq-group-model-${persona}`}+ aria-label={t("team.model_for_role", { n, persona })}+ title={uniform ? modelHover(models[0], labels) : tallyText}+ value={uniform ? models[0] : MIXED}+ onChange={(e) => {+ const v = e.target.value;+ if (v !== MIXED) setPicked((cur) => ({ ...cur, ...Object.fromEntries(idxs.map((i) => [i, v])) }));+ }}+ >+ {!uniform && (+ <option value={MIXED} disabled>+ {t("team.mixed_models", { n: tally.length })}+ </option>+ )}+ {modelOptions(persona, uniform ? models[0] : MIXED)}+ </select>+ </span>+ {warn && (+ <span+ className="teamreq-model-warn"+ data-testid={`teamreq-group-warn-${persona}`}+ role="img"+ aria-label={warn}+ title={warn}+ >+ <WarnGlyph />+ </span>+ )}+ </>+ ) : null}+ <span className="spacer" />+ <button+ className="teamreq-add teamreq-group-toggle"+ data-testid={`teamreq-group-toggle-${persona}`}+ aria-expanded={isOpen}+ onClick={() => setOpen((cur) => ({ ...cur, [persona]: !cur[persona] }))}+ >+ {isOpen ? t("team.hide_workers") : t("team.show_workers")}+ </button>+ </span>+ {offList && <span className="teamreq-model-note">{t("team.model_off_list_role")}</span>}+ {!uniform && (+ <span className="teamreq-model-note" data-testid={`teamreq-group-tally-${persona}`}>+ {tallyText}+ </span>+ )}+ <span className="teamreq-reason">+ {sharedReason ||+ (names.length > 3+ ? t("team.names_and_more", {+ names: names.slice(0, 3).join(t("team.list_separator")),+ n: names.length - 3,+ })+ : names.join(t("team.list_separator")))}+ </span>+ <span className="teamreq-dials">+ {offer.length > 0 ? (+ <span className="teamreq-connectors">+ <span className="teamreq-dial-label">{t("team.connectors_for_all", { n })}</span>+ {offer.map(groupBox)}+ {extra.length === 0 && addButton}+ </span>+ ) : extra.length === 0 && other.length === 0 ? (+ <span className="teamreq-connectors">+ <span className="teamreq-dial-label">{t("persona.connectors")}</span>+ <span className="teamreq-none">{t("team.none_available")}</span>+ </span>+ ) : null}+ {extra.length > 0 && (+ <span className="teamreq-connectors teamreq-beyond">+ <span className="teamreq-dial-label">{t("team.beyond_role")}</span>+ {extra.map(groupBox)}+ {addButton}+ </span>+ )}+ {offer.length === 0 && extra.length === 0 && addButton}+ {groupAdding[persona] && addable.length > 0 && (+ <span className="teamreq-connectors">+ {addable.map((c) => (+ <label key={c} className="teamreq-connector">+ <input+ type="checkbox"+ data-testid={`teamreq-group-connector-${persona}-${c}`}+ checked={false}+ onChange={() => setForWorkers(idxs, c, true)}+ />+ <span>{connectorLabel(c)}</span>+ </label>+ ))}+ </span>+ )}+ </span>+ </span>+ </div>+ {isOpen && (+ <div className="teamreq-group-members" data-testid={`teamreq-group-members-${persona}`}>+ {idxs.map(memberRow)}+ </div>+ )}+ </div>+ );+ };return (<div className="dirreq-card teamreq-card" data-testid="teamreq-card"><div className="teamreq-head"><Icon name="diamond" size={15} /><span className="teamreq-title">- {t("team.proposed", { count: item.members.length })}+ {/* Roles show only when some role has 2+ workers, so that sentence is always "N workers". */}+ {groups.length < item.members.length+ ? t("team.creating_roles", { workers: item.members.length, count: groups.length })+ : t("team.creating", { count: item.members.length })}</span></div>- {item.note && <div className="teamreq-note">{item.note}</div>}- {item.members.map((m, i) => (- <div className="teamreq-row" key={i}>- <span className="teamreq-diamond">◆</span>- <span className="teamreq-body">- {m.name && <b className="teamreq-name">{m.name}</b>}- {m.name ? " — " : ""}- <code>{m.persona}</code>- {m.model && <span className="teamreq-model"> · {m.model}</span>}- {m.reason && <span className="teamreq-reason"> — {m.reason}</span>}- </span>+ {note && (+ <div className="teamreq-note-wrap">+ <div className={"teamreq-note" + (noteLong && !noteOpen ? " clamped" : "")}>{note}</div>+ {noteLong && (+ <button+ className="teamreq-note-toggle"+ data-testid="teamreq-note-toggle"+ onClick={() => setNoteOpen((o) => !o)}+ >+ {noteOpen ? t("team.less") : t("team.more")}+ </button>+ )}+ </div>+ )}+ {/* The roster scrolls inside the card; the header above and the decision below stay+ in view however many workers the lead proposes. */}+ <div className="teamreq-roster" data-testid="teamreq-roster">+ {groups.map((g) => (g.idxs.length === 1 ? memberRow(g.idxs[0]) : groupRow(g)))}+ </div>+ {mode && (+ <div className="teamreq-approvals" data-testid="teamreq-approvals">+ <Trans+ i18nKey="team.approvals_follow"+ values={{ mode: modeLabel(mode) }}+ components={{ b: <b /> }}+ /></div>- ))}+ )}<label className="teamreq-chat"><inputtype="checkbox"@@ -52,8 +551,7 @@ export function TeamRequestCard({i</span></label>- <div className="dirreq-actions">- <span className="teamreq-grant">{t("team.grant_note")}</span>+ <div className="dirreq-actions teamreq-actions"><span className="spacer" /><button className="btn" onClick={() => onRespond(false)}>{t("team.not_now")}@@ -61,9 +559,10 @@ export function TeamRequestCard({<buttonclassName="btn primary"data-testid="teamreq-approve"- onClick={() => onRespond(true, undefined, chat)}+ title={t("team.grant_title")}+ onClick={() => onRespond(true, undefined, chat, decisions())}>- {t("team.create_start")}+ {t("team.create_team")}</button></div></div>diff --git a/surfaces/gui/src/components/WorkItemsCard.test.tsx b/surfaces/gui/src/components/WorkItemsCard.test.tsxnew file mode 100644index 00000000..ca3ffd5d--- /dev/null+++ b/surfaces/gui/src/components/WorkItemsCard.test.tsx@@ -0,0 +1,41 @@+// The card prints its own "Done when:" label; a lead that repeats the label inside the+// criteria text must not produce "Done when: Done when: …".+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++import { stripDoneWhen, WorkItemsCard } from "./WorkItemsCard";++describe("WorkItemsCard — criteria", () => {+ afterEach(cleanup);++ it("strips a leading Done when: (any case, spacing, repeated)", () => {+ expect(stripDoneWhen("Done when: the cap holds")).toBe("the cap holds");+ expect(stripDoneWhen(" done WHEN :Done when: the cap holds")).toBe("the cap holds");+ expect(stripDoneWhen("It is done when: the cap holds")).toBe("It is done when: the cap holds");+ expect(stripDoneWhen(undefined)).toBe("");+ });++ it("shows the label exactly once", () => {+ render(+ <WorkItemsCard+ item={{+ kind: "itemsreq",+ items: [{ title: "Cap the backoff", criteria: "Done when: Done when: no wait exceeds maxDelayMs" }],+ }}+ onRespond={vi.fn()}+ />,+ );+ const text = screen.getByTestId("itemsreq-card").textContent || "";+ expect(text.match(/Done when:/g)).toHaveLength(1);+ expect(text).toContain("Done when: no wait exceeds maxDelayMs");+ });++ it("measures the clamp on the stripped text", () => {+ // 150 chars of criteria + a repeated label: over the threshold raw, under it stripped.+ const criteria = "Done when: Done when: " + "x".repeat(150);+ render(+ <WorkItemsCard item={{ kind: "itemsreq", items: [{ title: "T", criteria }] }} onRespond={vi.fn()} />,+ );+ expect(screen.queryByTestId("itemsreq-ac-toggle-0")).toBeNull();+ });+});diff --git a/surfaces/gui/src/components/WorkItemsCard.tsx b/surfaces/gui/src/components/WorkItemsCard.tsxindex 5b27f309..b71d1419 100644--- a/surfaces/gui/src/components/WorkItemsCard.tsx+++ b/surfaces/gui/src/components/WorkItemsCard.tsx@@ -13,6 +13,12 @@ import { Icon } from "./Icon";// separately pushes criteria back toward 1–3 crisp checks.const CRITERIA_CLAMP_CHARS = 160;+// The card prints its own "Done when:" label — a lead that writes the label into the+// criteria text (sometimes twice) must not produce "Done when: Done when: …".+export function stripDoneWhen(criteria: string | undefined): string {+ return (criteria || "").replace(/^(\s*done\s+when\s*:\s*)+/i, "");+}+export function WorkItemsCard({item,onRespond,@@ -36,7 +42,8 @@ export function WorkItemsCard({{item.note && <div className="itemsreq-note">{item.note}</div>}<div className="itemsreq-list">{visible.map((entry, i) => {- const long = (entry.criteria || "").length > CRITERIA_CLAMP_CHARS;+ const criteria = stripDoneWhen(entry.criteria);+ const long = criteria.length > CRITERIA_CLAMP_CHARS;const open = !!openCriteria[i];return (<div className="itemsreq-item" key={i}>@@ -44,7 +51,7 @@ export function WorkItemsCard({<span className="itemsreq-body"><span className="itemsreq-item-title">{entry.title}</span><span className={"itemsreq-ac" + (long && !open ? " clamped" : "")}>- <b>{t("team.items_done_when")}</b> {entry.criteria}+ <b>{t("team.items_done_when")}</b> {criteria}</span>{long && (<buttondiff --git a/surfaces/gui/src/components/WorkerDecisionCard.test.tsx b/surfaces/gui/src/components/WorkerDecisionCard.test.tsxnew file mode 100644index 00000000..a0e961e4--- /dev/null+++ b/surfaces/gui/src/components/WorkerDecisionCard.test.tsx@@ -0,0 +1,93 @@+// A lead's decision on a worker's waiting call gets its own card: the generic approval+// card asked the human to click "Allow" to DENY a command it never showed (owner catch+// 2026-09-17). Payloads come from the card gallery's state files.+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it, vi } from "vitest";++import { approvalItemFromPayload } from "../cardPayloads";+import { inboxItemBuilders } from "../gallery/inboxItems";+import { STATES, statePayload } from "../gallery/states";+import { ApprovalCard } from "./ApprovalCard";+import { InboxItemCard } from "./InboxItemCard";++const state = (id: string) => STATES["worker-decision"].find((s) => s.id === id)!;++describe("WorkerDecisionCard", () => {+ afterEach(cleanup);++ it("shows the worker's command and the lead's reason, never the call id", () => {+ render(<ApprovalCard item={approvalItemFromPayload(statePayload("worker-decision", "lead-denies-command"))} onApprove={vi.fn()} />);+ const card = screen.getByTestId("workerdec-card");+ expect(card.textContent).toContain("The lead wants to deny nia’s command");+ expect(screen.getByTestId("workerdec-call").textContent).toContain("issue-1/web && npm run build");+ expect(screen.getByTestId("workerdec-note").textContent).toContain("already done and merged");+ expect(card.textContent).not.toContain("c51dc4bd");+ expect(card.textContent).not.toContain("requires approval");+ });++ it("following the lead approves the lead's decision and touches nothing else", () => {+ const onApprove = vi.fn();+ const onAnswerWorkerCall = vi.fn();+ render(+ <ApprovalCard+ item={approvalItemFromPayload(statePayload("worker-decision", "lead-denies-command"))}+ onApprove={onApprove}+ onAnswerWorkerCall={onAnswerWorkerCall}+ />,+ );+ expect(screen.getByTestId("workerdec-follow").textContent).toBe("Deny it, as the lead suggests");+ fireEvent.click(screen.getByTestId("workerdec-follow"));+ expect(onApprove).toHaveBeenCalledWith("once");+ expect(onAnswerWorkerCall).not.toHaveBeenCalled();+ });++ it("overriding answers the worker's call with the opposite and declines the lead's", () => {+ const onApprove = vi.fn();+ const onAnswerWorkerCall = vi.fn();+ render(+ <ApprovalCard+ item={approvalItemFromPayload(statePayload("worker-decision", "lead-denies-command"))}+ onApprove={onApprove}+ onAnswerWorkerCall={onAnswerWorkerCall}+ />,+ );+ expect(screen.getByTestId("workerdec-override").textContent).toBe("Allow nia’s command instead");+ fireEvent.click(screen.getByTestId("workerdec-override"));+ expect(onAnswerWorkerCall).toHaveBeenCalledWith("c51dc4bd79f74e87b7fc59050dc41c37", "allow");+ expect(onApprove).toHaveBeenCalledWith("deny");+ });++ it("words the buttons the other way round when the lead allows", () => {+ render(<ApprovalCard item={approvalItemFromPayload(statePayload("worker-decision", "lead-allows-command"))} onApprove={vi.fn()} />);+ expect(screen.getByTestId("workerdec-follow").textContent).toBe("Allow it, as the lead suggests");+ expect(screen.getByTestId("workerdec-override").textContent).toBe("Deny it instead");+ });++ it("says so when the call was already answered, and offers nothing to decide", () => {+ render(<ApprovalCard item={approvalItemFromPayload(statePayload("worker-decision", "already-answered"))} onApprove={vi.fn()} />);+ expect(screen.getByTestId("workerdec-answered").textContent).toContain("already denied");+ expect(screen.queryByTestId("workerdec-override")).toBeNull();+ });++ it("explains the gap when an older server sends no worker call", () => {+ render(<ApprovalCard item={approvalItemFromPayload(statePayload("worker-decision", "old-server"))} onApprove={vi.fn()} />);+ expect(screen.getByTestId("workerdec-missing").textContent).toContain("Open nia’s session");+ expect(screen.getByTestId("workerdec-follow")).toBeTruthy();+ });++ it("parked in the Inbox: follow resolves the lead's item; override resolves the worker's first", () => {+ const onResolve = vi.fn();+ render(<InboxItemCard item={inboxItemBuilders["worker-decision"]!(state("lead-denies-command"))} onResolve={onResolve} />);+ expect(screen.getByTestId("workerdec-card").textContent).not.toContain("call_id");+ fireEvent.click(screen.getByTestId("workerdec-override"));+ expect(onResolve.mock.calls).toEqual([+ ["c51dc4bd79f74e87b7fc59050dc41c37", "allow"],+ ["gallery-item", "deny"],+ ]);+ cleanup();+ const again = vi.fn();+ render(<InboxItemCard item={inboxItemBuilders["worker-decision"]!(state("lead-denies-command"))} onResolve={again} />);+ fireEvent.click(screen.getByTestId("workerdec-follow"));+ expect(again.mock.calls).toEqual([["gallery-item", "allow"]]);+ });+});diff --git a/surfaces/gui/src/components/WorkerDecisionCard.tsx b/surfaces/gui/src/components/WorkerDecisionCard.tsxnew file mode 100644index 00000000..d91bee8f--- /dev/null+++ b/surfaces/gui/src/components/WorkerDecisionCard.tsx@@ -0,0 +1,148 @@+// A lead's decision on one of its workers' waiting tool calls (`decide_worker_call`,+// agent-teams spec §11.6), when that decision needs the human. The generic approval card+// made the human click "Allow" to DENY a command it never showed (owner catch+// 2026-09-17). This card shows both halves — what the worker wants to run and what the+// lead decided, with its reason — and the buttons say what will happen to the WORKER'S+// call: follow the lead, or do the opposite.+//+// `workerCall` is attached by the server (it looks the waiting call up by `call_id`).+// An older server sends none: the card still explains the decision and says the call+// itself cannot be shown.+import type { ReactNode } from "react";+import { getI18n, Trans, useTranslation } from "react-i18next";+import { humanizeApprovalTitle } from "../humanize";+import { PreviewBlock, TitleText } from "./ApprovalCard";+import { Icon } from "./Icon";++export interface WorkerCall {+ worker?: string;+ tool: string;+ arguments?: any;+ reason?: string;+ // "pending" while the worker is still waiting; "resolved" when someone already answered.+ state?: string;+ resolution?: string | null;+}++export interface LeadDecision {+ worker: string;+ callId: string;+ decision: "allow" | "deny";+ note: string;+}++export function leadDecisionFromArgs(args: any): LeadDecision {+ const a = args && typeof args === "object" ? args : {};+ return {+ worker: String(a.worker ?? "").trim() || getI18n().t("workerdec.a_worker"),+ callId: String(a.call_id ?? ""),+ decision: String(a.decision ?? "").trim().toLowerCase() === "allow" ? "allow" : "deny",+ note: String(a.note ?? "").trim(),+ };+}++// "command" / "file change" / "action": the noun the card uses for the worker's call.+// Returned as a KEY SUFFIX: every sentence that names the call has one key per noun+// (`workerdec.title_deny_command`, …) so no language has to splice a noun into a sentence.+type Noun = "command" | "file_change" | "action";+function nounFor(tool?: string): Noun {+ if (tool === "run_shell") return "command";+ if (tool && /^(write_file|replace_in_file|apply_patch|apply_unified_diff)$/.test(tool)) return "file_change";+ return "action";+}++export function WorkerDecisionCard({+ decision,+ workerCall,+ onFollow,+ onOverride,+ compact = false,+ bare = false,+ chip,+}: {+ decision: LeadDecision;+ workerCall?: WorkerCall | null;+ // Do what the lead decided / do the opposite. Both answer the worker's call.+ onFollow: () => void;+ onOverride: () => void;+ compact?: boolean;+ // Inside an Inbox item the item's own frame is the box.+ bare?: boolean;+ chip?: ReactNode;+}) {+ const { t } = useTranslation();+ const { worker, note } = decision;+ const deny = decision.decision === "deny";+ const noun = nounFor(workerCall?.tool);+ const answered = workerCall?.state === "resolved";+ const args = workerCall?.arguments && typeof workerCall.arguments === "object" ? workerCall.arguments : {};+ const preview =+ typeof args.command === "string" ? args.command : typeof args.content === "string" ? args.content : "";+ return (+ <div+ className={bare ? "workerdec bare" : "approval workerdec" + (compact ? " approval-dock" : "")}+ data-testid="workerdec-card"+ >+ <div className="approval-top">+ <div className="approval-heading">+ <span className="approval-ico" title={t("approval.tool_title", { name: "decide_worker_call" })}>+ <Icon name="diamond" size={15} />+ </span>+ <span className="workerdec-title">+ <Trans+ i18nKey={`workerdec.title_${deny ? "deny" : "allow"}_${noun}`}+ values={{ worker }}+ components={{ b: <b /> }}+ />+ </span>+ </div>+ <span className="approval-scope">{t("workerdec.scope", { worker })}</span>+ </div>++ <div className="workerdec-label">{t("workerdec.wants_to", { worker })}</div>+ {workerCall ? (+ <div className="workerdec-call" data-testid="workerdec-call">+ <TitleText line={humanizeApprovalTitle(workerCall.tool, args)} />+ {preview && <PreviewBlock text={preview} />}+ {workerCall.reason && workerCall.reason !== "requires approval" && (+ <div className="approval-reason">{workerCall.reason}</div>+ )}+ </div>+ ) : (+ <div className="workerdec-missing" data-testid="workerdec-missing">+ {t(`workerdec.missing_${noun}`, { worker })}+ </div>+ )}++ <div className="workerdec-label">{t("workerdec.lead_reason")}</div>+ <div className="workerdec-note" data-testid="workerdec-note">+ {note || t("workerdec.no_reason")}+ </div>+ {chip}++ {answered ? (+ <>+ <div className="workerdec-answered" data-testid="workerdec-answered">+ {t(`workerdec.answered_${workerCall?.resolution === "allow" ? "allowed" : "denied"}_${noun}`)}+ </div>+ <div className="approval-btns">+ <span className="spacer" />+ <button className="btn" data-testid="workerdec-follow" onClick={onFollow}>+ {t("workerdec.ok")}+ </button>+ </div>+ </>+ ) : (+ <div className="approval-btns">+ <button className="btn approval-primary" data-testid="workerdec-follow" onClick={onFollow}>+ {deny ? t("workerdec.follow_deny") : t("workerdec.follow_allow")}+ </button>+ <span className="spacer" />+ <button className="btn quiet-deny" data-testid="workerdec-override" onClick={onOverride}>+ {deny ? t(`workerdec.override_allow_${noun}`, { worker }) : t("workerdec.override_deny")}+ </button>+ </div>+ )}+ </div>+ );+}