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): make run cancel stop the shared live turn (#2149)
Call Whited75388333ed9
diff --git a/core/session_turns.py b/core/session_turns.pyindex 4a9bb1024..8ef3be8ff 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -487,6 +487,11 @@ def emit_matches_active_turn(sink: dict, context: "MessageContext") -> bool:return not (sink_token is not None and ctx_token != sink_token)+# A Run cancel joining another Stop waits this long for that Stop's receipt.+# Together with one retried Stop it must fit the CLI's 30s cancel timeout.+_RUN_CANCEL_JOIN_WAIT_SECONDS = 10.0+_RUN_CANCEL_JOIN_POLL_SECONDS = 0.05+@dataclassclass Turn:"""The one active turn for an avibe session — the EXECUTION half of the FSM@@ -541,9 +546,10 @@ 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 = None+ # Run-level cancellation stops the live Turn whenever this Run's input may+ # have reached it; an input still outside the Turn is canceled alone.+ # Checked under the P0 writer lock.+ cancel_agent_run_id: str | None = Nonescope_id: str | None = Noneplatform: str = "avibe"source: str = "user"@@ -3489,8 +3495,8 @@ class SessionTurnManager:)).scalar_one_or_none()current = delivery_store.active_turn(conn, request.session_id)- expected_exclusive_run_id = str(- request.expected_exclusive_agent_run_id or ""+ cancel_run_id = str(+ request.cancel_agent_run_id or "").strip()if request.content is not None and session_status != "active":existing = (@@ -3510,10 +3516,10 @@ class SessionTurnManager:current_id = str((current or {}).get("id") or "") or Noneif current is None:if request.content is None:- if expected_exclusive_run_id:+ if cancel_run_id:cancellation = apply_live_agent_run_cancellation_in_connection(conn,- expected_exclusive_run_id,+ cancel_run_id,session_id=request.session_id,detach=True,)@@ -3555,7 +3561,7 @@ class SessionTurnManager:request.content is Noneand expected_turn_idand current_id != expected_turn_id- and not expected_exclusive_run_id+ and not cancel_run_id):return DeliveryResult(None,@@ -3564,33 +3570,48 @@ class SessionTurnManager:current_id,"target_turn_changed",)- if request.content is None and expected_exclusive_run_id:- exclusive, reason = delivery_store.agent_run_exclusively_owns_turn(+ if request.content is None and cancel_run_id:+ stops_turn, reason = delivery_store.agent_run_input_reached_turn(conn,- run_id=expected_exclusive_run_id,+ run_id=cancel_run_id,turn_id=str(current_id or ""),)replacement_terminalized = False- if not exclusive:+ if stops_turn and current.get("control_state") in {+ "pending",+ "interrupting",+ "reconciling",+ }:+ # A Stop without a receipt may still be refused. Record+ # nothing so a refused Stop cannot leave this Run+ # marked canceled while its backend keeps running.+ return DeliveryResult(+ None,+ None,+ "reconciling",+ current_id,+ "joined_unconfirmed_interrupt",+ )+ if not stops_turn:replacement_terminalized = (self._terminalize_detached_run_replacement(conn,- run_id=expected_exclusive_run_id,+ run_id=cancel_run_id,session_id=request.session_id,current=current,))cancellation = apply_live_agent_run_cancellation_in_connection(conn,- expected_exclusive_run_id,+ cancel_run_id,session_id=request.session_id,- detach=not exclusive,+ detach=not stops_turn,)if replacement_terminalized and cancellation != "run_detached":raise RuntimeError("replacement Run terminalized without cancellation ownership")- if not exclusive:+ if not stops_turn:return DeliveryResult(None,None,@@ -8146,7 +8167,11 @@ class SessionTurnManager:*,agent_run_id: str | None = None,) -> dict:- """Cancel a Session Turn or detach one exact Run from a shared Turn."""+ """Cancel a Session Turn, or one exact Run.++ A Run whose input may have reached the live Turn stops that whole Turn,+ exactly like Session Stop; a Run still outside it is canceled alone.+ """normalized_agent_run_id = (str(agent_run_id).strip() if agent_run_id is not None else None)@@ -8250,18 +8275,25 @@ class SessionTurnManager:"status": "stale_released","reason": "runtime_gone",}- result = await self.deliver(- DeliveryRequest(- session_id=session_id,- priority="p0",- content=None,- expected_turn_id=(str(owner["id"]) if owner is not None else None),- expected_exclusive_agent_run_id=(- normalized_agent_run_id- ),- ),- context=turn.context if turn is not None else None,+ request = DeliveryRequest(+ session_id=session_id,+ priority="p0",+ content=None,+ expected_turn_id=(str(owner["id"]) if owner is not None else None),+ cancel_agent_run_id=normalized_agent_run_id,)+ context = turn.context if turn is not None else None+ result = await self.deliver(request, context=context)+ # A Run cancel that meets another Stop awaiting its receipt waits for+ # that receipt: accepted confirms this cancel, refused lets it retry.+ deadline = asyncio.get_running_loop().time() + _RUN_CANCEL_JOIN_WAIT_SECONDS+ while (+ normalized_agent_run_id+ and result.reason == "joined_unconfirmed_interrupt"+ and asyncio.get_running_loop().time() < deadline+ ):+ await asyncio.sleep(_RUN_CANCEL_JOIN_POLL_SECONDS)+ result = await self.deliver(request, context=context)if result.state == "run_detached":return {"ok": True,@@ -8271,7 +8303,15 @@ class SessionTurnManager:}if result.state in {"waiting_terminal", "interrupt_waiting"}:return {"ok": True, "session_id": session_id, "status": "cancel_requested"}- if result.state == "settled":+ # ``claimed``: a pre-write stop settled the Turn and started its successor.+ if result.state in {"settled", "claimed"}:+ if normalized_agent_run_id and result.reason == "prewrite_canceled":+ return {+ "ok": True,+ "session_id": session_id,+ "status": "cancel_requested",+ "reason": result.reason,+ }if normalized_agent_run_id:return {"ok": True,diff --git a/docs/COMMANDS.md b/docs/COMMANDS.mdindex 1bcaff62c..e4eda8b79 100644--- a/docs/COMMANDS.md+++ b/docs/COMMANDS.md@@ -929,7 +929,7 @@ direct Agent Run calls.| --- | --- || `vibe runs list` | List recent runs || `vibe runs show <run_id>` | Show one run |-| `vibe runs cancel <run_id>` | Request cancellation |+| `vibe runs cancel <run_id>` | Request cancellation; once the run's input reached the live Session turn, this stops that turn like Session Stop, including other runs sharing it |## 6. Recommended Mental Modeldiff --git a/docs/COMMANDS_ZH.md b/docs/COMMANDS_ZH.mdindex 83332a000..f8c292bdf 100644--- a/docs/COMMANDS_ZH.md+++ b/docs/COMMANDS_ZH.md@@ -897,7 +897,7 @@ fork 会保持源 Session 的 backend;只有 backend 不变时,`--agent`、`| --- | --- || `vibe runs list` | 列出最近 run || `vibe runs show <run_id>` | 查看单个 run |-| `vibe runs cancel <run_id>` | 请求取消 run |+| `vibe runs cancel <run_id>` | 请求取消 run;若该 run 的输入已进入正在运行的 Session turn,会像 Session Stop 一样停止整个 turn,同一 turn 中的其他 run 也会一起停止 |## 6. 推荐心智模型diff --git a/skills/use-avibe-harness/SKILL.md b/skills/use-avibe-harness/SKILL.mdindex 651281c33..5fc9ae7d2 100644--- a/skills/use-avibe-harness/SKILL.md+++ b/skills/use-avibe-harness/SKILL.md@@ -73,7 +73,7 @@ Use `vibe session update --visible|--hidden` (`--visibility foreground|backgrounFor tasks, use `--message "..."` or `--message-file <path>` as the stored message. For watches, use `--message "..."` or `--message-file <path>` as the follow-up instruction template sent with waiter output. Prefer `--same-scope` or `--scope-id <scopes.id>` for new Session placement.-Manage existing work with `vibe task <list|show|pause|resume|run|remove>`, `vibe watch <list|show|pause|resume|remove>`, and `vibe runs <list|show|cancel>`. Use `vibe harness status` for one unified live/anomaly snapshot. For current-session run history, use `vibe runs list --current-session`. `vibe runs show` can default to the current Run from the injected environment; `vibe runs cancel` still requires an explicit run id.+Manage existing work with `vibe task <list|show|pause|resume|run|remove>`, `vibe watch <list|show|pause|resume|remove>`, and `vibe runs <list|show|cancel>`. Use `vibe harness status` for one unified live/anomaly snapshot. For current-session run history, use `vibe runs list --current-session`. `vibe runs show` can default to the current Run from the injected environment; `vibe runs cancel` still requires an explicit run id; once that run's input reached the live Session turn, it stops the whole turn like Session Stop, including other runs sharing it.The CLI exposes more options than this prompt lists. Before creating or changing Harness state, or whenever syntax/runtime effects are uncertain, read the relevant help: `vibe <command> --help` or `vibe <command> <subcommand> --help`.diff --git a/storage/background.py b/storage/background.pyindex 7555f1f11..9444b3c45 100644--- a/storage/background.py+++ b/storage/background.py@@ -2878,11 +2878,12 @@ def apply_live_agent_run_cancellation_in_connection() -> str:"""Record one live Run cancellation inside the Turn owner's transaction.- ``detach`` is the outcome of the shared-Turn ownership check made under the- same SQLite writer reservation. A detached participant becomes terminal,- retires its exact input when the Delivery state proves no native side effect,- and suppresses its callback before any terminal writer or callback drain can- run; an exclusive owner only records the cancellation request before P0 Stop.+ ``detach`` is true when the check made under the same SQLite writer+ reservation proves the Run's input never reached the live Turn. A detached+ Run becomes terminal, retires its exact input when the Delivery state proves+ no native side effect, and suppresses its callback before any terminal+ writer or callback drain can run; a Run inside the Turn only records the+ cancellation request before P0 Stop."""normalized_run_id = str(run_id or "").strip()diff --git a/storage/message_deliveries.py b/storage/message_deliveries.pyindex f4e431e98..992c5167c 100644--- a/storage/message_deliveries.py+++ b/storage/message_deliveries.py@@ -2261,19 +2261,22 @@ def accepted_agent_run_ids_for_turn(conn: Connection, turn_id: str) -> list[str]return run_ids-def agent_run_exclusively_owns_turn(+def agent_run_input_reached_turn(conn: Connection,*,run_id: str,turn_id: str,) -> tuple[bool, str]:- """Whether stopping ``run_id`` may safely interrupt the exact Turn.-- 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 this- proof and the P0 control-slot write.+ """Whether canceling ``run_id`` must stop the exact live Turn.++ One live Turn is one backend process turn: every initial, batched, or+ steered input written into it shares that process, so no single Run can be+ withdrawn from it. Canceling any Run whose input may have reached the Turn+ therefore stops the whole Turn, exactly like Session Stop. Only inputs+ proven outside the Turn (queued, pending steer, a waiting replacement) are+ canceled alone. A replacement already interrupting the Turn keeps its own+ authority. The caller holds SQLite's writer reservation while asking, so no+ participant can change between this proof and the P0 control-slot write."""normalized_run_id = str(run_id or "").strip()@@ -2285,11 +2288,10 @@ def agent_run_exclusively_owns_turn(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,+ message_deliveries.c.current_target_turn_id,).select_from(agent_runs.join(@@ -2304,29 +2306,21 @@ 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"- expected_delivery_state = "claimed" if turn["state"] == "starting" else "accepted"+ in_turn = (+ str(row["turn_id"] or "") == normalized_turn_id+ and row["state"] in {"claimed", "accepted"}+ ) or (+ str(row["current_target_turn_id"] or "") == normalized_turn_id+ and row["state"] in {"steering", "reconciling_steer"}+ )+ if not in_turn:+ return False, "run_not_owned_by_turn"+ # Only an accepted replacement owns the Turn's end; before its receipt the+ # caller waits for it, and a refusal leaves this Run to stop the Turn.if (- str(row["turn_id"] or "") != normalized_turn_id- or row["state"] != expected_delivery_state+ turn.get("control_mode") == "replace"+ and turn.get("control_state") == "waiting_terminal"):- 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 {- "running",- "processing",- }:- return False, "run_not_running"- 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 ""@@ -2346,31 +2340,7 @@ def agent_run_exclusively_owns_turn():return False, "turn_has_replacement_successor"return False, "turn_replacement_unresolved"- participant_delivery_ids = [- str(value)- for value in conn.execute(- select(message_deliveries.c.id)- .where(- or_(- and_(- message_deliveries.c.turn_id == normalized_turn_id,- message_deliveries.c.state.in_(("claimed", "accepted")),- ),- and_(- message_deliveries.c.current_target_turn_id- == normalized_turn_id,- message_deliveries.c.state.in_(- ("pending_steer", "steering", "reconciling_steer")- ),- ),- )- )- .order_by(message_deliveries.c.turn_position, message_deliveries.c.id)- ).scalars()- ]- if participant_delivery_ids != [str(row["delivery_id"])]:- return False, "turn_has_other_participants"- return True, "exclusive_run_owner"+ return True, "run_input_in_turn"def retire_queued_with_run(diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yamlindex 1589eb1b2..41052f4ae 100644--- a/tests/scenarios/harness_failure_recovery/catalog.yaml+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml@@ -4280,15 +4280,16 @@ scenarios:# 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+ name: Run cancellation stops a shared Session Turnstatus: coveredkind: cancellationlayer: scenariobackend: 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_turn+ # One live Turn is one backend process turn, so no Run can be withdrawn from+ # it. Canceling any Run whose input may have reached the Turn (initial,+ # batched, or steered) stops the whole Turn exactly like Session Stop. Only a+ # Run still outside the Turn (queued or unwritten steer) settles alone.+ test: tests/test_internal_server.py::test_hfr_476_run_cancel_stops_a_shared_turn- id: HFR-477name: one-shot Task schedule consumption is explicit and atomicstatus: covereddiff --git a/tests/test_internal_server.py b/tests/test_internal_server.pyindex e26e64063..f5376c151 100644--- a/tests/test_internal_server.py+++ b/tests/test_internal_server.py@@ -7263,8 +7263,37 @@ 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."""+def _cancel_run_through_live_turn(controller, session_id, turn_id, run_id):+ """Cancel one Run while a live runtime owns the exact durable Turn."""++ 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.cancel(+ session_id,+ agent_run_id=run_id,+ )+ finally:+ holder.cancel()+ await asyncio.gather(holder, return_exceptions=True)++ return asyncio.run(_go()), context+++def test_hfr_476_run_cancel_stops_a_shared_turn(monkeypatch, tmp_path):+ """Canceling a Run steered into a live Turn stops that Turn like Session Stop."""from core.scheduled_tasks import TaskExecutionStorefrom storage.background import attach_agent_run_delivery_in_connection@@ -7277,17 +7306,27 @@ def test_hfr_476_run_cancel_does_not_stop_a_shared_turn(monkeypatch, tmp_path):)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",+ owner_run, steer_run = (+ request_store.enqueue_agent_run(+ session_id=session_id,+ message=message,+ agent_name="worker",+ callback_session_id="ses_callback",+ )+ for message in ("initial owner", "steered participant"))- assert request_store.claim(run.id) is not None+ assert request_store.claim(owner_run.id) is not None+ assert request_store.claim(steer_run.id) is not Nonewith 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=initial["id"],+ )steer_id = message_deliveries.new_delivery_id()values = dict(initial)values.update(@@ -7303,53 +7342,48 @@ def test_hfr_476_run_cancel_does_not_stop_a_shared_turn(monkeypatch, tmp_path):conn.execute(delivery_rows.insert().values(**values))assert attach_agent_run_delivery_in_connection(conn,- run.id,+ steer_run.id,session_id=session_id,delivery_id=steer_id,)+ for run in (owner_run, steer_run):+ assert message_deliveries.agent_run_input_reached_turn(+ conn,+ run_id=run.id,+ turn_id=turn_id,+ ) == (True, "run_input_in_turn")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},- )+ internal_server.create_app(controller)- response = asyncio.run(_go())+ result, context = _cancel_run_through_live_turn(+ controller,+ session_id,+ turn_id,+ steer_run.id,+ )- assert response.status_code == 200- assert response.json() == {+ assert result == {"ok": True,"session_id": session_id,- "status": "run_detached",- "reason": "run_is_steered_participant",+ "status": "cancel_requested",}- controller.command_handler.handle_stop.assert_not_awaited()+ controller.command_handler.handle_stop.assert_awaited_once_with(context)+ saved = request_store.get_run(steer_run.id)+ assert saved is not None+ assert saved["cancel_requested"] is Truewith 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- saved = request_store.get_run(run.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() == []+ assert turn["control_mode"] == "stop_only"+ assert turn["control_state"] == "waiting_terminal"-def test_run_cancel_guard_counts_an_unresolved_steer_as_a_participant(+def test_run_cancel_stops_a_turn_with_an_unresolved_steer(monkeypatch,tmp_path,):- """A native steer in flight prevents the initial Run from stopping the Turn."""+ """A native steer in flight cannot keep the initial Run's cancel from stopping."""from core.scheduled_tasks import TaskExecutionStorefrom storage.background import attach_agent_run_delivery_in_connection@@ -7361,13 +7395,17 @@ def test_run_cancel_guard_counts_an_unresolved_steer_as_a_participant()session_id = session["id"]request_store = TaskExecutionStore()- owner_run = request_store.enqueue_agent_run(- session_id=session_id,- message="initial owner",- agent_name="worker",- callback_session_id="ses_callback",+ owner_run, steer_run = (+ request_store.enqueue_agent_run(+ session_id=session_id,+ message=message,+ agent_name="worker",+ callback_session_id="ses_callback",+ )+ for message in ("initial owner", "second input already steering"))assert request_store.claim(owner_run.id) is not None+ assert request_store.claim(steer_run.id) is not Nonewith engine.begin() as conn:turn = message_deliveries.get_turn(conn, turn_id)@@ -7386,7 +7424,6 @@ def test_run_cancel_guard_counts_an_unresolved_steer_as_a_participant(session_id=session_id,text="second input already steering",)- steer_id = str(steer["id"])claimed = message_deliveries.open_steer_attempt(conn,steer["id"],@@ -7397,48 +7434,141 @@ def test_run_cancel_guard_counts_an_unresolved_steer_as_a_participant()assert claimed is not Noneassert claimed["state"] == "steering"+ assert attach_agent_run_delivery_in_connection(+ conn,+ steer_run.id,+ session_id=session_id,+ delivery_id=str(claimed["id"]),+ )+ # A possibly-written steer is inside the Turn, so its own cancel stops too.+ assert message_deliveries.agent_run_input_reached_turn(+ conn,+ run_id=steer_run.id,+ turn_id=turn_id,+ ) == (True, "run_input_in_turn")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},- )+ internal_server.create_app(controller)- response = asyncio.run(_go())+ result, context = _cancel_run_through_live_turn(+ controller,+ session_id,+ turn_id,+ owner_run.id,+ )- assert response.status_code == 200- assert response.json() == {+ assert result == {"ok": True,"session_id": session_id,- "status": "run_detached",- "reason": "turn_has_other_participants",+ "status": "cancel_requested",}- controller.command_handler.handle_stop.assert_not_awaited()+ controller.command_handler.handle_stop.assert_awaited_once_with(context)saved = request_store.get_run(owner_run.id)assert saved is not None- assert saved["status"] == "canceled"- assert saved["callback_status"] == "skipped"- assert request_store.list_pending_callbacks() == []+ assert saved["cancel_requested"] is Truewith engine.connect() as conn:turn = message_deliveries.get_turn(conn, turn_id)- steer = message_deliveries.get_delivery(conn, steer_id)assert turn is not None- assert turn["state"] == "active"- assert turn["control_state"] is None- assert steer is not None- assert steer["state"] == "steering"+ assert turn["control_mode"] == "stop_only"+ assert turn["control_state"] == "waiting_terminal"+++def test_run_cancel_joining_a_refused_stop_retries_its_own_stop(+ monkeypatch,+ tmp_path,+):+ """A Run cancel waits for a joined Stop's receipt and retries when refused."""++ 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_run_cancel_joins_refused_stop",+ )+ session_id = session["id"]+ request_store = TaskExecutionStore()+ run = request_store.enqueue_agent_run(+ session_id=session_id,+ message="initial owner",+ 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"],+ )++ controller = _build_controller_double()+ internal_server.create_app(controller)+ stop_entered = asyncio.Event()+ release_stop = asyncio.Event()+ stop_calls = 0++ async def _refuse_first_stop(stop_context):+ nonlocal stop_calls+ stop_calls += 1+ if stop_calls > 1:+ return True+ stop_entered.set()+ await release_stop.wait()+ stop_context.platform_specific["stop_failure_reason"] = "refused"+ return False++ controller.command_handler.handle_stop = AsyncMock(side_effect=_refuse_first_stop)+ 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:+ session_stop = asyncio.create_task(controller.session_turns.cancel(session_id))+ await asyncio.wait_for(stop_entered.wait(), timeout=1.0)+ run_cancel = asyncio.create_task(+ controller.session_turns.cancel(session_id, agent_run_id=run.id)+ )+ await asyncio.sleep(0.1)+ assert not run_cancel.done()+ # Nothing is recorded while the joined Stop has no receipt.+ assert request_store.get_run(run.id)["cancel_requested"] is False+ release_stop.set()+ return await run_cancel, await session_stop+ finally:+ holder.cancel()+ await asyncio.gather(holder, return_exceptions=True)++ run_cancel, session_stop = asyncio.run(_go())++ assert session_stop["ok"] is False, session_stop+ assert run_cancel == {+ "ok": True,+ "session_id": session_id,+ "status": "cancel_requested",+ }+ assert controller.command_handler.handle_stop.await_count == 2+ assert request_store.get_run(run.id)["cancel_requested"] is True+ with engine.connect() as conn:+ turn = message_deliveries.get_turn(conn, turn_id)+ assert turn is not None and turn["control_state"] == "waiting_terminal"def test_run_cancel_guard_preserves_an_in_flight_replacement(monkeypatch, tmp_path):- """Canceling the owner Run cannot supersede another input's P0 replacement."""+ """Canceling the owner Run cannot supersede an accepted P0 replacement."""from core.scheduled_tasks import TaskExecutionStorefrom storage.background import attach_agent_run_delivery_in_connection@@ -7504,7 +7634,7 @@ def test_run_cancel_guard_preserves_an_in_flight_replacement(monkeypatch, tmp_paexpected_version=int(turn["version"]),expected_states=("active",),values={- "control_state": "interrupting",+ "control_state": "waiting_terminal","control_mode": "replace","control_attempt_id": message_deliveries.new_attempt_id(),"control_expected_native_turn_id": turn["native_turn_id"],@@ -7553,6 +7683,111 @@ 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_waits_for_an_unconfirmed_replacement(monkeypatch, tmp_path):+ """An owner Run cancel records nothing while a replacement has no receipt."""++ 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_unconfirmed_replacement_run_cancel",+ )+ session_id = session["id"]+ request_store = TaskExecutionStore()+ owner_run = request_store.enqueue_agent_run(+ session_id=session_id,+ message="initial owner",+ agent_name="worker",+ callback_session_id="ses_callback",+ )+ assert request_store.claim(owner_run.id) is not None++ with engine.begin() as conn:+ turn = message_deliveries.get_turn(conn, turn_id)+ initial = message_deliveries.delivery_for_turn(conn, turn_id)+ assert turn is not None+ assert initial is not None+ assert attach_agent_run_delivery_in_connection(+ conn,+ owner_run.id,+ session_id=session_id,+ delivery_id=initial["id"],+ )+ replacement = _reserve_submission(+ conn,+ scope_id=session["scope_id"],+ session_id=session_id,+ text="replacement from another user",+ )+ successor_turn_id = message_deliveries.new_turn_id()+ message_deliveries.insert_turn(+ conn,+ turn_id=successor_turn_id,+ session_id=session_id,+ initial_delivery_id=str(replacement["id"]),+ state="waiting",+ backend="claude",+ )+ replacement = message_deliveries.cas_delivery(+ conn,+ str(replacement["id"]),+ expected_version=int(replacement["version"]),+ expected_states=("reserved",),+ values={+ "priority": "p0",+ "state": "interrupt_waiting",+ "turn_id": successor_turn_id,+ "turn_role": "initial",+ "turn_position": 0,+ },+ )+ assert replacement is not None+ controlled = message_deliveries.cas_turn(+ conn,+ turn_id,+ expected_version=int(turn["version"]),+ expected_states=("active",),+ values={+ "control_state": "interrupting",+ "control_mode": "replace",+ "control_attempt_id": message_deliveries.new_attempt_id(),+ "control_expected_native_turn_id": turn["native_turn_id"],+ "control_successor_delivery_id": replacement["id"],+ "control_successor_turn_id": successor_turn_id,+ },+ )+ assert controlled is not None++ monkeypatch.setattr(session_turns, "_RUN_CANCEL_JOIN_WAIT_SECONDS", 0.2)+ 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 == 409+ assert response.json()["ok"] is False+ assert response.json()["code"] == "stop_unknown"+ assert response.json()["reason"] == "joined_unconfirmed_interrupt"+ 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 False++def test_run_cancel_retires_its_own_in_flight_replacement(monkeypatch, tmp_path):"""Canceling a replacement Run cannot leave its waiting prompt activatable."""@@ -7764,7 +7999,7 @@ def test_run_cancel_keeps_a_sole_starting_owner_attached(monkeypatch, tmp_path):def test_run_cancel_preserves_shared_starting_batch_siblings(monkeypatch, tmp_path):- """Detaching one claimed Run replays every surviving batch participant."""+ """Stopping an unwritten starting batch replays every surviving participant."""from core.scheduled_tasks import TaskExecutionStorefrom storage.background import attach_agent_run_delivery_in_connection@@ -7811,11 +8046,11 @@ def test_run_cancel_preserves_shared_starting_batch_siblings(monkeypatch, tmp_pasession_id=session["id"],delivery_id=str(delivery["id"]),)- assert message_deliveries.agent_run_exclusively_owns_turn(+ assert message_deliveries.agent_run_input_reached_turn(conn,run_id=runs[0].id,turn_id=turn_id,- ) == (False, "turn_has_other_participants")+ ) == (True, "run_input_in_turn")controller = _build_controller_double()app = internal_server.create_app(controller)@@ -7851,7 +8086,7 @@ def test_run_cancel_preserves_shared_starting_batch_siblings(monkeypatch, tmp_paresponse, started_original = asyncio.run(_go())assert response.status_code == 200- assert response.json()["status"] == "run_detached"+ assert response.json()["status"] == "cancel_requested"assert started_original is Falseassert dispatched == ["surviving batch participant"]assert request_store.get_run(runs[0].id)["status"] == "canceled"@@ -7872,6 +8107,150 @@ def test_run_cancel_preserves_shared_starting_batch_siblings(monkeypatch, tmp_paassert surviving["turn_id"] != turn_id+def _prewrite_batch_with_absorbing_runner(monkeypatch, tmp_path, native_id):+ """Start a real two-Run pre-write batch whose dispatch absorbs cancellation."""++ from core.native_dispatch_phase import DISPATCH_PHASE_PREWRITE, set_dispatch_phase+ from core.scheduled_tasks import TaskExecutionStore+ from core.services.dispatch import TurnDispatchOutcome+ 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=native_id)+ session_id = session["id"]+ request_store = TaskExecutionStore()+ texts = ("canceled batch participant", "surviving batch participant")+ runs = [+ request_store.enqueue_agent_run(+ session_id=session_id,+ message=message,+ agent_name="worker",+ )+ for message in texts+ ]+ assert all(request_store.claim(run.id) is not None for run in runs)+ with engine.begin() as conn:+ deliveries = [+ _reserve_submission(+ conn,+ scope_id=session["scope_id"],+ session_id=session_id,+ text=text,+ )+ for text in texts+ ]+ 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="\n\n".join(texts),+ )+ for run, delivery in zip(runs, claimed["deliveries"], strict=True):+ assert attach_agent_run_delivery_in_connection(+ conn,+ run.id,+ session_id=session_id,+ delivery_id=str(delivery["id"]),+ )++ controller = _build_controller_double()+ internal_server.create_app(controller)+ manager = controller.session_turns+ dispatch_entered = asyncio.Event()++ async def absorbing_prewrite_dispatch(_controller, dispatch_context, *_a, **_k):+ set_dispatch_phase(dispatch_context, DISPATCH_PHASE_PREWRITE)+ dispatch_entered.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ # OpenCode absorbs the inner cancellation after its cleanup.+ return TurnDispatchOutcome(+ error=None,+ settled_by=None,+ backend_dispatch_attempted=False,+ )++ monkeypatch.setattr(+ "core.session_turns.dispatch_turn_with_outcome",+ absorbing_prewrite_dispatch,+ )+ real_run = manager._run+ successor_starts: list[str] = []++ async def _run(run_session_id, run_context, text, **kwargs):+ if kwargs.get("logical_turn_id") == turn_id:+ return await real_run(run_session_id, run_context, text, **kwargs)+ successor_starts.append(text)++ monkeypatch.setattr(manager, "_run", _run)+ context = MessageContext(+ user_id="workbench",+ channel_id=session_id,+ platform="avibe",+ platform_specific={"workbench_session_id": session_id},+ )+ return SimpleNamespace(+ engine=engine,+ session_id=session_id,+ request_store=request_store,+ runs=runs,+ delivery_ids=[str(row["id"]) for row in claimed["deliveries"]],+ turn_id=turn_id,+ manager=manager,+ controller=controller,+ context=context,+ dispatch_entered=dispatch_entered,+ successor_starts=successor_starts,+ )+++def test_run_cancel_of_a_prewrite_batch_stops_it_like_session_stop(+ monkeypatch,+ tmp_path,+):+ """A pre-write Run cancel retires the whole claimed batch, like Stop."""++ batch = _prewrite_batch_with_absorbing_runner(+ monkeypatch,+ tmp_path,+ "proj_absorbing_prewrite_run_cancel",+ )++ async def _go():+ assert await batch.manager._start_persisted_turn(+ batch.turn_id,+ context=batch.context,+ )+ await asyncio.wait_for(batch.dispatch_entered.wait(), timeout=1.0)+ return await batch.manager.cancel(+ batch.session_id,+ agent_run_id=batch.runs[0].id,+ )++ result = asyncio.run(_go())++ assert result == {+ "ok": True,+ "session_id": batch.session_id,+ "status": "cancel_requested",+ "reason": "prewrite_canceled",+ }+ batch.controller.command_handler.handle_stop.assert_not_awaited()+ assert batch.successor_starts == []+ assert batch.request_store.get_run(batch.runs[0].id)["status"] == "canceled"+ with batch.engine.connect() as conn:+ original = message_deliveries.get_turn(conn, batch.turn_id)+ states = [+ message_deliveries.get_delivery(conn, delivery_id)["state"]+ for delivery_id in batch.delivery_ids+ ]+ assert original is not None and original["terminal_outcome"] == "not_written"+ assert states == ["retired", "retired"]+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."""@@ -7924,7 +8303,7 @@ def test_run_cancel_rechecks_a_changed_current_turn(monkeypatch, tmp_path):priority="p0",content=None,expected_turn_id="trn_recovered_predecessor",- expected_exclusive_agent_run_id=owner_run.id,+ cancel_agent_run_id=owner_run.id,),context=context,)@@ -8138,11 +8517,11 @@ def test_run_cancel_guard_allows_the_sole_initial_run_owner(monkeypatch, tmp_patsession_id=session["id"],delivery_id=initial["id"],)- assert message_deliveries.agent_run_exclusively_owns_turn(+ assert message_deliveries.agent_run_input_reached_turn(conn,run_id=run.id,turn_id=turn_id,- ) == (True, "exclusive_run_owner")+ ) == (True, "run_input_in_turn")# --- #84: scheduled provenance survives the merge-queue --------------------------diff --git a/vibe/cli.py b/vibe/cli.pyindex 06961613e..61ad5c17a 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -7487,7 +7487,10 @@ def _cancel_live_agent_run(store: TaskExecutionStore, run: dict) -> dict:),"controller_status_code": normalized_status_code,"controller_response": body,- "message": "Run was canceled without stopping the shared Session turn.",+ "message": i18n_t(+ "harness.run.cli.canceledBeforeLiveTurn",+ _configured_cli_language(),+ ),}if (normalized_status_code is not None@@ -17022,7 +17025,10 @@ def build_parser():runs_show_parser = runs_subparsers.add_parser("show", help="Show one Agent run")runs_show_parser.add_argument("run_id", nargs="?")_add_json_noop(runs_show_parser)- runs_cancel_parser = runs_subparsers.add_parser("cancel", help="Request best-effort cancellation for one run")+ runs_cancel_parser = runs_subparsers.add_parser(+ "cancel",+ help=i18n_t("harness.run.cli.help.cancel", _configured_cli_language()),+ )runs_cancel_parser.add_argument("run_id")_add_json_noop(runs_cancel_parser)diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex a0d4eedb9..749c2bcd2 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -171,7 +171,13 @@"failed": "The run failed before producing a result."},"bindingUnresolvedRetry": "Pinned agent session {session} cannot accept a turn ({attempt}/{threshold}). This definition will be paused after {threshold} consecutive unresolvable-target failures. Re-point it with: vibe task update {id} --session-id <id>.",- "bindingUnresolvedPaused": "paused: pinned agent session {session} cannot accept a turn. This definition would fail on every run. Re-point it with: vibe task update {id} --session-id <id>; then resume it with: vibe task resume {id}."+ "bindingUnresolvedPaused": "paused: pinned agent session {session} cannot accept a turn. This definition would fail on every run. Re-point it with: vibe task update {id} --session-id <id>; then resume it with: vibe task resume {id}.",+ "cli": {+ "help": {+ "cancel": "Request best-effort cancellation for one run; a run already in the live Session turn stops that whole turn, like Session Stop"+ },+ "canceledBeforeLiveTurn": "Run was canceled before its input reached the live Session turn."+ }},"notice": {"failed": "[Avibe Harness] Scheduled work \"{name}\" failed.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 73912e8af..3868da596 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -171,7 +171,13 @@"failed": "本次 run 在产出结果前失败,因此没有结果。"},"bindingUnresolvedRetry": "绑定的 Agent 会话 {session} 无法接收请求({attempt}/{threshold})。连续 {threshold} 次出现目标会话不可用后,该定义将自动暂停。请用以下命令重新绑定:vibe task update {id} --session-id <id>。",- "bindingUnresolvedPaused": "已暂停:绑定的 Agent 会话 {session} 无法接收请求,该定义继续运行只会反复失败。请用以下命令重新绑定:vibe task update {id} --session-id <id>;然后恢复:vibe task resume {id}。"+ "bindingUnresolvedPaused": "已暂停:绑定的 Agent 会话 {session} 无法接收请求,该定义继续运行只会反复失败。请用以下命令重新绑定:vibe task update {id} --session-id <id>;然后恢复:vibe task resume {id}。",+ "cli": {+ "help": {+ "cancel": "\u8bf7\u6c42\u5c3d\u529b\u53d6\u6d88\u4e00\u4e2a run\uff1b\u82e5\u8be5 run \u5df2\u8fdb\u5165\u6b63\u5728\u8fd0\u884c\u7684 Session turn\uff0c\u4f1a\u50cf Session Stop \u4e00\u6837\u505c\u6b62\u6574\u4e2a turn"+ },+ "canceledBeforeLiveTurn": "\u8be5 run \u5728\u5176\u8f93\u5165\u8fdb\u5165\u6b63\u5728\u8fd0\u884c\u7684 Session turn \u4e4b\u524d\u5df2\u88ab\u53d6\u6d88\u3002"+ }},"notice": {"failed": "[Avibe Harness] 后台任务「{name}」执行失败。",