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 @@ -55,7 +55,6 @@ function openInput(overrides: Partial<OpenApplicationInput> = {}): OpenApplicati
prewarmRunnerBeforeOpen: false,
enableTestIme: false,
stateDir: '/state',
runtimeHints: {},
execution: {},
...overrides,
};
Expand Down
18 changes: 13 additions & 5 deletions packages/contracts/src/application-lifecycle-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,16 @@ export type OpenApplicationPreparationInput = Readonly<{
*/
export type OpenApplicationRunnerDemand = 'none' | 'possible' | 'required';

/**
* A runtime-hints request paired with the fact-admitted operation that applies it natively. The
* pair is one field, so a hints request cannot exist without its transport; `openApplication`
* never imports or falls back to a sibling implementation behind a false runtime-hints fact.
*/
export type OpenApplicationRuntimeHints = Readonly<{
values: RuntimeHintValues;
apply: (input: RuntimeHintsApplicationInput) => Promise<void>;
}>;

/** The normalized public application launch, independent of daemon request shape. */
export type OpenApplicationInput = Readonly<{
target?: string;
Expand All @@ -110,13 +120,11 @@ export type OpenApplicationInput = Readonly<{
prewarmRunnerBeforeOpen: boolean;
enableTestIme: boolean;
stateDir: string;
runtimeHints: RuntimeHintValues;
/**
* The fact-admitted runtime-hint operation for this open. It is optional only when no
* transport hint is requested; `openApplication` never imports or falls back to a sibling
* implementation behind a false runtime-hints fact.
* The transport hints this open must apply natively, paired with their fact-admitted apply
* operation. Absent when the open requests no transport hint.
*/
applyRuntimeHints?: (input: RuntimeHintsApplicationInput) => Promise<void>;
runtimeHints?: OpenApplicationRuntimeHints;
execution: ApplicationLifecycleExecution;
}>;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,8 @@ const openApplicationFixture = vi.fn(
direct: ApplicationLifecycleRuntimeOperations,
input: Parameters<ApplicationLifecycleRuntimeOperations['openApplication']>[0],
) => {
if (input.applyRuntimeHints) {
const runtimeHints = input.runtimeHints;
if (runtimeHints) {
// The direct owner's close-before-relaunch happens inside its open; a hinted relaunch
// must close before the hints land, so take the close here and open as a fresh launch.
if (input.relaunch && input.target !== undefined) {
Expand All @@ -120,10 +121,10 @@ const openApplicationFixture = vi.fn(
surface: input.surface,
execution: input.execution,
});
await input.applyRuntimeHints({ appId: input.appBundleId, values: input.runtimeHints });
await runtimeHints.apply({ appId: input.appBundleId, values: runtimeHints.values });
return await direct.openApplication({ ...input, relaunch: false });
}
await input.applyRuntimeHints({ appId: input.appBundleId, values: input.runtimeHints });
await runtimeHints.apply({ appId: input.appBundleId, values: runtimeHints.values });
}
return await direct.openApplication(input);
},
Expand Down
31 changes: 30 additions & 1 deletion packages/daemon/src/sessions/__tests__/session-runtime.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { expect, test } from 'vitest';
import { daemonRuntimeSchema } from '@agent-device/kernel/contracts';
import { resolveEffectiveOpenRuntimeHints, toRuntimePlatform } from '../session-runtime.ts';
import {
openApplicationRuntimeHints,
resolveEffectiveOpenRuntimeHints,
toRuntimePlatform,
} from '../session-runtime.ts';

test.each(['ios', 'android', 'harmonyos'] as const)(
'%s runtime survives wire admission and open normalization',
Expand Down Expand Up @@ -29,3 +33,28 @@ test('non-leaf apple selector is not a runtime platform', () => {
expect(toRuntimePlatform('apple')).toBeUndefined();
expect(() => daemonRuntimeSchema.parse({ platform: 'apple' })).toThrow();
});

test('openApplicationRuntimeHints pairs transport hints with the admitted apply operation', () => {
const apply = async () => {};
expect(openApplicationRuntimeHints({ metroHost: '10.0.2.2', metroPort: 8081 }, apply)).toEqual({
values: { metroHost: '10.0.2.2', metroPort: '8081' },
apply,
});
});

test('openApplicationRuntimeHints is absent without transport hints, even when apply is missing', () => {
expect(openApplicationRuntimeHints({ launchUrl: 'demo://open' }, undefined)).toBeUndefined();
expect(openApplicationRuntimeHints(undefined, undefined)).toBeUndefined();
});

test('openApplicationRuntimeHints refuses transport hints without apply as an undispatched caller bug', () => {
let caught: unknown;
try {
openApplicationRuntimeHints({ metroHost: '10.0.2.2', metroPort: 8081 }, undefined);
} catch (error) {
caught = error;
}
expect(caught).toMatchObject({
details: { reason: 'runtime-hints-operation-missing', dispatched: 'no' },
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -288,8 +288,8 @@ test('failed relaunch retains the claim for close while allowing daemon idle rea
}
});

test.each([{ dispatched: 'no' as const }, { reason: 'runtime-hints-operation-missing' }])(
'a relaunch refusal with confirmed or undispatched effects leaves the daemon active: %o',
test.each([{ dispatched: 'no' as const }])(
'a relaunch refusal with undispatched effects leaves the daemon active: %o',
async (details) => {
const sessionStore = makeSessionStore();
publishSession(sessionStore, 'android-session', ANDROID_EMULATOR);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ import {
import { SessionStore } from '../../../core/session-store.ts';
import {
countConfiguredRuntimeHints,
runtimeHintValues,
openApplicationRuntimeHints,
setSessionRuntimeHintsForOpen,
} from '../../session-runtime.ts';
import { STARTUP_SAMPLE_METHOD, type StartupPerfSample } from './session-startup-metrics.ts';
Expand Down Expand Up @@ -307,8 +307,7 @@ export async function completeOpenCommand(params: {
prewarmRunnerBeforeOpen: req.flags?.maestro?.prewarmRunnerBeforeOpen === true,
enableTestIme: shouldActivateAndroidTestIme(device, req),
stateDir: sessionStore.resolveDaemonStateDir(),
runtimeHints: runtimeHintValues(runtimeHints),
applyRuntimeHints,
runtimeHints: openApplicationRuntimeHints(runtimeHints, applyRuntimeHints),
execution: applicationLifecycleExecutionFromRequest(
req,
logPath,
Expand All @@ -317,9 +316,7 @@ export async function completeOpenCommand(params: {
})
.catch((error: unknown) => {
const effectsConfirmedOrUndispatched =
error instanceof AppError &&
(readDispatchDisclosure(error.details) === 'no' ||
error.details?.reason === 'runtime-hints-operation-missing');
error instanceof AppError && readDispatchDisclosure(error.details) === 'no';
if (!effectsConfirmedOrUndispatched) markUnconfirmedRelaunch();
throw error;
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,11 +186,15 @@ export async function prepareOpenCommandDetails(params: {
});
if (runtimeHintPlan.clearRemovedRuntimeHints) {
if (!clearRuntimeHints) {
// prepareApplicationOpen above may already have booted the device — a device-reaching
// step of this operation — so the disclosure is 'unknown', not 'no' ('no' holds only
// while no step was dispatched).
throw new AppError(
'COMMAND_FAILED',
'Runtime hint clear operation was not admitted for this open.',
{
reason: 'runtime-hints-operation-missing',
dispatched: 'unknown',
},
);
}
Expand Down
23 changes: 23 additions & 0 deletions packages/daemon/src/sessions/session-runtime.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { CommandFlags, DaemonWireRequest } from '@agent-device/contracts/command';
import {
type OpenApplicationRuntimeHints,
type RuntimeHintValues,
type RuntimeHintsApplicationInput,
hasRuntimeTransportHintValues,
} from '@agent-device/contracts/application-lifecycle-runtime';
import { AppError, asAppError } from '@agent-device/kernel/errors';
Expand Down Expand Up @@ -54,6 +56,27 @@ export function hasRuntimeTransportHints(runtime: SessionRuntimeHints | undefine
return hasRuntimeTransportHintValues(runtimeHintValues(runtime));
}

/**
* Pairs the open's requested transport hints with the fact-admitted apply operation, so the
* lifecycle input cannot carry a hints request without its transport. Absent when the open
* requests no transport hint. Transport hints without the admitted operation are a caller bug:
* the builder refuses them here, before any dispatch, so `dispatched: 'no'` holds.
*/
export function openApplicationRuntimeHints(
runtime: SessionRuntimeHints | undefined,
apply: ((input: RuntimeHintsApplicationInput) => Promise<void>) | undefined,
): OpenApplicationRuntimeHints | undefined {
if (!hasRuntimeTransportHints(runtime)) return undefined;
if (apply === undefined) {
throw new AppError(
'COMMAND_FAILED',
'Transport runtime hints were requested without the fact-admitted apply operation; pair the hints with the operation or drop them.',
{ reason: 'runtime-hints-operation-missing', dispatched: 'no' },
);
}
return { values: runtimeHintValues(runtime), apply };
}

function normalizeRuntimeStringInput(
value: unknown,
fieldName: 'metroHost' | 'bundleUrl' | 'launchUrl',
Expand Down
1 change: 0 additions & 1 deletion packages/platform-android/src/lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,6 @@ function openInput(overrides: Partial<OpenApplicationInput> = {}): OpenApplicati
prewarmRunnerBeforeOpen: false,
enableTestIme: false,
stateDir: '/state',
runtimeHints: {},
execution: {},
...overrides,
};
Expand Down
15 changes: 3 additions & 12 deletions packages/platform-android/src/lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import {
type OpenApplicationInput,
type OpenApplicationOutcome,
type OpenApplicationTiming,
hasRuntimeTransportHintValues,
} from '@agent-device/contracts/application-lifecycle-runtime';
import type { PlatformRuntimeHost } from '@agent-device/contracts/platform-runtime-operations';
import {
Expand Down Expand Up @@ -122,18 +121,10 @@ async function openAndroidApplication(
});
timing.relaunchCloseDurationMs = elapsed(closeStartedAtMs);
}
if (hasRuntimeTransportHintValues(input.runtimeHints)) {
if (!input.applyRuntimeHints) {
throw new AppError(
'COMMAND_FAILED',
'Runtime hint operation was not admitted for this open.',
{
reason: 'runtime-hints-operation-missing',
},
);
}
const runtimeHints = input.runtimeHints;
if (runtimeHints) {
const hintsStartedAtMs = Date.now();
await input.applyRuntimeHints({ appId: input.appBundleId, values: input.runtimeHints });
await runtimeHints.apply({ appId: input.appBundleId, values: runtimeHints.values });
timing.runtimeHintsDurationMs = elapsed(hintsStartedAtMs);
}
const openStartedAtMs = Date.now();
Expand Down
25 changes: 16 additions & 9 deletions packages/platform-apple/src/expo-dev-client-launch.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { afterEach, expect, test, vi } from 'vitest';
import type { OpenApplicationInput } from '@agent-device/contracts/application-lifecycle-runtime';
import type {
OpenApplicationInput,
OpenApplicationRuntimeHints,
} from '@agent-device/contracts/application-lifecycle-runtime';
import { AppError, createRequestCanceledError } from '@agent-device/kernel/errors';
import { openInput as lifecycleOpenInput, simulator as SIMULATOR } from './lifecycle.fixtures.ts';

Expand All @@ -12,10 +15,14 @@ import { resolveExpoDevClientLaunchUrl } from './expo-dev-client-launch.ts';

const resolveScheme = vi.mocked(resolveIosSimulatorExpoDevClientScheme);

function hints(values: Record<string, string>): OpenApplicationRuntimeHints {
return { values, apply: async () => {} };
}

function openInput(overrides: Partial<OpenApplicationInput> = {}): OpenApplicationInput {
return {
...lifecycleOpenInput(),
runtimeHints: { metroHost: '127.0.0.1', metroPort: '8085' },
runtimeHints: hints({ metroHost: '127.0.0.1', metroPort: '8085' }),
...overrides,
};
}
Expand All @@ -36,7 +43,7 @@ test.each([
])('points an expo-dev-client at %s', async (_name, bundleUrl, expected) => {
resolveScheme.mockResolvedValue('exp+dev-slug');

const input = openInput(bundleUrl ? { runtimeHints: { bundleUrl } } : {});
const input = openInput(bundleUrl ? { runtimeHints: hints({ bundleUrl }) } : {});
await expect(resolveExpoDevClientLaunchUrl(SIMULATOR, input)).resolves.toBe(expected);
expect(resolveScheme).toHaveBeenCalledWith(SIMULATOR, 'com.example.app', {
timeoutMs: 3_000,
Expand All @@ -46,9 +53,9 @@ test.each([
test('points at the server origin of a bundle URL, not at the bundle itself', async () => {
resolveScheme.mockResolvedValue('exp+dev-slug');
const input = openInput({
runtimeHints: {
runtimeHints: hints({
bundleUrl: 'http://10.0.0.5:8090/.expo/.virtual-metro-entry.bundle?platform=ios&dev=true',
},
}),
});

await expect(resolveExpoDevClientLaunchUrl(SIMULATOR, input)).resolves.toBe(
Expand All @@ -59,7 +66,7 @@ test('points at the server origin of a bundle URL, not at the bundle itself', as
test('keeps a single pair of brackets around an IPv6 bundle URL host', async () => {
resolveScheme.mockResolvedValue('exp+dev-slug');
const input = openInput({
runtimeHints: { bundleUrl: 'http://[::1]:8090/index.bundle?platform=ios' },
runtimeHints: hints({ bundleUrl: 'http://[::1]:8090/index.bundle?platform=ios' }),
});

await expect(resolveExpoDevClientLaunchUrl(SIMULATOR, input)).resolves.toBe(
Expand All @@ -70,10 +77,10 @@ test('keeps a single pair of brackets around an IPv6 bundle URL host', async ()
test('keeps the server mount when opening a path-prefixed Expo bundle', async () => {
resolveScheme.mockResolvedValue('exp+dev-slug');
const input = openInput({
runtimeHints: {
runtimeHints: hints({
bundleUrl:
'https://metro.example.test/tenant-42/.expo/.virtual-metro-entry.bundle?platform=ios',
},
}),
});

const launchUrl = await resolveExpoDevClientLaunchUrl(SIMULATOR, input);
Expand All @@ -88,7 +95,7 @@ test.each([
'exp+dev-slug',
],
['an open without an app bundle id', openInput({ appBundleId: undefined }), 'exp+dev-slug'],
['hints without a host and port', openInput({ runtimeHints: {} }), 'exp+dev-slug'],
['hints without a host and port', openInput({ runtimeHints: hints({}) }), 'exp+dev-slug'],
])('keeps the plain launch for %s', async (_name, input, scheme) => {
resolveScheme.mockResolvedValue(scheme);

Expand Down
7 changes: 4 additions & 3 deletions packages/platform-apple/src/expo-dev-client-launch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@ export async function resolveExpoDevClientLaunchUrl(
input: OpenApplicationInput,
): Promise<string | undefined> {
if (!input.appBundleId || input.runtimeLaunchUrl?.trim()) return undefined;
const values = input.runtimeHints?.values;
const serverUrl = resolveRuntimeServerUrl({
metroHost: input.runtimeHints.metroHost,
metroPort: input.runtimeHints.metroPort ? Number(input.runtimeHints.metroPort) : undefined,
bundleUrl: input.runtimeHints.bundleUrl,
metroHost: values?.metroHost,
metroPort: values?.metroPort ? Number(values.metroPort) : undefined,
bundleUrl: values?.bundleUrl,
});
if (!serverUrl) return undefined;
let scheme: string | undefined;
Expand Down
24 changes: 19 additions & 5 deletions packages/platform-apple/src/lifecycle-expo-dev-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,33 +11,47 @@ vi.mock('./core/app-resolution.ts', async () => {
});

const devClientLaunch = vi.hoisted(() => vi.fn<() => Promise<string | undefined>>());
const applyRuntimeHints = vi.hoisted(() => vi.fn(async () => {}));
vi.mock('./expo-dev-client-launch.ts', () => ({ resolveExpoDevClientLaunchUrl: devClientLaunch }));

beforeEach(() => {
resetUrlOwner();
devClientLaunch.mockReset();
applyRuntimeHints.mockReset();
});

const DEV_CLIENT_URL = 'exp+dev-slug://expo-development-client/?url=http%3A%2F%2F127.0.0.1%3A8085';
const METRO_HINTS = { metroHost: '127.0.0.1', metroPort: '8085' };

test.each([
['Expo development build', DEV_CLIENT_URL, METRO_HINTS, `open ${DEV_CLIENT_URL}`, 0, 1],
['bare React Native app', undefined, METRO_HINTS, 'open', 1, 1],
['app without Metro hints', DEV_CLIENT_URL, {}, 'open', 0, 0],
[
'Expo development build',
DEV_CLIENT_URL,
{ values: METRO_HINTS, apply: applyRuntimeHints },
`open ${DEV_CLIENT_URL}`,
0,
1,
],
[
'bare React Native app',
undefined,
{ values: METRO_HINTS, apply: applyRuntimeHints },
'open',
1,
1,
],
['app without Metro hints', DEV_CLIENT_URL, undefined, 'open', 0, 0],
] as const)(
'%s opens through the appropriate route',
async (_, url, runtimeHints, event, prefs, probes) => {
devClientLaunch.mockResolvedValue(url);
const applyRuntimeHints = vi.fn(async () => {});
const { lifecycle, events } = launchUrlSimulator(async () => {
throw alertNotFound();
});

await lifecycle.openApplication({
...openInput(),
runtimeHints,
applyRuntimeHints,
execution: { plannedOperations: ['captureSnapshot'] },
});

Expand Down
1 change: 0 additions & 1 deletion packages/platform-apple/src/lifecycle.fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ export function openInput(): OpenApplicationInput {
prewarmRunnerBeforeOpen: false,
enableTestIme: false,
stateDir: '/tmp/agent-device-lifecycle-test',
runtimeHints: {},
execution: {},
};
}
Expand Down
Loading
Loading