runtime.spec.tsx 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  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 and retains catalog addresses only for addressed selection', async () => {
  180. const runtime = await runtimeWithFrame()
  181. await runtime.sessions.add({ id: 's1' })
  182. await runtime.sessions.add({ id: 's2' })
  183. const address = {
  184. parentSessionId: 's2' as SessionId,
  185. childSessionId: 's1' as SessionId,
  186. mode: 'continuable' as const,
  187. }
  188. runtime.sessions.openSubagent(address)
  189. await runtime.flush()
  190. expect(runtime.sessions.list.getSnapshot()).toMatchObject({ current: 's1', currentAddress: address })
  191. expect(runtime.sessions.subagentAddress('s1' as SessionId)).toEqual(address)
  192. expect(runtime.sessions.subagentAddress('s2' as SessionId)).toBeUndefined()
  193. await runtime.sessions.updateSummary('s1', { displayTitle: 'renamed', running: true })
  194. expect(runtime.sessions.list.getSnapshot().byId['s1' as SessionId])
  195. .toMatchObject({ displayTitle: 'renamed', running: true })
  196. runtime.sessions.setSubagentCatalogOpen('s2' as SessionId, true)
  197. await runtime.sessions.refreshSubagents('s2' as SessionId)
  198. runtime.sessions.open('s1' as SessionId)
  199. await runtime.flush()
  200. expect(runtime.sessions.list.getSnapshot().current).toBe('s1')
  201. expect(runtime.sessions.list.getSnapshot().currentAddress).toBeUndefined()
  202. runtime.sessions.clear()
  203. await runtime.flush()
  204. expect(runtime.sessions.list.getSnapshot().current).toBeUndefined()
  205. await expect(runtime.sessions.fork({
  206. sessionId: 's1' as SessionId, atSeq: 7, increaseTitle: true,
  207. })).resolves.toBe('s1')
  208. expect(runtime.sessions.calls).toEqual([
  209. { method: 'openSubagent', args: [address] },
  210. { method: 'setSubagentCatalogOpen', args: ['s2', true] },
  211. { method: 'refreshSubagents', args: ['s2'] },
  212. { method: 'open', args: ['s1'] },
  213. { method: 'clear', args: [] },
  214. { method: 'fork', args: [{ sessionId: 's1', atSeq: 7, increaseTitle: true }] },
  215. ])
  216. await runtime.dispose()
  217. })
  218. it('answers search with an empty page until a scenario declares hits, recording every call', async () => {
  219. const runtime = await runtimeWithFrame()
  220. await runtime.sessions.add({ id: 's1' })
  221. const signal = new AbortController().signal
  222. expect(runtime.sessions.searchResultLimit).toBeGreaterThan(0)
  223. await expect(runtime.sessions.search('marker', signal))
  224. .resolves.toEqual({ ok: true, value: { items: [], hasMore: false } })
  225. runtime.sessions.stubSearch(query => ({
  226. items: [{ sessionId: 's1' as SessionId, snippet: `hit: ${query}` }],
  227. hasMore: true,
  228. }))
  229. await expect(runtime.sessions.search('marker', signal)).resolves.toEqual({
  230. ok: true,
  231. value: { items: [{ sessionId: 's1', snippet: 'hit: marker' }], hasMore: true },
  232. })
  233. expect(runtime.sessions.calls).toEqual([
  234. { method: 'search', args: ['marker', signal] },
  235. { method: 'search', args: ['marker', signal] },
  236. ])
  237. await runtime.dispose()
  238. })
  239. })
  240. describe('stores', () => {
  241. const createSuiteStore = () => defineStore({
  242. init: () => ({ note: '' }),
  243. persist: 'trt.store',
  244. actions: { setNote: (d, note: string) => { d.note = note } },
  245. })
  246. it('resolves per-session instances via the host face: shared identity, isolation, action-driven re-render', async () => {
  247. const runtime = await runtimeWithFrame()
  248. const handle = createSuiteStore()
  249. runtime.slots.register(
  250. { name: 'trt.chat', store: handle },
  251. (props: SessionStandardProps & { useStore: <S>(sel: (s: { note: string }) => S) => S }) =>
  252. <span>note:{props.useStore(s => s.note)}</span>)
  253. const view = runtime.renderRoot()
  254. await runtime.sessions.add({ id: 's1' })
  255. expect(() => runtime.storeOf('trt.panel')).toThrow(/no registration/)
  256. const store = runtime.storeOf('trt.chat', 's1')
  257. await runtime.flush()
  258. ;(store.actions['setNote'] as (note: string) => void)('hello')
  259. await runtime.flush()
  260. expect(view.container.textContent).toContain('note:hello')
  261. expect(runtime.storeOf('trt.chat', 's1')).toBe(store) // cached per scope key
  262. await runtime.sessions.add({ id: 's2' })
  263. const other = runtime.storeOf('trt.chat', 's2')
  264. expect(other).not.toBe(store)
  265. expect(other.getSnapshot()).toEqual({ note: '' })
  266. await runtime.dispose()
  267. })
  268. it('storeOf guards: before renderRoot, and for storeless entries', async () => {
  269. const runtime = await runtimeWithFrame()
  270. runtime.slots.register({ name: 'trt.panel' }, () => null)
  271. expect(() => runtime.storeOf('trt.panel')).toThrow(/before renderRoot/)
  272. runtime.renderRoot()
  273. expect(() => runtime.storeOf('trt.panel')).toThrow(/declares no store/)
  274. await runtime.dispose()
  275. })
  276. it('remove() prunes the session store scope: persisted state clears, a re-added session starts fresh', async () => {
  277. const runtime = await runtimeWithFrame()
  278. const handle = createSuiteStore()
  279. runtime.slots.register({ name: 'trt.chat', store: handle }, () => null)
  280. runtime.renderRoot()
  281. await runtime.sessions.add({ id: 's1' })
  282. const doomed = runtime.storeOf('trt.chat', 's1')
  283. ;(doomed.actions['setNote'] as (note: string) => void)('buried')
  284. expect(localStorage.getItem('trt.store.s1')).not.toBeNull()
  285. await runtime.sessions.remove('s1')
  286. expect(localStorage.getItem('trt.store.s1')).toBeNull()
  287. expect(runtime.sessions.list.getSnapshot().ids).toEqual([])
  288. expect(runtime.sessions.provideInfo('s1')).toBeUndefined()
  289. await runtime.sessions.add({ id: 's1' })
  290. const reborn = runtime.storeOf('trt.chat', 's1')
  291. expect(reborn).not.toBe(doomed)
  292. expect(reborn.getSnapshot()).toEqual({ note: '' })
  293. await runtime.dispose()
  294. })
  295. it('remove() also disposes a minted scope fiber; removing a non-current session keeps the selection', async () => {
  296. const runtime = await runtimeWithFrame()
  297. await runtime.sessions.add({ id: 's1' })
  298. await runtime.sessions.add({ id: 's2' }, { current: false })
  299. const scope = runtime.sessions.scope('s1')!
  300. await runtime.sessions.remove('s2')
  301. expect(runtime.sessions.list.getSnapshot().current).toBe('s1')
  302. await runtime.sessions.remove('s1')
  303. expect(scope.fiber.uid).toBeNull() // disposed fiber loses its uid
  304. expect(runtime.sessions.list.getSnapshot().current).toBeUndefined()
  305. await runtime.dispose()
  306. })
  307. })
  308. describe('workspaces', () => {
  309. it('feeds useWorkspaces and records/stubs intent actions', async () => {
  310. const runtime = await runtimeWithFrame()
  311. runtime.slots.register(
  312. { name: 'trt.panel' },
  313. (props: { useWorkspaces: <S>(sel: (s: { phase: string }) => S) => S }) =>
  314. <span>ws:{props.useWorkspaces(s => s.phase)}</span>)
  315. const view = runtime.renderRoot()
  316. expect(view.container.textContent).toContain('ws:ready')
  317. await runtime.workspaces.update((draft) => { draft.phase = 'pending' })
  318. expect(view.container.textContent).toContain('ws:pending')
  319. runtime.workspaces.startSession('w1' as WorkspaceId)
  320. await expect(runtime.workspaces.connectWorkspace('w2' as WorkspaceId)).resolves.toBe('session-of-w2')
  321. expect(runtime.workspaces.calls).toEqual([
  322. { method: 'startSession', args: ['w1'] },
  323. { method: 'connectWorkspace', args: ['w2'] },
  324. ])
  325. const stub = vi.fn(() => Promise.resolve('other' as never))
  326. runtime.workspaces.stub('connectWorkspace', stub)
  327. await expect(runtime.workspaces.connectWorkspace('w3' as WorkspaceId)).resolves.toBe('other')
  328. expect(stub).toHaveBeenCalledOnce()
  329. await runtime.dispose()
  330. })
  331. it('records the browse calls: listDirectory serves an empty home, createDirectory joins, stubs override', async () => {
  332. const runtime = await runtimeWithFrame()
  333. // Defaults: an empty home level and parent/name joining.
  334. await expect(runtime.workspaces.listDirectory()).resolves.toMatchObject({ path: '/home/test', entries: [] })
  335. await expect(runtime.workspaces.listDirectory('/home/test')).resolves.toMatchObject({ path: '/home/test' })
  336. await expect(runtime.workspaces.createDirectory('/home/test', 'fresh')).resolves.toBe('/home/test/fresh')
  337. // The recorded signal seat mirrors the production face (undefined here;
  338. // cancellation tests pass and observe a real one).
  339. expect(runtime.workspaces.calls).toEqual([
  340. { method: 'listDirectory', args: [undefined, undefined] },
  341. { method: 'listDirectory', args: ['/home/test', undefined] },
  342. { method: 'createDirectory', args: ['/home/test', 'fresh'] },
  343. ])
  344. // Stubs replace the defaults like every sibling method.
  345. const listing = { path: '/x', home: '/x', crumbs: [], entries: [] }
  346. const listStub = vi.fn(() => Promise.resolve(listing as never))
  347. runtime.workspaces.stub('listDirectory', listStub)
  348. runtime.workspaces.stub('createDirectory', vi.fn(() => Promise.resolve('/x/made' as never)))
  349. const scan = new AbortController()
  350. await expect(runtime.workspaces.listDirectory('/x', scan.signal)).resolves.toBe(listing)
  351. // The stub receives the signal too, like the production face gives the wire.
  352. expect(listStub).toHaveBeenLastCalledWith('/x', scan.signal)
  353. await expect(runtime.workspaces.createDirectory('/x', 'made')).resolves.toBe('/x/made')
  354. await runtime.dispose()
  355. })
  356. })
  357. describe('feature mount and disposal', () => {
  358. it('mounts a plugin on a real fiber; dispose() cascades entries, declared children, and services', async () => {
  359. const runtime = await runtimeWithFrame()
  360. runtime.provide('layout', { openDetails: vi.fn() })
  361. const feature = await runtime.mount({
  362. inject: ['slots', 'layout'],
  363. apply: (ctx: typeof runtime.ctx) => {
  364. ctx.provide('feature-service', { ok: true })
  365. ctx.slots.register({
  366. name: 'trt.rows',
  367. id: 'row-1',
  368. children: { 'trt.rows.hole': { kind: 'single', scope: 'root' } },
  369. } as never, ((props: { renderSlot: (key: string, owner: object) => unknown }) =>
  370. <div data-testid="row">{props.renderSlot('trt.rows.hole', {}) as React.ReactNode}</div>) as never)
  371. },
  372. })
  373. const view = runtime.renderRoot()
  374. expect(view.getByTestId('row')).toBeTruthy()
  375. expect(runtime.ctx.get('feature-service')).toEqual({ ok: true })
  376. expect(runtime.slots.entries('trt.rows')).toHaveLength(1)
  377. await feature.dispose()
  378. await feature.dispose() // idempotent
  379. expect(runtime.slots.entries('trt.rows')).toHaveLength(0)
  380. expect(runtime.slots.spec('trt.rows.hole' as never)).toBeUndefined()
  381. expect(runtime.ctx.get('feature-service')).toBeUndefined()
  382. expect(view.queryByTestId('row')).toBeNull()
  383. await runtime.dispose()
  384. })
  385. it('mount fails loud on missing services instead of suspending forever', async () => {
  386. const runtime = await runtimeWithFrame()
  387. await expect(runtime.mount({ inject: ['slots', 'absent-service'], apply: () => {} }))
  388. .rejects.toThrow(/missing service\(s\) absent-service/)
  389. await runtime.dispose()
  390. })
  391. it('runtime dispose is idempotent, unmounts views, disposes mounted features, and clears persisted state', async () => {
  392. const runtime = await runtimeWithFrame()
  393. const feature = await runtime.mount({
  394. inject: ['slots'],
  395. apply: (ctx: typeof runtime.ctx) => { ctx.slots.register({ name: 'trt.panel' }, () => <b>p</b>) },
  396. })
  397. const view = runtime.renderRoot()
  398. expect(view.container.textContent).toContain('p')
  399. localStorage.setItem('trt.leftover', 'x')
  400. await runtime.dispose()
  401. expect(view.container.innerHTML).toBe('')
  402. expect(feature.fiber.uid).toBeNull()
  403. expect(localStorage.getItem('trt.leftover')).toBeNull()
  404. await runtime.dispose() // idempotent
  405. await expect(runtime.dispose()).resolves.toBeUndefined()
  406. })
  407. })
  408. describe('single-slot mounting (declare + renderSlot)', () => {
  409. it('renders one slot inside its data-slot wrapper and updates owner props in place', async () => {
  410. const runtime = await SlotTestRuntime.create()
  411. await runtime.declare({ 'trt.panel': { kind: 'single', scope: 'root' } })
  412. runtime.slots.register(
  413. { name: 'trt.panel' },
  414. ({ label }: { label?: string }) => <b data-testid="panel">{label ?? 'none'}</b>)
  415. const slot = runtime.renderSlot('trt.panel', { label: 'first' })
  416. expect(slot.container.getAttribute('data-slot')).toBe('trt.panel')
  417. expect(slot.view.getByTestId('panel').textContent).toBe('first')
  418. const panel = slot.view.getByTestId('panel')
  419. slot.update({ label: 'second' })
  420. expect(slot.view.getByTestId('panel').textContent).toBe('second')
  421. // In-place re-render: the element identity survived the owner flip.
  422. expect(slot.view.getByTestId('panel')).toBe(panel)
  423. await runtime.dispose()
  424. })
  425. it('views sibling slots of one tree separately and rejects undeclared keys', async () => {
  426. const runtime = await SlotTestRuntime.create()
  427. await runtime.declare({
  428. 'trt.panel': { kind: 'single', scope: 'root' },
  429. 'trt.rows': { kind: 'list', scope: 'root' },
  430. })
  431. runtime.slots.register({ name: 'trt.panel' }, () => <b>panel</b>)
  432. runtime.slots.register({ name: 'trt.rows', id: 'r1' }, () => <i>row</i>)
  433. const panel = runtime.renderSlot('trt.panel', {})
  434. const rows = runtime.renderSlot('trt.rows', {})
  435. expect(panel.container.textContent).toBe('panel')
  436. expect(rows.container.textContent).toBe('row')
  437. expect(() => runtime.renderSlot('trt.chat', {})).toThrow(/without declare\(\)/)
  438. await runtime.dispose()
  439. })
  440. it('folds class hashes and collapses svg internals in snapshots, leaving the live DOM alone', async () => {
  441. const runtime = await SlotTestRuntime.create()
  442. await runtime.declare({ 'trt.panel': { kind: 'single', scope: 'root' } })
  443. runtime.slots.register({ name: 'trt.panel' }, () => (
  444. <div className="_frame_a1b2c3 plain">
  445. <span className="_label_ff00aa">styled</span>
  446. <svg viewBox="0 0 16 16" aria-hidden="true">
  447. <path d="M0 0L16 16" fill="currentColor" />
  448. </svg>
  449. </div>
  450. ))
  451. const slot = runtime.renderSlot('trt.panel', {})
  452. expect(slot.container).toMatchSnapshot()
  453. // The serializer works on a clone: the live DOM keeps hashes and paths.
  454. expect(slot.container.querySelector('div')!.className).toBe('_frame_a1b2c3 plain')
  455. expect(slot.container.querySelector('svg path')).not.toBeNull()
  456. await runtime.dispose()
  457. })
  458. })
  459. describe('fixture session face', () => {
  460. it('fail-loud stubs name the missing verb; supplied overrides run instead', async () => {
  461. const runtime = await SlotTestRuntime.create()
  462. await runtime.sessions.add({ id: 's1' })
  463. const bare = runtime.sessions.behavior('s1')
  464. expect(() => bare.prompt()).toThrow(/prompt is not stubbed/)
  465. expect(() => bare.updateQueue()).toThrow(/updateQueue is not stubbed/)
  466. expect(() => bare.cancel()).toThrow(/cancel is not stubbed/)
  467. expect(() => bare.command()).toThrow(/command is not stubbed/)
  468. expect(() => bare.loadOlder()).toThrow(/loadOlder is not stubbed/)
  469. expect(() => bare.rename()).toThrow(/rename is not stubbed/)
  470. await runtime.dispose()
  471. })
  472. it('projections faces are identity-stable per key, read absent, and notify on set', async () => {
  473. const runtime = await SlotTestRuntime.create()
  474. await runtime.sessions.add({ id: 's1' })
  475. const session = runtime.sessions.behavior('s1')
  476. const face = session.projections.faceOf('todos')
  477. expect(session.projections.faceOf('todos')).toBe(face)
  478. expect(face.getSnapshot()).toBeUndefined()
  479. const seen: unknown[] = []
  480. const off = face.subscribe(() => { seen.push(face.getSnapshot()) })
  481. session.projections.set('todos', [1, 2])
  482. expect(seen).toEqual([[1, 2]])
  483. off()
  484. session.projections.set('todos', [3])
  485. expect(seen).toEqual([[1, 2]]) // unsubscribed
  486. // A never-subscribed key sets without listeners (the empty-notify arm).
  487. session.projections.set('untouched', 1)
  488. // The provide bundle hands the same store to the render side.
  489. const info = runtime.sessions.provideInfo('s1')!
  490. expect(info.projections?.faceOf('todos').getSnapshot()).toEqual([3])
  491. // A roster change rebuilds the ALREADY-materialized bundle eagerly
  492. // (production channel semantics: mounted entries must see the provider)
  493. // and skips never-materialized records (they pick the roster up lazily).
  494. await runtime.sessions.add({ id: 's-lazy' }, { current: false })
  495. const offProbe = runtime.sessions.provide({
  496. hooks: ['probe2'],
  497. resolve: () => ({ hooks: { probe2: { getSnapshot: () => 1, subscribe: () => () => {} } } }),
  498. })
  499. const rebuilt = runtime.sessions.provideInfo('s1')!
  500. expect(rebuilt).not.toBe(info)
  501. expect(rebuilt.hooks['probe2']).toBeDefined()
  502. offProbe()
  503. await runtime.dispose()
  504. })
  505. })
  506. describe('workspaces action face', () => {
  507. it('records every IWorkspaces verb with inert defaults and honors stubs', async () => {
  508. const runtime = await SlotTestRuntime.create()
  509. const ws = runtime.workspaces
  510. const created = await ws.create({ name: 'alpha' })
  511. expect(created.title).toBe('alpha')
  512. const registered = await ws.create({ path: '/tmp/beta' })
  513. expect(registered.path).toBe('/tmp/beta')
  514. await expect(ws.pickDirectory()).resolves.toBeNull()
  515. const renamed = await ws.rename('w1' as WorkspaceId, 'Renamed')
  516. expect(renamed.title).toBe('Renamed')
  517. await ws.delete('w1' as WorkspaceId)
  518. await ws.openPath('/proj/file.ts')
  519. const moved = await ws.insertSessionBefore('w1' as WorkspaceId, 's1' as SessionId, 's2' as SessionId)
  520. expect(moved.sessionIds).toEqual(['s1'])
  521. // Default archive mirrors the production effect: the id joins the list
  522. // state's archive set (features render against the same snapshot).
  523. await ws.archiveSession('s1' as SessionId)
  524. expect(ws.list.getSnapshot().archivedSessionIds).toEqual(['s1'])
  525. expect(ws.calls.map(c => c.method)).toEqual(
  526. ['create', 'create', 'pickDirectory', 'rename', 'delete', 'openPath', 'insertSessionBefore', 'archiveSession'])
  527. ws.stub('create', () => Promise.resolve({ workspaceId: 'ws-x', title: 'X', path: '/x', sessionIds: [] } as never))
  528. ws.stub('pickDirectory', () => Promise.resolve('/picked'))
  529. ws.stub('rename', () => Promise.resolve({ workspaceId: 'w1', title: 'S', path: '/s', sessionIds: [] } as never))
  530. ws.stub('delete', () => Promise.resolve())
  531. ws.stub('openPath', () => Promise.resolve())
  532. ws.stub('insertSessionBefore', () => Promise.resolve({ workspaceId: 'w1', title: '', path: '', sessionIds: [] } as never))
  533. ws.stub('archiveSession', () => Promise.resolve())
  534. expect((await ws.create({ name: 'y' })).title).toBe('X')
  535. await expect(ws.pickDirectory()).resolves.toBe('/picked')
  536. expect((await ws.rename('w1' as WorkspaceId, 'z')).title).toBe('S')
  537. await ws.delete('w1' as WorkspaceId)
  538. await ws.openPath('/other')
  539. expect((await ws.insertSessionBefore('w1' as WorkspaceId, 's1' as SessionId)).sessionIds).toEqual([])
  540. // The stub replaces the default set mutation: the set stays as-is.
  541. await ws.archiveSession('s2' as SessionId)
  542. expect(ws.list.getSnapshot().archivedSessionIds).toEqual(['s1'])
  543. await runtime.dispose()
  544. })
  545. })
  546. describe('single-slot mounting edge arms', () => {
  547. it('renderSlot fails loud after dispose and after an external unmount', async () => {
  548. const runtime = await SlotTestRuntime.create()
  549. await runtime.declare({ 'trt.panel': { kind: 'single', scope: 'root' } })
  550. runtime.slots.register({ name: 'trt.panel' }, () => <b>p</b>)
  551. runtime.renderSlot('trt.panel', {})
  552. // RTL cleanup empties the mounted tree behind the runtime's back: the
  553. // wrapper lookup names the state instead of returning a dead container.
  554. cleanup()
  555. expect(() => runtime.renderSlot('trt.panel', {})).toThrow(/rendered no wrapper/)
  556. await runtime.dispose()
  557. // After dispose the root registration is gone: the production boot-order
  558. // check fires before any wrapper lookup.
  559. expect(() => runtime.renderSlot('trt.panel', {})).toThrow(/'root' has no registration/)
  560. })
  561. it('serializes childless svg untouched next to scoped classes', async () => {
  562. const runtime = await SlotTestRuntime.create()
  563. await runtime.declare({ 'trt.panel': { kind: 'single', scope: 'root' } })
  564. runtime.slots.register({ name: 'trt.panel' }, () => (
  565. <div className="_frame_a1b2c3">
  566. <svg viewBox="0 0 1 1" aria-hidden="true" />
  567. </div>
  568. ))
  569. const slot = runtime.renderSlot('trt.panel', {})
  570. expect(slot.container).toMatchSnapshot()
  571. await runtime.dispose()
  572. })
  573. })