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(claude): stop reading CLI stderr and signal exits as auth failures (#2877)

Call Whitefed069a3b2e9
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 2d80a8ac5..952d7c75c 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -25,7 +25,7 @@ from modules.agents.claude_process_reaper import (
AVIBE_CLAUDE_SESSION_OWNER,
get_claude_client_pid,
get_claude_client_returncode,
- get_claude_client_stderr_tail,
+ claude_stderr_tail_section,
claude_process_exit_reason,
claude_process_exit_reason_i18n,
register_claude_owned_process,
@@ -471,8 +471,7 @@ class SessionHandler(BaseHandler):
return False
reason = claude_process_exit_reason(returncode)
- stderr_tail = get_claude_client_stderr_tail(client)
- diagnostic = f"\nClaude stderr tail:\n{stderr_tail}" if stderr_tail else ""
+ diagnostic = claude_stderr_tail_section(client)
logger.warning(
"Recreating cached Claude SDK client for %s because its process terminated (%s)%s",
composite_key,
@@ -3065,10 +3064,8 @@ class SessionHandler(BaseHandler):
setattr(client, "_vibe_resource_failure_checked", True)
if resource_failure is not None:
diagnostic = f"{diagnostic}\nResource diagnosis: {resource_failure.message}"
- stderr_tail = get_claude_client_stderr_tail(client)
- if stderr_tail:
- diagnostic = f"{diagnostic}\nClaude stderr tail:\n{stderr_tail}"
- return diagnostic
+ # Last, so auth classification can leave the CLI's stderr out.
+ return f"{diagnostic}{claude_stderr_tail_section(client)}"
def capture_session_id(
self,
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index 2a925d414..86592a04e 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -49,7 +49,9 @@ from core.session_activities import SessionActivity, activity_completion_output
from modules.claude_sdk_compat import TextBlock, ToolUseBlock, is_claude_sdk_buffer_error
from modules.agents.claude_process_reaper import (
AVIBE_CLAUDE_SESSION_OWNER,
+ claude_diagnostic_without_stderr,
claude_process_exit_reason_i18n,
+ claude_process_exit_signal,
get_claude_client_returncode,
register_claude_owned_process,
)
@@ -778,10 +780,10 @@ class ClaudeAgent(BaseAgent):
# over incidental auth words in a path, model id, or diagnostic.
handled = False
if not missing_session and not input_not_sent and not hub_refusal:
- handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(
+ handled = await self._offer_auth_recovery(
context,
- "claude",
error_notify,
+ client=client,
output=terminal_output_for(request),
terminal_error=diagnostic,
)
@@ -859,6 +861,43 @@ class ClaudeAgent(BaseAgent):
finally:
await self._delete_ack(context, request)
+ async def _offer_auth_recovery(
+ self,
+ context: MessageContext,
+ error_notify: str,
+ *,
+ client,
+ output,
+ terminal_error: str,
+ ) -> bool:
+ """Offer re-login for a failed Claude call that can be an auth failure.
+
+ A CLI that a signal ended (the OOM killer, a service stop) was
+ terminated, and that is the failure's cause whatever its diagnostic
+ says.
+
+ The CLI's stderr is never auth evidence. The CLI reports an auth
+ failure as frames: an Assistant message whose ``error`` is
+ ``authentication_failed``, then an ``is_error`` Result, and those
+ reach recovery on their own path. Stderr carries its notices, such as
+ one naming the claude.ai login at every start when an API key
+ outranks it, so reading it for auth words sent ordinary crashes to
+ OAuth. The diagnostic keeps stderr for the user; only this check
+ leaves it out.
+ """
+ if claude_process_exit_signal(get_claude_client_returncode(client)) is not None:
+ return False
+ evidence = claude_diagnostic_without_stderr(str(terminal_error or ""))
+ if not classify_auth_error("claude", f"{error_notify}\n{evidence}"):
+ return False
+ return await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(
+ context,
+ "claude",
+ error_notify,
+ output=output,
+ terminal_error=terminal_error,
+ )
+
def _teardown_is_intentional(self, composite_key: str, error: Exception, *, client=None) -> bool:
"""Did the service kill this Claude process itself?
@@ -3306,10 +3345,10 @@ class ClaudeAgent(BaseAgent):
)
if not intentional_teardown:
await self.record_model_hub_native_failure(failure_context, diagnostic)
- auth_handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(
+ auth_handled = await self._offer_auth_recovery(
context,
- "claude",
error_notify,
+ client=client,
output=terminal_output_for(pending_request),
terminal_error=diagnostic,
)
@@ -3542,6 +3581,26 @@ class ClaudeAgent(BaseAgent):
error,
client=errored_client,
)
+ if pending_request is None:
+ # No Turn is in flight: the last one already settled, and an
+ # agent-initiated Turn would hold a FIFO entry. Nobody waits on
+ # this runtime, so its end is no news for the conversation and
+ # no evidence about a Model Hub source. Retire it quietly, as an
+ # idle EOF does; the next Turn starts a fresh process.
+ logger.warning(
+ "Claude runtime %s ended with no Turn in flight: %s",
+ composite_key,
+ diagnostic,
+ )
+ await self._cleanup_runtime_session(
+ composite_key,
+ current_receiver_task=asyncio.current_task(),
+ expected_client=errored_client,
+ preserve_pending_request_state=True,
+ reason="receiver_error_without_turn",
+ )
+ self._refresh_activity_provenance_barrier(composite_key)
+ return
error_notify = self._format_error_notify(
error,
composite_key=composite_key,
@@ -3553,10 +3612,10 @@ class ClaudeAgent(BaseAgent):
)
if not intentional_teardown:
await self.record_model_hub_native_failure(failure_context, diagnostic)
- handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(
+ handled = await self._offer_auth_recovery(
context,
- "claude",
error_notify,
+ client=errored_client,
output=terminal_output_for(pending_request),
terminal_error=diagnostic,
)
diff --git a/modules/agents/claude_process_reaper.py b/modules/agents/claude_process_reaper.py
index 7d14a9fd7..127920109 100644
--- a/modules/agents/claude_process_reaper.py
+++ b/modules/agents/claude_process_reaper.py
@@ -78,6 +78,22 @@ def get_claude_client_returncode(client: object | None) -> int | None:
return _process_returncode(get_claude_client_process(client))
+def claude_process_exit_signal(returncode: int | None) -> int | None:
+ """The signal that ended a Claude CLI, or None when it exited on its own.
+
+ Python reports a process a signal killed as ``-N``. A CLI that catches the
+ signal and exits itself follows the shell convention ``128 + N``, which is
+ how the Claude CLI ends on SIGTERM (exit code 143).
+ """
+ if returncode is None or isinstance(returncode, bool):
+ return None
+ if returncode < 0:
+ return -returncode
+ if 128 < returncode < 128 + signal.NSIG:
+ return returncode - 128
+ return None
+
+
def claude_process_exit_reason(returncode: int) -> str:
"""Format a subprocess exit code for logs and user-facing diagnostics."""
if returncode < 0:
@@ -110,6 +126,24 @@ def get_claude_client_stderr_tail(client: object | None) -> str:
return "\n".join(str(line).strip() for line in lines if str(line).strip())
+_CLAUDE_STDERR_TAIL_HEADER = "\nClaude stderr tail:\n"
+
+
+def claude_stderr_tail_section(client: object | None) -> str:
+ """The diagnostic section quoting what a Claude CLI wrote on stderr.
+
+ A diagnostic ends with it, so ``claude_diagnostic_without_stderr`` can
+ leave it out.
+ """
+ stderr_tail = get_claude_client_stderr_tail(client)
+ return f"{_CLAUDE_STDERR_TAIL_HEADER}{stderr_tail}" if stderr_tail else ""
+
+
+def claude_diagnostic_without_stderr(diagnostic: str) -> str:
+ """A Claude failure diagnostic without its stderr section."""
+ return diagnostic.partition(_CLAUDE_STDERR_TAIL_HEADER)[0]
+
+
def _released_lstart_reading(started: float) -> float:
"""The value a released build recorded for a process that started at ``started``.
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index d2b5a8c0a..19ecb4294 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -364,6 +364,26 @@ scenarios:
test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_web_claude_oauth_launches_the_persisted_cli_path
supporting_tests:
- tests/test_claude_cli_path.py::test_web_auth_uses_configured_claude_cli_path_without_session_handler
+ - id: AUTH-SETUP-912
+ name: A Claude CLI that ends mid-Turn is reported as terminated, and its stderr never sends the user to re-login
+ status: covered
+ kind: historical_regression
+ layer: scenario_backed_runtime
+ backend: claude
+ # The CLI's stderr notice that an API key outranks the claude.ai login sits in
+ # every such runtime's diagnostic and matched the auth classifier, so an OOM
+ # kill (-9), a service stop (-15, 143) or a crash (1) told the user to log in
+ # again. Stderr is no longer auth evidence, and a signal exit is a termination.
+ test: tests/test_claude_agent_sessions.py::ClaudeRuntimeFailureAuthClassificationTests::test_cli_exit_during_a_turn_reports_termination_without_relogin
+ - id: AUTH-SETUP-913
+ name: An auth failure the Claude CLI reports keeps the re-login prompt beside its stderr login notice
+ status: covered
+ kind: negative_path
+ layer: scenario_backed_runtime
+ backend: claude
+ # In SDK mode the CLI reports an auth failure as frames (an Assistant message
+ # with error authentication_failed, then an is_error Result), not on stderr.
+ test: tests/test_claude_agent_sessions.py::ClaudeRuntimeFailureAuthClassificationTests::test_auth_failure_the_cli_reports_keeps_the_relogin_prompt
- id: AUTH-SETUP-119
name: Runtime manual provider code reaches native persistence and controller-confirmed readiness
status: covered
diff --git a/tests/scenarios/auth_setup/observations.yaml b/tests/scenarios/auth_setup/observations.yaml
index 4493975bc..43b961c2d 100644
--- a/tests/scenarios/auth_setup/observations.yaml
+++ b/tests/scenarios/auth_setup/observations.yaml
@@ -21,3 +21,22 @@ observations:
required_updates:
- update the Claude auth-failure detector
- keep a regression test in the runtime-specific suite
+ - id: OBS-AUTH-003
+ source: manual_regression
+ related_scenarios:
+ - AUTH-SETUP-912
+ - AUTH-SETUP-913
+ summary: A Claude CLI killed by the OOM killer, stopped with the service, or crashed told the user to log in again.
+ previous_assumption: A Claude process failure whose diagnostic mentions the login is an auth failure.
+ observed_behavior: >-
+ With an API key or another auth source beside a claude.ai login, the CLI writes a
+ connectors notice naming that login to stderr at every start. The stderr tail joins
+ every failure diagnostic, so exit -9 and 143 matched the auth classifier, posted the
+ re-login prompt and retired the runtime as an auth failure while the login was fine.
+ A hermetic run of the bundled CLI against a 401 stub, and with no login, reported
+ both failures only as an Assistant frame with error authentication_failed and an
+ is_error Result; stderr stayed empty.
+ required_updates:
+ - keep CLI stderr out of Claude auth evidence while the diagnostic still shows it
+ - let a signal exit outrank auth words in the diagnostic
+ - keep the prompt for an auth failure the CLI reports itself
diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yaml
index be1a809e9..36db7facb 100644
--- a/tests/scenarios/harness_failure_recovery/catalog.yaml
+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml
@@ -4442,6 +4442,16 @@ scenarios:
# owner. The detached record takes that phase's text, even when the Result body
# is empty, so it never replays later; text another phase set is untouched.
test: tests/test_claude_result_provenance.py::test_injected_turn_result_retires_its_unbuffered_assistant_text
+ - id: HFR-489
+ name: an idle Claude runtime that dies posts nothing to its conversation
+ status: covered
+ kind: failure
+ layer: contract
+ backend: claude
+ # Its last Turn already settled and no agent-initiated Turn holds the FIFO, so
+ # nobody waits on it: the runtime retires quietly, as an idle EOF does, with no
+ # notice, re-login prompt, Turn settlement or Model Hub failure record.
+ test: tests/test_claude_agent_sessions.py::ClaudeRuntimeFailureAuthClassificationTests::test_idle_runtime_death_posts_nothing_to_its_conversation
manual_evidence:
- local Incus backend process death after prompt acceptance
- local Incus controller restart with persisted queued successor
diff --git a/tests/scenarios/harness_failure_recovery/observations.yaml b/tests/scenarios/harness_failure_recovery/observations.yaml
index 70736aee8..c8952a19a 100644
--- a/tests/scenarios/harness_failure_recovery/observations.yaml
+++ b/tests/scenarios/harness_failure_recovery/observations.yaml
@@ -337,3 +337,13 @@ observations:
Vault expiry. Runtime restart sanitization alone cannot supply the binding;
command execution must replace provenance from its own definition, preserving
remote authority without borrowing the creator's transient proof.
+ - id: HFR-OBS-028
+ date: 2026-10-20
+ source: local Incus regression after an OOM kill and a service restart
+ result: confirmed
+ detail: >-
+ A receiver failure posted its notice whether or not a Turn was in flight. When the
+ OOM killer ended many idle Claude runtimes at once, each conversation whose last Turn
+ had already settled got a failure notice, a Lark channel included. The EOF path
+ already retired an idle runtime quietly; HFR-489 holds the receiver-error path to
+ the same rule, keyed on the Claude FIFO that every in-flight Turn occupies.
diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.py
index a0e4e4208..25071b46f 100644
--- a/tests/test_claude_agent_sessions.py
+++ b/tests/test_claude_agent_sessions.py
@@ -2302,7 +2302,8 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
"Failed to authenticate: OAuth login required",
)
),
- _transport=SimpleNamespace(_process=SimpleNamespace(returncode=-6)),
+ # The CLI exited by itself; a signal exit is a termination, not auth.
+ _transport=SimpleNamespace(_process=SimpleNamespace(returncode=1)),
_vibe_runtime_base_session_id="wechat_o9:reviewer",
_vibe_runtime_session_key=runtime_key,
)
@@ -3287,11 +3288,12 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
handle_session_error=AsyncMock(),
cleanup_session=AsyncMock(),
claude_error_diagnostic=lambda _key, _error: (
- "OAuth login failed; Claude process terminated: SIGABRT"
+ "OAuth login failed; Claude process terminated: exit code 1"
),
)
+ # The CLI exited by itself; a signal exit is a termination, not auth.
client = SimpleNamespace(
- _transport=SimpleNamespace(_process=SimpleNamespace(returncode=-6)),
+ _transport=SimpleNamespace(_process=SimpleNamespace(returncode=1)),
)
controller.claude_sessions[composite_key] = client
controller.receiver_tasks[composite_key] = asyncio.current_task()
@@ -3323,6 +3325,10 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
agent.session_handler = SimpleNamespace(handle_session_error=AsyncMock())
agent._clear_pending_reactions = AsyncMock()
context = SimpleNamespace()
+ # The Turn the receiver error interrupts.
+ agent._pending_requests["session-1:/tmp/work"] = [
+ SimpleNamespace(context=SimpleNamespace(platform_specific={}))
+ ]
class _FailingClient:
def receive_messages(self):
@@ -3370,6 +3376,10 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
)
agent._clear_pending_reactions = AsyncMock()
context = SimpleNamespace()
+ # The Turn the receiver error interrupts.
+ agent._pending_requests["session-1:/tmp/work"] = [
+ SimpleNamespace(context=SimpleNamespace(platform_specific={}))
+ ]
class _FailingClient:
def receive_messages(self):
@@ -3396,13 +3406,8 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
output=ANY,
terminal_error=terminal_error,
)
- controller.agent_auth_service.maybe_emit_auth_recovery_message.assert_awaited_once_with(
- context,
- "claude",
- "❌ Connection to Claude was lost. Please try your message again.",
- output=ANY,
- terminal_error=terminal_error,
- )
+ # Nothing in the failure reads as auth, so recovery is never offered.
+ controller.agent_auth_service.maybe_emit_auth_recovery_message.assert_not_awaited()
persist.assert_called_once()
self.assertEqual(
persist.call_args.args,
@@ -5009,5 +5014,243 @@ class BindReservedWorkbenchSessionTests(unittest.TestCase):
self.assertEqual(ensure_calls, [], "must not mint a hidden row when a workbench id is reserved")
+# The Claude CLI prints this on stderr at every start when an API key or another
+# auth source outranks a claude.ai login, so it sits in the stderr tail of every
+# such runtime's failure diagnostic.
+_CLAUDE_CONNECTORS_NOTICE = (
+ "⚠ claude.ai connectors are disabled because ANTHROPIC_API_KEY or another auth "
+ "source is set and takes precedence over your claude.ai login · Unset it to load "
+ "your organization's connectors"
+)
+
+
+class _RecordingIM:
+ def __init__(self):
+ self.formatter = SimpleNamespace(format_error=lambda text: text)
+ self.sent_messages = []
+ self.sent_button_messages = []
+
+ async def send_message(self, context, text, parse_mode=None):
+ self.sent_messages.append(text)
+ return "msg-1"
+
+ async def send_message_with_buttons(self, context, text, keyboard, parse_mode=None):
+ self.sent_button_messages.append(text)
+ return "btn-1"
+
+
+class ClaudeRuntimeFailureAuthClassificationTests(unittest.IsolatedAsyncioTestCase):
+ """A Claude runtime failure reaches the real diagnostic, notice and auth classifier."""
+
+ composite_key = "slack_C1:/tmp/work"
+
+ def _harness(self, returncode, *, frames=(), error=None, in_flight=True):
+ from claude_agent_sdk import ProcessError
+
+ from core.agent_auth_service import AgentAuthService
+ from core.handlers.session_handler import SessionHandler
+ from modules.im import MessageContext
+
+ controller = _StubController()
+ controller.config.language = "en"
+ controller.stored_session_mappings = {}
+ im = _RecordingIM()
+ controller.im_client = im
+ controller.get_im_client_for_context = lambda _context: im
+ controller._get_session_key = lambda _context: "slack::C1"
+ controller.emit_agent_message = AsyncMock()
+ handler = SessionHandler(controller)
+ handler.cleanup_session = AsyncMock()
+ controller.session_handler = handler
+ # The recovery classifier and messages are the real ones; only the
+ # service's construction-time Claude settings recovery is skipped.
+ auth_service = AgentAuthService.__new__(AgentAuthService)
+ auth_service.controller = controller
+ controller.agent_auth_service = auth_service
+ agent = ClaudeAgent(controller)
+ agent._clear_pending_reactions = AsyncMock()
+ agent._remove_ack_reaction = AsyncMock()
+
+ if error is None:
+ error = ProcessError(
+ f"Command failed with exit code {returncode}",
+ exit_code=returncode,
+ stderr="Check stderr output for details",
+ )
+
+ class _Client:
+ _transport = SimpleNamespace(_process=SimpleNamespace(returncode=returncode))
+ _vibe_stderr_lines = [_CLAUDE_CONNECTORS_NOTICE]
+
+ async def disconnect(self):
+ return None
+
+ def receive_messages(self):
+ async def _iterate():
+ for frame in frames:
+ yield frame
+ raise error
+
+ return _iterate()
+
+ client = _Client()
+ controller.claude_sessions[self.composite_key] = client
+ controller.receiver_tasks[self.composite_key] = asyncio.current_task()
+ context = MessageContext(
+ user_id="U1",
+ channel_id="C1",
+ platform="slack",
+ platform_specific={"turn_token": "turn-1"},
+ )
+ if in_flight:
+ agent._pending_requests[self.composite_key] = [
+ SimpleNamespace(
+ context=MessageContext(
+ user_id="U1",
+ channel_id="C1",
+ platform="slack",
+ platform_specific={"turn_token": "turn-1"},
+ )
+ )
+ ]
+ return agent, client, context, im, handler
+
+ async def _run(self, agent, client, context):
+ with patch(
+ "core.handlers.session_handler.observe_agent_resource_pressure",
+ lambda _controller: None,
+ ), patch("core.message_mirror.persist_agent_message") as persist:
+ await agent._receive_messages(client, "slack_C1", "/tmp/work", context)
+ return [call.args[2] for call in persist.call_args_list if call.args[1] == "notify"]
+
+ async def test_cli_exit_during_a_turn_reports_termination_without_relogin(self):
+ """Scenario: AUTH-SETUP-912
+
+ A Claude CLI whose stderr names the claude.ai login ends mid-Turn: the
+ OOM killer (``-9``), a service stop (``-15``, or ``143`` when the CLI
+ exits on SIGTERM itself), or an exit of its own (``1``). The user gets
+ the termination notice and the session resets, with no re-login
+ prompt. A signal exit stays a termination even when the error itself
+ mentions the login.
+ """
+ from core.agent_auth_service import classify_auth_error
+ from vibe.i18n import t
+
+ relogin = t("command.setup.resetPromptPlain", "en", backend="claude")
+ sigkill = t("error.claudeProcessSignal", "en", signal="SIGKILL", number=9)
+ for returncode, error, reason in (
+ (-9, None, sigkill),
+ (-15, None, t("error.claudeProcessSignal", "en", signal="SIGTERM", number=15)),
+ (143, None, t("error.claudeProcessExitCode", "en", code=143)),
+ (1, None, t("error.claudeProcessExitCode", "en", code=1)),
+ (-9, RuntimeError("Cannot write to terminated process after OAuth login failed"), sigkill),
+ ):
+ with self.subTest(returncode=returncode, error=str(error or "")):
+ agent, client, context, im, handler = self._harness(returncode, error=error)
+
+ notices = await self._run(agent, client, context)
+
+ termination = t("error.claudeProcessTerminated", "en", reason=reason)
+ self.assertEqual(im.sent_button_messages, [])
+ self.assertEqual(im.sent_messages, [termination])
+ self.assertEqual(notices, [f"\u274c {termination}"])
+ self.assertNotIn(relogin, "\n".join(notices))
+ handler.cleanup_session.assert_awaited_once_with(
+ self.composite_key,
+ current_receiver_task=asyncio.current_task(),
+ expected_client=client,
+ reason="process_terminated",
+ )
+ settlement = agent.controller.emit_agent_message.await_args
+ self.assertTrue(settlement.kwargs["is_error"])
+ # The settled diagnostic still quotes the stderr notice, which the
+ # auth classifier matches: the user keeps it, the auth check does
+ # not read it.
+ self.assertIn(_CLAUDE_CONNECTORS_NOTICE, settlement.kwargs["terminal_error"])
+ self.assertTrue(classify_auth_error("claude", settlement.kwargs["terminal_error"]))
+
+ async def test_idle_runtime_death_posts_nothing_to_its_conversation(self):
+ """Scenario: HFR-489
+
+ Its last Turn already settled, so a killed idle runtime retires quietly
+ whatever ended it: no notice, no re-login prompt, no Turn settlement.
+ """
+ for returncode in (-9, 143, 1):
+ with self.subTest(returncode=returncode):
+ agent, client, context, im, handler = self._harness(returncode, in_flight=False)
+
+ notices = await self._run(agent, client, context)
+
+ self.assertEqual(im.sent_messages, [])
+ self.assertEqual(im.sent_button_messages, [])
+ self.assertEqual(notices, [])
+ agent.controller.emit_agent_message.assert_not_awaited()
+ handler.cleanup_session.assert_awaited_once_with(
+ self.composite_key,
+ current_receiver_task=asyncio.current_task(),
+ activation_retired=False,
+ reason="receiver_error_without_turn",
+ expected_client=client,
+ )
+
+ async def test_auth_failure_the_cli_reports_keeps_the_relogin_prompt(self):
+ """Scenario: AUTH-SETUP-913
+
+ The same runtime, login notice in its stderr, with an auth failure the
+ CLI itself reports. In SDK mode it reports one as frames: a synthetic
+ Assistant message whose ``error`` is ``authentication_failed``, then an
+ ``is_error`` Result (the shape the bundled CLI emits for a missing
+ login, with nothing on stderr). A result frame alone, and the error of
+ a process that exited by itself, are reported too. Each keeps today's
+ re-login prompt.
+ """
+ from modules.claude_sdk_compat import AssistantMessage, ResultMessage
+ from vibe.i18n import t
+
+ not_logged_in = "Not logged in \u00b7 Please run /login"
+ cli_frames = (
+ AssistantMessage(
+ content=[TextBlock(text=not_logged_in)],
+ model="<synthetic>",
+ error="authentication_failed",
+ ),
+ ResultMessage(
+ subtype="success",
+ duration_ms=0,
+ duration_api_ms=0,
+ is_error=True,
+ num_turns=1,
+ session_id="native-1",
+ result=not_logged_in,
+ terminal_reason="api_error",
+ ),
+ )
+ expired = (
+ 'Failed to authenticate. API Error: 401 {"type":"error","error":'
+ '{"type":"authentication_error","message":"OAuth token has expired."}}'
+ )
+ result = type("ResultMessage", (), {})()
+ result.subtype = "error"
+ result.result = expired
+ result.duration_ms = 0
+ relogin_button = t("command.setup.resetPrompt", "en", backend="claude")
+ relogin = t("command.setup.resetPromptPlain", "en", backend="claude")
+ for name, harness in (
+ ("cli auth frames", dict(returncode=1, frames=cli_frames)),
+ ("result frame", dict(returncode=None, frames=(result,))),
+ ("self exit", dict(returncode=1, error=RuntimeError(expired))),
+ ):
+ with self.subTest(name):
+ agent, client, context, im, handler = self._harness(**harness)
+
+ notices = await self._run(agent, client, context)
+
+ self.assertEqual(len(im.sent_button_messages), 1)
+ self.assertTrue(im.sent_button_messages[0].endswith(f"\n\n{relogin_button}"))
+ self.assertEqual(len(notices), 1)
+ self.assertTrue(notices[0].endswith(f"\n\n{relogin}"))
+ self.assertEqual(im.sent_messages, [])
+
+
if __name__ == "__main__":
unittest.main()