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): isolate shared-turn run cancellation
cyh9c4930f0cf6a
diff --git a/core/internal_server.py b/core/internal_server.pyindex b63befb7b..dc51398e2 100644--- a/core/internal_server.py+++ b/core/internal_server.py@@ -1372,12 +1372,12 @@ def create_app(return {"ok": True, "queued": True}@app.post("/internal/cancel/{session_id}")- async def _cancel(session_id: str) -> Any:+ async def _cancel(session_id: str, run_id: str | None = None) -> Any:"""HTTP adapter: delegate Stop to the turn owner (FSM, Phase 1b) and map itsresult ``code`` to a status — ``not_in_flight`` -> 404, ``stop_failed`` ->409. ``session_id`` is the dispatch key the turn registered under, so the UIStop button works with just the URL it already has."""- result = await manager.cancel(session_id)+ result = await manager.cancel(session_id, agent_run_id=run_id)code = result.get("code")if code == "not_in_flight":return JSONResponse(status_code=404, content=result)diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex ef06e7d0c..621fa0a5f 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -3157,7 +3157,13 @@ class TaskExecutionStore:return Truereturn False- def mark_run_canceled(self, run_id: str, *, completed_at: Optional[str] = None) -> bool:+ def mark_run_canceled(+ self,+ run_id: str,+ *,+ completed_at: Optional[str] = None,+ skip_callback: bool = False,+ ) -> bool:now = completed_at or _utc_now_iso()existing = self.get_run(run_id)if existing is None:@@ -3171,6 +3177,8 @@ class TaskExecutionStore:updated_at=now,cancel_requested=True,cancel_requested_at=cancel_requested_at,+ callback_status="skipped" if skip_callback else None,+ callback_completed_at=now if skip_callback else None,)return True@@ -3194,6 +3202,9 @@ class TaskExecutionStore:"updated_at": now,})+ if skip_callback:+ payload["callback_status"] = "skipped"+ payload["callback_completed_at"] = nowcompleted_path = self._request_path(run_id, state="completed")with tempfile.NamedTemporaryFile(mode="w",diff --git a/core/session_turns.py b/core/session_turns.pyindex b8ace4112..3f1ee64cb 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -474,6 +474,9 @@ class DeliveryRequest:delivery_id: str | None = Noneexpected_delivery_id: str | None = Noneexpected_turn_id: str | None = None+ # Run-level cancellation may interrupt a backend only when this exact Run is+ # still the Turn's sole initial input. Checked under the P0 writer lock.+ expected_exclusive_agent_run_id: str | None = Nonescope_id: str | None = Noneplatform: str = "avibe"source: str = "user"@@ -3047,6 +3050,23 @@ class SessionTurnManager:current_id,"target_turn_changed",)+ expected_exclusive_run_id = str(+ request.expected_exclusive_agent_run_id or ""+ ).strip()+ if request.content is None and expected_exclusive_run_id:+ exclusive, reason = delivery_store.agent_run_exclusively_owns_turn(+ conn,+ run_id=expected_exclusive_run_id,+ turn_id=str(current_id or ""),+ )+ if not exclusive:+ return DeliveryResult(+ None,+ None,+ "run_detached",+ current_id,+ reason,+ )control_in_progress = current.get("control_state") in {"pending","interrupting",@@ -7339,14 +7359,33 @@ class SessionTurnManager:)return bool(terminal.get("changed"))- async def cancel(self, session_id: str) -> dict:- """Persist one empty-P0 control request against the exact active Turn."""+ async def cancel(+ self,+ session_id: str,+ *,+ agent_run_id: str | None = None,+ ) -> dict:+ """Cancel a Session Turn or detach one exact Run from a shared Turn."""turn = self.in_flight.get(session_id)if not self._durable_schema_available():+ if agent_run_id:+ return {+ "ok": True,+ "session_id": session_id,+ "status": "run_detached",+ "reason": "durable_turn_ownership_unavailable",+ }return await self._cancel_legacy_turn(session_id, turn)with self._sqlite_engine().connect() as conn:owner = delivery_store.active_turn(conn, session_id)if owner is None:+ if agent_run_id:+ return {+ "ok": True,+ "session_id": session_id,+ "status": "run_detached",+ "reason": "not_in_flight",+ }return {"ok": False,"code": "not_in_flight",@@ -7361,12 +7400,29 @@ class SessionTurnManager:priority="p0",content=None,expected_turn_id=str(owner["id"]),+ expected_exclusive_agent_run_id=(+ str(agent_run_id).strip() if agent_run_id else None+ ),),context=turn.context if turn is not None else None,)+ if result.state == "run_detached":+ return {+ "ok": True,+ "session_id": session_id,+ "status": "run_detached",+ "reason": result.reason or "shared_turn",+ }if result.state in {"waiting_terminal", "interrupt_waiting"}:return {"ok": True, "session_id": session_id, "status": "cancel_requested"}if result.state == "settled":+ if agent_run_id:+ return {+ "ok": True,+ "session_id": session_id,+ "status": "run_detached",+ "reason": result.reason or "already_terminal",+ }return {"ok": True,"session_id": session_id,diff --git a/storage/message_deliveries.py b/storage/message_deliveries.pyindex 74e29b57c..ebf42a56f 100644--- a/storage/message_deliveries.py+++ b/storage/message_deliveries.py@@ -1768,6 +1768,72 @@ def accepted_agent_run_ids_for_turn(conn: Connection, turn_id: str) -> list[str]return run_ids+def agent_run_exclusively_owns_turn(+ conn: Connection,+ *,+ run_id: str,+ turn_id: str,+) -> 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+ proof and the P0 control-slot write.+ """++ normalized_run_id = str(run_id or "").strip()+ normalized_turn_id = str(turn_id or "").strip()+ if not normalized_run_id or not normalized_turn_id:+ return False, "missing_run_turn_identity"+ turn = get_turn(conn, normalized_turn_id)+ if turn is None or turn.get("state") not in TURN_OWNER_STATES:+ return False, "turn_not_active"+ row = conn.execute(+ select(+ agent_runs.c.status,+ agent_runs.c.delivery_id,+ message_deliveries.c.session_id,+ message_deliveries.c.state,+ message_deliveries.c.turn_id,+ )+ .select_from(+ agent_runs.join(+ message_deliveries,+ message_deliveries.c.id == agent_runs.c.delivery_id,+ )+ )+ .where(agent_runs.c.id == normalized_run_id)+ .limit(1)+ ).mappings().first()+ if row is None:+ 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"+ 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 {+ "running",+ "processing",+ }:+ return False, "run_not_running"+ accepted_delivery_ids = [+ str(value)+ for value in conn.execute(+ select(message_deliveries.c.id)+ .where(message_deliveries.c.turn_id == normalized_turn_id)+ .where(message_deliveries.c.state == "accepted")+ .order_by(message_deliveries.c.turn_position, message_deliveries.c.id)+ ).scalars()+ ]+ if accepted_delivery_ids != [str(row["delivery_id"])]:+ return False, "turn_has_other_accepted_inputs"+ return True, "exclusive_run_owner"++def retire_queued_with_run(conn: Connection,session_id: str,diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yamlindex 2c0763459..00f7ad3a8 100644--- a/tests/scenarios/harness_failure_recovery/catalog.yaml+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml@@ -4275,6 +4275,16 @@ scenarios:# remain visible, while deleted definitions never leak their opaque id or append# internal error, origin, lifecycle, and inspection lines.test: tests/test_harness_failure_visibility.py::test_hfr_475_restart_notice_is_one_calm_action_without_internal_details+ - id: HFR-476+ name: Run cancellation cannot stop a shared Session Turn+ status: covered+ kind: cancellation+ layer: scenario+ backend: shared+ # A Run-level cancel may stop the backend only when its Delivery is the exact+ # Turn's sole initial accepted input. Steered or coalesced participants settle+ # locally, skip their callback, and leave the shared Session Turn untouched.+ test: tests/test_internal_server.py::test_hfr_476_run_cancel_does_not_stop_a_shared_turnmanual_evidence:- local Incus backend process death after prompt acceptance- local Incus controller restart with persisted queued successordiff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.pyindex ab733eb5a..977238347 100644--- a/tests/test_cli_task_command.py+++ b/tests/test_cli_task_command.py@@ -2495,7 +2495,7 @@ def test_runs_cancel_running_agent_run_stops_live_turn_and_marks_canceled(result = cli.cmd_runs_cancel(_parse_runs_cancel([request.id]))assert result == 0- cancel_dispatch.assert_awaited_once_with("ses_live_cancel")+ cancel_dispatch.assert_awaited_once_with("ses_live_cancel", run_id=request.id)saved = request_store.get_run(request.id)assert saved is not Noneassert saved["status"] == "canceled"@@ -2512,6 +2512,52 @@ def test_runs_cancel_running_agent_run_stops_live_turn_and_marks_canceled(assert payload["run"]["status"] == "canceled"+def test_runs_cancel_shared_turn_detaches_only_the_requested_run(+ monkeypatch,+ tmp_path: Path,+ capsys,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ request_store = cli.TaskExecutionStore()+ request = request_store.enqueue_agent_run(+ session_id="ses_shared_turn",+ message="one shared participant",+ agent_name="worker",+ callback_session_id="ses_callback",+ )+ assert request_store.claim(request.id) is not None+ cancel_dispatch = AsyncMock(+ return_value={+ "status_code": 200,+ "body": {+ "ok": True,+ "session_id": "ses_shared_turn",+ "status": "run_detached",+ "reason": "turn_has_other_accepted_inputs",+ },+ }+ )++ with (+ patch("vibe.cli._task_request_store", return_value=request_store),+ patch("vibe.internal_client.cancel_dispatch", cancel_dispatch),+ ):+ result = cli.cmd_runs_cancel(_parse_runs_cancel([request.id]))++ assert result == 0+ cancel_dispatch.assert_awaited_once_with("ses_shared_turn", run_id=request.id)+ saved = request_store.get_run(request.id)+ assert saved is not None+ assert saved["status"] == "canceled"+ assert saved["callback_status"] == "skipped"+ assert saved["callback_completed_at"] is not None+ assert request_store.list_pending_callbacks() == []+ payload = json.loads(capsys.readouterr().out)+ assert payload["cancel_code"] == "run_canceled_without_live_stop"+ assert payload["cancel_result"]["live_cancel_confirmed"] is False+ assert payload["cancel_result"]["run_terminalized"] is True++def test_runs_cancel_running_agent_run_reports_recorded_only_when_controller_unavailable(monkeypatch,tmp_path: Path,@@ -2536,7 +2582,7 @@ def test_runs_cancel_running_agent_run_reports_recorded_only_when_controller_unaresult = cli.cmd_runs_cancel(_parse_runs_cancel([request.id]))assert result == 0- cancel_dispatch.assert_awaited_once_with("ses_controller_down")+ cancel_dispatch.assert_awaited_once_with("ses_controller_down", run_id=request.id)saved = request_store.get_run(request.id)assert saved is not Noneassert saved["status"] == "running"@@ -2576,7 +2622,7 @@ def test_runs_cancel_running_agent_run_reports_recorded_only_when_backend_refuseresult = cli.cmd_runs_cancel(_parse_runs_cancel([request.id]))assert result == 0- cancel_dispatch.assert_awaited_once_with("ses_stop_failed")+ cancel_dispatch.assert_awaited_once_with("ses_stop_failed", run_id=request.id)saved = request_store.get_run(request.id)assert saved is not Noneassert saved["status"] == "running"@@ -2614,7 +2660,7 @@ def test_runs_cancel_running_agent_run_reports_recorded_only_when_no_live_turn(result = cli.cmd_runs_cancel(_parse_runs_cancel([request.id]))assert result == 0- cancel_dispatch.assert_awaited_once_with("ses_no_live_turn")+ cancel_dispatch.assert_awaited_once_with("ses_no_live_turn", run_id=request.id)saved = request_store.get_run(request.id)assert saved is not Noneassert saved["status"] == "running"@@ -2652,7 +2698,7 @@ def test_runs_cancel_running_agent_run_does_not_overwrite_already_finished_turn(result = cli.cmd_runs_cancel(_parse_runs_cancel([request.id]))assert result == 0- cancel_dispatch.assert_awaited_once_with("ses_already_finished")+ cancel_dispatch.assert_awaited_once_with("ses_already_finished", run_id=request.id)saved = request_store.get_run(request.id)assert saved is not Noneassert saved["status"] == "running"diff --git a/tests/test_internal_client.py b/tests/test_internal_client.pyindex 06e467258..dfa7e2e7a 100644--- a/tests/test_internal_client.py+++ b/tests/test_internal_client.py@@ -81,6 +81,34 @@ def test_cancel_dispatch_round_trip(tmp_path, socket_path):assert result["body"] == {"ok": True, "session_id": "ses_abc", "status": "cancel_requested"}+def test_cancel_dispatch_forwards_exact_run_guard(socket_path):+ app = FastAPI()+ captured: dict = {}++ @app.post("/internal/cancel/{session_id}")+ async def _cancel(session_id: str, run_id: str | None = None):+ captured.update(session_id=session_id, run_id=run_id)+ return {"ok": True, "session_id": session_id, "status": "run_detached"}++ async def _go():+ fake_transport = httpx.ASGITransport(app=app)+ with patch(+ "vibe.internal_client.httpx.AsyncHTTPTransport",+ return_value=fake_transport,+ ):+ return await internal_client.cancel_dispatch(+ "ses_shared",+ run_id="run_exact",+ socket_path=socket_path,+ )++ result = asyncio.run(_go())++ assert captured == {"session_id": "ses_shared", "run_id": "run_exact"}+ assert result["status_code"] == 200+ assert result["body"]["status"] == "run_detached"++def test_cancel_dispatch_missing_socket_raises_unavailable(tmp_path):sock = tmp_path / "missing.sock"with pytest.raises(internal_client.InternalServerUnavailable):diff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex 1a3352771..38909a750 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -4662,6 +4662,117 @@ def test_scheduled_gate_cancel_stops_scheduled_run(monkeypatch, tmp_path):assert session_id not in app.state.in_flight_dispatches, "slot released after the scheduled run was stopped"+def test_hfr_476_run_cancel_does_not_stop_a_shared_turn(monkeypatch, tmp_path):+ """A Run accepted as one Turn participant cannot issue Session-wide Stop."""++ from core.scheduled_tasks import TaskExecutionStore+ from storage.background import attach_agent_run_delivery_in_connection+ from storage.models import message_deliveries as delivery_rows++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ engine, session, turn_id = _create_active_test_turn(+ tmp_path,+ native_id="proj_shared_run_cancel",+ )+ session_id = session["id"]+ request_store = TaskExecutionStore()+ run = request_store.enqueue_agent_run(+ session_id=session_id,+ message="steered participant",+ agent_name="worker",+ callback_session_id="ses_callback",+ )+ assert request_store.claim(run.id) is not None++ with engine.begin() as conn:+ initial = message_deliveries.delivery_for_turn(conn, turn_id)+ assert initial is not None+ steer_id = message_deliveries.new_delivery_id()+ values = dict(initial)+ values.update(+ id=steer_id,+ priority="p1",+ dedupe_key=None,+ turn_role="steer",+ turn_position=1,+ submitted_at="2026-08-11T11:00:00Z",+ updated_at="2026-08-11T11:00:00Z",+ version=1,+ )+ conn.execute(delivery_rows.insert().values(**values))+ assert attach_agent_run_delivery_in_connection(+ conn,+ run.id,+ session_id=session_id,+ delivery_id=steer_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": run.id},+ )++ response = asyncio.run(_go())++ assert response.status_code == 200+ assert response.json() == {+ "ok": True,+ "session_id": session_id,+ "status": "run_detached",+ "reason": "run_is_steered_participant",+ }+ controller.command_handler.handle_stop.assert_not_awaited()+ with engine.connect() as conn:+ turn = message_deliveries.get_turn(conn, turn_id)+ assert turn is not None+ assert turn["state"] == "active"+ assert turn["control_state"] is None+++def test_run_cancel_guard_allows_the_sole_initial_run_owner(monkeypatch, tmp_path):+ """A Run remains allowed to stop the backend when it owns the whole 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_exclusive_run_cancel",+ )+ request_store = TaskExecutionStore()+ run = request_store.enqueue_agent_run(+ session_id=session["id"],+ message="sole initial participant",+ agent_name="worker",+ )+ assert request_store.claim(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,+ run.id,+ session_id=session["id"],+ delivery_id=initial["id"],+ )+ assert message_deliveries.agent_run_exclusively_owns_turn(+ conn,+ run_id=run.id,+ turn_id=turn_id,+ ) == (True, "exclusive_run_owner")++# --- #84: scheduled provenance survives the merge-queue --------------------------diff --git a/vibe/cli.py b/vibe/cli.pyindex d46fa6583..39dc590ec 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -6235,18 +6235,19 @@ def _live_cancel_was_confirmed(status_code: int | None, body: object) -> bool:return str(body.get("status") or "").strip() in {"cancel_requested", "stale_released"}-async def _request_live_run_cancel(session_id: str) -> dict:+async def _request_live_run_cancel(session_id: str, run_id: str) -> dict:from vibe import internal_client- return await internal_client.cancel_dispatch(session_id)+ return await internal_client.cancel_dispatch(session_id, run_id=run_id)def _cancel_live_agent_run(store: TaskExecutionStore, run: dict) -> dict:session_id = _run_session_id(run)+ run_id = str(run.get("id") or "").strip()from vibe import internal_clienttry:- controller_result = asyncio.run(_request_live_run_cancel(session_id))+ controller_result = asyncio.run(_request_live_run_cancel(session_id, run_id))except internal_client.InternalServerUnavailable as exc:return _recorded_only_cancel_result(reason_code="internal_unavailable", detail=str(exc))except Exception as exc: # noqa: BLE001@@ -6258,6 +6259,22 @@ def _cancel_live_agent_run(store: TaskExecutionStore, run: dict) -> dict:except (TypeError, ValueError):normalized_status_code = Nonebody = controller_result.get("body") or {}+ if (+ normalized_status_code is not None+ and 200 <= normalized_status_code < 300+ and isinstance(body, dict)+ and str(body.get("status") or "").strip() == "run_detached"+ ):+ run_terminalized = store.mark_run_canceled(run_id, skip_callback=True)+ return {+ "code": "run_canceled_without_live_stop",+ "live_cancel_attempted": False,+ "live_cancel_confirmed": False,+ "run_terminalized": run_terminalized,+ "controller_status_code": normalized_status_code,+ "controller_response": body,+ "message": "Run was canceled without stopping the shared Session turn.",+ }if not _live_cancel_was_confirmed(normalized_status_code, body):return _recorded_only_cancel_result(reason_code=_live_cancel_failure_code(normalized_status_code, body),@@ -6267,7 +6284,7 @@ def _cancel_live_agent_run(store: TaskExecutionStore, run: dict) -> dict:},)- run_terminalized = store.mark_run_canceled(str(run.get("id") or ""))+ run_terminalized = store.mark_run_canceled(run_id)return {"code": "live_cancel_confirmed","live_cancel_attempted": True,diff --git a/vibe/internal_client.py b/vibe/internal_client.pyindex 3695a7a44..ffe0e1d7b 100644--- a/vibe/internal_client.py+++ b/vibe/internal_client.py@@ -705,7 +705,12 @@ def notify_vault_request_created_sync(return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}-async def cancel_dispatch(session_id: str, *, socket_path: Optional[Path] = None) -> dict[str, Any]:+async def cancel_dispatch(+ session_id: str,+ *,+ run_id: str | None = None,+ socket_path: Optional[Path] = None,+) -> dict[str, Any]:"""Ask the controller to cancel a running ``dispatch_turn`` for``session_id``.@@ -726,7 +731,10 @@ async def cancel_dispatch(session_id: str, *, socket_path: Optional[Path] = None# room so a slow-but-successful stop isn't read-timed-out into a 500.timeout=httpx.Timeout(30.0, connect=1.0),) as client:- resp = await client.post(f"/internal/cancel/{session_id}")+ resp = await client.post(+ f"/internal/cancel/{session_id}",+ params={"run_id": run_id} if run_id else None,+ )except _SOCKET_ERRORS as exc:raise InternalServerUnavailable(str(exc)) from excreturn {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}