DEV Community

Sandeep Chakravartty
Sandeep Chakravartty

Posted on

Building Doppelgänger: A Privacy-First Hybrid AI Decision Simulator with Firebase AI Logic & Gemini Nano

How we built a structured 3-futures personal decision simulator using Firebase AI Logic Hybrid Inference (PREFER_ON_DEVICE + ONLY_IN_CLOUD), Zod-validated domain modeling, and owner-isolated Firestore rules.

Consequential life and career decisions—like leaving a stable engineering job to start a company, relocating, or taking on major financial risk—are hard because people rarely see their own unstated assumptions, second-order effects, and trade-offs until after they commit.

Most AI chat tools make this worse, not better:

  1. They give single-track, overly confident answers instead of mapping competing paths.
  2. They blur stated facts, assumptions, and speculation into one confident paragraph.
  3. They silently ship deeply sensitive personal context (runway, obligations, anxieties) to cloud servers by default.

Doppelgänger ("Your future isn't written. Explore what it could become.") solves this by treating AI as a structured decision-rehearsal engine rather than an oracle—and by running routine personal context extraction on-device first via Firebase AI Logic Hybrid Inference.


What Doppelgänger Does

Instead of a single chat box, Doppelgänger guides users through a structured simulation workspace:

  1. My Decision DNA (/profile) & Local-First Preference Extraction: Users capture standing risk tolerance, liquid runway, core values, and non-negotiables—or paste raw notes to extract structured preferences locally using InferenceMode.PREFER_ON_DEVICE.
  2. 7-Step Decision Wizard (/decisions/new): Captures the core question, current situation, 2–6 options, hard constraints, financial context, key assumptions, uncertainties, and weighted priorities—with draft persistence and a local-first brief summary.
  3. Three Futures Showcase (Safe, Balanced, Bold): Synthesizes 19-point structured paths that visually separate Grounded Facts, Key Assumptions, and Hypothetical Upsides/Downsides, alongside opportunity costs, second-order effects, reversibility notes, early warning signals, and a first-30-days checklist.
  4. Timeline Explorer (30d → 3y): Expands each path across 30d, 90d, 6m, 1y, and 3y horizons with positive/negative outcomes, watch signals, and mitigation actions.
  5. Comparison Dashboard & Live Priority Re-Weighting: Combines a qualitative comparison matrix with a 6-axis Recharts Radar chart—explicitly labeled as a Heuristic Estimate—and priority sliders that dynamically re-rank paths.
  6. Non-Destructive What-If Simulator: Challenges assumptions ("What if enterprise sales cycles take 6 months instead of 2?") without mutating the original baseline scenarios.
  7. Decision Journal & Grounded AI Companion: Logs reflections and real-world outcomes alongside a multi-turn startChat companion grounded in the active decision and approved Decision DNA.
  8. Hybrid AI Diagnostics (/diagnostics) & Full Autonomy (/settings): Probes window.LanguageModel.availability(), triggers user-gesture Gemini Nano downloads, displays real inference telemetry, enforces an explicit cloud-sharing consent gate, and supports full JSON export + one-click data/account deletion.

Architecture & Design

We structured Doppelgänger with strict separation between pure domain logic, storage, Firebase security, and Hybrid AI orchestration:

src/
├── ai/                  # Task routing table (taskConfig.ts) & prompt builders
├── domain/              # Pure Zod schemas, decision engine, fictional sample fixture
├── services/
│   ├── ai/              # FirebaseHybridAIService, browserCapabilities, telemetryStore, offline templates
│   ├── firebase/        # App, Auth, App Check, Remote Config, FirestoreStorageService
│   └── storage/         # WorkspaceStorageService interface + LocalDemoStorageService
└── features/            # auth, onboarding, profile, decisions, scenarios, diagnostics, settings
Enter fullscreen mode Exit fullscreen mode

1. Task-Aware Hybrid AI Routing (firebase/ai)

Not every task belongs in the same execution environment. In src/ai/taskConfig.ts, every AI capability declares an explicit InferenceMode:

Task InferenceMode Cloud Model Tier Rationale
extract_preferences PREFER_ON_DEVICE Fast (gemini-3.5-flash-lite fallback) Keeps raw personal notes local via Chrome Gemini Nano when available
summarize_decision PREFER_ON_DEVICE Fast (gemini-3.5-flash-lite fallback) Fast local brief condensation & assumption check
extract_assumptions PREFER_ON_DEVICE Fast (gemini-3.5-flash-lite fallback) Surfaces implicit beliefs locally before cloud simulation
generate_three_futures ONLY_IN_CLOUD Primary (gemini-3.8-flash) Deep 19-point multi-horizon synthesis across 3 futures
generate_what_if_branch ONLY_IN_CLOUD Primary (gemini-3.8-flash) Counterfactual stress-testing across trade-offs & deltas
companion_chat ONLY_IN_CLOUD Primary (gemini-3.8-flash) Multi-turn startChat grounded in scenario context

Cloud model IDs and feature toggles are managed dynamically through Firebase Remote Config (remoteconfig.template.json) rather than hardcoded.

2. Explicit Consent Gate & Honest Telemetry

FirebaseHybridAIService (src/services/ai/hybridAIService.ts) enforces two non-negotiable guarantees:

  • Consent Before Cloud Transmission: Before calling ONLY_IN_CLOUD—or PREFER_ON_DEVICE when window.LanguageModel.availability() is not 'available'—the service checks cloudConsentGranted. If consent is false, it throws a typed HybridAIError('consent_required') instead of silently leaking user context to the cloud.
  • No Latency Guessing: Execution source is recorded strictly from result.response.inferenceSource (InferenceSource.ON_DEVICE → 'on_device', InferenceSource.IN_CLOUD → 'in_cloud', undefined → 'unknown'), setting fallbackUsed: true whenever a prefer_on_device task ran in the cloud.

3. Structured Outputs & Bounded Recovery

All AI JSON responses are parsed (stripping markdown fences if present) and validated against strict Zod schemas (src/domain/schemas.ts). If the model returns malformed JSON or fails schema validation, FirebaseHybridAIService performs at most one corrective retry containing the exact Zod validation errors before surfacing a classified error.

4. Owner-Isolated Persistence & App Check

  • App Check Replay Protection: getAI(app, { backend: new GoogleAIBackend(), useLimitedUseAppCheckTokens: true }) pairs with ReCaptchaEnterpriseProvider in production and VITE_APP_CHECK_DEBUG_TOKEN in development.
  • Prototype Firestore Rules (firestore.rules): Every document under /users/{uid}/... enforces request.auth.uid == uid, strict allowed-field lists, string/list size caps, immutable uid/createdAt, and domain validator functions on both create and update.
  • Zero-Credential Demo Boundary: Through the WorkspaceStorageService interface, unconfigured or guest sessions seamlessly run in LocalDemoStorageService (localStorage) with a clearly labeled fictional sample (Maya Lin) and offline demo templates (actualSource: 'unknown').

What Went Well

  • Decoupled Pure Domain Engine: Keeping Zod schemas, comparison derivation (deriveScenarioComparison), priority re-weighting, and non-destructive What-If merging (mergeWhatIfBranch) pure in src/domain/ made core behavior fast and deterministic to unit test (8 domain tests running in ~16ms).
  • Zero-Friction Demo Mode Without Lying: Visitors and judges can test the entire 7-step wizard, 19-point Three Futures inspector, Radar comparison, What-If simulator, and Journal immediately without Firebase keys—while Diagnostics and badges remain 100% honest about running on offline-demo-template.
  • Strict TypeScript + Integration Tests Caught Real UI Bugs: Running tsc -b (noUncheckedIndexedAccess: true) alongside Vitest + React Testing Library caught a Tabs panel rendering omission and a Select children prop mismatch before anything shipped.

What Did Not Go Well

  • The # Directory Name Bug in Vite 7 / Vitest 3: Our initial workspace directory contained a # character (#BuildHybridAI 2026). Vite and Vitest strip # URL fragments internally during resolution, causing vite build (Failed to resolve /src/main.tsx) and vitest (Cannot find module '/@vite/env') to fail until the folder was renamed without #.
  • SDK Evolution Surprises in firebase@13.4.0: We initially assumed standard temperature/topP generation parameters and legacy { text } chat history parts. Compiling under tsc -b revealed that Gemini 3.x+ models deprecate temperature/topP/candidateCount in @firebase/ai and that ChatSession history TextPart objects now require { type: 'text', text: string }.
  • Local Emulator & Browser E2E Environment Gaps: Because Java, global firebase-tools, and Playwright were not pre-installed in the local build environment, Firestore Emulator security rule tests and real-browser E2E flows could not be executed locally alongside our 22 Vitest + Testing Library tests.

What We Learned

  1. Inspect installed .d.ts files early: Reading node_modules/@firebase/ai/dist/src/ directly saved hours by exposing exact signatures for HybridParams, initializeDeviceModel(onDownloadProgress), inferenceSource, and Gemini 3+ GenerationConfig.
  2. Treat tsc -b as your real typecheck: Root tsc --noEmit can mask stricter tsconfig.app.json settings like noUncheckedIndexedAccess: true. Wiring "typecheck": "tsc -b" caught real array-indexing edge cases across both source and tests.
  3. Privacy architecture shapes product trust: Separating Decision DNA opt-in, explicit cloud consent, fact vs. assumption labeling, and one-click JSON export / deletion turned privacy from marketing copy into concrete engineering invariants.
  4. Non-destructive counterfactuals make simulation practical: Keeping baseline Safe/Balanced/Bold paths immutable while overlaying What-If deltas makes assumption testing safe and easy to reason about.

Verification Summary

After the final code edits:

  • npm run typecheck (tsc -b): 0 errors
  • npm run lint (eslint .): 0 errors, 0 warnings
  • npm test (vitest run): 8 test files, 22 tests passed
  • npm run build (tsc -b && vite build): 2,595 modules bundled cleanly

Next up, we plan to wire CI-based Firestore Emulator security-rule testing, Playwright browser E2E tests, and longitudinal 30d/90d/6m outcome calibration so users can compare real-world outcomes back against their initial assumptions.

Top comments (0)