Skip to content

Commit 37dc3c4

Browse files
committed
fix(contracts): refuse launch-only open options before the lifecycle touches the device
Extracted from #3928. assertOpenAdmitted and assertOpenRequestShape run first in openDirectApplication, openAndroidApplication and openAppleApplication, so an open option the bound owner cannot honor is refused before any relaunch close, runner stop, or runtime-hint write. On a provider iOS simulator (Limrun/TestMu shape), --relaunch --launch-console used to close the running app and only then fail. The binding now carries a supportsLocalSimulatorLaunch owner capability, and every refusal uses a typed reason.
1 parent c48d27a commit 37dc3c4

7 files changed

Lines changed: 297 additions & 51 deletions

File tree

‎packages/contracts/src/application-lifecycle-interaction.test.ts‎

Lines changed: 125 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
import { expect, test } from 'vitest';
2+
import { AppError } from '@agent-device/kernel/errors';
23
import type { DeviceInfo } from '@agent-device/kernel/device';
34
import type { Interactor } from './interactor-types.ts';
45
import type { OpenApplicationInput } from './application-lifecycle-runtime.ts';
56
import {
67
bindDirectApplicationLifecycle,
78
bindLocalApplicationLifecycleInteractor,
9+
bindProviderApplicationLifecycleInteractor,
810
invokeApplicationOpen,
911
} from './application-lifecycle-interaction.ts';
1012

@@ -33,12 +35,16 @@ const WEB_DEVICE: DeviceInfo = {
3335
booted: true,
3436
};
3537

36-
function interactorWithOpen(open: Interactor['open'] = async () => undefined): Interactor {
38+
function interactorWithOpen(
39+
open: Interactor['open'] = async () => undefined,
40+
overrides: Partial<Pick<Interactor, 'close' | 'setSetting'>> = {},
41+
): Interactor {
3742
return {
3843
open,
3944
openDevice: async () => undefined,
4045
close: async () => undefined,
4146
setSetting: async () => undefined,
47+
...overrides,
4248
} as unknown as Interactor;
4349
}
4450

@@ -114,11 +120,11 @@ test.each([
114120
message: /launch-args requires an app target/,
115121
},
116122
{
117-
name: 'launch console outside an iOS simulator',
118-
device: LINUX_DEVICE,
119-
positionals: ['org.example.App'],
123+
name: 'launch console with a deep-link app target',
124+
device: IOS_SIMULATOR,
125+
positionals: ['example://home'],
120126
execution: { launchConsole: 'stdout' },
121-
message: /iOS simulator/i,
127+
message: /direct app/i,
122128
},
123129
{
124130
name: 'launch arguments on Linux',
@@ -165,3 +171,117 @@ test.each([
165171
}),
166172
).rejects.toThrow(message);
167173
});
174+
175+
test('the generic provider lifecycle refuses the launch console on a provider-shaped iOS simulator before touching the device', async () => {
176+
// A provider's iOS simulator has the local shape but dispatches through this generic provider
177+
// lifecycle, whose interactor would silently ignore the request; with closeBeforeRelaunch it
178+
// would also close the running app first. Binding a provider interactor derives no
179+
// local-simulator capability, so the open must refuse with the typed code and reason before
180+
// its relaunch close or open dispatch runs.
181+
const calls: string[] = [];
182+
const binding = bindProviderApplicationLifecycleInteractor({
183+
device: IOS_SIMULATOR,
184+
signal: new AbortController().signal,
185+
resolveInteractor: () =>
186+
interactorWithOpen(
187+
async () => {
188+
calls.push('open');
189+
},
190+
{
191+
close: async () => {
192+
calls.push('close');
193+
},
194+
},
195+
),
196+
});
197+
const lifecycle = bindDirectApplicationLifecycle({
198+
binding,
199+
owner: 'Provider',
200+
openTargetIdentity: 'bundle-id',
201+
closeBeforeRelaunch: true,
202+
});
203+
const refusal = await lifecycle
204+
.openApplication(
205+
openInput({ relaunch: true, execution: { launchConsole: '/tmp/launch-console.log' } }),
206+
)
207+
.then(
208+
() => undefined,
209+
(error: unknown) => error,
210+
);
211+
expect(refusal).toBeInstanceOf(AppError);
212+
expect((refusal as AppError).code).toBe('UNSUPPORTED_OPERATION');
213+
expect((refusal as AppError).details?.reason).toBe('launch-console-owner-unadmitted');
214+
expect(calls).toEqual([]);
215+
});
216+
217+
test('a local binding on a non-simulator device refuses the launch console with the typed code', async () => {
218+
const binding = bindLocalApplicationLifecycleInteractor({
219+
device: LINUX_DEVICE,
220+
signal: new AbortController().signal,
221+
resolveInteractor: async () => interactorWithOpen(),
222+
});
223+
const lifecycle = bindDirectApplicationLifecycle({
224+
binding,
225+
owner: 'Linux',
226+
openTargetIdentity: 'app-name',
227+
});
228+
const refusal = await lifecycle
229+
.openApplication(openInput({ execution: { launchConsole: '/tmp/launch-console.log' } }))
230+
.then(
231+
() => undefined,
232+
(error: unknown) => error,
233+
);
234+
expect(refusal).toBeInstanceOf(AppError);
235+
expect((refusal as AppError).code).toBe('UNSUPPORTED_OPERATION');
236+
expect((refusal as AppError).details?.reason).toBe('launch-console-owner-unadmitted');
237+
});
238+
239+
test('a URL-pair relaunch carrying launch-console and clear-app-state is refused before any close', async () => {
240+
// `open <bundle> <scheme://x> --relaunch --clear-app-state --launch-console`: the launch-only
241+
// options cannot ride a URL pair, and admission answers that from positionals and execution
242+
// alone — before the closeBeforeRelaunch owner closes the running app.
243+
const calls: string[] = [];
244+
const binding = bindLocalApplicationLifecycleInteractor({
245+
device: IOS_SIMULATOR,
246+
signal: new AbortController().signal,
247+
resolveInteractor: async () =>
248+
interactorWithOpen(
249+
async () => {
250+
calls.push('open');
251+
},
252+
{
253+
close: async () => {
254+
calls.push('close');
255+
},
256+
setSetting: async () => {
257+
calls.push('setSetting');
258+
},
259+
},
260+
),
261+
});
262+
const lifecycle = bindDirectApplicationLifecycle({
263+
binding,
264+
owner: 'Local',
265+
openTargetIdentity: 'bundle-id',
266+
closeBeforeRelaunch: true,
267+
});
268+
const refusal = await lifecycle
269+
.openApplication(
270+
openInput({
271+
relaunch: true,
272+
positionals: ['com.example.app', 'example://deal'],
273+
execution: {
274+
clearAppState: true,
275+
launchConsole: '/tmp/launch-console.log',
276+
},
277+
}),
278+
)
279+
.then(
280+
() => undefined,
281+
(error: unknown) => error,
282+
);
283+
expect(refusal).toBeInstanceOf(AppError);
284+
expect((refusal as AppError).code).toBe('INVALID_ARGS');
285+
expect((refusal as AppError).message).toMatch(/direct app/i);
286+
expect(calls).toEqual([]);
287+
});

‎packages/contracts/src/application-lifecycle-interaction.ts‎

Lines changed: 119 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,5 @@
11
import { isDeepLinkTarget } from './open-target.ts';
2-
import {
3-
LAUNCH_CONSOLE_DIRECT_APP_ONLY_MESSAGE,
4-
LAUNCH_CONSOLE_IOS_SIMULATOR_ONLY_MESSAGE,
5-
} from './launch-console.ts';
2+
import { LAUNCH_CONSOLE_DIRECT_APP_ONLY_MESSAGE } from './launch-console.ts';
63
import type { DeviceInfo } from '@agent-device/kernel/device';
74
import { isIosFamily } from '@agent-device/kernel/device';
85
import { AppError } from '@agent-device/kernel/errors';
@@ -26,6 +23,13 @@ import type {
2623
export type ApplicationLifecycleInteractorBinding = Readonly<{
2724
device: DeviceInfo;
2825
signal: AbortSignal;
26+
/**
27+
* True only for a local owner bound to an iOS simulator it controls, i.e. an owner whose direct
28+
* app launch can read simctl's console PTY. The shared open refuses `--launch-console` without
29+
* it, so a provider-backed simulator — same device shape, provider-owned lifecycle — refuses
30+
* rather than silently ignoring the request.
31+
*/
32+
supportsLocalSimulatorLaunch: boolean;
2933
resolveInteractor(
3034
execution: ApplicationLifecycleExecution,
3135
appBundleId?: string,
@@ -84,6 +88,10 @@ function bindApplicationLifecycleInteractor(
8488
return Object.freeze({
8589
device,
8690
signal,
91+
// A local owner bound to an iOS simulator controls simctl and can read the console PTY;
92+
// a provider owner never can, whatever the device shape says.
93+
supportsLocalSimulatorLaunch:
94+
ownership === 'local' && isIosFamily(device) && device.kind === 'simulator',
8795
resolveInteractor: async (execution, appBundleId) => {
8896
const runner = applicationLifecycleRunnerContext(execution, appBundleId, signal);
8997
if (ownership === 'local') return await params.resolveLocalInteractor(device, runner);
@@ -129,6 +137,108 @@ export function bindProviderApplicationLifecycleInteractor(
129137
});
130138
}
131139

140+
// The owner-admission refusal is private to the admission rule that raises it — the shared message
141+
// home's façade must stay exhaustive, and an unused public message is dead code.
142+
const LAUNCH_CONSOLE_UNADMITTED_MESSAGE =
143+
'--launch-console is supported only for a local iOS simulator app launch; this session owner cannot capture the launch console';
144+
145+
/**
146+
* The request-shape rule for the launch-only open options: what only `positionals` and `execution`
147+
* can answer, checked once and enforced twice — by {@link assertOpenAdmitted} before the lifecycle
148+
* touches the device, and by {@link invokeApplicationOpen} for its own folded and follow-up calls.
149+
* One helper per positional shape: no app target, a URL pair, or a single deep-link app target.
150+
* `--launch-console` and `--clear-app-state` act on the app the open launches, so they refuse every
151+
* shape but a direct app target, before any close, clear, or launch runs.
152+
*/
153+
function assertOpenRequestShape(
154+
positionals: readonly string[],
155+
execution: ApplicationLifecycleExecution,
156+
): void {
157+
if (positionals.length > 2) {
158+
throw new AppError('INVALID_ARGS', 'open accepts at most two arguments: <app|url> [url]');
159+
}
160+
const app = positionals[0];
161+
const url = positionals[1];
162+
if (app === undefined) {
163+
assertOpenDeviceOnlyRequest(execution);
164+
return;
165+
}
166+
if (url !== undefined) {
167+
assertOpenUrlPairRequest(app, url, execution);
168+
return;
169+
}
170+
if (isDeepLinkTarget(app)) {
171+
assertOpenDeepLinkAppRequest(execution);
172+
}
173+
}
174+
175+
function assertOpenDeviceOnlyRequest(execution: ApplicationLifecycleExecution): void {
176+
if (execution.launchConsole) {
177+
throw new AppError('INVALID_ARGS', '--launch-console requires an app target');
178+
}
179+
if (execution.launchArgs && execution.launchArgs.length > 0) {
180+
throw new AppError('INVALID_ARGS', '--launch-args requires an app target');
181+
}
182+
}
183+
184+
function assertOpenUrlPairRequest(
185+
app: string,
186+
url: string,
187+
execution: ApplicationLifecycleExecution,
188+
): void {
189+
if (isDeepLinkTarget(app)) {
190+
throw new AppError(
191+
'INVALID_ARGS',
192+
'open <app> <url> requires an app target as the first argument',
193+
);
194+
}
195+
if (!isDeepLinkTarget(url)) {
196+
throw new AppError('INVALID_ARGS', 'open <app> <url> requires a valid URL target');
197+
}
198+
if (execution.launchConsole) {
199+
throw new AppError('INVALID_ARGS', LAUNCH_CONSOLE_DIRECT_APP_ONLY_MESSAGE);
200+
}
201+
}
202+
203+
function assertOpenDeepLinkAppRequest(execution: ApplicationLifecycleExecution): void {
204+
if (execution.launchConsole) {
205+
throw new AppError('INVALID_ARGS', LAUNCH_CONSOLE_DIRECT_APP_ONLY_MESSAGE);
206+
}
207+
if (execution.clearAppState) {
208+
throw new AppError(
209+
'INVALID_ARGS',
210+
'Clearing app state requires an app target, not a deep link.',
211+
);
212+
}
213+
}
214+
215+
/**
216+
* One admission step for the open command, called by every `openApplication` entry before the
217+
* lifecycle touches the device. It enforces the owner capability and the request shape of the
218+
* launch-only options: `--launch-console` needs an owner that declared it can read simctl's console
219+
* PTY, and every other owner — any provider, any non-iOS-simulator device — is refused with
220+
* `UNSUPPORTED_OPERATION` and a typed reason; the positional and URL-pair checks in
221+
* {@link assertOpenRequestShape} then refuse a launch-only option on a request that cannot carry
222+
* one, with `INVALID_ARGS`. The owner answers first because where an option works at all is the
223+
* more actionable refusal. So no refusal — of an owner that cannot honor an option or of a
224+
* malformed launch-only request — ever follows a relaunch close, a runner stop, or a runtime-hint
225+
* write. The canonical open keeps the same shape rule for its own folded and follow-up dispatches,
226+
* plus the one refusal that needs the platform itself.
227+
*/
228+
export function assertOpenAdmitted(
229+
binding: Pick<ApplicationLifecycleInteractorBinding, 'device' | 'supportsLocalSimulatorLaunch'>,
230+
execution: ApplicationLifecycleExecution,
231+
positionals: readonly string[],
232+
): void {
233+
if (execution.launchConsole && !binding.supportsLocalSimulatorLaunch) {
234+
throw new AppError('UNSUPPORTED_OPERATION', LAUNCH_CONSOLE_UNADMITTED_MESSAGE, {
235+
reason: 'launch-console-owner-unadmitted',
236+
deviceId: binding.device.id,
237+
});
238+
}
239+
assertOpenRequestShape(positionals, execution);
240+
}
241+
132242
/**
133243
* Canonical direct open semantics used only after a package lifecycle binding has admitted the
134244
* operation. It intentionally has no device-resolution or platform-mechanics branches.
@@ -144,11 +254,11 @@ export async function invokeApplicationOpen(
144254
}>,
145255
): Promise<ApplicationLaunchReport | void> {
146256
const { device, positionals, execution } = params;
147-
assertOpenPositionals(positionals);
257+
assertOpenRequestShape(positionals, execution);
148258
const app = positionals[0];
149259
const url = positionals[1];
150260
if (!app) {
151-
await invokeDeviceOpen(params);
261+
await params.interactor.openDevice();
152262
return;
153263
}
154264
assertOpenDeviceSupport(device, execution);
@@ -165,29 +275,12 @@ type DirectOpenParameters = Readonly<{
165275
terminateRunningApp?: boolean;
166276
}>;
167277

168-
function assertOpenPositionals(positionals: readonly string[]): void {
169-
if (positionals.length > 2) {
170-
throw new AppError('INVALID_ARGS', 'open accepts at most two arguments: <app|url> [url]');
171-
}
172-
}
173-
174-
async function invokeDeviceOpen(params: DirectOpenParameters): Promise<void> {
175-
if (params.execution.launchConsole) {
176-
throw new AppError('INVALID_ARGS', '--launch-console requires an app target');
177-
}
178-
if (params.execution.launchArgs && params.execution.launchArgs.length > 0) {
179-
throw new AppError('INVALID_ARGS', '--launch-args requires an app target');
180-
}
181-
await params.interactor.openDevice();
182-
}
183-
184278
function assertOpenDeviceSupport(
185279
device: DeviceInfo,
186280
execution: ApplicationLifecycleExecution,
187281
): void {
188-
if (execution.launchConsole && (!isIosFamily(device) || device.kind !== 'simulator')) {
189-
throw new AppError('UNSUPPORTED_OPERATION', LAUNCH_CONSOLE_IOS_SIMULATOR_ONLY_MESSAGE);
190-
}
282+
// The launch-only options were admitted by shape and by owner before this point
283+
// (assertOpenAdmitted); what remains here is the one refusal that needs the platform itself.
191284
if (device.platform === 'linux' && execution.launchArgs && execution.launchArgs.length > 0) {
192285
throw new AppError('UNSUPPORTED_OPERATION', '--launch-args is not supported on Linux.');
193286
}
@@ -198,18 +291,6 @@ async function invokeApplicationUrlOpen(
198291
app: string,
199292
url: string,
200293
): Promise<ApplicationLaunchReport | void> {
201-
if (isDeepLinkTarget(app)) {
202-
throw new AppError(
203-
'INVALID_ARGS',
204-
'open <app> <url> requires an app target as the first argument',
205-
);
206-
}
207-
if (!isDeepLinkTarget(url)) {
208-
throw new AppError('INVALID_ARGS', 'open <app> <url> requires a valid URL target');
209-
}
210-
if (params.execution.launchConsole) {
211-
throw new AppError('INVALID_ARGS', LAUNCH_CONSOLE_DIRECT_APP_ONLY_MESSAGE);
212-
}
213294
return await params.interactor.open(app, {
214295
activity: params.execution.activity,
215296
appBundleId: params.appBundleId,
@@ -224,16 +305,7 @@ async function invokeApplicationTargetOpen(
224305
app: string,
225306
): Promise<ApplicationLaunchReport | void> {
226307
const { execution, interactor } = params;
227-
if (execution.launchConsole && isDeepLinkTarget(app)) {
228-
throw new AppError('INVALID_ARGS', LAUNCH_CONSOLE_DIRECT_APP_ONLY_MESSAGE);
229-
}
230308
if (execution.clearAppState) {
231-
if (isDeepLinkTarget(app)) {
232-
throw new AppError(
233-
'INVALID_ARGS',
234-
'Clearing app state requires an app target, not a deep link.',
235-
);
236-
}
237309
await interactor.setSetting('clear-app-state', 'clear', app);
238310
}
239311
return await interactor.open(app, {
@@ -302,6 +374,7 @@ async function openDirectApplication(
302374
input: OpenApplicationInput,
303375
): Promise<OpenApplicationOutcome> {
304376
const { binding } = params;
377+
assertOpenAdmitted(binding, input.execution, input.positionals);
305378
const interactor = await binding.resolveInteractor(input.execution, input.appBundleId);
306379
if (params.closeBeforeRelaunch && input.relaunch && input.target !== undefined) {
307380
await invokeApplicationClose({

0 commit comments

Comments
 (0)