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(rpc): mark undefined arg slots on the wire instead of guessing null → undefined

enes7502cb0d5c51
diff --git a/src/core/pty-coattach.test.ts b/src/core/pty-coattach.test.ts
index 458a785b1..69fba067f 100644
--- a/src/core/pty-coattach.test.ts
+++ b/src/core/pty-coattach.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { initPlatform, resetPlatformForTests } from './platform'
import { fakePlatform, type FakePlatform } from './platform-fake'
import { IPC } from '../shared/ipc'
+import { encodeArgs, parseRpcMessage } from '../shared/rpc'
/** One fake pty per spawn, recorded so a test can assert "exactly one spawn" and push output. */
interface FakePty {
@@ -681,6 +682,43 @@ describe('size negotiation: smallest subscriber wins', () => {
expect(spawned[0].resizes).toEqual([]) // no viewers → keep the last size, never resize to 1x1
expect(sizes(sessionId)).toEqual([])
})
+
+ // In the Server Edition the park signal does not arrive as a function call: the browser
+ // JSON-serialises it, the server parses it with `parseRpcMessage` and dispatches it into THIS
+ // handler. A decoder that rewrote every top-level `null` to `undefined` made the strict park
+ // check miss, so `normalizeSize(undefined, undefined)` clamped to {1,1}: the parked client stayed
+ // in the ledger claiming a 1×1 grid, and the min over subscribers collapsed the shared pty (and
+ // its tmux pane) to 1 column × 1 row for EVERY co-attached viewer — permanently, because a parked
+ // client never re-reports. So the wire itself is part of the contract.
+ it('parks (never 1x1) when the park signal comes over the WS-RPC wire', async () => {
+ await manager()
+ const { sessionId } = await create(ALICE, 80, 24)
+ await create(BOB, 120, 40)
+
+ const frame = JSON.stringify({
+ t: 'cast',
+ method: IPC.ptyResize,
+ args: encodeArgs([sessionId, null, null])
+ })
+ const m = parseRpcMessage(frame) as { method: string; args: unknown[] }
+ expect(m.args).toEqual([sessionId, null, null]) // the nulls MEAN something — they survive
+ fake.senderListeners[m.method](ALICE, ...m.args)
+
+ expect(spawned[0].resizes.at(-1)).toEqual({ cols: 120, rows: 40 }) // Bob's own size, not 1×1
+ expect(spawned[0].resizes.some((r) => r.cols === 1 || r.rows === 1)).toBe(false)
+ })
+
+ // Belt and braces: should any future encoding path lose the `null` again, the park check is loose
+ // (`== null`), so an `undefined` size degrades to PARK — the safe direction — instead of 1×1.
+ it('treats an undefined size as park, not as a 1x1 grid', async () => {
+ const m = await manager()
+ const { sessionId } = await create(ALICE, 80, 24)
+ await create(BOB, 120, 40)
+
+ m.resize(ALICE, sessionId, undefined as unknown as null, undefined as unknown as null)
+ expect(spawned[0].resizes.at(-1)).toEqual({ cols: 120, rows: 40 })
+ expect(spawned[0].resizes.some((r) => r.cols === 1 || r.rows === 1)).toBe(false)
+ })
})
// ── A node DELETED while somebody else is watching it ─────────────────────────────────────────
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index ad2f6cc69..ba743a0d9 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -1483,7 +1483,12 @@ export class PtyManager {
): void {
const session = this.sessions.get(sessionId)
if (!session) return
- if (cols === null || rows === null) {
+ // Loose `== null` on purpose (belt and braces): the sizes arrive over IPC on the desktop and
+ // over a JSON wire in the Server Edition, and JSON has no `undefined`. If any encoding path
+ // ever loses the distinction again, "no size" must degrade to PARK — dropping the client from
+ // the ledger — and never to `normalizeSize(undefined, undefined)`, which clamps to a 1×1 grid
+ // and would shrink the shared pty to one cell for every co-attached viewer.
+ if (cols == null || rows == null) {
session.sizes.delete(clientId)
} else {
const size = normalizeSize(cols, rows)
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 1f2afb9d1..52075e9d2 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -6,7 +6,13 @@
// namespaces (`pty`, `workspace`, `settings`) over that socket. Every other namespace comes from
// `buildStubApi()` (Task 7) so the renderer boots without a full Electron preload.
-import { parseRpcMessage, decodePtyData, E_DISCONNECTED, type RpcMessage } from '../../shared/rpc'
+import {
+ parseRpcMessage,
+ encodeArgs,
+ decodePtyData,
+ E_DISCONNECTED,
+ type RpcMessage
+} from '../../shared/rpc'
import { IPC } from '../../shared/ipc'
import {
UNKNOWN_CLAUDE_CLI_CAPS,
@@ -144,13 +150,15 @@ export class RpcClient {
const id = this.nextId++
return new Promise<unknown>((resolve, reject) => {
this.pending.set(id, { resolve, reject })
- this.ws.send(JSON.stringify({ t: 'req', id, method, args }))
+ // encodeArgs: an OMITTED optional argument must reach the handler as `undefined` (so its
+ // default fires) while a MEANINGFUL `null` (pty.resize park, presence clears) stays `null`.
+ this.ws.send(JSON.stringify({ t: 'req', id, method, args: encodeArgs(args) }))
})
}
/** Send a fire-and-forget cast (no response expected). */
cast(method: string, ...args: unknown[]): void {
- this.ws.send(JSON.stringify({ t: 'cast', method, args }))
+ this.ws.send(JSON.stringify({ t: 'cast', method, args: encodeArgs(args) }))
}
/** Subscribe to a channel; returns an unsubscribe function. */
diff --git a/src/server/platform-server.ts b/src/server/platform-server.ts
index f4561c50c..982dd6d16 100644
--- a/src/server/platform-server.ts
+++ b/src/server/platform-server.ts
@@ -3,6 +3,7 @@ import type { FlowOwner } from '../core/pty-manager'
import { IPC } from '../shared/ipc'
import {
E_NO_HANDLER,
+ encodeArgs,
encodePtyData,
type RpcErr,
type RpcOk,
@@ -212,7 +213,9 @@ export class ServerPlatform implements CorePlatform {
channel.startsWith(p)
)
if (deadPrefix) this.forgetFlowState(ServerPlatform.flowKey(uiId, channel.slice(deadPrefix.length)))
- sink.sendText(JSON.stringify({ t: 'ev', channel, args }))
+ // Symmetric with the browser's send: mark `undefined` arg slots so the renderer's listeners
+ // see them as `undefined` rather than `null` (and a real `null` still arrives as `null`).
+ sink.sendText(JSON.stringify({ t: 'ev', channel, args: encodeArgs(args) }))
}
}
diff --git a/src/shared/rpc.test.ts b/src/shared/rpc.test.ts
index 12290ea4b..0e4367d31 100644
--- a/src/shared/rpc.test.ts
+++ b/src/shared/rpc.test.ts
@@ -1,5 +1,9 @@
import { describe, it, expect } from 'vitest'
-import { parseRpcMessage, encodePtyData, decodePtyData } from './rpc'
+import { parseRpcMessage, encodeArgs, encodePtyData, decodePtyData } from './rpc'
+
+/** What a sender actually puts on the wire: encode the arg slots, then JSON. */
+const wire = (method: string, ...args: unknown[]): string =>
+ JSON.stringify({ t: 'cast', method, args: encodeArgs(args) })
describe('rpc protocol', () => {
it('parses each message kind and rejects malformed input', () => {
@@ -20,17 +24,21 @@ describe('rpc protocol', () => {
expect(parseRpcMessage('{"t":"req","id":"x","method":1}')).toBeNull()
})
- // `JSON.stringify([a, undefined])` is `[a, null]` — the wire has no `undefined`. So a browser
- // call that omits a trailing optional argument (`git.history(cwd)`, `worktreeMerge(repo, b, base)`)
- // arrives at the handler as an EXPLICIT `null`, which does NOT trigger a default parameter:
- // `worktreeMerge(…, push = false)` runs with `push === null`. Today every such default happens to
- // be falsy, so `null` coerces to the same behavior and the bug is invisible — safe by luck, not by
- // construction. The first `= true` default (or any handler that branches on `arg === undefined`)
- // reintroduces it; `git.history` already broke exactly this way. The decoder is the one place
- // that can close it for every handler at once, so it does: no method in the preload API surface
- // takes a meaningful `null`, which is what makes the substitution safe.
- it('decodes a null argument back to undefined, so default parameters actually apply', () => {
- const req = parseRpcMessage('{"t":"req","id":1,"method":"git:worktree-merge","args":["/repo","feat","main",null]}')
+ // `JSON.stringify([a, undefined])` is `[a, null]` — raw JSON has no `undefined`. A browser call
+ // that omits a trailing optional argument (`git.history(cwd)`, `worktreeMerge(repo, b, base)`)
+ // would therefore reach the handler as an EXPLICIT `null`, which does NOT trigger a default
+ // parameter: `worktreeMerge(…, push = false)` would run with `push === null` (`git.history` broke
+ // exactly this way). `encodeArgs` marks the `undefined` slots explicitly, so the decoder RESTORES
+ // them instead of guessing from `null`.
+ it('round-trips an omitted trailing argument as undefined, so default parameters apply', () => {
+ const req = parseRpcMessage(
+ JSON.stringify({
+ t: 'req',
+ id: 1,
+ method: 'git:worktree-merge',
+ args: encodeArgs(['/repo', 'feat', 'main', undefined])
+ })
+ )
expect(req).toEqual({
t: 'req', id: 1, method: 'git:worktree-merge', args: ['/repo', 'feat', 'main', undefined]
})
@@ -40,16 +48,32 @@ describe('rpc protocol', () => {
const push = args[3] as boolean | undefined
expect(((p = false) => p)(push)).toBe(false)
- // Interior nulls too: `[undefined, 2]` serialises to `[null, 2]` just the same.
- expect(parseRpcMessage('{"t":"cast","method":"m","args":[null,2]}')).toEqual({
+ // Interior undefined slots survive too.
+ expect(parseRpcMessage(wire('m', undefined, 2))).toEqual({
t: 'cast', method: 'm', args: [undefined, 2]
})
- expect(parseRpcMessage('{"t":"ev","channel":"c","args":[null]}')).toEqual({
- t: 'ev', channel: 'c', args: [undefined]
+ })
+
+ // The counterpart, and the reason the old blanket `null → undefined` decode was a BUG: several
+ // methods take a MEANINGFUL top-level `null` — `pty.resize(sid, null, null)` is the co-attach
+ // "park" signal (drop me from the size ledger), `presence.cursor/focus/chat/project(null)` clear
+ // state, `git.setActiveRemote(null)` clears the remote. Rewriting those to `undefined` collapsed
+ // the shared pty to 1×1 (the strict `cols === null` park check missed, and `normalizeSize(
+ // undefined, undefined)` clamps to 1). A null the caller MEANT must arrive as null.
+ it('preserves a meaningful top-level null (park signal / clear-state casts)', () => {
+ expect(parseRpcMessage(wire('pty:resize', 's1', null, null))).toEqual({
+ t: 'cast', method: 'pty:resize', args: ['s1', null, null]
+ })
+ expect(parseRpcMessage(wire('presence:cursor', null))).toEqual({
+ t: 'cast', method: 'presence:cursor', args: [null]
+ })
+ // …and a null and an omitted slot are distinguishable in the SAME call.
+ expect(parseRpcMessage(wire('m', null, undefined))).toEqual({
+ t: 'cast', method: 'm', args: [null, undefined]
})
})
- it('leaves a null NESTED inside an argument alone (only top-level slots are wire artifacts)', () => {
+ it('leaves a null NESTED inside an argument alone (encoding only marks top-level slots)', () => {
// A null inside an object/array is real data the sender meant to send — `{cwd: null}` is not the
// same as `{}` to a handler that checks `'cwd' in opts`. Only the top-level arg slots are the
// ones JSON mangled, so only those are restored.
diff --git a/src/shared/rpc.ts b/src/shared/rpc.ts
index a3cd1351a..2ce687bb7 100644
--- a/src/shared/rpc.ts
+++ b/src/shared/rpc.ts
@@ -18,25 +18,38 @@ export const E_NO_HANDLER = 'E_NO_HANDLER'
export const E_DISCONNECTED = 'E_DISCONNECTED'
/**
- * Undo JSON's `undefined` → `null` mangling on the TOP-LEVEL argument slots.
+ * Wire marker for an `undefined` TOP-LEVEL argument slot.
*
- * `JSON.stringify([a, undefined])` is `[a, null]`: the wire has no `undefined`. So a caller that
- * simply omits a trailing optional argument (`git.history(cwd)`, `worktreeMerge(repo, b, base)`)
- * hands the handler an explicit `null` — and an explicit `null` does NOT trigger a default
- * parameter. `worktreeMerge(…, push = false)` would run with `push === null`.
+ * `JSON.stringify([a, undefined])` is `[a, null]`: raw JSON has no `undefined`. So a caller that
+ * omits a trailing optional argument (`git.history(cwd)`, `worktreeMerge(repo, b, base)`) would
+ * hand the handler an explicit `null` — and an explicit `null` does NOT trigger a default
+ * parameter, so `worktreeMerge(…, push = false)` would run with `push === null` (`git.history`
+ * broke exactly this way once).
*
- * Every such default in the API today is falsy (`push = false`, `pruneOnly = false`, `full = false`),
- * so `null` coerces to the same behavior and nothing breaks — safe BY LUCK. The first `= true`
- * default, or any handler that tests `arg === undefined`, silently reintroduces the bug (`git.history`
- * already broke this way once). Restoring `undefined` here fixes it for every handler at once,
- * instead of asking each new one to remember.
+ * The *decoder* cannot repair that on its own: `null` on the wire is ambiguous between "JSON
+ * mangled an omitted argument" and "the caller meant null". And plenty of methods DO mean it —
+ * `pty.resize(sid, null, null)` is the co-attach PARK signal (drop me from the size ledger),
+ * `presence.cursor/focus/chat/project(null)` clear state, `git.setActiveRemote(null)` clears the
+ * active remote. Guessing `null → undefined` for all of them silently collapsed every co-attached
+ * viewer's shared pty to 1×1.
*
- * Only the top-level slots are touched: a `null` nested inside an object or array is data the sender
- * genuinely meant to send (`{cwd: null}` is not `{}`), and no method in the preload API surface takes
- * a meaningful top-level `null` — which is what makes the substitution safe. Arity is preserved: the
- * slot stays, it just holds `undefined` again.
+ * So the SENDER disambiguates instead: `encodeArgs` replaces each `undefined` slot with this
+ * sentinel, `decodeArgs` turns exactly that sentinel back into `undefined`, and every other value
+ * — `null` included — passes through untouched. Arity is preserved either way. The sentinel is a
+ * NUL-prefixed string: no argument in the API surface can collide with it, and it survives JSON.
+ *
+ * Only top-level slots are marked: a `null`/`undefined` nested inside an object or array is the
+ * sender's own data (`{cwd: null}` is not `{}`), and JSON's own object rules already govern it.
*/
-const decodeArgs = (args: unknown[]): unknown[] => args.map((a) => (a === null ? undefined : a))
+export const RPC_UNDEFINED = '\u0000__rpc_undefined__'
+
+/** Sender side: mark the `undefined` argument slots so the decoder can restore them. */
+export const encodeArgs = (args: unknown[]): unknown[] =>
+ args.map((a) => (a === undefined ? RPC_UNDEFINED : a))
+
+/** Receiver side: restore the marked slots. A `null` stays `null` — it is a real value. */
+const decodeArgs = (args: unknown[]): unknown[] =>
+ args.map((a) => (a === RPC_UNDEFINED ? undefined : a))
export function parseRpcMessage(text: string): RpcMessage | null {
let m: unknown