Skip to main content

Web platform

These features sit on top of live operations: collaboration, sharing, files, search, analytics, integrations, permissions, security, observability and offline support. They live in backend/app/platform/, backend/app/observability/ and backend/app/api_platform.py on the server, and in frontend/src/platform/, frontend/src/pages/ and frontend/src/terminal/platformPanels.jsx on the web. They never change dispatch behaviour. They read the controller's store and publish on its bus, like every other part of the system.

Map of the web app​

PathWhat it is
/Dispatcher console (keyboard-first terminal)
/welcomeOverview: live numbers, the uncertainty explainer, demo storylines, app directory, FAQ
/help, /help/<doc>This documentation, searchable, offline-capable, every heading linkable
/s/<token>A shared incident (public, read-only, expiring)
/caller, /ambulance, /hospital108 caller line, crew app, ER board
/onboardPublic registration: "Register a hospital" (location pin, helpline, ownership, NK-48 / CMCHIS, capabilities, contact, a sign-in for its ER) and "Register an ambulance fleet" (each ambulance's registration, type, base, crew phone, location mechanism). Every submission is a pending application; ?app=<id>&token=<token> shows its decision.
/adminAdmin portal; onboarding adds the Applications (approve / reject), Fleet (every source, enable / disable) and Data checks (records due for confirmation, the capacity "to call" list) tabs (pages/AdminOnboarding.jsx).
/docsOpenAPI reference (Swagger UI)
/metrics, /api/ready, /api/healthPrometheus metrics, readiness, liveness

Every view is a separate code-split bundle, so the crew phone never downloads the dispatcher terminal.

Getting started in the console​

The first time the console opens, it asks for a name or call sign. That name goes on team notes, approvals and the audit log. There are no accounts; the name stays on that device. A short guided tour follows. Replay it from the command line ("Take the guided tour"). The Getting started checklist tracks the first useful actions.

Keyboard​

Every action is a command. ⌘K / Ctrl+K (or /) opens the command line, and ? lists every shortcut. New shortcuts:

KeysAction
MWrite a team note on the selected incident
UAttach a file to the selected incident
Shift+SShare the selected incident
Shift+EDownload the incident report (Markdown)
Alt+LCopy a link to exactly this view
Alt+HOpen this guide
g o / g a / g f / g s / g wTeam notes / History / Files / Analytics / Integrations panels

Dialogs trap focus and return it when they close. Critical alerts are announced to screen readers (assertive), everything else politely. A skip link leads to the main content. Motion is reduced when the OS asks for it.

The command line searches locally as you type: commands, live incidents, units, hospitals. It also searches the server: closed incidents, team notes and these docs. Filters can be combined with words:

sev:critical status:active chest pain ch:sms is:hold unit:A12 zone:z07

The URL always reflects the console: /?incident=INC-…&unit=…&ws=dispatch&panel=collab. Bookmark it, paste it into a chat, or open it in another tab. Back and Forward restore the selection.

Collaboration​

  • Presence. Avatars in the top bar show who else has the console open. The Team notes panel shows who is on the same incident and who is typing. Each tab heartbeats every 15 s (POST /api/ops/presence). Changes fan out instantly over SSE as presence.updated.
  • Team notes. Threaded comments on an incident, never shown to the caller. @name mentions notify that operator. Notes support edit, delete and resolve. Only the author, or a supervisor, can edit or delete. Drafts autosave (see below).
  • History. One newest-first timeline per incident: system events, human decisions (audit), notes and files, with filters and paging. Download it as a report with Shift+E.
  • Files. Drag, drop, paste or choose files: photos, ECG strips, PDF, audio, video, text, CSV, JSON, up to 15 MB each. The server detects the type from the content, never from the name. Files are stored content-addressed (SHA-256) and served with Content-Disposition and a sandboxing CSP.

All of these are realtime. Every change is an event on the bus (comment.*, attachment.*, share.*), so other consoles update at once, webhooks fire, and the change lands in the audit log.

Sharing​

Shift+S creates an expiring, revocable public link to an incident. There are two scopes:

ScopeShowsFor
statusProgress, responding unit, ETA, destination hospitalThe caller's family
incidentSeverity distribution, findings, vitals, NEWS2, required capabilitiesA receiving team. No caller identifiers and no conversation.

Links last 1 hour to 7 days. Only a SHA-256 of the token is stored. Expired and revoked links return the same 404, so a link's existence can't be probed. Each link counts its views. The share page refreshes every 10 seconds, pauses while the tab is hidden, and keeps the last good state through short outages.

Autosave​

Drafts (team notes, replies) save in two places:

  1. On the device. Every keystroke goes to localStorage, so a reload or crash loses nothing.
  2. On the server. After 1.2 s of quiet, the draft goes to PUT /api/ops/drafts/{key}, stored per operator, so it follows them to another console.

Saves send If-Match: "<version>". If another tab saved a newer version, the server answers 412 with the current draft and the UI says so; nothing is silently overwritten.

Offline and installable (PWA)​

  • Install from the browser menu. The console and the crew app install as separate apps; the crew app starts at /ambulance.
  • The service worker (frontend/public/sw.js) caches the app shell and every built asset. API reads are network-first with the last good copy as fallback, so a dropped connection shows the last known state. Help docs and attachments stay readable offline.
  • Writes made offline are kept on the device and sent on reconnect: crew status and vitals through the crew outbox, team notes through the write queue. A banner shows how many are waiting.
  • A new deployment shows a "new version ready" banner. The page never swaps code under an operator mid-action.

Analytics​

The Analytics panel (g s) shows, for 1 h / 6 h / 24 h / 7 d:

  • incident volume over time
  • severity, channel and status mix
  • call→dispatch and call→scene p50/p90
  • recommendations held for a human, approvals, override rate, escalations
  • fleet availability
  • console usage and Core Web Vitals (LCP, INP, CLS)

Product telemetry is privacy-preserving. Only allow-listed event names and property keys are accepted (POST /api/ops/telemetry); free text, IDs and PII are dropped server-side. Browsers sending Global Privacy Control or Do Not Track contribute no usage events, and any operator can switch usage analytics off from the command line. Error reports and Web Vitals are always anonymous and always on.

Permissions​

Roles are defined in config/platform.yaml:

RoleCan
supervisoreverything, including webhooks and API keys
dispatcherdecide, reply, units, traffic, notes, files, share, export, analytics, demos
calltakerintake, reply, notes, files, export
adminthe admin portal (/admin): staff accounts, hospital records and verification, flagged callers, ambulance tiers; reads incidents
crewunit status, vitals, notes, files
hospitalits own hospital's ER board (er.read, scoped): the patients routed there, its referrals, record, capacity and diversion. No incident.read: never the dispatch picture or another hospital's patients
citizencall for help; profile shared with the crew; their own reports
viewerread-only, analytics, export

Sign-in​

Accounts are operator sessions (backend/app/platform/auth.py, api_auth.py). VAAZHVU_AUTH picks the mode:

  • open (default, local dev): anonymous requests act with default_role (env VAAZHVU_DEFAULT_ROLE), which is viewer: they can watch and call the emergency line, but must sign in at /login to act. For a quick local demo set VAAZHVU_DEFAULT_ROLE=supervisor in .env; never do that on a reachable deployment. A session or API key wins when present.
  • required: anonymous requests are public. They can call the emergency line (SOS, SMS, app, voice with a token from POST /api/ops/voice/token) and nothing else. Staff sign in at /login; crews sign in on /ambulance or in the crew app.
WhoHow they authenticateWhat it is bound to
Dispatcher, supervisor, ER, agencies/login: HttpOnly vz_session cookie (SameSite=Strict, Secure over HTTPS)their account's role
Ambulance crew, web (/ambulance)sign-in with unit_id: cookiethat unit: require_unit() refuses writes to any other unit, and vitals for any other incident
Ambulance crew, iOS (VaazhvuCrew)POST /api/auth/login {client: "native"} returns the token; kept in the keychain, sent as Authorization: Bearerthe unit picked next (POST /api/auth/unit)
Caller, web /caller and iOS Vaazhvuno account: every intake returns a caller_token for that incidentX-Caller-Token (or ?ct=) opens that one incident's tracking, chat and cancel (caller_or())
Citizen with an account (optional)POST /api/auth/register (phone, name, password), then /login or the app with the phone numbertheir own reports; every call carries their profile (blood group, conditions, emergency contact) to the crew
ER staff (/hospital)/login on an account with role hospital (the board asks for a sign-in in every mode)the one hospital an administrator linked it to: require_hospital() refuses any other, and case routes answer only for that hospital's patients. Dispatchers, administrators and supervisors (er.read) may open any board to oversee it
Administrator (/admin)/login on an account with role admin (or a supervisor)staff accounts, hospitals, callers, tiers

Create the first supervisor with python -m app.platform.auth create --username sup1 --role supervisor (inside the api container); a hospital account with --role hospital --hospital <id>, or one account per receiving hospital at once with python -m app.platform.auth hospitals --all (make hospital-accounts; --hospital <id> for some, --reset for new passwords): usernames er-<name>-<id tail>, random passwords written once to var/hospital_accounts.csv (owner-only, git-ignored). Administrators then manage accounts in /admin; an admin may create the roles listed in its grants (never supervisor or admin). Supervisors then add crews (role: crew) via POST /api/ops/operators. Set VAAZHVU_SESSION_SECRET to pin the signing secret; without it, one is generated and kept in the database. Writes held in a crew outbox while signed out (401/403) are kept and sent after the crew signs in again.

Prank and abusive callers​

Most calls are not emergencies, and an unclear or accidental call is fine: calling again is what we want. Only pranks and abuse count against a caller (platform/callers.py, config/platform.yaml callers):

  1. Mark: when closing a call the dispatcher records what it was (genuine, duplicate, no patient, accidental, advice, prank, abusive).
  2. Flag: one prank or abusive report in 30 days puts the caller on watch, two make them flagged. The next call is still taken and triaged at once; it shows the flag, and policy rule R14 asks a dispatcher to authorise the dispatch unless the call is likely critical (then it goes now and is checked after). Intake is never rate limited or refused.
  3. Report: the admin portal lists callers by status with each call's outcome; a supervisor can clear, watch or flag a caller by hand.
  4. Prune: closed prank incidents older than prune_after_days can be deleted from the portal (auto_prune: true does it on the retention schedule). The audit trail and the report stay.

Callers are keyed by an HMAC of the phone number (else the account, else the app's device id); staff see only a masked label like ••••3210.

The X-Vaazhvu-Role header, which the console sets from "Act as…", can only narrow a role, never widen it. A wallboard can run as viewer; nothing can escalate itself. The server checks permissions on every endpoint, and the UI explains unavailable actions instead of hiding them silently.

X-Vaazhvu-Actor names an anonymous operator for attribution. A signed-in session ignores it: the account names the operator.

Integrations​

API keys​

Supervisors create keys in Integrations → API keys with explicit scopes, which can't exceed the creator's own permissions. A key looks like vz_<prefix>_<secret> and is shown once; only its hash is stored. Use it as:

curl -H "Authorization: Bearer vz_1a2b3c4d_…" https://vaazhvu.example/api/ops/state

Keys are rate-limited per key, record last_used, and can be revoked at once.

For an MCP client (AI access and the Copilot) that should run simulations, give the key incident.read hospital.read sim.run intake.create. A key with incident.read hospital.read only can ask questions but not simulate.

Webhooks​

Integrations → Webhooks subscribes an HTTP(S) endpoint to event patterns (incident.*, dispatch.approved, *…). Each persisted bus event that matches is POSTed as:

{"id": "dlv_…", "webhook_id": "whk_…", "event": {"event_id": "evt_…", "event_type": "dispatch.approved", "seq": 812,
"timestamp": 1727857000.1, "incident_id": "INC-…", "source": "ops", "schema_version": "2.0", "payload": {…}}}

Headers: Vaazhvu-Event, Vaazhvu-Delivery, Idempotency-Key (the event id; the same on retries, so receivers can dedupe), and Vaazhvu-Signature.

Verifying the webhook signature. Vaazhvu-Signature: t=<unix seconds>,v1=<hex> where v1 = HMAC-SHA256(secret, "<t>.<raw body>"). Reject requests more than 5 minutes old.

import hashlib, hmac, time

def verify(secret: str, body: bytes, header: str) -> bool:
parts = dict(p.split("=", 1) for p in header.split(","))
if abs(time.time() - int(parts["t"])) > 300:
return False
mac = hmac.new(secret.encode(), f"{parts['t']}.".encode() + body, hashlib.sha256).hexdigest()
return hmac.compare_digest(mac, parts["v1"])

Delivery is at least once:

  • A 2xx answer is a success. Anything else is retried after 10 s, 1 min, 5 min, 30 min and 2 h, then marked failed.
  • A webhook auto-disables after 20 consecutive failures. Resuming it resets the counter.
  • Send test posts a signed webhook.ping. Every delivery can be inspected and retried by hand.
  • Pending deliveries survive restarts (they live in SQLite).
  • Telemetry (fleet.positions), presence and webhook.* are never delivered.

SSRF protection. Receiver URLs must be http(s) and carry no credentials. Their resolved address is checked when the webhook is created and again before every attempt: private, loopback, link-local and reserved ranges are refused. Redirects are not followed. For local development set VAAZHVU_WEBHOOK_ALLOW_PRIVATE=1; in production set webhooks.require_https: true.

Exports​

EndpointFormats
GET /api/ops/export/incidents?format=&status=&since=csv, json, ndjson
GET /api/ops/export/events?format=&incident_id=&after=ndjson, csv (streamed, paged)
GET /api/ops/export/audit?format=csv, json
GET /api/ops/incidents/{id}/export?format=md (report), json (full record)
GET /api/ops/incidents/{id}/fhirFHIR R4 transaction bundle

CSV cells that start with =, +, -, @, tab or CR get a leading ', so a spreadsheet won't execute them (formula injection).

API conventions​

  • Errors are RFC 9457 application/problem+json:

    {"type": "/docs/errors#validation_failed", "title": "Unprocessable Content", "status": 422, "detail": "text: String should have at least 1 character",
    "instance": "/api/ops/intake/text", "code": "validation_failed", "request_id": "…", "errors": [{"field": "text", "message": "…", "type": "string_too_short"}]}

    detail is always readable. errors lets forms mark the exact field. A 5xx never includes a stack trace; quote the request_id.

  • Request IDs. Send X-Request-ID (or let the server make one). It comes back on the response and appears on every log line for that request.

  • Rate limits are token buckets per API key, or per IP, for each class: read, write, upload, telemetry and share. Emergency intake (/api/ops/intake/*) is never rate limited. Responses carry RateLimit-Limit, RateLimit-Remaining and RateLimit-Policy. Over the limit, the server answers 429 with Retry-After. The web client retries reads with backoff and honours Retry-After. Configure the buckets in config/platform.yaml; VAAZHVU_RATE_LIMIT=0 disables them.

  • Body limits. JSON bodies are limited to 1 MiB and uploads to 15 MiB plus overhead (413).

  • Realtime uses the SSE stream (GET /api/ops/stream). It resumes from Last-Event-ID. Platform events (comment.*, attachment.*, share.*, presence.updated) arrive on it alongside operations events.

Security​

  • Security headers on every response:
    • Content-Security-Policy on HTML: same-origin scripts only; map tiles, fonts, frame-ancestors 'none', object-src 'none'
    • X-Content-Type-Options: nosniff
    • X-Frame-Options: DENY
    • Referrer-Policy
    • a Permissions-Policy allowing only geolocation, microphone and camera on the same origin
    • Cross-Origin-Opener-Policy and Cross-Origin-Resource-Policy
    • HSTS over HTTPS
    • Cache-Control: no-store on API responses
  • CORS is off unless VAAZHVU_CORS_ORIGINS lists origins.
  • Input validation. Every request model has bounded lengths and ranges. Free text is never rendered as HTML: docs use a safe Markdown renderer that builds elements, not HTML.
  • Secrets. Share tokens and API keys are stored hashed and compared in constant time. Webhook secrets are shown once and can be rotated.
  • Uploads. File types come from content sniffing against an allow-list. Filenames are sanitised. Stored blobs are content-addressed. Downloads carry Content-Disposition and a sandbox CSP.
  • Audit. Every human action is written to the audit log: approvals, overrides, notes, files, shares, keys and webhook changes.

Observability​

  • GET /metrics (Prometheus):
    • vaazhvu_http_requests_total{method,route,status}
    • vaazhvu_http_request_duration_seconds (histogram, by route template)
    • vaazhvu_http_inflight_requests
    • vaazhvu_sse_clients
    • vaazhvu_events_published_total{type}
    • vaazhvu_rate_limited_total{bucket}
    • vaazhvu_webhook_deliveries_total{result} and vaazhvu_webhook_delivery_seconds
    • vaazhvu_upload_bytes_total
    • vaazhvu_client_errors_total{kind}
    • vaazhvu_client_web_vital{metric}
  • GET /api/ready checks the database and controller, the webhook worker and its backlog. It returns 503 when not ready. GET /api/health is liveness.
  • Logs carry the request id: [<id>] in text logs. VAAZHVU_LOG_FORMAT=json switches to structured JSON with an http block (method, route, status, ms).
  • Responses carry Server-Timing: app;dur=….
  • Browser errors. Uncaught errors, rejected promises and React render errors are reported with the component name. Each panel has its own error boundary, so one broken panel never takes down the console.

Scaling notes​

  • Stateless edge. Rate-limit buckets and presence are in memory per process. For more than one API replica, move both to Redis; the interfaces are TokenBuckets.take and Platform.heartbeat / roster. Event fan-out across replicas already exists through the NATS mirror.
  • Storage. The platform tables live beside the event log in SQLite (WAL) and map 1:1 to Postgres. Analytics uses indexed SQL rollups (events(ts)). Exports stream and page through the log instead of loading it whole.
  • Blobs. Attachments are content-addressed on disk (VAAZHVU_UPLOAD_DIR). Point that directory at an object store mount, or swap Platform.save_blob for S3.
  • Webhooks. The worker drains a durable SQLite queue. A dedicated worker process can run the same WebhookDispatcher against the shared database.

Configuration​

VariableDefaultMeaning
VAAZHVU_DEFAULT_ROLEsupervisor (config/platform.yaml)Role of a browser with no narrower role
VAAZHVU_RATE_LIMIT10 disables rate limiting
VAAZHVU_TRUST_PROXY01 = take the client IP from X-Forwarded-For (only behind a trusted proxy)
VAAZHVU_CORS_ORIGINS—Comma-separated allowed origins
VAAZHVU_WEBHOOK_ALLOW_PRIVATE01 = allow webhook receivers on localhost or a private network
VAAZHVU_UPLOAD_DIRvar/uploadsAttachment blob store
VAAZHVU_LOG_FORMATtextjson for structured logs

Roles, rate limits, upload types and sizes, the webhook retry schedule, retention and the CSP sources are all in config/platform.yaml.

Retention (retention:): telemetry (30 days), finished webhook deliveries (14 days) and stale drafts (30 days) are pruned at startup and then at most hourly, driven by the client telemetry beacon (metric vaazhvu_retention_pruned_rows_total). The clinical record (events, audit, incidents, vitals, comments, attachments) is never pruned automatically; how long to keep it is a records-policy decision.

Retried writes apply once. A write sent with an Idempotency-Key header (8–128 of A-Za-z0-9._:-) and repeated with the same key gets the first 2xx response back (header Idempotent-Replayed: true) instead of running again; a concurrent duplicate waits for the first. Responses are kept for 24 hours in the SQLite idempotency table (migration 11), behind a bounded in-memory layer (observability/middleware.py ReplayCache), so a retry that lands after a server restart is still applied once; with no live store (no controller started) the cache is memory only. The offline outboxes rely on it: the web's one queue (frontend/src/platform/outbox.js, used by the crew app and by queue: true writes) and the iOS Outbox send one key per queued write on every attempt. Both are bounded: at most 500 writes, none older than 24 hours, only the latest 50 GPS fixes; a full browser store drops GPS fixes first and reports it (vz:outbox-error).

/api/asr and /api/translate need the nlp.run permission (supervisor, dispatcher, call-taker): they run compute-heavy models on arbitrary input.