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): address Codex review on PR #339

cyh97481e79ca13
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index dfdf81626..15e2b20f7 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -351,7 +351,12 @@ class ConsolidatedMessageDispatcher:
target_context = self._get_target_context(context)
try:
message_id = await im_client.send_message(target_context, text, parse_mode=parse_mode)
- mirror_outbound(context, text, native_message_id=message_id, kind="notify")
+ # ``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")
return message_id
except Exception as err:
logger.error("Failed to send notify message: %s", err)
@@ -501,8 +506,10 @@ class ConsolidatedMessageDispatcher:
await self._clear_consolidated_state(context)
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(
- context,
+ target_context,
display_text,
native_message_id=primary_message_id,
kind="result",
diff --git a/storage/messages_service.py b/storage/messages_service.py
index ef02722c8..9e8fa6196 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -229,7 +229,19 @@ def mark_session_read(
select(messages.c.created_at).where(messages.c.id == until_message_id)
).scalar_one_or_none()
if anchor is not None:
- base = base.where(messages.c.created_at <= anchor)
+ # ``created_at`` is stored at second precision, so a bare
+ # ``<= anchor`` would also mark newer messages created in the
+ # same second as read. Tie-break on ``id`` so only rows at-or-
+ # before the anchor message itself are affected.
+ base = base.where(
+ or_(
+ messages.c.created_at < anchor,
+ and_(
+ messages.c.created_at == anchor,
+ messages.c.id <= until_message_id,
+ ),
+ )
+ )
result = conn.execute(base)
return result.rowcount or 0
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index dad18452d..e5ea4530c 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -92,17 +92,27 @@ def list_sessions(
).first()
if cursor_row is not None:
cursor_active, cursor_created = cursor_row
+ # ``last_active_at`` + ``created_at`` are both second-granularity
+ # ISO strings, so multiple sessions can share the same pair and
+ # become unreachable on later pages without an ``id`` tie-breaker
+ # that matches the ORDER BY shape.
query = query.where(
(agent_sessions.c.last_active_at < cursor_active)
| (
(agent_sessions.c.last_active_at == cursor_active)
& (agent_sessions.c.created_at < cursor_created)
)
+ | (
+ (agent_sessions.c.last_active_at == cursor_active)
+ & (agent_sessions.c.created_at == cursor_created)
+ & (agent_sessions.c.id < before_id)
+ )
)
query = (
query.order_by(
agent_sessions.c.last_active_at.desc(),
agent_sessions.c.created_at.desc(),
+ agent_sessions.c.id.desc(),
)
.limit(min(max(int(limit), 1), 200))
)
diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.py
index ba10cd9b9..aca6a365d 100644
--- a/tests/test_message_mirror.py
+++ b/tests/test_message_mirror.py
@@ -114,3 +114,31 @@ def test_avibe_platform_is_noop(isolated_state):
with engine.connect() as conn:
rows = conn.execute(select(messages)).mappings().all()
assert rows == []
+
+
+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.
+ """
+ delivery_ctx = MessageContext(
+ user_id="agent",
+ channel_id="C_delivery", # different from any inbound channel
+ platform="slack",
+ thread_id=None,
+ message_id=None,
+ )
+ mirror_outbound(delivery_ctx, "agent reply", native_message_id="slack_out_42", kind="result")
+
+ 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"]
diff --git a/tests/test_messages_service.py b/tests/test_messages_service.py
new file mode 100644
index 000000000..6bae06ec1
--- /dev/null
+++ b/tests/test_messages_service.py
@@ -0,0 +1,137 @@
+"""Focused tests for storage.messages_service behaviours that are easy to
+regress: pagination cursor and the ``mark_session_read`` boundary check.
+"""
+
+from __future__ import annotations
+
+import sys
+import time
+from pathlib import Path
+
+import pytest
+from sqlalchemy import select
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from storage import messages_service
+from storage.db import create_sqlite_engine
+from storage.importer import ensure_sqlite_state
+from storage.models import agent_sessions, messages
+from storage.settings_service import upsert_scope
+
+
+def isolated_state(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ yield tmp_path
+
+
+def _seed_scope(conn) -> str:
+ now = messages_service._utc_now_iso()
+ return upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_test", now=now)
+
+
+def _seed_session(conn, scope_id: str, session_id: 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="",
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+
+
+def test_mark_session_read_ties_break_on_id(isolated_state):
+ """When ``until_message_id`` points at a message whose ``created_at``
+ is shared by newer messages (second precision), only rows at-or-before
+ the anchor *by id* should be marked read. Otherwise the user's still-
+ unread newest reply gets cleared.
+ """
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_test")
+ # Use a fixed timestamp so all three rows share the same created_at
+ # (mimicking the second-precision collision).
+ fixed_now = "2026-05-26T13:00:00Z"
+ for content in ("first", "second", "third"):
+ payload = {
+ "id": messages_service._new_message_id(),
+ "scope_id": scope_id,
+ "session_id": "ses_test",
+ "platform": "avibe",
+ "author": "agent",
+ "author_id": None,
+ "author_name": None,
+ "native_message_id": None,
+ "parent_native_message_id": None,
+ "content_text": content,
+ "content_json": "{}",
+ "metadata_json": "{}",
+ "created_at": fixed_now,
+ "updated_at": fixed_now,
+ "delivered_at": None,
+ "read_at": None,
+ }
+ conn.execute(messages.insert().values(**payload))
+
+ with engine.connect() as conn:
+ ordered = conn.execute(
+ select(messages.c.id, messages.c.content_text)
+ .where(messages.c.session_id == "ses_test")
+ .order_by(messages.c.id.asc())
+ ).all()
+ # Take the middle row as the anchor: its lexicographically-smaller
+ # id puts "first" before it and one row after it.
+ anchor_id = ordered[1][0]
+ anchor_text = ordered[1][1]
+
+ with engine.begin() as conn:
+ updated = messages_service.mark_session_read(conn, "ses_test", until_message_id=anchor_id)
+
+ assert updated == 2, "should mark only the anchor + the row with smaller id"
+
+ with engine.connect() as conn:
+ rows = conn.execute(
+ select(messages.c.content_text, messages.c.read_at)
+ .where(messages.c.session_id == "ses_test")
+ .order_by(messages.c.id.asc())
+ ).all()
+ read_states = {text: (read_at is not None) for text, read_at in rows}
+ # The two rows up to and including the anchor are marked read…
+ assert read_states[anchor_text] is True
+ # …and the row with the larger id (same timestamp) stays unread.
+ unread = [text for text, read in read_states.items() if not read]
+ assert len(unread) == 1, "exactly one row after the anchor must remain unread"
+
+
+def test_mark_session_read_without_anchor_marks_all(isolated_state):
+ """No ``until_message_id`` → mark every unread agent row."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_all")
+ for _ in range(3):
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_all",
+ platform="avibe",
+ author="agent",
+ text="payload",
+ )
+ time.sleep(0.001)
+
+ with engine.begin() as conn:
+ updated = messages_service.mark_session_read(conn, "ses_all")
+ assert updated == 3