test(terminal): #774 收尾——补 bottomOnly 原生承载面的单元判别性守护

独立验证节点实测:把 src/client/native/index.ts 的 sync() 里
`if (descriptor.bottomOnly === true) continue` 删掉后,14 个相关 spec、158 条
断言全绿,只有挂载 lane 能抓住「原生 guide 条目从 0 变 1」——这半边当时只有
部署级守护。

- tests/native-registration.spec.ts 新增「a bottomOnly descriptor never
  reaches the native surface」:断言注册表的**事件日志**里没有该 id、没有它的
  slot,guide 条目只有 files 与 git;正控(其余描述符确实注册了)在前,所以
  这条不会因为「什么都没注册」而空过。实测删掉那行 skip 后:本次相关的 8 个
  spec / 171 条用例中只有这条红(170 绿)。
- tests/terminal-tab.spec.tsx:「已退出只说一次」那条断言原先**不判别**——
  只翻 info.state 时 statusOf 本来就返回 undefined,门在不在都一样。现在把
  phase 也置为 disconnected(statusOf 有自己的一行),断言状态行恰好 1 个、
  唯一按钮是「新建终端」、且不含 disconnected 文案。实测去掉
  TerminalView.tsx 的 `missing || ended` 门即红。
- tests/terminal-tab.spec.tsx 新增「新建终端」的**真实路由**用例:此前被假
  betterSidebar.updateTab 掩盖,现在接真 service,覆盖 surface.update 认领
  与 store.reduce(patchTab) 两半(bottomOnly 类型永远没有原生记录,落 store
  是它唯一的真实路径)。
- src/client/builtins/tabs.tsx:onClose 不再以 `scope?.sessionId ?? ''` 调宿主
  close(),缺 scope 直接 return——空 sessionId 会让宿主 no-op 并让 shell 一直
  挂着一个 per-session 槽位。
This commit is contained in:
Menghuan1918 committed 2026-10-06 00:06:37 +08:00
1 parent 2f66c921df
commit 6c60693e7d
3 files changed
+145 -8

No files matched your search

+11 -1
View File
@@ -269,7 +269,17 @@ export function builtinTabs(ctx: Context): readonly TabDescriptor[] {
// 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 ?? '') },
onClose: (tab, scope) => {
// Every close path resolves a scope (the type makes it required), so
// this guard should be unreachable. It returns instead of substituting
// `''` for a missing one because an empty session id is the ONE option
// that is worse than doing nothing: the host would look the terminal up
// in a session that does not exist, no-op, and leave the shell running
// — invisibly holding a per-session terminal slot for the page's life.
const sessionId: string | undefined = scope?.sessionId
if (sessionId === undefined || sessionId === '') return
closeBottomTerminal(ctx, tab, sessionId)
},
},
{
id: 'diff',
+57 -1
View File
@@ -41,12 +41,16 @@ import { createSidebarStore } from '../src/client/state.ts'
function createRegistry() {
const registered = new Map<string, () => void>()
const events: string[] = []
/** Every definition the plugin handed the host, guide rows included. */
const definitions: Array<{ id: string; kind: string; guide?: Array<{ id?: unknown }> }> = []
let failReleaseOf: string | undefined
return {
registered,
events,
definitions,
failRelease(id: string): void { failReleaseOf = id },
register(definition: { id: string }): () => void {
register(definition: { id: string; kind: string; guide?: Array<{ id?: unknown }> }): () => void {
definitions.push(definition)
if (registered.has(definition.id)) {
throw new Error(`sidebarRight: tab type id "${definition.id}" is already registered`)
}
@@ -239,3 +243,55 @@ describe('native tab registration lifecycle', () => {
}
})
})
/**
* `bottomOnly` (#774): the type lives in the plugin's own workbench only.
*
* The mount lane pins the OUTCOME (the host's guide still lists exactly one
* `terminal` capsule), but until this case existed the MECHANISM had no unit
* guard at all: the #774 verification measured 14 related specs / 158
* assertions staying green with the `bottomOnly` skip in `sync()` deleted, so
* only a full deployment could catch it. This is the unit half, written on what
* actually reached the host rather than on what the plugin intended to send.
*/
describe('a bottomOnly descriptor never reaches the native surface', () => {
it('registers no tab type, no slot and no guide row for it', () => {
const host = createHost()
const { store, service, records } = createPlugins()
// The sixth built-in (#774), declared through the same public API an
// external plugin uses.
service.registerTab({
id: 'terminal-bottom',
title: () => 'Terminal',
description: () => 'Bottom shell',
bottomOnly: true,
single: true,
component: () => null,
})
const dispose = registerNativeSurface({ ctx: host.ctx as never, store, service, records })
// Positive control FIRST: the other descriptors did reach the host, and the
// visible one did contribute its guide row — so the absences below cannot
// be satisfied by a surface that registers nothing at all. (The `files`
// takeover follows the descriptor loop, hence its place at the end.)
expect(host.registry.events).toEqual([
'register dsh-better-sidebar:editor',
'register dsh-better-sidebar:git',
'register dsh-better-sidebar:files',
])
const guideIds = host.registry.definitions
.flatMap(definition => (definition.guide ?? []).map(entry => entry.id))
expect(guideIds.sort()).toEqual(['files', 'git'])
// The absence rides the EVENT LOG, not the live key set: a type registered
// and then orphaned leaves a key set that looks exactly like this one.
expect(host.registry.registered.has('dsh-better-sidebar:terminal-bottom')).toBe(false)
expect(host.registry.events.filter(event => event.includes('terminal-bottom'))).toEqual([])
expect(host.slotEvents.filter(event => event.includes('terminal-bottom'))).toEqual([])
// A notification re-runs `sync()`; the skip must survive it.
store.setPrefs(store.getPrefs())
expect(host.registry.events.filter(event => event.includes('terminal-bottom'))).toEqual([])
dispose()
})
})
+77 -6
View File
@@ -31,7 +31,7 @@ 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 { allLeaves, createSidebarStore, openTabInBottomPane } from '../src/client/state.ts'
import { createBetterSidebarService, type TabDescriptor } from '../src/client/service.ts'
import { builtinTabs } from '../src/client/builtins/tabs.tsx'
import {
@@ -477,20 +477,38 @@ describe('terminal-bottom: degradation and recovery', () => {
unmount()
})
it('an ended terminal offers the same new-terminal action, and says so once', async () => {
it('an ended terminal owns the only status line, and offers the new-terminal action', 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 } })
view.patch({
info: { id: view.id, title: 'Terminal', cwd: '/w', cols: 80, rows: 24, state: 'exited', exitCode: 0 },
// The phase is what makes this case DISCRIMINATING. A patch that only
// flipped `info.state` to `exited` would leave the pending-phase status
// line undefined either way (`statusOf` has no line for `connected`),
// so the assertion below ("the exited sentence appears once") held with
// and without the gate in `TerminalBottomView`. `disconnected` HAS a
// line of its own, and the gate is exactly what must stand it — with
// its Retry button — down: a process that is gone cannot be reconnected
// to, and the reader would get the same terminal described twice.
phase: 'disconnected',
writable: false,
})
})
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.
// The ended panel carries its own line, exactly once…
const line = t('exited')
expect(container.textContent!.split(line).length - 1).toBe(1)
// …it is the ONLY status line on screen (the suppressed one was a
// `role="status"` div as well)…
expect(container.querySelectorAll('[role="status"]')).toHaveLength(1)
// …and the only action is the new terminal: the suppressed line's Retry
// button would come FIRST in DOM order.
expect([...container.querySelectorAll('button')].map(button => button.textContent))
.toEqual([t('terminalNew')])
expect(container.textContent).not.toContain(t('disconnected'))
unmount()
})
@@ -507,6 +525,59 @@ describe('terminal-bottom: degradation and recovery', () => {
expect(view.refreshed).toBe(0)
unmount()
})
it('the new-terminal action rides the REAL updateTab route (native record first, own layout second)', async () => {
// Every other case here stubs `betterSidebar.updateTab`, which is only the
// call the view MAKES: the write itself travels
// `service.updateTab` → `surface.update` → `store.reduce(patchTab)`, and
// that route was uncovered. It matters most for this type: a `bottomOnly`
// tab never has a native record, so the store reduce is the only path its
// "new terminal" can take — with a stub, a broken route would still look
// green here and fail only in the browser.
const terminals = new FakeTerminals()
const store = createSidebarStore()
store.setSession('s1')
const service = createBetterSidebarService(store)
const ctx = ctxWith({ webTerminals: terminals, betterSidebar: service })
// The workbench's own state: the tab IS open. `patchTab` is a documented
// no-op for a missing id, so a case that skipped this would assert nothing.
store.reduce(state => openTabInBottomPane(state, bottomTab()))
const tabInStore = (): SidebarTab | undefined => allLeaves(store.getSnapshot().state!.bottomSplits)
.flatMap(leaf => leaf.tabs).find(tab => tab.id === 'terminal-bottom')
expect(tabInStore()?.meta).toBeUndefined()
const { container, unmount } = render(ctx, bottomTab())
await flush()
const view = terminals.views.get('s1\u0000' + bottomTerminalKey(0))!
act(() => { view.patch({ phase: 'failed', writable: false, issue: 'missingTerminal' }) })
const action = container.querySelector('button')!
// ── the native half: an id the native surface owns is patched THERE ────
const nativePatches: Array<{ tabId: string; patch: unknown; sessionId: string | undefined }> = []
service.setSurface({
openTab: () => {},
openResource: () => {},
fileAddress: () => 'dsh-resource://file/s1/x',
close: () => undefined,
update: (tabId, patch, sessionId) => {
nativePatches.push({ tabId, patch, sessionId })
return true
},
activate: () => false,
has: () => false,
})
act(() => { action.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
expect(nativePatches).toEqual([
{ tabId: 'terminal-bottom', patch: { meta: { terminalRun: 1 } }, sessionId: 's1' },
])
expect(tabInStore()?.meta, 'a native record owns the patch — the store stays out of it').toBeUndefined()
// ── the own-layout half: no native record, so the bottom tree takes it ──
service.setSurface(undefined)
act(() => { action.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
expect(tabInStore()?.meta).toEqual({ terminalRun: 1 })
unmount()
})
})
describe('terminal-bottom: identity helpers', () => {