diff --git a/packages/command-registry/src/flag-definitions-connection.ts b/packages/command-registry/src/flag-definitions-connection.ts index 4d3aada9c4..eb2e90ff9d 100644 --- a/packages/command-registry/src/flag-definitions-connection.ts +++ b/packages/command-registry/src/flag-definitions-connection.ts @@ -303,6 +303,26 @@ export const CONNECTION_FLAG_DEFINITIONS: readonly FlagDefinition[] = [ projectConfig: false, recorded: false, }, + { + key: 'providerNetworkLogs', + names: ['--provider-network-logs'], + type: 'boolean', + usageLabel: '--provider-network-logs', + usageDescription: + 'Limrun: capture session network traffic into a live HAR file on the daemon host; artifacts and close print its path and any tunnel failures. Pass --provider-network-hosts with your app API hosts. Captured traffic exits through the daemon host, the HAR holds raw headers and bodies, certificate-pinned hosts fail, and DNS-over-HTTPS bypasses the capture', + projectConfig: false, + recorded: false, + }, + { + key: 'providerNetworkHosts', + names: ['--provider-network-hosts'], + type: 'string', + usageLabel: '--provider-network-hosts ', + usageDescription: + 'With --provider-network-logs: comma-separated hosts to capture, such as your app API hosts (exact hosts, wildcards like *.example.com, or localhost: routes). Replaces the noisy default of common public domains plus localhost:8081', + projectConfig: false, + recorded: false, + }, { key: 'awsProjectArn', names: ['--aws-project-arn'], diff --git a/packages/command-registry/src/flag-groups.ts b/packages/command-registry/src/flag-groups.ts index d44966f880..8d193dd336 100644 --- a/packages/command-registry/src/flag-groups.ts +++ b/packages/command-registry/src/flag-groups.ts @@ -98,6 +98,8 @@ export const COMMON_COMMAND_SUPPORTED_FLAG_KEYS = flagKeys( 'providerNetworkProfile', 'providerCustomNetwork', 'providerNoResignApp', + 'providerNetworkLogs', + 'providerNetworkHosts', 'awsProjectArn', 'awsDeviceArn', 'awsAppArn', diff --git a/packages/contracts/src/client-connection.ts b/packages/contracts/src/client-connection.ts index 77b42b9f68..96bb4a55c9 100644 --- a/packages/contracts/src/client-connection.ts +++ b/packages/contracts/src/client-connection.ts @@ -167,6 +167,8 @@ export type AgentDeviceRequestOverrides = Pick< | 'providerNetworkProfile' | 'providerCustomNetwork' | 'providerNoResignApp' + | 'providerNetworkLogs' + | 'providerNetworkHosts' | 'awsProjectArn' | 'awsDeviceArn' | 'awsAppArn' diff --git a/packages/contracts/src/cloud-artifacts.ts b/packages/contracts/src/cloud-artifacts.ts index 5d3056a716..3cac24fb33 100644 --- a/packages/contracts/src/cloud-artifacts.ts +++ b/packages/contracts/src/cloud-artifacts.ts @@ -6,6 +6,7 @@ const CLOUD_ARTIFACT_KINDS = [ 'appium-log', 'device-log', 'automation-log', + 'network', 'provider-session', 'raw', ] as const; diff --git a/packages/contracts/src/lease-scope.ts b/packages/contracts/src/lease-scope.ts index 95ab79da0d..4ff5eaca6d 100644 --- a/packages/contracts/src/lease-scope.ts +++ b/packages/contracts/src/lease-scope.ts @@ -255,6 +255,8 @@ const LEASE_ALLOCATE_PROVIDER_FLAG_KEYS = [ 'providerNetworkProfile', 'providerCustomNetwork', 'providerNoResignApp', + 'providerNetworkLogs', + 'providerNetworkHosts', 'awsProjectArn', 'awsDeviceArn', 'awsAppArn', diff --git a/packages/contracts/src/provider-profile-fields.test.ts b/packages/contracts/src/provider-profile-fields.test.ts index b4012b1b39..d2722cfe39 100644 --- a/packages/contracts/src/provider-profile-fields.test.ts +++ b/packages/contracts/src/provider-profile-fields.test.ts @@ -27,6 +27,8 @@ const DECLARATION: ProviderProfileFieldDeclaration = { providerNetworkProfile: 'consumed', providerCustomNetwork: 'consumed', providerNoResignApp: 'refused', + providerNetworkLogs: 'consumed', + providerNetworkHosts: 'consumed', awsProjectArn: 'consumed', awsDeviceArn: 'consumed', awsAppArn: 'consumed', diff --git a/packages/contracts/src/remote-config-fields.ts b/packages/contracts/src/remote-config-fields.ts index 182dcc5b80..b2f7d32d4d 100644 --- a/packages/contracts/src/remote-config-fields.ts +++ b/packages/contracts/src/remote-config-fields.ts @@ -41,6 +41,13 @@ export type CloudProviderProfileFields = { providerNetworkProfile?: string; providerCustomNetwork?: string; providerNoResignApp?: boolean; + /** + * Asks a provider that supports it to capture session network traffic and deliver it as a HAR + * artifact. On Limrun the HAR is a live file the session writes while it runs. + */ + providerNetworkLogs?: boolean; + /** With `providerNetworkLogs`: comma-separated tunnel selectors replacing the default capture list. */ + providerNetworkHosts?: string; awsProjectArn?: string; awsDeviceArn?: string; awsAppArn?: string; @@ -67,6 +74,8 @@ export const PROVIDER_PROFILE_FIELD_FLAGS: Readonly< providerNetworkProfile: '--provider-network-profile', providerCustomNetwork: '--provider-custom-network', providerNoResignApp: '--provider-no-resign-app', + providerNetworkLogs: '--provider-network-logs', + providerNetworkHosts: '--provider-network-hosts', awsProjectArn: '--aws-project-arn', awsDeviceArn: '--aws-device-arn', awsAppArn: '--aws-app-arn', diff --git a/packages/daemon/src/sessions/handlers/session-doctor-options.test.ts b/packages/daemon/src/sessions/handlers/session-doctor-options.test.ts new file mode 100644 index 0000000000..552e5df762 --- /dev/null +++ b/packages/daemon/src/sessions/handlers/session-doctor-options.test.ts @@ -0,0 +1,29 @@ +import assert from 'node:assert/strict'; +import { test } from 'vitest'; +import type { DaemonRequest } from '../../core/daemon-request.ts'; +import { remoteConnectionChecks } from './session-doctor-options.ts'; + +function doctorRequest(flags: Record): DaemonRequest { + return { + token: 't', + session: 'default', + command: 'doctor', + positionals: [], + flags, + } as DaemonRequest; +} + +test('an enabled opt-in provider flag counts as configured provider scope', () => { + const [check] = remoteConnectionChecks(doctorRequest({ providerNetworkLogs: true }), { + required: true, + }); + assert.equal(check?.status, 'pass'); + assert.deepEqual(check?.evidence, { providerNetworkLogs: '' }); +}); + +test('a disabled opt-in provider flag is not provider scope', () => { + const [check] = remoteConnectionChecks(doctorRequest({ providerNetworkLogs: false }), { + required: true, + }); + assert.equal(check?.status, 'fail'); +}); diff --git a/packages/daemon/src/sessions/handlers/session-doctor-options.ts b/packages/daemon/src/sessions/handlers/session-doctor-options.ts index 49ab39dbde..ea688480fa 100644 --- a/packages/daemon/src/sessions/handlers/session-doctor-options.ts +++ b/packages/daemon/src/sessions/handlers/session-doctor-options.ts @@ -33,6 +33,8 @@ const REMOTE_PROVIDER_FLAG_KEYS = [ 'providerNetworkProfile', 'providerCustomNetwork', 'providerNoResignApp', + 'providerNetworkLogs', + 'providerNetworkHosts', 'awsProjectArn', 'awsDeviceArn', 'awsAppArn', @@ -153,8 +155,11 @@ function shouldProbeMetro(req: DaemonRequest, kind: DoctorKind): boolean { function remoteConnectionEvidence(req: DaemonRequest): Record | undefined { const configured = Object.fromEntries( + // An opt-in boolean counts only when it is on. [...REMOTE_CONNECTION_FLAG_KEYS, ...REMOTE_PROVIDER_FLAG_KEYS].flatMap((key) => - typeof req.flags?.[key] === 'string' ? [[key, '']] : [], + typeof req.flags?.[key] === 'string' || req.flags?.[key] === true + ? [[key, '']] + : [], ), ); const evidence = { diff --git a/packages/provider-limrun/src/device.ts b/packages/provider-limrun/src/device.ts index 8468e5ae36..b1afd85119 100644 --- a/packages/provider-limrun/src/device.ts +++ b/packages/provider-limrun/src/device.ts @@ -7,7 +7,10 @@ export type LimrunPlatform = 'ios' | 'android'; export const LIMRUN_PROVIDER = 'limrun'; -/** Limrun reads only the app to preinstall; it picks the instance itself. */ +/** + * Limrun reads the app to preinstall and the network capture settings; it picks the instance + * itself. + */ export const LIMRUN_PROFILE_FIELDS: ProviderProfileFieldDeclaration = { provider: LIMRUN_PROVIDER, label: 'Limrun', @@ -27,6 +30,8 @@ export const LIMRUN_PROFILE_FIELDS: ProviderProfileFieldDeclaration = { providerNetworkProfile: 'refused', providerCustomNetwork: 'refused', providerNoResignApp: 'refused', + providerNetworkLogs: 'consumed', + providerNetworkHosts: 'consumed', awsProjectArn: 'refused', awsDeviceArn: 'refused', awsAppArn: 'refused', diff --git a/packages/provider-limrun/src/network-har.test.ts b/packages/provider-limrun/src/network-har.test.ts new file mode 100644 index 0000000000..bb9f2b7d47 --- /dev/null +++ b/packages/provider-limrun/src/network-har.test.ts @@ -0,0 +1,349 @@ +import assert from 'node:assert/strict'; +import { test, vi } from 'vitest'; +import fs from 'node:fs'; +import path from 'node:path'; +import type { DestinationTunnelInspectionEvent } from '@limrun/api/destination-tunnel-inspection'; +import { DestinationTunnelSessionError } from '@limrun/api/destination-tunnel-dialer'; +import { mkdtempForTestSync } from './tmp-dir.fixtures.ts'; +import { + DEFAULT_LIMRUN_HAR_SELECTORS, + HAR_MAX_BYTES, + startLimrunHarCapture, +} from './network-har.ts'; + +function harEntry(url: string, error?: string, comment?: string): DestinationTunnelInspectionEvent { + return { + type: 'complete', + sequence: 1, + requestId: `req-${url}`, + data: { + startedDateTime: new Date().toISOString(), + time: 12, + request: { + method: 'GET', + url, + httpVersion: 'HTTP/1.1', + cookies: [], + headers: [], + queryString: [], + headersSize: -1, + bodySize: 0, + }, + ...(comment ? { comment } : {}), + response: { + // The tunnel reports a request it could not complete with status 0. + status: error ? 0 : 200, + statusText: error ? '' : 'OK', + httpVersion: 'HTTP/1.1', + cookies: [], + headers: [], + content: { size: 0, mimeType: 'application/json' }, + redirectURL: '', + headersSize: -1, + bodySize: 0, + }, + cache: {}, + timings: { send: 0, wait: 10, receive: 2 }, + _limrun: { tunnelId: 't1', selectorId: 's1', ...(error ? { error } : {}) }, + }, + } as unknown as DestinationTunnelInspectionEvent; +} + +function fakeTunnelClient( + lastDialFailure?: { + tunnelId: string; + selectorId: string; + reason: string; + osCode?: string; + }, + tunnelClose: () => void = () => {}, +) { + const started: { + selectors: string[]; + onEvent?: (e: DestinationTunnelInspectionEvent) => void; + onError?: (error: Error) => void; + }[] = []; + return { + started, + client: { + startTunnel: async (options: { + selectors: string[]; + onInspectionEvent?: (event: DestinationTunnelInspectionEvent) => void; + onInspectionError?: (error: Error) => void; + }) => { + started.push({ + selectors: options.selectors, + onEvent: options.onInspectionEvent, + onError: options.onInspectionError, + }); + return { + tunnelId: 't1', + selectors: [{ id: 's1', kind: 'domain', value: '*.com' }], + close: tunnelClose, + } as never; + }, + getTunnelStatus: async () => (lastDialFailure ? { lastDialFailure } : {}), + }, + }; +} + +function tempHarPath(): string { + return path.join(mkdtempForTestSync('limrun-har-'), 'session', 'har.har'); +} + +test('the default capture selectors carry the public wildcards and the Metro route', () => { + assert.ok(DEFAULT_LIMRUN_HAR_SELECTORS.includes('*.com')); + // One tunnel per instance: the Metro/companion route must ride this same tunnel. + assert.ok(DEFAULT_LIMRUN_HAR_SELECTORS.includes('localhost:8081')); +}); + +function readEntries(harPath: string): { response: { status: number } }[] { + return ( + JSON.parse(fs.readFileSync(harPath, 'utf8')) as { + log: { entries: { response: { status: number } }[] }; + } + ).log.entries; +} + +function readEntryCount(harPath: string): number { + return readEntries(harPath).length; +} + +test('completed requests reach the live HAR in one coalesced, owner-only write', async () => { + const fake = fakeTunnelClient(); + const harPath = tempHarPath(); + // An existing, wider directory is tightened too. + fs.mkdirSync(path.dirname(harPath), { recursive: true, mode: 0o755 }); + const result = await startLimrunHarCapture(fake.client, { harPath }); + assert.equal(result.ok, true); + if (!result.ok) return; + const emit = fake.started[0]?.onEvent; + assert.ok(emit); + emit(harEntry('https://example.com/a')); + emit(harEntry('https://example.com/b')); + assert.equal(readEntryCount(harPath), 0); + + await vi.waitFor(() => assert.equal(readEntryCount(harPath), 2)); + const document = JSON.parse(fs.readFileSync(harPath, 'utf8')) as { + log: { version: string; entries: unknown[] }; + }; + assert.equal(document.log.version, '1.2'); + assert.equal(document.log.entries.length, 2); + assert.equal(fs.statSync(harPath).mode & 0o777, 0o600); + assert.equal(fs.statSync(path.dirname(harPath)).mode & 0o777, 0o700); + + // Close flushes a request that is still inside the coalescing window. + emit(harEntry('https://example.com/c')); + await result.capture.close(); + assert.equal(readEntryCount(harPath), 3); + assert.deepEqual( + fs.readdirSync(path.dirname(harPath)).filter((name) => name.endsWith('.tmp')), + [], + ); +}); + +test('the HAR keeps the newest entries under its size cap and reports the dropped ones', async () => { + const fake = fakeTunnelClient(); + const harPath = tempHarPath(); + const result = await startLimrunHarCapture(fake.client, { harPath }); + assert.equal(result.ok, true); + if (!result.ok) return; + const emit = fake.started[0]?.onEvent; + assert.ok(emit); + // Two UTF-8 bytes per character: a quarter of the cap in bytes, an eighth in string length. + const large = 'é'.repeat(Math.ceil(HAR_MAX_BYTES / 8)); + for (let index = 0; index < 6; index += 1) { + emit(harEntry(`https://example.com/${index}`, undefined, large)); + } + await result.capture.close(); + + const urls = ( + JSON.parse(fs.readFileSync(harPath, 'utf8')) as { + log: { entries: { request: { url: string } }[] }; + } + ).log.entries.map((entry) => entry.request.url); + assert.deepEqual(urls, [ + 'https://example.com/3', + 'https://example.com/4', + 'https://example.com/5', + ]); + assert.ok(fs.statSync(harPath).size <= HAR_MAX_BYTES); + const report = await result.capture.failures(); + assert.equal(report.byKind['har-truncated']?.count, 3); +}); + +test('a relative HAR path is refused before any directory is touched', async () => { + const fake = fakeTunnelClient(); + const result = await startLimrunHarCapture(fake.client, { harPath: 'capture.har' }); + assert.equal(result.ok, false); + if (result.ok) return; + assert.equal(result.reason, 'tunnel-start-failed'); + assert.equal(fake.started.length, 0); +}); + +test('a capture whose HAR cannot be written refuses before the tunnel opens', async () => { + const fake = fakeTunnelClient(); + const harPath = tempHarPath(); + // A non-empty directory where the HAR belongs: the rename into place fails. + fs.mkdirSync(harPath, { recursive: true }); + fs.writeFileSync(path.join(harPath, 'occupied'), ''); + const result = await startLimrunHarCapture(fake.client, { harPath }); + assert.equal(result.ok, false); + if (result.ok) return; + assert.equal(result.reason, 'tunnel-start-failed'); + assert.equal(fake.started.length, 0); + assert.deepEqual(fs.readdirSync(path.dirname(harPath)), [path.basename(harPath)]); +}); + +test('a tunnel that refuses to close still gets its HAR written, and a later close retries', async () => { + let closeAttempts = 0; + const fake = fakeTunnelClient(undefined, () => { + closeAttempts += 1; + if (closeAttempts === 1) throw new Error('socket busy'); + }); + const harPath = tempHarPath(); + const result = await startLimrunHarCapture(fake.client, { harPath }); + assert.equal(result.ok, true); + if (!result.ok) return; + fake.started[0]?.onEvent?.(harEntry('https://example.com/a')); + + await assert.rejects(() => result.capture.close(), /socket busy/); + assert.equal(readEntryCount(harPath), 1); + await result.capture.close(); + await result.capture.close(); + assert.equal(closeAttempts, 2); +}); + +test('tunnel failures are counted, with the latest endpoints and the typed dial reason', async () => { + const fake = fakeTunnelClient({ + tunnelId: 't1', + selectorId: 's1', + reason: 'dns_not_found', + osCode: 'ENOTFOUND', + }); + const result = await startLimrunHarCapture(fake.client, { harPath: tempHarPath() }); + assert.equal(result.ok, true); + if (!result.ok) return; + const started = fake.started[0]; + assert.ok(started?.onEvent && started.onError); + started.onEvent(harEntry('https://example.com/ok')); + started.onEvent( + harEntry('https://missing.example.com/a', 'tunnel client could not open the destination'), + ); + started.onEvent({ + type: 'inspection_error', + sequence: 3, + data: { host: 'pinned.example.com', port: 443, message: 'terminate app TLS: EOF' }, + }); + started.onEvent({ + type: 'gap', + sequence: 9, + data: { fromSequence: 4, toSequence: 8, message: 'events dropped' }, + }); + started.onError(new Error('inspection stream closed')); + + const report = await result.capture.failures(); + assert.equal(report.total, 4); + const endpoints = Object.fromEntries( + Object.entries(report.byKind).map(([kind, entry]) => [ + kind, + { count: entry.count, latest: entry.latest.map(({ host, port }) => ({ host, port })) }, + ]), + ); + assert.deepEqual(endpoints, { + 'request-failed': { count: 1, latest: [{ host: 'missing.example.com', port: 443 }] }, + 'inspection-error': { count: 1, latest: [{ host: 'pinned.example.com', port: 443 }] }, + 'inspection-gap': { count: 1, latest: [{ host: undefined, port: undefined }] }, + 'inspection-stream-error': { count: 1, latest: [{ host: undefined, port: undefined }] }, + }); + assert.deepEqual(report.lastDialFailure, { + reason: 'dns_not_found', + osCode: 'ENOTFOUND', + selector: '*.com', + }); + // The failed request stays in the HAR, as a status-0 entry. + await result.capture.close(); + assert.deepEqual( + readEntries(result.capture.harPath).map((entry) => entry.response.status), + [200, 0], + ); +}); + +test('inspection errors from pinned hosts do not evict failed requests', async () => { + const fake = fakeTunnelClient(); + const result = await startLimrunHarCapture(fake.client, { harPath: tempHarPath() }); + assert.equal(result.ok, true); + if (!result.ok) return; + const emit = fake.started[0]?.onEvent; + assert.ok(emit); + emit(harEntry('https://api.example.com/login', 'client_dial_failed')); + for (let sequence = 0; sequence < 20; sequence += 1) { + emit({ + type: 'inspection_error', + sequence, + data: { host: 'pinned.example.com', port: 443, message: 'terminate app TLS: EOF' }, + }); + } + const report = await result.capture.failures(); + assert.equal(report.total, 21); + assert.equal(report.byKind['inspection-error']?.count, 20); + assert.equal(report.byKind['inspection-error']?.latest.length, 5); + assert.equal(report.byKind['request-failed']?.latest[0]?.host, 'api.example.com'); + await result.capture.close(); +}); + +test("another tunnel's dial failure is not reported as this capture's", async () => { + const fake = fakeTunnelClient({ tunnelId: 'older', selectorId: 's1', reason: 'client_timeout' }); + const result = await startLimrunHarCapture(fake.client, { harPath: tempHarPath() }); + assert.equal(result.ok, true); + if (!result.ok) return; + const report = await result.capture.failures(); + assert.equal(report.total, 0); + assert.equal(report.lastDialFailure, undefined); + await result.capture.close(); +}); + +test('a tunnel conflict is reported as a typed refusal, not a crash', async () => { + const result = await startLimrunHarCapture( + { + startTunnel: async () => { + throw new DestinationTunnelSessionError('already_active'); + }, + }, + { harPath: tempHarPath() }, + ); + assert.equal(result.ok, false); + if (result.ok) return; + assert.equal(result.reason, 'tunnel-in-use'); +}); + +test('conflict text without the typed session error code is not a tunnel conflict', async () => { + const result = await startLimrunHarCapture( + { + startTunnel: async () => { + throw new Error('destination tunnel failed: already_active'); + }, + }, + { harPath: tempHarPath() }, + ); + assert.equal(result.ok, false); + if (result.ok) return; + assert.equal(result.reason, 'tunnel-start-failed'); +}); + +test('a rejected selector is refused before any tunnel opens', async () => { + let opened = false; + const result = await startLimrunHarCapture( + { + startTunnel: async () => { + opened = true; + return {} as never; + }, + }, + { harPath: tempHarPath(), selectors: ['not a host!!'] }, + ); + assert.equal(result.ok, false); + if (result.ok) return; + assert.equal(result.reason, 'tunnel-start-failed'); + assert.equal(opened, false); +}); diff --git a/packages/provider-limrun/src/network-har.ts b/packages/provider-limrun/src/network-har.ts new file mode 100644 index 0000000000..3ca3094fc1 --- /dev/null +++ b/packages/provider-limrun/src/network-har.ts @@ -0,0 +1,400 @@ +import { DestinationTunnelHARAssembler } from '@limrun/api/destination-tunnel-har'; +import { validateDestinationTunnelSelectors } from '@limrun/api/destination-tunnel'; +import { DestinationTunnelSessionError } from '@limrun/api/destination-tunnel-dialer'; +import type { DestinationTunnelOpenFailureReason } from '@limrun/api/destination-tunnel'; +import type { DestinationTunnelInspectionEvent } from '@limrun/api/destination-tunnel-inspection'; +import type { DestinationTcpTunnel } from '@limrun/api/destination-tunnel-dialer'; +import fs from 'node:fs'; +import path from 'node:path'; + +/** + * The Limrun network capture: one destination tunnel with inspection, streamed into a live HAR 1.2 + * file. The file is replaced whole after completed requests, so a reader (jq included) always sees + * a valid document, during the session and after it. Memory and the cost of each write stay + * bounded however long the session runs: bodies are cut at `HAR_BODY_LIMIT_BYTES`, and the + * oldest entries leave the file once it would pass `HAR_MAX_BYTES`. + * + * One instance carries one destination tunnel, so the Metro/companion route rides this same + * tunnel: the default selectors include the `localhost:8081` route, which makes the host's Metro + * reachable from the device through the tunnel. + * + * Known limits: certificate-pinned hosts fail closed against the tunnel's interception, and apps + * that resolve names over DNS-over-HTTPS bypass the capture entirely. Captured traffic leaves from + * the daemon host, not from the device's network. + * + * Tunnel failures never reach the HAR's readers on their own: the SDK logs dial failures only to + * the console. The capture therefore records the typed inspection failures (a request the tunnel + * could not complete, an inspection error, a stream gap) and reads the tunnel's last typed dial + * failure on demand, so `artifacts` and close can report them. + */ + +/** Generic public-TLD wildcards, measured acceptable by Limrun's selector validation. */ +export const DEFAULT_LIMRUN_HAR_SELECTORS = Object.freeze([ + '*.com', + '*.org', + '*.app', + '*.net', + '*.io', + '*.dev', + // The Metro/companion route: the device reaches this host's Metro through the one tunnel. + 'localhost:8081', +] as const); + +export type LimrunHarTunnelClient = Readonly<{ + startTunnel(options: { + selectors: string[]; + inspection?: { enabled?: boolean; captureBodies?: boolean; maxBodyBytes?: number }; + onInspectionEvent?: (event: DestinationTunnelInspectionEvent) => void; + onInspectionError?: (error: Error) => void; + }): Promise; + getTunnelStatus?(): Promise< + Readonly<{ + lastDialFailure?: Readonly<{ + tunnelId: string; + selectorId: string; + reason: DestinationTunnelOpenFailureReason; + osCode?: string; + }>; + }> + >; +}>; + +/** + * What failed inside the capture: + * - `request-failed`: the tunnel accepted the device's request but could not complete it, for + * example a destination that did not resolve, refused, or timed out. The HAR holds the entry + * with status 0. + * - `inspection-error`: the tunnel could not inspect a connection, usually a certificate-pinned + * host that rejected the interception. + * - `inspection-gap`: the inspection stream skipped events, so the HAR misses requests. + * - `inspection-stream-error`: the inspection stream itself failed. + * - `har-write-failed`: the HAR file could not be written, so it lags the captured traffic. + * - `har-truncated`: the oldest entries left the HAR to keep it under its size cap; the count is + * the number of entries dropped. + */ +export type LimrunTunnelFailureKind = + | 'request-failed' + | 'inspection-error' + | 'inspection-gap' + | 'inspection-stream-error' + | 'har-write-failed' + | 'har-truncated'; + +export type LimrunTunnelFailure = Readonly<{ + at: string; + host?: string; + port?: number; + /** The provider's own description, kept verbatim for a human reader. */ + message: string; +}>; + +export type LimrunTunnelFailureReport = Readonly<{ + total: number; + /** + * Each kind's count and its most recent failures, oldest first. Kinds are kept apart, so the + * inspection errors of pinned system hosts cannot push an app's failed requests out. + */ + byKind: Readonly< + Partial< + Record< + LimrunTunnelFailureKind, + Readonly<{ count: number; latest: readonly LimrunTunnelFailure[] }> + > + > + >; + /** The tunnel's most recent dial failure, with the provider's typed reason. */ + lastDialFailure?: Readonly<{ + reason: DestinationTunnelOpenFailureReason; + osCode?: string; + selector?: string; + }>; +}>; + +const LATEST_FAILURES_PER_KIND = 5; +const TUNNEL_STATUS_BUDGET_MS = 2_000; +/** Completed requests within this window share one rewrite of the HAR file. */ +const HAR_WRITE_COALESCE_MS = 250; +/** Each request and response body is cut to this size, by the tunnel and by the assembler. */ +const HAR_BODY_LIMIT_BYTES = 64 * 1024; +/** The serialized entries a HAR file keeps; older entries are dropped first. */ +export const HAR_MAX_BYTES = 8 * 1024 * 1024; + +export type LimrunHarCapture = Readonly<{ + harPath: string; + /** + * Stops inspection and writes the final HAR document. Safe more than once; when the tunnel + * refuses to close, the HAR is still written and a later call tries the tunnel again. + */ + close(): Promise; + /** The failures recorded so far, plus the tunnel's last dial failure while it is open. */ + failures(): Promise; +}>; + +export type LimrunHarCaptureFailure = Readonly<{ + reason: 'tunnel-in-use' | 'tunnel-start-failed' | 'capture-dir-unset'; + message: string; +}>; + +export type LimrunHarCaptureResult = + | Readonly<{ ok: true; capture: LimrunHarCapture }> + | Readonly<{ ok: false } & LimrunHarCaptureFailure>; + +/** + * Opens the instance's destination tunnel with inspection and writes every completed request into + * `harPath` as a HAR 1.2 document. Bodies are captured; the file holds raw traffic. + */ +export async function startLimrunHarCapture( + client: LimrunHarTunnelClient, + input: Readonly<{ harPath: string; selectors?: readonly string[] }>, +): Promise { + const selectors = [...(input.selectors ?? DEFAULT_LIMRUN_HAR_SELECTORS)]; + try { + validateDestinationTunnelSelectors(selectors); + } catch (error) { + return { ok: false, reason: 'tunnel-start-failed', message: describe(error) }; + } + const failures = createFailureRecorder(); + try { + // A relative path would make the capture directory, and its chmod, the daemon's cwd. + if (!path.isAbsolute(input.harPath)) { + return { + ok: false, + reason: 'tunnel-start-failed', + message: 'The HAR path must be absolute.', + }; + } + // The HAR holds raw traffic, so only the daemon's user may read it. + const harDir = path.dirname(input.harPath); + await fs.promises.mkdir(harDir, { recursive: true, mode: 0o700 }); + // mkdir leaves an existing directory as it was, so tighten it explicitly. + await fs.promises.chmod(harDir, 0o700); + const harFile = createHarFile(input.harPath, { + onDropped: (count) => + failures.record( + 'har-truncated', + { message: `dropped the ${count} oldest entries to stay under ${HAR_MAX_BYTES} bytes` }, + count, + ), + onWriteError: (error) => failures.record('har-write-failed', { message: describe(error) }), + }); + // The first publication must succeed: a capture whose file cannot be written does not start. + await harFile.flush(true); + const assembler = new DestinationTunnelHARAssembler(HAR_BODY_LIMIT_BYTES); + let closed = false; + const tunnel = await client.startTunnel({ + selectors, + inspection: { enabled: true, captureBodies: true, maxBodyBytes: HAR_BODY_LIMIT_BYTES }, + onInspectionEvent: (event) => { + if (closed) return; + failures.observe(event); + const completed = assembler.add(event); + if (completed && event.type === 'complete') harFile.add(completed); + }, + onInspectionError: (error) => { + failures.record('inspection-stream-error', { message: describe(error) }); + }, + }); + return { + ok: true, + capture: Object.freeze({ + harPath: input.harPath, + close: async () => { + if (closed) return; + try { + tunnel.close(); + closed = true; + } finally { + await harFile.flush(); + } + }, + failures: async () => + failures.report( + closed + ? undefined + : await readLastDialFailure(client, tunnel.tunnelId, tunnel.selectors), + ), + }), + }; + } catch (error) { + return { + ok: false, + reason: + error instanceof DestinationTunnelSessionError && error.code === 'already_active' + ? 'tunnel-in-use' + : 'tunnel-start-failed', + message: describe(error), + }; + } +} + +function createFailureRecorder() { + const byKind: Partial< + Record + > = {}; + let total = 0; + const record = ( + kind: LimrunTunnelFailureKind, + failure: Omit, + count = 1, + ): void => { + total += count; + const entry = (byKind[kind] ??= { count: 0, latest: [] }); + entry.count += count; + entry.latest.push({ ...failure, at: new Date().toISOString() }); + if (entry.latest.length > LATEST_FAILURES_PER_KIND) entry.latest.shift(); + }; + return { + record, + observe(event: DestinationTunnelInspectionEvent): void { + if (event.type === 'complete' && event.data._limrun.error) { + record('request-failed', { + ...readUrlEndpoint(event.data.request.url), + message: event.data._limrun.error, + }); + } else if (event.type === 'inspection_error') { + const { host, port, message } = event.data; + record('inspection-error', { + ...(typeof host === 'string' ? { host } : {}), + ...(typeof port === 'number' ? { port } : {}), + message, + }); + } else if (event.type === 'gap') { + record('inspection-gap', { message: event.data.message }); + } + }, + report( + lastDialFailure: LimrunTunnelFailureReport['lastDialFailure'], + ): LimrunTunnelFailureReport { + return { + total, + byKind: Object.fromEntries( + Object.entries(byKind).map(([kind, entry]) => [ + kind, + { count: entry.count, latest: [...entry.latest] }, + ]), + ), + ...(lastDialFailure ? { lastDialFailure } : {}), + }; + }, + }; +} + +/** Best effort: the status read is bounded well below a listing or close request. */ +async function readLastDialFailure( + client: LimrunHarTunnelClient, + tunnelId: string, + selectors: DestinationTcpTunnel['selectors'], +): Promise { + const readStatus = client.getTunnelStatus; + if (!readStatus) return undefined; + const status = await new Promise> | undefined>( + (resolve) => { + const timer = setTimeout(() => resolve(undefined), TUNNEL_STATUS_BUDGET_MS); + readStatus + .call(client) + .then(resolve, () => resolve(undefined)) + .finally(() => clearTimeout(timer)); + }, + ); + const failure = status?.lastDialFailure; + if (!failure || failure.tunnelId !== tunnelId) return undefined; + const selector = selectors?.find((report) => report.id === failure.selectorId)?.value; + return { + reason: failure.reason, + ...(failure.osCode ? { osCode: failure.osCode } : {}), + ...(selector ? { selector } : {}), + }; +} + +function readUrlEndpoint(url: string): Readonly<{ host?: string; port?: number }> { + try { + const parsed = new URL(url); + const port = parsed.port + ? Number(parsed.port) + : parsed.protocol === 'https:' + ? 443 + : parsed.protocol === 'http:' + ? 80 + : undefined; + return { host: parsed.hostname, ...(port === undefined ? {} : { port }) }; + } catch { + return {}; + } +} + +const HAR_HEADER = + '{"log":{"version":"1.2","creator":{"name":"agent-device limrun-tunnel","version":"1"},"entries":['; +const HAR_FOOTER = ']}}\n'; +const HAR_WRAPPER_BYTES = Buffer.byteLength(HAR_HEADER) + Buffer.byteLength(HAR_FOOTER); + +/** + * The HAR file of one capture. Each entry is serialized once into a ring capped at + * `HAR_MAX_BYTES`; a write joins the ring, so its cost is bounded too. Writes coalesce, and one + * runs at a time, off the event loop. + */ +function createHarFile( + harPath: string, + hooks: Readonly<{ onDropped: (count: number) => void; onWriteError: (error: unknown) => void }>, +) { + const entries: { json: string; bytes: number }[] = []; + // The file's size in UTF-8 bytes: the wrapper, every entry, and the commas between them. + let bytes = HAR_WRAPPER_BYTES; + let timer: NodeJS.Timeout | undefined; + let inFlight: Promise | undefined; + let tempSequence = 0; + /** Publishes the file; `required` rethrows a failure instead of recording it. */ + const write = async (required: boolean): Promise => { + // A fresh, exclusively created temp file, renamed into place: a reader never sees a partial + // document, and the published file always carries the owner-only mode. + tempSequence += 1; + const tempPath = `${harPath}.${process.pid}-${tempSequence}.tmp`; + try { + const document = `${HAR_HEADER}${entries.map((entry) => entry.json).join(',')}${HAR_FOOTER}`; + await fs.promises.writeFile(tempPath, document, { + mode: 0o600, + flag: 'wx', + }); + await fs.promises.rename(tempPath, harPath); + } catch (error) { + await fs.promises.rm(tempPath, { force: true }).catch(() => undefined); + if (required) throw error; + hooks.onWriteError(error); + } + }; + const flush = async (required = false): Promise => { + clearTimeout(timer); + timer = undefined; + while (inFlight) await inFlight; + inFlight = write(required).finally(() => { + inFlight = undefined; + }); + await inFlight; + }; + return { + flush, + add(entry: unknown): void { + const json = JSON.stringify(entry); + const entryBytes = Buffer.byteLength(json); + entries.push({ json, bytes: entryBytes }); + bytes += entryBytes + (entries.length > 1 ? 1 : 0); + let dropped = 0; + // An entry that cannot fit even alone leaves too. + while (bytes > HAR_MAX_BYTES && entries.length > 0) { + const oldest = entries.shift(); + bytes -= (oldest?.bytes ?? 0) + (entries.length > 0 ? 1 : 0); + dropped += 1; + } + if (dropped > 0) hooks.onDropped(dropped); + timer ??= setTimeout(() => void flush(), HAR_WRITE_COALESCE_MS); + }, + }; +} + +/** Deletes a capture's HAR file once nothing reports it any more. */ +export async function discardLimrunHar(harPath: string): Promise { + await fs.promises.rm(harPath, { force: true }); +} + +function describe(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} diff --git a/packages/provider-limrun/src/runtime.test.ts b/packages/provider-limrun/src/runtime.test.ts index 343594ddb5..700d57ff04 100644 --- a/packages/provider-limrun/src/runtime.test.ts +++ b/packages/provider-limrun/src/runtime.test.ts @@ -1,4 +1,5 @@ import assert from 'node:assert/strict'; +import fs from 'node:fs'; import { test, vi } from 'vitest'; import type { AppsFilter, DeviceLease } from '@agent-device/contracts/device'; import type { Interactor } from '@agent-device/contracts/interactor-types'; @@ -12,6 +13,7 @@ import { } from '@agent-device/platform-android/mechanics'; import { createLimrunRuntime } from './runtime.ts'; import { unusedLimrunRuntimeHost } from './runtime.fixtures.ts'; +import { mkdtempForTestSync } from './tmp-dir.fixtures.ts'; import type { LimrunAdbExecutor, LimrunRuntimeDependencies } from './runtime-dependencies.ts'; /** @@ -27,6 +29,10 @@ const state = vi.hoisted(() => ({ | undefined, disconnect: vi.fn(), tunnelClose: vi.fn(), + androidDelete: vi.fn(async () => undefined), + inspectionEvents: [] as ((event: unknown) => void)[], + destinationTunnelClose: vi.fn(), + tunnelStatus: {} as Record, })); vi.mock('@limrun/api', () => ({ @@ -42,7 +48,7 @@ vi.mock('@limrun/api', () => ({ }, })), list: vi.fn(), - delete: vi.fn(async () => undefined), + delete: state.androidDelete, }; readonly assets = { getOrUpload: vi.fn(), list: vi.fn() }; }, @@ -61,6 +67,11 @@ vi.mock('@limrun/api/instance-client', () => ({ address: { address: '127.0.0.1', port: 62_001 }, close: state.tunnelClose, })), + startTunnel: vi.fn(async (options: { onInspectionEvent: (event: unknown) => void }) => { + state.inspectionEvents.push(options.onInspectionEvent); + return { tunnelId: 't1', selectors: [], close: state.destinationTunnelClose }; + }), + getTunnelStatus: vi.fn(async () => state.tunnelStatus), })), })); @@ -182,11 +193,150 @@ function requestScope(signal: AbortSignal = new AbortController().signal): Platf }; } -async function allocateAndroidDevice( - runtime: ReturnType, - leaseId = 'lease-appstate', -): Promise { - const lease: DeviceLease = { +test('a network capture reports its HAR and failures through artifacts and every release attempt', async () => { + const runtime = createLimrunRuntime( + { apiKey: 'lim_test_key', networkHarDir: mkdtempForTestSync('limrun-runtime-har-') }, + testDependencies(), + ); + const lease = androidLease('lease-capture'); + try { + await runtime.leaseLifecycle.allocate?.(lease, { flags: { providerNetworkLogs: true } }); + state.inspectionEvents.at(-1)?.(failedRequest('https://api.example.com/login')); + + const listed = await runtime.cloudArtifacts?.listCloudArtifacts?.({ leaseId: lease.leaseId }); + const harPath = listed?.cloudArtifacts[0]?.url; + assert.match(String(harPath), /android-instance-1-lease-capture\.har$/); + assert.match(String(listed?.message), /request-failed 1, latest api\.example\.com:443/); + + const release = runtime.leaseLifecycle.release; + assert.ok(release); + state.androidDelete.mockRejectedValueOnce(new Error('temporary delete failure')); + await assert.rejects(() => release(lease), /temporary delete failure/); + const retried = (await release(lease)) as { + cloudArtifacts?: { cloudArtifacts: { url?: string }[]; message?: string }; + }; + assert.equal(retried.cloudArtifacts?.cloudArtifacts[0]?.url, harPath); + assert.match(String(retried.cloudArtifacts?.message), /request-failed 1/); + assert.equal(state.destinationTunnelClose.mock.calls.length, 1); + } finally { + await runtime.shutdown?.(); + } +}); + +test('a repeat allocation starts the capture it newly asks for, and a dial-only failure is reported', async () => { + const runtime = createLimrunRuntime( + { apiKey: 'lim_test_key', networkHarDir: mkdtempForTestSync('limrun-runtime-har-') }, + testDependencies(), + ); + const lease = androidLease('lease-repeat'); + state.tunnelStatus = { + lastDialFailure: { tunnelId: 't1', selectorId: 's1', reason: 'connection_refused' }, + }; + try { + const first = await runtime.leaseLifecycle.allocate?.(lease); + assert.equal(first?.networkHar, undefined); + const repeat = await runtime.leaseLifecycle.allocate?.(lease, { + flags: { providerNetworkLogs: true }, + }); + assert.equal((repeat?.networkHar as { status?: string } | undefined)?.status, 'capturing'); + + const listed = await runtime.cloudArtifacts?.listCloudArtifacts?.({ leaseId: lease.leaseId }); + assert.match(String(listed?.message), /last dial failure connection_refused/); + } finally { + state.tunnelStatus = {}; + await runtime.shutdown?.(); + } +}); + +test('a repeat allocation retries a capture that could not start', async () => { + const runtime = createLimrunRuntime( + { apiKey: 'lim_test_key', networkHarDir: mkdtempForTestSync('limrun-runtime-har-') }, + testDependencies(), + ); + const lease = androidLease('lease-retry'); + try { + const first = await runtime.leaseLifecycle.allocate?.(lease, { + flags: { providerNetworkLogs: true, providerNetworkHosts: 'not a host!!' }, + }); + assert.equal((first?.networkHar as { status?: string } | undefined)?.status, 'unavailable'); + const retried = await runtime.leaseLifecycle.allocate?.(lease, { + flags: { providerNetworkLogs: true, providerNetworkHosts: 'api.example.com' }, + }); + assert.equal((retried?.networkHar as { status?: string } | undefined)?.status, 'capturing'); + } finally { + await runtime.shutdown?.(); + } +}); + +test('a stopped capture past the retention limit loses its record and its HAR file', async () => { + const runtime = createLimrunRuntime( + { apiKey: 'lim_test_key', networkHarDir: mkdtempForTestSync('limrun-runtime-har-') }, + testDependencies(), + ); + const release = runtime.leaseLifecycle.release; + assert.ok(release); + const harPaths: string[] = []; + try { + // 33 stopped captures; the 34th start evicts the oldest. + for (let index = 0; index < 34; index += 1) { + const lease = androidLease(`lease-retention-${index}`); + const allocation = await runtime.leaseLifecycle.allocate?.(lease, { + flags: { providerNetworkLogs: true }, + }); + harPaths.push(String((allocation?.networkHar as { harPath?: string } | undefined)?.harPath)); + if (index < 33) await release(lease); + } + assert.equal(fs.existsSync(harPaths[0] ?? ''), false); + assert.equal(fs.existsSync(harPaths[1] ?? ''), true); + assert.equal( + await runtime.cloudArtifacts?.listCloudArtifacts?.({ leaseId: 'lease-retention-0' }), + undefined, + ); + } finally { + await runtime.shutdown?.(); + } +}); + +test('a network capture that cannot start is an unavailable artifact with its typed reason', async () => { + const runtime = createLimrunRuntime({ apiKey: 'lim_test_key' }, testDependencies()); + const lease = androidLease('lease-no-dir'); + try { + const allocation = await runtime.leaseLifecycle.allocate?.(lease, { + flags: { providerNetworkLogs: true }, + }); + assert.deepEqual(allocation?.networkHar, { + status: 'unavailable', + reason: 'capture-dir-unset', + message: 'The runtime has no directory for network capture files.', + }); + const listed = await runtime.cloudArtifacts?.listCloudArtifacts?.({ leaseId: lease.leaseId }); + assert.equal(listed?.status, 'unavailable'); + assert.deepEqual(listed?.cloudArtifacts[0]?.metadata, { reason: 'capture-dir-unset' }); + assert.match(String(listed?.message), /did not start \(capture-dir-unset\)/); + } finally { + await runtime.shutdown?.(); + } +}); + +function failedRequest(url: string): unknown { + return { + type: 'complete', + sequence: 1, + requestId: 'req-1', + data: { + startedDateTime: new Date(0).toISOString(), + time: 0, + request: { method: 'GET', url, httpVersion: 'HTTP/1.1', headers: [], cookies: [] }, + response: { status: 0, statusText: '', httpVersion: '', headers: [], cookies: [] }, + cache: {}, + timings: { send: 0, wait: 0, receive: 0 }, + _limrun: { tunnelId: 't1', selectorId: 's1', error: 'client_dial_failed' }, + }, + }; +} + +function androidLease(leaseId: string): DeviceLease { + return { leaseId, tenantId: 'team-a', runId: 'run-a', @@ -196,7 +346,13 @@ async function allocateAndroidDevice( heartbeatAt: 1, expiresAt: 60_001, }; - const allocation = await runtime.leaseLifecycle.allocate?.(lease); +} + +async function allocateAndroidDevice( + runtime: ReturnType, + leaseId = 'lease-appstate', +): Promise { + const allocation = await runtime.leaseLifecycle.allocate?.(androidLease(leaseId)); const device = allocation?.device; if (!device || typeof device !== 'object') throw new Error('Expected allocated device'); return device as DeviceInfo; diff --git a/packages/provider-limrun/src/runtime.ts b/packages/provider-limrun/src/runtime.ts index 52ad6b6536..ad9189b840 100644 --- a/packages/provider-limrun/src/runtime.ts +++ b/packages/provider-limrun/src/runtime.ts @@ -51,6 +51,17 @@ import { resolveLimrunRuntimeInstance } from './runtime-instance.ts'; import type { LimrunRequestOperationDrain } from './request-cancellation.ts'; import type { LimrunAppAsset } from './app-catalog.ts'; import type { LimrunInstanceAccess } from './instance-access.ts'; +import type { + CloudArtifactProvider, + CloudArtifactsQuery, + CloudArtifactsResult, +} from '@agent-device/contracts/observability'; +import type { + LimrunHarCapture, + LimrunHarCaptureFailure, + LimrunTunnelFailureReport, +} from './network-har.ts'; +import path from 'node:path'; type LimrunRuntimeSession = LimrunIosSession | LimrunAndroidSession; @@ -64,6 +75,11 @@ export type LimrunRuntimeOptions = { keepAlive?: boolean; runtimeInstance?: string; instances?: LimrunInstanceAccess; + /** + * Where `--provider-network-logs` writes each session's live HAR file. The composition root + * resolves it under the daemon state dir; without it the opt-in reports a typed refusal. + */ + networkHarDir?: string; }; export type LimrunRuntime = ProviderDeviceRuntime & { @@ -108,6 +124,8 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { private readonly limrun: Limrun | undefined; private readonly sessions = new Map(); private readonly keepAliveTimers = new Map(); + /** Each lease's `--provider-network-logs` capture: live, stopped at release, or never started. */ + private readonly networkCaptures = new Map(); private readonly appAliases = new Map< string, Readonly<{ assetName: string; installedAppId: string }> @@ -256,14 +274,36 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { // ahead of attach as well as create, since an attached instance reads none of them either. rejectRefusedLimrunProfileFields(context); const existing = this.sessions.get(lease.leaseId); - if (existing) return { limrunInstanceId: existing.instanceId, device: existing.device }; + if (existing) { + // A repeat allocation can opt into the capture the first one did not ask for, or retry one + // that could not start. + const networkHar = + context?.flags?.providerNetworkLogs === true && + (this.networkCaptures.get(lease.leaseId)?.phase ?? 'unavailable') === 'unavailable' + ? await this.startNetworkCapture(lease, existing, context) + : undefined; + return { + limrunInstanceId: existing.instanceId, + device: existing.device, + ...(networkHar ? { networkHar } : {}), + }; + } const session = (await this.attachSession(platform, lease)) ?? (await this.createSession(platform, lease, context)); this.sessions.set(lease.leaseId, session); if (this.options.keepAlive) this.startKeepAlive(lease.leaseId, session); - return { limrunInstanceId: session.instanceId, device: session.device }; + const networkHar = + context?.flags?.providerNetworkLogs === true + ? await this.startNetworkCapture(lease, session, context) + : undefined; + return { + limrunInstanceId: session.instanceId, + providerSessionId: session.instanceId, + device: session.device, + ...(networkHar ? { networkHar } : {}), + }; } private async attachSession( @@ -350,12 +390,103 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { private async release(lease: DeviceLease): Promise | undefined> { const session = this.sessions.get(lease.leaseId); if (!session) return await this.releaseRecoveredSession(lease); + // A retry after a failed termination finds the capture already stopped and reports it again. + const networkCapture = await this.stopNetworkCapture(lease.leaseId); await this.terminateSession(session); this.sessions.delete(lease.leaseId); this.appAliases.delete(lease.leaseId); - return { limrunInstanceId: session.instanceId }; + return { + limrunInstanceId: session.instanceId, + providerSessionId: session.instanceId, + ...(networkCapture ? { cloudArtifacts: networkCaptureArtifacts(networkCapture) } : {}), + }; } + /** + * `--provider-network-logs`: opens the instance's one destination tunnel with inspection and + * keeps a live HAR file under the state dir. The Metro/companion route rides this tunnel. + */ + private async startNetworkCapture( + lease: DeviceLease, + session: LimrunRuntimeSession, + context?: LeaseLifecycleContext, + ): Promise> { + const instanceId = session.instanceId; + const harDir = this.options.networkHarDir; + const result = harDir + ? await import('./network-har.ts').then(({ startLimrunHarCapture }) => + startLimrunHarCapture(session.client, { + // One file per lease: an attached instance serves many sessions. + harPath: path.join(harDir, `${instanceId}-${fileSafe(lease.leaseId)}.har`), + selectors: readProviderNetworkHosts(context?.flags?.providerNetworkHosts), + }), + ) + : ({ + ok: false, + reason: 'capture-dir-unset', + message: 'The runtime has no directory for network capture files.', + } as const); + await this.forgetStoppedNetworkCaptures(); + if (!result.ok) { + const { reason, message } = result; + this.networkCaptures.set(lease.leaseId, { + phase: 'unavailable', + instanceId, + reason, + message, + }); + return { status: 'unavailable', reason, message }; + } + this.networkCaptures.set(lease.leaseId, { + phase: 'capturing', + instanceId, + capture: result.capture, + }); + return { status: 'capturing', harPath: result.capture.harPath }; + } + + private async stopNetworkCapture(leaseId: string): Promise { + const state = this.networkCaptures.get(leaseId); + if (state?.phase !== 'capturing') return state; + // Read the tunnel's last dial failure while the tunnel is still open. + const failures = await state.capture.failures(); + await state.capture.close(); + const stopped = { + phase: 'stopped', + instanceId: state.instanceId, + harPath: state.capture.harPath, + failures, + } as const; + this.networkCaptures.set(leaseId, stopped); + return stopped; + } + + /** Keeps released captures listable for a while without growing for the daemon's lifetime. */ + private async forgetStoppedNetworkCaptures(): Promise { + const settled = [...this.networkCaptures].filter(([, state]) => state.phase !== 'capturing'); + const { discardLimrunHar } = await import('./network-har.ts'); + for (const [leaseId, state] of settled.slice(0, -SETTLED_NETWORK_CAPTURE_LIMIT)) { + this.networkCaptures.delete(leaseId); + // The file holds raw traffic, so it lives exactly as long as the record that reports it. + if (state.phase === 'stopped') await discardLimrunHar(state.harPath).catch(() => undefined); + } + } + + readonly cloudArtifacts: CloudArtifactProvider = { + listCloudArtifacts: async ( + query: CloudArtifactsQuery, + ): Promise => { + const state = query.leaseId ? this.networkCaptures.get(query.leaseId) : undefined; + if (state?.phase !== 'capturing') return state ? networkCaptureArtifacts(state) : undefined; + return networkCaptureArtifacts({ + phase: 'stopped', + instanceId: state.instanceId, + harPath: state.capture.harPath, + failures: await state.capture.failures(), + }); + }, + }; + private async releaseRecoveredSession( lease: DeviceLease, ): Promise | undefined> { @@ -395,6 +526,13 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { const leaseId = session.lease.leaseId; clearInterval(this.keepAliveTimers.get(leaseId)); this.keepAliveTimers.delete(leaseId); + // A capture rides the instance's one tunnel; close it before the client disconnects. + const networkCapture = this.networkCaptures.get(leaseId); + if (networkCapture?.phase === 'capturing') { + this.networkCaptures.delete(leaseId); + // The client disconnect below ends the tunnel even when its own close fails. + await networkCapture.capture.close().catch(() => undefined); + } session.client.disconnect(); if (session.platform === 'android') await cleanupLimrunAndroidAdbTunnel(session); if (session.ownership === 'attached') return; @@ -545,3 +683,94 @@ function portReverseResult(options: ProviderPortReverseOptions): Record host.trim()) + .filter((host) => host.length > 0); + return hosts.length > 0 ? hosts : undefined; +} + +const SETTLED_NETWORK_CAPTURE_LIMIT = 32; + +type SettledNetworkCapture = + | Readonly<{ + phase: 'stopped'; + instanceId: string; + harPath: string; + failures: LimrunTunnelFailureReport; + }> + | Readonly<{ phase: 'unavailable'; instanceId: string } & LimrunHarCaptureFailure>; + +type NetworkCaptureState = + | SettledNetworkCapture + | Readonly<{ phase: 'capturing'; instanceId: string; capture: LimrunHarCapture }>; + +const NETWORK_ARTIFACT_NAME = 'Network traffic (HAR, live file on the daemon host)'; + +/** + * One HAR file, stated as a provider artifact whose `url` is its path on this host. The tunnel + * failure report rides the artifact's metadata, and its summary is the result's message. A capture + * that never started is an unavailable artifact carrying the typed reason. + */ +function networkCaptureArtifacts(capture: SettledNetworkCapture): CloudArtifactsResult { + if (capture.phase === 'unavailable') { + return { + provider: LIMRUN_PROVIDER, + status: 'unavailable', + providerSessionId: capture.instanceId, + message: `Network capture did not start (${capture.reason}): ${capture.message}`, + cloudArtifacts: [ + { + provider: LIMRUN_PROVIDER, + kind: 'network', + name: NETWORK_ARTIFACT_NAME, + availability: 'unavailable', + metadata: { reason: capture.reason }, + }, + ], + }; + } + const { harPath, instanceId, failures } = capture; + return { + provider: LIMRUN_PROVIDER, + status: 'ready', + providerSessionId: instanceId, + ...(failures.total > 0 || failures.lastDialFailure + ? { message: summarizeTunnelFailures(failures) } + : {}), + cloudArtifacts: [ + { + provider: LIMRUN_PROVIDER, + kind: 'network', + name: NETWORK_ARTIFACT_NAME, + url: harPath, + extension: 'har', + contentType: 'application/json', + availability: 'ready', + metadata: { tunnelFailures: failures }, + }, + ], + }; +} + +function summarizeTunnelFailures(failures: LimrunTunnelFailureReport): string { + const kinds = Object.entries(failures.byKind).map(([kind, entry]) => { + const failure = entry.latest.at(-1); + const endpoint = failure?.host + ? ` ${failure.host}${failure.port ? `:${failure.port}` : ''}` + : ''; + return `${kind} ${entry.count}, latest${endpoint} (${failure?.message})`; + }); + const dial = failures.lastDialFailure + ? [`last dial failure ${failures.lastDialFailure.reason}`] + : []; + return `Network capture failures: ${failures.total}; ${[...kinds, ...dial].join('; ')}`; +} diff --git a/packages/provider-testmu/src/profile-fields.ts b/packages/provider-testmu/src/profile-fields.ts index 07a6eb3511..f547185f2c 100644 --- a/packages/provider-testmu/src/profile-fields.ts +++ b/packages/provider-testmu/src/profile-fields.ts @@ -19,6 +19,8 @@ export const TESTMU_PROFILE_FIELDS: ProviderProfileFieldDeclaration = { providerNetworkProfile: 'refused', providerCustomNetwork: 'refused', providerNoResignApp: 'refused', + providerNetworkLogs: 'refused', + providerNetworkHosts: 'refused', awsProjectArn: 'refused', awsDeviceArn: 'refused', awsAppArn: 'refused', diff --git a/packages/provider-webdriver/src/aws-device-farm.ts b/packages/provider-webdriver/src/aws-device-farm.ts index e4e8706f08..802265db85 100644 --- a/packages/provider-webdriver/src/aws-device-farm.ts +++ b/packages/provider-webdriver/src/aws-device-farm.ts @@ -34,6 +34,8 @@ export const AWS_DEVICE_FARM_PROFILE_FIELDS: ProviderProfileFieldDeclaration = { providerNetworkProfile: 'refused', providerCustomNetwork: 'refused', providerNoResignApp: 'refused', + providerNetworkLogs: 'refused', + providerNetworkHosts: 'refused', awsProjectArn: 'consumed', awsDeviceArn: 'consumed', awsAppArn: 'consumed', diff --git a/packages/provider-webdriver/src/browserstack.ts b/packages/provider-webdriver/src/browserstack.ts index 797576576f..4ae188a3d8 100644 --- a/packages/provider-webdriver/src/browserstack.ts +++ b/packages/provider-webdriver/src/browserstack.ts @@ -39,6 +39,8 @@ export const BROWSERSTACK_PROFILE_FIELDS: ProviderProfileFieldDeclaration = { providerNetworkProfile: 'consumed', providerCustomNetwork: 'consumed', providerNoResignApp: 'consumed', + providerNetworkLogs: 'refused', + providerNetworkHosts: 'refused', awsProjectArn: 'refused', awsDeviceArn: 'refused', awsAppArn: 'refused', diff --git a/packages/provider-webdriver/src/profile-fields.fixtures.ts b/packages/provider-webdriver/src/profile-fields.fixtures.ts index a9afea4594..2acc0b6bed 100644 --- a/packages/provider-webdriver/src/profile-fields.fixtures.ts +++ b/packages/provider-webdriver/src/profile-fields.fixtures.ts @@ -24,6 +24,8 @@ export function consumeAllProfileFields(provider: string): ProviderProfileFieldD providerNetworkProfile: 'consumed', providerCustomNetwork: 'consumed', providerNoResignApp: 'consumed', + providerNetworkLogs: 'consumed', + providerNetworkHosts: 'consumed', awsProjectArn: 'consumed', awsDeviceArn: 'consumed', awsAppArn: 'consumed', diff --git a/packages/remote/src/remote-config-schema.ts b/packages/remote/src/remote-config-schema.ts index 234bbb8509..7189b3a0a0 100644 --- a/packages/remote/src/remote-config-schema.ts +++ b/packages/remote/src/remote-config-schema.ts @@ -78,6 +78,8 @@ export const REMOTE_CONFIG_FIELD_SPECS = [ { key: 'providerNetworkProfile', type: 'string' }, { key: 'providerCustomNetwork', type: 'string' }, { key: 'providerNoResignApp', type: 'boolean' }, + { key: 'providerNetworkLogs', type: 'boolean' }, + { key: 'providerNetworkHosts', type: 'string' }, { key: 'awsProjectArn', type: 'string' }, { key: 'awsDeviceArn', type: 'string' }, { key: 'awsAppArn', type: 'string' }, diff --git a/packages/test-kit/src/plugin.fixtures.ts b/packages/test-kit/src/plugin.fixtures.ts index dea3079ce5..7b65aa248b 100644 --- a/packages/test-kit/src/plugin.fixtures.ts +++ b/packages/test-kit/src/plugin.fixtures.ts @@ -103,6 +103,8 @@ const CONSUMED_PROFILE_FIELDS: Record = { providerNetworkProfile: 'consumed', providerCustomNetwork: 'consumed', providerNoResignApp: 'consumed', + providerNetworkLogs: 'consumed', + providerNetworkHosts: 'consumed', awsProjectArn: 'consumed', awsDeviceArn: 'consumed', awsAppArn: 'consumed', diff --git a/scripts/integration-progress-model.ts b/scripts/integration-progress-model.ts index 1ecbfd6824..23719f2ea5 100644 --- a/scripts/integration-progress-model.ts +++ b/scripts/integration-progress-model.ts @@ -279,6 +279,8 @@ function summarizeProviderScenarioFlagExclusions() { 'providerNetworkProfile', 'providerCustomNetwork', 'providerNoResignApp', + 'providerNetworkLogs', + 'providerNetworkHosts', 'awsProjectArn', 'awsDeviceArn', 'awsAppArn', diff --git a/skills/agent-device/SKILL.md b/skills/agent-device/SKILL.md index 82c2922e4b..2dabf4798c 100644 --- a/skills/agent-device/SKILL.md +++ b/skills/agent-device/SKILL.md @@ -20,3 +20,5 @@ Reaching an off-screen target is one command, not a scroll-and-check loop: `scro Copy refs byte-for-byte: `@e12`, `@e12~s4` — keep the `@` and any `~sN`. Prefer current refs, then `id`/`label`/`role` selectors; coordinates are a last resort. If snapshot reports sparse/AX-unavailable, its refs and selectors are invalid: run `agent-device screenshot`, inspect the image, use coordinates, then retry `snapshot -i` after navigating. Otherwise run `snapshot -i` only when the diff lacks the next target. Error output includes corrective hints; follow them instead of re-planning. Only when the task is specialized (for example gestures, scripting, TV, macOS, remote, or debugging) or a command shape is unclear, run `agent-device help `. `agent-device --help` lists topics, but is not a startup step. + +To capture network traffic on a Limrun session, see `agent-device help remote` or the Limrun docs. diff --git a/src/__tests__/limrun-runtime.test.ts b/src/__tests__/limrun-runtime.test.ts index dec506e77a..58ddae603e 100644 --- a/src/__tests__/limrun-runtime.test.ts +++ b/src/__tests__/limrun-runtime.test.ts @@ -755,7 +755,12 @@ test('Limrun keeps session tracked when release fails so release can be retried' limrunMockState.androidDelete.mockRejectedValueOnce(new Error('temporary delete failure')); await assert.rejects(() => releaseLease(lease), /temporary delete failure/); - assert.deepEqual(await releaseLease(lease), { limrunInstanceId: 'android-instance-1' }); + assert.deepEqual(await releaseLease(lease), { + limrunInstanceId: 'android-instance-1', + // The instance id doubles as the provider session id, so a released session's + // artifacts stay listable by that id. + providerSessionId: 'android-instance-1', + }); } finally { await runtime.shutdown(); } diff --git a/src/builtin-provider-plugins.ts b/src/builtin-provider-plugins.ts index 7698c35348..52708c2b72 100644 --- a/src/builtin-provider-plugins.ts +++ b/src/builtin-provider-plugins.ts @@ -6,6 +6,8 @@ import { } from '@agent-device/provider-webdriver/providers'; import { LIMRUN_ID } from './builtin-provider-ids.ts'; import type { HostEnvironment } from '@agent-device/kernel/source-value'; +import path from 'node:path'; +import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; import { limrunCredentialDeclaration, readLimrunCredentials, @@ -86,7 +88,15 @@ function limrunCandidate(host: HostEnvironment): PluginCandidate { import('./sdk/limrun-runtime-dependencies.ts'), ]); return runtime.createLimrunRuntime( - limrun, + { + ...limrun, + // HAR captures land beside the session files, under the daemon's own state dir. + networkHarDir: path.join( + resolveDaemonPaths(host.env.AGENT_DEVICE_STATE_DIR, { env: host.env, cwd: host.cwd }) + .baseDir, + 'network-har', + ), + }, dependencies.createLimrunRuntimeDependencies(host), { includePlatformModule: true, diff --git a/src/cli.ts b/src/cli.ts index 9973593f07..aa70298093 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -515,6 +515,8 @@ function buildClientConfig(ctx: CliRunContext): AgentDeviceClientConfig { providerNetworkProfile: currentFlags.providerNetworkProfile, providerCustomNetwork: currentFlags.providerCustomNetwork, providerNoResignApp: currentFlags.providerNoResignApp, + providerNetworkLogs: currentFlags.providerNetworkLogs, + providerNetworkHosts: currentFlags.providerNetworkHosts, awsProjectArn: currentFlags.awsProjectArn, awsDeviceArn: currentFlags.awsDeviceArn, awsAppArn: currentFlags.awsAppArn, diff --git a/src/cli/commands/connection.ts b/src/cli/commands/connection.ts index 55d4a3842b..b16e15c223 100644 --- a/src/cli/commands/connection.ts +++ b/src/cli/commands/connection.ts @@ -1,8 +1,5 @@ import type { HostEnvironment } from '@agent-device/kernel/source-value'; -import type { - CloudArtifact, - CloudProviderSessionResult, -} from '@agent-device/contracts/observability'; +import type { CloudProviderSessionResult } from '@agent-device/contracts/observability'; import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; import { resolveRemoteConfigProfile } from '@agent-device/remote/remote-config'; import { @@ -40,6 +37,7 @@ import { stopMetroCleanup, } from './connection-runtime.ts'; import { writeCommandOutput } from './shared.ts'; +import { formatDeliveredArtifactLines } from '../../commands/output/result-serialization.ts'; import { shellQuoteIfNeeded } from '@agent-device/kernel/device-shell'; import type { LeaseBackend } from '@agent-device/kernel/contracts'; import type { CliFlags } from '@agent-device/contracts/command'; @@ -389,7 +387,7 @@ function renderDisconnectOutput( return [ `Disconnected remote session "${session}".`, ...formatProviderReleaseWarnings(providerData), - ...formatReadyArtifactLinks(providerData?.cloudArtifacts?.cloudArtifacts), + ...formatDeliveredArtifactLines(providerData?.cloudArtifacts), ].join('\n'); } @@ -411,13 +409,6 @@ function formatProviderReleaseWarning(warning: unknown): string | undefined { return `Provider release warning${code}: ${entry.message}`; } -function formatReadyArtifactLinks(artifacts: CloudArtifact[] | undefined): string[] { - return (artifacts ?? []) - .filter((artifact) => (artifact.availability ?? 'ready') === 'ready' && artifact.url) - .slice(0, 3) - .map((artifact) => `${artifact.name}: ${artifact.url}`); -} - function readConnectProvider( positionals: string[], env: NodeJS.ProcessEnv, diff --git a/src/cli/connection/limrun-profile.ts b/src/cli/connection/limrun-profile.ts index 2586e6b383..793fd6c5ba 100644 --- a/src/cli/connection/limrun-profile.ts +++ b/src/cli/connection/limrun-profile.ts @@ -66,6 +66,9 @@ function buildLimrunRemoteProfile(options: { platform: flags.platform, target: 'mobile', session: flags.session, + // The capture opt-in is read at lease allocation, so it must survive into later commands. + providerNetworkLogs: flags.providerNetworkLogs, + providerNetworkHosts: flags.providerNetworkHosts, ...readMetroProfileFields(flags), }; } diff --git a/src/cli/parser/__tests__/args-parse-session.test.ts b/src/cli/parser/__tests__/args-parse-session.test.ts index adf7c068ed..abb7b2e5fe 100644 --- a/src/cli/parser/__tests__/args-parse-session.test.ts +++ b/src/cli/parser/__tests__/args-parse-session.test.ts @@ -738,6 +738,7 @@ test('parseArgs recognizes connect device-feature flags and their short aliases' '--network-profile', '4g-lte-advanced-good', '--provider-no-resign-app', + '--provider-network-logs', '--appium-version', '3.2.0', ], @@ -751,6 +752,7 @@ test('parseArgs recognizes connect device-feature flags and their short aliases' assert.equal(parsed.flags.providerLocale, 'Fr'); assert.equal(parsed.flags.providerNetworkProfile, '4g-lte-advanced-good'); assert.equal(parsed.flags.providerNoResignApp, true); + assert.equal(parsed.flags.providerNetworkLogs, true); }); test('parseArgs rejects an orientation the provider cannot start a session in', () => { diff --git a/src/commands/command-flags.ts b/src/commands/command-flags.ts index c139a6a385..88e68938e6 100644 --- a/src/commands/command-flags.ts +++ b/src/commands/command-flags.ts @@ -41,6 +41,8 @@ function buildFlags(options: InternalRequestOptions): CommandFlags { providerNetworkProfile: options.providerNetworkProfile, providerCustomNetwork: options.providerCustomNetwork, providerNoResignApp: options.providerNoResignApp, + providerNetworkLogs: options.providerNetworkLogs, + providerNetworkHosts: options.providerNetworkHosts, awsProjectArn: options.awsProjectArn, awsDeviceArn: options.awsDeviceArn, awsAppArn: options.awsAppArn, diff --git a/src/commands/management/output.test.ts b/src/commands/management/output.test.ts index 210bce03f9..494eb1805d 100644 --- a/src/commands/management/output.test.ts +++ b/src/commands/management/output.test.ts @@ -179,6 +179,34 @@ describe('artifactsCliOutput', () => { }); }); + test('prints the provider message after ready artifacts', () => { + const output = managementCliOutputFormatters.artifacts({ + env: process.env, + input: {}, + result: { + provider: 'limrun', + status: 'ready', + message: 'Network capture failures: 1 (request-failed 1).', + cloudArtifacts: [ + { + provider: 'limrun', + kind: 'network', + name: 'Network traffic', + url: '/tmp/state/network-har/i1.har', + availability: 'ready', + }, + ], + }, + }); + + expect(output.text).toBe( + [ + 'network: Network traffic ready /tmp/state/network-har/i1.har', + 'Network capture failures: 1 (request-failed 1).', + ].join('\n'), + ); + }); + test('prints exact retry command for pending provider sessions', () => { const output = managementCliOutputFormatters.artifacts({ env: process.env, diff --git a/src/commands/management/output.ts b/src/commands/management/output.ts index a69e5cc526..cbee9c2aaa 100644 --- a/src/commands/management/output.ts +++ b/src/commands/management/output.ts @@ -144,7 +144,10 @@ function artifactsCliOutput(result: AgentArtifactsResult): CliOutput { data: result, text: result.cloudArtifacts.length > 0 - ? result.cloudArtifacts.map(formatCloudArtifactLine).join('\n') + ? [ + ...result.cloudArtifacts.map(formatCloudArtifactLine), + ...(result.message ? [result.message] : []), + ].join('\n') : emptyText.join('\n'), }; } diff --git a/src/commands/output/result-serialization.ts b/src/commands/output/result-serialization.ts index 8da274aca5..83107b392f 100644 --- a/src/commands/output/result-serialization.ts +++ b/src/commands/output/result-serialization.ts @@ -9,6 +9,7 @@ import type { CaptureSnapshotResult, SessionCloseResult, } from '@agent-device/contracts/client'; +import type { CloudArtifactsResult } from '@agent-device/contracts/observability'; import { publicSnapshotCaptureAnnotations } from '@agent-device/contracts/capture'; import { isSerialAddressablePlatform } from '@agent-device/kernel/device'; import { successText, withSuccessText } from '@agent-device/kernel/success-text'; @@ -174,6 +175,26 @@ export function serializeCloseResult( session: result.session, ...(result.shutdown ? { shutdown: result.shutdown } : {}), ...('provider' in result && result.provider ? { provider: result.provider } : {}), - ...successText(result.session ? `Closed: ${result.session}` : 'Closed'), + ...successText( + [ + result.session ? `Closed: ${result.session}` : 'Closed', + ...formatDeliveredArtifactLines( + 'provider' in result ? result.provider?.cloudArtifacts : undefined, + ), + ].join('\n'), + ), }; } + +/** The ready provider artifacts a released session left behind, and the provider's note on them. */ +export function formatDeliveredArtifactLines( + cloudArtifacts: CloudArtifactsResult | undefined, +): string[] { + return [ + ...(cloudArtifacts?.cloudArtifacts ?? []) + .filter((artifact) => (artifact.availability ?? 'ready') === 'ready' && artifact.url) + .slice(0, 3) + .map((artifact) => `${artifact.name}: ${artifact.url}`), + ...(cloudArtifacts?.message ? [cloudArtifacts.message] : []), + ]; +} diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 40e8586d81..3bdf6abf2b 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -626,6 +626,7 @@ Limrun direct-device flow: Limrun creates remote iOS simulators and Android emulators only. Do not pass local device selectors such as --udid, --serial, or --device. To drive an existing instance without the API key, set LIM_IOS_INSTANCE_URL and LIM_IOS_INSTANCE_TOKEN, or LIM_ANDROID_INSTANCE_URL, LIM_ANDROID_INSTANCE_TOKEN, and LIM_ANDROID_INSTANCE_ADB_URL, from the instance status before connect. agent-device then never creates or deletes that instance; install, and apps before the first open, still need LIMRUN_API_KEY. Set LIMRUN_KEEP_ALIVE=1 to ping the instance every 30 seconds while a session is open, so an idle session does not hit the Limrun inactivity timeout. It is off by default. + To capture network traffic, connect with --provider-network-logs --provider-network-hosts . artifacts and close print the HAR path and any tunnel failures; the HAR holds raw headers and bodies, and captured traffic exits through the daemon host. agent-device apps agent-device open Example.apk agent-device snapshot -i diff --git a/src/commands/schema/command-overrides.ts b/src/commands/schema/command-overrides.ts index bca09df59b..3fa2a4cfde 100644 --- a/src/commands/schema/command-overrides.ts +++ b/src/commands/schema/command-overrides.ts @@ -107,6 +107,8 @@ const SCHEMA_ONLY_CLI_COMMAND_SCHEMAS = { 'providerNetworkProfile', 'providerCustomNetwork', 'providerNoResignApp', + 'providerNetworkLogs', + 'providerNetworkHosts', 'awsProjectArn', 'awsDeviceArn', 'awsAppArn', diff --git a/src/provider-limrun-credentials.ts b/src/provider-limrun-credentials.ts index bccdc4303c..8458acc489 100644 --- a/src/provider-limrun-credentials.ts +++ b/src/provider-limrun-credentials.ts @@ -7,6 +7,8 @@ export type LimrunCredentials = Readonly<{ region?: string; keepAlive?: boolean; instances?: LimrunInstanceAccess; + /** Directory the `--provider-network-logs` HAR files are written under. */ + networkHarDir?: string; }>; const ACCOUNT_VARS = { apiKey: 'LIMRUN_API_KEY', region: 'LIMRUN_REGION' } as const; diff --git a/website/docs/docs/limrun.md b/website/docs/docs/limrun.md index 98960a776e..c26eb1068f 100644 --- a/website/docs/docs/limrun.md +++ b/website/docs/docs/limrun.md @@ -69,7 +69,7 @@ agent-device disconnect On Android, agent-device connects to Limrun over an ADB tunnel. Snapshots use the Android snapshot helper, installs upload the app through Limrun asset storage, and port reverse runs over ADB, including the usual reverse setup for a local Metro server. -On iOS, agent-device supports app lifecycle commands, snapshots, screenshots, taps, text input, scrolling, the home button, clipboard read and write, app installation, and system alerts. `alert get/wait/accept/dismiss` read the alert from the same element tree as snapshots and dispatch the selected button; a choice is pressed only when its English label states the asked-for action (`Allow`, `Don't Allow`, `Ask App Not to Track`, and similar), so a localized alert is reported but never pressed. For an alert it recognizes, Limrun uses the same English button preferences as local Apple XCTest: `Allow While Using App` outranks `Allow Once`; `Open`, `Done`, and `Confirm…` accept; `Keep Browsing`, `Deny`, and `Skip` dismiss. Equal-ranked choices and unknown labels refuse. Limrun needs at least two actionable buttons to recognize an alert. App-owned dialogs are not system alerts there, so use `snapshot -i` and then `press @ref` or a label selector for the visible control. `open --launch-args` relaunches the app with those arguments through simctl. iOS cannot reverse a remote device port to a local host port, so for Metro use a publicly reachable HTTPS endpoint or bridge URL instead of a local-only address. +On iOS, agent-device supports app lifecycle commands, snapshots, screenshots, taps, text input, scrolling, the home button, clipboard read and write, app installation, and system alerts. `alert get/wait/accept/dismiss` read the alert from the same element tree as snapshots and dispatch the selected button; a choice is pressed only when its English label states the asked-for action (`Allow`, `Don't Allow`, `Ask App Not to Track`, and similar), so a localized alert is reported but never pressed. For an alert it recognizes, Limrun uses the same English button preferences as local Apple XCTest: `Allow While Using App` outranks `Allow Once`; `Open`, `Done`, and `Confirm…` accept; `Keep Browsing`, `Deny`, and `Skip` dismiss. Equal-ranked choices and unknown labels refuse. Limrun needs at least two actionable buttons to recognize an alert. App-owned dialogs are not system alerts there, so use `snapshot -i` and then `press @ref` or a label selector for the visible control. `open --launch-args` relaunches the app with those arguments through simctl. iOS has no `port reverse`: that command is Android-only, because it runs over ADB. iOS still reaches a local Metro. The instance client's destination tunnel routes device `localhost` connections back to this machine, so while that tunnel is open the app reaches a Metro listening on the host. With `agent-device connect limrun --provider-network-logs`, the session opens that tunnel when the device is allocated, usually by the first `open`, and keeps it; see [Capture session network traffic](#capture-session-network-traffic). Otherwise give the app a publicly reachable HTTPS Metro endpoint. On an iPhone, Limrun reports a native tab bar as one empty group. `snapshot` then hit-tests points across the bar and lists the tabs it finds under it, with their labels, frames, and selected state, so you can press a tab by label. If a hit-test fails, takes longer than 1.5 seconds, or the 24 hit-tests a snapshot allows run out before the bar is found, `snapshot` lists the bar without tabs and returns a warning. @@ -77,7 +77,54 @@ On iOS, `settings` supports `appearance`, `permission`, `location`, and `clear-a On iOS, `fill` taps the target, waits for that field to take text-entry focus, and only then types. Apps that never report a globally focused element, such as Flutter forms, still fill and report `textEntryReadiness: "focused-element"`. If the tap does not focus a field, `fill` fails with `text_entry_focus_not_observed` instead of typing into an unknown field. Use `type` to send text to whichever field already has focus. -To drive Limrun only through MCP, see [Use a provider only through MCP](/docs/device-clouds#use-a-provider-only-through-mcp). Limrun returns no provider artifacts, so `artifacts` has nothing to fetch. +To drive Limrun only through MCP, see [Use a provider only through MCP](/docs/device-clouds#use-a-provider-only-through-mcp). For Limrun, `artifacts` lists the network capture file only when you connect with `--provider-network-logs`; otherwise there are no provider artifacts to fetch. + +## Capture session network traffic + +`--provider-network-logs` records the device's HTTP traffic into a HAR 1.2 file on the machine that runs agent-device. The file stays valid while the session runs, so you can read it with `jq` at any point. + +Before you turn it on, know what the capture changes: + +- Captured traffic leaves through the machine that runs agent-device, not the device's own network. Servers see that machine's public IP, each new connection takes longer, and the device loses the captured hosts if agent-device stops. On CI, the traffic leaves from the CI runner. +- The HAR holds raw requests and responses, including headers, cookies, tokens, and bodies. Treat it as a secret: keep it out of logs, bug reports, and build artifacts that others can read. +- Certificate-pinned hosts refuse the connection, and an app that resolves names over DNS-over-HTTPS bypasses the capture. +- HTTPS hosts that don't support HTTP/2 fail to connect while the capture runs. +- Each request and response body is cut to 64 KiB. Once the file would pass 8 MiB, the oldest entries are dropped, and the failure summary reports them as `har-truncated`. + +Pass your app's API hosts with `--provider-network-hosts`, then open the app after you connect: + +```bash +agent-device connect limrun --platform ios --provider-network-logs \ + --provider-network-hosts "api.example.com,*.cdn.example.com,localhost:8081" +agent-device open com.example.app +agent-device artifacts # prints the HAR path +jq -r '.log.entries[] | "\(.response.status) \(.request.method) \(.request.url)"' +agent-device close # prints the HAR path again +agent-device disconnect +``` + +`--provider-network-hosts` takes exact hosts, wildcards such as `*.example.com`, and `localhost:` routes. Keep `localhost:8081`, or your Metro port, in the list when the app loads its bundle from a local Metro server. Without `--provider-network-hosts`, the capture covers every `.com`, `.org`, `.app`, `.net`, `.io`, and `.dev` host plus `localhost:8081`. Operating system traffic then fills most of the file, and hosts under other domains, such as `.co`, `.ai`, or country domains, are not captured. + +The file is `/network-har/-.har`, readable only by your user. `agent-device artifacts` lists it during the session and after `close`. agent-device keeps the files of the 32 most recent captures that have stopped and deletes older ones; files from a daemon that has stopped stay until you delete them. If the capture can't start, for example because a `--provider-network-hosts` entry is not a valid host, `artifacts` reports the network artifact as `unavailable` with the reason. + +### When a request fails or hangs + +A request that can't reach its host still appears in the HAR with status `0`. `artifacts` and `close` also print a failure summary after the HAR path: + +```text +Network capture failures: 9; inspection-error 8, latest bag.itunes.apple.com:443 (terminate app TLS: EOF); request-failed 1, latest api.example.com:443 (tunnel client could not open the destination: client_dial_failed); last dial failure tls_handshake_failed +``` + +- `request-failed`: the request reached the capture, but its host didn't resolve, refused, timed out, or failed the TLS handshake. Check that the machine running agent-device can reach the host. +- `inspection-error`: the capture couldn't read a connection. This is usually a certificate-pinned host. System hosts, such as Apple's, report these in every session. +- `inspection-gap` and `inspection-stream-error`: the HAR misses requests. Reconnect if you need a complete file. +- `har-truncated`: the oldest entries were dropped to keep the file under 8 MiB. Narrow `--provider-network-hosts` to keep more of your app's traffic. +- `har-write-failed`: the file could not be written, so it lags the traffic. Check the free disk space on the machine that runs agent-device. +- `last dial failure`: the reason Limrun reports for the most recent failed connection, such as `dns_not_found`, `connection_refused`, `client_timeout`, or `tls_handshake_failed`. + +Occasionally, requests skip the capture: they are missing from the HAR and from the failure summary. This affects the first request after the device is allocated, or now and then a whole session. If a request you expect is missing, repeat it. If the HAR stays empty while the app makes requests, run `close` and `disconnect`, then connect again. + +`artifacts --json` returns the same report, with counts and the latest failures of each kind, in `data.cloudArtifacts[0].metadata.tunnelFailures`. ## Embed the Node.js runtime @@ -131,4 +178,4 @@ After allocating a lease, call `runtime.getDeviceSession(device)` to get the all ## Get artifacts and troubleshoot -`agent-device artifacts` does not return provider artifacts for Limrun. If `connect` fails, check `LIMRUN_API_KEY` and the optional `LIMRUN_REGION`. For an existing instance, check its URL and token variables, and that the instance is still running. +For Limrun, `agent-device artifacts` lists only the `--provider-network-logs` HAR file. If a page hangs while the capture runs, read the failure summary that `artifacts` prints; see [When a request fails or hangs](#when-a-request-fails-or-hangs). If `connect` fails, check `LIMRUN_API_KEY` and the optional `LIMRUN_REGION`. For an existing instance, check its URL and token variables, and that the instance is still running.