Ver en Español
Cancelable Streaming and Zero VRAM Leaks in Chrome Built-in AI: AbortController, clone(), and Safe Rendering
Dec 01, 2026
Updated: Dec 01, 2026

Cancelable Streaming and Zero VRAM Leaks in Chrome Built-in AI: AbortController, clone(), and Safe Rendering

When a cloud LLM keeps generating unwanted output, you waste bandwidth and server tokens. With Chrome Built-in AI, inference runs on your user's own GPU or CPU: an unstoppable stream locks up local compute, and any open session that skips destroy() keeps holding VRAM long after a dialog closes or a route changes.

Once startup is wired properly with availability(), userActivation, and downloadprogress (Part 1 of this series), production reliability depends on three runtime habits: mid-stream cancellation, deterministic teardown, and XSS-safe rendering.

The Real Cost of Skipping destroy() and a Stop Button

A bare for await loop over promptStreaming() looks fine in a two-minute local check without AbortController or session.destroy(). Real usage exposes both gaps fast:

meme-memory-leak.jpg
  • Unstoppable streams: if the model heads in the wrong direction on paragraph one and there is no Cancel button, the user either sits through wasted generation or refreshes the entire tab.
  • Waiting on the garbage collector costs VRAM: JavaScript gives you no control over when GC runs. Every open LanguageModel session holds GPU or RAM resources until session.destroy() runs explicitly. Opening fresh sessions across clicks without destroying prior ones piles up zombie instances until Chrome throws OperationError or degrades the tab.

The Core Pattern: promptStreaming(), AbortController, finally, and pagehide

One clean structure covers both live cancellation and deterministic memory release. Allocate a fresh AbortController per turn, pass its signal to create() and promptStreaming(), treat AbortError as expected user control, and always call session?.destroy() in finally:

const controller = new AbortController();
const { signal } = controller;
cancelBtn.onclick = () => controller.abort();

// BFCache-safe teardown (use pagehide, never unload)
const onPageHide = () => controller.abort();
addEventListener('pagehide', onPageHide, { once: true });

let session;
try {
  session = await LanguageModel.create({ ...coreOpts, signal });
  const stream = session.promptStreaming(userPrompt, { signal });

  for await (const chunk of stream) {
    // Incremental delta chunks: append via textContent, never overwrite
    outputEl.textContent += chunk;
  }
} catch (err) {
  if (err.name === 'AbortError') {
    statusEl.textContent = 'Generation cancelled; partial output preserved.';
  } else {
    handleError(err);
  }
} finally {
  removeEventListener('pagehide', onPageHide);
  session?.destroy(); // Deterministic VRAM/RAM cleanup on success, abort, or error
}

Four invariants from the W3C Prompt API spec and demos/assets/lifecycle.js make this block dependable:

  1. promptStreaming() yields incremental deltas in a ReadableStream<string>: the call returns synchronously and iterates cleanly with for await (const chunk of stream). Each chunk contains only the new delta, so append it (+=) rather than replacing the full string.
  2. Aborting preserves your context quota: passing { signal } to prompt(), promptStreaming(), or append() removes queued items or halts active generation and rolls back the aborted prompt/response pair from session history, protecting your contextWindow. Aborting does not restore older messages already evicted by an earlier contextoverflow.
  3. AbortError is expected control flow, not a crash: keeping the partial text already printed lets the user keep reading or copying what arrived, while the status bar confirms a clean stop instead of flashing a red failure banner.
  4. Use pagehide, never unload, and close the create() race window: unload breaks Chrome's Back/Forward Cache (BFCache); pagehide tears down active streams without hurting back/forward navigation. This repository's sample audit (sample-audit-report.md) also caught a subtle edge case: if pagehide fires while api.create() is still resolving, your guard should link create() to a page-level AbortController and immediately destroy any session that resolves late.

Live Walkthrough: Cutting a Stream Mid-Sentence in Stream Garden

The second interactive demo from the talk (Demo 02 · Stream Garden) exercises this exact pattern against the native LanguageModel.promptStreaming() API in Chrome 148+ with a live AbortSignal.

Clicking Stream with LanguageModel begins incremental delivery while the oscilloscope plots chunk cadence live and arms the crimson Cancel (AbortController) button. Clicking Cancel mid-response produces three immediate outcomes: AbortSignal.aborted flips to true with a red cut line across the waveform, partial output stays readable inside #result under a clean AbortError banner, and the bottom hygiene ledger confirms finally { session.destroy() } released the session (createdTotal === destroyedTotal · 0 leaks).

demo-stream-garden-abort.gif

The static screenshot below shows the exact post-abort telemetry at rest: the two native controls (Streaming con LanguageModel and Cancelar (AbortController)), the frozen amber oscilloscope at ABORT @ chunk #16, preserved partial output, and the emerald hygiene card verifying createdTotal: 1 · destroyedTotal: 1 · 0 leaks.

demo-stream-garden-ui.png

Session Hygiene: baseSession.clone() and Chrome 148+ Context Quotas

Destroying a session after every turn works well for one-off queries, yet real apps often share a single system prompt across unrelated tasks without letting one task's history contaminate the next.

Chrome's session management best practices separate stateful and stateless APIs:

  • Prompt API (LanguageModel, stateful): once the user opens your AI workspace, pre-warm a clean baseSession holding only your initialPrompts. For each independent task, clone it via const task = await baseSession.clone({ signal }), run inference, and destroy task inside finally. Keep baseSession alive only while the AI panel stays open (Chrome unloads the model after an idle period when zero sessions exist).
  • Task APIs (Summarizer, Translator, LanguageDetector, Proofreader): stateless across calls. Reuse one instance across unrelated inputs and call destroy() when the user closes the feature.
// Clean base session with initialPrompts + isolated clone per task
const baseSession = await LanguageModel.create({
  ...coreOpts,
  initialPrompts: [{ role: 'system', content: 'Classify support tickets in one line.' }],
});

async function runIsolatedTask(ticketText, signal) {
  const taskSession = await baseSession.clone({ signal });
  try {
    const needed = await taskSession.measureContextUsage(ticketText);
    if (needed > taskSession.contextWindow - taskSession.contextUsage) {
      return { ok: false, reason: 'Input exceeds remaining contextWindow budget.' };
    }
    return { ok: true, text: await taskSession.prompt(ticketText, { signal }) };
  } finally {
    taskSession.destroy();
  }
}

If you are migrating 2024–2025 sample code, update the quota property names on web LanguageModel: the current names are session.contextUsage, session.contextWindow, session.measureContextUsage(input, { responseConstraint }), and the contextoverflow event. (inputQuota and measureInputUsage() remain on Task APIs such as Summarizer and Translator, but were removed from web LanguageModel.)

When history grows past contextWindow, Chrome fires contextoverflow and evicts the oldest user/assistant pairs while preserving the system prompt. If a single new prompt exceeds the entire window on its own, Chrome rejects with QuotaExceededError, exposing .requested and .contextWindow so you can trim or chunk the input.

Rendering Streamed Tokens Without Opening XSS Holes

Treat every token from a local model as untrusted input, just like user-submitted text. Even though Gemini Nano runs locally, third-party content inside the prompt can steer output into <script> tags, onerror handlers, or malicious links.

Chrome's guide to rendering streamed LLM responses states a strict rule: never run container.innerHTML += chunk. Re-parsing the accumulated HTML string on every chunk costs O(n²) work with visible paint flicker, and an XSS payload split across two chunks slips past naive per-chunk checks.

Pick the rendering path that matches your output:

  • Plain text: element.textContent += chunk. Fast and safe for most utility widgets.
  • Live Markdown: pair an incremental parser such as streaming-markdown writing into an off-screen DocumentFragment with the Sanitizer API (new Sanitizer(...) + replaceChildren(sanitizer.sanitize(buffer))) or DOMPurify over the accumulated buffer, halting rendering immediately if dangerous markup is stripped.

Auditing Leaks and Missing Signals Without Manual File Walks

Checking these invariants by hand across a growing frontend is brittle: one wrapper that drops signal or one modal missing destroy() is enough to leak GPU memory. Running the Built-in AI Lifecycle Auditor Prompt on this repository (sample-audit-report.md) caught that lab.js's prompt() helper dropped options.signal during create() and that three recipe demos had no Cancel button.

meme-why-lifecycle.jpg

Automation handles the mechanical scan and generates a Node-validated ai-lifecycle-guard.js; deciding where to clone sessions, how to budget contextWindow, and how your UI recovers after an abort stays an engineering call.

Part 3 closes the series on the boundary that breaks real integrations the moment your component leaves its standalone tab: running local AI inside a cross-origin <iframe> and configuring Permissions-Policy safely.

Live Lab and References

Sebastian Gomez

Sebastian Gomez

Creador de contenido principalmente acerca de tecnología.

Leave a Reply

0 Comments

Advertisements

Related Posts

Categorías