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(agents): explain failed agent CLI installs and upgrades (#2253)

Call Whited8a3226f6d5c
diff --git a/tests/test_agent_install_failures.py b/tests/test_agent_install_failures.py
new file mode 100644
index 000000000..a7f02add2
--- /dev/null
+++ b/tests/test_agent_install_failures.py
@@ -0,0 +1,293 @@
+"""Failed agent CLI installs and upgrades explain themselves.
+
+The installer output fixtures below are real captures from npm 11, npm 9, curl
+and ``opencode upgrade``, with only the machine-specific paths replaced.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+import time
+import urllib.error
+from datetime import datetime
+from pathlib import Path
+
+import pytest
+
+from config.v2_config import V2Config
+from vibe import api
+
+NPM11_ENOTEMPTY = """\
+npm error code ENOTEMPTY
+npm error syscall rename
+npm error path /Users/alice/.local/lib/node_modules/@openai/codex
+npm error dest /Users/alice/.local/lib/node_modules/@openai/.codex-lD3lp9Ti
+npm error errno -66
+npm error ENOTEMPTY: directory not empty, rename '/Users/alice/.local/lib/node_modules/@openai/codex' -> '/Users/alice/.local/lib/node_modules/@openai/.codex-lD3lp9Ti'
+npm error A complete log of this run can be found in: /Users/alice/.npm/_logs/2026-09-28T04_25_05_600Z-debug-0.log
+"""
+
+NPM9_ENOTEMPTY = """\
+npm ERR! code ENOTEMPTY
+npm ERR! syscall rename
+npm ERR! path /usr/local/lib/node_modules/@openai/codex
+npm ERR! dest /usr/local/lib/node_modules/@openai/.codex-RT5f2oYD
+npm ERR! errno -66
+npm ERR! ENOTEMPTY: directory not empty, rename '/usr/local/lib/node_modules/@openai/codex' -> '/usr/local/lib/node_modules/@openai/.codex-RT5f2oYD'
+
+npm ERR! A complete log of this run can be found in: /Users/alice/.npm/_logs/2026-09-28T04_27_26_217Z-debug-0.log
+"""
+
+
+def _npm_permission(code: str, errno: str, message: str) -> str:
+ return f"""\
+npm error code {code}
+npm error syscall mkdir
+npm error path /usr/local/lib/node_modules/@openai
+npm error errno {errno}
+npm error Error: {code}: {message}, mkdir '/usr/local/lib/node_modules/@openai'
+npm error at async mkdir (node:internal/fs/promises:858:10)
+npm error at async Arborist.reify (/usr/local/lib/node_modules/npm/node_modules/@npmcli/arborist/lib/arborist/reify.js:125:5) {{
+npm error errno: {errno},
+npm error code: '{code}',
+npm error syscall: 'mkdir',
+npm error path: '/usr/local/lib/node_modules/@openai'
+npm error }}
+npm error
+npm error The operation was rejected by your operating system.
+npm error It is likely you do not have the permissions to access this file as the current user
+npm error A complete log of this run can be found in: /Users/alice/.npm/_logs/2026-09-28T04_25_13_596Z-debug-0.log
+"""
+
+
+NPM_ENOTFOUND = """\
+npm error code ENOTFOUND
+npm error syscall getaddrinfo
+npm error errno ENOTFOUND
+npm error network request to https://registry.npmjs.org/@openai%2fcodex failed, reason: getaddrinfo ENOTFOUND registry.npmjs.org
+npm error network This is a problem related to network connectivity.
+npm error network In most cases you are behind a proxy or have bad network settings.
+npm error A complete log of this run can be found in: /Users/alice/.npm/_logs/2026-09-28T04_25_20_730Z-debug-0.log
+"""
+
+NPM9_ENOTFOUND = NPM_ENOTFOUND.replace("npm error", "npm ERR!")
+
+NPM_ECONNREFUSED = """\
+npm error code ECONNREFUSED
+npm error syscall connect
+npm error errno ECONNREFUSED
+npm error FetchError: request to http://127.0.0.1:7890/@openai%2fcodex failed, reason: connect ECONNREFUSED 127.0.0.1:7890
+npm error at ClientRequest.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/minipass-fetch/lib/index.js:130:14) {
+npm error code: 'ECONNREFUSED',
+npm error errno: 'ECONNREFUSED',
+npm error syscall: 'connect',
+npm error }
+npm error If you are behind a proxy, please make sure that the
+npm error 'proxy' config is set properly. See: 'npm help config'
+"""
+
+NPM_ETIMEDOUT = """\
+npm error code ETIMEDOUT
+npm error syscall connect
+npm error errno ETIMEDOUT
+npm error network request to https://registry.npmjs.org/@openai%2fcodex failed, reason: connect ETIMEDOUT 104.16.0.35:443
+npm error network This is a problem related to network connectivity.
+"""
+
+OPENCODE_UPGRADE_403 = """\
+● Using method: curl
+Error: Unexpected error
+StatusCode: non 2xx status code (403 GET https://api.github.com/repos/anomalyco/opencode/releases/latest)
+"""
+
+
+def github_rate_limit(monkeypatch):
+ """Answer ``GET /rate_limit`` at the HTTP boundary; record what was asked."""
+
+ requests: list[tuple[str, float]] = []
+ answer: dict = {"error": urllib.error.URLError("offline")}
+
+ class Opener:
+ def open(self, request, timeout):
+ requests.append((request.full_url, timeout))
+ if "error" in answer:
+ raise answer["error"]
+ return io.BytesIO(json.dumps(answer["payload"]).encode("utf-8"))
+
+ monkeypatch.setattr(api, "_http_opener_for_best_effort_probe", Opener)
+ return requests, answer
+
+
+def _installer(tmp_path: Path, *, stderr: str, exit_code: int) -> list[str]:
+ """A real installer process that prints what a failing installer prints."""
+
+ (tmp_path / "installer.err").write_text(stderr, encoding="utf-8")
+ script = tmp_path / "installer.sh"
+ script.write_text(
+ f'#!/bin/sh\necho "added 0 packages"\ncat "{tmp_path / "installer.err"}" >&2\nexit {exit_code}\n',
+ encoding="utf-8",
+ )
+ script.chmod(0o755)
+ return [str(script)]
+
+
+ ("output", "code", "params"),
+ [
+ pytest.param(
+ NPM11_ENOTEMPTY,
+ "npm_leftover_directory",
+ {"path": "/Users/alice/.local/lib/node_modules/@openai/.codex-lD3lp9Ti"},
+ id="npm11-enotempty",
+ ),
+ pytest.param(
+ NPM9_ENOTEMPTY,
+ "npm_leftover_directory",
+ {"path": "/usr/local/lib/node_modules/@openai/.codex-RT5f2oYD"},
+ id="npm9-enotempty",
+ ),
+ pytest.param(
+ _npm_permission("EACCES", "-13", "permission denied"),
+ "permission_denied",
+ {"path": "/usr/local/lib/node_modules/@openai"},
+ id="npm-eacces",
+ ),
+ pytest.param(
+ _npm_permission("EACCES", "-13", "permission denied").replace("npm error", "npm ERR!"),
+ "permission_denied",
+ {"path": "/usr/local/lib/node_modules/@openai"},
+ id="npm9-eacces",
+ ),
+ pytest.param(
+ _npm_permission("EPERM", "-1", "operation not permitted"),
+ "permission_denied",
+ {"path": "/usr/local/lib/node_modules/@openai"},
+ id="npm-eperm",
+ ),
+ pytest.param(OPENCODE_UPGRADE_403, "github_rate_limited", {"reset_at": None}, id="opencode-github-403"),
+ pytest.param(NPM_ENOTFOUND, "network_unreachable", {"host": "registry.npmjs.org"}, id="npm-enotfound"),
+ pytest.param(NPM9_ENOTFOUND, "network_unreachable", {"host": "registry.npmjs.org"}, id="npm9-enotfound"),
+ pytest.param(NPM_ECONNREFUSED, "network_unreachable", {"host": "127.0.0.1"}, id="npm-econnrefused"),
+ pytest.param(NPM_ETIMEDOUT, "network_unreachable", {"host": "registry.npmjs.org"}, id="npm-etimedout"),
+ pytest.param(
+ "curl: (6) Could not resolve host: claude.ai\n",
+ "network_unreachable",
+ {"host": "claude.ai"},
+ id="curl-dns",
+ ),
+ pytest.param(
+ "curl: (7) Failed to connect to opencode.ai port 443 after 0 ms: Couldn't connect to server\n",
+ "network_unreachable",
+ {"host": "opencode.ai"},
+ id="curl-connect",
+ ),
+ pytest.param(
+ "curl: (28) Failed to connect to claude.ai port 443 after 10002 ms: Timeout was reached\n",
+ "network_unreachable",
+ {"host": "claude.ai"},
+ id="curl-connect-timeout",
+ ),
+ # A reachable server that refuses the download is not a network problem.
+ pytest.param("curl: (56) The requested URL returned error: 404\n", "install_failed", {}, id="curl-http-404"),
+ # npm renaming a retired copy back is not a leftover from an earlier run.
+ pytest.param(
+ "npm error ENOTEMPTY: directory not empty, rename "
+ "'/usr/local/lib/node_modules/@openai/.codex-RT5f2oYD' -> '/usr/local/lib/node_modules/@openai/codex'\n",
+ "install_failed",
+ {},
+ id="npm-enotempty-not-retire",
+ ),
+ pytest.param("Error: something unexpected happened\n", "install_failed", {}, id="unrecognized"),
+ pytest.param(None, "install_failed", {}, id="no-output"),
+ ],
+)
+def test_recognize_install_failure(github_rate_limit, output, code, params):
+ requests, _answer = github_rate_limit
+
+ assert api._recognize_install_failure(output) == (code, params)
+ # Only a GitHub API refusal is worth asking GitHub about.
+ assert bool(requests) == (code == "github_rate_limited")
+
+
+def test_recognize_install_failure_reports_timeout_first():
+ assert api._recognize_install_failure(NPM_ENOTFOUND, timed_out=True) == ("install_timeout", {"minutes": 5})
+
+
+ ("language", "message", "hint"),
+ [
+ (
+ "en",
+ "Could not upgrade Codex.",
+ "npm left a temporary folder behind from an earlier interrupted update: "
+ "/Users/alice/.local/lib/node_modules/@openai/.codex-lD3lp9Ti. Delete that folder, then try again.",
+ ),
+ (
+ "zh",
+ "无法升级 Codex。",
+ "npm 在之前一次中断的更新中留下了临时目录:/Users/alice/.local/lib/node_modules/@openai/.codex-lD3lp9Ti。删除该目录后重试。",
+ ),
+ ],
+)
+def test_failed_upgrade_names_the_leftover_npm_directory(tmp_path, language, message, hint):
+ config = V2Config.default()
+ config.language = language
+ config.save()
+ cmd = _installer(tmp_path, stderr=NPM11_ENOTEMPTY, exit_code=190)
+
+ result = api._run_install_command("codex", cmd, lambda value: value, mode="upgrade")
+
+ assert result["ok"] is False
+ assert result["message"] == message
+ assert result["code"] == "npm_leftover_directory"
+ assert result["hint_params"] == {"path": "/Users/alice/.local/lib/node_modules/@openai/.codex-lD3lp9Ti"}
+ assert result["hint"] == hint
+ assert result["exit_code"] == 190
+ assert result["reason"] == "codex_upgrade_failed"
+ assert result["output"].startswith("added 0 packages")
+ assert result["output"].endswith(NPM11_ENOTEMPTY.strip())
+
+
+def test_unrecognized_failure_keeps_the_generic_message_and_output(tmp_path):
+ cmd = _installer(tmp_path, stderr="Error: something unexpected happened\n", exit_code=3)
+
+ result = api._run_install_command("claude", cmd, lambda value: value, mode="install")
+
+ assert result["message"] == "Could not install Claude Code."
+ assert result["code"] == "install_failed"
+ assert result["hint"] is None
+ assert result["exit_code"] == 3
+ assert result["output"].startswith("added 0 packages")
+ assert result["output"].endswith("Error: something unexpected happened")
+
+
[email protected]("lookup", ["exhausted", "unavailable", "not-exhausted"])
+def test_github_403_hint_says_when_the_limit_resets(tmp_path, github_rate_limit, lookup):
+ requests, answer = github_rate_limit
+ reset_at = int(time.time()) + 600
+ if lookup != "unavailable":
+ remaining = 0 if lookup == "exhausted" else 12
+ answer.pop("error")
+ answer["payload"] = {"resources": {"core": {"limit": 60, "remaining": remaining, "reset": reset_at}}}
+ cmd = _installer(tmp_path, stderr=OPENCODE_UPGRADE_403, exit_code=1)
+
+ result = api._run_install_command("opencode", cmd, lambda value: value, mode="upgrade")
+
+ assert [url for url, _timeout in requests] == ["https://api.github.com/rate_limit"]
+ assert all(timeout <= 5 for _url, timeout in requests)
+ assert result["message"] == "Could not upgrade OpenCode."
+ assert result["code"] == "github_rate_limited"
+ if lookup == "exhausted":
+ assert result["hint_params"] == {"reset_at": reset_at}
+ assert result["hint"] == (
+ "GitHub's API limit for this network is used up. It resets at "
+ f"{datetime.fromtimestamp(reset_at).strftime('%H:%M')} (in about 10 min); try again after that."
+ )
+ else:
+ assert result["hint_params"] == {"reset_at": None}
+ assert result["hint"] == (
+ "GitHub's API limit for this network is used up. It resets within an hour; try again later."
+ )
+ assert "403 GET https://api.github.com/repos/anomalyco/opencode/releases/latest" in result["output"]
diff --git a/ui/e2e/badge-triggers/fixture.tsx b/ui/e2e/badge-triggers/fixture.tsx
index 978c50ab0..ff58ba0d5 100644
--- a/ui/e2e/badge-triggers/fixture.tsx
+++ b/ui/e2e/badge-triggers/fixture.tsx
@@ -20,8 +20,8 @@ export function Fixture() {
const runtime: BackendRuntimeState = {
loaded: true, configError: false, enabled, cliPath,
cliStatus: state === 'error' ? 'missing' : state === 'loading' ? 'unknown' : 'ok',
- detecting: false, installing: false, installResult: null, installOutputOpen: false,
- savingRuntime: false, runtimeDirty: false, connectionRevision: 0, setCliPath, setInstallOutputOpen: noop,
+ detecting: false, installing: false, installResult: null,
+ savingRuntime: false, runtimeDirty: false, connectionRevision: 0, setCliPath,
detect: asyncNoop, install: asyncNoop, onSaveRuntime: asyncNoop,
toggleEnabled: () => setEnabled((previous) => !previous), handleLifecycleChanged: asyncNoop,
};
diff --git a/ui/src/components/onboarding/AssistantRow.tsx b/ui/src/components/onboarding/AssistantRow.tsx
index f5d33cbf0..9b4e1965a 100644
--- a/ui/src/components/onboarding/AssistantRow.tsx
+++ b/ui/src/components/onboarding/AssistantRow.tsx
@@ -6,6 +6,7 @@ import { Button } from '../ui/button';
import { Badge } from '../ui/badge';
import { Card } from '../ui/card';
import { getBackendUiMeta } from '@/lib/agentBackends';
+import { InstallOutcome } from '../shared/InstallOutcome';
import type { AssistantId } from './collaborationTimeline';
/** One card's reading of its current Model Hub route. */
@@ -18,9 +19,9 @@ export interface AssistantRowProps {
status: 'unknown' | 'ok' | 'missing';
installing: boolean;
detecting: boolean;
- error?: { message: string; output?: string | null };
+ error?: { message: string; hint?: string | null; output?: string | null; exit_code?: number };
lifecycle: ReactNode;
- /** The action the lifecycle pill offers — update or upgrade-in-flight — drawn
+ /** The action the lifecycle pill offers — update, reinstall or upgrade-in-flight — drawn
opposite the pill on the state row, where the design puts it. */
upgrade?: ReactNode;
enabledControl: ReactNode;
@@ -216,10 +217,8 @@ export function AssistantRow({ backend, status, installing, detecting, error, li
{routeError}
{onRetryRoute && <Button variant="link" size="xs" onClick={onRetryRoute}>{t('common.retry')}</Button>}
</div>}
- {error && <div className="onboarding-assistant-error" role="alert">
- <p>{error.message}</p>
- {error.output && <details><summary>{t('onboarding.details')}</summary><pre>{error.output}</pre></details>}
- </div>}
+ {error && <InstallOutcome className="onboarding-assistant-error"
+ result={{ ...error, ok: false, output: error.output ?? null }} />}
</div>
</Card>
);
diff --git a/ui/src/components/onboarding/AssistantSetup.test.tsx b/ui/src/components/onboarding/AssistantSetup.test.tsx
index bdce361c2..8776c9dea 100644
--- a/ui/src/components/onboarding/AssistantSetup.test.tsx
+++ b/ui/src/components/onboarding/AssistantSetup.test.tsx
@@ -217,7 +217,7 @@ describe('assistant installation presentation', () => {
await waitFor(() => expect(row('Codex').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy());
await act(async () => finishClaude({ ok: false, message: 'Network unavailable', output: 'Installer exited 1' }));
expect(row('Claude Code').getByText('Network unavailable')).toBeTruthy();
- expect(row('Claude Code').getByText('View details')).toBeTruthy();
+ expect(row('Claude Code').getByText(en.agentDetection.showOutput)).toBeTruthy();
expect(row('Codex').getByRole('button', { name: en.onboarding.setup.enabled })).toBeTruthy();
expect(row('OpenCode').getByText('Not installed')).toBeTruthy();
mock.api.installAgent.mockResolvedValue({ ok: true, path: '/isolated/bin/claude' });
@@ -374,6 +374,69 @@ describe('assistant installation presentation', () => {
await waitFor(() => expect(next).toHaveBeenCalled());
expect(mock.api.installAgent).not.toHaveBeenCalled();
});
+ it('keeps a failed upgrade from the state row on the card with its reason and output', async () => {
+ const saved = data(); saved.agents.codex.status = 'ok';
+ mock.api.getBackendRuntime.mockResolvedValue({ installed: true, has_update: true, current_version: '1', latest_version: '2' });
+ const failure = {
+ ok: false, message: 'Could not upgrade Codex.', code: 'npm_leftover_directory', exit_code: 190,
+ hint: 'npm left a temporary folder behind from an earlier interrupted update: /usr/local/lib/node_modules/@openai/.codex-lD3lp9Ti. Delete that folder, then try again.',
+ output: 'npm error code ENOTEMPTY\nnpm error dest /usr/local/lib/node_modules/@openai/.codex-lD3lp9Ti',
+ };
+ mock.api.installAgent.mockResolvedValue(failure);
+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
+ fireEvent.click(await row('Codex').findByRole('button', { name: en.backendLifecycle.upgradeNow }));
+
+ const outcome = await row('Codex').findByRole('alert');
+ expect(mock.showToast).toHaveBeenCalledWith(failure.message, 'error');
+ expect(within(outcome).getByText(failure.message)).toBeTruthy();
+ expect(within(outcome).getByText(failure.hint)).toBeTruthy();
+ expect(within(outcome).getByText(en.agentDetection.showOutput)).toBeTruthy();
+ expect(within(outcome).getByText('Exit code: 190')).toBeTruthy();
+ expect(outcome.querySelector('pre')?.textContent).toBe(failure.output);
+ // Once the chip has read the CLI back, trying again is one click away.
+ await waitFor(() => expect(row('Codex').getByRole('button', { name: en.backendLifecycle.upgradeNow }).hasAttribute('disabled')).toBe(false));
+ });
+ it('re-detects a CLI a failed upgrade from the state row removed, keeping the reason', async () => {
+ const saved = data(); saved.agents.codex.status = 'ok';
+ mock.api.getBackendRuntime.mockResolvedValue({ installed: true, has_update: true, current_version: '1', latest_version: '2' });
+ mock.api.installAgent.mockImplementation(async () => {
+ mock.api.detectCli.mockResolvedValue({ found: false, path: null });
+ mock.api.getBackendRuntime.mockResolvedValue({ installed: false, has_update: false, resolved_path: null });
+ return { ok: false, message: 'Could not upgrade Codex.', output: 'npm error code ENOTEMPTY' };
+ });
+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
+ fireEvent.click(await row('Codex').findByRole('button', { name: en.backendLifecycle.upgradeNow }));
+
+ // The row falls back to the install state, marked as failed, with the reason kept.
+ expect(await row('Codex').findByRole('button', { name: en.common.retry })).toBeTruthy();
+ expect(row('Codex').getByText(en.onboarding.setup.installFailed)).toBeTruthy();
+ expect(row('Codex').getByText('Could not upgrade Codex.')).toBeTruthy();
+ });
+ it('holds the state row until the chip reads an upgrade back, then offers it again if still behind', async () => {
+ const path = '/isolated/bin/codex';
+ const saved = data(); saved.agents.codex.status = 'ok'; saved.agents.codex.cli_path = path;
+ const behind = { installed: true, has_update: true, current_version: '1', latest_version: '2', resolved_path: path };
+ mock.api.getBackendRuntime.mockResolvedValue(behind);
+ mock.api.detectCli.mockResolvedValue({ found: true, path });
+ let readBack!: (runtime: typeof behind) => void;
+ mock.api.installAgent.mockImplementation(async () => {
+ // A native updater can exit zero without moving the version.
+ mock.api.getBackendRuntime.mockReturnValue(new Promise((resolve) => { readBack = resolve; }));
+ return { ok: true, path };
+ });
+ render(wrap(<AgentDetection data={saved} onNext={vi.fn()} />));
+ const detections = mock.api.detectCli.mock.calls.length;
+ fireEvent.click(await row('Codex').findByRole('button', { name: en.backendLifecycle.upgradeNow }));
+
+ await waitFor(() => expect(mock.api.detectCli.mock.calls.length).toBeGreaterThan(detections));
+ await act(async () => {});
+ // The attempt is over but the chip has not read it back: nothing to re-arm on yet.
+ expect(row('Codex').queryByRole('button', { name: en.backendLifecycle.upgradeNow })).toBeNull();
+ expect(row('Codex').getByRole('button', { name: en.backendLifecycle.upgrading }).hasAttribute('disabled')).toBe(true);
+
+ await act(async () => readBack(behind));
+ await waitFor(() => expect(row('Codex').getByRole('button', { name: en.backendLifecycle.upgradeNow }).hasAttribute('disabled')).toBe(false));
+ });
it('retains a detection error separately from missing installation', async () => {
mock.api.detectCli.mockRejectedValue(new Error('Probe failed'));
render(wrap(<AgentDetection data={{ ...data(), __onboardingDetected: false }} onNext={vi.fn()} />));
diff --git a/ui/src/components/onboarding/onboarding.css b/ui/src/components/onboarding/onboarding.css
index f41d19e5f..11fad1cc6 100644
--- a/ui/src/components/onboarding/onboarding.css
+++ b/ui/src/components/onboarding/onboarding.css
@@ -1214,7 +1214,7 @@
}
.onboarding-assistant-error { font-size: 12px; color: var(--destructive-ink); overflow-wrap: anywhere; margin-top: 8px; }
.onboarding-assistant-error pre { margin-top: 8px; max-height: 160px; overflow: auto; white-space: pre-wrap; }
-.onboarding-assistant-error summary { margin-top: 8px; cursor: pointer; }
+.onboarding-assistant-error summary { margin-top: 8px; cursor: pointer; color: inherit; }
/* "Open workspace and Back to introduction share a width and stack vertically." The
full width is what makes that true: without it this column shrink-wraps its widest
child, and the action's own `299/976` then resolves against that shrunken box and
diff --git a/ui/src/components/settings/BackendLifecycleChip.test.tsx b/ui/src/components/settings/BackendLifecycleChip.test.tsx
index f438617d3..bb1c3b09b 100644
--- a/ui/src/components/settings/BackendLifecycleChip.test.tsx
+++ b/ui/src/components/settings/BackendLifecycleChip.test.tsx
@@ -1,6 +1,7 @@
/* @vitest-environment jsdom */
-import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { useState } from 'react';
+import { cleanup, render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -23,15 +24,18 @@ vi.mock('@/context/ToastContext', () => ({
}));
vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
+ useTranslation: () => ({
+ t: (key: string, options?: Record<string, unknown>) => (options ? `${key} ${JSON.stringify(options)}` : key),
+ }),
}));
+const codexPath = '/usr/local/bin/codex';
const updateAvailable = {
ok: true,
name: 'codex',
enabled: true,
- cli_path: '/usr/local/bin/codex',
- resolved_path: '/usr/local/bin/codex',
+ cli_path: codexPath,
+ resolved_path: codexPath,
installed: true,
current_version: '1.0.0',
latest_version: '1.1.0',
@@ -40,6 +44,25 @@ const updateAvailable = {
process_status: 'running',
};
+// What ``install_agent`` returns for a failed upgrade: the headline and hint are
+// the server's, already localized; the UI's job is to keep them in view.
+const npmLeftover = {
+ ok: false,
+ message: 'Could not upgrade Codex.',
+ code: 'npm_leftover_directory',
+ hint: 'npm left a temporary folder behind from an earlier interrupted update: /usr/local/lib/node_modules/@openai/.codex-lD3lp9Ti. Delete that folder, then try again.',
+ exit_code: 190,
+ output: 'npm error code ENOTEMPTY\nnpm error dest /usr/local/lib/node_modules/@openai/.codex-lD3lp9Ti',
+};
+const unrecognized = {
+ ok: false,
+ message: 'Could not upgrade Codex.',
+ code: 'install_failed',
+ hint: null,
+ exit_code: 1,
+ output: 'Error: something unexpected happened',
+};
+
const deferred = <T,>() => {
let resolve!: (value: T) => void;
const promise = new Promise<T>((settle) => {
@@ -64,7 +87,7 @@ describe('BackendLifecycleChip', () => {
api.installAgent.mockReturnValue(install.promise);
const user = userEvent.setup();
- render(<BackendLifecycleChip name="codex" enabled cliStatus="ok" />);
+ render(<BackendLifecycleChip name="codex" enabled cliStatus="ok" cliPath={codexPath} />);
const chip = await screen.findByRole('button', {
name: 'backendLifecycle.statusUpdateAvailable',
@@ -97,4 +120,123 @@ describe('BackendLifecycleChip', () => {
'backendLifecycle.statusUpdateAvailable',
));
});
+
+ it.each([
+ ['a recognized failure with its hint', npmLeftover, [npmLeftover.message, npmLeftover.hint]],
+ ['an unrecognized failure with the generic message only', unrecognized, [unrecognized.message]],
+ ])('keeps %s and the installer output in the popover until the next attempt', async (_case, failure, lines) => {
+ api.installAgent.mockResolvedValue(failure);
+ const user = userEvent.setup();
+
+ render(<BackendLifecycleChip name="codex" enabled cliStatus="ok" cliPath={codexPath} />);
+ const chip = await screen.findByRole('button', { name: 'backendLifecycle.statusUpdateAvailable' });
+ await user.click(chip);
+ await user.click(await screen.findByRole('button', { name: 'backendLifecycle.upgradeNow' }));
+
+ await waitFor(() => expect(showToast).toHaveBeenCalledWith('Could not upgrade Codex.', 'error'));
+ // Dismissing the popover is when the toast would have been the only record.
+ await user.click(document.body);
+ await user.click(chip);
+ const outcome = await screen.findByRole('alert');
+ expect([...outcome.querySelectorAll(':scope > p')].map((line) => line.textContent)).toEqual(lines);
+ expect(within(outcome).getByText('agentDetection.showOutput')).toBeTruthy();
+ expect(within(outcome).getByText(`agentDetection.exitCode {"code":${failure.exit_code}}`)).toBeTruthy();
+ expect(outcome.querySelector('pre')?.textContent).toBe(failure.output);
+
+ const retry = deferred<{ ok: boolean; message: string; output: null }>();
+ api.installAgent.mockReturnValue(retry.promise);
+ await user.click(screen.getByRole('button', { name: 'backendLifecycle.upgradeNow' }));
+ expect(screen.queryByRole('alert')).toBeNull();
+ retry.resolve({ ok: true, message: '', output: null });
+ await waitFor(() => expect(showToast).toHaveBeenCalledWith('backendLifecycle.upgradeSuccess', 'success'));
+ });
+
+ it('retires a failure once the host detects a different executable', async () => {
+ api.installAgent.mockResolvedValue(npmLeftover);
+ const user = userEvent.setup();
+
+ // A Settings card has no refresh generation; only the path says which CLI it shows.
+ const { rerender } = render(<BackendLifecycleChip name="codex" enabled cliStatus="ok" cliPath={codexPath} />);
+ const chip = await screen.findByRole('button', { name: 'backendLifecycle.statusUpdateAvailable' });
+ await user.click(chip);
+ await user.click(await screen.findByRole('button', { name: 'backendLifecycle.upgradeNow' }));
+ expect((await screen.findByRole('alert')).textContent).toContain(npmLeftover.hint);
+
+ rerender(<BackendLifecycleChip name="codex" enabled cliStatus="ok" cliPath="/opt/homebrew/bin/codex" />);
+
+ expect(screen.queryByRole('alert')).toBeNull();
+ expect(screen.getByText('backendLifecycle.title')).toBeTruthy();
+ });
+
+ it('has the host re-detect a CLI a failed upgrade removed, so it offers a reinstall', async () => {
+ const disk = { present: true };
+ api.installAgent.mockImplementation(async () => {
+ disk.present = false;
+ api.getBackendRuntime.mockResolvedValue({ ...updateAvailable, resolved_path: null, installed: false, current_version: null, has_update: false });
+ return npmLeftover;
+ });
+ // The host owns detection: it reads the disk again whenever the chip reports a change.
+ const Host = () => {
+ const [cliStatus, setCliStatus] = useState<'ok' | 'missing'>('ok');
+ return (
+ <BackendLifecycleChip name="codex" enabled cliStatus={cliStatus} cliPath={codexPath}
+ onChanged={() => setCliStatus(disk.present ? 'ok' : 'missing')} />
+ );
+ };
+ const user = userEvent.setup();
+
+ render(<Host />);
+ const chip = await screen.findByRole('button', { name: 'backendLifecycle.statusUpdateAvailable' });
+ await user.click(chip);
+ await user.click(await screen.findByRole('button', { name: 'backendLifecycle.upgradeNow' }));
+
+ await waitFor(() => expect(chip.getAttribute('aria-label')).toBe('backendLifecycle.statusError'));
+ expect(screen.getByRole('alert').textContent).toContain(npmLeftover.hint);
+ expect(screen.getByRole('button', { name: 'backendLifecycle.reinstall' })).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'backendLifecycle.restart' })).toBeNull();
+ });
+
+ // Every notice the popover can show, most urgent first. Each state below overlaps
+ // with something reassuring — a desktop-managed install, a stale "latest" — and
+ // the popover must say what is wrong rather than that all is well.
+ const NOTICES = [
+ 'backendLifecycle.upgrading',
+ 'backendLifecycle.errorHint',
+ 'backendLifecycle.updateHint',
+ 'backendLifecycle.desktopManagedHint',
+ 'backendLifecycle.readyHint',
+ ];
+ const latest = { ...updateAvailable, current_version: '1.1.0', has_update: false };
+ const managed = { managed_by: 'desktop' as const };
+ it.each([
+ { state: 'ready', runtime: latest, notice: 'backendLifecycle.readyHint' },
+ { state: 'desktop-managed', runtime: { ...latest, ...managed }, notice: 'backendLifecycle.desktopManagedHint' },
+ { state: 'desktop-managed with an update', runtime: { ...updateAvailable, ...managed }, notice: 'backendLifecycle.updateHint' },
+ { state: 'desktop-managed and not found', runtime: { ...latest, ...managed }, cliStatus: 'missing' as const, notice: 'backendLifecycle.errorHint {"name":"Codex"}' },
+ { state: 'desktop-managed after a failed upgrade', runtime: { ...updateAvailable, ...managed }, after: { ...latest, ...managed }, notice: null },
+ { state: 'reading as latest after a failed upgrade', runtime: updateAvailable, after: latest, notice: null },
+ { state: 'still behind after a failed upgrade', runtime: updateAvailable, after: updateAvailable, notice: 'backendLifecycle.updateHint' },
+ ])('says what matters most when $state', async ({ runtime, cliStatus = 'ok', after, notice }) => {
+ api.getBackendRuntime.mockResolvedValue(runtime);
+ api.installAgent.mockImplementation(async () => {
+ api.getBackendRuntime.mockResolvedValue(after);
+ return unrecognized;
+ });
+ const user = userEvent.setup();
+
+ render(<BackendLifecycleChip name="codex" enabled cliStatus={cliStatus} cliPath={codexPath} />);
+ await user.click(screen.getByRole('button'));
+ const popover = (await screen.findByText('backendLifecycle.title')).closest('div.z-50') as HTMLElement;
+ const refresh = within(popover).getByRole('button', { name: 'common.refresh' });
+ const settled = () => waitFor(() => expect(refresh.hasAttribute('disabled')).toBe(false));
+ await settled();
+ if (after) {
+ await user.click(within(popover).getByRole('button', { name: 'backendLifecycle.upgradeNow' }));
+ await settled();
+ expect(within(popover).getByRole('alert').textContent).toContain(unrecognized.message);
+ }
+
+ expect(NOTICES.filter((key) => popover.textContent?.includes(key))).toEqual(notice ? [notice.split(' ')[0]] : []);
+ if (notice) expect(popover.textContent).toContain(notice);
+ });
});
diff --git a/ui/src/components/settings/BackendLifecycleChip.tsx b/ui/src/components/settings/BackendLifecycleChip.tsx
index ac7ebda6b..baed04c46 100644
--- a/ui/src/components/settings/BackendLifecycleChip.tsx
+++ b/ui/src/components/settings/BackendLifecycleChip.tsx
@@ -4,12 +4,14 @@ import { AlertCircle, Check, Download, RefreshCw, RotateCw, X } from 'lucide-rea
import clsx from 'clsx';
import { useApi, type BackendRuntimeInfo } from '../../context/ApiContext';
import { useToast } from '../../context/ToastContext';
+import { InstallOutcome, type InstallOutcomeResult } from '../shared/InstallOutcome';
import { Button } from '../ui/button';
import {
badgeVariants,
interactiveBadgeTriggerClassName,
mobileHeaderPopoverClassName,
} from '../ui/badge-variants';
+import { getBackendUiMeta } from '@/lib/agentBackends';
import { cn } from '@/lib/utils';
type CliStatus = 'unknown' | 'ok' | 'missing';
@@ -32,6 +34,10 @@ interface BackendLifecycleChipProps {
name: string;
enabled: boolean;
cliStatus: CliStatus;
+ /** The executable ``cliStatus`` was detected at. A failed upgrade describes
+ the executable it ran against, so its explanation retires once the host
+ detects a different one. */
+ cliPath: string;
/** Setup describes executable availability separately from connection readiness. */
readyLabel?: string;
/** Setup reads an off switch as a step the person has not taken yet, not as a
@@ -46,7 +52,9 @@ interface BackendLifecycleChipProps {
onVisual?: (visual: Visual) => void;
/** Bumped by a host that applied an upgrade through its own affordance — the
setup card's state-row button — so the chip's projection, and with it the
- pill, follows a change the chip did not make itself. */
+ pill, follows a change the chip did not make itself. The pill reads as
+ updating until that probe settles, so the host's affordance cannot re-arm
+ on the verdict from before the change. */
refreshKey?: number;
/** A host-owned lifecycle operation in flight — the setup card draws its own
upgrade affordance on the state row — so the chip's popover cannot launch a
@@ -80,6 +88,7 @@ const deriveVisual = (
cliStatus: CliStatus,
runtime: BackendRuntimeInfo | null,
operation: Operation,
+ confirming: boolean,
): 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.
@@ -92,6 +101,10 @@ const deriveVisual = (
// that window the local detection is the fresher signal — trust it and
// do not flip the chip to error just because the saved config is stale.
if (cliStatus !== 'ok' && runtime && runtime.installed === false) return 'error';
+ // A change the host applied is not done until the probe it asked for has read
+ // it back, just as the chip's own upgrade stays in progress through its probe;
+ // until then the runtime still describes the CLI from before the change.
+ if (confirming) return 'updating';
// ``opencode serve`` and ``codex app-server`` are lazy-spawn daemons: they
// stay stopped until a session needs them, so ``process_status === 'stopped'``
// is the normal idle state, not an error. Restart still works on demand
@@ -114,6 +127,7 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
name,
enabled,
cliStatus,
+ cliPath,
onChanged,
onOperationChange,
readyLabel,
@@ -129,11 +143,24 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
const [runtime, setRuntime] = React.useState<BackendRuntimeInfo | null>(null);
const [runtimeLoading, setRuntimeLoading] = React.useState(false);
const [operation, setOperation] = React.useState<Operation>('idle');
+ // The last upgrade's failure stays in the popover until the next attempt, so
+ // the reason outlives the toast that announced it. It is tied to what it
+ // describes: the executable it ran against, and the host's refresh generation,
+ // so a different CLI or an upgrade the host applied itself supersedes it.
+ const [failure, setFailure] = React.useState<{
+ result: InstallOutcomeResult;
+ cliPath: string;
+ refreshKey?: number;
+ } | null>(null);
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);
+ // The host refresh generation the current ``runtime`` was probed under.
+ const refreshKeyRef = React.useRef(refreshKey);
+ refreshKeyRef.current = refreshKey;
+ const [probedKey, setProbedKey] = React.useState(refreshKey);
React.useEffect(() => {
isMountedRef.current = true;
@@ -156,6 +183,7 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
const loadRuntime = React.useCallback(async () => {
const myToken = ++loadTokenRef.current;
+ const key = refreshKeyRef.current;
setRuntimeLoading(true);
let info: BackendRuntimeInfo | null = null;
try {
@@ -167,6 +195,7 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
// unmounted while we were in flight.
if (isMountedRef.current && loadTokenRef.current === myToken) {
setRuntime(info);
+ setProbedKey(key);
setRuntimeLoading(false);
}
}
@@ -192,8 +221,14 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
if (enabled && isOpen) void loadRuntime();
}, [enabled, isOpen, loadRuntime]);
- const visual = deriveVisual(enabled, cliStatus, runtime, operation);
+ // The effect above probes whenever the host refreshes an enabled, detected CLI.
+ const confirming = enabled && cliStatus === 'ok' && probedKey !== refreshKey;
+ const visual = deriveVisual(enabled, cliStatus, runtime, operation, confirming);
const busy = runtimeLoading || operation !== 'idle' || externallyBusy;
+ const shownFailure =
+ failure && failure.cliPath === cliPath && failure.refreshKey === refreshKey && visual !== 'disabled'
+ ? failure.result
+ : null;
React.useEffect(() => {
onVisual?.(visual);
@@ -201,19 +236,31 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
const handleUpgrade = async () => {
setOperation('upgrading');
+ setFailure(null);
onOperationChange?.(true);
try {
- const result = await api.installAgent(name);
- if (result.ok) {
- showToast(t('backendLifecycle.upgradeSuccess'), 'success');
- await loadRuntime();
- const installedPath = typeof result.path === 'string' && result.path ? result.path : null;
- await onChanged?.({ installedPath });
- } else {
- showToast(result.message || t('backendLifecycle.upgradeFailed'), 'error');
+ let installedPath: string | null = null;
+ try {
+ const result = await api.installAgent(name);
+ if (result.ok) {
+ showToast(t('backendLifecycle.upgradeSuccess'), 'success');
+ installedPath = typeof result.path === 'string' && result.path ? result.path : null;
+ } else {
+ const message = result.message || t('backendLifecycle.upgradeFailed');
+ if (isMountedRef.current) setFailure({ result: { ...result, message }, cliPath, refreshKey });
+ showToast(message, 'error');
+ }
+ } catch (e) {
+ if (isMountedRef.current) {
+ setFailure({ result: { ok: false, message: String(e), output: null }, cliPath, refreshKey });
+ }
+ showToast(String(e), 'error');
}
- } catch (e) {
- showToast(String(e), 'error');
+ // Failed or not, the attempt may have replaced or removed the CLI.
+ // The probe reads what it left, and the host re-detects the file its
+ // status describes, or a CLI the attempt removed goes on reading as ready.
+ await loadRuntime();
+ await onChanged?.({ installedPath });
} finally {
onOperationChange?.(false);
if (isMountedRef.current) setOperation('idle');
@@ -312,7 +359,9 @@ export const BackendLifecycleChip: React.FC<BackendLifecycleChipProps> = ({
runtime={runtime}
operation={operation}
name={name}
+ failed={!!shownFailure}
/>
+ {shownFailure && <InstallOutcome result={shownFailure} className="text-xs" />}
</div>
{visual !== 'disabled' && visual !== 'updating' && (
@@ -353,7 +402,8 @@ const ChipPopoverBody: React.FC<{
runtime: BackendRuntimeInfo | null;
operation: Operation;
name: string;
-}> = ({ visual, runtime, operation, name }) => {
+ failed: boolean;
+}> = ({ visual, runtime, operation, name, failed }) => {
const { t } = useTranslation();
if (visual === 'disabled') {
@@ -376,18 +426,27 @@ const ChipPopoverBody: React.FC<{
<span className="font-mono font-medium text-foreground">{runtime.latest_version}</span>
</div>
)}
- <StateBlock visual={visual} operation={operation} runtime={runtime} name={name} />
+ <StateBlock visual={visual} operation={operation} runtime={runtime} name={name} failed={failed} />
</>
);
};
+/**
+ * The popover's one notice, chosen by urgency: an operation in flight, then what
+ * is wrong and how to fix it, then what can be done, and reassurance last. Who
+ * installed the CLI is reassurance, so it never stands in for a problem, and
+ * nothing reassuring sits beside the last attempt's failure, which the popover
+ * shows under this notice.
+ */
const StateBlock: React.FC<{
visual: Visual;
operation: Operation;
runtime: BackendRuntimeInfo | null;
name: string;
-}> = ({ visual, operation, runtime, name }) => {
+ failed: boolean;
+}> = ({ visual, operation, runtime, name, failed }) => {
const { t } = useTranslation();
+ const label = getBackendUiMeta(name).label;
if (operation === 'upgrading') {
return (
@@ -397,6 +456,14 @@ const StateBlock: React.FC<{
</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-ink">
+ <AlertCircle size={16} className="shrink-0" />
+ <span>{t('backendLifecycle.errorHint', { name: label })}</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-ink">
@@ -410,6 +477,7 @@ const StateBlock: React.FC<{
</div>
);
}
+ if (failed) return null;
if (runtime?.managed_by === 'desktop') {
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">
@@ -418,14 +486,6 @@ const StateBlock: React.FC<{
</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-ink">
- <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-ink">
diff --git a/ui/src/components/settings/SettingsBackendsPage.tsx b/ui/src/components/settings/SettingsBackendsPage.tsx
index 63a4a2ff4..65517de04 100644
--- a/ui/src/components/settings/SettingsBackendsPage.tsx
+++ b/ui/src/components/settings/SettingsBackendsPage.tsx
@@ -171,6 +171,7 @@ export const SettingsBackendsPage: React.FC = () => {
name={meta.id}
enabled={agent.enabled}
cliStatus={agent.status}
+ cliPath={agent.cli_path}
onChanged={async (info) => {
const installedPath = info?.installedPath || null;
if (installedPath) {
diff --git a/ui/src/components/settings/shared/BackendRuntimeCard.tsx b/ui/src/components/settings/shared/BackendRuntimeCard.tsx
index c0b2d7c15..c091ab933 100644
--- a/ui/src/components/settings/shared/BackendRuntimeCard.tsx
+++ b/ui/src/components/settings/shared/BackendRuntimeCard.tsx
@@ -1,8 +1,6 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
import {
- ChevronDown,
- ChevronUp,
Download,
RefreshCw,
Save,
@@ -15,6 +13,7 @@ import { Button } from '../../ui/button';
import { Card, CardContent } from '../../ui/card';
import { Input } from '../../ui/input';
import { Label } from '../../ui/label';
+import { InstallOutcome } from '../../shared/InstallOutcome';
import { BackendLifecycleChip } from '../BackendLifecycleChip';
import { ToggleSwitch } from '../SettingsPrimitives';
import type { BackendRuntimeState, BackendId } from './useBackendRuntime';
@@ -106,6 +105,7 @@ export const BackendRuntimeCard: React.FC<BackendRuntimeCardProps> = ({
name={backend}
enabled={runtime.enabled}
cliStatus={runtime.cliStatus}
+ cliPath={runtime.cliPath}
onChanged={runtime.handleLifecycleChanged}
onOperationChange={(busy) => { if (!busy) void runtime.handleLifecycleChanged(null); }}
/>
@@ -151,53 +151,23 @@ export const BackendRuntimeCard: React.FC<BackendRuntimeCardProps> = ({
{runtime.cliStatus === 'missing' && (
<div className="space-y-2 rounded-lg border border-cyan/30 bg-cyan/[0.06] px-3 py-2.5">
<p className="text-[12px] text-cyan-ink">{t('agentDetection.installHint')}</p>
- <div className="flex flex-wrap items-center gap-3">
- <Button
- variant="brand-cyan"
- size="xs"
- onClick={() => void runtime.install()}
- disabled={runtime.installing}
- >
- {runtime.installing ? (
- <RefreshCw className="size-3.5 animate-spin" />
- ) : (
- <Download className="size-3.5" />
- )}
- {runtime.installing
- ? t('agentDetection.installing')
- : t('agentDetection.installAgent')}
- </Button>
- {runtime.installResult?.message && (
- <span
- className={clsx(
- 'text-[12px]',
- runtime.installResult.ok ? 'text-mint-ink' : 'text-destructive-ink',
- )}
- >
- {runtime.installResult.message}
- </span>
+ <Button
+ variant="brand-cyan"
+ size="xs"
+ onClick={() => void runtime.install()}
+ disabled={runtime.installing}
+ >
+ {runtime.installing ? (
+ <RefreshCw className="size-3.5 animate-spin" />
+ ) : (
+ <Download className="size-3.5" />
)}
- </div>
- {runtime.installResult?.output && (
- <div>
- <button
- type="button"
- onClick={() => runtime.setInstallOutputOpen((v) => !v)}
- className="inline-flex items-center gap-1 text-[11px] text-cyan-ink transition hover:text-cyan-ink/80"
- >
- {runtime.installOutputOpen ? (
- <ChevronUp size={12} />
- ) : (
- <ChevronDown size={12} />
- )}
- {t('agentDetection.showOutput')}
- </button>
- {runtime.installOutputOpen && (
- <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap rounded border border-border bg-background px-3 py-2 font-mono text-[11px] text-muted">
- {runtime.installResult.output}
- </pre>
- )}
- </div>
+ {runtime.installing
+ ? t('agentDetection.installing')
+ : t('agentDetection.installAgent')}
+ </Button>
+ {runtime.installResult && (
+ <InstallOutcome result={runtime.installResult} className="text-[12px]" />
)}
</div>
)}
diff --git a/ui/src/components/settings/shared/useBackendRuntime.ts b/ui/src/components/settings/shared/useBackendRuntime.ts
index de61a5dd5..391c2c438 100644
--- a/ui/src/components/settings/shared/useBackendRuntime.ts
+++ b/ui/src/components/settings/shared/useBackendRuntime.ts
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useApi } from '@/context/ApiContext';
+import { useApi, type InstallResult } from '@/context/ApiContext';
import { useToast } from '@/context/ToastContext';
import { setConfigField } from '@/lib/configMutations';
import { errorMessage } from '@/lib/errorMessage';
@@ -10,12 +10,6 @@ export type CliStatus = 'unknown' | 'ok' | 'missing';
export type BackendId = 'claude' | 'codex' | 'opencode';
-export interface InstallResult {
- ok: boolean;
- message: string;
- output?: string | null;
-}
-
export interface UseBackendRuntimeOptions {
/** Backend identifier used in V2Config keys and install_agent dispatch. */
backend: BackendId;
@@ -41,7 +35,6 @@ export interface BackendRuntimeState {
detecting: boolean;
installing: boolean;
installResult: InstallResult | null;
- installOutputOpen: boolean;
savingRuntime: boolean;
/** True once the user has typed a path different from the saved one. */
runtimeDirty: boolean;
@@ -49,7 +42,6 @@ export interface BackendRuntimeState {
connectionRevision: number;
setCliPath: (next: string) => void;
- setInstallOutputOpen: (open: boolean | ((prev: boolean) => boolean)) => void;
/** Runs ``detectCli`` and updates ``cliPath`` + ``cliStatus``. */
detect: (binary?: string) => Promise<void>;
/** Calls ``installAgent`` then re-runs detect with the resolved path. */
@@ -116,7 +108,6 @@ export function useBackendRuntime({
const [detecting, setDetecting] = useState(false);
const [installing, setInstalling] = useState(false);
const [installResult, setInstallResult] = useState<InstallResult | null>(null);
- const [installOutputOpen, setInstallOutputOpen] = useState(false);
const [savingRuntime, setSavingRuntime] = useState(false);
const [connectionRevision, setConnectionRevision] = useState(0);
const mutationQueue = useRef(Promise.resolve());
@@ -194,13 +185,12 @@ export function useBackendRuntime({
const intent = pathIntent.current;
setInstalling(true);
setInstallResult(null);
- setInstallOutputOpen(false);
try {
const result = await api.installAgent(backend);
if (!mounted.current) return;
const installedPath =
typeof result.path === 'string' && result.path ? result.path : null;
- setInstallResult({ ok: result.ok, message: result.message, output: result.output });
+ setInstallResult(result);
if (result.ok) {
if (installedPath) setSavedCliPath(installedPath);
if (pathIntent.current === intent) {
@@ -311,12 +301,10 @@ export function useBackendRuntime({
detecting,
installing,
installResult,
- installOutputOpen,
savingRuntime,
runtimeDirty,
connectionRevision,
setCliPath: (next) => { pathIntent.current += 1; setCliPath(next); },
- setInstallOutputOpen,
detect,
install,
onSaveRuntime,
diff --git a/ui/src/components/shared/InstallOutcome.tsx b/ui/src/components/shared/InstallOutcome.tsx
new file mode 100644
index 000000000..37dc9b68c
--- /dev/null
+++ b/ui/src/components/shared/InstallOutcome.tsx
@@ -0,0 +1,45 @@
+import { ChevronDown } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import type { InstallResult } from '../../context/ApiContext';
+import { cn } from '@/lib/utils';
+
+export type InstallOutcomeResult = Pick<InstallResult, 'ok' | 'message' | 'output' | 'hint' | 'exit_code'>;
+
+/**
+ * How an agent CLI install or upgrade ended: the server's localized headline, its
+ * hint when it recognized the failure, and the installer's own output behind a
+ * disclosure. Every surface that runs one draws the result through here, so a
+ * failure reads the same in Settings, in setup and in the lifecycle popover, and
+ * stays on screen after the toast is gone.
+ *
+ * Text size and the surrounding tone belong to the host; the hint inherits it.
+ */
+export function InstallOutcome({ result, className }: { result: InstallOutcomeResult; className?: string }) {
+ const { t } = useTranslation();
+ const { ok, message, hint, output } = result;
+ const exitCode = typeof result.exit_code === 'number' ? result.exit_code : null;
+ if (!message && !output) return null;
+ return (
+ <div className={cn('min-w-0 space-y-1 break-words', className)} role={ok ? 'status' : 'alert'}>
+ {message && <p className={ok ? 'text-mint-ink' : 'text-destructive-ink'}>{message}</p>}
+ {hint && <p>{hint}</p>}
+ {(output || exitCode !== null) && (
+ <details className="group">
+ <summary className="flex w-fit cursor-pointer list-none items-center gap-1 text-cyan-ink hover:text-cyan-ink/80">
+ <ChevronDown size={12} className="transition-transform group-open:rotate-180" />
+ {t('agentDetection.showOutput')}
+ </summary>
+ {exitCode !== null && (
+ <p className="mt-2 font-mono text-muted">{t('agentDetection.exitCode', { code: exitCode })}</p>
+ )}
+ {output && (
+ <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-all rounded border border-border bg-background px-3 py-2 font-mono text-[11px] text-muted">
+ {output}
+ </pre>
+ )}
+ </details>
+ )}
+ </div>
+ );
+}
diff --git a/ui/src/components/steps/AgentDetection.tsx b/ui/src/components/steps/AgentDetection.tsx
index 8f1ca7707..8b8c246b5 100644
--- a/ui/src/components/steps/AgentDetection.tsx
+++ b/ui/src/components/steps/AgentDetection.tsx
@@ -4,8 +4,6 @@ import {
ArrowLeft,
ArrowRight,
ArrowUpToLine,
- ChevronDown,
- ChevronUp,
Download,
ExternalLink,
RefreshCw,
@@ -13,10 +11,10 @@ import {
} from 'lucide-react';
import { Link, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
-import clsx from 'clsx';
import { useApi } from '../../context/ApiContext';
import { useToast } from '../../context/ToastContext';
import { BackendIcon } from '../visual';
+import { InstallOutcome, type InstallOutcomeResult } from '../shared/InstallOutcome';
import { AssistantRow } from '../onboarding/AssistantRow';
import { ASSISTANT_ORDER } from '../onboarding/collaborationTimeline';
import '../onboarding/onboarding.css';
@@ -131,10 +129,11 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
const [agents, setAgents] = useState<Record<string, AgentState>>(normalizeAgents(data));
const permission = useOpencodePermission({ autoFetchStatus: active });
const [installingAgents, setInstallingAgents] = useState<Record<string, boolean>>({});
- const [installResults, setInstallResults] = useState<
- Record<string, { ok: boolean; message: string; output?: string | null }>
- >({});
- const [expandedOutputs, setExpandedOutputs] = useState<Record<string, boolean>>({});
+ // The last install or upgrade result per backend, failures included: it is
+ // what the card keeps on screen once the toast has gone.
+ const [installResults, setInstallResults] = useState<Record<string, InstallOutcomeResult | undefined>>({});
+ const clearInstallResult = (name: string) =>
+ setInstallResults((prev) => (prev[name] ? { ...prev, [name]: undefined } : prev));
// Which backend's "Configure provider" modal is open (wizard mode only).
const [providerModal, setProviderModal] = useState<{ backend: RuntimeBackendId; method: 'oauth' | 'api_key' } | null>(null);
const [routeSelection, setRouteSelection] = useState<RouteChainSelection | null>(null);
@@ -285,12 +284,6 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
const [visuals, setVisuals] = useState<Partial<Record<string, BackendLifecycleVisual>>>({});
const [refreshingAgents, setRefreshingAgents] = useState<Record<string, boolean>>({});
const [chipRefresh, setChipRefresh] = useState<Record<string, number>>({});
- // A successful upgrade leaves the chip's own runtime probe in flight while this
- // handler has already finished, so the pill still reads `update` for a moment and
- // would re-arm the card's upgrade button against a backend that was just upgraded.
- // The lock holds the button disabled until the chip's reported visual leaves
- // `update`, which is the probe confirming what the upgrade did.
- const [upgradeLocks, setUpgradeLocks] = useState<Record<string, boolean>>({});
const pendingInstalls = useRef(new Set<string>());
const detectionTokens = useRef<Record<string, number>>({});
const isMissing = (agent: AgentState) => agent.status === 'missing';
@@ -509,52 +502,42 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
// The setup card draws the update action on the state row, beside the pill the
// chip renders, while the chip still owns the probe and the write. Bumping
// `chipRefresh` is what lets the chip re-probe a runtime the card's own button
- // changed, without the card duplicating the chip's lifecycle knowledge.
- useEffect(() => {
- setUpgradeLocks((current) => {
- let changed = false;
- const next = { ...current };
- for (const [name, locked] of Object.entries(current)) {
- if (locked && visuals[name] !== 'update' && visuals[name] !== 'updating') {
- next[name] = false;
- changed = true;
- }
- }
- return changed ? next : current;
- });
- }, [visuals]);
-
- const releaseUpgradeLock = (name: string) =>
- setUpgradeLocks((current) => (current[name] ? { ...current, [name]: false } : current));
-
+ // changed, without the card duplicating the chip's lifecycle knowledge. The chip
+ // reads as updating until that probe settles, so the button cannot re-arm on the
+ // verdict from before the attempt, whatever the probe then finds.
const upgradeAgent = async (name: string) => {
setRefreshingAgents((current) => ({ ...current, [name]: true }));
- setUpgradeLocks((current) => ({ ...current, [name]: true }));
+ clearInstallResult(name);
// The chip's own upgrade handler owns the toast contract for lifecycle
// operations; the card's affordance is the same operation drawn on the state
// row, so it settles failures the same way rather than swallowing them, and
// `refreshingAgents` is handed to the chip as externally busy so its popover
// cannot launch a second install against the same backend.
+ let installedPath: string | null = null;
+ let failure: InstallOutcomeResult | null = null;
try {
const result = await api.installAgent(name);
if (result.ok) {
showToast(t('backendLifecycle.upgradeSuccess'), 'success');
- const installedPath = typeof result.path === 'string' && result.path ? result.path : null;
- if (installedPath) {
- setAgents((prev) => ({ ...prev, [name]: { ...prev[name], cli_path: installedPath } }));
- }
- setChipRefresh((current) => ({ ...current, [name]: (current[name] || 0) + 1 }));
- await detect(name, installedPath || agents[name]?.cli_path || name);
+ const path = typeof result.path === 'string' && result.path ? result.path : null;
+ if (path) setAgents((prev) => ({ ...prev, [name]: { ...prev[name], cli_path: path } }));
+ installedPath = path;
} else {
- // A failed upgrade leaves the pill on `update` with no probe in flight, so
- // the visuals-driven release never fires; settle the lock here instead of
- // stranding the button disabled until a remount.
- releaseUpgradeLock(name);
- showToast(result.message || t('backendLifecycle.upgradeFailed'), 'error');
+ failure = { ...result, message: result.message || t('backendLifecycle.upgradeFailed') };
+ showToast(failure.message, 'error');
}
} catch (cause) {
- releaseUpgradeLock(name);
- showToast(String(cause), 'error');
+ failure = { ok: false, message: String(cause), output: null };
+ showToast(failure.message, 'error');
+ }
+ try {
+ // Failed or not, the attempt may have replaced or removed the CLI:
+ // the chip re-probes it and the card re-detects the file.
+ setChipRefresh((current) => ({ ...current, [name]: (current[name] || 0) + 1 }));
+ await detect(name, installedPath || agents[name]?.cli_path || name);
+ // Detection retires a failed install once it finds the CLI; a failed upgrade
+ // of a CLI that is still there stays on the card.
+ if (failure) setInstallResults((prev) => ({ ...prev, [name]: failure }));
} finally {
setRefreshingAgents((current) => ({ ...current, [name]: false }));
}
@@ -568,18 +551,14 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
pendingInstalls.current.add(name);
setInstallingAgents((prev) => ({ ...prev, [name]: true }));
- setInstallResults((prev) => ({ ...prev, [name]: { ok: false, message: '', output: null } }));
- setExpandedOutputs((prev) => ({ ...prev, [name]: false }));
+ clearInstallResult(name);
let installed = false;
try {
const result = await api.installAgent(name);
installed = result.ok;
const installedPath = typeof result.path === 'string' && result.path ? result.path : null;
- setInstallResults((prev) => ({
- ...prev,
- [name]: { ok: result.ok, message: result.message, output: result.output },
- }));
+ setInstallResults((prev) => ({ ...prev, [name]: result }));
if (result.ok) {
if (installedPath) {
setAgents((prev) => ({
@@ -614,10 +593,6 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
}
};
- const toggleOutput = (name: string) => {
- setExpandedOutputs((prev) => ({ ...prev, [name]: !prev[name] }));
- };
-
const opencodeAgent = agents['opencode'];
const readyBackends = ASSISTANT_ORDER.filter((name) => agents[name].enabled && agents[name].status === 'ok'
&& !installingAgents[name] && !detectingAgents[name] && !connectionPending[name]
@@ -763,6 +738,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
name={name}
enabled={agent.enabled}
cliStatus={active ? agent.status || 'unknown' : 'unknown'}
+ cliPath={agent.cli_path}
onChanged={async (info) => {
// After a successful (re)install the chip hands back the
// path the installer landed at — adopt it before
@@ -838,32 +814,12 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
? t('agentDetection.installing')
: t('agentDetection.installAgentNamed', { name: meta.label })}
</Button>
- {installResults[name]?.message && (
- <span
- className={clsx('text-[11px]', installResults[name].ok ? 'text-mint-ink' : 'text-destructive-ink')}
- >
- {installResults[name].message}
- </span>
- )}
</>
)}
</div>
- {isMissing(agent) && installResults[name]?.output && (
- <div>
- <button
- onClick={() => toggleOutput(name)}
- className="inline-flex items-center gap-1 text-[11px] text-cyan-ink transition hover:text-cyan-ink/80"
- >
- {expandedOutputs[name] ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
- {t('agentDetection.showOutput')}
- </button>
- {expandedOutputs[name] && (
- <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap rounded border border-border bg-background px-3 py-2 font-mono text-[11px] text-muted">
- {installResults[name].output}
- </pre>
- )}
- </div>
+ {isMissing(agent) && installResults[name] && (
+ <InstallOutcome result={installResults[name]} className="text-[11px]" />
)}
</div>
</div>
@@ -988,6 +944,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
label={t('onboarding.setup.enableNamed', { name: getBackendUiMeta(name).label })}
onClick={() => toggle(name, !agent.enabled)} />}
lifecycle={<BackendLifecycleChip name={name} enabled={agent.enabled} cliStatus={active ? agent.status || 'unknown' : 'unknown'}
+ cliPath={agent.cli_path}
readyLabel={t('onboarding.setup.enabled')}
disabledLabel={t('onboarding.setup.notEnabled')}
refreshKey={chipRefresh[name]}
@@ -998,6 +955,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
if (!pending) void refreshConnection(name);
}}
onChanged={async (info) => {
+ clearInstallResult(name);
const installedPath = info?.installedPath || agent.cli_path;
setAgents((previous) => ({ ...previous, [name]: { ...previous[name], cli_path: installedPath } }));
await detect(name, installedPath);
@@ -1005,7 +963,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
upgrade={agent.status === 'ok' && (visuals[name] === 'update' || visuals[name] === 'updating' || refreshingAgents[name]) ? (
<Button type="button" variant="secondary" className="onboarding-life-action"
onClick={() => void upgradeAgent(name)}
- disabled={refreshingAgents[name] || !!upgradeLocks[name] || visuals[name] === 'updating' || !!installingAgents[name]}>
+ disabled={refreshingAgents[name] || visuals[name] === 'updating' || !!installingAgents[name]}>
{refreshingAgents[name] || visuals[name] === 'updating'
? <RefreshCw size={14} className="motion-safe:animate-spin" />
: <ArrowUpToLine size={14} />}
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index a97f77080..16a021bc3 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -1885,6 +1885,12 @@ export type InstallResult = {
reason?: string | null;
action_class?: 'operator_only';
download_error?: DependencyDownloadError | null;
+ /** Agent CLI failures: a stable recognition code (``install_failed`` when
+ * nothing matched), its localized hint, and the installer's exit status. */
+ code?: string;
+ hint?: string | null;
+ hint_params?: Record<string, unknown>;
+ exit_code?: number;
};
export type DependencyDownloadError = {
@@ -3318,11 +3324,12 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
return last;
}
}
+ // ``last`` is still the running job, whose message announces the start.
return {
...last,
ok: false,
status: 'failed',
- message: last?.message || t('backendLifecycle.upgradeFailed'),
+ message: t('backendLifecycle.upgradeFailed'),
};
};
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index cb8a519f7..cfe709ffc 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -3401,7 +3401,8 @@
"installHint": "Agent not found. Click to install automatically.",
"installAgent": "Install",
"installing": "Installing...",
- "showOutput": "Show details"
+ "showOutput": "Show details",
+ "exitCode": "Exit code: {{code}}"
},
"backendLifecycle": {
"title": "Backend status",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index ad4a7901c..a000e2e1c 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -3401,7 +3401,8 @@
"installHint": "未找到 Agent,点击自动安装。",
"installAgent": "一键安装",
"installing": "安装中...",
- "showOutput": "显示详情"
+ "showOutput": "显示详情",
+ "exitCode": "退出码:{{code}}"
},
"backendLifecycle": {
"title": "后端状态",
diff --git a/vibe/api.py b/vibe/api.py
index 9dffbf319..63eb62aa7 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -105,6 +105,7 @@ from vibe.i18n import t as backend_t
from modules.agents.catalog import (
agent_backend_catalog_payload,
agent_backend_descriptors,
+ display_name_for_backend,
is_agent_backend,
latest_probe_for_backend,
runtime_refresh_success_message,
@@ -7363,6 +7364,144 @@ def _curl_installer_command(url: str, consumer: str) -> list[str]:
]
+_AGENT_INSTALL_TIMEOUT_SECONDS = 300
+
+# Installer failures we can explain, recognized from what the installer printed.
+# Each shape comes from real npm 9/11, curl, and ``opencode upgrade`` output;
+# the fixtures in tests/test_agent_install_failures.py are those captures.
+_NPM_ERROR_PREFIX = r"npm (?:error|ERR!)"
+_NPM_ERROR_CODE_RE = re.compile(rf"^{_NPM_ERROR_PREFIX} code (?P<code>\S+)\s*$", re.MULTILINE)
+_NPM_ERROR_PATH_RE = re.compile(rf"^{_NPM_ERROR_PREFIX} path (?P<path>.+?)\s*$", re.MULTILINE)
+_NPM_ENOTEMPTY_RENAME_RE = re.compile(
+ r"ENOTEMPTY: directory not empty, rename '(?P<source>[^']+)' -> '(?P<dest>[^']+)'"
+)
+# Before moving a new version in, npm renames the installed package to
+# ``.<name>-<8 chars>`` beside it. The suffix is derived from the package path,
+# so a folder left there by an interrupted update fails every retry the same way.
+_NPM_RETIRED_PACKAGE_RE = re.compile(r"^\.(?P<package>.+)-[A-Za-z0-9_-]{8}$")
+_NPM_PERMISSION_CODES = frozenset({"EACCES", "EPERM"})
+_NPM_NETWORK_CODES = frozenset({"ENOTFOUND", "ECONNREFUSED", "ETIMEDOUT"})
+_NPM_REQUEST_URL_RE = re.compile(r"request to (?P<url>\S+) failed")
+_CURL_UNREACHABLE_RE = re.compile(
+ r"^curl: \((?:6\) Could not resolve host: (?P<dns_host>\S+)|(?:7|28)\) Failed to connect to (?P<connect_host>\S+) port)",
+ re.MULTILINE,
+)
+_GITHUB_API_FORBIDDEN_RE = re.compile(r"\b403\b.*\bapi\.github\.com\b|\bapi\.github\.com\b.*\b403\b")
+_GITHUB_RATE_LIMIT_URL = "https://api.github.com/rate_limit"
+_GITHUB_RATE_LIMIT_TIMEOUT_SECONDS = 3
+_INSTALL_FAILURE_HINT_KEYS = {
+ "npm_leftover_directory": "agentInstall.hint.npmLeftoverDirectory",
+ "permission_denied": "agentInstall.hint.permissionDenied",
+ "network_unreachable": "agentInstall.hint.networkUnreachable",
+ "install_timeout": "agentInstall.hint.timedOut",
+}
+
+
+def _github_rate_limit_reset() -> int | None:
+ """When this network's exhausted GitHub API quota resets, as epoch seconds.
+
+ ``GET /rate_limit`` does not spend the quota it reports, so it still answers
+ after the call that failed. Best effort: the hint is still useful without a
+ time, so any failure here only drops the time.
+ """
+ req = urllib.request.Request(
+ _GITHUB_RATE_LIMIT_URL,
+ headers={"Accept": "application/vnd.github+json", "User-Agent": _BACKEND_RUNTIME_USER_AGENT},
+ )
+ try:
+ with _http_opener_for_best_effort_probe().open( # noqa: S310 - fixed GitHub API URL
+ req, timeout=_GITHUB_RATE_LIMIT_TIMEOUT_SECONDS
+ ) as resp:
+ core = json.loads(resp.read().decode("utf-8"))["resources"]["core"]
+ remaining, reset_at = int(core["remaining"]), int(core["reset"])
+ except Exception as exc:
+ logger.debug("GitHub rate limit lookup failed: %s", exc)
+ return None
+ if remaining > 0 or reset_at <= time.time():
+ return None
+ return reset_at
+
+
+def _recognize_install_failure(output: str | None, *, timed_out: bool = False) -> tuple[str, dict[str, Any]]:
+ """Map a failed agent CLI install/upgrade to a stable hint code and params.
+
+ The code is always one of ``install_timeout``, ``npm_leftover_directory``,
+ ``permission_denied``, ``github_rate_limited``, ``network_unreachable`` or
+ ``install_failed`` (nothing recognized); the params are what its hint names.
+ """
+ if timed_out:
+ return "install_timeout", {"minutes": _AGENT_INSTALL_TIMEOUT_SECONDS // 60}
+ text = output or ""
+ rename = _NPM_ENOTEMPTY_RENAME_RE.search(text)
+ if rename and _NPM_RETIRED_PACKAGE_RE.match(re.split(r"[\\/]", rename.group("dest"))[-1]):
+ return "npm_leftover_directory", {"path": rename.group("dest")}
+ npm_code = _NPM_ERROR_CODE_RE.search(text)
+ npm_code = npm_code.group("code") if npm_code else None
+ if npm_code in _NPM_PERMISSION_CODES:
+ path = _NPM_ERROR_PATH_RE.search(text)
+ if path:
+ return "permission_denied", {"path": path.group("path")}
+ if _GITHUB_API_FORBIDDEN_RE.search(text):
+ return "github_rate_limited", {"reset_at": _github_rate_limit_reset()}
+ if npm_code in _NPM_NETWORK_CODES:
+ request = _NPM_REQUEST_URL_RE.search(text)
+ host = urllib.parse.urlsplit(request.group("url")).hostname if request else None
+ if host:
+ return "network_unreachable", {"host": host}
+ curl = _CURL_UNREACHABLE_RE.search(text)
+ if curl:
+ return "network_unreachable", {"host": curl.group("dns_host") or curl.group("connect_host")}
+ return "install_failed", {}
+
+
+def _install_failure_hint(code: str, params: dict[str, Any], language: str) -> str | None:
+ if code == "github_rate_limited":
+ reset_at = params.get("reset_at")
+ if reset_at is None:
+ return backend_t("agentInstall.hint.githubRateLimitedNoReset", language)
+ return backend_t(
+ "agentInstall.hint.githubRateLimited",
+ language,
+ # The runtime's local time; the minutes keep it usable from a browser
+ # in another time zone.
+ time=datetime.fromtimestamp(reset_at).strftime("%H:%M"),
+ minutes=max(1, (int(reset_at - time.time()) + 59) // 60),
+ )
+ key = _INSTALL_FAILURE_HINT_KEYS.get(code)
+ return backend_t(key, language, **params) if key else None
+
+
+def _install_failure_result(
+ name: str,
+ mode: str,
+ output: str,
+ truncate_output,
+ *,
+ timed_out: bool = False,
+ **details: Any,
+) -> dict:
+ """The one shape every failed ``_run_install_command`` returns.
+
+ The headline names what failed in the instance language; ``code``/``hint``
+ say why when the output is recognized; ``output`` keeps the installer's own
+ words for the details. Recognition reads the whole output rather than the
+ truncated tail, so an explanation printed before a long tail still counts.
+ """
+ code, params = _recognize_install_failure(output, timed_out=timed_out)
+ language = _configured_backend_language()
+ backend = display_name_for_backend(name) if is_agent_backend(name) else name
+ headline = "agentInstall.upgradeFailed" if mode == "upgrade" else "agentInstall.installFailed"
+ return {
+ "ok": False,
+ "message": backend_t(headline, language, backend=backend),
+ "code": code,
+ "hint": _install_failure_hint(code, params, language),
+ "hint_params": params,
+ **details,
+ "output": truncate_output(output) or None,
+ }
+
+
def _run_install_command(
name: str,
cmd: list[str],
@@ -7392,23 +7531,30 @@ def _run_install_command(
**isolated_subprocess_kwargs(),
)
try:
- stdout, stderr = process.communicate(timeout=300) # 5 minute timeout
+ stdout, stderr = process.communicate(timeout=_AGENT_INSTALL_TIMEOUT_SECONDS)
except subprocess.TimeoutExpired:
logger.error("Agent %s %s timed out", name, mode)
signal_process_tree(process, KILL_SIGNAL, logger, f"{name} {mode}")
stdout, stderr = process.communicate(timeout=10)
output = (stdout or "") + ("\n" + stderr if stderr else "")
- output = truncate_output(output.strip())
- return {
- "ok": False,
- "message": f"{mode.capitalize()} timed out",
- "reason": f"{name}_{mode}_timeout",
- "timeout_seconds": 300,
- "output": output or None,
- }
+ # A killed installer can leave the CLI half-replaced; re-probe it.
+ _invalidate_version_cache(name)
+ return _install_failure_result(
+ name,
+ mode,
+ output.strip(),
+ truncate_output,
+ timed_out=True,
+ reason=f"{name}_{mode}_timeout",
+ timeout_seconds=_AGENT_INSTALL_TIMEOUT_SECONDS,
+ )
result = subprocess.CompletedProcess(cmd, process.returncode, stdout, stderr)
- output = result.stdout + ("\n" + result.stderr if result.stderr else "")
- output = truncate_output(output.strip())
+ raw_output = (result.stdout + ("\n" + result.stderr if result.stderr else "")).strip()
+ output = truncate_output(raw_output)
+ # Success or failure, the command may have replaced the CLI: the chip
+ # refreshes runtime right after this, and must read the new
+ # ``--version``, not the 30s-cached value.
+ _invalidate_version_cache(name)
if result.returncode == 0:
installed_path = resolve_cli_path(resolve_from or name)
if installed_path:
@@ -7419,10 +7565,6 @@ def _run_install_command(
name,
mode,
)
- # The chip refreshes runtime immediately after upgrade; drop the
- # 30s version cache so it reads the new `--version` instead of the
- # pre-upgrade value.
- _invalidate_version_cache(name)
# Persist real Agent backend CLI paths to V2Config so the next
# ``get_backend_runtime`` reads them directly instead of relying
@@ -7439,22 +7581,25 @@ def _run_install_command(
"output": output,
}
logger.warning("Agent %s %s failed: %s", name, mode, output)
- return {
- "ok": False,
- "message": f"{mode.capitalize()} failed (exit code {result.returncode})",
- "reason": f"{name}_{mode}_failed",
- "exit_code": result.returncode,
- "output": output,
- }
+ return _install_failure_result(
+ name,
+ mode,
+ raw_output,
+ truncate_output,
+ reason=f"{name}_{mode}_failed",
+ exit_code=result.returncode,
+ )
except Exception as e:
logger.error("Agent %s %s error: %s", name, mode, e)
- return {
- "ok": False,
- "message": str(e),
- "reason": f"{name}_{mode}_error",
- "error": str(e),
- "output": None,
- }
+ # No installer output reached us; the error is the detail.
+ return _install_failure_result(
+ name,
+ mode,
+ str(e),
+ truncate_output,
+ reason=f"{name}_{mode}_error",
+ error=str(e),
+ )
# =============================================================================
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 792efce1c..953772d11 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -844,6 +844,18 @@
"apiUpgrade": "This Runtime is managed by the Avibe desktop app.",
"backendUpgrade": "This Codex backend belongs to an older Avibe desktop Runtime and cannot be updated in place. Reopen the current desktop app to install it privately."
},
+ "agentInstall": {
+ "installFailed": "Could not install {backend}.",
+ "upgradeFailed": "Could not upgrade {backend}.",
+ "hint": {
+ "npmLeftoverDirectory": "npm left a temporary folder behind from an earlier interrupted update: {path}. Delete that folder, then try again.",
+ "permissionDenied": "The installer is not allowed to write to {path}. Make sure your user account can write to that folder, then try again.",
+ "githubRateLimited": "GitHub's API limit for this network is used up. It resets at {time} (in about {minutes} min); try again after that.",
+ "githubRateLimitedNoReset": "GitHub's API limit for this network is used up. It resets within an hour; try again later.",
+ "networkUnreachable": "Could not reach {host}. Check your network connection or proxy settings, then try again.",
+ "timedOut": "The installer did not finish within {minutes} minutes. Check your network connection, then try again."
+ }
+ },
"desktopBackendInstall": {
"success": "{backend} installed successfully.",
"unknownBackend": "Unknown desktop backend: {backend}.",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index b75ce6648..a315a3fd4 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -844,6 +844,18 @@
"apiUpgrade": "此 Runtime 由 Avibe 桌面应用管理。",
"backendUpgrade": "此 Codex 后端属于旧版 Avibe 桌面 Runtime,无法原地更新。请重新打开当前桌面应用,将其安装为私有后端。"
},
+ "agentInstall": {
+ "installFailed": "无法安装 {backend}。",
+ "upgradeFailed": "无法升级 {backend}。",
+ "hint": {
+ "npmLeftoverDirectory": "npm 在之前一次中断的更新中留下了临时目录:{path}。删除该目录后重试。",
+ "permissionDenied": "安装程序没有 {path} 的写入权限。请确认当前用户可以写入该目录,然后重试。",
+ "githubRateLimited": "当前网络的 GitHub API 调用额度已用完,将在 {time}(约 {minutes} 分钟后)重置,届时再试。",
+ "githubRateLimitedNoReset": "当前网络的 GitHub API 调用额度已用完,一小时内会重置,请稍后再试。",
+ "networkUnreachable": "无法连接 {host}。请检查网络连接或代理设置,然后重试。",
+ "timedOut": "安装程序在 {minutes} 分钟内未完成。请检查网络连接,然后重试。"
+ }
+ },
"desktopBackendInstall": {
"success": "{backend} 安装成功。",
"unknownBackend": "未知的桌面后端:{backend}。",