Architecture

Biscuit is a React single-page app (apps/web, also shipped as a Tauri desktop app in apps/desktop) backed by a Go API (services/api) and PostgreSQL. This document explains how the pieces fit, why each choice was made, and how the system scales. Exact numbers live in PERFORMANCE.md.

System at a glance

System architecture
Your devicesBiscuit API (one Go binary)Model providersWeb appReact · ViteDesktop appTauriPhone appExpoChat proxy/api/chat (Vercel)Groqrole=apiHTTP · SSEAgent loop≤10 roundsModel gatewayllm.RouterYour model servervLLM · Ollamarole=workerroutinesAction reviewTools: web, apps,MCP, memoryBot's computerChrome · controldPostgreSQLdata + NOTIFYApprovals in Nowkey stays on serverlisted modelsthe rest + fallbackallowedask first
You or your deviceCheck or decisionSaved or publishedOutside serviceHover or tab to a box to trace it

The web, desktop and phone apps can also run on their own: with no API they use sample data, and live replies come through the chat proxy.

Piece Lives in What it does
Web app apps/web React + Vite single-page app. Runs on sample data alone, or against the API when VITE_API_URL is set.
Desktop app apps/desktop Tauri v2 shell that ships the web build in the system webview. See DESKTOP.md.
Phone app apps/mobile Expo (React Native) app that reuses the web app's data through Metro. See MOBILE.md.
Chat proxy apps/web/api/chat.js Vercel edge function that forwards chat completions to Groq so the key never reaches a browser or phone.
API and worker services/api One Go binary: HTTP + SSE (role=api), routine scheduler (role=worker), or both (role=all).
PostgreSQL services/api/internal/store Source of truth, event bus (LISTEN/NOTIFY) and job queue (SKIP LOCKED).
Model gateway services/api/internal/llm One OpenAI-compatible client for Groq, Gemini and your own model servers.
Bot's computer services/api/internal/browser, services/controld A real browser per task: local Chrome, any CDP endpoint, or a microVM per workspace. See COMPUTERS.md.

One binary, three roles (BISCUIT_ROLE=api|worker|all). API and worker processes scale independently; both are stateless, so any number can run.

Language and stack decisions

Decision Choice Why
Backend language Go 1.26+ (single language) Goroutines make thousands of concurrent SSE streams cheap (~8 KB each); static binary, ~15 MB image, millisecond cold start; strong stdlib (HTTP/2, net/http routing, slog, crypto). A second language would add operational surface without a measurable win here — LLM work is I/O-bound streaming, not compute.
HTTP stdlib net/http (Go 1.22 method+pattern routing) Zero-dependency router, no reflection, allocation-free matching.
Database PostgreSQL via pgx/v5 Transactions, JSONB for flexible message/doc bodies, LISTEN/NOTIFY for fan-out, SKIP LOCKED for job claiming — one dependency covers storage, events and queueing.
Realtime Server-Sent Events One-way server→client fits the product (replies, sync). Works through proxies/HTTP/2, auto-reconnects natively, no sticky sessions.
IDs UUIDv7 (app-generated) Time-ordered → append-mostly B-tree inserts, natural "newest first" order, keyset pagination without timestamps, no DB round trip to mint IDs.
Auth argon2id passwords + stateless HMAC tokens Verification is CPU-only (~2.5 µs, no DB lookup) so auth scales with API nodes; key rotation by key ID.
Metrics Prometheus text format, built in Standard scrape target without a heavy client library.

Request lifecycle

Middleware order (outermost first): Core (request ID, panic recovery, access log, RED metrics by route pattern) → Secure headers → CORS → Gzip (JSON only; never SSE) → BodyLimit (1 MiB default) → Authenticate (bearer or ?access_token= for EventSource) → RateLimit (token bucket per user, or per IP when anonymous) → router → handler.

Handlers are thin: decode with DisallowUnknownFields, validate, call one store method, map errors in one place (fail) to RFC 9457 problem responses with stable codes.

Data model

Every tenant table carries workspace_id, and every index leads with it (messages (workspace_id, bot_id, id DESC), …). Consequences:

  • A workspace's rows cluster on disk; queries never scan other tenants.
  • Tenant isolation is enforced structurally — every repository method takes the workspace first, and the integration suite proves cross-tenant reads/deletes return 404.
  • The schema is ready for partitioning or sharding by workspace_id later without query changes.

Tables: workspaces, users, memberships, bots, messages, memories, docs + doc_revisions, routines + routine_runs, computer_sessions + computer_actions (the bot's computer and its audit trail), llm_usage (one row per model call). See services/api/internal/store/migrations/.

Consistency guarantees

Concern Mechanism
Duplicate POSTs (retries, double-clicks, flaky networks) Idempotency-Key → unique partial index; a replay returns the original message and does not trigger a second reply.
Concurrent document edits Optimistic concurrency: PUT … If-Match: "rev" → UPDATE … WHERE rev = $n; losers get 412 stale_revision. Proven with 10 racing writers → exactly 1 winner.
Every save is recoverable Append-only doc_revisions; revisions are immutable and cacheable forever.
Events only for committed data pg_notify runs inside the write transaction; Postgres delivers on commit only.
Routine fires exactly once per occurrence Workers SELECT … FOR UPDATE SKIP LOCKED, advance next_run_at in the same transaction, run after commit. Proven with 4 racing workers over 40 due routines → each claimed once.
Wall-clock schedules across DST next_run_at computed with time.Date in the routine's IANA zone (tested across the US DST change).

Realtime fan-out

Live sync across devices
A write commitspg_notify in thesame transactionAPI node ALISTENAPI node BLISTENYour phone tabYour laptopon commiton commitSSESSE
You or your deviceSaved or publishedHover or tab to a box to trace it
  1. A write commits and its pg_notify('biscuit_events', {ws, type, data}) is delivered to every API node.
  2. Each node holds one dedicated LISTEN connection and an in-memory index workspace → subscribers.
  3. Publishing is a non-blocking send into each subscriber's buffered channel (O(subscribers in that workspace)). A subscriber whose buffer is full is dropped and receives resync; it reconnects and refetches. One slow client can never stall others.
  4. Payloads over 7 KB are sent as references (ref: true) to stay under NOTIFY's 8 KB limit.
  5. 25-second heartbeats keep idle connections alive through proxies.

Replies in progress reach the asker's other devices the same way. While a reply runs, its node saves the text and steps to live_replies and publishes numbered reply.* events about four times a second (the sending tab still gets every token on its own stream). A device opening the chat reads GET /v1/bots/{bot}/replies, then follows events; a gap in the numbers makes it read the row again. The saved message carries body.replyId, so it takes the live bubble's place. Reconnecting refetches open chats and merges by message id, so nothing is lost or shown twice.

No Redis/NATS is required. If event volume ever outgrows Postgres NOTIFY (tens of thousands of events/second), swap the hub's Listen for a broker subscription — the Hub API is unchanged.

Model replies

One chat message, end to end
Your appGo APIAgent loopModel gatewayAction reviewTool1 POST /messages + Idempotency-Key2 event: message (saved)3 start reply, detached context4 StreamStep: chat + tools5 text + tool calls6 event: delta (text as it comes)7 each tool call8 allowed → run, in parallel9 event: step running / done10 result as a tool turnrepeat until it answers: ≤ 10 rounds, 4 minutes12 a write → approval card13 final answer14 event: done · saved, sent to your other devices
requeststreamed backHover a step to focus it

Reads run straight away. A write waits in Now; once you approve it, it runs and the bot carries on in the same chat. The reply is saved even if you close the tab.

POST /v1/bots/{bot}/messages stores the user message, then:

  • Streaming (Accept: text/event-stream): message → delta… → done on the same response.
  • Fire-and-forget: 202 immediately; the reply arrives on /v1/events.

Before it answers, a reply checks the chat's context window. Past 80% of the model's window, all but the newest four turns fold into one summary (chat_summaries), and the bot reads that summary plus the turns after it. GET /v1/bots/{bot}/context reports the same measure to the app's context ring.

Replies are generated on a context detached from the request, so a closed tab still gets a saved reply. Back-pressure is explicit:

  • BISCUIT_LLM_CONCURRENCY (default 32) caps concurrent upstream streams per process.
  • BISCUIT_REPLY_BACKLOG (default 512) caps replies in flight; beyond it the API returns 503 busy + Retry-After before writing anything — bursts degrade into fast, retryable errors instead of unbounded goroutines and memory.
  • Providers implement one interface (llm.Provider); Echo runs offline for dev and CI.
  • Model gateway (llm.Router): one OpenAI-compatible client serves Groq and our own model servers (vLLM, SGLang, TGI, Ollama). Models listed in BISCUIT_LLM_MODELS go to BISCUIT_LLM_BASE_URL, the rest to Groq; if our server fails before the first token, Groq answers with GROQ_MODEL. Tool calls for the bot's computer route the same way.
Which provider serves a model
Bot modelIn BISCUIT_LLM_MODELSStarts with gemini-Anything elseYour serverBISCUIT_LLM_BASE_URLGeminiGroq
You or your deviceCheck or decisionOutside serviceHover or tab to a box to trace it

If your own server fails before the first token, Groq answers with GROQ_MODEL instead.

  • Agent loop (internal/api/agentloop.go): every chat reply is a tool-using loop. Each step streams (llm.Agent.StreamStep: text to the user, tool calls collected, several per step); the calls run in parallel through one registry (web search and page reading, the bot's computer, connected apps, MCP, delegation, routines, memory, images, skills), each reported live as an SSE step; results go back as tool turns until the bot answers (≤ 10 rounds, 4 min). Grants decide what each bot is offered; writes become approvals. Group chats and delegated replies use the same registry in a one-shot pass.
  • Action review (internal/api/review.go): every tool call passes one gate — Ask first rules (win) → Allow automatically rules (incl. Always allow) → defaults (reads run, writes ask) → optional auto review by a separate model. An ask is an approval (Allow once / Always allow / Deny); once approved the action runs and the bot continues in the same chat. Unattended approvals expire after 30 minutes. The full flow is in AUTOMATION.md.
  • Usage: every chat reply writes an llm_usage row (workspace, bot, provider, model, tokens, latency, ok, fell back) for metering and for comparing our models with Groq; biscuit_llm_fallbacks_total counts fallbacks.
  • Attachments: files are uploaded first with POST /v1/attachments (up to 10 per message, 20 MB each, stored per workspace) and referenced from body.attachments on the message. Images up to 8 MB go to the model as images, text files are inlined, anything else is described by name and type. GET /v1/attachments/{id} serves a file only to the person who attached it; bot images use signed links (an HMAC of workspace and image ID, valid until the signing key rotates).
  • Ephemeral UI: when an answer has structure the model composes a view (a ~~~ui block of JSON or Markdown lines) with its own state and formulas. internal/api/genui.go holds the rule and the brief that varies per question; apps/web/src/genui reads it as it streams, including the catalog's own shorthand and views the model forgot to fence. Details in EPHEMERAL_UI.md.
  • Streaming chat. Markdown splits a reply into paragraphs and memoizes them, so only the paragraph being written re-renders. App marks (components/AppMark.tsx) and the live steps list (components/AgentWork.tsx) load lazily.
  • GitHub PR tools: the agent can list, read, review and open pull requests on connected repos; a PR linked to a chat opens in the PR panel beside it (diff, checks, comments, merge for admins).

The bot's computer

A bot can do real work on the web in its own browser, like Grok's agent mode:

One step on the bot's computer
Model picksone actionGateway: allow,ask or refuseAudit rowBrowser backendChrome · controldLive view≤10 fpsYou take overFresh look atthe pageallowedscreencastnext step
You or your deviceCheck or decisionSaved or publishedOutside serviceHover or tab to a box to trace it

The bot observes the page (URL, title, numbered interactive elements, page text), the model picks one tool (navigate, click, type, scroll, back, ask_human, done), the gateway decides it (allow, ask first or deny) and writes an audit row, and the action runs on a browser backend over CDP while a screencast streams to the live panel.

  • Browser backends (internal/browser/backend.go): chrome starts one local Chrome per task over a pipe, with a throwaway profile deleted on close; remote drives any browser that speaks CDP over a WebSocket (Lightpanda, a browser container, or controld: a Firecracker microVM per workspace with a warm pool, addressed by {owner} in the URL and spread over hosts by rendezvous hash; see COMPUTERS.md). Everything above the backend (agent, gateway, audit, live view) is the same. Pool limit (BISCUIT_COMPUTER_MAX), absolute lifetime (BISCUIT_COMPUTER_MAX_AGE), step limit. Lightpanda doesn't render, so the live view stays empty with it; use Chrome where people watch.
  • Live view: CDP screencast JPEG frames, "latest frame wins" for slow viewers, ≤ 10 fps on the wire, a captured closing frame so the panel always ends on what the bot saw. Frames are painted straight into an <img> in the browser (no React re-render per frame).
  • Network guard: every request the page makes is intercepted (CDP Fetch) and its host resolved; private, loopback, link-local (incl. 169.254.169.254), CGNAT and reserved addresses are refused, so a page can't reach the server's own network. A remote backend whose host filters egress itself can skip this (BISCUIT_COMPUTER_ISOLATED=1). Optional egress proxy (BISCUIT_COMPUTER_PROXY) gives sites one attributable address.
  • Decide before act: a gateway judges every action and writes an audit row (computer_actions). Secrets are never sent to the model: sensitive fields report [hidden: sensitive field] instead of their value, and a refused secret is redacted from logs.
  • Handover: "take control" waits for the bot's in-flight action to finish (action barrier), then the bot stands still while your clicks, scrolls and keys go to the real browser; on hand back it looks at the page fresh before acting.
  • Search: the agent uses Brave Search, which serves automated browsers; DuckDuckGo shows a human check to headless Chrome (measured), which would stall every search.
  • Planners: the model planner (Groq tool calling, one retry, prose answers accepted as the final answer) or an offline heuristic that still browses for real when no key is set.

Your own browser. In Settings → Computer access you can let bots use Chrome, Brave, Edge, Arc or Chromium on your computer instead of the cloud browser. The desktop app starts that browser with its own Biscuit profile (never your personal one) and connects its DevTools port to the API through a WebSocket tunnel at /v1/cdp/{session} (internal/api/cdptunnel.go), so the same action review, live view and audit apply. Long runs check in after BISCUIT_COMPUTER_MAX_STEPS (40) and stop at 200.

Patterns adapted from CopilotKit/OpenBot (MIT): the decide-before-act gateway with an audit trail, the action barrier on handover, human-verification handoff, secret masking and per-bot egress. OpenBot's own code (TypeScript/Playwright) is not vendored; these are Go reimplementations.

The chat proxy

apps/web/api/chat.js is a Vercel edge function deployed with the website. It lets the web, desktop and phone apps get real model replies without the API and without shipping a key:

  • GET /api/chat answers {configured: boolean}; the apps probe it once and fall back to demo replies when it says false.
  • POST /api/chat passes through only model, messages, temperature, max_tokens, reasoning_effort and response_format, pins the model to GROQ_MODEL (default openai/gpt-oss-120b), caps max_tokens at 3,000 and refuses more than 40 messages.
  • The key lives in the Vercel project's GROQ_API_KEY. The desktop app's origins (tauri://localhost, http(s)://tauri.localhost) get CORS so it can call the deployed proxy.

Scaling model

Load grows in… Scale by Notes
HTTP requests more role=api replicas Stateless; no sticky sessions (SSE reconnects anywhere).
Open SSE connections more API replicas ~8–10 KB per idle stream; 10k streams ≈ 100 MB.
Concurrent model replies BISCUIT_LLM_CONCURRENCY × replicas Bounded by provider quota; backlog protects memory.
Routines more role=worker replicas SKIP LOCKED makes workers additive.
Live computers more API replicas × BISCUIT_COMPUTER_MAX Each browser ≈ 150–300 MB RAM; a run is pinned to the node that started it, so its stream and controls must reach that node (route /v1/computer/{id}/* by id, or run computers on dedicated nodes).
Database vertical first; read replicas for list endpoints; partition messages by workspace_id hash when it passes ~100M rows Pool size: replicas × BISCUIT_DB_MAX_CONNS must stay under max_connections (use PgBouncer in transaction mode beyond ~200).

Rate limiting is per process (documented in httpx.Limiter): with N API replicas the effective per-user ceiling is up to N × BISCUIT_RATE_RPS. Size accordingly or front it with a shared limiter at the edge.

Frontend architecture (performance)

  • Route-level code splitting: only the home and chat screens ship in the first bundle; every other page is a lazy chunk, prefetched when the browser is idle so navigation stays instant.
  • On-demand heavy features: the 3D voxel ghost (three.js), the document/slide editors (and React's server renderer they use), and the ⌘K palette load on first use.
  • Long-lived vendor chunks: react, motion, icons and the rest are split so app deploys don't invalidate cached libraries.
  • Fonts: retro-style fonts load only when a style that uses them is active.
  • Event-loaded features: modals and the task-complete chomp mount on their first window event (OnFirstEvent replays it); charts, diagrams and GSAP load the first time they're used.
  • Caching layers: content-hashed /assets/* are immutable for a year; fonts and icons 30 days + stale-while-revalidate; HTML always revalidates (vercel.json). A service worker (public/sw.js) serves hashed assets cache-first, fonts stale-while-revalidate, and falls back to the cached app shell offline; it never touches /api/*. A tab left on an old deploy reloads once if a lazy chunk is gone (vite:preloadError).
  • Scaling lists: chats render the latest 60 messages ("Show earlier" adds more), and older messages and marketplace cards use content-visibility: auto so off-screen items cost nothing.
  • Budget enforced in CI: scripts/bundle-budget.mjs fails the build if the first-load JS exceeds 240 KB gzip or CSS 45 KB.
  • API client (apps/web/src/lib/api.ts): idempotent writes, streamed replies over fetch (deltas render as they arrive), and one EventSource for live sync with resync on reconnect. GETs go through an in-memory cache: concurrent reads share a request, results stay fresh for 15 s, then revalidate with If-None-Match against the API's ETags. Writes and live events drop the affected entries; sign-in changes and resyncs clear it. Nothing is persisted.

Desktop app

The desktop app
Tauri v2 shellRust, ~4 MBSystem webviewWebKit · WebView2apps/web buildshipped insideGo APIVITE_API_URLChat proxyVITE_CHAT_URLUpdater: latest.jsonbiscuit-releasesCORS for tauri://signed updates
Saved or publishedOutside serviceHover or tab to a box to trace it

apps/desktop is a Tauri v2 shell around the apps/web build. The web files ship inside the app and render in the system webview (WebKit on macOS and Linux, WebView2 on Windows), so there is no bundled browser engine: the macOS app is about 4 MB and idles around 250 MB of memory, most of it the web app itself.

  • The release profile uses LTO, one codegen unit, size optimisation and stripped symbols.
  • The window paints the app's dark background before the page loads (no white flash).
  • The service worker is off inside the app; the files are already local.
  • Network calls go to VITE_API_URL and VITE_CHAT_URL; both servers allow the app's origins.
  • Native features are opt-in through Tauri capabilities (src-tauri/capabilities/default.json): core:default, the updater and process restart (auto-updates), opening http(s) links in your browser, native dialogs and system notifications. Single-instance and deep-link plugins bring the open window forward instead of starting a second copy. A tray icon (the macOS menu bar) opens a quick-ask bar that sends a message to any bot's chat in the main window. Details and the release flow are in DESKTOP.md.

Phone app

The phone app
apps/mobileShared from the web appScreensExpo RouterWidgets · LiveActivitiessrc/lib/model.tsaskModel()App store+ demo repliessrc/lib/shared.tsEXPO_PUBLIC_CHAT_URL→ /api/chatEXPO_PUBLIC_GROQ_API_KEYMetro watches../web/srcGroqseed.ts · ghostData.tschomper.tssurfaces.*.tsbuild for otherslocal testing
You or your deviceCheck or decisionSaved or publishedOutside serviceHover or tab to a box to trace it

With neither variable set, or when the proxy reports no key, the app keeps its demo replies and nothing leaves the phone.

apps/mobile is a React Native app built with Expo (SDK 58) and Expo Router. There is no tab bar: home is the crew, and everything else opens from it.

  • Crew-grid home. A status bar (account, the grid of everything else, settings), search and your computer's connection pill sit above the crew as a grid of tiles tinted in each bot's colour (face, name, Ready / Working / Needs you). A bottom bar shows what needs you, opens voice with Biscuit and has a big + (src/app/(tabs)/chats/index.tsx). Chats add quick-action chips and "Connection needed" cards (src/ui/ChatAssist.tsx). Icons are the web's lucide set (lucide-react-native); floating controls and the composer use expo-glass-effect, with a bordered panel as the fallback.
  • Biscuit's design system. src/lib/theme.ts carries the same tokens as apps/web/src/styles/global.css (dark by default, light with the system), and the app ships the Matter typeface as static weights cut from the web font.
  • Shared code, not copies. metro.config.js watches apps/web/src; src/lib/shared.ts imports the demo bots and chats (data/seed.ts) and the ghost path data (bots/ghostData.ts, bots/chomper.ts). Only data and types cross over; web components stay on the web.
  • Live model, no server needed. src/lib/model.ts asks a real model through the chat proxy (EXPO_PUBLIC_CHAT_URL) or, for local testing only, straight from the phone (EXPO_PUBLIC_GROQ_API_KEY). With neither it keeps short demo replies. Connecting to the Go API (sign-in, live sync, server-side agent loop) is the next step. Details in MOBILE.md.
  • Outside the npm workspaces. Expo pins its own React and React Native, so the app keeps its own node_modules and lockfile. The release script still bumps its version with the others.
  • Browser preview. npx expo start --web runs it in a browser.