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(backends): add lifecycle chip with version/upgrade/restart

cyh8fe6c4bc7e7f
diff --git a/core/controller.py b/core/controller.py
index c3935d6d6..48e872596 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -25,6 +25,7 @@ from core.handlers import (
from core.agent_auth_service import AgentAuthService
from core.message_dispatcher import ConsolidatedMessageDispatcher
from core.processing_indicator import ProcessingIndicatorService
+from core.runtime_commands import RuntimeCommandWatcher
from core.scheduled_tasks import ScheduledTaskService
from core.update_checker import UpdateChecker
from core.watches import ManagedWatchService
@@ -73,6 +74,7 @@ class Controller:
self.message_dispatcher = ConsolidatedMessageDispatcher(self)
self.scheduled_task_service = ScheduledTaskService(self)
self.watch_service = ManagedWatchService(self)
+ self.runtime_command_watcher = RuntimeCommandWatcher(self)
# Background task for cleanup
self.cleanup_task: Optional[asyncio.Task] = None
@@ -420,6 +422,10 @@ class Controller:
self.watch_service.start()
except Exception as e:
logger.error("Failed to start watch service: %s", e, exc_info=True)
+ try:
+ await self.runtime_command_watcher.start()
+ except Exception as e:
+ logger.error("Failed to start runtime command watcher: %s", e, exc_info=True)
claude_timeout, codex_timeout = self._get_idle_cleanup_timeouts()
if (claude_timeout > 0 or codex_timeout > 0) and (
@@ -704,6 +710,7 @@ class Controller:
_stop_loop_coroutine(_cancel_cleanup_task(), "Idle cleanup task")
_stop_loop_coroutine(self.scheduled_task_service.stop(), "Scheduled task service")
_stop_loop_coroutine(self.watch_service.stop(), "Watch service")
+ _stop_loop_coroutine(self.runtime_command_watcher.stop(), "Runtime command watcher")
try:
codex_agent = self.agent_service.agents.get("codex")
diff --git a/core/runtime_commands.py b/core/runtime_commands.py
new file mode 100644
index 000000000..73ec9ddca
--- /dev/null
+++ b/core/runtime_commands.py
@@ -0,0 +1,127 @@
+"""Polls a shared directory for inter-process runtime command markers.
+
+The UI server runs in its own process (see ``vibe/cli.py::cmd_vibe``) and
+cannot reach into the controller's in-memory agent state. When the user
+clicks "Restart" on a backend, the UI server drops a marker file here so
+the controller can run the matching in-process cleanup
+(``AgentAuthService._refresh_backend_runtime``) instead of killing the
+subprocess out-of-band and leaving stale transports cached in the
+controller.
+
+The marker contract is intentionally minimal: file name encodes the
+command and target, contents are advisory only, file presence == request,
+file deletion == acknowledgement.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import re
+from pathlib import Path
+from typing import TYPE_CHECKING, Awaitable, Callable, Optional
+
+from config import paths
+
+if TYPE_CHECKING: # pragma: no cover - typing only
+ from core.controller import Controller
+
+logger = logging.getLogger(__name__)
+
+_SUPPORTED_BACKENDS = {"opencode", "codex"}
+_MARKER_PATTERN = re.compile(r"^restart-(?P<backend>[a-z][a-z0-9_-]*)\.cmd$")
+_POLL_INTERVAL_SECONDS = 0.5
+
+
+class RuntimeCommandWatcher:
+ """Background task that drains command markers and dispatches them."""
+
+ def __init__(
+ self,
+ controller: "Controller",
+ *,
+ directory: Optional[Path] = None,
+ poll_interval: float = _POLL_INTERVAL_SECONDS,
+ ) -> None:
+ self.controller = controller
+ self._directory = directory or (paths.get_state_dir() / "runtime_commands")
+ self._poll_interval = poll_interval
+ self._task: Optional[asyncio.Task] = None
+ self._stopping = asyncio.Event()
+
+ async def start(self) -> None:
+ if self._task and not self._task.done():
+ return
+ try:
+ self._directory.mkdir(parents=True, exist_ok=True)
+ except OSError as exc:
+ logger.warning("Runtime command watcher disabled: %s", exc)
+ return
+ self._stopping.clear()
+ self._task = asyncio.create_task(self._run(), name="runtime-command-watcher")
+ logger.info("Runtime command watcher started at %s", self._directory)
+
+ async def stop(self) -> None:
+ self._stopping.set()
+ task = self._task
+ if not task:
+ return
+ try:
+ await asyncio.wait_for(task, timeout=2.0)
+ except (asyncio.TimeoutError, asyncio.CancelledError):
+ task.cancel()
+ finally:
+ self._task = None
+
+ async def _run(self) -> None:
+ while not self._stopping.is_set():
+ try:
+ await self._sweep_once()
+ except Exception as exc: # pragma: no cover - keep loop alive
+ logger.warning("Runtime command sweep failed: %s", exc, exc_info=True)
+ try:
+ await asyncio.wait_for(self._stopping.wait(), timeout=self._poll_interval)
+ break
+ except asyncio.TimeoutError:
+ continue
+
+ async def _sweep_once(self) -> None:
+ try:
+ entries = list(self._directory.iterdir())
+ except FileNotFoundError:
+ return
+ for marker in entries:
+ if not marker.is_file():
+ continue
+ match = _MARKER_PATTERN.match(marker.name)
+ if not match:
+ logger.debug("Ignoring unknown runtime command marker: %s", marker.name)
+ marker.unlink(missing_ok=True)
+ continue
+ backend = match.group("backend")
+ if backend not in _SUPPORTED_BACKENDS:
+ logger.debug("Ignoring unsupported backend marker: %s", backend)
+ marker.unlink(missing_ok=True)
+ continue
+ await self._handle_restart(backend, marker)
+
+ async def _handle_restart(self, backend: str, marker: Path) -> None:
+ logger.info("Runtime command: refresh backend=%s", backend)
+ handler: Optional[Callable[[str], Awaitable[None]]] = getattr(
+ self.controller.agent_auth_service, "_refresh_backend_runtime", None
+ )
+ if handler is None:
+ logger.warning("AgentAuthService missing _refresh_backend_runtime; dropping marker")
+ marker.unlink(missing_ok=True)
+ return
+ try:
+ await handler(backend)
+ except Exception as exc:
+ logger.error("Backend refresh failed for %s: %s", backend, exc, exc_info=True)
+ finally:
+ # Always delete the marker so the UI server stops waiting; a
+ # failed refresh is still observable via the next runtime probe.
+ try:
+ marker.unlink(missing_ok=True)
+ except OSError as exc: # pragma: no cover - best-effort cleanup
+ logger.debug("Could not remove marker %s: %s", marker, exc)
diff --git a/docs/plans/backend-lifecycle-chip.md b/docs/plans/backend-lifecycle-chip.md
new file mode 100644
index 000000000..ffef025fb
--- /dev/null
+++ b/docs/plans/backend-lifecycle-chip.md
@@ -0,0 +1,123 @@
+# Backend Lifecycle Chip Plan
+
+## Background
+
+The Settings → Backends page currently shows a tiny "Found" / "Missing" pill per backend (`AgentDetection.tsx` → `StatusBadge`). It cannot tell the user:
+
+- whether the installed CLI is up to date
+- whether the backend's persistent server process (OpenCode / Codex) needs a restart to pick up a new Provider / MCP / env change
+- how to recover when a backend isn't running
+
+The unified `design.pen` (`qUpin` / `NrTO1` / `x53H1P`) replaces that pill with a chip + popover. The popover surfaces five visual states (Ready / Updating / Disabled / Error / Update Available) and the small set of operations the user is allowed to perform.
+
+## Goal
+
+Wire the Settings → Backends chip + popover to live backend state and provide three user-facing operations:
+
+1. **Upgrade** — for all three backends (Claude / OpenCode / Codex), re-run the installer to pull the latest CLI release.
+2. **Restart** — only for OpenCode and Codex (persistent server processes). Used after Provider / MCP / env config changes. Claude is a one-shot CLI so this action is hidden.
+3. **Reinstall** — when the backend's CLI is missing or fails to start, run the installer.
+
+Out of scope:
+
+- Stop / Start buttons. The user explicitly said Vibe Remote should manage these processes; only Restart is exposed.
+- PID / uptime / exit code / auto-restart timers. None of this leaks into the UI.
+- Per-cwd restart granularity for Codex. Restart resets all in-process Codex transports.
+
+## Solution
+
+### Process-model reminder
+
+- **OpenCode** — singleton server (`OpenCodeServerManager`), lazy-started on first message, PID persisted to `~/.vibe_remote/logs/opencode_server.json`. UI server can kill it via the existing pid-file path (same pattern as `vibe/cli.py::_stop_opencode_server`).
+- **Codex** — one persistent `codex app-server` subprocess **per working directory**, held in-memory inside `CodexAgent._transports`. No pid file. UI server enumerates `codex app-server` processes owned by the current user and sends SIGTERM; the controller's lazy-start path respawns on the next message.
+- **Claude** — one-shot CLI invocation per request; no daemon, no restart action.
+
+### Backend (Python)
+
+1. `vibe/api.py`
+ - `get_backend_runtime(name)` returns
+ ```python
+ {
+ "name": "opencode" | "claude" | "codex",
+ "enabled": bool, # from config
+ "cli_path": str, # configured path
+ "installed": bool, # resolves on PATH
+ "current_version": str | None, # `<cli> --version`, 5s timeout, 30s cache
+ "latest_version": str | None, # registry probe, 1h cache, best-effort
+ "has_update": bool,
+ "supports_restart": bool, # True for opencode / codex
+ "process_status": "running" | "stopped" | "unknown",
+ "error": str | None,
+ }
+ ```
+ - `restart_backend(name)` → `{ok, message}`. Reuses `_stop_opencode_server`-style pid-file kill for OpenCode; enumerates `codex app-server` processes via `psutil` for Codex; returns `{ok: False, message: "..."}` for Claude.
+ - Upgrade reuses `install_agent(name)` (already runs the upstream installer; same code path for install + upgrade).
+ - Caching uses two TTL dicts at module scope (`_VERSION_CACHE`, `_LATEST_CACHE`), guarded by short timeouts and clean fallback (`latest_version=None, has_update=False`) on network failure.
+
+2. `vibe/ui_server.py`
+ - `GET /backend/<name>/runtime` → returns `api.get_backend_runtime(name)`.
+ - `POST /backend/<name>/restart` → returns `api.restart_backend(name)`. Allowlists `{opencode, codex}`.
+ - Upgrade keeps using existing `POST /agent/<name>/install`.
+
+### Frontend
+
+3. `ui/src/components/settings/BackendLifecycleChip.tsx` (new)
+ - Props: `{ name, enabled, cliStatus, onUpgraded? }`.
+ - Owns its own popover state, version probe (lazy via `api.getBackendRuntime`), upgrade + restart calls.
+ - Visual state derivation (priority order):
+ 1. `enabled === false` → **Disabled** (muted)
+ 2. internal `phase === 'upgrading'` → **Updating** (cyan)
+ 3. `cliStatus === 'missing'` or `runtime.installed === false` → **Error / Not running** (red)
+ 4. `runtime.has_update` → **Update available** (amber)
+ 5. else → **Ready** (mint)
+ - Popover footer:
+ - **Update available** → `Upgrade` button.
+ - **Ready** → `Restart` button only when `runtime.supports_restart` (i.e. opencode / codex).
+ - **Error** → `Restart` (when supported) + `Reinstall` buttons.
+ - **Disabled** → muted hint, no buttons.
+ - **Updating** → progress, no buttons.
+ - Disable the Restart button if the backend is currently upgrading.
+
+4. `ui/src/context/ApiContext.tsx`
+ - Add `getBackendRuntime(name)` and `restartBackend(name)` with typed return shapes.
+
+5. `ui/src/components/steps/AgentDetection.tsx`
+ - Replace `<StatusBadge>` with `<BackendLifecycleChip>` inside each backend card header.
+ - Keep the existing first-time install hint (`isMissing(agent)` block) so the Setup Wizard's first-run guidance remains inline; the chip handles ongoing lifecycle.
+
+6. i18n: add `backendLifecycle.*` keys in `ui/src/i18n/en.json` + `ui/src/i18n/zh.json`.
+
+## Latest-version sources
+
+- **OpenCode** — `https://api.github.com/repos/sst/opencode/releases/latest` → `tag_name` (strip leading `v`).
+- **Codex** — `https://registry.npmjs.org/@openai/codex/latest` → `version`.
+- **Claude** — `https://registry.npmjs.org/@anthropic-ai/claude-code/latest` → `version`.
+
+All probes use a 5s timeout and short-circuit to `latest_version=None` on any error; the chip silently falls back to **Ready** instead of **Update available** in that case.
+
+## TODO
+
+- [x] Plan document.
+- [x] Implement `api.get_backend_runtime` + cache + version probes.
+- [x] Implement `api.restart_backend` — controller IPC via marker file `~/.vibe_remote/state/runtime_commands/restart-<backend>.cmd`, with UI-side direct-kill fallback when the controller doesn't ack within 4s.
+- [x] Wire HTTP routes `GET /backend/<name>/runtime` + `POST /backend/<name>/restart`.
+- [x] Add `getBackendRuntime` / `restartBackend` to `ApiContext`.
+- [x] Build `BackendLifecycleChip` + popover.
+- [x] Swap into `AgentDetection.tsx`.
+- [x] i18n strings for both languages.
+- [x] `npm run build` in `ui/`, fix typescript / lint warnings.
+- [x] `ruff check` on touched Python files.
+- [x] Reviewer subagent + manual sanity check.
+
+## Implementation notes (delta vs original plan)
+
+- Restart is **not** a direct UI-side kill anymore. The UI server writes a marker file and the controller's `RuntimeCommandWatcher` runs `agent_auth_service._refresh_backend_runtime(backend)` — the existing controller-side cleanup that already covers Codex transports + OpenCode singleton, so cached state in the controller process stays consistent. Direct kill remains only as a fallback after a 4 s ack timeout.
+- `packaging>=23.0` was added as a runtime dependency for proper PEP 440 version comparison; a tuple-based fallback handles parses that `packaging.version.Version` rejects.
+- Failed `latest_version` probes are cached for 120 s (vs 3600 s for success) so transient outages don't lock in a stale "no update" reading for an hour.
+- All version + latest caches are keyed by `(name, cli_path)` so editing the configured CLI path invalidates the cache.
+
+## Evidence
+
+- Unit: add focused pytest for version-string parsing + `restart_backend` Claude-path no-op.
+- Contract: `psutil` lookup is best-effort; no scenario catalog entry needed.
+- Manual: in regression Docker, open Settings → Backends, verify each chip renders the right state for installed / missing / disabled and that Upgrade + Restart succeed.
diff --git a/pyproject.toml b/pyproject.toml
index 778b416ff..6a8545197 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -63,6 +63,7 @@ dependencies = [
"SQLAlchemy>=2.0.0",
"alembic>=1.13.0",
"psutil>=5.9.0",
+ "packaging>=23.0",
]
[project.urls]
@@ -118,3 +119,8 @@ asyncio_mode = "auto"
markers = [
"integration: platform integration tests requiring Docker + platform tokens",
]
+
+[dependency-groups]
+dev = [
+ "pytest>=9.0.3",
+]
diff --git a/ui/src/components/settings/BackendLifecycleChip.tsx b/ui/src/components/settings/BackendLifecycleChip.tsx
new file mode 100644
index 000000000..e597cfbb6
--- /dev/null
+++ b/ui/src/components/settings/BackendLifecycleChip.tsx
@@ -0,0 +1,346 @@
+import React from 'react';
+import { useTranslation } from 'react-i18next';
+import { AlertCircle, Check, Download, RefreshCw, RotateCw, X } from 'lucide-react';
+import clsx from 'clsx';
+import { useApi, type BackendRuntimeInfo } from '../../context/ApiContext';
+import { useToast } from '../../context/ToastContext';
+import { Button } from '../ui/button';
+
+type CliStatus = 'unknown' | 'ok' | 'missing';
+type Phase = 'idle' | 'loading' | 'upgrading' | 'restarting';
+type Visual = 'disabled' | 'ready' | 'updating' | 'update' | 'error' | 'loading';
+
+interface BackendLifecycleChipProps {
+ name: string;
+ enabled: boolean;
+ cliStatus: CliStatus;
+ onChanged?: () => void | Promise<void>;
+}
+
+const VISUAL_STYLES: Record<Visual, string> = {
+ disabled: 'border-border bg-surface-2/60 text-muted',
+ ready: 'border-mint/30 bg-mint/[0.08] text-mint',
+ updating: 'border-cyan/30 bg-cyan/[0.10] text-cyan',
+ update: 'border-gold/30 bg-gold/15 text-gold',
+ error: 'border-destructive/30 bg-destructive/10 text-destructive',
+ loading: 'border-border bg-surface-2/60 text-muted',
+};
+
+const DOT_STYLES: Record<Visual, string> = {
+ disabled: 'bg-muted/60',
+ ready: 'bg-mint',
+ updating: 'bg-cyan animate-pulse',
+ update: 'bg-gold animate-pulse',
+ error: 'bg-destructive',
+ loading: 'bg-muted/60',
+};
+
+const deriveVisual = (
+ enabled: boolean,
+ cliStatus: CliStatus,
+ runtime: BackendRuntimeInfo | null,
+ phase: Phase,
+): Visual => {
+ // An in-flight upgrade outranks a stale "disabled" — if the user toggles a
+ // backend off mid-install we still want the progress affordance visible.
+ if (phase === 'upgrading') return 'updating';
+ if (!enabled) return 'disabled';
+ if (cliStatus === 'missing') return 'error';
+ if (runtime && runtime.installed === false) return 'error';
+ if (runtime?.has_update) return 'update';
+ if (cliStatus === 'ok') return 'ready';
+ return 'loading';
+};
+
+export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
+ name,
+ enabled,
+ cliStatus,
+ onChanged,
+}) => {
+ const { t } = useTranslation();
+ const api = useApi();
+ const { showToast } = useToast();
+ const [isOpen, setIsOpen] = React.useState(false);
+ const [runtime, setRuntime] = React.useState<BackendRuntimeInfo | null>(null);
+ const [phase, setPhase] = React.useState<Phase>('idle');
+ const popupRef = React.useRef<HTMLDivElement>(null);
+ const isMountedRef = React.useRef(true);
+ // Monotonic token guards against stale async writes when toggle/detect
+ // changes fire faster than the runtime probe completes.
+ const loadTokenRef = React.useRef(0);
+
+ React.useEffect(() => {
+ isMountedRef.current = true;
+ return () => {
+ isMountedRef.current = false;
+ };
+ }, []);
+
+ // Close on outside click — same pattern as VersionBadge.
+ React.useEffect(() => {
+ if (!isOpen) return;
+ const handleClickOutside = (event: MouseEvent) => {
+ if (popupRef.current && !popupRef.current.contains(event.target as Node)) {
+ setIsOpen(false);
+ }
+ };
+ document.addEventListener('mousedown', handleClickOutside);
+ return () => document.removeEventListener('mousedown', handleClickOutside);
+ }, [isOpen]);
+
+ const loadRuntime = React.useCallback(async () => {
+ const myToken = ++loadTokenRef.current;
+ setPhase('loading');
+ let info: BackendRuntimeInfo | null = null;
+ try {
+ info = await api.getBackendRuntime(name);
+ } catch (e) {
+ console.error(`Failed to load runtime for ${name}:`, e);
+ } finally {
+ // Drop the result if a newer request superseded us, or the component
+ // unmounted while we were in flight.
+ if (isMountedRef.current && loadTokenRef.current === myToken) {
+ setRuntime(info);
+ setPhase('idle');
+ }
+ }
+ }, [api, name]);
+
+ // Refresh when the chip opens, when the user toggles enabled, or when the CLI
+ // path is freshly detected. Keeps the chip in sync with the surrounding card.
+ React.useEffect(() => {
+ if (!enabled) {
+ // Bump the token so any in-flight probe drops its result.
+ loadTokenRef.current += 1;
+ setRuntime(null);
+ return;
+ }
+ if (cliStatus === 'ok' || isOpen) {
+ void loadRuntime();
+ }
+ }, [enabled, cliStatus, isOpen, loadRuntime]);
+
+ const visual = deriveVisual(enabled, cliStatus, runtime, phase);
+
+ const handleUpgrade = async () => {
+ setPhase('upgrading');
+ try {
+ const result = await api.installAgent(name);
+ if (result.ok) {
+ showToast(t('backendLifecycle.upgradeSuccess'), 'success');
+ await loadRuntime();
+ await onChanged?.();
+ } else {
+ showToast(result.message || t('backendLifecycle.upgradeFailed'), 'error');
+ }
+ } catch (e) {
+ showToast(String(e), 'error');
+ } finally {
+ if (isMountedRef.current) setPhase('idle');
+ }
+ };
+
+ const handleRestart = async () => {
+ setPhase('restarting');
+ try {
+ const result = await api.restartBackend(name);
+ showToast(
+ result.message || (result.ok ? t('backendLifecycle.restartSuccess') : t('backendLifecycle.restartFailed')),
+ result.ok ? 'success' : 'error',
+ );
+ if (result.ok) await loadRuntime();
+ } catch (e) {
+ showToast(String(e), 'error');
+ } finally {
+ if (isMountedRef.current) setPhase('idle');
+ }
+ };
+
+ const chipLabel = (() => {
+ switch (visual) {
+ case 'disabled':
+ return t('backendLifecycle.statusDisabled');
+ case 'ready':
+ return t('backendLifecycle.statusReady');
+ case 'updating':
+ return t('backendLifecycle.statusUpdating');
+ case 'update':
+ return t('backendLifecycle.statusUpdateAvailable');
+ case 'error':
+ return t('backendLifecycle.statusError');
+ case 'loading':
+ default:
+ return t('common.notChecked');
+ }
+ })();
+
+ return (
+ <div className="relative" ref={popupRef}>
+ <button
+ type="button"
+ onClick={() => setIsOpen((prev) => !prev)}
+ className={clsx(
+ 'inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors',
+ VISUAL_STYLES[visual],
+ )}
+ aria-label={chipLabel}
+ >
+ <span className={clsx('size-2 rounded-full', DOT_STYLES[visual])} />
+ {chipLabel}
+ </button>
+
+ {isOpen && (
+ <div
+ className={clsx(
+ 'z-50 rounded-lg border border-border bg-popover text-popover-foreground shadow-xl',
+ 'fixed inset-x-3 top-[4.5rem] max-h-[calc(100dvh-5.5rem)] overflow-auto',
+ 'md:absolute md:inset-x-auto md:right-0 md:top-full md:mt-2 md:w-72 md:max-h-none md:overflow-visible',
+ )}
+ >
+ <div className="flex items-center justify-between border-b border-border px-4 py-3">
+ <span className="text-sm font-medium text-foreground">{t('backendLifecycle.title')}</span>
+ <div className="flex items-center gap-1">
+ <button
+ type="button"
+ onClick={() => void loadRuntime()}
+ disabled={phase !== 'idle'}
+ className="rounded p-1.5 text-muted hover:bg-surface-2 hover:text-foreground disabled:opacity-50"
+ aria-label={t('common.refresh')}
+ title={t('common.refresh')}
+ >
+ <RefreshCw size={14} className={phase === 'loading' ? 'animate-spin' : ''} />
+ </button>
+ <button
+ type="button"
+ onClick={() => setIsOpen(false)}
+ className="rounded p-1.5 text-muted hover:bg-surface-2 hover:text-foreground"
+ aria-label={t('common.close')}
+ >
+ <X size={14} />
+ </button>
+ </div>
+ </div>
+
+ <div className="space-y-3 p-4">
+ <ChipPopoverBody
+ visual={visual}
+ runtime={runtime}
+ phase={phase}
+ name={name}
+ />
+ </div>
+
+ {visual !== 'disabled' && visual !== 'updating' && (
+ <div className="flex flex-wrap justify-end gap-2 border-t border-border px-4 py-3">
+ {visual === 'update' && (
+ <Button variant="brand" size="xs" onClick={() => void handleUpgrade()} disabled={phase !== 'idle'}>
+ <Download size={14} />
+ {t('backendLifecycle.upgradeNow')}
+ </Button>
+ )}
+ {visual === 'error' && (
+ <Button variant="brand" size="xs" onClick={() => void handleUpgrade()} disabled={phase !== 'idle'}>
+ <Download size={14} />
+ {t('backendLifecycle.reinstall')}
+ </Button>
+ )}
+ {visual !== 'update' && cliStatus === 'ok' && runtime?.supports_restart && (
+ <Button
+ variant="secondary"
+ size="xs"
+ onClick={() => void handleRestart()}
+ disabled={phase !== 'idle'}
+ >
+ <RotateCw size={14} className={phase === 'restarting' ? 'animate-spin' : ''} />
+ {t('backendLifecycle.restart')}
+ </Button>
+ )}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+};
+
+const ChipPopoverBody: React.FC<{
+ visual: Visual;
+ runtime: BackendRuntimeInfo | null;
+ phase: Phase;
+ name: string;
+}> = ({ visual, runtime, phase, name }) => {
+ const { t } = useTranslation();
+
+ if (visual === 'disabled') {
+ return (
+ <p className="rounded-md border border-border bg-surface-2/40 px-3 py-2 text-xs text-muted">
+ {t('backendLifecycle.disabledHint')}
+ </p>
+ );
+ }
+
+ return (
+ <>
+ <div className="flex items-center justify-between text-sm">
+ <span className="text-muted">{t('backendLifecycle.currentVersion')}</span>
+ <span className="font-mono font-medium text-foreground">{runtime?.current_version || '—'}</span>
+ </div>
+ {runtime?.latest_version && (
+ <div className="flex items-center justify-between text-sm">
+ <span className="text-muted">{t('backendLifecycle.latestVersion')}</span>
+ <span className="font-mono font-medium text-foreground">{runtime.latest_version}</span>
+ </div>
+ )}
+ <StateBlock visual={visual} phase={phase} runtime={runtime} name={name} />
+ </>
+ );
+};
+
+const StateBlock: React.FC<{
+ visual: Visual;
+ phase: Phase;
+ runtime: BackendRuntimeInfo | null;
+ name: string;
+}> = ({ visual, phase, runtime, name }) => {
+ const { t } = useTranslation();
+
+ if (phase === 'upgrading') {
+ return (
+ <div className="flex items-center gap-2 rounded-md border border-cyan/25 bg-cyan/10 px-3 py-2 text-sm text-cyan">
+ <RefreshCw size={16} className="shrink-0 animate-spin" />
+ <span>{t('backendLifecycle.upgrading')}</span>
+ </div>
+ );
+ }
+ if (visual === 'update') {
+ return (
+ <div className="flex items-center gap-2 rounded-md border border-gold/30 bg-gold/10 px-3 py-2 text-sm text-gold">
+ <AlertCircle size={16} className="shrink-0" />
+ <span>
+ {t('backendLifecycle.updateHint', {
+ from: runtime?.current_version || '—',
+ to: runtime?.latest_version || '—',
+ })}
+ </span>
+ </div>
+ );
+ }
+ if (visual === 'error') {
+ return (
+ <div className="flex items-center gap-2 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">
+ <AlertCircle size={16} className="shrink-0" />
+ <span>{t('backendLifecycle.errorHint', { name })}</span>
+ </div>
+ );
+ }
+ if (visual === 'ready') {
+ return (
+ <div className="flex items-center gap-2 rounded-md border border-mint/25 bg-mint/10 px-3 py-2 text-sm text-mint">
+ <Check size={16} className="shrink-0" />
+ <span>{t('backendLifecycle.readyHint')}</span>
+ </div>
+ );
+ }
+ return null;
+};
diff --git a/ui/src/components/steps/AgentDetection.tsx b/ui/src/components/steps/AgentDetection.tsx
index c051a3b36..49f7796e7 100644
--- a/ui/src/components/steps/AgentDetection.tsx
+++ b/ui/src/components/steps/AgentDetection.tsx
@@ -2,20 +2,19 @@ import React, { useEffect, useState } from 'react';
import {
ArrowLeft,
ArrowRight,
- Check,
ChevronDown,
ChevronUp,
Download,
RefreshCw,
Search,
Settings,
- X,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
import { useApi } from '../../context/ApiContext';
import { BackendIcon, EyebrowBadge, WizardCard } from '../visual';
import type { BackendId } from '../visual';
+import { BackendLifecycleChip } from '../settings/BackendLifecycleChip';
import { CompactField, CompactSelect, ToggleSwitch } from '../settings/SettingsPrimitives';
import { Button } from '../ui/button';
@@ -231,7 +230,12 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
</div>
</div>
<div className="flex items-center gap-3">
- <StatusBadge status={agent.status || 'unknown'} loading={checking} />
+ <BackendLifecycleChip
+ name={name}
+ enabled={agent.enabled}
+ cliStatus={agent.status || 'unknown'}
+ onChanged={() => detect(name, agent.cli_path)}
+ />
<ToggleSwitch
enabled={agent.enabled}
onClick={() => toggle(name, !agent.enabled)}
@@ -411,26 +415,3 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
);
};
-const StatusBadge: React.FC<{ status: 'unknown' | 'ok' | 'missing'; loading: boolean }> = ({ status, loading }) => {
- const { t } = useTranslation();
-
- if (loading) {
- return (
- <div className="text-muted">
- <RefreshCw className="size-3.5 animate-spin" />
- </div>
- );
- }
- if (status === 'unknown') {
- return <span className="text-[11px] text-muted">{t('common.notChecked')}</span>;
- }
- return status === 'ok' ? (
- <div className="inline-flex items-center gap-1.5 rounded-full border border-mint/30 bg-mint/[0.08] px-2 py-0.5 text-[11px] font-medium text-mint">
- <Check className="size-3" /> {t('common.found')}
- </div>
- ) : (
- <div className="inline-flex items-center gap-1.5 rounded-full border border-danger/30 bg-danger/10 px-2 py-0.5 text-[11px] font-medium text-danger">
- <X className="size-3" /> {t('common.missing')}
- </div>
- );
-};
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 554577669..fef36fdd9 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -19,6 +19,8 @@ export type ApiContextType = {
getFirstBindCode: () => Promise<any>;
detectCli: (binary: string) => Promise<any>;
installAgent: (name: string) => Promise<InstallResult>;
+ getBackendRuntime: (name: string) => Promise<BackendRuntimeInfo>;
+ restartBackend: (name: string) => Promise<BackendRestartResult>;
slackAuthTest: (botToken: string, proxyUrl?: string) => Promise<any>;
slackChannels: (botToken: string, browseAll?: boolean) => Promise<any>;
slackManifest: () => Promise<{ ok: boolean; manifest?: string; manifest_compact?: string; error?: string }>;
@@ -95,6 +97,26 @@ export type InstallResult = {
path?: string | null;
};
+export type BackendRuntimeInfo = {
+ ok: boolean;
+ name?: string;
+ enabled?: boolean;
+ cli_path?: string;
+ resolved_path?: string | null;
+ installed?: boolean;
+ current_version?: string | null;
+ latest_version?: string | null;
+ has_update?: boolean;
+ supports_restart?: boolean;
+ process_status?: 'running' | 'stopped' | 'unknown';
+ error?: string;
+};
+
+export type BackendRestartResult = {
+ ok: boolean;
+ message: string;
+};
+
const ApiContext = createContext<ApiContextType | undefined>(undefined);
export const useApi = () => {
@@ -171,6 +193,8 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
getFirstBindCode: () => getJson('/api/setup/first-bind-code'),
detectCli: (binary) => getJson(`/cli/detect?binary=${encodeURIComponent(binary)}`),
installAgent: (name) => postJson(`/agent/${encodeURIComponent(name)}/install`, {}),
+ getBackendRuntime: (name) => getJson(`/backend/${encodeURIComponent(name)}/runtime`),
+ restartBackend: (name) => postJson(`/backend/${encodeURIComponent(name)}/restart`, {}),
slackAuthTest: (botToken, proxyUrl) => postJson('/slack/auth_test', { bot_token: botToken, proxy_url: proxyUrl || undefined }),
slackChannels: (botToken, browseAll) => postJson('/slack/channels', { bot_token: botToken, browse_all: browseAll || false }),
slackManifest: () => getJson('/slack/manifest'),
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 6efad272d..d46c55894 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -520,6 +520,28 @@
"installing": "Installing...",
"showOutput": "Show details"
},
+ "backendLifecycle": {
+ "title": "Backend status",
+ "statusReady": "Ready",
+ "statusUpdating": "Updating",
+ "statusDisabled": "Disabled",
+ "statusError": "Not running",
+ "statusUpdateAvailable": "Update available",
+ "currentVersion": "Current version",
+ "latestVersion": "Latest version",
+ "readyHint": "Running the latest release.",
+ "updateHint": "Update available: {{from}} → {{to}}",
+ "errorHint": "{{name}} is not running. Try restarting or reinstalling.",
+ "disabledHint": "Toggle this backend on in the card header to activate.",
+ "upgrading": "Upgrading…",
+ "upgradeNow": "Upgrade",
+ "upgradeSuccess": "Upgrade complete",
+ "upgradeFailed": "Upgrade failed",
+ "reinstall": "Reinstall",
+ "restart": "Restart",
+ "restartSuccess": "Restart requested",
+ "restartFailed": "Restart failed"
+ },
"channelList": {
"eyebrow": "Groups",
"title": "Group Settings",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index be30523bc..8937da340 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -520,6 +520,28 @@
"installing": "安装中...",
"showOutput": "显示详情"
},
+ "backendLifecycle": {
+ "title": "后端状态",
+ "statusReady": "就绪",
+ "statusUpdating": "升级中",
+ "statusDisabled": "已停用",
+ "statusError": "未运行",
+ "statusUpdateAvailable": "可升级",
+ "currentVersion": "当前版本",
+ "latestVersion": "最新版本",
+ "readyHint": "当前已是最新版本。",
+ "updateHint": "可升级:{{from}} → {{to}}",
+ "errorHint": "{{name}} 当前未运行,可尝试重启或重新安装。",
+ "disabledHint": "请在卡片顶部开关中启用该后端。",
+ "upgrading": "正在升级…",
+ "upgradeNow": "立即升级",
+ "upgradeSuccess": "升级完成",
+ "upgradeFailed": "升级失败",
+ "reinstall": "重新安装",
+ "restart": "重启",
+ "restartSuccess": "已请求重启",
+ "restartFailed": "重启失败"
+ },
"channelList": {
"eyebrow": "群组",
"title": "群组设置",
diff --git a/uv.lock b/uv.lock
index 2637aa4fa..ab5ee9848 100644
--- a/uv.lock
+++ b/uv.lock
@@ -867,6 +867,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/0e/61/66938bbb5fc52dbdf84594873d5b51fb1f7c7794e9c0f5bd885f30bc507b/idna-3.11-py3-none-any.whl", hash = "sha256:771a87f49d9defaf64091e6e6fe9c18d4833f140bd19464795bc32d966ca37ea", size = 71008, upload-time = "2025-10-12T14:55:18.883Z" },
]
+[[package]]
+name = "iniconfig"
+version = "2.3.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" },
+]
+
[[package]]
name = "itsdangerous"
version = "2.2.0"
@@ -1199,6 +1208,24 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/b7/da/7d22601b625e241d4f23ef1ebff8acfc60da633c9e7e7922e24d10f592b3/multidict-6.7.0-py3-none-any.whl", hash = "sha256:394fc5c42a333c9ffc3e421a4c85e08580d990e08b99f6bf35b4132114c5dcb3", size = 12317, upload-time = "2025-10-06T14:52:29.272Z" },
]
+[[package]]
+name = "packaging"
+version = "26.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d7/f1/e7a6dd94a8d4a5626c03e4e99c87f241ba9e350cd9e6d75123f992427270/packaging-26.2.tar.gz", hash = "sha256:ff452ff5a3e828ce110190feff1178bb1f2ea2281fa2075aadb987c2fb221661", size = 228134, upload-time = "2026-04-24T20:15:23.917Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" },
+]
+
+[[package]]
+name = "pluggy"
+version = "1.6.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" },
+]
+
[[package]]
name = "propcache"
version = "0.4.1"
@@ -1532,6 +1559,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/c1/60/5d4751ba3f4a40a6891f24eec885f51afd78d208498268c734e256fb13c4/pydantic_settings-2.12.0-py3-none-any.whl", hash = "sha256:fddb9fd99a5b18da837b29710391e945b1e30c135477f484084ee513adb93809", size = 51880, upload-time = "2025-11-10T14:25:45.546Z" },
]
+[[package]]
+name = "pygments"
+version = "2.20.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/c3/b2/bc9c9196916376152d655522fdcebac55e66de6603a76a02bca1b6414f6c/pygments-2.20.0.tar.gz", hash = "sha256:6757cd03768053ff99f3039c1a36d6c0aa0b263438fcab17520b30a303a82b5f", size = 4955991, upload-time = "2026-03-29T13:29:33.898Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f4/7e/a72dd26f3b0f4f2bf1dd8923c85f7ceb43172af56d63c7383eb62b332364/pygments-2.20.0-py3-none-any.whl", hash = "sha256:81a9e26dd42fd28a23a2d169d86d7ac03b46e2f8b59ed4698fb4785f946d0176", size = 1231151, upload-time = "2026-03-29T13:29:30.038Z" },
+]
+
[[package]]
name = "pyjwt"
version = "2.10.1"
@@ -1546,6 +1582,24 @@ crypto = [
{ name = "cryptography" },
]
+[[package]]
+name = "pytest"
+version = "9.0.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "colorama", marker = "sys_platform == 'win32'" },
+ { name = "exceptiongroup", marker = "python_full_version < '3.11'" },
+ { name = "iniconfig" },
+ { name = "packaging" },
+ { name = "pluggy" },
+ { name = "pygments" },
+ { name = "tomli", marker = "python_full_version < '3.11'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/7d/0d/549bd94f1a0a402dc8cf64563a117c0f3765662e2e668477624baeec44d5/pytest-9.0.3.tar.gz", hash = "sha256:b86ada508af81d19edeb213c681b1d48246c1a91d304c6c81a427674c17eb91c", size = 1572165, upload-time = "2026-04-07T17:16:18.027Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d4/24/a372aaf5c9b7208e7112038812994107bc65a84cd00e0354a88c2c77a617/pytest-9.0.3-py3-none-any.whl", hash = "sha256:2c5efc453d45394fdd706ade797c0a81091eccd1d6e4bccfcd476e2b8e0ab5d9", size = 375249, upload-time = "2026-04-07T17:16:16.13Z" },
+]
+
[[package]]
name = "python-dotenv"
version = "1.2.1"
@@ -2078,6 +2132,7 @@ dependencies = [
{ name = "httpx", extra = ["socks"] },
{ name = "lark-oapi" },
{ name = "markdown-to-mrkdwn" },
+ { name = "packaging" },
{ name = "psutil" },
{ name = "pyjwt", extra = ["crypto"] },
{ name = "python-socks", extra = ["asyncio"] },
@@ -2090,6 +2145,11 @@ dependencies = [
{ name = "typing-extensions" },
]
+[package.dev-dependencies]
+dev = [
+ { name = "pytest" },
+]
+
[package.metadata]
requires-dist = [
{ name = "aiohttp", specifier = ">=3.8.0" },
@@ -2103,6 +2163,7 @@ requires-dist = [
{ name = "httpx", extras = ["socks"], specifier = ">=0.27" },
{ name = "lark-oapi", specifier = ">=1.4.0" },
{ name = "markdown-to-mrkdwn", specifier = ">=0.2.0" },
+ { name = "packaging", specifier = ">=23.0" },
{ name = "psutil", specifier = ">=5.9.0" },
{ name = "pyjwt", extras = ["crypto"], specifier = ">=2.9.0" },
{ name = "python-socks", extras = ["asyncio"], specifier = ">=2.0.0" },
@@ -2115,6 +2176,9 @@ requires-dist = [
{ name = "typing-extensions", specifier = ">=4.12.2" },
]
+[package.metadata.requires-dev]
+dev = [{ name = "pytest", specifier = ">=9.0.3" }]
+
[[package]]
name = "websockets"
version = "16.0"
diff --git a/vibe/api.py b/vibe/api.py
index b49875949..86618219c 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1475,6 +1475,440 @@ def install_agent(name: str) -> dict:
return {"ok": False, "message": str(e), "output": None}
+# =============================================================================
+# Backend lifecycle (version probe, latest check, restart)
+# =============================================================================
+
+# In-memory caches keyed by (backend, cli_path) so version answers stay tied
+# to the binary they came from. Trade freshness for fewer probes during rapid
+# popover opens. Tuned for human pacing (seconds), not bots.
+_BACKEND_VERSION_CACHE: dict[tuple[str, str], tuple[float, str | None]] = {}
+_BACKEND_LATEST_CACHE: dict[str, tuple[float, str | None]] = {}
+_BACKEND_VERSION_TTL_SECONDS = 30.0
+_BACKEND_LATEST_TTL_SECONDS = 3600.0
+# Failed lookups (network down, registry hiccup) re-probe sooner so a
+# transient outage doesn't pin "—" for the full hour.
+_BACKEND_LATEST_FAILURE_TTL_SECONDS = 120.0
+_BACKEND_RUNTIME_USER_AGENT = "vibe-remote/backend-runtime"
+
+_BACKENDS_WITH_RESTART = {"opencode", "codex"}
+_BACKEND_LATEST_PROBES = {
+ "opencode": ("github", "sst/opencode"),
+ "codex": ("npm", "@openai/codex"),
+ "claude": ("npm", "@anthropic-ai/claude-code"),
+}
+
+
+def _parse_semver(text: str) -> str | None:
+ """Extract the first dotted-numeric version token from *text*.
+
+ Handles outputs like ``opencode 1.2.3``, ``codex-cli 0.77.1 (build ...)``
+ and ``v1.0.0`` uniformly. Returns ``None`` if no version is found.
+ """
+ if not text:
+ return None
+ match = re.search(r"\d+(?:\.\d+){1,3}(?:[-+][\w.\-]+)?", text)
+ return match.group(0) if match else None
+
+
+def _probe_cli_version(cli_path: str | None) -> str | None:
+ """Run ``<cli> --version`` with a short timeout and return the parsed version."""
+ if not cli_path:
+ return None
+ try:
+ result = subprocess.run(
+ [cli_path, "--version"],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ env=_command_env_for(cli_path if os.path.isabs(cli_path) else None),
+ )
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError) as exc:
+ logger.debug("CLI version probe failed for %s: %s", cli_path, exc)
+ return None
+ output = (result.stdout or "") + " " + (result.stderr or "")
+ return _parse_semver(output.strip())
+
+
+def _fetch_latest_version(name: str) -> str | None:
+ """Best-effort upstream lookup. Returns ``None`` on any failure."""
+ probe = _BACKEND_LATEST_PROBES.get(name)
+ if not probe:
+ return None
+ kind, ident = probe
+ url = (
+ f"https://api.github.com/repos/{ident}/releases/latest"
+ if kind == "github"
+ else f"https://registry.npmjs.org/{ident}/latest"
+ )
+ try:
+ from vibe.proxy import resolve_proxy
+
+ proxy = resolve_proxy(None)
+ except Exception:
+ proxy = None
+
+ req = urllib.request.Request(url, headers={"User-Agent": _BACKEND_RUNTIME_USER_AGENT})
+ if proxy and not proxy.lower().startswith("socks"):
+ opener = urllib.request.build_opener(
+ urllib.request.ProxyHandler({"http": proxy, "https": proxy})
+ )
+ else:
+ # SOCKS proxies need aiohttp_socks; latest-version probe is best-effort
+ # so we silently fall back to direct urlopen rather than complicate the
+ # cache path. Direct-connection failures are cached for a short TTL.
+ opener = urllib.request.build_opener()
+
+ try:
+ with opener.open(req, timeout=5) as resp: # noqa: S310 - trusted registries
+ payload = json.loads(resp.read().decode("utf-8"))
+ except Exception as exc: # pragma: no cover - network failure path
+ logger.debug("Latest version probe failed for %s: %s", name, exc)
+ return None
+ raw = payload.get("tag_name") if kind == "github" else payload.get("version")
+ if not isinstance(raw, str):
+ return None
+ return raw.lstrip("v").strip() or None
+
+
+def _cached_version(name: str, cli_path: str | None) -> str | None:
+ key = (name, cli_path or "")
+ cached = _BACKEND_VERSION_CACHE.get(key)
+ if cached and time.time() - cached[0] < _BACKEND_VERSION_TTL_SECONDS:
+ return cached[1]
+ version = _probe_cli_version(cli_path)
+ _BACKEND_VERSION_CACHE[key] = (time.time(), version)
+ return version
+
+
+def _invalidate_version_cache(name: str) -> None:
+ """Drop all cached version entries for *name* across cli paths."""
+ for key in [k for k in _BACKEND_VERSION_CACHE if k[0] == name]:
+ _BACKEND_VERSION_CACHE.pop(key, None)
+
+
+def _cached_latest(name: str) -> str | None:
+ cached = _BACKEND_LATEST_CACHE.get(name)
+ if cached:
+ ttl = _BACKEND_LATEST_TTL_SECONDS if cached[1] else _BACKEND_LATEST_FAILURE_TTL_SECONDS
+ if time.time() - cached[0] < ttl:
+ return cached[1]
+ latest = _fetch_latest_version(name)
+ _BACKEND_LATEST_CACHE[name] = (time.time(), latest)
+ return latest
+
+
+def _compare_versions(current: str | None, latest: str | None) -> bool:
+ """Return True when *latest* is strictly greater than *current*.
+
+ Honors PEP 440 / semver pre-release ordering when possible (e.g. ``0.77.1``
+ is greater than ``0.77.1-beta.0``). Falls back to a conservative numeric
+ tuple comparison; returns False on any parsing failure so we never nag the
+ user with a phantom update.
+ """
+ if not current or not latest or current == latest:
+ return False
+
+ try:
+ from packaging.version import InvalidVersion, Version
+
+ try:
+ return Version(latest) > Version(current)
+ except InvalidVersion:
+ pass
+ except Exception: # pragma: no cover - packaging is a transitive dep
+ pass
+
+ def _parts(value: str) -> tuple[tuple[int, ...], bool] | None:
+ # Strip build metadata; keep pre-release tag to compare lexically.
+ core, _, pre = value.split("+", 1)[0].partition("-")
+ try:
+ nums = tuple(int(part) for part in core.split("."))
+ except ValueError:
+ return None
+ # A version with a pre-release suffix is "less than" the bare release.
+ return nums, bool(pre)
+
+ cur_parts = _parts(current)
+ new_parts = _parts(latest)
+ if cur_parts is None or new_parts is None:
+ return False
+ cur_nums, cur_is_pre = cur_parts
+ new_nums, new_is_pre = new_parts
+ if new_nums != cur_nums:
+ return new_nums > cur_nums
+ # Same numeric core: pre-release sorts before release.
+ return cur_is_pre and not new_is_pre
+
+
+def _opencode_server_pid() -> int | None:
+ pid_path = paths.get_logs_dir() / "opencode_server.json"
+ if not pid_path.exists():
+ return None
+ try:
+ info = json.loads(pid_path.read_text(encoding="utf-8"))
+ except Exception:
+ return None
+ pid = info.get("pid") if isinstance(info, dict) else None
+ return pid if isinstance(pid, int) and pid > 0 else None
+
+
+def _opencode_process_status() -> str:
+ from vibe import runtime
+
+ pid = _opencode_server_pid()
+ if not pid or not runtime.pid_alive(pid):
+ return "stopped"
+ cmd = runtime.get_process_command(pid) or ""
+ return "running" if "opencode" in cmd and "serve" in cmd else "unknown"
+
+
+def _process_matches_codex_binary(cmdline: list[str], resolved_binary: str | None) -> bool:
+ """Decide whether ``cmdline`` belongs to *our* codex app-server.
+
+ The original cmdline-substring check matched any ``codex`` mention in any
+ argument (e.g. a user invoking ``codex app-server`` themselves from a
+ shell, or another tool whose args happen to contain those tokens). We
+ now require:
+
+ 1. argv[0] resolves to the same absolute path as the configured
+ codex binary, **or** its basename starts with ``codex``; and
+ 2. one of the early arguments is exactly ``app-server``.
+
+ When ``resolved_binary`` is None we fall back to a basename match so the
+ chip still works for users whose config points at a CLI that isn't on
+ PATH right now.
+ """
+ if not cmdline:
+ return False
+ head = cmdline[0]
+ try:
+ head_resolved = str(Path(head).expanduser().resolve())
+ except Exception:
+ head_resolved = head
+ if resolved_binary:
+ # When we know which binary the user configured, require an exact
+ # match. A second codex install elsewhere on the system is *not* ours
+ # to kill.
+ try:
+ target = str(Path(resolved_binary).expanduser().resolve())
+ except Exception:
+ target = resolved_binary
+ if head_resolved != target:
+ return False
+ else:
+ # No resolved binary: best-effort basename match so the chip still
+ # works when the configured CLI isn't on PATH right now.
+ if not os.path.basename(head_resolved).startswith("codex"):
+ return False
+ # ``codex app-server`` always passes ``app-server`` as an argv token; we
+ # intentionally do NOT match it inside an arbitrary substring.
+ return "app-server" in cmdline[1:4]
+
+
+def _codex_processes(resolved_binary: str | None) -> list[int]:
+ """Find live ``codex app-server`` subprocesses owned by the current user.
+
+ The match must hit our resolved codex binary so unrelated tools that
+ happen to mention ``codex`` and ``app-server`` aren't swept up.
+ """
+ try:
+ import psutil
+ except ImportError: # pragma: no cover - psutil is a hard dep elsewhere
+ return []
+
+ current_uid = os.getuid() if hasattr(os, "getuid") else None
+ pids: list[int] = []
+ for proc in psutil.process_iter(attrs=["pid", "name", "cmdline", "uids"]):
+ try:
+ info = proc.info
+ cmdline = info.get("cmdline") or []
+ if not _process_matches_codex_binary(cmdline, resolved_binary):
+ continue
+ if current_uid is not None:
+ uids = info.get("uids")
+ proc_uid = getattr(uids, "real", None) if uids else None
+ if proc_uid is not None and proc_uid != current_uid:
+ continue
+ pids.append(info["pid"])
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ continue
+ return pids
+
+
+def _codex_process_status(resolved_binary: str | None) -> str:
+ return "running" if _codex_processes(resolved_binary) else "stopped"
+
+
+def get_backend_runtime(name: str) -> dict:
+ """Return live lifecycle info for one backend.
+
+ Versions are cached for short windows so popovers and re-renders do not
+ fan out into many CLI invocations or registry HTTP calls.
+ """
+ if name not in _BACKEND_LATEST_PROBES:
+ return {"ok": False, "error": f"Unknown backend: {name}"}
+
+ try:
+ config = V2Config.load()
+ except Exception as exc:
+ logger.debug("Failed to load config for backend runtime: %s", exc)
+ config = None
+
+ backend_cfg = getattr(getattr(config, "agents", None), name, None) if config else None
+ enabled = bool(getattr(backend_cfg, "enabled", False))
+ configured_path = getattr(backend_cfg, "cli_path", "") or name
+
+ resolved_path = resolve_cli_path(configured_path)
+ installed = resolved_path is not None
+
+ current_version = _cached_version(name, resolved_path) if installed else None
+ latest_version = _cached_latest(name)
+ has_update = _compare_versions(current_version, latest_version)
+
+ if name == "opencode":
+ process_status = _opencode_process_status() if installed else "stopped"
+ elif name == "codex":
+ process_status = _codex_process_status(resolved_path) if installed else "stopped"
+ else:
+ process_status = "unknown"
+
+ return {
+ "ok": True,
+ "name": name,
+ "enabled": enabled,
+ "cli_path": configured_path,
+ "resolved_path": resolved_path,
+ "installed": installed,
+ "current_version": current_version,
+ "latest_version": latest_version,
+ "has_update": has_update,
+ "supports_restart": name in _BACKENDS_WITH_RESTART,
+ "process_status": process_status,
+ }
+
+
+def _runtime_command_dir() -> Path:
+ """Directory the controller watches for cross-process command markers."""
+ base = paths.get_state_dir() / "runtime_commands"
+ base.mkdir(parents=True, exist_ok=True)
+ return base
+
+
+def _wait_for_controller_ack(marker: Path, timeout: float) -> bool:
+ """Poll for ``marker`` removal as a signal that the controller ran it."""
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if not marker.exists():
+ return True
+ time.sleep(0.1)
+ return False
+
+
+def _request_controller_restart(backend: str, timeout: float = 4.0) -> bool:
+ """Ask the controller to refresh a backend via the runtime-command marker.
+
+ The controller's ``RuntimeCommandWatcher`` (see ``core/runtime_commands.py``)
+ is the in-process owner of ``CodexAgent._transports`` / OpenCode server
+ state. Killing those processes from the UI server would leave that cache
+ stale, so the cleanest path is to ask the controller to call its existing
+ ``_refresh_backend_runtime(backend)`` for us. We drop a marker file and
+ wait briefly for the controller to delete it; the caller falls back to a
+ direct process kill when the controller is unreachable (e.g. running
+ detached, not yet started).
+ """
+ marker = _runtime_command_dir() / f"restart-{backend}.cmd"
+ try:
+ marker.write_text(
+ json.dumps({"backend": backend, "ts": time.time()}),
+ encoding="utf-8",
+ )
+ except OSError as exc:
+ logger.debug("Failed to write controller restart marker for %s: %s", backend, exc)
+ return False
+ if _wait_for_controller_ack(marker, timeout):
+ return True
+ # Marker still present — controller didn't pick it up. Clean up before
+ # falling back so we don't leave a stale request lying around.
+ try:
+ marker.unlink(missing_ok=True)
+ except OSError:
+ pass
+ return False
+
+
+def restart_backend(name: str) -> dict:
+ """Refresh the backend so the next request picks up new config/env.
+
+ Preferred path: drop a runtime-command marker that the controller
+ observes and reacts to via ``_refresh_backend_runtime``. This keeps the
+ controller's in-memory transport/session state consistent. If the
+ controller isn't running (e.g. service not yet started), we fall back to
+ killing the OS process directly — the controller's recovery logic will
+ rebuild state when it next starts.
+
+ Claude has no persistent process and is rejected at the route layer.
+ """
+ if name not in _BACKENDS_WITH_RESTART:
+ return {"ok": False, "message": f"Restart is not supported for backend: {name}"}
+
+ controller_handled = _request_controller_restart(name)
+ _invalidate_version_cache(name)
+
+ if controller_handled:
+ if name == "opencode":
+ return {"ok": True, "message": "OpenCode server refreshed; it will respawn on next request."}
+ return {"ok": True, "message": "Codex runtime refreshed; transports will respawn on next request."}
+
+ if name == "opencode":
+ from vibe import runtime
+ from vibe.cli import _stop_opencode_server
+
+ stopped = _stop_opencode_server()
+ if stopped:
+ return {"ok": True, "message": "OpenCode server stopped; it will respawn on next request."}
+ pid = _opencode_server_pid()
+ if not pid or not runtime.pid_alive(pid):
+ return {"ok": True, "message": "OpenCode server is not running; next request will start a fresh one."}
+ return {"ok": False, "message": "Failed to stop OpenCode server."}
+
+ # codex fallback: kill app-server processes; controller recovery rebuilds.
+ try:
+ import psutil
+ except ImportError:
+ return {"ok": False, "message": "psutil unavailable; cannot manage Codex processes."}
+
+ try:
+ config = V2Config.load()
+ backend_cfg = getattr(getattr(config, "agents", None), "codex", None)
+ configured = getattr(backend_cfg, "cli_path", "") or "codex"
+ except Exception:
+ configured = "codex"
+ resolved = resolve_cli_path(configured)
+
+ pids = _codex_processes(resolved)
+ if not pids:
+ return {"ok": True, "message": "Codex app-server is not running; next request will start a fresh one."}
+
+ failed: list[int] = []
+ for pid in pids:
+ try:
+ proc = psutil.Process(pid)
+ proc.terminate()
+ try:
+ proc.wait(timeout=5)
+ except psutil.TimeoutExpired:
+ proc.kill()
+ except (psutil.NoSuchProcess, psutil.AccessDenied) as exc:
+ logger.debug("Codex restart skip pid=%s: %s", pid, exc)
+ except Exception as exc:
+ logger.warning("Failed to stop codex pid=%s: %s", pid, exc)
+ failed.append(pid)
+ if failed:
+ return {"ok": False, "message": f"Failed to stop Codex process(es): {failed}"}
+ return {"ok": True, "message": f"Stopped {len(pids)} Codex process(es); they will respawn on next request."}
+
+
def codex_models() -> dict:
"""Best-effort merged list of Codex model options.
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index ec02bceac..e30aa3c22 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -1547,6 +1547,32 @@ def agent_install(name):
return jsonify(result)
+_ALLOWED_BACKENDS = {"opencode", "claude", "codex"}
+_BACKENDS_WITH_RESTART = {"opencode", "codex"}
+
+
[email protected]("/backend/<name>/runtime")
+def backend_runtime(name):
+ """Return lifecycle info (version, update, process status) for a backend."""
+ if name not in _ALLOWED_BACKENDS:
+ return jsonify({"ok": False, "error": f"Unknown backend: {name}"}), 400
+
+ from vibe import api
+
+ return jsonify(api.get_backend_runtime(name))
+
+
[email protected]("/backend/<name>/restart", methods=["POST"])
+def backend_restart(name):
+ """Restart a backend's persistent server process (opencode or codex)."""
+ if name not in _BACKENDS_WITH_RESTART:
+ return jsonify({"ok": False, "message": f"Restart is not supported for backend: {name}"}), 400
+
+ from vibe import api
+
+ return jsonify(api.restart_backend(name))
+
+
@app.route("/browse", methods=["POST"])
def browse_directory():
"""List sub-directories of a given path for the directory picker UI."""