refactor: apply repository naming contract

Apply the accepted pre-release package, service, type, directory, and role renames as one repository-wide change.
This commit is contained in:
Tianyi Cui
2026-08-13 00:36:22 +08:00
parent 101df7cf58
commit a2d0f7f411
3281 changed files with 21730 additions and 21592 deletions

View File

@@ -0,0 +1,176 @@
/** Models section registration: slot declaration injection, the locale-following label thunk, and HMR recovery. */
import { Context } from '@deepseek-ai/cordis'
import { describe, expect, it, vi } from 'vitest'
import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots'
import { SlotRegistry } from '@deepseek-ai/dsh-client-runtime/client'
import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
import { TestRemote, usePinnedBrowserLanguages } from '@deepseek-ai/dsh-client-test-runtime'
import { apply, inject, refreshIfLoaded } from '@deepseek-ai/dsh-client-ui-settings-models/client'
import { ModelsSection } from '../src/client/ModelsSection.tsx'
import { DeepSeekOnboardingDialog } from '../src/client/DeepSeekOnboardingDialog.tsx'
// The service reads its initial locale from the browser; these specs assert
// the shipped Chinese copy, so they state the browser they assume.
usePinnedBrowserLanguages('zh-CN')
async function bench() {
const ctx = new Context()
await ctx.plugin(SlotRegistry).await()
const locale = new LocaleRuntime(ctx)
ctx.provide('locale', locale)
// The plugins inject `remote`; forwarded events reach them through the
// same `$dispatch` handoff the connection sink makes.
new TestRemote(ctx)
// The apply path only captures the wire face; no call leaves this fake
// until a section actually loads.
ctx.provide('connection', { api: {} } as never)
return { ctx, slots: ctx.get('slots') as SlotRegistry, locale }
}
function declare(slots: SlotRegistry): () => void {
return slots.register(
{
name: 'root',
children: {
'settings.section': { kind: 'list', scope: 'root' },
'settings.onboarding': { kind: 'list', scope: 'root' },
},
} as never,
() => null,
)
}
describe('ui-settings-models apply', () => {
it('declares the services it uses', () => {
expect(inject).toEqual(['slots', 'locale', 'connection', 'remote'])
})
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).toMatchObject({ id: 'models', order: 10 })
// The nav label is a locale-following thunk; owners resolve at read time.
expect(resolveSlotLabel(entry.options.label)).toBe('模型')
const injected = (entry.inject as unknown as () => import('../src/client/ModelsSection.tsx').ModelsSectionInjected)()
expect(injected.t('nav')).toBe('模型')
expect(injected.t('deleteTitle')).toBe('删除 {provider}')
expect(typeof injected.controller.load).toBe('function')
expect(typeof injected.useSnapshot).toBe('function')
expect(injected.api).toBeDefined()
const onboarding = before.slots.entries('settings.onboarding')[0]!
expect(onboarding.component).toBe(DeepSeekOnboardingDialog)
expect(onboarding.options).toMatchObject({ id: 'deepseek-official', order: 0 })
const after = await bench()
await after.ctx.plugin({ inject: [...inject], apply }).await()
expect(after.slots.entries('settings.section')).toHaveLength(0)
expect(after.slots.entries('settings.onboarding')).toHaveLength(0)
declare(after.slots)
await Promise.resolve()
expect(after.slots.entries('settings.section')[0]!.component).toBe(ModelsSection)
expect(after.slots.entries('settings.onboarding')[0]!.component).toBe(DeepSeekOnboardingDialog)
// The self-inflicted ledger notifications hit the duplicate guard.
expect(after.slots.entries('settings.section')).toHaveLength(1)
})
it('the label thunk follows the active locale without re-registration', async () => {
const b = await bench()
declare(b.slots)
await b.ctx.plugin({ inject: [...inject], apply }).await()
b.locale.setLocale('en')
expect(resolveSlotLabel(b.slots.entries('settings.section')[0]!.options.label)).toBe('Models')
const injected = b.slots.entries('settings.section')[0]!.inject as unknown as () => import('../src/client/ModelsSection.tsx').ModelsSectionInjected
expect(injected().t('deleteTitle')).toBe('Delete {provider}?')
b.locale.setLocale('zh')
expect(resolveSlotLabel(b.slots.entries('settings.section')[0]!.options.label)).toBe('模型')
expect(injected().t('deleteTitle')).toBe('删除 {provider}')
})
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)
expect(b.slots.entries('settings.onboarding')).toHaveLength(0)
declare(b.slots)
await Promise.resolve()
expect(b.slots.entries('settings.section')[0]!.component).toBe(ModelsSection)
expect(b.slots.entries('settings.onboarding')[0]!.component).toBe(DeepSeekOnboardingDialog)
// The locale path also recovers through the same ledger re-check.
b.locale.setLocale('en')
expect(resolveSlotLabel(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)
expect(b.slots.entries('settings.onboarding')).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()
})
})
describe('pushed invalidations', () => {
it('ignores invalidations before the page ever loaded', async () => {
const b = await bench()
declare(b.slots)
await b.ctx.plugin({ inject: [...inject], apply }).await()
// The fake wire face has no methods: a fetch attempt would throw.
b.ctx.remote.$dispatch('settings/document-updated', ['llm-pi-ai', 1])
b.ctx.remote.$dispatch('credentials/updated', ['OPENAI_API_KEY'])
b.ctx.remote.$dispatch('llm/adapters-updated', [])
b.ctx.emit('connection/reset')
})
it('refreshes a loaded page and skips an idle one', () => {
const loads: number[] = []
const controller = {
store: { getSnapshot: () => ({ status: 'ready' }) },
load: () => { loads.push(1); return Promise.resolve() },
}
refreshIfLoaded(controller as unknown as import('../src/client/store.ts').ModelsSettingsStore)
expect(loads).toHaveLength(1)
const idle = {
store: { getSnapshot: () => ({ status: 'idle' }) },
load: () => { loads.push(2); return Promise.resolve() },
}
refreshIfLoaded(idle as unknown as import('../src/client/store.ts').ModelsSettingsStore)
expect(loads).toHaveLength(1)
})
it('routes pushed credential invalidation into the shared onboarding join', async () => {
const b = await bench()
declare(b.slots)
await b.ctx.plugin({ inject: [...inject], apply }).await()
const injected = (
b.slots.entries('settings.onboarding')[0]!.inject as unknown as
() => import('../src/client/DeepSeekOnboardingDialog.tsx').DeepSeekOnboardingInjected
)()
injected.controller.store.update((state) => { state.status = 'ready' })
const load = vi.spyOn(injected.controller, 'load').mockResolvedValue()
b.ctx.remote.$dispatch('credentials/updated', ['DEEPSEEK_API_KEY'])
expect(load).toHaveBeenCalledTimes(1)
})
})

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,23 @@
import { describe, expect, it } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import * as ModelsInvariant from '@deepseek-ai/dsh-client-ui-settings-models/invariant'
import InvariantRegistry 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(InvariantRegistry, { 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('renders null until the shell injects the section dependencies', () => {
expect(ModelsSection({})).toBeNull()
})
})

View File

@@ -0,0 +1,178 @@
// @vitest-environment jsdom
/** First-run DeepSeek prompt behavior over the shared Models join. */
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { RpcResponse } from '@deepseek-ai/dsh-api-remotes/client'
import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
import { DeepSeekOnboardingDialog } from '../src/client/DeepSeekOnboardingDialog.tsx'
import type { DeepSeekOnboardingDialogProps } from '../src/client/DeepSeekOnboardingDialog.tsx'
import { ModelsSettingsStore } from '../src/client/store.ts'
import { en } from '../src/client/locales.ts'
afterEach(cleanup)
let nextRpc = 0
function ok<T>(value: T): RpcResponse<T> {
return { rpcId: `onboarding-${nextRpc++}` as never, result: { ok: true, value } }
}
function fail<T>(message: string): RpcResponse<T> {
return {
rpcId: `onboarding-${nextRpc++}` as never,
result: { ok: false, error: { code: 'internal', message, details: {} } },
}
}
function harness(options: {
provider?: boolean
providerSettingsNs?: string
providerActive?: boolean
settingsNamespace?: boolean
apiKeyEnv?: string | null
configured?: () => boolean
credential?: { source?: string; writable: boolean }
describeFailure?: string
settingsWritable?: boolean
providersReject?: boolean
} = {}) {
let fileConfigured = false
const configured = options.configured ?? (() => fileConfigured)
const face = {
llm: {
providers: () => {
if (options.providersReject === true) return Promise.reject(new Error('provider transport unavailable'))
return Promise.resolve(ok({
providers: options.provider === false
? []
: [{
provider: 'deepseek-official',
displayName: 'DeepSeek',
settingsNs: options.providerSettingsNs ?? 'llm-deepseek',
settingsPath: [],
active: options.providerActive ?? true,
}],
}))
},
},
settings: {
describe: () => Promise.resolve(ok({
writable: options.settingsWritable ?? true,
namespaces: options.settingsNamespace === false
? []
: [{
ns: 'llm-deepseek',
schema: {},
value: options.apiKeyEnv === null
? {}
: { apiKeyEnv: options.apiKeyEnv ?? 'DEEPSEEK_API_KEY' },
applies: 'live' as const,
secrets: [],
revision: 0,
}],
})),
},
credentials: {
describe: () => options.describeFailure === undefined
? Promise.resolve(ok({
credentials: {
DEEPSEEK_API_KEY: {
configured: configured(),
...configured() && options.credential?.source !== undefined
? { source: options.credential.source }
: {},
writable: options.credential?.writable ?? true,
},
},
}))
: Promise.resolve(fail(options.describeFailure)),
},
}
const controller = new ModelsSettingsStore(face as never)
const openSection = vi.fn()
const complete = vi.fn()
const unusedHook = (() => { throw new Error('unused standard hook') }) as never
const props: DeepSeekOnboardingDialogProps = {
stepId: 'deepseek-official',
complete,
openSection,
useSessions: unusedHook,
useWorkspaces: unusedHook,
controller,
useSnapshot: bindSnapshotSelector(controller.store),
t: key => en[key],
}
return { controller, complete, openSection, props, configure: () => { fileConfigured = true } }
}
describe('DeepSeekOnboardingDialog', () => {
it('loads on first entry and presents one accessible route to Models', async () => {
const h = harness()
render(<DeepSeekOnboardingDialog {...h.props} />)
expect(await screen.findByRole('region', { name: en.onboardingTitle })).toBeTruthy()
expect(screen.getByText(en.onboardingDescription)).toBeTruthy()
const action = screen.getByRole('button', { name: en.onboardingGoToSettings })
expect(action).toBeTruthy()
expect(document.activeElement).toBe(screen.getByRole('heading', { name: en.onboardingTitle }))
expect(screen.queryByRole('textbox')).toBeNull()
})
it('opens the Models section and dismisses the prompt', async () => {
const h = harness()
render(<DeepSeekOnboardingDialog {...h.props} />)
await screen.findByRole('region')
fireEvent.click(screen.getByRole('button', { name: en.onboardingGoToSettings }))
expect(h.complete).toHaveBeenCalledOnce()
expect(h.openSection).toHaveBeenCalledWith('models')
})
it('allows configure-later dismissal without opening settings', async () => {
const h = harness()
render(<DeepSeekOnboardingDialog {...h.props} />)
await screen.findByRole('region')
fireEvent.click(screen.getByRole('button', { name: en.onboardingLater }))
expect(h.complete).toHaveBeenCalledOnce()
expect(h.openSection).not.toHaveBeenCalled()
})
it('does not block the product when DeepSeek setup is unavailable', async () => {
for (const h of [
harness({ describeFailure: 'credentials service is absent' }),
harness({ credential: { writable: false } }),
harness({ settingsWritable: false }),
harness({ providersReject: true }),
harness({ providerActive: false }),
harness({ settingsNamespace: false }),
harness({ apiKeyEnv: null }),
]) {
const view = render(<DeepSeekOnboardingDialog {...h.props} />)
await act(async () => { await h.controller.load() })
expect(screen.queryByRole('region')).toBeNull()
await waitFor(() => { expect(h.complete).toHaveBeenCalledOnce() })
expect(h.openSection).not.toHaveBeenCalled()
view.unmount()
}
})
it('skips an absent adapter and an already-configured environment credential', async () => {
for (const h of [
harness({ provider: false }),
harness({ providerSettingsNs: '' }),
harness({ configured: () => true, credential: { source: 'env', writable: false } }),
]) {
const view = render(<DeepSeekOnboardingDialog {...h.props} />)
await act(async () => { await h.controller.load() })
expect(screen.queryByRole('region')).toBeNull()
await waitFor(() => { expect(h.complete).toHaveBeenCalledOnce() })
view.unmount()
}
})
it('closes when an external credential invalidation refreshes the shared join', async () => {
const h = harness()
render(<DeepSeekOnboardingDialog {...h.props} />)
await screen.findByRole('region')
h.configure()
await act(async () => { await h.controller.load() })
await waitFor(() => { expect(screen.queryByRole('region')).toBeNull() })
expect(h.complete).toHaveBeenCalledOnce()
})
})

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,130 @@
/** Pure first-run readiness projection over the shared Models join. */
import { describe, expect, it } from 'vitest'
import type { CredentialView } from '@deepseek-ai/dsh-api-remotes/client'
import type { ModelsSettingsState, ProviderRow } from '../src/client/store.ts'
import { onboardingReadiness, providerUsable } from '../src/client/store.ts'
const missingCredential: CredentialView = { configured: false, writable: true }
function row(overrides: Partial<ProviderRow> = {}): ProviderRow {
return {
entry: {
provider: 'deepseek-official',
displayName: 'DeepSeek',
settingsNs: 'llm-deepseek',
settingsPath: [],
active: true,
},
configured: true,
removable: false,
apiKeyEnv: 'DEEPSEEK_API_KEY',
credential: missingCredential,
...overrides,
}
}
/** A second provider the user configured themselves. */
function otherRow(overrides: Partial<ProviderRow> = {}): ProviderRow {
return {
entry: {
provider: 'hfai',
displayName: 'HFAI',
settingsNs: 'llm-pi-ai',
settingsPath: ['providers', 'hfai'],
active: true,
},
configured: true,
removable: true,
apiKeyEnv: 'HFAI_API_KEY',
credential: { configured: true, source: 'file', writable: true },
...overrides,
}
}
function state(overrides: Partial<ModelsSettingsState> = {}): ModelsSettingsState {
return {
status: 'ready',
error: null,
credentialError: null,
writable: true,
rows: [row()],
namespaces: new Map(),
...overrides,
}
}
describe('providerUsable', () => {
it('requires a registered route and a stored key for every named reference', () => {
expect(providerUsable(otherRow())).toBe(true)
expect(providerUsable(otherRow({ entry: { ...otherRow().entry, active: false } }))).toBe(false)
expect(providerUsable(otherRow({ credential: missingCredential }))).toBe(false)
expect(providerUsable(otherRow({ credential: undefined }))).toBe(false)
})
it('treats a reference-free registered route as provider-native authentication', () => {
expect(providerUsable(otherRow({ apiKeyEnv: undefined, credential: undefined }))).toBe(true)
})
})
describe('onboardingReadiness', () => {
it('waits for the first join and skips onboarding when the adapter directory entry is absent', () => {
expect(onboardingReadiness(state({ status: 'idle', rows: [] }))).toEqual({ kind: 'loading' })
expect(onboardingReadiness(state({ status: 'loading', rows: [] }))).toEqual({ kind: 'loading' })
expect(onboardingReadiness(state({ rows: [] }))).toEqual({ kind: 'adapter-absent' })
expect(onboardingReadiness(state({
rows: [row({
entry: {
...row().entry,
settingsNs: '',
},
})],
}))).toEqual({ kind: 'adapter-absent' })
})
it('reports a missing writable effective credential', () => {
expect(onboardingReadiness(state())).toEqual({ kind: 'credential-missing' })
})
it('ends onboarding once any other registered provider can serve requests', () => {
expect(onboardingReadiness(state({ rows: [row(), otherRow()] }))).toEqual({ kind: 'provider-ready' })
// A provider the user cannot reach yet leaves the prompt in place.
expect(onboardingReadiness(state({
rows: [row(), otherRow({ credential: missingCredential })],
}))).toEqual({ kind: 'credential-missing' })
})
it('accepts file and process-environment credentials without prompting', () => {
expect(onboardingReadiness(state({
rows: [row({ credential: { configured: true, source: 'file', writable: true } })],
}))).toEqual({ kind: 'provider-ready' })
expect(onboardingReadiness(state({
rows: [row({ credential: { configured: true, source: 'env', writable: false } })],
}))).toEqual({ kind: 'provider-ready' })
})
it('turns missing capabilities into diagnostics that never block the product', () => {
expect(onboardingReadiness(state({ status: 'error', error: 'settings down' }))).toEqual({
kind: 'unavailable',
reason: 'load-failed',
})
expect(onboardingReadiness(state({
rows: [row({ entry: { ...row().entry, active: false } })],
}))).toEqual({ kind: 'unavailable', reason: 'provider-inactive' })
expect(onboardingReadiness(state({
credentialError: 'credentials service is absent',
}))).toEqual({
kind: 'unavailable',
reason: 'credentials-unavailable',
})
expect(onboardingReadiness(state({
rows: [row({ credential: undefined })],
}))).toEqual({ kind: 'unavailable', reason: 'credentials-unavailable' })
expect(onboardingReadiness(state({
rows: [row({ credential: { configured: false, writable: false } })],
}))).toEqual({ kind: 'unavailable', reason: 'credential-read-only' })
expect(onboardingReadiness(state({ writable: false }))).toEqual({
kind: 'unavailable',
reason: 'settings-read-only',
})
})
})

View File

@@ -0,0 +1,265 @@
/** Page-store join: directory × namespaces × credentials, with last-good rows on failure. */
import { describe, expect, it } from 'vitest'
import type { RpcResponse } from '@deepseek-ai/dsh-api-remotes/client'
import { messageOf, ModelsSettingsStore } from '../src/client/store.ts'
let nextRpc = 0
function ok<T>(value: T): RpcResponse<T> {
return { rpcId: `r-${nextRpc++}` as never, result: { ok: true, value } }
}
function fail<T>(message: string): RpcResponse<T> {
return { rpcId: `r-${nextRpc++}` as never, result: { ok: false, error: { code: 'internal', message, details: {} } } }
}
const DIRECTORY = [
{ provider: 'deepseek-official', displayName: 'DeepSeek', settingsNs: 'llm-deepseek', settingsPath: [], active: true },
{ provider: 'openai', displayName: 'openai', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'openai'], active: true },
{ provider: 'anthropic', displayName: 'anthropic', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'anthropic'], active: false },
{ provider: 'ghost', displayName: 'Ghost', settingsNs: '', settingsPath: [], active: true },
]
const NAMESPACES = [
{
ns: 'llm-deepseek',
schema: {},
value: { apiKeyEnv: 'DEEPSEEK_API_KEY', baseURL: 'https://base' },
base: { baseURL: 'https://base' },
applies: 'live' as const,
secrets: [],
revision: 0,
},
{
ns: 'llm-pi-ai',
schema: {},
value: { providers: { openai: { apiKeyEnv: 'OPENAI_API_KEY' } } },
user: { providers: { openai: { apiKeyEnv: 'OPENAI_API_KEY' } } },
applies: 'live' as const,
secrets: [],
revision: 0,
},
]
function api(overrides: {
providers?: () => Promise<RpcResponse<{ providers: typeof DIRECTORY }>>
describeSettings?: () => Promise<RpcResponse<{ writable: boolean; namespaces: typeof NAMESPACES }>>
describeCredentials?: (refs: string[]) => Promise<RpcResponse<{ credentials: Record<string, unknown> }>>
} = {}) {
const seenRefs: string[][] = []
const face = {
llm: {
providers: overrides.providers ?? (() => Promise.resolve(ok({ providers: DIRECTORY }))),
models: () => Promise.resolve(ok({ groups: [], failures: [] })),
},
settings: {
describe: overrides.describeSettings ?? (() => Promise.resolve(ok({ writable: true, hasDocument: false, namespaces: NAMESPACES }))),
update: () => Promise.resolve(fail('unused')),
replace: () => Promise.resolve(fail('unused')),
},
credentials: {
describe: (payload: { refs: string[] }) => {
seenRefs.push(payload.refs)
return (overrides.describeCredentials ?? (refs => Promise.resolve(ok({
credentials: Object.fromEntries(refs.map(ref => [ref, { configured: ref === 'OPENAI_API_KEY', writable: true }])),
}))))(payload.refs)
},
set: () => Promise.resolve(ok({})),
unset: () => Promise.resolve(ok({})),
},
}
return { face: face as never, seenRefs }
}
describe('ModelsSettingsStore', () => {
it('joins rows with configured, removable, and credential state', async () => {
const { face, seenRefs } = api()
const store = new ModelsSettingsStore(face)
await store.load()
const state = store.store.getSnapshot()
expect(state.status).toBe('ready')
expect(state.writable).toBe(true)
expect(state.credentialError).toBeNull()
expect(seenRefs).toEqual([['DEEPSEEK_API_KEY', 'OPENAI_API_KEY']])
const byProvider = new Map(state.rows.map(row => [row.entry.provider, row]))
expect(byProvider.get('deepseek-official')).toMatchObject({
configured: true,
removable: false,
apiKeyEnv: 'DEEPSEEK_API_KEY',
credential: { configured: false, writable: true },
})
expect(byProvider.get('openai')).toMatchObject({
configured: true,
removable: true,
apiKeyEnv: 'OPENAI_API_KEY',
credential: { configured: true },
})
expect(byProvider.get('anthropic')).toMatchObject({ configured: false, removable: false })
expect(byProvider.get('anthropic')?.apiKeyEnv).toBeUndefined()
expect(byProvider.get('ghost')).toMatchObject({ configured: false, removable: false })
expect(state.namespaces.get('llm-pi-ai')?.ns).toBe('llm-pi-ai')
})
it('degrades the credential badge, not the page, when the credential domain fails', async () => {
const { face } = api({ describeCredentials: () => Promise.resolve(fail('no provider')) })
const store = new ModelsSettingsStore(face)
await store.load()
const state = store.store.getSnapshot()
expect(state.status).toBe('ready')
expect(state.credentialError).toBe('no provider')
expect(state.rows.every(row => row.credential === undefined)).toBe(true)
})
it('settles a credential transport rejection without leaving the store loading', async () => {
const { face } = api({
describeCredentials: () => Promise.reject(new Error('credential transport down')),
})
const store = new ModelsSettingsStore(face)
await expect(store.load()).resolves.toBeUndefined()
expect(store.store.getSnapshot()).toMatchObject({
status: 'ready',
credentialError: 'credential transport down',
})
})
it('stringifies a non-Error credential transport rejection', async () => {
const { face } = api({
// oxlint-disable-next-line typescript/prefer-promise-reject-errors -- the non-Error rejection is the scenario
describeCredentials: () => Promise.reject('credential transport refusal'),
})
const store = new ModelsSettingsStore(face)
await expect(store.load()).resolves.toBeUndefined()
expect(store.store.getSnapshot().credentialError).toBe('credential transport refusal')
})
it('surfaces a directory failure and keeps the last good rows', async () => {
const { face } = api()
const store = new ModelsSettingsStore(face)
await store.load()
expect(store.store.getSnapshot().rows).toHaveLength(4)
const broken = api({ providers: () => Promise.resolve(fail('directory down')) })
const failing = new ModelsSettingsStore(broken.face)
await failing.load()
expect(failing.store.getSnapshot()).toMatchObject({ status: 'error', error: 'directory down' })
// The first store's snapshot is untouched by the second's failure.
expect(store.store.getSnapshot().status).toBe('ready')
})
it('lets the newest load win over a stale slow response', async () => {
let release: (() => void) | undefined
const gate = new Promise<void>((resolve) => { release = resolve })
let call = 0
const { face } = api({
providers: async () => {
call += 1
if (call === 1) {
await gate
return fail('stale slow failure')
}
return ok({ providers: DIRECTORY })
},
})
const store = new ModelsSettingsStore(face)
const first = store.load()
const second = store.load()
release?.()
await Promise.all([first, second])
expect(store.store.getSnapshot().status).toBe('ready')
})
})
describe('edge joins', () => {
it('treats a non-object profile as having no credential reference', async () => {
const { face } = api({
describeSettings: () => Promise.resolve(ok({
writable: true,
hasDocument: false,
namespaces: [{
ns: 'llm-pi-ai',
schema: {},
value: { providers: { weird: 'oops' } },
applies: 'live' as const,
secrets: [],
revision: 0,
}] as never,
})),
providers: () => Promise.resolve(ok({
providers: [
{ provider: 'weird', displayName: 'weird', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'weird'], active: false },
] as never,
})),
})
const store = new ModelsSettingsStore(face)
await store.load()
const state = store.store.getSnapshot()
expect(state.rows[0]).toMatchObject({ configured: true, removable: false })
expect(state.rows[0]?.apiKeyEnv).toBeUndefined()
})
it('skips the credential describe entirely when no row names a reference', async () => {
const { face, seenRefs } = api({
describeSettings: () => Promise.resolve(ok({
writable: true,
hasDocument: false,
namespaces: [{ ns: 'llm-pi-ai', schema: {}, value: { providers: {} }, applies: 'live' as const, secrets: [], revision: 0 }] as never,
})),
providers: () => Promise.resolve(ok({
providers: [
{ provider: 'anthropic', displayName: 'anthropic', settingsNs: 'llm-pi-ai', settingsPath: ['providers', 'anthropic'], active: false },
] as never,
})),
})
const store = new ModelsSettingsStore(face)
await store.load()
expect(seenRefs).toEqual([])
expect(store.store.getSnapshot().status).toBe('ready')
})
it('surfaces a settings describe failure', async () => {
const { face } = api({ describeSettings: () => Promise.resolve(fail('settings down')) })
const store = new ModelsSettingsStore(face)
await store.load()
expect(store.store.getSnapshot()).toMatchObject({ status: 'error', error: 'settings down' })
})
it('stringifies a non-Error load failure', async () => {
// The wire can surface non-Error throwables; the store must stringify them.
// oxlint-disable-next-line typescript/prefer-promise-reject-errors -- the non-Error rejection is the scenario
const { face } = api({ providers: () => Promise.reject('plain refusal') })
const store = new ModelsSettingsStore(face)
await store.load()
expect(store.store.getSnapshot()).toMatchObject({ status: 'error', error: 'plain refusal' })
})
it('drops a stale successful response after a newer load finished', async () => {
let release: (() => void) | undefined
const gate = new Promise<void>((resolve) => { release = resolve })
let call = 0
const { face } = api({
providers: async () => {
call += 1
if (call === 1) {
await gate
return ok({ providers: [] as never })
}
return ok({ providers: DIRECTORY })
},
})
const store = new ModelsSettingsStore(face)
const first = store.load()
const second = store.load()
await second
release?.()
await first
// The stale empty directory never overwrote the newer join.
expect(store.store.getSnapshot().rows).toHaveLength(4)
})
})
describe('messageOf', () => {
it('reads an Error message, and stringifies anything else a rejection may carry', () => {
// The wire layer rejects with an Error, but a host or a runtime can reject
// with any value, and the page still has to render something.
expect(messageOf(new Error('connection lost'))).toBe('connection lost')
expect(messageOf('the host refused')).toBe('the host refused')
expect(messageOf(undefined)).toBe('undefined')
})
})

View File

@@ -0,0 +1,92 @@
/**
* Models section stylesheet contract, asserted against the CSS text on disk.
*
* The section paints in both themes, and a `--dsw-*` name the theme does not
* declare fails silently: the browser takes the `var()` fallback, so the sheet
* still renders and only the dark theme looks wrong. Checking the names against
* the sheet that declares them is what turns that into a test failure.
*/
import { readdirSync, readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
const css = readFileSync(fileURLToPath(new URL('../src/client/ModelsSection.module.css', import.meta.url)), 'utf8')
// The theme package maps `./styles/*` to `./src/styles/*`, so the declarations
// stay on the source plane rather than needing a build.
// Every theme sheet, not just the platform tokens: font and scrollbar
// variables are declared in siblings, and a gate reading one file would call
// their names undeclared.
const tokens = readdirSync(fileURLToPath(new URL('../../ui-theme/src/styles/', import.meta.url)))
.filter(name => name.endsWith('.css'))
.map(name => readFileSync(fileURLToPath(new URL(`../../ui-theme/src/styles/${name}`, import.meta.url)), 'utf8'))
.join('\n')
/** The declarations of one top-level rule, by selector. */
function block(selector: string): string {
const match = new RegExp(`^\\${selector} \\{([^}]*)\\}`, 'm').exec(css)
if (match === null) throw new Error(`ModelsSection.module.css has no \`${selector}\` rule`)
return match[1] ?? ''
}
describe('ModelsSection theme styles', () => {
it('names only theme variables the token sheet defines', () => {
// A `--dsw-*` name the sheet never declares is not a near miss: it silently
// resolves to whatever literal sits in its fallback slot, which is how this
// section stayed light under the dark theme before. Undeclared names have
// no fallback at all and inherit, so both spellings must fail here.
// Every theme-variable prefix the sheets actually use, not just `--dsw-`:
// a `--dsh-` name reads as a plausible sibling and would otherwise slip
// past this gate into a fallback literal.
const named = [...css.matchAll(/var\((--(?:dsw|dsh|ds)-[a-z0-9-]+)/g)].map(match => match[1])
const undeclared = [...new Set(named)].filter(name => !tokens.includes(` ${String(name)}:`))
expect(undeclared).toEqual([])
expect(css).not.toMatch(/var\(--(?:surface|text-|border|accent-strong)/)
})
it('closes every block, so no rule is swallowed by the one above it', () => {
// A missing `}` on an `@media` block is not a parse error: every rule after
// it silently becomes conditional, and the whole fetch dialog once painted
// unstyled for anyone whose system does not ask for reduced motion. Nothing
// downstream reports this — the sheet loads and the classes still attach.
const bare = css.replace(/\/\*[\s\S]*?\*\//g, '')
expect((bare.match(/\}/g) ?? []).length).toBe((bare.match(/\{/g) ?? []).length)
})
it('separates the row card from the editor it expands into', () => {
// `bg-layer-3` and `bg-module-platform` both resolve to neutral-bluish-800
// under the dark theme, so filling the row with either erases the nested
// editor's boundary. The row is outlined; the fill is the editor's alone.
expect(block('.editor')).toContain('background: var(--dsw-alias-bg-module-platform)')
expect(block('.rowCard')).toContain('border: 1px solid var(--dsw-alias-border-l2)')
expect(block('.rowCard')).not.toMatch(/\bbackground\s*:/)
})
it('gives every dropdown the shared chevron instead of the OS arrow', () => {
// `select.input` caps the control at 240px, and the OS arrow is painted
// flush inside that shrunk right edge — visibly tighter than every other
// control on the page. `.selectInput` is what removes it, reserves the
// right pad, and paints the shared chevron; a `<select>` that takes
// `.input` alone silently keeps the OS one.
const sources = readdirSync(fileURLToPath(new URL('../src/client/', import.meta.url)))
.filter(name => name.endsWith('.tsx'))
.map(name => ({
name,
text: readFileSync(fileURLToPath(new URL(`../src/client/${name}`, import.meta.url)), 'utf8'),
}))
const bare = sources.flatMap(({ name, text }) => text
.split('<select')
.slice(1)
// The element's own attributes end at the first `>`; a child `<option>`
// carries no className of its own and must not answer for the select.
.map(rest => rest.slice(0, rest.indexOf('>')))
.filter(attributes => !attributes.includes('selectInput'))
.map(() => name))
expect(bare).toEqual([])
})
it('never falls back to a literal colour', () => {
// A token that resolves is never the problem; an undeclared one takes this
// branch, and a literal here is a single colour for both themes.
expect(css).not.toMatch(/var\(--dsw-[a-z0-9-]+\s*,\s*(?:#|rgb|rgba|hsl|hsla)/)
})
})