FlowWitness — Devpost Submission Writeup (#BuildHybridAI 2026)
Live Workbench (firebase-flow-witness.vercel.app) · 42s Demo Film (youtu.be/2H3QmFD4D20) · GitHub Repository · ADR-0001 · ADR-0002
Inspiration
Frontend developers and QA engineers constantly battle two verification failures that existing tools handle poorly:
- Optimistic Persistence Lies ("False Green"): A settings form or toggle flashes a green
"Preferences Saved ✓"toast immediately on click, yet silently writes to the wrong storage key or drops state on reload. - Design-Token Drift Buried in Pixel Noise: Running
pixelmatchacross responsive viewports produces 15–50 changed bounding boxes per screen—over 80% caused by subpixel font anti-aliasing or ticking timestamps. Streaming every full-resolution screenshot and DOM tree to a cloud LLM burns thousands of image tokens, adds multi-second latency, and leaks unreleased UI screens to external servers.
While inspecting the official @firebase/[email protected] ([email protected]) Web SDK source code, we realized that hybrid inference shouldn't just be an "offline fallback when Wi-Fi disconnects." Instead, Chrome's on-device Gemini Nano and Cloud Gemini form a natural Narrow Triage Sieve + Deep Root-Cause Diagnostician pair—provided we solve the real browser constraints around session concurrency, JSON schema serialization, and privacy guards.
What it does
FlowWitness is a browser-native hybrid UI & state verification workbench built on the official Firebase AI Logic Web SDK (firebase/ai) and Firebase App Check:
- 3-Beat Verification Storyboard:
- Beat 0 (Deterministic Pixel & DOM Diff,
0 ms): Runspixelmatch({ threshold: 0.1, includeAA: false, diffMask: true })to strip subpixel anti-aliasing noise deterministically, extracts DOM state deltas, and packs up to6changed regions into a single<= 384×384 pxcomposite sprite sheet (1Gemini image tile =258tokens). - Beat 1 (On-Device Gemini Nano Triage,
PREFER_ON_DEVICE/ONLY_ON_DEVICE): Evaluates the transition locally in Chrome under a strict JSON schema (benign_transition | false_green_persistence_lie | layout_or_token_break | unsure). Benign noise melts away locally at$0cloud cost; only genuine bugs orunsureedge cases escalate. - Beat 2 (Cloud Gemini Root-Cause Patch & Live Re-Verify,
PREFER_IN_CLOUD): Escalates flagged transitions with a deterministic pre-sliced component source snippet (<= 80lines) to Cloud Gemini (gemini-3.5-flash-lite), pinpointing the offending line and generating a minimal CSS/state fix. Clicking Apply Patch & Re-Verify applies the returned RFC 6902 JSON Patch to an executable example, reruns its storage/state/layout behavior, renders the result and requests Beat 1 again after Beat 0. Invalid patches remain failures; missing live model answers are disclosed rather than treated as model confirmation.
- Beat 0 (Deterministic Pixel & DOM Diff,
- Bring Your Own Snapshot / Code Dropzone: Developers can drop or paste their own
BeforeandAfterscreenshots (PNG/JPEG), expected claim, and component snippet to run the 3-Beat hybrid verification loop on their own projects. - Interactive Hybrid Resilience & Privacy Controls:
- Confidential Mode (
ONLY_ON_DEVICE): Guarantees0cloud bytes leave the browser when testing unreleased UI. - Simulate Cloud Outage (
FETCH_ERROR): DemonstratesPREFER_IN_CLOUD→"on_device"fallback mid-escalation via per-requestSingleRequestOptions.baseUrlfault injection without breakingdata:URL image decoding or App Check.
- Confidential Mode (
- 12-Scenario Ground-Truth Benchmark Drawer: Compares
Arm 1 (Deterministic Baseline),Arm 2 (On-Device Nano Alone), andArm 3 (Full Hybrid FlowWitness)across 6 true bugs and 6 benign controls.




How we built it
All live inference goes through official firebase/ai getGenerativeModel() with PREFER_ON_DEVICE / ONLY_ON_DEVICE for triage and PREFER_IN_CLOUD / ONLY_IN_CLOUD for cloud work. App Check initializes before AI, and cloud-capable requests require successful attestation. The executable benchmark uses independent settings, tenant-role, cart, pricing, modal, security, font, time, chart, skeleton, currency and tooltip examples.
The benchmark table uses recorded expected verdicts, not measured live-model accuracy. Verify Live requests actual inference and identifies replay or unanswered calls explicitly. Each true bug can be opened in the storyboard and patched; benign controls require no repair.
Local and Vercel setup require NEXT_PUBLIC_FIREBASE_API_KEY, NEXT_PUBLIC_FIREBASE_PROJECT_ID, NEXT_PUBLIC_FIREBASE_APP_ID, and NEXT_PUBLIC_FIREBASE_APPCHECK_SITE_KEY. NEXT_PUBLIC_FIREBASE_AI_MODEL optionally overrides gemini-3.5-flash-lite. Enable Firebase AI Logic, register App Check and enforce it in Firebase Console. Rebuild after setting public variables. Debug tokens are never bundled: only non-production localhost sessions without a site key accept a project-registered runtime globalThis.FIREBASE_APPCHECK_DEBUG_TOKEN. Site keys take precedence; production clears the debug flag. A ready local preference uses SDK device-only mode without a cloud-token prefetch.
We built FlowWitness with Next.js, React 19, TypeScript, firebase/ai (@firebase/[email protected]), firebase/app-check, pixelmatch, and fast-check Property-Based Testing (P1..P4):
- Dual-Target
HybridContractCompiler(P1): In@firebase/[email protected],Schema.object()storesoptionalPropertieson the class instance and only converts them into standard JSON Schemarequired: [...]when.toJSON()runs duringJSON.stringify().buildHybridModelParams()in src/core/flow-witness-engine.ts compiles a singleSchema.object()into bothinCloudParams.generationConfig.responseSchemaandonDeviceParams.promptOptions.responseConstraint(JSON.parse(JSON.stringify(schema))withomitResponseConstraintInput: true). - Application-Level Confidential Leak-Zero Guard (
P2a): In@firebase/[email protected](index.esm.js:2551-2557),callCloudOrDevice()checksif (!chromeAdapter) return inCloudCall()before checkingONLY_ON_DEVICE. Whenwindow.LanguageModelis absent,chromeAdapterisundefined, silently routingONLY_ON_DEVICEcalls to the cloud.executeHybridInference()interceptsONLY_ON_DEVICEwhenwindow.LanguageModelis unavailable and blocks withCONFIDENTIAL_MODE_ADAPTER_MISSING(0cloud calls). - Concurrency-1 FIFO Mutex & Epoch Fencing (
P2b&P4): BecauseChromeAdapterImpl.createSession()destroys any previousLanguageModelsession (this.oldSession.destroy()),executeHybridInference()serializes requests through a concurrency-1 FIFO mutex whilestudioReducer()in src/core/studio-model.ts fences async completions with a monotonicactiveRunId. - Per-Request
SingleRequestOptions.baseUrlFault Injection & Pre-Sliced Escalation: BecauseChromeAdapterImpl.isOnDeviceRequest()rejectsfunctionResponseparts, Beat 2 embeds pre-sliced source/tokens (<= 80lines) in a single-turnPREFER_IN_CLOUDcall and injects cloud outages viaSingleRequestOptions.baseUrl = "https://fault-injection.invalid"rather than mutatingwindow.fetch.
Challenges we ran into
- Preventing On-Device Session Self-Sabotage: Early prototypes fired parallel
generateContent()calls per diff bounding box, causingChromeAdapterImpl.createSession()to abort in-flight sessions and stretching per-screen latency to ~60s. Clustering changed regions into a single<= 384×384 pxcomposite sprite sheet and serializing calls through a FIFO mutex reduced Beat 1 to a single258-token request per transition. - Preserving
data:URL Decoding and App Check During Fault Injection: Overriding globalwindow.fetchto simulate offline mode brokeChromeAdapterImpl.toLanguageModelMessageContent()(which callsfetch("data:image/jpeg;base64,...")) and triggered@firebase/app-check's 24-hour token exchange lockout. Switching to@firebase/ai's per-requestSingleRequestOptions.baseUrlisolated fault injection cleanly to the cloud endpoint.
Accomplishments that we're proud of
- Recorded Routing Benchmark: The table computes metrics over expected recorded verdicts for the independent examples. It illustrates the routing policy and does not measure live Gemini accuracy or savings. Live verification has separate SDK receipts and explicitly identifies replay.
- Mathematically Verified Invariants (
P1..P4): All four core invariants (dual-schema round-trip conservation, confidential leak-zero & concurrency-1 mutex, single-tile<= 384×384sprite geometry, andactiveRunIdepoch fencing) are verified byfast-checkproperty-based tests and independent oracle negative calibration controls.
What we learned
- On-device models shine brightest when given a narrow structured classification contract with an explicit
unsureescalation exit rather than open-ended code generation. - Reading the underlying SDK implementation (
@firebase/[email protected]and@firebase/[email protected]) is essential for building reliable hybrid AI systems that respect session lifecycles, token caching, and privacy boundaries.
What's next for FlowWitness
- Packaging the Beat 0 + Beat 1 hybrid triage loop as a Playwright / Vitest visual-and-state assertion plugin (
expect(page).toPassFlowWitness(claim)) for local CI/CD pipelines. - Expanding multi-viewport responsive token diffing across mobile, tablet, and desktop breakpoints in a single composite sprite pass.