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

View File

@@ -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()
})

View File

@@ -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')
})
})

View File

@@ -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')
})
})

View File

@@ -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
})
})

View File

@@ -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)
})
})