The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(release): report handles on failed dmg detach
ethernetf6db54ddf219
diff --git a/apps/desktop/BUILDING.md b/apps/desktop/BUILDING.mdindex aedb94c36fa..bc248628284 100644--- a/apps/desktop/BUILDING.md+++ b/apps/desktop/BUILDING.md@@ -158,6 +158,19 @@ the update artifact, not an optional duplicate of the download DMG.See [macOS bundle updates](../../docs/macos-bundle-updates.md) for feed validationand native-event ordering.+### DMG detach diagnostics++The builder wrapper reports `[dmg-detach]` snapshots when dmgbuild cannot detach+its staging image. It runs `lsof` before the supplier retries or performs forced+cleanup. The snapshot identifies the mounted filesystem, backing image and+devices, then lists process names, PIDs, parent PIDs, users, descriptors and paths.++The queries use noninteractive `sudo` when available. Permission failures and+query timeouts are reported explicitly. Empty output does not prove that the+image has no holder. The shim does not stop processes or change detach results,+retry settings, signing or notarization. Explicit `CUSTOM_DMGBUILD_PATH`+overrides bypass the shim because their interpreter layout is not known.+## Development, assets, and verificationPrepare and activate the [PM developer environment](../../website/docs/reference/package-management.md#developer-workflow)diff --git a/apps/desktop/scripts/dmgbuild-diagnostics.cjs b/apps/desktop/scripts/dmgbuild-diagnostics.cjsnew file mode 100644index 00000000000..71f19356e98--- /dev/null+++ b/apps/desktop/scripts/dmgbuild-diagnostics.cjs@@ -0,0 +1,60 @@+'use strict'++const childProcess = require('node:child_process')+const { syncBuiltinESMExports } = require('node:module')+const path = require('node:path')+const { promisify } = require('node:util')++function wrapDmgbuildExecFile(execFile, write = chunk => process.stderr.write(chunk)) {+ function wrapped(file, args, options, callback) {+ if (+ typeof file !== 'string' ||+ path.basename(file) !== 'dmgbuild' ||+ !Array.isArray(args) ||+ typeof options !== 'object' ||+ (options?.env?.CUSTOM_DMGBUILD_PATH || process.env.CUSTOM_DMGBUILD_PATH)?.trim()+ ) {+ return execFile.apply(this, arguments)+ }++ // Use the interpreter and module path from the supplier's launcher.+ // A PATH shim cannot intercept dmgbuild's absolute /usr/bin/hdiutil call.+ const vendor = path.dirname(file)+ const diagnostic = path.resolve(__dirname, '../../../scripts/bundles/dmgbuild_diagnostics.py')+ const child = execFile.call(+ this,+ path.join(vendor, 'python', 'bin', 'python3'),+ [diagnostic, ...args],+ {+ ...options,+ env: { ...(options?.env || process.env), PYTHONPATH: path.join(vendor, 'python', 'lib') }+ },+ callback+ )+ // execFile buffers stderr. Tee it so a later successful retry cannot hide it.+ child.stderr?.on('data', write)+ return child+ }++ wrapped[promisify.custom] = (...args) => {+ const { promise, resolve, reject } = Promise.withResolvers()+ promise.child = wrapped(...args, (error, stdout, stderr) => {+ if (error) {+ error.stdout = stdout+ error.stderr = stderr+ reject(error)+ } else {+ resolve({ stdout, stderr })+ }+ })+ return promise+ }+ return wrapped+}++module.exports = { wrapDmgbuildExecFile }++if (process.platform === 'darwin') {+ childProcess.execFile = wrapDmgbuildExecFile(childProcess.execFile)+ syncBuiltinESMExports()+}diff --git a/apps/desktop/scripts/dmgbuild-diagnostics.test.mjs b/apps/desktop/scripts/dmgbuild-diagnostics.test.mjsnew file mode 100644index 00000000000..62323fb8004--- /dev/null+++ b/apps/desktop/scripts/dmgbuild-diagnostics.test.mjs@@ -0,0 +1,69 @@+import { execFile } from 'node:child_process'+import { EventEmitter } from 'node:events'+import { createRequire } from 'node:module'+import path from 'node:path'+import { promisify } from 'node:util'++import { expect, test } from 'vitest'++const require = createRequire(import.meta.url)+const { wrapDmgbuildExecFile } = require('./dmgbuild-diagnostics.cjs')++test('the resolved dmgbuild uses its paired Python and preserves args, results and live diagnostics', () => {+ const invocations = []+ const output = []+ const child = { stderr: new EventEmitter() }+ const original = (...args) => {+ invocations.push(args)+ return child+ }+ const wrapped = wrapDmgbuildExecFile(original, chunk => output.push(chunk))+ const vendor = path.resolve('tool cache', 'dmgbuild bundle')+ const args = ['-s', 'settings with spaces.json', 'Install Hermes Agent', 'output.dmg']+ const options = { maxBuffer: 1024, env: { KEEP: 'value', PYTHONPATH: 'old' } }+ const callback = () => {}++ expect(wrapped(path.join(vendor, 'dmgbuild'), args, options, callback)).toBe(child)+ const invocation = invocations[0]+ expect(invocation[0]).toBe(path.join(vendor, 'python', 'bin', 'python3'))+ expect(path.basename(invocation[1][0])).toBe('dmgbuild_diagnostics.py')+ expect(invocation[1].slice(1)).toEqual(args)+ expect(invocation[2]).toEqual({ ...options, env: { KEEP: 'value', PYTHONPATH: path.join(vendor, 'python', 'lib') } })+ expect(invocation[3]).toBe(callback)+ expect(options.env.PYTHONPATH).toBe('old')+ child.stderr.emit('data', Buffer.from('[dmg-detach] actual child output'))+ expect(output[0].toString()).toContain('[dmg-detach]')+})++test('promisified callers retain stdout, stderr and the real child handle', async () => {+ const wrapped = wrapDmgbuildExecFile(execFile)+ const pending = promisify(wrapped)(process.execPath, [+ '-e',+ 'process.stdout.write("out"); process.stderr.write("err")'+ ])+ expect(pending.child).toBeDefined()+ expect(await pending).toEqual({ stdout: 'out', stderr: 'err' })+ await expect(+ promisify(wrapped)(process.execPath, [+ '-e',+ 'process.stdout.write("out"); process.stderr.write("err"); process.exit(23)'+ ])+ ).rejects.toMatchObject({ code: 23, stdout: 'out', stderr: 'err' })+})++test('other executables and explicit custom dmgbuild overrides pass through unchanged', () => {+ const calls = []+ const original = (...args) => calls.push(args)+ const wrapped = wrapDmgbuildExecFile(original)+ const callback = () => {}+ wrapped('/usr/bin/true', callback)+ expect(calls[0]).toEqual(['/usr/bin/true', callback])+ const invocation = [+ path.resolve('custom', 'dmgbuild'),+ ['--help'],+ { env: { CUSTOM_DMGBUILD_PATH: '/custom/dmgbuild' } },+ callback+ ]+ wrapped(...invocation)+ expect(calls[1]).toEqual(invocation)+})diff --git a/apps/desktop/scripts/run-electron-builder.mjs b/apps/desktop/scripts/run-electron-builder.mjsindex a5f2bf22d82..9e585af00cb 100644--- a/apps/desktop/scripts/run-electron-builder.mjs+++ b/apps/desktop/scripts/run-electron-builder.mjs@@ -92,9 +92,12 @@ if (args.includes('--win') && process.env.AZURE_SIGN_ENDPOINT && process.env.AZU// exhausts the macOS table: EMFILE on a random .py. Raising ulimit only// moves the ceiling. --require, not an import: isbinaryfile captures// promisify(fs.open) at its own load.-const preload = path.join(import.meta.dirname, 'fs-open-limit.cjs')+const preloads = ['--require', path.join(import.meta.dirname, 'fs-open-limit.cjs')]+if (process.platform === 'darwin') {+ preloads.push('--require', path.join(import.meta.dirname, 'dmgbuild-diagnostics.cjs'))+}-const result = spawnSync(process.execPath, ['--require', preload, electronBuilderCli(), ...args], {+const result = spawnSync(process.execPath, [...preloads, electronBuilderCli(), ...args], {stdio: 'inherit'})if (result.error) {diff --git a/scripts/bundles/dmgbuild_diagnostics.py b/scripts/bundles/dmgbuild_diagnostics.pynew file mode 100644index 00000000000..1492016dfec--- /dev/null+++ b/scripts/bundles/dmgbuild_diagnostics.py@@ -0,0 +1,92 @@+"""Run the supplier's dmgbuild with failure-time, read-only handle diagnostics."""+from __future__ import annotations++import functools+import json+import subprocess+import sys+++def report_detach_failure(target, attachment, output, *, run=subprocess.run, stream=None):+ stream = sys.stderr if stream is None else stream++ def log(text):+ print(f"[dmg-detach] {text}", file=stream, flush=True)++ def invoke(argv):+ log("command: " + json.dumps(argv))+ try:+ result = run(argv, stdin=subprocess.DEVNULL, capture_output=True,+ text=True, encoding="utf-8", errors="replace", timeout=15)+ except subprocess.TimeoutExpired as error:+ for partial in (error.stdout, error.stderr):+ if partial:+ log(partial.decode("utf-8", errors="replace") if isinstance(partial, bytes) else partial)+ log("diagnostic timed out after 15s. Snapshot is incomplete.")+ return None+ except OSError as error:+ log(f"diagnostic unavailable: {error}")+ return None+ if result.stdout:+ log(result.stdout.rstrip())+ if result.stderr:+ log(result.stderr.rstrip())+ log(f"diagnostic exit status: {result.returncode}")+ return result++ log(f"detach failed for {target}: {output}")+ log("Open-handle snapshot before dmgbuild retries or cleanup. No processes are stopped.")+ elevated = invoke(["/usr/bin/sudo", "-n", "/usr/bin/true"])+ prefix = ["/usr/bin/sudo", "-n"] if elevated is not None and elevated.returncode == 0 else []+ if not prefix:+ log("Using an unprivileged snapshot; system-process handles may be hidden.")+ entities = attachment.get("entities", []) if attachment else []+ mounts = list(dict.fromkeys(e["mount-point"] for e in entities if e.get("mount-point")))+ devices = list(dict.fromkeys([target, *(e["dev-entry"] for e in entities if e.get("dev-entry"))]))+ raw_devices = ["/dev/r" + device[5:] for device in devices if device.startswith("/dev/disk")]+ image = attachment.get("image") if attachment else None+ log("attachment: " + json.dumps({"image": image, "entities": entities}))+ command = [*prefix, "/usr/sbin/lsof", "-nP", "+c", "0", "-R"]+ for mount in mounts:+ # Select the filesystem, not a recursive stat of every bundled file.+ invoke([*command, "+f", "--", mount])+ invoke([*command, "-f", "--", *([image] if image else []), *devices, *raw_devices])+ log("End of handle snapshot. Errors or empty output do not prove the absence of holders.")+++def wrap_hdiutil(native, *, report=report_detach_failure, stream=None):+ attachments = {}++ @functools.wraps(native)+ def observed(command, *args, **kwargs):+ result = native(command, *args, **kwargs)+ code, output = result+ if command == "attach" and code == 0 and isinstance(output, dict):+ attachment = {"image": args[-1], "entities": output.get("system-entities", [])}+ for entity in attachment["entities"]:+ for key in ("dev-entry", "mount-point"):+ if entity.get(key):+ attachments[entity[key]] = attachment+ elif command in ("detach", "unmount") and code != 0:+ target = next((arg for arg in reversed(args) if not arg.startswith("-")), "")+ try:+ report(target, attachments.get(target), output)+ except Exception as error:+ # Diagnostics must not replace the original detach failure.+ print(f"[dmg-detach] diagnostic failed: {error}",+ file=sys.stderr if stream is None else stream, flush=True)+ return result++ return observed+++def main():+ from dmgbuild import core+ from dmgbuild.__main__ import main as build++ core.hdiutil = wrap_hdiutil(core.hdiutil)+ build()+++if __name__ == "__main__":+ main()diff --git a/tests/scripts/test_dmgbuild_diagnostics.py b/tests/scripts/test_dmgbuild_diagnostics.pynew file mode 100644index 00000000000..9a0a176537c--- /dev/null+++ b/tests/scripts/test_dmgbuild_diagnostics.py@@ -0,0 +1,141 @@+"""DMG diagnostics observe failures without changing the native result."""+import io+import json+import os+import plistlib+import subprocess+import sys+from pathlib import Path++import pytest++from scripts.bundles import dmgbuild_diagnostics as diagnostics+++def test_detach_diagnostics_run_before_cleanup_and_preserve_results():+ events = []+ attachment = {"system-entities": [+ {"dev-entry": "/dev/disk24"},+ {"dev-entry": "/dev/disk25s1", "mount-point": "/Volumes/Install Hermes Agent"},+ ]}+ failure = (16, "hdiutil: couldn't eject disk25 - Resource busy")++ def native(command, *args, **kwargs):+ events.append((command, args, kwargs))+ if command == "attach":+ return 0, attachment+ return (0, "detached") if "-force" in args or command != "detach" else failure++ def report(target, image, output):+ events.append(("diagnostic", target, image, output))++ observed = diagnostics.wrap_hdiutil(native, report=report)+ observed("attach", "-nobrowse", "/tmp/our staging.dmg")+ assert observed("detach", "/dev/disk25s1", plist=False) is failure+ observed("detach", "-force", "/dev/disk25s1", plist=False)+ assert [event[0] for event in events] == ["attach", "detach", "diagnostic", "detach"]+ assert events[2][1] == "/dev/disk25s1"+ assert events[2][2] == {"image": "/tmp/our staging.dmg", "entities": attachment["system-entities"]}+ assert events[2][3] == failure[1]++ def broken_report(*args):+ raise OSError("diagnostic command unavailable")++ errors = io.StringIO()+ broken = diagnostics.wrap_hdiutil(native, report=broken_report, stream=errors)+ assert broken("detach", "/dev/disk25s1", plist=False) is failure+ assert "diagnostic command unavailable" in errors.getvalue()+ assert broken("convert", "input", "-o", "output")[0] == 0++ calls = []+ def run(argv, **kwargs):+ calls.append(argv)+ assert kwargs["timeout"] <= 15+ if argv[-1] == "/usr/bin/true":+ return subprocess.CompletedProcess(argv, 0, "", "")+ return subprocess.CompletedProcess(argv, 0, "COMMAND PID PPID USER FD TYPE NAME\nmds 4321 1 root 7r DIR /Volumes/Install Hermes Agent\n", "")++ diagnostics.report_detach_failure("/dev/disk25s1", events[2][2], failure[1], run=run, stream=errors)+ text = errors.getvalue()+ assert "mds 4321 1 root 7r" in text+ assert any("+f" in argv and argv[-1] == "/Volumes/Install Hermes Agent" for argv in calls)+ file_query = next(argv for argv in calls if "-f" in argv)+ assert "/tmp/our staging.dmg" in file_query and "/dev/disk24" in file_query+ assert "/dev/disk25s1" in file_query and "/dev/rdisk25s1" in file_query+ assert all("+D" not in argv for argv in calls)++ def timeout(argv, **kwargs):+ if argv[-1] == "/usr/bin/true":+ return subprocess.CompletedProcess(argv, 1, "", "sudo: a password is required")+ raise subprocess.TimeoutExpired(argv, kwargs["timeout"], output=b"partial holder data")++ errors = io.StringIO()+ diagnostics.report_detach_failure("/dev/disk25s1", events[2][2], failure[1], run=timeout, stream=errors)+ assert "unprivileged" in errors.getvalue()+ assert "partial holder data" in errors.getvalue()+ assert "timed out" in errors.getvalue()+++def test_diagnostic_entrypoint_preserves_cli_arguments_and_failure(tmp_path):+ # This package replays the supplier call contract, not a native DMG build.+ package = tmp_path / "dmgbuild"+ package.mkdir()+ (package / "__init__.py").write_text("", encoding="utf-8")+ (package / "core.py").write_text(+ 'def hdiutil(command, *args, **kwargs):\n'+ ' print("fixture native", command, *args, flush=True)\n'+ ' if command == "attach":\n'+ ' return 0, {"system-entities": [{"dev-entry": "/dev/hermes-dmg-fixture-not-a-device"}]}\n'+ ' return (0, "cleanup") if "-force" in args else (16, "Resource busy")\n', encoding="utf-8")+ (package / "__main__.py").write_text(+ 'import json, sys\nfrom . import core\n'+ 'def main():\n'+ ' print(json.dumps(sys.argv[1:]), flush=True)\n'+ ' core.hdiutil("attach", "-nobrowse", "/hermes-dmg-fixture-no-image.dmg")\n'+ ' result = core.hdiutil("detach", "/dev/hermes-dmg-fixture-not-a-device", plist=False)\n'+ ' core.hdiutil("detach", "-force", "/dev/hermes-dmg-fixture-not-a-device", plist=False)\n'+ ' raise SystemExit(result[0])\n', encoding="utf-8")+ args = ["-s", "settings with spaces.json", "Install Hermes Agent", "output.dmg"]+ result = subprocess.run([sys.executable, str(Path(diagnostics.__file__)), *args],+ cwd=tmp_path, env={**os.environ, "PYTHONPATH": str(tmp_path)},+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT,+ text=True, encoding="utf-8", timeout=60)+ assert result.returncode == 16+ assert json.dumps(args) in result.stdout+ assert result.stdout.index("[dmg-detach]") < result.stdout.index("fixture native detach -force")++[email protected]("macos")+def test_native_busy_image_reports_the_process_holding_its_file(tmp_path):+ image, mount = tmp_path.resolve() / "held.dmg", tmp_path.resolve() / "mount"+ mount.mkdir()+ subprocess.run(["/usr/bin/hdiutil", "create", "-size", "16m", "-fs", "HFS+",+ "-volname", "Hermes diagnostic fixture", str(image)],+ check=True, capture_output=True, timeout=60)++ def native(command, *args, plist=True):+ argv = ["/usr/bin/hdiutil", command, *args, *(["-plist"] if plist else [])]+ result = subprocess.run(argv, capture_output=True, timeout=60)+ output = plistlib.loads(result.stdout) if plist and result.returncode == 0 else (result.stdout + result.stderr).decode()+ return result.returncode, output++ log = io.StringIO()+ observed = diagnostics.wrap_hdiutil(native, report=lambda *args: diagnostics.report_detach_failure(*args, stream=log))+ device = None+ try:+ code, info = observed("attach", "-nobrowse", "-mountpoint", str(mount), str(image))+ assert code == 0, info+ device = next(e["dev-entry"] for e in info["system-entities"] if e.get("mount-point"))+ held = mount / "held-open.txt"+ with held.open("w") as handle:+ handle.write("owned test handle\n")+ handle.flush()+ code, output = observed("detach", device, plist=False)+ assert code != 0, "native fixture must reproduce a busy detach"+ report = log.getvalue()+ assert str(os.getpid()) in report+ assert str(held) in report+ assert "COMMAND" in report and "PID" in report+ finally:+ if device:+ subprocess.run(["/usr/bin/hdiutil", "detach", "-force", device], capture_output=True, timeout=60)