From 9826d94485f8ddbc3fa23a6012bf166f0b6a83a5 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Fri, 17 Apr 2026 17:41:45 -0700 Subject: [PATCH] fix terminal split remounts when daemon is disabled (#782) --- .../terminal-pane/pty-connection.test.ts | 83 ++++++++++++++++++- .../terminal-pane/pty-connection.ts | 72 +++++++++++++--- 2 files changed, 142 insertions(+), 13 deletions(-) diff --git a/src/renderer/src/components/terminal-pane/pty-connection.test.ts b/src/renderer/src/components/terminal-pane/pty-connection.test.ts index 71ab0c263..9701a688c 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.test.ts @@ -1,3 +1,4 @@ +/* oxlint-disable max-lines */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' type StoreState = { @@ -5,7 +6,7 @@ type StoreState = { worktreesByRepo: Record repos: { id: string; connectionId?: string | null }[] cacheTimerByKey: Record - settings: { promptCacheTimerEnabled?: boolean } | null + settings: { promptCacheTimerEnabled?: boolean; experimentalTerminalDaemon?: boolean } | null consumePendingColdRestore: ReturnType consumePendingSnapshot: ReturnType } @@ -276,6 +277,13 @@ describe('connectPanePty', () => { const { connectPanePty } = await import('./pty-connection') const transport = createMockTransport() transportFactoryQueue.push(transport) + mockStoreState = { + ...mockStoreState, + settings: { + ...mockStoreState.settings, + experimentalTerminalDaemon: true + } + } as StoreState const pane = createPane(2) const manager = createManager(2) const deps = createDeps({ @@ -296,6 +304,75 @@ describe('connectPanePty', () => { expect(deps.syncPanePtyLayoutBinding).toHaveBeenCalledWith(2, 'leaf-pty-2') }) + it('reuses the existing local PTY on split remount when the daemon is disabled', async () => { + const { connectPanePty } = await import('./pty-connection') + const transport = createMockTransport() + transportFactoryQueue.push(transport) + + mockStoreState = { + ...mockStoreState, + tabsByWorktree: { + 'wt-1': [{ id: 'tab-1', ptyId: 'pty-local-detached' }] + }, + settings: { + ...mockStoreState.settings, + // Why: with the daemon off, split/remount should still keep the + // in-process PTY alive within the same app session. This regression + // came from treating every remount like a daemon session reattach. + experimentalTerminalDaemon: false + } + } as StoreState + + const pane = createPane(2) + const manager = createManager(2) + const deps = createDeps({ + restoredLeafId: 'pane:2', + restoredPtyIdByLeafId: { 'pane:2': 'pty-local-detached' } + }) + + connectPanePty(pane as never, manager as never, deps as never) + + expect(transport.attach).toHaveBeenCalledWith( + expect.objectContaining({ existingPtyId: 'pty-local-detached' }) + ) + expect(transport.connect).not.toHaveBeenCalled() + expect(deps.syncPanePtyLayoutBinding).toHaveBeenCalledWith(2, 'pty-local-detached') + expect(deps.updateTabPtyId).toHaveBeenCalledWith('tab-1', 'pty-local-detached') + }) + + it('reattaches via daemon sessionId when the daemon is enabled and an in-session PTY is live', async () => { + const { connectPanePty } = await import('./pty-connection') + const transport = createMockTransport() + transportFactoryQueue.push(transport) + + mockStoreState = { + ...mockStoreState, + tabsByWorktree: { + 'wt-1': [{ id: 'tab-1', ptyId: 'pty-local-detached' }] + }, + settings: { + ...mockStoreState.settings, + // Why: complement of the daemon-off case — with the daemon on, the + // in-session remount path must go through connect({sessionId}) so + // the daemon's createOrAttach runs at the pane's real dimensions. + experimentalTerminalDaemon: true + } + } as StoreState + + const pane = createPane(2) + const manager = createManager(2) + const deps = createDeps() + + connectPanePty(pane as never, manager as never, deps as never) + + expect(transport.connect).toHaveBeenCalledWith( + expect.objectContaining({ sessionId: 'pty-local-detached' }) + ) + expect(transport.attach).not.toHaveBeenCalled() + await Promise.resolve() + expect(deps.syncPanePtyLayoutBinding).toHaveBeenCalledWith(2, 'pty-local-detached') + }) + it('persists a restarted pane PTY id and uses it on the next remount', async () => { const { connectPanePty } = await import('./pty-connection') @@ -325,6 +402,10 @@ describe('connectPanePty', () => { ...mockStoreState, tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: 'pty-restarted' }] + }, + settings: { + ...mockStoreState.settings, + experimentalTerminalDaemon: true } } diff --git a/src/renderer/src/components/terminal-pane/pty-connection.ts b/src/renderer/src/components/terminal-pane/pty-connection.ts index 8f99dce16..f4eee4fd0 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.ts @@ -283,25 +283,45 @@ export function connectPanePty( deps.restoredLeafId && deps.restoredPtyIdByLeafId ? (deps.restoredPtyIdByLeafId[deps.restoredLeafId] ?? null) : null - const existingPtyId = useAppStore - .getState() - .tabsByWorktree[deps.worktreeId]?.find((t) => t.id === deps.tabId)?.ptyId + const storeSnapshot = useAppStore.getState() + const existingPtyId = storeSnapshot.tabsByWorktree[deps.worktreeId]?.find( + (t) => t.id === deps.tabId + )?.ptyId - // Why: deferred reattach (Option 2). Instead of eagerly spawning PTYs at - // default 80×24 during reconnectPersistedTerminals (which fills eager - // buffers with content at wrong dimensions), we defer the daemon's - // createOrAttach to this point where fitAddon provides real dimensions. - // The daemon returns snapshot/coldRestore data in the spawn result. - const reattachSessionId = - restoredPtyId ?? (existingPtyId && !hasExistingPaneTransport ? existingPtyId : null) - if (reattachSessionId) { + const daemonEnabled = storeSnapshot.settings?.experimentalTerminalDaemon === true + // Why: restored leaf PTYs usually come from a previous app session, so + // they normally go back through the daemon's createOrAttach RPC to + // recover snapshot or cold-restore data at the pane's real dimensions. + // But split remounts in the current app session also carry a leaf binding + // in the saved layout. When the daemon is off, treating that live local + // PTY like a daemon session ID incorrectly spawns a fresh shell because + // LocalPtyProvider ignores sessionId. The reliable distinction is whether + // the tab still owns that PTY right now: same-session remounts keep the + // tab-level ptyId populated, while daemon-off cold starts clear it during + // session hydration. + const restoredSessionId = restoredPtyId ?? null + const detachedLivePtyId = + existingPtyId && !hasExistingPaneTransport + ? restoredSessionId + ? restoredSessionId === existingPtyId + ? restoredSessionId + : null + : existingPtyId + : null + const deferredReattachSessionId = + restoredSessionId && restoredSessionId !== detachedLivePtyId + ? restoredSessionId + : daemonEnabled + ? detachedLivePtyId + : null + if (deferredReattachSessionId) { allowInitialIdleCacheSeed = true const reattachPromise = transport.connect({ url: '', cols, rows, - sessionId: reattachSessionId, + sessionId: deferredReattachSessionId, callbacks: { onData: dataCallback, onError: reportError @@ -353,6 +373,34 @@ export function connectPanePty( .catch((err) => { reportError(err instanceof Error ? err.message : String(err)) }) + } else if (detachedLivePtyId) { + allowInitialIdleCacheSeed = false + // Why: surface synchronous attach failures (e.g., the PTY died between + // mount and remount, so window.api.pty.resize rejects) through + // reportError so the pane shows a diagnostic instead of silently + // leaving a blank surface. The deferred-reattach branch above uses + // `.catch(reportError)` for the same reason. Commit the pane/tab + // bindings only after attach returns: if attach throws, the stale + // ptyId must also be cleared from the tab and a fresh spawn kicked + // off — otherwise the next remount reads the same dead ptyId from + // the store and lands in this branch again in a loop. + try { + transport.attach({ + existingPtyId: detachedLivePtyId, + cols, + rows, + callbacks: { + onData: dataCallback, + onError: reportError + } + }) + deps.syncPanePtyLayoutBinding(pane.id, detachedLivePtyId) + deps.updateTabPtyId(deps.tabId, detachedLivePtyId) + } catch (err) { + reportError(err instanceof Error ? err.message : String(err)) + deps.clearTabPtyId(deps.tabId, detachedLivePtyId) + startFreshSpawn() + } } else { allowInitialIdleCacheSeed = false const pendingSpawn = hasExistingPaneTransport