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 @@ -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 @@ -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);
Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.',
Expand Down Expand Up @@ -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`,
Expand Down Expand Up @@ -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.
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 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(),
Expand Down Expand Up @@ -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<string, unknown>) =>
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-',
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 positionals the platform close receives. A close without an app closes the session app,
* the way `close <app>` 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;
}
Comment thread
thymikee marked this conversation as resolved.
Resolved

async function prepareRepairClose(params: {
req: DaemonRequest;
Expand All @@ -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,
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