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): preserve JSONC comments on permission setup

cyha214387f6076
diff --git a/tests/test_ui_api.py b/tests/test_ui_api.py
index c69425720..f3db4666d 100644
--- a/tests/test_ui_api.py
+++ b/tests/test_ui_api.py
@@ -195,7 +195,7 @@ def test_setup_opencode_permission_preserves_existing_json_fields(monkeypatch, t
monkeypatch.setattr(api.Path, "home", lambda: tmp_path)
result = api.setup_opencode_permission()
- updated = json.loads(config_path.read_text(encoding="utf-8"))
+ updated = parse_jsonc_object(config_path.read_text(encoding="utf-8"))
assert result["ok"] is True
assert result["config_path"] == str(config_path)
@@ -226,10 +226,14 @@ def test_setup_opencode_permission_accepts_jsonc_config(monkeypatch, tmp_path):
monkeypatch.setattr(api.Path, "home", lambda: tmp_path)
result = api.setup_opencode_permission()
- updated = json.loads(config_path.read_text(encoding="utf-8"))
+ updated_text = config_path.read_text(encoding="utf-8")
+ updated = parse_jsonc_object(updated_text)
assert result["ok"] is True
assert result["config_path"] == str(config_path)
+ assert "// Global defaults should be preserved." in updated_text
+ assert '"permission": "allow",' in updated_text
+ assert '"model": "anthropic/claude-sonnet-4-5",' in updated_text
assert updated == {
"model": "openai/gpt-5",
"agent": {"build": {"model": "anthropic/claude-sonnet-4-5"}},
@@ -274,9 +278,36 @@ def test_setup_opencode_permission_does_not_overwrite_invalid_existing_config(mo
assert result["ok"] is False
assert result["config_path"] == str(config_path)
assert "could not be parsed" in result["message"]
+ assert "File left unchanged." in result["message"]
assert config_path.read_text(encoding="utf-8") == original
+def test_setup_opencode_permission_preserves_comments_when_updating_existing_permission(monkeypatch, tmp_path):
+ config_path = tmp_path / ".config" / "opencode" / "opencode.json"
+ config_path.parent.mkdir(parents=True, exist_ok=True)
+ config_path.write_text(
+ """{
+ "model": "openai/gpt-5",
+ "permission": /* keep this block comment */ "prompt", // keep this inline comment
+}
+""",
+ encoding="utf-8",
+ )
+
+ monkeypatch.setattr(api.Path, "home", lambda: tmp_path)
+
+ result = api.setup_opencode_permission()
+ updated_text = config_path.read_text(encoding="utf-8")
+
+ assert result["ok"] is True
+ assert result["config_path"] == str(config_path)
+ assert '/* keep this block comment */ "allow", // keep this inline comment' in updated_text
+ assert parse_jsonc_object(updated_text) == {
+ "model": "openai/gpt-5",
+ "permission": "allow",
+ }
+
+
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"
@@ -294,7 +325,7 @@ def test_setup_opencode_permission_skips_comment_only_file_and_uses_next_valid_p
monkeypatch.setattr(api.Path, "home", lambda: tmp_path)
result = api.setup_opencode_permission()
- updated = json.loads(legacy_path.read_text(encoding="utf-8"))
+ updated = parse_jsonc_object(legacy_path.read_text(encoding="utf-8"))
assert result["ok"] is True
assert result["config_path"] == str(legacy_path)
diff --git a/vibe/api.py b/vibe/api.py
index 7dd33e4fa..e1f06e5d9 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1,5 +1,5 @@
-import json
import asyncio
+import json
import logging
import os
import shutil
@@ -21,7 +21,7 @@ from config.v2_settings import (
_routing_to_dict,
)
from config.v2_sessions import SessionsStore
-from vibe.opencode_config import get_opencode_config_paths, load_first_opencode_user_config
+from vibe.opencode_config import get_opencode_config_paths, load_first_opencode_user_config, set_jsonc_top_level_string_property
from vibe.upgrade import build_upgrade_plan, get_latest_version_info, get_restart_shell_command, get_running_vibe_path
@@ -723,9 +723,13 @@ def setup_opencode_permission() -> dict:
"config_path": str(probe.path),
}
- probe.config["permission"] = "allow"
try:
- probe.path.write_text(json.dumps(probe.config, indent=2) + "\n", encoding="utf-8")
+ original_content = probe.content
+ if original_content is None:
+ original_content = probe.path.read_text(encoding="utf-8")
+
+ updated_content = set_jsonc_top_level_string_property(original_content, "permission", "allow")
+ probe.path.write_text(updated_content, encoding="utf-8")
return {
"ok": True,
"message": "Permission set to 'allow'",
@@ -740,7 +744,7 @@ def setup_opencode_permission() -> dict:
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}",
+ "message": f"Existing OpenCode config could not be parsed: {error_message}. File left unchanged.",
"config_path": str(error_path),
}
diff --git a/vibe/opencode_config.py b/vibe/opencode_config.py
index e3d0605b8..997b4f1cf 100644
--- a/vibe/opencode_config.py
+++ b/vibe/opencode_config.py
@@ -14,6 +14,7 @@ logger = logging.getLogger(__name__)
@dataclass(slots=True)
class OpenCodeConfigProbeResult:
config: Optional[Dict[str, Any]] = None
+ content: Optional[str] = None
path: Optional[Path] = None
existing_paths: list[Path] = field(default_factory=list)
errors: list[tuple[Path, str]] = field(default_factory=list)
@@ -140,6 +141,224 @@ def parse_jsonc_object(content: str) -> Dict[str, Any]:
return parsed
+@dataclass(slots=True)
+class _JsoncTopLevelProperty:
+ key: str
+ key_start: int
+ value_start: int
+ value_end: int
+ delimiter_index: int
+ delimiter: str
+
+
+def _consume_json_string(source: str, start: int) -> int:
+ i = start + 1
+ escaped = False
+ while i < len(source):
+ char = source[i]
+ if escaped:
+ escaped = False
+ elif char == "\\":
+ escaped = True
+ elif char == '"':
+ return i + 1
+ i += 1
+ raise ValueError("unterminated string")
+
+
+def _consume_jsonc_comment(source: str, start: int) -> int:
+ next_char = source[start + 1] if start + 1 < len(source) else ""
+ if next_char == "/":
+ i = start + 2
+ while i < len(source) and source[i] != "\n":
+ i += 1
+ return i
+ if next_char == "*":
+ i = start + 2
+ while i + 1 < len(source):
+ if source[i] == "*" and source[i + 1] == "/":
+ return i + 2
+ i += 1
+ raise ValueError("unterminated block comment")
+ raise ValueError("expected JSONC comment")
+
+
+def _skip_jsonc_whitespace_and_comments(source: str, start: int) -> int:
+ i = start
+ while i < len(source):
+ char = source[i]
+ if char in " \t\r\n":
+ i += 1
+ continue
+ if char == "/" and i + 1 < len(source) and source[i + 1] in "/*":
+ i = _consume_jsonc_comment(source, i)
+ continue
+ return i
+ return i
+
+
+def _find_matching_jsonc_delimiter(source: str, start: int, opening: str, closing: str) -> int:
+ depth = 0
+ i = start
+ while i < len(source):
+ char = source[i]
+ if char == '"':
+ i = _consume_json_string(source, i)
+ continue
+ if char == "/" and i + 1 < len(source) and source[i + 1] in "/*":
+ i = _consume_jsonc_comment(source, i)
+ continue
+ if char == opening:
+ depth += 1
+ elif char == closing:
+ depth -= 1
+ if depth == 0:
+ return i
+ i += 1
+ raise ValueError(f"unterminated {opening}{closing} structure")
+
+
+def _consume_jsonc_primitive(source: str, start: int) -> int:
+ i = start
+ while i < len(source):
+ char = source[i]
+ if char in " \t\r\n,}]":
+ return i
+ if char == "/" and i + 1 < len(source) and source[i + 1] in "/*":
+ return i
+ i += 1
+ return i
+
+
+def _consume_jsonc_value(source: str, start: int) -> int:
+ if start >= len(source):
+ raise ValueError("missing JSON value")
+
+ char = source[start]
+ if char == '"':
+ return _consume_json_string(source, start)
+ if char == "{":
+ return _find_matching_jsonc_delimiter(source, start, "{", "}") + 1
+ if char == "[":
+ return _find_matching_jsonc_delimiter(source, start, "[", "]") + 1
+ return _consume_jsonc_primitive(source, start)
+
+
+def _line_start(source: str, index: int) -> int:
+ return source.rfind("\n", 0, index) + 1
+
+
+def _detect_newline(source: str) -> str:
+ return "\r\n" if "\r\n" in source else "\n"
+
+
+def _scan_jsonc_top_level_properties(source: str) -> tuple[int, int, list[_JsoncTopLevelProperty]]:
+ root_start = 1 if source.startswith("\ufeff") else 0
+ root_start = _skip_jsonc_whitespace_and_comments(source, root_start)
+ if root_start >= len(source) or source[root_start] != "{":
+ raise ValueError("root is not a JSON object")
+
+ root_end = _find_matching_jsonc_delimiter(source, root_start, "{", "}")
+ properties: list[_JsoncTopLevelProperty] = []
+
+ i = root_start + 1
+ while True:
+ i = _skip_jsonc_whitespace_and_comments(source, i)
+ if i >= root_end:
+ break
+ if source[i] != '"':
+ raise ValueError("expected object property")
+
+ key_end = _consume_json_string(source, i)
+ key = json.loads(source[i:key_end])
+
+ colon_index = _skip_jsonc_whitespace_and_comments(source, key_end)
+ if colon_index >= len(source) or source[colon_index] != ":":
+ raise ValueError("expected ':' after object property name")
+
+ value_start = _skip_jsonc_whitespace_and_comments(source, colon_index + 1)
+ value_end = _consume_jsonc_value(source, value_start)
+ delimiter_index = _skip_jsonc_whitespace_and_comments(source, value_end)
+ delimiter = source[delimiter_index] if delimiter_index < len(source) else ""
+
+ if delimiter not in {",", "}"}:
+ raise ValueError("expected ',' or '}' after object property")
+
+ properties.append(
+ _JsoncTopLevelProperty(
+ key=key,
+ key_start=i,
+ value_start=value_start,
+ value_end=value_end,
+ delimiter_index=delimiter_index,
+ delimiter=delimiter,
+ )
+ )
+
+ if delimiter == "}":
+ break
+ i = delimiter_index + 1
+
+ return root_start, root_end, properties
+
+
+def set_jsonc_top_level_string_property(source: str, key: str, value: str) -> str:
+ parse_jsonc_object(source)
+
+ root_start, root_end, properties = _scan_jsonc_top_level_properties(source)
+ serialized_value = json.dumps(value)
+
+ for prop in properties:
+ if prop.key == key:
+ return source[: prop.value_start] + serialized_value + source[prop.value_end :]
+
+ newline = _detect_newline(source)
+ root_line_start = _line_start(source, root_start)
+ closing_line_start = _line_start(source, root_end)
+ root_indent = source[root_line_start:root_start]
+ first_property_indent = None
+ if properties:
+ first_property = properties[0]
+ first_property_line_start = _line_start(source, first_property.key_start)
+ candidate_indent = source[first_property_line_start:first_property.key_start]
+ if candidate_indent.strip() == "":
+ first_property_indent = candidate_indent
+
+ child_indent = first_property_indent or (root_indent + " ")
+ property_text = f'{json.dumps(key)}: {serialized_value}'
+ has_multiline_layout = "\n" in source[root_start:root_end]
+
+ if not properties:
+ if has_multiline_layout:
+ insertion = f"{child_indent}{property_text}{newline}"
+ return source[:closing_line_start] + insertion + source[closing_line_start:]
+ return source[: root_start + 1] + property_text + source[root_end:]
+
+ last_property = properties[-1]
+ updated_source = source
+ trailing_comma = last_property.delimiter == ","
+
+ if not has_multiline_layout:
+ insertion_point = root_end
+ if not trailing_comma:
+ updated_source = updated_source[: last_property.value_end] + "," + updated_source[last_property.value_end :]
+ insertion_point += 1
+ prefix = " " if updated_source[insertion_point - 1] not in "{[ \t\r\n" else ""
+ suffix = "," if trailing_comma else ""
+ return updated_source[:insertion_point] + f"{prefix}{property_text}{suffix}" + updated_source[insertion_point:]
+
+ insertion_point = closing_line_start
+ if not trailing_comma:
+ updated_source = updated_source[: last_property.value_end] + "," + updated_source[last_property.value_end :]
+ if insertion_point > last_property.value_end:
+ insertion_point += 1
+
+ if has_multiline_layout:
+ suffix = "," if trailing_comma else ""
+ insertion = f"{child_indent}{property_text}{suffix}{newline}"
+ return updated_source[:insertion_point] + insertion + updated_source[insertion_point:]
+
+
def load_first_opencode_user_config(
*,
home: Path | None = None,
@@ -156,6 +375,7 @@ def load_first_opencode_user_config(
try:
content = config_path.read_text(encoding="utf-8")
result.config = parse_jsonc_object(content)
+ result.content = content
result.path = config_path
return result
except Exception as exc: