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
6 changes: 3 additions & 3 deletions electron-ui/electron/lib/api-spawn.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const fs = require('fs')
const http = require('http')
const net = require('net')

function createApiSpawn({ paths, llmConfig, state }) {
function createApiSpawn({ paths, llmConfig, state, spawnProcess = spawn }) {
const {
ROOT,
DATA_DIR,
Expand Down Expand Up @@ -47,7 +47,7 @@ function createApiSpawn({ paths, llmConfig, state }) {
// same paths whether Electron was launched from Finder, a shell, or a DMG.
function spawnHidden(cmd, args, opts = {}) {
const { env: envExtra, ...rest } = opts
return spawn(cmd, args, {
return spawnProcess(cmd, args, {
windowsHide: true,
...rest,
env: buildPythonEnv(envExtra),
Expand All @@ -62,7 +62,7 @@ function createApiSpawn({ paths, llmConfig, state }) {
let out = '', err = ''
proc.stdout.on('data', d => { out += d.toString() })
proc.stderr.on('data', d => { err += d.toString() })
proc.on('exit', code => resolve({ code: code === null ? 1 : code, stdout: out.trim(), stderr: err.trim() }))
proc.on('close', code => resolve({ code: code === null ? 1 : code, stdout: out.trim(), stderr: err.trim() }))
proc.on('error', e => resolve({ code: 1, stdout: '', stderr: e.message }))
})
}
Expand Down
82 changes: 82 additions & 0 deletions electron-ui/electron/lib/api-spawn.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@

const { test } = require('node:test')
const assert = require('node:assert/strict')
const { EventEmitter } = require('node:events')
const { createApiSpawn } = require('./api-spawn')

function makeFakeProcess() {
const child = new EventEmitter()
child.stdout = new EventEmitter()
child.stderr = new EventEmitter()
return child
}

function makeApi(child) {
return createApiSpawn({
paths: {
ROOT: process.cwd(),
DATA_DIR: process.cwd(),
PATH_HINTS: [],
},
llmConfig: {},
state: {},
spawnProcess: () => child,
})
}

test('runCommand waits for close after exit and late stdout', async () => {
const child = makeFakeProcess()
const api = makeApi(child)

let finished = false
const resultPromise = api.runCommand('python3', ['--version'])
resultPromise.then(() => { finished = true })

// The process exits before all stdout data is delivered.
child.emit('exit', 0)
await Promise.resolve()

assert.equal(finished, false,
'runCommand resolved on exit before stdout was collected')

child.stdout.emit('data', Buffer.from('Python 3.13.5\n'))
child.emit('close', 0)

const result = await resultPromise
assert.deepEqual(result, {
code: 0,
stdout: 'Python 3.13.5',
stderr: '',
})
})

test('runCommand preserves exit code and stderr', async () => {
const child = makeFakeProcess()
const api = makeApi(child)

const resultPromise = api.runCommand('python3', ['--version'])

child.emit('exit', 2)
child.stderr.emit('data', Buffer.from('version check failed\n'))
child.emit('close', 2)

assert.deepEqual(await resultPromise, {
code: 2,
stdout: '',
stderr: 'version check failed',
})
})

test('runCommand handles a spawn error', async () => {
const child = makeFakeProcess()
const api = makeApi(child)

const resultPromise = api.runCommand('python3', ['--version'])

child.emit('error', new Error('ENOENT'))
child.emit('close', -2)

const result = await resultPromise
assert.equal(result.code, 1)
assert.match(result.stderr, /ENOENT/)
})
184 changes: 184 additions & 0 deletions electron-ui/electron/lib/setup-diagnostics.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
const { test } = require('node:test')
const assert = require('node:assert/strict')
const { createSetup } = require('./setup')
const fs = require('node:fs')
const os = require('node:os')
const path = require('node:path')

// These tests exercise the public setup flow rather than private logging helpers.
// They simulate commands: no Python or package-manager install is performed.
async function scenario({ platform = 'linux', commandResult, existingPaths = [] }) {
const oldPlatform = process.platform
const oldPath = process.env.PATH
const originalExistsSync = fs.existsSync
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'clippy-python-diagnostics-'))
const calls = []
const messages = []
let pythonDone = false
try {
Object.defineProperty(process, 'platform', { configurable: true, value: platform })
fs.existsSync = (candidate) => existingPaths.includes(String(candidate)) || originalExistsSync(candidate)
const state = {
doneSoFar: 0,
setupWindow: {
isDestroyed: () => false,
webContents: {
send: (channel, payload) => {
messages.push({ channel, payload })
if (channel === 'step-update' && payload.key === 'python' && payload.state === 'done') {
pythonDone = true
// Stop after Python verification; do not enter package installation.
throw new Error('STOP_AFTER_PYTHON_VERIFIED')
}
},
},
},
}
const api = {
runCommand: async (command, args) => {
calls.push({ command, args })
return commandResult(command, args, calls.length)
},
}
const setup = createSetup({
paths: {
ROOT: dir, DATA_DIR: dir, USER_DATA: dir,
SYSTEM_PYTHON_COMMAND: 'python3', PYTHON_COMMAND: 'python3',
OLLAMA_COMMAND: 'ollama',
},
llmConfig: { usesManagedOllama: () => false },
api, state,
})
await setup.runSetup('python')
return {
calls, messages, pythonDone,
logs: messages.filter(m => m.channel === 'setup-log').map(m => String(m.payload.line)),
steps: messages.filter(m => m.channel === 'step-update').map(m => m.payload),
}
} finally {
fs.existsSync = originalExistsSync
Object.defineProperty(process, 'platform', { configurable: true, value: oldPlatform })
process.env.PATH = oldPath
fs.rmSync(dir, { recursive: true, force: true })
}
}

const result = (code, stdout = '', stderr = '') => ({ code, stdout, stderr })

function assertCommandLogged(run, command) {
assert.ok(run.logs.some(line => line.includes(command) && line.includes('--version')),
`Expected executable ${command} in logs; got ${JSON.stringify(run.logs)}`)
}

function assertDiagnostic(run, { code, stderr }) {
assert.ok(run.logs.some(line => {
const matchCode = new RegExp(`(?:exit|code)\\s*[:=]\\s*${code}(?!\\d)`, 'i').test(line)
const hasStderr = /stderr/i.test(line) && (stderr ? line.includes(stderr) : /stderr\s*[:=]\s*["']{2}/i.test(line))
return matchCode && hasStderr
}), `Expected diagnostic with code ${code} and stderr ${JSON.stringify(stderr)}; got ${JSON.stringify(run.logs)}`)
}

function assertInstallAttempt(run, packageManager) {
assert.ok(run.calls.some(c => c.command === packageManager && c.args[0] === 'install'),
`Expected ${packageManager} install attempt`)
}

test('failed initial probe identifies actual executable, exit code and stderr', async () => {
const run = await scenario({ commandResult: () => result(127, '', 'ENOENT: python3 missing') })
assertCommandLogged(run, 'python3')
assertDiagnostic(run, { code: 127, stderr: 'ENOENT: python3 missing' })
assert.ok(run.steps.some(s => s.key === 'python' && s.state === 'error'))
})

test('unsupported Python version reports exit status even when command succeeds', async () => {
const run = await scenario({ commandResult: () => result(0, 'Python 3.10.9', '') })
assertCommandLogged(run, 'python3')
assertDiagnostic(run, { code: 0, stderr: '' })
assert.ok(run.steps.some(s => s.key === 'python' && s.state === 'error'))
})

test('Homebrew post-install probe failure includes diagnostics', async () => {
let probes = 0
const run = await scenario({
platform: 'darwin',
commandResult: (cmd, args) => {
if (cmd === 'brew') return result(0, 'brew ready')
if (cmd === 'python3') return ++probes === 1
? result(127, '', 'before install')
: result(4, '', 'after install failure')
return result(4, '', 'after install failure')
},
})
assertInstallAttempt(run, 'brew')
assertDiagnostic(run, { code: 4, stderr: 'after install failure' })
})

test('winget post-install probe failure includes diagnostics', async () => {
let probes = 0
const run = await scenario({
platform: 'win32',
commandResult: (cmd) => {
if (cmd === 'winget') return result(0, 'installed')
if (cmd === 'python3') return ++probes === 1
? result(127, '', 'before install')
: result(4, '', 'after install failure')
return result(4, '', 'after install failure')
},
})
assertInstallAttempt(run, 'winget')
assertDiagnostic(run, { code: 4, stderr: 'after install failure' })
})

test('Homebrew post-install rejects unsupported Python and logs status', async () => {
let installed = false
const run = await scenario({
platform: 'darwin',
commandResult: (cmd, args) => {
if (cmd === 'brew') {
if (args[0] === 'install') installed = true
return result(0, 'ok')
}
return installed ? result(0, 'Python 3.10.9') : result(127, '', 'missing')
},
})
assertInstallAttempt(run, 'brew')
assertDiagnostic(run, { code: 0, stderr: '' })
assert.ok(run.steps.some(s => s.key === 'python' && s.state === 'error'))
})

test('winget post-install rejects unsupported Python and logs status', async () => {
let probes = 0
const run = await scenario({
platform: 'win32',
commandResult: (cmd) => cmd === 'winget' ? result(0, 'ok')
: cmd === 'python3' && ++probes === 1 ? result(127, '', 'missing') : result(0, 'Python 3.10.9'),
})
assertInstallAttempt(run, 'winget')
assertDiagnostic(run, { code: 0, stderr: '' })
assert.ok(run.steps.some(s => s.key === 'python' && s.state === 'error'))
})

test('fallback logs both attempted executables and accepts valid Python', async () => {
// A mocked known installation path avoids depending on the host OS.
const alternate = '/usr/bin/python3'
const run = await scenario({
existingPaths: [alternate],
commandResult: (cmd) => cmd === alternate
? result(0, 'Python 3.13.5') : result(127, '', 'python3 command missing'),
})
assertCommandLogged(run, 'python3')
assertCommandLogged(run, alternate)
assertDiagnostic(run, { code: 127, stderr: 'python3 command missing' })
assert.ok(run.calls.some(c => c.command === alternate))
assert.equal(run.pythonDone, true)
assert.equal(run.calls.some(c => ['winget', 'brew'].includes(c.command)), false)
})

test('valid Python completes the Python step without trying an installer', async () => {
const run = await scenario({ commandResult: () => result(0, 'Python 3.13.5') })
assert.equal(run.pythonDone, true)
assert.ok(run.steps.some(s => s.key === 'python' && s.state === 'done'))
assert.equal(run.calls.length, 1)
assert.equal(run.calls[0].command, 'python3')
assert.equal(run.logs.some(line => /Python detection.*(?:exit|code)/i.test(line)), false)
})
34 changes: 28 additions & 6 deletions electron-ui/electron/lib/setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -611,16 +611,21 @@ function createSetup({ paths, llmConfig, api, state, app, windowBridge, onLaunch
if (merged) process.env.PATH = merged
}

async function verifyWithKnownPaths(command, extraCandidates, args = ['--version']) {
let result = await runCommand(command, args)
async function verifyWithKnownPaths(command, extraCandidates, args = ['--version'], onAttempt = null) {
const run = async (executable) => {
const result = await runCommand(executable, args)
if (onAttempt) onAttempt(executable, args, result)
return result
}
let result = await run(command)
if (result.code === 0) return result
for (const candidate of extraCandidates || []) {
if (!candidate) continue
try {
if (!fs.existsSync(candidate)) continue
} catch (_) { continue }
addDirToPath(path.dirname(candidate))
result = await runCommand(candidate, args)
result = await run(candidate)
if (result.code === 0) return result
}
return result
Expand Down Expand Up @@ -653,7 +658,7 @@ function createSetup({ paths, llmConfig, api, state, app, windowBridge, onLaunch
if (process.platform === 'win32') await refreshWindowsPathFromRegistry()
const extra = runtimePythonPaths()
extra.forEach((candidate) => addDirToPath(path.dirname(candidate)))
return verifyWithKnownPaths(systemPythonCommand(), extra)
return verifyWithKnownPaths(systemPythonCommand(), extra, ['--version'], logPythonAttempt)
}

function acceptPythonVersion(raw) {
Expand All @@ -669,17 +674,32 @@ function createSetup({ paths, llmConfig, api, state, app, windowBridge, onLaunch
return false
}

function logPythonFailure(result) {
log(
`Python detection: exit=${result.code}, ` +
`stderr=${JSON.stringify(result.stderr || '')}`,
'err'
)
}

function logPythonAttempt(command, args, result) {
log(`> ${[command, ...args].join(' ')}`, 'dim')
if (result.code !== 0 || !String(result.stdout || result.stderr || '').trim()) {
logPythonFailure(result)
}
}

async function stepCheckPython() {
// Windows installs a missing Python with winget. macOS uses Homebrew
// when Homebrew is already installed. Linux stays a manual install.
stepUpdate('python', 'running', 'Checking for Python 3.11+...')
log('> python --version', 'dim')

const found = await verifyWithKnownPaths(systemPythonCommand(), runtimePythonPaths())
const found = await verifyWithKnownPaths(systemPythonCommand(), runtimePythonPaths(), ['--version'], logPythonAttempt)
const version = found.stdout || found.stderr

if (found.code === 0 && version) {
if (acceptPythonVersion(version)) return
logPythonFailure(found)
throw new Error('python-version-required')
}

Expand Down Expand Up @@ -709,6 +729,7 @@ function createSetup({ paths, llmConfig, api, state, app, windowBridge, onLaunch
const verifiedVersion = verify.stdout || verify.stderr
if (verify.code === 0 && verifiedVersion) {
if (acceptPythonVersion(verifiedVersion)) return
logPythonFailure(verify)
throw new Error('python-version-required')
}
}
Expand Down Expand Up @@ -747,6 +768,7 @@ function createSetup({ paths, llmConfig, api, state, app, windowBridge, onLaunch

const verifiedVersion = verify.stdout || verify.stderr || 'Python installed.'
if (acceptPythonVersion(verifiedVersion)) return
logPythonFailure(verify)
throw new Error('python-version-required')
}

Expand Down
Loading