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(chat-terminal): polish terminal panel with tabs, context menu and WebGL renderer (#17494)

Innei86384c07db65
diff --git a/locales/ar/chat.json b/locales/ar/chat.json
index 58f48ee67fd..397660a22fb 100644
--- a/locales/ar/chat.json
+++ b/locales/ar/chat.json
@@ -1204,6 +1204,7 @@
"taskSchedule.weekdays.tue": "الثلاثاء",
"taskSchedule.weekdays.wed": "الأربعاء",
"terminalPanel.close": "إغلاق لوحة الطرفية",
+ "terminalPanel.closeOtherTabs": "إغلاق المحطات الأخرى",
"terminalPanel.closeTab": "إغلاق الطرفية",
"terminalPanel.createFailed": "فشل بدء جلسة الطرفية",
"terminalPanel.newTab": "طرفية جديدة",
diff --git a/locales/bg-BG/chat.json b/locales/bg-BG/chat.json
index 92db476ef7a..0cf2b0f3ea1 100644
--- a/locales/bg-BG/chat.json
+++ b/locales/bg-BG/chat.json
@@ -1204,6 +1204,7 @@
"taskSchedule.weekdays.tue": "Вто",
"taskSchedule.weekdays.wed": "Сря",
"terminalPanel.close": "Затвори панела на терминала",
+ "terminalPanel.closeOtherTabs": "Затвори другите терминали",
"terminalPanel.closeTab": "Затвори терминала",
"terminalPanel.createFailed": "Неуспешно стартиране на терминалната сесия",
"terminalPanel.newTab": "Нов терминал",
diff --git a/locales/de-DE/chat.json b/locales/de-DE/chat.json
index 132cf4393c8..1a268972758 100644
--- a/locales/de-DE/chat.json
+++ b/locales/de-DE/chat.json
@@ -1204,6 +1204,7 @@
"taskSchedule.weekdays.tue": "Di",
"taskSchedule.weekdays.wed": "Mi",
"terminalPanel.close": "Terminal-Panel schließen",
+ "terminalPanel.closeOtherTabs": "Andere Terminals schließen",
"terminalPanel.closeTab": "Terminal schließen",
"terminalPanel.createFailed": "Fehler beim Starten der Terminal-Sitzung",
"terminalPanel.newTab": "Neues Terminal",
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 239732c5a23..cb84b968986 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1204,6 +1204,7 @@
"taskSchedule.weekdays.tue": "Tue",
"taskSchedule.weekdays.wed": "Wed",
"terminalPanel.close": "Close terminal panel",
+ "terminalPanel.closeOtherTabs": "Close other terminals",
"terminalPanel.closeTab": "Close terminal",
"terminalPanel.createFailed": "Failed to start the terminal session",
"terminalPanel.newTab": "New terminal",
diff --git a/locales/es-ES/chat.json b/locales/es-ES/chat.json
index 13c33310e84..b19986fdfc0 100644
--- a/locales/es-ES/chat.json
+++ b/locales/es-ES/chat.json
@@ -1204,6 +1204,7 @@
"taskSchedule.weekdays.tue": "Mar",
"taskSchedule.weekdays.wed": "Mié",
"terminalPanel.close": "Cerrar panel de terminal",
+ "terminalPanel.closeOtherTabs": "Cerrar otros terminales",
"terminalPanel.closeTab": "Cerrar terminal",
"terminalPanel.createFailed": "No se pudo iniciar la sesión del terminal",
"terminalPanel.newTab": "Nuevo terminal",
diff --git a/locales/fa-IR/chat.json b/locales/fa-IR/chat.json
index 897132ffee4..38cd6383923 100644
--- a/locales/fa-IR/chat.json
+++ b/locales/fa-IR/chat.json
@@ -1204,6 +1204,7 @@
"taskSchedule.weekdays.tue": "سه‌شنبه",
"taskSchedule.weekdays.wed": "چهارشنبه",
"terminalPanel.close": "بستن پنل ترمینال",
+ "terminalPanel.closeOtherTabs": "بستن سایر ترمینال‌ها",
"terminalPanel.closeTab": "بستن ترمینال",
"terminalPanel.createFailed": "شروع جلسه ترمینال ناموفق بود",
"terminalPanel.newTab": "ترمینال جدید",
diff --git a/locales/fr-FR/chat.json b/locales/fr-FR/chat.json
index f9d78ffd044..b8533f31eaf 100644
--- a/locales/fr-FR/chat.json
+++ b/locales/fr-FR/chat.json
@@ -1204,6 +1204,7 @@
"taskSchedule.weekdays.tue": "Mar",
"taskSchedule.weekdays.wed": "Mer",
"terminalPanel.close": "Fermer le panneau du terminal",
+ "terminalPanel.closeOtherTabs": "Fermer les autres terminaux",
"terminalPanel.closeTab": "Fermer le terminal",
"terminalPanel.createFailed": "Échec du démarrage de la session terminal",
"terminalPanel.newTab": "Nouveau terminal",
diff --git a/locales/it-IT/chat.json b/locales/it-IT/chat.json
index bcfb4a59ce0..023ccad01da 100644
--- a/locales/it-IT/chat.json
+++ b/locales/it-IT/chat.json
@@ -1204,6 +1204,7 @@
"taskSchedule.weekdays.tue": "Mar",
"taskSchedule.weekdays.wed": "Mer",
"terminalPanel.close": "Chiudi pannello terminale",
+ "terminalPanel.closeOtherTabs": "Chiudi gli altri terminali",
"terminalPanel.closeTab": "Chiudi terminale",
"terminalPanel.createFailed": "Impossibile avviare la sessione del terminale",
"terminalPanel.newTab": "Nuovo terminale",
diff --git a/locales/ja-JP/chat.json b/locales/ja-JP/chat.json
index eb2317ea973..c0aa869eced 100644
--- a/locales/ja-JP/chat.json
+++ b/locales/ja-JP/chat.json
@@ -1204,6 +1204,7 @@
"taskSchedule.weekdays.tue": "火",
"taskSchedule.weekdays.wed": "水",
"terminalPanel.close": "ターミナルパネルを閉じる",
+ "terminalPanel.closeOtherTabs": "他のターミナルを閉じる",
"terminalPanel.closeTab": "ターミナルを閉じる",
"terminalPanel.createFailed": "ターミナルセッションの開始に失敗しました",
"terminalPanel.newTab": "新しいターミナル",
diff --git a/locales/ko-KR/chat.json b/locales/ko-KR/chat.json
index a8f243bb833..864a51f6707 100644
--- a/locales/ko-KR/chat.json
+++ b/locales/ko-KR/chat.json
@@ -1204,6 +1204,7 @@
"taskSchedule.weekdays.tue": "화",
"taskSchedule.weekdays.wed": "수",
"terminalPanel.close": "터미널 패널 닫기",
+ "terminalPanel.closeOtherTabs": "다른 터미널 닫기",
"terminalPanel.closeTab": "터미널 닫기",
"terminalPanel.createFailed": "터미널 세션을 시작하지 못했습니다",
"terminalPanel.newTab": "새 터미널",
diff --git a/locales/nl-NL/chat.json b/locales/nl-NL/chat.json
index 75ffe9a67ca..3a16e3441a1 100644
--- a/locales/nl-NL/chat.json
+++ b/locales/nl-NL/chat.json
@@ -1204,6 +1204,7 @@
"taskSchedule.weekdays.tue": "Di",
"taskSchedule.weekdays.wed": "Wo",
"terminalPanel.close": "Sluit terminalpaneel",
+ "terminalPanel.closeOtherTabs": "Sluit andere terminals",
"terminalPanel.closeTab": "Sluit terminal",
"terminalPanel.createFailed": "Kan de terminalsessie niet starten",
"terminalPanel.newTab": "Nieuwe terminal",
diff --git a/locales/pl-PL/chat.json b/locales/pl-PL/chat.json
index 63ddfa92b01..2dd5d5f68c2 100644
--- a/locales/pl-PL/chat.json
+++ b/locales/pl-PL/chat.json
@@ -1204,6 +1204,7 @@
"taskSchedule.weekdays.tue": "Wt",
"taskSchedule.weekdays.wed": "Śr",
"terminalPanel.close": "Zamknij panel terminala",
+ "terminalPanel.closeOtherTabs": "Zamknij inne terminale",
"terminalPanel.closeTab": "Zamknij terminal",
"terminalPanel.createFailed": "Nie udało się rozpocząć sesji terminala",
"terminalPanel.newTab": "Nowy terminal",
diff --git a/locales/pt-BR/chat.json b/locales/pt-BR/chat.json
index 9d3b022b9ea..208d491d980 100644
--- a/locales/pt-BR/chat.json
+++ b/locales/pt-BR/chat.json
@@ -1204,6 +1204,7 @@
"taskSchedule.weekdays.tue": "Ter",
"taskSchedule.weekdays.wed": "Qua",
"terminalPanel.close": "Fechar painel do terminal",
+ "terminalPanel.closeOtherTabs": "Fechar outros terminais",
"terminalPanel.closeTab": "Fechar terminal",
"terminalPanel.createFailed": "Falha ao iniciar a sessão do terminal",
"terminalPanel.newTab": "Novo terminal",
diff --git a/locales/ru-RU/chat.json b/locales/ru-RU/chat.json
index 38056f93e9a..4c654cf08e7 100644
--- a/locales/ru-RU/chat.json
+++ b/locales/ru-RU/chat.json
@@ -1204,6 +1204,7 @@
"taskSchedule.weekdays.tue": "Вт",
"taskSchedule.weekdays.wed": "Ср",
"terminalPanel.close": "Закрыть панель терминала",
+ "terminalPanel.closeOtherTabs": "Закрыть другие терминалы",
"terminalPanel.closeTab": "Закрыть терминал",
"terminalPanel.createFailed": "Не удалось запустить сеанс терминала",
"terminalPanel.newTab": "Новый терминал",
diff --git a/locales/tr-TR/chat.json b/locales/tr-TR/chat.json
index 38bcf1f9499..690ba095629 100644
--- a/locales/tr-TR/chat.json
+++ b/locales/tr-TR/chat.json
@@ -1204,6 +1204,7 @@
"taskSchedule.weekdays.tue": "Salı",
"taskSchedule.weekdays.wed": "Çarşamba",
"terminalPanel.close": "Terminal panelini kapat",
+ "terminalPanel.closeOtherTabs": "Diğer terminalleri kapat",
"terminalPanel.closeTab": "Terminali kapat",
"terminalPanel.createFailed": "Terminal oturumunu başlatma başarısız oldu",
"terminalPanel.newTab": "Yeni terminal",
diff --git a/locales/vi-VN/chat.json b/locales/vi-VN/chat.json
index b4425edbe14..9b1f7ebd9e1 100644
--- a/locales/vi-VN/chat.json
+++ b/locales/vi-VN/chat.json
@@ -1204,6 +1204,7 @@
"taskSchedule.weekdays.tue": "Thứ Ba",
"taskSchedule.weekdays.wed": "Thứ Tư",
"terminalPanel.close": "Đóng bảng điều khiển terminal",
+ "terminalPanel.closeOtherTabs": "Đóng các terminal khác",
"terminalPanel.closeTab": "Đóng terminal",
"terminalPanel.createFailed": "Không thể bắt đầu phiên làm việc của terminal",
"terminalPanel.newTab": "Terminal mới",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 612efdaeb16..be932a1952b 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1204,6 +1204,7 @@
"taskSchedule.weekdays.tue": "二",
"taskSchedule.weekdays.wed": "三",
"terminalPanel.close": "关闭终端面板",
+ "terminalPanel.closeOtherTabs": "关闭其他终端",
"terminalPanel.closeTab": "关闭终端",
"terminalPanel.createFailed": "终端会话启动失败",
"terminalPanel.newTab": "新建终端",
diff --git a/locales/zh-TW/chat.json b/locales/zh-TW/chat.json
index 56a097470d5..597543c9b66 100644
--- a/locales/zh-TW/chat.json
+++ b/locales/zh-TW/chat.json
@@ -1204,6 +1204,7 @@
"taskSchedule.weekdays.tue": "週二",
"taskSchedule.weekdays.wed": "週三",
"terminalPanel.close": "關閉終端面板",
+ "terminalPanel.closeOtherTabs": "關閉其他終端機",
"terminalPanel.closeTab": "關閉終端",
"terminalPanel.createFailed": "無法啟動終端機會話",
"terminalPanel.newTab": "新建終端",
diff --git a/package.json b/package.json
index b4c0afe096c..b54ea88d56a 100644
--- a/package.json
+++ b/package.json
@@ -329,6 +329,7 @@
"@vercel/speed-insights": "^1.3.1",
"@virtuoso.dev/masonry": "^1.4.3",
"@xterm/addon-fit": "^0.11.0",
+ "@xterm/addon-webgl": "^0.18.0",
"@xterm/xterm": "^5.5.0",
"@zumer/snapdom": "^1.9.14",
"ahooks": "^3.9.7",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 218e08b3d4c..41f7027e203 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1373,6 +1373,7 @@ export default {
'thread.subagentReadOnlyHint':
'SubAgent conversations are read-only — execution is driven by the parent agent.',
'terminalPanel.close': 'Close terminal panel',
+ 'terminalPanel.closeOtherTabs': 'Close other terminals',
'terminalPanel.closeTab': 'Close terminal',
'terminalPanel.createFailed': 'Failed to start the terminal session',
'terminalPanel.newTab': 'New terminal',
diff --git a/src/features/ChatTerminal/Content.tsx b/src/features/ChatTerminal/Content.tsx
index 14f2598186f..c1748f1f9fa 100644
--- a/src/features/ChatTerminal/Content.tsx
+++ b/src/features/ChatTerminal/Content.tsx
@@ -1,9 +1,17 @@
'use client';
import { ActionIcon, Flexbox, Text } from '@lobehub/ui';
-import { Button } from '@lobehub/ui/base-ui';
-import { createStaticStyles, cx } from 'antd-style';
-import { PlusIcon, SquareTerminalIcon, XIcon } from 'lucide-react';
+import {
+ Button,
+ type ContextMenuItem,
+ ContextMenuTrigger,
+ TabsIndicator,
+ TabsList,
+ TabsRoot,
+ TabsTab,
+} from '@lobehub/ui/base-ui';
+import { createStaticStyles } from 'antd-style';
+import { CopyXIcon, PlusIcon, SquareTerminalIcon, XIcon } from 'lucide-react';
import { memo, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
@@ -26,30 +34,23 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
height: 100%;
background: ${cssVar.colorBgContainer};
`,
- tab: css`
- cursor: pointer;
-
- display: flex;
- gap: 4px;
- align-items: center;
-
- padding-block: 2px;
- padding-inline: 8px 2px;
- border-radius: ${cssVar.borderRadius};
-
- font-size: 12px;
- color: ${cssVar.colorTextSecondary};
-
- &:hover {
- background: ${cssVar.colorFillTertiary};
+ indicator: css`
+ && {
+ border-radius: ${cssVar.borderRadius};
+ background: ${cssVar.colorFillSecondary};
+ box-shadow: none;
}
`,
- tabActive: css`
- color: ${cssVar.colorText};
- background: ${cssVar.colorFillSecondary};
+ tab: css`
+ && {
+ gap: 4px;
+ height: 24px;
+ padding-inline: 8px 4px;
+ font-weight: normal;
+ }
- &:hover {
- background: ${cssVar.colorFillSecondary};
+ &&[data-active] {
+ color: ${cssVar.colorText};
}
`,
tabBar: css`
@@ -58,6 +59,17 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
padding-inline: 8px;
border-block-end: 1px solid ${cssVar.colorBorderSecondary};
`,
+ tabList: css`
+ && {
+ gap: 4px;
+ padding: 0;
+ border-radius: 0;
+ background: none;
+ }
+ `,
+ tabs: css`
+ width: auto;
+ `,
view: css`
overflow: hidden;
flex: 1;
@@ -92,6 +104,7 @@ const Content = memo(() => {
const createError = useChatTerminalStore((s) => s.createErrors[topicKey]);
const createTab = useChatTerminalStore((s) => s.createTab);
const closeTab = useChatTerminalStore((s) => s.closeTab);
+ const closeOtherTabs = useChatTerminalStore((s) => s.closeOtherTabs);
const setActiveTab = useChatTerminalStore((s) => s.setActiveTab);
const activeTab = tabs.find((tab) => tab.id === activeTabId) ?? tabs.at(-1);
@@ -114,28 +127,54 @@ const Content = memo(() => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tabs.length]);
+ const tabMenuItems = (tabId: string): ContextMenuItem[] => [
+ {
+ icon: XIcon,
+ key: 'close',
+ label: t('terminalPanel.closeTab'),
+ onClick: () => closeTab(topicKey, tabId),
+ },
+ {
+ disabled: tabs.length <= 1,
+ icon: CopyXIcon,
+ key: 'closeOthers',
+ label: t('terminalPanel.closeOtherTabs'),
+ onClick: () => closeOtherTabs(topicKey, tabId),
+ },
+ ];
+
return (
<Flexbox className={styles.container}>
<Flexbox horizontal align={'center'} className={styles.tabBar} gap={4}>
- {tabs.map((tab) => (
- <div
- className={cx(styles.tab, tab.id === activeTab?.id && styles.tabActive)}
- key={tab.id}
- onClick={() => setActiveTab(topicKey, tab.id)}
- >
- <SquareTerminalIcon size={12} />
- {tab.title}
- <ActionIcon
- icon={XIcon}
- size={'small'}
- title={t('terminalPanel.closeTab')}
- onClick={(e) => {
- e.stopPropagation();
- closeTab(topicKey, tab.id);
- }}
- />
- </div>
- ))}
+ <TabsRoot
+ className={styles.tabs}
+ size={'small'}
+ value={activeTab?.id ?? null}
+ onValueChange={(next) => {
+ if (typeof next === 'string') setActiveTab(topicKey, next);
+ }}
+ >
+ <TabsList className={styles.tabList}>
+ <TabsIndicator className={styles.indicator} />
+ {tabs.map((tab) => (
+ <ContextMenuTrigger items={() => tabMenuItems(tab.id)} key={tab.id}>
+ <TabsTab className={styles.tab} value={tab.id}>
+ <SquareTerminalIcon size={12} />
+ {tab.title}
+ <ActionIcon
+ icon={XIcon}
+ size={{ blockSize: 20, size: 12 }}
+ title={t('terminalPanel.closeTab')}
+ onClick={(e) => {
+ e.stopPropagation();
+ closeTab(topicKey, tab.id);
+ }}
+ />
+ </TabsTab>
+ </ContextMenuTrigger>
+ ))}
+ </TabsList>
+ </TabsRoot>
<ActionIcon
icon={PlusIcon}
loading={creating}
diff --git a/src/features/ChatTerminal/TerminalView.test.tsx b/src/features/ChatTerminal/TerminalView.test.tsx
index d908035440a..f895b087f26 100644
--- a/src/features/ChatTerminal/TerminalView.test.tsx
+++ b/src/features/ChatTerminal/TerminalView.test.tsx
@@ -26,10 +26,15 @@ vi.mock('@/store/user', () => ({
vi.mock('./theme', () => ({ buildXtermTheme: () => ({ background: '#000' }) }));
vi.mock('./xtermManager', () => ({ xtermManager: manager }));
+let resizeCallback: (() => void) | undefined;
+
beforeAll(() => {
vi.stubGlobal(
'ResizeObserver',
class {
+ constructor(cb: () => void) {
+ resizeCallback = cb;
+ }
disconnect = vi.fn();
observe = vi.fn();
},
@@ -39,6 +44,8 @@ beforeAll(() => {
afterEach(() => {
cleanup();
vi.clearAllMocks();
+ vi.useRealTimers();
+ resizeCallback = undefined;
preference.terminalFontFamily = '"JetBrains Mono"';
});
@@ -57,3 +64,27 @@ describe('TerminalView font family', () => {
expect(manager.applyTheme).toHaveBeenLastCalledWith({ background: '#000' }, 'Application Mono');
});
});
+
+describe('TerminalView refit', () => {
+ it('debounces refit across the open/close animation so the PTY resizes once, not per frame', () => {
+ render(<TerminalView sessionId={'refit'} />);
+
+ // Mount does one immediate fit so the terminal is sized when it appears.
+ expect(manager.fit).toHaveBeenCalledTimes(1);
+
+ vi.useFakeTimers();
+
+ // The height animation fires ResizeObserver on every frame (~16ms apart).
+ for (let i = 0; i < 10; i += 1) {
+ resizeCallback?.();
+ vi.advanceTimersByTime(16);
+ }
+
+ // No PTY resize while the frames are still streaming in.
+ expect(manager.fit).toHaveBeenCalledTimes(1);
+
+ // Exactly one trailing fit once the animation settles.
+ vi.advanceTimersByTime(100);
+ expect(manager.fit).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/src/features/ChatTerminal/TerminalView.tsx b/src/features/ChatTerminal/TerminalView.tsx
index c8f6d9189c6..931156ee1f6 100644
--- a/src/features/ChatTerminal/TerminalView.tsx
+++ b/src/features/ChatTerminal/TerminalView.tsx
@@ -27,10 +27,19 @@ const TerminalView = memo<{ sessionId: string }>(({ sessionId }) => {
xtermManager.fit(sessionId);
xtermManager.focus(sessionId);
- const observer = new ResizeObserver(() => xtermManager.fit(sessionId));
+ // The panel animates its height on open/close, so ResizeObserver fires every
+ // frame. Resizing the PTY per frame floods the shell with SIGWINCH and its
+ // redraws read as a phantom Enter — debounce so the PTY only learns the final
+ // size once the animation settles.
+ let fitTimer: ReturnType<typeof setTimeout> | undefined;
+ const observer = new ResizeObserver(() => {
+ if (fitTimer) clearTimeout(fitTimer);
+ fitTimer = setTimeout(() => xtermManager.fit(sessionId), 100);
+ });
observer.observe(host);
return () => {
+ if (fitTimer) clearTimeout(fitTimer);
observer.disconnect();
xtermManager.detach(sessionId);
};
diff --git a/src/features/ChatTerminal/index.test.tsx b/src/features/ChatTerminal/index.test.tsx
new file mode 100644
index 00000000000..860346e628b
--- /dev/null
+++ b/src/features/ChatTerminal/index.test.tsx
@@ -0,0 +1,81 @@
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useGlobalStore } from '@/store/global';
+import { initialState } from '@/store/global/initialState';
+
+import ChatTerminalPanel from './index';
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal()),
+ isDesktop: true,
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ DraggablePanel: ({ children, expand }: { children?: ReactNode; expand?: boolean }) => (
+ <div data-expand={String(expand)} data-testid="terminal-panel">
+ {children}
+ </div>
+ ),
+}));
+
+vi.mock('./Content', () => ({
+ default: () => <div data-testid="terminal-content" />,
+}));
+
+const setShow = (showTerminalPanel: boolean) =>
+ act(() => {
+ useGlobalStore.setState({
+ status: { ...useGlobalStore.getState().status, showTerminalPanel },
+ });
+ });
+
+beforeEach(() => {
+ useGlobalStore.setState({ status: { ...initialState.status } });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+describe('ChatTerminalPanel', () => {
+ it('drives open/close through controlled expand instead of unmounting', async () => {
+ render(<ChatTerminalPanel />);
+
+ // Closed: the panel is mounted (so it can animate) with expand=false,
+ // rather than returning null as the old implementation did.
+ expect(screen.getByTestId('terminal-panel').dataset.expand).toBe('false');
+
+ setShow(true);
+ await waitFor(() => expect(screen.getByTestId('terminal-panel').dataset.expand).toBe('true'));
+
+ setShow(false);
+ expect(screen.getByTestId('terminal-panel').dataset.expand).toBe('false');
+ });
+
+ it('defers Content until first open, then unmounts it after the collapse animation', async () => {
+ render(<ChatTerminalPanel />);
+
+ expect(screen.queryByTestId('terminal-content')).toBeNull();
+
+ setShow(true);
+ expect(await screen.findByTestId('terminal-content')).toBeDefined();
+
+ vi.useFakeTimers();
+ try {
+ setShow(false);
+ // Kept mounted while the panel collapses.
+ expect(screen.getByTestId('terminal-content')).toBeDefined();
+
+ act(() => {
+ vi.advanceTimersByTime(300);
+ });
+ // Unmounted once hidden, releasing the xterm canvas.
+ expect(screen.queryByTestId('terminal-content')).toBeNull();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/src/features/ChatTerminal/index.tsx b/src/features/ChatTerminal/index.tsx
index 8517df3fb27..3efb741572e 100644
--- a/src/features/ChatTerminal/index.tsx
+++ b/src/features/ChatTerminal/index.tsx
@@ -2,8 +2,8 @@
import { isDesktop } from '@lobechat/const';
import { DraggablePanel } from '@lobehub/ui';
-import { cssVar } from 'antd-style';
-import { lazy, memo, Suspense } from 'react';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { lazy, memo, Suspense, useEffect, useState } from 'react';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
@@ -12,6 +12,21 @@ import { systemStatusSelectors } from '@/store/global/selectors';
// panel is actually opened.
const Content = lazy(() => import('./Content'));
+const styles = createStaticStyles(({ css }) => ({
+ // DraggablePanel hard-codes `transition: all 0.2s` on its inner panel. The
+ // doubled selector out-specifies that without !important, so the component's
+ // own inline `transition: none` still wins while dragging (no lag on resize).
+ smoothResize: css`
+ && {
+ transition: all 0.3s cubic-bezier(0.32, 0.72, 0, 1);
+ }
+ `,
+}));
+
+// Keep in sync with the 0.3s height transition above: the panel must finish
+// collapsing before the terminal is torn down.
+const COLLAPSE_UNMOUNT_DELAY = 300;
+
/**
* Codex-style built-in terminal: a full-width bottom panel on the chat page
* with per-topic tab groups. Desktop-only.
@@ -23,12 +38,28 @@ const ChatTerminalPanel = memo(() => {
s.updateSystemStatus,
]);
- if (!isDesktop || !show) return null;
+ // Open/close is driven by DraggablePanel's controlled `expand` so the panel
+ // animates its height. The terminal is mounted while open and kept through
+ // the collapse animation, then unmounted once hidden to release the xterm
+ // canvas/WebGL context — the PTY and scrollback live in xtermManager, so
+ // reopening re-attaches the same session.
+ const [mounted, setMounted] = useState(show);
+ useEffect(() => {
+ if (show) {
+ setMounted(true);
+ return;
+ }
+ const timer = setTimeout(() => setMounted(false), COLLAPSE_UNMOUNT_DELAY);
+ return () => clearTimeout(timer);
+ }, [show]);
+
+ if (!isDesktop) return null;
return (
<DraggablePanel
- expand
backgroundColor={cssVar.colorBgContainer}
+ classNames={{ content: styles.smoothResize }}
+ expand={show}
expandable={false}
maxHeight={720}
minHeight={160}
@@ -43,9 +74,11 @@ const ChatTerminalPanel = memo(() => {
}
}}
>
- <Suspense fallback={null}>
- <Content />
- </Suspense>
+ {mounted && (
+ <Suspense fallback={null}>
+ <Content />
+ </Suspense>
+ )}
</DraggablePanel>
);
});
diff --git a/src/features/ChatTerminal/store.test.ts b/src/features/ChatTerminal/store.test.ts
new file mode 100644
index 00000000000..8a1bfa50824
--- /dev/null
+++ b/src/features/ChatTerminal/store.test.ts
@@ -0,0 +1,55 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useChatTerminalStore } from './store';
+import { xtermManager } from './xtermManager';
+
+vi.mock('@/services/electron/terminal', () => ({
+ electronTerminalService: { createSession: vi.fn() },
+}));
+
+vi.mock('./xtermManager', () => ({
+ xtermManager: { close: vi.fn(), ensure: vi.fn(), onSessionExit: vi.fn() },
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ useChatTerminalStore.setState({
+ activeTabIds: { topic: 'b' },
+ tabsByTopic: {
+ other: [{ id: 'x', title: 'x' }],
+ topic: [
+ { id: 'a', title: 'a' },
+ { id: 'b', title: 'b' },
+ { id: 'c', title: 'c' },
+ ],
+ },
+ });
+});
+
+describe('closeOtherTabs', () => {
+ it('keeps only the given tab, closes the others, and activates it', () => {
+ useChatTerminalStore.getState().closeOtherTabs('topic', 'a');
+
+ const { activeTabIds, tabsByTopic } = useChatTerminalStore.getState();
+ expect(tabsByTopic.topic).toEqual([{ id: 'a', title: 'a' }]);
+ expect(activeTabIds.topic).toBe('a');
+ expect(xtermManager.close).toHaveBeenCalledTimes(2);
+ expect(xtermManager.close).toHaveBeenCalledWith('b');
+ expect(xtermManager.close).toHaveBeenCalledWith('c');
+ });
+
+ it('leaves other topics untouched', () => {
+ useChatTerminalStore.getState().closeOtherTabs('topic', 'a');
+
+ expect(useChatTerminalStore.getState().tabsByTopic.other).toEqual([{ id: 'x', title: 'x' }]);
+ });
+
+ it('does nothing when the tab id is not in the topic', () => {
+ useChatTerminalStore.getState().closeOtherTabs('topic', 'missing');
+
+ const { activeTabIds, tabsByTopic } = useChatTerminalStore.getState();
+ expect(tabsByTopic.topic).toHaveLength(3);
+ expect(activeTabIds.topic).toBe('b');
+ expect(xtermManager.close).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/ChatTerminal/store.ts b/src/features/ChatTerminal/store.ts
index a9ea4542d1d..be7b8180acc 100644
--- a/src/features/ChatTerminal/store.ts
+++ b/src/features/ChatTerminal/store.ts
@@ -24,6 +24,7 @@ interface ChatTerminalState {
}
interface ChatTerminalActions {
+ closeOtherTabs: (topicKey: string, tabId: string) => void;
closeTab: (topicKey: string, tabId: string) => void;
createTab: (topicKey: string, cwd?: string) => Promise<void>;
setActiveTab: (topicKey: string, tabId: string) => void;
@@ -41,6 +42,18 @@ export const useChatTerminalStore = create<ChatTerminalActions & ChatTerminalSta
(set, get) => ({
activeTabIds: {},
+ closeOtherTabs: (topicKey, tabId) => {
+ const { activeTabIds, tabsByTopic } = get();
+ const tabs = tabsByTopic[topicKey] ?? [];
+ const kept = tabs.find((tab) => tab.id === tabId);
+ if (!kept) return;
+ for (const tab of tabs) if (tab.id !== tabId) xtermManager.close(tab.id);
+ set({
+ activeTabIds: { ...activeTabIds, [topicKey]: tabId },
+ tabsByTopic: { ...tabsByTopic, [topicKey]: [kept] },
+ });
+ },
+
closeTab: (topicKey, tabId) => {
xtermManager.close(tabId);
const { activeTabIds, tabsByTopic } = get();
diff --git a/src/features/ChatTerminal/xtermManager.test.ts b/src/features/ChatTerminal/xtermManager.test.ts
index f69eed3e0b7..32cd2fcf34f 100644
--- a/src/features/ChatTerminal/xtermManager.test.ts
+++ b/src/features/ChatTerminal/xtermManager.test.ts
@@ -2,10 +2,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { xtermManager } from './xtermManager';
-const { fitAddonFit, ipcOn, resizeSession } = vi.hoisted(() => ({
+const { fitAddonFit, ipcOn, resizeSession, webglInstances, webglShouldThrow } = vi.hoisted(() => ({
fitAddonFit: vi.fn(),
ipcOn: vi.fn(),
resizeSession: vi.fn().mockResolvedValue(undefined),
+ webglInstances: [] as { contextLoss: () => void; dispose: ReturnType<typeof vi.fn> }[],
+ webglShouldThrow: { value: false },
}));
vi.mock('@xterm/xterm/css/xterm.css', () => ({}));
@@ -16,6 +18,21 @@ vi.mock('@xterm/addon-fit', () => ({
},
}));
+vi.mock('@xterm/addon-webgl', () => ({
+ WebglAddon: class {
+ contextLoss = () => {};
+ dispose = vi.fn();
+ onContextLoss = (cb: () => void) => {
+ this.contextLoss = cb;
+ };
+
+ constructor() {
+ if (webglShouldThrow.value) throw new Error('WebGL2 unavailable');
+ webglInstances.push(this);
+ }
+ },
+}));
+
vi.mock('@xterm/xterm', () => ({
Terminal: class {
cols = 80;
@@ -41,6 +58,8 @@ vi.mock('debug', () => ({ default: () => vi.fn() }));
describe('xtermManager', () => {
beforeEach(() => {
vi.clearAllMocks();
+ webglInstances.length = 0;
+ webglShouldThrow.value = false;
document.body.replaceChildren();
Object.defineProperty(window, 'electron', {
configurable: true,
@@ -67,4 +86,70 @@ describe('xtermManager', () => {
expect(fitAddonFit).toHaveBeenCalledOnce();
expect(resizeSession).toHaveBeenCalledWith({ cols: 80, id: 'theme_first', rows: 24 });
});
+
+ it('loads the WebGL addon on attach and disposes it on detach', () => {
+ const host = document.createElement('div');
+ document.body.append(host);
+
+ xtermManager.attach('webgl_lifecycle', host);
+ expect(webglInstances).toHaveLength(1);
+ const instance = xtermManager.ensure('webgl_lifecycle');
+ expect(instance.term.loadAddon).toHaveBeenCalledWith(webglInstances[0]);
+ expect(instance.webgl).toBe(webglInstances[0]);
+
+ xtermManager.detach('webgl_lifecycle');
+ expect(webglInstances[0].dispose).toHaveBeenCalledOnce();
+ expect(instance.webgl).toBeUndefined();
+
+ xtermManager.attach('webgl_lifecycle', host);
+ expect(webglInstances).toHaveLength(2);
+ expect(instance.webgl).toBe(webglInstances[1]);
+ });
+
+ it('drops to the DOM renderer on context loss and retries on next attach', () => {
+ const host = document.createElement('div');
+ document.body.append(host);
+ xtermManager.attach('webgl_loss', host);
+ const instance = xtermManager.ensure('webgl_loss');
+
+ webglInstances[0].contextLoss();
+
+ expect(webglInstances[0].dispose).toHaveBeenCalledOnce();
+ expect(instance.webgl).toBeUndefined();
+
+ xtermManager.detach('webgl_loss');
+ xtermManager.attach('webgl_loss', host);
+ expect(webglInstances).toHaveLength(2);
+ expect(instance.webgl).toBe(webglInstances[1]);
+ });
+
+ it('survives a throwing WebGL addon dispose on detach', () => {
+ const host = document.createElement('div');
+ document.body.append(host);
+ xtermManager.attach('webgl_dispose_throw', host);
+ const instance = xtermManager.ensure('webgl_dispose_throw');
+ webglInstances[0].dispose.mockImplementation(() => {
+ throw new TypeError("Cannot read properties of undefined (reading '_isDisposed')");
+ });
+
+ expect(() => xtermManager.detach('webgl_dispose_throw')).not.toThrow();
+ expect(instance.webgl).toBeUndefined();
+ expect(host.contains(instance.container)).toBe(false);
+
+ xtermManager.attach('webgl_dispose_throw', host);
+ expect(instance.webgl).toBe(webglInstances[1]);
+ });
+
+ it('falls back permanently when the WebGL addon fails to initialize', () => {
+ const host = document.createElement('div');
+ document.body.append(host);
+ webglShouldThrow.value = true;
+
+ expect(() => xtermManager.attach('webgl_broken', host)).not.toThrow();
+ expect(xtermManager.ensure('webgl_broken').webgl).toBeUndefined();
+
+ webglShouldThrow.value = false;
+ xtermManager.attach('webgl_after_broken', host);
+ expect(webglInstances).toHaveLength(0);
+ });
});
diff --git a/src/features/ChatTerminal/xtermManager.ts b/src/features/ChatTerminal/xtermManager.ts
index f16ce6a8df1..56d418fa475 100644
--- a/src/features/ChatTerminal/xtermManager.ts
+++ b/src/features/ChatTerminal/xtermManager.ts
@@ -2,6 +2,7 @@ import '@xterm/xterm/css/xterm.css';
import type { TerminalDataPayload, TerminalExitPayload } from '@lobechat/electron-client-ipc';
import { FitAddon } from '@xterm/addon-fit';
+import { WebglAddon } from '@xterm/addon-webgl';
import type { ITheme } from '@xterm/xterm';
import { Terminal } from '@xterm/xterm';
import debug from 'debug';
@@ -15,6 +16,7 @@ interface TermInstance {
fit: FitAddon;
opened: boolean;
term: Terminal;
+ webgl?: WebglAddon;
}
type ExitListener = (sessionId: string, exitCode: number) => void;
@@ -30,6 +32,7 @@ class XtermManager {
private instances = new Map<string, TermInstance>();
private exitListeners = new Set<ExitListener>();
private ipcBound = false;
+ private webglUnavailable = false;
private bindIpc() {
if (this.ipcBound) return;
@@ -87,10 +90,34 @@ class XtermManager {
instance.term.open(instance.container);
instance.opened = true;
}
+ this.enableWebgl(instance);
}
detach(sessionId: string) {
- this.instances.get(sessionId)?.container.remove();
+ const instance = this.instances.get(sessionId);
+ if (!instance) return;
+ // Browsers cap live WebGL contexts (~8-16) and silently evict the oldest,
+ // so only the visible terminal keeps one — hidden tabs fall back to the
+ // (inert) DOM renderer until re-attached.
+ this.disposeWebgl(instance);
+ instance.container.remove();
+ }
+
+ private enableWebgl(instance: TermInstance) {
+ if (this.webglUnavailable || instance.webgl) return;
+ try {
+ const webgl = new WebglAddon();
+ webgl.onContextLoss(() => {
+ // Context reclaimed (OOM / resume from sleep) — drop to the DOM
+ // renderer now; the next attach retries WebGL.
+ if (instance.webgl === webgl) this.disposeWebgl(instance);
+ });
+ instance.term.loadAddon(webgl);
+ instance.webgl = webgl;
+ } catch (error) {
+ this.webglUnavailable = true;
+ log('WebGL renderer unavailable, falling back to DOM: %O', error);
+ }
}
focus(sessionId: string) {
@@ -130,10 +157,25 @@ class XtermManager {
this.disposeInstance(sessionId);
}
+ // Addon dispose reaches into xterm core internals and can throw when the
+ // addon and core versions drift (e.g. addon-webgl 0.19 on xterm 5.5) —
+ // cleanup paths must survive it or unmount breaks.
+ private disposeWebgl(instance: TermInstance) {
+ const { webgl } = instance;
+ if (!webgl) return;
+ instance.webgl = undefined;
+ try {
+ webgl.dispose();
+ } catch (error) {
+ log('webgl addon dispose failed: %O', error);
+ }
+ }
+
private disposeInstance(sessionId: string) {
const instance = this.instances.get(sessionId);
if (!instance) return;
this.instances.delete(sessionId);
+ this.disposeWebgl(instance);
instance.container.remove();
instance.term.dispose();
}