Inspiration

When earthquakes, flash floods, or grid collapses strike, cell towers fail at the exact moment first responders need operational clarity the most: Which aid camp still has open beds? Is the shortest road actually safe around a collapsed overpass? What are the exact steps for crush syndrome or tourniquet placement right now?

Every existing disaster tool hits the same split-brain failure mode:

  • Pure cloud AI becomes unusable the second a responder steps into a blackout zone.
  • Pure on-device AI operates in an isolated silo; when five medics return from different sectors with conflicting bed counts, damaged-camp reports, and hazy ward CCTV images, a phone alone cannot fuse multi-source evidence or forecast sector-wide supply depletion.

Crisis Connection was inspired by the idea that humanitarian response shouldn't have to choose between offline resilience and cloud intelligence. Using Firebase AI Logic, we built a closed-loop hybrid AI network where field handsets stay autonomous at zero signal and Base Camp Cloud Command reconciles the big picture the moment connectivity returns.

What it does

Crisis Connection unifies Main Base Camp (Web Command PWA) and Field Responders (Chrome Side Panel Extension, Android Native, and iOS/macOS Native) in a continuous 5-stage loop:

  1. Pre-Departure Field Pack (Online at Base Camp): Before heading into a zero-signal sector, responders download the latest Cloud Firestore snapshot of aid camps (beds, trauma kits, potable water, generator hours, safety ratings, hazard zones, and 6 offline medical/trauma protocols) and pre-warm on-device AI (model.initializeDeviceModel() on Chrome, onDeviceExtension?.warmUp() / Gemma 4 LiteRT-LM on Android, and Apple Foundation Models availability checks on iOS). If Apple Foundational Models are not available on an older iOS devices, there are Offline rules fallbacks for some quick triage prompts. This is also applicable in scenarios where there is no time for a local model to be downloaded, so that key information may be available no matter the situation.
  2. Offline Tactical Routing (distance × danger): Both Base Camp's full SVG topographic map and mobile/extension Sector Meridian mini-maps run an offline multi-entry Dijkstra engine that compares the Safest Optimal Route against the Pure Shortest Route, automatically warning responders away from collapsed overpasses, floods and gas leaks, rerouting immediately if a camp is marked DESTROYED.
  3. Hybrid Multimodal Field AI Assistant (ONLY_ON_DEVICE / PREFER_ON_DEVICE): Field workers query live local camp telemetry and cached emergency protocols (CPR, haemorrhage/tourniquet, START triage, crush injury, burns, water purification) via text, voice (Web Speech API), or camera photos. Dynamic response-scope calibration returns crisp 1-sentence answers for specific metric lookups (e.g., "How many trauma kits at CAMP-01?") and full operational briefings for broad questions, always displaying an honest inference badge (ON_DEVICE, IN_CLOUD, or LOCAL_FALLBACK_ENGINE) and latency telemetry.
  4. Always-On Cross-Platform BLE Mesh, Nearby Chat & Base Camp Broadcasts: While completely offline, Android, iOS, and Web/Chrome Extension clients exchange live camp bed updates, destruction alerts, undo overrides, and nearby responder chat over a shared 180-byte Bluetooth Low Energy (BLE) GATT wire protocol (with 3-hop relay) plus offline browser-tab BroadcastChannel gossip. When Base Camp dispatches an urgent Base Camp Broadcast via Firestore, online phones receive it in real time and automatically bridge it over BLE to offline teammates nearby. This way, it is possible to receive online broadcasts in the field whilst being completely without a connection.
  5. Base Camp Cloud Command (ONLY_IN_CLOUD): On the Web Command dashboard, Firebase AI Logic invokes Cloud Gemini with structured JSON (Schema.object) for three heavy reasoning workloads:
    • Multimodal Ward CCTV Vision: Analyzes ward camera frames or uploaded photos to count open vs. occupied cots, detect structural damage or smoke occlusion, and quantify visual uncertainty.
    • Multi-Source Conflict Reconciliation & Auditable Diff Commit: Collects prior Firestore ground truth, conflicting offline/mesh field reports, and CCTV counts, weighs them with Cloud Gemini, logs residual uncertainty (\(0\text{–}100\%\)), and lets coordinators commit and broadcast the verified ground truth back to Firestore and the fleet.
    • Long-Context Shortage Forecasting & Base Reorganization: Analyzes multi-hour camp history, burn rates, and logged uncertainties across all bases to predict bed, water, trauma kit, and generator depletion countdowns and output an actionable reorganization plan.

How we built it

Cross-Platform Firebase AI Logic Architecture

  • Web PWA & Chrome MV3 Side Panel Extension (src/, chrome-extension/): Built with React 18, TypeScript, Vite, and Tailwind CSS using firebase/ai (v13.4.0). Routes field queries via InferenceMode.ONLY_ON_DEVICE (offline) and InferenceMode.PREFER_ON_DEVICE (online) to Chrome Gemini Nano 4 with automatic Cloud Gemini (gemini-3.5-flash-lite / gemini-3.8-flash) streaming fallback and multimodal InlineDataPart image support, and runs Cloud Command analytics via InferenceMode.ONLY_IN_CLOUD with Schema.object.
  • Android Native (android/): Built with Kotlin and Jetpack Compose (Material 3 Matte Graphite dark theme) using Firebase BoM 35.2.0, com.google.firebase:firebase-ai, and com.google.firebase:firebase-ai-ondevice (OnDeviceConfig, InferenceMode, onDeviceExtension). On handsets without Android AICore, Crisis Connection integrates Google AI Edge LiteRT-LM (litertlm-android) to run an ungated on-device Gemma 4 E2B (gemma-4-E2B-it.litertlm) model fully offline.
  • iOS / macOS Native (ios/): Built with SwiftUI and Swift Package Manager (CrisisConnectionCore, firebase-ios-sdk v12.19+), combining Apple's on-device Foundation Models (SystemLanguageModel / LanguageModelSession on iOS/macOS 26+) with Cloud Gemini via FirebaseAILogic.
  • Supporting Firebase Stack: Real-time multi-device sync via Cloud Firestore (aidCamps, emergencyAlerts, fieldReports, uncertaintyLogs), zero-friction Anonymous Firebase Authentication, isolated Firebase App Check (reCAPTCHA v3 / Play Integrity / debug tokens), Firebase Remote Config for live tuning of cloud_model_name, default_inference_mode, danger_weight, and mesh_base_cycle_sec, and Firebase Hosting.

Core Algorithms & Mathematical Models

1. Multi-Entry Danger-Weighted Evacuation Routing

For every road segment \(e = (u, v)\) with length \(\ell(e)\) (km) and road-condition baseline danger \(d_{\text{road}}(e) \in {1, 3, 5, 7}\) (clear, debris, flooded, compromised), we compute the exact Euclidean point-to-segment distance \(\operatorname{dist}(h_k, \overline{uv})\) against every active hazard zone \((h_k, r_k, d_k)\):

$$d(e) = \max\Big(d_{\text{road}}(e),\ \max_{k:\,\operatorname{dist}(h_k,\overline{uv}) \le r_k} d_k\Big)$$

Severe hazards (\(d \ge 7\)) incur a nonlinear penalty \(\phi(d) = 2d\) (otherwise \(\phi(d) = d\)). Given the Remote Config danger weight \(w \ge 0\) (default \(w = 0.45\), with \(w = 0\) giving the pure-shortest baseline), Dijkstra minimizes edge cost:

$$c(e) = \ell(e)\cdot\big(1 + w\,\phi(d(e))\big)$$

Evaluating the 4 nearest graph entry nodes from arbitrary responder coordinates with a \(1.5\times\) off-road approach factor, each candidate path \(P\) to operational camp \(c\) is scored with a damaged-camp multiplier \(\gamma_{\text{status}} \in {1.0, 1.5}\) and hazard-adjusted travel speed \(v_{\text{eff}}\):

$$S(P, c) = L(P)\cdot\big(1 + \max(0.15, w)\,\bar{d}(P, c)\big)\cdot\gamma_{\text{status}}, \qquad v_{\text{eff}} = \max(5,\ 22 - 1.6\,\bar{d})\ \text{km/h}$$

2. Adaptive X-Cycle Mesh Cadence & 3-Hop BLE Wire Protocol

Rather than flooding radios at a fixed interval, our adaptive gossip controller adjusts sync period \(X\) from base interval \(X_0 = 15\text{ s}\) using critical-emergency status \(E\), unsynced report count \(N_u\), average database uncertainty \(\bar{U}\%\), and minimum peer battery \(B_{\min}\%\):

  • Emergency Burst (\(E = \text{true}\)): \(X = 4\text{ s}\) for rapid camp-destruction propagation.
  • Divergence Catch-Up (\(N_u \ge 2\) or \(\bar{U} \ge 45\%\)): \(X = \max(6,\ \operatorname{round}(0.55\,X_0))\).
  • Battery Saver (\(B_{\min} < 30\%\)): \(X = \min(30,\ \operatorname{round}(1.65\,X_0))\).
  • Normal Patrol: \(X = X_0\).

Across Android (BluetoothGattServer + BluetoothLeScanner), iOS (CoreBluetooth), and Chrome (Web Bluetooth), all devices speak a unified \(\le 180\)-byte UTF-8 JSON GATT packet format on service UUID 7C1D0001-4B52-4953-4953-434F4E4E4543 with 256-entry FIFO/LRU message-ID deduplication, 3-hop TTL decrement (\(h' = h - 1\) while \(h > 0\)), and Lamport version-vector conflict resolution with explicit Undo override (\(u = 1\)):

$$\text{accept}(p, \text{local}) \iff (u = 1) \lor (v_p > v_{\text{local}}) \lor \big(v_p = v_{\text{local}} \land t_p > t_{\text{local}} \land \Delta\text{state} \neq \emptyset\big)$$

3. Multi-Source Conflict Resolution & Uncertainty Quantification

When Cloud Gemini reconciles pending offline reports and optical CCTV observations, it produces structured JSON diffs and explicit uncertainty logs. When deterministic fallback computes offline previews, it fuses CCTV bed count \(b_{\text{CCTV}}\) and latest field count \(b_{\text{field}}\) and bounds residual uncertainty \(U\) by observation spread \(\Delta b = \max(B) - \min(B)\):

$$\hat{b} = \operatorname{round}(0.6\,b_{\text{CCTV}} + 0.4\,b_{\text{field}}), \qquad U = \min!\Big(85,\ \max!\big(10,\ \operatorname{round}(0.7\,U_{\text{CCTV}}) + \min(35,\ 3\,\Delta b)\big)\Big)$$

Challenges we ran into

  • On-device AI hardware fragmentation: Chrome Gemini Nano 4, Android AICore, and iOS 26 Apple Intelligence have strict device eligibility requirements. To guarantee true offline neural inference on broader Android hardware, we integrated LiteRT-LM (Gemma 4 E2B) and hit a native SIGILL crash in liblitertlm_jni.so on x86_64 Android Emulators due to missing CPU instructions, which we resolved by guarding runtime initialization while keeping physical devices accelerated.
  • Safety-filter false positives on emergency terminology: Apple's on-device Foundation Models initially triggered .guardrailViolation refusals on words like "DESTROYED" or "trauma" in disaster prompts. We fixed this with neutral logistics status framing (CLOSED_INOPERABLE, MedKits), compact token budgeting for the 4K context window, and automatic fallback to .permissiveContentTransformations. We also resolved a Swift 6 symbol ambiguity between FoundationModels.SystemLanguageModel and FirebaseAILogic.
  • Fitting a cross-platform mesh into 180 BLE bytes: Android, iOS, and Chrome Web Bluetooth negotiate conservative default MTUs. Designing a compact JSON schema that carries camp state, Lamport version, timestamp, hop TTL, and Undo override, or 96-character chat/broadcast alerts, strictly under 180 bytes while preventing relay broadcast storms required strict deduplication and cross-platform unit tests.
  • App Check vs. zero-friction multi-device sync: Enforcing App Check on a single default Firebase instance stalled Firestore reads on freshly installed test phones lacking a registered debug token. Splitting initialization into [DEFAULT] (Anonymous Auth + Firestore + Remote Config) and an isolated 'crisis-ai' app instance (App Check + Firebase AI Logic) kept live multi-device sync instant while securing AI calls.
  • Firestore snapshot race on conflict commit: During automated Cloud Command reconciliation, asynchronous Cloud Gemini responses raced with Firestore onSnapshot listeners that briefly re-hydrated already-committed field reports. Persisting resolved: true in Firestore plus a local resolved-ID guard eliminated stale conflict resurrection cleanly.

Accomplishments that we're proud of

  • True 4-target cross-platform parity: Web Command PWA, Chrome MV3 Side Panel Extension, native Android APK, and native iOS/macOS SwiftUI app all interoperate over the exact same Firestore schema and 180-byte BLE GATT mesh protocol.
  • Honest, transparent hybrid AI: Every response displays its real inference tier (ON_DEVICE Gemini Nano 4 / Gemma 4 / Apple Intelligence, IN_CLOUD Gemini, or LOCAL_FALLBACK_ENGINE) and exact diagnostic reason, never faking neural output or hiding uncertainty.
  • Genuine zero-signal survivability: Turning off Wi-Fi and cellular automatically enforces Offline mode, detaches cloud listeners cleanly, keeps routing/protocols/on-device AI operational, and lets Android and iOS handsets keep syncing beds, alerts, and chat peer-to-peer over BLE.
  • Verified end-to-end quality: Backed by automated unit tests across all three codebases (20 Web Vitest suites, 23 iOS SwiftPM XCTests, and Android JUnit tests) plus synchronized 1-minute interactive demos built directly into every client.

What we learned

  • Hybrid AI is a systems architecture, not a model flag: Designing clean boundaries between what belongs on-device (low-latency triage, private local RAG, zero-signal survival) and what belongs in the cloud (multimodal vision, multi-source conflict reconciliation, long-context forecasting) unlocks capabilities neither tier can deliver alone.
  • Small on-device models thrive on disciplined context engineering: Tightening Local RAG context and adding a dynamic response-scope directive dramatically improved accuracy and speed on Gemini Nano 4, Gemma 4 E2B, and Apple Foundation Models.
  • Uncertainty is a first-class feature in crisis UX: Surfacing how confident the system is, and why, builds far more operator trust than presenting stale disaster estimates as absolute truth.

What's next for Crisis Connection

  • Live drone & RTSP ward camera ingestion feeding directly into Cloud Command's multimodal bed and hazard detector.
  • Long-range LoRaWAN / Meshtastic bridge paired with BLE mesh so field teams can relay 180-byte camp packets across multi-kilometer rural disaster zones.
  • Cryptographic responder signatures on BLE mesh packets to prevent spoofed camp-destruction alerts in contested environments.
  • Multilingual on-device voice triage using local speech-to-text and translated trauma protocols for international relief teams.

Built With

  • android
  • apple-foundation-models
  • chrome
  • cloud-firestore
  • corebluetooth
  • firebase
  • firebase-ai-logic
  • firebase-app-check
  • firebase-authentication
  • firebase-hosting
  • firebase-remote-config
  • gemini
  • gemini-nano
  • gemma
  • jetpack-compose
  • kotlin
  • litert
  • pwa
  • react
  • swift
  • swiftui
  • tailwindcss
  • typescript
  • vite
  • web-bluetooth
Share this project:

Updates

Submission history