Skip to content

Commit c1ac863

Browse files
committed
fix(open): admit launch-only options before the lifecycle touches the device
Review round on #3928 (thymikee, second pass). A refused open still changed the device first: the owner refusal ran inside invokeApplicationOpen, after the relaunch close (closeBeforeRelaunch on Limrun/webdriver), the runner stop, and the runtime-hint write. `open <app> --relaunch --capture-network` on a provider iOS simulator killed the running app and then failed. - One admission step: contracts `assertOpenAdmitted(binding, execution)` is the whole rule for `--launch-console` and `--capture-network`. It is the first call in openDirectApplication, openAndroidApplication and openAppleApplication, so an owner that cannot honor the option is refused with UNSUPPORTED_OPERATION before any device action. It replaces the nine `supportsLocalSimulatorLaunch` pass-through sites and the four stacked refusals in the canonical open; `invokeApplicationOpen` keeps only its positional, URL, and argument-shape checks. - Both refusals carry a typed reason (`launch-console-owner-unadmitted`, `network-capture-owner-unadmitted`), matching the sibling `provider-runtime-interactor-missing` posture. Their messages stay module constants of the module that raises them, clear of any function's JSDoc (the shared message home's facade must stay exhaustive, and a re-export no consumer imports is dead code). - The provider-shaped contract test now opens with `relaunch: true` against a `closeBeforeRelaunch: true` owner and asserts the typed code and reason and that neither open nor close ran. A second case pins the same typed refusal for a local binding on a non-simulator device. - A probe file at its 32 MB cap no longer reads as current traffic: the capture read reports `atSizeCap` (the reader owns the cap constant mirroring the probe's AdMaxFileBytes) and the probe-mode dump says the window stopped recording. The cap check reads the handle offset through `getOffset:error:` instead of the raising `offsetInFile`, per ADR 0037 rule 6. - ADR 0037 rule 1 now states admission-before-device-action, rule 6 the cap note and the offset API, and rule 5 fixes Apple dump precedence — probe, then provider, then app-log — as the answer to the #3930 Metro question. Live evidence re-run at this head on ios-sim-net: one open with --capture-network --launch-console produced source=probe with five distinct httpbin URLs, a 10-line console log, masked Authorization/Cookie with X-Trace-Id kept, zero secret occurrences in network.jsonl; `open --relaunch --capture-network` on the local simulator stays admitted (relaunch close, then capture, dump still probe); a non-admitted open refuses with UNSUPPORTED_OPERATION and reason network-capture-owner-unadmitted.
1 parent 02addda commit c1ac863

13 files changed

Lines changed: 203 additions & 82 deletions

File tree

‎apple/network-capture/ADNetworkCapture.m‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,14 @@ static void AdWriteLine(NSString *line) {
4949
handle = [NSFileHandle fileHandleForWritingAtPath:kAdOutputPath];
5050
[handle seekToEndOfFile];
5151
});
52-
if (handle.offsetInFile >= AdMaxFileBytes) return;
52+
// `offsetInFile` raises when the seek underneath it fails (and is deprecated for exactly that
53+
// reason); `getOffset:error:` reports the same offset through an out-parameter (iOS 13+), so a
54+
// cap check on a handle whose offset cannot be read skips the write instead of raising in the
55+
// app under test (ADR 0037 rule 6).
56+
unsigned long long offset = 0;
57+
NSError *offsetError = nil;
58+
if (![handle getOffset:&offset error:&offsetError] || offsetError != nil) return;
59+
if (offset >= AdMaxFileBytes) return;
5360
// The error: form (available at the probe's iOS 15 floor): a plain writeData: raises an
5461
// Objective-C exception on ENOSPC, which would crash the app under test. A failed capture write
5562
// must never be the app's failure.

‎docs/adr/0037-ios-simulator-network-capture-probe.md‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,14 @@ Accepted (2026-10-23). Applies to iOS simulator app launches only.
99
1. `open <app> --capture-network` on an iOS simulator injects `apple/network-capture/ADNetworkCapture.m`
1010
(built on demand, cached per content hash and toolchain) into the app process through
1111
`SIMCTL_CHILD_DYLD_INSERT_LIBRARIES`. Admission follows the owner that dispatches the open, not
12-
the device shape: only the local Apple lifecycle declares it can inject the probe, so a
13-
provider-backed iOS simulator (Limrun, TestMu) refuses the flag with `UNSUPPORTED_OPERATION`
14-
instead of launching without capture. Every other platform and every URL open refuse the flag.
15-
`--launch-console` admits the same way, and the same local-Simulator declaration gates both.
12+
the device shape, and it happens before the lifecycle touches the device: `assertOpenAdmitted`
13+
runs first in every `openApplication` entry, so an owner that cannot inject the probe is refused
14+
with `UNSUPPORTED_OPERATION` and a typed `reason` before its relaunch close, runner stop, or
15+
runtime-hint write — a refused open never kills a running app. Only the local Apple lifecycle on
16+
an iOS simulator declares the capability, so a provider-backed iOS simulator (Limrun, TestMu)
17+
refuses the flag instead of launching without capture. Every other platform and every URL open
18+
refuse the flag. `--launch-console` admits the same way, and the same local-Simulator
19+
declaration gates both.
1620
2. The probe method-swizzles `-[NSURLSessionTask resume]`, observes each task to completion, and
1721
appends one JSON line per completed HTTP(S) task to the file named by
1822
`AGENT_DEVICE_NETWORK_CAPTURE_PATH` — the session's `network.jsonl`, one per session, replaced on
@@ -25,13 +29,18 @@ Accepted (2026-10-23). Applies to iOS simulator app launches only.
2529
5. `network dump` for a session with a capture window reads the probe file and reports
2630
`source: 'probe'`; a session opened without capture parses the app log and reports
2731
`source: 'app-log'`. These are the two modes, not a primary and a fallback. The dump states
28-
which source it used.
32+
which source it used. Apple source precedence is fixed here for every Apple dump, including the
33+
Metro-backed provider dump added later: **probe, then provider, then app-log**. The probe wins
34+
because the operator asked for it on this open and it also sees React Native `fetch`, which runs
35+
on URLSession on iOS; the provider transport answers only when no probe window is open.
2936
6. The probe file is host-side text an untrusted app wrote: reads are byte-bounded at the tail and
3037
pass through the operator's `AGENT_DEVICE_APP_LOG_REDACT_PATTERNS` before any response. The probe
3138
masks credential headers itself (`Authorization`, `Cookie`, `Set-Cookie`, and their
3239
authentication siblings) before writing, so a secret never enters the file and survives a dump
33-
run without operator patterns. File writes use `writeData:error:` and stop at a 32 MB cap: a
34-
capture failure must never crash the app under test.
40+
run without operator patterns. File writes use `writeData:error:` and the cap check reads the
41+
handle offset through `getOffset:error:` rather than the raising `offsetInFile`: a capture
42+
failure must never crash the app under test. Writes stop at a 32 MB file cap, and the dump
43+
reports a note when the file has reached it, so a capped window is never read as current traffic.
3544
7. The capture window names the app process the probe was injected into. If that app crashes and
3645
the runner relaunches it, the new process has no probe and writes nothing more; the dump of such
3746
a session keeps reporting `source: 'probe'` over the frozen entries. Reopen with

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

Lines changed: 61 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
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';
@@ -34,12 +35,16 @@ const WEB_DEVICE: DeviceInfo = {
3435
booted: true,
3536
};
3637

37-
function interactorWithOpen(open: Interactor['open'] = async () => undefined): Interactor {
38+
function interactorWithOpen(
39+
open: Interactor['open'] = async () => undefined,
40+
overrides: Partial<Pick<Interactor, 'close'>> = {},
41+
): Interactor {
3842
return {
3943
open,
4044
openDevice: async () => undefined,
4145
close: async () => undefined,
4246
setSetting: async () => undefined,
47+
...overrides,
4348
} as unknown as Interactor;
4449
}
4550

@@ -114,13 +119,6 @@ test.each([
114119
execution: { launchArgs: ['--flag'] },
115120
message: /launch-args requires an app target/,
116121
},
117-
{
118-
name: 'launch console outside an iOS simulator',
119-
device: LINUX_DEVICE,
120-
positionals: ['org.example.App'],
121-
execution: { launchConsole: 'stdout' },
122-
message: /iOS simulator/i,
123-
},
124122
{
125123
name: 'launch arguments on Linux',
126124
device: LINUX_DEVICE,
@@ -163,13 +161,6 @@ test.each([
163161
execution: { networkCapturePath: '/sessions/one/network.jsonl' },
164162
message: /direct app launch/,
165163
},
166-
{
167-
name: 'network capture outside an iOS simulator',
168-
device: LINUX_DEVICE,
169-
positionals: ['org.example.App'],
170-
execution: { networkCapturePath: '/sessions/one/network.jsonl' },
171-
message: /iOS simulator/i,
172-
},
173164
{
174165
name: 'network capture with a direct URL pair',
175166
device: IOS_SIMULATOR,
@@ -184,37 +175,78 @@ test.each([
184175
interactor: interactorWithOpen(),
185176
positionals,
186177
execution,
187-
supportsLocalSimulatorLaunch: true,
188178
}),
189179
).rejects.toThrow(message);
190180
});
191181

192-
for (const [name, execution] of [
193-
['capture', { networkCapturePath: '/sessions/one/network.jsonl' }],
194-
['launch console', { launchConsole: '/tmp/launch-console.log' }],
182+
for (const [name, execution, reason] of [
183+
[
184+
'capture',
185+
{ networkCapturePath: '/sessions/one/network.jsonl' },
186+
'network-capture-owner-unadmitted',
187+
],
188+
[
189+
'launch console',
190+
{ launchConsole: '/tmp/launch-console.log' },
191+
'launch-console-owner-unadmitted',
192+
],
195193
] as const) {
196-
test(`the generic provider lifecycle refuses ${name} on a provider-shaped iOS simulator`, async () => {
194+
test(`the generic provider lifecycle refuses ${name} on a provider-shaped iOS simulator before touching the device`, async () => {
197195
// Limrun's iOS simulator has the local shape but dispatches through this generic provider
198-
// lifecycle, whose interactor would silently ignore the request. Binding a provider interactor
199-
// derives no local-simulator capability, so the open must refuse with UNSUPPORTED_OPERATION.
200-
let opened = false;
196+
// lifecycle, whose interactor would silently ignore the request; with closeBeforeRelaunch it
197+
// would also close the running app first. Binding a provider interactor derives no
198+
// local-simulator capability, so the open must refuse with the typed code and reason before
199+
// its relaunch close or open dispatch runs.
200+
const calls: string[] = [];
201201
const binding = bindProviderApplicationLifecycleInteractor({
202202
device: IOS_SIMULATOR,
203203
signal: new AbortController().signal,
204204
resolveInteractor: () =>
205-
interactorWithOpen(async () => {
206-
opened = true;
207-
}),
205+
interactorWithOpen(
206+
async () => {
207+
calls.push('open');
208+
},
209+
{
210+
close: async () => {
211+
calls.push('close');
212+
},
213+
},
214+
),
208215
});
209216
const lifecycle = bindDirectApplicationLifecycle({
210217
binding,
211218
owner: 'Provider',
212219
openTargetIdentity: 'bundle-id',
220+
closeBeforeRelaunch: true,
221+
});
222+
const refusal = await lifecycle.openApplication(openInput({ relaunch: true, execution })).then(
223+
() => undefined,
224+
(error: unknown) => error,
225+
);
226+
expect(refusal).toBeInstanceOf(AppError);
227+
expect((refusal as AppError).code).toBe('UNSUPPORTED_OPERATION');
228+
expect((refusal as AppError).details?.reason).toBe(reason);
229+
expect(calls).toEqual([]);
230+
});
231+
232+
test(`a local binding on a non-simulator device refuses ${name} with the typed code`, async () => {
233+
const binding = bindLocalApplicationLifecycleInteractor({
234+
device: LINUX_DEVICE,
235+
signal: new AbortController().signal,
236+
resolveInteractor: async () => interactorWithOpen(),
237+
});
238+
const lifecycle = bindDirectApplicationLifecycle({
239+
binding,
240+
owner: 'Linux',
241+
openTargetIdentity: 'app-name',
213242
});
214-
await expect(lifecycle.openApplication(openInput({ execution }))).rejects.toThrow(
215-
/is supported only for a local iOS simulator/,
243+
const refusal = await lifecycle.openApplication(openInput({ execution })).then(
244+
() => undefined,
245+
(error: unknown) => error,
216246
);
217-
expect(opened).toBe(false);
247+
expect(refusal).toBeInstanceOf(AppError);
248+
expect((refusal as AppError).code).toBe('UNSUPPORTED_OPERATION');
249+
expect((refusal as AppError).details?.reason).toBe(reason);
218250
});
219251
}
220252

@@ -227,7 +259,6 @@ test('passes the session capture file to the interactor on a capture launch', as
227259
}),
228260
positionals: ['com.example.app'],
229261
execution: { networkCapturePath: '/sessions/one/network.jsonl' },
230-
supportsLocalSimulatorLaunch: true,
231262
});
232263
expect(seen).toMatchObject({ networkCapturePath: '/sessions/one/network.jsonl' });
233264
});

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

Lines changed: 37 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
import { isDeepLinkTarget } from './open-target.ts';
22
import {
33
CAPTURE_NETWORK_DIRECT_APP_ONLY_MESSAGE,
4-
CAPTURE_NETWORK_IOS_SIMULATOR_ONLY_MESSAGE,
54
LAUNCH_CONSOLE_DIRECT_APP_ONLY_MESSAGE,
6-
LAUNCH_CONSOLE_IOS_SIMULATOR_ONLY_MESSAGE,
75
} from './launch-console.ts';
86
import type { DeviceInfo } from '@agent-device/kernel/device';
97
import { isIosFamily } from '@agent-device/kernel/device';
@@ -143,18 +141,45 @@ export function bindProviderApplicationLifecycleInteractor(
143141
});
144142
}
145143

146-
/**
147-
* Canonical direct open semantics used only after a package lifecycle binding has admitted the
148-
* operation. It intentionally has no device-resolution or platform-mechanics branches.
149-
*/
150-
// The owner-capacity refusals belong to this module's admission rule, not to the shared
151-
// launch-option message home: only the canonical open states them.
144+
// The two owner-admission refusals are private to the admission rule that raises them — the
145+
// shared message home's façade must stay exhaustive, and an unused public message is dead code.
152146
const LAUNCH_CONSOLE_UNADMITTED_MESSAGE =
153147
'--launch-console is supported only for a local iOS simulator app launch; this session owner cannot capture the launch console';
154148

155149
const CAPTURE_NETWORK_UNADMITTED_MESSAGE =
156150
'--capture-network is supported only for a local iOS simulator app launch; this session owner cannot inject the capture probe';
157151

152+
/**
153+
* One admission step for the launch-only open options, called by every `openApplication` entry
154+
* before the lifecycle touches the device. `--launch-console` and `--capture-network` need an owner
155+
* that declared it can read simctl's console PTY or inject the capture probe; every other owner —
156+
* any provider, any non-iOS-simulator device — is refused with `UNSUPPORTED_OPERATION` and a typed
157+
* reason before its relaunch close, runner stop, or runtime-hint write runs. This is the whole
158+
* admission rule for those options (ADR 0037): the canonical open keeps only positional, URL, and
159+
* argument-shape checks.
160+
*/
161+
export function assertOpenAdmitted(
162+
binding: Pick<ApplicationLifecycleInteractorBinding, 'device' | 'supportsLocalSimulatorLaunch'>,
163+
execution: ApplicationLifecycleExecution,
164+
): void {
165+
if (execution.launchConsole && !binding.supportsLocalSimulatorLaunch) {
166+
throw new AppError('UNSUPPORTED_OPERATION', LAUNCH_CONSOLE_UNADMITTED_MESSAGE, {
167+
reason: 'launch-console-owner-unadmitted',
168+
deviceId: binding.device.id,
169+
});
170+
}
171+
if (execution.networkCapturePath && !binding.supportsLocalSimulatorLaunch) {
172+
throw new AppError('UNSUPPORTED_OPERATION', CAPTURE_NETWORK_UNADMITTED_MESSAGE, {
173+
reason: 'network-capture-owner-unadmitted',
174+
deviceId: binding.device.id,
175+
});
176+
}
177+
}
178+
179+
/**
180+
* Canonical direct open semantics used only after a package lifecycle binding has admitted the
181+
* operation. It intentionally has no device-resolution or platform-mechanics branches.
182+
*/
158183
export async function invokeApplicationOpen(
159184
params: Readonly<{
160185
device: DeviceInfo;
@@ -163,13 +188,6 @@ export async function invokeApplicationOpen(
163188
appBundleId?: string;
164189
execution: ApplicationLifecycleExecution;
165190
terminateRunningApp?: boolean;
166-
/**
167-
* From the owner's binding: true only for a local owner bound to an iOS simulator it controls,
168-
* whose direct app launch can read simctl's console PTY and inject the capture probe. An open
169-
* carrying `--launch-console` or `execution.networkCapturePath` without this declaration is
170-
* refused, so an owner that cannot honor the request never silently ignores it (ADR 0037).
171-
*/
172-
supportsLocalSimulatorLaunch: boolean;
173191
}>,
174192
): Promise<ApplicationLaunchReport | void> {
175193
const { device, positionals, execution } = params;
@@ -180,7 +198,7 @@ export async function invokeApplicationOpen(
180198
await invokeDeviceOpen(params);
181199
return;
182200
}
183-
assertOpenDeviceSupport(device, execution, params.supportsLocalSimulatorLaunch);
201+
assertOpenDeviceSupport(device, execution);
184202
if (url !== undefined) return await invokeApplicationUrlOpen(params, app, url);
185203
return await invokeApplicationTargetOpen(params, app);
186204
}
@@ -192,7 +210,6 @@ type DirectOpenParameters = Readonly<{
192210
appBundleId?: string;
193211
execution: ApplicationLifecycleExecution;
194212
terminateRunningApp?: boolean;
195-
supportsLocalSimulatorLaunch: boolean;
196213
}>;
197214

198215
function assertOpenPositionals(positionals: readonly string[]): void {
@@ -217,23 +234,9 @@ async function invokeDeviceOpen(params: DirectOpenParameters): Promise<void> {
217234
function assertOpenDeviceSupport(
218235
device: DeviceInfo,
219236
execution: ApplicationLifecycleExecution,
220-
supportsLocalSimulatorLaunch: boolean,
221237
): void {
222-
if (execution.launchConsole && (!isIosFamily(device) || device.kind !== 'simulator')) {
223-
throw new AppError('UNSUPPORTED_OPERATION', LAUNCH_CONSOLE_IOS_SIMULATOR_ONLY_MESSAGE);
224-
}
225-
if (execution.networkCapturePath && (!isIosFamily(device) || device.kind !== 'simulator')) {
226-
throw new AppError('UNSUPPORTED_OPERATION', CAPTURE_NETWORK_IOS_SIMULATOR_ONLY_MESSAGE);
227-
}
228-
// Both launch-only options additionally follow the owner, not the device shape: a
229-
// provider-backed iOS simulator has the shape but dispatches through a lifecycle that cannot
230-
// read the console PTY or inject the capture probe, so it must refuse rather than ignore (0037).
231-
if (execution.launchConsole && !supportsLocalSimulatorLaunch) {
232-
throw new AppError('UNSUPPORTED_OPERATION', LAUNCH_CONSOLE_UNADMITTED_MESSAGE);
233-
}
234-
if (execution.networkCapturePath && !supportsLocalSimulatorLaunch) {
235-
throw new AppError('UNSUPPORTED_OPERATION', CAPTURE_NETWORK_UNADMITTED_MESSAGE);
236-
}
238+
// The launch-only options were admitted by owner before this point (assertOpenAdmitted); what
239+
// remains here is what only the canonical open can see: the target shape of the request.
237240
if (device.platform === 'linux' && execution.launchArgs && execution.launchArgs.length > 0) {
238241
throw new AppError('UNSUPPORTED_OPERATION', '--launch-args is not supported on Linux.');
239242
}
@@ -352,6 +355,7 @@ async function openDirectApplication(
352355
input: OpenApplicationInput,
353356
): Promise<OpenApplicationOutcome> {
354357
const { binding } = params;
358+
assertOpenAdmitted(binding, input.execution);
355359
const interactor = await binding.resolveInteractor(input.execution, input.appBundleId);
356360
if (params.closeBeforeRelaunch && input.relaunch && input.target !== undefined) {
357361
await invokeApplicationClose({
@@ -366,7 +370,6 @@ async function openDirectApplication(
366370
positionals: input.positionals,
367371
appBundleId: input.appBundleId,
368372
execution: input.execution,
369-
supportsLocalSimulatorLaunch: binding.supportsLocalSimulatorLaunch,
370373
});
371374
const followUpUrl = followUpRuntimeLaunchUrl(input);
372375
if (followUpUrl) {
@@ -382,7 +385,6 @@ async function openDirectApplication(
382385
networkCapturePath: undefined,
383386
launchArgs: undefined,
384387
},
385-
supportsLocalSimulatorLaunch: binding.supportsLocalSimulatorLaunch,
386388
});
387389
}
388390
return { appBundleId: input.appBundleId, timing: {} };

‎packages/contracts/src/network-runtime.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,11 @@ export type NetworkAppLogRead = Readonly<{
9696
* this daemon owns; a probe that wrote nothing leaves `exists` false. `text` already carries the
9797
* operator's app-log redaction pass, so no consumer may treat it as raw app output.
9898
*/
99-
export type NetworkCaptureRead = NetworkAppLogRead;
99+
export type NetworkCaptureRead = NetworkAppLogRead &
100+
Readonly<{
101+
/** True when the probe stopped recording because the file reached its 32 MB cap (rule 6). */
102+
atSizeCap: boolean;
103+
}>;
100104

101105
export type NetworkRuntimeHost = Readonly<{
102106
commands: HostCommandRunner;

‎packages/daemon/src/__tests__/support/application-lifecycle-runtime-harness.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {
2+
assertOpenAdmitted,
23
bindProviderApplicationLifecycleInteractor,
34
invokeApplicationClose,
45
invokeApplicationOpen,
@@ -144,13 +145,13 @@ function applicationLifecycleRuntimeFixtureProviderOperations(
144145
}),
145146
prepareApplicationOpen: async () => undefined,
146147
openApplication: async (input) => {
148+
assertOpenAdmitted(binding, input.execution);
147149
await invokeApplicationOpen({
148150
device,
149151
interactor: await binding.resolveInteractor(input.execution, input.appBundleId),
150152
positionals: input.positionals,
151153
appBundleId: input.appBundleId,
152154
execution: input.execution,
153-
supportsLocalSimulatorLaunch: binding.supportsLocalSimulatorLaunch,
154155
});
155156
return { appBundleId: input.appBundleId, timing: {} };
156157
},

0 commit comments

Comments
 (0)