mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-26 19:07:17 +00:00
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:
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');
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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': '將選區貼上到終端',
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user