DEV Community

Cover image for Does Stop Reach the Model? Test Cancellation Through a Real Next.js Route

Does Stop Reach the Model? Test Cancellation Through a Real Next.js Route

A Stop button can freeze the text on screen while the server continues generating. From the user's perspective, the interaction has ended. From the provider's perspective, work may still be running.

That gap crosses several boundaries: the component, the HTTP connection, the Next.js request signal, the AI SDK, and the provider adapter. Testing only a callback or a route-shaped function leaves the runtime boundary untested.

The companion package starts a real local Next.js server and sends HTTP requests through an App Router route. A deterministic provider fixture makes completion, cancellation, and failure observable without a cloud API key.

Make the cancellation chain explicit

The client creates one AbortController for each generation. Stop aborts that controller. Starting another generation aborts the previous controller and increments a generation identifier, so a late result cannot update the new interaction.

The server forwards the request's signal into the model operation:

const result = streamText({
  model,
  prompt: "Generate a synthetic fixture.",
  maxRetries: 0,
  abortSignal: req.signal,
  onAbort: () => finish("aborted"),
  onError: () => finish("failed"),
  onEnd: () => finish(req.signal.aborted ? "aborted" : "completed"),
});
Enter fullscreen mode Exit fullscreen mode

This excerpt targets the tested ai@7.0.177 contract. The registry has moved since that run, so keep the lockfile when reproducing it and re-check callback names before upgrading. Copying examples from another major or patch version can change the behavior under discussion.

AI SDK's stopping guide explains the signal path and runtime dependency. Forwarding req.signal matters only if the server runtime propagates the disconnected client into that signal.

Client abort travels through the HTTP request and route signal to the provider; completed, aborted, and failed remain distinct terminal records.

Use a provider that can expose the boundary

The fixture uses the SDK's testing utilities and MockLanguageModelV4. It emits a first text chunk immediately, then follows one of three modes.

In completion mode it finishes normally. In hold mode it waits, giving the client a deterministic opportunity to disconnect after receiving data. In error mode it emits a provider error through the model stream protocol.

The provider also observes the signal passed by the SDK and records provider-abort-observed. That record is the important addition. A client-side AbortError alone cannot prove the server or provider observed cancellation.

The fixture performs no external inference. Its purpose is to test signal propagation and terminal-state handling through the framework, not to measure a provider's billing or cancellation latency.

Keep one terminal state per operation

The route creates a server-generated run identifier and uses a small guard around terminal recording:

let terminal = false;
const finish = (event: string) => {
  if (!terminal) {
    terminal = true;
    record(id, event);
  }
};
Enter fullscreen mode Exit fullscreen mode

Several lifecycle events can occur near one another. A provider error can be followed by response closure; an abort can race with final stream handling. The guard prevents a later callback from rewriting an operation that already has a terminal result.

The package keeps a bounded in-memory journal solely for the local experiment. A production implementation would use durable, access-controlled telemetry and a defined policy for partial output. The journal endpoint is not a production trace API.

Do not lose errors during stream conversion

The route returns a text stream using createTextStreamResponse() and toTextStream(). A plain text channel contains text; it does not automatically communicate every structured provider event to the client.

The example therefore checks the full stream for error parts before converting text deltas. An error terminates the response stream, allowing the client's read loop to enter its failure path. The server records the provider failure separately.

This detail emerged while testing the fixture. Simply throwing from the synthetic stream producer did not exercise the intended provider-error callback path. Emitting the model protocol's error part and testing the response boundary produced an inspectable failure case.

For a richer chat interface, use a protocol that carries structured lifecycle events and define how partial text is presented after failure. The small text fixture keeps the cancellation experiment readable.

Test over HTTP, after the first chunk

The test launches the pinned Next.js development server, waits for the route to become available, and exercises all three modes. It does not call the route handler directly.

For cancellation, it reads the first response chunk, aborts the client request, and waits for both the server's aborted record and the provider's abort observation. It asserts that the run was not also recorded as completed.

For normal completion, it consumes the response and checks the completed record. For provider failure, it checks the failed record and verifies that completion was not recorded.

That real HTTP test passed locally with Next.js 16.4.6 and AI SDK 7.0.177 on Node 24. It establishes behavior for the tested local runtime and synthetic provider. It does not establish behavior behind a deployed proxy or with an external provider.

Check the deployment boundary separately

Next.js Route Handlers use web request and response APIs, but hosting behavior still matters. The AI SDK guidance calls out cancellation support for the relevant Vercel function configuration; the package includes supportsCancellation: true in its deployment example.

No deployment was performed for this article. Repeat the same first-chunk cancellation test against the intended hosting environment and provider before claiming that Stop halts production generation.

Also decide whether the product needs resumable streams. The SDK documents constraints between abort-based stopping and resumable streaming; they should not be enabled as independent conveniences without considering their interaction.

Make Stop a verified behavior

The client also aborts on unmount and ignores stale generations. Those measures keep the UI coherent. The HTTP test establishes the deeper claim: in the tested setup, the cancellation request reaches the provider boundary.

That is the useful standard for an AI interface. A button label describes an intention; an observed signal chain shows what the application actually stops.

Top comments (6)

Collapse
 
innokentyb profile image
Kent Bodrov •

The next production check I’d want is a timeline with three separate events: the user requested stop, the server observed the disconnect, and the provider actually stopped work. If the last event is unavailable, I’d label the outcome unknown rather than infer it from the UI. Comparing the provider’s usage record with the stop timestamp could also reveal work that continued after the screen stopped updating.

Collapse
 
smtahosin profile image
S M Tahosin •

Raju lol provider-abort-observed xD AbortError here, model still burning tokens there. stealing the chunk 1 test :D

Collapse
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

@smtahosin Please do! Reading chunk one before abort is the key: it tests a live stream, not a request cancelled before generation starts. If you put the route behind a proxy, rerun the same test there—the local pass only covers the local signal chain.

Collapse
 
smtahosin profile image
S M Tahosin •

Raju haha ok proxy rerun it is... local green had me strutting around my desk for a solid 9 mins like i'd solved streaming lol. not trusting it till the proxy run passes too :D

Collapse
 
zubair933 profile image
Md Zubair •

Testing whether AbortSignal actually propagates all the way through your Next.js route down to the model stream catches one of the sneakiest token-waste bugs in AI apps—too many UIs close the client reader while the backend keeps burning inference tokens to completion.

Collapse
 
raju_dandigam profile image
Raju Dandigam Google Developer Experts •

@zubair933 Exactly—the first-chunk test separates a client-side AbortError from the provider-abort-observed event. I would repeat it through the deployed proxy and real provider before claiming token savings; the local fixture proves signal propagation, not billing behavior.