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): bound the captureHistory reply so a phone can keep it in one WS message

enesa2083c3ff0c6
diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.ts
index 7fcd4d421..07cb1f4e8 100644
--- a/src/main/remote/host-service.ts
+++ b/src/main/remote/host-service.ts
@@ -11,8 +11,10 @@
// into an `OP.Error` frame (then the stream is dropped).
// - `OP.Input` frame -> `write(sessionId, <utf-8 payload>)`
// - `OP.Resize` frame -> `resize(sessionId, cols, rows)` (payload = 2x uint16 LE)
-// - RPC `pty.captureHistory {streamId}` -> `captureHistory(persistKey)`, returning `{ output }`
-// (tmux scrollback, so a re-entering client can hydrate its empty emulator scrollback)
+// - RPC `pty.captureHistory {streamId, lines?, maxBytes?}` -> `captureHistory(persistKey, lines)`,
+// returning `{ output }` (tmux scrollback, so a re-entering client can hydrate its empty
+// emulator scrollback). `lines`/`maxBytes` are SIZE hints only — clamped, and they can only
+// SHRINK the reply (a phone on a mobile link asks for far less than the desktop caps).
// - RPC `pty.kill {streamId}` -> `kill(sessionId)`
// Output backpressure: when `sendFrame` returns false the host pauses the PTY via `setFlow`
// and resumes it on the next successful send.
@@ -28,7 +30,8 @@ import { app, ipcMain, safeStorage, type BrowserWindow } from 'electron'
import { IPC } from '../../shared/ipc'
import type { CanvasMutation, CanvasState, DirEntry, PtyCreateOptions } from '../../shared/types'
import type { AgentId } from '../../shared/agents/config'
-import { PtyManager, type DetachedSinks } from '../../core/pty-manager'
+import { PtyManager, trimToBytes, type DetachedSinks } from '../../core/pty-manager'
+import { HISTORY_LINES, HISTORY_MAX_BYTES, clampHistoryLines } from '../../core/history-limits'
import * as fsOps from '../../core/fs-ops'
import { getStoredEntitlement, isPremium } from '../../core/license'
import { genKeyPair, publicKeyToB64, type KeyPair } from './e2ee'
@@ -61,8 +64,9 @@ export interface HostPtyManager {
/** Current visible screen of a node's tmux session, for the attach snapshot. */
captureSnapshot(persistKey: string): Promise<string>
/** Scrollback (history + visible screen) of a node's tmux session, for hydrating a fresh
- * emulator on re-entry — the client's own scrollback is empty on a warm reattach. */
- captureHistory(persistKey: string): Promise<string>
+ * emulator on re-entry — the client's own scrollback is empty on a warm reattach. `lines` is
+ * clamped by the pty-manager itself (it is interpolated into a tmux command). */
+ captureHistory(persistKey: string, lines?: number): Promise<string>
write(sessionId: string, data: string): void
resize(sessionId: string, cols: number, rows: number): void
setFlow(sessionId: string, resume: boolean): void
@@ -302,17 +306,27 @@ export function createHostHandlers(
* (empty) emulator scrollback on re-entry. Deliberately keyed by `streamId`, never by a
* client-supplied tmux session name / persistKey: a client may only read the history of a
* session `pty.attach` already granted it. An unknown stream degrades to an empty result.
+ *
+ * `lines` / `maxBytes` are size hints, not targets: both are clamped to the desktop caps, so a
+ * client can only ever ask for LESS than `HISTORY_LINES` / `HISTORY_MAX_BYTES` of the session it
+ * already holds. A phone uses them to keep the (E2EE, base64-inflated) reply small enough to fit
+ * comfortably in one WebSocket message.
*/
function handleCaptureHistory(req: RpcRequest): void {
- const streamId = num(asRecord(req.params).streamId, -1)
- const stream = streams.get(streamId)
+ const p = asRecord(req.params)
+ const stream = streams.get(num(p.streamId, -1))
if (!stream) {
socket.respond(req.id, true, { output: '' })
return
}
+ const lines = clampHistoryLines(num(p.lines, HISTORY_LINES))
+ const maxBytes = Math.min(
+ HISTORY_MAX_BYTES,
+ Math.max(1, Math.floor(num(p.maxBytes, HISTORY_MAX_BYTES)))
+ )
void pty
- .captureHistory(stream.persistKey)
- .then((output) => socket.respond(req.id, true, { output }))
+ .captureHistory(stream.persistKey, lines)
+ .then((output) => socket.respond(req.id, true, { output: trimToBytes(output, maxBytes) }))
.catch(() => socket.respond(req.id, true, { output: '' }))
}
diff --git a/src/main/remote/remote-security.test.ts b/src/main/remote/remote-security.test.ts
index a3e1d3b35..f6b8bd869 100644
--- a/src/main/remote/remote-security.test.ts
+++ b/src/main/remote/remote-security.test.ts
@@ -107,10 +107,58 @@ describe('pty.captureHistory is scoped to the client\'s own streams', () => {
handlers.onRpc({ id: '2', method: 'pty.captureHistory', params: { streamId } })
await Promise.resolve()
await Promise.resolve()
- expect(pty.captureHistory as ReturnType<typeof vi.fn>).toHaveBeenCalledWith('node-a')
+ expect(pty.captureHistory as ReturnType<typeof vi.fn>).toHaveBeenCalledWith('node-a', 5000)
expect(responses[1]).toEqual({ id: '2', ok: true, body: { output: 'HISTORY' } })
})
+ it('keeps the streamId as the target even when hostile session names ride along', async () => {
+ // The actual override-attempt shape: a VALID streamId (the client legitimately holds it) plus
+ // a hostile persistKey/nodeId/session in the same params. The target must still come from the
+ // stream, never from the client's names.
+ const { socket, responses, fs, pty } = makeHostFakes()
+ const handlers = createHostHandlers(pty, socket, fs, () => [])
+ handlers.onRpc({ id: '1', method: 'pty.attach', params: { nodeId: 'node-a', cols: 80, rows: 24 } })
+ await Promise.resolve()
+ await Promise.resolve()
+ const streamId = (responses[0].body as { streamId: number }).streamId
+
+ handlers.onRpc({
+ id: '2',
+ method: 'pty.captureHistory',
+ params: { streamId, persistKey: 'victim', nodeId: 'victim', session: 'nt-victim' }
+ })
+ await Promise.resolve()
+ await Promise.resolve()
+ const captureHistory = pty.captureHistory as ReturnType<typeof vi.fn>
+ expect(captureHistory).toHaveBeenCalledTimes(1)
+ expect(captureHistory).toHaveBeenCalledWith('node-a', 5000) // NOT 'victim'
+ expect(responses[1]).toEqual({ id: '2', ok: true, body: { output: 'HISTORY' } })
+ })
+
+ it('clamps the client\'s lines/maxBytes hints (they can only shrink the reply)', async () => {
+ const { socket, responses, fs, pty } = makeHostFakes()
+ ;(pty.captureHistory as ReturnType<typeof vi.fn>).mockResolvedValue('one\ntwo\nthree\n')
+ const handlers = createHostHandlers(pty, socket, fs, () => [])
+ handlers.onRpc({ id: '1', method: 'pty.attach', params: { nodeId: 'node-a', cols: 80, rows: 24 } })
+ await Promise.resolve()
+ await Promise.resolve()
+ const streamId = (responses[0].body as { streamId: number }).streamId
+
+ // A client asking for MORE than the caps is clamped down to them; a small maxBytes trims the
+ // reply from the head (oldest lines first).
+ handlers.onRpc({
+ id: '2',
+ method: 'pty.captureHistory',
+ params: { streamId, lines: 999_999, maxBytes: 8 }
+ })
+ await Promise.resolve()
+ await Promise.resolve()
+ expect(pty.captureHistory as ReturnType<typeof vi.fn>).toHaveBeenCalledWith('node-a', 5000)
+ const body = responses[1].body as { output: string }
+ expect(Buffer.byteLength(body.output, 'utf-8')).toBeLessThanOrEqual(8)
+ expect(body.output).toBe('three\n')
+ })
+
it('degrades to an empty result for an unknown streamId (never reads another session)', async () => {
const { socket, responses, fs, pty } = makeHostFakes()
const handlers = createHostHandlers(pty, socket, fs, () => [])