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): show what every agent needs from you in one inbox (#904)
Ruben Lütke97299313982c
diff --git a/dodaios/agent_chat/attention.py b/dodaios/agent_chat/attention.pynew file mode 100644index 0000000000..25cab63af3--- /dev/null+++ b/dodaios/agent_chat/attention.py@@ -0,0 +1,713 @@+"""Who is waiting on the person right now, across every agent.++## The gap this closes++An agent that needs the person (a question, a tool approval, a secret, a+configuration proposal) parks a card in its own chat. That card is only seen+by someone who happens to have that chat open: with a dozen agents, the one+waiting is usually not the one on screen, and the work behind it sits still.++This module keeps one live list of everything that waits on the person, tells+the app when the list changes, and decides when a change is worth a+notification. The bell in the Agents section reads the list, the roster shows+each agent's reason, and the window title carries the count.++## Where the list comes from++* **Chat gates** are folded from the very events the chat timeline folds+ (``approval_required`` / ``question_required`` / ``credential_required`` and+ their resolutions), through the service's event listener. One listener sees+ every runner (our brain, the provider API loop, every CLI seat, Hermes and+ OpenClaw over ACP), because each of them ends in ``AgentChatService._emit``.+ After a restart the list is rebuilt from the tail of each chat's log, the+ same way a reopened chat rebuilds its cards.+* **Society items** are read from the society's approvals table: configuration+ proposals and parked unattended approvals. They are the source of truth+ there, so they are never mirrored here.++## When a change becomes a notification++Two transitions, decided here and shown by the app:++* ``needs_input``: an agent's waiting reason appeared or changed;+* ``done``: a turn the person started finished without leaving anything open.++Every notification passes one gate (:class:`AttentionGate`): never for a+routine or other unattended chat, never for a muted agent, never while the+person is looking at that agent, and at most one per agent and kind every+:data:`THROTTLE_S` seconds. Parked unattended approvals are counted but never+announced: background work never asks.++Nothing here is ever spoken. The only output is one app-bus event,+:class:`AgentAttentionChanged`, which the desktop app turns into the badge, an+in-app toast or a desktop notification. No voice path subscribes to it.+"""++from __future__ import annotations++import asyncio+import logging+import time+from collections.abc import Awaitable, Callable, Iterable+from dataclasses import dataclass, field, replace+from typing import Any, Final, Literal, NamedTuple++from dodaios.core.events import Event++log = logging.getLogger(__name__)++#: What an item asks of the person. Mirrors the ``waiting_reason.kind`` the+#: society agent payload carries.+Kind = Literal["question", "approval", "credential", "proposal"]+KINDS: Final[tuple[str, ...]] = ("question", "approval", "credential", "proposal")++#: One notification per agent and transition kind within this window.+THROTTLE_S: Final[float] = 5.0++#: A focus report older than this no longer says the person is looking: the+#: window that sent it may be gone without having said so.+FOCUS_TTL_S: Final[float] = 300.0++#: How long a "done" waits for the card a finished turn may still open (an+#: end-of-turn question or plan card arrives just after ``turn_finished``).+DONE_GRACE_S: Final[float] = 1.5++#: How much of a chat's log is replayed after a restart. Open cards sit at the+#: end of a chat: a later turn closes every card before it.+SEED_TAIL: Final[int] = 400++#: How many chats per surface are replayed after a restart, newest first.+SEED_SESSIONS: Final[int] = 200++#: Longest summary line an item carries (the card holds the rest).+SUMMARY_CHARS: Final[int] = 200++#: The society session prefix (``society:<agent>[...]``).+_SOCIETY_PREFIX: Final[str] = "society:"++#: The front-page chat surface: its gates belong to the lead agent, whose card+#: in the Agents section shows exactly that chat.+_LEAD_SURFACE: Final[str] = "jarvis"+++def _now_ms() -> int:+ return int(time.time() * 1000)+++def _line(value: Any, limit: int = SUMMARY_CHARS) -> str:+ return " ".join(str(value or "").split())[:limit]+++@dataclass(frozen=True, slots=True)+class AttentionItem:+ """One thing the person is asked for."""++ kind: str+ session_id: str+ ref_id: str+ summary: str+ since_ms: int+ expires_ms: int | None = None+ agent_id: str = ""+ turn_id: str = ""+ #: An end-of-turn card (a CLI that cannot ask mid-turn): its answer goes+ #: out as the next message and a new turn settles it.+ deferred: bool = False+ #: ``chat`` for a card in a chat, ``queue`` for the society's tables.+ source: str = "chat"+ #: Kind-specific facts the inbox needs to answer in place.+ detail: dict[str, Any] = field(default_factory=dict)++ def to_dict(self) -> dict[str, Any]:+ return {+ "kind": self.kind,+ "agent_id": self.agent_id,+ "session_id": self.session_id,+ "ref_id": self.ref_id,+ "summary": self.summary,+ "since_ms": self.since_ms,+ "expires_ms": self.expires_ms,+ "deferred": self.deferred,+ "source": self.source,+ # The full series stays on the card; the inbox needs the current step.+ "detail": {k: v for k, v in self.detail.items() if k != "questions"},+ }++ def reason(self) -> dict[str, Any]:+ """The ``waiting_reason`` shape of the society agent payload."""+ return {+ "kind": self.kind,+ "summary": self.summary,+ "session_id": self.session_id,+ "ref_id": self.ref_id,+ }+++class Change(NamedTuple):+ """What one event did to the list."""++ #: ``opened`` | ``closed`` | ``done`` | ``proposal`` | ``recount``.+ what: str+ session_id: str+ item: AttentionItem | None = None+++def _question_detail(questions: list[Any], answers: list[Any] | None) -> tuple[str, dict[str, Any]]:+ """The current step's text and what the inbox may offer to answer it."""+ answers = list(answers or [])+ step = next(+ (i for i in range(len(questions)) if i >= len(answers) or answers[i] is None),+ max(0, len(questions) - 1),+ )+ current = questions[step] if step < len(questions) and isinstance(questions[step], dict) else {}+ options = current.get("options") if isinstance(current.get("options"), list) else []+ labels = [_line(o.get("label"), 80) for o in options if isinstance(o, dict)]+ # A question this inbox cannot answer with one tap (several picks, a form)+ # still lists here; it is answered on its card.+ shape = str(current.get("type") or current.get("kind") or "single")+ multi = bool(current.get("multi") or current.get("multi_select") or current.get("multiSelect"))+ # Only a lone question: a series is reviewed and sent as a whole on its card.+ single = shape in ("single", "choice") and not multi and len(questions) == 1+ detail = {+ "question": _line(current.get("question"), 300),+ "options": labels,+ "step": step,+ "count": len(questions),+ "single": bool(single and labels),+ }+ return _line(current.get("question")), detail+++class AttentionBoard:+ """Open cards per chat, folded from the chat events. Pure: no I/O, no clock.++ The rules match the timeline reducer (``reduce.ts``), so the list and the+ cards on screen never disagree: a resolution closes its card, a new turn+ settles every end-of-turn card before it, and a finished turn closes any+ mid-turn card it left behind.+ """++ def __init__(self) -> None:+ self._open: dict[tuple[str, str], AttentionItem] = {}+ #: Chats whose next turn the person started by typing.+ self._typed: set[str] = set()+ #: Running turns the person started (by chat).+ self._person_turns: dict[str, str] = {}+ #: Chats that have been seen live (a restart replay never overrides them).+ self.live_sessions: set[str] = set()++ # ------------------------------------------------------------------ read++ def items(self) -> list[AttentionItem]:+ return sorted(self._open.values(), key=lambda item: item.since_ms)++ def open_in(self, session_id: str) -> list[AttentionItem]:+ return [item for (sid, _), item in self._open.items() if sid == session_id]++ # ----------------------------------------------------------------- write++ def seed(self, session_id: str, events: Iterable[dict[str, Any]]) -> None:+ """Rebuild one chat's open cards from its log (after a restart)."""+ if session_id in self.live_sessions:+ return+ for event in events:+ self._fold(session_id, event)+ # A replay says nothing about who started the turn that is running now.+ self._typed.discard(session_id)+ self._person_turns.pop(session_id, None)++ def observe(self, session_id: str, event: dict[str, Any]) -> list[Change]:+ """Fold one live event; returns what it changed."""+ self.live_sessions.add(session_id)+ return self._fold(session_id, event)++ def _open_item(self, item: AttentionItem) -> list[Change]:+ self._open[(item.session_id, item.ref_id)] = item+ return [Change("opened", item.session_id, item)]++ def _close(self, session_id: str, ref_id: str) -> list[Change]:+ item = self._open.pop((session_id, ref_id), None)+ return [Change("closed", session_id, item)] if item is not None else []++ def _fold(self, session_id: str, event: dict[str, Any]) -> list[Change]:+ kind = str(event.get("kind") or "")+ payload = event.get("payload") if isinstance(event.get("payload"), dict) else {}+ assert isinstance(payload, dict)+ ts = int(event.get("ts_ms") or 0) or _now_ms()+ turn_id = str(payload.get("turn_id") or "")++ if kind == "approval_required":+ ref = str(payload.get("approval_id") or "")+ if not ref:+ return []+ tool = _line(payload.get("name"), 120)+ return self._open_item(AttentionItem(+ kind="approval", session_id=session_id, ref_id=ref,+ summary=_line(payload.get("summary")) or tool, since_ms=ts, turn_id=turn_id,+ detail={"tool": tool},+ ))+ if kind == "approval_resolved":+ return self._close(session_id, str(payload.get("approval_id") or ""))++ if kind == "question_required":+ ref = str(payload.get("question_id") or "")+ raw = payload.get("questions")+ questions = raw if isinstance(raw, list) else []+ if not ref or not questions:+ return []+ summary, detail = _question_detail(questions, None)+ expires = int(payload.get("expires_ms") or 0) or None+ return self._open_item(AttentionItem(+ kind="question", session_id=session_id, ref_id=ref, summary=summary,+ since_ms=ts, expires_ms=expires, turn_id=turn_id,+ deferred=bool(payload.get("deferred")),+ detail={**detail, "asker": _line(payload.get("asker"), 80), "questions": questions},+ ))+ if kind == "question_progress":+ key = (session_id, str(payload.get("question_id") or ""))+ item = self._open.get(key)+ if item is None:+ return []+ questions = item.detail.get("questions") or []+ answers = payload.get("answers") if isinstance(payload.get("answers"), list) else None+ summary, detail = _question_detail(questions, answers)+ expires = int(payload.get("expires_ms") or 0) or item.expires_ms+ self._open[key] = replace(+ item, summary=summary or item.summary, expires_ms=expires,+ detail={**item.detail, **detail},+ )+ return []+ if kind == "question_resolved":+ return self._close(session_id, str(payload.get("question_id") or ""))++ if kind == "credential_required":+ ref = str(payload.get("request_id") or "")+ if not ref:+ return []+ label = _line(payload.get("label"), 120) or _line(payload.get("env"), 120)+ return self._open_item(AttentionItem(+ kind="credential", session_id=session_id, ref_id=ref, summary=label,+ since_ms=ts, turn_id=turn_id, detail={"label": label},+ ))+ if kind == "credential_resolved":+ return self._close(session_id, str(payload.get("request_id") or ""))++ if kind == "user_message":+ # An agent writing on the person's behalf (``author``) is not the+ # person starting work.+ if not payload.get("author"):+ self._typed.add(session_id)+ return []+ if kind == "turn_started":+ changes: list[Change] = []+ for item in self.open_in(session_id):+ if item.kind == "question" and item.deferred:+ changes += self._close(session_id, item.ref_id)+ if session_id in self._typed:+ self._typed.discard(session_id)+ self._person_turns[session_id] = turn_id+ else:+ self._person_turns.pop(session_id, None)+ return changes+ if kind == "turn_finished":+ changes = []+ for item in self.open_in(session_id):+ stale = item.kind in ("question", "approval") and not item.deferred+ if stale and (not turn_id or item.turn_id == turn_id):+ changes += self._close(session_id, item.ref_id)+ by_person = self._person_turns.pop(session_id, None)+ finished = str(payload.get("status") or "") == "done"+ if finished and by_person is not None and not self.open_in(session_id):+ changes.append(Change("done", session_id))+ return changes++ if kind == "notice":+ notice = str(payload.get("kind") or "")+ if notice == "proposal" and str(payload.get("status") or "pending") == "pending":+ item = AttentionItem(+ kind="proposal", session_id=session_id,+ ref_id=str(payload.get("proposal_id") or ""),+ summary=_line(payload.get("summary") or payload.get("text")), since_ms=ts,+ agent_id=str(payload.get("agent_id") or ""), source="queue",+ )+ return [Change("proposal", session_id, item)]+ if notice in ("proposal_resolved", "approval_cleared"):+ return [Change("recount", session_id)]+ return []+++# ---------------------------------------------------------------------- gate+++@dataclass(slots=True)+class Focus:+ """What the person is looking at, as the app last reported it."""++ agent_id: str = ""+ session_id: str = ""+ app_focused: bool = False+ muted: frozenset[str] = frozenset()+ at: float = 0.0+++class AttentionGate:+ """Decides whether a transition may become a notification.++ Returns the reason it was held back, or ``None`` to let it through. Pure+ apart from the injected clock, so every rule is unit-tested.+ """++ def __init__(+ self,+ *,+ clock: Callable[[], float] = time.monotonic,+ throttle_s: float = THROTTLE_S,+ focus_ttl_s: float = FOCUS_TTL_S,+ ) -> None:+ self._clock = clock+ self._throttle_s = throttle_s+ self._focus_ttl_s = focus_ttl_s+ self._last: dict[tuple[str, str], float] = {}+ self.focus = Focus()++ def report_focus(+ self,+ *,+ agent_id: str = "",+ session_id: str = "",+ app_focused: bool = False,+ muted: Iterable[str] = (),+ ) -> None:+ self.focus = Focus(+ agent_id=agent_id or "",+ session_id=session_id or "",+ app_focused=bool(app_focused),+ muted=frozenset(m for m in muted if m),+ at=self._clock(),+ )++ def looking_at(self, agent_id: str) -> bool:+ focus = self.focus+ fresh = focus.at > 0 and self._clock() - focus.at <= self._focus_ttl_s+ return fresh and focus.app_focused and bool(agent_id) and focus.agent_id == agent_id++ def verdict(self, *, agent_id: str, transition: str, session_id: str) -> str | None:+ if not agent_id:+ return "no_agent"+ if _unattended(session_id):+ return "unattended"+ if agent_id in self.focus.muted:+ return "muted"+ if self.looking_at(agent_id):+ return "looking"+ key = (agent_id, transition)+ now = self._clock()+ last = self._last.get(key)+ if last is not None and now - last < self._throttle_s:+ return "throttled"+ self._last[key] = now+ return None+++def _unattended(session_id: str) -> bool:+ """A routine run's own chat: nobody watches it, so it never notifies."""+ from dodaios.society.routine_runner import is_routine_session++ return is_routine_session(session_id)+++# ---------------------------------------------------------------------- event+++@dataclass(frozen=True, slots=True)+class AgentAttentionChanged(Event):+ """The list of things waiting on the person changed.++ ``count`` is the whole list's length (the badge). When the change is worth+ telling, ``transition`` says which (``needs_input`` | ``done``) with the+ agent and card it is about; otherwise it is empty and clients only refresh+ their list. Shown as a badge, an in-app toast or a desktop notification;+ never spoken.+ """++ count: int = 0+ transition: str = ""+ agent_id: str = ""+ agent_name: str = ""+ session_id: str = ""+ kind: str = ""+ ref_id: str = ""+ summary: str = ""+++# ------------------------------------------------------------------- service++Publisher = Callable[[Any], Awaitable[None]]+++class Attention:+ """The live list for one chat service, plus its notifier."""++ def __init__(+ self,+ service: Any,+ *,+ publish: Publisher | None = None,+ society: Callable[[], Any] | None = None,+ gate: AttentionGate | None = None,+ ) -> None:+ self.service = service+ self.board = AttentionBoard()+ self.gate = gate or AttentionGate()+ self._publish = publish+ self._society = society or (lambda: None)+ self._agents: dict[str, str | None] = {}+ self._tasks: set[asyncio.Task[Any]] = set()+ self._seeded = False+ self._seed_lock: asyncio.Lock | None = None+ self.done_grace_s = DONE_GRACE_S++ # ----------------------------------------------------------- listening++ def listener(self, session_id: str, event: dict[str, Any]) -> None:+ """The service's event listener: records, then schedules the rest."""+ changes = self.board.observe(session_id, event)+ if not changes:+ return+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError: # emitted off the loop: the list is already updated+ return+ task = loop.create_task(self._after(changes), name="agent-attention")+ self._tasks.add(task)+ task.add_done_callback(self._tasks.discard)++ async def _after(self, changes: list[Change]) -> None:+ try:+ await self.ensure_seeded()+ note: dict[str, Any] = {}+ for change in changes:+ if change.what != "done":+ note = await self._transition(change) or note+ await self._emit(len(await self.items()), note)+ done = [change for change in changes if change.what == "done"]+ if not done:+ return+ # A turn that ends by asking (an end-of-turn card) is not finished+ # news: that card's own notice tells it instead.+ await asyncio.sleep(self.done_grace_s)+ for change in done:+ if self.board.open_in(change.session_id):+ continue+ told = await self._transition(change)+ if told:+ await self._emit(len(await self.items()), told)+ except Exception: # noqa: BLE001 — a notifier must never break the chat it watches+ log.warning("agent attention: could not publish a change", exc_info=True)++ async def _transition(self, change: Change) -> dict[str, Any] | None:+ if change.what not in ("opened", "proposal", "done"):+ return None+ agent_id = (change.item.agent_id if change.item else "") or await self.agent_for(+ change.session_id+ ) or ""+ transition = "done" if change.what == "done" else "needs_input"+ if transition == "done" and change.session_id != f"{_SOCIETY_PREFIX}{agent_id}":+ # "Finished" is news only for an agent's own chat. The front-page+ # chat (typed or mirrored from a voice call) and agent-to-agent+ # conversations finish under the person's eyes or without them.+ return None+ held = self.gate.verdict(+ agent_id=agent_id, transition=transition, session_id=change.session_id+ )+ if held is not None:+ log.debug("agent attention: %s for %s held (%s)", transition, agent_id, held)+ return None+ item = change.item+ return {+ "transition": transition,+ "agent_id": agent_id,+ "agent_name": self._agent_name(agent_id),+ "session_id": change.session_id,+ "kind": item.kind if item else "",+ "ref_id": item.ref_id if item else "",+ "summary": item.summary if item else "",+ }++ async def _emit(self, count: int, note: dict[str, Any]) -> None:+ if self._publish is None:+ return+ await self._publish(+ AgentAttentionChanged(count=count, source_layer="agent_chat.attention", **note)+ )++ async def refresh(self) -> None:+ """Tell clients the list may have changed (a society item was decided)."""+ await self._emit(len(await self.items()), {})++ # ------------------------------------------------------------- reading++ async def ensure_seeded(self) -> None:+ """Rebuild open cards from the logs once (after a restart)."""+ if self._seeded:+ return+ if self._seed_lock is None:+ self._seed_lock = asyncio.Lock()+ async with self._seed_lock:+ if self._seeded:+ return+ try:+ logs = await asyncio.to_thread(self._read_logs)+ except Exception: # noqa: BLE001 — without a replay the list fills from live events+ log.warning("agent attention: could not replay chat logs", exc_info=True)+ logs = []+ for session_id, surface, events in logs:+ self._agents.setdefault(session_id, self._agent_from(session_id, surface))+ self.board.seed(session_id, events)+ self._seeded = True++ def _read_logs(self) -> list[tuple[str, str, list[dict[str, Any]]]]:+ store = getattr(self.service, "store", None)+ if store is None:+ return []+ out: list[tuple[str, str, list[dict[str, Any]]]] = []+ for surface in ("society", _LEAD_SURFACE):+ for session in store.list_sessions(SEED_SESSIONS, surface=surface):+ sid = session.session_id+ if _unattended(sid):+ continue+ out.append((sid, surface, store.list_events(sid, tail=SEED_TAIL)))+ return out++ @staticmethod+ def _agent_from(session_id: str, surface: str) -> str | None:+ if session_id.startswith(_SOCIETY_PREFIX):+ from dodaios.society.surface import agent_id_of++ return agent_id_of(session_id)+ if surface == _LEAD_SURFACE:+ from dodaios.society.roster import LEAD_AGENT_ID++ return LEAD_AGENT_ID+ return None++ async def agent_for(self, session_id: str) -> str | None:+ """The agent a chat belongs to; ``None`` for chats outside the Agents section."""+ if session_id in self._agents:+ return self._agents[session_id]+ surface = ""+ if not session_id.startswith(_SOCIETY_PREFIX):+ store = getattr(self.service, "store", None)+ session = await asyncio.to_thread(store.get_session, session_id) if store else None+ surface = str(getattr(session, "surface", "") or "")+ agent_id = self._agent_from(session_id, surface)+ self._agents[session_id] = agent_id+ return agent_id++ def _agent_name(self, agent_id: str) -> str:+ rt = self._society()+ cached = getattr(rt, "cached_agent", None)+ agent = cached(agent_id) if callable(cached) else None+ if agent is None:+ return ""+ from dodaios.society.display_name import display_name++ try:+ return display_name(agent)+ except Exception: # noqa: BLE001 — the name is cosmetic+ return str(getattr(agent, "name", "") or "")++ async def chat_items(self) -> list[AttentionItem]:+ await self.ensure_seeded()+ out: list[AttentionItem] = []+ for item in self.board.items():+ agent_id = await self.agent_for(item.session_id)+ if agent_id:+ out.append(replace(item, agent_id=agent_id))+ return out++ async def society_items(self) -> list[AttentionItem]:+ """Proposals and parked unattended approvals; empty until the society is up."""+ rt = self._society()+ approvals = getattr(rt, "approvals", None)+ if approvals is None:+ return []+ from dodaios.society.proposals import kind_of++ out: list[AttentionItem] = []+ for row in await approvals.pending():+ proposal = kind_of(row.capability) is not None+ session_id = str(row.action.get("session_id") or "") if proposal else ""+ out.append(AttentionItem(+ kind="proposal" if proposal else "approval",+ session_id=session_id or f"{_SOCIETY_PREFIX}{row.agent_id}",+ ref_id=row.id,+ summary=_line(row.summary) or row.capability,+ since_ms=int(row.created_ms or 0),+ expires_ms=int(row.expires_ms or 0) or None,+ agent_id=row.agent_id,+ source="queue",+ detail={+ "capability": row.capability,+ "parked": str(row.state) == "blocked",+ **({"proposal_kind": kind_of(row.capability)} if proposal else {}),+ },+ ))+ return out++ async def items(self) -> list[AttentionItem]:+ """Everything that waits on the person, oldest first."""+ chat = await self.chat_items()+ try:+ queued = await self.society_items()+ except Exception: # noqa: BLE001 — the chat list stands on its own+ log.warning("agent attention: society items unavailable", exc_info=True)+ queued = []+ return sorted(chat + queued, key=lambda item: item.since_ms)++ async def waiting_reasons(self) -> dict[str, dict[str, Any]]:+ """Per agent: the reason it waits, the newest live card first."""+ reasons: dict[str, tuple[tuple[int, int], AttentionItem]] = {}+ for item in await self.items():+ # A card blocking a chat outranks a queued proposal; newer outranks older.+ rank = (1 if item.source == "chat" else 0, item.since_ms)+ current = reasons.get(item.agent_id)+ if current is None or rank > current[0]:+ reasons[item.agent_id] = (rank, item)+ return {agent_id: item.reason() for agent_id, (_, item) in reasons.items()}+++# ------------------------------------------------------------------ wiring+++def install(+ service: Any,+ *,+ publish: Publisher | None = None,+ society: Callable[[], Any] | None = None,+) -> Attention:+ """Attach the attention list to ``service`` (idempotent)."""+ existing = getattr(service, "attention", None)+ if isinstance(existing, Attention):+ return existing+ attention = Attention(service, publish=publish, society=society)+ service.add_event_listener(attention.listener)+ service.attention = attention+ return attention+++def attention_of(service: Any) -> Attention | None:+ found = getattr(service, "attention", None)+ return found if isinstance(found, Attention) else None+++async def waiting_reasons(state: Any) -> dict[str, dict[str, Any]]:+ """``waiting_reason`` per agent for the roster payload; empty when no chat runs yet."""+ attention = attention_of(getattr(state, "agent_chat", None))+ if attention is None:+ return {}+ try:+ return await attention.waiting_reasons()+ except Exception: # noqa: BLE001 — the roster must load without it+ log.warning("agent attention: waiting reasons unavailable", exc_info=True)+ return {}diff --git a/dodaios/ui/web/attention_routes.py b/dodaios/ui/web/attention_routes.pynew file mode 100644index 0000000000..3a2fcdc969--- /dev/null+++ b/dodaios/ui/web/attention_routes.py@@ -0,0 +1,59 @@+"""What waits on the person across every agent (``/api/agent-chat/attention``).++The list itself lives in :mod:`dodaios.agent_chat.attention`; these routes+read it and take the app's focus report, which the notification gate needs to+stay quiet while the person is already looking at the agent in question.+"""++from __future__ import annotations++from typing import Any++from fastapi import APIRouter, Request+from pydantic import BaseModel, ConfigDict, Field++router = APIRouter(prefix="/api/agent-chat/attention", tags=["agent-chat"])+++async def _attention(request: Request) -> Any:+ from dodaios.agent_chat.attention import attention_of, install++ from .agent_chat_routes import _async_service++ service = await _async_service(request)+ # The server installs it with the app bus when it builds the service; a+ # service built elsewhere still answers, it just cannot notify.+ return attention_of(service) or install(+ service, society=lambda: getattr(request.app.state, "society", None)+ )++[email protected]("", summary="Everything an agent is waiting on the person for")+async def list_attention(request: Request) -> dict[str, Any]:+ attention = await _attention(request)+ items = await attention.items()+ return {"items": [item.to_dict() for item in items], "count": len(items)}+++class FocusBody(BaseModel):+ model_config = ConfigDict(extra="ignore")++ #: The agent whose chat is on screen; empty when none is.+ agent_id: str = Field(default="", max_length=200)+ session_id: str = Field(default="", max_length=400)+ #: Whether the app window has the keyboard focus.+ app_focused: bool = False+ #: Agents the person muted (no notifications, still counted).+ muted: list[str] = Field(default_factory=list, max_length=500)++[email protected]("/focus", summary="Tell the notifier what the person is looking at")+async def report_focus(body: FocusBody, request: Request) -> dict[str, Any]:+ attention = await _attention(request)+ attention.gate.report_focus(+ agent_id=body.agent_id,+ session_id=body.session_id,+ app_focused=body.app_focused,+ muted=body.muted,+ )+ return {"ok": True}diff --git a/dodaios/ui/web/frontend/src/components/society/attention/AttentionBell.tsx b/dodaios/ui/web/frontend/src/components/society/attention/AttentionBell.tsxnew file mode 100644index 0000000000..cba715ef83--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/attention/AttentionBell.tsx@@ -0,0 +1,123 @@+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";+import { createPortal } from "react-dom";+import { Bell } from "lucide-react";++import { fill, useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { CAPTION_ICON_BUTTON, CAPTION_ICON_CLASS, CAPTION_ICON_STROKE } from "@/components/layout/captionSwitch";+import { useAgentNavigation } from "@/views/society/agentNavigation";++import { AttentionInbox } from "./AttentionInbox";+import { useAgentAttention } from "./useAgentAttention";++/** Width of the inbox panel and its distance from the window edges. */+const PANEL_W = 384;+const EDGE = 12;++/**+ * The caption button for "waiting for you": a bell with the count, and the+ * inbox under it. The count is the same one the window title carries.+ * Quiet by design: it never animates on its own, it only changes its number.+ */+export function AttentionBell({ className }: { className?: string }) {+ const t = useT();+ const { count } = useAgentAttention();+ const [open, setOpen] = useState(false);+ const button = useRef<HTMLButtonElement>(null);+ const panel = useRef<HTMLDivElement>(null);+ const [left, setLeft] = useState(EDGE);++ const close = useCallback((refocus = true) => {+ setOpen(false);+ if (refocus) button.current?.focus({ preventScroll: true });+ }, []);++ useLayoutEffect(() => {+ if (!open) return;+ const place = () => {+ const rect = button.current?.getBoundingClientRect();+ const width = Math.min(PANEL_W, window.innerWidth - EDGE * 2);+ const center = rect ? rect.left + rect.width / 2 : window.innerWidth / 2;+ setLeft(Math.max(EDGE, Math.min(center - width / 2, window.innerWidth - width - EDGE)));+ };+ place();+ window.addEventListener("resize", place);+ return () => window.removeEventListener("resize", place);+ }, [open]);++ useEffect(() => {+ if (!open) return;+ const onKey = (event: KeyboardEvent) => {+ if (event.key === "Escape") {+ event.preventDefault();+ close();+ }+ };+ const onPointer = (event: PointerEvent) => {+ const target = event.target as Node | null;+ if (target && (panel.current?.contains(target) || button.current?.contains(target))) return;+ close(false);+ };+ document.addEventListener("keydown", onKey, true);+ document.addEventListener("pointerdown", onPointer, true);+ // Open lands on the panel, so the keyboard can walk the list at once.+ panel.current?.focus({ preventScroll: true });+ return () => {+ document.removeEventListener("keydown", onKey, true);+ document.removeEventListener("pointerdown", onPointer, true);+ };+ }, [open, close]);++ // Jumping to a card closes the inbox: the card is where the answer goes.+ useEffect(() => useAgentNavigation.subscribe((state, previous) => {+ if (state.request && state.request !== previous.request) setOpen(false);+ }), []);++ const label = count > 0+ ? fill(t("agent_attention.bell_count"), { count })+ : t("agent_attention.bell");++ return (+ <>+ <button+ ref={button}+ type="button"+ onClick={() => (open ? close() : setOpen(true))}+ aria-label={label}+ title={label}+ aria-haspopup="dialog"+ aria-expanded={open}+ data-testid="attention-bell"+ data-count={count}+ className={cn(CAPTION_ICON_BUTTON, "relative", (open || count > 0) && "text-foreground", className)}+ >+ <Bell aria-hidden className={CAPTION_ICON_CLASS} strokeWidth={CAPTION_ICON_STROKE} />+ {count > 0 && (+ <span+ aria-hidden+ data-testid="attention-bell-count"+ className="absolute -right-1 -top-1 flex h-4 min-w-4 items-center justify-center rounded-full bg-warning px-1 text-[10px] font-semibold leading-none tabular-nums text-background ring-2 ring-background"+ >+ {count > 9 ? "9+" : count}+ </span>+ )}+ </button>+ {open && createPortal(+ <div+ ref={panel}+ role="dialog"+ aria-label={t("agent_attention.title")}+ tabIndex={-1}+ style={{ left, width: `min(${PANEL_W}px, calc(100vw - ${EDGE * 2}px))` }}+ className={cn(+ "fixed top-10 z-[150] overflow-hidden rounded-xl bg-popover text-popover-foreground shadow-float outline-none",+ "origin-top motion-safe:animate-in motion-safe:fade-in-0 motion-safe:zoom-in-95 motion-safe:duration-150",+ )}+ >+ <AttentionInbox onClose={() => close()} />+ </div>,+ document.body,+ )}+ </>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/attention/AttentionInbox.test.tsx b/dodaios/ui/web/frontend/src/components/society/attention/AttentionInbox.test.tsxnew file mode 100644index 0000000000..066c918ce4--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/attention/AttentionInbox.test.tsx@@ -0,0 +1,184 @@+import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { useEventStore } from "@/store/events";+import { useAgentNavigation } from "@/views/society/agentNavigation";++import { AttentionBell } from "./AttentionBell";+import { AttentionInbox } from "./AttentionInbox";+import { quickActionsFor, type AttentionItem } from "./attentionApi";+import { resetAttentionStore, useAttentionStore } from "./attentionStore";+import { resetNotificationPrefs, useNotificationPrefs } from "./notificationPrefs";++const api = vi.hoisted(() => ({+ answer: vi.fn(async () => undefined),+ approve: vi.fn(async () => undefined),+}));+vi.mock("@/lib/agentChatApi", () => ({+ answerAgentChatQuestion: api.answer,+ resolveAgentChatApproval: api.approve,+}));+vi.mock("@/components/society/data", () => ({+ useSocietyRoster: () => ({+ data: {+ sample: false,+ agents: [+ { agentId: "scout", name: "Scout", tier: "specialist", state: "waiting", palette: {}, figure: null },+ { agentId: "brain", name: "Brain", tier: "specialist", state: "idle", palette: {}, figure: null },+ ],+ },+ }),+}));+vi.mock("@/components/society/AgentSwatch", () => ({ AgentSwatch: () => <span data-testid="swatch" /> }));++const NOW = Date.now();++const ROWS = [+ {+ kind: "question", agent_id: "scout", session_id: "society:scout", ref_id: "q1",+ summary: "Which database should the project use?", since_ms: NOW - 5 * 60_000, expires_ms: NOW + 120_000,+ source: "chat",+ detail: { question: "Which database should the project use?", options: ["SQLite", "Postgres"], step: 0, count: 2, single: true },+ },+ {+ kind: "approval", agent_id: "brain", session_id: "society:brain", ref_id: "a1",+ summary: "Run the migration", since_ms: NOW - 10 * 60_000, expires_ms: null, source: "chat", detail: { tool: "shell" },+ },+ {+ kind: "credential", agent_id: "scout", session_id: "society:scout", ref_id: "c1",+ summary: "GitHub token", since_ms: NOW - 60_000, expires_ms: null, source: "chat", detail: { label: "GitHub token" },+ },+];++function stubList(rows: unknown[] = ROWS) {+ const fetchMock = vi.fn(async (url: string) => {+ if (String(url).startsWith("/api/agent-chat/attention")) {+ return new Response(JSON.stringify({ items: rows, count: rows.length }));+ }+ return new Response("{}", { status: 404 });+ });+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+}++beforeEach(() => {+ resetAttentionStore();+ resetNotificationPrefs();+ useAgentNavigation.setState({ request: null, onScreen: null });+ useEventStore.setState({ activeSection: "agents" });+ api.answer.mockClear();+ api.approve.mockClear();+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++describe("AttentionInbox", () => {+ it("groups the waiting items by agent, longest wait first", async () => {+ stubList();+ render(<AttentionInbox />);+ const groups = await screen.findAllByTestId("attention-group");+ expect(groups.map((g) => g.dataset.agentId)).toEqual(["brain", "scout"]);+ const scoutItems = within(groups[1]).getAllByTestId("attention-item");+ expect(scoutItems.map((i) => i.dataset.kind)).toEqual(["question", "credential"]);+ expect(within(groups[1]).getByText("1 of 2", { exact: false })).toBeTruthy();+ expect(screen.getByTestId("attention-inbox-count").textContent).toBe("3");+ });++ it("answers a one-pick question in place and lets the row go", async () => {+ stubList();+ render(<AttentionInbox />);+ const options = await screen.findAllByTestId("attention-option");+ expect(options.map((o) => o.textContent)).toEqual(["ASQLite", "BPostgres"]);+ fireEvent.click(options[1]);+ await waitFor(() => expect(api.answer).toHaveBeenCalledWith("society:scout", "q1", 0, { optionIndex: 1 }));+ await waitFor(() => expect(useAttentionStore.getState().list?.items.some((i) => i.refId === "q1")).toBe(false), {+ timeout: 2000,+ });+ expect(useAttentionStore.getState().count).toBe(2);+ });++ it("allows an approval once, never always", async () => {+ stubList();+ render(<AttentionInbox />);+ const allow = await screen.findByTestId("attention-allow");+ expect(screen.getByTestId("attention-deny")).toBeTruthy();+ fireEvent.click(allow);+ await waitFor(() => expect(api.approve).toHaveBeenCalledWith("society:brain", "a1", "allow"));+ });++ it("shows a failed answer instead of dropping the row", async () => {+ stubList();+ api.approve.mockRejectedValueOnce(new Error("boom"));+ render(<AttentionInbox />);+ fireEvent.click(await screen.findByTestId("attention-deny"));+ expect(await screen.findByRole("alert")).toBeTruthy();+ expect(useAttentionStore.getState().list?.items).toHaveLength(3);+ });++ it("opens the agent at its card and closes", async () => {+ stubList();+ const onClose = vi.fn();+ render(<AttentionInbox onClose={onClose} />);+ const credential = (await screen.findAllByTestId("attention-item")).find((i) => i.dataset.kind === "credential")!;+ fireEvent.click(within(credential).getByText("GitHub token"));+ expect(useAgentNavigation.getState().request).toMatchObject({+ agentId: "scout", sessionId: "society:scout", cardRef: "c1", kind: "credential",+ });+ expect(onClose).toHaveBeenCalled();+ });++ it("mutes one agent from its group", async () => {+ stubList();+ render(<AttentionInbox />);+ const groups = await screen.findAllByTestId("attention-group");+ const mute = within(groups[0]).getByRole("button", { pressed: false });+ fireEvent.click(mute);+ expect(useNotificationPrefs.getState().muted).toEqual(["brain"]);+ });++ it("says plainly when nothing is waiting", async () => {+ stubList([]);+ render(<AttentionInbox />);+ expect(await screen.findByTestId("attention-inbox-empty")).toBeTruthy();+ });+});++describe("quickActionsFor", () => {+ const base: AttentionItem = {+ kind: "proposal", agentId: "a", sessionId: "s", refId: "r", summary: "", sinceMs: 0,+ expiresMs: null, deferred: false, source: "queue", detail: {},+ };+ it("offers only what can be settled safely in one tap", () => {+ expect(quickActionsFor(base).map((a) => a.type)).toEqual(["deny", "allow"]);+ expect(quickActionsFor({ ...base, detail: { proposal_kind: "team" } })).toEqual([]);+ expect(quickActionsFor({ ...base, kind: "credential" })).toEqual([]);+ expect(quickActionsFor({ ...base, kind: "question", detail: { options: ["x", "y"], single: false } })).toEqual([]);+ });+});++describe("AttentionBell", () => {+ it("shows the count and opens the inbox under it", async () => {+ stubList();+ render(<AttentionBell />);+ const bell = screen.getByTestId("attention-bell");+ await waitFor(() => expect(screen.getByTestId("attention-bell-count").textContent).toBe("3"));+ expect(document.title.startsWith("(3) ")).toBe(true);+ fireEvent.click(bell);+ expect(await screen.findByTestId("attention-inbox")).toBeTruthy();+ expect(bell.getAttribute("aria-expanded")).toBe("true");+ fireEvent.keyDown(document, { key: "Escape" });+ await waitFor(() => expect(screen.queryByTestId("attention-inbox")).toBeNull());+ });++ it("hides the count at zero", async () => {+ stubList([]);+ render(<AttentionBell />);+ await act(async () => {+ await Promise.resolve();+ });+ expect(screen.queryByTestId("attention-bell-count")).toBeNull();+ });+});diff --git a/dodaios/ui/web/frontend/src/components/society/attention/AttentionInbox.tsx b/dodaios/ui/web/frontend/src/components/society/attention/AttentionInbox.tsxnew file mode 100644index 0000000000..e169c4d8f4--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/attention/AttentionInbox.tsx@@ -0,0 +1,403 @@+import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import {+ ArrowUpRight,+ Bell,+ BellOff,+ Check,+ Inbox,+ KeyRound,+ MessageCircleQuestion,+ ShieldAlert,+ SlidersHorizontal,+ Sparkles,+ X,+} from "lucide-react";++import { fill, useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { Switch } from "@/components/ui/switch";+import { AgentSwatch } from "@/components/society/AgentSwatch";+import { useSocietyRoster, type SocietyAgent } from "@/components/society/data";+import { openAgent } from "@/views/society/agentNavigation";++import { quickActionsFor, runQuickAction, type AttentionItem, type AttentionKind, type QuickAction } from "./attentionApi";+import {+ desktopNotificationsSupported,+ desktopPermission,+ setDesktopNotices,+ setFinishedNotices,+ toggleAgentMuted,+ useNotificationPrefs,+} from "./notificationPrefs";+import { forgetAttentionItem } from "./attentionStore";+import { useAgentAttention, type AttentionGroup } from "./useAgentAttention";++/**+ * Everything the agents are waiting on the person for, in one calm list.+ *+ * Grouped by agent, the agent who has waited longest first. Each row says+ * what is asked and since when; the simple ones can be settled right here (a+ * one-pick question, an approval, a proposed change) and every row opens its+ * card in the agent's chat. Nothing in this list ever widens a permission:+ * "allow" here always means this once.+ */++const LETTERS = "ABCD";++const KIND_ICON: Record<AttentionKind, typeof ShieldAlert> = {+ question: MessageCircleQuestion,+ approval: ShieldAlert,+ credential: KeyRound,+ proposal: Sparkles,+};++/** A clock that ticks every `ms` while something on screen depends on it. */+function useNow(ms: number): number {+ const [now, setNow] = useState(Date.now);+ useEffect(() => {+ const timer = window.setInterval(() => setNow(Date.now()), ms);+ return () => window.clearInterval(timer);+ }, [ms]);+ return now;+}++/** "now", "4 min", "2 h", "3 d". */+export function ageLabel(t: (key: string) => string, sinceMs: number, now: number): string {+ const minutes = Math.floor(Math.max(0, now - sinceMs) / 60_000);+ if (minutes < 1) return t("agent_attention.age_now");+ if (minutes < 60) return fill(t("agent_attention.age_minutes"), { n: minutes });+ const hours = Math.floor(minutes / 60);+ if (hours < 24) return fill(t("agent_attention.age_hours"), { n: hours });+ return fill(t("agent_attention.age_days"), { n: Math.floor(hours / 24) });+}++function clock(ms: number): string {+ const seconds = Math.max(0, Math.ceil(ms / 1000));+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;+}++function open(item: AttentionItem, onDone?: () => void) {+ openAgent(item.agentId, { sessionId: item.sessionId, cardRef: item.refId, kind: item.kind });+ onDone?.();+}++export function AttentionInbox({ onClose, className }: { onClose?: () => void; className?: string }) {+ const t = useT();+ const { groups, count, isLoading, isError } = useAgentAttention();+ const roster = useSocietyRoster();+ const agents = useMemo(() => {+ const map = new Map<string, SocietyAgent>();+ for (const agent of roster.data?.agents ?? []) map.set(agent.agentId, agent);+ return map;+ }, [roster.data]);+ const [settings, setSettings] = useState(false);+ const timed = groups.some((group) => group.items.some((item) => item.expiresMs !== null));+ const now = useNow(timed ? 1000 : 30_000);++ return (+ <div className={cn("flex max-h-[min(70vh,560px)] min-h-0 flex-col", className)} data-testid="attention-inbox">+ <header className="flex items-center gap-2 border-b border-border px-4 pb-2.5 pt-3">+ <h2 className="m-0 text-sm font-semibold text-foreground-strong">{t("agent_attention.title")}</h2>+ {count > 0 && (+ <span className="rounded-full bg-secondary px-1.5 text-xs font-medium tabular-nums text-muted-foreground" data-testid="attention-inbox-count">+ {count}+ </span>+ )}+ <span className="flex-1" />+ <button+ type="button"+ onClick={() => setSettings((on) => !on)}+ aria-expanded={settings}+ aria-label={t("agent_attention.settings")}+ title={t("agent_attention.settings")}+ className={cn(+ "inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors duration-150",+ "hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ settings && "bg-secondary text-foreground",+ )}+ >+ <SlidersHorizontal className="h-3.5 w-3.5" strokeWidth={1.9} aria-hidden />+ </button>+ {onClose && (+ <button+ type="button"+ onClick={onClose}+ aria-label={t("agent_attention.close")}+ className="inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors duration-150 hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <X className="h-3.5 w-3.5" strokeWidth={1.9} aria-hidden />+ </button>+ )}+ </header>+ {settings && <NotificationSettings />}+ <div className="chat-scroller min-h-0 flex-1 overflow-y-auto px-2 py-2">+ {isLoading && groups.length === 0 ? (+ <p role="status" className="px-3 py-6 text-center text-xs text-muted-foreground">{t("agent_attention.loading")}</p>+ ) : isError && groups.length === 0 ? (+ <p role="alert" className="px-3 py-6 text-center text-xs text-muted-foreground">{t("agent_attention.unavailable")}</p>+ ) : groups.length === 0 ? (+ <EmptyInbox />+ ) : (+ <ul className="m-0 flex list-none flex-col gap-1 p-0">+ {groups.map((group) => (+ <AgentGroupRow key={group.agentId} group={group} agent={agents.get(group.agentId)} now={now} onOpened={onClose} />+ ))}+ </ul>+ )}+ </div>+ </div>+ );+}++function EmptyInbox() {+ const t = useT();+ return (+ <div className="flex flex-col items-center gap-2 px-6 py-8 text-center" data-testid="attention-inbox-empty">+ <span className="inline-flex h-9 w-9 items-center justify-center rounded-full bg-secondary text-muted-foreground">+ <Inbox className="h-4 w-4" strokeWidth={1.8} aria-hidden />+ </span>+ <p className="m-0 text-sm font-medium text-foreground">{t("agent_attention.empty_title")}</p>+ <p className="m-0 max-w-[260px] text-xs leading-relaxed text-muted-foreground">{t("agent_attention.empty_body")}</p>+ </div>+ );+}++function AgentGroupRow({ group, agent, now, onOpened }: {+ group: AttentionGroup; agent: SocietyAgent | undefined; now: number; onOpened?: () => void;+}) {+ const t = useT();+ const muted = useNotificationPrefs((s) => s.muted.includes(group.agentId));+ const name = agent?.name || group.agentId;+ const muteLabel = fill(t(muted ? "agent_attention.unmute" : "agent_attention.mute"), { agent: name });+ return (+ <li className="group/agent rounded-lg" data-testid="attention-group" data-agent-id={group.agentId}>+ <div className="flex items-center gap-2 px-2 pb-1 pt-1.5">+ {agent ? <AgentSwatch agent={agent} size={20} /> : <span aria-hidden className="h-5 w-5 rounded-full bg-secondary" />}+ <span className="min-w-0 truncate text-xs font-semibold text-foreground">{name}</span>+ <span className="text-xs tabular-nums text-muted-foreground">+ {fill(t("agent_attention.waiting_count"), { count: group.items.length })}+ </span>+ <span className="flex-1" />+ {muted && <span className="text-[11px] text-muted-foreground">{t("agent_attention.muted")}</span>}+ <button+ type="button"+ onClick={() => toggleAgentMuted(group.agentId)}+ aria-pressed={muted}+ aria-label={muteLabel}+ title={muteLabel}+ className={cn(+ "inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-[opacity,color,background-color] duration-150",+ "hover:bg-secondary hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ muted ? "opacity-100" : "opacity-0 group-hover/agent:opacity-100",+ )}+ >+ {muted ? <BellOff className="h-3.5 w-3.5" strokeWidth={1.9} aria-hidden /> : <Bell className="h-3.5 w-3.5" strokeWidth={1.9} aria-hidden />}+ </button>+ </div>+ <ul className="m-0 flex list-none flex-col p-0">+ {group.items.map((item) => (+ <AttentionRow key={`${item.sessionId}:${item.refId}`} item={item} now={now} onOpened={onOpened} />+ ))}+ </ul>+ </li>+ );+}++function kindLabel(t: (key: string) => string, item: AttentionItem): string {+ if (item.kind === "approval" && item.source === "queue") return t("agent_attention.kind_parked");+ return t(`agent_attention.kind_${item.kind}`);+}++function AttentionRow({ item, now, onOpened }: { item: AttentionItem; now: number; onOpened?: () => void }) {+ const t = useT();+ const [busy, setBusy] = useState<number | null>(null);+ const [error, setError] = useState(false);+ const [done, setDone] = useState(false);+ const actions = quickActionsFor(item);+ const Icon = KIND_ICON[item.kind] ?? MessageCircleQuestion;+ const live = item.source === "chat";++ const run = async (action: QuickAction, index: number) => {+ if (busy !== null) return;+ setBusy(index);+ setError(false);+ try {+ await runQuickAction(item, action);+ setDone(true);+ // Leave the check on screen for a beat, then let the row go.+ window.setTimeout(() => forgetAttentionItem(item), 450);+ } catch {+ setError(true);+ } finally {+ setBusy(null);+ }+ };++ const meta: ReactNode[] = [kindLabel(t, item)];+ if (item.kind === "question" && (item.detail.count ?? 1) > 1) {+ meta.push(fill(t("agent_attention.step"), { step: (item.detail.step ?? 0) + 1, count: item.detail.count ?? 1 }));+ }+ meta.push(ageLabel(t, item.sinceMs, now));+ if (item.expiresMs !== null && item.kind === "question" && !item.deferred) {+ meta.push(fill(t("agent_attention.closes_in"), { time: clock(item.expiresMs - now) }));+ }++ return (+ <li+ className={cn(+ "group/item relative flex gap-2.5 rounded-lg px-2 py-2 transition-[background-color,opacity] duration-200",+ "hover:bg-secondary focus-within:bg-secondary",+ done && "opacity-60",+ )}+ data-testid="attention-item"+ data-kind={item.kind}+ data-ref={item.refId}+ >+ <span+ aria-hidden+ className={cn(+ "mt-0.5 inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-secondary group-hover/item:bg-background",+ live ? "text-warning" : "text-muted-foreground",+ )}+ >+ {done ? <Check className="h-3.5 w-3.5 text-foreground" strokeWidth={2.2} /> : <Icon className="h-3.5 w-3.5" strokeWidth={1.9} />}+ </span>+ <div className="min-w-0 flex-1">+ <button+ type="button"+ onClick={() => open(item, onOpened)}+ className="block w-full rounded-sm text-left text-sm leading-snug text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <span className="line-clamp-2 [overflow-wrap:anywhere]">{item.summary || kindLabel(t, item)}</span>+ </button>+ <p className="m-0 mt-0.5 flex flex-wrap items-center gap-x-1.5 text-xs text-muted-foreground">+ {meta.map((part, index) => (+ <span key={index} className="inline-flex items-center gap-1.5">+ {index > 0 && <span aria-hidden className="text-border-strong">·</span>}+ {part}+ </span>+ ))}+ </p>+ {actions.length > 0 && !done && (+ <div className="mt-2 flex flex-wrap gap-1.5" role="group" aria-label={t("agent_attention.quick_answer")}>+ {actions.map((action, index) => (+ <QuickButton key={index} item={item} action={action} index={index} busy={busy} onRun={run} />+ ))}+ </div>+ )}+ {error && (+ <p role="alert" className="m-0 mt-1.5 text-xs text-destructive">{t("agent_attention.failed")}</p>+ )}+ </div>+ <button+ type="button"+ onClick={() => open(item, onOpened)}+ aria-label={t("agent_attention.open_card")}+ title={t("agent_attention.open_card")}+ className={cn(+ "mt-0.5 inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-[opacity,color] duration-150",+ "opacity-0 hover:text-foreground group-hover/item:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",+ )}+ >+ <ArrowUpRight className="h-3.5 w-3.5" strokeWidth={1.9} aria-hidden />+ </button>+ </li>+ );+}++const QUIET_BUTTON =+ "inline-flex h-7 max-w-full items-center gap-1.5 rounded-md border border-border bg-background px-2 text-xs text-foreground " ++ "transition-colors duration-150 hover:border-border-strong hover:bg-surface-raised disabled:opacity-50 " ++ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";++const INK_BUTTON =+ "inline-flex h-7 items-center gap-1.5 rounded-md bg-foreground px-2.5 text-xs font-medium text-background " ++ "transition-opacity duration-150 hover:opacity-90 disabled:opacity-50 " ++ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background";++function QuickButton({ item, action, index, busy, onRun }: {+ item: AttentionItem;+ action: QuickAction;+ index: number;+ busy: number | null;+ onRun: (action: QuickAction, index: number) => void;+}) {+ const t = useT();+ const disabled = busy !== null;+ if (action.type === "option") {+ const label = item.detail.options?.[action.index] ?? "";+ return (+ <button type="button" disabled={disabled} onClick={() => onRun(action, index)} className={QUIET_BUTTON}+ aria-label={label} data-testid="attention-option">+ <span aria-hidden className="font-mono text-[10px] text-muted-foreground">{LETTERS[action.index]}</span>+ <span className="truncate">{label}</span>+ </button>+ );+ }+ const allow = action.type === "allow";+ const proposal = item.kind === "proposal";+ const key = allow+ ? proposal ? "agent_attention.approve" : item.source === "queue" ? "agent_attention.approve" : "agent_attention.allow_once"+ : proposal ? "agent_attention.decline" : "agent_attention.deny";+ return (+ <button type="button" disabled={disabled} onClick={() => onRun(action, index)}+ className={allow ? INK_BUTTON : QUIET_BUTTON} data-testid={allow ? "attention-allow" : "attention-deny"}>+ {t(key)}+ </button>+ );+}++function NotificationSettings() {+ const t = useT();+ const desktop = useNotificationPrefs((s) => s.desktop);+ const finished = useNotificationPrefs((s) => s.finished);+ const [permission, setPermission] = useState(desktopPermission);+ const supported = desktopNotificationsSupported();+ const hint = !supported+ ? t("agent_attention.desktop_unsupported")+ : permission === "denied"+ ? t("agent_attention.desktop_blocked")+ : t("agent_attention.desktop_hint");+ const switching = useRef(false);+ return (+ <section className="flex flex-col gap-3 border-b border-border bg-sidebar px-4 py-3" aria-label={t("agent_attention.settings")}+ data-testid="attention-settings">+ <SettingRow+ id="attention-desktop"+ label={t("agent_attention.desktop")}+ hint={hint}+ checked={desktop && permission === "granted"}+ disabled={!supported || permission === "denied"}+ onChange={(on) => {+ if (switching.current) return;+ switching.current = true;+ void setDesktopNotices(on).finally(() => {+ switching.current = false;+ setPermission(desktopPermission());+ });+ }}+ />+ <SettingRow+ id="attention-finished"+ label={t("agent_attention.finished")}+ hint={t("agent_attention.finished_hint")}+ checked={finished}+ onChange={setFinishedNotices}+ />+ </section>+ );+}++function SettingRow({ id, label, hint, checked, disabled = false, onChange }: {+ id: string; label: string; hint: string; checked: boolean; disabled?: boolean; onChange: (on: boolean) => void;+}) {+ return (+ <div className="flex items-start gap-3">+ <div className="min-w-0 flex-1">+ <label htmlFor={id} className="block text-xs font-medium text-foreground">{label}</label>+ <p id={`${id}-hint`} className="m-0 mt-0.5 text-[11px] leading-relaxed text-muted-foreground">{hint}</p>+ </div>+ <Switch id={id} checked={checked} disabled={disabled} onCheckedChange={onChange} aria-describedby={`${id}-hint`} />+ </div>+ );+}diff --git a/dodaios/ui/web/frontend/src/components/society/attention/attentionApi.ts b/dodaios/ui/web/frontend/src/components/society/attention/attentionApi.tsnew file mode 100644index 0000000000..10ed65ca3c--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/attention/attentionApi.ts@@ -0,0 +1,160 @@+import {+ answerAgentChatQuestion,+ resolveAgentChatApproval,+} from "@/lib/agentChatApi";++/**+ * The "needs you" list (`GET /api/agent-chat/attention`,+ * dodaios/agent_chat/attention.py) and the decisions the inbox can take on an+ * item without opening its chat.+ */++export type AttentionKind = "question" | "approval" | "credential" | "proposal";++export interface AttentionDetail {+ /** question: the current step's text and options. */+ question?: string;+ options?: string[];+ step?: number;+ count?: number;+ /** question: one tap answers it (a single pick). */+ single?: boolean;+ asker?: string;+ /** approval: the tool asking. */+ tool?: string;+ /** credential: the field's label. */+ label?: string;+ /** queue items: the capability and whether it was parked. */+ capability?: string;+ parked?: boolean;+ proposal_kind?: string;+}++export interface AttentionItem {+ kind: AttentionKind;+ agentId: string;+ sessionId: string;+ refId: string;+ summary: string;+ sinceMs: number;+ expiresMs: number | null;+ /** An end-of-turn card: the answer goes out as the next message. */+ deferred: boolean;+ /** `chat` for a card in a chat, `queue` for a society item. */+ source: "chat" | "queue";+ detail: AttentionDetail;+}++export interface AttentionList {+ items: AttentionItem[];+ count: number;+}++interface ItemRow {+ kind: AttentionKind;+ agent_id: string;+ session_id: string;+ ref_id: string;+ summary: string;+ since_ms: number;+ expires_ms: number | null;+ deferred?: boolean;+ source?: string;+ detail?: AttentionDetail;+}++function rowToItem(row: ItemRow): AttentionItem {+ return {+ kind: row.kind,+ agentId: row.agent_id,+ sessionId: row.session_id,+ refId: row.ref_id,+ summary: row.summary ?? "",+ sinceMs: Number(row.since_ms) || 0,+ expiresMs: row.expires_ms ? Number(row.expires_ms) : null,+ deferred: Boolean(row.deferred),+ source: row.source === "queue" ? "queue" : "chat",+ detail: row.detail ?? {},+ };+}++export async function fetchAttention(): Promise<AttentionList> {+ const res = await fetch("/api/agent-chat/attention");+ if (!res.ok) throw new Error(`attention ${res.status}`);+ const body = (await res.json()) as { items?: ItemRow[]; count?: number };+ const items = (body.items ?? []).map(rowToItem);+ return { items, count: typeof body.count === "number" ? body.count : items.length };+}++export interface FocusReport {+ agentId: string;+ sessionId: string;+ appFocused: boolean;+ muted: string[];+}++export async function reportAttentionFocus(report: FocusReport): Promise<void> {+ await fetch("/api/agent-chat/attention/focus", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ agent_id: report.agentId,+ session_id: report.sessionId,+ app_focused: report.appFocused,+ muted: report.muted,+ }),+ });+}++/** What the inbox can do with an item in place. */+export type QuickAction =+ | { type: "option"; index: number }+ | { type: "allow" }+ | { type: "deny" };++/** The quick actions an item offers; empty means "open it in its chat". */+export function quickActionsFor(item: AttentionItem): QuickAction[] {+ if (item.kind === "question") {+ const options = item.detail.options ?? [];+ return item.detail.single && options.length > 0+ ? options.slice(0, 4).map((_, index) => ({ type: "option", index }))+ : [];+ }+ if (item.kind === "approval") return [{ type: "deny" }, { type: "allow" }];+ if (item.kind === "proposal") {+ // A team offer is a pick list; it is answered on its card.+ return item.detail.proposal_kind === "team" ? [] : [{ type: "deny" }, { type: "allow" }];+ }+ return [];+}++async function resolveSociety(path: string, approve: boolean): Promise<void> {+ const res = await fetch(path, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ approve, note: "" }),+ });+ if (!res.ok) throw new Error(`resolve ${res.status}`);+}++/** Carry out a quick action on `item`. Never widens a permission: allow means once. */+export async function runQuickAction(item: AttentionItem, action: QuickAction): Promise<void> {+ if (item.kind === "question" && action.type === "option") {+ await answerAgentChatQuestion(item.sessionId, item.refId, item.detail.step ?? 0, { optionIndex: action.index });+ return;+ }+ const approve = action.type === "allow";+ if (item.kind === "approval" && item.source === "chat") {+ await resolveAgentChatApproval(item.sessionId, item.refId, approve ? "allow" : "deny");+ return;+ }+ if (item.kind === "approval") {+ await resolveSociety(`/api/society/approvals/${encodeURIComponent(item.refId)}/resolve`, approve);+ return;+ }+ if (item.kind === "proposal") {+ await resolveSociety(`/api/society/proposals/${encodeURIComponent(item.refId)}/resolve`, approve);+ return;+ }+ throw new Error(`no quick action for ${item.kind}`);+}diff --git a/dodaios/ui/web/frontend/src/components/society/attention/attentionBus.test.ts b/dodaios/ui/web/frontend/src/components/society/attention/attentionBus.test.tsnew file mode 100644index 0000000000..a1fc824d4a--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/attention/attentionBus.test.ts@@ -0,0 +1,174 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { useEventStore } from "@/store/events";+import { useAgentNavigation } from "@/views/society/agentNavigation";++import { currentFocus, onAgentAttention, presentAttention } from "./attentionBus";+import { applyTitleBadge, resetAttentionStore, useAttentionStore } from "./attentionStore";+import { resetNotificationPrefs, useNotificationPrefs } from "./notificationPrefs";++const queryClient = { invalidateQueries: vi.fn(async () => undefined) };++function focusApp(focused: boolean) {+ vi.spyOn(document, "hasFocus").mockReturnValue(focused);+}++beforeEach(() => {+ resetAttentionStore();+ resetNotificationPrefs();+ useEventStore.setState({ toasts: [], activeSection: "skills" });+ useAgentNavigation.setState({ request: null, onScreen: null });+ document.title = "Dodaios";+ queryClient.invalidateQueries.mockClear();+});++afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++const NEEDS = {+ count: 1,+ transition: "needs_input",+ agent_id: "scout",+ agent_name: "Scout",+ session_id: "society:scout",+ kind: "question",+ ref_id: "q1",+ summary: "Which database?",+};++describe("badge", () => {+ it("carries the count in the window title and clears it at zero", () => {+ applyTitleBadge(3);+ expect(document.title).toBe("(3) Dodaios");+ applyTitleBadge(1);+ expect(document.title).toBe("(1) Dodaios");+ applyTitleBadge(0);+ expect(document.title).toBe("Dodaios");+ });++ it("takes the count from every bus change and refreshes the roster dots", () => {+ focusApp(true);+ onAgentAttention({ count: 2 }, queryClient as never);+ expect(useAttentionStore.getState().count).toBe(2);+ expect(document.title).toBe("(2) Dodaios");+ expect(queryClient.invalidateQueries).toHaveBeenCalledWith({ queryKey: ["society", "roster"] });+ expect(useEventStore.getState().toasts).toHaveLength(0); // no transition, no notice+ });++ it("re-reads the list only once a view has asked for it", () => {+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({ items: [], count: 0 })));+ vi.stubGlobal("fetch", fetchMock);+ onAgentAttention({ count: 0 }, queryClient as never);+ expect(fetchMock).not.toHaveBeenCalled();+ useAttentionStore.setState({ list: { items: [], count: 0 } });+ onAgentAttention({ count: 0 }, queryClient as never);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+});++describe("presentAttention", () => {+ it("is quiet for a muted agent and for finished work when that is off", () => {+ focusApp(true);+ useNotificationPrefs.setState({ muted: ["scout"] });+ expect(presentAttention(NEEDS)).toBe("muted");+ useNotificationPrefs.setState({ muted: [], finished: false });+ expect(presentAttention({ ...NEEDS, transition: "done" })).toBe("off");+ expect(presentAttention({ ...NEEDS, transition: "" })).toBe("none");+ });++ it("stays silent while the person looks at that agent", () => {+ focusApp(true);+ useEventStore.setState({ activeSection: "agents" });+ useAgentNavigation.setState({ onScreen: { agentId: "scout" } });+ expect(presentAttention(NEEDS)).toBe("looking");+ expect(useEventStore.getState().toasts).toHaveLength(0);+ });++ it("shows an in-app toast whose button opens the agent at the card", () => {+ focusApp(true);+ expect(presentAttention(NEEDS)).toBe("toast");+ const [toast] = useEventStore.getState().toasts;+ expect(toast.kind).toBe("warning");+ expect(toast.message).toContain("Scout");+ expect(toast.message).toContain("Which database?");+ void toast.action?.onAction();+ expect(useAgentNavigation.getState().request).toMatchObject({ agentId: "scout", cardRef: "q1", kind: "question" });+ expect(useEventStore.getState().activeSection).toBe("agents");+ });++ it("uses a desktop notification in the background, silent for finished work", () => {+ focusApp(false);+ const shown: Array<{ title: string; options: NotificationOptions }> = [];+ class FakeNotification {+ static permission = "granted";+ onclick: (() => void) | null = null;+ constructor(title: string, options: NotificationOptions) {+ shown.push({ title, options });+ }+ close() {}+ }+ vi.stubGlobal("Notification", FakeNotification);+ useNotificationPrefs.setState({ desktop: true });+ expect(presentAttention({ ...NEEDS, transition: "done" })).toBe("desktop");+ expect(shown[0].options.silent).toBe(true);+ expect(presentAttention(NEEDS)).toBe("desktop");+ expect(shown[1].options.silent).toBe(false);+ expect(shown[1].options.body).toBe("Which database?");+ });++ it("leaves the telling to the main window in a detached one", () => {+ focusApp(true);+ useEventStore.setState({ solo: true });+ try {+ expect(presentAttention(NEEDS)).toBe("none");+ } finally {+ useEventStore.setState({ solo: false });+ }+ });++ it("falls back to a toast in the background when desktop notices are off", () => {+ focusApp(false);+ expect(presentAttention(NEEDS)).toBe("toast");+ });+});++describe("focus report", () => {+ it("names the agent on screen, and the lead on the front-page chat", () => {+ focusApp(true);+ useNotificationPrefs.setState({ muted: ["quiet"] });+ useEventStore.setState({ activeSection: "agents" });+ useAgentNavigation.setState({ onScreen: { agentId: "scout" } });+ expect(currentFocus()).toEqual({ agentId: "scout", sessionId: "", appFocused: true, muted: ["quiet"] });+ useEventStore.setState({ activeSection: "chats" });+ expect(currentFocus().agentId).toBe("jarvis");+ useEventStore.setState({ activeSection: "skills" });+ expect(currentFocus().agentId).toBe("");+ });+});++describe("list reads", () => {+ it("reads once more when a change arrives during a read, so it is never lost", async () => {+ const { refreshAttention } = await import("./attentionStore");+ const bodies = [+ { items: [], count: 0 },+ { items: [], count: 1 },+ ];+ let release: (() => void) | null = null;+ const fetchMock = vi.fn(async () => {+ const body = bodies.shift() ?? { items: [], count: 1 };+ if (fetchMock.mock.calls.length === 1) await new Promise<void>((resolve) => { release = resolve; });+ return new Response(JSON.stringify(body), { status: 200 });+ });+ vi.stubGlobal("fetch", fetchMock);+ const first = refreshAttention();+ void refreshAttention(); // a change lands while the first read is out+ expect(fetchMock).toHaveBeenCalledTimes(1);+ await vi.waitFor(() => expect(release).not.toBeNull());+ release!();+ await first;+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));+ await vi.waitFor(() => expect(useAttentionStore.getState().count).toBe(1));+ });+});diff --git a/dodaios/ui/web/frontend/src/components/society/attention/attentionBus.ts b/dodaios/ui/web/frontend/src/components/society/attention/attentionBus.tsnew file mode 100644index 0000000000..55febeeee7--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/attention/attentionBus.ts@@ -0,0 +1,181 @@+import type { QueryClient } from "@tanstack/react-query";++import { fill, translate } from "@/i18n";+import { useEventStore } from "@/store/events";+import {+ isAgentOnScreen,+ openAgent,+ useAgentNavigation,+ type CardKind,+} from "@/views/society/agentNavigation";++import { reportAttentionFocus, type FocusReport } from "./attentionApi";+import { refreshAttention, syncAttentionCount, useAttentionStore } from "./attentionStore";+import { desktopPermission, isAgentMuted, useNotificationPrefs } from "./notificationPrefs";++/**+ * The app-wide half of "needs you": the badge, the notifications, and the+ * focus report the backend's gate needs.+ *+ * It lives at the socket (`useWebSocket` hands it every `AgentAttentionChanged`+ * envelope and every reconnect), so it works on every screen, not only in the+ * Agents section. Nothing here speaks: a change becomes a count, an in-app+ * toast while the app is in front, or a desktop notification while it is in+ * the background, when the person turned those on.+ */++/** The roster's fixed lead id; the front-page chat is the lead's chat. */+const LEAD_AGENT_ID = "jarvis";++/** How often a focused window repeats its focus report (the backend forgets after 5 min). */+const FOCUS_HEARTBEAT_MS = 120_000;+const FOCUS_DEBOUNCE_MS = 250;++/** The bus payload (dodaios/agent_chat/attention.py `AgentAttentionChanged`). */+export interface AttentionEnvelope {+ count?: number;+ transition?: string;+ agent_id?: string;+ agent_name?: string;+ session_id?: string;+ kind?: string;+ ref_id?: string;+ summary?: string;+}++const CARD_KINDS: readonly string[] = ["question", "approval", "credential", "proposal"];++function cardKind(kind: string | undefined): CardKind | undefined {+ return kind && CARD_KINDS.includes(kind) ? (kind as CardKind) : undefined;+}++export type Presentation = "none" | "muted" | "off" | "looking" | "desktop" | "toast";++/** Turn a transition into the one notice it deserves; returns which one. */+export function presentAttention(note: AttentionEnvelope): Presentation {+ const agentId = note.agent_id ?? "";+ const transition = note.transition ?? "";+ if (!agentId || (transition !== "needs_input" && transition !== "done")) return "none";+ // A detached section window keeps its badge but leaves the telling to the+ // main window, so one change is never announced twice.+ if (useEventStore.getState().solo) return "none";+ if (isAgentMuted(agentId)) return "muted";+ const prefs = useNotificationPrefs.getState();+ const done = transition === "done";+ if (done && !prefs.finished) return "off";+ const focused = typeof document !== "undefined" && document.hasFocus();+ if (focused && isAgentOnScreen(agentId)) return "looking";++ const agent = note.agent_name || translate("agent_attention.fallback_agent");+ const summary = (note.summary ?? "").trim();+ const go = () => openAgent(agentId, {+ sessionId: note.session_id || undefined,+ cardRef: note.ref_id || undefined,+ kind: cardKind(note.kind),+ });+ const title = fill(translate(done ? "agent_attention.notify_done" : "agent_attention.notify_needs"), { agent });++ if (!focused && prefs.desktop && desktopPermission() === "granted") {+ try {+ const notice = new Notification(title, {+ body: done ? translate("agent_attention.notify_done_body") : summary || translate("agent_attention.notify_needs_body"),+ tag: `dodaios-agent-${agentId}-${transition}`,+ // Finished work is news, not an alarm.+ silent: done,+ });+ notice.onclick = () => {+ window.focus();+ go();+ notice.close();+ };+ return "desktop";+ } catch {+ // A window that refuses notifications after all: the toast below.+ }+ }+ const message = summary && !done ? `${title}: ${summary}` : title;+ useEventStore.getState().pushToast(done ? "info" : "warning", message, {+ action: { label: translate("agent_attention.open"), onAction: go },+ ttlMs: done ? 4_000 : 8_000,+ });+ return "toast";+}++/** One bus envelope: refresh the badge and lists, then notify if it is news. */+export function onAgentAttention(payload: unknown, queryClient: QueryClient): void {+ const note = (payload ?? {}) as AttentionEnvelope;+ if (typeof note.count === "number") syncAttentionCount(note.count);+ // The list is re-read only once a view has asked for it; the badge needs none.+ if (useAttentionStore.getState().list) void refreshAttention();+ // The roster carries each agent's waiting reason (the warning dot).+ void queryClient.invalidateQueries({ queryKey: ["society", "roster"] });+ presentAttention(note);+}++/** On every (re)connect: read the count, and start the focus report once. */+export function seedAgentAttention(): void {+ startFocusReporter();+ void refreshAttention();+ sendFocus(true);+}++// ------------------------------------------------------------- focus report++/** What the person is looking at, as the backend's gate wants it. */+export function currentFocus(): FocusReport {+ const section = useEventStore.getState().activeSection;+ const onScreen = useAgentNavigation.getState().onScreen;+ const visible = typeof document === "undefined" || document.visibilityState !== "hidden";+ const appFocused = visible && typeof document !== "undefined" && document.hasFocus();+ let agentId = "";+ let sessionId = "";+ if (section === "agents" && onScreen) {+ agentId = onScreen.agentId;+ sessionId = onScreen.sessionId ?? "";+ } else if (section === "chats") {+ agentId = LEAD_AGENT_ID;+ }+ return { agentId, sessionId, appFocused, muted: [...useNotificationPrefs.getState().muted] };+}++let lastSent = "";+let debounce: ReturnType<typeof setTimeout> | null = null;+let reporterStarted = false;++function sendFocus(force = false): void {+ const report = currentFocus();+ const key = JSON.stringify(report);+ if (!force && key === lastSent) return;+ lastSent = key;+ void reportAttentionFocus(report).catch(() => {+ lastSent = ""; // try again with the next change+ });+}++function scheduleFocus(): void {+ if (debounce) clearTimeout(debounce);+ debounce = setTimeout(() => {+ debounce = null;+ sendFocus();+ }, FOCUS_DEBOUNCE_MS);+}++function startFocusReporter(): void {+ if (reporterStarted || typeof window === "undefined") return;+ reporterStarted = true;+ window.addEventListener("focus", scheduleFocus);+ window.addEventListener("blur", scheduleFocus);+ document.addEventListener("visibilitychange", scheduleFocus);+ useAgentNavigation.subscribe((state, previous) => {+ if (state.onScreen !== previous.onScreen) scheduleFocus();+ });+ useEventStore.subscribe((state, previous) => {+ if (state.activeSection !== previous.activeSection) scheduleFocus();+ });+ useNotificationPrefs.subscribe((state, previous) => {+ if (state.muted !== previous.muted) scheduleFocus();+ });+ window.setInterval(() => {+ if (currentFocus().appFocused) sendFocus(true);+ }, FOCUS_HEARTBEAT_MS);+}diff --git a/dodaios/ui/web/frontend/src/components/society/attention/attentionStore.ts b/dodaios/ui/web/frontend/src/components/society/attention/attentionStore.tsnew file mode 100644index 0000000000..e12a80ba10--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/attention/attentionStore.ts@@ -0,0 +1,94 @@+import { create } from "zustand";++import { fetchAttention, type AttentionItem, type AttentionList } from "./attentionApi";++/**+ * The "needs you" list and its count, held once for the whole app.+ *+ * A plain store rather than a query: the socket feeds it from outside any+ * React tree (`attentionBus`), and the bell must work in every shell that+ * renders the Agents section, with or without a query client around it.+ */++export type AttentionStatus = "idle" | "loading" | "ready" | "error";++interface AttentionState {+ /** The badge: open items across every agent (the window title carries it too). */+ count: number;+ /** The last list read; null until someone asked for it. */+ list: AttentionList | null;+ status: AttentionStatus;+ /** When the list was last read (ms), 0 for never. */+ readAt: number;+}++export const useAttentionStore = create<AttentionState>(() => ({ count: 0, list: null, status: "idle", readAt: 0 }));++const TITLE_BADGE = /^\(\d+\)\s+/;++/** Prefix the window title with the count ("(2) Dodaios"); restore it at zero. */+export function applyTitleBadge(count: number): void {+ if (typeof document === "undefined") return;+ const base = document.title.replace(TITLE_BADGE, "");+ const next = count > 0 ? `(${count}) ${base}` : base;+ if (document.title !== next) document.title = next;+}++/** Set the badge (the bell and the window title). */+export function syncAttentionCount(count: number): void {+ const safe = Number.isFinite(count) && count > 0 ? Math.floor(count) : 0;+ if (useAttentionStore.getState().count !== safe) useAttentionStore.setState({ count: safe });+ applyTitleBadge(safe);+}++let inflight: Promise<void> | null = null;+/** A change arrived while a read was on its way: read once more after it. */+let again = false;++/**+ * Read the list again, one request at a time. A call during a read asks for+ * one more read after it, so a change the running read may have missed is+ * never lost.+ */+export function refreshAttention(): Promise<void> {+ if (inflight) {+ again = true;+ return inflight;+ }+ if (!useAttentionStore.getState().list) useAttentionStore.setState({ status: "loading" });+ inflight = fetchAttention()+ .then((list) => {+ useAttentionStore.setState({ list, status: "ready", readAt: Date.now() });+ syncAttentionCount(list.count);+ })+ .catch(() => {+ // Keep what is on screen; the next change or reconnect tries again.+ useAttentionStore.setState((state) => ({ status: state.list ? state.status : "error" }));+ })+ .finally(() => {+ inflight = null;+ if (again) {+ again = false;+ void refreshAttention();+ }+ });+ return inflight;+}++/** Drop an answered item right away; the next read confirms it. */+export function forgetAttentionItem(item: AttentionItem): void {+ const { list } = useAttentionStore.getState();+ if (!list) return;+ const items = list.items.filter((other) => !(other.refId === item.refId && other.sessionId === item.sessionId));+ if (items.length === list.items.length) return;+ const count = Math.max(0, list.count - (list.items.length - items.length));+ useAttentionStore.setState({ list: { items, count } });+ syncAttentionCount(count);+}++/** For tests: back to an empty, unread store. */+export function resetAttentionStore(): void {+ inflight = null;+ again = false;+ useAttentionStore.setState({ count: 0, list: null, status: "idle", readAt: 0 });+}diff --git a/dodaios/ui/web/frontend/src/components/society/attention/notificationPrefs.ts b/dodaios/ui/web/frontend/src/components/society/attention/notificationPrefs.tsnew file mode 100644index 0000000000..87a5b57980--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/attention/notificationPrefs.ts@@ -0,0 +1,107 @@+import { create } from "zustand";++/**+ * How loudly waiting agents may reach the person, kept per window.+ *+ * * `muted`: agents that never notify (they still show in the list and badge).+ * * `desktop`: desktop notifications while the app is in the background. Off+ * until the person turns it on, because turning it on asks the system for+ * permission and nothing here may ask uninvited.+ * * `finished`: also tell when an agent finishes a job the person gave it.+ */++const STORAGE_KEY = "dodaios.attention.prefs";++export interface NotificationPrefs {+ muted: string[];+ desktop: boolean;+ finished: boolean;+}++const DEFAULTS: NotificationPrefs = { muted: [], desktop: false, finished: true };++function load(): NotificationPrefs {+ try {+ const raw = window.localStorage.getItem(STORAGE_KEY);+ if (!raw) return { ...DEFAULTS };+ const parsed = JSON.parse(raw) as Partial<NotificationPrefs>;+ return {+ muted: Array.isArray(parsed.muted) ? parsed.muted.filter((id) => typeof id === "string") : [],+ desktop: parsed.desktop === true,+ finished: parsed.finished !== false,+ };+ } catch {+ return { ...DEFAULTS };+ }+}++function save(prefs: NotificationPrefs): void {+ try {+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(prefs));+ } catch {+ // Private mode or a full disk: the choice holds for this window only.+ }+}++export const useNotificationPrefs = create<NotificationPrefs>(() => load());++function update(patch: Partial<NotificationPrefs>): void {+ useNotificationPrefs.setState(patch);+ save(useNotificationPrefs.getState());+}++export function isAgentMuted(agentId: string): boolean {+ return useNotificationPrefs.getState().muted.includes(agentId);+}++export function toggleAgentMuted(agentId: string): void {+ const { muted } = useNotificationPrefs.getState();+ update({ muted: muted.includes(agentId) ? muted.filter((id) => id !== agentId) : [...muted, agentId] });+}++export function setFinishedNotices(on: boolean): void {+ update({ finished: on });+}++/** Whether this window can show desktop notifications at all. */+export function desktopNotificationsSupported(): boolean {+ return typeof window !== "undefined" && "Notification" in window;+}++/** The system's answer for desktop notifications ("default" until asked). */+export function desktopPermission(): NotificationPermission | "unsupported" {+ return desktopNotificationsSupported() ? Notification.permission : "unsupported";+}++/**+ * Turn desktop notifications on or off. Turning them on asks the system once+ * (from the person's own click); a refusal leaves them off.+ */+export async function setDesktopNotices(on: boolean): Promise<boolean> {+ if (!on) {+ update({ desktop: false });+ return false;+ }+ if (!desktopNotificationsSupported()) return false;+ let permission = Notification.permission;+ if (permission === "default") {+ try {+ permission = await Notification.requestPermission();+ } catch {+ permission = "denied";+ }+ }+ const granted = permission === "granted";+ update({ desktop: granted });+ return granted;+}++/** For tests: forget the stored choice. */+export function resetNotificationPrefs(): void {+ try {+ window.localStorage.removeItem(STORAGE_KEY);+ } catch {+ // nothing stored+ }+ useNotificationPrefs.setState({ ...DEFAULTS, muted: [] });+}diff --git a/dodaios/ui/web/frontend/src/components/society/attention/useAgentAttention.ts b/dodaios/ui/web/frontend/src/components/society/attention/useAgentAttention.tsnew file mode 100644index 0000000000..8ab10f0093--- /dev/null+++ b/dodaios/ui/web/frontend/src/components/society/attention/useAgentAttention.ts@@ -0,0 +1,66 @@+import { useEffect, useMemo } from "react";++import type { AttentionItem } from "./attentionApi";+import { refreshAttention, useAttentionStore } from "./attentionStore";++/** Items of one agent, oldest first, with the agent's own oldest wait. */+export interface AttentionGroup {+ agentId: string;+ items: AttentionItem[];+ sinceMs: number;+}++/** A read younger than this is fresh enough for a newly mounted view. */+const FRESH_MS = 10_000;+/**+ * The slow safety read. The socket refreshes the list on every change; this+ * only catches society items decided without a chat event.+ */+const POLL_MS = 60_000;++/** The live "needs you" list, read on mount, on window focus and every minute. */+export function useAgentAttention() {+ const list = useAttentionStore((s) => s.list);+ const status = useAttentionStore((s) => s.status);+ const count = useAttentionStore((s) => s.count);++ useEffect(() => {+ const refresh = () => {+ if (typeof document !== "undefined" && document.visibilityState === "hidden") return;+ void refreshAttention();+ };+ if (Date.now() - useAttentionStore.getState().readAt > FRESH_MS) refresh();+ const timer = window.setInterval(refresh, POLL_MS);+ window.addEventListener("focus", refresh);+ return () => {+ window.clearInterval(timer);+ window.removeEventListener("focus", refresh);+ };+ }, []);++ const items = useMemo(() => list?.items ?? [], [list]);+ const groups = useMemo(() => groupByAgent(items), [items]);+ return {+ items,+ groups,+ count: list ? list.count : count,+ isLoading: status === "loading" || (status === "idle" && !list),+ isError: status === "error",+ };+}++/** Agents ordered by who has waited longest; each agent's items oldest first. */+export function groupByAgent(items: readonly AttentionItem[]): AttentionGroup[] {+ const byAgent = new Map<string, AttentionItem[]>();+ for (const item of items) {+ const list = byAgent.get(item.agentId) ?? [];+ list.push(item);+ byAgent.set(item.agentId, list);+ }+ return [...byAgent.entries()]+ .map(([agentId, list]) => {+ const sorted = [...list].sort((a, b) => a.sinceMs - b.sinceMs);+ return { agentId, items: sorted, sinceMs: sorted[0]?.sinceMs ?? 0 };+ })+ .sort((a, b) => a.sinceMs - b.sinceMs);+}diff --git a/dodaios/ui/web/frontend/src/components/society/data.ts b/dodaios/ui/web/frontend/src/components/society/data.tsindex 51dc83989f..8e20bd95be 100644--- a/dodaios/ui/web/frontend/src/components/society/data.ts+++ b/dodaios/ui/web/frontend/src/components/society/data.ts@@ -18,6 +18,7 @@ import type { MentionPlugin } from "./chat/mentionItems";import type { AgentApprovalMode, AgentRuntime, BrowserMode, Checkpoint, SocietyAgentRow } from "@/lib/societyApi";import type { CompanionAppearance } from "./companion/appearance";+import type { WaitingReason } from "./roster/rosterPreview";import { useCreateAgentDialog } from "./create/createAgentStore";import { NEUTRAL_ASSISTANT_NAME } from "@/lib/assistantNameCache";@@ -174,10 +175,15 @@ export interface SocietyAgent {wikiNamespace: string;/** The canonical agent_chat session bound to this agent; null on sample rows. */chatSessionId: string | null;+ /** What it waits on the person for right now (a question, an approval, ...); null when nothing. */+ waitingReason?: WaitingReason | null;routines: AgentRoutine[];stats: AgentStats;}+/** Why an agent waits on the person (the society payload's `waiting_reason`). */+export type { WaitingReason };+export interface RosterData {agents: SocietyAgent[];/** True while rows come from the sample roster rather than society.db. */@@ -292,6 +298,14 @@ export function rowToAgent(row: SocietyAgentRow): SocietyAgent {workspaceDir: row.workspace_dir ?? "",wikiNamespace: row.wiki_namespace ?? "",chatSessionId: row.session_id || null,+ waitingReason: row.waiting_reason+ ? {+ kind: row.waiting_reason.kind,+ summary: row.waiting_reason.summary,+ sessionId: row.waiting_reason.session_id,+ refId: row.waiting_reason.ref_id,+ }+ : null,routines: [],stats: {runs: row.stats?.runs ?? 0,diff --git a/dodaios/ui/web/frontend/src/hooks/useWebSocket.ts b/dodaios/ui/web/frontend/src/hooks/useWebSocket.tsindex d3d62a640c..0bee50ebfb 100644--- a/dodaios/ui/web/frontend/src/hooks/useWebSocket.ts+++ b/dodaios/ui/web/frontend/src/hooks/useWebSocket.ts@@ -39,6 +39,7 @@ import { announceDictationSettings } from "@/hooks/usePromptMode";import { petKeys } from "@/hooks/usePets";import { focusChatComposer, startNewTextChat } from "@/lib/newChat";import { SPEAKER_MUTE_EVENT } from "@/lib/speakerMute";+import { onAgentAttention, seedAgentAttention } from "@/components/society/attention/attentionBus";let singleton: WSClient | null = null;@@ -126,6 +127,8 @@ export function useWebSocket(): void {// with the window hidden, a wake-word denial before the socket opened)// is a one-shot bus event and would otherwise never be told.seedPermissionToast();+ // The "waiting for you" badge, re-read on every (re)connect.+ seedAgentAttention();return;}@@ -693,6 +696,8 @@ export function useWebSocket(): void {);}+ if (env.event_name === "AgentAttentionChanged") onAgentAttention(env.payload, queryClient);+if (env.event_name === "ToastNotification") {const p = env.payload as { kind?: string; message?: string };if (typeof p.message === "string") {diff --git a/dodaios/ui/web/frontend/src/i18n/agent-attention-i18n-parity.test.ts b/dodaios/ui/web/frontend/src/i18n/agent-attention-i18n-parity.test.tsnew file mode 100644index 0000000000..a3f089c936--- /dev/null+++ b/dodaios/ui/web/frontend/src/i18n/agent-attention-i18n-parity.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from "vitest";+import en from "./locales/en.json";+import de from "./locales/de.json";+import es from "./locales/es.json";+import pt from "./locales/pt.json";+import zh from "./locales/zh.json";++type Locale = Record<string, unknown>;++const block = (locale: Locale) => (locale.agent_attention ?? {}) as Record<string, string>;+const placeholders = (text: string) => (text.match(/\{\w+\}/g) ?? []).sort();++describe("agent attention i18n parity", () => {+ it("en defines the attention block", () => {+ expect(Object.keys(block(en as Locale)).length).toBeGreaterThan(0);+ });++ for (const [language, locale] of Object.entries({ de, es, pt, zh })) {+ it(`${language} has the same keys and placeholders as en`, () => {+ const source = block(en as Locale);+ const target = block(locale as Locale);+ expect(Object.keys(target).sort()).toEqual(Object.keys(source).sort());+ for (const [key, text] of Object.entries(source)) {+ expect(placeholders(target[key] ?? ""), `${language}.${key}`).toEqual(placeholders(text));+ expect((target[key] ?? "").trim().length, `${language}.${key}`).toBeGreaterThan(0);+ }+ });+ }++ it("never uses the assistant-name token, which the translator would fill", () => {+ for (const text of Object.values(block(en as Locale))) expect(text).not.toContain("{name}");+ });+});diff --git a/dodaios/ui/web/frontend/src/i18n/locales/de.json b/dodaios/ui/web/frontend/src/i18n/locales/de.jsonindex 3bfc3a95a7..56678010c9 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/de.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/de.json@@ -4192,6 +4192,51 @@"open_in_obsidian": "In Obsidian öffnen","open_vault_in_obsidian": "Vault in Obsidian öffnen"},+ "agent_attention": {+ "bell": "Wartet auf dich",+ "bell_count": "Wartet auf dich: {count}",+ "title": "Wartet auf dich",+ "close": "Schließen",+ "settings": "Benachrichtigungen einstellen",+ "loading": "Wird geladen …",+ "unavailable": "Die Liste ist gerade nicht verfügbar.",+ "empty_title": "Nichts wartet auf dich",+ "empty_body": "Braucht ein Agent eine Antwort, eine Freigabe oder einen Schlüssel, erscheint er hier.",+ "waiting_count": "{count} offen",+ "mute": "{agent} stummschalten",+ "unmute": "Stummschaltung für {agent} aufheben",+ "muted": "Stumm",+ "kind_question": "Frage",+ "kind_approval": "Freigabe",+ "kind_credential": "Schlüssel nötig",+ "kind_proposal": "Vorgeschlagene Änderung",+ "kind_parked": "Geparkte Freigabe",+ "step": "{step} von {count}",+ "closes_in": "entscheidet selbst in {time}",+ "age_now": "jetzt",+ "age_minutes": "{n} Min.",+ "age_hours": "{n} Std.",+ "age_days": "{n} T.",+ "quick_answer": "Hier antworten",+ "allow_once": "Einmal erlauben",+ "deny": "Ablehnen",+ "approve": "Bestätigen",+ "decline": "Ablehnen",+ "open": "Öffnen",+ "open_card": "Im Chat öffnen",+ "failed": "Das hat nicht geklappt. Versuch es noch einmal oder öffne den Chat.",+ "desktop": "Desktop-Benachrichtigungen",+ "desktop_hint": "Nur wenn die App im Hintergrund ist.",+ "desktop_blocked": "Vom System blockiert. Erlaube Benachrichtigungen für die App in den Systemeinstellungen.",+ "desktop_unsupported": "In diesem Fenster nicht verfügbar.",+ "finished": "Wenn ein Agent fertig ist",+ "finished_hint": "Ein leiser Hinweis, nur für Aufgaben von dir.",+ "fallback_agent": "Ein Agent",+ "notify_needs": "{agent} wartet auf dich",+ "notify_needs_body": "Öffne den Chat, um zu antworten.",+ "notify_done": "{agent} ist fertig",+ "notify_done_body": "Öffne den Chat, um das Ergebnis zu sehen."+ },"backlinks_panel": {"load_error": "Konnte Backlinks nicht laden.","empty": "Keine Backlinks."diff --git a/dodaios/ui/web/frontend/src/i18n/locales/en.json b/dodaios/ui/web/frontend/src/i18n/locales/en.jsonindex e5e369eaa0..0966165437 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/en.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/en.json@@ -4192,6 +4192,51 @@"open_in_obsidian": "Open in Obsidian","open_vault_in_obsidian": "Open vault in Obsidian"},+ "agent_attention": {+ "bell": "Waiting for you",+ "bell_count": "Waiting for you: {count}",+ "title": "Waiting for you",+ "close": "Close",+ "settings": "Notification settings",+ "loading": "Loading…",+ "unavailable": "The list is not available right now.",+ "empty_title": "Nothing is waiting for you",+ "empty_body": "When an agent needs an answer, an approval or a key, it shows up here.",+ "waiting_count": "{count} waiting",+ "mute": "Mute {agent}",+ "unmute": "Unmute {agent}",+ "muted": "Muted",+ "kind_question": "Question",+ "kind_approval": "Approval",+ "kind_credential": "Key needed",+ "kind_proposal": "Proposed change",+ "kind_parked": "Parked approval",+ "step": "{step} of {count}",+ "closes_in": "decides itself in {time}",+ "age_now": "now",+ "age_minutes": "{n} min",+ "age_hours": "{n} h",+ "age_days": "{n} d",+ "quick_answer": "Answer here",+ "allow_once": "Allow once",+ "deny": "Deny",+ "approve": "Approve",+ "decline": "Decline",+ "open": "Open",+ "open_card": "Open in chat",+ "failed": "That did not go through. Try again, or open the chat.",+ "desktop": "Desktop notifications",+ "desktop_hint": "Only while the app is in the background.",+ "desktop_blocked": "Blocked by the system. Allow notifications for the app in the system settings.",+ "desktop_unsupported": "Not available in this window.",+ "finished": "When an agent finishes",+ "finished_hint": "A quiet note, only for jobs you gave it.",+ "fallback_agent": "An agent",+ "notify_needs": "{agent} is waiting for you",+ "notify_needs_body": "Open the chat to answer.",+ "notify_done": "{agent} finished",+ "notify_done_body": "Open the chat to see the result."+ },"backlinks_panel": {"load_error": "Could not load backlinks.","empty": "No backlinks."diff --git a/dodaios/ui/web/frontend/src/i18n/locales/es.json b/dodaios/ui/web/frontend/src/i18n/locales/es.jsonindex f66d20b068..4fab7a43ca 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/es.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/es.json@@ -4192,6 +4192,51 @@"open_in_obsidian": "Abrir en Obsidian","open_vault_in_obsidian": "Abrir almacén en Obsidian"},+ "agent_attention": {+ "bell": "Esperando tu respuesta",+ "bell_count": "Esperando tu respuesta: {count}",+ "title": "Esperando tu respuesta",+ "close": "Cerrar",+ "settings": "Ajustes de notificaciones",+ "loading": "Cargando…",+ "unavailable": "La lista no está disponible ahora mismo.",+ "empty_title": "Nada espera tu respuesta",+ "empty_body": "Cuando un agente necesite una respuesta, una aprobación o una clave, aparecerá aquí.",+ "waiting_count": "{count} pendientes",+ "mute": "Silenciar a {agent}",+ "unmute": "Dejar de silenciar a {agent}",+ "muted": "Silenciado",+ "kind_question": "Pregunta",+ "kind_approval": "Aprobación",+ "kind_credential": "Hace falta una clave",+ "kind_proposal": "Cambio propuesto",+ "kind_parked": "Aprobación aparcada",+ "step": "{step} de {count}",+ "closes_in": "decide solo en {time}",+ "age_now": "ahora",+ "age_minutes": "{n} min",+ "age_hours": "{n} h",+ "age_days": "{n} d",+ "quick_answer": "Responder aquí",+ "allow_once": "Permitir una vez",+ "deny": "Denegar",+ "approve": "Aprobar",+ "decline": "Rechazar",+ "open": "Abrir",+ "open_card": "Abrir en el chat",+ "failed": "No se pudo completar. Inténtalo de nuevo o abre el chat.",+ "desktop": "Notificaciones de escritorio",+ "desktop_hint": "Solo cuando la app está en segundo plano.",+ "desktop_blocked": "Bloqueadas por el sistema. Permite las notificaciones de la app en los ajustes del sistema.",+ "desktop_unsupported": "No disponible en esta ventana.",+ "finished": "Cuando un agente termina",+ "finished_hint": "Un aviso discreto, solo para tareas que le diste.",+ "fallback_agent": "Un agente",+ "notify_needs": "{agent} espera tu respuesta",+ "notify_needs_body": "Abre el chat para responder.",+ "notify_done": "{agent} ha terminado",+ "notify_done_body": "Abre el chat para ver el resultado."+ },"backlinks_panel": {"load_error": "No se pudieron cargar los retroenlaces.","empty": "Sin retroenlaces."diff --git a/dodaios/ui/web/frontend/src/i18n/locales/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/pt.jsonindex 1445c3354e..1becb72cee 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/pt.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/pt.json@@ -4192,6 +4192,51 @@"open_in_obsidian": "Abrir no Obsidian","open_vault_in_obsidian": "Abrir vault no Obsidian"},+ "agent_attention": {+ "bell": "À espera de você",+ "bell_count": "À espera de você: {count}",+ "title": "À espera de você",+ "close": "Fechar",+ "settings": "Configurações de notificação",+ "loading": "Carregando…",+ "unavailable": "A lista não está disponível agora.",+ "empty_title": "Nada está à sua espera",+ "empty_body": "Quando um agente precisar de uma resposta, uma aprovação ou uma chave, ele aparece aqui.",+ "waiting_count": "{count} pendentes",+ "mute": "Silenciar {agent}",+ "unmute": "Reativar {agent}",+ "muted": "Silenciado",+ "kind_question": "Pergunta",+ "kind_approval": "Aprovação",+ "kind_credential": "Chave necessária",+ "kind_proposal": "Mudança proposta",+ "kind_parked": "Aprovação em espera",+ "step": "{step} de {count}",+ "closes_in": "decide sozinho em {time}",+ "age_now": "agora",+ "age_minutes": "{n} min",+ "age_hours": "{n} h",+ "age_days": "{n} d",+ "quick_answer": "Responder aqui",+ "allow_once": "Permitir uma vez",+ "deny": "Negar",+ "approve": "Aprovar",+ "decline": "Recusar",+ "open": "Abrir",+ "open_card": "Abrir no chat",+ "failed": "Não deu certo. Tente de novo ou abra o chat.",+ "desktop": "Notificações na área de trabalho",+ "desktop_hint": "Só quando o app está em segundo plano.",+ "desktop_blocked": "Bloqueadas pelo sistema. Permita as notificações do app nas configurações do sistema.",+ "desktop_unsupported": "Indisponível nesta janela.",+ "finished": "Quando um agente termina",+ "finished_hint": "Um aviso discreto, só para tarefas que você deu.",+ "fallback_agent": "Um agente",+ "notify_needs": "{agent} está à sua espera",+ "notify_needs_body": "Abra o chat para responder.",+ "notify_done": "{agent} terminou",+ "notify_done_body": "Abra o chat para ver o resultado."+ },"backlinks_panel": {"load_error": "Não foi possível carregar os backlinks.","empty": "Sem backlinks."diff --git a/dodaios/ui/web/frontend/src/i18n/locales/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/zh.jsonindex 90e98b0bdc..17f9f20a32 100644--- a/dodaios/ui/web/frontend/src/i18n/locales/zh.json+++ b/dodaios/ui/web/frontend/src/i18n/locales/zh.json@@ -4192,6 +4192,51 @@"open_in_obsidian": "在 Obsidian 中打开","open_vault_in_obsidian": "在 Obsidian 中打开资料库"},+ "agent_attention": {+ "bell": "等你处理",+ "bell_count": "等你处理:{count}",+ "title": "等你处理",+ "close": "关闭",+ "settings": "通知设置",+ "loading": "正在加载…",+ "unavailable": "列表暂时不可用。",+ "empty_title": "没有等你处理的事项",+ "empty_body": "当智能体需要你的回答、批准或密钥时,会显示在这里。",+ "waiting_count": "{count} 项待处理",+ "mute": "将 {agent} 设为静音",+ "unmute": "取消 {agent} 的静音",+ "muted": "已静音",+ "kind_question": "问题",+ "kind_approval": "批准",+ "kind_credential": "需要密钥",+ "kind_proposal": "建议的更改",+ "kind_parked": "搁置的批准",+ "step": "第 {step} 项,共 {count} 项",+ "closes_in": "{time} 后自动决定",+ "age_now": "刚刚",+ "age_minutes": "{n} 分钟",+ "age_hours": "{n} 小时",+ "age_days": "{n} 天",+ "quick_answer": "在此回答",+ "allow_once": "允许一次",+ "deny": "拒绝",+ "approve": "批准",+ "decline": "拒绝",+ "open": "打开",+ "open_card": "在聊天中打开",+ "failed": "未能完成。请重试,或打开聊天。",+ "desktop": "桌面通知",+ "desktop_hint": "仅在应用处于后台时。",+ "desktop_blocked": "已被系统阻止。请在系统设置中允许此应用的通知。",+ "desktop_unsupported": "此窗口不支持。",+ "finished": "智能体完成时",+ "finished_hint": "安静提示,仅限你交给它的任务。",+ "fallback_agent": "某个智能体",+ "notify_needs": "{agent} 正在等你",+ "notify_needs_body": "打开聊天进行回答。",+ "notify_done": "{agent} 已完成",+ "notify_done_body": "打开聊天查看结果。"+ },"backlinks_panel": {"load_error": "无法加载反向链接。","empty": "没有反向链接。"diff --git a/dodaios/ui/web/frontend/src/lib/societyApi.ts b/dodaios/ui/web/frontend/src/lib/societyApi.tsindex 0a12bdd39a..66a16fd435 100644--- a/dodaios/ui/web/frontend/src/lib/societyApi.ts+++ b/dodaios/ui/web/frontend/src/lib/societyApi.ts@@ -199,6 +199,16 @@ export interface SocietyAgentRow {last_active_ms: number | null;};run_state?: RunState;+ /** What the agent waits on the person for (dodaios/agent_chat/attention.py); null when nothing. */+ waiting_reason?: WaitingReasonRow | null;+}++/** Why an agent waits on the person: the newest open card of its chats, else a queued item. */+export interface WaitingReasonRow {+ kind: "question" | "approval" | "credential" | "proposal";+ summary: string;+ session_id: string;+ ref_id: string;}/** One quest as GET /api/society/quests returns it (dodaios/society/quests.py). */diff --git a/dodaios/ui/web/frontend/src/views/society/SocietyView.attention.test.tsx b/dodaios/ui/web/frontend/src/views/society/SocietyView.attention.test.tsxnew file mode 100644index 0000000000..ce2a80c0d2--- /dev/null+++ b/dodaios/ui/web/frontend/src/views/society/SocietyView.attention.test.tsx@@ -0,0 +1,71 @@+import { act, cleanup, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";++import { useEventStore } from "@/store/events";+import { openAgent, useAgentNavigation } from "./agentNavigation";+import { LAST_AGENT_STORAGE_KEY } from "./lastAgent";+import { SocietyView } from "./SocietyView";++const reveal = vi.hoisted(() => ({ calls: [] as unknown[] }));+vi.mock("./agentNavigation", async (importOriginal) => {+ const actual = await importOriginal<typeof import("./agentNavigation")>();+ return { ...actual, revealCard: vi.fn(async (target: unknown) => { reveal.calls.push(target); return true; }) };+});+vi.mock("@/hooks/useAppInstance", () => ({ useAppInstance: () => ({ name: "default", isDev: false }) }));+vi.mock("@/lib/mapFullscreen", () => ({ setMapFullscreen: vi.fn(async () => undefined) }));+vi.mock("@tanstack/react-query", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@tanstack/react-query")>()),+ useQueryClient: () => ({ invalidateQueries: async () => undefined }),+}));+vi.mock("@/i18n", () => ({ useT: () => (key: string) => key, useLocaleChunk: () => true, fill: (t: string) => t, translate: (k: string) => k }));+vi.mock("@/components/society/chat/useModelMenuData", () => ({ useModelMenuData: () => undefined }));+vi.mock("@/lib/societyChatGroups", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/lib/societyChatGroups")>()),+ useSocietyChatGroups: () => ({ data: [], isSuccess: true, isError: false, failureCount: 0 }),+}));+vi.mock("@/components/society/data", () => ({ useQuickCreateAgent: () => vi.fn(), useSocietyRoster: () => ({ data: { sample: false, agents: [+ { agentId: "jarvis", name: "Lead", tier: "lead", state: "idle" },+ { agentId: "scout", name: "Scout", tier: "specialist", state: "waiting" },+] }, isLoading: false }) }));+vi.mock("@/views/DodaiosAgentsView", () => ({ DodaiosAgentsView: () => <div data-testid="map" /> }));+vi.mock("@/components/society/card/AgentCardOverlay", () => ({ AgentCardOverlay: ({ agent }: any) => <div data-testid="workspace">{agent.name}</div> }));+vi.mock("@/components/society/roster/RosterRail", () => ({ RosterRail: () => <div data-testid="roster" /> }));+vi.mock("@/components/society/attention/AttentionBell", () => ({ AttentionBell: () => <button data-testid="attention-bell" /> }));++beforeEach(() => {+ reveal.calls = [];+ localStorage.removeItem(LAST_AGENT_STORAGE_KEY);+ useAgentNavigation.setState({ request: null, onScreen: null });+ useEventStore.setState({ activeSection: "agents" });+});+afterEach(() => cleanup());++it("puts the bell in the caption beside the mode switch", () => {+ render(<SocietyView />);+ expect(screen.getByTestId("mode-switch").contains(screen.getByTestId("attention-bell"))).toBe(true);+});++it("opens the requested agent and reveals the card", async () => {+ render(<SocietyView />);+ expect(screen.getByTestId("workspace").textContent).toBe("Lead");+ act(() => openAgent("scout", { sessionId: "society:scout", cardRef: "q1", kind: "question" }));+ await waitFor(() => expect(screen.getByTestId("workspace").textContent).toBe("Scout"));+ expect(reveal.calls).toEqual([{ cardRef: "q1", kind: "question" }]);+ expect(useAgentNavigation.getState().request).toBeNull();+ expect(useAgentNavigation.getState().onScreen).toEqual({ agentId: "scout" });+});++it("drops a request for an agent that is not on the roster", async () => {+ render(<SocietyView />);+ act(() => openAgent("gone", { cardRef: "x", kind: "approval" }));+ await waitFor(() => expect(useAgentNavigation.getState().request).toBeNull());+ expect(screen.getByTestId("workspace").textContent).toBe("Lead");+ expect(reveal.calls).toEqual([]);+});++it("forgets the agent on screen when the view goes away", () => {+ const view = render(<SocietyView />);+ expect(useAgentNavigation.getState().onScreen).toEqual({ agentId: "jarvis" });+ view.unmount();+ expect(useAgentNavigation.getState().onScreen).toBeNull();+});diff --git a/dodaios/ui/web/frontend/src/views/society/SocietyView.tsx b/dodaios/ui/web/frontend/src/views/society/SocietyView.tsxindex 8ffb22407b..e516be5d1c 100644--- a/dodaios/ui/web/frontend/src/views/society/SocietyView.tsx+++ b/dodaios/ui/web/frontend/src/views/society/SocietyView.tsx@@ -22,7 +22,10 @@ import { ChatGroupPanel } from "@/components/society/chat/ChatGroupPanel";import { useSocietyChatStore } from "@/components/society/chat/AgentChatPanel";import { chatGroupsKnown, createSocietyChatGroup, updateSocietyChatGroup, useSocietyChatGroups } from "@/lib/societyChatGroups";import { CanvasActivity } from "@/hooks/useCanvasAwake";+import { AttentionBell } from "@/components/society/attention/AttentionBell";+import { useAgentChatStore } from "@/store/agentChat";import { forgetLastAgentId, rememberLastAgentId, storedLastAgentId } from "./lastAgent";+import { revealCard, setAgentOnScreen, takeAgentRequest, useAgentNavigation } from "./agentNavigation";/** The page's two faces, in caption order: the agents, then the Verse. */const MODES = [@@ -179,6 +182,35 @@ export function SocietyView() {};}, [mode, switchMode, openPlace]);+ // "Needs you": tell the notifier which agent is on screen, and honour a+ // request to open an agent at one of its cards (agentNavigation.openAgent).+ const onScreenId = mode === "agents" && !openGroup ? openAgent?.agentId ?? null : null;+ useEffect(() => {+ setAgentOnScreen(onScreenId ? { agentId: onScreenId } : null);+ }, [onScreenId]);+ useEffect(() => () => setAgentOnScreen(null), []);++ const navigation = useAgentNavigation((s) => s.request);+ useEffect(() => {+ if (!navigation) return;+ const target = agents.find((agent) => agent.agentId === navigation.agentId);+ if (!target) {+ // Still loading: keep the request. Gone (or only the sample roster): drop it.+ if (!roster.isLoading) takeAgentRequest();+ return;+ }+ const taken = takeAgentRequest();+ if (!taken) return;+ switchMode("agents");+ selectAgent(taken.agentId);+ // The lead's card is the front-page chat, which holds many sessions.+ if (target.tier === "lead" && taken.sessionId && !taken.sessionId.startsWith("society:")) {+ const chat = useAgentChatStore.getState();+ if (chat.activeSessionId !== taken.sessionId) chat.openSession(taken.sessionId);+ }+ void revealCard({ cardRef: taken.cardRef, kind: taken.kind });+ }, [navigation, agents, roster.isLoading, selectAgent, switchMode]);+const onIslandSelect = useCallback((agentId: string | null) => {if (agentId) {selectAgent(agentId);@@ -220,7 +252,7 @@ export function SocietyView() {modes — one switch, always centered, always a way back. */}{createPortal(<div className="pointer-events-none fixed inset-x-0 top-0 z-[140] flex h-8 items-center justify-center" data-testid="mode-switch">- <div className="pointer-events-auto flex items-center gap-2">{modeSwitch}<BrowserProfilesButton iconOnly /></div>+ <div className="pointer-events-auto flex items-center gap-2">{modeSwitch}<BrowserProfilesButton iconOnly /><AttentionBell /></div></div>,document.body,)}diff --git a/dodaios/ui/web/frontend/src/views/society/agentNavigation.test.ts b/dodaios/ui/web/frontend/src/views/society/agentNavigation.test.tsnew file mode 100644index 0000000000..7a107b7610--- /dev/null+++ b/dodaios/ui/web/frontend/src/views/society/agentNavigation.test.ts@@ -0,0 +1,103 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { useEventStore } from "@/store/events";+import {+ findCard,+ HIGHLIGHT_MS,+ isAgentOnScreen,+ openAgent,+ revealCard,+ setAgentOnScreen,+ takeAgentRequest,+ useAgentNavigation,+} from "./agentNavigation";++function card(html: string): HTMLElement {+ const host = document.createElement("div");+ host.innerHTML = html;+ document.body.appendChild(host);+ return host;+}++beforeEach(() => {+ useAgentNavigation.setState({ request: null, onScreen: null });+ useEventStore.setState({ activeSection: "chats" });+});++afterEach(() => {+ document.body.innerHTML = "";+ vi.useRealTimers();+});++describe("openAgent", () => {+ it("records the request once and switches to the Agents section", () => {+ openAgent("scout", { sessionId: "society:scout", cardRef: "q1", kind: "question" });+ expect(useEventStore.getState().activeSection).toBe("agents");+ const taken = takeAgentRequest();+ expect(taken).toMatchObject({ agentId: "scout", cardRef: "q1", kind: "question" });+ expect(takeAgentRequest()).toBeNull();+ });++ it("gives two requests for the same agent different identities", () => {+ openAgent("scout");+ const first = useAgentNavigation.getState().request;+ openAgent("scout");+ expect(useAgentNavigation.getState().request?.nonce).not.toBe(first?.nonce);+ });++ it("ignores an empty agent id", () => {+ openAgent("");+ expect(useAgentNavigation.getState().request).toBeNull();+ expect(useEventStore.getState().activeSection).toBe("chats");+ });+});++describe("on screen", () => {+ it("counts only while the Agents section shows that agent", () => {+ setAgentOnScreen({ agentId: "scout" });+ expect(isAgentOnScreen("scout")).toBe(false); // another section is in front+ useEventStore.setState({ activeSection: "agents" });+ expect(isAgentOnScreen("scout")).toBe(true);+ expect(isAgentOnScreen("brain")).toBe(false);+ setAgentOnScreen(null);+ expect(isAgentOnScreen("scout")).toBe(false);+ });+});++describe("cards", () => {+ it("finds a card by its ref first, else the newest open card of the kind", () => {+ const host = card(`+ <div data-testid="question-card" data-state="open" id="old"></div>+ <div data-testid="question-card" data-state="person"></div>+ <div data-testid="question-card" data-state="open" id="new"></div>+ <div data-card-ref="q-exact" id="exact"></div>+ `);+ expect(findCard(host, "q-exact", "question")?.id).toBe("exact");+ expect(findCard(host, "missing", "question")?.id).toBe("new");+ expect(findCard(host, "missing")).toBeNull();+ });++ it("waits for the card to render, then scrolls to it and marks it", async () => {+ vi.useFakeTimers();+ const host = card("");+ const found = revealCard({ cardRef: "a1", kind: "approval" }, { root: host, intervalMs: 50 });+ const later = document.createElement("div");+ later.dataset.testid = "thread-approval";+ later.scrollIntoView = vi.fn();+ host.appendChild(later);+ await vi.advanceTimersByTimeAsync(60);+ await expect(found).resolves.toBe(true);+ expect(later.scrollIntoView).toHaveBeenCalled();+ expect(later.dataset.attentionHighlight).toBe("true");+ await vi.advanceTimersByTimeAsync(HIGHLIGHT_MS + 10);+ expect(later.dataset.attentionHighlight).toBeUndefined();+ });++ it("gives up quietly when no card shows", async () => {+ vi.useFakeTimers();+ const found = revealCard({ kind: "credential" }, { root: card(""), timeoutMs: 200, intervalMs: 50 });+ await vi.advanceTimersByTimeAsync(300);+ await expect(found).resolves.toBe(false);+ await expect(revealCard({})).resolves.toBe(false);+ });+});diff --git a/dodaios/ui/web/frontend/src/views/society/agentNavigation.ts b/dodaios/ui/web/frontend/src/views/society/agentNavigation.tsnew file mode 100644index 0000000000..e19deaab38--- /dev/null+++ b/dodaios/ui/web/frontend/src/views/society/agentNavigation.ts@@ -0,0 +1,161 @@+import { create } from "zustand";++import { useEventStore } from "@/store/events";++/**+ * One way to bring an agent (and one card in its chat) on screen, from+ * anywhere in the app: the "needs you" inbox, a desktop notification, a toast.+ *+ * `openAgent` records the request and switches to the Agents section;+ * `SocietyView` takes the request, opens that agent's chat and then calls+ * `revealCard`, which waits for the card to render, scrolls it into view and+ * marks it for a moment. Nothing here knows how a chat is laid out: a card is+ * found by its `data-card-ref`, or else as the newest open card of its kind.+ */++export type CardKind = "question" | "approval" | "credential" | "proposal";++export interface AgentNavigationRequest {+ agentId: string;+ /** The chat the card lives in, when it is not the agent's main chat. */+ sessionId?: string;+ /** The card to reveal (a question, approval or credential request id). */+ cardRef?: string;+ kind?: CardKind;+ /** Distinguishes two requests for the same agent. */+ nonce: number;+}++export interface AgentOnScreen {+ agentId: string;+ sessionId?: string;+}++interface AgentNavigationState {+ request: AgentNavigationRequest | null;+ /** The agent whose chat the person is looking at, if any. */+ onScreen: AgentOnScreen | null;+}++export const useAgentNavigation = create<AgentNavigationState>(() => ({ request: null, onScreen: null }));++let nonce = 0;++/** Open `agentId` in the Agents section and reveal `cardRef` once it renders. */+export function openAgent(+ agentId: string,+ opts: { sessionId?: string; cardRef?: string; kind?: CardKind } = {},+): void {+ if (!agentId) return;+ nonce += 1;+ useAgentNavigation.setState({ request: { agentId, ...opts, nonce } });+ const events = useEventStore.getState();+ if (events.activeSection !== "agents") events.setActiveSection("agents");+}++/** Take the pending request (once): the caller is about to honour it. */+export function takeAgentRequest(): AgentNavigationRequest | null {+ const { request } = useAgentNavigation.getState();+ if (request) useAgentNavigation.setState({ request: null });+ return request;+}++/** Record which agent is on screen (`null` when none is). */+export function setAgentOnScreen(next: AgentOnScreen | null): void {+ const current = useAgentNavigation.getState().onScreen;+ if (current?.agentId === next?.agentId && current?.sessionId === next?.sessionId) return;+ useAgentNavigation.setState({ onScreen: next });+}++/** Whether the person is looking at `agentId` right now. */+export function isAgentOnScreen(agentId: string): boolean {+ const { onScreen } = useAgentNavigation.getState();+ const section = useEventStore.getState().activeSection;+ return section === "agents" && onScreen?.agentId === agentId;+}++/** The newest open card of each kind, as the chat cards mark themselves. */+const OPEN_CARD: Record<CardKind, string> = {+ question: '[data-testid="question-card"][data-state="open"]',+ approval: '[data-testid="thread-approval"]',+ credential: '[data-testid="credential-card"][data-state="open"]',+ proposal: '[data-card-kind="proposal"]',+};++/** How long a revealed card stays marked. */+export const HIGHLIGHT_MS = 1800;++function cssEscape(value: string): string {+ return typeof CSS !== "undefined" && typeof CSS.escape === "function"+ ? CSS.escape(value)+ : value.replace(/["\\]/g, "\\$&");+}++/** The card for `ref` (or the newest open card of `kind`) inside `root`. */+export function findCard(root: ParentNode, ref?: string, kind?: CardKind): HTMLElement | null {+ if (ref) {+ const exact = root.querySelector<HTMLElement>(`[data-card-ref="${cssEscape(ref)}"]`);+ if (exact) return exact;+ }+ if (!kind) return null;+ const all = root.querySelectorAll<HTMLElement>(OPEN_CARD[kind]);+ return all.length > 0 ? all[all.length - 1] : null;+}++function prefersReducedMotion(): boolean {+ return typeof window !== "undefined" && typeof window.matchMedia === "function"+ && window.matchMedia("(prefers-reduced-motion: reduce)").matches;+}++/** Scroll `el` into view and mark it for {@link HIGHLIGHT_MS}. */+export function highlightCard(el: HTMLElement): void {+ const reduced = prefersReducedMotion();+ el.scrollIntoView?.({ block: "center", behavior: reduced ? "auto" : "smooth" });+ // A card that takes keys (the question card) gets them right away.+ if (el.hasAttribute("tabindex")) el.focus({ preventScroll: true });+ el.dataset.attentionHighlight = "true";+ if (!reduced && typeof el.animate === "function") {+ const ring = "hsl(var(--warning) / 0.55)";+ const none = "hsl(var(--warning) / 0)";+ el.animate(+ [+ { boxShadow: `0 0 0 0 ${none}` },+ { boxShadow: `0 0 0 3px ${ring}`, offset: 0.25 },+ { boxShadow: `0 0 0 3px ${ring}`, offset: 0.7 },+ { boxShadow: `0 0 0 0 ${none}` },+ ],+ { duration: HIGHLIGHT_MS, easing: "cubic-bezier(0.2, 0, 0, 1)" },+ );+ }+ window.setTimeout(() => {+ delete el.dataset.attentionHighlight;+ }, HIGHLIGHT_MS);+}++/**+ * Wait (up to `timeoutMs`) for the card to render, then reveal it.+ * Resolves `true` when a card was found.+ */+export function revealCard(+ target: { cardRef?: string; kind?: CardKind },+ { root = document, timeoutMs = 4000, intervalMs = 120 }: { root?: ParentNode; timeoutMs?: number; intervalMs?: number } = {},+): Promise<boolean> {+ if (!target.cardRef && !target.kind) return Promise.resolve(false);+ const started = Date.now();+ return new Promise((resolve) => {+ const look = () => {+ const el = findCard(root, target.cardRef, target.kind);+ if (el) {+ highlightCard(el);+ resolve(true);+ return;+ }+ if (Date.now() - started >= timeoutMs) {+ resolve(false);+ return;+ }+ window.setTimeout(look, intervalMs);+ };+ look();+ });+}diff --git a/dodaios/ui/web/server.py b/dodaios/ui/web/server.pyindex e2888d9491..7b41a0d358 100644--- a/dodaios/ui/web/server.py+++ b/dodaios/ui/web/server.py@@ -501,6 +501,7 @@ class WebServer:from .agent_accounts_routes import router as agent_accounts_routerfrom .agent_chat_routes import router as agent_chat_router+ from .attention_routes import router as attention_routerfrom .agent_mcp_routes import router as agent_mcp_routerfrom .agent_runtime_routes import router as agent_runtime_routerfrom .agentic_ide_git_routes import router as agentic_ide_git_router@@ -797,6 +798,7 @@ class WebServer:# opens on the boot path (AP-26); stop() cancels running turns.app.state.agent_chat = Noneapp.state.agent_chat_factory = self._build_agent_chat_service+ app.include_router(attention_router)app.include_router(agent_chat_router)from .agent_server_routes import router as agent_server_router@@ -4123,7 +4125,16 @@ class WebServer:# Install on first chat use, keeping result tracking off the boot path.self.bus.unsubscribe(DelegationResultReady, self._forward_delegation_to_chat)self.bus.subscribe(DelegationResultReady, self._forward_delegation_to_chat)- return AgentChatService(store, assistant_name=_name, bus=lambda: self.bus)+ service = AgentChatService(store, assistant_name=_name, bus=lambda: self.bus)+ # "Needs you" list and notifier: one event listener, nothing on boot.+ from dodaios.agent_chat.attention import install as install_attention++ install_attention(+ service,+ publish=self.bus.publish,+ society=lambda: getattr(self.app.state, "society", None),+ )+ return servicedef _schedule_registry_bootstraps(self) -> None:"""Start registry discovery after composition without delaying readiness."""diff --git a/dodaios/ui/web/society_routes.py b/dodaios/ui/web/society_routes.pyindex 4016960ead..492f23073b 100644--- a/dodaios/ui/web/society_routes.py+++ b/dodaios/ui/web/society_routes.py@@ -355,11 +355,18 @@ def _agent_row(agent: AgentRecord, request: HTTPConnection) -> dict[str, Any]:async def list_agents(request: Request, include_archived: bool = False) -> dict[str, Any]:rt = await _runtime(request)agents = await rt.roster.list(include_archived=include_archived)+ from dodaios.agent_chat.attention import waiting_reasons++ reasons = await waiting_reasons(request.app.state)rows = []for agent in agents:row = _agent_row(agent, request)+ # What it waits on the person for (a question, an approval, ...), or None.+ row["waiting_reason"] = reasons.get(agent.agent_id)if agent.state == "paused":row["run_state"] = "paused"+ elif row["waiting_reason"] is not None:+ row["run_state"] = "waiting"elif rt.checkpoints.is_busy(agent.agent_id):# A scheduler run OR a turn typed into the card: both are work.row["run_state"] = "working"diff --git a/tests/unit/agent_chat/test_attention.py b/tests/unit/agent_chat/test_attention.pynew file mode 100644index 0000000000..cd9440ed55--- /dev/null+++ b/tests/unit/agent_chat/test_attention.py@@ -0,0 +1,452 @@+"""The "needs you" list: aggregation over every runtime, the gate, the notifier."""++from __future__ import annotations++import asyncio+from dataclasses import dataclass+from types import SimpleNamespace+from typing import Any++import pytest++from dodaios.agent_chat.attention import (+ THROTTLE_S,+ AgentAttentionChanged,+ AttentionBoard,+ AttentionGate,+ attention_of,+ install,+ waiting_reasons,+)+from dodaios.agent_chat.events import make_event+from dodaios.agent_chat.service import AgentChatService+from dodaios.agent_chat.store import AgentChatStore++_QUESTION = {+ "question": "Which database should the project use?",+ "options": [{"label": "SQLite", "description": ""}, {"label": "Postgres", "description": ""}],+ "recommended": 0,+ "recommendation_reason": "",+}+++def _ev(kind: str, **payload: Any) -> dict[str, Any]:+ return make_event(kind, payload)+++class _Clock:+ def __init__(self) -> None:+ self.now = 1000.0++ def __call__(self) -> float:+ return self.now+++# ------------------------------------------------------------------- board+++def test_board_opens_and_closes_every_card_kind() -> None:+ board = AttentionBoard()+ sid = "society:scout"+ board.observe(sid, _ev("approval_required", approval_id="a1", name="shell", summary="Run ls"))+ board.observe(sid, _ev("question_required", question_id="q1", questions=[_QUESTION]))+ board.observe(sid, _ev("credential_required", request_id="c1", label="GitHub token"))+ kinds = sorted(item.kind for item in board.items())+ assert kinds == ["approval", "credential", "question"]+ question = next(item for item in board.items() if item.kind == "question")+ assert question.summary == _QUESTION["question"]+ assert question.detail["options"] == ["SQLite", "Postgres"]+ assert question.detail["single"] is True++ board.observe(sid, _ev("approval_resolved", approval_id="a1", decision="allow"))+ board.observe(sid, _ev("question_resolved", question_id="q1", answers=[]))+ board.observe(sid, _ev("credential_resolved", request_id="c1", status="saved"))+ assert board.items() == []+++def test_progress_moves_the_summary_to_the_next_question() -> None:+ board = AttentionBoard()+ second = {**_QUESTION, "question": "Where should it run?"}+ board.observe("s", _ev("question_required", question_id="q", questions=[_QUESTION, second]))+ board.observe(+ "s", _ev("question_progress", question_id="q", answers=[{"answer": "SQLite"}, None])+ )+ (item,) = board.items()+ assert item.summary == "Where should it run?"+ assert item.detail["step"] == 1 and item.detail["count"] == 2+++def test_a_multi_pick_question_is_listed_but_not_offered_for_one_tap() -> None:+ board = AttentionBoard()+ multi = {**_QUESTION, "multi_select": True}+ board.observe("s", _ev("question_required", question_id="q", questions=[multi]))+ assert board.items()[0].detail["single"] is False+++def test_a_new_turn_settles_end_of_turn_cards_and_a_finished_turn_its_own() -> None:+ board = AttentionBoard()+ board.observe(+ "s", _ev("question_required", question_id="d", questions=[_QUESTION], deferred=True)+ )+ board.observe("s", _ev("credential_required", request_id="c", label="Key"))+ board.observe("s", _ev("turn_started", turn_id="t2"))+ assert [item.kind for item in board.items()] == ["credential"] # a secret field stays open++ board.observe("s", _ev("approval_required", approval_id="a", name="x", turn_id="t2"))+ board.observe("s", _ev("turn_finished", turn_id="t2", status="error"))+ assert [item.kind for item in board.items()] == ["credential"]+++def test_done_only_for_a_turn_the_person_started_with_nothing_left_open() -> None:+ board = AttentionBoard()+ board.observe("s", _ev("turn_started", turn_id="t1"))+ assert [+ c.what for c in board.observe("s", _ev("turn_finished", turn_id="t1", status="done"))+ ] == []++ board.observe("s", _ev("user_message", text="hi", author="lead")) # an agent wrote it+ board.observe("s", _ev("turn_started", turn_id="t2"))+ assert board.observe("s", _ev("turn_finished", turn_id="t2", status="done")) == []++ board.observe("s", _ev("user_message", text="hi"))+ board.observe("s", _ev("turn_started", turn_id="t3"))+ changes = board.observe("s", _ev("turn_finished", turn_id="t3", status="done"))+ assert [c.what for c in changes] == ["done"]+++# -------------------------------------------------------------------- gate+++def test_gate_throttles_per_agent_and_kind() -> None:+ clock = _Clock()+ gate = AttentionGate(clock=clock)+ assert gate.verdict(agent_id="a", transition="needs_input", session_id="society:a") is None+ assert (+ gate.verdict(agent_id="a", transition="needs_input", session_id="society:a") == "throttled"+ )+ assert gate.verdict(agent_id="a", transition="done", session_id="society:a") is None+ assert gate.verdict(agent_id="b", transition="needs_input", session_id="society:b") is None+ clock.now += THROTTLE_S + 0.1+ assert gate.verdict(agent_id="a", transition="needs_input", session_id="society:a") is None+++def test_gate_is_quiet_while_the_person_looks_at_that_agent() -> None:+ clock = _Clock()+ gate = AttentionGate(clock=clock, focus_ttl_s=60)+ gate.report_focus(agent_id="a", app_focused=True)+ assert gate.verdict(agent_id="a", transition="needs_input", session_id="society:a") == "looking"+ assert gate.verdict(agent_id="b", transition="needs_input", session_id="society:b") is None+ gate.report_focus(agent_id="a", app_focused=False) # window in the background+ assert gate.verdict(agent_id="a", transition="done", session_id="society:a") is None+ gate.report_focus(agent_id="c", app_focused=True)+ clock.now += 61 # a stale report says nothing any more+ assert gate.verdict(agent_id="c", transition="done", session_id="society:c") is None+++def test_gate_holds_muted_agents_and_unattended_runs() -> None:+ gate = AttentionGate(clock=_Clock())+ gate.report_focus(muted=["quiet"])+ assert gate.verdict(agent_id="quiet", transition="done", session_id="society:quiet") == "muted"+ routine = "society:a:routine:task-1:run-1"+ assert gate.verdict(agent_id="a", transition="needs_input", session_id=routine) == "unattended"+ assert gate.verdict(agent_id="", transition="done", session_id="x") == "no_agent"+++# ------------------------------------------------------------- service fold+++@dataclass+class _Row:+ id: str+ agent_id: str+ capability: str+ summary: str+ created_ms: int+ expires_ms: int+ state: str = "pending"+ action: dict[str, Any] | None = None++ def __post_init__(self) -> None:+ self.action = self.action or {}+++class _Approvals:+ def __init__(self, rows: list[_Row]) -> None:+ self.rows = rows++ async def pending(self) -> list[_Row]:+ return list(self.rows)+++class _Society:+ def __init__(self, rows: list[_Row] | None = None) -> None:+ self.approvals = _Approvals(rows or [])+ self._agents = {+ aid: SimpleNamespace(agent_id=aid, name=aid.capitalize(), tier="specialist")+ for aid in ("brain", "cli", "hermes", "openclaw", "scout")+ }++ def cached_agent(self, agent_id: str) -> Any:+ return self._agents.get(agent_id)+++def _service() -> AgentChatService:+ return AgentChatService(AgentChatStore(":memory:"), assistant_name=lambda: "Testo")+++async def _settle(attention: Any) -> None:+ for _ in range(5):+ await asyncio.sleep(0)+ while attention._tasks: # noqa: SLF001 — wait for the scheduled publishes+ await asyncio.gather(*list(attention._tasks)) # noqa: SLF001+ await asyncio.sleep(0) # let the done callbacks drop the finished tasks+++async def test_aggregates_cards_from_every_runtime() -> None:+ svc = _service()+ seats = {+ "brain": ("openai", ""),+ "cli": ("claude-api", ""),+ "hermes": ("openrouter", "hermes"),+ "openclaw": ("openrouter", "openclaw"),+ }+ for agent_id, (provider, runtime) in seats.items():+ svc.store.create_session(+ provider=provider,+ model="m",+ effort="high",+ cwd=".",+ surface="society",+ session_id=f"society:{agent_id}",+ runtime=runtime,+ )+ lead = svc.store.create_session(+ provider="openai", model="m", effort="", cwd=".", surface="jarvis"+ )+ attention = install(svc, society=_Society)+ await svc._emit(+ "society:brain", _ev("approval_required", approval_id="a", name="shell", summary="Run")+ )+ await svc._emit("society:cli", _ev("question_required", question_id="q", questions=[_QUESTION]))+ await svc._emit("society:hermes", _ev("credential_required", request_id="c", label="Token"))+ await svc._emit(+ "society:openclaw",+ _ev("question_required", question_id="d", questions=[_QUESTION], deferred=True),+ )+ await svc._emit(+ lead.session_id, _ev("approval_required", approval_id="l", name="x", summary="Lead")+ )+ await _settle(attention)++ items = await attention.items()+ assert sorted((i.agent_id, i.kind) for i in items) == [+ ("brain", "approval"),+ ("cli", "question"),+ ("hermes", "credential"),+ ("jarvis", "approval"),+ ("openclaw", "question"),+ ]+ assert install(svc) is attention # idempotent+++async def test_society_queue_items_join_the_list_and_rank_below_live_cards() -> None:+ svc = _service()+ rows = [+ _Row(+ "p1",+ "scout",+ "core:config:rule",+ "Add a standing rule",+ 10,+ 99,+ action={"session_id": "society:scout"},+ ),+ _Row("u1", "brain", "plugin:gmail:send", "Send the digest", 20, 99, state="blocked"),+ ]+ attention = install(svc, society=lambda: _Society(rows))+ await svc._emit(+ "society:scout", _ev("approval_required", approval_id="a", name="x", summary="Live")+ )+ await _settle(attention)++ items = {i.ref_id: i for i in await attention.items()}+ assert items["p1"].kind == "proposal" and items["p1"].source == "queue"+ assert items["u1"].kind == "approval" and items["u1"].detail["parked"] is True+ reasons = await attention.waiting_reasons()+ assert reasons["scout"]["ref_id"] == "a" # the live card outranks the proposal+ assert reasons["brain"] == {+ "kind": "approval",+ "summary": "Send the digest",+ "session_id": "society:brain",+ "ref_id": "u1",+ }+ assert await waiting_reasons(SimpleNamespace(agent_chat=svc)) == reasons+ assert await waiting_reasons(SimpleNamespace(agent_chat=None)) == {}+++async def test_notifier_publishes_count_and_needs_input_but_never_speaks() -> None:+ svc = _service()+ published: list[Any] = []++ async def publish(event: Any) -> None:+ published.append(event)++ attention = install(svc, publish=publish, society=_Society)+ await svc._emit(+ "society:scout", _ev("approval_required", approval_id="a", name="x", summary="Run it")+ )+ await _settle(attention)+ assert all(isinstance(e, AgentAttentionChanged) for e in published)+ first = published[-1]+ assert (first.count, first.transition, first.agent_id, first.kind) == (+ 1,+ "needs_input",+ "scout",+ "approval",+ )+ assert first.agent_name == "Scout" and first.summary == "Run it"++ # A second card within the throttle window updates the count only.+ await svc._emit("society:scout", _ev("credential_required", request_id="c", label="Key"))+ await _settle(attention)+ assert (published[-1].count, published[-1].transition) == (2, "")++ # Answering clears the badge.+ await svc._emit("society:scout", _ev("approval_resolved", approval_id="a", decision="deny"))+ await svc._emit("society:scout", _ev("credential_resolved", request_id="c", status="declined"))+ await _settle(attention)+ assert published[-1].count == 0+ assert attention_of(svc) is attention+++async def test_notifier_is_silent_for_the_agent_on_screen_and_for_routines() -> None:+ svc = _service()+ published: list[Any] = []++ async def publish(event: Any) -> None:+ published.append(event)++ attention = install(svc, publish=publish, society=_Society)+ attention.gate.report_focus(agent_id="scout", app_focused=True)+ await svc._emit(+ "society:scout", _ev("approval_required", approval_id="a", name="x", summary="s")+ )+ await svc._emit(+ "society:brain:routine:t:r",+ _ev("approval_required", approval_id="b", name="x", summary="s"),+ )+ await _settle(attention)+ assert [e.transition for e in published] == ["", ""]+ assert published[-1].count == 2 # still counted+++async def test_done_is_told_only_for_the_agents_own_chat() -> None:+ svc = _service()+ published: list[Any] = []++ async def publish(event: Any) -> None:+ published.append(event)++ attention = install(svc, publish=publish, society=_Society)+ attention.done_grace_s = 0+ for sid in ("society:scout", "society:scout:with:brain"):+ await svc._emit(sid, _ev("user_message", text="go"))+ await svc._emit(sid, _ev("turn_started", turn_id=f"t-{sid}"))+ await svc._emit(sid, _ev("turn_finished", turn_id=f"t-{sid}", status="done"))+ await _settle(attention)+ told = [(e.transition, e.session_id) for e in published if e.transition]+ assert told == [("done", "society:scout")]+++async def test_a_turn_that_ends_by_asking_is_told_as_a_question_not_as_done() -> None:+ svc = _service()+ published: list[Any] = []++ async def publish(event: Any) -> None:+ published.append(event)++ attention = install(svc, publish=publish, society=_Society)+ attention.done_grace_s = 0.05+ sid = "society:scout"+ await svc._emit(sid, _ev("user_message", text="go"))+ await svc._emit(sid, _ev("turn_started", turn_id="t1"))+ await svc._emit(sid, _ev("turn_finished", turn_id="t1", status="done"))+ # A fence-only CLI's end-of-turn card lands right after the turn finished.+ await svc._emit(sid, _ev(+ "question_required", turn_id="t1", question_id="q-end", questions=[_QUESTION], deferred=True,+ ))+ await _settle(attention)+ told = [e.transition for e in published if e.transition]+ assert told == ["needs_input"]+++def test_a_series_is_never_offered_for_one_tap() -> None:+ board = AttentionBoard()+ board.observe("s", _ev("question_required", question_id="q", questions=[_QUESTION, _QUESTION]))+ assert board.items()[0].detail["single"] is False+ lone = AttentionBoard()+ lone.observe("s", _ev("question_required", question_id="q", questions=[_QUESTION]))+ assert lone.items()[0].detail["single"] is True+++async def test_open_cards_are_rebuilt_from_the_log_after_a_restart() -> None:+ store = AgentChatStore(":memory:")+ store.create_session(+ provider="kimi", model="m", effort="", cwd=".", surface="society", session_id="society:cli"+ )+ for event in (+ _ev("turn_started", turn_id="t1"),+ _ev("question_required", question_id="old", questions=[_QUESTION], deferred=True),+ _ev("turn_finished", turn_id="t1", status="done"),+ _ev("turn_started", turn_id="t2"),+ _ev("question_required", question_id="new", questions=[_QUESTION], deferred=True),+ _ev("turn_finished", turn_id="t2", status="done"),+ ):+ store.append_event("society:cli", event)+ svc = AgentChatService(store, assistant_name=lambda: "Testo")+ attention = install(svc, society=_Society)+ items = await attention.items()+ assert [(i.agent_id, i.ref_id, i.deferred) for i in items] == [("cli", "new", True)]+++def client() -> Any:+ from fastapi import FastAPI+ from fastapi.testclient import TestClient++ from dodaios.ui.web.attention_routes import router++ app = FastAPI()+ app.include_router(router)+ app.state.agent_chat = _service()+ app.state.society = _Society()+ return TestClient(app)+++def test_routes_list_items_and_take_the_focus_report(client: Any) -> None:+ svc = client.app.state.agent_chat+ # The card opened before the list existed: the first read replays the log.+ svc.store.create_session(+ provider="codex",+ model="m",+ effort="",+ cwd=".",+ surface="society",+ session_id="society:scout",+ )+ asyncio.run(+ svc._emit("society:scout", _ev("question_required", question_id="q", questions=[_QUESTION]))+ )+ body = client.get("/api/agent-chat/attention").json()+ assert body["count"] == 1+ (item,) = body["items"]+ assert item["agent_id"] == "scout" and item["kind"] == "question"+ assert "questions" not in item["detail"] and item["detail"]["options"] == ["SQLite", "Postgres"]++ ok = client.post(+ "/api/agent-chat/attention/focus",+ json={"agent_id": "scout", "app_focused": True, "muted": ["brain"]},+ )+ assert ok.json() == {"ok": True}+ gate = attention_of(svc).gate+ assert gate.looking_at("scout") and "brain" in gate.focus.muted