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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(relay): pty.attach says whether it had to CREATE the session
enes51b300dd02a2
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex dbed0cf4a..3deb161e1 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -1086,6 +1086,21 @@ export class PtyManager {return { controlPath: s.sshRemote.controlPath, conn: s.sshRemote.conn }}+ /**+ * Public read of the probe below, for callers that attach WITHOUT going through `create()` and+ * so never receive its `fresh` flag — today the relay host's `pty.attach` (`host-service.ts`).+ * `attachDetached` spawns through `tmux new-session -A`, which CREATES when the session is+ * gone, so without asking first a mirrored client cannot tell "I joined your live agent" from+ * "I just made you an empty login shell". That is what showed a phone a bare `~ %` prompt+ * under a Claude node's title after the host's tmux server died.+ *+ * Same fail-safe direction as everywhere else here: an unprobeable tmux answers "exists", so+ * the caller treats it as a warm join and types nothing into it.+ */+ async sessionExists(persistKey: string): Promise<boolean> {+ return this.tmuxSessionExists(persistKey)+ }+/** Whether a tmux session for this node id currently exists (server alive + session present).* Async like the remote probe: a bulk project load fires one `create()` per terminal node,* and a synchronous subprocess per probe would serialize on the main event loop. */diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.tsindex 20fe8fa2c..4d19856b3 100644--- a/src/main/remote/host-service.ts+++ b/src/main/remote/host-service.ts@@ -47,6 +47,11 @@ export const API_BASE = process.env.NODETERM_API_BASE || 'https://api.nodeterm.dconst textEncoder = new TextEncoder()const textDecoder = new TextDecoder()+/** How long `pty.attach` waits for the `fresh` probe before answering "warm" and moving on. A+ * local `tmux has-session` is ~10 ms; this only bounds the pathological case, because the probe+ * now precedes the attach response and its own timeout is 6 s. */+const FRESH_PROBE_BUDGET_MS = 750+// --- pure host handlers (RPC/frame <-> pty-manager) -------------------------// The slice of pty-manager the host needs. PtyManager satisfies this; tests pass a fake.@@ -60,6 +65,9 @@ export interface HostPtyManager {): string/** Current visible screen of a node's tmux session, for the attach snapshot. */captureSnapshot(persistKey: string): Promise<string>+ /** Does a tmux session for this node id exist RIGHT NOW? Asked before `attachDetached`, which+ * CREATES one when it doesn't — so the client can tell a warm join from a cold start. */+ sessionExists(persistKey: string): Promise<boolean>/** `clientId` identifies WHO typed (the bridged phone's presence peer), so the keystroke can be* attributed to it — null when this session has no peer, which just means it is not badged. */write(clientId: number | null, sessionId: string, data: string): void@@ -242,10 +250,12 @@ export function createHostHandlers(}/**- * 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).+ * Attach a mirrored terminal to the host's tmux session for `nodeId`: respond with the streamId+ * (and whether the session had to be CREATED — `fresh`), 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) — which is exactly what `fresh` reports,+ * so the client can run its cold restore instead of sitting in a bare login shell.*/function handleAttach(req: RpcRequest): void {const p = asRecord(req.params)@@ -261,14 +271,29 @@ export function createHostHandlers(const stream: Stream = { sessionId: '', persistKey: nodeId, 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).+ // Reserve the stream, then respond 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(() => '')+ // `fresh` — did this attach CREATE the session, or join a live one? It has to be asked BEFORE+ // `attachDetached`, whose `tmux new-session -A` creates when the session is gone; afterwards+ // it always exists and the answer is meaningless. Without it a mirrored client could not tell+ // "I joined your running agent" from "I just made you an empty login shell in $HOME", which is+ // what put a bare `~ %` prompt under a Claude node's title on the phone once the host's tmux+ // server had died. The agent transport has reported this all along; the relay did not.+ //+ // Bounded, and fail-safe toward "warm": a probe that is slow or unprobeable answers `false`,+ // so a client that cold-restores on `fresh` types nothing into a session that may be live.+ // The bound matters because this now precedes the RPC response and `has-session` can sit on+ // the 6 s probe timeout when tmux itself is wedged.+ void (async () => {+ const existed = await Promise.race([+ pty.sessionExists(nodeId).catch(() => true),+ new Promise<boolean>((r) => setTimeout(() => r(true), FRESH_PROBE_BUDGET_MS))+ ])+ socket.respond(req.id, true, { streamId, fresh: !existed })+ return pty.captureSnapshot(nodeId).catch(() => '')+ })().then((snapshot) => {// The stream may have been killed/closed while the capture was in flight.if (!streams.has(streamId)) returndiff --git a/src/main/remote/remote-security.test.ts b/src/main/remote/remote-security.test.tsindex f669052a2..8506be989 100644--- a/src/main/remote/remote-security.test.ts+++ b/src/main/remote/remote-security.test.ts@@ -33,6 +33,8 @@ function makeHostFakes() {createDetached: vi.fn(() => 'sess'),attachDetached: vi.fn(() => 'sess'),captureSnapshot: vi.fn(async () => ''),+ // Asked before every attach so the client learns whether the session had to be created.+ sessionExists: vi.fn(async () => true),write: vi.fn(),resize: vi.fn(),setFlow: vi.fn(),@@ -214,6 +216,54 @@ describe('R3: replayed encrypted frames are dropped', () => {})})+// `attachDetached` goes through `tmux new-session -A`, so an attach to a node whose tmux session+// is gone CREATES a bare login shell in $HOME. Without being told, a mirrored client showed that+// empty shell under the node's own title — a phone tapping a Claude session after the host's tmux+// server died got `~ %` and no agent. The attach reply now says which happened, so the client can+// run its cold restore (cd + `claude --resume`) instead.+describe('pty.attach reports whether it had to CREATE the session', () => {+ const attach = (handlers: ReturnType<typeof createHostHandlers>): void => {+ handlers.onRpc({ id: 'a', method: 'pty.attach', params: { nodeId: 'node-a', cols: 80, rows: 24 } })+ }+ const reply = async (responses: unknown[]): Promise<Record<string, unknown>> => {+ // The probe precedes the response, so let the microtasks settle.+ await vi.waitFor(() => expect(responses.length).toBeGreaterThan(0))+ return responses.at(-1) as Record<string, unknown>+ }++ it('reports fresh=false when the session is already live (a warm join types nothing)', async () => {+ const { socket, responses, fs, pty } = makeHostFakes()+ ;(pty.sessionExists as ReturnType<typeof vi.fn>).mockResolvedValue(true)+ attach(createHostHandlers(pty, socket, fs, () => ['/work']))+ expect(await reply(responses)).toMatchObject({ ok: true, body: { fresh: false } })+ })++ it('reports fresh=true when the session is gone, so the client cold-restores', async () => {+ const { socket, responses, fs, pty } = makeHostFakes()+ ;(pty.sessionExists as ReturnType<typeof vi.fn>).mockResolvedValue(false)+ attach(createHostHandlers(pty, socket, fs, () => ['/work']))+ expect(await reply(responses)).toMatchObject({ ok: true, body: { fresh: true } })+ })++ it('a probe that throws answers WARM — never invent a cold start over a live agent', async () => {+ const { socket, responses, fs, pty } = makeHostFakes()+ ;(pty.sessionExists as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('tmux wedged'))+ attach(createHostHandlers(pty, socket, fs, () => ['/work']))+ expect(await reply(responses)).toMatchObject({ ok: true, body: { fresh: false } })+ })++ it('asks BEFORE attaching — after `new-session -A` the answer is always "exists"', async () => {+ const { socket, responses, fs, pty } = makeHostFakes()+ ;(pty.sessionExists as ReturnType<typeof vi.fn>).mockResolvedValue(false)+ attach(createHostHandlers(pty, socket, fs, () => ['/work']))+ await reply(responses)+ const probedAt = (pty.sessionExists as ReturnType<typeof vi.fn>).mock.invocationCallOrder[0]+ await vi.waitFor(() => expect(pty.attachDetached).toHaveBeenCalled())+ const attachedAt = (pty.attachDetached as ReturnType<typeof vi.fn>).mock.invocationCallOrder[0]+ expect(probedAt).toBeLessThan(attachedAt)+ })+})+// Scrolling belongs to tmux (mouse on, alternate screen), and the phone cannot deliver the wheel// itself — its emulator swallows the gesture — so it asks the host to write it into the stream's// pty, which IS a tmux client. `lines` and the stream target both come off the wire.diff --git a/test/remote/host-handlers.test.ts b/test/remote/host-handlers.test.tsindex 4fc68e7c4..9d502c8e1 100644--- a/test/remote/host-handlers.test.ts+++ b/test/remote/host-handlers.test.ts@@ -15,6 +15,7 @@ function fakePty() {let lastOptions: PtyCreateOptions | null = nulllet counter = 0let snapshot = ''+ let sessionLive = trueconst mgr: HostPtyManager = {createDetached(options, sinks) {lastOptions = options@@ -33,6 +34,10 @@ function fakePty() {calls.push({ method: 'captureSnapshot', args: [persistKey] })return snapshot},+ sessionExists: async (persistKey) => {+ calls.push({ method: 'sessionExists', args: [persistKey] })+ return sessionLive+ },write: (clientId, sessionId, data) =>calls.push({ method: 'write', args: [clientId, sessionId, data] }),resize: (clientId, sessionId, cols, rows) =>@@ -50,6 +55,9 @@ function fakePty() {options: () => lastOptions!,setSnapshot: (s: string) => {snapshot = s+ },+ setSessionLive: (live: boolean) => {+ sessionLive = live}}}@@ -104,10 +112,15 @@ describe('createHostHandlers', () => {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 } }])+ // The stream is reserved SYNCHRONOUSLY — that, not the timing of the response, is what lets+ // the host route this streamId's inbound frames right away. The response itself now waits on+ // the `fresh` probe (a tmux side-call), because whether the attach CREATED the session has to+ // be asked before `attachDetached` does it.+ h.onFrame({ op: OP.Input, streamId: 1, seq: 0, payload: new TextEncoder().encode('x') })+ expect(pty.calls.some((c) => c.method === 'write')).toBe(true)// Capture + attach are async (a tmux side-call).await new Promise((r) => setTimeout(r, 0))+ expect(sock.responses).toEqual([{ id: 'r1', ok: true, body: { streamId: 1, fresh: false } }])expect(pty.calls).toContainEqual({ method: 'captureSnapshot', args: ['node-9'] })expect(pty.calls).toContainEqual({@@ -128,6 +141,28 @@ describe('createHostHandlers', () => {expect(Buffer.from(out!.payload).toString('utf8')).toBe('live')})+ // A node whose tmux session died (host reboot, tmux server gone) still ATTACHES — the client+ // needs a live pane to type its cold restore (`cd <cwd>; claude --resume <id>`) into, exactly as+ // the SSH path gets one from `tmux new-session -A`. What changed is that the reply now SAYS it+ // was a cold start, so the client runs that restore instead of presenting the bare login shell+ // under the node's title, which is what a phone saw as `~ %` on a Claude session.+ it('still creates on a cold node, but reports fresh=true so the client can restore', async () => {+ const pty = fakePty()+ pty.setSessionLive(false)+ const sock = fakeSocket()+ const h = createHostHandlers(pty.mgr, sock.socket)++ h.onRpc({ id: 'r1', method: 'pty.attach', params: { nodeId: 'cold-1', cols: 80, rows: 24 } })+ await new Promise((r) => setTimeout(r, 0))++ expect(sock.responses).toEqual([{ id: 'r1', ok: true, body: { streamId: 1, fresh: true } }])+ // Deliberately NOT a refusal: refusing would leave the client with nowhere to resume.+ expect(pty.calls).toContainEqual({+ method: 'attachDetached',+ args: ['cold-1', 'pty-1', { cols: 80, rows: 24 }]+ })+ })+it('attach sends an empty snapshot when the session has no current screen', async () => {const pty = fakePty() // snapshot defaults to ''const sock = fakeSocket()