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(messages): recover stale pending rows after interrupted dispatch (#1034)

mohd humaid9902ce800832
diff --git a/storage/messages_service.py b/storage/messages_service.py
index e64b544b2..4046930f8 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -17,11 +17,18 @@ import uuid
from datetime import datetime, timezone
from typing import Any, Iterable, Optional
-from sqlalchemy import and_, delete, func, or_, select, update
+from sqlalchemy import and_, delete, exists, func, or_, select, update
from sqlalchemy.engine import Connection
from storage.db import escape_sql_like
-from storage.models import agent_runs, agent_sessions, messages, scope_settings, scopes
+from storage.models import (
+ agent_runs,
+ agent_sessions,
+ messages,
+ scope_settings,
+ scopes,
+ show_session_events,
+)
from vibe.message_identity import HARNESS_TYPE, INPUT_TURN_AUTHOR_TYPES
@@ -743,6 +750,21 @@ def list_queued(conn: Connection, session_id: str) -> list[dict[str, Any]]:
return [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]
+def list_recoverable_pending(conn: Connection) -> list[dict[str, Any]]:
+ """Pending reservations not owned by the Show dispatch state machine."""
+
+ show_owner = select(show_session_events.c.id).where(
+ show_session_events.c.message_id == messages.c.id
+ )
+ query = (
+ select(messages)
+ .where(messages.c.type == PENDING_TYPE)
+ .where(~exists(show_owner))
+ .order_by(messages.c.created_at.asc(), messages.c.id.asc())
+ )
+ return [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]
+
+
def list_queued_session_ids(conn: Connection) -> list[str]:
"""Session ids with persisted queue rows, ordered by their oldest row."""
@@ -825,6 +847,17 @@ def clear_pending(conn: Connection, session_id: str) -> int:
return result.rowcount or 0
+def delete_pending(conn: Connection, message_id: str) -> bool:
+ """Delete one reserved pending row by id. Returns True when removed."""
+
+ result = conn.execute(
+ delete(messages)
+ .where(messages.c.id == message_id)
+ .where(messages.c.type == PENDING_TYPE)
+ )
+ return bool(result.rowcount)
+
+
def promote_pending(conn: Connection, message_id: str, to_type: str) -> bool:
"""Change only the rendering state of one reserved transcript row."""
result = conn.execute(
diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.py
index 8b5c71034..b0d9b6b6e 100644
--- a/tests/test_ui_session_stream.py
+++ b/tests/test_ui_session_stream.py
@@ -20,7 +20,12 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import pytest
+from sqlalchemy import select, update
+
from storage.importer import ensure_sqlite_state
+from storage.db import create_sqlite_engine
+from storage import messages_service
+from storage.models import agent_sessions, messages
from storage.models import scope_settings
from storage.settings_service import upsert_scope
from tests.ui_server_test_helpers import csrf_headers
@@ -189,8 +194,6 @@ def test_route_ambiguous_failure_settles_unowned_pending_visible_without_queuein
error_kind,
expected_status,
):
- from storage import messages_service
- from storage.db import create_sqlite_engine
from vibe import internal_client
from vibe.ui_server import app
@@ -241,8 +244,6 @@ def test_route_timeout_observes_controller_queue_without_republishing(
monkeypatch,
):
from core.session_turns import queue_pending_user_message
- from storage import messages_service
- from storage.db import create_sqlite_engine
from vibe import internal_client
from vibe.ui_server import app
@@ -284,6 +285,173 @@ def test_route_timeout_observes_controller_queue_without_republishing(
assert [event_type for event_type, _data in published].count("queue.updated") == 1
+def test_recover_stale_pending_promotes_visible_user(isolated_state, tmp_path):
+ from vibe import ui_server
+
+ scope_id, session_id = _make_session(tmp_path)
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ pending = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type=messages_service.PENDING_TYPE,
+ text="stuck pending",
+ )
+
+ with patch("vibe.sse_broker.broker.publish") as publish:
+ summary = ui_server._recover_stale_pending_messages()
+
+ assert summary == {"promoted": 1, "deleted": 0, "skipped": 0}
+ with engine.connect() as conn:
+ stored = conn.execute(
+ select(messages.c.type, messages.c.content_text).where(messages.c.id == pending["id"])
+ ).first()
+ assert stored == ("user", "stuck pending")
+ published_events = [call.args[0] for call in publish.call_args_list]
+ assert "message.new" in published_events
+ assert "session.activity" in published_events
+
+
+def test_recover_stale_pending_deletes_archived_session_rows(isolated_state, tmp_path):
+ from vibe import ui_server
+
+ scope_id, session_id = _make_session(tmp_path)
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ pending = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type=messages_service.PENDING_TYPE,
+ text="archived pending",
+ )
+ conn.execute(
+ update(agent_sessions)
+ .where(agent_sessions.c.id == session_id)
+ .values(status="archived", session_anchor=f"archived:{session_id}")
+ )
+
+ with patch("vibe.sse_broker.broker.publish") as publish:
+ summary = ui_server._recover_stale_pending_messages()
+
+ assert summary == {"promoted": 0, "deleted": 1, "skipped": 0}
+ with engine.connect() as conn:
+ stored = conn.execute(select(messages.c.id).where(messages.c.id == pending["id"])).scalar_one_or_none()
+ assert stored is None
+ publish.assert_not_called()
+
+
+def test_recover_stale_pending_deletes_rows_without_session(isolated_state, tmp_path):
+ from vibe import ui_server
+
+ scope_id, _ = _make_session(tmp_path)
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ pending = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=None,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type=messages_service.PENDING_TYPE,
+ text="orphaned pending",
+ )
+
+ with patch("vibe.sse_broker.broker.publish") as publish:
+ summary = ui_server._recover_stale_pending_messages()
+
+ assert summary == {"promoted": 0, "deleted": 1, "skipped": 0}
+ with engine.connect() as conn:
+ stored = conn.execute(
+ select(messages.c.id).where(messages.c.id == pending["id"])
+ ).scalar_one_or_none()
+ assert stored is None
+ publish.assert_not_called()
+
+
+def test_recover_stale_pending_skips_rows_already_retyped(isolated_state, tmp_path):
+ from vibe import ui_server
+
+ scope_id, session_id = _make_session(tmp_path)
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ pending = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type=messages_service.PENDING_TYPE,
+ text="already queued",
+ )
+ conn.execute(
+ update(messages)
+ .where(messages.c.id == pending["id"])
+ .values(type=messages_service.QUEUED_TYPE)
+ )
+
+ with patch("vibe.sse_broker.broker.publish") as publish:
+ summary = ui_server._recover_stale_pending_messages()
+
+ assert summary == {"promoted": 0, "deleted": 0, "skipped": 0}
+ with engine.connect() as conn:
+ stored = conn.execute(
+ select(messages.c.type).where(messages.c.id == pending["id"])
+ ).scalar_one()
+ assert stored == messages_service.QUEUED_TYPE
+ publish.assert_not_called()
+
+
+def test_recover_stale_pending_leaves_show_owned_rows_to_show_reconciler(
+ isolated_state,
+ tmp_path,
+):
+ from core.show_session_events import ShowSessionEventStore
+ from vibe import ui_server
+
+ _, session_id = _make_session(tmp_path)
+ store = ShowSessionEventStore()
+ try:
+ event = store.append(
+ session_id,
+ {
+ "id": "show_evt_pending_recovery_owner",
+ "type": "human.annotation.created",
+ "annotation": {
+ "comment": "Keep this reservation under Show ownership.",
+ "dispatch": True,
+ },
+ },
+ reserve_dispatch=True,
+ )
+ finally:
+ store.close()
+ assert event["message"]["type"] == messages_service.PENDING_TYPE
+
+ with patch("vibe.sse_broker.broker.publish") as publish:
+ summary = ui_server._recover_stale_pending_messages()
+ ui_server.reconcile_show_dispatch_messages_on_startup()
+
+ assert summary == {"promoted": 0, "deleted": 0, "skipped": 0}
+ store = ShowSessionEventStore()
+ try:
+ recovered = store.get_event(session_id, event["id"])
+ finally:
+ store.close()
+ assert recovered is not None
+ assert recovered["message"]["type"] == messages_service.PENDING_TYPE
+ publish.assert_not_called()
+
+
def test_create_session_without_backend_defers_to_default_agent(isolated_state, tmp_path):
"""POST /api/sessions with no ``agent_backend`` must NOT stamp a concrete
backend onto the session. A stamped backend is treated by message_handler
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 809c06a85..36b397fde 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -234,6 +234,55 @@ def _recover_stale_session_status(session_id: str) -> bool:
return changed
+def _recover_stale_pending_messages() -> dict[str, int]:
+ """Repair hidden ``pending`` send reservations left behind by UI interruption.
+
+ Recovery restores ordinary transcript visibility only; it never re-dispatches
+ the text. Show-owned reservations remain under Show's event-aware reconciler.
+ Rows whose session is missing or archived are deleted.
+ """
+
+ from core.services import sessions as workbench_sessions_service
+ from storage import messages_service
+
+ summary = {"promoted": 0, "deleted": 0, "skipped": 0}
+ engine = _projects_engine()
+ try:
+ with engine.connect() as conn:
+ pending_rows = messages_service.list_recoverable_pending(conn)
+
+ for row in pending_rows:
+ session_id = str(row.get("session_id") or "").strip()
+ with engine.begin() as conn:
+ session = None
+ if session_id:
+ try:
+ session = workbench_sessions_service.get_session(conn, session_id)
+ except LookupError:
+ pass
+ if not session or session.get("status") == "archived":
+ if messages_service.delete_pending(conn, str(row["id"])):
+ summary["deleted"] += 1
+ continue
+ promoted = messages_service.promote_pending(conn, str(row["id"]), "user")
+ if not promoted:
+ summary["skipped"] += 1
+ continue
+ settled = _load_session_message(session_id, str(row["id"]))
+ if settled is None or settled.get("type") != "user":
+ summary["skipped"] += 1
+ continue
+ summary["promoted"] += 1
+ _publish_visible_user_message(
+ settled,
+ session_id=session_id,
+ scope_id=session.get("scope_id"),
+ )
+ finally:
+ engine.dispose()
+ return summary
+
+
def _is_continuation_line(line: str, previous_message: str | None = None) -> bool:
stripped = line.lstrip()
return (
@@ -10827,6 +10876,27 @@ def reconcile_show_dispatch_messages_on_startup() -> None:
)
+async def _recover_stale_pending_messages_on_startup() -> None:
+ start = time.monotonic()
+ try:
+ summary = await asyncio.to_thread(_recover_stale_pending_messages)
+ except Exception:
+ duration_ms = int((time.monotonic() - start) * 1000)
+ logger.warning("Pending-message recovery raised after %sms", duration_ms, exc_info=True)
+ return
+ duration_ms = int((time.monotonic() - start) * 1000)
+ if any(summary.values()):
+ logger.info(
+ "Recovered stale pending messages in %sms: promoted=%s deleted=%s skipped=%s",
+ duration_ms,
+ summary["promoted"],
+ summary["deleted"],
+ summary["skipped"],
+ )
+ else:
+ logger.info("No stale pending messages to recover (%sms)", duration_ms)
+
+
async def _stop_startup_dependency_reconcile() -> None:
global _startup_dependency_reconcile_task
task, _startup_dependency_reconcile_task = _startup_dependency_reconcile_task, None
@@ -10842,6 +10912,7 @@ async def _stop_startup_dependency_reconcile() -> None:
app.add_event_handler("startup", sweep_orphan_show_runtime_servers_on_startup)
app.add_event_handler("startup", reconcile_show_dispatch_messages_on_startup)
+app.add_event_handler("startup", _recover_stale_pending_messages_on_startup)
app.add_event_handler("startup", _start_startup_dependency_reconcile)
app.add_event_handler("shutdown", _stop_startup_dependency_reconcile)
app.add_event_handler("shutdown", stop_show_runtime_on_shutdown)