slots-service.spec.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. /**
  2. * SlotsService terminal-design account (design.md §11-3 main landing):
  3. * built-in 'root', the three load-time throws (duplicate declaration /
  4. * undeclared contribution / cross-scope store handle), the renderer install
  5. * seam (double install / not installed / non-root key), store instance
  6. * resolution and lifecycle on the ledger axis, and the entry-unload cascade.
  7. */
  8. import { Context } from 'cordis'
  9. import { describe, expect, it, vi } from 'vitest'
  10. import type { FC } from 'react'
  11. import type { SlotRendererHost } from '@deepseek-ai/dsh-client-ui-slots'
  12. import { SlotsService } from '../src/client/slots.ts'
  13. // Test-only slot keys (merged so the typed entries/spec faces accept them).
  14. declare module '@deepseek-ai/dsh-client-ui-slots' {
  15. interface SlotMap {
  16. 't.host': { kind: 'single'; scope: 'root' }
  17. 't.panel': { kind: 'single'; scope: 'session' }
  18. 't.rows': { kind: 'list'; scope: 'root' }
  19. }
  20. }
  21. const C: FC<object> = () => null
  22. /**
  23. * Register/install/renderSlot through a type-erased view: the typed register
  24. * face rides wave-1 ui-slots types (red until that wave lands); the runtime
  25. * semantics under test are final.
  26. */
  27. interface ErasedService {
  28. register(options: object, component: unknown): () => void
  29. install(renderer: object): void
  30. renderSlot(key: string, owner: object): unknown
  31. }
  32. interface Bench {
  33. ctx: Context
  34. svc: SlotsService
  35. erased: ErasedService
  36. }
  37. async function boot(): Promise<Bench> {
  38. const ctx = new Context()
  39. const fiber = ctx.plugin(SlotsService)
  40. await fiber
  41. // Service accessor (ctx.get reads the reflect store, which Service-class
  42. // plugins do not write; the accessor is the product path).
  43. const svc = ctx.slots
  44. return { ctx, svc, erased: svc as unknown as ErasedService }
  45. }
  46. /** Engine-shaped instance stub (bare-source form: subscribe/getSnapshot + baked actions + clearPersisted). */
  47. interface FakeInstance {
  48. getSnapshot: () => undefined
  49. subscribe: () => () => void
  50. actions: Record<string, never>
  51. clearPersisted: ReturnType<typeof vi.fn>
  52. }
  53. /** Fake store handle factory (create-count and clearPersisted observable). */
  54. function fakeHandle() {
  55. const created: FakeInstance[] = []
  56. const handle = {
  57. create: vi.fn((_scopeKey?: string): FakeInstance => {
  58. const instance: FakeInstance = {
  59. getSnapshot: () => undefined, subscribe: () => () => undefined,
  60. actions: {}, clearPersisted: vi.fn(),
  61. }
  62. created.push(instance)
  63. return instance
  64. }),
  65. }
  66. return { handle, created }
  67. }
  68. /**
  69. * Install a capturing renderer, occupy 'root' (declaring `children` in the
  70. * same call — 'root' is single, so the one occupant is also the declarer),
  71. * and pull the host face out through renderSlot('root').
  72. */
  73. function captureHost(bench: Bench, children?: object): SlotRendererHost {
  74. let host: SlotRendererHost | undefined
  75. bench.erased.install({
  76. renderRoot: (h: SlotRendererHost) => { host = h; return 'rendered' },
  77. })
  78. bench.erased.register({ name: 'root', ...(children !== undefined ? { children } : {}) }, C)
  79. bench.ctx.reflect.provide('sessions', fakeSessions())
  80. bench.ctx.reflect.provide('workspaces', fakeWorkspaces())
  81. bench.erased.renderSlot('root', {})
  82. if (host === undefined) throw new Error('renderer never received the host')
  83. return host
  84. }
  85. /** Minimal independent Workspace list source for the renderer host seam. */
  86. function fakeWorkspaces() {
  87. const state = { items: [], phase: 'ready' as const }
  88. return { list: { getSnapshot: () => state, subscribe: () => () => undefined } }
  89. }
  90. /** Minimal sessions face for the host seam (list observable + current provide projection). */
  91. function fakeSessions() {
  92. const state = { ids: [], byId: {}, current: undefined as string | undefined }
  93. const absentInfo = { sessionId: undefined, hooks: { session: undefined }, props: {} }
  94. return {
  95. list: { getSnapshot: () => state, subscribe: () => () => undefined },
  96. currentProvideInfo: { getSnapshot: () => absentInfo, subscribe: () => () => undefined },
  97. }
  98. }
  99. describe("built-in 'root'", () => {
  100. it('is declared at construction: spec readable, occupancy open, no plugin needed', async () => {
  101. const bench = await boot()
  102. expect(bench.svc.spec('root')).toEqual({ kind: 'single', scope: 'root' })
  103. expect(() => bench.erased.register({ name: 'root' }, C)).not.toThrow()
  104. expect(bench.svc.entries('root')).toHaveLength(1)
  105. })
  106. it('rejects a second declaration of root, attributing the built-in row', async () => {
  107. const bench = await boot()
  108. expect(() => bench.erased.register({
  109. name: 'root', children: { 'root': { kind: 'single', scope: 'root' } },
  110. }, C)).toThrow(/already declared.*built-in/)
  111. })
  112. })
  113. describe('load-time validation', () => {
  114. it('throws on contributing into an undeclared slot', async () => {
  115. const bench = await boot()
  116. expect(() => bench.erased.register({ name: 't.host' }, C)).toThrow(/slot "t.host" is not declared/)
  117. })
  118. it('throws on a duplicate declaration, naming the slot and the prior declarant', async () => {
  119. const bench = await boot()
  120. bench.erased.register({ name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } } }, C)
  121. bench.erased.register({
  122. name: 't.host', children: { 't.rows': { kind: 'list', scope: 'root' } },
  123. }, C)
  124. expect(() => bench.erased.register({
  125. name: 't.rows', id: 'r1', children: { 't.rows': { kind: 'list', scope: 'root' } },
  126. }, C)).toThrow(/slot "t.rows" is already declared.*"t.host"/)
  127. })
  128. it('throws when one store handle is bound to two scopes', async () => {
  129. const bench = await boot()
  130. bench.erased.register({
  131. name: 'root',
  132. children: {
  133. 't.host': { kind: 'single', scope: 'root' },
  134. 't.panel': { kind: 'single', scope: 'session' },
  135. },
  136. }, C)
  137. const { handle } = fakeHandle()
  138. bench.erased.register({ name: 't.host', store: handle }, C)
  139. expect(() => bench.erased.register({ name: 't.panel', store: handle }, C))
  140. .toThrow(/one handle, one scope/)
  141. })
  142. it('commits nothing when the core rejects the entry (children stay undeclared)', async () => {
  143. const bench = await boot()
  144. bench.erased.register({ name: 'root' }, C) // 'root' single slot now occupied
  145. expect(() => bench.erased.register({
  146. name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } },
  147. }, C)).toThrow(/already has a registration/)
  148. // The failing call's declaration must not have landed.
  149. expect(() => bench.erased.register({ name: 't.host' }, C)).toThrow(/is not declared/)
  150. })
  151. })
  152. describe('renderer install seam', () => {
  153. it('throws on renderSlot before install (boot-order guidance)', async () => {
  154. const bench = await boot()
  155. expect(() => bench.erased.renderSlot('root', {})).toThrow(/renderer not installed/)
  156. })
  157. it('throws on double install', async () => {
  158. const bench = await boot()
  159. bench.erased.install({ renderRoot: () => null })
  160. expect(() => { bench.erased.install({ renderRoot: () => null }) }).toThrow(/already installed/)
  161. })
  162. it('throws on any non-root key (single ctx-level entry)', async () => {
  163. const bench = await boot()
  164. bench.erased.install({ renderRoot: () => null })
  165. expect(() => bench.erased.renderSlot('t.host', {})).toThrow(/only renders 'root'/)
  166. })
  167. it("throws on renderSlot('root') before any root registration", async () => {
  168. const bench = await boot()
  169. bench.erased.install({ renderRoot: () => null })
  170. expect(() => bench.erased.renderSlot('root', {})).toThrow(/no registration/)
  171. })
  172. it('renders through the installed renderer and returns its product', async () => {
  173. const bench = await boot()
  174. const renderRoot = vi.fn(() => 'tree')
  175. bench.erased.install({ renderRoot })
  176. bench.erased.register({ name: 'root' }, C)
  177. bench.ctx.reflect.provide('sessions', fakeSessions())
  178. bench.ctx.reflect.provide('workspaces', fakeWorkspaces())
  179. expect(bench.erased.renderSlot('root', {})).toBe('tree')
  180. expect(renderRoot).toHaveBeenCalledTimes(1)
  181. })
  182. it('fails before rendering when the Workspace object layer is absent', async () => {
  183. const bench = await boot()
  184. bench.erased.install({ renderRoot: () => null })
  185. bench.erased.register({ name: 'root' }, C)
  186. bench.ctx.reflect.provide('sessions', fakeSessions())
  187. expect(() => bench.erased.renderSlot('root', {})).toThrow(/workspaces service mounted/)
  188. })
  189. })
  190. describe('host face', () => {
  191. it('serves entriesOf/specOf/isLive off the ledger and flips isLive on disposal', async () => {
  192. const bench = await boot()
  193. const host = captureHost(bench, { 't.host': { kind: 'single', scope: 'root' } })
  194. const dispose = bench.erased.register({ name: 't.host' }, C)
  195. const rootEntry = host.entriesOf('root')[0]
  196. expect(rootEntry).toBeDefined()
  197. expect(rootEntry?.component).toBe(C)
  198. expect(host.specOf('root')).toEqual({ kind: 'single', scope: 'root' })
  199. expect(host.specOf('t.host')).toEqual({ kind: 'single', scope: 'root' })
  200. const childEntry = host.entriesOf('t.host')[0]
  201. expect(host.isLive(childEntry as never)).toBe(true)
  202. dispose()
  203. expect(host.isLive(childEntry as never)).toBe(false)
  204. expect(host.entriesOf('t.host')).toHaveLength(0)
  205. })
  206. it('exposes the session list and the atomic current provide projection', async () => {
  207. const bench = await boot()
  208. const host = captureHost(bench)
  209. expect(host.sessions.list.getSnapshot()).toMatchObject({ ids: [] })
  210. expect(host.sessions.provideInfo.getSnapshot()).toMatchObject({ sessionId: undefined })
  211. })
  212. it('exposes the independent Workspace list source', async () => {
  213. const bench = await boot()
  214. const host = captureHost(bench)
  215. expect(host.workspaces.list.getSnapshot()).toEqual({ items: [], phase: 'ready' })
  216. })
  217. })
  218. describe('store instance axis', () => {
  219. /** Boot with 'root' occupied and the three test children declared. */
  220. async function storeBench() {
  221. const bench = await boot()
  222. const host = captureHost(bench, {
  223. 't.host': { kind: 'single', scope: 'root' },
  224. 't.rows': { kind: 'list', scope: 'root' },
  225. 't.panel': { kind: 'single', scope: 'session' },
  226. })
  227. return { bench, host }
  228. }
  229. it('resolves one instance per (handle x root scope) shared across entries', async () => {
  230. const { bench, host } = await storeBench()
  231. const { handle } = fakeHandle()
  232. bench.erased.register({ name: 't.host', store: handle }, C)
  233. bench.erased.register({ name: 't.rows', id: 'a', store: handle }, C)
  234. const [hostEntry] = host.entriesOf('t.host')
  235. const [rowEntry] = host.entriesOf('t.rows')
  236. const a = host.storeOf(hostEntry as never, undefined)
  237. const b = host.storeOf(rowEntry as never, undefined)
  238. expect(a).toBeDefined()
  239. expect(a).toBe(b) // shared handle, same scope key = same instance
  240. expect(handle.create).toHaveBeenCalledTimes(1)
  241. expect(handle.create).toHaveBeenCalledWith() // root scope: keyless create
  242. })
  243. it('resolves per-session instances keyed by session id, created with the scope key', async () => {
  244. const { bench, host } = await storeBench()
  245. const { handle } = fakeHandle()
  246. bench.erased.register({ name: 't.panel', store: handle }, C)
  247. const [entry] = host.entriesOf('t.panel')
  248. const s1 = host.storeOf(entry as never, 's1')
  249. const s2 = host.storeOf(entry as never, 's2')
  250. expect(s1).not.toBe(s2)
  251. expect(host.storeOf(entry as never, 's1')).toBe(s1) // cached per key
  252. expect(handle.create).toHaveBeenCalledWith('s1')
  253. expect(handle.create).toHaveBeenCalledWith('s2')
  254. expect(() => host.storeOf(entry as never, undefined)).toThrow(/requires a session id/)
  255. })
  256. it('mints a fresh handle per register for the factory (exclusive) form', async () => {
  257. const { bench, host } = await storeBench()
  258. const factory = vi.fn(() => fakeHandle().handle)
  259. bench.erased.register({ name: 't.host', store: factory }, C)
  260. bench.erased.register({ name: 't.rows', id: 'a', store: factory }, C)
  261. expect(factory).toHaveBeenCalledTimes(2)
  262. const a = host.storeOf(host.entriesOf('t.host')[0] as never, undefined)
  263. const b = host.storeOf(host.entriesOf('t.rows')[0] as never, undefined)
  264. expect(a).not.toBe(b) // two mints, two instances
  265. })
  266. it('drops instances with the last holding entry and refuses stale resolution', async () => {
  267. const { bench, host } = await storeBench()
  268. const { handle } = fakeHandle()
  269. const d1 = bench.erased.register({ name: 't.host', store: handle }, C)
  270. bench.erased.register({ name: 't.rows', id: 'a', store: handle }, C)
  271. const rowEntry = host.entriesOf('t.rows')[0]
  272. const hostEntry = host.entriesOf('t.host')[0]
  273. const shared = host.storeOf(rowEntry as never, undefined)
  274. d1() // one holder left: record (and instance) survive
  275. expect(host.storeOf(rowEntry as never, undefined)).toBe(shared)
  276. expect(() => host.storeOf(hostEntry as never, undefined)).not.toThrow() // handle still live via the row entry
  277. // Note: dropping the row entry would sever the last reference; stale
  278. // resolution is covered through the cascade spec below.
  279. })
  280. it('pruneStoreScope clears persisted state per dead session, including never-materialized ones', async () => {
  281. const { bench, host } = await storeBench()
  282. const { handle, created } = fakeHandle()
  283. bench.erased.register({ name: 't.panel', store: handle }, C)
  284. const [entry] = host.entriesOf('t.panel')
  285. const s1 = host.storeOf(entry as never, 's1')
  286. expect(s1).toBe(created[0]) // the resolved instance is the fake the handle minted
  287. bench.svc.pruneStoreScope('s1')
  288. expect(created[0]?.clearPersisted).toHaveBeenCalledTimes(1)
  289. expect(host.storeOf(entry as never, 's1')).not.toBe(s1) // instance dropped, next resolve mints anew
  290. // Never-rendered dead session: a transient instance is created just to clear storage.
  291. const before = created.length
  292. bench.svc.pruneStoreScope('s-never')
  293. expect(created.length).toBe(before + 1)
  294. expect(created[created.length - 1]?.clearPersisted).toHaveBeenCalledTimes(1)
  295. })
  296. })
  297. describe('entry-unload cascade', () => {
  298. it('kills declared children, their contributions, and the ledger rows with the entry', async () => {
  299. const bench = await boot()
  300. let host: SlotRendererHost | undefined
  301. bench.erased.install({
  302. renderRoot: (h: SlotRendererHost) => { host = h; return 'rendered' },
  303. })
  304. bench.ctx.reflect.provide('sessions', fakeSessions())
  305. bench.ctx.reflect.provide('workspaces', fakeWorkspaces())
  306. // The declarer here is NOT the root occupant: root stays occupied by a
  307. // separate entry so disposing the declarer only kills its children.
  308. const disposeRoot = bench.erased.register({ name: 'root' }, C)
  309. bench.erased.renderSlot('root', {})
  310. if (host === undefined) throw new Error('renderer never received the host')
  311. disposeRoot()
  312. const disposeDeclarer = bench.erased.register({
  313. name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } },
  314. }, C)
  315. bench.erased.register({ name: 't.host' }, C)
  316. const [childEntry] = host.entriesOf('t.host')
  317. expect(childEntry).toBeDefined()
  318. disposeDeclarer()
  319. expect(bench.svc.spec('t.host')).toBeUndefined() // ledger row gone
  320. expect(host.specOf('t.host')).toBeUndefined() // outlets now render empty
  321. expect(bench.svc.entries('t.host')).toHaveLength(0) // contribution cleared
  322. expect(host.isLive(childEntry as never)).toBe(false) // stale bindings will throw upstream
  323. // The freed key is re-declarable by a new entry (no residue).
  324. expect(() => bench.erased.register({
  325. name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } },
  326. }, C)).not.toThrow()
  327. })
  328. it('cascades through cordis fiber disposal (plugin unload = full cleanup)', async () => {
  329. const bench = await boot()
  330. bench.erased.register({
  331. name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } },
  332. }, C)
  333. const fiber = bench.ctx.plugin({
  334. name: 'occupant',
  335. inject: ['slots'],
  336. apply: (pluginCtx: Context) => {
  337. ;(pluginCtx.slots as unknown as ErasedService).register({ name: 't.host' }, C)
  338. },
  339. })
  340. await fiber.await()
  341. expect(bench.svc.entries('t.host')).toHaveLength(1)
  342. await fiber.dispose()
  343. expect(bench.svc.entries('t.host')).toHaveLength(0)
  344. expect(bench.svc.spec('t.host')).toBeDefined() // declarer still live; slot stays declared
  345. })
  346. it('disposer is idempotent (stale second call is a no-op)', async () => {
  347. const bench = await boot()
  348. const dispose = bench.erased.register({
  349. name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } },
  350. }, C)
  351. dispose()
  352. expect(() => { dispose() }).not.toThrow()
  353. expect(() => bench.erased.register({
  354. name: 'root', children: { 't.host': { kind: 'single', scope: 'root' } },
  355. }, C)).not.toThrow()
  356. })
  357. })
  358. describe('event bridge', () => {
  359. it("re-emits entry writes and child declarations as 'slots/changed'", async () => {
  360. const bench = await boot()
  361. const seen: string[] = []
  362. bench.ctx.on('slots/changed', (key) => { seen.push(key) })
  363. bench.erased.register({
  364. name: 'root', children: { 't.rows': { kind: 'list', scope: 'root' } },
  365. }, C)
  366. bench.erased.register({ name: 't.rows', id: 'a' }, C)
  367. expect(seen).toEqual(['root', 't.rows', 't.rows'])
  368. })
  369. })