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(workbench): verify in-flight turn identity before active End promotion (#664)
Call White5d12c4302ae8
diff --git a/core/services/running_agents.py b/core/services/running_agents.pyindex ae7e02447..371218a3e 100644--- a/core/services/running_agents.py+++ b/core/services/running_agents.py@@ -892,6 +892,55 @@ async def _stop_active_agent(return {"ok": False, "error": str(payload.get("stop_failure_reason") or "stop_failed")}+def _inflight_turn_matches_row(+ controller: "Controller",+ *,+ session_id: str,+ backend: Optional[str],+ base_session_id: Optional[str],+) -> bool:+ """True when the Workbench turn in flight for ``session_id`` is THIS row's+ runtime (same backend / session anchor), so promoting the row to active and+ canceling that turn is correct.++ The in-flight turn's identity comes from the ``MessageContext`` it started+ under (``platform_specific.agent_session_target`` → ``agent_backend`` /+ ``session_anchor``; same source ``turn_state`` uses). We require a positive+ match on backend and/or anchor and NO conflict on either: a mismatch means a+ different turn is running under the same chat, and "no evidence" is treated as+ not-this-row (the backend-specific checks then decide), so we never cancel an+ unrelated turn.+ """+ manager = getattr(controller, "session_turns", None)+ in_flight = getattr(manager, "in_flight", None)+ if not isinstance(in_flight, dict):+ return False+ entry = in_flight.get(session_id)+ if entry is None:+ return False+ task = getattr(entry, "task", None)+ try:+ if task is not None and hasattr(task, "done") and task.done():+ return False+ except Exception: # noqa: BLE001+ pass+ payload = getattr(getattr(entry, "context", None), "platform_specific", None) or {}+ target = payload.get("agent_session_target") if isinstance(payload, dict) else None+ target = target if isinstance(target, dict) else {}+ turn_backend = str(target.get("agent_backend") or "").strip()+ turn_anchor = str(target.get("session_anchor") or "").strip()+ row_backend = str(backend or "").strip()+ row_base = str(base_session_id or "").strip()++ backend_conflict = bool(turn_backend and row_backend and turn_backend != row_backend)+ anchor_conflict = bool(turn_anchor and row_base and turn_anchor != row_base)+ if backend_conflict or anchor_conflict:+ return False+ backend_match = bool(turn_backend and turn_backend == row_backend)+ anchor_match = bool(turn_anchor and turn_anchor == row_base)+ return backend_match or anchor_match++def _resolve_live_state(controller: "Controller",*,@@ -912,15 +961,18 @@ def _resolve_live_state(Returns ``"active"``/``"idle"``, or ``None`` when the live state can't bedetermined (caller then falls back to the client-supplied ``state``)."""- # A Workbench/chat turn in flight is authoritative for any backend.- manager = getattr(controller, "session_turns", None)- is_in_flight = getattr(manager, "is_in_flight", None)- if session_id and callable(is_in_flight):- try:- if is_in_flight(session_id):- return "active"- except Exception: # noqa: BLE001- logger.debug("end: is_in_flight check failed for %s", session_id, exc_info=True)+ # A Workbench/chat turn in flight promotes the row to active — but ONLY when+ # that in-flight turn actually belongs to the clicked row. A chat session can+ # hold an idle row for one backend/base while a *different* turn (e.g. a new+ # Claude message after an idle Codex row) runs under the same ``session_id``;+ # promoting on ``session_id`` alone would make the active End cancel that+ # unrelated turn. So compare the in-flight turn's backend / session anchor to+ # the target before trusting it; on conflict or no positive identity match,+ # fall through to the backend-specific live checks below.+ if session_id and _inflight_turn_matches_row(+ controller, session_id=session_id, backend=backend, base_session_id=base_session_id+ ):+ return "active"if backend == "claude":active = getattr(controller, "claude_active_sessions", set()) or set()diff --git a/tests/test_running_agents_service.py b/tests/test_running_agents_service.pyindex 9abbab433..af2b22fea 100644--- a/tests/test_running_agents_service.py+++ b/tests/test_running_agents_service.py@@ -802,7 +802,20 @@ def test_end_active_workbench_turn_settles_via_manager(monkeypatch):return {"ok": True, "status": "cancel_requested", "backend": "claude"}cancel = _WorkbenchCancel()- manager = types.SimpleNamespace(is_in_flight=lambda sid: sid == "ses-wb", cancel=cancel)+ # The live-state recheck verifies the in-flight turn belongs to THIS row before+ # promoting to active, so expose an in_flight entry whose context identifies the+ # same (claude) backend.+ wb_entry = types.SimpleNamespace(+ task=types.SimpleNamespace(done=lambda: False),+ context=types.SimpleNamespace(+ platform_specific={"agent_session_target": {"agent_backend": "claude"}}+ ),+ )+ manager = types.SimpleNamespace(+ is_in_flight=lambda sid: sid == "ses-wb",+ cancel=cancel,+ in_flight={"ses-wb": wb_entry},+ )cleanup = _AsyncFlag()controller = _make_controller()controller.session_turns = manager@@ -947,6 +960,107 @@ def test_end_unknown_target():assert res["error"] == "unknown_target"+def _controller_with_inflight(session_id, *, agent_backend=None, session_anchor=None, task_done=False):+ target = {}+ if agent_backend is not None:+ target["agent_backend"] = agent_backend+ if session_anchor is not None:+ target["session_anchor"] = session_anchor+ ctx = types.SimpleNamespace(+ platform_specific=({"agent_session_target": target} if target else {})+ )+ entry = types.SimpleNamespace(task=types.SimpleNamespace(done=lambda: task_done), context=ctx)+ controller = _make_controller()+ controller.session_turns = types.SimpleNamespace(in_flight={session_id: entry})+ return controller+++def test_inflight_match_anchor_only():+ # The dominant production path: backend empty on the live context, but the+ # reliably-populated session_anchor matches the row → promote.+ c = _controller_with_inflight("s1", session_anchor="base-1")+ assert running_agents._inflight_turn_matches_row(+ c, session_id="s1", backend="codex", base_session_id="base-1"+ ) is True+++def test_inflight_match_backend_only():+ # No anchor on the context, but backend matches → promote.+ c = _controller_with_inflight("s1", agent_backend="claude")+ assert running_agents._inflight_turn_matches_row(+ c, session_id="s1", backend="claude", base_session_id="base-1"+ ) is True+++def test_inflight_no_match_same_backend_different_anchor():+ # Same backend but a different anchor → a different turn is running; do NOT+ # promote (anchor conflict wins over backend match).+ c = _controller_with_inflight("s1", agent_backend="claude", session_anchor="other-base")+ assert running_agents._inflight_turn_matches_row(+ c, session_id="s1", backend="claude", base_session_id="base-1"+ ) is False+++def test_inflight_no_match_when_target_missing_or_task_done():+ # No agent_session_target at all → no positive evidence → not this row.+ c_empty = _controller_with_inflight("s1")+ assert running_agents._inflight_turn_matches_row(+ c_empty, session_id="s1", backend="claude", base_session_id="base-1"+ ) is False+ # A completed task is not in flight, even if identity would match.+ c_done = _controller_with_inflight("s1", session_anchor="base-1", task_done=True)+ assert running_agents._inflight_turn_matches_row(+ c_done, session_id="s1", backend="claude", base_session_id="base-1"+ ) is False+++def test_end_does_not_cancel_unrelated_inflight_turn_of_other_backend():+ # Stale idle Codex row, but the SAME chat has since started a new Claude turn+ # (in flight under the same session_id). Ending the codex row must NOT cancel+ # the unrelated Claude turn — the live recheck sees a backend conflict, treats+ # the codex row as idle, and runs the idle codex teardown instead.+ cancel_called = {"v": False}++ async def _cancel(_sid):+ cancel_called["v"] = True+ return {"ok": True, "status": "cancel_requested", "backend": "claude"}++ inflight_ctx = types.SimpleNamespace(+ platform_specific={"agent_session_target": {"agent_backend": "claude", "session_anchor": "claude-base"}}+ )+ inflight_entry = types.SimpleNamespace(task=types.SimpleNamespace(done=lambda: False), context=inflight_ctx)+ manager = types.SimpleNamespace(+ is_in_flight=lambda sid: True,+ cancel=_cancel,+ in_flight={"chat-1": inflight_entry},+ )++ cleared = {}+ transport = types.SimpleNamespace(send_request=_AsyncFlag(), stop=_AsyncFlag())+ mgr = types.SimpleNamespace(+ get_cwd=lambda b: "/w",+ get_thread_id=lambda b: None,+ clear=lambda b: cleared.__setitem__("clr", b),+ sessions_for_cwd=lambda cwd: [],+ )+ treg = _FakeTurnRegistry({}, pending=set()) # the codex base is genuinely idle+ treg.clear_session = lambda b: cleared.__setitem__("treg", b)+ codex = types.SimpleNamespace(+ _session_mgr=mgr, _turn_registry=treg, _transports={"/w": transport}, _transport_last_activity={"/w": 0.0}+ )+ controller = _make_controller(codex=codex)+ controller.session_turns = manager++ res = asyncio.run(+ running_agents.end_running_agent(+ controller, backend="codex", state="active", session_id="chat-1", base_session_id="codex-base"+ )+ )+ assert res["ok"] is True+ assert cancel_called["v"] is False # the unrelated in-flight Claude turn was NOT canceled+ assert cleared.get("clr") == "codex-base" and cleared.get("treg") == "codex-base" # idle codex teardown ran++def test_end_rechecks_live_state_idle_to_active(monkeypatch):# The browser polled this Claude row as idle, but it went active before the# user clicked Disconnect. End must re-derive the live state server-side and