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(show): checkpoint background agent turns (#875)

Call White30e641765685
diff --git a/core/controller.py b/core/controller.py
index 130d3b710..a66020077 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -684,10 +684,6 @@ class Controller:
from core.services.dispatch import dispatch_turn
async def _on_im_message(context, text):
- checkpoint_service = getattr(self, "show_git_checkpoint_service", None)
- mark_im_turn = getattr(checkpoint_service, "mark_im_turn", None)
- if callable(mark_im_turn):
- mark_im_turn(context)
await dispatch_turn(self, context, text)
# Register callbacks with the IM client
@@ -1118,10 +1114,6 @@ class Controller:
def update_thread_message_id(self, context: MessageContext) -> None:
"""Run real-turn-start hooks after the runtime gate is acquired."""
- checkpoint_service = getattr(self, "show_git_checkpoint_service", None)
- begin_im_turn = getattr(checkpoint_service, "begin_im_turn", None)
- if callable(begin_im_turn):
- begin_im_turn(self, context)
self.message_dispatcher.update_thread_message_id(context)
async def clear_consolidated_message_id(
@@ -1283,13 +1275,6 @@ class Controller:
output: MessageOutput | None = None,
):
"""Backward-compatible entrypoint; delegated to message dispatcher."""
- checkpoint_service = getattr(self, "show_git_checkpoint_service", None)
- should_end_im_turn = getattr(checkpoint_service, "should_end_im_turn", None)
- publish_checkpoint_end = bool(
- should_end_im_turn(self, context, message_type, output=output)
- if callable(should_end_im_turn)
- else False
- )
try:
return await self.message_dispatcher.emit_agent_message(
context=context,
@@ -1303,8 +1288,10 @@ class Controller:
output=output,
)
finally:
- if publish_checkpoint_end:
- checkpoint_service.end_im_turn(context)
+ manager = getattr(self, "session_turns", None)
+ complete = getattr(manager, "on_terminal_delivery_complete", None)
+ if callable(complete):
+ complete(context)
def note_session_tokens(self, context: MessageContext, *, total: int) -> None:
"""Report the session's current context-window occupancy for the status
diff --git a/core/session_turns.py b/core/session_turns.py
index 63ad4b59c..6f969f356 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -49,6 +49,8 @@ SCHEDULED_PROVENANCE_KEY = "scheduled_provenance"
SCHEDULED_QUEUE_MERGE_WINDOW_SECONDS = 60
SCHEDULED_QUEUE_BURST_HINT_THRESHOLD = 3
SCHEDULED_QUEUE_FULL_DETAIL_LIMIT = 3
+_SHOW_CHECKPOINT_DEFERRED_START_KEY = "_avibe_show_git_deferred_start"
+_SHOW_CHECKPOINT_TERMINAL_PENDING_KEY = "_avibe_show_git_terminal_pending"
# The platform_specific keys the FLUSH rebuilds fresh from the session row (avibe
# routing). Everything ELSE the scheduled context carries is delivery / attribution
@@ -1291,31 +1293,92 @@ class SessionTurnManager:
flushed = await self.flush_queue(session_id)
return {"ok": True, "session_id": session_id, "status": "flushed" if flushed else "empty"}
- # --- the two status chokepoints (the dot is a projection of the turn) ---------
+ # --- shared turn chokepoints (status + Show checkpoint projection) ------------
+
+ def _begin_show_checkpoint(self, context: "MessageContext") -> None:
+ service = getattr(self.controller, "show_git_checkpoint_service", None)
+ begin_turn = getattr(service, "begin_turn", None)
+ if not callable(begin_turn):
+ return
+ try:
+ begin_turn(self.controller, context)
+ except Exception:
+ logger.exception("Show checkpoint start hook failed")
+
+ def _end_show_checkpoint(self, context: "MessageContext") -> None:
+ service = getattr(self.controller, "show_git_checkpoint_service", None)
+ end_turn = getattr(service, "end_turn", None)
+ if not callable(end_turn):
+ return
+ try:
+ end_turn(context)
+ except Exception:
+ logger.exception("Show checkpoint end hook failed")
+
+ @staticmethod
+ def _set_context_flag(context: "MessageContext", key: str, value: bool) -> None:
+ payload = dict(getattr(context, "platform_specific", None) or {})
+ if value:
+ payload[key] = True
+ else:
+ payload.pop(key, None)
+ context.platform_specific = payload
+
+ @staticmethod
+ def _pop_context_flag(context: "MessageContext", key: str) -> bool:
+ payload = dict(getattr(context, "platform_specific", None) or {})
+ value = bool(payload.pop(key, False))
+ context.platform_specific = payload
+ return value
+
+ def _agent_initiated_turn_will_register(self, context: "MessageContext") -> bool:
+ service = getattr(self.controller, "agent_service", None)
+ runtime_started = getattr(service, "runtime_turn_started", None)
+ if not callable(runtime_started) or runtime_started(context) is not True:
+ return False
+ session_id = self.controller._session_id_from_context(context)
+ get_key = getattr(self.controller, "_get_session_key", None)
+ if not session_id or not callable(get_key):
+ return False
+ session_key = get_key(context)
+ return session_id not in self.in_flight and self.get_turn_sink(session_key) is None
def on_running(self, context: "MessageContext") -> None:
- """INBOUND status chokepoint: mark the avibe session ``running`` when a turn
- starts (every source / backend funnels through AgentService.handle_message).
- Non-avibe turns carry no workbench session id and are skipped."""
+ """INBOUND turn chokepoint shared by every source and backend."""
if self.controller is None:
return
+ if self._agent_initiated_turn_will_register(context):
+ # Agent-initiated turns register their FSM bus lifecycle immediately
+ # after on_running. Let that start publish first so checkpointing
+ # observes path ownership and never emits a duplicate pair.
+ self._set_context_flag(context, _SHOW_CHECKPOINT_DEFERRED_START_KEY, True)
+ else:
+ self._begin_show_checkpoint(context)
session_id = self.controller._session_id_from_context(context)
if session_id:
self.controller.set_agent_status(session_id, "running")
def on_terminal_result(self, context: "MessageContext", *, is_error: bool) -> None:
- """OUTBOUND status chokepoint: settle the avibe dot when the ACTIVE turn's
- terminal ``result`` is emitted — ``idle`` normally, ``failed`` on
- ``is_error``. A late result from a superseded / stopped turn (the active-turn
- guard) or a non-avibe context (no session id) is skipped, so it can't flip a
- newer turn's ``running`` back."""
+ """OUTBOUND turn chokepoint for the active terminal ``result``."""
if self.controller is None:
return
+ if not self.is_active_emit(context):
+ return
+ # The dispatcher calls this before delivery. Record authority now, then
+ # checkpoint from Controller.emit_agent_message's post-delivery finally.
+ self._set_context_flag(context, _SHOW_CHECKPOINT_TERMINAL_PENDING_KEY, True)
session_id = self.controller._session_id_from_context(context)
- if not session_id or not self.is_active_emit(context):
+ if not session_id:
return
self.controller.set_agent_status(session_id, "failed" if is_error else "idle")
+ def on_terminal_delivery_complete(self, context: "MessageContext") -> None:
+ """Checkpoint an accepted terminal result after delivery and persistence."""
+
+ if not self._pop_context_flag(context, _SHOW_CHECKPOINT_TERMINAL_PENDING_KEY):
+ return
+ self._end_show_checkpoint(context)
+
def register_agent_initiated_turn(self, context: "MessageContext") -> bool:
"""Register a turn the BACKEND started on its own (agent-initiated:
background-task completion / ScheduleWakeup) as a first-class FSM citizen,
@@ -1394,6 +1457,8 @@ class SessionTurnManager:
return False
self.in_flight[session_id] = Turn(task=task, context=context)
bus.publish("turn.start", {"session_id": session_id})
+ if self._pop_context_flag(context, _SHOW_CHECKPOINT_DEFERRED_START_KEY):
+ self._begin_show_checkpoint(context)
return True
def is_active_emit(self, context: "MessageContext") -> bool:
diff --git a/core/show_git.py b/core/show_git.py
index 49c73fdfb..f733b318d 100644
--- a/core/show_git.py
+++ b/core/show_git.py
@@ -16,7 +16,6 @@ from typing import Any
from config import paths
from core.git_binary import ResolvedGit, resolve_git
-from core.message_output import MessageOutput
logger = logging.getLogger(__name__)
@@ -34,7 +33,7 @@ _CHECKPOINT_KINDS = {PRE_TURN, POST_TURN, ADOPT}
_MANAGED_POINTER_PARENT = "show-git"
_SESSION_ID_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$")
_MAIN_ANCHOR_REF = "refs/avibe/checkpoint-main"
-_IM_TURN_STATE_KEY = "_avibe_show_git_checkpoint"
+_TURN_STATE_KEY = "_avibe_show_git_checkpoint"
_CHECKPOINT_STATUS_VERSION = 1
_checkpoint_service_active: bool | None = None
_SCRUBBED_GIT_ENV = {
@@ -598,6 +597,7 @@ class ShowGitCheckpointService:
self._bus: Any = None
self._subscription_id: int | None = None
self._active_turns: dict[str, _ActiveTurnCheckpoint] = {}
+ self._open_bus_turns: set[str] = set()
@property
def enabled(self) -> bool:
@@ -624,23 +624,17 @@ class ShowGitCheckpointService:
self._bus = None
self._subscription_id = None
self._active_turns.clear()
+ self._open_bus_turns.clear()
_record_checkpoint_service_state(False)
_checkpoint_service_active = None
@staticmethod
- def _im_turn_state(context: Any) -> dict[str, Any] | None:
- state = (getattr(context, "platform_specific", None) or {}).get(_IM_TURN_STATE_KEY)
+ def _turn_state(context: Any) -> dict[str, Any] | None:
+ state = (getattr(context, "platform_specific", None) or {}).get(_TURN_STATE_KEY)
return state if isinstance(state, dict) else None
- def mark_im_turn(self, context: Any) -> None:
- if not self.enabled:
- return
- payload = dict(getattr(context, "platform_specific", None) or {})
- payload[_IM_TURN_STATE_KEY] = {"start_published": False, "ended": False}
- context.platform_specific = payload
-
@staticmethod
- def _existing_im_session_id(controller: Any, context: Any) -> str | None:
+ def _existing_session_id(controller: Any, context: Any) -> str | None:
session_id = controller._session_id_from_context(context)
if session_id:
return session_id
@@ -652,7 +646,7 @@ class ShowGitCheckpointService:
try:
row = finder(controller._get_session_key(context), base_session_id)
except Exception:
- logger.debug("IM Show checkpoint session lookup failed", exc_info=True)
+ logger.debug("Show checkpoint session lookup failed", exc_info=True)
return None
session_id = str(row.get("id") or "").strip() if row else ""
if not session_id:
@@ -663,7 +657,7 @@ class ShowGitCheckpointService:
return session_id
@staticmethod
- def _link_im_message(context: Any, session_id: str) -> bool:
+ def _link_message(context: Any, session_id: str) -> bool:
platform = str(getattr(context, "platform", None) or "").strip()
message_id = str(getattr(context, "message_id", None) or "").strip()
if not platform or platform == "avibe" or not message_id:
@@ -678,63 +672,58 @@ class ShowGitCheckpointService:
)
return True
except Exception:
- logger.debug("IM Show checkpoint message link failed", exc_info=True)
+ logger.debug("Show checkpoint message link failed", exc_info=True)
return False
- def begin_im_turn(self, controller: Any, context: Any) -> None:
- state = self._im_turn_state(context)
- if self._bus is None or state is None or state.get("start_published"):
+ def begin_turn(self, controller: Any, context: Any) -> None:
+ """Publish checkpoint start from the shared backend execution boundary."""
+
+ if self._bus is None:
+ return
+ state = self._turn_state(context)
+ if state is None or state.get("ended"):
+ state = {"start_observed": False, "ended": False}
+ if state.get("start_observed"):
return
- session_id = self._existing_im_session_id(controller, context)
+ payload = dict(getattr(context, "platform_specific", None) or {})
+ payload[_TURN_STATE_KEY] = state
+ context.platform_specific = payload
+ session_id = self._existing_session_id(controller, context)
if not session_id:
- # A first-ever IM turn has no Show workspace yet. Its terminal event
- # lazily adopts the workspace if the turn creates one.
+ # A first-ever turn can bind its session only after backend dispatch.
+ # Keep the state on the context so terminal delivery can lazily adopt
+ # a workspace created during that turn.
return
+ owns_bus_lifecycle = session_id not in self._open_bus_turns
state = {
**state,
- "start_published": True,
+ "start_observed": True,
"start_session_id": session_id,
- "message_linked": self._link_im_message(context, session_id),
+ "owns_bus_lifecycle": owns_bus_lifecycle,
+ "message_linked": self._link_message(context, session_id),
}
payload = dict(context.platform_specific or {})
- payload[_IM_TURN_STATE_KEY] = state
+ payload[_TURN_STATE_KEY] = state
context.platform_specific = payload
- self._bus.publish("turn.start", {"session_id": session_id})
+ # Workbench and /internal/dispatch may already have published their UI
+ # lifecycle before backend execution reached this shared boundary.
+ if owns_bus_lifecycle:
+ self._bus.publish("turn.start", {"session_id": session_id})
- def should_end_im_turn(
- self,
- controller: Any,
- context: Any,
- message_type: str,
- *,
- output: MessageOutput | None = None,
- ) -> bool:
- state = self._im_turn_state(context)
- if self._bus is None or message_type != "result" or state is None or state.get("ended"):
- return False
- if output is not None and (not output.completes_turn or output.detached):
- return False
- matches = getattr(getattr(controller, "agent_service", None), "emit_matches_runtime_turn", None)
- if not callable(matches):
- return True
- try:
- return bool(matches(context))
- except Exception:
- logger.debug("IM Show checkpoint active-turn check failed", exc_info=True)
- return True
+ def end_turn(self, context: Any) -> None:
+ """Publish checkpoint end from the shared terminal-result boundary."""
- def end_im_turn(self, context: Any) -> None:
- state = self._im_turn_state(context)
+ state = self._turn_state(context)
if self._bus is None or state is None or state.get("ended"):
return
payload = dict(getattr(context, "platform_specific", None) or {})
session_id = str(payload.get("agent_session_id") or state.get("start_session_id") or "").strip()
message_linked = bool(state.get("message_linked"))
if session_id and not message_linked:
- message_linked = self._link_im_message(context, session_id)
- payload[_IM_TURN_STATE_KEY] = {**state, "ended": True, "message_linked": message_linked}
+ message_linked = self._link_message(context, session_id)
+ payload[_TURN_STATE_KEY] = {**state, "ended": True, "message_linked": message_linked}
context.platform_specific = payload
- if session_id:
+ if session_id and (not state.get("start_observed") or state.get("owns_bus_lifecycle")):
self._bus.publish("turn.end", {"session_id": session_id})
def _handle_event(self, event_type: str, data: Any) -> None:
@@ -743,6 +732,10 @@ class ShowGitCheckpointService:
session_id = str(data.get("session_id") or "").strip()
if not _SESSION_ID_PATTERN.fullmatch(session_id):
return
+ if event_type == "turn.start":
+ self._open_bus_turns.add(session_id)
+ else:
+ self._open_bus_turns.discard(session_id)
if not paths.get_show_page_dir(session_id).is_dir():
if event_type == "turn.end":
self._active_turns.pop(session_id, None)
diff --git a/docs/plans/show-page-durability.md b/docs/plans/show-page-durability.md
index dfdbd17a2..9e00de858 100644
--- a/docs/plans/show-page-durability.md
+++ b/docs/plans/show-page-durability.md
@@ -15,10 +15,13 @@ branch to the existing worktree at each session turn boundary.
- Lazily adopt only existing workspaces into external gitdirs under
`~/.avibe/show-git/`; write the workspace `.git` pointer only when Avibe owns
it, and use shadow checkpoints beside user-managed repositories.
-- Subscribe in the controller to `turn.start` and `turn.end`; normalize the
- legacy streaming Show dispatch and direct IM turns onto that bus without
- touching the shared turn manager, and never create Show Page workspaces from
- checkpoint paths.
+- Subscribe in the controller to `turn.start` and `turn.end`; project checkpoint
+ lifecycle from the shared inbound/terminal turn chokepoints every backend and
+ source traverses. Existing Workbench and streaming dispatch events remain for
+ their UI/cancellation lifecycle, while context-local state makes overlap
+ idempotent. Terminal authority is recorded before delivery, then the checkpoint
+ runs after delivery/persistence and before the event loop can start the next
+ gated turn. Checkpoint paths never create Show Page workspaces.
- Isolate every platform Git invocation from ambient Git environment, global
configuration, signing, hooks, and automatic GC.
- Self-heal only provably Avibe-owned or dangling state, bound retained history,
@@ -33,3 +36,13 @@ branch to the existing worktree at each session turn boundary.
- Route coverage for private/public runtime proxy and static fallback boundaries.
- Incus edit/overwrite/restore/forward-commit verification remains an
integration-pass check after the coordinated milestone lands.
+
+## Integration Follow-up
+
+The first implementation attached lifecycle publication to the known transport
+paths, so background Agent Runs, scheduled tasks, and watch callbacks could reach
+the backend without checkpoint events. The follow-up closes that architectural
+gap at `SessionTurnManager.on_running` / `on_terminal_result`, after the runtime
+gate and at the authorized terminal output respectively; controller delivery
+completion executes the post-turn checkpoint. `MESSAGE-DELIVERY-006` enumerates
+every current turn entry point against this shared contract.
diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yaml
index 8702e70be..df0e1e957 100644
--- a/tests/scenarios/message_delivery/catalog.yaml
+++ b/tests/scenarios/message_delivery/catalog.yaml
@@ -43,6 +43,12 @@ scenarios:
kind: lifecycle
layer: contract
test: tests/test_scheduled_tasks.py::test_agent_run_forwards_multiple_outputs_and_completes_once
+ - id: MESSAGE-DELIVERY-006
+ name: Every turn entry point reaches Show checkpoint lifecycle
+ status: covered
+ kind: lifecycle
+ layer: contract
+ test: tests/test_show_git_turn_entrypoints.py::test_all_turn_entrypoints_reach_checkpoint_subscriber
next_priority:
- MESSAGE-DELIVERY-101
- MESSAGE-DELIVERY-102
diff --git a/tests/test_controller_dispatch_loop.py b/tests/test_controller_dispatch_loop.py
index e0c7ba72e..b067b43e9 100644
--- a/tests/test_controller_dispatch_loop.py
+++ b/tests/test_controller_dispatch_loop.py
@@ -12,6 +12,7 @@ from core.controller import Controller
from core.git_binary import ResolvedGit
from core.inbox_events import InboxEventBus
from core.message_output import MessageOutput
+from core.session_turns import SessionTurnManager
from core.show_git import ShowGitCheckpointService
from modules.im import MessageContext
@@ -261,6 +262,7 @@ def test_im_show_checkpoint_lifecycle_spans_real_start_to_terminal_result(monkey
checkpoint_bus = InboxEventBus()
checkpoint_service.start(checkpoint_bus)
controller.show_git_checkpoint_service = checkpoint_service
+ controller.session_turns = SessionTurnManager(controller)
monkeypatch.setattr(
"core.message_mirror.link_inbound_message_session",
lambda **kwargs: linked_messages.append(kwargs),
@@ -272,7 +274,6 @@ def test_im_show_checkpoint_lifecycle_spans_real_start_to_terminal_result(monkey
message_id="msg-1",
platform_specific={},
)
- checkpoint_service.mark_im_turn(context)
context.platform_specific["turn_base_session_id"] = "anchor"
lifecycle = []
subscription_id = checkpoint_bus.subscribe_callback(
@@ -281,6 +282,7 @@ def test_im_show_checkpoint_lifecycle_spans_real_start_to_terminal_result(monkey
else None
)
try:
+ controller.session_turns.on_running(context)
controller.update_thread_message_id(context)
detached_result = asyncio.run(
controller.emit_agent_message(
@@ -292,7 +294,11 @@ def test_im_show_checkpoint_lifecycle_spans_real_start_to_terminal_result(monkey
)
assert lifecycle == [("turn.start", {"session_id": "ses_im"})]
first_result = asyncio.run(controller.emit_agent_message(context, "result", "done"))
+ controller.session_turns.on_terminal_result(context, is_error=False)
+ controller.session_turns.on_terminal_delivery_complete(context)
second_result = asyncio.run(controller.emit_agent_message(context, "result", "duplicate"))
+ controller.session_turns.on_terminal_result(context, is_error=False)
+ controller.session_turns.on_terminal_delivery_complete(context)
finally:
checkpoint_bus.unsubscribe(subscription_id)
checkpoint_service.stop()
@@ -337,6 +343,7 @@ def test_first_im_show_turn_adopts_on_terminal_after_backend_binds_session(monke
checkpoint_bus = InboxEventBus()
checkpoint_service.start(checkpoint_bus)
controller.show_git_checkpoint_service = checkpoint_service
+ controller.session_turns = SessionTurnManager(controller)
monkeypatch.setattr(
"core.message_mirror.link_inbound_message_session",
lambda **kwargs: linked_messages.append(kwargs),
@@ -348,7 +355,6 @@ def test_first_im_show_turn_adopts_on_terminal_after_backend_binds_session(monke
message_id="msg-new",
platform_specific={},
)
- checkpoint_service.mark_im_turn(context)
context.platform_specific["turn_base_session_id"] = "new-anchor"
lifecycle = []
subscription_id = checkpoint_bus.subscribe_callback(
@@ -357,10 +363,13 @@ def test_first_im_show_turn_adopts_on_terminal_after_backend_binds_session(monke
else None
)
try:
+ controller.session_turns.on_running(context)
controller.update_thread_message_id(context)
assert lifecycle == []
context.platform_specific["agent_session_id"] = "ses_new_im"
asyncio.run(controller.emit_agent_message(context, "result", "done"))
+ controller.session_turns.on_terminal_result(context, is_error=False)
+ controller.session_turns.on_terminal_delivery_complete(context)
finally:
checkpoint_bus.unsubscribe(subscription_id)
checkpoint_service.stop()
@@ -373,3 +382,40 @@ def test_first_im_show_turn_adopts_on_terminal_after_backend_binds_session(monke
"session_id": "ses_new_im",
}
]
+
+
+def test_terminal_checkpoint_runs_after_dispatcher_delivery() -> None:
+ controller = Controller.__new__(Controller)
+ order = []
+
+ class _CheckpointService:
+ @staticmethod
+ def begin_turn(_controller, _context) -> None:
+ order.append("checkpoint-start")
+
+ @staticmethod
+ def end_turn(_context) -> None:
+ order.append("checkpoint-end")
+
+ class _Dispatcher:
+ async def emit_agent_message(self, **kwargs):
+ controller.session_turns.on_terminal_result(kwargs["context"], is_error=False)
+ order.append("delivered")
+ return "result-1"
+
+ controller.show_git_checkpoint_service = _CheckpointService()
+ controller.message_dispatcher = _Dispatcher()
+ controller.set_agent_status = lambda _session_id, _status: None
+ controller.session_turns = SessionTurnManager(controller)
+ context = MessageContext(
+ user_id="U",
+ channel_id="C",
+ platform="slack",
+ platform_specific={"agent_session_id": "ses_delivery_order"},
+ )
+
+ controller.session_turns.on_running(context)
+ result = asyncio.run(controller.emit_agent_message(context, "result", "done"))
+
+ assert result == "result-1"
+ assert order == ["checkpoint-start", "delivered", "checkpoint-end"]
diff --git a/tests/test_controller_platform_reconcile.py b/tests/test_controller_platform_reconcile.py
index 919cf52b4..fae0941e5 100644
--- a/tests/test_controller_platform_reconcile.py
+++ b/tests/test_controller_platform_reconcile.py
@@ -189,11 +189,9 @@ def test_reconcile_adds_platform_with_callbacks_before_start(monkeypatch):
assert controller.im_client.clients["discord"].settings_manager.platform == "discord"
-def test_im_message_callback_marks_checkpoint_turn_before_dispatch(monkeypatch):
+def test_im_message_callback_uses_shared_dispatch_without_transport_checkpoint_shim(monkeypatch):
controller = _controller(_config(["slack"]))
- marked = []
dispatched = []
- controller.show_git_checkpoint_service = SimpleNamespace(mark_im_turn=lambda context: marked.append(context))
async def _dispatch(_controller, context, text):
dispatched.append((context, text))
@@ -208,7 +206,6 @@ def test_im_message_callback_marks_checkpoint_turn_before_dispatch(monkeypatch):
asyncio.run(_run_callback())
- assert marked == [context]
assert dispatched == [(context, "hello")]
diff --git a/tests/test_show_git.py b/tests/test_show_git.py
index 320b828b3..6fb556c0a 100644
--- a/tests/test_show_git.py
+++ b/tests/test_show_git.py
@@ -1,18 +1,22 @@
from __future__ import annotations
+import asyncio
import json
import os
import shutil
import subprocess
import time
from pathlib import Path
+from types import SimpleNamespace
import pytest
from config import paths
from core import show_git
+from core import inbox_events
from core.git_binary import ResolvedGit
from core.inbox_events import InboxEventBus
+from core.session_turns import SessionTurnManager
from core.show_git import (
POST_TURN,
PRE_TURN,
@@ -584,6 +588,126 @@ def test_duplicate_turn_events_do_not_create_duplicate_checkpoint_commits(resolv
]
+def test_shared_turn_hooks_reuse_path_owned_bus_lifecycle(resolved_git, monkeypatch):
+ session_id = "ses_path_owned"
+ context = SimpleNamespace(platform="avibe", platform_specific={"agent_session_id": session_id})
+ controller = SimpleNamespace(
+ _session_id_from_context=lambda _context: session_id,
+ _get_session_key=lambda _context: "avibe::ses_path_owned",
+ )
+ calls = []
+
+ class FakeRepository:
+ def checkpoint(self, checkpoint, **kwargs):
+ calls.append((checkpoint, kwargs))
+ return True
+
+ monkeypatch.setattr(
+ show_git,
+ "load_turn_checkpoint_context",
+ lambda _session_id, **_kwargs: TurnCheckpointContext(message="edit page", message_id="message-1"),
+ )
+ service = ShowGitCheckpointService(resolved_git)
+ monkeypatch.setattr(service, "_repository", lambda _session_id: FakeRepository())
+ bus = InboxEventBus()
+ service.start(bus)
+ lifecycle = []
+ subscription_id = bus.subscribe_callback(
+ lambda event_type, data: lifecycle.append((event_type, data))
+ if event_type in {"turn.start", "turn.end"}
+ else None
+ )
+
+ try:
+ bus.publish("turn.start", {"session_id": session_id})
+ service.begin_turn(controller, context)
+ _workspace(session_id)
+ service.end_turn(context)
+ bus.publish("turn.end", {"session_id": session_id})
+ finally:
+ bus.unsubscribe(subscription_id)
+ service.stop()
+
+ assert lifecycle == [
+ ("turn.start", {"session_id": session_id}),
+ ("turn.end", {"session_id": session_id}),
+ ]
+ assert calls == [(POST_TURN, {"message": "edit page", "run_id": None})]
+
+
+def test_agent_initiated_turn_reuses_fsm_bus_lifecycle(resolved_git, monkeypatch):
+ session_id = "ses_agent_initiated"
+ _workspace(session_id)
+ calls = []
+
+ class FakeRepository:
+ def checkpoint(self, checkpoint, **kwargs):
+ calls.append((checkpoint, kwargs))
+ return True
+
+ monkeypatch.setattr(
+ show_git,
+ "load_turn_checkpoint_context",
+ lambda _session_id, **_kwargs: TurnCheckpointContext(message="background result", message_id="message-1"),
+ )
+ service = ShowGitCheckpointService(resolved_git)
+ monkeypatch.setattr(service, "_repository", lambda _session_id: FakeRepository())
+ bus = InboxEventBus()
+ monkeypatch.setattr(inbox_events, "bus", bus)
+ service.start(bus)
+ lifecycle = []
+ subscription_id = bus.subscribe_callback(
+ lambda event_type, data: lifecycle.append((event_type, data))
+ if event_type in {"turn.start", "turn.end"}
+ else None
+ )
+ context = SimpleNamespace(
+ platform="avibe",
+ channel_id=session_id,
+ platform_specific={"agent_session_id": session_id, "turn_token": "turn-agent"},
+ )
+ controller = SimpleNamespace(
+ _session_id_from_context=lambda _context: session_id,
+ _get_session_key=lambda _context: f"avibe::{session_id}",
+ set_agent_status=lambda _session_id, _status: None,
+ show_git_checkpoint_service=service,
+ agent_service=SimpleNamespace(runtime_turn_started=lambda _context: True),
+ )
+ manager = SessionTurnManager(controller)
+ controller.get_turn_sink = manager.get_turn_sink
+
+ async def _flush_queue(_session_id: str) -> bool:
+ return False
+
+ manager.flush_queue = _flush_queue
+
+ async def _exercise() -> None:
+ manager.on_running(context)
+ assert lifecycle == []
+ assert manager.register_agent_initiated_turn(context) is True
+ manager.on_terminal_result(context, is_error=False)
+ manager.on_terminal_delivery_complete(context)
+ sink = manager.get_turn_sink(f"avibe::{session_id}")
+ assert sink is not None
+ sink["done_event"].set()
+ await manager.in_flight[session_id].task
+
+ try:
+ asyncio.run(_exercise())
+ finally:
+ bus.unsubscribe(subscription_id)
+ service.stop()
+
+ assert lifecycle == [
+ ("turn.start", {"session_id": session_id}),
+ ("turn.end", {"session_id": session_id}),
+ ]
+ assert calls == [
+ (PRE_TURN, {"run_id": None}),
+ (POST_TURN, {"message": "background result", "run_id": None}),
+ ]
+
+
def test_agent_contract_uses_startup_latched_checkpoint_service_state(resolved_git, monkeypatch):
bus = InboxEventBus()
unavailable_service = ShowGitCheckpointService(None)
diff --git a/tests/test_show_git_turn_entrypoints.py b/tests/test_show_git_turn_entrypoints.py
new file mode 100644
index 000000000..470b8e236
--- /dev/null
+++ b/tests/test_show_git_turn_entrypoints.py
@@ -0,0 +1,325 @@
+"""Contract coverage for Show checkpoints across every turn entry point."""
+
+from __future__ import annotations
+
+import asyncio
+from collections import defaultdict
+from types import SimpleNamespace
+
+import httpx
+
+from config import paths
+from core import inbox_events, internal_server, show_git
+from core.git_binary import ResolvedGit
+from core.inbox_events import InboxEventBus
+from core.message_dispatcher import ConsolidatedMessageDispatcher
+from core.message_output import MessageOutput
+from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore, TaskExecutionStore
+from core.services.dispatch import dispatch_turn
+from core.session_turns import SessionTurnManager, emit_matches_active_turn
+from core.show_git import POST_TURN, PRE_TURN, ShowGitCheckpointService, TurnCheckpointContext
+from modules.agents.service import AgentService
+from modules.im import MessageContext
+from storage.importer import ensure_sqlite_state
+
+
+class _Settings:
+ @staticmethod
+ def _canonicalize_message_type(message_type: str) -> str:
+ return message_type
+
+ @staticmethod
+ def is_message_type_hidden(_settings_key: str, _message_type: str) -> bool:
+ return False
+
+
+class _IMClient:
+ @staticmethod
+ def should_use_thread_for_reply() -> bool:
+ return False
+
+
+class _TerminalDispatcher:
+ def __init__(self, controller) -> None:
+ self._delegate = ConsolidatedMessageDispatcher(controller)
+
+ @staticmethod
+ async def begin_status_bubble(_context) -> None:
+ return None
+
+ @staticmethod
+ def update_thread_message_id(_context) -> None:
+ return None
+
+ async def emit_agent_message(self, **kwargs):
+ return await self._delegate.emit_agent_message(**kwargs)
+
+
+class _TerminalAgent:
+ name = "checkpoint-probe"
+
+ def __init__(self, controller) -> None:
+ self.controller = controller
+
+ @staticmethod
+ def runtime_turn_key(request) -> str:
+ return request.composite_session_id
+
+ async def handle_message(self, request) -> None:
+ await self.controller.emit_agent_message(
+ request.context,
+ "result",
+ "",
+ level="silent",
+ output=MessageOutput(completes_turn=True, completes_run=False),
+ )
+
+
+class _MessageHandler:
+ def __init__(self, controller) -> None:
+ self.controller = controller
+
+ async def _run(self, context: MessageContext, message: str) -> None:
+ session_id = (context.platform_specific or {}).get("agent_session_id")
+ request = SimpleNamespace(
+ context=context,
+ message=message,
+ composite_session_id=f"runtime:{session_id}",
+ processing_indicator=None,
+ )
+ await self.controller.agent_service.handle_message("checkpoint-probe", request)
+
+ async def handle_user_message(self, context: MessageContext, message: str):
+ await self._run(context, message)
+ return None
+
+ async def handle_scheduled_message(self, context: MessageContext, message: str, parsed_session_key=None):
+ del parsed_session_key
+ await self._run(context, message)
+ return None
+
+
+class _Controller:
+ def __init__(self, checkpoint_service: ShowGitCheckpointService) -> None:
+ self.config = SimpleNamespace(reply_enhancements=False)
+ self.show_git_checkpoint_service = checkpoint_service
+ self.statuses = []
+ self.session_turns = SessionTurnManager(self)
+ self.session_turn_gate = self.session_turns
+ self.agent_service = AgentService(self)
+ self.agent_service.register(_TerminalAgent(self))
+ self.message_dispatcher = _TerminalDispatcher(self)
+ self.message_handler = _MessageHandler(self)
+ self.processing_indicator = None
+ self.command_handler = SimpleNamespace(handle_stop=self._stop)
+
+ @staticmethod
+ async def _stop(_context) -> bool:
+ return True
+
+ @staticmethod
+ def _session_id_from_context(context) -> str | None:
+ return (context.platform_specific or {}).get("agent_session_id")
+
+ @staticmethod
+ def _get_settings_key(context) -> str:
+ return context.channel_id
+
+ @staticmethod
+ def get_settings_manager_for_context(_context) -> _Settings:
+ return _Settings()
+
+ @staticmethod
+ def get_im_client_for_context(_context) -> _IMClient:
+ return _IMClient()
+
+ @staticmethod
+ def _get_session_key(context) -> str:
+ return f"{context.platform}::{context.channel_id}"
+
+ def register_turn_sink(self, session_key: str, **kwargs) -> None:
+ self.session_turns.register_turn_sink(session_key, **kwargs)
+
+ def pop_turn_sink(self, session_key: str, done_event=None) -> None:
+ self.session_turns.pop_turn_sink(session_key, done_event)
+
+ def get_turn_sink(self, session_key: str):
+ return self.session_turns.get_turn_sink(session_key)
+
+ def mark_turn_complete(self, context=None) -> None:
+ if context is None:
+ return
+ sink = self.get_turn_sink(self._get_session_key(context))
+ if sink is None or not emit_matches_active_turn(sink, context):
+ return
+ done = sink.get("done_event")
+ if done is not None:
+ done.set()
+
+ def set_agent_status(self, session_id: str, status: str) -> None:
+ self.statuses.append((session_id, status))
+
+ def update_thread_message_id(self, context) -> None:
+ self.message_dispatcher.update_thread_message_id(context)
+
+ async def emit_agent_message(self, context, message_type, text, **kwargs):
+ try:
+ return await self.message_dispatcher.emit_agent_message(
+ context=context,
+ message_type=message_type,
+ text=text,
+ **kwargs,
+ )
+ finally:
+ self.session_turns.on_terminal_delivery_complete(context)
+
+ @staticmethod
+ def _t(key: str, **_kwargs) -> str:
+ return key
+
+
+def _context(name: str, *, platform: str, trigger_kind: str | None = None) -> MessageContext:
+ session_id = f"ses_{name}"
+ metadata = {
+ "platform": platform,
+ "agent_session_id": session_id,
+ "task_execution_id": f"run-{name}",
+ }
+ if trigger_kind:
+ metadata["task_trigger_kind"] = trigger_kind
+ metadata["turn_source"] = "scheduled"
+ return MessageContext(
+ user_id="user",
+ channel_id=session_id,
+ platform=platform,
+ message_id=f"message-{name}",
+ platform_specific=metadata,
+ )
+
+
+def test_all_turn_entrypoints_reach_checkpoint_subscriber(monkeypatch, tmp_path) -> None:
+ """Scenario: MESSAGE-DELIVERY-006."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ contexts = {
+ "im_message": _context("im_message", platform="slack"),
+ "workbench_chat": _context("workbench_chat", platform="avibe"),
+ "internal_dispatch": _context("internal_dispatch", platform="avibe"),
+ "agent_run_sync": _context("agent_run_sync", platform="slack", trigger_kind="agent_run"),
+ "agent_run_async": _context("agent_run_async", platform="slack", trigger_kind="agent_run"),
+ "scheduled_task": _context("scheduled_task", platform="slack", trigger_kind="scheduled"),
+ "watch_callback": _context("watch_callback", platform="slack", trigger_kind="watch"),
+ }
+ checkpoint_calls = defaultdict(list)
+
+ class _Repository:
+ def __init__(self, session_id: str) -> None:
+ self.session_id = session_id
+
+ def checkpoint(self, checkpoint: str, **_kwargs) -> bool:
+ checkpoint_calls[self.session_id].append(checkpoint)
+ return True
+
+ monkeypatch.setattr(
+ show_git,
+ "load_turn_checkpoint_context",
+ lambda session_id, **_kwargs: TurnCheckpointContext(
+ message=f"drive {session_id}",
+ message_id=f"message-{session_id}",
+ ),
+ )
+ service = ShowGitCheckpointService(ResolvedGit(path=tmp_path / "git", source="system"))
+ monkeypatch.setattr(service, "_repository", lambda session_id: _Repository(session_id))
+ monkeypatch.setattr(service, "_link_message", lambda _context, _session_id: True)
+ bus = InboxEventBus()
+ monkeypatch.setattr(inbox_events, "bus", bus)
+ service.start(bus)
+ controller = _Controller(service)
+ lifecycle = []
+ subscription_id = bus.subscribe_callback(
+ lambda event_type, data: lifecycle.append((event_type, data))
+ if event_type in {"turn.start", "turn.end"}
+ else None
+ )
+ for context in contexts.values():
+ paths.get_show_page_dir(context.platform_specific["agent_session_id"]).mkdir(parents=True)
+
+ scheduled = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=TaskExecutionStore(tmp_path / "task_requests"),
+ )
+
+ async def _build_scheduled_context(
+ _target,
+ *,
+ execution_id: str,
+ **_kwargs,
+ ) -> MessageContext:
+ return contexts[execution_id]
+
+ monkeypatch.setattr(scheduled, "_build_context", _build_scheduled_context)
+
+ async def _build_dispatch_payload(payload) -> tuple[str, MessageContext]:
+ return "edit show page", contexts[payload["entrypoint"]]
+
+ monkeypatch.setattr(internal_server, "_build_dispatch_payload", _build_dispatch_payload)
+ app = internal_server.create_app(controller)
+
+ async def _exercise() -> None:
+ await dispatch_turn(controller, contexts["im_message"], "IM message")
+
+ workbench = contexts["workbench_chat"]
+ workbench_id = workbench.platform_specific["agent_session_id"]
+ await controller.session_turns.submit(workbench_id, workbench, "Workbench chat")
+ await controller.session_turns.in_flight[workbench_id].task
+
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ response = await client.post(
+ "/internal/dispatch",
+ json={"session_id": "ses_internal_dispatch", "entrypoint": "internal_dispatch"},
+ )
+ assert response.status_code == 200
+
+ # Sync and async CLI modes enqueue the same Agent Run execution; only
+ # the CLI caller's wait behavior differs. Exercise that executor twice.
+ for name in ("agent_run_sync", "agent_run_async"):
+ await scheduled._execute_agent_run(
+ session_key="slack::channel::C123",
+ session_id=None,
+ post_to=None,
+ deliver_key=None,
+ message=name,
+ execution_id=name,
+ )
+
+ for name in ("scheduled_task", "watch_callback"):
+ await scheduled._execute_request(
+ session_key="slack::channel::C123",
+ session_id=None,
+ post_to=None,
+ deliver_key=None,
+ prompt=name,
+ execution_id=name,
+ trigger_kind=contexts[name].platform_specific["task_trigger_kind"],
+ )
+
+ try:
+ asyncio.run(_exercise())
+ finally:
+ bus.unsubscribe(subscription_id)
+ service.stop()
+
+ expected_lifecycle = []
+ for name, context in contexts.items():
+ session_id = context.platform_specific["agent_session_id"]
+ expected_lifecycle.extend(
+ [
+ ("turn.start", {"session_id": session_id}),
+ ("turn.end", {"session_id": session_id}),
+ ]
+ )
+ assert checkpoint_calls[session_id] == [PRE_TURN, POST_TURN], name
+ assert lifecycle == expected_lifecycle