Halmurat T.
Halmurat T.

Senior SDET

Home Blog Books ask About

The Dispatch

Weekly QA notes from the trenches.

Welcome aboard!

You're on the list. Expect real-world QA insights — no fluff, no spam.

© 2026 Halmurat T.

Automation 29
  • Selenium
  • Playwright
  • Appium
  • Cypress
AI Testing 68
CI/CD 13
  • GitHub Actions
  • Slack Reporting
QA Strategy 11
Case Studies 9
Blog/AI Testing
AI TestingHalmurat T./October 20, 2026/14 min

Your Stop Button Lies: Tokens You Still Pay For

Filed underai-testing/playwright/llm/cicd/ai-agents
Your Stop Button Lies: Tokens You Still Pay For

Table of Contents
  • Why does a working Stop button still cost you money?
  • What are the three layers a real cancel has to cross?
  • Why does the naive Playwright test pass when cancellation is broken?
  • How do you prove the browser actually aborted the request?
  • How do you prove the upstream call actually stopped?
  • The bug DOM tests structurally cannot see: the phantom tool call
  • How do you make the cancel land mid-stream every time?
  • Don’t test against a real provider in the blocking lane
  • Watch out for EventSource and auto-reconnect
  • What I’d do differently

On this page

  • Why does a working Stop button still cost you money?
  • What are the three layers a real cancel has to cross?
  • Why does the naive Playwright test pass when cancellation is broken?
  • How do you prove the browser actually aborted the request?
  • How do you prove the upstream call actually stopped?
  • The bug DOM tests structurally cannot see: the phantom tool call
  • How do you make the cancel land mid-stream every time?
  • Don’t test against a real provider in the blocking lane
  • Watch out for EventSource and auto-reconnect
  • What I’d do differently

Your AI chat feature has a Stop button. A user gets three sentences into a rambling 600-token answer, decides they’ve seen enough, clicks Stop, and the text freezes. The UI looks perfect. Your Playwright test clicks Stop, asserts the streaming indicator disappeared, and goes green. Everyone’s happy — except the model kept generating all 600 tokens on the server, and you paid for every one of them.

This is the cancellation gap, and it’s the most expensive untested path in most AI products. The Stop button is a UI affordance that hides a distributed-systems problem: clearing the browser’s view of a stream is trivial, but actually cancelling the work means propagating an abort across three layers — the browser, your server, and the provider. Break the propagation anywhere and the visible behavior is identical to success. Your DOM assertion can’t tell the difference, which is exactly why this bug ships.

Why does a working Stop button still cost you money?

Because stopping the display of a stream and stopping the generation of a stream are two different operations, and only the first one is visible to a Playwright test. When the browser closes a fetch reader, the tokens stop arriving in the UI — but whether the server hears about that and tells the provider to stop depends on code you probably never wrote.

The provider’s billing model makes this concrete. You’re charged for output tokens the model generates, not the ones your client reads. If you disconnect without a real cancel, the provider keeps generating and bills you for the full completion — you just threw the tokens away. A proper cancel that reaches the provider immediately stops model processing and billing, and not every provider even supports that. Output tokens are where the money is — Anthropic bills Claude output at 5x the input rate — so a broken cancel wastes exactly the most expensive tokens you buy.

§ Why the wasted tokens are the expensive ones

5x

Output vs input

Claude output tokens cost 5x input

$85K/mo

Avg AI spend, 2025

Projected, up from ~$63K in 2024 (CloudZero)

5-30x

Agentic token use

More tokens per task than a chatbot (Gartner)

Multiply the per-call waste by every user who abandons a long generation, then multiply again by agentic features that burn 5–30x more tokens per task than a chatbot, and the “harmless” Stop button becomes a line item. Inference is already the dominant operating cost of most AI applications; a cancel path that silently no-ops is a cost regression that no dashboard attributes to you.

What are the three layers a real cancel has to cross?

A click on Stop has to travel from the browser all the way to the provider, and every hop is a place the signal can die. Here’s the chain that a working implementation completes:

Browser: abort the fetch

The Stop handler calls AbortController.abort(), which tears down the fetch reader and closes the underlying HTTP connection. This is the only layer most teams implement — and the only one a DOM test observes.

Server: detect the dropped connection

Node signals a closed client connection by emitting close on the response object. Your handler has to be listening for it — res.on('close', ...) — and distinguish a real disconnect from a normal completion by checking res.writableEnded.

Server: propagate the abort upstream

On close, the handler calls .abort() on the AbortController it passed into the provider SDK call. Skip this and the provider never learns the user left; it finishes generating into a socket nobody is reading.

The failure mode I’ve seen most often is layer two working and layer three missing. The connection drops, the server knows it dropped, and nobody wired that knowledge to the upstream request. Detecting the disconnect and propagating one abort signal from the socket down through the fetch pipeline is the whole job — and it’s invisible from the browser, so it never gets a test until the finance team asks why the bill doubled.

Why does the naive Playwright test pass when cancellation is broken?

Because it asserts on the one layer that always works. Clicking Stop reliably freezes the DOM whether or not the upstream call dies, so a test that checks the DOM is testing the strongest link in the chain and ignoring the two weakest:

tests/ai/stop-button.spec.ts
test('stop button halts the response', async ({ page }) => {
await page.goto('/chat');
await page.getByRole('textbox').fill('Write me a 500-word essay on caching');
await page.getByRole('button', { name: 'Send' }).click();
await expect(page.getByTestId('streaming-indicator')).toBeVisible();
await page.getByRole('button', { name: 'Stop' }).click();
// Passes even if the model generates all 500 words on the server.
await expect(page.getByTestId('streaming-indicator')).toBeHidden();
});

This test is not wrong, it’s incomplete. It’s the AI-cancellation cousin of the streaming race where Playwright’s auto-wait hands you a half-rendered answer: both bugs come from trusting the DOM as an oracle for a process that lives on the server. The indicator hiding tells you the frontend reacted. It tells you nothing about whether the generation stopped.

How do you prove the browser actually aborted the request?

Assert that the request failed with an abort, not that it completed. When AbortController.abort() fires, the browser cancels the in-flight request and Playwright surfaces it as a failed request with net::ERR_ABORTED — a signal you can wait for directly:

tests/ai/stop-aborts-fetch.spec.ts
test('stop aborts the in-flight completion request', async ({ page }) => {
await page.goto('/chat');
await page.getByRole('textbox').fill('Write me a 500-word essay on caching');
await page.getByRole('button', { name: 'Send' }).click();
const aborted = page.waitForEvent('requestfailed', (req) =>
req.url().includes('/api/chat') && req.failure()?.errorText.includes('aborted'),
);
await page.getByRole('button', { name: 'Stop' }).click();
await aborted; // throws if the request completed normally instead of aborting
});

This is a real improvement — it fails loudly if the Stop handler forgot to call abort() and instead just hid the indicator with CSS. But it still only proves layer one. A browser can abort a fetch while the server, oblivious, keeps streaming into the void. To catch that, you have to observe the server.

How do you prove the upstream call actually stopped?

Put a controllable test double where the provider would be and let it record whether it saw the disconnect. This is the assertion that protects your bill, and it’s the one no browser-only test can make. Reuse the same gated mock LLM server you run in CI, but have it register a close listener and remember whether the client bailed mid-stream:

tests/fixtures/streaming-llm.ts
// A fake SSE endpoint that streams slowly and records client disconnects.
export function streamingLLM() {
const state = { disconnectedMidStream: false, tokensSent: 0 };
const handler = (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.on('close', () => {
// writableEnded is false only if we hadn't finished — i.e. a real cancel.
if (!res.writableEnded) state.disconnectedMidStream = true;
});
const timer = setInterval(() => {
res.write(`data: token-${state.tokensSent++}\n\n`);
}, 100);
res.on('close', () => clearInterval(timer));
};
return { handler, state };
}

Now the test asserts on the server’s view of the world, not the browser’s:

tests/ai/stop-cancels-upstream.spec.ts
test('stop propagates to the upstream stream', async ({ page, llm }) => {
await page.goto('/chat');
await page.getByRole('button', { name: 'Send' }).click();
await expect(page.getByTestId('streaming-indicator')).toBeVisible();
await page.getByRole('button', { name: 'Stop' }).click();
await expect.poll(() => llm.state.disconnectedMidStream).toBe(true);
expect(llm.state.tokensSent).toBeLessThan(20); // it stopped, it didn't drain
});

If you run real models in a nightly eval lane instead of a mock, get the same evidence from the trace: assert the gen_ai span ended as cancelled and its output-token count is bounded, exactly the span-level assertion pattern from wiring OTel GenAI traces into Playwright. Either way, the object under assertion is server-side token production — the thing you actually pay for.

The bug DOM tests structurally cannot see: the phantom tool call

Cancellation gets genuinely dangerous the moment your AI can act. An agent decides mid-stream to call issueRefund, the tool call is already dispatched, and the user hits Stop. The UI resets to a clean state. The refund fires anyway. Now you have a side effect the user explicitly tried to prevent, and no visible trace of it.

This is the cancellation twin of the retry that duplicates a side effect: both are about a mutation escaping the control flow you thought bounded it. Test it by asserting the side-effect endpoint is not hit after a cancel:

tests/ai/stop-blocks-side-effect.spec.ts
test('stopping before a tool call prevents the side effect', async ({ page }) => {
let refundCalled = false;
await page.route('**/api/refund', (route) => { refundCalled = true; route.abort(); });
await page.goto('/chat');
await page.getByRole('textbox').fill('Refund my last order');
await page.getByRole('button', { name: 'Send' }).click();
await page.getByRole('button', { name: 'Stop' }).click();
await page.waitForTimeout(1500); // give a leaked tool call time to fire
expect(refundCalled).toBe(false);
});
[ WARNING ]

A fixed waitForTimeout is a smell in most tests, but here it’s load-bearing: a phantom tool call fires after the cancel, so you have to wait out the window in which it could leak. Assert on a negative — “this never happened” — and give it long enough to be meaningful. This is the rare case where waiting is the assertion.

How do you make the cancel land mid-stream every time?

Control the stream so Stop always arrives during generation, never before it starts or after it ends. A flaky cancellation test is worse than none — it trains the team to rerun until green. The fix is the gated mock above: it emits a token every 100ms and never finishes on its own, so there’s always a live stream to cancel. Click Stop only after the indicator is visible and at least one token has landed, and the timing is deterministic across every runner.

Don’t test against a real provider in the blocking lane

Real streams finish at unpredictable times, so a cancel racing a completion will flake one run in ten. Keep the deterministic cancel assertions on the mock in your merge gate, and let real-provider cancellation live in the nightly lane where a rerun is cheap — the same two-lane split that keeps flaky model calls out of your critical path.

Watch out for EventSource and auto-reconnect

If your app streams over the browser’s native EventSource, you inherit two traps. It can’t send custom headers and, worse, it automatically reconnects when the connection drops — so your “cancel” can silently resurrect the stream a second later. Assert that no new request to the endpoint is made in the two seconds after Stop, or move to fetch with a ReadableStream where you own the lifecycle outright.

What I’d do differently

I’d have written the upstream-cancellation test before the feature shipped, not after a billing spike forced an investigation. On one team we found the Stop button had been “working” for months — perfect UI, happy users — while every cancelled generation ran to completion on the server. The DOM test had been green the entire time. The mock that records disconnectedMidStream is fifteen lines; it would have caught the bug on the first pull request instead of on an invoice.

I’d also treat cancellation as a first-class state in the design, not an afterthought bolted onto streaming. “Stopped by user” deserves the same test coverage as “completed” and “errored,” because it’s the state most likely to leak money and side effects — and the only one your users reach by deliberately intervening.

Your one concrete next step: take your existing Stop-button test and add a single assertion that the completion request aborted (waitForEvent('requestfailed')). That five-line change tells you today whether your Stop button stops anything at all. If it stays green, you’ve confirmed layer one. If it goes red, you just found a bug that’s been quietly billing you the whole time.

Want more field-tested AI testing tactics like this? I send one deep-dive a week on testing AI features without the flake and without the surprise bills — no fluff, just what’s held up across enterprise codebases.

§ Frequently Asked FAQ
+ Does clicking Stop in the browser cancel the LLM call automatically?

No. Aborting the browser fetch stops your client from reading tokens, but the server keeps streaming — and the provider keeps generating and billing — unless your backend detects the disconnect and propagates an abort upstream. You pay for tokens the model generates, not the ones your UI displays.

+ How do I assert the upstream generation actually stopped in Playwright?

You can’t see it from the DOM. Route the request through a controllable test double that listens for the connection close event and records whether the client disconnected mid-stream, then assert on that server-side state. For real-provider runs, assert on the GenAI trace span’s cancelled status and bounded token count instead.

+ Why does my Stop-button test pass even though cancellation is broken?

Because it only checks the DOM. Clicking Stop reliably hides the streaming indicator whether or not the upstream call dies, so a DOM-only assertion tests the strongest link in the chain and ignores the server-side propagation that actually stops billing. It’s the same trap as the streaming auto-wait race.

+ What is a phantom tool call and how do I test for it?

It’s a tool call an agent dispatches mid-stream that fires even after the user hits Stop, causing a side effect the user tried to prevent. Test it by intercepting the side-effect endpoint with page.route, cancelling, then asserting the endpoint was never called within a window long enough for a leaked call to fire — the cancellation twin of a retry that duplicates a side effect.

+ Should cancellation tests run against a real model or a mock?

Use a gated mock in CI for your blocking merge gate so the cancel lands mid-stream deterministically and never flakes. Run real-provider cancellation in a nightly lane where an occasional rerun is cheap. Real streams finish at unpredictable times, so a cancel racing a completion will flake in a merge gate.

§ Further Reading 03 of 03
01AI Testing

Your AI Agent Is Looping, and No Test Caught It

A max-iterations cap hides livelock instead of catching it. Here's the Playwright test a senior SDET writes to detect cyclic tool calls before they hit prod.

Read →
02AI Testing

Your AI Agent Retries and Charges the Card Twice

A tool call commits but the response is lost, so your AI agent retries and double-charges. Here's the Playwright test a senior SDET writes for exactly-once.

Read →
03AI Testing

Your AI Feature Has Three Clocks. They Disagree.

Your browser clock, your server clock, and the model's idea of now rarely agree. Pin all three in Playwright before a date bug quietly reaches production.

Read →

Don't miss a thing

Subscribe to get updates straight to your inbox.

HT

No spam · Unsubscribe anytime

Welcome aboard!

You're on the list. Expect real-world QA insights — no fluff, no spam.

§ Colophon

Halmurat T. — Senior SDET writing about test automation, CI/CD, and QA strategy from 10+ years in the enterprise trenches.

Set in
IBM Plex Sans, Lora, and IBM Plex Mono.
Built with
Astro, MDX, Tailwind CSS & Expressive Code. Served by Vercel.
Privacy
No cookies. No tracking scripts on the main thread — analytics run sandboxed via Partytown.
Source
github.com/Halmurat-Uyghur
Terminal
Try /ask to query Halmurat's notes in a shell prompt.

© 2026 Halmurat T. · Written in plain text, shipped in plain time.

Search
Esc

Search is not available in dev mode.

Run npm run build then npm run preview:local to test search locally.