Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(desktop): reopen closed tabs with Cmd/Ctrl+Shift+T and switch tabs with Cmd+1–9 (#23224)

Lobehub Coder57c1ca6a8ce3
diff --git a/apps/desktop/resources/locales/en/menu.json b/apps/desktop/resources/locales/en/menu.json
index 3dd6ab3f124..59da14f8aca 100644
--- a/apps/desktop/resources/locales/en/menu.json
+++ b/apps/desktop/resources/locales/en/menu.json
@@ -52,6 +52,7 @@
"file.newWindow": "New Window",
"file.preferences": "Preferences",
"file.quit": "Quit",
+ "file.reopenClosedTab": "Reopen Closed Tab",
"file.title": "File",
"help.about": "About",
"help.githubRepo": "GitHub Repository",
diff --git a/apps/desktop/resources/locales/zh-CN/menu.json b/apps/desktop/resources/locales/zh-CN/menu.json
index 02f98b2cb6c..57e367d8b88 100644
--- a/apps/desktop/resources/locales/zh-CN/menu.json
+++ b/apps/desktop/resources/locales/zh-CN/menu.json
@@ -54,6 +54,7 @@
"file.newWindow": "新建窗口",
"file.preferences": "设置…",
"file.quit": "退出",
+ "file.reopenClosedTab": "重新打开关闭的标签页",
"file.title": "文件",
"help.about": "关于",
"help.githubRepo": "GitHub 仓库",
diff --git a/apps/desktop/src/main/locales/default/menu.ts b/apps/desktop/src/main/locales/default/menu.ts
index 9d5ffa5fdc4..f035fa848d0 100644
--- a/apps/desktop/src/main/locales/default/menu.ts
+++ b/apps/desktop/src/main/locales/default/menu.ts
@@ -54,6 +54,7 @@ const menu = {
'file.newWindow': 'New Window',
'file.preferences': 'Preferences',
'file.quit': 'Quit',
+ 'file.reopenClosedTab': 'Reopen Closed Tab',
'file.title': 'File',
'help.about': 'About',
'help.githubRepo': 'GitHub Repository',
diff --git a/apps/desktop/src/main/menus/impls/BaseMenuPlatform.test.ts b/apps/desktop/src/main/menus/impls/BaseMenuPlatform.test.ts
index 9bc63e1b636..d7a695c2a9f 100644
--- a/apps/desktop/src/main/menus/impls/BaseMenuPlatform.test.ts
+++ b/apps/desktop/src/main/menus/impls/BaseMenuPlatform.test.ts
@@ -15,6 +15,10 @@ class TestNewWindowMenuPlatform extends BaseMenuPlatform {
triggerNewWindow(targetWindow?: ElectronBrowserWindow | null) {
this.openNewWindow(targetWindow);
}
+
+ triggerReopenClosedTab(targetWindow?: ElectronBrowserWindow | null) {
+ this.reopenClosedTab(targetWindow);
+ }
}
class TestDevToolsMenuPlatform extends BaseMenuPlatform {
buildDevToolsItem(label = 'Developer Tools', accelerator = 'F12') {
@@ -328,4 +332,55 @@ describe('BaseMenuPlatform', () => {
expect(mainWindow.broadcast).toHaveBeenCalledWith('openNewWindow');
});
});
+
+ // Each app-shell window keeps its own closed-tab history, so the reopen must reach the
+ // window the user is working in rather than always the main window.
+ describe('reopenClosedTab', () => {
+ let menuPlatform: TestNewWindowMenuPlatform;
+ let mainWindow: { broadcast: ReturnType<typeof vi.fn>; show: ReturnType<typeof vi.fn> };
+
+ const registerBrowser = (identifier: string, path: string, target: ElectronBrowserWindow) => {
+ const browser = {
+ broadcast: vi.fn(),
+ options: { path },
+ show: vi.fn(),
+ webContents: target.webContents,
+ };
+ mockApp.browserManager.browsers.set(identifier, browser as any);
+ return browser;
+ };
+
+ beforeEach(() => {
+ mainWindow = { broadcast: vi.fn(), show: vi.fn() };
+ vi.mocked(mockApp.browserManager.getMainWindow).mockReturnValue(mainWindow as any);
+ menuPlatform = new TestNewWindowMenuPlatform(mockApp);
+ });
+
+ afterEach(() => {
+ mockApp.browserManager.browsers.clear();
+ });
+
+ it('reopens the tab in the focused workspace window, not the main window', () => {
+ const target = createBrowserWindow({});
+ const workspaceWindow = registerBrowser('workspace_ws1', '/acme', target);
+
+ menuPlatform.triggerReopenClosedTab(target);
+
+ expect(workspaceWindow.broadcast).toHaveBeenCalledWith('reopenClosedTab');
+ expect(mainWindow.broadcast).not.toHaveBeenCalled();
+ expect(mainWindow.show).not.toHaveBeenCalled();
+ });
+
+ it('falls back to showing the main window from a popup or with nothing focused', () => {
+ const target = createBrowserWindow({});
+ const popup = registerBrowser('popup', '/popup/agent/a/t', target);
+
+ menuPlatform.triggerReopenClosedTab(target);
+ menuPlatform.triggerReopenClosedTab(null);
+
+ expect(popup.broadcast).not.toHaveBeenCalled();
+ expect(mainWindow.show).toHaveBeenCalledTimes(2);
+ expect(mainWindow.broadcast).toHaveBeenCalledWith('reopenClosedTab');
+ });
+ });
});
diff --git a/apps/desktop/src/main/menus/impls/BaseMenuPlatform.ts b/apps/desktop/src/main/menus/impls/BaseMenuPlatform.ts
index 2804a4eb4b2..66ac514b3f1 100644
--- a/apps/desktop/src/main/menus/impls/BaseMenuPlatform.ts
+++ b/apps/desktop/src/main/menus/impls/BaseMenuPlatform.ts
@@ -100,10 +100,28 @@ export abstract class BaseMenuPlatform {
/**
* File > New Window: ask the window the user is working in to open its current
- * workspace in a new window. Only full-app windows mount the File-menu bridge,
- * so popups, devtools, or no focused window fall back to the main window.
+ * workspace in a new window.
*/
protected openNewWindow(targetWindow?: BaseWindow | null): void {
+ this.resolveAppShellWindow(targetWindow).browser.broadcast('openNewWindow');
+ }
+
+ /**
+ * File > Reopen Closed Tab: each app-shell window keeps its own closed-tab history,
+ * so the window the user is working in reopens its own tab. Falling back to the main
+ * window also brings it forward, since it may be hidden behind a popup or in the tray.
+ */
+ protected reopenClosedTab(targetWindow?: BaseWindow | null): void {
+ const { browser, isFallback } = this.resolveAppShellWindow(targetWindow);
+ if (isFallback) browser.show();
+ browser.broadcast('reopenClosedTab');
+ }
+
+ /**
+ * The full-app window a File-menu command targets. Only full-app windows mount the
+ * File-menu bridge, so popups, devtools, or no focused window fall back to the main window.
+ */
+ private resolveAppShellWindow(targetWindow?: BaseWindow | null) {
const focused =
targetWindow && 'webContents' in targetWindow
? (targetWindow as BrowserWindow)
@@ -113,11 +131,11 @@ export abstract class BaseMenuPlatform {
(browser) => browser.webContents === focused.webContents,
)
: undefined;
- const isAppShell = focusedBrowser && !NON_APP_SHELL_PATH.test(focusedBrowser.options.path);
- (isAppShell ? focusedBrowser : this.app.browserManager.getMainWindow()).broadcast(
- 'openNewWindow',
- );
+ if (focusedBrowser && !NON_APP_SHELL_PATH.test(focusedBrowser.options.path)) {
+ return { browser: focusedBrowser, isFallback: false };
+ }
+ return { browser: this.app.browserManager.getMainWindow(), isFallback: true };
}
protected closeFocusedTabOrWindow(targetWindow?: BaseWindow | null): void {
diff --git a/apps/desktop/src/main/menus/impls/linux.test.ts b/apps/desktop/src/main/menus/impls/linux.test.ts
index b4a2318abad..58c7f593878 100644
--- a/apps/desktop/src/main/menus/impls/linux.test.ts
+++ b/apps/desktop/src/main/menus/impls/linux.test.ts
@@ -170,6 +170,20 @@ describe('LinuxMenu', () => {
expect(menuLabels).toContain('Window');
expect(menuLabels).toContain('Help');
});
+
+ it('reopens the last closed tab from File > Reopen Closed Tab (Ctrl+Shift+T)', () => {
+ linuxMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const fileMenu = template.find((item: any) => item.label === 'File');
+ const reopenItem = fileMenu.submenu.find((item: any) => item.accelerator === 'Ctrl+Shift+T');
+
+ expect(reopenItem).toBeDefined();
+ reopenItem.click(undefined, null);
+ const mainWindow = (mockApp.browserManager.getMainWindow as any).mock.results.at(-1).value;
+ expect(mainWindow.show).toHaveBeenCalled();
+ expect(mainWindow.broadcast).toHaveBeenCalledWith('reopenClosedTab');
+ });
});
describe('buildContextMenu', () => {
diff --git a/apps/desktop/src/main/menus/impls/linux.ts b/apps/desktop/src/main/menus/impls/linux.ts
index 37935251674..29f2cde8efe 100644
--- a/apps/desktop/src/main/menus/impls/linux.ts
+++ b/apps/desktop/src/main/menus/impls/linux.ts
@@ -84,6 +84,11 @@ export class LinuxMenu extends BaseMenuPlatform implements IMenuPlatform {
click: (_item, targetWindow) => this.openNewWindow(targetWindow),
label: t('file.newWindow'),
},
+ {
+ accelerator: 'Ctrl+Shift+T',
+ click: (_item, targetWindow) => this.reopenClosedTab(targetWindow),
+ label: t('file.reopenClosedTab'),
+ },
{ type: 'separator' },
{
accelerator: 'Alt+Ctrl+A',
diff --git a/apps/desktop/src/main/menus/impls/macOS.test.ts b/apps/desktop/src/main/menus/impls/macOS.test.ts
index 771c3002a4c..f61a630f92e 100644
--- a/apps/desktop/src/main/menus/impls/macOS.test.ts
+++ b/apps/desktop/src/main/menus/impls/macOS.test.ts
@@ -314,6 +314,22 @@ describe('MacOSMenu', () => {
expect(mainWindow.broadcast).toHaveBeenCalledWith('openNewWindow');
});
+ it('reopens the last closed tab from File > Reopen Closed Tab (Shift+Command+T)', () => {
+ macOSMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const fileMenu = template.find((item: any) => item.label === 'File');
+ const reopenItem = fileMenu.submenu.find(
+ (item: any) => item.accelerator === 'Shift+Command+T',
+ );
+
+ expect(reopenItem).toBeDefined();
+ reopenItem.click(undefined, null);
+ const mainWindow = (mockApp.browserManager.getMainWindow as any).mock.results.at(-1).value;
+ expect(mainWindow.show).toHaveBeenCalled();
+ expect(mainWindow.broadcast).toHaveBeenCalledWith('reopenClosedTab');
+ });
+
it('should handle visit website click', async () => {
macOSMenu.buildAndSetAppMenu();
diff --git a/apps/desktop/src/main/menus/impls/macOS.ts b/apps/desktop/src/main/menus/impls/macOS.ts
index 3509916bf41..2010f51d2aa 100644
--- a/apps/desktop/src/main/menus/impls/macOS.ts
+++ b/apps/desktop/src/main/menus/impls/macOS.ts
@@ -142,6 +142,11 @@ export class MacOSMenu extends BaseMenuPlatform implements IMenuPlatform {
click: (_item, targetWindow) => this.openNewWindow(targetWindow),
label: t('file.newWindow'),
},
+ {
+ accelerator: 'Shift+Command+T',
+ click: (_item, targetWindow) => this.reopenClosedTab(targetWindow),
+ label: t('file.reopenClosedTab'),
+ },
{ type: 'separator' },
{
accelerator: 'Alt+Command+A',
diff --git a/apps/desktop/src/main/menus/impls/windows.test.ts b/apps/desktop/src/main/menus/impls/windows.test.ts
index 21bceeb5b80..4c3638b2b32 100644
--- a/apps/desktop/src/main/menus/impls/windows.test.ts
+++ b/apps/desktop/src/main/menus/impls/windows.test.ts
@@ -7,6 +7,9 @@ import { WindowsMenu } from './windows';
// Mock Electron modules
vi.mock('electron', () => ({
+ BrowserWindow: class BrowserWindow {
+ static getFocusedWindow = vi.fn();
+ },
Menu: {
buildFromTemplate: vi.fn((template) => ({ template })),
setApplicationMenu: vi.fn(),
@@ -150,6 +153,20 @@ describe('WindowsMenu', () => {
expect(fileMenu.id).toBe('app-0');
expect(newTab.id).toBe('app-0-1');
});
+
+ it('reopens the last closed tab from File > Reopen Closed Tab (Ctrl+Shift+T)', () => {
+ windowsMenu.buildAndSetAppMenu();
+
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+ const fileMenu = template.find((item: any) => item.label === 'File');
+ const reopenItem = fileMenu.submenu.find((item: any) => item.accelerator === 'Ctrl+Shift+T');
+
+ expect(reopenItem).toBeDefined();
+ reopenItem.click(undefined, null);
+ const mainWindow = (mockApp.browserManager.getMainWindow as any).mock.results.at(-1).value;
+ expect(mainWindow.show).toHaveBeenCalled();
+ expect(mainWindow.broadcast).toHaveBeenCalledWith('reopenClosedTab');
+ });
});
describe('buildContextMenu', () => {
diff --git a/apps/desktop/src/main/menus/impls/windows.ts b/apps/desktop/src/main/menus/impls/windows.ts
index 166c74574c0..b47ebe96549 100644
--- a/apps/desktop/src/main/menus/impls/windows.ts
+++ b/apps/desktop/src/main/menus/impls/windows.ts
@@ -85,6 +85,11 @@ export class WindowsMenu extends BaseMenuPlatform implements IMenuPlatform {
click: (_item, targetWindow) => this.openNewWindow(targetWindow),
label: t('file.newWindow'),
},
+ {
+ accelerator: 'Ctrl+Shift+T',
+ click: (_item, targetWindow) => this.reopenClosedTab(targetWindow),
+ label: t('file.reopenClosedTab'),
+ },
{ type: 'separator' },
{
accelerator: 'Alt+Ctrl+A',
diff --git a/locales/en-US/electron.json b/locales/en-US/electron.json
index 3fe19adcddb..c51b5d4063f 100644
--- a/locales/en-US/electron.json
+++ b/locales/en-US/electron.json
@@ -168,6 +168,7 @@
"tab.openInSplitView": "Open in Split View",
"tab.overflow": "{{count}} more tabs",
"tab.pin": "Pin Tab",
+ "tab.reopenClosedTab": "Reopen Closed Tab",
"tab.resizeSplitView": "Resize Split View",
"tab.running": "Agent is running",
"tab.unpin": "Unpin Tab",
diff --git a/locales/en-US/hotkey.json b/locales/en-US/hotkey.json
index 5671cbf2030..baa9bdd3611 100644
--- a/locales/en-US/hotkey.json
+++ b/locales/en-US/hotkey.json
@@ -43,7 +43,7 @@
"showApp.title": "Show Main Window",
"switchAgent.desc": "Switch between pinned agents in the sidebar by holding Ctrl and pressing numbers 0-9",
"switchAgent.title": "Quick Switch Agent",
- "switchTab.desc": "Jump to a specific tab by its position (1–9) in the Desktop app tab bar",
+ "switchTab.desc": "Jump to a tab by its position (1–8) in the Desktop app tab bar, or to the last tab with 9",
"switchTab.title": "Switch to Tab by Number",
"toggleFavorite.desc": "Add the open page to the Favorites section of the sidebar, or remove it",
"toggleFavorite.title": "Add to / Remove from Favorites",
diff --git a/locales/zh-CN/electron.json b/locales/zh-CN/electron.json
index 947f69d68e3..05c664fb436 100644
--- a/locales/zh-CN/electron.json
+++ b/locales/zh-CN/electron.json
@@ -168,6 +168,7 @@
"tab.openInSplitView": "在右侧分栏打开",
"tab.overflow": "另有 {{count}} 个标签页",
"tab.pin": "固定标签页",
+ "tab.reopenClosedTab": "重新打开关闭的标签页",
"tab.resizeSplitView": "调整分栏宽度",
"tab.running": "助理运行中",
"tab.unpin": "取消固定",
diff --git a/locales/zh-CN/hotkey.json b/locales/zh-CN/hotkey.json
index 5ee57777f33..097c00e2d36 100644
--- a/locales/zh-CN/hotkey.json
+++ b/locales/zh-CN/hotkey.json
@@ -43,7 +43,7 @@
"showApp.title": "显示主窗口",
"switchAgent.desc": "通过按住 Ctrl 加数字 0~9 切换固定在侧边栏的助理",
"switchAgent.title": "快捷切换助理",
- "switchTab.desc": "通过按住 ⌘/Ctrl 加数字 1~9 跳转到对应位置的标签页",
+ "switchTab.desc": "按住 ⌘/Ctrl 加数字 1~8 跳转到对应位置的标签页,加 9 跳转到最后一个标签页",
"switchTab.title": "按编号切换标签页",
"toggleFavorite.desc": "将当前页面加入侧边栏收藏夹,或从中移出",
"toggleFavorite.title": "加入 / 移出收藏夹",
diff --git a/packages/const/src/hotkeys.ts b/packages/const/src/hotkeys.ts
index 25d91483b21..069af8af863 100644
--- a/packages/const/src/hotkeys.ts
+++ b/packages/const/src/hotkeys.ts
@@ -109,7 +109,8 @@ export const HOTKEYS_REGISTRATION: HotkeyRegistration = [
{
group: HotkeyGroupEnum.Essential,
id: HotkeyEnum.SwitchTab,
- keys: combineKeys([KeyEnum.Ctrl, KeyEnum.Number]),
+ // Mod is ⌘ on macOS and Ctrl elsewhere, matching browsers' tab shortcuts.
+ keys: combineKeys([KeyEnum.Mod, KeyEnum.Number]),
nonEditable: true,
scopes: [HotkeyScopeEnum.Global],
},
diff --git a/packages/electron-client-ipc/src/events/navigation.ts b/packages/electron-client-ipc/src/events/navigation.ts
index a87fbd5351e..d8e4859f337 100644
--- a/packages/electron-client-ipc/src/events/navigation.ts
+++ b/packages/electron-client-ipc/src/events/navigation.ts
@@ -63,4 +63,10 @@ export interface NavigationBroadcastEvents {
/** Ask the renderer to open the Recently Viewed surface. */
openRecentlyViewed: () => void;
+
+ /**
+ * Ask renderer to reopen the most recently closed tab (or bulk-closed tabs).
+ * Triggered by Cmd/Ctrl+Shift+T on the main window.
+ */
+ reopenClosedTab: () => void;
}
diff --git a/packages/locales/src/default/electron.ts b/packages/locales/src/default/electron.ts
index 251b38e4a4d..3ab9b364fca 100644
--- a/packages/locales/src/default/electron.ts
+++ b/packages/locales/src/default/electron.ts
@@ -86,6 +86,7 @@ export default {
'tab.openInSplitView': 'Open in Split View',
'tab.overflow': '{{count}} more tabs',
'tab.pin': 'Pin Tab',
+ 'tab.reopenClosedTab': 'Reopen Closed Tab',
'tab.resizeSplitView': 'Resize Split View',
'tab.running': 'Agent is running',
'tab.unpin': 'Unpin Tab',
diff --git a/packages/locales/src/default/hotkey.ts b/packages/locales/src/default/hotkey.ts
index f436f405234..50201f71be2 100644
--- a/packages/locales/src/default/hotkey.ts
+++ b/packages/locales/src/default/hotkey.ts
@@ -45,7 +45,8 @@ export default {
'switchAgent.desc':
'Switch between pinned agents in the sidebar by holding Ctrl and pressing numbers 0-9',
'switchAgent.title': 'Quick Switch Agent',
- 'switchTab.desc': 'Jump to a specific tab by its position (1–9) in the Desktop app tab bar',
+ 'switchTab.desc':
+ 'Jump to a tab by its position (1–8) in the Desktop app tab bar, or to the last tab with 9',
'switchTab.title': 'Switch to Tab by Number',
'openTaskFilter.desc': 'Open the filter menu on the Tasks page',
'openTaskFilter.title': 'Filter Tasks',
diff --git a/src/features/Electron/titlebar/TabBar/TabItem.tsx b/src/features/Electron/titlebar/TabBar/TabItem.tsx
index 5757c73ee17..e0dd7a25c21 100644
--- a/src/features/Electron/titlebar/TabBar/TabItem.tsx
+++ b/src/features/Electron/titlebar/TabBar/TabItem.tsx
@@ -39,6 +39,7 @@ interface TabDragFollow {
}
interface TabItemProps {
+ canReopenClosed: boolean;
drag?: TabDragFollow;
/**
* Where the tab's offset spring starts on the very first render — the strip's previous
@@ -63,6 +64,7 @@ interface TabItemProps {
onDragStart: (id: string, event: React.PointerEvent<HTMLElement>) => void;
onMoveBy: (id: string, delta: -1 | 1) => void;
onOpenInSplitView: (id: string) => void;
+ onReopenClosed: () => void;
onTogglePin: (id: string) => void;
pinnedCount: number;
splitViewEnabled: boolean;
@@ -74,6 +76,7 @@ interface TabItemProps {
const TabItem = memo<TabItemProps>(
({
+ canReopenClosed,
item,
isActive,
isSplitVisible,
@@ -97,6 +100,7 @@ const TabItem = memo<TabItemProps>(
onDragStart,
onMoveBy,
onOpenInSplitView,
+ onReopenClosed,
onTogglePin,
}) => {
const styles = useStyles;
@@ -238,6 +242,7 @@ const TabItem = memo<TabItemProps>(
const contextMenuItems = useCallback(
(): DropdownItem[] =>
buildTabContextMenuItems({
+ canReopenClosed,
id,
index,
inSplitView: isSplitVisible,
@@ -247,6 +252,7 @@ const TabItem = memo<TabItemProps>(
onCloseRight,
onCloseSplitView,
onOpenInSplitView,
+ onReopenClosed,
onTogglePin,
pinned,
pinnedCount,
@@ -269,7 +275,9 @@ const TabItem = memo<TabItemProps>(
onCloseRight,
onCloseSplitView,
onOpenInSplitView,
+ onReopenClosed,
onTogglePin,
+ canReopenClosed,
],
);
diff --git a/src/features/Electron/titlebar/TabBar/__snapshots__/tabContextMenu.test.ts.snap b/src/features/Electron/titlebar/TabBar/__snapshots__/tabContextMenu.test.ts.snap
index 1f0053abef4..c638b79a962 100644
--- a/src/features/Electron/titlebar/TabBar/__snapshots__/tabContextMenu.test.ts.snap
+++ b/src/features/Electron/titlebar/TabBar/__snapshots__/tabContextMenu.test.ts.snap
@@ -38,5 +38,14 @@ exports[`tab context menu ownership > goes native on macOS desktop (plain string
"label": "tab.closeRightTabs",
"type": "normal",
},
+ {
+ "type": "separator",
+ },
+ {
+ "enabled": false,
+ "id": "9",
+ "label": "tab.reopenClosedTab",
+ "type": "normal",
+ },
]
`;
diff --git a/src/features/Electron/titlebar/TabBar/index.tsx b/src/features/Electron/titlebar/TabBar/index.tsx
index 35bc7efe529..cd076d6130e 100644
--- a/src/features/Electron/titlebar/TabBar/index.tsx
+++ b/src/features/Electron/titlebar/TabBar/index.tsx
@@ -24,7 +24,7 @@ import { useStripWidth } from './hooks/useStripWidth';
import { useTabDrag } from './hooks/useTabDrag';
import { TAB_SPRING } from './motion';
import { resolveCloseShortcut } from './resolveCloseShortcut';
-import { resolveNewTabUrl } from './scope';
+import { resolveNewTabUrl, tabScopeKey } from './scope';
import { useStyles } from './styles';
import TabItem from './TabItem';
import {
@@ -59,6 +59,10 @@ const TabBar = () => {
const unpinTab = useElectronStore((s) => s.unpinTab);
const closeSplitView = useElectronStore((s) => s.closeSplitView);
const openTabInSplitView = useElectronStore((s) => s.openTabInSplitView);
+ const reopenClosedTab = useElectronStore((s) => s.reopenClosedTab);
+ const canReopenClosed = useElectronStore(
+ (s) => (s.closedTabBuckets[tabScopeKey(s.activeTabScope)]?.length ?? 0) > 0,
+ );
const tabIds = useMemo(() => tabs.map((tab) => tab.tab.id), [tabs]);
const pinnedCount = useMemo(() => tabs.filter((tab) => tab.tab.pinned).length, [tabs]);
@@ -224,6 +228,8 @@ const TabBar = () => {
handleNewTab(data?.path);
});
+ useWatchBroadcast('reopenClosedTab', reopenClosedTab);
+
const overflowItems = useCallback((): DropdownItem[] => {
const visible = new Set(visibleIndices);
@@ -268,6 +274,7 @@ const TabBar = () => {
return (
<TabItem
+ canReopenClosed={canReopenClosed}
drag={drag.session?.id === placement.id ? dragFollow : undefined}
enterWidth={settleInstantly ? placement.width : 0}
enterX={settleInstantly ? placement.x : previousTotal.current}
@@ -295,6 +302,7 @@ const TabBar = () => {
onDragStart={drag.startDrag}
onMoveBy={handleMoveBy}
onOpenInSplitView={openTabInSplitView}
+ onReopenClosed={reopenClosedTab}
onTogglePin={handleTogglePin}
/>
);
diff --git a/src/features/Electron/titlebar/TabBar/tabContextMenu.test.ts b/src/features/Electron/titlebar/TabBar/tabContextMenu.test.ts
index 79e5814c9ff..a073c5e2f8e 100644
--- a/src/features/Electron/titlebar/TabBar/tabContextMenu.test.ts
+++ b/src/features/Electron/titlebar/TabBar/tabContextMenu.test.ts
@@ -5,8 +5,17 @@ import { toNativeTemplate } from '@/libs/contextMenu/toNativeTemplate';
import { buildTabContextMenuItems } from './tabContextMenu';
-const build = (index: number, totalCount: number, pinned = false, pinnedCount = 0) =>
+const onReopenClosed = vi.fn();
+
+const build = (
+ index: number,
+ totalCount: number,
+ pinned = false,
+ pinnedCount = 0,
+ canReopenClosed = false,
+) =>
buildTabContextMenuItems({
+ canReopenClosed,
id: 'tab-1',
index,
inSplitView: false,
@@ -16,6 +25,7 @@ const build = (index: number, totalCount: number, pinned = false, pinnedCount =
onCloseRight: vi.fn(),
onCloseSplitView: vi.fn(),
onOpenInSplitView: vi.fn(),
+ onReopenClosed,
onTogglePin: vi.fn(),
pinned,
pinnedCount,
@@ -46,7 +56,23 @@ describe('close entries', () => {
it('leaves the whole close group out for a lone tab', () => {
const keys = build(0, 1).map((item) => (item && 'key' in item ? item.key : item?.type));
- expect(keys).toEqual(['togglePin', 'openInSplitView']);
+ expect(keys).toEqual(['togglePin', 'openInSplitView', 'divider', 'reopenClosedTab']);
+ });
+});
+
+describe('reopen closed tab entry', () => {
+ it('is disabled until a tab has been closed', () => {
+ expect(isDisabled(build(1, 3), 'reopenClosedTab')).toBe(true);
+ expect(isDisabled(build(1, 3, false, 0, true), 'reopenClosedTab')).toBe(false);
+ });
+
+ it('stays offered for a lone tab, since a close can leave just one', () => {
+ const items = build(0, 1, false, 0, true);
+ const entry = items.find((item) => !!item && 'key' in item && item.key === 'reopenClosedTab');
+
+ expect(isDisabled(items, 'reopenClosedTab')).toBe(false);
+ (entry as { onClick: () => void }).onClick();
+ expect(onReopenClosed).toHaveBeenCalledTimes(1);
});
});
diff --git a/src/features/Electron/titlebar/TabBar/tabContextMenu.ts b/src/features/Electron/titlebar/TabBar/tabContextMenu.ts
index 073156e049b..4f8b836fceb 100644
--- a/src/features/Electron/titlebar/TabBar/tabContextMenu.ts
+++ b/src/features/Electron/titlebar/TabBar/tabContextMenu.ts
@@ -10,9 +10,11 @@ type TabContextMenuLabelKey =
| 'tab.closeSplitView'
| 'tab.openInSplitView'
| 'tab.pin'
+ | 'tab.reopenClosedTab'
| 'tab.unpin';
interface TabContextMenuParams {
+ canReopenClosed: boolean;
id: string;
index: number;
inSplitView: boolean;
@@ -22,6 +24,7 @@ interface TabContextMenuParams {
onCloseRight: (id: string) => void;
onCloseSplitView: () => void;
onOpenInSplitView: (id: string) => void;
+ onReopenClosed: () => void;
onTogglePin: (id: string) => void;
pinned: boolean;
pinnedCount: number;
@@ -34,6 +37,7 @@ interface TabContextMenuParams {
// reach something. Pinned tabs occupy indices 0..pinnedCount-1, which is what lets the
// reachable counts fall out of the target's index alone.
export const buildTabContextMenuItems = ({
+ canReopenClosed,
id,
index,
inSplitView,
@@ -43,6 +47,7 @@ export const buildTabContextMenuItems = ({
onCloseRight,
onCloseSplitView,
onOpenInSplitView,
+ onReopenClosed,
onTogglePin,
pinned,
pinnedCount,
@@ -69,9 +74,20 @@ export const buildTabContextMenuItems = ({
: null,
];
+ // Undoing a close is about the strip, not this tab, so it stays offered even for a lone tab.
+ const reopenEntries: DropdownItem[] = [
+ { type: 'divider' },
+ {
+ disabled: !canReopenClosed,
+ key: 'reopenClosedTab',
+ label: t('tab.reopenClosedTab'),
+ onClick: onReopenClosed,
+ },
+ ];
+
// A lone tab has nothing to close (see tabClose), so the whole close group is left out
// rather than shown disabled.
- if (!isTabClosable(totalCount)) return tabEntries;
+ if (!isTabClosable(totalCount)) return [...tabEntries, ...reopenEntries];
return [
...tabEntries,
@@ -100,5 +116,6 @@ export const buildTabContextMenuItems = ({
label: t('tab.closeRightTabs'),
onClick: () => onCloseRight(id),
},
+ ...reopenEntries,
];
};
diff --git a/src/hooks/useHotkeys/desktopTabScope.test.ts b/src/hooks/useHotkeys/desktopTabScope.test.ts
index a3f20176395..2b91cad1f81 100644
--- a/src/hooks/useHotkeys/desktopTabScope.test.ts
+++ b/src/hooks/useHotkeys/desktopTabScope.test.ts
@@ -98,13 +98,42 @@ describe('desktop tab shortcuts', () => {
}
});
- it('ignores missing tabs, empty lists and unrelated modifier combinations', () => {
+ it('uses Command, not Control, for the number shortcuts on macOS', () => {
+ const userAgent = vi
+ .spyOn(navigator, 'userAgent', 'get')
+ .mockReturnValue('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)');
+ renderHook(useRegisterDesktopTabHotkeys);
+
+ press('1', 'Digit1', { ctrlKey: true });
+ expect(state.switchTab).not.toHaveBeenCalled();
+
+ press('1', 'Digit1', { metaKey: true });
+ expect(state.switchTab).toHaveBeenLastCalledWith('first');
+
+ userAgent.mockRestore();
+ });
+
+ it('jumps to the last tab with 9, however many tabs are open', () => {
renderHook(useRegisterDesktopTabHotkeys);
+
press('9', 'Digit9', { ctrlKey: true });
+ expect(state.switchTab).toHaveBeenLastCalledWith('third');
+
+ state.tabs = Array.from({ length: 12 }, (_, i) => ({ id: `tab-${i + 1}` }));
+ press('9', 'Digit9', { ctrlKey: true });
+ expect(state.switchTab).toHaveBeenLastCalledWith('tab-12');
+ press('8', 'Digit8', { ctrlKey: true });
+ expect(state.switchTab).toHaveBeenLastCalledWith('tab-8');
+ });
+
+ it('ignores missing tabs, empty lists and unrelated modifier combinations', () => {
+ renderHook(useRegisterDesktopTabHotkeys);
+ press('5', 'Digit5', { ctrlKey: true });
press('1', 'Digit1', { altKey: true });
press('1', 'Digit1', { altKey: true, ctrlKey: true });
press('Tab', 'Tab', { altKey: true });
state.tabs = [];
+ press('9', 'Digit9', { ctrlKey: true });
press('Tab', 'Tab', { ctrlKey: true });
press('Tab', 'Tab', { ctrlKey: true, shiftKey: true });
expect(state.switchTab).not.toHaveBeenCalled();
diff --git a/src/hooks/useHotkeys/desktopTabScope.ts b/src/hooks/useHotkeys/desktopTabScope.ts
index 1fb3ab8363a..d5c129d9e7a 100644
--- a/src/hooks/useHotkeys/desktopTabScope.ts
+++ b/src/hooks/useHotkeys/desktopTabScope.ts
@@ -6,7 +6,7 @@ import { useHotkeys } from 'react-hotkeys-hook';
import { useElectronStore } from '@/store/electron';
/**
- * Ctrl+1–9: jump to the Nth tab.
+ * Cmd/Ctrl+1–8: jump to the Nth tab; Cmd/Ctrl+9: jump to the last tab, as in browsers.
* Ctrl+Tab: cycle to the next tab, wrapping around.
* Ctrl+Shift+Tab: cycle to the previous tab, wrapping around.
*
@@ -23,7 +23,7 @@ export const useRegisterDesktopTabHotkeys = () => {
// Use the physical number key, including keyboard layouts such as AZERTY.
const digit = Number(e.code.replace(/^(Digit|Numpad)/, ''));
const { tabs, switchTab } = useElectronStore.getState();
- const target = tabs[digit - 1];
+ const target = digit === 9 ? tabs.at(-1) : tabs[digit - 1];
if (target) switchTab(target.id);
},
{
diff --git a/src/store/electron/actions/tabPages.reopenClosedTab.test.ts b/src/store/electron/actions/tabPages.reopenClosedTab.test.ts
new file mode 100644
index 00000000000..75d0afd2cac
--- /dev/null
+++ b/src/store/electron/actions/tabPages.reopenClosedTab.test.ts
@@ -0,0 +1,292 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { PERSONAL_TAB_SCOPE, type TabScope } from '@/features/Electron/titlebar/TabBar/scope';
+import { getTabPages } from '@/features/Electron/titlebar/TabBar/storage';
+import { type TabItem } from '@/features/Electron/titlebar/TabBar/types';
+import { useElectronStore } from '@/store/electron';
+import { initialState } from '@/store/electron/initialState';
+
+const tab = (id: string, url: string, patch: Partial<TabItem> = {}): TabItem => ({
+ id,
+ lastVisited: 1,
+ url,
+ ...patch,
+});
+
+const home = tab('home', '/');
+const goal = tab('goal', '/agent/a1/goal/g1', { cached: { title: 'Ship the launch post' } });
+const topic = tab('topic', '/agent/a1?topic=t1');
+const page = tab('page', '/page/p1');
+
+const seed = (
+ tabs: TabItem[],
+ activeTabId: string,
+ activeTabScope: TabScope = PERSONAL_TAB_SCOPE,
+) => {
+ const { result } = renderHook(() => useElectronStore());
+ act(() => {
+ useElectronStore.setState({ activeTabId, activeTabScope, tabs });
+ });
+ return result;
+};
+
+const urls = (tabs: TabItem[]) => tabs.map((item) => item.url);
+
+describe('reopenClosedTab', () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ useElectronStore.setState({
+ ...initialState,
+ activeTabId: null,
+ closedTabBuckets: {},
+ splitView: null,
+ tabs: [],
+ });
+ });
+
+ it('does nothing when no tab was closed', () => {
+ const result = seed([home, goal], 'goal');
+
+ let returned: string | null = 'unset';
+ act(() => {
+ returned = result.current.reopenClosedTab();
+ });
+
+ expect(returned).toBeNull();
+ expect(urls(result.current.tabs)).toEqual(['/', '/agent/a1/goal/g1']);
+ });
+
+ it('restores the closed tab at its old position with its title, and focuses it', () => {
+ const result = seed([home, goal, topic], 'topic');
+
+ act(() => {
+ result.current.removeTab('goal');
+ });
+ expect(urls(result.current.tabs)).toEqual(['/', '/agent/a1?topic=t1']);
+
+ act(() => {
+ result.current.reopenClosedTab();
+ });
+
+ const { activeTabId, tabs } = result.current;
+ expect(urls(tabs)).toEqual(['/', '/agent/a1/goal/g1', '/agent/a1?topic=t1']);
+ expect(tabs[1].cached?.title).toBe('Ship the launch post');
+ expect(activeTabId).toBe(tabs[1].id);
+ expect(getTabPages(PERSONAL_TAB_SCOPE).tabs.map((item) => item.url)).toEqual(urls(tabs));
+ });
+
+ it('reopens tabs in reverse close order, one close at a time', () => {
+ const result = seed([home, goal, topic, page], 'home');
+
+ act(() => {
+ result.current.removeTab('goal');
+ result.current.removeTab('page');
+ });
+
+ act(() => {
+ result.current.reopenClosedTab();
+ });
+ expect(urls(result.current.tabs)).toEqual(['/', '/agent/a1?topic=t1', '/page/p1']);
+
+ act(() => {
+ result.current.reopenClosedTab();
+ });
+ expect(urls(result.current.tabs)).toEqual([
+ '/',
+ '/agent/a1/goal/g1',
+ '/agent/a1?topic=t1',
+ '/page/p1',
+ ]);
+
+ let returned: string | null = 'unset';
+ act(() => {
+ returned = result.current.reopenClosedTab();
+ });
+ expect(returned).toBeNull();
+ });
+
+ // addNewTab deliberately allows two tabs on the same page, so one bulk close can take
+ // both; a tab restored earlier in the same reopen must not count as "already open".
+ it('counts an open tab on that page once, restoring the other copy', () => {
+ const secondHome = tab('home-2', '/');
+ const result = seed([home, secondHome, goal], 'goal');
+
+ act(() => {
+ result.current.closeOtherTabs('goal');
+ });
+ act(() => {
+ result.current.addNewTab('/');
+ });
+ expect(urls(result.current.tabs)).toEqual(['/agent/a1/goal/g1', '/']);
+
+ act(() => {
+ result.current.reopenClosedTab();
+ });
+
+ expect(urls(result.current.tabs).filter((url) => url === '/')).toHaveLength(2);
+ expect(result.current.tabs).toHaveLength(3);
+ });
+
+ it('brings back every tab of a bulk close, even two on the same page', () => {
+ const secondHome = tab('home-2', '/');
+ const result = seed([home, secondHome, goal], 'goal');
+
+ act(() => {
+ result.current.closeOtherTabs('goal');
+ });
+ expect(urls(result.current.tabs)).toEqual(['/agent/a1/goal/g1']);
+
+ act(() => {
+ result.current.reopenClosedTab();
+ });
+
+ expect(urls(result.current.tabs)).toEqual(['/', '/', '/agent/a1/goal/g1']);
+ });
+
+ it('brings back every tab a bulk close took, focusing the tab that was active', () => {
+ const result = seed([home, goal, topic, page], 'page');
+
+ act(() => {
+ result.current.closeOtherTabs('topic');
+ });
+ expect(urls(result.current.tabs)).toEqual(['/agent/a1?topic=t1']);
+
+ act(() => {
+ result.current.reopenClosedTab();
+ });
+
+ const { activeTabId, tabs } = result.current;
+ expect(urls(tabs)).toEqual(['/', '/agent/a1/goal/g1', '/agent/a1?topic=t1', '/page/p1']);
+ expect(tabs.find((item) => item.id === activeTabId)?.url).toBe('/page/p1');
+ });
+
+ it('keeps a reopened pinned tab inside the pinned run', () => {
+ const pinnedGoal = { ...goal, pinned: true };
+ const result = seed([pinnedGoal, home, topic], 'home');
+
+ act(() => {
+ result.current.removeTab('goal');
+ });
+ act(() => {
+ result.current.reopenClosedTab();
+ });
+
+ const { tabs } = result.current;
+ expect(urls(tabs)).toEqual(['/agent/a1/goal/g1', '/', '/agent/a1?topic=t1']);
+ expect(tabs[0].pinned).toBe(true);
+ });
+
+ it('switches to the page instead of duplicating it when it is already open again', () => {
+ const result = seed([home, goal], 'home');
+
+ act(() => {
+ result.current.removeTab('goal');
+ result.current.addTab('/agent/a1/goal/g1', undefined, false);
+ });
+ const reopenedId = result.current.tabs[1].id;
+
+ act(() => {
+ result.current.reopenClosedTab();
+ });
+
+ expect(urls(result.current.tabs)).toEqual(['/', '/agent/a1/goal/g1']);
+ expect(result.current.activeTabId).toBe(reopenedId);
+ });
+
+ it('does not record the copy a self-split made', () => {
+ const result = seed([home, goal], 'goal');
+
+ let copyId: string | null = null;
+ act(() => {
+ copyId = result.current.openTabInSplitView('goal');
+ });
+ act(() => {
+ result.current.removeTab(copyId!);
+ });
+
+ expect(result.current.closedTabBuckets).toEqual({});
+ });
+
+ it('does not record a lone home tab replaced by a fresh home tab', () => {
+ const result = seed([home], 'home');
+
+ act(() => {
+ result.current.removeTab('home');
+ });
+
+ expect(result.current.closedTabBuckets).toEqual({});
+ });
+
+ // Closing the last tab leaves a generated home tab so TabHost has something to render;
+ // undoing that close should not leave that placeholder behind as an extra tab.
+ it('replaces the untouched home tab that closing the last tab left behind', () => {
+ const result = seed([goal], 'goal');
+
+ act(() => {
+ result.current.removeTab('goal');
+ });
+ expect(urls(result.current.tabs)).toEqual(['/']);
+
+ act(() => {
+ result.current.reopenClosedTab();
+ });
+
+ const { activeTabId, tabs } = result.current;
+ expect(urls(tabs)).toEqual(['/agent/a1/goal/g1']);
+ expect(activeTabId).toBe(tabs[0].id);
+ });
+
+ it('keeps that home tab once the user navigated it', () => {
+ const result = seed([goal], 'goal');
+
+ act(() => {
+ result.current.removeTab('goal');
+ });
+ act(() => {
+ result.current.updateTab(result.current.tabs[0].id, '/page/p1');
+ });
+ act(() => {
+ result.current.reopenClosedTab();
+ });
+
+ expect(urls(result.current.tabs)).toEqual(['/agent/a1/goal/g1', '/page/p1']);
+ });
+
+ it('keeps that home tab once the user opened another tab beside it', () => {
+ const result = seed([goal], 'goal');
+
+ act(() => {
+ result.current.removeTab('goal');
+ });
+ act(() => {
+ result.current.addTab('/page/p1');
+ });
+ act(() => {
+ result.current.reopenClosedTab();
+ });
+
+ expect(urls(result.current.tabs)).toEqual(['/agent/a1/goal/g1', '/', '/page/p1']);
+ });
+
+ it('keeps closed tabs per scope', () => {
+ const result = seed([home, goal], 'goal');
+
+ act(() => {
+ result.current.removeTab('goal');
+ result.current.loadTabs('/acme');
+ });
+
+ let returned: string | null = 'unset';
+ act(() => {
+ returned = result.current.reopenClosedTab();
+ });
+ expect(returned).toBeNull();
+
+ act(() => {
+ result.current.loadTabs('/');
+ result.current.reopenClosedTab();
+ });
+ expect(urls(result.current.tabs)).toContain('/agent/a1/goal/g1');
+ });
+});
diff --git a/src/store/electron/actions/tabPages.ts b/src/store/electron/actions/tabPages.ts
index bb9f7338eb4..7f8c25cd098 100644
--- a/src/store/electron/actions/tabPages.ts
+++ b/src/store/electron/actions/tabPages.ts
@@ -20,11 +20,33 @@ import { type ElectronStore } from '../store';
const generateTabId = (): string => `tab_${nanoid(8)}`;
+const CLOSED_TAB_GROUPS_LIMIT = 20;
+
// ======== Types ======== //
+/** A tab as it was when closed, enough to put it back where it stood. */
+export interface ClosedTab {
+ cached?: DynamicRouteMeta;
+ /**
+ * Set when this was the last tab: the generated home tab that replaced it. Reopening
+ * takes that placeholder's place while it is still the only, untouched tab.
+ */
+ fallbackHomeTabId?: string;
+ index: number;
+ pinned?: boolean;
+ url: string;
+ wasActive: boolean;
+}
+
export interface TabPagesState {
activeTabId: string | null;
activeTabScope: TabScope;
+ /**
+ * Tabs closed this session, per scope, newest last. One close — a single tab or a bulk
+ * "close others / left / right" — is one group, and one reopen brings the group back.
+ * Memory only: the open tabs themselves already survive a restart.
+ */
+ closedTabBuckets: Record<string, ClosedTab[][]>;
splitView: SplitViewState | null;
tabs: TabItem[];
}
@@ -52,6 +74,7 @@ export interface SplitViewState {
export const tabPagesInitialState: TabPagesState = {
activeTabScope: PERSONAL_TAB_SCOPE,
activeTabId: null,
+ closedTabBuckets: {},
splitView: null,
tabs: [],
};
@@ -239,6 +262,9 @@ export class TabPagesActionImpl {
if (index < 0) return null;
const newTabs = tabs.filter((t) => t.id !== id);
+ const homeUrl = tabScopeHomeUrl(activeTabScope);
+ // A lone home tab only makes way for an identical fresh one, so there is nothing to undo.
+ const closed = newTabs.length === 0 && isSameTabTarget(tabs[index], homeUrl) ? [] : [index];
// With no tab left TabHost has nothing to render, so the last close lands on a fresh
// home tab instead — a new id, because a live router is never re-pointed at a new url.
@@ -246,9 +272,18 @@ export class TabPagesActionImpl {
const home: TabItem = {
id: generateTabId(),
lastVisited: Date.now(),
- url: tabScopeHomeUrl(activeTabScope),
+ url: homeUrl,
};
- this.#set({ activeTabId: home.id, splitView: null, tabs: [home] }, false, 'removeTab');
+ this.#set(
+ {
+ activeTabId: home.id,
+ closedTabBuckets: this.#rememberClosed(closed, home.id),
+ splitView: null,
+ tabs: [home],
+ },
+ false,
+ 'removeTab',
+ );
this.#persist();
return home.id;
}
@@ -268,6 +303,7 @@ export class TabPagesActionImpl {
this.#set(
{
activeTabId: newActiveId,
+ closedTabBuckets: this.#rememberClosed(closed),
splitView: reconciled.splitView,
tabs: this.#touch(reconciled.tabs, newActiveId),
},
@@ -302,6 +338,69 @@ export class TabPagesActionImpl {
this.#closeExcept((_, i) => i <= index, id, 'closeRightTabs');
};
+ /**
+ * Undo the latest close in the active scope (Cmd/Ctrl+Shift+T): its tabs return to their
+ * old positions with their cached titles, and the one that was focused takes focus — or
+ * the last one restored. A page that is open again is switched to, not duplicated. Only
+ * the url comes back; the closed tab's router, history and in-page state are gone.
+ */
+ reopenClosedTab = (): string | null => {
+ const { activeTabScope, closedTabBuckets, tabs } = this.#get();
+ const key = tabScopeKey(activeTabScope);
+ const groups = closedTabBuckets[key] ?? [];
+ const group = groups.at(-1);
+ if (!group) return null;
+
+ // Undoing a last-tab close drops the home tab generated for it, unless the user has
+ // since navigated it or opened another tab beside it.
+ const fallbackHomeTabId = group.find((closed) => closed.fallbackHomeTabId)?.fallbackHomeTabId;
+ const isUntouchedFallback =
+ !!fallbackHomeTabId &&
+ tabs.length === 1 &&
+ tabs[0].id === fallbackHomeTabId &&
+ isSameTabTarget(tabs[0], tabScopeHomeUrl(activeTabScope));
+
+ // Only tabs open before this reopen count as "already open", and each stands in for one
+ // closed tab: a bulk close can take two tabs on the same page (addNewTab allows that),
+ // and as many tabs on that page as were closed must be open afterwards.
+ const openBefore = isUntouchedFallback ? [] : tabs;
+ const matched = new Set<string>();
+ let nextTabs = openBefore;
+ let focusId = '';
+ const hadActive = group.some((closed) => closed.wasActive);
+ const now = Date.now();
+
+ for (const closed of group.toSorted((a, b) => a.index - b.index)) {
+ const existing = openBefore.find((t) => !matched.has(t.id) && isSameTabTarget(t, closed.url));
+ if (existing) matched.add(existing.id);
+ const id = existing?.id ?? generateTabId();
+
+ if (!existing) {
+ const restored: TabItem = { cached: closed.cached, id, lastVisited: now, url: closed.url };
+ if (closed.pinned) restored.pinned = true;
+
+ // Array order must equal render order (see #setPinned), so the old index is
+ // clamped into the tab's own run.
+ const pinnedCount = nextTabs.filter((t) => t.pinned).length;
+ const position = closed.pinned
+ ? Math.min(closed.index, pinnedCount)
+ : Math.min(Math.max(closed.index, pinnedCount), nextTabs.length);
+ nextTabs = [...nextTabs.slice(0, position), restored, ...nextTabs.slice(position)];
+ }
+
+ if (closed.wasActive || !hadActive) focusId = id;
+ }
+
+ this.#set(
+ { closedTabBuckets: { ...closedTabBuckets, [key]: groups.slice(0, -1) }, tabs: nextTabs },
+ false,
+ 'reopenClosedTab',
+ );
+ // activateTab owns split-pane replacement, the keep-alive touch and persistence.
+ this.activateTab(focusId);
+ return focusId;
+ };
+
moveTab = (id: string, toIndex: number, pinned: boolean): void => {
const { tabs } = this.#get();
const index = tabs.findIndex((t) => t.id === id);
@@ -413,7 +512,8 @@ export class TabPagesActionImpl {
action: string,
): void => {
const { tabs, activeTabId } = this.#get();
- const newTabs = tabs.filter((tab, index) => tab.pinned || keep(tab, index));
+ const kept = tabs.map((tab, index) => !!tab.pinned || keep(tab, index));
+ const newTabs = tabs.filter((_, index) => kept[index]);
if (newTabs.length === tabs.length) return;
const preferredActiveId = newTabs.some((t) => t.id === activeTabId) ? activeTabId : targetId;
@@ -422,6 +522,9 @@ export class TabPagesActionImpl {
this.#set(
{
activeTabId: reconciled.activeTabId,
+ closedTabBuckets: this.#rememberClosed(
+ kept.flatMap((isKept, index) => (isKept ? [] : [index])),
+ ),
splitView: reconciled.splitView,
tabs: this.#touch(reconciled.tabs, reconciled.activeTabId),
},
@@ -452,6 +555,34 @@ export class TabPagesActionImpl {
this.#persist();
};
+ // Snapshot the tabs at `indices` (positions in the current list) as one closed group of
+ // the active scope. The copy a self-split made only mirrors its source, so it is skipped.
+ #rememberClosed = (
+ indices: number[],
+ fallbackHomeTabId?: string,
+ ): Record<string, ClosedTab[][]> => {
+ const { activeTabId, activeTabScope, closedTabBuckets, splitView, tabs } = this.#get();
+ const group: ClosedTab[] = indices
+ .filter((index) => tabs[index] && tabs[index].id !== splitView?.duplicatedTabId)
+ .map((index) => {
+ const tab = tabs[index];
+ const closed: ClosedTab = {
+ index,
+ url: tab.url,
+ wasActive: tab.id === activeTabId,
+ };
+ if (tab.cached) closed.cached = tab.cached;
+ if (tab.pinned) closed.pinned = true;
+ if (fallbackHomeTabId) closed.fallbackHomeTabId = fallbackHomeTabId;
+ return closed;
+ });
+ if (group.length === 0) return closedTabBuckets;
+
+ const key = tabScopeKey(activeTabScope);
+ const groups = [...(closedTabBuckets[key] ?? []), group].slice(-CLOSED_TAB_GROUPS_LIMIT);
+ return { ...closedTabBuckets, [key]: groups };
+ };
+
// Every path that makes a tab active must refresh its `lastVisited`: TabHost
// ranks keep-alive routers by that timestamp, so a tab activated without a
// navigation would stay at its stale recency and get its router disposed (and