fix: preserve terminal session state during periodic saves (#461)

This commit is contained in:
Jinjing
2026-04-10 21:06:37 -07:00
committed by GitHub
parent 1049b8af65
commit 821e205c6f
4 changed files with 235 additions and 88 deletions
+42 -88
View File
@@ -26,62 +26,10 @@ import {
import { getVisibleWorktreeIds } from './components/sidebar/visible-worktrees'
import { useGlobalFileDrop } from './hooks/useGlobalFileDrop'
import { registerUpdaterBeforeUnloadBypass } from './lib/updater-beforeunload'
import type { BrowserTab, PersistedOpenFile, WorkspaceVisibleTabType } from '../../shared/types'
import type { OpenFile } from './store/slices/editor'
import { buildWorkspaceSessionPayload } from './lib/workspace-session'
const isMac = navigator.userAgent.includes('Mac')
/** Build the editor-file portion of the workspace session for persistence.
* Only edit-mode files are saved — diffs and conflict views are transient. */
function buildEditorSessionData(
openFiles: OpenFile[],
activeFileIdByWorktree: Record<string, string | null>,
activeTabTypeByWorktree: Record<string, WorkspaceVisibleTabType>
): {
openFilesByWorktree: Record<string, PersistedOpenFile[]>
activeFileIdByWorktree: Record<string, string | null>
activeTabTypeByWorktree: Record<string, WorkspaceVisibleTabType>
} {
const editFiles = openFiles.filter((f) => f.mode === 'edit')
const byWorktree: Record<string, PersistedOpenFile[]> = {}
for (const f of editFiles) {
const arr = byWorktree[f.worktreeId] ?? (byWorktree[f.worktreeId] = [])
arr.push({
filePath: f.filePath,
relativePath: f.relativePath,
worktreeId: f.worktreeId,
language: f.language,
isPreview: f.isPreview || undefined
})
}
return {
openFilesByWorktree: byWorktree,
activeFileIdByWorktree,
activeTabTypeByWorktree
}
}
function buildBrowserSessionData(
browserTabsByWorktree: Record<string, BrowserTab[]>,
activeBrowserTabIdByWorktree: Record<string, string | null>
): {
browserTabsByWorktree: Record<string, BrowserTab[]>
activeBrowserTabIdByWorktree: Record<string, string | null>
} {
return {
// Why: browser tabs persist only lightweight chrome state. Live guest
// webContents are recreated on restore, so loading is reset to false and
// transient errors are preserved only as last-known tab metadata.
browserTabsByWorktree: Object.fromEntries(
Object.entries(browserTabsByWorktree).map(([worktreeId, tabs]) => [
worktreeId,
tabs.map((tab) => ({ ...tab, loading: false }))
])
),
activeBrowserTabIdByWorktree
}
}
function isEditableTarget(target: EventTarget | null): boolean {
if (!(target instanceof HTMLElement)) {
return false
@@ -257,23 +205,21 @@ function App(): React.JSX.Element {
return
}
const timer = window.setTimeout(() => {
// Why: setWorkspaceSession is a full replacement, not a merge.
// Every call MUST include activeWorktreeIdsOnShutdown or it is
// silently erased from disk.
const activeWorktreeIdsOnShutdown = Object.entries(tabsByWorktree)
.filter(([, tabs]) => tabs.some((t) => t.ptyId))
.map(([worktreeId]) => worktreeId)
void window.api.session.set({
activeRepoId,
activeWorktreeId,
activeTabId,
tabsByWorktree,
terminalLayoutsByTabId,
activeWorktreeIdsOnShutdown,
activeTabIdByWorktree,
...buildEditorSessionData(openFiles, activeFileIdByWorktree, activeTabTypeByWorktree),
...buildBrowserSessionData(browserTabsByWorktree, activeBrowserTabIdByWorktree)
})
void window.api.session.set(
buildWorkspaceSessionPayload({
activeRepoId,
activeWorktreeId,
activeTabId,
tabsByWorktree,
terminalLayoutsByTabId,
activeTabIdByWorktree,
openFiles,
activeFileIdByWorktree,
activeTabTypeByWorktree,
browserTabsByWorktree,
activeBrowserTabIdByWorktree
})
)
}, 150)
return () => window.clearTimeout(timer)
@@ -307,29 +253,37 @@ function App(): React.JSX.Element {
}
}
const state = useAppStore.getState()
const activeWorktreeIdsOnShutdown = Object.entries(state.tabsByWorktree)
.filter(([, tabs]) => tabs.some((t) => t.ptyId))
.map(([worktreeId]) => worktreeId)
window.api.session.setSync({
activeRepoId: state.activeRepoId,
activeWorktreeId: state.activeWorktreeId,
activeTabId: state.activeTabId,
tabsByWorktree: state.tabsByWorktree,
terminalLayoutsByTabId: state.terminalLayoutsByTabId,
activeWorktreeIdsOnShutdown,
activeTabIdByWorktree: state.activeTabIdByWorktree,
...buildEditorSessionData(
state.openFiles,
state.activeFileIdByWorktree,
state.activeTabTypeByWorktree
),
...buildBrowserSessionData(state.browserTabsByWorktree, state.activeBrowserTabIdByWorktree)
})
window.api.session.setSync(buildWorkspaceSessionPayload(state))
}
window.addEventListener('beforeunload', captureAndFlush)
return () => window.removeEventListener('beforeunload', captureAndFlush)
}, [])
// Periodically capture terminal scrollback buffers and persist to disk.
// Why: the normal shutdown path races with PTY exit events — before-quit
// kills all PTYs, whose async exit handlers close tabs and unmount
// TerminalPane components (removing their capture callbacks) before the
// renderer's beforeunload can run. Periodic saves ensure scrollback is
// available on restart even when the shutdown capture is lost.
useEffect(() => {
const PERIODIC_SAVE_INTERVAL_MS = 3 * 60_000
const timer = window.setInterval(() => {
if (!useAppStore.getState().workspaceSessionReady || shutdownBufferCaptures.size === 0) {
return
}
for (const capture of shutdownBufferCaptures) {
try {
capture()
} catch {
// Don't let one pane's failure block the rest.
}
}
const state = useAppStore.getState()
void window.api.session.set(buildWorkspaceSessionPayload(state))
}, PERIODIC_SAVE_INTERVAL_MS)
return () => window.clearInterval(timer)
}, [])
useEffect(() => {
if (!persistedUIReady) {
return
+7
View File
@@ -592,6 +592,13 @@ export default function Terminal(): React.JSX.Element | null {
window.api.ui.confirmWindowClose()
return
}
// Why: before-quit (main process) kills all PTYs before this handler
// runs. The async PTY exit events close tabs and unmount TerminalPane
// components, removing their buffer capture callbacks. Dispatching
// beforeunload here — while components are still mounted — captures
// scrollback buffers before the race can discard them. This mirrors
// the auto-updater path (preload/index.ts) which does the same thing.
window.dispatchEvent(new Event('beforeunload'))
const state = useAppStore.getState()
const allPtyIds = Object.values(state.ptyIdsByTabId).flat()
if (allPtyIds.length === 0) {
@@ -0,0 +1,86 @@
import { describe, expect, it } from 'vitest'
import { buildWorkspaceSessionPayload } from './workspace-session'
import type { AppState } from '../store'
function createSnapshot(overrides: Partial<AppState> = {}): AppState {
return {
activeRepoId: 'repo-1',
activeWorktreeId: 'wt-1',
activeTabId: 'tab-1',
tabsByWorktree: {
'wt-1': [{ id: 'tab-1', title: 'shell', ptyId: 'pty-1', worktreeId: 'wt-1' }],
'wt-2': [{ id: 'tab-2', title: 'editor', ptyId: null, worktreeId: 'wt-2' }]
},
terminalLayoutsByTabId: {
'tab-1': { root: null, activeLeafId: null, expandedLeafId: null }
},
activeTabIdByWorktree: { 'wt-1': 'tab-1', 'wt-2': 'tab-2' },
openFiles: [
{
filePath: '/tmp/demo.ts',
relativePath: 'demo.ts',
worktreeId: 'wt-1',
language: 'typescript',
mode: 'edit',
isDirty: false,
isPreview: false,
content: '',
originalContent: ''
},
{
filePath: '/tmp/demo.diff',
relativePath: 'demo.diff',
worktreeId: 'wt-1',
language: 'diff',
mode: 'diff',
isDirty: false,
isPreview: false,
content: '',
originalContent: ''
}
],
activeFileIdByWorktree: { 'wt-1': '/tmp/demo.ts' },
activeTabTypeByWorktree: { 'wt-1': 'editor', 'wt-2': 'terminal' },
browserTabsByWorktree: {
'wt-1': [
{
id: 'browser-1',
url: 'https://example.com',
title: 'Example',
loading: true,
canGoBack: false,
canGoForward: false,
errorCode: null,
errorDescription: null
}
]
},
activeBrowserTabIdByWorktree: { 'wt-1': 'browser-1' },
...overrides
} as AppState
}
describe('buildWorkspaceSessionPayload', () => {
it('preserves activeWorktreeIdsOnShutdown for full replacement writes', () => {
const payload = buildWorkspaceSessionPayload(createSnapshot())
expect(payload.activeWorktreeIdsOnShutdown).toEqual(['wt-1'])
})
it('persists only edit-mode files and resets browser loading state', () => {
const payload = buildWorkspaceSessionPayload(createSnapshot())
expect(payload.openFilesByWorktree).toEqual({
'wt-1': [
{
filePath: '/tmp/demo.ts',
relativePath: 'demo.ts',
worktreeId: 'wt-1',
language: 'typescript',
isPreview: undefined
}
]
})
expect(payload.browserTabsByWorktree?.['wt-1'][0].loading).toBe(false)
})
})
+100
View File
@@ -0,0 +1,100 @@
import type {
BrowserTab,
PersistedOpenFile,
WorkspaceSessionState,
WorkspaceVisibleTabType
} from '../../../shared/types'
import type { AppState } from '../store'
import type { OpenFile } from '../store/slices/editor'
type WorkspaceSessionSnapshot = Pick<
AppState,
| 'activeRepoId'
| 'activeWorktreeId'
| 'activeTabId'
| 'tabsByWorktree'
| 'terminalLayoutsByTabId'
| 'activeTabIdByWorktree'
| 'openFiles'
| 'activeFileIdByWorktree'
| 'activeTabTypeByWorktree'
| 'browserTabsByWorktree'
| 'activeBrowserTabIdByWorktree'
>
/** Build the editor-file portion of the workspace session for persistence.
* Only edit-mode files are saved — diffs and conflict views are transient. */
export function buildEditorSessionData(
openFiles: OpenFile[],
activeFileIdByWorktree: Record<string, string | null>,
activeTabTypeByWorktree: Record<string, WorkspaceVisibleTabType>
): Pick<
WorkspaceSessionState,
'openFilesByWorktree' | 'activeFileIdByWorktree' | 'activeTabTypeByWorktree'
> {
const editFiles = openFiles.filter((f) => f.mode === 'edit')
const byWorktree: Record<string, PersistedOpenFile[]> = {}
for (const f of editFiles) {
const arr = byWorktree[f.worktreeId] ?? (byWorktree[f.worktreeId] = [])
arr.push({
filePath: f.filePath,
relativePath: f.relativePath,
worktreeId: f.worktreeId,
language: f.language,
isPreview: f.isPreview || undefined
})
}
return {
openFilesByWorktree: byWorktree,
activeFileIdByWorktree,
activeTabTypeByWorktree
}
}
export function buildBrowserSessionData(
browserTabsByWorktree: Record<string, BrowserTab[]>,
activeBrowserTabIdByWorktree: Record<string, string | null>
): Pick<WorkspaceSessionState, 'browserTabsByWorktree' | 'activeBrowserTabIdByWorktree'> {
return {
// Why: browser tabs persist only lightweight chrome state. Live guest
// webContents are recreated on restore, so loading is reset to false and
// transient errors are preserved only as last-known tab metadata.
browserTabsByWorktree: Object.fromEntries(
Object.entries(browserTabsByWorktree).map(([worktreeId, tabs]) => [
worktreeId,
tabs.map((tab) => ({ ...tab, loading: false }))
])
),
activeBrowserTabIdByWorktree
}
}
export function buildWorkspaceSessionPayload(
snapshot: WorkspaceSessionSnapshot
): WorkspaceSessionState {
const activeWorktreeIdsOnShutdown = Object.entries(snapshot.tabsByWorktree)
.filter(([, tabs]) => tabs.some((tab) => tab.ptyId))
.map(([worktreeId]) => worktreeId)
return {
activeRepoId: snapshot.activeRepoId,
activeWorktreeId: snapshot.activeWorktreeId,
activeTabId: snapshot.activeTabId,
tabsByWorktree: snapshot.tabsByWorktree,
terminalLayoutsByTabId: snapshot.terminalLayoutsByTabId,
// Why: session:set fully replaces the persisted object, so every write path
// must carry forward which worktrees still had live PTYs. Dropping this
// field silently disables eager terminal reconnect on the next restart.
activeWorktreeIdsOnShutdown,
activeTabIdByWorktree: snapshot.activeTabIdByWorktree,
...buildEditorSessionData(
snapshot.openFiles,
snapshot.activeFileIdByWorktree,
snapshot.activeTabTypeByWorktree
),
...buildBrowserSessionData(
snapshot.browserTabsByWorktree,
snapshot.activeBrowserTabIdByWorktree
)
}
}