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:
- They give single-track, overly confident answers instead of mapping competing paths.
- They blur stated facts, assumptions, and speculation into one confident paragraph.
- 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:
-
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 usingInferenceMode.PREFER_ON_DEVICE. -
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. - 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.
-
Timeline Explorer (
30d→3y): Expands each path across30d,90d,6m,1y, and3yhorizons with positive/negative outcomes, watch signals, and mitigation actions. - 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.
- Non-Destructive What-If Simulator: Challenges assumptions ("What if enterprise sales cycles take 6 months instead of 2?") without mutating the original baseline scenarios.
-
Decision Journal & Grounded AI Companion: Logs reflections and real-world outcomes alongside a multi-turn
startChatcompanion grounded in the active decision and approved Decision DNA. -
Hybrid AI Diagnostics (
/diagnostics) & Full Autonomy (/settings): Probeswindow.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
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—orPREFER_ON_DEVICEwhenwindow.LanguageModel.availability()is not'available'—the service checkscloudConsentGranted. If consent is false, it throws a typedHybridAIError('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'), settingfallbackUsed: truewhenever aprefer_on_devicetask 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 withReCaptchaEnterpriseProviderin production andVITE_APP_CHECK_DEBUG_TOKENin development. -
Prototype Firestore Rules (
firestore.rules): Every document under/users/{uid}/...enforcesrequest.auth.uid == uid, strict allowed-field lists, string/list size caps, immutableuid/createdAt, and domain validator functions on bothcreateandupdate. -
Zero-Credential Demo Boundary: Through the
WorkspaceStorageServiceinterface, unconfigured or guest sessions seamlessly run inLocalDemoStorageService(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 insrc/domain/made core behavior fast and deterministic to unit test (8domain 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 aTabspanel rendering omission and aSelectchildren 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, causingvite build(Failed to resolve /src/main.tsx) andvitest(Cannot find module '/@vite/env') to fail until the folder was renamed without#. -
SDK Evolution Surprises in
firebase@13.4.0: We initially assumed standardtemperature/topPgeneration parameters and legacy{ text }chat history parts. Compiling undertsc -brevealed that Gemini 3.x+ models deprecatetemperature/topP/candidateCountin@firebase/aiand thatChatSessionhistoryTextPartobjects 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
-
Inspect installed
.d.tsfiles early: Readingnode_modules/@firebase/ai/dist/src/directly saved hours by exposing exact signatures forHybridParams,initializeDeviceModel(onDownloadProgress),inferenceSource, and Gemini 3+GenerationConfig. -
Treat
tsc -bas your real typecheck: Roottsc --noEmitcan mask strictertsconfig.app.jsonsettings likenoUncheckedIndexedAccess: true. Wiring"typecheck": "tsc -b"caught real array-indexing edge cases across both source and tests. - 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.
- 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)