diff --git a/packages/daemon/src/core/composite-resource-admission-ime.test.ts b/packages/daemon/src/core/composite-resource-admission-ime.test.ts index 56edee2d21..2df72c6d21 100644 --- a/packages/daemon/src/core/composite-resource-admission-ime.test.ts +++ b/packages/daemon/src/core/composite-resource-admission-ime.test.ts @@ -145,7 +145,8 @@ test.each(['batch', 'replay'] as const)( expect(failed.json.error?.data?.details).toMatchObject({ reason: 'session_cleanup_incomplete', failedSteps: ['application_lifecycle'], - dispatchedSteps: 1, + // home and the session app's platform close. + dispatchedSteps: 2, }); expect(world.home).toHaveBeenCalledOnce(); expect(helper.currentIme()).toBe(helperIme); diff --git a/packages/daemon/src/server/__tests__/request-router-typed-error.test.ts b/packages/daemon/src/server/__tests__/request-router-typed-error.test.ts index 9d4ac838a9..1feff918b0 100644 --- a/packages/daemon/src/server/__tests__/request-router-typed-error.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-typed-error.test.ts @@ -192,8 +192,8 @@ test('BLOCKER 2 (second follow-up): a repair-close platform-close failure surfac }), ); - // A targeted close (an explicit positional app target) is what makes the - // repair-armed platform close actually dispatch instead of no-op. + // A targeted close (an explicit positional app target) makes the repair-armed platform close + // dispatch; a session with no app dispatches none. const response = await handler(request('close', { positionals: ['com.example.app'] })); expect(response.ok).toBe(false); @@ -227,10 +227,9 @@ test('#1391: an ordinary close-time script-save failure surfaces details.reason/ sessionStore.publish('typed-error', session); try { - // Untargeted close: no positionals, so no platform close is dispatched - // (`shouldDispatchPlatformClose`) — isolates the script-save failure from - // any platform-close error, matching BLOCKER 2's own targeted-vs-untargeted - // distinction above. + // Untargeted close on a session with no app: no platform close is dispatched, which isolates + // the script-save failure from any platform-close error, matching BLOCKER 2's own + // targeted-vs-untargeted distinction above. const response = await handler(request('close')); expect(response.ok).toBe(false); diff --git a/packages/daemon/src/sessions/__tests__/replay-repair/session-replay-repair-transaction-close-ordering.test.ts b/packages/daemon/src/sessions/__tests__/replay-repair/session-replay-repair-transaction-close-ordering.test.ts index fa45ee15cc..86920135e0 100644 --- a/packages/daemon/src/sessions/__tests__/replay-repair/session-replay-repair-transaction-close-ordering.test.ts +++ b/packages/daemon/src/sessions/__tests__/replay-repair/session-replay-repair-transaction-close-ordering.test.ts @@ -95,8 +95,8 @@ test('BLOCKER 2 (new): a repair close whose PLATFORM close fails never commits a const session = makeCompleteRepairSession(sessionStore, sessionName, root); const healedPath = path.join(root, 'flow.healed.ad'); - // A targeted close (an explicit positional app target) is what makes - // `dispatchTargetedPlatformClose` actually dispatch instead of no-op. + // A targeted close (an explicit positional app target) makes the platform close dispatch; a + // session with no app dispatches none. const platformCloseError = new AppError('DEVICE_UNAVAILABLE', 'platform close failed', { reason: 'device_disconnected', hint: 'Reconnect the device and retry close.', @@ -184,8 +184,8 @@ test('BLOCKER 3 (second follow-up): a retry after a SUCCESSFUL platform close bu // default path — the commit must refuse to clobber it, giving a // deterministic commit FAILURE after a platform close that genuinely // succeeds (the lifecycle seam's `beforeEach` default resolves). A - // targeted close (an explicit positional app target) is what makes - // `dispatchTargetedPlatformClose` actually dispatch instead of no-op. + // targeted close (an explicit positional app target) makes the + // platform close dispatch; a session with no app dispatches none. fs.writeFileSync( healedPath, `context platform=ios device="x"\nclick id="old"\n${HEAL_COMPLETE_SENTINEL}\n`, @@ -281,7 +281,7 @@ test('BLOCKER 3 (third follow-up): an untargeted close that performed NO platfor 'agent-device-repair-transaction-close-identity-untargeted-', ); sessionStore.retire(sessionStore.lookup(sessionName)!); - makeCompleteRepairSession(sessionStore, sessionName, root); + makeCompleteRepairSession(sessionStore, sessionName, root).appBundleId = undefined; const healedPath = path.join(root, 'flow.healed.ad'); // A prior COMPLETE artifact already sits at the default path so the commit // deterministically fails and the session is retained for retry. @@ -290,9 +290,8 @@ test('BLOCKER 3 (third follow-up): an untargeted close that performed NO platfor `context platform=ios device="x"\nclick id="old"\n${HEAL_COMPLETE_SENTINEL}\n`, ); - // First attempt: UNTARGETED close — `shouldDispatchPlatformClose` is false - // (no positional target, not `web`), so the platform close never dispatches - // at all; the commit then fails (no-clobber). + // First attempt: UNTARGETED close on a session with no app (not `web`), so the platform close + // never dispatches at all; the commit then fails (no-clobber). const first = await handleCloseCommand({ host: createTestHostEnvironment(), platformServices: daemonPlatformServicesFixture(), @@ -326,6 +325,39 @@ test('BLOCKER 3 (third follow-up): an untargeted close that performed NO platfor expect(retry.ok).toBe(true); }); +test('an untargeted close dispatches the session app once, and a retry naming that app skips the repeat', async () => { + const { root, sessionStore, sessionName, logPath, leaseRegistry } = setup( + 'agent-device-repair-transaction-close-identity-session-app-', + ); + sessionStore.retire(sessionStore.lookup(sessionName)!); + makeCompleteRepairSession(sessionStore, sessionName, root); + fs.writeFileSync( + path.join(root, 'flow.healed.ad'), + `context platform=ios device="x"\nclick id="old"\n${HEAL_COMPLETE_SENTINEL}\n`, + ); + const closeRequest = (positionals: string[], flags: Record) => + handleCloseCommand({ + host: createTestHostEnvironment(), + platformServices: daemonPlatformServicesFixture(), + req: { token: 't', session: sessionName, command: 'close', positionals, flags }, + sessionName, + logPath, + sessionStore, + leaseRegistry, + }); + + const first = await closeRequest([], {}); + expect(first.ok).toBe(false); + expect(mockLifecycleDispatch).toHaveBeenCalledTimes(1); + expect(mockLifecycleDispatch.mock.calls[0]?.[2]).toEqual(['com.example.app']); + + const retry = await closeRequest(['com.example.app'], { + saveScript: path.join(root, 'flow.promoted.ad'), + }); + expect(retry.ok).toBe(true); + expect(mockLifecycleDispatch).toHaveBeenCalledTimes(1); +}); + test('BLOCKER 3 (third follow-up): a retry targeting a DIFFERENT app than the succeeded close never skips the platform close for the new target', async () => { const { root, sessionStore, sessionName, logPath, leaseRegistry } = setup( 'agent-device-repair-transaction-close-identity-changed-target-', diff --git a/packages/daemon/src/sessions/handlers/__tests__/session-provider-shutdown.test.ts b/packages/daemon/src/sessions/handlers/__tests__/session-provider-shutdown.test.ts index 600a759d06..6071f644b4 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/session-provider-shutdown.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/session-provider-shutdown.test.ts @@ -157,7 +157,7 @@ for (const platform of ['ios', 'android'] as const) { test(`${platform} close --shutdown finalizes before releasing a retained lease exactly once`, async () => { const world = scenario(platform, true); expect(await world.run()).toMatchObject({ ok: true, data: { shutdown: { success: true } } }); - expect(world.events).toEqual(['finalize', 'release']); + expect(world.events).toEqual(['close', 'finalize', 'release']); expect(world.release).toHaveBeenCalledOnce(); expect(world.sessionStore.get('test')).toBeUndefined(); expect(world.leaseRegistry.listActiveLeases()).toEqual([]); diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-lifecycle-runtime.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-lifecycle-runtime.test.ts index 27ff1fc970..25f3f55966 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-lifecycle-runtime.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-lifecycle-runtime.test.ts @@ -432,3 +432,41 @@ test('a supported Android close clears admitted runtime hints exactly once', asy }), ); }); + +test('close without an app closes the session app, and a session with no app closes without one', async () => { + const sessionStore = makeSessionStore(); + const device = { + platform: 'android' as const, + id: 'emulator-5554', + name: 'Pixel', + kind: 'emulator' as const, + target: 'mobile' as const, + booted: true, + }; + const withApp = makeSession('close-session-app', device); + withApp.appBundleId = 'com.example.app'; + sessionStore.publish(withApp.name, withApp); + sessionStore.publish('close-no-app', makeSession('close-no-app', device)); + const closed: Array = []; + const bindDevice: Parameters[0]['bindDevice'] = async (boundDevice, use) => { + const binding = await mockBindDeviceRuntime(boundDevice, use); + return { + ...binding, + operations: { + ...binding.operations, + closeApplication: async (input: CloseApplicationInput) => { + closed.push(input.positionals); + }, + }, + }; + }; + + const appClose = await close({ sessionName: withApp.name, sessionStore, bindDevice }); + const noAppClose = await close({ sessionName: 'close-no-app', sessionStore, bindDevice }); + + expect(appClose?.ok).toBe(true); + expect(noAppClose?.ok).toBe(true); + expect(closed).toEqual([['com.example.app']]); + expect(sessionStore.get(withApp.name)).toBeUndefined(); + expect(sessionStore.get('close-no-app')).toBeUndefined(); +}); diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts index 8add840bc0..660d040e26 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts @@ -76,8 +76,16 @@ type RepairClosePreparation = | { repairArmed: boolean; healedScriptPath?: string; aborted?: boolean } | { response: DaemonResponse }; -const shouldDispatchPlatformClose = (req: DaemonRequest, session: SessionState): boolean => - (req.positionals?.length ?? 0) > 0 || isWebSession(session); +/** + * The positionals the platform close receives. A close without an app closes the session app, + * the way `close ` does (#4684). A web session always dispatches, with no app. A native + * session that never opened an app has nothing to close. + */ +function platformCloseTarget(req: DaemonRequest, session: SessionState): string[] | undefined { + if (req.positionals && req.positionals.length > 0) return req.positionals; + if (isWebSession(session)) return []; + return session.appBundleId ? [session.appBundleId] : undefined; +} async function prepareRepairClose(params: { req: DaemonRequest; @@ -89,7 +97,7 @@ async function prepareRepairClose(params: { const { req, ref, logPath, sessionStore, lifecycle } = params; const session = sessionStore.requireCurrent(ref); const repairArmed = isRepairArmedSession(session); - const closeReceipt = JSON.stringify(req.positionals ?? []); + const closeReceipt = JSON.stringify(platformCloseTarget(req, session) ?? []); if (repairArmed && !hasRepairPlatformCloseReceipt(session, closeReceipt)) { const platformCloseError = await dispatchTargetedPlatformClose({ req, @@ -194,10 +202,11 @@ async function dispatchTargetedPlatformClose(params: { lifecycle: CloseRuntime | CloseRuntimeWithRuntimeHintClear; }): Promise { const { req, session, logPath, lifecycle } = params; - if (!shouldDispatchPlatformClose(req, session)) return undefined; + const positionals = platformCloseTarget(req, session); + if (!positionals) return undefined; try { await lifecycle.operations.closeApplication({ - positionals: req.positionals ?? [], + positionals, outPath: req.flags?.out, appBundleId: session.appBundleId, surface: session.surface ?? 'app', diff --git a/test/integration/provider-scenarios/android-test-suite.test.ts b/test/integration/provider-scenarios/android-test-suite.test.ts index afe86e6e17..c24267558a 100644 --- a/test/integration/provider-scenarios/android-test-suite.test.ts +++ b/test/integration/provider-scenarios/android-test-suite.test.ts @@ -194,11 +194,13 @@ test( world.adbCalls.find((call) => call.slice(0, 3).join(' ') === 'shell input tap'), ['shell', 'input', 'tap', '180', '330'], ); + // Each flow's launchApp stops the app, and the suite's close of each flow's session + // stops the session app again. assert.equal( world.adbCalls.filter( (call) => call.join(' ') === 'shell am force-stop com.android.settings', ).length, - 2, + 4, ); // The second flow's open finds the helper the first flow installed, so its launch probe // adds one capture. diff --git a/test/integration/provider-scenarios/limrun-android-performance.test.ts b/test/integration/provider-scenarios/limrun-android-performance.test.ts index 23a59370f8..9dd1a4e0dc 100644 --- a/test/integration/provider-scenarios/limrun-android-performance.test.ts +++ b/test/integration/provider-scenarios/limrun-android-performance.test.ts @@ -42,9 +42,15 @@ vi.mock('@agent-device/host-kit/command', async (original) => ({ test('Limrun Android memory sampling reaches the allocated session ADB through daemon dispatch', async () => { const dependencies = createLimrunRuntimeDependencies({ env: {}, cwd: process.cwd() }); + // Plain close stops the session app; the fake device then reports it gone. + let settingsStopped = false; const sessionExec = vi.fn(async (invocation) => { const args = [...invocation.command]; const ok = { exitCode: 0, stdout: '', stderr: '' }; + if (args.join(' ') === 'shell am force-stop com.android.settings') { + settingsStopped = true; + return ok; + } if (args[0] === 'disconnect') return ok; expect(invocation.target.selector).toEqual({ kind: 'serial', serial: '127.0.0.1:62001' }); if (args.join(' ') === 'shell dumpsys meminfo com.android.settings') { @@ -57,7 +63,10 @@ test('Limrun Android memory sampling reaches the allocated session ADB through d ) { return { ...ok, stdout: 'Status: ok\nActivity: com.android.settings/.Settings\n' }; } - return respondToAndroidSettingsAdbCommand(args, '', '', {}); + return respondToAndroidSettingsAdbCommand(args, '', '', { + ...(settingsStopped ? { dumpsysWindow: () => 'mCurrentFocus=null\n' } : {}), + pidof: () => (settingsStopped ? { exitCode: 1, stdout: '', stderr: '' } : undefined), + }); }); const registration = createLimrunRuntime( { apiKey: 'test-api-key' }, @@ -108,7 +117,14 @@ test('Limrun Android memory sampling reaches the allocated session ADB through d 'meminfo', 'com.android.settings', ]); + sessionExec.mockClear(); assertRpcOk(await daemon.callCommand('close', [], scope, options)); + expect(sessionExec.mock.calls.map(([invocation]) => invocation.command)).toContainEqual([ + 'shell', + 'am', + 'force-stop', + 'com.android.settings', + ]); } finally { await daemon.close(); await runtime.shutdown(); diff --git a/test/integration/provider-scenarios/replay-repair-abort-close.test.ts b/test/integration/provider-scenarios/replay-repair-abort-close.test.ts index d047cbda3f..0fd0f4ce71 100644 --- a/test/integration/provider-scenarios/replay-repair-abort-close.test.ts +++ b/test/integration/provider-scenarios/replay-repair-abort-close.test.ts @@ -6,12 +6,11 @@ import { test } from 'vitest'; import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from '../../../src/__tests__/test-utils/android-snapshot-helper.ts'; import type { AndroidAdbProvider } from '@agent-device/platform-android/mechanics'; import { assertRpcError, assertRpcOk } from './assertions.ts'; -import { androidSettingsXml, androidSnapshotHelperOutput } from './android-world.ts'; import { - androidImeLifecycleAdbResult, createAndroidProviderShellState, updateAndroidProviderImeShellState, } from './android-ime-lifecycle-world.ts'; +import { androidRepairAdbResult } from './replay-repair-world.ts'; import { PROVIDER_SCENARIO_ANDROID } from './fixtures.ts'; import { createProviderScenarioHarness } from './harness.ts'; @@ -109,33 +108,3 @@ test('Provider-backed integration: repair close paths (abort, plain close, commi fs.rmSync(tempRoot, { recursive: true, force: true }); } }, 30_000); - -function androidRepairAdbResult( - args: readonly string[], - shellState: ReturnType, -): { - stdout: string; - stderr: string; - exitCode: number; -} { - const ime = androidImeLifecycleAdbResult(args.join(' '), args, shellState); - if (ime) return ime; - if (args.join(' ') === 'shell getprop sys.boot_completed') { - return { stdout: '1\n', stderr: '', exitCode: 0 }; - } - if (args.join(' ') === 'shell dumpsys window windows') { - return { - stdout: 'mCurrentFocus=Window{42 u0 com.android.settings/.Settings}\n', - stderr: '', - exitCode: 0, - }; - } - if (args.join(' ').startsWith('shell am instrument ')) { - return { - stdout: androidSnapshotHelperOutput(androidSettingsXml('Display')), - stderr: '', - exitCode: 0, - }; - } - return { stdout: '', stderr: '', exitCode: 0 }; -} diff --git a/test/integration/provider-scenarios/replay-repair-world.ts b/test/integration/provider-scenarios/replay-repair-world.ts index 9bbd129919..6c508f10ee 100644 --- a/test/integration/provider-scenarios/replay-repair-world.ts +++ b/test/integration/provider-scenarios/replay-repair-world.ts @@ -4,6 +4,9 @@ import { createAndroidProviderShellState, } from './android-ime-lifecycle-world.ts'; +// Shell states whose Settings app was force-stopped and not started since. +const stoppedSettings = new WeakSet(); + export function androidRepairAdbResult( args: readonly string[], shellState: ReturnType, @@ -12,6 +15,11 @@ export function androidRepairAdbResult( stderr: string; exitCode: number; } { + if (args.join(' ') === 'shell am force-stop com.android.settings') { + stoppedSettings.add(shellState); + } else if (args[0] === 'shell' && args[1] === 'am' && args[2]?.startsWith('start')) { + stoppedSettings.delete(shellState); + } const ime = androidImeLifecycleAdbResult(args.join(' '), args, shellState); if (ime) return ime; if (args.join(' ') === 'shell getprop sys.boot_completed') { @@ -19,7 +27,9 @@ export function androidRepairAdbResult( } if (args.join(' ') === 'shell dumpsys window windows') { return { - stdout: 'mCurrentFocus=Window{42 u0 com.android.settings/.Settings}\n', + stdout: stoppedSettings.has(shellState) + ? 'mCurrentFocus=null\n' + : 'mCurrentFocus=Window{42 u0 com.android.settings/.Settings}\n', stderr: '', exitCode: 0, };