The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): script marker-helper runner and hand-off protocol negotiation
Tekniumdfa539fa9920
diff --git a/apps/desktop/electron/updater/marker-helper.test-helpers.ts b/apps/desktop/electron/updater/marker-helper.test-helpers.tsnew file mode 100644index 00000000000..c6b95df2f81--- /dev/null+++ b/apps/desktop/electron/updater/marker-helper.test-helpers.ts@@ -0,0 +1,55 @@+/** A checkout with a REAL fake hand-off script that answers marker-helper ops. */++import fs from 'fs'+import os from 'os'+import path from 'path'++const roots: string[] = []++/** Call from afterEach. */+export function cleanupFakeCheckouts(): void {+ for (const root of roots.splice(0)) {+ fs.rmSync(root, { recursive: true, force: true })+ }+}++/** A scratch directory removed by cleanupFakeCheckouts. */+export function scratchRoot(tag: string): string {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), `${tag}-`))+ roots.push(root)++ return root+}++/**+ * Text of a REAL fake hand-off script: it records its argv to+ * `$HERMES_HOME/helper-calls.log`, prints the verdict staged in+ * `$HERMES_HOME/helper-verdict`, exits with `$HERMES_HOME/helper-exit`+ * (default 0), and — like the real helper — removes the marker when it+ * answers `reclaimed`/`withdrawn`.+ */+export function fakeHelperScript(protocolLine = '# hermes-handoff-protocol: 2'): string {+ return [+ '#!/usr/bin/env bash',+ protocolLine,+ 'printf "%s\\n" "$*" >> "$HERMES_HOME/helper-calls.log"',+ 'if [ "$1" != "--marker-op" ]; then exit 3; fi',+ '[ -f "$HERMES_HOME/helper-sleep" ] && sleep "$(cat "$HERMES_HOME/helper-sleep")"',+ 'verdict="$(cat "$HERMES_HOME/helper-verdict" 2>/dev/null)"',+ 'case "$verdict" in reclaimed|withdrawn) rm -f "$HERMES_HOME/.hermes-update-in-progress" ;; esac',+ 'printf "%s\\n" "$verdict"',+ 'exit "$(cat "$HERMES_HOME/helper-exit" 2>/dev/null || echo 0)"',+ ''+ ].join('\n')+}++/** A checkout whose posix.sh is `fakeHelperScript`. */+export function fakeHelperCheckout(protocolLine = '# hermes-handoff-protocol: 2'): { root: string; home: string } {+ const root = scratchRoot('marker-helper')+ const home = path.join(root, 'home')+ fs.mkdirSync(home)+ fs.mkdirSync(path.join(root, 'scripts', 'desktop-update'), { recursive: true })+ fs.writeFileSync(path.join(root, 'scripts', 'desktop-update', 'posix.sh'), fakeHelperScript(protocolLine))++ return { root, home }+}diff --git a/apps/desktop/electron/updater/marker-helper.test.ts b/apps/desktop/electron/updater/marker-helper.test.tsnew file mode 100644index 00000000000..90f59bd1282--- /dev/null+++ b/apps/desktop/electron/updater/marker-helper.test.ts@@ -0,0 +1,194 @@+/**+ * The checkout script's marker helper (A7 rule 3, SPEC section 6): protocol+ * negotiation from the script text, the exact command line, and the one-line+ * verdict — exercised against a REAL fake script process (bash), with the+ * spawn injected only to pin the Windows command line on a POSIX host.+ */++import fs from 'fs'+import assert from 'node:assert/strict'+import os from 'os'+import path from 'path'++import { afterEach, describe, test } from 'vitest'++import {+ type HelperSpawn,+ markerHelperCommand,+ parseMarkerHelperVerdict,+ readHandoffProtocol,+ runMarkerHelper+} from './marker-helper'+import { cleanupFakeCheckouts, fakeHelperCheckout, scratchRoot } from './marker-helper.test-helpers'++afterEach(cleanupFakeCheckouts)++describe('protocol negotiation', () => {+ test.each([+ ['exact protocol 2 line', '#!/bin/sh\n# hermes-handoff-protocol: 2\n', 2],+ ['trailing whitespace', '# hermes-handoff-protocol: 2 \r\n', 2],+ ['a later protocol', 'x\n# hermes-handoff-protocol: 3\n', 3],+ ['protocol 1 is legacy', '# hermes-handoff-protocol: 1\n', 1],+ ['no line (origin/main scripts)', '#!/usr/bin/env bash\necho hi\n', 1],+ ['indented line does not count', ' # hermes-handoff-protocol: 2\n', 1],+ ['mid-line mention does not count', 'echo "# hermes-handoff-protocol: 2"\n', 1],+ ['two spaces after the colon', '# hermes-handoff-protocol: 2\n', 1]+ ])('%s', (_label, text, expected) => {+ const file = path.join(fakeHelperCheckout().root, 'script.sh')+ fs.writeFileSync(file, text)++ assert.equal(readHandoffProtocol(file), expected)+ })++ test('a missing script is legacy', () => {+ assert.equal(readHandoffProtocol(path.join(os.tmpdir(), 'no-such-script.sh')), 1)+ assert.equal(readHandoffProtocol(null), 1)+ })+})++test.each([+ ['absent', { kind: 'absent' }],+ ['reclaimed\n', { kind: 'reclaimed' }],+ ['held', { kind: 'held' }],+ ['busy', { kind: 'busy' }],+ ['withdrawn\r\n', { kind: 'withdrawn' }],+ ['foreign', { kind: 'foreign' }],+ ['live 4242', { kind: 'live', pid: 4242 }],+ ['taken 77\n', { kind: 'taken', pid: 77 }],+ ['live', { kind: 'unsupported' }],+ ['taken x', { kind: 'unsupported' }],+ ['taken 0', { kind: 'unsupported' }],+ ['held 5', { kind: 'unsupported' }],+ ['reclaimed\nheld', { kind: 'unsupported' }],+ ['usage: posix.sh [--branch B]', { kind: 'unsupported' }],+ ['', { kind: 'unsupported' }]+])('verdict line %j', (stdout, expected) => {+ assert.deepEqual(parseMarkerHelperVerdict(stdout), expected)+})++describe.skipIf(process.platform === 'win32')('runMarkerHelper against a real script process', () => {+ test.each([+ ['reclaimed', { kind: 'reclaimed' }],+ ['held', { kind: 'held' }],+ ['live 31337', { kind: 'live', pid: 31337 }],+ ['taken 99', { kind: 'taken', pid: 99 }],+ ['withdrawn', { kind: 'withdrawn' }]+ ])('prints %j', async (verdict, expected) => {+ const { root, home } = fakeHelperCheckout()+ fs.writeFileSync(path.join(home, 'helper-verdict'), verdict)++ const got = await runMarkerHelper('withdraw', {+ updateRoot: root,+ hermesHome: home,+ desktopPid: 4242,+ runId: 'desk-4242-abc-0001',+ isWindows: false+ })++ assert.deepEqual(got, expected)+ assert.equal(+ fs.readFileSync(path.join(home, 'helper-calls.log'), 'utf8'),+ `--marker-op withdraw --install-root ${root} --desktop-pid 4242 --handoff-run desk-4242-abc-0001\n`,+ 'exact argv, and HERMES_HOME reached the script'+ )+ })++ test('reclaim without a desktop pid or run passes neither flag', async () => {+ const { root, home } = fakeHelperCheckout()+ fs.writeFileSync(path.join(home, 'helper-verdict'), 'absent')++ assert.deepEqual(await runMarkerHelper('reclaim', { updateRoot: root, hermesHome: home, isWindows: false }), {+ kind: 'absent'+ })+ assert.equal(fs.readFileSync(path.join(home, 'helper-calls.log'), 'utf8'), `--marker-op reclaim --install-root ${root}\n`)+ })++ test.each([+ ['usage exit 64 (old checkout rejects --marker-op)', '64', 'reclaimed'],+ ['nonzero exit even with a verdict', '1', 'reclaimed'],+ ['garbage output', '0', 'sure, done'],+ ['two lines', '0', 'reclaimed\nheld']+ ])('%s => unsupported', async (_label, exit, verdict) => {+ const { root, home } = fakeHelperCheckout()+ fs.writeFileSync(path.join(home, 'helper-verdict'), verdict)+ fs.writeFileSync(path.join(home, 'helper-exit'), exit)++ assert.deepEqual(await runMarkerHelper('reclaim', { updateRoot: root, hermesHome: home, isWindows: false }), {+ kind: 'unsupported'+ })+ })++ test('a helper past its timeout is killed and unsupported', async () => {+ const { root, home } = fakeHelperCheckout()+ fs.writeFileSync(path.join(home, 'helper-verdict'), 'reclaimed')+ fs.writeFileSync(path.join(home, 'helper-sleep'), '5')+ const started = Date.now()++ assert.deepEqual(+ await runMarkerHelper('reclaim', { updateRoot: root, hermesHome: home, isWindows: false, timeoutMs: 300 }),+ { kind: 'unsupported' }+ )+ assert.ok(Date.now() - started < 4000, 'bounded by the timeout')+ })++ test('a checkout without the script is unsupported', async () => {+ const root = scratchRoot('marker-helper-none')++ assert.deepEqual(await runMarkerHelper('reclaim', { updateRoot: root, hermesHome: root, isWindows: false }), {+ kind: 'unsupported'+ })+ })+})++test('the Windows command line: powershell -File windows.ps1 -MarkerOp ... (hidden, HERMES_HOME set)', async () => {+ const root = scratchRoot('marker-helper-win')+ const script = path.join(root, 'scripts', 'desktop-update', 'windows.ps1')+ fs.mkdirSync(path.dirname(script), { recursive: true })+ fs.writeFileSync(script, '# hermes-handoff-protocol: 2\n')+ const calls: Parameters<HelperSpawn>[] = []++ const spawn: HelperSpawn = async (...args) => {+ calls.push(args)++ return { code: 0, stdout: 'taken 4040\r\n' }+ }++ const got = await runMarkerHelper('withdraw', {+ updateRoot: root,+ hermesHome: path.join(root, 'home'),+ desktopPid: 12,+ runId: 'desk-12-a-beef',+ isWindows: true,+ spawn+ })++ assert.deepEqual(got, { kind: 'taken', pid: 4040 })+ assert.equal(calls.length, 1)+ const [command, args, options] = calls[0]+ assert.equal(command, 'powershell.exe')+ assert.deepEqual(args, [+ '-NoProfile',+ '-NonInteractive',+ '-ExecutionPolicy',+ 'Bypass',+ '-File',+ script,+ '-MarkerOp',+ 'withdraw',+ '-InstallRoot',+ root,+ '-DesktopPid',+ '12',+ '-HandoffRun',+ 'desk-12-a-beef'+ ])+ assert.equal(options.env.HERMES_HOME, path.join(root, 'home'))+ assert.equal(options.windowsHide, true)+ assert.equal(options.timeout, 20_000)+ assert.deepEqual(markerHelperCommand('reclaim', script, { updateRoot: root, isWindows: true }).args.slice(-4), [+ '-MarkerOp',+ 'reclaim',+ '-InstallRoot',+ root+ ])+})diff --git a/apps/desktop/electron/updater/marker-helper.ts b/apps/desktop/electron/updater/marker-helper.tsnew file mode 100644index 00000000000..35813200e2e--- /dev/null+++ b/apps/desktop/electron/updater/marker-helper.ts@@ -0,0 +1,228 @@+/**+ * The checkout script's marker helper (A7 rule 3, SPEC section 6): Electron's+ * ONLY way to mutate the update marker. The script holds the `<marker>.lock`+ * kernel lock for the whole read-judge-mutate; Node has no portable kernel+ * lock, so Electron never deletes or rewrites the marker itself.+ *+ * posix: bash <root>/scripts/desktop-update/posix.sh --marker-op <op> --install-root <root>+ * [--desktop-pid P] [--handoff-run R]+ * Windows: powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File windows.ps1+ * -MarkerOp <op> -InstallRoot <root> [-DesktopPid P] [-HandoffRun R]+ *+ * One stdout line: `absent | reclaimed | held | busy | live <pid> | withdrawn |+ * taken <pid> | foreign`. Anything else, a nonzero exit, a timeout or a+ * missing script is `unsupported` (an older checkout).+ */++import { type ChildProcess, spawn } from 'node:child_process'+import { existsSync, readFileSync } from 'node:fs'+import * as path from 'node:path'++import { resolveUpdateScriptHandoff } from '../updater-process'++export type MarkerHelperOp = 'reclaim' | 'withdraw'++export type MarkerHelperVerdict =+ | { kind: 'absent' | 'reclaimed' | 'held' | 'busy' | 'withdrawn' | 'foreign' | 'unsupported' }+ | { kind: 'live' | 'taken'; pid: number }++export const MARKER_HELPER_TIMEOUT_MS = 20_000++/** The protocol line a hand-off script advertises (SPEC 4). */+const PROTOCOL_RE = /^# hermes-handoff-protocol: (\d+)\s*$/m++export interface HelperSpawnResult {+ /** Exit code; null when killed (timeout) or the spawn failed. */+ code: number | null+ stdout: string+}++export type HelperSpawn = (+ command: string,+ args: string[],+ options: { env: NodeJS.ProcessEnv; timeout: number; windowsHide: boolean }+) => Promise<HelperSpawnResult>++export interface MarkerHelperOptions {+ updateRoot: string+ hermesHome: string+ desktopPid?: number | null+ runId?: string | null+ isWindows: boolean+ spawn?: HelperSpawn+ timeoutMs?: number+}++/** The checkout's hand-off script, or null when the checkout predates it. */+export function handoffScriptPath(updateRoot: string, isWindows: boolean): string | null {+ if (isWindows) {+ return resolveUpdateScriptHandoff(updateRoot, { isWindows: true })?.scriptPath ?? null+ }++ const posix = path.join(updateRoot, 'scripts', 'desktop-update', 'posix.sh')++ return existsSync(posix) ? posix : null+}++/** Hand-off protocol a script speaks: 2+ from its protocol line, else 1 (legacy). */+export function readHandoffProtocol(scriptPath: string | null | undefined): number {+ if (!scriptPath) {+ return 1+ }++ try {+ const match = PROTOCOL_RE.exec(readFileSync(scriptPath, 'utf8'))+ const version = match ? Number(match[1]) : 1++ return Number.isSafeInteger(version) && version >= 2 ? version : 1+ } catch {+ return 1+ }+}++/**+ * Spawn the helper and collect stdout, hard-bounded by `timeout`: on POSIX the+ * helper runs in its own process group and the whole group is killed on+ * timeout, so a stuck grandchild holding the pipe cannot extend the wait.+ */+const defaultSpawn: HelperSpawn = (command, args, { env, timeout, windowsHide }) =>+ new Promise(resolve => {+ const posix = process.platform !== 'win32'+ let stdout = ''+ let settled = false+ let timer: ReturnType<typeof setTimeout> | undefined++ const finish = (code: number | null) => {+ if (!settled) {+ settled = true+ clearTimeout(timer)+ resolve({ code, stdout })+ }+ }++ let child: ChildProcess++ try {+ child = spawn(command, args, { env, windowsHide, detached: posix, stdio: ['ignore', 'pipe', 'ignore'] })+ } catch {+ finish(null)++ return+ }++ child.stdout?.setEncoding('utf8')+ child.stdout?.on('data', (chunk: string) => {+ if (stdout.length < 64 * 1024) {+ stdout += chunk+ }+ })+ child.on('error', () => finish(null))+ child.on('close', code => finish(typeof code === 'number' ? code : null))+ timer = setTimeout(() => {+ try {+ if (posix && child.pid) {+ process.kill(-child.pid, 'SIGKILL')+ } else {+ child.kill()+ }+ } catch {+ // Already gone.+ }++ finish(null)+ }, timeout)+ })++const BARE_VERDICTS = new Set(['absent', 'reclaimed', 'held', 'busy', 'withdrawn', 'foreign'])++/** Parse the helper's one verdict line; anything else is `unsupported`. */+export function parseMarkerHelperVerdict(stdout: string): MarkerHelperVerdict {+ const lines = stdout.split(/\r?\n/).map(line => line.trim()).filter(Boolean)++ if (lines.length !== 1) {+ return { kind: 'unsupported' }+ }++ const [word, arg, ...extra] = lines[0].split(/\s+/)++ if (extra.length) {+ return { kind: 'unsupported' }+ }++ if (arg === undefined) {+ return BARE_VERDICTS.has(word) ? ({ kind: word } as MarkerHelperVerdict) : { kind: 'unsupported' }+ }++ const pid = /^\d+$/.test(arg) ? Number(arg) : NaN++ if ((word === 'live' || word === 'taken') && Number.isSafeInteger(pid) && pid > 0) {+ return { kind: word, pid }+ }++ return { kind: 'unsupported' }+}++/** The exact command line for one helper op (exported for tests). */+export function markerHelperCommand(+ op: MarkerHelperOp,+ scriptPath: string,+ { updateRoot, desktopPid, runId, isWindows }: Pick<MarkerHelperOptions, 'updateRoot' | 'desktopPid' | 'runId' | 'isWindows'>+): { command: string; args: string[] } {+ const hasPid = typeof desktopPid === 'number' && Number.isInteger(desktopPid) && desktopPid > 0++ if (isWindows) {+ return {+ command: 'powershell.exe',+ args: [+ '-NoProfile',+ '-NonInteractive',+ '-ExecutionPolicy',+ 'Bypass',+ '-File',+ scriptPath,+ '-MarkerOp',+ op,+ '-InstallRoot',+ updateRoot,+ ...(hasPid ? ['-DesktopPid', String(desktopPid)] : []),+ ...(runId ? ['-HandoffRun', runId] : [])+ ]+ }+ }++ return {+ command: 'bash',+ args: [+ scriptPath,+ '--marker-op',+ op,+ '--install-root',+ updateRoot,+ ...(hasPid ? ['--desktop-pid', String(desktopPid)] : []),+ ...(runId ? ['--handoff-run', runId] : [])+ ]+ }+}++/** Run one marker op through the checkout's script under its sidecar lock. */+export async function runMarkerHelper(op: MarkerHelperOp, options: MarkerHelperOptions): Promise<MarkerHelperVerdict> {+ const scriptPath = handoffScriptPath(options.updateRoot, options.isWindows)++ if (!scriptPath) {+ return { kind: 'unsupported' }+ }++ const { command, args } = markerHelperCommand(op, scriptPath, options)++ try {+ const result = await (options.spawn ?? defaultSpawn)(command, args, {+ env: { ...process.env, HERMES_HOME: options.hermesHome },+ timeout: options.timeoutMs ?? MARKER_HELPER_TIMEOUT_MS,+ windowsHide: true+ })++ return result.code === 0 ? parseMarkerHelperVerdict(result.stdout) : { kind: 'unsupported' }+ } catch {+ return { kind: 'unsupported' }+ }+}