Tech Stack

June 24, 2026 · View on GitHub

Overview

This document defines the complete technology stack for the AI chat aggregator application. All choices optimize for: serverless architecture, local development parity, end-to-end type safety, minimal vendor lock-in, and cost efficiency. It describes the v2 target; the legacy backend coexists until cutover, and the design record lives in docs/history/BACKEND-REDESIGN.md.


Core Values

Serverless Architecture Pay for what you use. Zero idle costs.

Local Development Parity Every production service runs locally. Developers never need production access. What works on your machine works in production.

End-to-End Type Safety TypeScript everywhere. Shared schemas between frontend and backend. Change a type, get errors everywhere it breaks—before users do.

Universal Idempotency Every operation is safe to retry. Network glitch? Just retry. No duplicate charges, no corrupted state.

One Mechanism Per Task, Made Recoverable No backup mechanisms. Each task has a single mechanism that recovers itself — leases, TTLs, lazy checks. Auditors detect; humans repair.

Crash Recovery by Construction Nothing commits mid-run, so a crash at any moment leaves nothing to clean up.

Single Writer Per Table Every table has exactly one owning slice; everyone else goes through its published API.

Configurability Over Rebuild Models, capabilities, and workflows are data. New behavior ships as registry entries and definitions, not deploys.

Frequent Forever Backups Your data is backed up daily to geographically separate storage. Encrypted. Verified.

Cost Efficiency Optimize for low costs.

Developer Experience First One command starts everything. Clear errors. Fast iteration. If it's painful to develop, it's painful to maintain.

Minimal Vendor Lock-in Standard tools, standard protocols.

Accessibility Compliance Every feature works for everyone. WCAG compliance.

No Security Through Obscurity Our security doesn't depend on hiding how things work. The source code is visible. Our architecture is documented. Security comes from good design, not secrets.


Language

TechnologyPurpose
TypeScriptAll code (frontend, backend, shared packages). Enables type safety across the entire stack with shared schemas.

Frontend

TechnologyPurpose
React 19UI framework. Largest ecosystem, best Capacitor support, excellent for text-heavy interfaces.
ViteBuild tool and dev server. Fast HMR, simple config, no SSR complexity for SPA.
rolldown-viteRust-based drop-in for Vite's bundler. Faster builds; applied workspace-wide via a pnpm override.
TanStack RouterRouting. Fully type-safe routes, params, and search params. Compile-time errors for invalid routes.
TanStack QueryServer state management. Caching, background refetching, request deduplication for all API calls.
ZustandClient state management. Lightweight, minimal boilerplate for UI state not tied to server.
shadcn/uiSource of accessible primitives (Radix-based) in packages/ui. Copy-paste ownership; extended in-house with composites and domain features.
Tailwind CSSStyling. Utility-first, consistent design tokens, pairs with shadcn/ui.
Sandpack (planned)Browser code execution. Renders HTML/React/CSS in iframe sandbox for artifact previews.
input-otpOTP input component. Accessible, mobile-friendly 6-digit code entry for 2FA verification.
react-qrcode-logoQR code generation. Renders TOTP provisioning URIs for authenticator app setup.
StreamdownMarkdown rendering with plugin system. Plugins: @streamdown/code (Shiki), @streamdown/mermaid, @streamdown/math (KaTeX).
ShikiSyntax highlighting for code blocks (via @streamdown/code).
Framer MotionAnimation library for transitions and micro-interactions.
Lucide ReactIcon library. SVG icons used throughout UI.
React VirtuosoVirtual scrolling for long message lists.

Marketing Site

TechnologyPurpose
AstroStatic site generator. SSG for SEO, partial hydration, deployed alongside main app.

Mobile

TechnologyPurpose
CapacitorNative wrapper. Same React codebase runs on iOS/Android with native API access.

Backend

TechnologyPurpose
HonoAPI framework. Ultrafast, runs on Workers/Node/Bun, native streaming support.
ZodSchema validation. Runtime validation + TypeScript inference. Shared schemas between frontend/backend.
@hono/zod-validatorInput validation middleware. Zod schemas validate request body/params/query in Hono route chains.
hono/clientTyped RPC client. hc<AppType>() infers types from Hono route chains. Ships with hono, zero additional dependencies.
neverthrowTyped Result error channel at service seams. Must-use enforced by a vendored lint rule.
ts-patternExhaustive matching (DomainError→code, node dispatch); compiler catches unhandled variants.
cockatielRetry/timeout policies on external calls, built only via the policy factory. No in-isolate breakers.
eslint-plugin-boundariesEnforces slice/package boundaries and intra-slice layers from the import graph.
ts-morphStructural architecture tests lint can't express (idempotency wrapping, schema-object scoping).
joseCloudflare Access JWT verification in the admin Worker.

Database

TechnologyPurpose
NeonCloud PostgreSQL 18. Serverless, scales to zero, branching for previews. Native uuidv7().
DrizzleORM. Type-safe, lightweight, identical queries on Neon and local Postgres.

Cache

TechnologyPurpose
Upstash RedisServerless Redis. OPAQUE challenge state, rate limiting, 2FA attempt tracking.
Serverless Redis HTTPLocal development proxy. Emulates Upstash REST API against local Redis.

Hosting

TechnologyPurpose
Cloudflare WorkersAPI hosting: one product Worker + one admin Worker (service-binding RPC between them).
Cloudflare PagesFrontend hosting. Deploys Vite app, admin SPA, and Astro marketing site.
Cloudflare Durable ObjectsTwo roles: ConversationRoom (realtime hub, stream coordination, in-process flow executor) and JobDispatcher (alarm-clocked job execution).

Storage

TechnologyPurpose
Cloudflare R2Primary object storage. S3-compatible. User files, artifacts, exports.
Backblaze B2Backup storage. Different vendor for disaster recovery. Receives Kopia backups.
KopiaBackup tool. Incremental, encrypted, deduplicated backups from R2 to B2.

Code Execution

TechnologyPurpose
Cloudflare Containers / Sandbox SDK (deferred)Server-side heavy compute (transcode, code execution) when a feature forces it. Same vendor; behind the TransformCompute port.
Sandpack (planned)Client-side sandbox. Browser iframe for HTML/React/CSS preview. No server needed.

Authentication

TechnologyPurpose
@cloudflare/opaque-tsOPAQUE PAKE protocol. Zero-knowledge password auth.
iron-sessionEncrypted session cookies. Stateless, no server-side session store.
otplibTOTP generation and verification for two-factor authentication.

Cryptography

TechnologyPurpose
@noble/ciphersXChaCha20-Poly1305 AEAD encryption for ECIES message blobs. Audited, zero deps.
@noble/curvesX25519 ECDH for key exchange between client and recovery flows.
@noble/hashesSHA-256, HKDF-SHA-256 for key derivation, epoch confirmation hashes, and content-addressable storage.
@scure/bip39BIP39 mnemonic generation for 12-word recovery phrases.
hash-wasmArgon2id password hashing in WebAssembly.
fflateRaw deflate compression before encryption. Saves ~18 bytes per message vs gzip.

Email

TechnologyPurpose
ResendTransactional email. HTTP API for verification emails. Test addresses for CI.

Payments

TechnologyPurpose
HelcimPayment processing. Handles credit loading.

Analytics & Observability

TechnologyPurpose
Cloudflare Workers LogsStructured logs, allowlisted fields; Logpush to R2 for retention.
Workers Analytics EngineApp/business metrics. SQL API only; every metric has a named watcher.
SentryUnexpected errors only, backend only. Scrubbed at the Telemetry port; errorCode fingerprints.
Cloudflare OTel tracingVendor-neutral tracing (open beta; Sentry tracing is the fallback).
PostHog (deferred)Product analytics, if ever: self-hosted, no autocapture, never session replay.

AI / LLM

TechnologyPurpose
Vercel AI SDKProvider-agnostic streaming inference for text, image, and video. The portability seam behind the ModelProvider port.
Vercel AI GatewayThe single gateway: 100+ models, metadata auto-discovery, per-request ZDR, per-generation cost as billing truth.

Excluded Services

Each was evaluated and excluded; re-entry conditions live in ARCHITECTURE.md.

ServiceWhy excluded
Cloudflare WorkflowsDurable resume is exactly what fast-fail makes unwanted.
Cloudflare QueuesA send can't be atomic with a Postgres commit; the jobs table can.
HyperdriveNo PG18; caching isn't read-your-writes safe; pooling doesn't bind yet.
Fly.ioSecond compute vendor for a deferred feature; Cloudflare Containers preferred.
AxiomWorkers Logs covers it natively.
Effect-TSTeam fit and migration cost; would discard Drizzle/Zod inference.

Development

TechnologyPurpose
TurborepoMonorepo orchestration. Parallel builds, caching, task dependencies.
pnpmPackage manager.
VitestUnit/integration testing.
PlaywrightE2E testing. Cross-browser,.
fisheryTest factories with traits, sequences, and async DB creation.
@faker-js/fakerRealistic fake data generation.
MinIOLocal S3-compatible server. Emulates R2 for local dev and CI tests via pnpm db:up.
Payment MocksLocal mock for Helcim. No real API calls in local development.
Helcim SandboxHelcim's test environment. Used in CI for real payment flow testing.
execaSubprocess execution. Clean API for running shell commands from TypeScript scripts.
tsxTypeScript execution. Runs TypeScript directly without compilation step.

CI/CD

TechnologyPurpose
GitHub ActionsCI/CD pipelines. Tests on PR, deploy on merge, scheduled backups.

CI/CD Infrastructure Principle

CI runs the same Docker Compose infrastructure as local development. GitHub Actions executes pnpm db:up (and future pnpm storage:up, etc.) rather than defining service containers in workflow YAML.

Benefits:

  • Single source of truth: docker-compose.yml
  • No duplication between workflow files and compose configuration
  • Identical test environment locally and in CI

Environment Management

FilePurpose
.env.developmentDev defaults, committed. No secrets.
.env.exampleProduction template, committed. Documents vars.
Cloudflare SecretsProduction secrets stored in Workers.
Github SecretsProduction secrets for workflows.

Local dev and CI use .env.development. No secrets needed outside production.


Licensing

ItemChoice
LicenseProprietary (source-available, no rights granted).
CAARequired for all contributions via CLA Assistant bot.

Monorepo Structure

/
├── apps/
│   ├── web/              # React + Vite (main application)
│   ├── marketing/        # Astro (marketing site)
│   ├── api/              # Product Worker — vertical slices (map in ARCHITECTURE.md)
│   ├── admin-api/        # Admin Worker — Access-gated, RPC into the product Worker
│   └── admin/            # Admin SPA (Pages)

├── packages/
│   ├── ui/               # Shared component library: primitives, composites, hooks, utilities
│   ├── shared/           # Zod schemas, types, constants, contracts
│   ├── db/               # Drizzle schema, migrations, client
│   ├── crypto/           # Encryption, key derivation, OPAQUE helpers
│   ├── realtime/         # Durable Objects: ConversationRoom + JobDispatcher
│   └── config/           # Shared ESLint, TypeScript configs, arch-test harness

├── e2e/                  # Playwright E2E tests
├── scripts/              # Dev tooling (seed, db-reset, generate-env)
├── docs/                 # Documentation (history/ holds archived plans)

├── .github/
│   └── workflows/
│       ├── ci.yml        # Test on PR
│       ├── deploy.yml    # Deploy on merge
│       └── backup.yml    # Daily backups

├── turbo.json
├── pnpm-workspace.yaml
├── package.json
└── README.md

Data Flow

Cloud Mode

Browser → API (Workers) → Neon Postgres / R2 / Redis
                       → ConversationRoom DO → Vercel AI Gateway (flows + streaming)
                       → JobDispatcher DO (async jobs)

API Patterns

PatternTechnologyUse Case
Request/ResponseHono + Zod + hc<AppType>() typed clientCRUD, auth, billing, members, links; POST /chat returns a run handle
WebSocketConversationRoom Durable ObjectThe sole streaming transport: turn tokens, flow progress, presence, media events, replay/resume
Jobsjobs table + JobDispatcher DOAll must-happen async work (true-up, exports, reclaim, admin actions)

Local Development

pnpm dev

Starts:

  • Vite (frontend) on :5173
  • Wrangler (Workers) on :8787
  • Postgres (Docker) on :5432
  • Neon Proxy (Docker) on :4444 (WebSocket → Postgres)
  • Redis (Docker) on :6379
  • Serverless Redis HTTP (Docker) on :8079 (Upstash REST API emulator)
  • MinIO (S3-compatible R2 emulator) on :9000

External APIs are mocked locally. Real-API tests run on every PR in CI: AI Gateway via the test job (vitest integration tests with AI_GATEWAY_API_KEY_RESTRICTED); Helcim sandbox via the e2e job (Playwright payment flows with HELCIM_API_TOKEN_SANDBOX). The verify:evidence step asserts each real service was actually exercised.