Skip to content
Gemini Notebook

Case study · technical assessment

A NotebookLM clone on one Cloudflare Worker

I took a static HTML clone of Gemini Notebook and turned it into a working product: sources, cited chat, nine Studio generators, sharing, an admin area and per-user AI limits. Below is how the pieces fit, why each one is there, and what I would build next.

Worker serves the app, the API and the jobs
1
Studio generators, from podcast audio to quizzes
9
automated tests passing
376
status items working end to end
27/36
languages, English and Brazilian Portuguese
2

01 · What it is

Upload what you read, then ask it questions

Gemini Notebook is Google's NotebookLM idea: a notebook of sources the AI is told to answer from. Answers carry numbered citations that link back to the passages the model used.

01

Sources

Paste text, add a website, upload a PDF, Office file, EPUB or plain text, or let web research find pages for you. Each source is cleaned, split into passages, embedded into pgvector and summarised.

02

Chat with citations

Answers stream in as they are written. Numbered markers link to the source passage, and you get follow-up questions, the model's reasoning summary, stop and regenerate.

03

Studio

Nine generators turn the selected sources into an audio overview with two hosts, a narrated scene presentation, slides, a mind map, a report, flashcards, a quiz, an infographic or a data table.

04

Sharing and admin

Notebooks have owners, editors and viewers, plus link access. Admins see users, sessions, AI usage, errors and failed jobs in one place.

02 · Where it stands

Most of the spec works, and the rest is written down

I walked through every feature in a real Chrome with real OpenAI calls and recorded the result in docs/STATUS.md. Nothing in the spec is missing outright. The partial items are listed later on this page with the reason each one waited.

Works end to end
27 / 36
Partial
9 / 36
Missing
0 / 36

Counted per row of the status table; some spec features have more than one row.

03 · The stack and why

Each choice had to earn its place

The brief was a full product on a small team's budget. That pushed me toward pieces that remove whole categories of work: one deploy unit, one type system from database to button, and managed services for the parts that are hard to run.

TanStack Start

Full-stack React: SSR, file routes, server routes, Router and Query.

Why

It renders on the server and also hosts the API routes, so the UI and the backend ship as one app. The router is fully typed, including search params, and it runs natively on Cloudflare Workers.

Trade-off

It is younger than Next.js. A few things need care, like server-only code inside isomorphic functions, so I guard the client bundle with a build check.

Cloudflare Workers

Runtime and hosting for SSR, API, jobs, cron and assets.

Why

One Worker serves everything, and the platform supplies what a notebook app needs: Workflows for durable AI jobs, R2 for audio, an email binding and cron.

Trade-off

Workers are not Node. Postgres sockets are pinned to the request that opened them, and steps longer than about 30 seconds need Workflows instead of waitUntil.

oRPC + Zod

Typed procedures for everything except the chat stream and media.

Why

Contracts are plain Zod schemas, so the client gets types and validation without generated code. Typed error codes travel to the client, and OpenAPI docs come for free.

Trade-off

It is a smaller community than tRPC, and version 2 is still in beta. I pin the version and keep procedures thin.

Drizzle + Neon (pgvector)

SQL-first ORM over serverless Postgres, vectors in the same database.

Why

Embeddings live next to the rows they belong to, so retrieval is one SQL join filtered by notebook and selected sources. Neon branches can give each preview its own database.

Trade-off

No separate vector store means pgvector tuning is on me; filtering before the HNSW index is on the tech-debt list.

Better Auth

Sessions, email verification, reset, 2FA, passkeys, admin, Google.

Why

It stores sessions in my own database and comes with plugins for the hard parts: TOTP with lockout, passkeys, bans and impersonation, OAuth. Rate limits on the credential endpoints are built in.

Trade-off

Plugin typing is heavy, so I keep the full auth object out of shared types and expose narrow interfaces instead.

TanStack AI + OpenAI

Chat streaming, structured output, embeddings and text-to-speech.

Why

The streaming protocol (AG-UI) works the same on server and client, structured output is validated against Zod, and middleware hooks let me meter every call in one place. Most model calls go through one module; switching providers would also touch the model list and the web-search tool.

Trade-off

The library is new and moves fast. I checked each API against the installed package before using it and wrote the findings down.

04 · The repository

One app, eleven packages, one rule about imports

A pnpm workspace driven by Turborepo. The web app is the only deployable; everything else is a package it depends on, grouped by who may import it.

Monorepo layoutThe repository root splits into the web app, server-only packages, shared leaf packages and tooling.Repositorypnpm · TurborepoWeb appthe only deployableapps/web├ src/routes├ src/features├ src/styles/clone└ src/server.tsServer-onlynever imported by the browserpackages/api routers · ai · jobs usage · limits · opspackages/authpackages/dbpackages/emailpackages/envShared leavessafe on both sidespackages/errorspackages/intlpackages/uipackages/configToolingsetup, scripts, agent skillspackages/project-setup-cliscripts/.agents/skills.github/workflowsFocusRuns in the Worker
Figure 01The repository root splits into the web app, server-only packages, shared leaf packages and tooling.

Server-only packages

api, auth, db, email and env open database connections or read secrets when imported. They export nothing the browser can use, and their exports maps list every entry point instead of a wildcard.

Shared leaves

errors, intl, ui and config hold error codes and messages, the i18n runtime, shadcn primitives for the few non-clone screens, and the shared tsconfig with the lint boundary.

Tooling

project-setup-cli runs pnpm setup and pnpm doctor, scripts/ holds the test runners and preview tooling, and .agents/skills carries the playbooks the coding agents load. packages/storage is a template leftover with no importer.

05 · Architecture

One Worker with four doors

Pages, API, the chat stream and the background jobs are all the same deploy. The Worker talks to three services: Postgres for data and vectors, R2 for audio and OpenAI for the models.

Gemini Notebook architectureThe browser talks to one Cloudflare Worker that serves pages, the API, the chat stream and background jobs, backed by Postgres, R2 and OpenAI.ONE CLOUDFLARE WORKERHTTPSSSESQLSTART JOBAUDIOTOKENSBrowserPagesTanStack StartAPIoRPC · Better AuthChat stream/api/chat · SSEBackground jobsNotebookJobWorkflowCron: audit outboxscheduled()DatabaseNeon · pgvectorAudio filesMEDIAModelsTanStack AIEmail bindingFocusRuns in the WorkerStorageExternal serviceAsync or optional
Figure 02The browser talks to one Cloudflare Worker that serves pages, the API, the chat stream and background jobs, backed by Postgres, R2 and OpenAI.

Why the jobs are in the same Worker

The Workflow class is just another export of the Worker entry. It reuses the same modules as the API, so a Studio job and a chat turn call the same OpenAI function and write the same tables.

What is not here

There is no queue service, no separate API server and no vector database. Each would be one more thing to deploy, secure and pay for, and the product does not need them at this size.

06 · Layers and seams

Thin edges, deep modules in the middle

A request passes through six layers. The interesting code sits behind small interfaces, so callers learn little and tests can swap the edges.

Application layersSix layers from the React UI down to Postgres, R2 and OpenAI, with procedures and seams in the middle.01Clone UIReact components, clone CSSfeatures/* · styles/clone/*.css02RoutesSSR pages, server routesroutes/* · /api/chat · /api/media03Proceduresauth · limits · meteringrouters/*.ts · limits/procedure.ts04Domain servicesaccess, ingest, chat, studionotebook/* · jobs/*-job.ts05SeamsOpenAI, steps, usage scopeai/openai.ts · jobs/steps.ts · usage/scope.ts06InfrastructurePostgres, R2, OpenAIpackages/db · R2 · OpenAI · Better AuthFocusRuns in the WorkerStorage
Figure 03Six layers from the React UI down to Postgres, R2 and OpenAI, with procedures and seams in the middle.

The OpenAI seam

Four functions in ai/openai.ts are the only way the code reaches a model: streamChat, generateObject, embedBatch and speak. Reasoning settings and metering live there; model ids sit next door in models.ts.

The step runner

Every long job is written against a two-line interface, steps.do(name, fn). On Cloudflare it is a durable Workflow step; in tests and on Node it is a plain call. The same job code runs in both.

The usage scope

Entry points open an AsyncLocalStorage scope that says who is paying and for which feature. Code in between never passes a user id around. Calls made inside a scope are recorded against that user, on a best-effort basis.

Client-safe contracts

Zod contracts and enums live in leaf files with no imports from the server. A lint rule and a build check keep it that way, because a barrel file once shipped the database schema to the browser.

07 · Infrastructure

Five layers of one object

Pull the deployed system apart and it is a single stack: the Worker's fetch on top, storage at the base. Every request travels down through the layers, and the oRPC procedures in the middle are where it gets checked.

Infrastructure stack, explodedExploded view of the deployed stack from top to bottom: the Cloudflare Worker fetch, the TanStack Start router, the oRPC procedures as the focal layer, notebook services beside the job workflow, and Postgres beside R2 media storage.R2 mediaMEDIA · generated audioPostgresneon · pgvector · via hyperdriveNotebook servicesdomain logic · drizzleJob workflowNotebookJobWorkflow · 2 retriesoRPC proceduressession · role · ai limits · zod inputStart routerssr · /api/rpc · /api/chat · /api/auth · /api/mediaWorker fetchrequest scope · security headers
Figure 04The deployed stack, exploded along the request path. Parts on one level sit side by side; the oRPC procedures (in blue) are where every call is checked.

Edge

One Cloudflare Worker answers every request. Its fetch opens a request scope in AsyncLocalStorage, hands off to TanStack Start, and adds the security headers on the way out.

Doors

The router splits traffic: SSR pages, /api/rpc for oRPC, /api/chat for the SSE stream, /api/auth for Better Auth, and /api/media for R2 reads with Range.

Procedures

Every oRPC call passes the same chain: session, the admin role where needed, the AI token budget and rate limit, then Zod input validation. /api/chat repeats it by hand.

Domain and storage

Services read and write Postgres through Drizzle, with pgvector for retrieval. Long AI work runs in NotebookJobWorkflow, and generated audio lands in R2.

08 · Infrastructure

Anatomy of a request

Every call crosses the same machine: the Cloudflare edge, one Worker, a door, a row of checks, the domain and its stores, and a stamp on the way out. A refusal leaves the line early, down a chute, with one code and one status.

Anatomy of a request, drawn as a sorting lineAn isometric sorting line on a base plate. A parcel, the request, enters a tunnel (the Cloudflare edge and the Worker fetch) and picks up a small canister, its own Postgres pool. It passes a door selector with four side lanes (SSR pages, /api/chat, /api/auth, /api/media) and keeps to /api/rpc. Four gates follow, each with a pusher and a chute to a lower return belt: the session gate (401), the role gate (403), the AI budget meter with its dial (429 with retryAfter) and the Zod sieve (422). Then the domain workshop checks notebook access (404 or 403) and is wired to the stores behind it: Postgres on Neon with pgvector, the R2 media cabinet, OpenAI and the Workflow carousel. A stamp press over both belts marks every response with the security headers.080102401034030442905422060740409
  1. 01Edge
  2. 02Doors
  3. 03Session
  4. 04Role
  5. 05AI budget
  6. 06Zod sieve
  7. 07Domain
  8. 08Stores
  9. 09Headers
09 Way out · 200 OK

withSecurityHeaders stamps every response, refusals too: nosniff, X-Frame-Options DENY, CSP frame-ancestors 'none', COOP, Referrer- and Permissions-Policy, HSTS on https.

Figure 05One Worker fetch per request, read as a sorting line. Each check is a gate with a pusher; a refused request drops down its chute onto the return belt and still gets the security headers on the way out. Pick a request to watch where it ends.

09 · Life of a Studio item

From a click to a podcast, step by step

Generating an audio overview takes a few minutes and dozens of model calls. The request returns at once; a Workflow does the work in named steps, and Cloudflare keeps each finished step's result across retries.

Generating an audio overviewA Studio request is checked and stored, then a Workflow writes the script, voices each line, stores the audio and marks the item ready while the client polls.generatecheck limitsinsert rowstart instancescript, voicesstore audioready + usagepollClientProcedurePostgresWorkflowOpenAIR2FocusRuns in the WorkerStorageExternal serviceAsync or optional
Figure 06A Studio request is checked and stored, then a Workflow writes the script, voices each line, stores the audio and marks the item ready while the client polls.

Limits come first

Before anything is written, the procedure checks the user's daily token budget and the Studio rate window. A refusal is HTTP 429 with the number of seconds to wait.

Steps checkpoint their results

Each step reloads its row by id and returns something small. A finished step is not run again; a step that fails mid-way runs again from the start, so a model call inside it can be paid twice. Text-to-speech runs as one step per line, six at a time, and each audio part goes to R2 before the next step joins them.

The client just polls

The Studio tile reads the row until it says ready or failed. No websocket to keep alive, and a closed tab loses nothing.

10 · Background jobs, inside

How a long job runs, retries and fails

Imports, Studio items and research all go through one module, packages/api/src/jobs. A mutation writes the row and starts a job; the job moves the row to ready or failed. Nothing else touches it in between.

Lifecycle of a background jobA mutation writes the row, the dispatcher starts a Workflow or an in-process run, named steps retry until the row is ready or failed.RETRY, BACKOFFJOB FAILURESTALE > 1HMutationstudio.generatePending rowimporting · generating· researchingDispatcherjobs/dispatcher.tsWorkflowdurable step.doIn-processinProcessStepsNamed stepsload · generate · tts:nstore · settleReadystatus: readyFailedstatus: failed · errorFocusRuns in the WorkerStorageAsync or optional
Figure 07A mutation writes the row, the dispatcher starts a Workflow or an in-process run, named steps retry until the row is ready or failed.

The module

One way in

startNotebookJob receives a small JSON job: the kind, the row id and who pays for it. That object is also the Workflow instance's params, so everything else is reloaded from the row.

The dispatcher

With the Workflow binding it creates a Workflow instance whose id comes from the row (ingest-<source>-<attempt>, artifact-<id>, research-<id>). A double click cannot start two runs: the second create finds the instance and stops. Without the binding, or if create fails, the same job runs in-process on waitUntil.

Steps are the seam

Jobs are written against StepRunner.do(name, fn, policy). workflowSteps maps it to step.do with retries (2 by default, exponential from 10 s) and a timeout (5 min by default). inProcessSteps just calls fn. Two adapters, so the seam is real, and tests run the same job code with a fake step.

Two kinds of failure

A JobFailure is a message the user should see and that retrying cannot fix: it is stored as the step's result, never retried, and replayed as the same message. Anything else is retried by Workflows, then the job writes failed with a generic message.

A connection per step

Workers pin a Postgres socket to the invocation that opened it, so each step opens and closes its own connection through withDb and returns something small (a Workflow step result is capped at 1 MiB). Bulk data goes to Postgres or R2.

Metered and swept

Each step runs inside the job's usage scope, so its model calls are charged to the user. A throttled sweep, run from the polled reads, marks anything still importing, generating or researching after an hour as failed.

The four job kinds and their steps

ingest

fetch → guide → chunks:clear → embed:n → overview → settle

One embed step per batch of passages. If embedding fails, embed:n:plain keeps the passages without vectors so keyword search still works.

artifact

load → generate · or · load → script → tts:n → store → settle

Text types are one model call. Audio and video write a script, voice each line as its own step (six at a time, three retries), then join the parts in R2.

research

load → discover (+ report for deep research)

Results are written only while the job is still researching, so Cancel wins over a late result.

report

report

A deep research report retried on its own, with a 15-minute timeout because it searches the web many times.

11 · Cited chat

Retrieval first, then a streamed answer

The chat route is the one place that streams. It finds the passages that match the question, numbers them in the prompt and keeps those numbers as citations when it saves the answer.

A chat turnA question is checked, embedded, matched against source passages, answered as a stream and saved with its citations.QuestionPOST /api/chatCheckssession · access · limitsEmbedtext-embedding-3-smallRetrievepgvector · top-kPrompt[n] passagesStreamSSE · AG-UISavemessage · usageCitations[n] → chunkFocusRuns in the WorkerStorageExternal serviceAsync or optional
Figure 08A question is checked, embedded, matched against source passages, answered as a stream and saved with its citations.

Retrieval

Cosine similarity in pgvector over the selected sources, with a full-text fallback when vectors find nothing. Only the top passages go into the prompt.

Grounding

Source text sits inside clear delimiters in the prompt, and the model is told to treat them as data and to answer from the numbered passages. That lowers the risk of a page smuggling in instructions; it cannot rule it out.

Persistence

When the stream ends, the server saves the question, the answer, its citations and follow-ups, then sends one final event with the saved ids. A reload shows the same thing.

12 · Usage and limits

Model calls are counted, and every user has a limit

Without limits, one script or one shared link could run up the OpenAI bill. Each AI entry point checks two things before it starts, and every call writes one usage row when it ends.

How an AI request is admittedA request must be signed in, under the daily token budget and inside the action's rate window before it runs and is metered.YESYESYESNONONOAI requestaiProcedure · /api/chatSigned in?Under budget?Inside window?Run in scoperunWithAiUsage()Record usageai_usage_event401UNAUTHORIZED429 + retryAI_RATE_LIMITED · AI_DAILY_LIMITFocusRuns in the WorkerStorage
Figure 09A request must be signed in, under the daily token budget and inside the action's rate window before it runs and is metered.

Two limits

A fixed window per action (chat, Studio, research, imports, small helpers) and a rolling 24-hour token budget per user. Both live in Postgres, because Worker isolates share no memory and an in-memory counter would never throttle.

A limit, not a reservation

The budget is checked against tokens already recorded before work starts. Two long jobs started together can both pass, and speech is counted in characters, not tokens. A hard spending cap would reserve an estimate up front and reconcile it later.

Metering

A TanStack AI middleware records tokens, model, duration and outcome for each call. If the insert fails, the call still succeeds; losing a usage row must never break a chat.

What people see

Users get a localized message with the wait time and a usage dialog in settings. Admins get usage by feature, model, user and day.

13 · Error handling

The round trip of an error

A failed call does not end in a stack trace. It leaves the server as one code with one status, and arrives on the screen as one translated sentence, with the guilty fields marked when there are any.

The round trip of an errorInvalid input fails the Zod schema, is rethrown as INPUT_VALIDATION, mapped to HTTP 422 and resolved on the client into a translated toast with field errors; rate limits answer 429 with retryAfter, server faults are written to the admin error log and shown as a generic message, and a 401 sends the browser to /login.ALT[invalid input][over the AI rate][unexpected throw][no session]POST /api/rpcparse inputBAD_REQUEST ← ValidationErrorrethrow INPUT_VALIDATION422 · flattened fieldErrorsAI_RATE_LIMITED { retryAfter }429 · retryAfterrecordServerFault → recordError500 · INTERNAL_SERVER_ERROR401 UNAUTHORIZED → /loginresolveErrorMessage → ERROR_MESSAGE_KEYStranslated messageBrowserRPCLinkoRPC handlerRPCHandlerZod schema.input(zod)Error mapperpackages/errorsAdmin error logappErrorLogi18n · toasten · pt-BRselected pathserver stepPostgresclientreply
HTTP
422
Code
INPUT_VALIDATION
The person sees
Toast “Please check the highlighted fields.”, and each message from fieldErrors next to its input.
Admin error log
No. A refusal is expected traffic.
Figure 10One request, four ways to fail. Pick a path to follow it from the procedure to what the person sees.

One code, one status, one message

APP_ERRORS is the single list of codes. APP_ERROR_STATUS_MAP gives each one its HTTP status, and ERROR_MESSAGE_KEYS gives it a sentence in English and Portuguese. Nothing on the screen is a raw server message.

Validation errors carry the fields

A Zod failure would leave oRPC as a bare BAD_REQUEST. The error mapper rethrows it as INPUT_VALIDATION with the flattened issues, so a form can put each message next to the input that caused it.

Faults are recorded, not shown

Only isServerFault errors, an unexpected throw or a 500, are written to appErrorLog by recordServerFault. The admin reads the stack in admin › Errors; the user reads a calm, generic sentence.

Limits say when to come back

AI_RATE_LIMITED and AI_DAILY_LIMIT carry retryAfter in their data, and the translation interpolates it, so the toast tells the person how long to wait instead of just “try again”.

14 · Security

Seven doors, nine controls

Every way into the Worker, checked against every control it should pass. Most doors share the same checks; the chat stream repeats them by hand, and a few cells are honest gaps.

Security matrix: each door into the Worker (rows) against each control (columns). Input validation is the focus column.
DoorControlSecurity headersevery responseSessionrequireAuthAdmin rolerole = admin2FATOTPRate limitDB · AI windowsfocusInput validationZodSSRF guardfetch-url.tsAudit / error logappErrorLog · outboxCache policyCache-Control
SSR pagesTanStack Start
/api/rpcoRPC
/api/chatSSE
/api/authBetter Auth
/api/mediaR2 · Range
/api/og + sitemappublic
Cronscheduled()

Hover or focus a cell to read why it has that state. Arrow keys move between cells.

  • Applied
  • Applied differently
  • Not applicable
  • Not yet

Not yet

  • CSP without script-src: TanStack Start hydrates with inline scripts, and a nonce pipeline is its own project.
  • No output validation: 0 .output() schemas on the procedures.
  • No request id to tie a log line to the request that caused it.
  • No CORS headers: origin trust is Better Auth trustedOrigins.
  • No rate limit on pages, media or OG images: only auth endpoints and AI calls are limited.
Figure 11Security matrix: each door into the Worker (rows) against each control (columns). Input validation is the focus column.

15 · Quality and security

Checks that run on every change

I treat a change as done when five gates pass and the feature has been used in a real browser. Security is layered so that one missed check is caught by the next.

Gates

  1. Types

    Strict TypeScript from one shared base config, from the database schema to the React props.

  2. Lint

    Oxlint with a client/server boundary: importing server code into a client file is an error.

  3. Tests

    Vitest next to the code, plus database suites against a real pgvector Postgres.

  4. Bundle check

    The production build fails if strings that only exist on the server reach the browser.

  5. Format

    Oxfmt on changed files, so diffs stay about behaviour.

Defences

  • Identity

    Sessions read from the database on every request, so bans and revocations apply at once. Credential endpoints are rate-limited.

  • Untrusted input

    URL import blocks private and metadata addresses and re-checks redirects. HTML exports are sanitized and CSV exports escape formulas.

  • Cost and abuse

    AI rate limits and budgets, 300 sources per notebook, 8,000-character questions, limited invites and error reports.

  • Headers

    nosniff, frame-ancestors none, a strict referrer policy, a permissions policy and HSTS on https.

16 · What I avoided

The shortcuts I did not take

Most of these looked faster at the time. Each one has a written reason, and several have an architecture decision record.

AvoidedBarrel files in server code

InsteadLeaf modules and explicit package exports

A convenient re-export once put the database DDL in every visitor's browser.

AvoidedLong AI work on waitUntil

InsteadCloudflare Workflows with durable steps

waitUntil is cut about 30 seconds after the response. Audio and deep research take minutes.

AvoidedAudio as data URLs in the database

InsteadR2 objects behind a range-capable route

Each audio overview was 5 to 15 MB of base64 inside one database row.

AvoidedIn-memory rate limits

InsteadCounters in Postgres

Each Worker isolate has its own memory, so the limit would reset at random.

AvoidedTrusting a cached session

InsteadA database read per request

A ban has to work now, not when a cookie expires.

Avoideddb:push

InsteadVersioned migrations with a journal table, applied before each deploy

Every schema change is reviewable and repeatable. CI applies them twice, so the second run must be a no-op.

AvoidedA second design system on the clone screens

InsteadThe clone's CSS, copied verbatim

Pixel parity with the reference. shadcn is only for screens the clone never had.

AvoidedHard-coded text

InsteadEnglish and Portuguese catalogs, errors as codes

The main UI, error messages and this page exist in both languages. A few pages outside the clone still fall back to English.

17 · Delivery

From a branch to production

The pipeline is written as GitHub Actions plus Wrangler. Each pull request is set up to get a full preview with its own Worker, its own database branch and its own Workflow, so a reviewer can click through the real thing.

From branch to productionA branch passes CI, gets its own preview, merges to main and is migrated, built and deployed to the production Worker.Branchgit push · PRci.ymlCheckstypes · lint · testspr-preview.ymlPreviewown Worker + DBMergemaindeploy-prod.ymlReleasemigrate · buildProductiongoogle-notebook-webemergency-shutdown.ymlKill switchFocusAsync or optional
Figure 12A branch passes CI, gets its own preview, merges to main and is migrated, built and deployed to the production Worker.

ci.yml

Typecheck, lint, format, migrations applied twice (the second run must be a no-op), all tests on a pgvector service, and the bundle check.

pr-preview.yml

Deploys google-notebook-web-pr-N with a Neon branch and a separate jobs Workflow, and removes the Worker and the branch when the PR closes. The preview Workflow is left behind, a known gap.

deploy-prod.yml

On push to main: apply pending migrations to production, build, then wrangler deploy.

emergency-shutdown.yml

Turns the workers.dev URL off and back on in seconds. It does not block the custom domain; that needs the route disabled or a WAF rule. A second workflow deletes the Worker for good.

Actions is enabled on this repository, but no workflow run has been recorded yet. So far every release went out from a laptop with the same steps the workflow runs: pnpm db:migrate, build, wrangler deploy. Previews have not run for the same reason.

18 · Tests

Tests sit next to the code they protect

Pure logic gets fast unit tests. Anything that crosses a seam is tested through its interface, and the database suites run against real Postgres.

API

148

Chunking, citations, prompts, the SSRF guard, job steps and dispatch, the usage meter, rate-limit windows, AI and admin procedures.

Web

170

Components with Testing Library, the error boundary, chat error mapping, the admin guard, security headers, locale parity between English and Portuguese.

Auth

38

Base URLs, session and 2FA outcomes, the audit plan, admin email parsing. The audit-durability suite runs real sign-ups when a test database is set.

Errors

20

Every error code resolves to a message in both languages and maps to its HTTP status.

376 passing across 4 packages on 2026-10-08, plus database suites that run when a test database is configured.

How they are written and run

Pure logic, literal expectations

Chunking, citations, prompt building, the rate-limit window, the usage meter and the Studio scoring are plain functions tested against literal values.

Through the interface

Procedures are called with createRouterClient and fake sessions, the way the app calls them: signed out, wrong role, over the limit. Jobs run through a fake Workflow step to prove retries and JobFailure behave.

Components in jsdom

Testing Library renders the sign-in page, the error boundary, dialogs and admin panels, and clicks through them.

Real Postgres when it matters

pnpm test:integration starts a temporary local Postgres and applies every migration twice; the second run must be a no-op. CI does the same on a pgvector service.

A real OpenAI smoke test

Opt-in (RUN_OPENAI_SMOKE=1): embeddings, structured output, a streamed cited answer, web search and text-to-speech against the live API. Last run on gpt-6-luna, 5 of 5.

Build and browser

The production build fails if server code reaches the client. Visible changes are then used in a real Chrome against the dev server on workerd.

19 · How it was built

Three days, eight phases

I worked with AI coding agents under written rules, the way I would brief a team: a spec, a definition of done and a record of every decision.

Project timelineEight phases from the static clone to usage limits and the admin area.BEFOREStatic cloneOCT 3PortOCT 3AI featuresOCT 4CleanupOCT 4Debt auditOCT 4WorkflowsOCT 4WalkthroughOCT 5Limits & admin
Figure 13Eight phases from the static clone to usage limits and the admin area.
  1. before

    Static clone

    The screens rebuilt as plain HTML over several QA rounds, with reference screenshots.

  2. Oct 3

    Port

    The clone ported 1:1 into TanStack Start, with a real backend behind it.

  3. Oct 3

    AI features

    Ingestion, cited chat, nine Studio generators and research on TanStack AI.

  4. Oct 4

    Cleanup

    Template leftovers removed: mobile app, billing, push, demos, organizations.

  5. Oct 4

    Debt audit

    Twenty-eight findings, from SSRF bypasses to leaky member lists. Most fixed.

  6. Oct 4

    Workflows

    Long jobs moved to durable steps; audio moved to R2; dev moved onto workerd.

  7. Oct 4

    Walkthrough

    Every feature tried in a real browser; bugs fixed and recorded.

  8. Oct 5

    Limits & admin

    Usage metering, rate limits, Google sign-in, error boundaries, the admin area.

The tools in the loop

Claude Code

Lead and integrator

Plans the change, writes most of it, runs the five gates, drives Chrome to verify, and splits independent work into sub-agents that each own a set of files.

Codex CLI

Second opinion and parallel lanes

GPT-6 Sol at high reasoning effort reviews the stack and fact-checks docs; it also takes hands-on lanes through the codex-first and codex-super skills. The architecture infographic came from it.

Grok CLI

Delegated implementation

Through the grok-first skill, Grok Build takes implementation and exploration tasks while Claude writes the brief and checks the result.

Claude in Chrome

Verification

A real browser session against the dev server or production: screenshots, console logs and network, the evidence behind docs/STATUS.md.

Rules the agents follow

AGENTS.md sets the client/server boundary, the migration workflow and the design authority. CONTEXT.md fixes the vocabulary, so a Notebook, a Source and an Artifact mean the same thing in code, docs and chat.

Parallel work with clear ownership

Independent pieces run as parallel sub-agents that each own a set of files. While one built the admin screens, another thread changed auth and chat. I review, integrate and commit.

Evidence over claims

Status in the docs cites what was run: the HTTP status seen, the screen checked, the test that covers it. When I found a bug while verifying, the fix and its test went in the same change.

20 · Agent skills

Instructions packaged for the agents

A skill is a short playbook an agent loads for one kind of task. The project carries its own in .agents/skills, and I used a few more while writing this page.

Run and ship (this repo)

  • startup
  • setup-envs
  • deploy-cloudflare
  • agent-browser

Boot dev on workerd, manage env files and secrets, deploy Workers and previews, and drive a real Chrome to verify a change.

Matt Pocock's engineering skills

  • codebase-design
  • improve-codebase-architecture
  • domain-modeling
  • tdd
  • diagnosing-bugs
  • code-review
  • grilling
  • research
  • triage
  • writing-for-agents

Deep modules and seams, architecture reviews, the glossary and decision records, test-first fixes, a diagnosis loop, two-axis reviews, stress-testing a plan before building it, sourced research, issue triage and agent docs.

poteto-mode (pstack)

  • principle-prove-it-works
  • principle-make-operations-idempotent
  • principle-boundary-discipline
  • principle-test-behavior-not-implementation
  • principle-guard-the-context-window

Principles that shaped concrete choices: idempotent job steps, guards only at system boundaries, tests that assert literal results, verification against the real artifact, bulk reading pushed to sub-agents.

superpowers

  • brainstorming
  • writing-plans

Brainstorm, then spec, then plan. The specs and plans in docs/superpowers came out of that flow.

Delegation

  • codex-first
  • codex-super
  • grok-first

How Claude hands implementation lanes to Codex or Grok and keeps the design and the final verdict.

Code and UI quality

  • typescript-best-practices
  • vercel-react-best-practices
  • vercel-composition-patterns
  • web-design-guidelines

Rules applied while writing and reviewing: types, React performance, component composition, accessibility.

This page

  • diagram-design
  • humanizer

Editorial SVG diagrams that follow strict layout rules, and a pass that takes the machine tone out of the text.

21 · Second opinion

An independent review by Codex

I asked Codex CLI, running GPT-6 Sol at its highest reasoning effort in a read-only sandbox, to judge the stack against the code and to fact-check this page. It found real problems. The copy above already carries its corrections; the risks it ranked are below, in its order.

The architecture is coherent for a small product, but the page presented several conditional behaviours as guarantees. The largest operational gap is that a failed Workflow dispatch falls back to waitUntil. The AI limits are useful controls, not a hard spending ceiling.

Codex CLI 0.160 · gpt-6-sol · reasoning effort xhigh · read-only · 2026-10-08

1 · Durability of the fallback

When Workflow creation fails for any reason other than an existing instance, the job runs in-process on waitUntil. Better: keep the row retryable and reconcile it through a durable path.

2 · The AI ceiling is soft

Admission reads tokens already recorded, so concurrent or long jobs can pass together. Better: reserve an estimate when the job starts and reconcile real usage afterwards.

3 · Connections across slow calls

Ingest and research call pages and models inside withDb. Better: split each step into a short read, the external call and a short write.

4 · Sign-up without verification

Production lets an unverified email sign in. That is deliberate for this test deployment; a public launch should require verification and test it in CI.

5 · Thinner release evidence

CI has never run on this repository, the migration journal stores names without checksums, and there is no deploy smoke gate or end-to-end Worker test.

6 · Narrower boundary claims

SSR still imports the whole router (a documented exception), and the bundle check looks for known strings rather than walking the import graph.

22 · What is left, and why

What is still open, how big it is, and why it waited

Most of these waited for time, not because they were hard: I went deep on the core loop first. Each item says what it would take and whether anything besides time is missing. Two items from an earlier version of this list, PDF import and saved viewer progress, were built after a reviewer asked why they were missing.

  1. Harden the job path4–8 days

    Time. Codex's review ranked it first: a failed Workflow dispatch falls back to waitUntil, some steps hold a database connection during slow model calls, and the AI budget is a check rather than a reservation. Reserving cost also needs one decision: how much to estimate per job and what to do on overrun.

  2. End-to-end tests2–4 days

    Time, no decision needed. Today it is unit and integration tests plus a scripted browser walk. A Playwright path (sign in, add a source, chat, generate a Studio item) with recorded OpenAI responses comes next.

  3. Observability0.5–2 days

    Partly there: Workers Logs and traces are on, and server faults and failed jobs show up in the admin area. Missing are job and artifact ids on every log line, failure-rate graphs and one alert. Sentry would add client stack traces with source maps for a few more days. Prometheus and Grafana fit long-running servers better; on Workers, Sentry or Cloudflare's own Analytics Engine is the shorter path.

  4. Invites for people without an account2–4 days

    Time plus two decisions: how long an invite stays valid, and whether signing up with the invited email grants access by itself. It also closes a privacy gap: today the invite form reveals which emails have accounts.

  5. 2FA and passkey settings screens1–3 days

    Time only. The server already supports both and the 2FA sign-in challenge exists; the screens to turn them on and manage them left with the template.

  6. Scanned PDFs, images, audio, YouTube transcripts3–8 days each

    Each needs another model (OCR, vision, speech-to-text) with its own cost, plus a decision on sending users' files to a third party.

  7. Discover, Analytics, Web Push1–3 weeks

    Product decisions first: who may publish a notebook and how it is moderated, which activity Analytics counts and its privacy threshold. Web Push also needs VAPID keys and background delivery.

  8. A real brand1–3 days

    An identity decision, not engineering: a name, a logo and copy of our own. The press quotes on the landing page must go before anything public.

Done after review

PDF and Office files

PDF, Word, PowerPoint, Excel, OpenDocument, RTF and EPUB are converted to Markdown in the browser with anydoc (WebAssembly, loaded only when someone uploads a document), then imported like any text. Scanned PDFs without a text layer are refused with a clear message, because anydoc does no OCR.

Saved viewer progress

Quiz answers, flashcard position and marks, and the audio or video position are saved per user in an artifact_progress table and restored when the item is opened again, on any device. A regenerated item starts fresh, since Retry creates a new artifact.

23 · Glossary

Words with one meaning here

The same terms are used in the code, the docs and this page.

Notebook
A collection of Sources owned by one user and shared through members or a link.
Source
Text the AI may answer from, split into passages and embedded.
Citation
A numbered link from an answer back to the passage it used.
Artifact
Something Studio generated: audio, slides, a quiz and so on.
Seam
A place where behaviour can be swapped without editing callers, like the OpenAI module.
Workflow step
A named, retryable unit of a long job whose result Cloudflare keeps.
Usage scope
The context that tells the meter who pays for a model call.

24 · Try it

Run it in five commands

You need Node 22, pnpm, a Postgres with pgvector and an OpenAI key. The setup wizard writes the env files and can create a Neon database for you.

pnpm installpnpm setuppnpm doctorpnpm db:migratepnpm dev:web

Thanks for reading. I'm happy to walk through any of it live.

↑