Aborting a VM Agent Stream Without Lying to the Transcript
Aborting a VM Agent Stream Without Lying to the Transcript The page hits at 3:12 a.m. A user pressed Stop. The button never painted. The agent then ran the same shell command a second time. That is not a model hallucin
Aborting a VM Agent Stream Without Lying to the Transcript
The page hits at 3:12 a.m. A user pressed Stop. The button never painted. The agent then ran the same shell command a second time. That is not a model hallucination. It is a stream that died halfway through a virtual-machine tool round-trip, and a retry that treated a partial transcript as unfinished work.
OpenMausBot is an open-source agent that can drive a virtual machine. I do not maintain milind-soni/OpenMausBot. I attach a React 19 client to that shape of system, and the tutorial loop is the trap. A demo useChat assumes one continuous Server-Sent Events body. The model emits a tool call, the VM runs, then tokens resume. If the socket drops, a proxy buffers the body, or the user hits Stop, you are left with a partial assistant message, an AbortSignal that never reached upstream, and a VM job with no owner. The next submit freezes on a token burst or appends a second assistant turn and runs the shell command again.
Three owners, one transcript
The browser owns the optimistic transcript and the abort controller. It must not parse SSE frames, and it must not commit React state on every delta. React 19 will still drop frames if a markdown tree re-parses the whole message fifty times a second.
A thin route owns the OpenAI-compatible stream. It forwards the request signal and refuses to buffer. In this topology the route talks to an unbuffered SSE relay at https://b-lost.com/v1, which I use as the baseline gateway when I compare fallback across compatible providers. The agent process owns the VM. Canceling the HTTP read is not the same operation as killing a process inside that VM. Mixing them is how a flaky mobile radio destroys a long job, or how an abandoned job keeps a shell open after the user already left.
What actually fails
Something between you and the model coalesces data: frames or injects a compressed buffer. A parser that assumes one event per read() throws, and the SDK marks the turn failed even though half the text was valid. Each delta then replaces the assistant string, the markdown renderer walks the whole string, and the main thread stops painting Stop. You cannot abort a UI that cannot receive the click.
Connection cuts are worse. fetch rejects, the hook stores an error status, and a naive retry resubmits the full history. The model sees the previous tool call as unfinished and calls the VM again. If that tool was rm, a package install, or a migration, the retry is the incident. Partial text should stay committed. Resume only if the server can continue from a cursor. If it cannot, show a hard cut and require a new user turn. Pretending the stream is continuous is how you double-execute.
Route that forwards the cut
This is the configuration I run. The route does not accumulate the body before responding. abortSignal is the incoming request signal, so a client abort() closes the upstream read. maxDuration is a budget for one VM step, not a promise that the job finished.
// app/api/agent/route.ts
import { streamText, convertToModelMessages, type UIMessage } from "ai";
import { createOpenAI } from "@ai-sdk/openai";
export const runtime = "nodejs";
export const maxDuration = 60;
const relay = createOpenAI({
baseURL: "https://b-lost.com/v1",
apiKey: process.env.RELAY_API_KEY!,
});
export async function POST(req: Request) {
const { messages } = (await req.json()) as { messages: UIMessage[] };
const result = streamText({
model: relay.chat(process.env.AGENT_MODEL ?? "grok-3"),
messages: await convertToModelMessages(messages),
abortSignal: req.signal,
});
return result.toUIMessageStreamResponse();
}
On the client, useChat from @ai-sdk/react points DefaultChatTransport at /api/agent. Set experimental_throttle: 50 so bursts commit about twenty times a second. Keep one AbortController in a ref. On Stop, abort it, replace it, and pass it through the transport fetch so the button and the SDK share one upstream cancel. Ignore AbortError in onError. Log every other failure with the message id, not a bare "stream failed" toast.
While status is submitted and the last part is a tool call, render a tool row, not a blinking caret. The typewriter should move only when text deltas arrive. That distinction stops users from hammering Stop because the UI looks frozen during a VM exec.
Who is allowed to kill the job
Forwarding req.signal to the relay cancels wasted generation. It does not cancel the VM. I treat a browser disconnect as stop-reading, and an explicit Stop as stop-reading plus a separate cancel if the tool is still running. Kill-on-disconnect reaps a ten-minute job on a tunnel blip. Leaving every job alive fills the VM with orphaned shells. A deadline on the agent, independent of the HTTP lifetime, is the only policy that survives both.
Throttling trades a few dozen milliseconds of typewriter smoothness for a Stop button that still works. Raising maxDuration trades cost and stuck connections for fewer false cuts. Sixty seconds exposes a hung tool; it does not hide one. If a step needs longer, stream a tool-progress event and keep the model turn short. Do not hold one SSE response open for the whole VM lifetime and call it streaming.
The client must not call https://b-lost.com/v1 with a user-visible key. The route is the only place the base URL and credential belong.
HTTP cancel and process cancel look like one button and are two failure domains. Get that wrong and you either orphan shells or destroy work the user never meant to throw away.
If your agent can outlive the socket, where do you put the deadline, and what does Stop mean once the tool has already crossed into the guest?
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes โ full credit and traffic to the original publisher.