Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(workbench): per-session inbox with unified typed message persistence + realtime (#359)
Call White877353bc06ac
diff --git a/core/inbox_events.py b/core/inbox_events.pynew file mode 100644index 000000000..860d8bc23--- /dev/null+++ b/core/inbox_events.py@@ -0,0 +1,65 @@+"""Controller-side fan-out bus for inbox change events.++The Controller process persists agent messages (``message_mirror``), but the+browser SSE broker lives in the UI server process. This bus lets the Controller+publish ``inbox.session.updated`` events; ``core/internal_server.py`` exposes+them over ``GET /internal/events`` (a long-lived SSE on the dispatch socket),+and the UI server re-broadcasts them to browsers via its own ``SSEBroker``.++Thread-safe like ``vibe/sse_broker.py``: ``publish`` may be called from any+thread/loop and lands on each subscriber's loop via ``call_soon_threadsafe``.+"""++from __future__ import annotations++import asyncio+import logging+import threading+from typing import Any++logger = logging.getLogger(__name__)+++class InboxEventBus:+ def __init__(self) -> None:+ self._subscribers: dict[int, tuple[asyncio.AbstractEventLoop, asyncio.Queue]] = {}+ self._next_id = 0+ self._lock = threading.Lock()++ def subscribe(self) -> tuple[int, asyncio.Queue]:+ loop = asyncio.get_event_loop()+ queue: asyncio.Queue = asyncio.Queue(maxsize=500)+ with self._lock:+ sub_id = self._next_id+ self._next_id += 1+ self._subscribers[sub_id] = (loop, queue)+ return sub_id, queue++ def unsubscribe(self, sub_id: int) -> None:+ with self._lock:+ self._subscribers.pop(sub_id, None)++ def publish(self, event_type: str, data: Any) -> None:+ """Fan ``(event_type, data)`` out to every subscriber. No-op when none."""+ with self._lock:+ subs = list(self._subscribers.values())+ if not subs:+ return+ for loop, queue in subs:+ try:+ loop.call_soon_threadsafe(self._put_nowait, queue, event_type, data)+ except RuntimeError:+ # Loop closed mid-publish; drop silently.+ pass++ @staticmethod+ def _put_nowait(queue: asyncio.Queue, event_type: str, data: Any) -> None:+ try:+ queue.put_nowait((event_type, data))+ except asyncio.QueueFull:+ logger.warning("inbox event bus subscriber queue full; dropping %s", event_type)+++# Process-wide singleton (Controller process). ``message_mirror`` publishes;+# ``internal_server`` subscribes.+bus = InboxEventBus()diff --git a/core/internal_server.py b/core/internal_server.pyindex 03a3f7bf1..13803f5b5 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -147,6 +147,34 @@ def create_app(controller: "Controller") -> FastAPI:headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"},)+ @app.get("/internal/events")+ async def _events() -> Any:+ """Long-lived SSE feed of Controller-side inbox events.++ The UI server opens this once on startup and re-broadcasts each event+ to browsers via its own SSEBroker, so realtime inbox updates (a new+ agent ``result`` bumping a session to the top) work across the+ process boundary.+ """+ from core.inbox_events import bus++ sub_id, queue = bus.subscribe()++ async def _stream():+ try:+ yield ": connected\n\n"+ while True:+ event_type, data = await queue.get()+ yield _sse_event(event_type, data)+ finally:+ bus.unsubscribe(sub_id)++ return StreamingResponse(+ _stream(),+ media_type="text/event-stream",+ headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"},+ )+@app.post("/internal/cancel/{session_id}")async def _cancel(session_id: str) -> Any:# ``session_id`` is the dispatch key — matches the body field@@ -292,7 +320,13 @@ def _build_dispatch_payload(payload: dict[str, Any]) -> tuple[str, MessageContexuser_id = payload.get("user_id") or "workbench"channel_id = payload.get("channel_id") or session_id- platform_specific: dict[str, Any] = {"workbench_session_id": session_id}+ # ``agent_session_id`` is the agent_sessions PK; persist_agent_message reads+ # it to attribute avibe agent replies to the right session (IM stamps it at+ # session-resolve time). For avibe the dispatch session_id IS that PK.+ platform_specific: dict[str, Any] = {+ "workbench_session_id": session_id,+ "agent_session_id": session_id,+ }session_row = _lookup_session(session_id)if session_row is not None:target = {diff --git a/core/message_dispatcher.py b/core/message_dispatcher.pyindex d366be057..9e72dc4db 100644--- a/core/message_dispatcher.py+++ b/core/message_dispatcher.py@@ -13,7 +13,7 @@ from typing import Optionalfrom config.platform_registry import get_platform_descriptorfrom modules.im import MessageContext-from core.message_mirror import mirror_outbound+from core.message_mirror import persist_agent_messagefrom core.reply_enhancer import process_reply, strip_file_links, strip_silent_blocksfrom storage.background import SQLiteBackgroundTaskStorefrom vibe.i18n import t as i18n_t@@ -363,6 +363,36 @@ class ConsolidatedMessageDispatcher:await self._clear_consolidated_state(context)return None+ # Resolve the delivery target once. Routed / post_to / thread replies+ # land in a different channel than the source context, and the persisted+ # row must follow the reply to where it was actually delivered (IM+ # cross-platform history) — persist_agent_message attributes IM rows to+ # this target's scope.+ target_context = self._get_target_context(context)++ # For a result, persist the SAME cleaned text the user receives:+ # process_reply() strips file:// markdown links + the trailing+ # quick-reply button block before delivery/streaming, so persisting the+ # raw text would surface markup in the inbox preview / chat transcript+ # that was never shown. Computed once here and reused for delivery below.+ enhanced = None+ persist_text = text+ if canonical_type == "result":+ quick_replies_on = getattr(self.controller.config, "reply_enhancements", True)+ enhanced = process_reply(text, include_quick_replies=quick_replies_on)+ persist_text = enhanced.text if enhanced.text.strip() else text++ # Persistence is decided per delivery path below, not here, so that:+ # * suppressed scheduled runs (intentionally private) never leak into+ # the cross-platform messages history,+ # * a user-facing result/notify that fails every IM send isn't recorded+ # as if the user received it (matches the old success-only mirror),+ # * intermediate assistant/tool_call log rows STILL persist pre-mute so+ # muted process messages land in the store.+ # avibe always persists its result/notify: the SSE stream is the delivery+ # and the persisted row is the inbox/transcript source of truth.+ persists_without_delivery = target_context.platform == "avibe"+if (context.platform_specific or {}).get("suppress_delivery"):message_id = f"suppressed:{(context.platform_specific or {}).get('task_execution_id') or canonical_type}"self._record_suppressed_run_message(context, text, message_id)@@ -371,15 +401,12 @@ class ConsolidatedMessageDispatcher:return message_idif canonical_type == "notify":- target_context = self._get_target_context(context)try:message_id = await im_client.send_message(target_context, text, parse_mode=parse_mode)- # ``target_context`` carries the post-override platform / channel- # / thread, so the mirror row lands in the scope where the- # message was actually delivered. Mirroring the original- # ``context`` would mis-attribute scheduled or post_to-routed- # replies to their source scope.- mirror_outbound(target_context, text, native_message_id=message_id, kind="notify")+ # Record only once delivered (avibe always, via SSE) so a failed+ # IM send isn't stored as if the user received it.+ if persists_without_delivery or message_id is not None:+ persist_agent_message(target_context, "notify", text)await _stream_chunk(context, text=text, message_id=message_id, kind="notify")return message_idexcept Exception as err:@@ -387,14 +414,12 @@ class ConsolidatedMessageDispatcher:return Noneif canonical_type == "result":- target_context = self._get_target_context(context)primary_message_id: Optional[str] = Nonescheduled_anchor_message_id: Optional[str] = Nonedelivered_as_attachment = False- # Extract file links and optional quick-reply buttons.- quick_replies_on = getattr(self.controller.config, "reply_enhancements", True)- enhanced = process_reply(text, include_quick_replies=quick_replies_on)+ # ``enhanced`` (extracted file links + quick-reply buttons) was+ # computed above for persistence; reuse it for delivery.display_text = enhanced.text if enhanced.text.strip() else textif self._result_within_limit(context, display_text):@@ -529,15 +554,15 @@ class ConsolidatedMessageDispatcher:# a fresh log message instead of appending to the previous one.await self._clear_consolidated_state(context)+ # Persist the delivered result (cleaned text == what was shown).+ # avibe always persists (SSE is its delivery); for IM a result that+ # failed every send/upload (primary_message_id is None) is NOT+ # recorded, matching the old outbound mirror's success-only rule.+ if persists_without_delivery or primary_message_id is not None:+ persist_agent_message(target_context, "result", persist_text)+if primary_message_id and display_text:- # Use ``target_context`` so scheduled / post_to-routed replies- # mirror under their actual delivery scope, not the source.- mirror_outbound(- target_context,- display_text,- native_message_id=primary_message_id,- kind="result",- )+ # Stream the delivered result to live consumers (avibe SSE).await _stream_chunk(context, text=display_text, message_id=primary_message_id, kind="result")@@ -547,6 +572,11 @@ class ConsolidatedMessageDispatcher:if canonical_type not in {"system", "assistant", "toolcall"}:canonical_type = "assistant"+ # Persist the intermediate log row BEFORE the mute filter so muted+ # assistant / tool_call messages still land in the store (product+ # requirement: the process log is complete even when a channel hides it).+ persist_agent_message(target_context, canonical_type, persist_text)+if settings_manager.is_message_type_hidden(settings_key, canonical_type):preview = text if len(text) <= 500 else f"{text[:500]}…"logger.info(diff --git a/core/message_mirror.py b/core/message_mirror.pyindex 1cf4feb60..357df1363 100644--- a/core/message_mirror.py+++ b/core/message_mirror.py@@ -11,8 +11,10 @@ Hooks live in two places:* ``core/handlers/message_handler.py`` calls :func:`mirror_inbound` onceper human-originated turn, after session resolution.-* ``core/message_dispatcher.py`` calls :func:`mirror_outbound` once per- successful agent ``result`` / ``notify`` send.+* ``core/message_dispatcher.py`` calls :func:`persist_agent_message` once per+ agent ``emit_agent_message`` — for every type (result / assistant /+ tool_call / notify), on every platform incl. avibe, BEFORE the IM mute+ filter so hidden messages still land.Failures are swallowed and logged. A bad mirror write must never breakthe live IM reply path.@@ -75,50 +77,108 @@ def _append_quietly(conn, **kwargs) -> None:)-def mirror_inbound(context: MessageContext, text: str) -> None:- """Record a human-originated message into the messages table."""-+def _scope_id_for_session(conn, session_id: str) -> Optional[str]:+ """Resolve a message's scope from its agent session (works for avibe ++ IM once the session has been reserved)."""+ from sqlalchemy import select++ from storage.models import agent_sessions++ row = conn.execute(+ select(agent_sessions.c.scope_id).where(agent_sessions.c.id == session_id)+ ).first()+ return row[0] if row else None+++# Maps the dispatcher's canonical message type to the persisted ``messages.type``.+# ``system`` folds into ``notify`` (a process message, not a user-facing reply)+# so it never pollutes the result-only inbox preview.+_AGENT_TYPE_BY_CANONICAL = {+ "result": "result",+ "notify": "notify",+ "assistant": "assistant",+ "toolcall": "tool_call",+ "tool_call": "tool_call",+ "system": "notify",+}+++def persist_agent_message(context: MessageContext, canonical_type: str, text: str) -> None:+ """Persist one agent output into the workbench ``messages`` store.++ Unified across **all** platforms (including avibe, which has no IM mirror)+ and called BEFORE any IM delivery/mute decision, so assistant / tool_call+ messages land even when a channel hides them. Each ``emit_agent_message``+ call is a distinct logical message — the consolidated IM "log" message only+ merges them for display — so one row per emit is correct, not fragments.++ ``context`` is the **post-routing delivery target** (see+ ``emit_agent_message``): IM rows are attributed to the channel that actually+ received the reply, so routed / ``post_to`` / thread replies are recorded+ under their delivery scope rather than the source session's — keeping+ cross-platform history/search pointed at the right conversation. avibe rows+ instead use the session's project scope (``agent_session_id`` from+ ``context.platform_specific``), which is what the per-session inbox groups on.+ """if not text or not text.strip():returnif not context.platform:return- if context.platform == "avibe":- # avibe's REST endpoint already writes through ``messages_service``;- # mirroring here would double-count the row.- return+ message_type = _AGENT_TYPE_BY_CANONICAL.get(canonical_type or "", "assistant")+ session_id = (context.platform_specific or {}).get("agent_session_id")try:engine = create_sqlite_engine()+ inbox_row = Nonewith engine.begin() as conn:- scope_id = _resolve_scope_id(conn, context)+ if context.platform == "avibe":+ # Inbox groups by the avibe session's project scope; never invent+ # a 'channel' scope for avibe (projects are pre-created via+ # /api/projects). Skip if the session row isn't visible yet.+ scope_id = _scope_id_for_session(conn, session_id) if session_id else None+ row_session_id = session_id+ else:+ # IM: attribute the row to the delivery channel (this ``context``+ # is the routed target), matching where the reply was sent. The+ # cross-platform history is scope-keyed, not session-keyed, so the+ # row carries no session_id — same shape as ``mirror_inbound``.+ scope_id = _resolve_scope_id(conn, context)+ row_session_id = Noneif scope_id is None:return_append_quietly(conn,scope_id=scope_id,- session_id=None,+ session_id=row_session_id,platform=context.platform,- author="user",+ author="agent",+ message_type=message_type,text=text,- author_id=context.user_id,- native_message_id=context.message_id,parent_native_message_id=context.thread_id,+ content={"kind": canonical_type} if canonical_type else None,)+ # Recompute the session's inbox row so the realtime event can patch+ # the browser without a refetch. avibe-only: the workbench inbox is+ # scoped to avibe sessions (IM rows persist but aren't shown there).+ if context.platform == "avibe" and session_id:+ inbox_row = messages_service.get_inbox_session(conn, session_id)+ if inbox_row is not None:+ from core.inbox_events import bus++ bus.publish("inbox.session.updated", inbox_row)except Exception:- logger.exception("mirror_inbound: unexpected failure on platform=%s", context.platform)+ logger.exception("persist_agent_message: failure on platform=%s", context.platform)-def mirror_outbound(- context: MessageContext,- text: str,- *,- native_message_id: Optional[str],- kind: str = "result",-) -> None:- """Record a successful agent reply into the messages table."""+def mirror_inbound(context: MessageContext, text: str) -> None:+ """Record a human-originated message into the messages table."""if not text or not text.strip():return- if not context.platform or context.platform == "avibe":+ if not context.platform:+ return+ if context.platform == "avibe":+ # avibe's REST endpoint already writes through ``messages_service``;+ # mirroring here would double-count the row.returntry:engine = create_sqlite_engine()@@ -131,11 +191,12 @@ def mirror_outbound(scope_id=scope_id,session_id=None,platform=context.platform,- author="agent",+ author="user",+ message_type="user",text=text,- native_message_id=native_message_id,+ author_id=context.user_id,+ native_message_id=context.message_id,parent_native_message_id=context.thread_id,- content={"kind": kind} if kind else None,)except Exception:- logger.exception("mirror_outbound: unexpected failure on platform=%s", context.platform)+ logger.exception("mirror_inbound: unexpected failure on platform=%s", context.platform)diff --git a/docs/plans/workbench-inbox-per-session.md b/docs/plans/workbench-inbox-per-session.mdnew file mode 100644index 000000000..2da52196a--- /dev/null+++ b/docs/plans/workbench-inbox-per-session.md@@ -0,0 +1,150 @@+# Workbench Inbox — Per-Session Feed · Design Doc++> **Branch**: `feat/workbench-inbox-per-session`+> **Status**: Implemented (2026-05-30) — backend query, typed persistence,+> Controller→UI realtime bridge, and frontend all landed.+> **Owner**: cyhhao++## 0. Prerequisite (confirmed 2026-05-30): unified, typed message persistence++**Finding (git archaeology):** avibe agent replies were *never* persisted — the mirror+(`920a513`) was built to "mirror **non-avibe** IM messages" and skips avibe; the avibe+adapter (`a7b87c0`) only pushes over SSE and never wrote to `messages`; `ui_server` only+ever wrote the user's own message. So the messages table holds avibe **user** rows but no+agent replies. Not a regression — an unfinished corner.++**Decision:** persist messages in the **Controller**, unified across all platforms incl.+avibe, **decoupled from IM delivery/muting** — i.e. `assistant` and `tool_call` messages are+persisted even when the IM side hides them (`emit_agent_message` currently drops them before+send). Add a first-class **`type` column** to `messages` (Alembic migration + backfill):++| `type` | meaning |+| --- | --- |+| `user` | human-sent |+| `assistant` | agent's intermediate text (before the final result) |+| `tool_call` | tool invocation |+| `notify` | progress/notification |+| `result` | the final user-facing answer (inbox preview = latest of these) |++Persistence hook lives in the Controller message flow *before* the IM mute filter, so every+type lands regardless of per-channel display preferences. The per-session inbox preview =+latest `type='result'` message — aligned with the avibe chat, which only renders results;+`assistant` / `tool_call` are the intermediate process log and never drive the preview.+Realtime therefore uses the Controller→UI events bridge (§4), since persistence now happens+Controller-side for all platforms.++**Read paths stay result-aware** (so persisting the full process log never leaks): the avibe+chat transcript (`/api/sessions/<id>/messages`) is scoped to `type IN ('user','result','notify')`+plus rows with `metadata.source='show_page'` — it keeps the dialogue, terminal `notify` markers+(a failed/stopped turn, rendered as a distinct gold "Notify" row), and Show-Page transcript+marks, while hiding intermediate `assistant` / `tool_call` process rows. The unread counts+(`unread_counts` / `unread_counts_by_session`) count `type='result'` only — matching the inbox+card's `unread_count` so the sidebar badge and the card never disagree. ChatPage marks the+actively-viewed session read on any unread so the open chat never badges itself.++## 1. Why++The current Workbench Inbox is a flat **per-message** feed: `messages_service.list_inbox`+returns the most recent agent-authored message rows, so one busy session produces many+cards, cards show raw `scope_id`/`session_id` (no project name / session title), and there+is no realtime push for agent replies (only the web user-message write publishes an SSE+event; agent replies are written by the mirror in the **Controller** process and never reach+the UI server's browser SSE).++We are reshaping it into a Slack-like **per-session** feed: one card per conversation,+showing that conversation's latest agent reply, jumping to the top in real time on any new+message.++## 2. Confirmed product decisions++1. **Sort** by each session's last message of **any author**, time descending.+2. **Preview** text = that session's **latest agent reply** (distinct from the sort key).+3. **Tabs**: "Unread" lists only sessions with unread agent messages; "All" lists every+ session that has ≥1 agent reply.+4. **Open = mark the whole session read** (reuse existing `mark_session_read`).+5. **Scope**: avibe web sessions only (`platform = 'avibe'`).+6. **Realtime**: a new agent reply must bump its card to the top within ~1s, no manual+ refresh. Requires a Controller→UI cross-process event channel.+7. **"Replied" badge**: shown when the session's **last message is from the user**+ (`last_message_author == 'user'`) — i.e. you've responded and are awaiting the agent.+ NOT a sticky "ever replied" flag.++## 3. Data model — query-time aggregation, no new table++`agent_sessions` is the conversation aggregate root; `messages` stays the single source of+truth for read/unread. No schema migration.++Per-session inbox row (computed):++| Field | Source |+| --- | --- |+| `session_id` | `agent_sessions.id` |+| `scope_id` / `project_id` | `agent_sessions.scope_id` → `scopes.native_id` |+| `project_name` | `scopes.display_name` |+| `title` | `agent_sessions.title` |+| `last_activity_at` (sort key) | `MAX(messages.created_at)` over the session, any author |+| `last_message_author` | author of the message at `last_activity_at` (→ `replied` = `=='user'`) |+| `preview_text` / `preview_at` | latest `type='result'` message in the session |+| `unread_count` | count of `type='result' AND read_at IS NULL` in the session |++Eligibility: sessions with ≥1 `type='result'` message, `platform='avibe'`. "Unread" filter:+`unread_count > 0`. Sort: `last_activity_at DESC, session_id DESC`. Pagination: keyset cursor+on `(last_activity_at, session_id)` ("load more").++Implementation: `storage/messages_service.py::list_inbox_sessions(conn, *, unread_only,+limit, before)` using window functions / grouped subqueries over `messages` joined to+`agent_sessions` + `scopes`. `mark_session_read` is unchanged.++## 4. Realtime — Controller → UI events bridge++Reuses the existing internal Unix-socket infra (`core/internal_server.py` ++`vibe/internal_client.py`) and the per-process browser `SSEBroker`.++1. **Controller event bus** (`core/inbox_events.py`): a small thread-safe fan-out+ (`asyncio.Queue` per subscriber) owned by the Controller. `persist_agent_message`+ (`core/message_mirror.py`, runs in the Controller) emits an `inbox.session.updated` event+ after persisting an avibe **result** — carrying the recomputed per-session inbox row (so+ the browser can patch without a refetch). Intermediate `assistant`/`tool_call` persist+ silently (no result row yet → no event).+2. **`GET /internal/events`** (new, `core/internal_server.py`): long-lived SSE that subscribes+ to the event bus and streams events; mirrors the existing `/internal/dispatch` streaming+ shape.+3. **UI server subscriber**: a lifespan background task (`vibe/ui_server.py`) connects via a+ new `internal_client.stream_events()` and re-publishes each event to the browser `SSEBroker`+ (`broker.publish('inbox.session.updated', row)`), reconnecting on drop.+4. The existing in-process web user-message write also publishes `inbox.session.updated` so+ the user's own send updates the feed instantly without the round trip.++Browser: `WorkbenchInboxContext` handles `inbox.session.updated` by upserting the row and+re-sorting (bump to top); `inbox.unread.changed` / `markRead` zero the unread.++## 5. Frontend++- `WorkbenchInboxContext`: state becomes `inboxSessions: InboxSession[]` (+ `totalUnread`,+ pagination cursor). Realtime upsert + re-sort. `markRead(sessionId)` unchanged.+- `InboxPage`: one card per session — project name, title, **agent** preview, relative time+ (of last activity), unread badge, **已回复 / Replied** badge when `last_message_author=='user'`.+ Unread/All tabs; "Load more".+- `WorkbenchSidebar` `InboxHoverPopover`: show session title + project name (not IDs).+- i18n: `workbench.inbox.replied` etc. in `en.json` + `zh.json`.++## 6. Tests++- `tests/test_messages_service.py`: `list_inbox_sessions` — one card per session, sort by last+ activity (any author), preview = latest **result** (an intermediate `assistant` bumps the+ sort clock but never the preview), `unread_count`, `replied` when last message is the user's,+ pagination cursor.+- `tests/test_message_mirror.py`: `persist_agent_message` lands a typed agent row; an avibe+ `result` on a resolved session both persists **and** publishes `inbox.session.updated`; an+ intermediate `assistant` persists without publishing (no result yet).+- `tests/test_inbox_events.py`: `InboxEventBus` fan-out / unsubscribe / no-subscriber no-op.+- `tests/test_sqlite_state_migration.py`: HEAD bumped to the `messages.type` migration.+- Keep existing `unread_counts` / `mark_session_read` tests green.++## 7. Commit breakdown++1. Plan doc (this file).+2. Backend: `list_inbox_sessions` + `/api/inbox` shape change + tests.+3. Realtime: Controller event bus + `/internal/events` + UI subscriber + emit on writes.+4. Frontend: context + InboxPage + sidebar popover + i18n.+5. Polish + PR.diff --git a/storage/alembic/versions/20260531_0009_messages_type.py b/storage/alembic/versions/20260531_0009_messages_type.pynew file mode 100644index 000000000..ccf595e10--- /dev/null+++ b/storage/alembic/versions/20260531_0009_messages_type.py@@ -0,0 +1,67 @@+"""add messages.type column++Adds a first-class ``type`` column to ``messages`` (user / assistant /+tool_call / notify / result), distinct from the coarse ``author``. Backfills+existing rows from ``author`` + the legacy ``content_json.kind`` so the+per-session inbox can preview the latest ``result`` reply.++Revision ID: 20260531_0009+Revises: 20260530_0009+Create Date: 2026-05-31+"""++from __future__ import annotations++import sqlalchemy as sa+from alembic import op++revision = "20260531_0009"+down_revision = "20260530_0009"+branch_labels = None+depends_on = None+++def _columns(bind, table: str) -> set[str]:+ return {row[1] for row in bind.exec_driver_sql(f'pragma table_info("{table}")')}+++def _tables(bind) -> set[str]:+ return {row[0] for row in bind.exec_driver_sql("select name from sqlite_master where type = 'table'")}+++def upgrade() -> None:+ bind = op.get_bind()+ if "messages" not in _tables(bind):+ return+ if "type" in _columns(bind, "messages"):+ return++ # server_default lets the NOT NULL add succeed on existing rows; new+ # inserts always pass an explicit type via messages_service.append.+ op.add_column(+ "messages",+ sa.Column("type", sa.String(), nullable=False, server_default="assistant"),+ )++ # Backfill: user rows -> user; agent rows keep their legacy content_json+ # kind (notify/result) or fall back to assistant; everything else (system)+ # collapses to assistant so it still surfaces as a textual reply.+ bind.exec_driver_sql(+ """+ update messages+ set type = case+ when author = 'user' then 'user'+ when json_extract(content_json, '$.kind') = 'notify' then 'notify'+ when json_extract(content_json, '$.kind') = 'result' then 'result'+ when json_extract(content_json, '$.kind') = 'toolcall' then 'tool_call'+ when json_extract(content_json, '$.kind') = 'tool_call' then 'tool_call'+ else 'assistant'+ end+ """+ )+++def downgrade() -> None:+ bind = op.get_bind()+ if "messages" in _tables(bind) and "type" in _columns(bind, "messages"):+ op.drop_column("messages", "type")diff --git a/storage/messages_service.py b/storage/messages_service.pyindex dc622c38c..6d1c279c4 100644--- a/storage/messages_service.py+++ b/storage/messages_service.py@@ -11,6 +11,7 @@ land in one place.from __future__ import annotationsimport json+import timeimport uuidfrom datetime import datetime, timezonefrom typing import Any, Iterable, Optional@@ -18,7 +19,7 @@ from typing import Any, Iterable, Optionalfrom sqlalchemy import and_, func, or_, select, updatefrom sqlalchemy.engine import Connection-from storage.models import messages+from storage.models import agent_sessions, messages, scopesdef _utc_now_iso() -> str:@@ -26,7 +27,18 @@ def _utc_now_iso() -> str:def _new_message_id() -> str:- return f"msg_{uuid.uuid4().hex[:16]}"+ """Time-sortable message id.++ The transcript and inbox order rows by ``(created_at, id)`` and+ ``created_at`` is second-resolution, so two rows written in the same second+ — e.g. a fast avibe turn where the user prompt and the agent result land+ together — tie on ``created_at``. A microsecond-clock prefix makes the id+ monotonic so that tie-break preserves insertion order; otherwise a random+ uuid could render the result before the prompt, or make the inbox pick the+ wrong "last" row for its activity / replied state. The random suffix keeps+ ids unique within the same microsecond.+ """+ return f"msg_{int(time.time() * 1_000_000):015x}{uuid.uuid4().hex[:8]}"def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:@@ -44,6 +56,7 @@ def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:"session_id": row.get("session_id"),"platform": row.get("platform"),"author": row.get("author"),+ "type": row.get("type"),"author_id": row.get("author_id"),"author_name": row.get("author_name"),"native_message_id": row.get("native_message_id"),@@ -65,6 +78,7 @@ def append(session_id: Optional[str],platform: str,author: str,+ message_type: Optional[str] = None,text: Optional[str] = None,content: Optional[dict[str, Any]] = None,metadata: Optional[dict[str, Any]] = None,@@ -89,6 +103,12 @@ def append(body.setdefault("text", text)plain = text if text is not None else body.get("text") or None+ # Default the type from the author so legacy callers that only set ``author``+ # (e.g. show-page transcript annotations) stay correctly typed — a human row+ # must be ``user`` (not ``assistant``), or the user+result transcript filter+ # would drop it. Typed callers (inbox/IM mirror) pass message_type explicitly.+ resolved_type = message_type or ("user" if author == "user" else "assistant")+now = _utc_now_iso()payload = {"id": _new_message_id(),@@ -96,6 +116,7 @@ def append("session_id": session_id,"platform": platform,"author": author,+ "type": resolved_type,"author_id": author_id,"author_name": author_name,"native_message_id": native_message_id,@@ -118,10 +139,32 @@ def list_session_messages(session_id: str,after_id: Optional[str] = None,limit: int = 50,+ types: Optional[Iterable[str]] = None,+ include_metadata_sources: Iterable[str] = (),) -> dict[str, Any]:- """Return messages for one session in chronological order with cursor pagination."""+ """Return messages for one session in chronological order with cursor pagination.++ ``types`` optionally restricts the rows to a set of message types. The chat+ transcript passes ``('user', 'result')`` so the intermediate ``assistant`` /+ ``tool_call`` / ``notify`` rows — now persisted for avibe sessions too — stay+ out of the conversation view (they're the process log, not the dialogue).++ ``include_metadata_sources`` keeps rows whose ``metadata.source`` matches even+ when their type is filtered out — the chat transcript passes ``('show_page',)``+ so Show-Page transcript marks (written with ``author='agent'`` → ``type+ ='assistant'``) stay visible alongside the user/result dialogue.+ """query = select(messages).where(messages.c.session_id == session_id)+ metadata_sources = list(include_metadata_sources)+ if types is not None:+ type_filter = messages.c.type.in_(list(types))+ if metadata_sources:+ query = query.where(+ or_(type_filter, func.json_extract(messages.c.metadata_json, "$.source").in_(metadata_sources))+ )+ else:+ query = query.where(type_filter)if after_id:anchor = conn.execute(select(messages.c.created_at).where(messages.c.id == after_id)@@ -143,63 +186,25 @@ def list_session_messages(return {"messages": rows, "next_after_id": next_after}-def list_inbox(- conn: Connection,- *,- platform: Optional[str] = None,- unread_only: bool = False,- limit: int = 30,- before_id: Optional[str] = None,-) -> dict[str, Any]:- """Cross-session feed for the workbench Inbox.-- Returns the most recent agent-authored messages first (the human- sent them, they don't need to see their own as "new"). The- ``platform`` filter defaults to nothing so users opting into- cross-platform mirroring see Slack/Discord here too; per the- workbench scope the UI passes ``platform='avibe'`` to scope it- down.- """-- query = select(messages).where(messages.c.author == "agent")- if platform is not None:- query = query.where(messages.c.platform == platform)- if unread_only:- query = query.where(messages.c.read_at.is_(None))- if before_id:- anchor = conn.execute(- select(messages.c.created_at).where(messages.c.id == before_id)- ).scalar_one_or_none()- if anchor is not None:- query = query.where(- or_(- messages.c.created_at < anchor,- and_(messages.c.created_at == anchor, messages.c.id < before_id),- )- )- effective_limit = min(max(int(limit), 1), 200)- query = query.order_by(messages.c.created_at.desc(), messages.c.id.desc()).limit(effective_limit)- rows = [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]- # Same fix as ``list_session_messages``: gate the cursor on the- # clamped page size, not the raw caller-supplied limit.- next_before = rows[-1]["id"] if len(rows) == effective_limit else None- return {"messages": rows, "next_before_id": next_before}--def unread_counts(conn: Connection,*,platform: Optional[str] = None,) -> dict[str, int]:- """Return ``{scope_id: count}`` for unread agent messages.+ """Return ``{scope_id: count}`` for unread agent ``result`` messages.Used by the sidebar / hover popover to show per-session unread dotsplus the global count without dragging every row through Python.+ Filtered to ``type='result'`` so it agrees with the inbox feed, whose+ unread/preview/eligibility are all result-only — otherwise intermediate+ ``assistant`` / ``tool_call`` rows (now persisted for avibe too) would+ inflate the badge past what the feed shows."""query = (select(messages.c.scope_id, func.count(messages.c.id)).where(messages.c.author == "agent")+ .where(messages.c.type == "result").where(messages.c.read_at.is_(None)).group_by(messages.c.scope_id))@@ -213,17 +218,20 @@ def unread_counts_by_session(*,platform: Optional[str] = None,) -> dict[str, int]:- """Return ``{session_id: count}`` for unread agent messages.+ """Return ``{session_id: count}`` for unread agent ``result`` messages.Per-session granularity for the sidebar: a project can hold severalsessions, so a scope-level count (see ``unread_counts``) would stamp thesame badge on every session row. Rows with a null ``session_id`` are- skipped — they can't be attributed to a specific session.+ skipped — they can't be attributed to a specific session. Filtered to+ ``type='result'`` so the sidebar badge matches the inbox card's unread+ count (the realtime ``inbox.session.updated`` row is result-only too)."""query = (select(messages.c.session_id, func.count(messages.c.id)).where(messages.c.author == "agent")+ .where(messages.c.type == "result").where(messages.c.read_at.is_(None)).where(messages.c.session_id.is_not(None)).group_by(messages.c.session_id)@@ -233,6 +241,168 @@ def unread_counts_by_session(return {session_id: int(count) for session_id, count in conn.execute(query).all()}+def list_inbox_sessions(+ conn: Connection,+ *,+ platform: Optional[str] = "avibe",+ unread_only: bool = False,+ limit: int = 30,+ before: Optional[str] = None,+ only_session: Optional[str] = None,+) -> dict[str, Any]:+ """Per-session ("Slack-like") inbox feed.++ One row per session that has at least one agent reply. Sorted by the+ session's most recent message of *any* author (the activity clock),+ descending. The preview text is the session's latest *agent* reply+ (distinct from the sort key). ``replied`` is True when the most recent+ message is the user's (they've responded, awaiting the agent).++ Keyset pagination via ``before`` (an opaque ``"<last_activity_at>|<session_id>"``+ cursor returned as ``next_cursor``).+ """++ m = messages++ # Rank every message in a session by recency (any author) → latest = activity clock.+ any_ranked = (+ select(+ m.c.session_id.label("session_id"),+ m.c.scope_id.label("scope_id"),+ m.c.author.label("last_author"),+ m.c.created_at.label("last_activity_at"),+ func.row_number()+ .over(partition_by=m.c.session_id, order_by=(m.c.created_at.desc(), m.c.id.desc()))+ .label("rn"),+ )+ .where(m.c.session_id.is_not(None))+ )+ if platform is not None:+ any_ranked = any_ranked.where(m.c.platform == platform)+ any_ranked = any_ranked.subquery()+ latest_any = select(any_ranked).where(any_ranked.c.rn == 1).subquery()++ # Rank agent messages by recency → latest agent reply = preview (also proves eligibility).+ agent_ranked = (+ select(+ m.c.session_id.label("session_id"),+ m.c.content_text.label("preview_text"),+ m.c.content_json.label("preview_json"),+ m.c.created_at.label("preview_at"),+ func.row_number()+ .over(partition_by=m.c.session_id, order_by=(m.c.created_at.desc(), m.c.id.desc()))+ .label("rn"),+ )+ .where(m.c.session_id.is_not(None))+ .where(m.c.type == "result")+ )+ if platform is not None:+ agent_ranked = agent_ranked.where(m.c.platform == platform)+ agent_ranked = agent_ranked.subquery()+ latest_agent = select(agent_ranked).where(agent_ranked.c.rn == 1).subquery()++ # Unread agent messages per session.+ unread_q = (+ select(m.c.session_id.label("session_id"), func.count().label("unread_count"))+ .where(m.c.session_id.is_not(None))+ .where(m.c.type == "result")+ .where(m.c.read_at.is_(None))+ .group_by(m.c.session_id)+ )+ if platform is not None:+ unread_q = unread_q.where(m.c.platform == platform)+ unread_sub = unread_q.subquery()++ unread_count_col = func.coalesce(unread_sub.c.unread_count, 0)+ query = (+ select(+ latest_agent.c.session_id,+ latest_agent.c.preview_text,+ latest_agent.c.preview_json,+ latest_agent.c.preview_at,+ latest_any.c.last_author,+ latest_any.c.last_activity_at,+ agent_sessions.c.title,+ agent_sessions.c.scope_id,+ scopes.c.native_id.label("project_id"),+ scopes.c.display_name.label("project_name"),+ unread_count_col.label("unread_count"),+ )+ .select_from(+ latest_agent.join(latest_any, latest_any.c.session_id == latest_agent.c.session_id)+ .join(agent_sessions, agent_sessions.c.id == latest_agent.c.session_id)+ .join(scopes, scopes.c.id == agent_sessions.c.scope_id, isouter=True)+ .join(unread_sub, unread_sub.c.session_id == latest_agent.c.session_id, isouter=True)+ )+ )+ if unread_only:+ query = query.where(unread_count_col > 0)+ if only_session:+ query = query.where(latest_agent.c.session_id == only_session)+ if before:+ cursor_at, _, cursor_session = before.partition("|")+ if cursor_at and cursor_session:+ query = query.where(+ or_(+ latest_any.c.last_activity_at < cursor_at,+ and_(+ latest_any.c.last_activity_at == cursor_at,+ latest_agent.c.session_id < cursor_session,+ ),+ )+ )++ effective_limit = min(max(int(limit), 1), 100)+ query = query.order_by(+ latest_any.c.last_activity_at.desc(), latest_agent.c.session_id.desc()+ ).limit(effective_limit)++ rows = conn.execute(query).mappings().all()+ sessions: list[dict[str, Any]] = []+ for row in rows:+ preview = row["preview_text"]+ if not preview and row["preview_json"]:+ try:+ preview = (json.loads(row["preview_json"]) or {}).get("text") or ""+ except json.JSONDecodeError:+ preview = ""+ unread = int(row["unread_count"] or 0)+ sessions.append(+ {+ "session_id": row["session_id"],+ "scope_id": row["scope_id"],+ "project_id": row["project_id"],+ "project_name": row["project_name"],+ "title": row["title"],+ "last_activity_at": row["last_activity_at"],+ "last_message_author": row["last_author"],+ "replied": row["last_author"] == "user",+ "preview_text": preview or "",+ "preview_at": row["preview_at"],+ "unread_count": unread,+ "unread": unread > 0,+ }+ )++ next_cursor = None+ if len(sessions) == effective_limit:+ tail = sessions[-1]+ next_cursor = f"{tail['last_activity_at']}|{tail['session_id']}"+ return {"sessions": sessions, "next_cursor": next_cursor}+++def get_inbox_session(+ conn: Connection,+ session_id: str,+ *,+ platform: Optional[str] = "avibe",+) -> Optional[dict[str, Any]]:+ """Return one session's inbox row (or None if it has no agent ``result``+ yet). Used to build realtime ``inbox.session.updated`` payloads."""+ rows = list_inbox_sessions(conn, platform=platform, only_session=session_id, limit=1)["sessions"]+ return rows[0] if rows else None++def mark_session_read(conn: Connection,session_id: str,diff --git a/storage/migrations.py b/storage/migrations.pyindex 98a888c45..b19817e9c 100644--- a/storage/migrations.py+++ b/storage/migrations.py@@ -12,7 +12,7 @@ from config import pathsfrom storage.db import create_sqlite_engine, sqlite_urlINITIAL_REVISION = "20260501_0001"-LATEST_SCHEMA_REVISION = "20260530_0009"+LATEST_SCHEMA_REVISION = "20260531_0009"REMOVE_LEGACY_DEFAULT_AGENT_REVISION = "20260530_0008"INITIAL_TABLES = {"state_meta",@@ -29,6 +29,7 @@ HEAD_REQUIRED_COLUMNS = {"agents": {"enabled"},"scope_settings": {"agent_name"},"agent_sessions": {"agent_id", "agent_name"},+ "messages": {"type"},"run_definitions": {"deleted_at","definition_type",@@ -338,6 +339,25 @@ def _repair_head_required_columns(conn: sqlite3.Connection, tables: set[str]) ->run_columns = _column_names(conn, "agent_runs")if "message" in run_columns and "prompt" in run_columns:conn.execute('update "agent_runs" set message = prompt where message is null')++ # messages.type (20260531_0009): add + backfill, mirroring the migration, so+ # a drifted/unversioned head schema reaches readiness instead of leaving+ # messages_service.append writing a column that doesn't exist.+ if "messages" in tables and "type" not in _column_names(conn, "messages"):+ conn.execute('alter table "messages" add column "type" VARCHAR not null default \'assistant\'')+ conn.execute(+ """+ update messages set type = case+ when author = 'user' then 'user'+ when json_extract(content_json, '$.kind') = 'notify' then 'notify'+ when json_extract(content_json, '$.kind') = 'result' then 'result'+ when json_extract(content_json, '$.kind') in ('toolcall', 'tool_call') then 'tool_call'+ else 'assistant'+ end+ """+ )+ changed = True+_ensure_new_background_indexes(conn)return changeddiff --git a/storage/models.py b/storage/models.pyindex f7031a725..f8aaca171 100644--- a/storage/models.py+++ b/storage/models.py@@ -287,6 +287,10 @@ messages = Table(Column("session_id", String, ForeignKey("agent_sessions.id", ondelete="SET NULL"), nullable=True),Column("platform", String, nullable=False),Column("author", String, nullable=False),+ # Fine-grained message type, distinct from the coarse ``author``:+ # user / assistant / tool_call / notify / result. The inbox preview uses+ # the latest ``assistant`` row. Persisted regardless of IM display muting.+ Column("type", String, nullable=False, server_default="assistant"),Column("author_id", String, nullable=True),Column("author_name", Text, nullable=True),Column("native_message_id", String, nullable=True),diff --git a/tests/test_inbox_events.py b/tests/test_inbox_events.pynew file mode 100644index 000000000..d0aa118f4--- /dev/null+++ b/tests/test_inbox_events.py@@ -0,0 +1,73 @@+"""Unit tests for the controller-side ``InboxEventBus`` fan-out.++The bus is the Controller-process half of the realtime inbox bridge:+``core.message_mirror`` publishes ``inbox.session.updated`` here, and+``core.internal_server``'s ``GET /internal/events`` subscribes and streams the+events over the dispatch socket to the UI server. These tests pin the contract+the bridge relies on: subscribers receive published events, unsubscribe stops+delivery, and a publish with no subscribers is a harmless no-op.++The repo has no ``pytest-asyncio``; following the existing convention+(``tests/test_dispatcher_stream_chunk.py``) each async scenario runs inside+``asyncio.run`` so the loop captured at ``subscribe`` time is the one driving+``publish``'s ``call_soon_threadsafe``.+"""++from __future__ import annotations++import asyncio+import sys+from pathlib import Path++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from core.inbox_events import InboxEventBus+++def test_publish_delivers_to_subscriber():+ async def scenario():+ bus = InboxEventBus()+ sub_id, queue = bus.subscribe()+ bus.publish("inbox.session.updated", {"session_id": "s1"})+ event_type, data = await asyncio.wait_for(queue.get(), timeout=1.0)+ bus.unsubscribe(sub_id)+ return event_type, data++ event_type, data = asyncio.run(scenario())+ assert event_type == "inbox.session.updated"+ assert data == {"session_id": "s1"}+++def test_fanout_to_every_subscriber():+ async def scenario():+ bus = InboxEventBus()+ _, q1 = bus.subscribe()+ _, q2 = bus.subscribe()+ bus.publish("e", {"n": 1})+ return (+ await asyncio.wait_for(q1.get(), timeout=1.0),+ await asyncio.wait_for(q2.get(), timeout=1.0),+ )++ a, b = asyncio.run(scenario())+ assert a == ("e", {"n": 1})+ assert b == ("e", {"n": 1})+++def test_unsubscribe_stops_delivery():+ async def scenario():+ bus = InboxEventBus()+ sub_id, queue = bus.subscribe()+ bus.unsubscribe(sub_id)+ bus.publish("inbox.session.updated", {"session_id": "s1"})+ with pytest.raises(asyncio.TimeoutError):+ await asyncio.wait_for(queue.get(), timeout=0.05)++ asyncio.run(scenario())+++def test_publish_without_subscribers_is_noop():+ # No loop captured, no subscribers — must not raise (boot / headless path).+ InboxEventBus().publish("inbox.session.updated", {"x": 1})diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.pyindex 4733f4255..230475369 100644--- a/tests/test_message_dispatcher_result_fallback.py+++ b/tests/test_message_dispatcher_result_fallback.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport sysimport unittestfrom pathlib import Path+from unittest import mocksys.path.insert(0, str(Path(__file__).resolve().parents[1]))@@ -130,6 +131,84 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):self.assertIsNone(reply_to)self.assertEqual([button.text for button in keyboard.buttons[0]], ["Continue", "Stop"])+ async def test_result_persists_cleaned_display_text_not_raw(self):+ """The persisted result must match what the user was shown, not the raw+ text with reply-enhancer artifacts. The inbox preview + chat transcript+ reload the persisted row, so the trailing quick-reply button block (and+ file:// links) must already be stripped at persist time."""+ im_client = _NativeMarkdownIMClient()+ controller = _StubController(platform="slack", im_client=im_client, reply_enhancements=True)+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(user_id="U1", channel_id="C1", platform="slack")+ raw = "Body\n\n---\n[Continue] | [Stop]"++ with mock.patch("core.message_dispatcher.persist_agent_message") as persist:+ await dispatcher.emit_agent_message(context, "result", raw)++ # Delivered text had the quick-reply block stripped to "Body".+ _, delivered_text, _, _ = im_client.native_markdown_messages[0]+ self.assertEqual(delivered_text, "Body")+ # The persisted row must equal the displayed text, not the raw input.+ persist.assert_called_once()+ _, persisted_type, persisted_text = persist.call_args.args+ self.assertEqual(persisted_type, "result")+ self.assertEqual(persisted_text, "Body")+ self.assertNotIn("[Continue]", persisted_text)++ async def test_suppressed_delivery_is_not_persisted(self):+ """Suppressed scheduled output is intentionally private — it must NOT+ leak into the cross-platform messages history."""+ controller = _StubController(platform="slack")+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(+ user_id="U1", channel_id="C1", platform="slack",+ platform_specific={"suppress_delivery": True},+ )+ with mock.patch("core.message_dispatcher.persist_agent_message") as persist:+ message_id = await dispatcher.emit_agent_message(context, "result", "private output")+ persist.assert_not_called()+ self.assertTrue(message_id.startswith("suppressed:"))++ async def test_notify_persisted_only_on_successful_send(self):+ controller = _StubController(platform="slack")+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(user_id="U1", channel_id="C1", platform="slack")+ with mock.patch("core.message_dispatcher.persist_agent_message") as persist:+ await dispatcher.emit_agent_message(context, "notify", "heads up")+ persist.assert_called_once()+ self.assertEqual(persist.call_args.args[1], "notify")++ async def test_notify_not_persisted_when_send_fails(self):+ class _FailClient(_StubIMClient):+ async def send_message(self, *args, **kwargs):+ raise RuntimeError("platform API down")++ controller = _StubController(platform="slack", im_client=_FailClient())+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(user_id="U1", channel_id="C1", platform="slack")+ with mock.patch("core.message_dispatcher.persist_agent_message") as persist:+ result = await dispatcher.emit_agent_message(context, "notify", "heads up")+ self.assertIsNone(result)+ persist.assert_not_called()++ async def test_muted_log_message_still_persists(self):+ """assistant / tool_call rows persist BEFORE the mute filter, so a muted+ process log still lands in the store (product requirement)."""+ class _HiddenSettings(_StubSettingsManager):+ def is_message_type_hidden(self, settings_key, canonical_type):+ return True++ controller = _StubController(platform="slack")+ controller.get_settings_manager_for_context = lambda ctx: _HiddenSettings()+ dispatcher = ConsolidatedMessageDispatcher(controller)+ context = MessageContext(user_id="U1", channel_id="C1", platform="slack")+ with mock.patch("core.message_dispatcher.persist_agent_message") as persist:+ result = await dispatcher.emit_agent_message(context, "assistant", "thinking…")+ # Hidden → not delivered, but still persisted.+ self.assertIsNone(result)+ persist.assert_called_once()+ self.assertEqual(persist.call_args.args[1], "assistant")+async def test_summary_upload_becomes_primary_anchor_without_duplicate_upload(self):controller = _StubController(platform="lark", language="en", fail_first_send=True)dispatcher = ConsolidatedMessageDispatcher(controller)diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.pyindex aca6a365d..630c78f7a 100644--- a/tests/test_message_mirror.py+++ b/tests/test_message_mirror.py@@ -1,22 +1,22 @@-"""Unit tests for the cross-platform message mirror.--These cover the contract that-``core.handlers.message_handler.MessageHandler`` and-``core.message_dispatcher.ConsolidatedMessageDispatcher`` rely on:--* a fresh ``(platform, channel_id)`` is auto-upserted as a 'channel'-typed- scope on first inbound mirror,-* the same call also writes an author='user' row,-* a follow-up outbound mirror lands an author='agent' row on the same- scope,-* repeated mirror calls with the same ``native_message_id`` are- idempotent (no extra rows, no raised exception),-* ``platform='avibe'`` is a no-op so the workbench REST writer stays the- single source of truth.+"""Unit tests for the cross-platform message mirror + unified agent persist.++Covers the contract that ``MessageHandler`` / ``ConsolidatedMessageDispatcher``+rely on:++* a fresh ``(platform, channel_id)`` auto-upserts as a 'channel'-typed scope on+ first inbound mirror, writing an author='user', type='user' row,+* ``persist_agent_message`` lands an author='agent' row (typed) on the same+ scope for the live reply,+* repeated inbound mirror calls with the same ``native_message_id`` are+ idempotent,+* ``mirror_inbound`` is a no-op for ``platform='avibe'`` (the workbench REST+ writer owns the user row), while ``persist_agent_message`` DOES persist avibe+ agent output (unified store)."""from __future__ import annotations+import asyncioimport sysfrom pathlib import Path@@ -25,11 +25,12 @@ from sqlalchemy import selectsys.path.insert(0, str(Path(__file__).resolve().parents[1]))-from core.message_mirror import mirror_inbound, mirror_outbound+from core.message_mirror import mirror_inbound, persist_agent_messagefrom modules.im import MessageContextfrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state-from storage.models import messages, scopes+from storage.models import agent_sessions, messages, scopes+from storage.settings_service import upsert_scope@pytest.fixture()@@ -65,25 +66,96 @@ def test_inbound_creates_scope_and_user_row(isolated_state):).mappings().all()assert len(message_rows) == 1assert message_rows[0]["author"] == "user"+ assert message_rows[0]["type"] == "user"assert message_rows[0]["content_text"] == "hello there"assert message_rows[0]["author_id"] == "U_alice"-def test_outbound_writes_agent_row_on_same_scope(isolated_state):+def test_persist_agent_writes_typed_agent_row_on_same_scope(isolated_state):ctx = _slack_ctx()mirror_inbound(ctx, "ping")- mirror_outbound(ctx, "pong", native_message_id="slack_m_002", kind="result")+ persist_agent_message(ctx, "result", "pong")engine = create_sqlite_engine()with engine.connect() as conn:rows = conn.execute(- select(messages).where(messages.c.platform == "slack").order_by(messages.c.created_at)+ select(messages).where(messages.c.platform == "slack")).mappings().all()- assert [row["author"] for row in rows] == ["user", "agent"]- assert rows[1]["content_text"] == "pong"- assert rows[1]["native_message_id"] == "slack_m_002"- # Both rows share the scope auto-created on first inbound.- assert rows[0]["scope_id"] == rows[1]["scope_id"]+ # Two separate-second-resolution writes can tie on created_at, so assert by+ # author rather than row order.+ assert {row["author"] for row in rows} == {"user", "agent"}+ agent_row = next(r for r in rows if r["author"] == "agent")+ user_row = next(r for r in rows if r["author"] == "user")+ assert agent_row["content_text"] == "pong"+ assert agent_row["type"] == "result"+ # No session resolved on this synthetic context -> falls back to the+ # channel scope auto-created on first inbound; both rows share it.+ assert agent_row["scope_id"] == user_row["scope_id"]+++def test_persist_agent_maps_canonical_type(isolated_state):+ ctx = _slack_ctx()+ mirror_inbound(ctx, "ping")+ persist_agent_message(ctx, "toolcall", "ran a tool")++ engine = create_sqlite_engine()+ with engine.connect() as conn:+ agent_row = conn.execute(+ select(messages).where(messages.c.author == "agent")+ ).mappings().first()+ # canonical 'toolcall' persists as the 'tool_call' type.+ assert agent_row["type"] == "tool_call"+++def test_persist_agent_im_uses_delivery_scope_not_session(isolated_state):+ """A routed IM reply (the delivery target differs from the source session's+ channel) is attributed to the DELIVERY channel scope with no session_id, so+ cross-platform history points at where the reply was actually sent — not the+ originating session's channel. (``emit_agent_message`` hands us the+ post-routing target context.)"""+ from storage.models import agent_sessions++ engine = create_sqlite_engine()+ now = "2026-05-30T12:00:00Z"+ with engine.begin() as conn:+ # Source session lives under channel C_source.+ scope_source = upsert_scope(+ conn, platform="slack", scope_type="channel", native_id="C_source", now=now+ )+ conn.execute(+ agent_sessions.insert().values(+ id="ses_im",+ scope_id=scope_source,+ agent_backend="claude",+ agent_variant="default",+ session_anchor="anchor_ses_im",+ native_session_id="",+ status="active",+ metadata_json="{}",+ created_at=now,+ updated_at=now,+ last_active_at=now,+ )+ )++ # Delivery target = C_delivery, but agent_session_id still rides along.+ target_ctx = MessageContext(+ user_id="U",+ channel_id="C_delivery",+ platform="slack",+ platform_specific={"agent_session_id": "ses_im"},+ )+ persist_agent_message(target_ctx, "result", "routed answer")++ engine = create_sqlite_engine()+ with engine.connect() as conn:+ row = conn.execute(select(messages).where(messages.c.author == "agent")).mappings().first()+ delivery_scope = conn.execute(+ select(scopes.c.id).where(scopes.c.platform == "slack", scopes.c.native_id == "C_delivery")+ ).scalar_one()+ assert row["scope_id"] == delivery_scope # delivery channel, NOT C_source+ assert row["session_id"] is None # IM rows are scope-keyed, not session-keyed+ assert row["content_text"] == "routed answer"def test_duplicate_native_message_id_is_swallowed(isolated_state):@@ -100,45 +172,121 @@ def test_duplicate_native_message_id_is_swallowed(isolated_state):assert rows[0]["content_text"] == "first"-def test_avibe_platform_is_noop(isolated_state):- avibe_ctx = MessageContext(- user_id="U_alice",- channel_id="avibe-channel",+def test_persist_agent_publishes_inbox_event_for_avibe(isolated_state):+ """An avibe agent ``result`` on a resolved session both persists AND+ publishes ``inbox.session.updated`` on the bus, so the UI bridge can bump+ the card without a refetch. The published row carries the resolved preview.+ """+ from core import inbox_events++ engine = create_sqlite_engine()+ now = "2026-05-30T12:00:00Z"+ with engine.begin() as conn:+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_x", now=now)+ conn.execute(+ agent_sessions.insert().values(+ id="ses_pub",+ scope_id=scope_id,+ agent_backend="claude",+ agent_variant="default",+ session_anchor="anchor_ses_pub",+ native_session_id="",+ title="Published",+ status="active",+ metadata_json="{}",+ created_at=now,+ updated_at=now,+ last_active_at=now,+ )+ )++ ctx = MessageContext(+ user_id="workbench",+ channel_id="ses_pub",platform="avibe",- message_id="avibe_001",+ platform_specific={"agent_session_id": "ses_pub"},)- mirror_inbound(avibe_ctx, "this should not land")- mirror_outbound(avibe_ctx, "neither should this", native_message_id="avibe_002")- engine = create_sqlite_engine()+ async def scenario():+ sub_id, queue = inbox_events.bus.subscribe()+ try:+ persist_agent_message(ctx, "result", "final answer")+ return await asyncio.wait_for(queue.get(), timeout=1.0)+ finally:+ inbox_events.bus.unsubscribe(sub_id)++ event_type, data = asyncio.run(scenario())+ assert event_type == "inbox.session.updated"+ assert data["session_id"] == "ses_pub"+ assert data["preview_text"] == "final answer"+ assert data["title"] == "Published"++ # The row was persisted too (publish is in addition to, not instead of).with engine.connect() as conn:- rows = conn.execute(select(messages)).mappings().all()- assert rows == []+ agent_rows = conn.execute(+ select(messages).where(messages.c.author == "agent", messages.c.session_id == "ses_pub")+ ).mappings().all()+ assert len(agent_rows) == 1 and agent_rows[0]["type"] == "result"-def test_outbound_mirror_uses_delivery_target_scope(isolated_state):- """Regression: dispatcher calls mirror_outbound with ``target_context``,- which may carry a different channel/platform than the inbound ``context``- (e.g. ``post_to`` overrides on scheduled / watch-driven runs). The mirror- must land under the delivery scope, not the source scope.+def test_persist_agent_no_publish_without_result(isolated_state):+ """An intermediate ``assistant`` message persists but must NOT publish an+ inbox event — the session has no ``result`` yet, so it isn't inbox-visible."""- delivery_ctx = MessageContext(- user_id="agent",- channel_id="C_delivery", # different from any inbound channel- platform="slack",- thread_id=None,- message_id=None,+ from core import inbox_events++ engine = create_sqlite_engine()+ now = "2026-05-30T12:00:00Z"+ with engine.begin() as conn:+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_y", now=now)+ conn.execute(+ agent_sessions.insert().values(+ id="ses_noresult",+ scope_id=scope_id,+ agent_backend="claude",+ agent_variant="default",+ session_anchor="anchor_ses_noresult",+ native_session_id="",+ status="active",+ metadata_json="{}",+ created_at=now,+ updated_at=now,+ last_active_at=now,+ )+ )++ ctx = MessageContext(+ user_id="workbench",+ channel_id="ses_noresult",+ platform="avibe",+ platform_specific={"agent_session_id": "ses_noresult"},+ )++ async def scenario():+ sub_id, queue = inbox_events.bus.subscribe()+ try:+ persist_agent_message(ctx, "assistant", "thinking out loud")+ with pytest.raises(asyncio.TimeoutError):+ await asyncio.wait_for(queue.get(), timeout=0.05)+ finally:+ inbox_events.bus.unsubscribe(sub_id)++ asyncio.run(scenario())+++def test_avibe_inbound_is_noop(isolated_state):+ """avibe user messages are written by the workbench REST endpoint, so the+ inbound mirror stays a no-op (agent output is persisted via+ persist_agent_message, which is exercised in the messages_service tests)."""+ avibe_ctx = MessageContext(+ user_id="U_alice",+ channel_id="avibe-channel",+ platform="avibe",+ message_id="avibe_001",)- mirror_outbound(delivery_ctx, "agent reply", native_message_id="slack_out_42", kind="result")+ mirror_inbound(avibe_ctx, "this should not land")engine = create_sqlite_engine()with engine.connect() as conn:- scope_row = conn.execute(- select(scopes).where(scopes.c.platform == "slack", scopes.c.native_id == "C_delivery")- ).mappings().first()- assert scope_row is not None, "outbound scope must be auto-upserted under the delivery target"- rows = conn.execute(select(messages).where(messages.c.platform == "slack")).mappings().all()- assert len(rows) == 1- assert rows[0]["author"] == "agent"- assert rows[0]["content_text"] == "agent reply"- assert rows[0]["scope_id"] == scope_row["id"]+ rows = conn.execute(select(messages).where(messages.c.author == "user")).mappings().all()+ assert rows == []diff --git a/tests/test_messages_service.py b/tests/test_messages_service.pyindex 23d0f8a70..134143f25 100644--- a/tests/test_messages_service.py+++ b/tests/test_messages_service.py@@ -16,7 +16,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))from storage import messages_servicefrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state-from storage.models import agent_sessions, messages+from storage.models import agent_sessions, messages, scopesfrom storage.settings_service import upsert_scope@@ -166,31 +166,151 @@ def test_list_session_messages_cursor_uses_clamped_limit(isolated_state):assert page["next_after_id"] is not None-def test_list_inbox_cursor_uses_clamped_limit(isolated_state):- """Same regression as the per-session pagination, for the Inbox feed."""+def test_list_session_messages_filters_to_user_facing_types(isolated_state):+ """The chat transcript scopes to user-facing types so the intermediate+ assistant / tool_call / notify rows now persisted for avibe stay out of the+ dialogue view (they're the process log, not the conversation)."""engine = create_sqlite_engine()with engine.begin() as conn:scope_id = _seed_scope(conn)- _seed_session(conn, scope_id, "ses_inbox")- for _ in range(201):+ _seed_session(conn, scope_id, "ses_tx")+ # Distinct timestamps so chronological order is deterministic (append's+ # second-resolution now would tie and fall back to random id order).+ _insert_msg(conn, scope_id, "ses_tx", "user", "q", "2026-05-30T10:00:00Z", msg_type="user")+ _insert_msg(conn, scope_id, "ses_tx", "agent", "thinking", "2026-05-30T10:00:01Z", msg_type="assistant")+ _insert_msg(conn, scope_id, "ses_tx", "agent", "ran tool", "2026-05-30T10:00:02Z", msg_type="tool_call")+ _insert_msg(conn, scope_id, "ses_tx", "agent", "progress", "2026-05-30T10:00:03Z", msg_type="notify")+ _insert_msg(conn, scope_id, "ses_tx", "agent", "final", "2026-05-30T10:00:04Z", msg_type="result")++ with engine.connect() as conn:+ every = messages_service.list_session_messages(conn, session_id="ses_tx")+ dialogue = messages_service.list_session_messages(+ conn, session_id="ses_tx", types=("user", "result")+ )++ assert [m["type"] for m in every["messages"]] == ["user", "assistant", "tool_call", "notify", "result"]+ assert [m["text"] for m in dialogue["messages"]] == ["q", "final"]+++def test_same_second_messages_order_by_insertion(isolated_state):+ """Rows sharing a (second-resolution) created_at still order by insertion in+ the transcript: the monotonic message id breaks the ``(created_at, id)`` tie,+ so a fast avibe turn never renders the agent result before the user prompt+ (nor lets the inbox pick the wrong 'last' row)."""+ engine = create_sqlite_engine()+ fixed = "2026-05-30T12:00:00Z"+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ _seed_session(conn, scope_id, "ses_fast")+ # Identical created_at for both rows; ids come from _new_message_id() in+ # insertion order (the DB round-trip between calls separates microseconds).+ for author, mtype, text in (("user", "user", "prompt"), ("agent", "result", "answer")):+ conn.execute(+ messages.insert().values(+ id=messages_service._new_message_id(),+ scope_id=scope_id,+ session_id="ses_fast",+ platform="avibe",+ author=author,+ type=mtype,+ content_text=text,+ content_json="{}",+ metadata_json="{}",+ created_at=fixed,+ updated_at=fixed,+ read_at=None,+ )+ )++ with engine.connect() as conn:+ page = messages_service.list_session_messages(conn, session_id="ses_fast")+ assert [m["text"] for m in page["messages"]] == ["prompt", "answer"]+++def test_list_session_messages_keeps_show_page_marks(isolated_state):+ """Show-Page transcript marks (author='agent' → type='assistant', but+ metadata.source='show_page') stay visible in the chat transcript even though+ plain intermediate 'assistant' process rows are filtered out."""+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ _seed_session(conn, scope_id, "ses_mark")+ messages_service.append(+ conn, scope_id=scope_id, session_id="ses_mark", platform="avibe", author="user", text="q"+ )+ # Avibe intermediate assistant (process log) — must be hidden.+ messages_service.append(+ conn, scope_id=scope_id, session_id="ses_mark", platform="avibe",+ author="agent", message_type="assistant", text="thinking",+ )+ # Show-page assistant mark — must stay visible via metadata.source.+ messages_service.append(+ conn, scope_id=scope_id, session_id="ses_mark", platform="avibe",+ author="agent", text="annotation", metadata={"source": "show_page"},+ )+ messages_service.append(+ conn, scope_id=scope_id, session_id="ses_mark", platform="avibe",+ author="agent", message_type="result", text="final",+ )++ with engine.connect() as conn:+ page = messages_service.list_session_messages(+ conn, session_id="ses_mark", types=("user", "result"), include_metadata_sources=("show_page",)+ )+ texts = [m["text"] for m in page["messages"]]+ assert texts == ["q", "annotation", "final"] # 'thinking' (plain assistant) filtered out+++def test_transcript_keeps_notify_terminal_marker(isolated_state):+ """The chat transcript keeps a terminal ``notify`` (e.g. an agent run that+ failed and stopped without a result) while still hiding the intermediate+ assistant / tool_call process rows."""+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ _seed_session(conn, scope_id, "ses_n")+ for author, mtype, text in (+ ("user", "user", "go"),+ ("agent", "assistant", "thinking"),+ ("agent", "tool_call", "ran tool"),+ ("agent", "notify", "Agent run failed and stopped."),+ ):messages_service.append(- conn,- scope_id=scope_id,- session_id="ses_inbox",- platform="avibe",- author="agent",- text="ping",+ conn, scope_id=scope_id, session_id="ses_n", platform="avibe",+ author=author, message_type=mtype, text=text,)with engine.connect() as conn:- page = messages_service.list_inbox(conn, platform="avibe", limit=1000)- assert len(page["messages"]) == 200- assert page["next_before_id"] is not None+ page = messages_service.list_session_messages(+ conn, session_id="ses_n", types=("user", "result", "notify"), include_metadata_sources=("show_page",)+ )+ texts = [m["text"] for m in page["messages"]]+ assert texts == ["go", "Agent run failed and stopped."] # notify kept; assistant/tool_call hidden+++def test_append_defaults_type_from_author(isolated_state):+ """Callers that omit message_type (e.g. show-page transcript annotations)+ get a type derived from author — a human row must be 'user' so the+ user+result transcript filter keeps it, not mis-typed 'assistant'."""+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ _seed_session(conn, scope_id, "ses_def")+ user_row = messages_service.append(+ conn, scope_id=scope_id, session_id="ses_def", platform="avibe", author="user", text="hi"+ )+ agent_row = messages_service.append(+ conn, scope_id=scope_id, session_id="ses_def", platform="avibe", author="agent", text="yo"+ )+ assert user_row["type"] == "user"+ assert agent_row["type"] == "assistant"def test_unread_counts_by_session_splits_within_a_scope(isolated_state):- """Two sessions in one project must report distinct per-session unread- counts, even though the scope-level aggregate lumps them together."""+ """Two sessions in one project report distinct per-session unread counts,+ counting unread agent *result* messages only. Intermediate assistant /+ tool_call rows (persisted for avibe but not user-facing) must NOT inflate+ the badge past what the inbox card shows."""engine = create_sqlite_engine()with engine.begin() as conn:scope_id = _seed_scope(conn)@@ -198,14 +318,26 @@ def test_unread_counts_by_session_splits_within_a_scope(isolated_state):_seed_session(conn, scope_id, "ses_b")for _ in range(2):messages_service.append(- conn, scope_id=scope_id, session_id="ses_a", platform="avibe", author="agent", text="a"+ conn, scope_id=scope_id, session_id="ses_a", platform="avibe",+ author="agent", message_type="result", text="a",)messages_service.append(- conn, scope_id=scope_id, session_id="ses_b", platform="avibe", author="agent", text="b"+ conn, scope_id=scope_id, session_id="ses_b", platform="avibe",+ author="agent", message_type="result", text="b",+ )+ # An unread assistant + tool_call (intermediate) and a user message+ # must NOT count toward the unread badge.+ messages_service.append(+ conn, scope_id=scope_id, session_id="ses_b", platform="avibe",+ author="agent", message_type="assistant", text="thinking",)- # A user message and a read agent message must not count.messages_service.append(- conn, scope_id=scope_id, session_id="ses_b", platform="avibe", author="user", text="hi"+ conn, scope_id=scope_id, session_id="ses_b", platform="avibe",+ author="agent", message_type="tool_call", text="ran tool",+ )+ messages_service.append(+ conn, scope_id=scope_id, session_id="ses_b", platform="avibe",+ author="user", message_type="user", text="hi",)with engine.connect() as conn:@@ -213,5 +345,125 @@ def test_unread_counts_by_session_splits_within_a_scope(isolated_state):by_scope = messages_service.unread_counts(conn, platform="avibe")assert by_session == {"ses_a": 2, "ses_b": 1}- # Scope aggregate still lumps both sessions together.+ # Scope aggregate still lumps both sessions together (result-only).assert by_scope == {scope_id: 3}+++def _seed_titled_session(conn, scope_id: str, session_id: str, title: str) -> None:+ now = messages_service._utc_now_iso()+ conn.execute(+ agent_sessions.insert().values(+ id=session_id,+ scope_id=scope_id,+ agent_backend="claude",+ agent_variant="default",+ session_anchor="anchor_" + session_id,+ native_session_id="",+ title=title,+ status="active",+ metadata_json="{}",+ created_at=now,+ updated_at=now,+ last_active_at=now,+ )+ )+++def _insert_msg(conn, scope_id, session_id, author, text, created_at, *, read=True, msg_type=None):+ """Direct insert so the test controls created_at (second-resolution) + read_at.++ Agent rows default to type='result' (the user-facing reply the inbox+ previews); pass ``msg_type`` to insert an intermediate type (assistant /+ tool_call) that must NOT drive the inbox preview.+ """+ resolved_type = msg_type or ("user" if author == "user" else "result")+ conn.execute(+ messages.insert().values(+ id=f"msg_{session_id}_{created_at[-9:]}_{author}_{resolved_type}",+ scope_id=scope_id,+ session_id=session_id,+ platform="avibe",+ author=author,+ type=resolved_type,+ content_text=text,+ content_json="{}",+ metadata_json="{}",+ created_at=created_at,+ updated_at=created_at,+ read_at=created_at if (read and author == "agent") else None,+ )+ )+++def test_list_inbox_sessions_per_session_feed(isolated_state):+ """One card per session, sorted by last activity (any author) desc, preview =+ latest agent reply, replied = last message is the user's, with unread counts."""+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ conn.execute(scopes.update().where(scopes.c.id == scope_id).values(display_name="My Project"))+ _seed_titled_session(conn, scope_id, "ses_a", "Alpha")+ _seed_titled_session(conn, scope_id, "ses_b", "Beta")+ _seed_titled_session(conn, scope_id, "ses_c", "Gamma")+ # ses_a: agent reply (read), then the user replied last → replied, no unread.+ _insert_msg(conn, scope_id, "ses_a", "agent", "A1", "2026-05-30T10:00:00Z")+ _insert_msg(conn, scope_id, "ses_a", "user", "AU", "2026-05-30T10:05:00Z")+ # ses_b: two result replies, the second unread → most recent activity, unread=1.+ _insert_msg(conn, scope_id, "ses_b", "agent", "B1", "2026-05-30T10:01:00Z")+ _insert_msg(conn, scope_id, "ses_b", "agent", "B2", "2026-05-30T10:10:00Z", read=False)+ # An intermediate assistant message arrives LAST — it must bump the+ # activity clock (sort key) but NOT become the preview (preview = result).+ _insert_msg(+ conn, scope_id, "ses_b", "agent", "thinking…", "2026-05-30T10:11:00Z",+ read=False, msg_type="assistant",+ )+ # ses_c: only a user message, no agent reply → excluded from the feed.+ _insert_msg(conn, scope_id, "ses_c", "user", "CU", "2026-05-30T10:20:00Z")++ with engine.connect() as conn:+ feed = messages_service.list_inbox_sessions(conn, platform="avibe")++ rows = feed["sessions"]+ # ses_c excluded (no agent reply); ses_b before ses_a (10:10 > 10:05).+ assert [r["session_id"] for r in rows] == ["ses_b", "ses_a"]++ b, a = rows[0], rows[1]+ assert b["title"] == "Beta" and b["project_name"] == "My Project" and b["project_id"] == "proj_test"+ assert b["preview_text"] == "B2" and b["unread_count"] == 1 and b["unread"] is True+ assert b["replied"] is False # last message is the agent's+ # ses_a: preview is the latest AGENT reply (A1), not the user's last message.+ assert a["preview_text"] == "A1" and a["unread_count"] == 0+ assert a["replied"] is True # last message is the user's++ # Unread filter drops the fully-read ses_a.+ with engine.connect() as conn:+ unread_feed = messages_service.list_inbox_sessions(conn, platform="avibe", unread_only=True)+ assert [r["session_id"] for r in unread_feed["sessions"]] == ["ses_b"]++ # The sidebar badge map agrees with the feed cards' result-only unread_count+ # — the unread intermediate 'thinking' assistant row at 10:11 must NOT make+ # the two sources disagree (1 vs 2).+ with engine.connect() as conn:+ by_session = messages_service.unread_counts_by_session(conn, platform="avibe")+ assert by_session == {"ses_b": 1}+ assert b["unread_count"] == by_session["ses_b"]+++def test_list_inbox_sessions_pagination(isolated_state):+ """Keyset 'load more' walks sessions in last-activity order."""+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ for i in range(3):+ sid = f"ses_{i}"+ _seed_titled_session(conn, scope_id, sid, f"S{i}")+ _insert_msg(conn, scope_id, sid, "agent", f"reply {i}", f"2026-05-30T1{i}:00:00Z")++ with engine.connect() as conn:+ page1 = messages_service.list_inbox_sessions(conn, platform="avibe", limit=2)+ assert [r["session_id"] for r in page1["sessions"]] == ["ses_2", "ses_1"]+ assert page1["next_cursor"]+ page2 = messages_service.list_inbox_sessions(+ conn, platform="avibe", limit=2, before=page1["next_cursor"]+ )+ assert [r["session_id"] for r in page2["sessions"]] == ["ses_0"]diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.pyindex 2e6a922bc..97e798cf2 100644--- a/tests/test_sqlite_state_migration.py+++ b/tests/test_sqlite_state_migration.py@@ -16,7 +16,7 @@ from storage.models import metadatafrom storage.settings_service import SQLiteSettingsService-HEAD_REVISION = "20260530_0009"+HEAD_REVISION = "20260531_0009"def test_run_migrations_creates_initial_schema(tmp_path: Path) -> None:@@ -280,6 +280,36 @@ def test_run_migrations_repairs_head_columns_before_stamping_head(tmp_path: Pathassert background_tables_ready(db_path) is True+def test_background_tables_ready_requires_messages_type(tmp_path: Path) -> None:+ """A DB at the prior (20260530_0009) head — full tables but no messages.type —+ must report NOT ready so SQLiteBackgroundTaskStore triggers the migration;+ otherwise messages_service.append would write a column that doesn't exist."""+ db_path = tmp_path / "vibe.sqlite"+ engine = create_sqlite_engine(db_path)+ try:+ metadata.create_all(engine)+ finally:+ engine.dispose()++ with sqlite3.connect(db_path) as conn:+ conn.execute('alter table "messages" drop column "type"')+ conn.execute("create table if not exists alembic_version (version_num varchar(32) not null)")+ conn.execute("delete from alembic_version")+ conn.execute("insert into alembic_version values ('20260530_0009')")+ conn.commit()++ assert background_tables_ready(db_path) is False++ run_migrations(db_path)++ with sqlite3.connect(db_path) as conn:+ columns = {row[1] for row in conn.execute("pragma table_info(messages)")}+ version = conn.execute("select version_num from alembic_version").fetchone()+ assert "type" in columns+ assert version == (HEAD_REVISION,)+ assert background_tables_ready(db_path) is True++def test_run_migrations_repairs_head_stamped_background_schema_drift(tmp_path: Path) -> None:db_path = tmp_path / "vibe.sqlite"engine = create_sqlite_engine(db_path)diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex c75c0d57a..5ada70b6f 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -7,6 +7,7 @@ import clsx from 'clsx';import { Info } from 'lucide-react';import { useApi } from '../../context/ApiContext';+import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';import type { VibeAgentBrief, WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';import { apiFetch } from '../../lib/apiFetch';import { Badge } from '../ui/badge';@@ -33,6 +34,7 @@ export const ChatPage: React.FC = () => {const navigate = useNavigate();const location = useLocation();const api = useApi();+ const { unreadBySession, markRead: markInboxRead } = useWorkbenchInbox();const [session, setSession] = useState<WorkbenchSession | null>(null);const [agents, setAgents] = useState<VibeAgentBrief[]>([]);const [messages, setMessages] = useState<WorkbenchMessage[]>([]);@@ -60,6 +62,11 @@ export const ChatPage: React.FC = () => {setSession(fetched);setAgents(agentList.agents);setMessages(msgs.messages);+ // The agent result is now persisted, so the reloaded transcript already+ // contains it — drop the optimistic stream chunks in the same render to+ // avoid showing the reply twice (persisted row + leftover chunk). Batched+ // with setMessages so there's no duplicate/absence flash.+ setStreamChunks([]);} catch (err: any) {setError(err?.message ?? String(err));} finally {@@ -175,6 +182,17 @@ export const ChatPage: React.FC = () => {refresh();}, [refresh]);+ // The user is actively viewing this session, so an agent reply here is seen,+ // not "new". Clear unread whenever it appears — on open, or when a realtime+ // inbox.session.updated lands after a streamed turn — so the Inbox/sidebar+ // never badge the chat you're looking at. Reactive to the unread map, so it's+ // race-free against the cross-process event ordering.+ useEffect(() => {+ if (sessionId && (unreadBySession[sessionId] ?? 0) > 0) {+ void markInboxRead(sessionId);+ }+ }, [sessionId, unreadBySession, markInboxRead]);+// The Workbench canvas creates the session and hands its first message// over as router state. Replay it once through the streaming compose path// so the agent turn actually starts. Clear the state afterwards so a manual@@ -633,13 +651,20 @@ const StreamingChunks: React.FC<{ chunks: PendingChunk[]; session: WorkbenchSess};const MessageRow: React.FC<{ message: WorkbenchMessage; session: WorkbenchSession }> = ({ message, session }) => {- const isAgent = message.author === 'agent';- const isSystem = message.author === 'system';+ const { t } = useTranslation();+ // A notify row is a turn-terminal marker (e.g. an agent run that failed and+ // stopped without a result). Render it distinctly from an agent reply — gold+ // box, "Notify" identifier — so the user reads it as a status, not an answer.+ const isNotify = message.type === 'notify';+ const isAgent = !isNotify && message.author === 'agent';+ const isSystem = !isNotify && message.author === 'system';return (<divclassName={clsx('flex flex-col gap-1 rounded-xl border px-4 py-3',- isAgent+ isNotify+ ? 'border-gold/30 bg-gold/[0.06]'+ : isAgent? 'border-mint/20 bg-mint/[0.04]': isSystem? 'border-border bg-foreground/[0.02]'@@ -650,12 +675,16 @@ const MessageRow: React.FC<{ message: WorkbenchMessage; session: WorkbenchSessio<spanclassName={clsx('rounded border px-1.5 py-0 font-mono font-bold uppercase',- isAgent ? 'border-mint/40 bg-mint/[0.10] text-mint' : 'border-border-strong bg-foreground/[0.04] text-muted',+ isNotify+ ? 'border-gold/40 bg-gold/10 text-gold'+ : isAgent+ ? 'border-mint/40 bg-mint/[0.10] text-mint'+ : 'border-border-strong bg-foreground/[0.04] text-muted',)}>- {message.author}+ {isNotify ? t('chat.notifyLabel') : message.author}</span>- {message.author_name && <span className="font-semibold text-foreground">{message.author_name}</span>}+ {!isNotify && message.author_name && <span className="font-semibold text-foreground">{message.author_name}</span>}{isAgent && session.agent_name && <span className="font-mono text-muted">{session.agent_name}</span>}<span className="ml-auto font-mono text-muted">{message.created_at}</span></div>diff --git a/ui/src/components/workbench/InboxPage.tsx b/ui/src/components/workbench/InboxPage.tsxindex d5d316cd6..2b2028ee6 100644--- a/ui/src/components/workbench/InboxPage.tsx+++ b/ui/src/components/workbench/InboxPage.tsx@@ -1,11 +1,11 @@import { useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { useNavigate } from 'react-router-dom';-import { ArrowRight, CheckCheck, Filter, Inbox, MessageSquareReply, RefreshCw } from 'lucide-react';+import { ArrowRight, CheckCheck, Filter, Inbox, Loader2, MessageSquareReply, RefreshCw } from 'lucide-react';import clsx from 'clsx';import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';-import type { WorkbenchMessage } from '../../context/ApiContext';+import type { InboxSession } from '../../context/ApiContext';import { formatRelativeTime } from '../../lib/relativeTime';type FilterMode = 'unread' | 'all';@@ -13,33 +13,53 @@ type FilterMode = 'unread' | 'all';export const InboxPage: React.FC = () => {const { t } = useTranslation();const navigate = useNavigate();- const { recentMessages, totalUnread, refresh, markRead, loading } = useWorkbenchInbox();+ const {+ inboxSessions,+ unreadBySession,+ totalUnread,+ unreadSessions,+ nextCursor,+ loading,+ loadingMore,+ refresh,+ loadMore,+ markRead,+ } = useWorkbenchInbox();const [filter, setFilter] = useState<FilterMode>('unread');+ // The unread map is the single source of truth (loaded pagination-independent+ // and kept in sync by realtime upserts + mark-read). A session drops out of+ // the map once its count hits zero, so a missing key means 0 — never fall+ // back to the card's own (now stale) unread_count, or a marked-read session+ // would stay badged / stuck in the Unread tab.+ const unreadOf = (s: InboxSession) => unreadBySession[s.session_id] ?? 0;+const visible = useMemo(() => {- if (filter === 'all') return recentMessages;- return recentMessages.filter((m) => m.author === 'agent' && !m.read_at);- }, [filter, recentMessages]);+ if (filter === 'all') return inboxSessions;+ return inboxSessions.filter((s) => unreadOf(s) > 0);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [filter, inboxSessions, unreadBySession]);- const onRowOpen = (message: WorkbenchMessage) => {- if (message.session_id && !message.read_at) {- markRead(message.session_id);- }- if (message.session_id) {- navigate(`/chat/${encodeURIComponent(message.session_id)}`);- }+ const openSession = (s: InboxSession) => {+ if (unreadOf(s) > 0) markRead(s.session_id);+ navigate(`/chat/${encodeURIComponent(s.session_id)}`);};const onMarkAllRead = async () => {- const sessionsToMark = new Set<string>();- for (const m of recentMessages) {- if (m.author === 'agent' && !m.read_at && m.session_id) {- sessionsToMark.add(m.session_id);- }- }- await Promise.all(Array.from(sessionsToMark).map((id) => markRead(id)));+ const ids = Object.entries(unreadBySession)+ .filter(([, n]) => (n || 0) > 0)+ .map(([id]) => id);+ await Promise.all(ids.map((id) => markRead(id)));};+ const hasMore = !!nextCursor;+ // Only declare "all clear" when nothing is visible AND nothing left to load+ // could match. On the Unread tab that means no unread sessions exist anywhere+ // (unreadSessions is pagination-independent) — otherwise unread sessions on a+ // later page would be hidden behind a false "all caught up". On All it means+ // there are simply no more pages.+ const showEmpty = visible.length === 0 && (filter === 'unread' ? unreadSessions === 0 : !hasMore);+return (<div className="mx-auto flex w-full max-w-4xl flex-col gap-6 py-2">{/* Header */}@@ -53,7 +73,7 @@ export const InboxPage: React.FC = () => {</div><h1 className="text-2xl font-bold text-foreground">{t('workbench.inbox.title')}</h1><p className="text-[13px] text-muted">- {t('workbench.inbox.headerCount', { unread: totalUnread, total: recentMessages.length })}+ {t('workbench.inbox.headerCount', { unread: unreadSessions, total: inboxSessions.length })}</p></div><button@@ -113,7 +133,7 @@ export const InboxPage: React.FC = () => {</div>{/* Empty state */}- {visible.length === 0 ? (+ {showEmpty ? (<div className="flex flex-col items-center gap-3 rounded-2xl border border-dashed border-border bg-surface px-6 py-16 text-center"><CheckCheck className="size-8 text-mint" /><div className="text-[15px] font-semibold text-foreground">@@ -125,78 +145,103 @@ export const InboxPage: React.FC = () => {</div>) : (<div className="flex flex-col gap-3">- {visible.map((m) => {- const unread = m.author === 'agent' && !m.read_at;- const projectId = m.scope_id ? m.scope_id.split('::').pop() : null;- const sessionLabel = (m.metadata?.session_title as string | undefined) || m.session_id || '—';+ {/* Unread tab, current pages hold no unread but more exist further+ down — prompt to load instead of rendering nothing. */}+ {visible.length === 0 && (+ <div className="rounded-xl border border-dashed border-border bg-surface px-4 py-6 text-center text-[12.5px] text-muted">+ {t('workbench.inbox.moreUnreadBeyond')}+ </div>+ )}+ {visible.map((s) => {+ const unread = unreadOf(s);+ const projectLabel = s.project_name || s.project_id || 'avibe';+ const sessionLabel = s.title?.trim() || s.session_id;return (<article- key={m.id}+ key={s.session_id}className={clsx('flex flex-col gap-3 rounded-xl border p-4 transition',- unread+ unread > 0? 'border-mint/30 bg-mint/[0.05] shadow-[0_0_24px_-12px_rgba(91,255,160,0.4)]': 'border-border bg-surface',)}><div className="flex items-center gap-2 text-[11px]">- <span className="inline-flex items-center gap-1 rounded-md border border-border-strong bg-surface-2 px-2 py-0.5 font-mono font-semibold text-cyan">- {projectId || 'avibe'}+ <span className="inline-flex max-w-[40%] items-center gap-1 truncate rounded-md border border-border-strong bg-surface-2 px-2 py-0.5 font-semibold text-cyan">+ {projectLabel}</span><span className="text-muted">·</span><span className="flex-1 truncate text-[13px] font-semibold text-foreground">{sessionLabel}</span>- <span className="font-mono text-muted">{formatRelativeTime(m.created_at, t)}</span>+ {s.replied && (+ <span className="inline-flex items-center gap-1 rounded-md border border-cyan/30 bg-cyan/[0.08] px-1.5 py-0.5 text-[10px] font-semibold text-cyan">+ <MessageSquareReply className="size-2.5" />+ {t('workbench.inbox.replied')}+ </span>+ )}+ <span className="shrink-0 font-mono text-muted">{formatRelativeTime(s.last_activity_at, t)}</span></div><div className="flex flex-col gap-1">- <div className="flex items-center gap-2 text-[10px]">- <span className={clsx('font-bold uppercase tracking-wider', m.author === 'agent' ? 'text-mint' : 'text-cyan')}>- {m.author === 'agent' ? t('workbench.inbox.agent') : t('workbench.inbox.you')}- </span>+ <div className="text-[10px] font-bold uppercase tracking-wider text-mint">+ {t('workbench.inbox.agent')}</div>- <p className={clsx('text-[13px] leading-relaxed', unread ? 'text-foreground' : 'text-muted')}>- {m.text || '—'}+ <p className={clsx('line-clamp-3 text-[13px] leading-relaxed', unread > 0 ? 'text-foreground' : 'text-muted')}>+ {s.preview_text || '—'}</p></div><div className="flex items-center gap-2"><buttontype="button"- onClick={() => onRowOpen(m)}+ onClick={() => openSession(s)}className="inline-flex items-center gap-1.5 rounded-md border border-mint/30 bg-mint/[0.06] px-3 py-1.5 text-[11px] font-semibold text-mint transition hover:bg-mint/[0.12]">{t('workbench.inbox.openSession')}<ArrowRight className="size-3" /></button>- {unread && (- <button- type="button"- onClick={() => m.session_id && markRead(m.session_id)}- className="inline-flex items-center gap-1.5 rounded-md border border-border-strong px-3 py-1.5 text-[11px] font-medium text-foreground transition hover:bg-foreground/[0.04]"- >- <MessageSquareReply className="size-3" />- {t('workbench.inbox.markRead')}- </button>+ {unread > 0 && (+ <>+ <span className="inline-flex min-w-[1.1rem] items-center justify-center rounded-full bg-mint px-1.5 font-mono text-[9px] font-bold text-[#080812]">+ {unread > 99 ? '99+' : unread}+ </span>+ <button+ type="button"+ onClick={() => markRead(s.session_id)}+ className="inline-flex items-center gap-1.5 rounded-md border border-border-strong px-3 py-1.5 text-[11px] font-medium text-foreground transition hover:bg-foreground/[0.04]"+ >+ <CheckCheck className="size-3" />+ {t('workbench.inbox.markRead')}+ </button>+ </>)}</div></article>);})}- </div>- )}- {/* Footer placeholder — pagination via before_id arrives once the- inbox accrues real volume. */}- {visible.length > 0 && (- <button- type="button"- onClick={() => navigate('/')}- className="self-center text-[11px] text-muted hover:text-foreground"- >- {t('workbench.inbox.backToCanvas')}- </button>+ {/* Load more walks the full feed by activity; the active tab then+ re-derives ``visible``. Shown on both tabs (and even when the+ Unread tab's current page is empty) so unread sessions deeper in+ history stay reachable. */}+ {hasMore && (+ <button+ type="button"+ onClick={() => loadMore()}+ disabled={loadingMore}+ className={clsx(+ 'flex items-center justify-center gap-1.5 self-center rounded-md border px-4 py-2 text-[12px] font-medium transition',+ loadingMore+ ? 'cursor-wait border-border bg-foreground/[0.02] text-muted'+ : 'border-border-strong text-foreground hover:bg-foreground/[0.04]',+ )}+ >+ {loadingMore && <Loader2 className="size-3.5 animate-spin" />}+ {t('workbench.inbox.loadMore')}+ </button>+ )}+ </div>)}</div>);diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsxindex ddf4690da..e4a9f4aa7 100644--- a/ui/src/components/workbench/WorkbenchSidebar.tsx+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx@@ -24,7 +24,7 @@ import type { LucideIcon } from 'lucide-react';import { useApi } from '../../context/ApiContext';import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';-import type { WorkbenchMessage, WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';+import type { InboxSession, WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';import { formatRelativeTime } from '../../lib/relativeTime';import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';import { Input } from '../ui/input';@@ -44,22 +44,36 @@ const CAPABILITY_NAV: CapabilityNavItem[] = [];// 360px floating popover that opens when the user hovers the Inbox entry.-// Mirrors design.pen KmQ1L — header + a few rows + footer "open full inbox"-// link. Pure presentational; data comes from <WorkbenchInboxProvider>.+// Mirrors design.pen KmQ1L — header + a few session cards + footer "open full+// inbox" link. Pure presentational; data comes from <WorkbenchInboxProvider>.const InboxHoverPopover: React.FC<{visible: boolean;- messages: WorkbenchMessage[];+ sessions: InboxSession[];+ unreadBySession: Record<string, number>;+ unreadSessions: number;totalUnread: number;- onItemClick: (message: WorkbenchMessage) => void;+ onItemClick: (session: InboxSession) => void;onMarkAllRead: () => void;onMouseEnter: () => void;onMouseLeave: () => void;-}> = ({ visible, messages, totalUnread, onItemClick, onMarkAllRead, onMouseEnter, onMouseLeave }) => {+}> = ({+ visible,+ sessions,+ unreadBySession,+ unreadSessions,+ totalUnread,+ onItemClick,+ onMarkAllRead,+ onMouseEnter,+ onMouseLeave,+}) => {const { t } = useTranslation();const navigate = useNavigate();if (!visible) return null;- const shown = messages.slice(0, 5);- const isUnread = (m: WorkbenchMessage) => m.author === 'agent' && !m.read_at;+ const shown = sessions.slice(0, 5);+ // The unread map is authoritative; a session absent from it has 0 unread+ // (don't fall back to the card's stale unread_count — see InboxPage).+ const unreadOf = (s: InboxSession) => unreadBySession[s.session_id] ?? 0;return (<divrole="dialog"@@ -72,7 +86,7 @@ const InboxHoverPopover: React.FC<{<div className="flex flex-1 flex-col"><div className="text-[13px] font-bold text-foreground">{t('workbench.inbox.title')}</div><div className="text-[10px] text-muted">- {t('workbench.inbox.headerCount', { unread: totalUnread, total: messages.length })}+ {t('workbench.inbox.headerCount', { unread: unreadSessions, total: sessions.length })}</div></div><button@@ -96,38 +110,41 @@ const InboxHoverPopover: React.FC<{</div>) : (<div className="flex flex-col gap-1">- {shown.map((m) => {- const unread = isUnread(m);- const projectId = m.scope_id ? m.scope_id.split('::').pop() : null;+ {shown.map((s) => {+ const unread = unreadOf(s);+ const projectLabel = s.project_name || s.project_id || 'avibe';return (<button- key={m.id}+ key={s.session_id}type="button"- onClick={() => onItemClick(m)}+ onClick={() => onItemClick(s)}className={clsx('flex flex-col gap-1.5 rounded-lg px-3 py-2.5 text-left transition',- unread+ unread > 0? 'border-l-2 border-mint bg-mint/[0.06] hover:bg-mint/[0.10]': 'hover:bg-foreground/[0.04]',)}><div className="flex items-center gap-1.5 text-[10px]">- <span className="truncate font-mono font-semibold text-cyan">{projectId || 'avibe'}</span>+ <span className="truncate font-semibold text-cyan">{projectLabel}</span><span className="text-muted">·</span><span className="flex-1 truncate font-semibold text-foreground">- {m.metadata?.session_title as string | undefined || m.session_id}- </span>- <span className="font-mono text-muted">- {formatRelativeTime(m.created_at, t)}+ {s.title?.trim() || s.session_id}</span>+ {s.replied && (+ <span className="shrink-0 font-semibold text-cyan" title={t('workbench.inbox.replied')}>+ ↩+ </span>+ )}+ <span className="font-mono text-muted">{formatRelativeTime(s.last_activity_at, t)}</span></div><divclassName={clsx('line-clamp-2 text-[11.5px] leading-relaxed',- unread ? 'text-foreground' : 'text-muted',+ unread > 0 ? 'text-foreground' : 'text-muted',)}>- {m.text || '—'}+ {s.preview_text || '—'}</div></button>);@@ -366,7 +383,7 @@ export const WorkbenchSidebar: React.FC = () => {const { t } = useTranslation();const api = useApi();const navigate = useNavigate();- const { totalUnread, recentMessages, markRead, unreadBySession } = useWorkbenchInbox();+ const { totalUnread, unreadSessions, inboxSessions, markRead, unreadBySession } = useWorkbenchInbox();const [popoverOpen, setPopoverOpen] = useState(false);const closeTimer = useRef<number | null>(null);@@ -572,27 +589,19 @@ export const WorkbenchSidebar: React.FC = () => {};}, []);- const onItemClick = (message: WorkbenchMessage) => {+ const onItemClick = (session: InboxSession) => {setPopoverOpen(false);- if (message.session_id) {- navigate(`/chat/${encodeURIComponent(message.session_id)}`);- if (!message.read_at) markRead(message.session_id);- } else {- navigate('/inbox');- }+ navigate(`/chat/${encodeURIComponent(session.session_id)}`);+ if ((unreadBySession[session.session_id] ?? 0) > 0) markRead(session.session_id);};const onMarkAllRead = async () => {- // Mark every session with at least one unread agent message as read.- // Cheaper than a dedicated endpoint for now since we already know the- // candidate session ids from recentMessages.- const sessionsToMark = new Set<string>();- for (const m of recentMessages) {- if (m.author === 'agent' && !m.read_at && m.session_id) {- sessionsToMark.add(m.session_id);- }- }- await Promise.all(Array.from(sessionsToMark).map((id) => markRead(id)));+ // Mark every session that still has unread agent replies. The unread map is+ // pagination-independent, so this clears sessions beyond the first page too.+ const ids = Object.entries(unreadBySession)+ .filter(([, n]) => (n || 0) > 0)+ .map(([id]) => id);+ await Promise.all(ids.map((id) => markRead(id)));};const badge = useMemo(() => {@@ -636,7 +645,9 @@ export const WorkbenchSidebar: React.FC = () => {</NavLink><InboxHoverPopovervisible={popoverOpen}- messages={recentMessages}+ sessions={inboxSessions}+ unreadBySession={unreadBySession}+ unreadSessions={unreadSessions}totalUnread={totalUnread}onItemClick={onItemClick}onMarkAllRead={onMarkAllRead}diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 6bde33709..e4ee0f535 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -105,7 +105,7 @@ export type ApiContextType = {sendSessionMessage: (sessionId: string, payload: { text?: string; content?: Record<string, unknown>; metadata?: Record<string, unknown>; author_id?: string; author_name?: string }) => Promise<WorkbenchMessage>;markSessionRead: (sessionId: string, untilMessageId?: string) => Promise<{ updated: number; unread_counts: Record<string, number>; unread_by_session: Record<string, number> }>;cancelSession: (sessionId: string) => Promise<{ ok: boolean; status?: string; code?: string; detail?: string }>;- listInbox: (params?: { platform?: string; unreadOnly?: boolean; limit?: number; beforeId?: string }) => Promise<{ messages: WorkbenchMessage[]; next_before_id: string | null; unread_counts: Record<string, number>; unread_by_session: Record<string, number> }>;+ listInbox: (params?: { platform?: string; unreadOnly?: boolean; limit?: number; before?: string }) => Promise<InboxFeedResult>;connectWorkbenchEvents: (handlers: WorkbenchEventHandlers) => () => void;listVibeAgents: (params?: { backend?: string; includeDisabled?: boolean }) => Promise<{ ok: boolean; agents: VibeAgentBrief[]; default_agent_name: string | null }>;getVibeAgent: (name: string) => Promise<{ ok: boolean; agent: VibeAgentFull; default_agent_name: string | null }>;@@ -344,6 +344,10 @@ export type WorkbenchEventHandlers = {unread_counts: Record<string, number>;unread_by_session?: Record<string, number>;}) => void;+ // A session's inbox card changed — new agent reply, or the user replied.+ // Carries the recomputed per-session row so consumers upsert + re-sort in+ // place without a refetch (the realtime "bump to top" signal).+ onInboxSessionUpdated?: (data: InboxSession) => void;onAny?: (event: WorkbenchEventEnvelope) => void;onError?: (err: Event) => void;};@@ -355,6 +359,10 @@ export type WorkbenchMessage = {session_id: string | null;platform: string;author: 'user' | 'agent' | 'system' | string;+ // First-class message type: 'user' | 'assistant' | 'tool_call' | 'notify' |+ // 'result'. Distinct from the coarse author — the chat renders 'notify' as a+ // terminal status marker, and the inbox previews 'result' only.+ type: 'user' | 'assistant' | 'tool_call' | 'notify' | 'result' | string;author_id: string | null;author_name: string | null;native_message_id: string | null;@@ -368,6 +376,34 @@ export type WorkbenchMessage = {read_at: string | null;};+// One row of the per-session ("Slack-like") inbox feed from ``GET /api/inbox``.+// Aggregated per session at query time: ``preview_text`` is the session's latest+// agent ``result`` (aligned with the avibe chat, which only shows results),+// ``last_activity_at`` is the most recent message of *any* author (the sort+// key), and ``replied`` is true when that most recent message is the user's.+export type InboxSession = {+ session_id: string;+ scope_id: string | null;+ project_id: string | null;+ project_name: string | null;+ title: string | null;+ last_activity_at: string;+ last_message_author: string | null;+ replied: boolean;+ preview_text: string;+ preview_at: string | null;+ unread_count: number;+ unread: boolean;+};++export type InboxFeedResult = {+ sessions: InboxSession[];+ next_cursor: string | null;+ unread_by_session: Record<string, number>;+ unread_total: number;+ unread_sessions: number;+};+// =============================================================================// Harness (scheduled tasks / watches / runs)// =============================================================================@@ -1094,7 +1130,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenif (params?.platform) search.set('platform', params.platform);if (params?.unreadOnly) search.set('unread_only', '1');if (params?.limit) search.set('limit', String(params.limit));- if (params?.beforeId) search.set('before_id', params.beforeId);+ if (params?.before) search.set('before', params.before);const qs = search.toString();return getJson(qs ? `/api/inbox?${qs}` : '/api/inbox');},@@ -1249,6 +1285,19 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenhandlers.onInboxUnreadChanged?.(envelope.data);}});+ source.addEventListener('inbox.session.updated', (e: MessageEvent) => {+ const envelope = (() => {+ try {+ return JSON.parse(e.data) as WorkbenchEventEnvelope<InboxSession>;+ } catch {+ return null;+ }+ })();+ if (envelope) {+ handlers.onAny?.(envelope);+ handlers.onInboxSessionUpdated?.(envelope.data);+ }+ });source.onerror = (err) => handlers.onError?.(err);return () => source.close();},diff --git a/ui/src/context/WorkbenchInboxContext.tsx b/ui/src/context/WorkbenchInboxContext.tsxindex 9eb1db6a5..dd907433d 100644--- a/ui/src/context/WorkbenchInboxContext.tsx+++ b/ui/src/context/WorkbenchInboxContext.tsx@@ -2,47 +2,86 @@ import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useimport type { ReactNode } from 'react';import { useApi } from './ApiContext';-import type { WorkbenchMessage } from './ApiContext';+import type { InboxSession } from './ApiContext';++const PAGE_SIZE = 30;interface InboxState {- /** Per-scope (project) unread counts (only agent-authored messages count). */- unreadByScope: Record<string, number>;- /** Per-session unread counts — a project can hold several sessions, so the- * sidebar badges each session row from this rather than the scope total. */+ /** Per-session ("Slack-like") feed: one card per conversation, newest+ * activity first. Driven by realtime ``inbox.session.updated`` upserts. */+ inboxSessions: InboxSession[];+ /** Pagination-independent per-session unread counts — the sidebar badges+ * each session row from this (a session with unread may sit past the first+ * inbox page, so the feed array alone isn't a complete source). */unreadBySession: Record<string, number>;- /** Sum of ``unreadByScope`` — cached so consumers don't re-derive. */+ /** Sum of ``unreadBySession`` — the Inbox nav badge. */totalUnread: number;- /** Recent agent messages across all sessions (reverse-chronological). */- recentMessages: WorkbenchMessage[];+ /** Number of sessions with ≥1 unread reply — the header "N unread" count. */+ unreadSessions: number;+ /** Keyset cursor for "load more"; null when the feed is fully loaded. */+ nextCursor: string | null;loading: boolean;+ loadingMore: boolean;refresh: () => Promise<void>;+ loadMore: () => Promise<void>;markRead: (sessionId: string, untilMessageId?: string) => Promise<void>;}const WorkbenchInboxContext = createContext<InboxState | undefined>(undefined);+// Sort matches the backend keyset order: last activity (any author) desc, then+// session_id desc as the stable tie-break, so client upserts stay consistent+// with server-paginated pages.+const byActivityDesc = (a: InboxSession, b: InboxSession): number => {+ if (a.last_activity_at !== b.last_activity_at) {+ return a.last_activity_at < b.last_activity_at ? 1 : -1;+ }+ if (a.session_id === b.session_id) return 0;+ return a.session_id < b.session_id ? 1 : -1;+};++const upsertSession = (list: InboxSession[], row: InboxSession): InboxSession[] => {+ const next = list.filter((s) => s.session_id !== row.session_id);+ next.push(row);+ next.sort(byActivityDesc);+ return next;+};++const appendPage = (prev: InboxSession[], page: InboxSession[]): InboxSession[] => {+ const seen = new Set(prev.map((s) => s.session_id));+ const merged = prev.concat(page.filter((s) => !seen.has(s.session_id)));+ merged.sort(byActivityDesc);+ return merged;+};+/** Provider that owns the Inbox state shared across WorkbenchSidebar + InboxPage.*- * Connects to ``/api/events`` once on mount and updates state in place when- * new messages or unread-count changes arrive. The provider value is memoized- * per [[feedback_react_context_value_memoize]] so consumer ``useEffect``- * hooks that depend on context functions don't re-fire on every parent- * render. */+ * Connects to ``/api/events`` once on mount and updates the per-session feed in+ * place: ``inbox.session.updated`` upserts + re-sorts a card (the realtime+ * "bump to top"), ``inbox.unread.changed`` refreshes the unread map after a+ * mark-read elsewhere. The provider value is memoized per+ * [[feedback_react_context_value_memoize]] so consumer ``useEffect`` hooks that+ * depend on context functions don't re-fire on every parent render. */export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) => {const api = useApi();- const [unreadByScope, setUnreadByScope] = useState<Record<string, number>>({});+ const [inboxSessions, setInboxSessions] = useState<InboxSession[]>([]);const [unreadBySession, setUnreadBySession] = useState<Record<string, number>>({});- const [recentMessages, setRecentMessages] = useState<WorkbenchMessage[]>([]);+ const [nextCursor, setNextCursor] = useState<string | null>(null);const [loading, setLoading] = useState(false);+ const [loadingMore, setLoadingMore] = useState(false);// Avoid duplicate refresh-on-first-mount during StrictMode double-invoke.const initialFetched = useRef(false);+ // Mirror the cursor into a ref so ``loadMore`` can read the latest value+ // without re-creating its identity (and the context value) on every page.+ const cursorRef = useRef<string | null>(null);+ cursorRef.current = nextCursor;const refresh = useCallback(async () => {setLoading(true);try {- const result = await api.listInbox({ platform: 'avibe', limit: 30 });- setRecentMessages(result.messages);- setUnreadByScope(result.unread_counts);+ const result = await api.listInbox({ platform: 'avibe', limit: PAGE_SIZE });+ setInboxSessions(result.sessions);+ setNextCursor(result.next_cursor);setUnreadBySession(result.unread_by_session ?? {});} catch (err) {console.error('[inbox] refresh failed', err);@@ -51,10 +90,27 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>}}, [api]);+ const loadMore = useCallback(async () => {+ const cursor = cursorRef.current;+ if (!cursor) return;+ setLoadingMore(true);+ try {+ const result = await api.listInbox({ platform: 'avibe', limit: PAGE_SIZE, before: cursor });+ setInboxSessions((prev) => appendPage(prev, result.sessions));+ setNextCursor(result.next_cursor);+ } catch (err) {+ console.error('[inbox] load more failed', err);+ } finally {+ setLoadingMore(false);+ }+ }, [api]);+const markRead = useCallback(async (sessionId: string, untilMessageId?: string) => {const result = await api.markSessionRead(sessionId, untilMessageId);- setUnreadByScope(result.unread_counts);+ // The unread map is authoritative for badges; the card's unread styling+ // derives from it, so clearing here clears the dot without touching the+ // feed order (a read doesn't change last activity).setUnreadBySession(result.unread_by_session ?? {});},[api],@@ -66,41 +122,24 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>refresh();}const disconnect = api.connectWorkbenchEvents({- onMessageNew: (message) => {- // Only agent turns belong on the inbox feed — the user's own- // messages don't need to come back as "new" notifications.- if (message.author !== 'agent' || message.platform !== 'avibe') return;- setRecentMessages((prev) => {- // Skip duplicates if the REST POST optimistic update already- // added the row (rare for agent-authored events, but defensive).- if (prev.some((m) => m.id === message.id)) return prev;- return [message, ...prev].slice(0, 30);+ onInboxSessionUpdated: (row) => {+ setInboxSessions((prev) => upsertSession(prev, row));+ setUnreadBySession((prev) => {+ if ((prev[row.session_id] ?? 0) === row.unread_count) return prev;+ const next = { ...prev };+ if (row.unread_count > 0) next[row.session_id] = row.unread_count;+ else delete next[row.session_id];+ return next;});- if (!message.read_at && message.scope_id) {- setUnreadByScope((prev) => ({- ...prev,- [message.scope_id as string]: (prev[message.scope_id as string] ?? 0) + 1,- }));- }- if (!message.read_at && message.session_id) {- setUnreadBySession((prev) => ({- ...prev,- [message.session_id as string]: (prev[message.session_id as string] ?? 0) + 1,- }));- }},onInboxUnreadChanged: (data) => {- if (data?.unread_counts) {- setUnreadByScope(data.unread_counts);- }if (data?.unread_by_session) {setUnreadBySession(data.unread_by_session);}},onError: (err) => {- // Browser EventSource will auto-reconnect; keep this as a log- // entry rather than a crash so the workbench stays usable when- // the dev proxy is restarting / etc.+ // Browser EventSource auto-reconnects; keep this a log, not a crash,+ // so the workbench stays usable while the dev proxy restarts / etc.console.debug('[inbox] sse error', err);},});@@ -108,21 +147,39 @@ export const WorkbenchInboxProvider = ({ children }: { children: ReactNode }) =>}, [api, refresh]);const totalUnread = useMemo(- () => Object.values(unreadByScope).reduce((sum, n) => sum + (n || 0), 0),- [unreadByScope],+ () => Object.values(unreadBySession).reduce((sum, n) => sum + (n || 0), 0),+ [unreadBySession],+ );+ const unreadSessions = useMemo(+ () => Object.values(unreadBySession).filter((n) => (n || 0) > 0).length,+ [unreadBySession],);const value = useMemo<InboxState>(() => ({- unreadByScope,+ inboxSessions,unreadBySession,totalUnread,- recentMessages,+ unreadSessions,+ nextCursor,loading,+ loadingMore,refresh,+ loadMore,markRead,}),- [unreadByScope, unreadBySession, totalUnread, recentMessages, loading, refresh, markRead],+ [+ inboxSessions,+ unreadBySession,+ totalUnread,+ unreadSessions,+ nextCursor,+ loading,+ loadingMore,+ refresh,+ loadMore,+ markRead,+ ],);return <WorkbenchInboxContext.Provider value={value}>{children}</WorkbenchInboxContext.Provider>;diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex c1c0ccacc..8ef5b8914 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -484,7 +484,10 @@"allClearBody": "No unread agent messages right now. Switch to \"All\" to browse history.","backToCanvas": "Back to canvas","agent": "Agent",- "you": "You"+ "you": "You",+ "replied": "Replied",+ "loadMore": "Load more",+ "moreUnreadBeyond": "More unread sessions may be further down — load more to see them."},"modules": {"comingSoonEyebrow": "Coming soon",@@ -1479,6 +1482,7 @@"missingSessionId": "Missing session id in the URL.","transcriptEmpty": "Type a message below to start the conversation","streaming": "Streaming",+ "notifyLabel": "Notify","compose": {"placeholder": "Type a message…","hint": "⌘/Ctrl+Enter to send",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex f47cd6007..2259ced3e 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -484,7 +484,10 @@"allClearBody": "当前没有未读的 Agent 消息。切到\"全部\"可以浏览历史。","backToCanvas": "回到画布","agent": "Agent",- "you": "我"+ "you": "我",+ "replied": "已回复",+ "loadMore": "加载更多",+ "moreUnreadBeyond": "还有未读会话在后面的分页里,点击「加载更多」查看。"},"modules": {"comingSoonEyebrow": "即将就位",@@ -1478,6 +1481,7 @@"missingSessionId": "URL 缺少 session id。","transcriptEmpty": "在下方输入消息开始对话","streaming": "实时输出中",+ "notifyLabel": "通知","compose": {"placeholder": "输入消息…","hint": "⌘/Ctrl+Enter 发送",diff --git a/vibe/inbox_bridge.py b/vibe/inbox_bridge.pynew file mode 100644index 000000000..757102aa4--- /dev/null+++ b/vibe/inbox_bridge.py@@ -0,0 +1,60 @@+"""UI-server side relay: Controller inbox events → browser SSE broker.++The Controller process persists agent messages (``core.message_mirror``) and+publishes ``inbox.session.updated`` onto its in-process+``core.inbox_events.bus``, which ``core.internal_server`` exposes over the+dispatch Unix socket at ``GET /internal/events``. The UI server runs in a+*separate* process, so its ``vibe.sse_broker.broker`` never sees those events+directly. This module bridges the gap: one long-lived background task+subscribes to the controller feed and re-publishes every event to the local+broker, which fans it out to each browser's ``GET /api/events``.++One task per UI-server process (started from the ASGI ``startup`` hook). It+reconnects with backoff whenever the socket is missing (controller still+booting), the stream drops, or the controller restarts — so realtime inbox+updates self-heal without a UI reload.+"""++from __future__ import annotations++import asyncio+import logging++from vibe import internal_client+from vibe.sse_broker import broker++logger = logging.getLogger(__name__)++# Reconnect backoff. The controller socket is often absent for a beat during+# co-startup / controller restart, so start tight (fast first connect) and cap+# it so a long-down controller doesn't busy-spin.+_BACKOFF_INITIAL = 1.0+_BACKOFF_MAX = 15.0+++async def run_inbox_bridge() -> None:+ """Relay controller inbox events to the local SSE broker until cancelled.++ Never raises out (except ``CancelledError`` on shutdown): every failure+ path loops back into a reconnect so a transient controller outage can't+ kill the bridge.+ """++ backoff = _BACKOFF_INITIAL+ while True:+ try:+ async for event_type, data in internal_client.stream_events():+ # A flowing event proves the link is healthy → reset backoff so+ # the next genuine drop reconnects promptly.+ backoff = _BACKOFF_INITIAL+ broker.publish(event_type, data)+ except asyncio.CancelledError:+ raise+ except internal_client.InternalServerUnavailable:+ logger.debug("inbox bridge: controller socket unavailable; retry in %.1fs", backoff)+ except Exception:+ logger.warning("inbox bridge: stream error; retry in %.1fs", backoff, exc_info=True)+ else:+ logger.debug("inbox bridge: controller feed closed; reconnect in %.1fs", backoff)+ await asyncio.sleep(backoff)+ backoff = min(backoff * 2, _BACKOFF_MAX)diff --git a/vibe/internal_client.py b/vibe/internal_client.pyindex f0c62a1a0..a578a30b7 100644--- a/vibe/internal_client.py+++ b/vibe/internal_client.py@@ -113,6 +113,63 @@ async def stream_dispatch(raise InternalServerUnavailable(str(exc)) from exc+async def stream_events(+ *,+ socket_path: Optional[Path] = None,+) -> AsyncIterator[tuple[str, Any]]:+ """Subscribe to the controller's long-lived ``GET /internal/events`` feed.++ Yields ``(event_name, parsed_data)`` for each event, e.g.+ ``("inbox.session.updated", {...inbox row...})``. The read timeout is+ disabled (the connection is meant to stay open); raises+ ``InternalServerUnavailable`` on connect failure so the UI server's+ subscriber loop can back off and reconnect.+ """++ target = (socket_path or default_socket_path()).expanduser().resolve()+ if not target.exists():+ raise InternalServerUnavailable(f"dispatch socket missing at {target}")++ transport = httpx.AsyncHTTPTransport(uds=str(target))+ try:+ async with httpx.AsyncClient(+ transport=transport,+ base_url="http://localhost",+ timeout=httpx.Timeout(None, connect=5.0),+ ) as client:+ try:+ stream = client.stream("GET", "/internal/events")+ except (httpx.ConnectError, FileNotFoundError, PermissionError) as exc:+ raise InternalServerUnavailable(str(exc)) from exc++ async with stream as resp:+ if resp.status_code >= 400:+ detail = await resp.aread()+ raise InternalServerUnavailable(+ f"events endpoint returned {resp.status_code}: {detail!r}"+ )++ current_event: Optional[str] = None+ async for line in resp.aiter_lines():+ if not line:+ current_event = None+ continue+ if line.startswith("event:"):+ current_event = line.split(":", 1)[1].strip()+ elif line.startswith("data:"):+ raw = line[5:].lstrip()+ try:+ parsed = json.loads(raw)+ except json.JSONDecodeError:+ logger.warning("internal_client: invalid SSE data line %r", raw)+ continue+ yield (current_event or "message", parsed)+ except InternalServerUnavailable:+ raise+ except (httpx.ConnectError, FileNotFoundError, PermissionError) as exc:+ raise InternalServerUnavailable(str(exc)) from exc++async def cancel_dispatch(session_id: str, *, socket_path: Optional[Path] = None) -> dict[str, Any]:"""Ask the controller to cancel a running ``dispatch_turn`` for``session_id``.diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 60713b88a..28c430a32 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3016,11 +3016,20 @@ def sessions_messages_list(session_id: str):workbench_sessions_service.get_session(conn, session_id)except LookupError as err:return jsonify({"error": str(err)}), 404+ # Chat transcript = the dialogue + turn-terminal markers. avibe turns+ # persist intermediate assistant / tool_call rows (unified store) that we+ # keep OUT of the conversation view, but ``notify`` rows are kept: a+ # terminal notify (e.g. an agent run that failed and stopped without a+ # result) marks the end of that turn and must stay visible. Show-Page+ # transcript marks (metadata.source='show_page') are kept regardless of+ # type.result = messages_service.list_session_messages(conn,session_id=session_id,after_id=after_id,limit=limit,+ types=("user", "result", "notify"),+ include_metadata_sources=("show_page",),)return jsonify(result)@@ -3067,6 +3076,7 @@ async def sessions_messages_create(session_id: str):session_id=session_id,platform="avibe",author="user",+ message_type="user",text=text if isinstance(text, str) else None,content=content if isinstance(content, dict) else None,metadata=payload.get("metadata") or {},@@ -3082,6 +3092,18 @@ async def sessions_messages_create(session_id: str):"session.activity",{"session_id": session_id, "scope_id": session["scope_id"], "event": "user_message"},)+ # Bump the session's inbox card for the user's own reply: re-rank it to the+ # top and flip the "replied" badge. The agent-reply side of this is covered+ # by the cross-process bridge (controller persists + publishes), but the+ # user message is persisted here in the UI process, so the controller bus+ # never sees it — publish in-process. No-op until the session has a result.+ try:+ with engine.connect() as conn:+ inbox_row = messages_service.get_inbox_session(conn, session_id, platform="avibe")+ if inbox_row is not None:+ broker.publish("inbox.session.updated", inbox_row)+ except Exception:+ logger.debug("inbox.session.updated publish (user message) failed", exc_info=True)if request.args.get("stream") != "1":return jsonify(message), 201@@ -3240,32 +3262,35 @@ async def workbench_events():@app.route("/api/inbox", methods=["GET"])def inbox_list():- """Cross-session inbox feed. Defaults to avibe-only per workbench scope."""+ """Per-session ("Slack-like") inbox feed: one row per conversation, newest+ activity first. Defaults to avibe-only per workbench scope."""from storage import messages_serviceplatform = request.args.get("platform") or "avibe"+ scope_filter = platform if platform != "all" else Noneunread_only = request.args.get("unread_only") in {"1", "true", "yes"}try:limit = int(request.args.get("limit") or 30)except (TypeError, ValueError):limit = 30- before_id = request.args.get("before_id") or None+ before = request.args.get("before") or Noneengine = _projects_engine()with engine.connect() as conn:- result = messages_service.list_inbox(+ result = messages_service.list_inbox_sessions(conn,- platform=platform if platform != "all" else None,+ platform=scope_filter,unread_only=unread_only,limit=limit,- before_id=before_id,- )- scope_filter = platform if platform != "all" else None- result["unread_counts"] = messages_service.unread_counts(conn, platform=scope_filter)- result["unread_by_session"] = messages_service.unread_counts_by_session(- conn, platform=scope_filter+ before=before,)+ # Pagination-independent unread map for the sidebar badges (a session+ # with unread may sit past the first inbox page) + header totals.+ per_session = messages_service.unread_counts_by_session(conn, platform=scope_filter)+ result["unread_by_session"] = per_session+ result["unread_total"] = sum(per_session.values())+ result["unread_sessions"] = len(per_session)return jsonify(result)@@ -4150,6 +4175,40 @@ def _reconcile_remote_access_for_ui_start(config: V2Config | None) -> None:logger.warning("Failed to reconcile remote access after UI start", exc_info=True)+# --- Realtime inbox bridge --------------------------------------------------+# Relays the controller's cross-process inbox events into the local SSE broker+# (see vibe/inbox_bridge.py). One task per UI-server process, owned by the ASGI+# lifecycle so it starts after the loop is alive and is cancelled cleanly on+# shutdown/reload instead of leaking a pending task.++_inbox_bridge_task: "asyncio.Task | None" = None+++async def _start_inbox_bridge() -> None:+ global _inbox_bridge_task+ from vibe.inbox_bridge import run_inbox_bridge++ if _inbox_bridge_task is None or _inbox_bridge_task.done():+ _inbox_bridge_task = asyncio.create_task(run_inbox_bridge(), name="inbox-events-bridge")+++async def _stop_inbox_bridge() -> None:+ global _inbox_bridge_task+ task, _inbox_bridge_task = _inbox_bridge_task, None+ if task is not None and not task.done():+ task.cancel()+ try:+ await task+ except asyncio.CancelledError:+ pass+ except Exception:+ logger.debug("inbox bridge shutdown raised", exc_info=True)+++app.add_event_handler("startup", _start_inbox_bridge)+app.add_event_handler("shutdown", _stop_inbox_bridge)++def _bind_ui_socket(host: str, port: int) -> socket.socket:family = socket.AF_INET6 if host and ":" in host else socket.AF_INETsock = socket.socket(family)