Joel Stevick

Production RAG, line by line · listFile() draws a file's row; events() reads the answer's stream · stage 6 of 6

File list and stream reader

After an upload, listFile adds the file to the page's list from the Worker's reply: the name, the page count, the pages that had no text, and a Remove button. The same function draws every file when the page loads. After a question, the page reads the response body with a stream reader, decodes it to text and splits it into server-sent events at each blank line. A partial event stays in a buffer until the next chunk completes it. An async generator yields each whole event to the submit handler's for await loop, which acts on it at once: a stage event changes the status line, each unit (one checked sentence, lead-in or list item) is appended to the answer, and done ends the ask. The same drawing functions render earlier answers from the session's history.

Runs in: Browser, the visitor's page: demo.html and its module script. New to Cloudflare? How these fit together
demo.html199 / 199 lines on this page explainedlines 130-151,298-418,445-500 of 505; the rest are on other stage pages
In the browser
runs in the visitor's browser, on the demo page
Ingestion
runs when a PDF's text is uploaded
Query time
runs when the Worker answers a question or a search_documents call from the MCP server, and in the request handling every route shares, in the Worker and in the site's functions, which uploads and removals pass through too
MCP request
runs on a request to the MCP server or its OAuth endpoints
Site request
runs on a site request that is not a question, an upload, an MCP call or the cron: a page load, a session read, the demo page's /api/grants calls, an admin read, a file's removal
Scheduled
runs in the Worker's daily cron job
Eval run
runs when the eval harness runs on a developer's machine
MCP host
runs in an MCP host outside the Worker: the search loop example, on a developer's machine (npm run search) or in its test
Module load
runs once, when the module is loaded
Type only
erased by the TypeScript compiler; never runs
Never runs
a comment, a licence or markup with no behaviour of its own

Pinned to joelstevick-demo-rag-pipeline at 6a9c6c7.

demo.html The demo page: listFile (130–151), the functions that draw an answer (298–387), the stream's constants and parser (388–418) and the rest of the Ask submit handler (445–500).

listFile()

function · lines 130–151View on GitHub

Draws one file's row in the file list.

Called by #pdfs change handler Upload handlerCalls Module scope The demo page removeFile() Removing a file

  function listFile(file) {    const li = document.createElement("li");    li.dataset.file = file.name;

A row for the file In the browser

WhatTakes { name, pages, skipped } and creates an <li> whose data-file attribute holds the file name.

WhylistFile is called with the upload's reply and, at page load, with each of the session's files. Both carry name, pages and skipped, the only fields listFile reads. The upload's reply also carries chunks and chars, which listFile ignores. No code in this repository reads data-file; it records in the DOM which file the row is for.

The file list with a new row, "observatory-handbook.pdf: 3 pages", its remove button and the note "Searchable by keywords now; by meaning in about a minute.", and the line "observatory-handbook.pdf added." under the list. The trash icon and the indexing note come from the live page and are newer than the code shown here.
The page after the Worker replies. listFile draws the new row with its page count and its remove button, and the status line says the file was added. At the pinned commit, the Worker writes the chunks' vectors before it sends this reply. 2026-11-29, the live demo at joelstevick.com/demo in Chrome. The live page is newer than the pinned commit, so its file selector, trash icons and indexing note are not in the code shown here.
    const label = document.createElement("span");    label.className = "file";    label.textContent = `${file.name}: ${file.pages} ${file.pages === 1 ? "page" : "pages"}`;

Name and page count In the browser

WhatA span with class file reads "<name>: <n> page" or "pages", where n is the PDF's own page count.

WhyThe text is set with textContent, never innerHTML, so a file name that contains markup is shown as text and cannot inject HTML into the page.

    if (file.skipped.length > 0) {      const skipped = document.createElement("span");      skipped.className = "skipped";      skipped.textContent = ` · skipped, no text: ${file.skipped.length === file.pages ? "every page" : `page${file.skipped.length === 1 ? "" : "s"} ${file.skipped.join(", ")}`}`;      label.append(skipped);    }

The pages with no text In the browser

WhatWhen skipped is not empty, a span with class skipped is appended inside the name span, after a middle dot. It reads "skipped, no text: every page" when every page was skipped, and otherwise "skipped, no text: page N" or "pages N, M".

WhyA scanned or blank page has no text layer, so pdf.js extracts nothing from it and it cannot be searched. The page lists those pages next to the file, after the upload and on every reload, so the visitor knows in advance why a question about them finds nothing.

    const remove = document.createElement("button");    remove.type = "button";    remove.className = "remove";    remove.textContent = "Remove";    remove.setAttribute("aria-label", `Remove ${file.name}`);    remove.addEventListener("click", () => removeFile(file.name, li, remove));

The Remove button In the browser

WhatA button labelled Remove, with an aria-label that names the file, calls removeFile with the name, the row and the button.

WhyThe aria-label tells a screen reader which of several Remove buttons this one is. removeFile asks the Worker to delete the file's vectors, then its chunks, archived pages and file row, and to give its pages and characters back to the demo account's limits. The page removes the row only after a 200 or a 404 (the file was already gone). On any other failure it enables the button again.

    li.append(label, remove);    $("files").append(li);  }

Into the list In the browser

WhatThe label and the button are added to the row, and the row is appended to #files.

WhyAppending keeps the list in upload order, which is also the order the session returns on reload (files ORDER BY rowid).

answerBox()

function · lines 298–318View on GitHub

Creates an answer's box: open at the top for a new answer, collapsed below for an earlier one.

Called by Ask form submit handler: read the stream, render it render()Calls Module scope The demo page

  // A new answer's box, or an earlier one's. A new answer (from Ask) goes on top and is shown open.  // An earlier answer (from the session's history, when the page loads) is drawn collapsed to its  // question, in a <details> the visitor opens with a click, so a reload keeps every answer without  // filling the screen; earlier answers come newest first and are appended in that order, below any new ones.

New and earlier answers Never runs

WhatThe comment explains the two kinds of box. A new answer goes at the top, open. An earlier answer, from the session's history at page load, is a collapsed <details> that shows only its question, and earlier answers are appended newest first below any new ones.

WhyAfter a reload the page still shows the account's earlier answers without filling the screen. session() returns the newest 20 that passed the check (HISTORY in app.ts).

  function answerBox(question, earlier = false) {    const box = document.createElement(earlier ? "details" : "div");    box.className = earlier ? "answer earlier" : "answer";    const q = document.createElement(earlier ? "summary" : "p");    q.className = "q";    q.textContent = question;

The box and its question In the browser

WhatA new answer's box is a <div class="answer">, and an earlier answer's is a <details class="answer earlier">. The question is a <p class="q">, or the <summary> the visitor clicks. Its text is set with textContent.

Why<details> and <summary> give a disclosure widget that works from the keyboard without any script. The page sets every string it draws with textContent, so the question, the model's sentences and the document passages are all treated as text and none of them can inject markup.

    // The answer: prose, or a list. A list is drawn as bullets under its lead-in, so "what jobs have    // I held" reads as one job a line rather than one long sentence. Both are inside the one ".a"    // element, which holds the whole of what the answer says.    const a = document.createElement("div");    a.className = "a";    box.append(q, a);

One element for the whole answer In the browser

WhatAn empty <div class="a"> is added after the question. The prose and the list are drawn inside it.

WhyaddProse and addItem look for their elements inside .a, so sentences and items can arrive in any order and still go into the paragraph and the list.

    if (earlier) $("answers").append(box);    else $("answers").prepend(box);    return box;  }

Place it In the browser

WhatAn earlier answer is appended to #answers and a new one is prepended. The box is returned.

WhyThe history arrives newest first and is appended in that order. A new answer must appear above all of it.

addProse()

function · lines 319–326View on GitHub

Adds a sentence or a list's lead-in to the answer's paragraph.

Called by Ask form submit handler: read the stream, render it render()

  // One sentence (or a list's lead-in) added to the answer's paragraph.  function addProse(box, text) {    const a = box.querySelector(".a");    let lead = a.querySelector(":scope > p");    if (!lead) { lead = document.createElement("p"); a.prepend(lead); }    lead.textContent = lead.textContent ? `${lead.textContent} ${text}` : text;  }

Append to the leading paragraph In the browser

WhatFinds the <p> that is a direct child of .a (:scope > p), creating and prepending one if there is none, and appends the text after a space.

WhyPrepending keeps the lead-in above the bullets even if an item was drawn first. Streamed sentences arrive one at a time and must read as one paragraph, so each is joined to the text already there.

addItem()

function · lines 327–336View on GitHub

Adds one list item to the answer's bullets.

Called by Ask form submit handler: read the stream, render it render()

  // One list item added to the answer's bullets.  function addItem(box, text) {    const a = box.querySelector(".a");    let items = a.querySelector(":scope > ul.items");    if (!items) { items = document.createElement("ul"); items.className = "items"; a.append(items); }    const li = document.createElement("li");    li.textContent = text;    items.append(li);  }

Append a bullet In the browser

WhatFinds or creates <ul class="items"> at the end of .a and appends an <li> with the item's text.

WhyA list answer (up to twelve items, MAX_ITEMS = 12 in demo/src/check.ts) is shown as one item a line instead of a run-on sentence.

addSources()

function · lines 337–379View on GitHub

Draws the sources under an answer: one line per file and page, with a button for each cited passage.

Called by Ask form submit handler: read the stream, render it render()

  // The sources under an answer: one line per file and page, with a button for each passage cited from it.  function addSources(box, sources) {    if (sources.length === 0) return;    const list = document.createElement("ul");    list.className = "sources";

Nothing to draw, or the list In the browser

WhatWith no sources (a fallback), it returns. Otherwise it creates <ul class="sources">.

WhyA fallback carries no sources, so it gets no empty list.

An answer card: the question "How long must the dome be open before the first exposure, and why?", three sentences of answer, and under them the source line "observatory-handbook.pdf · page 2" with a "Show the passage" button.
A cited answer from the sample PDF. Three checked sentences come first. Under them the page draws the sources from the done event, one line per file and page, each with a button that shows the cited passage. 2026-11-29, the live demo at joelstevick.com/demo in Chrome. The live page is newer than the pinned commit, so its file selector, trash icons and indexing note are not in the code shown here.
    const groups = new Map();    for (const source of sources) {      const key = JSON.stringify([source.file, source.page]);      if (!groups.has(key)) groups.set(key, []);      groups.get(key).push(source);    }

Group by file and page In the browser

WhatA Map keyed by JSON.stringify([file, page]) collects the sources for each file and page, in the order they first appear.

WhyTwo passages from the same page become one line with two buttons. A Map keeps insertion order, so the lines follow the order in which the Worker first cited each page. The JSON array is an unambiguous composite key; joining the two values with a separator could collide with a file name that contains the separator.

    for (const sources of groups.values()) {      const { file, page } = sources[0];      const li = document.createElement("li");      const url = opened.get(file);      const name = document.createElement(url ? "a" : "span");      name.className = "source-name";      name.textContent = file;      // No rel="noopener": Chrome opens a blob URL in a new browsing context group as about:blank.      if (url) { name.href = `${url}#page=${page}`; name.target = "_blank"; }

The file's name, a link when possible In the browser

WhatFor each group, if this tab still holds the PDF (opened maps a file name to an object URL made at upload), the name is a link to url#page=N that opens in a new tab. Otherwise the name is plain text.

WhyThe PDF never left the browser, so only the tab that read it can open it. #page= is the PDF open parameter that browsers' built-in PDF viewers support. The source comment explains why rel="noopener" is omitted: with it, Chrome opens a blob URL as about:blank.

      // A passage widened past a page break names the last page it reaches.      const last = Math.max(page, ...sources.map((source) => source.last_page ?? page));      li.append(name, last > page ? ` · pages ${page}–${last}` : ` · page ${page}`);

Page or page range In the browser

WhatThe last page is the largest last_page among the group's sources, or the page itself. After the name, a middle dot and "page N" or "pages N–M" follow.

WhyA passage widened across a page break (ASK 5) carries last_page, and the reader needs to know to look past the first page.

      sources.forEach((source, i) => {        const label = sources.length === 1 ? "the passage" : `passage ${i + 1}`;        const passage = document.createElement("blockquote");        passage.className = "passage";        passage.textContent = source.passage;        passage.hidden = true;        const show = document.createElement("button");        show.type = "button";        show.textContent = `Show ${label}`;        show.addEventListener("click", () => {          passage.hidden = !passage.hidden;          show.textContent = `${passage.hidden ? "Show" : "Hide"} ${label}`;        });        li.append(show, passage);      });

A Show button for each passage In the browser

WhatEach source gets a hidden <blockquote class="passage"> with its stored text, and a button, "Show the passage" (or "Show passage n" when the line has several), that toggles the passage and its own label.

WhyThe passage is the stored text of a chunk the sentence cites. The check has confirmed that every cited id was a chunk the model was given, and that every figure in the sentence appears in its cited passages or in the question. The visitor can compare the sentence with its source in place. The passages start hidden so that the answer stays readable.

      list.append(li);    }    box.append(list);  }

Add the list under the answer In the browser

WhatEach line is appended to the list, and the list is appended to the box after .a.

WhyThe sources come after the whole answer. On a stream they are drawn only when done arrives.

render()

function · lines 380–387View on GitHub

Draws one whole answer at once: an earlier answer, or a fallback.

Called by Ask form submit handler: read the stream, render it start() Demo accounts and sessionsCalls addItem() addProse() addSources() answerBox()

  // Draws one whole answer: an earlier one, or a fallback line.  function render(question, body, earlier = false) {    const box = answerBox(question, earlier);    if (body.answer) addProse(box, body.answer);    for (const item of Array.isArray(body.items) ? body.items : []) addItem(box, item);    addSources(box, body.sources ?? []);  }

A whole answer in one call In the browser

WhatCreates the box, adds answer as prose if it is present, adds each of items as a bullet, then draws the sources.

WhyThe history and a fallback arrive whole, not unit by unit. They use the same drawing functions as the stream, so an earlier answer shows the same sentences, bullets and sources as it did live. It is collapsed, and it has no stop line if it stopped partway, because session() does not return the stopped mark. A fallback's answer is the "couldn't find that" line, drawn as prose with no sources.

STAGES, STOPPED, TROUBLE_STOP

constant · lines 388–391View on GitHub

The status line for each stage, and the two lines shown when an answer stops.

  const STAGES = { retrieving: "Searching your documents…", reranking: "Choosing passages…", writing: "Writing…" };  const STOPPED = "The answer stopped here: its next sentence didn't check out against your documents.";  const TROUBLE_STOP = "The answer stopped here: the demo had trouble finishing it.";

The page's words for the stream In the browser

WhatSTAGES maps the Worker's stage names to the status text. STOPPED is the line under an answer that a later sentence's check ended. TROUBLE_STOP is the line when the model failed partway.

WhyThe Worker sends only machine names: the stages retrieving, reranking and writing, and a stopped event's reason. The reason is uncited, ungrounded or overlong from the check, or trouble when the model failed partway; empty only ever leads to a fallback. The page holds the wording. STOPPED repeats the exported STOPPED in app.ts word for word, because the Worker does not send it.

retrieving → "Searching your documents…"reranking → "Choosing passages…"writing → "Writing…"

The question form with "Searching your documents…" on the status line under it.
The status line during retrieval. The page shows "Searching your documents…" when it sends the question, and again when the retrieving stage event arrives. 2026-11-29, the live demo at joelstevick.com/demo in Chrome. The live page is newer than the pinned commit, so its file selector, trash icons and indexing note are not in the code shown here.
The question form with "Choosing passages…" on the status line under it.
The status line after the reranking stage event arrives. It reads "Choosing passages…" while Claude Haiku ranks the candidate pool. 2026-11-29, the live demo at joelstevick.com/demo in Chrome. The live page is newer than the pinned commit, so its file selector, trash icons and indexing note are not in the code shown here.
The question form with "Writing…" on the status line under it.
The status line after the writing stage event arrives. It reads "Writing…" until the first checked unit of the answer arrives and the page clears it. 2026-11-29, the live demo at joelstevick.com/demo in Chrome. The live page is newer than the pinned commit, so its file selector, trash icons and indexing note are not in the code shown here.

events()

async generator · lines 392–418View on GitHub

Parses the response body into server-sent events as the body arrives.

Called by Ask form submit handler: read the stream, render it

  // The events of the ask's stream, each as { event, data }, as they arrive. The ask is a POST,  // so the browser's EventSource (which can only GET) is no use; the response body is read here  // with a reader instead. The body is text/event-stream: "event: <type>", "data: <json>", and a  // blank line ending each event. It arrives in chunks that can end mid-line, so the text is kept  // in a buffer and only whole events, those followed by a blank line, are taken from it; the rest  // waits for the next chunk. An async generator, so the submit handler below can read the  // events with a plain `for await` loop and act on each the moment it is whole.

Why a reader, not EventSource Never runs

WhatThe doc comment says the ask is a POST and EventSource can only send GET, so the body is read with a stream reader. It describes the framing (event:, data:, a blank line) and why a buffer is needed.

WhyEventSource has no method or body option, so the question would have to go in the URL. Reading the body of a fetch gives the same event stream from a POST with a JSON body.

The same idea, shown in the episode's own code: Reading the response: chunks, lines and server-sent events From Streaming for RAG engineers, Ep 1: Async Generators: Streaming, Step by Step
  async function* events(response) {    // Bytes to text as they come; a character split across two chunks is joined by the decoder.    const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();    let buffer = "";

Bytes to text, then a reader In the browser

Whatresponse.body, a ReadableStream of bytes, is piped through a TextDecoderStream (UTF-8), and a reader is taken on the result. buffer holds the text not yet parsed.

WhyA network chunk can end in the middle of a multi-byte character, such as an em dash or an accented letter. TextDecoderStream holds the partial bytes and joins them with the next chunk. Decoding each chunk separately would produce replacement characters.

    for (;;) {      const { value, done } = await reader.read();      if (value) buffer += value;

Read a chunk In the browser

WhatEach reader.read() resolves with the next decoded chunk, or with done when the Worker has closed the stream. Any text is added to the buffer.

Whyread() resolves as soon as bytes arrive, so the page sees a frame within network latency of the Worker writing it, not at the end of the answer.

      let end;      while ((end = buffer.indexOf("\n\n")) >= 0) {        const block = buffer.slice(0, end);        buffer = buffer.slice(end + 2);        const event = /^event: (.*)$/m.exec(block)?.[1] ?? "message";        const data = /^data: (.*)$/m.exec(block)?.[1];        if (data !== undefined) yield { event, data: JSON.parse(data) };      }

Take whole events from the buffer In the browser

WhatWhile the buffer contains a blank line (\n\n), the text before it is one event block and is removed from the buffer. The event: line gives the event type, "message" if the line is absent, as the SSE format specifies. The data: line is parsed as JSON, and the pair is yielded as {event, data}. A block with no data: line is skipped.

WhyChunks do not align with events, so only text followed by a blank line is a complete event; the rest waits for the next chunk. The parser reads only the first data: line and splits only on \n\n. That matches what the Worker writes (one data: line of JSON with no raw newlines, and \n line endings), but it is not a general SSE parser. A malformed data: line makes JSON.parse throw, and the handler's catch ends the loop.

      // `done` is the server closing the stream: the ask is over.      if (done) return;    }  }

The Worker closed the stream In the browser

WhatWhen read() reports done, the generator returns, after it has taken every whole event from the buffer.

WhyThe Worker closes the stream to say the ask is over. Text left in the buffer without a closing blank line is an incomplete event, and it is dropped.

Ask form submit handler: read the stream, render it

handler · lines 445–500View on GitHub

Reads the ask's events, updates the page on each one, then restores the form.

Calls addItem() addProse() addSources() answerBox() events() render() Module scope The demo page

      // The answer is announced once, when it is whole, not once a sentence.      answers.setAttribute("aria-busy", "true");      let box = null;      let ended = false;

Announce the answer once, when it is complete In the browser

What#answers, an aria-live region, gets aria-busy="true". box (the answer's box, created on the first unit) starts as null, and ended (whether a terminal event has arrived) starts as false.

Whyaria-busy tells screen readers to hold the live region's announcements until the finally block clears it, so the answer is read once, complete, instead of once per sentence.

      // Every event of this ask, kept on the window for the test suite: a streamed body cannot be      // read back from the browser once the page has consumed it.      const got = [];      window.lastAsk = got;

Every event, kept for the tests In the browser

WhatEach event of this ask is pushed onto got, which is exposed as window.lastAsk.

WhyOnce the page has consumed a streamed body, nothing can read it again, so an end-to-end test inspects the events here.

      // Each event is acted on as it arrives, so the page changes while the answer is still      // being written. The events, in the order the Worker sends them (demo/src/app.ts, AskEvent):      //   stage     which step the ask is at: the status line names it;      //   unit      one checked sentence (or lead-in, or list item): appended to the answer;      //   stopped   a later sentence failed its check, or the model failed partway: a line says so;      //   done      the whole answer: its sources are drawn under it;      //   fallback  nothing passed the check: the "couldn't find that" line;      //   error     the model failed before any sentence, or the ask threw: the trouble line.      for await (const { event: type, data } of events(response)) {        got.push({ event: type, data });

One event at a time, as it arrives In the browser

Whatfor await iterates events(response), destructures each event into type and data, and records it. The comment lists the six event types and what each one does on the page. stopped covers a failed check and the model failing partway; error covers the model failing before any sentence and an exception in the ask.

WhyEach iteration runs as soon as the parser yields, so the page changes while the Worker is still writing. The comment's list mirrors AskEvent in app.ts, the Worker's side of this protocol.

The same idea, shown in the episode's own code: The caller writes the for await loop over the stream From Streaming for RAG engineers, Ep 2: Async Generators in TypeScript: Why They're a Must for Streaming
        if (type === "stage") status.textContent = STAGES[data.stage] ?? "";

stage: the status line In the browser

WhatThe status line shows the STAGES text for data.stage, or nothing for an unknown stage.

WhyAll three stage events arrive before the first sentence, while the Worker waits on retrieval, the rerank call and the answer model's first tokens. The status line shows which of them the ask is waiting on.

        else if (type === "unit") {          // The first unit makes the answer's box; the status line and the question box clear then, not before.          if (!box) { box = answerBox(question); status.textContent = ""; form.elements.question.value = ""; }          if (data.kind === "item") addItem(box, data.text);          else addProse(box, data.text);

unit: a checked sentence or item In the browser

WhatThe first unit creates the answer's box and clears the status line and the input. An item unit is then added as a bullet, and a lead or sentence unit is added to the paragraph.

WhyEvery unit passed its check in the Worker before it was sent, so the page can show it at once and never has to remove it. The input is cleared only here and at done or fallback, so a question that ends in an error or a refusal stays in the input to try again. The unit's sources (passage ids) are not drawn; done carries the full sources.

        } else if (type === "stopped") {          // What is on the page stays: each sentence passed its own check. The line says why no more comes.          const line = document.createElement("p");          line.className = "stopped";          line.textContent = data.reason === "trouble" ? TROUBLE_STOP : STOPPED;          box?.append(line);

stopped: say why no more comes In the browser

WhatA <p class="stopped"> is added under the answer: TROUBLE_STOP when the reason is trouble, and STOPPED for any reason from the check.

WhyThe sentences already shown stay, because each one passed its own check. The line tells the visitor that the answer is deliberately incomplete. The Worker sends stopped only after at least one unit, so box exists; ?. guards against a missing box anyway.

        } else if (type === "done" || type === "fallback") {          ended = true;          status.textContent = "";          form.elements.question.value = "";          // `done` after units: the sources go under the box already drawn. `fallback`: nothing          // was shown, so the whole thing is drawn now, as an earlier answer is.          if (type === "done") addSources(box ?? answerBox(question), data.sources);          else render(question, data);          left = data.left;          showLeft();          if (left <= 0) showOffer();

done or fallback: finish the answer In the browser

WhatMarks the ask as ended and clears the status line and the input. On done, the sources are drawn under the box already on the page (the Worker sends done only after at least one unit; box ?? answerBox(question) guards against a missing box anyway). On fallback, render() draws the whole fallback line. Both update left from data.left and show the offer when no questions remain.

WhyA fallback follows no unit, so there is no box until now. left is the Worker's own count after this question, so the page never computes it.

        } else if (type === "error") {          ended = true;          status.textContent = data.error || "Something went wrong. Please try again in a minute.";        }

error: the trouble line In the browser

WhatMarks the ask as ended and shows data.error in the status line. left is not updated, and the input is left as it is.

WhyUsually nothing has been shown: the answer model failed before its first sentence, the Worker gave the question back, and the input still holds the question. The visitor can submit it again, and the count on the page is already correct. The pump also sends error for an exception from anywhere else in the ask (D1 failing during retrieval, or a bug), possibly after some sentences. In that case the question is not given back, and the count shown stays one too high until the page reloads. The page's comment on line 460 names both cases.

      }      // The stream closed without done, fallback or error: the connection was cut mid-answer.      if (!ended) status.textContent = "The answer was cut off. Please try again in a minute.";

Closed without an ending: cut off In the browser

WhatIf the stream ended without done, fallback or error, the status line says the answer was cut off.

WhyThe Worker ends every ask with exactly one of the three, so their absence means the connection dropped during the answer.

    } catch {      status.textContent = "Couldn't reach the server. Please try again in a minute.";

fetch or parsing failed In the browser

WhatThe catch shows "Couldn't reach the server." for any exception: a fetch that a network failure rejected, or an error thrown while reading or parsing the stream.

Whyfetch rejects only when no response arrives. HTTP errors came back as JSON, and the handler already showed their error in the status line (or the offer, on 429). A broken stream also ends here, with the same message.

    } finally {      answers.removeAttribute("aria-busy");      button.disabled = false;    }  });

Always restore the form In the browser

WhatThe finally block removes aria-busy, so screen readers announce the answer, and enables the Ask button again.

Whyfinally runs on every path, including the early returns for a JSON refusal, so the form is never left disabled.