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
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_idlater 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
- A write commits and its
pg_notify('biscuit_events', {ws, type, data})is delivered to every API node. - Each node holds one dedicated
LISTENconnection and an in-memory indexworkspace → subscribers. - 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. - Payloads over 7 KB are sent as references (
ref: true) to stay under NOTIFY's 8 KB limit. - 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
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… →doneon the same response. - Fire-and-forget:
202immediately; 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);Echoruns 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 inBISCUIT_LLM_MODELSgo toBISCUIT_LLM_BASE_URL, the rest to Groq; if our server fails before the first token, Groq answers withGROQ_MODEL. Tool calls for the bot's computer route the same way.
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 SSEstep; results go back astoolturns 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_usagerow (workspace, bot, provider, model, tokens, latency, ok, fell back) for metering and for comparing our models with Groq;biscuit_llm_fallbacks_totalcounts fallbacks. - Attachments: files are uploaded first with
POST /v1/attachments(up to 10 per message, 20 MB each, stored per workspace) and referenced frombody.attachmentson 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
~~~uiblock of JSON or Markdown lines) with its own state and formulas.internal/api/genui.goholds the rule and the brief that varies per question;apps/web/src/genuireads 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:
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):chromestarts one local Chrome per task over a pipe, with a throwaway profile deleted on close;remotedrives 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
remotebackend 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/chatanswers{configured: boolean}; the apps probe it once and fall back to demo replies when it saysfalse.POST /api/chatpasses through onlymodel,messages,temperature,max_tokens,reasoning_effortandresponse_format, pins the model toGROQ_MODEL(defaultopenai/gpt-oss-120b), capsmax_tokensat 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 (
OnFirstEventreplays it); charts, diagrams and GSAP load the first time they're used. - Caching layers: content-hashed
/assets/*areimmutablefor 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: autoso off-screen items cost nothing. - Budget enforced in CI:
scripts/bundle-budget.mjsfails 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 overfetch(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 withIf-None-Matchagainst the API's ETags. Writes and live events drop the affected entries; sign-in changes and resyncs clear it. Nothing is persisted.
Desktop app
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_URLandVITE_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), openinghttp(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
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 useexpo-glass-effect, with a bordered panel as the fallback. - Biscuit's design system.
src/lib/theme.tscarries the same tokens asapps/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.jswatchesapps/web/src;src/lib/shared.tsimports 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.tsasks 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_modulesand lockfile. The release script still bumps its version with the others. - Browser preview.
npx expo start --webruns it in a browser.