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): avoid repeated model control requests

cyh195b1f81f498
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index ea53d025b..79500b182 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -73,6 +73,24 @@ class SessionHandler(BaseHandler):
setattr(client, "_vibe_runtime_base_session_id", base_session_id)
setattr(client, "_vibe_runtime_session_key", composite_key)
+ async def _set_claude_model_if_needed(self, client: ClaudeSDKClient, desired_model: Optional[str]) -> None:
+ unknown = object()
+ current_model = getattr(client, "_vibe_current_model", unknown)
+ if current_model is not unknown and current_model == desired_model:
+ return
+
+ if current_model is unknown and desired_model is None:
+ setattr(client, "_vibe_current_model", None)
+ return
+
+ set_model = getattr(client, "set_model", None)
+ if not callable(set_model):
+ logger.warning("Claude SDK client does not support model switching")
+ return
+
+ await set_model(desired_model)
+ setattr(client, "_vibe_current_model", desired_model)
+
def get_base_session_id(self, context: MessageContext, source: str = "human") -> str:
"""Get base session ID based on platform and context (without path)"""
platform = self._get_context_platform(context)
@@ -399,11 +417,11 @@ class SessionHandler(BaseHandler):
if composite_key in self.claude_sessions and not effective_agent:
client = self.claude_sessions[composite_key]
- # Apply current model from routing on every request, consistent with
- # how OpenCode/Codex pass the model on each prompt/turn call.
+ # Claude SDK model changes are control requests; only send one when
+ # the effective model actually changes.
current_model = explicit_model or self.config.claude.default_model
try:
- await client.set_model(current_model)
+ await self._set_claude_model_if_needed(client, current_model)
except Exception as e:
logger.warning(f"Failed to update model on cached Claude session: {e}")
logger.info(
@@ -423,13 +441,11 @@ class SessionHandler(BaseHandler):
)
if cached_key in self.claude_sessions:
client = self.claude_sessions[cached_key]
- # Apply explicit model override from routing/subagent params,
- # consistent with how OpenCode/Codex pass the model per request.
- # When no explicit override, keep the agent frontmatter model
+ # When no explicit override, keep the agent/frontmatter model
# that was set at session creation.
if explicit_model:
try:
- await client.set_model(explicit_model)
+ await self._set_claude_model_if_needed(client, explicit_model)
except Exception as e:
logger.warning(f"Failed to update model on cached Claude subagent session: {e}")
logger.info(
@@ -613,6 +629,7 @@ class SessionHandler(BaseHandler):
raise
self.claude_sessions[composite_key] = client
+ setattr(client, "_vibe_current_model", effective_model)
self.bind_claude_runtime_session(client, base_session_id, composite_key)
self.touch_session_activity(composite_key)
logger.info(f"Created new Claude SDK client for {base_session_id} at {working_path}")
diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.py
index 0cdb4da74..f1178368d 100644
--- a/tests/test_claude_cli_path.py
+++ b/tests/test_claude_cli_path.py
@@ -163,6 +163,100 @@ def test_session_handler_keeps_sdk_default_for_default_claude_binary(monkeypatch
assert captured["options"].cli_path is None
+def test_session_handler_does_not_repeat_claude_model_control_request(monkeypatch, tmp_path: Path) -> None:
+ captured: dict[str, Any] = {"clients": []}
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ captured["options"] = options
+ captured["clients"].append(self)
+ self.model_calls = []
+
+ async def connect(self) -> None:
+ captured["connected"] = True
+
+ async def set_model(self, model) -> None:
+ self.model_calls.append(model)
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+
+ controller = _Controller(tmp_path)
+ controller.config.claude.default_model = "claude-sonnet-4-5"
+ handler = SessionHandler(controller)
+ context = MessageContext(user_id="U123", channel_id="C123")
+
+ first_client = _run_session(handler, context)
+ second_client = _run_session(handler, context)
+
+ assert first_client is second_client
+ assert len(captured["clients"]) == 1
+ assert captured["options"].extra_args == {"model": "claude-sonnet-4-5"}
+ assert first_client.model_calls == []
+
+
+def test_session_handler_updates_cached_claude_model_only_when_changed(monkeypatch, tmp_path: Path) -> None:
+ captured: dict[str, Any] = {}
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ captured["options"] = options
+ self.model_calls = []
+
+ async def connect(self) -> None:
+ captured["connected"] = True
+
+ async def set_model(self, model) -> None:
+ self.model_calls.append(model)
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+
+ controller = _Controller(tmp_path)
+ controller.config.claude.default_model = "claude-sonnet-4-5"
+ handler = SessionHandler(controller)
+ context = MessageContext(user_id="U123", channel_id="C123")
+
+ client = _run_session(handler, context)
+ controller.config.claude.default_model = "claude-opus-4-1"
+
+ _run_session(handler, context)
+ _run_session(handler, context)
+
+ assert client.model_calls == ["claude-opus-4-1"]
+
+
+def test_session_handler_does_not_send_none_model_control_request_for_cached_default(
+ monkeypatch,
+ tmp_path: Path,
+) -> None:
+ captured: dict[str, Any] = {}
+
+ class _StubClaudeSDKClient:
+ def __init__(self, options):
+ captured["options"] = options
+ self.model_calls = []
+
+ async def connect(self) -> None:
+ captured["connected"] = True
+
+ async def set_model(self, model) -> None:
+ self.model_calls.append(model)
+
+ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)
+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)
+
+ controller = _Controller(tmp_path)
+ handler = SessionHandler(controller)
+ context = MessageContext(user_id="U123", channel_id="C123")
+
+ client = _run_session(handler, context)
+ _run_session(handler, context)
+
+ assert captured["options"].extra_args == {}
+ assert client.model_calls == []
+
+
def test_session_handler_passes_non_default_claude_command_name(monkeypatch, tmp_path: Path) -> None:
captured: dict[str, Any] = {}