Compare commits

..
Author SHA1 Message Date
陈大猫 d397e76cc2 merge(main): pick up plugin-contract CI hang fix from #4240 2026-11-14 20:42:33 +08:00
陈大猫 cf7f998689 fix(ci): prevent plugin-contract lint-and-test hang (#4240) 2026-11-14 20:17:13 +08:00
陈大猫 7bad2f4939 fix(logs): tolerate unavailable finalization IPC
Preserve window close and layout saves when session-log finalization IPC cannot be set up, and clear its timeout on setup failures.

Follow-up for #4235 / PR #4236.
2026-11-14 14:20:47 +08:00
陈大猫 ee06726153 fix(logs): finalize logs when unconnected sessions close
Capture never-connected terminal logs at explicit session removal, including empty buffers, without finalizing logs during runtime remounts. Cover tab close, failed-dialog close, batch close, and workspace close with persistence regressions.

Fixes #4235
2026-11-14 13:43:35 +08:00
陈大猫 69de51a61d fix(logs): finalize session logs when the app quits without closing tabs
Fixes #4235
2026-11-14 13:34:14 +08:00
16 changed files with 763 additions and 15 deletions

No files matched your search

+17
View File
@@ -1220,6 +1220,23 @@ export function handleConnectToHostImpl(getCtx: AppContextGetter, host: Host, hi
}
}
export function startRestoredSessionConnectionLogImpl(getCtx: AppContextGetter, session: TerminalSession) {
const { addConnectionLog, systemInfoRef } = getCtx();
const { username, hostname } = systemInfoRef.current;
addConnectionLog({
sessionId: session.id,
hostId: session.hostId,
hostLabel: session.hostLabel,
hostname: session.hostname,
username: session.username,
protocol: session.protocol || 'ssh',
startTime: Date.now(),
localUsername: username,
localHostname: hostname,
saved: false,
});
}
export async function handleTerminalDataCaptureImpl(getCtx: AppContextGetter, sessionId: string, data: string) {
const { IS_DEV, connectionLogs, selectConnectionLogForTerminalDataCapture, sessions, updateConnectionLog } = getCtx();
{
+12 -2
View File
@@ -104,7 +104,7 @@ import { collectSnippetDeleteIds } from '../../domain/snippetSelection.ts';
import { shouldOpenLocalTerminalOnStartup, resolveStartupLandingSetting } from '../../domain/startupLanding';
import { createOpenTerminalQueue } from './openTerminalQueue';
import { useAppStartupEffects } from './useAppStartupEffects';
import { handleTrayJumpToSessionImpl, handleTrayTogglePortForwardImpl, handleTrayPanelConnectImpl, handleTrayPanelConnectRequestImpl, flushQueuedTrayPanelConnectHostsImpl, handleGlobalHotkeyKeyDownImpl, handleEscapeKeyDownImpl, handleKeyboardInteractiveSubmitImpl, handleKeyboardInteractiveCancelImpl, handlePassphraseSubmitImpl, handlePassphraseCancelImpl, handlePassphraseSkipImpl, handleFidoPromptSubmitImpl, handleFidoPromptCancelImpl, createLocalTerminalWithCurrentShellImpl, splitSessionWithCurrentShellImpl, copySessionWithCurrentShellImpl, duplicateSessionWithCurrentShellImpl, copyWorkspaceWithCurrentShellImpl, copySessionToNewWindowWithCurrentShellImpl, confirmIfBusyLocalTerminalImpl, closeTabsBatchImpl, executeHotkeyActionImpl, handleCreateLocalTerminalImpl, handleConnectToHostImpl, handleTerminalDataCaptureImpl, hasMultipleProtocolsImpl, handleHostConnectWithProtocolCheckImpl, handleProtocolSelectImpl, handleRootContextMenuImpl, markForwardedNativeShortcutEvent } from './AppHandlers';
import { handleTrayJumpToSessionImpl, handleTrayTogglePortForwardImpl, handleTrayPanelConnectImpl, handleTrayPanelConnectRequestImpl, flushQueuedTrayPanelConnectHostsImpl, handleGlobalHotkeyKeyDownImpl, handleEscapeKeyDownImpl, handleKeyboardInteractiveSubmitImpl, handleKeyboardInteractiveCancelImpl, handlePassphraseSubmitImpl, handlePassphraseCancelImpl, handlePassphraseSkipImpl, handleFidoPromptSubmitImpl, handleFidoPromptCancelImpl, createLocalTerminalWithCurrentShellImpl, splitSessionWithCurrentShellImpl, copySessionWithCurrentShellImpl, duplicateSessionWithCurrentShellImpl, copyWorkspaceWithCurrentShellImpl, copySessionToNewWindowWithCurrentShellImpl, confirmIfBusyLocalTerminalImpl, closeTabsBatchImpl, executeHotkeyActionImpl, handleCreateLocalTerminalImpl, handleConnectToHostImpl, handleTerminalDataCaptureImpl, startRestoredSessionConnectionLogImpl, hasMultipleProtocolsImpl, handleHostConnectWithProtocolCheckImpl, handleProtocolSelectImpl, handleRootContextMenuImpl, markForwardedNativeShortcutEvent } from './AppHandlers';
type OpenSessionInNewWindowPayload = {
title?: string;
@@ -1895,8 +1895,18 @@ export function AppSideEffects() {
setActiveTabId('vault');
}, [setActiveTabId]);
const restoredSessionLogsStartedRef = useRef(new Set<string>());
// A restored tab retains its session ID, but its previous ConnectionLog is closed.
// Start the new incarnation's log before updateSessionStatus clears restoreState.
// Wrap updateSessionStatus to track lastConnectedAt on successful connection
const handleSessionStatusChange = useCallback((sessionId: string, status: TerminalSession['status']) => {
const session = sessionByIdRef.current.get(sessionId);
if (session?.restoreState === 'restored-disconnected'
&& (status === 'connecting' || status === 'connected')
&& !restoredSessionLogsStartedRef.current.has(sessionId)) {
restoredSessionLogsStartedRef.current.add(sessionId);
startRestoredSessionConnectionLogImpl(() => ({ addConnectionLog, systemInfoRef }), session);
}
updateSessionStatus(sessionId, status);
if (status === 'connected') {
const session = sessionByIdRef.current.get(sessionId);
@@ -1904,7 +1914,7 @@ export function AppSideEffects() {
updateHostLastConnected(session.hostId);
}
}
}, [updateSessionStatus, updateHostLastConnected]);
}, [addConnectionLog, updateSessionStatus, updateHostLastConnected]);
const handleUpdateHostFromTerminal = useCallback((host: TerminalHostUpdate) => {
// Functional update + identity-preserving updateHosts: only the patched
@@ -0,0 +1,206 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { readFileSync } from 'node:fs';
import React, { useEffect, useRef } from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import { JSDOM } from 'jsdom';
import { installBrowserLockFixture } from '../testSupport/browserLockFixture';
import { useSessionState } from '../state/useSessionState';
import { captureClosingTerminalSessions, useTerminalSessionCloseCapture } from '../state/terminalSessionCloseCapture';
import { selectConnectionLogForTerminalDataCapture } from '../../domain/connectionLog';
import { createConnectionLogBuffer } from '../../components/terminal/connectionLogBuffer';
import { TerminalConnectionProgress } from '../../components/terminal/TerminalConnectionProgress';
import { I18nProvider } from '../i18n/I18nProvider';
import { handleTerminalDataCaptureImpl } from './AppHandlers';
const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
test('explicit close persists never-connected logs; runtime remounts leave them open', async (t) => {
const dom = new JSDOM('', { url: 'http://localhost' });
const globals = ['window', 'localStorage', 'CustomEvent', 'navigator', 'IS_REACT_ACT_ENVIRONMENT'];
const previous = new Map(globals.map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
Object.defineProperties(globalThis, {
window: { value: dom.window, configurable: true },
localStorage: { value: dom.window.localStorage, configurable: true },
CustomEvent: { value: dom.window.CustomEvent, configurable: true },
IS_REACT_ACT_ENVIRONMENT: { value: true, configurable: true },
});
installBrowserLockFixture();
const { useVaultState } = await import('../state/useVaultState');
try {
for (const scenario of [
{ name: 'tab X before connected, empty buffer', status: 'connecting', data: '' },
{ name: 'failed-dialog close, empty buffer', status: 'disconnected', data: '' },
{ name: 'failed-dialog close preserves buffered diagnostics', status: 'disconnected', data: 'SSH diagnostic\r\n' },
{ name: 'batch close before connected', status: 'connecting', data: '', closeMode: 'batch' },
{ name: 'workspace close before connected', status: 'connecting', data: '', closeMode: 'workspace' },
] as const) {
await t.test(scenario.name, async () => {
let vault!: ReturnType<typeof useVaultState>;
let state!: ReturnType<typeof useSessionState>;
let root: ReactTestRenderer | undefined;
let sessionId!: string;
let logId!: string;
const captures: Promise<void>[] = [];
const capturedData: string[] = [];
function TerminalProbe() {
const hasConnectedRef = useRef(false);
const terminalDataCapturedRef = useRef(false);
const buffer = useRef(createConnectionLogBuffer(10000));
useEffect(() => {
buffer.current.append(scenario.data);
return () => { buffer.current.reset(); };
}, []);
useTerminalSessionCloseCapture({
sessionId, enabled: true, hasConnectedRef, terminalDataCapturedRef,
finalizeTerminalLogData: () => buffer.current.toString(),
onTerminalDataCapture: (id, data, options) => {
assert.equal(options.finalized, true);
assert.ok(state.sessions.some((session) => session.id === id), 'capture starts before removal');
terminalDataCapturedRef.current = true;
capturedData.push(data);
const pending = handleTerminalDataCaptureImpl(() => ({
IS_DEV: false, connectionLogs: vault.connectionLogs, sessions: state.sessions,
selectConnectionLogForTerminalDataCapture, updateConnectionLog: vault.updateConnectionLog,
}), id, data);
captures.push(pending);
return pending;
},
});
return scenario.status === 'disconnected' ? React.createElement(
I18nProvider, { locale: 'en' }, React.createElement(TerminalConnectionProgress, {
status: 'disconnected', error: 'Connection refused', timeLeft: 0,
isCancelling: false, showLogs: false, progressLogs: [],
onCancelConnect: () => {}, onCloseSession: () => state.closeSession(sessionId),
}),
) : null;
}
function Probe({ showTerminal = true }) {
vault = useVaultState();
state = useSessionState({ persistSessionRestore: false });
return showTerminal && state.sessions.some((session) => session.id === sessionId)
? React.createElement(TerminalProbe) : null;
}
const mount = async () => {
await act(async () => { root = create(React.createElement(Probe)); });
for (let attempt = 0; !vault.isInitialized && attempt < 50; attempt++) {
await act(async () => { await tick(); });
}
assert.equal(vault.isInitialized, true);
};
try {
await mount();
await act(async () => { sessionId = state.createLocalTerminal(); });
await act(async () => {
state.updateSessionStatus(sessionId, scenario.status);
const session = state.sessions.find((candidate) => candidate.id === sessionId)!;
logId = vault.addConnectionLog({
sessionId, hostId: session.hostId, hostLabel: session.hostLabel,
hostname: session.hostname, username: session.username,
protocol: session.protocol, startTime: Date.now(),
localUsername: 'local-user', localHostname: 'local-host', saved: false,
});
await vault.updateConnectionLog(logId, {});
});
if ('closeMode' in scenario && scenario.closeMode === 'workspace') {
let otherId!: string;
await act(async () => { otherId = state.createLocalTerminal(); });
await act(async () => { state.createWorkspaceFromSessions(sessionId, otherId, 'right'); });
}
// Recycle the renderer while retaining the session, as with a pane
// remount. Neither disposal nor the replacement runtime may end its log.
await act(async () => { root!.update(React.createElement(Probe, { showTerminal: false })); });
await act(async () => { root!.update(React.createElement(Probe)); });
assert.equal(captures.length, 0);
assert.equal(vault.connectionLogs.find((log) => log.id === logId)?.endTime, undefined);
// Both UI actions converge here. This exercises the actual state
// removal, owning-terminal hook, capture handler and vault persistence.
await act(async () => {
if ('closeMode' in scenario && scenario.closeMode === 'workspace') {
state.closeWorkspace(state.workspaces[0].id);
} else if ('closeMode' in scenario && scenario.closeMode === 'batch') {
state.closeSessions([sessionId]);
} else if (scenario.status === 'disconnected') {
// Click the actual Close button rendered inside the failed dialog.
root!.root.findByType('button').props.onClick();
} else {
state.closeSession(sessionId);
}
await Promise.all(captures);
});
assert.equal(state.sessions.some((session) => session.id === sessionId), false);
assert.deepEqual(capturedData, [scenario.data]);
await act(async () => { state.closeSession(sessionId); });
assert.equal(captures.length, 1, 'removed runtimes must unregister their capture');
await act(async () => { root!.unmount(); });
root = undefined;
await mount();
const persisted = vault.connectionLogs.find((log) => log.id === logId)!;
assert.ok(persisted.endTime, 'a durable endTime must exist even without terminal output');
assert.equal(persisted.terminalData || '', scenario.data);
} finally {
await act(async () => { root?.unmount(); });
}
});
}
} finally {
dom.window.close();
for (const key of globals) {
const descriptor = previous.get(key);
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
}
});
test('close capture skips non-owning, already connected and already captured runtimes', async (t) => {
const previous = Object.getOwnPropertyDescriptor(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', { value: true, configurable: true });
try {
for (const scenario of [
{ name: 'attached popup / inactive restored placeholder', enabled: false, connected: false, captured: false },
{ name: 'connected terminal uses existing drain path', enabled: true, connected: true, captured: false },
{ name: 'quit already captured the log', enabled: true, connected: false, captured: true },
]) {
await t.test(scenario.name, async () => {
let calls = 0;
let root!: ReactTestRenderer;
function Probe() {
useTerminalSessionCloseCapture({
sessionId: 'guarded', enabled: scenario.enabled,
hasConnectedRef: useRef(scenario.connected),
terminalDataCapturedRef: useRef(scenario.captured),
finalizeTerminalLogData: () => { calls++; return ''; },
onTerminalDataCapture: () => { calls++; },
});
return null;
}
await act(async () => { root = create(React.createElement(Probe)); });
try {
await act(async () => { captureClosingTerminalSessions(['guarded']); });
assert.equal(calls, 0);
} finally {
await act(async () => { root.unmount(); });
}
});
}
} finally {
if (previous) Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', previous);
else Reflect.deleteProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT');
}
});
test('both UI close paths reach session removal and Terminal registers the owning capture', () => {
const read = (path: string) => readFileSync(new URL(path, import.meta.url), 'utf8');
const app = read('./AppView.tsx');
assert.match(app, /onCloseSession=\{closeSession\}/);
assert.match(read('../../components/top-tabs/TopTabItems.tsx'), /onClick=\{\(e\) => onCloseSession\(session\.id, e\)\}/);
const terminal = read('../../components/Terminal.tsx');
assert.match(terminal, /useTerminalSessionCloseCapture\(\{\s*sessionId,\s*enabled: !attachExistingSession && restoreState !== "restored-disconnected",\s*hasConnectedRef,\s*terminalDataCapturedRef,\s*finalizeTerminalLogData,\s*onTerminalDataCapture: handleTerminalDataCaptureOnce,/);
const handler = terminal.slice(terminal.indexOf('const handleCloseDisconnectedSession ='), terminal.indexOf('const handleHostKeyClose ='));
assert.match(handler, /onCloseSession\?\.\(sessionId\)/);
assert.match(read('../../components/TerminalLayer.tsx'), /onCloseSession\(sessionId\)/);
assert.match(read('../../components/terminal/TerminalView.tsx'), /onCloseSession: handleCloseDisconnectedSession/);
assert.match(read('../../components/terminal/TerminalConnectionProgress.tsx'), /onClick=\{onCloseSession\}/);
});
@@ -0,0 +1,132 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { readFileSync } from 'node:fs';
import { EventEmitter } from 'node:events';
import React from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
import { JSDOM } from 'jsdom';
import { installBrowserLockFixture } from '../testSupport/browserLockFixture';
import { withVaultImportLock } from '../state/vaultManagedImportLock';
import { selectConnectionLogForTerminalDataCapture } from '../../domain/connectionLog';
import type { TerminalSession } from '../../domain/models';
import { createConnectionLogBuffer } from '../../components/terminal/connectionLogBuffer';
import { handleTerminalDataCaptureImpl, startRestoredSessionConnectionLogImpl } from './AppHandlers';
import { createPreloadApi } from '../../electron/preload/api.cjs';
import { finalizeSessionLogs } from '../../electron/bridges/sessionLogShutdown.cjs';
const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
test('quit persists replay before acknowledgment; restored reconnect keeps the old log and starts a new one', async () => {
const dom = new JSDOM('', { url: 'http://localhost' });
const globals = ['window', 'localStorage', 'CustomEvent', 'navigator', 'IS_REACT_ACT_ENVIRONMENT'];
const previous = new Map(globals.map((key) => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
Object.defineProperties(globalThis, {
window: { value: dom.window, configurable: true },
localStorage: { value: dom.window.localStorage, configurable: true },
CustomEvent: { value: dom.window.CustomEvent, configurable: true },
IS_REACT_ACT_ENVIRONMENT: { value: true, configurable: true },
});
installBrowserLockFixture();
const { useVaultState } = await import('../state/useVaultState');
let vault!: ReturnType<typeof useVaultState>;
let root: ReactTestRenderer | undefined;
const Probe = () => { vault = useVaultState(); return null; };
const mount = async () => {
await act(async () => { root = create(React.createElement(Probe)); });
for (let attempt = 0; !vault.isInitialized && attempt < 50; attempt++) {
await act(async () => { await tick(); });
}
assert.equal(vault.isInitialized, true);
};
const session: TerminalSession = {
id: 'restorable-tab', hostId: 'host', hostLabel: 'Host', hostname: 'host.test',
username: 'user', protocol: 'ssh', status: 'connected',
};
const systemInfoRef = { current: { username: 'local-user', hostname: 'local-host' } };
const capture = (data: string) => handleTerminalDataCaptureImpl(() => ({
IS_DEV: false, connectionLogs: vault.connectionLogs, sessions: [session],
selectConnectionLogForTerminalDataCapture, updateConnectionLog: vault.updateConnectionLog,
}), session.id, data);
try {
await mount();
let oldId!: string;
await act(async () => {
oldId = vault.addConnectionLog({
sessionId: session.id, hostId: session.hostId, hostLabel: session.hostLabel,
hostname: session.hostname, username: session.username, protocol: 'ssh', startTime: 1,
localUsername: 'local-user', localHostname: 'local-host', saved: false,
});
// Wait for the initial catalog write before blocking the capture write.
await vault.updateConnectionLog(oldId, {});
});
const buffer = createConnectionLogBuffer(10000);
buffer.append('output before quitting\r\n');
const ipcMain = new EventEmitter();
const ipcRenderer = new EventEmitter() as EventEmitter & { send: (channel: string, payload: unknown) => void };
const webContents = { send: (channel: string, payload: unknown) => ipcRenderer.emit(channel, {}, payload) };
ipcRenderer.send = (channel, payload) => ipcMain.emit(channel, { sender: webContents }, payload);
const api = createPreloadApi({ ipcRenderer });
const off = api.onFinalizeSessionLogs(() => capture(buffer.toString()));
let release!: () => void;
const blockedWrite = withVaultImportLock('connection-logs', () => new Promise<void>((resolve) => { release = resolve; }));
await tick();
let acknowledged = false;
await act(async () => {
const quit = finalizeSessionLogs(webContents, { ipcMain }).then((success: boolean) => {
acknowledged = true;
assert.equal(success, true);
});
await tick();
assert.equal(acknowledged, false, 'main must wait for the persistence queue');
release();
await blockedWrite;
await quit;
});
off();
// Remounting reads durable storage. Node has no IndexedDB, so this also
// exercises the existing localStorage replay fallback.
await act(async () => { root?.unmount(); });
await mount();
const oldLog = vault.connectionLogs.find((log) => log.id === oldId)!;
assert.ok(oldLog.endTime);
assert.equal(oldLog.terminalData, 'output before quitting\r\n');
await act(async () => {
startRestoredSessionConnectionLogImpl(() => ({ addConnectionLog: vault.addConnectionLog, systemInfoRef }), {
...session, status: 'disconnected', restoreState: 'restored-disconnected',
});
});
const newLog = vault.connectionLogs.find((log) => log.id !== oldId)!;
assert.equal(newLog.sessionId, session.id);
assert.equal(newLog.endTime, undefined);
assert.equal(newLog.terminalData, undefined);
await act(async () => { await capture('output after reconnect\r\n'); });
await act(async () => { root?.unmount(); });
await mount();
assert.equal(vault.connectionLogs.find((log) => log.id === oldId)?.terminalData, oldLog.terminalData);
assert.equal(vault.connectionLogs.find((log) => log.id === oldId)?.endTime, oldLog.endTime);
assert.equal(vault.connectionLogs.find((log) => log.id === newLog.id)?.terminalData, 'output after reconnect\r\n');
assert.ok(vault.connectionLogs.find((log) => log.id === newLog.id)?.endTime);
} finally {
await act(async () => { root?.unmount(); });
dom.window.close();
for (const key of globals) {
const descriptor = previous.get(key);
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
}
});
test('terminal quit listener drains output and awaits capture without tearing down tabs', () => {
const source = readFileSync(new URL('../../components/Terminal.tsx', import.meta.url), 'utf8');
const start = source.indexOf('onFinalizeSessionLogs?.(async () => {');
assert.ok(start > 0);
const listener = source.slice(start, source.indexOf('const attachHomeWebContentsIdRef', start));
assert.match(listener, /await flushPendingTerminalWritesBeforeHibernate\(term\)/);
assert.match(listener, /await handleTerminalDataCaptureOnce\(sessionId, finalizeTerminalLogData\(\), \{ finalized: true \}\)/);
assert.doesNotMatch(listener, /closeSession|teardown/);
const effects = readFileSync(new URL('./AppSideEffects.tsx', import.meta.url), 'utf8');
const handler = effects.slice(effects.indexOf('const handleSessionStatusChange ='), effects.indexOf('const handleUpdateHostFromTerminal ='));
assert.ok(handler.indexOf('startRestoredSessionConnectionLogImpl(') < handler.indexOf('updateSessionStatus(sessionId, status)'));
assert.match(handler, /restoredSessionLogsStartedRef\.current\.has\(sessionId\)/);
});
@@ -0,0 +1,57 @@
import { useEffect, type RefObject } from 'react';
import { logger } from '../../lib/logger';
const closeCaptures = new Map<string, Set<() => void>>();
/** Notify owning terminals before explicit session removal, never on runtime cleanup. */
export function captureClosingTerminalSessions(sessionIds: readonly string[]): void {
for (const sessionId of new Set(sessionIds)) {
for (const capture of closeCaptures.get(sessionId) ?? []) capture();
}
}
export function useTerminalSessionCloseCapture({
sessionId,
enabled,
hasConnectedRef,
terminalDataCapturedRef,
finalizeTerminalLogData,
onTerminalDataCapture,
}: {
sessionId: string;
enabled: boolean;
hasConnectedRef: RefObject<boolean>;
terminalDataCapturedRef: RefObject<boolean>;
finalizeTerminalLogData: () => string;
onTerminalDataCapture: (
sessionId: string,
data: string,
options: { finalized: true },
) => void | Promise<void>;
}): void {
useEffect(() => {
if (!enabled) return;
const capture = () => {
// Connected terminals retain their existing drain/serialize close path.
if (hasConnectedRef.current || terminalDataCapturedRef.current) return;
try {
// A never-connected runtime is disposed synchronously on unmount.
// Finish its log now, even if empty, so persistence can set endTime.
void Promise.resolve(onTerminalDataCapture(
sessionId, finalizeTerminalLogData(), { finalized: true },
)).catch((err: unknown) => {
logger.warn('Failed to capture terminal log on session close', err);
});
} catch (err) {
logger.warn('Failed to capture terminal log on session close', err);
}
};
const captures = closeCaptures.get(sessionId) ?? new Set<() => void>();
closeCaptures.set(sessionId, captures);
captures.add(capture);
return () => {
captures.delete(capture);
if (!captures.size) closeCaptures.delete(sessionId);
};
}, [sessionId, enabled, hasConnectedRef, terminalDataCapturedRef, finalizeTerminalLogData, onTerminalDataCapture]);
}
+3
View File
@@ -75,6 +75,7 @@ import {
getSessionConnectionLabel,
} from '../../domain/sessionTabTitle';
import { cleanupClosedTerminalSessions } from './aiStateSnapshots';
import { captureClosingTerminalSessions } from './terminalSessionCloseCapture';
import { syncSessionHostLabels } from '../../domain/syncSessionHostLabels';
import { useVaultSnapshotField } from './vaultSnapshotStore';
@@ -603,6 +604,7 @@ export const useSessionState = ({
const closedIds = sessionsRef.current
.filter(session => session.workspaceId === workspaceId)
.map(session => session.id);
captureClosingTerminalSessions(closedIds);
cleanupClosedTerminalSessions(closedIds);
for (const sessionId of closedIds) {
sessionPresentationStore.clearSession(sessionId);
@@ -626,6 +628,7 @@ export const useSessionState = ({
}, [setActiveTabId]);
const closeSessions = useCallback((sessionIds: string[]) => {
captureClosingTerminalSessions(sessionIds);
cleanupClosedTerminalSessions(sessionIds);
for (const sessionId of sessionIds) {
sessionPresentationStore.clearSession(sessionId);
+23
View File
@@ -82,6 +82,7 @@ import { useStoredBoolean } from "../application/state/useStoredBoolean";
import { readOptionalStoredStringValue, useStoredString } from "../application/state/useStoredString";
import { performSessionLogAction, type SessionLogAction } from "../application/state/sessionLogActions";
import { useSessionLogBackend } from "../application/state/useSessionLogBackend";
import { useTerminalSessionCloseCapture } from "../application/state/terminalSessionCloseCapture";
import { useTerminalLayoutSuppressActive } from "../application/state/terminalLayoutSuppressStore";
import { useAppearanceChromeStore } from "../application/state/appearanceChromeStore";
import {
@@ -1676,6 +1677,28 @@ const TerminalComponent: React.FC<TerminalProps> = ({
return captureHandler(capturedSessionId, capturedData);
}, [finalizeTerminalLogData]);
useTerminalSessionCloseCapture({
sessionId,
enabled: !attachExistingSession && restoreState !== "restored-disconnected",
hasConnectedRef,
terminalDataCapturedRef,
finalizeTerminalLogData,
onTerminalDataCapture: handleTerminalDataCaptureOnce,
});
useEffect(() => {
// Attached popups do not own the ConnectionLog; the home terminal captures it.
if (attachExistingSession) return;
return netcattyBridge.get()?.onFinalizeSessionLogs?.(async () => {
if (terminalDataCapturedRef.current || (restoreState === "restored-disconnected" && statusRef.current === "disconnected")) return;
const term = termRef.current;
if (term && !await flushPendingTerminalWritesBeforeHibernate(term)) {
throw new Error("Terminal output did not drain before quit capture");
}
await handleTerminalDataCaptureOnce(sessionId, finalizeTerminalLogData(), { finalized: true });
});
}, [attachExistingSession, restoreState, sessionId, finalizeTerminalLogData, handleTerminalDataCaptureOnce]);
const attachHomeWebContentsIdRef = useRef<number | null | undefined>(undefined);
useEffect(() => {
+3 -3
View File
@@ -938,9 +938,9 @@ export function useTerminalEffects(ctx: TerminalEffectsContext) {
return;
}
// A boot that never reached "connected" has nothing worth capturing, and
// the teardown below awaits terminal drain plus serialization before it
// closes anything. Cancel the pending backend boot after giving an immediate
// Never-connected logs are captured at explicit session close, including
// empty buffers. Runtime cleanup alone must not end an open log.
// Cancel the pending backend boot after giving an immediate
// remount a chance to replace this generation, instead of letting it
// finish against a pane that is already gone. Attached popups never own
// the backend session (skip closeSession) but still sync-dispose xterm.
+38
View File
@@ -0,0 +1,38 @@
const { randomUUID } = require("node:crypto");
// Keep the renderer alive until its ConnectionLog replay writes have committed.
function finalizeSessionLogs(webContents, { ipcMain, timeoutMs = 5000 } = {}) {
if (!webContents || webContents.isDestroyed?.() || webContents.isCrashed?.()
|| typeof webContents.send !== "function"
|| typeof ipcMain?.on !== "function"
|| typeof ipcMain?.removeListener !== "function") {
return Promise.resolve(false);
}
return new Promise((resolve) => {
const requestId = randomUUID();
const finish = (success) => {
clearTimeout(timer);
try {
ipcMain.removeListener("app:session-logs-finalized", onResult);
} catch {
// IPC teardown must not prevent the window from closing.
}
if (!success) console.warn("[SessionLogs] Renderer did not finalize logs before close");
resolve(success);
};
const onResult = (event, payload) => {
if (event.sender === webContents && payload?.requestId === requestId) {
finish(payload.success === true);
}
};
const timer = setTimeout(() => finish(false), timeoutMs);
try {
ipcMain.on("app:session-logs-finalized", onResult);
webContents.send("app:finalize-session-logs", { requestId });
} catch {
finish(false);
}
});
}
module.exports = { finalizeSessionLogs };
@@ -0,0 +1,193 @@
const assert = require("node:assert/strict");
const test = require("node:test");
const { EventEmitter } = require("node:events");
const { finalizeSessionLogs } = require("./sessionLogShutdown.cjs");
const { createPreloadApi } = require("../preload/api.cjs");
const { handleBeforeQuit } = require("../main/appLockLifecycle.cjs");
const { readFileSync } = require("node:fs");
const vm = require("node:vm");
const tick = () => new Promise((resolve) => setImmediate(resolve));
function renderer(ipcMain = new EventEmitter()) {
const ipcRenderer = new EventEmitter();
const webContents = { send: (channel, payload) => ipcRenderer.emit(channel, {}, payload) };
ipcRenderer.send = (channel, payload) => ipcMain.emit(channel, { sender: webContents }, payload);
const api = createPreloadApi({ ipcRenderer });
return { api, ipcMain, ipcRenderer, webContents };
}
test("finalization waits for every terminal replay commit, including a hidden renderer", async () => {
const h = renderer();
const commits = [];
const off = h.api.onFinalizeSessionLogs(() => { throw new Error("unmounted terminal"); });
off();
for (let i = 0; i < 2; i++) {
h.api.onFinalizeSessionLogs(() => new Promise((resolve) => commits.push(resolve)));
}
let done = false;
const pending = finalizeSessionLogs(h.webContents, h).then((result) => { done = true; return result; });
await tick();
assert.equal(done, false);
commits[0](); await tick();
assert.equal(done, false);
commits[1]();
assert.equal(await pending, true);
assert.equal(h.ipcMain.listenerCount("app:session-logs-finalized"), 0);
});
test("empty renderers acknowledge immediately; failed captures acknowledge failure", async () => {
const h = renderer();
assert.equal(await finalizeSessionLogs(h.webContents, h), true);
h.api.onFinalizeSessionLogs(() => { throw new Error("capture failed"); });
assert.equal(await finalizeSessionLogs(h.webContents, h), false);
});
test("overlapping window close and app quit share the pending replay commit", async () => {
const h = renderer();
let finish;
let captures = 0;
h.api.onFinalizeSessionLogs(() => {
captures++;
return new Promise((resolve) => { finish = resolve; });
});
const first = finalizeSessionLogs(h.webContents, h);
let secondDone = false;
const second = finalizeSessionLogs(h.webContents, h).then((result) => { secondDone = true; return result; });
await tick();
assert.equal(captures, 1);
assert.equal(secondDone, false);
finish();
assert.equal(await first, true);
assert.equal(await second, true);
});
test("only the queried renderer and current request can acknowledge finalization", async () => {
const ipcMain = new EventEmitter();
let request;
const webContents = { send: (_channel, payload) => { request = payload; } };
let done = false;
const pending = finalizeSessionLogs(webContents, { ipcMain }).then((result) => { done = true; return result; });
ipcMain.emit("app:session-logs-finalized", { sender: {} }, { ...request, success: true });
ipcMain.emit("app:session-logs-finalized", { sender: webContents }, { requestId: "old", success: true });
await tick();
assert.equal(done, false);
ipcMain.emit("app:session-logs-finalized", { sender: webContents }, { ...request, success: true });
assert.equal(await pending, true);
});
test("unresponsive and destroyed renderers do not strand quit or leak listeners", async () => {
const ipcMain = new EventEmitter();
assert.equal(await finalizeSessionLogs({ send() {} }, { ipcMain, timeoutMs: 1 }), false);
assert.equal(await finalizeSessionLogs({ send() { throw new Error("destroyed"); } }, { ipcMain }), false);
assert.equal(await finalizeSessionLogs({ isDestroyed: () => true }, { ipcMain }), false);
assert.equal(ipcMain.listenerCount("app:session-logs-finalized"), 0);
});
test("unavailable finalize IPC returns immediately without scheduling timers or sending", async (t) => {
const timer = t.mock.method(globalThis, "setTimeout");
const ipcMain = new EventEmitter();
const send = t.mock.fn();
const on = t.mock.method(ipcMain, "on");
for (const unavailableIpc of [undefined, null, {}, { on() {} }, { removeListener() {} }, { on: true, removeListener() {} }, { on() {}, removeListener: true }]) {
assert.equal(await finalizeSessionLogs({ send }, { ipcMain: unavailableIpc }), false);
}
for (const webContents of [undefined, null, {}, { send: true }]) {
assert.equal(await finalizeSessionLogs(webContents, { ipcMain }), false);
}
assert.equal(timer.mock.callCount(), 0);
assert.equal(on.mock.callCount(), 0);
assert.equal(send.mock.callCount(), 0);
});
for (const failure of ["registration", "send", "cleanup"]) {
test(`finalize IPC ${failure} errors do not reject or leave a pending timeout`, async (t) => {
t.mock.timers.enable({ apis: ["setTimeout"] });
const warn = t.mock.method(console, "warn", () => {});
const ipcMain = new EventEmitter();
const webContents = { send() { throw new Error("send failed"); } };
if (failure === "registration") {
ipcMain.on = (channel, listener) => {
EventEmitter.prototype.on.call(ipcMain, channel, listener);
throw new Error("registration failed");
};
} else if (failure === "cleanup") {
ipcMain.removeListener = (channel, listener) => {
EventEmitter.prototype.removeListener.call(ipcMain, channel, listener);
throw new Error("cleanup failed");
};
}
let result;
const pending = finalizeSessionLogs(webContents, { ipcMain }).then((success) => { result = success; });
await tick();
assert.equal(result, false, "failed setup must finish before the timeout");
await pending;
assert.equal(ipcMain.listenerCount("app:session-logs-finalized"), 0);
assert.equal(warn.mock.callCount(), 1);
t.mock.timers.tick(5000);
assert.equal(warn.mock.callCount(), 1, "the cleared timeout must not run after finalization");
});
}
test("tray quit finalizes only after the dirty guard accepts and waits before quitting", async () => {
const h = renderer();
let finishCapture;
let captures = 0;
let quits = 0;
h.api.onFinalizeSessionLogs(() => {
captures++;
return new Promise((resolve) => { finishCapture = resolve; });
});
let shutdown;
const options = {
event: { preventDefault() {} }, mainWindows: [{ webContents: h.webContents }],
queryDirtyEditors: async () => true,
commitQuit: () => { shutdown = finalizeSessionLogs(h.webContents, h).then(() => { quits++; }); },
dialog: { showMessageBoxSync() {} },
};
await handleBeforeQuit(options);
assert.equal(captures, 0);
await handleBeforeQuit({ ...options, queryDirtyEditors: async () => false });
await tick();
assert.equal(captures, 1);
assert.equal(quits, 0);
finishCapture(); await shutdown;
assert.equal(quits, 1);
});
test("production quit commit awaits renderer logs and file streams before plugins and process exit", async () => {
const source = readFileSync(require.resolve("../main.cjs"), "utf8");
const start = source.indexOf(" const commitQuit = () => {");
const end = source.indexOf('\n app.on("before-quit"', start);
assert.ok(start >= 0 && end > start);
const calls = [];
let finishCapture;
let finishStreams;
const hiddenWindow = { webContents: {} };
const context = {
console,
getWindowManager: () => ({ setIsQuitting: () => calls.push("quitting"), getAppContentWindows: () => [hiddenWindow] }),
electronModule: { ipcMain: {} },
finalizeSessionLogs: (wc) => {
assert.equal(wc, hiddenWindow.webContents);
calls.push("capture");
return new Promise((resolve) => { finishCapture = resolve; });
},
sessionLogStreamManager: { cleanupAll: () => {
calls.push("streams");
return new Promise((resolve) => { finishStreams = resolve; });
} },
appLockController: { setLocked: () => calls.push("lock") },
runPluginShutdown: async () => { calls.push("plugins"); return { timedOut: false }; },
app: { quit: () => calls.push("quit") },
quitGuardChannelBusy: false, quitConfirmed: false,
};
vm.runInNewContext(`${source.slice(start, end)}; commitQuit();`, context);
assert.deepEqual(calls, ["lock", "quitting", "capture"]);
assert.equal(context.quitGuardChannelBusy, true);
finishCapture(); await tick();
assert.deepEqual(calls, ["lock", "quitting", "capture", "streams"]);
assert.equal(context.quitConfirmed, false);
finishStreams(); await tick();
assert.deepEqual(calls, ["lock", "quitting", "capture", "streams", "plugins", "quit"]);
assert.equal(context.quitConfirmed, true);
});
@@ -16,10 +16,29 @@ const {
startStream,
startStreamToFile,
stopStream,
cleanupAll,
} = require("./sessionLogStreamManager.cjs");
const TEMP_ROOT = path.join(__dirname, ".tmp-session-log-stream-tests");
test("quit cleanup finishes all pending file captures before resolving", async () => {
const directory = path.join(TEMP_ROOT, `quit-${Date.now()}`);
try {
for (const sessionId of ["quit-one", "quit-two"]) {
startStreamToFile(sessionId, { filePath: path.join(directory, `${sessionId}.log`), format: "raw" });
appendData(sessionId, `output before quit: ${sessionId}\r\n`);
}
await cleanupAll();
for (const sessionId of ["quit-one", "quit-two"]) {
assert.equal(hasStream(sessionId), false);
assert.equal(fs.readFileSync(path.join(directory, `${sessionId}.log`), "utf8"), `output before quit: ${sessionId}\r\n`);
}
} finally {
await cleanupAll();
fs.rmSync(directory, { recursive: true, force: true });
}
});
test("txt stream live snapshots include pending ED2 cleared screens", async () => {
const directory = path.join(TEMP_ROOT, `stream-${Date.now()}-${Math.random().toString(16).slice(2)}`);
const sessionId = `session-${Date.now()}-${Math.random().toString(16).slice(2)}`;
@@ -4,6 +4,7 @@ const {
} = require("./windowsWindowChrome.cjs");
const { attachDisplayRecovery } = require("./displayRecovery.cjs");
const perfTrace = require("../../perfTrace.cjs");
const { finalizeSessionLogs } = require("../sessionLogShutdown.cjs");
const TERMINAL_KEYBOARD_FOCUS = Symbol("netcattyTerminalKeyboardFocus");
@@ -534,11 +535,12 @@ function createMainWindowApi(ctx) {
: false;
})();
Promise.resolve(dirtyEditorQuery)
.then((hasDirty) => {
.then(async (hasDirty) => {
if (hasDirty) {
thisWindowCloseRequested = false;
return;
}
await finalizeSessionLogs(win.webContents, { ipcMain: electronModule.ipcMain });
dirtyEditorCloseConfirmed = true;
try {
win.close();
@@ -10,10 +10,18 @@ for (const peer of [true, false]) {
let ownsTabs = true;
let ownerChecks = 0;
let dirtyChecks = 0;
const ipcMain = new EventEmitter();
let finishLogCapture;
let logCaptures = 0;
let closeToTray = false;
class Window extends EventEmitter {
constructor() {
super(); this.destroyed = false;
this.webContents = Object.assign(new EventEmitter(), { id: 71, isDestroyed: () => this.destroyed, setWindowOpenHandler() {}, openDevTools() {}, send() {} });
this.webContents = Object.assign(new EventEmitter(), { id: 71, isDestroyed: () => this.destroyed, setWindowOpenHandler() {}, openDevTools() {}, send: (channel, payload) => {
if (channel !== "app:finalize-session-logs") return;
logCaptures++;
finishLogCapture = () => ipcMain.emit("app:session-logs-finalized", { sender: this.webContents }, { requestId: payload.requestId, success: true });
} });
}
close() { const event = { prevented: false, preventDefault() { this.prevented = true; } }; this.emit("close", event); if (!event.prevented) { this.destroyed = true; this.emit("closed"); } }
isDestroyed() { return this.destroyed; }
@@ -30,7 +38,11 @@ for (const peer of [true, false]) {
V8_CACHE_OPTIONS: "code", THEME_COLORS: { light: {} },
unhealthyWebContentsIds: new Set(), rendererReadySeenByWebContentsId: new Set(),
__dirname, URL, require, console, setTimeout, clearTimeout,
getGlobalShortcutBridge: () => ({ handleWindowClose: () => false }),
getGlobalShortcutBridge: () => ({ handleWindowClose: (event) => {
if (!closeToTray) return false;
event.preventDefault();
return true;
} }),
getMainWindowCount: () => 1,
debugLog() {}, resolveFrontendBackgroundColor() { return null; }, loadWindowState() { return null; },
getDevRendererBaseUrl: (url) => url, getWindowBoundsState() { return null; },
@@ -43,10 +55,18 @@ for (const peer of [true, false]) {
closeEditorTabsForSource: () => { ownerChecks++; return new Promise((resolve) => { finish = resolve; }); },
queryDirtyEditors: async () => { dirtyChecks++; return false; },
});
const win = await api.createWindow({ BrowserWindow: Window, nativeTheme: {}, app: {}, screen: {}, shell: {}, ipcMain: {} }, {
const win = await api.createWindow({ BrowserWindow: Window, nativeTheme: {}, app: {}, screen: {}, shell: {}, ipcMain }, {
preload: "/tmp/preload.cjs", devServerUrl: "http://localhost:5173", isDev: true, isMac: true,
electronDir: __dirname, route: peer ? "session-window" : undefined, registerAsMainWindow: !peer,
});
if (!peer) {
closeToTray = true;
win.close(); await tick();
assert.equal(win.destroyed, false);
assert.equal(logCaptures, 0, "hiding to tray must keep the session log live");
assert.equal(ownerChecks, 0);
closeToTray = false;
}
win.close(); win.close();
assert.equal(ownerChecks, 1, "repeat close must share the ownership check");
assert.equal(dirtyChecks, 0, "the short dirty query must not race a detached Save/Cancel prompt");
@@ -54,10 +74,14 @@ for (const peer of [true, false]) {
finish({ success: true, cancelled: true }); await tick();
assert.equal(win.destroyed, false, "Cancel keeps the source save/dock renderer alive");
assert.equal(dirtyChecks, 0);
assert.equal(logCaptures, 0, "Cancel must leave the live log ongoing");
win.close();
ownsTabs = false;
finish({ success: true, cancelled: false }); await tick();
assert.equal(dirtyChecks, 1);
assert.equal(logCaptures, 1);
assert.equal(win.destroyed, false, "renderer must survive until replay persistence acknowledges completion");
finishLogCapture(); await tick();
assert.equal(win.destroyed, true, "close proceeds only after all owned editors settled");
});
}
+12 -6
View File
@@ -237,6 +237,7 @@ const {
} = require("./main/appLockLifecycle.cjs");
const ptyProcessTree = require("./bridges/ptyProcessTree.cjs");
const { queryDirtyEditors } = require("./bridges/dirtyEditorGuard.cjs");
const { finalizeSessionLogs } = require("./bridges/sessionLogShutdown.cjs");
// GPU settings
// NOTE: Do not disable Chromium sandbox by default.
@@ -1665,7 +1666,17 @@ if (!gotLock) {
}
getWindowManager().setIsQuitting(true);
quitGuardChannelBusy = true;
void runPluginShutdown()
void (async () => {
try {
await Promise.all(getWindowManager().getAppContentWindows().map((win) => (
finalizeSessionLogs(win.webContents, { ipcMain: electronModule.ipcMain })
)));
await sessionLogStreamManager.cleanupAll();
} catch (error) {
console.warn("[SessionLogs] Shutdown failed; continuing app quit:", error);
}
return runPluginShutdown();
})()
.then(({ timedOut }) => {
if (timedOut) console.warn("[Plugins] Shutdown deadline elapsed; continuing app quit");
})
@@ -1727,11 +1738,6 @@ if (!gotLock) {
// Cleanup all PTY sessions and port forwarding tunnels before quitting
app.on("will-quit", () => {
try {
sessionLogStreamManager.cleanupAll();
} catch (err) {
console.warn("Error during session log stream cleanup:", err);
}
try {
terminalBridge.cleanupAllSessions();
} catch (err) {
+17
View File
@@ -7,6 +7,19 @@ const fs = require("node:fs");
const { stageRendererFileToTemp } = require("./stageUploadFile.cjs");
function createPreloadApi(ctx) {
const sessionLogFinalizers = new Set();
let pendingSessionLogFinalization = null;
ctx.ipcRenderer?.on?.("app:finalize-session-logs", async (_event, { requestId }) => {
const pending = pendingSessionLogFinalization ??= Promise.allSettled(
[...sessionLogFinalizers].map((finalize) => Promise.resolve().then(finalize)),
);
const results = await pending;
if (pendingSessionLogFinalization === pending) pendingSessionLogFinalization = null;
ctx.ipcRenderer.send("app:session-logs-finalized", {
requestId,
success: results.every((result) => result.status === "fulfilled"),
});
});
const terminalDataBacklog = ctx.terminalDataBacklog || null;
const displayDataListeners = ctx.displayDataListeners || new Map();
const closedTerminalDataSessions = ctx.closedTerminalDataSessions || null;
@@ -1544,6 +1557,10 @@ function createPreloadApi(ctx) {
reportDirtyEditorsResult: (hasDirty, reason, options) => ipcRenderer.send("app:dirty-editors-result", {
hasDirty, reason, requestId: options?.requestId, pending: options?.pending === true,
}),
onFinalizeSessionLogs: (finalize) => {
sessionLogFinalizers.add(finalize);
return () => sessionLogFinalizers.delete(finalize);
},
// Port Forwarding API
startPortForward: async (options) => {
+1
View File
@@ -299,6 +299,7 @@ declare global {
// Quit guard: subscribe to main-process quit requests that query for dirty editors.
// Each response must echo the request ID, including pending-transfer acknowledgements.
onCheckDirtyEditors?(listener: (request: { requestId: string; deadline: number }) => void): () => void;
onFinalizeSessionLogs?(listener: () => Promise<void>): () => void;
// Report the dirty-check result back to the main process.
reportDirtyEditorsResult?(hasDirty: boolean, reason?: "editors" | "transfers", options?: { requestId?: string; pending?: boolean }): void;