# mardan-shah/voice-app architecture

> Architecture diagram of the GitHub repository mardan-shah/voice-app, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-06-01). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/mardan-shah/voice-app
- Repository: https://github.com/mardan-shah/voice-app

## Overview

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: [`src/app/api/chat/route.ts`](https://github.com/mardan-shah/voice-app/blob/main/src/app/api/chat/route.ts) (Chat API), [`src/app/(main)/chat/page.tsx`](https://github.com/mardan-shah/voice-app/blob/main/src/app/(main)/chat/page.tsx) (Main Workspace), [`supabase/schema.sql`](https://github.com/mardan-shah/voice-app/blob/main/supabase/schema.sql) (Postgres Schema), [`src/components/chat/ChatWindow.tsx`](https://github.com/mardan-shah/voice-app/blob/main/src/components/chat/ChatWindow.tsx) (Chat UI)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_browser["Browser UI"]
  node_root["App Shell<br/>Next.js app<br/>[layout.tsx]"]
  node_auth_routes["Auth Screens<br/>route group<br/>[page.tsx]"]
  node_main_routes["Main Workspace<br/>route group<br/>[page.tsx]"]
  node_chat_ui["Chat UI<br/>feature UI<br/>[ChatWindow.tsx]"]
  node_personality_ui["Personality UI<br/>feature UI"]
  node_nav_ui["Layout Nav<br/>layout UI<br/>[Navbar.tsx]"]
  node_auth_hook{{"Auth Hook<br/>client hook<br/>[useAuth.ts]"}}
  node_chat_hook{{"Chat Hook<br/>client hook<br/>[useChat.ts]"}}
  node_voice_hook{{"Voice Hook<br/>client hook<br/>[useVoice.ts]"}}
  node_auth_store(("Auth Store<br/>zustand store<br/>[authStore.ts]"))
  node_chat_store(("Chat Store<br/>zustand store<br/>[chatStore.ts]"))
  node_settings_store(("Settings Store<br/>zustand store<br/>[settingsStore.ts]"))
  node_voice_lib["Voice Engines<br/>browser speech<br/>[speechToText.ts]"]
end

subgraph group_server["Next.js Server"]
  node_chat_route["Chat API<br/>route handler<br/>[route.ts]"]
  node_account_route["Account API<br/>route handler<br/>[route.ts]"]
  node_server_lib["Server Supabase<br/>server lib<br/>[server.ts]"]
  node_ollama_lib["AI Gateway<br/>ai client<br/>[client.ts]"]
  node_prompt_lib["Prompt Builder<br/>prompting<br/>[promptBuilder.ts]"]
end

subgraph group_data["Supabase Data"]
  node_supabase_db[("Postgres Schema<br/>database schema<br/>[schema.sql]")]
end

subgraph group_external["External Services"]
  node_supabase_client[("Supabase Auth<br/>hosted auth")]
  node_fieldwaves_ai["Fieldwaves AI<br/>remote inference"]
end

node_root -->|"renders"| node_auth_routes
node_root -->|"renders"| node_main_routes
node_main_routes -->|"uses"| node_chat_ui
node_main_routes -->|"uses"| node_personality_ui
node_main_routes -->|"wraps"| node_nav_ui
node_chat_ui -->|"drives"| node_chat_hook
node_chat_ui -->|"captures audio"| node_voice_hook
node_chat_hook -->|"updates"| node_chat_store
node_auth_hook -->|"projects"| node_auth_store
node_personality_ui -->|"saves"| node_settings_store
node_voice_hook -->|"reads"| node_settings_store
node_voice_hook -->|"uses"| node_voice_lib
node_auth_hook -->|"authenticates"| node_supabase_client
node_chat_hook -->|"PUT /api/chat"| node_chat_route
node_chat_route -->|"verifies"| node_server_lib
node_chat_route -->|"builds prompt"| node_prompt_lib
node_chat_route -->|"calls"| node_ollama_lib
node_chat_route -->|"reads/writes"| node_supabase_db
node_server_lib -->|"accesses"| node_supabase_db
node_supabase_db -->|"RLS via auth.uid()"| node_supabase_client
node_ollama_lib -->|"requests"| node_fieldwaves_ai
node_account_route -->|"privileged delete"| node_server_lib
node_supabase_db -.->|"embeds memory"| node_fieldwaves_ai

click node_root "https://github.com/mardan-shah/voice-app/blob/main/src/app/layout.tsx"
click node_auth_routes "https://github.com/mardan-shah/voice-app/blob/main/src/app/(auth)/login/page.tsx"
click node_main_routes "https://github.com/mardan-shah/voice-app/blob/main/src/app/(main)/chat/page.tsx"
click node_chat_ui "https://github.com/mardan-shah/voice-app/blob/main/src/components/chat/ChatWindow.tsx"
click node_personality_ui "https://github.com/mardan-shah/voice-app/blob/main/src/components/personality/PersonalitySelector.tsx"
click node_nav_ui "https://github.com/mardan-shah/voice-app/blob/main/src/components/layout/Navbar.tsx"
click node_auth_hook "https://github.com/mardan-shah/voice-app/blob/main/src/hooks/useAuth.ts"
click node_chat_hook "https://github.com/mardan-shah/voice-app/blob/main/src/hooks/useChat.ts"
click node_voice_hook "https://github.com/mardan-shah/voice-app/blob/main/src/hooks/useVoice.ts"
click node_auth_store "https://github.com/mardan-shah/voice-app/blob/main/src/store/authStore.ts"
click node_chat_store "https://github.com/mardan-shah/voice-app/blob/main/src/store/chatStore.ts"
click node_settings_store "https://github.com/mardan-shah/voice-app/blob/main/src/store/settingsStore.ts"
click node_chat_route "https://github.com/mardan-shah/voice-app/blob/main/src/app/api/chat/route.ts"
click node_account_route "https://github.com/mardan-shah/voice-app/blob/main/src/app/api/account/delete/route.ts"
click node_server_lib "https://github.com/mardan-shah/voice-app/blob/main/src/lib/supabase/server.ts"
click node_ollama_lib "https://github.com/mardan-shah/voice-app/blob/main/src/lib/ollama/client.ts"
click node_prompt_lib "https://github.com/mardan-shah/voice-app/blob/main/src/lib/ollama/promptBuilder.ts"
click node_voice_lib "https://github.com/mardan-shah/voice-app/blob/main/src/lib/voice/speechToText.ts"
click node_supabase_db "https://github.com/mardan-shah/voice-app/blob/main/supabase/schema.sql"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_root,node_auth_routes,node_main_routes,node_chat_ui,node_personality_ui,node_nav_ui,node_auth_hook,node_chat_hook,node_voice_hook,node_auth_store,node_chat_store,node_settings_store,node_voice_lib toneBlue
class node_chat_route,node_account_route,node_server_lib,node_ollama_lib,node_prompt_lib toneAmber
class node_supabase_db toneMint
class node_supabase_client,node_fieldwaves_ai toneRose
```

## Components

### Browser UI

Client-rendered routes, components, hooks, and state

- [App Shell](https://github.com/mardan-shah/voice-app/blob/main/src/app/layout.tsx): Next.js app · Root layout and entry pages for the single deployable app · `src/app/layout.tsx`
- [Auth Screens](https://github.com/mardan-shah/voice-app/blob/main/src/app/(auth)/login/page.tsx): route group · Login and signup flows for unauthenticated users · `src/app/(auth)/login/page.tsx`
- [Main Workspace](https://github.com/mardan-shah/voice-app/blob/main/src/app/(main)/chat/page.tsx): route group · Protected product area containing chat, history, personality, and voice settings · `src/app/(main)/chat/page.tsx`
- [Chat UI](https://github.com/mardan-shah/voice-app/blob/main/src/components/chat/ChatWindow.tsx): feature UI · Conversation window, message composer, and mic control · `src/components/chat/ChatWindow.tsx`
- [Personality UI](https://github.com/mardan-shah/voice-app/blob/main/src/components/personality/PersonalitySelector.tsx): feature UI · Persona selection and settings screen · `src/components/personality/PersonalitySelector.tsx`
- [Layout Nav](https://github.com/mardan-shah/voice-app/blob/main/src/components/layout/Navbar.tsx): layout UI · Shared navigation and sidebar scaffolding for the main app · `src/components/layout/Navbar.tsx`
- [Auth Hook](https://github.com/mardan-shah/voice-app/blob/main/src/hooks/useAuth.ts): client hook · Projects Supabase session state into the browser and handles redirects · `src/hooks/useAuth.ts`
- [Chat Hook](https://github.com/mardan-shah/voice-app/blob/main/src/hooks/useChat.ts): client hook · Drives message submission, streaming updates, and chat state · `src/hooks/useChat.ts`
- [Voice Hook](https://github.com/mardan-shah/voice-app/blob/main/src/hooks/useVoice.ts): client hook · Manages speech recognition and speech synthesis lifecycle · `src/hooks/useVoice.ts`
- [Auth Store](https://github.com/mardan-shah/voice-app/blob/main/src/store/authStore.ts): zustand store · Client-side projection of user and session state · `src/store/authStore.ts`
- [Chat Store](https://github.com/mardan-shah/voice-app/blob/main/src/store/chatStore.ts): zustand store · Active conversation state and streaming fragments · `src/store/chatStore.ts`
- [Settings Store](https://github.com/mardan-shah/voice-app/blob/main/src/store/settingsStore.ts): zustand store · Persona and voice preferences used by the client · `src/store/settingsStore.ts`
- [Voice Engines](https://github.com/mardan-shah/voice-app/blob/main/src/lib/voice/speechToText.ts): browser speech · 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](https://github.com/mardan-shah/voice-app/blob/main/src/app/api/chat/route.ts): route handler · Trusted chat orchestration: validate token, retrieve memory, call AI, stream SSE, persist results · `src/app/api/chat/route.ts`
- [Account API](https://github.com/mardan-shah/voice-app/blob/main/src/app/api/account/delete/route.ts): route handler · Privileged account deletion and related server-side actions · `src/app/api/account/delete/route.ts`
- [Server Supabase](https://github.com/mardan-shah/voice-app/blob/main/src/lib/supabase/server.ts): server lib · Server-only Supabase clients, proxy session handling, and privileged DB access · `src/lib/supabase/server.ts`
- [AI Gateway](https://github.com/mardan-shah/voice-app/blob/main/src/lib/ollama/client.ts): ai client · Ollama-compatible chat and embedding client used by the server · `src/lib/ollama/client.ts`
- [Prompt Builder](https://github.com/mardan-shah/voice-app/blob/main/src/lib/ollama/promptBuilder.ts): prompting · 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](https://github.com/mardan-shah/voice-app/blob/main/supabase/schema.sql): database 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**: hosted auth · Email/password and Google OAuth identity provider
- **Fieldwaves AI**: remote inference · Remote generation and embedding service exposed through an Ollama-compatible API

## Connections

- 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
