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): dispose offline session by binding; reconnect disposes stale only after rebind

enesc7ade2993fce
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index dfb2b2219..2dc01aa98 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -131,7 +131,13 @@ import {
import { relativeTime } from '../lib/relativeTime'
import { AgentIcon } from '../lib/agentIcons'
import { branchClaudeSession } from '../lib/claudeBranch'
-import { useSession, SessionProvider, sessionForProject, setActiveSession } from '../session/session'
+import {
+ useSession,
+ SessionProvider,
+ sessionForProject,
+ setActiveSession,
+ disposeSession,
+} from '../session/session'
import {
openRelayTab,
handleRelayDrop,
@@ -440,12 +446,19 @@ export function Canvas() {
// relay session down (held presence teardown + socket close), or the peer lingers in the host's
// facepile and the socket leaks until quit. Runs on BOTH close and delete (unlike a local tmux
// project, there is nothing to keep warm). No-op for a non-relay project.
+ //
+ // Dispose by the project BINDING, not by iterating relayTabsRef: an INVOLUNTARY drop already
+ // removed the tab from relayTabsRef (it went offline) but KEPT the session bound, so only
+ // `sessionForProject` still reaches it — iterating relayTabsRef alone would orphan the offline
+ // session in the registry forever. `disposeSession` is idempotent: it runs the held teardowns for
+ // a still-live tab, no-ops them for an already-offline one, and unbinds + drops the entry either
+ // way. We also sweep any live relayTabsRef entry for the project so a dead connectionId can't linger.
const disposeRelayTabForProject = useCallback((projectId: string) => {
for (const [connectionId, tab] of relayTabsRef.current) {
- if (tab.projectId !== projectId) continue
- relayTabsRef.current.delete(connectionId)
- tab.dispose() // idempotent — a prior socket-drop dispose leaves this a safe no-op
+ if (tab.projectId === projectId) relayTabsRef.current.delete(connectionId)
}
+ const s = sessionForProject(projectId)
+ if (s.source === 'relay') disposeSession(s.id)
}, [])
const [remoteDialogOpen, setRemoteDialogOpen] = useState(false)
// "Connect over SSH…" project-creation dialog (from the Welcome screen).
@@ -1807,7 +1820,12 @@ export function Canvas() {
// to the EXISTING project id (reuse the tab, clear its "unavailable" grey) instead of adding a new
// one — so a socket drop → greyed reconnectable tab, never a duplicate.
const mountRemoteMirror = useCallback(
- (connectionId: string, label = 'Remote host', reconnectProjectId?: string) => {
+ (
+ connectionId: string,
+ label = 'Remote host',
+ reconnectProjectId?: string,
+ staleSessionId?: string
+ ) => {
if (relayTabsRef.current.has(connectionId)) return
void openRelayTab(connectionId, label, {
relayClient: window.nodeTerminal.relayClient,
@@ -1818,8 +1836,15 @@ export function Canvas() {
})
.then((tab) => {
relayTabsRef.current.set(connectionId, tab)
- // Back online: un-grey the reused tab.
- if (reconnectProjectId) useProjects.getState().setProjectUnavailable(reconnectProjectId, false)
+ if (reconnectProjectId) {
+ // The fresh session is now bound to the tab (openRelayTab rebound the SAME project id),
+ // so it is finally safe to drop the stale offline session it replaced. Disposing only
+ // AFTER a successful rebind is what keeps a FAILED reconnect reconnectable: if approval
+ // never lands, the offline session stays bound and the tab stays greyed-clickable.
+ if (staleSessionId) disposeSession(staleSessionId)
+ // Back online: un-grey the reused tab.
+ useProjects.getState().setProjectUnavailable(reconnectProjectId, false)
+ }
// A host/relay drop AFTER approval is INVOLUNTARY (not a user close): grey the tab to
// "unavailable" and take its session offline (presence teardown runs once) — but KEEP the
// project so a click can reconnect it in place. See relay-tab `handleRelayDrop`.
@@ -1846,7 +1871,7 @@ export function Canvas() {
// relay-api.ts gotcha 2). Shared by the first connect and the Task 7 reconnect (which passes the
// existing project id so the fresh session rebinds the SAME tab).
const confirmAndMount = useCallback(
- (connectionId: string, label: string, reconnectProjectId?: string) => {
+ (connectionId: string, label: string, reconnectProjectId?: string, staleSessionId?: string) => {
const unSas = window.nodeTerminal.relayClient.onSas(connectionId, (sas) => {
unSas()
if (sas && window.confirm(`Verify this code matches the one shown on the host:\n\n${sas}`)) {
@@ -1857,7 +1882,7 @@ export function Canvas() {
window.nodeTerminal.relayClient.disconnect(connectionId)
}
})
- mountRemoteMirror(connectionId, label, reconnectProjectId)
+ mountRemoteMirror(connectionId, label, reconnectProjectId, staleSessionId)
},
[mountRemoteMirror]
)
@@ -1877,21 +1902,18 @@ export function Canvas() {
// Reconnect an offline (dropped) relay tab IN PLACE (Stage 4 Task 7). The relay offer is
// single-use (main/remote/pairing.ts), so v1 has no silent/pinned reconnect — prompt for a FRESH
- // pairing code, drop the stale offline session, and mount the new connection onto the SAME tab.
+ // pairing code and mount the new connection onto the SAME tab. The stale offline session is
+ // captured here and disposed only AFTER the fresh session rebinds (in mountRemoteMirror's success
+ // path), so a cancelled/failed reconnect leaves the offline tab still bound and reconnectable.
const reconnectRelay = useCallback(
(projectId: string) => {
const label = useProjects.getState().getProject(projectId)?.name ?? 'Remote host'
+ const bound = sessionForProject(projectId)
+ const staleSessionId = bound.source === 'relay' ? bound.id : undefined
void reconnectRelayTab(projectId, {
promptForOffer: () => promptDialog({ message: "Paste the host's new pairing code:" }),
connect: (offer) => window.nodeTerminal.relayClient.connect(offer),
- mount: (connectionId, projId) => confirmAndMount(connectionId, label, projId),
- disposeStale: (projId) => {
- for (const [connId, tab] of relayTabsRef.current) {
- if (tab.projectId !== projId) continue
- relayTabsRef.current.delete(connId)
- tab.dispose() // disposeSession: unbind + drop the offline session before rebinding
- }
- },
+ mount: (connectionId, projId) => confirmAndMount(connectionId, label, projId, staleSessionId),
onError: (message) => window.alert(`Could not reconnect: ${message}`),
})
},
diff --git a/src/renderer/session/relay-tab.test.ts b/src/renderer/session/relay-tab.test.ts
index 59c3b30a0..77a0c2208 100644
--- a/src/renderer/session/relay-tab.test.ts
+++ b/src/renderer/session/relay-tab.test.ts
@@ -172,35 +172,46 @@ describe('reconnectRelayTab (Stage 4 Task 7 — reconnect an offline tab IN PLAC
deps: RelayReconnectDeps
connect: ReturnType<typeof vi.fn>
mount: ReturnType<typeof vi.fn>
- disposeStale: ReturnType<typeof vi.fn>
} {
const connect = vi.fn().mockResolvedValue('conn-new')
const mount = vi.fn()
- const disposeStale = vi.fn()
const deps: RelayReconnectDeps = {
promptForOffer: over.promptForOffer ?? (() => Promise.resolve('fresh-offer')),
connect: over.connect ?? connect,
mount: over.mount ?? mount,
- disposeStale: over.disposeStale ?? disposeStale,
onError: over.onError ?? vi.fn(),
}
- return { deps, connect, mount, disposeStale }
+ return { deps, connect, mount }
}
it('prompts for a FRESH code (the offer is single-use), connects, and mounts onto the SAME project', async () => {
- const { deps, connect, mount, disposeStale } = reconnectDeps()
+ const { deps, connect, mount } = reconnectDeps()
await reconnectRelayTab('proj-1', deps)
- expect(disposeStale).toHaveBeenCalledWith('proj-1') // the stale offline session is dropped first
expect(connect).toHaveBeenCalledWith('fresh-offer') // a fresh pairing, not a silent reuse
expect(mount).toHaveBeenCalledWith('conn-new', 'proj-1') // reuse the existing tab, not a new one
})
+ it('connects BEFORE anything tears the stale session down (a connect failure must not strand the tab)', async () => {
+ // The stale offline session is disposed by `mount`, only after the fresh session rebinds — never
+ // up-front — so a connect that throws leaves the tab still bound + reconnectable. Assert mount is
+ // the ONLY disposal lever and it never runs when connect fails.
+ const onError = vi.fn()
+ const mount = vi.fn()
+ const { deps } = reconnectDeps({
+ connect: vi.fn().mockRejectedValue(new Error('relay unreachable')),
+ mount,
+ onError,
+ })
+ await reconnectRelayTab('proj-1', deps)
+ expect(mount).not.toHaveBeenCalled() // nothing disposed the stale session → tab stays reconnectable
+ expect(onError).toHaveBeenCalledWith('relay unreachable')
+ })
+
it('a cancelled prompt reconnects nothing', async () => {
- const { deps, connect, mount, disposeStale } = reconnectDeps({
+ const { deps, connect, mount } = reconnectDeps({
promptForOffer: () => Promise.resolve(null),
})
await reconnectRelayTab('proj-1', deps)
- expect(disposeStale).not.toHaveBeenCalled()
expect(connect).not.toHaveBeenCalled()
expect(mount).not.toHaveBeenCalled()
})
diff --git a/src/renderer/session/relay-tab.ts b/src/renderer/session/relay-tab.ts
index 9dca3405d..61ce5f7b1 100644
--- a/src/renderer/session/relay-tab.ts
+++ b/src/renderer/session/relay-tab.ts
@@ -118,22 +118,24 @@ export interface RelayReconnectDeps {
/** `relayClient.connect` — resolves a fresh connectionId. */
connect(offer: string): Promise<string>
/** Confirm the SAS + mount the fresh connection onto the EXISTING project id (reuses the tab —
- * never a duplicate). Clears `unavailable` once the tab is live again. */
+ * never a duplicate). Disposes the stale offline session only after the fresh one rebinds, and
+ * clears `unavailable` once the tab is live again. */
mount(connectionId: string, projectId: string): void
- /** Dispose the stale offline tab for this project (unbind + drop from the registry) before the
- * same project id is rebound to the fresh session. */
- disposeStale(projectId: string): void
onError(message: string): void
}
/** Reconnect an offline relay tab IN PLACE — same project id, so no duplicate tab is spawned. v1:
- * the offer is single-use, so this prompts for a FRESH pairing code, disposes the stale offline
- * session, connects, and mounts onto the existing tab. Cancelling the prompt reconnects nothing. */
+ * the offer is single-use, so this prompts for a FRESH pairing code, connects, and mounts onto the
+ * existing tab. Cancelling the prompt reconnects nothing.
+ *
+ * The stale offline session is NOT torn down here: `mount` disposes it only once the fresh session
+ * has rebound the project (see Canvas `mountRemoteMirror`). Disposing it up-front would unbind the
+ * project, so a connect failure or a declined SAS would strand the tab resolved to the LOCAL
+ * session — greyed but no longer recognised as relay, hence no longer reconnectable. */
export async function reconnectRelayTab(projectId: string, deps: RelayReconnectDeps): Promise<void> {
const offer = (await deps.promptForOffer())?.trim()
if (!offer) return
try {
- deps.disposeStale(projectId)
const connectionId = await deps.connect(offer)
deps.mount(connectionId, projectId)
} catch (err) {
diff --git a/src/renderer/session/session.test.ts b/src/renderer/session/session.test.ts
index a1549b7d1..a66e5539e 100644
--- a/src/renderer/session/session.test.ts
+++ b/src/renderer/session/session.test.ts
@@ -204,6 +204,30 @@ describe('takeSessionOffline (Stage 4 Task 7 — an INVOLUNTARY drop, not a user
expect(relayClose).toHaveBeenCalledTimes(1)
})
+ it('an OFFLINE session stays disposable by BINDING (the Task-7 leak fix) and disposeSession runs its teardowns only once', () => {
+ // Regression: the drop path removed the tab from the Canvas relayTabsRef, so a cleanup that
+ // iterated relayTabsRef could no longer reach the offline session — it leaked in the registry
+ // forever. The fix disposes by the project BINDING instead, which takeSessionOffline KEEPS. This
+ // proves the offline session is still reachable + fully removable that way.
+ const local = createSession('local', fakeApi, 'This Mac')
+ setActiveSession(local.id)
+ const relay = createSession('relay', { marker: 'relay' } as unknown as NodeTerminalApi, 'remote')
+ const presenceTeardown = vi.fn()
+ holdSessionTeardown(relay.id, presenceTeardown)
+ bindProjectToSession('remote-tab', relay.id)
+ takeSessionOffline(relay.id) // teardown ran once here
+
+ // Resolve the offline session the way Canvas now does — through the binding, not relayTabsRef.
+ const bound = sessionForProject('remote-tab')
+ expect(bound.source).toBe('relay')
+ disposeSession(bound.id)
+
+ // Gone: entry dropped, binding pruned (falls back to local), and the teardown did NOT run twice.
+ expect(sessionCount()).toBe(1)
+ expect(sessionForProject('remote-tab')).toBe(local)
+ expect(presenceTeardown).toHaveBeenCalledTimes(1)
+ })
+
it('is a no-op for an unknown id', () => {
expect(() => takeSessionOffline('relay-nope')).not.toThrow()
})