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(codex): rebind resumed threads after auth changes (#1112)

Call Whitef17feab03e4e
diff --git a/config/v2_compat.py b/config/v2_compat.py
index 980f2ad49..3a4798d73 100644
--- a/config/v2_compat.py
+++ b/config/v2_compat.py
@@ -45,6 +45,7 @@ class CodexCompatConfig:
extra_args: list[str]
default_model: Optional[str] = None
idle_timeout_seconds: int = DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS
+ auth_mode: str = "oauth"
@dataclass
@@ -123,6 +124,7 @@ def to_app_config(v2: V2Config) -> AppCompatConfig:
extra_args=[],
default_model=v2.agents.codex.default_model,
idle_timeout_seconds=v2.agents.codex.idle_timeout_seconds,
+ auth_mode=v2.agents.codex.auth_mode,
)
opencode = None
if v2.agents.opencode.enabled:
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 5498aed14..68d80e9c4 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -891,7 +891,7 @@ class AgentAuthService:
output: MessageOutput | None = None,
terminal_error: str | None = None,
) -> bool:
- """Emit a reset-oauth button when the backend error is auth-related.
+ """Emit the recovery action appropriate for an auth-related error.
Each backend error-emit site calls this FIRST and emits its own failure
path only when this returns ``False``. When this DOES handle the error,
@@ -902,26 +902,39 @@ class AgentAuthService:
if not classify_auth_error(backend, error_text):
return False
- recovery_text = f"{error_text}\n\n{self._t('command.setup.resetPrompt', backend=backend)}"
- await self._send_message_with_button(
- context,
- recovery_text,
- button_text=self._t("button.resetOAuth"),
- callback_data=f"auth_setup:{backend}",
+ backend_config = self._resolve_backend_config(backend)
+ uses_codex_api_key = (
+ backend == "codex"
+ and getattr(backend_config, "auth_mode", None) == "api_key"
)
- # The IM send above goes through ``send_message_with_buttons``, which is NOT
- # a durable ``messages`` row, and the web Chat renders only durable rows —
- # so persist the recovery text (error + reset instruction) HERE, the single
- # home for it, rather than each backend persisting an error-only copy that
- # drops the actionable reset prompt (Codex P2). No-op for contexts without
- # a resolvable scope (persist_agent_message guards internally).
+ if uses_codex_api_key:
+ recovery_text = f"{error_text}\n\n{self._t('command.setup.apiKeyRecoveryPrompt', backend=backend)}"
+ await self._send_message(context, recovery_text)
+ else:
+ recovery_text = f"{error_text}\n\n{self._t('command.setup.resetPrompt', backend=backend)}"
+ await self._send_message_with_button(
+ context,
+ recovery_text,
+ button_text=self._t("button.resetOAuth"),
+ callback_data=f"auth_setup:{backend}",
+ )
+ # Transport sends are not durable ``messages`` rows, and the web Chat
+ # renders only durable rows. Persist the recovery text here, the single
+ # home for it, rather than letting each backend store an error-only copy
+ # that drops the actionable recovery prompt. No-op for contexts without a
+ # resolvable scope (persist_agent_message guards internally).
#
# The durable row has NO inline button, so persist a BUTTON-FREE variant:
# ``resetPrompt`` says "use the button below", which is a dangling
# instruction on the workbench Chat. Point at the cross-platform
# ``/setup {backend}`` command instead so the persisted copy is actionable
# everywhere (Codex P2).
- durable_text = f"{error_text}\n\n{self._t('command.setup.resetPromptPlain', backend=backend)}"
+ durable_prompt = (
+ self._t("command.setup.apiKeyRecoveryPrompt", backend=backend)
+ if uses_codex_api_key
+ else self._t("command.setup.resetPromptPlain", backend=backend)
+ )
+ durable_text = f"{error_text}\n\n{durable_prompt}"
try:
from core.message_mirror import persist_agent_message
diff --git a/docs/plans/codex-provider-rebind.md b/docs/plans/codex-provider-rebind.md
new file mode 100644
index 000000000..0199be126
--- /dev/null
+++ b/docs/plans/codex-provider-rebind.md
@@ -0,0 +1,33 @@
+# Codex Provider Rebinding
+
+## Background
+
+Codex persists the provider id on each native thread. Avibe previously compared
+only that id when deciding whether `thread/resume` needed a provider override.
+That is insufficient because Avibe deliberately reuses `openai-managed` while
+switching its definition between ChatGPT OAuth and API-key/custom-base-URL
+configurations. A legacy thread and the current runtime can therefore have the
+same provider id but incompatible routing.
+
+## Goal
+
+Resume an existing Codex thread against the current Avibe-managed provider
+definition without changing the thread's user-visible Avibe Session identity.
+Keep API-key recovery guidance distinct from OAuth recovery guidance.
+
+## Solution
+
+1. Keep the existing provider-id transition rule.
+2. When a persisted thread is first resumed in a fresh Codex app-server,
+ explicitly rebind Avibe-managed providers even when the provider id matches.
+ Settings saves already refresh the Codex runtime, so this makes the new
+ provider definition authoritative without adding migration state.
+3. For Codex API-key mode, report a key/base-URL recovery action instead of
+ offering an OAuth reset.
+
+## Verification
+
+- Focused unit coverage for same-id managed-provider rebinding.
+- A closed-loop auth scenario covering OAuth-era native thread resume after an
+ API-key/custom-base-URL switch.
+- Existing provider-transition, model-preservation, and auth recovery tests.
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index 2faca1623..9ff62c57c 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -43,6 +43,9 @@ if TYPE_CHECKING:
_CODEX_MANAGED_PROVIDER_IDS = frozenset((MANAGED_PROVIDER_ID, *LEGACY_MANAGED_PROVIDER_IDS))
_CODEX_MODEL_HUB_PROVIDER_ID = "avibe_model_hub"
_CODEX_DEFAULT_PROVIDER_ID = "openai"
+_CODEX_REBINDABLE_SAME_ID_PROVIDERS = _CODEX_MANAGED_PROVIDER_IDS | frozenset(
+ (_CODEX_MODEL_HUB_PROVIDER_ID,)
+)
CODEX_CALLER_ENV_DIR = "codex-caller-env"
@@ -1213,7 +1216,12 @@ class CodexAgent(BaseAgent):
resume_params,
request,
)
- model_provider = await self._resolve_resume_model_provider_override(transport, request, persisted)
+ model_provider = await self._resolve_resume_model_provider_override(
+ transport,
+ request,
+ persisted,
+ rebind_same_provider=True,
+ )
if model_provider:
resume_params["modelProvider"] = model_provider
resp = await transport.send_request(
@@ -1279,15 +1287,17 @@ class CodexAgent(BaseAgent):
transport: CodexTransport,
request: AgentRequest,
thread_id: str,
+ *,
+ rebind_same_provider: bool = False,
) -> Optional[str]:
"""Return a provider override only when a persisted thread is stale.
Codex preserves a thread's latest model / reasoning effort on resume
unless the client sends a model/provider override. Vibe Remote only
- needs to override the provider after the user changes Codex auth mode
- between Vibe Remote-managed OAuth/API-key providers, so inspect the
- stored thread first and leave normal resumes on Codex's persisted
- fallback path.
+ overrides transitions between managed providers. A persisted thread's
+ first resume in a fresh app-server also rebinds Avibe-managed same-id
+ providers, because OAuth and API-key/custom-base-URL configurations
+ deliberately reuse ``openai-managed``.
"""
current_provider = await self._read_effective_model_provider(transport, request)
if not current_provider:
@@ -1314,6 +1324,8 @@ class CodexAgent(BaseAgent):
stored_provider = stored_provider.strip()
if stored_provider == current_provider:
+ if rebind_same_provider and current_provider in _CODEX_REBINDABLE_SAME_ID_PROVIDERS:
+ return current_provider
return None
if not self._is_managed_provider_transition(stored_provider, current_provider):
return None
diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yaml
index 10ec6fd1d..dbaaede30 100644
--- a/tests/scenarios/auth_setup/catalog.yaml
+++ b/tests/scenarios/auth_setup/catalog.yaml
@@ -155,5 +155,12 @@ scenarios:
layer: scenario_backed_runtime
backend: claude
test: tests/test_claude_agent_sessions.py::test_assistant_auth_error_without_is_api_error_flag_still_triggers_recovery
+ - id: AUTH-SETUP-903
+ name: Legacy Codex thread rebinds after API-key endpoint switch
+ status: covered
+ kind: historical_regression
+ layer: scenario
+ backend: codex
+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_legacy_codex_thread_rebinds_once_after_api_key_endpoint_switch
next_priority:
- AUTH-SETUP-301
diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
index 3f833fac4..f1da014af 100644
--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py
@@ -15,6 +15,7 @@ from config.v2_config import (
ModelHubSourceStateConfig,
)
from core.handlers.model_hub.service import ModelHubError
+from modules.agents.codex.agent import CodexAgent
from tests.scenario_harness.auth_setup import AuthSetupScenarioHarness, FakeProcess
from tests.scenario_harness.core import ScenarioExpect, ScenarioRunner, ScenarioStep
from tests.scenario_harness.model_hub_native_oauth import NativeOAuthScenarioHarness
@@ -49,7 +50,88 @@ class _FakeCodexNextTurnRuntime:
return "turn-ok"
+class _CodexProviderBindingSessions:
+ def get_agent_session_id(self, *_args, **_kwargs):
+ return "thread-existing"
+
+ def ensure_agent_session_id(self, *_args, **_kwargs):
+ return "ses-provider"
+
+ def bind_agent_session(self, *_args, **_kwargs):
+ return "ses-provider"
+
+
class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):
+ async def test_legacy_codex_thread_rebinds_once_after_api_key_endpoint_switch(self):
+ """Scenario: AUTH-SETUP-903"""
+ agent = object.__new__(CodexAgent)
+ agent.controller = SimpleNamespace(
+ config=SimpleNamespace(platform="avibe", reply_enhancements=True)
+ )
+ agent.codex_config = SimpleNamespace(
+ default_model=None,
+ auth_mode="api_key",
+ base_url="https://relay.example/v1",
+ )
+ agent.sessions = _CodexProviderBindingSessions()
+ agent._session_mgr = SimpleNamespace(set_thread_id=lambda *_args: None)
+ agent._build_thread_developer_instructions = lambda _request: None
+ request = SimpleNamespace(
+ working_path="/tmp/work",
+ context=SimpleNamespace(
+ platform="avibe",
+ platform_specific={},
+ user_id="U1",
+ channel_id="C1",
+ thread_id=None,
+ ),
+ base_session_id="base-provider",
+ session_key="avibe::project::provider",
+ subagent_name=None,
+ subagent_model=None,
+ subagent_reasoning_effort=None,
+ vibe_agent_id=None,
+ vibe_agent_name=None,
+ )
+ provider_config = {
+ "name": "OpenAI",
+ "base_url": "https://relay.example/v1",
+ "wire_api": "responses",
+ "requires_openai_auth": True,
+ "supports_websockets": False,
+ }
+
+ calls = []
+
+ async def send_request(method, params):
+ calls.append((method, params))
+ if method == "config/read":
+ return {
+ "config": {
+ "model_provider": "openai-managed",
+ "model_providers": {"openai-managed": provider_config},
+ }
+ }
+ if method == "thread/read":
+ return {
+ "thread": {
+ "id": "thread-existing",
+ "modelProvider": "openai-managed",
+ }
+ }
+ if method == "thread/resume":
+ return {"thread": {"id": "thread-existing"}}
+ raise AssertionError(f"Unexpected Codex request: {method}")
+
+ thread_id = await agent._start_or_resume_thread(
+ SimpleNamespace(send_request=send_request),
+ request,
+ )
+
+ self.assertEqual(thread_id, "thread-existing")
+ resume = next(params for method, params in calls if method == "thread/resume")
+ self.assertEqual(resume["modelProvider"], "openai-managed")
+
async def test_native_model_hub_reauth_confirms_before_honest_failure(self):
"""Scenario: AUTH-SETUP-106"""
state_dir = tempfile.TemporaryDirectory()
diff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.py
index 91628b5fa..2abcf5e1b 100644
--- a/tests/test_agent_auth_service.py
+++ b/tests/test_agent_auth_service.py
@@ -70,7 +70,7 @@ class _StubConfig(SimpleNamespace):
platform="slack",
language="en",
agents=SimpleNamespace(
- codex=SimpleNamespace(cli_path="codex"),
+ codex=SimpleNamespace(cli_path="codex", auth_mode="oauth"),
claude=SimpleNamespace(cli_path="claude"),
opencode=SimpleNamespace(cli_path="opencode"),
),
@@ -224,6 +224,41 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
terminal_error="❌ Codex error: 401 Unauthorized",
)
+ async def test_codex_api_key_auth_error_points_to_key_settings_without_oauth_button(self):
+ from config.v2_compat import to_app_config
+ from config.v2_config import AgentsConfig, RuntimeConfig, SlackConfig, V2Config
+
+ controller = _StubController()
+ v2_config = V2Config(
+ mode="self_host",
+ version="v2",
+ slack=SlackConfig(),
+ runtime=RuntimeConfig(default_cwd="."),
+ agents=AgentsConfig(),
+ )
+ v2_config.agents.codex.auth_mode = "api_key"
+ controller.config = to_app_config(v2_config)
+ service = AgentAuthService(controller)
+ context = MessageContext(user_id="U1", channel_id="C1")
+
+ with patch("core.message_mirror.persist_agent_message") as persist:
+ handled = await service.maybe_emit_auth_recovery_message(
+ context,
+ "codex",
+ "❌ Codex error: 401 Unauthorized",
+ )
+
+ self.assertTrue(handled)
+ self.assertEqual(controller.im_client.sent_button_messages, [])
+ self.assertEqual(len(controller.im_client.sent_messages), 1)
+ _, text = controller.im_client.sent_messages[0]
+ self.assertIn("API key", text)
+ self.assertIn("Base URL", text)
+ self.assertNotIn("OAuth", text)
+ persisted_text = persist.call_args.args[2]
+ self.assertIn("API key", persisted_text)
+ self.assertNotIn("/setup codex", persisted_text)
+
async def test_maybe_emit_auth_recovery_message_defers_non_auth_error_to_caller(self):
# A NON-auth terminal error returns False: the calling backend emits its
# OWN terminal error result (which settles the dot via the same outbound
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index 4866bed09..77bba17d5 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -1422,10 +1422,14 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertIn("Current session id: `sesk8m4q2p7x`", developer_instructions)
self.assertNotIn("Channel-level session key:", developer_instructions)
- async def test_resume_thread_does_not_force_model_provider_when_thread_matches_config(self):
+ async def test_resume_thread_rebinds_managed_provider_when_thread_id_matches_config(self):
agent = object.__new__(CodexAgent)
agent.controller = SimpleNamespace(config=SimpleNamespace(platform="slack", reply_enhancements=True))
- agent.codex_config = SimpleNamespace(default_model=None)
+ agent.codex_config = SimpleNamespace(
+ default_model=None,
+ auth_mode="api_key",
+ base_url="https://relay.example/v1",
+ )
agent._session_mgr = SimpleNamespace(set_thread_id=Mock())
agent.sessions = SimpleNamespace(
get_agent_session_id=Mock(return_value="thread-existing"),
@@ -1464,7 +1468,7 @@ class CodexAgentPayloadTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(transport.send_request.await_args_list[1].args[0], "thread/read")
method, params = transport.send_request.await_args_list[2].args
self.assertEqual(method, "thread/resume")
- self.assertNotIn("modelProvider", params)
+ self.assertEqual(params["modelProvider"], "openai-managed")
async def test_resume_thread_overrides_stale_session_model_provider(self):
agent = object.__new__(CodexAgent)
diff --git a/tests/test_v2_compat_platforms.py b/tests/test_v2_compat_platforms.py
index 1e075c570..fc7f4ce6d 100644
--- a/tests/test_v2_compat_platforms.py
+++ b/tests/test_v2_compat_platforms.py
@@ -142,3 +142,19 @@ def test_to_app_config_exposes_opencode_default_model_fields() -> None:
assert compat.opencode.default_model == "gpt-5.4"
assert compat.opencode.default_reasoning_effort == "high"
assert compat.opencode.default_provider == "openai"
+
+
+def test_to_app_config_exposes_codex_auth_mode() -> None:
+ config = V2Config(
+ mode="self_host",
+ version="v2",
+ slack=SlackConfig(),
+ runtime=RuntimeConfig(default_cwd="."),
+ agents=AgentsConfig(),
+ )
+ config.agents.codex.auth_mode = "api_key"
+
+ compat = to_app_config(config)
+
+ assert compat.codex is not None
+ assert compat.codex.auth_mode == "api_key"
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 5c4156369..a7d3685a4 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -395,6 +395,7 @@
"claudeMethodFallback": "Choose a Claude sign-in source with `/setup claude claudeai` or `/setup claude console`.",
"resetPrompt": "{backend} looks logged out. Use the button below to restart OAuth setup.",
"resetPromptPlain": "{backend} looks logged out. Run `/setup {backend}` to restart OAuth setup.",
+ "apiKeyRecoveryPrompt": "{backend} rejected the configured API key. Check the API key and Base URL in Settings, save them, and retry.",
"manualFallback": "If inline buttons are unavailable, run `/setup {backend}`.",
"codexInstructions": "Codex setup started.\n\n1. Open this URL in your browser:\n{url}\n\n2. Enter this one-time code:\n`{code}`\n\nThe bot will keep waiting here and confirm when login finishes.",
"claudeInstructions": "Claude setup started.\n\nOpen this URL in your browser and finish the login flow:\n{url}\n\nWhen the browser callback page shows the final `authorizationCode#state` value, send it back directly in this chat.",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 78468f401..86c19a290 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -395,6 +395,7 @@
"claudeMethodFallback": "如果当前平台不支持按钮,请执行 `/setup claude claudeai` 或 `/setup claude console`。",
"resetPrompt": "{backend} 看起来已经掉线了。请点击下面的按钮重新发起 OAuth 登录。",
"resetPromptPlain": "{backend} 看起来已经掉线了。请发送 `/setup {backend}` 重新发起 OAuth 登录。",
+ "apiKeyRecoveryPrompt": "{backend} 拒绝了当前配置的 API Key。请在设置中检查 API Key 和 Base URL,保存后重试。",
"manualFallback": "如果当前平台不支持按钮,请执行 `/setup {backend}`。",
"codexInstructions": "Codex 登录修复已开始。\n\n1. 在浏览器打开这个地址:\n{url}\n\n2. 输入这个一次性验证码:\n`{code}`\n\nBot 会继续等待,并在登录完成后回消息确认。",
"claudeInstructions": "Claude 登录修复已开始。\n\n请在浏览器打开下面的地址并完成登录:\n{url}\n\n浏览器回调页面会显示最终的 `authorizationCode#state`,请直接把它发回当前聊天。",