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
35 changes: 0 additions & 35 deletions packages/contracts/src/device-boot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,41 +99,6 @@ 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: 4 additions & 7 deletions packages/daemon/src/__tests__/support/boot-ownership-fixtures.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
import type { CloseBootOwnership } from '@agent-device/contracts/device-boot';
import type { CloseBootOwnership } from '../../core/session-state.ts';

/**
* The boot-ownership pair an `open` records when it proved nothing about the device's boot: it owns no
* The boot ownership 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.
* inventing one of their own, so a new answer of the pair cannot be quietly defaulted away.
*/
export const NO_BOOT_PROOF: CloseBootOwnership = {
ownsBoot: false,
bootOwnerUnverified: false,
};
export const NO_BOOT_PROOF: CloseBootOwnership = 'none';
19 changes: 15 additions & 4 deletions packages/daemon/src/core/session-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,16 @@ export type SessionRef = Readonly<{
lifetime: object;
}>;

/**
* Whether a session's `open` owns stopping the device it holds, and whether it must say why not.
* The four answers are exclusive by type: an open either proved its boot, inferred one the platform
* did not disprove, disproved the inference it started from, or has no claim at all. #4791: only
* `proved` and `inferred` owe a stop, and `disproved` is the one close reports. The daemon's own
* vocabulary: `resolveSessionBootOwnership` decides a member, `SessionStore.updateOpenDevice`
* records it, and a plain `close` reads what was recorded.
*/
export type CloseBootOwnership = 'proved' | 'inferred' | 'disproved' | 'none';

export type SessionState = {
name: string;
sessionScope?: SessionScope;
Expand Down Expand Up @@ -176,10 +186,11 @@ export type SessionState = {
device: DeviceInfo;
/**
* #4162: this session's `open` booted the local simulator or emulator it now holds, so a plain
* `close` stops it and leaves the device as the session found it. Recorded only when device
* selection reports the boot (`selection.bootOccurred`), which never happens for a provider or
* physical target, nor for a device that was already running. The open-state publisher sets it
* through `SessionStore.updateOpenDevice`; changing device identity clears it. Close only reads it.
* `close` stops it and leaves the device as the session found it. Recorded when device selection
* reports the boot (`selection.bootOccurred`) or the platform's own boot step reports performing
* it (#4791), neither of which happens for a provider or physical target, nor for a device that
* was already running. The open-state publisher sets it through `SessionStore.updateOpenDevice`;
* changing device identity clears it. Close only reads it.
*/
bootedByOpen?: true;
/**
Expand Down
34 changes: 25 additions & 9 deletions packages/daemon/src/core/session-store.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { AndroidEmulatorLaunchIdentity } from '@agent-device/contracts/device-readiness-runtime';
import type { CloseBootOwnership } from '@agent-device/contracts/device-boot';
import {
resolveSessionDir,
resolveSessionAppLogPath,
Expand All @@ -17,7 +16,12 @@ import {
type DeviceInfo,
} from '@agent-device/kernel/device';
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
import type { SessionRef, SessionRuntimeHints, SessionState } from './session-state.ts';
import type {
CloseBootOwnership,
SessionRef,
SessionRuntimeHints,
SessionState,
} from './session-state.ts';
import { recordActionEntry, type RecordActionEntry } from './session-action-recorder.ts';
import { isSafeSessionSegment, safeSessionName } from '@agent-device/host-kit/session-paths';
import {
Expand Down Expand Up @@ -425,7 +429,12 @@ export class SessionStore {
session.lastActivityAtMs = atMs;
}

/** Keep boot ownership and its launch identity together for the same device identity. */
/**
* Keep boot ownership and its launch identity together for the same device identity. A `none`
* write — a re-open that proved nothing — keeps the recorded disproval: it establishes no ownership
* of its own, and a session that disproved a boot is still the same promise to report keeping that
* device running, whether this re-open then succeeds or fails partway.
*/
updateOpenDevice(
ref: SessionRef,
device: DeviceInfo,
Expand All @@ -434,19 +443,26 @@ export class SessionStore {
): void {
const current = this.requireCurrent(ref);
const retainsBoot = sameDeviceIdentity(deviceIdentity(current.device), deviceIdentity(device));
const ownsBoot = bootOwnership.ownsBoot || (retainsBoot && current.bootedByOpen === true);
const provesBoot = bootOwnership === 'proved' || bootOwnership === 'inferred';
const ownsBoot = provesBoot || (retainsBoot && current.bootedByOpen === true);
this.update(ref, {
device,
androidLaunchIdentity: bootOwnership.ownsBoot
androidLaunchIdentity: provesBoot
? 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,
// #4791: the reason rides the ownership it refused. A write that owns a stop — including a
// re-open that disproves its OWN boot while an earlier open of this same device proved one and
// #4162 keeps it — reports nothing, because close stops on the preserved proof.
bootOwnerUnverified: ownsBoot
? undefined
: bootOwnership === 'disproved'
? true
: retainsBoot
? current.bootOwnerUnverified
: undefined,
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,22 @@ function createRoutedSession() {
cwd: process.cwd(),
});

async function run(command: {
name: 'open' | 'close';
flags?: Record<string, unknown>;
/** What the platform's own boot step reports about the open's preparation call. */
bootPerformance?: DeviceBootPerformance;
}) {
/** Every open of this suite must state what its boot step reports; a close reports nothing. */
type RunCommand =
| {
name: 'open';
/** What the platform's own boot step reports about the open's preparation call. */
bootPerformance: DeviceBootPerformance;
/** Fails the open after its ownership write and before dispatch, keeping the session. */
failBeforeDispatch?: boolean;
flags?: Record<string, unknown>;
}
| { name: 'close'; flags?: Record<string, unknown> };

async function run(command: RunCommand) {
if (command.name === 'open') {
// Selection sees a shut-down simulator, which is the inference #4791 refuses to act on alone.
// A re-open of this session resolves the session's own device and infers no boot at all.
vi.mocked(resolveTargetDevice).mockResolvedValue(STOPPED_SIMULATOR);
}
const loader: LifecycleOperationsLoader = async (device, signal, shutdownTarget) => {
Expand All @@ -92,7 +100,8 @@ function createRoutedSession() {
prepareApplicationOpen: async (
input: Parameters<typeof operations.prepareApplicationOpen>[0],
) => {
input.onBootPerformance?.(command.bootPerformance!);
// An open states its boot report in its own command shape; a close prepares nothing.
if (command.name === 'open') input.onBootPerformance?.(command.bootPerformance);
},
});
};
Expand All @@ -109,6 +118,18 @@ function createRoutedSession() {
session: SESSION,
positionals: command.name === 'open' ? ['Demo'] : [],
flags: command.flags ?? {},
...(command.name === 'open' && command.failBeforeDispatch
? {
internal: {
openLifecycle: {
beforeDispatch: async () => ({
ok: false as const,
error: { code: 'COMMAND_FAILED' as const, message: 'Dispatch refused' },
}),
},
},
}
: {}),
},
sessionName: SESSION,
logPath: path.join(stateDir, 'daemon.log'),
Expand Down Expand Up @@ -172,3 +193,52 @@ test('plain close stops the simulator whose boot the platform reports performing
expect(closeWarnings(closed!)).toBeUndefined();
if (closed?.ok) expect(closed.data).toMatchObject({ shutdown: { success: true } });
}, 30_000);

test('close --shutdown commands the stop a disproved open withheld', async () => {
// The state the warning actually creates: the user is told the device is still running and
// answers with an explicit shutdown. That commands the stop without the ownership question.
const runs = createRoutedSession();

const opened = await runs.run({
name: 'open',
bootPerformance: { performed: false, reason: 'already-booted' },
});
expect(opened?.ok).toBe(true);

const closed = await runs.run({ name: 'close', flags: { shutdown: true } });

expect(closed?.ok).toBe(true);
expect(mockShutdownTargetRuntime).toHaveBeenCalledTimes(1);
expect(closeWarnings(closed!)).toBeUndefined();
if (closed?.ok) expect(closed.data).toMatchObject({ shutdown: { success: true } });
}, 30_000);

test('a failed re-open cannot silence the disproved boot the session already reported', async () => {
// The re-open writes ownership before dispatch and its own readiness finds the foreign boot up,
// so it proves nothing. When its dispatch then fails, the surviving session keeps the record:
// the same simulator is still running on somebody else's boot, and close must still say so.
const runs = createRoutedSession();

const opened = await runs.run({
name: 'open',
bootPerformance: { performed: false, reason: 'already-booted' },
});
expect(opened?.ok).toBe(true);

const reopened = await runs.run({
name: 'open',
bootPerformance: { performed: false, reason: 'already-booted' },
flags: {},
failBeforeDispatch: true,
});
expect(reopened?.ok).toBe(false);
expect(runs.sessionStore.get(SESSION)?.bootOwnerUnverified).toBe(true);

const closed = await runs.run({ name: 'close' });

expect(closed?.ok).toBe(true);
expect(mockShutdownTargetRuntime).not.toHaveBeenCalled();
expect(closeWarnings(closed!)).toEqual([
expect.stringContaining(CLOSE_BOOT_OWNER_UNVERIFIED_REASONS.bootOwnerUnverified),
]);
}, 30_000);
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { test } from 'vitest';
import { publishOpenSession } from '../session-open-state.ts';
import { makeSessionStore } from './session-open-runtime.fixtures.ts';
import { NO_BOOT_PROOF } from '../../../../__tests__/support/boot-ownership-fixtures.ts';
import type { CloseBootOwnership } from '../../../../core/session-state.ts';
import {
authoringPublication,
makeIosSession,
Expand Down Expand Up @@ -63,26 +64,31 @@ test('a re-open of a session that never armed records nothing', () => {
//
// Ownership survives reopens of the same target. A replacement owns only its own boot.

function firstOpen(bootedByOpen: boolean | undefined) {
/** One open of a fresh session under the given ownership answer. */
function firstOpen(bootOwnership: CloseBootOwnership) {
const store = makeSessionStore();
return publishOpenSession({
req: { token: 't', command: 'open', positionals: [], session: 's' },
sessionStore: store,
sessionName: 's',
device: IOS_SIMULATOR,
surface: 'app',
bootOwnership: { ownsBoot: bootedByOpen === true, bootOwnerUnverified: false },
bootOwnership,
}).session;
}

test('#4162: an open whose selection reported the boot records it on the new session', () => {
assert.equal(firstOpen(true).bootedByOpen, true);
assert.equal(firstOpen('inferred').bootedByOpen, true);
});

test.each([false, undefined] as const)(
'#4162: an open whose selection reported no boot records nothing',
(bootedByOpen) => {
assert.equal(firstOpen(bootedByOpen).bootedByOpen, undefined);
test('an open whose boot step proved the boot records it on the new session', () => {
assert.equal(firstOpen('proved').bootedByOpen, true);
});

test.each(['none', 'disproved'] as const)(
'#4162: an open whose selection reported no boot records nothing: %s',
(bootOwnership) => {
assert.equal(firstOpen(bootOwnership).bootedByOpen, undefined);
},
);

Expand All @@ -100,7 +106,7 @@ test.each([false, true])('replacement target owns only its own boot: %s', (repla
existingRef: ref,
device: { ...IOS_SIMULATOR, id: 'replacement-simulator' },
surface: 'app',
bootOwnership: { ownsBoot: replacementBooted, bootOwnerUnverified: false },
bootOwnership: replacementBooted ? 'inferred' : 'none',
}),
);
assert.equal(next.bootedByOpen, replacementBooted ? true : undefined);
Expand All @@ -121,7 +127,7 @@ test.each(bootOwnershipFacts)(
existingRef: ref,
device: IOS_SIMULATOR,
surface: 'app',
bootOwnership: { ownsBoot: true, bootOwnerUnverified: false },
bootOwnership: 'inferred',
}),
);

Expand Down Expand Up @@ -160,14 +166,14 @@ test('#4791: an open the platform disproved records no boot and the reason close
sessionName: 's',
device: IOS_SIMULATOR,
surface: 'app',
bootOwnership: { ownsBoot: false, bootOwnerUnverified: true },
bootOwnership: 'disproved',
}).session;

assert.equal(next.bootedByOpen, undefined);
assert.equal(next.bootOwnerUnverified, true);
});

test('#4791: a re-open of the same target clears the disproved boot with its own proof', () => {
test('#4791: a re-open that proves its own boot clears the earlier disproved one', () => {
const store = makeSessionStore();
const existing = makeIosSession('s', { bootOwnerUnverified: true });
const ref = store.publish(existing.name, existing);
Expand All @@ -180,13 +186,37 @@ test('#4791: a re-open of the same target clears the disproved boot with its own
existingRef: ref,
device: IOS_SIMULATOR,
surface: 'app',
bootOwnership: NO_BOOT_PROOF,
bootOwnership: 'proved',
}),
);

// The device went down and this open really brought it up: close owes the stop, not the warning.
assert.equal(next.bootedByOpen, true);
assert.equal(next.bootOwnerUnverified, undefined);
});

test('#4791: a re-open that proves nothing keeps the disproved boot on record', () => {
// The same foreign boot is still running — readiness finds it up and answers nothing new — so a
// later plain close must keep warning about it, whether this re-open then succeeds or fails.
const store = makeSessionStore();
const existing = makeIosSession('s', { bootOwnerUnverified: true });
const ref = store.publish(existing.name, existing);

const next = store.requireCurrent(
publishOpenSession({
req: { token: 't', command: 'open', positionals: [], session: existing.name },
sessionStore: store,
sessionName: existing.name,
existingRef: ref,
device: IOS_SIMULATOR,
surface: 'app',
bootOwnership: NO_BOOT_PROOF,
}),
);

assert.equal(next.bootOwnerUnverified, true);
});

test('#4791: a disproved re-open cannot take back a boot an earlier open of the same device proved', () => {
const store = makeSessionStore();
const existing = makeIosSession('s', { bootedByOpen: true });
Expand All @@ -200,7 +230,7 @@ test('#4791: a disproved re-open cannot take back a boot an earlier open of the
existingRef: ref,
device: IOS_SIMULATOR,
surface: 'app',
bootOwnership: { ownsBoot: false, bootOwnerUnverified: true },
bootOwnership: 'disproved',
}),
);

Expand Down
Loading
Loading