runtime.spec.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. // @vitest-environment jsdom
  2. /**
  3. * SlotTestRuntime behavior: root declaration + rendering, session
  4. * add/update/switch/remove through the real renderer, shared store identity
  5. * and scope pruning, feature mount/dispose cascade, and runtime disposal
  6. * idempotence. All through the production SlotsService + createSlotRenderer
  7. * stack — this suite is the fixture the migrated feature specs rely on.
  8. */
  9. import { afterEach, describe, expect, it, vi } from 'vitest'
  10. import { cleanup } from '@testing-library/react'
  11. import { defineStore } from '@deepseek-ai/dsh-client-runtime/client'
  12. import type { SessionId, WorkspaceId } from '@deepseek-ai/dsh-client-runtime/client'
  13. import type { PropsRenderSlots, SessionStandardProps } from '@deepseek-ai/dsh-client-ui-slots'
  14. import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime'
  15. declare module '@deepseek-ai/dsh-client-ui-slots' {
  16. interface SlotMap {
  17. 'trt.panel': { kind: 'single'; scope: 'root'; owner: { label?: string } }
  18. 'trt.chat': { kind: 'single'; scope: 'session' }
  19. 'trt.rows': { kind: 'list'; scope: 'root' }
  20. }
  21. }
  22. afterEach(cleanup)
  23. type FrameProps = PropsRenderSlots<'trt.panel' | 'trt.chat' | 'trt.rows'>
  24. /** Root frame declaring all three suite slots (render sites for each kind). */
  25. function Frame({ renderSlot, SessionProvider }: FrameProps) {
  26. return (
  27. <>
  28. {renderSlot('trt.panel', { label: 'from-owner' }, { fallback: <i>no panel</i> })}
  29. <SessionProvider empty={() => <i>no session</i>}>
  30. {() => renderSlot('trt.chat', {})}
  31. </SessionProvider>
  32. {renderSlot('trt.rows', {})}
  33. </>
  34. )
  35. }
  36. const CHILDREN = {
  37. 'trt.panel': { kind: 'single', scope: 'root' },
  38. 'trt.chat': { kind: 'single', scope: 'session' },
  39. 'trt.rows': { kind: 'list', scope: 'root' },
  40. } as const
  41. async function runtimeWithFrame() {
  42. const runtime = await SlotTestRuntime.create()
  43. await runtime.root.declare(CHILDREN, Frame)
  44. return runtime
  45. }
  46. describe('root declaration and rendering', () => {
  47. it('renders declared slots through the real renderer: fallback, then a live registration, then unload', async () => {
  48. const runtime = await runtimeWithFrame()
  49. const view = runtime.renderRoot()
  50. expect(view.container.textContent).toContain('no panel')
  51. let dispose = (): void => {}
  52. await runtime.flush() // no-op guard: flush outside mutations is safe
  53. await (async () => {
  54. dispose = runtime.slots.register(
  55. { name: 'trt.panel' },
  56. ({ label }: { label?: string }) => <b>panel:{label}</b>)
  57. await runtime.flush()
  58. })()
  59. expect(view.container.textContent).toContain('panel:from-owner')
  60. dispose()
  61. await runtime.flush()
  62. expect(view.container.textContent).toContain('no panel')
  63. await runtime.dispose()
  64. })
  65. it('fails loud when rendering with no root declaration (production boot-order check)', async () => {
  66. const runtime = await SlotTestRuntime.create()
  67. expect(() => runtime.renderRoot()).toThrow(/'root' has no registration/)
  68. await runtime.dispose()
  69. })
  70. })
  71. describe('sessions', () => {
  72. it('drives SessionProvider: empty state, current session, switch, live snapshot updates', async () => {
  73. const runtime = await runtimeWithFrame()
  74. runtime.slots.register({ name: 'trt.chat' }, (props: SessionStandardProps) => {
  75. const running = props.useSession(s => s.running)
  76. return <span>chat:{props.sessionId}:{String(running)}</span>
  77. })
  78. const view = runtime.renderRoot()
  79. expect(view.container.textContent).toContain('no session')
  80. await runtime.sessions.add({ id: 's1' })
  81. expect(view.container.textContent).toContain('chat:s1:false')
  82. await runtime.sessions.updateSnapshot('s1', (draft) => { draft.running = true })
  83. expect(view.container.textContent).toContain('chat:s1:true')
  84. await runtime.sessions.add({ id: 's2' }) // becomes current by default
  85. expect(view.container.textContent).toContain('chat:s2:false')
  86. await runtime.sessions.setCurrent(undefined)
  87. expect(view.container.textContent).toContain('no session')
  88. await runtime.sessions.setCurrent('s1')
  89. expect(view.container.textContent).toContain('chat:s1:true')
  90. await runtime.dispose()
  91. })
  92. it('add with current:false keeps the selection; unknown ids fail loud on the mutators', async () => {
  93. const runtime = await runtimeWithFrame()
  94. await runtime.sessions.add({ id: 's1' })
  95. await runtime.sessions.add({ id: 's2' }, { current: false })
  96. expect(runtime.sessions.list.getSnapshot().current).toBe('s1')
  97. expect(runtime.sessions.list.getSnapshot().ids).toEqual(['s1', 's2'])
  98. await expect(runtime.sessions.add({ id: 's1' })).rejects.toThrow(/already added/)
  99. await expect(runtime.sessions.setCurrent('ghost')).rejects.toThrow(/not added/)
  100. await expect(runtime.sessions.updateSnapshot('ghost', () => {})).rejects.toThrow(/not added/)
  101. await expect(runtime.sessions.remove('ghost')).rejects.toThrow(/not added/)
  102. expect(() => runtime.sessions.behavior('ghost')).toThrow(/not added/)
  103. await runtime.dispose()
  104. })
  105. it('mints REAL-tag scopes lazily and resolves them through the production scopeOf; bindings expose the behavior face', async () => {
  106. const runtime = await runtimeWithFrame()
  107. const prompt = vi.fn()
  108. await runtime.sessions.add({ id: 's1', session: { prompt } })
  109. expect(runtime.sessions.provideInfo('ghost')).toBeUndefined()
  110. expect(runtime.sessions.scope('ghost')).toBeUndefined()
  111. expect(runtime.sessions.binding('ghost')).toBeUndefined()
  112. const scope = runtime.sessions.scope('s1')!
  113. expect(runtime.sessions.scope('s1')).toBe(scope) // stable per session
  114. expect(runtime.sessions.scopeOf(scope)).toBe('s1')
  115. expect(runtime.sessions.scopeOf(runtime.ctx)).toBeUndefined()
  116. // sessionOf resolves the behavior face off the scope tag.
  117. expect(runtime.sessions.sessionOf(scope)).toBe(runtime.sessions.behavior('s1'))
  118. expect(runtime.sessions.sessionOf(runtime.ctx)).toBeUndefined()
  119. const binding = runtime.sessions.binding('s1')!
  120. expect(binding.sessionId).toBe('s1')
  121. expect(binding.ctx).toBe(scope)
  122. ;(binding.session as { prompt: () => void }).prompt()
  123. expect(prompt).toHaveBeenCalledOnce()
  124. expect(runtime.sessions.behavior('s1')).toBe(binding.session)
  125. // The binding's session doubles as the conversation observable face.
  126. expect((binding.session as { getSnapshot(): { sessionId: string } }).getSnapshot().sessionId).toBe('s1')
  127. // A scoped service resolves through the scope ctx (scope-addressed pattern).
  128. runtime.provide('probe', { hello: 'world' })
  129. expect(scope.get('probe')).toEqual({ hello: 'world' })
  130. await runtime.dispose()
  131. })
  132. it('materializes provide bundles: built-in session hook, custom providers, no-session projection', async () => {
  133. const runtime = await runtimeWithFrame()
  134. await runtime.sessions.add({ id: 's1' })
  135. const info = runtime.sessions.provideInfo('s1')!
  136. expect(info.sessionId).toBe('s1')
  137. expect(info.hooks['session']).toBeDefined() // the built-in useSession source
  138. expect(runtime.sessions.provideInfo('s1')).toBe(info) // identity-stable
  139. // A feature provider (the ui-conversation input pattern): declared names
  140. // materialize per session and land in the no-session roster as undefined.
  141. const off = runtime.sessions.provide({
  142. hooks: ['probe'],
  143. props: ['probeActions'],
  144. resolve: binding => ({
  145. hooks: { probe: { getSnapshot: () => binding.sessionId, subscribe: () => () => {} } },
  146. props: { probeActions: { poke: () => {} } },
  147. }),
  148. })
  149. const enriched = runtime.sessions.provideInfo('s1')!
  150. expect(enriched.hooks['probe']?.getSnapshot()).toBe('s1')
  151. expect(enriched.props['probeActions']).toBeDefined()
  152. const maybe = runtime.sessions.maybeProvideInfo(undefined)
  153. expect(maybe.sessionId).toBeUndefined()
  154. expect(Object.keys(maybe.hooks)).toEqual(['session', 'probe'])
  155. expect(runtime.sessions.maybeProvideInfo('s1')).toBe(runtime.sessions.provideInfo('s1'))
  156. expect(runtime.sessions.maybeProvideInfo('ghost').sessionId).toBeUndefined()
  157. // Misdeclared providers fail loud AT REGISTRATION (the production
  158. // channel rebuilds live bundles eagerly and rolls the roster back):
  159. // missing hook, missing prop, duplicate hook, duplicate prop.
  160. expect(() => runtime.sessions.provide({ hooks: ['void'], resolve: () => ({}) }))
  161. .toThrow(/missing hook "void"/)
  162. expect(() => runtime.sessions.provide({ props: ['void'], resolve: () => ({}) }))
  163. .toThrow(/missing prop "void"/)
  164. expect(() => runtime.sessions.provide({
  165. hooks: ['session'],
  166. resolve: () => ({ hooks: { session: { getSnapshot: () => 0, subscribe: () => () => {} } } }),
  167. })).toThrow(/duplicate hook "session"/)
  168. const propA = runtime.sessions.provide({ props: ['twice'], resolve: () => ({ props: { twice: 1 } }) })
  169. expect(() => runtime.sessions.provide({ props: ['twice'], resolve: () => ({ props: { twice: 2 } }) }))
  170. .toThrow(/duplicate prop "twice"/)
  171. propA()
  172. // The rejected registrations rolled back: the roster still materializes.
  173. expect(runtime.sessions.provideInfo('s1')).toBeDefined()
  174. off()
  175. off() // disposer is idempotent
  176. expect(Object.keys(runtime.sessions.maybeProvideInfo(undefined).hooks)).toEqual(['session'])
  177. await runtime.dispose()
  178. })
  179. it('records service-face calls; open() moves the selection and clear() empties it', async () => {
  180. const runtime = await runtimeWithFrame()
  181. await runtime.sessions.add({ id: 's1' })
  182. await runtime.sessions.add({ id: 's2' })
  183. runtime.sessions.open('s1' as SessionId)
  184. await runtime.flush()
  185. expect(runtime.sessions.list.getSnapshot().current).toBe('s1')
  186. runtime.sessions.clear()
  187. await runtime.flush()
  188. expect(runtime.sessions.list.getSnapshot().current).toBeUndefined()
  189. expect(runtime.sessions.calls).toEqual([
  190. { method: 'open', args: ['s1'] },
  191. { method: 'clear', args: [] },
  192. ])
  193. await runtime.dispose()
  194. })
  195. })
  196. describe('stores', () => {
  197. const createSuiteStore = () => defineStore({
  198. init: () => ({ note: '' }),
  199. persist: 'trt.store',
  200. actions: { setNote: (d, note: string) => { d.note = note } },
  201. })
  202. it('resolves per-session instances via the host face: shared identity, isolation, action-driven re-render', async () => {
  203. const runtime = await runtimeWithFrame()
  204. const handle = createSuiteStore()
  205. runtime.slots.register(
  206. { name: 'trt.chat', store: handle },
  207. (props: SessionStandardProps & { useStore: <S>(sel: (s: { note: string }) => S) => S }) =>
  208. <span>note:{props.useStore(s => s.note)}</span>)
  209. const view = runtime.renderRoot()
  210. await runtime.sessions.add({ id: 's1' })
  211. expect(() => runtime.storeOf('trt.panel')).toThrow(/no registration/)
  212. const store = runtime.storeOf('trt.chat', 's1')
  213. await runtime.flush()
  214. ;(store.actions['setNote'] as (note: string) => void)('hello')
  215. await runtime.flush()
  216. expect(view.container.textContent).toContain('note:hello')
  217. expect(runtime.storeOf('trt.chat', 's1')).toBe(store) // cached per scope key
  218. await runtime.sessions.add({ id: 's2' })
  219. const other = runtime.storeOf('trt.chat', 's2')
  220. expect(other).not.toBe(store)
  221. expect(other.getSnapshot()).toEqual({ note: '' })
  222. await runtime.dispose()
  223. })
  224. it('storeOf guards: before renderRoot, and for storeless entries', async () => {
  225. const runtime = await runtimeWithFrame()
  226. runtime.slots.register({ name: 'trt.panel' }, () => null)
  227. expect(() => runtime.storeOf('trt.panel')).toThrow(/before renderRoot/)
  228. runtime.renderRoot()
  229. expect(() => runtime.storeOf('trt.panel')).toThrow(/declares no store/)
  230. await runtime.dispose()
  231. })
  232. it('remove() prunes the session store scope: persisted state clears, a re-added session starts fresh', async () => {
  233. const runtime = await runtimeWithFrame()
  234. const handle = createSuiteStore()
  235. runtime.slots.register({ name: 'trt.chat', store: handle }, () => null)
  236. runtime.renderRoot()
  237. await runtime.sessions.add({ id: 's1' })
  238. const doomed = runtime.storeOf('trt.chat', 's1')
  239. ;(doomed.actions['setNote'] as (note: string) => void)('buried')
  240. expect(localStorage.getItem('trt.store.s1')).not.toBeNull()
  241. await runtime.sessions.remove('s1')
  242. expect(localStorage.getItem('trt.store.s1')).toBeNull()
  243. expect(runtime.sessions.list.getSnapshot().ids).toEqual([])
  244. expect(runtime.sessions.provideInfo('s1')).toBeUndefined()
  245. await runtime.sessions.add({ id: 's1' })
  246. const reborn = runtime.storeOf('trt.chat', 's1')
  247. expect(reborn).not.toBe(doomed)
  248. expect(reborn.getSnapshot()).toEqual({ note: '' })
  249. await runtime.dispose()
  250. })
  251. it('remove() also disposes a minted scope fiber; removing a non-current session keeps the selection', async () => {
  252. const runtime = await runtimeWithFrame()
  253. await runtime.sessions.add({ id: 's1' })
  254. await runtime.sessions.add({ id: 's2' }, { current: false })
  255. const scope = runtime.sessions.scope('s1')!
  256. await runtime.sessions.remove('s2')
  257. expect(runtime.sessions.list.getSnapshot().current).toBe('s1')
  258. await runtime.sessions.remove('s1')
  259. expect(scope.fiber.uid).toBeNull() // disposed fiber loses its uid
  260. expect(runtime.sessions.list.getSnapshot().current).toBeUndefined()
  261. await runtime.dispose()
  262. })
  263. })
  264. describe('workspaces', () => {
  265. it('feeds useWorkspaces and records/stubs intent actions', async () => {
  266. const runtime = await runtimeWithFrame()
  267. runtime.slots.register(
  268. { name: 'trt.panel' },
  269. (props: { useWorkspaces: <S>(sel: (s: { phase: string }) => S) => S }) =>
  270. <span>ws:{props.useWorkspaces(s => s.phase)}</span>)
  271. const view = runtime.renderRoot()
  272. expect(view.container.textContent).toContain('ws:ready')
  273. await runtime.workspaces.update((draft) => { draft.phase = 'pending' })
  274. expect(view.container.textContent).toContain('ws:pending')
  275. runtime.workspaces.startSession('w1' as WorkspaceId)
  276. await expect(runtime.workspaces.connectWorkspace('w2' as WorkspaceId)).resolves.toBe('session-of-w2')
  277. expect(runtime.workspaces.calls).toEqual([
  278. { method: 'startSession', args: ['w1'] },
  279. { method: 'connectWorkspace', args: ['w2'] },
  280. ])
  281. const stub = vi.fn(() => Promise.resolve('other' as never))
  282. runtime.workspaces.stub('connectWorkspace', stub)
  283. await expect(runtime.workspaces.connectWorkspace('w3' as WorkspaceId)).resolves.toBe('other')
  284. expect(stub).toHaveBeenCalledOnce()
  285. await runtime.dispose()
  286. })
  287. })
  288. describe('feature mount and disposal', () => {
  289. it('mounts a plugin on a real fiber; dispose() cascades entries, declared children, and services', async () => {
  290. const runtime = await runtimeWithFrame()
  291. runtime.provide('layout', { openDetails: vi.fn() })
  292. const feature = await runtime.mount({
  293. inject: ['slots', 'layout'],
  294. apply: (ctx: typeof runtime.ctx) => {
  295. ctx.provide('feature-service', { ok: true })
  296. ctx.slots.register({
  297. name: 'trt.rows',
  298. id: 'row-1',
  299. children: { 'trt.rows.hole': { kind: 'single', scope: 'root' } },
  300. } as never, ((props: { renderSlot: (key: string, owner: object) => unknown }) =>
  301. <div data-testid="row">{props.renderSlot('trt.rows.hole', {}) as React.ReactNode}</div>) as never)
  302. },
  303. })
  304. const view = runtime.renderRoot()
  305. expect(view.getByTestId('row')).toBeTruthy()
  306. expect(runtime.ctx.get('feature-service')).toEqual({ ok: true })
  307. expect(runtime.slots.entries('trt.rows')).toHaveLength(1)
  308. await feature.dispose()
  309. await feature.dispose() // idempotent
  310. expect(runtime.slots.entries('trt.rows')).toHaveLength(0)
  311. expect(runtime.slots.spec('trt.rows.hole' as never)).toBeUndefined()
  312. expect(runtime.ctx.get('feature-service')).toBeUndefined()
  313. expect(view.queryByTestId('row')).toBeNull()
  314. await runtime.dispose()
  315. })
  316. it('mount fails loud on missing services instead of suspending forever', async () => {
  317. const runtime = await runtimeWithFrame()
  318. await expect(runtime.mount({ inject: ['slots', 'absent-service'], apply: () => {} }))
  319. .rejects.toThrow(/missing service\(s\) absent-service/)
  320. await runtime.dispose()
  321. })
  322. it('runtime dispose is idempotent, unmounts views, disposes mounted features, and clears persisted state', async () => {
  323. const runtime = await runtimeWithFrame()
  324. const feature = await runtime.mount({
  325. inject: ['slots'],
  326. apply: (ctx: typeof runtime.ctx) => { ctx.slots.register({ name: 'trt.panel' }, () => <b>p</b>) },
  327. })
  328. const view = runtime.renderRoot()
  329. expect(view.container.textContent).toContain('p')
  330. localStorage.setItem('trt.leftover', 'x')
  331. await runtime.dispose()
  332. expect(view.container.innerHTML).toBe('')
  333. expect(feature.fiber.uid).toBeNull()
  334. expect(localStorage.getItem('trt.leftover')).toBeNull()
  335. await runtime.dispose() // idempotent
  336. await expect(runtime.dispose()).resolves.toBeUndefined()
  337. })
  338. })
  339. describe('single-slot mounting (declare + renderSlot)', () => {
  340. it('renders one slot inside its data-slot wrapper and updates owner props in place', async () => {
  341. const runtime = await SlotTestRuntime.create()
  342. await runtime.declare({ 'trt.panel': { kind: 'single', scope: 'root' } })
  343. runtime.slots.register(
  344. { name: 'trt.panel' },
  345. ({ label }: { label?: string }) => <b data-testid="panel">{label ?? 'none'}</b>)
  346. const slot = runtime.renderSlot('trt.panel', { label: 'first' })
  347. expect(slot.container.getAttribute('data-slot')).toBe('trt.panel')
  348. expect(slot.view.getByTestId('panel').textContent).toBe('first')
  349. const panel = slot.view.getByTestId('panel')
  350. slot.update({ label: 'second' })
  351. expect(slot.view.getByTestId('panel').textContent).toBe('second')
  352. // In-place re-render: the element identity survived the owner flip.
  353. expect(slot.view.getByTestId('panel')).toBe(panel)
  354. await runtime.dispose()
  355. })
  356. it('views sibling slots of one tree separately and rejects undeclared keys', async () => {
  357. const runtime = await SlotTestRuntime.create()
  358. await runtime.declare({
  359. 'trt.panel': { kind: 'single', scope: 'root' },
  360. 'trt.rows': { kind: 'list', scope: 'root' },
  361. })
  362. runtime.slots.register({ name: 'trt.panel' }, () => <b>panel</b>)
  363. runtime.slots.register({ name: 'trt.rows', id: 'r1' }, () => <i>row</i>)
  364. const panel = runtime.renderSlot('trt.panel', {})
  365. const rows = runtime.renderSlot('trt.rows', {})
  366. expect(panel.container.textContent).toBe('panel')
  367. expect(rows.container.textContent).toBe('row')
  368. expect(() => runtime.renderSlot('trt.chat', {})).toThrow(/without declare\(\)/)
  369. await runtime.dispose()
  370. })
  371. it('folds class hashes and collapses svg internals in snapshots, leaving the live DOM alone', async () => {
  372. const runtime = await SlotTestRuntime.create()
  373. await runtime.declare({ 'trt.panel': { kind: 'single', scope: 'root' } })
  374. runtime.slots.register({ name: 'trt.panel' }, () => (
  375. <div className="_frame_a1b2c3 plain">
  376. <span className="_label_ff00aa">styled</span>
  377. <svg viewBox="0 0 16 16" aria-hidden="true">
  378. <path d="M0 0L16 16" fill="currentColor" />
  379. </svg>
  380. </div>
  381. ))
  382. const slot = runtime.renderSlot('trt.panel', {})
  383. expect(slot.container).toMatchSnapshot()
  384. // The serializer works on a clone: the live DOM keeps hashes and paths.
  385. expect(slot.container.querySelector('div')!.className).toBe('_frame_a1b2c3 plain')
  386. expect(slot.container.querySelector('svg path')).not.toBeNull()
  387. await runtime.dispose()
  388. })
  389. })
  390. describe('fixture session face', () => {
  391. it('fail-loud stubs name the missing verb; supplied overrides run instead', async () => {
  392. const runtime = await SlotTestRuntime.create()
  393. await runtime.sessions.add({ id: 's1' })
  394. const bare = runtime.sessions.behavior('s1')
  395. expect(() => bare.prompt()).toThrow(/prompt is not stubbed/)
  396. expect(() => bare.cancel()).toThrow(/cancel is not stubbed/)
  397. expect(() => bare.loadOlder()).toThrow(/loadOlder is not stubbed/)
  398. await runtime.dispose()
  399. })
  400. it('projections faces are identity-stable per key, read absent, and notify on set', async () => {
  401. const runtime = await SlotTestRuntime.create()
  402. await runtime.sessions.add({ id: 's1' })
  403. const session = runtime.sessions.behavior('s1')
  404. const face = session.projections.faceOf('todos')
  405. expect(session.projections.faceOf('todos')).toBe(face)
  406. expect(face.getSnapshot()).toBeUndefined()
  407. const seen: unknown[] = []
  408. const off = face.subscribe(() => { seen.push(face.getSnapshot()) })
  409. session.projections.set('todos', [1, 2])
  410. expect(seen).toEqual([[1, 2]])
  411. off()
  412. session.projections.set('todos', [3])
  413. expect(seen).toEqual([[1, 2]]) // unsubscribed
  414. // A never-subscribed key sets without listeners (the empty-notify arm).
  415. session.projections.set('untouched', 1)
  416. // The provide bundle hands the same store to the render side.
  417. const info = runtime.sessions.provideInfo('s1')!
  418. expect(info.projections?.faceOf('todos').getSnapshot()).toEqual([3])
  419. // A roster change rebuilds the ALREADY-materialized bundle eagerly
  420. // (production channel semantics: mounted entries must see the provider)
  421. // and skips never-materialized records (they pick the roster up lazily).
  422. await runtime.sessions.add({ id: 's-lazy' }, { current: false })
  423. const offProbe = runtime.sessions.provide({
  424. hooks: ['probe2'],
  425. resolve: () => ({ hooks: { probe2: { getSnapshot: () => 1, subscribe: () => () => {} } } }),
  426. })
  427. const rebuilt = runtime.sessions.provideInfo('s1')!
  428. expect(rebuilt).not.toBe(info)
  429. expect(rebuilt.hooks['probe2']).toBeDefined()
  430. offProbe()
  431. await runtime.dispose()
  432. })
  433. })
  434. describe('workspaces action face', () => {
  435. it('records every IWorkspaces verb with inert defaults and honors stubs', async () => {
  436. const runtime = await SlotTestRuntime.create()
  437. const ws = runtime.workspaces
  438. const created = await ws.create({ name: 'alpha' })
  439. expect(created.title).toBe('alpha')
  440. const registered = await ws.create({ path: '/tmp/beta' })
  441. expect(registered.path).toBe('/tmp/beta')
  442. await expect(ws.pickDirectory()).resolves.toBeNull()
  443. const renamed = await ws.rename('w1' as WorkspaceId, 'Renamed')
  444. expect(renamed.title).toBe('Renamed')
  445. await ws.delete('w1' as WorkspaceId)
  446. await ws.openPath('/proj/file.ts')
  447. const moved = await ws.insertSessionBefore('w1' as WorkspaceId, 's1' as SessionId, 's2' as SessionId)
  448. expect(moved.sessionIds).toEqual(['s1'])
  449. expect(ws.calls.map(c => c.method)).toEqual(
  450. ['create', 'create', 'pickDirectory', 'rename', 'delete', 'openPath', 'insertSessionBefore'])
  451. ws.stub('create', () => Promise.resolve({ workspaceId: 'ws-x', title: 'X', path: '/x', sessionIds: [] } as never))
  452. ws.stub('pickDirectory', () => Promise.resolve('/picked'))
  453. ws.stub('rename', () => Promise.resolve({ workspaceId: 'w1', title: 'S', path: '/s', sessionIds: [] } as never))
  454. ws.stub('delete', () => Promise.resolve())
  455. ws.stub('openPath', () => Promise.resolve())
  456. ws.stub('insertSessionBefore', () => Promise.resolve({ workspaceId: 'w1', title: '', path: '', sessionIds: [] } as never))
  457. expect((await ws.create({ name: 'y' })).title).toBe('X')
  458. await expect(ws.pickDirectory()).resolves.toBe('/picked')
  459. expect((await ws.rename('w1' as WorkspaceId, 'z')).title).toBe('S')
  460. await ws.delete('w1' as WorkspaceId)
  461. await ws.openPath('/other')
  462. expect((await ws.insertSessionBefore('w1' as WorkspaceId, 's1' as SessionId)).sessionIds).toEqual([])
  463. await runtime.dispose()
  464. })
  465. })
  466. describe('single-slot mounting edge arms', () => {
  467. it('renderSlot fails loud after dispose and after an external unmount', async () => {
  468. const runtime = await SlotTestRuntime.create()
  469. await runtime.declare({ 'trt.panel': { kind: 'single', scope: 'root' } })
  470. runtime.slots.register({ name: 'trt.panel' }, () => <b>p</b>)
  471. runtime.renderSlot('trt.panel', {})
  472. // RTL cleanup empties the mounted tree behind the runtime's back: the
  473. // wrapper lookup names the state instead of returning a dead container.
  474. cleanup()
  475. expect(() => runtime.renderSlot('trt.panel', {})).toThrow(/rendered no wrapper/)
  476. await runtime.dispose()
  477. // After dispose the root registration is gone: the production boot-order
  478. // check fires before any wrapper lookup.
  479. expect(() => runtime.renderSlot('trt.panel', {})).toThrow(/'root' has no registration/)
  480. })
  481. it('serializes childless svg untouched next to scoped classes', async () => {
  482. const runtime = await SlotTestRuntime.create()
  483. await runtime.declare({ 'trt.panel': { kind: 'single', scope: 'root' } })
  484. runtime.slots.register({ name: 'trt.panel' }, () => (
  485. <div className="_frame_a1b2c3">
  486. <svg viewBox="0 0 1 1" aria-hidden="true" />
  487. </div>
  488. ))
  489. const slot = runtime.renderSlot('trt.panel', {})
  490. expect(slot.container).toMatchSnapshot()
  491. await runtime.dispose()
  492. })
  493. })