Inspiration
People living with chronic pain track deeply sensitive health details every day: pain flares, anatomical locations, medication schedules, doctor names, and personal triggers. Yet nearly all health tracking apps either upload every raw diary entry straight to a remote server—creating unnecessary privacy exposure and failing offline—or offer zero longitudinal intelligence when preparing for a 10-minute clinic visit.
Chronic pain care is a textbook use case for Hybrid AI: private daily check-ins belong on the user's device, while complex 30-day pattern analysis and multi-drug analgesic safety reviews benefit from cloud reasoning only when the user explicitly consents.
What it does
PainFree Hybrid is an offline-first clinical pain and medication companion built around three focused workspaces:
Daily Care Check-in (
PREFER_ON_DEVICE/ONLY_ON_DEVICE):- Interactive 0–10 pain scale, Front/Back anatomical body heatmap that lights up as episodes accumulate, 1-tap medication regimen presets, hands-free voice check-in, and multimodal JPEG/PNG pill-bottle label scanning (with local canvas EXIF/GPS metadata stripping).
- On-Device Gemini Nano Triage: On Chrome Desktop with Gemini Nano ready, triage runs 100% offline in ~2.5 seconds with zero cloud API requests, generating concise clinical summaries, self-care guidance, and negation-aware red-flag screening.
- Local Privacy Shield + Safe Cloud Fallback: On devices without Gemini Nano, our 0ms in-browser Privacy Shield masks doctor names, clinics, phone numbers, emails, and IDs locally, strips raw private symptom notes by default, and seamlessly falls back to Cloud Gemini via Firebase AI Logic without blocking first load on a multi-GB model download.
Clinician Report & Multi-Drug Safety (
ONLY_IN_CLOUD):- Deterministic local safety net continuously checks 30-day logs for 48-hour duplicate NSAID active ingredients (mapping brand aliases like Advil/Ibuprofen + Naproxen) and true 24-hour rolling Acetaminophen intake ≥ 3,000 mg.
- Tracks Before → After medication pain relief so patients can see which regimen actually reduces their pain.
- Before escalating to Cloud Gemini, a Consent Dialog displays the exact de-identified JSON payload (
YYYY-MM-DDTHH:mmtimestamps, zero raw notes) and pins that exact snapshot. Upon approval,ONLY_IN_CLOUDsynthesizes a 30-day doctor handoff summary, safety alerts, and 3 consultation questions ready for Copy Markdown or Print/PDF.
Hybrid AI Inspector:
- Toggle all four Firebase AI Logic
InferenceModepolicies (PREFER_ON_DEVICE,ONLY_ON_DEVICE,PREFER_IN_CLOUD,ONLY_IN_CLOUD), inspect liveApp Checkstatus,Remote Configmodel source, Service Worker status, and audit every call in a real-time Hybrid Routing Decision Trace table.
- Toggle all four Firebase AI Logic
How we built it
- Firebase AI Logic (
firebase/ai,GoogleAIBackend): Real runtimegetGenerativeModelcalls across all fourInferenceModesettings, readingresult.response.inferenceSource(ON_DEVICE/IN_CLOUD) and structured JSON output (responseMimeType: "application/json"). - Firebase App Check (
firebase/app-check): Enforced on Firebase AI Logic with reCAPTCHA Enterprise in production (App Check: verified), while gating dev debug tokens strictly behindimport.meta.env.DEVso production bundles never contain debug tokens. - Firebase Remote Config: Dynamically controls
cloud_fallback_model(gemini-3.5-flash-lite) in real time without redeploying. - Firebase Authentication & Cloud Firestore: Anonymous sign-in + opt-in sync of de-identified metrics under per-UID
firestore.ruleswith a strict 9-field schema allowlist (rawnotesforbidden at the rules level). - Firebase Hosting & Offline PWA: Live at https://painfree-hybrid-2026.web.app with hardened CSP,
X-Frame-Options: DENY,X-Content-Type-Options: nosniff,Referrer-Policy,Permissions-Policy, and allowlisted static app-shell Service Worker (/sw.js).
Challenges we ran into
- Unbranded Chromium Echo Stubs & Malformed LLM JSON: Unbranded Chromium resolves
ONLY_ON_DEVICEwith an echo stub string instead of throwing; we built explicit echo-stub detection (isChromiumEchoStub) so fallback triggers cleanly, plus defensive runtime schema parsers. - Clinical Negation Edge Cases: Naive keyword matching falsely flagged
"No chest pain"or missed contrastive phrases like"No chest pain but shortness of breath"; we implemented clause-splitting and double-negation-aware screening backed by automated tests. - Client & Privacy Hardening: We ran adversarial security audits to eliminate XSS, pin consent-preview snapshots, strip image EXIF metadata via canvas, prevent raw GET form leaks, serialize Clear Ledger against in-flight Firestore syncs, and verify zero secret/debug-token exposure in
dist/.
Accomplishments that we're proud of
- Verified 100% offline
ON_DEVICEGemini Nano triage in Chrome Desktop (2555 mswarm inference,0external network requests,On-Device Ratio: 100%). - Verified live production
App Check: verified+ domain-locked API key + Remote Config(remote)+ strict CSP on https://painfree-hybrid-2026.web.app. - 11/11 automated security & logic tests (
npm test) covering XSS, runtime schemas, red-flag negation, NSAID/Acetaminophen windows, PII scrubbing,localStorageresilience, Clear Ledger concurrency, and production bundle debug-token checks.
What we learned
True hybrid AI UX means designing non-blocking degradation (never forcing a multi-GB download before a user can log pain), making privacy boundaries observable (Local Privacy Shield + JSON consent preview + Live Routing Trace), and pairing deterministic clinical safety nets with generative synthesis.
What's next for PainFree Hybrid
- Expanding to Android via Firebase AI Logic on-device Gemini Nano for mobile bedside logging.
- Adding FHIR / Apple Health / Health Connect export for direct EHR clinician handoff.
- Multilingual voice check-in with on-device speech-to-text as local Web Speech engines mature.
Built With
- cloud-firestore
- firebase
- firebase-ai-logic
- firebase-app-check
- firebase-auth
- firebase-hosting
- firebase-remote-config
- gemini
- gemini-nano
- pwa
- typescript
- vite