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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(opencode): preserve invalid config files
cyh2c0ec4cf7aa8
diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.pyindex 33ba12037..87a983423 100644--- a/modules/agents/opencode/server.py+++ b/modules/agents/opencode/server.py@@ -645,8 +645,8 @@ class OpenCodeServerManager:Returns:Parsed config dict, or None if file doesn't exist or is invalid."""- config, _ = load_first_opencode_user_config(logger_instance=logger)- return config+ probe = load_first_opencode_user_config(logger_instance=logger)+ return probe.configdef _get_agent_config(self, config: Dict[str, Any], agent_name: Optional[str]) -> Dict[str, Any]:"""Get agent-specific config from opencode.json with type safety."""diff --git a/tests/test_ui_api.py b/tests/test_ui_api.pyindex d4b411a2a..4a6a06c2f 100644--- a/tests/test_ui_api.py+++ b/tests/test_ui_api.py@@ -235,6 +235,50 @@ def test_setup_opencode_permission_accepts_jsonc_config(monkeypatch, tmp_path):}+def test_setup_opencode_permission_does_not_overwrite_invalid_existing_config(monkeypatch, tmp_path):+ config_path = tmp_path / ".config" / "opencode" / "opencode.json"+ config_path.parent.mkdir(parents=True, exist_ok=True)+ original = '{\n "model": "openai/gpt-5",\n'+ config_path.write_text(original, encoding="utf-8")++ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)++ result = api.setup_opencode_permission()++ assert result["ok"] is False+ assert result["config_path"] == str(config_path)+ assert "could not be parsed" in result["message"]+ assert config_path.read_text(encoding="utf-8") == original+++def test_setup_opencode_permission_skips_comment_only_file_and_uses_next_valid_path(monkeypatch, tmp_path):+ xdg_path = tmp_path / ".config" / "opencode" / "opencode.json"+ legacy_path = tmp_path / ".opencode" / "opencode.json"+ xdg_path.parent.mkdir(parents=True, exist_ok=True)+ legacy_path.parent.mkdir(parents=True, exist_ok=True)+ xdg_path.write_text("// placeholder only\n", encoding="utf-8")+ legacy_path.write_text(+ """{+ "model": "openai/gpt-5",+}+""",+ encoding="utf-8",+ )++ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)++ result = api.setup_opencode_permission()+ updated = json.loads(legacy_path.read_text(encoding="utf-8"))++ assert result["ok"] is True+ assert result["config_path"] == str(legacy_path)+ assert xdg_path.read_text(encoding="utf-8") == "// placeholder only\n"+ assert updated == {+ "model": "openai/gpt-5",+ "permission": "allow",+ }++def test_parse_jsonc_object_preserves_comment_markers_inside_strings():parsed = parse_jsonc_object("""{diff --git a/vibe/api.py b/vibe/api.pyindex 06e455f06..6c8418749 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -706,27 +706,38 @@ def setup_opencode_permission() -> dict:3. Create new file at ~/.config/opencode/opencode.json (XDG standard)Mirrors _load_opencode_user_config behavior: skips invalid files and tries next.+ If config files exist but none can be parsed, returns an error instead of+ overwriting the existing file contents.Returns:{"ok": bool, "message": str, "config_path": str}"""config_paths = get_opencode_config_paths(Path.home())- config, config_path = load_first_opencode_user_config(home=Path.home(), logger_instance=logger)+ probe = load_first_opencode_user_config(home=Path.home(), logger_instance=logger)- if config is not None and config_path is not None:- if config.get("permission") == "allow":+ if probe.config is not None and probe.path is not None:+ if probe.config.get("permission") == "allow":return {"ok": True,"message": "Permission already set",- "config_path": str(config_path),+ "config_path": str(probe.path),}- config["permission"] = "allow"- config_path.write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")+ probe.config["permission"] = "allow"+ probe.path.write_text(json.dumps(probe.config, indent=2) + "\n", encoding="utf-8")return {"ok": True,"message": "Permission set to 'allow'",- "config_path": str(config_path),+ "config_path": str(probe.path),+ }++ if probe.existing_paths:+ error_path, error_message = probe.errors[0] if probe.errors else (probe.existing_paths[0], "unknown parse error")+ logger.error(f"Refusing to overwrite invalid OpenCode config at {error_path}: {error_message}")+ return {+ "ok": False,+ "message": f"Existing OpenCode config could not be parsed: {error_message}",+ "config_path": str(error_path),}# No existing valid config found, create at XDG path (first in list)diff --git a/vibe/opencode_config.py b/vibe/opencode_config.pyindex a80f67f47..e3d0605b8 100644--- a/vibe/opencode_config.py+++ b/vibe/opencode_config.py@@ -4,12 +4,21 @@ from __future__ import annotationsimport jsonimport logging+from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Dict, Optionallogger = logging.getLogger(__name__)+@dataclass(slots=True)+class OpenCodeConfigProbeResult:+ config: Optional[Dict[str, Any]] = None+ path: Optional[Path] = None+ existing_paths: list[Path] = field(default_factory=list)+ errors: list[tuple[Path, str]] = field(default_factory=list)++def get_opencode_config_paths(home: Path | None = None) -> list[Path]:resolved_home = home or Path.home()return [@@ -123,7 +132,7 @@ def _strip_trailing_commas(source: str) -> str:def parse_jsonc_object(content: str) -> Dict[str, Any]:normalized = _strip_trailing_commas(_strip_jsonc_comments(content.lstrip("\ufeff"))).strip()if not normalized:- return {}+ raise ValueError("empty JSONC content")parsed = json.loads(normalized)if not isinstance(parsed, dict):@@ -135,18 +144,23 @@ def load_first_opencode_user_config(*,home: Path | None = None,logger_instance: Optional[logging.Logger] = None,-) -> tuple[Optional[Dict[str, Any]], Optional[Path]]:+) -> OpenCodeConfigProbeResult:active_logger = logger_instance or logger+ result = OpenCodeConfigProbeResult()for config_path in get_opencode_config_paths(home):if not config_path.exists():continue+ result.existing_paths.append(config_path)try:content = config_path.read_text(encoding="utf-8")- return parse_jsonc_object(content), config_path+ result.config = parse_jsonc_object(content)+ result.path = config_path+ return resultexcept Exception as exc:active_logger.warning(f"Failed to load {config_path}: {exc}")+ result.errors.append((config_path, str(exc)))continue- return None, None+ return result