How mardan-shah/voice-app works
1. Overall shape
- This is a full-stack Next.js App Router application that splits into a browser UI, Next.js server routes, Supabase-backed persistence/auth, and a remote Ollama-compatible AI service.
- The key architectural idea is a strict separation between public browser code and trusted server code.
2. Primary user-facing areas
- The app has two route groups: (auth) for login/signup screens and (main) for the protected product area.
- The main workspace includes chat, history, personality settings, and voice settings. These are all browser-rendered pages, not separate services.
3. Authentication boundary
- Authentication is handled by Supabase Auth with email/password and Google OAuth.
- Browser-side auth uses the public Supabase key, while server-side privileged actions use a server-only Supabase secret key.
- A Next.js Proxy layer refreshes and validates session cookies, but actual privileged authorization is still enforced on API routes by verifying the bearer token.
4. Chat as the central workflow
- The chat page is the main orchestration point for the product.
- The browser collects a typed message or microphone transcript, attaches the current Supabase access token, and sends it to PUT /api/chat.
- The UI is designed for streaming incremental response fragments rather than waiting for a full completion.
5. Server-side chat pipeline
- The chat route validates the caller by checking the Supabase access token, then uses the trusted user identity for all persistence.
- It optionally loads semantic memories, builds the prompt from personality settings and recent history, calls the remote AI endpoint, streams tokens back as SSE, and finally persists the completed assistant message and emotion.
- This route is the main trust boundary because it can write data with elevated privileges.
6. AI inference integration
- The server talks to a remote Fieldwaves AI gateway that exposes Ollama-compatible generation and embedding endpoints.
- Text generation uses a chat model (gemma4:e2b by default), while semantic memory uses an embedding model (nomic-embed-text).
- Upstream AI output is NDJSON, which the server converts into Server-Sent Events for the browser.
7. Long-term semantic memory
- Memory is stored in Supabase Postgres using the pgvector extension.
- Each user message can be embedded and stored in a message_embeddings table, then later retrieved through a PostgreSQL RPC that ranks similarity with cosine distance.
- Memory retrieval is user-scoped and optional: if embeddings fail, chat still works without memory recall.
8. Database and ownership model
- Supabase Postgres stores several user-owned tables: profile/user row, AI settings, voice settings, chat history, emotion records, and message embeddings.
- Row Level Security restricts browser-accessible queries to the current user via auth.uid().
- Foreign keys are configured with cascade delete so account deletion removes dependent rows.
9. Browser state and client modules
- The browser side uses Zustand stores for auth projection, active chat state, and settings.
- Custom hooks separate concerns: useAuth handles session projection and redirects, useChat handles streaming chat behavior, usePersonality saves persona settings, and useVoice manages speech lifecycle.
- UI components are organized by feature area: chat, layout, personality, and small reusable UI primitives.
10. Voice subsystem
- Voice features are entirely browser-native: speech recognition via SpeechRecognition/webkitSpeechRecognition, and speech output via speechSynthesis.
- The server does not receive raw audio; it only receives the transcript text after recognition.
- Voice settings are persisted per user and control the browser speech synthesis parameters.
11. Emotion tagging
- Emotion classification is implemented as part of prompt/response handling, not as a separate ML service.
- The model is instructed to append an emotion tag, the server parses it, strips it from visible content, stores it, and exposes the latest emotion in the final streamed result.
- Emotion data is therefore a lightweight metadata layer attached to chat responses.
12. PWA and runtime packaging
- The app includes PWA metadata, icons, and production service-worker generation via next-pwa.
- This improves installability and app-like behavior, but the core system still depends on network access to Supabase and the AI endpoint.
- The repository is a single deployable Next.js app, with the external Supabase and AI services forming the main runtime dependencies.
13. Important architectural limitation
- The schema currently does not include a complete bootstrap trigger for creating per-user profile/settings rows on first signup.
- That means initial user provisioning is an integration gap in the current architecture, and the app assumes those rows exist for personality, voice, and persistence flows to work fully.
Main entry points: route.ts Chat API · page.tsx Main Workspace · schema.sql Postgres Schema · ChatWindow.tsx Chat UI
Components 21
Browser UI
Client-rendered routes, components, hooks, and state
- App Shell · Root layout and entry pages for the single deployable app
src/app/layout.tsx - Auth Screens · Login and signup flows for unauthenticated users
src/app/(auth)/login/page.tsx - Main Workspace · Protected product area containing chat, history, personality, and voice settings
src/app/(main)/chat/page.tsx - Chat UI · Conversation window, message composer, and mic control
src/components/chat/ChatWindow.tsx - Personality UI · Persona selection and settings screen
src/components/personality/PersonalitySelector.tsx - Layout Nav · Shared navigation and sidebar scaffolding for the main app
src/components/layout/Navbar.tsx - Auth Hook · Projects Supabase session state into the browser and handles redirects
src/hooks/useAuth.ts - Chat Hook · Drives message submission, streaming updates, and chat state
src/hooks/useChat.ts - Voice Hook · Manages speech recognition and speech synthesis lifecycle
src/hooks/useVoice.ts - Auth Store · Client-side projection of user and session state
src/store/authStore.ts - Chat Store · Active conversation state and streaming fragments
src/store/chatStore.ts - Settings Store · Persona and voice preferences used by the client
src/store/settingsStore.ts - Voice Engines · Browser speech-to-text and text-to-speech helpers
src/lib/voice/speechToText.ts
Next.js Server
Route handlers and server-only integration code
- Chat API · Trusted chat orchestration: validate token, retrieve memory, call AI, stream SSE, persist results
src/app/api/chat/route.ts - Account API · Privileged account deletion and related server-side actions
src/app/api/account/delete/route.ts - Server Supabase · Server-only Supabase clients, proxy session handling, and privileged DB access
src/lib/supabase/server.ts - AI Gateway · Ollama-compatible chat and embedding client used by the server
src/lib/ollama/client.ts - Prompt Builder · Combines persona, history, and optional memory into the model prompt
src/lib/ollama/promptBuilder.ts
Supabase Data
Postgres schema, auth, and persisted user state
- Postgres Schema · User-owned tables, RLS policies, cascade deletes, and vector-backed memory storage
supabase/schema.sql
External Services
Remote auth and AI dependencies
- Supabase Auth · Email/password and Google OAuth identity provider
- Fieldwaves AI · Remote generation and embedding service exposed through an Ollama-compatible API
Connections 23
- App Shell → Auth Screens: renders · Public auth entry points
- App Shell → Main Workspace: renders · Protected app workspace
- Main Workspace → Chat UI: uses · Chat page composition
- Main Workspace → Personality UI: uses · Persona settings screen
- Main Workspace → Layout Nav: wraps · Shared navigation scaffold
- Chat UI → Chat Hook: drives · Submits messages and receives streaming updates
- Chat UI → Voice Hook: captures audio · Turns microphone input into transcript text
- Chat Hook → Chat Store: updates · Keeps conversation state in sync
- Auth Hook → Auth Store: projects · Maintains browser session state
- Personality UI → Settings Store: saves · Persists persona preferences in client state
- Voice Hook → Settings Store: reads · Uses voice preferences for speech synthesis
- Voice Hook → Voice Engines: uses · Browser-native speech recognition and playback
- Auth Hook → Supabase Auth: authenticates · Session and OAuth-backed identity
- Chat Hook → Chat API: PUT /api/chat · Sends text plus access token for streaming completion
- Chat API → Server Supabase: verifies · Validates bearer token and performs trusted DB access
- Chat API → Prompt Builder: builds prompt · Combines persona, history, and memory context
- Chat API → AI Gateway: calls · Streams generation and embeddings from remote AI
- Chat API → Postgres Schema: reads/writes · Loads history and persists assistant messages, emotions, and embeddings
- Server Supabase → Postgres Schema: accesses · Privileged server-side persistence
- Postgres Schema → Supabase Auth: RLS via auth.uid() · Browser queries are constrained to the signed-in user
- AI Gateway → Fieldwaves AI: requests · Ollama-compatible chat and embedding endpoints
- Account API → Server Supabase: privileged delete · Server-side account removal flow
- Postgres Schema → Fieldwaves AI: embeds memory · Embeddings used for semantic recall and similarity search