Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(workbench): rank sessions by agent activity, not only user input (#1820)

Call White199cccf95834
diff --git a/core/message_mirror.py b/core/message_mirror.py
index 9af228ee5..6e6920710 100644
--- a/core/message_mirror.py
+++ b/core/message_mirror.py
@@ -30,6 +30,7 @@ from typing import Any, Optional
from sqlalchemy.exc import IntegrityError
from core.run_settlement import NON_COMPLETING_TURN_SETTLEMENTS
+from core.services import sessions as workbench_sessions_service
from modules.im.base import MessageContext
from storage import agent_events_service, messages_service, settings_service
from storage.db import get_cached_sqlite_engine
@@ -326,6 +327,7 @@ def persist_agent_message(
appended_row = None
tool_event_row = None
message_type = None
+ activity_ranked = False
is_tool_call = _is_tool_call_type(canonical_type)
with engine.begin() as conn:
if context.platform == "avibe":
@@ -445,6 +447,64 @@ def persist_agent_message(
# scoped to avibe sessions (IM rows persist but aren't shown there).
if context.platform == "avibe" and session_id and not suppress_delivery:
inbox_row = messages_service.get_inbox_session(conn, session_id)
+ # Both branches rejoin here: a chat row and a tool-call trace event are
+ # equally proof the agent is working, and the session list ranked on
+ # input alone, so an unattended session sank while it worked. Rides the
+ # open transaction — no extra commit, no extra fsync.
+ #
+ # THE RANK ASSERTS ONE THING: this session's agent persisted output just
+ # now. So it is bounded by exactly the conditions that can make that
+ # claim false, and by nothing else:
+ # 1. a session row to rank (``row_session_id``);
+ # 2. output that actually materialized (below);
+ # 3. the row is not archived — archive is terminal, re-asserted inside
+ # the UPDATE because this write has no request boundary to guard it;
+ # 4. the throttle, also a predicate on the row (see the storage helper).
+ # Conditions of the surrounding DELIVERY path are deliberately absent,
+ # and borrowing one by proximity is what cost two review rounds.
+ # ``context.platform`` is not a condition: the rank is read by the Web
+ # list, ``vibe session list``, the run graph and the running-agents view
+ # alike, so output ranks on every platform. ``suppress_delivery`` is not
+ # one either — a hidden session is not an unread one. A background
+ # Session is out of the session list but is a first-class agent-graph
+ # node ordered by this very column (``agent_graph`` defaults
+ # ``include_background=True``), and visibility is a MUTABLE preference
+ # where the archive is terminal: the PATCH that restores a session to the
+ # foreground writes ``visibility`` and ``updated_at`` and never backfills
+ # ``last_active_at``. Holding the rank while hidden therefore saves no
+ # dead write; it leaves the row mis-ordered for every later reader.
+ #
+ # (2) is a row having materialized, not merely reaching this line:
+ # ``_append_quietly`` returns ``None`` when the same
+ # ``native_message_id`` arrives twice, and the promote path can decline
+ # too, so a retried terminal output persists nothing. Replaying one
+ # logical output must not lift a long-finished session back to the top of
+ # the list on nothing new. The tool-call branch always inserts, so this
+ # only ever excludes the deduplicated chat row.
+ if row_session_id and (appended_row is not None or tool_event_row is not None):
+ activity_ranked = workbench_sessions_service.touch_session_agent_activity(
+ conn, row_session_id
+ )
+ # A rank change means the list has to re-sort, so tell an open browser the
+ # same way an accepted user send does. Gated on the bump having actually
+ # landed, which bounds this to one event per minute per session — strictly
+ # cheaper than the per-message ``inbox.session.updated`` below. avibe-only
+ # for the reason the publishes below are: an IM session has no open Chat or
+ # sidebar consumer, so publishing it would be dead traffic.
+ #
+ # It follows the RANK, not delivery, so it fires for a hidden session too —
+ # which is right rather than merely consistent: the surface that orders
+ # background rows by this column is the agent graph, and that is the view
+ # whose consumer refetches on this event. The payload is
+ # ``{session_id, scope_id, event}`` with no content, so a reorder announces
+ # nothing a suppressed message body would have carried.
+ if activity_ranked and context.platform == "avibe":
+ from core.inbox_events import bus
+
+ bus.publish(
+ "session.activity",
+ {"session_id": row_session_id, "scope_id": scope_id, "event": "agent_activity"},
+ )
# tool_call rows never enter ``messages``/TRANSCRIPT_TYPES; when the Chat
# activity panel is enabled they fan out here as a synthesized
# ``message.new`` so an open Chat page shows the step live. Default off →
diff --git a/core/services/sessions.py b/core/services/sessions.py
index 0078891c2..caea913f4 100644
--- a/core/services/sessions.py
+++ b/core/services/sessions.py
@@ -55,6 +55,7 @@ from storage.workbench_sessions_service import (
require_enabled_agent_identity,
set_agent_status,
touch_session,
+ touch_session_agent_activity,
update_session,
)
from vibe.i18n import t as i18n_t
@@ -78,6 +79,7 @@ __all__ = [
"set_agent_status",
"session_archived_message",
"touch_session",
+ "touch_session_agent_activity",
"update_session",
"reserve_agent_session",
"reserve_standalone_agent_session",
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index dd98c777f..973061577 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -20,7 +20,7 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Mapping, Optional
-from sqlalchemy import and_, func, or_, select, update
+from sqlalchemy import Integer, and_, cast, func, or_, select, update
from sqlalchemy.engine import Connection
from config import paths
@@ -1541,6 +1541,92 @@ def touch_session(conn: Connection, session_id: str) -> None:
)
+# Coarsest stamp the activity-ordered surfaces can't tell apart. They render
+# relative ages ("2 min ago") off a list that re-sorts on whole rows, so a minute
+# of skew is invisible there while it bounds the write rate by the number of
+# ACTIVE sessions instead of by message volume — agent output arrives at
+# tool-call rate, tens of rows per minute per session.
+AGENT_ACTIVITY_RANK_INTERVAL_SECONDS = 60
+
+
+def _epoch_seconds(value: Any) -> Any:
+ """An ISO timestamp as whole seconds since the epoch, or NULL if undatable.
+
+ Takes a column or a literal and returns a SQL expression, so the same
+ conversion applies to both sides of a comparison.
+
+ Integer seconds rather than ``julianday`` arithmetic: julianday returns days
+ as a float near 2.46e6, so subtracting two of them leaves under a millisecond
+ of resolution and an exactly-``interval``-old stamp evaluates to 59.9999996 —
+ the throttle boundary would then depend on float error rather than on the
+ interval. Whole seconds are exact, and one second is far finer than any
+ interval this gates. ``strftime`` is available in every SQLite that can open
+ the database, unlike the ``unixepoch()`` shorthand (3.38+).
+ """
+
+ return cast(func.strftime("%s", value), Integer)
+
+
+def touch_session_agent_activity(conn: Connection, session_id: str) -> bool:
+ """Rank a session as recently active because its own agent produced output.
+
+ ``touch_session`` records *input*: a user send, a Show Page event. Nothing
+ recorded output, so a session whose agent has been working unattended for an
+ hour — genuinely the most active one there is — sank below sessions idle since
+ their last user message.
+
+ Called once per persisted agent message and per tool-call trace event, so it
+ carries its own rate limit rather than asking every caller to remember one:
+ the ``WHERE`` clause matches only when the stored stamp is already older than
+ :data:`AGENT_ACTIVITY_RANK_INTERVAL_SECONDS`. Keeping the throttle in the row
+ is what makes it correct as well as cheap — the controller and the UI server
+ are separate processes (see ``CLAUDE.md`` §2), so a process-local cache would
+ hold two disagreeing answers and need eviction to boot. A throttled call
+ costs one primary-key-keyed UPDATE that matches nothing and dirties no page.
+
+ Returns ``True`` only when the stamp actually moved — throttled, archived, and
+ unknown rows all return ``False`` — so a caller can gate its realtime publish
+ on this without tracking any state itself.
+
+ Unrelated to ``SessionHandler.touch_session_activity``, which is an
+ in-process ``monotonic()`` idle clock for runtime keep-alive.
+ """
+
+ now = _utc_now_iso()
+ stored_epoch = _epoch_seconds(agent_sessions.c.last_active_at)
+ result = conn.execute(
+ update(agent_sessions)
+ .where(
+ agent_sessions.c.id == session_id,
+ # Archive is terminal, and this is the one session write with no entry
+ # point to guard: ``touch_session``'s callers reject an archived target
+ # up front (``ui_server`` and ``show_session_events`` both consult
+ # ``is_session_archived``) because a *user* action arrives at a request
+ # boundary. Agent output does not — ``archive_session`` commits the
+ # archive first and cancels the in-flight turn best-effort afterwards,
+ # so a turn keeps emitting into a row that is already archived. The
+ # predicate belongs in the UPDATE for the same reason it does at the
+ # PATCH above: a read-then-write check reserves nothing, and an archive
+ # committing in that window is exactly the case being guarded.
+ agent_sessions.c.status != "archived",
+ # A parsed comparison rather than a text one because the column holds
+ # more than one ISO shape: second-granularity ``…Z`` from
+ # ``_utc_now_iso`` here and in ``agent_session_rows`` alongside
+ # ``…+00:00`` rows from ``sessions_service``'s ``isoformat()``, which
+ # compare wrongly as text at the same instant. ``strftime('%s')``
+ # yields NULL for a NULL or undatable stamp, and that arm has to bump —
+ # a row we cannot date is a row whose rank would otherwise freeze
+ # forever.
+ or_(
+ stored_epoch.is_(None),
+ _epoch_seconds(now) - stored_epoch >= AGENT_ACTIVITY_RANK_INTERVAL_SECONDS,
+ ),
+ )
+ .values(last_active_at=now, updated_at=now)
+ )
+ return result.rowcount == 1
+
+
VALID_AGENT_STATUSES = ("idle", "running", "failed")
diff --git a/tests/test_core_services_sessions.py b/tests/test_core_services_sessions.py
index 2c1125e4f..44c4e5444 100644
--- a/tests/test_core_services_sessions.py
+++ b/tests/test_core_services_sessions.py
@@ -9,6 +9,7 @@ shape or the public function set must update this file in lock-step.
from __future__ import annotations
import sys
+from datetime import datetime, timedelta, timezone
from pathlib import Path
import pytest
@@ -78,6 +79,7 @@ def test_public_surface_is_stable():
"list_sessions_page",
"set_agent_status",
"touch_session",
+ "touch_session_agent_activity",
"update_session",
# Legacy IM-style reservation helpers added in C2 for the CLI:
"reserve_agent_session",
@@ -117,6 +119,7 @@ def test_each_workbench_function_delegates_to_storage():
"list_sessions",
"set_agent_status",
"touch_session",
+ "touch_session_agent_activity",
"update_session",
):
assert getattr(sessions_service, name) is getattr(storage_sessions, name)
@@ -882,3 +885,243 @@ def test_workbench_default_action_drops_the_explicit_override_marker(isolated_st
f"dispatch handed the backend reasoning_effort="
f"{request.vibe_agent_reasoning_effort!r} instead of the default Agent's"
)
+
+
+# --- Agent-activity rank (session-list ordering) ----------------------
+#
+# ``touch_session`` records input; ``touch_session_agent_activity`` records the
+# session's own agent producing output, so a session working unattended stops
+# sinking below sessions idle since their last user message. It carries its own
+# rate limit because it is called once per agent message and tool-call event.
+
+
+def _rank_stamp_shapes(instant: datetime) -> dict[str, str]:
+ """One stored ``last_active_at`` text per shape the column holds, each
+ naming the same ``instant``.
+
+ Seeded by shape rather than by case so a writer added later is covered by
+ construction. The shapes come from the writers:
+ ``storage.workbench_sessions_service`` and ``storage.agent_session_rows``
+ write ``strftime("%Y-%m-%dT%H:%M:%SZ")``; ``storage.sessions_service``
+ writes ``datetime.isoformat()``, which omits the fractional part when it is
+ exactly zero — one writer, two shapes. Naive rows predate the tz-aware
+ writers. Text ordering disagrees with instant ordering across these, which
+ is why the throttle compares parsed times instead of strings.
+ """
+
+ return {
+ "z_second": instant.strftime("%Y-%m-%dT%H:%M:%SZ"),
+ "z_microsecond": instant.isoformat().replace("+00:00", "Z"),
+ "offset_second": instant.replace(microsecond=0).isoformat(),
+ "offset_microsecond": instant.isoformat(),
+ "naive_second": instant.replace(tzinfo=None).strftime("%Y-%m-%dT%H:%M:%S"),
+ }
+
+
+def _seed_session_with_stamp(conn, scope_id: str, title: str, stamp) -> str:
+ session_id = sessions_service.create_session(
+ conn, scope_id=scope_id, agent_backend="claude", title=title
+ )["id"]
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == session_id)
+ .values(last_active_at=stamp)
+ )
+ return session_id
+
+
+def _freeze_rank_clock(monkeypatch, instant: datetime) -> None:
+ """Pin the helper's own clock so the assertions describe the interval
+ rather than the wall clock the test happens to run on."""
+
+ monkeypatch.setattr(
+ storage_sessions,
+ "_utc_now_iso",
+ lambda: instant.strftime("%Y-%m-%dT%H:%M:%SZ"),
+ )
+
+
+def test_agent_activity_rank_is_throttled_to_its_interval(isolated_state, monkeypatch):
+ """Agent output arrives at tool-call rate, so the rank must move at most
+ once per interval however many messages land inside it — and must move
+ again on the first call past it.
+ """
+ interval = storage_sessions.AGENT_ACTIVITY_RANK_INTERVAL_SECONDS
+ start = datetime(2026, 9, 2, 12, 0, 0, tzinfo=timezone.utc)
+
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_avibe_scope(conn)
+ session_id = _seed_session_with_stamp(
+ conn, scope_id, "working", start.strftime("%Y-%m-%dT%H:%M:%SZ")
+ )
+
+ def bumps_over(offsets: list[int]) -> list[bool]:
+ moved = []
+ for offset in offsets:
+ _freeze_rank_clock(monkeypatch, start + timedelta(seconds=offset))
+ with engine.begin() as conn:
+ moved.append(sessions_service.touch_session_agent_activity(conn, session_id))
+ return moved
+
+ # A burst inside one interval: the stamp is already that recent, so no write
+ # lands however many messages the agent emits.
+ assert bumps_over([1, 2, 5, interval - 1]) == [False, False, False, False]
+ # First call at/after the interval moves it, and re-arms the window.
+ assert bumps_over([interval, interval + 1, 2 * interval - 1]) == [True, False, False]
+ assert bumps_over([2 * interval]) == [True]
+
+ with engine.connect() as conn:
+ stored = sessions_service.get_session(conn, session_id)
+ assert stored["last_active_at"] == (start + timedelta(seconds=2 * interval)).strftime(
+ "%Y-%m-%dT%H:%M:%SZ"
+ )
+
+
+def test_agent_activity_rank_decides_by_instant_for_every_stored_shape(
+ isolated_state, monkeypatch
+):
+ """The throttle decision follows the instant a stamp names, in every shape
+ the column stores — not the text, which sorts differently across shapes.
+ """
+ interval = storage_sessions.AGENT_ACTIVITY_RANK_INTERVAL_SECONDS
+ now = datetime(2026, 9, 2, 12, 0, 0, tzinfo=timezone.utc)
+ fresh = now - timedelta(seconds=5, microseconds=-123456)
+ stale = now - timedelta(seconds=interval * 2, microseconds=-123456)
+
+ engine = create_sqlite_engine()
+ seeded: dict[tuple[str, str], str] = {}
+ with engine.begin() as conn:
+ scope_id = _seed_avibe_scope(conn)
+ for age, instant in (("fresh", fresh), ("stale", stale)):
+ for shape, stamp in _rank_stamp_shapes(instant).items():
+ seeded[(age, shape)] = _seed_session_with_stamp(
+ conn, scope_id, f"{age}-{shape}", stamp
+ )
+
+ _freeze_rank_clock(monkeypatch, now)
+ moved = {}
+ with engine.begin() as conn:
+ for key, session_id in seeded.items():
+ moved[key] = sessions_service.touch_session_agent_activity(conn, session_id)
+
+ # Every shape, one property: inside the interval the rank holds; past it, it moves.
+ assert moved == {key: key[0] == "stale" for key in seeded}
+
+
+def test_agent_activity_rank_bumps_a_row_it_cannot_date(isolated_state, monkeypatch):
+ """A stamp the database cannot parse must fail open. Holding the rank would
+ freeze such a row at the bottom of the list forever; moving it costs one
+ write per interval, the same as any other row.
+ """
+ engine = create_sqlite_engine()
+ undatable = {"null": None, "empty": "", "garbage": "not-a-timestamp"}
+ seeded = {}
+ with engine.begin() as conn:
+ scope_id = _seed_avibe_scope(conn)
+ for name, stamp in undatable.items():
+ seeded[name] = _seed_session_with_stamp(conn, scope_id, name, stamp)
+
+ _freeze_rank_clock(monkeypatch, datetime(2026, 9, 2, 12, 0, 0, tzinfo=timezone.utc))
+ with engine.begin() as conn:
+ moved = {
+ name: sessions_service.touch_session_agent_activity(conn, session_id)
+ for name, session_id in seeded.items()
+ }
+ assert moved == dict.fromkeys(undatable, True)
+
+ with engine.connect() as conn:
+ stamps = {
+ name: sessions_service.get_session(conn, session_id)["last_active_at"]
+ for name, session_id in seeded.items()
+ }
+ assert stamps == dict.fromkeys(undatable, "2026-09-02T12:00:00Z")
+
+
+def test_agent_activity_rank_lifts_a_session_working_unattended(isolated_state, monkeypatch):
+ """The user-facing property this exists for: a session whose agent is still
+ working outranks one whose user spoke more recently but has since gone
+ quiet. Ordering is read through the same list the sidebar renders.
+ """
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_avibe_scope(conn)
+ working = _seed_session_with_stamp(conn, scope_id, "agent-working", "2026-09-02T11:00:00Z")
+ replied = _seed_session_with_stamp(conn, scope_id, "user-replied", "2026-09-02T11:30:00Z")
+
+ with engine.connect() as conn:
+ before = [row["title"] for row in sessions_service.list_sessions(conn, scope_id=scope_id)["sessions"]]
+ assert before == ["user-replied", "agent-working"]
+
+ # The unattended session's agent emits one message: no user input at all.
+ _freeze_rank_clock(monkeypatch, datetime(2026, 9, 2, 12, 0, 0, tzinfo=timezone.utc))
+ with engine.begin() as conn:
+ assert sessions_service.touch_session_agent_activity(conn, working) is True
+
+ with engine.connect() as conn:
+ after = [row["title"] for row in sessions_service.list_sessions(conn, scope_id=scope_id)["sessions"]]
+ assert after == ["agent-working", "user-replied"]
+ # The session nobody touched kept its rank — the bump is not a global re-sort.
+ with engine.connect() as conn:
+ assert sessions_service.get_session(conn, replied)["last_active_at"] == "2026-09-02T11:30:00Z"
+
+
+# Every value the session lifecycle ``status`` column holds. The rank is one more
+# write against a row whose archived state is terminal, and the repository
+# enforces that with a ``status != 'archived'`` predicate on every write rather
+# than a per-caller check, so the property is stated over the whole domain
+# instead of over the one case a reviewer happened to name.
+SESSION_LIFECYCLE_STATUSES = ("active", "archived")
+
+
+def test_agent_activity_rank_never_writes_an_archived_row(isolated_state, monkeypatch):
+ """Archive is terminal, including for late output.
+
+ ``archive_session`` commits the archive first and cancels the in-flight turn
+ best-effort afterwards, so a turn can still be emitting into an
+ already-archived session. Every seeded row carries the same stale stamp, so
+ the throttle would allow all of them and the status predicate is the only
+ thing deciding — and the expectation is derived from the rule, so a lifecycle
+ status added later is covered rather than silently skipped.
+ """
+ stale = "2020-01-01T00:00:00Z"
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_avibe_scope(conn)
+ seeded = {
+ status: _seed_session_with_stamp(conn, scope_id, f"s-{status}", stale)
+ for status in SESSION_LIFECYCLE_STATUSES
+ }
+ for status, session_id in seeded.items():
+ conn.execute(
+ agent_sessions.update()
+ .where(agent_sessions.c.id == session_id)
+ .values(status=status)
+ )
+
+ def archived_row() -> dict:
+ with engine.connect() as conn:
+ return dict(
+ conn.execute(
+ agent_sessions.select().where(agent_sessions.c.id == seeded["archived"])
+ )
+ .mappings()
+ .one()
+ )
+
+ before = archived_row()
+
+ _freeze_rank_clock(monkeypatch, datetime(2026, 9, 2, 12, 0, 0, tzinfo=timezone.utc))
+ with engine.begin() as conn:
+ moved = {
+ status: sessions_service.touch_session_agent_activity(conn, session_id)
+ for status, session_id in seeded.items()
+ }
+ assert moved == {status: status != "archived" for status in SESSION_LIFECYCLE_STATUSES}
+
+ # Nothing on the archived row moved, not merely its rank: the return value is
+ # a claim about the write, and ``updated_at`` shifting would still be a
+ # mutation of terminal metadata. Compared against the row as it was rather
+ # than against a chosen date, so the assertion holds whatever day it runs on.
+ assert archived_row() == before
+ assert before["last_active_at"] == stale
diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.py
index 6233ba06e..405a5d062 100644
--- a/tests/test_message_mirror.py
+++ b/tests/test_message_mirror.py
@@ -35,6 +35,7 @@ from core.message_mirror import (
)
from modules.im import MessageContext
from storage import messages_service
+from storage.agent_session_rows import SESSION_VISIBILITIES
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state
from storage.models import agent_events, agent_sessions, media_objects, messages, scopes
@@ -48,6 +49,36 @@ def isolated_state(monkeypatch, tmp_path):
yield tmp_path
+# The topics that fan message CONTENT out to an open browser: the Chat transcript
+# row and the Inbox card preview. Named once as a class so a test can assert "this
+# row did not stream" by naming what must not appear, instead of asserting the bus
+# stayed silent — ``persist_agent_message`` also publishes contentless events on
+# the same path for unrelated concerns (the session-list rank), and a test that
+# reads silence as its property fails on the next one of those to be added while
+# proving nothing more about content.
+CONTENT_TOPICS = frozenset({"message.new", "inbox.session.updated"})
+
+
+async def _drain_published(queue: asyncio.Queue, *, quiet: float = 0.1) -> dict[str, dict]:
+ """Everything published to ``queue``, keyed by topic.
+
+ Drains until the bus goes quiet rather than reading a fixed count: a count
+ silently re-points a test's assertions at whichever events happen to arrive
+ first, so ``for _ in range(2)`` starts failing when an unrelated third topic
+ is published — not because the asserted property broke, but because the test
+ stopped looking at it. ``bus.publish`` enqueues synchronously, so the quiet
+ window is paid once and only after every event is already in the queue.
+ """
+
+ events: dict[str, dict] = {}
+ while True:
+ try:
+ topic, payload = await asyncio.wait_for(queue.get(), timeout=quiet)
+ except asyncio.TimeoutError:
+ return events
+ events[topic] = payload
+
+
def _slack_ctx(message_id="m_001") -> MessageContext:
return MessageContext(
user_id="U_alice",
@@ -469,10 +500,7 @@ def test_persist_agent_publishes_message_and_inbox_for_avibe(isolated_state):
with patch("core.web_push_notifications.maybe_notify_inbox_message", fake_notify):
persist_agent_message(ctx, "result", "final answer")
- # Drain both events (order: message.new, then inbox.session.updated).
- for _ in range(2):
- event_type, data = await asyncio.wait_for(queue.get(), timeout=1.0)
- events[event_type] = data
+ events = await _drain_published(queue)
finally:
inbox_events.bus.unsubscribe(sub_id)
return events
@@ -541,17 +569,15 @@ def test_persist_agent_intermediate_persisted_but_not_streamed(isolated_state):
async def scenario():
sub_id, queue = inbox_events.bus.subscribe()
- seen = []
try:
persist_agent_message(ctx, "assistant", "thinking out loud")
- # No events at all — assistant is process log: not streamed, not inbox.
- with pytest.raises(asyncio.TimeoutError):
- await asyncio.wait_for(queue.get(), timeout=0.1)
+ return await _drain_published(queue)
finally:
inbox_events.bus.unsubscribe(sub_id)
- return seen
- asyncio.run(scenario())
+ published = asyncio.run(scenario())
+ # Assistant is process log: neither streamed to the transcript nor inbox-eligible.
+ assert not (CONTENT_TOPICS & set(published))
# ...but the row IS still persisted (for history / debugging).
with engine.connect() as conn:
every = messages_service.list_session_messages(conn, session_id="ses_noresult", types=("assistant",))
@@ -599,12 +625,12 @@ def test_persist_agent_toolcall_avibe_writes_event_without_streaming(isolated_st
sub_id, queue = inbox_events.bus.subscribe()
try:
persist_agent_message(ctx, "tool_call", "Tool input failed to parse")
- with pytest.raises(asyncio.TimeoutError):
- await asyncio.wait_for(queue.get(), timeout=0.1)
+ return await _drain_published(queue)
finally:
inbox_events.bus.unsubscribe(sub_id)
- asyncio.run(scenario())
+ published = asyncio.run(scenario())
+ assert not (CONTENT_TOPICS & set(published))
with engine.connect() as conn:
message_row = conn.execute(select(messages).where(messages.c.session_id == "ses_tool")).first()
event_row = conn.execute(select(agent_events).where(agent_events.c.session_id == "ses_tool")).mappings().one()
@@ -646,17 +672,11 @@ def test_persist_agent_toolcall_publishes_when_activity_enabled(isolated_state,
async def scenario():
sub_id, queue = inbox_events.bus.subscribe()
- events: dict[str, dict] = {}
try:
persist_agent_message(ctx, "tool_call", "🔧 `Bash` `{\"command\":\"ls\"}`")
- evt = await asyncio.wait_for(queue.get(), timeout=1.0)
- events[evt[0]] = evt[1]
- # Only ONE event — no inbox bump for a trace row.
- with pytest.raises(asyncio.TimeoutError):
- await asyncio.wait_for(queue.get(), timeout=0.1)
+ return await _drain_published(queue)
finally:
inbox_events.bus.unsubscribe(sub_id)
- return events
events = asyncio.run(scenario())
assert "message.new" in events and "inbox.session.updated" not in events
@@ -701,16 +721,11 @@ def test_persist_agent_assistant_publishes_when_activity_enabled(isolated_state,
async def scenario():
sub_id, queue = inbox_events.bus.subscribe()
- events: dict[str, dict] = {}
try:
persist_agent_message(ctx, "assistant", "thinking out loud")
- evt = await asyncio.wait_for(queue.get(), timeout=1.0)
- events[evt[0]] = evt[1]
- with pytest.raises(asyncio.TimeoutError):
- await asyncio.wait_for(queue.get(), timeout=0.1)
+ return await _drain_published(queue)
finally:
inbox_events.bus.unsubscribe(sub_id)
- return events
events = asyncio.run(scenario())
assert "message.new" in events and "inbox.session.updated" not in events
@@ -767,15 +782,11 @@ def test_persist_agent_output_is_visible_without_activity_streaming(
async def scenario():
sub_id, queue = inbox_events.bus.subscribe()
- events: dict[str, dict] = {}
try:
persist_agent_message(ctx, "output", "primary answer")
- for _ in range(2):
- event = await asyncio.wait_for(queue.get(), timeout=1.0)
- events[event[0]] = event[1]
+ return await _drain_published(queue)
finally:
inbox_events.bus.unsubscribe(sub_id)
- return events
events = asyncio.run(scenario())
assert events["message.new"]["type"] == "output"
@@ -868,15 +879,11 @@ def test_persist_agent_terminal_notify_updates_inbox(isolated_state):
async def scenario():
sub_id, queue = inbox_events.bus.subscribe()
- events: dict[str, dict] = {}
try:
persist_agent_message(ctx, "notify", "❌ Claude error: boom")
- for _ in range(2): # message.new + inbox.session.updated, any order
- evt = await asyncio.wait_for(queue.get(), timeout=1.0)
- events[evt[0]] = evt[1]
+ return await _drain_published(queue)
finally:
inbox_events.bus.unsubscribe(sub_id)
- return events
events = asyncio.run(scenario())
assert "inbox.session.updated" in events
@@ -1058,12 +1065,16 @@ def test_background_standalone_persists_full_turn_without_realtime_delivery(isol
try:
mirror_harness_inbound(context, "background prompt")
persist_agent_message(context, "result", "background result")
- with pytest.raises(asyncio.TimeoutError):
- await asyncio.wait_for(queue.get(), timeout=0.1)
+ return await _drain_published(queue)
finally:
inbox_events.bus.unsubscribe(sub_id)
- asyncio.run(scenario())
+ published = asyncio.run(scenario())
+ # The property is "persisted but not DELIVERED", so it is asserted over the
+ # named content topics. Asserting the bus stayed silent would have read the
+ # contentless session-list rank event as a delivery while proving nothing
+ # more about content — the reason ``CONTENT_TOPICS`` exists.
+ assert not (CONTENT_TOPICS & set(published))
with engine.connect() as conn:
rows = conn.execute(
select(messages).where(messages.c.session_id == "ses_background").order_by(messages.c.author)
@@ -1223,3 +1234,263 @@ def test_avibe_inbound_is_noop(isolated_state):
with engine.connect() as conn:
rows = conn.execute(select(messages).where(messages.c.author == "user")).mappings().all()
assert rows == []
+
+
+# --- Session-list rank (agent output, no user input) ------------------
+
+
+def _seed_ranked_session(
+ session_id: str,
+ *,
+ last_active_at: str,
+ native_id: str,
+ status: str = "active",
+ visibility: str = "foreground",
+) -> str:
+ engine = create_sqlite_engine()
+ seeded = "2026-05-30T12:00:00Z"
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn, platform="avibe", scope_type="project", native_id=native_id, now=seeded
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id=session_id,
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_variant="default",
+ session_anchor=f"anchor_{session_id}",
+ native_session_id="",
+ status=status,
+ visibility=visibility,
+ metadata_json="{}",
+ created_at=seeded,
+ updated_at=seeded,
+ last_active_at=last_active_at,
+ )
+ )
+ return scope_id
+
+
+RANK_NOW = "2026-09-02T12:00:00Z"
+
+
+def _freeze_rank_clock(monkeypatch) -> None:
+ """Pin the rank helper's clock. Its stamp is both the value written and the
+ one the throttle compares against, so an unfrozen clock lets a second
+ boundary between the write and the assertion decide the result.
+ """
+
+ import storage.workbench_sessions_service as storage_sessions
+
+ monkeypatch.setattr(storage_sessions, "_utc_now_iso", lambda: RANK_NOW)
+
+
+def _publish_agent_message(
+ ctx: MessageContext, msg_type: str, text: str, **kwargs
+) -> dict[str, dict]:
+ from core import inbox_events
+
+ async def scenario():
+ sub_id, queue = inbox_events.bus.subscribe()
+ try:
+ persist_agent_message(ctx, msg_type, text, **kwargs)
+ return await _drain_published(queue)
+ finally:
+ inbox_events.bus.unsubscribe(sub_id)
+
+ return asyncio.run(scenario())
+
+
[email protected]("msg_type,text", [("tool_call", "🔧 `Bash`"), ("assistant", "still going")])
+def test_agent_output_ranks_the_session_and_announces_the_reorder(
+ isolated_state, monkeypatch, msg_type, text
+):
+ """Agent output alone moves the session's list rank and tells an open
+ browser to re-sort — the point of the change: nobody replied, and both a
+ chat row and a bare tool-call trace count as the agent working.
+ """
+ _freeze_rank_clock(monkeypatch)
+ sid = f"ses_rank_{msg_type}"
+ scope_id = _seed_ranked_session(sid, last_active_at="2020-01-01T00:00:00Z", native_id=f"p_{msg_type}")
+ ctx = MessageContext(
+ user_id="workbench",
+ channel_id=sid,
+ platform="avibe",
+ platform_specific={"agent_session_id": sid},
+ )
+
+ published = _publish_agent_message(ctx, msg_type, text)
+
+ assert published["session.activity"] == {
+ "session_id": sid,
+ "scope_id": scope_id,
+ "event": "agent_activity",
+ }
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ row = conn.execute(select(agent_sessions).where(agent_sessions.c.id == sid)).mappings().one()
+ assert row["last_active_at"] == RANK_NOW
+
+
+def test_agent_output_reorder_event_follows_the_rank_throttle(isolated_state, monkeypatch):
+ """The realtime reorder is published exactly when the rank moved, so the
+ burst of messages inside one throttle interval costs no events at all.
+ Gating on the write's own answer is what keeps the two in step without the
+ publisher tracking any state of its own.
+ """
+ _freeze_rank_clock(monkeypatch)
+ sid = "ses_rank_fresh"
+ _seed_ranked_session(sid, last_active_at=RANK_NOW, native_id="p_fresh")
+ ctx = MessageContext(
+ user_id="workbench",
+ channel_id=sid,
+ platform="avibe",
+ platform_specific={"agent_session_id": sid},
+ )
+
+ published = _publish_agent_message(ctx, "tool_call", "🔧 `Bash`")
+
+ assert "session.activity" not in published
+
+
+def test_agent_output_ranks_a_session_of_every_visibility(isolated_state, monkeypatch):
+ """Visibility is not part of the rank predicate — for every value it holds.
+
+ ``last_active_at`` is row state, and visibility is a MUTABLE display
+ preference where the archive is terminal: the session PATCH moves a row
+ between foreground and background and never backfills the stamp. A
+ background session is also a first-class agent-graph node ordered by this
+ very column, so holding its rank does not save a dead write — it leaves the
+ row mis-ordered for every later reader, including after it is restored.
+
+ Seeded over the whole storage vocabulary rather than over the one case a
+ reviewer named, and the expectation is derived from the rule ("every
+ visibility ranks") instead of written as a skip list, so a fourth visibility
+ is covered by construction. ``suppress_delivery`` is set the way its only
+ producer derives it, so the delivery flag that used to gate this is present
+ and demonstrably no longer decides.
+ """
+ _freeze_rank_clock(monkeypatch)
+ stale = "2020-01-01T00:00:00Z"
+ events: dict[str, dict] = {}
+ for visibility in sorted(SESSION_VISIBILITIES):
+ sid = f"ses_rank_vis_{visibility}"
+ _seed_ranked_session(
+ sid, last_active_at=stale, native_id=f"p_{visibility}", visibility=visibility
+ )
+ ctx = MessageContext(
+ user_id="workbench",
+ channel_id=sid,
+ platform="avibe",
+ platform_specific={
+ "agent_session_id": sid,
+ # Exactly how ``core/internal_server.py`` derives it for this path.
+ "suppress_delivery": visibility == "background",
+ },
+ )
+ events[visibility] = _publish_agent_message(ctx, "result", f"done {visibility}")
+
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ stamps = {
+ row["visibility"]: row["last_active_at"]
+ for row in conn.execute(select(agent_sessions)).mappings()
+ }
+ assert stamps == {visibility: RANK_NOW for visibility in SESSION_VISIBILITIES}
+ # The reorder announcement follows the rank rather than delivery, so the
+ # hidden row's re-sort reaches the one view that renders it.
+ assert {v: "session.activity" in e for v, e in events.items()} == {
+ visibility: True for visibility in SESSION_VISIBILITIES
+ }
+
+
+def test_replayed_output_that_persisted_nothing_does_not_rank(isolated_state, monkeypatch):
+ """The rank follows what materialized, not what was attempted.
+
+ A retried terminal output keeps its ``native_message_id``, so the append hits
+ the unique constraint and nothing new lands. Ranking there would let a replay
+ of one logical output lift a long-finished session back to the top of the
+ list on no new work at all.
+
+ The seeded stamp is stale, so the throttle would have allowed this write —
+ the only thing that can hold the rank is the materialized-row gate, which is
+ what makes this a test of that gate rather than of the throttle.
+ """
+ _freeze_rank_clock(monkeypatch)
+ sid = "ses_rank_replay"
+ stale = "2020-01-01T00:00:00Z"
+ scope_id = _seed_ranked_session(sid, last_active_at=stale, native_id="p_replay")
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=sid,
+ platform="avibe",
+ author="agent",
+ source="agent",
+ message_type="result",
+ text="done",
+ native_message_id="receipt_1",
+ )
+ ctx = MessageContext(
+ user_id="workbench",
+ channel_id=sid,
+ platform="avibe",
+ platform_specific={"agent_session_id": sid},
+ )
+
+ published = _publish_agent_message(ctx, "result", "done", native_message_id="receipt_1")
+
+ assert "session.activity" not in published
+ with engine.connect() as conn:
+ row = conn.execute(select(agent_sessions).where(agent_sessions.c.id == sid)).mappings().one()
+ assert row["last_active_at"] == stale
+
+
+def test_im_agent_output_ranks_the_row_without_publishing(isolated_state, monkeypatch):
+ """``vibe session list``, the run graph and the running-agents view read the
+ same rank for every platform, so the row is ranked there too — while the
+ SSE stays avibe-only like every other publish on this path, an IM session
+ having no open browser consumer.
+ """
+ _freeze_rank_clock(monkeypatch)
+ engine = create_sqlite_engine()
+ seeded = "2026-05-30T12:00:00Z"
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn, platform="slack", scope_type="channel", native_id="C_rank", now=seeded
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_rank_im",
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_variant="default",
+ session_anchor="anchor_ses_rank_im",
+ native_session_id="",
+ status="active",
+ metadata_json="{}",
+ created_at=seeded,
+ updated_at=seeded,
+ last_active_at="2020-01-01T00:00:00Z",
+ )
+ )
+
+ ctx = MessageContext(
+ user_id="U_alice",
+ channel_id="C_rank",
+ platform="slack",
+ platform_specific={"agent_session_id": "ses_rank_im"},
+ )
+ published = _publish_agent_message(ctx, "result", "done")
+
+ assert "session.activity" not in published
+ with engine.connect() as conn:
+ row = (
+ conn.execute(select(agent_sessions).where(agent_sessions.c.id == "ses_rank_im"))
+ .mappings()
+ .one()
+ )
+ assert row["last_active_at"] == RANK_NOW
diff --git a/ui/src/context/WorkbenchProjectsProvider.tsx b/ui/src/context/WorkbenchProjectsProvider.tsx
index aefc55bf1..4a50ed656 100644
--- a/ui/src/context/WorkbenchProjectsProvider.tsx
+++ b/ui/src/context/WorkbenchProjectsProvider.tsx
@@ -121,7 +121,16 @@ function removeSessionRow(
return changed ? next : prev;
}
-const REORDER_ACTIVITY_EVENTS = new Set(['created', 'user_message', 'show_event']);
+// `agent_activity`: the agent produced output with nobody replying, so the row's
+// rank moved on its own. Rate-limited at the source (one per minute per session,
+// see storage.workbench_sessions_service.touch_session_agent_activity), which is
+// why an event that fires on agent output can drive a reconcile at all.
+const REORDER_ACTIVITY_EVENTS = new Set([
+ 'created',
+ 'user_message',
+ 'show_event',
+ 'agent_activity',
+]);
// Single source of truth for the workbench projects/sessions tree. The desktop
// WorkbenchSidebar (always mounted) and the mobile ProjectsPage (route) both