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(opencode): show provider test excerpts (#487)

Call Whited18109035d8d
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 203eaf2a1..aecbc26f4 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -21,6 +21,7 @@ from modules.claude_sdk_compat import (
ClaudeSDKClient,
)
from modules.agents.catalog import WEB_OAUTH_BACKENDS
+from modules.agents.opencode.message_processor import extract_opencode_response_text
from modules.im import InlineButton, InlineKeyboard, MessageContext
from vibe.i18n import t as i18n_t
from vibe.opencode_config import remove_opencode_provider_api_key
@@ -2129,16 +2130,10 @@ class AgentAuthService:
if terminal is not None:
if error_payload:
break
- parts = terminal.get("parts") or []
- pieces: list[str] = []
- for part in parts:
- if not isinstance(part, dict):
- continue
- if part.get("type") == "text":
- text_val = part.get("text") or ""
- if isinstance(text_val, str) and text_val.strip():
- pieces.append(text_val.strip())
- final_text = "\n\n".join(pieces).strip()
+ final_text = extract_opencode_response_text(
+ terminal,
+ allow_non_text_fallback=True,
+ )
break
await asyncio.sleep(poll_interval)
else:
diff --git a/modules/agents/opencode/message_processor.py b/modules/agents/opencode/message_processor.py
index 8c08950ba..bc1900600 100644
--- a/modules/agents/opencode/message_processor.py
+++ b/modules/agents/opencode/message_processor.py
@@ -4,35 +4,61 @@ from __future__ import annotations
import logging
import os
-from typing import Any, Dict
+from typing import Any, Dict, Mapping
logger = logging.getLogger(__name__)
+def extract_opencode_response_text(
+ response: Mapping[str, Any],
+ *,
+ allow_non_text_fallback: bool = False,
+) -> str:
+ """Extract user-visible assistant text from an OpenCode message."""
+ parts = response.get("parts", [])
+ text_parts: list[str] = []
+ fallback_parts: list[str] = []
+
+ if not isinstance(parts, list):
+ return ""
+
+ for part in parts:
+ if not isinstance(part, dict):
+ continue
+ text = part.get("text")
+ if not isinstance(text, str) or not text.strip():
+ continue
+ cleaned = text.strip()
+ if part.get("type") == "text":
+ text_parts.append(cleaned)
+ else:
+ fallback_parts.append(cleaned)
+
+ if text_parts:
+ return "\n\n".join(text_parts).strip()
+ if allow_non_text_fallback:
+ return "\n\n".join(fallback_parts).strip()
+ return ""
+
+
class OpenCodeMessageProcessorMixin:
"""Pure-ish helpers that depend only on instance config."""
def _extract_response_text(self, response: Dict[str, Any]) -> str:
+ text = extract_opencode_response_text(response)
parts = response.get("parts", [])
- text_parts = []
-
- for part in parts:
- part_type = part.get("type")
- if part_type == "text":
- text = part.get("text", "")
- if text:
- text_parts.append(text)
- if not text_parts and parts:
- part_types = [p.get("type") for p in parts]
+ if not text and isinstance(parts, list) and parts:
+ part_types = [p.get("type") for p in parts if isinstance(p, dict)]
msg_id = response.get("info", {}).get("id", "unknown")
logger.info(
- "OpenCode message %s has no text parts; part types: %s",
+ "OpenCode message %s has no extractable text; part types: %s",
msg_id,
part_types,
)
- return "\n\n".join(text_parts).strip()
+ return text
+
def _to_relative_path(self, abs_path: str, cwd: str) -> str:
"""Convert absolute file paths to relative paths under cwd."""
diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.py
index dd3f35b0c..84216dc7b 100644
--- a/tests/test_web_oauth_flow.py
+++ b/tests/test_web_oauth_flow.py
@@ -11,11 +11,13 @@ into ``_web_flows`` and mocking ``_send_claude_callback``.
from __future__ import annotations
import asyncio
+import os
from unittest.mock import AsyncMock
import pytest
from core.agent_auth_service import AgentAuthService, WebAuthFlow
+from modules.agents.opencode.message_processor import extract_opencode_response_text
class _Backend:
@@ -51,6 +53,23 @@ def _run(coro):
return asyncio.get_event_loop_policy().new_event_loop().run_until_complete(coro)
+def test_opencode_message_text_extractor_ignores_non_text_by_default() -> None:
+ message = {
+ "parts": [
+ {
+ "type": "reasoning",
+ "text": "internal chain-of-thought-ish content",
+ }
+ ]
+ }
+
+ assert extract_opencode_response_text(message) == ""
+ assert (
+ extract_opencode_response_text(message, allow_non_text_fallback=True)
+ == "internal chain-of-thought-ish content"
+ )
+
+
def test_unsupported_backend_raises(service: AgentAuthService) -> None:
with pytest.raises(ValueError, match="unsupported_backend"):
_run(service.start_web_setup("gemini"))
@@ -264,10 +283,32 @@ class _FakeOpencodeServer:
self.wait_future: asyncio.Future = asyncio.get_event_loop_policy().new_event_loop().create_future()
self.start_calls: list[tuple[str, int, dict]] = []
self.wait_calls: list[tuple[str, int, dict]] = []
+ self.catalog: dict = {}
+ self.created_session: dict = {"info": {"id": "sess_probe"}}
+ self.messages: list[dict] = []
+ self.sent_messages: list[tuple[str, str, str, dict | None]] = []
+ self.abort_calls: list[tuple[str, str]] = []
+ self.message_sent = False
async def get_provider_auth(self):
return self.auth_map
+ async def get_available_models(self, _directory):
+ return self.catalog
+
+ async def create_session(self, _directory, *, title):
+ return self.created_session
+
+ async def list_messages(self, _session_id, _directory):
+ return self.messages if self.message_sent else []
+
+ async def send_message(self, session_id, directory, content, *, model=None):
+ self.sent_messages.append((session_id, directory, content, model))
+ self.message_sent = True
+
+ async def abort_session(self, session_id, directory):
+ self.abort_calls.append((session_id, directory))
+
async def start_provider_oauth(self, provider_id, *, method, prompt_answers):
self.start_calls.append((provider_id, method, prompt_answers))
return self.next_authorize
@@ -392,6 +433,48 @@ def test_opencode_oauth_success_clears_provider_options_key(
assert flow.state == "success"
+def test_opencode_provider_test_returns_excerpt_from_non_text_part(
+ service: AgentAuthService, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ fake = _FakeOpencodeServer()
+ fake.catalog = {
+ "providers": [
+ {
+ "id": "anthropic",
+ "models": {"claude-opus-4.8": {}},
+ }
+ ]
+ }
+ fake.messages = [
+ {
+ "info": {
+ "id": "msg_assistant",
+ "role": "assistant",
+ "time": {"completed": 123},
+ },
+ "parts": [
+ {
+ "type": "reasoning",
+ "id": "part_reasoning",
+ "text": "Hello from a non-text OpenCode part",
+ }
+ ],
+ }
+ ]
+ monkeypatch.setattr(service, "_opencode_server", AsyncMock(return_value=fake))
+
+ result = _run(service.test_opencode_provider("anthropic"))
+
+ assert result["ok"] is True
+ assert result["model"] == "claude-opus-4.8"
+ assert result["excerpt"] == "Hello from a non-text OpenCode part"
+ assert fake.sent_messages[-1][3] == {
+ "providerID": "anthropic",
+ "modelID": "claude-opus-4.8",
+ }
+ assert fake.abort_calls == [("sess_probe", os.path.expanduser("~"))]
+
+
def test_remove_web_auth_rejects_unsupported_backend(service: AgentAuthService) -> None:
# OpenCode joined ``WEB_BACKENDS`` for OAuth, but ``remove_web_auth``
# is claude / codex specific — opencode providers use the