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.

feat(relay): offline "unavailable" tab + reconnect (Stage 4 Task 7)

enes83bc99c814f8
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index e80665020..dfb2b2219 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -132,7 +132,12 @@ import { relativeTime } from '../lib/relativeTime'
import { AgentIcon } from '../lib/agentIcons'
import { branchClaudeSession } from '../lib/claudeBranch'
import { useSession, SessionProvider, sessionForProject, setActiveSession } from '../session/session'
-import { openRelayTab, type RelayTab } from '../session/relay-tab'
+import {
+ openRelayTab,
+ handleRelayDrop,
+ reconnectRelayTab,
+ type RelayTab,
+} from '../session/relay-tab'
import { buildBackgroundLinkMaps, buildContextLinkNote, buildLinkMap, buildNotePushMessage, classifyLink, type LinkEndpoint } from '../lib/noteLink'
import { useSettings } from '../state/settings'
import { activePermissionMode } from '../state/permissionMode'
@@ -1798,38 +1803,50 @@ export function Canvas() {
// expected, not an error to alert about.
const cancelledConnsRef = useRef<Set<string>>(new Set())
- const mountRemoteMirror = useCallback((connectionId: string, label = 'Remote host') => {
- if (relayTabsRef.current.has(connectionId)) return
- void openRelayTab(connectionId, label, {
- relayClient: window.nodeTerminal.relayClient,
- addProject: (name) => useProjects.getState().addProject(name),
- setActiveProject: (id) => useProjects.getState().setActive(id),
- })
- .then((tab) => {
- relayTabsRef.current.set(connectionId, tab)
- // A host/relay drop after approval tears the tab's session down (once).
- const un = window.nodeTerminal.relayClient.onClosed(connectionId, () => {
- un()
- relayTabsRef.current.delete(connectionId)
- tab.dispose()
- })
+ // `reconnectProjectId` (Stage 4 Task 7): when reconnecting an offline tab, bind the fresh session
+ // 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) => {
+ if (relayTabsRef.current.has(connectionId)) return
+ void openRelayTab(connectionId, label, {
+ relayClient: window.nodeTerminal.relayClient,
+ addProject: reconnectProjectId
+ ? () => ({ id: reconnectProjectId }) // reconnect: reuse the existing tab, don't spawn one
+ : (name) => useProjects.getState().addProject(name),
+ setActiveProject: (id) => useProjects.getState().setActive(id),
})
- .catch((err) => {
- // A user who declined the SAS triggered this close themselves — don't cry error.
- if (cancelledConnsRef.current.delete(connectionId)) return
- window.alert(`Remote session did not open: ${(err as Error).message}`)
- })
- }, [])
+ .then((tab) => {
+ relayTabsRef.current.set(connectionId, tab)
+ // Back online: un-grey the reused tab.
+ if (reconnectProjectId) 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`.
+ const un = window.nodeTerminal.relayClient.onClosed(connectionId, () => {
+ un()
+ relayTabsRef.current.delete(connectionId)
+ handleRelayDrop(tab, {
+ setProjectUnavailable: (id, v) => useProjects.getState().setProjectUnavailable(id, v),
+ })
+ })
+ })
+ .catch((err) => {
+ // A user who declined the SAS triggered this close themselves — don't cry error.
+ if (cancelledConnsRef.current.delete(connectionId)) return
+ window.alert(`Remote session did not open: ${(err as Error).message}`)
+ })
+ },
+ []
+ )
- // "New Remote Connection" entry point (dock / palette): paste a host's pairing offer, connect,
- // compare the SAS, confirm, and open the host as a project tab. This is the primary remote entry.
- const connectRemote = useCallback(async () => {
- const offer = (await promptDialog({ message: "Paste the host's pairing code:" }))?.trim()
- if (!offer) return
- try {
- const connectionId = await window.nodeTerminal.relayClient.connect(offer)
- // Surface the SAS so this human can verify it matches the host's before confirming (the
- // mutual-approval gate — the confirm rides the ENCRYPTED tunnel in main; see relay-client.ts).
+ // Surface the SAS so this human can verify it matches the host's before confirming (the
+ // mutual-approval gate — the confirm rides the ENCRYPTED tunnel in main; see relay-client.ts),
+ // then build the tab (registers the one-shot onApproved listener BEFORE approval fires — see
+ // 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) => {
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}`)) {
@@ -1840,13 +1857,46 @@ export function Canvas() {
window.nodeTerminal.relayClient.disconnect(connectionId)
}
})
- // Build the tab now (registers the one-shot onApproved listener BEFORE approval fires — see
- // relay-api.ts gotcha 2); it resolves once both humans confirm.
- mountRemoteMirror(connectionId)
+ mountRemoteMirror(connectionId, label, reconnectProjectId)
+ },
+ [mountRemoteMirror]
+ )
+
+ // "New Remote Connection" entry point (dock / palette): paste a host's pairing offer, connect,
+ // compare the SAS, confirm, and open the host as a project tab. This is the primary remote entry.
+ const connectRemote = useCallback(async () => {
+ const offer = (await promptDialog({ message: "Paste the host's pairing code:" }))?.trim()
+ if (!offer) return
+ try {
+ const connectionId = await window.nodeTerminal.relayClient.connect(offer)
+ confirmAndMount(connectionId, 'Remote host')
} catch (err) {
window.alert(`Could not connect: ${(err as Error).message}`)
}
- }, [mountRemoteMirror])
+ }, [confirmAndMount])
+
+ // 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.
+ const reconnectRelay = useCallback(
+ (projectId: string) => {
+ const label = useProjects.getState().getProject(projectId)?.name ?? 'Remote host'
+ 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
+ }
+ },
+ onError: (message) => window.alert(`Could not reconnect: ${message}`),
+ })
+ },
+ [confirmAndMount]
+ )
/** Open a file as a code editor node on the canvas. `sshFs` must be passed explicitly by the
* caller: only genuinely-remote, Explorer-opened files in an SSH project pass `true`; native
@@ -5074,6 +5124,7 @@ export function Canvas() {
<div className="canvas-root">
<TabBar
onSwitch={switchProject}
+ onReconnect={reconnectRelay}
onOpenWelcome={() => setWelcomeOpen(true)}
onRename={renameProject}
onSetFolder={setProjectFolder}
diff --git a/src/renderer/components/TabBar.tsx b/src/renderer/components/TabBar.tsx
index 8c471a54d..b20b74918 100644
--- a/src/renderer/components/TabBar.tsx
+++ b/src/renderer/components/TabBar.tsx
@@ -5,7 +5,8 @@ import { useAgentStatus } from '../state/agentStatus'
import { useSettings } from '../state/settings'
import { accountsForProject, systemAccountDisplay } from '../state/workspace'
import { useSystemAccount } from '../state/systemAccount'
-import { sessionCount, useProjectSession } from '../session/session'
+import { sessionCount, sessionForProject, useProjectSession } from '../session/session'
+import { tabClickAction } from '../session/relay-tab'
import {
ALL_PERMISSION_MODES,
PERMISSION_MODE_LABELS,
@@ -14,6 +15,9 @@ import {
interface TabBarProps {
onSwitch: (id: string) => void
+ /** Reconnect an offline (dropped) relay tab in place (Stage 4 Task 7). Called when an
+ * "unavailable" tab whose session is a relay/server source is clicked. */
+ onReconnect: (id: string) => void
/** Open the start screen (New project / Open folder / Clone repo) — what "+" now shows. */
onOpenWelcome: () => void
onRename: (id: string, name: string) => void
@@ -52,6 +56,7 @@ function TabSessionLabel({ projectId }: { projectId: string }) {
*/
export function TabBar({
onSwitch,
+ onReconnect,
onOpenWelcome,
onRename,
onSetFolder,
@@ -190,10 +195,19 @@ export function TabBar({
key={p.id}
className={`tab${active ? ' active' : ''}${p.unavailable ? ' unavailable' : ''}`}
style={active ? { color: p.color } : undefined}
- onClick={() => !editingId && !p.unavailable && onSwitch(p.id)}
+ onClick={() => {
+ if (editingId) return
+ // An unavailable tab distinguishes by its bound session source: a dropped RELAY
+ // tab reconnects on click (Stage 4 Task 7), a missing local folder is inert.
+ const action = tabClickAction(!!p.unavailable, sessionForProject(p.id).source)
+ if (action === 'switch') onSwitch(p.id)
+ else if (action === 'reconnect') onReconnect(p.id)
+ }}
title={
p.unavailable
- ? `${p.cwd ?? 'project'} is unavailable (folder missing or unreachable)`
+ ? sessionForProject(p.id).source === 'local'
+ ? `${p.cwd ?? 'project'} is unavailable (folder missing or unreachable)`
+ : `${p.name} disconnected — click to reconnect`
: p.cwd || undefined
}
>
diff --git a/src/renderer/session/relay-tab.test.ts b/src/renderer/session/relay-tab.test.ts
index 7eaa2de19..59c3b30a0 100644
--- a/src/renderer/session/relay-tab.test.ts
+++ b/src/renderer/session/relay-tab.test.ts
@@ -1,5 +1,12 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
-import { openRelayTab, type RelayTabDeps } from './relay-tab'
+import {
+ openRelayTab,
+ handleRelayDrop,
+ reconnectRelayTab,
+ tabClickAction,
+ type RelayTabDeps,
+ type RelayReconnectDeps,
+} from './relay-tab'
import {
createSession,
setActiveSession,
@@ -25,19 +32,22 @@ function fakeRelayClient() {
}
}
-/** A bridged relay api whose `pty.create` is a spy — this is what `LocalTransport(api)` must hit. */
+/** A bridged relay api whose `pty.create` is a spy — this is what `LocalTransport(api)` must hit.
+ * `presenceUnsub` is what the session's held presence teardown calls (onSync's unsubscribe), so a
+ * drop that "runs the presence teardown" is observable in node env. */
function fakeBridgedApi() {
const ptyCreate = vi.fn().mockResolvedValue({ sessionId: 's1', fresh: false })
+ const presenceUnsub = vi.fn()
const api = {
marker: 'relay-bridged',
pty: { create: ptyCreate },
presence: {
hello: vi.fn().mockResolvedValue({ clientId: 'x', peers: [] }),
- onSync: vi.fn(() => () => {}),
+ onSync: vi.fn(() => presenceUnsub),
onPeer: vi.fn(() => () => {}),
},
} as unknown as NodeTerminalApi
- return { api, ptyCreate }
+ return { api, ptyCreate, presenceUnsub }
}
function makeDeps(over: Partial<RelayTabDeps> & { handle: RelayApiHandle }): {
@@ -129,3 +139,93 @@ describe('openRelayTab (connect → tab → mount)', () => {
}
})
})
+
+describe('handleRelayDrop (Stage 4 Task 7 — involuntary drop → greyed reconnectable tab)', () => {
+ it('marks the bound project unavailable + runs the presence teardown ONCE, never removes it', async () => {
+ const { api, presenceUnsub } = fakeBridgedApi()
+ const close = vi.fn()
+ const handle: RelayApiHandle = { api, ready: () => Promise.resolve(), close }
+ const { deps } = makeDeps({ handle })
+ const tab = await openRelayTab('conn-1', "Ayşe's Mac", deps)
+
+ const setProjectUnavailable = vi.fn()
+ handleRelayDrop(tab, { setProjectUnavailable })
+
+ // The tab greys but survives — the peer left every facepile (presence teardown ran) and the
+ // dead socket was closed, but the PROJECT is kept and stays bound to a 'relay' source.
+ expect(setProjectUnavailable).toHaveBeenCalledWith(tab.projectId, true)
+ expect(presenceUnsub).toHaveBeenCalledTimes(1)
+ expect(close).toHaveBeenCalledTimes(1)
+ expect(sessionForProject(tab.projectId).source).toBe('relay') // still reconnectable in place
+ expect(sessionForProject(tab.projectId).status).toBe('offline')
+ expect(sessionCount()).toBe(2) // local + the offline relay — NOT removed
+
+ // Idempotent: a redundant drop (a revoke racing the FIN) re-runs no teardown.
+ handleRelayDrop(tab, { setProjectUnavailable })
+ expect(presenceUnsub).toHaveBeenCalledTimes(1)
+ expect(close).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('reconnectRelayTab (Stage 4 Task 7 — reconnect an offline tab IN PLACE)', () => {
+ function reconnectDeps(over: Partial<RelayReconnectDeps> = {}): {
+ 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 }
+ }
+
+ 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()
+ 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('a cancelled prompt reconnects nothing', async () => {
+ const { deps, connect, mount, disposeStale } = reconnectDeps({
+ promptForOffer: () => Promise.resolve(null),
+ })
+ await reconnectRelayTab('proj-1', deps)
+ expect(disposeStale).not.toHaveBeenCalled()
+ expect(connect).not.toHaveBeenCalled()
+ expect(mount).not.toHaveBeenCalled()
+ })
+
+ it('surfaces a connect failure through onError (no throw)', async () => {
+ const onError = vi.fn()
+ const { deps } = reconnectDeps({
+ connect: vi.fn().mockRejectedValue(new Error('relay unreachable')),
+ onError,
+ })
+ await expect(reconnectRelayTab('proj-1', deps)).resolves.toBeUndefined()
+ expect(onError).toHaveBeenCalledWith('relay unreachable')
+ })
+})
+
+describe('tabClickAction (which behavior a tab click gets)', () => {
+ it('an available tab switches', () => {
+ expect(tabClickAction(false, 'relay')).toBe('switch')
+ expect(tabClickAction(false, 'local')).toBe('switch')
+ })
+ it('an unavailable RELAY tab reconnects (a socket drop, clickable to reconnect)', () => {
+ expect(tabClickAction(true, 'relay')).toBe('reconnect')
+ expect(tabClickAction(true, 'server')).toBe('reconnect')
+ })
+ it('an unavailable LOCAL tab is inert (a missing folder, not clickable-to-reconnect)', () => {
+ expect(tabClickAction(true, 'local')).toBe('ignore')
+ })
+})
diff --git a/src/renderer/session/relay-tab.ts b/src/renderer/session/relay-tab.ts
index 15b616355..9dca3405d 100644
--- a/src/renderer/session/relay-tab.ts
+++ b/src/renderer/session/relay-tab.ts
@@ -23,6 +23,8 @@ import {
holdSessionTeardown,
disposeSession,
getSessionStores,
+ takeSessionOffline,
+ type SessionSource,
} from './session'
/** Backstop for a `ready()` that neither approves nor closes (the network vanished without a FIN). */
@@ -86,6 +88,70 @@ export async function openRelayTab(
}
}
+// ── Stage 4 Task 7: offline "unavailable" tab + reconnect ────────────────────────────────────────
+//
+// A relay tab is a connection BOOKMARK, not a workspace on the peer's disk (docs/remote-sessions.md
+// "Persistence"). So an involuntary socket drop must NOT vanish the tab — it greys to "unavailable"
+// (reusing the workspace-index rendering) and reconnects on click. This is DISTINCT from a
+// user-initiated close (`RelayTab.dispose` → `disposeSession`, which drops the tab): closing by hand
+// is deliberate destruction; a dropped socket is a temporary outage the host's tmux survives.
+
+export interface RelayDropDeps {
+ /** Grey the tab without dropping it (`useProjects.getState().setProjectUnavailable`). */
+ setProjectUnavailable(projectId: string, unavailable: boolean): void
+}
+
+/** Handle an INVOLUNTARY relay socket drop (host/relay gone): take the session offline — its
+ * presence teardown runs ONCE so the peer leaves every facepile, the already-dead socket close
+ * no-ops — but KEEP the project tab and its 'relay' binding so it greys to "unavailable" and can
+ * reconnect in place. NEVER removes the project (that is only a user close). Idempotent. */
+export function handleRelayDrop(tab: RelayTab, deps: RelayDropDeps): void {
+ takeSessionOffline(tab.sessionId)
+ deps.setProjectUnavailable(tab.projectId, true)
+}
+
+export interface RelayReconnectDeps {
+ /** Prompt the human for a FRESH pairing code. The relay offer carries a SINGLE-USE token
+ * (main/remote/pairing.ts), so v1 has no silent/pinned reconnect — the host must mint a new
+ * offer. Returns null when cancelled. */
+ promptForOffer(): Promise<string | null>
+ /** `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. */
+ 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. */
+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) {
+ deps.onError(err instanceof Error ? err.message : String(err))
+ }
+}
+
+/** Which behavior a tab click gets. An available tab switches. An unavailable tab distinguishes by
+ * its bound session SOURCE: a relay/server drop is clickable-to-reconnect; a local unavailable tab
+ * is a missing folder — inert (there is nothing to reconnect to). */
+export function tabClickAction(
+ unavailable: boolean,
+ source: SessionSource
+): 'switch' | 'reconnect' | 'ignore' {
+ if (!unavailable) return 'switch'
+ return source === 'local' ? 'ignore' : 'reconnect'
+}
+
/** Resolve on approval (`handle.ready()`); reject on a pre-approval socket drop or a timeout. */
function raceApproval(
handle: RelayApiHandle,
diff --git a/src/renderer/session/session.test.ts b/src/renderer/session/session.test.ts
index 865541b7a..a1549b7d1 100644
--- a/src/renderer/session/session.test.ts
+++ b/src/renderer/session/session.test.ts
@@ -12,6 +12,8 @@ import {
disposeSession,
holdSessionTeardown,
setMeAll,
+ setSessionStatus,
+ takeSessionOffline,
} from './session'
import type { NodeTerminalApi } from '@shared/types'
import type { PeerIdentity } from '@shared/presence'
@@ -174,6 +176,48 @@ describe('disposeSession (obligation 1 — the missing disposal path)', () => {
})
})
+describe('takeSessionOffline (Stage 4 Task 7 — an INVOLUNTARY drop, not a user close)', () => {
+ it('runs held teardowns once and flips status offline, but KEEPS the entry + its binding', () => {
+ 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()
+ const relayClose = vi.fn()
+ holdSessionTeardown(relay.id, presenceTeardown)
+ holdSessionTeardown(relay.id, relayClose)
+ bindProjectToSession('remote-tab', relay.id)
+
+ takeSessionOffline(relay.id)
+
+ // The peer left every facepile (presence teardown ran) and the dead socket was closed — ONCE.
+ expect(presenceTeardown).toHaveBeenCalledTimes(1)
+ expect(relayClose).toHaveBeenCalledTimes(1)
+ // Unlike disposeSession, the session survives (offline) and the tab stays bound to it — that is
+ // what lets the greyed tab resolve to a 'relay' source and reconnect in place.
+ expect(sessionCount()).toBe(2)
+ expect(sessionForProject('remote-tab')).toBe(relay)
+ expect(sessionForProject('remote-tab').status).toBe('offline')
+
+ // Idempotent: a second drop (a revoke racing the FIN) re-runs nothing.
+ takeSessionOffline(relay.id)
+ expect(presenceTeardown).toHaveBeenCalledTimes(1)
+ expect(relayClose).toHaveBeenCalledTimes(1)
+ })
+
+ it('is a no-op for an unknown id', () => {
+ expect(() => takeSessionOffline('relay-nope')).not.toThrow()
+ })
+
+ it('setSessionStatus updates a live session and no-ops for an unknown id', () => {
+ const s = createSession('relay', { marker: 'relay' } as unknown as NodeTerminalApi, 'remote')
+ setSessionStatus(s.id, 'connecting')
+ expect(s.status).toBe('connecting')
+ setSessionStatus(s.id, 'connected')
+ expect(s.status).toBe('connected')
+ expect(() => setSessionStatus('nope', 'offline')).not.toThrow()
+ })
+})
+
describe('setMeAll (obligation 2 — a rename re-helloes EVERY live session)', () => {
it('re-helloes and updates identity on all registered sessions, not just the active one', () => {
const a = apiWithHelloSpy('a')
diff --git a/src/renderer/session/session.ts b/src/renderer/session/session.ts
index ab5b13e77..d053cdece 100644
--- a/src/renderer/session/session.ts
+++ b/src/renderer/session/session.ts
@@ -81,6 +81,18 @@ export function holdSessionTeardown(sessionId: string, teardown: () => void): vo
e.teardowns.push(teardown)
}
+/** Run a session's held teardowns EXACTLY ONCE. splice() so a teardown that (re-entrantly) triggers
+ * another run finds nothing left to re-run. Shared by disposeSession + takeSessionOffline. */
+function runTeardowns(e: Entry): void {
+ for (const t of e.teardowns.splice(0)) {
+ try {
+ t()
+ } catch (err) {
+ console.warn('[session] teardown failed', err)
+ }
+ }
+}
+
/** Tear a session down (obligation 1 — the missing disposal path a remote tab needs on disconnect):
* run every held teardown EXACTLY ONCE, drop the entry, and unbind its projects so their (now
* dead) tabs resolve back to the local session. Idempotent and no-op for an unknown id — a double
@@ -89,19 +101,33 @@ export function disposeSession(sessionId: string): void {
const e = SESSIONS.get(sessionId)
if (!e || e.disposed) return
e.disposed = true
- // splice() so a teardown that (re-entrantly) calls disposeSession again finds nothing to re-run.
- for (const t of e.teardowns.splice(0)) {
- try {
- t()
- } catch (err) {
- console.warn('[session] teardown failed', err)
- }
- }
+ runTeardowns(e)
SESSIONS.delete(sessionId)
for (const [projectId, sid] of PROJECT_BINDINGS) if (sid === sessionId) PROJECT_BINDINGS.delete(projectId)
if (activeId === sessionId) activeId = SESSIONS.has('local') ? 'local' : null
}
+/** Set a session's live status (Stage 4 Task 7 — a relay tab going offline / reconnecting). No-op
+ * for an unknown id. This mutates the live session object in place, which is how the tab session
+ * label (and the offline gate) read the current state without re-registering the session. */
+export function setSessionStatus(sessionId: string, status: WorkspaceSession['status']): void {
+ const e = SESSIONS.get(sessionId)
+ if (e) e.session.status = status
+}
+
+/** Take a session OFFLINE on an INVOLUNTARY socket drop (host/relay gone) — the counterpart of a
+ * user close. Unlike disposeSession, this KEEPS the entry and its project binding: run the held
+ * teardowns once (presence leaves every peer's facepile; the already-dead relay socket close is a
+ * safe no-op) and flip status to 'offline', but leave the tab bound to a 'relay' source so the
+ * greyed "unavailable" tab can reconnect IN PLACE (see relay-tab `handleRelayDrop` / `tabClickAction`).
+ * Idempotent; no-op once offline/disposed/unknown. */
+export function takeSessionOffline(sessionId: string): void {
+ const e = SESSIONS.get(sessionId)
+ if (!e || e.disposed || e.session.status === 'offline') return
+ runTeardowns(e)
+ e.session.status = 'offline'
+}
+
/** Test-only: clears the registry so each test starts with no sessions. */
export function resetSessionsForTest(): void {
SESSIONS.clear()
diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.ts
index 12cb775d1..8faa533b5 100644
--- a/src/renderer/state/projects.ts
+++ b/src/renderer/state/projects.ts
@@ -32,6 +32,10 @@ interface ProjectsState {
replaceProject(project: Project): void
renameProject(id: string, name: string): void
setProjectCwd(id: string, cwd: string): void
+ /** Grey (or un-grey) a project tab as "unavailable" WITHOUT dropping it — runtime-only, never
+ * persisted (see the toWorkspace tripwire). Set true when a relay tab's socket drops (Stage 4
+ * Task 7) so it stays reconnectable; cleared when it reconnects. */
+ setProjectUnavailable(id: string, unavailable: boolean): void
/** Sets (or clears, with undefined) the project's default Claude account for new nodes. */
setProjectDefaultAccount(id: string, accountId: string | undefined): void
/** Sets (or clears, with undefined = fall back to the global setting) the project's default
@@ -179,6 +183,12 @@ export const useProjects = create<ProjectsState>((set, get) => ({
}))
},
+ setProjectUnavailable(id, unavailable) {
+ set((s) => ({
+ projects: s.projects.map((p) => (p.id === id ? { ...p, unavailable } : p))
+ }))
+ },
+
setProjectDefaultAccount(id, accountId) {
set((s) => ({
projects: s.projects.map((p) => (p.id === id ? { ...p, defaultAccountId: accountId } : p))