Skip to content

Commit 1ef7aad

Browse files
committed
docs+ux: make device ownership discoverable end to end
Complete the #1320 agent experience so 'busy? -> inspect -> choose or release' is discoverable from every surface an agent actually reads: - devices now projects the blocking claim owner per row (claimedBy with session and workspace, observe-policy projection; provably dead owners are excluded because the next open replaces them automatically), so an agent told a device is busy can pick a free one from the same listing. - help debugging gains a 'Device busy and ownership' section separating the two DEVICE_IN_USE flavors and their exact recoveries. - AGENTS.md documents both flavors; docs/agents/device-verification.md retires the last ps/kill recovery guidance in favor of device status, daemon stop --state-dir, and device release --stale (Stage 5 of #1320). - ADR-0010 no longer calls DEVICE_IN_USE 'the only retriable code' without naming the claim path's non-retriable override. - The rendered cross-worktree claim error gains a help-conformance quiz case binding (sample-output-device-claim-inspects-owner). - README points at device status / device release --stale. Part of #1320.
1 parent e16bb4a commit 1ef7aad

12 files changed

Lines changed: 182 additions & 11 deletions

File tree

‎AGENTS.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -113,8 +113,10 @@ cross-language rules change through golden tables under `contracts/fixtures/`.
113113
regenerate baselines to accept unrelated findings.
114114
- The first Node process after a newly signed Apple runner launches may block during Gatekeeper
115115
verification. Warm it with a throwaway `node -e 0` before measuring.
116-
- `DEVICE_IN_USE` normally means another session still owns the device. Follow the error's targeted
117-
`close --session` hint instead of debugging the daemon.
116+
- `DEVICE_IN_USE` has two flavors. "already in use by session X" is this daemon — follow the
117+
error's targeted `close --session` hint. "owned by session X in workspace Y" is another
118+
worktree's device claim — non-retriable; follow the error's `device status`/`device release
119+
--stale` recovery instead of debugging the daemon or hunting PIDs.
118120
- A changing timeout failure set that passes in isolation is host contention. Reproduce the same
119121
test on `origin/main` under the same load before treating it as a regression.
120122

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ The same session and evidence model works at every step: the agent explores the
145145

146146
Support depth varies by target. Newer backends such as HarmonyOS and Vega OS cover a subset of commands; run `agent-device capabilities --platform <platform>` to see what a target supports.
147147

148-
Sessions are scoped to the caller's git worktree, and host-local device claims stop parallel agents from taking over each other's simulators and emulators. The same commands drive hosted devices on [BrowserStack, AWS Device Farm, and Limrun](https://oss.callstack.com/agent-device/docs/device-clouds).
148+
Sessions are scoped to the caller's git worktree, and host-local device claims stop parallel agents from taking over each other's simulators and emulators. Inspect ownership without a daemon via `agent-device device status`, and settle provably dead owners with `agent-device device release --stale`. The same commands drive hosted devices on [BrowserStack, AWS Device Farm, and Limrun](https://oss.callstack.com/agent-device/docs/device-clouds).
149149

150150
`agent-device` uses the inspect-act-verify process from Vercel's [agent-browser](https://github.com/vercel-labs/agent-browser) for mobile, TV, and desktop apps. Basic `--platform web` support runs `agent-browser` in the same session and replay system.
151151

‎docs/adr/0010-error-system.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@ agent failures (selector/ref misses), and consumers that drop fields (MCP tool e
2828
`err instanceof AppError ? err : new AppError(...)`.
2929
2. **Code selection.** Use the most specific `KnownAppErrorCode`; `COMMAND_FAILED` is for genuine
3030
runtime failures of a well-formed request, never a catch-all for capability gaps
31-
(`UNSUPPORTED_OPERATION`), contention (`DEVICE_IN_USE`, the only retriable code), or ambiguity
31+
(`UNSUPPORTED_OPERATION`), contention (`DEVICE_IN_USE`, the only code retriable by default;
32+
the cross-worktree device-claim path overrides it to `retriable: false`), or ambiguity
3233
(`AMBIGUOUS_MATCH`). New codes are added to the union deliberately; machine-dispatchable
3334
sub-classification rides in `details.reason` (the lease registry is the model).
3435
3. **Hints answer "what should the agent run next".** A hint is required wherever the per-code

‎docs/agents/device-verification.md‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,13 @@ failed verification attempts.
3838
- Use a purpose-specific session name for experiments, and an isolated `--state-dir` under
3939
`/private/tmp` when you need cleanup isolation beyond the current worktree's default daemon.
4040
- Track opened sessions in working notes; close each one before the final response.
41-
- If `close` is blocked by stale daemon metadata, inspect processes first with
42-
`ps -ax | rg "agent-device|xcodebuild test-without-building"`. Stop only exact stale PIDs belonging
43-
to this verification run, then `pnpm clean:daemon`.
44-
- If cleanup cannot be completed, report the remaining session name, state dir, PIDs, and metadata
45-
paths as a blocker.
41+
- If `close` is blocked or ownership looks stuck, inspect it with
42+
`agent-device device status --stale` (daemonless), stop the owning daemon with
43+
`agent-device daemon stop --state-dir <dir>` (add `--clean` to remove retained runners), and
44+
release provably dead owners with `agent-device device release --stale`. Do not hunt PIDs with
45+
`ps`/`kill`.
46+
- If cleanup cannot be completed, report the remaining session name, state dir, and the
47+
`device status --stale` output as a blocker.
4648

4749
## Sandboxed environments
4850

‎packages/contracts/src/client-device-view.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,15 @@ export type AgentDeviceDevice = {
2121
*/
2222
appleOs?: AppleOS;
2323
identifiers: AgentDeviceIdentifiers;
24+
/**
25+
* Present when a host-local device claim currently blocks foreign use of
26+
* this device (#1320). Provably dead owners are not projected — the next
27+
* open reconciles and replaces them automatically.
28+
*/
29+
claimedBy?: {
30+
session: string;
31+
workspace: string;
32+
};
2433
ios?: {
2534
udid: string;
2635
};

‎scripts/help-conformance-cases.mjs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import {
22
AMBIGUOUS_MATCH_SAMPLE,
33
APP_NOT_INSTALLED_SAMPLE,
44
BROWSERSTACK_CONNECT_SAMPLE,
5+
DEVICE_CLAIM_IN_USE_SAMPLE,
56
DEVICE_IN_USE_SAMPLE,
67
FOREGROUND_SNAPSHOT_FAILURE_SAMPLE,
78
MERGED_CARD_ACTIONS_SAMPLE,
@@ -575,6 +576,28 @@ Use the output already shown to determine whether the feed-search UI is present,
575576
{ id: 'noRawCoordinateTarget', pattern: RAW_COORDINATE_TARGET },
576577
],
577578
},
579+
{
580+
id: 'sample-output-device-claim-inspects-owner',
581+
docs: ['--help:first30', 'debugging'],
582+
recovery: { code: 'DEVICE_IN_USE', sample: DEVICE_CLAIM_IN_USE_SAMPLE },
583+
task: quiz(
584+
DEVICE_CLAIM_IN_USE_SAMPLE,
585+
'A different worktree owns this device and you must not interrupt it. What command should run next?',
586+
),
587+
expectations: ['validPlanCommands', 'fullPrefix'],
588+
matchers: [
589+
{
590+
id: 'runsDeviceStatus',
591+
pattern:
592+
/(?:^|\n)agent-device\s+device\s+status\s+--platform\s+android\s+--serial\s+emulator-5554\b/i,
593+
},
594+
],
595+
forbidden: [
596+
{ id: 'noRetryOpen', pattern: /(?:^|\n)agent-device\s+open\b/i },
597+
{ id: 'noForeignClose', pattern: /(?:^|\n)agent-device\s+close\b/i },
598+
{ id: 'noPidHunting', pattern: /(?:^|\n)\s*(?:ps|kill|pkill)\b/i },
599+
],
600+
},
578601
{
579602
id: 'sample-output-stale-ref-resnapshots',
580603
docs: ['--help:first30'],

‎src/cli-schema/cli-help.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,6 +512,11 @@ Example:
512512
agent-device react-devtools profile report @c5
513513
agent-device network dump --include headers
514514
515+
Device busy and ownership:
516+
DEVICE_IN_USE has two flavors. "already in use by session X" is this daemon: reuse it with --session X, or run close --session X first. "owned by session X in workspace Y" is another worktree's daemon holding the host-global device claim: it is never retriable — run the error's exact recovery command instead of retrying.
517+
Inspect ownership without any daemon: agent-device device status (add --stale for proven-dead owners; settle and release those with agent-device device release --stale). devices marks rows that are claimed, so pick an unclaimed device instead of contending.
518+
A live foreign owner is released only by closing its session from its own workspace or stopping its daemon: agent-device daemon stop --state-dir <owner state dir> (the error names the state dir). Never recover by hunting PIDs with ps/kill. boot/install/shutdown take the same claims as open and refuse foreign-claimed devices identically.
519+
515520
Use snapshot, screenshot, logs, network, perf frames, and perf memory for device/app runtime evidence. Use react-devtools when component internals or React rendering behavior matters.`,
516521
},
517522
cdp: {

‎src/client/client-normalizers.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,10 +108,21 @@ export function normalizeDevice(value: unknown): AgentDeviceDevice {
108108
// a non-Apple record with a stray appleOs value is not preserved.
109109
...(isApplePlatform(platform) && appleOs ? { appleOs } : {}),
110110
identifiers: buildDeviceIdentifiers(platform, id, name),
111+
...readClaimedBy(record),
111112
...buildClientDevicePlatformFields(platform, id),
112113
};
113114
}
114115

116+
function readClaimedBy(record: Record<string, unknown>): Pick<AgentDeviceDevice, 'claimedBy'> {
117+
const value = record.claimedBy;
118+
if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
119+
const claimedBy = value as Record<string, unknown>;
120+
const session = claimedBy.session;
121+
const workspace = claimedBy.workspace;
122+
if (typeof session !== 'string' || typeof workspace !== 'string') return {};
123+
return { claimedBy: { session, workspace } };
124+
}
125+
115126
export function normalizeSession(value: unknown): AgentDeviceSession {
116127
const { record, platform, id, name, target } = readClientDeviceIdentity(value, 'name');
117128
const deviceName = readRequiredString(record, 'device');

‎src/commands/management/output.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,10 @@ function formatDeviceLine(device: AgentDeviceDevice): string {
232232
const kind = device.kind ? ` ${device.kind}` : '';
233233
const target = device.target ? ` target=${device.target}` : '';
234234
const booted = typeof device.booted === 'boolean' ? ` booted=${device.booted}` : '';
235-
return `${device.name} (${device.platform}${kind}${target})${booted}`;
235+
const claimed = device.claimedBy
236+
? ` claimed by session "${device.claimedBy.session}" in ${device.claimedBy.workspace}`
237+
: '';
238+
return `${device.name} (${device.platform}${kind}${target})${booted}${claimed}`;
236239
}
237240

238241
function formatCloudArtifactLine(artifact: CloudArtifactsResult['cloudArtifacts'][number]): string {

‎src/daemon/handlers/__tests__/session-devices-batch-runtime.test.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { handleSessionCommands } from './session-command-harness.ts';
1414
import { mkdtempForTestSync } from '../../../__tests__/test-utils/tmp-dir.ts';
1515
import { withTestDeviceInventory } from '../../../__tests__/test-utils/device-inventory-gateways.ts';
1616
import type { DeviceInfo } from '@agent-device/kernel/device';
17+
import { readCurrentOwnerIdentity } from '@agent-device/host-kit/process';
1718

1819
test('devices filters Apple-family platform selectors', async () => {
1920
const sessionStore = makeSessionStore();
@@ -497,3 +498,80 @@ test('release_materialized_paths removes retained install artifacts', async () =
497498
expect(fs.existsSync(retained.installablePath)).toBe(false);
498499
fs.rmSync(tempRoot, { recursive: true, force: true });
499500
});
501+
502+
test('devices projects the blocking claim owner and hides provably dead owners', async () => {
503+
const claimsDir = mkdtempForTestSync('agent-device-devices-claims-');
504+
const previousClaimsDir = process.env.AGENT_DEVICE_CLAIMS_DIR;
505+
process.env.AGENT_DEVICE_CLAIMS_DIR = claimsDir;
506+
const owner = readCurrentOwnerIdentity();
507+
const writeClaim = (id: string, ownerPid: number, ownerStartTime: string | null) => {
508+
fs.writeFileSync(
509+
path.join(claimsDir, `${id}.json`),
510+
JSON.stringify({
511+
schemaVersion: 1,
512+
deviceKey: `local:android:none:${id}`,
513+
device: { platform: 'android', id, name: id, kind: 'emulator' },
514+
session: `${id}-session`,
515+
workspace: `/worktrees/${id}`,
516+
stateDir: process.cwd(),
517+
ownerPid,
518+
ownerStartTime,
519+
ownerToken: `${id}-token`,
520+
createdAtMs: 1,
521+
updatedAtMs: 1,
522+
}),
523+
);
524+
};
525+
writeClaim('emulator-5554', owner.pid, owner.startTime);
526+
writeClaim('emulator-5556', 999_999_999, 'long-gone');
527+
const sessionStore = makeSessionStore();
528+
const inventory: DeviceInfo[] = [
529+
makeAndroidInventoryDevice('emulator-5554'),
530+
makeAndroidInventoryDevice('emulator-5556'),
531+
];
532+
try {
533+
const response = await withTestDeviceInventory(
534+
{ local: async () => inventory },
535+
async () =>
536+
await handleSessionCommands({
537+
req: {
538+
token: 't',
539+
session: 'default',
540+
command: 'devices',
541+
positionals: [],
542+
flags: { platform: 'android' },
543+
},
544+
sessionName: 'default',
545+
logPath: path.join(os.tmpdir(), 'daemon.log'),
546+
sessionStore,
547+
invoke: noopInvoke,
548+
}),
549+
);
550+
expect(response?.ok).toBeTruthy();
551+
if (response?.ok) {
552+
const devices = response.data?.devices as Array<Record<string, unknown>> | undefined;
553+
expect(devices).toHaveLength(2);
554+
expect(devices?.[0]?.claimedBy).toEqual({
555+
session: 'emulator-5554-session',
556+
workspace: '/worktrees/emulator-5554',
557+
});
558+
// The dead owner is not projected: the next open reconciles and replaces it.
559+
expect(devices?.[1]?.claimedBy).toBeUndefined();
560+
}
561+
} finally {
562+
if (previousClaimsDir === undefined) delete process.env.AGENT_DEVICE_CLAIMS_DIR;
563+
else process.env.AGENT_DEVICE_CLAIMS_DIR = previousClaimsDir;
564+
fs.rmSync(claimsDir, { recursive: true, force: true });
565+
}
566+
});
567+
568+
function makeAndroidInventoryDevice(id: string): DeviceInfo {
569+
return {
570+
platform: 'android',
571+
id,
572+
name: id,
573+
kind: 'emulator',
574+
target: 'mobile',
575+
booted: true,
576+
};
577+
}

0 commit comments

Comments
 (0)