From 1ff8fa351418d4705bd9e72ce54151fc11465f07 Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Mon, 5 Oct 2026 23:42:45 +0800 Subject: [PATCH] =?UTF-8?q?feat(terminal):=20=E5=BA=95=E9=83=A8=E5=B7=A5?= =?UTF-8?q?=E4=BD=9C=E5=8F=B0=E7=BB=88=E7=AB=AF=20tab=20terminal-bottom?= =?UTF-8?q?=EF=BC=88#774=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 底部 + 菜单里开得出 shell,刷新后认回同一个 shell,且**不**变成宿主 右列终端的第二个入口。 实现分三层: 1. 宿主能力层(src/client/terminal-client.ts,核心 bundle 安全):结构化 探测 `ctx.webTerminals`(view/close/recover 三个函数都在才算数)+ 身份助手。**不写进 dsh.client.inject**:注入一个不存在的服务会把整行 拖成 pending,插件在无终端控制器的部署上会整体不加载;也**不** value-import 任何 @deepseek-ai/*(纯度门),类型面手工声明。 2. chunk 层(src/client/TerminalView.tsx + terminal.module.css + chunks/terminal.tsx + terminal-lazy.tsx):xterm 与它的样式表整份打进 lib/client-terminal.js(750 KB),核心包一处都没有;chunk 名在 9 处 镜像(tsdown / bundle-route / chunk-loader / package.json.files / package-registry / bundle-route.spec),另两处 spec 从 CHUNK_NAMES 派生。 3. 描述符层(builtins/tabs.tsx):第 6 个内置类型,`bottomOnly: true` (见上一个 commit)、`single`、`available` 读同一份探测、`onClose` 结束进程。 三条恢复语义的由来: - **contentId 恒定,terminalId 不写进 tab.meta**:宿主 view() 显式传 terminalId 会关掉「缺了就建」分支,一个过期 id 会把页签永久卡在 missingTerminal;宿主自己的 (sessionId, contentId) → 终端 id 持久绑定 本来就能在刷新后认回同一个 shell。 - **「新建终端」换代号**:DSH 重启后 PTY 没了而 localStorage 绑定还在, 恒定 contentId 会永远认领死绑定。tab.meta.terminalRun(默认 0)+1 换 一代 contentId 让宿主另铸进程;key 与 contentId 一起换(views 按 (sessionId, key) 记忆化)。 - **关页签才结束进程**:宿主的契约是「视图跨 DOM 卸载存活」,这正是刷新 能认回同一个 shell 的原因,所以卸载不 close;但不 close 会让每个关掉 的终端永久占一个 per-session 终端槽位(terminalLimit),因此 descriptor 的 onClose → webTerminals.close() 是唯一且必须存在的回收路径。 测试(判别性证据见交付报告): - tests/terminal-tab.spec.tsx 14 条:view() 调用形状与 contentId 恒定性、 mount/detach、write/resize 转发与上限夹紧、snapshot 重放 + acknowledge、 无服务降级、missingTerminal → 换代号、onClose → close()。 - tests/builtins.spec.ts 内置清单 5 → 6,并新增「terminal-bottom 是 bottomOnly、其余内置都不是」。 - tests/chunk-artifact.spec.ts 新增产物包含性断言:chunk 里必须有 xterm(xterm-char-measure-element / @xterm/xterm/lib/xterm.js), lib/client.js 与 lib/client-registry.js 里一处都不许有。 - tests/e2e/mount.e2e.ts 第三条真实浏览器用例:先开原生右列(guide 基线 = 宿主 terminal 恰好 1 条)→ 展开底部工作台(data-active + 布局推挤 > 0)→ 点空面板的 Terminal 卡片 → 断言 tab 挂载、.xterm 在、chunk 有 响应、状态不停在 unavailable/loading、宿主 terminal 条目仍为 1 且 terminal-bottom 条目为 0、无 pageerror / 插件 console 错误。 依赖:@xterm/xterm@^6.0.0 + @xterm/addon-fit@^0.11.0(与宿主自用版本一致, 安装期零脚本,不触市场拒绝名单)。lockfile 只手工拼接这 2 个包的 4 个块: pnpm add 会顺手重解析无关 caret 范围,产出 99+/69- 的噪声 diff。 --- package.json | 3 + pnpm-lock.yaml | 16 + scripts/package-registry.mjs | 2 + src/bundle-route.ts | 2 +- src/client/TerminalView.tsx | 318 +++++++++++++++++++ src/client/builtins/index.ts | 7 +- src/client/builtins/tabs.tsx | 49 ++- src/client/chunk-loader.ts | 2 +- src/client/chunks/terminal.tsx | 9 + src/client/terminal-client.ts | 219 +++++++++++++ src/client/terminal-lazy.tsx | 16 + src/client/terminal.module.css | 92 ++++++ tests/builtins.spec.ts | 30 +- tests/bundle-route.spec.ts | 2 +- tests/chunk-artifact.spec.ts | 23 ++ tests/e2e/mount.e2e.ts | 190 ++++++++++-- tests/lazy-chunk.spec.tsx | 3 +- tests/terminal-tab.spec.tsx | 549 +++++++++++++++++++++++++++++++++ tsdown.config.ts | 2 +- 19 files changed, 1486 insertions(+), 48 deletions(-) create mode 100644 src/client/TerminalView.tsx create mode 100644 src/client/chunks/terminal.tsx create mode 100644 src/client/terminal-client.ts create mode 100644 src/client/terminal-lazy.tsx create mode 100644 src/client/terminal.module.css create mode 100644 tests/terminal-tab.spec.tsx diff --git a/package.json b/package.json index 4b5ad168..04f2d9ac 100644 --- a/package.json +++ b/package.json @@ -65,6 +65,7 @@ "lib/client-editor.js", "lib/client-locale.js", "lib/client-mermaid.js", + "lib/client-terminal.js", "lib/types/**/*.d.ts", "src", "scripts/install.sh", @@ -145,6 +146,8 @@ "@codemirror/view": "^6.43.8", "@deepseek-ai/schemastery": "^3.18.4", "@lezer/highlight": "^1.2.3", + "@xterm/addon-fit": "^0.11.0", + "@xterm/xterm": "^6.0.0", "clsx": "^2.1.1", "dompurify": "^3.4.14", "mermaid": "^11.16.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5e0ff35f..6fe33023 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -77,6 +77,12 @@ importers: '@lezer/highlight': specifier: ^1.2.3 version: 1.2.3 + '@xterm/addon-fit': + specifier: ^0.11.0 + version: 0.11.0 + '@xterm/xterm': + specifier: ^6.0.0 + version: 6.0.0 clsx: specifier: ^2.1.1 version: 2.1.1 @@ -1586,6 +1592,12 @@ packages: '@vitest/utils@4.1.11': resolution: {integrity: sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==} + '@xterm/addon-fit@0.11.0': + resolution: {integrity: sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==} + + '@xterm/xterm@6.0.0': + resolution: {integrity: sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==} + '@yuku-codegen/binding-android-arm64@0.8.7': resolution: {integrity: sha512-C/0zV5IhgVdYhGJTwrY0v8dknxlhiKwtVJkMUaexu9/QvRmzlV4vfU3hZlUSgqc2BxQHntL1mCVbDq8j0FRFDw==} cpu: [arm64] @@ -4761,6 +4773,10 @@ snapshots: convert-source-map: 2.0.0 tinyrainbow: 3.1.1 + '@xterm/addon-fit@0.11.0': {} + + '@xterm/xterm@6.0.0': {} + '@yuku-codegen/binding-android-arm64@0.8.7': optional: true diff --git a/scripts/package-registry.mjs b/scripts/package-registry.mjs index 43fe5d69..dfa3c474 100644 --- a/scripts/package-registry.mjs +++ b/scripts/package-registry.mjs @@ -41,6 +41,8 @@ const files = [ 'lib/client-mermaid.js.map', 'lib/client-locale.js', 'lib/client-locale.js.map', + 'lib/client-terminal.js', + 'lib/client-terminal.js.map', 'README.md', 'LICENSE', ] diff --git a/src/bundle-route.ts b/src/bundle-route.ts index 452fa012..72631b56 100644 --- a/src/bundle-route.ts +++ b/src/bundle-route.ts @@ -19,7 +19,7 @@ import { fileURLToPath } from 'node:url' import type { Context, SidebarHttpRequest, SidebarHttpResponse } from './context-types.ts' /** The chunk names the client may request (mirror of src/client/chunk-loader.ts). */ -export const CHUNK_NAMES = ['editor', 'mermaid', 'locale'] as const +export const CHUNK_NAMES = ['editor', 'mermaid', 'locale', 'terminal'] as const export type ChunkName = (typeof CHUNK_NAMES)[number] /** Directory of this host-half module (lib/ — the chunk scripts live next to it). */ diff --git a/src/client/TerminalView.tsx b/src/client/TerminalView.tsx new file mode 100644 index 00000000..10d6e666 --- /dev/null +++ b/src/client/TerminalView.tsx @@ -0,0 +1,318 @@ +/** + * The bottom workbench's terminal: an xterm.js emulator driven by the HOST's + * session-scoped terminal service (`ctx.webTerminals`, see + * ./terminal-client.ts). The plugin owns no PTY — the host keeps process + * lifetime, screen recovery and reconnection, and this view is only the + * emulator plus the command plumbing. + * + * This module is the LAZY CHUNK's payload (`src/client/chunks/terminal.tsx`): + * xterm is hundreds of KB, so it must never be reachable from the core + * bundle. `tsdown.config.ts` builds `lib/client-terminal.js`, and + * `tests/chunk-artifact.spec.ts` pins that xterm is inside the chunk and NOT + * inside `lib/client.js`. Never import this file from a core-bundle module — + * reach it through `lazyChunkComponent('terminal', …)` instead. + * + * The host's terminal model is frame-based, not a stream: + * + * - `view.state.render` holds the NEXT frame awaiting + * {@link HostTerminalView.acknowledge}; a `snapshot` frame carries the whole + * serialized screen and must be REPLAYED (reset + resize + write), an + * `output` frame is appended. The emulator's write callback is what releases + * the following frame, so an unacknowledged frame stops output for good. + * - `mount()` attaches the DOM lifetime and returns a DETACH callback: a + * remount (tab switch, panel collapse, session switch) re-attaches to the + * same live process. Unmounting must NOT close the terminal — the host's + * contract is "a view survives DOM unmount; its process only ends on + * explicit close", and it is what makes a reload restore the same shell. The + * descriptor's `onClose` is the one place that does close it. + * - The process identity is restored through the host's persisted + * `(sessionId, contentId) -> terminalId` binding, so the content identity + * must be STABLE across mounts ({@link bottomTerminalContentId}). "New + * terminal" deliberately mints a new one, because the old binding points at + * a process that is gone (host restart, terminal closed elsewhere) and + * reusing it would wedge the tab on `missingTerminal` forever. + * - `write` / `resize` go through the model (which serializes them and refuses + * them while the view is not writable), never straight to the remote — + * otherwise two windows' keystrokes would interleave. + * + * Colors come from theme tokens: the stylesheet paints the screen from + * `--dsw-*` / `--ds-*` and the concrete values are read back through + * `getComputedStyle`, the same token bridge `theme.ts` documents for xterm's + * palette. This module carries no color literal (`tests/theme.spec.ts`). + */ +import { FitAddon } from '@xterm/addon-fit' +import { Terminal } from '@xterm/xterm' +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useSyncExternalStore, type ReactNode } from 'react' +import '@xterm/xterm/css/xterm.css' +import type { Context } from '../context-types.ts' +import type { SessionScope } from './api.ts' +import type { SidebarTab } from './state.ts' +import { t } from './locales.ts' +import { isDarkScheme, subscribeColorScheme } from './theme.ts' +import { + bottomTerminalContentId, bottomTerminalKey, nextTerminalMeta, terminalRunOf, webTerminals, + type HostTerminalEnvironment, type HostTerminalView, type HostTerminalViewState, +} from './terminal-client.ts' +import css from './terminal.module.css' + +/** The props the bottom terminal view consumes from its tab descriptor. */ +export interface TerminalBottomProps { + ctx: Context + scope: SessionScope + tab: SidebarTab + visible: boolean +} + +/** + * Render the bottom workbench's terminal tab. + * @param props - the client context, the tab's session scope and visibility. + * @returns the terminal screen plus its status/degradation panels. + */ +export function TerminalBottomView({ ctx, scope, tab, visible }: TerminalBottomProps): ReactNode { + const sessionId = scope.sessionId + // The service is probed structurally, never injected: a deployment without + // it keeps the tray row disabled and renders the explanation below. + const service = useMemo(() => webTerminals(ctx), [ctx]) + const run = terminalRunOf(tab) + // `view()` allocates the terminal eagerly and memoizes one model per + // (session, key) on the host side, so this memo must be the ONLY creation + // path: a repeat `view()` for the same key is free, a new key is a new PTY. + const model = useMemo( + () => service?.view(sessionId, bottomTerminalKey(run), bottomTerminalContentId(run)), + [service, sessionId, run], + ) + const state = useSyncExternalStore( + useMemo(() => (callback: () => void) => model?.state.subscribe(callback) ?? (() => {}), [model]), + useCallback(() => model?.state.getSnapshot(), [model]), + ) + const scheme = useSyncExternalStore(subscribeColorScheme, isDarkScheme) + + // The DOM lifetime only — the detach leaves the shell running. The app's + // own teardown for the process is the descriptor's `onClose`. + useEffect(() => { + if (model === undefined) return + return model.mount() + }, [model]) + + const newTerminal = useCallback(() => { + // Writing the generation is what mints the replacement: the memo above + // rebuilds against a fresh content identity, so the host allocates a new + // terminal instead of adopting a binding whose process is gone. + ctx.get('betterSidebar')?.updateTab(tab.id, { meta: nextTerminalMeta(tab) }, sessionId) + }, [ctx, tab, sessionId]) + + if (service === undefined) { + return ( +
+

{t('terminalUnavailable')}

+
+ ) + } + if (model === undefined || state === undefined) return null + + const missing = state.issue === 'missingTerminal' + const ended = state.info?.state === 'exited' || state.phase === 'closed' + // The missing/ended panels carry their own message, so the pending-phase + // status line is only for a terminal that is still worth waiting on — + // without this gate a closed terminal would say "exited" twice. + const status = missing || ended ? undefined : statusOf(state) + + return ( +
+ {status !== undefined && ( +
+ {status} + {reconnectable(state) && ( + + )} +
+ )} + {(missing || ended) && ( +
+

+ {missing ? t('terminalGone') : t('exited')} +

+ +
+ )} + {state.info !== undefined && !missing && ( + + )} + {state.error !== undefined && state.issue === undefined && ( +

{t('terminalError')}: {state.error}

+ )} +
+ ) +} + +/** The one-line status for a view whose screen is not worth showing yet. */ +function statusOf(state: HostTerminalViewState): string | undefined { + switch (state.phase) { + case 'idle': + case 'loading': + case 'creating': + case 'connecting': + return t('loading') + case 'disconnected': + return t('disconnected') + case 'failed': + return t('terminalConnectFailed') + default: + return undefined + } +} + +/** + * Whether the retry affordance applies: the two phases that describe a + * terminal that exists but is not currently attached (an ended or missing + * terminal gets the "new terminal" action instead). + */ +function reconnectable(state: HostTerminalViewState): boolean { + return state.phase === 'failed' || state.phase === 'disconnected' +} + +interface TerminalScreenProps { + model: HostTerminalView + state: HostTerminalViewState + visible: boolean + scheme: boolean + label: string +} + +/** + * The emulator cell, mounted once the host reported a terminal and bound to + * the MODEL: a status change re-renders around it, only a new terminal + * (a "new terminal" mint, or the tab remounting) opens a new emulator. + */ +function TerminalScreen({ model, state, visible, scheme, label }: TerminalScreenProps): ReactNode { + const element = useRef(null) + const emulator = useRef(undefined) + const fit = useRef(undefined) + const lastRevision = useRef(0) + // Read inside the xterm effects without re-creating the emulator on every + // snapshot: the emulator is bound to the MODEL, the live flags are read + // through this ref (the host's own terminal body does exactly this). + const current = useRef({ state, visible }) + current.current = { state, visible } + + useLayoutEffect(() => { + const node = element.current + if (node === null) return + const xterm = new Terminal({ + // The screen element is painted from theme tokens; xterm needs the + // concrete stack, so read it back instead of hardcoding one. + fontFamily: getComputedStyle(node).fontFamily, + fontSize: 13, + minimumContrastRatio: 4.5, + cursorBlink: true, + scrollback: current.current.state.environment?.scrollback ?? 0, + }) + const addon = new FitAddon() + xterm.loadAddon(addon) + xterm.open(node) + xterm.textarea?.setAttribute('aria-label', label) + emulator.current = xterm + fit.current = addon + lastRevision.current = 0 + const input = xterm.onData((data) => { model.write(data) }) + const measure = (): void => { + const live = current.current + if (!live.visible || !live.state.writable || node.clientWidth === 0 || node.clientHeight === 0) return + fitScreen(xterm, addon, live.state.environment, model) + } + // jsdom has no ResizeObserver; the explicit fit effect below still applies. + const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(measure) + observer?.observe(node) + return () => { + observer?.disconnect() + input.dispose() + xterm.dispose() + emulator.current = undefined + fit.current = undefined + } + }, [model, label]) + + // xterm takes concrete colors, so they are read off the screen element the + // stylesheet paints from tokens (the bridge theme.ts documents). A scheme + // flip, or a new terminal, re-reads them in place. + useLayoutEffect(() => { + const node = element.current + const xterm = emulator.current + if (node === null || xterm === undefined) return + const style = getComputedStyle(node) + xterm.options.theme = { + background: style.backgroundColor, + foreground: style.color, + cursor: style.color, + cursorAccent: style.backgroundColor, + selectionBackground: style.color, + selectionForeground: style.backgroundColor, + } + }, [scheme, model, state.phase]) + + // The frame protocol: replay a snapshot, append output, then ACK — the host + // holds the next frame until this write's callback runs. + useLayoutEffect(() => { + const xterm = emulator.current + const render = state.render + if (xterm === undefined || render === undefined || render.revision <= lastRevision.current) return + lastRevision.current = render.revision + if (render.frame.type === 'snapshot') { + xterm.reset() + xterm.resize(render.frame.info.cols, render.frame.info.rows) + } + xterm.write(render.frame.type === 'snapshot' ? render.frame.screen : render.frame.data, () => { + model.acknowledge(render.revision) + }) + }, [state.render, model]) + + // Size and input control both follow the view state: fitting a view that + // does not hold control would fight the window that does. Read the fields + // out first so the effect's dependency list is exactly what it uses. + const { writable, environment, info } = state + useLayoutEffect(() => { + const xterm = emulator.current + if (xterm === undefined) return + xterm.options.disableStdin = !writable + if (visible && writable) fitScreen(xterm, fit.current, environment, model) + else if (info !== undefined && !writable) xterm.resize(info.cols, info.rows) + }, [visible, writable, environment, info, model]) + + useEffect(() => { + if (visible && writable) emulator.current?.focus() + }, [visible, writable]) + + return
+} + +/** + * Fit the emulator to its box and publish the size, clamped to the host's + * per-terminal limits (a size the host refuses would leave the shell's own + * idea of the window wrong). + */ +function fitScreen( + xterm: Terminal, + addon: FitAddon | undefined, + environment: HostTerminalEnvironment | undefined, + model: HostTerminalView, +): void { + const dimensions = addon?.proposeDimensions() + if (dimensions === undefined || environment === undefined) return + const cols = Math.min(dimensions.cols, environment.maxCols) + const rows = Math.min(dimensions.rows, environment.maxRows) + if (cols < 2 || rows < 1) return + xterm.resize(cols, rows) + model.resize(cols, rows) +} diff --git a/src/client/builtins/index.ts b/src/client/builtins/index.ts index f1c96a96..1b55738e 100644 --- a/src/client/builtins/index.ts +++ b/src/client/builtins/index.ts @@ -14,15 +14,16 @@ import { builtinViewers } from './viewers.tsx' /** * Register all built-in tabs and viewers with the service. Returns a * disposer that unregisters everything (cordis auto-invokes it on fiber - * disposal). The `ctx` is threaded into tab descriptors that need it - * (EditorHost reads `ctx.betterSidebar` for file-viewer matching). + * disposal). The `ctx` is threaded into the descriptor factory that needs it + * (the bottom terminal's `onClose` probes `ctx.webTerminals` to end the host + * process; components read `ctx.betterSidebar` from their props). */ export function registerBuiltins( ctx: Context, service: BetterSidebarService, ): () => void { const disposers: (() => void)[] = [] - for (const tab of builtinTabs()) { + for (const tab of builtinTabs(ctx)) { disposers.push(service.registerTab(tab)) } for (const viewer of builtinViewers()) { diff --git a/src/client/builtins/tabs.tsx b/src/client/builtins/tabs.tsx index 4761dce0..e9f25bbe 100644 --- a/src/client/builtins/tabs.tsx +++ b/src/client/builtins/tabs.tsx @@ -1,6 +1,6 @@ /** * The built-in tab descriptors: the plugin registers its own pages - * (editor / git — the unified changes tab / subagent / sidechat / browser / + * (editor / git — the unified changes tab / subagent / sidechat / terminal-bottom / * diff) through * the same {@link BetterSidebarService} external plugins use — eating its * own dogfood. The editor IS the files window (the old standalone explorer @@ -11,10 +11,16 @@ * interactive shells outright, and the host's `browser` kind (delegated to * from the chat's http(s) links) owns embedded pages. See * docs/plans/2026-09-21-dsh-0.1.6-alpha.2-adaptation.md. + * + * `terminal-bottom` (#774) is the one type that is NOT a host tab: it is the + * plugin's own bottom workbench terminal, driving the host's session-scoped + * terminal service through a self-drawn xterm. It declares `bottomOnly` so it + * can never become a second right-Sidebar terminal capsule beside the host's + * own. See docs/plans/2026-10-05-bottom-terminal-tab.md. */ import { IconCodeOutlineRegular, IconPanelLeftOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import { - changesTabIcon, filesTabIcon, sidechatTabIcon, tasksTabIcon, + changesTabIcon, filesTabIcon, sidechatTabIcon, tasksTabIcon, terminalTabIcon, } from './tab-icons.tsx' import { t } from '../locales.ts' import { openSidebarFile } from '../sidebar-file.ts' @@ -25,11 +31,14 @@ import { ChangesTab, opCountOf } from '../changes/ChangesTab.tsx' import { DiffTab } from '../DiffTab.tsx' import { SubagentView } from '../SubagentView.tsx' import { consumeSidechatSeed, SideChatView, sidechatThreadIdOf } from '../SideChatView.tsx' +import { LazyTerminalBottom } from '../terminal-lazy.tsx' +import { closeBottomTerminal, webTerminals } from '../terminal-client.ts' import { api } from '../api.ts' +import type { Context } from '../../context-types.ts' import type { TabDescriptor } from '../service.ts' -/** The 5 built-in tab descriptors (the host owns terminal and browser). */ -export function builtinTabs(): readonly TabDescriptor[] { +/** The 6 built-in tab descriptors (the host owns the right-Sidebar terminal and browser). */ +export function builtinTabs(ctx: Context): readonly TabDescriptor[] { return [ { id: 'editor', @@ -230,6 +239,38 @@ export function builtinTabs(): readonly TabDescriptor[] { ), }, + { + // The bottom workbench's terminal (#774). NOT the host's right-Sidebar + // terminal: the plugin owns no PTY, this page is a self-drawn xterm + // driven by the host's session-scoped terminal service + // (src/client/terminal-client.ts), and the two terminals are separate + // processes on purpose. `bottomOnly` is what keeps this type out of the + // host's guide — a second "Terminal" capsule there would be the + // shadowing the mount lane pins as absent. + id: 'terminal-bottom', + title: () => t('terminal'), + description: () => t('guideDescTerminal'), + icon: terminalTabIcon, + // Below the four host-facing pages (10..35) and above the hidden diff + // tab: the terminal is a secondary tool, but a visible menu row. + order: 40, + bottomOnly: true, + // One terminal per session workbench: reopening focuses the live tab. + single: true, + // The service is probed, never injected (it is absent on deployments + // without the host terminal controller): a missing service shows a + // disabled menu row instead of a terminal that cannot start. + available: (ctx) => webTerminals(ctx) !== undefined, + // The bottom terminal never declares a title override: the tab strip + // reads the descriptor's own title. + component: LazyTerminalBottom, + // Unmounting the view deliberately leaves the shell running (the host's + // "a view survives DOM unmount" contract, and what makes a reload + // reattach), so closing the TAB is the only thing that ends the process + // — without it every closed bottom terminal would hold one of the host's + // per-session terminal slots forever. + onClose: (tab, scope) => { closeBottomTerminal(ctx, tab, scope?.sessionId ?? '') }, + }, { id: 'diff', title: () => t('changes'), diff --git a/src/client/chunk-loader.ts b/src/client/chunk-loader.ts index 8055dd41..1b6ad2a2 100644 --- a/src/client/chunk-loader.ts +++ b/src/client/chunk-loader.ts @@ -52,7 +52,7 @@ */ import { hostRouteUrl } from './host-route-url.ts' -export type ChunkName = 'editor' | 'mermaid' | 'locale' +export type ChunkName = 'editor' | 'mermaid' | 'locale' | 'terminal' /** The module exports a chunk factory provides (namespace-ish record). */ export type ChunkExports = Record diff --git a/src/client/chunks/terminal.tsx b/src/client/chunks/terminal.tsx new file mode 100644 index 00000000..27d9db32 --- /dev/null +++ b/src/client/chunks/terminal.tsx @@ -0,0 +1,9 @@ +/** + * Lazy chunk entry: the bottom workbench's terminal emulator (xterm.js + the + * fit addon, several hundred KB). Built as `lib/client-terminal.js` and + * registered under the `terminal` global chunk slot — fetched only when the + * bottom tray's terminal tab is first opened (see chunk-loader.ts and + * src/client/TerminalView.tsx). Never import this module from the core bundle: + * it pulls xterm into the startup path. + */ +export { TerminalBottomView } from '../TerminalView.tsx' diff --git a/src/client/terminal-client.ts b/src/client/terminal-client.ts new file mode 100644 index 00000000..8a52b882 --- /dev/null +++ b/src/client/terminal-client.ts @@ -0,0 +1,219 @@ +/** + * The plugin's structural read of the HOST's browser terminal service + * (`ctx.webTerminals`, provided by `@deepseek-ai/dsh-api-terminal-controller`'s + * client half on the web profile). + * + * The plugin does NOT own a PTY stack any more (v0.21.1 yielded the terminal to + * DSH's own right-Sidebar type): the bottom workbench's terminal drives the + * host's session-scoped terminals through this service, and the host keeps + * process lifetime, screen recovery and reconnection. + * + * Detection is STRUCTURAL and by name only — the plugin never imports the host + * package (the client-bundle purity gate forbids `@deepseek-ai/*` value + * imports outside the platform module table), and `webTerminals` is + * deliberately NOT in `package.json#dsh.client.inject`: a deployment without + * the service must still activate the plugin (a missing injected service leaves + * the whole row `pending`), so the terminal tab degrades instead. + * + * The shapes mirror the pinned host package (`dsh-api-terminal-controller` + * 0.2.0-rc.1, `lib/types/client/{index,model}.d.ts` + `lib/types/types.d.ts`): + * + * - `view(sessionId, key, contentId, terminalId?, shellPath?)` returns the + * STABLE model for one occurrence (`key` memoizes it; repeating a call is + * free) and allocates the terminal eagerly on first call. `contentId` is the + * persistence key: the service remembers `(sessionId, contentId) -> host + * terminal id` in `localStorage`, so passing the same `contentId` after a + * page reload ADOPTS the saved process instead of allocating a new one — + * unless an explicit `terminalId` is given, which wins. + * - `mount()` attaches the DOM lifetime and returns a DETACH callback; the + * process survives unmount (only `close()` ends it). + * - `state.render` is the next screen frame awaiting + * {@link HostTerminalView.acknowledge}; the service will not publish the + * following frame until it is acknowledged, so the emulator's write callback + * is what releases the stream. + * - `write` / `resize` are refused unless the view is currently `writable` + * (the host serializes input across windows per attachment). + */ +import type { Context } from '../context-types.ts' + +/** A host terminal identity, unique per Session and host lifetime. */ +export type WebTerminalId = string + +/** Host-owned terminal state; process exit never creates a replacement shell. */ +export interface HostTerminalInfo { + readonly id: WebTerminalId + readonly title: string + /** Initial working directory; a shell's own `cd` does not update it. */ + readonly cwd: string + readonly cols: number + readonly rows: number + readonly state: 'running' | 'exited' | 'failed' + readonly exitCode: number | null + readonly error?: string +} + +/** Working directory and limits shared by new and restored terminals. */ +export interface HostTerminalEnvironment { + readonly cwd: string + readonly maxInputBytes: number + readonly maxCols: number + readonly maxRows: number + readonly scrollback: number +} + +/** + * Every attachment begins with a complete bounded screen (the host serializes + * the emulator's screen), then ordered output; `state` frames only carry + * metadata. This is why the view REPLAYS `screen` rather than appending it. + */ +export type HostTerminalFrame = + | { readonly type: 'snapshot'; readonly sequence: number; readonly screen: string; readonly info: HostTerminalInfo } + | { readonly type: 'output'; readonly sequence: number; readonly data: string } + | { readonly type: 'state'; readonly info: HostTerminalInfo } + +/** Product error identifiers the host terminals UI translates. */ +export type HostTerminalIssue = 'missingTerminal' | 'inputFull' | 'attachmentEnded' | 'invalidOutput' | 'terminalLimit' + +/** + * The two frame kinds that carry screen content. The host's render slot is + * `Extract`: a `state` frame is + * metadata only and never reaches the emulator. + */ +export type HostRenderFrame = Extract + +/** Observable state of one occurrence. */ +export interface HostTerminalViewState { + readonly phase: 'idle' | 'loading' | 'creating' | 'connecting' | 'connected' | 'disconnected' | 'closing' | 'closed' | 'failed' + readonly environment?: HostTerminalEnvironment | undefined + readonly title?: string | undefined + readonly info?: HostTerminalInfo | undefined + /** Whether this view currently holds input/resize control. */ + readonly writable: boolean + /** The next screen frame awaiting {@link HostTerminalView.acknowledge}. */ + readonly render?: { readonly revision: number; readonly frame: HostRenderFrame } | undefined + readonly error?: string | undefined + readonly issue?: HostTerminalIssue | undefined +} + +/** The host's observable snapshot store face (a subset of `SnapshotStore`). */ +export interface HostSnapshot { + getSnapshot(): T + subscribe(listener: () => void): () => void +} + +/** One terminal occurrence's model. A view survives DOM unmount. */ +export interface HostTerminalView { + readonly id: WebTerminalId + readonly state: HostSnapshot + /** Attach the DOM lifetime; the returned detach leaves the process alive. */ + mount(): () => void + /** Start or recover this tab (deduplicated by the service). */ + refresh(): Promise + /** Reattach with a fresh screen and regain input control. */ + connect(): void + /** Release the next stream item after the emulator parsed this frame. */ + acknowledge(revision: number): void + /** Serialize raw input (refused unless writable). */ + write(data: string): void + /** Resize only from the currently writable view. */ + resize(cols: number, rows: number): void + /** Terminate the process; the DOM lifetime is irrelevant to it. */ + close(): Promise +} + +/** The service slice this plugin consumes. */ +export interface WebTerminalsFace { + view( + sessionId: string, + key: string, + contentId: string, + terminalId?: WebTerminalId, + shellPath?: string, + ): HostTerminalView + /** + * Save a close intent, release the occurrence immediately and drop the + * `(sessionId, contentId)` binding; the process cleanup outlives DOM + * unmount and a page reload (the plugin's tab `onClose`). + */ + close(sessionId: string, key: string, contentId: string, terminalId?: WebTerminalId): void + /** Query host terminals without a live view or unfinished close. */ + recover(sessionId: string): Promise +} + +/** + * The host terminal service, when this deployment mounts it. + * + * Structural detection (`view` + `close` + `recover` are the members this + * plugin calls); a service that does not look like the pinned contract reads + * as absent rather than throwing at the first keystroke. + * @param ctx - the client context. + */ +export function webTerminals(ctx: Context): WebTerminalsFace | undefined { + const service = ctx.get('webTerminals') as unknown as Partial | undefined + if (service === undefined || service === null) return undefined + if (typeof service.view !== 'function' || typeof service.close !== 'function') return undefined + if (typeof service.recover !== 'function') return undefined + return service as WebTerminalsFace +} + +/** Namespace for the plugin's own occurrence key and content identity. */ +const TERMINAL_NS = 'dsh-better-sidebar:terminal-bottom' + +/** The persisted `tab.meta` field holding the content-identity generation. */ +const RUN_FIELD = 'terminalRun' + +/** + * The content identity of the bottom terminal at `run`. + * + * The host keys its recovery binding on `(sessionId, contentId)`, so a stable + * value is what makes a page reload adopt the SAME host terminal instead of + * allocating a new one. A "new terminal" (the run bump) deliberately changes + * it: the old binding points at a process that is gone — a host restart, or a + * terminal closed elsewhere — and reusing it would wedge the tab on + * `missingTerminal` forever. + * @param run - the content-identity generation (0 for a tab's first terminal). + */ +export function bottomTerminalContentId(run: number): string { + return run === 0 ? TERMINAL_NS : `${TERMINAL_NS}#${run}` +} + +/** + * The occurrence key: what the host service memoizes one `TerminalView` by, + * per session. It equals the content identity so both move together when a + * replacement terminal is minted, and it is namespaced so it can never collide + * with a host sidebar occurrence key (those are layout tab ids such as `tab1`). + * @param run - the content-identity generation. + */ +export function bottomTerminalKey(run: number): string { + return bottomTerminalContentId(run) +} + +/** The content-identity generation a tab carries (absent/corrupt reads as 0). */ +export function terminalRunOf(tab: { meta?: unknown }): number { + const meta = tab.meta !== null && typeof tab.meta === 'object' && !Array.isArray(tab.meta) + ? tab.meta as Record + : {} + const run = meta[RUN_FIELD] + return typeof run === 'number' && Number.isSafeInteger(run) && run >= 0 ? run : 0 +} + +/** The `tab.meta` patch that mints the tab's next terminal. */ +export function nextTerminalMeta(tab: { meta?: unknown }): Record { + return { [RUN_FIELD]: terminalRunOf(tab) + 1 } +} + +/** + * End the tab's host terminal (the descriptor's `onClose`). Unmounting the + * view deliberately does NOT do this — that is the host's "a view survives DOM + * unmount" contract, and it is what lets a reload reattach — so without this + * every closed bottom terminal would leave its shell running invisibly. + * @param ctx - the client context. + * @param tab - the closing tab (its `meta` names the content identity). + * @param sessionId - the tab's session. + */ +export function closeBottomTerminal(ctx: Context, tab: { meta?: unknown }, sessionId: string): void { + const service = webTerminals(ctx) + if (service === undefined) return + const run = terminalRunOf(tab) + service.close(sessionId, bottomTerminalKey(run), bottomTerminalContentId(run)) +} diff --git a/src/client/terminal-lazy.tsx b/src/client/terminal-lazy.tsx new file mode 100644 index 00000000..664fbfb7 --- /dev/null +++ b/src/client/terminal-lazy.tsx @@ -0,0 +1,16 @@ +/** + * The chunk-resident bottom terminal (xterm lazy chunk): a light stub module + * so the core-bundle descriptor can mount the terminal view without statically + * pulling xterm (and the xterm stylesheet) into the startup path. The chunk + * itself (src/client/chunks/terminal) loads on first render via + * /sidebar/bundle. + */ +import type { ComponentType } from 'react' +import { lazyChunkComponent } from './lazy-chunk.tsx' +import type { TerminalBottomProps } from './TerminalView.tsx' + +/** The terminal view, deferred until its tab is first mounted. */ +export const LazyTerminalBottom = lazyChunkComponent( + 'terminal', + (mod) => mod.TerminalBottomView as ComponentType | undefined, +) diff --git a/src/client/terminal.module.css b/src/client/terminal.module.css new file mode 100644 index 00000000..4a9462ef --- /dev/null +++ b/src/client/terminal.module.css @@ -0,0 +1,92 @@ +/* + * The bottom terminal's shell (src/client/TerminalView.tsx). + * + * Skin contract (guide §12): every declaration resolves to a `--dsw-*` / + * `--ds-*` token, and `color` never carries a literal — `tests/theme.spec.ts` + * enforces the second half mechanically. The screen element is also the token + * BRIDGE for xterm's own palette: the component reads its computed + * `background-color` / `color` / `font-family` back and hands those concrete + * values to the emulator, so a skin flip re-themes the terminal in place. + */ + +.root { + display: flex; + flex: 1; + flex-direction: column; + box-sizing: border-box; + height: 100%; + min-height: 0; + color: var(--dsw-alias-label-primary); +} + +.screen { + flex: 1; + min-width: 0; + min-height: 0; + padding: 8px; + overflow: hidden; + color: var(--dsw-alias-label-primary); + background: var(--dsw-alias-bg-base); + font-family: var(--ds-font-family-code, monospace); +} + +.screen .xterm { + height: 100%; +} + +.screen .xterm-viewport { + background: var(--dsw-alias-bg-base); +} + +.status { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + padding: 5px 12px; + color: var(--dsw-alias-label-secondary, var(--dsw-alias-label-primary)); + background: var(--dsw-alias-bg-l2); +} + +.noticeBlock { + display: flex; + flex: 1; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 16px; + min-height: 0; + padding: 24px; + overflow: auto; +} + +.notice { + max-width: 32ch; + margin: 0; + line-height: 1.6; + text-align: center; + overflow-wrap: anywhere; + color: var(--dsw-alias-label-primary); +} + +.error { + margin: 0; + padding: 10px 12px; + overflow-wrap: anywhere; + color: var(--dsw-alias-label-primary); + background: var(--dsw-alias-bg-l2); +} + +.action { + flex: none; + padding: 3px 10px; + border: 0.5px solid var(--dsw-alias-border-l4); + border-radius: 6px; + cursor: pointer; + color: var(--dsw-alias-label-primary); + background: var(--dsw-alias-bg-layer-1); +} + +.action:hover { + background: var(--dsw-alias-bg-l2); +} diff --git a/tests/builtins.spec.ts b/tests/builtins.spec.ts index b49a4848..3ae04f4c 100644 --- a/tests/builtins.spec.ts +++ b/tests/builtins.spec.ts @@ -1,5 +1,5 @@ /** - * Built-in registration tests: the plugin registers 5 tabs and 3 file + * Built-in registration tests: the plugin registers 6 tabs and 3 file * viewers through the same service external plugins use (dogfooding); * the catch-all `code` viewer and the html sandbox settings pin the * registry's behavior. The read-only previews (image / pdf / @@ -9,6 +9,10 @@ * already NOT built in — they moved to the recommended office plugin, * see src/client/plugins-viewers.ts.) The git tab is the unified changes * tab (git lens + session lens, PR #471's file-trace merged in). + * + * `terminal-bottom` (#774) is the sixth: the plugin's OWN bottom-workbench + * terminal, which is `bottomOnly` and therefore contributes no native tab + * type. It is the one built-in whose carrier surface is asserted here. */ import { describe, expect, it } from 'vitest' import type { ReactElement } from 'react' @@ -31,13 +35,33 @@ function setup(): { service: ReturnType; stor } describe('built-in tab registrations', () => { - it('registers the 5 built-in tabs (the host owns terminal and browser)', () => { + it('registers the 6 built-in tabs (the host owns the right-sidebar terminal and browser)', () => { const { service } = setup() expect(service.getTabs().map(t => t.id).sort()).toEqual( - ['diff', 'editor', 'git', 'sidechat', 'subagent'], + ['diff', 'editor', 'git', 'sidechat', 'subagent', 'terminal-bottom'], ) }) + it('the terminal tab is bottom-only and never claims a native right-sidebar type', () => { + // #774 / AGENTS §2: DSH's own right Sidebar already offers exactly one + // `terminal` entry, and the mount lane pins that count. A plugin type that + // also reached the native surface would add a second capsule for a page + // the host's column cannot draw; `bottomOnly` is the whole mechanism. + const { service } = setup() + const terminal = service.getTab('terminal-bottom') + expect(terminal).toBeDefined() + expect(terminal?.bottomOnly).toBe(true) + // Visible in the bottom + menu (hidden would remove it from the menu). + expect(terminal?.hidden).not.toBe(true) + expect(terminal?.icon).toBeDefined() + expect(terminal?.component).toBeDefined() + // Every other built-in keeps both surfaces. + for (const descriptor of service.getTabs()) { + if (descriptor.id === 'terminal-bottom') continue + expect(descriptor.bottomOnly, descriptor.id).not.toBe(true) + } + }) + it('the git (changes) tab is a single-instance badge-carrying visible tab', () => { const { service } = setup() const changes = service.getTab('git') diff --git a/tests/bundle-route.spec.ts b/tests/bundle-route.spec.ts index 6fc73968..2e55fada 100644 --- a/tests/bundle-route.spec.ts +++ b/tests/bundle-route.spec.ts @@ -150,6 +150,6 @@ describe('/sidebar/bundle route', () => { }) it('exports the chunk allowlist (mirror of src/client/chunk-loader.ts)', () => { - expect([...CHUNK_NAMES]).toEqual(['editor', 'mermaid', 'locale']) + expect([...CHUNK_NAMES]).toEqual(['editor', 'mermaid', 'locale', 'terminal']) }) }) diff --git a/tests/chunk-artifact.spec.ts b/tests/chunk-artifact.spec.ts index d6d6e8be..33c8efb6 100644 --- a/tests/chunk-artifact.spec.ts +++ b/tests/chunk-artifact.spec.ts @@ -60,4 +60,27 @@ describe.skipIf(!chunksBuilt)('built chunk artifacts', () => { }), name).not.toThrow() } }) + + /** + * The emulator's own DOM contract, present in xterm's runtime source AND in + * its stylesheet — either half landing in the core bundle means the lazy + * split broke. `@xterm/xterm` alone would be too weak a probe: the package + * NAME also shows up in doc comments and locale copy. + */ + const XTERM_MARKER = 'xterm-char-measure-element' + + it('the terminal chunk carries xterm and the core bundles carry none of it', () => { + // #774's whole build requirement: several hundred KB of emulator must not + // reach startup. The core bundle is what the plugin ships to every page + // load, so a static import of src/client/TerminalView.tsx (or of the + // xterm stylesheet) from a core module would show up here. + const chunk = readFileSync('lib/client-terminal.js', 'utf8') + expect(chunk).toContain(XTERM_MARKER) + expect(chunk).toContain('@xterm/xterm/lib/xterm.js') + for (const file of ['lib/client.js', 'lib/client-registry.js']) { + const source = readFileSync(file, 'utf8') + expect(source, `${file} must not bundle xterm`).not.toContain(XTERM_MARKER) + expect(source, `${file} must not resolve @xterm/xterm`).not.toContain('@xterm/xterm') + } + }) }) diff --git a/tests/e2e/mount.e2e.ts b/tests/e2e/mount.e2e.ts index 80304a93..b5756fab 100644 --- a/tests/e2e/mount.e2e.ts +++ b/tests/e2e/mount.e2e.ts @@ -30,7 +30,7 @@ import { mkdirSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { test, expect, type APIRequestContext } from '@playwright/test' +import { test, expect, type APIRequestContext, type Page } from '@playwright/test' import { PAGE_URL, createHostApi, gotoPage, hostRpc, sendFirstMessage, sidebarApi } from './host' /** Workspace the sidebar renders against (created by the lane's seeding). */ @@ -155,6 +155,45 @@ test.beforeAll(async () => { await seedSession() }) +/** + * Dismiss the keyless boot's onboarding takeovers, which mask the whole shell: + * a versioned welcome notice ("Continue", persists its acknowledgement to + * settings) and, once that is acknowledged, a provider-config dialog + * ("Configure later", session-only — always present while no credential is + * configured). Both mount only after the settings join resolves. Wait + * (bounded) for one to appear; a DSH build without onboarding proceeds + * straight on. + * + * Dismissal loops until none remain, in any stacking order — a masked click is + * retried next round instead of failing. + * @param page - the lane's page. + */ +async function dismissOnboarding(page: Page): Promise { + try { + await expect + .poll(() => page.getByRole('button', { name: /^(Continue|Configure later)$/ }).count(), { timeout: 60_000 }) + .toBeGreaterThan(0) + } catch { + console.warn('[e2e] no onboarding takeover appeared; proceeding without dismissal') + } + for (let round = 0; round < 8; round++) { + let dismissed = false + for (const name of ['Continue', 'Configure later']) { + const button = page.getByRole('button', { name, exact: true }).first() + if ((await button.count()) === 0) continue + try { + await button.click({ timeout: 4_000 }) + dismissed = true + await page.waitForTimeout(1_000) + } catch { + // Masked by the takeover stacked above it; the next round tries the + // other button first. + } + } + if (!dismissed) break + } +} + test.afterAll(async () => { await api?.dispose() }) @@ -195,38 +234,9 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async expect(hostZ).toBeGreaterThan(20) expect(hostZ).toBeLessThan(30) - // A keyless boot stacks onboarding takeovers that mask the whole shell: a - // versioned welcome notice ("Continue", persists its acknowledgement to - // settings) and, once that is acknowledged, a provider-config dialog - // ("Configure later", session-only — always present while no credential is - // configured). Both mount only after the settings join resolves. Wait - // (bounded) for one to appear; a DSH build without onboarding proceeds - // straight to the sweep. - try { - await expect - .poll(() => page.getByRole('button', { name: /^(Continue|Configure later)$/ }).count(), { timeout: 60_000 }) - .toBeGreaterThan(0) - } catch { - console.warn('[e2e] no onboarding takeover appeared; proceeding without dismissal') - } - // Dismiss whatever takeover is present, in any stacking order, until none - // remain — a masked click is retried next round instead of failing. - for (let round = 0; round < 8; round++) { - let dismissed = false - for (const name of ['Continue', 'Configure later']) { - const button = page.getByRole('button', { name, exact: true }).first() - if ((await button.count()) === 0) continue - try { - await button.click({ timeout: 4_000 }) - dismissed = true - await page.waitForTimeout(1_000) - } catch { - // Masked by the takeover stacked above it; the next round tries the - // other button first. - } - } - if (!dismissed) break - } + // A keyless boot stacks onboarding takeovers that mask the whole shell; see + // dismissOnboarding. + await dismissOnboarding(page) // The seeded session must give the sidebar a session scope: without it the // workbench has no pane to render and the tab sweep is impossible. @@ -648,6 +658,120 @@ test('plugin mounts into the DSH shell and survives a built-in tab sweep', async await page.screenshot({ path: 'test-results/mount-final.png' }) }) +test('the bottom workbench opens the plugin terminal (#774) without shadowing the host terminal', async ({ page }) => { + // The bottom terminal is the ONE plugin page that is not a native tab type + // (`bottomOnly`): it draws its own xterm against the host's session-scoped + // terminal service. Two things must hold at once in a real browser — + // - the tab opens, mounts a real emulator and the chunk is fetched from + // /sidebar/bundle/terminal.js, with no console error or pageerror, and + // - DSH's own right-Sidebar `terminal` capsule is STILL exactly one: the + // plugin must not be shadowing the host again (AGENTS §2). + const pageErrors: string[] = [] + const consoleErrors: string[] = [] + page.on('pageerror', (error) => pageErrors.push(String(error))) + page.on('console', (message) => { + if (message.type() === 'error') consoleErrors.push(message.text()) + }) + + const terminalChunk = page.waitForResponse( + (response) => response.url().includes('/sidebar/bundle/terminal.js'), + { timeout: 120_000 }, + ) + await page.goto(PAGE_URL, { waitUntil: 'domcontentloaded' }) + await expect(page.locator('#root > *')).not.toHaveCount(0, { timeout: 90_000 }) + const sidebar = page.locator('[data-dsh-better-sidebar]') + await expect(sidebar).toBeAttached({ timeout: 90_000 }) + await dismissOnboarding(page) + + // The seeded session already has content — the header's workbench toggle is + // registered into DSH's session-header utilities, which render only for such + // a session. Open the native right column FIRST: the guide below is what the + // shadowing assertion reads, and the bottom panel anchors itself to the + // center column DSH's AppFrame lays out between the two sidebars, so the + // column has to be in its settled geometry before the panel measures it. + await sendFirstMessage(page) + await page.locator('[data-sidebar-right-expand]').first().click() + const guide = page.locator('[data-sidebar-right-guide]') + await expect(guide).toBeVisible({ timeout: 60_000 }) + const hostTerminalEntry = page.locator('[data-sidebar-right-guide-entry="terminal"]') + await expect( + hostTerminalEntry, + 'the host terminal capsule must exist before the plugin one (baseline)', + ).toHaveCount(1, { timeout: 30_000 }) + + // The workbench toggle is a TOGGLE, and a session that already shows its + // seeded editor tab is open on arrival — clicking unconditionally would + // collapse it, and every later query would then measure the slid-off + // (translateY(102%)) panel. + const bottomExpand = page.locator('[data-dsh-bottom-toggle]:visible').first() + await expect(bottomExpand).toBeAttached({ timeout: 60_000 }) + if ((await bottomExpand.getAttribute('data-active')) !== 'true') await bottomExpand.click() + await expect(bottomExpand, 'the workbench must end up expanded').toHaveAttribute('data-active', 'true', { timeout: 30_000 }) + // The layout push is the expanded state's own observable: it is 0 while the + // workbench is closed (`bottomPushHeight`), so this also proves the panel is + // on screen rather than mid-slide. + await expect + .poll( + () => page.evaluate(() => Number.parseFloat( + document.documentElement.style.getPropertyValue('--dsh-sidebar-height'), + ) || 0), + { timeout: 60_000 }, + ) + .toBeGreaterThan(0) + const bottomPanel = page.locator('[data-dsh-bottom-panel]') + await expect(bottomPanel).toBeVisible({ timeout: 30_000 }) + + // The workbench's NEW-TAB surface is what must offer the type. An empty pane + // renders one card per openable type (`PaneEmptyCards`), fed by the very + // same `buildNewTabOptions` list as the + menu — so a `Terminal` card here + // is the same registration evidence, and unlike the + button it cannot be + // pushed out of the viewport by the strip's own scrollport. + const terminalCard = bottomPanel.getByRole('button', { name: 'Terminal', exact: true }) + await expect( + terminalCard, + 'the bottom workbench must offer the plugin terminal as an openable type', + ).toHaveCount(1, { timeout: 30_000 }) + await terminalCard.click() + + const terminal = bottomPanel.locator('[data-dsh-bottom-terminal]') + await expect(terminal, 'the bottom terminal view must mount').toHaveCount(1, { timeout: 30_000 }) + await expect( + terminal.locator('.xterm'), + 'a real xterm emulator must be attached (the chunk materialized)', + ).toHaveCount(1, { timeout: 60_000 }) + await terminalChunk + // The host service is mounted on the web profile, so the view leaves its + // pending phases; a PTY the sandbox refuses still ends in a terminal state + // (failed/disconnected), which the status line reports rather than crashes. + await expect + .poll(async () => terminal.getAttribute('data-terminal-state'), { timeout: 60_000 }) + .not.toBe('unavailable') + expect( + await terminal.getAttribute('data-terminal-state'), + 'the terminal must not wedge in a pending phase', + ).not.toBe('loading') + + // Shadowing check: the plugin's entry is bottom-only, so the host's own + // guide STILL lists exactly one `terminal` capsule — with the plugin's + // terminal now open beside it — and never one for `terminal-bottom`. + await expect( + hostTerminalEntry, + 'the plugin must not shadow the host terminal', + ).toHaveCount(1, { timeout: 30_000 }) + await expect( + page.locator('[data-sidebar-right-guide-entry="terminal-bottom"]'), + 'a bottom-only type must never take a guide slot', + ).toHaveCount(0) + await expect(guide).toBeVisible() + + expect(pageErrors, 'pageerrors during the terminal open').toEqual([]) + expect( + consoleErrors.filter((text) => /dsh-better-sidebar|Unhandled/.test(text)), + 'plugin-prefixed or unhandled console errors during the terminal open', + ).toEqual([]) + await page.screenshot({ path: 'test-results/mount-terminal.png' }) +}) + test('conservative auto: URL stamps alone never modify the layout; plugin chrome carries the stable data attributes', async ({ page }) => { // The official DSH Desktop shell stamps every render URL with // dsh-desktop-mode / dsh-desktop-platform. Under the conservative AUTO diff --git a/tests/lazy-chunk.spec.tsx b/tests/lazy-chunk.spec.tsx index 339572cc..332807ee 100644 --- a/tests/lazy-chunk.spec.tsx +++ b/tests/lazy-chunk.spec.tsx @@ -18,6 +18,7 @@ import { builtinViewers } from '../src/client/builtins/viewers.tsx' import { registerChunkForTests, resetChunks } from '../src/client/chunk-loader.ts' import { lazyChunkComponent } from '../src/client/lazy-chunk.tsx' import type { FileViewerProps, TabComponentProps } from '../src/client/service.ts' +import type { Context } from '../src/context-types.ts' import css from '../src/client/sidebar.module.css' const Marker = (): ReactNode => createElement('div', { 'data-testid': 'chunk-rendered' }, 'loaded') @@ -93,7 +94,7 @@ describe('built-in descriptor contract (render-prop functions)', () => { }) it('a built-in tab component keeps the same contract', () => { - const tabs = builtinTabs() + const tabs = builtinTabs({} as Context) const editor = tabs.find(tab => tab.id === 'editor') expect(editor).toBeDefined() // The descriptor renders from props; a real tab is part of the contract — diff --git a/tests/terminal-tab.spec.tsx b/tests/terminal-tab.spec.tsx new file mode 100644 index 00000000..2b2832dd --- /dev/null +++ b/tests/terminal-tab.spec.tsx @@ -0,0 +1,549 @@ +/** + * The bottom workbench's terminal tab (#774). + * + * Three contracts are pinned here, in the order they break: + * + * 1. CARRIER SURFACE: `terminal-bottom` is `bottomOnly`, so it is offered in + * the plugin's own + menu, never registered as a native right-Sidebar tab + * type, and an `openTab` that asked for the right column still lands in the + * bottom workbench. (DSH's own right Sidebar owns one `terminal` entry; + * a second capsule is the shadowing the mount lane pins as absent.) + * 2. THE HOST CONTRACT: the view drives `ctx.webTerminals` structurally — the + * stable `(sessionId, key, contentId)` occurrence identity that makes a + * reload adopt the SAME host terminal, the mount/detach pair that leaves + * the process alive across DOM unmount, `write`/`resize` forwarding, and + * the frame protocol (`snapshot` → reset+resize+write, `output` → write, + * then `acknowledge` — an unacknowledged frame stops output for good). + * 3. DEGRADATION: a deployment without the host service renders the + * explanation instead of throwing, and the + menu row is disabled. + * + * xterm itself is mocked: jsdom cannot open a real emulator (no canvas, no + * ResizeObserver), and the assertions are about the plumbing AROUND it. The + * real emulator is only exercised by the mount lane's browser run. + */ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createElement, type ReactElement } from 'react' +import { act } from 'react-dom/test-utils' +// First import: browser globals before the primitive-carrying sidebar graph loads. +import './browser-globals.ts' +import { renderRoot, setupReactAct } from './test-utils.ts' +import { t } from '../src/client/locales.ts' +import type { Context } from '../src/context-types.ts' +import type { SidebarTab } from '../src/client/state.ts' +import { createSidebarStore } from '../src/client/state.ts' +import { createBetterSidebarService, type TabDescriptor } from '../src/client/service.ts' +import { builtinTabs } from '../src/client/builtins/tabs.tsx' +import { + bottomTerminalContentId, bottomTerminalKey, nextTerminalMeta, terminalRunOf, + type HostTerminalView, type HostTerminalViewState, type WebTerminalsFace, +} from '../src/client/terminal-client.ts' +import { TerminalBottomView } from '../src/client/TerminalView.tsx' + +setupReactAct() + +/** One recorded xterm invocation set (the emulator is a recording stub). */ +interface XtermCalls { + open: HTMLElement[] + dispose: number + reset: number + resize: Array<[number, number]> + writes: string[] + dataHandlers: Array<(data: string) => void> + options: Record + disposed: boolean +} + +/** + * The xterm stubs, built inside `vi.hoisted` — `vi.mock` factories are hoisted + * above the imports, so they cannot close over anything declared below them. + */ +const xterm = vi.hoisted(() => { + const emulators: XtermCalls[] = [] + /** FitAddon.proposeDimensions() result; tests override it per case. */ + const fit: { proposed: { cols: number; rows: number } | undefined } = { + proposed: { cols: 100, rows: 30 }, + } + class FakeTerminal { + readonly calls: XtermCalls = { + open: [], dispose: 0, reset: 0, resize: [], writes: [], + dataHandlers: [], options: {}, disposed: false, + } + + options: Record = {} + + constructor() { + // One object: the component assigns `xterm.options.disableStdin`, and + // the assertions read the very same record. + this.options = this.calls.options + emulators.push(this.calls) + } + + loadAddon(): void { /* the fit addon is stubbed too */ } + open(node: HTMLElement): void { this.calls.open.push(node) } + reset(): void { this.calls.reset += 1 } + resize(cols: number, rows: number): void { this.calls.resize.push([cols, rows]) } + focus(): void { /* focus bookkeeping is not asserted */ } + dispose(): void { this.calls.dispose += 1; this.calls.disposed = true } + onData(handler: (data: string) => void): { dispose: () => void } { + this.calls.dataHandlers.push(handler) + return { dispose: () => { /* no listener bookkeeping needed */ } } + } + + write(data: string, callback?: () => void): void { + this.calls.writes.push(data) + callback?.() + } + } + class FakeFitAddon { + proposeDimensions(): { cols: number; rows: number } | undefined { return fit.proposed } + } + return { emulators, fit, FakeTerminal, FakeFitAddon } +}) + +vi.mock('@xterm/xterm', () => ({ Terminal: xterm.FakeTerminal })) +vi.mock('@xterm/addon-fit', () => ({ FitAddon: xterm.FakeFitAddon })) + +/** A snapshot store with the host's `SnapshotStore` read/subscribe face. */ +class FakeStore { + private listeners = new Set<() => void>() + + constructor(private value: T) {} + + getSnapshot = (): T => this.value + + subscribe = (listener: () => void): (() => void) => { + this.listeners.add(listener) + return () => { this.listeners.delete(listener) } + } + + set(next: T): void { + this.value = next + for (const listener of [...this.listeners]) listener() + } +} + +/** One recorded host terminal model. */ +class FakeView implements HostTerminalView { + readonly state: FakeStore + mounted = 0 + detached = 0 + connected = 0 + refreshed = 0 + readonly writes: string[] = [] + readonly resizes: Array<[number, number]> = [] + readonly acks: number[] = [] + + constructor( + readonly id: string, + readonly sessionId: string, + readonly key: string, + readonly contentId: string, + info: { cols: number; rows: number }, + ) { + this.state = new FakeStore({ + phase: 'connected', + writable: true, + environment: { cwd: '/w', maxInputBytes: 4096, maxCols: 120, maxRows: 40, scrollback: 1000 }, + info: { + id, title: 'Terminal', cwd: '/w', cols: info.cols, rows: info.rows, + state: 'running', exitCode: null, + }, + }) + } + + mount(): () => void { + this.mounted += 1 + return () => { this.detached += 1 } + } + + async refresh(): Promise { this.refreshed += 1 } + connect(): void { this.connected += 1 } + acknowledge(revision: number): void { this.acks.push(revision) } + write(data: string): void { this.writes.push(data) } + resize(cols: number, rows: number): void { this.resizes.push([cols, rows]) } + async close(): Promise { /* the process ends */ } + + /** Publish a new state (the host's own patch path). */ + patch(next: Partial): void { + this.state.set({ ...this.state.getSnapshot(), ...next }) + } +} + +/** + * A structural double of the host's `ClientTerminals`, mirroring the ONE + * behaviour this plugin depends on for restore: `view()` memoizes per + * `(sessionId, key)` and resolves the terminal identity through the persisted + * `(sessionId, contentId)` binding, so repeating a call after a remount + * adopts the same host terminal instead of allocating a new one + * (dsh-api-terminal-controller 0.2.0-rc.1 `lib/client.js` `view()`). + */ +class FakeTerminals implements WebTerminalsFace { + readonly views = new Map() + readonly bindings = new Map() + readonly viewCalls: Array<{ sessionId: string; key: string; contentId: string; terminalId?: string }> = [] + readonly closeCalls: Array<{ sessionId: string; key: string; contentId: string }> = [] + allocated = 0 + + view(sessionId: string, key: string, contentId: string, terminalId?: string): HostTerminalView { + this.viewCalls.push({ sessionId, key, contentId, ...(terminalId === undefined ? {} : { terminalId }) }) + const memo = `${sessionId}\u0000${key}` + const existing = this.views.get(memo) + if (existing !== undefined) return existing + const binding = `${sessionId}\u0000${contentId}` + const saved = terminalId ?? this.bindings.get(binding) + const id = saved ?? `term-${++this.allocated}` + this.bindings.set(binding, id) + const view = new FakeView(id, sessionId, key, contentId, { cols: 80, rows: 24 }) + this.views.set(memo, view) + return view + } + + close(sessionId: string, key: string, contentId: string): void { + this.closeCalls.push({ sessionId, key, contentId }) + this.views.delete(`${sessionId}\u0000${key}`) + this.bindings.delete(`${sessionId}\u0000${contentId}`) + } + + async recover(): Promise { return [] } +} + +/** A context exposing the given services by name (the plugin probes structurally). */ +function ctxWith(services: Record): Context { + return { get: (name: string) => services[name] } as unknown as Context +} + +/** + * A context carrying the fakes the view probes: `webTerminals` (the host + * service) and `betterSidebar` (the plugin's own service, whose `updateTab` + * records the meta the "new terminal" action persists). + */ +function viewSetup(terminals: WebTerminalsFace | undefined) { + const store = createSidebarStore() + const service = createBetterSidebarService(store) + const order: string[] = [] + const ctx = ctxWith({ + ...(terminals === undefined ? {} : { webTerminals: terminals }), + betterSidebar: { + updateTab: (tabId: string, patch: { meta?: unknown }) => { + order.push(`${tabId}:${JSON.stringify(patch.meta)}`) + store.reduce(state => ({ + ...state, + bottomSplits: { + kind: 'leaf', id: 'pane:1', + tabs: state.bottomSplits.kind === 'leaf' + ? state.bottomSplits.tabs.map(candidate => candidate.id === tabId ? { ...candidate, meta: patch.meta } : candidate) + : [], + active: tabId, + }, + })) + }, + }, + }) + return { ctx, service, store, order } +} + +/** The bottom terminal tab as the workbench opens it (`single` → id = type). */ +function bottomTab(meta?: unknown): SidebarTab { + return { id: 'terminal-bottom', type: 'terminal-bottom', title: 'Terminal', ...(meta === undefined ? {} : { meta }) } +} + +function render(ctx: Context, tab: SidebarTab, visible = true) { + return renderRoot(createElement(TerminalBottomView, { ctx, scope: { sessionId: 's1', cwd: '/w' }, tab, visible })) +} + +/** Flush the microtask queue the memoized `view()`/refresh path may schedule. */ +async function flush(): Promise { + await act(async () => { await Promise.resolve() }) +} + +beforeEach(() => { + xterm.emulators.length = 0 + xterm.fit.proposed = { cols: 100, rows: 30 } +}) + +afterEach(() => { + for (const element of document.querySelectorAll('body > div')) element.remove() +}) + +describe('terminal-bottom: carrier surface', () => { + it('registers as a bottom-only, single-instance, service-gated built-in tab', () => { + const tabs = builtinTabs(ctxWith({ webTerminals: new FakeTerminals() })) + const terminal = tabs.find(tab => tab.id === 'terminal-bottom') + expect(terminal).toBeDefined() + expect(terminal?.bottomOnly).toBe(true) + expect(terminal?.single).toBe(true) + expect(terminal?.hidden).not.toBe(true) + // No createTab: the id safety net keeps ONE bottom terminal per session. + expect(terminal?.createTab).toBeUndefined() + }) + + it('the + menu row is disabled when the host provides no terminal service', () => { + const descriptor = builtinTabs(ctxWith({})) as readonly TabDescriptor[] + const terminal = descriptor.find(tab => tab.id === 'terminal-bottom') + const state = createSidebarStore().getSnapshot().state! + const scope = { sessionId: 's1' } + expect(terminal?.available?.(ctxWith({}), scope, state)).toBe(false) + expect(terminal?.available?.(ctxWith({ webTerminals: new FakeTerminals() }), scope, state)).toBe(true) + }) + + it('an open asking for the right column still lands in the bottom workbench', () => { + // The native surface is installed: without `bottomOnly` this open would be + // handed to the host's sidebar (and a second terminal capsule with it). + const store = createSidebarStore() + store.setSession('s1') + const service = createBetterSidebarService(store) + service.registerTab(builtinTabs(ctxWith({ webTerminals: new FakeTerminals() })).find(tab => tab.id === 'terminal-bottom')!) + const native: string[] = [] + service.setSurface({ + openTab: (input) => { native.push(input.kind) }, + openResource: () => {}, + fileAddress: () => 'dsh-resource://file/s1/x', + close: () => undefined, + update: () => false, + activate: () => false, + has: () => false, + }) + service.openTab({ type: 'terminal-bottom' }, { sessionId: 's1' }) + expect(native, 'a bottom-only type must never reach the native sidebar').toEqual([]) + const state = store.getSnapshot().state! + expect(state.bottomOpen).toBe(true) + const tabs = state.bottomSplits.kind === 'leaf' ? state.bottomSplits.tabs : [] + expect(tabs.map(tab => tab.id)).toEqual(['terminal-bottom']) + }) +}) + +describe('terminal-bottom: the host terminal contract', () => { + it('mounts one view per (session, key, contentId) and detaches — never closes — on unmount', async () => { + const terminals = new FakeTerminals() + const { ctx } = viewSetup(terminals) + const { unmount } = render(ctx, bottomTab()) + await flush() + + expect(terminals.viewCalls).toHaveLength(1) + expect(terminals.viewCalls[0]).toEqual({ + sessionId: 's1', + key: bottomTerminalKey(0), + contentId: bottomTerminalContentId(0), + }) + const view = terminals.views.get('s1\u0000' + bottomTerminalKey(0))! + expect(view.mounted).toBe(1) + expect(xterm.emulators).toHaveLength(1) + expect(xterm.emulators[0]!.open).toHaveLength(1) + + unmount() + expect(view.detached, 'the DOM lifetime detaches').toBe(1) + // The host's contract: unmount leaves the process running, so the plugin + // must NOT close it here (only the tab's onClose does). + expect(terminals.closeCalls).toEqual([]) + expect(xterm.emulators[0]!.disposed, 'the emulator itself is released').toBe(true) + }) + + it('a remount adopts the SAME host terminal through the stable content identity', async () => { + const terminals = new FakeTerminals() + const { ctx } = viewSetup(terminals) + + const first = render(ctx, bottomTab()) + await flush() + const allocated = terminals.allocated + const view = terminals.views.get('s1\u0000' + bottomTerminalKey(0))! + first.unmount() + + // A page reload looks exactly like this to the plugin: a fresh mount of + // the same tab, with the host service's own state gone. + terminals.views.clear() + const second = render(ctx, bottomTab()) + await flush() + + expect(terminals.viewCalls.map(call => call.contentId)).toEqual([ + bottomTerminalContentId(0), + bottomTerminalContentId(0), + ]) + expect(terminals.allocated, 'no second terminal was allocated').toBe(allocated) + expect(terminals.views.get('s1\u0000' + bottomTerminalKey(0))!.id).toBe(view.id) + second.unmount() + }) + + it('forwards emulator input to the model and a fit to the model resize', async () => { + const terminals = new FakeTerminals() + const { ctx } = viewSetup(terminals) + const { unmount } = render(ctx, bottomTab()) + await flush() + const view = terminals.views.get('s1\u0000' + bottomTerminalKey(0))! + + // Keystrokes go through the MODEL (it serializes them and refuses them + // while the view is not writable), never straight to the remote. + act(() => { xterm.emulators[0]!.dataHandlers[0]!('echo hi\r') }) + expect(view.writes).toEqual(['echo hi\r']) + + // The first fit publishes the measured size inside the host's limits. + expect(view.resizes).toEqual([[100, 30]]) + + // A later, larger box is clamped to the host's per-terminal limits + // (120x40) rather than asking for a size the host would refuse. + xterm.fit.proposed = { cols: 400, rows: 200 } + act(() => { + view.patch({ environment: { cwd: '/w', maxInputBytes: 4096, maxCols: 120, maxRows: 40, scrollback: 1000 } }) + }) + expect(view.resizes).toEqual([[100, 30], [120, 40]]) + + // Not writable: stdin is disabled and no further resize is published. + act(() => { view.patch({ writable: false }) }) + expect(xterm.emulators[0]!.options.disableStdin).toBe(true) + expect(view.resizes).toHaveLength(2) + unmount() + }) + + it('replays a snapshot frame, appends output frames, and acknowledges each revision', async () => { + const terminals = new FakeTerminals() + const { ctx } = viewSetup(terminals) + const { unmount } = render(ctx, bottomTab()) + await flush() + const view = terminals.views.get('s1\u0000' + bottomTerminalKey(0))! + + act(() => { + view.patch({ + render: { + revision: 1, + frame: { + type: 'snapshot', sequence: 1, screen: 'restored screen', + info: { id: view.id, title: 'Terminal', cwd: '/w', cols: 90, rows: 20, state: 'running', exitCode: null }, + }, + }, + }) + }) + expect(xterm.emulators[0]!.reset).toBe(1) + expect(xterm.emulators[0]!.resize).toContainEqual([90, 20]) + expect(xterm.emulators[0]!.writes).toEqual(['restored screen']) + expect(view.acks).toEqual([1]) + + act(() => { + view.patch({ render: { revision: 2, frame: { type: 'output', sequence: 2, data: 'more output' } } }) + }) + expect(xterm.emulators[0]!.reset, 'output frames are appended, never replayed').toBe(1) + expect(xterm.emulators[0]!.writes).toEqual(['restored screen', 'more output']) + expect(view.acks).toEqual([1, 2]) + + // A repeated revision (a re-render with the same state) is not re-written. + act(() => { + view.patch({ render: { revision: 2, frame: { type: 'output', sequence: 2, data: 'more output' } } }) + }) + expect(xterm.emulators[0]!.writes).toHaveLength(2) + unmount() + }) +}) + +describe('terminal-bottom: degradation and recovery', () => { + it('renders the explanation — and allocates nothing — without the host service', async () => { + const { ctx } = viewSetup(undefined) + const { container, unmount } = render(ctx, bottomTab()) + await flush() + const section = container.querySelector('[data-dsh-bottom-terminal]') + expect(section?.getAttribute('data-terminal-state')).toBe('unavailable') + expect(section?.textContent).toBeTruthy() + expect(xterm.emulators).toHaveLength(0) + unmount() + }) + + it('offers a new terminal when the bound process is gone, minting a fresh content identity', async () => { + const terminals = new FakeTerminals() + const { ctx, order } = viewSetup(terminals) + const { container, rerender, unmount } = render(ctx, bottomTab()) + await flush() + const first = terminals.views.get('s1\u0000' + bottomTerminalKey(0))! + + act(() => { first.patch({ phase: 'failed', writable: false, issue: 'missingTerminal' }) }) + const action = container.querySelector('button') + expect(action, 'the missing-terminal panel offers a new terminal').not.toBeNull() + // The raw host issue id never reaches the reader. + expect(container.textContent).not.toContain('missingTerminal') + + act(() => { action!.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) + // The plugin persists the content-identity generation on the tab. + expect(order).toEqual(['terminal-bottom:{"terminalRun":1}']) + + // The workbench re-renders the tab from its own store, meta included. The + // view must then ask the host for a NEW content identity: reusing the dead + // binding would wedge the tab on `missingTerminal` for the page's life. + rerender(createElement(TerminalBottomView, { + ctx, scope: { sessionId: 's1', cwd: '/w' }, tab: bottomTab({ terminalRun: 1 }), visible: true, + })) + await flush() + expect(terminals.viewCalls.map(call => call.contentId)).toEqual([ + bottomTerminalContentId(0), + bottomTerminalContentId(1), + ]) + expect(terminals.allocated, 'the replacement is a genuinely new terminal').toBe(2) + unmount() + }) + + it('an ended terminal offers the same new-terminal action, and says so once', async () => { + const terminals = new FakeTerminals() + const { ctx } = viewSetup(terminals) + const { container, unmount } = render(ctx, bottomTab()) + await flush() + const view = terminals.views.get('s1\u0000' + bottomTerminalKey(0))! + act(() => { + view.patch({ info: { id: view.id, title: 'Terminal', cwd: '/w', cols: 80, rows: 24, state: 'exited', exitCode: 0 } }) + }) + expect(container.querySelector('button')).not.toBeNull() + // The ended panel carries its own line: the pending-phase status line must + // stand down, or the reader sees the same sentence twice. + const line = t('exited') + expect(container.textContent!.split(line).length - 1).toBe(1) + unmount() + }) + + it('a disconnected view reconnects through the model instead of reloading the page', async () => { + const terminals = new FakeTerminals() + const { ctx } = viewSetup(terminals) + const { container, unmount } = render(ctx, bottomTab()) + await flush() + const view = terminals.views.get('s1\u0000' + bottomTerminalKey(0))! + act(() => { view.patch({ phase: 'disconnected', writable: false }) }) + const action = container.querySelector('button')! + act(() => { action.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) + expect(view.connected).toBe(1) + expect(view.refreshed).toBe(0) + unmount() + }) +}) + +describe('terminal-bottom: identity helpers', () => { + it('keeps run 0 stable and namespaces every later run', () => { + expect(bottomTerminalContentId(0)).toBe('dsh-better-sidebar:terminal-bottom') + expect(bottomTerminalKey(0)).toBe(bottomTerminalContentId(0)) + expect(bottomTerminalContentId(1)).toBe(bottomTerminalKey(1)) + expect(bottomTerminalContentId(1)).toContain('#1') + // Distinct per run — the whole point of the generation. + expect(bottomTerminalContentId(1)).not.toBe(bottomTerminalContentId(0)) + }) + + it('reads a generation only from a well-formed meta, defaulting to 0', () => { + expect(terminalRunOf(bottomTab())).toBe(0) + expect(terminalRunOf(bottomTab({ terminalRun: 3 }))).toBe(3) + expect(terminalRunOf(bottomTab({ terminalRun: -1 }))).toBe(0) + expect(terminalRunOf(bottomTab({ terminalRun: 1.5 }))).toBe(0) + expect(terminalRunOf(bottomTab({ terminalRun: 'two' }))).toBe(0) + expect(terminalRunOf(bottomTab(null))).toBe(0) + expect(terminalRunOf(bottomTab([1, 2]))).toBe(0) + expect(nextTerminalMeta(bottomTab({ terminalRun: 3 }))).toEqual({ terminalRun: 4 }) + }) +}) + +describe('terminal-bottom: the descriptor close hook', () => { + it('closing the tab ends the host terminal (no leaked shell)', () => { + const terminals = new FakeTerminals() + const ctx = ctxWith({ webTerminals: terminals }) + const descriptor = builtinTabs(ctx).find(tab => tab.id === 'terminal-bottom') + const scope = { sessionId: 's1' } + const icon = descriptor?.icon + expect(icon).toBeDefined() + expect((typeof icon === 'function' ? icon(14) : icon) as ReactElement).toBeTruthy() + + descriptor?.onClose?.(bottomTab({ terminalRun: 2 }), scope) + expect(terminals.closeCalls).toEqual([ + { sessionId: 's1', key: bottomTerminalKey(2), contentId: bottomTerminalContentId(2) }, + ]) + }) +}) diff --git a/tsdown.config.ts b/tsdown.config.ts index 4bfb012c..cba0c019 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -324,7 +324,7 @@ function makeCssPlugin(pluginId: string): BuildPlugin { } /** The lazy chunk names (keep in sync with src/bundle-route.ts CHUNK_NAMES). */ -const CHUNKS = ['editor', 'mermaid', 'locale'] +const CHUNKS = ['editor', 'mermaid', 'locale', 'terminal'] export default [ {