Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(relay): resume a paused phone stream on drain; skip unchanged relay.json rewrites

Brandon Bridges45ab4592f73c
diff --git a/CLAUDE.md b/CLAUDE.md
index 6c038e929..995fcd3c4 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -9359,6 +9359,20 @@ unix-socket forward and dev-server `-L` forward over it. POSIX keeps OpenSSH unt
`POST /v1/relay/host-token` / `/v1/relay/device` must admit deviceId (no-entitlement) mints, and
the relay server may rate-limit free hosts independently — a client-side gate must NOT be
reintroduced to work around a backend refusal (fix the backend policy instead).
+- **A paused phone stream is resumed by a drain sweep, never by "the next chunk"**
+ (`main/remote/host-service.ts`, FLOW_SWEEP_MS). `sendFrame` refuses — and drops — a frame once the
+ relay socket holds >8 MB, and the host pauses the pty; a paused node-pty emits no `onData`, so the
+ old resume-on-next-successful-send never fired and the phone's terminal froze until it detached
+ (audit net-1). A 250 ms sweep, armed only while a stream is paused and cleared in
+ `dropStream`/`closeAll`, waits for `bufferedAmount() <= 256 KB`, then capture → `OP.Snapshot*` →
+ `setFlow(resume)`, in that order (the dropped frame desynced the phone; resuming first lets live
+ output race the repaint). A refused repaint retries with backoff (250 ms doubling to 10 s: a
+ reconnecting relay reads 0 buffered but refuses every send, so no backoff = a tmux capture per
+ tick). Output still queued after the pause is dropped, not streamed. An empty
+ capture resumes WITHOUT a repaint — unlike `ui-sink-registry`'s keep-desynced rule, staying here
+ means staying frozen. Same design as `core/ui-sink-registry.ts`; do not reintroduce a chunk-driven
+ resume. `~/.nodeterm/relay.json` is written only when its content changes or the file is missing
+ (`relay-advertise.ts`): the ~90 s listener cycle used to rewrite it identically (~960/day, net-5).
- **The phone's Chat screen verbs** (`chat.page` / `chat.status` / `chat.send` / `agent.answer`,
`host-service.ts` `handleChat` → `main/remote/host-chat.ts`, spec + exact error strings in
`docs/mobile-chat-view.md` §3.2). Four rules a refactor must not undo: (1) **the phone sends only a
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 352058a2e..b12c54587 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -629,6 +629,12 @@ anything else. Board-level fields survive every transform — `pullLinks` is one
SSH node became a local shell in this machine's `$HOME`. CLAUDE.md, "A remote node is NEVER
spawned locally".
+- **Relay backpressure is undone by a drain sweep, never by the next chunk of output.** A paused
+ pty produces no next chunk, so a resume that waits for one never comes: that froze the phone's
+ terminal for good after a single >8 MB burst. `host-service.ts` arms a 250 ms sweep while a stream
+ is paused, then repaints with a snapshot before it resumes; `core/ui-sink-registry.ts` does the same
+ for every other sink. A new paused path needs the same trigger. CLAUDE.md, "Remote access".
+
- **An SSH project's node runs on the project's host — ask the project, not the node.** Node
fields like `sshRemoteTmux` arrive through a shared `project.json` that the host's own desktop and
teammates also write, so a node without them must still never become a local shell (issue #1186).
diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.ts
index 78bca9f0d..c58224324 100644
--- a/src/main/remote/host-service.ts
+++ b/src/main/remote/host-service.ts
@@ -16,8 +16,9 @@
// - RPC `pty.destroy {streamId}` -> the injected `destroyNode` (the phone's "End session"):
// permanently ends the stream's tmux session and takes the node off its canvas — the same two
// steps the desktop × performs. The target is resolved from the stream, never client params.
-// Output backpressure: when `sendFrame` returns false the host pauses the PTY via `setFlow`
-// and resumes it on the next successful send.
+// Output backpressure: when `sendFrame` returns false the host pauses the PTY via `setFlow`; a
+// 250 ms drain sweep (armed only while a stream is paused) resumes it once the socket is back under
+// 256 KB and repaints the phone with a fresh snapshot — see FLOW_SWEEP_MS.
//
// This file is glue over already-tested units (relay-socket, framing, pairing, pty-manager).
// The pure RPC/frame -> pty-manager mapping lives in `createHostHandlers` so it is unit-
@@ -72,6 +73,23 @@ const textDecoder = new TextDecoder()
* now precedes the attach response and its own timeout is 6 s. */
const FRESH_PROBE_BUDGET_MS = 750
+/**
+ * Relay backpressure recovery for a paused phone stream. `sendFrame` refuses (and DROPS) a frame
+ * once the socket holds more than 8 MB (`MAX_BINARY_BUFFERED_AMOUNT`); the host then pauses the
+ * pty. A paused node-pty emits no `onData`, so a resume driven off "the next successful send" can
+ * never happen — the audit (REPORT §4.7 net-1) found exactly that: after one >8 MB burst the phone's
+ * terminal froze until it detached. The sweep is the drain trigger instead, mirroring
+ * `core/ui-sink-registry.ts` (RESYNC_SWEEP_MS / WS_LOW_WATER: "never the next chunk as the drain
+ * trigger"). It exists only while some stream is paused, so the healthy path pays nothing.
+ */
+const FLOW_SWEEP_MS = 250
+/** Resume below this many buffered bytes — the registry's WS_LOW_WATER, so "less full" never flaps. */
+const FLOW_LOW_WATER = 256_000
+/** A repaint the socket refused is retried on 250 ms, 500, 1 s … capped here. While the relay is
+ * between transports `bufferedAmount()` reads 0 but every send fails, so without a backoff each
+ * tick would spawn a `tmux capture-pane` (the registry's RESYNC_BACKOFF_MAX_MS guards the same). */
+const FLOW_BACKOFF_MAX_MS = 10_000
+
// --- pure host handlers (RPC/frame <-> pty-manager) -------------------------
// The slice of pty-manager the host needs. PtyManager satisfies this; tests pass a fake.
@@ -113,6 +131,10 @@ export interface HostPtyManager {
export interface HostRelaySocket {
respond(id: string, ok: boolean, body: unknown): void
sendFrame(op: number, streamId: number, seq: number, payload: Uint8Array): boolean
+ /** Bytes queued and not yet flushed (RelaySocket.bufferedAmount). Drives the drain sweep that
+ * resumes a paused stream. Optional so fakes compile; absent reads as 0 (drained), because a
+ * socket that cannot report must fail toward resuming — never toward "paused forever". */
+ bufferedAmount?(): number
}
export interface HostHandlers {
@@ -234,6 +256,15 @@ interface Stream {
seq: number
/** True while the PTY is paused due to relay backpressure. */
paused: boolean
+ /** True while a drain-triggered repaint (capture → snapshot → resume) is in flight. */
+ resuming?: boolean
+ /** Refused repaints since the pause, and when the next one may be tried (FLOW_BACKOFF_MAX_MS). */
+ resumeAttempts?: number
+ resumeNotBefore?: number
+ /** The current-screen capture for this stream (the attach's own `prep.snapshot`), kept so a
+ * resume after backpressure can repaint the phone: the frame that crossed the 8 MB line was
+ * dropped, so the phone's emulator is desynced and only a fresh screen can fix it. */
+ snapshot?: () => Promise<string>
}
function asRecord(value: unknown): Record<string, unknown> {
@@ -339,10 +370,65 @@ export function createHostHandlers(
// reverse (sessionId -> streamId) index is needed.
const streams = new Map<number, Stream>()
let streamCounter = 0
+ // The drain sweep (FLOW_SWEEP_MS). Armed on a pause, cleared once no stream is paused.
+ let flowSweep: ReturnType<typeof setInterval> | null = null
+
+ function armFlowSweep(): void {
+ if (flowSweep) return
+ flowSweep = setInterval(() => {
+ for (const [id, s] of streams) if (s.paused) maybeResume(id, s)
+ stopFlowSweepIfIdle()
+ }, FLOW_SWEEP_MS)
+ flowSweep.unref?.() // never the reason the main process stays alive
+ }
+
+ function stopFlowSweepIfIdle(): void {
+ if (!flowSweep) return
+ for (const s of streams.values()) if (s.paused) return
+ clearInterval(flowSweep)
+ flowSweep = null
+ }
+
+ /** Resume a paused stream IF its socket has drained: capture → snapshot → resume, in that order.
+ * While paused no `onData` can fire, so nothing interleaves with the repaint; resuming first
+ * would let live output race ahead of a now-stale snapshot. */
+ function maybeResume(streamId: number, stream: Stream): void {
+ if (!stream.paused || stream.resuming) return
+ if (Date.now() < (stream.resumeNotBefore ?? 0)) return
+ if ((socket.bufferedAmount?.() ?? 0) > FLOW_LOW_WATER) return
+ stream.resuming = true
+ void (async () => {
+ let screen = ''
+ try {
+ screen = stream.snapshot ? await stream.snapshot() : ''
+ } catch {
+ screen = ''
+ }
+ stream.resuming = false
+ // Killed / closed while the capture was in flight: its pty is released, never resume it.
+ if (streams.get(streamId) !== stream || !stream.paused) return
+ // An empty capture skips the repaint but STILL resumes. Unlike the registry (which keeps a
+ // client desynced and retries on an empty capture), staying here means staying paused —
+ // the very freeze this sweep exists to end. A stale screen beats a frozen one.
+ if (screen && !sendSnapshot(streamId, stream, screen)) {
+ // Refused (refilled, or the relay is reconnecting): stay paused, retry with backoff.
+ const attempts = (stream.resumeAttempts ?? 0) + 1
+ stream.resumeAttempts = attempts
+ stream.resumeNotBefore = Date.now() + Math.min(FLOW_SWEEP_MS * 2 ** (attempts - 1), FLOW_BACKOFF_MAX_MS)
+ return
+ }
+ stream.resumeAttempts = 0
+ stream.resumeNotBefore = 0
+ stream.paused = false
+ pty.setFlow(null, stream.sessionId, true)
+ stopFlowSweepIfIdle()
+ })()
+ }
function dropStream(streamId: number): void {
const stream = streams.get(streamId)
streams.delete(streamId)
+ stopFlowSweepIfIdle()
// Report AFTER the delete: `detached` may consult the live viewer set via its own bookkeeping,
// and a callback that throws must not leave the stream registered.
if (stream) {
@@ -374,15 +460,21 @@ export function createHostHandlers(
socket.sendFrame(OP.Resized, streamId, stream.seq++, payload)
},
onData: (data) => {
+ if (stream.paused) {
+ // A batch already queued before the pause took hold. The phone is desynced (a frame was
+ // dropped), so streaming more of it only paints garbage: drop it, and let the repaint
+ // that resumes the stream bring the screen back. A chunk we can see is a free drain check.
+ maybeResume(streamId, stream)
+ return
+ }
const bytes = textEncoder.encode(data)
const ok = socket.sendFrame(OP.Output, streamId, stream.seq++, bytes)
- if (!ok && !stream.paused) {
- // Relay buffer is full — pause the PTY so the OS pipe backpressures the producer.
+ if (!ok) {
+ // Relay buffer is full — pause the PTY so the OS pipe backpressures the producer. The
+ // sweep, not the next chunk, resumes it (a paused pty produces no next chunk).
stream.paused = true
pty.setFlow(null, stream.sessionId, false)
- } else if (ok && stream.paused) {
- stream.paused = false
- pty.setFlow(null, stream.sessionId, true)
+ armFlowSweep()
}
},
onExit: (exitCode) => {
@@ -403,18 +495,22 @@ export function createHostHandlers(
// (with colors) stays small in practice.
const SNAPSHOT_CHUNK_BYTES = 256 * 1024
- function sendSnapshot(streamId: number, stream: Stream, text: string): void {
- socket.sendFrame(OP.SnapshotStart, streamId, stream.seq++, new Uint8Array(0))
+ /** Send `text` as a Start/Chunk…/End snapshot. Returns false if any frame was refused — the
+ * attach ignores that (as it always has); a backpressure resume retries on the next sweep, and
+ * the client's reassembler discards a partial buffer on the next Start (snapshot.ts). */
+ function sendSnapshot(streamId: number, stream: Stream, text: string): boolean {
+ let ok = socket.sendFrame(OP.SnapshotStart, streamId, stream.seq++, new Uint8Array(0))
const bytes = textEncoder.encode(text)
for (let i = 0; i < bytes.length; i += SNAPSHOT_CHUNK_BYTES) {
- socket.sendFrame(
- OP.SnapshotChunk,
- streamId,
- stream.seq++,
- bytes.subarray(i, i + SNAPSHOT_CHUNK_BYTES)
- )
+ ok =
+ socket.sendFrame(
+ OP.SnapshotChunk,
+ streamId,
+ stream.seq++,
+ bytes.subarray(i, i + SNAPSHOT_CHUNK_BYTES)
+ ) && ok
}
- socket.sendFrame(OP.SnapshotEnd, streamId, stream.seq++, new Uint8Array(0))
+ return socket.sendFrame(OP.SnapshotEnd, streamId, stream.seq++, new Uint8Array(0)) && ok
}
/**
@@ -520,6 +616,7 @@ export function createHostHandlers(
}
: {})
})
+ stream.snapshot = () => prep.snapshot()
const snapshot = await prep.snapshot().catch(() => '')
// The stream may have been killed/closed while the capture was in flight.
if (!streams.has(streamId)) return
@@ -1259,6 +1356,7 @@ export function createHostHandlers(
pty.kill(null, stream.sessionId)
}
streams.clear()
+ stopFlowSweepIfIdle()
for (const stream of closing) {
try {
remoteViewer?.detached(stream.persistKey)
diff --git a/src/main/remote/relay-advertise.test.ts b/src/main/remote/relay-advertise.test.ts
new file mode 100644
index 000000000..28768e70f
--- /dev/null
+++ b/src/main/remote/relay-advertise.test.ts
@@ -0,0 +1,81 @@
+// Audit net-5 (REPORT §4.7): the standing host rewrote ~/.nodeterm/relay.json with identical
+// content on every ~90 s listener cycle. The advertiser now skips an unchanged write, but must still
+// rewrite when the content changes, when the file has gone, and after a remove. Every test runs
+// against a temp dir through the factory — never the live ~/.nodeterm.
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { promises as fs } from 'fs'
+import os from 'os'
+import path from 'path'
+
+const atomic = vi.hoisted(() => ({ writes: 0 }))
+vi.mock('../../core/fs-atomic', async (importOriginal) => {
+ const real = await importOriginal<typeof import('../../core/fs-atomic')>()
+ return {
+ ...real,
+ writeFileAtomic: async (...args: Parameters<typeof real.writeFileAtomic>) => {
+ atomic.writes++
+ return real.writeFileAtomic(...args)
+ }
+ }
+})
+
+import { createRelayAdvertiser, type RelayAdvertisement } from './relay-advertise'
+
+const AD: RelayAdvertisement = {
+ v: 1,
+ hostId: 'host-1',
+ hostPublicKeyB64: 'cHVi',
+ relayEndpoint: 'wss://relay.example/ws',
+ hostDeviceId: 'dev-1'
+}
+
+let dir: string
+let file: string
+
+beforeEach(async () => {
+ dir = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-relay-ad-'))
+ file = path.join(dir, '.nodeterm', 'relay.json')
+ atomic.writes = 0
+})
+
+afterEach(async () => {
+ await fs.rm(dir, { recursive: true, force: true })
+})
+
+describe('relay advertisement — skip unchanged rewrites', () => {
+ it('writes once, then skips byte-identical advertisements', async () => {
+ const ad = createRelayAdvertiser(file)
+ await ad.write(AD)
+ expect(JSON.parse(await fs.readFile(file, 'utf8'))).toEqual(AD)
+ await ad.write({ ...AD })
+ await ad.write({ ...AD })
+ expect(atomic.writes).toBe(1)
+ })
+
+ it('rewrites when the content changes', async () => {
+ const ad = createRelayAdvertiser(file)
+ await ad.write(AD)
+ await ad.write({ ...AD, relayEndpoint: 'wss://other.example/ws' })
+ expect(atomic.writes).toBe(2)
+ expect(JSON.parse(await fs.readFile(file, 'utf8')).relayEndpoint).toBe('wss://other.example/ws')
+ })
+
+ it('rewrites an unchanged advertisement whose file has gone', async () => {
+ const ad = createRelayAdvertiser(file)
+ await ad.write(AD)
+ await fs.rm(file)
+ await ad.write(AD)
+ expect(atomic.writes).toBe(2)
+ expect(JSON.parse(await fs.readFile(file, 'utf8'))).toEqual(AD)
+ })
+
+ it('remove deletes the file and forgets it, so the next start writes again', async () => {
+ const ad = createRelayAdvertiser(file)
+ await ad.write(AD)
+ await ad.remove()
+ await expect(fs.access(file)).rejects.toThrow()
+ await ad.write(AD)
+ expect(atomic.writes).toBe(2)
+ expect(JSON.parse(await fs.readFile(file, 'utf8'))).toEqual(AD)
+ })
+})
diff --git a/src/main/remote/relay-advertise.ts b/src/main/remote/relay-advertise.ts
index 19756dc90..b0768072c 100644
--- a/src/main/remote/relay-advertise.ts
+++ b/src/main/remote/relay-advertise.ts
@@ -25,19 +25,59 @@ export interface RelayAdvertisement {
hostDeviceId: string
}
-/** Best-effort atomic write — a failed advertisement only means late adoption is unavailable. */
-export async function writeRelayAdvertisement(ad: RelayAdvertisement): Promise<void> {
- try {
- await fs.mkdir(path.dirname(FILE), { recursive: true, mode: 0o700 })
- await writeFileAtomic(FILE, JSON.stringify(ad, null, 2) + '\n', { mode: 0o600 })
- } catch {
- // Advertisement is opportunistic; pairing-time provisioning still works.
+/**
+ * The advertisement writer for one file. The standing host calls `write` on EVERY successful
+ * listener open — every ~90 s, 24/7, with byte-identical content (audit REPORT §4.7 net-5 measured
+ * the mtime refreshing each cycle: ~960 mkdir + temp-write + rename a day for nothing). So an
+ * unchanged advertisement is skipped: the last string we wrote is kept in memory, and the file is
+ * rewritten only when the content changes or the file has gone (a user or another tool deleted it —
+ * one stat per cycle is what that costs). `remove` forgets it, so the next start always writes.
+ * A factory so the tests can point it at a temp dir and never touch the live ~/.nodeterm.
+ */
+export function createRelayAdvertiser(file: string): {
+ write(ad: RelayAdvertisement): Promise<void>
+ remove(): Promise<void>
+} {
+ let lastWritten: string | null = null
+ return {
+ /** Best-effort atomic write — a failed advertisement only means late adoption is unavailable. */
+ async write(ad) {
+ const content = JSON.stringify(ad, null, 2) + '\n'
+ try {
+ if (content === lastWritten) {
+ try {
+ await fs.access(file)
+ return // unchanged and still there
+ } catch {
+ /* gone — fall through and rewrite it */
+ }
+ }
+ await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 })
+ await writeFileAtomic(file, content, { mode: 0o600 })
+ lastWritten = content
+ } catch {
+ // Advertisement is opportunistic; pairing-time provisioning still works. `lastWritten` is
+ // untouched, so a failed write is retried on the next cycle.
+ }
+ },
+ /** Remove the advertisement (host stopped / toggle off) so phones stop offering adoption.
+ * `removeAtomic` retries transient Windows sharing violations and treats "already absent"
+ * (ENOENT) as success; it never throws. */
+ async remove() {
+ lastWritten = null
+ await removeAtomic(file)
+ }
}
}
-/** Remove the advertisement (host stopped / toggle off) so phones stop offering adoption.
- * `removeAtomic` retries transient Windows sharing violations and treats "already absent"
- * (ENOENT) as success; it never throws. */
+const advertiser = createRelayAdvertiser(FILE)
+
+/** Best-effort atomic write of ~/.nodeterm/relay.json; skipped when unchanged (see above). */
+export async function writeRelayAdvertisement(ad: RelayAdvertisement): Promise<void> {
+ await advertiser.write(ad)
+}
+
+/** Remove ~/.nodeterm/relay.json (host stopped / toggle off); never throws. */
export async function removeRelayAdvertisement(): Promise<void> {
- await removeAtomic(FILE)
+ await advertiser.remove()
}
diff --git a/test/remote/host-handlers.test.ts b/test/remote/host-handlers.test.ts
index 363fa1d7a..8e6400932 100644
--- a/test/remote/host-handlers.test.ts
+++ b/test/remote/host-handlers.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi } from 'vitest'
+import { afterEach, describe, it, expect, vi } from 'vitest'
import {
createHostHandlers,
type HostPtyManager,
@@ -77,14 +77,17 @@ function fakePty() {
function fakeSocket(sendOk = true) {
const responses: { id: string; ok: boolean; body: unknown }[] = []
const frames: { op: number; streamId: number; seq: number; payload: Uint8Array }[] = []
+ // `ok` / `buffered` are mutable so a test can stall the socket and then let it drain.
+ const state = { ok: sendOk, buffered: 0 }
const socket: HostRelaySocket = {
respond: (id, ok, body) => responses.push({ id, ok, body }),
sendFrame: (op, streamId, seq, payload) => {
frames.push({ op, streamId, seq, payload })
- return sendOk
- }
+ return state.ok
+ },
+ bufferedAmount: () => state.buffered
}
- return { socket, responses, frames }
+ return { socket, responses, frames, state }
}
const resizePayload = (cols: number, rows: number) => {
@@ -253,19 +256,124 @@ describe('createHostHandlers', () => {
expect(pty.calls).toHaveLength(0)
})
- it('pauses the PTY on backpressure and resumes on the next successful send', async () => {
- const pty = fakePty()
- const sock = fakeSocket(false) // sendFrame returns false → backpressure
- const h = createHostHandlers(pty.mgr, sock.socket)
- await openViaAttach(h)
+ // Audit net-1 (REPORT §4.7): a paused node-pty emits NO further onData, so a resume that waits for
+ // "the next successful send" never comes and the phone's terminal froze for good after one >8 MB
+ // burst. These tests deliver nothing after the pause — the drain sweep alone must resume it.
+ describe('relay backpressure: the drain sweep resumes a paused stream', () => {
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ const resumes = (pty: ReturnType<typeof fakePty>) =>
+ pty.calls.filter((c) => c.method === 'setFlow' && c.args[2] === true)
+
+ async function pausedStream(screen = 'SCREEN') {
+ const pty = fakePty()
+ pty.setSnapshot(screen)
+ const sock = fakeSocket()
+ const h = createHostHandlers(pty.mgr, sock.socket)
+ await openViaAttach(h)
+ vi.useFakeTimers()
+ sock.state.ok = false // the relay buffer is over 8 MB: sendFrame refuses (and drops)
+ sock.state.buffered = 9_000_000
+ pty.sinks().onData('a')
+ expect(pty.calls).toContainEqual({ method: 'setFlow', args: [null, 'pty-1', false] })
+ return { pty, sock, h }
+ }
+
+ it('resumes once drained, with no further pty output, and repaints BEFORE resuming', async () => {
+ const { pty, sock } = await pausedStream()
+ const order: string[] = []
+ sock.socket.sendFrame = (op) => {
+ order.push(`frame:${op}`)
+ return true
+ }
+ const realSetFlow = pty.mgr.setFlow
+ pty.mgr.setFlow = (...args) => {
+ order.push(`setFlow:${String(args[2])}`)
+ realSetFlow(...args)
+ }
+ sock.state.ok = true
+ sock.state.buffered = 0 // drained — and the paused pty delivers NOTHING
+
+ await vi.advanceTimersByTimeAsync(300)
+
+ expect(resumes(pty)).toEqual([{ method: 'setFlow', args: [null, 'pty-1', true] }])
+ // A fresh screen (the frame that crossed the line was dropped), and only then live output.
+ expect(order).toEqual([
+ `frame:${OP.SnapshotStart}`,
+ `frame:${OP.SnapshotChunk}`,
+ `frame:${OP.SnapshotEnd}`,
+ 'setFlow:true'
+ ])
+ expect(vi.getTimerCount()).toBe(0) // the sweep disarms once nothing is paused
+ })
+
+ it('stays paused while the socket is above the low-water mark', async () => {
+ const { pty, sock } = await pausedStream()
+ sock.state.ok = true
+ sock.state.buffered = 1_000_000 // draining, but not below 256 KB yet
+
+ await vi.advanceTimersByTimeAsync(2_000)
+ expect(resumes(pty)).toEqual([])
- pty.sinks().onData('a') // send fails → pause
- expect(pty.calls).toContainEqual({ method: 'setFlow', args: [null, 'pty-1', false] })
+ sock.state.buffered = 100_000
+ await vi.advanceTimersByTimeAsync(300)
+ expect(resumes(pty)).toHaveLength(1)
+ })
+
+ it('drops output still queued after the pause instead of streaming a desynced screen', async () => {
+ const { pty, sock } = await pausedStream()
+ const outputs = () => sock.frames.filter((f) => f.op === OP.Output).length
+ const before = outputs()
+ pty.sinks().onData('late batch') // the one queueData batch already in flight
+ expect(outputs()).toBe(before)
+ })
+
+ it('an empty capture still resumes (no repaint) rather than staying frozen', async () => {
+ const { pty, sock } = await pausedStream('')
+ sock.state.ok = true
+ sock.state.buffered = 0
+ const framesBefore = sock.frames.length
+
+ await vi.advanceTimersByTimeAsync(300)
+
+ expect(resumes(pty)).toHaveLength(1)
+ expect(sock.frames.slice(framesBefore).some((f) => f.op === OP.SnapshotStart)).toBe(false)
+ })
+
+ it('a snapshot the socket refuses keeps the stream paused and retries with backoff', async () => {
+ const { pty, sock } = await pausedStream()
+ const captures = () => pty.calls.filter((c) => c.method === 'captureSnapshot').length
+ const capturesAtPause = captures()
+ // Reports drained, but every send fails — what a relay between transports looks like
+ // (bufferedAmount 0, state not ready). Must not become a capture per tick.
+ sock.state.buffered = 0
+ await vi.advanceTimersByTimeAsync(5_000)
+ expect(resumes(pty)).toEqual([])
+ // 250 ms ticks for 5 s would be 20 captures; the backoff (250, 500, 1 s, 2 s …) allows ~5.
+ expect(captures() - capturesAtPause).toBeLessThanOrEqual(6)
+
+ sock.state.ok = true
+ await vi.advanceTimersByTimeAsync(10_500)
+ expect(resumes(pty)).toHaveLength(1)
+ })
- // Flip the socket to succeed, then deliver more output → resume.
- sock.socket.sendFrame = vi.fn(() => true)
- pty.sinks().onData('b')
- expect(pty.calls).toContainEqual({ method: 'setFlow', args: [null, 'pty-1', true] })
+ it('closeAll while paused disarms the sweep and never resumes the released pty', async () => {
+ const { pty, sock, h } = await pausedStream()
+ h.closeAll()
+ expect(vi.getTimerCount()).toBe(0)
+ sock.state.ok = true
+ sock.state.buffered = 0
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(resumes(pty)).toEqual([])
+ })
+
+ it('pty.kill while paused disarms the sweep', async () => {
+ const { h } = await pausedStream()
+ h.onRpc({ id: 'k', method: 'pty.kill', params: { streamId: 1 } })
+ expect(vi.getTimerCount()).toBe(0)
+ })
})
it('rejects unknown RPC methods', () => {