Skip to content

Commit 15c8c96

Browse files
committed
fix(macos): size the registration probe to finish the race it waits out
The probe's 5 s ceiling exceeded the healthy open it precedes by an order of magnitude while the case it waits out registers within ~0.75 s. The ceiling now covers the full poll plus the reads ahead of it with measured room (reads cost well under 300 ms together on a healthy host), so a host too loaded to answer within the wait is dropped at the remaining-budget floor instead of holding the open for seconds the race never needs. The batched bundle-identifier read gains a hermetic invariant against the real plutil: one -extract answers for every plist it is named, in argument order, so one call can pair every candidate bundle; the unit fakes cannot carry that proof because they script the rows.
1 parent d6f1e4e commit 15c8c96

2 files changed

Lines changed: 83 additions & 16 deletions

File tree

‎packages/platform-apple/src/os/macos/launch-services-registration.test.ts‎

Lines changed: 77 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
1-
import { afterEach, beforeEach, expect, test, vi } from 'vitest';
1+
import { mkdir, rm, writeFile } from 'node:fs/promises';
2+
import path from 'node:path';
3+
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
24
import { AppError } from '@agent-device/kernel/errors';
3-
import type { ExecResult } from '@agent-device/host-kit/command';
5+
import { runCmd, type ExecResult } from '@agent-device/host-kit/command';
46
import type { HostProcessInfo } from '@agent-device/host-kit/process';
7+
import { mkdtempForTest } from '../../__tests__/tmp-dir.ts';
58

69
vi.mock('node:timers/promises', () => ({ setTimeout: vi.fn(async () => undefined) }));
710
vi.mock('@agent-device/host-kit/process', async (importOriginal) => ({
@@ -366,7 +369,7 @@ test('openBundle spends its budget on reads rather than on a wait with nothing l
366369
// A slow scan on a loaded host: by the time it answers, the probe's shared budget is nearly
367370
// gone. Spending the remainder on a 200 ms sleep and a read killed at 100 ms would spawn tools
368371
// that cannot answer, so the wait is left alone and the open runs.
369-
vi.advanceTimersByTime(4_900);
372+
vi.advanceTimersByTime(2_400);
370373
return { stdout: 'com.example.demo\ncom.ghost.app\n' };
371374
}
372375
return {};
@@ -393,7 +396,7 @@ test('openBundle arms every probe read with only the budget the deadline still a
393396
// be armed with the remainder rather than with its own cap: a read armed above what is left could
394397
// run past the budget that bounds this probe.
395398
if (call.cmd === LAUNCH_SERVICES_TOOL) {
396-
vi.advanceTimersByTime(3_600);
399+
vi.advanceTimersByTime(1_900);
397400
return {};
398401
}
399402
// Neither candidate is the opened bundle, so the wait never starts and the reads stay two.
@@ -405,11 +408,11 @@ test('openBundle arms every probe read with only the budget the deadline still a
405408

406409
expect(calls.map(({ cmd, timeoutMs }) => ({ cmd, timeoutMs }))).toEqual([
407410
{ cmd: LAUNCH_SERVICES_TOOL, timeoutMs: LAUNCH_SERVICES_READ_CAP_MS },
408-
{ cmd: 'plutil', timeoutMs: 1_400 },
411+
{ cmd: 'plutil', timeoutMs: 600 },
409412
{ cmd: 'open', timeoutMs: undefined },
410413
]);
411414
// The process-table read is the other seam this probe arms, and it is the one whose cap is largest.
412-
expect(listHostProcesses).toHaveBeenCalledWith({ timeoutMs: 1_400 });
415+
expect(listHostProcesses).toHaveBeenCalledWith({ timeoutMs: 600 });
413416
expect(mockSleep).not.toHaveBeenCalled();
414417
});
415418

@@ -421,7 +424,7 @@ test('openBundle skips a read whose share of the budget falls below what a tool
421424
// answer in time, and a zero timeout turns into no timer at all, which is how a probe that is
422425
// meant to be bounded would stop bounding itself.
423426
if (call.cmd === LAUNCH_SERVICES_TOOL) {
424-
vi.advanceTimersByTime(4_950);
427+
vi.advanceTimersByTime(2_450);
425428
return {};
426429
}
427430
return call.cmd === 'plutil' ? { stdout: 'com.example.demo\ncom.ghost.app\n' } : {};
@@ -577,3 +580,70 @@ test('openBundle reports a probe that failed for a reason no typed code describe
577580
}),
578581
);
579582
});
583+
584+
// `plutil -extract` answers one `-extract` for every plist it is given, in argument order, so one
585+
// call can name every candidate bundle. This pins that batched shape against the real tool: a
586+
// candidate set the probe cannot pair with the rows it gets back ends the whole fix, and scripted
587+
// rows above cannot prove the tool actually behaves that way.
588+
describe.skipIf(process.platform !== 'darwin')(
589+
'bundle identifier reads against the real plutil',
590+
() => {
591+
test('openBundle names every candidate plist in one real batch and waits on its own pid', async () => {
592+
// Three bundles written to disk, the opened target second and under a name with a space.
593+
// Their plists are real; only their being "running" is the mocked process table.
594+
const root = await mkdtempForTest('ad-3406-plutil-batch-');
595+
const bundle = async (name: string, bundleId: string): Promise<string> => {
596+
const bundlePath = path.join(root, name);
597+
await mkdir(path.join(bundlePath, 'Contents'), { recursive: true });
598+
await writeFile(
599+
path.join(bundlePath, 'Contents', 'Info.plist'),
600+
'<?xml version="1.0" encoding="UTF-8"?>\n' +
601+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" ' +
602+
'"http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n' +
603+
'<plist version="1.0"><dict><key>CFBundleIdentifier</key>' +
604+
`<string>${bundleId}</string></dict></plist>\n`,
605+
);
606+
return bundlePath;
607+
};
608+
const other = await bundle('Other.app', 'com.example.other');
609+
const target = await bundle('My Target.app', BUNDLE_ID);
610+
const spaced = await bundle('Late Night.app', 'com.example.late-night');
611+
processTable.rows = [
612+
{ pid: 4300, command: `${other}/Contents/MacOS/Other` },
613+
{ pid: 4242, command: `${target}/Contents/MacOS/My Target -ProofFlag` },
614+
{ pid: 4301, command: `${spaced}/Contents/MacOS/Late Night` },
615+
] satisfies HostProcessInfo[];
616+
617+
let pidPinnedReads = 0;
618+
// plutil runs for real through the exec seam. The LaunchServices view and `open` itself stay
619+
// scripted: an unlisted-then-listed registration cannot be arranged with a real bundle that
620+
// is not actually running, and a real `open` would launch a real copy.
621+
const runCommand: AppleToolCommandExecutor = async (cmd, args, options) => {
622+
if (cmd === 'open') return { exitCode: 0, stdout: '', stderr: '' };
623+
if (cmd === LAUNCH_SERVICES_TOOL) {
624+
if (!args.some((arg) => arg.startsWith('pid='))) {
625+
return { exitCode: 0, stdout: '', stderr: '' };
626+
}
627+
pidPinnedReads += 1;
628+
return {
629+
exitCode: 0,
630+
stdout: pidPinnedReads > 1 ? 'ASN:0x0-0x1234-"My Target":\n' : '',
631+
stderr: '',
632+
};
633+
}
634+
return await runCmd(cmd, args, options);
635+
};
636+
637+
try {
638+
await openBundle(runCommand);
639+
640+
// The copy is found only if the real batch paired its row with its path among three, so
641+
// the wait ran and ended on the target's own pid rather than the open going out blind.
642+
expect(pidPinnedReads).toBe(2);
643+
expect(mockSleep).toHaveBeenCalledTimes(2);
644+
} finally {
645+
await rm(root, { recursive: true, force: true });
646+
}
647+
}, 10_000);
648+
},
649+
);

‎packages/platform-apple/src/os/macos/launch-services-registration.ts‎

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,13 @@ const LAUNCH_SERVICES_READ_TIMEOUT_MS = 1_000;
1717
const PROCESS_TABLE_TIMEOUT_MS = 2_000;
1818
const BUNDLE_ID_READ_TIMEOUT_MS = 1_500;
1919
/**
20-
* Ceiling for the whole probe, shared by every read below. AGENTS.md asks an optional probe's
21-
* budget to stay shorter than the operation it precedes, and this one exceeds a healthy `open -b`
22-
* (~70 ms measured) on purpose — see the PR #3707 discussion: the operation this probe guards is
23-
* the open REQUEST, which runs inside the command registry's 90 s envelope, and the probe's own
24-
* worst case is bounded at this ceiling with every read failing open. The measured typical cost
25-
* is what makes that trade proportionate: one `lsappinfo find` (12-40 ms) plus one process-table
26-
* read (~0.2-0.3 s on a healthy host), and the 5 s ceiling is only ever reached when a host tool
27-
* hangs — the open then proceeds late rather than being withheld.
20+
* Ceiling for the whole probe, shared by every read below. It has to exceed the full wait plus
21+
* the reads ahead of it — registration lands 0.5-0.75 s after a direct spawn — or the probe gives
22+
* up on the only case it exists for; the reads themselves fit the remainder with room on a healthy
23+
* host. AGENTS.md sizes a probe budget against the operation it precedes: the cost tradeoff of
24+
* this one against `open -b` is measured and argued in PR #3707.
2825
*/
29-
const LAUNCH_SERVICES_PROBE_BUDGET_MS = 5_000;
26+
const LAUNCH_SERVICES_PROBE_BUDGET_MS = 2_500;
3027
/**
3128
* Below this remaining budget a read is worth skipping rather than spawning with a token amount. It
3229
* is also what keeps every read bounded: the exec seam turns a zero timeout into no timer at all, so

0 commit comments

Comments
 (0)