diff --git a/packages/daemon/src/core/__tests__/session-selector.test.ts b/packages/daemon/src/core/__tests__/session-selector.test.ts index 39ea0ba563..6fe6eba913 100644 --- a/packages/daemon/src/core/__tests__/session-selector.test.ts +++ b/packages/daemon/src/core/__tests__/session-selector.test.ts @@ -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; diff --git a/packages/daemon/src/core/session-recovery-hints.test.ts b/packages/daemon/src/core/session-recovery-hints.test.ts index d469b0440c..101e7781fa 100644 --- a/packages/daemon/src/core/session-recovery-hints.test.ts +++ b/packages/daemon/src/core/session-recovery-hints.test.ts @@ -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::default` — building it from the @@ -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 }); + + 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 ')).toBeGreaterThan(-1); + expect(hint.indexOf('--wait ')).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 ')).toBeGreaterThan(-1); + expect(hint.indexOf('--wait ')).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'); @@ -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 }, + 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); +}); diff --git a/packages/daemon/src/core/session-recovery-hints.ts b/packages/daemon/src/core/session-recovery-hints.ts index f3a425bb24..2a75abbbda 100644 --- a/packages/daemon/src/core/session-recovery-hints.ts +++ b/packages/daemon/src/core/session-recovery-hints.ts @@ -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}.` ); } @@ -114,8 +112,9 @@ 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, @@ -123,10 +122,9 @@ function buildForeignWorkspaceSessionRecoveryHint( ): 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.` ); } @@ -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. diff --git a/packages/daemon/src/server/__tests__/request-router-lock-policy.test.ts b/packages/daemon/src/server/__tests__/request-router-lock-policy.test.ts index 6666030a70..b6f16ebd96 100644 --- a/packages/daemon/src/server/__tests__/request-router-lock-policy.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-lock-policy.test.ts @@ -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); } }); @@ -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); } }); diff --git a/packages/daemon/src/sessions/__tests__/replay-maestro/session-replay-maestro-error-projection.test.ts b/packages/daemon/src/sessions/__tests__/replay-maestro/session-replay-maestro-error-projection.test.ts index 4f760efd70..2bed45225c 100644 --- a/packages/daemon/src/sessions/__tests__/replay-maestro/session-replay-maestro-error-projection.test.ts +++ b/packages/daemon/src/sessions/__tests__/replay-maestro/session-replay-maestro-error-projection.test.ts @@ -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'); diff --git a/packages/daemon/src/sessions/handlers/__tests__/session-doctor-options.test.ts b/packages/daemon/src/sessions/handlers/__tests__/session-doctor-options.test.ts index daad8a8fbb..1cad2babe9 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/session-doctor-options.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/session-doctor-options.test.ts @@ -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). @@ -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'; diff --git a/packages/daemon/src/sessions/handlers/__tests__/session-relaunch-guards.test.ts b/packages/daemon/src/sessions/handlers/__tests__/session-relaunch-guards.test.ts index e6b2e23e17..dbe3dd5e22 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/session-relaunch-guards.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/session-relaunch-guards.test.ts @@ -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'); } @@ -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(); }); diff --git a/packages/daemon/src/sessions/handlers/session-doctor-options.ts b/packages/daemon/src/sessions/handlers/session-doctor-options.ts index ea688480fa..76c54a72e7 100644 --- a/packages/daemon/src/sessions/handlers/session-doctor-options.ts +++ b/packages/daemon/src/sessions/handlers/session-doctor-options.ts @@ -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'; @@ -120,6 +121,7 @@ export function sessionChecks( ]; } + const [otherSession] = sameDeviceSessions; return [ { id: 'session', @@ -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, diff --git a/scripts/help-conformance-cases.mjs b/scripts/help-conformance-cases.mjs index bcccde117b..f9f7d4e7fa 100644 --- a/scripts/help-conformance-cases.mjs +++ b/scripts/help-conformance-cases.mjs @@ -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: [ diff --git a/scripts/help-conformance-sample-outputs.mjs b/scripts/help-conformance-sample-outputs.mjs index 7f408cd08c..b2acf2650d 100644 --- a/scripts/help-conformance-sample-outputs.mjs +++ b/scripts/help-conformance-sample-outputs.mjs @@ -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 .`, + 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 . Only if that session is yours: reuse --session checkout, or run agent-device close --session checkout first.`, }; // Enforced cross-daemon device claim conflict from