Commit graph

129 commits

Author SHA1 Message Date
Daniel Onyejesi
53a486dbd5 Fix: bump SW cache to v12, switch JS/CSS to network-first
Old pedscribe-v11 cache was serving stale admin.js to browsers
even after server updates. New cache name forces old SW to
deactivate and all clients to get fresh JS on next load.
Also switch JS/CSS from stale-while-revalidate to network-first
so code fixes are picked up immediately.
2026-03-29 20:02:34 -04:00
Daniel Onyejesi
0ca4ba1c04 Fix model management: empty LiteLLM list, always reload panel, clear-all
- LITELLM_MODELS = [] — no hardcoded models, global selector now only
  shows what admin has actually added via Search API
- getAvailableModelsWithOverrides: for LiteLLM returns only custom list
- Remove toggle safety check — admin can disable any/all models freely
- Admin panel always reloads on tab open (was cached, showing stale data)
- Add 'Clear all models' button for LiteLLM to wipe and start fresh
- Add POST /config/models/clear-all endpoint
2026-03-29 19:32:09 -04:00
Daniel Onyejesi
90fccbe58d Add LiteLLM STT and TTS support
- TRANSCRIBE_PROVIDER=litellm routes audio to LiteLLM /audio/transcriptions
- TTS_PROVIDER=litellm routes to LiteLLM /audio/speech
- Both auto-detect when LITELLM_API_BASE is set (no extra config needed)
- LITELLM_STT_MODEL (default: whisper-1), LITELLM_TTS_MODEL (default: tts-1)
- LITELLM_TTS_VOICE (default: alloy) — alloy/echo/fable/onyx/nova/shimmer
- ElevenLabs still works if ELEVENLABS_API_KEY is set and TTS_PROVIDER=elevenlabs
- Health endpoint now reports tts provider
2026-03-29 19:11:16 -04:00
Daniel Onyejesi
3cd7268e5d Fix admin model management: route ordering, LiteLLM built-ins, auto-select
- Root cause: PUT /config/:key(*) wildcard was registered before
  /config/models/toggle and /config/models/default, intercepting them
  and returning "value is required" (body had modelId not value)
- Fix: move all model-specific PUT routes before the wildcard
- LiteLLM: return empty built-in list with discovery hint (hardcoded
  models don't match user's proxy — must use Search API)
- After adding a discovered model: auto-select it in the default dropdown
- GET /config/models now returns defaultModel so dropdown pre-selects it
2026-03-29 18:42:09 -04:00
Daniel Onyejesi
f8dd4d9f86 v9.1: Add Google Vertex AI + LiteLLM support, admin model management panel
- Add Vertex AI provider (Gemini models via @google-cloud/vertexai SDK)
- Add LiteLLM proxy support (OpenAI-compatible, routes to any provider)
- Admin panel: model search/discover from provider API, enable/disable, custom models, set default
- New endpoints: /config/models/discover, /config/models/add-discovered, /config/models/default
- Updated models.js with VERTEX_MODELS and LITELLM_MODELS lists
- Updated health endpoint with vertex + litellm status
2026-03-29 10:32:45 -04:00
ifedan-ed
cfdb008208 Fix APK crash: replace XML splash with PNG, add real mipmap launcher icons
Some checks failed
Build TWA APK / build-apk (push) Has been cancelled
Build & Push Docker Image / build (push) Has been cancelled
Root cause: TWA LauncherActivity.onCreate calls Bitmap.createBitmap on the
splash drawable — the XML layer-list with only a color fill had 0x0 intrinsic
dimensions, causing IllegalArgumentException: "width and height must be > 0".

Fixes:
- Replace splash.xml with splash.png (384x384 blue circle with P logo)
- Add proper PNG launcher icons at all 5 density buckets (mdpi through xxxhdpi)
- Change android:icon from @drawable to @mipmap for proper icon resolution
2026-03-29 11:07:10 +00:00
ifedan-ed
49b5a49999 Server-side audio backups with compression, viewable AI corrections
Audio Backups:
- New audio_backups table in PostgreSQL (bytea, gzip compressed)
- POST /api/audio-backups — upload with gzip compression (level 6)
- GET /api/audio-backups — list user's backups
- GET /api/audio-backups/:id/audio — download decompressed audio
- DELETE /api/audio-backups/:id — delete backup
- Auto-cleanup every hour (24h expiry)
- Frontend saves to server first, falls back to IndexedDB
- Settings shows source badge (server/local) per backup

AI Corrections:
- Corrections list is now expandable — click to view original vs corrected
- Shows red "Original" and green "Corrected to" sections
- Click arrow to expand/collapse each correction
- Date shown on each correction
2026-03-29 10:56:31 +00:00
ifedan-ed
8d963ab7b5 Fix Android crash: use resource references for TWA colors instead of inline hex
The TWA LauncherActivity crashed with Resources$NotFoundException (0xffffffff)
because android:value with hex color strings is not supported by
androidbrowserhelper — it expects android:resource pointing to color resources.

- Created res/values/colors.xml with all app colors
- Changed AndroidManifest.xml to use android:resource="@color/..."
- Updated styles.xml to reference color resources
2026-03-29 10:47:27 +00:00
ifedan-ed
3d503ba309 Security: remove auth debug logging that exposed emails and responses
Removed console.log statements in auth.js that logged email addresses
and auth API responses to browser console. Final cleanup for v9.
2026-03-29 10:41:35 +00:00
ifedan-ed
0e350b8cad Remove admin model management panel — models use global selector instead
The admin model management (enable/disable, custom models, default override)
had persistent rendering issues. Removed the UI panel — models are managed
via the global model selector in the header, which works reliably. Backend
API endpoints for model config are retained for future use.
2026-03-29 02:30:29 +00:00
ifedan-ed
bf89cad954 Zero-config speech: skip upload when no transcription API, use browser speech directly
- Add GET /api/transcribe/status endpoint — returns whether any server
  transcription provider (Whisper/AWS/Local) is configured
- Frontend checks status on login via checkTranscribeStatus()
- When no provider configured: recording stops instantly, keeps live
  Web Speech API text, shows friendly toast — no error, no upload wait
- Works in encounter, dictation, and SOAP tabs
- App now works fully out-of-the-box with just an AI provider key
2026-03-29 02:09:53 +00:00
ifedan-ed
51fc818e4a Fix: admin models loading, clear refine/instructions on New, bigger HPI areas, unique labels
- Admin models: reset modelsLoaded flag on error so retry works
- Admin default model: fix redundant fetch race condition
- clearTab: now clears refine inputs, instructions, and demographic fields
- Encounter/dictation clear buttons: also clear refine input
- SOAP: instructions textarea already cleared by clearTab (soap-instructions)
- Encounter HPI: bigger transcript (400px) and output (600px) text areas
- Unique label enforcement: 409 error if saving with duplicate label
2026-03-29 01:35:45 +00:00
ifedan-ed
50492ff30c Revert chunk size to 8KB — larger sizes cause AWS deserialization errors
Keep 8KB CHUNK_SIZE (proven stable) but replace 10ms setTimeout delay
with a microtask break every 16 chunks. This avoids the AWS SDK
"Deserialization error: inspect {error}.\$response" while still
eliminating the ~1.25s/MB artificial delay from the old 10ms sleep.
2026-03-29 01:21:43 +00:00
ifedan-ed
d52c0fba38 Optimize transcription speed: remove artificial delays, add timing
- AWS Transcribe: remove 10ms delay between chunks (was adding ~1.25s/MB),
  increase chunk size from 8KB to 32KB (AWS max per frame)
- Add detailed timing logs (ffmpeg, streaming, total) for diagnostics
- OpenAI Whisper: use response_format='text' for faster response parsing
- Frontend: show transcription time in toast, request 16kHz sample rate,
  increase bitrate to 32kbps Opus (better quality, still small files)
- Return duration in API response for all providers
2026-03-29 00:59:30 +00:00
ifedan-ed
eb18a71fa4 Fix APK signing: use apksigner directly instead of broken r0adkll action
The r0adkll/sign-android-release@v1 hardcodes build-tools 29.0.3 which
isn't available. Now uses apksigner from the latest installed build-tools
directly with zipalign + sign + verify steps.
2026-03-29 00:51:42 +00:00
ifedan-ed
8a0e59d1ce Fix APK build: add appcompat dependency for Theme.AppCompat 2026-03-29 00:46:51 +00:00
ifedan-ed
55e18aacb7 Fix APK build: use Gradle setup action, generate proper wrapper
The gradlew stub and missing gradle-wrapper.jar caused CI build to fail.
Now uses gradle/actions/setup-gradle@v4 to install Gradle, then generates
wrapper before building. Also renames signed APK and uploads both signed
and unsigned to GitHub Releases.
2026-03-29 00:41:42 +00:00
ifedan-ed
c03f9cd47b Add SHA256 fingerprint to assetlinks.json for TWA domain verification 2026-03-29 00:32:58 +00:00
ifedan-ed
1d62d55ed4 v9: APK hardening, service worker caching, admin model validation, Docker v9
- APK: Add WAKE_LOCK, BOOT_COMPLETED, ACCESS_NETWORK_STATE permissions
- APK: Disable allowBackup for medical data security
- APK: AudioRecordingService now acquires wake lock, has stop action in notification
- Serve /.well-known/assetlinks.json for TWA domain verification
- Service worker: cache app shell, stale-while-revalidate for assets, network-first for API
- Admin model management: validate model ID format, prevent built-in conflicts, audit toggle actions, prevent disabling all models
- Bump version to v9.0.0, Docker tag to v9
2026-03-28 23:53:39 +00:00
Daniel Onyejesi
6f671b3f47 Add admin model management dashboard — enable/disable, custom models, default override
- Full model management UI in admin panel: toggle models on/off, add custom
  model IDs (any OpenRouter/Bedrock ID), set admin-configured default model
- /api/models now returns admin-set default model, frontend respects it
- Toggle switch CSS for clean enable/disable UX
- Backend already had the API endpoints, this adds the missing UI
2026-03-28 22:07:16 +00:00
Daniel Onyejesi
e33cd4dc60 v10: Local Whisper transcription, bigger text areas, flexible AI memory
- Add local Whisper (whisper.cpp / faster-whisper) as transcription provider
  Set TRANSCRIBE_PROVIDER=local with configurable model size and binary path
- Upgrade all refine/instruction inputs to resizable textareas across
  encounter, dictation, hospital course, chart review, well visit, sick visit
- Make AI memory injection flexible: physician preferences and corrections
  are now actively applied (not just "formatting reference"), while still
  overridable by current prompt instructions
2026-03-28 22:00:30 +00:00
Daniel Onyejesi
933d406d93 Set TWA default host to peds.danvics.com, simplify APK workflow 2026-03-28 21:12:25 +00:00
Daniel Onyejesi
5f066bb760 v9: Major feature update — audio backup, SOAP save, Dragon memory, S3 docs, CI/CD, APK
Phase 1 — Critical Fixes:
- Fix SOAP instructions not clearing on Clear button
- Show transcription provider (AWS/OpenAI) in UI toast
- Fix silent transcription failures in dictation and SOAP modules
- Add IndexedDB audio backup system (24hr retention, retry from Settings)
- Prevent duplicate encounter saves with idempotency keys
- Add Save/Load/New bar to SOAP note generator

Phase 2 — Features:
- Dragon-like AI memory: auto-track user corrections, inject into prompts
- Per-section template categories (SOAP, HPI, well visit, sick visit)
- Bigger textarea for SOAP instructions
- S3 document upload/management (AWS S3, Backblaze B2, MinIO compatible)
- Faster transcription via lower bitrate recording (16kbps opus)

Phase 3 — APK & CI/CD:
- GitHub Actions: Docker build+push on version tags
- GitHub Actions: TWA APK build for Obtainium auto-updates
- Android TWA project with foreground service for background recording
- Enhanced PWA manifest with shortcuts and maskable icons
2026-03-28 21:08:32 +00:00
Daniel Onyejesi
15494b4675 Security fixes: remove SSO token from URL, add prompt boundaries
- OIDC callback now passes only ?sso=ok flag, token stays in
  httpOnly cookie (prevents token leaking to logs/referrer/history)
- Frontend auth.js uses cookie-based auth for SSO flow
- Add [PHYSICIAN TEMPLATES] boundary markers around physicianMemories
  in all 5 generation routes to mitigate prompt injection
- Consistent boundary format across wellVisit, sickVisit, hpi, soap,
  hospitalCourse
2026-03-25 19:25:49 -04:00
Daniel Onyejesi
4194715e5c Remove Firefox speech notice, fix auth.js SSO flow race condition
- Remove Firefox speech recognition notice (not needed)
- Fix missing closing brace that made speech recognition unreachable
- Fix auth.js SSO token handling to prevent brief auth screen flash
2026-03-25 19:04:20 -04:00
Daniel Onyejesi
e776487cb1 Add OpenID Connect SSO + Firefox speech notice
OIDC/SSO:
- New /api/auth/oidc route with PKCE for secure authorization
- Supports Azure AD, Okta, Keycloak, PocketID, Google, any OIDC provider
- Admin configurable: issuer, client ID/secret, button label
- Option to disable local auth (force SSO only)
- Auto-creates users on first SSO login, links existing by email
- SSO button on login page, hidden until admin enables OIDC

Firefox:
- Show info toast on first recording that live preview requires
  Chrome/Edge; server-side transcription still works in all browsers
2026-03-25 18:54:44 -04:00
Daniel Onyejesi
0268d37151 Fix AWS Transcribe: reduce chunk size from 32KB to 8KB
AWS Transcribe rejects audio event frames over ~16KB with a
cryptic "Deserialization error" / "Your stream is too big" message
hidden inside the SDK error object. Reducing to 8KB per chunk
fixes both Standard and Medical Transcribe streaming.
2026-03-25 18:41:05 -04:00
Daniel Onyejesi
ad7a08e4c5 Improve Transcribe error diagnostics, add minimum audio check
- Log $response status/headers/body on deserialization errors
- Add 10ms delay between audio chunks to prevent stream overload
- Skip transcription if audio < 0.5s (too short for recognition)
- Cleaner error logging with dedicated logTranscribeError helper
2026-03-25 18:29:48 -04:00
Daniel Onyejesi
21d960d56e Add detailed error logging for Transcribe Medical failures
Log error name, AWS metadata, and root cause to diagnose
the "non-retryable streaming request" error.
2026-03-25 18:24:37 -04:00
Daniel Onyejesi
dbda2ad913 Add Medical→Standard fallback and better error logging for AWS Transcribe
When Medical Transcribe fails (wrong IAM permissions, region not
supported), automatically falls back to Standard Transcribe instead
of returning an error. Logs the specific failure reason.
2026-03-25 18:10:21 -04:00
Daniel Onyejesi
168f67adee Fix missing error handling in nextcloud disconnect, update docker-compose to v8
- Add try-catch to /nextcloud/disconnect route (was crashing on DB errors)
- Update docker-compose.yml image tag from v7 to v8
- Remove unused SESSION_SECRET from .env.example
2026-03-25 17:53:48 -04:00
Daniel Onyejesi
79f9fefb52 Wire physician memories/templates into all AI generation routes
Previously only well-visit and sick-visit used saved physician
templates. Now HPI encounter, HPI dictation, SOAP, and hospital
course all fetch getUserMemoryContext() and pass physicianMemories
to the backend so the AI learns from saved templates/preferences.
2026-03-25 17:35:30 -04:00
Daniel Onyejesi
70d2f34770 v8.0.0: Fix speech recognition repeating text, enable AWS Transcribe Medical
- Add deduplication logic to prevent Chrome Speech API from repeating
  sentences during long recording sessions (all 4 recording modules)
- Enable AWS Transcribe Medical with PRIMARYCARE specialty in .env
- Bump version to 8.0.0
2026-03-25 17:24:28 -04:00
Daniel Onyejesi
3da61c455e Add ffmpeg audio conversion fallback for AWS Transcribe
- transcribeAWS.js: convert browser WebM/Opus → PCM 16kHz mono via
  ffmpeg before sending to AWS Transcribe — PCM is unambiguous and
  most reliable; gracefully falls back to ogg-opus if ffmpeg absent
- Dockerfile: install ffmpeg (apk add ffmpeg) so Docker image works
  out of the box with AWS Transcribe
- README: document Amazon Transcribe setup, ffmpeg requirement,
  Transcribe Medical specialty options, and env vars reference
2026-03-25 20:35:24 +00:00
Daniel Onyejesi
767d28fc54 Add Amazon Transcribe streaming (no S3) with Medical specialty support
- New src/utils/transcribeAWS.js: streams audio directly to AWS
  Transcribe without requiring an S3 bucket
- Supports AWS_TRANSCRIBE_MEDICAL=true for Transcribe Medical
  (better clinical accuracy: drug names, diagnoses, procedures)
- AWS_TRANSCRIBE_SPECIALTY configures specialty (default PRIMARYCARE)
- transcribe.js auto-selects AWS when AWS_BEDROCK_REGION is set,
  or can be forced with TRANSCRIBE_PROVIDER=aws|openai
- Falls back to OpenAI Whisper when AWS is not configured
- Add @aws-sdk/client-transcribe-streaming as optional dependency
- Update .env.example with transcription configuration docs
2026-03-25 20:26:10 +00:00
Daniel Onyejesi
f397ca7725 v7: fix speech recognition repetition, HTML injection, long-session guard
- Fix word repetition: use sessionFinals pattern so each browser SR
  session starts fresh; no overlap when recognition auto-restarts
- Fix HTML injection / '>' parse error: escape < > & in live transcript
  innerHTML before inserting speech recognition text
- Add 24 MB blob guard: fall back to live SR transcript if audio file
  is too large for Whisper API (long sessions)
- Bump version to 7.0.0, update docker-compose image tag to v7
2026-03-25 20:07:10 +00:00
Daniel Onyejesi
689d5e9028 Expand DEVELOPER_GUIDE with detailed architecture, DB layer, file descriptions
- Added request flow walkthrough, AI provider selection logic
- Documented database layer (raw pg, no ORM) with helper methods
- Expanded directory structure with detailed per-file descriptions
- Expanded frontend JS descriptions (what each file does)
- Rewrote PDF section with current 50k char limit, supported types
- Updated version history through v6.0
2026-03-24 19:30:01 -04:00
Daniel Onyejesi
46ddfac358 Increase PDF/doc context to 50k chars, raise maxTokens ceiling to 8k
Supports large PDFs (~30 pages) from upload and Nextcloud.
maxTokens is a ceiling, not a target — short topics still get short responses.
2026-03-24 19:22:51 -04:00
Daniel Onyejesi
27d20c962f Re-add vendor model Opus 4.6, update DEVELOPER_GUIDE with logs/Bedrock docs
- Re-added Opus 4.6 (JSON sanitizer now handles its output)
- Added Logs & Debugging section with docker logs commands and prefixes
- Added Bedrock Model Notes (inference profiles, maxTokens, JSON sanitization)
- Updated version history through v5.8
- Updated rate limiting docs, build/push process, current image tag
2026-03-24 19:14:00 -04:00
Daniel Onyejesi
0e01f94247 Fix JSON parse for Sonnet 4.6: escape literal newlines in strings
Sonnet 4.6 outputs literal newline characters inside JSON string
values (e.g. in HTML body field) instead of \n escape sequences.
Added sanitizeJsonString that walks the string character by character
and escapes unescaped control chars inside quoted values.
2026-03-24 19:01:16 -04:00
Daniel Onyejesi
24ccb402b0 Remove vendor model Opus 4.6 (returns invalid JSON via Bedrock) 2026-03-24 18:43:28 -04:00
Daniel Onyejesi
cd9071a27d Re-add Qwen3 235B (works in us-east-1 despite docs) 2026-03-24 18:35:51 -04:00
Daniel Onyejesi
208ce27fa4 Comprehensive Bedrock fix: inference profiles + maxTokens clamping
- ALL models that need inference profiles now use us. prefix IDs:
  Anthropic (all 8), Nova (3), Meta Llama (3), DeepSeek R1, Writer
- Models with low max output tokens (Cohere 4096, Jamba 4096) now
  have maxOut field; callBedrock clamps maxTokens automatically
- Removed Qwen3 235B (no us-east-1 support, no inference profile)
- Added better debug logging for response block structure
2026-03-24 18:26:43 -04:00
Daniel Onyejesi
a43468fd4e Fix Anthropic models: use cross-region inference profiles (us. prefix)
Opus 4.6, Opus 4.5, Sonnet 4.6, Haiku 4.5 do NOT support direct
on-demand invocation — they require cross-region inference profile IDs
(us.anthropic.* prefix). Updated all affected bedrockIds. Also fixed
isAnthropic check to handle us.anthropic.* prefix.

Sonnet 4.5, Sonnet 4, 3.5 Haiku also updated to use profiles for
consistency (profiles work everywhere, direct IDs are limited).
2026-03-24 18:17:36 -04:00
Daniel Onyejesi
e4faf07a6d Fix Opus 4.6 thinking blocks, re-add Amazon Nova models
- Opus 4.6 returns multiple content blocks (thinking + text); was only
  reading content[0] which was the thinking block (just '{')
- Now iterates all blocks and extracts only type:'text' blocks
- Added debug logging for Bedrock response structure
- Re-added Nova Pro, Nova Lite, Nova Micro with correct region metadata
2026-03-24 18:05:27 -04:00
Daniel Onyejesi
8f0f9ff9e6 Fix AI invalid JSON: add system prompt + robust JSON extraction
Opus 4.6 and other large models add preamble/thinking text before
JSON output. Fix: add system message enforcing JSON-only, strip
leading text before first {, trim trailing text after last }, and
log raw output on parse failure for debugging.
2026-03-24 17:52:49 -04:00
Daniel Onyejesi
a0dec0d1d7 Fix Bedrock models: remove Nova (no on-demand), add region filtering
- Removed Amazon Nova models (not available for on-demand invocation)
- Replaced DeepSeek V3 with V3.2 (correct model ID)
- Removed Mistral Large 24.07 (us-west-2 only), added Magistral Small
- Added vendor model Opus 4.1, Writer Palmyra X5, Qwen3, Command R
- Each model now has region metadata; getAvailableModels() filters
  to only show models available in the configured AWS_BEDROCK_REGION
- Fixes "on-demand throughput not allowed" and region mismatch errors
2026-03-24 17:45:36 -04:00
Daniel Onyejesi
9437da2c99 Add resend verification link on login + rate limit (3/15min) 2026-03-24 14:14:42 -04:00
Daniel Onyejesi
114bc4e7cd Fix CMS button clickability, replace AI topic input with context box
- Add type="button" to all CMS action buttons to prevent default submit
- Change overflow:hidden to overflow:visible on .cms-main to prevent clipping
- Add z-index to .cms-editor-actions for reliable click targeting
- Replace AI "Topic" text input with a descriptive textarea context box
  so users can tell AI what to generate (AI creates its own title)
- Rename AI tab from "By Topic" to "Describe Content"
2026-03-24 11:52:02 -04:00
Daniel Onyejesi
3863a9c8d1 Fix login screen not showing on sign-out
Remove !important from #auth-screen CSS so the inline style set by
exitApp() can override it and display the login form after logout.
2026-03-24 11:24:26 -04:00