Skip to content

Commit 1bdd382

Browse files
committed
fix: preserve platform network recovery routes
1 parent ca905c8 commit 1bdd382

12 files changed

Lines changed: 161 additions & 38 deletions

File tree

‎packages/capture-kit/src/index.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,5 +26,4 @@ export {
2626
createUnavailablePlatformRuntimeBinding,
2727
createUnavailablePlatformRuntimeOwner,
2828
} from './platform-runtime-unavailable.ts';
29-
export type { UnavailablePlatformRuntimeFacts } from './platform-runtime-unavailable.ts';
3029
export { mergeNetworkDumps, readRecentNetworkTrafficFromText } from './network-traffic.ts';

‎packages/contracts/src/app-log-runtime.ts‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,7 @@ import type {
77
HostCommandRunner,
88
HostToolchainPreparer,
99
} from './platform-runtime-host.ts';
10-
import type {
11-
ResourceOwnershipFence,
12-
RuntimeProviderMode,
13-
} from './platform-runtime.ts';
10+
import type { ResourceOwnershipFence, RuntimeProviderMode } from './platform-runtime.ts';
1411
import type { PendingTransferGuard } from './async-lifecycle.ts';
1512
import {
1613
type CleanupOutcome,

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

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

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

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

Lines changed: 2 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 { AppleToolHost, HostCommandRunner } from './platform-runtime-host.ts';
66
import type { RuntimeProviderMode } from './platform-runtime.ts';
77
import type { NetworkDump } from './network-traffic.ts';
88

@@ -75,6 +75,7 @@ export type NetworkAppLogRead = Readonly<{
7575

7676
export type NetworkRuntimeHost = Readonly<{
7777
commands: HostCommandRunner;
78+
appleTools: AppleToolHost;
7879
appLogs: Readonly<{
7980
readRecent(sessionId: string, maxScanLines: number): Promise<NetworkAppLogRead>;
8081
readProcessMarker(sessionId: string): Promise<AppLogProcessMarkerReadOutcome>;

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

Lines changed: 47 additions & 6 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,16 @@ 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+
isXcrunAvailable: async () => false,
141+
run: async () => {
142+
throw new Error('unused');
143+
},
144+
},
100145
appLogs: {
101146
readRecent: async () => ({
102147
path: '/sessions/one/app.log',
@@ -118,13 +163,9 @@ function commandResult(request: HostCommandRequest, pid: string) {
118163

119164
function unusedAppLogHost(): Omit<
120165
PlatformRuntimeHost,
121-
'commands' | 'appLogs' | 'networkTransports'
166+
'appleTools' | 'commands' | 'appLogs' | 'networkTransports'
122167
> {
123168
return {
124-
appleTools: {
125-
isXcrunAvailable: async () => false,
126-
run: async () => ({ stdout: '', stderr: '', exitCode: 0 }),
127-
},
128169
toolchains: { prepare: async () => {} },
129170
artifacts: {
130171
resolveSession: () => ({

‎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,
@@ -29,6 +31,7 @@ export async function dumpAndroidNetworkTraffic(
2931
const notes: string[] = [];
3032
const context = await recoveryContext(host, device, input, signal);
3133
if (context && input.appBundleId) {
34+
assertAndroidLogPackageSafe(input.appBundleId);
3235
const recovered = await recoverPackageTraffic(host, device, input.appBundleId, signal);
3336
if (recovered) {
3437
const recoveryDump = readRecentNetworkTrafficFromText(recovered.text, {
@@ -67,6 +70,22 @@ export async function dumpAndroidNetworkTraffic(
6770
});
6871
}
6972

73+
async function runOptionalRecoveryCommand(
74+
host: PlatformRuntimeHost,
75+
request: HostCommandRequest,
76+
signal: AbortSignal,
77+
): Promise<HostCommandResult | undefined> {
78+
signal.throwIfAborted();
79+
try {
80+
const result = await host.commands.run(request, signal);
81+
signal.throwIfAborted();
82+
return result;
83+
} catch {
84+
signal.throwIfAborted();
85+
return undefined;
86+
}
87+
}
88+
7089
async function recoveryContext(
7190
host: PlatformRuntimeHost,
7291
device: DeviceInfo,
@@ -97,9 +116,9 @@ async function recoverPackageTraffic(
97116
appBundleId: string,
98117
signal: AbortSignal,
99118
): Promise<{ text: string; pids: readonly string[] } | undefined> {
100-
assertAndroidLogPackageSafe(appBundleId);
101119
const currentPid = await resolveAndroidPid(host, device.id, appBundleId, signal);
102-
const result = await host.commands.run(
120+
const result = await runOptionalRecoveryCommand(
121+
host,
103122
{
104123
executable: 'adb',
105124
args: ['-s', device.id, 'logcat', '-d', '-v', 'time', '-t', '4000'],
@@ -108,6 +127,7 @@ async function recoverPackageTraffic(
108127
},
109128
signal,
110129
);
130+
if (!result) return undefined;
111131
if (result.exitCode !== 0 || !result.stdout.trim()) return undefined;
112132
const pids = collectPackagePids(result.stdout, appBundleId, currentPid);
113133
if (pids.length === 0) return undefined;
@@ -130,14 +150,16 @@ async function resolveAndroidPid(
130150
appBundleId: string,
131151
signal: AbortSignal,
132152
): Promise<string | undefined> {
133-
const result = await host.commands.run(
153+
const result = await runOptionalRecoveryCommand(
154+
host,
134155
{
135156
executable: 'adb',
136157
args: ['-s', deviceId, 'shell', 'pidof', appBundleId],
137158
allowFailure: true,
138159
},
139160
signal,
140161
);
162+
if (!result) return undefined;
141163
const pid = result.stdout.trim().split(/\s+/)[0];
142164
return pid && /^\d+$/.test(pid) ? pid : undefined;
143165
}

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

Lines changed: 18 additions & 16 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,10 @@ 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+
tool: 'simctl',
43+
args: expect.arrayContaining(['spawn', 'sim-1', '--start', '@1']),
4444
timeoutMs: 4_000,
4545
}),
4646
expect.any(AbortSignal),
@@ -50,7 +50,7 @@ test('recovers an empty iOS simulator dump from bounded simctl log history', asy
5050
test('preserves the simulator no-HTTP explanation after recovery returns app lines', async () => {
5151
const result = await dumpAppleNetworkTraffic(
5252
host({
53-
commandRun: async () => ({
53+
runSimctl: async () => ({
5454
stdout: '2026-08-10T10:00:00Z application diagnostic only\n',
5555
stderr: '',
5656
exitCode: 0,
@@ -69,10 +69,10 @@ test('preserves the simulator no-HTTP explanation after recovery returns app lin
6969
});
7070

7171
test('parses macOS session app-log traffic without loading simulator recovery', async () => {
72-
const commandRun = vi.fn();
72+
const runSimctl = vi.fn();
7373
const result = await dumpAppleNetworkTraffic(
7474
host({
75-
commandRun,
75+
runSimctl,
7676
text: '2026-08-10T10:00:00Z GET https://mac.example.test status=204\n',
7777
}),
7878
{ ...simulator, appleOs: 'macos', kind: 'device', target: 'desktop' },
@@ -84,7 +84,7 @@ test('parses macOS session app-log traffic without loading simulator recovery',
8484
backend: 'macos',
8585
dump: { entries: [{ url: 'https://mac.example.test', status: 204 }] },
8686
});
87-
expect(commandRun).not.toHaveBeenCalled();
87+
expect(runSimctl).not.toHaveBeenCalled();
8888
});
8989

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

102102
function host(options: {
103103
text?: string;
104-
commandRun: PlatformRuntimeHost['commands']['run'];
104+
runSimctl: PlatformRuntimeHost['appleTools']['run'];
105105
}): PlatformRuntimeHost {
106106
return {
107107
...unusedAppLogHost(),
108-
commands: { which: async () => undefined, run: options.commandRun },
108+
commands: {
109+
which: async () => undefined,
110+
run: async () => {
111+
throw new Error('generic command runner must not own Apple network recovery');
112+
},
113+
},
114+
appleTools: { isXcrunAvailable: async () => true, run: options.runSimctl },
109115
appLogs: {
110116
readRecent: async () => ({
111117
path: '/sessions/one/app.log',
@@ -121,13 +127,9 @@ function host(options: {
121127

122128
function unusedAppLogHost(): Omit<
123129
PlatformRuntimeHost,
124-
'commands' | 'appLogs' | 'networkTransports'
130+
'appleTools' | 'commands' | 'appLogs' | 'networkTransports'
125131
> {
126132
return {
127-
appleTools: {
128-
isXcrunAvailable: async () => false,
129-
run: async () => ({ stdout: '', stderr: '', exitCode: 0 }),
130-
},
131133
toolchains: { prepare: async () => {} },
132134
artifacts: {
133135
resolveSession: () => ({

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

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,6 @@ async function recoverSimulatorTraffic(
6565
signal: AbortSignal,
6666
): Promise<{ dump: NetworkDump; lineCount: number } | undefined> {
6767
const args = [
68-
'simctl',
6968
...(device.simulatorSetPath ? ['--set', device.simulatorSetPath] : []),
7069
'spawn',
7170
device.id,
@@ -83,8 +82,8 @@ async function recoverSimulatorTraffic(
8382
? ['--start', `@${Math.floor(startedAt / 1000)}`]
8483
: ['--last', '5m']),
8584
);
86-
const result = await host.commands.run(
87-
{ executable: 'xcrun', args, allowFailure: true, timeoutMs: 4_000 },
85+
const result = await host.appleTools.run(
86+
{ tool: 'simctl', args, allowFailure: true, timeoutMs: 4_000 },
8887
signal,
8988
);
9089
if (result.exitCode !== 0 || !result.stdout.trim()) return undefined;

‎packages/platform-web/package.json‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
"type": "module",
66
"description": "Web-family platform runtime metadata and implementations for agent-device.",
77
"dependencies": {
8-
"@agent-device/capture-kit": "workspace:*",
98
"@agent-device/contracts": "workspace:*",
109
"@agent-device/kernel": "workspace:*"
1110
},

‎pnpm-lock.yaml‎

Lines changed: 0 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)