okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-guidata (4c4596746) into f-0213-int22a3d7068

main
1.6 KiB36 linesraw
1/**
2 * A quiet NDJSON answer stays open (#4878). A chat turn can say nothing for minutes (the model reads a long prompt, a tool
3 * runs, an approval waits), and the desktop's web view gives up on a request that has been silent for 60 seconds ("Load failed")
4 * while the turn goes on in the background. A beat frame, the same `{"type":"beat"}` the Time-skip stream uses and the chat
5 * consumer ignores, goes out every 15 seconds. It changes nothing else: a client that goes away still cancels (or detaches
6 * from) its turn through the response's own close, exactly as before, and the timer ends on finish, on close and on stop().
7 */
8export const BEAT_MS = 15_000;
9const BEAT_LINE = `${JSON.stringify({ type: 'beat' })}\n`;
10
11/** The interval (a tester may shorten it: STRATA_STREAM_BEAT_MS); anything that is not a sensible number is the default. */
12export function beatInterval(env = process.env) {
13  const n = Number(env.STRATA_STREAM_BEAT_MS);
14  return Number.isFinite(n) && n >= 20 && n <= 60_000 ? n : BEAT_MS;
15}
16
17/** Start beating on `res`. Returns stop(), which is safe to call more than once. */
18export function keepStreamAlive(res, { ms = beatInterval() } = {}) {
19  let timer = setInterval(() => {
20    if (res.writableEnded || res.destroyed) { stop(); return; }
21    try { res.write(BEAT_LINE); } catch { stop(); }
22  }, ms);
23  timer.unref?.();
24  function stop() {
25    if (timer === null) return;
26    clearInterval(timer);
27    timer = null;
28    res.off?.('finish', stop);
29    res.off?.('close', stop);
30    res.off?.('error', stop);
31  }
32  res.once('finish', stop);
33  res.once('close', stop);
34  res.once('error', stop);
35  return stop;
36}