From 57d34cced794288aabd706b3c423d929d60102d4 Mon Sep 17 00:00:00 2001 From: Julius Olsson Date: Fri, 27 Nov 2026 15:44:12 -0800 Subject: [PATCH 1/4] docs(setup): plan fresh-user setup, binary detection, and bootstrap fixes --- ...26-11-27-fresh-user-setup-and-bootstrap.md | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 docs/plans/2026-11-27-fresh-user-setup-and-bootstrap.md diff --git a/docs/plans/2026-11-27-fresh-user-setup-and-bootstrap.md b/docs/plans/2026-11-27-fresh-user-setup-and-bootstrap.md new file mode 100644 index 000000000..64b82c891 --- /dev/null +++ b/docs/plans/2026-11-27-fresh-user-setup-and-bootstrap.md @@ -0,0 +1,61 @@ +# Plan: Fresh-User Setup, Binary Detection, and Bootstrap Fixes + +Fixes #1553 + +## Problem + +Fresh-user setup, binary detection, and provider enablement have several interlocking bugs that strand or mislead users who start with zero providers, have noisy shell startup files, or run into Gatekeeper/noexec stalls on bundled tools: + +1. **Stale `providerEnablement` cache after Setup discovers a CLI**: `providerEnablement.ts` caches `cachedDetected` for the process lifetime and only clears it on `resetProviderEnablement`. When a user installs a CLI or sets a manual path in `SetupGate` (`setup:check` / `setup:set-tool-path`), `provider-enablement:changed` is never broadcast, so `PathPickerModal` (`⌘T`) still hides the newly installed provider until app restart. +2. **0-provider `PathPickerModal` silently submits Claude**: When a user chooses "Continue with a Terminal" (`enabledKinds.size === 0`), `PathPickerModal` renders an empty provider bar and silently falls back to `DEFAULT_PROVIDER` (`'claude'`), causing `⌘T` to fail on spawn instead of offering to open Setup or a Terminal tab. +3. **Unbounded `probeExecutable` and sticky failed-probe cache**: In `runtimeTools.ts`, `probeExecutable` has no timeout (a Gatekeeper/XProtect stall hangs indefinitely) and caches rejected promises permanently in `execProbeCache` (clearing quarantine and clicking Retry still fails until app restart). +4. **Bundled archive presence vs. executable resolution mismatch**: `prerequisites.ts` marks bundled tools (`opencode`, `mitmdump`) as `found: true, source: 'bundled'` using `isBundledArchiveAvailable` (file existence only) instead of `resolveBundledTool` (actual extraction + exec probe), and ignores a valid manual override on a bundled tool. When the bundled binary fails its exec probe, `SetupGate` falsely reports "Bundled" and hides manual override / install options. +5. **`SetupGate` UX dead ends**: + - Pressing `Enter` inside "Enter Path Manually…" bubbles to `DialogActions` and closes `SetupGate` before the user sees the result or validation error. + - `setup:set-tool-path` rejects `~/...` paths instead of expanding leading `~/` to `homedir()`. + - `Found` (and `Bundled`) provider rows do not offer **Change Path…**, so users cannot point an already-detected provider at a different binary. + - When `setup:check` fails (`check === null`) and the user explicitly opens Setup (`requested && error`), `SetupGate` returns `null` instead of rendering the error state with a Retry button. +6. **Noisy `.zprofile`, missing macOS bin dirs, and duplicate startup probes**: + - `binaryResolver.ts` reads the *first* line of `zsh -lc` stdout, so any `.zprofile` banner/echo breaks `command -v` detection for every tool. + - `WELL_KNOWN_BIN_DIRS` omits `~/.local/share/mise/shims`, `~/Library/pnpm`, `~/.npm-global/bin`, and `~/.claude/local`. + - `checkPrerequisites()` does not deduplicate concurrent in-flight calls, so startup (`SetupGate` + `providerEnablement`) spawns ~16 parallel login shells at once. + +## Implementation Plan + +1. **`providerEnablement` sync + 0-provider `PathPickerModal`**: + - Add `syncDetectedProvidersFromCheck(result)` to `src/main/setup/providerEnablement.ts` that updates `cachedDetected` / `lastDetected`, re-resolves the snapshot in order, invalidates the usage cache, and broadcasts `provider-enablement:changed` when detected providers change (or on initial sync). + - Call `syncDetectedProvidersFromCheck` from `setup:check` and `setup:set-tool-path` in `src/main/ipc/setup.ts` (best-effort so a sync error never fails setup IPC). + - Update `PathPickerModal.tsx` and `PathPickerSurface.tsx` so when `enabledKinds.size === 0`: + - Show an inline notice with an **Open Setup** action. + - Skip conversation listing and hide `ResumeSection`. + - Offer **Open Terminal** / **Create & Open Terminal** (via `onOpenTerminal`) instead of silently submitting `DEFAULT_PROVIDER`. + - Sync `provider` when `enabledKinds` changes from empty to non-empty. +2. **Bounded `probeExecutable` timeout & success-only caching (`src/main/setup/runtimeTools.ts`)**: + - Add an 8s default timeout (`EXEC_PROBE_TIMEOUT_MS`) to `probeExecutable` that kills the hung child (`SIGKILL`) and rejects with `BundledToolExecProbeError`. + - Keep in-flight deduplication in `execProbeCache`, but evict rejected entries on failure so Retry re-probes cleanly. +3. **Align bundled tool detection with `resolveBundledTool` (`src/main/setup/prerequisites.ts`)**: + - For bundled tools without a valid manual override, call `resolveBundledTool(tool)` instead of `isBundledArchiveAvailable(tool)`. + - Only report `source: 'bundled'` when `resolveBundledTool` returns a non-null executable path; otherwise fall back to system PATH / manual override / install prompt. + - Respect valid manual overrides over bundled tools (matching `toolchain.ts`). +4. **Fix `SetupGate` UX dead ends (`SetupGate.tsx`, `dialog-actions.tsx`, `src/main/ipc/setup.ts`)**: + - Support `data-owns-enter` in `focusedControlOwnsEnter` (`dialog-actions.tsx`), mark the manual path `` with `data-owns-enter`, and disable `confirmOnEnter` on `SetupGate`'s `DialogActions` while any row's path editor is open. + - Expand leading `~/` (and bare `~`) to `homedir()` in `setup:set-tool-path` before absolute-path validation. + - Enable manual path editing on all provider rows (**Change Path…** when found/bundled, **Enter Path Manually…** when missing). + - Render `SetupGate` when `requested && error` even when `check === null`, showing the error alert, Close, and Retry. +5. **Fix `binaryResolver.ts` & deduplicate `checkPrerequisites()`**: + - Read the last non-empty line of `runLoginShell` stdout in `resolveToolPath` so `.zprofile` banners do not break detection. + - Add `~/.local/share/mise/shims`, `~/Library/pnpm`, `~/.npm-global/bin`, and `~/.claude/local` to `WELL_KNOWN_BIN_DIRS`. + - Deduplicate concurrent in-flight `checkPrerequisites()` calls via an `inFlightCheck` promise cleared in `.finally()`. + +## Verification + +- Add/update unit & renderer tests in: + - `src/main/setup/providerEnablement.test.ts` + - `src/main/ipc/setup.test.ts` + - `src/main/setup/runtimeTools.test.ts` + - `src/main/setup/prerequisites.test.ts` + - `src/main/setup/binaryResolver.test.ts` + - `src/renderer/src/components/ui/dialog-actions.renderer.test.tsx` + - `src/renderer/src/features/setup/firstRun.renderer.test.tsx` + - `src/renderer/src/features/path-picker/ui/PathPickerModal.renderer.test.tsx` +- Run `npm run typecheck` and targeted `vitest` suites in the worktree. From bd1c4831ce1cc003e569bd676775ac166a111d67 Mon Sep 17 00:00:00 2001 From: Julius Olsson Date: Fri, 27 Nov 2026 15:48:45 -0800 Subject: [PATCH 2/4] fix(setup): harden binary detection, bundled probes, and check deduplication Refs #1553 - Parse the last non-empty line of login-shell stdout so noisy .zprofile banners do not break command -v detection, and scan ~/.local/share/mise/shims, ~/Library/pnpm, ~/.npm-global/bin, and ~/.claude/local. - Add an 8s timeout to probeExecutable (killing Gatekeeper/XProtect stalls) and evict failed probes from execProbeCache so Retry re-probes cleanly. - Resolve bundled tools via resolveBundledTool instead of isBundledArchiveAvailable so unrunnable bundled binaries fall back to system PATH or manual/install flows, and honor valid manual overrides above bundled binaries. - Deduplicate concurrent in-flight checkPrerequisites() calls on startup. --- src/main/setup/binaryResolver.test.ts | 67 ++++++++++++++++++++ src/main/setup/binaryResolver.ts | 80 +++++++++++++++--------- src/main/setup/prerequisites.test.ts | 86 +++++++++++++++++++++++--- src/main/setup/prerequisites.ts | 50 +++++++++++---- src/main/setup/runtimeTools.test.ts | 69 +++++++++++++++++++++ src/main/setup/runtimeTools.ts | 88 +++++++++++++++++++++------ 6 files changed, 372 insertions(+), 68 deletions(-) create mode 100644 src/main/setup/binaryResolver.test.ts create mode 100644 src/main/setup/runtimeTools.test.ts diff --git a/src/main/setup/binaryResolver.test.ts b/src/main/setup/binaryResolver.test.ts new file mode 100644 index 000000000..d2dcbe992 --- /dev/null +++ b/src/main/setup/binaryResolver.test.ts @@ -0,0 +1,67 @@ +import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const shellMock = vi.hoisted(() => ({ runLoginShell: vi.fn() })) +vi.mock('@main/setup/shell.js', () => shellMock) + +const homeMock = vi.hoisted(() => ({ dir: '' })) +vi.mock('os', async importOriginal => { + const actual = await importOriginal() + return { + ...actual, + homedir: () => homeMock.dir || actual.homedir(), + } +}) + +import { resolveToolPath } from './binaryResolver.js' + +let dir: string +const originalPath = process.env.PATH + +beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'binary-resolver-')) + homeMock.dir = dir + shellMock.runLoginShell.mockReset() + process.env.PATH = '' +}) + +afterEach(async () => { + process.env.PATH = originalPath + homeMock.dir = '' + await rm(dir, { recursive: true, force: true }) +}) + +async function makeExecutable(path: string): Promise { + await mkdir(join(path, '..'), { recursive: true }) + await writeFile(path, '#!/bin/sh\nexit 0\n') + await chmod(path, 0o755) +} + +describe('resolveToolPath (#1553)', () => { + it('reads the last non-empty line of login-shell stdout so noisy .zprofile banners do not break detection', async () => { + const bin = join(dir, 'custom', 'claude') + await makeExecutable(bin) + shellMock.runLoginShell.mockResolvedValue({ + stdout: `Welcome to zsh!\nLoaded nvm v20\n\n${bin}\n\n`, + stderr: '', + }) + + expect(await resolveToolPath('claude')).toBe(bin) + }) + + it.each([ + ['mise shims', ['.local', 'share', 'mise', 'shims']], + ['pnpm home', ['Library', 'pnpm']], + ['npm-global', ['.npm-global', 'bin']], + ['claude local', ['.claude', 'local']], + ])('falls back to well-known macOS bin dir: %s', async (_label, segments) => { + shellMock.runLoginShell.mockRejectedValue(new Error('shell probe failed')) + const bin = join(dir, ...segments, 'claude') + await makeExecutable(bin) + + expect(await resolveToolPath('claude')).toBe(bin) + }) +}) diff --git a/src/main/setup/binaryResolver.ts b/src/main/setup/binaryResolver.ts index 8c783c9e5..255ed0466 100644 --- a/src/main/setup/binaryResolver.ts +++ b/src/main/setup/binaryResolver.ts @@ -75,39 +75,49 @@ export async function isExecutable(path: string): Promise { // when the app is launched from a terminal it is the user's real PATH; from // Finder it is launchd's minimal one, which is exactly when the well-known // dirs earn their keep. -const WELL_KNOWN_BIN_DIRS = [ - join(homedir(), '.local', 'bin'), - // WHY ~/.opencode/bin (#995 Codex review, reproduced): OpenCode's own - // installer — the command the setup panel now tells users to run — writes - // the binary here and appends its PATH export to ~/.zshrc. The login-shell - // probe runs `$SHELL -lc`, and `zsh -lc` sources .zprofile/.zshenv but NOT - // .zshrc, so the probe cannot see it either. Without this entry the loop the - // feature exists to close dead-ended: the gate says "Not installed", the - // user runs the command it gave them, presses Retry, and it still says - // "Not installed". - join(homedir(), '.opencode', 'bin'), - // The Grok CLI's own layout, for the same reason. Its npm install lands in a - // prefix already scanned below, but a native install puts the binary here. - join(homedir(), '.grok', 'bin'), - // Pi's installer (https://pi.dev/install.sh) writes `pi` into ~/.local/bin - // (above) for an npm install, or into ~/.pi/agent/bin for its managed - // install — and, like OpenCode's, relies on a .zshrc PATH line the login - // probe never sources. - join(homedir(), '.pi', 'agent', 'bin'), - join(homedir(), '.volta', 'bin'), - join(homedir(), '.asdf', 'shims'), - join(homedir(), '.bun', 'bin'), - join(homedir(), '.cargo', 'bin'), - '/opt/homebrew/bin', - '/usr/local/bin', - '/usr/bin', - '/bin', -] +function getWellKnownBinDirs(): string[] { + const home = homedir() + return [ + join(home, '.local', 'bin'), + // WHY ~/.opencode/bin (#995 Codex review, reproduced): OpenCode's own + // installer — the command the setup panel now tells users to run — writes + // the binary here and appends its PATH export to ~/.zshrc. The login-shell + // probe runs `$SHELL -lc`, and `zsh -lc` sources .zprofile/.zshenv but NOT + // .zshrc, so the probe cannot see it either. Without this entry the loop the + // feature exists to close dead-ended: the gate says "Not installed", the + // user runs the command it gave them, presses Retry, and it still says + // "Not installed". + join(home, '.opencode', 'bin'), + // The Grok CLI's own layout, for the same reason. Its npm install lands in a + // prefix already scanned below, but a native install puts the binary here. + join(home, '.grok', 'bin'), + // Pi's installer (https://pi.dev/install.sh) writes `pi` into ~/.local/bin + // (above) for an npm install, or into ~/.pi/agent/bin for its managed + // install — and, like OpenCode's, relies on a .zshrc PATH line the login + // probe never sources. + join(home, '.pi', 'agent', 'bin'), + // Claude Code's local install layout (`claude migrate-installer` / native + // local shim), plus common macOS version-manager and global-package dirs + // that are frequently added in `.zshrc` rather than `.zprofile` (#1553). + join(home, '.claude', 'local'), + join(home, '.local', 'share', 'mise', 'shims'), + join(home, 'Library', 'pnpm'), + join(home, '.npm-global', 'bin'), + join(home, '.volta', 'bin'), + join(home, '.asdf', 'shims'), + join(home, '.bun', 'bin'), + join(home, '.cargo', 'bin'), + '/opt/homebrew/bin', + '/usr/local/bin', + '/usr/bin', + '/bin', + ] +} async function scanForTool(command: string): Promise { const pathDirs = (process.env.PATH ?? '').split(':').filter(Boolean) const seen = new Set() - for (const dir of [...pathDirs, ...WELL_KNOWN_BIN_DIRS]) { + for (const dir of [...pathDirs, ...getWellKnownBinDirs()]) { if (seen.has(dir)) continue seen.add(dir) const candidate = join(dir, command) @@ -127,7 +137,17 @@ export async function resolveToolPath(tool: SetupToolId): Promise timeoutMs: 10_000, maxBuffer: 64 * 1024, }) - const path = result.stdout.trim().split('\n')[0]?.trim() + // WHY the LAST non-empty line, not `[0]` (#1553): users frequently have + // echoes, MOTDs, or tool-init notices in `~/.zprofile` or `~/.zshenv`. + // Those print to stdout BEFORE `command -v` runs, so line 0 was the banner + // text — which failed `isExecutable()` and broke Layer 1 detection for + // every tool on the machine. `command -v` always writes the resolved path + // as the final non-empty line. + const lines = result.stdout + .split(/\r?\n/) + .map(line => line.trim()) + .filter(Boolean) + const path = lines.at(-1) if (path && await isExecutable(path)) return path } catch { // Probe failure is NOT evidence of absence (#495 A1) — a broken rc diff --git a/src/main/setup/prerequisites.test.ts b/src/main/setup/prerequisites.test.ts index caa5442a3..e4a18b837 100644 --- a/src/main/setup/prerequisites.test.ts +++ b/src/main/setup/prerequisites.test.ts @@ -14,15 +14,17 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest' const paths = vi.hoisted(() => ({ STATE_DIR: '' })) vi.mock('@main/storage/paths.js', () => paths) -vi.mock('@main/setup/binaryResolver.js', () => ({ - resolveToolPath: async (tool: string) => (tool === 'codex' ? '/fresh/codex' : null), - isExecutable: async (path: string) => path === '/fresh/codex', - classifyExecutable: async () => 'ok', +const resolver = vi.hoisted(() => ({ + resolveToolPath: vi.fn(async (tool: string): Promise => (tool === 'codex' ? '/fresh/codex' : null)), + isExecutable: vi.fn(async (path: string): Promise => path === '/fresh/codex'), + classifyExecutable: vi.fn(async () => 'ok' as const), })) -vi.mock('@main/setup/runtimeTools.js', () => ({ - isBundledArchiveAvailable: async () => false, - resolveBundledTool: async () => null, +vi.mock('@main/setup/binaryResolver.js', () => resolver) +const runtimeTools = vi.hoisted(() => ({ + isBundledArchiveAvailable: vi.fn(async (_tool?: string): Promise => false), + resolveBundledTool: vi.fn(async (_tool: string): Promise => null), })) +vi.mock('@main/setup/runtimeTools.js', () => runtimeTools) const renameFaults = vi.hoisted(() => ({ failNext: 0 })) vi.mock('fs/promises', async importOriginal => { const actual = await importOriginal() @@ -44,6 +46,10 @@ beforeEach(async () => { dir = await mkdtemp(join(tmpdir(), 'prerequisites-')) paths.STATE_DIR = dir renameFaults.failNext = 0 + resolver.resolveToolPath.mockReset().mockImplementation(async (tool: string) => (tool === 'codex' ? '/fresh/codex' : null)) + resolver.isExecutable.mockReset().mockImplementation(async (path: string) => path === '/fresh/codex') + runtimeTools.isBundledArchiveAvailable.mockReset().mockResolvedValue(false) + runtimeTools.resolveBundledTool.mockReset().mockResolvedValue(null) vi.resetModules() vi.spyOn(console, 'warn').mockImplementation(() => {}) await mkdir(dir, { recursive: true }) @@ -75,3 +81,69 @@ it('launches the persisted probe when the write-back lands', async () => { expect(JSON.parse(await readFile(join(dir, 'setup.json'), 'utf8')).toolPaths.codex).toBe('/fresh/codex') expect(getToolPath('codex', '')).toBe('/fresh/codex') }) + +// #1553: bundled tools must only report `source: 'bundled'` when +// `resolveBundledTool` succeeds, not merely when an archive exists on disk. +it('falls back to system/missing when resolveBundledTool returns null even if archive exists', async () => { + runtimeTools.isBundledArchiveAvailable.mockResolvedValue(true) + runtimeTools.resolveBundledTool.mockResolvedValue(null) + resolver.resolveToolPath.mockImplementation(async (tool: string) => + tool === 'opencode' ? '/usr/local/bin/opencode' : null, + ) + const { checkPrerequisites } = await import('./prerequisites.js') + const check = await checkPrerequisites() + expect(check.tools.opencode).toMatchObject({ + found: true, + path: '/usr/local/bin/opencode', + source: 'system', + }) + expect(check.tools.mitmdump).toMatchObject({ + found: false, + path: null, + source: undefined, + }) +}) + +it('prefers a valid manual override over a bundled binary', async () => { + runtimeTools.resolveBundledTool.mockImplementation(async (tool: string) => + tool === 'opencode' ? '/app.asar.unpacked/opencode' : null, + ) + resolver.isExecutable.mockImplementation(async (path: string) => path === '/custom/opencode') + await writeFile( + join(dir, 'setup.json'), + JSON.stringify({ version: 1, manualToolPaths: { opencode: '/custom/opencode' } }), + ) + const { checkPrerequisites } = await import('./prerequisites.js') + const check = await checkPrerequisites() + expect(check.tools.opencode).toMatchObject({ + found: true, + path: '/custom/opencode', + source: 'system', + }) +}) + +it('deduplicates concurrent in-flight checkPrerequisites() calls', async () => { + let releaseBrew!: () => void + const brewGate = new Promise(resolve => { releaseBrew = resolve }) + resolver.resolveToolPath.mockImplementation(async (tool: string) => { + if (tool === 'brew') { + await brewGate + return '/opt/homebrew/bin/brew' + } + return null + }) + const { checkPrerequisites } = await import('./prerequisites.js') + const first = checkPrerequisites() + const second = checkPrerequisites() + expect(second).toBe(first) + releaseBrew() + const [a, b] = await Promise.all([first, second]) + expect(a).toBe(b) + const brewCalls = resolver.resolveToolPath.mock.calls.filter(([tool]) => tool === 'brew') + expect(brewCalls).toHaveLength(1) + + // After completion, a subsequent call runs a fresh check. + await checkPrerequisites() + const brewCallsAfter = resolver.resolveToolPath.mock.calls.filter(([tool]) => tool === 'brew') + expect(brewCallsAfter).toHaveLength(2) +}) diff --git a/src/main/setup/prerequisites.ts b/src/main/setup/prerequisites.ts index b820097a1..cf6e1ee64 100644 --- a/src/main/setup/prerequisites.ts +++ b/src/main/setup/prerequisites.ts @@ -4,7 +4,7 @@ import type { SetupToolStatus, } from '@shared/types/setup.js' import { isExecutable, resolveToolPath } from '@main/setup/binaryResolver.js' -import { isBundledArchiveAvailable } from '@main/setup/runtimeTools.js' +import { resolveBundledTool } from '@main/setup/runtimeTools.js' import type { BundledToolId } from '@main/setup/runtimeTools.js' import { loadSetupState, updateToolPaths } from '@main/setup/setupState.js' import { listProviderSetupDescriptors } from '@providers/registry.setup.js' @@ -93,7 +93,23 @@ const TOOL_META: Record> = // providers (Hermes) have no binary to find; see SetupToolId. const CHECK_ORDER: SetupToolId[] = ['brew', ...LOCAL_PROVIDER_KINDS, 'git', 'mitmdump'] -export async function checkPrerequisites(): Promise { +// Deduplicate concurrent in-flight prerequisite checks (#1553). On startup, +// SetupGate (`setup:check`) and providerEnablement (`provider-enablement:get`) +// both call `checkPrerequisites()` at the same time; without sharing the +// in-flight promise, startup spawns 2x CHECK_ORDER.length (~16) parallel login +// shells simultaneously. Cleared in `finally` so every subsequent explicit +// Retry runs a fresh probe. +let inFlightCheck: Promise | null = null + +export function checkPrerequisites(): Promise { + if (inFlightCheck) return inFlightCheck + inFlightCheck = runCheckPrerequisites().finally(() => { + inFlightCheck = null + }) + return inFlightCheck +} + +async function runCheckPrerequisites(): Promise { const state = await loadSetupState() const brewPath = await resolveToolPath('brew') const entries = await Promise.all( @@ -125,8 +141,8 @@ export async function checkPrerequisites(): Promise { // via the null → delete write-back. Re-checks the file, not // the bookkeeping, so genuinely-removed tools still clear. const manual = state.manualToolPaths[tool] - let systemPath = - manual && (await isExecutable(manual)) ? manual : null + const hasValidManual = Boolean(manual && (await isExecutable(manual))) + let systemPath = hasValidManual ? manual! : null if (!systemPath) { systemPath = tool === 'brew' ? brewPath : await resolveToolPath(tool) } @@ -134,15 +150,25 @@ export async function checkPrerequisites(): Promise { const persisted = state.toolPaths[tool] if (persisted && (await isExecutable(persisted))) systemPath = persisted } - // WHY bundled detection takes precedence over PATH: - // When we ship a tool, that is the version we tested with and - // the version proxy diagnostics + behaviour assume. A user's - // stale Homebrew install of an older mitmproxy could pass - // PATH detection but break our proxy startup contract. Show - // the bundled status so the user knows what's actually being - // spawned at runtime. + // WHY `resolveBundledTool` instead of `isBundledArchiveAvailable` (#1553): + // `isBundledArchiveAvailable` only checks whether the file/archive + // exists on disk, NOT whether the OS will actually execute it. On a + // noexec mount, Gatekeeper stall, or broken extraction, `resolveBundledTool` + // returns null at spawn time while `isBundledArchiveAvailable` still + // returned true — causing SetupGate to report "Bundled" (hiding the + // manual override and install options) and bootstrap to pick a broken + // provider. Probing through `resolveBundledTool` ensures "Bundled" only + // appears when the bundled binary is genuinely runnable; otherwise we + // fall back cleanly to `systemPath` or show the install/manual options. + // + // WHY `!hasValidManual` gates bundled precedence: + // Matches `toolchain.ts`: a valid manual override beats the bundled + // binary, so SetupGate must show the user's chosen path as `system` + // rather than falsely labelling it `Bundled`. const bundled = - BUNDLED_TOOL_IDS.has(tool) && (await isBundledArchiveAvailable(tool as BundledToolId)) + !hasValidManual && + BUNDLED_TOOL_IDS.has(tool) && + Boolean(await resolveBundledTool(tool as BundledToolId)) const found = bundled || Boolean(systemPath) const status: SetupToolStatus = { ...TOOL_META[tool], diff --git a/src/main/setup/runtimeTools.test.ts b/src/main/setup/runtimeTools.test.ts new file mode 100644 index 000000000..1f1f1d770 --- /dev/null +++ b/src/main/setup/runtimeTools.test.ts @@ -0,0 +1,69 @@ +import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +vi.mock('electron', () => ({ + app: { + getAppPath: () => '/nonexistent', + getPath: () => '/nonexistent', + }, +})) + +import { + BundledToolExecProbeError, + clearExecProbeCacheForTests, + probeExecutable, +} from './runtimeTools.js' + +let dir: string + +beforeEach(async () => { + clearExecProbeCacheForTests() + dir = await mkdtemp(join(tmpdir(), 'runtime-tools-probe-')) +}) + +afterEach(async () => { + clearExecProbeCacheForTests() + await rm(dir, { recursive: true, force: true }) +}) + +describe('probeExecutable (#1553)', () => { + it('kills a hung binary after timeoutMs and rejects with BundledToolExecProbeError', async () => { + const script = join(dir, 'hang.sh') + await writeFile(script, '#!/bin/sh\nsleep 10\n') + await chmod(script, 0o755) + + await expect(probeExecutable('opencode', script, ['--version'], 120)).rejects.toThrow( + BundledToolExecProbeError, + ) + await expect(probeExecutable('opencode', script, ['--version'], 120)).rejects.toThrow( + /timed out after 120ms/, + ) + }) + + it('evicts failed probes from execProbeCache so Retry succeeds once fixed, while caching successes', async () => { + const script = join(dir, 'flaky.sh') + const counter = join(dir, 'count.txt') + // First run fails (simulates Gatekeeper/quarantine failure). + await writeFile(script, '#!/bin/sh\necho blocked >&2\nexit 1\n') + await chmod(script, 0o755) + + await expect(probeExecutable('opencode', script, ['--version'], 2_000)).rejects.toThrow( + BundledToolExecProbeError, + ) + + // User clears quarantine / fixes the binary; next probe must re-run and succeed. + await writeFile(script, `#!/bin/sh\necho x >> "${counter}"\nexit 0\n`) + await chmod(script, 0o755) + + await expect(probeExecutable('opencode', script, ['--version'], 2_000)).resolves.toBeUndefined() + // Subsequent call hits the success cache without spawning again. + await expect(probeExecutable('opencode', script, ['--version'], 2_000)).resolves.toBeUndefined() + + const { readFile } = await import('node:fs/promises') + const lines = (await readFile(counter, 'utf8')).trim().split('\n') + expect(lines).toHaveLength(1) + }) +}) diff --git a/src/main/setup/runtimeTools.ts b/src/main/setup/runtimeTools.ts index e8c9c747a..56c32e895 100644 --- a/src/main/setup/runtimeTools.ts +++ b/src/main/setup/runtimeTools.ts @@ -117,19 +117,33 @@ export class BundledToolExecProbeError extends Error { } } +// Bounded timeout for the real-exec version probe (#1553). On macOS, a +// quarantined or freshly-unpacked binary can stall inside Gatekeeper/XProtect +// assessment; without a timeout, startup and SetupGate hang indefinitely. +export const EXEC_PROBE_TIMEOUT_MS = 8_000 + // Cache keyed by binary path, NOT by tool: mitmdump probes a freshly // extracted per-version path, and a re-extraction after corruption gets a -// new tmp path and therefore a fresh probe. Failures are cached too — a -// noexec mount does not heal within a process lifetime, and re-spawning a -// known-broken binary on every resolve would just spam the journal. The -// cached promise is always awaited immediately by its first caller, so a -// cached rejection never floats unhandled. +// new tmp path and therefore a fresh probe. +// +// WHY only SUCCESSFUL probes are kept in the cache (#1553): we used to keep +// rejected promises forever, assuming failures only meant an immutable noexec +// mount. In practice, macOS Gatekeeper quarantine, XProtect stalls, or a +// transient chmod/extract hiccup can be cleared by the user while the app is +// running — caching the failure permanently made SetupGate's Retry button +// useless until app restart. Keeping the in-flight promise still deduplicates +// concurrent probes, and evicting on rejection ensures Retry re-probes. const execProbeCache = new Map>() -function probeExecutable( +export function clearExecProbeCacheForTests(): void { + execProbeCache.clear() +} + +export function probeExecutable( tool: BundledToolId, binary: string, versionArgs: string[], + timeoutMs: number = EXEC_PROBE_TIMEOUT_MS, ): Promise { const cached = execProbeCache.get(binary) if (cached) return cached @@ -137,47 +151,83 @@ function probeExecutable( const child = spawn(binary, versionArgs, { stdio: ['ignore', 'ignore', 'pipe'], }) + let settled = false let stderr = '' + const finish = (outcome: { ok: true } | { ok: false; err: Error }) => { + if (settled) return + settled = true + clearTimeout(timer) + if (outcome.ok) resolve() + else reject(outcome.err) + } + const timer = setTimeout(() => { + try { + child.kill('SIGKILL') + } catch { + // Child may have already exited between timeout scheduling and kill. + } + finish({ + ok: false, + err: new BundledToolExecProbeError( + tool, + binary, + `bundled ${tool} at ${binary} timed out after ${timeoutMs}ms on its version probe (Gatekeeper/XProtect stall or hung binary)`, + ), + }) + }, timeoutMs) child.stderr.on('data', chunk => { stderr += String(chunk) }) child.once('error', err => { const code = (err as NodeJS.ErrnoException).code if (code === 'EACCES') { - reject( - new BundledToolExecProbeError( + finish({ + ok: false, + err: new BundledToolExecProbeError( tool, binary, `bundled ${tool} at ${binary} has its executable bit set but the OS refused to execute it (EACCES) — the containing filesystem may be mounted noexec`, { cause: err }, ), - ) + }) return } - reject( - new BundledToolExecProbeError( + finish({ + ok: false, + err: new BundledToolExecProbeError( tool, binary, `bundled ${tool} at ${binary} failed to spawn: ${code ?? err.message}`, { cause: err }, ), - ) + }) }) child.once('exit', code => { - if (code === 0) resolve() - else { - reject( - new BundledToolExecProbeError( + if (code === 0) { + finish({ ok: true }) + } else { + finish({ + ok: false, + err: new BundledToolExecProbeError( tool, binary, `bundled ${tool} at ${binary} exited ${code} on its version probe: ${stderr.trim()}`, ), - ) + }) } }) }) - execProbeCache.set(binary, probe) - return probe + const tracked = probe.then( + () => undefined, + err => { + if (execProbeCache.get(binary) === tracked) { + execProbeCache.delete(binary) + } + throw err + }, + ) + execProbeCache.set(binary, tracked) + return tracked } export function getPlatformKey(): string | null { From b5b1e2ec4c1ed68c013a2d19d731169c5e628718 Mon Sep 17 00:00:00 2001 From: Julius Olsson Date: Fri, 27 Nov 2026 15:48:45 -0800 Subject: [PATCH 3/4] fix(setup): sync provider enablement and fix SetupGate & 0-provider PathPicker UX Refs #1553 - Sync newly discovered providers from setup:check and setup:set-tool-path into providerEnablement and broadcast provider-enablement:changed so PathPickerModal updates without an app restart. - When zero providers are enabled in PathPickerModal, show an inline Open Setup action and open a Terminal tab instead of silently submitting DEFAULT_PROVIDER ('claude'). - Prevent Enter inside SetupGate's manual path input from closing the dialog via DialogActions, expand leading ~/ in setup:set-tool-path, expose Change Path... on Found/Bundled provider rows, and render the error + Retry state when requested with check === null. --- src/main/ipc/setup.test.ts | 33 +++- src/main/ipc/setup.ts | 32 +++- src/main/setup/providerEnablement.test.ts | 24 +++ src/main/setup/providerEnablement.ts | 38 +++++ .../ui/dialog-actions.renderer.test.tsx | 4 + .../src/components/ui/dialog-actions.tsx | 8 +- .../surfaces/PathPickerSurface.tsx | 9 ++ .../ui/PathPickerModal.renderer.test.tsx | 55 +++++++ .../path-picker/ui/PathPickerModal.tsx | 145 +++++++++++++----- .../features/setup/firstRun.renderer.test.tsx | 65 ++++++++ .../src/features/setup/ui/SetupGate.tsx | 126 +++++++++++---- 11 files changed, 466 insertions(+), 73 deletions(-) diff --git a/src/main/ipc/setup.test.ts b/src/main/ipc/setup.test.ts index e756856e1..a19a97cf0 100644 --- a/src/main/ipc/setup.test.ts +++ b/src/main/ipc/setup.test.ts @@ -1,5 +1,5 @@ import { mkdtemp, readFile, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' +import { homedir, tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, expect, it, vi } from 'vitest' @@ -28,9 +28,16 @@ vi.mock('@main/setup/binaryResolver.js', () => ({ isExecutable: async () => false, classifyExecutable: async () => 'ok', })) -vi.mock('@main/setup/runtimeTools.js', () => ({ isBundledArchiveAvailable: async () => false })) +vi.mock('@main/setup/runtimeTools.js', () => ({ + isBundledArchiveAvailable: async () => false, + resolveBundledTool: async () => null, +})) vi.mock('@main/setup/toolchain.js', () => ({ refreshToolchainFromState: async () => {} })) vi.mock('@main/setup/homebrewInstaller.js', () => ({ installWithHomebrew: vi.fn() })) +const syncDetected = vi.hoisted(() => ({ fn: vi.fn(async () => ({})) })) +vi.mock('@main/setup/providerEnablement.js', () => ({ + syncDetectedProvidersFromCheck: syncDetected.fn, +})) // Each rename in order: `true` fails it. The answer's write is the first, the // check's write-back the second. const renamePlan = vi.hoisted(() => ({ fail: [] as boolean[] })) @@ -51,6 +58,7 @@ beforeEach(async () => { paths.STATE_DIR = dir handlers.clear() renamePlan.fail = [] + syncDetected.fn.mockClear() vi.resetModules() vi.spyOn(console, 'warn').mockImplementation(() => {}) const { registerSetupIpc } = await import('./setup.js') @@ -90,3 +98,24 @@ it('rejects a skip whose own write fails', async () => { renamePlan.fail = [true] await expect(invoke('setup:skip-optional', 'mitmdump')).rejects.toThrow('ENOSPC') }) + +// #1553: tilde expansion in setup:set-tool-path + syncing providerEnablement. +it('expands leading ~/ to homedir() in setup:set-tool-path and syncs provider enablement', async () => { + const result = await invoke('setup:set-tool-path', 'claude', '~/.local/bin/claude') as { ok: boolean } + expect(result.ok).toBe(true) + expect(await onDisk()).toMatchObject({ + manualToolPaths: { claude: join(homedir(), '.local/bin/claude') }, + }) + expect(syncDetected.fn).toHaveBeenCalledOnce() +}) + +it('rejects relative paths in setup:set-tool-path', async () => { + const result = await invoke('setup:set-tool-path', 'claude', 'local/bin/claude') as { ok: boolean; reason?: string } + expect(result.ok).toBe(false) + expect(result.reason).toContain('starting with / or ~/') +}) + +it('syncs provider enablement after setup:check', async () => { + await invoke('setup:check') + expect(syncDetected.fn).toHaveBeenCalledOnce() +}) diff --git a/src/main/ipc/setup.ts b/src/main/ipc/setup.ts index a77f0ce47..a2d164ed6 100644 --- a/src/main/ipc/setup.ts +++ b/src/main/ipc/setup.ts @@ -1,3 +1,6 @@ +import { homedir } from 'node:os' +import { join } from 'node:path' + import { ipcMain } from 'electron' import type { @@ -8,12 +11,20 @@ import type { import { classifyExecutable } from '@main/setup/binaryResolver.js' import { installWithHomebrew } from '@main/setup/homebrewInstaller.js' import { checkPrerequisites } from '@main/setup/prerequisites.js' +import { syncDetectedProvidersFromCheck } from '@main/setup/providerEnablement.js' import { markNoProvidersAcknowledged, markOptionalSkipped, setManualToolPath } from '@main/setup/setupState.js' import { refreshToolchainFromState } from '@main/setup/toolchain.js' export function registerSetupIpc(): void { ipcMain.handle('setup:check', async () => { - return await checkPrerequisites() + const check = await checkPrerequisites() + // Sync newly discovered CLIs into providerEnablement so PathPickerModal + // (⌘T) reflects installs immediately without an app restart (#1553). + // Best-effort: a secondary enablement sync failure must never fail setup. + await syncDetectedProvidersFromCheck(check).catch(err => { + console.warn('[setup] failed to sync provider enablement after check:', err) + }) + return check }) ipcMain.handle('setup:install', async (_evt, target: SetupInstallTarget) => { @@ -63,9 +74,18 @@ export function registerSetupIpc(): void { ipcMain.handle( 'setup:set-tool-path', async (_evt, tool: SetupToolId, rawPath: string): Promise => { - const candidate = rawPath.trim() + const trimmed = rawPath.trim() + // Expand leading `~` / `~/` to homedir() before absolute-path validation + // (#1553): users routinely paste `~/.local/bin/claude` or `~/.opencode/bin/opencode` + // from install docs, and rejecting tilde paths forces them to look up + // their full home directory manually. + const candidate = trimmed === '~' + ? homedir() + : trimmed.startsWith('~/') + ? join(homedir(), trimmed.slice(2)) + : trimmed if (!candidate.startsWith('/')) { - return { ok: false, reason: 'Enter an absolute path (starting with /).' } + return { ok: false, reason: 'Enter an absolute path (starting with / or ~/).' } } // classifyExecutable, not a bare X_OK check: POSIX access(dir, X_OK) // succeeds for any searchable directory, so `/usr/local/bin` used to @@ -88,7 +108,11 @@ export function registerSetupIpc(): void { } await setManualToolPath(tool, candidate) await refreshToolchainFromState() - return { ok: true, check: await checkPrerequisites() } + const check = await checkPrerequisites() + await syncDetectedProvidersFromCheck(check).catch(err => { + console.warn('[setup] failed to sync provider enablement after set-tool-path:', err) + }) + return { ok: true, check } }, ) } diff --git a/src/main/setup/providerEnablement.test.ts b/src/main/setup/providerEnablement.test.ts index ce5bcd4ac..04d62d372 100644 --- a/src/main/setup/providerEnablement.test.ts +++ b/src/main/setup/providerEnablement.test.ts @@ -172,3 +172,27 @@ it('never publishes a pending toggle through an overlapping read', async () => { expect(snapshot.entries.find(entry => entry.kind === 'claude')!.enabled).toBe(true) expect(enablement.getCachedProviderEnablement()!.entries.find(entry => entry.kind === 'claude')!.enabled).toBe(true) }) + +// #1553: when SetupGate discovers a newly installed CLI via setup:check or +// setup:set-tool-path, providerEnablement must update its cached detected set +// and broadcast `provider-enablement:changed` so PathPickerModal (⌘T) shows +// the new provider without an app restart. +it('updates cached detection and broadcasts when syncDetectedProvidersFromCheck sees new providers', async () => { + probe.checkPrerequisites.mockResolvedValue({ usableProviders: [] }) + const enablement = await import('./providerEnablement.js') + const initial = await enablement.getProviderEnablementSnapshot() + expect(initial.entries.find(entry => entry.kind === 'claude')).toMatchObject({ enabled: false, installed: false }) + + const broadcasts: boolean[] = [] + enablement.onProviderEnablementChanged(snapshot => { + broadcasts.push(snapshot.entries.find(entry => entry.kind === 'claude')!.enabled) + }) + + const synced = await enablement.syncDetectedProvidersFromCheck({ usableProviders: ['claude'] }) + expect(synced.entries.find(entry => entry.kind === 'claude')).toMatchObject({ enabled: true, installed: true }) + expect(broadcasts).toEqual([true]) + + // Re-syncing the identical detected set must not spam broadcasts. + await enablement.syncDetectedProvidersFromCheck({ usableProviders: ['claude'] }) + expect(broadcasts).toEqual([true]) +}) diff --git a/src/main/setup/providerEnablement.ts b/src/main/setup/providerEnablement.ts index 9ed58a715..d7fb26dc5 100644 --- a/src/main/setup/providerEnablement.ts +++ b/src/main/setup/providerEnablement.ts @@ -11,6 +11,7 @@ import { type ProviderEnablementSnapshot, } from '@shared/types/providerEnablement.js' import { checkPrerequisites } from '@main/setup/prerequisites.js' +import type { SetupCheckResult } from '@shared/types/setup.js' import { peekHermesConnectionService } from '@main/hermes/registry.js' import { invalidateUsageSnapshotCache } from '@main/usage/usageService.js' import { @@ -109,6 +110,43 @@ export async function refreshRemoteProviderDetection(): Promise { emit(await resolveAndCache()) } +function setsEqual(a: ReadonlySet, b: ReadonlySet): boolean { + if (a.size !== b.size) return false + for (const item of a) { + if (!b.has(item)) return false + } + return true +} + +/** + * Push a fresh `checkPrerequisites()` result into the cached detected set and + * broadcast `provider-enablement:changed` if the detected set changed. + * + * WHY this exists (#1553): `cachedDetected` is held for the process lifetime so + * picker opens don't re-run login-shell probes. Without this hook, installing a + * CLI or setting a manual path in SetupGate updated `setup.json` and the setup + * store, but `providerEnablement` kept serving its startup empty set until the + * user restarted the app — so `⌘T` (PathPickerModal) still hid the newly + * installed provider. Reusing the `checkPrerequisites()` result the setup IPC + * already computed avoids spawning a second wave of login-shell probes. + */ +export async function syncDetectedProvidersFromCheck( + result: Pick, +): Promise { + const nextDetected: ReadonlySet = new Set( + (result.usableProviders ?? []).filter(kind => AGENT_PROVIDER_KINDS.includes(kind)), + ) + const previousDetected = cachedDetected + cachedDetected = nextDetected + lastDetected = nextDetected + const snapshot = await resolveAndCache(async () => nextDetected) + if (!previousDetected || !setsEqual(previousDetected, nextDetected)) { + invalidateUsageSnapshotCache() + emit(snapshot) + } + return snapshot +} + /** Fail-open before the first resolve: hiding a user's providers because a * poll had not run yet is worse than briefly showing a provider that was * just disabled — and matches pre-#1102 behavior exactly. */ diff --git a/src/renderer/src/components/ui/dialog-actions.renderer.test.tsx b/src/renderer/src/components/ui/dialog-actions.renderer.test.tsx index 3b451cc95..5632d7af4 100644 --- a/src/renderer/src/components/ui/dialog-actions.renderer.test.tsx +++ b/src/renderer/src/components/ui/dialog-actions.renderer.test.tsx @@ -132,6 +132,10 @@ describe('focusedControlOwnsEnter', () => { // The dialog surface and ordinary containers do not: Enter there is the // dialog's to handle. expect(focusedControlOwnsEnter(document.createElement('div'))).toBe(false) + expect(focusedControlOwnsEnter(document.createElement('input'))).toBe(false) + const ownedInput = document.createElement('input') + ownedInput.setAttribute('data-owns-enter', '') + expect(focusedControlOwnsEnter(ownedInput)).toBe(true) expect(focusedControlOwnsEnter(null)).toBe(false) }) }) diff --git a/src/renderer/src/components/ui/dialog-actions.tsx b/src/renderer/src/components/ui/dialog-actions.tsx index 8f31d9063..af75db025 100644 --- a/src/renderer/src/components/ui/dialog-actions.tsx +++ b/src/renderer/src/components/ui/dialog-actions.tsx @@ -160,13 +160,19 @@ export function focusedControlOwnsEnter(target: EventTarget | null): boolean { // its own option list on several platforms, and the dialog-level listener // saw that Enter bubble up — Merge Project Tabs opens with focus on its // Keep select, so "Enter to choose the kept tab" MERGED the tabs at once. + // + // `data-owns-enter` (#1553): an inline sub-form input inside a larger dialog + // (such as SetupGate's manual path editor) owns its own Enter submission and + // must never confirm/close the enclosing dialog. Single-input dialogs like + // AgentTitlePrompt omit the attribute so Enter still confirms the dialog. // Every caller of this predicate only ever steps ASIDE when it returns // true, so widening it cannot make any handler act where it did not. return ( target.tagName === 'BUTTON' || target.tagName === 'A' || target.tagName === 'TEXTAREA' || - target.tagName === 'SELECT' + target.tagName === 'SELECT' || + target.hasAttribute('data-owns-enter') ) } diff --git a/src/renderer/src/features/path-picker/surfaces/PathPickerSurface.tsx b/src/renderer/src/features/path-picker/surfaces/PathPickerSurface.tsx index 396b809ad..21a64c5e6 100644 --- a/src/renderer/src/features/path-picker/surfaces/PathPickerSurface.tsx +++ b/src/renderer/src/features/path-picker/surfaces/PathPickerSurface.tsx @@ -78,6 +78,14 @@ export function PathPickerSurface() { [closePathPicker, workspace], ) + const onOpenTerminal = useCallback( + async (cwd: string) => { + await workspace.newTab(cwd, undefined, 'terminal') + closePathPicker() + }, + [closePathPicker, workspace], + ) + const onResume = useCallback( async (cwd: string, sessionId: string, provider: AgentProviderKind) => { // Resume reuses newTab's plumbing — same workspace entry, same @@ -122,6 +130,7 @@ export function PathPickerSurface() { defaultValue={defaultValue} onCancel={closePathPicker} onAccept={onAccept} + onOpenTerminal={onOpenTerminal} onResume={onResume} openTabsForPath={openTabsForPath} onActivateTab={onActivateTab} diff --git a/src/renderer/src/features/path-picker/ui/PathPickerModal.renderer.test.tsx b/src/renderer/src/features/path-picker/ui/PathPickerModal.renderer.test.tsx index 93532c357..beae4dfc2 100644 --- a/src/renderer/src/features/path-picker/ui/PathPickerModal.renderer.test.tsx +++ b/src/renderer/src/features/path-picker/ui/PathPickerModal.renderer.test.tsx @@ -5,6 +5,8 @@ import type { Conversation, ConversationListRequest, ConversationListResponse } import { PathPickerModal } from './PathPickerModal' import { MISSING_PROVIDER_HINT, resetSetupStoreForTests, useSetupStore } from '@renderer/features/setup/store' +import { useProviderEnablementStore } from '@renderer/features/providers/store' +import { AGENT_PROVIDER_KINDS } from '@shared/types/providerKind' import { loadFirstRunCheck } from '@shared/setup/firstRunRecordings.testSupport' const originalApiDescriptor = Object.getOwnPropertyDescriptor(window, 'api') @@ -297,3 +299,56 @@ describe('PathPickerModal keyboard', () => { }) }) +describe('PathPickerModal with zero enabled providers (#1553)', () => { + const originalEnablement = useProviderEnablementStore.getState() + afterEach(() => { + useProviderEnablementStore.setState(originalEnablement, true) + resetSetupStoreForTests() + }) + + function setZeroEnabledProviders(): void { + useProviderEnablementStore.getState().setSnapshot({ + entries: AGENT_PROVIDER_KINDS.map(kind => ({ + kind, + installed: false, + enabled: false, + because: 'detected' as const, + })), + opencodeUsageSource: 'none', + zaiCredentialPresent: false, + }) + } + + it('shows an inline Open Setup action and opens a Terminal instead of silently submitting Claude', async () => { + setZeroEnabledProviders() + const list = vi.fn(async () => response([])) + installApi(list) + const onAccept = vi.fn() + const onOpenTerminal = vi.fn() + const onCancel = vi.fn() + render( + , + ) + + expect(screen.getByText(/No agent providers are enabled/)).toBeInTheDocument() + expect(screen.getByRole('button', { name: 'Open Setup' })).toBeInTheDocument() + const confirm = screen.getByRole('button', { name: 'Open Terminal' }) + fireEvent.click(confirm) + await waitFor(() => expect(onOpenTerminal).toHaveBeenCalledWith('/repo')) + expect(onAccept).not.toHaveBeenCalled() + expect(list).not.toHaveBeenCalled() + + // Clicking Open Setup closes the picker and opens SetupGate. + fireEvent.click(screen.getByRole('button', { name: 'Open Setup' })) + expect(onCancel).toHaveBeenCalled() + expect(useSetupStore.getState().requested).toBe(true) + }) +}) + diff --git a/src/renderer/src/features/path-picker/ui/PathPickerModal.tsx b/src/renderer/src/features/path-picker/ui/PathPickerModal.tsx index ce04f8960..d22c8b772 100644 --- a/src/renderer/src/features/path-picker/ui/PathPickerModal.tsx +++ b/src/renderer/src/features/path-picker/ui/PathPickerModal.tsx @@ -3,7 +3,7 @@ import { EmptyState } from '@renderer/components/ui/empty-state' import { useEnabledAgentProviderKinds } from '@renderer/features/providers/store' import type { AgentProviderKind } from '@shared/types/providerKind' import { getRendererProviderCapabilities } from '@providers/registry.renderer.capabilities' -import { MISSING_PROVIDER_HINT, preferredPickerProvider, useMissingProviders } from '@renderer/features/setup/store' +import { MISSING_PROVIDER_HINT, preferredPickerProvider, useMissingProviders, useSetupStore } from '@renderer/features/setup/store' import { useEffect, useRef, useState } from 'react' import { Button } from '@renderer/components/ui/button' @@ -50,6 +50,12 @@ type Props = { /** Called when the user opens a brand-new session for `cwd`. * Now carries the selected provider so App knows which kind to spawn. */ onAccept: (expandedPath: string, provider: AgentProvider) => void | Promise + /** Called when no agent providers are enabled and the user opens a plain + * terminal tab for `cwd` instead (#1553). */ + onOpenTerminal?: (expandedPath: string) => void | Promise + /** Optional override for the inline "Open Setup" action shown when 0 + * providers are enabled. Defaults to closing the picker and opening Setup. */ + onOpenSetup?: () => void /** Called when the user picks a previous session to resume. */ onResume: ( expandedPath: string, @@ -90,6 +96,8 @@ export function PathPickerModal({ defaultValue = '', onCancel, onAccept, + onOpenTerminal, + onOpenSetup, onResume, openTabsForPath, onActivateTab, @@ -102,6 +110,7 @@ export function PathPickerModal({ // first one that is. It used to be Claude unconditionally, so on a Mac // without Claude, ⌘T failed only after the user had chosen a directory. const enabledKinds = useEnabledAgentProviderKinds() + const noEnabledProviders = enabledKinds.size === 0 // A disabled preselect would open the picker on a provider the user asked // to hide (#1102); fall back to the first enabled kind, then the default. const initialProvider = (): AgentProvider => { @@ -112,6 +121,15 @@ export function PathPickerModal({ const [provider, setProvider] = useState(initialProvider) const missingProviders = useMissingProviders() + // Keep the selected provider valid when `enabledKinds` updates live (e.g. + // after SetupGate discovers a newly installed CLI and broadcasts + // `provider-enablement:changed`, #1553). + useEffect(() => { + if (enabledKinds.size > 0 && !enabledKinds.has(provider)) { + setProvider(initialProvider()) + } + }, [enabledKinds, provider]) + // Resume list state. We eagerly refresh the list whenever the path // changes and resolves to a valid directory — gives the user live // feedback as they type (e.g. "ah, no recorded sessions in this @@ -203,6 +221,13 @@ export function PathPickerModal({ // that was just tab-completed into an existing directory. setPendingCreatePath(null) setResolvedPath(result.path) + if (noEnabledProviders) { + setSessions([]) + setListingTarget(null) + setListingError(null) + setSessionsLoading(false) + return + } try { // Scope 'cwd', not 'repository': this picker is about one typed // directory, and a worktree's sessions listed under the main checkout @@ -226,7 +251,7 @@ export function PathPickerModal({ } }, 150) return () => clearTimeout(t) - }, [value, open, provider]) + }, [value, open, provider, noEnabledProviders]) // Decided at submit time from the freshly expanded path, never from the // debounced `resolvedPath` the hint below renders: the user can press Enter @@ -259,6 +284,14 @@ export function PathPickerModal({ onActivateTab!(holder.tabId) return } + if (noEnabledProviders) { + // Never silently submit DEFAULT_PROVIDER ('claude') when the user + // has zero enabled providers (#1553): open a Terminal tab if the + // host supports it, otherwise do nothing and leave the Open Setup + // prompt visible. + if (onOpenTerminal) await onOpenTerminal(result.path) + return + } await onAccept(result.path, provider) return } @@ -266,6 +299,9 @@ export function PathPickerModal({ setError(result.error) return } + if (noEnabledProviders && !onOpenTerminal) { + return + } const created = await window.api.createDirectory(value) if (!created.ok) { setError(created.error) @@ -281,6 +317,10 @@ export function PathPickerModal({ setError(reValidated.error) return } + if (noEnabledProviders) { + await onOpenTerminal!(reValidated.path) + return + } await onAccept(reValidated.path, provider) } catch (err) { setError(err instanceof Error ? err.message : String(err)) @@ -339,35 +379,62 @@ export function PathPickerModal({
- {/* Provider toggle: one choice among providers, announced by - aria-pressed (it was colour only) with a keyboard focus ring. */} -
- {AGENT_PROVIDER_KINDS.filter(p => enabledKinds.has(p)).map(p => ( - - ))} -
+ Open Setup + +
+ ) : ( +
+ {AGENT_PROVIDER_KINDS.filter(p => enabledKinds.has(p)).map(p => ( + + ))} +
+ )}
@@ -435,13 +502,15 @@ export function PathPickerModal({ {/* Resume section — shows the most recent sessions recorded in the currently-typed cwd. Click a row to spawn with --resume. */} - + {!noEnabledProviders && ( + + )} {listingError && (
@@ -476,10 +545,12 @@ export function PathPickerModal({ confirmLabel={ preferred ? (preferred.current ? 'Stay Here' : 'Go to Tab') - : pendingCreatePath ? 'Create & Open' : 'New Session' + : noEnabledProviders + ? (pendingCreatePath ? 'Create & Open Terminal' : 'Open Terminal') + : (pendingCreatePath ? 'Create & Open' : 'New Session') } confirmOnEnter={false} - confirmDisabled={busy || (!preferred && value.trim() === '')} + confirmDisabled={busy || (!preferred && (value.trim() === '' || (noEnabledProviders && !onOpenTerminal)))} onConfirm={() => { if (preferred) onActivateTab?.(preferred.tabId) else void submit({ forceNewTab: true }) @@ -487,7 +558,7 @@ export function PathPickerModal({ onCancel={onCancel} cancelDisabled={busy} escapeCancels={!busy} - extraActions={preferred ? ( + extraActions={preferred && (!noEnabledProviders || onOpenTerminal) ? ( ) : null} {!isBundled && !tool.found && target && tool.installable ? ( @@ -416,12 +479,17 @@ function SetupRow({
setOverridePath(e.target.value)} onKeyDown={e => { - if (e.key === 'Enter' && overridePath.trim()) void submitOverride() + if (e.key === 'Enter') { + e.preventDefault() + e.stopPropagation() + if (overridePath.trim()) void submitOverride() + } }} - placeholder={`/absolute/path/to/${tool.id}`} + placeholder={`/absolute/path/to/${tool.id} or ~/…`} spellCheck={false} aria-label={`Path to ${tool.id}`} className="h-7 min-w-0 flex-1 text-[11px]" From 611fb24edca2308a04f9094a5d25b419ccb2bad8 Mon Sep 17 00:00:00 2001 From: Julius Olsson Date: Fri, 27 Nov 2026 15:55:37 -0800 Subject: [PATCH 4/4] fix(setup): guard check and detection races, keep mitmdump lazy, and tighten SetupGate Enter Refs #1553 Address PR review findings: - Add { force?: boolean } and monotonic checkGeneration to checkPrerequisites() so post-mutation callers never coalesce onto a stale pre-mutation check and older checks cannot clobber newer write-backs or toolchain state. - Add monotonic detectionGeneration guard in providerEnablement.ts so an older in-flight detectInstalledKinds() cannot overwrite a newer syncDetectedProvidersFromCheck(). - Keep mitmdump on lazy isBundledArchiveAvailable so fresh startup does not block on extracting an 87 MB tarball, while continuing to probe bare-binary opencode via resolveBundledTool. - Guard SetupGate manual path Enter with busy === null and hide DialogActions' Enter key chip while editing a path. --- ...26-11-27-fresh-user-setup-and-bootstrap.md | 9 ++ src/main/ipc/setup.ts | 8 +- src/main/setup/homebrewInstaller.ts | 2 +- src/main/setup/prerequisites.test.ts | 51 ++++++++++-- src/main/setup/prerequisites.ts | 82 ++++++++++++------- src/main/setup/providerEnablement.test.ts | 25 ++++++ src/main/setup/providerEnablement.ts | 32 ++++++-- .../src/features/setup/ui/SetupGate.tsx | 4 +- 8 files changed, 163 insertions(+), 50 deletions(-) diff --git a/docs/plans/2026-11-27-fresh-user-setup-and-bootstrap.md b/docs/plans/2026-11-27-fresh-user-setup-and-bootstrap.md index 64b82c891..a274bde0a 100644 --- a/docs/plans/2026-11-27-fresh-user-setup-and-bootstrap.md +++ b/docs/plans/2026-11-27-fresh-user-setup-and-bootstrap.md @@ -59,3 +59,12 @@ Fresh-user setup, binary detection, and provider enablement have several interlo - `src/renderer/src/features/setup/firstRun.renderer.test.tsx` - `src/renderer/src/features/path-picker/ui/PathPickerModal.renderer.test.tsx` - Run `npm run typecheck` and targeted `vitest` suites in the worktree. + +## Review Disposition + +| Finding | Severity | Disposition | +| --- | --- | --- | +| Post-mutation callers (`setup:set-tool-path`, `setup:skip-optional`, `setup:acknowledge-no-providers`, `setup:install`) could coalesce onto a stale pre-mutation `inFlightCheck`, or an older check could clobber a newer write-back | Blocking | Fixed: added `checkPrerequisites({ force?: boolean })`, monotonic `checkGeneration` guard around `updateToolPaths` / `refreshToolchainFromState`, identity-checked `finally`, and `force: true` at all post-mutation callers. | +| Older in-flight `detectInstalledKinds()` could overwrite a newer `syncDetectedProvidersFromCheck()` in `providerEnablement.ts` | Blocking | Fixed: added monotonic `detectionGeneration` counter and identity-checked `inFlightDetection` cleanup; added regression test. | +| Calling `resolveBundledTool('mitmdump')` during `checkPrerequisites()` eagerly extracted an 87 MB tarball on fresh startup | Non-blocking | Fixed: kept `mitmdump` on lazy `isBundledArchiveAvailable` while probing bare-binary `opencode` via `resolveBundledTool`. | +| `SetupGate` Enter handler in manual path input did not guard `busy === null`, and `DialogActions` still showed the `↩` chip while editing a path | Non-blocking | Fixed: guarded Enter submit with `busy === null && overridePath.trim()` and set `confirmKey={mustAnswer || editingTools.size > 0 ? null : 'Enter'}`. | diff --git a/src/main/ipc/setup.ts b/src/main/ipc/setup.ts index a2d164ed6..1c32ded58 100644 --- a/src/main/ipc/setup.ts +++ b/src/main/ipc/setup.ts @@ -38,7 +38,7 @@ export function registerSetupIpc(): void { ok: false, target, output: `Unknown setup install target: ${String(target)}`, - check: await checkPrerequisites(), + check: await checkPrerequisites({ force: true }), } } return await installWithHomebrew(target) @@ -46,7 +46,7 @@ export function registerSetupIpc(): void { ipcMain.handle('setup:skip-optional', async (_evt, tool: SetupToolId) => { await markOptionalSkipped(tool, true) - return await checkPrerequisites() + return await checkPrerequisites({ force: true }) }) // The first-run answer "continue without a provider" (#995). Durable for the @@ -54,7 +54,7 @@ export function registerSetupIpc(): void { // launch, and in every new window, for a user who has already answered it. ipcMain.handle('setup:acknowledge-no-providers', async () => { await markNoProvidersAcknowledged() - return await checkPrerequisites() + return await checkPrerequisites({ force: true }) }) // Escape hatch for #495 A1: automatic resolution is a probe, and a @@ -108,7 +108,7 @@ export function registerSetupIpc(): void { } await setManualToolPath(tool, candidate) await refreshToolchainFromState() - const check = await checkPrerequisites() + const check = await checkPrerequisites({ force: true }) await syncDetectedProvidersFromCheck(check).catch(err => { console.warn('[setup] failed to sync provider enablement after set-tool-path:', err) }) diff --git a/src/main/setup/homebrewInstaller.ts b/src/main/setup/homebrewInstaller.ts index 0ab93cd25..7bcbd62d3 100644 --- a/src/main/setup/homebrewInstaller.ts +++ b/src/main/setup/homebrewInstaller.ts @@ -42,6 +42,6 @@ export async function installWithHomebrew( ok, target, output, - check: await checkPrerequisites(), + check: await checkPrerequisites({ force: true }), } } diff --git a/src/main/setup/prerequisites.test.ts b/src/main/setup/prerequisites.test.ts index e4a18b837..8bf8760e1 100644 --- a/src/main/setup/prerequisites.test.ts +++ b/src/main/setup/prerequisites.test.ts @@ -82,9 +82,11 @@ it('launches the persisted probe when the write-back lands', async () => { expect(getToolPath('codex', '')).toBe('/fresh/codex') }) -// #1553: bundled tools must only report `source: 'bundled'` when -// `resolveBundledTool` succeeds, not merely when an archive exists on disk. -it('falls back to system/missing when resolveBundledTool returns null even if archive exists', async () => { +// #1553: bundled opencode (bare binary) must only report `source: 'bundled'` +// when `resolveBundledTool` succeeds, not merely when an archive exists on +// disk. mitmdump (87 MB tarball) stays lazy on `isBundledArchiveAvailable` so +// startup does not block on extraction. +it('falls back to system for opencode when resolveBundledTool returns null, while keeping mitmdump lazy', async () => { runtimeTools.isBundledArchiveAvailable.mockResolvedValue(true) runtimeTools.resolveBundledTool.mockResolvedValue(null) resolver.resolveToolPath.mockImplementation(async (tool: string) => @@ -98,9 +100,8 @@ it('falls back to system/missing when resolveBundledTool returns null even if ar source: 'system', }) expect(check.tools.mitmdump).toMatchObject({ - found: false, - path: null, - source: undefined, + found: true, + source: 'bundled', }) }) @@ -147,3 +148,41 @@ it('deduplicates concurrent in-flight checkPrerequisites() calls', async () => { const brewCallsAfter = resolver.resolveToolPath.mock.calls.filter(([tool]) => tool === 'brew') expect(brewCallsAfter).toHaveLength(2) }) + +it('force: true bypasses in-flight deduplication and prevents the older check from clobbering newer state', async () => { + let releaseFirstBrew!: () => void + const firstBrewGate = new Promise(resolve => { releaseFirstBrew = resolve }) + let brewInvocation = 0 + resolver.resolveToolPath.mockImplementation(async (tool: string) => { + if (tool === 'brew') { + brewInvocation += 1 + if (brewInvocation === 1) await firstBrewGate + return '/opt/homebrew/bin/brew' + } + if (tool === 'codex') { + return brewInvocation === 1 ? '/stale/codex' : '/newer/codex' + } + return null + }) + resolver.isExecutable.mockImplementation(async (path: string) => + path === '/stale/codex' || path === '/newer/codex', + ) + + const { checkPrerequisites } = await import('./prerequisites.js') + const { getToolPath } = await import('./toolchain.js') + + const staleCheck = checkPrerequisites() + // A post-mutation check forces a fresh run while `staleCheck` is still parked. + const freshCheck = checkPrerequisites({ force: true }) + expect(freshCheck).not.toBe(staleCheck) + + const fresh = await freshCheck + expect(fresh.tools.codex).toMatchObject({ found: true, path: '/newer/codex' }) + expect(getToolPath('codex', '')).toBe('/newer/codex') + + // Now let the older check finish; it must NOT overwrite disk or toolchain. + releaseFirstBrew() + await staleCheck + expect(JSON.parse(await readFile(join(dir, 'setup.json'), 'utf8')).toolPaths.codex).toBe('/newer/codex') + expect(getToolPath('codex', '')).toBe('/newer/codex') +}) diff --git a/src/main/setup/prerequisites.ts b/src/main/setup/prerequisites.ts index cf6e1ee64..a8359eb0b 100644 --- a/src/main/setup/prerequisites.ts +++ b/src/main/setup/prerequisites.ts @@ -4,7 +4,7 @@ import type { SetupToolStatus, } from '@shared/types/setup.js' import { isExecutable, resolveToolPath } from '@main/setup/binaryResolver.js' -import { resolveBundledTool } from '@main/setup/runtimeTools.js' +import { isBundledArchiveAvailable, resolveBundledTool } from '@main/setup/runtimeTools.js' import type { BundledToolId } from '@main/setup/runtimeTools.js' import { loadSetupState, updateToolPaths } from '@main/setup/setupState.js' import { listProviderSetupDescriptors } from '@providers/registry.setup.js' @@ -97,19 +97,30 @@ const CHECK_ORDER: SetupToolId[] = ['brew', ...LOCAL_PROVIDER_KINDS, 'git', 'mit // SetupGate (`setup:check`) and providerEnablement (`provider-enablement:get`) // both call `checkPrerequisites()` at the same time; without sharing the // in-flight promise, startup spawns 2x CHECK_ORDER.length (~16) parallel login -// shells simultaneously. Cleared in `finally` so every subsequent explicit -// Retry runs a fresh probe. +// shells simultaneously. +// +// WHY `{ force?: boolean }` + `checkGeneration`: +// Post-mutation callers (`setup:set-tool-path`, `setup:skip-optional`, +// `setup:acknowledge-no-providers`, `setup:install`) MUST NOT coalesce onto +// an older in-flight check that read `setup.json` BEFORE the mutation landed. +// Passing `force: true` starts a new generation; `finally` only clears +// `inFlightCheck` if it still points at THIS promise, and the write-back / +// toolchain refresh is gated on `generation === checkGeneration` so an older +// check finishing last can never clobber a newer check's tool paths. let inFlightCheck: Promise | null = null +let checkGeneration = 0 -export function checkPrerequisites(): Promise { - if (inFlightCheck) return inFlightCheck - inFlightCheck = runCheckPrerequisites().finally(() => { - inFlightCheck = null +export function checkPrerequisites(options?: { force?: boolean }): Promise { + if (!options?.force && inFlightCheck) return inFlightCheck + const generation = ++checkGeneration + const current = runCheckPrerequisites(generation).finally(() => { + if (inFlightCheck === current) inFlightCheck = null }) - return inFlightCheck + inFlightCheck = current + return current } -async function runCheckPrerequisites(): Promise { +async function runCheckPrerequisites(generation: number): Promise { const state = await loadSetupState() const brewPath = await resolveToolPath('brew') const entries = await Promise.all( @@ -150,16 +161,18 @@ async function runCheckPrerequisites(): Promise { const persisted = state.toolPaths[tool] if (persisted && (await isExecutable(persisted))) systemPath = persisted } - // WHY `resolveBundledTool` instead of `isBundledArchiveAvailable` (#1553): - // `isBundledArchiveAvailable` only checks whether the file/archive - // exists on disk, NOT whether the OS will actually execute it. On a - // noexec mount, Gatekeeper stall, or broken extraction, `resolveBundledTool` - // returns null at spawn time while `isBundledArchiveAvailable` still - // returned true — causing SetupGate to report "Bundled" (hiding the - // manual override and install options) and bootstrap to pick a broken - // provider. Probing through `resolveBundledTool` ensures "Bundled" only - // appears when the bundled binary is genuinely runnable; otherwise we - // fall back cleanly to `systemPath` or show the install/manual options. + // WHY `opencode` uses `resolveBundledTool` while `mitmdump` stays on + // `isBundledArchiveAvailable` (#1553): + // - `opencode` is a single unpacked Mach-O binary: probing it through + // `resolveBundledTool` is fast (and success-cached), and proves the + // OS will actually execute it. On a noexec mount or Gatekeeper block, + // `isBundledArchiveAvailable` falsely reported "Bundled", hiding + // manual override / install options and causing first-run bootstrap + // to pick a broken provider. + // - `mitmdump` is an ~87 MB `.tar.gz` archive extracted lazily on first + // proxy use; calling `resolveBundledTool('mitmdump')` here would + // block every fresh startup on extracting 87 MB before SetupGate + // even renders. // // WHY `!hasValidManual` gates bundled precedence: // Matches `toolchain.ts`: a valid manual override beats the bundled @@ -168,7 +181,9 @@ async function runCheckPrerequisites(): Promise { const bundled = !hasValidManual && BUNDLED_TOOL_IDS.has(tool) && - Boolean(await resolveBundledTool(tool as BundledToolId)) + (tool === 'opencode' + ? Boolean(await resolveBundledTool('opencode')) + : await isBundledArchiveAvailable(tool as BundledToolId)) const found = bundled || Boolean(systemPath) const status: SetupToolStatus = { ...TOOL_META[tool], @@ -197,17 +212,24 @@ async function runCheckPrerequisites(): Promise { // persisted (#1403 recheck a), so "found at X" is also what a launch uses. // The cost: the next launch starts from the last persisted paths until a // check's write-back lands. - const probed = Object.fromEntries( - entries.map(([tool, status]) => [tool, status.path]), - ) as Partial> - let unsaved: typeof probed | undefined - try { - await updateToolPaths(probed) - } catch (error) { - console.warn('[setup] could not persist probed tool paths:', (error as NodeJS.ErrnoException).code ?? 'error') - unsaved = probed + // Guard write-back + toolchain refresh by generation: if a newer `force: true` + // check started after a setup mutation (e.g. `setup:set-tool-path`), this + // older check must not overwrite `toolPaths` or `toolchain` with stale data. + if (generation === checkGeneration) { + const probed = Object.fromEntries( + entries.map(([tool, status]) => [tool, status.path]), + ) as Partial> + let unsaved: typeof probed | undefined + try { + await updateToolPaths(probed) + } catch (error) { + console.warn('[setup] could not persist probed tool paths:', (error as NodeJS.ErrnoException).code ?? 'error') + unsaved = probed + } + if (generation === checkGeneration) { + await refreshToolchainFromState(unsaved) + } } - await refreshToolchainFromState(unsaved) // No `ready`/`blocking` any more (#995): nothing blocks launch. The policy // that replaced them is in readiness.ts, and it runs here so every diff --git a/src/main/setup/providerEnablement.test.ts b/src/main/setup/providerEnablement.test.ts index 04d62d372..d884ef04d 100644 --- a/src/main/setup/providerEnablement.test.ts +++ b/src/main/setup/providerEnablement.test.ts @@ -196,3 +196,28 @@ it('updates cached detection and broadcasts when syncDetectedProvidersFromCheck await enablement.syncDetectedProvidersFromCheck({ usableProviders: ['claude'] }) expect(broadcasts).toEqual([true]) }) + +it('never lets an older in-flight detectInstalledKinds overwrite a newer syncDetectedProvidersFromCheck', async () => { + let releaseStaleProbe!: (value: { usableProviders: string[] }) => void + probe.checkPrerequisites.mockImplementationOnce( + () => new Promise(resolve => { releaseStaleProbe = resolve }), + ) + const enablement = await import('./providerEnablement.js') + + // Kick off initial detection (stays in flight). + const initialPromise = enablement.getProviderEnablementSnapshot() + await vi.waitFor(() => expect(releaseStaleProbe).toBeTypeOf('function')) + + // Meanwhile Setup discovers Claude and syncs it. + await enablement.syncDetectedProvidersFromCheck({ usableProviders: ['claude'] }) + + // Now the older probe finishes with an empty set; it must NOT overwrite Claude. + releaseStaleProbe({ usableProviders: [] }) + await initialPromise + + const snapshot = await enablement.getProviderEnablementSnapshot() + expect(snapshot.entries.find(entry => entry.kind === 'claude')).toMatchObject({ + enabled: true, + installed: true, + }) +}) diff --git a/src/main/setup/providerEnablement.ts b/src/main/setup/providerEnablement.ts index d7fb26dc5..2d03d1731 100644 --- a/src/main/setup/providerEnablement.ts +++ b/src/main/setup/providerEnablement.ts @@ -33,28 +33,40 @@ let cachedSnapshot: ProviderEnablementSnapshot | null = null // `cachedDetected` to force a fresh probe). It is what a saved change is // shown against when the fresh probe fails; see `mutate`. let lastDetected: ReadonlySet | null = null +// Monotonic generation counter for `cachedDetected` / `lastDetected` (#1553): +// an older in-flight `detectInstalledKinds()` resolving after a newer +// `syncDetectedProvidersFromCheck()` or `resetProviderEnablement()` must never +// overwrite the fresher detected set. +let detectionGeneration = 0 function detectInstalledKinds(): Promise> { if (cachedDetected) return Promise.resolve(cachedDetected) if (inFlightDetection) return inFlightDetection - inFlightDetection = checkPrerequisites() + const generation = ++detectionGeneration + const current = checkPrerequisites() .then(result => { // usableProviders is the exact resolution the first-run SetupGate uses // (manual override → PATH probe → bundled archive), so Settings → // Providers and the gate can never disagree about "installed". - cachedDetected = new Set( + const next = new Set( (result.usableProviders ?? []).filter(kind => AGENT_PROVIDER_KINDS.includes(kind)), ) - lastDetected = cachedDetected - return cachedDetected + if (generation !== detectionGeneration) { + return cachedDetected ?? next + } + cachedDetected = next + lastDetected = next + return next }) // WHY in `finally` (#1403 review): cleared only on success, a rejected // probe stayed in flight forever, so every later resolve returned the - // same rejection until restart. + // same rejection until restart. Guarded by identity so an older probe + // cannot clear a newer probe's in-flight slot. .finally(() => { - inFlightDetection = null + if (inFlightDetection === current) inFlightDetection = null }) - return inFlightDetection + inFlightDetection = current + return current } // WHY refreshes are ordered (#1403 verification a): a refresh reads setup @@ -137,6 +149,10 @@ export async function syncDetectedProvidersFromCheck( (result.usableProviders ?? []).filter(kind => AGENT_PROVIDER_KINDS.includes(kind)), ) const previousDetected = cachedDetected + // Advance the generation so any older in-flight `detectInstalledKinds()` + // cannot clobber this fresher detection when it settles later. + detectionGeneration += 1 + inFlightDetection = null cachedDetected = nextDetected lastDetected = nextDetected const snapshot = await resolveAndCache(async () => nextDetected) @@ -209,6 +225,8 @@ export async function resetProviderEnablement( // Reset must also redo detection: "installed" is the display hint on the // settings row, and a stale cached detection would keep showing the state // from before any install that happened while the app was closed. + detectionGeneration += 1 + inFlightDetection = null cachedDetected = null return await mutate(() => setProviderEnablementOverride(kind, null)) } diff --git a/src/renderer/src/features/setup/ui/SetupGate.tsx b/src/renderer/src/features/setup/ui/SetupGate.tsx index 9e36fd796..6b418efc8 100644 --- a/src/renderer/src/features/setup/ui/SetupGate.tsx +++ b/src/renderer/src/features/setup/ui/SetupGate.tsx @@ -317,7 +317,7 @@ export function SetupGate() { dead. Guards carried over (k3): both buttons wait while busy. */} 0 ? null : 'Enter'} confirmOnEnter={editingTools.size === 0} confirmDisabled={busy !== null} onConfirm={() => void continueOn()} @@ -486,7 +486,7 @@ function SetupRow({ if (e.key === 'Enter') { e.preventDefault() e.stopPropagation() - if (overridePath.trim()) void submitOverride() + if (busy === null && overridePath.trim()) void submitOverride() } }} placeholder={`/absolute/path/to/${tool.id} or ~/…`}