apply.client.spec.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. /** ui-theme apply wiring: service provision, settings dictionaries riding the
  2. * locale service, declaration-aware Appearance row registration, snapshot
  3. * projection into the row store, and HMR collapse recovery. */
  4. import { Context } from '@deepseek-ai/cordis'
  5. import { describe, expect, it, vi } from 'vitest'
  6. import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
  7. import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
  8. import { TestRemote } from '@deepseek-ai/dsh-client-test-runtime'
  9. import { apply as settingsApply, inject as settingsInject } from '@deepseek-ai/dsh-client-ui-settings/client'
  10. import { apply, inject, SETTINGS_NS } from '@deepseek-ai/dsh-client-ui-theme/client'
  11. import type { AppearanceRowInjected, ThemeRuntime } from '@deepseek-ai/dsh-client-ui-theme/client'
  12. import { THEME_SETTINGS_NAMESPACE, ThemeSettingsSchema } from '../src/theme-settings.ts'
  13. import { AppearanceRow } from '../src/client/AppearanceRow.tsx'
  14. import type { createAppearanceRowStore } from '../src/client/settings-store.ts'
  15. // These specs assert the shipped Chinese copy. The lane has no jsdom `window`,
  16. // so browser-language detection never runs and a fresh LocaleRuntime opens on
  17. // FALLBACK_LOCALE (en); bench stages zh explicitly on the locale instead.
  18. const SLOT = 'settings.general.item'
  19. function deferred<T>() {
  20. let resolve!: (value: T) => void
  21. const promise = new Promise<T>((done) => { resolve = done })
  22. return { promise, resolve }
  23. }
  24. async function bench(isLoopback = true) {
  25. const ctx = new Context()
  26. await ctx.plugin(SlotRegistry).await()
  27. const locale = new LocaleRuntime(ctx)
  28. locale.setLocale('zh')
  29. ctx.provide('locale', locale)
  30. let preference = 'system'
  31. const namespace = () => ({
  32. ns: THEME_SETTINGS_NAMESPACE,
  33. schema: ThemeSettingsSchema.toJSON(),
  34. value: { preference },
  35. applies: 'live' as const,
  36. secrets: [],
  37. revision: 0,
  38. })
  39. const describe = vi.fn(() => Promise.resolve({
  40. rpcId: 'theme-describe' as never,
  41. result: {
  42. ok: true as const,
  43. value: { writable: true, hasDocument: true, namespaces: [namespace()] },
  44. },
  45. }))
  46. const mutate = vi.fn((request: { ops: { value: string }[] }) => {
  47. preference = request.ops[0]!.value
  48. return Promise.resolve({
  49. rpcId: 'theme-mutate' as never,
  50. result: { ok: true as const, value: namespace() },
  51. })
  52. })
  53. ctx.provide('connection', { api: { settings: { describe, mutate } }, isLoopback } as never)
  54. const events = new TestRemote(ctx)
  55. await ctx.plugin({ inject: [...settingsInject], apply: settingsApply }).await()
  56. return {
  57. ctx, slots: ctx.get('slots') as SlotRegistry, locale, describe, mutate, events,
  58. setHostPreference: (next: string) => { preference = next },
  59. }
  60. }
  61. /** Stand in for the settings shell: declare the General item slot from root. */
  62. function declareItems(slots: SlotRegistry): () => void {
  63. return slots.register(
  64. { name: 'root', children: { [SLOT]: { kind: 'list', scope: 'root' } } } as never,
  65. () => null,
  66. )
  67. }
  68. /** Mirror the framework's inject choreography: bake a real instance from the
  69. * declared handle and hand its actions to the entry's inject factory. */
  70. function faceOf(slots: SlotRegistry) {
  71. const entry = slots.entries(SLOT).find(e => e.component === AppearanceRow)!
  72. const handle = entry.store as ReturnType<typeof createAppearanceRowStore>
  73. const instance = handle.create()
  74. const face = (entry.inject as unknown as (a: typeof instance.actions) => AppearanceRowInjected)(instance.actions)
  75. return { entry, instance, face }
  76. }
  77. describe('ui-theme apply', () => {
  78. it('declares the slot and locale services', () => {
  79. expect(inject).toEqual(['slots', 'locale', 'connection', 'remote', 'settingsScope'])
  80. })
  81. it('provides the service, registers localized copy, and registers the row (declaration before or after apply)', async () => {
  82. const before = await bench()
  83. declareItems(before.slots)
  84. await before.ctx.plugin({ inject: [...inject], apply }).await()
  85. expect(before.locale.bind(SETTINGS_NS)('appearance.title')).toBe('外观')
  86. before.locale.setLocale('en')
  87. expect(before.locale.bind(SETTINGS_NS)('appearance.title')).toBe('Appearance')
  88. const entry = before.slots.entries(SLOT).find(e => e.component === AppearanceRow)!
  89. expect(entry.options).toMatchObject({ id: 'appearance', order: 10 })
  90. const after = await bench()
  91. const fiber = after.ctx.plugin({ inject: [...inject], apply })
  92. await fiber.await()
  93. expect(after.slots.entries(SLOT)).toHaveLength(0)
  94. declareItems(after.slots)
  95. await Promise.resolve()
  96. expect(after.slots.entries(SLOT).some(e => e.component === AppearanceRow)).toBe(true)
  97. })
  98. it('projects service snapshots into the row store and routes face writes back', async () => {
  99. const b = await bench()
  100. declareItems(b.slots)
  101. await b.ctx.plugin({ inject: [...inject], apply }).await()
  102. const theme = b.ctx.get('theme') as ThemeRuntime
  103. // An event ahead of any inject hits the unbound-actions arm.
  104. theme.setTheme('dark')
  105. const { instance, face } = faceOf(b.slots)
  106. // The inject-time re-sync sealed the init window: the mirror is current.
  107. expect(instance.getSnapshot().preference).toBe('dark')
  108. // Copy rides the standard locale seat: the entry declares the namespace.
  109. expect(b.slots.entries(SLOT).find(e => e.component === AppearanceRow)!.locale).toBe(SETTINGS_NS)
  110. face.setTheme('system')
  111. expect(theme.getTheme().preference).toBe('system')
  112. expect(instance.getSnapshot().preference).toBe('system')
  113. await vi.waitFor(() => { expect(b.mutate).toHaveBeenCalledTimes(2) })
  114. })
  115. it('loads Host settings at boot, refreshes its namespace, and keeps remote browsers process-local', async () => {
  116. const b = await bench()
  117. // The shared mirror read once at bench time; a Host-side change reaches it
  118. // through the document invalidation, exactly as production announces one.
  119. b.setHostPreference('dark')
  120. b.events.emit('settings/document-updated', [THEME_SETTINGS_NAMESPACE, 0])
  121. declareItems(b.slots)
  122. await b.ctx.plugin({ inject: [...inject], apply }).await()
  123. const theme = b.ctx.get('theme') as ThemeRuntime
  124. await vi.waitFor(() => { expect(theme.getTheme().preference).toBe('dark') })
  125. // The mirror refreshes on every document commit (ns-agnostic); the scope's
  126. // derived value only moves when its own namespace changed.
  127. b.events.emit('settings/document-updated', ['unrelated', 0])
  128. await vi.waitFor(() => { expect(b.describe).toHaveBeenCalledTimes(3) })
  129. expect(theme.getTheme().preference).toBe('dark')
  130. b.setHostPreference('light')
  131. b.events.emit('settings/document-updated', [THEME_SETTINGS_NAMESPACE, 0])
  132. await vi.waitFor(() => { expect(theme.getTheme().preference).toBe('light') })
  133. b.setHostPreference('dark')
  134. b.ctx.emit('connection/reset')
  135. await vi.waitFor(() => { expect(theme.getTheme().preference).toBe('dark') })
  136. const remote = await bench(false)
  137. declareItems(remote.slots)
  138. await remote.ctx.plugin({ inject: [...inject], apply }).await()
  139. const remoteTheme = remote.ctx.get('theme') as ThemeRuntime
  140. remoteTheme.setTheme('dark')
  141. await Promise.resolve()
  142. expect(remote.describe).not.toHaveBeenCalled()
  143. expect(remote.mutate).not.toHaveBeenCalled()
  144. })
  145. it('activates before a slow settings refresh and converges when it settles', async () => {
  146. const b = await bench()
  147. b.setHostPreference('dark')
  148. const describe = b.describe.getMockImplementation()!
  149. const pending = deferred<Awaited<ReturnType<typeof describe>>>()
  150. b.describe.mockImplementationOnce(() => pending.promise)
  151. // The refresh hangs on the wire; the mirror keeps serving the last good
  152. // answer, so activation never blocks on the settings transport.
  153. b.events.emit('settings/document-updated', [THEME_SETTINGS_NAMESPACE, 0])
  154. const fiber = b.ctx.plugin({ inject: [...inject], apply })
  155. await fiber.await()
  156. const theme = b.ctx.get('theme') as ThemeRuntime
  157. expect(theme.getTheme().preference).toBe('system')
  158. pending.resolve(await describe())
  159. await vi.waitFor(() => { expect(theme.getTheme().preference).toBe('dark') })
  160. await fiber.dispose()
  161. })
  162. it('ignores an invalid preference crossing the settings wire', async () => {
  163. const b = await bench()
  164. b.setHostPreference('sepia')
  165. b.events.emit('settings/document-updated', [THEME_SETTINGS_NAMESPACE, 0])
  166. await b.ctx.plugin({ inject: [...inject], apply }).await()
  167. const theme = b.ctx.get('theme') as ThemeRuntime
  168. await vi.waitFor(() => { expect(b.describe).toHaveBeenCalledTimes(2) })
  169. expect(theme.getTheme().preference).toBe('system')
  170. })
  171. it('recovers after an HMR collapse of the declaring entry (stale disposer must not block)', async () => {
  172. const b = await bench()
  173. const host = declareItems(b.slots)
  174. await b.ctx.plugin({ inject: [...inject], apply }).await()
  175. expect(b.slots.entries(SLOT)).toHaveLength(1)
  176. // Collapse: the declarer dies, the cascade removes our entry while the
  177. // apply closure still holds its (now stale) disposer.
  178. host()
  179. expect(b.slots.entries(SLOT)).toHaveLength(0)
  180. declareItems(b.slots)
  181. await Promise.resolve()
  182. expect(b.slots.entries(SLOT).some(e => e.component === AppearanceRow)).toBe(true)
  183. })
  184. it('teardown removes the row and the dictionaries; teardown without a declaration is quiet', async () => {
  185. const b = await bench()
  186. declareItems(b.slots)
  187. const fiber = b.ctx.plugin({ inject: [...inject], apply })
  188. await fiber.await()
  189. expect(b.slots.entries(SLOT)).toHaveLength(1)
  190. await fiber.dispose()
  191. expect(b.slots.entries(SLOT)).toHaveLength(0)
  192. // Dictionary disposal: translation falls back to the bare key.
  193. expect(b.locale.bind(SETTINGS_NS)('appearance.title')).toBe('appearance.title')
  194. // Never-declared bench: the effect disposer's dispose arm stays undefined.
  195. const quiet = await bench()
  196. const f2 = quiet.ctx.plugin({ inject: [...inject], apply })
  197. await f2.await()
  198. await f2.dispose()
  199. expect(quiet.slots.entries(SLOT)).toHaveLength(0)
  200. })
  201. })