runtime.spec.tsx 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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. it('records the browse calls: listDirectory serves an empty home, createDirectory joins, stubs override', async () => {
  288. const runtime = await runtimeWithFrame()
  289. // Defaults: an empty home level and parent/name joining.
  290. await expect(runtime.workspaces.listDirectory()).resolves.toMatchObject({ path: '/home/test', entries: [] })
  291. await expect(runtime.workspaces.listDirectory('/home/test')).resolves.toMatchObject({ path: '/home/test' })
  292. await expect(runtime.workspaces.createDirectory('/home/test', 'fresh')).resolves.toBe('/home/test/fresh')
  293. // The recorded signal seat mirrors the production face (undefined here;
  294. // cancellation tests pass and observe a real one).
  295. expect(runtime.workspaces.calls).toEqual([
  296. { method: 'listDirectory', args: [undefined, undefined] },
  297. { method: 'listDirectory', args: ['/home/test', undefined] },
  298. { method: 'createDirectory', args: ['/home/test', 'fresh'] },
  299. ])
  300. // Stubs replace the defaults like every sibling method.
  301. const listing = { path: '/x', home: '/x', crumbs: [], entries: [] }
  302. const listStub = vi.fn(() => Promise.resolve(listing as never))
  303. runtime.workspaces.stub('listDirectory', listStub)
  304. runtime.workspaces.stub('createDirectory', vi.fn(() => Promise.resolve('/x/made' as never)))
  305. const scan = new AbortController()
  306. await expect(runtime.workspaces.listDirectory('/x', scan.signal)).resolves.toBe(listing)
  307. // The stub receives the signal too, like the production face gives the wire.
  308. expect(listStub).toHaveBeenLastCalledWith('/x', scan.signal)
  309. await expect(runtime.workspaces.createDirectory('/x', 'made')).resolves.toBe('/x/made')
  310. await runtime.dispose()
  311. })
  312. })
  313. describe('feature mount and disposal', () => {
  314. it('mounts a plugin on a real fiber; dispose() cascades entries, declared children, and services', async () => {
  315. const runtime = await runtimeWithFrame()
  316. runtime.provide('layout', { openDetails: vi.fn() })
  317. const feature = await runtime.mount({
  318. inject: ['slots', 'layout'],
  319. apply: (ctx: typeof runtime.ctx) => {
  320. ctx.provide('feature-service', { ok: true })
  321. ctx.slots.register({
  322. name: 'trt.rows',
  323. id: 'row-1',
  324. children: { 'trt.rows.hole': { kind: 'single', scope: 'root' } },
  325. } as never, ((props: { renderSlot: (key: string, owner: object) => unknown }) =>
  326. <div data-testid="row">{props.renderSlot('trt.rows.hole', {}) as React.ReactNode}</div>) as never)
  327. },
  328. })
  329. const view = runtime.renderRoot()
  330. expect(view.getByTestId('row')).toBeTruthy()
  331. expect(runtime.ctx.get('feature-service')).toEqual({ ok: true })
  332. expect(runtime.slots.entries('trt.rows')).toHaveLength(1)
  333. await feature.dispose()
  334. await feature.dispose() // idempotent
  335. expect(runtime.slots.entries('trt.rows')).toHaveLength(0)
  336. expect(runtime.slots.spec('trt.rows.hole' as never)).toBeUndefined()
  337. expect(runtime.ctx.get('feature-service')).toBeUndefined()
  338. expect(view.queryByTestId('row')).toBeNull()
  339. await runtime.dispose()
  340. })
  341. it('mount fails loud on missing services instead of suspending forever', async () => {
  342. const runtime = await runtimeWithFrame()
  343. await expect(runtime.mount({ inject: ['slots', 'absent-service'], apply: () => {} }))
  344. .rejects.toThrow(/missing service\(s\) absent-service/)
  345. await runtime.dispose()
  346. })
  347. it('runtime dispose is idempotent, unmounts views, disposes mounted features, and clears persisted state', async () => {
  348. const runtime = await runtimeWithFrame()
  349. const feature = await runtime.mount({
  350. inject: ['slots'],
  351. apply: (ctx: typeof runtime.ctx) => { ctx.slots.register({ name: 'trt.panel' }, () => <b>p</b>) },
  352. })
  353. const view = runtime.renderRoot()
  354. expect(view.container.textContent).toContain('p')
  355. localStorage.setItem('trt.leftover', 'x')
  356. await runtime.dispose()
  357. expect(view.container.innerHTML).toBe('')
  358. expect(feature.fiber.uid).toBeNull()
  359. expect(localStorage.getItem('trt.leftover')).toBeNull()
  360. await runtime.dispose() // idempotent
  361. await expect(runtime.dispose()).resolves.toBeUndefined()
  362. })
  363. })
  364. describe('single-slot mounting (declare + renderSlot)', () => {
  365. it('renders one slot inside its data-slot wrapper and updates owner props in place', async () => {
  366. const runtime = await SlotTestRuntime.create()
  367. await runtime.declare({ 'trt.panel': { kind: 'single', scope: 'root' } })
  368. runtime.slots.register(
  369. { name: 'trt.panel' },
  370. ({ label }: { label?: string }) => <b data-testid="panel">{label ?? 'none'}</b>)
  371. const slot = runtime.renderSlot('trt.panel', { label: 'first' })
  372. expect(slot.container.getAttribute('data-slot')).toBe('trt.panel')
  373. expect(slot.view.getByTestId('panel').textContent).toBe('first')
  374. const panel = slot.view.getByTestId('panel')
  375. slot.update({ label: 'second' })
  376. expect(slot.view.getByTestId('panel').textContent).toBe('second')
  377. // In-place re-render: the element identity survived the owner flip.
  378. expect(slot.view.getByTestId('panel')).toBe(panel)
  379. await runtime.dispose()
  380. })
  381. it('views sibling slots of one tree separately and rejects undeclared keys', async () => {
  382. const runtime = await SlotTestRuntime.create()
  383. await runtime.declare({
  384. 'trt.panel': { kind: 'single', scope: 'root' },
  385. 'trt.rows': { kind: 'list', scope: 'root' },
  386. })
  387. runtime.slots.register({ name: 'trt.panel' }, () => <b>panel</b>)
  388. runtime.slots.register({ name: 'trt.rows', id: 'r1' }, () => <i>row</i>)
  389. const panel = runtime.renderSlot('trt.panel', {})
  390. const rows = runtime.renderSlot('trt.rows', {})
  391. expect(panel.container.textContent).toBe('panel')
  392. expect(rows.container.textContent).toBe('row')
  393. expect(() => runtime.renderSlot('trt.chat', {})).toThrow(/without declare\(\)/)
  394. await runtime.dispose()
  395. })
  396. it('folds class hashes and collapses svg internals in snapshots, leaving the live DOM alone', async () => {
  397. const runtime = await SlotTestRuntime.create()
  398. await runtime.declare({ 'trt.panel': { kind: 'single', scope: 'root' } })
  399. runtime.slots.register({ name: 'trt.panel' }, () => (
  400. <div className="_frame_a1b2c3 plain">
  401. <span className="_label_ff00aa">styled</span>
  402. <svg viewBox="0 0 16 16" aria-hidden="true">
  403. <path d="M0 0L16 16" fill="currentColor" />
  404. </svg>
  405. </div>
  406. ))
  407. const slot = runtime.renderSlot('trt.panel', {})
  408. expect(slot.container).toMatchSnapshot()
  409. // The serializer works on a clone: the live DOM keeps hashes and paths.
  410. expect(slot.container.querySelector('div')!.className).toBe('_frame_a1b2c3 plain')
  411. expect(slot.container.querySelector('svg path')).not.toBeNull()
  412. await runtime.dispose()
  413. })
  414. })
  415. describe('fixture session face', () => {
  416. it('fail-loud stubs name the missing verb; supplied overrides run instead', async () => {
  417. const runtime = await SlotTestRuntime.create()
  418. await runtime.sessions.add({ id: 's1' })
  419. const bare = runtime.sessions.behavior('s1')
  420. expect(() => bare.prompt()).toThrow(/prompt is not stubbed/)
  421. expect(() => bare.cancel()).toThrow(/cancel is not stubbed/)
  422. expect(() => bare.command()).toThrow(/command is not stubbed/)
  423. expect(() => bare.loadOlder()).toThrow(/loadOlder is not stubbed/)
  424. await runtime.dispose()
  425. })
  426. it('projections faces are identity-stable per key, read absent, and notify on set', async () => {
  427. const runtime = await SlotTestRuntime.create()
  428. await runtime.sessions.add({ id: 's1' })
  429. const session = runtime.sessions.behavior('s1')
  430. const face = session.projections.faceOf('todos')
  431. expect(session.projections.faceOf('todos')).toBe(face)
  432. expect(face.getSnapshot()).toBeUndefined()
  433. const seen: unknown[] = []
  434. const off = face.subscribe(() => { seen.push(face.getSnapshot()) })
  435. session.projections.set('todos', [1, 2])
  436. expect(seen).toEqual([[1, 2]])
  437. off()
  438. session.projections.set('todos', [3])
  439. expect(seen).toEqual([[1, 2]]) // unsubscribed
  440. // A never-subscribed key sets without listeners (the empty-notify arm).
  441. session.projections.set('untouched', 1)
  442. // The provide bundle hands the same store to the render side.
  443. const info = runtime.sessions.provideInfo('s1')!
  444. expect(info.projections?.faceOf('todos').getSnapshot()).toEqual([3])
  445. // A roster change rebuilds the ALREADY-materialized bundle eagerly
  446. // (production channel semantics: mounted entries must see the provider)
  447. // and skips never-materialized records (they pick the roster up lazily).
  448. await runtime.sessions.add({ id: 's-lazy' }, { current: false })
  449. const offProbe = runtime.sessions.provide({
  450. hooks: ['probe2'],
  451. resolve: () => ({ hooks: { probe2: { getSnapshot: () => 1, subscribe: () => () => {} } } }),
  452. })
  453. const rebuilt = runtime.sessions.provideInfo('s1')!
  454. expect(rebuilt).not.toBe(info)
  455. expect(rebuilt.hooks['probe2']).toBeDefined()
  456. offProbe()
  457. await runtime.dispose()
  458. })
  459. })
  460. describe('workspaces action face', () => {
  461. it('records every IWorkspaces verb with inert defaults and honors stubs', async () => {
  462. const runtime = await SlotTestRuntime.create()
  463. const ws = runtime.workspaces
  464. const created = await ws.create({ name: 'alpha' })
  465. expect(created.title).toBe('alpha')
  466. const registered = await ws.create({ path: '/tmp/beta' })
  467. expect(registered.path).toBe('/tmp/beta')
  468. await expect(ws.pickDirectory()).resolves.toBeNull()
  469. const renamed = await ws.rename('w1' as WorkspaceId, 'Renamed')
  470. expect(renamed.title).toBe('Renamed')
  471. await ws.delete('w1' as WorkspaceId)
  472. await ws.openPath('/proj/file.ts')
  473. const moved = await ws.insertSessionBefore('w1' as WorkspaceId, 's1' as SessionId, 's2' as SessionId)
  474. expect(moved.sessionIds).toEqual(['s1'])
  475. expect(ws.calls.map(c => c.method)).toEqual(
  476. ['create', 'create', 'pickDirectory', 'rename', 'delete', 'openPath', 'insertSessionBefore'])
  477. ws.stub('create', () => Promise.resolve({ workspaceId: 'ws-x', title: 'X', path: '/x', sessionIds: [] } as never))
  478. ws.stub('pickDirectory', () => Promise.resolve('/picked'))
  479. ws.stub('rename', () => Promise.resolve({ workspaceId: 'w1', title: 'S', path: '/s', sessionIds: [] } as never))
  480. ws.stub('delete', () => Promise.resolve())
  481. ws.stub('openPath', () => Promise.resolve())
  482. ws.stub('insertSessionBefore', () => Promise.resolve({ workspaceId: 'w1', title: '', path: '', sessionIds: [] } as never))
  483. expect((await ws.create({ name: 'y' })).title).toBe('X')
  484. await expect(ws.pickDirectory()).resolves.toBe('/picked')
  485. expect((await ws.rename('w1' as WorkspaceId, 'z')).title).toBe('S')
  486. await ws.delete('w1' as WorkspaceId)
  487. await ws.openPath('/other')
  488. expect((await ws.insertSessionBefore('w1' as WorkspaceId, 's1' as SessionId)).sessionIds).toEqual([])
  489. await runtime.dispose()
  490. })
  491. })
  492. describe('single-slot mounting edge arms', () => {
  493. it('renderSlot fails loud after dispose and after an external unmount', async () => {
  494. const runtime = await SlotTestRuntime.create()
  495. await runtime.declare({ 'trt.panel': { kind: 'single', scope: 'root' } })
  496. runtime.slots.register({ name: 'trt.panel' }, () => <b>p</b>)
  497. runtime.renderSlot('trt.panel', {})
  498. // RTL cleanup empties the mounted tree behind the runtime's back: the
  499. // wrapper lookup names the state instead of returning a dead container.
  500. cleanup()
  501. expect(() => runtime.renderSlot('trt.panel', {})).toThrow(/rendered no wrapper/)
  502. await runtime.dispose()
  503. // After dispose the root registration is gone: the production boot-order
  504. // check fires before any wrapper lookup.
  505. expect(() => runtime.renderSlot('trt.panel', {})).toThrow(/'root' has no registration/)
  506. })
  507. it('serializes childless svg untouched next to scoped classes', async () => {
  508. const runtime = await SlotTestRuntime.create()
  509. await runtime.declare({ 'trt.panel': { kind: 'single', scope: 'root' } })
  510. runtime.slots.register({ name: 'trt.panel' }, () => (
  511. <div className="_frame_a1b2c3">
  512. <svg viewBox="0 0 1 1" aria-hidden="true" />
  513. </div>
  514. ))
  515. const slot = runtime.renderSlot('trt.panel', {})
  516. expect(slot.container).toMatchSnapshot()
  517. await runtime.dispose()
  518. })
  519. })