Skip to content

Commit 4c2ae0c

Browse files
authored
feat(cli): open --wait, flag suggestions, and refusals that name what to run (#2665)
* fix(cli): name the flag an unknown guess was reaching for --output and --path are the spellings an agent reaches for before reading the synopsis, and the refusal only said "Unknown flag". Suggestions now come from the live flag registry filtered by what the command in scope accepts, so a guess is never answered with a flag that command would refuse: "trace start --path" keeps the bare refusal, while "screenshot --output" is pointed at --out. * feat(cli): open --wait <ms> queues for a device another session holds A device another workspace's session is holding refused at once, leaving the caller to poll by hand, and the foreign-workspace refusal named a session its `--session` value could not reach. `open --wait <ms>` spends a budget on that contention before the request takes the device's execution lock, which is the whole design: `close`, `record stop` and every other operation that could free the device need the same lock, so an open that waited while holding it would have blocked its own recovery. Verified on a live emulator — a waiting open now lets a competing `close` return in 0.1s and opens the device itself once the holder is gone; the first attempt at a daemon-side wait inside the lock stalled that close for the full budget. The refusal that ends a spent budget names the owning session address, says the wait happened and does not offer it again, while a refusal from a command that cannot wait never mentions the flag. The budget extends the command's timeout envelope rather than eating into it, so a long wait cannot end in a client-side daemon reset. * fix(ios): say what a non-macOS host can drive instead of refusing "Apple tools are only available on macOS" is true and useless to a caller on Linux that just wants its app driven: it reads as a missing install, and `retriable` was unset so replay could retry it. The refusal now carries `supportedOn`, the observed `hostOs`, `retriable: false`, and a hint naming the Android commands for the same workflow plus the remote-Mac-daemon route. * fix(daemon): let a waiting open re-wait when the device is retaken An `--wait` budget ended as soon as no session held the device, but nothing reserved the device until the request took its execution lock, so two waiters could both see one free device and the loser refused with most of its budget left. The open now looks at the device again under its own locks, hands them back when another session took it in that window, and waits for what remains of its budget. The recorded spend moves to that same look, so only a budget that ran out with a holder visible reports a spent wait, and a refusal stops offering `--wait` to a caller that arrived carrying it. The target device is resolved once, as part of the request's execution-lock plan, and contention is polled in the session store alone. A budget that reaches the daemon anywhere but through the CLI is now checked against the bounds the option declares, which the Node client never enforced. * fix(daemon): refuse an unspendable open --wait budget before device work Reading the budget after the target device was resolved left a hole: an open whose device could not be resolved never reached the bounds check, so a Node client or a raw wire request carrying `waitMs: 5000000` passed the check the CLI parser would have applied and went looking for a device with a budget it could not spend. The budget is now the first thing the wait reads. * test(daemon): prove the open contention guard decides the race The race test's open task bound the device unconditionally, so adding an `open --wait` budget to the current execution locks would allow all old checks to be demonstrated. The task refuses with the same fact the real open does. Out-of-range `waitMs` budgets fail before any device work. * refactor(daemon): tighten the open-wait request seams The request scope now parses the `waitMs` option once and supplies the resulting budget to the wait, instead of validating it before the device lookup and reading it again afterward. The reader fails closed when a caller supplies a budget but its option declaration has gone missing. The refusal helper checks the command directly, so reuse outside the open path cannot offer `--wait` to an interaction.
1 parent 33d48a1 commit 4c2ae0c

28 files changed

Lines changed: 1318 additions & 83 deletions

‎packages/command-registry/src/flag-definitions-workflow.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,20 @@ export const WORKFLOW_FLAG_DEFINITIONS: readonly FlagDefinition[] = [
8989
projectConfig: true,
9090
recorded: false,
9191
},
92+
{
93+
key: 'waitMs',
94+
names: ['--wait'],
95+
type: 'int',
96+
min: 100,
97+
max: 120000,
98+
usageLabel: '--wait <ms>',
99+
usageDescription:
100+
'Open: wait up to n ms for a device another session is holding before failing with DEVICE_IN_USE',
101+
inputDescription:
102+
"Block this open for up to n milliseconds (100-120000) while another session holds the device, then fail with DEVICE_IN_USE naming that session. Only session contention is waited for: a device claim held by another workspace is refused at once with its recovery command. A device that never frees, or is taken again while this open waits, costs the full budget, which extends this command's timeout envelope rather than eating into it.",
103+
projectConfig: false,
104+
recorded: false,
105+
},
92106
{
93107
key: 'retries',
94108
names: ['--retries'],

‎packages/command-registry/src/timeout-policy.ts‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ type BoundedTimeoutPolicy = CommandTimeoutPolicy & { envelopeMs: number };
4646
type FlagTimeoutBudget = Extract<CommandTimeoutBudget, { source: 'flag' }>;
4747
type RequestTimeoutInput = Readonly<{
4848
positionals?: string[];
49-
flags?: Readonly<{ timeoutMs?: number; settle?: boolean }>;
49+
flags?: Readonly<{ timeoutMs?: number; settle?: boolean; waitMs?: number }>;
5050
}>;
5151

5252
/** Resolves the request envelope from its declared policy and user-supplied budget. */
@@ -81,13 +81,30 @@ function resolveFlagBudgetTimeoutMs(
8181
return resolveWideningFlagBudget(policy, policy.budget, flags);
8282
}
8383
if (policy.budget.envelope === 'margin') {
84-
return typeof flags?.timeoutMs === 'number'
85-
? widenToUserBudget(policy, flags.timeoutMs)
86-
: policy.envelopeMs;
84+
return resolveMarginEnvelopeTimeoutBudget(policy, flags);
8785
}
8886
return typeof flags?.timeoutMs === 'number' ? flags.timeoutMs : policy.envelopeMs;
8987
}
9088

89+
/**
90+
* The `--timeout` budget, widened again for a `--wait` budget. A wait is work the command does
91+
* before its own startup budget can even begin — the device is still somebody else's — so it
92+
* extends the envelope rather than eating into it. With no wait this is exactly the margin
93+
* envelope `--timeout` has always produced.
94+
*/
95+
function resolveMarginEnvelopeTimeoutBudget(
96+
policy: BoundedTimeoutPolicy,
97+
flags: RequestTimeoutInput['flags'],
98+
): number {
99+
const startupEnvelopeMs =
100+
typeof flags?.timeoutMs === 'number'
101+
? widenToUserBudget(policy, flags.timeoutMs)
102+
: policy.envelopeMs;
103+
return typeof flags?.waitMs === 'number'
104+
? widenPastBaseEnvelope({ ...policy, envelopeMs: startupEnvelopeMs }, flags.waitMs)
105+
: startupEnvelopeMs;
106+
}
107+
91108
function resolveWideningFlagBudget(
92109
policy: BoundedTimeoutPolicy,
93110
budget: FlagTimeoutBudget,

‎packages/contracts/src/cli-flags.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ export type CliFlags = CloudProviderProfileFields &
145145
record?: boolean;
146146
retainPaths?: boolean;
147147
retentionMs?: number;
148+
waitMs?: number;
148149
replayMaestro?: boolean;
149150
reporter?: string[];
150151
reportJunit?: string;

‎packages/contracts/src/client-app.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,14 @@ export type AppOpenOptions = AgentDeviceRequestOverrides &
6868
relaunch?: boolean;
6969
/** Startup budget in milliseconds: bounds the Simulator boot wait on a cold device. */
7070
timeoutMs?: number;
71+
/**
72+
* Block this open for up to n milliseconds (100-120000) while another session holds the device,
73+
* then fail with DEVICE_IN_USE naming that session. Only session contention is waited for: a
74+
* device claim held by another workspace is refused at once with its recovery command. A device
75+
* that never frees, or is taken again while this open waits, costs the full budget, which
76+
* extends this command's timeout envelope rather than eating into it.
77+
*/
78+
waitMs?: number;
7179
// Editor documentation for a public type: a `.d.ts` is read where no
7280
// FlagDefinition resolves, and nothing generates these docs. It is not a second
7381
// statement of what the option does — it is the option's ONE declaration (the

‎packages/platform-apple/src/inventory.test.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,35 @@ test('Apple inventory rejects unsupported hosts and missing tools with typed err
5151
);
5252
});
5353

54+
test('the non-macOS refusal names what this host can drive instead', async () => {
55+
const refusal = await createAppleInventorySource(createInventoryHost({ hostOs: 'linux' }))
56+
.discover({ platform: 'ios' }, inventoryScope)
57+
.catch((error: unknown) => error);
58+
59+
assert.ok(refusal instanceof AppError);
60+
assert.equal(refusal.code, 'UNSUPPORTED_PLATFORM');
61+
assert.equal(refusal.details?.supportedOn, 'macOS');
62+
assert.equal(refusal.details?.hostOs, 'linux');
63+
assert.equal(refusal.details?.retriable, false);
64+
const hint = String(refusal.details?.hint);
65+
assert.match(hint, /runs Linux/);
66+
assert.match(hint, /agent-device devices --platform android/);
67+
assert.match(hint, /agent-device open <app\.apk> --platform android/);
68+
assert.match(hint, /--daemon-base-url/);
69+
});
70+
71+
// The label is what makes the refusal readable, and an unmapped host must still refuse
72+
// rather than render `undefined`.
73+
test('every host operating system renders a readable refusal', async () => {
74+
for (const hostOs of ['win32', 'other'] as const) {
75+
const refusal = await createAppleInventorySource(createInventoryHost({ hostOs }))
76+
.discover({ platform: 'ios' }, inventoryScope)
77+
.catch((error: unknown) => error);
78+
assert.ok(refusal instanceof AppError);
79+
assert.match(String(refusal.details?.hint), /runs (Windows|a non-macOS host),/);
80+
}
81+
});
82+
5483
test('simulator-only inventory avoids physical discovery and observes fresh booted devices', async () => {
5584
const calls: string[][] = [];
5685
const observed: string[] = [];

‎packages/platform-apple/src/inventory.ts‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { DeviceInventoryRequest } from '@agent-device/contracts/device';
22
import type {
33
DeviceInventoryHostFor,
4+
HostOperatingSystem,
45
PlatformRequestScope,
56
} from '@agent-device/contracts/platform-runtime-host';
67
import type { DeviceInventorySource } from '@agent-device/contracts/platform-module';
@@ -26,7 +27,7 @@ async function discoverAppleDevices(
2627
return [hostMacDevice(host)];
2728
}
2829
if (host.hostOs !== 'darwin') {
29-
throw new AppError('UNSUPPORTED_PLATFORM', 'Apple tools are only available on macOS');
30+
throw appleHostUnsupportedError(host.hostOs);
3031
}
3132
if (!(await host.appleTools.isXcrunAvailable(scope.signal))) {
3233
throw new AppError('TOOL_MISSING', 'xcrun not found in PATH');
@@ -59,6 +60,33 @@ function isMacOnlyRequest(request: Readonly<DeviceInventoryRequest>): boolean {
5960
);
6061
}
6162

63+
const HOST_OS_LABELS: Record<HostOperatingSystem, string> = {
64+
darwin: 'macOS',
65+
linux: 'Linux',
66+
win32: 'Windows',
67+
other: 'a non-macOS host',
68+
};
69+
70+
/**
71+
* The refusal a non-macOS host gets for Apple sessions. Naming only the requirement left
72+
* Linux and Windows callers at a dead end — the host OS never changes for a running
73+
* daemon, so there is nothing to retry and nothing to install here. The hint carries the
74+
* Android shape of the same request, which is what this host can drive, and the one way
75+
* to reach a real iOS Simulator from here: a daemon running on a Mac.
76+
*/
77+
function appleHostUnsupportedError(hostOs: HostOperatingSystem): AppError {
78+
return new AppError('UNSUPPORTED_PLATFORM', 'Apple tools are only available on macOS', {
79+
supportedOn: 'macOS',
80+
hostOs,
81+
retriable: false,
82+
hint:
83+
`This host runs ${HOST_OS_LABELS[hostOs]}, so it cannot boot iOS Simulators or run macOS sessions. ` +
84+
'Drive Android here instead with the same command shape: agent-device devices --platform android to list ' +
85+
'targets, then agent-device open <app.apk> --platform android. To use an iOS Simulator from this machine, ' +
86+
'run agent-device on a macOS host and pass --daemon-base-url <that daemon URL>.',
87+
});
88+
}
89+
6290
function hostMacDevice(host: DeviceInventoryHostFor<'apple'>): DeviceInfo {
6391
return {
6492
platform: 'apple',

‎scripts/integration-progress-model.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -347,6 +347,14 @@ function summarizeProviderScenarioFlagExclusions() {
347347
owner: 'daemon session-open-foreground lifecycle unit tests',
348348
keys: ['foreground'],
349349
},
350+
{
351+
// Contention is this daemon's session store and this host's device-claim files. A
352+
// provider scenario allocates a device of its own, so no provider-backed flow can be
353+
// refused as busy and there is nothing for a scenario lane to observe.
354+
name: 'local device contention waiting',
355+
owner: 'daemon session-open contention unit tests',
356+
keys: ['waitMs'],
357+
},
350358
{
351359
name: 'Apple simulator screenshot rendering options',
352360
owner: 'iOS platform and screenshot-diff runtime tests',

‎src/__tests__/command-descriptor-timeout-policy.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,4 +364,38 @@ test('open and prepare startup budgets keep a client-envelope margin over the da
364364
resolveCommandRequestTimeoutMs(resolveCommandTimeoutPolicy('open'), { ...base }),
365365
90_000,
366366
);
367+
368+
// A --wait budget is spent before the startup budget can begin, so it extends the envelope
369+
// instead of being consumed by it; otherwise a 60s wait would leave a cold boot 30s of envelope
370+
// and end in a client-side daemon reset rather than the open's own refusal.
371+
assert.equal(
372+
resolveCommandRequestTimeoutMs(resolveCommandTimeoutPolicy('open'), {
373+
...base,
374+
flags: { waitMs: 60_000 },
375+
}),
376+
180_000,
377+
);
378+
assert.equal(
379+
resolveCommandRequestTimeoutMs(resolveCommandTimeoutPolicy('open'), {
380+
...base,
381+
flags: { timeoutMs: 600_000, waitMs: 60_000 },
382+
}),
383+
720_000,
384+
);
385+
// Even a small wait keeps the margin over the base, so the open's own refusal wins the race.
386+
assert.equal(
387+
resolveCommandRequestTimeoutMs(resolveCommandTimeoutPolicy('open'), {
388+
...base,
389+
flags: { waitMs: 1_000 },
390+
}),
391+
121_000,
392+
);
393+
// Only `open` reads a wait budget; other commands' envelopes ignore it.
394+
assert.equal(
395+
resolveCommandRequestTimeoutMs(resolveCommandTimeoutPolicy('press'), {
396+
...base,
397+
flags: { waitMs: 60_000 },
398+
}),
399+
90_000,
400+
);
367401
});

‎src/cli/parser/__tests__/command-suggestions.test.ts‎

Lines changed: 68 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,18 @@
11
import assert from 'node:assert/strict';
22
import { test } from 'vitest';
3-
import { isKnownCliCommandName } from '@agent-device/command-registry/catalog';
3+
import { isKnownCliCommandName, listCliCommandNames } from '@agent-device/command-registry/catalog';
44
import { keyboardCliReader } from '../../../commands/system/index.ts';
55
import { AppError } from '@agent-device/kernel/errors';
66
import { parseArgs } from '../args.ts';
77
import type { CliFlags } from '@agent-device/contracts/command';
8-
import { listCommandAliasSuggestionEntries, suggestCommandFor } from '../command-suggestions.ts';
8+
import { getFlagDefinitions } from '../../../cli-schema/command-schema.ts';
9+
import { isFlagSupportedForCommand } from '../../../cli-schema/option-schema.ts';
10+
import {
11+
listCommandAliasSuggestionEntries,
12+
listFlagNameSuggestionEntries,
13+
suggestCommandFor,
14+
suggestFlagFor,
15+
} from '../command-suggestions.ts';
916

1017
// Guards against the curated alias map drifting to a command that no longer
1118
// exists (renamed, removed, gated) in the live command registry.
@@ -222,3 +229,62 @@ test('unrelated unknown flags are unaffected', () => {
222229
error.message === 'Unknown flag: --not-a-real-flag',
223230
);
224231
});
232+
233+
// Guards against the curated flag map drifting to a flag that no longer exists, or to
234+
// one no command accepts — a suggestion the parser would then refuse itself.
235+
test('every curated flag suggestion names a registered flag at least one command accepts', () => {
236+
const commands = listCliCommandNames();
237+
for (const [guess, canonical] of listFlagNameSuggestionEntries()) {
238+
const definition = getFlagDefinitions().find((entry) => entry.names.includes(canonical));
239+
assert.ok(definition, `flag suggestion for "${guess}" names unregistered flag "${canonical}"`);
240+
assert.ok(
241+
definition && commands.some((command) => isFlagSupportedForCommand(definition.key, command)),
242+
`flag suggestion "${canonical}" for "${guess}" is accepted by no command`,
243+
);
244+
}
245+
});
246+
247+
for (const guess of ['--output', '--path', '--Output']) {
248+
test(`a guessed output-path flag on screenshot names ${guess} -> --out`, () => {
249+
assert.throws(
250+
() => parseArgs(['screenshot', guess, './shot.png']),
251+
(error: unknown) =>
252+
error instanceof AppError &&
253+
error.code === 'INVALID_ARGS' &&
254+
error.message === `Unknown flag: ${guess}. Did you mean --out?`,
255+
);
256+
});
257+
}
258+
259+
// The closest negative: `--path` means nothing to `trace`, whose path is positional and
260+
// which accepts no `--out` at all. A suggestion map applied without the per-command gate
261+
// would push a flag this command refuses.
262+
test('a guessed flag the command does not accept is not pushed at it', () => {
263+
assert.throws(
264+
() => parseArgs(['trace', 'start', '--path', './trace.log']),
265+
(error: unknown) =>
266+
error instanceof AppError &&
267+
error.code === 'INVALID_ARGS' &&
268+
error.message === 'Unknown flag: --path',
269+
);
270+
});
271+
272+
// The registry-derived fallback, not the curated map: `--pixel-densityy` is one edit from
273+
// a flag screenshot accepts, and the candidate list comes from that command's own surface.
274+
test('a mistyped flag the command accepts is suggested by nearest name', () => {
275+
assert.throws(
276+
() => parseArgs(['screenshot', '--pixel-densityy', '2']),
277+
(error: unknown) =>
278+
error instanceof AppError &&
279+
error.code === 'INVALID_ARGS' &&
280+
error.message === 'Unknown flag: --pixel-densityy. Did you mean --pixel-density?',
281+
);
282+
});
283+
284+
test('suggestFlagFor never throws for arbitrary input', () => {
285+
for (const input of ['', '-', '--', '@#$%', '--a'.repeat(200), '--JSON']) {
286+
for (const command of ['screenshot', 'open', null]) {
287+
assert.doesNotThrow(() => suggestFlagFor(input, command));
288+
}
289+
}
290+
});

‎src/cli/parser/args.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ export function parseRawArgs(argv: string[]): RawParsedArgs {
101101
else positionals.push(arg);
102102
continue;
103103
}
104-
throw new AppError('INVALID_ARGS', formatUnknownFlagMessage(token));
104+
throw new AppError('INVALID_ARGS', formatUnknownFlagMessage(token, command));
105105
}
106106

107107
const parsed = parseFlagValue(definition, token, inlineValue, argv[i + 1]);

0 commit comments

Comments
 (0)