01 / The problem
A chat box is the easy part.
I started Aegis to make the browser-to-model path concrete, then kept asking what changes when more than one person depends on it. Which account owns a conversation? What happens when access is disabled mid-session? How do request limits behave when two prompts arrive together? And when a stream breaks halfway through, what should the database say happened?
The project grew in small steps: chat and a route handler, streamed responses, relational persistence, multi-turn context, authentication, role checks, admin controls, audit events, and finally concurrency and failure tests. The useful work turned out to be around the model call, not just the prompt itself.
Keep each boundary visible: browser input is untrusted, access is checked on the server, writes are short and transactional, and provider output is not considered complete until the provider says it is.
02 / Request lifecycle
A request with a few guardrails.
This is the private authenticated chat path. The app checks the local invariants first, releases the database transaction, then calls the provider.
- 01 Browser Submits a message with the HttpOnly session cookie.
- 02 Next.js route Checks origin, identity, request shape, and policy.
- 03 SQLite admission Checks owner/quota; records one user message and usage row.
- 04 OpenAI stream Receives the ordered recent history and current prompt.
- 05 Browser SSE Renders text deltas as they arrive.
After a successful completion: the server stores one complete assistant message in SQLite, then sends the final done event. No transaction stays open during model generation.
The browser sends JSON and its same-origin session cookie to POST /api/chat. The route checks the request origin, resolves the current user, validates the body and conversation ID, then checks the account's AI policy. Admission rechecks status and policy in the write transaction, verifies that the conversation belongs to the user, loads the recent history, checks the UTC-day request count, and records the new user message plus one usage row.
For an existing conversation, the server sends up to 12 earlier messages in insertion order and then the current message exactly once. For a new conversation, it creates the owner-scoped conversation and inserts the user message before calling OpenAI. The provider never receives an unbounded database transcript.
03 / Stream lifecycle
Fast feedback, explicit completion.
The route streams provider events as Server-Sent Events. Each output-text delta is accumulated server-side and forwarded to the browser, where the chat client parses events and appends text to the current assistant message. The client also passes an abort signal; disconnecting cancels the upstream request.
const openaiStream = await openai.responses.create({
model: "gpt-6-luna",
input: [...admission.history, { role: "user", content: message }],
stream: true,
});app/api/chat/route.ts · current source A browser can display partial text before generation ends, so “visible” and “durable” are different states. The server waits for the provider's explicit response.completed event before persisting. Errors, incomplete responses, cancellation, and persistence failures emit safe error events and never create a successful assistant row.
if (event.type === "response.output_text.delta") {
assistantText += event.delta;
yield { event: "delta", data: { text: event.delta } };
}
// After response.completed, write one complete assistant row.
persistAssistant(assistantText);lib/chat-stream.ts · excerpt If generation fails after admission, the user message and request-usage row remain. That gives the conversation a record of the attempted prompt and counts it against the request allowance; no assistant message is written. The current design has no retry-state marker or automatic deduplication.
04 / Data model
Conversations have owners. Messages have order.
SQLite is the database; Drizzle is the TypeScript query and migration layer. In db/schema.ts, a conversation has a required foreign key to its user, and each message belongs to a conversation. This keeps ownership and ordering queryable instead of packing the transcript into one JSON value.
Foreign keys connect the records; checks constrain allowed roles and statuses; indexes support the access paths. A migration records each schema change so the same table structure can be applied consistently on a fresh database. The private chat history loader uses the most recent 12 message rows. Persistence is not model memory: those rows affect an answer only when the server includes them in that request.
05 / Concurrency and integrity
Check and claim the slot together.
If a user has one request left, two overlapping requests must not both read the same old count and pass. `admitChatRequest` uses an immediate SQLite transaction to serialize the status, ownership, policy, quota, and insert sequence. Public demo counters use the same pattern for their fixed-window check-and-increment.
request ABEGIN IMMEDIATE → count → admit + insert → COMMIT
request Bwait → read updated count → reject at limit
Provisioning hashes passwords before opening the transaction, then inserts users and their audit rows together. Status and AI policy changes likewise couple the business write to its audit record. If an audit insert fails, the mutation rolls back. The network request to an AI provider is never inside one of these transactions.
database.transaction((transaction) => {
updateAccount(transaction, targetUserId, nextStatus);
writeAuditLog(transaction, {
actorUserId,
action: "user.disabled",
targetUserId,
});
}, { behavior: "immediate" });lib/admin-user-transactions.ts · simplified excerpt Independent SQLite connections exercise the last-quota-slot race. Locks can still be busy and fail; there is no retry queue. This is a single-instance local-file design, not distributed coordination.
06 / Identity and governance
The UI is not the permission check.
Identity
Passwords are hashed with Argon2id. A signed JWT lives in an HttpOnly, SameSite cookie. On each protected request, the server verifies the token and reloads the account's current role and status from SQLite, so a disabled account is rejected before that token expires.
Administration
Server-side helpers enforce member and admin access for pages and API routes. Admin controls cover bounded bulk provisioning, account enable/disable, per-user AI availability, prompt length, daily request count, and a recent audit log. Cookie-authenticated mutations also use same-origin checks.
The audit log is application-append-only: it records successful mutations with actor, target, action, small safe metadata, and timestamp. It does not store plaintext passwords, password hashes, session tokens, API keys, or prompts. It is not tamper-proof against a host or database-file owner, and it is not delivered to an external SIEM.
Aegis records admitted request counts and applies prompt-size and request-per-day limits. It does not currently measure model tokens, latency, or currency cost, and application quotas cannot guarantee provider spend.
07 / Demo boundaries
Synthetic state stays separate.
The synthetic /demo playground keeps sample people, policies, scripted chat, and illustrative audit events in browser state. Those scripted interactions do not call OpenAI or read/write real account records. A separate optional live demo path posts to /api/demo/chat, uses a distinct Groq-compatible key, and is disabled unless explicitly configured and the provider free tier has been operator-verified.
That optional route has prompt/output/time bounds, a small concurrent-inference cap, and persisted abuse counters; it does not save demo prompts or replies as user conversations. The app itself is not publicly hosted, and there are no shared public Aegis credentials. Private chat uses the separate server-only OPENAI_API_KEY.
08 / Verification
Tests that keep the claims honest.
The checks run locally and in GitHub Actions use synthetic fixtures; they do not call OpenAI or Groq.
Lint, TypeScript, and the webpack production build are also part of CI. Passing tests show that these modeled cases behave as expected; they do not prove a future deployment, provider billing limits, restore reliability, or multi-host behavior.
npm run lint
npx tsc --noEmit
npm run test:sse
npm run test:step11
npm run test:demo
npm run build -- --webpackLocal and CI verification 09 / What I learned
Useful constraints, visible edges.
- Persistence is not context. A conversation can survive refresh while the model sees only the bounded history the application chooses to send.
- Streaming changes durability. Partial output can reach the browser, but only a confirmed complete result becomes an assistant row.
- Transactions stop at the network boundary. Keep local invariants atomic; don’t hold a SQLite writer lock while waiting for inference.
- Current state beats stale claims. Checking role and status from SQLite makes access changes effective without waiting for JWT expiry.
The trade-off is a small system that is easy to run and explain, but deliberately not horizontally scalable. Moving beyond one host would mean replacing local SQLite assumptions, reconsidering shared rate limits, and adding operational work such as backups, restore drills, TLS, monitoring, and key rotation.