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
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. When this session's open booted a local simulator or emulator, close stops it too, leaving the device as the session found it; a device that was already running keeps running. When the emulator process its own open launched is gone or cannot be verified, plain close leaves the emulator running and warns. Pass shutdown to explicitly stop a local simulator or emulator regardless of boot ownership. A daemon whose policy denies device-shutdown skips the implicit stop on plain close, which succeeds with a warning that the local device stays running. Explicit close with shutdown fails with UNAUTHORIZED and details.reason DAEMON_POLICY_DENIED. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s, a killed process does not exit within 10s, or a new process runs past 2s; a relaunching open accepts that new process. For foreground timeouts, JSON details include foregroundObservations and initialProcessCount; the android_close_foreground_fence request diagnostic retains the last five probe results and timings, including when a probe throws. 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. When this session's open booted a local simulator or emulator, close stops it too, leaving the device as the session found it; a device that was already running keeps running. For an Apple simulator, the proof that open booted it is that open's own boot step performed the boot; when something else booted it first, plain close leaves the simulator running and warns with boot-owner-unverified. When the emulator process its own open launched is gone or cannot be verified, plain close leaves the emulator running and warns. Pass shutdown to explicitly stop a local simulator or emulator regardless of boot ownership. A daemon whose policy denies device-shutdown skips the implicit stop on plain close, which succeeds with a warning that the local device stays running. Explicit close with shutdown fails with UNAUTHORIZED and details.reason DAEMON_POLICY_DENIED. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s, a killed process does not exit within 10s, or a new process runs past 2s; a relaunching open accepts that new process. For foreground timeouts, JSON details include foregroundObservations and initialProcessCount; the android_close_foreground_fence request diagnostic retains the last five probe results and timings, including when a probe throws. 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.",
{
app: stringField('Optional app to close.'),
shutdown: booleanField(
Expand Down
42 changes: 42 additions & 0 deletions packages/contracts/src/__tests__/device-boot.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { describe, expect, test } from 'vitest';
import { resolveSessionBootOwnership } from '../device-boot.ts';

// #4791: boot ownership is decided from the platform's own boot report, not from what an inventory
// snapshot said before the boot could happen. These pin the decision at the owner of the type; the
// routed close behavior is pinned in the daemon's session-lifecycle lane.
describe('resolveSessionBootOwnership', () => {
test('a boot the boot step reports performing owns the stop on its own', () => {
expect(
resolveSessionBootOwnership({
inferredFromSnapshot: false,
bootPerformance: { performed: true },
}),
).toEqual({ ownsBoot: true, bootOwnerUnverified: false });
});

test('the snapshot inference still owns the boot for an owner that reports nothing', () => {
// Android boots through the daemon's own emulator launch outside its preparation, so it answers
// nothing and the inference stays in charge there.
expect(
resolveSessionBootOwnership({ inferredFromSnapshot: true, bootPerformance: undefined }),
).toEqual({ ownsBoot: true, bootOwnerUnverified: false });
});

test('a boot the boot step disproves refuses the snapshot inference and says so', () => {
expect(
resolveSessionBootOwnership({
inferredFromSnapshot: true,
bootPerformance: { performed: false, reason: 'already-booted' },
}),
).toEqual({ ownsBoot: false, bootOwnerUnverified: true });
});

test('nothing is owed when neither the snapshot nor the boot step claims a boot', () => {
expect(
resolveSessionBootOwnership({
inferredFromSnapshot: false,
bootPerformance: { performed: false, reason: 'no-boot-attempt' },
}),
).toEqual({ ownsBoot: false, bootOwnerUnverified: false });
});
});
9 changes: 9 additions & 0 deletions packages/contracts/src/application-lifecycle-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type { RunnerLogicalLeaseContext } from './runner-lease-context.ts';
import type { SessionSurface } from './session-surface.ts';
import type { ProviderPortReverseOptions } from './provider-device-runtime.ts';
import type { TargetShutdownResult } from './target-shutdown-contract.ts';
import type { DeviceBootPerformance } from './device-boot.ts';

/**
* A deliberately neutral runtime-hint payload. Daemon policy owns parsing and
Expand Down Expand Up @@ -84,6 +85,14 @@ export type OpenApplicationPreparationInput = Readonly<{
surface: SessionSurface;
prewarmRunnerOnColdBoot: boolean;
execution: ApplicationLifecycleExecution;
/**
* #4791: an owner whose preparation contains the step that could boot the device reports what that
* step did with its own call: `performed: true` is positive proof this open booted the device, and
* a `performed: false` answer is positive proof it did not, whatever an earlier inventory snapshot
* said. An owner that performs no boot step in its preparation answers nothing — answering for a
* boot made elsewhere would misreport this call.
*/
onBootPerformance?: (performance: DeviceBootPerformance) => void;
}>;

/**
Expand Down
55 changes: 55 additions & 0 deletions packages/contracts/src/device-boot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,61 @@ export type LaunchedDeviceProcessService = Readonly<{
): Promise<LaunchedProcessStopConfirmation>;
}>;

/**
* What the boot step of an `open` reports about its OWN call. Boot ownership needs positive proof, so
* an owner that started the boot reports `performed: true`, and an owner that found the device already
* up reports that too — `already-booted` is the tool's own answer for a device that was up before the
* call, `no-boot-attempt` is the answer when readiness settled the device without reaching a boot. An
* owner whose readiness step reports nothing leaves the port unset rather than guessing.
*/
export type DeviceBootPerformance =
| Readonly<{ performed: true }>
| Readonly<{ performed: false; reason: 'already-booted' | 'no-boot-attempt' }>;

/**
* The warning token plain `close` publishes when the platform answered its own boot step with "this
* call did not boot the device", so the session has no boot of its own to stop and whatever is running
* belongs to somebody else. Callers read a member; none writes a literal.
*/
export const CLOSE_BOOT_OWNER_UNVERIFIED_REASONS = {
bootOwnerUnverified: 'boot-owner-unverified',
} as const satisfies Record<string, string>;

/**
* Whether a session's `open` owns stopping the device it holds, and whether it must say why not.
*
* #4791: a boot the platform reports performing is positive proof, so it owns the boot whatever the
* snapshot said. A device-selection snapshot only says the device was STOPPED when the open looked at
* it, which is not proof the open booted it: anything else could have booted it in the meantime, and
* nothing about booting a simulator claims the device. So when the platform answers that its own boot
* step did not boot the device, the session owns no stop and reports the inference it refused. An
* owner whose open boots the device through some step of its own, outside the preparation that reports
* (the daemon's Android emulator launch), reports nothing, which leaves the snapshot inference in
* charge for that family.
*/
export type CloseBootOwnership = Readonly<{
ownsBoot: boolean;
bootOwnerUnverified: boolean;
}>;

export function resolveSessionBootOwnership(
input: Readonly<{
/** Device selection's inference: the pre-open snapshot said this stopped local device needed a boot. */
inferredFromSnapshot: boolean;
/** What the platform's own boot step reported about its call, when that owner reports at all. */
bootPerformance: DeviceBootPerformance | undefined;
}>,
): CloseBootOwnership {
// A boot the boot step reports performing is proof on its own: the device can even have gone down
// between the snapshot and this call, which makes the boot real while the inference says nothing.
const performed = input.bootPerformance?.performed === true;
const disprovesSnapshot = input.bootPerformance?.performed === false;
return {
ownsBoot: performed || (input.inferredFromSnapshot && !disprovesSnapshot),
bootOwnerUnverified: input.inferredFromSnapshot && disprovesSnapshot,
};
}

/**
* The `details.failedOpenEmulatorCleanupReason` values a failed open publishes, from the owner of
* this outcome. Callers read a member; none writes a literal.
Expand Down
11 changes: 11 additions & 0 deletions packages/daemon/src/__tests__/support/boot-ownership-fixtures.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { CloseBootOwnership } from '@agent-device/contracts/device-boot';

/**
* The boot-ownership pair an `open` records when it proved nothing about the device's boot: it owns no
* stop, and it disproved nothing. Suites that are not about boot ownership pass this instead of
* inventing one of their own, so a new field of the pair cannot be quietly defaulted away.
*/
export const NO_BOOT_PROOF: CloseBootOwnership = {
ownsBoot: false,
bootOwnerUnverified: false,
};
8 changes: 8 additions & 0 deletions packages/daemon/src/core/session-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,14 @@ export type SessionState = {
* through `SessionStore.updateOpenDevice`; changing device identity clears it. Close only reads it.
*/
bootedByOpen?: true;
/**
* #4791: this session's `open` inferred a boot from a pre-open snapshot that said the device was
* stopped, and the platform then answered its own boot step with "this call did not boot it". The
* session therefore owns no stop, and a plain `close` reports in `warnings` that it left the device
* running rather than stopping a boot it never caused. Recorded and cleared by the same
* `SessionStore.updateOpenDevice` write as `bootedByOpen`; close only reads it.
*/
bootOwnerUnverified?: true;
androidLaunchIdentity?: AndroidEmulatorLaunchIdentity;
createdAt: number;
surface?: SessionSurface;
Expand Down
11 changes: 8 additions & 3 deletions packages/daemon/src/core/session-store.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { AndroidEmulatorLaunchIdentity } from '@agent-device/contracts/device-readiness-runtime';
import type { CloseBootOwnership } from '@agent-device/contracts/device-boot';
import {
resolveSessionDir,
resolveSessionAppLogPath,
Expand Down Expand Up @@ -428,20 +429,24 @@ export class SessionStore {
updateOpenDevice(
ref: SessionRef,
device: DeviceInfo,
bootOccurred: boolean,
bootOwnership: CloseBootOwnership,
androidLaunchIdentity?: AndroidEmulatorLaunchIdentity,
): void {
const current = this.requireCurrent(ref);
const retainsBoot = sameDeviceIdentity(deviceIdentity(current.device), deviceIdentity(device));
const ownsBoot = bootOccurred || (retainsBoot && current.bootedByOpen === true);
const ownsBoot = bootOwnership.ownsBoot || (retainsBoot && current.bootedByOpen === true);
this.update(ref, {
device,
androidLaunchIdentity: bootOccurred
androidLaunchIdentity: bootOwnership.ownsBoot
? androidLaunchIdentity
: retainsBoot
? current.androidLaunchIdentity
: undefined,
bootedByOpen: ownsBoot ? true : undefined,
// #4791: the reason is reported only alongside the ownership it refused. A re-open that disproves
// its OWN boot cannot erase a boot an earlier open of this same device proved and #4162 keeps, so
// that close stops on the preserved proof and says nothing.
bootOwnerUnverified: !ownsBoot && bootOwnership.bootOwnerUnverified ? true : undefined,
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
} from '../../__tests__/support/legacy-snapshot-capture-fixture.ts';
import { captureSnapshotWithInteractor } from '../../core/snapshot-interactor-capture.ts';
import { daemonPlatformServicesFixture } from '../../__tests__/support/platform-services-fixture.ts';
import { NO_BOOT_PROOF } from '../../__tests__/support/boot-ownership-fixtures.ts';
import { selectorCaptureFixture } from '../../__tests__/support/selector-capture-fixture.ts';
import {
SAVE_ANNOTATION,
Expand Down Expand Up @@ -185,6 +186,7 @@ test.each(['close and reopen', 'open with refreshed device'])(
device: closes ? initial.session.device : { ...initial.session.device },
surface: 'app',
appBundleId: initial.session.appBundleId,
bootOwnership: NO_BOOT_PROOF,
});
}
return { ok: true, data: {} };
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import {
inspectDeviceClaims,
} from '@agent-device/daemon-contracts/device-claims';
import { SessionStore } from '../../../../core/session-store.ts';
import { NO_BOOT_PROOF } from '../../../../__tests__/support/boot-ownership-fixtures.ts';
import { resolveTargetDevice } from '@agent-device/device-selection/dispatch-resolve';
import type { DeviceInfo } from '@agent-device/kernel/device';

Expand Down Expand Up @@ -460,7 +461,11 @@ test('changing the device serial clears launch ownership', async () => {
const runs = createRoutedSession();
await openBootedByThisSession(runs);
const ref = runs.sessionStore.lookup(SESSION)!;
runs.sessionStore.updateOpenDevice(ref, { ...BOOTED_EMULATOR, id: 'emulator-5556' }, false);
runs.sessionStore.updateOpenDevice(
ref,
{ ...BOOTED_EMULATOR, id: 'emulator-5556' },
NO_BOOT_PROOF,
);
expect(runs.sessionStore.get(SESSION)?.androidLaunchIdentity).toBeUndefined();
expect(runs.sessionStore.get(SESSION)?.bootedByOpen).toBeUndefined();
});
Loading
Loading