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.

feat(config): hot reconcile platform saves

cyh321654eb6fbc
diff --git a/core/internal_server.py b/core/internal_server.py
index 541c89bcd..f0d842a23 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -314,6 +314,19 @@ def create_app(controller: "Controller") -> FastAPI:
)
return JSONResponse(status_code=202, content={"ok": True, "session_id": session_id})
+ @app.post("/internal/reconcile-platforms")
+ async def _reconcile_platforms() -> Any:
+ """Hot-apply the persisted platform config on the controller loop."""
+ try:
+ from config.v2_compat import to_app_config
+ from config.v2_config import V2Config
+
+ result = await controller.reconcile_platforms(to_app_config(V2Config.load()))
+ return JSONResponse(status_code=200, content=result)
+ except Exception as exc:
+ logger.exception("internal platform reconcile failed")
+ return JSONResponse(status_code=500, content={"ok": False, "error": str(exc)})
+
@app.get("/internal/events")
async def _events() -> Any:
"""Long-lived SSE feed of Controller-side inbox events.
diff --git a/tests/test_internal_client.py b/tests/test_internal_client.py
index 8a88c4ba4..9e494637e 100644
--- a/tests/test_internal_client.py
+++ b/tests/test_internal_client.py
@@ -99,6 +99,36 @@ def test_dispatch_async_missing_socket_raises_unavailable(tmp_path):
asyncio.run(internal_client.dispatch_async({"session_id": "s", "text": "x"}, socket_path=sock))
+def test_reconcile_platforms_round_trip(tmp_path):
+ app = FastAPI()
+ calls: list[bool] = []
+
+ @app.post("/internal/reconcile-platforms")
+ async def _reconcile():
+ calls.append(True)
+ return {"ok": True, "rebuilt": ["slack"]}
+
+ sock = tmp_path / "dispatch.sock"
+ sock.touch()
+
+ async def _go():
+ fake_transport = httpx.ASGITransport(app=app)
+ with patch("vibe.internal_client.httpx.AsyncHTTPTransport", return_value=fake_transport):
+ return await internal_client.reconcile_platforms(socket_path=sock)
+
+ result = asyncio.run(_go())
+
+ assert calls == [True]
+ assert result["status_code"] == 200
+ assert result["body"] == {"ok": True, "rebuilt": ["slack"]}
+
+
+def test_reconcile_platforms_missing_socket_raises_unavailable(tmp_path):
+ sock = tmp_path / "missing.sock"
+ with pytest.raises(internal_client.InternalServerUnavailable):
+ asyncio.run(internal_client.reconcile_platforms(socket_path=sock))
+
+
def test_turn_state_os_error_raises_unavailable(tmp_path):
"""Socket files can exist on Docker Desktop bind mounts while connection
operations raise platform ``OSError`` values (for example errno 95). The UI
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 31e96be68..7768928be 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -156,6 +156,7 @@ def test_create_app_exposes_minimal_endpoints():
# flow re-publishes its SSE chunks as ``show.dispatch``).
assert ("/internal/health", ("GET",)) in routes
assert ("/internal/dispatch_async", ("POST",)) in routes
+ assert ("/internal/reconcile-platforms", ("POST",)) in routes
assert ("/internal/cancel/{session_id}", ("POST",)) in routes
assert ("/internal/dispatch", ("POST",)) in routes
@@ -179,6 +180,31 @@ def test_health_endpoint():
assert resp.json() == {"ok": True, "service": "vibe-remote-internal", "version": 1}
+def test_reconcile_platforms_endpoint_calls_controller(monkeypatch):
+ controller = _build_controller_double()
+ calls = []
+
+ async def reconcile_platforms(config):
+ calls.append(config)
+ return {"ok": True, "added": ["discord"]}
+
+ controller.reconcile_platforms = reconcile_platforms
+ monkeypatch.setattr("config.v2_config.V2Config.load", lambda: "v2-config")
+ monkeypatch.setattr("config.v2_compat.to_app_config", lambda config: f"compat:{config}")
+ app = internal_server.create_app(controller)
+
+ async def _go():
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
+ return await client.post("/internal/reconcile-platforms")
+
+ resp = asyncio.run(_go())
+
+ assert resp.status_code == 200
+ assert resp.json() == {"ok": True, "added": ["discord"]}
+ assert calls == ["compat:v2-config"]
+
+
async def _dispatch_round_trip(body: dict) -> httpx.Response:
app = internal_server.create_app(_build_controller_double())
transport = httpx.ASGITransport(app=app)
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 3b1b2d312..566bbef4f 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -313,6 +313,124 @@ def test_config_routes_redact_platform_and_gateway_secrets(monkeypatch, tmp_path
assert "client_secret" not in data["gateway"]
+def test_config_post_hot_reconciles_platform_enablement(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ from vibe import api
+ from vibe import internal_client
+
+ payload = _full_config_payload()
+ payload["platforms"] = {"enabled": ["discord"], "primary": "discord"}
+ api.save_config(payload)
+
+ reconcile_calls = []
+ restart_calls = []
+
+ async def _reconcile_platforms():
+ reconcile_calls.append(True)
+ return {"status_code": 200, "body": {"ok": True, "added": ["slack"]}}
+
+ monkeypatch.setattr(internal_client, "reconcile_platforms", _reconcile_platforms)
+ monkeypatch.setattr(ui_server, "_schedule_service_restart_for_config_fallback", lambda: restart_calls.append(True) or {"ok": True})
+
+ next_payload = {
+ **payload,
+ "platforms": {"enabled": ["discord", "slack"], "primary": "discord"},
+ "slack": {"bot_token": "xoxb-hot-token", "app_token": "xapp-hot-token"},
+ }
+ client = app.test_client()
+ response = client.post("/api/config", json=next_payload, headers=csrf_headers(client))
+
+ assert response.status_code == 200
+ data = response.get_json()
+ assert data["platform_runtime"]["hot_reconciled"] is True
+ assert reconcile_calls == [True]
+ assert restart_calls == []
+
+
+def test_config_post_hot_reconciles_platform_runtime_credential_change(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ from vibe import api
+ from vibe import internal_client
+
+ payload = _full_config_payload()
+ payload["platforms"] = {"enabled": ["discord"], "primary": "discord"}
+ api.save_config(payload)
+
+ reconcile_calls = []
+
+ async def _reconcile_platforms():
+ reconcile_calls.append(True)
+ return {"status_code": 200, "body": {"ok": True, "rebuilt": ["discord"]}}
+
+ monkeypatch.setattr(internal_client, "reconcile_platforms", _reconcile_platforms)
+
+ client = app.test_client()
+ response = client.post(
+ "/api/config",
+ json={"discord": {"bot_token": "discord-new-token-12345"}},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ assert response.get_json()["platform_runtime"]["body"]["rebuilt"] == ["discord"]
+ assert reconcile_calls == [True]
+
+
+def test_config_post_non_platform_change_does_not_reconcile_platforms(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ from vibe import api
+ from vibe import internal_client
+
+ payload = _full_config_payload()
+ payload["platforms"] = {"enabled": ["discord"], "primary": "discord"}
+ api.save_config(payload)
+
+ async def _reconcile_platforms():
+ raise AssertionError("platform reconcile should not run")
+
+ monkeypatch.setattr(internal_client, "reconcile_platforms", _reconcile_platforms)
+
+ client = app.test_client()
+ response = client.post("/api/config", json={"show_duration": False}, headers=csrf_headers(client))
+
+ assert response.status_code == 200
+ assert "platform_runtime" not in response.get_json()
+
+
+def test_config_post_schedules_service_restart_when_hot_reconcile_unavailable(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+ from vibe import api
+ from vibe import internal_client
+
+ payload = _full_config_payload()
+ payload["platforms"] = {"enabled": ["discord"], "primary": "discord"}
+ api.save_config(payload)
+
+ async def _reconcile_platforms():
+ raise internal_client.InternalServerUnavailable("missing socket")
+
+ restart_calls = []
+ monkeypatch.setattr(internal_client, "reconcile_platforms", _reconcile_platforms)
+ monkeypatch.setattr(
+ ui_server,
+ "_schedule_service_restart_for_config_fallback",
+ lambda: restart_calls.append(True) or {"ok": True, "restart": {"job_id": "job-hot-fallback"}},
+ )
+
+ client = app.test_client()
+ response = client.post(
+ "/api/config",
+ json={"platforms": {"enabled": ["discord", "slack"], "primary": "discord"}, "slack": {"bot_token": "xoxb-hot-token", "app_token": "xapp-hot-token"}},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ runtime = response.get_json()["platform_runtime"]
+ assert runtime["hot_reconciled"] is False
+ assert runtime["restart_scheduled"] is True
+ assert restart_calls == [True]
+
+
def test_static_ui_assets_use_cache_headers(monkeypatch, tmp_path):
ui_dist = tmp_path / "dist"
assets_dir = ui_dist / "assets"
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index 96202ddc6..0fbf454ef 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -216,6 +216,29 @@ async def dispatch_async(
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
+async def reconcile_platforms(
+ *,
+ socket_path: Optional[Path] = None,
+ timeout: float = 30.0,
+) -> dict[str, Any]:
+ """Ask the controller to hot-apply the persisted platform configuration."""
+
+ target = (socket_path or default_socket_path()).expanduser().resolve()
+ if not target.exists():
+ raise InternalServerUnavailable(f"dispatch socket missing at {target}")
+ transport = httpx.AsyncHTTPTransport(uds=str(target))
+ try:
+ async with httpx.AsyncClient(
+ transport=transport,
+ base_url="http://localhost",
+ timeout=httpx.Timeout(timeout, connect=5.0),
+ ) as client:
+ resp = await client.post("/internal/reconcile-platforms")
+ except _SOCKET_ERRORS as exc:
+ raise InternalServerUnavailable(str(exc)) from exc
+ return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
+
+
async def cancel_dispatch(session_id: str, *, socket_path: Optional[Path] = None) -> dict[str, Any]:
"""Ask the controller to cancel a running ``dispatch_turn`` for
``session_id``.
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 62d8747a9..0f94c2e79 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1014,6 +1014,35 @@ def _should_rotate_remote_session_secret(previous: V2Config | None, current: V2C
return bool(previous_cloud.enabled and not current_cloud.enabled and current_cloud.session_secret)
+def _platform_runtime_signature(config: V2Config) -> dict[str, tuple[Any, ...]]:
+ from config.platform_registry import get_platform_descriptor
+
+ signatures: dict[str, tuple[Any, ...]] = {}
+ for platform in config.platforms.enabled:
+ descriptor = get_platform_descriptor(platform)
+ platform_config = descriptor.get_config(config)
+ signatures[platform] = (
+ tuple(getattr(platform_config, field, None) for field in descriptor.runtime_reconcile_field_names())
+ if platform_config is not None
+ else ()
+ )
+ return signatures
+
+
+def _platform_runtime_fields_changed(previous: V2Config | None, current: V2Config, payload: dict) -> bool:
+ from config.platform_registry import im_platform_descriptors
+
+ if previous is None:
+ return False
+ platform_config_keys = {descriptor.config_key for descriptor in im_platform_descriptors()}
+ if "platforms" not in payload and "platform" not in payload and not any(key in payload for key in platform_config_keys):
+ return False
+ return (
+ set(previous.platforms.enabled) != set(current.platforms.enabled)
+ or _platform_runtime_signature(previous) != _platform_runtime_signature(current)
+ )
+
+
# Static PWA / icon assets must be reachable WITHOUT the remote-access auth
# cookie. iOS "Add to Home Screen" fetches the apple-touch-icon + manifest in a
# context that doesn't carry the session, so gating them makes the installed app
@@ -2199,6 +2228,36 @@ def _restart_in_flight() -> bool:
return age < _RESTART_SEED_GRACE_SECONDS
+def _schedule_service_restart_for_config_fallback() -> dict[str, Any]:
+ from vibe import runtime
+ from vibe.restart_supervisor import schedule_restart
+
+ with _RESTART_CONTROL_LOCK:
+ if _restart_in_flight():
+ return {"ok": False, "code": "restart_in_progress", "error": "a restart is already in progress"}
+ status = runtime.read_status()
+ runtime.write_status("restarting", "restarting", status.get("service_pid"), status.get("ui_pid"))
+ restart = schedule_restart(delay_seconds=0.0, trigger="web-ui-config", scope="service")
+ return {"ok": True, "restart": restart}
+
+
+def _save_config_and_runtime_decisions(payload: dict) -> tuple[V2Config, bool, bool]:
+ from vibe import api
+ from vibe import remote_access
+
+ with CONFIG_LOCK:
+ previous_config = _load_remote_access_config()
+ config = api.save_config(payload)
+ should_reconcile_remote_access = False
+ if _remote_access_settings_changed(previous_config, config, payload):
+ if _should_rotate_remote_session_secret(previous_config, config, payload):
+ remote_access.rotate_session_secret(config)
+ config = V2Config.load()
+ should_reconcile_remote_access = True
+ should_reconcile_platforms = _platform_runtime_fields_changed(previous_config, config, payload)
+ return config, should_reconcile_remote_access, should_reconcile_platforms
+
+
@app.route("/api/control", methods=["POST"])
def control():
from vibe import runtime
@@ -2253,29 +2312,47 @@ def control():
@app.route("/api/config", methods=["POST"])
-def config_post():
+async def config_post():
from vibe import api
+ from vibe import internal_client
from vibe import remote_access
payload = request.json or {}
remote_access_runtime = None
- should_reconcile_remote_access = False
- with CONFIG_LOCK:
- previous_config = _load_remote_access_config() if "remote_access" in payload else None
- try:
- config = api.save_config(payload)
- except ValueError as exc:
- message = str(exc)
- return jsonify({"ok": False, "error": message, "message": message}), 400
- if _remote_access_settings_changed(previous_config, config, payload):
- if _should_rotate_remote_session_secret(previous_config, config, payload):
- remote_access.rotate_session_secret(config)
- should_reconcile_remote_access = True
+ try:
+ config, should_reconcile_remote_access, should_reconcile_platforms = await asyncio.to_thread(
+ _save_config_and_runtime_decisions,
+ payload,
+ )
+ except ValueError as exc:
+ message = str(exc)
+ return jsonify({"ok": False, "error": message, "message": message}), 400
if should_reconcile_remote_access:
- remote_access_runtime = remote_access.reconcile()
+ remote_access_runtime = await asyncio.to_thread(remote_access.reconcile)
+ platform_runtime = None
+ if should_reconcile_platforms:
+ try:
+ result = await internal_client.reconcile_platforms()
+ platform_runtime = {
+ "ok": result.get("status_code") == 200 and bool((result.get("body") or {}).get("ok")),
+ "hot_reconciled": result.get("status_code") == 200 and bool((result.get("body") or {}).get("ok")),
+ "body": result.get("body") or {},
+ }
+ except internal_client.InternalServerUnavailable as exc:
+ platform_runtime = {"ok": False, "hot_reconciled": False, "error": str(exc)}
+ if not platform_runtime.get("ok"):
+ restart_result = await asyncio.to_thread(_schedule_service_restart_for_config_fallback)
+ platform_runtime["restart_scheduled"] = bool(restart_result.get("ok"))
+ if restart_result.get("ok"):
+ platform_runtime["restart"] = restart_result.get("restart")
+ else:
+ platform_runtime["restart_error"] = restart_result.get("error")
+ platform_runtime["restart_code"] = restart_result.get("code")
response_payload = api.config_to_payload(config)
if remote_access_runtime is not None:
response_payload["remote_access_runtime"] = remote_access_runtime
+ if platform_runtime is not None:
+ response_payload["platform_runtime"] = platform_runtime
return jsonify(response_payload)