Skip to content

Commit d73bdb4

Browse files
committed
fix: preserve platform network recovery routes
1 parent e7b8d0e commit d73bdb4

16 files changed

Lines changed: 271 additions & 21 deletions

File tree

‎packages/contracts/src/facades/platform.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,8 @@ export type { CleanupOnlyAppLogProcessReattachOutcome } from '../app-log-process
141141
export { mergeNetworkDumps, readRecentNetworkTrafficFromText } from '../network-traffic.ts';
142142
export type { NetworkDump, NetworkDumpParserOptions } from '../network-traffic.ts';
143143
export type {
144+
AppleSimctlCommandRequest,
145+
AppleToolHost,
144146
NetworkAppLogRead,
145147
NetworkAppLogSnapshot,
146148
NetworkDumpInput,

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,12 @@ function compileTimeNetworkProjectionProof(
2121
void compileTimeNetworkProjectionProof;
2222

2323
function compileTimeCanonicalHostProof(host: NetworkRuntimeHost): void {
24+
void host.appleTools.runSimctl({ args: ['spawn', 'sim-1', 'log', 'show'] });
25+
void host.appleTools.runSimctl({
26+
// @ts-expect-error The focused Apple port cannot execute an arbitrary binary.
27+
executable: 'xcrun',
28+
args: ['simctl', 'list'],
29+
});
2430
void host.appLogs.readRecent('session-id', 4000);
2531
void host.appLogs.readProcessMarker('session-id');
2632
// @ts-expect-error Callers cannot supply an arbitrary app-log path.

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

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type { NetworkIncludeMode } from '@agent-device/kernel/contracts';
22
import type { DeviceInfo } from '@agent-device/kernel/device';
33
import type { AppLogLiveState, AppLogProcessMarkerReadOutcome } from './app-log-runtime.ts';
44
import type { LogBackend } from './logs.ts';
5-
import type { HostCommandRunner } from './platform-runtime-host.ts';
5+
import type { HostCommandResult, HostCommandRunner } from './platform-runtime-host.ts';
66
import type { RuntimeProviderMode } from './platform-runtime.ts';
77
import type { NetworkDump } from './network-traffic.ts';
88

@@ -64,6 +64,17 @@ export type NetworkTransport = Readonly<{
6464
dump?: NetworkProviderDump;
6565
}>;
6666

67+
export type AppleSimctlCommandRequest = Readonly<{
68+
args: readonly string[];
69+
timeoutMs?: number;
70+
allowFailure?: boolean;
71+
}>;
72+
73+
/** Request-bound Apple tooling used by package-owned network recovery. */
74+
export type AppleToolHost = Readonly<{
75+
runSimctl(request: AppleSimctlCommandRequest, signal?: AbortSignal): Promise<HostCommandResult>;
76+
}>;
77+
6778
export type NetworkAppLogRead = Readonly<{
6879
path: string;
6980
exists: boolean;
@@ -75,6 +86,7 @@ export type NetworkAppLogRead = Readonly<{
7586

7687
export type NetworkRuntimeHost = Readonly<{
7788
commands: HostCommandRunner;
89+
appleTools: AppleToolHost;
7890
appLogs: Readonly<{
7991
readRecent(sessionId: string, maxScanLines: number): Promise<NetworkAppLogRead>;
8092
readProcessMarker(sessionId: string): Promise<AppLogProcessMarkerReadOutcome>;

‎packages/platform-android/src/logs/runtime.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,11 @@ function hostFixture(
285285
return { stdout: '123\n', stderr: '', exitCode: 0 };
286286
},
287287
},
288+
appleTools: {
289+
runSimctl: async () => {
290+
throw new Error('unused');
291+
},
292+
},
288293
outputs: {
289294
openAppend: async () => {
290295
outputOpens += 1;

‎packages/platform-android/src/network/runtime.test.ts‎

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,44 @@ test('detects an active stream still bound to the previous Android pid', async (
6969
expect(command.mock.calls.some(([request]) => request.args.includes('logcat'))).toBe(true);
7070
});
7171

72+
test('keeps canonical traffic when optional logcat recovery fails', async () => {
73+
const result = await dumpAndroidNetworkTraffic(
74+
host({
75+
marker: { status: 'missing' },
76+
command: (request) => commandResult(request, '222'),
77+
appLogText: '01-01 00:00:00.000 D/App (222): GET https://canonical.example.test status=200',
78+
logcat: new Error('adb transport unavailable'),
79+
}),
80+
device,
81+
input({ appLogSnapshot: { state: 'ended', startedAt: 1 } }),
82+
new AbortController().signal,
83+
);
84+
85+
expect(result).toMatchObject({
86+
source: 'app-log',
87+
dump: { entries: [{ url: 'https://canonical.example.test', status: 200 }] },
88+
});
89+
});
90+
91+
test('preserves the exact request cancellation reason during optional recovery', async () => {
92+
const controller = new AbortController();
93+
const reason = new Error('request cancelled');
94+
controller.abort(reason);
95+
96+
await expect(
97+
dumpAndroidNetworkTraffic(
98+
host({
99+
marker: { status: 'missing' },
100+
command: (request) => commandResult(request, '222'),
101+
logcat: new Error('transport error after cancellation'),
102+
}),
103+
device,
104+
input({ appLogSnapshot: { state: 'ended', startedAt: 1 } }),
105+
controller.signal,
106+
),
107+
).rejects.toBe(reason);
108+
});
109+
72110
function input(overrides: Partial<NetworkDumpInput> = {}): NetworkDumpInput {
73111
return {
74112
sessionId: 'one',
@@ -85,7 +123,7 @@ function host(options: {
85123
marker: Awaited<ReturnType<PlatformRuntimeHost['appLogs']['readProcessMarker']>>;
86124
command(request: HostCommandRequest): { stdout: string; stderr: string; exitCode: number };
87125
appLogText?: string;
88-
logcat: string;
126+
logcat: string | Error;
89127
}): PlatformRuntimeHost {
90128
return {
91129
...unusedAppLogHost(),
@@ -94,9 +132,15 @@ function host(options: {
94132
run: async (request) => {
95133
if (!request.args.includes('logcat')) return options.command(request);
96134
options.command(request);
135+
if (options.logcat instanceof Error) throw options.logcat;
97136
return { stdout: options.logcat, stderr: '', exitCode: 0 };
98137
},
99138
},
139+
appleTools: {
140+
runSimctl: async () => {
141+
throw new Error('unused');
142+
},
143+
},
100144
appLogs: {
101145
readRecent: async () => ({
102146
path: '/sessions/one/app.log',
@@ -118,7 +162,7 @@ function commandResult(request: HostCommandRequest, pid: string) {
118162

119163
function unusedAppLogHost(): Omit<
120164
PlatformRuntimeHost,
121-
'commands' | 'appLogs' | 'networkTransports'
165+
'appleTools' | 'commands' | 'appLogs' | 'networkTransports'
122166
> {
123167
return {
124168
artifacts: {

‎packages/platform-android/src/network/runtime.ts‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import type {
2+
HostCommandRequest,
3+
HostCommandResult,
24
NetworkDumpInput,
35
NetworkDumpResult,
46
PlatformRuntimeHost,
@@ -32,6 +34,7 @@ export async function dumpAndroidNetworkTraffic(
3234
const notes: string[] = [];
3335
const context = await recoveryContext(host, device, input, signal);
3436
if (context && input.appBundleId) {
37+
assertAndroidLogPackageSafe(input.appBundleId);
3538
const recovered = await recoverPackageTraffic(host, device, input.appBundleId, signal);
3639
if (recovered) {
3740
const recoveryDump = readRecentNetworkTrafficFromText(recovered.text, {
@@ -70,6 +73,22 @@ export async function dumpAndroidNetworkTraffic(
7073
});
7174
}
7275

76+
async function runOptionalRecoveryCommand(
77+
host: PlatformRuntimeHost,
78+
request: HostCommandRequest,
79+
signal: AbortSignal,
80+
): Promise<HostCommandResult | undefined> {
81+
signal.throwIfAborted();
82+
try {
83+
const result = await host.commands.run(request, signal);
84+
signal.throwIfAborted();
85+
return result;
86+
} catch {
87+
signal.throwIfAborted();
88+
return undefined;
89+
}
90+
}
91+
7392
async function recoveryContext(
7493
host: PlatformRuntimeHost,
7594
device: DeviceInfo,
@@ -100,9 +119,9 @@ async function recoverPackageTraffic(
100119
appBundleId: string,
101120
signal: AbortSignal,
102121
): Promise<{ text: string; pids: readonly string[] } | undefined> {
103-
assertAndroidLogPackageSafe(appBundleId);
104122
const currentPid = await resolveAndroidPid(host, device.id, appBundleId, signal);
105-
const result = await host.commands.run(
123+
const result = await runOptionalRecoveryCommand(
124+
host,
106125
{
107126
executable: 'adb',
108127
args: ['-s', device.id, 'logcat', '-d', '-v', 'time', '-t', '4000'],
@@ -111,6 +130,7 @@ async function recoverPackageTraffic(
111130
},
112131
signal,
113132
);
133+
if (!result) return undefined;
114134
if (result.exitCode !== 0 || !result.stdout.trim()) return undefined;
115135
const pids = collectPackagePids(result.stdout, appBundleId, currentPid);
116136
if (pids.length === 0) return undefined;
@@ -133,14 +153,16 @@ async function resolveAndroidPid(
133153
appBundleId: string,
134154
signal: AbortSignal,
135155
): Promise<string | undefined> {
136-
const result = await host.commands.run(
156+
const result = await runOptionalRecoveryCommand(
157+
host,
137158
{
138159
executable: 'adb',
139160
args: ['-s', deviceId, 'shell', 'pidof', appBundleId],
140161
allowFailure: true,
141162
},
142163
signal,
143164
);
165+
if (!result) return undefined;
144166
const pid = result.stdout.trim().split(/\s+/)[0];
145167
return pid && /^\d+$/.test(pid) ? pid : undefined;
146168
}

‎packages/platform-apple/src/logs/runtime.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,11 @@ function hostFixture(
162162
exitCode: request.args.includes('get_app_container') ? 1 : 0,
163163
},
164164
},
165+
appleTools: {
166+
runSimctl: async () => {
167+
throw new Error('unused');
168+
},
169+
},
165170
outputs: {
166171
readTail: async () => '',
167172
openAppend: async () => {

‎packages/platform-apple/src/network/runtime.test.ts‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ const simulator: DeviceInfo = {
1414
};
1515

1616
test('recovers an empty iOS simulator dump from bounded simctl log history', async () => {
17-
const commandRun = vi.fn(async () => ({
17+
const runSimctl = vi.fn(async () => ({
1818
stdout: [
1919
'Timestamp Ty Process[PID:TID]',
2020
'2026-08-10T10:00:00Z GET https://recovered.example.test status=200',
@@ -23,7 +23,7 @@ test('recovers an empty iOS simulator dump from bounded simctl log history', asy
2323
exitCode: 0,
2424
}));
2525
const result = await dumpAppleNetworkTraffic(
26-
host({ commandRun }),
26+
host({ runSimctl }),
2727
simulator,
2828
input({ appLogSnapshot: { state: 'active', startedAt: 1_000 } }),
2929
new AbortController().signal,
@@ -37,10 +37,9 @@ test('recovers an empty iOS simulator dump from bounded simctl log history', asy
3737
expect(result.source).toBe('app-log');
3838
if (result.source !== 'app-log') throw new Error('expected app-log result');
3939
expect(result.notes[0]).toContain('Recovered 1 iOS simulator HTTP entry');
40-
expect(commandRun).toHaveBeenCalledWith(
40+
expect(runSimctl).toHaveBeenCalledWith(
4141
expect.objectContaining({
42-
executable: 'xcrun',
43-
args: expect.arrayContaining(['simctl', 'spawn', 'sim-1', '--start', '@1']),
42+
args: expect.arrayContaining(['spawn', 'sim-1', '--start', '@1']),
4443
timeoutMs: 4_000,
4544
}),
4645
expect.any(AbortSignal),
@@ -50,7 +49,7 @@ test('recovers an empty iOS simulator dump from bounded simctl log history', asy
5049
test('preserves the simulator no-HTTP explanation after recovery returns app lines', async () => {
5150
const result = await dumpAppleNetworkTraffic(
5251
host({
53-
commandRun: async () => ({
52+
runSimctl: async () => ({
5453
stdout: '2026-08-10T10:00:00Z application diagnostic only\n',
5554
stderr: '',
5655
exitCode: 0,
@@ -69,10 +68,10 @@ test('preserves the simulator no-HTTP explanation after recovery returns app lin
6968
});
7069

7170
test('parses macOS session app-log traffic without loading simulator recovery', async () => {
72-
const commandRun = vi.fn();
71+
const runSimctl = vi.fn();
7372
const result = await dumpAppleNetworkTraffic(
7473
host({
75-
commandRun,
74+
runSimctl,
7675
text: '2026-08-10T10:00:00Z GET https://mac.example.test status=204\n',
7776
}),
7877
{ ...simulator, appleOs: 'macos', kind: 'device', target: 'desktop' },
@@ -84,7 +83,7 @@ test('parses macOS session app-log traffic without loading simulator recovery',
8483
backend: 'macos',
8584
dump: { entries: [{ url: 'https://mac.example.test', status: 204 }] },
8685
});
87-
expect(commandRun).not.toHaveBeenCalled();
86+
expect(runSimctl).not.toHaveBeenCalled();
8887
});
8988

9089
function input(overrides: Partial<NetworkDumpInput> = {}): NetworkDumpInput {
@@ -101,11 +100,17 @@ function input(overrides: Partial<NetworkDumpInput> = {}): NetworkDumpInput {
101100

102101
function host(options: {
103102
text?: string;
104-
commandRun: PlatformRuntimeHost['commands']['run'];
103+
runSimctl: PlatformRuntimeHost['appleTools']['runSimctl'];
105104
}): PlatformRuntimeHost {
106105
return {
107106
...unusedAppLogHost(),
108-
commands: { which: async () => undefined, run: options.commandRun },
107+
commands: {
108+
which: async () => undefined,
109+
run: async () => {
110+
throw new Error('generic command runner must not own Apple network recovery');
111+
},
112+
},
113+
appleTools: { runSimctl: options.runSimctl },
109114
appLogs: {
110115
readRecent: async () => ({
111116
path: '/sessions/one/app.log',
@@ -121,7 +126,7 @@ function host(options: {
121126

122127
function unusedAppLogHost(): Omit<
123128
PlatformRuntimeHost,
124-
'commands' | 'appLogs' | 'networkTransports'
129+
'appleTools' | 'commands' | 'appLogs' | 'networkTransports'
125130
> {
126131
return {
127132
artifacts: {

‎packages/platform-apple/src/network/runtime.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,6 @@ async function recoverSimulatorTraffic(
6868
signal: AbortSignal,
6969
): Promise<{ dump: NetworkDump; lineCount: number } | undefined> {
7070
const args = [
71-
'simctl',
7271
...(device.simulatorSetPath ? ['--set', device.simulatorSetPath] : []),
7372
'spawn',
7473
device.id,
@@ -86,8 +85,8 @@ async function recoverSimulatorTraffic(
8685
? ['--start', `@${Math.floor(startedAt / 1000)}`]
8786
: ['--last', '5m']),
8887
);
89-
const result = await host.commands.run(
90-
{ executable: 'xcrun', args, allowFailure: true, timeoutMs: 4_000 },
88+
const result = await host.appleTools.runSimctl(
89+
{ args, allowFailure: true, timeoutMs: 4_000 },
9190
signal,
9291
);
9392
if (result.exitCode !== 0 || !result.stdout.trim()) return undefined;

‎packages/platform-harmonyos/src/logs/runtime.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,11 @@ function hostFixture() {
107107
which: async () => 'hdc',
108108
run: async () => ({ stdout: '456\n', stderr: '', exitCode: 0 }),
109109
},
110+
appleTools: {
111+
runSimctl: async () => {
112+
throw new Error('unused');
113+
},
114+
},
110115
outputs: {
111116
readTail: async () => '',
112117
openAppend: async () => {

0 commit comments

Comments
 (0)