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(core): preserve terminal failure integrations

cyh22abee9eac4e
diff --git a/core/backend_failure.py b/core/backend_failure.py
index 14a83c84c..6e3c25f59 100644
--- a/core/backend_failure.py
+++ b/core/backend_failure.py
@@ -7,6 +7,18 @@ from typing import Any
from core.message_output import MessageOutput, terminal_output_for, terminal_turn_output
+BACKEND_FAILURE_EVENT = "backend_failure"
+
+
+def is_backend_failure_notification(message_type: str | None, metadata: Any) -> bool:
+ """Whether a persisted message is the visible half of a terminal failure."""
+
+ return (
+ str(message_type or "").strip() == "notify"
+ and isinstance(metadata, dict)
+ and metadata.get("event") == BACKEND_FAILURE_EVENT
+ )
+
def _terminal_output(request: Any, output: MessageOutput | None) -> MessageOutput:
if output is not None:
@@ -73,7 +85,7 @@ async def emit_backend_failure(
notify_metadata.update(
{
"backend": backend_name,
- "event": "backend_failure",
+ "event": BACKEND_FAILURE_EVENT,
"failure_id": identity,
}
)
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index f6f719278..5fd68d83f 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -1343,10 +1343,10 @@ class ConsolidatedMessageDispatcher:
``is_error`` marks a terminal ``result`` as a FAILED turn. It is the only
signal the sidebar dot needs on the way out: a terminal result settles the
- session to ``idle`` (or ``failed`` when ``is_error``). Callers that hit a
- terminal failure emit it as ``result`` + ``is_error=True`` instead of a
- bare ``notify`` — that routes the failure through this one outbound
- chokepoint (dot + SSE stream release), so no caller pokes the dot directly.
+ session to ``idle`` (or ``failed`` when ``is_error``). Structured backend
+ failures use a visible ``notify`` for delivery followed by a silent
+ ``result`` with ``is_error=True`` for lifecycle settlement, keeping those
+ responsibilities independent while still passing through this chokepoint.
``level`` is the visibility grade — orthogonal to ``message_type``. The
type says what role the message plays (and drives the dot + unread); the
diff --git a/core/services/session_fork.py b/core/services/session_fork.py
index 67c05e530..56e436d1c 100644
--- a/core/services/session_fork.py
+++ b/core/services/session_fork.py
@@ -14,6 +14,7 @@ from pathlib import Path
from typing import Any, Optional
from config import paths
+from core.backend_failure import BACKEND_FAILURE_EVENT, is_backend_failure_notification
from vibe.i18n import t
TRIM_LATEST_RUNNING_TURN_BACKENDS = {"codex", "opencode"}
@@ -79,10 +80,13 @@ class ForkSourceState:
has_messages_after_anchor: bool = False
has_terminal_agent_output_after_anchor: bool = False
has_user_turn_after_anchor: bool = False
+ anchor_is_backend_failure: bool = False
@property
def anchor_is_terminal_agent_output(self) -> bool:
- return self.anchor_author == "agent" and self.anchor_type in TERMINAL_AGENT_OUTPUT_TYPES
+ return self.anchor_author == "agent" and (
+ self.anchor_type in TERMINAL_AGENT_OUTPUT_TYPES or self.anchor_is_backend_failure
+ )
@dataclass(frozen=True)
@@ -388,7 +392,7 @@ def fork_source_state(fork: dict[str, Any] | None) -> ForkSourceState:
if not source_session_id or not source_message_id:
return ForkSourceState()
- from sqlalchemy import select
+ from sqlalchemy import and_, func, or_, select
from storage.db import create_sqlite_engine
from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
@@ -399,7 +403,13 @@ def fork_source_state(fork: dict[str, Any] | None) -> ForkSourceState:
try:
with engine.connect() as conn:
anchor = conn.execute(
- select(messages.c.created_at, messages.c.id, messages.c.author, messages.c.type)
+ select(
+ messages.c.created_at,
+ messages.c.id,
+ messages.c.author,
+ messages.c.type,
+ messages.c.metadata_json,
+ )
.where(messages.c.session_id == source_session_id, messages.c.id == source_message_id)
.limit(1)
).mappings().first()
@@ -412,10 +422,17 @@ def fork_source_state(fork: dict[str, Any] | None) -> ForkSourceState:
| ((messages.c.created_at == anchor_created_at) & (messages.c.id > anchor_id))
)
latest_after_anchor = conn.execute(
- select(messages.c.author, messages.c.type)
+ select(messages.c.author, messages.c.type, messages.c.metadata_json)
.where(
messages.c.session_id == source_session_id,
- messages.c.type.in_(["user", *list(SOURCE_PROGRESS_AGENT_OUTPUT_TYPES)]),
+ or_(
+ messages.c.type.in_(["user", *list(SOURCE_PROGRESS_AGENT_OUTPUT_TYPES)]),
+ and_(
+ messages.c.type == "notify",
+ func.json_extract(messages.c.metadata_json, "$.event")
+ == BACKEND_FAILURE_EVENT,
+ ),
+ ),
after_anchor,
)
.order_by(messages.c.created_at.desc(), messages.c.id.desc())
@@ -427,9 +444,18 @@ def fork_source_state(fork: dict[str, Any] | None) -> ForkSourceState:
latest_after_anchor_type = (
str(latest_after_anchor["type"] or "").strip() if latest_after_anchor else ""
)
+ latest_after_anchor_metadata = _load_metadata(
+ latest_after_anchor["metadata_json"] if latest_after_anchor else None
+ )
has_terminal_agent_output_after_anchor = (
latest_after_anchor_author == "agent"
- and latest_after_anchor_type in TERMINAL_AGENT_OUTPUT_TYPES
+ and (
+ latest_after_anchor_type in TERMINAL_AGENT_OUTPUT_TYPES
+ or is_backend_failure_notification(
+ latest_after_anchor_type,
+ latest_after_anchor_metadata,
+ )
+ )
)
has_user_turn_after_anchor = (
conn.execute(
@@ -452,6 +478,10 @@ def fork_source_state(fork: dict[str, Any] | None) -> ForkSourceState:
has_messages_after_anchor=latest_after_anchor is not None,
has_terminal_agent_output_after_anchor=has_terminal_agent_output_after_anchor,
has_user_turn_after_anchor=has_user_turn_after_anchor,
+ anchor_is_backend_failure=is_backend_failure_notification(
+ anchor["type"],
+ _load_metadata(anchor["metadata_json"]),
+ ),
)
except Exception as exc:
import logging
diff --git a/core/web_push_notifications.py b/core/web_push_notifications.py
index a1f069066..3d72c6afb 100644
--- a/core/web_push_notifications.py
+++ b/core/web_push_notifications.py
@@ -10,18 +10,37 @@ from typing import Any
from sqlalchemy import or_, select
+from core.backend_failure import is_backend_failure_notification
from storage import messages_service, web_push_service
from storage.models import agent_sessions, messages
logger = logging.getLogger(__name__)
-_NOTIFIABLE_TYPES = {"result", "error"}
+_NOTIFIABLE_TYPES = {"result", "error", "notify"}
_UNREAD_GATED_TYPES = {"result"}
WEB_PUSH_NOTIFICATION_DELAY_SECONDS = 3.0
WEB_PUSH_USER_KEY_METADATA = "_web_push_user_key"
WEB_PUSH_USER_KEYS_METADATA = "_web_push_user_keys"
+def _is_notifiable_message(message_type: Any, metadata: Any = None) -> bool:
+ normalized_type = str(message_type or "").strip()
+ return normalized_type in {"result", "error"} or is_backend_failure_notification(
+ normalized_type,
+ metadata,
+ )
+
+
+def _parse_metadata(value: Any) -> dict[str, Any]:
+ if isinstance(value, dict):
+ return value
+ try:
+ parsed = json.loads(value or "{}")
+ except (TypeError, json.JSONDecodeError):
+ return {}
+ return parsed if isinstance(parsed, dict) else {}
+
+
def maybe_notify_inbox_message(message: dict[str, Any] | None, inbox_row: dict[str, Any] | None) -> None:
"""Schedule Web Push for a newly persisted inbox-visible Workbench message.
@@ -36,7 +55,7 @@ def maybe_notify_inbox_message(message: dict[str, Any] | None, inbox_row: dict[s
return
if message.get("author") != "agent":
return
- if message.get("type") not in _NOTIFIABLE_TYPES:
+ if not _is_notifiable_message(message.get("type"), message.get("metadata")):
return
if not message.get("session_id"):
return
@@ -61,13 +80,17 @@ def _message_still_unread(conn: Any, message_id: str | None) -> bool:
if not message_id:
return False
row = conn.execute(
- select(messages.c.type, messages.c.read_at)
+ select(messages.c.type, messages.c.read_at, messages.c.metadata_json)
.where(messages.c.id == message_id)
.where(messages.c.platform == "avibe")
.where(messages.c.author == "agent")
.where(messages.c.type.in_(_NOTIFIABLE_TYPES))
).first()
- return bool(row is not None and (row[0] not in _UNREAD_GATED_TYPES or row[1] is None))
+ return bool(
+ row is not None
+ and _is_notifiable_message(row[0], _parse_metadata(row[2]))
+ and (row[0] not in _UNREAD_GATED_TYPES or row[1] is None)
+ )
def _metadata_user_keys(metadata: dict[str, Any]) -> list[str]:
@@ -96,15 +119,24 @@ def _web_push_user_keys_for_message(conn: Any, message_id: str | None) -> list[s
if not message_id:
return []
agent_row = conn.execute(
- select(messages.c.session_id, messages.c.created_at, messages.c.id)
+ select(
+ messages.c.session_id,
+ messages.c.created_at,
+ messages.c.id,
+ messages.c.type,
+ messages.c.metadata_json,
+ )
.where(messages.c.id == message_id)
.where(messages.c.platform == "avibe")
.where(messages.c.author == "agent")
.where(messages.c.type.in_(_NOTIFIABLE_TYPES))
).first()
- if not agent_row or not agent_row[0]:
+ if not agent_row or not agent_row[0] or not _is_notifiable_message(
+ agent_row[3],
+ _parse_metadata(agent_row[4]),
+ ):
return []
- session_id, created_at, row_id = agent_row
+ session_id, created_at, row_id = agent_row[0], agent_row[1], agent_row[2]
user_rows = conn.execute(
select(messages.c.metadata_json)
diff --git a/tests/test_session_fork.py b/tests/test_session_fork.py
index 3da769a86..0b802b280 100644
--- a/tests/test_session_fork.py
+++ b/tests/test_session_fork.py
@@ -1128,6 +1128,85 @@ def test_fork_source_state_ignores_notify_as_terminal_output(
engine.dispose()
+def test_fork_source_state_treats_backend_failure_notify_anchor_as_terminal(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from config import paths
+ from storage.importer import ensure_sqlite_state
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ db_path = paths.get_sqlite_state_path()
+ source_id = _seed_source_session(db_path, tmp_path)
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ row = conn.execute(select(agent_sessions).where(agent_sessions.c.id == source_id)).mappings().one()
+ notify = messages_service.append(
+ conn,
+ scope_id=row["scope_id"],
+ session_id=source_id,
+ platform="avibe",
+ author="agent",
+ message_type="notify",
+ text="Codex backend failed",
+ metadata={"event": "backend_failure", "failure_id": "failure_1"},
+ )
+
+ fork = {"source_session_id": source_id, "source_message_id": notify["id"]}
+ state = fork_source_state(fork)
+
+ assert state.anchor_is_terminal_agent_output is True
+ assert state.has_messages_after_anchor is False
+ assert fork_anchor_is_terminal_agent_output(fork) is True
+ finally:
+ engine.dispose()
+
+
+def test_fork_source_state_treats_backend_failure_notify_after_anchor_as_terminal(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from config import paths
+ from storage.importer import ensure_sqlite_state
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ db_path = paths.get_sqlite_state_path()
+ source_id = _seed_source_session(db_path, tmp_path)
+ engine = create_sqlite_engine(db_path)
+ try:
+ with engine.begin() as conn:
+ row = conn.execute(select(agent_sessions).where(agent_sessions.c.id == source_id)).mappings().one()
+ user = messages_service.append(
+ conn,
+ scope_id=row["scope_id"],
+ session_id=source_id,
+ platform="avibe",
+ author="user",
+ message_type="user",
+ text="Do the task",
+ )
+ messages_service.append(
+ conn,
+ scope_id=row["scope_id"],
+ session_id=source_id,
+ platform="avibe",
+ author="agent",
+ message_type="notify",
+ text="Codex backend failed",
+ metadata={"event": "backend_failure", "failure_id": "failure_1"},
+ )
+
+ state = fork_source_state({"source_session_id": source_id, "source_message_id": user["id"]})
+
+ assert state.latest_after_anchor_author == "agent"
+ assert state.latest_after_anchor_type == "notify"
+ assert state.has_messages_after_anchor is True
+ assert state.has_terminal_agent_output_after_anchor is True
+ finally:
+ engine.dispose()
+
+
def test_fork_source_state_ignores_operational_rows_after_anchor(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
diff --git a/tests/test_web_push_notifications.py b/tests/test_web_push_notifications.py
index 9df31c509..af9b167e4 100644
--- a/tests/test_web_push_notifications.py
+++ b/tests/test_web_push_notifications.py
@@ -54,6 +54,35 @@ def test_maybe_notify_inbox_message_schedules_agent_result(monkeypatch):
]
+def test_maybe_notify_inbox_message_schedules_backend_failure_notify(monkeypatch):
+ calls = []
+
+ class _Thread:
+ def __init__(self, *, target, args, daemon):
+ assert daemon is True
+ self.args = args
+
+ def start(self):
+ calls.append(self.args[0])
+
+ monkeypatch.setattr(web_push_notifications.threading, "Thread", _Thread)
+
+ web_push_notifications.maybe_notify_inbox_message(
+ {
+ "id": "msg_failure",
+ "platform": "avibe",
+ "author": "agent",
+ "type": "notify",
+ "session_id": "ses_1",
+ "text": "Codex backend failed",
+ "metadata": {"event": "backend_failure", "failure_id": "failure_1"},
+ },
+ {"title": "Build fix"},
+ )
+
+ assert [call["message_id"] for call in calls] == ["msg_failure"]
+
+
def test_maybe_notify_inbox_message_skips_non_notifiable(monkeypatch):
calls = []
monkeypatch.setattr(
@@ -91,6 +120,70 @@ def test_maybe_notify_inbox_message_skips_non_notifiable(monkeypatch):
assert calls == []
+def test_backend_failure_notify_passes_durable_web_push_gates(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-07-11T00:00:00Z"
+ with engine.begin() as conn:
+ scope_id = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_failure", now=now)
+ conn.execute(
+ agent_sessions.insert().values(
+ id="ses_failure",
+ scope_id=scope_id,
+ agent_backend="codex",
+ agent_variant="default",
+ session_anchor="ses_failure",
+ native_session_id="",
+ title="Failure",
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_failure",
+ platform="avibe",
+ author="user",
+ source="user",
+ metadata={"_web_push_user_key": "remote:user-a"},
+ message_type="user",
+ text="Please finish",
+ )
+ failure = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_failure",
+ platform="avibe",
+ author="agent",
+ source="agent",
+ metadata={"event": "backend_failure", "failure_id": "failure_1"},
+ message_type="notify",
+ text="Codex backend failed",
+ )
+ ordinary_notify = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id="ses_failure",
+ platform="avibe",
+ author="agent",
+ source="agent",
+ message_type="notify",
+ text="Still working",
+ )
+
+ with engine.connect() as conn:
+ assert web_push_notifications._message_still_unread(conn, failure["id"]) is True
+ assert web_push_notifications._web_push_user_keys_for_message(conn, failure["id"]) == ["remote:user-a"]
+ assert web_push_notifications._message_still_unread(conn, ordinary_notify["id"]) is False
+ assert web_push_notifications._web_push_user_keys_for_message(conn, ordinary_notify["id"]) == []
+ engine.dispose()
+
+
def test_send_to_enabled_subscriptions_waits_then_sends_to_owner_devices(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
ensure_sqlite_state()