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(claude): preserve missing-session recovery and explicit input retry (#1974)
Call Whitee73698b72bf1
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.pyindex a92e0b38a..e5f1d7a39 100644--- a/core/agent_auth_service.py+++ b/core/agent_auth_service.py@@ -237,9 +237,21 @@ def classify_auth_error(backend: str, error_text: str) -> bool:if not text:return False+ # Status evidence must be distinct from UUIDs, paths, ports, and counts.+ # Keep the native CLI/HTTP and serialized response shapes we consume.+ http_401 = text == "401" or bool(+ re.search(+ r"""(?<![\w/.-])(?:http(?:/\d(?:\.\d)?|error)?"""+ r"""|status(?:[_ ]?code)?|(?:api )?error(?: code)?"""+ r"""|failed to (?:send message|start async prompt))"""+ r"""["']?\s*[:=]?\s*["']?401(?=$|[\s,;:)}\]"'])""",+ text,+ )+ or re.search(r"(?<![\w/.-])401\s+client error\b", text)+ )+if backend == "codex":needles = (- "401","unauthorized","not logged in","login required",@@ -247,11 +259,10 @@ def classify_auth_error(backend: str, error_text: str) -> bool:"oauth","token data is not available",)- return any(needle in text for needle in needles)+ return http_401 or any(needle in text for needle in needles)if backend == "claude":needles = (- "401","unauthorized","oauth","re-auth",@@ -260,19 +271,16 @@ def classify_auth_error(backend: str, error_text: str) -> bool:"login","logged out",)- return any(needle in text for needle in needles)+ return http_401 or any(needle in text for needle in needles)if backend == "opencode":needles = (- "401","unauthorized","authentication","credential","api key",- "failed to send message: 401",- "failed to start async prompt: 401",)- return any(needle in text for needle in needles)+ return http_401 or any(needle in text for needle in needles)return Falsediff --git a/core/native_dispatch_phase.py b/core/native_dispatch_phase.pyindex 134d042cb..22f7902f1 100644--- a/core/native_dispatch_phase.py+++ b/core/native_dispatch_phase.py@@ -71,3 +71,23 @@ def mark_backend_dispatch_attempted(context: Any) -> None:"""Record the boundary immediately before an adapter's native write."""set_dispatch_phase(context, DISPATCH_PHASE_ATTEMPTING)+++def mark_prewrite_recovery_required(context: Any, reason: str) -> None:+ """Retain a definitive startup failure for an explicit user retry."""++ if backend_dispatch_attempted(context) is not False:+ return+ evidence = set_dispatch_phase(context, DISPATCH_PHASE_PREWRITE)+ evidence["failure"] = {"reason": reason, "requires_explicit_retry": True}+++def prewrite_failure_evidence(context: Any) -> dict[str, Any]:+ """Copy adapter-owned failure evidence into the durable start receipt."""++ if backend_dispatch_attempted(context) is not False:+ return {}+ payload = getattr(context, "platform_specific", None) or {}+ evidence = payload.get(DISPATCH_EVIDENCE_KEY)+ failure = evidence.get("failure") if isinstance(evidence, dict) else None+ return dict(failure) if isinstance(failure, dict) else {}diff --git a/core/session_turns.py b/core/session_turns.pyindex 8b1210541..1cbdff799 100644--- a/core/session_turns.py+++ b/core/session_turns.py@@ -38,6 +38,7 @@ from core.message_context import (from core.native_dispatch_phase import (backend_dispatch_attempted,mark_prewrite_user_stop,+ prewrite_failure_evidence,)from core.run_settlement import (NON_COMPLETING_TURN_SETTLEMENTS,@@ -1890,6 +1891,7 @@ class SessionTurnManager:deliveries: list[dict[str, Any]],dispatch_text: str,attempt_id: str | None = None,+ explicit_retry: bool = False,) -> dict[str, Any] | None:"""Claim a Delivery batch and all linked Agent Runs atomically."""@@ -1908,6 +1910,11 @@ class SessionTurnManager:conn, session_id, str(delivery["id"]), reason=reason)return None+ if not explicit_retry and any(+ delivery_store.requires_explicit_start_retry(delivery)+ for delivery in deliveries+ ):+ return Nonebinding = conn.execute(select(agent_sessions.c.agent_backend,@@ -3175,6 +3182,7 @@ class SessionTurnManager:backend=backend,deliveries=delivery_rows,dispatch_text=dispatch_text,+ explicit_retry=True,)if claimed is None:turn_id = None@@ -5072,6 +5080,7 @@ class SessionTurnManager:turn_id: str,*,outcome: str,+ failure_evidence: dict[str, Any] | None = None,) -> dict[str, Any]:"""Settle definitive no-write evidence at the terminal chokepoint."""return self._terminalize_durable_turn(@@ -5079,7 +5088,7 @@ class SessionTurnManager:"not_written",settled_by=outcome,evidence_kind="definitive_prewrite_failure",- evidence={"reason": outcome},+ evidence={"reason": outcome, **(failure_evidence or {})},)def _reconcile_durable_runner_release(@@ -5093,6 +5102,7 @@ class SessionTurnManager:settled_by: str | None,terminal_is_error: bool,cancel_defers_queue_resume: bool = False,+ failure_evidence: dict[str, Any] | None = None,) -> dict[str, Any]:"""Contain post-native ownership writes so runner cleanup always finishes."""@@ -5172,6 +5182,7 @@ class SessionTurnManager:return self._settle_durable_prewrite_failure(turn_id,outcome=SETTLED_BY_NO_TERMINAL_RESULT,+ failure_evidence=failure_evidence,)if settled_by is not None:return self._terminalize_durable_turn(@@ -7451,6 +7462,7 @@ class SessionTurnManager:settled_by=settled_by,terminal_is_error=terminal_is_error,cancel_defers_queue_resume=cancel_defers_queue_resume,+ failure_evidence=prewrite_failure_evidence(context),)# Only definitive pre-write failure may synthesize an empty# terminal result. Once native work may have produced output, adiff --git a/docs/plans/claude-session-recovery-errors.md b/docs/plans/claude-session-recovery-errors.mdnew file mode 100644index 000000000..05550555b--- /dev/null+++ b/docs/plans/claude-session-recovery-errors.md@@ -0,0 +1,75 @@+# Claude session recovery errors++## Problem++A persisted Claude session can outlive its native transcript. Resuming it+fails before a model request is sent. The shared authentication classifier+currently matches `401` anywhere in an error string, including inside a+session UUID, and incorrectly offers OAuth login. A pending Workbench input+can also be retried repeatedly after this permanent startup failure.++## Change contract++- Classify HTTP authentication failures from actual status evidence, not+ digits embedded in identifiers, paths, or unrelated numeric values.+ Preserve supported real authentication-error shapes across all backends.+- Keep Claude's missing-native-session error distinct from authentication,+ transport, and model-supply failures through its user-facing error path.+- Preserve the Avibe session, native-session binding, conversation history,+ working directory, and unsent user input. Never silently create an empty+ replacement session or replay a failed input in an unbounded loop.+- Reuse existing terminal-turn and queued-input ownership. Investigate the+ retry path on current master before changing it; add no parallel queue or+ persistent lifecycle unless the existing model cannot express the outcome.+- User-facing recovery guidance is localized and explains how to resume in+ the original location or explicitly start a new conversation.+- No automatic OAuth reset, model switch, runtime restart, or live data+ mutation belongs to this code change.++## Boundaries and ownership++The shared authentication classifier produces the recovery decision;+backend error handling consumes it and owns the concrete failure kind.+The session handler produces the missing-transcript error. Existing turn+settlement and Workbench queue services own failure completion and pending+input. Model Hub routing and engine behavior remain independently diagnosed+by the orchestrator and are outside this implementation lane.++## Validation++- Reproduce a missing-session error containing a UUID with `4016`, and+ verify a variant without those digits has the same classification.+- Cover identifier/path/number false positives and genuine HTTP 401 and+ authentication messages for each existing backend.+- Exercise the consuming Claude error path and durable user-visible+ notification, preserving session binding and input ownership.+- Reproduce any queue change through its real service/controller boundary+ with test-owned state, including unchanged state and explicit retry.+- Run focused tests and changed-file Ruff, then exact-head Codex review+ and the repository's complete required CI gates.++## Implementation++- The authentication classifier recognizes contextual HTTP/CLI status forms+ while retaining backend-specific authentication messages.+- Claude's typed missing-session failure bypasses OAuth recovery. Its localized+ notification includes the existing `MessageOutput` Turn provenance so the+ failed-notice Retry action can resolve the original input.+- Before native write, Claude records `failure.reason=native_session_not_found`+ and `failure.requires_explicit_retry=true` in the shared dispatch evidence.+ The existing terminal owner copies this evidence to the `not_written` start+ receipt in each affected Delivery's history. No schema or lifecycle is added.+- Automatic start claims respect that receipt until the existing failed-notice+ Retry action or explicit Send Now authorizes a new attempt. Input snapshots+ remain unchanged. Other startup failures and unknown acceptance keep their+ existing policy; a repeated missing-session failure requires another explicit+ retry.+- MESSAGE-DELIVERY-029 covers Claude's consuming error path, durable input+ retention, periodic/restart recovery, and both explicit retry paths.++## Operational recovery++The orchestrator separately checks native transcript availability and live+model requests using supported Avibe APIs and CLI. Recovery must preserve+existing user data and distinguish reconstruction from an exact native+resume. Live operational results are not substituted for hermetic tests.diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 0f98414ca..5096c19f4 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -7,6 +7,7 @@ from typing import Any, Callable, Literal, Optionalfrom core.agent_auth_service import classify_auth_errorfrom core.backend_failure import backend_failure_notification_output, emit_backend_failure+from core.handlers.session_handler import ClaudeSessionNotFoundErrorfrom core.message_dispatcher import ActivityOutputDeliveryErrorfrom core.message_output import (HARNESS_RUN_ID_TRIGGER_KINDS,@@ -16,7 +17,7 @@ from core.message_output import (terminal_output_for,terminal_turn_output,)-from core.native_dispatch_phase import mark_backend_dispatch_attempted+from core.native_dispatch_phase import mark_backend_dispatch_attempted, mark_prewrite_recovery_requiredfrom core.processing_indicator import STOPPED_REACTION_EMOJIfrom core.reply_enhancer import strip_silent_blocksfrom core.runtime_activation import RuntimeActivationIdentity@@ -142,6 +143,13 @@ class ClaudeAgent(BaseAgent):def _format_error_notify(self, error: Exception, *, composite_key: str | None = None) -> str:"""Return the durable notify text for Claude terminal errors."""+ if isinstance(error, ClaudeSessionNotFoundError):+ detail = self._translate_error(+ "error.claudeSessionNotFound",+ sessionId=error.session_id,+ path=error.working_path,+ )+ return f"❌ {detail}"if is_claude_sdk_buffer_error(error):return f"❌ {self._translate_error('error.sessionConnectionLost')}"client = self.claude_sessions.get(composite_key) if composite_key else None@@ -255,6 +263,9 @@ class ClaudeAgent(BaseAgent):raiseexcept Exception as e:logger.error(f"Error processing Claude message: {e}", exc_info=True)+ missing_session = isinstance(e, ClaudeSessionNotFoundError)+ if missing_session:+ mark_prewrite_recovery_required(context, "native_session_not_found")diagnostic = self._claude_error_diagnostic(runtime_session_key, e)# Classify BEFORE recording: ``record_model_hub_native_failure``# turns the pending native/hub attempt into a failed one, so a@@ -272,13 +283,17 @@ class ClaudeAgent(BaseAgent):await self._remove_ack_reaction(request)error_notify = self._format_error_notify(e, composite_key=runtime_session_key)try:- handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(- context,- "claude",- error_notify,- output=terminal_output_for(request),- terminal_error=diagnostic,- )+ # A typed local resume failure takes precedence over incidental+ # auth words in the working path or captured process diagnostic.+ handled = False+ if not missing_session:+ handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(+ context,+ "claude",+ error_notify,+ output=terminal_output_for(request),+ terminal_error=diagnostic,+ )if handled and client is not None and get_claude_client_returncode(client) is not None:# Auth recovery owns the visible settlement, but a query can# fail after the cached CLI has already exited. Retire that@@ -329,7 +344,7 @@ class ClaudeAgent(BaseAgent):context,"notify",error_notify,- metadata=notification.metadata,+ metadata=notification.provenance(context),native_message_id=notification.idempotency_key,)except Exception:diff --git a/storage/message_deliveries.py b/storage/message_deliveries.pyindex 790a7b3a6..6e364e19d 100644--- a/storage/message_deliveries.py+++ b/storage/message_deliveries.py@@ -355,6 +355,19 @@ def failure_retry_state(delivery: dict[str, Any]) -> str:return state+def requires_explicit_start_retry(delivery: dict[str, Any]) -> bool:+ """An unwritten permanent failure stays queued until its owner retries it."""+ for event in reversed(_history(delivery.get("delivery_history_json"))["events"]):+ if event.get("kind") == FAILURE_RETRY_HISTORY_KIND:+ return False+ if event.get("kind") == "start":+ return (+ event.get("outcome") == "not_written"+ and (event.get("receipt") or {}).get("requires_explicit_retry") is True+ )+ return False++def active_turn(conn: Connection, session_id: str) -> dict[str, Any] | None:return _one(conn,diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yamlindex 52c269303..4dac397e3 100644--- a/tests/scenarios/message_delivery/catalog.yaml+++ b/tests/scenarios/message_delivery/catalog.yaml@@ -182,6 +182,12 @@ scenarios:kind: concurrencylayer: contracttest: tests/test_backend_failure_retry.py::test_failure_retry_queue_drain_rechecks_the_boundary+ - id: MESSAGE-DELIVERY-029+ name: Missing Claude transcript retains unwritten input until explicit recovery+ status: covered+ kind: recovery+ layer: contract+ test: tests/test_claude_session_recovery.py::test_missing_session_queue_waits_for_explicit_recovery- id: MESSAGE-DELIVERY-101name: Unresolved fallback-capable delivery fences only later FIFO submissionsstatus: covereddiff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.pyindex a3ce42eff..499c72a98 100644--- a/tests/test_agent_auth_service.py+++ b/tests/test_agent_auth_service.py@@ -2377,6 +2377,65 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsynclass ClassifyAuthErrorTests(unittest.TestCase):+ def test_status_evidence_requires_reset_for_every_backend(self):+ diagnostics = (+ "401",+ "HTTP 401",+ "HTTP/1.1 401",+ "HTTP/2 401",+ "HTTPError: 401",+ "unexpected status 401",+ "status code: 401",+ 'response {"status_code": 401}',+ 'response {"statusCode":401}',+ 'response {"status":"401"}',+ "API Error: 401",+ "Error code: 401",+ "401 Client Error for url: https://example.test",+ "Failed to send message: 401",+ "Failed to start async prompt: 401",+ )+ for backend in ("claude", "codex", "opencode"):+ for diagnostic in diagnostics:+ with self.subTest(backend=backend, diagnostic=diagnostic):+ self.assertTrue(classify_auth_error(backend, diagnostic))++ def test_identifiers_paths_and_numbers_are_not_http_statuses(self):+ diagnostics = (+ "Claude Code session not found in current working directory: "+ "11111111-2222-4016-8444-555555555555 (/Users/example/ai-work)",+ "Claude Code session not found in current working directory: "+ "11111111-2222-5016-8444-555555555555 (/Users/example/ai-work)",+ "session job-401-missing could not resume",+ "file /tmp/401/session.jsonl not found",+ "file /tmp/error:401/session.jsonl not found",+ "connect failed at http://localhost:401",+ "processed 401 records before failure",+ "request_id=401",+ "request_id=ab401cd",+ "exit code 1401",+ "API Error: 4016",+ "status: 401.5",+ "status: 401-session",+ "temporary network timeout",+ )+ for backend in ("claude", "codex", "opencode"):+ for diagnostic in diagnostics:+ with self.subTest(backend=backend, diagnostic=diagnostic):+ self.assertFalse(classify_auth_error(backend, diagnostic))++ def test_auth_messages_without_http_status_remain_supported(self):+ diagnostics = {+ "claude": ("OAuth token expired", "Please login", "logged out"),+ "codex": ("not logged in", "login required", "authentication failed"),+ "opencode": ("missing provider credential", "invalid api key", "authentication failed"),+ }+ for backend, messages in diagnostics.items():+ for diagnostic in messages:+ with self.subTest(backend=backend, diagnostic=diagnostic):+ self.assertTrue(classify_auth_error(backend, diagnostic))+ self.assertFalse(classify_auth_error("unknown", "HTTP 401"))+def test_codex_401_requires_reset(self):self.assertTrue(classify_auth_error("codex", "unexpected status 401 Unauthorized"))diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.pyindex 91bde8a53..2c19b9867 100644--- a/tests/test_claude_cli_path.py+++ b/tests/test_claude_cli_path.py@@ -1890,8 +1890,11 @@ def test_session_handler_expands_tilde_in_claude_cli_path(monkeypatch, tmp_path:assert captured["options"].cli_path == str(Path("~/bin/claude").expanduser())-def test_session_handler_surfaces_claude_missing_resume_session(monkeypatch, tmp_path: Path) -> None:- stale_session_id = "11111111-1111-1111-1111-111111111111"+ "stale_session_id",+ ["11111111-2222-4016-8444-555555555555", "11111111-2222-5016-8444-555555555555"],+)+def test_session_handler_surfaces_claude_missing_resume_session(monkeypatch, tmp_path: Path, stale_session_id) -> None:captured: dict[str, Any] = {}class _StaleSessions:@@ -1932,6 +1935,8 @@ def test_session_handler_surfaces_claude_missing_resume_session(monkeypatch, tmpassert exc_info.value.working_path == str(tmp_path)assert stale_session_id in exc_info.value.stderrassert captured["options"].resume == stale_session_id+ assert controller.settings_manager.sessions.get_claude_session_id("test::C123", "slack_C123") == stale_session_id+ assert handler.claude_sessions == {}def test_claude_startup_failure_is_recorded_before_scope_retirement(diff --git a/tests/test_claude_session_recovery.py b/tests/test_claude_session_recovery.pynew file mode 100644index 000000000..6aee6c5e5--- /dev/null+++ b/tests/test_claude_session_recovery.py@@ -0,0 +1,256 @@+"""Missing native transcripts preserve durable input until explicit recovery."""++from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+from sqlalchemy import select, update++from core.handlers.session_handler import ClaudeSessionNotFoundError, SessionHandler+from core.native_dispatch_phase import (+ DISPATCH_PHASE_ATTEMPTING,+ DISPATCH_PHASE_PREWRITE,+ backend_dispatch_attempted,+ mark_prewrite_recovery_required,+ prewrite_failure_evidence,+ set_dispatch_phase,+)+from core.run_settlement import SETTLED_BY_TERMINAL_RESULT+from core.services.dispatch import TurnDispatchOutcome+from core.session_turns import DeliveryRequest, SessionTurnManager+from modules.agents.base import AgentRequest+from modules.agents.claude_agent import ClaudeAgent+from storage import message_deliveries as deliveries, messages_service+from storage.models import agent_sessions, session_turns+from tests.backend_failure_retry_helpers import reserve_failure_retry+from tests.test_claude_agent_sessions import _StubController+from tests.test_session_delivery_fsm import _context, _fsm_schema_template, managers # noqa: F401+from vibe.i18n import t+++NATIVE_ID = "11111111-2222-4016-8444-555555555555"+++def _agent_fixture(monkeypatch, engine, *, language, working_path):+ controller = _StubController()+ controller.config.language = language+ controller.stored_session_mappings = {}+ controller.im_client.send_message = AsyncMock()+ controller.im_client.formatter.format_error = lambda text: f"❌ {text}"+ handler = SessionHandler(controller)+ handler.get_or_create_claude_session = AsyncMock(+ side_effect=ClaudeSessionNotFoundError(NATIVE_ID, working_path)+ )+ handler.cleanup_session = AsyncMock()+ controller.session_handler = handler+ controller.emit_agent_message = AsyncMock()+ # Force the auth branch to accept if called: typed local failure must win+ # even with "login"/"oauth" in a cwd, independently of the text classifier.+ controller.agent_auth_service.maybe_emit_auth_recovery_message.return_value = True+ controller.agent_service = SimpleNamespace(release_runtime_turn=lambda _context: None)+ agent = ClaudeAgent(controller)+ agent._delete_ack = AsyncMock()+ agent.record_model_hub_native_failure = AsyncMock()+ monkeypatch.setattr("core.message_mirror.get_cached_sqlite_engine", lambda: engine)+ return agent, controller+++def _request(context, text, working_path):+ return AgentRequest(+ context=context,+ message=text,+ user_message=text,+ working_path=working_path,+ base_session_id="ses_fsm",+ composite_session_id=f"ses_fsm:{working_path}",+ session_key="avibe::ses_fsm",+ )++[email protected]("language", ["en", "zh"])+async def test_missing_session_delivers_localized_notice_and_terminal_failure(+ managers, monkeypatch, tmp_path, language+):+ _manager, _restarted, engine, _other, _starts = managers+ working_path = str(tmp_path / "oauth-login-401" / "原目录")+ with engine.begin() as conn:+ conn.execute(+ update(agent_sessions).where(agent_sessions.c.id == "ses_fsm").values(+ agent_backend="claude", native_session_id=NATIVE_ID, workdir=working_path+ )+ )+ agent, controller = _agent_fixture(monkeypatch, engine, language=language, working_path=working_path)+ context = _context()+ context.platform_specific["turn_token"] = "trn_missing"+ set_dispatch_phase(context, DISPATCH_PHASE_PREWRITE)+ request = _request(context, "请继续,保留这段输入", working_path)++ await agent.handle_message(request)++ controller.agent_auth_service.maybe_emit_auth_recovery_message.assert_not_awaited()+ controller.session_handler.cleanup_session.assert_not_awaited()+ assert agent._pending_requests == {}+ assert controller.receiver_tasks == {}+ assert backend_dispatch_attempted(context) is False+ assert request.message == "请继续,保留这段输入"+ expected = f"❌ {t('error.claudeSessionNotFound', language, sessionId=NATIVE_ID, path=working_path)}"+ controller.im_client.send_message.assert_awaited_once_with(context, expected)+ terminal = controller.emit_agent_message.await_args+ assert terminal.args == (context, "result", "")+ assert terminal.kwargs["is_error"] is True+ assert terminal.kwargs["level"] == "silent"+ assert terminal.kwargs["output"].completes_turn is True+ assert terminal.kwargs["output"].settles_run is True+ assert NATIVE_ID in terminal.kwargs["terminal_error"]+ with engine.connect() as conn:+ notices = messages_service.list_session_messages(conn, session_id="ses_fsm")["messages"]+ binding = conn.execute(select(agent_sessions).where(agent_sessions.c.id == "ses_fsm")).mappings().one()+ assert len(notices) == 1+ assert notices[0]["text"] == expected+ assert notices[0]["type"] == "notify"+ assert notices[0]["metadata"]["event"] == "backend_failure"+ assert notices[0]["metadata"]["turn_id"] == "trn_missing"+ assert binding["native_session_id"] == NATIVE_ID+ assert binding["workdir"] == working_path++[email protected]("retry", ["failure_notice", "send_now", "still_missing"])+async def test_missing_session_queue_waits_for_explicit_recovery(+ managers, monkeypatch, tmp_path, retry+):+ """MESSAGE-DELIVERY-029: failed startup -> retained input -> explicit retry."""+ manager, restarted, engine, _other, starts = managers+ working_path = str(tmp_path / "原目录")+ with engine.begin() as conn:+ conn.execute(+ update(agent_sessions).where(agent_sessions.c.id == "ses_fsm").values(+ agent_backend="claude", native_session_id=NATIVE_ID, workdir=working_path+ )+ )+ messages_service.append(+ conn, session_id="ses_fsm", scope_id=None, platform="avibe",+ author="agent", source="agent", message_type="result", text="历史回复",+ )+ agent, controller = _agent_fixture(monkeypatch, engine, language="zh", working_path=working_path)+ manager._run = SessionTurnManager._run.__get__(manager, SessionTurnManager)+ manager.controller.emit_agent_message = AsyncMock()++ async def dispatch(_controller, context, text, **_kwargs):+ # The shared dispatch phase is also shared by the adapter's context copy.+ evidence = set_dispatch_phase(context, DISPATCH_PHASE_PREWRITE)+ copied = _context()+ copied.platform_specific = dict(context.platform_specific)+ assert copied.platform_specific["agent_dispatch_evidence"] is evidence+ await agent.handle_message(_request(copied, text, working_path))+ return TurnDispatchOutcome(None, SETTLED_BY_TERMINAL_RESULT, backend_dispatch_attempted(context))++ monkeypatch.setattr("core.session_turns.dispatch_turn_with_outcome", dispatch)+ admitted = await manager.deliver(+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="请继续原来的工作"),+ context=_context(),+ )+ await manager.in_flight["ses_fsm"].task+ with engine.connect() as conn:+ retained = deliveries.get_delivery(conn, admitted.delivery_id)+ turn = deliveries.get_turn(conn, admitted.turn_id)+ notices = messages_service.list_session_messages(conn, session_id="ses_fsm")["messages"]+ assert retained["state"] == "queued"+ assert retained["message_id"] is None+ assert retained["current_attempt_id"] is None+ assert turn["state"] == "terminal"+ assert turn["terminal_outcome"] == "not_written"+ assert turn["start_receipt_outcome"] == "not_written"+ notice = next(row for row in notices if row["type"] == "notify")+ assert notice["metadata"]["turn_id"] == admitted.turn_id+ assert any(row["text"] == "历史回复" for row in notices)++ # Repeated timer drains and a new manager after restart cannot replay.+ for _ in range(3):+ assert not await manager.drain_delivery_queue("ses_fsm")+ await restarted.recover_durable_delivery_state("ses_fsm")+ with engine.connect() as conn:+ unchanged = deliveries.get_delivery(conn, admitted.delivery_id)+ turns = list(conn.execute(select(session_turns.c.id)))+ assert unchanged == retained+ assert len(turns) == 1+ assert starts == []+ controller.session_handler.get_or_create_claude_session.assert_awaited_once()++ # The same durable input and snapshot remain owned by the retry.+ if retry == "still_missing":+ result = await manager.send_now("ses_fsm", expected_delivery_id=admitted.delivery_id)+ assert result["status"] == "claimed"+ await manager.in_flight["ses_fsm"].task+ assert controller.session_handler.get_or_create_claude_session.await_count == 2+ for _ in range(3):+ await restarted.recover_durable_delivery_state("ses_fsm")+ with engine.connect() as conn:+ retried = deliveries.get_delivery(conn, admitted.delivery_id)+ assert retried["snapshot_json"] == retained["snapshot_json"]+ assert retried["state"] == "queued"+ assert starts == []+ return+ elif retry == "failure_notice":+ with engine.begin() as conn:+ reserved = reserve_failure_retry(conn, notice)+ assert reserved["id"] == admitted.delivery_id+ result = await restarted.deliver(+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="ignored", delivery_id=reserved["id"]),+ context=_context(),+ )+ assert result.state == "claimed"+ else:+ result = await restarted.send_now("ses_fsm", expected_delivery_id=admitted.delivery_id)+ assert result["status"] == "claimed"+ assert len(starts) == 1+ assert "请继续原来的工作" in starts[0][1]+ with engine.connect() as conn:+ retried = deliveries.get_delivery(conn, admitted.delivery_id)+ assert retried["snapshot_json"] == retained["snapshot_json"]+ assert retried["turn_id"] != admitted.turn_id++[email protected]("phase", [None, DISPATCH_PHASE_ATTEMPTING])+def test_unknown_or_attempted_native_input_cannot_require_prewrite_retry(phase):+ context = _context()+ if phase is not None:+ set_dispatch_phase(context, phase)+ before = dict(context.platform_specific)+ mark_prewrite_recovery_required(context, "native_session_not_found")+ assert prewrite_failure_evidence(context) == {}+ assert context.platform_specific == before+ assert backend_dispatch_attempted(context) is (None if phase is None else True)+++async def test_query_failure_does_not_mark_input_as_unwritten(managers, monkeypatch, tmp_path):+ _manager, _restarted, engine, _other, _starts = managers+ agent, controller = _agent_fixture(monkeypatch, engine, language="en", working_path=str(tmp_path))+ client = SimpleNamespace(+ query=AsyncMock(side_effect=ClaudeSessionNotFoundError(NATIVE_ID, str(tmp_path))),+ )+ controller.session_handler.get_or_create_claude_session = AsyncMock(return_value=client)+ agent._prepare_message_with_files = lambda request: request.message+ context = _context()+ set_dispatch_phase(context, DISPATCH_PHASE_PREWRITE)+ await agent.handle_message(_request(context, "native may have received this", str(tmp_path)))+ client.query.assert_awaited_once()+ assert backend_dispatch_attempted(context) is True+ assert prewrite_failure_evidence(context) == {}+ assert "failure" not in context.platform_specific["agent_dispatch_evidence"]+++async def test_ordinary_queue_and_transient_prewrite_failure_still_drain(managers):+ manager, restarted, engine, _other, starts = managers+ initial = await manager.deliver(+ DeliveryRequest(session_id="ses_fsm", priority="p3", content="ordinary input"),+ context=_context(),+ )+ assert len(starts) == 1+ manager._settle_durable_prewrite_failure(initial.turn_id, outcome="transient_start_failure")+ with engine.connect() as conn:+ retained = deliveries.get_delivery(conn, initial.delivery_id)+ assert retained["state"] == "queued"+ assert not deliveries.requires_explicit_start_retry(retained)+ await restarted.recover_durable_delivery_state("ses_fsm")+ assert len(starts) == 2+ assert starts[1][1] == starts[0][1]diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 5a5035659..3b506711f 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -407,7 +407,7 @@"claudeProcessExitCode": "exit code {code}","claudeProcessTerminated": "Claude Code process terminated ({reason}); the session was reset. Please try your message again.","claudeCredentialTypeInvalid": "Choose either API key or auth token for the Claude Code credential.",- "claudeSessionNotFound": "Claude Code could not find the historical session `{sessionId}` in the current working directory:\n`{path}`\n\nClaude Code sessions are scoped to a working directory. This usually means the conversation was resumed after switching workdirs, or the local Claude Code session data changed. Switch back to the original working directory to continue that session, or start a new Claude Code session from the current directory.",+ "claudeSessionNotFound": "Claude Code could not find the historical session `{sessionId}` in the current working directory:\n`{path}`\n\nClaude Code sessions are scoped to a working directory. This usually means the conversation was resumed after switching workdirs, or the local Claude Code session data changed. Restore the original session in its original working directory, then explicitly retry the pending input; or start a new conversation from the current directory.","sessionGeneric": "An error occurred: {error}","codexPromptRefreshUnavailable": "Codex could not confirm that it can safely refresh Avibe's instructions for this existing session. Check or update Codex, then retry this turn.","opencodeModelHubOverlayRequired": "OpenCode is still preparing for Gateway mode. Retry in a moment.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 3412a69cb..f33f79578 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -407,7 +407,7 @@"claudeProcessExitCode": "退出码 {code}","claudeProcessTerminated": "Claude Code 进程已终止({reason});会话已重置,请重试。","claudeCredentialTypeInvalid": "Claude Code 凭据类型只能选择 API Key 或 Auth Token。",- "claudeSessionNotFound": "Claude Code 在当前工作目录下找不到历史会话 `{sessionId}`:\n`{path}`\n\nClaude Code 的会话和工作目录相关。通常是恢复会话后切换了工作目录,或本地 Claude Code 会话数据发生变化。请切回原来的工作目录继续该会话,或在当前目录开始一个新的 Claude Code 会话。",+ "claudeSessionNotFound": "Claude Code 在当前工作目录下找不到历史会话 `{sessionId}`:\n`{path}`\n\nClaude Code 的会话和工作目录相关。通常是恢复会话后切换了工作目录,或本地 Claude Code 会话数据发生变化。请在原工作目录恢复原会话,再手动重试待发送的输入;也可以在当前目录开始一个新会话。","sessionGeneric": "发生错误:{error}","codexPromptRefreshUnavailable": "Codex 无法确认能否安全刷新此现有会话的 Avibe 指令。请检查或升级 Codex 后重试本回合。","opencodeModelHubOverlayRequired": "OpenCode 仍在准备 Gateway 模式,请稍后重试。",