apply.client.spec.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. /** Models section registration: slot declaration injection, the locale-following label thunk, and HMR recovery. */
  2. import { Context } from '@deepseek-ai/cordis'
  3. import { describe, expect, it, vi } from 'vitest'
  4. import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots'
  5. import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
  6. import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
  7. import { TestRemote } from '@deepseek-ai/dsh-client-test-runtime'
  8. import { apply as settingsApply, inject as settingsInject } from '@deepseek-ai/dsh-client-ui-settings/client'
  9. import { apply, inject, refreshIfLoaded } from '@deepseek-ai/dsh-client-ui-settings-models/client'
  10. import {
  11. WELCOME_NOTICE_ACK_FIELD, WELCOME_NOTICE_SETTINGS_NAMESPACE, WELCOME_NOTICE_VERSION,
  12. } from '../src/onboarding-copy.ts'
  13. import { ModelsSection } from '../src/client/ModelsSection.tsx'
  14. import { DeepSeekOnboardingDialog } from '../src/client/DeepSeekOnboardingDialog.tsx'
  15. import { WelcomeNotice } from '../src/client/WelcomeNotice.tsx'
  16. // These specs assert the shipped Chinese copy. The lane has no jsdom `window`,
  17. // so browser-language detection never runs and a fresh LocaleRuntime opens on
  18. // FALLBACK_LOCALE (en); bench stages zh explicitly on the locale instead.
  19. async function bench(isLoopback = true, settings?: object, services: object = {}) {
  20. const ctx = new Context()
  21. await ctx.plugin(SlotRegistry).await()
  22. const locale = new LocaleRuntime(ctx)
  23. locale.setLocale('zh')
  24. ctx.provide('locale', locale)
  25. const remote = new TestRemote(ctx)
  26. // Without a settings face the mirror's reads fail and stay contained; the
  27. // Models join itself never fetches until a section actually loads. The real
  28. // ui-settings apply also provides the settingsSchema service.
  29. ctx.provide('connection', {
  30. api: settings === undefined ? services : { ...services, settings },
  31. isLoopback,
  32. } as never)
  33. await ctx.plugin({ inject: [...settingsInject], apply: settingsApply }).await()
  34. return { ctx, slots: ctx.get('slots') as SlotRegistry, locale, remote }
  35. }
  36. function declare(slots: SlotRegistry): () => void {
  37. return slots.register(
  38. {
  39. name: 'root',
  40. children: {
  41. 'settings.section': { kind: 'list', scope: 'root' },
  42. 'settings.onboarding': { kind: 'list', scope: 'root' },
  43. },
  44. } as never,
  45. () => null,
  46. )
  47. }
  48. describe('ui-settings-models apply', () => {
  49. it('declares the services it uses', () => {
  50. expect(inject).toEqual(['slots', 'locale', 'connection', 'remote', 'settingsScope', 'settingsSchema'])
  51. })
  52. it('registers the models nav entry for declarations before or after apply', async () => {
  53. const before = await bench()
  54. declare(before.slots)
  55. await before.ctx.plugin({ inject: [...inject], apply }).await()
  56. const entry = before.slots.entries('settings.section')[0]!
  57. expect(entry.component).toBe(ModelsSection)
  58. expect(entry.options).toMatchObject({ id: 'models', order: 10 })
  59. // The nav label is a locale-following thunk; owners resolve at read time.
  60. expect(resolveSlotLabel(entry.options.label)).toBe('模型')
  61. const injected = (entry.inject as unknown as () => import('../src/client/ModelsSection.tsx').ModelsSectionInjected)()
  62. expect(injected.t('nav')).toBe('模型')
  63. expect(injected.t('deleteTitle')).toBe('删除 {provider}?')
  64. expect(typeof injected.controller.load).toBe('function')
  65. expect(injected.hooks.snapshot).toBe(injected.controller.store)
  66. expect(injected.api).toBeDefined()
  67. const onboarding = before.slots.entries('settings.onboarding')
  68. expect(onboarding).toHaveLength(2)
  69. expect(onboarding.find(entry => entry.options.id === 'welcome-notice')).toMatchObject({
  70. component: WelcomeNotice,
  71. options: { id: 'welcome-notice', order: -100 },
  72. })
  73. const deepSeek = onboarding.find(entry => entry.options.id === 'deepseek-official')!
  74. expect(deepSeek.component).toBe(DeepSeekOnboardingDialog)
  75. expect(deepSeek.options).toMatchObject({ id: 'deepseek-official', order: 0 })
  76. const deepSeekInjected = (
  77. deepSeek.inject as unknown as () => import('../src/client/DeepSeekOnboardingDialog.tsx').DeepSeekOnboardingInjected
  78. )()
  79. expect(deepSeekInjected.hooks.models).toBe(injected.controller.store)
  80. expect(deepSeekInjected.api).toBeDefined()
  81. const after = await bench()
  82. await after.ctx.plugin({ inject: [...inject], apply }).await()
  83. expect(after.slots.entries('settings.section')).toHaveLength(0)
  84. expect(after.slots.entries('settings.onboarding')).toHaveLength(0)
  85. declare(after.slots)
  86. await Promise.resolve()
  87. expect(after.slots.entries('settings.section')[0]!.component).toBe(ModelsSection)
  88. expect(after.slots.entries('settings.onboarding')).toHaveLength(2)
  89. // The self-inflicted ledger notifications hit the duplicate guard.
  90. expect(after.slots.entries('settings.section')).toHaveLength(1)
  91. })
  92. it('the label thunk follows the active locale without re-registration', async () => {
  93. const b = await bench()
  94. declare(b.slots)
  95. await b.ctx.plugin({ inject: [...inject], apply }).await()
  96. b.locale.setLocale('en')
  97. expect(resolveSlotLabel(b.slots.entries('settings.section')[0]!.options.label)).toBe('Models')
  98. const injected = b.slots.entries('settings.section')[0]!.inject as unknown as () => import('../src/client/ModelsSection.tsx').ModelsSectionInjected
  99. expect(injected().t('deleteTitle')).toBe('Delete {provider}?')
  100. b.locale.setLocale('zh')
  101. expect(resolveSlotLabel(b.slots.entries('settings.section')[0]!.options.label)).toBe('模型')
  102. expect(injected().t('deleteTitle')).toBe('删除 {provider}?')
  103. })
  104. it('locale change while the slot is undeclared stays a no-op', async () => {
  105. const b = await bench()
  106. await b.ctx.plugin({ inject: [...inject], apply }).await()
  107. b.locale.setLocale('en')
  108. expect(b.slots.entries('settings.section')).toHaveLength(0)
  109. b.locale.setLocale('zh')
  110. })
  111. it('re-registers after an HMR collapse re-declares the slot (stale disposer must not block)', async () => {
  112. const b = await bench()
  113. const redeclare = declare(b.slots)
  114. await b.ctx.plugin({ inject: [...inject], apply }).await()
  115. expect(b.slots.entries('settings.section')).toHaveLength(1)
  116. // Declarer unload: the cascade removes our entry while our local
  117. // disposer variable goes stale.
  118. redeclare()
  119. expect(b.slots.entries('settings.section')).toHaveLength(0)
  120. expect(b.slots.entries('settings.onboarding')).toHaveLength(0)
  121. declare(b.slots)
  122. await Promise.resolve()
  123. expect(b.slots.entries('settings.section')[0]!.component).toBe(ModelsSection)
  124. expect(b.slots.entries('settings.onboarding')).toHaveLength(2)
  125. // The locale path also recovers through the same ledger re-check.
  126. b.locale.setLocale('en')
  127. expect(resolveSlotLabel(b.slots.entries('settings.section')[0]!.options.label)).toBe('Models')
  128. b.locale.setLocale('zh')
  129. })
  130. it('registers the zh/en nav dictionaries and disposes everything with the fiber', async () => {
  131. const b = await bench()
  132. declare(b.slots)
  133. const fiber = b.ctx.plugin({ inject: [...inject], apply })
  134. await fiber.await()
  135. expect(b.locale.bind('settings.models')('nav')).toBe('模型')
  136. await fiber.dispose()
  137. expect(b.slots.entries('settings.section')).toHaveLength(0)
  138. expect(b.slots.entries('settings.onboarding')).toHaveLength(0)
  139. // The (ns, locale) seats are free again — the dictionary disposers ran.
  140. expect(() => b.locale.register('settings.models', 'zh', {})).not.toThrow()
  141. expect(() => b.locale.register('settings.models', 'en', {})).not.toThrow()
  142. })
  143. it('keeps remote-browser acknowledgement in process memory', async () => {
  144. const b = await bench(false)
  145. declare(b.slots)
  146. await b.ctx.plugin({ inject: [...inject], apply }).await()
  147. const entry = b.slots.entries('settings.onboarding')
  148. .find(candidate => candidate.options.id === 'welcome-notice')!
  149. const injected = (
  150. entry.inject as unknown as () => import('../src/client/WelcomeNotice.tsx').WelcomeNoticeInjected
  151. )()
  152. await injected.controller.load()
  153. expect(injected.controller.store.getSnapshot()).toEqual({
  154. status: 'ready', acknowledged: false, error: null,
  155. })
  156. })
  157. })
  158. describe('pushed invalidations', () => {
  159. it('ignores invalidations before the page ever loaded', async () => {
  160. const b = await bench()
  161. declare(b.slots)
  162. await b.ctx.plugin({ inject: [...inject], apply }).await()
  163. // The fake wire face has no methods: a fetch attempt would throw.
  164. b.remote.emit('settings/document-updated', ['llm-pi-ai', 1])
  165. b.remote.emit('credentials/reference-updated', ['OPENAI_API_KEY'])
  166. b.remote.emit('llm/adapters-updated', [])
  167. b.ctx.emit('connection/reset')
  168. })
  169. it('refreshes a loaded page and skips an idle one', () => {
  170. const loads: number[] = []
  171. const controller = {
  172. store: { getSnapshot: () => ({ status: 'ready' }) },
  173. load: () => { loads.push(1); return Promise.resolve() },
  174. }
  175. refreshIfLoaded(controller as unknown as import('../src/client/store.ts').ModelsSettingsStore)
  176. expect(loads).toHaveLength(1)
  177. const idle = {
  178. store: { getSnapshot: () => ({ status: 'idle' }) },
  179. load: () => { loads.push(2); return Promise.resolve() },
  180. }
  181. refreshIfLoaded(idle as unknown as import('../src/client/store.ts').ModelsSettingsStore)
  182. expect(loads).toHaveLength(1)
  183. })
  184. it('routes pushed credential invalidation into the shared onboarding join', async () => {
  185. const b = await bench()
  186. declare(b.slots)
  187. await b.ctx.plugin({ inject: [...inject], apply }).await()
  188. const entry = b.slots.entries('settings.onboarding')
  189. .find(candidate => candidate.options.id === 'deepseek-official')!
  190. const injected = (
  191. entry.inject as unknown as
  192. () => import('../src/client/DeepSeekOnboardingDialog.tsx').DeepSeekOnboardingInjected
  193. )()
  194. injected.controller.store.update((state) => { state.status = 'ready' })
  195. const load = vi.spyOn(injected.controller, 'load').mockResolvedValue()
  196. b.remote.emit('credentials/reference-updated', ['DEEPSEEK_API_KEY'])
  197. expect(load).toHaveBeenCalledTimes(1)
  198. })
  199. it('welcome state follows the shared mirror across document commits', async () => {
  200. // The welcome notice derives from its settings scope: a document commit
  201. // reaches it through the mirror's one refresh, with no routing here.
  202. const acknowledgement = { current: undefined as string | undefined }
  203. const settings = {
  204. describe: vi.fn(() => Promise.resolve({
  205. rpcId: 'apply-welcome' as never,
  206. result: {
  207. ok: true as const,
  208. value: {
  209. writable: true,
  210. hasDocument: false,
  211. namespaces: [{
  212. ns: WELCOME_NOTICE_SETTINGS_NAMESPACE,
  213. schema: {},
  214. value: acknowledgement.current === undefined ? {} : { [WELCOME_NOTICE_ACK_FIELD]: acknowledgement.current },
  215. applies: 'live' as const,
  216. secrets: [],
  217. revision: 0,
  218. }],
  219. },
  220. },
  221. })),
  222. }
  223. const b = await bench(true, settings)
  224. declare(b.slots)
  225. await b.ctx.plugin({ inject: [...inject], apply }).await()
  226. const entry = b.slots.entries('settings.onboarding')
  227. .find(candidate => candidate.options.id === 'welcome-notice')!
  228. const injected = (
  229. entry.inject as unknown as
  230. () => import('../src/client/WelcomeNotice.tsx').WelcomeNoticeInjected
  231. )()
  232. await injected.controller.load()
  233. await vi.waitFor(() => {
  234. expect(injected.hooks.welcome.getSnapshot()).toMatchObject({ status: 'ready', acknowledged: false })
  235. })
  236. acknowledgement.current = WELCOME_NOTICE_VERSION
  237. b.remote.emit('settings/document-updated', ['ui-onboarding', 1])
  238. await vi.waitFor(() => {
  239. expect(injected.hooks.welcome.getSnapshot()).toMatchObject({ status: 'ready', acknowledged: true })
  240. })
  241. })
  242. it('joins the refreshed mirror view on a settings invalidation', async () => {
  243. let revision = 1
  244. const describe = vi.fn(() => Promise.resolve({
  245. rpcId: `apply-models-${revision}` as never,
  246. result: {
  247. ok: true as const,
  248. value: {
  249. writable: true,
  250. hasDocument: false,
  251. namespaces: [{
  252. ns: 'llm-test',
  253. schema: {},
  254. value: {},
  255. applies: 'live' as const,
  256. secrets: [],
  257. revision,
  258. }],
  259. },
  260. },
  261. }))
  262. const providers = vi.fn(() => Promise.resolve({
  263. rpcId: 'apply-models-providers' as never,
  264. result: { ok: true as const, value: { providers: [] } },
  265. }))
  266. const b = await bench(true, { describe }, { llm: { providers } })
  267. declare(b.slots)
  268. await b.ctx.plugin({ inject: [...inject], apply }).await()
  269. const entry = b.slots.entries('settings.section')
  270. .find(candidate => candidate.options.id === 'models')!
  271. const injected = (
  272. entry.inject as unknown as
  273. () => import('../src/client/ModelsSection.tsx').ModelsSectionInjected
  274. )()
  275. await injected.controller.load()
  276. expect(injected.hooks.snapshot.getSnapshot().namespaces.get('llm-test')?.revision).toBe(1)
  277. revision = 2
  278. b.remote.emit('settings/document-updated', ['llm-test', revision])
  279. await vi.waitFor(() => {
  280. expect(injected.hooks.snapshot.getSnapshot().namespaces.get('llm-test')?.revision).toBe(2)
  281. })
  282. expect(describe).toHaveBeenCalledTimes(2)
  283. })
  284. })