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(workbench): Phase 3 — scheduled provenance through the queue + queue.updated on enqueue (#84) (#388)

Call Whited378498edaf3
diff --git a/core/internal_server.py b/core/internal_server.py
index 80cf232e9..cb0ca66c7 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -132,12 +132,15 @@ def create_app(controller: "Controller") -> FastAPI:
def _enqueue() -> None:
from core.message_mirror import _scope_id_for_session
+ from core.session_turns import SCHEDULED_PROVENANCE_KEY, capture_scheduled_provenance
from storage import messages_service
from storage.db import create_sqlite_engine
- # ``pop_queued`` / ``flush_queue`` key off (session_id, type=queued) +
- # scope_id + text only, so the harness attribution (author/source) is safe
- # to carry — it just records who triggered the queued run.
+ # Persist the scheduled run's delivery / attribution provenance on the
+ # queued row's metadata so flush_queue re-runs it as SOURCE_SCHEDULED with
+ # that restored — keeping suppress_delivery / the delivery target / the task
+ # attribution instead of degrading to a plain user turn (#84). The key's
+ # PRESENCE also marks this row as a scheduled segment for the flush.
engine = create_sqlite_engine()
with engine.begin() as conn:
scope_id = _scope_id_for_session(conn, session_id)
@@ -151,6 +154,7 @@ def create_app(controller: "Controller") -> FastAPI:
source="harness",
message_type=messages_service.QUEUED_TYPE,
text=text,
+ metadata={SCHEDULED_PROVENANCE_KEY: capture_scheduled_provenance(context)},
)
await manager.submit(session_id, context, text, source=SOURCE_SCHEDULED, enqueue=_enqueue)
diff --git a/core/session_turns.py b/core/session_turns.py
index 3ffd4cae0..797002006 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -20,13 +20,51 @@ import asyncio
import logging
from typing import TYPE_CHECKING, Any, Callable, Optional
-from core.services.dispatch import SOURCE_HUMAN, dispatch_turn
+from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turn
if TYPE_CHECKING:
from modules.im import MessageContext
logger = logging.getLogger(__name__)
+# A queued row's ``metadata[SCHEDULED_PROVENANCE_KEY]`` carries the scheduled run's
+# context.platform_specific provenance that the gate must restore when the row is
+# finally flushed — so a scheduled run enqueued behind an active turn keeps its
+# delivery override / suppression / task attribution + runs as SOURCE_SCHEDULED, not
+# a plain human turn (#84). Its PRESENCE also marks the row as a scheduled segment
+# (vs a user send) for flush_queue.
+SCHEDULED_PROVENANCE_KEY = "scheduled_provenance"
+
+# The platform_specific keys the FLUSH rebuilds fresh from the session row (avibe
+# routing). Everything ELSE the scheduled context carries is delivery / attribution
+# provenance to preserve. We capture by EXCLUDING these (a blocklist) rather than
+# whitelisting provenance keys, so a delivery field like ``delivery_override`` — what
+# ``MessageDispatcher._get_target_context`` actually redirects delivery on — can't be
+# silently omitted (Codex P1 #3338692433).
+_FLUSH_REBUILT_KEYS = frozenset(
+ {"platform", "is_dm", "workbench_session_id", "agent_session_id", "agent_session_target", "turn_token"}
+)
+
+
+def capture_scheduled_provenance(context: "MessageContext") -> dict:
+ """Capture the scheduled run's provenance to persist on its queued row so
+ flush_queue can restore it (#84):
+
+ - ``message_id`` — the top-level stable ``scheduled:/watch:/webhook:`` native id
+ that ``mirror_harness_inbound`` persists the prompt under, and that the
+ ``(platform, native_message_id)`` uniqueness dedupes a retried/duplicated
+ execution on. The flush's rebuilt context is otherwise ``message_id=None`` so a
+ queued retry would lose dedup + native provenance (Codex P2 #3338722672).
+ - ``platform_specific`` — the delivery / attribution slice: everything EXCEPT the
+ routing keys the flush rebuilds, captured by exclusion so a delivery field like
+ ``delivery_override`` can't be silently missed (Codex P1 #3338692433).
+ """
+ spec = getattr(context, "platform_specific", None) or {}
+ return {
+ "message_id": getattr(context, "message_id", None),
+ "platform_specific": {k: v for k, v in spec.items() if k not in _FLUSH_REBUILT_KEYS},
+ }
+
def emit_matches_active_turn(sink: dict, context: "MessageContext") -> bool:
"""The ONE active-turn token rule (FSM Phase 2 — collapses the three previously
@@ -148,9 +186,18 @@ class SessionTurnManager:
if should_enqueue:
if enqueue is not None:
enqueue()
- # Idle + pre-existing queue → no running turn to flush behind, so drain
- # the whole queue (this row included) now, in order.
- if not busy:
+ if busy:
+ # The row joins the active turn's queue and stays until it drains —
+ # surface the queue growth NOW so the UI reflects it immediately
+ # (the later flush emits its own queue.updated when it pops). This
+ # closes the enqueue-time gap for BOTH Chat and scheduled sends.
+ from core.inbox_events import bus
+
+ bus.publish("queue.updated", {"session_id": session_id})
+ else:
+ # Idle + pre-existing queue → no running turn to flush behind, so
+ # drain the whole queue (this row included) now, in order. flush_queue
+ # publishes queue.updated itself.
await self.flush_queue(session_id)
return "enqueued"
await self._run(session_id, context, text, source=source)
@@ -245,54 +292,84 @@ class SessionTurnManager:
bus.publish("turn.start", {"session_id": session_id})
async def flush_queue(self, session_id: str) -> bool:
- """Pop the messages queued while a turn ran, merge them into one
- (newline-joined) user message, and run it as the next turn — recursively
- draining the queue. Returns True if a turn was started, False on an empty
- queue / failure (so ``send-now`` can report idle instead of leaving the
- client stuck waiting). The merge is the user's choice (one dispatch, not N);
- the individual queued rows are deleted by ``pop_queued`` and replaced by the
- single merged user row."""
+ """Drain the send-while-busy queue ONE segment per call — the turn's
+ completion re-flushes the next, so segments run in order, one at a time.
+
+ A leading run of consecutive USER rows is merged into a single user turn (the
+ user's choice — one dispatch, not N). A SCHEDULED row (it carries stored
+ provenance) is NOT merged: it runs as its OWN ``SOURCE_SCHEDULED`` turn with
+ its delivery / attribution provenance restored, so a scheduled run that was
+ enqueued behind an active turn keeps its suppress-delivery / delivery-target /
+ source when it finally runs (#84). Returns True if a turn was started, False
+ on an empty queue / failure."""
from core.inbox_events import bus
from storage import messages_service
from storage.db import create_sqlite_engine
if not session_id:
return False
+
+ is_scheduled = False
+ scheduled_text = ""
+ scheduled_prov: dict = {}
+ scheduled_message_id = None
user_row = None
inbox_row = None
try:
engine = create_sqlite_engine()
with engine.begin() as conn:
- rows = messages_service.pop_queued(conn, session_id)
- texts = [r.get("text") for r in rows if (r.get("text") or "").strip()]
- if not texts:
+ rows = messages_service.list_queued(conn, session_id)
+ if not rows:
return False
- user_row = messages_service.append(
- conn,
- scope_id=rows[0]["scope_id"],
- session_id=session_id,
- platform="avibe",
- author="user",
- source="user",
- message_type="user",
- text="\n".join(texts),
- )
- inbox_row = messages_service.get_inbox_session(conn, session_id)
+ if (rows[0].get("metadata") or {}).get(SCHEDULED_PROVENANCE_KEY) is not None:
+ # Scheduled segment: exactly this one row, run on its own.
+ is_scheduled = True
+ segment = [rows[0]]
+ scheduled_text = rows[0].get("text") or ""
+ prov = rows[0]["metadata"][SCHEDULED_PROVENANCE_KEY] or {}
+ scheduled_message_id = prov.get("message_id")
+ scheduled_prov = prov.get("platform_specific") or {}
+ else:
+ # User segment: the leading run of consecutive non-scheduled rows
+ # (stop at the first scheduled row so it stays its own turn).
+ segment = []
+ for r in rows:
+ if (r.get("metadata") or {}).get(SCHEDULED_PROVENANCE_KEY) is not None:
+ break
+ segment.append(r)
+ messages_service.delete_queued(conn, [r["id"] for r in segment])
+ if not is_scheduled:
+ texts = [r.get("text") for r in segment if (r.get("text") or "").strip()]
+ if not texts:
+ return False
+ user_row = messages_service.append(
+ conn,
+ scope_id=segment[0]["scope_id"],
+ session_id=session_id,
+ platform="avibe",
+ author="user",
+ source="user",
+ message_type="user",
+ text="\n".join(texts),
+ )
+ inbox_row = messages_service.get_inbox_session(conn, session_id)
except Exception:
- logger.exception("queue flush: failed to pop/merge for session=%s", session_id)
+ logger.exception("queue flush: failed to claim/merge for session=%s", session_id)
return False
- if user_row is None:
- return False
- # Surface the flushed (merged) user message, bump the inbox card (so other
- # workbench views re-rank + flip 'replied' without waiting for the next
- # result — Codex P2), and mark the queue empty.
- bus.publish("message.new", user_row)
- if inbox_row is not None:
- bus.publish("inbox.session.updated", inbox_row)
+
+ # Surface the flushed (merged) user message + bump the inbox card so other
+ # workbench views re-rank / flip 'replied' without waiting for the result
+ # (Codex P2). A scheduled segment has NO user row — its prompt is mirrored by
+ # its own dispatch, exactly as a non-enqueued scheduled run. Either way the
+ # queue changed.
+ if user_row is not None:
+ bus.publish("message.new", user_row)
+ if inbox_row is not None:
+ bus.publish("inbox.session.updated", inbox_row)
bus.publish("queue.updated", {"session_id": session_id})
- # Rebuild routing from the CURRENT session row so a queued follow-up uses the
- # session's latest agent / model / effort — the user may have changed it while
- # the prior (now-finished) turn was running (Codex P2).
+
+ # Rebuild routing from the CURRENT session row so a flushed follow-up uses the
+ # session's latest agent / model / effort (Codex P2).
if self._build_context is None:
logger.error("queue flush: no build_context bound for session=%s", session_id)
return False
@@ -301,7 +378,22 @@ class SessionTurnManager:
except Exception:
logger.exception("queue flush: failed to build context for session=%s", session_id)
return False
- await self._run(session_id, context, user_row.get("text") or "")
+
+ if not is_scheduled:
+ await self._run(session_id, context, user_row.get("text") or "")
+ else:
+ # Restore the scheduled run's delivery / source provenance onto the rebuilt
+ # (fresh-routing) context, then run as SOURCE_SCHEDULED — not a plain user
+ # turn — so suppress_delivery / the delivery target / the task attribution
+ # carry through the queue (#84).
+ if context.platform_specific is None:
+ context.platform_specific = {}
+ context.platform_specific.update(scheduled_prov)
+ if scheduled_message_id is not None:
+ # Restore the stable scheduled:/watch:/webhook: native id so the
+ # flushed prompt persists + dedupes under it (Codex P2), not None.
+ context.message_id = scheduled_message_id
+ await self._run(session_id, context, scheduled_text, source=SOURCE_SCHEDULED)
return True
def turn_state(self, session_id: str) -> dict:
diff --git a/storage/messages_service.py b/storage/messages_service.py
index 08547ecb1..86385a3e8 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -303,6 +303,17 @@ def pop_queued(conn: Connection, session_id: str) -> list[dict[str, Any]]:
return rows
+def delete_queued(conn: Connection, ids: list[str]) -> None:
+ """Delete a CLAIMED subset of queued rows by id. The caller read them via
+ ``list_queued`` and is claiming exactly this segment (e.g. the leading run of
+ user rows, or one scheduled row). Scoped to the read ids — not a broad
+ session+type predicate — so a row another writer enqueued after the read
+ survives for the next flush (same safety rationale as ``pop_queued``)."""
+ if not ids:
+ return
+ conn.execute(delete(messages).where(messages.c.id.in_(ids)))
+
+
def promote_pending(conn: Connection, message_id: str, to_type: str) -> bool:
"""Promote a reserved ``pending`` row to its decided type — ``user`` once the
turn is accepted, or ``queued`` when a turn is already running. The row is
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 83dc290b6..9910100d8 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -17,6 +17,7 @@ from __future__ import annotations
import asyncio
import sys
+import types
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock
@@ -420,6 +421,8 @@ def test_dispatch_async_enqueues_during_busy_turn(monkeypatch, tmp_path):
)
session_id = session["id"]
+ from core.inbox_events import bus
+
controller = _build_controller_double()
app = internal_server.create_app(controller)
transport = httpx.ASGITransport(app=app)
@@ -433,6 +436,7 @@ def test_dispatch_async_enqueues_during_busy_turn(monkeypatch, tmp_path):
task,
MessageContext(user_id="U", channel_id="C", platform="avibe"),
)
+ sub_id, events = bus.subscribe()
try:
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
resp = await client.post(
@@ -441,12 +445,22 @@ def test_dispatch_async_enqueues_during_busy_turn(monkeypatch, tmp_path):
)
finally:
task.cancel()
- return resp
-
- resp = asyncio.run(_go())
+ # bus.publish defers delivery via loop.call_soon_threadsafe; yield so the
+ # scheduled puts land before we drain.
+ await asyncio.sleep(0.05)
+ published = []
+ while not events.empty():
+ published.append(events.get_nowait())
+ bus.unsubscribe(sub_id)
+ return resp, published
+
+ resp, published = asyncio.run(_go())
assert resp.status_code == 202
assert resp.json()["queued"] is True
controller.message_handler.handle_user_message.assert_not_awaited()
+ # Enqueue surfaces the queue growth immediately so the UI reflects it without
+ # waiting for the flush (queue.updated-on-enqueue, #3336001455).
+ assert ("queue.updated", {"session_id": session_id}) in published
with engine.connect() as conn:
# The row was atomically re-typed to queued (now out of the transcript).
assert [q["text"] for q in messages_service.list_queued(conn, session_id)] == ["while busy"]
@@ -826,3 +840,165 @@ def test_scheduled_gate_cancel_stops_scheduled_run(monkeypatch, tmp_path):
# scheduled run's own context.
controller.command_handler.handle_stop.assert_awaited_once()
assert session_id not in app.state.in_flight_dispatches, "slot released after the scheduled run was stopped"
+
+
+# --- #84: scheduled provenance survives the merge-queue --------------------------
+
+
+def _seed_avibe_session_with_queue(queued):
+ """Create an isolated avibe session and seed its queue (oldest first). Each
+ ``queued`` entry is ``(text, scheduled_provenance | None)`` — None => a user row,
+ a dict => a scheduled row carrying that provenance under the marker key."""
+ from core.services import sessions as sessions_service
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state
+ from storage.settings_service import upsert_scope
+
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = upsert_scope(
+ conn, platform="avibe", scope_type="project", native_id="proj_q84", now="2026-05-31T00:00:00Z"
+ )
+ session = sessions_service.create_session(
+ conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"
+ )
+ for text, prov in queued:
+ messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=session["id"],
+ platform="avibe",
+ author=("harness" if prov is not None else "user"),
+ source=("harness" if prov is not None else "user"),
+ message_type=messages_service.QUEUED_TYPE,
+ text=text,
+ metadata=({session_turns.SCHEDULED_PROVENANCE_KEY: prov} if prov is not None else None),
+ )
+ return session["id"]
+
+
+def _manager_capturing_runs():
+ """A SessionTurnManager whose ``_run`` records each flushed turn's (text, source,
+ suppress_delivery) instead of dispatching."""
+ runs: list = []
+ mgr = session_turns.SessionTurnManager(
+ controller=types.SimpleNamespace(),
+ build_context=lambda sid: MessageContext(
+ user_id="U", channel_id="C", platform="avibe", platform_specific={"agent_session_id": sid}
+ ),
+ )
+
+ async def _fake_run(sid, context, text, *, source=SOURCE_HUMAN):
+ runs.append((text, source, context))
+
+ mgr._run = _fake_run
+ return mgr, runs
+
+
+def test_flush_runs_scheduled_row_as_scheduled_with_provenance(tmp_path, monkeypatch):
+ """A queued scheduled run flushes as its OWN SOURCE_SCHEDULED turn with its
+ delivery provenance restored — not merged into a plain user turn (#84)."""
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ override = {"channel_id": "slack-321", "platform": "slack"}
+ session_id = _seed_avibe_session_with_queue(
+ [(
+ "scheduled prompt",
+ {
+ "message_id": "scheduled:exec-1",
+ "platform_specific": {
+ "suppress_delivery": True,
+ "delivery_override": override,
+ "task_trigger_kind": "task",
+ },
+ },
+ )]
+ )
+ mgr, runs = _manager_capturing_runs()
+
+ assert asyncio.run(mgr.flush_queue(session_id)) is True
+ assert len(runs) == 1
+ text, source, ctx = runs[0]
+ # Ran as scheduled (not user), with the FULL provenance restored: the delivery
+ # override (the redirect _get_target_context uses) + suppress_delivery (#84 / P1)
+ # AND the stable scheduled native id for dedup (P2).
+ assert (text, source) == ("scheduled prompt", SOURCE_SCHEDULED)
+ assert ctx.platform_specific["suppress_delivery"] is True
+ assert ctx.platform_specific["delivery_override"] == override
+ assert ctx.message_id == "scheduled:exec-1"
+
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+
+ with create_sqlite_engine().begin() as conn:
+ assert messages_service.list_queued(conn, session_id) == []
+
+
+def test_flush_segments_user_then_scheduled_in_order(tmp_path, monkeypatch):
+ """A mixed queue drains one segment per flush, in order: leading user rows merge
+ into one user turn; the scheduled row then runs separately with its provenance.
+ The completion-reflush handles the next segment, so one flush runs only the first
+ segment and leaves the rest (#84)."""
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ session_id = _seed_avibe_session_with_queue(
+ [
+ ("u1", None),
+ ("u2", None),
+ ("sched", {"message_id": "scheduled:x", "platform_specific": {"suppress_delivery": True}}),
+ ]
+ )
+ mgr, runs = _manager_capturing_runs()
+
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+
+ # First flush: leading user rows merge into one user turn; the scheduled row stays.
+ assert asyncio.run(mgr.flush_queue(session_id)) is True
+ assert [(t, s) for t, s, _ in runs] == [("u1\nu2", SOURCE_HUMAN)]
+ assert "suppress_delivery" not in (runs[0][2].platform_specific or {})
+ with create_sqlite_engine().begin() as conn:
+ remaining = messages_service.list_queued(conn, session_id)
+ assert [r["text"] for r in remaining] == ["sched"]
+
+ # Second flush (what the turn completion triggers): the scheduled row runs as
+ # SOURCE_SCHEDULED with its provenance.
+ assert asyncio.run(mgr.flush_queue(session_id)) is True
+ assert (runs[-1][0], runs[-1][1]) == ("sched", SOURCE_SCHEDULED)
+ assert runs[-1][2].platform_specific["suppress_delivery"] is True
+
+
+def test_capture_scheduled_provenance_keeps_delivery_drops_routing():
+ """capture_scheduled_provenance keeps the delivery / attribution keys — notably
+ delivery_override, the redirect MessageDispatcher._get_target_context uses — and
+ DROPS the routing keys the flush rebuilds, so a queued scheduled run keeps its
+ delivery target (#84 / Codex P1 #3338692433)."""
+ override = {"channel_id": "slack-9", "platform": "slack"}
+ ctx = MessageContext(
+ user_id="U",
+ channel_id="C",
+ platform="avibe",
+ message_id="scheduled:exec-9",
+ platform_specific={
+ "platform": "avibe",
+ "is_dm": False,
+ "agent_session_id": "ses1",
+ "agent_session_target": {"id": "ses1"},
+ "delivery_override": override,
+ "suppress_delivery": True,
+ "turn_source": "scheduled",
+ "task_trigger_kind": "task",
+ },
+ )
+ prov = session_turns.capture_scheduled_provenance(ctx)
+ # The stable native id is captured for dedup (Codex P2).
+ assert prov["message_id"] == "scheduled:exec-9"
+ spec = prov["platform_specific"]
+ # Delivery / attribution provenance kept.
+ assert spec["delivery_override"] == override
+ assert spec["suppress_delivery"] is True
+ assert spec["turn_source"] == "scheduled"
+ assert spec["task_trigger_kind"] == "task"
+ # Routing keys the flush rebuilds are NOT carried.
+ for routing in ("platform", "is_dm", "agent_session_id", "agent_session_target"):
+ assert routing not in spec