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(setup): reconcile backend runtime after config saves (#926)

Call Whitea1a143bf23df
diff --git a/AGENTS.md b/AGENTS.md
index cc3281d85..a38154cc7 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -150,6 +150,11 @@ Agent routing model:
Source-of-truth rule:
- when changing persistent product behavior, align with V2 config and current Web UI flows rather than legacy assumptions
+- a successful `agents.*` runtime config save must also reconcile any live
+ controller through the backend rolling-refresh path; persisted config and
+ built-in Agent rows alone do not update the in-memory backend registry, and
+ callers must not issue a second restart after the config API accepts that
+ reconciliation
## 5. Development Workflow
diff --git a/core/controller.py b/core/controller.py
index 3783fda7f..de7ffdbae 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -479,6 +479,28 @@ class Controller:
"primary": next_primary,
}
+ async def reconcile_agent_backends(self, backends: list[str]) -> dict[str, Any]:
+ """Hot-apply persisted config for the requested Agent backends."""
+ from modules.agents.catalog import AGENT_BACKENDS
+
+ requested: list[str] = []
+ for backend in backends:
+ if backend not in AGENT_BACKENDS:
+ raise ValueError(f"Unsupported agent backend: {backend}")
+ if backend not in requested:
+ requested.append(backend)
+
+ states: dict[str, str] = {}
+ for backend in requested:
+ states[backend] = await self.backend_restart_coordinator.request_restart(backend)
+
+ logger.info("Hot-reconciled Agent backends: %s", states)
+ return {
+ "ok": True,
+ "backends": requested,
+ "states": states,
+ }
+
def _migrate_discord_guild_scope_from_config(self) -> None:
if "discord" not in self.platform_settings_managers:
return
diff --git a/core/internal_server.py b/core/internal_server.py
index 47236140a..2a4af4176 100644
--- a/core/internal_server.py
+++ b/core/internal_server.py
@@ -406,6 +406,25 @@ def create_app(controller: "Controller") -> FastAPI:
logger.exception("internal platform reconcile failed")
return JSONResponse(status_code=500, content={"ok": False, "error": str(exc)})
+ @app.post("/internal/reconcile-agent-backends")
+ async def _reconcile_agent_backends(request: Request) -> Any:
+ """Hot-apply persisted Agent backend config on the controller loop."""
+ payload = await _safe_json(request)
+ backends = payload.get("backends")
+ if not isinstance(backends, list) or not all(isinstance(item, str) for item in backends):
+ return JSONResponse(
+ status_code=400,
+ content={"ok": False, "error": "backends must be a list of strings"},
+ )
+ try:
+ result = await controller.reconcile_agent_backends(backends)
+ return JSONResponse(status_code=200, content=result)
+ except ValueError as exc:
+ return JSONResponse(status_code=400, content={"ok": False, "error": str(exc)})
+ except Exception as exc:
+ logger.exception("internal Agent backend 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/docs/plans/setup-backend-runtime-reconcile.md b/docs/plans/setup-backend-runtime-reconcile.md
new file mode 100644
index 000000000..24dc58786
--- /dev/null
+++ b/docs/plans/setup-backend-runtime-reconcile.md
@@ -0,0 +1,51 @@
+# Setup Backend Runtime Reconciliation
+
+## Background
+
+The setup wizard persists backend enablement after its provider modal closes.
+The modal intentionally defers backend restart because the controller may not be
+running yet. When a controller is already running, however, `POST /api/config`
+updates the V2 config and built-in Agent records without updating the
+controller's in-memory backend registry. A newly enabled Codex Agent can then
+route to a backend that is absent until the whole service restarts.
+
+The same configuration/runtime split can affect OpenCode registration and
+Claude runtime fields, even though Claude is registered unconditionally.
+
+## Goal
+
+Make a successful backend runtime config save authoritative for both persisted
+state and any live controller, without requiring a full service restart.
+
+## Design
+
+1. Compare the previous and saved V2 configs through `to_app_config`, so the
+ change detector follows the exact runtime projection consumed by backend
+ adapters.
+2. Send the changed backend IDs from the UI process to a new controller-only
+ Unix-socket endpoint. The payload contract is:
+
+ ```json
+ {"backends": ["opencode", "claude", "codex"]}
+ ```
+
+3. The controller validates and deduplicates those IDs, then sends each through
+ the existing `BackendRestartCoordinator`. That path drains active work and
+ registers, unregisters, or refreshes the backend from the saved config.
+4. If no controller is running, keep the save successful and report that the
+ config will apply on the next start. If a service process is running but its
+ internal socket cannot reconcile, schedule the existing service restart
+ fallback rather than leaving a live process stale.
+5. Settings and wizard callers consume the config response instead of issuing a
+ second backend restart after the shared boundary has already reconciled it.
+
+No credentials cross the internal boundary. The UI process produces only
+backend IDs; the controller loads the persisted config itself.
+
+## Validation
+
+- [x] Unit: runtime change detection for Codex, OpenCode, and Claude
+- [x] Contract: internal client/server request and response shape
+- [x] Scenario `AUTH-SETUP-902`: first-run Codex enablement hot-registers before
+ the first Agent turn
+- [x] Focused Python tests, Ruff, and UI build
diff --git a/tests/test_backend_restart.py b/tests/test_backend_restart.py
index 769364d2d..e830d569d 100644
--- a/tests/test_backend_restart.py
+++ b/tests/test_backend_restart.py
@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, Mock
import pytest
from core.backend_restart import BackendRestartCoordinator
+from core.controller import Controller
class _AgentService:
@@ -161,3 +162,35 @@ def test_idle_refresh_failure_is_propagated_before_ack() -> None:
)
asyncio.run(run())
+
+
+def test_controller_reconciles_requested_backends_once_in_order() -> None:
+ async def run() -> None:
+ coordinator = SimpleNamespace(request_restart=AsyncMock(side_effect=["restarted", "draining"]))
+ controller = SimpleNamespace(backend_restart_coordinator=coordinator)
+
+ result = await Controller.reconcile_agent_backends(
+ controller,
+ ["codex", "codex", "opencode"],
+ )
+
+ assert result == {
+ "ok": True,
+ "backends": ["codex", "opencode"],
+ "states": {"codex": "restarted", "opencode": "draining"},
+ }
+ assert [awaited.args for awaited in coordinator.request_restart.await_args_list] == [
+ ("codex",),
+ ("opencode",),
+ ]
+
+ asyncio.run(run())
+
+
+def test_controller_rejects_unknown_backend_reconcile() -> None:
+ controller = SimpleNamespace(backend_restart_coordinator=SimpleNamespace(request_restart=AsyncMock()))
+
+ with pytest.raises(ValueError, match="Unsupported agent backend: unknown"):
+ asyncio.run(Controller.reconcile_agent_backends(controller, ["unknown"]))
+
+ controller.backend_restart_coordinator.request_restart.assert_not_awaited()
diff --git a/tests/test_internal_client.py b/tests/test_internal_client.py
index 06c085b80..d4f6b926a 100644
--- a/tests/test_internal_client.py
+++ b/tests/test_internal_client.py
@@ -130,6 +130,51 @@ def test_reconcile_platforms_missing_socket_raises_unavailable(tmp_path):
asyncio.run(internal_client.reconcile_platforms(socket_path=sock))
+def test_reconcile_agent_backends_round_trip(tmp_path):
+ app = FastAPI()
+ captured: dict = {}
+
+ @app.post("/internal/reconcile-agent-backends")
+ async def _reconcile(payload: dict):
+ captured["payload"] = payload
+ return {
+ "ok": True,
+ "backends": payload["backends"],
+ "states": {backend: "restarted" for backend in payload["backends"]},
+ }
+
+ 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_agent_backends(
+ ["codex", "opencode"],
+ socket_path=sock,
+ )
+
+ result = asyncio.run(_go())
+
+ assert captured["payload"] == {"backends": ["codex", "opencode"]}
+ assert result["status_code"] == 200
+ assert result["body"]["states"] == {
+ "codex": "restarted",
+ "opencode": "restarted",
+ }
+
+
+def test_reconcile_agent_backends_missing_socket_raises_unavailable(tmp_path):
+ sock = tmp_path / "missing.sock"
+ with pytest.raises(internal_client.InternalServerUnavailable):
+ asyncio.run(
+ internal_client.reconcile_agent_backends(
+ ["codex"],
+ socket_path=sock,
+ )
+ )
+
+
def test_notify_vault_request_created_round_trip(tmp_path):
app = FastAPI()
captured: dict = {}
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index f2ed2d3aa..dfa0d1b24 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -158,6 +158,7 @@ def test_create_app_exposes_minimal_endpoints():
assert ("/internal/health", ("GET",)) in routes
assert ("/internal/dispatch_async", ("POST",)) in routes
assert ("/internal/reconcile-platforms", ("POST",)) in routes
+ assert ("/internal/reconcile-agent-backends", ("POST",)) in routes
assert ("/internal/cancel/{session_id}", ("POST",)) in routes
assert ("/internal/dispatch", ("POST",)) in routes
assert ("/internal/events", ("GET",)) in routes
@@ -307,6 +308,59 @@ def test_reconcile_platforms_endpoint_reports_controller_failure(monkeypatch):
assert resp.json() == {"ok": False, "error": "IM thread for discord did not stop within timeout"}
+def test_reconcile_agent_backends_endpoint_calls_controller():
+ controller = _build_controller_double()
+ calls = []
+
+ async def reconcile_agent_backends(backends):
+ calls.append(backends)
+ return {
+ "ok": True,
+ "backends": backends,
+ "states": {backend: "restarted" for backend in backends},
+ }
+
+ controller.reconcile_agent_backends = reconcile_agent_backends
+ 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-agent-backends",
+ json={"backends": ["codex", "opencode"]},
+ )
+
+ resp = asyncio.run(_go())
+
+ assert resp.status_code == 200
+ assert resp.json()["states"] == {
+ "codex": "restarted",
+ "opencode": "restarted",
+ }
+ assert calls == [["codex", "opencode"]]
+
+
+def test_reconcile_agent_backends_endpoint_rejects_invalid_shape():
+ app = internal_server.create_app(_build_controller_double())
+
+ 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-agent-backends",
+ json={"backends": "codex"},
+ )
+
+ resp = asyncio.run(_go())
+
+ assert resp.status_code == 400
+ assert resp.json() == {
+ "ok": False,
+ "error": "backends must be a list of strings",
+ }
+
+
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 d342a18ec..29b8e88ee 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -499,6 +499,173 @@ def test_platform_runtime_fields_changed_detects_primary_only_change():
)
+def test_changed_agent_backend_runtimes_uses_backend_runtime_projection():
+ from config.v2_config import V2Config
+
+ payload = _full_config_payload()
+ payload["agents"]["codex"]["enabled"] = False
+ previous = V2Config.from_payload(payload)
+
+ changed_payload = json.loads(json.dumps(payload))
+ changed_payload["agents"]["codex"] = {
+ **changed_payload["agents"]["codex"],
+ "enabled": True,
+ "cli_path": "/opt/codex",
+ }
+ changed_payload["agents"]["opencode"] = {
+ **changed_payload["agents"]["opencode"],
+ "cli_path": "/opt/opencode",
+ }
+ changed_payload["agents"]["claude"] = {
+ **changed_payload["agents"]["claude"],
+ "cli_path": "/opt/claude",
+ }
+ current = V2Config.from_payload(changed_payload)
+
+ assert ui_server._changed_agent_backend_runtimes(
+ previous,
+ current,
+ {"agents": changed_payload["agents"]},
+ ) == ["opencode", "claude", "codex"]
+ assert ui_server._changed_agent_backend_runtimes(previous, current, {"show_duration": False}) == []
+ assert ui_server._changed_agent_backend_runtimes(None, current, {"agents": changed_payload["agents"]}) == []
+
+
+def test_config_post_hot_reconciles_first_setup_codex_enablement(monkeypatch, tmp_path):
+ """Scenario: AUTH-SETUP-902."""
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from vibe import api
+ from vibe import internal_client
+
+ payload = _full_config_payload()
+ payload["agents"]["codex"]["enabled"] = False
+ api.save_config(payload)
+
+ reconcile_calls = []
+
+ async def _reconcile_agent_backends(backends):
+ reconcile_calls.append(backends)
+ return {
+ "status_code": 200,
+ "body": {
+ "ok": True,
+ "backends": backends,
+ "states": {"codex": "restarted"},
+ },
+ }
+
+ monkeypatch.setattr(internal_client, "reconcile_agent_backends", _reconcile_agent_backends)
+
+ client = app.test_client()
+ response = client.post(
+ "/api/config",
+ json={
+ "agents": {
+ "codex": {
+ "enabled": True,
+ "cli_path": "/opt/codex",
+ }
+ }
+ },
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ data = response.get_json()
+ assert data["agents"]["codex"]["enabled"] is True
+ assert data["agent_backend_runtime"] == {
+ "ok": True,
+ "hot_reconciled": True,
+ "backends": ["codex"],
+ "body": {
+ "ok": True,
+ "backends": ["codex"],
+ "states": {"codex": "restarted"},
+ },
+ }
+ assert reconcile_calls == [["codex"]]
+
+
+def test_config_post_defers_backend_reconcile_until_next_start_when_service_is_stopped(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from vibe import api
+ from vibe import internal_client
+ from vibe import runtime
+
+ payload = _full_config_payload()
+ payload["agents"]["codex"]["enabled"] = False
+ api.save_config(payload)
+
+ async def _reconcile_agent_backends(_backends):
+ raise internal_client.InternalServerUnavailable("missing socket")
+
+ restart_calls = []
+ monkeypatch.setattr(internal_client, "reconcile_agent_backends", _reconcile_agent_backends)
+ monkeypatch.setattr(runtime, "service_process_running", lambda: False)
+ monkeypatch.setattr(
+ ui_server,
+ "_schedule_service_restart_for_config_fallback",
+ lambda: restart_calls.append(True) or {"ok": True},
+ )
+
+ client = app.test_client()
+ response = client.post(
+ "/api/config",
+ json={"agents": {"codex": {"enabled": True}}},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ runtime_result = response.get_json()["agent_backend_runtime"]
+ assert runtime_result["hot_reconciled"] is False
+ assert runtime_result["apply_on_next_start"] is True
+ assert restart_calls == []
+
+
+def test_config_post_restarts_running_service_when_backend_reconcile_is_unavailable(
+ monkeypatch,
+ tmp_path,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from vibe import api
+ from vibe import internal_client
+ from vibe import runtime
+
+ payload = _full_config_payload()
+ payload["agents"]["opencode"]["enabled"] = False
+ api.save_config(payload)
+
+ async def _reconcile_agent_backends(_backends):
+ raise internal_client.InternalServerUnavailable("missing socket")
+
+ restart_calls = []
+ monkeypatch.setattr(internal_client, "reconcile_agent_backends", _reconcile_agent_backends)
+ monkeypatch.setattr(runtime, "service_process_running", lambda: True)
+ monkeypatch.setattr(
+ ui_server,
+ "_schedule_service_restart_for_config_fallback",
+ lambda: restart_calls.append(True)
+ or {"ok": True, "restart": {"job_id": "job-backend-fallback"}},
+ )
+
+ client = app.test_client()
+ response = client.post(
+ "/api/config",
+ json={"agents": {"opencode": {"enabled": True}}},
+ headers=csrf_headers(client),
+ )
+
+ assert response.status_code == 200
+ runtime_result = response.get_json()["agent_backend_runtime"]
+ assert runtime_result["hot_reconciled"] is False
+ assert runtime_result["restart_scheduled"] is True
+ assert runtime_result["restart"]["job_id"] == "job-backend-fallback"
+ assert restart_calls == [True]
+
+
def test_config_post_non_platform_change_does_not_reconcile_platforms(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
from vibe import api
@@ -511,13 +678,18 @@ def test_config_post_non_platform_change_does_not_reconcile_platforms(monkeypatc
async def _reconcile_platforms():
raise AssertionError("platform reconcile should not run")
+ async def _reconcile_agent_backends(_backends):
+ raise AssertionError("Agent backend reconcile should not run")
+
monkeypatch.setattr(internal_client, "reconcile_platforms", _reconcile_platforms)
+ monkeypatch.setattr(internal_client, "reconcile_agent_backends", _reconcile_agent_backends)
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()
+ assert "agent_backend_runtime" not in response.get_json()
def test_config_post_schedules_service_restart_when_hot_reconcile_unavailable(monkeypatch, tmp_path):
diff --git a/ui/src/components/settings/providers/BackendProviderConfig.tsx b/ui/src/components/settings/providers/BackendProviderConfig.tsx
index 87c8e34b3..a01794517 100644
--- a/ui/src/components/settings/providers/BackendProviderConfig.tsx
+++ b/ui/src/components/settings/providers/BackendProviderConfig.tsx
@@ -12,19 +12,17 @@ import { OpencodeProviderConfig } from './OpencodeProviderConfig';
export function BackendProviderConfig({
backend,
hideEnableToggle,
- deferRestart,
}: {
backend: BackendId;
hideEnableToggle?: boolean;
- deferRestart?: boolean;
}) {
switch (backend) {
case 'claude':
- return <ClaudeProviderConfig hideEnableToggle={hideEnableToggle} deferRestart={deferRestart} />;
+ return <ClaudeProviderConfig hideEnableToggle={hideEnableToggle} />;
case 'codex':
- return <CodexProviderConfig hideEnableToggle={hideEnableToggle} deferRestart={deferRestart} />;
+ return <CodexProviderConfig hideEnableToggle={hideEnableToggle} />;
case 'opencode':
- return <OpencodeProviderConfig hideEnableToggle={hideEnableToggle} deferRestart={deferRestart} />;
+ return <OpencodeProviderConfig hideEnableToggle={hideEnableToggle} />;
default:
return null;
}
diff --git a/ui/src/components/settings/providers/ClaudeProviderConfig.tsx b/ui/src/components/settings/providers/ClaudeProviderConfig.tsx
index 6518769c7..3d34110ab 100644
--- a/ui/src/components/settings/providers/ClaudeProviderConfig.tsx
+++ b/ui/src/components/settings/providers/ClaudeProviderConfig.tsx
@@ -32,8 +32,7 @@ const DEFAULT_CLI = 'claude';
export const ClaudeProviderConfig: React.FC<{
hideEnableToggle?: boolean;
- deferRestart?: boolean;
-}> = ({ hideEnableToggle, deferRestart } = {}) => {
+}> = ({ hideEnableToggle } = {}) => {
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
@@ -43,7 +42,6 @@ export const ClaudeProviderConfig: React.FC<{
const runtime = useBackendRuntime({
backend: BACKEND_ID,
defaultCli: DEFAULT_CLI,
- deferRestart,
});
// Auth state — OAuth vs API-key.
diff --git a/ui/src/components/settings/providers/CodexProviderConfig.tsx b/ui/src/components/settings/providers/CodexProviderConfig.tsx
index af80d67f9..0a8d21ad9 100644
--- a/ui/src/components/settings/providers/CodexProviderConfig.tsx
+++ b/ui/src/components/settings/providers/CodexProviderConfig.tsx
@@ -23,8 +23,7 @@ const DEFAULT_CLI = 'codex';
export const CodexProviderConfig: React.FC<{
hideEnableToggle?: boolean;
- deferRestart?: boolean;
-}> = ({ hideEnableToggle, deferRestart } = {}) => {
+}> = ({ hideEnableToggle } = {}) => {
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
@@ -35,7 +34,6 @@ export const CodexProviderConfig: React.FC<{
const runtime = useBackendRuntime({
backend: BACKEND_ID,
defaultCli: DEFAULT_CLI,
- deferRestart,
});
const [state, setState] = useState<CodexAuthState | null>(null);
diff --git a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx b/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
index 0a07181c4..5a6848e0b 100644
--- a/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
+++ b/ui/src/components/settings/providers/OpencodeProviderConfig.tsx
@@ -160,8 +160,7 @@ const providerMatchesSearch = (provider: OpencodeProvider, q: string): boolean =
export const OpencodeProviderConfig: React.FC<{
hideEnableToggle?: boolean;
- deferRestart?: boolean;
-}> = ({ hideEnableToggle, deferRestart } = {}) => {
+}> = ({ hideEnableToggle } = {}) => {
const { t } = useTranslation();
const api = useApi();
const { showToast } = useToast();
@@ -170,7 +169,6 @@ export const OpencodeProviderConfig: React.FC<{
const runtime = useBackendRuntime({
backend: BACKEND_ID,
defaultCli: DEFAULT_CLI,
- deferRestart,
});
const permission = useOpencodePermission();
const { setPermissionAllowed } = permission;
diff --git a/ui/src/components/settings/shared/useBackendRuntime.ts b/ui/src/components/settings/shared/useBackendRuntime.ts
index 68248680d..73a3b2e14 100644
--- a/ui/src/components/settings/shared/useBackendRuntime.ts
+++ b/ui/src/components/settings/shared/useBackendRuntime.ts
@@ -19,16 +19,6 @@ export interface UseBackendRuntimeOptions {
backend: BackendId;
/** Fallback CLI binary name when V2Config carries no override. */
defaultCli: string;
- /**
- * Skip the controller restart in ``onSaveRuntime`` and treat the save as
- * successful once the config write lands. Used by the setup wizard, where
- * the controller is not necessarily running yet — there, attempting a
- * restart and treating "not acknowledged" as a failure would surface a
- * spurious failed/dirty save even though the cli_path write succeeded. The
- * settings route leaves this unset so saving a CLI path still restarts the
- * backend exactly as before.
- */
- deferRestart?: boolean;
}
export interface BackendRuntimeState {
@@ -76,6 +66,29 @@ const withoutLegacyDefaultBackend = (agents: Record<string, any> | undefined | n
return rest;
};
+type BackendRuntimeApplyResult = {
+ hot_reconciled?: boolean;
+ restart_scheduled?: boolean;
+ apply_on_next_start?: boolean;
+ restart_error?: string;
+ error?: string;
+};
+
+const assertBackendRuntimeApplied = (savedConfig: unknown, fallbackMessage: string) => {
+ const runtime = (
+ savedConfig as { agent_backend_runtime?: BackendRuntimeApplyResult } | null
+ )?.agent_backend_runtime;
+ if (
+ !runtime ||
+ runtime.hot_reconciled === true ||
+ runtime.restart_scheduled === true ||
+ runtime.apply_on_next_start === true
+ ) {
+ return;
+ }
+ throw new Error(runtime.restart_error || runtime.error || fallbackMessage);
+};
+
/**
* Encapsulates the runtime (CLI lifecycle) state shared by every
* Settings → Backends provider page. Previously each page (Claude /
@@ -88,7 +101,6 @@ const withoutLegacyDefaultBackend = (agents: Record<string, any> | undefined | n
export function useBackendRuntime({
backend,
defaultCli,
- deferRestart = false,
}: UseBackendRuntimeOptions): BackendRuntimeState {
const api = useApi();
const { showToast } = useToast();
@@ -197,18 +209,11 @@ export function useBackendRuntime({
cli_path: cliPath || defaultCli,
},
};
- await api.saveConfig({ agents: nextAgents });
- // In the wizard the controller may not be running yet, so a restart
- // would (correctly) go un-acknowledged. Treat the config write as the
- // success boundary there and skip the restart — the controller picks up
- // the new cli_path when it next starts. The settings route keeps the
- // restart so an edit to a live backend takes effect immediately.
- if (!deferRestart) {
- const restart = await api.restartBackend(backend);
- if (!restart?.ok) {
- throw new Error(restart?.message || t('common.saveFailed'));
- }
- }
+ const saved = await api.saveConfig({ agents: nextAgents });
+ // The config boundary owns both persistence and live runtime
+ // reconciliation. A second route-level restart would refresh the backend
+ // twice and could interrupt a transport that was just rebuilt.
+ assertBackendRuntimeApplied(saved, t('common.saveFailed'));
setSavedCliPath(cliPath);
showToast(t('common.saved'), 'success');
} catch (e: any) {
@@ -216,7 +221,7 @@ export function useBackendRuntime({
} finally {
setSavingRuntime(false);
}
- }, [api, backend, cliPath, defaultCli, deferRestart, enabled, showToast, t]);
+ }, [api, backend, cliPath, defaultCli, enabled, showToast, t]);
const toggleEnabled = useCallback(() => {
const next = !enabled;
@@ -236,22 +241,17 @@ export function useBackendRuntime({
enabled: next,
},
};
- await api.saveConfig({
+ const savedConfig = await api.saveConfig({
agents: nextAgents,
});
saved = true;
- if (!deferRestart) {
- const restart = await api.restartBackend(backend);
- if (!restart?.ok) {
- throw new Error(restart?.message || t('common.saveFailed'));
- }
- }
+ assertBackendRuntimeApplied(savedConfig, t('common.saveFailed'));
} catch (e: any) {
showToast(e?.message || t('common.saveFailed'), 'error');
if (!saved) setEnabled(!next);
}
})();
- }, [api, backend, deferRestart, enabled, showToast, t]);
+ }, [api, backend, enabled, showToast, t]);
const handleLifecycleChanged = useCallback(
async (info: { installedPath?: string | null } | undefined | null) => {
diff --git a/ui/src/components/steps/AgentDetection.tsx b/ui/src/components/steps/AgentDetection.tsx
index c9408060a..ba03fd741 100644
--- a/ui/src/components/steps/AgentDetection.tsx
+++ b/ui/src/components/steps/AgentDetection.tsx
@@ -432,11 +432,9 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
</DialogTitle>
</DialogHeader>
{providerModal && (
- // ``deferRestart``: the wizard runs before/while the controller
- // is started, so the embedded runtime Save persists the cli_path
- // without attempting a (would-be-unacknowledged) restart that
- // otherwise reads as a failed/dirty save.
- <BackendProviderConfig backend={providerModal as RuntimeBackendId} hideEnableToggle deferRestart />
+ // Config saves reconcile a live controller at the shared API
+ // boundary and defer naturally when the controller is stopped.
+ <BackendProviderConfig backend={providerModal as RuntimeBackendId} hideEnableToggle />
)}
</DialogContent>
</Dialog>
diff --git a/vibe/internal_client.py b/vibe/internal_client.py
index d95ec9aea..9ffc36cb0 100644
--- a/vibe/internal_client.py
+++ b/vibe/internal_client.py
@@ -302,6 +302,33 @@ async def reconcile_platforms(
return {"status_code": resp.status_code, "body": resp.json() if resp.content else {}}
+async def reconcile_agent_backends(
+ backends: list[str],
+ *,
+ socket_path: Optional[Path] = None,
+ timeout: float = 30.0,
+) -> dict[str, Any]:
+ """Ask the controller to hot-apply persisted Agent backend config."""
+
+ 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-agent-backends",
+ json={"backends": backends},
+ )
+ 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 notify_vault_request_created(
request_payload: dict[str, Any],
*,
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 0d65f7693..ca9c22d01 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1387,6 +1387,27 @@ def _platform_runtime_fields_changed(previous: V2Config | None, current: V2Confi
)
+def _changed_agent_backend_runtimes(
+ previous: V2Config | None,
+ current: V2Config,
+ payload: dict,
+) -> list[str]:
+ """Return backends whose persisted runtime projection changed."""
+ if previous is None or "agents" not in payload:
+ return []
+
+ from config.v2_compat import to_app_config
+ from modules.agents.catalog import AGENT_BACKENDS
+
+ previous_runtime = to_app_config(previous)
+ current_runtime = to_app_config(current)
+ return [
+ backend
+ for backend in AGENT_BACKENDS
+ if getattr(previous_runtime, backend, None) != getattr(current_runtime, backend, None)
+ ]
+
+
# 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
@@ -3973,7 +3994,7 @@ def _schedule_service_restart_for_config_fallback() -> dict[str, Any]:
return {"ok": True, "restart": restart}
-def _save_config_and_runtime_decisions(payload: dict) -> tuple[V2Config, bool, bool]:
+def _save_config_and_runtime_decisions(payload: dict) -> tuple[V2Config, bool, bool, list[str]]:
from vibe import api
from vibe import remote_access
@@ -3987,7 +4008,8 @@ def _save_config_and_runtime_decisions(payload: dict) -> tuple[V2Config, bool, b
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
+ changed_agent_backends = _changed_agent_backend_runtimes(previous_config, config, payload)
+ return config, should_reconcile_remote_access, should_reconcile_platforms, changed_agent_backends
_UI_RUNTIME_ACTIVE = False
@@ -4063,7 +4085,12 @@ async def config_post():
payload = request.json or {}
remote_access_runtime = None
try:
- config, should_reconcile_remote_access, should_reconcile_platforms = await asyncio.to_thread(
+ (
+ config,
+ should_reconcile_remote_access,
+ should_reconcile_platforms,
+ changed_agent_backends,
+ ) = await asyncio.to_thread(
_save_config_and_runtime_decisions,
payload,
)
@@ -4092,11 +4119,52 @@ async def config_post():
else:
platform_runtime["restart_error"] = restart_result.get("error")
platform_runtime["restart_code"] = restart_result.get("code")
+ agent_backend_runtime = None
+ if changed_agent_backends:
+ try:
+ result = await internal_client.reconcile_agent_backends(changed_agent_backends)
+ body = result.get("body") or {}
+ hot_reconciled = result.get("status_code") == 200 and bool(body.get("ok"))
+ agent_backend_runtime = {
+ "ok": hot_reconciled,
+ "hot_reconciled": hot_reconciled,
+ "backends": changed_agent_backends,
+ "body": body,
+ }
+ except internal_client.InternalServerUnavailable as exc:
+ agent_backend_runtime = {
+ "ok": False,
+ "hot_reconciled": False,
+ "backends": changed_agent_backends,
+ "error": str(exc),
+ }
+
+ if not agent_backend_runtime.get("ok"):
+ from vibe import runtime
+
+ service_running = await asyncio.to_thread(runtime.service_process_running)
+ if service_running:
+ if platform_runtime and platform_runtime.get("restart_scheduled"):
+ agent_backend_runtime["restart_scheduled"] = True
+ if platform_runtime.get("restart"):
+ agent_backend_runtime["restart"] = platform_runtime["restart"]
+ else:
+ restart_result = await asyncio.to_thread(_schedule_service_restart_for_config_fallback)
+ agent_backend_runtime["restart_scheduled"] = bool(restart_result.get("ok"))
+ if restart_result.get("ok"):
+ agent_backend_runtime["restart"] = restart_result.get("restart")
+ else:
+ agent_backend_runtime["restart_error"] = restart_result.get("error")
+ agent_backend_runtime["restart_code"] = restart_result.get("code")
+ else:
+ agent_backend_runtime["apply_on_next_start"] = True
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
+ if agent_backend_runtime is not None:
+ response_payload["agent_backend_runtime"] = agent_backend_runtime
return jsonify(response_payload)