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.
Case study · technical assessment
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.
Scroll, or use the section list ↓
01 · What it is
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.
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.
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.
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.
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
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.
Counted per row of the status table; some spec features have more than one row.
03 · The stack and why
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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
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.
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.
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
A request passes through six layers. The interesting code sits behind small interfaces, so callers learn little and tests can swap the edges.
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.
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.
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.
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
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.
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.
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.
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.
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
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.
withSecurityHeaders stamps every response, refusals too: nosniff, X-Frame-Options DENY, CSP frame-ancestors 'none', COOP, Referrer- and Permissions-Policy, HSTS on https.
09 · Life of a Studio item
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.
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.
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 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
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.
The module
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.
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.
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.
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.
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.
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
ingestfetch → 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.
artifactload → 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.
researchload → discover (+ report for deep research)
Results are written only while the job is still researching, so Cancel wins over a late result.
reportreport
A deep research report retried on its own, with a 15-minute timeout because it searches the web many times.
11 · Cited chat
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.
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.
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.
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
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.
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.
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.
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.
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
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.
INPUT_VALIDATIONAPP_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.
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.
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.
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
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.
| Door×Control | Security headersevery response | SessionrequireAuth | Admin rolerole = admin | 2FATOTP | Rate limitDB · AI windows | focusInput validationZod | SSRF guardfetch-url.ts | Audit / error logappErrorLog · outbox | Cache 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.
15 · Quality and security
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
Strict TypeScript from one shared base config, from the database schema to the React props.
Oxlint with a client/server boundary: importing server code into a client file is an error.
Vitest next to the code, plus database suites against a real pgvector Postgres.
The production build fails if strings that only exist on the server reach the browser.
Oxfmt on changed files, so diffs stay about behaviour.
Defences
Sessions read from the database on every request, so bans and revocations apply at once. Credential endpoints are rate-limited.
URL import blocks private and metadata addresses and re-checks redirects. HTML exports are sanitized and CSV exports escape formulas.
AI rate limits and budgets, 300 sources per notebook, 8,000-character questions, limited invites and error reports.
nosniff, frame-ancestors none, a strict referrer policy, a permissions policy and HSTS on https.
16 · What I avoided
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
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.
ci.ymlTypecheck, 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.ymlDeploys 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.ymlOn push to main: apply pending migrations to production, build, then wrangler deploy.
emergency-shutdown.ymlTurns 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
Pure logic gets fast unit tests. Anything that crosses a seam is tested through its interface, and the database suites run against real Postgres.
Chunking, citations, prompts, the SSRF guard, job steps and dispatch, the usage meter, rate-limit windows, AI and admin procedures.
Components with Testing Library, the error boundary, chat error mapping, the admin guard, security headers, locale parity between English and Portuguese.
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.
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
Chunking, citations, prompt building, the rate-limit window, the usage meter and the Studio scoring are plain functions tested against literal values.
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.
Testing Library renders the sign-in page, the error boundary, dialogs and admin panels, and clicks through them.
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.
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.
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
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.
The screens rebuilt as plain HTML over several QA rounds, with reference screenshots.
The clone ported 1:1 into TanStack Start, with a real backend behind it.
Ingestion, cited chat, nine Studio generators and research on TanStack AI.
Template leftovers removed: mobile app, billing, push, demos, organizations.
Twenty-eight findings, from SSRF bypasses to leaky member lists. Most fixed.
Long jobs moved to durable steps; audio moved to R2; dev moved onto workerd.
Every feature tried in a real browser; bugs fixed and recorded.
Usage metering, rate limits, Google sign-in, error boundaries, the admin area.
The tools in the loop
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.
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.
Delegated implementation
Through the grok-first skill, Grok Build takes implementation and exploration tasks while Claude writes the brief and checks the result.
Verification
A real browser session against the dev server or production: screenshots, console logs and network, the evidence behind docs/STATUS.md.
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.
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.
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
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.
startupsetup-envsdeploy-cloudflareagent-browserBoot dev on workerd, manage env files and secrets, deploy Workers and previews, and drive a real Chrome to verify a change.
codebase-designimprove-codebase-architecturedomain-modelingtdddiagnosing-bugscode-reviewgrillingresearchtriagewriting-for-agentsDeep 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.
principle-prove-it-worksprinciple-make-operations-idempotentprinciple-boundary-disciplineprinciple-test-behavior-not-implementationprinciple-guard-the-context-windowPrinciples 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.
brainstormingwriting-plansBrainstorm, then spec, then plan. The specs and plans in docs/superpowers came out of that flow.
codex-firstcodex-supergrok-firstHow Claude hands implementation lanes to Codex or Grok and keeps the design and the final verdict.
typescript-best-practicesvercel-react-best-practicesvercel-composition-patternsweb-design-guidelinesRules applied while writing and reviewing: types, React performance, component composition, accessibility.
diagram-designhumanizerEditorial SVG diagrams that follow strict layout rules, and a pass that takes the machine tone out of the text.
21 · Second opinion
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.
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.
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.
Ingest and research call pages and models inside withDb. Better: split each step into a short read, the external call and a short write.
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.
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.
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
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.
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.
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.
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.
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.
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.
Each needs another model (OCR, vision, speech-to-text) with its own cost, plus a decision on sending users' files to a third party.
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.
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, 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.
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
The same terms are used in the code, the docs and this page.
24 · Try it
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:webThanks for reading. I'm happy to walk through any of it live.