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.

feat(core): mirror non-avibe IM messages into the workbench store

cyh920a5130b0eb
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 1dfcbdb6b..29325085a 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -124,6 +124,14 @@ class MessageHandler(BaseHandler):
context = await self._prepare_turn_context(context, source)
+ # Mirror the user's message into the workbench messages table
+ # before we kick off the agent. Wrapped in try/except inside
+ # the helper so a mirror failure can't take down the turn.
+ if source == self.TURN_SOURCE_HUMAN:
+ from core.message_mirror import mirror_inbound
+
+ mirror_inbound(context, control_message)
+
base_session_id, working_path, composite_key = self.session_handler.get_session_info(context, source=source)
payload = dict(context.platform_specific or {})
payload["turn_source"] = source
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index c349ff500..dfdf81626 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -13,6 +13,7 @@ from typing import Optional
from config.platform_registry import get_platform_descriptor
from modules.im import MessageContext
+from core.message_mirror import mirror_outbound
from core.reply_enhancer import process_reply, strip_file_links, strip_silent_blocks
from storage.background import SQLiteBackgroundTaskStore
from vibe.i18n import t as i18n_t
@@ -349,7 +350,9 @@ class ConsolidatedMessageDispatcher:
if canonical_type == "notify":
target_context = self._get_target_context(context)
try:
- return await im_client.send_message(target_context, text, parse_mode=parse_mode)
+ 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")
+ return message_id
except Exception as err:
logger.error("Failed to send notify message: %s", err)
return None
@@ -497,6 +500,14 @@ class ConsolidatedMessageDispatcher:
# a fresh log message instead of appending to the previous one.
await self._clear_consolidated_state(context)
+ if primary_message_id and display_text:
+ mirror_outbound(
+ context,
+ display_text,
+ native_message_id=primary_message_id,
+ kind="result",
+ )
+
return primary_message_id
if canonical_type not in {"system", "assistant", "toolcall"}:
diff --git a/core/message_mirror.py b/core/message_mirror.py
new file mode 100644
index 000000000..1cf4feb60
--- /dev/null
+++ b/core/message_mirror.py
@@ -0,0 +1,141 @@
+"""Best-effort mirror of inbound + outbound IM traffic into ``messages``.
+
+This is the cross-platform write path that feeds the workbench: every
+non-avibe IM event (Slack DM, Discord channel reply, Telegram private
+chat, Lark/Feishu group ping, WeChat push) lands a row in the same
+``messages`` table that avibe sessions write to. Downstream views — the
+Inbox feed, per-session transcript, future cross-platform search — read
+from one shape regardless of origin.
+
+Hooks live in two places:
+
+* ``core/handlers/message_handler.py`` calls :func:`mirror_inbound` once
+ per human-originated turn, after session resolution.
+* ``core/message_dispatcher.py`` calls :func:`mirror_outbound` once per
+ successful agent ``result`` / ``notify`` send.
+
+Failures are swallowed and logged. A bad mirror write must never break
+the live IM reply path.
+"""
+
+from __future__ import annotations
+
+import logging
+from datetime import datetime, timezone
+from typing import Optional
+
+from sqlalchemy.exc import IntegrityError
+
+from modules.im.base import MessageContext
+from storage import messages_service, settings_service
+from storage.db import create_sqlite_engine
+
+logger = logging.getLogger(__name__)
+
+# Non-avibe IM scopes are stored as 'channel' rows — one per DM/group/topic.
+# avibe projects are 'project' typed and pre-created via ``/api/projects``;
+# this module never touches those.
+DEFAULT_SCOPE_TYPE = "channel"
+
+
+def _now() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _resolve_scope_id(conn, context: MessageContext) -> Optional[str]:
+ platform = (context.platform or "").strip()
+ native_id = (context.channel_id or "").strip()
+ if not platform or not native_id:
+ return None
+ try:
+ return settings_service.upsert_scope(
+ conn,
+ platform=platform,
+ scope_type=DEFAULT_SCOPE_TYPE,
+ native_id=native_id,
+ now=_now(),
+ supports_threads=bool(context.thread_id),
+ )
+ except Exception:
+ logger.exception("mirror: failed to upsert scope for %s::%s", platform, native_id)
+ return None
+
+
+def _append_quietly(conn, **kwargs) -> None:
+ """Insert one row, swallowing the unique-constraint clash that fires
+ when the same native message id is delivered twice (rare retry path).
+ """
+ try:
+ messages_service.append(conn, **kwargs)
+ except IntegrityError:
+ logger.debug(
+ "mirror: skipped duplicate native_message_id %s on platform %s",
+ kwargs.get("native_message_id"),
+ kwargs.get("platform"),
+ )
+
+
+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:
+ return
+ if context.platform == "avibe":
+ # avibe's REST endpoint already writes through ``messages_service``;
+ # mirroring here would double-count the row.
+ return
+ try:
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _resolve_scope_id(conn, context)
+ if scope_id is None:
+ return
+ _append_quietly(
+ conn,
+ scope_id=scope_id,
+ session_id=None,
+ platform=context.platform,
+ author="user",
+ text=text,
+ author_id=context.user_id,
+ native_message_id=context.message_id,
+ parent_native_message_id=context.thread_id,
+ )
+ except Exception:
+ logger.exception("mirror_inbound: unexpected 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."""
+
+ if not text or not text.strip():
+ return
+ if not context.platform or context.platform == "avibe":
+ return
+ try:
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _resolve_scope_id(conn, context)
+ if scope_id is None:
+ return
+ _append_quietly(
+ conn,
+ scope_id=scope_id,
+ session_id=None,
+ platform=context.platform,
+ author="agent",
+ text=text,
+ native_message_id=native_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)
diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.py
new file mode 100644
index 000000000..ba10cd9b9
--- /dev/null
+++ b/tests/test_message_mirror.py
@@ -0,0 +1,116 @@
+"""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.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+from sqlalchemy import select
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from core.message_mirror import mirror_inbound, mirror_outbound
+from modules.im import MessageContext
+from storage.db import create_sqlite_engine
+from storage.importer import ensure_sqlite_state
+from storage.models import messages, scopes
+
+
+def isolated_state(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ yield tmp_path
+
+
+def _slack_ctx(message_id="m_001") -> MessageContext:
+ return MessageContext(
+ user_id="U_alice",
+ channel_id="C_general",
+ platform="slack",
+ thread_id=None,
+ message_id=message_id,
+ )
+
+
+def test_inbound_creates_scope_and_user_row(isolated_state):
+ mirror_inbound(_slack_ctx(), "hello there")
+
+ 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_general")
+ ).mappings().first()
+ assert scope_row is not None
+ assert scope_row["scope_type"] == "channel"
+
+ message_rows = conn.execute(
+ select(messages).where(messages.c.platform == "slack")
+ ).mappings().all()
+ assert len(message_rows) == 1
+ assert message_rows[0]["author"] == "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):
+ ctx = _slack_ctx()
+ mirror_inbound(ctx, "ping")
+ mirror_outbound(ctx, "pong", native_message_id="slack_m_002", kind="result")
+
+ 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)
+ ).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"]
+
+
+def test_duplicate_native_message_id_is_swallowed(isolated_state):
+ ctx = _slack_ctx(message_id="dup_id")
+ mirror_inbound(ctx, "first")
+ mirror_inbound(ctx, "duplicate delivery")
+
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ rows = conn.execute(select(messages).where(messages.c.platform == "slack")).mappings().all()
+ # Unique (platform, native_message_id) constraint keeps the second
+ # write from materializing.
+ assert len(rows) == 1
+ 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",
+ platform="avibe",
+ message_id="avibe_001",
+ )
+ mirror_inbound(avibe_ctx, "this should not land")
+ mirror_outbound(avibe_ctx, "neither should this", native_message_id="avibe_002")
+
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ rows = conn.execute(select(messages)).mappings().all()
+ assert rows == []