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(bots): bridge mutations to open Web clients (#3124)

Call White69c315ab8603
diff --git a/core/bots.py b/core/bots.py
index 31a15e7eb..209d5fe33 100644
--- a/core/bots.py
+++ b/core/bots.py
@@ -38,6 +38,7 @@ from core.vibe_agents import (
is_main_bot_agent,
normalize_agent_name,
)
+from core.inbox_events import publish_bots_changed
from storage.agent_session_rows import BOT_SESSION_ID_PREFIX, is_bot_session_id, reserve_write_lock
from storage.agent_session_rows import hidden_bot_session_ids as stored_hidden_bot_session_ids
from storage.models import agent_sessions, agents
@@ -524,6 +525,7 @@ class BotService:
bot = bot_from_agent(agent)
assert bot is not None
self.ensure_home(bot, authorization_context=context)
+ publish_bots_changed(bot.handle)
return bot
def set_bot(
@@ -587,6 +589,7 @@ class BotService:
bot = bot_from_agent(agent)
assert bot is not None
self.ensure_home(bot, authorization_context=context)
+ publish_bots_changed(bot.handle)
return bot
def update_bot(
@@ -618,7 +621,9 @@ class BotService:
self._move(conn, bot.agent.id, position)
if display_name is not ...:
self._sync_session_title(conn, bot.session_id, record["display_name"])
- return self._require_bot(conn, handle)
+ updated = self._require_bot(conn, handle)
+ publish_bots_changed(handle)
+ return updated
def remove_bot(self, handle: str, *, authorization_context: Any = None) -> Bot:
"""Drop the Bot role, keeping the Agent, the Session, and the directory (D4 ``remove``)."""
@@ -633,7 +638,8 @@ class BotService:
record["removed_at"] = _now()
self._write_record(conn, bot.agent, record)
self._compact_positions(conn)
- return bot
+ publish_bots_changed(handle)
+ return bot
def set_avatar_image(self, handle: str, data: bytes, *, authorization_context: Any = None) -> Bot:
"""Store an uploaded avatar as ``avatar.png`` in the Bot's directory, scaled to 256px (D5)."""
@@ -651,7 +657,9 @@ class BotService:
record = dict(agent_bot_record(bot.agent) or {})
record["avatar"] = {"kind": "image"}
self._write_record(conn, bot.agent, record)
- return self._require_bot(conn, handle)
+ updated = self._require_bot(conn, handle)
+ publish_bots_changed(handle)
+ return updated
def avatar_path(self, handle: str, *, authorization_context: Any = None) -> Path:
bot = self.get_bot(handle, authorization_context=authorization_context)
diff --git a/core/inbox_events.py b/core/inbox_events.py
index 61eba6e3c..9230e8e6d 100644
--- a/core/inbox_events.py
+++ b/core/inbox_events.py
@@ -19,6 +19,7 @@ from typing import Any, Callable
logger = logging.getLogger(__name__)
+BOTS_CHANGED_EVENT = "bots.changed"
RUNS_UPDATED_EVENT = "runs.updated"
VAULTS_UPDATED_EVENT = "vaults.updated"
QUEUE_UPDATED_EVENT = "queue.updated"
@@ -209,6 +210,37 @@ def publish_run_updated(**kwargs: Any) -> None:
bus.publish(RUNS_UPDATED_EVENT, run_updated_payload(**kwargs))
+def publish_bots_changed(handle: str) -> None:
+ """Refetch the Owner's Bot list after commit, regardless of the writer's process.
+
+ Controller writes use its bus. Other writers reuse the internal events bridge,
+ with immediate local delivery (also when the controller is down) and the same
+ echo suppression as Vault updates. No route or CLI command publishes again.
+ """
+ payload = {"handle": handle}
+ if is_controller_process():
+ bus.publish(BOTS_CHANGED_EVENT, payload)
+ return
+
+ from uuid import uuid4
+
+ from vibe.inbox_bridge import remember_local_event
+ from vibe.sse_broker import broker
+
+ event_id = uuid4().hex
+ remember_local_event(event_id)
+ broker.publish(BOTS_CHANGED_EVENT, payload)
+ try:
+ from vibe import internal_client
+
+ internal_client.publish_event_sync(
+ BOTS_CHANGED_EVENT, {**payload, "_event_id": event_id}, timeout=1.5
+ )
+ except Exception:
+ # The durable mutation succeeded. Reconnection makes clients re-read it.
+ logger.debug("bots.changed bridge publish failed", exc_info=True)
+
+
def publish_definitions_updated(*, definition_type: str) -> None:
"""Publish a payload-free scheduling hint after a definition commit."""
diff --git a/core/internal_server.py b/core/internal_server.py
index f445d9174..34823b151 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -1839,6 +1839,7 @@ def create_app(
same Controller -> UI-server -> browser SSE path.
"""
from core.inbox_events import (
+ BOTS_CHANGED_EVENT,
DEFINITIONS_UPDATED_EVENT,
QUEUE_UPDATED_EVENT,
RUNS_UPDATED_EVENT,
@@ -1852,6 +1853,7 @@ def create_app(
event_type = str(payload.get("type") or "").strip()
data = payload.get("data")
if event_type not in {
+ BOTS_CHANGED_EVENT,
DEFINITIONS_UPDATED_EVENT,
QUEUE_UPDATED_EVENT,
RUNS_UPDATED_EVENT,
diff --git a/core/vibe_agents.py b/core/vibe_agents.py
index ca70259ef..18d34c140 100644
--- a/core/vibe_agents.py
+++ b/core/vibe_agents.py
@@ -1196,7 +1196,14 @@ class VibeAgentStore:
updated = conn.execute(
select(agents).where(agents.c.id == existing.id).limit(1)
).mappings().one()
- return self._from_row(updated)
+ agent = self._from_row(updated)
+ # The Bot role is its Agent description, including edits through Agent APIs/CLI.
+ record = agent_bot_record(agent)
+ if record is not None and agent.description != existing.description:
+ from core.inbox_events import publish_bots_changed
+
+ publish_bots_changed(str(record["handle"]))
+ return agent
def set_enabled(self, name: str, enabled: bool, *, user_context: Any = None) -> VibeAgent:
return self.update(name, enabled=enabled, user_context=user_context)
@@ -1903,9 +1910,14 @@ class VibeAgentStore:
record = current.metadata.get(BOT_METADATA_KEY)
record = dict(record) if isinstance(record, dict) else {}
restored = {**_main_bot_record(), **{key: record[key] for key in ("display_name", "avatar") if key in record}}
- return self._write_builtin_state(
+ updated = self._write_builtin_state(
current, metadata={**current.metadata, BOT_METADATA_KEY: restored}, enabled=True
)
+ if current.metadata.get(BOT_METADATA_KEY) != restored:
+ from core.inbox_events import publish_bots_changed
+
+ publish_bots_changed(MAIN_BOT_HANDLE)
+ return updated
vibey = self.get_builtin_default_agent_for_backend("vibey", enabled_only=False)
def only_one(conn: Connection, _agent: VibeAgent) -> None:
@@ -1921,7 +1933,7 @@ class VibeAgentStore:
raise _MainBotExists()
try:
- return self._create(
+ created = self._create(
name=self._free_agent_name(MAIN_BOT_AGENT_NAME),
backend="vibey",
description=MAIN_BOT_DESCRIPTION,
@@ -1938,6 +1950,10 @@ class VibeAgentStore:
if current is None:
raise
return current
+ from core.inbox_events import publish_bots_changed
+
+ publish_bots_changed(MAIN_BOT_HANDLE)
+ return created
def get_builtin_default_agent_for_backend(self, backend: str, *, enabled_only: bool = True) -> Optional[VibeAgent]:
"""The backend's built-in Agent: the one owner of built-in identity.
diff --git a/docs/plans/bots.md b/docs/plans/bots.md
index c41ba7b35..df4455dd1 100644
--- a/docs/plans/bots.md
+++ b/docs/plans/bots.md
@@ -390,6 +390,19 @@ You are `@<bot:memory>`, the background memory of the user's Bots, above all of
The contract the Web UI builds on. Every route requires the instance owner.
+All Bot mutations publish one owner-only `bots.changed` invalidation after commit,
+from the shared service rather than the Web routes. CLI writers use the existing
+internal event socket and controller-to-UI inbox bridge; controller writers use
+the controller bus. UI writers also deliver locally (including when the controller
+is offline), suppressing their own bridge echo. Editing a Bot Agent's description
+publishes the same event because it changes the Bot's role; unchanged descriptions
+and list reads do not. An active Bot's Agent cannot be renamed.
+
+Replacing `avatar.png` directly is not a Bot API mutation and has no filesystem
+watcher. The image URL already includes its file mtime, so the next Bot-list fetch
+(including stream reconnection) picks up a replacement. Uploading through the Bot
+API invalidates immediately.
+
| Route | Purpose |
| --- | --- |
| `GET /api/bots` | Bots in display order: handle, display name (empty means the localized default for the main Bot), avatar (`emoji` with hue, `image` with URL, or the main Bot's mascot), role, Agent name, Session id, position, built-in flag |
diff --git a/tests/test_bot_events.py b/tests/test_bot_events.py
new file mode 100644
index 000000000..e3507bd64
--- /dev/null
+++ b/tests/test_bot_events.py
@@ -0,0 +1,239 @@
+"""Bot invalidation crosses the CLI/controller/UI process boundary once per mutation.
+
+The old route-only publisher left a connected browser stale after CLI mutations.
+Exercise the real CLI, internal event socket, bridge, and browser SSE generator;
+ordinary Bot CRUD tests only checked the new rows or the HTTP response.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import io
+import json
+import os
+import sys
+import tempfile
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from core import inbox_events
+from core.bots import BotService
+from storage.importer import ensure_sqlite_state
+from tests.ui_server_test_helpers import csrf_headers
+from vibe import inbox_bridge, internal_client, ui_server
+from vibe.authorization import instance_owner_context
+from vibe.ui_compat import g
+
+
+def home(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ monkeypatch.setattr(inbox_events, "_CONTROLLER_PROCESS", False)
+ ensure_sqlite_state()
+ with BotService() as service:
+ service.store.ensure_builtin_default_agents([])
+ return tmp_path
+
+
+async def _live_bridge(monkeypatch):
+ # Keep AF_UNIX paths short on macOS. All persistent state stays in the test home.
+ with tempfile.TemporaryDirectory(prefix="bot-events-", dir="/tmp") as socket_dir:
+ socket_path = str(Path(socket_dir) / "events.sock")
+ monkeypatch.setenv("VIBE_INTERNAL_DISPATCH_SOCKET", socket_path)
+ controller = await asyncio.create_subprocess_exec(
+ sys.executable,
+ "-c",
+ "from types import SimpleNamespace; from pathlib import Path; import sys, asyncio; "
+ "from core.internal_server import serve; "
+ "asyncio.run(serve(SimpleNamespace(), socket_path=Path(sys.argv[1])))",
+ socket_path,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ monkeypatch.setattr(inbox_bridge, "_bridge_connected", False)
+ monkeypatch.setattr(inbox_bridge, "_BACKOFF_INITIAL", 0.02)
+ bridge = asyncio.create_task(inbox_bridge.run_inbox_bridge())
+ try:
+ async with asyncio.timeout(15):
+ while not inbox_bridge.is_bridge_connected():
+ if controller.returncode is not None:
+ _, stderr = await controller.communicate()
+ pytest.fail(stderr.decode())
+ await asyncio.sleep(0.02)
+ yield
+ except TimeoutError:
+ if controller.returncode is None:
+ controller.terminate()
+ _, stderr = await asyncio.wait_for(controller.communicate(), timeout=5)
+ pytest.fail(f"controller/bridge timed out: {stderr.decode()}")
+ finally:
+ bridge.cancel()
+ with contextlib.suppress(asyncio.CancelledError):
+ await bridge
+ if controller.returncode is None:
+ controller.terminate()
+ try:
+ await asyncio.wait_for(controller.communicate(), timeout=5)
+ except TimeoutError:
+ controller.kill()
+ await controller.communicate()
+
+
+async def _browser_events():
+ with ui_server.app.test_request_context("/api/events"):
+ g.authorization_context = instance_owner_context()
+ response = await ui_server.workbench_events()
+ iterator = response.body_iterator.__aiter__()
+ try:
+ for _ in range(3):
+ await anext(iterator)
+ yield iterator
+ finally:
+ await iterator.aclose()
+
+
+async def _bot_events_through_barrier(iterator):
+ # This goes through the same ordered controller feed. Reading it proves that
+ # an echoed Web event has reached the bridge, rather than guessing with sleep.
+ await internal_client.publish_event("definitions.updated", {"definition_type": "watch"})
+ events = []
+ async with asyncio.timeout(5):
+ async for chunk in iterator:
+ text = chunk.decode() if isinstance(chunk, bytes) else chunk
+ if "event: definitions.updated\n" in text:
+ return events
+ if "event: bots.changed\n" in text:
+ data = next(line[6:] for line in text.splitlines() if line.startswith("data: "))
+ events.append(json.loads(data)["data"])
+ raise AssertionError("browser stream ended before the barrier")
+
+
+async def _cli(*args):
+ child = await asyncio.create_subprocess_exec(
+ sys.executable, "-c", "from vibe.cli import main; main()", *args,
+ env=dict(os.environ), stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
+ )
+ try:
+ stdout, stderr = await asyncio.wait_for(child.communicate(), timeout=20)
+ except BaseException:
+ if child.returncode is None:
+ child.kill()
+ await child.communicate()
+ raise
+ assert child.returncode == 0, (stdout.decode(), stderr.decode())
+ return json.loads(stdout)
+
+
[email protected](sys.platform == "win32", reason="Exercises the Unix-domain IPC transport")
[email protected]("entry", ["cli", "web"])
+async def test_bot_mutations_reach_a_connected_browser_once(home, monkeypatch, entry):
+ """Committed CLI/Web writes produce one browser event, including Web's IPC echo."""
+ client = ui_server.app.test_client()
+
+ def web(method, path, **kwargs):
+ response = getattr(client, method)(path, headers=csrf_headers(client), **kwargs)
+ assert response.status_code < 300, response.get_json()
+ return response.get_json()
+
+ async def mutate(cli_args, method, path, payload=None):
+ if entry == "cli":
+ return await _cli(*cli_args)
+ return await asyncio.to_thread(web, method, path, json=payload)
+
+ async with _live_bridge(monkeypatch), _browser_events() as events:
+ operations = [
+ (("bot", "create", "--name", "Researcher", "--handle", "researcher"),
+ "post", "/api/bots", {"display_name": "Researcher", "handle": "researcher"}),
+ (("bot", "update", "researcher", "--name", "Scholar", "--position", "1"),
+ "patch", "/api/bots/researcher", {"display_name": "Scholar", "position": 1}),
+ (("bot", "update", "researcher", "--emoji", "R", "--hue", "210"),
+ "patch", "/api/bots/researcher", {"avatar": {"emoji": "R", "hue": 210}}),
+ (("bot", "remove", "researcher"), "delete", "/api/bots/researcher", None),
+ (("bot", "set", "researcher", "--name", "Scholar"),
+ "post", "/api/bots/set", {"agent_name": "researcher", "display_name": "Scholar"}),
+ ]
+ for cli_args, method, path, payload in operations:
+ await mutate(cli_args, method, path, payload)
+ received = await _bot_events_through_barrier(events)
+ assert len(received) == 1, received
+ assert received[0]["handle"] == "researcher"
+ listed = await asyncio.to_thread(client.get, "/api/bots")
+ bots = listed.get_json()["bots"]
+ if method == "delete":
+ assert [bot["handle"] for bot in bots] == ["main"]
+ else:
+ assert bots[-1]["display_name"] == ("Researcher" if path == "/api/bots" else "Scholar")
+
+ # Agent edits share the same role field. Previously these also stayed stale.
+ await _cli("agent", "update", "researcher", "--description", "Reviews evidence.")
+ received = await _bot_events_through_barrier(events)
+ assert len(received) == 1 and received[0]["handle"] == "researcher"
+ listed = await asyncio.to_thread(client.get, "/api/bots")
+ assert listed.get_json()["bots"][-1]["role"] == "Reviews evidence."
+
+ if entry == "web":
+ image = io.BytesIO()
+ Image.new("RGB", (8, 8), "blue").save(image, format="PNG")
+ uploaded = await asyncio.to_thread(web, "put", "/api/bots/researcher/avatar", content=image.getvalue())
+ received = await _bot_events_through_barrier(events)
+ assert len(received) == 1 and received[0]["handle"] == "researcher"
+ assert uploaded["bot"]["avatar"]["kind"] == "image"
+
+ # A failed transaction, an unchanged role, and a list read are not changes.
+ refused = await asyncio.to_thread(
+ client.patch, "/api/bots/researcher", json={"display_name": "Rolled back", "position": -1},
+ headers=csrf_headers(client),
+ )
+ assert refused.status_code == 400
+ await _cli("agent", "update", "researcher", "--description", "Reviews evidence.")
+ assert await _bot_events_through_barrier(events) == []
+
+
+async def test_controller_bot_mutation_publishes_after_commit_without_ipc(home, monkeypatch):
+ """Controller writers must not synchronously call their own socket or publish twice."""
+ monkeypatch.setattr(inbox_events, "_CONTROLLER_PROCESS", True)
+
+ def no_socket(*args, **kwargs):
+ pytest.fail("controller attempted an IPC round trip to itself")
+
+ monkeypatch.setattr(internal_client, "publish_event_sync", no_socket)
+ snapshots = []
+
+ def observe_commit(event_type, payload):
+ if event_type == "bots.changed":
+ with BotService() as reader:
+ snapshots.append(reader.get_bot(payload["handle"]).display_name)
+
+ callback_id = inbox_events.bus.subscribe_callback(observe_commit)
+ sub_id, queue = inbox_events.bus.subscribe()
+ try:
+ with BotService() as service:
+ await asyncio.to_thread(service.create_bot, display_name="Researcher")
+ event_type, payload = await asyncio.wait_for(queue.get(), timeout=1)
+ assert (event_type, payload) == ("bots.changed", {"handle": "researcher"})
+ assert snapshots == ["Researcher"]
+ assert queue.empty()
+ finally:
+ inbox_events.bus.unsubscribe(sub_id)
+ inbox_events.bus.unsubscribe(callback_id)
+
+
+async def test_web_bot_update_still_reaches_browser_without_controller(home):
+ """The shared publisher preserves Web-local delivery when IPC is unavailable."""
+ client = ui_server.app.test_client()
+ async with _browser_events() as events:
+ response = await asyncio.to_thread(
+ client.post, "/api/bots", json={"display_name": "Researcher"}, headers=csrf_headers(client),
+ )
+ assert response.status_code == 201
+ frame = await asyncio.wait_for(anext(events), timeout=1)
+ assert "event: bots.changed\n" in frame
+ assert '"handle":"researcher"' in frame
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 466c6c8d5..590f4d5b9 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -10155,13 +10155,6 @@ def _bot_owner_context():
return require_instance_role(getattr(g, "authorization_context", None), "owner")
-def _publish_bots_changed(handle: str | None = None) -> None:
- """Tell the Owner's open Workbench to refetch ``GET /api/bots``; an unlisted event stays Owner-only."""
- from vibe.sse_broker import broker
-
- broker.publish("bots.changed", {"handle": handle} if handle else {})
-
-
@app.route("/api/bots", methods=["GET"])
def bots_list():
from core.bots import BotService
@@ -10195,7 +10188,6 @@ def bots_create():
)
except Exception as exc:
return _bot_error_response(exc)
- _publish_bots_changed(bot.handle)
return jsonify({"ok": True, "bot": bot.to_payload()}), 201
@@ -10215,7 +10207,6 @@ def bots_set():
)
except Exception as exc:
return _bot_error_response(exc)
- _publish_bots_changed(bot.handle)
return jsonify({"ok": True, "bot": bot.to_payload()})
@@ -10272,7 +10263,6 @@ def bots_update(handle):
bot = service.update_bot(handle, authorization_context=context, **fields)
except Exception as exc:
return _bot_error_response(exc)
- _publish_bots_changed(bot.handle)
return jsonify({"ok": True, "bot": bot.to_payload()})
@@ -10286,7 +10276,6 @@ def bots_remove(handle):
bot = service.remove_bot(handle, authorization_context=context)
except Exception as exc:
return _bot_error_response(exc)
- _publish_bots_changed(bot.handle)
return jsonify({"ok": True, "removed": bot.handle, "agent_name": bot.agent.name, "session_id": bot.session_id})
@@ -10315,7 +10304,6 @@ async def bots_avatar_upload(handle: str, starlette_request: FastAPIRequest):
bot = await asyncio.to_thread(store)
except Exception as exc:
return _bot_error_response(exc)
- _publish_bots_changed(bot.handle)
return jsonify({"ok": True, "bot": bot.to_payload()})
return await _dispatch_native_ui_request(starlette_request, handler)