Deterministic end-to-end tests for an AI product: a scripted fake model

by Chanan Braunstein, Owner

TripEagle is a group trip planner with an AI, Kestrel, in most of its screens. Kestrel answers a traveler's questions, reads forwarded booking emails, turns a pasted itinerary into days, reads receipts, writes the blurbs on the trip site, and interviews a new planner before drafting a whole trip. A screen that shows any of that has a model call behind it.

TripEagle has two end-to-end suites: Playwright specs for the web app and Maestro flows for the phone app. Both drive a built server, and neither ever reaches a real model. This post is about how: one switch that turns the server into the suite's server, a fake model that answers from a script, a fake Stripe that still runs the real webhook, and a browser that can't resolve any host but the laptop's.

This is the sixth post in Techniques from TripEagle, after self-hosting a world map. The code is simplified from the TripEagle monorepo so it stands on its own.

Why the suites can't use a real model

The obvious first attempt is to give the suite server an API key and let it call the model. It fails for reasons that have nothing to do with the model's quality.

  1. You can't assert on the answer. A spec wants to check that the traveler's question was asked and the answer came back and stayed in their history. A real model words it differently every run, so the best you can assert is "some text appeared", which also passes when the text is an error message.
  2. The answer has to pass its checks. Every AI feature in TripEagle checks the model's output with a schema and a domain check before anything lands (more on that). A real model fails those checks now and then, which is the right behaviour in production and a flaky spec in a suite.
  3. It costs money and time. A full interview and first draft makes a call for every interview turn, one for the trip's shape, one for each region's days, and more for the packing list and the blurbs. Run that on every spec, every retry and every developer's laptop, and the suite has a bill and minutes it didn't need.
  4. It puts a key where keys don't belong. Every CI runner and every laptop running the suite would hold a production-grade model key.
  5. An outage fails your build. A rate limit or a provider incident turns a change to a button into a red pull request.

And none of it buys anything. The suites test our path: the call is made, the answer goes through its checks, it lands where the feature lands things, and the screen shows it. Whether a real model answers well is a different question, measured by a separate red-team script on the real models, outside CI.

So the suite gets a fake. The rest of this post is about making the fake safe and making it deterministic.

One switch, read in one place

Every fake the suite uses sits behind one environment variable, SUITE_SERVER. Only the script that starts the suite's server sets it. Nothing reads it directly: everything that behaves differently on the suite server asks one function.

export const suiteServerSetting = 'SUITE_SERVER'

/** Whether this is the suite's server. With the switch on anywhere else, it throws. */
export function onSuiteServer(env: Env): boolean {
  refuseDeployedSuiteServer(env)
  return Boolean(env[suiteServerSetting])
}

Then each adapter that has a fake picks it here:

export function createModel(env: Env): Model {
  if (onSuiteServer(env)) return createSuiteModel()
  if (!env.ANTHROPIC_API_KEY) return unavailableModel('ANTHROPIC_API_KEY is not set')
  return realModel(env.ANTHROPIC_API_KEY)
}

export function createStripe(env: Env): Stripe {
  if (onSuiteServer(env)) return createSuiteStripe()
  // ...
}

It didn't start as one switch. The fake model came first, behind its own SUITE_FAKE_MODEL setting. When the suite next needed to lift the sign-in rate limits, the obvious move was a second setting with its own guard. Instead the first was folded into a general one, so each fake after it (Stripe, then a media bucket, then place search) added a branch and nothing else: no new setting to forget to unset, and no new guard to get wrong.

Refusing to start in production

A switch that makes the server answer from a script, lift rate limits and take payments on a fake page must never be on in a deployment. So with it on, the process checks that it looks like the suite's server, and stops if it doesn't:

const localHosts = new Set(['localhost', '127.0.0.1', '[::1]'])

/** What says this process is deployed, or undefined when nothing does. */
function deployedBy(env: Env, raw: Record<string, unknown>): string | undefined {
  const fly = Object.keys({ ...raw, ...env }).find((name) => name.startsWith('FLY_'))
  if (fly) return `${fly} is set`
  if (env.ANTHROPIC_API_KEY) return 'ANTHROPIC_API_KEY is set'
  if (env.STRIPE_SECRET_KEY) return 'STRIPE_SECRET_KEY is set'
  const db = URL.parse(env.DATABASE_URL ?? '')?.hostname ?? ''
  if (!localHosts.has(db)) return "DATABASE_URL isn't on this machine"
  return undefined
}

export function refuseDeployedSuiteServer(env: Env, raw: Record<string, unknown> = {}) {
  if (!env[suiteServerSetting]) return
  const deployed = deployedBy(env, raw)
  if (deployed) {
    throw new Error(`${suiteServerSetting} is for the suite's server alone, and ${deployed}`)
  }
}

The checks are things a deployment always has and the suite never does. The host sets FLY_ variables on every machine, production and previews alike, and most of them aren't in the app's own env schema, so the check reads the raw environment too. The suite never has a model key or a Stripe key, since both are faked. And the suite's database is always on the laptop, while a deployment's never is. So the check would also refuse a deployment on some other hosting provider, which sets no FLY_ variables.

Where it runs matters as much as what it checks. The web process builds its adapters lazily, on the first request that needs them, and the health check doesn't need them. A deploy with the switch on would pass its health check and go live, and only throw when a traveler asked Kestrel something. So the server's entry point calls refuseDeployedSuiteServer before it serves anything, the background worker's entry points call it at start too, and createModel calls it again as it's built. A deploy with the switch on fails its health check and never takes traffic.

The script

The unit tests already had a fake model: a queue. A test pushes the answers it expects, the code under test makes its calls, and each call takes the next answer.

const model = createFakeModel()
model.answers({ output: { blurb: 'A harbour town.' } })
await writeBlurb(place, { model })

That's right for a unit test, where one test owns the fake and knows the order of its calls. It's wrong for the suite server, which is long-lived. One server serves every spec and every phone flow in the run, a retried spec makes its calls again, and two background jobs can finish in either order. An answer queued for the blurb would be taken by the receipt scan, and from then on every answer would be one call off.

So the suite's model answers each call by what it asks, never by when it arrives. A call says three things about itself:

  • its kind: a one-shot ask, a tool-using turn, or a streamed converse;
  • its feature: blurbs, receipt_scan, forwarded_booking and so on;
  • its schema: the shape of the structured output it wants.

The schema is the most useful of the three. One feature can make several calls that want different shapes, and the interview wants a different schema for each card it's due to show. Every call builds its schema from the same exported constant, so the fake can tell them apart by comparing them:

/** Whether a call is held to `schema`: the same JSON, since each call builds its own copy. */
const heldTo = (call: { schema: unknown }, schema: unknown) =>
  JSON.stringify(call.schema) === JSON.stringify(schema)

The script is then a table: for each kind, for each feature, a function that answers the call or returns undefined when it has nothing for it.

type Scripted<C> = (call: C, now: Date) => FakeAnswer | undefined

export const suiteKestrelAnswer = "Kestrel answers this from the suite's script."
export const suiteBlurbOf = (name: string) => `${name}, as the suite's script describes it.`

export const suiteReceiptReading = {
  amount: 38.5,
  currency: 'EUR',
  date: '',
  category: 'food_and_drink',
  merchant: 'Taverna Katina',
}

export const suiteScript: {
  ask: Partial<Record<ModelFeature, Scripted<ModelAsk>>>
  turn: Partial<Record<ModelFeature, Scripted<ModelTurn>>>
  converse: string
} = {
  ask: {
    // Every receipt, whatever the picture, is the same taverna's bill.
    receipt_scan: (ask) =>
      heldTo(ask, receiptScanSchema) ? { output: suiteReceiptReading } : undefined,

    // A blurb names the place it was asked for, so a spec can find it.
    blurbs: (ask) => {
      const name = heldTo(ask, blurbSchema) ? fencedLineOf(ask.input) : undefined
      return name ? { output: { blurb: suiteBlurbOf(name) } } : undefined
    },

    // The trip's shape, from the interview's answers.
    plan_turn: (ask, now) =>
      heldTo(ask, tripShapeSchema) ? startScript(now).shape : undefined,
  },
  turn: {
    // The day fill fills whichever region and days its input asks for.
    plan_turn: (turn, now) => {
      if (!heldTo(turn, dayFillSchema)) return undefined
      const region = /The region:\n<untrusted>\n(.+)\n<\/untrusted>/.exec(turn.input)?.[1]
      const days = /Fill days? ([\d, ]+)\./.exec(turn.input)?.[1]?.split(', ').map(Number)
      return region && days ? startScript(now).daysIn(region, days) : undefined
    },
  },
  // What Kestrel answers every question.
  converse: suiteKestrelAnswer,
}

Some answers are constants, like the receipt. Some read just enough of the input to answer the right thing. A blurb names the place it was asked about, so a spec that asks for two blurbs can tell which landed where. The day fill fills exactly the days it was asked for, because a different number of days would fail the feature's own check.

Reading the input like this couples the script to the prompt's wording. That's deliberate, and it's cheap: if someone rewords "Fill days 3, 4." the day fill stops being answered and the spec that needs it fails at once, with the reason below.

Unscripted calls fail

The model that serves the script is small:

export function createSuiteModel(now = () => new Date()): Model {
  const answered = <C extends { feature: ModelFeature }>(
    call: C,
    script: Partial<Record<ModelFeature, Scripted<C>>>,
  ): ModelAnswer => {
    const answer = script[call.feature]?.(call, now())
    if (!answer) return { failure: "the suite's script has no answer for this call", usage }
    return { ...structuredClone(answer), usage }
  }

  return {
    available: true,
    ask: async (ask) => answered(ask, suiteScript.ask),
    turn: async (turn) => answered(turn, suiteScript.turn),
    async *converse() {
      // A word at a time, as a model streams.
      for (const word of suiteScript.converse.split(/(?= )/)) yield { text: word }
      yield { answered: usage }
    },
  }
}

Two choices in it matter.

It says it's available. With no key, TripEagle's model reports itself unavailable and every AI feature hides behind "AI isn't available". The fake reports itself available, so every feature offers itself in the suite the way it does in production.

Anything the script doesn't cover fails. It doesn't return a placeholder string or an empty object. A failure is what a model outage looks like to the feature, so it lands nothing, and the screen says what it says when the model is down. When a spec starts reaching a feature the script doesn't answer, it fails right there, on a screen showing the feature's failure, instead of passing on an answer nobody meant.

In the real code the suite's model is built on the unit tests' queue fake: each call's scripted answer is queued just before the call is made. That way it goes through the same request refusals and prompt building as the fake the unit tests use, and nothing about the suite's model is a second implementation.

Every answer is a real answer

A scripted answer isn't a shortcut past the feature. It goes through the feature's schema, its read… check and its landing exactly as a model's would, so the suite tests the real path. That only works if every scripted answer actually passes those checks, and a check that's tightened later would quietly break the script.

So the longest part of the script, the interview and first draft of a new trip, lives in its own function (startScript), and a unit test plays it in order through every feature's own reader. If a reader starts refusing a scripted answer, that test fails, rather than a phone flow twenty minutes into a run.

The same function takes now. The interview's trip is a Saturday to a Friday in June of next year, worked out from the current date, so the script's dates are never in the past and never trip a "dates must be in the future" check:

/** The second Saturday of June in the year after `now`'s, to the Friday after. */
function juneWeekAfter(now: Date) {
  const year = now.getUTCFullYear() + 1
  const firstOfJune = new Date(Date.UTC(year, 5, 1))
  const firstSaturday = 1 + ((6 - firstOfJune.getUTCDay() + 7) % 7)
  const start = new Date(Date.UTC(year, 5, firstSaturday + 7))
  const end = new Date(Date.UTC(year, 5, firstSaturday + 13))
  return { start: start.toISOString().slice(0, 10), end: end.toISOString().slice(0, 10) }
}

What a spec looks like

Because the answers are exported constants, a spec can assert on them by name rather than restating them:

import { suiteKestrelAnswer } from '../app/suite-script.server'

test('a traveler asks Kestrel, and the question is kept for them', async ({ signedIn, trip }) => {
  const traveler = await (await signedIn('trip-site', 'traveler', { trip })).newPage()
  await traveler.goto(trip.site)

  const sheet = await openAsk(traveler)
  await sheet.getByRole('textbox', { name: 'Your question' }).fill('What time is the ferry?')
  await sheet.getByRole('button', { name: 'Ask', exact: true }).click()
  await expect(sheet.getByText(suiteKestrelAnswer, { exact: true })).toBeVisible()

  await traveler.reload()
  const again = await openAsk(traveler)
  await expect(again.getByText(suiteKestrelAnswer, { exact: true })).toBeVisible()
})

The spec isn't testing that Kestrel knows when the ferry leaves. It's testing that the question reaches the model, the answer streams back to the right person's sheet, and it's still there after a reload. Those are the things that break when someone changes the app.

A fake Stripe that still runs the real webhook

Buying a pass is the other flow a suite can't run against the real service. Stripe's test mode exists, but the hosted checkout page is Stripe's, it's off the laptop, and every run would need a Stripe key, the network and Stripe's servers to be up.

The easy fake is to skip payment: on the suite server, the Buy button grants the pass. That would test nothing that matters. The part of a payment worth testing end to end is TripEagle's own: the webhook checks Stripe's signature, records the purchase, sets the trip's tier, emails the gift, writes the audit rows. A fake that skips the webhook skips all of it.

So the suite's Stripe fakes Stripe's side and nothing else:

  • Creating a checkout session keeps the session in memory and returns the URL of a checkout page on the suite server itself, /suite/checkout?session=cs_suite_…, in place of Stripe's hosted page.
  • That page shows what's being bought and its price, with Pay and Cancel.
  • Pay builds the checkout.session.completed event Stripe would send, signs it in Stripe's Stripe-Signature scheme, POSTs it over HTTP to the server's own /webhooks/stripe, and sends the buyer on to the session's success URL.
export async function suiteCheckoutAction({ request, services }: Args) {
  const session = sessionOf(request, services) // a 404 when the suite's Stripe made none
  const now = services.now()
  const body = JSON.stringify(paidEvent(session, now))

  const response = await fetch(`${new URL(session.url).origin}/webhooks/stripe`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Stripe-Signature': stripeSignature(body, services.stripeWebhookSecret ?? '', now),
    },
    body,
    signal: AbortSignal.timeout(15_000),
  })
  if (!response.ok) return data({ refused: response.status }, { status: 502 })
  throw redirect(session.successUrl)
}

/** The event Stripe sends once a session is paid: the fields the webhook reads, and no more. */
function paidEvent(session: SuiteCheckout, at: Date) {
  return {
    id: `evt_${session.id}`,
    object: 'event',
    type: 'checkout.session.completed',
    created: Math.floor(at.getTime() / 1000),
    data: {
      object: {
        id: session.id,
        object: 'checkout.session',
        mode: 'payment',
        payment_status: 'paid',
        payment_intent: `pi_${session.id}`,
        amount_total: session.amountUsdCents,
        currency: 'usd',
        metadata: session.metadata,
      },
    },
  }
}

The signature follows Stripe's published scheme: a timestamp, and an HMAC-SHA256 over <timestamp>.<body>, keyed by the whole webhook secret, whsec_ prefix included.

import { createHmac } from 'node:crypto'

export function stripeSignature(body: string, secret: string, at: Date): string {
  const t = String(Math.floor(at.getTime() / 1000))
  const v1 = createHmac('sha256', secret).update(`${t}.${body}`).digest('hex')
  return `t=${t},v1=${v1}`
}

On the other side, the real webhook doesn't know the suite exists. It checks the header the way it checks one from Stripe: the timestamp must be within five minutes, and one of the v1= signatures (there are several while a secret is being rolled) must match, compared in constant time.

import { createHmac, timingSafeEqual } from 'node:crypto'

const tolerance = 5 * 60_000

function signed(secret: string, header: string | null, body: string, now: Date): boolean {
  if (!header) return false
  const parts = header.split(',').map((part) => part.trim().split('='))
  const t = parts.find(([name]) => name === 't')?.[1]
  if (!t || !/^\d+$/.test(t)) return false
  if (Math.abs(now.getTime() - Number(t) * 1000) > tolerance) return false

  const expected = createHmac('sha256', secret).update(`${t}.${body}`).digest()
  return parts.some(([name, mac]) => {
    if (name !== 'v1' || !mac || !/^[0-9a-f]+$/i.test(mac)) return false
    const given = Buffer.from(mac, 'hex')
    return given.length === expected.length && timingSafeEqual(given, expected)
  })
}

The secret is the run's own. Playwright's config makes a fresh one each run and hands it to the suite server, the same way it hands over the test mailbox's token:

process.env.SUITE_STRIPE_WEBHOOK_SECRET ??= `whsec_${randomBytes(32).toString('hex')}`

A few details keep the fake honest.

  • The checkout page exists only on the suite server. It looks the session up in the suite's Stripe, which no deployment has, so on any other server every request to it is a 404.
  • The server still has no STRIPE_SECRET_KEY. With the switch on, a process that has one refuses to start (above), so the fake and the real client can never both be live.
  • The webhook's unit tests keep their own copy of the signing recipe. It would be tidy to import stripeSignature there. But then if the page signed wrongly, the tests would sign wrongly in exactly the same way and still pass. A second copy, written from Stripe's documentation, is an independent check that the page signs the way Stripe does.
  • What stays in unit tests: refunds, disputes and unpaid sessions. The suite checks the happy path and an abandoned checkout, and the webhook's unit tests cover everything Stripe can send.

The spec that buys a pass reads like a person buying one:

test("a planner buys a Trip Pass, and the trip's limits lift", async ({ signedIn, newTrip }) => {
  const trip = await newTrip({ free: true })
  const planner = await (await signedIn('studio', 'organizer', { trip })).newPage()
  const offLaptop = offLocalhost(planner)

  await planner.goto(`${trip.studio}/pass`)
  await planner.getByRole('button', { name: 'Buy Trip Pass' }).click()
  await expect(planner).toHaveURL(/\/suite\/checkout\?session=cs_suite_/)
  await planner.getByRole('button', { name: /^Pay / }).click()

  await expect(planner.getByRole('status')).toContainText('The Trip Pass is on the trip.')
  expect(offLaptop).toEqual([])
})

The last line comes back under Nothing leaves the laptop, below.

The same switch, for files

The suite needed one more fake once a spec uploaded a photo. Photos go straight from the browser or phone to object storage with a signed PUT, and a background job reads them back to make the smaller copies.

The suite server holds an in-memory bucket on a port of its own and points the app's media origin at it. It behaves like the real bucket where it matters: a PUT is stored only if its length and content type match what was signed, and a GET is served only under a signature the real media Worker's own verifier accepts. It answers the browser's CORS preflight, so the web app's direct uploads work the same way the phone's do. The bytes go when the run ends, along with the scratch database schema.

The upload endpoints don't change at all. The signing, the PUT, the background job and the page that draws the picture all work on the same objects, with no cloud account, no storage key and nothing written to disk.

Nothing leaves the laptop

Fakes cover the services you thought of. The suite also needs to catch the ones you didn't: a font from a CDN, a map tile, an analytics beacon, a new SDK that phones home. Each is a test that depends on the network, and a leak of whatever the page sends.

Playwright's usual tool for this is page.route('**/*', ...), aborting anything that isn't localhost. TripEagle uses Chromium's resolver instead:

export const laptopHosts = ['localhost', '*.localhost', '127.0.0.1'] as const

/** Every other host fails to resolve, so a request to it is never sent. */
const onlyLocalhost = `--host-resolver-rules=MAP * ~NOTFOUND, ${laptopHosts
  .map((host) => `EXCLUDE ${host}`)
  .join(', ')}`

export default defineConfig({
  use: { launchOptions: { args: [onlyLocalhost] } },
  // ...
})

MAP * ~NOTFOUND makes every hostname fail to resolve, and each EXCLUDE lets one pattern through. (*.localhost is there because each trip site is served on a subdomain like t-1a2b3c4d.localhost, which Chromium resolves to the loopback address.)

It sits at the resolver rather than in a route for two reasons. A route is set up per page or per context, and the suite has several contexts that are created inside helpers, such as the one that signs in. A launch flag covers every context the browser ever opens. And routes don't see requests a service worker makes, while the resolver does.

The resolver fails quietly, though. A blocked font just falls back, and a blocked map tile leaves the map without streets. The spec still passes, and nobody learns that the page tried to reach something. So specs that care also record what was asked for:

/** Whether `host` is one of `laptopHosts`, the subdomains of localhost included. */
const onLaptop = (host: string) =>
  host === 'localhost' || host.endsWith('.localhost') || host === '127.0.0.1'

/** Every request the page made to a host off the laptop. The resolver already refuses them. */
export function offLocalhost(page: Page): string[] {
  const asked: string[] = []
  page.on('request', (request) => {
    const url = new URL(request.url())
    if (url.protocol !== 'http:' && url.protocol !== 'https:') return
    if (onLaptop(url.hostname)) return
    asked.push(request.url())
  })
  return asked
}

expect(offLaptop).toEqual([]) at the end of the payment spec is the proof that the checkout never tried to reach Stripe. The resolver guarantees nothing was sent, and the list says whether the page tried. (A page's request event doesn't see what a service worker fetches; listening on the browser context as well would.)

The phone app's flows have no browser to put a flag on, so for them the server makes sure there's nothing to reach. It runs with no external keys at all, so every service it doesn't fake reports itself unavailable, and the screens say so as they would during an outage. And its basemap origin points at an unused path on its own port, so the map draws its pins with no streets rather than fetching tiles from the internet.

--host-resolver-rules is a Chromium flag, so this only works in the Chromium project. TripEagle's suite runs on Chromium alone. A suite that also runs Firefox or WebKit would need a route there, or a proxy.

What to take from this

  • Don't run end-to-end tests against a real model. You can't assert on the answer, it fails its own checks now and then, and it costs money, time and a key on every runner. Measure the model separately.
  • Put every fake behind one switch, read in one function. The next fake adds a branch, not a setting and a guard.
  • Make the switch refuse to start anywhere that looks deployed, by things a deployment always has, and check it before the server serves, not when an adapter is first built.
  • Answer by what each call asks, not by the order calls come in. A long-lived server serving many specs and retries can't keep a queue in order. A call's feature and its output schema identify it.
  • Fail every unscripted call. A placeholder answer turns a spec that reached the wrong feature into a pass.
  • Send scripted answers through the real checks, and keep a unit test that plays the script through every reader so a tightened check fails there first.
  • Fake the third party's side and keep yours. The fake checkout signs a real event with the run's secret and posts it to the real webhook, so signature checks, purchases and audit rows are all tested.
  • Block the network at the browser's resolver, and record what tried. The block makes it safe, and the record makes a leak fail the spec.

More articles

Self-hosting a world map: one PMTiles archive on R2 behind a Worker

TripEagle’s maps use no tile provider. The whole planet is one 139 GB PMTiles archive in R2, served by a Worker that caches each range it reads, for about $2 a month. Phones get regional extracts cut on the server, and Greek and Cyrillic names are given Latin ones when the archive is built.

Read more: Self-hosting a world map: one PMTiles archive on R2 behind a Worker

Fast database tests: migrate a template once, copy it per test

Migrating a fresh schema for every database test was most of the suite’s time. Migrating one template per run and copying it with CREATE DATABASE … TEMPLATE cut the setup to a fifth and the suite by more than half.

Read more: Fast database tests: migrate a template once, copy it per test

Tell us about your project

Ready to start building? Let's talk about how we can help bring your idea to life.