Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(chat): enable retry on linked Harness failure notices (#2018)

Call White0e5a672ad183
diff --git a/core/backend_failure.py b/core/backend_failure.py
index 138e11588..750002076 100644
--- a/core/backend_failure.py
+++ b/core/backend_failure.py
@@ -267,6 +267,7 @@ async def emit_replayed_backend_failure(
diagnostic: str,
*,
failure_id: str,
+ turn_id: str | None = None,
display_text: str | None = None,
delivery: DeliveryEvidence | None = None,
) -> None:
@@ -305,6 +306,11 @@ async def emit_replayed_backend_failure(
``delivery`` is filled in with what the notify attempt actually proved; the
drain acks its durable notice on that evidence, never on a clean return.
+
+ ``turn_id`` is the durable notice's failed Turn, supplied only when the
+ delivery target is that Run's own Session. It is message provenance, never a
+ live context token. Unlinked and cross-Session reports remain informational;
+ all replays stay outside foreground Activity even when Retry is available.
"""
backend_name = str(backend or "backend").strip() or "backend"
@@ -317,6 +323,9 @@ async def emit_replayed_backend_failure(
backend_name,
failure_id=failure_id,
failure_id_authoritative=True,
+ output=MessageOutput(
+ metadata={"turn_id": str(turn_id or "").strip() or None, "replayed": True},
+ ),
)
# ``delivery`` is passed ONLY when a caller asked for it: controller-like objects
# that implement ``emit_agent_message`` without the keyword must keep working.
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index a1f9ba685..cea25cb0f 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -6526,6 +6526,15 @@ class ScheduledTaskService:
str(run.get("error") or "").strip() or body,
display_text=body,
failure_id=failure_id,
+ # The durable notice owns this identity, not a parsed
+ # failure_id or a live context token. Other delivery
+ # rungs report the failure without offering a retry in
+ # an unrelated Session.
+ turn_id=(
+ failure_notices.notice_turn_id(notice)
+ if session_id and session_id == run.get("session_id")
+ else None
+ ),
delivery=rung,
)
except Exception as exc:
diff --git a/docs/plans/backend-failure-retry.md b/docs/plans/backend-failure-retry.md
index e82bfe02f..e478b4c96 100644
--- a/docs/plans/backend-failure-retry.md
+++ b/docs/plans/backend-failure-retry.md
@@ -14,7 +14,14 @@ not a new backend retry protocol or an automatic retry policy.
Its visible restart explanation is unchanged. The notice does not settle
another Turn or replay the original request; clicking continues through the
existing admission path. Harness-owned interruptions retain their existing
- notice owner, and a restorable live backend does not acquire a retry action.
+ notice owner: its owed-notice drain carries the authoritative notice `turn_id`
+ when delivering to the Run's own explicit Session. Generic Run failures
+ without a Turn binding and fallback delivery to another Session remain
+ informational; a Turn is never guessed from a failure ID or notification text.
+ The existing admission checks still reject stale, busy, stopped, or
+ acceptance-unknown work. Clicking continues that Session, not the original
+ Task/Watch command or definition. A restorable live backend does not acquire
+ a retry action.
Recovery sets `metadata.replayed=true`: the notice describes an already-ended
Turn, even on immediate delivery. This is not detached completion and does not
disable Retry. The Web classifier refreshes durable Activity without settling
@@ -23,6 +30,8 @@ not a new backend retry protocol or an automatic retry policy.
filter apply the same nonterminal provenance, so history readback cannot
reinterpret the notice as newer work ending. Ordinary live failures keep
their terminal UI role.
+ The Harness replay emitter applies the same historical provenance to every
+ owed notice without adding a live Turn token to its delivery context.
- The action targets the notice's exact Session and failed Turn. The server
rechecks access, archive/read-only status, current Turn, and pending input.
A newer task, another live owner, or an unresolved native start blocks it.
@@ -98,6 +107,7 @@ implementations; IM-specific notification button rendering is not added here.
Scenario contracts: `MESSAGE-DELIVERY-026` through `MESSAGE-DELIVERY-028`.
Restart notification binding and continuation: `MESSAGE-DELIVERY-030`.
+Harness-owned notification binding and continuation: `MESSAGE-DELIVERY-320`.
## Known by design
diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yaml
index 845106609..8e2c1ada9 100644
--- a/tests/scenarios/message_delivery/catalog.yaml
+++ b/tests/scenarios/message_delivery/catalog.yaml
@@ -332,5 +332,11 @@ scenarios:
kind: recovery
layer: contract
test: tests/test_session_delivery_fsm.py::test_steering_preparation_failure_preserves_a_definitively_unwritten_batch
+ - id: MESSAGE-DELIVERY-320
+ name: Harness restart notices retain same-Session Retry without reviving historical work
+ status: covered
+ kind: recovery
+ layer: contract
+ test: tests/test_harness_failure_retry.py::test_harness_restart_notice_retries_through_web_and_controller
next_priority:
- - MESSAGE-DELIVERY-320
+ - MESSAGE-DELIVERY-321
diff --git a/tests/scenarios/message_delivery/observations.yaml b/tests/scenarios/message_delivery/observations.yaml
index 2fa492c55..a77fe1614 100644
--- a/tests/scenarios/message_delivery/observations.yaml
+++ b/tests/scenarios/message_delivery/observations.yaml
@@ -1,6 +1,19 @@
version: 1
capability: message_delivery
observations:
+ - id: OBS-MESSAGE-DELIVERY-008
+ source: user_feedback_and_read_only_runtime_diagnosis
+ related_scenarios:
+ - MESSAGE-DELIVERY-320
+ summary: Harness-owned restart notifications still lacked Retry after ordinary restart notifications gained it.
+ previous_assumption: Preserving the existing Harness notification owner also preserved the failed-Turn action contract.
+ observed_behavior: The accepted failed Turn and owed notice were durably linked in one Session, but the replay emitter omitted turn_id and historical Activity provenance.
+ required_updates:
+ - carry the owed notice's authoritative Turn only to the Run's own explicit Session
+ - mark replayed notifications as historical without supplying a live context token
+ - reuse Web Retry admission and one continue Delivery without rerunning Tasks or Watches
+ - retain unlinked and cross-Session fallback reports as informational notices
+ - cover real Run settlement, delivery, persistence, Web/controller admission, and existing frontend rendering
- id: OBS-MESSAGE-DELIVERY-007
source: user_feedback
related_scenarios:
diff --git a/tests/test_harness_failure_retry.py b/tests/test_harness_failure_retry.py
new file mode 100644
index 000000000..114faac54
--- /dev/null
+++ b/tests/test_harness_failure_retry.py
@@ -0,0 +1,220 @@
+"""MESSAGE-DELIVERY-320: Harness recovery uses the existing notice-bound Retry."""
+
+from __future__ import annotations
+
+import asyncio
+from unittest.mock import AsyncMock, patch
+
+import httpx
+import pytest
+from sqlalchemy import select
+
+from core import internal_server
+from core.message_dispatcher import ConsolidatedMessageDispatcher
+from core.scheduled_tasks import ScheduledTaskService, TaskExecutionStore
+from core.session_turns import DeliveryRequest, SessionTurnManager
+from storage import message_deliveries, messages_service
+from storage.background import attach_agent_run_delivery_in_connection
+from storage.db import create_sqlite_engine
+from storage.models import agent_runs
+from tests.backend_failure_retry_helpers import seed_failed_notice
+from tests.scenario_harness.message_delivery import MessageDeliveryController
+from tests.test_harness_failure_visibility import _drain_service
+from tests.test_internal_server import _bind_test_native_start, _build_controller_double
+from tests.test_session_delivery_fsm import _context
+from tests.test_ui_session_stream import _make_session, isolated_state # noqa: F401
+from tests.ui_server_test_helpers import csrf_headers
+
+
[email protected](autouse=True)
+def _isolate_web_push(monkeypatch):
+ monkeypatch.setattr("core.web_push_notifications.maybe_notify_inbox_message", lambda *_args: None)
+
+
+def _harness_restart_notice(tmp_path, *, backend="codex", target="same", linked=True):
+ """Real Run/Delivery/Turn settlement, owed-notice drain, and message storage."""
+ scope_id, session_id = _make_session(tmp_path, agent_backend=backend)
+ engine = create_sqlite_engine()
+ controller = MessageDeliveryController(platform="avibe")
+ controller.config.language = "zh"
+ request_store = TaskExecutionStore()
+ service = _drain_service(tmp_path, controller, request_store.sqlite_backend, request_store)
+ service._t = ScheduledTaskService._t.__get__(service, ScheduledTaskService)
+ controller.scheduled_task_service = service
+ controller.emit_agent_message = ConsolidatedMessageDispatcher(controller).emit_agent_message
+
+ def context(sid):
+ value = _context(sid)
+ value.platform_specific["agent_session_target"]["agent_backend"] = backend
+ return value
+
+ manager = SessionTurnManager(controller, build_context=context)
+ manager._engine = engine
+ controller.session_turns = manager
+ run = request_store.enqueue_agent_run(
+ message="检查剩余工作,不要重复提交", session_id=session_id,
+ agent_name="worker", agent_backend=backend,
+ )
+ assert request_store.claim(run.id) is not None
+
+ async def accept(_sid, ctx, _text, **_kwargs):
+ _bind_test_native_start(engine, ctx)
+
+ manager._run = accept
+ original = asyncio.run(manager.deliver(
+ DeliveryRequest(
+ session_id=session_id, priority="p3", content=run.prompt,
+ source="harness", author="harness", message_type="harness",
+ ),
+ context=context(session_id),
+ ))
+ with engine.begin() as conn:
+ assert attach_agent_run_delivery_in_connection(
+ conn, run.id, session_id=session_id, delivery_id=original.delivery_id,
+ )
+ manager._terminalize_durable_turn(
+ original.turn_id, "failed", settled_by="restarted", evidence_kind="service_shutdown",
+ )
+ stored_run = request_store.get_run(run.id)
+ owed = request_store.sqlite_backend.owed_failure_notice(run.id)
+ assert stored_run["status"] == "failed"
+ assert owed["turn_id"] == original.turn_id
+ assert owed["failure_id"] == f"turn:{original.turn_id}"
+ if not linked:
+ # Legacy and command-only reports do not become linked by parsing their ID.
+ owed = {**owed, "turn_id": None}
+ newer = None
+ if target == "newer":
+ newer = asyncio.run(manager.deliver(
+ DeliveryRequest(session_id=session_id, priority="p3", content="新的一轮工作"),
+ context=context(session_id),
+ ))
+ if target == "other":
+ from core.services import sessions
+
+ with engine.begin() as conn:
+ other = sessions.create_session(
+ conn, scope_id=scope_id, agent_backend=backend,
+ agent_name="worker",
+ )
+ notice_session = other["id"]
+ from core.scheduled_tasks import parse_scope_id
+
+ service._failure_notice_targets = lambda _run: [
+ (parse_scope_id(scope_id), notice_session),
+ ]
+ else:
+ notice_session = session_id
+ from core.delivery_evidence import DeliveryEvidence
+
+ evidence = DeliveryEvidence()
+ assert asyncio.run(service._emit_failure_notice(stored_run, owed, evidence))
+ assert evidence.persisted_row is not None
+ # Same authoritative identity survives another delivery attempt.
+ assert asyncio.run(service._emit_failure_notice(stored_run, owed, DeliveryEvidence()))
+ with engine.connect() as conn:
+ notices = [
+ row for row in messages_service.list_session_messages(conn, session_id=notice_session)["messages"]
+ if row["type"] == "notify"
+ ]
+ turn = message_deliveries.get_turn(conn, original.turn_id)
+ if newer is not None:
+ assert message_deliveries.get_turn(conn, newer.turn_id)["state"] == "active"
+ assert len(notices) == 1
+ assert turn["terminal_outcome"] == "failed"
+ assert turn["start_receipt_outcome"] == "accepted"
+ assert controller.runtime_release_calls == controller.stream_completion_calls == 0
+ from vibe.message_types import activity_role_for
+
+ assert activity_role_for("notify", notices[0]["metadata"]) == "none"
+ return session_id, notices[0], turn
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
+def test_harness_restart_notice_retries_through_web_and_controller(isolated_state, tmp_path, monkeypatch, backend):
+ """MESSAGE-DELIVERY-320: a Harness report admits one continue, not a Run rerun."""
+ from vibe import ui_server
+
+ session_id, notice, turn = _harness_restart_notice(tmp_path, backend=backend)
+ assert "[Avibe Harness]" in notice["text"]
+ assert notice["metadata"]["turn_id"] == turn["id"]
+ assert notice["metadata"]["replayed"] is True
+ assert notice["metadata"]["detached"] is False
+ controller = _build_controller_double()
+ internal_app = internal_server.create_app(controller)
+ manager = controller.session_turns
+ engine = create_sqlite_engine()
+ starts = []
+
+ async def accept(sid, context, text, *, logical_turn_id=None, **_kwargs):
+ starts.append((sid, text))
+ _bind_test_native_start(engine, context)
+ manager._terminalize_durable_turn(
+ logical_turn_id, "completed", settled_by="terminal_result", evidence_kind="test_terminal",
+ )
+
+ manager._run = accept
+
+ async def dispatch(payload):
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=internal_app), base_url="http://testserver",
+ ) as internal:
+ response = await internal.post("/internal/dispatch_async", json=payload)
+ return {"status_code": response.status_code, "body": response.json()}
+
+ monkeypatch.setattr("vibe.internal_client.dispatch_async", dispatch)
+ client = ui_server.app.test_client()
+ headers = csrf_headers(client)
+ draft = client.put(
+ f"/api/sessions/{session_id}/draft", headers=headers,
+ json={"text": "保留这份草稿", "expected_updated_at": None},
+ ).get_json()["draft"]
+ url = f"/api/sessions/{session_id}/messages"
+ first = client.post(url, headers=headers, json={"retry_for": notice["id"], "text": "replay original tools"})
+ duplicate = client.post(url, headers=headers, json={"retry_for": notice["id"]})
+ assert first.status_code == duplicate.status_code == 201
+ assert first.get_json()["id"] == duplicate.get_json()["id"]
+ assert first.get_json()["draft"] == draft
+ assert first.get_json()["draft_advanced"] is False
+ assert starts == [(session_id, "continue")]
+ with engine.connect() as conn:
+ reloaded = messages_service.get_message(conn, notice["id"])
+ runs = conn.execute(select(agent_runs.c.id, agent_runs.c.status)).all()
+ assert reloaded["content"]["failure_retry"]["state"] == "accepted"
+ assert runs == [(notice["metadata"]["run_id"], "failed")]
+
+
[email protected]("change", ["newer", "delayed", "pending", "unlinked", "other_session"])
+def test_harness_notice_keeps_retry_boundary_guards(isolated_state, tmp_path, change):
+ """MESSAGE-DELIVERY-320: no cross-Session, inferred, busy, or stale retry."""
+ from vibe import ui_server
+
+ _source_session, notice, _turn = _harness_restart_notice(
+ tmp_path,
+ target={"other_session": "other", "delayed": "newer"}.get(change, "same"),
+ linked=change != "unlinked",
+ )
+ assert notice["metadata"]["replayed"] is True
+ if change in {"unlinked", "other_session"}:
+ assert not notice["metadata"].get("turn_id")
+ with create_sqlite_engine().begin() as conn:
+ if change == "newer":
+ seed_failed_notice(conn, session_id=notice["session_id"], scope_id=notice["scope_id"])
+ elif change == "pending":
+ message_deliveries.insert_delivery(
+ conn, delivery_id=message_deliveries.new_delivery_id(),
+ session_id=notice["session_id"], priority="p3", state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=notice["scope_id"], session_id=notice["session_id"], platform="avibe",
+ author="user", source="user", text="另一个任务",
+ ),
+ dispatch_text="另一个任务",
+ )
+ client = ui_server.app.test_client()
+ with patch("vibe.internal_client.dispatch_async", AsyncMock()) as dispatch:
+ response = client.post(
+ f"/api/sessions/{notice['session_id']}/messages", headers=csrf_headers(client),
+ json={"retry_for": notice["id"]},
+ )
+ assert response.status_code == 409
+ dispatch.assert_not_awaited()
diff --git a/ui/src/components/workbench/FailureRetry.test.tsx b/ui/src/components/workbench/FailureRetry.test.tsx
index 926b1f4c8..0588352d8 100644
--- a/ui/src/components/workbench/FailureRetry.test.tsx
+++ b/ui/src/components/workbench/FailureRetry.test.tsx
@@ -31,11 +31,14 @@ function mount(props: Partial<Parameters<typeof FailureRetry>[0]> = {}) {
}
describe('failed-turn retry action', () => {
- it('offers retry for a restart interruption with authoritative Turn metadata', async () => {
+ it.each([
+ '⚠️ 本轮执行被中断——Avibe 服务在它运行期间重启。如果这项工作仍然需要完成,请重新发送请求。',
+ '[Avibe Harness] 一项后台任务已随 Avibe 重启停止。如需继续,请发送“继续”给 Agent。',
+ ])('MESSAGE-DELIVERY-320: offers retry for a linked restart notice: %s', async (text) => {
const onRetry = mount({
message: {
...notice,
- text: '⚠️ 本轮执行被中断——Avibe 服务在它运行期间重启。如果这项工作仍然需要完成,请重新发送请求。',
+ text,
metadata: {
event: 'backend_failure', backend: 'codex',
failure_id: 'turn:interrupted-turn', turn_id: 'interrupted-turn', detached: false,
@@ -106,6 +109,13 @@ describe('failed-turn retry action', () => {
{ message: { ...notice, metadata: { ...notice.metadata, detached: true } } },
{ message: { ...notice, metadata: { event: 'backend_failure' } } },
{ message: { ...notice, text: 'Avibe 服务重启,本轮执行被中断', metadata: {} } },
+ {
+ message: {
+ ...notice,
+ text: '[Avibe Harness] 一项后台任务已随 Avibe 重启停止。如需继续,请发送“继续”给 Agent。',
+ metadata: { event: 'backend_failure', failure_id: 'turn:unbound', replayed: true },
+ },
+ },
{ message: { ...notice, author: 'user' } as WorkbenchMessage },
])('does not offer an ineligible action', (props) => {
mount(props);