diff --git a/electron-ui/electron/lib/api-spawn.js b/electron-ui/electron/lib/api-spawn.js index 9636a02..1448a47 100644 --- a/electron-ui/electron/lib/api-spawn.js +++ b/electron-ui/electron/lib/api-spawn.js @@ -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, @@ -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), @@ -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 })) }) } diff --git a/electron-ui/electron/lib/api-spawn.test.js b/electron-ui/electron/lib/api-spawn.test.js new file mode 100644 index 0000000..23a035e --- /dev/null +++ b/electron-ui/electron/lib/api-spawn.test.js @@ -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/) +}) diff --git a/electron-ui/electron/lib/setup-diagnostics.test.js b/electron-ui/electron/lib/setup-diagnostics.test.js new file mode 100644 index 0000000..1016582 --- /dev/null +++ b/electron-ui/electron/lib/setup-diagnostics.test.js @@ -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) +}) diff --git a/electron-ui/electron/lib/setup.js b/electron-ui/electron/lib/setup.js index 5acb146..c888916 100644 --- a/electron-ui/electron/lib/setup.js +++ b/electron-ui/electron/lib/setup.js @@ -611,8 +611,13 @@ 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 @@ -620,7 +625,7 @@ function createSetup({ paths, llmConfig, api, state, app, windowBridge, onLaunch 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 @@ -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) { @@ -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') } @@ -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') } } @@ -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') }