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
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ test('selector mismatch explains session recovery commands', () => {
assert.equal(err.code, 'INVALID_ARGS');
assert.match(err.message, /Session "default" is already bound to android device "Pixel 9"/i);
assert.match(err.message, /--platform=ios/i);
assert.match(err.details?.hint ?? '', /agent-device session list/i);
assert.match(err.details?.hint ?? '', /open it with a different --session name/i);
assert.match(err.details?.hint ?? '', /--session default/i);
assert.match(err.details?.hint ?? '', /agent-device close --session default/i);
return true;
Expand Down
102 changes: 98 additions & 4 deletions packages/daemon/src/core/session-recovery-hints.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
import { makeStoredSessionRef } from '../__tests__/support/store-factory.ts';
import { test, expect } from 'vitest';
import { buildSessionRecoveryHint } from './session-recovery-hints.ts';
import {
buildForeignWorkspaceSessionConflict,
buildSessionRecoveryHint,
} from './session-recovery-hints.ts';
import type { SessionRef, SessionState } from './session-state.ts';
import { IOS_SIMULATOR } from '@agent-device/test-kit';
import { IOS_SIMULATOR, mkdtempForTestSync } from '@agent-device/test-kit';
import { PLATFORM_SELECTORS, webSessionBackendKey } from '@agent-device/kernel/device';
import type { AppError } from '@agent-device/kernel/errors';
import { makeSessionStore, makeStoredSessionRef } from '../__tests__/support/store-factory.ts';
import { resolveEffectiveSessionName } from '../sessions/session-routing.ts';
import type { DaemonRequest } from './daemon-request.ts';

// The recovery hint's whole job is to hand back a command that works. For an implicitly
// cwd-scoped session — named `default`, stored as `cwd:<hash>:default` — building it from the
Expand Down Expand Up @@ -30,10 +37,42 @@ test('device-in-use recovery names the address --session accepts, not the public
const hint = buildSessionRecoveryHint(scopedRef(), 'device-in-use');

expect(hint).toContain(`agent-device close --session ${SCOPED_ADDRESS}`);
expect(hint).toContain(`rerun the command with --session ${SCOPED_ADDRESS}`);
expect(hint).toContain(`reuse --session ${SCOPED_ADDRESS}`);
expect(hint).not.toMatch(/--session default\b/);
});

// A device-in-use hint is read by agents sharing a host: it must offer the moves that leave the
// holding session alone before any that would take it over.
test('device-in-use recovery lists non-takeover options before reusing or closing the holder', () => {
const hint = buildSessionRecoveryHint(scopedRef(), 'device-in-use', { offersDeviceWait: true });
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved

const firstTakeover = Math.min(
hint.indexOf(`--session ${SCOPED_ADDRESS}`),
hint.indexOf('close --session'),
);
expect(firstTakeover).toBeGreaterThan(-1);
expect(hint.indexOf('agent-device devices')).toBeGreaterThan(-1);
expect(hint.indexOf('agent-device devices')).toBeLessThan(firstTakeover);
expect(hint.indexOf('--wait <ms>')).toBeGreaterThan(-1);
expect(hint.indexOf('--wait <ms>')).toBeLessThan(firstTakeover);
expect(hint.slice(0, firstTakeover)).toMatch(/only if that session is yours/i);
});

test('foreign-workspace recovery lists non-takeover options before closing the holder', () => {
const hint = String(
buildForeignWorkspaceSessionConflict(scopedRef(), IOS_SIMULATOR, { offersDeviceWait: true })
.error.details?.hint,
);

const close = hint.indexOf(`close --session ${SCOPED_ADDRESS}`);
expect(close).toBeGreaterThan(-1);
expect(hint.indexOf('agent-device devices')).toBeGreaterThan(-1);
expect(hint.indexOf('agent-device devices')).toBeLessThan(close);
expect(hint.indexOf('--wait <ms>')).toBeGreaterThan(-1);
expect(hint.indexOf('--wait <ms>')).toBeLessThan(close);
expect(hint.slice(close)).toMatch(/only if that workspace is yours/);
});

test('selector-conflict recovery uses the same address', () => {
const hint = buildSessionRecoveryHint(scopedRef(), 'selector-conflict');

Expand Down Expand Up @@ -85,3 +124,58 @@ test('selector-conflict recovery offers no platform session to a hand-named sess

expect(hint).not.toContain('--platform');
});

// Diagnostic redaction cuts any string over 400 characters, which would drop the trailing
// commands of a hint. The bound comes from the code that limits addresses: the web session name
// validator, and the implicit workspace address session routing builds for every platform.
// Explicit native and tenant-prefixed names have no length limit, so no fixed text covers them.
function longestBoundedAddress(): string {
let webMaxLength = 0;
try {
webSessionBackendKey({ name: 'x'.repeat(256) });
} catch (error) {
webMaxLength = Number((error as AppError).details?.maxLength);
}
expect(webMaxLength).toBeGreaterThan(0);
const cwd = mkdtempForTestSync('agent-device-hint-scope-');
const workspaceAddresses = [undefined, ...PLATFORM_SELECTORS].map((platform) =>
resolveEffectiveSessionName(
{
command: 'open',
token: 'test-token',
session: 'default',
positionals: [],
flags: { platform },
meta: { cwd },
} satisfies DaemonRequest,
makeSessionStore(),
),
);
return [...workspaceAddresses, 'x'.repeat(webMaxLength)].reduce((longest, address) =>
address.length > longest.length ? address : longest,
);
}

test('every recovery variant fits the redaction cap with the longest bounded address', () => {
const address = longestBoundedAddress();
// A cwd scope keeps the platform-session suffix in the selector-conflict variant.
const session = scopedRef().session;
const ref = makeStoredSessionRef(session, address);
const recording = makeStoredSessionRef(
{ ...session, screenRecording: {} as NonNullable<SessionState['screenRecording']> },
address,
);
const hints = [
buildSessionRecoveryHint(ref, 'device-in-use', { offersDeviceWait: true }),
buildSessionRecoveryHint(ref, 'device-in-use', { waitedMs: 30_000 }),
buildSessionRecoveryHint(ref, 'selector-conflict', { offersPlatformSession: true }),
buildSessionRecoveryHint(recording, 'device-in-use'),
buildSessionRecoveryHint(recording, 'selector-conflict'),
String(
buildForeignWorkspaceSessionConflict(ref, IOS_SIMULATOR, { offersDeviceWait: true }).error
.details?.hint,
),
];

for (const hint of hints) expect(hint.length).toBeLessThanOrEqual(400);
});
45 changes: 25 additions & 20 deletions packages/daemon/src/core/session-recovery-hints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,14 +98,12 @@ function buildRecordingSessionRecoveryHint(
const recordStopCommand = `agent-device record stop --session ${sessionArg}`;
const reuseText =
context === 'selector-conflict'
? `To keep using this device, rerun the command with --session ${sessionArg} and remove conflicting device selectors.`
: `To keep using this device, reuse --session ${sessionArg} for commands that should attach to the recording session.`;
? `use --session ${sessionArg} without device selectors`
: `reuse --session ${sessionArg}`;

return (
`Recording session "${sessionAddress}" owns this device. ` +
`Run ${recordStopCommand}; if the session still appears in agent-device session list, run ${closeCommand}. ` +
`${reuseText} ` +
`Run agent-device session list to inspect active sessions.`
`A recording session, maybe another agent's or user's, holds this device. ${CHOOSE_ANOTHER_DEVICE}` +
`Only if it is yours: run ${recordStopCommand}, then ${closeCommand} if still open; or ${reuseText}.`
);
}

Expand All @@ -114,19 +112,19 @@ function buildRecordingSessionRecoveryHint(
* holder is another workspace's implicit session. The address is still the whole point — it is
* what `close --session` and `--session` take, and for an implicit session it is the store key
* rather than the `default` name `session list` shows (#2031) — but reusing it would run this
* workspace's commands inside the other workspace's session, so closing it, switching device, and
* waiting are the moves offered.
* workspace's commands inside the other workspace's session, so switching device and waiting are
* offered first. Closing it stays on offer, conditioned on the workspace: it is often the caller's
* own from another folder.
*/
function buildForeignWorkspaceSessionRecoveryHint(
sessionAddress: string,
options: SessionRecoveryOptions,
): string {
const sessionArg = shellQuoteIfNeeded(sessionAddress);
return (
`${describeOpenWaitAttempt(options)}Session "${sessionAddress}" belongs to another workspace. ` +
`Run agent-device close --session ${sessionArg} to release this device from that workspace, ` +
`agent-device devices to choose another device. ` +
`${waitForDeviceHint(options)}Run agent-device session list to inspect active sessions.`
`${describeOpenWaitAttempt(options)}The holding session belongs to another workspace, possibly another agent's or user's. ` +
`${CHOOSE_ANOTHER_DEVICE}${waitForDeviceHint(options)}` +
`Run agent-device close --session ${sessionArg} only if that workspace is yours.`
);
}

Expand All @@ -140,21 +138,28 @@ function buildOpenSessionRecoveryHint(
const closeCommand = `agent-device close --session ${sessionArg}`;
if (context === 'selector-conflict') {
return (
`Run agent-device session list to inspect active sessions. ` +
`To reuse this device, rerun the command with --session ${sessionArg} and remove conflicting device selectors. ` +
`To switch devices, first run ${closeCommand}, then open the desired device with a different --session name.` +
implicitPlatformSessionHint(ref, options)
`To use the selected device, open it with a different --session name.` +
implicitPlatformSessionHint(ref, options) +
` Only if session "${sessionAddress}" is yours: rerun with --session ${sessionArg} without device selectors, or run ${closeCommand}.`
);
}

return (
`${describeOpenWaitAttempt(options)}Run agent-device session list to inspect active sessions. ` +
`To reuse this device, rerun the command with --session ${sessionArg}. ` +
`To open a new session on this device, first run ${closeCommand}. ` +
`${waitForDeviceHint(options)}`.trimEnd()
`${describeOpenWaitAttempt(options)}${HOLDER_MAY_BE_FOREIGN}${CHOOSE_ANOTHER_DEVICE}${waitForDeviceHint(options)}` +
`Only if that session is yours: reuse --session ${sessionArg}, or run ${closeCommand} first.`
);
}

/**
* A device-in-use hint is read by an agent that may share the host with other agents, so the moves
* that leave the holding session alone come before any that reuse or close it. Diagnostic
* redaction caps a hint at 400 characters, so the text stays within that with the longest
* bounded session address.
*/
const HOLDER_MAY_BE_FOREIGN = 'The holding session may belong to another agent or user. ';
const CHOOSE_ANOTHER_DEVICE =
'Run agent-device devices and open another device with a device selector. ';

/**
* The record of a spent `--wait` budget, phrased so a caller that already waited is not told to
* wait again. Only an `open` can wait, so this is the only place the budget is spoken of.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ test('direct daemon requests cannot bypass reject lock policy for existing sessi
if (!response.ok) {
expect(response.error.code).toBe('INVALID_ARGS');
expect(response.error.message).toMatch(/--udid=SIM-999/i);
expect(response.error.hint).toMatch(/agent-device session list/i);
expect(response.error.hint).toMatch(/open it with a different --session name/i);
expect(response.error.hint).toMatch(/agent-device close --session qa-ios/i);
}
});
Expand Down Expand Up @@ -505,7 +505,7 @@ test('batch steps cannot bypass reject lock policy on nested direct requests', a
expect(response.error.code).toBe('INVALID_ARGS');
expect(response.error.message).toMatch(/Batch failed at step 1/i);
expect(response.error.message).toMatch(/--serial=emulator-5554/i);
expect(response.error.hint).toMatch(/agent-device session list/i);
expect(response.error.hint).toMatch(/open it with a different --session name/i);
expect(response.error.hint).toMatch(/agent-device close --session qa-ios/i);
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ test('a typed Maestro replay error keeps its recovery hint', async () => {
expect(response.ok).toBe(false);
if (response.ok) return;
expect(response.error.code).toBe('INVALID_ARGS');
expect(response.error.hint).toContain('agent-device session list');
expect(response.error.hint).toContain('open it with a different --session name');
expect(response.error.hint).toContain('--session default');
// The throw site's own details survive beside the projected hint.
expect(response.error.details?.session).toBe('default');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { makeSessionStore } from '../../../__tests__/support/store-factory.ts';
import { makeIosSession } from '../../../__tests__/support/session-factories.ts';
import { sessionChecks } from '../session-doctor-options.ts';

// The doctor's recovery command must carry each session's ADDRESS — the string `close --session`
// The doctor's close suggestion must carry each session's ADDRESS — the string `close --session`
// accepts — and dedupe by address: two cwd-scoped implicit sessions both carry the public name
// `default`, so a name compare hid them from each other and the printed
// `close --session default` addressed neither (#2031/#1394).
Expand All @@ -18,11 +18,26 @@ test('the same-device warning names the other session by its address, not its na

expect(check?.status).toBe('warn');
expect(check?.summary).toContain(other);
expect(check?.command).toContain(`--session ${other}`);
expect(check?.command).not.toContain('--session default');
expect(check?.hint).toContain(`agent-device close --session ${other}`);
expect(check?.hint).not.toContain('--session default');
// Agents run `command` verbatim and the other session may be another agent's.
expect(check?.hint).toMatch(/only if that session is yours/);
expect(check?.command).toBeUndefined();
expect(check?.evidence).toMatchObject({ session: here, sameDeviceSessions: [other] });
});

test('the same-device close suggestion shell-quotes a session name with metacharacters', () => {
const store = makeSessionStore();
const here = 'cwd:aaaaaaaaaaaaaaaa:default';
const other = 'a;b $(x)';
store.publish(here, makeIosSession('default'));
store.publish(other, makeIosSession(other));

const [check] = sessionChecks(store, here, store.get(here));

expect(check?.hint).toContain("agent-device close --session 'a;b $(x)' --platform");
});

test('a session alone on its device passes with its own address in evidence', () => {
const store = makeSessionStore();
const here = 'cwd:aaaaaaaaaaaaaaaa:default';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ test('open on in-use device returns DEVICE_IN_USE before readiness checks', asyn
expect(response?.ok).toBe(false);
if (response && !response.ok) {
expect(response.error.code).toBe('DEVICE_IN_USE');
expect(response.error.details?.hint).toContain('agent-device session list');
expect(response.error.details?.hint).toContain('agent-device devices');
expect(response.error.details?.hint).toContain('--session busy-session');
expect(response.error.details?.hint).toContain('agent-device close --session busy-session');
}
Expand Down Expand Up @@ -142,10 +142,10 @@ test('open on device owned by recording session returns recording recovery hint'
expect(response?.ok).toBe(false);
if (response && !response.ok) {
expect(response.error.code).toBe('DEVICE_IN_USE');
expect(response.error.details?.hint).toContain('Recording session "default" owns this device');
expect(response.error.details?.hint).toContain('A recording session, maybe another agent');
expect(response.error.details?.hint).toContain('agent-device record stop --session default');
expect(response.error.details?.hint).toContain('agent-device close --session default');
expect(response.error.details?.hint).toContain('agent-device session list');
expect(response.error.details?.hint).toContain('agent-device devices');
}
expect(mockEnsureDeviceReady).not.toHaveBeenCalled();
});
Expand Down
12 changes: 6 additions & 6 deletions packages/daemon/src/sessions/handlers/session-doctor-options.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { detectProjectRuntimeKind } from '@agent-device/host-kit/project-runtime';
import { publicPlatformString } from '@agent-device/kernel/device';
import { shellQuoteIfNeeded } from '@agent-device/kernel/device-shell';
import type { SessionStore } from '../../core/session-store.ts';
import type { DaemonRequest } from '../../core/daemon-request.ts';
import type { SessionState } from '../../core/session-state.ts';
Expand Down Expand Up @@ -120,6 +121,7 @@ export function sessionChecks(
];
}

const [otherSession] = sameDeviceSessions;
return [
{
id: 'session',
Expand All @@ -128,13 +130,11 @@ export function sessionChecks(
sameDeviceSessions.length > 0
? `Other active sessions target the same device: ${sameDeviceSessions.join(', ')}`
: `Active session ${session.name} targets ${session.device.name}`,
// No `command`: agents run that field verbatim, and the daemon cannot tell whether another
// session is the caller's, so the close stays conditional in the hint.
hint:
sameDeviceSessions.length > 0
? 'Close stale sessions before a QA run if they belong to old attempts.'
: undefined,
command:
sameDeviceSessions.length > 0
? `agent-device close --session ${sameDeviceSessions[0]} --platform ${publicPlatformString(session.device)}`
otherSession !== undefined
? `Before a QA run, run agent-device close --session ${shellQuoteIfNeeded(otherSession)} --platform ${publicPlatformString(session.device)} only if that session is yours and left from an old attempt.`
: undefined,
evidence: {
session: sessionName,
Expand Down
2 changes: 1 addition & 1 deletion scripts/help-conformance-cases.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -560,7 +560,7 @@ Use the output already shown to determine whether the feed-search UI is present,
recovery: { code: 'DEVICE_IN_USE', sample: DEVICE_IN_USE_SAMPLE },
task: quiz(
DEVICE_IN_USE_SAMPLE,
'The default web session cannot open https://example.test because the "checkout" session already owns the device. Without closing that session, what command can reuse it or wait for the device to free up?',
'The default web session cannot open https://example.test because the "checkout" session, which is yours, already holds the device. Without closing that session, what command can reuse it or wait for the device to free up?',
),
expectations: ['validPlanCommands', 'fullPrefix'],
matchers: [
Expand Down
2 changes: 1 addition & 1 deletion scripts/help-conformance-sample-outputs.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ Detected an overly complex or slow accessibility tree. Fell back to the private-
// (packages/daemon/src/core/session-recovery-hints.ts) — the parity test drives that exact producer.
export const DEVICE_IN_USE_SAMPLE = {
command: 'agent-device open https://example.test --platform web --session default',
output: `Error (DEVICE_IN_USE): Device is already in use by session "checkout". Not dispatched. Next: Run agent-device session list to inspect active sessions. To reuse this device, rerun the command with --session checkout. To open a new session on this device, first run agent-device close --session checkout. To wait for the device to free up, run the same open with --wait <ms>.`,
output: `Error (DEVICE_IN_USE): Device is already in use by session "checkout". Not dispatched. Next: The holding session may belong to another agent or user. Run agent-device devices and open another device with a device selector. To wait for the device to free up, run the same open with --wait <ms>. Only if that session is yours: reuse --session checkout, or run agent-device close --session checkout first.`,
};

// Enforced cross-daemon device claim conflict from
Expand Down
Loading