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(terminal): clickable links, split panes and Ghostty command-key bindings (#18500)

Innei93b20ef2b6c6
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 060946f9892..ba6c680b84b 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -1584,9 +1584,11 @@
"taskSchedule.weekdays.wed": "Wed",
"terminalPanel.close": "Close terminal panel",
"terminalPanel.closeOtherTabs": "Close other terminals",
+ "terminalPanel.closePane": "Close pane",
"terminalPanel.closeTab": "Close terminal",
"terminalPanel.createFailed": "Failed to start the terminal session",
"terminalPanel.newTab": "New terminal",
+ "terminalPanel.split": "Split terminal",
"terminalPanel.title": "Terminal",
"textSelection.addToConversation": "Add to conversation",
"textSelection.added": "Added to conversation context",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 64156bd03a1..d19a11eb338 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -1584,9 +1584,11 @@
"taskSchedule.weekdays.wed": "δΈ‰",
"terminalPanel.close": "ε…³ι—­η»ˆη«―ι’ζΏ",
"terminalPanel.closeOtherTabs": "ε…³ι—­ε…Άδ»–η»ˆη«―",
+ "terminalPanel.closePane": "ε…³ι—­εˆ†ζ ",
"terminalPanel.closeTab": "ε…³ι—­η»ˆη«―",
"terminalPanel.createFailed": "终端会话启动倱θ΄₯",
"terminalPanel.newTab": "ζ–°ε»Ίη»ˆη«―",
+ "terminalPanel.split": "ζ‹†εˆ†η»ˆη«―",
"terminalPanel.title": "终端",
"textSelection.addToConversation": "添加到对话",
"textSelection.added": "ε·²ζ·»εŠ εˆ°ε―Ήθ―δΈŠδΈ‹ζ–‡",
diff --git a/package.json b/package.json
index 91c548bc0c1..bbb5ec958c4 100644
--- a/package.json
+++ b/package.json
@@ -333,6 +333,7 @@
"@vercel/speed-insights": "^1.3.1",
"@virtuoso.dev/masonry": "^1.4.3",
"@xterm/addon-fit": "^0.11.0",
+ "@xterm/addon-web-links": "^0.12.0",
"@xterm/addon-webgl": "^0.18.0",
"@xterm/xterm": "^5.5.0",
"@zumer/snapdom": "^1.9.14",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index c06a7d40747..61d62a36366 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1857,9 +1857,11 @@ export default {
'SubAgent conversations are read-only β€” execution is driven by the parent agent.',
'terminalPanel.close': 'Close terminal panel',
'terminalPanel.closeOtherTabs': 'Close other terminals',
+ 'terminalPanel.closePane': 'Close pane',
'terminalPanel.closeTab': 'Close terminal',
'terminalPanel.createFailed': 'Failed to start the terminal session',
'terminalPanel.newTab': 'New terminal',
+ 'terminalPanel.split': 'Split terminal',
'terminalPanel.title': 'Terminal',
'thread.threadMessageCount': '{{messageCount}} messages',
'thread.title': 'Subtopic',
diff --git a/src/features/ChatTerminal/Content.tsx b/src/features/ChatTerminal/Content.tsx
index c1748f1f9fa..6878d170273 100644
--- a/src/features/ChatTerminal/Content.tsx
+++ b/src/features/ChatTerminal/Content.tsx
@@ -11,7 +11,13 @@ import {
TabsTab,
} from '@lobehub/ui/base-ui';
import { createStaticStyles } from 'antd-style';
-import { CopyXIcon, PlusIcon, SquareTerminalIcon, XIcon } from 'lucide-react';
+import {
+ CopyXIcon,
+ PlusIcon,
+ SquareSplitHorizontalIcon,
+ SquareTerminalIcon,
+ XIcon,
+} from 'lucide-react';
import { memo, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
@@ -22,9 +28,9 @@ import { topicSelectors } from '@/store/chat/selectors';
import { useElectronStore } from '@/store/electron';
import { useGlobalStore } from '@/store/global';
+import SplitView from './SplitView';
import type { TerminalTab } from './store';
import { useChatTerminalStore } from './store';
-import TerminalView from './TerminalView';
const EMPTY_TABS: TerminalTab[] = [];
@@ -106,6 +112,10 @@ const Content = memo(() => {
const closeTab = useChatTerminalStore((s) => s.closeTab);
const closeOtherTabs = useChatTerminalStore((s) => s.closeOtherTabs);
const setActiveTab = useChatTerminalStore((s) => s.setActiveTab);
+ const splitPane = useChatTerminalStore((s) => s.splitPane);
+ const closePane = useChatTerminalStore((s) => s.closePane);
+ const setActivePane = useChatTerminalStore((s) => s.setActivePane);
+ const setPaneFlex = useChatTerminalStore((s) => s.setPaneFlex);
const activeTab = tabs.find((tab) => tab.id === activeTabId) ?? tabs.at(-1);
@@ -183,6 +193,13 @@ const Content = memo(() => {
onClick={() => createTab(topicKey, cwd)}
/>
<Flexbox flex={1} />
+ <ActionIcon
+ disabled={!activeTab || creating}
+ icon={SquareSplitHorizontalIcon}
+ size={'small'}
+ title={t('terminalPanel.split')}
+ onClick={() => activeTab && splitPane(topicKey, activeTab.id, cwd)}
+ />
<ActionIcon
icon={XIcon}
size={'small'}
@@ -192,7 +209,13 @@ const Content = memo(() => {
</Flexbox>
<div className={styles.view}>
{activeTab ? (
- <TerminalView sessionId={activeTab.id} />
+ <SplitView
+ activePaneId={activeTab.activePaneId}
+ panes={activeTab.panes}
+ onActivatePane={(paneId) => setActivePane(topicKey, activeTab.id, paneId)}
+ onClosePane={(paneId) => closePane(topicKey, paneId)}
+ onResize={(flex) => setPaneFlex(topicKey, activeTab.id, flex)}
+ />
) : createError ? (
<Flexbox align={'center'} flex={1} gap={8} height={'100%'} justify={'center'}>
<Text type={'secondary'}>{t('terminalPanel.createFailed')}</Text>
diff --git a/src/features/ChatTerminal/SplitView.tsx b/src/features/ChatTerminal/SplitView.tsx
new file mode 100644
index 00000000000..d7bdc6ecdaf
--- /dev/null
+++ b/src/features/ChatTerminal/SplitView.tsx
@@ -0,0 +1,152 @@
+'use client';
+
+import { ActionIcon } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { XIcon } from 'lucide-react';
+import { Fragment, type PointerEvent as ReactPointerEvent, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { DIVIDER_WIDTH, paneTrackWidth, resizePanes } from './paneLayout';
+import type { TerminalPane } from './store';
+import TerminalView from './TerminalView';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ close: css`
+ position: absolute;
+ z-index: 1;
+ inset-block-start: 2px;
+ inset-inline-end: 2px;
+
+ opacity: 0;
+
+ transition: opacity 0.15s;
+ `,
+ divider: css`
+ cursor: col-resize;
+ position: relative;
+ flex: none;
+ inline-size: ${DIVIDER_WIDTH}px;
+
+ &::after {
+ content: '';
+
+ position: absolute;
+ inset-block: 0;
+ inset-inline-start: ${(DIVIDER_WIDTH - 1) / 2}px;
+
+ inline-size: 1px;
+
+ background: ${cssVar.colorBorderSecondary};
+
+ transition: background 0.15s;
+ }
+
+ &:hover::after {
+ background: ${cssVar.colorPrimary};
+ }
+ `,
+ pane: css`
+ position: relative;
+ overflow: hidden;
+ min-inline-size: 0;
+ transition: opacity 0.15s;
+
+ /* Set only while split, so a lone pane is never dimmed. */
+ &[data-inactive-pane] {
+ opacity: 0.7;
+ }
+
+ &:hover [data-pane-close],
+ &:focus-within [data-pane-close] {
+ opacity: 1;
+ }
+ `,
+ root: css`
+ display: flex;
+ block-size: 100%;
+ `,
+}));
+
+interface SplitViewProps {
+ activePaneId: string;
+ onActivatePane: (paneId: string) => void;
+ onClosePane: (paneId: string) => void;
+ onResize: (flex: number[]) => void;
+ panes: TerminalPane[];
+}
+
+const SplitView = ({
+ activePaneId,
+ onActivatePane,
+ onClosePane,
+ onResize,
+ panes,
+}: SplitViewProps) => {
+ const { t } = useTranslation('chat');
+ const rootRef = useRef<HTMLDivElement>(null);
+ const [dragFlex, setDragFlex] = useState<number[]>();
+
+ const flex = dragFlex?.length === panes.length ? dragFlex : panes.map((pane) => pane.flex);
+ const split = panes.length > 1;
+
+ const handleDividerDown =
+ (dividerIndex: number) => (event: ReactPointerEvent<HTMLDivElement>) => {
+ const root = rootRef.current;
+ if (!root) return;
+ event.preventDefault();
+
+ const startX = event.clientX;
+ const start = [...flex];
+ const trackWidth = paneTrackWidth(root.getBoundingClientRect().width, panes.length);
+ let latest = start;
+
+ const handleMove = (moveEvent: PointerEvent) => {
+ const next = resizePanes(start, dividerIndex, moveEvent.clientX - startX, trackWidth);
+ if (!next) return;
+ latest = next;
+ setDragFlex(next);
+ };
+
+ const handleUp = () => {
+ globalThis.removeEventListener('pointermove', handleMove);
+ globalThis.removeEventListener('pointerup', handleUp);
+ setDragFlex(undefined);
+ onResize(latest);
+ };
+
+ globalThis.addEventListener('pointermove', handleMove);
+ globalThis.addEventListener('pointerup', handleUp);
+ };
+
+ return (
+ <div className={styles.root} ref={rootRef}>
+ {panes.map((pane, index) => (
+ <Fragment key={pane.id}>
+ {index > 0 && (
+ <div className={styles.divider} onPointerDown={handleDividerDown(index - 1)} />
+ )}
+ <div
+ className={styles.pane}
+ data-inactive-pane={split && pane.id !== activePaneId ? '' : undefined}
+ style={{ flex: `${flex[index]} 1 0` }}
+ onPointerDownCapture={() => onActivatePane(pane.id)}
+ >
+ {split && (
+ <div data-pane-close className={styles.close}>
+ <ActionIcon
+ icon={XIcon}
+ size={{ blockSize: 20, size: 12 }}
+ title={t('terminalPanel.closePane')}
+ onClick={() => onClosePane(pane.id)}
+ />
+ </div>
+ )}
+ <TerminalView sessionId={pane.id} />
+ </div>
+ </Fragment>
+ ))}
+ </div>
+ );
+};
+
+export default SplitView;
diff --git a/src/features/ChatTerminal/keybindings.test.ts b/src/features/ChatTerminal/keybindings.test.ts
new file mode 100644
index 00000000000..b5af1b335a7
--- /dev/null
+++ b/src/features/ChatTerminal/keybindings.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveTerminalKeyAction } from './keybindings';
+
+const key = (init: Partial<KeyboardEvent> & { key: string }) =>
+ ({ ctrlKey: false, metaKey: false, shiftKey: false, type: 'keydown', ...init }) as KeyboardEvent;
+
+describe('resolveTerminalKeyAction β€” Ghostty ⌘ defaults', () => {
+ it('sends Ctrl-A for βŒ˜β† so readline jumps to the line start', () => {
+ expect(resolveTerminalKeyAction(key({ key: 'ArrowLeft', metaKey: true }))).toEqual({
+ bytes: '\u0001',
+ type: 'send',
+ });
+ });
+
+ it('sends Ctrl-E for βŒ˜β†’', () => {
+ expect(resolveTerminalKeyAction(key({ key: 'ArrowRight', metaKey: true }))).toEqual({
+ bytes: '\u0005',
+ type: 'send',
+ });
+ });
+
+ it('sends Ctrl-U for ⌘⌫', () => {
+ expect(resolveTerminalKeyAction(key({ key: 'Backspace', metaKey: true }))).toEqual({
+ bytes: '\u0015',
+ type: 'send',
+ });
+ });
+
+ it('scrolls the viewport for ⌘Home / ⌘End / ⌘PageUp / ⌘PageDown', () => {
+ expect(resolveTerminalKeyAction(key({ key: 'Home', metaKey: true }))?.type).toBe('scrollToTop');
+ expect(resolveTerminalKeyAction(key({ key: 'End', metaKey: true }))?.type).toBe(
+ 'scrollToBottom',
+ );
+ expect(resolveTerminalKeyAction(key({ key: 'PageUp', metaKey: true }))).toEqual({
+ pages: -1,
+ type: 'scrollPages',
+ });
+ expect(resolveTerminalKeyAction(key({ key: 'PageDown', metaKey: true }))).toEqual({
+ pages: 1,
+ type: 'scrollPages',
+ });
+ });
+
+ it('moves between split panes for ⌘βŒ₯← / ⌘βŒ₯β†’', () => {
+ expect(
+ resolveTerminalKeyAction(key({ altKey: true, key: 'ArrowLeft', metaKey: true })),
+ ).toEqual({ direction: -1, type: 'focusSiblingPane' });
+ expect(
+ resolveTerminalKeyAction(key({ altKey: true, key: 'ArrowRight', metaKey: true })),
+ ).toEqual({ direction: 1, type: 'focusSiblingPane' });
+ });
+});
+
+describe('resolveTerminalKeyAction β€” keys that must reach xterm untouched', () => {
+ it('ignores plain arrows, which xterm encodes as CSI sequences itself', () => {
+ expect(resolveTerminalKeyAction(key({ key: 'ArrowLeft' }))).toBeUndefined();
+ });
+
+ it('ignores βŒ₯← / βŒ₯β†’ β€” xterm already rewrites those to ESC b / ESC f on macOS', () => {
+ expect(resolveTerminalKeyAction(key({ altKey: true, key: 'ArrowLeft' }))).toBeUndefined();
+ expect(resolveTerminalKeyAction(key({ altKey: true, key: 'ArrowRight' }))).toBeUndefined();
+ });
+
+ it('ignores βŒ˜β†‘ / βŒ˜β†“ β€” jump_to_prompt needs shell integration we do not emit', () => {
+ expect(resolveTerminalKeyAction(key({ key: 'ArrowUp', metaKey: true }))).toBeUndefined();
+ expect(resolveTerminalKeyAction(key({ key: 'ArrowDown', metaKey: true }))).toBeUndefined();
+ });
+
+ it('ignores βŒ˜β‡§β† and βŒ˜βŒƒβ† so app-level and split-resize combos stay free', () => {
+ expect(
+ resolveTerminalKeyAction(key({ key: 'ArrowLeft', metaKey: true, shiftKey: true })),
+ ).toBeUndefined();
+ expect(
+ resolveTerminalKeyAction(key({ ctrlKey: true, key: 'ArrowLeft', metaKey: true })),
+ ).toBeUndefined();
+ });
+
+ it('ignores keyup, so a binding fires once rather than twice', () => {
+ expect(
+ resolveTerminalKeyAction(key({ key: 'ArrowLeft', metaKey: true, type: 'keyup' })),
+ ).toBeUndefined();
+ });
+});
diff --git a/src/features/ChatTerminal/keybindings.ts b/src/features/ChatTerminal/keybindings.ts
new file mode 100644
index 00000000000..4fc6a7575e3
--- /dev/null
+++ b/src/features/ChatTerminal/keybindings.ts
@@ -0,0 +1,61 @@
+export type TerminalKeyAction =
+ | { bytes: string; type: 'send' }
+ | { direction: -1 | 1; type: 'focusSiblingPane' }
+ | { pages: number; type: 'scrollPages' }
+ | { type: 'scrollToBottom' }
+ | { type: 'scrollToTop' };
+
+/**
+ * Ghostty's default ⌘ bindings, which xterm.js leaves unhandled on purpose:
+ * its arrow-key cases bail on `metaKey` so embedders can claim ⌘ themselves.
+ * Source of truth is `ghostty +list-keybinds --default` (checked on 1.3.1).
+ *
+ * βŒ₯←/βŒ₯β†’ are absent here because xterm.js already rewrites them to ESC b / ESC f
+ * on macOS, which is exactly what Ghostty binds them to.
+ *
+ * Left unimplemented on purpose β€” don't "restore" these without the machinery:
+ * - βŒ˜β†‘/βŒ˜β†“ (jump_to_prompt) needs OSC 133 shell integration we don't emit
+ * - ⇧+arrows (adjust_selection) has no keyboard-selection API in xterm.js
+ * - βŒ˜βŒƒ+arrows (resize_split) has no meaning for our relative flex widths
+ */
+// readline control codes, named for what the shell does with them
+const BEGINNING_OF_LINE = '\u0001';
+const END_OF_LINE = '\u0005';
+const KILL_TO_LINE_START = '\u0015';
+
+export const resolveTerminalKeyAction = (event: KeyboardEvent): TerminalKeyAction | undefined => {
+ if (event.type !== 'keydown' || !event.metaKey || event.ctrlKey || event.shiftKey) return;
+
+ if (event.altKey) {
+ if (event.key === 'ArrowLeft') return { direction: -1, type: 'focusSiblingPane' };
+ if (event.key === 'ArrowRight') return { direction: 1, type: 'focusSiblingPane' };
+ return;
+ }
+
+ switch (event.key) {
+ case 'ArrowLeft': {
+ return { bytes: BEGINNING_OF_LINE, type: 'send' };
+ }
+ case 'ArrowRight': {
+ return { bytes: END_OF_LINE, type: 'send' };
+ }
+ case 'Backspace': {
+ return { bytes: KILL_TO_LINE_START, type: 'send' };
+ }
+ case 'End': {
+ return { type: 'scrollToBottom' };
+ }
+ case 'Home': {
+ return { type: 'scrollToTop' };
+ }
+ case 'PageDown': {
+ return { pages: 1, type: 'scrollPages' };
+ }
+ case 'PageUp': {
+ return { pages: -1, type: 'scrollPages' };
+ }
+ default: {
+ return;
+ }
+ }
+};
diff --git a/src/features/ChatTerminal/links.test.ts b/src/features/ChatTerminal/links.test.ts
new file mode 100644
index 00000000000..7c58691f608
--- /dev/null
+++ b/src/features/ChatTerminal/links.test.ts
@@ -0,0 +1,38 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { electronSystemService } from '@/services/electron/system';
+
+import { openTerminalLink } from './links';
+
+vi.mock('@/services/electron/system', () => ({
+ electronSystemService: { openExternalLink: vi.fn().mockResolvedValue(undefined) },
+}));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('openTerminalLink', () => {
+ it('hands http(s) links to the system browser', () => {
+ openTerminalLink('https://lobehub.com/docs?a=1#x');
+
+ expect(electronSystemService.openExternalLink).toHaveBeenCalledWith(
+ 'https://lobehub.com/docs?a=1#x',
+ );
+ });
+
+ it.each(['file:///etc/passwd', 'vscode://x', 'javascript:alert(1)', 'mailto:[email protected]'])(
+ 'refuses to open %s β€” terminal output is attacker-reachable and the main process does no check',
+ (uri) => {
+ openTerminalLink(uri);
+
+ expect(electronSystemService.openExternalLink).not.toHaveBeenCalled();
+ },
+ );
+
+ it('ignores text that is not a URL at all', () => {
+ openTerminalLink('not a link');
+
+ expect(electronSystemService.openExternalLink).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/ChatTerminal/links.ts b/src/features/ChatTerminal/links.ts
new file mode 100644
index 00000000000..dc584ad077c
--- /dev/null
+++ b/src/features/ChatTerminal/links.ts
@@ -0,0 +1,29 @@
+import debug from 'debug';
+
+import { electronSystemService } from '@/services/electron/system';
+
+const log = debug('lobe-desktop:chat-terminal');
+
+// The main process hands this straight to shell.openExternal, and terminal
+// output is attacker-reachable β€” any command can print an escape sequence. So
+// the renderer is the gate: only http(s) ever reaches the OS handler.
+const OPENABLE_PROTOCOLS = new Set(['http:', 'https:']);
+
+export const openTerminalLink = (uri: string) => {
+ let parsed: URL;
+ try {
+ parsed = new URL(uri);
+ } catch {
+ log('ignoring unparseable terminal link: %s', uri);
+ return;
+ }
+
+ if (!OPENABLE_PROTOCOLS.has(parsed.protocol)) {
+ log('ignoring terminal link with unsupported protocol: %s', parsed.protocol);
+ return;
+ }
+
+ void electronSystemService.openExternalLink(parsed.href).catch((error) => {
+ log('failed to open terminal link %s: %O', parsed.href, error);
+ });
+};
diff --git a/src/features/ChatTerminal/paneLayout.test.ts b/src/features/ChatTerminal/paneLayout.test.ts
new file mode 100644
index 00000000000..3b65fc29481
--- /dev/null
+++ b/src/features/ChatTerminal/paneLayout.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest';
+
+import { DIVIDER_WIDTH, paneTrackWidth, resizePanes } from './paneLayout';
+
+const rounded = (flex: number[] | undefined) =>
+ flex?.map((value) => Math.round(value * 1000) / 1000);
+
+describe('paneTrackWidth', () => {
+ it('excludes the dividers, so flex maps onto the space panes actually get', () => {
+ expect(paneTrackWidth(1000, 3)).toBe(1000 - 2 * DIVIDER_WIDTH);
+ expect(paneTrackWidth(1000, 1)).toBe(1000);
+ });
+});
+
+describe('resizePanes', () => {
+ it('moves flex from one pane of the pair to the other', () => {
+ expect(rounded(resizePanes([1, 1], 0, 200, 1000))).toEqual([1.4, 0.6]);
+ });
+
+ it('leaves panes outside the dragged pair untouched', () => {
+ expect(rounded(resizePanes([1, 1, 1], 1, 100, 1000))).toEqual([1, 1.3, 0.7]);
+ });
+
+ it('clamps at MIN_PANE_WIDTH instead of collapsing the neighbour', () => {
+ // 1000px track, total flex 2 β†’ the 160px floor is 0.32 flex.
+ expect(rounded(resizePanes([1, 1], 0, 100_000, 1000))).toEqual([1.68, 0.32]);
+ expect(rounded(resizePanes([1, 1], 0, -100_000, 1000))).toEqual([0.32, 1.68]);
+ });
+
+ it('scales the floor with the pane count, since flex is relative to the total', () => {
+ // 3 panes, total flex 3 β†’ the same 160px floor is 0.48 flex.
+ expect(rounded(resizePanes([1, 1, 1], 1, 100_000, 1000))).toEqual([1, 1.52, 0.48]);
+ });
+
+ it('refuses the drag when the pair cannot fit two minimum-width panes', () => {
+ expect(resizePanes([1, 1], 0, 10, 300)).toBeUndefined();
+ });
+
+ it('refuses the drag before layout has a measurable width', () => {
+ expect(resizePanes([1, 1], 0, 10, 0)).toBeUndefined();
+ });
+});
diff --git a/src/features/ChatTerminal/paneLayout.ts b/src/features/ChatTerminal/paneLayout.ts
new file mode 100644
index 00000000000..1e3eed6e4cc
--- /dev/null
+++ b/src/features/ChatTerminal/paneLayout.ts
@@ -0,0 +1,35 @@
+export const MIN_PANE_WIDTH = 160;
+export const DIVIDER_WIDTH = 9;
+
+export const paneTrackWidth = (rootWidth: number, paneCount: number) =>
+ rootWidth - (paneCount - 1) * DIVIDER_WIDTH;
+
+/**
+ * New flex values after dragging the divider that sits after `dividerIndex`.
+ *
+ * A divider only ever moves the two panes it sits between: their combined flex
+ * is the budget, so every other pane keeps the width it had. Returns undefined
+ * when the pair has no room left to honour MIN_PANE_WIDTH on both sides.
+ */
+export const resizePanes = (
+ flex: number[],
+ dividerIndex: number,
+ deltaPx: number,
+ trackWidth: number,
+): number[] | undefined => {
+ const total = flex.reduce((sum, value) => sum + value, 0);
+ if (trackWidth <= 0 || total <= 0) return;
+
+ const pairFlex = flex[dividerIndex] + flex[dividerIndex + 1];
+ const minFlex = (MIN_PANE_WIDTH / trackWidth) * total;
+ if (pairFlex < minFlex * 2) return;
+
+ const dragged = flex[dividerIndex] + (deltaPx / trackWidth) * total;
+ const next = Math.min(Math.max(dragged, minFlex), pairFlex - minFlex);
+
+ return flex.map((value, index) => {
+ if (index === dividerIndex) return next;
+ if (index === dividerIndex + 1) return pairFlex - next;
+ return value;
+ });
+};
diff --git a/src/features/ChatTerminal/store.test.ts b/src/features/ChatTerminal/store.test.ts
index 8a1bfa50824..45bf5489840 100644
--- a/src/features/ChatTerminal/store.test.ts
+++ b/src/features/ChatTerminal/store.test.ts
@@ -3,25 +3,48 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useChatTerminalStore } from './store';
import { xtermManager } from './xtermManager';
+const { createSession, exitListeners, navListeners } = vi.hoisted(() => ({
+ createSession: vi.fn(),
+ exitListeners: [] as ((sessionId: string, exitCode: number) => void)[],
+ navListeners: [] as ((sessionId: string, direction: -1 | 1) => void)[],
+}));
+
vi.mock('@/services/electron/terminal', () => ({
- electronTerminalService: { createSession: vi.fn() },
+ electronTerminalService: { createSession },
}));
vi.mock('./xtermManager', () => ({
- xtermManager: { close: vi.fn(), ensure: vi.fn(), onSessionExit: vi.fn() },
+ xtermManager: {
+ close: vi.fn(),
+ ensure: vi.fn(),
+ focus: vi.fn(),
+ onPaneNavigate: (listener: (sessionId: string, direction: -1 | 1) => void) => {
+ navListeners.push(listener);
+ },
+ onSessionExit: (listener: (sessionId: string, exitCode: number) => void) => {
+ exitListeners.push(listener);
+ },
+ },
}));
+const pane = (id: string, flex = 1) => ({ flex, id });
+
+const tab = (id: string, panes: string[] = [id]) => ({
+ activePaneId: panes.at(-1)!,
+ id,
+ panes: panes.map((paneId) => pane(paneId)),
+ title: id,
+});
+
beforeEach(() => {
vi.clearAllMocks();
useChatTerminalStore.setState({
activeTabIds: { topic: 'b' },
+ createErrors: {},
+ creatingByTopic: {},
tabsByTopic: {
- other: [{ id: 'x', title: 'x' }],
- topic: [
- { id: 'a', title: 'a' },
- { id: 'b', title: 'b' },
- { id: 'c', title: 'c' },
- ],
+ other: [tab('x')],
+ topic: [tab('a'), tab('b'), tab('c')],
},
});
});
@@ -31,7 +54,7 @@ describe('closeOtherTabs', () => {
useChatTerminalStore.getState().closeOtherTabs('topic', 'a');
const { activeTabIds, tabsByTopic } = useChatTerminalStore.getState();
- expect(tabsByTopic.topic).toEqual([{ id: 'a', title: 'a' }]);
+ expect(tabsByTopic.topic.map((t) => t.id)).toEqual(['a']);
expect(activeTabIds.topic).toBe('a');
expect(xtermManager.close).toHaveBeenCalledTimes(2);
expect(xtermManager.close).toHaveBeenCalledWith('b');
@@ -41,7 +64,7 @@ describe('closeOtherTabs', () => {
it('leaves other topics untouched', () => {
useChatTerminalStore.getState().closeOtherTabs('topic', 'a');
- expect(useChatTerminalStore.getState().tabsByTopic.other).toEqual([{ id: 'x', title: 'x' }]);
+ expect(useChatTerminalStore.getState().tabsByTopic.other.map((t) => t.id)).toEqual(['x']);
});
it('does nothing when the tab id is not in the topic', () => {
@@ -52,4 +75,204 @@ describe('closeOtherTabs', () => {
expect(activeTabIds.topic).toBe('b');
expect(xtermManager.close).not.toHaveBeenCalled();
});
+
+ it('kills every pane of the tabs it closes, not just their first', () => {
+ useChatTerminalStore.setState({
+ tabsByTopic: { topic: [tab('a'), tab('b', ['b', 'b2', 'b3'])] },
+ });
+
+ useChatTerminalStore.getState().closeOtherTabs('topic', 'a');
+
+ expect(xtermManager.close).toHaveBeenCalledTimes(3);
+ for (const id of ['b', 'b2', 'b3']) expect(xtermManager.close).toHaveBeenCalledWith(id);
+ });
+});
+
+describe('closeTab', () => {
+ it('kills every pane in the tab', () => {
+ useChatTerminalStore.setState({ tabsByTopic: { topic: [tab('a', ['a', 'a2'])] } });
+
+ useChatTerminalStore.getState().closeTab('topic', 'a');
+
+ expect(xtermManager.close).toHaveBeenCalledTimes(2);
+ expect(useChatTerminalStore.getState().tabsByTopic.topic).toEqual([]);
+ });
+});
+
+describe('splitPane', () => {
+ it('inserts the new pane after the active one and halves its width', async () => {
+ useChatTerminalStore.setState({ tabsByTopic: { topic: [tab('a')] } });
+ createSession.mockResolvedValue({ cwd: '/repo', id: 'a2', shell: '/bin/zsh' });
+
+ await useChatTerminalStore.getState().splitPane('topic', 'a', '/repo');
+
+ const [target] = useChatTerminalStore.getState().tabsByTopic.topic;
+ expect(target.panes).toEqual([pane('a', 0.5), pane('a2', 0.5)]);
+ expect(target.activePaneId).toBe('a2');
+ expect(xtermManager.ensure).toHaveBeenCalledWith('a2');
+ });
+
+ it('leaves the other panes at the width the user dragged them to', async () => {
+ useChatTerminalStore.setState({
+ tabsByTopic: {
+ topic: [
+ { activePaneId: 'a2', id: 'a', panes: [pane('a', 0.3), pane('a2', 1.7)], title: 'a' },
+ ],
+ },
+ });
+ createSession.mockResolvedValue({ cwd: '/repo', id: 'a3', shell: '/bin/zsh' });
+
+ await useChatTerminalStore.getState().splitPane('topic', 'a', '/repo');
+
+ expect(useChatTerminalStore.getState().tabsByTopic.topic[0].panes).toEqual([
+ pane('a', 0.3),
+ pane('a2', 0.85),
+ pane('a3', 0.85),
+ ]);
+ });
+
+ it('does not add a pane when the session fails to start', async () => {
+ useChatTerminalStore.setState({ tabsByTopic: { topic: [tab('a')] } });
+ createSession.mockRejectedValue(new Error('no pty'));
+
+ await useChatTerminalStore.getState().splitPane('topic', 'a', '/repo');
+
+ const state = useChatTerminalStore.getState();
+ expect(state.tabsByTopic.topic[0].panes).toEqual([pane('a')]);
+ expect(state.createErrors.topic).toBe('no pty');
+ });
+});
+
+describe('closePane', () => {
+ it('removes the pane and keeps the tab while other panes remain', () => {
+ useChatTerminalStore.setState({
+ activeTabIds: { topic: 'a' },
+ tabsByTopic: { topic: [tab('a', ['a', 'a2'])] },
+ });
+
+ useChatTerminalStore.getState().closePane('topic', 'a2');
+
+ const { activeTabIds, tabsByTopic } = useChatTerminalStore.getState();
+ expect(tabsByTopic.topic[0].panes).toEqual([pane('a')]);
+ expect(tabsByTopic.topic[0].activePaneId).toBe('a');
+ expect(activeTabIds.topic).toBe('a');
+ expect(xtermManager.close).toHaveBeenCalledWith('a2');
+ });
+
+ it('drops the tab once its last pane is closed', () => {
+ useChatTerminalStore.setState({
+ activeTabIds: { topic: 'b' },
+ tabsByTopic: { topic: [tab('a'), tab('b')] },
+ });
+
+ useChatTerminalStore.getState().closePane('topic', 'b');
+
+ const { activeTabIds, tabsByTopic } = useChatTerminalStore.getState();
+ expect(tabsByTopic.topic.map((t) => t.id)).toEqual(['a']);
+ expect(activeTabIds.topic).toBe('a');
+ });
+});
+
+describe('setActivePane', () => {
+ it('activates the clicked pane', () => {
+ useChatTerminalStore.setState({ tabsByTopic: { topic: [tab('a', ['a', 'a2'])] } });
+
+ useChatTerminalStore.getState().setActivePane('topic', 'a', 'a');
+
+ expect(useChatTerminalStore.getState().tabsByTopic.topic[0].activePaneId).toBe('a');
+ });
+
+ it('keeps state identity when the pane is already active, so a pointerdown does not rerender', () => {
+ useChatTerminalStore.setState({ tabsByTopic: { topic: [tab('a', ['a', 'a2'])] } });
+ const before = useChatTerminalStore.getState().tabsByTopic;
+
+ useChatTerminalStore.getState().setActivePane('topic', 'a', 'a2');
+
+ expect(useChatTerminalStore.getState().tabsByTopic).toBe(before);
+ });
+});
+
+describe('setPaneFlex', () => {
+ it('applies the dragged widths in pane order', () => {
+ useChatTerminalStore.setState({ tabsByTopic: { topic: [tab('a', ['a', 'a2'])] } });
+
+ useChatTerminalStore.getState().setPaneFlex('topic', 'a', [0.4, 1.6]);
+
+ expect(useChatTerminalStore.getState().tabsByTopic.topic[0].panes).toEqual([
+ pane('a', 0.4),
+ pane('a2', 1.6),
+ ]);
+ });
+
+ it('ignores a stale width list that no longer matches the pane count', () => {
+ useChatTerminalStore.setState({ tabsByTopic: { topic: [tab('a', ['a', 'a2'])] } });
+
+ useChatTerminalStore.getState().setPaneFlex('topic', 'a', [0.4]);
+
+ expect(useChatTerminalStore.getState().tabsByTopic.topic[0].panes).toEqual([
+ pane('a'),
+ pane('a2'),
+ ]);
+ });
+});
+
+describe('pane navigation', () => {
+ const navigate = (sessionId: string, direction: -1 | 1) => {
+ for (const listener of navListeners) listener(sessionId, direction);
+ };
+
+ it('moves focus to the neighbouring pane and focuses its terminal', () => {
+ useChatTerminalStore.setState({ tabsByTopic: { topic: [tab('a', ['a', 'a2', 'a3'])] } });
+
+ navigate('a2', 1);
+
+ expect(useChatTerminalStore.getState().tabsByTopic.topic[0].activePaneId).toBe('a3');
+ expect(xtermManager.focus).toHaveBeenCalledWith('a3');
+ });
+
+ it('stops at the edge instead of wrapping, matching Ghostty goto_split', () => {
+ useChatTerminalStore.setState({ tabsByTopic: { topic: [tab('a', ['a', 'a2'])] } });
+
+ navigate('a', -1);
+
+ expect(useChatTerminalStore.getState().tabsByTopic.topic[0].activePaneId).toBe('a2');
+ expect(xtermManager.focus).not.toHaveBeenCalled();
+ });
+
+ it('ignores a session that no longer belongs to any tab', () => {
+ useChatTerminalStore.setState({ tabsByTopic: { topic: [tab('a', ['a', 'a2'])] } });
+
+ navigate('gone', 1);
+
+ expect(xtermManager.focus).not.toHaveBeenCalled();
+ });
+});
+
+describe('session exit', () => {
+ it('removes only the exited pane, leaving its tab open', () => {
+ useChatTerminalStore.setState({
+ activeTabIds: { topic: 'a' },
+ tabsByTopic: { topic: [tab('a', ['a', 'a2'])] },
+ });
+
+ for (const listener of exitListeners) listener('a2', 0);
+
+ const { tabsByTopic } = useChatTerminalStore.getState();
+ expect(tabsByTopic.topic[0].panes).toEqual([pane('a')]);
+ expect(tabsByTopic.topic[0].activePaneId).toBe('a');
+ });
+
+ it('drops the tab when the exited pane was its last one', () => {
+ useChatTerminalStore.setState({
+ activeTabIds: { topic: 'b' },
+ tabsByTopic: { other: [tab('x')], topic: [tab('a'), tab('b')] },
+ });
+
+ for (const listener of exitListeners) listener('b', 0);
+
+ const { activeTabIds, tabsByTopic } = useChatTerminalStore.getState();
+ expect(tabsByTopic.topic.map((t) => t.id)).toEqual(['a']);
+ expect(activeTabIds.topic).toBe('a');
+ expect(tabsByTopic.other.map((t) => t.id)).toEqual(['x']);
+ });
});
diff --git a/src/features/ChatTerminal/store.ts b/src/features/ChatTerminal/store.ts
index be7b8180acc..00aa788f889 100644
--- a/src/features/ChatTerminal/store.ts
+++ b/src/features/ChatTerminal/store.ts
@@ -7,8 +7,18 @@ import { xtermManager } from './xtermManager';
const log = debug('lobe-desktop:chat-terminal');
+export interface TerminalPane {
+ /** Relative width inside the tab β€” only meaningful against sibling panes */
+ flex: number;
+ /** PTY session id */
+ id: string;
+}
+
export interface TerminalTab {
+ activePaneId: string;
+ /** Equals the id of the session the tab was opened with */
id: string;
+ panes: TerminalPane[];
title: string;
}
@@ -25,9 +35,13 @@ interface ChatTerminalState {
interface ChatTerminalActions {
closeOtherTabs: (topicKey: string, tabId: string) => void;
+ closePane: (topicKey: string, paneId: string) => void;
closeTab: (topicKey: string, tabId: string) => void;
createTab: (topicKey: string, cwd?: string) => Promise<void>;
+ setActivePane: (topicKey: string, tabId: string, paneId: string) => void;
setActiveTab: (topicKey: string, tabId: string) => void;
+ setPaneFlex: (topicKey: string, tabId: string, flex: number[]) => void;
+ splitPane: (topicKey: string, tabId: string, cwd?: string) => Promise<void>;
}
const tabTitle = (cwd: string, shell: string) => {
@@ -38,8 +52,72 @@ const tabTitle = (cwd: string, shell: string) => {
return dir || shell.split(/[/\\]/).pop() || 'shell';
};
-export const useChatTerminalStore = create<ChatTerminalActions & ChatTerminalState>()(
- (set, get) => ({
+/** Drops the pane from whichever tab holds it, dropping the tab once it runs empty. */
+const withoutPane = (tabs: TerminalTab[], paneId: string): TerminalTab[] =>
+ tabs.flatMap((tab) => {
+ if (!tab.panes.some((pane) => pane.id === paneId)) return [tab];
+ const panes = tab.panes.filter((pane) => pane.id !== paneId);
+ if (panes.length === 0) return [];
+ return [
+ {
+ ...tab,
+ activePaneId: tab.activePaneId === paneId ? panes.at(-1)!.id : tab.activePaneId,
+ panes,
+ },
+ ];
+ });
+
+const reassignActiveTab = (
+ tabs: TerminalTab[],
+ activeTabId: string | undefined,
+): string | undefined =>
+ tabs.some((tab) => tab.id === activeTabId) ? activeTabId : tabs.at(-1)?.id;
+
+export const useChatTerminalStore = create<ChatTerminalActions & ChatTerminalState>()((
+ set,
+ get,
+) => {
+ // Shared by createTab and splitPane: both spawn a PTY and both are gated by
+ // the same per-topic in-flight flag so a double click can't fork two shells.
+ const spawnSession = async (topicKey: string, cwd?: string) => {
+ if (get().creatingByTopic[topicKey]) return;
+ set((s) => ({
+ createErrors: { ...s.createErrors, [topicKey]: undefined },
+ creatingByTopic: { ...s.creatingByTopic, [topicKey]: true },
+ }));
+ try {
+ const info = await electronTerminalService.createSession({ cols: 80, cwd, rows: 24 });
+ xtermManager.ensure(info.id);
+ return info;
+ } catch (error) {
+ log('failed to create terminal session for %s: %O', topicKey, error);
+ set((s) => ({
+ createErrors: {
+ ...s.createErrors,
+ [topicKey]: error instanceof Error ? error.message : String(error),
+ },
+ }));
+ return;
+ } finally {
+ set((s) => ({ creatingByTopic: { ...s.creatingByTopic, [topicKey]: false } }));
+ }
+ };
+
+ const updateTab = (
+ topicKey: string,
+ tabId: string,
+ update: (tab: TerminalTab) => TerminalTab,
+ ) => {
+ const { tabsByTopic } = get();
+ const tabs = tabsByTopic[topicKey] ?? [];
+ const next = tabs.map((tab) => (tab.id === tabId ? update(tab) : tab));
+ // Bail on a no-op update β€” setActivePane runs on every pointerdown in a
+ // pane, and a fresh tabsByTopic identity there would rerender the panel.
+ if (next.every((tab, index) => tab === tabs[index])) return;
+ set({ tabsByTopic: { ...tabsByTopic, [topicKey]: next } });
+ };
+
+ return {
activeTabIds: {},
closeOtherTabs: (topicKey, tabId) => {
@@ -47,80 +125,139 @@ export const useChatTerminalStore = create<ChatTerminalActions & ChatTerminalSta
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);
+ for (const tab of tabs) {
+ if (tab.id === tabId) continue;
+ for (const pane of tab.panes) xtermManager.close(pane.id);
+ }
set({
activeTabIds: { ...activeTabIds, [topicKey]: tabId },
tabsByTopic: { ...tabsByTopic, [topicKey]: [kept] },
});
},
- closeTab: (topicKey, tabId) => {
- xtermManager.close(tabId);
+ closePane: (topicKey, paneId) => {
+ xtermManager.close(paneId);
const { activeTabIds, tabsByTopic } = get();
- const tabs = (tabsByTopic[topicKey] ?? []).filter((tab) => tab.id !== tabId);
- const activeTabId =
- activeTabIds[topicKey] === tabId ? tabs.at(-1)?.id : activeTabIds[topicKey];
+ const tabs = withoutPane(tabsByTopic[topicKey] ?? [], paneId);
set({
- activeTabIds: { ...activeTabIds, [topicKey]: activeTabId },
+ activeTabIds: {
+ ...activeTabIds,
+ [topicKey]: reassignActiveTab(tabs, activeTabIds[topicKey]),
+ },
tabsByTopic: { ...tabsByTopic, [topicKey]: tabs },
});
},
+ closeTab: (topicKey, tabId) => {
+ const { activeTabIds, tabsByTopic } = get();
+ const tabs = tabsByTopic[topicKey] ?? [];
+ for (const tab of tabs) {
+ if (tab.id !== tabId) continue;
+ for (const pane of tab.panes) xtermManager.close(pane.id);
+ }
+ const kept = tabs.filter((tab) => tab.id !== tabId);
+ set({
+ activeTabIds: {
+ ...activeTabIds,
+ [topicKey]: reassignActiveTab(kept, activeTabIds[topicKey]),
+ },
+ tabsByTopic: { ...tabsByTopic, [topicKey]: kept },
+ });
+ },
+
createErrors: {},
createTab: async (topicKey, cwd) => {
- if (get().creatingByTopic[topicKey]) return;
- set((s) => ({
- createErrors: { ...s.createErrors, [topicKey]: undefined },
- creatingByTopic: { ...s.creatingByTopic, [topicKey]: true },
- }));
- try {
- const info = await electronTerminalService.createSession({ cols: 80, cwd, rows: 24 });
- xtermManager.ensure(info.id);
- const { activeTabIds, tabsByTopic } = get();
- set({
- activeTabIds: { ...activeTabIds, [topicKey]: info.id },
- tabsByTopic: {
- ...tabsByTopic,
- [topicKey]: [
- ...(tabsByTopic[topicKey] ?? []),
- { id: info.id, title: tabTitle(info.cwd, info.shell) },
- ],
- },
- });
- } catch (error) {
- log('failed to create terminal session for %s: %O', topicKey, error);
- set((s) => ({
- createErrors: {
- ...s.createErrors,
- [topicKey]: error instanceof Error ? error.message : String(error),
- },
- }));
- } finally {
- set((s) => ({ creatingByTopic: { ...s.creatingByTopic, [topicKey]: false } }));
- }
+ const info = await spawnSession(topicKey, cwd);
+ if (!info) return;
+ const { activeTabIds, tabsByTopic } = get();
+ set({
+ activeTabIds: { ...activeTabIds, [topicKey]: info.id },
+ tabsByTopic: {
+ ...tabsByTopic,
+ [topicKey]: [
+ ...(tabsByTopic[topicKey] ?? []),
+ {
+ activePaneId: info.id,
+ id: info.id,
+ panes: [{ flex: 1, id: info.id }],
+ title: tabTitle(info.cwd, info.shell),
+ },
+ ],
+ },
+ });
},
creatingByTopic: {},
+ setActivePane: (topicKey, tabId, paneId) => {
+ updateTab(topicKey, tabId, (tab) =>
+ tab.activePaneId === paneId || !tab.panes.some((pane) => pane.id === paneId)
+ ? tab
+ : { ...tab, activePaneId: paneId },
+ );
+ },
+
setActiveTab: (topicKey, tabId) => {
set({ activeTabIds: { ...get().activeTabIds, [topicKey]: tabId } });
},
+ setPaneFlex: (topicKey, tabId, flex) => {
+ updateTab(topicKey, tabId, (tab) =>
+ flex.length === tab.panes.length
+ ? { ...tab, panes: tab.panes.map((pane, index) => ({ ...pane, flex: flex[index] })) }
+ : tab,
+ );
+ },
+
+ splitPane: async (topicKey, tabId, cwd) => {
+ const info = await spawnSession(topicKey, cwd);
+ if (!info) return;
+ updateTab(topicKey, tabId, (tab) => {
+ const found = tab.panes.findIndex((pane) => pane.id === tab.activePaneId);
+ const sourceIndex = found === -1 ? tab.panes.length - 1 : found;
+ // The new pane takes half of the pane it was split from, so the rest
+ // of the row keeps whatever widths the user dragged them to.
+ const half = tab.panes[sourceIndex].flex / 2;
+ const panes = tab.panes.map((pane, index) =>
+ index === sourceIndex ? { ...pane, flex: half } : pane,
+ );
+ panes.splice(sourceIndex + 1, 0, { flex: half, id: info.id });
+ return { ...tab, activePaneId: info.id, panes };
+ });
+ },
+
tabsByTopic: {},
- }),
-);
+ };
+});
+
+// ⌘βŒ₯←/β†’ arrives on whichever pane has focus; only the store knows its neighbours.
+xtermManager.onPaneNavigate((sessionId, direction) => {
+ const { tabsByTopic, setActivePane } = useChatTerminalStore.getState();
+ for (const [topicKey, tabs] of Object.entries(tabsByTopic)) {
+ const tab = tabs.find((candidate) => candidate.panes.some((pane) => pane.id === sessionId));
+ if (!tab) continue;
+ const index = tab.panes.findIndex((pane) => pane.id === sessionId);
+ // Directional, not cyclic β€” matches Ghostty's goto_split, which stops at the edge.
+ const target = tab.panes[index + direction];
+ if (!target) return;
+ setActivePane(topicKey, tab.id, target.id);
+ xtermManager.focus(target.id);
+ return;
+ }
+});
-// When the shell process exits (user types `exit`, or the main process reaps an
-// idle/LRU-evicted session), close its tab in whichever topic owns it.
+// When a shell process exits (user types `exit`, or the main process reaps an
+// idle/LRU-evicted session), drop its pane wherever it lives β€” and with it the
+// tab, once that was its last pane.
xtermManager.onSessionExit((sessionId) => {
const { activeTabIds, tabsByTopic } = useChatTerminalStore.getState();
const nextTabs: Record<string, TerminalTab[]> = {};
const nextActive = { ...activeTabIds };
for (const [topicKey, tabs] of Object.entries(tabsByTopic)) {
- const filtered = tabs.filter((tab) => tab.id !== sessionId);
+ const filtered = withoutPane(tabs, sessionId);
nextTabs[topicKey] = filtered;
- if (activeTabIds[topicKey] === sessionId) nextActive[topicKey] = filtered.at(-1)?.id;
+ nextActive[topicKey] = reassignActiveTab(filtered, activeTabIds[topicKey]);
}
useChatTerminalStore.setState({ activeTabIds: nextActive, tabsByTopic: nextTabs });
});
diff --git a/src/features/ChatTerminal/xtermManager.test.ts b/src/features/ChatTerminal/xtermManager.test.ts
index 32cd2fcf34f..ef2a189cb48 100644
--- a/src/features/ChatTerminal/xtermManager.test.ts
+++ b/src/features/ChatTerminal/xtermManager.test.ts
@@ -2,10 +2,20 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { xtermManager } from './xtermManager';
-const { fitAddonFit, ipcOn, resizeSession, webglInstances, webglShouldThrow } = vi.hoisted(() => ({
+const {
+ fitAddonFit,
+ ipcOn,
+ keyHandlers,
+ resizeSession,
+ termInput,
+ webglInstances,
+ webglShouldThrow,
+} = vi.hoisted(() => ({
fitAddonFit: vi.fn(),
ipcOn: vi.fn(),
+ keyHandlers: [] as ((event: KeyboardEvent) => boolean)[],
resizeSession: vi.fn().mockResolvedValue(undefined),
+ termInput: vi.fn(),
webglInstances: [] as { contextLoss: () => void; dispose: ReturnType<typeof vi.fn> }[],
webglShouldThrow: { value: false },
}));
@@ -35,12 +45,19 @@ vi.mock('@xterm/addon-webgl', () => ({
vi.mock('@xterm/xterm', () => ({
Terminal: class {
+ attachCustomKeyEventHandler = (handler: (event: KeyboardEvent) => boolean) => {
+ keyHandlers.push(handler);
+ };
cols = 80;
+ input = termInput;
loadAddon = vi.fn();
onData = vi.fn();
open = vi.fn();
options = {};
rows = 24;
+ scrollPages = vi.fn();
+ scrollToBottom = vi.fn();
+ scrollToTop = vi.fn();
write = vi.fn();
},
}));
@@ -153,3 +170,43 @@ describe('xtermManager', () => {
expect(webglInstances).toHaveLength(0);
});
});
+
+describe('xtermManager keybindings', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ const press = (init: Partial<KeyboardEvent> & { key: string }) => {
+ const preventDefault = vi.fn();
+ const handled = keyHandlers.at(-1)!({
+ ctrlKey: false,
+ metaKey: false,
+ preventDefault,
+ shiftKey: false,
+ type: 'keydown',
+ ...init,
+ } as unknown as KeyboardEvent);
+ return { handled, preventDefault };
+ };
+
+ it('turns \u2318\u2190 into the readline line-start code and swallows the event', () => {
+ xtermManager.ensure('keys_home');
+
+ const { handled, preventDefault } = press({ key: 'ArrowLeft', metaKey: true });
+
+ expect(termInput).toHaveBeenCalledWith('\u0001');
+ // Swallowed so Chromium does not treat it as history-back.
+ expect(preventDefault).toHaveBeenCalledTimes(1);
+ expect(handled).toBe(false);
+ });
+
+ it('leaves unclaimed keys to xterm so normal typing still reaches the PTY', () => {
+ xtermManager.ensure('keys_plain');
+
+ const { handled, preventDefault } = press({ key: 'ArrowLeft' });
+
+ expect(termInput).not.toHaveBeenCalled();
+ expect(preventDefault).not.toHaveBeenCalled();
+ expect(handled).toBe(true);
+ });
+});
diff --git a/src/features/ChatTerminal/xtermManager.ts b/src/features/ChatTerminal/xtermManager.ts
index 56d418fa475..f3b0aedac59 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 { WebLinksAddon } from '@xterm/addon-web-links';
import { WebglAddon } from '@xterm/addon-webgl';
import type { ITheme } from '@xterm/xterm';
import { Terminal } from '@xterm/xterm';
@@ -9,6 +10,9 @@ import debug from 'debug';
import { electronTerminalService } from '@/services/electron/terminal';
+import { resolveTerminalKeyAction } from './keybindings';
+import { openTerminalLink } from './links';
+
const log = debug('lobe-desktop:chat-terminal');
interface TermInstance {
@@ -20,6 +24,7 @@ interface TermInstance {
}
type ExitListener = (sessionId: string, exitCode: number) => void;
+type PaneNavListener = (sessionId: string, direction: -1 | 1) => void;
/**
* Module-level registry of live xterm instances, keyed by PTY session id.
@@ -31,6 +36,7 @@ type ExitListener = (sessionId: string, exitCode: number) => void;
class XtermManager {
private instances = new Map<string, TermInstance>();
private exitListeners = new Set<ExitListener>();
+ private paneNavListeners = new Set<PaneNavListener>();
private ipcBound = false;
private webglUnavailable = false;
@@ -55,6 +61,12 @@ class XtermManager {
return () => this.exitListeners.delete(listener);
}
+ /** ⌘βŒ₯←/β†’ β€” the store owns which pane sits next to which, so it resolves the move. */
+ onPaneNavigate(listener: PaneNavListener) {
+ this.paneNavListeners.add(listener);
+ return () => this.paneNavListeners.delete(listener);
+ }
+
ensure(sessionId: string): TermInstance {
this.bindIpc();
const existing = this.instances.get(sessionId);
@@ -68,11 +80,44 @@ class XtermManager {
allowProposedApi: true,
cursorBlink: true,
fontSize: 12,
+ // Handles OSC 8 hyperlinks; WebLinksAddon below covers bare URLs in output.
+ linkHandler: { activate: (_event, uri) => openTerminalLink(uri) },
macOptionIsMeta: true,
scrollback: 10_000,
});
const fit = new FitAddon();
term.loadAddon(fit);
+ term.loadAddon(new WebLinksAddon((_event, uri) => openTerminalLink(uri)));
+ term.attachCustomKeyEventHandler((event) => {
+ const action = resolveTerminalKeyAction(event);
+ if (!action) return true;
+ // Chromium maps βŒ˜β† to history-back, so an unclaimed key would navigate
+ // the SPA out from under the panel.
+ event.preventDefault();
+ switch (action.type) {
+ case 'focusSiblingPane': {
+ for (const listener of this.paneNavListeners) listener(sessionId, action.direction);
+ break;
+ }
+ case 'scrollPages': {
+ term.scrollPages(action.pages);
+ break;
+ }
+ case 'scrollToBottom': {
+ term.scrollToBottom();
+ break;
+ }
+ case 'scrollToTop': {
+ term.scrollToTop();
+ break;
+ }
+ case 'send': {
+ term.input(action.bytes);
+ break;
+ }
+ }
+ return false;
+ });
term.onData((data) => {
void electronTerminalService.writeSession({ data, id: sessionId });
});