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): let the Turn decide a Run whose background task ends mid-Turn (#2975)
Call White0c408e5ce737
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex bbcc90164..e02db68e1 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -3224,6 +3224,7 @@ class TaskExecutionStore:error: Optional[str] = None,result_text: Optional[str] = None,metadata: Optional[dict[str, Any]] = None,+ amend_only: bool = False,) -> bool:if self._sqlite is None:return False@@ -3233,6 +3234,7 @@ class TaskExecutionStore:error=error,result_text=result_text,metadata=metadata,+ amend_only=amend_only,)def update_callback_status(@@ -4658,7 +4660,7 @@ class ScheduledTaskService:if callable(drain_terminals):for activity in drain_terminals():try:- self.settle_activity_runs(activity)+ self.settle_activity_runs(activity, recovered=True)except Exception:self._pending_recovered_activity_terminals.append(activity)logger.warning(@@ -4717,7 +4719,7 @@ class ScheduledTaskService:remaining.append(activity)continuetry:- self.settle_activity_runs(activity)+ self.settle_activity_runs(activity, recovered=True)if callable(ack_terminal):ack_terminal(activity)except Exception:@@ -7671,9 +7673,16 @@ class ScheduledTaskService:lines.extend(self._deleted_definition_lines(run_id))return "\n".join(lines)- def settle_activity_runs(self, activity: Any) -> list[str]:+ def settle_activity_runs(self, activity: Any, *, recovered: bool = False) -> list[str]:"""Settle deferred Runs when a failed/stopped owned Activity is last.+ An Activity's own outcome counts only once its Run's Turn has recorded a+ terminal and the Run waits on that Activity. One that ends while the+ Turn still runs, such as a background task the Agent stops or sees fail,+ is a step the Agent answers in that Turn, so the Turn's terminal decides+ the Run. A ``recovered`` terminal comes from before a restart: its Turn+ is gone and cannot answer it, so the Activity's outcome settles the Run.+An Activity whose metadata names an ``interrupt_reason`` was ended bythe service itself, as a forced runtime refresh does. Its Runs thensettle as that interruption, which owes the user a notice, instead of a@@ -7714,10 +7723,18 @@ class ScheduledTaskService:if activity_status == "failed" and not interrupt_reasonelse None)+ # The live Turn sees its own task stop or fail and answers it; it cannot+ # see the service end the task or the runtime lose it.+ seen_by_turn = (+ not recovered+ and not interrupt_reason+ and activity_status in {"failed", "stopped", "killed"}+ )for run_id in run_ids:self.request_store.defer_run_terminal(run_id,terminal_status=terminal_status,+ amend_only=seen_by_turn,**({"error": own_failure} if own_failure else {}),)if callable(has_blocker) and has_blocker(run_id):@@ -8012,6 +8029,11 @@ class ScheduledTaskService:parts.append(str(run["stderr"]))if run.get("stdout") and status != "succeeded":parts.append(str(run["stdout"]))+ result_text = str(run.get("result_text") or "").strip()+ if result_text and status in {"canceled", "failed"}:+ # The Agent's reply was recorded before the Run ended this way; the+ # caller gets it with the outcome instead of being told it never came.+ parts = [self._t(f"harness.run.fallbackResult.{status}WithResult"), *parts, result_text]if parts:return "\n\n".join(part.strip() for part in parts if part and part.strip())if status == "canceled":diff --git a/docs/plans/full-duplex-sessions.md b/docs/plans/full-duplex-sessions.mdindex 91b2ed8de..7f8d62333 100644--- a/docs/plans/full-duplex-sessions.md+++ b/docs/plans/full-duplex-sessions.md@@ -109,12 +109,20 @@ policy; it never satisfies or inherits the parent's automatic callback. Parentagainst the callback Run created only from the parent's terminal result.If a Run fails or is canceled after recording partial outputs, its callback-Session receives one terminal failure/cancellation Message. A successful Run-receives one terminal result Message; prior Activity or progress output is not-copied into the callback Session.+Session receives one terminal failure/cancellation Message. When the Run's+terminal reply was already recorded, for example before a background Activity+it left running stopped or failed, that Message states the outcome and then+carries the reply. A successful Run receives one terminal result Message; prior+Activity or progress output is not copied into the callback Session.A terminal Run intent is retained in `result_payload_json` while a non-detached-owned Activity remains active. A later Activity output can complete that Run+owned Activity remains active. An owned Activity's own outcome only amends an+intent its Turn already recorded: a background task the Agent stops, or sees+fail, while the Turn still runs is a step of that Turn, and the Turn's terminal+decides the Run. An Activity the Turn cannot answer still settles the Run+ahead of it: one the service ended (it carries an `interrupt_reason`), one the+runtime lost (`disconnected`), or a terminal recovered after a restart. A+later Activity output can complete that Runwithout acquiring lifecycle authority over whichever foreground Turn is current.Deferred terminal intent is excluded from generic restart requeueing, thenreconciled against recovered Activity/output snapshots before normal Run drain.diff --git a/storage/background.py b/storage/background.pyindex 3c5fc4963..f97fa094b 100644--- a/storage/background.py+++ b/storage/background.py@@ -6926,9 +6926,16 @@ class SQLiteBackgroundTaskStore:result_text: Optional[str] = None,metadata: Optional[dict[str, Any]] = None,updated_at: Optional[str] = None,+ amend_only: bool = False,_conn: Any = None,) -> bool:- """Remember a terminal intent and its evidence while an Activity blocks it."""+ """Remember a terminal intent and its evidence while an Activity blocks it.++ ``amend_only`` adds to an intent the Run's Turn already recorded and does+ nothing when there is none: an owned Activity that ends while its Turn is+ still running is a step the Agent sees and answers in that Turn, so the+ Turn's own terminal decides the Run.+ """now = updated_at or _utc_now_iso()row_to_publish = None@@ -6942,6 +6949,8 @@ class SQLiteBackgroundTaskStore:result_payload = _json_loads(row["result_payload_json"], {})if not isinstance(result_payload, dict):result_payload = {}+ if amend_only and not result_payload.get("deferred_terminal_status"):+ return Falsenormalized = _stronger_terminal_status(result_payload.get("deferred_terminal_status"),terminal_status,diff --git a/tests/test_agent_run_close_after.py b/tests/test_agent_run_close_after.pyindex 8da71c3a1..8965a6ea8 100644--- a/tests/test_agent_run_close_after.py+++ b/tests/test_agent_run_close_after.py@@ -1205,8 +1205,9 @@ def test_an_activity_started_while_the_runs_terminal_record_waits_still_defers_tdef test_an_activity_that_settles_while_the_runs_terminal_record_waits_stays_first(tmp_path, monkeypatch) -> None:"""#2706: the other order. An owned Activity that the loop saw open ends -- durably -- and settles the Run whilethe record waits for SQLite's writer. The Activity's settlement committed first, so it stays first: the Run keeps- the Activity's status and the record adds only its output, exactly as when the Activity had ended before the result- on the loop."""+ the Activity's outcome and the record adds only its output, exactly as when the Activity had ended before the result+ on the loop. Only an Activity the service ended settles a Run whose Turn is still running, so this one is a runtime+ replacement."""from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore, TaskExecutionStorefrom storage.background import SQLiteBackgroundTaskStore@@ -1262,14 +1263,17 @@ def test_an_activity_that_settles_while_the_runs_terminal_record_waits_stays_fir# The Activity ends on the loop and its Run owner settles it, before the record commits.blocked[0] = Falseactivity_store.upsert_activity(activity_row, phase="awaiting_output")- activity = SimpleNamespace(id="activity-1", status="stopped", run_id=queued.id, metadata={})+ activity = SimpleNamespace(+ id="activity-1", status="killed", run_id=queued.id, metadata={"interrupt_reason": "backend_refresh"}+ )assert scheduled.settle_activity_runs(activity) == [queued.id]release.set()await recordasyncio.run(exercise())settled = request_store.get_run(queued.id)- assert normalize_run_status(settled["status"]) == "canceled", "the later record replaced the Activity's settlement"+ assert settled["metadata"].get("interrupt_reason") == "backend_refresh", "the later record replaced the Activity's settlement"+ assert settled["error"] != "the turn failed", "the later record replaced the Activity's settlement"def test_the_runs_terminal_record_reads_only_its_sessions_activities(tmp_path, monkeypatch) -> None:diff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.pyindex 03c30e45f..168eda7dd 100644--- a/tests/test_message_dispatcher_scheduled.py+++ b/tests/test_message_dispatcher_scheduled.py@@ -2463,7 +2463,7 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):terminal_runs = set()class _RequestStore:- def defer_run_terminal(self, run_id, *, terminal_status, error=None):+ def defer_run_terminal(self, run_id, *, terminal_status, error=None, amend_only=False):events.append(("defer", run_id, terminal_status))def settle_deferred_run(self, run_id, *, error):diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex ce427c2da..a66e5606b 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -8426,6 +8426,11 @@ def test_refresh_ending_the_last_activity_keeps_the_runs_first_cause(run_id=request.id,)if prior == "failed_sibling":+ # The Turn already replied; its terminal waits on both Activities.+ assert request_store._sqlite.defer_run_terminal(+ request.id,+ terminal_status="succeeded",+ ) is Truefirst = registry.complete(backend="claude",runtime_key="runtime-1",@@ -8554,6 +8559,140 @@ def test_terminal_owned_activity_settles_deferred_run_once(assert request_store.get_run(request.id)["completed_at"] == completed_at+def _service_with_activity_registry(tmp_path: Path):+ request_store = TaskExecutionStore()+ controller = _avibe_controller_double(+ gate=SimpleNamespace(submit_scheduled=lambda *_args, **_kwargs: None, in_flight={}),+ handle_scheduled_message=lambda *_args, **_kwargs: None,+ )+ registry = SessionActivityRegistry()+ controller.agent_service = SimpleNamespace(activities=registry)+ service = ScheduledTaskService(+ controller=controller,+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),+ request_store=request_store,+ )+ return request_store, registry, service++[email protected]("activity_status", ["stopped", "killed", "failed"])+def test_an_activity_that_ends_during_its_turn_leaves_the_run_to_the_turn(+ tmp_path: Path,+ monkeypatch,+ activity_status: str,+) -> None:+ """A background task the Agent stops, or sees fail, while its Turn still runs is one step of that Turn.++ The Agent answers it in the same Turn, so the Turn's terminal decides the Run. A delegated Run that stopped its own+ background test and then finished its work was settled ``canceled``, and its caller was told no result existed.+ """++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ request_store, registry, service = _service_with_activity_registry(tmp_path)+ request = request_store.enqueue_agent_run(+ session_id="target-session",+ message="delegated work",+ agent_name="claude",+ )+ assert request_store.claim(request.id) is not None+ registry.start(+ backend="claude",+ runtime_key="runtime-1",+ session_id="target-session",+ activity_id="task-tests",+ kind="background_task",+ run_id=request.id,+ )+ activity = registry.complete(+ backend="claude",+ runtime_key="runtime-1",+ activity_id="task-tests",+ status=activity_status,+ )+ assert activity is not None++ assert service.settle_activity_runs(activity) == []+ running = request_store.get_run(request.id)+ assert running["status"] == "running"+ assert "deferred_terminal_status" not in (running["result_payload"] or {})++ result = request_store._sqlite.record_run_output(+ request.id,+ output_id="turn:final",+ text="The work is done.",+ terminal_status="succeeded",+ )++ assert result["terminal_transition"] is True+ terminal = request_store.get_run(request.id)+ assert terminal["status"] == "succeeded"+ assert terminal["result_text"] == "The work is done."+++ ("activity_status", "expected_status", "expected_lead"),+ [+ ("stopped", "canceled", "The run was canceled after producing the result below."),+ ("failed", "failed", "The run failed after producing the result below."),+ ],+)+def test_a_run_that_ends_badly_after_its_reply_still_calls_back_with_the_reply(+ tmp_path: Path,+ monkeypatch,+ activity_status: str,+ expected_status: str,+ expected_lead: str,+) -> None:+ """The Turn replied, then a background task it left running stopped or failed. The Run ends that way, and its+ caller receives the outcome together with the reply instead of a claim that no result was produced."""++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ caller_session_id = _make_avibe_session(monkeypatch, tmp_path)+ request_store, registry, service = _service_with_activity_registry(tmp_path)+ request = request_store.enqueue_agent_run(+ session_id="target-session",+ message="delegated work",+ agent_name="claude",+ callback_session_id=caller_session_id,+ )+ assert request_store.claim(request.id) is not None+ registry.start(+ backend="claude",+ runtime_key="runtime-1",+ session_id="target-session",+ activity_id="task-tests",+ kind="background_task",+ run_id=request.id,+ )+ assert request_store.defer_run_terminal(+ request.id,+ terminal_status="succeeded",+ result_text="The work is done.",+ ) is True+ activity = registry.complete(+ backend="claude",+ runtime_key="runtime-1",+ activity_id="task-tests",+ status=activity_status,+ )+ assert service.settle_activity_runs(activity) == [request.id]++ asyncio.run(service._drain_callbacks())++ original = request_store.get_run(request.id)+ assert original["status"] == expected_status+ callback_runs = [+ run+ for run in request_store.list_runs()+ if run.get("source_kind") == "callback" and run.get("parent_run_id") == request.id+ ]+ assert len(callback_runs) == 1+ message = callback_runs[0]["message"]+ assert message.startswith(expected_lead)+ assert message.endswith("The work is done.")+ assert f"Background Activity task-tests {activity_status}" in message++def test_failed_activity_intent_survives_until_last_owned_activity_finishes(tmp_path: Path,monkeypatch,diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 9642fed0b..ec6c7ccbc 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -173,7 +173,9 @@},"fallbackResult": {"canceled": "The run was canceled before producing a result.",- "failed": "The run failed before producing a result."+ "failed": "The run failed before producing a result.",+ "canceledWithResult": "The run was canceled after producing the result below.",+ "failedWithResult": "The run failed after producing the result below."},"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}."diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex e151d3275..8c2b0e50a 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -173,7 +173,9 @@},"fallbackResult": {"canceled": "本次 run 在产出结果前被取消,因此没有结果。",- "failed": "本次 run 在产出结果前失败,因此没有结果。"+ "failed": "本次 run 在产出结果前失败,因此没有结果。",+ "canceledWithResult": "本次 run 在产出下面的结果后被取消。",+ "failedWithResult": "本次 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}。"