Skip to content
Closed
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 @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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-',
);
Expand All @@ -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(),
Expand All @@ -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({
Expand All @@ -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);
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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([]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<readonly string[]> = [];
const bindDevice: Parameters<typeof close>[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();
});
Original file line number Diff line number Diff line change
Expand Up @@ -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 <app>` 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;
Expand Down Expand Up @@ -194,10 +202,11 @@ async function dispatchTargetedPlatformClose(params: {
lifecycle: CloseRuntime | CloseRuntimeWithRuntimeHintClear;
}): Promise<unknown> {
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',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof dependencies.host.runAdb>(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') {
Expand All @@ -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' },
Expand Down Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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<typeof createAndroidProviderShellState>,
): {
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 };
}
12 changes: 11 additions & 1 deletion test/integration/provider-scenarios/replay-repair-world.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<object>();

export function androidRepairAdbResult(
args: readonly string[],
shellState: ReturnType<typeof createAndroidProviderShellState>,
Expand All @@ -12,14 +15,21 @@ 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') {
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',
stdout: stoppedSettings.has(shellState)
? 'mCurrentFocus=null\n'
: 'mCurrentFocus=Window{42 u0 com.android.settings/.Settings}\n',
stderr: '',
exitCode: 0,
};
Expand Down
Loading