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(ssh): a node delete reaches the host without a live client
enes42e4f7792e54
diff --git a/CLAUDE.md b/CLAUDE.mdindex 7bbde2e50..a520cd312 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -620,6 +620,37 @@ Lifecycle, by intent:- **User clicks ×** → `destroy(persistKey)` runs `tmux kill-session`, permanently ending it. For aREMOTE node it kills the remote session **and then the local one of the same name** — normally ano-op, but it reaps the orphan the pre-`requireRemote` local fallback below could leave behind.+ **Whether a node IS remote is answered WITHOUT a live session** (`core/remote-end.ts`,+ `planRemoteEnd`). `runEndSession` used to read it off the dying `Session` alone+ (`dying?.sshRemote`), and its comment claimed "both callers run while the session is still live"+ — which is false for the case that matters: a delete arrives precisely when there may be nothing+ attached (an app restart, the offscreen release, the 5-min park expiry, a project that is not+ even open). `dying` was then `undefined`, remoteness read as "local", the remote branch was+ skipped **in silence**, and the one kill that went out went to the LOCAL socket, where a+ `requireRemote` node has nothing at all. Everything else about the teardown ran, so the node left+ the canvas looking deleted while its `nt-<id>` kept running on the host — a leak with no surface+ anywhere. The durable answer is the machine-local index: the shell wires+ `PtyManager.setRemoteNodeOwner` to `workspaceStore.sshProjectIdForNode` + that project's+ ControlMaster (`refForProject`). A LIVE `sshRemote` still wins when there is one — it is the exact+ master the session was spawned over, and a node created seconds ago may not be in the index cache+ yet — so the two sources are complementary, not redundant. The Server Edition wires no resolver+ (it has no SSH-project manager) and its deletes stay on the local path unchanged.+ **And the kill is CHECKED.** The old `catch {}` read "remote session may not exist / master down;+ ignore", which are not the same fact: tmux's own exit 1 ("can't find session", `probeSaysAbsent`)+ is an ANSWER, while ssh's 255 / a 127 / a spawn error is a NON-answer with the session still+ running. A non-answer — and a node whose project has no master at all — is **recorded**+ (`core/pending-remote-kills.ts`, atomic JSON under userData, keyed by `user@host` because several+ projects share one host's tmux server) and settled the next time that host connects+ (`SshProjectManager.settleOwedKills`, hung on the shared connect attempt so the REUSE branch pays+ too; an entry is dropped only on tmux exit 0 or 1). The delete itself is **never refused** over an+ unreachable host: the node is going, and a refusal strands it on the canvas with the same session+ still running plus a dialog — the user answers that by deleting it again. That trade is only+ defensible BECAUSE the debt is durable; drop the store and refusing becomes the honest option.+ **Only a `delete` may owe a debt.** A `recycle` keeps the node (worktree move, model switch,+ "pause & end session"), so a kill deferred to a later reconnect would land on the session that+ node has since RESPAWNED under the same name — ending live work hours after the action that+ queued it, with nothing on screen connecting the two. A recycle still ATTEMPTS the remote kill;+ it just records nothing when it cannot land, exactly as before.- **A remote node is NEVER spawned locally** (`PtyCreateOptions.requireRemote`). `sshRemote` says"here is the master to run over"; `requireRemote` says "and if there isn't one, spawn NOTHING".Without it, a create with no `sshRemote` falls through to core's local tmux/plain-shell branchesdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 65aef4472..19f60ec10 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -168,6 +168,23 @@ reporting "no sessions" on a host running thirty.never a substituted nearest match. A hand-editable value that is unrecognised must yield the safedefault, never something more destructive than the default.+**A node's OWNERSHIP is persisted state, never a live object.** "Is this node remote / whose host is+it on?" must be answerable with nothing attached, because the questions that ask it — a delete, a+kill, a cleanup — arrive precisely when nothing is: after an app restart, after the offscreen+release, after the park timer, for a project that is not open. `PtyManager.runEndSession` read it+off the dying in-memory `Session` instead, so an SSH node deleted with no live client had its remote+`kill-session` skipped **in silence** and its one kill sent to the LOCAL tmux socket, where a+`requireRemote` node has nothing; the node left the canvas looking deleted and its `nt-<id>` kept+running on the host. Ask the machine-local index (`workspaceStore.sshProjectIdForNode`), and treat a+live handle as the *complement* of that answer, not its source.++**A side effect you could not deliver is not a side effect you performed.** The `ok:false` rule is+not only for reads. `catch {}` around a remote kill folded "tmux says there is no such session" (an+ANSWER) into "the ControlMaster is down" (a NON-answer, session still running). Classify the failure+— and when the work genuinely cannot be done now, either refuse the action with a reason or write+the debt down and settle it later (`core/pending-remote-kills.ts`). Silently dropping it is the one+option that is never available.+**A Server Edition agent owns only nodes it freshly opened in this server run.** Thecreator ledger is process-local and must never be rebuilt from `.nodeterm/project.json`, titles,hook history, or a surviving tmux name: all are writable or stale. A restart therefore clearsdiff --git a/docs/session-memory.md b/docs/session-memory.mdindex 243bd30cf..23dce9b8e 100644--- a/docs/session-memory.md+++ b/docs/session-memory.md@@ -434,20 +434,17 @@ own `×` use.- Switching between two SSH projects with the **same `user@host`** (the scope key carries no port)leaves the previous rows on screen until the re-sweep, because `enterScope` only clears when thescope *string* changes.-- **FOLLOW-UP OWED — the sessions sidebar still has the bug this feature fixed in the panel, and the- two surfaces now disagree about the same session.** `SessionsSidebar.tsx`'s close button calls- `closeSession(projectId, id)` (via `Canvas.tsx`'s `onCloseSession`) with **no remote leg**: for an- SSH project's node that is not mounted, `transport.destroy` has no live client carrying- `sshRemote`, so it touches only the local socket while the host's `nt-<id>` keeps running — after- a confirm that says it stopped. The session-memory panel routes the identical case through- `planSessionKill` → `sshProject.killSessions`, so ending a session from the panel works and- ending the same session from the sidebar does not.- Deliberately out of scope here: the sidebar's rows span arbitrary projects on arbitrary hosts, so- its correct fix is **owner-routed per row** (the owner project's own master, not the active- project's — the panel's rule is only sound because the panel shows one machine at a time), which- is a different rule on a surface this change does not own. Whoever takes it should reuse- `planSessionKill`'s shape rather than inventing a third kill path, and should widen its- `remoteProjectId` leg from "the active project" to "the row's owner" as the same change.+- **CLOSED (was: the sessions sidebar has the bug this feature fixed in the panel).** The fix did+ not land on the sidebar; it landed a layer down, where every surface benefits at once.+ `PtyManager.runEndSession` used to read remoteness off the live `Session` object alone+ (`dying?.sshRemote`), so a delete with no mounted client — the sidebar's cross-project close, the+ node `×` after an app restart or an offscreen release, Delete on a parked node — skipped the+ remote branch silently and sent its one kill to the LOCAL socket, where a `requireRemote` node has+ nothing. A resolver wired from the persisted index (`setRemoteNodeOwner` →+ `workspaceStore.sshProjectIdForNode` plus that project's ControlMaster, see `core/remote-end.ts`)+ now answers without a live client, and an undelivered kill is recorded+ (`core/pending-remote-kills.ts`) and settled on that host's next connect instead of being+ swallowed. `planSessionKill` stays for the panel's ORPHAN rows, which no project claims.## 10. Device checklistdiff --git a/src/core/pending-remote-kills.test.ts b/src/core/pending-remote-kills.test.tsnew file mode 100644index 000000000..e5f0df089--- /dev/null+++ b/src/core/pending-remote-kills.test.ts@@ -0,0 +1,138 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest'+import { promises as fs } from 'fs'+import os from 'os'+import path from 'path'+import { initPlatform, resetPlatformForTests, platform } from './platform'+import { fakePlatform } from './platform-fake'+import {+ drainPendingRemoteKills,+ pendingRemoteKillsFor,+ readPendingRemoteKills,+ recordPendingRemoteKill,+ settlePendingRemoteKills,+ PENDING_REMOTE_KILL_MAX+} from './pending-remote-kills'++const HOST = '[email protected]'++describe('pending remote kills', () => {+ let dir: string++ beforeEach(async () => {+ dir = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-prk-'))+ initPlatform(fakePlatform({ userDataDir: dir }))+ })+ afterEach(async () => {+ resetPlatformForTests()+ await fs.rm(dir, { recursive: true, force: true })+ })++ const file = (): string => path.join(platform().userDataDir, 'pending-remote-kills.json')++ it('records, reads back and settles by host', async () => {+ await recordPendingRemoteKill({ hostKey: HOST, session: 'nt-a', reason: 'not-connected', projectId: 'p1' })+ await recordPendingRemoteKill({ hostKey: '[email protected]', session: 'nt-b', reason: 'no-ssh' })++ expect((await pendingRemoteKillsFor(HOST)).map((e) => e.session)).toEqual(['nt-a'])+ await settlePendingRemoteKills(HOST, ['nt-a'])+ expect(await pendingRemoteKillsFor(HOST)).toEqual([])+ // The other host's debt is untouched — settling is scoped, not a wipe.+ expect((await readPendingRemoteKills()).map((e) => e.session)).toEqual(['nt-b'])+ })++ it('settling is scoped to ONE host even when two owe the SAME session name', async () => {+ // Not hypothetical: node ids live in the git-shared project file, so two hosts holding a+ // clone of the same canvas carry identical `nt-<id>` names. Settling by name alone would+ // forget a debt nobody paid, which is the silent leak this store exists to prevent.+ await recordPendingRemoteKill({ hostKey: HOST, session: 'nt-a', reason: 'not-connected' })+ await recordPendingRemoteKill({ hostKey: '[email protected]', session: 'nt-a', reason: 'not-connected' })+ // Recording is scoped the same way: the second host's debt must not have displaced the first.+ expect(await readPendingRemoteKills()).toHaveLength(2)++ await settlePendingRemoteKills(HOST, ['nt-a'])++ expect(await pendingRemoteKillsFor(HOST)).toEqual([])+ expect((await pendingRemoteKillsFor('[email protected]')).map((e) => e.session)).toEqual(['nt-a'])+ })++ it('is idempotent per (host, session): a re-delete refreshes rather than stacks', async () => {+ await recordPendingRemoteKill({ hostKey: HOST, session: 'nt-a', reason: 'not-connected' })+ await recordPendingRemoteKill({ hostKey: HOST, session: 'nt-a', reason: 'delivery-failed' })+ const owed = await pendingRemoteKillsFor(HOST)+ expect(owed).toHaveLength(1)+ expect(owed[0].reason).toBe('delivery-failed')+ })++ it('serializes concurrent records — a multi-select delete loses none', async () => {+ await Promise.all(+ Array.from({ length: 12 }, (_, i) =>+ recordPendingRemoteKill({ hostKey: HOST, session: `nt-${i}`, reason: 'not-connected' })+ )+ )+ expect(await pendingRemoteKillsFor(HOST)).toHaveLength(12)+ })++ it('caps the file, dropping the oldest', async () => {+ for (let i = 0; i < PENDING_REMOTE_KILL_MAX + 5; i++)+ await recordPendingRemoteKill({ hostKey: HOST, session: `nt-${i}`, reason: 'not-connected' })+ const all = await readPendingRemoteKills()+ expect(all).toHaveLength(PENDING_REMOTE_KILL_MAX)+ expect(all[0].session).toBe('nt-5')+ })++ it('a corrupt file yields no debts instead of throwing into a delete', async () => {+ await fs.writeFile(file(), '{ not json', 'utf8')+ expect(await readPendingRemoteKills()).toEqual([])+ // …and the next record repairs it.+ await recordPendingRemoteKill({ hostKey: HOST, session: 'nt-a', reason: 'no-ssh' })+ expect(await pendingRemoteKillsFor(HOST)).toHaveLength(1)+ })++ it('drops entries that are not shaped like a debt (hand-edited file)', async () => {+ await fs.writeFile(+ file(),+ JSON.stringify([{ hostKey: HOST, session: 'nt-a', at: 1 }, { hostKey: HOST }, null, 7]),+ 'utf8'+ )+ expect((await readPendingRemoteKills()).map((e) => e.session)).toEqual(['nt-a'])+ })++ describe('drain', () => {+ beforeEach(async () => {+ await recordPendingRemoteKill({ hostKey: HOST, session: 'nt-a', reason: 'not-connected' })+ await recordPendingRemoteKill({ hostKey: HOST, session: 'nt-b', reason: 'not-connected' })+ await recordPendingRemoteKill({ hostKey: '[email protected]', session: 'nt-c', reason: 'no-ssh' })+ })++ it('settles only what the killer PROVED gone, and only on this host', async () => {+ const seen: string[] = []+ const r = await drainPendingRemoteKills(HOST, async (session) => {+ seen.push(session)+ return session === 'nt-a'+ })+ expect(seen).toEqual(['nt-a', 'nt-b'])+ expect(r).toEqual({ settled: ['nt-a'], owed: 2 })+ // 'nt-b' is still owed: a kill that could not be confirmed is never evidence of absence.+ expect((await pendingRemoteKillsFor(HOST)).map((e) => e.session)).toEqual(['nt-b'])+ expect((await pendingRemoteKillsFor('[email protected]')).map((e) => e.session)).toEqual(['nt-c'])+ })++ it('a throwing killer settles nothing and never rejects', async () => {+ const r = await drainPendingRemoteKills(HOST, async () => {+ throw new Error('master died again')+ })+ expect(r.settled).toEqual([])+ expect(await pendingRemoteKillsFor(HOST)).toHaveLength(2)+ })++ it('does nothing at all for a host that owes nothing', async () => {+ let calls = 0+ const r = await drainPendingRemoteKills('[email protected]', async () => {+ calls+++ return true+ })+ expect(calls).toBe(0)+ expect(r).toEqual({ settled: [], owed: 0 })+ })+ })+})diff --git a/src/core/pending-remote-kills.ts b/src/core/pending-remote-kills.tsnew file mode 100644index 000000000..8bb5fc942--- /dev/null+++ b/src/core/pending-remote-kills.ts@@ -0,0 +1,174 @@+import path from 'path'+import { promises as fs } from 'fs'+import { platform } from './platform'+import { writeFileAtomic } from './fs-atomic'+import type { RemoteEndDeferReason } from './remote-end'++/**+ * Remote sessions this machine still owes a `kill-session`.+ *+ * A node delete is a canvas edit, and the canvas edit must succeed: the user asked for the node to+ * be gone, and refusing while the host is unreachable strands it on the canvas with no better+ * offer than "try again later" — which is the same leak plus friction, and which they will answer+ * by deleting it again the moment the refusal is out of the way. So the delete goes through and+ * the KILL is written down instead, to be paid the next time that host is reachable.+ *+ * That is the repo rule about `ok:false` applied to a side effect rather than to a read: an+ * undelivered kill is not a delivered one, and the difference is recorded rather than swallowed by+ * the `catch {}` that used to stand here. Between the record and the drain the session is visible+ * where it has always been visible — the session-memory panel lists every `nt-` session on the+ * host — and it is now also listed here, by name, with the reason it was not killed.+ *+ * Keyed by `hostKey` (`user@host`), not by project: several projects share one host's `$HOME` and+ * one tmux server, so a host reached again through ANY of them can settle every session owed on+ * it. `projectId` rides along as provenance only.+ *+ * Desktop only in practice — the Server Edition wires no owner resolver, so it records nothing —+ * but the store itself is shell-neutral and lives in core for that reason.+ */+export interface PendingRemoteKill {+ /** `user@host` — what the drain matches on. */+ hostKey: string+ /** The tmux session NAME (`nt-<nodeId>`), already sanitized by `sessionName`. */+ session: string+ reason: RemoteEndDeferReason | 'delivery-failed'+ /** ms epoch, for the age cap and for saying how long a debt has been outstanding. */+ at: number+ /** Which project the node belonged to. Provenance; never the match key. */+ projectId?: string+}++/**+ * Bounded because this file is forever and a canvas churns through node ids: an unreachable host+ * that a user keeps deleting nodes on would otherwise grow it without limit. Oldest entries are+ * dropped first — a kill owed for months is the one least likely to still be worth sending, and+ * the session-memory panel remains the honest view of what is actually running on a host.+ */+export const PENDING_REMOTE_KILL_MAX = 500++const FILE = 'pending-remote-kills.json'++function filePath(): string {+ return path.join(platform().userDataDir, FILE)+}++/**+ * All writes go through one chain. Two deletes landing in the same tick otherwise read the file+ * before either wrote it and the second one's rewrite loses the first one's entry — the exact+ * shape of lost write this store exists to prevent, and the exact shape a canvas produces (a+ * multi-select Delete ends N nodes at once).+ */+let chain: Promise<unknown> = Promise.resolve()++function serialize<T>(op: () => Promise<T>): Promise<T> {+ const run = chain.then(op, op)+ chain = run.catch(() => undefined)+ return run+}++function isPending(value: unknown): value is PendingRemoteKill {+ const e = value as Partial<PendingRemoteKill> | null+ return (+ !!e &&+ typeof e.hostKey === 'string' &&+ !!e.hostKey &&+ typeof e.session === 'string' &&+ !!e.session &&+ typeof e.at === 'number'+ )+}++/** Tolerant read: a hand-mangled or half-written file yields NO debts rather than throwing into a+ * delete. Losing a record here costs a leaked session; throwing costs the delete itself. */+async function read(): Promise<PendingRemoteKill[]> {+ try {+ const raw = await fs.readFile(filePath(), 'utf8')+ const parsed: unknown = JSON.parse(raw)+ return Array.isArray(parsed) ? parsed.filter(isPending) : []+ } catch {+ return []+ }+}++async function write(entries: PendingRemoteKill[]): Promise<void> {+ const capped = entries.slice(-PENDING_REMOTE_KILL_MAX)+ await writeFileAtomic(filePath(), JSON.stringify(capped))+}++/** Every outstanding debt, oldest first. */+export function readPendingRemoteKills(): Promise<PendingRemoteKill[]> {+ return serialize(read)+}++/** What is owed on one host. */+export async function pendingRemoteKillsFor(hostKey: string): Promise<PendingRemoteKill[]> {+ return (await readPendingRemoteKills()).filter((e) => e.hostKey === hostKey)+}++/**+ * Record one undelivered kill. Idempotent per `(hostKey, session)` — re-deleting the same node, or+ * a drain attempt that failed again, refreshes the existing entry instead of stacking duplicates+ * that would each cost their own ssh round trip at drain time.+ *+ * Never throws: this runs inside a teardown whose other half has already committed, and a failed+ * bookkeeping write must not turn a delete the user watched succeed into a rejected promise.+ */+export function recordPendingRemoteKill(entry: Omit<PendingRemoteKill, 'at'>): Promise<void> {+ return serialize(async () => {+ try {+ const entries = (await read()).filter(+ (e) => !(e.hostKey === entry.hostKey && e.session === entry.session)+ )+ entries.push({ ...entry, at: Date.now() })+ await write(entries)+ } catch (error) {+ console.warn(+ `[pty] could not record the undelivered remote kill for ${entry.session}`,+ error instanceof Error ? error.message : String(error)+ )+ }+ })+}++/** Forget debts that have been settled (or that we have decided will never be). */+export function settlePendingRemoteKills(hostKey: string, sessions: string[]): Promise<void> {+ const done = new Set(sessions)+ return serialize(async () => {+ const entries = await read()+ const left = entries.filter((e) => !(e.hostKey === hostKey && done.has(e.session)))+ if (left.length !== entries.length) await write(left)+ })+}++/**+ * Pay off what a host owes, now that it is reachable again.+ *+ * `kill` returns whether the session is PROVEN gone — delivered, or answered by tmux's own "can't+ * find session". A `false` leaves the entry exactly where it was, because a failed read (or a+ * master that dropped again mid-drain) is never evidence of absence: dropping the debt there would+ * reintroduce the silent leak one layer up.+ *+ * Best-effort by contract, and never throws: it runs off the back of a `connected` event, which+ * must never fail because a cleanup could not.+ */+export async function drainPendingRemoteKills(+ hostKey: string,+ kill: (session: string) => Promise<boolean>+): Promise<{ settled: string[]; owed: number }> {+ let owed: PendingRemoteKill[] = []+ try {+ owed = await pendingRemoteKillsFor(hostKey)+ } catch {+ return { settled: [], owed: 0 }+ }+ const settled: string[] = []+ for (const entry of owed) {+ try {+ if (await kill(entry.session)) settled.push(entry.session)+ } catch {+ /* still owed — leave the entry alone */+ }+ }+ if (settled.length) await settlePendingRemoteKills(hostKey, settled).catch(() => undefined)+ return { settled, owed: owed.length }+}diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 6e8cee8fb..ad0403235 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -36,6 +36,12 @@ import {remoteTerminateForegroundArgs,remotePaneCursorArgs} from './remote-ssh/control-master'+import {+ planRemoteEnd,+ type RemoteEndPlan,+ type RemoteNodeOwnerResolver+} from './remote-end'+import { recordPendingRemoteKill, type PendingRemoteKill } from './pending-remote-kills'import { probeAgentSockToPin } from './remote-ssh/agent-probe'import { parsePaneCursor } from './pane-cursor'import { classifyPaneCwd } from './pane-cwd'@@ -912,6 +918,8 @@ export class PtyManager {* exactly as it did before it existed.*/private readProjectSpawnOverrides: ProjectSpawnOverridesReader | null = null+ /** "Which SSH host owns this node?", from the persisted index — see `setRemoteNodeOwner`. */+ private remoteNodeOwner: RemoteNodeOwnerResolver | null = null/** ONE shared snapshot interval for all persisted sessions — a per-session interval spawned* one tmux/ssh capture subprocess per session per tick, forever, even for idle terminals. */private snapshotTimer: ReturnType<typeof setInterval> | null = null@@ -1497,6 +1505,19 @@ export class PtyManager {this.readProjectSpawnOverrides = read}+ /**+ * Wire "which host owns this node?", answered from PERSISTED project data rather than from a+ * live session — see `remote-end.ts` for the leak this closes.+ *+ * A separate setter for the same reason as the one above: the resolver needs the workspace store+ * AND the SSH-project manager, and neither shell has both by the time `init` runs. Wiring none+ * (the Server Edition, which has no SSH-project manager) leaves every delete on the local path it+ * already took.+ */+ setRemoteNodeOwner(resolve: RemoteNodeOwnerResolver | null): void {+ this.remoteNodeOwner = resolve+ }+/*** The project's contribution to THIS spawn — bounded and fail-open on every path.*@@ -4671,6 +4692,67 @@ export class PtyManager {return promise}+ /**+ * Deliver the remote half of an end — or write down that we could not.+ *+ * The `catch {}` this replaces read "remote session may not exist / master down; ignore", and+ * those two are not the same fact at all. "May not exist" is an ANSWER: tmux says `can't find+ * session` and exits 1, which is what `probeSaysAbsent` is anchored to and what the local kill+ * loop has always treated as the ordinary case. "Master down" is a NON-answer — ssh's own 255,+ * a 127 for a tmux that is not on the remote PATH, a spawn error with no code at all — and the+ * session is still running on the host. Ignoring both is how ~150 `nt-` sessions accumulate on a+ * machine whose owner deleted them.+ *+ * A non-answer is therefore RECORDED, and paid off the next time that host is reachable+ * (`drainPendingRemoteKills`, run from the SSH project's connect). The delete itself is never+ * refused over it: the node is going, and a refusal would strand it on the canvas with the same+ * session still running plus a dialog. That choice is only defensible BECAUSE the debt is+ * durable — drop the store and the honest thing to do becomes refusing.+ *+ * **Only a DELETE may owe a debt.** A `recycle` keeps the node (worktree move, model switch,+ * "pause & end session"), so a kill deferred to some later reconnect would land on the session+ * the node has since RESPAWNED under the same name — it would end live work, hours after the+ * action that queued it, with nothing on screen connecting the two. A recycle whose remote kill+ * could not be delivered therefore does exactly what it did before: nothing. Only `delete` makes+ * "kill this name whenever you next can" an unconditionally correct instruction.+ */+ private async endRemoteSession(+ persistKey: string,+ intent: EndIntent,+ plan: Extract<RemoteEndPlan, { kind: 'deliver' | 'defer' }>+ ): Promise<void> {+ const session = sessionName(persistKey)+ const owe = (reason: PendingRemoteKill['reason']): Promise<void> =>+ intent === 'delete'+ ? recordPendingRemoteKill({+ hostKey: plan.hostKey,+ session,+ reason,+ projectId: plan.projectId+ })+ : Promise.resolve()+ if (plan.kind === 'defer') {+ await owe(plan.reason)+ return+ }+ try {+ await this.confirmedProcessRun(+ plan.ssh,+ remoteTmuxKillArgs(plan.conn, plan.controlPath, session)+ )+ } catch (error) {+ // tmux's own "can't find session" (exit 1) settles it — there is nothing left to kill, and+ // that is the expected answer for a host that rebooted since the session was last seen.+ if (probeSaysAbsent(error)) return+ await owe('delivery-failed')+ console.warn(+ `[pty] remote kill for ${session} on ${plan.hostKey} was not delivered` ++ (intent === 'delete' ? '; owed until that host reconnects' : ''),+ error instanceof Error ? error.message : String(error)+ )+ }+ }+private async runEndSession(clientId: ClientId | null,persistKey: string,@@ -4681,9 +4763,16 @@ export class PtyManager {/** Trusted replacement identity; present only after confirmed profile preflight. */replacementTarget?: PtyRecycleTarget): Promise<void> {- // Both callers run while the session is still live, so its sshRemote is known. Capture it- // synchronously before any await. The index is the co-attach one (UI sessions); the scan is- // the fallback for a session that is live but not indexed.+ // The index is the co-attach one (UI sessions); the scan is the fallback for a session that is+ // live but not indexed. Both are captured synchronously, before any await.+ //+ // What this used to say — "both callers run while the session is still live, so its sshRemote+ // is known" — was simply not true, and believing it leaked remote sessions. A delete arrives+ // precisely when there may be NO live session: after an app restart, after the offscreen+ // release disposed the client, after the park timer ran out, or for a node whose project is not+ // open at all. `dying` was then undefined, `sshRemote` with it, and the remote branch below was+ // skipped in silence while the one kill that did go out went to the LOCAL socket — nothing at+ // all for a `requireRemote` node. See `planRemoteEnd`.const indexedId = this.byPersistKey.get(persistKey)const indexed = indexedId ? this.sessions.get(indexedId) : undefinedconst fallback = indexed ?? this.sessionByPersistKey(persistKey)@@ -4693,7 +4782,16 @@ export class PtyManager {? [...this.sessions.entries()].find(([, candidate]) => candidate === fallback)?.[0]: undefined)const dying = fallback- const sshRemote = dying?.sshRemote+ // Resolved here, synchronously, for the same reason the live handle always was: a+ // connect/disconnect landing mid-teardown must not change the branch that already committed to+ // it. The resolver is the FALLBACK — a live `sshRemote` is the exact handle this session was+ // spawned over and still wins — and it is what makes a delete with no live client reach the+ // host at all.+ const remoteEnd = planRemoteEnd({+ live: dying?.sshRemote,+ owner: this.remoteNodeOwner?.(persistKey) ?? null,+ ssh: findSsh()+ })// SessionHostClient has a real request/response acknowledgement. Await it BEFORE any local// deletion claim: on transport failure the node, tombstone, subscribers and transcript tails// remain available, because the host outcome is unknown and the user must be able to retry.@@ -4823,16 +4921,13 @@ export class PtyManager {// too, and there are two of them to keep in step.if (intent === 'delete') clearNodeAgentStatus(persistKey)if (!backendAlreadyEnded) {- if (sshRemote) {+ if (remoteEnd.kind !== 'none') {// Remote (ssh-project) node: end the REMOTE session.- const ssh = findSsh()- if (ssh) {- try {- await runAsync(ssh, remoteTmuxKillArgs(sshRemote.conn, sshRemote.controlPath, sessionName(persistKey)))- } catch {- // remote session may not exist / master down; ignore- }- }+ //+ // Routed through `confirmedProcessRun` — which IS `runAsync` in production, so the command+ // and its bounds are unchanged — because this is confirmed teardown now rather than a+ // best-effort side call, and because a kill nothing can observe is a kill nothing can test.+ await this.endRemoteSession(persistKey, intent, remoteEnd)// ...and then fall through to the LOCAL kill below rather than returning. A remote node// normally has no local session — but it may have one from before `requireRemote`, when a// create issued with the master down spawned a local shell under this exact name. Thatdiff --git a/src/core/pty-remote-delete.test.ts b/src/core/pty-remote-delete.test.tsnew file mode 100644index 000000000..766d3be20--- /dev/null+++ b/src/core/pty-remote-delete.test.ts@@ -0,0 +1,191 @@+/**+ * Deleting an SSH project's node must end the session on the HOST — including when this process+ * holds no live client for it.+ *+ * The bug: `runEndSession` decided "is this node remote?" from the in-memory live `Session` alone+ * (`dying?.sshRemote`). With no live client — after an app restart, after the offscreen release,+ * after the park timer, or for a node whose project is simply not open — `dying` is undefined, the+ * remote branch was skipped in silence, and the ONE kill that did go out went to the LOCAL tmux+ * socket, where a `requireRemote` node has nothing. Everything else about the teardown ran, so+ * nothing looked wrong: the node left the canvas and its `nt-<id>` kept running on the host.+ *+ * These pin the fix from the outside: the ownership answer comes from PERSISTED project data (the+ * resolver the shell wires to `workspaceStore.sshProjectIdForNode` + the project's ControlMaster),+ * never from a live session, and a kill that could not be delivered is RECORDED, not swallowed.+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { existsSync } from 'fs'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform, type FakePlatform } from './platform-fake'+import { DEFAULT_SETTINGS } from '../shared/types'+import { sessionName } from './tmux-naming'++vi.mock('./session-host-backend', async () =>+ (await import('./__fixtures__/no-session-host')).noSessionHost()+)+vi.mock('node-pty', () => ({+ spawn: () => ({+ onData: () => {},+ onExit: () => {},+ write: () => {},+ resize: () => {},+ pause: () => {},+ resume: () => {},+ kill: () => {},+ pid: 4321+ })+}))+vi.mock('./pty-devices', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./pty-devices')>()),+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })+}))++const HAS_SSH = ['/usr/bin/ssh', '/usr/local/bin/ssh', '/opt/homebrew/bin/ssh'].some((p) =>+ existsSync(p)+)++const CONN = { host: 'example.test', user: 'deploy' }+const NODE = 'node-remote-1'++describe('deleting a remote node with no live client', () => {+ let fake: FakePlatform+ let runs: Array<{ file: string; args: string[] }>++ beforeEach(() => {+ fake = fakePlatform()+ initPlatform(fake)+ runs = []+ })+ afterEach(() => {+ resetPlatformForTests()+ vi.restoreAllMocks()+ })++ async function manager(fail?: (args: readonly string[]) => unknown) {+ const { PtyManager } = await import('./pty-manager')+ const m = new PtyManager({+ confirmedProcessRun: async (file: string, args: readonly string[]) => {+ runs.push({ file, args: [...args] })+ const error = fail?.(args)+ if (error) throw error+ return { stdout: '', stderr: '' }+ }+ })+ m.init(() => DEFAULT_SETTINGS)+ return m+ }++ const owner = (nodeId: string) =>+ nodeId === NODE+ ? {+ projectId: 'p1',+ hostKey: '[email protected]',+ remote: { conn: CONN, controlPath: '/tmp/cm-p1' }+ }+ : null++ it.skipIf(!HAS_SSH)(+ 'kills the session on the host, resolved from persisted project data',+ async () => {+ const m = await manager()+ m.setRemoteNodeOwner((nodeId) =>+ nodeId === NODE+ ? {+ projectId: 'p1',+ hostKey: '[email protected]',+ remote: { conn: CONN, controlPath: '/tmp/cm-p1' }+ }+ : null+ )++ await m.destroySession(null, NODE)++ const remote = runs.filter((r) => r.file.endsWith('ssh'))+ expect(remote.length).toBeGreaterThan(0)+ const flat = remote.map((r) => r.args.join(' ')).join('\n')+ expect(flat).toContain('kill-session')+ expect(flat).toContain(sessionName(NODE))+ expect(flat).toContain('/tmp/cm-p1')+ }+ )++ it('records the undelivered kill when the project is not connected', async () => {+ const m = await manager()+ m.setRemoteNodeOwner((nodeId) =>+ nodeId === NODE ? { projectId: 'p1', hostKey: '[email protected]' } : null+ )++ await m.destroySession(null, NODE)++ const { readPendingRemoteKills } = await import('./pending-remote-kills')+ const pending = await readPendingRemoteKills()+ expect(pending.map((e) => e.session)).toContain(sessionName(NODE))+ expect(pending[0].projectId).toBe('p1')+ })++ it.skipIf(!HAS_SSH)(+ "tmux's own \"can't find session\" (exit 1) settles it — nothing is owed",+ async () => {+ // The commonest outcome for a host that rebooted since the session was last seen. It is an+ // ANSWER, and recording a debt for it would queue an ssh round trip per reconnect forever.+ const m = await manager((args) =>+ args.join(' ').includes('kill-session') ? Object.assign(new Error('can\'t find session'), { code: 1 }) : null+ )+ m.setRemoteNodeOwner(owner)++ await m.destroySession(null, NODE)++ const { readPendingRemoteKills } = await import('./pending-remote-kills')+ expect(await readPendingRemoteKills()).toEqual([])+ }+ )++ it.skipIf(!HAS_SSH)('a transport failure (ssh 255) is owed, not swallowed', async () => {+ // A dead ControlMaster says nothing about whether the session is still running — and it+ // usually is. This is the case the old `catch {}` threw away.+ const m = await manager((args) =>+ args.join(' ').includes('kill-session')+ ? Object.assign(new Error('ssh: Control socket connect: No such file'), { code: 255 })+ : null+ )+ m.setRemoteNodeOwner(owner)++ await m.destroySession(null, NODE)++ const { readPendingRemoteKills } = await import('./pending-remote-kills')+ const pending = await readPendingRemoteKills()+ expect(pending).toHaveLength(1)+ expect(pending[0]).toMatchObject({+ session: sessionName(NODE),+ hostKey: '[email protected]',+ reason: 'delivery-failed'+ })+ })++ it('a RECYCLE still kills remotely but never owes a debt', async () => {+ // A recycle keeps the node (worktree move, model switch, "pause & end session"), so a kill+ // deferred to some later reconnect would land on the session the node has since RESPAWNED+ // under the same name — ending live work hours after the action that queued it. Only a delete+ // makes "kill this name whenever you next can" unconditionally correct.+ const m = await manager()+ m.setRemoteNodeOwner((nodeId) =>+ nodeId === NODE ? { projectId: 'p1', hostKey: '[email protected]' } : null+ )++ await m.recycleSession(null, NODE)++ const { readPendingRemoteKills } = await import('./pending-remote-kills')+ expect(await readPendingRemoteKills()).toEqual([])+ })++ it('leaves a LOCAL node untouched — no resolver answer, no remote call, no debt', async () => {+ const m = await manager()+ m.setRemoteNodeOwner(() => null)++ await m.destroySession(null, 'node-local-1')++ expect(runs.filter((r) => r.file.endsWith('ssh'))).toEqual([])+ const { readPendingRemoteKills } = await import('./pending-remote-kills')+ expect(await readPendingRemoteKills()).toEqual([])+ })+})diff --git a/src/core/remote-end.test.ts b/src/core/remote-end.test.tsnew file mode 100644index 000000000..5a17ac05b--- /dev/null+++ b/src/core/remote-end.test.ts@@ -0,0 +1,85 @@+import { describe, it, expect } from 'vitest'+import { planRemoteEnd } from './remote-end'++const CONN = { host: 'h1.test', user: 'deploy' }+const OTHER = { host: 'h2.test', user: 'root' }+const LIVE = { conn: CONN, controlPath: '/cm/live.sock' }+const OWNED = { conn: CONN, controlPath: '/cm/owner.sock' }++describe('planRemoteEnd', () => {+ it('is a no-op for a node nothing claims — the local path is untouched', () => {+ expect(planRemoteEnd({ live: undefined, owner: null, ssh: '/usr/bin/ssh' })).toEqual({+ kind: 'none'+ })+ })++ it('uses the LIVE handle when there is one, even if a resolver also answers', () => {+ const plan = planRemoteEnd({+ live: LIVE,+ owner: { projectId: 'p1', hostKey: '[email protected]', remote: { conn: OTHER, controlPath: '/cm/owner.sock' } },+ ssh: '/usr/bin/ssh'+ })+ // The live handle is the master this session was actually spawned over; it cannot disagree+ // with itself, so it wins over anything the index believes.+ expect(plan).toMatchObject({ kind: 'deliver', controlPath: '/cm/live.sock', conn: CONN })+ })++ it('derives the host key from the live connection when only a live handle exists', () => {+ const plan = planRemoteEnd({ live: LIVE, owner: null, ssh: '/usr/bin/ssh' })+ expect(plan).toMatchObject({ kind: 'deliver', hostKey: '[email protected]', projectId: undefined })+ })++ it('THE FIX: with no live session, the persisted owner supplies the master', () => {+ const plan = planRemoteEnd({+ live: undefined,+ owner: { projectId: 'p1', hostKey: '[email protected]', remote: OWNED },+ ssh: '/usr/bin/ssh'+ })+ expect(plan).toEqual({+ kind: 'deliver',+ ssh: '/usr/bin/ssh',+ conn: CONN,+ controlPath: '/cm/owner.sock',+ hostKey: '[email protected]',+ projectId: 'p1'+ })+ })++ it('defers when the owning project has no ControlMaster', () => {+ const plan = planRemoteEnd({+ live: undefined,+ owner: { projectId: 'p1', hostKey: '[email protected]' },+ ssh: '/usr/bin/ssh'+ })+ expect(plan).toEqual({+ kind: 'defer',+ reason: 'not-connected',+ hostKey: '[email protected]',+ projectId: 'p1'+ })+ })++ it('defers when there is no ssh binary at all — including for a live handle', () => {+ expect(planRemoteEnd({ live: LIVE, owner: null, ssh: null })).toEqual({+ kind: 'defer',+ reason: 'no-ssh',+ hostKey: '[email protected]',+ projectId: undefined+ })+ expect(+ planRemoteEnd({ live: undefined, owner: { projectId: 'p1', hostKey: '[email protected]' }, ssh: null })+ ).toMatchObject({ kind: 'defer', reason: 'no-ssh' })+ })++ it('a missing ssh binary is decided BEFORE connectedness — the reason names what is wrong', () => {+ // Both are true at once for a disconnected project on a machine with no ssh. Reporting+ // 'not-connected' would send the user to reconnect a project that could never be killed from+ // here anyway.+ const plan = planRemoteEnd({+ live: undefined,+ owner: { projectId: 'p1', hostKey: '[email protected]', remote: OWNED },+ ssh: null+ })+ expect(plan).toMatchObject({ kind: 'defer', reason: 'no-ssh' })+ })+})diff --git a/src/core/remote-end.ts b/src/core/remote-end.tsnew file mode 100644index 000000000..cf6622355--- /dev/null+++ b/src/core/remote-end.ts@@ -0,0 +1,94 @@+import type { SshConnection } from '../shared/ssh'+import { sshHostKey } from '../shared/ssh'++/**+ * WHERE a node's session lives, answered WITHOUT a live client.+ *+ * The whole point of this module. `PtyManager` used to decide "is this node remote?" from the+ * in-memory `Session` object alone, and a delete arrives precisely when there may be no session:+ * after an app restart, after the offscreen release disposed the client, after the park timer ran+ * out, or for a node whose project is not even open. The answer was then `undefined` — read as+ * "local" — so the remote kill was skipped in silence and the one kill that went out went to the+ * LOCAL tmux socket, where a `requireRemote` node has nothing at all. The node left the canvas and+ * its `nt-<id>` kept running on the host, with nothing anywhere saying so.+ *+ * The durable answer is the machine-local project index (`workspaceStore.sshProjectIdForNode`),+ * which knows a node's owning SSH project whether or not anything is attached to it. The shell+ * wires that in as `RemoteNodeOwnerResolver`; the Server Edition wires none (it has no SSH-project+ * manager) and therefore keeps the local-only behaviour it already had.+ */+export interface RemoteNodeOwner {+ /** The SSH project this node belongs to, per the persisted index. */+ projectId: string+ /**+ * `user@host` for that project. Keyed on separately from `projectId` because the DEBT below is+ * settled per host, not per project: several projects share one host's `$HOME` and one tmux+ * server, and a host reached again through any of them can pay off every session owed on it.+ */+ hostKey: string+ /** The live ControlMaster, when the project is currently connected. Absent ⇒ nothing to send on. */+ remote?: { conn: SshConnection; controlPath: string }+}++/** Sync on purpose: `runEndSession` captures its remote answer BEFORE its first await, exactly as+ * it always captured `dying.sshRemote`, so a connect/disconnect mid-teardown cannot change it+ * underneath the branch that already committed to it. */+export type RemoteNodeOwnerResolver = (nodeId: string) => RemoteNodeOwner | null++/** Why a remote kill could not be sent. Recorded verbatim so the debt says what happened. */+export type RemoteEndDeferReason =+ /** The owning project has no ControlMaster right now (host down, network gone, never connected). */+ | 'not-connected'+ /** No `ssh` on this machine. Nothing can reach the host from here, now or later. */+ | 'no-ssh'++export type RemoteEndPlan =+ /** Not a remote node: the local path runs exactly as it always did. */+ | { kind: 'none' }+ | {+ kind: 'deliver'+ ssh: string+ conn: SshConnection+ controlPath: string+ hostKey: string+ projectId?: string+ }+ | { kind: 'defer'; reason: RemoteEndDeferReason; hostKey: string; projectId?: string }++/**+ * Decide what ending a node owes the remote host.+ *+ * Pure so the matrix — and specifically the four ways a node can be remote with nothing live — is+ * provable without a tmux server, an ssh binary or a socket.+ *+ * `live` (the dying `Session.sshRemote`) still wins when it is there: it is the exact handle the+ * session was actually spawned over, so it can never disagree with itself. The resolver is the+ * FALLBACK, not a replacement — a node created seconds ago may not be in the index cache yet, and+ * for that node the live handle is the only truth there is.+ */+export function planRemoteEnd(args: {+ live: { conn: SshConnection; controlPath: string } | undefined+ owner: RemoteNodeOwner | null+ ssh: string | null+}): RemoteEndPlan {+ const { live, owner, ssh } = args+ const target = live ?? owner?.remote+ const hostKey = live ? sshHostKey(live.conn) : owner?.hostKey+ // Neither a live remote session nor a persisted remote owner: a local node, and this module has+ // no opinion about it. Byte-identical to the pre-fix path.+ if (!target && !owner) return { kind: 'none' }+ // `hostKey` is only unknown when there is no owner AND no live conn, which the line above+ // already returned on. The fallback keeps the type honest without inventing a host name.+ const host = hostKey ?? ''+ if (!ssh) return { kind: 'defer', reason: 'no-ssh', hostKey: host, projectId: owner?.projectId }+ if (!target)+ return { kind: 'defer', reason: 'not-connected', hostKey: host, projectId: owner?.projectId }+ return {+ kind: 'deliver',+ ssh,+ conn: target.conn,+ controlPath: target.controlPath,+ hostKey: host,+ projectId: owner?.projectId+ }+}diff --git a/src/main/index.ts b/src/main/index.tsindex d2c1f4202..b6cd1d177 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -218,7 +218,7 @@ import {} from '../core/remote-ssh/control-master'import { planRemoteWorkspacePoll } from './remote-workspace-poll'import { sessionName } from '../core/tmux-naming'-import { posixQuote, type SshConnection } from '../shared/ssh'+import { posixQuote, sshHostKey, type SshConnection } from '../shared/ssh'import { buildHandoff, type HandoffRemote } from './handoff'import { initContextLink, setNodeTranscript } from '../core/context-link'import { transcriptPathOf } from '../core/context-link-core'@@ -495,6 +495,32 @@ workspaceStore.onPersist = () => {workspaceWatcher.sync()refreshNodeTokens()}+// "Which host owns this node?", answered WITHOUT a live session — the persisted index, not the+// in-memory `Session`. A delete arrives precisely when there may be nothing attached (an app+// restart, the offscreen release, the park timer, a project that is not even open), and core used+// to read remoteness off the dying session alone: the remote `kill-session` was then skipped in+// silence and the node's `nt-<id>` kept running on the host. See core/remote-end.ts.+//+// Wired here rather than in `ptyManager.init` because it needs BOTH the workspace store and the+// SSH-project manager, and the manager is created much later — `sshProjectManager` is read inside+// the closure, so an early delete simply sees no live master and records the debt.+// The Server Edition wires none: it has no SSH-project manager, so its deletes stay local.+ptyManager.setRemoteNodeOwner((nodeId) => {+ const projectId = workspaceStore.sshProjectIdForNode(nodeId)+ if (!projectId) return null+ // The persisted endpoint is what makes the host NAMEABLE while it is unreachable — without it a+ // debt could not be keyed, and an undeliverable kill would have to be dropped again.+ const server = workspaceStore.projectTargetInfo(projectId)?.ssh?.server+ if (!server) return null+ // The LIVE conn (not the persisted one) when there is a master: it carries this run's pinned+ // agent socket and trust provenance, and it is the same handle `killSessions` runs over.+ const ref = sshProjectManager?.refForProject(projectId)+ return {+ projectId,+ hostKey: sshHostKey(ref?.conn ?? server),+ remote: ref ? { conn: ref.conn, controlPath: ref.controlPath } : undefined+ }+})const gitService = new GitService()// Project setup/archive runner (SDD: 2026-08-19-project-settings-trust). The trust store is keyeddiff --git a/src/main/remote-end-wiring.test.ts b/src/main/remote-end-wiring.test.tsnew file mode 100644index 000000000..1df821d49--- /dev/null+++ b/src/main/remote-end-wiring.test.ts@@ -0,0 +1,37 @@+// The remote-owner resolver is the whole fix, and a resolver nobody registers ships INERT.+//+// `PtyManager.setRemoteNodeOwner(null)` is the shipped default and every unit test passes without+// it: core keeps taking the live-session-only path, the local kill still runs, nothing throws, and+// the only symptom is an `nt-<id>` that keeps running on a host nobody is looking at. There is no+// type error to catch that — which is exactly the class of hole+// `codex-identity-record-wiring.test.ts` and `hook-verified-parity.test.ts` exist for, so this is+// pinned the same way: at source level.+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'fs'+import path from 'path'++const SRC = readFileSync(path.join(__dirname, 'index.ts'), 'utf8').replace(/\r\n/g, '\n')++describe('main wires the remote-node owner resolver', () => {+ it('registers it on the pty manager', () => {+ expect(SRC).toContain('ptyManager.setRemoteNodeOwner(')+ })++ it('answers from the PERSISTED index, not from a live session', () => {+ // `sshProjectIdForNode` scans the index entries' cached node lists, so it answers for a node+ // whose project is closed, never opened this run, or whose terminal was released offscreen —+ // the four cases where the old `dying?.sshRemote` read `undefined` and the remote kill was+ // skipped in silence.+ expect(SRC).toContain('workspaceStore.sshProjectIdForNode(nodeId)')+ })++ it('names the host from the persisted endpoint, so an unreachable one can still be recorded', () => {+ // Without a host key an undeliverable kill could not be keyed, and the only thing left to do+ // with it would be to drop it — which is the bug.+ expect(SRC).toContain('workspaceStore.projectTargetInfo(projectId)?.ssh?.server')+ })++ it('takes the live ControlMaster when the project is connected', () => {+ expect(SRC).toContain('sshProjectManager?.refForProject(projectId)')+ })+})diff --git a/src/main/remote-ssh/ssh-project.pendingKills.test.ts b/src/main/remote-ssh/ssh-project.pendingKills.test.tsnew file mode 100644index 000000000..8d27cc9d8--- /dev/null+++ b/src/main/remote-ssh/ssh-project.pendingKills.test.ts@@ -0,0 +1,113 @@+// Paying off the remote `kill-session`s a node delete could not deliver.+//+// The delete itself never blocks on an unreachable host — the node is going, and refusing would+// strand it on the canvas with the session still running. That is only defensible because the kill+// is written down and settled here, so this file covers the half that makes the trade honest: the+// debt is keyed by HOST (several projects share one host's tmux server), an entry is dropped ONLY+// on tmux's own answer, and a transport failure leaves it owed for the next connect.+import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest'+import { promises as fs } from 'fs'+import os from 'os'+import path from 'path'++vi.mock('electron', () => ({+ app: { getPath: () => '/tmp/nodeterm-test' },+ ipcMain: { handle: () => undefined, on: () => undefined }+}))++import { SshProjectManager } from './ssh-project'+import { remoteTmuxPathPrologue } from '../../shared/ssh'+import { initPlatform, resetPlatformForTests } from '../../core/platform'+import { fakePlatform } from '../../core/platform-fake'+import { pendingRemoteKillsFor, recordPendingRemoteKill } from '../../core/pending-remote-kills'++const TP = remoteTmuxPathPrologue()+const conn = { host: 'h.example.com', user: 'deploy', port: 22 }+const HOST = '[email protected]'++/** `conns` is private; a test is the one caller allowed to seed it, since `connect()` would need a+ * real ssh. Same pattern as ssh-project.killSessions.test.ts. */+function managerWithConn(code: (session: string) => number): {+ mgr: SshProjectManager+ runs: string[][]+} {+ const runs: string[][] = []+ const run = async (args: string[]): Promise<{ code: number; stdout: string }> => {+ runs.push(args)+ return { code: code(args.at(-1) ?? ''), stdout: '' }+ }+ const mgr = new SshProjectManager({ run } as never)+ ;(mgr as unknown as { conns: Map<string, unknown> }).conns.set('p1', {+ conn,+ controlPath: '/s.sock',+ master: { kill: () => undefined }+ })+ return { mgr, runs }+}++const settle = (mgr: SshProjectManager, projectId = 'p1'): Promise<void> =>+ (mgr as unknown as { settleOwedKills: (id: string) => Promise<void> }).settleOwedKills(projectId)++describe('SshProjectManager: settling owed remote kills on connect', () => {+ let dir: string++ beforeEach(async () => {+ dir = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-owed-'))+ initPlatform(fakePlatform({ userDataDir: dir }))+ })+ afterEach(async () => {+ resetPlatformForTests()+ await fs.rm(dir, { recursive: true, force: true })+ })++ it('kills what is owed on this HOST and forgets it', async () => {+ await recordPendingRemoteKill({ hostKey: HOST, session: 'nt-abc', reason: 'not-connected' })+ const { mgr, runs } = managerWithConn(() => 0)++ await settle(mgr)++ expect(runs.map((r) => r.at(-1))).toEqual([`${TP}tmux -L nodeterm-rmt kill-session -t =nt-abc`])+ expect(await pendingRemoteKillsFor(HOST)).toEqual([])+ })++ it("tmux's own exit 1 also settles it — the session was already gone", async () => {+ await recordPendingRemoteKill({ hostKey: HOST, session: 'nt-abc', reason: 'not-connected' })+ const { mgr } = managerWithConn(() => 1)+ await settle(mgr)+ expect(await pendingRemoteKillsFor(HOST)).toEqual([])+ })++ it('an ssh transport failure (255) leaves it owed for the next connect', async () => {+ // A failed read is never evidence of absence: the session is almost certainly still running.+ await recordPendingRemoteKill({ hostKey: HOST, session: 'nt-abc', reason: 'not-connected' })+ const { mgr } = managerWithConn(() => 255)+ await settle(mgr)+ expect((await pendingRemoteKillsFor(HOST)).map((e) => e.session)).toEqual(['nt-abc'])+ })++ it("touches nothing owed to a DIFFERENT host", async () => {+ await recordPendingRemoteKill({ hostKey: '[email protected]', session: 'nt-xyz', reason: 'no-ssh' })+ const { mgr, runs } = managerWithConn(() => 0)+ await settle(mgr)+ expect(runs).toEqual([])+ expect((await pendingRemoteKillsFor('[email protected]')).map((e) => e.session)).toEqual(['nt-xyz'])+ })++ it('does nothing for a project with no live master', async () => {+ await recordPendingRemoteKill({ hostKey: HOST, session: 'nt-abc', reason: 'not-connected' })+ const { mgr, runs } = managerWithConn(() => 0)+ await settle(mgr, 'p-unknown')+ expect(runs).toEqual([])+ expect(await pendingRemoteKillsFor(HOST)).toHaveLength(1)+ })++ it('is hung on the shared connect attempt, so the REUSE branch settles too', async () => {+ // `connectOnce`'s reuse branch returns long before the `connected` event, so wiring this to+ // that event would leave every reconnect-onto-a-live-master owing forever. Source-level+ // because driving `connect()` needs a real ssh.+ const src = fs.readFile(path.join(__dirname, 'ssh-project.ts'), 'utf8')+ const text = (await src).replace(/\r\n/g, '\n')+ const connectBody = text.slice(text.indexOf('const ticket = Symbol('), text.indexOf('private async connectOnce'))+ expect(connectBody).toContain('this.settleOwedKills(projectId)')+ })+})diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 6d0e3d896..e2421a678 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -19,6 +19,7 @@ import { candidateName, safeDownloadBasename } from '../../core/download-name'import { removeAtomic, renameAtomic } from '../../core/fs-atomic'import { findExecutableSync, shellPathNow } from '../../core/exec-path'import { isSafeRemoteHome } from '../../core/remote-safety'+import { drainPendingRemoteKills } from '../../core/pending-remote-kills'import { mediaCachePruneList, remoteMediaCacheName } from '../../core/remote-ssh/media-cache'import { allowMediaPath } from '../media-protocol'import { remoteAccountConfigDir, isSupportedClaudeVersion } from '../../core/claude-accounts-core'@@ -493,10 +494,39 @@ export class SshProjectManager {const attempt = this.connectOnce(projectId, conn, remoteCwd, ticket).finally(() => {if (this.inFlight.get(projectId)?.attempt === attempt) this.inFlight.delete(projectId)})+ // This host is reachable again, so this is the moment to pay off any remote `kill-session` a+ // node delete could not deliver while it was down (see core/pending-remote-kills.ts). Hung on+ // the shared attempt rather than inside `connectOnce`, so the REUSE branch — which returns+ // long before the `connected` event — settles its debts too.+ //+ // Fire-and-forget, same contract as the tunnel resync below it: several remote round trips of+ // pure cleanup must never delay, or fail, a connect that has already succeeded.+ void attempt.then(+ () => this.settleOwedKills(projectId),+ () => {}+ )this.inFlight.set(projectId, { conn, attempt, ticket })return attempt}+ /**+ * Deliver the remote kills this machine still owes the host behind `projectId`.+ *+ * Keyed by HOST, not by project: several projects share one host's `$HOME` and one tmux server,+ * so whichever of them reconnects first can settle every session owed there. An entry is dropped+ * only on tmux's own answer — exit 0 (killed) or exit 1 ("can't find session" / "no server+ * running", i.e. already gone). Anything else is a failed READ, never evidence of absence, and+ * the debt stays for the next connect.+ */+ private async settleOwedKills(projectId: string): Promise<void> {+ const c = this.conns.get(projectId)+ if (!c) return+ await drainPendingRemoteKills(sshHostKey(c.conn), async (session) => {+ const { code } = await this.r.run(remoteTmuxKillArgs(c.conn, c.controlPath, session))+ return code === 0 || code === 1+ })+ }+private async connectOnce(projectId: string,conn: SshConnection,diff --git a/src/renderer/lib/sessionKill.ts b/src/renderer/lib/sessionKill.tsindex 2c934a325..648e7c43e 100644--- a/src/renderer/lib/sessionKill.ts+++ b/src/renderer/lib/sessionKill.ts@@ -17,12 +17,15 @@// needs no live session. It is idempotent — a session already ended by `destroy` (the mounted case)// is a best-effort miss on the host — so no case analysis is needed at the call site.-// KNOWN GAP, recorded in docs/session-memory.md's "Known gaps": the SESSIONS SIDEBAR still calls-// `closeSession` with no remote leg, so ending an unmounted SSH node's session there leaves the-// host's `nt-<id>` running after a confirm that said otherwise — the two surfaces now disagree-// about the same session. Its correct fix is owner-routed per row (the row's OWNER project's-// master, not the active project's, which is only sound here because the panel shows one machine-// at a time); reuse this file rather than adding a third kill path.+// That gap is CLOSED, and not here: `PtyManager.runEndSession` no longer decides remoteness from+// the live `Session` alone. A resolver wired from the persisted index (`setRemoteNodeOwner` →+// `workspaceStore.sshProjectIdForNode` + that project's ControlMaster — see core/remote-end.ts)+// answers for a node with no live client at all, so every `transport.destroy` — the sessions+// sidebar's `closeSession`, the node `×`, Delete, a delete after an app restart — now reaches the+// host by itself, and a kill it could not deliver is written down rather than swallowed.+//+// This file therefore stays for what it always was: the panel's ORPHAN rows, which carry no node+// id any project claims, so no resolver can find an owner for them. Do not add a third kill path.import type { Project } from '@shared/types'