From d23f0f750558dc1b70bee6ba75a9b14135cca010 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 24 Oct 2026 20:44:39 +0200 Subject: [PATCH 01/10] feat(limrun): capture session traffic into a live HAR with --provider-network-logs The opt-in opens the instance's one destination tunnel with Limrun's own inspection and rewrites a HAR 1.2 file under the daemon state dir on every completed request, so the artifact stays valid while the session runs and after it. The Metro/companion localhost route rides the same tunnel. The HAR path is reported at allocate, listed by artifacts, and printed at disconnect. --- .../src/flag-definitions-connection.ts | 20 +++ packages/command-registry/src/flag-groups.ts | 2 + packages/contracts/src/client-connection.ts | 2 + packages/contracts/src/cloud-artifacts.ts | 1 + packages/contracts/src/lease-scope.ts | 2 + .../src/provider-profile-fields.test.ts | 2 + .../contracts/src/remote-config-fields.ts | 9 ++ .../handlers/session-doctor-options.ts | 2 + packages/provider-limrun/src/device.ts | 2 + .../provider-limrun/src/network-har.test.ts | 131 ++++++++++++++++++ packages/provider-limrun/src/network-har.ts | 126 +++++++++++++++++ packages/provider-limrun/src/runtime.ts | 130 ++++++++++++++++- .../provider-testmu/src/profile-fields.ts | 2 + .../provider-webdriver/src/aws-device-farm.ts | 2 + .../provider-webdriver/src/browserstack.ts | 2 + .../src/profile-fields.fixtures.ts | 2 + packages/remote/src/remote-config-schema.ts | 2 + packages/test-kit/src/plugin.fixtures.ts | 2 + scripts/integration-progress-model.ts | 2 + skills/agent-device/SKILL.md | 2 + src/builtin-provider-plugins.ts | 9 +- src/cli.ts | 2 + src/cli/connection/limrun-profile.ts | 3 + .../__tests__/args-parse-session.test.ts | 2 + src/commands/command-flags.ts | 2 + src/commands/schema/command-overrides.ts | 2 + src/provider-limrun-credentials.ts | 2 + website/docs/docs/limrun.md | 20 ++- 28 files changed, 481 insertions(+), 6 deletions(-) create mode 100644 packages/provider-limrun/src/network-har.test.ts create mode 100644 packages/provider-limrun/src/network-har.ts diff --git a/packages/command-registry/src/flag-definitions-connection.ts b/packages/command-registry/src/flag-definitions-connection.ts index 4d3aada9c4..493406dc53 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 through the provider tunnel and write it as a live HAR file under the session artifacts; print the path at disconnect. 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 tunnel selectors (exact hosts, wildcards like api.example.com or *.example.com, or localhost: routes) that replace the default public-domain capture', + 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.ts b/packages/daemon/src/sessions/handlers/session-doctor-options.ts index 49ab39dbde..30adbe4703 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', diff --git a/packages/provider-limrun/src/device.ts b/packages/provider-limrun/src/device.ts index 8468e5ae36..e89236cb1b 100644 --- a/packages/provider-limrun/src/device.ts +++ b/packages/provider-limrun/src/device.ts @@ -27,6 +27,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..ef2ca0aa50 --- /dev/null +++ b/packages/provider-limrun/src/network-har.test.ts @@ -0,0 +1,131 @@ +import assert from 'node:assert/strict'; +import { test } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import type { DestinationTunnelInspectionEvent } from '@limrun/api/destination-tunnel-inspection'; +import { DEFAULT_LIMRUN_HAR_SELECTORS, startLimrunHarCapture } from './network-har.ts'; + +function harEntry(url: 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, + }, + response: { + status: 200, + statusText: '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' }, + }, + } as unknown as DestinationTunnelInspectionEvent; +} + +function fakeTunnelClient() { + const started: { + selectors: string[]; + onEvent?: (e: DestinationTunnelInspectionEvent) => void; + }[] = []; + return { + started, + client: { + startTunnel: async (options: { + selectors: string[]; + onInspectionEvent?: (event: DestinationTunnelInspectionEvent) => void; + }) => { + started.push({ selectors: options.selectors, onEvent: options.onInspectionEvent }); + return { + tunnelId: 't1', + close: () => {}, + } as never; + }, + }, + }; +} + +function tempHarPath(): string { + return path.join(fs.mkdtempSync(path.join(os.tmpdir(), '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')); +}); + +test('a completed inspection event lands in a valid HAR document', 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); + emit(harEntry('https://example.com/a')); + emit(harEntry('https://example.com/b')); + + 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); + + result.capture.close(); + const final = JSON.parse(fs.readFileSync(result.capture.harPath, 'utf8')) as { + log: { entries: unknown[] }; + }; + assert.equal(final.log.entries.length, 2); +}); + +test('a tunnel conflict is reported as a typed refusal, not a crash', async () => { + const harPath = tempHarPath(); + const result = await startLimrunHarCapture( + { + startTunnel: async () => { + throw new Error('tunnel already_active for this instance'); + }, + }, + { harPath }, + ); + assert.equal(result.ok, false); + if (result.ok) return; + assert.equal(result.reason, 'tunnel-in-use'); +}); + +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..d7bb5f8bd4 --- /dev/null +++ b/packages/provider-limrun/src/network-har.ts @@ -0,0 +1,126 @@ +import { DestinationTunnelHARAssembler } from '@limrun/api/destination-tunnel-har'; +import { validateDestinationTunnelSelectors } from '@limrun/api/destination-tunnel'; +import type { DestinationTunnelHAREntry } from '@limrun/api/destination-tunnel-har'; +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 prototype Limrun network capture: one destination tunnel with inspection, streamed into a + * live HAR 1.2 file. The file is rewritten on every completed request, so a reader (jq included) + * always sees a valid document, during the session and after it. + * + * 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. + */ + +/** 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 }; + onInspectionEvent?: (event: DestinationTunnelInspectionEvent) => void; + onInspectionError?: (error: Error) => void; + }): Promise; +}>; + +export type LimrunHarCapture = Readonly<{ + harPath: string; + /** Stops inspection and writes the final HAR document. Safe more than once. */ + close(): void; +}>; + +export type LimrunHarCaptureFailure = Readonly<{ + reason: 'tunnel-in-use' | 'tunnel-start-failed'; + 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 entries: DestinationTunnelHAREntry[] = []; + try { + fs.mkdirSync(path.dirname(input.harPath), { recursive: true }); + writeHar(input.harPath, entries); + const assembler = new DestinationTunnelHARAssembler(); + const tunnel = await client.startTunnel({ + selectors, + inspection: { enabled: true, captureBodies: true }, + onInspectionEvent: (event) => { + const completed = assembler.add(event); + if (!completed || event.type !== 'complete') return; + entries.push(completed); + writeHar(input.harPath, entries); + }, + }); + let closed = false; + return { + ok: true, + capture: Object.freeze({ + harPath: input.harPath, + close: () => { + if (closed) return; + closed = true; + tunnel.close(); + writeHar(input.harPath, entries); + }, + }), + }; + } catch (error) { + const message = describe(error); + return { + ok: false, + reason: /already_active/i.test(message) ? 'tunnel-in-use' : 'tunnel-start-failed', + message, + }; + } +} + +function writeHar(harPath: string, entries: readonly DestinationTunnelHAREntry[]): void { + const document = { + log: { + version: '1.2', + creator: { name: 'agent-device limrun-tunnel', version: '1' }, + entries, + }, + }; + // Write-then-rename, so a reader never observes a half-written document. + const tempPath = `${harPath}.tmp`; + fs.writeFileSync(tempPath, `${JSON.stringify(document, null, 1)}\n`); + fs.renameSync(tempPath, harPath); +} + +function describe(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} diff --git a/packages/provider-limrun/src/runtime.ts b/packages/provider-limrun/src/runtime.ts index 52ad6b6536..09ac8e83ac 100644 --- a/packages/provider-limrun/src/runtime.ts +++ b/packages/provider-limrun/src/runtime.ts @@ -51,6 +51,14 @@ 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 } from './network-har.ts'; +import path from 'node:path'; +import os from 'node:os'; type LimrunRuntimeSession = LimrunIosSession | LimrunAndroidSession; @@ -64,6 +72,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 +121,12 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { private readonly limrun: Limrun | undefined; private readonly sessions = new Map(); private readonly keepAliveTimers = new Map(); + /** Live `--provider-network-logs` captures, and the HAR path each released session left behind. */ + private readonly networkCaptures = new Map(); + private readonly releasedNetworkHarPaths = new Map< + string, + Readonly<{ harPath: string; instanceId?: string }> + >(); private readonly appAliases = new Map< string, Readonly<{ assetName: string; installedAppId: string }> @@ -263,7 +282,16 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { (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 +378,75 @@ 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); + const networkHar = 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, + ...(networkHar ? { networkHar } : {}), + ...(networkHar + ? { cloudArtifacts: harArtifacts(session.instanceId, networkHar.harPath) } + : {}), + }; + } + + /** + * `--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 | undefined> { + const harDir = this.options.networkHarDir ?? path.join(os.tmpdir(), 'agent-device-network-har'); + const harPath = path.join(harDir, `${session.instanceId}.har`); + const selectors = readProviderNetworkHosts(context?.flags?.providerNetworkHosts); + const { startLimrunHarCapture } = await import('./network-har.ts'); + const result = await startLimrunHarCapture(session.client, { harPath, selectors }); + if (!result.ok) { + return { + status: 'unavailable', + reason: result.reason, + message: result.message, + harPath, + }; + } + this.networkCaptures.set(lease.leaseId, result.capture); + return { status: 'capturing', harPath }; + } + + private async stopNetworkCapture( + leaseId: string, + ): Promise | undefined> { + const capture = this.networkCaptures.get(leaseId); + if (!capture) return undefined; + this.networkCaptures.delete(leaseId); + capture.close(); + this.releasedNetworkHarPaths.set(leaseId, { + harPath: capture.harPath, + instanceId: this.sessions.get(leaseId)?.instanceId, + }); + return { harPath: capture.harPath }; } + readonly cloudArtifacts: CloudArtifactProvider = { + listCloudArtifacts: async ( + query: CloudArtifactsQuery, + ): Promise => { + if (!query.leaseId) return undefined; + const capture = this.networkCaptures.get(query.leaseId); + if (capture) { + return harArtifacts(this.sessions.get(query.leaseId)?.instanceId, capture.harPath); + } + const released = this.releasedNetworkHarPaths.get(query.leaseId); + if (released) return harArtifacts(released.instanceId, released.harPath); + return undefined; + }, + }; + private async releaseRecoveredSession( lease: DeviceLease, ): Promise | undefined> { @@ -395,6 +486,9 @@ 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. + this.networkCaptures.get(leaseId)?.close(); + this.networkCaptures.delete(leaseId); session.client.disconnect(); if (session.platform === 'android') await cleanupLimrunAndroidAdbTunnel(session); if (session.ownership === 'attached') return; @@ -545,3 +639,35 @@ function portReverseResult(options: ProviderPortReverseOptions): Record host.trim()) + .filter((host) => host.length > 0); + return hosts.length > 0 ? hosts : undefined; +} + +/** One finished HAR file, stated as a provider artifact whose `url` is its path on this host. */ function harArtifacts( + providerSessionId: string | undefined, + harPath: string, +): CloudArtifactsResult { + return { + provider: LIMRUN_PROVIDER, + status: 'ready', + ...(providerSessionId ? { providerSessionId } : {}), + cloudArtifacts: [ + { + provider: LIMRUN_PROVIDER, + kind: 'network', + name: 'Network traffic (HAR, live file on the daemon host)', + url: harPath, + extension: 'har', + contentType: 'application/json', + availability: 'ready', + }, + ], + }; +} 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..6aa314b204 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 debug network traffic on a remote Limrun session, connect with `--provider-network-logs`, open the app after connecting, then read the printed HAR artifact with `jq`. Certificate-pinned hosts fail and DNS-over-HTTPS bypasses the capture. diff --git a/src/builtin-provider-plugins.ts b/src/builtin-provider-plugins.ts index 7698c35348..86d159b4aa 100644 --- a/src/builtin-provider-plugins.ts +++ b/src/builtin-provider-plugins.ts @@ -6,6 +6,7 @@ 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 { limrunCredentialDeclaration, readLimrunCredentials, @@ -86,7 +87,13 @@ function limrunCandidate(host: HostEnvironment): PluginCandidate { import('./sdk/limrun-runtime-dependencies.ts'), ]); return runtime.createLimrunRuntime( - limrun, + { + ...limrun, + // The daemon exports its resolved state dir; HAR captures land beside the session files. + networkHarDir: host.env.AGENT_DEVICE_STATE_DIR + ? path.join(host.env.AGENT_DEVICE_STATE_DIR, 'network-har') + : undefined, + }, 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/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/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..1b19c55550 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. `agent-device connect limrun --provider-network-logs` opens that tunnel for the session and keeps it; see the next section. 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,21 @@ 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). Limrun returns no provider artifacts, so `artifacts` has nothing to fetch, apart from the HAR file below. + +## Capture session network traffic + +To debug network remotely, connect with `--provider-network-logs`, open the app after connecting, then read the HAR artifact with `jq`. The flag asks Limrun's own tunnel inspection to record every completed request, and agent-device rewrites the HAR file after each one, so the file is valid while the session runs: + +```bash +agent-device connect limrun --platform ios --provider-network-logs +agent-device open com.example.app +agent-device close +agent-device disconnect # prints the HAR path +jq '.log.entries | length' +``` + +The path is `/network-har/.har`. `agent-device artifacts` lists it during the session and after `disconnect`, while the daemon still knows the session. The file holds raw traffic, including headers and bodies. By default the capture covers the public TLD wildcards plus the `localhost:8081` Metro route; `--provider-network-logs --provider-network-hosts "api.example.com,*.example.net,localhost:19000"` replaces that list with your own exact hosts, wildcards, or `localhost:` routes. Note: certificate-pinned hosts fail, and DNS-over-HTTPS bypasses capture. ## Embed the Node.js runtime @@ -131,4 +145,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. +`agent-device artifacts` does not return provider artifacts for Limrun, apart from the `--provider-network-logs` HAR file described above. 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. From 8b483e015db06eaa79392bf464bd6b5cf9384568 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sat, 24 Oct 2026 20:50:12 +0200 Subject: [PATCH 02/10] feat(cli): print delivered provider artifacts when a session closes --- packages/provider-limrun/src/network-har.test.ts | 4 ++-- src/__tests__/limrun-runtime.test.ts | 7 ++++++- src/commands/output/result-serialization.ts | 13 ++++++++++++- 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/packages/provider-limrun/src/network-har.test.ts b/packages/provider-limrun/src/network-har.test.ts index ef2ca0aa50..d290319db3 100644 --- a/packages/provider-limrun/src/network-har.test.ts +++ b/packages/provider-limrun/src/network-har.test.ts @@ -1,9 +1,9 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; import fs from 'node:fs'; -import os from 'node:os'; import path from 'node:path'; import type { DestinationTunnelInspectionEvent } from '@limrun/api/destination-tunnel-inspection'; +import { mkdtempForTestSync } from './tmp-dir.fixtures.ts'; import { DEFAULT_LIMRUN_HAR_SELECTORS, startLimrunHarCapture } from './network-har.ts'; function harEntry(url: string): DestinationTunnelInspectionEvent { @@ -65,7 +65,7 @@ function fakeTunnelClient() { } function tempHarPath(): string { - return path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'limrun-har-')), 'session', 'har.har'); + return path.join(mkdtempForTestSync('limrun-har-'), 'session', 'har.har'); } test('the default capture selectors carry the public wildcards and the Metro route', () => { 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/commands/output/result-serialization.ts b/src/commands/output/result-serialization.ts index 8da274aca5..315be35f5c 100644 --- a/src/commands/output/result-serialization.ts +++ b/src/commands/output/result-serialization.ts @@ -170,10 +170,21 @@ function serializeOpenSessionPaths(result: AppOpenResult): Record { + const artifacts = + 'provider' in result + ? (result.provider?.cloudArtifacts?.cloudArtifacts ?? []).filter( + (artifact) => (artifact.availability ?? 'ready') === 'ready' && artifact.url, + ) + : []; return { 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', + ...artifacts.slice(0, 3).map((artifact) => `${artifact.name}: ${artifact.url}`), + ].join('\n'), + ), }; } From 9be3c788798e95d6f1c608e669b36967fcf6d71e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 29 Oct 2026 11:00:52 +0100 Subject: [PATCH 03/10] feat(limrun): report network capture tunnel failures in artifacts and close The SDK logs per-connection dial failures only to the console, so a hung page under --provider-network-logs left no trace an agent could read. The capture now records the typed inspection failures (failed requests with host and port, inspection errors, stream gaps) per kind, reads the tunnel's last typed dial failure, and reports them in the HAR artifact metadata and as the artifacts/close summary. A tunnel conflict is now classified by the SDK's typed session error code instead of its message text. Docs state that captured traffic exits through the agent-device host, that the HAR is sensitive, that hosts without HTTP/2 fail under capture, and that agents should pass --provider-network-hosts. Co-Authored-By: Claude Opus 5.5 --- .../src/flag-definitions-connection.ts | 4 +- .../provider-limrun/src/network-har.test.ts | 130 ++++++++++++- packages/provider-limrun/src/network-har.ts | 184 +++++++++++++++++- packages/provider-limrun/src/runtime.ts | 70 ++++--- skills/agent-device/SKILL.md | 2 +- src/cli/commands/connection.ts | 1 + src/commands/management/output.test.ts | 28 +++ src/commands/management/output.ts | 5 +- src/commands/output/result-serialization.ts | 11 +- website/docs/docs/limrun.md | 46 ++++- 10 files changed, 428 insertions(+), 53 deletions(-) diff --git a/packages/command-registry/src/flag-definitions-connection.ts b/packages/command-registry/src/flag-definitions-connection.ts index 493406dc53..9d3cdf8465 100644 --- a/packages/command-registry/src/flag-definitions-connection.ts +++ b/packages/command-registry/src/flag-definitions-connection.ts @@ -309,7 +309,7 @@ export const CONNECTION_FLAG_DEFINITIONS: readonly FlagDefinition[] = [ type: 'boolean', usageLabel: '--provider-network-logs', usageDescription: - 'Limrun: capture session network traffic through the provider tunnel and write it as a live HAR file under the session artifacts; print the path at disconnect. Certificate-pinned hosts fail and DNS-over-HTTPS bypasses the capture', + 'Limrun: capture session network traffic into a live HAR file on this host; artifacts and close print its path and any tunnel failures. Captured traffic exits through this host, the HAR holds raw headers and bodies, certificate-pinned hosts fail, and DNS-over-HTTPS bypasses the capture', projectConfig: false, recorded: false, }, @@ -319,7 +319,7 @@ export const CONNECTION_FLAG_DEFINITIONS: readonly FlagDefinition[] = [ type: 'string', usageLabel: '--provider-network-hosts ', usageDescription: - 'With --provider-network-logs: comma-separated tunnel selectors (exact hosts, wildcards like api.example.com or *.example.com, or localhost: routes) that replace the default public-domain capture', + '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, }, diff --git a/packages/provider-limrun/src/network-har.test.ts b/packages/provider-limrun/src/network-har.test.ts index d290319db3..2cf9e6ad14 100644 --- a/packages/provider-limrun/src/network-har.test.ts +++ b/packages/provider-limrun/src/network-har.test.ts @@ -3,10 +3,11 @@ import { test } 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, startLimrunHarCapture } from './network-har.ts'; -function harEntry(url: string): DestinationTunnelInspectionEvent { +function harEntry(url: string, error?: string): DestinationTunnelInspectionEvent { return { type: 'complete', sequence: 1, @@ -37,15 +38,21 @@ function harEntry(url: string): DestinationTunnelInspectionEvent { }, cache: {}, timings: { send: 0, wait: 10, receive: 2 }, - _limrun: { tunnelId: 't1', selectorId: 's1' }, + _limrun: { tunnelId: 't1', selectorId: 's1', ...(error ? { error } : {}) }, }, } as unknown as DestinationTunnelInspectionEvent; } -function fakeTunnelClient() { +function fakeTunnelClient(lastDialFailure?: { + tunnelId: string; + selectorId: string; + reason: string; + osCode?: string; +}) { const started: { selectors: string[]; onEvent?: (e: DestinationTunnelInspectionEvent) => void; + onError?: (error: Error) => void; }[] = []; return { started, @@ -53,13 +60,20 @@ function fakeTunnelClient() { startTunnel: async (options: { selectors: string[]; onInspectionEvent?: (event: DestinationTunnelInspectionEvent) => void; + onInspectionError?: (error: Error) => void; }) => { - started.push({ selectors: options.selectors, onEvent: options.onInspectionEvent }); + started.push({ + selectors: options.selectors, + onEvent: options.onInspectionEvent, + onError: options.onInspectionError, + }); return { tunnelId: 't1', + selectors: [{ id: 's1', kind: 'domain', value: '*.com' }], close: () => {}, } as never; }, + getTunnelStatus: async () => (lastDialFailure ? { lastDialFailure } : {}), }, }; } @@ -98,21 +112,123 @@ test('a completed inspection event lands in a valid HAR document', async () => { assert.equal(final.log.entries.length, 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. + const document = JSON.parse(fs.readFileSync(result.capture.harPath, 'utf8')) as { + log: { entries: unknown[] }; + }; + assert.equal(document.log.entries.length, 2); + result.capture.close(); +}); + +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'); + 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); + result.capture.close(); +}); + test('a tunnel conflict is reported as a typed refusal, not a crash', async () => { - const harPath = tempHarPath(); const result = await startLimrunHarCapture( { startTunnel: async () => { - throw new Error('tunnel already_active for this instance'); + throw new DestinationTunnelSessionError('already_active'); }, }, - { harPath }, + { 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( diff --git a/packages/provider-limrun/src/network-har.ts b/packages/provider-limrun/src/network-har.ts index d7bb5f8bd4..f1e405d842 100644 --- a/packages/provider-limrun/src/network-har.ts +++ b/packages/provider-limrun/src/network-har.ts @@ -1,5 +1,7 @@ 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 { DestinationTunnelHAREntry } from '@limrun/api/destination-tunnel-har'; import type { DestinationTunnelInspectionEvent } from '@limrun/api/destination-tunnel-inspection'; import type { DestinationTcpTunnel } from '@limrun/api/destination-tunnel-dialer'; @@ -16,7 +18,13 @@ import path from 'node:path'; * 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. + * 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. */ @@ -38,12 +46,73 @@ export type LimrunHarTunnelClient = Readonly<{ 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. + */ +export type LimrunTunnelFailureKind = + | 'request-failed' + | 'inspection-error' + | 'inspection-gap' + | 'inspection-stream-error'; + +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; + export type LimrunHarCapture = Readonly<{ harPath: string; /** Stops inspection and writes the final HAR document. Safe more than once. */ close(): void; + /** The failures recorded so far, plus the tunnel's last dial failure while it is open. */ + failures(): Promise; }>; export type LimrunHarCaptureFailure = Readonly<{ @@ -70,6 +139,7 @@ export async function startLimrunHarCapture( return { ok: false, reason: 'tunnel-start-failed', message: describe(error) }; } const entries: DestinationTunnelHAREntry[] = []; + const failures = createFailureRecorder(); try { fs.mkdirSync(path.dirname(input.harPath), { recursive: true }); writeHar(input.harPath, entries); @@ -78,11 +148,15 @@ export async function startLimrunHarCapture( selectors, inspection: { enabled: true, captureBodies: true }, onInspectionEvent: (event) => { + failures.observe(event); const completed = assembler.add(event); if (!completed || event.type !== 'complete') return; entries.push(completed); writeHar(input.harPath, entries); }, + onInspectionError: (error) => { + failures.record('inspection-stream-error', { message: describe(error) }); + }, }); let closed = false; return { @@ -95,18 +169,120 @@ export async function startLimrunHarCapture( tunnel.close(); writeHar(input.harPath, entries); }, + failures: async () => + failures.report( + closed + ? undefined + : await readLastDialFailure(client, tunnel.tunnelId, tunnel.selectors), + ), }), }; } catch (error) { - const message = describe(error); return { ok: false, - reason: /already_active/i.test(message) ? 'tunnel-in-use' : 'tunnel-start-failed', - message, + 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, + ): void => { + total += 1; + const entry = (byKind[kind] ??= { count: 0, latest: [] }); + entry.count += 1; + 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 {}; + } +} + function writeHar(harPath: string, entries: readonly DestinationTunnelHAREntry[]): void { const document = { log: { diff --git a/packages/provider-limrun/src/runtime.ts b/packages/provider-limrun/src/runtime.ts index 09ac8e83ac..beeaa6f204 100644 --- a/packages/provider-limrun/src/runtime.ts +++ b/packages/provider-limrun/src/runtime.ts @@ -56,7 +56,7 @@ import type { CloudArtifactsQuery, CloudArtifactsResult, } from '@agent-device/contracts/observability'; -import type { LimrunHarCapture } from './network-har.ts'; +import type { LimrunHarCapture, LimrunTunnelFailureReport } from './network-har.ts'; import path from 'node:path'; import os from 'node:os'; @@ -123,10 +123,7 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { private readonly keepAliveTimers = new Map(); /** Live `--provider-network-logs` captures, and the HAR path each released session left behind. */ private readonly networkCaptures = new Map(); - private readonly releasedNetworkHarPaths = new Map< - string, - Readonly<{ harPath: string; instanceId?: string }> - >(); + private readonly releasedNetworkCaptures = new Map(); private readonly appAliases = new Map< string, Readonly<{ assetName: string; installedAppId: string }> @@ -378,16 +375,15 @@ 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); - const networkHar = await this.stopNetworkCapture(lease.leaseId); + const networkHar = await this.stopNetworkCapture(lease.leaseId, session.instanceId); await this.terminateSession(session); this.sessions.delete(lease.leaseId); this.appAliases.delete(lease.leaseId); return { limrunInstanceId: session.instanceId, providerSessionId: session.instanceId, - ...(networkHar ? { networkHar } : {}), ...(networkHar - ? { cloudArtifacts: harArtifacts(session.instanceId, networkHar.harPath) } + ? { networkHar: { harPath: networkHar.harPath }, cloudArtifacts: harArtifacts(networkHar) } : {}), }; } @@ -420,16 +416,17 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { private async stopNetworkCapture( leaseId: string, - ): Promise | undefined> { + instanceId: string, + ): Promise { const capture = this.networkCaptures.get(leaseId); if (!capture) return undefined; this.networkCaptures.delete(leaseId); + // Read the tunnel's last dial failure while the tunnel is still open. + const failures = await capture.failures(); capture.close(); - this.releasedNetworkHarPaths.set(leaseId, { - harPath: capture.harPath, - instanceId: this.sessions.get(leaseId)?.instanceId, - }); - return { harPath: capture.harPath }; + const released = { harPath: capture.harPath, instanceId, failures }; + this.releasedNetworkCaptures.set(leaseId, released); + return released; } readonly cloudArtifacts: CloudArtifactProvider = { @@ -439,11 +436,14 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { if (!query.leaseId) return undefined; const capture = this.networkCaptures.get(query.leaseId); if (capture) { - return harArtifacts(this.sessions.get(query.leaseId)?.instanceId, capture.harPath); + return harArtifacts({ + harPath: capture.harPath, + instanceId: this.sessions.get(query.leaseId)?.instanceId, + failures: await capture.failures(), + }); } - const released = this.releasedNetworkHarPaths.get(query.leaseId); - if (released) return harArtifacts(released.instanceId, released.harPath); - return undefined; + const released = this.releasedNetworkCaptures.get(query.leaseId); + return released ? harArtifacts(released) : undefined; }, }; @@ -650,14 +650,23 @@ function readProviderNetworkHosts(value: unknown): readonly string[] | undefined return hosts.length > 0 ? hosts : undefined; } -/** One finished HAR file, stated as a provider artifact whose `url` is its path on this host. */ function harArtifacts( - providerSessionId: string | undefined, - harPath: string, -): CloudArtifactsResult { +type ReleasedNetworkCapture = Readonly<{ + harPath: string; + instanceId?: string; + failures: LimrunTunnelFailureReport; +}>; + +/** + * 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. + */ +function harArtifacts(capture: ReleasedNetworkCapture): CloudArtifactsResult { + const { harPath, instanceId, failures } = capture; return { provider: LIMRUN_PROVIDER, status: 'ready', - ...(providerSessionId ? { providerSessionId } : {}), + ...(instanceId ? { providerSessionId: instanceId } : {}), + ...(failures.total > 0 ? { message: summarizeTunnelFailures(failures) } : {}), cloudArtifacts: [ { provider: LIMRUN_PROVIDER, @@ -667,7 +676,22 @@ function readProviderNetworkHosts(value: unknown): readonly string[] | undefined 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/skills/agent-device/SKILL.md b/skills/agent-device/SKILL.md index 6aa314b204..5d850590c6 100644 --- a/skills/agent-device/SKILL.md +++ b/skills/agent-device/SKILL.md @@ -21,4 +21,4 @@ Copy refs byte-for-byte: `@e12`, `@e12~s4` — keep the `@` and any `~sN`. Prefe 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 debug network traffic on a remote Limrun session, connect with `--provider-network-logs`, open the app after connecting, then read the printed HAR artifact with `jq`. Certificate-pinned hosts fail and DNS-over-HTTPS bypasses the capture. +To debug network traffic on a remote Limrun session, connect with `--provider-network-logs --provider-network-hosts `, open the app after connecting, then read the HAR path that `artifacts` prints with `jq`. If requests fail or hang, read the failure summary that `artifacts` prints. diff --git a/src/cli/commands/connection.ts b/src/cli/commands/connection.ts index 55d4a3842b..7425aafce8 100644 --- a/src/cli/commands/connection.ts +++ b/src/cli/commands/connection.ts @@ -390,6 +390,7 @@ function renderDisconnectOutput( `Disconnected remote session "${session}".`, ...formatProviderReleaseWarnings(providerData), ...formatReadyArtifactLinks(providerData?.cloudArtifacts?.cloudArtifacts), + ...(providerData?.cloudArtifacts?.message ? [providerData.cloudArtifacts.message] : []), ].join('\n'); } 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 315be35f5c..a2524c46bb 100644 --- a/src/commands/output/result-serialization.ts +++ b/src/commands/output/result-serialization.ts @@ -170,12 +170,10 @@ function serializeOpenSessionPaths(result: AppOpenResult): Record { - const artifacts = - 'provider' in result - ? (result.provider?.cloudArtifacts?.cloudArtifacts ?? []).filter( - (artifact) => (artifact.availability ?? 'ready') === 'ready' && artifact.url, - ) - : []; + const cloudArtifacts = 'provider' in result ? result.provider?.cloudArtifacts : undefined; + const artifacts = (cloudArtifacts?.cloudArtifacts ?? []).filter( + (artifact) => (artifact.availability ?? 'ready') === 'ready' && artifact.url, + ); return { session: result.session, ...(result.shutdown ? { shutdown: result.shutdown } : {}), @@ -184,6 +182,7 @@ export function serializeCloseResult( [ result.session ? `Closed: ${result.session}` : 'Closed', ...artifacts.slice(0, 3).map((artifact) => `${artifact.name}: ${artifact.url}`), + ...(cloudArtifacts?.message ? [cloudArtifacts.message] : []), ].join('\n'), ), }; diff --git a/website/docs/docs/limrun.md b/website/docs/docs/limrun.md index 1b19c55550..c290ab1e8d 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 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. `agent-device connect limrun --provider-network-logs` opens that tunnel for the session and keeps it; see the next section. Otherwise give the app a publicly reachable HTTPS Metro endpoint. +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. `agent-device connect limrun --provider-network-logs` opens that tunnel for the session 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,21 +77,49 @@ 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, apart from the HAR file below. +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 only the network capture file described below. ## Capture session network traffic -To debug network remotely, connect with `--provider-network-logs`, open the app after connecting, then read the HAR artifact with `jq`. The flag asks Limrun's own tunnel inspection to record every completed request, and agent-device rewrites the HAR file after each one, so the file is valid while the session runs: +`--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. + +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 +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 close -agent-device disconnect # prints the HAR path -jq '.log.entries | length' +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`. `agent-device artifacts` lists it during the session and after `close`, while the daemon still runs. + +### 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 ``` -The path is `/network-har/.har`. `agent-device artifacts` lists it during the session and after `disconnect`, while the daemon still knows the session. The file holds raw traffic, including headers and bodies. By default the capture covers the public TLD wildcards plus the `localhost:8081` Metro route; `--provider-network-logs --provider-network-hosts "api.example.com,*.example.net,localhost:19000"` replaces that list with your own exact hosts, wildcards, or `localhost:` routes. Note: certificate-pinned hosts fail, and DNS-over-HTTPS bypasses capture. +- `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. +- `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`. + +`artifacts --json` returns the same report, with counts and the latest failures of each kind, in `cloudArtifacts[0].metadata.tunnelFailures`. ## Embed the Node.js runtime @@ -145,4 +173,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, apart from the `--provider-network-logs` HAR file described above. 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. From ebf0430c1e68aa6089f6f6f71ef75ef384b71435 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 29 Oct 2026 11:15:30 +0100 Subject: [PATCH 04/10] docs(limrun): note that the first request after allocation can skip the capture Co-Authored-By: Claude Opus 5.5 --- website/docs/docs/limrun.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/website/docs/docs/limrun.md b/website/docs/docs/limrun.md index c290ab1e8d..31f2fe1f48 100644 --- a/website/docs/docs/limrun.md +++ b/website/docs/docs/limrun.md @@ -119,6 +119,8 @@ Network capture failures: 9; inspection-error 8, latest bag.itunes.apple.com:443 - `inspection-gap` and `inspection-stream-error`: the HAR misses requests. Reconnect if you need a complete file. - `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`. +The first request after the device is allocated can occasionally skip the capture: it is missing from the HAR and from the failure summary. If the first page or API call you expect is missing, open it again. + `artifacts --json` returns the same report, with counts and the latest failures of each kind, in `cloudArtifacts[0].metadata.tunnelFailures`. ## Embed the Node.js runtime From 9e20c67e1be44e8b379472535659b35edff90dc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 29 Oct 2026 11:22:22 +0100 Subject: [PATCH 05/10] fix(limrun): make a capture that cannot start visible and harden the HAR file A capture that failed to start was dropped with the allocate result, so artifacts reported no provider support at all. Each lease now keeps one capture state (capturing, stopped, unavailable): artifacts and close report an unavailable capture with its typed reason, and a release retry reports the stopped capture again. Completed requests share one coalesced HAR rewrite, a write failure is recorded as har-write-failed, the file is owner-only, and it is named per lease so attached instances do not overwrite each other. The tmpdir fallback is gone; without a capture directory the opt-in refuses with capture-dir-unset. Co-Authored-By: Claude Opus 5.5 --- .../src/flag-definitions-connection.ts | 2 +- .../provider-limrun/src/network-har.test.ts | 30 ++- packages/provider-limrun/src/network-har.ts | 27 ++- packages/provider-limrun/src/runtime.test.ts | 94 +++++++++- packages/provider-limrun/src/runtime.ts | 174 ++++++++++++------ src/cli/commands/connection.ts | 16 +- src/commands/output/result-serialization.ts | 23 ++- website/docs/docs/limrun.md | 2 +- 8 files changed, 267 insertions(+), 101 deletions(-) diff --git a/packages/command-registry/src/flag-definitions-connection.ts b/packages/command-registry/src/flag-definitions-connection.ts index 9d3cdf8465..53456cdcb2 100644 --- a/packages/command-registry/src/flag-definitions-connection.ts +++ b/packages/command-registry/src/flag-definitions-connection.ts @@ -309,7 +309,7 @@ export const CONNECTION_FLAG_DEFINITIONS: readonly FlagDefinition[] = [ type: 'boolean', usageLabel: '--provider-network-logs', usageDescription: - 'Limrun: capture session network traffic into a live HAR file on this host; artifacts and close print its path and any tunnel failures. Captured traffic exits through this host, the HAR holds raw headers and bodies, certificate-pinned hosts fail, and DNS-over-HTTPS bypasses the capture', + 'Limrun: capture session network traffic into a live HAR file on this host; artifacts and close print its path and any tunnel failures. Pass --provider-network-hosts with your app API hosts. Captured traffic exits through this host, the HAR holds raw headers and bodies, certificate-pinned hosts fail, and DNS-over-HTTPS bypasses the capture', projectConfig: false, recorded: false, }, diff --git a/packages/provider-limrun/src/network-har.test.ts b/packages/provider-limrun/src/network-har.test.ts index 2cf9e6ad14..182ec244b2 100644 --- a/packages/provider-limrun/src/network-har.test.ts +++ b/packages/provider-limrun/src/network-har.test.ts @@ -1,5 +1,5 @@ import assert from 'node:assert/strict'; -import { test } from 'vitest'; +import { afterEach, test, vi } from 'vitest'; import fs from 'node:fs'; import path from 'node:path'; import type { DestinationTunnelInspectionEvent } from '@limrun/api/destination-tunnel-inspection'; @@ -88,7 +88,17 @@ test('the default capture selectors carry the public wildcards and the Metro rou assert.ok(DEFAULT_LIMRUN_HAR_SELECTORS.includes('localhost:8081')); }); -test('a completed inspection event lands in a valid HAR document', async () => { +afterEach(() => { + vi.useRealTimers(); +}); + +function readEntryCount(harPath: string): number { + return (JSON.parse(fs.readFileSync(harPath, 'utf8')) as { log: { entries: unknown[] } }).log + .entries.length; +} + +test('completed requests reach the live HAR in one coalesced, owner-only write', async () => { + vi.useFakeTimers(); const fake = fakeTunnelClient(); const harPath = tempHarPath(); const result = await startLimrunHarCapture(fake.client, { harPath }); @@ -98,18 +108,21 @@ test('a completed inspection event lands in a valid HAR document', async () => { assert.ok(emit); emit(harEntry('https://example.com/a')); emit(harEntry('https://example.com/b')); + assert.equal(readEntryCount(harPath), 0); + vi.advanceTimersByTime(250); 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')); result.capture.close(); - const final = JSON.parse(fs.readFileSync(result.capture.harPath, 'utf8')) as { - log: { entries: unknown[] }; - }; - assert.equal(final.log.entries.length, 2); + assert.equal(readEntryCount(harPath), 3); }); test('tunnel failures are counted, with the latest endpoints and the typed dial reason', async () => { @@ -160,11 +173,8 @@ test('tunnel failures are counted, with the latest endpoints and the typed dial selector: '*.com', }); // The failed request stays in the HAR, as a status-0 entry. - const document = JSON.parse(fs.readFileSync(result.capture.harPath, 'utf8')) as { - log: { entries: unknown[] }; - }; - assert.equal(document.log.entries.length, 2); result.capture.close(); + assert.equal(readEntryCount(result.capture.harPath), 2); }); test('inspection errors from pinned hosts do not evict failed requests', async () => { diff --git a/packages/provider-limrun/src/network-har.ts b/packages/provider-limrun/src/network-har.ts index f1e405d842..d32b71f872 100644 --- a/packages/provider-limrun/src/network-har.ts +++ b/packages/provider-limrun/src/network-har.ts @@ -67,12 +67,14 @@ export type LimrunHarTunnelClient = Readonly<{ * 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. */ export type LimrunTunnelFailureKind = | 'request-failed' | 'inspection-error' | 'inspection-gap' - | 'inspection-stream-error'; + | 'inspection-stream-error' + | 'har-write-failed'; export type LimrunTunnelFailure = Readonly<{ at: string; @@ -106,6 +108,8 @@ export type LimrunTunnelFailureReport = Readonly<{ 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; export type LimrunHarCapture = Readonly<{ harPath: string; @@ -116,7 +120,7 @@ export type LimrunHarCapture = Readonly<{ }>; export type LimrunHarCaptureFailure = Readonly<{ - reason: 'tunnel-in-use' | 'tunnel-start-failed'; + reason: 'tunnel-in-use' | 'tunnel-start-failed' | 'capture-dir-unset'; message: string; }>; @@ -141,8 +145,19 @@ export async function startLimrunHarCapture( const entries: DestinationTunnelHAREntry[] = []; const failures = createFailureRecorder(); try { - fs.mkdirSync(path.dirname(input.harPath), { recursive: true }); + // The HAR holds raw traffic, so only the daemon's user may read it. + fs.mkdirSync(path.dirname(input.harPath), { recursive: true, mode: 0o700 }); writeHar(input.harPath, entries); + let pendingWrite: NodeJS.Timeout | undefined; + const flush = (): void => { + clearTimeout(pendingWrite); + pendingWrite = undefined; + try { + writeHar(input.harPath, entries); + } catch (error) { + failures.record('har-write-failed', { message: describe(error) }); + } + }; const assembler = new DestinationTunnelHARAssembler(); const tunnel = await client.startTunnel({ selectors, @@ -152,7 +167,7 @@ export async function startLimrunHarCapture( const completed = assembler.add(event); if (!completed || event.type !== 'complete') return; entries.push(completed); - writeHar(input.harPath, entries); + pendingWrite ??= setTimeout(flush, HAR_WRITE_COALESCE_MS); }, onInspectionError: (error) => { failures.record('inspection-stream-error', { message: describe(error) }); @@ -167,7 +182,7 @@ export async function startLimrunHarCapture( if (closed) return; closed = true; tunnel.close(); - writeHar(input.harPath, entries); + flush(); }, failures: async () => failures.report( @@ -293,7 +308,7 @@ function writeHar(harPath: string, entries: readonly DestinationTunnelHAREntry[] }; // Write-then-rename, so a reader never observes a half-written document. const tempPath = `${harPath}.tmp`; - fs.writeFileSync(tempPath, `${JSON.stringify(document, null, 1)}\n`); + fs.writeFileSync(tempPath, `${JSON.stringify(document, null, 1)}\n`, { mode: 0o600 }); fs.renameSync(tempPath, harPath); } diff --git a/packages/provider-limrun/src/runtime.test.ts b/packages/provider-limrun/src/runtime.test.ts index 343594ddb5..769c3d761d 100644 --- a/packages/provider-limrun/src/runtime.test.ts +++ b/packages/provider-limrun/src/runtime.test.ts @@ -12,6 +12,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 +28,9 @@ const state = vi.hoisted(() => ({ | undefined, disconnect: vi.fn(), tunnelClose: vi.fn(), + androidDelete: vi.fn(async () => undefined), + inspectionEvents: [] as ((event: unknown) => void)[], + destinationTunnelClose: vi.fn(), })); vi.mock('@limrun/api', () => ({ @@ -42,7 +46,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 +65,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 () => ({})), })), })); @@ -182,11 +191,76 @@ 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 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 +270,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 beeaa6f204..c7a3acaaa1 100644 --- a/packages/provider-limrun/src/runtime.ts +++ b/packages/provider-limrun/src/runtime.ts @@ -56,9 +56,12 @@ import type { CloudArtifactsQuery, CloudArtifactsResult, } from '@agent-device/contracts/observability'; -import type { LimrunHarCapture, LimrunTunnelFailureReport } from './network-har.ts'; +import type { + LimrunHarCapture, + LimrunHarCaptureFailure, + LimrunTunnelFailureReport, +} from './network-har.ts'; import path from 'node:path'; -import os from 'node:os'; type LimrunRuntimeSession = LimrunIosSession | LimrunAndroidSession; @@ -121,9 +124,8 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { private readonly limrun: Limrun | undefined; private readonly sessions = new Map(); private readonly keepAliveTimers = new Map(); - /** Live `--provider-network-logs` captures, and the HAR path each released session left behind. */ - private readonly networkCaptures = new Map(); - private readonly releasedNetworkCaptures = 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 }> @@ -375,16 +377,15 @@ 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); - const networkHar = await this.stopNetworkCapture(lease.leaseId, session.instanceId); + // 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, providerSessionId: session.instanceId, - ...(networkHar - ? { networkHar: { harPath: networkHar.harPath }, cloudArtifacts: harArtifacts(networkHar) } - : {}), + ...(networkCapture ? { cloudArtifacts: networkCaptureArtifacts(networkCapture) } : {}), }; } @@ -396,54 +397,77 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { lease: DeviceLease, session: LimrunRuntimeSession, context?: LeaseLifecycleContext, - ): Promise | undefined> { - const harDir = this.options.networkHarDir ?? path.join(os.tmpdir(), 'agent-device-network-har'); - const harPath = path.join(harDir, `${session.instanceId}.har`); - const selectors = readProviderNetworkHosts(context?.flags?.providerNetworkHosts); - const { startLimrunHarCapture } = await import('./network-har.ts'); - const result = await startLimrunHarCapture(session.client, { harPath, selectors }); + ): 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); + this.forgetStoppedNetworkCaptures(); if (!result.ok) { - return { - status: 'unavailable', - reason: result.reason, - message: result.message, - harPath, - }; + const { reason, message } = result; + this.networkCaptures.set(lease.leaseId, { + phase: 'unavailable', + instanceId, + reason, + message, + }); + return { status: 'unavailable', reason, message }; } - this.networkCaptures.set(lease.leaseId, result.capture); - return { status: 'capturing', harPath }; + this.networkCaptures.set(lease.leaseId, { + phase: 'capturing', + instanceId, + capture: result.capture, + }); + return { status: 'capturing', harPath: result.capture.harPath }; } - private async stopNetworkCapture( - leaseId: string, - instanceId: string, - ): Promise { - const capture = this.networkCaptures.get(leaseId); - if (!capture) return undefined; - this.networkCaptures.delete(leaseId); + 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 capture.failures(); - capture.close(); - const released = { harPath: capture.harPath, instanceId, failures }; - this.releasedNetworkCaptures.set(leaseId, released); - return released; + const failures = await state.capture.failures(); + 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 forgetStoppedNetworkCaptures(): void { + const settled = [...this.networkCaptures].filter(([, state]) => state.phase !== 'capturing'); + for (const [leaseId] of settled.slice(0, -SETTLED_NETWORK_CAPTURE_LIMIT)) { + this.networkCaptures.delete(leaseId); + } } readonly cloudArtifacts: CloudArtifactProvider = { listCloudArtifacts: async ( query: CloudArtifactsQuery, ): Promise => { - if (!query.leaseId) return undefined; - const capture = this.networkCaptures.get(query.leaseId); - if (capture) { - return harArtifacts({ - harPath: capture.harPath, - instanceId: this.sessions.get(query.leaseId)?.instanceId, - failures: await capture.failures(), - }); - } - const released = this.releasedNetworkCaptures.get(query.leaseId); - return released ? harArtifacts(released) : undefined; + 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(), + }); }, }; @@ -487,8 +511,11 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { clearInterval(this.keepAliveTimers.get(leaseId)); this.keepAliveTimers.delete(leaseId); // A capture rides the instance's one tunnel; close it before the client disconnects. - this.networkCaptures.get(leaseId)?.close(); - this.networkCaptures.delete(leaseId); + const networkCapture = this.networkCaptures.get(leaseId); + if (networkCapture?.phase === 'capturing') { + networkCapture.capture.close(); + this.networkCaptures.delete(leaseId); + } session.client.disconnect(); if (session.platform === 'android') await cleanupLimrunAndroidAdbTunnel(session); if (session.ownership === 'attached') return; @@ -640,6 +667,10 @@ function unsupported(command: string, message: string): never { throw new AppError('UNSUPPORTED_OPERATION', message, { command }); } +function fileSafe(value: string): string { + return value.replaceAll(/[^\w.-]/g, '_'); +} + /** The `--provider-network-hosts` comma list, or undefined to keep the default selectors. */ function readProviderNetworkHosts(value: unknown): readonly string[] | undefined { if (typeof value !== 'string') return undefined; @@ -650,28 +681,57 @@ function readProviderNetworkHosts(value: unknown): readonly string[] | undefined return hosts.length > 0 ? hosts : undefined; } -type ReleasedNetworkCapture = Readonly<{ - harPath: string; - instanceId?: string; - failures: LimrunTunnelFailureReport; -}>; +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. + * 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 harArtifacts(capture: ReleasedNetworkCapture): CloudArtifactsResult { +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', - ...(instanceId ? { providerSessionId: instanceId } : {}), + providerSessionId: instanceId, ...(failures.total > 0 ? { message: summarizeTunnelFailures(failures) } : {}), cloudArtifacts: [ { provider: LIMRUN_PROVIDER, kind: 'network', - name: 'Network traffic (HAR, live file on the daemon host)', + name: NETWORK_ARTIFACT_NAME, url: harPath, extension: 'har', contentType: 'application/json', diff --git a/src/cli/commands/connection.ts b/src/cli/commands/connection.ts index 7425aafce8..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,8 +387,7 @@ function renderDisconnectOutput( return [ `Disconnected remote session "${session}".`, ...formatProviderReleaseWarnings(providerData), - ...formatReadyArtifactLinks(providerData?.cloudArtifacts?.cloudArtifacts), - ...(providerData?.cloudArtifacts?.message ? [providerData.cloudArtifacts.message] : []), + ...formatDeliveredArtifactLines(providerData?.cloudArtifacts), ].join('\n'); } @@ -412,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/commands/output/result-serialization.ts b/src/commands/output/result-serialization.ts index a2524c46bb..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'; @@ -170,10 +171,6 @@ function serializeOpenSessionPaths(result: AppOpenResult): Record { - const cloudArtifacts = 'provider' in result ? result.provider?.cloudArtifacts : undefined; - const artifacts = (cloudArtifacts?.cloudArtifacts ?? []).filter( - (artifact) => (artifact.availability ?? 'ready') === 'ready' && artifact.url, - ); return { session: result.session, ...(result.shutdown ? { shutdown: result.shutdown } : {}), @@ -181,9 +178,23 @@ export function serializeCloseResult( ...successText( [ result.session ? `Closed: ${result.session}` : 'Closed', - ...artifacts.slice(0, 3).map((artifact) => `${artifact.name}: ${artifact.url}`), - ...(cloudArtifacts?.message ? [cloudArtifacts.message] : []), + ...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/website/docs/docs/limrun.md b/website/docs/docs/limrun.md index 31f2fe1f48..df73ac9b73 100644 --- a/website/docs/docs/limrun.md +++ b/website/docs/docs/limrun.md @@ -104,7 +104,7 @@ 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`. `agent-device artifacts` lists it during the session and after `close`, while the daemon still runs. +The file is `/network-har/-.har`, readable only by your user. `agent-device artifacts` lists it during the session and after `close`, while the daemon still runs. 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 From 7de97ba9d31dd475fb6e79e0908281de62801496 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 29 Oct 2026 11:47:32 +0100 Subject: [PATCH 06/10] docs(limrun): a whole session can occasionally skip the capture Co-Authored-By: Claude Opus 5.5 --- website/docs/docs/limrun.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/docs/limrun.md b/website/docs/docs/limrun.md index df73ac9b73..0a1938349b 100644 --- a/website/docs/docs/limrun.md +++ b/website/docs/docs/limrun.md @@ -119,7 +119,7 @@ Network capture failures: 9; inspection-error 8, latest bag.itunes.apple.com:443 - `inspection-gap` and `inspection-stream-error`: the HAR misses requests. Reconnect if you need a complete file. - `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`. -The first request after the device is allocated can occasionally skip the capture: it is missing from the HAR and from the failure summary. If the first page or API call you expect is missing, open it again. +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 `cloudArtifacts[0].metadata.tunnelFailures`. From 31cf8cd1b815987ae41f62a7103abcaf7875074e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 29 Oct 2026 12:50:59 +0100 Subject: [PATCH 07/10] fix(limrun): bound the HAR capture and address review - Bound memory and per-write cost: bodies are cut to 64 KiB by the tunnel and the assembler, each entry is serialized once into a ring capped at 8 MiB, the oldest entries are dropped with a typed har-truncated failure, and writes are async with one in flight through exclusive temp files. - close() is async: it writes the HAR even when the tunnel refuses to close, and a later call retries the tunnel. - A repeat allocation starts the capture it newly asks for; a dial-only failure reaches the summary; a stopped capture's HAR is deleted when its record is evicted. - The capture directory comes from the daemon's resolved state dir, and doctor counts an enabled opt-in boolean as provider scope. - Docs: opt-in artifacts wording, allocation timing, retention, size bounds, the data wrapper, the daemon host in flag help, help remote, and the skill as a one-line pointer. Co-Authored-By: Claude Opus 5.5 --- .../src/flag-definitions-connection.ts | 2 +- .../handlers/session-doctor-options.test.ts | 29 ++++ .../handlers/session-doctor-options.ts | 5 +- packages/provider-limrun/src/device.ts | 5 +- .../provider-limrun/src/network-har.test.ts | 113 ++++++++++--- packages/provider-limrun/src/network-har.ts | 148 +++++++++++++----- packages/provider-limrun/src/runtime.test.ts | 28 +++- packages/provider-limrun/src/runtime.ts | 31 +++- skills/agent-device/SKILL.md | 2 +- src/builtin-provider-plugins.ts | 11 +- src/commands/schema/cli-help.ts | 1 + website/docs/docs/limrun.md | 11 +- 12 files changed, 299 insertions(+), 87 deletions(-) create mode 100644 packages/daemon/src/sessions/handlers/session-doctor-options.test.ts diff --git a/packages/command-registry/src/flag-definitions-connection.ts b/packages/command-registry/src/flag-definitions-connection.ts index 53456cdcb2..eb2e90ff9d 100644 --- a/packages/command-registry/src/flag-definitions-connection.ts +++ b/packages/command-registry/src/flag-definitions-connection.ts @@ -309,7 +309,7 @@ export const CONNECTION_FLAG_DEFINITIONS: readonly FlagDefinition[] = [ type: 'boolean', usageLabel: '--provider-network-logs', usageDescription: - 'Limrun: capture session network traffic into a live HAR file on this host; artifacts and close print its path and any tunnel failures. Pass --provider-network-hosts with your app API hosts. Captured traffic exits through this host, the HAR holds raw headers and bodies, certificate-pinned hosts fail, and DNS-over-HTTPS bypasses the capture', + '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, }, 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 30adbe4703..ea688480fa 100644 --- a/packages/daemon/src/sessions/handlers/session-doctor-options.ts +++ b/packages/daemon/src/sessions/handlers/session-doctor-options.ts @@ -155,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 e89236cb1b..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', diff --git a/packages/provider-limrun/src/network-har.test.ts b/packages/provider-limrun/src/network-har.test.ts index 182ec244b2..99b9c3e401 100644 --- a/packages/provider-limrun/src/network-har.test.ts +++ b/packages/provider-limrun/src/network-har.test.ts @@ -1,13 +1,17 @@ import assert from 'node:assert/strict'; -import { afterEach, test, vi } from 'vitest'; +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, startLimrunHarCapture } from './network-har.ts'; +import { + DEFAULT_LIMRUN_HAR_SELECTORS, + HAR_MAX_BYTES, + startLimrunHarCapture, +} from './network-har.ts'; -function harEntry(url: string, error?: string): DestinationTunnelInspectionEvent { +function harEntry(url: string, error?: string, comment?: string): DestinationTunnelInspectionEvent { return { type: 'complete', sequence: 1, @@ -25,9 +29,11 @@ function harEntry(url: string, error?: string): DestinationTunnelInspectionEvent headersSize: -1, bodySize: 0, }, + ...(comment ? { comment } : {}), response: { - status: 200, - statusText: 'OK', + // 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: [], @@ -43,12 +49,15 @@ function harEntry(url: string, error?: string): DestinationTunnelInspectionEvent } as unknown as DestinationTunnelInspectionEvent; } -function fakeTunnelClient(lastDialFailure?: { - tunnelId: string; - selectorId: string; - reason: string; - osCode?: string; -}) { +function fakeTunnelClient( + lastDialFailure?: { + tunnelId: string; + selectorId: string; + reason: string; + osCode?: string; + }, + tunnelClose: () => void = () => {}, +) { const started: { selectors: string[]; onEvent?: (e: DestinationTunnelInspectionEvent) => void; @@ -70,7 +79,7 @@ function fakeTunnelClient(lastDialFailure?: { return { tunnelId: 't1', selectors: [{ id: 's1', kind: 'domain', value: '*.com' }], - close: () => {}, + close: tunnelClose, } as never; }, getTunnelStatus: async () => (lastDialFailure ? { lastDialFailure } : {}), @@ -88,17 +97,19 @@ test('the default capture selectors carry the public wildcards and the Metro rou assert.ok(DEFAULT_LIMRUN_HAR_SELECTORS.includes('localhost:8081')); }); -afterEach(() => { - vi.useRealTimers(); -}); +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 (JSON.parse(fs.readFileSync(harPath, 'utf8')) as { log: { entries: unknown[] } }).log - .entries.length; + return readEntries(harPath).length; } test('completed requests reach the live HAR in one coalesced, owner-only write', async () => { - vi.useFakeTimers(); const fake = fakeTunnelClient(); const harPath = tempHarPath(); const result = await startLimrunHarCapture(fake.client, { harPath }); @@ -110,7 +121,7 @@ test('completed requests reach the live HAR in one coalesced, owner-only write', emit(harEntry('https://example.com/b')); assert.equal(readEntryCount(harPath), 0); - vi.advanceTimersByTime(250); + await vi.waitFor(() => assert.equal(readEntryCount(harPath), 2)); const document = JSON.parse(fs.readFileSync(harPath, 'utf8')) as { log: { version: string; entries: unknown[] }; }; @@ -121,8 +132,59 @@ test('completed requests reach the live HAR in one coalesced, owner-only write', // Close flushes a request that is still inside the coalescing window. emit(harEntry('https://example.com/c')); - result.capture.close(); + 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); + const large = 'x'.repeat(Math.ceil(HAR_MAX_BYTES / 4)); + 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', + ]); + const report = await result.capture.failures(); + assert.equal(report.byKind['har-truncated']?.count, 3); +}); + +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 () => { @@ -173,8 +235,11 @@ test('tunnel failures are counted, with the latest endpoints and the typed dial selector: '*.com', }); // The failed request stays in the HAR, as a status-0 entry. - result.capture.close(); - assert.equal(readEntryCount(result.capture.harPath), 2); + 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 () => { @@ -197,7 +262,7 @@ test('inspection errors from pinned hosts do not evict failed requests', async ( 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'); - result.capture.close(); + await result.capture.close(); }); test("another tunnel's dial failure is not reported as this capture's", async () => { @@ -208,7 +273,7 @@ test("another tunnel's dial failure is not reported as this capture's", async () const report = await result.capture.failures(); assert.equal(report.total, 0); assert.equal(report.lastDialFailure, undefined); - result.capture.close(); + await result.capture.close(); }); test('a tunnel conflict is reported as a typed refusal, not a crash', async () => { diff --git a/packages/provider-limrun/src/network-har.ts b/packages/provider-limrun/src/network-har.ts index d32b71f872..2839c70d77 100644 --- a/packages/provider-limrun/src/network-har.ts +++ b/packages/provider-limrun/src/network-har.ts @@ -2,16 +2,17 @@ import { DestinationTunnelHARAssembler } from '@limrun/api/destination-tunnel-ha 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 { DestinationTunnelHAREntry } from '@limrun/api/destination-tunnel-har'; 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 prototype Limrun network capture: one destination tunnel with inspection, streamed into a - * live HAR 1.2 file. The file is rewritten on every completed request, so a reader (jq included) - * always sees a valid document, during the session and after it. + * 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 @@ -42,7 +43,7 @@ export const DEFAULT_LIMRUN_HAR_SELECTORS = Object.freeze([ export type LimrunHarTunnelClient = Readonly<{ startTunnel(options: { selectors: string[]; - inspection?: { enabled?: boolean; captureBodies?: boolean }; + inspection?: { enabled?: boolean; captureBodies?: boolean; maxBodyBytes?: number }; onInspectionEvent?: (event: DestinationTunnelInspectionEvent) => void; onInspectionError?: (error: Error) => void; }): Promise; @@ -68,13 +69,16 @@ export type LimrunHarTunnelClient = Readonly<{ * - `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-write-failed' + | 'har-truncated'; export type LimrunTunnelFailure = Readonly<{ at: string; @@ -110,11 +114,18 @@ 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. */ - close(): void; + /** + * 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; }>; @@ -142,47 +153,47 @@ export async function startLimrunHarCapture( } catch (error) { return { ok: false, reason: 'tunnel-start-failed', message: describe(error) }; } - const entries: DestinationTunnelHAREntry[] = []; const failures = createFailureRecorder(); try { // The HAR holds raw traffic, so only the daemon's user may read it. - fs.mkdirSync(path.dirname(input.harPath), { recursive: true, mode: 0o700 }); - writeHar(input.harPath, entries); - let pendingWrite: NodeJS.Timeout | undefined; - const flush = (): void => { - clearTimeout(pendingWrite); - pendingWrite = undefined; - try { - writeHar(input.harPath, entries); - } catch (error) { - failures.record('har-write-failed', { message: describe(error) }); - } - }; - const assembler = new DestinationTunnelHARAssembler(); + await fs.promises.mkdir(path.dirname(input.harPath), { recursive: true, mode: 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) }), + }); + await harFile.flush(); + const assembler = new DestinationTunnelHARAssembler(HAR_BODY_LIMIT_BYTES); + let closed = false; const tunnel = await client.startTunnel({ selectors, - inspection: { enabled: true, captureBodies: true }, + 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') return; - entries.push(completed); - pendingWrite ??= setTimeout(flush, HAR_WRITE_COALESCE_MS); + if (completed && event.type === 'complete') harFile.add(completed); }, onInspectionError: (error) => { failures.record('inspection-stream-error', { message: describe(error) }); }, }); - let closed = false; return { ok: true, capture: Object.freeze({ harPath: input.harPath, - close: () => { + close: async () => { if (closed) return; - closed = true; - tunnel.close(); - flush(); + try { + tunnel.close(); + closed = true; + } finally { + await harFile.flush(); + } }, failures: async () => failures.report( @@ -212,10 +223,11 @@ function createFailureRecorder() { const record = ( kind: LimrunTunnelFailureKind, failure: Omit, + count = 1, ): void => { - total += 1; + total += count; const entry = (byKind[kind] ??= { count: 0, latest: [] }); - entry.count += 1; + entry.count += count; entry.latest.push({ ...failure, at: new Date().toISOString() }); if (entry.latest.length > LATEST_FAILURES_PER_KIND) entry.latest.shift(); }; @@ -298,18 +310,68 @@ function readUrlEndpoint(url: string): Readonly<{ host?: string; port?: number } } } -function writeHar(harPath: string, entries: readonly DestinationTunnelHAREntry[]): void { - const document = { - log: { - version: '1.2', - creator: { name: 'agent-device limrun-tunnel', version: '1' }, - entries, +const HAR_HEADER = + '{"log":{"version":"1.2","creator":{"name":"agent-device limrun-tunnel","version":"1"},"entries":['; + +/** + * 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: string[] = []; + let bytes = 0; + let timer: NodeJS.Timeout | undefined; + let inFlight: Promise | undefined; + let tempSequence = 0; + const write = async (): 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 { + await fs.promises.writeFile(tempPath, `${HAR_HEADER}${entries.join(',')}]}}\n`, { + mode: 0o600, + flag: 'wx', + }); + await fs.promises.rename(tempPath, harPath); + } catch (error) { + hooks.onWriteError(error); + await fs.promises.rm(tempPath, { force: true }).catch(() => undefined); + } + }; + const flush = async (): Promise => { + clearTimeout(timer); + timer = undefined; + while (inFlight) await inFlight; + inFlight = write().finally(() => { + inFlight = undefined; + }); + await inFlight; + }; + return { + flush, + add(entry: unknown): void { + const serialized = JSON.stringify(entry); + entries.push(serialized); + bytes += serialized.length; + let dropped = 0; + while (bytes > HAR_MAX_BYTES && entries.length > 1) { + bytes -= entries.shift()?.length ?? 0; + dropped += 1; + } + if (dropped > 0) hooks.onDropped(dropped); + timer ??= setTimeout(() => void flush(), HAR_WRITE_COALESCE_MS); }, }; - // Write-then-rename, so a reader never observes a half-written document. - const tempPath = `${harPath}.tmp`; - fs.writeFileSync(tempPath, `${JSON.stringify(document, null, 1)}\n`, { mode: 0o600 }); - fs.renameSync(tempPath, harPath); +} + +/** 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 { diff --git a/packages/provider-limrun/src/runtime.test.ts b/packages/provider-limrun/src/runtime.test.ts index 769c3d761d..f67bd628d2 100644 --- a/packages/provider-limrun/src/runtime.test.ts +++ b/packages/provider-limrun/src/runtime.test.ts @@ -31,6 +31,7 @@ const state = vi.hoisted(() => ({ androidDelete: vi.fn(async () => undefined), inspectionEvents: [] as ((event: unknown) => void)[], destinationTunnelClose: vi.fn(), + tunnelStatus: {} as Record, })); vi.mock('@limrun/api', () => ({ @@ -69,7 +70,7 @@ vi.mock('@limrun/api/instance-client', () => ({ state.inspectionEvents.push(options.onInspectionEvent); return { tunnelId: 't1', selectors: [], close: state.destinationTunnelClose }; }), - getTunnelStatus: vi.fn(async () => ({})), + getTunnelStatus: vi.fn(async () => state.tunnelStatus), })), })); @@ -221,6 +222,31 @@ test('a network capture reports its HAR and failures through artifacts and every } }); +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 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'); diff --git a/packages/provider-limrun/src/runtime.ts b/packages/provider-limrun/src/runtime.ts index c7a3acaaa1..b57a2f0ce8 100644 --- a/packages/provider-limrun/src/runtime.ts +++ b/packages/provider-limrun/src/runtime.ts @@ -274,7 +274,18 @@ 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. + const networkHar = + context?.flags?.providerNetworkLogs === true && !this.networkCaptures.has(lease.leaseId) + ? await this.startNetworkCapture(lease, existing, context) + : undefined; + return { + limrunInstanceId: existing.instanceId, + device: existing.device, + ...(networkHar ? { networkHar } : {}), + }; + } const session = (await this.attachSession(platform, lease)) ?? @@ -413,7 +424,7 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { reason: 'capture-dir-unset', message: 'The runtime has no directory for network capture files.', } as const); - this.forgetStoppedNetworkCaptures(); + await this.forgetStoppedNetworkCaptures(); if (!result.ok) { const { reason, message } = result; this.networkCaptures.set(lease.leaseId, { @@ -437,7 +448,7 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { 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(); - state.capture.close(); + await state.capture.close(); const stopped = { phase: 'stopped', instanceId: state.instanceId, @@ -449,10 +460,13 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { } /** Keeps released captures listable for a while without growing for the daemon's lifetime. */ - private forgetStoppedNetworkCaptures(): void { + private async forgetStoppedNetworkCaptures(): Promise { const settled = [...this.networkCaptures].filter(([, state]) => state.phase !== 'capturing'); - for (const [leaseId] of settled.slice(0, -SETTLED_NETWORK_CAPTURE_LIMIT)) { + 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); } } @@ -513,8 +527,9 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { // A capture rides the instance's one tunnel; close it before the client disconnects. const networkCapture = this.networkCaptures.get(leaseId); if (networkCapture?.phase === 'capturing') { - networkCapture.capture.close(); 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); @@ -726,7 +741,9 @@ function networkCaptureArtifacts(capture: SettledNetworkCapture): CloudArtifacts provider: LIMRUN_PROVIDER, status: 'ready', providerSessionId: instanceId, - ...(failures.total > 0 ? { message: summarizeTunnelFailures(failures) } : {}), + ...(failures.total > 0 || failures.lastDialFailure + ? { message: summarizeTunnelFailures(failures) } + : {}), cloudArtifacts: [ { provider: LIMRUN_PROVIDER, diff --git a/skills/agent-device/SKILL.md b/skills/agent-device/SKILL.md index 5d850590c6..2dabf4798c 100644 --- a/skills/agent-device/SKILL.md +++ b/skills/agent-device/SKILL.md @@ -21,4 +21,4 @@ Copy refs byte-for-byte: `@e12`, `@e12~s4` — keep the `@` and any `~sN`. Prefe 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 debug network traffic on a remote Limrun session, connect with `--provider-network-logs --provider-network-hosts `, open the app after connecting, then read the HAR path that `artifacts` prints with `jq`. If requests fail or hang, read the failure summary that `artifacts` prints. +To capture network traffic on a Limrun session, see `agent-device help remote` or the Limrun docs. diff --git a/src/builtin-provider-plugins.ts b/src/builtin-provider-plugins.ts index 86d159b4aa..52708c2b72 100644 --- a/src/builtin-provider-plugins.ts +++ b/src/builtin-provider-plugins.ts @@ -7,6 +7,7 @@ import { 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, @@ -89,10 +90,12 @@ function limrunCandidate(host: HostEnvironment): PluginCandidate { return runtime.createLimrunRuntime( { ...limrun, - // The daemon exports its resolved state dir; HAR captures land beside the session files. - networkHarDir: host.env.AGENT_DEVICE_STATE_DIR - ? path.join(host.env.AGENT_DEVICE_STATE_DIR, 'network-har') - : undefined, + // 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), { 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/website/docs/docs/limrun.md b/website/docs/docs/limrun.md index 0a1938349b..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 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. `agent-device connect limrun --provider-network-logs` opens that tunnel for the session and keeps it; see [Capture session network traffic](#capture-session-network-traffic). Otherwise give the app a publicly reachable HTTPS Metro endpoint. +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,7 @@ 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). For Limrun, `artifacts` lists only the network capture file described below. +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 @@ -89,6 +89,7 @@ Before you turn it on, know what the capture changes: - 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: @@ -104,7 +105,7 @@ 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`, while the daemon still runs. 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. +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 @@ -117,11 +118,13 @@ Network capture failures: 9; inspection-error 8, latest bag.itunes.apple.com:443 - `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 `cloudArtifacts[0].metadata.tunnelFailures`. +`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 From 44b0e2da50ea7baaab7a0cafb887d6c8a7b66e33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 29 Oct 2026 13:29:35 +0100 Subject: [PATCH 08/10] fix(limrun): refuse a capture whose HAR cannot be written, and cap the file in UTF-8 bytes The first publication of the HAR now has to succeed before the tunnel opens, so an unwritable capture path is an unavailable capture instead of a ready artifact pointing at a missing file. The size cap counts UTF-8 bytes plus the document wrapper and commas, and an entry that cannot fit alone is dropped. Co-Authored-By: Claude Opus 5.5 --- .../provider-limrun/src/network-har.test.ts | 19 +++++++++- packages/provider-limrun/src/network-har.ts | 36 ++++++++++++------- 2 files changed, 41 insertions(+), 14 deletions(-) diff --git a/packages/provider-limrun/src/network-har.test.ts b/packages/provider-limrun/src/network-har.test.ts index 99b9c3e401..42ccaf1e54 100644 --- a/packages/provider-limrun/src/network-har.test.ts +++ b/packages/provider-limrun/src/network-har.test.ts @@ -148,7 +148,8 @@ test('the HAR keeps the newest entries under its size cap and reports the droppe if (!result.ok) return; const emit = fake.started[0]?.onEvent; assert.ok(emit); - const large = 'x'.repeat(Math.ceil(HAR_MAX_BYTES / 4)); + // 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)); } @@ -164,10 +165,26 @@ test('the HAR keeps the newest entries under its size cap and reports the droppe '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 capture whose HAR cannot be written refuses before the tunnel opens', async () => { + const fake = fakeTunnelClient(); + const harPath = tempHarPath(); + fs.mkdirSync(path.dirname(harPath), { recursive: true, mode: 0o500 }); + try { + 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); + } finally { + fs.chmodSync(path.dirname(harPath), 0o700); + } +}); + 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, () => { diff --git a/packages/provider-limrun/src/network-har.ts b/packages/provider-limrun/src/network-har.ts index 2839c70d77..daf38c3227 100644 --- a/packages/provider-limrun/src/network-har.ts +++ b/packages/provider-limrun/src/network-har.ts @@ -166,7 +166,8 @@ export async function startLimrunHarCapture( ), onWriteError: (error) => failures.record('har-write-failed', { message: describe(error) }), }); - await harFile.flush(); + // 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({ @@ -312,6 +313,8 @@ function readUrlEndpoint(url: string): Readonly<{ host?: string; port?: number } 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 @@ -322,32 +325,36 @@ function createHarFile( harPath: string, hooks: Readonly<{ onDropped: (count: number) => void; onWriteError: (error: unknown) => void }>, ) { - const entries: string[] = []; - let bytes = 0; + 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; - const write = async (): Promise => { + /** 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 { - await fs.promises.writeFile(tempPath, `${HAR_HEADER}${entries.join(',')}]}}\n`, { + 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) { - hooks.onWriteError(error); await fs.promises.rm(tempPath, { force: true }).catch(() => undefined); + if (required) throw error; + hooks.onWriteError(error); } }; - const flush = async (): Promise => { + const flush = async (required = false): Promise => { clearTimeout(timer); timer = undefined; while (inFlight) await inFlight; - inFlight = write().finally(() => { + inFlight = write(required).finally(() => { inFlight = undefined; }); await inFlight; @@ -355,12 +362,15 @@ function createHarFile( return { flush, add(entry: unknown): void { - const serialized = JSON.stringify(entry); - entries.push(serialized); - bytes += serialized.length; + 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; - while (bytes > HAR_MAX_BYTES && entries.length > 1) { - bytes -= entries.shift()?.length ?? 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); From e812372756f6b6e75a811b0b01cbc571e8f9e7cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 29 Oct 2026 14:06:10 +0100 Subject: [PATCH 09/10] fix(limrun): retry an unavailable capture, tighten an existing capture dir, and pin HAR retention Co-Authored-By: Claude Opus 5.5 --- .../provider-limrun/src/network-har.test.ts | 21 ++++---- packages/provider-limrun/src/network-har.ts | 5 +- packages/provider-limrun/src/runtime.test.ts | 50 +++++++++++++++++++ packages/provider-limrun/src/runtime.ts | 6 ++- 4 files changed, 69 insertions(+), 13 deletions(-) diff --git a/packages/provider-limrun/src/network-har.test.ts b/packages/provider-limrun/src/network-har.test.ts index 42ccaf1e54..d966c11332 100644 --- a/packages/provider-limrun/src/network-har.test.ts +++ b/packages/provider-limrun/src/network-har.test.ts @@ -112,6 +112,8 @@ function readEntryCount(harPath: string): number { 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; @@ -173,16 +175,15 @@ test('the HAR keeps the newest entries under its size cap and reports the droppe test('a capture whose HAR cannot be written refuses before the tunnel opens', async () => { const fake = fakeTunnelClient(); const harPath = tempHarPath(); - fs.mkdirSync(path.dirname(harPath), { recursive: true, mode: 0o500 }); - try { - 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); - } finally { - fs.chmodSync(path.dirname(harPath), 0o700); - } + // 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 () => { diff --git a/packages/provider-limrun/src/network-har.ts b/packages/provider-limrun/src/network-har.ts index daf38c3227..036fa1514e 100644 --- a/packages/provider-limrun/src/network-har.ts +++ b/packages/provider-limrun/src/network-har.ts @@ -156,7 +156,10 @@ export async function startLimrunHarCapture( const failures = createFailureRecorder(); try { // The HAR holds raw traffic, so only the daemon's user may read it. - await fs.promises.mkdir(path.dirname(input.harPath), { recursive: true, mode: 0o700 }); + 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( diff --git a/packages/provider-limrun/src/runtime.test.ts b/packages/provider-limrun/src/runtime.test.ts index f67bd628d2..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'; @@ -247,6 +248,55 @@ test('a repeat allocation starts the capture it newly asks for, and a dial-only } }); +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'); diff --git a/packages/provider-limrun/src/runtime.ts b/packages/provider-limrun/src/runtime.ts index b57a2f0ce8..ad9189b840 100644 --- a/packages/provider-limrun/src/runtime.ts +++ b/packages/provider-limrun/src/runtime.ts @@ -275,9 +275,11 @@ class LimrunRuntimeImplementation implements ProviderDeviceRuntime { rejectRefusedLimrunProfileFields(context); const existing = this.sessions.get(lease.leaseId); if (existing) { - // A repeat allocation can opt into the capture the first one did not ask for. + // 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.has(lease.leaseId) + context?.flags?.providerNetworkLogs === true && + (this.networkCaptures.get(lease.leaseId)?.phase ?? 'unavailable') === 'unavailable' ? await this.startNetworkCapture(lease, existing, context) : undefined; return { From a597bf451e5a59fb840d065adfa66a40d034d037 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Thu, 29 Oct 2026 14:54:06 +0100 Subject: [PATCH 10/10] fix(limrun): refuse a relative HAR path before touching any directory Co-Authored-By: Claude Opus 5.5 --- packages/provider-limrun/src/network-har.test.ts | 9 +++++++++ packages/provider-limrun/src/network-har.ts | 8 ++++++++ 2 files changed, 17 insertions(+) diff --git a/packages/provider-limrun/src/network-har.test.ts b/packages/provider-limrun/src/network-har.test.ts index d966c11332..bb9f2b7d47 100644 --- a/packages/provider-limrun/src/network-har.test.ts +++ b/packages/provider-limrun/src/network-har.test.ts @@ -172,6 +172,15 @@ test('the HAR keeps the newest entries under its size cap and reports the droppe 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(); diff --git a/packages/provider-limrun/src/network-har.ts b/packages/provider-limrun/src/network-har.ts index 036fa1514e..3ca3094fc1 100644 --- a/packages/provider-limrun/src/network-har.ts +++ b/packages/provider-limrun/src/network-har.ts @@ -155,6 +155,14 @@ export async function startLimrunHarCapture( } 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 });