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.

feat(b5): terminal snapshot + attach-to-existing (live remote session)

enes0e4f068f14d2
diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.ts
index d5769f1a4..1a551e7d3 100644
--- a/src/main/pty-manager.ts
+++ b/src/main/pty-manager.ts
@@ -169,6 +169,52 @@ export class PtyManager {
return this.spawnSession(options, null, sinks)
}
+ /**
+ * Attach a detached (relay-served) PTY to the EXISTING tmux session for a node id, rather
+ * than always creating a fresh one. Because `spawnSession` uses `tmux new-session -A`, passing
+ * the node id as the `persistKey` reattaches the existing `nt-<nodeId>` session if it exists,
+ * or creates it otherwise (graceful fallback). Used by the relay host so a mirrored terminal
+ * resumes the host's live session instead of opening a blank shell. Pair with `captureSnapshot`
+ * to paint the current screen before live output starts streaming.
+ */
+ attachDetached(
+ persistKey: string,
+ sinks: DetachedSinks,
+ options: Omit<PtyCreateOptions, 'persistKey'> = { cols: 80, rows: 24 }
+ ): string {
+ return this.spawnSession({ ...options, persistKey }, null, sinks)
+ }
+
+ /**
+ * Capture the CURRENT visible pane of a node's tmux session (with colors, via `-e`). Returns
+ * the screen text so the relay host can send it as a snapshot the mirrored client paints before
+ * live output. Empty string if tmux is unavailable or the session doesn't exist yet.
+ */
+ async captureSnapshot(persistKey: string): Promise<string> {
+ if (!this.tmuxPath) return ''
+ try {
+ const { stdout } = await runAsync(
+ this.tmuxPath,
+ ['-L', TMUX_SOCKET, 'capture-pane', '-p', '-e', '-t', sessionName(persistKey)],
+ { encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024 }
+ )
+ return stdout
+ } catch {
+ return ''
+ }
+ }
+
+ /** Whether a tmux session for this node id currently exists (host attach-vs-create decision). */
+ async hasSession(persistKey: string): Promise<boolean> {
+ if (!this.tmuxPath) return false
+ try {
+ await runAsync(this.tmuxPath, ['-L', TMUX_SOCKET, 'has-session', '-t', sessionName(persistKey)])
+ return true
+ } catch {
+ return false
+ }
+ }
+
private spawnSession(
options: PtyCreateOptions,
webContentsId: number | null,
diff --git a/src/main/remote/client-service.ts b/src/main/remote/client-service.ts
index 2b3e26469..46bfe9158 100644
--- a/src/main/remote/client-service.ts
+++ b/src/main/remote/client-service.ts
@@ -27,6 +27,7 @@ import { OP, type Frame } from './framing'
import { CANVAS_MUTATE_METHOD, CANVAS_STATE_METHOD } from './host-service'
import { decodeOffer } from './pairing'
import { connectRelay, type RelaySocket, type RpcRequest } from './relay-socket'
+import { createSnapshotReassembler, type SnapshotReassembler } from './snapshot'
// Default relay endpoint override gate — mirrors host-service.ts. Used only for the dev gate;
// the actual endpoint a client connects to comes from the decoded offer.
@@ -68,6 +69,8 @@ export interface ClientHandlers {
interface Stream {
/** Outbound OP.Input/OP.Resize sequence counter. */
seq: number
+ /** Reassembles the host's SnapshotStart→Chunk*→End into the initial screen text. */
+ snapshot: SnapshotReassembler
}
function asRecord(value: unknown): Record<string, unknown> {
@@ -95,12 +98,22 @@ export function createClientHandlers(
return {
async create(options) {
- const body = asRecord(await socket.rpc('pty.create', options))
+ // RemoteTransport is only ever used for mirrored (remote) nodes, so `create` maps to
+ // `pty.attach` — the client attaches to the host's EXISTING tmux session for this node id
+ // (the persistKey is the host node id from the mirror) and gets a snapshot of the current
+ // screen before live output, instead of spawning a fresh blank PTY (B4's blank-terminal bug).
+ const body = asRecord(
+ await socket.rpc('pty.attach', {
+ nodeId: options.persistKey,
+ cols: options.cols,
+ rows: options.rows
+ })
+ )
const streamId = body.streamId
if (typeof streamId !== 'number' || !Number.isFinite(streamId)) {
throw new Error('Host did not return a streamId.')
}
- streams.set(streamId, { seq: 0 })
+ streams.set(streamId, { seq: 0, snapshot: createSnapshotReassembler() })
return streamId
},
write(streamId, data) {
@@ -120,7 +133,19 @@ export function createClientHandlers(
void socket.rpc('pty.kill', { streamId }).catch(() => {})
},
onFrame(frame) {
- if (!streams.has(frame.streamId)) return
+ const stream = streams.get(frame.streamId)
+ if (!stream) return
+ if (
+ frame.op === OP.SnapshotStart ||
+ frame.op === OP.SnapshotChunk ||
+ frame.op === OP.SnapshotEnd
+ ) {
+ // Buffer the snapshot; on End deliver the reassembled current screen as the FIRST onData
+ // so the mirrored xterm paints it before any live output arrives.
+ const res = stream.snapshot.accept(frame)
+ if (res.done && res.text) sinks.onData(frame.streamId, res.text)
+ return
+ }
if (frame.op === OP.Output) {
sinks.onData(frame.streamId, textDecoder.decode(frame.payload))
return
diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.ts
index 644924907..9f05bcf45 100644
--- a/src/main/remote/host-service.ts
+++ b/src/main/remote/host-service.ts
@@ -46,6 +46,14 @@ const textDecoder = new TextDecoder()
// The slice of pty-manager the host needs. PtyManager satisfies this; tests pass a fake.
export interface HostPtyManager {
createDetached(options: PtyCreateOptions, sinks: DetachedSinks): string
+ /** Attach a relay-served PTY to the EXISTING tmux session for a node id (create if absent). */
+ attachDetached(
+ persistKey: string,
+ sinks: DetachedSinks,
+ options?: Omit<PtyCreateOptions, 'persistKey'>
+ ): string
+ /** Current visible screen of a node's tmux session, for the attach snapshot. */
+ captureSnapshot(persistKey: string): Promise<string>
write(sessionId: string, data: string): void
resize(sessionId: string, cols: number, rows: number): void
setFlow(sessionId: string, resume: boolean): void
@@ -101,21 +109,10 @@ export function createHostHandlers(pty: HostPtyManager, socket: HostRelaySocket)
streams.delete(streamId)
}
- function handleCreate(req: RpcRequest): void {
- const p = asRecord(req.params)
- const options: PtyCreateOptions = {
- cols: Math.max(1, num(p.cols, 80)),
- rows: Math.max(1, num(p.rows, 24)),
- cwd: str(p.cwd),
- shell: str(p.shell),
- persistKey: str(p.persistKey),
- agentId: str(p.agentId) as AgentId | undefined
- }
-
- const streamId = ++streamCounter
- const stream: Stream = { sessionId: '', seq: 0, paused: false }
-
- const sinks: DetachedSinks = {
+ // Build the output/exit sinks for a new stream: pipe PTY output into OP.Output frames (with
+ // relay backpressure -> setFlow pause/resume) and PTY exit into an OP.Error frame.
+ function makeSinks(streamId: number, stream: Stream): DetachedSinks {
+ return {
onData: (data) => {
const bytes = textEncoder.encode(data)
const ok = socket.sendFrame(OP.Output, streamId, stream.seq++, bytes)
@@ -139,6 +136,22 @@ export function createHostHandlers(pty: HostPtyManager, socket: HostRelaySocket)
dropStream(streamId)
}
}
+ }
+
+ function handleCreate(req: RpcRequest): void {
+ const p = asRecord(req.params)
+ const options: PtyCreateOptions = {
+ cols: Math.max(1, num(p.cols, 80)),
+ rows: Math.max(1, num(p.rows, 24)),
+ cwd: str(p.cwd),
+ shell: str(p.shell),
+ persistKey: str(p.persistKey),
+ agentId: str(p.agentId) as AgentId | undefined
+ }
+
+ const streamId = ++streamCounter
+ const stream: Stream = { sessionId: '', seq: 0, paused: false }
+ const sinks = makeSinks(streamId, stream)
let sessionId: string
try {
@@ -152,6 +165,73 @@ export function createHostHandlers(pty: HostPtyManager, socket: HostRelaySocket)
socket.respond(req.id, true, { streamId })
}
+ // Reassembled snapshot is sent as one or more OP.SnapshotChunk frames between Start and End.
+ // 256 KB keeps each chunk well under the relay's per-frame limits while a full-screen capture
+ // (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))
+ 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)
+ )
+ }
+ socket.sendFrame(OP.SnapshotEnd, streamId, stream.seq++, new Uint8Array(0))
+ }
+
+ /**
+ * Attach a mirrored terminal to the host's EXISTING tmux session for `nodeId`: respond with the
+ * streamId, send a SNAPSHOT of the current screen (so the client paints it before any live
+ * output), then start streaming live output via `attachDetached`. Falls back to plain create
+ * semantics when no session exists yet (attachDetached creates one; the snapshot is empty).
+ */
+ function handleAttach(req: RpcRequest): void {
+ const p = asRecord(req.params)
+ const nodeId = str(p.nodeId) ?? str(p.persistKey)
+ if (!nodeId) {
+ socket.respond(req.id, false, { message: 'pty.attach requires a nodeId.' })
+ return
+ }
+ const cols = Math.max(1, num(p.cols, 80))
+ const rows = Math.max(1, num(p.rows, 24))
+
+ const streamId = ++streamCounter
+ const stream: Stream = { sessionId: '', seq: 0, paused: false }
+ const sinks = makeSinks(streamId, stream)
+
+ // Reserve the stream and respond up front so the client can route Input/Resize frames; the
+ // snapshot + live attach then proceed. Capturing the screen is async (a tmux side-call).
+ streams.set(streamId, stream)
+ socket.respond(req.id, true, { streamId })
+
+ void pty
+ .captureSnapshot(nodeId)
+ .catch(() => '')
+ .then((snapshot) => {
+ // The stream may have been killed/closed while the capture was in flight.
+ if (!streams.has(streamId)) return
+ // Snapshot first (current screen) — then live output begins on attach.
+ sendSnapshot(streamId, stream, snapshot)
+ try {
+ stream.sessionId = pty.attachDetached(nodeId, sinks, { cols, rows })
+ } catch {
+ // Attach failed (e.g. tmux unavailable) — surface as an exit so the client tears down.
+ socket.sendFrame(
+ OP.Error,
+ streamId,
+ stream.seq++,
+ textEncoder.encode(JSON.stringify({ exitCode: 1 }))
+ )
+ dropStream(streamId)
+ }
+ })
+ }
+
function handleKill(req: RpcRequest): void {
const streamId = num(asRecord(req.params).streamId, -1)
const stream = streams.get(streamId)
@@ -168,6 +248,9 @@ export function createHostHandlers(pty: HostPtyManager, socket: HostRelaySocket)
case 'pty.create':
handleCreate(req)
break
+ case 'pty.attach':
+ handleAttach(req)
+ break
case 'pty.kill':
handleKill(req)
break
diff --git a/src/main/remote/snapshot.ts b/src/main/remote/snapshot.ts
new file mode 100644
index 000000000..ce3496c3d
--- /dev/null
+++ b/src/main/remote/snapshot.ts
@@ -0,0 +1,64 @@
+// Snapshot reassembly — the unit-testable core of the terminal "current screen" feature.
+//
+// When a client attaches to a host's existing tmux session it must paint the CURRENT screen
+// before any live output arrives, otherwise the mirrored xterm renders blank (B4's bug). The
+// host sends the captured screen as a three-stage sequence on the stream's channel:
+//
+// OP.SnapshotStart — opens the buffer (payload ignored; reserved for a header)
+// OP.SnapshotChunk (0..N) — payload = a slice of the UTF-8 bytes of the captured screen
+// OP.SnapshotEnd — closes the buffer; the accumulated bytes are decoded to text
+//
+// The reassembler accumulates the chunk *bytes* (so a multi-byte UTF-8 codepoint split across a
+// chunk boundary survives) and only decodes on End. Pure: no sockets, no Electron.
+
+import { OP, type Frame } from './framing'
+
+const textDecoder = new TextDecoder()
+
+/** Result of feeding one frame: `done:false` while buffering, `done:true` + `text` on End. */
+export type SnapshotResult = { done: false } | { done: true; text: string }
+
+export interface SnapshotReassembler {
+ /**
+ * Feed one decoded frame. Returns `{done:false}` for Start/Chunk (and for unrelated frames),
+ * or `{done:true, text}` on End — the reassembled snapshot text, ready to deliver as the
+ * session's first `onData`.
+ */
+ accept(frame: Frame): SnapshotResult
+}
+
+export function createSnapshotReassembler(): SnapshotReassembler {
+ // Pending chunk byte-slices, concatenated only on End so a multi-byte codepoint split across
+ // a chunk boundary is decoded correctly.
+ let chunks: Uint8Array[] = []
+ let open = false
+
+ return {
+ accept(frame) {
+ switch (frame.op) {
+ case OP.SnapshotStart:
+ // A fresh Start discards any partial buffer (no leak between snapshots on one stream).
+ chunks = []
+ open = true
+ return { done: false }
+ case OP.SnapshotChunk:
+ if (open && frame.payload.length > 0) chunks.push(frame.payload)
+ return { done: false }
+ case OP.SnapshotEnd: {
+ const total = chunks.reduce((n, c) => n + c.length, 0)
+ const merged = new Uint8Array(total)
+ let offset = 0
+ for (const c of chunks) {
+ merged.set(c, offset)
+ offset += c.length
+ }
+ chunks = []
+ open = false
+ return { done: true, text: textDecoder.decode(merged) }
+ }
+ default:
+ return { done: false }
+ }
+ }
+ }
+}
diff --git a/test/remote/client-handlers.test.ts b/test/remote/client-handlers.test.ts
index 01806969f..3e1799e65 100644
--- a/test/remote/client-handlers.test.ts
+++ b/test/remote/client-handlers.test.ts
@@ -13,7 +13,8 @@ function fakeSocket(createBody: unknown = { streamId: 7 }) {
const socket: ClientRelaySocket = {
rpc: vi.fn(async (method, params) => {
rpcs.push({ method, params })
- if (method === 'pty.create') return createBody
+ // RemoteTransport is remote-only, so `create` maps to `pty.attach` (attach-to-existing).
+ if (method === 'pty.attach') return createBody
return {}
}),
sendFrame: vi.fn((op, streamId, seq, payload) => {
@@ -35,15 +36,38 @@ function fakeSinks() {
}
describe('createClientHandlers', () => {
- it('maps create to RPC pty.create and resolves with the host streamId', async () => {
+ it('maps create to RPC pty.attach (nodeId from persistKey) and resolves with the host streamId', async () => {
const sock = fakeSocket({ streamId: 7 })
const sinks = fakeSinks()
const h = createClientHandlers(sock.socket, sinks.sinks)
- const streamId = await h.create({ cols: 100, rows: 30, cwd: '/tmp' })
+ const streamId = await h.create({ cols: 100, rows: 30, cwd: '/tmp', persistKey: 'node-9' })
expect(streamId).toBe(7)
- expect(sock.rpcs).toEqual([{ method: 'pty.create', params: { cols: 100, rows: 30, cwd: '/tmp' } }])
+ expect(sock.rpcs).toEqual([
+ { method: 'pty.attach', params: { nodeId: 'node-9', cols: 100, rows: 30 } }
+ ])
+ })
+
+ it('delivers a buffered snapshot (Start→Chunk*→End) as the first onData before live output', async () => {
+ const sock = fakeSocket({ streamId: 4 })
+ const sinks = fakeSinks()
+ const h = createClientHandlers(sock.socket, sinks.sinks)
+ await h.create({ cols: 80, rows: 24, persistKey: 'node-x' })
+
+ h.onFrame({ op: OP.SnapshotStart, streamId: 4, seq: 0, payload: new Uint8Array(0) })
+ h.onFrame({ op: OP.SnapshotChunk, streamId: 4, seq: 1, payload: new TextEncoder().encode('cur') })
+ h.onFrame({ op: OP.SnapshotChunk, streamId: 4, seq: 2, payload: new TextEncoder().encode('rent') })
+ // Nothing delivered until End.
+ expect(sinks.data).toEqual([])
+ h.onFrame({ op: OP.SnapshotEnd, streamId: 4, seq: 3, payload: new Uint8Array(0) })
+ // Snapshot first, then live output.
+ h.onFrame({ op: OP.Output, streamId: 4, seq: 4, payload: new TextEncoder().encode('live') })
+
+ expect(sinks.data).toEqual([
+ { streamId: 4, data: 'current' },
+ { streamId: 4, data: 'live' }
+ ])
})
it('throws when the host does not return a numeric streamId', async () => {
diff --git a/test/remote/host-handlers.test.ts b/test/remote/host-handlers.test.ts
index 5429f164a..64cca6a2d 100644
--- a/test/remote/host-handlers.test.ts
+++ b/test/remote/host-handlers.test.ts
@@ -14,6 +14,7 @@ function fakePty() {
let lastSinks: DetachedSinks | null = null
let lastOptions: PtyCreateOptions | null = null
let counter = 0
+ let snapshot = ''
const mgr: HostPtyManager = {
createDetached(options, sinks) {
lastOptions = options
@@ -22,6 +23,16 @@ function fakePty() {
calls.push({ method: 'createDetached', args: [options, id] })
return id
},
+ attachDetached(persistKey, sinks, options) {
+ lastSinks = sinks
+ const id = `pty-${++counter}`
+ calls.push({ method: 'attachDetached', args: [persistKey, id, options] })
+ return id
+ },
+ captureSnapshot: async (persistKey) => {
+ calls.push({ method: 'captureSnapshot', args: [persistKey] })
+ return snapshot
+ },
write: (sessionId, data) => calls.push({ method: 'write', args: [sessionId, data] }),
resize: (sessionId, cols, rows) =>
calls.push({ method: 'resize', args: [sessionId, cols, rows] }),
@@ -32,7 +43,10 @@ function fakePty() {
mgr,
calls,
sinks: () => lastSinks!,
- options: () => lastOptions!
+ options: () => lastOptions!,
+ setSnapshot: (s: string) => {
+ snapshot = s
+ }
}
}
@@ -69,6 +83,63 @@ describe('createHostHandlers', () => {
expect(sock.responses).toEqual([{ id: 'r1', ok: true, body: { streamId: 1 } }])
})
+ it('maps pty.attach to a snapshot sequence then attachDetached on the existing session', async () => {
+ const pty = fakePty()
+ pty.setSnapshot('CURRENT SCREEN')
+ const sock = fakeSocket()
+ const h = createHostHandlers(pty.mgr, sock.socket)
+
+ h.onRpc({ id: 'r1', method: 'pty.attach', params: { nodeId: 'node-9', cols: 100, rows: 30 } })
+ // Responds with the streamId synchronously so the client can route frames.
+ expect(sock.responses).toEqual([{ id: 'r1', ok: true, body: { streamId: 1 } }])
+ // Capture + attach are async (a tmux side-call).
+ await new Promise((r) => setTimeout(r, 0))
+
+ expect(pty.calls).toContainEqual({ method: 'captureSnapshot', args: ['node-9'] })
+ expect(pty.calls).toContainEqual({
+ method: 'attachDetached',
+ args: ['node-9', 'pty-1', { cols: 100, rows: 30 }]
+ })
+
+ // Snapshot frames precede any live output: Start, one Chunk (the screen text), End.
+ expect(sock.frames[0]).toMatchObject({ op: OP.SnapshotStart, streamId: 1 })
+ expect(sock.frames[1]).toMatchObject({ op: OP.SnapshotChunk, streamId: 1 })
+ expect(Buffer.from(sock.frames[1].payload).toString('utf8')).toBe('CURRENT SCREEN')
+ expect(sock.frames[2]).toMatchObject({ op: OP.SnapshotEnd, streamId: 1 })
+
+ // Live output then drives the same stream.
+ pty.sinks().onData('live')
+ const out = sock.frames.find((f) => f.op === OP.Output)
+ expect(out).toBeDefined()
+ expect(Buffer.from(out!.payload).toString('utf8')).toBe('live')
+ })
+
+ it('attach sends an empty snapshot when the session has no current screen', async () => {
+ const pty = fakePty() // snapshot defaults to ''
+ const sock = fakeSocket()
+ const h = createHostHandlers(pty.mgr, sock.socket)
+
+ h.onRpc({ id: 'r1', method: 'pty.attach', params: { nodeId: 'node-1', cols: 80, rows: 24 } })
+ await new Promise((r) => setTimeout(r, 0))
+
+ // Empty snapshot: Start, End, no Chunk.
+ expect(sock.frames.map((f) => f.op)).toContain(OP.SnapshotStart)
+ expect(sock.frames.map((f) => f.op)).toContain(OP.SnapshotEnd)
+ expect(sock.frames.some((f) => f.op === OP.SnapshotChunk)).toBe(false)
+ expect(pty.calls).toContainEqual({
+ method: 'attachDetached',
+ args: ['node-1', 'pty-1', { cols: 80, rows: 24 }]
+ })
+ })
+
+ it('rejects pty.attach without a nodeId', () => {
+ const pty = fakePty()
+ const sock = fakeSocket()
+ const h = createHostHandlers(pty.mgr, sock.socket)
+ h.onRpc({ id: 'r1', method: 'pty.attach', params: { cols: 80, rows: 24 } })
+ expect(sock.responses[0]).toMatchObject({ id: 'r1', ok: false })
+ })
+
it('pipes PTY output into OP.Output frames with an incrementing seq', () => {
const pty = fakePty()
const sock = fakeSocket()
diff --git a/test/remote/relay-e2e.test.ts b/test/remote/relay-e2e.test.ts
index 2dabc4e46..df8c7c9cb 100644
--- a/test/remote/relay-e2e.test.ts
+++ b/test/remote/relay-e2e.test.ts
@@ -184,6 +184,16 @@ function makeEchoPty(): HostPtyManager {
sinks.set(sessionId, s)
return sessionId
},
+ attachDetached(_persistKey: string, s: DetachedSinks): string {
+ // Same echo semantics as create — the client now opens streams via pty.attach.
+ const sessionId = `echo-${++counter}`
+ sinks.set(sessionId, s)
+ return sessionId
+ },
+ async captureSnapshot(): Promise<string> {
+ // No prior screen in the fake; an empty snapshot still exercises the Start→End path.
+ return ''
+ },
write(sessionId: string, data: string): void {
sinks.get(sessionId)?.onData(data)
},
@@ -288,11 +298,11 @@ describe('B4 relay end-to-end (real relay + real protocol + fake pty)', () => {
// Both ends complete the E2EE handshake.
await withTimeout(Promise.all([hostReady.promise, clientReady.promise]), HANDSHAKE_TIMEOUT_MS, 'handshake')
- // --- client opens a stream via RPC pty.create ---
+ // --- client opens a stream via RPC pty.attach (persistKey = host node id) ---
const streamId = await withTimeout(
- clientHandlers.create({ cols: 80, rows: 24 }),
+ clientHandlers.create({ cols: 80, rows: 24, persistKey: 'node-e2e' }),
HANDSHAKE_TIMEOUT_MS,
- 'pty.create'
+ 'pty.attach'
)
expect(typeof streamId).toBe('number')
diff --git a/test/remote/snapshot.test.ts b/test/remote/snapshot.test.ts
new file mode 100644
index 000000000..7baed59ec
--- /dev/null
+++ b/test/remote/snapshot.test.ts
@@ -0,0 +1,65 @@
+import { describe, it, expect } from 'vitest'
+import { createSnapshotReassembler } from '../../src/main/remote/snapshot'
+import { OP, decodeFrame, encodeFrame } from '../../src/main/remote/framing'
+
+const enc = new TextEncoder()
+
+// Build the three-stage snapshot wire sequence for one stream: Start, N chunks, End.
+function snapshotFrames(streamId: number, chunks: string[]): Uint8Array[] {
+ let seq = 0
+ const frames: Uint8Array[] = []
+ frames.push(encodeFrame(OP.SnapshotStart, streamId, seq++, new Uint8Array(0)))
+ for (const c of chunks) frames.push(encodeFrame(OP.SnapshotChunk, streamId, seq++, enc.encode(c)))
+ frames.push(encodeFrame(OP.SnapshotEnd, streamId, seq++, new Uint8Array(0)))
+ return frames
+}
+
+describe('createSnapshotReassembler', () => {
+ it('concatenates SnapshotStart→Chunk*→End into the original string and signals ready on End', () => {
+ const r = createSnapshotReassembler()
+ const frames = snapshotFrames(5, ['hello ', 'world'])
+
+ // Start: opens the buffer, no payload yet, not ready.
+ expect(r.accept(decodeFrame(frames[0])!)).toEqual({ done: false })
+ // Chunks accumulate, still not ready.
+ expect(r.accept(decodeFrame(frames[1])!)).toEqual({ done: false })
+ expect(r.accept(decodeFrame(frames[2])!)).toEqual({ done: false })
+ // End: ready, with the reassembled text.
+ expect(r.accept(decodeFrame(frames[3])!)).toEqual({ done: true, text: 'hello world' })
+ })
+
+ it('handles an empty snapshot (Start then End, no chunks)', () => {
+ const r = createSnapshotReassembler()
+ let seq = 0
+ const start = decodeFrame(encodeFrame(OP.SnapshotStart, 1, seq++, new Uint8Array(0)))!
+ const end = decodeFrame(encodeFrame(OP.SnapshotEnd, 1, seq++, new Uint8Array(0)))!
+ expect(r.accept(start)).toEqual({ done: false })
+ expect(r.accept(end)).toEqual({ done: true, text: '' })
+ })
+
+ it('preserves UTF-8 across chunk boundaries (multi-byte split)', () => {
+ const r = createSnapshotReassembler()
+ // "é" is 0xC3 0xA9 — split the two bytes across two chunks to prove byte-level reassembly.
+ const full = enc.encode('café')
+ const a = full.slice(0, 4) // "caf" + first byte of é
+ const b = full.slice(4) // second byte of é
+ let seq = 0
+ r.accept(decodeFrame(encodeFrame(OP.SnapshotStart, 2, seq++, new Uint8Array(0)))!)
+ r.accept(decodeFrame(encodeFrame(OP.SnapshotChunk, 2, seq++, a))!)
+ r.accept(decodeFrame(encodeFrame(OP.SnapshotChunk, 2, seq++, b))!)
+ const res = r.accept(decodeFrame(encodeFrame(OP.SnapshotEnd, 2, seq++, new Uint8Array(0)))!)
+ expect(res).toEqual({ done: true, text: 'café' })
+ })
+
+ it('a fresh Start resets a partial buffer (no leak between snapshots)', () => {
+ const r = createSnapshotReassembler()
+ let seq = 0
+ r.accept(decodeFrame(encodeFrame(OP.SnapshotStart, 3, seq++, new Uint8Array(0)))!)
+ r.accept(decodeFrame(encodeFrame(OP.SnapshotChunk, 3, seq++, enc.encode('stale')))!)
+ // New Start discards the stale partial buffer.
+ r.accept(decodeFrame(encodeFrame(OP.SnapshotStart, 3, seq++, new Uint8Array(0)))!)
+ r.accept(decodeFrame(encodeFrame(OP.SnapshotChunk, 3, seq++, enc.encode('fresh')))!)
+ const res = r.accept(decodeFrame(encodeFrame(OP.SnapshotEnd, 3, seq++, new Uint8Array(0)))!)
+ expect(res).toEqual({ done: true, text: 'fresh' })
+ })
+})