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 587629c4ba..d0dbac09cc 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/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..e738cf0538 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 @@ -6,7 +6,7 @@ import { storeSessionForTest } from '../../../__tests__/support/store-factory.ts * platform close must run and succeed BEFORE the healed `.ad` commits (never claim a successful * close a failed platform op didn't perform), a retry after a successful platform close but a * failed commit never re-dispatches that platform close, a competing writer can never clobber a - * COMPLETE artifact, and close identity is tracked per TARGETED app so an untargeted close or a + * COMPLETE artifact, and close identity is tracked per request target so an untargeted close or a * differently-targeted retry never wrongly skips the platform close. * * See `session-replay-repair-transaction.test.ts` for the shared repair-transaction background. @@ -276,7 +276,7 @@ test('BLOCKER 3: a competing second writer never overwrites a COMPLETE artifact expect(fs.readFileSync(healedPath, 'utf8')).toBe(committed); }); -test('BLOCKER 3 (third follow-up): an untargeted close that performed NO platform operation never lets a targeted retry skip the platform close', async () => { +test('BLOCKER 3 (third follow-up): an untargeted close receipt never lets a targeted retry skip the platform close', async () => { const { root, sessionStore, sessionName, logPath, leaseRegistry } = setup( 'agent-device-repair-transaction-close-identity-untargeted-', ); @@ -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 — it closes the session app (#4684); the + // commit then fails (no-clobber). const first = await handleCloseCommand({ host: createTestHostEnvironment(), platformServices: daemonPlatformServicesFixture(), @@ -303,7 +302,8 @@ test('BLOCKER 3 (third follow-up): an untargeted close that performed NO platfor leaseRegistry, }); expect(first.ok).toBe(false); - expect(mockLifecycleDispatch).not.toHaveBeenCalled(); + expect(mockLifecycleDispatch).toHaveBeenCalledTimes(1); + expect(mockLifecycleDispatch.mock.calls[0]?.[2]).toEqual(['com.example.app']); expect(sessionStore.get(sessionName)).toBeDefined(); const retry = await handleCloseCommand({ @@ -321,8 +321,9 @@ test('BLOCKER 3 (third follow-up): an untargeted close that performed NO platfor sessionStore, leaseRegistry, }); - expect(mockLifecycleDispatch).toHaveBeenCalledTimes(1); - expect(mockLifecycleDispatch.mock.calls[0]?.[2]).toEqual(['com.example.app']); + // The receipt is keyed on the request's positionals, so the targeted retry dispatches again. + expect(mockLifecycleDispatch).toHaveBeenCalledTimes(2); + expect(mockLifecycleDispatch.mock.calls[1]?.[2]).toEqual(['com.example.app']); expect(retry.ok).toBe(true); }); 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..af13c2cc45 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 app the platform close targets. `close` without an app closes the session app (#4684), the + * same way `close ` does; a native session that never opened an app has nothing to close. + * A web session's close always dispatches, with no positional. + */ +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; @@ -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, };