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): honest pty.kill errors + a real pty.destroy so the phone can end a session

enese170ae08802c
diff --git a/src/core/project-node-append.test.ts b/src/core/project-node-append.test.ts
index 4db3e744f..4bcf125db 100644
--- a/src/core/project-node-append.test.ts
+++ b/src/core/project-node-append.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { appendProjectNode } from './project-node-append'
+import { appendProjectNode, removeProjectNode } from './project-node-append'
const NOW = new Date('2026-07-16T10:00:00.000Z')
@@ -180,3 +180,44 @@ describe('appendProjectNode', () => {
expect(f.nodes[0].agentId).toBeUndefined()
})
})
+
+describe('removeProjectNode', () => {
+ const two = [sibling, { ...sibling, id: 'term-bbb-2', ssh: undefined, sshRemoteTmux: undefined }]
+
+ it('removes the node, bumps rev, refreshes savedAt', () => {
+ const out = removeProjectNode(baseFile(two), 'term-aaa-1', NOW)
+ expect(out).not.toBeNull()
+ const f = JSON.parse(out!)
+ expect(f.rev).toBe(8)
+ expect(f.savedAt).toBe('2026-07-16T10:00:00.000Z')
+ expect(f.nodes.map((n: { id: string }) => n.id)).toEqual(['term-bbb-2'])
+ })
+
+ it('round-trips every field it does not know (bridges, kanban, future schema)', () => {
+ const extra = {
+ bridges: [{ from: 'term-aaa-1', to: 'term-bbb-2' }],
+ kanban: { columns: [], assignments: [{ nodeId: 'term-aaa-1', columnId: 'c1' }] },
+ futureField: { keep: true }
+ }
+ const f = JSON.parse(removeProjectNode(baseFile(two, extra), 'term-aaa-1', NOW)!)
+ // Dangling references are deliberately left for their readers' lazy pruning (same as a
+ // desktop delete) — removal must not reinterpret parts of the file it does not own.
+ expect(f.bridges).toEqual(extra.bridges)
+ expect(f.kanban).toEqual(extra.kanban)
+ expect(f.futureField).toEqual(extra.futureField)
+ expect(f.viewport).toEqual({ x: 1, y: 2, zoom: 0.5 })
+ })
+
+ it('answers null for a node id not in this file — "try the next project", no rev churn', () => {
+ expect(removeProjectNode(baseFile(two), 'term-zzz-9', NOW)).toBeNull()
+ expect(removeProjectNode(baseFile([]), 'term-aaa-1', NOW)).toBeNull()
+ })
+
+ it('refuses: bad JSON / wrong shape / wrong version / empty id — never invents a file', () => {
+ expect(removeProjectNode('{ not json', 'term-aaa-1', NOW)).toBeNull()
+ expect(removeProjectNode('[1,2]', 'term-aaa-1', NOW)).toBeNull()
+ expect(removeProjectNode('{"version":99,"rev":1,"nodes":[]}', 'term-aaa-1', NOW)).toBeNull()
+ expect(removeProjectNode('{"version":1}', 'term-aaa-1', NOW)).toBeNull()
+ expect(removeProjectNode(baseFile(two), '', NOW)).toBeNull()
+ })
+})
diff --git a/src/core/project-node-append.ts b/src/core/project-node-append.ts
index 9299ee673..0137afb7d 100644
--- a/src/core/project-node-append.ts
+++ b/src/core/project-node-append.ts
@@ -141,3 +141,35 @@ export function appendProjectNode(raw: string, input: RemoteNodeInput, now: Date
root.savedAt = now.toISOString()
return JSON.stringify(root, null, 2)
}
+
+/**
+ * Pure removal of a node from a project.json's raw text — the host side of the relay
+ * `pty.destroy` verb ("End session" on the phone), mirroring what the desktop's × does to the
+ * canvas after `transport.destroy`. Same raw-object discipline as `appendProjectNode`: every
+ * field this version does not know round-trips untouched, and dangling references the node may
+ * leave behind (kanban assignments, bridges, ropes) are deliberately NOT chased here — their
+ * readers already tolerate and lazily prune dead ids, exactly as they do after a desktop delete.
+ *
+ * Returns null whenever nothing must be written: unparsable/wrong-shape text (a file we couldn't
+ * parse must never be invented or overwritten), or a node id that simply isn't in this file —
+ * which is an ANSWER (try the next project), not an error.
+ */
+export function removeProjectNode(raw: string, nodeId: string, now: Date): string | null {
+ if (typeof nodeId !== 'string' || !nodeId) return null
+ let root: Record<string, unknown>
+ try {
+ const parsed: unknown = JSON.parse(raw)
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null
+ root = parsed as Record<string, unknown>
+ } catch {
+ return null
+ }
+ if (root.version !== 1 || typeof root.rev !== 'number' || !Array.isArray(root.nodes)) return null
+ const nodes = root.nodes as Array<Record<string, unknown>>
+ if (!nodes.some((n) => n?.id === nodeId)) return null
+
+ root.nodes = nodes.filter((n) => n?.id !== nodeId)
+ root.rev = (root.rev as number) + 1
+ root.savedAt = now.toISOString()
+ return JSON.stringify(root, null, 2)
+}
diff --git a/src/core/workspace-store.test.ts b/src/core/workspace-store.test.ts
index 9ade0ad2c..58405a03a 100644
--- a/src/core/workspace-store.test.ts
+++ b/src/core/workspace-store.test.ts
@@ -630,6 +630,44 @@ describe('appendRemoteNode (phone-registered sessions over the relay)', () => {
})
})
+describe('removeRemoteNode (the phone\'s "End session" over the relay)', () => {
+ it('finds the node by SCAN (no projectId on the wire), removes it and broadcasts the change', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot })]))
+ fake.sent.length = 0
+ expect(await store.removeRemoteNode('term-1')).toBe(true)
+ const file = path.join(projRoot, '.nodeterm/project.json')
+ const raw = await fs.readFile(file, 'utf-8')
+ const f = JSON.parse(raw)
+ expect(f.rev).toBe(2)
+ expect(f.nodes).toEqual([])
+ // Recorded as OUR write + announced explicitly, exactly like appendRemoteNode.
+ expect(store.isSelfWrite(file, raw)).toBe(true)
+ const broadcast = fake.sent.filter((s) => s.channel === 'workspace:external-change')
+ expect(broadcast).toHaveLength(1)
+ expect(broadcast[0].args[0]).toMatchObject({ id: 'p1', cwd: projRoot })
+ expect(broadcast[0].args[0].nodes).toEqual([])
+ })
+
+ it('a node in no local project answers false with nothing written (unregistered phone session)', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([project({ cwd: projRoot })]))
+ const file = path.join(projRoot, '.nodeterm/project.json')
+ const before = await fs.readFile(file, 'utf-8')
+ expect(await store.removeRemoteNode('term-nope-1')).toBe(false)
+ expect(await fs.readFile(file, 'utf-8')).toBe(before) // untouched, no rev churn
+ })
+
+ it('skips ssh and inline entries — their files are not on this machine / do not exist', async () => {
+ const store = new WorkspaceStore()
+ await store.save(ws([
+ project({ id: 'ssh1', ssh: { server: { host: 'h', user: 'u' } as never, remoteCwd: '~/x' }, cwd: undefined }),
+ project({ id: 'inline1' })
+ ]))
+ expect(await store.removeRemoteNode('term-1')).toBe(false)
+ })
+})
+
describe('refreshSshProject', () => {
const sshConn = { server: { host: 'h', user: 'u' } as any, remoteCwd: '~/app' }
const remoteFileOf = async (store: WorkspaceStore, p: Project) => {
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index 5c9de44c2..d8f310346 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -24,7 +24,7 @@ import { readProjectCapabilities, type ProjectCapability } from '../shared/proje
import type { CapabilityAckMap } from './project-capability-consent'
import { hoistLegacyNodeExec, type LocalNodeExecMap } from '../shared/node-exec'
import { collisionSeed, derivedProjectId, freshProjectId } from '../shared/project-id'
-import { appendProjectNode, type RemoteNodeInput } from './project-node-append'
+import { appendProjectNode, removeProjectNode, type RemoteNodeInput } from './project-node-append'
/** Checked remote read: `absent` (no file — safe to push our cache) is NOT `error` (connection
* down / ssh failure — a failed read is never evidence of absence, so nothing may be pushed). */
@@ -1316,6 +1316,64 @@ export class WorkspaceStore {
return true
}
+ /**
+ * Takes a DESTROYED session's node off its project's canvas — the host side of the relay
+ * `pty.destroy` verb ("End session" on the phone), run AFTER the tmux kill so the file only ever
+ * loses a node whose session is already gone. Node ids are globally unique (they are tmux
+ * session names), so the node is looked up by SCAN across the local ref projects — the phone
+ * addresses sessions by streamId→nodeId and knows no projectId. Same v1 scope and the same
+ * announce-and-record discipline as `appendRemoteNode` above, and queued on `saveChain` for the
+ * same read-modify-write reason. A node found in NO file is an answer (an unregistered phone
+ * session, an inline project), not an error: the caller treats false as "nothing to remove".
+ */
+ removeRemoteNode(nodeId: string, now = new Date()): Promise<boolean> {
+ const run = this.saveChain.then(() => this.removeRemoteNodeNow(nodeId, now))
+ this.saveChain = run.catch(() => {})
+ return run
+ }
+
+ private async removeRemoteNodeNow(nodeId: string, now: Date): Promise<boolean> {
+ for (const e of this.index?.entries ?? []) {
+ // Local ref projects only, like appendRemoteNode: an ssh ref's file lives on another
+ // machine (and a relay `pty.attach` only ever reaches THIS machine's tmux anyway).
+ if (!e.cwd || e.ssh) continue
+ const file = projectFilePath(e.cwd)
+ let raw: string
+ try {
+ raw = await fs.readFile(file, 'utf-8')
+ } catch {
+ continue
+ }
+ const updated = removeProjectNode(raw, nodeId, now)
+ if (updated === null) continue // not in this project (or unreadable file) — keep looking
+ try {
+ await writeAtomic(file, updated)
+ } catch {
+ return false
+ }
+ this.lastWritten.set(file, updated)
+ try {
+ const parsed = JSON.parse(updated) as ProjectFileV1
+ this.revs.set(e.id, parsed.rev)
+ platform().broadcast(
+ IPC.workspaceExternalChange,
+ fileToProject(parsed, {
+ id: e.id,
+ cwd: e.cwd,
+ closed: e.closed,
+ viewport: e.viewport,
+ defaultAccountId: e.defaultAccountId,
+ breadcrumbs: e.breadcrumbs,
+ capabilityAck: e.capabilityAck,
+ localExec: e.localExec
+ })
+ )
+ } catch { /* the file is written and cached; the next load/poll drops the node */ }
+ return true
+ }
+ return false
+ }
+
/**
* The mirror write for one ssh entry, with the server's own additions rescued first.
*
diff --git a/src/main/index.ts b/src/main/index.ts
index 69cd84334..8b025a669 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -3310,6 +3310,16 @@ app.whenReady().then(async () => {
projectId: string,
node: { id: string; title?: string; agentId?: string; accountId?: string }
) => workspaceStore.appendRemoteNode(projectId, node),
+ // "End session" from the phone (`pty.destroy`): the SAME two steps the desktop × performs —
+ // kill the tmux session on every socket it could live on (the sweep may have seen it on either
+ // — see the session-memory panel's kill rule), then take the node off its project's canvas
+ // (written as an outside edit, so the watcher broadcasts it and the canvas drops the node
+ // live). Node removal is best-effort by design: an unregistered phone session or an inline
+ // project has no file entry to remove, and that must not fail a destroy that already landed.
+ destroyNode: async (nodeId: string) => {
+ await ptyManager.destroySession(null, nodeId, { everySocket: true })
+ await workspaceStore.removeRemoteNode(nodeId).catch(() => false)
+ },
// Jail roots beyond the active canvas: the phone browses EVERY project (projects.list), so
// its fs/git access spans every local project root — not just the tab the desktop happens
// to have focused (that gap read as "cwd is outside the shared project roots" on the phone).
diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.ts
index a1c535517..4d6b9e361 100644
--- a/src/main/remote/host-service.ts
+++ b/src/main/remote/host-service.ts
@@ -12,7 +12,10 @@
// - `OP.Input` frame -> `write(sessionId, <utf-8 payload>)`
// - `OP.Resize` frame -> `resize(sessionId, cols, rows)` (payload = 2x uint16 LE)
// - RPC `pty.kill {streamId}` -> `kill(null, sessionId)` (null = the relay owns this pty; it has
-// no UI subscribers, so dropping its sinks releases it)
+// no UI subscribers, so dropping its sinks releases it — the tmux session keeps running)
+// - 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.
//
@@ -24,6 +27,7 @@ import { randomUUID } from 'crypto'
import path from 'path'
import { app, ipcMain, type BrowserWindow } from 'electron'
import { IPC } from '../../shared/ipc'
+import { REF_MAX_LEN } from '../../shared/presence'
import type { CanvasMutation, CanvasState, DirEntry, PtyCreateOptions } from '../../shared/types'
import type { AgentId } from '../../shared/agents/config'
import { PtyManager, type DetachedSinks } from '../../core/pty-manager'
@@ -191,7 +195,12 @@ export function createHostHandlers(
git?: HostGitOps,
// Registers a phone-started session as a project node (WorkspaceStore.appendRemoteNode).
// Absent ⇒ `projects.registerNode` is not served.
- registerNode?: (projectId: string, node: RemoteNodeInput) => Promise<boolean>
+ registerNode?: (projectId: string, node: RemoteNodeInput) => Promise<boolean>,
+ // Permanently ends a node's session + removes the node from its canvas — the phone's
+ // "End session" (`pty.destroy`), reaching the SAME path as the desktop ×
+ // (`destroySession(…, {everySocket:true})` + node removal). Absent ⇒ `pty.destroy` is not
+ // served, which is what an un-wired context (and every pre-feature test fake) should say.
+ destroyNode?: (nodeId: string) => Promise<void>
): HostHandlers {
// streamId -> Stream. PTY callbacks close over their own `streamId` directly, so no
// reverse (sessionId -> streamId) index is needed.
@@ -464,13 +473,57 @@ export function createHostHandlers(
function handleKill(req: RpcRequest): void {
const streamId = num(asRecord(req.params).streamId, -1)
const stream = streams.get(streamId)
- if (stream) {
- pty.kill(null, stream.sessionId)
- dropStream(streamId)
+ // An unknown streamId is an honest error, not a silent success: answering `true` here hid
+ // every failure on this path from the client (issue #374) — the app had nothing to surface.
+ if (!stream) {
+ socket.respond(req.id, false, { message: 'Unknown streamId.' })
+ return
}
+ pty.kill(null, stream.sessionId)
+ dropStream(streamId)
socket.respond(req.id, true, {})
}
+ /**
+ * The phone's "End session": permanently end the stream's tmux session and remove its node from
+ * the canvas, via the injected `destroyNode` — the same path the desktop × takes. Three rules:
+ * - The target is the STREAM's `persistKey`, never a client-sent node id: a client can only
+ * destroy a session it has actually attached to (post-approval), the same envelope every
+ * other session-scoped RPC here lives in.
+ * - The viewer is dropped in the SAME synchronous turn as the destroy begins (the R4 adjacency
+ * rule): a late Input frame must never be written into a session on its way out.
+ * - The answer is honest. `destroyNode` absent, an unknown streamId, or a failed destroy all
+ * respond `ok:false` with a message the phone can show — never an unconditional success.
+ */
+ function handleDestroy(req: RpcRequest): void {
+ if (!destroyNode) {
+ socket.respond(req.id, false, { message: 'pty.destroy is not served on this host.' })
+ return
+ }
+ const streamId = num(asRecord(req.params).streamId, -1)
+ const stream = streams.get(streamId)
+ if (!stream) {
+ socket.respond(req.id, false, { message: 'Unknown streamId.' })
+ return
+ }
+ // Same cap the desktop wire applies to a client-supplied node id (endFromClient/REF_MAX_LEN):
+ // the key was client-chosen at attach time and a destroy kills things — refuse, never truncate.
+ if (stream.persistKey.length > REF_MAX_LEN) {
+ socket.respond(req.id, false, { message: 'Invalid node id.' })
+ return
+ }
+ const nodeId = stream.persistKey
+ pty.kill(null, stream.sessionId)
+ dropStream(streamId)
+ void destroyNode(nodeId)
+ .then(() => socket.respond(req.id, true, {}))
+ .catch((err: unknown) =>
+ socket.respond(req.id, false, {
+ message: (err as Error)?.message ?? 'Could not end the session.'
+ })
+ )
+ }
+
return {
onRpc(req) {
switch (req.method) {
@@ -486,6 +539,9 @@ export function createHostHandlers(
case 'pty.kill':
handleKill(req)
break
+ case 'pty.destroy':
+ handleDestroy(req)
+ break
case 'pty.scroll':
handleScroll(req)
break
@@ -729,6 +785,9 @@ export interface HostSessionOptions {
git?: HostGitOps
/** Registers a phone-started session as a project node (`projects.registerNode`). Optional. */
registerNode?: (projectId: string, node: RemoteNodeInput) => Promise<boolean>
+ /** Permanently ends a node's session + removes the node (`pty.destroy`). Optional: absent ⇒
+ * the verb answers with an honest "not served" error. */
+ destroyNode?: (nodeId: string) => Promise<void>
/** Extra fs/git jail roots beyond the shared canvas's node cwds — production passes the
* workspace's local project cwds: the phone browses EVERY project over `projects.list`, so a
* canvas-only jail denied whichever project the desktop didn't happen to have focused. */
@@ -849,7 +908,8 @@ export function connectHostSession(opts: HostSessionOptions): HostSession {
opts.listProjects ?? (async () => ''),
opts.getClientId ?? (() => null),
opts.git,
- opts.registerNode
+ opts.registerNode,
+ opts.destroyNode
)
canvasSync = createHostCanvasSync(socket, opts.applyMutation)
unsubCanvas = opts.subscribeCanvas(() => scheduleBroadcast())
@@ -869,6 +929,9 @@ export function connectHostSession(opts: HostSessionOptions): HostSession {
export interface HostBridgeDeps {
git?: HostGitOps
registerNode?: (projectId: string, node: { id: string; title?: string; agentId?: string }) => Promise<boolean>
+ /** The phone's "End session" (`pty.destroy`): destroy the tmux session on every socket it could
+ * live on + take the node off its project's canvas — the desktop ×'s two steps. */
+ destroyNode?: (nodeId: string) => Promise<void>
/** Workspace-level jail roots (local project cwds) merged with the canvas node cwds. */
workspaceRoots?: () => string[]
}
@@ -939,6 +1002,7 @@ export function initRemoteHost(
listProjects,
git: bridge.git,
registerNode: bridge.registerNode,
+ destroyNode: bridge.destroyNode,
extraRoots: bridge.workspaceRoots,
// Typing attribution: this session's input frames are this phone's keystrokes.
getClientId: () => phone.id(),
diff --git a/src/main/remote/remote-security.test.ts b/src/main/remote/remote-security.test.ts
index 17a47358c..9667bcd39 100644
--- a/src/main/remote/remote-security.test.ts
+++ b/src/main/remote/remote-security.test.ts
@@ -371,3 +371,115 @@ describe('R4: a killed stream stops accepting input in the same turn', () => {
expect(writeMock).not.toHaveBeenCalled()
})
})
+
+// --- pty.kill honesty + pty.destroy (issue #374) ------------------------------
+
+// `pty.kill` used to answer `true` unconditionally — including when no stream matched — so every
+// failure on that path was invisible to the client. And no relay method could END a session at
+// all: `pty.kill` only drops the viewer (tmux keeps running, by design), while the desktop's
+// "End session" is `destroySession(…, {everySocket:true})` + node removal. `pty.destroy` now
+// reaches that path through an injected `destroyNode`, honestly refused when un-wired.
+
+describe('pty.kill answers honestly', () => {
+ it('an unknown streamId is an error, not a silent success', () => {
+ const { socket, responses, fs, pty } = makeHostFakes()
+ const handlers = createHostHandlers(pty, socket, fs, () => ['/work'])
+ handlers.onRpc({ id: '1', method: 'pty.kill', params: { streamId: 99 } })
+ expect(pty.kill).not.toHaveBeenCalled()
+ expect(responses).toEqual([
+ { id: '1', ok: false, body: { message: expect.stringContaining('Unknown streamId') } }
+ ])
+ })
+
+ it('a live stream still kills the viewer and answers ok', async () => {
+ const { socket, responses, fs, pty } = makeHostFakes()
+ const handlers = createHostHandlers(pty, socket, fs, () => ['/work'])
+ await attachStream(handlers, 'node-a')
+ handlers.onRpc({ id: 'k', method: 'pty.kill', params: { streamId: 1 } })
+ expect(pty.kill).toHaveBeenCalledWith(null, 'sess')
+ expect(responses.at(-1)).toMatchObject({ id: 'k', ok: true })
+ })
+})
+
+describe('pty.destroy ends the session through the injected destroyNode', () => {
+ it('is honestly refused when no destroyNode is wired (old/partial hosts)', async () => {
+ const { socket, responses, fs, pty } = makeHostFakes()
+ const handlers = createHostHandlers(pty, socket, fs, () => ['/work'])
+ await attachStream(handlers, 'node-a')
+ handlers.onRpc({ id: 'd', method: 'pty.destroy', params: { streamId: 1 } })
+ expect(responses.at(-1)).toEqual({
+ id: 'd',
+ ok: false,
+ body: { message: expect.stringContaining('not served') }
+ })
+ // The refusal must not have touched the stream either.
+ expect(pty.kill).not.toHaveBeenCalled()
+ })
+
+ it('destroys the STREAM’s node (never a client-sent id) and answers ok', async () => {
+ const { socket, responses, fs, pty } = makeHostFakes()
+ const destroyNode = vi.fn(async () => {})
+ const handlers = createHostHandlers(
+ pty, socket, fs, () => ['/work'], async () => '', () => null, undefined, undefined, destroyNode
+ )
+ await attachStream(handlers, 'node-a')
+ // A hostile nodeId param rides along — it must be ignored in favor of the stream's own key.
+ handlers.onRpc({ id: 'd', method: 'pty.destroy', params: { streamId: 1, nodeId: 'victim' } })
+ await vi.waitFor(() => expect(responses.at(-1)).toMatchObject({ id: 'd', ok: true }))
+ expect(destroyNode).toHaveBeenCalledTimes(1)
+ expect(destroyNode).toHaveBeenCalledWith('node-a')
+ // The viewer is dropped like pty.kill does — the destroy ends the underlying session.
+ expect(pty.kill).toHaveBeenCalledWith(null, 'sess')
+ })
+
+ it('an unknown streamId is refused without calling destroyNode', () => {
+ const { socket, responses, fs, pty } = makeHostFakes()
+ const destroyNode = vi.fn(async () => {})
+ const handlers = createHostHandlers(
+ pty, socket, fs, () => ['/work'], async () => '', () => null, undefined, undefined, destroyNode
+ )
+ handlers.onRpc({ id: 'd', method: 'pty.destroy', params: { streamId: 42 } })
+ expect(destroyNode).not.toHaveBeenCalled()
+ expect(responses).toEqual([
+ { id: 'd', ok: false, body: { message: expect.stringContaining('Unknown streamId') } }
+ ])
+ })
+
+ it('a failed destroy is an honest error carrying the reason', async () => {
+ const { socket, responses, fs, pty } = makeHostFakes()
+ const destroyNode = vi.fn(async () => {
+ throw new Error('tmux kill-session failed')
+ })
+ const handlers = createHostHandlers(
+ pty, socket, fs, () => ['/work'], async () => '', () => null, undefined, undefined, destroyNode
+ )
+ await attachStream(handlers, 'node-a')
+ handlers.onRpc({ id: 'd', method: 'pty.destroy', params: { streamId: 1 } })
+ await vi.waitFor(() =>
+ expect(responses.at(-1)).toEqual({
+ id: 'd',
+ ok: false,
+ body: { message: 'tmux kill-session failed' }
+ })
+ )
+ })
+
+ it('R4 adjacency: a late Input frame after pty.destroy is dropped, even while destroy is in flight', async () => {
+ const { socket, fs, pty } = makeHostFakes()
+ const writeMock = pty.write as ReturnType<typeof vi.fn>
+ // A destroyNode that never resolves inside the test window — the drop must not wait for it.
+ const destroyNode = vi.fn(() => new Promise<void>(() => {}))
+ const handlers = createHostHandlers(
+ pty, socket, fs, () => ['/work'], async () => '', () => null, undefined, undefined, destroyNode
+ )
+ await attachStream(handlers, 'node-a')
+ handlers.onFrame(inputFrame(1, 'echo live\n'))
+ expect(writeMock).toHaveBeenCalledWith(null, 'sess', 'echo live\n')
+ writeMock.mockClear()
+
+ const late = Promise.resolve().then(() => handlers.onFrame(inputFrame(1, 'echo late\n')))
+ handlers.onRpc({ id: 'd', method: 'pty.destroy', params: { streamId: 1 } })
+ await late
+ expect(writeMock).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/main/remote/standing-host.ts b/src/main/remote/standing-host.ts
index 6db4a99b8..d0303b385 100644
--- a/src/main/remote/standing-host.ts
+++ b/src/main/remote/standing-host.ts
@@ -335,6 +335,7 @@ export function initStandingHost(
listProjects,
git: bridge.git,
registerNode: bridge.registerNode,
+ destroyNode: bridge.destroyNode,
extraRoots: bridge.workspaceRoots,
// Typing attribution: this pooled session's input frames are ITS phone's keystrokes.
getClientId: () => pooled.presence.id(),