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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(harness): reconcile run cancellation ownership
cyhcb7aff5ca95a
diff --git a/core/session_turns.py b/core/session_turns.pyindex 2ee3bded5..e55450d30 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -3070,25 +3070,8 @@ class SessionTurnManager:request.content is Noneand expected_turn_idand current_id != expected_turn_id+ and not expected_exclusive_run_id):- if expected_exclusive_run_id:- cancellation = apply_live_agent_run_cancellation_in_connection(- conn,- expected_exclusive_run_id,- session_id=request.session_id,- detach=True,- )- return DeliveryResult(- None,- None,- (- "run_detached"- if cancellation == "run_detached"- else "settled"- ),- current_id,- cancellation,- )return DeliveryResult(None,None,@@ -3526,6 +3509,15 @@ class SessionTurnManager:"control_receipt_json": json.dumps({"reason": reason or "stop_error"}, sort_keys=True),+ **(+ {+ "control_mode": None,+ "control_successor_delivery_id": None,+ "control_successor_turn_id": None,+ }+ if definitive and not terminal_proven+ else {}+ ),},)receipt_result = {diff --git a/storage/message_deliveries.py b/storage/message_deliveries.pyindex 8dc79b5ba..cb7a57536 100644--- a/storage/message_deliveries.py+++ b/storage/message_deliveries.py@@ -1786,10 +1786,10 @@ def agent_run_exclusively_owns_turn() -> tuple[bool, str]:"""Whether stopping ``run_id`` may safely interrupt the exact Turn.- An accepted steer is a participant in an existing Turn, not its owner. A- Run-level cancel must therefore stay local unless the Run's Delivery is the- Turn's initial and only accepted input. The caller holds SQLite's writer- reservation while asking, so a concurrent steer cannot slip between this+ A Run may own either the sole claimed input of a starting Turn or the sole+ accepted input of an active Turn. Steers, claimed batch siblings, and live+ replacement control are independent participants. The caller holds SQLite's+ writer reservation while asking, so no participant can slip between thisproof and the P0 control-slot write."""@@ -1821,8 +1821,12 @@ def agent_run_exclusively_owns_turn(return False, "run_delivery_missing"if str(row["session_id"] or "") != str(turn["session_id"] or ""):return False, "run_session_mismatch"- if str(row["turn_id"] or "") != normalized_turn_id or row["state"] != "accepted":- return False, "run_not_accepted_by_turn"+ expected_delivery_state = "claimed" if turn["state"] == "starting" else "accepted"+ if (+ str(row["turn_id"] or "") != normalized_turn_id+ or row["state"] != expected_delivery_state+ ):+ return False, "run_not_owned_by_turn"if str(row["delivery_id"] or "") != str(turn["initial_delivery_id"] or ""):return False, "run_is_steered_participant"if str(row["status"] or "").strip().lower() not in {@@ -1830,12 +1834,35 @@ def agent_run_exclusively_owns_turn("processing",}:return False, "run_not_running"- if (- turn.get("control_mode") == "replace"- or turn.get("control_successor_delivery_id")- or turn.get("control_successor_turn_id")- ):- return False, "turn_has_replacement_successor"+ if agent_run_ids_for_delivery(conn, {"id": row["delivery_id"]}) != [+ normalized_run_id+ ]:+ return False, "delivery_has_other_runs"+ if turn.get("control_mode") == "replace" and turn.get("control_state") in {+ "pending",+ "interrupting",+ "waiting_terminal",+ "reconciling",+ }:+ successor_turn_id = str(turn.get("control_successor_turn_id") or "")+ successor_delivery_id = str(+ turn.get("control_successor_delivery_id") or ""+ )+ successor = get_turn(conn, successor_turn_id)+ successor_delivery = get_delivery(conn, successor_delivery_id)+ if (+ successor is not None+ and successor["state"] == "waiting"+ and successor["session_id"] == turn["session_id"]+ and successor["initial_delivery_id"] == successor_delivery_id+ and successor_delivery is not None+ and successor_delivery["state"] == "interrupt_waiting"+ and successor_delivery["session_id"] == turn["session_id"]+ and successor_delivery["turn_id"] == successor_turn_id+ and successor_delivery["turn_role"] == "initial"+ ):+ return False, "turn_has_replacement_successor"+ return False, "turn_replacement_unresolved"participant_delivery_ids = [str(value)for value in conn.execute(@@ -1844,7 +1871,7 @@ def agent_run_exclusively_owns_turn(or_(and_(message_deliveries.c.turn_id == normalized_turn_id,- message_deliveries.c.state == "accepted",+ message_deliveries.c.state.in_(("claimed", "accepted")),),and_(message_deliveries.c.current_target_turn_iddiff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 05c25815c..7e1f380ec 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -5045,6 +5045,219 @@ def test_run_cancel_guard_preserves_an_in_flight_replacement(monkeypatch, tmp_paassert replacement is not None and replacement["state"] == "interrupt_waiting"+def test_run_cancel_keeps_a_sole_starting_owner_attached(monkeypatch, tmp_path):+ """A claimed initial Run owns its starting Turn until native start resolves."""++ from core.scheduled_tasks import TaskExecutionStore+ from storage.background import attach_agent_run_delivery_in_connection++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ engine, session = _create_test_session(+ tmp_path,+ native_id="proj_starting_run_cancel",+ )+ session_id = session["id"]+ request_store = TaskExecutionStore()+ owner_run = request_store.enqueue_agent_run(+ session_id=session_id,+ message="starting owner",+ agent_name="worker",+ )+ assert request_store.claim(owner_run.id) is not None++ with engine.begin() as conn:+ delivery = _reserve_submission(+ conn,+ scope_id=session["scope_id"],+ session_id=session_id,+ text="starting owner",+ )+ turn_id = message_deliveries.new_turn_id()+ message_deliveries.insert_turn(+ conn,+ turn_id=turn_id,+ session_id=session_id,+ initial_delivery_id=str(delivery["id"]),+ state="starting",+ backend="claude",+ )+ claimed = message_deliveries.open_start_attempt(+ conn,+ str(delivery["id"]),+ expected_version=int(delivery["version"]),+ turn_id=turn_id,+ attempt_id=message_deliveries.new_attempt_id(),+ )+ assert claimed is not None and claimed["state"] == "claimed"+ assert attach_agent_run_delivery_in_connection(+ conn,+ owner_run.id,+ session_id=session_id,+ delivery_id=str(claimed["id"]),+ )++ controller = _build_controller_double()+ app = internal_server.create_app(controller)+ transport = httpx.ASGITransport(app=app)++ async def _go():+ async with httpx.AsyncClient(+ transport=transport,+ base_url="http://testserver",+ ) as client:+ return await client.post(+ f"/internal/cancel/{session_id}",+ params={"run_id": owner_run.id},+ )++ response = asyncio.run(_go())++ assert response.status_code == 200+ assert response.json() == {+ "ok": True,+ "session_id": session_id,+ "status": "cancel_requested",+ }+ controller.command_handler.handle_stop.assert_not_awaited()+ saved = request_store.get_run(owner_run.id)+ assert saved is not None+ assert saved["status"] == "running"+ assert saved["cancel_requested"] is True+ with engine.connect() as conn:+ turn = message_deliveries.get_turn(conn, turn_id)+ delivery = message_deliveries.get_delivery(conn, str(delivery["id"]))+ assert turn is not None+ assert turn["state"] == "starting"+ assert turn["control_state"] == "pending"+ assert turn["control_mode"] == "stop_only"+ assert delivery is not None and delivery["state"] == "claimed"+++def test_run_cancel_does_not_own_a_shared_starting_batch(monkeypatch, tmp_path):+ """Other claimed inputs keep a starting batch shared."""++ from core.scheduled_tasks import TaskExecutionStore+ from storage.background import attach_agent_run_delivery_in_connection++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ engine, session = _create_test_session(+ tmp_path,+ native_id="proj_shared_starting_run_cancel",+ )+ request_store = TaskExecutionStore()+ owner_run = request_store.enqueue_agent_run(+ session_id=session["id"],+ message="one batch participant",+ agent_name="worker",+ )+ assert request_store.claim(owner_run.id) is not None++ with engine.begin() as conn:+ deliveries = [+ _reserve_submission(+ conn,+ scope_id=session["scope_id"],+ session_id=session["id"],+ text=text,+ )+ for text in ("one batch participant", "another batch participant")+ ]+ turn_id = message_deliveries.new_turn_id()+ claimed = message_deliveries.claim_start_batch(+ conn,+ turn_id=turn_id,+ session_id=session["id"],+ backend="claude",+ deliveries=deliveries,+ dispatch_text="one batch participant\n\nanother batch participant",+ )+ assert attach_agent_run_delivery_in_connection(+ conn,+ owner_run.id,+ session_id=session["id"],+ delivery_id=str(claimed["deliveries"][0]["id"]),+ )+ assert message_deliveries.agent_run_exclusively_owns_turn(+ conn,+ run_id=owner_run.id,+ turn_id=turn_id,+ ) == (False, "turn_has_other_participants")+++def test_run_cancel_rechecks_a_changed_current_turn(monkeypatch, tmp_path):+ """A stale observed Turn cannot detach a Run that owns the current Turn."""++ from core.scheduled_tasks import TaskExecutionStore+ from storage.background import attach_agent_run_delivery_in_connection++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ engine, session, turn_id = _create_active_test_turn(+ tmp_path,+ native_id="proj_changed_turn_run_cancel",+ )+ session_id = session["id"]+ request_store = TaskExecutionStore()+ owner_run = request_store.enqueue_agent_run(+ session_id=session_id,+ message="recovered current owner",+ agent_name="worker",+ )+ assert request_store.claim(owner_run.id) is not None+ with engine.begin() as conn:+ initial = message_deliveries.delivery_for_turn(conn, turn_id)+ assert initial is not None+ assert attach_agent_run_delivery_in_connection(+ conn,+ owner_run.id,+ session_id=session_id,+ delivery_id=str(initial["id"]),+ )++ controller = _build_controller_double()+ internal_server.create_app(controller)+ context = MessageContext(+ user_id="workbench",+ channel_id=session_id,+ platform="avibe",+ platform_specific={"workbench_session_id": session_id},+ )++ async def _go():+ holder = asyncio.create_task(asyncio.Event().wait())+ controller.session_turns.in_flight[session_id] = session_turns.Turn(+ task=holder,+ context=context,+ logical_turn_id=turn_id,+ )+ try:+ return await controller.session_turns.deliver(+ session_turns.DeliveryRequest(+ session_id=session_id,+ priority="p0",+ content=None,+ expected_turn_id="trn_recovered_predecessor",+ expected_exclusive_agent_run_id=owner_run.id,+ ),+ context=context,+ )+ finally:+ holder.cancel()+ await asyncio.gather(holder, return_exceptions=True)++ result = asyncio.run(_go())++ assert result.state == "waiting_terminal"+ controller.command_handler.handle_stop.assert_awaited_once()+ saved = request_store.get_run(owner_run.id)+ assert saved is not None+ assert saved["status"] == "running"+ assert saved["cancel_requested"] is True+ with engine.connect() as conn:+ turn = message_deliveries.get_turn(conn, turn_id)+ assert turn is not None+ assert turn["control_state"] == "waiting_terminal"++def test_run_cancel_without_an_active_turn_settles_atomically(monkeypatch, tmp_path):"""An orphaned live projection is canceled without inventing a Session Stop."""diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.pyindex 28eb12ba2..972093c5d 100644--- a/tests/test_session_delivery_fsm.py+++ b/tests/test_session_delivery_fsm.py@@ -2807,6 +2807,50 @@ def test_definitive_p0_refusal_leaves_backlog_behind_the_active_turn(managers) -assert _row(engine, queued_id)["state"] == "queued"+def test_refused_replacement_releases_its_control_ownership(managers) -> None:+ manager, _other, engine, _engine_b, _starts = managers++ async def run() -> tuple[str, str]:+ turn_id, context = await _activate(manager)+ holder = asyncio.create_task(asyncio.Event().wait())+ manager.in_flight["ses_fsm"] = Turn(+ task=holder,+ context=context,+ logical_turn_id=turn_id,+ )++ async def refused(stop_context):+ stop_context.platform_specific["stop_failure_reason"] = "refused"+ return False++ manager.controller.command_handler.handle_stop = AsyncMock(side_effect=refused)+ try:+ result = await manager.deliver(+ DeliveryRequest(+ session_id="ses_fsm",+ priority="p0",+ content="replacement",+ ),+ context=_context(),+ )+ finally:+ holder.cancel()+ await asyncio.gather(holder, return_exceptions=True)+ assert result.state == "queued"+ return turn_id, str(result.delivery_id)++ turn_id, replacement_delivery_id = asyncio.run(run())+ with engine.connect() as conn:+ active = delivery_store.get_turn(conn, turn_id)+ assert active is not None+ assert active["state"] == "active"+ assert active["control_state"] == "refused"+ assert active["control_mode"] is None+ assert active["control_successor_turn_id"] is None+ assert active["control_successor_delivery_id"] is None+ assert _row(engine, replacement_delivery_id)["state"] == "queued"++def test_empty_p0_uses_the_control_slot_without_creating_a_message_delivery(managers) -> None:manager, _other, engine, _engine_b, _starts = managers