diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index d26494ab5..e51b245a8 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -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, - activeTabTypeByWorktree: Record -): { - openFilesByWorktree: Record - activeFileIdByWorktree: Record - activeTabTypeByWorktree: Record -} { - const editFiles = openFiles.filter((f) => f.mode === 'edit') - const byWorktree: Record = {} - 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, - activeBrowserTabIdByWorktree: Record -): { - browserTabsByWorktree: Record - activeBrowserTabIdByWorktree: Record -} { - 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 diff --git a/src/renderer/src/components/Terminal.tsx b/src/renderer/src/components/Terminal.tsx index 3cec0284b..8c37054a6 100644 --- a/src/renderer/src/components/Terminal.tsx +++ b/src/renderer/src/components/Terminal.tsx @@ -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) { diff --git a/src/renderer/src/lib/workspace-session.test.ts b/src/renderer/src/lib/workspace-session.test.ts new file mode 100644 index 000000000..d7e77ed38 --- /dev/null +++ b/src/renderer/src/lib/workspace-session.test.ts @@ -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 { + 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) + }) +}) diff --git a/src/renderer/src/lib/workspace-session.ts b/src/renderer/src/lib/workspace-session.ts new file mode 100644 index 000000000..6bf20a058 --- /dev/null +++ b/src/renderer/src/lib/workspace-session.ts @@ -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, + activeTabTypeByWorktree: Record +): Pick< + WorkspaceSessionState, + 'openFilesByWorktree' | 'activeFileIdByWorktree' | 'activeTabTypeByWorktree' +> { + const editFiles = openFiles.filter((f) => f.mode === 'edit') + const byWorktree: Record = {} + 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, + activeBrowserTabIdByWorktree: Record +): Pick { + 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 + ) + } +}