Skip to content
Open
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
2 changes: 1 addition & 1 deletion packages/command-surface/src/management/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ const openCommandMetadata = defineFieldCommandMetadata(

const closeCommandMetadata = defineFieldCommandMetadata(
'close',
'Close the named app, or close the active session app when app is omitted. The shutdown option also stops the session simulator or emulator where supported; close alone never stops the device. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s or a killed process does not exit within 10s; a new process that Android starts afterwards does not fail it. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running. If close cannot confirm its cleanup on a session that holds a device claim, the session and its claim stay. A repeated close retries cleanup with the same options, except that save-script must be omitted after publication.',
'Close the named app, or close the active session app when app is omitted. The shutdown option also stops the session simulator or emulator where supported; close alone never stops the device. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s or a killed process does not exit within 10s; a new process that Android starts afterwards does not fail it. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running. Plain close can still end a local Android session and release its claim if adb returns a valid device list that omits the session’s serial, even if the list is empty. If close cannot confirm its remaining cleanup on a session that holds a device claim, the session and its claim stay. A repeated close retries cleanup with the same options, except that save-script must be omitted after publication.',
{
app: stringField('Optional app to close.'),
shutdown: booleanField('Shutdown the session/device where supported.'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export function daemonPlatformServicesFixture(
deviceBootObservation: Object.freeze({
observeBootTimeMs: observeBootTimeMsFixture,
}),
observeLocalAndroidAdbSerials: observeLocalAndroidAdbSerialsFixture,
ensureLocalDeviceReady: ensureLocalDeviceReadyFixture,
resolveRequestedOpenSurface: resolveRequestedOpenSurfaceFixture,
validateOpenRelaunchTarget: validateOpenRelaunchTargetFixture,
Expand All @@ -37,6 +38,7 @@ export function daemonPlatformServicesFixture(

/** The canned runner-session observation: no live runner on any device. */
const observeRunnerSessionFixture = vi.fn(async (_deviceId: string) => undefined);
const observeLocalAndroidAdbSerialsFixture = vi.fn(async () => undefined);
/** The canned foreground answer: nothing observable to name a sole foreground app. */
const resolveSoleForegroundAppFixture = vi.fn(
async (_params: Readonly<{ simulatorSetPath?: string }>) => undefined,
Expand Down
6 changes: 3 additions & 3 deletions packages/daemon/src/core/platform-services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@ export type EnsureLocalDeviceReady = (device: DeviceInfo, signal: AbortSignal) =

/**
* Root-composed platform services the daemon asks of the host machine for work that binds no
* device runtime, over mechanics the daemon must never name or load itself. The two observation
* members are published contracts types; readiness and open-target classification are signatures
* declared here over neutral types. Device execution is NOT in this port and never
* device runtime, over mechanics the daemon must never name or load itself.
* Device execution is NOT in this port and never
* enters it (ADR 0019): it goes through the request-bound runtime binding
* (`RequestExecutionScope.bindDevice`), whose owner facts stay the only admission authority.
*/
export type DaemonPlatformServices = Readonly<{
appleSessionObservation: AppleSessionObservation;
deviceBootObservation: DeviceBootObservationService;
observeLocalAndroidAdbSerials(signal?: AbortSignal): Promise<readonly string[] | undefined>;
ensureLocalDeviceReady: EnsureLocalDeviceReady;
resolveRequestedOpenSurface(params: {
device: DeviceInfo;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,11 @@ afterEach(() => {
function claimDevice(
sessionStore: ReturnType<typeof makeSessionStore>,
session: string,
target: SessionState['device'] = device,
): ReturnType<typeof acquireDeviceClaim> {
return acquireDeviceClaim({
env: process.env,
device,
device: target,
session,
workspace: process.cwd(),
stateDir: sessionStore.resolveDaemonStateDir(),
Expand All @@ -76,25 +77,28 @@ async function openSession(
sessionName: string,
options: Readonly<{
claim?: false;
device?: SessionState['device'];
sessionStore?: ReturnType<typeof makeSessionStore>;
lease?: Readonly<{ registry: LeaseRegistryInstance; retainOnClose?: true }>;
scriptPublication?: SessionState['scriptPublication'];
}> = {},
) {
const sessionStore = makeSessionStore();
const sessionStore = options.sessionStore ?? makeSessionStore();
const target = options.device ?? device;
const acquired =
options.claim === false ? undefined : await claimDevice(sessionStore, sessionName);
options.claim === false ? undefined : await claimDevice(sessionStore, sessionName, target);
if (acquired && acquired.status !== 'acquired') {
throw new Error('expected the test session to acquire a device claim');
}
const lease = options.lease?.registry.allocateLease({
tenantId: 'tenant-a',
runId: 'run-1',
leaseBackend: 'android-instance',
deviceKey: 'android:' + device.id,
deviceKey: 'android:' + target.id,
...(options.lease.retainOnClose ? { retainOnClose: true } : {}),
});
sessionStore.publish(sessionName, {
...makeSession(sessionName, device),
...makeSession(sessionName, target),
appBundleId: 'com.example.app',
...(acquired ? { deviceClaim: acquired.ownership } : {}),
...(options.scriptPublication ? { scriptPublication: options.scriptPublication } : {}),
Expand Down Expand Up @@ -122,12 +126,17 @@ function close(
leaseLifecycleProvider?: LeaseLifecycleProvider;
saveScript?: true;
app?: string;
observeLocalAndroidAdbSerials?: () => Promise<readonly string[] | undefined>;
}> = {},
) {
return handleSessionCommands({
host: createTestHostEnvironment(),
createCommandSurface: fakeCreateCommandSurface,
platformServices: daemonPlatformServicesFixture(),
platformServices: daemonPlatformServicesFixture(
options.observeLocalAndroidAdbSerials
? { observeLocalAndroidAdbSerials: options.observeLocalAndroidAdbSerials }
: {},
),
lifecycleOperationsLoader: loader,
req: {
token: 't',
Expand Down Expand Up @@ -164,6 +173,104 @@ const cleanupIncomplete = {
}),
};

const wifiDevice = { ...device, id: '192.0.2.10:5555', kind: 'device' as const };
const movedDevice = { ...wifiDevice, id: '192.0.2.11:5555' };
const pidofFailure = new AppError('COMMAND_FAILED', 'Could not read process state', {
reason: 'android-process-probe-unavailable',
});

test('plain close releases the last device claim when adb confirms an empty inventory', async () => {
const name = 'last-adb-serial';
const sessionStore = await openSession(name, { device: wifiDevice });
const { loader } = lifecycleOperationsSpy({
closeApplication: async () => {
throw pidofFailure;
},
});

await expect(
close(sessionStore, name, loader, { observeLocalAndroidAdbSerials: async () => [] }),
).resolves.toMatchObject({ ok: true, data: { session: name } });
expect(sessionStore.get(name)).toBeUndefined();
expect(inspectDeviceClaims({ serial: wifiDevice.id }, process.env)).toEqual([]);
});

test('plain close retires only the session and claim for a serial that left local adb', async () => {
const sessionName = 'vanished-adb-serial';
const sessionStore = await openSession(sessionName, { device: wifiDevice });
await openSession('other-session', { device: movedDevice, sessionStore });
const { loader, finalizeApplicationClose } = lifecycleOperationsSpy({
closeApplication: async () => {
throw pidofFailure;
},
});
const observeLocalAndroidAdbSerials = vi.fn(async () => [movedDevice.id]);

await expect(
close(sessionStore, sessionName, loader, { observeLocalAndroidAdbSerials }),
).resolves.toMatchObject({ ok: true, data: { session: sessionName } });

expect(finalizeApplicationClose).toHaveBeenCalledOnce();
expect(sessionStore.get(sessionName)).toBeUndefined();
expect(inspectDeviceClaims({ serial: wifiDevice.id }, process.env)).toEqual([]);
expect(sessionStore.get('other-session')?.device.id).toBe(movedDevice.id);
expect(inspectDeviceClaims({ serial: movedDevice.id }, process.env)[0]?.claim?.session).toBe(
'other-session',
);
});

test.each([
{ condition: 'still listed', serials: [wifiDevice.id], error: pidofFailure },
{ condition: 'of unknown presence', serials: undefined, error: pidofFailure },
{
condition: 'absent but the app-stop failure has no typed reason',
serials: [movedDevice.id],
error: new AppError('COMMAND_FAILED', pidofFailure.message),
},
])(
'plain close keeps the session and claim when the serial is $condition',
async ({ serials, error }) => {
const sessionName = 'retain-adb-serial';
const sessionStore = await openSession(sessionName, { device: wifiDevice });
const { loader } = lifecycleOperationsSpy({
closeApplication: async () => {
throw error;
},
});

await expect(
close(sessionStore, sessionName, loader, {
observeLocalAndroidAdbSerials: async () => serials,
}),
).rejects.toBe(error);

expect(sessionStore.get(sessionName)).toBeDefined();
expect(inspectDeviceClaims({ serial: wifiDevice.id }, process.env)[0]?.claim?.session).toBe(
sessionName,
);
},
);

test('close preserves its app-stop error if the session retires during the inventory read', async () => {
const name = 'retired-during-inventory';
const sessionStore = await openSession(name, { device: wifiDevice, claim: false });
const ref = sessionStore.lookup(name)!;
const { loader } = lifecycleOperationsSpy({
closeApplication: async () => {
throw pidofFailure;
},
});
const observeLocalAndroidAdbSerials = vi.fn(async () => {
sessionStore.retire(ref);
return [movedDevice.id];
});

await expect(close(sessionStore, name, loader, { observeLocalAndroidAdbSerials })).rejects.toBe(
pidofFailure,
);
expect(observeLocalAndroidAdbSerials).toHaveBeenCalledOnce();
});

test('a retried close reruns the failed cleanup and then releases the device claim', async () => {
const sessionName = 'close-retry-releases-claim';
const sessionStore = await openSession(sessionName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import type { DaemonResponse } from '@agent-device/kernel/contracts';
import type { DaemonPlatformServices } from '../../../core/platform-services.ts';
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
import { getRequestSignal } from '@agent-device/host-kit/request';
import { AppError, normalizeError } from '@agent-device/kernel/errors';
import type { LeaseLifecycleProvider, TargetShutdownResult } from '@agent-device/contracts/device';
import type { DaemonRequest } from '../../../core/daemon-request.ts';
Expand Down Expand Up @@ -365,6 +366,7 @@
clearRuntimeHints: admission.clearRuntimeHints,
repairArmed: repair.repairArmed,
platformResourceCleanup,
observeLocalAndroidAdbSerials: params.platformServices.observeLocalAndroidAdbSerials,
}),
);
if (closed.kind === 'response') return closed.response;
Expand Down Expand Up @@ -423,6 +425,7 @@
clearRuntimeHints?: RuntimeHintClearOperation;
repairArmed: boolean;
platformResourceCleanup: PlatformResourceCleanup;
observeLocalAndroidAdbSerials: DaemonPlatformServices['observeLocalAndroidAdbSerials'];
}): Promise<SessionCloseFinalization> {
const {
req,
Expand All @@ -437,7 +440,7 @@
const { address: sessionName } = ref;
const cleanupFailures: SessionCleanupFailure[] = [];
const {
platformCloseError,
platformCloseError: appStopError,
retainExecutionHost,
saveScriptOutcome,
shutdownPrepared,
Expand All @@ -456,7 +459,12 @@
finalizeOrdinaryCloseScript,
platformResourceCleanup: params.platformResourceCleanup,
});
let session = sessionStore.requireCurrent(ref);
const mayRetireAfterAppStopError =
cleanupFailures.length === 0 && (await isAndroidCloseSerialAbsent(appStopError, params));
const platformCloseError = mayRetireAfterAppStopError ? undefined : appStopError;
let session = sessionStore.resolveCurrent(ref);
if (!session && appStopError) throw appStopError;
session ??= sessionStore.requireCurrent(ref);
// Each cleanup report is built where the session's fate is decided, so its diagnostic and hint
// describe what actually happened to the session. It is built even when a platform-close error
// takes precedence, so that error never hides the cleanup failures.
Expand Down Expand Up @@ -504,6 +512,50 @@
};
}

async function isAndroidCloseSerialAbsent(
error: unknown,
{
req,
ref,
sessionStore,
lifecycle,
observeLocalAndroidAdbSerials,
}: {
req: DaemonRequest;
ref: SessionRef;
sessionStore: SessionStore;
lifecycle: CloseRuntime | CloseRuntimeWithRuntimeHintClear;
observeLocalAndroidAdbSerials: DaemonPlatformServices['observeLocalAndroidAdbSerials'];
},
): Promise<boolean> {
if (
!(error instanceof AppError) ||
error.details?.reason !== 'android-process-probe-unavailable' ||
lifecycle.owner.kind !== 'local-family' ||
lifecycle.owner.family !== 'android' ||
req.positionals?.length ||
req.flags?.shutdown ||
req.flags?.saveScript ||
req.internal?.killApp
) {
return false;
}
const signal = getRequestSignal(req.meta?.requestId);
const serials = await observeLocalAndroidAdbSerials(signal).catch(() => undefined);
const serial = sessionStore.resolveCurrent(ref)?.device.id;
if (signal?.aborted || !serial || !adbInventoryOmitsSerial(serials, serial)) return false;
emitDiagnostic({
level: 'warn',
phase: 'android_app_stop_skipped_device_absent',
data: { serial },
});
return true;
}
Comment thread
thymikee marked this conversation as resolved.
Resolved

function adbInventoryOmitsSerial(serials: readonly string[] | undefined, serial: string): boolean {
return serials !== undefined && !serials.includes(serial);
}

Check warning on line 557 in packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts

View check run for this annotation

apex-sentinel-staging / Apex Sentinel

minor: Empty adb devices read mid adb-server restart still retires the session and frees its claim

A plain close whose app-stop probe failed with `android-process-probe-unavailable`, run while the adb server is restarting, gets `adb devices` exit 0 with an empty list. `adbInventoryOmitsSerial` returns true for `[]`, so close retires the session and releases the claim while the app is still running and the device is still attached. Commit f0e08d05 reverted the cd874548 guard that kept the claim on an empty inventory.

function buildCloseSuccessResponse(params: {
session: SessionState;
repair: Extract<RepairClosePreparation, { repairArmed: boolean }>;
Expand Down
18 changes: 16 additions & 2 deletions packages/platform-android/src/ime-lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import assert from 'node:assert/strict';
import { test } from 'vitest';
import { bindAndroidAdbHostStub } from './adb-host.fixtures.ts';
import { withAndroidHostAdbTransport } from './adb-executor.ts';
import { listAndroidAdbSerialsQuick } from './ime-lifecycle.ts';
import { listAndroidAdbSerialsQuick, observeAndroidAdbDevices } from './ime-lifecycle.ts';

test('quick serial listing keeps an unbound adb host port loud', async () => {
await assert.rejects(
Expand All @@ -19,7 +19,7 @@ test('quick serial listing routes its global devices call through the scoped tra
async (invocation) => {
seenArgs.push(invocation.command);
return {
stdout: 'List of devices attached\nemulator-5554\tdevice\n',
stdout: 'List of devices attached\n\nemulator-5554\tdevice\npartial-row\n',
stderr: '',
exitCode: 0,
};
Expand All @@ -40,3 +40,17 @@ test('quick serial listing treats a classified transport failure as empty invent

assert.deepEqual(serials, []);
});

test('strict adb inventory refuses a malformed row rather than inferring absence', async () => {
bindAndroidAdbHostStub();
const devices = await withAndroidHostAdbTransport(
async () => ({
stdout: 'List of devices attached\nemulator-5554\tdevice\npartial-row\n',
stderr: '',
exitCode: 0,
}),
async () => await observeAndroidAdbDevices(),
);

assert.equal(devices, undefined);
});
36 changes: 28 additions & 8 deletions packages/platform-android/src/ime-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,39 @@ export {

// Serials only, with no full-inventory name, boot-state, or target probes.
export async function listAndroidAdbSerialsQuick(): Promise<string[]> {
const devices = await readAndroidAdbDevices({ allowPartial: true });
return devices?.filter(({ state }) => state === 'device').map(({ serial }) => serial) ?? [];
}

/** Includes offline and unauthorized rows. Undefined means adb did not establish its inventory. */
export async function observeAndroidAdbDevices(
signal?: AbortSignal,
): Promise<readonly { serial: string; state: string }[] | undefined> {
return readAndroidAdbDevices({ signal });
}

async function readAndroidAdbDevices(options: {
signal?: AbortSignal;
allowPartial?: boolean;
}): Promise<readonly { serial: string; state: string }[] | undefined> {
requireAndroidAdbHost();
try {
const result = await runAndroidHostAdb(parseAndroidAdbArgv(['devices']), {
timeoutMs: 5_000,
signal: options.signal,
});
return result.stdout
.split('\n')
.map((line) => line.trim())
.filter((line) => line.length > 0 && !line.startsWith('List of devices'))
.map((line) => line.split(/\s+/))
.filter((parts) => parts[1] === 'device')
.map((parts) => parts[0] as string);
const lines = result.stdout.trim().split(/\r?\n/);
const rows = options.allowPartial ? lines : lines.slice(1);
if (!options.allowPartial && lines[0]?.trim() !== 'List of devices attached') return undefined;
const devices: { serial: string; state: string }[] = [];
for (const row of rows) {
const [serial, state] = row.trim().split(/\s+/);
if (!serial) continue;
if (state) devices.push({ serial, state });
else if (!options.allowPartial) return undefined;
}
return devices;
} catch {
return [];
return undefined;
}
}
Loading
Loading