Skip to content

Session Recording and Replay (Recipes)

A session recipe is a declarative, site-agnostic script for a multi-step web flow — log in, open orders, open a specific order — plus the machinery to record one real human pass through that flow and replay it later against a fresh WebView. The whole capability lives in pure Dart under lib/src/session_recipe/, is exported from the umbrella library, and touches native code only through the ordinary controller and cookie-manager APIs. It is the deterministic counterpart to the network-level VCR Cassettes and the WebView Pool: cassettes answer “what did the network say”, recipes answer “what did the user click, in what order, on which page”.

Sources: main.dart, main.dart, README.md

The Three Artifacts and the Seam Between Them

Section titled “The Three Artifacts and the Seam Between Them”

Everything in this feature is a transformation between three artifacts. A recipe definition (SessionRecipe) is authored and bundled with the app; a recording (RecipeRecording) is produced by one human run and persisted by the consuming app; a replay consumes both and produces a ReplayResult. The definition is the only artifact a developer writes by hand — recordings are machine-generated JSON, and the library deliberately ships no storage format, so the app decides where recordings live.

flowchart LR
A["SessionRecipe<br/>authored definition"] -->|RecipeRecorder.maybeCreate| B["RecipeRecorder<br/>live capture"]
B -->|confirmCurrentStep / finish| C["RecipeRecording<br/>JSON artifact"]
C -->|app persistence| D[("App store")]
D -->|load| E["RecipeReplayer"]
A --> E
E -->|ReplayDriver| F["InAppWebViewController<br/>+ CookieManager"]
E --> G["ReplayResult"]

The architectural seam that makes this testable is ReplayDriver, an interface with six operations — restoreCookies, loadUrl, waitForLoad, evaluateJavascript, getUrl, getHtml. InAppWebViewReplayDriver is the production adapter over a real controller; the entire replay loop is written against the interface, so replayWithDriver runs to completion with no WebView at all. SPLIT_MAP.md classifies this whole cluster as the RecipePort capability, with ReplayDriver as the port and InAppWebViewReplayDriver as its adapter.

Sources: recipe_replayer.dart, SPLIT_MAP.md

Artifact Type Authored by Key fields
Definition SessionRecipe Developer id, entryUrl, ordered steps, loggedOutUrlPatterns, loggedOutSelectors, version
Step definition RecipeStepDefinition Developer id, instruction, captureTap, signalPatterns, waitForNetworkIdle
Recording RecipeRecording Recorder id, recipeId, recipeVersion, siteHost, createdAt, steps, session, complete
Per-step capture RecordedStep Recorder stepId, visitedUrls, tapTarget, signals, confirmedAt, pageHtml
Session SessionSnapshot Recorder domain-filtered cookies, capturedAt

Sources: models.dart, models.dart, models.dart

A definition is valid only when it has at least one step and every step id is unique; isValid() is the gate maybeCreate checks before any recorder exists, so an invalid definition fails closed and yields null rather than a half-wired recorder. Step ids are the join key between definition and recording, which is what makes definitions editable after the fact.

final recipe = SessionRecipe(
id: 'hepsiburada-order-detail',
name: 'Order detail',
entryUrl: 'https://www.hepsiburada.com',
steps: [
RecipeStepDefinition(id: 'login', instruction: 'Log in'),
RecipeStepDefinition(
id: 'open-orders',
instruction: 'Open the orders list',
captureTap: true,
signalPatterns: ['/api/orders'],
waitForNetworkIdle: true,
),
],
loggedOutUrlPatterns: ['*/giris*'],
loggedOutSelectors: ['.login-form'],
);

captureTap is the switch that decides whether a step records a replayable DOM action; signalPatterns are case-insensitive substrings matched against request URLs for live feedback only; waitForNetworkIdle adds a bounded quiet period before the tap. loggedOutUrlPatterns and loggedOutSelectors are the session-expiry detectors consulted after every navigation during replay.

Sources: models.dart, models.dart, models_test.dart

Recording is wired entirely through callbacks the InAppWebView widget already exposes, following the same convention as NetworkCaptureManager: maybeCreate builds the recorder plus its internal NavigationTracker, mergeUserScripts composes caller scripts with the tap listener and the tracker’s script, and attach registers the __zikzakRecipeTap__ JavaScript handler.

final recorder = RecipeRecorder.maybeCreate(
recipe: recipe,
onEvent: (event) { /* drive the overlay from TapCaptured / SignalMatched / ... */ },
)!;
InAppWebView(
initialUserScripts: RecipeRecorder.mergeUserScripts(null, recorder),
onWebViewCreated: recorder.attach,
onLoadStart: (_, url) => recorder.onLoadStart(url),
onUpdateVisitedHistory: (_, url, __) => recorder.onUpdateVisitedHistory(url),
onNetworkRequest: (_, req) => recorder.onNetworkRequest(req),
onNetworkResponse: (_, res) => recorder.onNetworkResponse(res),
);

Sources: recipe_recorder.dart, in_app_webview.dart, README.md

Step control is a small state machine. confirmCurrentStep stamps confirmedAt, best-effort snapshots the full page HTML into pageHtml for offline selector validation, and either advances (emitting StepAdvanced) or auto-finishes on the last step. redoCurrentStep replaces the current RecordedStep with a fresh one and clears the dedup timestamp so the same tap can be captured again. finish is idempotent: it snapshots cookies through CookieManager.getAllCookies, filters them to the entry URL’s host tree, marks the recording complete, and emits RecordingFinished.

stateDiagram-v2
[*] --> Step0: maybeCreate
Step0 --> StepN: confirmCurrentStep
StepN --> StepN1: confirmCurrentStep
StepN1 --> Finished: confirmCurrentStep (last)
StepN --> StepN: redoCurrentStep
StepN1 --> StepN1: redoCurrentStep
Finished --> Finished: finish (idempotent)

Sources: recipe_recorder.dart, recipe_recorder.dart

The recorder emits a sealed event stream for live UI feedback — TapCaptured, SignalMatched, UrlVisited, StepAdvanced, RecordingFinished — and all of the underlying handlers (handleTapPayload, onNetworkRequest, onNetworkResponse) are public and WebView-free, which is precisely why the recorder is unit-testable without a platform. Signal matching records the first pattern that matches per request and later backfills statusCode from the response by URL, walking the current step’s signals backwards.

Sources: recipe_recorder.dart, recipe_recorder.dart

This is the part of the feature that carries the real engineering weight, and it is split across two mirrored implementations: tap_listener_js.dart runs in the page, selector_candidate_rules.dart holds the same rules in testable Dart. The in-page listener installs a capture-phase click and touchend listener at document start in all frames, resolves the tapped node to its actionable ancestor (a, button, [role=button], input), ranks candidates, validates them against the live DOM, builds an XPath, and reports the payload through the bridge.

Three details determine replay reliability. First, synthetic events are ignored — event.isTrusted === false drops .click() dispatches from the dialogue dismisser or the replayer, so only real user intent is recorded. Second, candidates are validated in-page at record time: each candidate is run through querySelectorAll, uniquely-matching ones lead, candidates resolving to the tapped element follow, and anything that resolves elsewhere or throws is demoted to the tail. Third, early events are not lost: payloads fired before Dart registers its handler are queued in-page (cap 200) and flushed when the recorder evaluates window.__zikzakRecipeTap__.ready() from attach.

Sources: tap_listener_js.dart, tap_listener_js.dart, tap_listener_js.dart, recipe_recorder.dart

Rank Candidate form Kept when Rationale
1 #id id is not UUID-ish, has no 4+ digit run, no 8+ hex run framework-generated ids churn across sessions
2 a[href="…"], a[href^="…"] anchor with href (JS side only) hrefs distinguish links that share every class
3 [data-testid=…], [data-test=…], other data-* attribute present and non-empty test hooks are the most stable authored signal
4 tag.cls1.cls2 at least one non-utility class survives css-…, sc-…, jss, Mui… and hash-suffixed classes are filtered
5 nth-of-type path always, capped at 3 levels positional last resort

Sources: selector_candidate_rules.dart, selector_candidate_rules.dart, selector_candidates_test.dart

Alongside the CSS list, the listener records a positional XPath anchored at the nearest stable-id ancestor, and a normalized textContent capped at 100 characters. On the Dart side, handleTapPayload applies a 1500 ms duplicate-suppression window: an identical payload (same page URL, text, tag, candidates) inside that window is treated as an accidental double-click or a touchend/click double-fire and dropped, while a different tap on the same step simply replaces the previous one — latest wins.

Sources: tap_listener_js.dart, recipe_recorder.dart, recipe_recorder.dart, recipe_recorder_test.dart

Every model is a plain Dart class with toJson/fromJson and no I/O. The app persists RecipeRecording.toJson() wherever it likes — Hive box, SQLite row, file — keyed by the recording’s id, which the recorder generates as a base-36 microsecond timestamp plus a random suffix. Two backward-compatibility properties are load-bearing: xpath and pageHtml are nullable so recordings made before those captures existed still parse, and version defaults to 1 when absent.

Sources: models.dart, models.dart, recipe_recorder.dart, models_test.dart

Replay restores cookies before the first navigation, then walks the recording’s steps — not the definition’s — so a recording made against an older, shorter recipe still replays; the definition contributes only per-step settings looked up by step id, with a synthetic fallback definition (captureTap: true, no idle wait) for recorded steps the recipe no longer declares.

Sources: recipe_replayer.dart, recipe_replayer.dart, recipe_replayer_test.dart

Entry-URL selection per step is the subtlest rule in the module, and each branch exists because of an observed failure mode. Step 0 always starts from recipe.entryUrl, because a recorded first visitedUrl is typically a mid-OAuth-chain URL with a dead state/code_challenge that hangs a cold run. For a tap step, replay navigates to tapTarget.pageUrl — the page the tap happened on — because visitedUrls already holds the post-tap destination, and tapping there clicks whatever element the selector coincidentally matches on the landing page. Non-tap steps use the first recorded visitedUrl, falling back to the current page URL.

Sources: recipe_replayer.dart, recipe_replayer_test.dart

Tap dispatch is a bounded poll rather than a single shot: _dispatchTap re-evaluates the click snippet every 400 ms until stepTimeout, because replay pages are frequently SPAs still rendering when waitForLoad returns. The injected snippet is text-aware — candidates whose resolved element contains the recorded text are strongly preferred, the first matching candidate is the fallback, then the XPath, then an exact-text scan over a, button, [role=button], input — and it is side-effect free until it actually finds something and calls .click(). Session expiry is checked after navigation and again after a tap, via glob-matched URL patterns (* any run, ? single char, whole-URL anchored) and an optional selector probe.

Sources: recipe_replayer.dart, replay_click_js.dart, recipe_replayer.dart

final result = await RecipeReplayer(
stepTimeout: const Duration(seconds: 30),
networkIdleQuiet: const Duration(seconds: 2),
).replay(
controller: controller,
recipe: recipe,
recording: recording,
onProgress: (p) => overlay.show(p.stepId, p.state), // navigating / tapping / done
untilStepId: 'open-order', // optional early stop
);

Sources: recipe_replayer.dart, models.dart

untilStepId supports partial replays that stop after a named step and return that step’s URL and HTML; an unknown id fails fast with unknown-step before any driver interaction, so no cookies are touched. Replay never throws for expected failures — the default driver’s waitForLoad converts a dead controller into “loaded” and a genuine stall into TimeoutException, which the loop reports as a result.

Sources: recipe_replayer.dart, recipe_replayer.dart, recipe_replayer_test.dart

Status failureReason Trigger completedSteps
success — all recording steps done, or untilStepId reached every step run
sessionExpired session-expired logged-out URL glob or selector matched steps before the failing one
stepFailed navigation-timeout waitForLoad exceeded stepTimeout steps before the failing one
stepFailed no-selector-matched tap unresolved for the whole stepTimeout steps before the failing one
stepFailed unknown-step untilStepId absent from the recording empty, no driver calls

Sources: models.dart, recipe_replayer.dart, recipe_replayer_test.dart

The suite is fast because nothing in it needs a platform: the recorder’s tap and signal handlers are plain Dart, and replay runs against a configurable FakeReplayDriver that logs every interaction. Cover the four axes that actually break in production — dedup semantics, selector ranking, entry-URL selection, and version drift.

Terminal window
cd zikzak_inappwebview
flutter test test/session_recipe/ # models, recorder, replayer, selector rules

Sources: recipe_replayer_test.dart, recipe_replayer_test.dart, selector_candidates_test.dart

Recipes consume two neighbouring capabilities rather than reimplementing them: URL history comes from the injected-script NavigationTracker (see Dialogue Dismisser and Navigation Tracking), and signal matching is fed by the network callbacks that also drive Network Capture, Interception, and Secret Redaction. Cookie snapshots use the shared CookieManager, and cookie/host matching accepts exact domain, parent domain, or subdomain of the site host. For network-level record/replay and pool-based execution, continue to VCR Cassettes and the WebView Pool; for the passkey path that can make a recorded login step unnecessary, see WebAuthn and Passkey Bridge.