Skip to content

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

test(server): pin the terminal resync on the repaint, not screen residue (#516)

Yaowei Zheng5059bb3a8594
diff --git a/changelog/unreleased/2026-08-27-terminal-resync-flake.md b/changelog/unreleased/2026-08-27-terminal-resync-flake.md
new file mode 100644
index 00000000..ecb0831e
--- /dev/null
+++ b/changelog/unreleased/2026-08-27-terminal-resync-flake.md
@@ -0,0 +1,36 @@
+# The terminal resync test stopped reading screen residue
+
+- **Date:** 2026-08-27
+- **Type:** process
+- **Scope:** `server`, `ci`
+- **PR:** [#516](https://github.com/Prism-Shadow/penguin-harness/pull/516)
+
+[中文版](2026-08-27-terminal-resync-flake.zh.md)
+
+`terminal stream backpressure > resyncs a lagging viewer with a fresh Restore instead of
+disconnecting it` failed five times in one day on macOS CI, on five pull requests that touched no
+terminal code, and passed on every rerun. Its resync assertion read a marker the flood prints once
+at the end, which is only still on a 24-row screen if the server happened to take its snapshot
+after the burst settled — an instant the test does not get to choose. The assertion was rewritten
+to read what a resync actually promises, and the two mechanics that turned one such flake into a
+minutes-long hard failure were removed with it.
+
+## Details
+
+- The resync Restore is now asserted to be the self-contained repaint `renderRestoreAnsi` emits —
+ reset, leave the alternate buffer, clear screen and scrollback — carrying consecutive rows of the
+ burst's own fill line. Both hold at every instant the viewer's socket can drain past the low
+ watermark at, mid-burst included; the `BURST-DONE-` tail marker held only after it settled. What
+ the test pins did not change: the server still has to mark the paused viewer as lagging, the
+ socket still has to be `OPEN` rather than disconnected, a second Restore still has to arrive, and
+ the stream still has to carry live output afterwards.
+- Lag detection was scoped to the attempt that is running. The suite's captured server log outlives
+ a single attempt and vitest retries this file on macOS, so a second attempt read the first one's
+ `pausing for resync` line, skipped the flood loop altogether, and then sat out a 60-second
+ deadline waiting for a resync on a terminal nothing had ever flooded.
+- The stream client is closed in a `finally`. A failing assertion used to skip the inline `close()`
+ and leave the socket attached, so `server.close()` in `afterAll` never called back and the run
+ reported a 10-second hook timeout stacked on top of the real failure.
+- The burst is paused with `ws.pause()` instead of a pause on the socket underneath it. `ws` pauses
+ that socket on its own whenever its receiver backs up and resumes it again on the receiver's
+ `drain`, respecting only a pause the caller asked for.
diff --git a/changelog/unreleased/2026-08-27-terminal-resync-flake.zh.md b/changelog/unreleased/2026-08-27-terminal-resync-flake.zh.md
new file mode 100644
index 00000000..c39f1196
--- /dev/null
+++ b/changelog/unreleased/2026-08-27-terminal-resync-flake.zh.md
@@ -0,0 +1,29 @@
+# 终端 resync 测试不再依赖屏幕残留
+
+- **Date:** 2026-08-27
+- **Type:** process
+- **Scope:** `server`, `ci`
+- **PR:** [#516](https://github.com/Prism-Shadow/penguin-harness/pull/516)
+
+[English](2026-08-27-terminal-resync-flake.md)
+
+`terminal stream backpressure > resyncs a lagging viewer with a fresh Restore instead of
+disconnecting it` 一天之内在 macOS CI 上失败五次,落在五个与终端毫无关系的 pull request 上,而每一次重跑都通过。
+它的 resync 断言读的是灌注输出末尾只打印一次的标记,而那行字要留在 24 行的屏幕上,前提是服务端恰好在这一轮
+灌注平息之后才拍下快照——而这个时刻并不由测试决定。此次把断言改为读取 resync 真正承诺的东西,并一并去掉了
+那两处把一次抖动放大成长达数分钟硬失败的机制。
+
+## 细节
+
+- resync 的 Restore 现在被断言为 `renderRestoreAnsi` 发出的那份自足重绘——重置、离开 alternate buffer、
+ 清屏并清 scrollback——且其中带有由灌注自身的填充行构成的连续若干行。无论观众的 socket 在哪一刻跌破低水位,
+ 这两点都成立,灌注进行途中也一样;而 `BURST-DONE-` 这个末尾标记只在灌注平息之后才成立。测试钉住的东西没有变:
+ 服务端仍然必须把暂停读取的观众标记为落后,socket 仍然必须处于 `OPEN` 而不是被断开,第二帧 Restore 仍然必须到达,
+ 其后这条流仍然必须能继续送出实时输出。
+- 落后判定被限定在当前这一次尝试之内。该测试文件捕获的服务端日志会跨越单次尝试存活,而 vitest 在 macOS 上会重试
+ 这个文件,于是第二次尝试读到了第一次留下的 `pausing for resync`,径直跳过整个灌注循环,然后在一个从未被灌注过的
+ 终端上白等 60 秒的期限。
+- 流客户端改在 `finally` 里关闭。此前断言一旦失败就会跳过写在末尾的 `close()`,把 socket 留在连接状态,于是
+ `afterAll` 中的 `server.close()` 永远等不到回调,一次运行便会在真正的失败之上再叠加一条 10 秒的 hook 超时。
+- 灌注期间改用 `ws.pause()` 暂停,而不是去暂停它下面那个 socket。`ws` 在自己的 receiver 积压时会自行暂停该 socket,
+ 并在 receiver `drain` 时再把它恢复,只有调用方主动要求的暂停才会被它尊重。
diff --git a/packages/server/test/terminal-stream.test.ts b/packages/server/test/terminal-stream.test.ts
index a689543c..2fcbcd96 100644
--- a/packages/server/test/terminal-stream.test.ts
+++ b/packages/server/test/terminal-stream.test.ts
@@ -291,26 +291,45 @@ describePty("terminal stream handshake", () => {
);
});
+/**
+ * The line the backpressure flood is made of, and the marker its resync assertion reads.
+ * It fills every row of the screen for the whole burst, so it is there whichever instant
+ * the resync snapshot is taken at — unlike a marker printed once at the end of a round,
+ * which megabytes of scrolling carry off the screen again.
+ */
+const FLOOD_LINE = "0123456789abcdef";
+
+/** Every Restore opens with this self-contained repaint (see snapshot.ts). */
+const RESTORE_PREAMBLE = "\x1b[0m\x1b[?1049l\x1b[H\x1b[2J\x1b[3J";
+
describePty("terminal stream backpressure", () => {
it("resyncs a lagging viewer with a fresh Restore instead of disconnecting it", async () => {
const terminal = await createTerminal();
+ const client = await attach(terminal.id);
try {
- const client = await attach(terminal.id);
await client.waitFor(() => client.restoreText().length > 0, "attach restore");
// Stop reading: the TCP window and then the server's userland queue fill while
- // the shell floods ~7 MB — far past the high watermark.
- const socket = (client.ws as unknown as { _socket: { pause(): void; resume(): void } })
- ._socket;
- socket.pause();
+ // the shell floods ~7 MB — far past the high watermark. Pausing the WebSocket rather
+ // than the socket under it is what makes the pause hold: ws pauses that socket on
+ // its own whenever its receiver backs up, and resumes it again on the receiver's
+ // 'drain' unless this flag says the caller asked for the pause.
+ client.ws.pause();
// Flood until the server itself reports this viewer as lagging. A fixed burst is a
// coin flip: a paused reader still lets the kernel absorb megabytes into its socket
// buffers (autotuned), so the server's own send queue — the thing the watermark
// measures — may never cross 1 MiB however much the shell wrote. This suite failed
// that way roughly one run in three, locally and on CI.
- const isLagging = (): boolean => serverLogs.some((l) => l.includes("pausing for resync"));
+ //
+ // Only lines logged from here on count. `serverLogs` outlives one attempt and vitest
+ // retries this file on macOS, so a second attempt reading the first one's line would
+ // skip the flood altogether and then sit out the resync deadline below on a terminal
+ // nothing ever flooded — which is how a single flake became a hard 60s failure.
+ const loggedBefore = serverLogs.length;
+ const isLagging = (): boolean =>
+ serverLogs.slice(loggedBefore).some((l) => l.includes("pausing for resync"));
for (let round = 1; round <= 8 && !isLagging(); round += 1) {
- client.sendInput(`yes 0123456789abcdef | head -n 400000; echo BURST-DONE-${round}\r`);
+ client.sendInput(`yes ${FLOOD_LINE} | head -n 400000; echo BURST-DONE-${round}\r`);
await waitForCapture(terminal.id, `BURST-DONE-${round}`, 60_000);
}
expect(isLagging(), "server never marked the paused viewer as lagging").toBe(true);
@@ -318,17 +337,26 @@ describePty("terminal stream backpressure", () => {
// The burst has fully landed server-side, and the lagging viewer is still attached.
expect(client.ws.readyState).toBe(WebSocket.OPEN);
- // Catching up delivers one resync Restore carrying the final screen, and the
- // stream is live again afterwards.
- socket.resume();
- const restores = (): number =>
- client.frames.filter((f) => f.opcode === TerminalStreamOpcode.Restore).length;
- await client.waitFor(() => restores() >= 2, "resync Restore frame", 60_000);
- const resync = client.frames.filter((f) => f.opcode === TerminalStreamOpcode.Restore)[1]!;
- expect(resync.text).toContain("BURST-DONE-");
+ // Catching up delivers a resync Restore, and the stream is live again afterwards.
+ client.ws.resume();
+ const restores = (): StreamClient["frames"] =>
+ client.frames.filter((f) => f.opcode === TerminalStreamOpcode.Restore);
+ await client.waitFor(() => restores().length >= 2, "resync Restore frame", 60_000);
+ const resync = restores()[1]!;
+ // What a resync promises is the repaint, not a particular line of screen residue:
+ // the snapshot is taken whenever this viewer's socket drains past the low watermark,
+ // which the test does not get to choose and which may well be mid-flood. So assert
+ // the two things that hold at every such instant — it is the same self-contained
+ // repaint an attach sends, and it carries the flooded screen rather than the empty
+ // one the attach Restore captured.
+ expect(resync.text.slice(0, RESTORE_PREAMBLE.length)).toBe(RESTORE_PREAMBLE);
+ expect(resync.text).toContain(`${FLOOD_LINE}\r\n${FLOOD_LINE}`);
await runAndWait(client, "echo LIVE-$((40+2))", "LIVE-42");
- await client.close();
} finally {
+ // Closed here rather than after the assertions: a socket a failed assertion left open
+ // holds server.close() in afterAll until the hook deadline, which buries the real
+ // failure under a hook timeout.
+ await client.close();
await api.delete(`/api/terminals/${terminal.id}`);
}
// Megabytes through a pty, a paused socket and a drain: minutes of budget on a loaded
diff --git a/packages/server/vitest.config.ts b/packages/server/vitest.config.ts
index 9df415da..446409f3 100644
--- a/packages/server/vitest.config.ts
+++ b/packages/server/vitest.config.ts
@@ -7,7 +7,9 @@
* past the 5s/10s defaults — a different file on each run. Larger deadlines change nothing
* for passing tests; POSIX keeps the defaults to fail fast during local development. The
* hook timeout matters here specifically: `cleanup()` removes the whole test root, and on
- * win32 that rm can legitimately take retries (see helpers.ts).
+ * win32 that rm can legitimately take retries (see helpers.ts). POSIX is deliberately left
+ * at the default: a hook that blows this deadline on macOS has so far meant a test leaking
+ * an open connection into `server.close()`, which a larger number only delays.
*
* `isolate: false` lets a worker reuse its module registry across the files it runs instead
* of discarding it after each one. Every file here imports the whole app graph, core's
@@ -26,7 +28,10 @@
* teardown crash — which ci.yml absorbs with one retry of the whole command instead.
*
* macOS is retried once too: terminal-stream.test.ts drives a real pty and asserts on what
- * came back through it, and that assertion has lost the race on the macOS runner.
+ * came back through it, and that assertion has lost the race on the macOS runner. A retry
+ * only rescues a test whose attempts are independent, which constrains what a retried file
+ * may read from its own file scope: a test that consults an accumulator an earlier attempt
+ * appended to retries into a different — and certain — failure.
*
* `restoreMocks` makes the spy half of that mechanical rather than a reading of the suite:
* a `vi.spyOn` whose inline `mockRestore()` is skipped by a failing assertion above it