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(auth): add setup scenario harness coverage

cyhc49625f71c38
diff --git a/AGENTS.md b/AGENTS.md
index 4f5d22680..1b103aa63 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -202,6 +202,7 @@ Testing guidance:
- use pytest-style tests (`test_<feature>.py`) colocated or under `tests/`
- for IM integrations, stub/mock platform clients and validate outbound payload/schema behavior
+- for multi-step auth/setup flows, add or update a closed-loop scenario harness case under `tests/test_agent_auth_setup_scenarios.py`; keep provider-specific parsing and heuristics in focused unit tests
- for UI changes, run `npm run build` in `ui/`
- for cross-platform or user-facing verification, use the Docker regression workflow
- until CI fully covers a flow, do a manual sanity check for the affected workflow when practical
diff --git a/docs/regression/AUTH_SETUP_SCENARIOS.md b/docs/regression/AUTH_SETUP_SCENARIOS.md
new file mode 100644
index 000000000..0c6bc3a41
--- /dev/null
+++ b/docs/regression/AUTH_SETUP_SCENARIOS.md
@@ -0,0 +1,102 @@
+# Auth Setup Scenario Harness
+
+This document defines the lightweight closed-loop regression pattern for IM-driven backend auth/setup flows.
+
+It complements existing unit tests and manual Docker regression:
+
+- unit tests still own parsing, heuristics, and narrow edge cases
+- scenario harness tests own the multi-step setup flow inside the service boundary
+- manual regression still owns real IM adapters, real OAuth pages, and real provider accounts
+
+## Goal
+
+Catch regressions where each individual helper still passes, but the full setup flow no longer closes correctly.
+
+Typical failures in this category:
+
+- setup starts, but no completion waiter is attached
+- the user reply is no longer consumed by the active setup flow
+- runtime refresh is skipped after successful verification
+- the final success/failure message is never emitted
+- one backend-specific branch accidentally steals another backend's follow-up input
+
+## Keep It Lightweight
+
+Do not build a generic workflow engine first.
+
+The preferred pattern is:
+
+1. keep production code changes small
+2. add a focused scenario test under `tests/test_agent_auth_setup_scenarios.py`
+3. use fake process / fake control client / fake IM client transcripts
+4. drive the real public service methods (`start_setup`, `maybe_consume_setup_reply`, `submit_code`) whenever practical
+
+If a new helper is only needed by one scenario, keep it local to the test file.
+
+## Required Coverage
+
+When changing auth/setup behavior, add or update at least one closed-loop scenario that covers:
+
+1. setup starts
+2. the user-facing login instruction is emitted
+3. the external follow-up is simulated
+ - CLI text transcript
+ - plain IM reply
+ - control-channel completion
+4. login verification runs
+5. backend runtime refresh happens
+6. a terminal user-visible message is emitted
+
+For any backend-specific auth flow, the default target is one happy-path scenario plus unit tests for branchy edge cases.
+
+## Current Scenario Matrix
+
+- Codex device auth:
+ - start setup
+ - emit device URL and code
+ - complete process
+ - verify login
+ - refresh runtime
+ - emit success
+- Claude manual callback:
+ - start control-channel auth
+ - emit manual URL
+ - accept plain `authorizationCode#state` reply
+ - wait for completion
+ - verify login
+ - refresh runtime
+ - emit success
+- OpenCode direct key:
+ - start setup
+ - emit auth URL
+ - accept plain credential reply
+ - install key
+ - refresh runtime
+ - clear stale sessions
+ - emit success
+
+## What Stays in Unit Tests
+
+Keep these as small focused tests instead of scenario tests:
+
+- callback/code parsing
+- credential-shape heuristics
+- auth-error classification
+- flow lookup priority
+- single cleanup invariants
+
+Scenario tests should assert the user journey, not every internal branch.
+
+## What Still Needs Manual Regression
+
+Keep manual regression for:
+
+- real IM transport behavior
+- real OAuth/account/provider interactions
+- CLI or SDK behavior that cannot be deterministically simulated at the service boundary
+
+When a bug is first discovered manually, the follow-up rule is:
+
+1. fix the root cause
+2. add the narrow unit test if needed
+3. add or update the nearest closed-loop scenario so the same journey cannot silently regress again
diff --git a/docs/regression/README.md b/docs/regression/README.md
index b398b635e..b4921976c 100644
--- a/docs/regression/README.md
+++ b/docs/regression/README.md
@@ -7,6 +7,7 @@ The container state is persistent by default. Changes you make through the UI or
It complements the existing automated `E2E` flow instead of replacing it:
- `E2E testing` keeps using scripts and pytest for automatable scenarios.
+- multi-step auth/setup journeys should add a focused scenario harness case; see `AUTH_SETUP_SCENARIOS.md`
- `Regression testing` is for human-triggered checks on real IM platforms.
## Setup
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index f3d4d443c..b99e140ba 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -669,9 +669,6 @@ class ClaudeAgent(BaseAgent):
return handled
def _is_auth_failure_assistant_message(self, message) -> bool:
- if not getattr(message, "isApiErrorMessage", False):
- return False
-
error_kind = (getattr(message, "error", "") or "").strip().lower()
return error_kind == "authentication_failed"
diff --git a/tests/test_agent_auth_setup_scenarios.py b/tests/test_agent_auth_setup_scenarios.py
new file mode 100644
index 000000000..a80d8b3fd
--- /dev/null
+++ b/tests/test_agent_auth_setup_scenarios.py
@@ -0,0 +1,219 @@
+import asyncio
+import sys
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT))
+
+from core.agent_auth_service import AgentAuthService
+from modules.im import MessageContext
+
+
+class _ScenarioIMClient:
+ def __init__(self):
+ self.events = []
+
+ async def send_message(self, context, text, parse_mode=None):
+ self.events.append(("message", text))
+ return f"msg-{len(self.events)}"
+
+ async def send_message_with_buttons(self, context, text, keyboard, parse_mode=None):
+ self.events.append(("buttons", text, keyboard))
+ return f"btn-{len(self.events)}"
+
+ def rendered_texts(self):
+ return [event[1] for event in self.events]
+
+
+class _ScenarioController:
+ def __init__(self):
+ self.config = SimpleNamespace(
+ platform="slack",
+ language="en",
+ agents=SimpleNamespace(
+ codex=SimpleNamespace(cli_path="codex"),
+ claude=SimpleNamespace(cli_path="claude"),
+ opencode=SimpleNamespace(cli_path="opencode"),
+ ),
+ )
+ self.im_client = _ScenarioIMClient()
+ self.agent_service = SimpleNamespace(agents={})
+ self.sessions = SimpleNamespace(get_agent_session_id=lambda *args, **kwargs: None)
+ self.session_handler = SimpleNamespace(
+ get_session_info=lambda context: ("base-1", "/tmp/workdir", "base-1:/tmp/workdir"),
+ get_working_path=lambda context: "/tmp/workdir",
+ )
+
+ def get_im_client_for_context(self, context):
+ return self.im_client
+
+ def _get_settings_key(self, context):
+ return context.channel_id
+
+ def _get_lang(self):
+ return "en"
+
+ def resolve_agent_for_context(self, context):
+ return "codex"
+
+ def get_opencode_overrides(self, context):
+ return (None, None, None)
+
+
+class _FakeProcess:
+ def __init__(self):
+ self.returncode = None
+ self.stdout = SimpleNamespace(readline=AsyncMock(return_value=b""))
+ self._done = asyncio.Event()
+
+ async def wait(self):
+ await self._done.wait()
+ return self.returncode
+
+ def finish(self, returncode=0):
+ self.returncode = returncode
+ self._done.set()
+
+ def terminate(self):
+ self.finish(-15)
+
+ def kill(self):
+ self.finish(-9)
+
+
+class _SetupScenarioHarness:
+ def __init__(self):
+ self.controller = _ScenarioController()
+ self.service = AgentAuthService(self.controller)
+ self.context = MessageContext(user_id="U1", channel_id="C1")
+
+ def flow(self, backend: str):
+ return self.service._flows[f"C1:{backend}"]
+
+ def rendered_texts(self):
+ return self.controller.im_client.rendered_texts()
+
+
+class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
+ async def test_codex_device_auth_scenario_reaches_terminal_success(self):
+ harness = _SetupScenarioHarness()
+ fake_process = _FakeProcess()
+ harness.service._start_codex_process = AsyncMock(return_value=fake_process)
+ harness.service._read_codex_output = AsyncMock(return_value=None)
+ harness.service._verify_login = AsyncMock(return_value=(True, "Logged in using ChatGPT"))
+ harness.service._refresh_backend_runtime = AsyncMock()
+
+ await harness.service.start_setup(harness.context, backend="codex", force_reset=True)
+
+ flow = harness.flow("codex")
+ self.assertFalse(flow.waiter_task.done())
+
+ await harness.service._handle_process_text(
+ harness.context,
+ "codex",
+ "Open this URL to authenticate: https://auth.openai.com/codex/device",
+ )
+ await harness.service._handle_process_text(
+ harness.context,
+ "codex",
+ "Then enter this code: T74L-XU61D",
+ )
+
+ fake_process.finish(0)
+ await flow.waiter_task
+
+ harness.service._refresh_backend_runtime.assert_awaited_once_with("codex")
+ rendered = harness.rendered_texts()
+ self.assertIn("starting codex", rendered[0].lower())
+ self.assertIn("https://auth.openai.com/codex/device", rendered[1])
+ self.assertIn("T74L-XU61D", rendered[1])
+ self.assertIn("codex login is active again", rendered[-1].lower())
+ self.assertNotIn("C1:codex", harness.service._flows)
+
+ async def test_claude_manual_callback_scenario_accepts_plain_reply_and_completes(self):
+ harness = _SetupScenarioHarness()
+ fake_client = object()
+ completion_released = asyncio.Event()
+ callback_payloads = []
+
+ harness.service._start_claude_control_flow = AsyncMock(
+ return_value=(fake_client, "https://platform.claude.com/oauth/code/callback")
+ )
+
+ async def fake_control_request(client, request, timeout=900.0):
+ self.assertIs(client, fake_client)
+ if request["subtype"] == "claude_oauth_wait_for_completion":
+ await completion_released.wait()
+ return {}
+ raise AssertionError(f"unexpected control request: {request}")
+
+ async def fake_send_callback(client, authorization_code, state):
+ self.assertIs(client, fake_client)
+ callback_payloads.append((authorization_code, state))
+ completion_released.set()
+
+ harness.service._send_claude_control_request = AsyncMock(side_effect=fake_control_request)
+ harness.service._send_claude_callback = AsyncMock(side_effect=fake_send_callback)
+ harness.service._verify_login = AsyncMock(return_value=(True, '{"loggedIn": true}'))
+ harness.service._refresh_backend_runtime = AsyncMock()
+ harness.service._disconnect_claude_client = AsyncMock()
+
+ await harness.service.start_setup(
+ harness.context,
+ backend="claude",
+ force_reset=True,
+ claude_login_method="console",
+ )
+
+ flow = harness.flow("claude")
+ self.assertFalse(flow.waiter_task.done())
+
+ consumed = await harness.service.maybe_consume_setup_reply(harness.context, "auth-code#oauth-state")
+ self.assertTrue(consumed)
+
+ await flow.waiter_task
+
+ self.assertEqual(callback_payloads, [("auth-code", "oauth-state")])
+ harness.service._refresh_backend_runtime.assert_awaited_once_with("claude")
+ harness.service._disconnect_claude_client.assert_awaited_once_with(fake_client)
+ rendered = harness.rendered_texts()
+ self.assertIn("starting claude", rendered[0].lower())
+ self.assertIn("https://platform.claude.com/oauth/code/callback", rendered[1])
+ self.assertIn("submitted", rendered[2].lower())
+ self.assertIn("claude login is active again", rendered[-1].lower())
+ self.assertNotIn("C1:claude", harness.service._flows)
+
+ async def test_opencode_direct_key_scenario_installs_key_and_refreshes_runtime(self):
+ harness = _SetupScenarioHarness()
+ harness.service._resolve_opencode_provider = AsyncMock(return_value="opencode")
+ harness.service._install_opencode_api_key = AsyncMock()
+ harness.service._refresh_backend_runtime = AsyncMock()
+ harness.service._clear_backend_sessions_for_context = AsyncMock()
+
+ await harness.service.start_setup(harness.context, backend="opencode", force_reset=True)
+
+ flow = harness.flow("opencode")
+ self.assertTrue(flow.awaiting_code)
+ self.assertEqual(flow.url, "https://opencode.ai/auth")
+
+ consumed = await harness.service.maybe_consume_setup_reply(
+ harness.context,
+ "oc_live_Abcdef1234567890",
+ )
+ self.assertTrue(consumed)
+
+ harness.service._install_opencode_api_key.assert_awaited_once_with("opencode", "oc_live_Abcdef1234567890")
+ harness.service._refresh_backend_runtime.assert_awaited_once_with("opencode")
+ harness.service._clear_backend_sessions_for_context.assert_awaited_once_with("opencode", harness.context)
+ rendered = harness.rendered_texts()
+ self.assertIn("starting opencode", rendered[0].lower())
+ self.assertIn("https://opencode.ai/auth", rendered[1])
+ self.assertIn("opencode login is active again", rendered[-1].lower())
+ self.assertNotIn("C1:opencode", harness.service._flows)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.py
index abf9f3046..f2e4387dc 100644
--- a/tests/test_claude_agent_sessions.py
+++ b/tests/test_claude_agent_sessions.py
@@ -280,6 +280,45 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn(composite_key, controller.receiver_tasks)
self.assertNotIn(composite_key, controller.claude_sessions)
+ async def test_assistant_auth_error_without_is_api_error_flag_still_triggers_recovery(self):
+ controller = _StubController()
+ controller.agent_auth_service.maybe_emit_auth_recovery_message = AsyncMock(return_value=True)
+ controller._get_session_key = lambda context: "telegram::user::U1"
+ controller.emit_agent_message = AsyncMock()
+ agent = ClaudeAgent(controller)
+ agent._remove_ack_reaction = AsyncMock()
+ agent._extract_text_blocks = lambda message, context: (
+ 'Failed to authenticate. API Error: 401 {"type":"error","error":{"type":"authentication_error",'
+ '"message":"Invalid bearer token"}}'
+ )
+ context = SimpleNamespace()
+ composite_key = "session-1:/tmp/work"
+ current_task = asyncio.current_task()
+ controller.receiver_tasks[composite_key] = current_task
+ controller.claude_sessions[composite_key] = _StubClient()
+
+ assistant_message = type(
+ "AssistantMessage",
+ (),
+ {
+ "content": [],
+ "error": "authentication_failed",
+ },
+ )()
+
+ class _Client:
+ def receive_messages(self):
+ async def _iterate():
+ yield assistant_message
+
+ return _iterate()
+
+ await agent._receive_messages(_Client(), "session-1", "/tmp/work", context)
+
+ controller.agent_auth_service.maybe_emit_auth_recovery_message.assert_awaited_once()
+ self.assertNotIn(composite_key, controller.receiver_tasks)
+ self.assertNotIn(composite_key, controller.claude_sessions)
+
async def test_handle_auth_failure_result_requires_explicit_error_subtype(self):
controller = _StubController()
controller.agent_auth_service.maybe_emit_auth_recovery_message = AsyncMock(return_value=True)