Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

fix(console): validate uninstall target before running the command (CHOO-3755) (#1011)

Abel Dantas6c37e3bc8686
diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/DependencyInstallationStatusCard.tsx b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/DependencyInstallationStatusCard.tsx
index 0a3c8ec05..576eb935b 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/DependencyInstallationStatusCard.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/agents-page/DependencyInstallationStatusCard.tsx
@@ -195,12 +195,7 @@ export const DependencyInstallationStatusCard = observer(function DependencyInst
variant="destructive"
disabled={isUninstalling}
onClick={() => {
- const name = agentPayload?.name ?? 'Agent';
- void toast.promise(uninstall(), {
- loading: `Uninstalling ${name}...`,
- success: `${name} successfully uninstalled`,
- error: `Failed to uninstall ${name}`,
- });
+ void uninstall();
}}
>
Uninstall
diff --git a/console/apps/switch-console-desktop/src/renderer/lib/stores/use-agent-installation-statuses.ts b/console/apps/switch-console-desktop/src/renderer/lib/stores/use-agent-installation-statuses.ts
index 8fb89bd9d..721a1cb61 100644
--- a/console/apps/switch-console-desktop/src/renderer/lib/stores/use-agent-installation-statuses.ts
+++ b/console/apps/switch-console-desktop/src/renderer/lib/stores/use-agent-installation-statuses.ts
@@ -134,7 +134,18 @@ export function useAgentInstallationStatuses(connectionId?: string) {
mutationKey: opKey('uninstall', connectionId),
mutationFn: ({ id, method }) =>
rpc.providers.uninstall(id, connectionId, method) as Promise<unknown>,
- onSuccess: invalidate,
+ onSuccess: (result, vars) => {
+ invalidate();
+ const name = nameOf(vars.id);
+ if ((result as { success: boolean }).success) {
+ toast({ title: `${name} successfully uninstalled` });
+ } else {
+ toast({ title: `Failed to uninstall ${name}`, variant: 'destructive' });
+ }
+ },
+ onError: (_, vars) => {
+ toast({ title: `Failed to uninstall ${nameOf(vars.id)}`, variant: 'destructive' });
+ },
});
const setUsedMutation = useMutation<
diff --git a/console/apps/switch-console-desktop/src/shared/core/providers/agent-payload.ts b/console/apps/switch-console-desktop/src/shared/core/providers/agent-payload.ts
index f81562f55..02e2fe64c 100644
--- a/console/apps/switch-console-desktop/src/shared/core/providers/agent-payload.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/providers/agent-payload.ts
@@ -136,6 +136,7 @@ export type AgentUninstallError =
| { type: 'unknown-dependency'; id: string }
| { type: 'no-uninstall-strategy'; id: string }
| { type: 'no-uninstall-command'; id: string }
+ | { type: 'uninstall-target-not-found'; id: string; package: string; method: string }
| InstallCommandError;
// ---------------------------------------------------------------------------
diff --git a/console/packages/core/src/host-dependencies/runtime/host-dependency-manager.test.ts b/console/packages/core/src/host-dependencies/runtime/host-dependency-manager.test.ts
index 1434d4a7f..feb5c1525 100644
--- a/console/packages/core/src/host-dependencies/runtime/host-dependency-manager.test.ts
+++ b/console/packages/core/src/host-dependencies/runtime/host-dependency-manager.test.ts
@@ -615,6 +615,64 @@ describe('HostDependencyManager uninstall', () => {
}),
},
},
+ {
+ id: 'opencode-pm-prefix',
+ name: 'OpenCode (npm with prefix, migration)',
+ category: 'agent',
+ commands: ['opencode'],
+ versionArgs: ['--version'],
+ installCommands: {
+ linux: [
+ {
+ method: 'npm',
+ command: 'npm install -g --prefix "$HOME/.local" @opencode/cli',
+ uninstallCommand: 'npm uninstall -g --prefix "$HOME/.local" @opencode/cli opencode-ai',
+ recommended: true,
+ },
+ ],
+ },
+ updates: { kind: 'none' },
+ uninstall: { kind: 'package-manager' },
+ },
+ {
+ id: 'codex-pm-migration',
+ name: 'Codex (dual-package uninstall)',
+ category: 'agent',
+ commands: ['codex'],
+ versionArgs: ['--version'],
+ installCommands: {
+ macos: [
+ {
+ method: 'npm',
+ command: 'npm install -g @openai/codex',
+ recommended: true,
+ uninstallCommand: 'npm uninstall -g @openai/codex old-codex-name',
+ },
+ ],
+ linux: [
+ {
+ method: 'npm',
+ command: 'npm install -g @openai/codex',
+ recommended: true,
+ uninstallCommand: 'npm uninstall -g @openai/codex old-codex-name',
+ },
+ ],
+ windows: [
+ {
+ method: 'npm',
+ command: 'npm install -g @openai/codex',
+ recommended: true,
+ uninstallCommand: 'npm uninstall -g @openai/codex old-codex-name',
+ },
+ ],
+ },
+ updates: {
+ kind: 'supported',
+ releaseSource: { kind: 'npm', package: '@openai/codex' },
+ update: { kind: 'package-manager' },
+ },
+ uninstall: { kind: 'package-manager' },
+ },
];
it('returns unknown-dependency error for an unrecognised id', async () => {
@@ -653,7 +711,19 @@ describe('HostDependencyManager uninstall', () => {
it('runs the uninstallCommand for package-manager strategy and re-probes', async () => {
const runInstallCommand = vi.fn(async () => ok<void>());
- const manager = new HostDependencyManager(missingCtx, {
+ // Verification passes: npm list confirms the package is installed
+ const verifiedCtx = makeCtx(async (command, args = []) => {
+ if (
+ command === 'npm' &&
+ args[0] === 'list' &&
+ args[1] === '-g' &&
+ args[2] === '@openai/codex'
+ ) {
+ return { stdout: '/usr/lib\n└── @openai/[email protected]\n', stderr: '' };
+ }
+ throw new Error('missing');
+ });
+ const manager = new HostDependencyManager(verifiedCtx, {
dependencies: UNINSTALL_DEPENDENCIES,
runInstallCommand,
installMethodDetector: npmDetector,
@@ -676,7 +746,14 @@ describe('HostDependencyManager uninstall', () => {
exitCode: 243,
})
);
- const manager = new HostDependencyManager(missingCtx, {
+ // Verification passes so we reach the runner
+ const verifiedCtx = makeCtx(async (command, args = []) => {
+ if (command === 'npm' && args[0] === 'list') {
+ return { stdout: '/usr/lib\n└── @openai/[email protected]\n', stderr: '' };
+ }
+ throw new Error('missing');
+ });
+ const manager = new HostDependencyManager(verifiedCtx, {
dependencies: UNINSTALL_DEPENDENCIES,
runInstallCommand,
});
@@ -742,6 +819,146 @@ describe('HostDependencyManager uninstall', () => {
args: ['custom-remove', '--force'],
});
});
+
+ it('returns uninstall-target-not-found when npm package is not installed globally', async () => {
+ const runInstallCommand = vi.fn(async () => ok<void>());
+ // npm list exits non-zero when the package isn't installed
+ const notInstalledCtx = makeCtx(async (command, args = []) => {
+ if (command === 'npm' && args[0] === 'list') {
+ throw new Error('npm ERR! code ELSPROBLEMS');
+ }
+ throw new Error('missing');
+ });
+ const manager = new HostDependencyManager(notInstalledCtx, {
+ dependencies: UNINSTALL_DEPENDENCIES,
+ runInstallCommand,
+ installMethodDetector: npmDetector,
+ });
+
+ const result = await manager.uninstall('codex-pm');
+
+ expect(result).toEqual({
+ success: false,
+ error: {
+ type: 'uninstall-target-not-found',
+ id: 'codex-pm',
+ package: '@openai/codex',
+ method: 'npm',
+ },
+ });
+ // Must not attempt the uninstall command
+ expect(runInstallCommand).not.toHaveBeenCalled();
+ });
+
+ it('verifies npm package before running uninstall command', async () => {
+ const callOrder: string[] = [];
+ const verifyAndUninstallCtx = makeCtx(async (command, args = []) => {
+ if (command === 'npm' && args[0] === 'list') {
+ callOrder.push('npm-list');
+ return { stdout: '/usr/lib\n└── @openai/[email protected]\n', stderr: '' };
+ }
+ throw new Error('missing');
+ });
+ const runInstallCommand = vi.fn(async () => {
+ callOrder.push('uninstall');
+ return ok<void>();
+ });
+ const manager = new HostDependencyManager(verifyAndUninstallCtx, {
+ dependencies: UNINSTALL_DEPENDENCIES,
+ runInstallCommand,
+ installMethodDetector: npmDetector,
+ });
+
+ await manager.uninstall('codex-pm');
+
+ // Verification must run before the uninstall command
+ expect(callOrder).toEqual(['npm-list', 'uninstall']);
+ });
+
+ it('forwards --prefix to npm list when the uninstall command uses a custom prefix', async () => {
+ const runInstallCommand = vi.fn(async () => ok<void>());
+ let listArgs: string[] = [];
+ const prefixCtx = makeCtx(async (command, args = []) => {
+ if (command === 'npm' && args[0] === 'list') {
+ listArgs = [...args];
+ return { stdout: '/home/user/.local/lib\n└── @opencode/[email protected]\n', stderr: '' };
+ }
+ throw new Error('missing');
+ });
+ const manager = new HostDependencyManager(prefixCtx, {
+ dependencies: UNINSTALL_DEPENDENCIES,
+ runInstallCommand,
+ installMethodDetector: npmDetector,
+ platform: 'linux',
+ });
+
+ await manager.uninstall('opencode-pm-prefix');
+
+ // npm list must include --prefix matching the uninstall command
+ expect(listArgs).toEqual([
+ 'list',
+ '-g',
+ '@opencode/cli',
+ '--depth=0',
+ '--prefix',
+ '$HOME/.local',
+ ]);
+ expect(runInstallCommand).toHaveBeenCalled();
+ });
+
+ it('passes pre-flight when any of multiple uninstall targets is installed (migration)', async () => {
+ const runInstallCommand = vi.fn(async () => ok<void>());
+ // Only the legacy name is installed — the new name is not
+ const migrationCtx = makeCtx(async (command, args = []) => {
+ if (command === 'npm' && args[0] === 'list' && args[2] === '@openai/codex') {
+ throw new Error('npm ERR! code ELSPROBLEMS');
+ }
+ if (command === 'npm' && args[0] === 'list' && args[2] === 'old-codex-name') {
+ return { stdout: '/usr/lib\n└── [email protected]\n', stderr: '' };
+ }
+ throw new Error('missing');
+ });
+ const manager = new HostDependencyManager(migrationCtx, {
+ dependencies: UNINSTALL_DEPENDENCIES,
+ runInstallCommand,
+ installMethodDetector: npmDetector,
+ });
+
+ const result = await manager.uninstall('codex-pm-migration');
+
+ // Pre-flight passes because the second target is found
+ expect(runInstallCommand).toHaveBeenCalled();
+ expect(result.success).toBe(true);
+ });
+
+ it('skips pre-flight verification for cli uninstall strategy', async () => {
+ const runInstallCommand = vi.fn(async () => ok<void>());
+ const claudeCtx = makeCtx(async (command, args = []) => {
+ if (command === 'npm' && args[0] === 'list') {
+ throw new Error('npm list should not be called for cli uninstall');
+ }
+ if (command === 'which' && args[0] === 'claude') {
+ return { stdout: '/usr/local/bin/claude\n', stderr: '' };
+ }
+ if (command === 'which' && args[0] === '-a' && args[1] === 'claude') {
+ return { stdout: '/usr/local/bin/claude\n', stderr: '' };
+ }
+ if (command === 'realpath') {
+ return { stdout: `${args[0]}\n`, stderr: '' };
+ }
+ throw new Error('missing');
+ });
+ const manager = new HostDependencyManager(claudeCtx, {
+ dependencies: UNINSTALL_DEPENDENCIES,
+ runInstallCommand,
+ installMethodDetector: unknownDetector,
+ });
+
+ await manager.uninstall('claude-cli-uninstall');
+
+ // cli strategy should not trigger npm list verification
+ expect(runInstallCommand).toHaveBeenCalled();
+ });
});
describe('HostDependencyManager unknown install source', () => {
diff --git a/console/packages/core/src/host-dependencies/runtime/host-dependency-manager.ts b/console/packages/core/src/host-dependencies/runtime/host-dependency-manager.ts
index 5c93a70a4..ad9446697 100644
--- a/console/packages/core/src/host-dependencies/runtime/host-dependency-manager.ts
+++ b/console/packages/core/src/host-dependencies/runtime/host-dependency-manager.ts
@@ -17,6 +17,7 @@ import type {
DependencyId,
DependencyInstallResult,
DependencyProbeOptions,
+ DependencyUninstallError,
DependencyState,
DependencyStatus,
DependencyStatusUpdatedEvent,
@@ -787,9 +788,143 @@ export class HostDependencyManager {
return ok(state);
}
+ /**
+ * Extracts package/formula names from an uninstall command string.
+ * Returns all targets — a command may name several packages (e.g.
+ * `npm uninstall -g @opencode/cli opencode-ai` for migration).
+ *
+ * For npm: every non-flag, non-subcommand token after `npm uninstall`.
+ * For homebrew: every non-flag token after `brew uninstall`.
+ */
+ private extractUninstallTargets(command: string, method: InstallMethod): string[] {
+ const tokens = command.split(/\s+/).filter(Boolean);
+ if (tokens.length < 2) return [];
+
+ if (method === 'npm') {
+ const flagsWithValue = new Set(['--prefix', '--registry']);
+ const targets: string[] = [];
+ for (let i = 0; i < tokens.length; i++) {
+ const tok = tokens[i]!;
+ if (tok.startsWith('-')) {
+ if (flagsWithValue.has(tok)) i++; // skip the flag's value
+ continue;
+ }
+ if (tok === 'npm' || tok === 'uninstall') continue;
+ targets.push(tok);
+ }
+ return targets;
+ }
+
+ if (method === 'homebrew') {
+ const targets: string[] = [];
+ for (const tok of tokens) {
+ if (tok.startsWith('-') || tok === 'brew' || tok === 'uninstall') continue;
+ targets.push(tok);
+ }
+ return targets;
+ }
+
+ return [];
+ }
+
+ /**
+ * Extracts the `--prefix` value from an npm command string, if present.
+ * The Linux OpenCode option installs under `--prefix "$HOME/.local"`, so
+ * the verification must query the same prefix rather than the default global root.
+ */
+ private extractNpmPrefix(command: string): string | null {
+ const tokens = command.split(/\s+/).filter(Boolean);
+ for (let i = 0; i < tokens.length - 1; i++) {
+ if (tokens[i] === '--prefix') {
+ const val = tokens[i + 1];
+ // Strip surrounding quotes that may appear in shell command strings
+ return val ? val.replace(/^["']|["']$/g, '') : null;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Pre-flight check: verify at least one of the target packages/formulas is
+ * actually installed before running the uninstall command. A command may list
+ * several packages (e.g. `npm uninstall -g @opencode/cli opencode-ai` for
+ * migration from a renamed package); the check passes when any one is found.
+ *
+ * For npm commands with `--prefix`, the same prefix is forwarded to `npm list`
+ * so the check queries the right install root.
+ *
+ * Returns the first found target on success, or an error when none is installed.
+ */
+ private async verifyUninstallTarget(
+ id: DependencyId,
+ command: string,
+ method: InstallMethod
+ ): Promise<Result<string, DependencyUninstallError>> {
+ const targets = this.extractUninstallTargets(command, method);
+ if (targets.length === 0) return ok('');
+
+ const VERIFY_TIMEOUT_MS = 10_000;
+
+ if (method === 'npm') {
+ const prefix = this.extractNpmPrefix(command);
+
+ for (const target of targets) {
+ const listArgs = ['list', '-g', target, '--depth=0'];
+ if (prefix) listArgs.push('--prefix', prefix);
+
+ try {
+ await this.ctx.exec('npm', listArgs, { timeout: VERIFY_TIMEOUT_MS });
+ return ok(target);
+ } catch {
+ // This target not found; try the next one
+ }
+ }
+
+ this.logger.warn(
+ `[HostDependencyManager] Pre-flight check: none of [${targets.join(', ')}] installed globally via npm`
+ );
+ return err({
+ type: 'uninstall-target-not-found',
+ id,
+ package: targets.join(', '),
+ method,
+ });
+ }
+
+ if (method === 'homebrew') {
+ for (const target of targets) {
+ try {
+ await this.ctx.exec('brew', ['list', target], { timeout: VERIFY_TIMEOUT_MS });
+ return ok(target);
+ } catch {
+ // This target not found; try the next one
+ }
+ }
+
+ this.logger.warn(
+ `[HostDependencyManager] Pre-flight check: none of [${targets.join(', ')}] installed via homebrew`
+ );
+ return err({
+ type: 'uninstall-target-not-found',
+ id,
+ package: targets.join(', '),
+ method,
+ });
+ }
+
+ // No verification available for this method; proceed
+ return ok('');
+ }
+
/**
* Uninstall an agent dependency on this host, then re-probe to confirm it is gone.
*
+ * Before running the uninstall command, a pre-flight check verifies the target
+ * package/formula is actually installed under the expected name. This catches
+ * mismatches like a descriptor naming `opencode-ai` when the binary was installed
+ * as `@opencode/cli` — npm silently exits 0 for packages that aren't installed,
+ * which would otherwise produce a false success.
+ *
* Routing is driven by the active installation's provenance: method selections use
* PM uninstall commands when available (e.g. `brew uninstall <formula>`), otherwise
* fall back to CLI self-uninstall. `manageable === false` → no-uninstall-strategy.
@@ -836,6 +971,14 @@ export class HostDependencyManager {
const plan = this.resolveUpdatePlan(effectiveMethod, descriptor, 'uninstall');
if (plan.kind === 'package-manager') {
+ // Pre-flight: verify the target package is actually installed
+ const resolvedMethod =
+ effectiveMethod ?? pickInstallOption(descriptor, this.platform)?.method;
+ if (resolvedMethod) {
+ const verify = await this.verifyUninstallTarget(id, plan.command, resolvedMethod);
+ if (!verify.success) return verify;
+ }
+
const runResult = await this.runInstallCommand(plan.command);
if (!runResult.success) return err(runResult.error);
} else if (plan.kind === 'cli') {
diff --git a/console/packages/core/src/host-dependencies/runtime/types.ts b/console/packages/core/src/host-dependencies/runtime/types.ts
index 624062bfc..f08d984e6 100644
--- a/console/packages/core/src/host-dependencies/runtime/types.ts
+++ b/console/packages/core/src/host-dependencies/runtime/types.ts
@@ -65,6 +65,7 @@ export type DependencyUninstallError =
| { type: 'unknown-dependency'; id: string }
| { type: 'no-uninstall-strategy'; id: string }
| { type: 'no-uninstall-command'; id: string }
+ | { type: 'uninstall-target-not-found'; id: string; package: string; method: string }
| { type: 'still-present'; id: string }
| InstallCommandError;
diff --git a/console/packages/plugins/src/agents/impl/opencode/host-dependency.test.ts b/console/packages/plugins/src/agents/impl/opencode/host-dependency.test.ts
index ef5a625c1..6f84816b4 100644
--- a/console/packages/plugins/src/agents/impl/opencode/host-dependency.test.ts
+++ b/console/packages/plugins/src/agents/impl/opencode/host-dependency.test.ts
@@ -20,9 +20,9 @@ describe('opencode host dependency', () => {
expect(option.recommended).toBe(true);
});
- it('installs the opencode-ai package on every platform', () => {
+ it('installs the @opencode/cli package on every platform', () => {
for (const platform of ['macos', 'linux', 'windows'] as const) {
- expect(firstOption(platform).command).toContain('opencode-ai');
+ expect(firstOption(platform).command).toContain('@opencode/cli');
}
});
@@ -32,6 +32,14 @@ describe('opencode host dependency', () => {
expect(firstOption(platform).command).not.toContain('--prefix');
});
+ it('uninstalls both @opencode/cli and the legacy opencode-ai on every platform', () => {
+ for (const platform of ['macos', 'linux', 'windows'] as const) {
+ const cmd = firstOption(platform).uninstallCommand ?? '';
+ expect(cmd).toContain('@opencode/cli');
+ expect(cmd).toContain('opencode-ai');
+ }
+ });
+
it('probes the opencode binary', () => {
expect(hostDependency.binaryNames).toEqual(['opencode']);
});
diff --git a/console/packages/plugins/src/agents/impl/opencode/index.ts b/console/packages/plugins/src/agents/impl/opencode/index.ts
index 44a7e46a9..76d06a015 100644
--- a/console/packages/plugins/src/agents/impl/opencode/index.ts
+++ b/console/packages/plugins/src/agents/impl/opencode/index.ts
@@ -27,16 +27,27 @@ const validateSessionId = (id: string) => id.startsWith('ses');
* user-writable, and changing them would strand anyone who already has it.
*/
const OPENCODE_HOST_DEPENDENCY = (() => {
- const base = npmDependency({ id: 'opencode', package: 'opencode-ai' });
+ const base = npmDependency({ id: 'opencode', package: '@opencode/cli' });
+
+ // Uninstall must target both the current package (@opencode/cli) and the
+ // legacy name (opencode-ai) that Console used to install. Users may have
+ // either one; npm silently skips whichever isn't present.
+ const patchUninstall = (options: typeof base.installCommands.macos) =>
+ options?.map((opt) => ({
+ ...opt,
+ ...(opt.uninstallCommand ? { uninstallCommand: opt.uninstallCommand + ' opencode-ai' } : {}),
+ }));
+
return {
...base,
installCommands: {
- ...base.installCommands,
+ macos: patchUninstall(base.installCommands.macos),
+ windows: patchUninstall(base.installCommands.windows),
linux: [
{
method: 'npm' as const,
- command: 'npm install -g --prefix "$HOME/.local" opencode-ai',
- uninstallCommand: 'npm uninstall -g --prefix "$HOME/.local" opencode-ai',
+ command: 'npm install -g --prefix "$HOME/.local" @opencode/cli',
+ uninstallCommand: 'npm uninstall -g --prefix "$HOME/.local" @opencode/cli opencode-ai',
recommended: true,
},
],