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.

test(auth): expand setup scenario coverage

cyhf18d97eb06a1
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index ea5b28c2c..a3410a0ad 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -154,6 +154,7 @@ class AgentAuthService:
self._flows: dict[str, AgentAuthFlow] = {}
self._flows_by_id: dict[str, AgentAuthFlow] = {}
self._flow_lock = asyncio.Lock()
+ self.setup_timeout_seconds = 900.0
def _t(self, key: str, **kwargs) -> str:
lang = getattr(self.controller, "_get_lang", lambda: getattr(self.controller.config, "language", "en"))()
@@ -885,7 +886,7 @@ class AgentAuthService:
async def _wait_for_completion(self, flow: AgentAuthFlow) -> None:
try:
assert flow.process is not None
- await flow.process.wait()
+ await asyncio.wait_for(flow.process.wait(), timeout=self.setup_timeout_seconds)
await flow.reader_task
ok, detail = await self._verify_login(flow)
if ok:
@@ -902,6 +903,14 @@ class AgentAuthService:
button_text=self._t("button.resetOAuth"),
callback_data=f"auth_setup:{flow.backend}",
)
+ except asyncio.TimeoutError:
+ await self._terminate_process_for_timeout(flow)
+ await self._send_message_with_button(
+ flow.context,
+ f"❌ {self._t('command.setup.failed', backend=flow.backend, detail=self._t('command.setup.timedOut', backend=flow.backend))}",
+ button_text=self._t("button.resetOAuth"),
+ callback_data=f"auth_setup:{flow.backend}",
+ )
except asyncio.CancelledError:
raise
except Exception as err: # noqa: BLE001
@@ -920,9 +929,13 @@ class AgentAuthService:
if flow.claude_client is None:
raise RuntimeError("Claude auth flow is missing its SDK client")
- await self._send_claude_control_request(
- flow.claude_client,
- {"subtype": "claude_oauth_wait_for_completion"},
+ await asyncio.wait_for(
+ self._send_claude_control_request(
+ flow.claude_client,
+ {"subtype": "claude_oauth_wait_for_completion"},
+ timeout=self.setup_timeout_seconds,
+ ),
+ timeout=self.setup_timeout_seconds,
)
ok, detail = await self._verify_login(flow)
if ok:
@@ -939,6 +952,13 @@ class AgentAuthService:
button_text=self._t("button.resetOAuth"),
callback_data=f"auth_setup:{flow.backend}",
)
+ except asyncio.TimeoutError:
+ await self._send_message_with_button(
+ flow.context,
+ f"❌ {self._t('command.setup.failed', backend=flow.backend, detail=self._t('command.setup.timedOut', backend=flow.backend))}",
+ button_text=self._t("button.resetOAuth"),
+ callback_data=f"auth_setup:{flow.backend}",
+ )
except asyncio.CancelledError:
raise
except Exception as err: # noqa: BLE001
@@ -1166,6 +1186,21 @@ class AgentAuthService:
await self._disconnect_claude_client(flow.claude_client)
self._drop_flow(flow)
+ async def _terminate_process_for_timeout(self, flow: AgentAuthFlow) -> None:
+ if flow.reader_task and not flow.reader_task.done():
+ flow.reader_task.cancel()
+ try:
+ await flow.reader_task
+ except asyncio.CancelledError:
+ pass
+ if flow.process is not None and flow.process.returncode is None:
+ flow.process.terminate()
+ try:
+ await asyncio.wait_for(flow.process.wait(), timeout=5)
+ except asyncio.TimeoutError:
+ flow.process.kill()
+ await flow.process.wait()
+
def _drop_flow(self, flow: AgentAuthFlow) -> None:
if self._flows.get(flow.flow_key) is flow:
self._flows.pop(flow.flow_key, None)
diff --git a/docs/regression/AUTH_SETUP_SCENARIOS.md b/docs/regression/AUTH_SETUP_SCENARIOS.md
index 37b7228c7..5d38e230e 100644
--- a/docs/regression/AUTH_SETUP_SCENARIOS.md
+++ b/docs/regression/AUTH_SETUP_SCENARIOS.md
@@ -57,6 +57,7 @@ Reference implementation currently lives in:
- `tests/scenario_harness/`
- `tests/test_agent_auth_setup_scenarios.py`
- `docs/regression/AUTH_SETUP_SCENARIOS.md`
+- `docs/regression/AUTH_SETUP_SCENARIO_CATALOG.md`
## Current Scenario Matrix
@@ -67,22 +68,51 @@ Reference implementation currently lives in:
- verify login
- refresh runtime
- emit success
+ - prove the next user turn sees refreshed runtime instead of stale auth state
- Claude manual callback:
- start control-channel auth
- emit manual URL
- accept plain `authorizationCode#state` reply
+ - treat plain reply and `/setup code ...` fallback as one logical submission, not two
+ - reject malformed callback values while keeping the flow recoverable
- wait for completion
+ - time out into a recoverable terminal state if completion never arrives
- verify login
- refresh runtime
- emit success
+ - reject wrong-user callback submission without stealing the flow
+ - treat assistant auth-failure runtime events as OAuth recovery, even without deprecated metadata flags
- OpenCode direct key:
- start setup
- emit auth URL
- accept plain credential reply
+ - reject invalid-looking replies without killing the flow
+ - allow a later valid retry to complete the flow
- install key
- refresh runtime
- clear stale sessions
- emit success
+ - prove the next user turn sees refreshed runtime and cleared sessions
+- Shared multi-flow routing:
+ - keep Claude and OpenCode flows active in one channel
+ - route callback-shaped input to Claude
+ - route credential-shaped input to OpenCode
+ - avoid cross-flow stealing
+- Shared teardown and restart:
+ - let a flow timeout into a recoverable terminal state
+ - start setup again immediately
+ - prove the new attempt gets a fresh flow and fresh instructions
+ - prove a failed attempt does not leak stale runtime state into the next retry
+
+The detailed capability matrix now lives in:
+
+- `docs/regression/AUTH_SETUP_SCENARIO_CATALOG.md`
+
+Use the catalog when deciding:
+
+- which backend/path needs the next scenario
+- whether a new bug is already covered by an existing scenario ID
+- whether the gap is scenario-worthy or should stay unit/contract/manual
## What Stays in Unit Tests
diff --git a/docs/regression/AUTH_SETUP_SCENARIO_CATALOG.md b/docs/regression/AUTH_SETUP_SCENARIO_CATALOG.md
index 1dc9e0c7a..640570f1c 100644
--- a/docs/regression/AUTH_SETUP_SCENARIO_CATALOG.md
+++ b/docs/regression/AUTH_SETUP_SCENARIO_CATALOG.md
@@ -84,10 +84,211 @@
- Current test:
`tests/test_agent_auth_setup_scenarios.py::test_codex_failure_scenario_emits_reset_path`
-## Next High-Priority Gaps
+### `AUTH-SETUP-103 Wrong user cannot submit into another user's active flow`
-- `AUTH-SETUP-102` wrong Claude callback format keeps the flow active
-- `AUTH-SETUP-103` wrong user cannot submit code into someone else's flow
-- `AUTH-SETUP-203` setup timeout emits a recoverable terminal state
-- `AUTH-SETUP-204` success path refreshes runtime and clears stale sessions before next user turn
-- `AUTH-SETUP-205` concurrent backend flows in one channel do not steal each other's replies
+- Type: negative path
+- Layer: scenario
+- Given:
+ A setup flow is active in a shared channel for one user.
+- When:
+ Another user tries to submit the follow-up callback/code into that flow.
+- Then:
+ The reply is not consumed, the user gets an ownership error, and the original flow remains active.
+- Current test:
+ `tests/test_agent_auth_setup_scenarios.py::test_claude_wrong_user_cannot_submit_callback_into_active_flow`
+
+### `AUTH-SETUP-102 Malformed Claude callback keeps the flow recoverable`
+
+- Type: negative path
+- Layer: scenario
+- Given:
+ Claude setup is waiting for the browser callback value.
+- When:
+ The user submits a malformed value that is not `authorizationCode#state`.
+- Then:
+ The callback is rejected, the flow stays active, and the user gets retry guidance.
+- Current test:
+ `tests/test_agent_auth_setup_scenarios.py::test_claude_malformed_callback_keeps_flow_active_and_instructs_retry`
+
+### `AUTH-SETUP-204 Successful setup refreshes runtime before the next user turn`
+
+- Type: recovery / post-success readiness
+- Layer: scenario
+- Given:
+ A setup flow completes successfully.
+- When:
+ The next user turn happens immediately after the success message.
+- Then:
+ Runtime refresh and stale-session cleanup have already happened, so the next turn sees the refreshed backend state.
+- Current test:
+ `tests/test_agent_auth_setup_scenarios.py::test_successful_setup_refreshes_runtime_before_the_next_turn`
+
+### `AUTH-SETUP-203 Setup timeout emits a recoverable terminal state`
+
+- Type: recovery / timeout
+- Layer: scenario
+- Given:
+ A setup flow starts but external completion never arrives.
+- When:
+ The flow hits its deadline.
+- Then:
+ The flow terminates into a recoverable failure, emits a retry/reset path, and cleans up the active flow.
+- Current test:
+ `tests/test_agent_auth_setup_scenarios.py::test_claude_timeout_emits_recoverable_terminal_state`
+
+### `AUTH-SETUP-205 Concurrent backend flows do not steal each other's replies`
+
+- Type: concurrency / routing
+- Layer: scenario
+- Given:
+ Multiple backend setup flows are active in the same channel.
+- When:
+ The user sends backend-specific follow-up replies.
+- Then:
+ Each reply is consumed by the matching backend flow and the other flow remains intact until its own reply arrives.
+- Current test:
+ `tests/test_agent_auth_setup_scenarios.py::test_concurrent_setup_flows_route_replies_to_the_matching_backend`
+
+### `AUTH-SETUP-104 Invalid OpenCode credential reply stays recoverable until a valid retry`
+
+- Type: negative path
+- Layer: scenario
+- Given:
+ OpenCode direct-key setup is waiting for a credential reply.
+- When:
+ The user first sends an invalid-looking value, then retries with a valid credential.
+- Then:
+ The invalid reply is ignored, the flow stays active, and the valid retry still completes the flow successfully.
+- Current test:
+ `tests/test_agent_auth_setup_scenarios.py::test_opencode_invalid_reply_keeps_flow_recoverable_until_valid_retry`
+
+### `AUTH-SETUP-206 Terminal teardown leaves the next setup attempt clean`
+
+- Type: recovery / teardown
+- Layer: scenario
+- Given:
+ A setup flow reaches a terminal timeout/failure state.
+- When:
+ The user starts setup again immediately afterward.
+- Then:
+ The old flow no longer owns the channel state, a new flow starts cleanly, and fresh instructions are emitted for the new attempt.
+- Current test:
+ `tests/test_agent_auth_setup_scenarios.py::test_timed_out_flow_allows_clean_restart_without_stale_state`
+
+### `AUTH-SETUP-105 Plain callback submission and command fallback do not double-consume the same flow`
+
+- Type: negative path / input deduplication
+- Layer: scenario
+- Given:
+ A setup flow accepts plain-text follow-up input in the chat.
+- When:
+ The user first submits the plain reply, then repeats the old `/setup code ...` fallback after the flow already completed.
+- Then:
+ The flow is consumed exactly once and the fallback sees no active flow instead of replaying the submission.
+- Current test:
+ `tests/test_agent_auth_setup_scenarios.py::test_callback_submission_and_fallback_command_do_not_double_consume_claude_flow`
+
+### `AUTH-SETUP-901 Codex setup success refreshes runtime before the next turn`
+
+- Type: historical regression / post-success readiness
+- Layer: scenario
+- Given:
+ Codex setup completes successfully.
+- When:
+ The next user turn starts immediately afterward.
+- Then:
+ Codex runtime refresh has already completed, so the next turn does not reuse stale auth state.
+- Current test:
+ `tests/test_agent_auth_setup_scenarios.py::test_codex_successful_setup_refreshes_runtime_before_the_next_turn`
+
+### `AUTH-SETUP-902 Claude assistant auth-failure event triggers recovery even without the deprecated API-error flag`
+
+- Type: historical regression / auth recovery
+- Layer: scenario-backed runtime regression
+- Given:
+ Claude runtime receives an assistant auth-failure event.
+- When:
+ The event carries `error=\"authentication_failed\"` but does not expose the older `isApiErrorMessage` flag.
+- Then:
+ OAuth recovery still triggers and the stale runtime session is cleaned up instead of leaking the failure as plain text.
+- Current test:
+ `tests/test_claude_agent_sessions.py::test_assistant_auth_error_without_is_api_error_flag_still_triggers_recovery`
+
+### `AUTH-SETUP-207 Recoverable failure leaves the next attempt free of stale runtime state`
+
+- Type: recovery / clean retry
+- Layer: scenario
+- Given:
+ A setup attempt ends in a recoverable failure.
+- When:
+ The user starts setup again immediately afterward.
+- Then:
+ The failed flow no longer owns the channel state, runtime refresh does not leak from the failed attempt, and the next attempt can complete cleanly.
+- Current test:
+ `tests/test_agent_auth_setup_scenarios.py::test_failed_codex_setup_does_not_leave_stale_runtime_for_next_attempt`
+
+## Coverage Matrix
+
+This matrix tracks the current `AUTH-SETUP` capability by:
+
+- backend
+- user-visible phase
+- dominant risk
+- current evidence layer
+- next action
+
+Status legend:
+
+- `covered`
+ scenario coverage exists
+- `partial`
+ only unit/contract coverage exists, or only one backend branch is covered
+- `manual`
+ currently depends on manual regression
+- `gap`
+ not covered yet
+
+| Scenario band | Backend | User-visible phase | Dominant risk | Status | Current evidence | Next action |
+| --- | --- | --- | --- | --- | --- | --- |
+| `AUTH-SETUP-001` | Codex | start -> device URL/code -> verify success | waiter missing, success never emitted | covered | scenario + unit | keep as happy-path baseline |
+| `AUTH-SETUP-002` | Claude | start -> manual callback -> verify success | callback reply not consumed, completion never closes | covered | scenario + unit | keep as happy-path baseline |
+| `AUTH-SETUP-003` | OpenCode | start -> direct key reply -> refresh success | credential reply not installed, stale session survives | covered | scenario + unit | keep as happy-path baseline |
+| `AUTH-SETUP-101` | OpenCode | waiting for credential reply | normal chat stolen by setup flow | covered | scenario + unit | extend the same pattern to Claude/Codex waiting replies |
+| `AUTH-SETUP-201` | Codex | re-enter setup while active flow exists | duplicate flows, stale process survives | covered | scenario + unit | add cross-backend re-entry coverage |
+| `AUTH-SETUP-202` | Codex | process exits but verify fails | user gets no recovery path | covered | scenario + unit | add equivalent Claude/OpenCode recovery failures |
+| `AUTH-SETUP-102` | Claude | callback reply accepted | malformed `authorizationCode#state` is consumed or flow dies | covered | scenario + unit | preserve as callback-shape guardrail |
+| `AUTH-SETUP-103` | shared | waiting for user reply | wrong user can submit into another user's flow | covered | scenario + unit | keep as shared ownership guardrail |
+| `AUTH-SETUP-104` | OpenCode | waiting for credential reply | invalid-looking credential consumed or separator-only reply swallowed | covered | scenario + unit + heuristic tests | preserve as invalid-retry guardrail |
+| `AUTH-SETUP-105` | shared | fallback input handling | plain reply and fallback command both consume the same flow | covered | scenario | preserve as input-dedup guardrail |
+| `AUTH-SETUP-203` | shared | long-running active flow | timeout leaves non-terminal or unrecoverable state | covered | scenario | preserve as timeout recovery baseline |
+| `AUTH-SETUP-204` | shared | immediately after successful setup | success emitted before runtime is truly usable | covered | scenario + historical manual bug | preserve as post-success readiness guardrail |
+| `AUTH-SETUP-205` | shared | concurrent replies in one channel | one backend flow steals another backend's reply | covered | scenario | preserve as concurrency routing guardrail |
+| `AUTH-SETUP-206` | shared | success / failure teardown | stale sessions, pending requests, or old runtime survive | covered | scenario + unit fragments | preserve as clean-restart teardown baseline |
+| `AUTH-SETUP-901` | Codex | post-OAuth usability | login completes but runtime is not refreshed | covered | scenario + historical bug fix | preserve as observed regression guardrail |
+| `AUTH-SETUP-902` | Claude | auth failure detection | assistant auth failure is treated as plain text | covered | runtime regression test + historical bug fix | preserve as observed recovery guardrail |
+
+## Priority Queue
+
+The next scenario wave should focus on the gaps that most directly affect user trust:
+
+1. `AUTH-SETUP-204`
+ now covered; keep extending it beyond OpenCode when more backends need post-success readiness checks
+2. `AUTH-SETUP-103`
+ now covered; keep it as the shared ownership baseline
+3. `AUTH-SETUP-205`
+ now covered; keep it as the multi-flow routing baseline
+4. `AUTH-SETUP-106`
+ callback buttons should not allow stale button presses to restart the wrong backend flow after channel state changed
+5. `AUTH-SETUP-208`
+ cross-user concurrent setup attempts should not cross-contaminate runtime cleanup
+
+## Coverage Notes
+
+- `Codex`
+ happy path, re-entry, failed verification, and post-success runtime usability are covered
+- `Claude`
+ happy path, malformed callback, wrong-user ownership, timeout recovery, and assistant auth-failure recovery are covered
+- `OpenCode`
+ happy path, plain-chat protection, invalid-retry recovery, and post-success readiness are covered
+- `shared lifecycle`
+ cross-user ownership, timeout, concurrency, input deduplication, post-success usability, and clean-restart teardown now have scenario baselines
diff --git a/tests/scenario_harness/core.py b/tests/scenario_harness/core.py
index 9e0993a53..63c149b41 100644
--- a/tests/scenario_harness/core.py
+++ b/tests/scenario_harness/core.py
@@ -116,6 +116,12 @@ class BaseScenarioHarness:
self.controller = controller or ScenarioControllerBase()
self.context = MessageContext(user_id=user_id, channel_id=channel_id)
+ def make_context(self, *, user_id: str | None = None, channel_id: str | None = None) -> MessageContext:
+ return MessageContext(
+ user_id=user_id or self.context.user_id,
+ channel_id=channel_id or self.context.channel_id,
+ )
+
@property
def events(self):
return self.controller.im_probe.events
diff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.py
index bc12f8e25..ac5ae98fe 100644
--- a/tests/test_agent_auth_service.py
+++ b/tests/test_agent_auth_service.py
@@ -821,6 +821,7 @@ class AgentAuthServiceTests(unittest.IsolatedAsyncioTestCase):
service._send_claude_control_request.assert_awaited_once_with(
flow.claude_client,
{"subtype": "claude_oauth_wait_for_completion"},
+ timeout=service.setup_timeout_seconds,
)
service._refresh_backend_runtime.assert_awaited_once_with("claude")
service._disconnect_claude_client.assert_awaited_once_with(flow.claude_client)
diff --git a/tests/test_agent_auth_setup_scenarios.py b/tests/test_agent_auth_setup_scenarios.py
index ccc13be90..dc780f66d 100644
--- a/tests/test_agent_auth_setup_scenarios.py
+++ b/tests/test_agent_auth_setup_scenarios.py
@@ -2,6 +2,7 @@ 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]
@@ -11,6 +12,35 @@ from tests.scenario_harness.auth_setup import AuthSetupScenarioHarness, FakeProc
from tests.scenario_harness.core import ScenarioExpect, ScenarioRunner, ScenarioStep
+class _FakeNextTurnRuntime:
+ def __init__(self):
+ self.refreshed = False
+ self.cleared_settings_keys = []
+
+ async def refresh(self):
+ self.refreshed = True
+
+ async def clear_sessions(self, settings_key: str):
+ self.cleared_settings_keys.append(settings_key)
+
+ def run_turn(self, settings_key: str) -> str:
+ assert self.refreshed, "Expected runtime to be refreshed before the next turn"
+ assert settings_key in self.cleared_settings_keys, "Expected stale sessions to be cleared before the next turn"
+ return "turn-ok"
+
+
+class _FakeCodexNextTurnRuntime:
+ def __init__(self):
+ self.refreshed = False
+
+ async def refresh(self):
+ self.refreshed = True
+
+ def run_turn(self) -> str:
+ assert self.refreshed, "Expected Codex runtime to be refreshed before the next turn"
+ return "turn-ok"
+
+
class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
async def test_codex_failure_scenario_emits_reset_path(self):
"""Scenario: AUTH-SETUP-202"""
@@ -126,6 +156,158 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
ScenarioExpect.text_contains(harness, "codex login is active again")
ScenarioExpect.flow_missing(harness, "C1:codex")
+ async def test_codex_successful_setup_refreshes_runtime_before_the_next_turn(self):
+ """Scenario: AUTH-SETUP-901"""
+ harness = AuthSetupScenarioHarness()
+ fake_process = FakeProcess()
+ runtime = _FakeCodexNextTurnRuntime()
+ runner = ScenarioRunner(harness)
+ harness.controller.agent_service.agents["codex"] = SimpleNamespace(
+ refresh_auth_state=AsyncMock(side_effect=runtime.refresh)
+ )
+ 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"))
+
+ await runner.run(
+ ScenarioStep(
+ "start_setup",
+ lambda h: h.service.start_setup(h.context, backend="codex", force_reset=True),
+ ),
+ ScenarioStep(
+ "emit_device_url",
+ lambda h: h.service._handle_process_text(
+ h.context,
+ "codex",
+ "Open this URL to authenticate: https://auth.openai.com/codex/device",
+ ),
+ ),
+ )
+
+ flow = harness.flow("codex")
+ fake_process.finish(0)
+ await flow.waiter_task
+
+ await runner.run(
+ ScenarioStep(
+ "next_turn_after_success",
+ lambda h: runtime.run_turn(),
+ ),
+ )
+
+ harness.controller.agent_service.agents["codex"].refresh_auth_state.assert_awaited_once()
+ ScenarioExpect.step_history(runner, ["start_setup", "emit_device_url", "next_turn_after_success"])
+ ScenarioExpect.text_contains(harness, "codex login is active again")
+ ScenarioExpect.flow_missing(harness, "C1:codex")
+
+ async def test_claude_wrong_user_cannot_submit_callback_into_active_flow(self):
+ """Scenario: AUTH-SETUP-103"""
+ harness = AuthSetupScenarioHarness()
+ fake_client = object()
+ runner = ScenarioRunner(harness)
+ callback_payloads = []
+ harness.service._start_claude_control_flow = AsyncMock(
+ return_value=(fake_client, "https://platform.claude.com/oauth/code/callback")
+ )
+ harness.service._wait_for_claude_completion = AsyncMock(return_value=None)
+ harness.service._send_claude_callback = AsyncMock(
+ side_effect=lambda client, authorization_code, state: callback_payloads.append((client, authorization_code, state))
+ )
+
+ await runner.run(
+ ScenarioStep(
+ "start_setup",
+ lambda h: h.service.start_setup(
+ h.context,
+ backend="claude",
+ force_reset=True,
+ claude_login_method="console",
+ ),
+ ),
+ )
+
+ intruder_context = harness.make_context(user_id="U2")
+ consumed = await harness.service.maybe_consume_setup_reply(intruder_context, "auth-code#oauth-state")
+ self.assertFalse(consumed)
+ self.assertEqual(callback_payloads, [])
+
+ await runner.run(
+ ScenarioStep(
+ "intruder_submit_callback",
+ lambda h: h.service.submit_code(intruder_context, "auth-code#oauth-state", backend_hint="claude"),
+ ),
+ )
+
+ ScenarioExpect.step_history(runner, ["start_setup", "intruder_submit_callback"])
+ ScenarioExpect.text_contains(harness, "starting claude", index=0)
+ ScenarioExpect.text_contains(harness, "https://platform.claude.com/oauth/code/callback", index=1)
+ ScenarioExpect.text_contains(harness, "only the user who started this setup flow")
+ self.assertIn("C1:claude", harness.service._flows)
+ self.assertEqual(callback_payloads, [])
+
+ async def test_callback_submission_and_fallback_command_do_not_double_consume_claude_flow(self):
+ """Scenario: AUTH-SETUP-105"""
+ harness = AuthSetupScenarioHarness()
+ fake_client = object()
+ completion_released = asyncio.Event()
+ callback_payloads = []
+ runner = ScenarioRunner(harness)
+
+ 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 runner.run(
+ ScenarioStep(
+ "start_setup",
+ lambda h: h.service.start_setup(
+ h.context,
+ backend="claude",
+ force_reset=True,
+ claude_login_method="console",
+ ),
+ ),
+ ScenarioStep(
+ "submit_plain_callback",
+ lambda h: h.service.maybe_consume_setup_reply(h.context, "auth-code#oauth-state"),
+ ),
+ )
+
+ flow = harness.flow("claude")
+ await flow.waiter_task
+ self.assertEqual(callback_payloads, [("auth-code", "oauth-state")])
+
+ await runner.run(
+ ScenarioStep(
+ "submit_fallback_after_completion",
+ lambda h: h.service.handle_setup_command(h.context, "code auth-code#oauth-state"),
+ ),
+ )
+
+ ScenarioExpect.step_history(runner, ["start_setup", "submit_plain_callback", "submit_fallback_after_completion"])
+ ScenarioExpect.text_contains(harness, "submitted")
+ ScenarioExpect.text_contains(harness, "there is no active setup flow")
+ self.assertEqual(callback_payloads, [("auth-code", "oauth-state")])
+ ScenarioExpect.flow_missing(harness, "C1:claude")
+
async def test_claude_manual_callback_scenario_accepts_plain_reply_and_completes(self):
"""Scenario: AUTH-SETUP-002"""
harness = AuthSetupScenarioHarness()
@@ -186,6 +368,157 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
ScenarioExpect.text_contains(harness, "claude login is active again")
ScenarioExpect.flow_missing(harness, "C1:claude")
+ async def test_claude_malformed_callback_keeps_flow_active_and_instructs_retry(self):
+ """Scenario: AUTH-SETUP-102"""
+ harness = AuthSetupScenarioHarness()
+ fake_client = object()
+ runner = ScenarioRunner(harness)
+ harness.service._start_claude_control_flow = AsyncMock(
+ return_value=(fake_client, "https://platform.claude.com/oauth/code/callback")
+ )
+ harness.service._wait_for_claude_completion = AsyncMock(return_value=None)
+ harness.service._send_claude_callback = AsyncMock()
+
+ await runner.run(
+ ScenarioStep(
+ "start_setup",
+ lambda h: h.service.start_setup(
+ h.context,
+ backend="claude",
+ force_reset=True,
+ claude_login_method="console",
+ ),
+ ),
+ ScenarioStep(
+ "submit_malformed_callback",
+ lambda h: h.service.submit_code(h.context, "not-a-valid-callback", backend_hint="claude"),
+ ),
+ )
+
+ harness.service._send_claude_callback.assert_not_awaited()
+ ScenarioExpect.step_history(runner, ["start_setup", "submit_malformed_callback"])
+ ScenarioExpect.text_contains(harness, "authorizationCode#state")
+ self.assertIn("C1:claude", harness.service._flows)
+
+ async def test_concurrent_setup_flows_route_replies_to_the_matching_backend(self):
+ """Scenario: AUTH-SETUP-205"""
+ harness = AuthSetupScenarioHarness()
+ fake_client = object()
+ completion_released = asyncio.Event()
+ callback_payloads = []
+ runner = ScenarioRunner(harness)
+
+ harness.service._start_claude_control_flow = AsyncMock(
+ return_value=(fake_client, "https://platform.claude.com/oauth/code/callback")
+ )
+ 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()
+
+ 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}'))
+
+ await runner.run(
+ ScenarioStep(
+ "start_claude_setup",
+ lambda h: h.service.start_setup(
+ h.context,
+ backend="claude",
+ force_reset=True,
+ claude_login_method="console",
+ ),
+ ),
+ ScenarioStep(
+ "start_opencode_setup",
+ lambda h: h.service.start_setup(h.context, backend="opencode", force_reset=True),
+ ),
+ )
+
+ consumed_callback = await harness.service.maybe_consume_setup_reply(harness.context, "auth-code#oauth-state")
+ self.assertTrue(consumed_callback)
+ self.assertEqual(callback_payloads, [("auth-code", "oauth-state")])
+ self.assertTrue(harness.flow("opencode").awaiting_code)
+ self.assertIn("C1:claude", harness.service._flows)
+
+ consumed_credential = await harness.service.maybe_consume_setup_reply(
+ harness.context,
+ "oc_live_Abcdef1234567890",
+ )
+ self.assertTrue(consumed_credential)
+
+ await harness.flow("claude").waiter_task
+
+ harness.service._install_opencode_api_key.assert_awaited_once_with("opencode", "oc_live_Abcdef1234567890")
+ harness.service._clear_backend_sessions_for_context.assert_any_await("opencode", harness.context)
+ ScenarioExpect.step_history(runner, ["start_claude_setup", "start_opencode_setup"])
+ ScenarioExpect.text_contains(harness, "starting claude", index=0)
+ ScenarioExpect.text_contains(harness, "starting opencode", index=2)
+ ScenarioExpect.text_contains(harness, "submitted")
+ ScenarioExpect.text_contains(harness, "opencode login is active again")
+ ScenarioExpect.text_contains(harness, "claude login is active again")
+ ScenarioExpect.flow_missing(harness, "C1:claude")
+ ScenarioExpect.flow_missing(harness, "C1:opencode")
+
+ async def test_claude_timeout_emits_recoverable_terminal_state(self):
+ """Scenario: AUTH-SETUP-203"""
+ harness = AuthSetupScenarioHarness()
+ fake_client = object()
+ runner = ScenarioRunner(harness)
+ completion_started = asyncio.Event()
+ release_completion = asyncio.Event()
+
+ harness.service.setup_timeout_seconds = 0.01
+ 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":
+ completion_started.set()
+ await release_completion.wait()
+ return {}
+ raise AssertionError(f"unexpected control request: {request}")
+
+ harness.service._send_claude_control_request = AsyncMock(side_effect=fake_control_request)
+ harness.service._disconnect_claude_client = AsyncMock()
+
+ await runner.run(
+ ScenarioStep(
+ "start_setup",
+ lambda h: h.service.start_setup(
+ h.context,
+ backend="claude",
+ force_reset=True,
+ claude_login_method="console",
+ ),
+ ),
+ )
+
+ flow = harness.flow("claude")
+ await completion_started.wait()
+ await flow.waiter_task
+
+ ScenarioExpect.step_history(runner, ["start_setup"])
+ ScenarioExpect.text_contains(harness, "timed out")
+ ScenarioExpect.button_callback_contains(harness, "auth_setup:claude")
+ ScenarioExpect.flow_missing(harness, "C1:claude")
+ harness.service._disconnect_claude_client.assert_awaited_once_with(fake_client)
+
async def test_opencode_direct_key_scenario_installs_key_and_refreshes_runtime(self):
"""Scenario: AUTH-SETUP-003"""
harness = AuthSetupScenarioHarness()
@@ -224,6 +557,222 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
ScenarioExpect.text_contains(harness, "opencode login is active again")
ScenarioExpect.flow_missing(harness, "C1:opencode")
+ async def test_opencode_invalid_reply_keeps_flow_recoverable_until_valid_retry(self):
+ """Scenario: AUTH-SETUP-104"""
+ harness = AuthSetupScenarioHarness()
+ runner = ScenarioRunner(harness)
+ 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 runner.run(
+ ScenarioStep(
+ "start_setup",
+ lambda h: h.service.start_setup(h.context, backend="opencode", force_reset=True),
+ ),
+ )
+
+ flow = harness.flow("opencode")
+ before_count = len(harness.rendered_texts())
+ consumed_invalid = await harness.service.maybe_consume_setup_reply(harness.context, "--------------------")
+ self.assertFalse(consumed_invalid)
+ self.assertTrue(flow.awaiting_code)
+ self.assertEqual(len(harness.rendered_texts()), before_count)
+ harness.service._install_opencode_api_key.assert_not_awaited()
+
+ await runner.run(
+ ScenarioStep(
+ "submit_valid_retry",
+ lambda h: h.service.maybe_consume_setup_reply(
+ h.context,
+ "oc_live_Abcdef1234567890",
+ ),
+ ),
+ )
+
+ 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)
+ ScenarioExpect.step_history(runner, ["start_setup", "submit_valid_retry"])
+ ScenarioExpect.text_contains(harness, "opencode login is active again")
+ ScenarioExpect.flow_missing(harness, "C1:opencode")
+
+ async def test_successful_setup_refreshes_runtime_before_the_next_turn(self):
+ """Scenario: AUTH-SETUP-204"""
+ harness = AuthSetupScenarioHarness()
+ runtime = _FakeNextTurnRuntime()
+ runner = ScenarioRunner(harness)
+
+ harness.controller.agent_service.agents["opencode"] = SimpleNamespace(
+ clear_sessions=AsyncMock(side_effect=runtime.clear_sessions)
+ )
+ harness.service._resolve_opencode_provider = AsyncMock(return_value="opencode")
+ harness.service._install_opencode_api_key = AsyncMock()
+ harness.service._refresh_opencode_server = AsyncMock(side_effect=runtime.refresh)
+
+ await runner.run(
+ ScenarioStep(
+ "start_setup",
+ lambda h: h.service.start_setup(h.context, backend="opencode", force_reset=True),
+ ),
+ ScenarioStep(
+ "submit_direct_credential",
+ lambda h: h.service.maybe_consume_setup_reply(
+ h.context,
+ "oc_live_Abcdef1234567890",
+ ),
+ ),
+ ScenarioStep(
+ "next_turn_after_success",
+ lambda h: runtime.run_turn(h.context.channel_id),
+ ),
+ )
+
+ harness.service._install_opencode_api_key.assert_awaited_once_with("opencode", "oc_live_Abcdef1234567890")
+ harness.service._refresh_opencode_server.assert_awaited_once()
+ ScenarioExpect.step_history(runner, ["start_setup", "submit_direct_credential", "next_turn_after_success"])
+ ScenarioExpect.text_contains(harness, "opencode login is active again")
+ ScenarioExpect.flow_missing(harness, "C1:opencode")
+
+ async def test_timed_out_flow_allows_clean_restart_without_stale_state(self):
+ """Scenario: AUTH-SETUP-206"""
+ harness = AuthSetupScenarioHarness()
+ first_client = object()
+ second_client = object()
+ first_started = asyncio.Event()
+ first_release = asyncio.Event()
+ second_started = asyncio.Event()
+ second_release = asyncio.Event()
+ runner = ScenarioRunner(harness)
+
+ harness.service.setup_timeout_seconds = 0.01
+ harness.service._start_claude_control_flow = AsyncMock(
+ side_effect=[
+ (first_client, "https://platform.claude.com/oauth/code/callback?attempt=1"),
+ (second_client, "https://platform.claude.com/oauth/code/callback?attempt=2"),
+ ]
+ )
+
+ async def fake_control_request(client, request, timeout=900.0):
+ if request["subtype"] != "claude_oauth_wait_for_completion":
+ raise AssertionError(f"unexpected control request: {request}")
+ if client is first_client:
+ first_started.set()
+ await first_release.wait()
+ return {}
+ if client is second_client:
+ second_started.set()
+ await second_release.wait()
+ return {}
+ raise AssertionError(f"unexpected client: {client!r}")
+
+ harness.service._send_claude_control_request = AsyncMock(side_effect=fake_control_request)
+ harness.service._disconnect_claude_client = AsyncMock()
+ harness.service._verify_login = AsyncMock(return_value=(True, '{"loggedIn": true}'))
+ harness.service._refresh_backend_runtime = AsyncMock()
+
+ await runner.run(
+ ScenarioStep(
+ "start_first_setup",
+ lambda h: h.service.start_setup(
+ h.context,
+ backend="claude",
+ force_reset=True,
+ claude_login_method="console",
+ ),
+ ),
+ )
+
+ first_flow = harness.flow("claude")
+ await first_started.wait()
+ await first_flow.waiter_task
+ ScenarioExpect.flow_missing(harness, "C1:claude")
+
+ await runner.run(
+ ScenarioStep(
+ "start_second_setup",
+ lambda h: h.service.start_setup(
+ h.context,
+ backend="claude",
+ force_reset=True,
+ claude_login_method="console",
+ ),
+ ),
+ )
+
+ second_flow = harness.flow("claude")
+ await second_started.wait()
+ self.assertIsNot(first_flow, second_flow)
+ self.assertIs(second_flow.claude_client, second_client)
+ self.assertTrue(second_flow.login_prompt_sent)
+ self.assertEqual(harness.service._start_claude_control_flow.await_count, 2)
+ ScenarioExpect.step_history(runner, ["start_first_setup", "start_second_setup"])
+ ScenarioExpect.text_contains(harness, "attempt=1")
+ ScenarioExpect.text_contains(harness, "timed out")
+ ScenarioExpect.text_contains(harness, "attempt=2")
+ await harness.service._terminate_flow(second_flow)
+
+ async def test_failed_codex_setup_does_not_leave_stale_runtime_for_next_attempt(self):
+ """Scenario: AUTH-SETUP-207"""
+ harness = AuthSetupScenarioHarness()
+ first_process = FakeProcess()
+ second_process = FakeProcess()
+ runner = ScenarioRunner(harness)
+ harness.service._start_codex_process = AsyncMock(side_effect=[first_process, second_process])
+ harness.service._read_codex_output = AsyncMock(return_value=None)
+ harness.service._verify_login = AsyncMock(side_effect=[(False, "not logged in"), (True, "Logged in using ChatGPT")])
+ harness.service._refresh_backend_runtime = AsyncMock()
+
+ await runner.run(
+ ScenarioStep(
+ "start_first_setup",
+ lambda h: h.service.start_setup(h.context, backend="codex", force_reset=True),
+ ),
+ ScenarioStep(
+ "emit_first_device_url",
+ lambda h: h.service._handle_process_text(
+ h.context,
+ "codex",
+ "Open this URL to authenticate: https://auth.openai.com/codex/device?attempt=1",
+ ),
+ ),
+ )
+
+ first_flow = harness.flow("codex")
+ first_process.finish(0)
+ await first_flow.waiter_task
+ ScenarioExpect.flow_missing(harness, "C1:codex")
+ harness.service._refresh_backend_runtime.assert_not_awaited()
+
+ await runner.run(
+ ScenarioStep(
+ "start_second_setup",
+ lambda h: h.service.start_setup(h.context, backend="codex", force_reset=True),
+ ),
+ ScenarioStep(
+ "emit_second_device_url",
+ lambda h: h.service._handle_process_text(
+ h.context,
+ "codex",
+ "Open this URL to authenticate: https://auth.openai.com/codex/device?attempt=2",
+ ),
+ ),
+ )
+
+ second_flow = harness.flow("codex")
+ second_process.finish(0)
+ await second_flow.waiter_task
+
+ harness.service._refresh_backend_runtime.assert_awaited_once_with("codex")
+ ScenarioExpect.step_history(
+ runner,
+ ["start_first_setup", "emit_first_device_url", "start_second_setup", "emit_second_device_url"],
+ )
+ ScenarioExpect.text_contains(harness, "not logged in")
+ ScenarioExpect.text_contains(harness, "codex login is active again")
+ ScenarioExpect.flow_missing(harness, "C1:codex")
+
async def test_opencode_waiting_key_scenario_ignores_plain_chat(self):
"""Scenario: AUTH-SETUP-101"""
harness = AuthSetupScenarioHarness()
diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.py
index f2e4387dc..f0501e008 100644
--- a/tests/test_claude_agent_sessions.py
+++ b/tests/test_claude_agent_sessions.py
@@ -281,6 +281,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn(composite_key, controller.claude_sessions)
async def test_assistant_auth_error_without_is_api_error_flag_still_triggers_recovery(self):
+ """Scenario: AUTH-SETUP-902"""
controller = _StubController()
controller.agent_auth_service.maybe_emit_auth_recovery_message = AsyncMock(return_value=True)
controller._get_session_key = lambda context: "telegram::user::U1"
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index f20af5334..89f089a21 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -261,6 +261,7 @@
"opencodeInstructions": "OpenCode setup started for `{provider}`.\n\nOpen this page to create or retrieve a credential:\n{url}\n\nWhen you get the key, reply with it directly in this chat.",
"opencodeCodePrompt": "OpenCode is waiting for the `{provider}` API key. Reply with the key directly in this chat.",
"opencodeCodeRetryPrompt": "OpenCode is still waiting for the `{provider}` API key. The previous value may not have been accepted. Reply with the key directly in this chat.",
+ "timedOut": "{backend} setup timed out. Start setup again to retry.",
"success": "{backend} login is active again.",
"failed": "{backend} setup failed: {detail}",
"unknownFailure": "Unknown login failure."
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index e4798d7ce..4ff117c7e 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -261,6 +261,7 @@
"opencodeInstructions": "OpenCode 的 `{provider}` 认证修复已开始。\n\n请打开下面这个页面创建或获取凭据:\n{url}\n\n拿到 key 之后,直接在当前聊天里回复即可。",
"opencodeCodePrompt": "OpenCode 正在等待 `{provider}` 的 API key。请直接在当前聊天里回复 key。",
"opencodeCodeRetryPrompt": "OpenCode 仍在等待 `{provider}` 的 API key,上一条值可能没有被接受。请直接在当前聊天里回复 key。",
+ "timedOut": "{backend} 登录修复已超时,请重新发起 setup 再试一次。",
"success": "{backend} 已重新登录,可继续使用。",
"failed": "{backend} 登录修复失败:{detail}",
"unknownFailure": "未知登录失败。"