Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(server,web): a live stream that dies silently is reopened from its last event, and a stuck write cuts the connection

lmliheng1d49df9b4945
diff --git a/changelog/unreleased/2026-10-13-sse-stall.md b/changelog/unreleased/2026-10-13-sse-stall.md
new file mode 100644
index 00000000..ea306903
--- /dev/null
+++ b/changelog/unreleased/2026-10-13-sse-stall.md
@@ -0,0 +1,43 @@
+# The Web App catches up on its own when a live stream dies silently
+
+- **Date:** 2026-10-13
+- **Type:** fix
+- **Scope:** `server`, `web`, `docs`
+
+[中文版](2026-10-13-sse-stall.zh.md)
+
+Ported from upstream PenguinHarness (#1026, commit `99dacb54`).
+
+A Session stream or the user event stream whose connection died without an error (a half-open
+connection, a stuck proxy or NAT, a laptop that slept or changed networks) left the page frozen
+until it was reloaded, while the Agent kept running on the server. The page now notices the
+silence and resumes the stream from the last event it received, and the server cuts off a stream
+whose peer stopped reading.
+
+## Details
+
+- The server's heartbeat is now a named `ping` event (`data: {}`, no `id:` line), sent right
+ after a stream's initial events and every 20 seconds after, instead of a comment line the page
+ could not see. It moves neither the client's `Last-Event-ID` nor the replay position.
+- Once a stream has sent a ping, the Web App treats 50 seconds without any event as a dead
+ connection: it closes the stream and opens a new one from the last event id it saw, which the
+ server replays from, or answers with `resync_required` when that id has left its buffer.
+ Showing the tab checks at once.
+- A stream from a server that never pings, such as a machine still on an older version, and a
+ stream the browser gave up on are left as they were before.
+- `GET /api/sessions/:id/stream` and `GET /api/events` accept the last event id as the
+ `lastEventId` query parameter when no `Last-Event-ID` header is sent, since a page cannot set
+ headers on an EventSource it opens itself. The header wins when both are present.
+- An event stream whose socket sends nothing for 40 seconds (up to 80 while a write is pending)
+ has its connection closed, so a client that is still there reconnects and resumes.
+- The server API reference (`/docs/server-api`, § Streaming (SSE)) documents the ping event, the
+ `lastEventId` parameter, the idle timeout and the client's liveness check.
+
+## Compatibility
+
+- **Old server, new page.** The watchdog arms on a stream's first `ping` only. A server that never
+ pings — a machine on an older version behind the proxy — gets a plain EventSource exactly as
+ before.
+- **New server, old page.** The old page has no listener for the named `ping`, and the id-less
+ frame leaves its `Last-Event-ID` alone.
+- Nothing on disk changes, so there is no backward-compatibility step.
diff --git a/changelog/unreleased/2026-10-13-sse-stall.zh.md b/changelog/unreleased/2026-10-13-sse-stall.zh.md
new file mode 100644
index 00000000..9d95e410
--- /dev/null
+++ b/changelog/unreleased/2026-10-13-sse-stall.zh.md
@@ -0,0 +1,26 @@
+# 实时流无声断开时,Web App 自行追上进度
+
+- **Date:** 2026-10-13
+- **Type:** fix
+- **Scope:** `server`, `web`, `docs`
+
+[English](2026-10-13-sse-stall.md)
+
+移植自上游 PenguinHarness(#1026,提交 `99dacb54`)。
+
+Session 流或用户事件流的连接如果在没有任何错误的情况下断掉(半开的连接、卡住的代理或 NAT、休眠或切换了网络的笔记本),页面会一直停在原处,直到刷新,而 Agent 仍在服务器上继续运行。现在页面会察觉这段静默,从收到的最后一个事件处续接流;服务器也会切断对端已不再读取的流。
+
+## 细节
+
+- 服务器的心跳改为名为 `ping` 的事件(`data: {}`,没有 `id:` 行),在流的初始事件之后立即发送,之后每 20 秒一次,取代页面看不到的注释行。它既不改变客户端的 `Last-Event-ID`,也不改变重放位置。
+- 流发送过 ping 之后,Web App 把 50 秒内没有任何事件判定为连接已死:关闭这条流,从见到的最后一个事件 id 新开一条。服务器据此重放;该 id 已移出缓冲区时则回以 `resync_required`。标签页重新显示时立即检查一次。
+- 来自从不发送 ping 的服务器的流(例如仍在旧版本上的机器)以及浏览器已放弃的流,行为与以前相同。
+- 没有 `Last-Event-ID` 请求头时,`GET /api/sessions/:id/stream` 与 `GET /api/events` 接受以查询参数 `lastEventId` 传递的最后事件 id,因为页面自己新建的 EventSource 无法设置请求头。两者同时出现时以请求头为准。
+- socket 连续 40 秒没有发出任何数据(有写入挂起时最长 80 秒)的事件流会被关闭连接,仍然在线的客户端随之重连并续传。
+- 服务器 API 参考文档(`/docs/server-api`,「流式传输(SSE)」一节)补充了 ping 事件、`lastEventId` 参数、空闲超时和客户端的存活检查。
+
+## 兼容性
+
+- **旧服务器、新页面**:看门狗只在流发出的第一个 `ping` 上武装;从不发送 ping 的服务器(例如代理后面仍在旧版本上的机器)拿到的就是与以前完全一样的普通 EventSource。
+- **新服务器、旧页面**:旧页面没有 `ping` 事件的监听器,而这个不带 id 的帧也不会改动它的 `Last-Event-ID`。
+- 磁盘上没有任何变化,因此不需要兼容处理。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index dfad405b..d56da9c7 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -1113,7 +1113,7 @@ Real-time delivery uses Server-Sent Events, not WebSocket, on two kinds of chann
### Wire Format
-Default (unnamed) SSE events carry raw OmniMessage envelopes as single-line JSON: the same protocol the SDK yields and the Trace stores (see [OmniMessage Protocol](/omni-message)). Events named `server_event` carry the `ServerEvent` union:
+Default (unnamed) SSE events carry raw OmniMessage envelopes as single-line JSON: the same protocol the SDK yields and the Trace stores (see [OmniMessage Protocol](/omni-message)). Events named `ping` are the heartbeat (see [Delivery Guarantees](#delivery-guarantees)). Events named `server_event` carry the `ServerEvent` union:
```ts
export type ServerEvent =
@@ -1187,9 +1187,10 @@ export type ServerEvent =
- Event ids increase monotonically per channel and have the form `<epoch>-<seq>`.
- Each channel keeps a bounded replay buffer: the most recent 10,000 events or 8MB.
-- On reconnect with `Last-Event-ID`, the server replays the gap if the id is still in the buffer. Otherwise it first sends `resync_required`, and the client refetches `/messages` before continuing.
-- A heartbeat comment line is written every 20 seconds. The same beat re-checks the session behind the connection and ends the stream when that session is gone or has expired, so a client whose sign-in was revoked stops streaming instead of waiting for its next request to fail. Revoking sessions directly — an admin resetting a password or deleting an account — ends that user's open streams at once; the heartbeat is the catch-all. A stream authenticated by the local API token has no session row and is left alone.
-- Event order: on a reconnect that carries `Last-Event-ID`, the replayed gap (or `resync_required`) arrives first, then the initial events (the authoritative `task_state` snapshot and any still-pending `approval_request`s), then the live stream. A fresh connection without `Last-Event-ID` skips the replay, so its first event is the `task_state` snapshot.
+- On reconnect with `Last-Event-ID`, the server replays the gap if the id is still in the buffer. Otherwise it first sends `resync_required`, and the client refetches `/messages` before continuing. A client that opens a new connection itself can pass the id as the `lastEventId` query parameter instead, since an `EventSource` cannot set headers. When both are present, the header wins.
+- A `ping` event (`data: {}`, no `id:` line) is sent right after the initial events and then every 20 seconds. A browser hands it to the page, unlike a comment line, so a client that has received one can treat a long silence as a dead connection. Without an id it moves neither the client's `Last-Event-ID` nor the replay position. The same beat re-checks the session behind the connection and ends the stream when that session is gone or has expired, so a client whose sign-in was revoked stops streaming instead of waiting for its next request to fail. Revoking sessions directly — an admin resetting a password or deleting an account — ends that user's open streams at once; the heartbeat is the catch-all. A stream authenticated by the local API token has no session row and is left alone.
+- A stream whose socket sends nothing for 40 seconds (up to 80 while a write is pending) is closed. With a `ping` every 20 seconds, only a peer that stopped reading, as behind a half-open connection or a stuck proxy, lets a stream go that quiet. A client that is still there finds the stream ended, reconnects and resumes from its last event id.
+- Event order: on a reconnect that carries `Last-Event-ID` (or `lastEventId`), the replayed gap (or `resync_required`) arrives first, then the initial events (the authoritative `task_state` snapshot and any still-pending `approval_request`s), then a `ping`, then the live stream. A fresh connection without either skips the replay, so its first event is the `task_state` snapshot.
### Recommended Client Pattern
@@ -1200,6 +1201,7 @@ The bundled Web App connects in this order:
3. If the response carries `live` (a Task is running), drop the buffered partial events the cursor already covers and apply `live.fragments` on top of the history. The in-progress message reappears with its streamed prefix intact.
4. Replay the buffer, removing the overlap.
5. Continue with the live stream.
+6. Once the stream has sent a `ping`, treat 50 seconds without any event as a dead connection: close it and reconnect with `?lastEventId=` set to the last id received. Check at once when the page becomes visible, since background timers run late. A stream that never sends `ping` comes from a server older than the heartbeat event; leave it to the browser's own reconnection.
## Type Imports
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index e5d50a44..fb3c2c72 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -1113,7 +1113,7 @@ Telegram 连接时会先清空积压,跳过无连接期间发送的消息。
### 传输格式
-默认(未命名)的 SSE 事件以单行 JSON 携带原始 OmniMessage 信封:SDK 产出、Trace 存储的就是这个协议(见 [OmniMessage 协议](/omni-message))。名为 `server_event` 的事件携带 `ServerEvent` 联合类型:
+默认(未命名)的 SSE 事件以单行 JSON 携带原始 OmniMessage 信封:SDK 产出、Trace 存储的就是这个协议(见 [OmniMessage 协议](/omni-message))。名为 `ping` 的事件是心跳(见[投递保证](#投递保证))。名为 `server_event` 的事件携带 `ServerEvent` 联合类型:
```ts
export type ServerEvent =
@@ -1187,9 +1187,10 @@ export type ServerEvent =
- 事件 id 在每个通道内单调递增,格式为 `<epoch>-<seq>`。
- 每个通道保留一个有界的重放缓冲区:最近 10,000 个事件或 8MB。
-- 携带 `Last-Event-ID` 重连时,如果 id 仍在缓冲区内,服务器会重放缺失的事件;否则先发送 `resync_required`,客户端重新拉取 `/messages` 后再继续。
-- 每 20 秒写入一行心跳注释。同一次心跳会复查连接背后的会话,会话已删除或已过期时结束该流,因此登录被吊销的客户端会立即停止接收,而不必等到下一次请求失败才发现。直接吊销会话的操作——管理员重置密码或删除账号——会当场结束该用户所有打开中的流,心跳是兜底。以本地 API token 鉴权的流没有对应的会话记录,不受影响。
-- 事件顺序:携带 `Last-Event-ID` 重连时,先到达重放的缺失部分(或 `resync_required`),然后是初始事件(权威的 `task_state` 快照和所有仍待处理的 `approval_request`),最后是实时流。不带 `Last-Event-ID` 的新连接跳过重放,第一个事件就是 `task_state` 快照。
+- 携带 `Last-Event-ID` 重连时,如果 id 仍在缓冲区内,服务器会重放缺失的事件;否则先发送 `resync_required`,客户端重新拉取 `/messages` 后再继续。客户端自己新建连接时,也可以改用查询参数 `lastEventId` 传递这个 id,因为 `EventSource` 无法设置请求头。两者同时出现时以请求头为准。
+- 初始事件之后立即发送一个 `ping` 事件(`data: {}`,没有 `id:` 行),之后每 20 秒一次。与注释行不同,浏览器会把它交给页面,所以收到过它的客户端可以把长时间的静默判定为连接已死。它不带 id,既不改变客户端的 `Last-Event-ID`,也不改变重放位置。同一次心跳会复查连接背后的会话,会话已删除或已过期时结束该流,因此登录被吊销的客户端会立即停止接收,而不必等到下一次请求失败才发现。直接吊销会话的操作——管理员重置密码或删除账号——会当场结束该用户所有打开中的流,心跳是兜底。以本地 API token 鉴权的流没有对应的会话记录,不受影响。
+- socket 连续 40 秒没有发出任何数据的流会被关闭(有写入挂起时最长 80 秒)。`ping` 每 20 秒一次,只有对端已不再读取时(半开的连接、卡住的代理),流才会安静这么久。仍然在线的客户端会发现流已结束,随即重连,并从最后一个事件 id 续传。
+- 事件顺序:携带 `Last-Event-ID`(或 `lastEventId`)重连时,先到达重放的缺失部分(或 `resync_required`),然后是初始事件(权威的 `task_state` 快照和所有仍待处理的 `approval_request`),再是一个 `ping`,最后是实时流。两者都不带的新连接跳过重放,第一个事件就是 `task_state` 快照。
### 推荐的客户端模式
@@ -1200,6 +1201,7 @@ export type ServerEvent =
3. 如果响应带有 `live`(有 Task 正在运行),丢弃缓存中游标已覆盖的 partial 事件,把 `live.fragments` 应用在历史之上。进行中的消息会重新出现,已流式输出的前缀原样保留。
4. 重放缓存的事件,去掉重叠部分。
5. 之后继续处理实时流。
+6. 流发送过 `ping` 之后,50 秒内没有收到任何事件即判定连接已死:关闭它,并以查询参数 `?lastEventId=` 带上最后收到的 id 重新连接。页面重新可见时立即检查一次,因为后台的定时器会延迟执行。从不发送 `ping` 的流来自早于心跳事件的服务器,交给浏览器自带的重连处理。
## 类型导入
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index ff0c4050..d0b15e9e 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -20,6 +20,7 @@ import fsp from "node:fs/promises";
import path from "node:path";
import { Hono } from "hono";
import type { Context, MiddlewareHandler } from "hono";
+import type { HttpBindings } from "@hono/node-server";
import { bodyLimit } from "hono/body-limit";
import { bodyLimitBytes, toAttachmentLimits } from "./services/attachment-limits.js";
import type { DatabaseSync } from "node:sqlite";
@@ -71,6 +72,7 @@ import { AuthSessionsRepo } from "./db/repos/auth-sessions.js";
import { ensureInstallId } from "./install-id.js";
import { handleError, HttpError, errorBody } from "./http/errors.js";
import { attributedProjectId } from "./http/attribution.js";
+import { STREAM_IDLE_MS } from "./http/sse.js";
import { installRoutes } from "./http/routes/install.js";
import { ChannelHub } from "./runtime/channel.js";
import { ErrorRecorder } from "./runtime/error-recorder.js";
@@ -397,6 +399,20 @@ export function createApp(boot: ServerBoot): Hono<AppEnv> {
log(`${c.req.method} ${c.req.path} ${c.res.status} ${ms}ms`);
});
+ // An event stream's socket that sends nothing for STREAM_IDLE_MS is destroyed (Node lets the
+ // first expiry pass while a write is pending, so a stuck write is cut within two). A live
+ // stream pings every 20 s; it goes that quiet only when its peer stopped reading and a write
+ // never completes, and then only the socket can end it: the stream's own close queues behind
+ // that write. The abort runs the stream's teardown. Only the host holds the socket (`c.env`,
+ // passed by index.ts), hence here.
+ app.use("*", async (c, next) => {
+ await next();
+ const socket = (c.env as Partial<HttpBindings> | undefined)?.incoming?.socket;
+ if (socket && c.res.headers.get("content-type")?.startsWith("text/event-stream")) {
+ socket.setTimeout(STREAM_IDLE_MS, () => socket.destroy());
+ }
+ });
+
// Canonical-host guard (loopback binds only): the App is served on one loopback name and
// previews on its counterpart, but the SAME process answers on both. Without this, Agent-
// written preview HTML on the preview host could call /api same-origin and — if a session
diff --git a/packages/server/src/http/sse.ts b/packages/server/src/http/sse.ts
index 5d17fc29..ae698ee3 100644
--- a/packages/server/src/http/sse.ts
+++ b/packages/server/src/http/sse.ts
@@ -5,12 +5,17 @@
*
* - Response headers: text/event-stream, no-cache, `X-Accel-Buffering: no` (disables
* buffering on reverse proxies);
- * - Heartbeat: writes a `: ping` comment line every 20s; the connection is torn down on write failure;
+ * - Heartbeat: a named `ping` event (`data: {}`, no `id:` line) right after the initial
+ * events and every 20s after. A browser hides comment lines from the page, so only an
+ * event lets it tell a quiet stream from a dead one (web api/sse.ts); without an id it
+ * moves neither Last-Event-ID nor the replay cursor. A peer that stops reading is cut off
+ * by the host's idle timeout ({@link STREAM_IDLE_MS}, app.ts);
* - Replay protocol: a fresh subscription without Last-Event-ID does not replay the buffer
* (history is served by the messages endpoint) — it only sends the initial events the
* caller supplied (pending approvals / hello). With a Last-Event-ID that hits the buffer,
* replay resumes from there; on a miss, `resync_required` is sent first, then the
- * connection continues.
+ * connection continues. A page cannot set headers on an EventSource it opens itself, so
+ * the id may come as the `lastEventId` query parameter instead; the header wins.
* - Revocation: a stream is authorised at connect and never again by the request path, so
* an authenticated route hands over {@link SseRevocation} — the registry that can end
* this stream from outside, and the check the heartbeat runs on it.
@@ -27,6 +32,12 @@ import { SESSION_COOKIE, bearerToken } from "../auth/middleware.js";
const HEARTBEAT_MS = 20_000;
+/** An event stream's socket that sends nothing for this long is destroyed (app.ts): two missed beats. */
+export const STREAM_IDLE_MS = 2 * HEARTBEAT_MS;
+
+/** The heartbeat frame: named so a page can see it, id-less so it moves no cursor. */
+const PING = { event: "ping", data: "{}" } as const;
+
/** How the session behind one connection reaches the stream it authorised. */
export interface SseRevocation {
/** The user this connection was authenticated as. */
@@ -72,7 +83,9 @@ export function streamRevocation(
/** Stream out a Channel as an SSE response. */
export function sseEndpoint(c: Context, channel: Channel, opts: SseEndpointOptions = {}): Response {
- const lastEventIdHeader = c.req.header("Last-Event-ID");
+ // The header wins: the browser sets it on its own reconnects, and it is newer than the id
+ // the page wrote into the URL when it opened this EventSource.
+ const lastEventId = c.req.header("Last-Event-ID") ?? c.req.query("lastEventId");
const revocation = opts.revocation;
c.header("X-Accel-Buffering", "no");
c.header("Cache-Control", "no-cache");
@@ -95,7 +108,9 @@ export function sseEndpoint(c: Context, channel: Channel, opts: SseEndpointOptio
let unsubscribe: (() => void) | null = null;
let heartbeat: ReturnType<typeof setInterval> | null = null;
try {
- // Write serialization: SSE events must be written fully and in order; any write failure tears down the connection.
+ // Write serialization: SSE events must be written fully and in order. A write to a peer
+ // that stopped reading never completes; the host's idle timeout then destroys the
+ // socket, which aborts the stream and lands in finish() below.
let chain: Promise<void> = Promise.resolve();
const enqueue = (write: () => Promise<unknown>): void => {
chain = chain
@@ -118,9 +133,9 @@ export function sseEndpoint(c: Context, channel: Channel, opts: SseEndpointOptio
unsubscribe = channel.subscribe(listener);
// Subscribe first (to avoid dropping events in a race with broadcasts), then replay
// synchronously — event order: buffered replay (or resync_required) -> initial events
- // (task_state snapshot / pending approvals / hello) -> live stream.
- if (lastEventIdHeader !== undefined) {
- const replay = channel.replayAfter(lastEventIdHeader);
+ // (task_state snapshot / pending approvals / hello) -> ping -> live stream.
+ if (lastEventId !== undefined) {
+ const replay = channel.replayAfter(lastEventId);
if (!replay.hit) {
const resync: ServerEvent = { type: "resync_required" };
channel.sendTo(listener, resync, "server_event");
@@ -131,6 +146,9 @@ export function sseEndpoint(c: Context, channel: Channel, opts: SseEndpointOptio
for (const event of opts.initialEvents ?? []) {
channel.sendTo(listener, event, "server_event");
}
+ // The first beat goes out at once, so a client knows from the first second that this
+ // stream pings — not only after the first interval has passed.
+ enqueue(() => stream.writeSSE(PING));
heartbeat = setInterval(() => {
// The heartbeat is the one beat an open stream already has, so re-asking whether
@@ -143,7 +161,7 @@ export function sseEndpoint(c: Context, channel: Channel, opts: SseEndpointOptio
finish();
return;
}
- enqueue(() => stream.write(": ping\n\n"));
+ enqueue(() => stream.writeSSE(PING));
}, HEARTBEAT_MS);
stream.onAbort(() => finish());
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index 6176cc21..758ee2ae 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -281,7 +281,8 @@ class PenguinServer {
});
this.httpServer = serve(
{
- fetch: (request: Request) => this.app?.fetch(request) ?? startingResponse(),
+ // `env` carries the Node request: app.ts sets an event stream's idle timeout on its socket.
+ fetch: (request: Request, env) => this.app?.fetch(request, env) ?? startingResponse(),
hostname: this.config.host,
port: this.config.port,
},
@@ -444,7 +445,7 @@ class PenguinServer {
*/
private openIpv6Loopback(port: number): void {
const loopback = serve({
- fetch: (request: Request) => this.app?.fetch(request) ?? startingResponse(),
+ fetch: (request: Request, env) => this.app?.fetch(request, env) ?? startingResponse(),
hostname: "::1",
port,
});
diff --git a/packages/server/test/live-streams.test.ts b/packages/server/test/live-streams.test.ts
index bed7547a..4512c7e0 100644
--- a/packages/server/test/live-streams.test.ts
+++ b/packages/server/test/live-streams.test.ts
@@ -164,11 +164,12 @@ describe("the SSE heartbeat re-checks its own session", () => {
const res = await streamingApp(session, registry).request("/stream");
const reader = res.body!.getReader();
await reader.read(); // hello: the connection is established and registered
+ await reader.read(); // the ping every stream opens with
vi.advanceTimersByTime(HEARTBEAT_MS);
const beat = await reader.read();
expect(beat.done).toBe(false);
- expect(new TextDecoder().decode(beat.value)).toContain(": ping");
+ expect(new TextDecoder().decode(beat.value)).toContain("event: ping");
expect(registry.countFor("alice")).toBe(1);
await reader.cancel();
});
@@ -179,7 +180,8 @@ describe("the SSE heartbeat re-checks its own session", () => {
const session = { live: true };
const res = await streamingApp(session, registry).request("/stream");
const reader = res.body!.getReader();
- await reader.read();
+ await reader.read(); // hello
+ await reader.read(); // the opening ping
expect(registry.countFor("alice")).toBe(1);
// Whatever dropped the rows did not tell the registry — the beat is what notices.
diff --git a/packages/server/test/sse-stream.test.ts b/packages/server/test/sse-stream.test.ts
index 1015c783..77bb430b 100644
--- a/packages/server/test/sse-stream.test.ts
+++ b/packages/server/test/sse-stream.test.ts
@@ -3,8 +3,10 @@
*
* - A new subscription's first frame is always the task_state snapshot: idle when idle; when
* running, `running` followed by the replay of pending approvals.
+ * - The opening frames end with the heartbeat: a `ping` event with `data: {}` and no id.
* - A Last-Event-ID from another epoch gets resync_required first, then the snapshot; one that
- * hits the replay buffer gets the later events, then the snapshot.
+ * hits the replay buffer gets the later events, then the snapshot, and so does the same id
+ * passed as the `lastEventId` query parameter.
* - An admin resetting a user's password ends that user's open event streams at once, and the
* old session cannot reopen one.
*/
@@ -91,8 +93,8 @@ describe("sse-stream", () => {
t.deps.sessionsRepo.insert(row);
});
- const getStream = (headers: Record<string, string> = {}) =>
- t.app.request(`/api/sessions/${SID}/stream`, { headers: { cookie, ...headers } });
+ const getStream = (headers: Record<string, string> = {}, query = "") =>
+ t.app.request(`/api/sessions/${SID}/stream${query}`, { headers: { cookie, ...headers } });
it("FD-1: a new subscription's first frame is always the task_state snapshot (idle)", async () => {
const frames = await readSseFrames(await getStream(), 1);
@@ -101,6 +103,11 @@ describe("sse-stream", () => {
expect(frames[0]!.id).toMatch(/^[0-9a-f]{8}-\d+$/); // FD-2: opaque string id
});
+ it("the opening frames end with an id-less ping event", async () => {
+ const frames = await readSseFrames(await getStream(), 2);
+ expect(frames[1]).toEqual({ event: "ping", data: "{}" });
+ });
+
it("FD-1: subscribing while running receives task_state: running, then pending approvals are replayed", async () => {
t.deps.manager.adopt(row, approvalFakeSession(SID));
await t.deps.manager.startTask(SID, [userText("go")]);
@@ -140,8 +147,12 @@ describe("sse-stream", () => {
expect(res.status).toBe(200);
const reader = res.body!.getReader();
// The hello frame proves the subscription is live — and therefore registered — before
- // the reset lands.
- expect(new TextDecoder().decode((await reader.read()).value)).toContain("hello");
+ // the reset lands; the ping that follows it is the last of the opening frames.
+ let opening = "";
+ while (!opening.includes("event: ping")) {
+ opening += new TextDecoder().decode((await reader.read()).value);
+ }
+ expect(opening).toContain("hello");
const admin = await loginAdmin(t.app);
const reset = await apiClient(t.app, admin.cookie).post(
@@ -156,11 +167,14 @@ describe("sse-stream", () => {
expect((await t.app.request("/api/events", { headers: { cookie: own } })).status).toBe(401);
});
- it("FD-2: same-epoch Last-Event-ID hitting the buffer → replays later events, then the task_state snapshot", async () => {
+ it.each([
+ { carrier: "Last-Event-ID", open: (id: string) => getStream({ "Last-Event-ID": id }) },
+ { carrier: "?lastEventId=", open: (id: string) => getStream({}, `?lastEventId=${id}`) },
+ ])("FD-2: a buffered $carrier → later events, then the snapshot", async ({ open }) => {
const channel = t.deps.channels.get(SID);
const first = channel.publish(userText("m1"));
channel.publish(userText("m2"));
- const frames = await readSseFrames(await getStream({ "Last-Event-ID": first.id }), 2);
+ const frames = await readSseFrames(await open(first.id), 2);
expect(frames[0]!.event).toBeUndefined(); // replayed OmniMessage
expect((JSON.parse(frames[0]!.data) as { payload: { text: string } }).payload.text).toBe("m2");
expect(JSON.parse(frames[1]!.data)).toEqual({ type: "task_state", state: "idle", queued: 0 });
diff --git a/packages/server/test/sse-wire.test.ts b/packages/server/test/sse-wire.test.ts
new file mode 100644
index 00000000..0320c7c9
--- /dev/null
+++ b/packages/server/test/sse-wire.test.ts
@@ -0,0 +1,89 @@
+/**
+ * An event stream over a real socket: the app served by @hono/node-server, read by a Node
+ * HTTP client that stops reading, the way a dead peer or a stuck proxy does.
+ *
+ * - Given a subscriber that stopped reading while events keep coming, once its socket has
+ * sent nothing for the idle timeout the server destroys it and drops the subscription,
+ * and the client, reading again, finds the stream ended (which sends an EventSource to
+ * reconnect).
+ */
+import http from "node:http";
+import net from "node:net";
+import { serve } from "@hono/node-server";
+import { afterAll, beforeAll, expect, it, vi } from "vitest";
+import { userText } from "@lmliheng/penguin-core";
+import { sessionRow, uniqueSessionId } from "./fixtures/session.js";
+import { createTestApp, provisionUser, waitFor } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+let t: TestApp;
+let cookie: string;
+let server: ReturnType<typeof serve>;
+let port: number;
+
+beforeAll(async () => {
+ t = await createTestApp();
+ ({ cookie } = await provisionUser(t.app, "wire"));
+ await new Promise<void>((resolve) => {
+ server = serve({ fetch: t.app.fetch, hostname: "127.0.0.1", port: 0 }, (info) => {
+ port = info.port;
+ resolve();
+ });
+ });
+});
+afterAll(async () => {
+ (server as http.Server).closeAllConnections();
+ await new Promise((resolve) => server.close(resolve));
+ await t.cleanup();
+});
+
+it("a subscriber that stopped reading is cut off once its socket goes idle, and unsubscribed", async () => {
+ // A socket's idle timer is Node's own, out of fake timers' reach: whatever idle timeout the
+ // app asks for runs as 300 ms here.
+ const setSocketTimeout = net.Socket.prototype.setTimeout;
+ vi.spyOn(net.Socket.prototype, "setTimeout").mockImplementation(function (
+ this: net.Socket,
+ ms: number,
+ callback?: () => void,
+ ) {
+ return setSocketTimeout.call(this, ms > 0 ? 300 : 0, callback);
+ });
+ const sessionId = uniqueSessionId();
+ t.deps.sessionsRepo.insert(sessionRow(sessionId, { projectId: "wire-default_project" }));
+ const channel = t.deps.channels.get(sessionId);
+ const accepted = new Promise<net.Socket>((resolve) => server.once("connection", resolve));
+ const res = await new Promise<http.IncomingMessage>((resolve, reject) => {
+ const headers = { host: `localhost:${port}`, cookie };
+ http
+ .get(
+ {
+ host: "127.0.0.1",
+ port,
+ path: `/api/sessions/${sessionId}/stream`,
+ headers,
+ agent: false,
+ },
+ resolve,
+ )
+ .on("error", reject);
+ });
+ res.on("error", () => undefined);
+ const socket = await accepted;
+ await waitFor(() => channel.subscriberCount === 1);
+
+ // The peer stops reading; events keep coming until the buffers are full and a write sticks.
+ res.socket.pause();
+ const body = "x".repeat(64 * 1024);
+ const deadline = Date.now() + 3000;
+ while (!socket.destroyed && Date.now() < deadline) {
+ channel.publish(userText(body));
+ channel.publish(userText(body));
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ }
+ expect(socket.destroyed).toBe(true);
+ await waitFor(() => channel.subscriberCount === 0);
+
+ res.socket.resume();
+ res.resume();
+ await waitFor(() => res.socket.destroyed);
+});
diff --git a/packages/web/e2e/stream-stall.spec.mjs b/packages/web/e2e/stream-stall.spec.mjs
new file mode 100644
index 00000000..e3fcbe64
--- /dev/null
+++ b/packages/web/e2e/stream-stall.spec.mjs
@@ -0,0 +1,136 @@
+/**
+ * A Session stream that dies silently mid-run: the page must catch up without a reload.
+ *
+ * The browser reaches the server through a TCP relay. Mid-reply the relay swallows the open
+ * Session stream's bytes and closes nothing, as a half-open connection or a stuck proxy does.
+ * The run finishes on the server; then the page's clock jumps past the liveness window, and
+ * the page must reconnect from the last event it saw and show the whole reply exactly once.
+ * The mock LLM's "slow text test" streams 40 chunks, one every 200 ms.
+ */
+import net from "node:net";
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+const U = "stalluser";
+const P = "password123";
+
+/** Create a session for the user's auto-provisioned project (models PUT is idempotent). */
+async function createSession(page) {
+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const projectId = projects.projects[0].projectId;
+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {
+ data: {
+ defaultModel: { provider: "custom", modelId: "claude-4-8" },
+ models: [
+ {
+ provider: "custom",
+ modelId: "claude-4-8",
+ apiKey: "sk-mock",
+ baseUrl: MOCK,
+ contextWindow: 200000,
+ },
+ ],
+ },
+ });
+ expect(put.ok(), "put models").toBeTruthy();
+ const res = await page.request.post(
+ `${BASE}/api/projects/${projectId}/agents/default_agent/sessions`,
+ { data: { provider: "custom", modelId: "claude-4-8", approvalMode: "allow-all" } },
+ );
+ expect(res.ok(), `create session: ${await res.text()}`).toBeTruthy();
+ return (await res.json()).session.sessionId;
+}
+
+/** A TCP relay in front of the server; `silenceSessionStreams()` mutes the open Session streams. */
+async function startRelay() {
+ const target = new URL(BASE);
+ const pairs = new Set();
+ const server = net.createServer((client) => {
+ const upstream = net.connect(Number(target.port), "127.0.0.1");
+ const pair = { client, upstream, sessionStream: false, silent: false };
+ pairs.add(pair);
+ client.on("data", (chunk) => {
+ if (/^GET \/api\/sessions\/[^/\s]+\/stream[?\s]/m.test(chunk.toString("latin1"))) {
+ pair.sessionStream = true;
+ }
+ upstream.write(chunk);
+ });
+ upstream.on("data", (chunk) => {
+ if (!pair.silent) client.write(chunk);
+ });
+ const end = () => {
+ pairs.delete(pair);
+ client.destroy();
+ upstream.destroy();
+ };
+ for (const socket of [client, upstream]) {
+ socket.on("close", end);
+ socket.on("error", end);
+ }
+ });
+ await new Promise((resolve) => server.listen(0, resolve));
+ return {
+ url: `http://localhost:${server.address().port}`,
+ silenceSessionStreams() {
+ const streams = [...pairs].filter((pair) => pair.sessionStream);
+ for (const pair of streams) pair.silent = true;
+ return streams.length;
+ },
+ close() {
+ for (const pair of pairs) {
+ pair.client.destroy();
+ pair.upstream.destroy();
+ }
+ return new Promise((resolve) => server.close(resolve));
+ },
+ };
+}
+
+test("a Session stream that goes silent mid-run catches up on its own, without a reload", async ({
+ page,
+}) => {
+ await provisionAndLogin(page.request, U, P);
+ const sessionId = await createSession(page);
+ const relay = await startRelay();
+ try {
+ // A fake clock that runs at real speed until the test jumps it forward.
+ await page.clock.install();
+ await page.goto(`${relay.url}/chat/${sessionId}`);
+ // Survives only if the page is never reloaded.
+ await page.evaluate(() => {
+ window.__stallMarker = "same page";
+ });
+
+ const ta = page.getByPlaceholder(/输入消息/);
+ await ta.waitFor();
+ await ta.fill("slow text test");
+ await page.getByRole("button", { name: "发送" }).click();
+ const reply = page.locator(".md-body", { hasText: /chunk-1\s/ }).first();
+ await expect(reply).toContainText("chunk-3 ");
+
+ expect(relay.silenceSessionStreams(), "a Session stream was open").toBeGreaterThan(0);
+
+ // The run finishes on the server while the page hears nothing.
+ await expect
+ .poll(
+ async () =>
+ (await (await page.request.get(`${BASE}/api/sessions/${sessionId}`)).json()).session
+ .status,
+ { timeout: 30_000 },
+ )
+ .toBe("idle");
+ await expect(reply).not.toContainText("chunk-40");
+
+ // Past the liveness window: the page notices the silence and reconnects.
+ await page.clock.fastForward(60_000);
+ await expect(reply).toContainText("chunk-40", { timeout: 15_000 });
+ const text = await reply.textContent();
+ expect(text.match(/chunk-5 /g)).toHaveLength(1);
+ expect(text.match(/chunk-39 /g)).toHaveLength(1);
+ expect(await page.evaluate(() => window.__stallMarker)).toBe("same page");
+ } finally {
+ await relay.close();
+ }
+});
diff --git a/packages/web/src/api/sse.ts b/packages/web/src/api/sse.ts
index d273abda..a48d751d 100644
--- a/packages/web/src/api/sse.ts
+++ b/packages/web/src/api/sse.ts
@@ -9,6 +9,11 @@
* disconnect, the browser auto-reconnects and attaches a `Last-Event-ID` header (the server
* replays from its ring buffer; if the event was already evicted, it pushes resync_required
* instead).
+ * - Liveness: a connection can die without any error (half-open TCP, a stuck proxy or NAT).
+ * Once a stream has sent a `ping` (the server's heartbeat, every 20 s), {@link SILENCE_MS}
+ * without any event closes it and opens a new one with `?lastEventId=` set to the last id
+ * seen; the tab becoming visible checks at once, since background timers run late. A stream
+ * that never pinged (an older server), or that the browser gave up on, is left as it is.
* Docs: /docs/server-api § "Streaming (SSE)".
*/
import type { OmniMessage } from "@lmliheng/penguin-core/omnimessage";
@@ -16,6 +21,9 @@ import type { ServerEvent } from "@lmliheng/penguin-server/api";
import { apiUrl } from "../lib/server-context";
import { machineForSession } from "../lib/session-machines";
+/** The server pings every 20 s: this much silence means the connection is gone. */
+const SILENCE_MS = 50_000;
+
export interface StreamHandlers {
/**
* A single OmniMessage (full/streaming/event, envelope as-is). `eventId` is the SSE
@@ -26,7 +34,7 @@ export interface StreamHandlers {
onOmniMessage: (msg: OmniMessage, eventId: string | null) => void;
/** A single server event (`eventId`: same as onOmniMessage). */
onServerEvent: (event: ServerEvent, eventId: string | null) => void;
- /** Connection established (including a successful auto-reconnect). */
+ /** Connection established (including a successful auto-reconnect, and a reopen after silence). */
onOpen?: () => void;
/**
* Connection error. `closed` is true when the browser has deemed the connection fatally
@@ -41,8 +49,20 @@ export interface StreamConnection {
}
function subscribe(url: string, handlers: StreamHandlers): StreamConnection {
- const source = new EventSource(url);
- source.onmessage = (e: MessageEvent<string>) => {
+ let source: EventSource | undefined;
+ /** The newest event id seen on any of this subscription's connections. */
+ let lastEventId = "";
+ let lastHeard = 0;
+ /** The stream has pinged, so silence means a dead connection. */
+ let armed = false;
+ let watchdog: ReturnType<typeof setTimeout> | undefined;
+
+ const heard = (e: MessageEvent<string>) => {
+ lastHeard = Date.now();
+ if (e.lastEventId) lastEventId = e.lastEventId;
+ };
+ const onMessage = (e: MessageEvent<string>) => {
+ heard(e);
try {
// Every server event carries an `id:` line; lastEventId is "" only if none did.
handlers.onOmniMessage(JSON.parse(e.data) as OmniMessage, e.lastEventId || null);
@@ -50,17 +70,62 @@ function subscribe(url: string, handlers: StreamHandlers): StreamConnection {
// Ignore lines that fail to parse (the protocol guarantees single-line JSON data, so this shouldn't normally happen).
}
};
- source.addEventListener("server_event", (e: MessageEvent<string>) => {
+ const onServerEvent = (e: MessageEvent<string>) => {
+ heard(e);
try {
handlers.onServerEvent(JSON.parse(e.data) as ServerEvent, e.lastEventId || null);
} catch {
// Same as above.
}
- });
- if (handlers.onOpen) source.onopen = handlers.onOpen;
- const { onError } = handlers;
- if (onError) source.onerror = () => onError(source.readyState === EventSource.CLOSED);
- return { close: () => source.close() };
+ };
+ const onPing = (e: MessageEvent<string>) => {
+ heard(e);
+ armed = true;
+ check();
+ };
+ const onError = () => {
+ const closed = source?.readyState === EventSource.CLOSED;
+ // The browser gave up on the connection: what happens next is the caller's call, as before.
+ if (closed) disarm();
+ handlers.onError?.(closed);
+ };
+ const connect = () => {
+ source?.close();
+ lastHeard = Date.now();
+ source = new EventSource(
+ lastEventId ? `${url}?lastEventId=${encodeURIComponent(lastEventId)}` : url,
+ );
+ source.onmessage = onMessage;
+ source.addEventListener("server_event", onServerEvent);
+ source.addEventListener("ping", onPing);
+ if (handlers.onOpen) source.onopen = handlers.onOpen;
+ source.onerror = onError;
+ };
+
+ /** Reopens a stream silent for the whole window; otherwise waits out the rest of it. */
+ const check = () => {
+ clearTimeout(watchdog);
+ if (!armed) return;
+ if (Date.now() - lastHeard >= SILENCE_MS) connect();
+ watchdog = setTimeout(check, lastHeard + SILENCE_MS - Date.now());
+ };
+ const disarm = () => {
+ armed = false;
+ clearTimeout(watchdog);
+ };
+ const onVisibility = () => {
+ if (document.visibilityState === "visible") check();
+ };
+
+ document.addEventListener("visibilitychange", onVisibility);
+ connect();
+ return {
+ close: () => {
+ disarm();
+ document.removeEventListener("visibilitychange", onVisibility);
+ source?.close();
+ },
+ };
}
/** Subscribes to a Session's output stream (GET /api/sessions/:sessionId/stream). */
diff --git a/packages/web/src/features/chat/use-session-stream.ts b/packages/web/src/features/chat/use-session-stream.ts
index b87d9b56..452f87f1 100644
--- a/packages/web/src/features/chat/use-session-stream.ts
+++ b/packages/web/src/features/chat/use-session-stream.ts
@@ -7,7 +7,8 @@
* 2. GET messages renders history, then replays the buffer (overlap deduped); on load failure,
* expose error and a retry entry point;
* 3. Disconnects are auto-reconnected by the browser (Last-Event-ID built in; server replays from
- * its buffer); resync_required → controller rebuilds the model and keeps consuming the same
+ * its buffer), and a connection that went silent is reopened by api/sse.ts from the last id
+ * seen; resync_required → controller rebuilds the model and keeps consuming the same
* connection;
* 4. task_state in the stream is the authoritative run state (server pushes the current snapshot
* on subscribe); initialStatus only serves as the first-frame placeholder, driving the input
diff --git a/packages/web/test/helpers/event-source.ts b/packages/web/test/helpers/event-source.ts
new file mode 100644
index 00000000..0bafacb5
--- /dev/null
+++ b/packages/web/test/helpers/event-source.ts
@@ -0,0 +1,63 @@
+/**
+ * The browser's `EventSource` and the page's visibility, for the node suite. The test plays
+ * the server through `emit` and `fail`; as in the browser, an event without an id keeps the
+ * source's last event id, and a closed source never dispatches again. The package config
+ * sets `unstubGlobals`, so both stubs are gone before the next test.
+ */
+import { vi } from "vitest";
+
+export class FakeEventSource {
+ static readonly CLOSED = 2;
+ readyState = 0;
+ onopen: (() => void) | null = null;
+ onmessage: ((e: MessageEvent<string>) => void) | null = null;
+ onerror: (() => void) | null = null;
+ private readonly listeners = new Map<string, (e: MessageEvent<string>) => void>();
+ private lastEventId = "";
+
+ constructor(readonly url: string) {}
+ addEventListener(type: string, listener: (e: MessageEvent<string>) => void): void {
+ this.listeners.set(type, listener);
+ }
+ close(): void {
+ this.readyState = FakeEventSource.CLOSED;
+ }
+ /** One frame from the server: `message` is an unnamed one. */
+ emit(type: string, data = "{}", id?: string): void {
+ if (this.readyState === FakeEventSource.CLOSED) return;
+ if (id !== undefined) this.lastEventId = id;
+ const e = new MessageEvent(type, { data, lastEventId: this.lastEventId });
+ if (type === "message") this.onmessage?.(e);
+ else this.listeners.get(type)?.(e);
+ }
+ /** The browser gives up on the connection (a non-200 answer): closed, `error` fired. */
+ fail(): void {
+ this.readyState = FakeEventSource.CLOSED;
+ this.onerror?.();
+ }
+}
+
+/** Installs the fake; returns every source constructed, oldest first. */
+export function stubEventSource(): FakeEventSource[] {
+ const sources: FakeEventSource[] = [];
+ vi.stubGlobal(
+ "EventSource",
+ class extends FakeEventSource {
+ constructor(url: string) {
+ super(url);
+ sources.push(this);
+ }
+ },
+ );
+ return sources;
+}
+
+/** Installs a `document` whose visibility the test sets, firing `visibilitychange`. */
+export function stubVisibility(): (state: DocumentVisibilityState) => void {
+ const doc = Object.assign(new EventTarget(), { visibilityState: "visible" });
+ vi.stubGlobal("document", doc);
+ return (state) => {
+ doc.visibilityState = state;
+ doc.dispatchEvent(new Event("visibilitychange"));
+ };
+}
diff --git a/packages/web/test/sse.test.ts b/packages/web/test/sse.test.ts
new file mode 100644
index 00000000..30a6fa15
--- /dev/null
+++ b/packages/web/test/sse.test.ts
@@ -0,0 +1,102 @@
+/**
+ * Stream liveness (api/sse.ts), against the browser's EventSource contract.
+ *
+ * - Given a stream that has pinged, when it is silent for 50 s, its EventSource is closed and
+ * one new one opens with `?lastEventId=` set to the newest id seen (at 49 s nothing
+ * happens); silent again before the new one delivered an id, it resumes from the same id.
+ * - Given pings every 20 s, the stream is never reopened.
+ * - Given a tab whose timers did not run, becoming visible past the window reopens the stream
+ * at once; being hidden does not.
+ * - Given a server that never pings (one older than the heartbeat), nothing reopens it.
+ * - Once the caller closed it, or the browser gave up on it (reported as a closed error),
+ * nothing reopens it.
+ */
+import { afterEach, expect, it, vi } from "vitest";
+import { openSessionStream } from "../src/api/sse";
+import { FakeEventSource, stubEventSource, stubVisibility } from "./helpers/event-source";
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+function subscribe() {
+ vi.useFakeTimers();
+ const sources = stubEventSource();
+ const setVisibility = stubVisibility();
+ const errors: boolean[] = [];
+ const conn = openSessionStream("s1", {
+ onOmniMessage: () => undefined,
+ onServerEvent: () => undefined,
+ onError: (closed) => errors.push(closed),
+ });
+ return { sources, setVisibility, conn, errors };
+}
+type Sub = ReturnType<typeof subscribe>;
+
+/** What a current server sends first: the snapshot, with an id, then a ping. */
+function greet(source: FakeEventSource, id: string): void {
+ source.emit("server_event", JSON.stringify({ type: "task_state", state: "running" }), id);
+ source.emit("ping");
+}
+
+const live = (sources: FakeEventSource[]) =>
+ sources.filter((s) => s.readyState !== FakeEventSource.CLOSED);
+
+it("a stream silent for 50 s is reopened, once, from the newest event id seen", () => {
+ const { sources } = subscribe();
+ greet(sources[0]!, "e-1");
+ sources[0]!.emit("message", "{}", "e-2");
+
+ vi.advanceTimersByTime(49_000);
+ expect(sources).toHaveLength(1);
+ vi.advanceTimersByTime(1_000);
+ expect(sources[1]!.url).toBe("/api/sessions/s1/stream?lastEventId=e-2");
+ expect(live(sources)).toEqual([sources[1]]);
+
+ sources[1]!.emit("ping");
+ vi.advanceTimersByTime(50_000);
+ expect(sources[2]!.url).toBe("/api/sessions/s1/stream?lastEventId=e-2");
+ expect(live(sources)).toEqual([sources[2]]);
+});
+
+it("a stream that keeps pinging is never reopened", () => {
+ const { sources } = subscribe();
+ greet(sources[0]!, "e-1");
+ for (let beat = 0; beat < 10; beat++) {
+ vi.advanceTimersByTime(20_000);
+ sources[0]!.emit("ping");
+ }
+ expect(sources).toHaveLength(1);
+});
+
+it("becoming visible past the window reopens the stream at once, though no timer ran", () => {
+ const { sources, setVisibility } = subscribe();
+ greet(sources[0]!, "e-1");
+ vi.setSystemTime(Date.now() + 120_000);
+ setVisibility("hidden");
+ expect(sources).toHaveLength(1);
+ setVisibility("visible");
+ expect(sources[1]!.url).toBe("/api/sessions/s1/stream?lastEventId=e-1");
+ expect(live(sources)).toEqual([sources[1]]);
+});
+
+it("a stream that never pinged is never reopened", () => {
+ const { sources, setVisibility } = subscribe();
+ sources[0]!.emit("server_event", JSON.stringify({ type: "task_state", state: "idle" }), "e-1");
+ vi.advanceTimersByTime(60 * 60_000);
+ setVisibility("visible");
+ expect(live(sources)).toEqual([sources[0]]);
+});
+
+it.each([
+ { how: "the caller closed it", end: (s: Sub) => s.conn.close(), errors: [] },
+ { how: "the browser gave up on it", end: (s: Sub) => s.sources[0]!.fail(), errors: [true] },
+])("once $how, a stream is never reopened", ({ end, errors }) => {
+ const sub = subscribe();
+ greet(sub.sources[0]!, "e-1");
+ end(sub);
+ vi.advanceTimersByTime(60 * 60_000);
+ sub.setVisibility("visible");
+ expect(live(sub.sources)).toEqual([]);
+ expect(sub.errors).toEqual(errors);
+});