Skip to content

VCR Cassettes and the WebView Pool

This page documents the two load-bearing primitives of the zikzak_inappwebview_module intelligence tier: the WebViewPool, which manages mission-scoped HeadlessInAppWebView instances so parallel agent loops never leak render processes, and the VCR cassette engine, which records live headless traffic into a deterministic, committable artifact and replays it in CI without a network. Both live in the module tier and depend only on the plugin core’s public API — they never touch zikzak_inappwebview_platform_interface internals. The material here is advanced: it assumes familiarity with the Two-Tier Core/Module Split and the Grep Gate and the Headless WebView and the Live-Instance Cap.

Sources: README.md, zikzak_inappwebview_module.dart

Architectural Positioning: The Module Tier

Section titled “Architectural Positioning: The Module Tier”

The module package is the value-add layer that consumes the plugin core exclusively through its public surface — InAppWebView, InAppWebViewController, HeadlessInAppWebView, CookieManager, and the raw capture-event stream. It is organized as a ports-and-services graph: abstract ports define the contracts, concrete services implement them, and plain models carry the data. The pool and the cassette engine are two such services, each bound to a port (WebViewSessionFactory and CassetteEngine respectively) so tests can inject fakes and drive behavior without platform channels. The package is publish_to: none and resolves siblings via dependency_overrides, marking it as a dev-only tier whose zuraffa codegen integration is pending upstream issue #389.

Sources: README.md, pubspec.yaml, webview_session_factory.dart

The following diagram shows how the pool and the cassette engine relate to their ports, the headless instances they manage, and the core-tier cap that bounds them. Read it as a dependency graph: arrows point from a component to the contract or collaborator it relies on.

graph TD
subgraph Module["zikzak_inappwebview_module (intelligence tier)"]
Pool["WebViewPool<br/>(service)"]
VCR["CassetteEngineImpl<br/>(VCR service)"]
FactoryPort["WebViewSessionFactory<br/>(port)"]
CassettePort["CassetteEngine<br/>(port)"]
PoolSession["PoolSession<br/>(model)"]
Cassette["Cassette / CassetteEntry<br/>(model)"]
end
subgraph Core["zikzak_inappwebview (plugin core, public API only)"]
Headless["HeadlessInAppWebView"]
Cap["maxLiveWebViews<br/>(process-wide cap)"]
end
Pool -. implements .-> FactoryPort
VCR -. implements .-> CassettePort
Pool -->|creates & reuses| Headless
Pool -->|wraps in| PoolSession
VCR -->|records / synthesizes| Headless
VCR -->|serializes| Cassette
Pool -->|reads default cap| Cap
Headless --> Cap

Sources: webview_pool.dart, cassette_engine_impl.dart, pool_session.dart

The WebView Pool: Mission-Scoped Session Continuity

Section titled “The WebView Pool: Mission-Scoped Session Continuity”

The central defect the pool exists to fix is state loss and instance leakage when parallel agent missions drive headless web views. The pool keys instances by a caller-supplied sessionId — one handle per mission — not by URL, so a browse → intercept → execute_js → cookies sequence reuses the same underlying HeadlessInAppWebView and preserves its cookies and JS execution context. acquire returns a PoolSession handle wrapping the headless instance together with the InAppWebViewSettings composed at acquisition time; release returns the instance to an idle pool for warm reuse; disposeAll tears everything down and resets liveCount to zero.

Sources: webview_pool.dart, pool_session.dart, spec.md

The pool tracks three storage structures: an _active map keyed by sessionId, a per-eTLD+1 _idle map of most-recently-used-first lists, and a _genericIdle list for hint-less sessions. The acquire routine resolves an instance in a strict priority order — return the already-active session, then a domain-affine idle instance, then a generic idle instance, and only then create a new one under the caps. A subtlety worth noting: when a warm idle instance is reissued under a new sessionId, the pool rewraps it in a fresh PoolSession handle so sessions() reports the new association while the native webview object — and its warm state — survives unchanged.

Sources: webview_pool.dart, webview_pool.dart

Domain affinity is what makes stateful agent sequences work without re-authenticating on every step. When a mission re-acquires for the same effective top-level-domain-plus-one — say app.example.com after shop.example.com — the pool prefers a warm idle instance already scoped to example.com, so cookies and JS context survive the acquisition boundary. The eTLD+1 key is derived by a pragmatic heuristic that splits on dots and takes the last two parts, degrading gracefully to exact-match for IPv4 addresses and localhost rather than throwing. A full public-suffix-list implementation can be swapped in later without changing the affinity contract.

Sources: webview_pool.dart, webview_pool.dart, spec.md

The acceptance suite pins this behavior precisely: an affine acquisition for app.example.com reuses the warm instance scoped to example.com (A5), while a request for other.org must not receive the example.com instance and instead creates a new one (A7). A generic hint-less session released into _genericIdle is later reused by any acquisition (A7, A8).

Sources: webview_pool_test.dart

Caps, TTL Eviction, and Memory-Pressure Disposal

Section titled “Caps, TTL Eviction, and Memory-Pressure Disposal”

The pool enforces three protective limits drawn from WebViewPoolConfig: a maximum number of live instances (active + idle), a maximum per eTLD+1 domain, and an idle TTL after which idle instances are evicted. Defaults are platform-aware — iOS/Android receive a maxPerDomain of 1 and a 180-second TTL because each mobile render process is expensive, macOS gets 2/300s, and desktop/Web get 3/300s — with the live ceiling always drawn from HeadlessInAppWebView.maxLiveWebViews so the Dart pool and the native hard stop stay synchronized.

Sources: webview_pool.dart, headless_in_app_webview.dart

Two ordering guarantees govern eviction. First, the per-domain cap check is pure and runs before any max-live eviction, so a refused acquisition never destroys a warm idle instance to make room it does not need (regression #390). Second, when the live cap is reached and room must be made, the pool evicts the globally oldest idle instance — never an active one — and if nothing is evictable it throws WebViewPoolExhaustedException rather than exceeding the cap (SC-005). A periodic 30-second timer sweeps expired idle instances, and an AppLifecycleListener disposes idle instances first on backgrounding or memory pressure while leaving active sessions intact.

Sources: webview_pool.dart, webview_pool.dart, webview_pool_test.dart

The following table summarizes the platform-aware defaults and the eviction ordering guarantees, which are the two dimensions most likely to surprise a new integrator.

Dimension iOS / Android macOS Web / Linux / Windows
maxLiveInstances HeadlessInAppWebView.maxLiveWebViews (default 3) same (default 5) same (default 8)
maxPerDomain 1 2 3
idleTtlSeconds 180 300 300
Eviction order oldest idle first, active never oldest idle first oldest idle first
Cap exceeded, nothing evictable throw WebViewPoolExhaustedException same same

Sources: webview_pool.dart, headless_in_app_webview.dart

Concurrency Safety and Per-Acquisition Settings

Section titled “Concurrency Safety and Per-Acquisition Settings”

The agent loop fires many tool calls in parallel, so acquire, release, and disposeAll are serialized through a future-chain mutex: each caller appends its critical section after the previous one’s Completer completes, guaranteeing that only one mutation runs at a time. This is what prevents K concurrent acquire calls for the same sessionId from race-creating duplicate instances (A13) and ensures M distinct concurrent acquisitions leave liveCount == M with no aliased instances (A14). Each acquire also accepts caller-provided InAppWebViewSettings that are applied to the issued instance only; a warm reuse carries the new acquisition’s settings into the handle while the native instance keeps the settings it was originally created with, since initialSettings is not retroactive.

Sources: webview_pool.dart, webview_pool_test.dart

VCR Cassettes: Deterministic Record and Replay

Section titled “VCR Cassettes: Deterministic Record and Replay”

The cassette engine is the module’s answer to a CI problem: agent-driven scraping must be regression-testable without live network or real webviews. CassetteEngineImpl wraps a HeadlessInAppWebView and operates in one of two modes through the same public API. In record mode it captures navigations, served HTML, network events, and cookie snapshots; in replay mode it serves recorded HTML and synthesizes network events with zero outbound calls, so downstream distillation logic runs unmodified. Loading a cassette flips the engine into replay mode; saving one snapshots and clears the recorded entries.

Sources: cassette_engine_impl.dart, cassette_engine.dart, spec.md

A Cassette is a versioned artifact carrying a name, a recordedAt timestamp, and an ordered list of CassetteEntry objects. Each entry is keyed by (url, normalizedRequest) and stores the servedHtml, a list of CassetteNetworkEvent records (each a request/response/body pair with headers and status), and a cookieSnapshot. Every model round-trips through JSON via toJson/fromJson, and the format declares cassetteFormatVersion = 1; a loader rejects any cassette whose declared version exceeds the supported maximum with a clear FormatException.

Sources: cassette.dart, cassette.dart, cassette_model_test.dart

replayUrl resolves a URL against the loaded cassette deterministically: first an exact entry.url match, then a best-match prefix fallback (url.startsWith(entry.url)) so minor ordering or header differences still resolve to a stable entry. When nothing matches, the UnmatchedPolicy decides the outcome — hard (the default) throws a StateError naming the unmatched URL, while soft returns null so CI triage can proceed. This two-tier match-then-policy design balances strict reproducibility against day-to-day triage ergonomics.

Sources: cassette_engine_impl.dart, cassette_engine.dart

Redaction, Compression, and Format Versioning

Section titled “Redaction, Compression, and Format Versioning”

Because cassettes are intended to be committed under test/fixtures/, redaction is mandatory at record time. The engine scrubs a fixed set of sensitive header patterns — authorization, cookie, set-cookie, x-api-key, x-auth-token — replacing matching values with [REDACTED], and redacts all cookie values while retaining their keys. Serialization is gzip.encode(utf8.encode(jsonEncode(...))), keeping cassettes small and compressible, and saveCassetteToFile/loadCassetteFromFile wrap the byte streams for on-disk artifacts. A load-bearing implementation detail: saveCassette copies _recordedEntries into a new list before clearing, because an unmodifiable live view would otherwise empty the returned cassette and silently lose the recording.

Sources: cassette_engine_impl.dart, cassette_engine_impl.dart, cassette_engine_impl.dart

The following table contrasts the two engines across the dimensions an integrator actually configures, clarifying that they are complementary primitives rather than competing ones.

Concern WebViewPool CassetteEngineImpl
Primary contract (port) WebViewSessionFactory CassetteEngine
Unit of state PoolSession (per sessionId) CassetteEntry (per URL/request)
Lifecycle driver acquire / release / disposeAll loadCassette / saveCassette
Key axis mission handle + eTLD+1 affinity (URL, normalized request)
Failure mode WebViewPoolExhaustedException on cap UnmatchedPolicy hard/soft on miss
Determinism mechanism warm-instance reuse gzipped, versioned, redacted artifact

Sources: webview_pool.dart, cassette_engine_impl.dart

The two primitives are designed to compose: the pool supplies the deterministic, mission-scoped HeadlessInAppWebView that the cassette engine records against or synthesizes into. A record run drives a pooled headless session against a live page while the engine captures navigations and network events; a replay run in CI loads the committed cassette and serves recorded HTML with no live network, and because the cassette format and matching logic are platform-independent, a cassette recorded on one platform replays identically on any other. The CaptureConfig default maxPayloadSize of 50 KB is the shared body-size cap that keeps recorded response bodies bounded, linking the cassette writer to the module’s capture settings rather than introducing a competing limit.

Sources: spec.md, capture_source.dart, README.md

Having established how the module’s pool and cassette engine manage headless state and deterministic replay, continue with the surrounding intelligence-tier capabilities and their foundations. The capture layer that feeds the cassette engine is documented in Network Capture, Interception, and Secret Redaction, and the recipe-based session recording that builds on these primitives in Session Recording and Replay (Recipes). For the core-tier headless cap that the pool’s platform defaults synchronize with, see Headless WebView and the Live-Instance Cap, and for the architectural boundary that keeps this module honest, revisit Two-Tier Core/Module Split and the Grep Gate.