Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agents): tabbed agent details pane with full anatomy and learning review (#908)
Ruben Lütkedd0c3e207ae2
diff --git a/dodaios/society/learning_review.py b/dodaios/society/learning_review.pynew file mode 100644index 0000000000..de0a9b96a8--- /dev/null+++ b/dodaios/society/learning_review.py@@ -0,0 +1,260 @@+"""One agent's learning review queue: what it proposed or wrote that waits for the person.++The queue is a read model over rows that already exist, so it needs no table,+enum or event kind of its own:++* ``proposal:<approval id>`` — a pending configuration proposal (rule, skill,+ routine, approval rule, focus, team, identity). Approve and reject go through+ :func:`dodaios.society.proposals.resolve`, the same path the chat card uses.+* ``share:<approval id>`` — a note the agent asked to promote to shared+ knowledge. Approve promotes it; reject keeps it private.+* ``memory:<knowledge id>`` — an entry the agent wrote into its own notebook+ (``MEMORY.md`` / ``USER.md``) that nobody has looked at yet. Approve keeps it;+ reject removes the entry from the notebook.++Only recent memory writes are listed (``MEMORY_WINDOW_MS``) and the list is+bounded, so years of old bookkeeping rows never turn into a wall of chores. The+person's own writes never need review and are skipped. Nothing here calls a+model, so deciding an item never bills a key.+"""++from __future__ import annotations++import logging+from typing import Any, Final++from .events import now_ms+from .memory import MEMORY_SHARE_CAPABILITY, MemoryRefused+from .proposals import kind_of++log = logging.getLogger(__name__)++__all__ = ["MEMORY_WINDOW_MS", "ReviewRefused", "decide", "queue"]++#: Memory writes older than this are history, not a review chore.+MEMORY_WINDOW_MS: Final[int] = 14 * 24 * 3600 * 1000+#: Most items one queue lists; the total is reported separately.+MAX_ITEMS: Final[int] = 40+_MAX_PREVIEW: Final[int] = 24+_MAX_LINE: Final[int] = 240+_BOOKS: Final[tuple[str, ...]] = ("MEMORY.md", "USER.md")+++class ReviewRefused(ValueError):+ """An item that is unknown, not this agent's, or already decided."""+++def _clip(text: Any) -> str:+ line = " ".join(str(text or "").split())+ return line if len(line) <= _MAX_LINE else line[: _MAX_LINE - 1] + "…"+++def _lines(prefix: str, values: list[Any]) -> list[str]:+ return [f"{prefix} {_clip(v)}" for v in values if str(v or "").strip()]+++def _proposal_preview(kind: str, payload: dict[str, Any], agent: Any) -> list[str]:+ """A diff-style preview: ``+`` added, ``-`` removed, two spaces unchanged."""+ if kind == "rule":+ operation = str(payload.get("operation") or "add")+ out = _lines("-", [payload.get("old_text")]) if operation != "add" else []+ return out + (_lines("+", [payload.get("text")]) if operation != "remove" else [])+ if kind == "focus":+ new = [str(x) for x in payload.get("focus") or []]+ old = [str(x) for x in getattr(agent, "focus", []) or []]+ out = [f"- {cap}" for cap in old if cap not in new]+ out += [f"+ {cap}" if cap not in old else f" {cap}" for cap in new]+ return out+ if kind == "approval_rule":+ return _lines("+ ask first:", list(payload.get("require_approval") or [])) + _lines(+ "+ always allow:", list(payload.get("always_allow") or [])+ )+ if kind == "identity":+ out: list[str] = []+ for key in ("name", "title", "description"):+ new_value = payload.get(key)+ if not new_value:+ continue+ old_value = getattr(agent, key, "")+ if old_value and old_value != new_value:+ out.append(f"- {key}: {_clip(old_value)}")+ out.append(f"+ {key}: {_clip(new_value)}")+ return out+ if kind == "skill":+ return (+ _lines("+", [payload.get("name")])+ + _lines(" ", [payload.get("goal")])+ + _lines(" ·", list(payload.get("steps") or []))+ )+ if kind == "routine":+ operation = str(payload.get("operation") or "create")+ if operation in {"pause", "resume", "cancel", "delete"}:+ return [f" {operation} {payload.get('task_id', '')}"]+ schedule = payload.get("schedule") or {}+ return _lines("+", [payload.get("title")]) + _lines(+ " ", [f"{schedule.get('kind', 'every')}: {payload.get('prompt', '')}"]+ )+ return _lines("+", list(payload.get("names") or []))+++def _book_of(path: str) -> str:+ name = path.rsplit("/", 1)[-1]+ return name if name in _BOOKS else ""+++async def queue(rt: Any, agent: Any) -> dict[str, Any]:+ """Every review item of ``agent``, newest first, plus per-kind totals."""+ await rt.approvals.expire_due()+ items: list[dict[str, Any]] = []+ pending = [a for a in await rt.approvals.pending() if a.agent_id == agent.agent_id]+ for approval in pending:+ proposal_kind = kind_of(approval.capability)+ if proposal_kind is not None:+ payload = approval.action.get("payload") or {}+ items.append(+ {+ "id": f"proposal:{approval.id}",+ "kind": "proposal",+ "proposal_kind": proposal_kind,+ "summary": approval.summary,+ "reason": _clip(approval.action.get("reason")),+ "preview": _proposal_preview(proposal_kind, payload, agent)[:_MAX_PREVIEW],+ "created_ms": approval.created_ms,+ }+ )+ elif approval.capability == MEMORY_SHARE_CAPABILITY:+ items.append(+ {+ "id": f"share:{approval.id}",+ "kind": "memory_share",+ "proposal_kind": "",+ "summary": approval.summary,+ "reason": "",+ "preview": _lines("+", [approval.action.get("title")]),+ "path": str(approval.action.get("path") or ""),+ "created_ms": approval.created_ms,+ }+ )+ since = now_ms() - MEMORY_WINDOW_MS+ rows = await rt.store.list_knowledge_rows(+ agent_id=agent.agent_id, reviewed=False, limit=MAX_ITEMS * 4+ )+ memory = [+ r+ for r in rows+ if int(r.get("created_ms") or 0) >= since+ and str(r.get("origin") or "") != "user"+ and _book_of(str(r.get("wiki_path") or ""))+ and str(r.get("summary") or "").strip()+ ]+ for row in memory:+ items.append(+ {+ "id": f"memory:{int(row['id'])}",+ "kind": "memory",+ "proposal_kind": "",+ "summary": _clip(row.get("summary")),+ "reason": "",+ "preview": _lines("+", [row.get("summary")]),+ "path": str(row.get("wiki_path") or ""),+ "book": _book_of(str(row.get("wiki_path") or "")),+ "origin": str(row.get("origin") or ""),+ "created_ms": int(row.get("created_ms") or 0),+ }+ )+ items.sort(key=lambda item: int(item.get("created_ms") or 0), reverse=True)+ counts = {+ "proposal": sum(1 for i in items if i["kind"] == "proposal"),+ "memory_share": sum(1 for i in items if i["kind"] == "memory_share"),+ "memory": sum(1 for i in items if i["kind"] == "memory"),+ }+ return {"items": items[:MAX_ITEMS], "total": len(items), "counts": counts}+++async def _pending_approval(rt: Any, agent: Any, approval_id: str) -> Any:+ item = await rt.approvals.get(approval_id)+ if item is None or item.agent_id != agent.agent_id:+ raise KeyError(approval_id)+ if str(item.state) not in ("pending", "blocked"):+ raise ReviewRefused("already decided")+ return item+++async def decide(+ rt: Any,+ agent: Any,+ item_id: str,+ *,+ approve: bool,+ task_store: Any = None,+ scheduler: Any = None,+) -> dict[str, Any]:+ """Approve or reject one item of the queue; returns ``{"id", "outcome", ...}``.++ Raises ``KeyError`` for an unknown item and :class:`ReviewRefused` for one+ that cannot be decided (already decided, wrong kind).+ """+ kind, _, ref = item_id.partition(":")+ if not ref:+ raise KeyError(item_id)+ if kind == "proposal":+ from . import proposals++ await _pending_approval(rt, agent, ref)+ try:+ result = await proposals.resolve(+ rt, ref, approve=approve, task_store=task_store, scheduler=scheduler+ )+ except ValueError as exc:+ raise ReviewRefused(str(exc)) from exc+ outcome = "rejected" if not approve else ("applied" if result.get("applied") else "failed")+ return {"id": item_id, "outcome": outcome, "detail": str(result.get("detail") or "")}+ if kind == "share":+ current = await _pending_approval(rt, agent, ref)+ if current.capability != MEMORY_SHARE_CAPABILITY:+ raise ReviewRefused("not a knowledge share")+ knowledge_id = int(current.action.get("knowledge_id") or 0)+ await rt.approvals.resolve(ref, approve=approve, note="agent pane")+ try:+ if approve:+ path = await rt.memory.promote(knowledge_id)+ return {"id": item_id, "outcome": "applied", "detail": path}+ if knowledge_id:+ await rt.memory.dismiss(knowledge_id)+ except MemoryRefused as exc:+ log.info("society review: share %s not applied: %s", item_id, exc)+ return {"id": item_id, "outcome": "failed", "detail": str(exc)}+ return {"id": item_id, "outcome": "rejected", "detail": ""}+ if kind == "memory":+ try:+ knowledge_id = int(ref)+ except ValueError as exc:+ raise KeyError(item_id) from exc+ rows = await rt.store.list_knowledge_rows(agent_id=agent.agent_id, limit=100_000)+ row = next((r for r in rows if int(r["id"]) == knowledge_id), None)+ if row is None:+ raise KeyError(item_id)+ if row.get("reviewed"):+ raise ReviewRefused("already decided")+ detail = ""+ outcome = "applied" if approve else "rejected"+ if not approve:+ # The staged summary is the entry's text (clipped at 280 characters):+ # remove the entry that carries it. An entry since rewritten by the+ # agent is no longer this text, and stays.+ target = _book_of(str(row.get("wiki_path") or "")).removesuffix(".md").lower()+ try:+ await rt.memory.remember_receipt(+ agent,+ "",+ target=target or None,+ origin="user",+ operation="remove",+ old_text=str(row.get("summary") or ""),+ )+ except (MemoryRefused, ValueError, KeyError) as exc:+ log.info("society review: %s not removed: %s", item_id, exc)+ outcome, detail = "not_found", str(exc)+ await rt.store.mark_knowledge_reviewed(knowledge_id)+ return {"id": item_id, "outcome": outcome, "detail": detail}+ raise KeyError(item_id)diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentLimits.test.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentLimits.test.tsxindex 847f22ceac..7cd591e0b3 100644--- a/dodaios/ui/web/frontend/src/components/society/card/AgentLimits.test.tsx+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentLimits.test.tsx@@ -1,20 +1,18 @@/**- * The card's Limits block — the budget, ceiling and concurrency a person can- * change after the agent exists.+ * The limits and permissions in the agent pane's Tools & access tab — the+ * budget, ceiling, approval mode and concurrency a person can change after+ * the agent exists.*- * All three were settable only once, at creation, behind a disclosure labelled- * "More" that nobody opened, so the numbers on the card read as decoration- * (maintainer, 2026-09-03). What this pins is the part that would break- * silently: that Save sends the three fields the PATCH route enforces, and- * that it sends NOTHING else — the route re-derives an agent's focus whenever- * a title or description arrives, so a budget edit that carried prose along- * would quietly rewrite the tools the agent reaches for.+ * What this pins is the part that would break silently: Save sends ONLY the+ * fields that changed. The route re-derives an agent's focus whenever a title+ * or description arrives, so a budget edit that carried prose or tool lists+ * along would quietly rewrite the tools the agent reaches for.*/import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";-import { AgentSpecSheet } from "@/components/society/card/AgentSpecSheet";+import { ToolsTab } from "@/components/society/card/pane/ToolsTab";import type { SocietyAgent } from "@/components/society/data";const AGENT: SocietyAgent = {@@ -48,25 +46,57 @@ const AGENT: SocietyAgent = {stats: { runs: 0, totalCostUsd: 0, spentTodayUsd: 0, lastActiveMs: null },};-function renderCard(over: Partial<SocietyAgent> = {}) {+function rowFor(agent: SocietyAgent, body: Record<string, unknown>) {+ return {+ agent: {+ agent_id: agent.agentId, name: agent.name, title: agent.title, description: agent.description,+ tier: agent.tier, parent_agent_id: null, state: "active", avatar: {}, checkpoint: "idle",+ provider: "", model: "", effort: "", account_id: "", grant_mode: agent.grantMode,+ grants: agent.toolGrants, focus: agent.focus, denies: agent.denies, skills: null,+ workspace_dir: agent.workspaceDir, wiki_namespace: agent.wikiNamespace, knowledge_scope: "shared",+ permission_ceiling: agent.permissionCeiling, approval_mode: agent.approvalMode ?? null,+ approval_rules: { require_approval: [], always_allow: [] },+ daily_budget_usd: agent.dailyBudgetUsd, max_concurrent_runs: agent.maxConcurrentRuns,+ browser_mode: "own", browser_allowed_domains: [], computer_id: null, runtime: "jarvis",+ session_id: agent.chatSessionId, created_ms: 0, updated_ms: 0,+ stats: { runs: 0, total_cost_usd: 0, last_active_ms: null },+ ...body,+ },+ };+}++function renderTab(over: Partial<SocietyAgent> = {}) {const client = new QueryClient({defaultOptions: { queries: { retry: false, staleTime: Infinity } },});+ const agent = { ...AGENT, ...over };return render(<QueryClientProvider client={client}>- <AgentSpecSheet agent={{ ...AGENT, ...over }} />+ <ToolsTab agent={agent} sample={false} /></QueryClientProvider>,);}let fetchMock: ReturnType<typeof vi.fn>;-describe("the card's limits", () => {+function patchBody(): Record<string, unknown> {+ const patch = fetchMock.mock.calls.find((c) => (c[1] as RequestInit | undefined)?.method === "PATCH");+ expect(patch).toBeTruthy();+ return JSON.parse(String((patch?.[1] as RequestInit).body)) as Record<string, unknown>;+}++describe("the agent pane's limits and permissions", () => {beforeEach(() => {- fetchMock = vi.fn(async (url: string) => {+ fetchMock = vi.fn(async (url: string, init?: RequestInit) => {if (String(url).includes("/capabilities")) {return { ok: true, json: async () => ({ capabilities: [] }) } as Response;}+ if (String(url).includes("/providers")) {+ return { ok: true, json: async () => ({ providers: [] }) } as Response;+ }+ if (init?.method === "PATCH") {+ return { ok: true, json: async () => rowFor(AGENT, JSON.parse(String(init.body))) } as Response;+ }return { ok: true, json: async () => ({}) } as Response;});vi.stubGlobal("fetch", fetchMock);@@ -77,87 +107,98 @@ describe("the card's limits", () => {vi.restoreAllMocks();});- test("shows the cap beside today's spend, so the budget reads as the gate it is", async () => {- renderCard();- await waitFor(() => expect(screen.getByTestId("agent-limits-edit")).toBeTruthy());- expect(screen.getByTestId("agent-card-sheet").textContent).toContain("$0.00 of $2.00");+ test("nothing is sent and no save bar shows until something changes", async () => {+ renderTab();+ await screen.findByTestId("agent-pane-limits");+ expect(screen.queryByTestId("agent-pane-savebar")).toBeNull();+ expect(fetchMock.mock.calls.some((c) => (c[1] as RequestInit | undefined)?.method === "PATCH")).toBe(false);});- test("saves the three enforced knobs, and nothing that would re-derive the tools", async () => {- renderCard();- fireEvent.click(await screen.findByTestId("agent-limits-edit"));-- fireEvent.change(screen.getByTestId("agent-budget-input"), { target: { value: "7.5" } });- fireEvent.click(screen.getByText("Ask first"));- fireEvent.click(screen.getByText("Save"));-- await waitFor(() => {- const patch = fetchMock.mock.calls.find((c) => c[1]?.method === "PATCH");- expect(patch).toBeTruthy();- const body = JSON.parse(String(patch?.[1]?.body));- expect(body).toEqual({- daily_budget_usd: 7.5,- permission_ceiling: "ask",- max_concurrent_runs: 1,- });- });+ test("a budget edit sends the budget and nothing that would re-derive the tools", async () => {+ renderTab();+ fireEvent.change(await screen.findByTestId("agent-budget-input"), { target: { value: "7.5" } });+ fireEvent.click(screen.getByTestId("agent-pane-save"));+ await waitFor(() => expect(patchBody()).toEqual({ daily_budget_usd: 7.5 }));});- test("saves an explicit approval mode while preserving the ceiling", async () => {- renderCard({ approvalMode: "bypass" });- fireEvent.click(await screen.findByTestId("agent-limits-edit"));- fireEvent.click(screen.getByText("Always ask"));- fireEvent.click(screen.getByText("Save"));-- await waitFor(() => {- const patch = fetchMock.mock.calls.find((call) => call[1]?.method === "PATCH");- const body = JSON.parse(String(patch?.[1]?.body));- expect(body.approval_mode).toBe("always_ask");- expect(body.permission_ceiling).toBe("monitor");- });+ test("raising the legacy ceiling asks first, then saves it", async () => {+ renderTab();+ const ceiling = await screen.findByTestId("agent-pane-ceiling");+ fireEvent.click(within(ceiling).getByText("Ask first"));+ fireEvent.click(screen.getByTestId("agent-pane-save"));+ const confirm = await screen.findByTestId("agent-pane-widen");+ await waitFor(() => expect(confirm.textContent).toContain("Ask first"));+ expect(fetchMock.mock.calls.some((c) => (c[1] as RequestInit | undefined)?.method === "PATCH")).toBe(false);+ fireEvent.click(screen.getByTestId("agent-pane-widen-confirm"));+ await waitFor(() => expect(patchBody()).toEqual({ permission_ceiling: "ask" }));+ });++ test("a stricter approval mode saves without a confirmation", async () => {+ renderTab({ approvalMode: "bypass" });+ const modes = await screen.findByTestId("agent-pane-approval-mode");+ fireEvent.click(within(modes).getByText("Always ask"));+ fireEvent.click(screen.getByTestId("agent-pane-save"));+ await waitFor(() => expect(patchBody()).toEqual({ approval_mode: "always_ask" }));+ expect(screen.queryByTestId("agent-pane-widen")).toBeNull();});test("an empty budget means no cap rather than a broken number", async () => {- renderCard();- fireEvent.click(await screen.findByTestId("agent-limits-edit"));- fireEvent.change(screen.getByTestId("agent-budget-input"), { target: { value: "" } });- fireEvent.click(screen.getByText("Save"));-- await waitFor(() => {- const patch = fetchMock.mock.calls.find((c) => c[1]?.method === "PATCH");- expect(JSON.parse(String(patch?.[1]?.body)).daily_budget_usd).toBe(0);- });+ renderTab();+ fireEvent.change(await screen.findByTestId("agent-budget-input"), { target: { value: "" } });+ fireEvent.click(screen.getByTestId("agent-pane-save"));+ await waitFor(() => expect(patchBody().daily_budget_usd).toBe(0));});test("switching the cap off sends 0, which is the scheduler's no-cap", async () => {- renderCard();- fireEvent.click(await screen.findByTestId("agent-limits-edit"));- fireEvent.click(screen.getByTestId("agent-budget-switch"));+ renderTab();+ fireEvent.click(await screen.findByTestId("agent-budget-switch"));expect(screen.queryByTestId("agent-budget-input")).toBeNull();- fireEvent.click(screen.getByText("Save"));-- await waitFor(() => {- const patch = fetchMock.mock.calls.find((c) => c[1]?.method === "PATCH");- expect(JSON.parse(String(patch?.[1]?.body)).daily_budget_usd).toBe(0);- });+ fireEvent.click(screen.getByTestId("agent-pane-save"));+ await waitFor(() => expect(patchBody()).toEqual({ daily_budget_usd: 0 }));});test("a stored 0 reads as the cap switched off, and turning it on restores a number", async () => {- renderCard({ dailyBudgetUsd: 0 });- await waitFor(() => expect(screen.getByTestId("agent-limits-edit")).toBeTruthy());- expect(screen.getByTestId("agent-card-sheet").textContent).toContain("no cap");-- fireEvent.click(screen.getByTestId("agent-limits-edit"));- expect(screen.getByTestId("agent-budget-switch").getAttribute("aria-checked")).toBe("false");+ renderTab({ dailyBudgetUsd: 0 });+ const toggle = await screen.findByTestId("agent-budget-switch");+ expect(toggle.getAttribute("aria-checked")).toBe("false");expect(screen.queryByTestId("agent-budget-input")).toBeNull();-- fireEvent.click(screen.getByTestId("agent-budget-switch"));+ fireEvent.click(toggle);expect(screen.getByTestId("agent-budget-input")).toBeTruthy();- fireEvent.click(screen.getByText("Save"));+ fireEvent.click(screen.getByTestId("agent-pane-save"));+ await waitFor(() => expect(patchBody()).toEqual({ daily_budget_usd: 2 }));+ });- await waitFor(() => {- const patch = fetchMock.mock.calls.find((c) => c[1]?.method === "PATCH");- expect(JSON.parse(String(patch?.[1]?.body)).daily_budget_usd).toBe(2);- });+ test("after a save, a later change to the agent is adopted rather than shadowed by a stale draft", async () => {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });+ const tree = (agent: SocietyAgent) => (+ <QueryClientProvider client={client}>+ <ToolsTab agent={agent} sample={false} />+ </QueryClientProvider>+ );+ // The server stores sets sorted: the saved row lists the sites in another order.+ const view = render(tree(AGENT));+ const sites = await screen.findByTestId("agent-pane-sites");+ for (const site of ["zeta.example", "alpha.example"]) {+ fireEvent.change(within(sites).getByRole("textbox"), { target: { value: site } });+ fireEvent.keyDown(within(sites).getByRole("textbox"), { key: "Enter" });+ }+ fireEvent.click(screen.getByTestId("agent-pane-save"));+ await waitFor(() => expect(patchBody()).toEqual({ browser_allowed_domains: ["zeta.example", "alpha.example"] }));+ const saved: SocietyAgent = { ...AGENT, browserAllowedDomains: ["alpha.example", "zeta.example"] };+ view.rerender(tree(saved));+ await waitFor(() => expect(screen.queryByTestId("agent-pane-savebar")).toBeNull());+ // An approved proposal then moves the budget: the tab shows it, with nothing "unsaved".+ view.rerender(tree({ ...saved, dailyBudgetUsd: 5 }));+ await waitFor(() => expect((screen.getByTestId("agent-budget-input") as HTMLInputElement).value).toBe("5"));+ expect(screen.queryByTestId("agent-pane-savebar")).toBeNull();+ });++ test("Discard returns every field to the saved value", async () => {+ renderTab();+ const input = (await screen.findByTestId("agent-budget-input")) as HTMLInputElement;+ fireEvent.change(input, { target: { value: "9" } });+ fireEvent.click(await screen.findByText("Discard"));+ expect((screen.getByTestId("agent-budget-input") as HTMLInputElement).value).toBe("2");+ expect(screen.queryByTestId("agent-pane-savebar")).toBeNull();});});diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentSandboxSection.test.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentSandboxSection.test.tsxindex 893600248f..d2e40a0f9f 100644--- a/dodaios/ui/web/frontend/src/components/society/card/AgentSandboxSection.test.tsx+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentSandboxSection.test.tsx@@ -48,3 +48,21 @@ test("rejected environment selection keeps the saved environment", async () => {method: "PATCH", body: JSON.stringify({ execution_environment: "sandbox" }),}));});++test("leaving the sandbox asks before the agent gets this computer back", async () => {+ const fetcher = vi.fn(async (url: string, _init?: RequestInit) => new Response(JSON.stringify(+ url === "/api/society/sandbox" ? { available: true } : { files: [] },+ )));+ vi.stubGlobal("fetch", fetcher);+ render(<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>+ <AgentSandboxSection agent={agent} show="choice" />+ </QueryClientProvider>);+ fireEvent.click(screen.getByRole("combobox"));+ fireEvent.click(await screen.findByRole("option", { name: "society.sandbox.local" }));+ expect(await screen.findByTestId("agent-sandbox-confirm-local")).toBeTruthy();+ expect(fetcher.mock.calls.some(([, init]) => (init as RequestInit | undefined)?.method === "PATCH")).toBe(false);+ fireEvent.click(screen.getByTestId("agent-sandbox-confirm-local-yes"));+ await waitFor(() => expect(fetcher).toHaveBeenCalledWith("/api/society/agents/sandbox-user", expect.objectContaining({+ method: "PATCH", body: JSON.stringify({ execution_environment: "local" }),+ })));+});diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentSandboxSection.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentSandboxSection.tsxindex 0a4b109c34..c762a674f2 100644--- a/dodaios/ui/web/frontend/src/components/society/card/AgentSandboxSection.tsx+++ b/dodaios/ui/web/frontend/src/components/society/card/AgentSandboxSection.tsx@@ -30,21 +30,29 @@ export function SandboxChoice({ value, onChange, disabled = false }: {</div>;}-export function AgentSandboxSection({ agent }: { agent: SocietyAgent }) {+/**+ * `choice` is the environment picker alone (the agent pane's placement+ * section), `files` the sandbox file browser alone (its Files page), `all`+ * both, as the create dialog and older surfaces use it.+ */+export function AgentSandboxSection({ agent, show = "all" }: { agent: SocietyAgent; show?: "all" | "choice" | "files" }) {const t = useT();const client = useQueryClient();const [error, setError] = useState("");const [busy, setBusy] = useState(false);const [path, setPath] = useState(".");+ // Leaving the sandbox gives the agent this computer's files, shell and+ // network back: that widening asks once before it is saved.+ const [confirmLocal, setConfirmLocal] = useState(false);const enabled = agent.executionEnvironment === "sandbox";const base = `/api/society/agents/${encodeURIComponent(agent.agentId)}/sandbox`;const ready = useQuery({- queryKey: ["society", "sandbox", "status"], enabled, retry: false,+ queryKey: ["society", "sandbox", "status"], enabled: enabled && show !== "choice", retry: false,queryFn: () => json<{ available: boolean; needs_image: boolean; message: string }>("/api/society/sandbox"),});const files = useQuery({queryKey: ["society", "sandbox", agent.agentId, path],- enabled: enabled && ready.data?.available === true, retry: false,+ enabled: enabled && show !== "choice" && ready.data?.available === true, retry: false,queryFn: () => json<{ files: { name: string; directory: boolean }[] }>(`${base}/files?path=${encodeURIComponent(path)}`),});async function perform(work: () => Promise<unknown>) {@@ -52,16 +60,28 @@ export function AgentSandboxSection({ agent }: { agent: SocietyAgent }) {try { await work(); } catch (exc) { setError(exc instanceof Error ? exc.message : String(exc)); }finally { setBusy(false); }}+ const place = (value: "local" | "sandbox") => void perform(async () => {+ setConfirmLocal(false);+ await json(`/api/society/agents/${encodeURIComponent(agent.agentId)}`, {+ method: "PATCH", headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ execution_environment: value }),+ });+ await client.invalidateQueries({ queryKey: ["society", "roster"] });+ });return <section className="flex flex-col gap-3" data-testid="agent-sandbox">- <SandboxChoice value={enabled ? "sandbox" : "local"} disabled={busy || agent.runtime !== "jarvis" && !!agent.runtime}- onChange={(value) => void perform(async () => {- await json(`/api/society/agents/${encodeURIComponent(agent.agentId)}`, {- method: "PATCH", headers: { "Content-Type": "application/json" },- body: JSON.stringify({ execution_environment: value }),- });- await client.invalidateQueries({ queryKey: ["society", "roster"] });- })} />- {enabled ? <>+ {show !== "files" ? <SandboxChoice value={enabled ? "sandbox" : "local"} disabled={busy || agent.runtime !== "jarvis" && !!agent.runtime}+ onChange={(value) => {+ if (enabled && value === "local") setConfirmLocal(true);+ else place(value);+ }} /> : null}+ {confirmLocal ? <div role="alertdialog" aria-label={t("society.agent_pane.leave_sandbox")} className="flex flex-col gap-2 rounded-lg border border-warning p-3 text-xs" data-testid="agent-sandbox-confirm-local">+ <p className="text-foreground">{t("society.agent_pane.leave_sandbox_body")}</p>+ <div className="flex justify-end gap-2">+ <Button size="sm" variant="ghost" onClick={() => setConfirmLocal(false)}>{t("society.agent_pane.go_back")}</Button>+ <Button size="sm" onClick={() => place("local")} data-testid="agent-sandbox-confirm-local-yes">{t("society.agent_pane.allow_and_save")}</Button>+ </div>+ </div> : null}+ {enabled && show !== "choice" ? <><p className="text-xs text-muted-foreground">{t("society.sandbox.storage")}</p>{ready.isLoading ? <p role="status">{t("society.sandbox.checking")}</p> : null}{ready.data?.message ? <p role="status" className="text-xs">{ready.data.message}</p> : null}diff --git a/dodaios/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsx b/dodaios/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsxdeleted file mode 100644index 27743ed0e0..0000000000--- a/dodaios/ui/web/frontend/src/components/society/card/AgentSpecSheet.tsx+++ /dev/null@@ -1,868 +0,0 @@-/**- * The model card's spec column — a champion card of the island.- *- * It used to be a stack of grey headings whose most important line read "No- * focus tools" above an empty list: `GRANTED TOOLS` only ever filled for an- * allow-list agent, and almost every agent runs `grant_mode = all`. So the- * card said nothing about the one thing that makes a Gmail agent a Gmail- * agent.- *- * It now leads with HANDS — what this agent reaches for first, as tiles- * carrying the services' real marks — and says in one quiet line that- * everything else stays in reach, because it does (agent-definition §3.2).- *- * TWO RULES this file exists to keep (maintainer, 2026-09-03):- *- * 1. Nothing on the card is decoration. Every value shown is one a part of- * the system actually reads: the ceiling decides approvals- * (`society/approvals.decide`), the daily budget stops a dispatch- * (`society/scheduler`, which is why today's spend is drawn against it- * rather than the lifetime total), `max_concurrent_runs` caps runs in- * flight, focus orders the tool list. The one control that did nothing —- * "Assign task", disabled since it shipped — is gone rather than greyed.- * 2. Nothing is empty because nobody asked. Routines, learned skills and the- * activity log come from routes that existed all along and that no- * frontend file was calling (`../cardData.ts`).- *- * The skin is in `agentCard.css`: the island's shape, the app's colours.- * Jarvis keeps its two special sections — its brain is the app's chat brain- * and its orders are the user's own instructions file.- *- * Every string goes through the locale files.- */-import { useMemo, useState } from "react";-import { useQuery } from "@tanstack/react-query";-import { MessageSquare, Pause, Play, Server } from "lucide-react";--import { ProviderLogo } from "@/components/providers/ProviderLogo";-import { ScrollArea } from "@/components/ui/scroll-area";-import { Switch } from "@/components/ui/switch";-import { useT } from "@/i18n";-import { useRunLocale } from "@/components/runs/format";-import { useComputers } from "@/hooks/useComputers";-import { societyDisplayName } from "@/lib/societyDisplayName";-import { cn } from "@/lib/utils";-import { useEventStore } from "@/store/events";--import { AgentRoutinesList } from "./AgentRoutinesList";-import { AgentSandboxSection } from "./AgentSandboxSection";-import { RetireButton } from "./RetireButton";-import { CapabilityChip } from "../CapabilityChip";-import { useAgentActivity, useAgentSkills, type AgentActivity } from "../cardData";-import { AGENT_APPROVAL_MODES, PERMISSION_CEILINGS, fetchSocietyProviders, type AgentApprovalMode } from "@/lib/societyApi";--import {- useSetAgentComputer,- useSetAgentPaused,- useSocietyCapabilities,- useUpdateAgentDescription,- useUpdateAgentLimits,- type AgentRunState,- type Capability,- type PermissionCeiling,- type SocietyAgent,-} from "../data";-import { CapabilityTile } from "./CapabilityTile";-import { ComputerPicker } from "../create/ComputerPicker";-import { LeadBrain, LeadInstructions } from "./LeadSections";--import "./agentCard.css";-import { BuiltByBadge } from "@/components/selfBuild/BuiltByBadge";--/** How far up the three-step ladder a ceiling sits. `block` never reaches a card. */-const CEILING_STEP: Record<PermissionCeiling, number> = { safe: 1, monitor: 2, ask: 3 };--/** The state dot's fill — the same three status jobs the rest of the app uses. */-const STATE_FILL: Record<AgentRunState, string> = {- idle: "bg-muted-foreground/40",- working: "bg-success",- waiting: "bg-warning",- paused: "bg-muted-foreground/25",-};--const REACH_STEPS = 6;-/** More rows than this and the log stops being a glance. */-const LOG_ROWS = 6;--/**- * The agent's standing instructions, editable in place. Rules mostly arrive- * through the chat (the agent proposes, the person confirms), but a person may- * also write them directly; the PATCH sends the description alone and the route- * keeps the focus and approval rules the agent earned.- */-function DescriptionEditor({ agent }: { agent: SocietyAgent }) {- const t = useT();- const update = useUpdateAgentDescription();- const [editing, setEditing] = useState(false);- const [draft, setDraft] = useState(agent.description);- const [saving, setSaving] = useState(false);- const [error, setError] = useState("");- const begin = () => {- setDraft(agent.description);- setError("");- setEditing(true);- };- const save = async () => {- setSaving(true);- setError("");- try {- await update(agent, draft.trim());- setEditing(false);- } catch (err) {- setError(err instanceof Error ? err.message : String(err));- } finally {- setSaving(false);- }- };- return (- <>- <div className="mb-2 flex items-center justify-between gap-2">- <h3 className="ac-head">{t("society.card.description")}</h3>- {editing ? null : (- <button- type="button"- onClick={begin}- className="rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground"- >- {t("society.card.edit")}- </button>- )}- </div>- {editing ? (- <div className="flex flex-col gap-2">- <textarea- value={draft}- onChange={(e) => setDraft(e.target.value)}- rows={Math.min(14, Math.max(4, draft.split(/\r?\n/).length + 1))}- disabled={saving}- className="w-full resize-y rounded-md border border-border bg-background px-2.5 py-2 text-sm leading-relaxed text-foreground outline-none focus:border-primary"- />- <div className="flex items-center gap-2">- <button- type="button"- disabled={saving}- onClick={() => void save()}- className="rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50"- >- {saving ? t("society.card.saving") : t("society.card.save")}- </button>- <button- type="button"- disabled={saving}- onClick={() => setEditing(false)}- className="rounded-md border border-border px-2.5 py-1 text-xs font-medium text-foreground hover:bg-muted disabled:opacity-50"- >- {t("society.card.cancel")}- </button>- {error ? <span className="text-xs text-destructive">{error}</span> : null}- </div>- </div>- ) : agent.description ? (- <p className="whitespace-pre-line text-sm leading-relaxed">{agent.description}</p>- ) : (- <p className="text-xs text-muted-foreground">{t("society.card.no_description")}</p>- )}- </>- );-}--function formatDate(ms: number | null, fallback: string, locale: string): string {- if (ms === null) return fallback;- return new Date(ms).toLocaleDateString(locale, { day: "2-digit", month: "short", year: "numeric" });-}--/** "in 3 h", "in 2 d", "now" — from an epoch in ms. */-function untilLabel(ms: number, t: (key: string) => string): string {- const delta = ms - Date.now();- if (delta <= 60_000) return t("society.card.due_now");- const minutes = Math.round(delta / 60_000);- if (minutes < 60) return t("society.card.due_in").replace("{0}", `${minutes} min`);- const hours = Math.round(minutes / 60);- if (hours < 48) return t("society.card.due_in").replace("{0}", `${hours} h`);- return t("society.card.due_in").replace("{0}", `${Math.round(hours / 24)} d`);-}--export function relativeUntil(iso: string | null, t: (key: string) => string): string | null {- if (!iso) return null;- const ms = Date.parse(iso);- return Number.isNaN(ms) ? null : untilLabel(ms, t);-}--/** "2 min ago", "3 h ago" — the past half of the same ladder. */-function agoLabel(ms: number, t: (key: string) => string): string {- const delta = Date.now() - ms;- if (delta < 60_000) return t("society.card.just_now");- const minutes = Math.round(delta / 60_000);- const unit =- minutes < 60- ? `${minutes} min`- : minutes < 2880- ? `${Math.round(minutes / 60)} h`- : `${Math.round(minutes / 1440)} d`;- return t("society.card.ago").replace("{0}", unit);-}--export interface AgentSpecSheetProps {- agent: SocietyAgent;- /**- * Hands the card back to its chat. The profile is the card's second face,- * so "Chat" here is a real way back rather than the placeholder it was- * while the chat had no place of its own.- */- onOpenChat?: () => void;- /**- * The agent was retired: the card closes so the island's ceremony- * (`world/retirement.ts`) is actually visible behind it.- */- onRetired?: () => void;-}--export function AgentSpecSheet({ agent, onOpenChat, onRetired }: AgentSpecSheetProps) {- const t = useT();- const locale = useRunLocale();- const assistantName = useEventStore((s) => s.assistantName);- const displayName = societyDisplayName(agent, assistantName);- const capabilities = useSocietyCapabilities();- const activity = useAgentActivity(agent.agentId);- const skills = useAgentSkills(agent.agentId);- const setPaused = useSetAgentPaused();- const computers = useComputers();- const remoteComputer = agent.computerId- ? (computers.data ?? []).find((c) => c.id === agent.computerId) ?? null- : null;- const [busy, setBusy] = useState(false);- const byId = useMemo(() => {- const map = new Map<string, Capability>();- for (const c of capabilities.data ?? []) map.set(c.id, c);- return map;- }, [capabilities.data]);-- // The catalog is optional enrichment: the query does not retry, and a card- // with no catalog still names every tool through the brand resolver. What- // it must NOT do is print a total it does not have.- const catalogSize = capabilities.data?.length ?? 0;- const allowlist = agent.grantMode === "allowlist";-- /** What the agent reaches for first — its allow-list is its hands when it has no focus. */- const hands = agent.focus.length > 0 ? agent.focus : allowlist ? agent.toolGrants : [];- const paused = agent.lifecycle === "paused" || agent.state === "paused";-- const reachFilled = allowlist- ? Math.max(1, Math.round((agent.toolGrants.length / Math.max(catalogSize, 1)) * REACH_STEPS))- : REACH_STEPS;- const reachValue = allowlist- ? t("society.card.reach_allowlist")- .replace("{0}", String(agent.toolGrants.length))- .replace("{1}", String(catalogSize))- : t("society.card.reach_all");-- // The budget is a real gate, so it is drawn as one: today's spend against- // the cap the scheduler refuses at. A cap of 0 means "no cap" there, so it- // means "no cap" here too rather than a bar that is always full.- const capped = agent.dailyBudgetUsd > 0;- const spentToday = agent.stats.spentTodayUsd;- const spentShare = capped ? Math.min(1, spentToday / agent.dailyBudgetUsd) : 0;- const exhausted = capped && spentToday >= agent.dailyBudgetUsd;-- const log = (activity.data?.events ?? []).slice(0, LOG_ROWS);- const activeRuns = activity.data?.activeRuns ?? 0;- const learned = skills.data ?? [];-- const togglePause = async () => {- setBusy(true);- try {- await setPaused(agent, !paused);- } finally {- setBusy(false);- }- };-- return (- <div className="ac-card" data-testid="agent-card-sheet">- <header className="ac-band" data-tier={agent.tier}>- <span className="min-w-0 flex-1">- <span className="ac-band-name block truncate">{displayName}</span>- {/* Jarvis' title IS "Lead", so the tier would otherwise read twice. */}- <span className="ac-band-title block truncate">- {[t(`society.tier.${agent.tier}`), agent.title]- .filter((part, i, all) => part && all.indexOf(part) === i)- .join(" · ")}- </span>- </span>- {remoteComputer ? (- <span- data-testid="agent-remote-badge"- title={t("society.card.runs_on_badge").replace("{computer}", remoteComputer.name)}- className="inline-flex max-w-[40%] shrink-0 items-center gap-1 rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground"- >- <Server className="h-3 w-3 shrink-0" aria-hidden />- <span className="truncate">{remoteComputer.name}</span>- </span>- ) : null}- <BuiltByBadge type="agent" id={agent.agentId} />- <span className={cn("ac-dot", STATE_FILL[agent.state])} data-state={agent.state} aria-hidden />- <span className="shrink-0 text-xs text-muted-foreground">- {activeRuns > 0- ? t("society.card.active_runs").replace("{0}", String(activeRuns))- : t(`society.state.${agent.state}`)}- </span>- </header>-- <ScrollArea className="min-h-0 flex-1">- <div className="flex flex-col gap-5 p-5">- <section>- <h3 className="ac-head mb-2.5">{t("society.card.hands")}</h3>- {hands.length === 0 ? (- <p className="ac-prose text-xs leading-relaxed text-muted-foreground">- {t("society.card.hands_empty")}- </p>- ) : (- <ul className="flex flex-wrap gap-3">- {hands.map((id) => (- <CapabilityTile- key={id}- id={id}- capability={byId.get(id)}- palette={agent.palette}- disconnectedHint={t("society.card.not_connected")}- />- ))}- </ul>- )}- <p className="ac-prose mt-3 text-xs leading-relaxed text-muted-foreground">- {allowlist- ? t("society.card.hands_rest_allowlist")- : catalogSize > 0- ? t("society.card.hands_rest").replace("{0}", String(catalogSize))- : t("society.card.hands_rest_plain")}- </p>- {agent.denies.length > 0 ? (- <div className="mt-3">- <p className="ac-prose mb-1.5 text-xs text-muted-foreground">{t("society.card.denied")}</p>- <div className="flex flex-wrap gap-1.5">- {agent.denies.map((id) => (- <CapabilityChip key={id} id={id} capability={byId.get(id)} className="line-through opacity-60" />- ))}- </div>- </div>- ) : null}- </section>-- {learned.length > 0 ? (- <section>- <h3 className="ac-head mb-2.5">{t("society.card.learned")}</h3>- <ul className="flex flex-wrap gap-3">- {learned.map((skill) => (- <CapabilityTile- key={skill.slug}- id={`skill:${skill.slug}`}- capability={{- id: `skill:${skill.slug}`,- kind: "skill",- label: skill.name,- one_liner: skill.whenToUse || skill.description,- risk_tier: "safe",- connected: true,- tool_name: "",- }}- palette={agent.palette}- />- ))}- </ul>- </section>- ) : null}-- {agent.tier !== "lead" && <AgentSandboxSection agent={agent} />}- {agent.tier !== "lead" && agent.executionEnvironment !== "sandbox" && <RunsOnSection agent={agent} />}-- <LimitsSection- agent={agent}- reachFilled={reachFilled}- reachValue={reachValue}- spentToday={spentToday}- spentShare={spentShare}- capped={capped}- exhausted={exhausted}- />-- <section className="grid grid-cols-2 gap-2">- <Plate label={t("society.card.place")} value={t(`society.checkpoint.${agent.checkpoint}`)} />- <Plate label={t("society.card.created")} value={formatDate(agent.createdMs, "—", locale)} />- </section>-- <section>- <h3 className="ac-head mb-2">{t("society.card.brain")}</h3>- {agent.tier === "lead" ? (- <LeadBrain />- ) : (- <div className="flex flex-wrap items-center gap-2 text-sm">- {agent.provider ? (- <span className="inline-flex items-center gap-1.5">- <ProviderLogo- providerId={agent.provider}- label={agent.providerLabel || agent.provider}- size="sm"- />- <span className="font-medium">{agent.providerLabel || agent.provider}</span>- </span>- ) : (- <span className="font-medium">{t("society.card.default_brain")}</span>- )}- {agent.model ? <span className="ac-prose font-mono text-xs">{agent.model}</span> : null}- {agent.effort ? <span className="text-xs text-muted-foreground">{agent.effort}</span> : null}- </div>- )}- </section>-- <section className="ac-prose">- {agent.tier === "lead" ? <LeadInstructions /> : <DescriptionEditor agent={agent} />}- </section>-- {agent.approvalRules.requireApproval.length > 0 || agent.approvalRules.alwaysAllow.length > 0 ? (- <section>- <h3 className="ac-head mb-2">{t("society.card.approval_rules")}</h3>- {agent.approvalRules.requireApproval.length > 0 ? (- <RuleRow label={t("society.card.require_approval")} ids={agent.approvalRules.requireApproval} byId={byId} />- ) : null}- {agent.approvalRules.alwaysAllow.length > 0 ? (- <RuleRow label={t("society.card.always_allow")} ids={agent.approvalRules.alwaysAllow} byId={byId} />- ) : null}- </section>- ) : null}-- <AgentRoutinesList- agentId={agent.agentId}- sampleRoutines={agent.routines}- variant="sheet"- />-- <section>- <h3 className="ac-head mb-2">{t("society.card.recent")}</h3>- {log.length === 0 ? (- <p className="ac-prose text-xs text-muted-foreground">{t("society.card.no_recent")}</p>- ) : (- <div className="ac-log">- {log.map((row) => (- <LogRow key={row.id} row={row} agentId={agent.agentId} t={t} />- ))}- </div>- )}- </section>-- <section>- <h3 className="ac-head mb-2">{t("society.card.record")}</h3>- <div className="grid grid-cols-3 gap-2">- <Plate label={t("society.card.runs")} value={String(agent.stats.runs)} />- <Plate label={t("society.card.cost")} value={`$${agent.stats.totalCostUsd.toFixed(2)}`} />- <Plate- label={t("society.card.last_active")}- value={formatDate(agent.stats.lastActiveMs, t("society.card.never"), locale)}- />- </div>- </section>-- {agent.workspaceDir || agent.wikiNamespace ? (- <section>- <h3 className="ac-head mb-2">{t("society.card.where")}</h3>- <div className="grid grid-cols-2 gap-2">- {agent.workspaceDir ? (- <Plate label={t("society.card.workspace")} value={agent.workspaceDir} mono />- ) : null}- {agent.wikiNamespace ? (- <Plate label={t("society.card.wiki")} value={agent.wikiNamespace} mono />- ) : null}- </div>- </section>- ) : null}- </div>- </ScrollArea>-- <div className="ac-actions">- <button- type="button"- className="ac-btn"- disabled={!onOpenChat}- title={onOpenChat ? undefined : t("society.card.chat_soon")}- onClick={onOpenChat}- >- <MessageSquare className="h-3.5 w-3.5" aria-hidden />- {t("society.card.action_chat")}- </button>- <button type="button" className="ac-btn ml-auto" disabled={busy} onClick={() => void togglePause()}>- {paused ? <Play className="h-3.5 w-3.5" aria-hidden /> : <Pause className="h-3.5 w-3.5" aria-hidden />}- {paused ? t("society.card.action_resume") : t("society.card.action_pause")}- </button>- {/* Last, and on its own: pausing is a Tuesday, retiring is forever. */}- <RetireButton agent={agent} onRetired={onRetired} />- </div>- </div>- );-}--/**- * The three knobs a person may turn after the agent exists, plus the reach- * they cannot (that one follows the grant mode).- *- * All three are enforced somewhere — the budget stops a dispatch, the ceiling- * decides what runs without asking, the concurrency caps runs in flight — and- * until now they could be set only once, at creation, behind the Advanced- * disclosure, and never again (maintainer, 2026-09-03). Read mode is the- * meters as before; Edit turns the same rows into controls and PATCHes the- * three together.- */-function LimitsSection({- agent,- reachFilled,- reachValue,- spentToday,- spentShare,- capped,- exhausted,-}: {- agent: SocietyAgent;- reachFilled: number;- reachValue: string;- spentToday: number;- spentShare: number;- capped: boolean;- exhausted: boolean;-}) {- const t = useT();- const update = useUpdateAgentLimits();- const [editing, setEditing] = useState(false);- const [saving, setSaving] = useState(false);- const [error, setError] = useState("");- const [ceiling, setCeiling] = useState<PermissionCeiling>(agent.permissionCeiling);- const [approvalMode, setApprovalMode] = useState<AgentApprovalMode | null>(agent.approvalMode ?? null);- const providerRows = useQuery({ queryKey: ["society", "providers"], queryFn: fetchSocietyProviders });- const runner = providerRows.data?.find((row) => row.id === agent.provider)?.runner;- const [budget, setBudget] = useState(String(agent.dailyBudgetUsd));- // The stored 0 IS 'no cap' (the scheduler skips the gate), so the switch- // reads it back rather than asking the person to know that.- const [budgetOn, setBudgetOn] = useState(agent.dailyBudgetUsd > 0);- const [jobs, setJobs] = useState(String(agent.maxConcurrentRuns));-- const begin = () => {- setCeiling(agent.permissionCeiling);- setApprovalMode(agent.approvalMode ?? null);- setBudget(String(agent.dailyBudgetUsd || 2));- setBudgetOn(agent.dailyBudgetUsd > 0);- setJobs(String(agent.maxConcurrentRuns));- setError("");- setEditing(true);- };- const save = async () => {- setSaving(true);- setError("");- try {- await update(agent, {- permissionCeiling: ceiling,- approvalMode,- dailyBudgetUsd: budgetOn ? Math.max(0, Number.parseFloat(budget) || 0) : 0,- maxConcurrentRuns: Number.parseInt(jobs, 10) || 1,- });- setEditing(false);- } catch (err) {- setError(err instanceof Error ? err.message : String(err));- } finally {- setSaving(false);- }- };-- return (- <section className="flex flex-col gap-2">- <div className="mb-0.5 flex items-center justify-between gap-2">- <h3 className="ac-head">{t("society.card.limits")}</h3>- {editing ? null : (- <button- type="button"- onClick={begin}- data-testid="agent-limits-edit"- className="rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground"- >- {t("society.card.edit")}- </button>- )}- </div>-- {editing ? (- <div className="ac-prose flex flex-col gap-3">- {agent.tier !== "lead" && <div className="flex flex-col gap-1">- <span className="text-xs text-muted-foreground">{t("society.approval_mode.title")}</span>- <div className="flex flex-wrap gap-1">- {AGENT_APPROVAL_MODES.map((mode) => {- const unknownRunner = Boolean(agent.provider) && runner == null;- const unavailable = mode === "always_ask"- ? unknownRunner || (runner != null && runner !== "codex-cli" && runner !== "brain")- : mode === "ask" && (unknownRunner || (runner != null- && !["codex-cli", "claude-cli", "glm-cli", "brain"].includes(runner)));- return <button- key={mode}- type="button"- disabled={saving || unavailable}- title={unavailable ? t("society.approval_mode.unavailable") : t(`society.approval_mode.${mode}_hint`)}- onClick={() => setApprovalMode(mode)}- aria-pressed={approvalMode === mode}- className={cn(- "rounded-md border px-2.5 py-1 text-xs transition-colors disabled:opacity-50",- approvalMode === mode- ? "border-border-strong bg-secondary text-foreground"- : "border-border text-muted-foreground hover:bg-secondary",- )}- >{t(`society.approval_mode.${mode}`)}</button>;- })}- </div>- <p className="text-xs text-muted-foreground">- {approvalMode ? t(`society.approval_mode.${approvalMode}_hint`) : t("society.approval_mode.legacy_hint")}- </p>- </div>}- {(agent.tier === "lead" || !agent.approvalMode) && <div className="flex flex-col gap-1">- <span className="text-xs text-muted-foreground">{t("society.approval_mode.legacy_ceiling")}</span>- <div className="flex flex-wrap gap-1">- {PERMISSION_CEILINGS.map((step) => (- <button- key={step}- type="button"- disabled={saving}- onClick={() => setCeiling(step)}- aria-pressed={ceiling === step}- className={cn(- "rounded-md border px-2.5 py-1 text-xs transition-colors disabled:opacity-50",- ceiling === step- ? "border-border-strong bg-secondary text-foreground"- : "border-border text-muted-foreground hover:bg-secondary",- )}- >- {t(`society.ceiling.${step}`)}- </button>- ))}- </div>- </div>}-- <div className="flex flex-wrap items-end gap-4">- <div className="flex flex-col gap-1">- <span className="flex items-center gap-2 text-xs text-muted-foreground">- <Switch- checked={budgetOn}- onCheckedChange={setBudgetOn}- disabled={saving}- aria-label={t("society.card.budget_cap")}- data-testid="agent-budget-switch"- />- {t("society.card.budget_cap")}- </span>- {budgetOn ? (- <input- type="number"- min={0}- step={0.5}- inputMode="decimal"- disabled={saving}- value={budget}- onChange={(e) => setBudget(e.target.value)}- data-testid="agent-budget-input"- className="w-28 rounded-md border border-border bg-background px-2 py-1 font-mono text-sm text-foreground outline-none focus:border-primary disabled:opacity-50"- />- ) : (- <span className="py-1 text-sm text-muted-foreground">{t("society.card.no_cap")}</span>- )}- </div>- <label className="flex flex-col gap-1">- <span className="text-xs text-muted-foreground">{t("society.card.jobs_at_once")}</span>- <input- type="number"- min={1}- step={1}- inputMode="numeric"- disabled={saving}- value={jobs}- onChange={(e) => setJobs(e.target.value)}- className="w-20 rounded-md border border-border bg-background px-2 py-1 font-mono text-sm text-foreground outline-none focus:border-primary disabled:opacity-50"- />- </label>- </div>- <p className="text-xs text-muted-foreground">- {budgetOn ? t("society.card.budget_hint") : t("society.card.budget_off_hint")}- </p>-- <div className="flex items-center gap-2">- <button- type="button"- disabled={saving}- onClick={() => void save()}- className="rounded-md bg-primary px-2.5 py-1 text-xs font-medium text-primary-foreground hover:bg-primary/90 disabled:opacity-50"- >- {saving ? t("society.card.saving") : t("society.card.save")}- </button>- <button- type="button"- disabled={saving}- onClick={() => setEditing(false)}- className="rounded-md border border-border px-2.5 py-1 text-xs font-medium text-foreground hover:bg-muted disabled:opacity-50"- >- {t("society.card.cancel")}- </button>- {error ? <span className="text-xs text-destructive">{error}</span> : null}- </div>- </div>- ) : (- <>- {agent.tier !== "lead" && agent.approvalMode ? (- <div className="text-xs text-muted-foreground">- {t("society.approval_mode.title")}: <span className="text-foreground">{t(`society.approval_mode.${agent.approvalMode}`)}</span>- </div>- ) : (- <StepMeter- label={t("society.approval_mode.legacy_ceiling")}- steps={3}- filled={CEILING_STEP[agent.permissionCeiling] ?? 0}- value={t(`society.ceiling.${agent.permissionCeiling}`)}- />- )}- <StepMeter- label={t("society.card.meter_reach")}- steps={REACH_STEPS}- filled={reachFilled}- value={reachValue}- />- <div className="ac-meter">- <span className="ac-meter-label">{t("society.card.meter_today")}</span>- <span- className="ac-meter-bar"- data-spent={exhausted ? "1" : "0"}- role="img"- aria-label={`${t("society.card.meter_today")}: $${spentToday.toFixed(2)}`}- >- <span className="ac-meter-fill" style={{ width: `${Math.round(spentShare * 100)}%` }} />- </span>- <span className="ac-meter-value">- {capped- ? t("society.card.spent_of")- .replace("{0}", spentToday.toFixed(2))- .replace("{1}", agent.dailyBudgetUsd.toFixed(2))- : t("society.card.no_cap")}- </span>- </div>- <div className="ac-meter">- <span className="ac-meter-label">{t("society.card.jobs_at_once")}</span>- <span className="ac-meter-value">{agent.maxConcurrentRuns}</span>- </div>- </>- )}- </section>- );-}--/**- * A value on a short discrete ladder, drawn as filled notches. Only used for- * things that really are steps — the three permission ceilings, the share of- * the catalog an allow-list keeps — never for a number dressed up as one.- */-function StepMeter({- label,- steps,- filled,- value,-}: {- label: string;- steps: number;- filled: number;- value: string;-}) {- return (- <div className="ac-meter">- <span className="ac-meter-label">{label}</span>- <span className="ac-meter-track" role="img" aria-label={`${label}: ${value}`}>- {Array.from({ length: steps }, (_, i) => (- <span key={i} className="ac-meter-seg" data-on={i < filled ? "1" : "0"} />- ))}- </span>- <span className="ac-meter-value">{value}</span>- </div>- );-}--function Plate({ label, value, mono }: { label: string; value: string; mono?: boolean }) {- return (- <div className="ac-plate" title={value}>- <div className="ac-plate-label truncate">{label}</div>- <div className={cn("ac-plate-value truncate", mono && "ac-prose font-mono text-xs")}>{value}</div>- </div>- );-}--/**- * One line of the agent's own traffic. `events_for_agent` also carries the- * board's broadcasts, so `cardData` filters those out first — a row here is- * always something this agent sent or was sent.- */-function LogRow({- row,- agentId,- t,-}: {- row: AgentActivity;- agentId: string;- t: (key: string) => string;-}) {- const outgoing = row.fromAgent === agentId;- const what = outgoing- ? row.toAgent- ? t("society.card.log_to").replace("{0}", row.toAgent)- : t("society.card.log_board")- : t("society.card.log_from").replace("{0}", row.fromAgent ?? "?");- return (- <div className="ac-log-row">- <span className="ac-log-type">{row.type.toLowerCase()}</span>- <span className="ac-log-what truncate">- {what}- {row.costUsd > 0 ? ` · $${row.costUsd.toFixed(2)}` : ""}- </span>- <span className="ac-log-when">{row.tsMs ? agoLabel(row.tsMs, t) : ""}</span>- </div>- );-}--function RuleRow({ label, ids, byId }: { label: string; ids: string[]; byId: Map<string, Capability> }) {- return (- <div className="mb-2">- <p className="ac-prose mb-1 text-xs text-muted-foreground">{label}</p>- <div className="flex flex-wrap gap-1.5">- {ids.map((id) => (- <CapabilityChip key={id} id={id} capability={byId.get(id.split(":").slice(0, 2).join(":"))} />- ))}- </div>- </div>- );-}--/**- * Where the agent's work executes — this computer or a connected one. The- * change applies from the agent's next turn; a turn already running finishes- * where it started.- */-function RunsOnSection({ agent }: { agent: SocietyAgent }) {- const t = useT();- const setComputer = useSetAgentComputer();- const [saving, setSaving] = useState(false);- const [error, setError] = useState("");- return (- <section className="flex flex-col gap-2" data-testid="agent-runs-on">- <ComputerPicker- value={agent.computerId ?? ""}- labelClass="ac-head mb-1 block"- testId="agent-runs-on-picker"- onChange={(id) => {- if (saving || id === (agent.computerId ?? "")) return;- setSaving(true);- setError("");- setComputer(agent, id)- .catch((err: unknown) => setError(err instanceof Error ? err.message : String(err)))- .finally(() => setSaving(false));- }}- />- {error ? <p role="alert" className="text-xs text-destructive">{error}</p> : null}- {saving ? <p className="text-xs text-muted-foreground">{t("society.card.runs_on_saving")}</p> : null}- </section>- );-}diff --git a/dodaios/ui/web/frontend/src/components/society/card/OptionsRail.test.tsx b/dodaios/ui/web/frontend/src/components/society/card/OptionsRail.test.tsxindex d9a6673628..a3b4049b6d 100644--- a/dodaios/ui/web/frontend/src/components/society/card/OptionsRail.test.tsx+++ b/dodaios/ui/web/frontend/src/components/society/card/OptionsRail.test.tsx@@ -1,11 +1,15 @@/**- * The chat-face Options rail: preview + this agent's routines, Retire behind- * ⋯ (still two-press), and a switch of agent swaps both panes.+ * The agent pane beside the chat: tabs that persist, an Overview with the+ * six-part anatomy, in-pane drill-down with Back, the review queue with+ * "Review in chat", Retire behind ⋯ (still two-press), and a switch of agent+ * that swaps everything.*/import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { readComposerDraft, writeComposerDraft } from "@/components/agentchat/composerDrafts";+import { useSocietyChatStore } from "@/components/society/chat/AgentChatPanel";import { OptionsRail } from "@/components/society/card/OptionsRail";import { AgentChatLayout } from "./AgentChatLayout";import type { SocietyAgent } from "@/components/society/data";@@ -15,7 +19,7 @@ function agent(over: Partial<SocietyAgent> = {}): SocietyAgent {agentId: "gamil-agent",name: "Gamil agent",title: "Specialist",- description: "",+ description: "Look after the mail.",tier: "specialist",provider: "",providerLabel: "",@@ -34,7 +38,7 @@ function agent(over: Partial<SocietyAgent> = {}): SocietyAgent {state: "idle",lifecycle: "active",createdMs: 0,- chatSessionId: null,+ chatSessionId: "society:gamil-agent",routines: [],stats: { runs: 0, totalCostUsd: 0, spentTodayUsd: 0, lastActiveMs: null },...over,@@ -66,46 +70,77 @@ function json(body: unknown, status = 200) {} as Response;}+const QUEUE = {+ items: [+ {+ id: "proposal:p1",+ kind: "proposal",+ proposal_kind: "rule",+ summary: "Add a standing rule: Reply within a day.",+ reason: "You asked twice.",+ preview: ["+ Reply within a day."],+ created_ms: 1_788_000_000_000,+ },+ {+ id: "memory:7",+ kind: "memory",+ proposal_kind: "",+ summary: "The user prefers short replies.",+ reason: "",+ preview: ["+ The user prefers short replies."],+ book: "USER.md",+ created_ms: 1_787_000_000_000,+ },+ ],+ total: 2,+ counts: { proposal: 1, memory_share: 0, memory: 1 },+};+let fetchMock: ReturnType<typeof vi.fn>;-describe("OptionsRail", () => {+describe("OptionsRail (agent pane)", () => {beforeEach(() => {- fetchMock = vi.fn(async (url: string) => {+ window.localStorage.clear();+ fetchMock = vi.fn(async (url: string, init?: RequestInit) => {const path = String(url);if (path === "/api/tasks/gm1") {return json({ id: "gm1", title: "Inbox sweep", state: "scheduled", steps: [],spec: { action: { kind: "agent", prompt: "Read the inbox." } } });}+ if (path.includes("/review/") && init?.method === "POST") {+ return json({ id: "proposal:p1", outcome: "applied", detail: "" });+ }+ if (path.includes("/gamil-agent/review-queue")) return json(QUEUE);+ if (path.includes("/notes-agent/review-queue")) {+ return json({ items: [QUEUE.items[1]], total: 1, counts: { proposal: 0, memory_share: 0, memory: 1 } });+ }+ if (path.includes("/review-queue")) return json({ items: [], total: 0, counts: { proposal: 0, memory_share: 0, memory: 0 } });+ if (path.includes("/knowledge")) {+ return json({ files: [{ path: "memory/USER.md", name: "USER.md", kind: "memory", updated_ms: 1, size: 10 }],+ learned_instructions: ["Sign off with the user's first name."], reviews: { pending: 0, done: 1 }, last_review: null });+ }+ if (path.includes("/skills")) return json({ skills: [{ slug: "triage", name: "Inbox triage", when_to_use: "A full inbox." }] });+ if (path.includes("/capabilities")) {+ return json({ capabilities: [{ id: "plugin:gmail", kind: "plugin", label: "gmail", one_liner: "Mail", risk_tier: "monitor", connected: true, tool_name: "gmail" }] });+ }+ if (path.includes("/providers")) return json({ providers: [] });if (path.includes("/browser/status")) {return json({ installed: false, phase: "idle", percent: 0, running: false });}- if (path.includes("/gamil-agent/browser")) {- return json({ installed: false, mode: "own", logged_in_profile: false, running: false });- }- if (path.includes("/scout/browser")) {+ if (path.includes("/gamil-agent/browser") || path.includes("/scout/browser")) {return json({ installed: false, mode: "own", logged_in_profile: false, running: false });}if (path.includes("/gamil-agent/routines")) {return json({routines: [- {- id: "gm1",- title: "[agent:Gamil] Inbox sweep",- state: "scheduled",- trigger: { kind: "every", interval_seconds: 18_000 },- },+ { id: "gm1", title: "[agent:Gamil] Inbox sweep", state: "scheduled", trigger: { kind: "every", interval_seconds: 18_000 } },],});}if (path.includes("/scout/routines")) {return json({routines: [- {- id: "sc1",- title: "[agent:Scout] Dawn brief",- state: "scheduled",- trigger: { kind: "every", interval_seconds: 86_400 },- },+ { id: "sc1", title: "[agent:Scout] Dawn brief", state: "scheduled", trigger: { kind: "every", interval_seconds: 86_400 } },],});}@@ -120,12 +155,18 @@ describe("OptionsRail", () => {vi.unstubAllGlobals();});- test("shows the screen and this agent's routines, not a full-width Retire", async () => {+ test("opens on the Overview with the six-part anatomy and a calm header", async () => {mount(agent());- await waitFor(() => expect(screen.getByTestId("agent-browser-preview")).toBeTruthy());- await waitFor(() => expect(screen.getByTestId("agent-routines").textContent).toContain("Inbox sweep"));+ const anatomy = await screen.findByTestId("agent-pane-anatomy");+ for (const row of ["instructions", "memory", "skills", "routines", "tools", "files"]) {+ expect(screen.getByTestId(`agent-pane-row-${row}`)).toBeTruthy();+ }+ await waitFor(() => expect(screen.getByTestId("agent-pane-row-routines").textContent).toContain("1"));+ await waitFor(() => expect(screen.getByTestId("agent-pane-row-memory").textContent).toContain("2 waiting"));+ expect(anatomy).toBeTruthy();+ expect(screen.getByTestId("edit-agent-appearance")).toBeTruthy();+ expect(screen.getByTestId("share-agent")).toBeTruthy();expect(screen.queryByTestId("agent-card-retire")).toBeNull();- expect(screen.getByTestId("agent-card-options-more")).toBeTruthy();});test("Retire lives behind ⋯ and still only arms on the first press", async () => {@@ -138,63 +179,133 @@ describe("OptionsRail", () => {expect(fetchMock.mock.calls.filter((c) => (c[1] as RequestInit | undefined)?.method === "DELETE")).toHaveLength(0);});- test("collapses the entire rail with a reachable toggle and preserves browser and routine drafts", async () => {+ test("the chosen tab survives a reload", async () => {+ const first = mount(agent());+ fireEvent.mouseDown(screen.getByTestId("agent-pane-tab-tasks"), { button: 0 });+ fireEvent.click(screen.getByTestId("agent-pane-tab-tasks"));+ await waitFor(() => expect(screen.getByTestId("agent-routines").textContent).toContain("Inbox sweep"));+ first.unmount();+ mount(agent());+ await waitFor(() => expect(screen.getByTestId("agent-routines").textContent).toContain("Inbox sweep"));+ expect(screen.getByTestId("agent-pane-tab-tasks").getAttribute("data-state")).toBe("active");+ });++ test("folding the pane keeps routine and chat drafts", async () => {+ window.localStorage.setItem("society.agentPane.tab", "tasks");mount(agent());await screen.findByText("Inbox sweep");const toggle = await screen.findByRole("button", { name: "Collapse Options" });const panel = document.getElementById(toggle.getAttribute("aria-controls")!)!;- const browser = screen.getByTestId("agent-browser-preview");- const canvas = browser.querySelector("canvas");fireEvent.click(screen.getByTestId("agent-routines-add"));const title = screen.getByRole("textbox", { name: "Title" }) as HTMLInputElement;fireEvent.change(title, { target: { value: "Unsaved routine" } });const chat = screen.getByRole("textbox", { name: "Chat draft" }) as HTMLTextAreaElement;fireEvent.change(chat, { target: { value: "Unsent message" } });- toggle.focus();fireEvent.click(toggle);- expect(toggle.getAttribute("aria-expanded")).toBe("false");expect(panel.hidden).toBe(true);- expect(screen.queryByRole("complementary", { name: "Options" })).toBeNull();- expect(document.activeElement).toBe(toggle);- expect(screen.getByRole("textbox", { name: "Chat draft" })).toBe(chat);expect(chat.value).toBe("Unsent message");-fireEvent.click(screen.getByRole("button", { name: "Expand Options" }));expect(panel.hidden).toBe(false);- expect(toggle.getAttribute("aria-expanded")).toBe("true");- expect(screen.getByTestId("agent-browser-preview")).toBe(browser);- expect(browser.querySelector("canvas")).toBe(canvas);expect(screen.getByRole("textbox", { name: "Title" })).toBe(title);expect(title.value).toBe("Unsaved routine");- expect(fetchMock.mock.calls.some(([, init]) => {- const method = (init as RequestInit | undefined)?.method ?? "GET";- return method !== "GET";- })).toBe(false);+ expect(fetchMock.mock.calls.some(([, init]) => ((init as RequestInit | undefined)?.method ?? "GET") !== "GET")).toBe(false);});- test("keeps the selected routine detail open when Options is folded", async () => {+ test("a routine draft survives a trip to another tab", async () => {+ window.localStorage.setItem("society.agentPane.tab", "tasks");mount(agent());- fireEvent.click(await screen.findByText("Inbox sweep"));- const detail = await screen.findByTestId("agent-routine-detail");- const toggle = await screen.findByRole("button", { name: "Collapse Options" });- fireEvent.click(toggle);- fireEvent.click(screen.getByRole("button", { name: "Expand Options" }));- expect(screen.getByTestId("agent-routine-detail")).toBe(detail);+ await screen.findByText("Inbox sweep");+ fireEvent.click(screen.getByTestId("agent-routines-add"));+ fireEvent.change(screen.getByRole("textbox", { name: "Title" }), { target: { value: "Keep me" } });+ fireEvent.mouseDown(screen.getByTestId("agent-pane-tab-overview"), { button: 0 });+ await screen.findByTestId("agent-pane-anatomy");+ fireEvent.mouseDown(screen.getByTestId("agent-pane-tab-tasks"), { button: 0 });+ expect((screen.getByRole("textbox", { name: "Title" }) as HTMLInputElement).value).toBe("Keep me");});- test("switching agent swaps the caption and the routines list", async () => {+ test("the browser tab shows the agent's screen", async () => {+ window.localStorage.setItem("society.agentPane.tab", "browser");+ mount(agent());+ await waitFor(() => expect(screen.getByTestId("agent-browser-preview")).toBeTruthy());+ });++ test("an anatomy row drills down in place and Back returns", async () => {+ mount(agent());+ fireEvent.click(await screen.findByTestId("agent-pane-row-instructions"));+ const input = (await screen.findByTestId("agent-pane-instructions-input")) as HTMLTextAreaElement;+ expect(input.value).toBe("Look after the mail.");+ expect(screen.getByTestId("agent-pane-subpage").textContent).toContain("Instructions");+ fireEvent.click(screen.getByTestId("agent-pane-back"));+ await screen.findByTestId("agent-pane-anatomy");+ expect(screen.queryByTestId("agent-pane-subpage")).toBeNull();+ });++ test("the review queue decides real items and seeds the chat on request", async () => {+ window.localStorage.setItem("society.agentPane.tab", "memory");+ writeComposerDraft(useSocietyChatStore, "society:gamil-agent", { text: "", choices: [] });+ mount(agent());+ await screen.findByTestId("agent-pane-review-proposal:p1");+ expect(screen.getByTestId("agent-pane-review-memory:7").textContent).toContain("The user prefers short replies.");++ fireEvent.click(screen.getByTestId("agent-pane-review-approve-proposal:p1"));+ await waitFor(() => {+ const call = fetchMock.mock.calls.find(([url, init]) => String(url).includes("/review/") && (init as RequestInit)?.method === "POST");+ expect(call?.[0]).toBe("/api/society/agents/gamil-agent/review/proposal%3Ap1/approve");+ });++ fireEvent.click(screen.getByTestId("agent-pane-review-in-chat"));+ expect(readComposerDraft(useSocietyChatStore, "society:gamil-agent").text).toContain("walk me through");+ // Seeding never sends: no chat message request went out.+ expect(fetchMock.mock.calls.some(([url]) => String(url).includes("/api/agent-chat/"))).toBe(false);+ });++ test("unblocking a tool asks before it is saved", async () => {+ window.localStorage.setItem("society.agentPane.tab", "tools");+ mount(agent({ denies: ["plugin:gmail"] }));+ const row = await screen.findByTestId("agent-pane-tool-plugin:gmail");+ expect(row.getAttribute("data-state")).toBe("blocked");+ fireEvent.click(row.querySelector('[data-value="on"]')!);+ fireEvent.click(await screen.findByTestId("agent-pane-save"));+ const confirm = await screen.findByTestId("agent-pane-widen");+ await waitFor(() => expect(confirm.textContent).toContain("Gmail"));+ expect(fetchMock.mock.calls.some(([, init]) => (init as RequestInit | undefined)?.method === "PATCH")).toBe(false);+ });++ test("switching agent swaps the header and the routines", async () => {+ window.localStorage.setItem("society.agentPane.tab", "tasks");const { rerender, client } = mount(agent());await waitFor(() => expect(screen.getByTestId("agent-routines").textContent).toContain("Inbox sweep"));rerender(<QueryClientProvider client={client}>- <OptionsRail agent={agent({ agentId: "scout", name: "Scout" })} onRetired={() => undefined} />+ <OptionsRail agent={agent({ agentId: "scout", name: "Scout", chatSessionId: "society:scout" })} onRetired={() => undefined} /></QueryClientProvider>,);await waitFor(() => expect(screen.getByTestId("agent-routines").textContent).toContain("Dawn brief"));- expect(screen.getByTestId("agent-browser-preview").textContent).toContain("Scout");+ expect(screen.getByTestId("agent-card-options").textContent).toContain("Scout");expect(screen.getByTestId("agent-routines").textContent).not.toContain("Inbox sweep");});++ test("only real decisions mark the Memory tab, and the review nudge can be dismissed", async () => {+ const first = mount(agent());+ await waitFor(() => expect(screen.getByTestId("agent-pane-row-memory").textContent).toContain("2 waiting"));+ expect(screen.getByTestId("agent-pane-tab-memory").querySelector(".ap-tab-badge")).toBeTruthy();+ first.unmount();++ mount(agent({ agentId: "notes-agent", chatSessionId: "society:notes-agent" }));+ await waitFor(() => expect(screen.getByTestId("agent-pane-row-memory").textContent).toContain("1 waiting"));+ // A notebook write is listed, but it does not raise a mark on the tab.+ expect(screen.getByTestId("agent-pane-tab-memory").querySelector(".ap-tab-badge")).toBeNull();+ const nudge = await screen.findByTestId("agent-pane-suggestion-review");+ fireEvent.click(within(nudge).getByRole("button", { name: "Dismiss" }));+ await waitFor(() => expect(screen.queryByTestId("agent-pane-suggestion-review")).toBeNull());+ });++ test("the lead gets a History tab and no Share", async () => {+ mount(agent({ agentId: "jarvis", name: "Jarvis", tier: "lead", chatSessionId: null }));+ expect(await screen.findByTestId("agent-pane-tab-history")).toBeTruthy();+ expect(screen.queryByTestId("share-agent")).toBeNull();+ });});diff --git a/dodaios/ui/web/frontend/src/components/society/card/OptionsRail.tsx b/dodaios/ui/web/frontend/src/components/society/card/OptionsRail.tsxindex 6261255955..1519cff38d 100644--- a/dodaios/ui/web/frontend/src/components/society/card/OptionsRail.tsx+++ b/dodaios/ui/web/frontend/src/components/society/card/OptionsRail.tsx@@ -1,20 +1,58 @@/**- * The chat-face right column: this agent's browser screen, its routines, and- * a tucked-away Retire control. On the lead's card only, the typed chats and- * the voice sessions join in, so a hung-up call is one click away. Extracted- * from AgentCardOverlay so the overlay stays the layout and this file owns- * what you can do to the agent.+ * The agent's home beside its chat: one details pane with the same anatomy+ * for every agent, in tabs that remember where the person was.+ *+ * - Overview: identity (name, role, instructions edited in place), what it+ * runs on, its six-part anatomy as counted rows, and a few next steps.+ * - Tools & access: reach, tools, approvals and rules, limits, its browser+ * and where it works, saved together; widening changes ask first.+ * - Memory: its notebooks, learned rules and skills, plus the review queue+ * of what it learned or proposed, with "Review in chat".+ * - Tasks: its routines. Browser: its live screen. History: the lead's chats+ * and calls.+ *+ * Drill-downs (instructions, a memory file, skills, files) open IN the pane+ * with a Back button instead of stacking a modal. Look and Share are header+ * actions; Pause and Retire live in the header's "…" menu. The file keeps its+ * historical name and export: the layout mounts `<OptionsRail …>`.*/-import { lazy, Suspense, useEffect, useRef, useState } from "react";-import { MoreHorizontal, Share2 } from "lucide-react";+import { lazy, Suspense, useEffect, useRef, useState, type CSSProperties } from "react";+import * as Tabs from "@radix-ui/react-tabs";+import {+ ChevronLeft,+ History,+ LayoutGrid,+ Lightbulb,+ ListChecks,+ Monitor,+ MoreHorizontal,+ Palette,+ Pause,+ Play,+ Share2,+ Wrench,+ type LucideIcon,+} from "lucide-react";-import { useT } from "@/i18n";+import { useLocaleChunk, useT } from "@/i18n";+import { societyDisplayName } from "@/lib/societyDisplayName";+import { cn } from "@/lib/utils";+import { useEventStore } from "@/store/events";-import type { SocietyAgent } from "../data";+import { AgentSwatch } from "../AgentSwatch";+import { useSetAgentPaused, type SocietyAgent } from "../data";+import { DodaiosHistoryRail } from "../chat/DodaiosHistoryRail";import { AgentBrowserPreview } from "./AgentBrowserPreview";import { AgentRoutinesList } from "./AgentRoutinesList";-import { DodaiosHistoryRail } from "../chat/DodaiosHistoryRail";import { RetireButton } from "./RetireButton";+import { MemoryTab } from "./pane/MemoryTab";+import { OverviewTab } from "./pane/OverviewTab";+import { usePaneStack, usePaneTab, type PaneTab } from "./pane/paneState";+import { useReviewQueue } from "./pane/reviewQueue";+import { FilesPage, InstructionsPage, MemoryFilePage, SkillsPage } from "./pane/SubPages";+import { ToolsTab } from "./pane/ToolsTab";+import "./pane/agentPane.css";+const AgentAppearanceDialog = lazy(() => import("../companion/AgentAppearanceDialog").then(m => ({ default: m.AgentAppearanceDialog })));const ShareAgentDialog = lazy(() => import("./ShareAgentDialog").then(m => ({ default: m.ShareAgentDialog })));@@ -23,29 +61,197 @@ export interface OptionsRailProps {onRetired: () => void;/** True when rows come from the sample roster rather than society.db. */sample?: boolean;+ /** The width the layout gives the pane, in px; the pane adapts its tab labels to it. */+ width?: number;}-export function OptionsRail({ agent, onRetired, sample = false }: OptionsRailProps) {+const TAB_ICONS: Record<PaneTab, LucideIcon> = {+ overview: LayoutGrid,+ tools: Wrench,+ memory: Lightbulb,+ tasks: ListChecks,+ browser: Monitor,+ history: History,+};++export function OptionsRail({ agent, onRetired, sample = false, width }: OptionsRailProps) {const t = useT();- const [more, setMore] = useState(false);+ useLocaleChunk("society");+ const lead = agent.tier === "lead";+ const assistantName = useEventStore((s) => s.assistantName);+ const available: PaneTab[] = lead+ ? ["overview", "tools", "memory", "tasks", "browser", "history"]+ : ["overview", "tools", "memory", "tasks", "browser"];+ const [tab, setTab] = usePaneTab(available);+ const stack = usePaneStack();+ const [visited, setVisited] = useState<Set<PaneTab>>(() => new Set([tab]));const [appearanceOpen, setAppearanceOpen] = useState(false);const [shareOpen, setShareOpen] = useState(false);- const [routineOpen, setRoutineOpen] = useState(false);- const moreRef = useRef<HTMLDivElement>(null);+ const queue = useReviewQueue(agent.agentId, !sample);+ // Only real decisions (a proposal, a share request) mark the tab; the+ // agent's routine notebook writes wait quietly in the list.+ const pending = (queue.data?.counts?.proposal ?? 0) + (queue.data?.counts?.memory_share ?? 0);+ const { reset } = stack;useEffect(() => {- setMore(false);setAppearanceOpen(false);setShareOpen(false);- }, [agent.agentId]);+ reset();+ }, [agent.agentId, reset]);++ useEffect(() => {+ setVisited((prev) => (prev.has(tab) ? prev : new Set([...prev, tab])));+ }, [tab]);++ const choose = (next: PaneTab) => {+ stack.reset();+ setTab(next);+ };++ const page = stack.page;+ const tabLabel = (id: PaneTab) => t(`society.agent_pane.tab_${id}`);++ return (+ <aside+ className="ap-root"+ aria-label={t("society.card.options")}+ data-testid="agent-card-options"+ data-width={width}+ style={{ "--ap-agent": agent.palette.primary } as CSSProperties}+ >+ <PaneHeader+ agent={agent}+ sample={sample}+ name={societyDisplayName(agent, assistantName)}+ onLook={() => setAppearanceOpen(true)}+ onShare={() => setShareOpen(true)}+ onRetired={onRetired}+ />+ <Tabs.Root value={tab} onValueChange={(value) => choose(value as PaneTab)} className="flex min-h-0 flex-1 flex-col">+ <Tabs.List className="ap-tabs" aria-label={t("society.agent_pane.tabs")}>+ {available.map((id) => {+ const Icon = TAB_ICONS[id];+ return (+ <Tabs.Trigger+ key={id}+ value={id}+ className="ap-tab"+ aria-label={tabLabel(id)}+ title={tabLabel(id)}+ data-testid={`agent-pane-tab-${id}`}+ >+ <Icon className="h-3.5 w-3.5 shrink-0" aria-hidden />+ <span className="ap-tab-label">{tabLabel(id)}</span>+ {id === "memory" && pending > 0 ? <span className="ap-tab-badge" aria-hidden /> : null}+ </Tabs.Trigger>+ );+ })}+ </Tabs.List>++ {page ? (+ <div className="ap-sub" data-testid="agent-pane-subpage">+ <button type="button" className="ap-icon-btn" onClick={stack.back} aria-label={t("society.agent_pane.back")} title={t("society.agent_pane.back")} data-testid="agent-pane-back">+ <ChevronLeft className="h-4 w-4" aria-hidden />+ </button>+ <span className="truncate">{page.title}</span>+ </div>+ ) : null}+ {page ? (+ <div key={`${agent.agentId}:${page.id}`} className="flex min-h-0 flex-1 flex-col">+ {page.id === "instructions" ? <InstructionsPage agent={agent} sample={sample} />+ : page.id === "skills" ? <SkillsPage agent={agent} sample={sample} />+ : page.id === "files" ? <FilesPage agent={agent} />+ : page.id.startsWith("file:") ? <MemoryFilePage agent={agent} path={page.id.slice(5)} />+ : null}+ </div>+ ) : null}++ {available.map((id) => {+ const active = id === tab && !page;+ // A visited tab keeps its state (a routine draft, unsaved access+ // edits) while hidden; the live browser stream runs only on screen.+ const mounted = id === "browser" ? active : visited.has(id) || id === tab;+ if (!mounted) return null;+ return (+ <Tabs.Content+ key={id}+ value={id}+ forceMount+ hidden={!active}+ className={cn("min-h-0 flex-1 flex-col outline-none", active ? "flex" : "hidden")}+ >+ {id === "overview" ? (+ <OverviewTab key={agent.agentId} agent={agent} sample={sample} queue={queue.data} onTab={choose} onPage={stack.push} />+ ) : id === "tools" ? (+ <ToolsTab key={agent.agentId} agent={agent} sample={sample} />+ ) : id === "memory" ? (+ <MemoryTab key={agent.agentId} agent={agent} sample={sample} queue={queue.data} queueLoading={queue.isLoading} onPage={stack.push} />+ ) : id === "tasks" ? (+ <div className="ap-body" data-fill="true">+ <AgentRoutinesList+ key={agent.agentId}+ agentId={agent.agentId}+ sampleRoutines={sample ? agent.routines : undefined}+ variant="rail"+ className="min-h-48 flex-1"+ />+ </div>+ ) : id === "browser" ? (+ <div className="ap-body" data-fill="true">+ <AgentBrowserPreview agent={agent} />+ </div>+ ) : (+ <div className="ap-body" data-fill="true">+ <DodaiosHistoryRail />+ </div>+ )}+ </Tabs.Content>+ );+ })}+ </Tabs.Root>+ {appearanceOpen && <Suspense fallback={null}><AgentAppearanceDialog key={agent.agentId} agent={agent} sample={sample} onClose={() => setAppearanceOpen(false)} /></Suspense>}+ {shareOpen && <Suspense fallback={null}><ShareAgentDialog key={agent.agentId} agent={agent} onClose={() => setShareOpen(false)} /></Suspense>}+ </aside>+ );+}++function PaneHeader({+ agent,+ sample,+ name,+ onLook,+ onShare,+ onRetired,+}: {+ agent: SocietyAgent;+ sample: boolean;+ name: string;+ onLook: () => void;+ onShare: () => void;+ onRetired: () => void;+}) {+ const t = useT();+ const lead = agent.tier === "lead";+ const setPaused = useSetAgentPaused();+ const [more, setMore] = useState(false);+ const [busy, setBusy] = useState(false);+ const moreRef = useRef<HTMLDivElement>(null);+ const triggerRef = useRef<HTMLButtonElement>(null);+ const paused = agent.lifecycle === "paused" || agent.state === "paused";+ useEffect(() => setMore(false), [agent.agentId]);useEffect(() => {if (!more) return;+ // Keyboard users land on the first action, as a menu should.+ moreRef.current?.querySelector<HTMLElement>('[role="menu"] button:not(:disabled)')?.focus();const onDown = (e: MouseEvent) => {if (!moreRef.current?.contains(e.target as Node)) setMore(false);};const onKey = (e: KeyboardEvent) => {- if (e.key === "Escape") setMore(false);+ if (e.key === "Escape") {+ setMore(false);+ triggerRef.current?.focus();+ }};document.addEventListener("mousedown", onDown);document.addEventListener("keydown", onKey);@@ -55,65 +261,69 @@ export function OptionsRail({ agent, onRetired, sample = false }: OptionsRailPro};}, [more]);+ const togglePause = async () => {+ setBusy(true);+ try {+ await setPaused(agent, !paused);+ } finally {+ setBusy(false);+ setMore(false);+ }+ };+return (- <aside- className="flex h-full min-h-0 flex-col border-l border-border bg-sidebar"- aria-label={t("society.card.options")}- data-testid="agent-card-options"- >- <header className="flex shrink-0 items-center justify-between gap-2 px-3 pb-1 pt-3">- <h2 className="font-display text-sm font-semibold tracking-tight text-foreground">- {t("society.card.options")}- </h2>- <div ref={moreRef} className="relative">- <button- type="button"- className="rounded-md p-1 text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-strong"- aria-label={t("society.card.options_more")}- aria-expanded={more}- aria-haspopup="menu"- onClick={() => setMore((v) => !v)}- data-testid="agent-card-options-more"- >- <MoreHorizontal className="h-4 w-4" aria-hidden />- </button>- {more ? (- <div- role="menu"- className="absolute right-0 top-full z-10 mt-1 w-56 rounded-md border border-border bg-popover p-3 shadow-float"- >+ <header className="ap-head">+ <span className="ap-avatar">+ <AgentSwatch agent={agent} size={30} />+ </span>+ <div className="min-w-0 flex-1">+ <h2 className="ap-name" title={name}>{name}</h2>+ <div className="ap-meta">+ <span className="ap-dot" data-state={agent.state} aria-hidden />+ <span className="shrink-0">{t(`society.state.${agent.state}`)}</span>+ {agent.title && agent.title !== name ? <span className="truncate">· {agent.title}</span> : null}+ </div>+ </div>+ <button type="button" className="ap-icon-btn" onClick={onLook} aria-label={t("society.companion.appearance")} title={t("society.companion.appearance")} data-testid="edit-agent-appearance">+ <Palette className="h-4 w-4" aria-hidden />+ </button>+ {/* The lead is every install's own assistant and sample rows are not real agents: neither is shareable. */}+ {!lead && !sample ? (+ <button type="button" className="ap-icon-btn" onClick={onShare} aria-label={t("society.share.cta")} title={t("society.share.cta_hint")} data-testid="share-agent">+ <Share2 className="h-4 w-4" aria-hidden />+ </button>+ ) : null}+ <div ref={moreRef} className="relative">+ <button+ ref={triggerRef}+ type="button"+ className="ap-icon-btn"+ aria-label={t("society.card.options_more")}+ aria-expanded={more}+ aria-haspopup="menu"+ onClick={() => setMore((v) => !v)}+ data-testid="agent-card-options-more"+ >+ <MoreHorizontal className="h-4 w-4" aria-hidden />+ </button>+ {more ? (+ <div role="menu" className="ap-menu shadow-float">+ {!lead ? (+ <>+ <button type="button" role="menuitem" className="ap-menu-item" disabled={busy} onClick={() => void togglePause()} data-testid="agent-pane-pause">+ {paused ? <Play className="h-3.5 w-3.5" aria-hidden /> : <Pause className="h-3.5 w-3.5" aria-hidden />}+ {paused ? t("society.card.action_resume") : t("society.card.action_pause")}+ </button>+ <div className="ap-menu-sep" role="separator" />+ </>+ ) : null}+ <div className="p-2"><RetireButton agent={agent} onRetired={onRetired} variant="rail" /></div>- ) : null}- </div>- </header>- <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto px-3 pb-3 pt-2">- <div className="flex shrink-0 gap-2">- <button type="button" onClick={() => setAppearanceOpen(true)} data-testid="edit-agent-appearance" className="min-w-0 flex-1 rounded-lg border border-border px-3 py-2 text-left text-sm font-medium text-foreground hover:bg-secondary">{t("society.companion.appearance")}</button>- {/* The lead is every install's own Jarvis and sample rows are not real agents: neither is shareable. */}- {agent.tier !== "lead" && !sample && (- <button type="button" onClick={() => setShareOpen(true)} data-testid="share-agent" title={t("society.share.cta_hint")} className="flex shrink-0 items-center gap-1.5 rounded-lg border border-border px-3 py-2 text-sm font-medium text-foreground hover:bg-secondary">- <Share2 className="h-3.5 w-3.5 text-muted-foreground" aria-hidden />- {t("society.share.cta")}- </button>- )}- </div>- <div className={routineOpen ? "hidden" : "contents"}>- <AgentBrowserPreview agent={agent} />- {agent.tier === "lead" ? <DodaiosHistoryRail /> : null}- </div>- <AgentRoutinesList- key={agent.agentId}- agentId={agent.agentId}- onDetailOpenChange={setRoutineOpen}- sampleRoutines={sample ? agent.routines : undefined}- variant="rail"- className="min-h-48 flex-1"- />+ </div>+ ) : null}</div>- {appearanceOpen && <Suspense fallback={null}><AgentAppearanceDialog key={agent.agentId} agent={agent} sample={sample} onClose={() => setAppearanceOpen(false)} /></Suspense>}- {shareOpen && <Suspense fallback={null}><ShareAgentDialog key={agent.agentId} agent={agent} onClose={() => setShareOpen(false)} /></Suspense>}- </aside>+ </header>);}diff --git a/dodaios/ui/web/frontend/src/components/society/card/pane/MemoryTab.tsx b/dodaios/ui/web/frontend/src/components/society/card/pane/MemoryTab.tsxnew file mode 100644index 0000000000..b83937258f--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/card/pane/MemoryTab.tsx@@ -0,0 +1,226 @@+/**+ * Memory & learning: what the agent keeps about the person and its work, and+ * the review queue of what it learned or proposed since. Every queued item+ * shows a diff-style preview and is decided in one click; "Review in chat"+ * puts a ready message into the agent's composer (never sent by itself), so+ * the agent can walk the person through the list in conversation instead.+ */+import { useState } from "react";+import { BookUser, Check, FileText, MessageSquare, NotebookPen, Sparkles, X } from "lucide-react";++import { useRunLocale } from "@/components/runs/format";+import { useLocaleChunk, useT } from "@/i18n";++import { useAgentSkills } from "../../cardData";+import type { SocietyAgent } from "../../data";+import { useAgentKnowledge } from "../AgentKnowledge";+import type { PanePage } from "./paneState";+import { useDecideReviewItem, type ReviewItem, type ReviewQueue } from "./reviewQueue";+import { seedAgentComposer } from "./seedComposer";+import { AnatomyRow, PaneHint, PaneSection } from "./ui";++/** Preview lines shown before the item is opened. */+const PREVIEW_LINES = 3;++export function MemoryTab({+ agent,+ sample,+ queue,+ queueLoading,+ onPage,+}: {+ agent: SocietyAgent;+ sample: boolean;+ queue: ReviewQueue | undefined;+ queueLoading: boolean;+ onPage: (page: PanePage) => void;+}) {+ const t = useT();+ useLocaleChunk("society");+ const knowledge = useAgentKnowledge(agent.agentId, sample);+ const skills = useAgentSkills(sample ? null : agent.agentId);+ const [seeded, setSeeded] = useState(false);+ const items = queue?.items ?? [];+ const files = knowledge.data?.files ?? [];+ const rules = knowledge.data?.learned_instructions ?? [];++ const reviewInChat = () => {+ setSeeded(seedAgentComposer(agent, t("society.agent_pane.review_chat_seed")));+ };++ return (+ <div className="ap-body" data-testid="agent-pane-memory">+ <PaneSection+ title={+ items.length+ ? t("society.agent_pane.review_title_count").replace("{0}", String(queue?.total ?? items.length))+ : t("society.agent_pane.review_title")+ }+ action={+ items.length ? (+ <button type="button" className="ap-link" onClick={reviewInChat} data-testid="agent-pane-review-in-chat">+ <MessageSquare className="h-3 w-3" aria-hidden />+ {t("society.agent_pane.review_in_chat")}+ </button>+ ) : null+ }+ testId="agent-pane-review"+ >+ {seeded ? <PaneHint>{t("society.agent_pane.review_seeded")}</PaneHint> : null}+ {sample ? (+ <PaneHint>{t("society.profile_card.sample_hint")}</PaneHint>+ ) : queueLoading && !queue ? (+ <PaneHint>{t("society.profile_card.loading")}</PaneHint>+ ) : items.length === 0 ? (+ <PaneHint>{t("society.agent_pane.review_empty")}</PaneHint>+ ) : (+ <div className="flex flex-col gap-2">+ {items.map((item) => (+ <ReviewRow key={item.id} agentId={agent.agentId} item={item} />+ ))}+ </div>+ )}+ </PaneSection>++ <PaneSection title={t("society.profile_card.learned_instructions")}>+ {rules.length ? (+ <ul className="flex list-disc flex-col gap-1.5 pl-4 text-[13px] leading-snug">+ {rules.map((rule) => <li key={rule}>{rule}</li>)}+ </ul>+ ) : (+ <PaneHint>{t("society.profile_card.no_instructions")}</PaneHint>+ )}+ </PaneSection>++ <PaneSection title={t("society.agent_pane.memory_files")}>+ {sample ? (+ <PaneHint>{t("society.profile_card.sample_hint")}</PaneHint>+ ) : knowledge.isLoading ? (+ <PaneHint>{t("society.profile_card.loading")}</PaneHint>+ ) : knowledge.isError ? (+ <p role="alert" className="text-xs text-destructive">{t("society.profile_card.load_error")}</p>+ ) : files.length === 0 ? (+ <PaneHint>{t("society.profile_card.empty")}</PaneHint>+ ) : (+ <div className="ap-rows">+ {files.map((file) => (+ <AnatomyRow+ key={file.path}+ icon={file.name === "USER.md" ? BookUser : file.name === "MEMORY.md" ? NotebookPen : file.kind === "skills" ? Sparkles : FileText}+ label={file.name === "USER.md" ? t("society.profile_card.user_book") : file.name === "MEMORY.md" ? t("society.profile_card.memory_book") : file.name}+ detail={file.path}+ onOpen={() => onPage({ id: `file:${file.path}`, title: file.name })}+ testId={`agent-pane-file-${file.path}`}+ />+ ))}+ </div>+ )}+ <PaneHint>{t("society.profile_card.knowledge_hint")}</PaneHint>+ </PaneSection>++ <PaneSection+ title={t("society.agent_pane.skills")}+ action={+ (skills.data?.length ?? 0) > 0 ? (+ <button type="button" className="ap-link" onClick={() => onPage({ id: "skills", title: t("society.agent_pane.skills") })}>+ {t("society.agent_pane.open")}+ </button>+ ) : null+ }+ >+ <PaneHint>+ {(skills.data?.length ?? 0) > 0+ ? (skills.data ?? []).map((s) => s.name).join(", ")+ : t("society.agent_pane.skills_none")}+ </PaneHint>+ </PaneSection>+ </div>+ );+}++const KIND_KEYS: Record<string, string> = {+ rule: "society.agent_pane.kind_rule",+ skill: "society.agent_pane.kind_skill",+ routine: "society.agent_pane.kind_routine",+ approval_rule: "society.agent_pane.kind_approval_rule",+ focus: "society.agent_pane.kind_focus",+ team: "society.agent_pane.kind_team",+ identity: "society.agent_pane.kind_identity",+};++function ReviewRow({ agentId, item }: { agentId: string; item: ReviewItem }) {+ const t = useT();+ const locale = useRunLocale();+ const decide = useDecideReviewItem(agentId);+ const [open, setOpen] = useState(false);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState("");+ const kind =+ item.kind === "proposal"+ ? t(KIND_KEYS[item.proposal_kind] ?? "society.agent_pane.kind_rule")+ : item.kind === "memory_share"+ ? t("society.agent_pane.kind_share")+ : item.book === "USER.md"+ ? t("society.agent_pane.kind_user_memory")+ : t("society.agent_pane.kind_memory");+ const approveLabel =+ item.kind === "proposal" ? t("society.agent_pane.apply") : item.kind === "memory_share" ? t("society.agent_pane.share") : t("society.agent_pane.keep");+ const rejectLabel =+ item.kind === "proposal" ? t("society.agent_pane.reject") : item.kind === "memory_share" ? t("society.agent_pane.keep_private") : t("society.agent_pane.forget");+ const lines = open ? item.preview : item.preview.slice(0, PREVIEW_LINES);++ const run = async (approve: boolean) => {+ setBusy(true);+ setError("");+ try {+ await decide(item, approve);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ setBusy(false);+ }+ };++ return (+ <article className="ap-review" data-testid={`agent-pane-review-${item.id}`}>+ <div className="flex items-center justify-between gap-2">+ <span className="ap-review-kind">{kind}</span>+ {item.created_ms ? (+ <time className="text-[11px] text-muted-foreground" dateTime={new Date(item.created_ms).toISOString()}>+ {new Date(item.created_ms).toLocaleDateString(locale, { day: "2-digit", month: "short" })}+ </time>+ ) : null}+ </div>+ {item.kind === "proposal" ? <p className="ap-review-text">{item.summary}</p> : null}+ {lines.length ? (+ <button+ type="button"+ className="ap-diff text-left"+ data-open={open ? "true" : undefined}+ aria-expanded={item.preview.length > PREVIEW_LINES ? open : undefined}+ onClick={() => setOpen((v) => !v)}+ >+ {lines.map((line, i) => (+ <span key={i} data-op={line.startsWith("+") ? "+" : line.startsWith("-") ? "-" : " "}>+ {line}+ </span>+ ))}+ {!open && item.preview.length > PREVIEW_LINES ? (+ <span>{t("society.agent_pane.more_lines").replace("{0}", String(item.preview.length - PREVIEW_LINES))}</span>+ ) : null}+ </button>+ ) : null}+ {item.reason ? <p className="ap-hint">{item.reason}</p> : null}+ {error ? <p role="alert" className="text-xs text-destructive">{error}</p> : null}+ <div className="flex items-center justify-end gap-1.5">+ <button type="button" className="ap-btn" data-variant="ghost" disabled={busy} onClick={() => void run(false)} data-testid={`agent-pane-review-reject-${item.id}`}>+ <X className="h-3.5 w-3.5" aria-hidden />+ {rejectLabel}+ </button>+ <button type="button" className="ap-btn" data-variant="outline" disabled={busy} onClick={() => void run(true)} data-testid={`agent-pane-review-approve-${item.id}`}>+ <Check className="h-3.5 w-3.5" aria-hidden />+ {approveLabel}+ </button>+ </div>+ </article>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/card/pane/OverviewTab.tsx b/dodaios/ui/web/frontend/src/components/society/card/pane/OverviewTab.tsxnew file mode 100644index 0000000000..2ba7a2e828--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/card/pane/OverviewTab.tsx@@ -0,0 +1,348 @@+/**+ * The pane's first tab: who this agent is, what it runs on, and its anatomy+ * in six counted rows that each open where that part is managed. A short list+ * of next steps sits on top while there is something worth doing; each one+ * can be dismissed for good.+ */+import { useMemo, useState } from "react";+import {+ BookOpen,+ CalendarClock,+ FolderOpen,+ Lightbulb,+ Sparkles,+ Wrench,+ X,+} from "lucide-react";++import { ProviderLogo } from "@/components/providers/ProviderLogo";+import { useRunLocale } from "@/components/runs/format";+import { useLocaleChunk, useT } from "@/i18n";+import { societyDisplayName } from "@/lib/societyDisplayName";+import { resolveToolBrand } from "@/lib/toolBrand";+import { useEventStore } from "@/store/events";++import { RuntimeMark } from "../../RuntimeBadge";+import { useAgentRoutines, useAgentSkills } from "../../cardData";+import { useSocietyCapabilities, useUpdateAgentConfig, type SocietyAgent } from "../../data";+import { useAgentKnowledge } from "../AgentKnowledge";+import { LeadBrain } from "../LeadSections";+import { useDismissedSuggestions, type PanePage, type PaneTab } from "./paneState";+import type { ReviewQueue } from "./reviewQueue";+import { AnatomyRow, InlineEdit, PaneHint, PaneSection } from "./ui";++/** More lines than this and the instructions preview fades into "open to read all". */+const PREVIEW_LINES = 5;+const MAX_SUGGESTIONS = 3;++export interface OverviewTabProps {+ agent: SocietyAgent;+ sample: boolean;+ queue: ReviewQueue | undefined;+ onTab: (tab: PaneTab) => void;+ onPage: (page: PanePage) => void;+}++interface Suggestion {+ id: string;+ text: string;+ go: () => void;+}++export function OverviewTab({ agent, sample, queue, onTab, onPage }: OverviewTabProps) {+ const t = useT();+ useLocaleChunk("society");+ const locale = useRunLocale();+ const lead = agent.tier === "lead";+ const assistantName = useEventStore((s) => s.assistantName);+ const update = useUpdateAgentConfig();+ const knowledge = useAgentKnowledge(agent.agentId, sample);+ const skills = useAgentSkills(sample ? null : agent.agentId);+ const routines = useAgentRoutines(sample ? null : agent.agentId);+ const capabilities = useSocietyCapabilities(!sample && !lead);+ const [dismissed, dismiss] = useDismissedSuggestions(agent.agentId);+ const [expanded, setExpanded] = useState(false);++ const memoryFiles = (knowledge.data?.files ?? []).filter((f) => f.kind === "memory");+ const learnedRules = knowledge.data?.learned_instructions ?? [];+ const skillCount = skills.data?.length ?? 0;+ const routineRows = routines.data ?? [];+ const routineCount = sample ? agent.routines.length : routineRows.length;+ const nextRun = routineRows.map((r) => r.dueMs).filter((ms): ms is number => typeof ms === "number").sort((a, b) => a - b)[0];+ const pendingReview = queue?.total ?? 0;+ // Proposals and share requests are decisions; notebook writes are not.+ const decisions = (queue?.counts?.proposal ?? 0) + (queue?.counts?.memory_share ?? 0);++ const byId = useMemo(() => new Map((capabilities.data ?? []).map((c) => [c.id, c])), [capabilities.data]);+ const disconnected = agent.focus.filter((id) => byId.get(id)?.connected === false);++ const descriptionLines = agent.description.split(/\r?\n/).filter((line) => line.trim());+ const long = descriptionLines.length > PREVIEW_LINES || agent.description.length > 420;++ const instructionsPage = () => onPage({ id: "instructions", title: t("society.agent_pane.instructions") });+ const filesPage = () => onPage({ id: "files", title: t("society.agent_pane.files") });++ const suggestions: Suggestion[] = [];+ if (pendingReview > 0) {+ // Keyed by the count: dismissing it holds until something new arrives,+ // so a busy notebook never turns into a standing nag.+ suggestions.push({+ id: `review:${pendingReview}`,+ text: t("society.agent_pane.suggest_review").replace("{0}", String(pendingReview)),+ go: () => onTab("memory"),+ });+ }+ if (!lead && !agent.description.trim()) {+ suggestions.push({ id: "instructions", text: t("society.agent_pane.suggest_instructions"), go: instructionsPage });+ }+ if (!lead && disconnected.length > 0) {+ suggestions.push({+ id: "connect",+ text: t("society.agent_pane.suggest_connect").replace(+ "{0}",+ disconnected.map((id) => resolveToolBrand(byId.get(id)?.tool_name || id.replace(/^[a-z]+:/, "")).label).join(", "),+ ),+ go: () => onTab("tools"),+ });+ }+ if (!sample && routines.isSuccess && routineCount === 0) {+ suggestions.push({ id: "routine", text: t("society.agent_pane.suggest_routine"), go: () => onTab("tasks") });+ }+ const visible = suggestions.filter((s) => !dismissed.has(s.id)).slice(0, MAX_SUGGESTIONS);++ const toolsDetail = lead+ ? t("society.card.tools_all")+ : agent.focus.length+ ? agent.focus.map((id) => resolveToolBrand(byId.get(id)?.tool_name || id.replace(/^(plugin|cli|mcp|skill|core):/, "")).label).join(", ")+ : agent.grantMode === "allowlist"+ ? t("society.agent_pane.tools_allowlist_detail").replace("{0}", String(agent.toolGrants.length))+ : t("society.agent_pane.tools_all_detail");++ const capped = agent.dailyBudgetUsd > 0;+ const spent = agent.stats.spentTodayUsd;+ const share = capped ? Math.min(1, spent / agent.dailyBudgetUsd) : 0;+ const lastActive = agent.stats.lastActiveMs+ ? new Date(agent.stats.lastActiveMs).toLocaleDateString(locale, { day: "2-digit", month: "short" })+ : t("society.card.never");++ return (+ <div className="ap-body" data-testid="agent-pane-overview">+ {visible.length > 0 ? (+ <PaneSection title={t("society.agent_pane.next_steps")} testId="agent-pane-suggestions">+ <div className="flex flex-col gap-1.5">+ {visible.map((s) => (+ <div key={s.id} className="ap-suggest" data-testid={`agent-pane-suggestion-${s.id.split(":")[0]}`}>+ <button type="button" className="ap-suggest-go" onClick={s.go}>+ {s.text}+ </button>+ <button+ type="button"+ className="ap-icon-btn h-6 w-6"+ aria-label={t("society.agent_pane.dismiss")}+ title={t("society.agent_pane.dismiss")}+ onClick={() => dismiss(s.id)}+ >+ <X className="h-3 w-3" aria-hidden />+ </button>+ </div>+ ))}+ </div>+ </PaneSection>+ ) : null}++ <PaneSection title={t("society.agent_pane.identity")}>+ <div className="flex flex-col gap-1.5">+ <div className="flex min-w-0 items-baseline gap-2">+ <span className="w-14 shrink-0 truncate text-xs text-muted-foreground">{t("society.profile_card.name")}</span>+ {lead ? (+ <span className="truncate text-sm font-medium" title={t("society.agent_pane.lead_name_hint")}>+ {societyDisplayName(agent, assistantName)}+ </span>+ ) : (+ <InlineEdit+ value={agent.name}+ label={t("society.agent_pane.rename")}+ maxLength={40}+ disabled={sample}+ className="text-sm font-medium"+ testId="agent-pane-name"+ onSave={async (name) => {+ if (!name) throw new Error(t("society.agent_pane.name_required"));+ await update(agent, { name });+ }}+ />+ )}+ </div>+ <div className="flex min-w-0 items-baseline gap-2">+ <span className="w-14 shrink-0 truncate text-xs text-muted-foreground">{t("society.agent_pane.role")}</span>+ <InlineEdit+ value={agent.title}+ label={t("society.agent_pane.edit_role")}+ placeholder={t("society.agent_pane.role_placeholder")}+ maxLength={120}+ disabled={sample || lead}+ className="text-sm"+ testId="agent-pane-role"+ onSave={async (title) => {+ await update(agent, { title });+ }}+ />+ </div>+ </div>+ </PaneSection>++ <PaneSection+ title={t("society.agent_pane.instructions")}+ action={+ <button type="button" className="ap-link" onClick={instructionsPage} data-testid="agent-pane-edit-instructions">+ {t(lead || sample ? "society.agent_pane.open" : "society.card.edit")}+ </button>+ }+ >+ {lead ? (+ <PaneHint>{t("society.card.instructions_hint")}</PaneHint>+ ) : agent.description.trim() ? (+ <button+ type="button"+ className="ap-instructions text-left"+ data-long={long && !expanded ? "true" : undefined}+ style={expanded ? { maxHeight: "none" } : undefined}+ onClick={() => setExpanded((v) => !v)}+ aria-expanded={expanded}+ >+ {agent.description}+ </button>+ ) : (+ <PaneHint>{t("society.agent_pane.instructions_empty")}</PaneHint>+ )}+ </PaneSection>++ <PaneSection title={t("society.agent_pane.runs_on")}>+ {lead ? (+ <LeadBrain />+ ) : (+ <div className="ap-seat" data-testid="agent-pane-seat">+ <span className="ap-seat-pill" title={t(`society.runtime.${agent.runtime ?? "jarvis"}_hint`)}>+ <RuntimeMark runtime={agent.runtime ?? "jarvis"} label={t(`society.runtime.${agent.runtime ?? "jarvis"}`)} />+ <span className="truncate">{t(`society.runtime.${agent.runtime ?? "jarvis"}`)}</span>+ </span>+ {agent.provider ? (+ <span className="ap-seat-pill">+ <ProviderLogo providerId={agent.provider} label={agent.providerLabel || agent.provider} size="sm" />+ <span className="truncate">{agent.providerLabel || agent.provider}</span>+ </span>+ ) : (+ <span className="ap-seat-pill px-2">{t("society.card.default_brain")}</span>+ )}+ {agent.model ? <span className="truncate font-mono text-[11px]">{agent.model}</span> : null}+ {agent.effort ? <span>· {agent.effort}</span> : null}+ {agent.executionEnvironment === "sandbox" ? <span>· {t("society.sandbox.code")}</span> : null}+ </div>+ )}+ {lead ? null : <PaneHint>{t("society.agent_pane.seat_hint")}</PaneHint>}+ </PaneSection>++ <PaneSection title={t("society.agent_pane.anatomy")} testId="agent-pane-anatomy">+ <div className="ap-rows">+ <AnatomyRow+ icon={BookOpen}+ label={t("society.agent_pane.instructions")}+ detail={+ learnedRules.length+ ? t("society.agent_pane.instructions_learned").replace("{0}", String(learnedRules.length))+ : agent.description.trim() || lead+ ? t("society.agent_pane.instructions_written")+ : t("society.agent_pane.instructions_none")+ }+ onOpen={instructionsPage}+ testId="agent-pane-row-instructions"+ />+ <AnatomyRow+ icon={Lightbulb}+ label={t("society.agent_pane.memory")}+ detail={+ pendingReview+ ? t("society.agent_pane.memory_waiting").replace("{0}", String(pendingReview))+ : t("society.agent_pane.memory_detail")+ }+ count={sample ? null : pendingReview > 0 ? pendingReview : memoryFiles.length}+ attention={decisions > 0}+ onOpen={() => onTab("memory")}+ testId="agent-pane-row-memory"+ />+ <AnatomyRow+ icon={Sparkles}+ label={t("society.agent_pane.skills")}+ detail={skillCount ? (skills.data ?? []).map((s) => s.name).join(", ") : t("society.agent_pane.skills_none")}+ count={sample ? null : skillCount}+ onOpen={() => onPage({ id: "skills", title: t("society.agent_pane.skills") })}+ testId="agent-pane-row-skills"+ />+ <AnatomyRow+ icon={CalendarClock}+ label={t("society.agent_pane.routines")}+ detail={+ nextRun+ ? t("society.agent_pane.routines_next").replace(+ "{0}",+ new Date(nextRun).toLocaleString(locale, { weekday: "short", hour: "2-digit", minute: "2-digit" }),+ )+ : routineCount+ ? t("society.agent_pane.routines_idle")+ : t("society.agent_pane.routines_none")+ }+ count={routineCount}+ onOpen={() => onTab("tasks")}+ testId="agent-pane-row-routines"+ />+ <AnatomyRow+ icon={Wrench}+ label={t("society.agent_pane.tools")}+ detail={toolsDetail}+ count={lead ? null : agent.focus.length || null}+ attention={disconnected.length > 0}+ onOpen={() => onTab("tools")}+ testId="agent-pane-row-tools"+ />+ <AnatomyRow+ icon={FolderOpen}+ label={t("society.agent_pane.files")}+ detail={agent.workspaceDir || `society/${agent.agentId}/`}+ onOpen={filesPage}+ testId="agent-pane-row-files"+ />+ </div>+ </PaneSection>++ <PaneSection title={t("society.card.record")}>+ <div className="ap-stats">+ <div className="ap-stat">+ <span className="ap-stat-label">{t("society.card.runs")}</span>+ <span className="ap-stat-value">{agent.stats.runs}</span>+ </div>+ <div className="ap-stat">+ <span className="ap-stat-label">{t("society.card.cost")}</span>+ <span className="ap-stat-value">${agent.stats.totalCostUsd.toFixed(2)}</span>+ </div>+ <div className="ap-stat">+ <span className="ap-stat-label">{t("society.card.last_active")}</span>+ <span className="ap-stat-value">{lastActive}</span>+ </div>+ </div>+ <div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">+ <span>{t("society.card.meter_today")}</span>+ <span className="tabular-nums">+ {capped+ ? t("society.card.spent_of").replace("{0}", spent.toFixed(2)).replace("{1}", agent.dailyBudgetUsd.toFixed(2))+ : `$${spent.toFixed(2)} · ${t("society.card.no_cap")}`}+ </span>+ </div>+ {capped ? (+ <div className="ap-meter" data-full={share >= 1 ? "true" : undefined} role="img" aria-label={`${t("society.card.meter_today")}: $${spent.toFixed(2)}`}>+ <span className="ap-meter-fill" style={{ width: `${Math.round(share * 100)}%` }} />+ </div>+ ) : null}+ </PaneSection>+ </div>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/card/pane/SubPages.tsx b/dodaios/ui/web/frontend/src/components/society/card/pane/SubPages.tsxnew file mode 100644index 0000000000..0c4b80b338--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/card/pane/SubPages.tsx@@ -0,0 +1,165 @@+/**+ * The pane's drill-down pages. Each replaces the tab body in place, under a+ * header with Back, so configuring an agent never stacks a modal on its chat.+ */+import { useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { FileText, Sparkles } from "lucide-react";++import { useT } from "@/i18n";++import { useAgentSkills } from "../../cardData";+import { useUpdateAgentConfig, type SocietyAgent } from "../../data";+import { MemoryMarkdown } from "../../chat/MemoryDocument";+import { AgentSandboxSection } from "../AgentSandboxSection";+import { LearnedInstructions } from "../AgentKnowledge";+import { LeadInstructions } from "../LeadSections";+import { PaneHint, PaneSection } from "./ui";++export function InstructionsPage({ agent, sample }: { agent: SocietyAgent; sample: boolean }) {+ const t = useT();+ const update = useUpdateAgentConfig();+ const [draft, setDraft] = useState(agent.description);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState("");+ const [saved, setSaved] = useState(false);+ if (agent.tier === "lead") {+ return (+ <div className="ap-body">+ <LeadInstructions />+ </div>+ );+ }+ const dirty = draft !== agent.description;+ const save = async () => {+ setSaving(true);+ setError("");+ setSaved(false);+ try {+ const text = draft.trim();+ await update(agent, { description: text });+ setDraft(text);+ setSaved(true);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setSaving(false);+ }+ };+ return (+ <div className="ap-body" data-testid="agent-pane-instructions-page">+ <PaneSection>+ <PaneHint>{t("society.profile_card.instructions_hint")}</PaneHint>+ <textarea+ className="ap-input min-h-[240px]"+ value={draft}+ aria-label={t("society.agent_pane.instructions")}+ placeholder={t("society.card.no_description")}+ disabled={sample || saving}+ onChange={(event) => {+ setDraft(event.target.value);+ setSaved(false);+ }}+ data-testid="agent-pane-instructions-input"+ />+ <div className="flex items-center justify-end gap-2">+ {error ? <span role="alert" className="mr-auto text-xs text-destructive">{error}</span> : null}+ {saved && !dirty ? <span role="status" className="mr-auto text-xs text-muted-foreground">{t("society.profile_card.saved")}</span> : null}+ <button type="button" className="ap-btn" data-variant="ghost" disabled={!dirty || saving} onClick={() => setDraft(agent.description)}>+ {t("society.agent_pane.discard")}+ </button>+ <button type="button" className="ap-btn" data-variant="primary" disabled={!dirty || saving || sample} onClick={() => void save()}>+ {t(saving ? "society.card.saving" : "society.card.save")}+ </button>+ </div>+ </PaneSection>+ <LearnedInstructions agentId={agent.agentId} sample={sample} />+ </div>+ );+}++export function SkillsPage({ agent, sample }: { agent: SocietyAgent; sample: boolean }) {+ const t = useT();+ const skills = useAgentSkills(sample ? null : agent.agentId);+ const rows = skills.data ?? [];+ return (+ <div className="ap-body" data-testid="agent-pane-skills-page">+ <PaneHint>{t("society.agent_pane.skills_hint")}</PaneHint>+ {rows.length === 0 ? (+ <PaneHint>{skills.isLoading ? t("society.profile_card.loading") : t("society.agent_pane.skills_none")}</PaneHint>+ ) : (+ <div className="ap-rows">+ {rows.map((skill) => (+ <div key={skill.slug} className="ap-row items-start">+ <span className="ap-row-icon" aria-hidden><Sparkles className="h-3.5 w-3.5" /></span>+ <span className="min-w-0 flex-1">+ <span className="ap-row-label">{skill.name}</span>+ <span className="block text-xs leading-snug text-muted-foreground">{skill.whenToUse || skill.description}</span>+ </span>+ </div>+ ))}+ </div>+ )}+ </div>+ );+}++export function FilesPage({ agent }: { agent: SocietyAgent }) {+ const t = useT();+ const sandbox = agent.executionEnvironment === "sandbox";+ return (+ <div className="ap-body" data-testid="agent-pane-files-page">+ <PaneHint>{t(sandbox ? "society.sandbox.storage" : "society.agent_pane.files_hint")}</PaneHint>+ <div className="ap-rows">+ <div className="ap-row">+ <span className="min-w-0 flex-1">+ <span className="ap-row-label">{t("society.card.workspace")}</span>+ <span className="block break-all font-mono text-[11px] text-muted-foreground">{agent.workspaceDir || `society/${agent.agentId}/workspace`}</span>+ </span>+ </div>+ <div className="ap-row">+ <span className="min-w-0 flex-1">+ <span className="ap-row-label">{t("society.card.wiki")}</span>+ <span className="block break-all font-mono text-[11px] text-muted-foreground">{agent.wikiNamespace || `society/${agent.agentId}/`}</span>+ </span>+ </div>+ </div>+ {sandbox ? <AgentSandboxSection agent={agent} show="files" /> : null}+ </div>+ );+}++/** One memory file, read-only, rendered as the agent wrote it. */+export function MemoryFilePage({ agent, path }: { agent: SocietyAgent; path: string }) {+ const t = useT();+ const file = useQuery({+ queryKey: ["society", "profile-knowledge-file", agent.agentId, path],+ retry: false,+ queryFn: async ({ signal }) => {+ const res = await fetch(+ `/api/society/agents/${encodeURIComponent(agent.agentId)}/knowledge/file?path=${encodeURIComponent(path)}`,+ { signal },+ );+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ return (await res.json()) as { content: string };+ },+ });+ return (+ <div className="ap-body" data-testid="agent-pane-file-page">+ <div className="flex items-center gap-2 text-xs text-muted-foreground">+ <FileText className="h-3.5 w-3.5 shrink-0" aria-hidden />+ <span className="truncate font-mono">{path}</span>+ <span className="ml-auto shrink-0">{t("society.profile_card.read_only")}</span>+ </div>+ {file.isLoading ? (+ <PaneHint>{t("society.profile_card.loading")}</PaneHint>+ ) : file.isError ? (+ <p role="alert" className="text-xs text-destructive">{t("society.profile_card.load_error")}</p>+ ) : (+ <div className="ap-file">+ <MemoryMarkdown text={file.data?.content || t("society.profile_card.empty_file")} />+ </div>+ )}+ </div>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/card/pane/ToolsTab.tsx b/dodaios/ui/web/frontend/src/components/society/card/pane/ToolsTab.tsxnew file mode 100644index 0000000000..8995ca7162--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/card/pane/ToolsTab.tsx@@ -0,0 +1,531 @@+/**+ * Tools & access: everything that decides what this agent may touch, in one+ * draft with one Save. Reach and tools, approvals and rules, limits and its+ * browser are edited together; a change that lets the agent do MORE asks once+ * before it is saved. Placement (sandbox, computer) saves on its own, as it+ * always did, because it moves the agent rather than tuning it.+ *+ * Every field rides `PATCH /api/society/agents/{id}`, and only the fields that+ * changed are sent. Hermes and OpenClaw agents read the same roster row on+ * every turn (the per-turn tool filter), so a saved change applies from the+ * agent's next turn on every runtime.+ */+import { useEffect, useMemo, useRef, useState } from "react";+import { useQuery } from "@tanstack/react-query";+import { Ban, Check, Circle, Search, Star } from "lucide-react";++import { Switch } from "@/components/ui/switch";+import { useLocaleChunk, useT } from "@/i18n";+import { AGENT_APPROVAL_MODES, PERMISSION_CEILINGS, fetchSocietyProviders, type AgentApprovalMode, type BrowserMode } from "@/lib/societyApi";+import { societyDisplayName } from "@/lib/societyDisplayName";+import { resolveToolBrand } from "@/lib/toolBrand";+import { useEventStore } from "@/store/events";++import { capabilityKind, capabilityName } from "../../CapabilityChip";+import { ComputerPicker } from "../../create/ComputerPicker";+import {+ useSetAgentComputer,+ useSocietyCapabilities,+ useUpdateAgentConfig,+ type Capability,+ type GrantMode,+ type PermissionCeiling,+ type SocietyAgent,+} from "../../data";+import { AgentSandboxSection } from "../AgentSandboxSection";+import {+ draftFromAgent,+ isDirty,+ normalizeDomain,+ patchFromDraft,+ setGrantMode,+ setToolState,+ toolState,+ widenings,+ type AccessDraft,+ type ToolState,+ type Widening,+} from "./accessDraft";+import { ChipList, PaneHint, PaneSection, Segmented, type SegmentOption } from "./ui";++/** Rows shown before "Show all": enough for the tools an agent really uses. */+const TOOL_PREVIEW = 8;++/** Runners that can show an actionable approval card, per mode (mirrors the PATCH validator). */+function modeUnavailable(mode: AgentApprovalMode, provider: string, runner: string | undefined): boolean {+ const unknownRunner = Boolean(provider) && runner == null;+ if (mode === "always_ask") return unknownRunner || (runner != null && runner !== "codex-cli" && runner !== "brain");+ if (mode === "ask") {+ return unknownRunner || (runner != null && !["codex-cli", "claude-cli", "glm-cli", "brain"].includes(runner));+ }+ return false;+}++export function ToolsTab({ agent, sample }: { agent: SocietyAgent; sample: boolean }) {+ const t = useT();+ useLocaleChunk("society");+ const lead = agent.tier === "lead";+ const update = useUpdateAgentConfig();+ const assistantName = useEventStore((s) => s.assistantName);+ const capabilities = useSocietyCapabilities(!sample);+ const providers = useQuery({ queryKey: ["society", "providers"], queryFn: fetchSocietyProviders, enabled: !lead && !sample, retry: false });+ const runner = providers.data?.find((row) => row.id === agent.provider)?.runner;++ const base = useMemo(() => draftFromAgent(agent), [agent]);+ const [draft, setDraft] = useState<AccessDraft>(base);+ const agentRef = useRef(agent);+ // A saved change, an approved proposal or a refetch moves the agent: adopt+ // it unless the person is in the middle of an edit of their own. "In the+ // middle of an edit" is judged by meaning, not by text, because the server+ // stores sets sorted and a byte-wise check would freeze a stale draft.+ useEffect(() => {+ const previous = agentRef.current;+ agentRef.current = agent;+ if (previous === agent) return;+ setDraft((current) => (isDirty(previous, current) ? current : draftFromAgent(agent)));+ }, [agent]);+ const confirmRef = useRef<HTMLButtonElement>(null);++ const [saving, setSaving] = useState(false);+ const [error, setError] = useState("");+ const [confirm, setConfirm] = useState<Widening[] | null>(null);+ const dirty = isDirty(agent, draft);++ const catalog = capabilities.data ?? [];+ const byId = useMemo(() => new Map(catalog.map((c) => [c.id, c])), [catalog]);+ const labelOf = (id: string) => {+ const known = byId.get(id) ?? byId.get(id.split(":").slice(0, 2).join(":"));+ const brand = resolveToolBrand(known?.tool_name || capabilityName(id));+ return brand.brandId ? brand.label : known?.label ?? id;+ };++ const save = async (confirmed: boolean) => {+ const widen = widenings(agent, draft);+ if (!confirmed && widen.length > 0) {+ setConfirm(widen);+ return;+ }+ setConfirm(null);+ setSaving(true);+ setError("");+ try {+ const saved = await update(agent, patchFromDraft(agent, draft));+ // Take the stored values (sorted, normalised) as the new starting point.+ setDraft(draftFromAgent(saved));+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setSaving(false);+ }+ };++ // The confirmation takes focus, so a keyboard user hears it and can answer.+ useEffect(() => {+ if (confirm) confirmRef.current?.focus();+ }, [confirm]);++ const disabled = sample || saving;+ const ceilingOptions: SegmentOption<PermissionCeiling>[] = PERMISSION_CEILINGS.map((step) => ({ value: step, label: t(`society.ceiling.${step}`) }));++ return (+ <div className="flex min-h-0 flex-1 flex-col" data-testid="agent-pane-tools">+ <div className="ap-body">+ {lead ? (+ <PaneSection title={t("society.agent_pane.reach")}>+ <PaneHint>{t("society.agent_pane.lead_tools_hint")}</PaneHint>+ </PaneSection>+ ) : (+ <>+ <PaneSection title={t("society.agent_pane.reach")}>+ <Segmented<GrantMode>+ label={t("society.agent_pane.reach")}+ value={draft.grantMode}+ disabled={disabled}+ testId="agent-pane-grant-mode"+ options={[+ { value: "all", label: t("society.agent_pane.reach_all") },+ { value: "allowlist", label: t("society.agent_pane.reach_allowlist") },+ ]}+ onChange={(mode) => setDraft((d) => setGrantMode(d, mode))}+ />+ <PaneHint>+ {t(draft.grantMode === "all" ? "society.agent_pane.reach_all_hint" : "society.agent_pane.reach_allowlist_hint")}+ </PaneHint>+ </PaneSection>+ <ToolList+ draft={draft}+ catalog={catalog}+ loading={capabilities.isLoading}+ failed={capabilities.isError}+ disabled={disabled}+ onChange={(id, state) => setDraft((d) => setToolState(d, id, state))}+ />+ </>+ )}++ <PaneSection title={t("society.agent_pane.approvals")} testId="agent-pane-approvals">+ {!lead ? (+ <>+ <Segmented<AgentApprovalMode>+ label={t("society.approval_mode.title")}+ value={draft.approvalMode}+ disabled={disabled}+ testId="agent-pane-approval-mode"+ options={AGENT_APPROVAL_MODES.map((mode) => {+ const off = modeUnavailable(mode, agent.provider, runner);+ return {+ value: mode,+ label: t(`society.approval_mode.${mode}`),+ disabled: off,+ title: off ? t("society.approval_mode.unavailable") : t(`society.approval_mode.${mode}_hint`),+ };+ })}+ onChange={(mode) => setDraft((d) => ({ ...d, approvalMode: mode }))}+ />+ <PaneHint>+ {draft.approvalMode ? t(`society.approval_mode.${draft.approvalMode}_hint`) : t("society.approval_mode.legacy_hint")}+ </PaneHint>+ </>+ ) : null}+ {lead || !agent.approvalMode ? (+ <div className="flex flex-col gap-1.5">+ <span className="text-xs text-muted-foreground">{t("society.approval_mode.legacy_ceiling")}</span>+ <Segmented<PermissionCeiling>+ label={t("society.approval_mode.legacy_ceiling")}+ value={draft.permissionCeiling}+ disabled={disabled}+ testId="agent-pane-ceiling"+ options={ceilingOptions}+ onChange={(step) => setDraft((d) => ({ ...d, permissionCeiling: step }))}+ />+ </div>+ ) : null}+ </PaneSection>++ {!lead ? (+ <PaneSection title={t("society.card.approval_rules")} testId="agent-pane-rules">+ <PaneHint>{t("society.agent_pane.rules_hint")}</PaneHint>+ <span className="text-xs font-medium text-foreground">{t("society.card.require_approval")}</span>+ <ChipList+ items={draft.requireApproval}+ onChange={(items) => setDraft((d) => ({ ...d, requireApproval: items }))}+ placeholder={t("society.agent_pane.rule_placeholder")}+ addLabel={t("society.agent_pane.add")}+ removeLabel={t("society.agent_pane.remove")}+ suggestions={catalog.map((c) => c.id)}+ disabled={disabled}+ emptyText={t("society.agent_pane.rules_none")}+ testId="agent-pane-require"+ />+ <span className="mt-1 text-xs font-medium text-foreground">{t("society.card.always_allow")}</span>+ <ChipList+ items={draft.alwaysAllow}+ onChange={(items) => setDraft((d) => ({ ...d, alwaysAllow: items }))}+ placeholder={t("society.agent_pane.rule_placeholder")}+ addLabel={t("society.agent_pane.add")}+ removeLabel={t("society.agent_pane.remove")}+ suggestions={catalog.map((c) => c.id)}+ disabled={disabled}+ emptyText={t("society.agent_pane.rules_none")}+ testId="agent-pane-allow"+ />+ </PaneSection>+ ) : null}++ <PaneSection title={t("society.card.limits")} testId="agent-pane-limits">+ <div className="flex flex-wrap items-end gap-4">+ <div className="flex flex-col gap-1.5">+ <span className="flex items-center gap-2 text-xs text-muted-foreground">+ <Switch+ checked={draft.budgetOn}+ onCheckedChange={(on) => setDraft((d) => ({ ...d, budgetOn: on }))}+ disabled={disabled}+ aria-label={t("society.card.budget_cap")}+ data-testid="agent-budget-switch"+ />+ {t("society.card.budget_cap")}+ </span>+ {draft.budgetOn ? (+ <span className="flex items-center gap-1 text-sm">+ <span className="text-muted-foreground">$</span>+ <input+ type="number"+ min={0}+ step={0.5}+ inputMode="decimal"+ disabled={disabled}+ value={draft.budget}+ onChange={(e) => setDraft((d) => ({ ...d, budget: e.target.value }))}+ data-testid="agent-budget-input"+ aria-label={t("society.card.budget_cap")}+ className="ap-input"+ />+ </span>+ ) : (+ <span className="py-1 text-sm text-muted-foreground">{t("society.card.no_cap")}</span>+ )}+ </div>+ <label className="flex flex-col gap-1.5">+ <span className="text-xs text-muted-foreground">{t("society.card.jobs_at_once")}</span>+ <input+ type="number"+ min={1}+ max={10}+ step={1}+ inputMode="numeric"+ disabled={disabled}+ value={draft.jobs}+ onChange={(e) => setDraft((d) => ({ ...d, jobs: e.target.value }))}+ data-testid="agent-jobs-input"+ className="ap-input"+ />+ </label>+ </div>+ <PaneHint>{t(draft.budgetOn ? "society.card.budget_hint" : "society.card.budget_off_hint")}</PaneHint>+ </PaneSection>++ <PaneSection title={t("society.agent_pane.browser")} testId="agent-pane-browser-access">+ <Segmented<BrowserMode>+ label={t("society.agent_pane.browser")}+ value={draft.browserMode}+ disabled={disabled}+ testId="agent-pane-browser-mode"+ options={[+ { value: "own", label: t("society.agent_pane.browser_own") },+ { value: "attach", label: t("society.agent_pane.browser_attach") },+ ]}+ onChange={(mode) => setDraft((d) => ({ ...d, browserMode: mode }))}+ />+ <PaneHint>{t(draft.browserMode === "own" ? "society.agent_pane.browser_own_hint" : "society.agent_pane.browser_attach_hint")}</PaneHint>+ <span className="text-xs font-medium text-foreground">{t("society.agent_pane.sites")}</span>+ <ChipList+ items={draft.domains}+ onChange={(items) => setDraft((d) => ({ ...d, domains: items }))}+ placeholder={t("society.agent_pane.site_placeholder")}+ addLabel={t("society.agent_pane.add")}+ removeLabel={t("society.agent_pane.remove")}+ normalize={normalizeDomain}+ disabled={disabled}+ emptyText={t("society.agent_pane.sites_any")}+ testId="agent-pane-sites"+ />+ </PaneSection>++ {!lead && !sample ? (+ <PaneSection title={t("society.card.where")} testId="agent-pane-placement">+ <PaneHint>{t("society.agent_pane.placement_hint")}</PaneHint>+ <AgentSandboxSection agent={agent} show="choice" />+ {agent.executionEnvironment !== "sandbox" ? <RunsOn agent={agent} /> : null}+ </PaneSection>+ ) : null}+ </div>++ {confirm ? (+ <div className="ap-savebar" data-tone="warn" role="alertdialog" aria-label={t("society.agent_pane.widen_title")} data-testid="agent-pane-widen">+ <div className="ap-widen">+ <strong className="text-xs font-semibold">{t("society.agent_pane.widen_title").replace("{0}", societyDisplayName(agent, assistantName))}</strong>+ <ul>+ {confirm.map((w) => (+ <li key={w.key}>{wideningText(w, t, labelOf)}</li>+ ))}+ </ul>+ </div>+ <span className="flex-1" />+ <button ref={confirmRef} type="button" className="ap-btn" data-variant="ghost" onClick={() => setConfirm(null)}>+ {t("society.agent_pane.go_back")}+ </button>+ <button type="button" className="ap-btn" data-variant="primary" onClick={() => void save(true)} data-testid="agent-pane-widen-confirm">+ {t("society.agent_pane.allow_and_save")}+ </button>+ </div>+ ) : dirty || error ? (+ <div className="ap-savebar" data-testid="agent-pane-savebar">+ {error ? (+ <span role="alert" className="min-w-0 flex-1 truncate text-xs text-destructive" title={error}>{error}</span>+ ) : (+ <span className="min-w-0 flex-1 text-xs text-muted-foreground">{t("society.agent_pane.unsaved")}</span>+ )}+ <button type="button" className="ap-btn" data-variant="ghost" disabled={saving} onClick={() => { setDraft(base); setError(""); }}>+ {t("society.agent_pane.discard")}+ </button>+ <button type="button" className="ap-btn" data-variant="primary" disabled={saving || !dirty || sample} onClick={() => void save(false)} data-testid="agent-pane-save">+ {t(saving ? "society.card.saving" : "society.card.save")}+ </button>+ </div>+ ) : null}+ </div>+ );+}++function wideningText(w: Widening, t: (key: string) => string, labelOf: (id: string) => string): string {+ const names = w.items.map(labelOf).join(", ");+ switch (w.key) {+ case "reach_all":+ return t("society.agent_pane.widen_reach_all");+ case "tools_added":+ return t("society.agent_pane.widen_tools").replace("{0}", names);+ case "unblocked":+ return t("society.agent_pane.widen_unblocked").replace("{0}", names);+ case "approval_mode":+ return t("society.agent_pane.widen_mode").replace("{0}", t(`society.approval_mode.${w.items[0]}`));+ case "ceiling":+ return t("society.agent_pane.widen_ceiling").replace("{0}", t(`society.ceiling.${w.items[0]}`));+ case "always_allow":+ return t("society.agent_pane.widen_allow").replace("{0}", w.items.join(", "));+ case "require_removed":+ return t("society.agent_pane.widen_require").replace("{0}", w.items.join(", "));+ case "browser_attach":+ return t("society.agent_pane.widen_browser");+ case "domains_opened":+ return w.items[0] === "*"+ ? t("society.agent_pane.widen_sites_any")+ : t("society.agent_pane.widen_sites").replace("{0}", w.items.join(", "));+ }+}++const KIND_ORDER = ["plugin", "mcp", "cli", "skill", "core"];++function ToolList({+ draft,+ catalog,+ loading,+ failed,+ disabled,+ onChange,+}: {+ draft: AccessDraft;+ catalog: Capability[];+ loading: boolean;+ failed: boolean;+ disabled: boolean;+ onChange: (id: string, state: ToolState) => void;+}) {+ const t = useT();+ const [query, setQuery] = useState("");+ const [all, setAll] = useState(false);+ const allowlist = draft.grantMode === "allowlist";++ const rows = useMemo(() => {+ const known = new Map(catalog.map((c) => [c.id, c]));+ // Ids the agent carries that the catalog no longer lists stay editable.+ for (const id of [...draft.focus, ...draft.grants, ...draft.denies]) {+ if (!known.has(id)) {+ known.set(id, { id, kind: capabilityKind(id) ?? "core", label: capabilityName(id), one_liner: "", risk_tier: "", connected: false, tool_name: "" });+ }+ }+ const rank = (c: Capability) => {+ const state = toolState(draft, c.id);+ if (state === "first") return 0;+ if (state === "blocked") return 2;+ if (allowlist && state === "on") return 1;+ return c.connected ? 3 : 4;+ };+ return [...known.values()].sort((a, b) => {+ const byState = rank(a) - rank(b);+ if (byState) return byState;+ if (rank(a) === 0) return draft.focus.indexOf(a.id) - draft.focus.indexOf(b.id);+ const byKind = KIND_ORDER.indexOf(String(a.kind)) - KIND_ORDER.indexOf(String(b.kind));+ return byKind || a.label.localeCompare(b.label);+ });+ // The order is fixed when the list opens or the search changes, so a row+ // the person just switched does not jump away from under the pointer.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [catalog, allowlist, query]);++ const needle = query.trim().toLowerCase();+ const filtered = needle+ ? rows.filter((c) => [c.id, c.label, c.one_liner, ...(c.aliases ?? [])].some((v) => v?.toLowerCase().includes(needle)))+ : rows;+ const shown = needle || all ? filtered : filtered.slice(0, TOOL_PREVIEW);++ const options: SegmentOption<ToolState>[] = [+ allowlist+ ? { value: "off", label: t("society.agent_pane.tool_off"), icon: Circle }+ : { value: "blocked", label: t("society.agent_pane.tool_block"), icon: Ban },+ { value: "on", label: t("society.agent_pane.tool_on"), icon: Check },+ { value: "first", label: t("society.agent_pane.tool_first"), icon: Star },+ ];++ return (+ <PaneSection title={t("society.agent_pane.tools")} testId="agent-pane-tool-list">+ <label className="ap-search">+ <Search className="h-3.5 w-3.5 shrink-0 text-muted-foreground" aria-hidden />+ <input+ type="search"+ value={query}+ placeholder={t("society.agent_pane.search_tools")}+ aria-label={t("society.agent_pane.search_tools")}+ onChange={(e) => setQuery(e.target.value)}+ />+ </label>+ {loading ? <PaneHint>{t("society.profile_card.loading")}</PaneHint> : null}+ {failed ? <PaneHint>{t("society.agent_pane.tools_unavailable")}</PaneHint> : null}+ {!loading && filtered.length === 0 ? <PaneHint>{t("society.profile_card.no_results")}</PaneHint> : null}+ <ul className="ap-tools">+ {shown.map((c) => {+ const state = toolState(draft, c.id);+ const brand = resolveToolBrand(c.tool_name || capabilityName(c.id));+ const label = brand.brandId ? brand.label : c.label;+ const shownState = allowlist && state === "blocked" ? "off" : state;+ return (+ <li key={c.id} className="ap-tool" data-state={state} data-testid={`agent-pane-tool-${c.id}`}>+ <span className="ap-tool-mark" aria-hidden>+ {brand.logoUrl ? <img src={brand.logoUrl} alt="" draggable={false} /> : brand.monogram}+ </span>+ <span className="min-w-0 flex-1" title={c.one_liner || c.id}>+ <span className="ap-tool-name">{label}</span>+ <span className="ap-tool-sub" data-off={c.connected ? undefined : "true"}>+ {c.connected ? (c.one_liner || c.id) : t("society.card.not_connected")}+ </span>+ </span>+ <Segmented<ToolState>+ label={label}+ size="sm"+ value={shownState}+ disabled={disabled}+ options={options}+ onChange={(next) => onChange(c.id, next)}+ />+ </li>+ );+ })}+ </ul>+ {!needle && filtered.length > TOOL_PREVIEW ? (+ <button type="button" className="ap-link self-start" onClick={() => setAll((v) => !v)}>+ {all ? t("society.agent_pane.show_less") : t("society.agent_pane.show_all").replace("{0}", String(filtered.length))}+ </button>+ ) : null}+ </PaneSection>+ );+}++/**+ * Where the agent's work executes — this computer or a connected one. The+ * change applies from the agent's next turn; a turn already running finishes+ * where it started.+ */+function RunsOn({ agent }: { agent: SocietyAgent }) {+ const t = useT();+ const setComputer = useSetAgentComputer();+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState("");+ return (+ <div className="flex flex-col gap-2" data-testid="agent-runs-on">+ <ComputerPicker+ value={agent.computerId ?? ""}+ labelClass="text-xs text-muted-foreground mb-1 block"+ testId="agent-runs-on-picker"+ onChange={(id) => {+ if (saving || id === (agent.computerId ?? "")) return;+ setSaving(true);+ setError("");+ setComputer(agent, id)+ .catch((err: unknown) => setError(err instanceof Error ? err.message : String(err)))+ .finally(() => setSaving(false));+ }}+ />+ {error ? <p role="alert" className="text-xs text-destructive">{error}</p> : null}+ {saving ? <p className="text-xs text-muted-foreground">{t("society.card.runs_on_saving")}</p> : null}+ </div>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/card/pane/accessDraft.test.ts b/dodaios/ui/web/frontend/src/components/society/card/pane/accessDraft.test.tsnew file mode 100644index 0000000000..fa2dbc04a5--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/card/pane/accessDraft.test.ts@@ -0,0 +1,83 @@+import { describe, expect, test } from "vitest";++import { agentConfigBody, type SocietyAgent } from "../../data";+import {+ draftFromAgent,+ normalizeDomain,+ patchFromDraft,+ setGrantMode,+ setToolState,+ toolState,+ widenings,+} from "./accessDraft";++const BASE = {+ agentId: "mail",+ name: "Mail",+ tier: "specialist",+ grantMode: "all",+ toolGrants: [],+ focus: ["plugin:gmail"],+ denies: ["cli:gh"],+ approvalRules: { requireApproval: ["plugin:gmail:send"], alwaysAllow: [] },+ permissionCeiling: "monitor",+ approvalMode: "ask",+ dailyBudgetUsd: 2,+ maxConcurrentRuns: 1,+ browserMode: "own",+ browserAllowedDomains: ["mail.google.com"],+} as unknown as SocietyAgent;++describe("access draft", () => {+ test("an untouched draft sends nothing", () => {+ expect(patchFromDraft(BASE, draftFromAgent(BASE))).toEqual({});+ expect(widenings(BASE, draftFromAgent(BASE))).toEqual([]);+ });++ test("tool states move between denies, focus and grants", () => {+ let draft = draftFromAgent(BASE);+ expect(toolState(draft, "plugin:gmail")).toBe("first");+ expect(toolState(draft, "cli:gh")).toBe("blocked");+ expect(toolState(draft, "plugin:notion")).toBe("on");+ draft = setToolState(draft, "plugin:notion", "first");+ expect(draft.focus).toEqual(["plugin:gmail", "plugin:notion"]);+ draft = setToolState(draft, "plugin:gmail", "blocked");+ expect(draft.focus).toEqual(["plugin:notion"]);+ expect(draft.denies).toContain("plugin:gmail");+ expect(patchFromDraft(BASE, draft)).toEqual({ focus: ["plugin:notion"], denies: ["cli:gh", "plugin:gmail"] });+ });++ test("moving to an allow-list keeps the focus tools as its hands", () => {+ const draft = setGrantMode(draftFromAgent(BASE), "allowlist");+ expect(draft.grants).toEqual(["plugin:gmail"]);+ expect(toolState(draft, "plugin:notion")).toBe("off");+ expect(widenings(BASE, draft)).toEqual([]);+ });++ test("every widening is named; a narrowing is not", () => {+ let draft = draftFromAgent(BASE);+ draft = setToolState(draft, "cli:gh", "on");+ draft = { ...draft, approvalMode: "bypass", permissionCeiling: "ask", alwaysAllow: ["plugin:gmail:send"], requireApproval: [] };+ draft = { ...draft, browserMode: "attach", domains: [] };+ expect(widenings(BASE, draft).map((w) => w.key)).toEqual([+ "unblocked", "approval_mode", "ceiling", "always_allow", "require_removed", "browser_attach", "domains_opened",+ ]);+ const stricter = { ...draftFromAgent(BASE), approvalMode: "always_ask" as const, permissionCeiling: "safe" as const };+ expect(widenings(BASE, stricter)).toEqual([]);+ });++ test("the patch maps onto the route's field names", () => {+ const draft = { ...draftFromAgent(BASE), budgetOn: false, jobs: "3", domains: ["example.com"] };+ expect(agentConfigBody(patchFromDraft(BASE, draft))).toEqual({+ daily_budget_usd: 0,+ max_concurrent_runs: 3,+ browser_allowed_domains: ["example.com"],+ });+ });++ test("pasted sites become bare host names", () => {+ expect(normalizeDomain("https://Mail.Google.com/u/0/#inbox")).toBe("mail.google.com");+ expect(normalizeDomain("example.com:8080")).toBe("example.com");+ expect(normalizeDomain("not a site")).toBe("");+ });+});diff --git a/dodaios/ui/web/frontend/src/components/society/card/pane/accessDraft.ts b/dodaios/ui/web/frontend/src/components/society/card/pane/accessDraft.tsnew file mode 100644index 0000000000..9705c2d1d7--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/card/pane/accessDraft.ts@@ -0,0 +1,186 @@+/**+ * The Tools & access tab as plain data: a draft of everything the tab edits,+ * the one-tool state machine, the PATCH that carries only what changed, and+ * the list of changes that WIDEN what the agent may do (those ask first).+ *+ * Kept free of React so every rule here is unit-tested on its own.+ */+import type { AgentApprovalMode, BrowserMode } from "@/lib/societyApi";++import type { AgentConfigPatch, GrantMode, PermissionCeiling, SocietyAgent } from "../../data";++export interface AccessDraft {+ grantMode: GrantMode;+ grants: string[];+ focus: string[];+ denies: string[];+ approvalMode: AgentApprovalMode | null;+ permissionCeiling: PermissionCeiling;+ requireApproval: string[];+ alwaysAllow: string[];+ budgetOn: boolean;+ /** Kept as typed text so a half-typed number is not reformatted under the cursor. */+ budget: string;+ jobs: string;+ browserMode: BrowserMode;+ domains: string[];+}++/** How one capability stands for this agent. `off` exists only on an allow-list. */+export type ToolState = "blocked" | "off" | "on" | "first";++export function draftFromAgent(agent: SocietyAgent): AccessDraft {+ return {+ grantMode: agent.grantMode,+ grants: [...agent.toolGrants],+ focus: [...agent.focus],+ denies: [...agent.denies],+ approvalMode: agent.approvalMode ?? null,+ permissionCeiling: agent.permissionCeiling,+ requireApproval: [...agent.approvalRules.requireApproval],+ alwaysAllow: [...agent.approvalRules.alwaysAllow],+ budgetOn: agent.dailyBudgetUsd > 0,+ budget: String(agent.dailyBudgetUsd > 0 ? agent.dailyBudgetUsd : 2),+ jobs: String(agent.maxConcurrentRuns),+ browserMode: agent.browserMode ?? "own",+ domains: [...(agent.browserAllowedDomains ?? [])],+ };+}++export function toolState(draft: AccessDraft, id: string): ToolState {+ if (draft.denies.includes(id)) return "blocked";+ if (draft.focus.includes(id)) return "first";+ if (draft.grantMode === "allowlist") return draft.grants.includes(id) ? "on" : "off";+ return "on";+}++const without = (list: string[], id: string) => list.filter((x) => x !== id);+const withId = (list: string[], id: string) => (list.includes(id) ? list : [...list, id]);++export function setToolState(draft: AccessDraft, id: string, state: ToolState): AccessDraft {+ const allowlist = draft.grantMode === "allowlist";+ switch (state) {+ case "blocked":+ return { ...draft, denies: withId(draft.denies, id), focus: without(draft.focus, id), grants: without(draft.grants, id) };+ case "off":+ return { ...draft, denies: without(draft.denies, id), focus: without(draft.focus, id), grants: without(draft.grants, id) };+ case "on":+ return {+ ...draft,+ denies: without(draft.denies, id),+ focus: without(draft.focus, id),+ grants: allowlist ? withId(draft.grants, id) : draft.grants,+ };+ case "first":+ return {+ ...draft,+ denies: without(draft.denies, id),+ focus: withId(draft.focus, id),+ grants: allowlist ? withId(draft.grants, id) : draft.grants,+ };+ }+}++/**+ * Switch between "everything connected" and "only what I pick". Moving to an+ * allow-list starts from the tools the agent reaches for first, so it is never+ * left with no hands by one click.+ */+export function setGrantMode(draft: AccessDraft, mode: GrantMode): AccessDraft {+ if (mode === draft.grantMode) return draft;+ if (mode === "allowlist" && draft.grants.length === 0) {+ return { ...draft, grantMode: mode, grants: [...draft.focus] };+ }+ return { ...draft, grantMode: mode };+}++const sameList = (a: string[], b: string[]) => a.length === b.length && a.every((x, i) => x === b[i]);+const sameSet = (a: string[], b: string[]) => a.length === b.length && a.every((x) => b.includes(x));++export function budgetValue(draft: AccessDraft): number {+ return draft.budgetOn ? Math.max(0, Number.parseFloat(draft.budget) || 0) : 0;+}++export function jobsValue(draft: AccessDraft): number {+ return Math.min(10, Math.max(1, Number.parseInt(draft.jobs, 10) || 1));+}++/** Only the fields that differ from the agent: a budget edit never carries prose or tools along. */+export function patchFromDraft(agent: SocietyAgent, draft: AccessDraft): AgentConfigPatch {+ const patch: AgentConfigPatch = {};+ if (draft.grantMode !== agent.grantMode) patch.grantMode = draft.grantMode;+ if (!sameSet(draft.grants, agent.toolGrants)) patch.toolGrants = draft.grants;+ if (!sameList(draft.focus, agent.focus)) patch.focus = draft.focus;+ if (!sameSet(draft.denies, agent.denies)) patch.denies = draft.denies;+ if (draft.approvalMode && draft.approvalMode !== (agent.approvalMode ?? null)) patch.approvalMode = draft.approvalMode;+ if (draft.permissionCeiling !== agent.permissionCeiling) patch.permissionCeiling = draft.permissionCeiling;+ if (+ !sameSet(draft.requireApproval, agent.approvalRules.requireApproval) ||+ !sameSet(draft.alwaysAllow, agent.approvalRules.alwaysAllow)+ ) {+ patch.approvalRules = { requireApproval: draft.requireApproval, alwaysAllow: draft.alwaysAllow };+ }+ if (budgetValue(draft) !== agent.dailyBudgetUsd) patch.dailyBudgetUsd = budgetValue(draft);+ if (jobsValue(draft) !== agent.maxConcurrentRuns) patch.maxConcurrentRuns = jobsValue(draft);+ if (draft.browserMode !== (agent.browserMode ?? "own")) patch.browserMode = draft.browserMode;+ if (!sameSet(draft.domains, agent.browserAllowedDomains ?? [])) patch.browserAllowedDomains = draft.domains;+ return patch;+}++export function isDirty(agent: SocietyAgent, draft: AccessDraft): boolean {+ return Object.keys(patchFromDraft(agent, draft)).length > 0;+}++/** One change that lets the agent do more than before. `items` names what, when that helps. */+export interface Widening {+ key:+ | "reach_all"+ | "tools_added"+ | "unblocked"+ | "approval_mode"+ | "ceiling"+ | "always_allow"+ | "require_removed"+ | "browser_attach"+ | "domains_opened";+ items: string[];+}++const MODE_RANK: Record<AgentApprovalMode, number> = { always_ask: 0, ask: 1, bypass: 2 };+const CEILING_RANK: Record<PermissionCeiling, number> = { safe: 0, monitor: 1, ask: 2 };++export function widenings(agent: SocietyAgent, draft: AccessDraft): Widening[] {+ const out: Widening[] = [];+ if (agent.grantMode === "allowlist" && draft.grantMode === "all") out.push({ key: "reach_all", items: [] });+ if (draft.grantMode === "allowlist") {+ const added = draft.grants.filter((id) => agent.grantMode === "allowlist" && !agent.toolGrants.includes(id));+ if (added.length) out.push({ key: "tools_added", items: added });+ }+ const unblocked = agent.denies.filter((id) => !draft.denies.includes(id));+ if (unblocked.length) out.push({ key: "unblocked", items: unblocked });+ if (draft.approvalMode && agent.approvalMode && MODE_RANK[draft.approvalMode] > MODE_RANK[agent.approvalMode]) {+ out.push({ key: "approval_mode", items: [draft.approvalMode] });+ }+ if (CEILING_RANK[draft.permissionCeiling] > CEILING_RANK[agent.permissionCeiling]) {+ out.push({ key: "ceiling", items: [draft.permissionCeiling] });+ }+ const allowed = draft.alwaysAllow.filter((p) => !agent.approvalRules.alwaysAllow.includes(p));+ if (allowed.length) out.push({ key: "always_allow", items: allowed });+ const unasked = agent.approvalRules.requireApproval.filter((p) => !draft.requireApproval.includes(p));+ if (unasked.length) out.push({ key: "require_removed", items: unasked });+ if ((agent.browserMode ?? "own") === "own" && draft.browserMode === "attach") out.push({ key: "browser_attach", items: [] });+ const before = agent.browserAllowedDomains ?? [];+ if (before.length > 0) {+ const opened = draft.domains.length === 0 ? ["*"] : draft.domains.filter((d) => !before.includes(d));+ if (opened.length) out.push({ key: "domains_opened", items: opened });+ }+ return out;+}++/** "example.com" from what a person pastes: a URL, a host with a path, mixed case. */+export function normalizeDomain(raw: string): string {+ const text = raw.trim().toLowerCase();+ if (!text) return "";+ const host = text.replace(/^[a-z]+:\/\//, "").split(/[/?#]/)[0].replace(/:\d+$/, "");+ return /^[a-z0-9*][a-z0-9.*-]*\.[a-z0-9-]+$/.test(host) ? host : "";+}diff --git a/dodaios/ui/web/frontend/src/components/society/card/pane/agentPane.css b/dodaios/ui/web/frontend/src/components/society/card/pane/agentPane.cssnew file mode 100644index 0000000000..d975ea885d--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/card/pane/agentPane.css@@ -0,0 +1,704 @@+/*+ * The agent pane: one calm column for everything about one agent.+ *+ * Chrome is neutral; the agent's own colour (`--ap-agent`, set from its+ * palette on the root) is the only decorative hue, and it marks just two+ * things: the active tab and the avatar ring. Every other colour is a theme+ * token, so light and dark both follow the app. Motion stays between 120 and+ * 200 ms and switches off under reduced motion.+ */++.ap-root {+ --ap-radius-sm: 6px;+ --ap-radius: 10px;+ --ap-radius-lg: 12px;+ display: flex;+ height: 100%;+ min-height: 0;+ flex-direction: column;+ background: hsl(var(--sidebar));+ border-left: 1px solid hsl(var(--border));+ color: hsl(var(--foreground));+ container: agent-pane / inline-size;+}++/* ---------------------------------------------------------------- header */++.ap-head {+ display: flex;+ flex-shrink: 0;+ align-items: center;+ gap: 10px;+ padding: 12px 10px 8px 12px;+}++.ap-avatar {+ position: relative;+ flex-shrink: 0;+ border-radius: 10px;+ box-shadow: 0 0 0 1.5px hsl(var(--sidebar)), 0 0 0 3px var(--ap-agent, hsl(var(--border-strong)));+}++.ap-name {+ display: block;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 14px;+ font-weight: 600;+ letter-spacing: -0.01em;+ color: hsl(var(--foreground-strong));+}++.ap-meta {+ display: flex;+ min-width: 0;+ align-items: center;+ gap: 6px;+ font-size: 12px;+ color: hsl(var(--muted-foreground));+}++.ap-dot {+ width: 7px;+ height: 7px;+ flex-shrink: 0;+ border-radius: 999px;+ background: hsl(var(--muted-foreground) / 0.45);+}+.ap-dot[data-state="working"] { background: hsl(var(--success)); }+.ap-dot[data-state="waiting"] { background: hsl(var(--warning)); }+.ap-dot[data-state="paused"] { background: hsl(var(--muted-foreground) / 0.25); }++.ap-icon-btn {+ display: inline-flex;+ height: 28px;+ width: 28px;+ flex-shrink: 0;+ align-items: center;+ justify-content: center;+ border-radius: var(--ap-radius-sm);+ color: hsl(var(--muted-foreground));+ transition: background-color 120ms ease, color 120ms ease;+}+.ap-icon-btn:hover:not(:disabled) {+ background: hsl(var(--secondary));+ color: hsl(var(--foreground));+}+.ap-icon-btn:focus-visible {+ outline: none;+ box-shadow: 0 0 0 2px hsl(var(--ring));+}+.ap-icon-btn:disabled { opacity: 0.4; }++.ap-menu {+ position: absolute;+ right: 0;+ top: calc(100% + 4px);+ z-index: 20;+ width: 232px;+ border: 1px solid hsl(var(--border));+ border-radius: var(--ap-radius-lg);+ background: hsl(var(--popover));+ padding: 4px;+ /* Depth comes from .shadow-float on the element (index.css doctrine). */+}++.ap-menu-item {+ display: flex;+ width: 100%;+ align-items: center;+ gap: 8px;+ border-radius: var(--ap-radius-sm);+ padding: 7px 8px;+ text-align: left;+ font-size: 13px;+ color: hsl(var(--foreground));+}+.ap-menu-item:hover:not(:disabled) { background: hsl(var(--secondary)); }+.ap-menu-item:disabled { opacity: 0.5; }+.ap-menu-sep {+ margin: 4px 2px;+ height: 1px;+ background: hsl(var(--border));+}++/* ------------------------------------------------------------------ tabs */++.ap-tabs {+ display: flex;+ flex-shrink: 0;+ align-items: center;+ gap: 2px;+ border-bottom: 1px solid hsl(var(--border));+ padding: 0 8px;+ overflow-x: auto;+ scrollbar-width: none;+}+.ap-tabs::-webkit-scrollbar { display: none; }++.ap-tab {+ position: relative;+ display: inline-flex;+ flex-shrink: 0;+ height: 34px;+ min-width: 30px;+ align-items: center;+ justify-content: center;+ gap: 6px;+ border-radius: var(--ap-radius-sm) var(--ap-radius-sm) 0 0;+ padding: 0 7px;+ font-size: 12.5px;+ font-weight: 500;+ color: hsl(var(--muted-foreground));+ transition: color 120ms ease, background-color 120ms ease;+}+.ap-tab:hover { color: hsl(var(--foreground)); }+.ap-tab:focus-visible {+ outline: none;+ box-shadow: inset 0 0 0 2px hsl(var(--ring));+}+.ap-tab[data-state="active"] { color: hsl(var(--foreground-strong)); }+.ap-tab[data-state="active"]::after {+ content: "";+ position: absolute;+ left: 6px;+ right: 6px;+ bottom: -1px;+ height: 2px;+ border-radius: 2px;+ background: var(--ap-agent, hsl(var(--foreground-strong)));+}+.ap-tab-label { white-space: nowrap; }+.ap-tab[data-state="inactive"] .ap-tab-label { display: none; }+.ap-tab-badge {+ position: absolute;+ right: 3px;+ top: 6px;+ width: 6px;+ height: 6px;+ border-radius: 999px;+ background: hsl(var(--warning));+}++/* A wide pane has room for every label. */+@container agent-pane (min-width: 400px) {+ .ap-tab[data-state="inactive"] .ap-tab-label { display: inline; }+}++/* ------------------------------------------------------- sub-page header */++.ap-sub {+ display: flex;+ flex-shrink: 0;+ align-items: center;+ gap: 4px;+ border-bottom: 1px solid hsl(var(--border));+ padding: 4px 8px;+ font-size: 13px;+ font-weight: 600;+ color: hsl(var(--foreground-strong));+}++/* ------------------------------------------------------------------ body */++.ap-body {+ display: flex;+ min-height: 0;+ flex: 1;+ flex-direction: column;+ gap: 18px;+ overflow-y: auto;+ padding: 12px 12px 16px;+ animation: ap-in 160ms ease-out;+}+.ap-body[data-fill="true"] { gap: 12px; }++@keyframes ap-in {+ from { opacity: 0; transform: translateY(2px); }+ to { opacity: 1; transform: none; }+}++.ap-section { display: flex; flex-direction: column; gap: 8px; }+.ap-section-head {+ display: flex;+ min-height: 22px;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+}+.ap-section-title {+ font-size: 11.5px;+ font-weight: 600;+ letter-spacing: 0.02em;+ color: hsl(var(--muted-foreground));+}+.ap-hint {+ font-size: 12px;+ line-height: 1.45;+ color: hsl(var(--muted-foreground));+}++.ap-link {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ border-radius: var(--ap-radius-sm);+ padding: 2px 6px;+ font-size: 12px;+ font-weight: 500;+ color: hsl(var(--muted-foreground));+}+.ap-link:hover:not(:disabled) { background: hsl(var(--secondary)); color: hsl(var(--foreground)); }+.ap-link:disabled { opacity: 0.5; }++/* --------------------------------------------------------------- identity */++.ap-inline {+ display: flex;+ min-width: 0;+ max-width: 100%;+ align-items: center;+ border-radius: var(--ap-radius-sm);+ margin: -2px -6px;+ padding: 2px 6px;+ text-align: left;+ transition: background-color 120ms ease;+}+.ap-inline:hover:not(:disabled) { background: hsl(var(--secondary)); }+.ap-inline:disabled { cursor: default; }+.ap-inline-empty { color: hsl(var(--muted-foreground)); }++.ap-instructions {+ position: relative;+ max-height: 7.6em;+ overflow: hidden;+ white-space: pre-line;+ font-size: 13px;+ line-height: 1.45;+ color: hsl(var(--foreground));+}+.ap-instructions[data-long="true"]::after {+ content: "";+ position: absolute;+ inset: auto 0 0 0;+ height: 2.2em;+ background: linear-gradient(to bottom, transparent, hsl(var(--sidebar)));+}++.ap-seat {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 6px;+ font-size: 12px;+ color: hsl(var(--muted-foreground));+}+.ap-seat-pill {+ display: inline-flex;+ max-width: 100%;+ align-items: center;+ gap: 5px;+ border: 1px solid hsl(var(--border));+ border-radius: 999px;+ padding: 1px 8px 1px 4px;+ color: hsl(var(--foreground));+}++/* --------------------------------------------------------- anatomy rows */++.ap-rows {+ display: flex;+ flex-direction: column;+ overflow: hidden;+ border: 1px solid hsl(var(--border));+ border-radius: var(--ap-radius-lg);+ background: hsl(var(--card));+}++.ap-row {+ display: flex;+ min-height: 44px;+ width: 100%;+ align-items: center;+ gap: 10px;+ padding: 7px 10px;+ text-align: left;+ transition: background-color 120ms ease;+}+.ap-row + .ap-row { border-top: 1px solid hsl(var(--border)); }+button.ap-row:hover { background: hsl(var(--secondary)); }+button.ap-row:focus-visible { outline: none; box-shadow: inset 0 0 0 2px hsl(var(--ring)); }++.ap-row-icon {+ display: inline-flex;+ height: 26px;+ width: 26px;+ flex-shrink: 0;+ align-items: center;+ justify-content: center;+ border-radius: 8px;+ background: hsl(var(--secondary));+ color: hsl(var(--foreground-secondary, var(--foreground)));+}+.ap-row-label {+ display: block;+ font-size: 13px;+ font-weight: 500;+ color: hsl(var(--foreground));+}+.ap-row-detail {+ display: block;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 11.5px;+ color: hsl(var(--muted-foreground));+}+.ap-row-count {+ flex-shrink: 0;+ font-size: 12px;+ font-variant-numeric: tabular-nums;+ color: hsl(var(--muted-foreground));+}+.ap-row-count[data-attention="true"] {+ border-radius: 999px;+ box-shadow: inset 0 0 0 1px hsl(var(--warning));+ padding: 0 7px;+ color: hsl(var(--foreground-strong));+}+.ap-row-chevron { flex-shrink: 0; color: hsl(var(--muted-foreground)); opacity: 0.6; }+button.ap-row:hover .ap-row-chevron { opacity: 1; }++/* ------------------------------------------------------------ suggestions */++.ap-suggest {+ display: flex;+ align-items: center;+ gap: 8px;+ border: 1px solid hsl(var(--border));+ border-radius: var(--ap-radius);+ padding: 6px 6px 6px 10px;+ font-size: 12.5px;+}+.ap-suggest-go {+ min-width: 0;+ flex: 1;+ text-align: left;+ color: hsl(var(--foreground));+}+.ap-suggest-go:hover { text-decoration: underline; text-underline-offset: 2px; }++/* -------------------------------------------------------------- record */++.ap-stats {+ display: grid;+ grid-template-columns: repeat(3, minmax(0, 1fr));+ gap: 6px;+}+.ap-stat {+ min-width: 0;+ border-radius: var(--ap-radius);+ background: hsl(var(--card));+ border: 1px solid hsl(var(--border));+ padding: 7px 9px;+}+.ap-stat-label {+ display: block;+ font-size: 11px;+ color: hsl(var(--muted-foreground));+}+.ap-stat-value {+ display: block;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 13px;+ font-weight: 600;+ font-variant-numeric: tabular-nums;+ color: hsl(var(--foreground));+}++.ap-meter {+ position: relative;+ height: 4px;+ overflow: hidden;+ border-radius: 999px;+ background: hsl(var(--secondary));+}+.ap-meter-fill {+ position: absolute;+ inset: 0 auto 0 0;+ border-radius: 999px;+ background: hsl(var(--foreground) / 0.55);+ transition: width 200ms ease;+}+.ap-meter[data-full="true"] .ap-meter-fill { background: hsl(var(--warning)); }++/* ----------------------------------------------------- segmented control */++.ap-seg {+ display: inline-flex;+ max-width: 100%;+ flex-wrap: wrap;+ gap: 2px;+ border-radius: 8px;+ background: hsl(var(--card));+ border: 1px solid hsl(var(--border));+ padding: 2px;+}+.ap-seg-item {+ display: inline-flex;+ height: 24px;+ align-items: center;+ justify-content: center;+ gap: 5px;+ border-radius: 6px;+ padding: 0 9px;+ font-size: 12px;+ font-weight: 500;+ color: hsl(var(--muted-foreground));+ transition: background-color 120ms ease, color 120ms ease;+}+.ap-seg[data-size="sm"] .ap-seg-item { height: 22px; min-width: 24px; padding: 0 5px; }+.ap-seg-item:hover:not(:disabled) { color: hsl(var(--foreground)); }+.ap-seg-item[aria-checked="true"] {+ background: hsl(var(--secondary));+ color: hsl(var(--foreground-strong));+ box-shadow: inset 0 1px 0 rgb(var(--sheen-rgb) / 0.05), 0 0 0 1px hsl(var(--border-strong) / 0.5);+}+.ap-seg-item[aria-checked="true"][data-value="blocked"] { color: hsl(var(--destructive)); }+.ap-seg-item:disabled { opacity: 0.4; cursor: not-allowed; }+.ap-seg-item:focus-visible { outline: none; box-shadow: 0 0 0 2px hsl(var(--ring)); }++/* --------------------------------------------------------------- tools */++.ap-search {+ display: flex;+ align-items: center;+ gap: 6px;+ border: 1px solid hsl(var(--border));+ border-radius: 8px;+ background: hsl(var(--background));+ padding: 0 8px;+}+.ap-search input {+ height: 30px;+ min-width: 0;+ flex: 1;+ background: transparent;+ font-size: 12.5px;+ color: hsl(var(--foreground));+ outline: none;+}++.ap-tools { display: flex; flex-direction: column; }+.ap-tool {+ display: flex;+ min-height: 36px;+ align-items: center;+ gap: 8px;+ border-radius: 8px;+ padding: 3px 4px 3px 6px;+}+.ap-tool:hover { background: hsl(var(--secondary)); }+.ap-tool[data-state="blocked"] .ap-tool-name { text-decoration: line-through; opacity: 0.6; }+.ap-tool[data-state="off"] .ap-tool-name { color: hsl(var(--muted-foreground)); }+.ap-tool-mark {+ display: inline-flex;+ height: 22px;+ width: 22px;+ flex-shrink: 0;+ align-items: center;+ justify-content: center;+ overflow: hidden;+ border-radius: 6px;+ background: hsl(var(--plugin-icon-surface, var(--card)));+ border: 1px solid hsl(var(--border));+ font-size: 10px;+ font-weight: 700;+ text-transform: uppercase;+ color: hsl(var(--muted-foreground));+}+.ap-tool-mark img { height: 100%; width: 100%; object-fit: contain; padding: 3px; }+.ap-tool-name {+ display: block;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 12.5px;+ color: hsl(var(--foreground));+}+.ap-tool-sub {+ display: block;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 11px;+ color: hsl(var(--muted-foreground));+}+.ap-tool-sub[data-off="true"] { color: hsl(var(--warning)); }++/* --------------------------------------------------------------- chips */++.ap-chips { display: flex; flex-direction: column; gap: 6px; }+.ap-chip {+ display: inline-flex;+ max-width: 100%;+ align-items: center;+ gap: 4px;+ border: 1px solid hsl(var(--border));+ border-radius: 999px;+ background: hsl(var(--card));+ padding: 1px 4px 1px 9px;+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 11.5px;+ color: hsl(var(--foreground));+}+.ap-chip-x {+ display: inline-flex;+ height: 18px;+ width: 18px;+ align-items: center;+ justify-content: center;+ border-radius: 999px;+ color: hsl(var(--muted-foreground));+}+.ap-chip-x:hover { background: hsl(var(--secondary)); color: hsl(var(--foreground)); }+.ap-chip-add { display: flex; align-items: center; gap: 4px; }+.ap-chip-suggest {+ gap: 4px;+ padding: 1px 9px 1px 6px;+ color: hsl(var(--muted-foreground));+ border-style: dashed;+}+.ap-chip-suggest:hover { color: hsl(var(--foreground)); border-style: solid; }++.ap-input {+ height: 30px;+ min-width: 0;+ flex: 1;+ border: 1px solid hsl(var(--border));+ border-radius: 8px;+ background: hsl(var(--background));+ padding: 0 9px;+ font-size: 12.5px;+ color: hsl(var(--foreground));+ outline: none;+ transition: border-color 120ms ease, box-shadow 120ms ease;+}+.ap-input:focus { border-color: hsl(var(--border-strong)); box-shadow: 0 0 0 3px hsl(var(--ring) / 0.18); }+.ap-input:disabled { opacity: 0.55; }+textarea.ap-input { height: auto; padding: 8px 10px; line-height: 1.5; resize: vertical; }+.ap-input[type="number"] { width: 84px; flex: none; font-variant-numeric: tabular-nums; }++/* ------------------------------------------------------------ save bar */++.ap-savebar {+ display: flex;+ flex-shrink: 0;+ flex-wrap: wrap;+ align-items: center;+ gap: 6px;+ border-top: 1px solid hsl(var(--border));+ background: hsl(var(--popover));+ padding: 8px 10px;+ box-shadow: inset 0 1px 0 rgb(var(--sheen-rgb) / 0.05);+ animation: ap-rise 160ms ease-out;+}+@keyframes ap-rise {+ from { opacity: 0; transform: translateY(6px); }+ to { opacity: 1; transform: none; }+}+.ap-savebar[data-tone="warn"] { border-top-color: hsl(var(--warning) / 0.6); }++.ap-btn {+ display: inline-flex;+ height: 28px;+ align-items: center;+ justify-content: center;+ gap: 6px;+ border-radius: 8px;+ padding: 0 11px;+ font-size: 12.5px;+ font-weight: 500;+ transition: background-color 120ms ease, opacity 120ms ease;+}+.ap-btn:disabled { opacity: 0.5; }+.ap-btn:focus-visible { outline: none; box-shadow: 0 0 0 2px hsl(var(--ring)); }+.ap-btn[data-variant="primary"] { background: hsl(var(--primary)); color: hsl(var(--primary-foreground)); }+.ap-btn[data-variant="primary"]:hover:not(:disabled) { opacity: 0.9; }+.ap-btn[data-variant="ghost"] { color: hsl(var(--foreground)); }+.ap-btn[data-variant="ghost"]:hover:not(:disabled) { background: hsl(var(--secondary)); }+.ap-btn[data-variant="outline"] { border: 1px solid hsl(var(--border)); color: hsl(var(--foreground)); }+.ap-btn[data-variant="outline"]:hover:not(:disabled) { background: hsl(var(--secondary)); }++.ap-widen {+ display: flex;+ flex-direction: column;+ gap: 4px;+ width: 100%;+ font-size: 12px;+ color: hsl(var(--foreground));+}+.ap-widen ul { display: flex; flex-direction: column; gap: 2px; padding-left: 14px; list-style: disc; }+.ap-widen li { color: hsl(var(--muted-foreground)); }++/* -------------------------------------------------------- review queue */++.ap-review {+ display: flex;+ flex-direction: column;+ gap: 6px;+ border: 1px solid hsl(var(--border));+ border-radius: var(--ap-radius-lg);+ background: hsl(var(--card));+ padding: 9px 10px;+}+.ap-review-kind {+ font-size: 11px;+ font-weight: 600;+ color: hsl(var(--muted-foreground));+}+.ap-review-text {+ font-size: 12.5px;+ line-height: 1.4;+ color: hsl(var(--foreground));+}+.ap-diff {+ display: flex;+ flex-direction: column;+ overflow: hidden;+ border-radius: var(--ap-radius-sm);+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 11px;+ line-height: 1.5;+}+.ap-diff span {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: pre;+ padding: 0 6px;+ color: hsl(var(--muted-foreground));+}+.ap-diff span[data-op="+"] { background: hsl(var(--diff-add-bg) / 0.18); color: hsl(var(--diff-add)); }+.ap-diff span[data-op="-"] { background: hsl(var(--diff-del-bg) / 0.18); color: hsl(var(--diff-del)); }+.ap-diff[data-open="true"] span { white-space: pre-wrap; }++/* ---------------------------------------------------------- file viewer */++.ap-file {+ min-height: 0;+ overflow-wrap: anywhere;+ font-size: 13px;+}++@media (prefers-reduced-motion: reduce) {+ .ap-body,+ .ap-savebar { animation: none; }+ .ap-tab,+ .ap-row,+ .ap-seg-item,+ .ap-icon-btn,+ .ap-meter-fill { transition: none; }+}diff --git a/dodaios/ui/web/frontend/src/components/society/card/pane/paneState.ts b/dodaios/ui/web/frontend/src/components/society/card/pane/paneState.tsnew file mode 100644index 0000000000..853799bce8--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/card/pane/paneState.ts@@ -0,0 +1,99 @@+/**+ * What the agent pane remembers between visits: the open tab (one for every+ * agent, so "I manage tools now" carries over when the person switches agents)+ * and the next-step suggestions the person dismissed (per agent).+ *+ * Browser storage is a convenience here, never a source of truth: every read+ * and write is guarded, and the pane works the same with storage blocked.+ */+import { useCallback, useState } from "react";++export const PANE_TABS = ["overview", "tools", "memory", "tasks", "browser", "history"] as const;+export type PaneTab = (typeof PANE_TABS)[number];++const TAB_KEY = "society.agentPane.tab";+const DISMISSED_KEY = "society.agentPane.dismissed";++function read(key: string): string | null {+ try {+ return window.localStorage.getItem(key);+ } catch {+ return null;+ }+}++function write(key: string, value: string): void {+ try {+ window.localStorage.setItem(key, value);+ } catch {+ /* storage blocked: the choice lasts for this view only */+ }+}++export function isPaneTab(value: unknown): value is PaneTab {+ return typeof value === "string" && (PANE_TABS as readonly string[]).includes(value);+}++export function readStoredTab(): PaneTab {+ const stored = read(TAB_KEY);+ return isPaneTab(stored) ? stored : "overview";+}++/** The open tab, persisted. `available` drops tabs this agent does not have (History is lead-only). */+export function usePaneTab(available: readonly PaneTab[]): [PaneTab, (tab: PaneTab) => void] {+ const [tab, setTab] = useState<PaneTab>(readStoredTab);+ const choose = useCallback((next: PaneTab) => {+ setTab(next);+ write(TAB_KEY, next);+ }, []);+ return [available.includes(tab) ? tab : "overview", choose];+}++function readDismissed(): Record<string, string[]> {+ const raw = read(DISMISSED_KEY);+ if (!raw) return {};+ try {+ const parsed = JSON.parse(raw) as unknown;+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, string[]>) : {};+ } catch {+ return {};+ }+}++/** The suggestion ids this person dismissed for one agent, plus a way to dismiss another. */+export function useDismissedSuggestions(agentId: string): [Set<string>, (id: string) => void] {+ const [all, setAll] = useState(readDismissed);+ const dismiss = useCallback((id: string) => {+ setAll((prev) => {+ // A counted id ("review:3") replaces its older counts, so the list stays small.+ const family = id.includes(":") ? `${id.split(":")[0]}:` : null;+ const kept = (prev[agentId] ?? []).filter((x) => !family || !x.startsWith(family));+ const next = { ...prev, [agentId]: [...new Set([...kept, id])] };+ write(DISMISSED_KEY, JSON.stringify(next));+ return next;+ });+ }, [agentId]);+ return [new Set(all[agentId] ?? []), dismiss];+}++/** One level of in-pane drill-down: a sub-page with a title and a way back. */+export interface PanePage {+ id: string;+ title: string;+}++/** A small stack of sub-pages; the pane header shows Back while it is not empty. */+export function usePaneStack(): {+ page: PanePage | null;+ push: (page: PanePage) => void;+ back: () => void;+ reset: () => void;+} {+ const [stack, setStack] = useState<PanePage[]>([]);+ return {+ page: stack.length ? stack[stack.length - 1] : null,+ push: useCallback((page: PanePage) => setStack((prev) => [...prev, page]), []),+ back: useCallback(() => setStack((prev) => prev.slice(0, -1)), []),+ reset: useCallback(() => setStack([]), []),+ };+}diff --git a/dodaios/ui/web/frontend/src/components/society/card/pane/reviewQueue.ts b/dodaios/ui/web/frontend/src/components/society/card/pane/reviewQueue.tsnew file mode 100644index 0000000000..3ff6b3f2ef--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/card/pane/reviewQueue.ts@@ -0,0 +1,93 @@+/**+ * The agent's learning review queue (`GET /api/society/agents/{id}/review-queue`)+ * and its two decisions. A decided item leaves the list at once and comes back+ * with its error if the server refuses.+ */+import { useCallback } from "react";+import { useQuery, useQueryClient } from "@tanstack/react-query";++import { requestError } from "../../data";++export type ReviewItemKind = "proposal" | "memory_share" | "memory";++export interface ReviewItem {+ id: string;+ kind: ReviewItemKind;+ /** rule | skill | routine | approval_rule | focus | team | identity, for a proposal. */+ proposal_kind: string;+ summary: string;+ reason: string;+ /** Diff-style lines: "+ " added, "- " removed, " " unchanged. */+ preview: string[];+ path?: string;+ book?: string;+ created_ms: number;+}++export interface ReviewQueue {+ items: ReviewItem[];+ total: number;+ counts: Record<ReviewItemKind, number>;+}++export const reviewQueueKey = (agentId: string) => ["society", "review-queue", agentId] as const;++export function useReviewQueue(agentId: string, enabled = true) {+ return useQuery({+ queryKey: reviewQueueKey(agentId),+ enabled,+ retry: false,+ staleTime: 10_000,+ refetchInterval: import.meta.env.MODE === "test" ? false : 30_000,+ queryFn: async ({ signal }): Promise<ReviewQueue> => {+ const res = await fetch(`/api/society/agents/${encodeURIComponent(agentId)}/review-queue`, { signal });+ // An app restarted onto this bundle before its backend: an empty queue, not an error.+ if (res.status === 404) return { items: [], total: 0, counts: { proposal: 0, memory_share: 0, memory: 0 } };+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ return (await res.json()) as ReviewQueue;+ },+ });+}++export interface ReviewOutcome {+ id: string;+ outcome: "applied" | "rejected" | "failed" | "not_found";+ detail: string;+}++export function useDecideReviewItem(agentId: string) {+ const client = useQueryClient();+ return useCallback(+ async (item: ReviewItem, approve: boolean): Promise<ReviewOutcome> => {+ const key = reviewQueueKey(agentId);+ const before = client.getQueryData<ReviewQueue>(key);+ if (before) {+ client.setQueryData<ReviewQueue>(key, {+ ...before,+ items: before.items.filter((row) => row.id !== item.id),+ total: Math.max(0, before.total - 1),+ counts: { ...before.counts, [item.kind]: Math.max(0, before.counts[item.kind] - 1) },+ });+ }+ try {+ const res = await fetch(+ `/api/society/agents/${encodeURIComponent(agentId)}/review/${encodeURIComponent(item.id)}/${approve ? "approve" : "reject"}`,+ { method: "POST" },+ );+ if (!res.ok) {+ throw requestError((await res.json().catch(() => null)) as { detail?: unknown } | null, `HTTP ${res.status}`);+ }+ return (await res.json()) as ReviewOutcome;+ } catch (err) {+ if (before) client.setQueryData(key, before);+ throw err;+ } finally {+ void client.invalidateQueries({ queryKey: key });+ // A yes on a proposal changes the agent itself; knowledge counts move too.+ void client.invalidateQueries({ queryKey: ["society", "roster"] });+ void client.invalidateQueries({ queryKey: ["society", "agent-knowledge", agentId] });+ }+ },+ [agentId, client],+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/card/pane/seedComposer.ts b/dodaios/ui/web/frontend/src/components/society/card/pane/seedComposer.tsnew file mode 100644index 0000000000..6c3d143e2b--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/card/pane/seedComposer.ts@@ -0,0 +1,29 @@+/**+ * Put a ready message into this agent's chat composer without sending it.+ *+ * The society composer keeps its unsent text in the composer draft store of+ * its chat store, keyed by session; writing there is exactly what typing does,+ * so the person sees the text, can change it, and decides to send. Existing+ * unsent text is kept and the seed goes below it.+ */+import { readComposerDraft, writeComposerDraft } from "@/components/agentchat/composerDrafts";+import { useAgentChatStore } from "@/store/agentChat";++import { useSocietyChatStore } from "../../chat/AgentChatPanel";+import type { SocietyAgent } from "../../data";++export function seedAgentComposer(agent: SocietyAgent, text: string): boolean {+ const lead = agent.tier === "lead";+ const store = lead ? useAgentChatStore : useSocietyChatStore;+ const sessionId = lead ? store.getState().activeSessionId : agent.chatSessionId;+ if (!lead && !sessionId) return false;+ const current = readComposerDraft(store, sessionId);+ const joined = current.text.trim() ? `${current.text.trimEnd()}\n\n${text}` : text;+ writeComposerDraft(store, sessionId, { ...current, text: joined });+ // The field hydrates from the draft on its next layout; focus follows it.+ window.requestAnimationFrame(() => {+ const field = document.querySelector<HTMLElement>('[data-testid="agent-card-chat"] [data-testid="composer-chip-field"]');+ field?.focus();+ });+ return true;+}diff --git a/dodaios/ui/web/frontend/src/components/society/card/pane/ui.tsx b/dodaios/ui/web/frontend/src/components/society/card/pane/ui.tsxnew file mode 100644index 0000000000..35e897c72f--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/card/pane/ui.tsx@@ -0,0 +1,331 @@+/**+ * The agent pane's small building blocks: a titled section, a counted+ * anatomy row that opens somewhere, a compact segmented control, a chip list+ * with an add field. Styling lives in `agentPane.css` and uses theme tokens only.+ */+import { useRef, useState, type ReactNode } from "react";+import { ChevronRight, Plus, X, type LucideIcon } from "lucide-react";++import { cn } from "@/lib/utils";++export function PaneSection({+ title,+ action,+ children,+ className,+ testId,+}: {+ title?: ReactNode;+ action?: ReactNode;+ children: ReactNode;+ className?: string;+ testId?: string;+}) {+ return (+ <section className={cn("ap-section", className)} data-testid={testId}>+ {title || action ? (+ <div className="ap-section-head">+ {title ? <h3 className="ap-section-title">{title}</h3> : <span />}+ {action}+ </div>+ ) : null}+ {children}+ </section>+ );+}++export function PaneHint({ children, className }: { children: ReactNode; className?: string }) {+ return <p className={cn("ap-hint", className)}>{children}</p>;+}++/** One line of the agent's anatomy: what it is, how much of it there is, and where it lives. */+export function AnatomyRow({+ icon: Icon,+ label,+ detail,+ count,+ attention,+ onOpen,+ testId,+}: {+ icon: LucideIcon;+ label: string;+ detail: string;+ count?: string | number | null;+ /** A small warn-coloured mark: something here waits for the person. */+ attention?: boolean;+ onOpen?: () => void;+ testId?: string;+}) {+ const body = (+ <>+ <span className="ap-row-icon" aria-hidden>+ <Icon className="h-3.5 w-3.5" />+ </span>+ <span className="min-w-0 flex-1">+ <span className="ap-row-label">{label}</span>+ <span className="ap-row-detail">{detail}</span>+ </span>+ {count !== undefined && count !== null ? (+ <span className="ap-row-count" data-attention={attention ? "true" : undefined}>+ {count}+ </span>+ ) : null}+ {onOpen ? <ChevronRight className="ap-row-chevron h-3.5 w-3.5" aria-hidden /> : null}+ </>+ );+ return onOpen ? (+ <button type="button" className="ap-row" onClick={onOpen} data-testid={testId}>+ {body}+ </button>+ ) : (+ <div className="ap-row" data-testid={testId}>+ {body}+ </div>+ );+}++export interface SegmentOption<T extends string> {+ value: T;+ label: string;+ title?: string;+ disabled?: boolean;+ icon?: LucideIcon;+}++/** A compact radio group drawn as a segmented control. */+export function Segmented<T extends string>({+ value,+ options,+ onChange,+ label,+ size = "md",+ disabled = false,+ testId,+}: {+ value: T | null;+ options: SegmentOption<T>[];+ onChange: (value: T) => void;+ label: string;+ size?: "sm" | "md";+ disabled?: boolean;+ testId?: string;+}) {+ return (+ <div role="radiogroup" aria-label={label} className="ap-seg" data-size={size} data-testid={testId}>+ {options.map((option) => {+ const Icon = option.icon;+ const checked = option.value === value;+ return (+ <button+ key={option.value}+ type="button"+ role="radio"+ aria-checked={checked}+ aria-label={size === "sm" && Icon ? option.label : undefined}+ title={option.title ?? (size === "sm" ? option.label : undefined)}+ disabled={disabled || option.disabled}+ data-value={option.value}+ className="ap-seg-item"+ onClick={() => {+ if (!checked) onChange(option.value);+ }}+ >+ {Icon ? <Icon className="h-3 w-3" aria-hidden /> : null}+ {size === "sm" && Icon ? null : <span>{option.label}</span>}+ </button>+ );+ })}+ </div>+ );+}++/** Editable chips: each removable, plus a field that adds one (Enter or the + button). */+export function ChipList({+ items,+ onChange,+ placeholder,+ addLabel,+ removeLabel,+ normalize = (raw) => raw.trim(),+ suggestions,+ disabled = false,+ emptyText,+ testId,+}: {+ items: string[];+ onChange: (items: string[]) => void;+ placeholder: string;+ addLabel: string;+ /** "Remove {0}" */+ removeLabel: string;+ normalize?: (raw: string) => string;+ suggestions?: string[];+ disabled?: boolean;+ emptyText?: string;+ testId?: string;+}) {+ const [draft, setDraft] = useState("");+ const value = normalize(draft);+ const needle = draft.trim().toLowerCase();+ // Matches show as themed chips under the field, never as an OS popup.+ const matches = needle+ ? (suggestions ?? []).filter((s) => s.toLowerCase().includes(needle) && !items.includes(s) && s !== value).slice(0, 5)+ : [];+ const addValue = (next: string) => {+ setDraft("");+ if (!next || items.includes(next)) return;+ onChange([...items, next]);+ };+ const add = () => addValue(value);+ return (+ <div className="ap-chips" data-testid={testId}>+ {items.length === 0 && emptyText ? <span className="ap-hint">{emptyText}</span> : null}+ {items.length > 0 ? (+ <ul className="flex flex-wrap gap-1.5">+ {items.map((item) => (+ <li key={item} className="ap-chip">+ <span className="truncate">{item}</span>+ {disabled ? null : (+ <button+ type="button"+ className="ap-chip-x"+ aria-label={removeLabel.replace("{0}", item)}+ onClick={() => onChange(items.filter((x) => x !== item))}+ >+ <X className="h-3 w-3" aria-hidden />+ </button>+ )}+ </li>+ ))}+ </ul>+ ) : null}+ {disabled ? null : (+ <div className="ap-chip-add">+ <input+ className="ap-input"+ value={draft}+ placeholder={placeholder}+ aria-label={placeholder}+ onChange={(event) => setDraft(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ event.preventDefault();+ add();+ }+ }}+ />+ <button type="button" className="ap-icon-btn" aria-label={addLabel} title={addLabel} disabled={!value} onClick={add}>+ <Plus className="h-3.5 w-3.5" aria-hidden />+ </button>+ </div>+ )}+ {matches.length ? (+ <div className="flex flex-wrap gap-1">+ {matches.map((match) => (+ <button key={match} type="button" className="ap-chip ap-chip-suggest" onClick={() => addValue(match)}>+ <Plus className="h-3 w-3" aria-hidden />+ <span className="truncate">{match}</span>+ </button>+ ))}+ </div>+ ) : null}+ </div>+ );+}++/** Inline text that turns into a field on click; Enter saves, Escape cancels. */+export function InlineEdit({+ value,+ onSave,+ label,+ placeholder,+ disabled = false,+ className,+ maxLength,+ testId,+}: {+ value: string;+ onSave: (next: string) => Promise<void>;+ label: string;+ placeholder?: string;+ disabled?: boolean;+ className?: string;+ maxLength?: number;+ testId?: string;+}) {+ const [editing, setEditing] = useState(false);+ const [draft, setDraft] = useState(value);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState("");+ // Enter commits and the blur that follows must not commit a second time.+ const committing = useRef(false);+ const commit = async () => {+ if (committing.current) return;+ const next = draft.trim();+ if (next === value.trim()) {+ setEditing(false);+ return;+ }+ committing.current = true;+ setBusy(true);+ setError("");+ try {+ await onSave(next);+ setEditing(false);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ committing.current = false;+ setBusy(false);+ }+ };+ if (!editing) {+ return (+ <button+ type="button"+ className={cn("ap-inline", className)}+ disabled={disabled}+ aria-label={`${label}: ${value || placeholder || ""}`}+ title={disabled ? undefined : label}+ data-testid={testId}+ onClick={() => {+ setDraft(value);+ setError("");+ setEditing(true);+ }}+ >+ {value ? <span className="truncate">{value}</span> : <span className="ap-inline-empty truncate">{placeholder}</span>}+ </button>+ );+ }+ return (+ <span className="flex min-w-0 flex-col gap-1">+ <input+ autoFocus+ className={cn("ap-input", className)}+ value={draft}+ aria-label={label}+ maxLength={maxLength}+ disabled={busy}+ data-testid={testId ? `${testId}-input` : undefined}+ onChange={(event) => setDraft(event.target.value)}+ onBlur={() => void commit()}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ event.preventDefault();+ void commit();+ } else if (event.key === "Escape") {+ event.preventDefault();+ setEditing(false);+ }+ }}+ />+ {error ? (+ <span role="alert" className="text-xs text-destructive">+ {error}+ </span>+ ) : null}+ </span>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/data.ts b/dodaios/ui/web/frontend/src/components/society/data.tsindex 0f41ce6a38..987c24084e 100644--- a/dodaios/ui/web/frontend/src/components/society/data.ts+++ b/dodaios/ui/web/frontend/src/components/society/data.ts@@ -16,7 +16,7 @@ import { useCallback, useEffect } from "react";import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";import type { MentionPlugin } from "./chat/mentionItems";-import type { AgentApprovalMode, AgentRuntime, Checkpoint, SocietyAgentRow } from "@/lib/societyApi";+import type { AgentApprovalMode, AgentRuntime, BrowserMode, Checkpoint, SocietyAgentRow } from "@/lib/societyApi";import type { CompanionAppearance } from "./companion/appearance";import { useCreateAgentDialog } from "./create/createAgentStore";@@ -141,6 +141,10 @@ export interface SocietyAgent {/** Where the agent runs: null/absent = this computer, else a connected computer id. */computerId?: string | null;executionEnvironment?: "local" | "sandbox";+ /** `own` = the agent's own browser profile; `attach` = the person's running Chrome. */+ browserMode?: BrowserMode;+ /** Sites its browser may open; empty = no restriction. */+ browserAllowedDomains?: string[];/** The agent loop that runs its turns (docs/agent-runtimes.md); absent = Jarvis. */runtime?: AgentRuntime;/** The character: archetype, base, parts, palette. null = the palette tile. */@@ -263,6 +267,8 @@ export function rowToAgent(row: SocietyAgentRow): SocietyAgent {accountId: row.account_id,computerId: row.computer_id ?? null,executionEnvironment: row.execution_environment ?? "local",+ browserMode: row.browser_mode ?? "own",+ browserAllowedDomains: row.browser_allowed_domains ?? [],runtime: row.runtime ?? "jarvis",effort: row.effort,figure,@@ -664,6 +670,90 @@ export function useUpdateAgentLimits() {);}+/**+ * Any subset of the fields the agent pane edits after creation. Each maps onto+ * one `PATCH /api/society/agents/{id}` field; the roster validators+ * (`society/roster.py::_coerce`) stay the only judge of what is allowed.+ */+export interface AgentConfigPatch {+ name?: string;+ title?: string;+ description?: string;+ grantMode?: GrantMode;+ toolGrants?: string[];+ focus?: string[];+ denies?: string[];+ approvalMode?: AgentApprovalMode;+ permissionCeiling?: PermissionCeiling;+ approvalRules?: ApprovalRules;+ dailyBudgetUsd?: number;+ maxConcurrentRuns?: number;+ browserMode?: BrowserMode;+ browserAllowedDomains?: string[];+}++/** The wire body for a config patch: only the keys that are set, in snake case. */+export function agentConfigBody(patch: AgentConfigPatch): Record<string, unknown> {+ const body: Record<string, unknown> = {};+ if (patch.name !== undefined) body.name = patch.name;+ if (patch.title !== undefined) body.title = patch.title;+ if (patch.description !== undefined) body.description = patch.description;+ if (patch.grantMode !== undefined) body.grant_mode = patch.grantMode;+ if (patch.toolGrants !== undefined) body.grants = patch.toolGrants;+ if (patch.focus !== undefined) body.focus = patch.focus;+ if (patch.denies !== undefined) body.denies = patch.denies;+ if (patch.approvalMode !== undefined) body.approval_mode = patch.approvalMode;+ if (patch.permissionCeiling !== undefined) body.permission_ceiling = patch.permissionCeiling;+ if (patch.approvalRules !== undefined) {+ body.approval_rules = {+ require_approval: patch.approvalRules.requireApproval,+ always_allow: patch.approvalRules.alwaysAllow,+ };+ }+ if (patch.dailyBudgetUsd !== undefined) body.daily_budget_usd = Math.max(0, patch.dailyBudgetUsd);+ if (patch.maxConcurrentRuns !== undefined) body.max_concurrent_runs = Math.max(1, Math.round(patch.maxConcurrentRuns));+ if (patch.browserMode !== undefined) body.browser_mode = patch.browserMode;+ if (patch.browserAllowedDomains !== undefined) body.browser_allowed_domains = patch.browserAllowedDomains;+ return body;+}++/**+ * Save part of an agent's configuration from the agent pane. The updated row+ * goes straight into the roster cache, so the pane never flickers back to+ * the old value while the refetch runs. Sample rows change in place.+ */+export function useUpdateAgentConfig() {+ const client = useQueryClient();+ return useCallback(+ async (agent: SocietyAgent, patch: AgentConfigPatch): Promise<SocietyAgent> => {+ const body = agentConfigBody(patch);+ if (Object.keys(body).length === 0) return agent;+ if (SAMPLE_ROSTER.includes(agent)) {+ Object.assign(agent, patch);+ await client.invalidateQueries({ queryKey: ROSTER_QUERY_KEY });+ return agent;+ }+ const res = await fetch(`/api/society/agents/${encodeURIComponent(agent.agentId)}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ });+ if (!res.ok) {+ throw requestError((await res.json().catch(() => null)) as { detail?: unknown } | null, `HTTP ${res.status}`);+ }+ const updated = rowToAgent(((await res.json()) as { agent: SocietyAgentRow }).agent);+ const merged = { ...updated, state: agent.state, routines: agent.routines };+ client.setQueryData<RosterData>(ROSTER_QUERY_KEY, (prev) => prev ? {+ ...prev,+ agents: prev.agents.map((row) => (row.agentId === agent.agentId ? { ...merged, name: row.tier === "lead" ? row.name : merged.name } : row)),+ } : prev);+ void client.invalidateQueries({ queryKey: ROSTER_QUERY_KEY });+ return merged;+ },+ [client],+ );+}+/** Move an agent to another computer (`PATCH computer_id`); "" = this computer. */export function useSetAgentComputer() {const client = useQueryClient();diff --git a/dodaios/ui/web/frontend/src/i18n/locales/society/de.json b/dodaios/ui/web/frontend/src/i18n/locales/society/de.jsonindex b26d135478..ddac1fbd22 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/society/de.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/society/de.json@@ -4,6 +4,123 @@"options_collapse": "Optionen einklappen","options_expand": "Optionen ausklappen"},+ "agent_pane": {+ "tabs": "Agentendetails",+ "tab_overview": "Übersicht",+ "tab_tools": "Werkzeuge & Zugriff",+ "tab_memory": "Gedächtnis",+ "tab_tasks": "Aufgaben",+ "tab_browser": "Browser",+ "tab_history": "Verlauf",+ "back": "Zurück",+ "next_steps": "Nächste Schritte",+ "dismiss": "Ausblenden",+ "suggest_review": "{0} gelernte Dinge prüfen",+ "suggest_instructions": "Seine festen Anweisungen schreiben",+ "suggest_connect": "Hauptwerkzeuge nicht verbunden: {0}",+ "role": "Rolle",+ "suggest_routine": "Gib ihm eine Aufgabe, die nach Zeitplan läuft",+ "identity": "Identität",+ "rename": "Umbenennen",+ "name_required": "Ein Name ist nötig.",+ "lead_name_hint": "Der Lead heißt wie dein Aktivierungswort; ändere es in den Spracheinstellungen.",+ "edit_role": "Rolle bearbeiten",+ "role_placeholder": "Rolle in einer Zeile",+ "instructions": "Anweisungen",+ "open": "Öffnen",+ "instructions_empty": "Noch keine festen Anweisungen. Sag ihm, was seine Aufgabe ist, hier oder im Chat.",+ "runs_on": "Läuft auf",+ "seat_hint": "Das Modell wechselst du in der Modellauswahl des Chats. Die Laufzeit bleibt für das ganze Leben des Agenten gleich.",+ "anatomy": "Woraus er besteht",+ "instructions_learned": "Geschrieben, dazu {0} gelernte Regeln",+ "instructions_written": "Wie er arbeitet",+ "instructions_none": "Noch nicht geschrieben",+ "memory": "Gedächtnis",+ "memory_detail": "Was er über dich und seine Arbeit weiß",+ "memory_waiting": "{0} warten auf deine Prüfung",+ "skills": "Skills",+ "skills_none": "Noch keine Skills. Er speichert einen, wenn sich eine Arbeit zu wiederholen lohnt.",+ "skills_hint": "Abläufe, die er nach erledigter Arbeit für sich selbst aufgeschrieben hat. Er nutzt sie, wenn die Lage passt.",+ "routines": "Routinen",+ "routines_next": "Nächster Lauf {0}",+ "routines_idle": "Gerade nichts geplant",+ "routines_none": "Aufgaben, die von selbst laufen",+ "tools": "Werkzeuge",+ "tools_all_detail": "Alle verbundenen Werkzeuge",+ "tools_allowlist_detail": "{0} ausgewählte Werkzeuge",+ "files": "Dateien",+ "files_hint": "Wo er seine Arbeit auf diesem Computer und seine Notizen im Wiki ablegt.",+ "reach": "Reichweite",+ "reach_all": "Alles Verbundene",+ "reach_allowlist": "Nur was ich auswähle",+ "reach_all_hint": "Er darf jedes verbundene Werkzeug nutzen, außer denen, die du sperrst. Werkzeuge mit „Zuerst nutzen“ kommen zuerst.",+ "reach_allowlist_hint": "Er nutzt nur die Werkzeuge, die unten eingeschaltet sind.",+ "lead_tools_hint": "Der Lead nutzt jedes Werkzeug, das die Einstellungen der App erlauben.",+ "search_tools": "Werkzeuge suchen",+ "tools_unavailable": "Die Werkzeugliste konnte nicht geladen werden. Gespeicherte Einstellungen bleiben, wie sie sind.",+ "tool_off": "Aus",+ "tool_block": "Sperren",+ "tool_on": "An",+ "tool_first": "Zuerst nutzen",+ "show_all": "Alle {0} zeigen",+ "show_less": "Weniger zeigen",+ "approvals": "Berechtigungen",+ "rules_hint": "Nutze eine Werkzeug-ID wie plugin:gmail oder eine einzelne Aktion wie plugin:gmail:send.",+ "rule_placeholder": "Werkzeug- oder Aktions-ID",+ "rules_none": "Keine",+ "add": "Hinzufügen",+ "remove": "{0} entfernen",+ "browser": "Browser",+ "browser_own": "Eigener Browser",+ "browser_attach": "Mein Chrome",+ "browser_own_hint": "Ein eigenes Browserprofil, das nur dieser Agent nutzt.",+ "browser_attach_hint": "Er arbeitet in deinem laufenden Chrome, mit deinen Anmeldungen.",+ "sites": "Erlaubte Websites",+ "site_placeholder": "beispiel.de",+ "sites_any": "Jede Website",+ "placement_hint": "Diese beiden speichern sofort und gelten ab seiner nächsten Antwort.",+ "unsaved": "Ungespeicherte Änderungen",+ "discard": "Verwerfen",+ "widen_title": "Damit bekommt {0} mehr Spielraum:",+ "widen_reach_all": "Er darf jedes verbundene Werkzeug nutzen, nicht nur die ausgewählten.",+ "widen_tools": "Neue Werkzeuge: {0}",+ "widen_unblocked": "Nicht mehr gesperrt: {0}",+ "widen_mode": "Er fragt seltener: {0}",+ "widen_ceiling": "Mehr Läufe ohne Nachfrage: {0}",+ "widen_allow": "Immer erlaubt ohne Nachfrage: {0}",+ "widen_require": "Fragt nicht mehr vor: {0}",+ "widen_browser": "Er arbeitet in deinem eigenen Chrome, mit deinen Anmeldungen.",+ "widen_sites": "Sein Browser darf auch öffnen: {0}",+ "widen_sites_any": "Sein Browser darf jede Website öffnen.",+ "go_back": "Zurück",+ "allow_and_save": "Erlauben und speichern",+ "leave_sandbox": "Code-Sandbox verlassen",+ "leave_sandbox_body": "Außerhalb der Sandbox arbeitet dieser Agent wieder mit den Dateien, der Shell und dem Netzwerk dieses Computers.",+ "review_title": "Wartet auf deine Prüfung",+ "review_title_count": "Wartet auf deine Prüfung ({0})",+ "review_in_chat": "Im Chat durchgehen",+ "review_seeded": "Eine Nachricht liegt im Chat bereit. Schick sie ab, wenn ihr die Liste gemeinsam durchgehen wollt.",+ "review_chat_seed": "Geh bitte mit mir durch, was du gelernt oder vorgeschlagen hast und was noch auf meine Prüfung wartet, einen Punkt nach dem anderen, und frag mich zu jedem.",+ "review_empty": "Nichts wartet. Was er lernt oder vorschlägt, erscheint zuerst hier.",+ "memory_files": "Notizbücher und Dateien",+ "kind_rule": "Feste Regel",+ "kind_skill": "Neuer Skill",+ "kind_routine": "Routine",+ "kind_approval_rule": "Berechtigungsregel",+ "kind_focus": "Hauptwerkzeuge",+ "kind_team": "Teamkollegen",+ "kind_identity": "Name und Rolle",+ "kind_share": "Mit allen Agenten teilen",+ "kind_memory": "Seine Notizen",+ "kind_user_memory": "Über dich",+ "apply": "Übernehmen",+ "reject": "Ablehnen",+ "share": "Teilen",+ "keep_private": "Privat behalten",+ "keep": "Behalten",+ "forget": "Vergessen",+ "more_lines": "+{0} weitere Zeilen"+ },"browser_profiles": {"profile_unavailable": "Profil getrennt — bitte ein Profil auswählen","chrome_offline": "Chrome nicht verbunden",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/society/en.json b/dodaios/ui/web/frontend/src/i18n/locales/society/en.jsonindex 6374e0274b..b416b88bb0 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/society/en.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/society/en.json@@ -4,6 +4,123 @@"options_collapse": "Collapse Options","options_expand": "Expand Options"},+ "agent_pane": {+ "tabs": "Agent details",+ "tab_overview": "Overview",+ "tab_tools": "Tools & access",+ "tab_memory": "Memory",+ "tab_tasks": "Tasks",+ "tab_browser": "Browser",+ "tab_history": "History",+ "back": "Back",+ "next_steps": "Next steps",+ "dismiss": "Dismiss",+ "suggest_review": "Review {0} things it learned",+ "suggest_instructions": "Write its standing instructions",+ "suggest_connect": "Main tools not connected: {0}",+ "role": "Role",+ "suggest_routine": "Give it a task that runs on a schedule",+ "identity": "Identity",+ "rename": "Rename",+ "name_required": "A name is required.",+ "lead_name_hint": "The lead goes by your wake word; change it in the voice settings.",+ "edit_role": "Edit role",+ "role_placeholder": "Add a one-line role",+ "instructions": "Instructions",+ "open": "Open",+ "instructions_empty": "No standing instructions yet. Tell it what its job is, here or in the chat.",+ "runs_on": "Runs on",+ "seat_hint": "Change the model in the chat's model picker. The runtime stays the same for the agent's whole life.",+ "anatomy": "What it is made of",+ "instructions_learned": "Written, plus {0} learned rules",+ "instructions_written": "How it works",+ "instructions_none": "Not written yet",+ "memory": "Memory",+ "memory_detail": "What it knows about you and its work",+ "memory_waiting": "{0} waiting for your review",+ "skills": "Skills",+ "skills_none": "No skills yet. It saves one when a job is worth repeating.",+ "skills_hint": "Playbooks it wrote for itself after finished work. It uses them when the situation matches.",+ "routines": "Routines",+ "routines_next": "Next run {0}",+ "routines_idle": "Nothing scheduled right now",+ "routines_none": "Jobs that run on their own",+ "tools": "Tools",+ "tools_all_detail": "Every connected tool",+ "tools_allowlist_detail": "{0} picked tools",+ "files": "Files",+ "files_hint": "Where it keeps its work on this computer and its notes in the wiki.",+ "reach": "Reach",+ "reach_all": "Everything connected",+ "reach_allowlist": "Only what I pick",+ "reach_all_hint": "It may use every connected tool except the ones you block. Tools marked to reach first come first.",+ "reach_allowlist_hint": "It uses only the tools switched on below.",+ "lead_tools_hint": "The lead uses every tool the app's own settings allow.",+ "search_tools": "Search tools",+ "tools_unavailable": "The tool list could not be loaded. Saved choices stay as they are.",+ "tool_off": "Off",+ "tool_block": "Block",+ "tool_on": "On",+ "tool_first": "Reach first",+ "show_all": "Show all {0}",+ "show_less": "Show fewer",+ "approvals": "Permissions",+ "rules_hint": "Use a tool id such as plugin:gmail, or a single action such as plugin:gmail:send.",+ "rule_placeholder": "Tool or action id",+ "rules_none": "None",+ "add": "Add",+ "remove": "Remove {0}",+ "browser": "Browser",+ "browser_own": "Its own browser",+ "browser_attach": "My Chrome",+ "browser_own_hint": "A separate browser profile that only this agent uses.",+ "browser_attach_hint": "It works in your running Chrome, with your sign-ins.",+ "sites": "Allowed sites",+ "site_placeholder": "example.com",+ "sites_any": "Any site",+ "placement_hint": "These two save right away and apply from its next reply.",+ "unsaved": "Unsaved changes",+ "discard": "Discard",+ "widen_title": "This gives {0} more room:",+ "widen_reach_all": "It may use every connected tool, not only the ones you picked.",+ "widen_tools": "New tools: {0}",+ "widen_unblocked": "No longer blocked: {0}",+ "widen_mode": "It asks less often: {0}",+ "widen_ceiling": "More runs without asking: {0}",+ "widen_allow": "Always allowed without asking: {0}",+ "widen_require": "No longer asks before: {0}",+ "widen_browser": "It works in your own Chrome, with your sign-ins.",+ "widen_sites": "Its browser may also open: {0}",+ "widen_sites_any": "Its browser may open any site.",+ "go_back": "Go back",+ "allow_and_save": "Allow and save",+ "leave_sandbox": "Leave the code sandbox",+ "leave_sandbox_body": "Outside the sandbox this agent works with this computer's files, shell and network again.",+ "review_title": "Waiting for your review",+ "review_title_count": "Waiting for your review ({0})",+ "review_in_chat": "Review in chat",+ "review_seeded": "A message is ready in the chat. Send it when you want to go through the list together.",+ "review_chat_seed": "Please walk me through what you learned or proposed that is still waiting for my review, one item at a time, and ask me about each.",+ "review_empty": "Nothing waiting. What it learns or proposes shows up here first.",+ "memory_files": "Notebooks and files",+ "kind_rule": "Standing rule",+ "kind_skill": "New skill",+ "kind_routine": "Routine",+ "kind_approval_rule": "Permission rule",+ "kind_focus": "Main tools",+ "kind_team": "Teammates",+ "kind_identity": "Name and role",+ "kind_share": "Share with all agents",+ "kind_memory": "Its notes",+ "kind_user_memory": "About you",+ "apply": "Apply",+ "reject": "Reject",+ "share": "Share",+ "keep_private": "Keep private",+ "keep": "Keep",+ "forget": "Forget",+ "more_lines": "+{0} more lines"+ },"browser_profiles": {"profile_unavailable": "Profile disconnected — choose a profile","chrome_offline": "Chrome disconnected",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/society/es.json b/dodaios/ui/web/frontend/src/i18n/locales/society/es.jsonindex 9b6074a235..21f33c6424 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/society/es.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/society/es.json@@ -4,6 +4,123 @@"options_collapse": "Contraer opciones","options_expand": "Expandir opciones"},+ "agent_pane": {+ "tabs": "Detalles del agente",+ "tab_overview": "Resumen",+ "tab_tools": "Herramientas y acceso",+ "tab_memory": "Memoria",+ "tab_tasks": "Tareas",+ "tab_browser": "Navegador",+ "tab_history": "Historial",+ "back": "Volver",+ "next_steps": "Próximos pasos",+ "dismiss": "Descartar",+ "suggest_review": "Revisar {0} cosas que aprendió",+ "suggest_instructions": "Escribir sus instrucciones fijas",+ "suggest_connect": "Herramientas principales sin conectar: {0}",+ "role": "Rol",+ "suggest_routine": "Dale una tarea que se ejecute según un horario",+ "identity": "Identidad",+ "rename": "Cambiar nombre",+ "name_required": "El nombre es obligatorio.",+ "lead_name_hint": "El agente principal usa tu palabra de activación; cámbiala en los ajustes de voz.",+ "edit_role": "Editar rol",+ "role_placeholder": "Añade un rol en una línea",+ "instructions": "Instrucciones",+ "open": "Abrir",+ "instructions_empty": "Aún no hay instrucciones fijas. Dile cuál es su trabajo, aquí o en el chat.",+ "runs_on": "Funciona con",+ "seat_hint": "Cambia el modelo en el selector de modelo del chat. El entorno de ejecución es el mismo durante toda la vida del agente.",+ "anatomy": "De qué está hecho",+ "instructions_learned": "Escritas, más {0} reglas aprendidas",+ "instructions_written": "Cómo trabaja",+ "instructions_none": "Aún sin escribir",+ "memory": "Memoria",+ "memory_detail": "Lo que sabe de ti y de su trabajo",+ "memory_waiting": "{0} esperan tu revisión",+ "skills": "Habilidades",+ "skills_none": "Aún no hay habilidades. Guarda una cuando un trabajo merece repetirse.",+ "skills_hint": "Guías que escribió para sí mismo tras terminar un trabajo. Las usa cuando la situación encaja.",+ "routines": "Rutinas",+ "routines_next": "Próxima ejecución {0}",+ "routines_idle": "Nada programado ahora",+ "routines_none": "Trabajos que se ejecutan solos",+ "tools": "Herramientas",+ "tools_all_detail": "Todas las herramientas conectadas",+ "tools_allowlist_detail": "{0} herramientas elegidas",+ "files": "Archivos",+ "files_hint": "Dónde guarda su trabajo en este ordenador y sus notas en la wiki.",+ "reach": "Alcance",+ "reach_all": "Todo lo conectado",+ "reach_allowlist": "Solo lo que yo elija",+ "reach_all_hint": "Puede usar cualquier herramienta conectada salvo las que bloquees. Las marcadas para usar primero van primero.",+ "reach_allowlist_hint": "Solo usa las herramientas activadas abajo.",+ "lead_tools_hint": "El agente principal usa todas las herramientas que permiten los ajustes de la app.",+ "search_tools": "Buscar herramientas",+ "tools_unavailable": "No se pudo cargar la lista de herramientas. Lo guardado sigue igual.",+ "tool_off": "Desactivada",+ "tool_block": "Bloquear",+ "tool_on": "Activada",+ "tool_first": "Usar primero",+ "show_all": "Mostrar las {0}",+ "show_less": "Mostrar menos",+ "approvals": "Permisos",+ "rules_hint": "Usa un id de herramienta como plugin:gmail, o una sola acción como plugin:gmail:send.",+ "rule_placeholder": "Id de herramienta o acción",+ "rules_none": "Ninguna",+ "add": "Añadir",+ "remove": "Quitar {0}",+ "browser": "Navegador",+ "browser_own": "Su propio navegador",+ "browser_attach": "Mi Chrome",+ "browser_own_hint": "Un perfil de navegador aparte que solo usa este agente.",+ "browser_attach_hint": "Trabaja en tu Chrome abierto, con tus sesiones iniciadas.",+ "sites": "Sitios permitidos",+ "site_placeholder": "ejemplo.com",+ "sites_any": "Cualquier sitio",+ "placement_hint": "Estos dos se guardan al momento y se aplican desde su próxima respuesta.",+ "unsaved": "Cambios sin guardar",+ "discard": "Descartar",+ "widen_title": "Esto le da a {0} más margen:",+ "widen_reach_all": "Puede usar cualquier herramienta conectada, no solo las que elegiste.",+ "widen_tools": "Herramientas nuevas: {0}",+ "widen_unblocked": "Ya no bloqueadas: {0}",+ "widen_mode": "Pregunta con menos frecuencia: {0}",+ "widen_ceiling": "Más ejecuciones sin preguntar: {0}",+ "widen_allow": "Siempre permitido sin preguntar: {0}",+ "widen_require": "Ya no pregunta antes de: {0}",+ "widen_browser": "Trabaja en tu propio Chrome, con tus sesiones iniciadas.",+ "widen_sites": "Su navegador también puede abrir: {0}",+ "widen_sites_any": "Su navegador puede abrir cualquier sitio.",+ "go_back": "Volver",+ "allow_and_save": "Permitir y guardar",+ "leave_sandbox": "Salir del entorno aislado de código",+ "leave_sandbox_body": "Fuera del entorno aislado, este agente vuelve a trabajar con los archivos, la terminal y la red de este ordenador.",+ "review_title": "Esperando tu revisión",+ "review_title_count": "Esperando tu revisión ({0})",+ "review_in_chat": "Revisar en el chat",+ "review_seeded": "Hay un mensaje listo en el chat. Envíalo cuando quieras repasar la lista juntos.",+ "review_chat_seed": "Repasa conmigo, por favor, lo que aprendiste o propusiste y que sigue esperando mi revisión, de uno en uno, y pregúntame por cada punto.",+ "review_empty": "Nada pendiente. Lo que aprenda o proponga aparece aquí primero.",+ "memory_files": "Cuadernos y archivos",+ "kind_rule": "Regla fija",+ "kind_skill": "Habilidad nueva",+ "kind_routine": "Rutina",+ "kind_approval_rule": "Regla de permisos",+ "kind_focus": "Herramientas principales",+ "kind_team": "Compañeros",+ "kind_identity": "Nombre y rol",+ "kind_share": "Compartir con todos los agentes",+ "kind_memory": "Sus notas",+ "kind_user_memory": "Sobre ti",+ "apply": "Aplicar",+ "reject": "Rechazar",+ "share": "Compartir",+ "keep_private": "Mantener privado",+ "keep": "Conservar",+ "forget": "Olvidar",+ "more_lines": "+{0} líneas más"+ },"browser_profiles": {"profile_unavailable": "Perfil desconectado — elige un perfil","chrome_offline": "Chrome desconectado",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/society/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/society/pt.jsonindex 4b979c9880..e5383fa4c0 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/society/pt.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/society/pt.json@@ -4,6 +4,123 @@"options_collapse": "Recolher opções","options_expand": "Expandir opções"},+ "agent_pane": {+ "tabs": "Detalhes do agente",+ "tab_overview": "Visão geral",+ "tab_tools": "Ferramentas e acesso",+ "tab_memory": "Memória",+ "tab_tasks": "Tarefas",+ "tab_browser": "Navegador",+ "tab_history": "Histórico",+ "back": "Voltar",+ "next_steps": "Próximos passos",+ "dismiss": "Dispensar",+ "suggest_review": "Revisar {0} coisas que ele aprendeu",+ "suggest_instructions": "Escrever as instruções fixas dele",+ "suggest_connect": "Ferramentas principais não conectadas: {0}",+ "role": "Função",+ "suggest_routine": "Dê a ele uma tarefa que rode em um horário",+ "identity": "Identidade",+ "rename": "Renomear",+ "name_required": "O nome é obrigatório.",+ "lead_name_hint": "O agente principal usa a sua palavra de ativação; altere-a nas configurações de voz.",+ "edit_role": "Editar função",+ "role_placeholder": "Adicione uma função em uma linha",+ "instructions": "Instruções",+ "open": "Abrir",+ "instructions_empty": "Ainda não há instruções fixas. Diga qual é o trabalho dele, aqui ou no chat.",+ "runs_on": "Roda em",+ "seat_hint": "Troque o modelo no seletor de modelo do chat. O ambiente de execução é o mesmo durante toda a vida do agente.",+ "anatomy": "Do que ele é feito",+ "instructions_learned": "Escritas, mais {0} regras aprendidas",+ "instructions_written": "Como ele trabalha",+ "instructions_none": "Ainda não escritas",+ "memory": "Memória",+ "memory_detail": "O que ele sabe sobre você e o trabalho dele",+ "memory_waiting": "{0} aguardando a sua revisão",+ "skills": "Habilidades",+ "skills_none": "Ainda não há habilidades. Ele salva uma quando vale a pena repetir um trabalho.",+ "skills_hint": "Roteiros que ele escreveu para si mesmo depois de concluir um trabalho. Ele os usa quando a situação combina.",+ "routines": "Rotinas",+ "routines_next": "Próxima execução {0}",+ "routines_idle": "Nada agendado agora",+ "routines_none": "Trabalhos que rodam sozinhos",+ "tools": "Ferramentas",+ "tools_all_detail": "Todas as ferramentas conectadas",+ "tools_allowlist_detail": "{0} ferramentas escolhidas",+ "files": "Arquivos",+ "files_hint": "Onde ele guarda o trabalho neste computador e as notas na wiki.",+ "reach": "Alcance",+ "reach_all": "Tudo o que está conectado",+ "reach_allowlist": "Só o que eu escolher",+ "reach_all_hint": "Ele pode usar qualquer ferramenta conectada, exceto as que você bloquear. As marcadas para usar primeiro vêm primeiro.",+ "reach_allowlist_hint": "Ele usa só as ferramentas ativadas abaixo.",+ "lead_tools_hint": "O agente principal usa todas as ferramentas que as configurações do app permitem.",+ "search_tools": "Buscar ferramentas",+ "tools_unavailable": "Não foi possível carregar a lista de ferramentas. O que está salvo continua igual.",+ "tool_off": "Desligada",+ "tool_block": "Bloquear",+ "tool_on": "Ligada",+ "tool_first": "Usar primeiro",+ "show_all": "Mostrar todas as {0}",+ "show_less": "Mostrar menos",+ "approvals": "Permissões",+ "rules_hint": "Use um id de ferramenta como plugin:gmail, ou uma única ação como plugin:gmail:send.",+ "rule_placeholder": "Id de ferramenta ou ação",+ "rules_none": "Nenhuma",+ "add": "Adicionar",+ "remove": "Remover {0}",+ "browser": "Navegador",+ "browser_own": "Navegador próprio",+ "browser_attach": "Meu Chrome",+ "browser_own_hint": "Um perfil de navegador separado que só este agente usa.",+ "browser_attach_hint": "Ele trabalha no seu Chrome aberto, com os seus logins.",+ "sites": "Sites permitidos",+ "site_placeholder": "exemplo.com",+ "sites_any": "Qualquer site",+ "placement_hint": "Estes dois são salvos na hora e valem a partir da próxima resposta dele.",+ "unsaved": "Alterações não salvas",+ "discard": "Descartar",+ "widen_title": "Isto dá a {0} mais liberdade:",+ "widen_reach_all": "Ele pode usar qualquer ferramenta conectada, não só as que você escolheu.",+ "widen_tools": "Ferramentas novas: {0}",+ "widen_unblocked": "Não mais bloqueadas: {0}",+ "widen_mode": "Ele pergunta com menos frequência: {0}",+ "widen_ceiling": "Mais execuções sem perguntar: {0}",+ "widen_allow": "Sempre permitido sem perguntar: {0}",+ "widen_require": "Não pergunta mais antes de: {0}",+ "widen_browser": "Ele trabalha no seu próprio Chrome, com os seus logins.",+ "widen_sites": "O navegador dele também pode abrir: {0}",+ "widen_sites_any": "O navegador dele pode abrir qualquer site.",+ "go_back": "Voltar",+ "allow_and_save": "Permitir e salvar",+ "leave_sandbox": "Sair do ambiente isolado de código",+ "leave_sandbox_body": "Fora do ambiente isolado, este agente volta a trabalhar com os arquivos, o terminal e a rede deste computador.",+ "review_title": "Aguardando a sua revisão",+ "review_title_count": "Aguardando a sua revisão ({0})",+ "review_in_chat": "Revisar no chat",+ "review_seeded": "Há uma mensagem pronta no chat. Envie quando quiser passar pela lista juntos.",+ "review_chat_seed": "Por favor, passe comigo pelo que você aprendeu ou propôs e que ainda aguarda a minha revisão, um item de cada vez, e me pergunte sobre cada um.",+ "review_empty": "Nada pendente. O que ele aprender ou propuser aparece aqui primeiro.",+ "memory_files": "Cadernos e arquivos",+ "kind_rule": "Regra fixa",+ "kind_skill": "Habilidade nova",+ "kind_routine": "Rotina",+ "kind_approval_rule": "Regra de permissão",+ "kind_focus": "Ferramentas principais",+ "kind_team": "Colegas de equipe",+ "kind_identity": "Nome e função",+ "kind_share": "Compartilhar com todos os agentes",+ "kind_memory": "Notas dele",+ "kind_user_memory": "Sobre você",+ "apply": "Aplicar",+ "reject": "Rejeitar",+ "share": "Compartilhar",+ "keep_private": "Manter privado",+ "keep": "Manter",+ "forget": "Esquecer",+ "more_lines": "+{0} linhas"+ },"browser_profiles": {"profile_unavailable": "Perfil desligado — escolhe um perfil","chrome_offline": "Chrome desligado",diff --git a/dodaios/ui/web/frontend/src/i18n/locales/society/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/society/zh.jsonindex a7972e9893..dfe5cd2881 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/society/zh.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/society/zh.json@@ -4,6 +4,123 @@"options_collapse": "收起选项","options_expand": "展开选项"},+ "agent_pane": {+ "tabs": "智能体详情",+ "tab_overview": "概览",+ "tab_tools": "工具与权限",+ "tab_memory": "记忆",+ "tab_tasks": "任务",+ "tab_browser": "浏览器",+ "tab_history": "历史",+ "back": "返回",+ "next_steps": "下一步",+ "dismiss": "忽略",+ "suggest_review": "审阅它学到的 {0} 项内容",+ "suggest_instructions": "为它写下固定指令",+ "suggest_connect": "未连接的主要工具:{0}",+ "role": "角色",+ "suggest_routine": "给它一个按计划运行的任务",+ "identity": "身份",+ "rename": "重命名",+ "name_required": "必须填写名称。",+ "lead_name_hint": "主智能体使用你的唤醒词作为名字;可在语音设置中修改。",+ "edit_role": "编辑角色",+ "role_placeholder": "用一行写下角色",+ "instructions": "指令",+ "open": "打开",+ "instructions_empty": "还没有固定指令。在这里或聊天中告诉它它的工作是什么。",+ "runs_on": "运行于",+ "seat_hint": "在聊天的模型选择器中更换模型。运行环境在智能体的整个生命周期内保持不变。",+ "anatomy": "它的组成",+ "instructions_learned": "已写好,另有 {0} 条学到的规则",+ "instructions_written": "它的工作方式",+ "instructions_none": "尚未编写",+ "memory": "记忆",+ "memory_detail": "它对你和它的工作了解的内容",+ "memory_waiting": "{0} 项等待你审阅",+ "skills": "技能",+ "skills_none": "还没有技能。当某项工作值得重复时,它会保存一个。",+ "skills_hint": "它在完成工作后为自己写下的操作手册。情况相符时它会使用。",+ "routines": "例行任务",+ "routines_next": "下次运行 {0}",+ "routines_idle": "目前没有计划",+ "routines_none": "自动运行的工作",+ "tools": "工具",+ "tools_all_detail": "所有已连接的工具",+ "tools_allowlist_detail": "已选 {0} 个工具",+ "files": "文件",+ "files_hint": "它在这台电脑上存放工作、在 wiki 中存放笔记的位置。",+ "reach": "可用范围",+ "reach_all": "所有已连接的",+ "reach_allowlist": "仅我选择的",+ "reach_all_hint": "它可以使用所有已连接的工具,你屏蔽的除外。标记为优先使用的工具排在前面。",+ "reach_allowlist_hint": "它只使用下面已开启的工具。",+ "lead_tools_hint": "主智能体使用应用设置允许的所有工具。",+ "search_tools": "搜索工具",+ "tools_unavailable": "无法加载工具列表。已保存的选择保持不变。",+ "tool_off": "关闭",+ "tool_block": "屏蔽",+ "tool_on": "开启",+ "tool_first": "优先使用",+ "show_all": "显示全部 {0} 个",+ "show_less": "收起",+ "approvals": "权限",+ "rules_hint": "使用工具 id,例如 plugin:gmail,或单个操作,例如 plugin:gmail:send。",+ "rule_placeholder": "工具或操作 id",+ "rules_none": "无",+ "add": "添加",+ "remove": "移除 {0}",+ "browser": "浏览器",+ "browser_own": "它自己的浏览器",+ "browser_attach": "我的 Chrome",+ "browser_own_hint": "一个只供此智能体使用的独立浏览器配置。",+ "browser_attach_hint": "它在你正在运行的 Chrome 中工作,使用你的登录状态。",+ "sites": "允许的网站",+ "site_placeholder": "example.com",+ "sites_any": "任何网站",+ "placement_hint": "这两项会立即保存,并从它的下一次回复开始生效。",+ "unsaved": "有未保存的更改",+ "discard": "放弃",+ "widen_title": "这会让 {0} 拥有更多权限:",+ "widen_reach_all": "它可以使用所有已连接的工具,而不仅是你选择的。",+ "widen_tools": "新增工具:{0}",+ "widen_unblocked": "不再屏蔽:{0}",+ "widen_mode": "它询问得更少:{0}",+ "widen_ceiling": "更多运行无需询问:{0}",+ "widen_allow": "始终允许且无需询问:{0}",+ "widen_require": "不再事先询问:{0}",+ "widen_browser": "它在你自己的 Chrome 中工作,使用你的登录状态。",+ "widen_sites": "它的浏览器还可以打开:{0}",+ "widen_sites_any": "它的浏览器可以打开任何网站。",+ "go_back": "返回",+ "allow_and_save": "允许并保存",+ "leave_sandbox": "离开代码沙盒",+ "leave_sandbox_body": "离开沙盒后,此智能体将再次使用这台电脑的文件、终端和网络。",+ "review_title": "等待你审阅",+ "review_title_count": "等待你审阅({0})",+ "review_in_chat": "在聊天中审阅",+ "review_seeded": "聊天中已准备好一条消息。想一起过一遍列表时再发送。",+ "review_chat_seed": "请带我逐项过一遍你学到或提议、但仍在等待我审阅的内容,每一项都问问我的意见。",+ "review_empty": "没有待审阅的内容。它学到或提议的东西会先出现在这里。",+ "memory_files": "笔记本和文件",+ "kind_rule": "固定规则",+ "kind_skill": "新技能",+ "kind_routine": "例行任务",+ "kind_approval_rule": "权限规则",+ "kind_focus": "主要工具",+ "kind_team": "队友",+ "kind_identity": "名称和角色",+ "kind_share": "与所有智能体共享",+ "kind_memory": "它的笔记",+ "kind_user_memory": "关于你",+ "apply": "应用",+ "reject": "拒绝",+ "share": "共享",+ "keep_private": "保持私有",+ "keep": "保留",+ "forget": "忘记",+ "more_lines": "还有 {0} 行"+ },"browser_profiles": {"profile_unavailable": "配置文件已断开 — 请选择一个配置文件","chrome_offline": "Chrome 已断开",diff --git a/dodaios/ui/web/society_routes.py b/dodaios/ui/web/society_routes.pyindex d1da3e82a3..985c587aa2 100644--- a/dodaios/ui/web/society_routes.py+++ b/dodaios/ui/web/society_routes.py@@ -1435,6 +1435,55 @@ async def promote_agent_skill(agent_id: str, slug: str, request: Request) -> dicreturn {"promoted": str(target), "state": "draft"}+# ---------------------------------------------------------- learning review++[email protected]("/agents/{agent_id}/review-queue", openapi_extra={"x-jarvis-readonly": True})+async def agent_review_queue(agent_id: str, request: Request) -> dict[str, Any]:+ """What this agent proposed or wrote that waits for the person (agent pane)."""+ from dodaios.society.learning_review import queue++ rt = await _runtime(request)+ agent = await rt.roster.resolve(agent_id)+ if agent is None:+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})+ return await queue(rt, agent)+++ "/agents/{agent_id}/review/{item_id}/{decision}",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def decide_review_item(+ agent_id: str,+ item_id: str,+ decision: Literal["approve", "reject"],+ request: Request,+) -> dict[str, Any]:+ """Approve or reject one review item; a proposal goes through its own resolve path."""+ from dodaios.society.learning_review import ReviewRefused, decide++ rt = await _runtime(request)+ agent = await rt.roster.resolve(agent_id)+ if agent is None:+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)})+ try:+ return await decide(+ rt,+ agent,+ item_id,+ approve=decision == "approve",+ task_store=getattr(request.app.state, "task_store", None),+ scheduler=getattr(request.app.state, "task_scheduler", None),+ )+ except KeyError as exc:+ raise HTTPException(404, {"reason": str(FailureReason.TARGET_UNKNOWN)}) from exc+ except ReviewRefused as exc:+ raise HTTPException(+ 409, {"reason": str(FailureReason.BLOCKED_BY_POLICY), "detail": str(exc)}+ ) from exc++# ----------------------------------------------------------------- browserdiff --git a/tests/contract/test_agent_mcp_harmony.py b/tests/contract/test_agent_mcp_harmony.pyindex 4e2bc9ddc0..6b489bcefa 100644--- a/tests/contract/test_agent_mcp_harmony.py+++ b/tests/contract/test_agent_mcp_harmony.py@@ -125,6 +125,13 @@ WITHHELD: Final[dict[str, str]] = {"confirming a proposal changes an agent's rules, routines or skills — the ""owner's decision at their own keyboard, never a remote client's"),+ "GET /api/society/agents/{agent_id}/review-queue": (+ "the learning review queue is the owner's view in the agent's details pane"+ ),+ "POST /api/society/agents/{agent_id}/review/{item_id}/{decision}": (+ "approving or rejecting what an agent learned is the owner's decision, "+ "never a remote client's"+ ),"POST /api/society/onboarding/start": ("the one-time team offer is onboarding UI in the lead's chat, not an API verb"),diff --git a/tests/unit/society/test_agent_config_pane.py b/tests/unit/society/test_agent_config_pane.pynew file mode 100644index 0000000000..7d5be02952--- /dev/null+++ b/tests/unit/society/test_agent_config_pane.py@@ -0,0 +1,297 @@+"""The agent pane's configuration and learning review, headless.++* every field the pane edits round-trips through ``PATCH /api/society/agents/{id}``+ and the roster validators, and a bad value is refused rather than stored;+* a tool change on a Hermes or OpenClaw agent reaches its very next tool call,+ because the CLI/ACP tool filter re-reads the roster row every time;+* the review queue lists real proposal, knowledge-share and memory rows, and+ approve / reject act on them through the existing resolve paths.+"""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from dodaios.agent_chat.store import AgentChatStore+from dodaios.society.runtime import SocietyRuntime+from dodaios.society.surface import tools_for_cli_session+from dodaios.ui.web.society_routes import router+from tests.fakes.fake_agent_chat import FakeChatService+++def _tool(name: str, desc: str) -> SimpleNamespace:+ return SimpleNamespace(+ name=name, description=desc, risk_tier="monitor", parameters={}, schema={}+ )+++TOOLS = {+ "gmail": _tool("gmail", "Read and send mail."),+ "google_calendar": _tool("google_calendar", "Read the calendar."),+ "cli_gh": _tool("cli_gh", "GitHub CLI."),+}+++def _app(tmp_path: Path) -> tuple[FastAPI, SocietyRuntime]:+ runtime = SocietyRuntime(tmp_path, seed_starter_team=False, brain_tools=lambda: TOOLS)+ app = FastAPI()+ app.include_router(router)+ app.state.society_factory = lambda: runtime+ return app, runtime+++# ------------------------------------------------------------------ PATCH+++def test_every_pane_field_round_trips_through_patch(tmp_path: Path) -> None:+ app, _ = _app(tmp_path)+ with TestClient(app) as c:+ c.post("/api/society/agents", json={"name": "Mailbox", "description": "Handle my mail."})+ body = {+ "grant_mode": "allowlist",+ "grants": ["plugin:gmail", "cli:gh"],+ "focus": ["plugin:gmail"],+ "denies": ["plugin:google_calendar"],+ "permission_ceiling": "ask",+ "approval_rules": {"require_approval": ["plugin:gmail:send"], "always_allow": []},+ "daily_budget_usd": 7.5,+ "max_concurrent_runs": 3,+ "browser_mode": "attach",+ "browser_allowed_domains": ["Mail.Google.com", "mail.google.com"],+ }+ response = c.patch("/api/society/agents/mailbox", json=body)+ assert response.status_code == 200, response.text+ agent = c.get("/api/society/agents/mailbox").json()["agent"]+ assert agent["grant_mode"] == "allowlist"+ assert agent["grants"] == ["cli:gh", "plugin:gmail"]+ assert agent["focus"] == ["plugin:gmail"]+ assert agent["denies"] == ["plugin:google_calendar"]+ assert agent["permission_ceiling"] == "ask"+ assert agent["approval_rules"] == {+ "require_approval": ["plugin:gmail:send"],+ "always_allow": [],+ }+ assert agent["daily_budget_usd"] == 7.5+ assert agent["max_concurrent_runs"] == 3+ assert agent["browser_mode"] == "attach"+ assert agent["browser_allowed_domains"] == ["mail.google.com"]+ # Nothing the pane did not send moved: the instructions stay as written.+ assert agent["description"] == "Handle my mail."++ renamed = c.patch("/api/society/agents/mailbox", json={"name": "Inbox", "title": "Mail"})+ assert renamed.status_code == 200, renamed.text+ assert renamed.json()["agent"]["name"] == "Inbox"+ assert renamed.json()["agent"]["title"] == "Mail"+++ "body",+ [+ {"browser_mode": "everywhere"},+ {"grant_mode": "some"},+ {"permission_ceiling": "block"},+ {"max_concurrent_runs": 11},+ {"daily_budget_usd": -1},+ {"approval_rules": {"require_approval": "plugin:gmail"}},+ {"name": "a/b"},+ ],+)+def test_a_bad_value_is_refused_and_nothing_is_stored(tmp_path: Path, body: dict) -> None:+ app, _ = _app(tmp_path)+ with TestClient(app) as c:+ c.post("/api/society/agents", json={"name": "Mailbox"})+ before = c.get("/api/society/agents/mailbox").json()["agent"]+ response = c.patch("/api/society/agents/mailbox", json=body)+ assert 400 <= response.status_code < 500, response.text+ after = c.get("/api/society/agents/mailbox").json()["agent"]+ assert {k: after[k] for k in before if k != "stats"} == {+ k: before[k] for k in before if k != "stats"+ }+++# ------------------------------------------------- per-turn tool filtering++[email protected]("runtime", ["hermes", "openclaw"])+async def test_a_tool_change_reaches_the_runtime_on_its_next_call(+ tmp_path: Path, runtime: str+) -> None:+ chat_store = AgentChatStore(tmp_path / "chat.db")+ service = FakeChatService(chat_store)+ cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path)))+ rt = SocietyRuntime(+ tmp_path, seed_starter_team=False, chat_service=lambda: service, cfg=lambda: cfg+ )+ await rt.ensure_started()+ try:+ agent, _ = await rt.roster.create(name="Remote", runtime=runtime, provider="openai")+ chat_store.create_session(+ session_id=agent.session_id,+ surface="society",+ provider="openai",+ model="test-model",+ effort="medium",+ cwd=str(tmp_path / "workspace"),+ permission_mode="bypass",+ runtime=runtime,+ )+ brain = SimpleNamespace(_tools={}, _config=cfg)++ async def names() -> list[str]:+ picked = await tools_for_cli_session(agent.session_id, dict(TOOLS), brain)+ assert picked is not None+ # The agent's own hands (society_*, its folder tools) always stay.+ return [n for n in picked if n in TOOLS]++ assert {"gmail", "cli_gh", "google_calendar"} <= set(await names())++ await rt.roster.update(agent.agent_id, {"denies": ["plugin:gmail"]})+ assert "gmail" not in await names()++ await rt.roster.update(+ agent.agent_id,+ {"denies": [], "grant_mode": "allowlist", "grants": ["cli:gh"], "focus": ["cli:gh"]},+ )+ assert await names() == ["cli_gh"]+ finally:+ await rt.close()+ chat_store.close()+++# ----------------------------------------------------------- review queue+++def test_the_review_queue_decides_real_proposals(tmp_path: Path) -> None:+ app, _ = _app(tmp_path)+ with TestClient(app) as c:+ c.post("/api/society/agents", json={"name": "Mailbox", "description": "Handle my mail."})+ c.post("/api/society/agents", json={"name": "Other"})++ def park(agent_id: str, text: str) -> str:+ return c.post(+ "/api/society/approvals",+ json={+ "agent_id": agent_id,+ "capability": "core:config:rule",+ "action": {"kind": "rule", "payload": {"text": text}, "reason": "asked"},+ "summary": f"Add a standing rule: {text}",+ },+ ).json()["approval"]["id"]++ keep = park("mailbox", "Be brief.")+ drop = park("mailbox", "Use emoji.")+ park("other", "Not mine.")++ queue = c.get("/api/society/agents/mailbox/review-queue").json()+ ids = {item["id"] for item in queue["items"]}+ assert ids == {f"proposal:{keep}", f"proposal:{drop}"}+ assert queue["counts"]["proposal"] == 2+ item = next(i for i in queue["items"] if i["id"] == f"proposal:{keep}")+ assert item["proposal_kind"] == "rule"+ assert item["preview"] == ["+ Be brief."]++ approved = c.post(f"/api/society/agents/mailbox/review/proposal:{keep}/approve")+ assert approved.status_code == 200, approved.text+ assert approved.json()["outcome"] == "applied"+ rejected = c.post(f"/api/society/agents/mailbox/review/proposal:{drop}/reject")+ assert rejected.json()["outcome"] == "rejected"++ agent = c.get("/api/society/agents/mailbox").json()["agent"]+ assert agent["description"] == "Handle my mail.\n\nBe brief."+ assert c.get("/api/society/agents/mailbox/review-queue").json()["total"] == 0++ again = c.post(f"/api/society/agents/mailbox/review/proposal:{keep}/approve")+ assert again.status_code == 409+ foreign = park("other", "Still not mine.")+ foreign_url = f"/api/society/agents/mailbox/review/proposal:{foreign}/approve"+ assert c.post(foreign_url).status_code == 404+ assert c.post("/api/society/agents/mailbox/review/nonsense/approve").status_code == 404+ assert c.post("/api/society/agents/mailbox/review/proposal:x/maybe").status_code == 422+++def test_a_focus_proposal_previews_as_a_diff(tmp_path: Path) -> None:+ app, _ = _app(tmp_path)+ with TestClient(app) as c:+ c.post("/api/society/agents", json={"name": "Mailbox", "focus": ["plugin:gmail"]})+ c.post(+ "/api/society/approvals",+ json={+ "agent_id": "mailbox",+ "capability": "core:config:focus",+ "action": {"kind": "focus", "payload": {"focus": ["cli:gh"]}, "reason": ""},+ "summary": "Reach first for: cli:gh",+ },+ )+ item = c.get("/api/society/agents/mailbox/review-queue").json()["items"][0]+ assert item["preview"] == ["- plugin:gmail", "+ cli:gh"]+++async def test_memory_writes_are_kept_or_forgotten(tmp_path: Path) -> None:+ from dodaios.society import learning_review++ rt = SocietyRuntime(tmp_path, seed_starter_team=False)+ await rt.ensure_started()+ try:+ agent, _ = await rt.roster.create(name="Scout")+ await rt.memory.remember(agent, "The user prefers short replies.", target="user")+ await rt.memory.remember(agent, "The weekly report goes out on Friday.", target="memory")+ await rt.memory.remember(agent, "I asked for this myself.", target="memory", origin="user")++ queue = await learning_review.queue(rt, agent)+ memory = [i for i in queue["items"] if i["kind"] == "memory"]+ # The person's own write never needs review.+ assert sorted(i["summary"] for i in memory) == [+ "The user prefers short replies.",+ "The weekly report goes out on Friday.",+ ]+ keep = next(i for i in memory if "Friday" in i["summary"])+ forget = next(i for i in memory if "short replies" in i["summary"])+ assert forget["book"] == "USER.md"++ kept = await learning_review.decide(rt, agent, keep["id"], approve=True)+ assert kept["outcome"] == "applied"+ gone = await learning_review.decide(rt, agent, forget["id"], approve=False)+ assert gone["outcome"] == "rejected"++ texts = [e.text for e in rt.memory.entries(agent)]+ assert "The weekly report goes out on Friday." in texts+ assert "The user prefers short replies." not in texts+ after = await learning_review.queue(rt, agent)+ assert [i for i in after["items"] if i["kind"] == "memory"] == []+ with pytest.raises(learning_review.ReviewRefused):+ await learning_review.decide(rt, agent, keep["id"], approve=True)+ finally:+ await rt.close()+++async def test_a_knowledge_share_is_promoted_or_kept_private(tmp_path: Path) -> None:+ from dodaios.society import learning_review++ rt = SocietyRuntime(tmp_path, seed_starter_team=False)+ await rt.ensure_started()+ try:+ agent, _ = await rt.roster.create(name="Scout")+ shared = await rt.memory.propose_shared(agent, "Office hours", "Mon to Fri, 9 to 5.")+ private = await rt.memory.propose_shared(agent, "Draft idea", "Not ready yet.")+ queue = await learning_review.queue(rt, agent)+ shares = {i["id"] for i in queue["items"] if i["kind"] == "memory_share"}+ assert shares == {f"share:{shared['approval_id']}", f"share:{private['approval_id']}"}++ promoted = await learning_review.decide(+ rt, agent, f"share:{shared['approval_id']}", approve=True+ )+ assert promoted["outcome"] == "applied"+ assert promoted["detail"].startswith("society/shared/")+ kept = await learning_review.decide(+ rt, agent, f"share:{private['approval_id']}", approve=False+ )+ assert kept["outcome"] == "rejected"+ left = (await learning_review.queue(rt, agent))["items"]+ assert not [i for i in left if i["kind"] == "memory_share"]+ finally:+ await rt.close()