feat(tabs): reopen recently closed terminal tabs and workspaces with Cmd/Ctrl+Shift+T (#4325)

* feat(tabs): reopen recently closed terminal tabs and workspaces with Cmd/Ctrl+Shift+T

* test(tabs): drain activeTabStore notification timer before closing jsdom

* fix(tabs): exclude ephemeral hosts from closed tab reopen history
This commit is contained in:
陈大猫 authored and GitHub committed 2026-11-25 11:18:18 +08:00
1 parent bbbcf72b81
commit d9cb9a8fbc
15 files changed
+1625 -4

No files matched your search

@@ -1032,3 +1032,108 @@ test('host list shortcut calls the same store toggle as the toolbar button', ()
const source = readFileSync(new URL('./app/AppSideEffects.tsx', import.meta.url), 'utf8');
assert.match(source, /toggleHostTree:\s*\(\)\s*=>\s*terminalHostTreeStore\.toggle\(\)/);
});
test('Cmd+Shift+T on macOS and Ctrl+Shift+T on PC dispatch reopenClosedTab and stay out of text inputs', () => {
for (const [scheme, keyProps] of [
['mac', { metaKey: true, ctrlKey: false }],
['pc', { metaKey: false, ctrlKey: true }],
] as const) {
const target = new FakeHTMLElement();
const actions: string[] = [];
let prevented = false;
let stopped = false;
handleGlobalHotkeyKeyDownImpl(() => ({
HOTKEY_DEBUG: false,
closeTabKeyStr: '',
executeHotkeyAction: (action: string) => {
actions.push(action);
},
hotkeyScheme: scheme,
keyBindings: DEFAULT_KEY_BINDINGS,
matchesKeyBinding,
}), {
key: 'T',
code: 'KeyT',
...keyProps,
altKey: false,
shiftKey: true,
target,
composedPath: () => [target],
preventDefault: () => { prevented = true; },
stopPropagation: () => { stopped = true; },
} as unknown as KeyboardEvent);
assert.deepEqual(actions, ['reopenClosedTab']);
assert.equal(prevented, true);
assert.equal(stopped, true);
const input = new FakeInputHTMLElement();
const inputActions: string[] = [];
handleGlobalHotkeyKeyDownImpl(() => ({
HOTKEY_DEBUG: false,
closeTabKeyStr: '',
executeHotkeyAction: (action: string) => {
inputActions.push(action);
},
hotkeyScheme: scheme,
keyBindings: DEFAULT_KEY_BINDINGS,
matchesKeyBinding,
}), {
key: 'T',
code: 'KeyT',
...keyProps,
altKey: false,
shiftKey: true,
target: input,
composedPath: () => [input],
preventDefault: () => {},
stopPropagation: () => {},
} as unknown as KeyboardEvent);
assert.deepEqual(inputActions, []);
}
});
test('executeHotkeyActionImpl reopenClosedTab calls reopenLastClosedTab and records connection logs for reopened workspace panes', () => {
const logs: Array<Record<string, unknown>> = [];
let receivedHostIds: string[] = [];
const hostsById = new Map([
['h-1', { id: 'h-1', label: 'Prod', hostname: 'prod.test', username: 'ops', port: 22, os: 'linux', group: '', tags: [] }],
]);
executeHotkeyActionImpl(() => ({
activeTabStore: { getActiveTabId: () => 'vault' },
addConnectionLogRef: { current: (log: Record<string, unknown>) => logs.push(log) },
editorTabs: [],
hostsById,
orderedTabs: [],
reopenLastClosedTab: (opts: { availableHostIds?: ReadonlySet<string> }) => {
receivedHostIds = [...(opts.availableHostIds ?? [])];
return {
kind: 'workspace',
tabId: 'ws-new',
workspace: { id: 'ws-new', title: 'Prod Split', root: { id: 'p', type: 'pane', sessionId: 's-new-1' } },
sessions: [
{ id: 's-new-1', hostId: 'h-1', hostLabel: 'Prod', hostname: 'prod.test', username: 'ops', status: 'connecting', protocol: 'ssh', workspaceId: 'ws-new' },
{ id: 's-new-2', hostId: 'local-terminal', hostLabel: 'Local Terminal', hostname: 'localhost', username: 'local', status: 'connecting', protocol: 'local', workspaceId: 'ws-new' },
],
};
},
sessions: [],
settings: {},
systemInfoRef: { current: { username: 'dev', hostname: 'laptop' } },
toEditorTabId: (id: string) => id,
workspaces: [],
}), 'reopenClosedTab', {} as KeyboardEvent);
assert.deepEqual(receivedHostIds, ['h-1']);
assert.equal(logs.length, 2);
assert.equal(logs[0].sessionId, 's-new-1');
assert.equal(logs[0].hostId, 'h-1');
assert.equal(logs[0].username, 'ops');
assert.equal(logs[1].sessionId, 's-new-2');
assert.equal(logs[1].hostId, '');
assert.equal(logs[1].username, 'dev');
assert.equal(logs[1].protocol, 'local');
});
+34 -1
View File
@@ -915,7 +915,7 @@ export async function closeTabsBatchImpl(getCtx: AppContextGetter, targetIds: st
}
export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string, e: KeyboardEvent) {
const { IS_DEV, MOVE_FOCUS_DEBOUNCE_MS, activeTabStore, addConnectionLogRef, canUseGlobalBroadcast, closePluginViewTab, closeSession, closeTabInFlightRef, closeWorkspace, collectSessionIds, confirmIfBusyLocalTerminal, createLocalTerminalWithCurrentShell, editorTabs, fromEditorTabId, handleOpenSettingsRef, handleRequestCloseEditorTabRef, isEditorTabId, isPluginViewTabId, isQuickSwitcherOpen, lastMoveFocusTimeRef, moveFocusInWorkspace, orderedTabs, resolveCloseIntent, resolveSnippetsShortcutIntent, sessions, setActiveTabId, setAddToWorkspaceDialog, setIsQuickSwitcherOpen, setNavigateToSection, settings, sftpPaneMagnificationRef, splitSessionWithCurrentShell, systemInfoRef, terminalPaneMagnificationRef, toEditorTabId, toggleBroadcast, toggleGlobalBroadcast, toggleHostTree, toggleScriptsSidePanelRef, toggleSidePanelRef, toggleWindowOpacity, workspaces } = getCtx();
const { IS_DEV, MOVE_FOCUS_DEBOUNCE_MS, activeTabStore, addConnectionLogRef, canUseGlobalBroadcast, closePluginViewTab, closeSession, closeTabInFlightRef, closeWorkspace, collectSessionIds, confirmIfBusyLocalTerminal, createLocalTerminalWithCurrentShell, editorTabs, fromEditorTabId, handleOpenSettingsRef, handleRequestCloseEditorTabRef, hostsById, isEditorTabId, isPluginViewTabId, isQuickSwitcherOpen, lastMoveFocusTimeRef, moveFocusInWorkspace, orderedTabs, reopenLastClosedTab, resolveCloseIntent, resolveSnippetsShortcutIntent, sessions, setActiveTabId, setAddToWorkspaceDialog, setIsQuickSwitcherOpen, setNavigateToSection, settings, sftpPaneMagnificationRef, splitSessionWithCurrentShell, systemInfoRef, terminalPaneMagnificationRef, toEditorTabId, toggleBroadcast, toggleGlobalBroadcast, toggleHostTree, toggleScriptsSidePanelRef, toggleSidePanelRef, toggleWindowOpacity, workspaces } = getCtx();
{
const shortcutTabs = buildNumberShortcutTabTargets({
showSftpTab: settings.showSftpTab ?? true,
@@ -1061,6 +1061,39 @@ export function executeHotkeyActionImpl(getCtx: AppContextGetter, action: string
});
break;
}
case 'reopenClosedTab': {
const reopened = reopenLastClosedTab?.({
availableHostIds: hostsById ? new Set(hostsById.keys()) : undefined,
hostsById,
});
if (reopened && addConnectionLogRef?.current) {
const reopenedSessions = reopened.kind === 'session'
? [reopened.session]
: reopened.sessions;
const localUsername = systemInfoRef?.current?.username ?? '';
const localHostname = systemInfoRef?.current?.hostname ?? '';
const startTime = Date.now();
for (const reopenedSession of reopenedSessions) {
addConnectionLogRef.current({
sessionId: reopenedSession.id,
hostId: reopenedSession.protocol === 'local' && reopenedSession.hostId === 'local-terminal'
? ''
: reopenedSession.hostId,
hostLabel: reopenedSession.hostLabel,
hostname: reopenedSession.hostname,
username: reopenedSession.protocol === 'local'
? localUsername
: reopenedSession.username,
protocol: reopenedSession.protocol || 'ssh',
startTime,
localUsername,
localHostname,
saved: false,
});
}
}
break;
}
case 'openHosts':
setActiveTabId('vault');
break;
+6
View File
@@ -264,6 +264,7 @@ export function AppSideEffects() {
closeSession,
closeSessions,
closeWorkspace,
reopenLastClosedTab,
updateSessionStatus,
createWorkspaceWithHosts,
createWorkspaceFromTargets,
@@ -293,6 +294,8 @@ export function AppSideEffects() {
() => new Map(hosts.map((host) => [host.id, host])),
[hosts],
);
const hostByIdRef = useRef(hostById);
hostByIdRef.current = hostById;
const terminalHosts = useMemo(
() => (ephemeralHosts.length > 0 ? [...hosts, ...ephemeralHosts] : hosts),
[hosts, ephemeralHosts],
@@ -1128,12 +1131,14 @@ export function AppSideEffects() {
fromEditorTabId,
handleOpenSettingsRef,
handleRequestCloseEditorTabRef,
hostsById: hostByIdRef.current,
isEditorTabId,
isPluginViewTabId,
isQuickSwitcherOpen: isQuickSwitcherOpenRef.current,
lastMoveFocusTimeRef,
moveFocusInWorkspace,
orderedTabs: orderedTabsRef.current,
reopenLastClosedTab,
resolveCloseIntent,
resolveSnippetsShortcutIntent,
sessions: sessionsRef.current,
@@ -1165,6 +1170,7 @@ export function AppSideEffects() {
closePluginViewTab,
closeSession,
closeWorkspace,
reopenLastClosedTab,
createLocalTerminalWithCurrentShell,
splitSessionWithCurrentShell,
moveFocusInWorkspace,
+1
View File
@@ -1039,6 +1039,7 @@ Highlight the focused split pane:
'settings.shortcuts.binding.close-tab': 'Close Tab',
'settings.shortcuts.binding.close-session': 'Close Session Pane',
'settings.shortcuts.binding.new-tab': 'New Local Tab',
'settings.shortcuts.binding.reopen-closed-tab': 'Reopen Closed Tab',
'settings.shortcuts.binding.copy': 'Copy from Terminal',
'settings.shortcuts.binding.paste': 'Paste to Terminal',
'settings.shortcuts.binding.paste-selection': 'Paste Selection to Terminal',
+1
View File
@@ -1039,6 +1039,7 @@ Resalta el panel dividido enfocado:
'settings.shortcuts.binding.close-tab': 'Cerrar pestaña',
'settings.shortcuts.binding.close-session': 'Cerrar panel de sesión',
'settings.shortcuts.binding.new-tab': 'Nueva pestaña local',
'settings.shortcuts.binding.reopen-closed-tab': 'Reabrir pestaña cerrada',
'settings.shortcuts.binding.copy': 'Copiar desde la terminal',
'settings.shortcuts.binding.paste': 'Pegar en la terminal',
'settings.shortcuts.binding.paste-selection': 'Pegar selección en la terminal',
+1
View File
@@ -952,6 +952,7 @@ export const ruCoreMessages: Messages = {
'settings.shortcuts.binding.close-tab': 'Закрыть вкладку',
'settings.shortcuts.binding.close-session': 'Закрыть панель сессии',
'settings.shortcuts.binding.new-tab': 'Новая локальная вкладка',
'settings.shortcuts.binding.reopen-closed-tab': 'Повторно открыть закрытую вкладку',
'settings.shortcuts.binding.copy': 'Копировать из терминала',
'settings.shortcuts.binding.paste': 'Вставить в терминал',
'settings.shortcuts.binding.paste-selection': 'Вставить выделение в терминал',
@@ -590,6 +590,7 @@ export const zhCNTerminalMessages: Messages = {
'settings.shortcuts.binding.close-tab': '关闭标签页',
'settings.shortcuts.binding.close-session': '关闭会话窗格',
'settings.shortcuts.binding.new-tab': '新建本地标签页',
'settings.shortcuts.binding.reopen-closed-tab': '重新打开关闭的标签页',
'settings.shortcuts.binding.copy': '从终端复制',
'settings.shortcuts.binding.paste': '粘贴到终端',
'settings.shortcuts.binding.paste-selection': '将选区粘贴到终端',
@@ -590,6 +590,7 @@ export const zhTWTerminalMessages: Messages = {
'settings.shortcuts.binding.close-tab': '關閉分頁',
'settings.shortcuts.binding.close-session': '關閉工作階段窗格',
'settings.shortcuts.binding.new-tab': '新增本機分頁',
'settings.shortcuts.binding.reopen-closed-tab': '重新開啟關閉的分頁',
'settings.shortcuts.binding.copy': '從終端複製',
'settings.shortcuts.binding.paste': '貼上到終端',
'settings.shortcuts.binding.paste-selection': '將選區貼上到終端',
+1
View File
@@ -25,6 +25,7 @@ export const getAppLevelActions = (): Set<string> => {
'closeTab',
'closeSession',
'newTab',
'reopenClosedTab',
'openHosts',
'openSftp',
'quickSwitch',
@@ -0,0 +1,334 @@
import assert from "node:assert/strict";
import test from "node:test";
import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { JSDOM } from "jsdom";
import type { Host } from "../../domain/models";
import { buildSshDeepLinkEphemeralHostFromSaved } from "../../domain/sshDeepLink";
import { collectSessionIds } from "../../domain/workspace";
import { activeTabStore } from "./activeTabStore";
import { useSessionState } from "./useSessionState";
const makeHost = (id: string, label: string): Host => ({
id,
label,
hostname: `${id}.example.test`,
username: "ubuntu",
port: 22,
os: "linux",
group: "",
tags: [],
protocol: "ssh",
});
function setupDom(t: test.TestContext) {
const dom = new JSDOM('<div id="root"></div>', { url: "http://localhost" });
const globals = {
window: dom.window,
document: dom.window.document,
localStorage: dom.window.localStorage,
CustomEvent: dom.window.CustomEvent,
Event: dom.window.Event,
IS_REACT_ACT_ENVIRONMENT: true,
};
const previous = new Map<string, PropertyDescriptor | undefined>();
for (const [key, value] of Object.entries(globals)) {
previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key));
Object.defineProperty(globalThis, key, { configurable: true, value });
}
const root = createRoot(document.getElementById("root")!);
t.after(async () => {
activeTabStore.setActiveTabId("vault");
await new Promise((resolve) => dom.window.setTimeout(resolve, 0));
await act(async () => root.unmount());
dom.window.close();
for (const [key, descriptor] of previous) {
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
else Reflect.deleteProperty(globalThis, key);
}
});
return { root };
}
test("useSessionState reopens closed standalone tabs and 2-pane split workspaces in LIFO order", async (t) => {
const { root } = setupDom(t);
let state!: ReturnType<typeof useSessionState>;
function Probe() {
state = useSessionState({ persistSessionRestore: false });
return null;
}
await act(async () => {
root.render(React.createElement(React.StrictMode, null, React.createElement(Probe)));
});
const hostA = makeHost("h-a", "App Server");
const hostB = makeHost("h-b", "DB Server");
const hostsById = new Map<string, Host>([
[hostA.id, hostA],
[hostB.id, hostB],
]);
const availableHostIds = new Set(hostsById.keys());
// 1. Open and close a standalone SSH host tab and a local terminal tab.
let soloId = "";
let localId = "";
await act(async () => {
soloId = state.connectToHost(hostA);
localId = state.createLocalTerminal({ shellName: "Zsh", localStartDir: "/tmp" });
});
await act(async () => {
state.updateSessionRestoreCwd(localId, "/Users/dev/workspace");
state.renameSessionInline(soloId, "Custom Prod");
});
await act(async () => {
state.closeSession(soloId);
});
await act(async () => {
state.closeSession(localId);
});
assert.equal(state.sessions.length, 0);
assert.equal(state.getClosedTabHistoryCount(), 2);
// 2. Create a 2-pane split workspace, customize split sizes & focus, then close it.
await act(async () => {
state.createWorkspaceWithHosts("Ops Split", [hostA, hostB]);
});
const origWorkspace = state.workspaces[0];
assert.ok(origWorkspace);
assert.equal(origWorkspace.root.type, "split");
const origPaneIds = collectSessionIds(origWorkspace.root);
assert.equal(origPaneIds.length, 2);
await act(async () => {
state.updateSplitSizes(origWorkspace.id, origWorkspace.root.id, [0.7, 0.3]);
state.setWorkspaceFocusedSession(origWorkspace.id, origPaneIds[1]);
});
await act(async () => {
state.closeWorkspace(origWorkspace.id);
});
assert.equal(state.workspaces.length, 0);
assert.equal(state.sessions.length, 0);
assert.equal(activeTabStore.getActiveTabId(), "vault");
assert.equal(state.getClosedTabHistoryCount(), 3);
// 3. First reopen: restores the 2-pane split workspace with ratios, title, and focused pane.
await act(async () => {
const reopened = state.reopenLastClosedTab({ availableHostIds, hostsById });
assert.ok(reopened && reopened.kind === "workspace");
});
assert.equal(state.workspaces.length, 1);
assert.equal(state.sessions.length, 2);
const restoredWs = state.workspaces[0];
assert.notEqual(restoredWs.id, origWorkspace.id);
assert.equal(restoredWs.title, "Ops Split");
assert.equal(restoredWs.viewMode, "split");
assert.equal(restoredWs.root.type, "split");
assert.deepEqual(restoredWs.root.sizes, [0.7, 0.3]);
assert.equal(activeTabStore.getActiveTabId(), restoredWs.id);
const restoredPaneIds = collectSessionIds(restoredWs.root);
assert.equal(restoredPaneIds.length, 2);
assert.equal(restoredWs.focusedSessionId, restoredPaneIds[1]);
assert.deepEqual(
state.sessions.map((s) => s.hostId),
[hostA.id, hostB.id],
);
assert.ok(state.sessions.every((s) => s.status === "connecting" && s.workspaceId === restoredWs.id));
// 4. Second reopen: restores the local terminal tab with its last tracked CWD.
await act(async () => {
const reopened = state.reopenLastClosedTab({ availableHostIds, hostsById });
assert.ok(reopened && reopened.kind === "session");
});
assert.equal(state.sessions.length, 3);
const restoredLocal = state.sessions.find((s) => !s.workspaceId && s.protocol === "local");
assert.ok(restoredLocal);
assert.notEqual(restoredLocal.id, localId);
assert.equal(restoredLocal.localStartDir, "/Users/dev/workspace");
assert.equal(restoredLocal.status, "connecting");
assert.equal(activeTabStore.getActiveTabId(), restoredLocal.id);
// 5. Third reopen: restores the standalone SSH host tab with customName preserved.
await act(async () => {
const reopened = state.reopenLastClosedTab({ availableHostIds, hostsById });
assert.ok(reopened && reopened.kind === "session");
});
assert.equal(state.sessions.length, 4);
const restoredSolo = state.sessions.find((s) => !s.workspaceId && s.hostId === hostA.id);
assert.ok(restoredSolo);
assert.notEqual(restoredSolo.id, soloId);
assert.equal(restoredSolo.customName, "Custom Prod");
assert.equal(restoredSolo.status, "connecting");
assert.equal(activeTabStore.getActiveTabId(), restoredSolo.id);
// 6. Fourth reopen on empty stack is a clean no-op.
await act(async () => {
const empty = state.reopenLastClosedTab({ availableHostIds, hostsById });
assert.equal(empty, null);
});
assert.equal(state.sessions.length, 4);
});
test("useSessionState skips deleted vault hosts and ignores hidden MCP sessions on reopen", async (t) => {
const { root } = setupDom(t);
let state!: ReturnType<typeof useSessionState>;
function Probe() {
state = useSessionState({ persistSessionRestore: false });
return null;
}
await act(async () => {
root.render(React.createElement(React.StrictMode, null, React.createElement(Probe)));
});
const keepHost = makeHost("h-keep", "Keep");
const deleteHost = makeHost("h-delete", "Delete Me");
let keepId = "";
let deleteId = "";
let hiddenId = "";
await act(async () => {
keepId = state.connectToHost(keepHost);
deleteId = state.connectToHost(deleteHost);
hiddenId = state.connectToHost(keepHost, { hidden: true });
});
await act(async () => {
state.closeSession(keepId);
});
await act(async () => {
state.closeSession(deleteId);
});
await act(async () => {
state.closeSession(hiddenId);
});
// Hidden session was never added to history.
assert.equal(state.getClosedTabHistoryCount(), 2);
// Delete `h-delete` from the vault before reopening.
const remainingHosts = new Map<string, Host>([[keepHost.id, keepHost]]);
const availableHostIds = new Set(remainingHosts.keys());
await act(async () => {
const reopened = state.reopenLastClosedTab({ availableHostIds, hostsById: remainingHosts });
assert.ok(reopened && reopened.kind === "session");
assert.equal(reopened.session.hostId, keepHost.id);
});
assert.equal(state.sessions.length, 1);
assert.equal(state.sessions[0].hostId, keepHost.id);
assert.equal(state.getClosedTabHistoryCount(), 0);
});
test("useSessionState prunes deleted hosts from a closed split workspace on reopen without persisting history to localStorage", async (t) => {
const { root } = setupDom(t);
let state!: ReturnType<typeof useSessionState>;
function Probe() {
state = useSessionState({ persistSessionRestore: false });
return null;
}
await act(async () => {
root.render(React.createElement(React.StrictMode, null, React.createElement(Probe)));
});
const hostA = makeHost("h-a", "Web");
const hostB = makeHost("h-b", "Worker");
const hostC = makeHost("h-c", "Cache");
await act(async () => {
state.createWorkspaceWithHosts("Cluster", [hostA, hostB, hostC]);
});
const ws = state.workspaces[0];
assert.ok(ws && ws.root.type === "split");
await act(async () => {
state.updateSplitSizes(ws.id, ws.root.id, [0.2, 0.3, 0.5]);
});
await act(async () => {
state.closeWorkspace(ws.id);
});
assert.equal(window.localStorage.length, 0, "closed tab history must stay in-memory only");
// Delete hostB from the vault before reopening.
const survivingHosts = new Map<string, Host>([
[hostA.id, hostA],
[hostC.id, hostC],
]);
await act(async () => {
const reopened = state.reopenLastClosedTab({
availableHostIds: new Set(survivingHosts.keys()),
hostsById: survivingHosts,
});
assert.ok(reopened && reopened.kind === "workspace");
});
assert.equal(state.workspaces.length, 1);
const restored = state.workspaces[0];
assert.equal(restored.title, "Cluster");
assert.equal(restored.root.type, "split");
assert.equal(collectSessionIds(restored.root).length, 2);
assert.deepEqual(state.sessions.map((s) => s.hostId), [hostA.id, hostC.id]);
assert.ok(Math.abs((restored.root.sizes?.[0] ?? 0) - 2 / 7) < 1e-9);
assert.ok(Math.abs((restored.root.sizes?.[1] ?? 0) - 5 / 7) < 1e-9);
});
test("useSessionState excludes ephemeral deep-link hosts with bastion/proxy/legacy settings from reopen history", async (t) => {
const { root } = setupDom(t);
let state!: ReturnType<typeof useSessionState>;
function Probe() {
state = useSessionState({ persistSessionRestore: false });
return null;
}
await act(async () => {
root.render(React.createElement(React.StrictMode, null, React.createElement(Probe)));
});
const savedHost: Host = {
...makeHost("h-bastion-target", "Bastion Target"),
hostChain: { hostIds: ["h-jump"] },
proxyConfig: { type: "socks5", host: "127.0.0.1", port: 1080 },
legacyAlgorithms: true,
};
const ephemeralHost = buildSshDeepLinkEphemeralHostFromSaved(
savedHost,
{ rawUrl: `ssh://${savedHost.username}:otp@${savedHost.hostname}`, hostname: savedHost.hostname, username: savedHost.username, password: "otp" },
{ id: "ephemeral-1", now: 1000 },
);
let savedSessionId = "";
let ephSessionId = "";
await act(async () => {
savedSessionId = state.connectToHost(savedHost);
ephSessionId = state.connectToHost(ephemeralHost);
});
await act(async () => {
state.closeSession(savedSessionId);
});
await act(async () => {
state.closeSession(ephSessionId);
});
// Only the saved vault host was recorded; the ephemeral host was skipped.
assert.equal(state.getClosedTabHistoryCount(), 1);
const hostsById = new Map<string, Host>([[savedHost.id, savedHost]]);
await act(async () => {
const reopened = state.reopenLastClosedTab({
availableHostIds: new Set(hostsById.keys()),
hostsById,
});
assert.ok(reopened && reopened.kind === "session");
assert.equal(reopened.session.hostId, savedHost.id);
assert.equal(reopened.session.ephemeralHost, undefined);
});
assert.equal(state.sessions.length, 1);
assert.equal(state.sessions[0].hostId, savedHost.id);
assert.equal(state.getClosedTabHistoryCount(), 0);
});
+76 -3
View File
@@ -79,6 +79,15 @@ import {
import { cleanupClosedTerminalSessions } from './aiStateSnapshots';
import { captureClosingTerminalSessions } from './terminalSessionCloseCapture';
import { syncSessionHostLabels } from '../../domain/syncSessionHostLabels';
import {
createClosedSessionEntry,
createClosedWorkspaceEntry,
materializeClosedTabEntry,
popClosedTabEntry,
pushClosedTabEntry,
type ClosedTabEntry,
type ReopenClosedTabMaterialized,
} from '../../domain/closedTabHistory';
import { useVaultSnapshotField } from './vaultSnapshotStore';
export function addWorkspaceIfMissing(
@@ -280,6 +289,10 @@ export const useSessionState = ({
const [restorePreviousSessionRevision, setRestorePreviousSessionRevision] = useState(0);
const sessionsRef = useRef(sessions);
const tabOrderRef = useRef(tabOrder);
// Bounded in-memory LIFO stack of recently closed standalone tabs and split
// workspaces (Cmd/Ctrl+Shift+T). Kept in a ref so closing tabs adds no extra
// React re-renders and never persists ephemeral/session data to localStorage.
const closedTabHistoryRef = useRef<ClosedTabEntry[]>([]);
const scheduleSessionRestorePersistRef = useRef<() => void>(() => {});
const sessionRestoreCwdByIdRef = useRef(
new Map(
@@ -617,9 +630,17 @@ export const useSessionState = ({
}, []);
const closeWorkspace = useCallback((workspaceId: string) => {
const closedIds = sessionsRef.current
.filter(session => session.workspaceId === workspaceId)
.map(session => session.id);
const closingWorkspace = workspacesRef.current.find(w => w.id === workspaceId);
const closingSessions = sessionsRef.current.filter(session => session.workspaceId === workspaceId);
if (closingWorkspace && closingSessions.length > 0) {
const closedEntry = createClosedWorkspaceEntry(closingWorkspace, closingSessions, {
cwdBySessionId: sessionRestoreCwdByIdRef.current,
});
if (closedEntry) {
closedTabHistoryRef.current = pushClosedTabEntry(closedTabHistoryRef.current, closedEntry);
}
}
const closedIds = closingSessions.map(session => session.id);
captureClosingTerminalSessions(closedIds);
cleanupClosedTerminalSessions(closedIds);
for (const sessionId of closedIds) {
@@ -654,6 +675,16 @@ export const useSessionState = ({
}, []);
const closeSessions = useCallback((sessionIds: string[]) => {
for (const sessionId of new Set(sessionIds)) {
const targetSession = sessionsRef.current.find(session => session.id === sessionId);
if (!targetSession) continue;
const closedEntry = createClosedSessionEntry(targetSession, {
lastCwd: sessionRestoreCwdByIdRef.current.get(sessionId),
});
if (closedEntry) {
closedTabHistoryRef.current = pushClosedTabEntry(closedTabHistoryRef.current, closedEntry);
}
}
captureClosingTerminalSessions(sessionIds);
cleanupClosedTerminalSessions(sessionIds);
for (const sessionId of sessionIds) {
@@ -682,6 +713,46 @@ export const useSessionState = ({
}
}, []);
const reopenLastClosedTab = useCallback((options?: {
availableHostIds?: ReadonlySet<string>;
hostsById?: ReadonlyMap<string, Host>;
}): ReopenClosedTabMaterialized | null => {
const { entry, nextHistory } = popClosedTabEntry(closedTabHistoryRef.current, {
availableHostIds: options?.availableHostIds,
});
closedTabHistoryRef.current = nextHistory;
if (!entry) return null;
const materialized = materializeClosedTabEntry(entry, {
hostsById: options?.hostsById,
});
if (!materialized) return null;
if (materialized.kind === 'session') {
const reopenedSession = materialized.session;
setSessions(prev => addTerminalSessionIfMissing(prev, reopenedSession));
setTabOrder(prev => (prev.includes(reopenedSession.id) ? prev : [...prev, reopenedSession.id]));
setActiveTabId(reopenedSession.id);
return materialized;
}
const { workspace, sessions: reopenedSessions } = materialized;
const reopenedSessionIds = new Set(reopenedSessions.map(s => s.id));
setSessions(prev => {
if (prev.some(s => reopenedSessionIds.has(s.id))) return prev;
return [...prev, ...reopenedSessions];
});
setWorkspaces(prev => addWorkspaceIfMissing(prev, workspace));
setTabOrder(prev => (prev.includes(workspace.id) ? prev : [...prev, workspace.id]));
setActiveTabId(workspace.id);
return materialized;
}, [setActiveTabId]);
const getClosedTabHistoryCount = useCallback(
() => closedTabHistoryRef.current.length,
[],
);
const closeSession = useCallback((sessionId: string, e?: MouseEvent) => {
e?.stopPropagation();
closeSessions([sessionId]);
@@ -1595,6 +1666,8 @@ export const useSessionState = ({
closeSession,
closeSessions,
closeWorkspace,
reopenLastClosedTab,
getClosedTabHistoryCount,
updateSessionStatus,
updateSessionFontSize,
setSessionPoppedOut,
+461
View File
@@ -0,0 +1,461 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { Host, TerminalSession, Workspace } from "./models";
import { buildSshDeepLinkEphemeralHostFromSaved } from "./sshDeepLink";
import { collectSessionIds } from "./workspace";
import { createHostTerminalSession } from "../application/state/sessionFactories";
import {
DEFAULT_CLOSED_TAB_HISTORY_LIMIT,
createClosedSessionEntry,
createClosedSessionSnapshot,
createClosedWorkspaceEntry,
isClosedSessionSnapshotRestorable,
materializeClosedTabEntry,
popClosedTabEntry,
pruneClosedTabEntries,
pushClosedTabEntry,
type ClosedTabEntry,
} from "./closedTabHistory";
const makeSession = (
id: string,
overrides: Partial<TerminalSession> = {},
): TerminalSession => ({
id,
hostId: `host-${id}`,
hostLabel: `Host ${id}`,
hostname: `${id}.example.test`,
username: "ops",
status: "connected",
protocol: "ssh",
port: 22,
...overrides,
});
const makeHost = (id: string, overrides: Partial<Host> = {}): Host => ({
id,
label: `Vault ${id}`,
hostname: `${id}.vault.test`,
username: "admin",
port: 22,
os: "linux",
group: "",
tags: [],
protocol: "ssh",
...overrides,
});
test("createClosedSessionSnapshot strips transient, secret-adjacent, and script fields", () => {
const hidden = createClosedSessionSnapshot(makeSession("s-hidden", { hiddenFromTabs: true }));
assert.equal(hidden, null);
const source = makeSession("s1", {
customName: "Prod Web",
fontSize: 15,
fontSizeOverride: true,
localShell: "/bin/zsh",
localShellArgs: ["-l"],
startupCommand: "rm -rf /tmp/foo",
noAutoRun: false,
pendingScriptId: "script-1",
reuseConnectionFromSessionId: "prev-session",
restoreState: "restored-disconnected",
pendingInitialCwd: "/var/log",
dynamicTitle: "vim",
requireFreshConnection: true,
});
const snapshot = createClosedSessionSnapshot(source, { lastCwd: "/srv/app" });
assert.ok(snapshot);
assert.equal(snapshot.sourceSessionId, "s1");
assert.equal(snapshot.customName, "Prod Web");
assert.equal(snapshot.fontSize, 15);
assert.equal(snapshot.fontSizeOverride, true);
assert.equal(snapshot.lastCwd, "/srv/app");
assert.equal(snapshot.requireFreshConnection, true);
assert.deepEqual(snapshot.localShellArgs, ["-l"]);
// Mutating source arrays after snapshotting does not mutate the snapshot.
source.localShellArgs?.push("-i");
assert.deepEqual(snapshot.localShellArgs, ["-l"]);
assert.equal("startupCommand" in snapshot, false);
assert.equal("pendingScriptId" in snapshot, false);
assert.equal("pendingScript" in snapshot, false);
assert.equal("reuseConnectionFromSessionId" in snapshot, false);
assert.equal("restoreState" in snapshot, false);
assert.equal("pendingInitialCwd" in snapshot, false);
assert.equal("dynamicTitle" in snapshot, false);
});
test("pushClosedTabEntry enforces bounded LIFO limit and deduplicates by sourceId", () => {
let history: ClosedTabEntry[] = [];
for (let i = 1; i <= DEFAULT_CLOSED_TAB_HISTORY_LIMIT + 5; i++) {
const entry = createClosedSessionEntry(makeSession(`s-${i}`), { closedAt: i });
history = pushClosedTabEntry(history, entry);
}
assert.equal(history.length, DEFAULT_CLOSED_TAB_HISTORY_LIMIT);
assert.equal(history[0].sourceId, "s-6");
assert.equal(history[history.length - 1].sourceId, "s-25");
// Duplicate push of an already-recorded close event is ignored.
const dup = createClosedSessionEntry(makeSession("s-25"), { closedAt: 999 });
const afterDup = pushClosedTabEntry(history, dup);
assert.equal(afterDup.length, DEFAULT_CLOSED_TAB_HISTORY_LIMIT);
assert.equal(afterDup[afterDup.length - 1].closedAt, 25);
// Pop returns most recently closed entry first (LIFO).
const firstPop = popClosedTabEntry(afterDup);
assert.equal(firstPop.entry?.sourceId, "s-25");
assert.equal(firstPop.nextHistory.length, DEFAULT_CLOSED_TAB_HISTORY_LIMIT - 1);
const secondPop = popClosedTabEntry(firstPop.nextHistory);
assert.equal(secondPop.entry?.sourceId, "s-24");
});
test("isClosedSessionSnapshotRestorable handles vault hosts, local terminals, quick serial, and rejects ephemeral hosts", () => {
const availableHostIds = new Set(["host-live"]);
assert.equal(
isClosedSessionSnapshotRestorable(
createClosedSessionSnapshot(makeSession("s1", { hostId: "host-live" }))!,
availableHostIds,
),
true,
);
assert.equal(
isClosedSessionSnapshotRestorable(
createClosedSessionSnapshot(makeSession("s2", { hostId: "host-deleted" }))!,
availableHostIds,
),
false,
);
assert.equal(
isClosedSessionSnapshotRestorable(
createClosedSessionSnapshot(makeSession("local-1", {
hostId: "local-terminal",
protocol: "local",
hostname: "localhost",
username: "local",
}))!,
availableHostIds,
),
true,
);
assert.equal(
isClosedSessionSnapshotRestorable(
createClosedSessionSnapshot(makeSession("serial-1", {
hostId: "serial-abc",
protocol: "serial",
hostname: "/dev/ttyUSB0",
username: "",
serialConfig: { path: "/dev/ttyUSB0", baudRate: 115200 },
}))!,
availableHostIds,
),
true,
);
assert.equal(
isClosedSessionSnapshotRestorable(
{
sourceSessionId: "eph-1",
hostId: "ephemeral-1",
hostLabel: "Deep Link",
hostname: "jump.example.test",
username: "ops",
protocol: "ssh",
ephemeralHost: true,
},
availableHostIds,
),
false,
);
assert.equal(
isClosedSessionSnapshotRestorable({
sourceSessionId: "eph-1",
hostId: "ephemeral-1",
hostLabel: "Deep Link",
hostname: "jump.example.test",
username: "ops",
protocol: "ssh",
ephemeralHost: true,
}),
false,
);
});
test("ephemeral hosts with bastion hostChain, proxyConfig, and legacyAlgorithms are excluded from closed tab history", () => {
const savedBastionTarget = makeHost("h-prod-internal", {
label: "Internal Prod",
hostname: "10.0.0.42",
username: "ops",
hostChain: { hostIds: ["h-bastion-1"] },
proxyConfig: { type: "socks5", host: "127.0.0.1", port: 1080 },
legacyAlgorithms: true,
});
const ephemeralHost = buildSshDeepLinkEphemeralHostFromSaved(
savedBastionTarget,
{ rawUrl: "ssh://ops:one-time-password@10.0.0.42", hostname: "10.0.0.42", username: "ops", password: "one-time-password" },
{ id: "ephemeral-deeplink-1", now: 1234 },
);
assert.equal(ephemeralHost.ephemeral, true);
assert.deepEqual(ephemeralHost.hostChain, { hostIds: ["h-bastion-1"] });
assert.deepEqual(ephemeralHost.proxyConfig, { type: "socks5", host: "127.0.0.1", port: 1080 });
assert.equal(ephemeralHost.legacyAlgorithms, true);
const ephemeralSession = createHostTerminalSession("sess-eph-1", ephemeralHost);
assert.equal(ephemeralSession.ephemeralHost, true);
// Ephemeral standalone tabs are never captured because their Host record
// (including hostChain, proxyConfig, legacyAlgorithms, and one-time auth) is
// purged on close and cannot be faithfully reconstructed via fallback host.
assert.equal(createClosedSessionSnapshot(ephemeralSession), null);
assert.equal(createClosedSessionEntry(ephemeralSession), null);
// An all-ephemeral workspace is excluded.
const ephOnlyWs: Workspace = {
id: "ws-eph-only",
title: "Ephemeral Only",
root: { id: "p-eph", type: "pane", sessionId: ephemeralSession.id },
};
assert.equal(
createClosedWorkspaceEntry(ephOnlyWs, [{ ...ephemeralSession, workspaceId: ephOnlyWs.id }]),
null,
);
// A mixed workspace drops the ephemeral pane and preserves the restorable saved host pane.
const savedSession = makeSession("sess-saved-1", {
workspaceId: "ws-mixed",
hostId: savedBastionTarget.id,
});
const mixedWs: Workspace = {
id: "ws-mixed",
title: "Mixed",
focusedSessionId: ephemeralSession.id,
root: {
id: "split-mixed",
type: "split",
direction: "vertical",
sizes: [0.6, 0.4],
children: [
{ id: "p-saved", type: "pane", sessionId: savedSession.id },
{ id: "p-eph", type: "pane", sessionId: ephemeralSession.id },
],
},
};
const mixedEntry = createClosedWorkspaceEntry(mixedWs, [
savedSession,
{ ...ephemeralSession, workspaceId: mixedWs.id },
]);
assert.ok(mixedEntry);
assert.deepEqual(collectSessionIds(mixedEntry.root), [savedSession.id]);
assert.equal(mixedEntry.focusedSessionId, savedSession.id);
// Even a pre-built ephemeral entry is rejected by pruneClosedTabEntries,
// popClosedTabEntry, and materializeClosedTabEntry.
const craftedEphemeralEntry: ClosedTabEntry = {
kind: "session",
sourceId: "sess-eph-crafted",
closedAt: 1,
session: {
sourceSessionId: "sess-eph-crafted",
hostId: ephemeralHost.id,
hostLabel: ephemeralHost.label,
hostname: ephemeralHost.hostname,
username: ephemeralHost.username,
protocol: "ssh",
ephemeralHost: true,
},
};
assert.deepEqual(pruneClosedTabEntries([craftedEphemeralEntry]), []);
assert.equal(popClosedTabEntry([craftedEphemeralEntry]).entry, null);
assert.equal(materializeClosedTabEntry(craftedEphemeralEntry), null);
});
test("createClosedWorkspaceEntry captures nested layout ratios, focus, and view mode, and skips empty workspaces", () => {
const emptyWs: Workspace = {
id: "ws-empty",
title: "Empty",
root: { id: "r", type: "split", direction: "vertical", children: [], sizes: [] },
};
assert.equal(createClosedWorkspaceEntry(emptyWs, []), null);
const ws: Workspace = {
id: "ws-1",
title: "Prod Cluster",
autoTitle: false,
viewMode: "split",
focusedSessionId: "s3",
focusSessionOrder: ["s2", "s3", "s1"],
anchorChatId: "chat-should-not-carry",
root: {
id: "split-root",
type: "split",
direction: "vertical",
sizes: [0.35, 0.65],
children: [
{ id: "pane-1", type: "pane", sessionId: "s1" },
{
id: "split-right",
type: "split",
direction: "horizontal",
sizes: [0.3, 0.7],
children: [
{ id: "pane-2", type: "pane", sessionId: "s2" },
{ id: "pane-3", type: "pane", sessionId: "s3" },
],
},
],
},
};
const members = [
makeSession("s1", { workspaceId: "ws-1" }),
makeSession("s2", { workspaceId: "ws-1" }),
makeSession("s3", { workspaceId: "ws-1", protocol: "local", hostId: "local-terminal" }),
];
const entry = createClosedWorkspaceEntry(ws, members, {
closedAt: 1000,
cwdBySessionId: new Map([["s3", "/Users/dev/project"]]),
});
assert.ok(entry);
assert.equal(entry.kind, "workspace");
assert.equal(entry.title, "Prod Cluster");
assert.equal(entry.autoTitle, false);
assert.equal(entry.viewMode, "split");
assert.equal(entry.focusedSessionId, "s3");
assert.deepEqual(entry.focusSessionOrder, ["s2", "s3", "s1"]);
assert.equal(entry.sessions.length, 3);
assert.equal(entry.sessions[2].lastCwd, "/Users/dev/project");
assert.equal(entry.root.type, "split");
assert.deepEqual(entry.root.sizes, [0.35, 0.65]);
assert.equal("anchorChatId" in entry, false);
});
test("pruneClosedTabEntries and popClosedTabEntry skip deleted hosts and prune partial workspace panes while preserving ratios", () => {
const ws: Workspace = {
id: "ws-1",
title: "Mixed",
focusedSessionId: "s2",
focusSessionOrder: ["s1", "s2", "s3"],
root: {
id: "root",
type: "split",
direction: "vertical",
sizes: [0.2, 0.3, 0.5],
children: [
{ id: "p1", type: "pane", sessionId: "s1" },
{ id: "p2", type: "pane", sessionId: "s2" },
{ id: "p3", type: "pane", sessionId: "s3" },
],
},
};
const wsEntry = createClosedWorkspaceEntry(ws, [
makeSession("s1", { workspaceId: "ws-1", hostId: "h-keep-1" }),
makeSession("s2", { workspaceId: "ws-1", hostId: "h-deleted" }),
makeSession("s3", { workspaceId: "ws-1", hostId: "h-keep-3" }),
])!;
const deletedStandalone = createClosedSessionEntry(makeSession("s-del", { hostId: "h-deleted" }))!;
let history: ClosedTabEntry[] = [];
history = pushClosedTabEntry(history, wsEntry);
history = pushClosedTabEntry(history, deletedStandalone);
const availableHostIds = new Set(["h-keep-1", "h-keep-3"]);
const pruned = pruneClosedTabEntries(history, { availableHostIds });
assert.equal(pruned.length, 1);
assert.equal(pruned[0].kind, "workspace");
assert.deepEqual(collectSessionIds(pruned[0].root), ["s1", "s3"]);
assert.equal(pruned[0].focusedSessionId, "s1");
assert.deepEqual(pruned[0].focusSessionOrder, ["s1", "s3"]);
assert.equal(pruned[0].root.type, "split");
// Ratios 0.2 and 0.5 renormalized to 2/7 and 5/7.
assert.ok(Math.abs((pruned[0].root.sizes?.[0] ?? 0) - 2 / 7) < 1e-9);
assert.ok(Math.abs((pruned[0].root.sizes?.[1] ?? 0) - 5 / 7) < 1e-9);
// popClosedTabEntry skips the deleted standalone entry at the top and pops the pruned workspace.
const popped = popClosedTabEntry(history, { availableHostIds });
assert.ok(popped.entry);
assert.equal(popped.entry.kind, "workspace");
assert.deepEqual(collectSessionIds(popped.entry.root), ["s1", "s3"]);
assert.equal(popped.nextHistory.length, 0);
// If all hosts are deleted, pop returns null cleanly.
const emptyPop = popClosedTabEntry(history, { availableHostIds: new Set() });
assert.equal(emptyPop.entry, null);
assert.equal(emptyPop.nextHistory.length, 0);
});
test("materializeClosedTabEntry mints fresh ids, reconnects immediately, and refreshes live host metadata", () => {
let seq = 0;
const createId = () => `new-${++seq}`;
const hostsById = new Map<string, Host>([
["host-s1", makeHost("host-s1", { label: "Renamed Prod", hostname: "prod-new.test", username: "deploy" })],
]);
const sessionEntry = createClosedSessionEntry(
makeSession("s1", { customName: "My Tab", status: "disconnected" }),
)!;
const reopenedSolo = materializeClosedTabEntry(sessionEntry, { hostsById, createId });
assert.ok(reopenedSolo && reopenedSolo.kind === "session");
assert.equal(reopenedSolo.tabId, "new-1");
assert.equal(reopenedSolo.session.id, "new-1");
assert.equal(reopenedSolo.session.status, "connecting");
assert.equal(reopenedSolo.session.restoreState, undefined);
assert.equal(reopenedSolo.session.hostLabel, "Renamed Prod");
assert.equal(reopenedSolo.session.hostname, "prod-new.test");
assert.equal(reopenedSolo.session.username, "deploy");
assert.equal(reopenedSolo.session.customName, "My Tab");
const ws: Workspace = {
id: "ws-old",
title: "Dual",
viewMode: "split",
focusedSessionId: "s2",
focusSessionOrder: ["s1", "s2"],
root: {
id: "split-old",
type: "split",
direction: "vertical",
sizes: [0.7, 0.3],
children: [
{ id: "p1-old", type: "pane", sessionId: "s1" },
{ id: "p2-old", type: "pane", sessionId: "s2" },
],
},
};
const wsEntry = createClosedWorkspaceEntry(ws, [
makeSession("s1", { workspaceId: "ws-old" }),
makeSession("s2", {
workspaceId: "ws-old",
hostId: "local-terminal",
protocol: "local",
hostname: "localhost",
username: "local",
localStartDir: "/home/initial",
}),
], { cwdBySessionId: new Map([["s2", "/home/current"]]) })!;
const reopenedWs = materializeClosedTabEntry(wsEntry, { hostsById, createId });
assert.ok(reopenedWs && reopenedWs.kind === "workspace");
assert.notEqual(reopenedWs.workspace.id, "ws-old");
assert.equal(reopenedWs.tabId, reopenedWs.workspace.id);
assert.equal(reopenedWs.workspace.title, "Dual");
assert.equal(reopenedWs.workspace.viewMode, "split");
assert.equal(reopenedWs.sessions.length, 2);
assert.ok(reopenedWs.sessions.every((s) => s.workspaceId === reopenedWs.workspace.id));
assert.ok(reopenedWs.sessions.every((s) => s.status === "connecting"));
assert.equal(reopenedWs.sessions[0].hostLabel, "Renamed Prod");
assert.equal(reopenedWs.sessions[1].localStartDir, "/home/current");
const newPaneIds = collectSessionIds(reopenedWs.workspace.root);
assert.deepEqual(newPaneIds, reopenedWs.sessions.map((s) => s.id));
assert.equal(reopenedWs.workspace.focusedSessionId, reopenedWs.sessions[1].id);
assert.deepEqual(reopenedWs.workspace.focusSessionOrder, reopenedWs.sessions.map((s) => s.id));
assert.equal(reopenedWs.workspace.root.type, "split");
assert.deepEqual(reopenedWs.workspace.root.sizes, [0.7, 0.3]);
});
+540
View File
@@ -0,0 +1,540 @@
import type {
Host,
PluginConnectionConfig,
SerialConfig,
TerminalSession,
Workspace,
WorkspaceNode,
WorkspaceViewMode,
} from "./models";
import { isPluginHostProtocol, sanitizePluginConnection } from "./pluginConnection";
import { cloneWorkspaceTree, collectSessionIds } from "./workspace";
export const DEFAULT_CLOSED_TAB_HISTORY_LIMIT = 20;
const LOCAL_TERMINAL_HOST_ID = "local-terminal";
/**
* Non-secret, in-memory snapshot of a closed terminal session.
* Never persists to storage and never carries credentials, one-shot snippet
* startup scripts, or live transport reuse handles.
*/
export interface ClosedTerminalSessionSnapshot {
sourceSessionId: string;
hostId: string;
hostLabel: string;
hostname: string;
username: string;
protocol?: TerminalSession["protocol"];
pluginConnection?: PluginConnectionConfig;
port?: number;
moshEnabled?: boolean;
etEnabled?: boolean;
shellType?: TerminalSession["shellType"];
charset?: string;
serialConfig?: SerialConfig;
localShell?: string;
localShellArgs?: string[];
localShellName?: string;
localShellIcon?: string;
localStartDir?: string;
fontSize?: number;
fontSizeOverride?: boolean;
customName?: string;
lastCwd?: string;
requireFreshConnection?: boolean;
ephemeralHost?: boolean;
autoOpenSidePanel?: TerminalSession["autoOpenSidePanel"];
}
export interface ClosedSessionTabEntry {
kind: "session";
/** Original session id used to avoid duplicate pushes for the same close event. */
sourceId: string;
closedAt: number;
session: ClosedTerminalSessionSnapshot;
}
export interface ClosedWorkspaceTabEntry {
kind: "workspace";
/** Original workspace id used to avoid duplicate pushes for the same close event. */
sourceId: string;
closedAt: number;
title: string;
autoTitle?: boolean;
generatedTitle?: boolean;
viewMode?: WorkspaceViewMode;
snippetId?: string;
root: WorkspaceNode;
focusedSessionId?: string;
focusSessionOrder?: string[];
sessions: ClosedTerminalSessionSnapshot[];
}
export type ClosedTabEntry = ClosedSessionTabEntry | ClosedWorkspaceTabEntry;
export type ReopenClosedTabMaterialized =
| {
kind: "session";
tabId: string;
session: TerminalSession;
}
| {
kind: "workspace";
tabId: string;
workspace: Workspace;
sessions: TerminalSession[];
};
const uniqueStrings = (values: readonly string[]): string[] => {
const seen = new Set<string>();
const next: string[] = [];
for (const value of values) {
if (!value || seen.has(value)) continue;
seen.add(value);
next.push(value);
}
return next;
};
const sanitizeProtocol = (
value: TerminalSession["protocol"],
): TerminalSession["protocol"] | undefined => {
if (
value === "ssh"
|| value === "telnet"
|| value === "mosh"
|| value === "et"
|| value === "local"
|| value === "serial"
) {
return value;
}
return typeof value === "string" && isPluginHostProtocol(value) ? value : undefined;
};
const cloneSerialConfig = (config: SerialConfig | undefined): SerialConfig | undefined => (
config ? { ...config } : undefined
);
const pruneAndCloneWorkspaceRoot = (
node: WorkspaceNode,
validSessionIds: ReadonlySet<string>,
): WorkspaceNode | null => {
if (node.type === "pane") {
return validSessionIds.has(node.sessionId)
? { id: node.id, type: "pane", sessionId: node.sessionId }
: null;
}
const keptChildren = node.children
.map((child, originalIndex) => ({
child: pruneAndCloneWorkspaceRoot(child, validSessionIds),
originalIndex,
}))
.filter((item): item is { child: WorkspaceNode; originalIndex: number } => item.child !== null);
if (keptChildren.length === 0) return null;
if (keptChildren.length === 1) return keptChildren[0].child;
const rawSizes = Array.isArray(node.sizes) ? node.sizes : undefined;
const canReuseSizes = rawSizes?.length === node.children.length
&& rawSizes.every((size) => typeof size === "number" && Number.isFinite(size) && size > 0);
const nextSizes = canReuseSizes
? keptChildren.map(({ originalIndex }) => rawSizes[originalIndex])
: keptChildren.map(() => 1 / keptChildren.length);
const total = nextSizes.reduce((sum, size) => sum + size, 0);
return {
id: node.id,
type: "split",
direction: node.direction,
children: keptChildren.map((item) => item.child),
sizes: total > 0
? nextSizes.map((size) => size / total)
: keptChildren.map(() => 1 / keptChildren.length),
};
};
export function createClosedSessionSnapshot(
session: TerminalSession,
options?: { lastCwd?: string },
): ClosedTerminalSessionSnapshot | null {
// Hidden MCP sessions were never tabs. Ephemeral hosts (password deep links,
// unsaved quick-connects, and saved-host overrides built by
// buildSshDeepLinkEphemeralHostFromSaved) have their in-memory Host record
// purged on close, so host-level routing/settings (hostChain, proxyConfig,
// legacyAlgorithms, deviceType, one-time auth) cannot be faithfully
// reconstructed from a TerminalSession snapshot alone. Mirror
// domain/sessionRestore.ts and exclude them.
if (session.hiddenFromTabs || session.ephemeralHost) return null;
const protocol = sanitizeProtocol(session.protocol);
const pluginConnection = sanitizePluginConnection(session.pluginConnection, protocol);
const serialConfig = cloneSerialConfig(session.serialConfig);
const resolvedCwd = options?.lastCwd?.trim() || session.lastCwd?.trim() || undefined;
return {
sourceSessionId: session.id,
hostId: session.hostId,
hostLabel: session.hostLabel,
hostname: session.hostname,
username: session.username,
...(protocol ? { protocol } : {}),
...(pluginConnection ? { pluginConnection } : {}),
...(session.port !== undefined ? { port: session.port } : {}),
...(session.moshEnabled !== undefined ? { moshEnabled: session.moshEnabled } : {}),
...(session.etEnabled !== undefined ? { etEnabled: session.etEnabled } : {}),
...(session.shellType ? { shellType: session.shellType } : {}),
...(session.charset ? { charset: session.charset } : {}),
...(serialConfig ? { serialConfig } : {}),
...(session.localShell !== undefined ? { localShell: session.localShell } : {}),
...(session.localShellArgs ? { localShellArgs: [...session.localShellArgs] } : {}),
...(session.localShellName !== undefined ? { localShellName: session.localShellName } : {}),
...(session.localShellIcon !== undefined ? { localShellIcon: session.localShellIcon } : {}),
...(session.localStartDir ? { localStartDir: session.localStartDir } : {}),
...(session.fontSize !== undefined ? { fontSize: session.fontSize } : {}),
...(session.fontSizeOverride !== undefined ? { fontSizeOverride: session.fontSizeOverride } : {}),
...(session.customName ? { customName: session.customName } : {}),
...(resolvedCwd ? { lastCwd: resolvedCwd } : {}),
...(session.requireFreshConnection === true ? { requireFreshConnection: true } : {}),
...(session.ephemeralHost === true ? { ephemeralHost: true } : {}),
...(session.autoOpenSidePanel ? { autoOpenSidePanel: session.autoOpenSidePanel } : {}),
};
}
export function createClosedSessionEntry(
session: TerminalSession,
options?: { closedAt?: number; lastCwd?: string },
): ClosedSessionTabEntry | null {
const snapshot = createClosedSessionSnapshot(session, { lastCwd: options?.lastCwd });
if (!snapshot) return null;
return {
kind: "session",
sourceId: session.id,
closedAt: options?.closedAt ?? Date.now(),
session: snapshot,
};
}
export function createClosedWorkspaceEntry(
workspace: Workspace,
sessions: readonly TerminalSession[],
options?: {
closedAt?: number;
cwdBySessionId?: ReadonlyMap<string, string>;
},
): ClosedWorkspaceTabEntry | null {
const snapshotsById = new Map<string, ClosedTerminalSessionSnapshot>();
for (const session of sessions) {
if (session.workspaceId !== workspace.id) continue;
const snapshot = createClosedSessionSnapshot(session, {
lastCwd: options?.cwdBySessionId?.get(session.id),
});
if (snapshot) {
snapshotsById.set(session.id, snapshot);
}
}
if (snapshotsById.size === 0) return null;
const validSessionIds = new Set(snapshotsById.keys());
const prunedRoot = pruneAndCloneWorkspaceRoot(workspace.root, validSessionIds);
if (!prunedRoot) return null;
const rootSessionIds = collectSessionIds(prunedRoot);
if (rootSessionIds.length === 0) return null;
const rootSessionIdSet = new Set(rootSessionIds);
const orderedSnapshots = rootSessionIds
.map((id) => snapshotsById.get(id))
.filter((snapshot): snapshot is ClosedTerminalSessionSnapshot => Boolean(snapshot));
const focusedSessionId = workspace.focusedSessionId && rootSessionIdSet.has(workspace.focusedSessionId)
? workspace.focusedSessionId
: rootSessionIds[0];
const focusSessionOrder = workspace.focusSessionOrder
? uniqueStrings(workspace.focusSessionOrder).filter((id) => rootSessionIdSet.has(id))
: undefined;
return {
kind: "workspace",
sourceId: workspace.id,
closedAt: options?.closedAt ?? Date.now(),
title: workspace.title,
...(typeof workspace.autoTitle === "boolean" ? { autoTitle: workspace.autoTitle } : {}),
...(workspace.generatedTitle === true ? { generatedTitle: true } : {}),
...(workspace.viewMode === "split" || workspace.viewMode === "focus"
? { viewMode: workspace.viewMode }
: {}),
...(workspace.snippetId ? { snippetId: workspace.snippetId } : {}),
root: prunedRoot,
focusedSessionId,
...(focusSessionOrder && focusSessionOrder.length > 0 ? { focusSessionOrder } : {}),
sessions: orderedSnapshots,
};
}
/**
* Determine whether a closed session snapshot can still be reopened given the
* current set of vault host ids.
*
* Self-contained sessions (local terminals and quick-connect serial ports) do
* not depend on a vault host record and remain restorable even when
* `availableHostIds` is empty. Ephemeral host sessions are rejected because
* their in-memory Host record (routing, proxy/jump chain, legacy algorithms,
* and one-time credentials) is purged when the tab closes.
*/
export function isClosedSessionSnapshotRestorable(
snapshot: ClosedTerminalSessionSnapshot,
availableHostIds?: ReadonlySet<string>,
): boolean {
if (snapshot.ephemeralHost === true) {
return false;
}
if (!availableHostIds) return true;
if (snapshot.protocol === "local" && snapshot.hostId === LOCAL_TERMINAL_HOST_ID) {
return true;
}
if (
snapshot.protocol === "serial"
&& Boolean(snapshot.serialConfig?.path)
&& snapshot.hostId.startsWith("serial-")
) {
return true;
}
return Boolean(snapshot.hostId) && availableHostIds.has(snapshot.hostId);
}
export function pushClosedTabEntry(
history: readonly ClosedTabEntry[],
entry: ClosedTabEntry | null,
maxEntries: number = DEFAULT_CLOSED_TAB_HISTORY_LIMIT,
): ClosedTabEntry[] {
if (!entry || maxEntries <= 0) return [...history];
// Deduplicate by original session/workspace id so duplicate close callbacks
// before React commits cannot record the same closed tab twice.
if (history.some((existing) => existing.kind === entry.kind && existing.sourceId === entry.sourceId)) {
return [...history];
}
const next = [...history, entry];
return next.length > maxEntries ? next.slice(next.length - maxEntries) : next;
}
const pruneSingleClosedTabEntry = (
entry: ClosedTabEntry,
availableHostIds?: ReadonlySet<string>,
): ClosedTabEntry | null => {
if (entry.kind === "session") {
return isClosedSessionSnapshotRestorable(entry.session, availableHostIds) ? entry : null;
}
const survivingSessions = entry.sessions.filter((snapshot) =>
isClosedSessionSnapshotRestorable(snapshot, availableHostIds),
);
if (survivingSessions.length === 0) return null;
const survivingIds = new Set(survivingSessions.map((snapshot) => snapshot.sourceSessionId));
const prunedRoot = pruneAndCloneWorkspaceRoot(entry.root, survivingIds);
if (!prunedRoot) return null;
const rootSessionIds = collectSessionIds(prunedRoot);
if (rootSessionIds.length === 0) return null;
const rootSessionIdSet = new Set(rootSessionIds);
const orderedSessions = rootSessionIds
.map((id) => survivingSessions.find((snapshot) => snapshot.sourceSessionId === id))
.filter((snapshot): snapshot is ClosedTerminalSessionSnapshot => Boolean(snapshot));
const focusedSessionId = entry.focusedSessionId && rootSessionIdSet.has(entry.focusedSessionId)
? entry.focusedSessionId
: rootSessionIds[0];
const focusSessionOrder = entry.focusSessionOrder
? uniqueStrings(entry.focusSessionOrder).filter((id) => rootSessionIdSet.has(id))
: undefined;
return {
...entry,
root: prunedRoot,
focusedSessionId,
...(focusSessionOrder && focusSessionOrder.length > 0
? { focusSessionOrder }
: { focusSessionOrder: undefined }),
sessions: orderedSessions,
};
};
export function pruneClosedTabEntries(
history: readonly ClosedTabEntry[],
options?: { availableHostIds?: ReadonlySet<string> },
): ClosedTabEntry[] {
const next: ClosedTabEntry[] = [];
for (const entry of history) {
const pruned = pruneSingleClosedTabEntry(entry, options?.availableHostIds);
if (pruned) next.push(pruned);
}
return next;
}
export function popClosedTabEntry(
history: readonly ClosedTabEntry[],
options?: { availableHostIds?: ReadonlySet<string> },
): { entry: ClosedTabEntry | null; nextHistory: ClosedTabEntry[] } {
const remaining = [...history];
while (remaining.length > 0) {
const candidate = remaining.pop() as ClosedTabEntry;
const pruned = pruneSingleClosedTabEntry(candidate, options?.availableHostIds);
if (pruned) {
return {
entry: pruned,
nextHistory: remaining,
};
}
}
return {
entry: null,
nextHistory: [],
};
}
const materializeSessionSnapshot = (
snapshot: ClosedTerminalSessionSnapshot,
params: {
id: string;
workspaceId?: string;
liveHost?: Host;
},
): TerminalSession => {
const { id, workspaceId, liveHost } = params;
const isLocal = snapshot.protocol === "local";
const hostLabel = liveHost?.label || snapshot.hostLabel;
const hostname = liveHost?.hostname || snapshot.hostname;
const username = isLocal
? snapshot.username
: (liveHost?.username ?? snapshot.username);
const localStartDir = isLocal
? (snapshot.lastCwd ?? snapshot.localStartDir)
: snapshot.localStartDir;
return {
id,
hostId: snapshot.hostId,
hostLabel,
hostname,
username,
status: "connecting",
...(workspaceId ? { workspaceId } : {}),
...(snapshot.protocol ? { protocol: snapshot.protocol } : {}),
...(snapshot.pluginConnection
? { pluginConnection: sanitizePluginConnection(snapshot.pluginConnection, snapshot.protocol) }
: {}),
...(snapshot.port !== undefined ? { port: snapshot.port } : {}),
...(snapshot.moshEnabled !== undefined ? { moshEnabled: snapshot.moshEnabled } : {}),
...(snapshot.etEnabled !== undefined ? { etEnabled: snapshot.etEnabled } : {}),
...(snapshot.shellType ? { shellType: snapshot.shellType } : {}),
...(snapshot.charset ? { charset: snapshot.charset } : {}),
...(snapshot.serialConfig ? { serialConfig: cloneSerialConfig(snapshot.serialConfig) } : {}),
...(snapshot.localShell !== undefined ? { localShell: snapshot.localShell } : {}),
...(snapshot.localShellArgs ? { localShellArgs: [...snapshot.localShellArgs] } : {}),
...(snapshot.localShellName !== undefined ? { localShellName: snapshot.localShellName } : {}),
...(snapshot.localShellIcon !== undefined ? { localShellIcon: snapshot.localShellIcon } : {}),
...(localStartDir ? { localStartDir } : {}),
...(snapshot.fontSize !== undefined ? { fontSize: snapshot.fontSize } : {}),
...(snapshot.fontSizeOverride !== undefined ? { fontSizeOverride: snapshot.fontSizeOverride } : {}),
...(snapshot.customName ? { customName: snapshot.customName } : {}),
...(snapshot.requireFreshConnection === true ? { requireFreshConnection: true } : {}),
...(snapshot.ephemeralHost === true ? { ephemeralHost: true } : {}),
...(snapshot.autoOpenSidePanel ? { autoOpenSidePanel: snapshot.autoOpenSidePanel } : {}),
};
};
export function materializeClosedTabEntry(
entry: ClosedTabEntry,
options?: {
hostsById?: ReadonlyMap<string, Host>;
createId?: () => string;
},
): ReopenClosedTabMaterialized | null {
const createId = options?.createId ?? (() => crypto.randomUUID());
if (entry.kind === "session") {
if (entry.session.ephemeralHost === true) return null;
const newSessionId = createId();
const liveHost = options?.hostsById?.get(entry.session.hostId);
const session = materializeSessionSnapshot(entry.session, {
id: newSessionId,
liveHost,
});
return {
kind: "session",
tabId: newSessionId,
session,
};
}
const rootSessionIds = collectSessionIds(entry.root);
const snapshotBySourceId = new Map(
entry.sessions
.filter((snapshot) => snapshot.ephemeralHost !== true)
.map((snapshot) => [snapshot.sourceSessionId, snapshot] as const),
);
const validSourceIds = rootSessionIds.filter((id) => snapshotBySourceId.has(id));
if (validSourceIds.length === 0) return null;
const validRoot = pruneAndCloneWorkspaceRoot(entry.root, new Set(validSourceIds));
if (!validRoot) return null;
const newWorkspaceId = `ws-${createId()}`;
const sessionIdMap = new Map<string, string>(
validSourceIds.map((oldId) => [oldId, createId()]),
);
const nodeIdMap = new Map<string, string>();
const assignNodeIds = (node: WorkspaceNode) => {
nodeIdMap.set(node.id, createId());
if (node.type === "split") {
node.children.forEach(assignNodeIds);
}
};
assignNodeIds(validRoot);
const sessions = validSourceIds.map((oldId) => {
const snapshot = snapshotBySourceId.get(oldId) as ClosedTerminalSessionSnapshot;
const liveHost = snapshot.ephemeralHost ? undefined : options?.hostsById?.get(snapshot.hostId);
return materializeSessionSnapshot(snapshot, {
id: sessionIdMap.get(oldId) as string,
workspaceId: newWorkspaceId,
liveHost,
});
});
const remappedFocusedSessionId = (entry.focusedSessionId && sessionIdMap.get(entry.focusedSessionId))
?? sessionIdMap.get(validSourceIds[0]);
const remappedFocusSessionOrder = entry.focusSessionOrder
? entry.focusSessionOrder
.map((oldId) => sessionIdMap.get(oldId))
.filter((newId): newId is string => Boolean(newId))
: undefined;
const workspace: Workspace = {
id: newWorkspaceId,
title: entry.title,
root: cloneWorkspaceTree(validRoot, sessionIdMap, nodeIdMap),
...(typeof entry.autoTitle === "boolean" ? { autoTitle: entry.autoTitle } : {}),
...(entry.generatedTitle === true ? { generatedTitle: true } : {}),
...(entry.viewMode ? { viewMode: entry.viewMode } : {}),
...(entry.snippetId ? { snippetId: entry.snippetId } : {}),
focusedSessionId: remappedFocusedSessionId,
...(remappedFocusSessionOrder && remappedFocusSessionOrder.length > 0
? { focusSessionOrder: remappedFocusSessionOrder }
: {}),
};
return {
kind: "workspace",
tabId: newWorkspaceId,
workspace,
sessions,
};
}
@@ -0,0 +1,62 @@
import assert from "node:assert/strict";
import test from "node:test";
import { findActiveSystemShortcutConflict } from "./activeKeyBindings.ts";
import { DEFAULT_KEY_BINDINGS, matchesKeyBinding } from "./models/keyBindings.ts";
import { getAppLevelActions } from "../application/state/useGlobalHotkeys.ts";
test("reopen-closed-tab defaults to Cmd+Shift+T on macOS and Ctrl+Shift+T on PC without conflicts", () => {
const binding = DEFAULT_KEY_BINDINGS.find((entry) => entry.id === "reopen-closed-tab");
assert.ok(binding, "reopen-closed-tab must exist in DEFAULT_KEY_BINDINGS");
assert.equal(binding.action, "reopenClosedTab");
assert.equal(binding.category, "tabs");
assert.equal(binding.mac, "⌘ + Shift + T");
assert.equal(binding.pc, "Ctrl + Shift + T");
assert.deepEqual(
DEFAULT_KEY_BINDINGS.filter((entry) => entry.mac === binding.mac).map((entry) => entry.id),
["reopen-closed-tab"],
);
assert.deepEqual(
DEFAULT_KEY_BINDINGS.filter((entry) => entry.pc === binding.pc).map((entry) => entry.id),
["reopen-closed-tab"],
);
assert.equal(
findActiveSystemShortcutConflict("⌘ + Shift + T", "mac", DEFAULT_KEY_BINDINGS)?.id,
"reopen-closed-tab",
);
assert.equal(
findActiveSystemShortcutConflict("Ctrl + Shift + T", "pc", DEFAULT_KEY_BINDINGS)?.id,
"reopen-closed-tab",
);
assert.equal(
matchesKeyBinding(
{ key: "T", code: "KeyT", metaKey: true, ctrlKey: false, altKey: false, shiftKey: true } as KeyboardEvent,
binding.mac,
true,
),
true,
);
assert.equal(
matchesKeyBinding(
{ key: "T", code: "KeyT", metaKey: false, ctrlKey: true, altKey: false, shiftKey: true } as KeyboardEvent,
binding.pc,
false,
),
true,
);
assert.equal(
matchesKeyBinding(
{ key: "t", code: "KeyT", metaKey: true, ctrlKey: false, altKey: false, shiftKey: false } as KeyboardEvent,
binding.mac,
true,
),
false,
);
});
test("reopenClosedTab is registered as an app-level action", () => {
assert.equal(getAppLevelActions().has("reopenClosedTab"), true);
});
+1
View File
@@ -244,6 +244,7 @@ export const DEFAULT_KEY_BINDINGS: KeyBinding[] = [
{ id: 'close-tab', action: 'closeTab', label: 'Close Tab', mac: '⌘ + W', pc: 'Ctrl + W', category: 'tabs' },
{ id: 'close-session', action: 'closeSession', label: 'Close Session Pane', mac: '⌘ + Shift + W', pc: 'Ctrl + Shift + W', category: 'tabs' },
{ id: 'new-tab', action: 'newTab', label: 'New Local Tab', mac: '⌘ + T', pc: 'Ctrl + T', category: 'tabs' },
{ id: 'reopen-closed-tab', action: 'reopenClosedTab', label: 'Reopen Closed Tab', mac: '⌘ + Shift + T', pc: 'Ctrl + Shift + T', category: 'tabs' },
// Terminal Operations
{ id: 'copy', action: 'copy', label: 'Copy from Terminal', mac: '⌘ + C', pc: 'Ctrl + Shift + C', category: 'terminal' },