Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions skills/agent-device/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ agent-device open <app> --foreground

That starts the session and returns the initial interactive snapshot with `@refs`.

Loop: act with `press|click|fill|longpress <target> ... --settle`, `scroll <direction> --settle`, or `back --settle`; continue from the printed diff, verify the named expectation with a read-only command (`wait text "..."`, `is`, or `get`; bare `find` clicks, so check with `find text "..." exists`), then run `agent-device close`, or `agent-device close --shutdown` if your session booted a local simulator or emulator, unless the user asks to keep it running. When a result needs time, wait with `wait stable` or `wait absent <selector>` instead of sleeping and reading again.
Loop: act with `press|click|fill|longpress <target> ... --settle`, `scroll <direction> --settle`, or `back --settle`; continue from the printed diff, verify the named expectation with a read-only command (`wait text "..."`, `is`, or `get`; bare `find` clicks, so check with `find text "..." exists`), then run `agent-device close`, or `agent-device close --shutdown` if your session booted a local simulator or emulator, unless the user asks to keep it running. When a result needs time, wait with `wait stable` or `wait absent <selector>` instead of sleeping and reading again. Pull to refresh is `scroll refresh`. To restart the app, or make it load new JavaScript, run `open <app> --relaunch`; for a JS-only change, `metro reload`. There is no `reload` command.

For exploratory QA, read `agent-device help dogfood`; its platform checks run `agent-device audit`.

Expand All @@ -23,6 +23,6 @@ Reaching an off-screen target is one command, not a scroll-and-check loop: `scro

Copy refs byte-for-byte: `@e12`, `@e12~s4` — keep the `@` and any `~sN`. Prefer current refs, then `id`/`label`/`role` selectors; coordinates are a last resort. If snapshot reports sparse/AX-unavailable, its refs and selectors are invalid: run `agent-device screenshot`, inspect the image, use coordinates, then retry `snapshot -i` after navigating. Otherwise run `snapshot -i` only when the diff lacks the next target. Save a capture to a file you keep: `agent-device screenshot evidence.png` (or pass `--out <path>`).

Error output includes corrective hints; follow them instead of re-planning. If the error is `DEVICE_IN_USE`, another session holds the device: open with `--wait <ms>`, or run `agent-device device status --stale` and then `agent-device device release --stale` to clear a provably dead owner. Never kill daemon processes with `pkill -f agent-device`. Only when the task is specialized (for example gestures, scripting, TV, macOS, remote, or debugging) or a command shape is unclear, run `agent-device help <topic>`. `agent-device --help` lists topics, `agent-device help commands` lists commands; neither is a startup step.
Error output includes corrective hints; follow them instead of re-planning. When your host runs commands in a sandbox and allows `agent-device` by command name, run each call as its own command: do not chain it with `;`, `&&`, or `|`, and do not quote its binary path, or the host's allow rule misses the call and it cannot reach the daemon or the device. If the error is `DEVICE_IN_USE`, another session holds the device: open with `--wait <ms>`, or run `agent-device device status --stale` and then `agent-device device release --stale` to clear a provably dead owner. Never kill daemon processes with `pkill -f agent-device`. Only when the task is specialized (for example gestures, scripting, TV, macOS, remote, or debugging) or a command shape is unclear, run `agent-device help <topic>`. `agent-device --help` lists topics, `agent-device help commands` lists commands; neither is a startup step.

To capture network traffic on a Limrun session, see `agent-device help remote` or the Limrun docs.
56 changes: 56 additions & 0 deletions src/__tests__/cli-help.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,22 @@ test('help gestures prints the multi-touch topic and skips daemon dispatch', asy
assert.match(result.stdout, /agent-device gesture transform 200 420 80 -40 2 35 700/);
});

// Reading `help gestures` to find the pull-to-refresh command costed a 7 KB read in every run:
// the answer was in the last half of the topic. It must lead, and `help scroll` must answer it.
test('help gestures names scroll refresh as pull to refresh in its first lines', async () => {
const result = await runCliCapture(['help', 'gestures']);
const firstLines = result.stdout.split('\n').slice(0, 5).join('\n');
assert.match(firstLines, /Pull to refresh is agent-device scroll refresh/);
});

test('help scroll names pull to refresh in its first lines', async () => {
const result = await runCliCapture(['help', 'scroll']);
assert.equal(result.code, 0);
assert.equal(result.calls.length, 0);
const firstLines = result.stdout.split('\n').slice(0, 5).join('\n');
assert.match(firstLines, /refresh is pull-to-refresh/);
});

test('help unknown command prints error plus root decision card and skips daemon dispatch', async () => {
const result = await runCliCapture(['help', 'not-a-command']);
assert.equal(result.code, 1);
Expand All @@ -227,6 +243,46 @@ test('help unknown command prints error plus root decision card and skips daemon
assert.doesNotMatch(result.stdout, /Global Flags:/);
});

// The measured waste: `agent-device reload --help` printed an unrelated suggestion plus the whole
// root help, about 3 KB per hit. A confident suggestion replaces the dump with one pointer line.
for (const argv of [
['help', 'reload'],
['reload', '--help'],
['help', 'restart'],
]) {
test(`${argv.join(' ')} answers with the relaunch and metro reload shapes in a short read`, async () => {
const result = await runCliCapture(argv);
assert.equal(result.code, 1);
assert.equal(result.calls.length, 0);
assert.match(
result.stderr,
/Unknown command: (reload|restart)\. Did you mean open <app> --relaunch \(or metro reload\)\?/,
);
assert.doesNotMatch(result.stderr, /record/);
assert.doesNotMatch(result.stdout, /All \d+ commands: agent-device help commands/);
assert.match(result.stdout, /agent-device --help/);
const bytes = Buffer.byteLength(`${result.stdout}${result.stderr}`);
assert.ok(bytes <= 400, `expected at most 400 bytes of output, got ${bytes}`);
});
}

test('help with a single nearest name stays short; several candidates keep the root card', async () => {
const single = await runCliCapture(['help', 'presss']);
assert.match(single.stderr, /Did you mean press\?/);
assert.doesNotMatch(single.stdout, /All \d+ commands:/);
const several = await runCliCapture(['help', 'scr']);
assert.match(several.stderr, /one of: scroll, screenshot/);
assert.match(several.stdout, /All \d+ commands: agent-device help commands/);
});

test('the bare reload command fails in the parser with the same short hint', async () => {
const result = await runCliCapture(['reload']);
assert.equal(result.code, 1);
assert.equal(result.calls.length, 0);
assert.match(result.stderr, /Did you mean open <app> --relaunch \(or metro reload\)\?/);
assert.doesNotMatch(result.stdout, /All \d+ commands:/);
});

test('unknown command --help prints error plus root decision card and skips daemon dispatch', async () => {
const result = await runCliCapture(['not-a-command', '--help']);
assert.equal(result.code, 1);
Expand Down
15 changes: 4 additions & 11 deletions src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { parseRawArgs, usage, usageForCommand } from './cli/parser/args.ts';
import { suggestCommandFor } from './cli/parser/command-suggestions.ts';
import { parseRawArgs, usage, usageForCommand, usageForUnknownCommand } from './cli/parser/args.ts';
import { formatUnknownCommandMessage } from './cli/parser/command-suggestions.ts';
import {
asAppError,
AppError,
Expand Down Expand Up @@ -295,8 +295,8 @@ async function parseCliInputOrExit(
writeStdout(commandHelp);
return exitAfterFlush(0);
}
await printHumanError(new AppError('INVALID_ARGS', formatUnknownHelpTargetMessage(helpTarget)));
writeStdout(`${await usage()}\n`);
await printHumanError(new AppError('INVALID_ARGS', formatUnknownCommandMessage(helpTarget)));
writeStdout(await usageForUnknownCommand(helpTarget));
return exitAfterFlush(1);
}

Expand Down Expand Up @@ -717,13 +717,6 @@ function isDebugRequested(argv: string[]): boolean {
}
}

function formatUnknownHelpTargetMessage(helpTarget: string): string {
const hint = suggestCommandFor(helpTarget);
return hint
? `Unknown command: ${helpTarget}. Did you mean ${hint}?`
: `Unknown command: ${helpTarget}`;
}

function formatUnhandledCommandMessage(command: string): string {
if (isKnownCliCommandName(command)) {
// Registered-but-unhandled means catalog/dispatch drift — make it visible
Expand Down
54 changes: 42 additions & 12 deletions src/cli/parser/__tests__/command-suggestions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,21 @@ test('every curated alias suggestion target resolves to a registered command', (
});

// Guards the full example shapes, not just the leading command token: every
// example must parse as a valid invocation (placeholders substituted), so a
// renamed flag (e.g. open --relaunch) or a dropped subcommand fails here.
// example and alternative must parse as a valid invocation (placeholders
// substituted), so a renamed flag (e.g. open --relaunch) or a dropped
// subcommand fails here.
test('every curated alias suggestion example parses as a valid invocation', () => {
for (const [guess, suggestion] of listCommandAliasSuggestionEntries()) {
const tokens = suggestion.example
.split(' ')
.map((token) => (token.startsWith('<') ? 'com.example.app' : token));
assert.doesNotThrow(
() => parseArgs(tokens, { strictFlags: true }),
`alias suggestion example for "${guess}" ("${suggestion.example}") no longer parses`,
);
for (const shape of [suggestion.example, suggestion.alternative]) {
if (shape === undefined) continue;
const tokens = shape
.split(' ')
.map((token) => (token.startsWith('<') ? 'com.example.app' : token));
assert.doesNotThrow(
() => parseArgs(tokens, { strictFlags: true }),
`alias suggestion for "${guess}" ("${shape}") no longer parses`,
);
}
}
});

Expand All @@ -66,11 +70,37 @@ for (const guess of ['start', 'restart']) {
(error: unknown) =>
error instanceof AppError &&
error.code === 'INVALID_ARGS' &&
error.message.includes('Did you mean open <app> --relaunch?'),
error.message.includes('Did you mean open <app> --relaunch'),
);
});
}

// `reload` and `restart` are the names an agent reaches for when the app must
// restart or pick up new JavaScript. Both intents are printed in one short hint,
// and `reload` must never fall through to the nearest-name `record` suggestion.
for (const guess of ['reload', 'restart']) {
test(`${guess} names open --relaunch and metro reload, never an unrelated command`, () => {
assert.throws(
() => parseArgs([guess]),
(error: unknown) =>
error instanceof AppError &&
error.code === 'INVALID_ARGS' &&
error.message ===
`Unknown command: ${guess}. Did you mean open <app> --relaunch (or metro reload)?`,
);
});
}

test('a curated two-shape suggestion stays shorter than a help read', () => {
const suggestion = suggestCommandFor('reload');
assert.ok(suggestion);
assert.ok(
Buffer.byteLength(`Unknown command: reload. Did you mean ${suggestion}?`) <= 400,
`suggestion message must stay under 400 bytes, got ${Buffer.byteLength(suggestion!)}`,
);
assert.doesNotMatch(suggestion!, /record/);
});

for (const guess of ['pinch', 'zoom']) {
test(`${guess} suggests gesture pinch on an element`, () => {
assert.throws(
Expand Down Expand Up @@ -160,8 +190,8 @@ test('screencap and capture suggest screenshot', () => {
});

test('curated suggestions are case-insensitive', () => {
assert.equal(suggestCommandFor('RESTART'), 'open <app> --relaunch');
assert.equal(suggestCommandFor('Restart'), 'open <app> --relaunch');
assert.equal(suggestCommandFor('RESTART'), 'open <app> --relaunch (or metro reload)');
assert.equal(suggestCommandFor('Restart'), 'open <app> --relaunch (or metro reload)');
assert.equal(suggestCommandFor('Touch'), 'press');
assert.equal(suggestCommandFor('DISMISS'), 'keyboard dismiss');
});
Expand Down
23 changes: 17 additions & 6 deletions src/cli/parser/args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,12 @@ import {
normalizeCliCommandAlias,
retiredCliCommandMessage,
} from '@agent-device/command-registry/cli-command-aliases';
import { formatUnknownFlagMessage, suggestCommandFor } from './command-suggestions.ts';
import {
formatUnknownCommandMessage,
formatUnknownFlagMessage,
hasSingleCommandSuggestion,
UNKNOWN_COMMAND_POINTER,
} from './command-suggestions.ts';

type ParsedArgs = {
command: string | null;
Expand Down Expand Up @@ -178,11 +183,7 @@ export function finalizeParsedArgs(
// This ensures "Unknown command" errors take precedence over flag validation errors
// However, skip this check if --help is provided, since cli.ts will handle it gracefully
if (parsed.command && !isKnownCliCommandName(parsed.command) && !flags.help) {
const hint = suggestCommandFor(parsed.command);
const message = hint
? `Unknown command: ${parsed.command}. Did you mean ${hint}?`
: `Unknown command: ${parsed.command}`;
throw new AppError('INVALID_ARGS', message);
throw new AppError('INVALID_ARGS', formatUnknownCommandMessage(parsed.command));
}

const disallowed = parsed.providedFlags.filter(
Expand Down Expand Up @@ -521,6 +522,16 @@ export async function usageForCommand(command: string): Promise<string | null> {
return buildCommandUsageText(normalizeCommandAlias(command));
}

/**
* What a help read for an unknown name prints after its error line: the short
* pointer when the suggestion names one command, the root decision card when it
* lists several candidates or none.
*/
export async function usageForUnknownCommand(command: string): Promise<string> {
if (hasSingleCommandSuggestion(command)) return UNKNOWN_COMMAND_POINTER;
return `${await usage()}\n`;
}
Comment thread
thymikee marked this conversation as resolved.
Resolved

/** The one-line synopsis of a command or alias, or `null` for an unknown or retired name. */
export async function commandSynopsis(command: string): Promise<string | null> {
const { buildCommandSynopsis } = await import('../../commands/schema/cli-help.ts');
Expand Down
56 changes: 53 additions & 3 deletions src/cli/parser/command-suggestions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,31 @@ type CommandAliasSuggestion = {
command: string;
/** Full example invocation shown to the user. */
example: string;
/**
* Second shape for a guess that covers two intents: restarting the app versus
* loading new JavaScript. Printed in parentheses after `example`, so it must
* parse on its own as a valid invocation.
*/
alternative?: string;
};

const OPEN_RELAUNCH_EXAMPLE = 'open <app> --relaunch';
const METRO_RELOAD_EXAMPLE = 'metro reload';

const COMMAND_ALIAS_SUGGESTIONS: Record<string, CommandAliasSuggestion> = {
start: { command: 'open', example: OPEN_RELAUNCH_EXAMPLE },
restart: { command: 'open', example: OPEN_RELAUNCH_EXAMPLE },
restart: {
command: 'open',
example: OPEN_RELAUNCH_EXAMPLE,
alternative: METRO_RELOAD_EXAMPLE,
},
// `reload` is the name agents reach for to restart an app or pick up new JS, and
// the nearest-name fallback answers it with the unrelated `record`.
reload: {
command: 'open',
example: OPEN_RELAUNCH_EXAMPLE,
alternative: METRO_RELOAD_EXAMPLE,
},
touch: { command: 'press', example: 'press' },
input: { command: 'fill', example: 'fill' },
settext: { command: 'fill', example: 'fill' },
Expand Down Expand Up @@ -140,14 +158,28 @@ function levenshteinDistance(a: string, b: string): number {
*/
export function suggestCommandFor(command: string): string | undefined {
const normalized = command.toLowerCase();
const curated = COMMAND_ALIAS_SUGGESTIONS[normalized]?.example;
if (curated) return curated;
const curated = COMMAND_ALIAS_SUGGESTIONS[normalized];
if (curated) {
return curated.alternative ? `${curated.example} (or ${curated.alternative})` : curated.example;
}
const nearest = getNearestCommandNames(normalized);
if (nearest.length === 0) return undefined;
if (nearest.length === 1) return nearest[0];
return `one of: ${nearest.join(', ')}`;
}

/**
* True when an unknown command has one answer: a curated alias or a single nearest
* name. A multi-candidate guess or no guess is not one; the root card shows the shapes.
*/
export function hasSingleCommandSuggestion(command: string): boolean {
const normalized = command.toLowerCase();
return (
Object.hasOwn(COMMAND_ALIAS_SUGGESTIONS, normalized) ||
getNearestCommandNames(normalized).length === 1
);
}

// Unknown flag names that read like an app/bundle identity concept. `open` (and
// the commands the curated map above points agents toward) take the app or
// bundle id as a positional argument, not a flag, so a bare "Unknown flag"
Expand Down Expand Up @@ -242,6 +274,24 @@ function stripFlagDashes(token: string): string {
return token.replace(/^--?/, '');
}

/**
* The one-line read printed instead of the root decision card when an unknown
* command already got a confident suggestion, so the whole answer stays shorter
* than a help read.
*/
export const UNKNOWN_COMMAND_POINTER = 'Run agent-device --help for commands and topics.\n';

/**
* Builds the error message for an unknown CLI command name, carrying the
* "Did you mean ...?" hint when the suggestion maps have a confident answer.
*/
export function formatUnknownCommandMessage(command: string): string {
const hint = suggestCommandFor(command);
return hint
? `Unknown command: ${command}. Did you mean ${hint}?`
: `Unknown command: ${command}`;
}

export function formatUnknownFlagMessage(token: string, command: string | null): string {
const normalized = token.toLowerCase();
if (POSITIONAL_APP_FLAG_GUESSES.has(normalized)) {
Expand Down
2 changes: 1 addition & 1 deletion src/commands/schema/cli-help-gestures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export const gestureHelpTopic = {
summary: 'Full multi-touch gesture shapes and platform quirks',
body: `agent-device help gestures

Full command shapes and platform quirks for touch/pointer gestures beyond scroll/swipe. Read this when a task needs multi-touch, a repeated gesture series, or exact per-platform verification.
Full command shapes and platform quirks for touch/pointer gestures beyond scroll/swipe. Pull to refresh is agent-device scroll refresh. Read this when a task needs multi-touch, a repeated gesture series, or exact per-platform verification.

Shapes:
agent-device longpress 300 500 800
Expand Down
1 change: 1 addition & 0 deletions website/docs/docs/agent-setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ For React Native JavaScript heap growth, heap snapshots, allocation hotspots, or
For React Native apps, overlays, Metro/Fast Refresh blockers, and routing to profiling or debugging evidence, read `agent-device help react-native`.

Use MCP tools or the CLI in the integrated terminal.
Run each agent-device call as its own command. When your host runs commands in a sandbox and allows `agent-device` by command name, do not chain it with `;`, `&&`, or `|`, and do not quote its binary path, or the host's allow rule misses the call and it cannot reach the daemon or the device.
If `agent-device` is not on PATH but the user installed it globally in another shell, resolve the command the same way the user would from a normal terminal session and run that absolute path instead. This may require inspecting shell startup behavior or package-manager/global bin locations; do not assume the agent process `PATH` is the user's `PATH`.
Do not silently fall back to `npx -y agent-device@latest`; ask or use an exact version.
MCP exposes structured tools backed by the agent-device client; it does not expose generic shell execution.
Expand Down
Loading