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(persistence): warn when local session protection is unavailable
enes0b479f8a034f
diff --git a/docs/windows-session-host.md b/docs/windows-session-host.mdindex 3ebb82400..15dadfa6c 100644--- a/docs/windows-session-host.md+++ b/docs/windows-session-host.md@@ -69,6 +69,21 @@ Electron main process Session-host process (standalone, detacthis backend between the tmux branch and the plain-shell fallback, and constructs a`SessionHostPty` instead of calling `pty.spawn` directly.+## Availability notice++`pty:tmux-status` retains its tmux-only `available` field and adds `persistence`: the+user's `enabled` setting and the discovered `backend` (`tmux`, `session-host`, or null).+Discovery does not start the host or certify runtime health. POSIX prefers tmux; Windows+uses the session host. A missing/errored status stays unknown, including over Server Edition's+WS bridge. Older peers without the field also remain unknown.++The desktop/browser banner warns when protection is disabled, absent, or unknown; Settings+shows the same state and refreshes it after a setting change and periodically. The state is+about **new local terminals**, not SSH/relay hosts or an upgrade of existing plain shells.+An installer is offered only from a local project, so it cannot run on the selected remote+host by mistake. Runtime session-host attach failures still use the terminal's existing error+path; a bundle being present is not proof an individual session attached successfully.+## Windows profile resolutionThe profile catalog is a trusted desktop service. Its public API returns only a stable `id`,diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex f2651bb85..6fa504e85 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -1781,10 +1781,7 @@ export class PtyManager {)}- /** Feeds the renderer's "tmux not found" banner. Without tmux the app silently degrades to a- * plain shell (no cross-restart continuity, no mobile attach) — users never discover that on- * their own, so the banner surfaces it with a one-click install command when a known package- * manager is present (run in a terminal node, gh-sign-in style). */+ /** Discover the backend for NEW local terminals without starting a session host. */tmuxStatus(): TmuxStatus {// Re-probe when unavailable: the banner polls this while its install command runs, and a// successful probe here is what makes new sessions tmux-backed without a restart.@@ -1792,12 +1789,19 @@ export class PtyManager {const available = !!this.tmuxPathconst hint = available? null- : tmuxInstall(process.platform, (cmd) => findCommand(cmd, process.env, fs.existsSync))+ : tmuxInstall(this.runtimePlatform, (cmd) => findCommand(cmd, process.env, fs.existsSync))return {available,installCommand: hint?.command ?? null,installLabel: hint?.label ?? null,- platform: process.platform+ platform: this.runtimePlatform,+ persistence: {+ enabled: this.getSettings().tmuxEnabled,+ backend:+ this.runtimePlatform !== 'win32' && available+ ? 'tmux'+ : sessionHostSupported() ? 'session-host' : null+ }}}diff --git a/src/core/pty-persistence-status.test.ts b/src/core/pty-persistence-status.test.tsnew file mode 100644index 000000000..9095d1c82--- /dev/null+++ b/src/core/pty-persistence-status.test.ts@@ -0,0 +1,41 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'+import { PtyManager } from './pty-manager'++const host = vi.hoisted(() => ({ supported: vi.fn(() => false) }))+vi.mock('./session-host-backend', () => ({ sessionHostSupported: host.supported }))+vi.mock('node-pty', () => ({ spawn: vi.fn() }))++describe('local persistence discovery (#575)', () => {+ beforeEach(() => { initPlatform(fakePlatform()); host.supported.mockReturnValue(false) })+ afterEach(() => { vi.restoreAllMocks(); resetPlatformForTests() })++ function manager(platform: NodeJS.Platform, tmux: boolean, enabled = true): PtyManager {+ const mgr = new PtyManager({ runtimePlatform: platform })+ // Isolate discovery from the real machine, config writes and running tmux servers.+ Object.assign(mgr, { tmuxPath: tmux ? '/fixture/tmux' : null, getSettings: () => ({ tmuxEnabled: enabled }) })+ vi.spyOn(mgr, 'ensureTmux').mockImplementation(() => {})+ return mgr+ }++ it.each(['win32', 'linux', 'darwin'] as const)('reports missing and newly available host on %s', (os) => {+ const mgr = manager(os, false)+ expect(mgr.tmuxStatus()).toMatchObject({ platform: os, persistence: { enabled: true, backend: null } })+ host.supported.mockReturnValue(true)+ expect(mgr.tmuxStatus().persistence).toEqual({ enabled: true, backend: 'session-host' })+ })+ it('prefers tmux on POSIX, without even probing the host', () => {+ host.supported.mockClear()+ expect(manager('darwin', true).tmuxStatus().persistence?.backend).toBe('tmux')+ expect(host.supported).not.toHaveBeenCalled()+ })+ it('never treats a Windows tmux path as protection', () => {+ expect(manager('win32', true).tmuxStatus().persistence?.backend).toBeNull()+ })+ it('keeps the user setting distinct from backend discovery', () => {+ host.supported.mockReturnValue(true)+ expect(manager('win32', false, false).tmuxStatus().persistence).toEqual({ enabled: false, backend: 'session-host' })+ expect(manager('linux', true, false).tmuxStatus().persistence).toEqual({ enabled: false, backend: 'tmux' })+ })+})diff --git a/src/renderer/bridge/ws-bridge.namespaces.test.ts b/src/renderer/bridge/ws-bridge.namespaces.test.tsindex 991169238..b1d4e5f18 100644--- a/src/renderer/bridge/ws-bridge.namespaces.test.ts+++ b/src/renderer/bridge/ws-bridge.namespaces.test.ts@@ -99,10 +99,11 @@ describe('buildRealApi: host platform', () => {const api = buildRealApi(c as never)await expect(api.pty.tmuxStatus()).resolves.toEqual({- available: true,+ available: false,installCommand: null,installLabel: null,- platform: null+ platform: null,+ persistence: null})})})diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex bc8a799ea..0ad3efbdd 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -259,11 +259,11 @@ export function buildRealApi(client.request(IPC.ptyReadScrollback, persistKey) as Promise<string>,sendText: (persistKey, text, opts) =>client.request(IPC.ptySendText, persistKey, text, opts?.enter) as Promise<boolean>,- // Fail-open: an errored status must not raise the banner in the browser.+ // A failed read is unknown, never evidence that persistence is available.tmuxStatus: () =>client.request(IPC.ptyTmuxStatus)- .catch(() => ({ available: true, installCommand: null, installLabel: null, platform: null })) as Promise<TmuxStatus>,+ .catch(() => ({ available: false, installCommand: null, installLabel: null, platform: null, persistence: null })) as Promise<TmuxStatus>,// Unknown on failure (null), never a rejection: the restart poller reads null as "not a// shell yet" and gives up on its own deadline.paneCommand: (persistKey) =>diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 9cbed6b7a..b909dd287 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -193,6 +193,7 @@ import { UpdateCard } from '../components/UpdateCard'import { AnnouncementBanner } from '../components/AnnouncementBanner'import { ResumeCard } from '../components/ResumeCard'import { TmuxBanner } from '../components/TmuxBanner'+import { localSession } from '../session/localSession'import { PtyPressureBanner } from '../components/PtyPressureBanner'import { ShortcutCaptureBanner } from '../components/ShortcutCaptureBanner'import { ConflictBar } from '../components/ConflictBar'@@ -14156,7 +14157,10 @@ export function Canvas() {<div className="top-banners"><AnnouncementBanner />- <TmuxBanner onInstall={runInTerminal} />+ {/* Discovery belongs to the local core; never run its installer on an SSH/relay host. */}+ <TmuxBanner+ onInstall={!isSshProject && session.id === localSession.id ? runInTerminal : undefined}+ />{/* This MACHINE is running out of pty devices — subscribes for itself; a failed"Fix automatically…" lands in the same notice strip as every other async op. */}<PtyPressureBanner onError={(text) => setNotice({ kind: 'error', text })} />diff --git a/src/renderer/components/TmuxBanner.tsx b/src/renderer/components/TmuxBanner.tsxindex 72a2b7851..3969cb54e 100644--- a/src/renderer/components/TmuxBanner.tsx+++ b/src/renderer/components/TmuxBanner.tsx@@ -1,18 +1,9 @@import { useEffect, useRef, useState } from 'react'import { IconClose } from './icons'-import type { TmuxStatus } from '@shared/types'+import { persistenceDescription, usePersistenceStatus } from './usePersistenceStatus'import { localSession } from '../session/localSession'-// "tmux not found" strip: without tmux the app silently degrades to a plain shell — terminals-// don't survive restarts and the mobile companion can't attach — and nothing used to say so-// (one field report ran degraded for months without anyone noticing). Shown every launch until-// tmux is installed; the ✕ hides it for this session only. The install button runs the suggested-// package-manager command in a new terminal node (the gh-sign-in pattern) and — unlike the first-// version, which dismissed the banner optimistically and left the user guessing (second field-// report) — keeps the banner up as a status strip: installing → ready | failed. tmuxStatus()-// re-probes on every call (ensureTmux), so `available` flipping true is also what makes NEW-// terminals tmux-backed without a restart. Hidden on win32 and on any fetch error (fail-open).-+// Backend discovery is shared with Settings. Availability does not assert runtime health.export const INSTALL_POLL_MS = 3000export const INSTALL_CAP_MS = 5 * 60_000export const READY_HIDE_MS = 6000@@ -25,27 +16,12 @@ export function pollOutcome(available: boolean, elapsedMs: number): InstallPhasereturn elapsedMs >= INSTALL_CAP_MS ? 'failed' : 'installing'}-export function TmuxBanner({ onInstall }: { onInstall: (command: string) => void }): JSX.Element | null {- const [status, setStatus] = useState<TmuxStatus | null>(null)+export function TmuxBanner({ onInstall }: { onInstall?: (command: string) => void }): JSX.Element | null {+ const status = usePersistenceStatus()const [dismissed, setDismissed] = useState(false)const [phase, setPhase] = useState<InstallPhase>('missing')const startedAtRef = useRef(0)- useEffect(() => {- let cancelled = false- // Deliberately the LOCAL session, not useSession(): this banner is about THIS machine's tmux- // (the host whose terminals lose continuity), never a relay tab's remote host.- localSession.api.pty- .tmuxStatus()- .then((s) => {- if (!cancelled) setStatus(s)- })- .catch(() => {})- return () => {- cancelled = true- }- }, [])-// While installing, poll tmuxStatus. The raw install output is visible in the spawned// terminal node either way — the banner only reports the outcome.useEffect(() => {@@ -59,7 +35,9 @@ export function TmuxBanner({ onInstall }: { onInstall: (command: string) => voidconst next = pollOutcome(s.available, Date.now() - startedAtRef.current)if (next !== 'installing') setPhase(next)})- .catch(() => {})+ .catch(() => {+ if (!cancelled && Date.now() - startedAtRef.current >= INSTALL_CAP_MS) setPhase('failed')+ })}, INSTALL_POLL_MS)return () => {cancelled = true@@ -74,23 +52,31 @@ export function TmuxBanner({ onInstall }: { onInstall: (command: string) => voidreturn () => clearTimeout(t)}, [phase])- if (!status || dismissed || status.platform === 'win32') return null- if (status.available && phase === 'missing') return null+ if (dismissed || status === undefined) return null+ if (status?.persistence?.enabled && status.persistence.backend && phase === 'missing') return nullconst title =- phase === 'installing' ? 'Installing tmux' : phase === 'ready' ? 'tmux ready' : 'tmux not found'+ phase === 'installing'+ ? 'Installing tmux'+ : phase === 'ready'+ ? 'tmux ready'+ : !status?.persistence+ ? 'Session protection unknown'+ : !status.persistence.enabled+ ? 'Session protection off'+ : 'Session protection unavailable'const body =phase === 'installing'? 'Running the install in a terminal node — watch it for progress (it may ask for your password).': phase === 'ready'- ? 'New terminals will survive restarts from now on. Terminals opened before the install stay on the plain shell.'+ ? 'tmux is now available for new local terminals. Existing plain-shell terminals are not upgraded.': phase === 'failed'? 'The install hasn’t completed. Check the terminal node for errors, or install tmux with your package manager and restart nodeterm.'- : status.installCommand- ? 'Terminals won’t survive restarts and the mobile app can’t attach until tmux is installed.'- : 'Terminals won’t survive restarts and the mobile app can’t attach. Install tmux with your package manager (e.g. brew install tmux), then restart nodeterm.'+ : persistenceDescription(status)- const showInstall = (phase === 'missing' || phase === 'failed') && !!status.installCommand+ const showInstall =+ (phase === 'missing' || phase === 'failed') && !!onInstall &&+ status?.persistence?.enabled && !status.persistence.backend && !!status.installCommandreturn (<div className="announce-banner announce-banner--warning"><span className="announce-banner__dot" />@@ -101,14 +87,14 @@ export function TmuxBanner({ onInstall }: { onInstall: (command: string) => void{showInstall && (<buttonclassName="announce-banner__btn"- title={status.installCommand!}+ title={status!.installCommand!}onClick={() => {- onInstall(status.installCommand!)+ onInstall?.(status!.installCommand!)startedAtRef.current = Date.now()setPhase('installing')}}>- {phase === 'failed' ? 'Retry' : (status.installLabel ?? 'Install tmux')}+ {phase === 'failed' ? 'Retry' : (status!.installLabel ?? 'Install tmux')}</button>)}<button className="announce-banner__close" title="Dismiss" aria-label="Dismiss" onClick={() => setDismissed(true)}>diff --git a/src/renderer/components/persistence-status.test.tsx b/src/renderer/components/persistence-status.test.tsxnew file mode 100644index 000000000..2851b8083--- /dev/null+++ b/src/renderer/components/persistence-status.test.tsx@@ -0,0 +1,80 @@+// @vitest-environment jsdom+import { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { TmuxStatus } from '@shared/types'+const mock = vi.hoisted(() => ({ read: vi.fn(), enabled: true }))+vi.mock('../session/localSession', () => ({ localSession: { api: { pty: { tmuxStatus: mock.read } } } }))+vi.mock('../state/settings', () => ({ useSettings: (select: (s: unknown) => unknown) => select({ settings: { tmuxEnabled: mock.enabled } }) }))+import { TmuxBanner } from './TmuxBanner'+import { persistenceDescription } from './usePersistenceStatus'+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true+const status = (backend: 'tmux' | 'session-host' | null, enabled = true, platform = 'win32'): TmuxStatus => ({+ available: backend === 'tmux', platform, installCommand: null, installLabel: null, persistence: { enabled, backend }+})+afterEach(() => { vi.useRealTimers(); mock.read.mockReset(); mock.enabled = true })++describe('session protection notice', () => {+ it.each([['win32', null], ['linux', null], ['darwin', null], ['win32', 'session-host'], ['linux', 'session-host'], ['darwin', 'tmux']] as const)(+ '%s / %s renders the actual backend availability', async (platform, backend) => {+ mock.read.mockResolvedValue(status(backend, true, platform))+ const el = document.createElement('div'); const root = createRoot(el)+ try {+ await act(async () => root.render(<TmuxBanner onInstall={vi.fn()} />))+ expect(el.textContent?.includes('No session protection backend')).toBe(backend === null)+ if (backend) expect(el.textContent).toBe('')+ } finally { await act(async () => root.unmount()) }+ }+ )+ it('refreshes after discovery changes, and warns on a failed read', async () => {+ vi.useFakeTimers()+ mock.read.mockResolvedValue(status(null))+ const el = document.createElement('div'); const root = createRoot(el)+ try {+ await act(async () => root.render(<TmuxBanner onInstall={vi.fn()} />))+ expect(el.textContent).toContain('will not survive')+ mock.read.mockResolvedValue(status('session-host'))+ await act(async () => { await vi.advanceTimersByTimeAsync(15_000) })+ expect(el.textContent).toBe('')+ mock.read.mockRejectedValue(new Error('offline'))+ await act(async () => { await vi.advanceTimersByTimeAsync(15_000) })+ expect(el.textContent).toContain('could not be checked')+ } finally { await act(async () => root.unmount()) }+ })+ it('offers installation only when the caller supplies a local route; tracks completion', async () => {+ vi.useFakeTimers()+ const missing = { ...status(null, true, 'linux'), installCommand: 'fixture-install', installLabel: 'Install tmux' }+ mock.read.mockResolvedValue(missing)+ const onInstall = vi.fn()+ const el = document.createElement('div'); const root = createRoot(el)+ try {+ await act(async () => root.render(<TmuxBanner />))+ expect(el.querySelector('.announce-banner__btn')).toBeNull()+ await act(async () => root.render(<TmuxBanner onInstall={onInstall} />))+ await act(async () => (el.querySelector('.announce-banner__btn') as HTMLButtonElement).click())+ expect(onInstall).toHaveBeenCalledWith('fixture-install')+ expect(el.textContent).toContain('Installing tmux')+ mock.read.mockResolvedValue(status('tmux', true, 'linux'))+ await act(async () => { await vi.advanceTimersByTimeAsync(3000) })+ expect(el.textContent).toContain('Existing plain-shell terminals are not upgraded')+ } finally { await act(async () => root.unmount()) }+ })+ it('disabled protection warns even with a backend; dismisses only the notice', async () => {+ mock.read.mockResolvedValue(status('session-host', false))+ const el = document.createElement('div'); const root = createRoot(el)+ try {+ await act(async () => root.render(<TmuxBanner onInstall={vi.fn()} />))+ expect(el.textContent).toContain('Session protection off')+ expect(el.querySelector('.announce-banner__btn')).toBeNull()+ await act(async () => (el.querySelector('.announce-banner__close') as HTMLButtonElement).click())+ expect(el.textContent).toBe('')+ expect(mock.enabled).toBe(true)+ } finally { await act(async () => root.unmount()) }+ })+ it('does not confuse disabled, unknown or older peers with available protection', () => {+ expect(persistenceDescription(status('session-host', false))).toContain('is off')+ expect(persistenceDescription(null)).toContain('not confirmed')+ expect(persistenceDescription({ ...status(null), persistence: undefined })).toContain('not confirmed')+ expect(persistenceDescription(status('session-host'))).toContain('runtime startup can still fail')+ })+})diff --git a/src/renderer/components/settings/nav.ts b/src/renderer/components/settings/nav.tsindex b9d6633a4..251711908 100644--- a/src/renderer/components/settings/nav.ts+++ b/src/renderer/components/settings/nav.ts@@ -75,7 +75,7 @@ export const SETTINGS_GROUPS: SettingsGroup[] = [sections: [{ id: 'terminal', title: 'Terminal' },{ id: 'shell', title: 'Shell' },- { id: 'tmux', title: 'tmux' },+ { id: 'tmux', title: 'Session protection' },{ id: 'github-issues', title: 'GitHub Issues' },{ id: 'behavior', title: 'Behavior' }]diff --git a/src/renderer/components/settings/sections/TmuxSection.tsx b/src/renderer/components/settings/sections/TmuxSection.tsxindex b14267917..1e7cdbacf 100644--- a/src/renderer/components/settings/sections/TmuxSection.tsx+++ b/src/renderer/components/settings/sections/TmuxSection.tsx@@ -1,3 +1,4 @@+import { persistenceDescription, usePersistenceStatus } from '../../usePersistenceStatus'import { useSettings } from '../../../state/settings'import { SettingsSection } from '../SettingsSection'import { SearchableRow } from '../SearchableRow'@@ -12,8 +13,8 @@ import {const ROWS = {enabled: {- title: 'Persistent sessions (tmux)',- keywords: ['tmux', 'persistent', 'session', 'continuity']+ title: 'Persistent sessions',+ keywords: ['tmux', 'persistent', 'session', 'continuity', 'protection', 'host']},scrollback: { title: 'Scrollback lines', keywords: ['tmux', 'scrollback', 'history', 'lines'] },leadPane: {@@ -28,19 +29,21 @@ const ROWS = {const ENTRIES = Object.values(ROWS)export function TmuxSection({ isActive }: { isActive: boolean }): React.JSX.Element {+ const status = usePersistenceStatus()const settings = useSettings((s) => s.settings)const update = useSettings((s) => s.update)return (<SettingsSectionid="tmux"- title="tmux"+ title="Session protection"description="Applies to new terminals / next launch."isActive={isActive}searchEntries={ENTRIES}><SearchableRow {...ROWS.enabled}><FieldRow- label="Persistent sessions (tmux)"+ label="Persistent sessions"+ description={persistenceDescription(status)}control={<Switchchecked={settings.tmuxEnabled}diff --git a/src/renderer/components/usePersistenceStatus.ts b/src/renderer/components/usePersistenceStatus.tsnew file mode 100644index 000000000..be3874cf4--- /dev/null+++ b/src/renderer/components/usePersistenceStatus.ts@@ -0,0 +1,40 @@+import { useEffect, useState } from 'react'+import type { TmuxStatus } from '@shared/types'+import { localSession } from '../session/localSession'+import { useSettings } from '../state/settings'++/** Always the local core (the server in a browser), never the selected relay host. */+export function usePersistenceStatus(): TmuxStatus | null | undefined {+ const enabled = useSettings((s) => s.settings.tmuxEnabled)+ const [status, setStatus] = useState<TmuxStatus | null>()+ useEffect(() => {+ let cancelled = false+ const refresh = async (): Promise<void> => {+ try {+ const next = await localSession.api.pty.tmuxStatus()+ if (!cancelled) setStatus(next)+ } catch {+ if (!cancelled) setStatus(null)+ }+ }+ void refresh()+ // Settings saves are coalesced for 300 ms; re-read after that write as well.+ const settled = setTimeout(() => void refresh(), 1000)+ const timer = setInterval(() => void refresh(), 15_000)+ return () => {+ cancelled = true+ clearInterval(timer)+ clearTimeout(settled)+ }+ }, [enabled])+ return status+}++export function persistenceDescription(status: TmuxStatus | null | undefined): string {+ if (status === undefined) return 'Checking session protection…'+ const p = status?.persistence+ if (!p) return 'Session protection could not be checked. Continuity is not confirmed.'+ if (!p.enabled) return 'Session protection is off for new local terminals. They will not survive an app or server restart.'+ if (!p.backend) return 'No session protection backend was found. New local terminals will not survive an app or server restart.'+ return `${p.backend === 'tmux' ? 'tmux' : 'Session host'} is available for new local terminals. Existing plain-shell terminals are not upgraded; runtime startup can still fail.`+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex d05cad046..4f20e69a0 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -892,9 +892,12 @@ export const EMPTY_WORKSPACE: Workspace = {// ---- Contract for the API exposed to the renderer via preload -----/** Wire shape of pty:tmux-status — behind the "tmux not found" banner. */+/** Local core backend discovery, not a runtime health check or a promise about existing sessions. */export interface TmuxStatus {+ /** tmux discovery only; retained for older callers and install polling. */available: boolean+ /** Absent on older peers; null when discovery could not be read. */+ persistence?: { enabled: boolean; backend: 'tmux' | 'session-host' | null } | null/** One-shot install command for a terminal node; null = no known installer (text-only banner). */installCommand: string | null/** Button caption for installCommand (e.g. "Install Homebrew + tmux" when brew must come first). */