Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions docs/plans/2026-11-27-fresh-user-setup-and-bootstrap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# 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 `<Input>` 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.

## 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'}`. |
33 changes: 31 additions & 2 deletions src/main/ipc/setup.test.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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[] }))
Expand All @@ -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')
Expand Down Expand Up @@ -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()
})
38 changes: 31 additions & 7 deletions src/main/ipc/setup.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { homedir } from 'node:os'
import { join } from 'node:path'

import { ipcMain } from 'electron'

import type {
Expand All @@ -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) => {
Expand All @@ -27,23 +38,23 @@ 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)
})

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
// same reason a skipped helper is: otherwise the panel reopens on every
// 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
Expand All @@ -63,9 +74,18 @@ export function registerSetupIpc(): void {
ipcMain.handle(
'setup:set-tool-path',
async (_evt, tool: SetupToolId, rawPath: string): Promise<SetupSetToolPathResult> => {
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
Expand All @@ -88,7 +108,11 @@ export function registerSetupIpc(): void {
}
await setManualToolPath(tool, candidate)
await refreshToolchainFromState()
return { ok: true, 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)
})
return { ok: true, check }
},
)
}
67 changes: 67 additions & 0 deletions src/main/setup/binaryResolver.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof import('os')>()
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<void> {
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)
})
})
Loading
Loading