Skip to content

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

fix(web): 实时流一个字节都收不到时,页面不再停在原地

lmliheng43ca2f85fa4b
diff --git a/changelog/unreleased/2026-11-13-stream-stall-refresh.md b/changelog/unreleased/2026-11-13-stream-stall-refresh.md
new file mode 100644
index 00000000..07f1fe22
--- /dev/null
+++ b/changelog/unreleased/2026-11-13-stream-stall-refresh.md
@@ -0,0 +1,56 @@
+# A live stream that never delivers anything no longer leaves the page looking frozen
+
+- **Date:** 2026-11-13
+- **Type:** fix
+- **Scope:** `web`
+
+[中文版](2026-11-13-stream-stall-refresh.zh.md)
+
+A conversation whose live SSE stream was being swallowed — the handshake completed, the response
+body never arrived, which is what a proxy or NAT in between can do — went completely silent: the
+page kept showing whatever it already had, nothing ever moved again, and a Task running on the
+server read as a hung agent. The client's only liveness watch was armed by the server's `ping`, so
+a connection that never delivered one was not watched at all.
+
+The connection is now watched against both failures. One that receives nothing at all within 30
+seconds is treated as open but not connected, and reopened; after three of those in a row the
+stream is judged stalled — it stops reopening at once, probes once a minute, and tells the page,
+which then refreshes the conversation from `GET /messages` on a timer and says so in a strip above
+the composer. The first event to get through clears the verdict, the timer and the strip.
+
+## Details
+
+- `packages/web/src/api/sse.ts`: a first-frame deadline (`FIRST_FRAME_MS`, 30 s) beside the
+ existing silence window (`SILENCE_MS`, 50 s), which still applies only to a stream that has
+ pinged. Three connections in a row with nothing on them (`MAX_STALLED`) stop the immediate
+ reopen and switch to one probe a minute (`STALL_REPROBE_MS`). The new `onLiveness` handler
+ reports the verdict, and every reconnect — probes included — keeps resuming from the newest
+ event id seen.
+- `packages/web/src/lib/omni/stream-controller.ts`: `refresh()`, which refetches the tail window in
+ place and, unlike a resync rebuild, keeps the pending-approvals table, so an approval on screen
+ stays answerable while the stream is down. It is a no-op while a load is in flight, after a
+ failed one, and once disposed.
+- `packages/web/src/features/chat/use-session-stream.ts`: the verdict starts and stops a
+ six-second refresh timer and is exposed as `streamStalled`.
+- `packages/web/src/features/chat/stream-stalled-banner.tsx`: the strip, mounted above the composer
+ beside the goal banner.
+
+## Tests
+
+- `packages/web/test/sse.test.ts`: a connection with nothing on it is reopened at the deadline;
+ three in a row stall the stream, hold no connection open, report once and probe a minute later;
+ a frame on a probe returns it to live and the probing stops; a probe the browser itself gives up
+ on schedules the next one; a stalled stream keeps resuming from
+ the newest id it ever saw. The earlier guarantees are unchanged: a greeted stream's 50-second
+ silence window, a stream that only pings, a late tab, a stream that spoke but never pinged, and a
+ connection the caller closed or the browser gave up on.
+- `packages/web/test/stream-controller.test.ts`: a refresh lands the refetched history in a fresh
+ model without duplicating it, keeps the pending approval, and leaves the transcript on screen
+ until the fetch returns; it is a no-op while a load is in flight, after a failure, and once
+ disposed.
+
+## Compatibility
+
+No wire change, no new dependency, no Project config change, one new line of copy (the strip). A
+server older than the heartbeat is unaffected: it answers a subscribe with its `task_state`
+snapshot, which retires the new first-frame deadline, and its silence was never watched.
diff --git a/changelog/unreleased/2026-11-13-stream-stall-refresh.zh.md b/changelog/unreleased/2026-11-13-stream-stall-refresh.zh.md
new file mode 100644
index 00000000..34b40be2
--- /dev/null
+++ b/changelog/unreleased/2026-11-13-stream-stall-refresh.zh.md
@@ -0,0 +1,42 @@
+# 一个字节都送不到的实时流,不再让页面看起来卡死
+
+- **Date:** 2026-11-13
+- **Type:** fix
+- **Scope:** `web`
+
+[English](2026-11-13-stream-stall-refresh.md)
+
+实时流被中途吃掉时——握手完成了,响应体却一直不来,中间的代理或 NAT 就可能这样——对话会彻底安静下来:页面停在
+已经显示的内容上,再也不会动,而服务端明明在跑的 Task 看起来像卡死的智能体。客户端唯一的存活判断要靠服务端的
+`ping` 来武装,于是一个 `ping` 都没送到的连接根本没人看。
+
+现在两种失败各有各的期限。30 秒内一个事件都收不到的连接按「开着但没通」处理并重开;连着三条都这样,这条流就
+判定为停止:不再立刻重开,改成每分钟试探一次,并告诉页面 —— 页面随即靠定时 `GET /messages` 刷新对话,并在对话框
+上方用一条提示说明。第一个送到的帧会清掉这个判断、那个定时器和那条提示。
+
+## 细节
+
+- `packages/web/src/api/sse.ts`:在原有的静默窗口(`SILENCE_MS`,50 秒)之外新增首帧期限
+ (`FIRST_FRAME_MS`,30 秒);静默窗口仍然只对发送过 `ping` 的流生效。连续三条连接上什么都没有
+ (`MAX_STALLED`)时不再立刻重开,改为每分钟试探一条(`STALL_REPROBE_MS`)。新增的 `onLiveness`
+ 回调报告这个判断,而且每一次重连——包括试探——都仍然从见过的最新事件 id 续传。
+- `packages/web/src/lib/omni/stream-controller.ts`:新增 `refresh()`,就地重取尾部窗口;与 resync 重建不同,
+ 它保留未决审批表,所以流断了的时候屏幕上的审批仍然可答。加载在途、加载失败过、以及已释放之后,它都是空操作。
+- `packages/web/src/features/chat/use-session-stream.ts`:这个判断负责开停一个六秒的刷新定时器,并作为
+ `streamStalled` 交出去。
+- `packages/web/src/features/chat/stream-stalled-banner.tsx`:那条提示本身,挂在对话框上方、目标横幅旁边。
+
+## 测试
+
+- `packages/web/test/sse.test.ts`:一个字节都没有的连接会在期限到点时被重开;连着三条会判定停止、不保留任何
+ 连接、只报告一次、一分钟后再试探;试探时收到一帧即恢复实时并停止试探;被浏览器放弃的那次试探会自己安排下一次;
+ 停住的流仍然从见过的最新 id 续传。
+ 原有保证一条没变:打过招呼的流 50 秒静默窗口、只会发 `ping` 的流、迟到的标签页,以及开过口但从不发心跳的流、
+ 被调用方关掉或被浏览器放弃的连接。
+- `packages/web/test/stream-controller.test.ts`:刷新把重取到的历史放进新模型、不重复,保留未决审批,并且在
+ 取回之前屏幕上仍是原来的对话;加载在途、失败过、已释放之后都是空操作。
+
+## 兼容性
+
+线上协议没变、没有新依赖、Project 配置没变,只多了一条文案(那条提示)。比心跳事件更老的服务器不受影响:
+它在订阅时就会发 `task_state` 快照,新加的首帧期限因此解除,而它的安静本来就不在观察范围内。
diff --git a/changelog/unreleased/2026-11-13-trace-transport-frames.md b/changelog/unreleased/2026-11-13-trace-transport-frames.md
new file mode 100644
index 00000000..fd063890
--- /dev/null
+++ b/changelog/unreleased/2026-11-13-trace-transport-frames.md
@@ -0,0 +1,51 @@
+# The Trace panel shows the live frames this browser actually received
+
+- **Date:** 2026-11-13
+- **Type:** feature
+- **Scope:** `web`
+
+[中文版](2026-11-13-trace-transport-frames.zh.md)
+
+When a live conversation went quiet there was no way to tell, from the browser, whether data had
+stopped arriving or the server had stopped writing: a frame is gone the moment it is delivered, and
+a reload replaces the connection with a different one.
+
+The Trace panel now carries a **Transport** toggle, off by default. Switched on, it lists the SSE
+frames this browser received — newest first, each with its event name, the id the channel gave it,
+its byte length and the opening of its payload — together with the connection's own markers (`open`,
+`reopen`, `stalled`, `live`, `probe`, `error`, `closed`) and one marker for any quiet stretch longer
+than the server's heartbeat, carrying how long it lasted. The choice is remembered in the browser.
+
+## Details
+
+- `packages/web/src/api/sse-frames.ts`: the page-level ring (300 entries, oldest out), fed by
+ `api/sse.ts` with every frame it receives. Recording stays off unless the toggle turned it on
+ (`penguin.sseFrames`), and turning it off drops what was collected — a frozen list left on screen
+ would read as a stream that stopped. Identical consecutive markers closer together than ten
+ seconds collapse into one, so a browser retrying a dead connection cannot flush the ring.
+- `packages/web/src/features/traces/sse-frame-list.tsx`: the view — toggle, count, clear button and
+ rows — re-rendering on the recorder's notifications only while its dock tab is showing.
+- `packages/web/src/features/traces/transport-rows.ts`: which entries this Session's panel shows
+ (its own channel plus the page's user-level one, marked, newest first, capped at 120 rows).
+- `packages/web/src/features/traces/trace-panel.tsx`: the view, above the file pills.
+- `packages/web/src/lib/format.ts`: `formatTime` also takes epoch milliseconds, so a live record's
+ own clock prints without a round trip through ISO text.
+
+## Tests
+
+- `packages/web/test/sse-frames.test.ts`: recording stays off until the toggle and turns off with
+ the ring; the newest 300 survive; a quiet stretch past the heartbeat leaves one marker carrying
+ its length while one exactly at the interval leaves none; identical markers collapse and frames
+ never do; subscribers are notified until they leave; byte lengths are counted on UTF-8 and
+ previews capped.
+- `packages/web/test/sse.test.ts`: frames reach the recorder from the subscription with their event
+ name, id and byte length.
+- `packages/web/test/transport-rows.test.ts`, `packages/web/test/sse-frame-list.test.ts`: row
+ selection, order and cap; and the rendered markup — off by default, the frames in the wire's own
+ words once on, another Session's channel left out.
+
+## Compatibility
+
+No wire change, no new dependency, no Project config change. It is off by default, so a reader who
+never opens the toggle sees the panel as it was. The view holds the receiving side only: what the
+server wrote is not visible from the browser, and it does not claim otherwise.
diff --git a/changelog/unreleased/2026-11-13-trace-transport-frames.zh.md b/changelog/unreleased/2026-11-13-trace-transport-frames.zh.md
new file mode 100644
index 00000000..b80d963e
--- /dev/null
+++ b/changelog/unreleased/2026-11-13-trace-transport-frames.zh.md
@@ -0,0 +1,40 @@
+# 轨迹面板里能看到本浏览器实际收到的实时帧
+
+- **Date:** 2026-11-13
+- **Type:** feature
+- **Scope:** `web`
+
+[English](2026-11-13-trace-transport-frames.md)
+
+实时对话安静下来时,光从浏览器这边分不清是数据不再送达,还是服务端不再写:帧一送到就没了,刷新页面换来的又是
+另一条连接。
+
+轨迹面板现在多了一个**传输**开关,默认关闭。打开后它列出本浏览器收到的 SSE 帧 —— 新的在上,每行给出事件名、
+通道给的 id、字节数和载荷开头 —— 外加连接自己的标记(`open` / `reopen` / `stalled` / `live` / `probe` /
+`error` / `closed`),以及超过心跳间隔的静默标记(标出静默了多久)。选择记在浏览器里。
+
+## 细节
+
+- `packages/web/src/api/sse-frames.ts`:页面级环形缓冲(300 条,最旧的先出),由 `api/sse.ts` 在每收到一帧时写入。
+ 开关没打开就不记录(键是 `penguin.sseFrames`);关掉时把已收集的清掉 —— 一份冻在屏幕上的列表会被读成流停了。
+ 相邻且间隔不到十秒的同一个标记会合并成一条,否则一个不断重试死连接的浏览器会把环形缓冲冲掉。
+- `packages/web/src/features/traces/sse-frame-list.tsx`:这个视图本身 —— 开关、计数、清空按钮和每一行 ——
+ 只在自己的停靠页显示时跟着记录器的通知重绘。
+- `packages/web/src/features/traces/transport-rows.ts`:本 Session 的面板显示哪些条目(它自己的通道加上页面那条
+ 用户级流,后者带标记),新的在上,最多 120 行。
+- `packages/web/src/features/traces/trace-panel.tsx`:视图挂在文件药丸上方。
+- `packages/web/src/lib/format.ts`:`formatTime` 也接受毫秒时间戳,现场的记录不必绕一圈 ISO 文本才能打印自己的钟。
+
+## 测试
+
+- `packages/web/test/sse-frames.test.ts`:开关打开前不记录、关掉时清空;最近 300 条留下;超过心跳间隔的静默留下
+ 一条带时长的标记,而刚好等于间隔的那次不留;相同标记合并、帧从不合并;订阅者一直被通知到退出为止;字节数按
+ UTF-8 计算、预览有长度上限。
+- `packages/web/test/sse.test.ts`:帧从订阅处进入记录器,带着事件名、id 和字节数。
+- `packages/web/test/transport-rows.test.ts`、`packages/web/test/sse-frame-list.test.ts`:行的取舍、顺序与上限;
+ 以及渲染出来的内容 —— 默认关闭,打开后是协议自己的字眼,别的 Session 的通道不出现。
+
+## 兼容性
+
+线上协议没变、没有新依赖、Project 配置没变。它默认关闭,没打开这个开关的人看到的还是原来那块面板。这个视图
+只记录收到的那一半:服务端写了什么在浏览器这边看不见,它也不声称自己能看到。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 978b0664..6fb09e72 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -1244,7 +1244,8 @@ 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.
+6. Watch the connection against two deadlines, because two failures look different from here. A connection that receives nothing at all within 30 seconds is open but not connected: close it and reconnect with `?lastEventId=` set to the last id received (a current server answers a subscribe with its `task_state` snapshot at once, so this holds against every server version). Once the stream has spoken, 50 seconds without any event is a dead connection — but only for a stream that has sent a `ping`: silence from a server older than the heartbeat event is its normal state. Check at once when the page becomes visible, since background timers run late.
+7. After three connections in a row that opened and received not a single byte, the channel is not coming back on its own: stop reopening at once, try one fresh connection a minute, and say so on screen. A page showing live state should then keep itself current with a periodic `GET /messages` until a probe finally receives an event.
## Type Imports
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 60102a48..e04d643c 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -1244,7 +1244,8 @@ export type ServerEvent =
3. 如果响应带有 `live`(有 Task 正在运行),丢弃缓存中游标已覆盖的 partial 事件,把 `live.fragments` 应用在历史之上。进行中的消息会重新出现,已流式输出的前缀原样保留。
4. 重放缓存的事件,去掉重叠部分。
5. 之后继续处理实时流。
-6. 流发送过 `ping` 之后,50 秒内没有收到任何事件即判定连接已死:关闭它,并以查询参数 `?lastEventId=` 带上最后收到的 id 重新连接。页面重新可见时立即检查一次,因为后台的定时器会延迟执行。从不发送 `ping` 的流来自早于心跳事件的服务器,交给浏览器自带的重连处理。
+6. 按两种失败各设一个期限,因为它们从这里看不一样。30 秒内一个事件都没收到的连接是「开着但没通」:关掉它,并以查询参数 `?lastEventId=` 带上最后收到的 id 重新连接(当前服务器在订阅时立刻发 `task_state` 快照,所以这个期限对所有版本的服务器都成立)。流开过口之后,50 秒内没有收到任何事件即判定连接已死——但只对发送过 `ping` 的流成立:从不发心跳的旧服务器的安静是它的常态。页面重新可见时立即检查一次,因为后台的定时器会延迟执行。
+7. 连续三条连接都是开着却一个字节都没收到时,这条通道不会自己回来了:停止立刻重开,改成每分钟试一条新连接,并在界面上说明。此时显示实时状态的页面应当靠定时 GET `/messages` 保持内容最新,直到某次试探真的收到事件为止。
## 类型导入
diff --git a/packages/docs/content/sessions-and-traces.en.md b/packages/docs/content/sessions-and-traces.en.md
index 779d8ab5..cf4586ec 100644
--- a/packages/docs/content/sessions-and-traces.en.md
+++ b/packages/docs/content/sessions-and-traces.en.md
@@ -183,6 +183,12 @@ Both are priced by the same rule: the Project's current rates for the model, at
The approval mechanism itself is covered in [Tools & Approval](/tools).
+### The Transport view (the live frames this page received)
+
+The **Transport** toggle at the top of the Trace panel is off by default. Switched on, it records every frame this browser **actually received** on the live streams and lists them newest first: the SSE event name (`message` / `server_event` / `ping`), the id the channel gave it, its byte length and the opening of its payload — plus connection markers (`open` / `reopen` / `stalled` / `live` / `probe` / `error` / `closed`) and a `silence` marker carrying the length of any quiet stretch longer than the server's heartbeat. `user` on a row marks the `GET /api/events` stream; the rest belong to this Session.
+
+It holds the receiving half: a frame in the list proves one arrived, and its absence proves nothing about what the server wrote. That is exactly why it exists — when a conversation looks stuck, it is where "the data never arrived" is told apart from "the server never wrote". The choice is remembered in this browser (`penguin.sseFrames`), and the ring keeps the newest 300 entries.
+
### Moving Trace files across deployments
- **Export:** in a conversation's Trace panel, **Export** downloads the selected file verbatim as JSONL.
diff --git a/packages/docs/content/sessions-and-traces.zh.md b/packages/docs/content/sessions-and-traces.zh.md
index a32660ba..51583b39 100644
--- a/packages/docs/content/sessions-and-traces.zh.md
+++ b/packages/docs/content/sessions-and-traces.zh.md
@@ -183,6 +183,12 @@ Web App 的 Trace 视图和用量、成本统计都来自这份数据,不存
审批机制本身见[工具与审批](/tools)。
+### 传输视图(本页收到的实时帧)
+
+Trace 面板顶部的**传输**开关默认关闭。打开后它记录本浏览器在实时流上**实际收到**的每一帧,倒序列出:事件名(`message` / `server_event` / `ping`)、通道给的 id、字节数和载荷开头,另外还有连接标记(`open` / `reopen` / `stalled` / `live` / `probe` / `error` / `closed`)和超过心跳间隔的 `silence` 标记(带静默时长)。同一行里 `用户级` 标记的是 `GET /api/events` 那条流,其余属于本 Session。
+
+它记的是收到的那一半:能证明某一帧到过,不能证明服务端没有写过。这正是它存在的理由——对话看起来停住时,它是分辨「数据没送到」和「服务端没写」的地方。开关状态记在本浏览器(`penguin.sseFrames`),环形缓冲保留最近 300 条。
+
### 跨部署迁移 Trace 文件
- **导出:** 在对话的 Trace 面板中,**导出**会把选中的文件原样下载为 JSONL。
diff --git a/packages/web/src/api/sse-frames.ts b/packages/web/src/api/sse-frames.ts
new file mode 100644
index 00000000..3564708a
--- /dev/null
+++ b/packages/web/src/api/sse-frames.ts
@@ -0,0 +1,173 @@
+/**
+ * Browser-side record of the SSE frames this page actually RECEIVED (api/sse.ts feeds it), read
+ * by the Trace panel's Transport view. It answers the one question a silent stream raises and no
+ * other surface can: did the server write and nothing arrived, or was nothing ever written?
+ * The page holds the received half only — the server's own writes are not visible from here.
+ *
+ * Off by default, and it stays off unless the reader switches it on (the Trace panel's Transport
+ * toggle writes `penguin.sseFrames`): the ring keeps a payload's first characters, which is not
+ * something to record behind the reader's back, and the toggle is also what makes the cost
+ * bounded and deliberate rather than paid by every reader of every Session.
+ *
+ * Bounded: frames arrive at up to a few per second, so the ring keeps the recent past
+ * (SSE_FRAME_CAP) and the oldest fall out. A channel that went quiet for longer than the
+ * server's heartbeat interval leaves one `silence` marker, so "nothing arrived for 40 s" is
+ * distinguishable from "nothing was written in that time".
+ */
+/** How many entries the ring keeps; the newest win, the oldest fall out. */
+export const SSE_FRAME_CAP = 300;
+/** A quiet stretch longer than this is marked as one `silence` entry (the server's heartbeat is 20 s). */
+export const SSE_QUIET_MS = 20_000;
+/** How much of a payload's text an entry keeps. */
+export const SSE_PREVIEW_CHARS = 120;
+/** Identical consecutive lifecycle markers closer together than this are one entry (a browser retrying a dead connection repeats itself). */
+const LIFECYCLE_DEDUPE_MS = 10_000;
+
+/** The localStorage key the Transport toggle writes. */
+const STORAGE_KEY = "penguin.sseFrames";
+
+/** Which of the two subscriptions a frame came from. */
+export type SseChannel = "session" | "events";
+
+export interface SseFrameEntry {
+ /** This browser's clock at the moment of the entry. */
+ at: number;
+ /**
+ * A received frame, a connection marker (`open` / `reopen` / `probe` / `stalled` / `live` /
+ * `error` / `closed`), or one `silence` gap between frames.
+ */
+ kind: "frame" | "lifecycle" | "gap";
+ channel: SseChannel;
+ /** The Session whose channel this is; null for the user-level stream (GET /api/events). */
+ sessionId: string | null;
+ /** A frame: its SSE event name (`message`, `server_event`, `ping`). A marker: its own name. */
+ event: string;
+ id: string | null;
+ /** A frame: the payload's length in bytes. 0 for markers. */
+ bytes: number;
+ /** A frame: the payload's opening text (SSE_PREVIEW_CHARS at most). */
+ preview: string;
+ /** A `silence` entry: how long the channel had been quiet. */
+ gapMs?: number;
+}
+
+let entries: SseFrameEntry[] = [];
+let lastFrameAt = 0;
+let lastAt = 0;
+let lastKey = "";
+const listeners = new Set<() => void>();
+
+/** Bytes of a payload, counted on the payload's own encoding rather than on UTF-16 code units. */
+const encoder = new TextEncoder();
+
+/** Whether this browser is recording frames. Anything unreadable (private browsing, no storage) reads as off. */
+export function sseFramesEnabled(): boolean {
+ try {
+ return localStorage.getItem(STORAGE_KEY) === "1";
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Switches recording on or off and keeps the choice in localStorage. Turning it off drops what
+ * was collected: the ring describes the connection as it was recorded, and a frozen list left on
+ * screen would read as a stream that stopped.
+ */
+export function setSseFramesEnabled(on: boolean): void {
+ try {
+ if (on) localStorage.setItem(STORAGE_KEY, "1");
+ else localStorage.removeItem(STORAGE_KEY);
+ } catch {
+ /* best-effort persistence (private browsing, quota) — the current page still records */
+ }
+ if (!on) clearSseFrames();
+ else notify();
+}
+
+/** The recorded entries, oldest first. */
+export function sseFrames(): readonly SseFrameEntry[] {
+ return entries;
+}
+
+/** Drops every entry (the Transport view's clear button). */
+export function clearSseFrames(): void {
+ if (entries.length === 0) return;
+ entries = [];
+ lastFrameAt = 0;
+ lastAt = 0;
+ lastKey = "";
+ notify();
+}
+
+/** Called after every change to the ring; the Transport view re-renders on it. */
+export function subscribeSseFrames(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+/** A received frame's stored form: the payload's opening text and its byte length. */
+export function frameRecord(data: string): { bytes: number; preview: string } {
+ return { bytes: encoder.encode(data).length, preview: data.slice(0, SSE_PREVIEW_CHARS) };
+}
+
+/** Records one frame, connection marker or gap. A no-op while recording is off. */
+export function noteSseFrame(entry: Omit<SseFrameEntry, "at">): void {
+ if (!sseFramesEnabled()) return;
+ const at = Date.now();
+ const key = entryKey({ ...entry, at });
+ if (entry.kind === "lifecycle" && key === lastKey && at - lastAt < LIFECYCLE_DEDUPE_MS) return;
+ if (entry.kind === "frame" && lastFrameAt !== 0 && at - lastFrameAt > SSE_QUIET_MS) {
+ push({
+ at,
+ kind: "gap",
+ channel: entry.channel,
+ sessionId: entry.sessionId,
+ event: "silence",
+ id: null,
+ bytes: 0,
+ preview: "",
+ gapMs: at - lastFrameAt,
+ });
+ }
+ push({ ...entry, at });
+}
+
+function entryKey(e: SseFrameEntry): string {
+ return `${e.kind}|${e.channel}|${e.sessionId ?? ""}|${e.event}|${e.preview}`;
+}
+
+function push(e: SseFrameEntry): void {
+ entries.push(e);
+ if (entries.length > SSE_FRAME_CAP) entries = entries.slice(-SSE_FRAME_CAP);
+ lastAt = e.at;
+ lastKey = entryKey(e);
+ if (e.kind === "frame") lastFrameAt = e.at;
+ notify();
+}
+
+function notify(): void {
+ for (const listener of [...listeners]) listener();
+}
+
+/** A connection marker (`open` / `reopen` / `stalled` / …) for one channel — the shape api/sse.ts records. */
+export function lifecycleEntry(
+ channel: SseChannel,
+ sessionId: string | null,
+ event: string,
+): Omit<SseFrameEntry, "at"> {
+ return { kind: "lifecycle", channel, sessionId, event, id: null, bytes: 0, preview: "" };
+}
+
+/** A frame one channel received — the shape api/sse.ts records. */
+export function receivedEntry(
+ channel: SseChannel,
+ sessionId: string | null,
+ event: string,
+ id: string | null,
+ data: string,
+): Omit<SseFrameEntry, "at"> {
+ return { kind: "frame", channel, sessionId, event, id, ...frameRecord(data) };
+}
diff --git a/packages/web/src/api/sse.ts b/packages/web/src/api/sse.ts
index 00ef8f2e..193161c0 100644
--- a/packages/web/src/api/sse.ts
+++ b/packages/web/src/api/sse.ts
@@ -9,20 +9,41 @@
* 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.
+ * - Liveness: a connection can die without any error (half-open TCP, a stuck proxy or NAT, a
+ * middlebox that completes the handshake and then swallows the body). Two watches, because two
+ * failures look different from here: a connection that delivers nothing at all within
+ * {@link FIRST_FRAME_MS} is dead on arrival — the current server answers a subscribe with its
+ * task_state snapshot, so silence that long means the answer never got through, and the same
+ * watch covers servers of any age (an old one with no heartbeat included); once the stream has
+ * spoken, {@link SILENCE_MS} without any event closes it and opens a new one with
+ * `?lastEventId=` set to the last id seen, though only for a stream that has pinged (the
+ * server's heartbeat, every 20 s) — silence from a server that never pings is its normal state,
+ * not a symptom. Reopening is immediate, and once {@link MAX_STALLED} connections in a row have
+ * died on arrival the stream is judged STALLED: the channel is not coming back on its own, so
+ * instead of reopening every {@link FIRST_FRAME_MS} forever it is probed once a minute and the
+ * caller is told, through {@link StreamHandlers.onLiveness}, to keep itself current another way.
+ * Any event that gets through clears that verdict at once. The tab becoming visible checks
+ * immediately, since background timers run late; a connection the browser gave up on is left as
+ * it is.
+ * - Every frame received goes to api/sse-frames.ts, which records nothing until the reader turns
+ * the Trace panel's Transport view on.
* Docs: /docs/server-api § "Streaming (SSE)".
*/
import type { OmniMessage } from "@adelie/core/omnimessage";
import type { ServerEvent } from "@adelie/server/api";
import { apiUrl } from "../lib/server-context";
import { machineForSession } from "../lib/session-machines";
+import { lifecycleEntry, noteSseFrame, receivedEntry } from "./sse-frames";
+import type { SseChannel } from "./sse-frames";
/** The server pings every 20 s: this much silence means the connection is gone. */
const SILENCE_MS = 50_000;
+/** A connection that has delivered nothing at all in this long never really connected. */
+const FIRST_FRAME_MS = 30_000;
+/** This many connections in a row with nothing on them: the stream is stalled, not flaky. */
+const MAX_STALLED = 3;
+/** While stalled, how often one fresh connection is tried. */
+const STALL_REPROBE_MS = 60_000;
export interface StreamHandlers {
/**
@@ -42,27 +63,65 @@ export interface StreamHandlers {
* when false, the browser will auto-reconnect and no manual handling is needed.
*/
onError?: (closed: boolean) => void;
+ /**
+ * The stream's liveness verdict, on every change: "stalled" once several connections in a row
+ * have delivered nothing (the transport is eating the stream, so nothing this page shows will
+ * ever move on its own), "live" again the moment an event gets through — whether that is the
+ * next probe or the browser's own reconnect. A consumer that shows live state should refresh
+ * itself on a timer while stalled.
+ */
+ onLiveness?: (state: "live" | "stalled") => void;
}
export interface StreamConnection {
close: () => void;
}
-function subscribe(url: string, handlers: StreamHandlers): StreamConnection {
+function subscribe(
+ url: string,
+ channel: SseChannel,
+ sessionId: string | null,
+ handlers: StreamHandlers,
+): StreamConnection {
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;
+ /** The current connection has delivered at least one event. */
+ let gotFrame = false;
+ /** When the current connection was opened. */
+ let openedAt = 0;
+ /** Connections in a row that opened and then delivered nothing. */
+ let silentOpens = 0;
+ /** The stream is not coming back on its own: probed once a minute instead of reopened at once. */
+ let stalled = false;
let watchdog: ReturnType<typeof setTimeout> | undefined;
+ let probe: ReturnType<typeof setTimeout> | undefined;
const heard = (e: MessageEvent<string>) => {
lastHeard = Date.now();
+ gotFrame = true;
if (e.lastEventId) lastEventId = e.lastEventId;
+ if (stalled || silentOpens !== 0) {
+ stalled = false;
+ silentOpens = 0;
+ noteSseFrame(lifecycleEntry(channel, sessionId, "live"));
+ handlers.onLiveness?.("live");
+ }
+ // The frame moves the deadline: the first one retires the dead-on-arrival watch entirely
+ // (a stream that never pings has no silence window — see the module comment), a later one
+ // puts the silence window back at this moment.
+ watch();
};
- const onMessage = (e: MessageEvent<string>) => {
+ /** One frame off the wire: counted as heard, and handed to the recorder. */
+ const received = (event: string, e: MessageEvent<string>) => {
heard(e);
+ noteSseFrame(receivedEntry(channel, sessionId, event, e.lastEventId || null, e.data));
+ };
+ const onMessage = (e: MessageEvent<string>) => {
+ received("message", 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);
@@ -71,7 +130,7 @@ function subscribe(url: string, handlers: StreamHandlers): StreamConnection {
}
};
const onServerEvent = (e: MessageEvent<string>) => {
- heard(e);
+ received("server_event", e);
try {
handlers.onServerEvent(JSON.parse(e.data) as ServerEvent, e.lastEventId || null);
} catch {
@@ -79,35 +138,88 @@ function subscribe(url: string, handlers: StreamHandlers): StreamConnection {
}
};
const onPing = (e: MessageEvent<string>) => {
- heard(e);
+ received("ping", 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.
+ noteSseFrame(lifecycleEntry(channel, sessionId, closed ? "closed" : "error"));
+ // The browser gave up on the connection: what happens next is the caller's call, as before —
+ // except while the stream is stalled, where the probe is the only thing still trying and the
+ // browser retries nothing: a probe that dies like this schedules the next one.
if (closed) disarm();
+ if (closed && stalled) scheduleProbe();
handlers.onError?.(closed);
};
const connect = () => {
+ clearTimeout(watchdog);
+ clearTimeout(probe);
source?.close();
- lastHeard = Date.now();
+ openedAt = Date.now();
+ gotFrame = false;
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.onopen = () => {
+ noteSseFrame(lifecycleEntry(channel, sessionId, "open"));
+ handlers.onOpen?.();
+ };
source.onerror = onError;
+ watch();
};
- /** Reopens a stream silent for the whole window; otherwise waits out the rest of it. */
- const check = () => {
+ /** When the current connection should be judged dead (`0`: nothing worth watching yet). */
+ const dueAt = (): number => {
+ if (!gotFrame) return openedAt + FIRST_FRAME_MS;
+ if (armed) return lastHeard + SILENCE_MS;
+ return 0;
+ };
+ /** Arms the watchdog for that deadline; the timer runs late in a background tab, hence check(). */
+ const watch = () => {
+ clearTimeout(watchdog);
+ const due = dueAt();
+ if (due !== 0) watchdog = setTimeout(fire, Math.max(0, due - Date.now()));
+ };
+ /** The deadline is up: this connection is dead — silent from the start, or silent past the window. */
+ const fire = () => {
+ clearTimeout(watchdog);
+ if (!gotFrame) {
+ silentOpens += 1;
+ if (silentOpens >= MAX_STALLED) return stall();
+ } else {
+ noteSseFrame(lifecycleEntry(channel, sessionId, "reopen"));
+ }
+ connect();
+ };
+ /** One fresh connection after the probe interval, recorded as a probe (`connect` clears the timer). */
+ const scheduleProbe = () => {
+ clearTimeout(probe);
+ probe = setTimeout(() => {
+ noteSseFrame(lifecycleEntry(channel, sessionId, "probe"));
+ connect();
+ }, STALL_REPROBE_MS);
+ };
+ /** Nothing is coming through: stop reopening at once, probe once a minute, and say so. */
+ const stall = () => {
clearTimeout(watchdog);
- if (!armed) return;
- if (Date.now() - lastHeard >= SILENCE_MS) connect();
- watchdog = setTimeout(check, lastHeard + SILENCE_MS - Date.now());
+ source?.close();
+ if (!stalled) {
+ stalled = true;
+ noteSseFrame(lifecycleEntry(channel, sessionId, "stalled"));
+ handlers.onLiveness?.("stalled");
+ }
+ scheduleProbe();
+ };
+ /** Reopens immediately if the deadline has already passed (a late timer, or a tab just shown). */
+ const check = () => {
+ if (stalled) return; // the probe timer owns the cadence
+ const due = dueAt();
+ if (due !== 0 && Date.now() >= due) return fire();
+ watch();
};
const disarm = () => {
armed = false;
@@ -122,6 +234,7 @@ function subscribe(url: string, handlers: StreamHandlers): StreamConnection {
return {
close: () => {
disarm();
+ clearTimeout(probe);
document.removeEventListener("visibilitychange", onVisibility);
source?.close();
},
@@ -132,7 +245,7 @@ function subscribe(url: string, handlers: StreamHandlers): StreamConnection {
export function openSessionStream(sessionId: string, handlers: StreamHandlers): StreamConnection {
// Routed like every other Session call: the stream comes from the machine running it.
const path = `/api/sessions/${encodeURIComponent(sessionId)}/stream`;
- return subscribe(apiUrl(path, machineForSession(sessionId)), handlers);
+ return subscribe(apiUrl(path, machineForSession(sessionId)), "session", sessionId, handlers);
}
/**
@@ -145,5 +258,5 @@ export function openUserEvents(
handlers: StreamHandlers,
machineId: string | null = null,
): StreamConnection {
- return subscribe(apiUrl("/api/events", machineId), handlers);
+ return subscribe(apiUrl("/api/events", machineId), "events", null, handlers);
}
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index 857b8130..d7d25256 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -135,6 +135,7 @@ import type { CostStatDisplay } from "./header-stats";
import { buildInputHistory } from "./input-history";
import { buildOutline } from "./outline-model";
import { GoalStatusBanner } from "./goal-banner";
+import { StreamStalledBanner } from "./stream-stalled-banner";
import { handoffMessage, modelSwitchMessage } from "./agent-handoff";
import { modelLabel } from "./model-select";
import { sessionModelPickerDisabled, sessionRowStale, switchContextShape } from "./model-switch";
@@ -2790,6 +2791,10 @@ export function ChatPage() {
className="shrink-0 border-t border-gray-200 bg-canvas px-3 pb-[calc(0.75rem+env(safe-area-inset-bottom))] pt-3 md:pb-3 dark:border-gray-800"
>
<div className="mx-auto max-w-3xl">
+ {/* Stalled stream (the live connection delivers nothing, so the page
+ refetches on a timer): the reader is told why the conversation
+ may lag, and it clears itself once an event gets through again. */}
+ {stream.streamStalled && <StreamStalledBanner />}
{/* Goal banner docked above the composer: an in-flight goal's progress
(restored on load while still active), or the terminal state reached
during this page's lifetime. The stop button is the composer's
diff --git a/packages/web/src/features/chat/stream-stalled-banner.tsx b/packages/web/src/features/chat/stream-stalled-banner.tsx
new file mode 100644
index 00000000..b548e966
--- /dev/null
+++ b/packages/web/src/features/chat/stream-stalled-banner.tsx
@@ -0,0 +1,30 @@
+/**
+ * The stalled-stream strip above the composer: the live stream has stopped delivering — several
+ * connections in a row received nothing at all, which is what a proxy or NAT swallowing the
+ * response body looks like from here (api/sse.ts owns the verdict) — so this page keeps the
+ * conversation current by refetching it on a timer.
+ *
+ * Without the strip that failure is invisible AND misleading: the Task is running on the server,
+ * the reply is being written, and the page simply never shows any of it, which reads as a hung
+ * agent rather than a broken connection.
+ *
+ * It says what the page is doing rather than what broke. The connection comes back on its own —
+ * the stream is probed once a minute — and the strip clears itself the moment a probe gets an
+ * event through; reloading is the reader's way out before that.
+ */
+import { GlyphIcon, ICONS, NoticeStrip } from "@adelie/ui";
+import { S } from "../../lib/strings";
+
+export function StreamStalledBanner() {
+ return (
+ <NoticeStrip
+ tone="attention"
+ className="anim-fade mb-2 flex items-center gap-2 rounded-md border px-3 py-2 text-xs"
+ >
+ <span data-slot="icon" className="shrink-0">
+ <GlyphIcon d={ICONS.rotateCw} size={14} />
+ </span>
+ <span className="min-w-0 flex-1 truncate">{S.chat.streamStalled}</span>
+ </NoticeStrip>
+ );
+}
diff --git a/packages/web/src/features/chat/use-session-stream.ts b/packages/web/src/features/chat/use-session-stream.ts
index 90f9d11b..e66635d0 100644
--- a/packages/web/src/features/chat/use-session-stream.ts
+++ b/packages/web/src/features/chat/use-session-stream.ts
@@ -9,7 +9,8 @@
* 3. Disconnects are auto-reconnected by the browser (Last-Event-ID built in; server replays from
* 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;
+ * connection; a stream api/sse.ts judges STALLED (nothing arrives at all — a proxy eating the
+ * body) is refreshed on a timer instead, so the conversation keeps moving without it;
* 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
* area state and the Session list badge;
@@ -42,6 +43,9 @@ export type { OlderHistoryState, PendingApproval } from "../../lib/omni/stream-c
/** Minimum spacing between version commits: below one frame at 8fps, invisible as staleness, but ~8× fewer full re-parses of the growing message during a fast large-code stream. */
const BUMP_MIN_INTERVAL_MS = 120;
+/** How often a stall-refreshing page refetches the transcript while the live stream is not delivering (api/sse.ts reports the verdict). */
+const STALL_REFRESH_MS = 6_000;
+
export interface SessionStreamState {
/**
* The Session everything below describes (null: none, a draft). It trails the `sessionId`
@@ -89,6 +93,13 @@ export interface SessionStreamState {
markLocalDecision: (toolCallId: string) => void;
/** Removed from the pending table immediately after this client submits a decision (optimistic update; keyed by approvalKey). */
resolveApproval: (key: string) => void;
+ /**
+ * The live stream is not delivering (several connections in a row received nothing — see
+ * api/sse.ts), so this page refreshes the transcript on a timer instead of waiting for
+ * events that are not coming. Drives the strip above the composer; the composition is
+ * unchanged, and the window is short enough that a running Task still reads as running.
+ */
+ streamStalled: boolean;
/** History load failure message (paired with retry to show a retry entry point). */
error: string | null;
/** Re-fetch history (only meaningful after a load failure). */
@@ -124,6 +135,7 @@ export function useSessionStream(
const [subagents, setSubagents] = useState<SubagentRuntimeInfo[]>([]);
const [error, setError] = useState<string | null>(null);
const [pendingTick, setPendingTick] = useState(0);
+ const [streamStalled, setStreamStalled] = useState(false);
const [goal, setGoal] = useState<GoalBannerState | null>(null);
const [describes, setDescribes] = useState<string | null>(sessionId);
@@ -207,6 +219,7 @@ export function useSessionStream(
setSubagents([]);
setLoading(false);
setError(null);
+ setStreamStalled(false);
setGoal(null);
setPendingTick((t) => t + 1);
setVersion((v) => v + 1);
@@ -225,6 +238,7 @@ export function useSessionStream(
setReturnedSteering([]);
setPendingFollowUps([]);
setSubagents([]);
+ setStreamStalled(false);
setPendingTick((t) => t + 1);
// Restore an in-flight goal's banner (only when still active — a long-finished goal
@@ -266,10 +280,36 @@ export function useSessionStream(
});
controllerRef.current = controller;
+ // While the stream is stalled this page is its own source of truth: nothing will arrive on
+ // the connection, so the transcript is refetched on a timer. A refresh keeps the pending
+ // approvals and never blanks what is on screen, and the controller refuses one while
+ // another is in flight — so a tick landing on a slow fetch costs nothing, and re-entry needs
+ // no guard here. Background tabs have their timers throttled by the browser, which bounds
+ // what an unwatched page spends on this.
+ let poll: number | undefined;
+ const stopPolling = () => {
+ if (poll === undefined) return;
+ window.clearInterval(poll);
+ poll = undefined;
+ };
+ const pollWhileStalled = () => {
+ if (poll !== undefined) return;
+ void controller.refresh();
+ poll = window.setInterval(() => void controller.refresh(), STALL_REFRESH_MS);
+ };
+
// Connect-first: subscribe to the stream before fetching history.
const conn = openSessionStream(sessionId, {
onOmniMessage: controller.handleOmni,
onServerEvent: controller.handleServer,
+ // The connection's liveness verdict drives the strip and the refresh timer above: they
+ // start together the moment the stream is judged dead, and stop the moment it delivers
+ // an event again.
+ onLiveness: (state) => {
+ setStreamStalled(state === "stalled");
+ if (state === "stalled") pollWhileStalled();
+ else stopPolling();
+ },
// Hydrate the goal banner only once the subscription is live (fires on first connect and
// every reconnect); the prev/active guards keep it from clobbering a live banner.
onOpen: hydrateGoal,
@@ -283,6 +323,7 @@ export function useSessionStream(
return () => {
goalFetchStale = true;
+ stopPolling();
controller.dispose();
conn.close();
if (rafRef.current !== null) {
@@ -337,6 +378,7 @@ export function useSessionStream(
pendingApprovals: controllerRef.current?.pendingApprovals ?? EMPTY_PENDING,
markLocalDecision,
resolveApproval,
+ streamStalled,
error,
retry,
goal,
diff --git a/packages/web/src/features/traces/sse-frame-list.tsx b/packages/web/src/features/traces/sse-frame-list.tsx
new file mode 100644
index 00000000..2c412024
--- /dev/null
+++ b/packages/web/src/features/traces/sse-frame-list.tsx
@@ -0,0 +1,128 @@
+/**
+ * The Trace panel's Transport view: the SSE frames this browser actually received, newest first,
+ * behind a toggle that is OFF by default (see api/sse-frames.ts — it stores payload prefixes, so
+ * it is the reader's call, and the state is remembered in localStorage).
+ *
+ * Its question is the one nothing else on screen can answer: the live stream went quiet — did
+ * data ever arrive, and what was in it? A row is one frame off the wire (its SSE event name, its
+ * id, its byte length, the opening of its payload), one connection marker (`open`, `reopen`,
+ * `stalled`, `live`, `probe`, `error`, `closed`), or one `silence` marker for a stretch longer
+ * than the server's heartbeat. Reading down it separates the two failures a quiet conversation
+ * has: nothing arriving (frames are missing) from nothing being written (frames are there).
+ *
+ * It shows the receiving side only. What the server wrote is not visible from here — a page can
+ * prove that a frame arrived, never that one was never sent.
+ *
+ * Live while it shows: frames land as the run streams, so the list re-renders on the recorder's
+ * own notifications. A hidden dock tab (or a turned-off toggle) records nothing to the screen and
+ * subscribes to nothing.
+ */
+import { useEffect, useReducer, useState } from "react";
+import { formatBytes, humanizeDuration } from "../../lib/format";
+import { S } from "../../lib/strings";
+import {
+ clearSseFrames,
+ setSseFramesEnabled,
+ sseFrames,
+ sseFramesEnabled,
+ subscribeSseFrames,
+} from "../../api/sse-frames";
+import { formatFrameTime, transportRows } from "./transport-rows";
+
+/** The pill both the file row and this toggle wear. */
+const PILL_CLASS = "rounded-md border px-2 py-0.5 font-mono text-xs transition-colors duration-150";
+
+export function SseFrameList({ sessionId, active }: { sessionId: string; active: boolean }) {
+ const [enabled, setEnabled] = useState(sseFramesEnabled);
+ const [, bump] = useReducer((v: number) => v + 1, 0);
+
+ // The recorder reports every change; only a showing panel listens, so a hidden tab pays
+ // nothing per frame.
+ useEffect(() => {
+ if (!enabled || !active) return;
+ return subscribeSseFrames(bump);
+ }, [enabled, active]);
+
+ const rows = enabled ? transportRows(sseFrames(), sessionId) : [];
+
+ const toggle = () => {
+ const next = !enabled;
+ setSseFramesEnabled(next);
+ setEnabled(next);
+ };
+
+ return (
+ <div className="rounded-md border border-gray-200 dark:border-gray-800">
+ <div className="flex items-center gap-2 px-2.5 py-1.5">
+ <span className="shrink-0 text-xs text-gray-400">{S.tracePanel.transport}</span>
+ <button
+ type="button"
+ aria-pressed={enabled}
+ onClick={toggle}
+ className={`${PILL_CLASS} ${
+ enabled
+ ? "border-gray-400 bg-gray-200/70 font-semibold text-gray-900 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100"
+ : "border-gray-200 text-gray-500 hover:bg-gray-100 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/60"
+ }`}
+ >
+ {enabled ? S.tracePanel.transportOn : S.tracePanel.transportOff}
+ </button>
+ {enabled && (
+ <span className="min-w-0 flex-1 truncate text-xs text-gray-400">
+ {S.tracePanel.transportCount(rows.length)}
+ </span>
+ )}
+ {enabled && rows.length > 0 && (
+ <button
+ type="button"
+ onClick={() => clearSseFrames()}
+ className={`${PILL_CLASS} border-gray-200 text-gray-500 hover:bg-gray-100 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/60`}
+ >
+ {S.tracePanel.transportClear}
+ </button>
+ )}
+ </div>
+ {!enabled && (
+ <p className="px-2.5 pb-1.5 text-xs text-gray-400">{S.tracePanel.transportHint}</p>
+ )}
+ {enabled && rows.length === 0 && (
+ <p className="px-2.5 pb-1.5 text-xs text-gray-400">{S.tracePanel.transportEmpty}</p>
+ )}
+ {enabled && rows.length > 0 && (
+ <ul className="max-h-64 overflow-y-auto border-t border-gray-100 dark:border-gray-800/60">
+ {rows.map((f, i) => (
+ <li
+ key={`${f.at}-${i}`}
+ className="flex items-baseline gap-2 px-2.5 py-1 font-mono text-xs"
+ >
+ <span className="shrink-0 text-gray-400">{formatFrameTime(f.at)}</span>
+ {/* Which of the two streams this row came off: the Session's own (unmarked) or the
+ page's user-level one, which carries no Session (see transport-rows.ts). */}
+ {f.sessionId === null && (
+ <span className="shrink-0 text-gray-400">{S.tracePanel.transportChannel}</span>
+ )}
+ <span
+ className={`shrink-0 ${
+ f.kind === "frame" ? "text-gray-700 dark:text-gray-300" : "text-gray-400"
+ }`}
+ >
+ {f.kind === "gap"
+ ? S.tracePanel.transportSilence(humanizeDuration(f.gapMs ?? 0))
+ : f.event}
+ </span>
+ {/* The channel's own id (`<epoch>-<seq>`): what a reconnect resumes from, and
+ what a gap in the sequence shows up as. */}
+ {f.id !== null && <span className="shrink-0 text-gray-400">{f.id}</span>}
+ {f.kind === "frame" && (
+ <span className="shrink-0 text-gray-400">{formatBytes(f.bytes)}</span>
+ )}
+ <span className="min-w-0 flex-1 truncate text-gray-500 dark:text-gray-400">
+ {f.preview}
+ </span>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ );
+}
diff --git a/packages/web/src/features/traces/trace-panel.tsx b/packages/web/src/features/traces/trace-panel.tsx
index 568fa162..8357be9c 100644
--- a/packages/web/src/features/traces/trace-panel.tsx
+++ b/packages/web/src/features/traces/trace-panel.tsx
@@ -21,6 +21,7 @@ import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { formatBytes } from "../../lib/format";
import { TraceFileView } from "./trace-file-view";
+import { SseFrameList } from "./sse-frame-list";
import {
activeTraceFile,
advanceTraceRefresh,
@@ -142,6 +143,9 @@ export function TracePanel({
{S.tracePanel.loadFailed} · {error}
</NoticeStrip>
)}
+ {/* What this browser received on the live streams (off unless switched on): the one
+ place a stalled stream can be told from a quiet one. */}
+ <SseFrameList sessionId={session.sessionId} active={active} />
<div className="flex flex-wrap items-center gap-1.5">
<span className="mr-1 text-xs text-gray-400">{S.traces.filesTitle}</span>
{visibleFiles.map((f) => (
diff --git a/packages/web/src/features/traces/transport-rows.ts b/packages/web/src/features/traces/transport-rows.ts
new file mode 100644
index 00000000..056ddc30
--- /dev/null
+++ b/packages/web/src/features/traces/transport-rows.ts
@@ -0,0 +1,39 @@
+/**
+ * The Transport view's rows (the component in sse-frame-list.tsx): which of the recorded frames
+ * belong in this Session's panel, in which order, and how a frame's clock reads.
+ *
+ * Two channels belong here. The Session's own stream is the point of the view. The page's
+ * user-level stream (GET /api/events — the one that carries session_created and the like) is kept
+ * as well and marked as such: it is the same page and the same failure, and someone diagnosing a
+ * silent stream needs to know which of the two was quiet. Every other Session's channel is
+ * dropped — the panel is about this conversation.
+ *
+ * Newest first, because the reader is looking for the frame that just arrived, or for the fact
+ * that none did, and capped: a long run holds hundreds of frames, and the ring's own cap is the
+ * record where the list is only a window.
+ */
+import { formatTime } from "../../lib/format";
+import type { SseFrameEntry } from "../../api/sse-frames";
+
+/** How many rows the list renders — the newest; the ring keeps the rest. */
+export const FRAME_ROW_CAP = 120;
+
+/** This Session's frames and the page's own user-level ones, newest first, capped to the newest `cap`. */
+export function transportRows(
+ entries: readonly SseFrameEntry[],
+ sessionId: string,
+ cap: number = FRAME_ROW_CAP,
+): SseFrameEntry[] {
+ return entries
+ .filter((e) => e.sessionId === sessionId || e.sessionId === null)
+ .slice(-cap)
+ .reverse();
+}
+
+/**
+ * A row's clock: `HH:mm:ss.SSS`. Frames land tens of milliseconds apart while a reply streams,
+ * so whole seconds would leave a run of rows that cannot be ordered.
+ */
+export function formatFrameTime(at: number): string {
+ return `${formatTime(at)}.${String(new Date(at).getMilliseconds()).padStart(3, "0")}`;
+}
diff --git a/packages/web/src/lib/format.ts b/packages/web/src/lib/format.ts
index 16c4b11a..67b66705 100644
--- a/packages/web/src/lib/format.ts
+++ b/packages/web/src/lib/format.ts
@@ -304,9 +304,13 @@ export function formatRelativeShort(iso: string, locale: "zh" | "en"): string {
return formatMonthDay(localYmd(d), locale);
}
-/** ISO timestamp → local `HH:mm:ss` (inline display in the Trace timeline); returns the input unchanged if parsing fails. */
-export function formatTime(iso: string): string {
- const d = new Date(iso);
- if (Number.isNaN(d.getTime())) return iso;
+/**
+ * ISO timestamp (or epoch milliseconds) → local `HH:mm:ss` (inline display in the Trace timeline
+ * and the Transport view); a number is accepted so a live record's own clock can be printed
+ * without a round trip through ISO text.
+ */
+export function formatTime(when: string | number): string {
+ const d = new Date(when);
+ if (Number.isNaN(d.getTime())) return String(when);
return `${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`;
}
diff --git a/packages/web/src/lib/install-scope.ts b/packages/web/src/lib/install-scope.ts
index a5462ed5..c8b8f27f 100644
--- a/packages/web/src/lib/install-scope.ts
+++ b/packages/web/src/lib/install-scope.ts
@@ -143,6 +143,12 @@ export const KEY_RULES: readonly KeyRule[] = [
scope: "browser",
why: "Whether tool cards name the built-in tools by their short alias; a display choice of this browser, naming nothing on the server.",
},
+ {
+ kind: "exact",
+ key: "penguin.sseFrames",
+ scope: "browser",
+ why: "Whether the Trace panel's Transport view records SSE frames; a debugging instrument of this browser, naming nothing on the server.",
+ },
{
kind: "exact",
key: "penguin.terminal.theme",
diff --git a/packages/web/src/lib/omni/stream-controller.ts b/packages/web/src/lib/omni/stream-controller.ts
index f099321f..465cc97d 100644
--- a/packages/web/src/lib/omni/stream-controller.ts
+++ b/packages/web/src/lib/omni/stream-controller.ts
@@ -177,6 +177,14 @@ export interface StreamController {
load: () => Promise<void>;
/** Retry entry point after a history load failure (keeps the buffer, refetches history). */
retry: () => Promise<void>;
+ /**
+ * Refetch the transcript in place, keeping the pending-approvals table — the resync rebuild
+ * clears it, where a refresh is not a resync: an approval on screen has to stay answerable.
+ * The entry point for a page that keeps itself current on a timer while the live stream is
+ * stalled (see api/sse.ts), and therefore a no-op while a load is in flight, after a failed
+ * one, and once disposed: a caller may fire it on a timer without checking anything.
+ */
+ refresh: () => Promise<void>;
/** Prepend the previous window (scroll-up backfill); no-op while loading, failed, at the beginning, or before the initial load settled. */
loadOlder: () => Promise<void>;
/** SSE OmniMessage entry point (`eventId`: the SSE event id, used for live-tail cursor alignment). */
@@ -370,14 +378,16 @@ export function createStreamController(deps: StreamControllerDeps): StreamContro
* The decision runs inside load() (it needs the response); this entry only picks the
* request shape.
*/
- const rebuild = async (): Promise<void> => {
+ const rebuild = async (keepPending = false): Promise<void> => {
epoch += 1;
phase = "buffering";
buffer = [];
// Clear the pending-approvals table: an approval decided while
// disconnected shouldn't leave a lingering button; the server will
// resend still-pending approval_request events on the same connection afterward, naturally rebuilding it.
- clearPending();
+ // A refresh (keepPending) skips this: it is not a resync, nothing is resent, and a lone
+ // still-pending approval would simply disappear from the screen.
+ if (!keepPending) clearPending();
// Atomic swap — deliberately NOT `onLoading(true)`. The fresh model (shared localDecisions
// injected, so approvals decided on this end stay labeled "manual") is handed to load(), which
// makes it the visible model only once history is back in hand. Until then the OLD transcript
@@ -605,6 +615,10 @@ export function createStreamController(deps: StreamControllerDeps): StreamContro
page: { kind: "tail", limit: TAIL_UNITS },
});
},
+ refresh: async () => {
+ if (disposed || failed || phase !== "live") return;
+ await rebuild(true);
+ },
loadOlder,
handleOmni: (msg, eventId = null) => {
if (disposed) return;
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 657d97fe..c5f949ea 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -371,6 +371,22 @@ export const en: Strings = {
empty: "No traces yet",
emptyHint: "This session has not produced a Trace file yet",
loadFailed: "Failed to load traces",
+ /**
+ * The Transport view (features/traces/sse-frame-list.tsx): the SSE frames this browser
+ * actually received. `transportHint` says what turning it on does; the frame's own names
+ * (`open` / `ping` / `server_event` / `silence` …) are the protocol's words and stay as they
+ * are.
+ */
+ transport: "Transport",
+ transportOn: "Recording",
+ transportOff: "Off",
+ transportHint:
+ "Records the live frames this browser actually received, so a stalled stream can be read as data that never arrived rather than a server that never wrote.",
+ transportCount: (n: number) => `Last ${n} frames, newest first`,
+ transportEmpty: "No frames received yet",
+ transportClear: "Clear",
+ transportChannel: "user",
+ transportSilence: (gap: string) => `silent ${gap}`,
},
settings: {
@@ -3745,6 +3761,13 @@ export const en: Strings = {
sessionOnOfflineMachineUnknown:
"This conversation is on a machine that is not connected right now.",
sessionOfflineHint: "It will open as soon as the connection is back.",
+ /**
+ * The stalled-stream strip above the composer (features/chat/stream-stalled-banner.tsx):
+ * the live stream is not delivering, so the page refetches the conversation on a timer.
+ * It names what the page is doing, not which layer failed — the reader's question is
+ * whether the conversation still works.
+ */
+ streamStalled: "The live connection dropped — refreshing on a timer",
emptyStream: "Send a message to start the conversation",
historyLoadFailed: "Failed to load history",
statsLabel: "Stats",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 52392898..4e3301f5 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -441,6 +441,22 @@ export const zh = {
empty: "暂无轨迹",
emptyHint: "该会话还没有产生 Trace 文件",
loadFailed: "轨迹加载失败",
+ /**
+ * The Transport view (features/traces/sse-frame-list.tsx): the SSE frames this browser
+ * actually received. `transportHint` says what turning it on does; the frame's own names
+ * (`open` / `ping` / `server_event` / `silence` …) are the protocol's words and stay as they
+ * are.
+ */
+ transport: "传输",
+ transportOn: "记录中",
+ transportOff: "已关闭",
+ transportHint:
+ "打开后记录本浏览器实际收到的实时帧:实时流停了时,用它看是数据没送到,还是服务端没写。",
+ transportCount: (n: number) => `最近 ${n} 帧,新的在上`,
+ transportEmpty: "还没有收到帧",
+ transportClear: "清空",
+ transportChannel: "用户级",
+ transportSilence: (gap: string) => `静默 ${gap}`,
},
settings: {
@@ -3830,6 +3846,13 @@ export const zh = {
sessionOnOfflineMachine: (machine: string) => `这个对话在 ${machine} 上,当前没有连接。`,
sessionOnOfflineMachineUnknown: "这个对话在某台机器上,当前没有连接。",
sessionOfflineHint: "连接恢复后会自动打开。",
+ /**
+ * The stalled-stream strip above the composer (features/chat/stream-stalled-banner.tsx):
+ * the live stream is not delivering, so the page refetches the conversation on a timer.
+ * It names what the page is doing, not which layer failed — the reader's question is
+ * whether the conversation still works.
+ */
+ streamStalled: "实时连接已断开,正在定时刷新",
emptyStream: "发送一条消息开始对话",
historyLoadFailed: "历史消息加载失败",
statsLabel: "统计信息",
diff --git a/packages/web/test/sse-frame-list.test.ts b/packages/web/test/sse-frame-list.test.ts
new file mode 100644
index 00000000..0f37cbcc
--- /dev/null
+++ b/packages/web/test/sse-frame-list.test.ts
@@ -0,0 +1,62 @@
+/**
+ * The Transport view's markup (features/traces/sse-frame-list.tsx): off by default, and what a
+ * reader gets once it is on — the recorded frames, newest first, in the wire's own words, with
+ * another Session's channel kept out.
+ */
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import {
+ clearSseFrames,
+ noteSseFrame,
+ receivedEntry,
+ setSseFramesEnabled,
+} from "../src/api/sse-frames";
+import { SseFrameList } from "../src/features/traces/sse-frame-list";
+import { S } from "../src/lib/strings";
+
+function memoryStorage(): Storage {
+ const map = new Map<string, string>();
+ return {
+ getItem: (key: string) => map.get(key) ?? null,
+ setItem: (key: string, value: string) => void map.set(key, value),
+ removeItem: (key: string) => void map.delete(key),
+ } as unknown as Storage;
+}
+
+beforeEach(() => {
+ vi.stubGlobal("localStorage", memoryStorage());
+});
+
+afterEach(() => {
+ clearSseFrames();
+});
+
+const render = (sessionId = "s1") =>
+ renderToStaticMarkup(createElement(SseFrameList, { sessionId, active: true }));
+
+it("starts off, saying what turning it on would do", () => {
+ noteSseFrame(receivedEntry("session", "s1", "ping", null, "{}"));
+ const html = render();
+ expect(html).toContain(S.tracePanel.transportOff);
+ expect(html).toContain(S.tracePanel.transportHint);
+ expect(html).not.toContain(S.tracePanel.transportCount(1));
+});
+
+it("lists the recorded frames newest first, and leaves another Session's channel out", () => {
+ setSseFramesEnabled(true);
+ noteSseFrame(receivedEntry("session", "s1", "ping", "e-1", "{}"));
+ noteSseFrame(receivedEntry("session", "s2", "server_event", "e-2", '{"other":1}'));
+ noteSseFrame(receivedEntry("session", "s1", "server_event", "e-3", '{"type":"task_state"}'));
+ noteSseFrame(receivedEntry("events", null, "server_event", "e-4", '{"type":"hello"}'));
+
+ const html = render();
+ expect(html).toContain(S.tracePanel.transportOn);
+ expect(html).toContain(S.tracePanel.transportCount(3));
+ expect(html).toContain("e-3");
+ expect(html).not.toContain("other");
+ expect(html).toContain(S.tracePanel.transportChannel);
+ // Newest first: the last frame recorded is the first row rendered.
+ expect(html.indexOf("hello")).toBeLessThan(html.indexOf("task_state"));
+ expect(html.indexOf("task_state")).toBeLessThan(html.indexOf("ping"));
+});
diff --git a/packages/web/test/sse-frames.test.ts b/packages/web/test/sse-frames.test.ts
new file mode 100644
index 00000000..13a1a707
--- /dev/null
+++ b/packages/web/test/sse-frames.test.ts
@@ -0,0 +1,143 @@
+/**
+ * The SSE frame ring (api/sse-frames.ts), the Trace panel's Transport view's source:
+ *
+ * - recording is off until the toggle turns it on, and turning it off drops what was collected
+ * (a frozen list would read as a stream that stopped);
+ * - the ring keeps the newest SSE_FRAME_CAP entries and lets the oldest fall out;
+ * - a quiet stretch longer than the heartbeat leaves ONE `silence` marker carrying its length —
+ * at the interval exactly, nothing is marked;
+ * - identical consecutive connection markers close together are one entry, or a browser
+ * retrying a dead connection would flush the ring; frames are never collapsed;
+ * - a channel is recorded with its own name (`events` carries no Session: it is the user-level
+ * stream), and every change notifies the subscribers until they unsubscribe;
+ * - a payload's byte length is counted on its UTF-8 encoding, its preview capped.
+ */
+import { beforeEach, expect, it, vi } from "vitest";
+import {
+ SSE_FRAME_CAP,
+ SSE_PREVIEW_CHARS,
+ SSE_QUIET_MS,
+ clearSseFrames,
+ frameRecord,
+ lifecycleEntry,
+ noteSseFrame,
+ receivedEntry,
+ setSseFramesEnabled,
+ sseFrames,
+ sseFramesEnabled,
+ subscribeSseFrames,
+} from "../src/api/sse-frames";
+
+const T0 = 1_700_000_000_000;
+
+function memoryStorage(): Storage {
+ const map = new Map<string, string>();
+ return {
+ getItem: (key: string) => map.get(key) ?? null,
+ setItem: (key: string, value: string) => void map.set(key, value),
+ removeItem: (key: string) => void map.delete(key),
+ } as unknown as Storage;
+}
+
+beforeEach(() => {
+ vi.stubGlobal("localStorage", memoryStorage());
+ vi.useFakeTimers();
+ vi.setSystemTime(T0);
+ clearSseFrames();
+});
+
+const frame = (id: string | null = null) =>
+ receivedEntry("session", "s1", "ping", id, JSON.stringify({ type: "task_state" }));
+
+it("records nothing until the toggle is on, and drops the ring when it goes off", () => {
+ expect(sseFramesEnabled()).toBe(false);
+ noteSseFrame(frame());
+ expect(sseFrames()).toEqual([]);
+
+ setSseFramesEnabled(true);
+ expect(sseFramesEnabled()).toBe(true);
+ noteSseFrame(frame());
+ expect(sseFrames()).toHaveLength(1);
+
+ setSseFramesEnabled(false);
+ expect(sseFramesEnabled()).toBe(false);
+ expect(sseFrames()).toEqual([]);
+});
+
+it("keeps the newest cap's worth, dropping the oldest", () => {
+ setSseFramesEnabled(true);
+ for (let i = 0; i < SSE_FRAME_CAP + 10; i++) noteSseFrame(frame(`e-${i}`));
+ const frames = sseFrames();
+ expect(frames).toHaveLength(SSE_FRAME_CAP);
+ expect(frames[0]!.id).toBe("e-10");
+ expect(frames.at(-1)!.id).toBe(`e-${SSE_FRAME_CAP + 9}`);
+});
+
+it("marks a quiet stretch past the heartbeat as one silence entry, and one at the interval as none", () => {
+ setSseFramesEnabled(true);
+ noteSseFrame(frame("e-1"));
+ vi.setSystemTime(T0 + SSE_QUIET_MS);
+ noteSseFrame(frame("e-2"));
+ expect(sseFrames()).toHaveLength(2);
+
+ vi.setSystemTime(T0 + SSE_QUIET_MS * 2 + 1);
+ noteSseFrame(frame("e-3"));
+ const frames = sseFrames();
+ expect(frames).toHaveLength(4);
+ expect(frames[2]).toMatchObject({
+ kind: "gap",
+ event: "silence",
+ channel: "session",
+ sessionId: "s1",
+ gapMs: SSE_QUIET_MS + 1,
+ bytes: 0,
+ });
+ // The marker carries the gap, not a frame: the ring's own frame clock moves on with e-3.
+ vi.setSystemTime(T0 + SSE_QUIET_MS * 2 + 2);
+ noteSseFrame(frame("e-4"));
+ expect(sseFrames()).toHaveLength(5);
+});
+
+it("collapses identical consecutive markers, and never frames", () => {
+ setSseFramesEnabled(true);
+ noteSseFrame(lifecycleEntry("session", "s1", "error"));
+ vi.setSystemTime(T0 + 3_000);
+ noteSseFrame(lifecycleEntry("session", "s1", "error"));
+ expect(sseFrames()).toHaveLength(1);
+
+ // A different marker is its own entry, and so is the same one past the collapse window.
+ noteSseFrame(lifecycleEntry("session", "s1", "open"));
+ vi.setSystemTime(T0 + 20_000);
+ noteSseFrame(lifecycleEntry("session", "s1", "error"));
+ expect(sseFrames().map((f) => f.event)).toEqual(["error", "open", "error"]);
+
+ noteSseFrame(frame());
+ noteSseFrame(frame());
+ expect(sseFrames()).toHaveLength(5);
+});
+
+it("records the user-level stream without a Session, and notifies subscribers until they leave", () => {
+ setSseFramesEnabled(true);
+ const first = vi.fn();
+ const second = vi.fn();
+ const leaveFirst = subscribeSseFrames(first);
+ const leaveSecond = subscribeSseFrames(second);
+
+ noteSseFrame(receivedEntry("events", null, "server_event", null, "{}"));
+ expect(sseFrames()[0]).toMatchObject({ channel: "events", sessionId: null });
+ expect(first).toHaveBeenCalledTimes(1);
+ expect(second).toHaveBeenCalledTimes(1);
+
+ leaveFirst();
+ noteSseFrame(frame());
+ expect(first).toHaveBeenCalledTimes(1);
+ expect(second).toHaveBeenCalledTimes(2);
+ leaveSecond();
+});
+
+it("counts a payload's bytes on its UTF-8 encoding and caps its preview", () => {
+ expect(frameRecord("中文")).toEqual({ bytes: 6, preview: "中文" });
+ const long = "x".repeat(SSE_PREVIEW_CHARS + 50);
+ expect(frameRecord(long).preview).toHaveLength(SSE_PREVIEW_CHARS);
+ expect(frameRecord(long).bytes).toBe(SSE_PREVIEW_CHARS + 50);
+});
diff --git a/packages/web/test/sse.test.ts b/packages/web/test/sse.test.ts
index 30a6fa15..5172ebba 100644
--- a/packages/web/test/sse.test.ts
+++ b/packages/web/test/sse.test.ts
@@ -7,16 +7,25 @@
* - 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.
+ * - Given a stream that spoke but never pinged (a server older than the heartbeat), nothing
+ * reopens it: no silence window applies to it, and its first frame retired the
+ * dead-on-arrival watch.
+ * - Given a connection that delivers nothing at all, it is reopened at the deadline, and after
+ * three in a row the stream is judged stalled: no connection is held open, the caller is told
+ * once, and one fresh connection is tried a minute later; a frame on a probe returns it to
+ * live — and every reconnect, probes included, resumes from the newest id ever seen. A probe
+ * the browser gives up on schedules the next one: while stalled, nothing else is retrying.
* - 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 { clearSseFrames, sseFrames, sseFramesEnabled } from "../src/api/sse-frames";
import { FakeEventSource, stubEventSource, stubVisibility } from "./helpers/event-source";
afterEach(() => {
vi.useRealTimers();
+ clearSseFrames();
});
function subscribe() {
@@ -24,12 +33,14 @@ function subscribe() {
const sources = stubEventSource();
const setVisibility = stubVisibility();
const errors: boolean[] = [];
+ const liveness: ("live" | "stalled")[] = [];
const conn = openSessionStream("s1", {
onOmniMessage: () => undefined,
onServerEvent: () => undefined,
onError: (closed) => errors.push(closed),
+ onLiveness: (state) => liveness.push(state),
});
- return { sources, setVisibility, conn, errors };
+ return { sources, setVisibility, conn, errors, liveness };
}
type Sub = ReturnType<typeof subscribe>;
@@ -39,6 +50,9 @@ function greet(source: FakeEventSource, id: string): void {
source.emit("ping");
}
+/** How a stream dies on arrival: the connection opens and the body never arrives. */
+const silence = (ms: number) => vi.advanceTimersByTime(ms);
+
const live = (sources: FakeEventSource[]) =>
sources.filter((s) => s.readyState !== FakeEventSource.CLOSED);
@@ -80,7 +94,7 @@ it("becoming visible past the window reopens the stream at once, though no timer
expect(live(sources)).toEqual([sources[1]]);
});
-it("a stream that never pinged is never reopened", () => {
+it("a stream that never pinged is left alone: no silence window, no dead-on-arrival watch", () => {
const { sources, setVisibility } = subscribe();
sources[0]!.emit("server_event", JSON.stringify({ type: "task_state", state: "idle" }), "e-1");
vi.advanceTimersByTime(60 * 60_000);
@@ -88,6 +102,88 @@ it("a stream that never pinged is never reopened", () => {
expect(live(sources)).toEqual([sources[0]]);
});
+it("a connection that delivers nothing is reopened at the deadline, and three of them stall the stream", () => {
+ const { sources, liveness } = subscribe();
+ silence(29_000);
+ expect(sources).toHaveLength(1);
+ silence(1_000);
+ expect(sources[1]!.url).toBe("/api/sessions/s1/stream");
+
+ silence(30_000);
+ expect(sources).toHaveLength(3);
+ silence(30_000);
+ // Three in a row: nothing is left open, the caller is told once, and no connection is made
+ // on the next tick.
+ expect(liveness).toEqual(["stalled"]);
+ expect(live(sources)).toEqual([]);
+ silence(59_000);
+ expect(sources).toHaveLength(3);
+
+ // The probe opens one connection, which gets the same first-frame window as any other.
+ silence(1_000);
+ expect(sources).toHaveLength(4);
+ expect(live(sources)).toEqual([sources[3]]);
+ silence(30_000);
+ expect(liveness).toEqual(["stalled"]);
+ expect(live(sources)).toEqual([]);
+});
+
+it("one frame on a probe brings a stalled stream back to live, and the probing stops", () => {
+ const { sources, liveness } = subscribe();
+ silence(90_000);
+ expect(liveness).toEqual(["stalled"]);
+ silence(60_000);
+ sources[3]!.emit("server_event", JSON.stringify({ type: "task_state", state: "idle" }), "e-9");
+ expect(liveness).toEqual(["stalled", "live"]);
+ silence(60 * 60_000);
+ expect(sources).toHaveLength(4);
+});
+
+it("a probe the browser gives up on does not end the probing", () => {
+ const { sources } = subscribe();
+ silence(90_000);
+ silence(60_000); // the probe
+ expect(sources).toHaveLength(4);
+ // The browser closes that probe (a non-200 answer): nothing retries it for us, so the stream
+ // schedules the next probe itself rather than leaving the page with a dead stream forever.
+ sources[3]!.fail();
+ silence(59_000);
+ expect(sources).toHaveLength(4);
+ silence(1_000);
+ expect(sources).toHaveLength(5);
+});
+
+it("a stalled stream keeps resuming from the newest id it ever saw", () => {
+ const { sources } = subscribe();
+ greet(sources[0]!, "e-5");
+ silence(50_000); // the greeted connection goes quiet: one immediate reopen
+ expect(sources[1]!.url).toBe("/api/sessions/s1/stream?lastEventId=e-5");
+ silence(30_000 + 30_000 + 30_000); // three connections in a row with nothing on them
+ silence(60_000); // the probe
+ expect(sources[4]!.url).toBe("/api/sessions/s1/stream?lastEventId=e-5");
+});
+
+it("every frame received is recorded, once recording is on", () => {
+ vi.stubGlobal("localStorage", {
+ getItem: (key: string) => (key === "penguin.sseFrames" ? "1" : null),
+ setItem: () => undefined,
+ removeItem: () => undefined,
+ });
+ expect(sseFramesEnabled()).toBe(true);
+ const { sources } = subscribe();
+ greet(sources[0]!, "e-1");
+ sources[0]!.emit("message", '{"a":1}', "e-2");
+ const bytes = (data: string) => new TextEncoder().encode(data).length;
+ const snapshot = JSON.stringify({ type: "task_state", state: "running" });
+ const frames = sseFrames();
+ expect(frames.map((f) => [f.kind, f.channel, f.sessionId, f.event, f.id, f.bytes])).toEqual([
+ ["frame", "session", "s1", "server_event", "e-1", bytes(snapshot)],
+ ["frame", "session", "s1", "ping", "e-1", bytes("{}")],
+ ["frame", "session", "s1", "message", "e-2", bytes('{"a":1}')],
+ ]);
+ expect(frames[0]!.preview).toBe(snapshot);
+});
+
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] },
diff --git a/packages/web/test/stream-controller.test.ts b/packages/web/test/stream-controller.test.ts
index 3a120e43..91f645b3 100644
--- a/packages/web/test/stream-controller.test.ts
+++ b/packages/web/test/stream-controller.test.ts
@@ -1045,3 +1045,54 @@ describe("history load failure and retry (#6)", () => {
expect(h.controller.model.items.filter((i) => i.kind === "user_text")).toHaveLength(1);
});
});
+
+describe("refresh (the page keeping itself current while the live stream is stalled)", () => {
+ const PRESENT = ["user_text", "tool_call", "assistant_text"];
+ const TC = at(
+ toolCall({ name: "x", arguments: "{}", toolCallId: "t1" }),
+ "2026-07-05T00:00:01.000Z",
+ );
+ const TAIL: OmniMessage[] = [
+ at(userText("q1"), "2026-07-05T00:00:00.000Z"),
+ TC,
+ at(assistantText("a1"), "2026-07-05T00:00:02.000Z"),
+ ];
+
+ it("refetches the tail in place, keeping a pending approval no resync would have resent", async () => {
+ const h = createHarness();
+ const p = h.controller.load();
+ h.resolveLoad(TAIL, undefined, undefined, pageInfo());
+ await p;
+ h.controller.handleServer({ type: "approval_request", toolCall: TC });
+ expect(h.controller.pendingApprovals.size).toBe(1);
+
+ const r = h.controller.refresh();
+ // The transcript stays exactly as it is until the refetch lands — a reader watching a
+ // stalled stream must not see the conversation blank out once a minute.
+ expect(h.controller.model.items.map((i) => i.kind)).toEqual(PRESENT);
+ expect(h.pageArgs.at(-1)).toEqual({ kind: "tail", limit: TAIL_UNITS });
+ h.resolveLoad(TAIL, undefined, undefined, pageInfo());
+ await r;
+ // The refetched history lands in a fresh model (no duplication), and the approval is still
+ // answerable: the table survives a refresh, which is what tells it apart from a resync rebuild.
+ expect(h.controller.model.items.map((i) => i.kind)).toEqual(PRESENT);
+ expect(h.controller.pendingApprovals.size).toBe(1);
+ });
+
+ it("is a no-op while a load is in flight, after a failed one, and once disposed", async () => {
+ const h = createHarness();
+ // In flight (the initial load holds the pipeline): a second fetch would race its epoch.
+ const p = h.controller.load();
+ await h.controller.refresh();
+ expect(h.loadCalls()).toBe(1);
+ h.rejectLoad(new Error("network error"));
+ await p;
+
+ // Failed: the page shows the error and its Retry entry point, not a silent retry loop.
+ await h.controller.refresh();
+ expect(h.loadCalls()).toBe(1);
+ h.controller.dispose();
+ await h.controller.refresh();
+ expect(h.loadCalls()).toBe(1);
+ });
+});
diff --git a/packages/web/test/transport-rows.test.ts b/packages/web/test/transport-rows.test.ts
new file mode 100644
index 00000000..6681948b
--- /dev/null
+++ b/packages/web/test/transport-rows.test.ts
@@ -0,0 +1,45 @@
+/**
+ * The Transport view's row derivation (features/traces/transport-rows.ts):
+ *
+ * - this Session's frames and the page's own user-level ones are kept (the second marked by its
+ * null Session), another Session's channel is dropped;
+ * - newest first, capped to the newest rows;
+ * - a row's clock carries milliseconds, so frames milliseconds apart keep their order.
+ */
+import { expect, it } from "vitest";
+import type { SseFrameEntry } from "../src/api/sse-frames";
+import {
+ FRAME_ROW_CAP,
+ formatFrameTime,
+ transportRows,
+} from "../src/features/traces/transport-rows";
+
+function frame(at: number, sessionId: string | null): SseFrameEntry {
+ return {
+ at,
+ kind: "frame",
+ channel: sessionId === null ? "events" : "session",
+ sessionId,
+ event: "ping",
+ id: null,
+ bytes: 2,
+ preview: "{}",
+ };
+}
+
+it("keeps this Session's frames and the user-level stream's, dropping another Session's", () => {
+ const entries = [frame(1, "s1"), frame(2, null), frame(3, "s2"), frame(4, "s1")];
+ expect(transportRows(entries, "s1").map((e) => e.at)).toEqual([4, 2, 1]);
+});
+
+it("is newest first and capped to the newest rows", () => {
+ const entries = Array.from({ length: FRAME_ROW_CAP + 5 }, (_, i) => frame(i + 1, "s1"));
+ const rows = transportRows(entries, "s1");
+ expect(rows).toHaveLength(FRAME_ROW_CAP);
+ expect(rows[0]!.at).toBe(FRAME_ROW_CAP + 5);
+ expect(rows.at(-1)!.at).toBe(6);
+});
+
+it("reads a row's clock with milliseconds", () => {
+ expect(formatFrameTime(new Date(2026, 0, 2, 3, 4, 5, 678).getTime())).toBe("03:04:05.678");
+});