test(gui): settings package suites; ledger-judged re-registration

Full per-file coverage for the three settings packages: invariant
companions, store mirroring with revision guards, behavior-shaped
section/shell specs (props-fed, real store engine), and apply-level
suites on a real Context + SlotCore covering declaration-aware deferral
and HMR collapse recovery. All three registrants now judge presence on
the slot ledger instead of a local disposer, which went stale when a
parent redeclaration cascade removed the entry (ds-review-bot finding);
the locale re-register path keeps the same idempotence.
This commit is contained in:
imccyu
2026-07-26 01:10:23 +08:00
parent b1b180e098
commit c5cc348816
12 changed files with 764 additions and 12 deletions
@@ -98,9 +98,11 @@ export function apply(ctx: ClientContext): void {
}
// Nav labels are registrant-localized: re-register on locale change so
// the ledger carries fresh text (the version bump re-renders the shell).
// The ledger check mirrors tryRegister: after an HMR collapse `dispose`
// stays set while the entry is gone — relabeling then must stay quiet.
const offLocale = ctx.on('locale/change', () => {
if (!registered()) return
dispose?.()
if (dispose === undefined || !registered()) return
dispose()
dispose = undefined
tryRegister()
})
@@ -0,0 +1,139 @@
/** apply wiring: dictionary registration, declaration-aware section entry,
* snapshot projection into the slot store, locale-driven relabeling, and
* recovery after an HMR collapse of the declaring entry. */
import { Context } from 'cordis'
import { describe, expect, it } from 'vitest'
import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client'
import { LocaleService } from '@deepseek-ai/dsh-client-locale/client'
import { ThemeService } from '@deepseek-ai/dsh-client-ui-theme/client'
import { apply, inject } from '@deepseek-ai/dsh-client-ui-settings-general/client'
import type { GeneralSectionInjected } from '@deepseek-ai/dsh-client-ui-settings-general/client'
import { GeneralSection } from '../src/client/GeneralSection.tsx'
import type { createGeneralSettingsStore } from '../src/client/store.ts'
const NS = 'settings.general'
async function bench() {
const ctx = new Context()
await ctx.plugin(SlotsService).await()
const locale = new LocaleService(ctx)
const theme = new ThemeService(ctx)
ctx.provide('locale', locale)
ctx.provide('theme', theme)
return { ctx, slots: ctx.get('slots') as SlotsService, locale, theme }
}
/** Stand in for the settings shell: declare the section list slot from root. */
function declareSection(slots: SlotsService): () => void {
return slots.register(
{ name: 'root', children: { 'settings.section': { kind: 'list', scope: 'root' } } } as never,
() => null,
)
}
/** Mirror the framework's inject choreography: bake a real instance from the
* declared handle and hand its actions to the entry's inject factory. */
function faceOf(slots: SlotsService) {
const entry = slots.entries('settings.section')[0]!
const handle = entry.store as ReturnType<typeof createGeneralSettingsStore>
const instance = handle.create()
const face = (entry.inject as unknown as (a: typeof instance.actions) => GeneralSectionInjected)(instance.actions)
return { entry, instance, face }
}
describe('ui-settings-general apply', () => {
it('declares the slot, locale, and theme services', () => {
expect(inject).toEqual(['slots', 'locale', 'theme'])
})
it('registers dictionaries and the section entry for declarations before or after apply', async () => {
const before = await bench()
declareSection(before.slots)
await before.ctx.plugin({ inject: [...inject], apply }).await()
const entry = before.slots.entries('settings.section')[0]!
expect(entry.component).toBe(GeneralSection)
expect(entry.options).toMatchObject({ id: 'general', order: 0, label: '通用设置' })
expect(before.locale.bind(NS)('nav')).toBe('通用设置')
const after = await bench()
const fiber = after.ctx.plugin({ inject: [...inject], apply })
await fiber.await()
expect(after.slots.entries('settings.section')).toHaveLength(0)
declareSection(after.slots)
await Promise.resolve()
expect(after.slots.entries('settings.section')[0]!.component).toBe(GeneralSection)
// Teardown without a live registration exercises the undefined-disposer arm.
await fiber.dispose()
expect(after.slots.entries('settings.section')).toHaveLength(0)
})
it('projects service snapshots into the store and routes face writes back', async () => {
const b = await bench()
declareSection(b.slots)
await b.ctx.plugin({ inject: [...inject], apply }).await()
// Events ahead of any inject hit the unbound-actions arm without a store.
b.theme.setTheme('dark')
const { instance, face } = faceOf(b.slots)
// The inject-time re-sync sealed the init window: both mirrors are current.
expect(instance.getSnapshot().localeActive).toBe('zh')
expect(instance.getSnapshot().localeOptions.map(l => l.id)).toEqual(['zh', 'en'])
expect(instance.getSnapshot().themePreference).toBe('dark')
expect(face.t('nav')).toBe('通用设置')
face.setLocale('en')
expect(b.locale.getLocale().active).toBe('en')
expect(instance.getSnapshot().localeActive).toBe('en')
expect(face.t('nav')).toBe('General')
face.setTheme('system')
expect(b.theme.getTheme().preference).toBe('system')
expect(instance.getSnapshot().themePreference).toBe('system')
})
it('re-registers with a fresh ledger label when the locale changes', async () => {
const b = await bench()
declareSection(b.slots)
await b.ctx.plugin({ inject: [...inject], apply }).await()
expect(b.slots.entries('settings.section')[0]!.options.label).toBe('通用设置')
b.locale.setLocale('en')
const entry = b.slots.entries('settings.section')[0]!
expect(entry.options.label).toBe('General')
expect(entry.component).toBe(GeneralSection)
})
it('recovers after an HMR collapse of the declaring entry (stale disposer must not block)', async () => {
const b = await bench()
const host = declareSection(b.slots)
await b.ctx.plugin({ inject: [...inject], apply }).await()
expect(b.slots.entries('settings.section')).toHaveLength(1)
// Collapse: the declarer dies, the cascade removes our entry while the
// apply closure still holds its (now stale) disposer.
host()
expect(b.slots.entries('settings.section')).toHaveLength(0)
// A locale change inside the collapsed window must stay quiet.
b.locale.setLocale('en')
expect(b.slots.entries('settings.section')).toHaveLength(0)
// Redeclaration restores the entry — with the current locale's label.
declareSection(b.slots)
await Promise.resolve()
const entry = b.slots.entries('settings.section')[0]!
expect(entry.component).toBe(GeneralSection)
expect(entry.options.label).toBe('General')
})
it('removes the entry and the dictionaries on teardown', async () => {
const b = await bench()
declareSection(b.slots)
const fiber = b.ctx.plugin({ inject: [...inject], apply })
await fiber.await()
expect(b.slots.entries('settings.section')).toHaveLength(1)
await fiber.dispose()
expect(b.slots.entries('settings.section')).toHaveLength(0)
// Dictionary disposal: translation falls back to the bare key.
expect(b.locale.bind(NS)('nav')).toBe('nav')
})
})
@@ -0,0 +1,112 @@
// @vitest-environment jsdom
/** GeneralSection behavior: skeleton rows stay inert, Language menu drives
* setLocale, Appearance cubes follow the preference and drive setTheme. */
import { afterEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { createSnapshotStore, type SessionListState, type WorkspaceListState } from '@deepseek-ai/dsh-client-runtime/client'
import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
import { GeneralSection } from '../src/client/GeneralSection.tsx'
import { createGeneralSettingsStore } from '../src/client/store.ts'
import { en } from '../src/client/locales.ts'
import type { GeneralSectionComponentProps } from '../src/client/contract.ts'
afterEach(cleanup)
const LOCALES = [{ id: 'zh', label: '中文' }, { id: 'en', label: 'English' }]
/** Empty global standard-kit hooks (the section reads neither). */
function emptySessions() {
const store = createSnapshotStore<SessionListState>(
{ ids: [], byId: {}, current: undefined, intent: undefined, phase: 'ready' })
return bindSnapshotSelector(store)
}
function emptyWorkspaces() {
const store = createSnapshotStore<WorkspaceListState>({
items: [], intent: undefined, state: 'idle', phase: 'ready', error: null,
baselinesReady: true, recentWorkspaceId: undefined,
})
return bindSnapshotSelector(store)
}
function mount(init?: { active?: string; preference?: 'light' | 'dark' | 'system' }) {
// Real store instance — the sanctioned zero-machinery path for tests.
const store = createGeneralSettingsStore().create()
store.actions.syncLocale(init?.active ?? 'en', LOCALES, 0)
store.actions.syncTheme(init?.preference ?? 'system', 0)
const setLocale = vi.fn()
const setTheme = vi.fn()
const props: GeneralSectionComponentProps = {
useSessions: emptySessions(),
useWorkspaces: emptyWorkspaces(),
useStore: bindSnapshotSelector(store),
actions: store.actions,
t: (key: string) => en[key] ?? key,
setLocale,
setTheme,
}
render(<GeneralSection {...props} />)
return { store, setLocale, setTheme }
}
const pressed = (name: RegExp): string | null =>
screen.getByRole('button', { name }).getAttribute('aria-pressed')
describe('GeneralSection', () => {
it('renders the four groups with skeleton rows inert', () => {
const b = mount()
// Permission: disabled selector showing the fixed value.
const permission = screen.getByRole('button', { name: /Read only/ }) as HTMLButtonElement
expect(permission.disabled).toBe(true)
fireEvent.click(permission)
// Tool Call: both mode cubes render as plain text, no buttons.
expect(screen.getByText('Schema mode')).toBeDefined()
expect(screen.getByText('Code mode')).toBeDefined()
expect(screen.queryByRole('button', { name: /Schema mode/ })).toBeNull()
expect(b.setLocale).not.toHaveBeenCalled()
expect(b.setTheme).not.toHaveBeenCalled()
})
it('opens the language menu, selects a locale, and closes', () => {
const b = mount({ active: 'en' })
const trigger = screen.getByRole('button', { name: /English/ })
expect(trigger.getAttribute('aria-expanded')).toBe('false')
fireEvent.click(trigger)
expect(trigger.getAttribute('aria-expanded')).toBe('true')
fireEvent.click(screen.getByRole('menuitem', { name: '中文' }))
expect(b.setLocale).toHaveBeenCalledWith('zh')
expect(trigger.getAttribute('aria-expanded')).toBe('false')
expect(screen.queryByRole('menuitem', { name: '中文' })).toBeNull()
})
it('closes the language menu on outside pointerdown without selecting', () => {
const b = mount({ active: 'en' })
const trigger = screen.getByRole('button', { name: /English/ })
fireEvent.click(trigger)
expect(screen.getByRole('menuitem', { name: '中文' })).toBeDefined()
fireEvent.pointerDown(document.body)
expect(trigger.getAttribute('aria-expanded')).toBe('false')
expect(screen.queryByRole('menuitem', { name: '中文' })).toBeNull()
expect(b.setLocale).not.toHaveBeenCalled()
})
it('reflects a store locale change in the trigger label (unknown id falls back to the id)', () => {
const b = mount({ active: 'en' })
act(() => { b.store.actions.syncLocale('zh', LOCALES, 1) })
expect(screen.getByRole('button', { name: /中文/ })).toBeDefined()
act(() => { b.store.actions.syncLocale('fr', LOCALES, 2) })
expect(screen.getByRole('button', { name: /fr/ })).toBeDefined()
})
it('marks the appearance cube matching the preference and switches on click', () => {
const b = mount({ preference: 'dark' })
expect(pressed(/Dark/)).toBe('true')
expect(pressed(/Light/)).toBe('false')
expect(pressed(/System/)).toBe('false')
fireEvent.click(screen.getByRole('button', { name: /Light/ }))
expect(b.setTheme).toHaveBeenCalledWith('light')
// Selection follows the store mirror, not the click echo.
act(() => { b.store.actions.syncTheme('light', 1) })
expect(pressed(/Light/)).toBe('true')
expect(pressed(/Dark/)).toBe('false')
})
})
@@ -0,0 +1,18 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import * as GeneralInvariant from '@deepseek-ai/dsh-client-ui-settings-general/invariant'
import InvariantService from '@deepseek-ai/dsh-invariants'
describe('invariant companion', () => {
it('registers under the package name with an empty installer', async () => {
const ctx = new Context()
await ctx.plugin(InvariantService, { enabled: true })
await expect(ctx.plugin(GeneralInvariant).await()).resolves.toBeDefined()
})
it('node-half apply is a no-op host placeholder', async () => {
const { apply } = await import('@deepseek-ai/dsh-client-ui-settings-general')
apply()
expect(true).toBe(true) // reaching here without throw is the contract
})
})
@@ -0,0 +1,56 @@
/** General settings store: snapshot-mirror actions and the revision guard. */
import { describe, expect, it } from 'vitest'
import { createGeneralSettingsStore } from '../src/client/store.ts'
const LOCALES = [{ id: 'zh', label: '中文' }, { id: 'en', label: 'English' }]
describe('createGeneralSettingsStore', () => {
it('init shape: empty mirrors with revisions at -1', () => {
const store = createGeneralSettingsStore().create()
expect(store.getSnapshot()).toEqual({
localeActive: '',
localeOptions: [],
localeRevision: -1,
themePreference: 'system',
themeRevision: -1,
})
})
it('syncLocale mirrors the snapshot and advances the revision', () => {
const store = createGeneralSettingsStore().create()
store.actions.syncLocale('zh', LOCALES, 0)
expect(store.getSnapshot().localeActive).toBe('zh')
expect(store.getSnapshot().localeOptions).toEqual(LOCALES)
expect(store.getSnapshot().localeRevision).toBe(0)
store.actions.syncLocale('en', LOCALES, 1)
expect(store.getSnapshot().localeActive).toBe('en')
expect(store.getSnapshot().localeRevision).toBe(1)
})
it('syncLocale revision guard drops stale and duplicate writes', () => {
const store = createGeneralSettingsStore().create()
store.actions.syncLocale('en', LOCALES, 5)
// Stale (lower) and duplicate (equal) revisions leave the mirror intact.
store.actions.syncLocale('zh', LOCALES, 4)
store.actions.syncLocale('zh', LOCALES, 5)
expect(store.getSnapshot().localeActive).toBe('en')
expect(store.getSnapshot().localeRevision).toBe(5)
})
it('syncTheme mirrors the preference and guards its revision independently', () => {
const store = createGeneralSettingsStore().create()
store.actions.syncTheme('dark', 0)
expect(store.getSnapshot().themePreference).toBe('dark')
expect(store.getSnapshot().themeRevision).toBe(0)
store.actions.syncTheme('light', 2)
expect(store.getSnapshot().themePreference).toBe('light')
// Stale theme write is dropped; the locale revision axis is untouched.
store.actions.syncTheme('system', 1)
expect(store.getSnapshot().themePreference).toBe('light')
expect(store.getSnapshot().themeRevision).toBe(2)
expect(store.getSnapshot().localeRevision).toBe(-1)
})
})
@@ -31,9 +31,15 @@ export function apply(ctx: ClientContext): void {
]
return () => { for (const dispose of disposers) dispose() }
}, 'ui-settings-models: nav copy dictionaries')
// Declaration-aware registration; the LEDGER is the has-registered judge
// (not a local flag): after an HMR collapse re-declares the slot, the
// cascade already removed our entry, and a stale disposer must not block
// the re-registration.
ctx.effect(() => {
let dispose: (() => void) | undefined
const register = (): void => {
const tryRegister = (): void => {
if (ctx.slots.spec('settings.section') === undefined) return
if (ctx.slots.entries('settings.section').some(e => e.component === ModelsSection)) return
dispose = ctx.slots.register({
name: 'settings.section',
id: 'models',
@@ -41,16 +47,14 @@ export function apply(ctx: ClientContext): void {
label: ctx.locale.bind('settings.models')('nav'),
}, ModelsSection)
}
const tryRegister = (): void => {
if (ctx.slots.spec('settings.section') === undefined || dispose !== undefined) return
register()
}
// Nav labels are registrant-localized: re-register on locale change so
// the ledger carries fresh text (the version bump re-renders the shell).
// Dispose-then-requery: after an HMR collapse the disposer is stale and
// the ledger/spec re-check keeps this path an idempotent no-op.
const offLocale = ctx.on('locale/change', () => {
if (dispose === undefined) return
dispose()
register()
dispose?.()
dispose = undefined
tryRegister()
})
const unsubscribe = ctx.slots.subscribe('settings.section', () => { tryRegister() })
tryRegister()
@@ -0,0 +1,95 @@
/** Models section registration: declaration-aware deferral, locale re-registration, and HMR recovery. */
import { Context } from 'cordis'
import { describe, expect, it } from 'vitest'
import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client'
import { LocaleService } from '@deepseek-ai/dsh-client-locale/client'
import { apply, inject } from '@deepseek-ai/dsh-client-ui-settings-models/client'
import { ModelsSection } from '../src/client/ModelsSection.tsx'
async function bench() {
const ctx = new Context()
await ctx.plugin(SlotsService).await()
const locale = new LocaleService(ctx)
ctx.provide('locale', locale)
return { ctx, slots: ctx.get('slots') as SlotsService, locale }
}
function declare(slots: SlotsService): () => void {
return slots.register(
{ name: 'root', children: { 'settings.section': { kind: 'list', scope: 'root' } } } as never,
() => null,
)
}
describe('ui-settings-models apply', () => {
it('declares the services it uses', () => {
expect(inject).toEqual(['slots', 'locale'])
})
it('registers the models nav entry for declarations before or after apply', async () => {
const before = await bench()
declare(before.slots)
await before.ctx.plugin({ inject: [...inject], apply }).await()
const entry = before.slots.entries('settings.section')[0]!
expect(entry.component).toBe(ModelsSection)
expect(entry.options).toEqual({ id: 'models', order: 10, label: '模型' })
const after = await bench()
await after.ctx.plugin({ inject: [...inject], apply }).await()
expect(after.slots.entries('settings.section')).toHaveLength(0)
declare(after.slots)
await Promise.resolve()
expect(after.slots.entries('settings.section')[0]!.component).toBe(ModelsSection)
// The self-inflicted ledger notifications hit the duplicate guard.
expect(after.slots.entries('settings.section')).toHaveLength(1)
})
it('re-registers with fresh label text on locale change', async () => {
const b = await bench()
declare(b.slots)
await b.ctx.plugin({ inject: [...inject], apply }).await()
b.locale.setLocale('en')
expect(b.slots.entries('settings.section')[0]!.options.label).toBe('Models')
b.locale.setLocale('zh')
expect(b.slots.entries('settings.section')[0]!.options.label).toBe('模型')
})
it('locale change while the slot is undeclared stays a no-op', async () => {
const b = await bench()
await b.ctx.plugin({ inject: [...inject], apply }).await()
b.locale.setLocale('en')
expect(b.slots.entries('settings.section')).toHaveLength(0)
b.locale.setLocale('zh')
})
it('re-registers after an HMR collapse re-declares the slot (stale disposer must not block)', async () => {
const b = await bench()
const redeclare = declare(b.slots)
await b.ctx.plugin({ inject: [...inject], apply }).await()
expect(b.slots.entries('settings.section')).toHaveLength(1)
// Declarer unload: the cascade removes our entry while our local
// disposer variable goes stale.
redeclare()
expect(b.slots.entries('settings.section')).toHaveLength(0)
declare(b.slots)
await Promise.resolve()
expect(b.slots.entries('settings.section')[0]!.component).toBe(ModelsSection)
// The locale path also recovers through the same ledger re-check.
b.locale.setLocale('en')
expect(b.slots.entries('settings.section')[0]!.options.label).toBe('Models')
b.locale.setLocale('zh')
})
it('registers the zh/en nav dictionaries and disposes everything with the fiber', async () => {
const b = await bench()
declare(b.slots)
const fiber = b.ctx.plugin({ inject: [...inject], apply })
await fiber.await()
expect(b.locale.bind('settings.models')('nav')).toBe('模型')
await fiber.dispose()
expect(b.slots.entries('settings.section')).toHaveLength(0)
// The (ns, locale) seats are free again — the dictionary disposers ran.
expect(() => b.locale.register('settings.models', 'zh', {})).not.toThrow()
expect(() => b.locale.register('settings.models', 'en', {})).not.toThrow()
})
})
@@ -0,0 +1,23 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import * as ModelsInvariant from '@deepseek-ai/dsh-client-ui-settings-models/invariant'
import InvariantService from '@deepseek-ai/dsh-invariants'
import { ModelsSection } from '../src/client/ModelsSection.tsx'
describe('invariant companion', () => {
it('registers under the package name with an empty installer', async () => {
const ctx = new Context()
await ctx.plugin(InvariantService, { enabled: true })
await expect(ctx.plugin(ModelsInvariant).await()).resolves.toBeDefined()
})
it('node-half apply is a no-op host placeholder', async () => {
const { apply } = await import('@deepseek-ai/dsh-client-ui-settings-models')
apply()
expect(true).toBe(true) // reaching here without throw is the contract
})
it('the section content column is intentionally empty this phase', () => {
expect(ModelsSection()).toBeNull()
})
})
@@ -43,13 +43,23 @@ export function apply(ctx: ClientContext): void {
sectionsVersion: () => ctx.slots.getVersion('settings.section'),
subscribeSections: (listener) => ctx.slots.subscribe('settings.section', listener),
sections: () => ctx.slots.entries('settings.section')
.map(e => ({ id: e.options.id ?? '', order: e.options.order ?? 0, label: e.options.label ?? '' }))
.map(e => ({
/* v8 ignore next -- list-slot registration requires id (SlotCore rejects an entry without one) */
id: e.options.id ?? '',
order: e.options.order ?? 0,
label: e.options.label ?? '',
}))
.sort((a, b) => a.order - b.order),
})
// Declaration-aware registration; the LEDGER is the has-registered judge
// (not a local flag): after an HMR collapse re-declares the slot, the
// cascade already removed our entry, and a stale disposer must not block
// the re-registration.
ctx.effect(() => {
let dispose: (() => void) | undefined
const tryRegister = (): void => {
if (ctx.slots.spec('sidebar.settings') === undefined || dispose !== undefined) return
if (ctx.slots.spec('sidebar.settings') === undefined) return
if (ctx.slots.entries('sidebar.settings').some(e => e.component === SettingsRoot)) return
dispose = ctx.slots.register({
name: 'sidebar.settings',
children: { 'settings.section': { kind: 'list', scope: 'root' } },
@@ -0,0 +1,120 @@
/** Settings shell registration: declaration-aware deferral, the injected face, and HMR recovery. */
import { Context } from 'cordis'
import { describe, expect, it, vi } from 'vitest'
import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client'
import { LocaleService } from '@deepseek-ai/dsh-client-locale/client'
import { apply, inject } from '@deepseek-ai/dsh-client-ui-settings/client'
import type { SettingsRootInjected } from '@deepseek-ai/dsh-client-ui-settings/client'
import { SettingsRoot } from '../src/client/SettingsRoot.tsx'
async function bench() {
const ctx = new Context()
await ctx.plugin(SlotsService).await()
const locale = new LocaleService(ctx)
ctx.provide('locale', locale)
return { ctx, slots: ctx.get('slots') as SlotsService, locale }
}
function declare(slots: SlotsService): () => void {
return slots.register(
{ name: 'root', children: { 'sidebar.settings': { kind: 'single', scope: 'root' } } } as never,
() => null,
)
}
function injectedOf(slots: SlotsService): SettingsRootInjected {
const entry = slots.entries('sidebar.settings')[0]!
return (entry.inject as () => SettingsRootInjected)()
}
describe('ui-settings apply', () => {
it('declares the services it uses', () => {
expect(inject).toEqual(['slots', 'locale'])
})
it('registers the shell for declarations that arrive before or after apply', async () => {
const before = await bench()
declare(before.slots)
await before.ctx.plugin({ inject: [...inject], apply }).await()
expect(before.slots.entries('sidebar.settings')[0]!.component).toBe(SettingsRoot)
expect(before.slots.spec('settings.section')).toEqual({ kind: 'list', scope: 'root' })
const after = await bench()
await after.ctx.plugin({ inject: [...inject], apply }).await()
expect(after.slots.entries('sidebar.settings')).toHaveLength(0)
declare(after.slots)
await Promise.resolve()
expect(after.slots.entries('sidebar.settings')[0]!.component).toBe(SettingsRoot)
// The self-inflicted ledger notifications hit the duplicate guard.
expect(after.slots.entries('sidebar.settings')).toHaveLength(1)
})
it('registers the zh/en shell dictionaries and disposes them with the fiber', async () => {
const b = await bench()
declare(b.slots)
const fiber = b.ctx.plugin({ inject: [...inject], apply })
await fiber.await()
expect(b.locale.bind('settings')('title')).toBe('设置')
b.locale.setLocale('en')
expect(b.locale.bind('settings')('close')).toBe('Close')
await fiber.dispose()
// The (ns, locale) seats are free again — the dictionary disposers ran.
expect(() => b.locale.register('settings', 'zh', {})).not.toThrow()
expect(() => b.locale.register('settings', 'en', {})).not.toThrow()
})
it('exposes translate over "<ns>:<key>" refs with literal echo for plain text', async () => {
const b = await bench()
declare(b.slots)
await b.ctx.plugin({ inject: [...inject], apply }).await()
const injected = injectedOf(b.slots)
expect(injected.translate('settings:title')).toBe('设置')
expect(injected.translate('no colon ref')).toBe('no colon ref')
})
it('projects the section ledger into ordered nav rows with option defaults', async () => {
const b = await bench()
declare(b.slots)
await b.ctx.plugin({ inject: [...inject], apply }).await()
const injected = injectedOf(b.slots)
expect(injected.sections()).toEqual([])
b.slots.register({ name: 'settings.section', id: 'z', order: 20, label: 'Z' } as never, () => null)
b.slots.register({ name: 'settings.section', id: 'a' } as never, () => null)
expect(injected.sections()).toEqual([
{ id: 'a', order: 0, label: '' },
{ id: 'z', order: 20, label: 'Z' },
])
expect(injected.sectionsVersion()).toBe(b.slots.getVersion('settings.section'))
const listener = vi.fn()
const off = injected.subscribeSections(listener)
b.slots.register({ name: 'settings.section', id: 'b', order: 1, label: 'B' } as never, () => null)
await Promise.resolve()
expect(listener).toHaveBeenCalled()
off()
})
it('re-registers after an HMR collapse re-declares the slot (stale disposer must not block)', async () => {
const b = await bench()
const redeclare = declare(b.slots)
await b.ctx.plugin({ inject: [...inject], apply }).await()
expect(b.slots.entries('sidebar.settings')).toHaveLength(1)
// Declarer unload: the cascade removes our entry and the slot spec while
// our local disposer variable goes stale.
redeclare()
expect(b.slots.entries('sidebar.settings')).toHaveLength(0)
declare(b.slots)
await Promise.resolve()
expect(b.slots.entries('sidebar.settings')[0]!.component).toBe(SettingsRoot)
expect(b.slots.spec('settings.section')).toEqual({ kind: 'list', scope: 'root' })
})
it('unregisters the shell and collapses settings.section on teardown', async () => {
const b = await bench()
declare(b.slots)
const fiber = b.ctx.plugin({ inject: [...inject], apply })
await fiber.await()
await fiber.dispose()
expect(b.slots.entries('sidebar.settings')).toHaveLength(0)
expect(b.slots.spec('settings.section')).toBeUndefined()
})
})
@@ -0,0 +1,18 @@
import { describe, expect, it } from 'vitest'
import { Context } from 'cordis'
import * as SettingsInvariant from '@deepseek-ai/dsh-client-ui-settings/invariant'
import InvariantService from '@deepseek-ai/dsh-invariants'
describe('invariant companion', () => {
it('registers under the package name with an empty installer', async () => {
const ctx = new Context()
await ctx.plugin(InvariantService, { enabled: true })
await expect(ctx.plugin(SettingsInvariant).await()).resolves.toBeDefined()
})
it('node-half apply is a no-op host placeholder', async () => {
const { apply } = await import('@deepseek-ai/dsh-client-ui-settings')
apply()
expect(true).toBe(true) // reaching here without throw is the contract
})
})
@@ -0,0 +1,155 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import type { SettingsRootComponentProps } from '../src/client/contract/slots.ts'
import { SettingsRoot } from '../src/client/SettingsRoot.tsx'
afterEach(cleanup)
const DICT: Record<string, string> = {
'settings:trigger': 'Settings',
'settings:title': 'Settings',
'settings:close': 'Close',
}
type Row = { id: string; order: number; label: string }
function mount({
wide = true,
rows = [
{ id: 'general', order: 0, label: 'General' },
{ id: 'models', order: 10, label: 'Models' },
],
}: { wide?: boolean; rows?: Row[] } = {}) {
// Mutable row store standing in for the ledger; bump() plays a change.
let current = rows
let version = 0
const listeners = new Set<() => void>()
const renderSlot = vi.fn(
((_key: string, _owner: unknown, opts?: { only?: string }) =>
<div data-testid={`section-${opts?.only ?? 'all'}`} />) as SettingsRootComponentProps['renderSlot'],
)
// Global standard kit stubs: the shell consumes neither hook.
const unusedHook = (() => { throw new Error('unused by SettingsRoot') }) as never
const props: SettingsRootComponentProps = {
useSessions: unusedHook,
useWorkspaces: unusedHook,
wide,
translate: (ref) => DICT[ref] ?? ref,
sectionsVersion: () => version,
subscribeSections: (listener) => {
listeners.add(listener)
return () => { listeners.delete(listener) }
},
sections: () => current,
renderSlot,
}
const view = render(<SettingsRoot {...props} />)
const bump = (next: Row[]) => {
act(() => {
current = next
version += 1
for (const fn of [...listeners]) fn()
})
}
return { view, renderSlot, bump, listeners }
}
function openPanel() {
fireEvent.click(screen.getByRole('button', { name: 'Settings' }))
}
describe('SettingsRoot trigger', () => {
it('renders the wide row with the label and opens the dialog', () => {
mount()
const trigger = screen.getByRole('button', { name: 'Settings' })
expect(trigger.textContent).toContain('Settings')
expect(trigger.getAttribute('aria-expanded')).toBe('false')
fireEvent.click(trigger)
expect(screen.getByRole('dialog')).toBeTruthy()
expect(screen.getByRole('button', { name: 'Settings', expanded: true })).toBeTruthy()
})
it('drops the label in the rail state', () => {
mount({ wide: false })
expect(screen.getByRole('button', { name: 'Settings' }).textContent).toBe('')
})
})
describe('SettingsPanel close paths', () => {
it('closes via the header button', () => {
mount()
openPanel()
fireEvent.click(screen.getByRole('button', { name: 'Close' }))
expect(screen.queryByRole('dialog')).toBeNull()
})
it('closes via a mask click', () => {
mount()
openPanel()
const dialog = screen.getByRole('dialog')
fireEvent.click(dialog.parentElement!.firstElementChild!)
expect(screen.queryByRole('dialog')).toBeNull()
})
it('closes via document-level Escape and unhooks the listener with the panel', () => {
mount()
openPanel()
fireEvent.keyDown(document, { key: 'Escape' })
expect(screen.queryByRole('dialog')).toBeNull()
// Ignored while closed (listener removed with the panel) and non-Escape
// keys are ignored while open.
fireEvent.keyDown(document, { key: 'Escape' })
openPanel()
fireEvent.keyDown(document, { key: 'Enter' })
expect(screen.getByRole('dialog')).toBeTruthy()
})
it('lands focus on the close button when the dialog opens', () => {
mount()
openPanel()
expect(document.activeElement).toBe(screen.getByRole('button', { name: 'Close' }))
})
})
describe('SettingsPanel navigation', () => {
it('projects rows, marks the first active, and renders only that section', () => {
mount()
openPanel()
expect(screen.getByRole('button', { name: 'General' }).getAttribute('aria-current')).toBe('true')
expect(screen.getByRole('button', { name: 'Models' }).getAttribute('aria-current')).toBeNull()
expect(screen.getByTestId('section-general')).toBeTruthy()
})
it('switches the rendered section on nav click', () => {
mount()
openPanel()
fireEvent.click(screen.getByRole('button', { name: 'Models' }))
expect(screen.getByRole('button', { name: 'Models' }).getAttribute('aria-current')).toBe('true')
expect(screen.getByTestId('section-models')).toBeTruthy()
expect(screen.queryByTestId('section-general')).toBeNull()
})
it('falls back to the first row when the active entry unregisters', () => {
const { bump } = mount()
openPanel()
fireEvent.click(screen.getByRole('button', { name: 'Models' }))
bump([{ id: 'general', order: 0, label: 'General' }])
expect(screen.queryByRole('button', { name: 'Models' })).toBeNull()
expect(screen.getByTestId('section-general')).toBeTruthy()
})
it('renders an empty content column when the ledger is empty', () => {
const { renderSlot } = mount({ rows: [] })
openPanel()
expect(screen.getByRole('dialog')).toBeTruthy()
expect(renderSlot).not.toHaveBeenCalled()
})
it('drops the ledger subscription on unmount', () => {
const { view, listeners } = mount()
expect(listeners.size).toBe(1)
view.unmount()
expect(listeners.size).toBe(0)
})
})