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): verify pty.destroy's outcome — never answer success over a session still running

enes17493b84eda9
diff --git a/src/main/index.ts b/src/main/index.ts
index b0c67e740..5d893be8f 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -3344,8 +3344,16 @@ app.whenReady().then(async () => {
// (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.
+ //
+ // The kill is VERIFIED before the node comes off the canvas (issue #581): destroySession
+ // swallows its per-step failures by design, so it can resolve having ended nothing — and
+ // removing the node then would strand a live session with no canvas entry pointing at it.
+ // The throw also rides back to the phone as the verb's honest error.
destroyNode: async (nodeId: string) => {
await ptyManager.destroySession(null, nodeId, { everySocket: true })
+ if (await ptyManager.sessionExists(nodeId).catch(() => true)) {
+ throw new Error('The session is still running — the host could not end it.')
+ }
await workspaceStore.removeRemoteNode(nodeId).catch(() => false)
},
// Jail roots beyond the active canvas: the phone browses EVERY project (projects.list), so
diff --git a/src/main/remote/host-destroy-tmux.test.ts b/src/main/remote/host-destroy-tmux.test.ts
new file mode 100644
index 000000000..0cab7849a
--- /dev/null
+++ b/src/main/remote/host-destroy-tmux.test.ts
@@ -0,0 +1,150 @@
+// Issue #581 regression — the relay's `pty.destroy` against a REAL tmux session.
+//
+// The destroy chain (`destroySession` → tmux kill fan-out) swallows its per-step failures by
+// design ("session may not exist on this socket" is a normal case), so the promise resolving
+// proves only that nothing threw. Measured while root-causing #581: a chain that quietly ended
+// NOTHING answered `ok:true`, and the phone — whose alert path only speaks on `ok:false` — had
+// nothing to show over a session that kept running. `handleDestroy` therefore verifies the
+// OUTCOME (`sessionExists` after the destroy must say gone) before answering.
+//
+// This suite runs the verb against tmux for real, on the real `node-terminal` socket with a
+// unique throwaway session name — the same discipline as the canvas-control shim and
+// remote-usage suites (generated side-effects are proven on the real interpreter, not a fake).
+// node-pty stays mocked (suite convention: it is built for Electron's ABI); the pty spawn is
+// irrelevant here — the tmux side-calls and the kill are real subprocesses.
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { execFile } from 'child_process'
+import { promisify } from 'util'
+import { existsSync, promises as fs } from 'fs'
+import os from 'os'
+import path from 'path'
+import { initPlatform, resetPlatformForTests } from '../../core/platform'
+import { fakePlatform } from '../../core/platform-fake'
+import { DEFAULT_SETTINGS } from '../../shared/types'
+import { TMUX_SOCKET, sessionName } from '../../core/tmux-naming'
+import { createHostHandlers, type HostFsOps, type HostRelaySocket } from './host-service'
+
+const run = promisify(execFile)
+// Same fixed candidates findTmux tries first; a machine with tmux elsewhere just skips the suite.
+const TMUX =
+ ['/opt/homebrew/bin/tmux', '/usr/local/bin/tmux', '/usr/bin/tmux'].find((p) => existsSync(p)) ??
+ null
+
+vi.mock('../../core/session-host-backend', async () =>
+ (await import('../../core/__fixtures__/no-session-host')).noSessionHost()
+)
+vi.mock('node-pty', () => ({
+ spawn: () => ({
+ onData: () => {},
+ onExit: () => {},
+ write: () => {},
+ resize: () => {},
+ pause: () => {},
+ resume: () => {},
+ kill: () => {},
+ pid: 4321
+ })
+}))
+vi.mock('../../core/pty-devices', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../../core/pty-devices')>()),
+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })
+}))
+
+describe.skipIf(!TMUX || process.platform === 'win32')(
+ 'pty.destroy against a real tmux session (issue #581)',
+ () => {
+ let userData: string
+ let nodeId: string
+
+ const hasSession = async (): Promise<boolean> => {
+ try {
+ await run(TMUX!, ['-L', TMUX_SOCKET, 'has-session', '-t', `=${sessionName(nodeId)}`])
+ return true
+ } catch {
+ return false
+ }
+ }
+
+ beforeEach(async () => {
+ userData = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-destroy-'))
+ initPlatform(fakePlatform({ userDataDir: userData }))
+ // Unique per run: this socket is the REAL one, shared with whatever else the machine runs.
+ nodeId = `e581-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
+ await run(TMUX!, ['-L', TMUX_SOCKET, 'new-session', '-d', '-s', sessionName(nodeId), 'sleep', '600'])
+ expect(await hasSession()).toBe(true)
+ })
+ afterEach(async () => {
+ resetPlatformForTests()
+ try {
+ await run(TMUX!, ['-L', TMUX_SOCKET, 'kill-session', '-t', `=${sessionName(nodeId)}`])
+ } catch {
+ /* already gone — the expected case */
+ }
+ await fs.rm(userData, { recursive: true, force: true })
+ })
+
+ interface Rig {
+ manager: import('../../core/pty-manager').PtyManager
+ handlers: ReturnType<typeof createHostHandlers>
+ responses: Array<{ id: string; ok: boolean; body: unknown }>
+ }
+
+ // `destroyNode` receives the rig so a test can wire it to the real manager (the production
+ // shape) or to a silent no-op (the #581 shape).
+ async function rig(destroyNode: (id: string, r: Rig) => Promise<void>): Promise<Rig> {
+ const { PtyManager } = await import('../../core/pty-manager')
+ const manager = new PtyManager()
+ manager.init(() => DEFAULT_SETTINGS)
+ const responses: Rig['responses'] = []
+ const socket: HostRelaySocket = {
+ respond: (id, ok, body) => responses.push({ id, ok, body }),
+ sendFrame: () => true
+ }
+ const fsOps: HostFsOps = {
+ listDir: async () => [],
+ readText: async () => '',
+ readBinary: async () => '',
+ writeText: async () => true
+ }
+ const r: Partial<Rig> = { manager, responses }
+ r.handlers = createHostHandlers(
+ manager,
+ socket,
+ fsOps,
+ () => [],
+ async () => '',
+ () => null,
+ undefined,
+ undefined,
+ (id) => destroyNode(id, r as Rig)
+ )
+ return r as Rig
+ }
+
+ async function attachAndDestroy(r: Rig): Promise<void> {
+ r.handlers.onRpc({ id: 'a', method: 'pty.attach', params: { nodeId, cols: 80, rows: 24 } })
+ await vi.waitFor(() => expect(r.responses.length).toBeGreaterThan(0), { timeout: 10_000 })
+ r.handlers.onRpc({ id: 'd', method: 'pty.destroy', params: { streamId: 1 } })
+ await vi.waitFor(() => expect(r.responses.length).toBeGreaterThan(1), { timeout: 15_000 })
+ }
+
+ it('the production wiring kills the real session and answers a verified ok', async () => {
+ const r = await rig((id, { manager }) => manager.destroySession(null, id, { everySocket: true }))
+ await attachAndDestroy(r)
+ expect(r.responses.at(-1)).toMatchObject({ id: 'd', ok: true })
+ expect(await hasSession()).toBe(false)
+ }, 30_000)
+
+ it('a destroy chain that quietly ends NOTHING now answers an honest error (the #581 symptom)', async () => {
+ const r = await rig(async () => {}) // resolves without killing anything — the silent no-op
+ await attachAndDestroy(r)
+ // The REAL session is still running — and the verb now says so instead of `ok:true`.
+ expect(await hasSession()).toBe(true)
+ expect(r.responses.at(-1)).toEqual({
+ id: 'd',
+ ok: false,
+ body: { message: expect.stringContaining('still running') }
+ })
+ }, 30_000)
+ }
+)
diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.ts
index 4d6b9e361..1dba6085f 100644
--- a/src/main/remote/host-service.ts
+++ b/src/main/remote/host-service.ts
@@ -494,6 +494,13 @@ export function createHostHandlers(
* 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.
+ * - The answer is VERIFIED (issue #581). The destroy chain deliberately swallows per-step
+ * failures ("session may not exist on this socket" is a normal case for its kill fan-out), so
+ * `destroyNode` resolving proves only that nothing threw — measured: with tmux unresolved the
+ * whole kill block is skipped and the verb answered success over a session still running. So
+ * the OUTCOME is probed: `sessionExists` after the destroy must say gone. Its fail-safe
+ * direction (unprobeable ⇒ exists) is exactly right here — a destructive verb must not report
+ * success on uncertainty (the `confirmedTmuxSessionExists` rule, applied one layer up).
*/
function handleDestroy(req: RpcRequest): void {
if (!destroyNode) {
@@ -516,7 +523,17 @@ export function createHostHandlers(
pty.kill(null, stream.sessionId)
dropStream(streamId)
void destroyNode(nodeId)
- .then(() => socket.respond(req.id, true, {}))
+ .then(async () => {
+ // Verify the user-visible outcome, not the chain's plumbing: is the session GONE?
+ const stillThere = await pty.sessionExists(nodeId).catch(() => true)
+ if (stillThere) {
+ socket.respond(req.id, false, {
+ message: 'The session is still running — the host could not end it.'
+ })
+ return
+ }
+ socket.respond(req.id, true, {})
+ })
.catch((err: unknown) =>
socket.respond(req.id, false, {
message: (err as Error)?.message ?? 'Could not end the session.'
diff --git a/src/main/remote/remote-security.test.ts b/src/main/remote/remote-security.test.ts
index 9667bcd39..565e507c1 100644
--- a/src/main/remote/remote-security.test.ts
+++ b/src/main/remote/remote-security.test.ts
@@ -416,9 +416,12 @@ describe('pty.destroy ends the session through the injected destroyNode', () =>
expect(pty.kill).not.toHaveBeenCalled()
})
- it('destroys the STREAM’s node (never a client-sent id) and answers ok', async () => {
+ it('destroys the STREAM’s node (never a client-sent id) and answers a VERIFIED ok', async () => {
const { socket, responses, fs, pty } = makeHostFakes()
- const destroyNode = vi.fn(async () => {})
+ // The destroy actually lands: after it, the session no longer exists.
+ const destroyNode = vi.fn(async () => {
+ ;(pty.sessionExists as ReturnType<typeof vi.fn>).mockResolvedValue(false)
+ })
const handlers = createHostHandlers(
pty, socket, fs, () => ['/work'], async () => '', () => null, undefined, undefined, destroyNode
)
@@ -432,6 +435,42 @@ describe('pty.destroy ends the session through the injected destroyNode', () =>
expect(pty.kill).toHaveBeenCalledWith(null, 'sess')
})
+ // Issue #581: `destroyNode` resolving proves only that nothing threw — every per-step failure
+ // inside the destroy chain is swallowed by design, so a chain that quietly ended NOTHING used to
+ // answer success, and the app (which surfaces failures in an alert) had nothing to show over a
+ // session that kept running. The verb now verifies the outcome itself.
+ it('a destroy that resolves while the session still exists answers an honest error, not success', async () => {
+ const { socket, responses, fs, pty } = makeHostFakes()
+ const destroyNode = vi.fn(async () => {}) // resolves — and ends nothing (sessionExists stays true)
+ 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: expect.stringContaining('still running') }
+ })
+ )
+ })
+
+ it('an unprobeable outcome is a failure too — never success on uncertainty', async () => {
+ const { socket, responses, fs, pty } = makeHostFakes()
+ const destroyNode = vi.fn(async () => {
+ ;(pty.sessionExists as ReturnType<typeof vi.fn>).mockRejectedValue(new Error('tmux wedged'))
+ })
+ 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)).toMatchObject({ id: 'd', ok: false })
+ )
+ })
+
it('an unknown streamId is refused without calling destroyNode', () => {
const { socket, responses, fs, pty } = makeHostFakes()
const destroyNode = vi.fn(async () => {})