Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Fix GUI first-launch MCP race and put graff on PATH

justrach773992aea02e
diff --git a/AGENTS.md b/AGENTS.md
index bdf2e510..2efabb3c 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -49,6 +49,14 @@ new load-bearing decision, add a record in the same branch.
The graphical app follows [docs/design.md](docs/design.md). Radii are tokens (`rounded-composer`, `rounded-window`, `rounded-card`, `rounded-control`, `rounded-chip`, `rounded-full`). Icon-only buttons are circles; labelled buttons are pills; the prompt bar is 32px. Do not invent `rounded-[Npx]` for chrome. Nested split panes stay 6px. The TUI is not this surface.
+## Packaged GUI installs `graff` on PATH
+
+First launch of a packaged desktop build must leave `graff` as a command the user can type in a new terminal. **This includes Developer ID signed and notarized `.app` / `.dmg` builds.** Notarization, stapling, Gatekeeper, and the release sign flow do not skip, stub, or replace that step. MCP client setup is a separate first-launch job and must not gate PATH install (a failed `graff mcp install` is not an excuse to skip the shim).
+
+`apps/native/electron/engine-launcher.cjs` writes `~/.local/bin/graff`, prepends that directory on zsh/bash **login and interactive** startup files (`.zprofile` and `.zshrc`, not only the GUI process’s `SHELL`), and shims `~/bin`, `/opt/homebrew/bin`, and `/usr/local/bin` when writable. `HARNESS_NO_PATH=1` is the only skip — do not set it in notarized or release builds.
+
+Regression: `apps/native/electron/engine-launcher.test.cjs` (`login zsh finds graff without inheriting the app PATH` and `packaged first launch always installs graff on PATH, including notarized builds`).
+
## Driving the pager (no PTY, no Ghostty window)
Do not spawn `graff tui` or a terminal emulator to inspect or click the pager.
diff --git a/apps/native/electron/engine-launcher.cjs b/apps/native/electron/engine-launcher.cjs
index 5b09e8c9..67d7ccbe 100644
--- a/apps/native/electron/engine-launcher.cjs
+++ b/apps/native/electron/engine-launcher.cjs
@@ -4,43 +4,56 @@ const marker = '# Codegraff bundled engine launcher';
const pathMarker = '# Codegraff GUI CLI PATH';
const quote = value => "'" + value.replaceAll("'", "'\\''") + "'";
-async function ensurePath(home, directory, shell = process.env.SHELL || '/bin/zsh') {
+async function writeShim(file, source) {
+ let owned = true;
+ try {
+ const stat = await fs.lstat(file);
+ owned = stat.isFile() && stat.size < 16384 && (await fs.readFile(file, 'utf8')).includes(marker);
+ } catch (error) {
+ if (error.code !== 'ENOENT') throw error;
+ }
+ if (!owned) return false;
+ const temporary = `${file}.${process.pid}.next`;
+ await fs.mkdir(path.dirname(file), {recursive: true});
+ try {
+ await fs.writeFile(temporary, source, {mode: 0o755, flag: 'wx'});
+ await fs.rename(temporary, file);
+ } finally { await fs.rm(temporary, {force: true}); }
+ return true;
+}
+
+async function ensurePath(home, directory) {
if (process.env.HARNESS_NO_PATH) return;
- const shellName = path.basename(shell);
- const candidates = [
- [path.join(home, '.zshrc'), shellName === 'zsh', `export PATH=${quote(directory)}:"$PATH"`],
- [path.join(home, '.bash_profile'), shellName === 'bash', `export PATH=${quote(directory)}:"$PATH"`],
- [path.join(home, '.bashrc'), shellName === 'bash', `export PATH=${quote(directory)}:"$PATH"`],
- [path.join(home, '.profile'), !['zsh', 'bash', 'fish'].includes(shellName), `export PATH=${quote(directory)}:"$PATH"`],
- [path.join(home, '.config/fish/config.fish'), shellName === 'fish', `fish_add_path -m ${quote(directory)}`],
+ const line = `export PATH=${quote(directory)}:"$PATH"`;
+ const files = [
+ [path.join(home, '.zshrc'), line, true],
+ [path.join(home, '.zprofile'), line, true],
+ [path.join(home, '.bash_profile'), line, true],
+ [path.join(home, '.bashrc'), line, true],
+ [path.join(home, '.profile'), line, false],
+ [path.join(home, '.config/fish/config.fish'), `fish_add_path -m ${quote(directory)}`, false],
];
- for (const [file, create, line] of candidates) {
+ for (const [file, snippet, create] of files) {
let source;
try { source = await fs.readFile(file, 'utf8'); }
catch (error) { if (error.code !== 'ENOENT') throw error; if (!create) continue; source = ''; }
if (source.includes(pathMarker)) continue;
- await fs.mkdir(path.dirname(file), {recursive:true});
- await fs.appendFile(file, `\n${pathMarker}\n${line}\n`, {mode:0o600});
+ await fs.mkdir(path.dirname(file), {recursive: true});
+ await fs.appendFile(file, `\n${pathMarker}\n${snippet}\n`, {mode: 0o600});
}
}
-async function installEngine(binary, home, {shell} = {}) {
+async function installEngine(binary, home, {extraBin} = {}) {
await fs.access(binary, require('node:fs').constants.X_OK);
const directory = path.join(home, '.local/bin'), file = path.join(directory, 'graff');
- await fs.mkdir(directory, {recursive:true});
- let owned = true;
- try {
- const stat = await fs.lstat(file);
- owned = stat.isFile() && stat.size < 16384 && (await fs.readFile(file, 'utf8')).includes(marker);
- } catch (error) { if (error.code !== 'ENOENT') throw error; }
- if (!owned) return 'Existing graff command preserved';
const source = `#!/bin/sh\n${marker}\nexec ${quote(binary)} "$@"\n`;
- const temporary = `${file}.${process.pid}.next`;
- try {
- await fs.writeFile(temporary, source, {mode:0o755, flag:'wx'});
- await fs.rename(temporary, file);
- } finally { await fs.rm(temporary, {force:true}); }
- await ensurePath(home, directory, shell);
- return `Installed graff in ${directory}. Open a new terminal to use it.`;
+ const installed = await writeShim(file, source);
+ // PATH even when ~/.local/bin/graff is someone else's binary — otherwise the
+ // user still cannot type `graff` after installing the app.
+ await ensurePath(home, directory);
+ for (const dir of extraBin ?? [path.join(home, 'bin')]) {
+ try { await writeShim(path.join(dir, 'graff'), source); } catch { /* not writable */ }
+ }
+ return installed ? `Installed graff in ${directory}. Open a new terminal to use it.` : 'Existing graff command preserved';
}
module.exports = {installEngine, ensurePath};
diff --git a/apps/native/electron/engine-launcher.test.cjs b/apps/native/electron/engine-launcher.test.cjs
index d30db0a8..5c09cc9b 100644
--- a/apps/native/electron/engine-launcher.test.cjs
+++ b/apps/native/electron/engine-launcher.test.cjs
@@ -1,6 +1,7 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
+const {readFileSync} = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const {promisify} = require('node:util');
@@ -13,14 +14,17 @@ test('bundled graff forwards arguments, updates with GUI and configures PATH onc
const first = path.join(home, "old ' bundle"), second = path.join(home, 'new bundle');
await fs.writeFile(first, '#!/bin/sh\nprintf "%s\\n" "$@"\n', {mode:0o700});
await fs.writeFile(second, '#!/bin/sh\necho updated\n', {mode:0o700});
- await installEngine(first, home, {shell:'/bin/zsh'});
+ await installEngine(first, home, {extraBin: []});
const launcher = path.join(home, '.local/bin/graff');
assert.equal((await execFile(launcher, ['a b', '$(literal)'])).stdout, 'a b\n$(literal)\n');
const rc = await fs.readFile(path.join(home, '.zshrc'), 'utf8');
- await installEngine(second, home, {shell:'/bin/zsh'});
+ const profile = await fs.readFile(path.join(home, '.zprofile'), 'utf8');
+ assert.match(profile, /export PATH=/);
+ await installEngine(second, home, {extraBin: []});
assert.equal((await execFile(launcher)).stdout, 'updated\n');
assert.equal(await fs.readFile(path.join(home, '.zshrc'), 'utf8'), rc);
- const result = await execFile('/bin/zsh', ['-c', 'source "$HOME/.zshrc"; command -v graff'], {env:{HOME:home,PATH:'/usr/bin:/bin'}});
+ assert.equal(await fs.readFile(path.join(home, '.zprofile'), 'utf8'), profile);
+ const result = await execFile('/bin/zsh', ['-c', 'source "$HOME/.zprofile"; command -v graff'], {env:{HOME:home,PATH:'/usr/bin:/bin'}});
assert.equal(result.stdout.trim(), launcher);
} finally { await fs.rm(home, {recursive:true,force:true}); }
});
@@ -31,7 +35,66 @@ test('independent graff command is preserved', async () => {
const file = path.join(home,'.local/bin/graff');
await fs.mkdir(path.dirname(file),{recursive:true});
await fs.writeFile(file,'custom');
- assert.equal(await installEngine('/bin/echo',home),'Existing graff command preserved');
+ assert.equal(await installEngine('/bin/echo',home,{extraBin: []}),'Existing graff command preserved');
assert.equal(await fs.readFile(file,'utf8'),'custom');
+ assert.match(await fs.readFile(path.join(home, '.zshrc'), 'utf8'), /Codegraff GUI CLI PATH/);
} finally {await fs.rm(home,{recursive:true,force:true});}
});
+
+test('login zsh finds graff without inheriting the app PATH', async () => {
+ // macOS Terminal is a login, often non-interactive, zsh: it reads .zprofile
+ // and not .zshrc. A notarized .app that only patched .zshrc leaves `graff`
+ // as command-not-found. ZDOTDIR isolates this from the developer's files.
+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'graff-engine-'));
+ try {
+ const binary = path.join(home, 'graff-bin');
+ await fs.writeFile(binary, '#!/bin/sh\necho ok\n', {mode:0o700});
+ await installEngine(binary, home, {extraBin: []});
+ const launcher = path.join(home, '.local/bin/graff');
+ const result = await execFile('/bin/zsh', ['-lc', 'command -v graff'], {
+ env: {
+ HOME: home, ZDOTDIR: home, SHELL: '/bin/zsh', PATH: '/usr/bin:/bin',
+ TERM: 'dumb', USER: process.env.USER || 'graff',
+ },
+ timeout: 8000,
+ });
+ assert.equal(result.stdout.trim(), launcher);
+ } finally { await fs.rm(home, {recursive:true, force:true}); }
+});
+
+test('packaged first launch always installs graff on PATH, including notarized builds', () => {
+ const source = readFileSync(path.join(__dirname, 'main.cjs'), 'utf8');
+ const ready = source.indexOf('app.whenReady()');
+ assert.ok(ready >= 0);
+ const engine = source.indexOf("require('./engine-launcher.cjs').installEngine", ready);
+ const mcp = source.indexOf("require('./mcp-install.cjs').installMcp", ready);
+ assert.ok(engine > ready, 'packaged launch must call installEngine');
+ assert.ok(mcp > ready && mcp < engine, 'MCP setup is a sibling of PATH install, not its parent');
+ assert.equal(source.slice(mcp, engine).includes('.then('), false, 'MCP failure must not skip PATH install');
+ const call = source.slice(engine, engine + 900);
+ assert.match(call, /extraBin:/);
+ assert.match(call, /\/opt\/homebrew\/bin/);
+ assert.match(call, /\/usr\/local\/bin/);
+ assert.match(call, /['"]bin['"]/);
+ const gate = source.slice(source.lastIndexOf('if (', engine), engine);
+ assert.match(gate, /app\.isPackaged/);
+ assert.doesNotMatch(gate, /developmentBuild/);
+ assert.doesNotMatch(source.slice(ready, engine + 900), /notar/i);
+ assert.doesNotMatch(source.slice(ready, engine + 900), /HARNESS_NO_PATH/);
+});
+
+test('writable extra bin dirs get a graff shim', async () => {
+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'graff-engine-'));
+ try {
+ const binary = path.join(home, 'graff-bin');
+ const extra = path.join(home, 'brew/bin');
+ await fs.writeFile(binary, '#!/bin/sh\necho ok\n', {mode:0o700});
+ await fs.mkdir(extra, {recursive: true});
+ await installEngine(binary, home, {extraBin: [extra]});
+ const shim = path.join(extra, 'graff');
+ assert.equal((await execFile(shim)).stdout, 'ok\n');
+ await fs.writeFile(shim, 'custom');
+ await installEngine(binary, home, {extraBin: [extra]});
+ assert.equal(await fs.readFile(shim, 'utf8'), 'custom');
+ } finally { await fs.rm(home, {recursive:true, force:true}); }
+});
diff --git a/apps/native/electron/main.cjs b/apps/native/electron/main.cjs
index 7b52a705..ae57a1d3 100644
--- a/apps/native/electron/main.cjs
+++ b/apps/native/electron/main.cjs
@@ -80,15 +80,22 @@ process.on('SIGTERM', () => app.quit());
process.on('SIGINT', () => app.quit());
app.whenReady().then(async () => {
- if (app.isPackaged && !developmentBuild && !process.env.GRAFF_ELECTRON_SMOKE) {
- void require('./mcp-install.cjs').installMcp(path.join(resources, 'graff'), app.getPath('home'), { once: true })
- .catch(error => dialog.showErrorBox('MCP setup incomplete', `${error.message}\nRetry from Tools → Configure MCP clients.`));
- }
await require('./shell-path.cjs').restoreShellPath();
if (app.isPackaged && !process.env.GRAFF_ELECTRON_SMOKE) {
- void require('./engine-launcher.cjs').installEngine(path.join(resources, 'graff'), app.getPath('home'))
- .then(() => require('./mcp-install.cjs').installMcp(path.join(resources, 'graff'), app.getPath('home'), { once: true, version: app.getVersion() }))
- .catch(error => dialog.showErrorBox('Command setup incomplete', `${error.message}\nRetry from Tools → Install codegraff terminal command.`));
+ const home = app.getPath('home');
+ const binary = path.join(resources, 'graff');
+ // One MCP install per launch. A second overlapping `graff mcp install` used
+ // to lose the installer lock (BlockingIOError / errno 35) and pop "MCP setup
+ // incomplete" while the first was still running.
+ void require('./mcp-install.cjs').installMcp(binary, home, { once: true, version: app.getVersion() })
+ .catch(error => dialog.showErrorBox('MCP setup incomplete', `${error.message}\nRetry from Tools → Configure MCP clients.`));
+ void require('./engine-launcher.cjs').installEngine(binary, home, {
+ extraBin: ['/opt/homebrew/bin', '/usr/local/bin', path.join(home, 'bin')],
+ }).then(() => {
+ const dir = path.join(home, '.local/bin');
+ const parts = (process.env.PATH || '').split(':').filter(Boolean);
+ if (!parts.includes(dir)) process.env.PATH = [dir, ...parts].join(':');
+ }).catch(error => dialog.showErrorBox('Command setup incomplete', `${error.message}\nRetry from Tools → Install codegraff terminal command.`));
}
app.setAccessibilitySupportEnabled(true);
const passkeysConfigured = require('./webauthn.cjs').configureWebAuthn(app, resources);
@@ -249,7 +256,9 @@ app.whenReady().then(async () => {
} catch (error) { dialog.showErrorBox('MCP setup', error.message); }
} }, { label: 'Install codegraff terminal command…', enabled: app.isPackaged && process.platform === 'darwin', click: async () => {
try {
- await require('./engine-launcher.cjs').installEngine(path.join(resources, 'graff'), app.getPath('home'));
+ await require('./engine-launcher.cjs').installEngine(path.join(resources, 'graff'), app.getPath('home'), {
+ extraBin: ['/opt/homebrew/bin', '/usr/local/bin', path.join(app.getPath('home'), 'bin')],
+ });
const installed = await require('./cli-launcher.cjs').installLauncher(path.resolve(app.getPath('exe'), '../../..'), app.getPath('home'));
await dialog.showMessageBox(win, { message: 'Terminal command installed', detail: `Run graff for the CLI or codegraff . for the GUI. Open a new terminal to load the PATH update (${path.dirname(installed)}).` });
} catch (error) { dialog.showErrorBox('Terminal command', error.message); }
diff --git a/apps/native/electron/mcp-install.cjs b/apps/native/electron/mcp-install.cjs
index 42d80fa8..af84cab4 100644
--- a/apps/native/electron/mcp-install.cjs
+++ b/apps/native/electron/mcp-install.cjs
@@ -3,7 +3,15 @@ const { execFile } = require('node:child_process');
const fs = require('node:fs/promises');
const path = require('node:path');
-async function installMcp(binary, home, { once = false, version = '1' } = {}) {
+let queue = Promise.resolve();
+
+async function installMcp(binary, home, opts = {}) {
+ const run = queue.then(() => installMcpLocked(binary, home, opts));
+ queue = run.catch(() => {});
+ return run;
+}
+
+async function installMcpLocked(binary, home, { once = false, version = '1' } = {}) {
if (process.env.GRAFF_NO_MCP === '1') return 'MCP setup skipped';
const receipt = path.join(home, '.graff/mcp/gui-installed');
if (once) {
diff --git a/apps/native/electron/mcp-install.test.cjs b/apps/native/electron/mcp-install.test.cjs
index 9859ac31..1c180411 100644
--- a/apps/native/electron/mcp-install.test.cjs
+++ b/apps/native/electron/mcp-install.test.cjs
@@ -25,3 +25,19 @@ test('failed GUI setup leaves no success receipt', async () => {
await assert.rejects(fs.access(path.join(home, '.graff/mcp/gui-installed')));
} finally { await fs.rm(home, {recursive:true, force:true}); }
});
+
+test('overlapping GUI setup runs the engine once', async () => {
+ const home = await fs.mkdtemp(path.join(os.tmpdir(), 'graff-mcp-gui-'));
+ try {
+ const binary = path.join(home, 'fake-graff');
+ const runs = path.join(home, 'runs');
+ await fs.writeFile(binary, `#!/bin/sh\necho x >> "${runs}"\nsleep 0.3\necho registered\n`, {mode:0o700});
+ const [a, b] = await Promise.all([
+ installMcp(binary, home, {once:true, version:'1'}),
+ installMcp(binary, home, {once:true, version:'1'}),
+ ]);
+ assert.match(a, /registered/);
+ assert.equal(b, 'MCP already configured');
+ assert.equal((await fs.readFile(runs, 'utf8')).trim().split('\n').length, 1);
+ } finally { await fs.rm(home, {recursive:true, force:true}); }
+});
diff --git a/docs/mcp-server.md b/docs/mcp-server.md
index c816edf6..52dc9a3e 100644
--- a/docs/mcp-server.md
+++ b/docs/mcp-server.md
@@ -3,9 +3,11 @@
## Automatic HTTP setup
The packaged GUI installs its bundled `graff` command into `~/.local/bin` on
-launch and adds that directory to shell startup files. Open a new terminal to
-load the PATH change. GUI updates refresh this managed launcher; an existing
-independently installed command is preserved. `HARNESS_NO_PATH=1` skips PATH edits.
+launch (and `~/bin` plus Homebrew/`/usr/local/bin` when those dirs are writable)
+and prepends `~/.local/bin` on zsh/bash login and interactive startup files.
+Open a new terminal if your current one was started before that PATH line.
+GUI updates refresh this managed launcher; an existing independently installed
+command is preserved. `HARNESS_NO_PATH=1` skips PATH edits.
The CLI installer and first launch of the packaged GUI run `graff mcp install`.
The GUI also offers **Tools → Configure MCP clients**. Setup requires Python 3
diff --git a/scripts/install-mcp.py b/scripts/install-mcp.py
index 437411a6..39192e01 100644
--- a/scripts/install-mcp.py
+++ b/scripts/install-mcp.py
@@ -154,6 +154,35 @@ def ready(url, token):
return False
+def run_managed(argv, check=True):
+ delay = 0.05
+ for attempt in range(6):
+ try:
+ return subprocess.run(argv, check=check, capture_output=True, stdin=subprocess.DEVNULL)
+ except BlockingIOError:
+ if attempt == 5:
+ raise
+ time.sleep(delay)
+ delay = min(delay * 2, 0.5)
+
+
+def acquire_install_lock(lock_path, timeout=12.0):
+ if lock_path.is_symlink():
+ raise ValueError('Refusing symlinked installer lock')
+ install_lock = open(lock_path, 'a')
+ os.chmod(lock_path, 0o600)
+ deadline = time.monotonic() + timeout
+ while True:
+ try:
+ fcntl.flock(install_lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
+ return install_lock
+ except BlockingIOError:
+ if time.monotonic() >= deadline:
+ install_lock.close()
+ raise ValueError('another MCP install is already running; retry from Tools → Configure MCP clients')
+ time.sleep(0.1)
+
+
def service(home, executable, directory, port, token):
state = home / '.graff/mcp'
command = [str(executable), 'mcp', 'serve', '--http', '--port', str(port)]
@@ -167,9 +196,9 @@ def service(home, executable, directory, port, token):
'StandardOutPath': str(state / 'service.log'), 'StandardErrorPath': str(state / 'service.log')}
atomic(target, plistlib.dumps(config).decode())
domain = f'gui/{os.getuid()}'
- subprocess.run(['launchctl', 'bootout', domain + '/dev.codegraff.mcp'], capture_output=True)
- subprocess.run(['launchctl', 'bootstrap', domain, str(target)], check=True, capture_output=True)
- subprocess.run(['launchctl', 'kickstart', '-k', domain + '/dev.codegraff.mcp'], check=True, capture_output=True)
+ run_managed(['launchctl', 'bootout', domain + '/dev.codegraff.mcp'], check=False)
+ run_managed(['launchctl', 'bootstrap', domain, str(target)])
+ run_managed(['launchctl', 'kickstart', '-k', domain + '/dev.codegraff.mcp'])
elif sys.platform.startswith('linux') and shutil.which('systemctl'):
target = home / '.config/systemd/user/codegraff-mcp.service'
if target.exists() and MARKER not in target.read_text():
@@ -179,9 +208,9 @@ def service(home, executable, directory, port, token):
'ExecStart=' + ' '.join(quote(part) for part in command) + '\n' +
'WorkingDirectory=' + quote(directory) + '\nEnvironment=GRAFF_MCP_TOKEN=' + token +
'\nRestart=on-failure\nRestartSec=10\n[Install]\nWantedBy=default.target\n')
- subprocess.run(['systemctl', '--user', 'daemon-reload'], check=True, capture_output=True)
- subprocess.run(['systemctl', '--user', 'enable', '--now', 'codegraff-mcp.service'], check=True, capture_output=True)
- subprocess.run(['systemctl', '--user', 'restart', 'codegraff-mcp.service'], check=True, capture_output=True)
+ run_managed(['systemctl', '--user', 'daemon-reload'])
+ run_managed(['systemctl', '--user', 'enable', '--now', 'codegraff-mcp.service'])
+ run_managed(['systemctl', '--user', 'restart', 'codegraff-mcp.service'])
else:
raise ValueError('Automatic service setup needs macOS launchd or Linux user systemd')
@@ -212,11 +241,16 @@ def main():
raise ValueError('Refusing symlinked service directory')
os.chmod(state, 0o700)
lock_path = state / 'install.lock'
- if lock_path.is_symlink():
- raise ValueError('Refusing symlinked installer lock')
- install_lock = open(lock_path, 'a')
- os.chmod(lock_path, 0o600)
- fcntl.flock(install_lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
+ url = f'http://127.0.0.1:{args.port}/mcp'
+ try:
+ install_lock = acquire_install_lock(lock_path)
+ except ValueError:
+ token_path = state / 'token'
+ token = token_path.read_text().strip() if token_path.exists() else ''
+ if token and ready(url, token):
+ print(f'MCP ready at {url}; another installer holds the lock.')
+ return
+ raise
token_path = state / 'token'
if token_path.is_symlink():
raise ValueError('Refusing symlinked token')
@@ -224,7 +258,6 @@ def main():
if not re.fullmatch('[0-9a-f]{64}', token):
raise ValueError('Invalid stored service token')
atomic(token_path, token + '\n')
- url = f'http://127.0.0.1:{args.port}/mcp'
service(home, binary, directory, args.port, token)
for _ in range(30):
if ready(url, token):
diff --git a/scripts/test-install-mcp.py b/scripts/test-install-mcp.py
index 2d5ae527..8dd30a93 100644
--- a/scripts/test-install-mcp.py
+++ b/scripts/test-install-mcp.py
@@ -4,7 +4,10 @@ import json
import os
from pathlib import Path
import plistlib
+import subprocess
import tempfile
+import threading
+import time
import sys
import unittest
from unittest.mock import patch
@@ -102,5 +105,56 @@ class InstallTests(unittest.TestCase):
run.assert_not_called()
self.assertEqual(path.read_bytes(), original)
+ def _hold_lock(self, lock_path):
+ holder = subprocess.Popen(
+ [sys.executable, '-c',
+ 'import fcntl, sys, time\n'
+ 'f = open(sys.argv[1], "a")\n'
+ 'fcntl.flock(f.fileno(), fcntl.LOCK_EX)\n'
+ 'sys.stdout.write("h")\n'
+ 'sys.stdout.flush()\n'
+ 'time.sleep(30)\n', str(lock_path)],
+ stdout=subprocess.PIPE,
+ )
+ self.addCleanup(holder.kill)
+ self.assertEqual(holder.stdout.read(1), b'h')
+ return holder
+
+ def test_lock_waits_for_holder(self):
+ lock_path = self.home / 'install.lock'
+ holder = self._hold_lock(lock_path)
+ got = []
+ def waiter():
+ handle = installer.acquire_install_lock(lock_path, timeout=2)
+ got.append(True)
+ handle.close()
+ thread = threading.Thread(target=waiter)
+ thread.start()
+ time.sleep(0.15)
+ self.assertEqual(got, [])
+ holder.kill()
+ holder.wait()
+ thread.join(2)
+ self.assertFalse(thread.is_alive())
+ self.assertEqual(got, [True])
+
+ def test_lock_timeout_is_not_blocking_io(self):
+ lock_path = self.home / 'install.lock'
+ self._hold_lock(lock_path)
+ with self.assertRaises(ValueError) as ctx:
+ installer.acquire_install_lock(lock_path, timeout=0.25)
+ self.assertIn('already running', str(ctx.exception))
+
+ def test_run_managed_retries_blocking_io(self):
+ calls = {'n': 0}
+ def fake(argv, **_kwargs):
+ calls['n'] += 1
+ if calls['n'] < 3:
+ raise BlockingIOError(35, 'Resource temporarily unavailable')
+ return subprocess.CompletedProcess(argv, 0)
+ with patch.object(installer.subprocess, 'run', fake):
+ installer.run_managed(['launchctl', 'bootstrap', 'x'])
+ self.assertEqual(calls['n'], 3)
+
if __name__ == '__main__':
unittest.main()