runtime.spec.tsx 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  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 { stubSettingsScope } from '../src/settings-scope.ts'
  11. import { cleanup } from '@testing-library/react'
  12. import { defineStore } from '@deepseek-ai/dsh-client-runtime/client'
  13. import type { SessionId, WorkspaceId } from '@deepseek-ai/dsh-client-runtime/client'
  14. import type { PropsRenderSlots, SessionStandardProps } from '@deepseek-ai/dsh-client-ui-slots'
  15. import { SlotTestRuntime } from '@deepseek-ai/dsh-client-test-runtime'
  16. declare module '@deepseek-ai/dsh-client-ui-slots' {
  17. interface SlotMap {
  18. 'trt.panel': { kind: 'single'; scope: 'root'; owner: { label?: string } }
  19. 'trt.chat': { kind: 'single'; scope: 'session' }
  20. 'trt.rows': { kind: 'list'; scope: 'root' }
  21. 'trt.rows.hole': { kind: 'single'; scope: 'root' }
  22. }
  23. }
  24. afterEach(cleanup)
  25. type FrameProps = PropsRenderSlots<'trt.panel' | 'trt.chat' | 'trt.rows'>
  26. /** Root frame declaring all three suite slots (render sites for each kind). */
  27. function Frame({ renderSlot, SessionProvider }: FrameProps) {
  28. return (
  29. <>
  30. {renderSlot('trt.panel', { label: 'from-owner' }, { fallback: <i>no panel</i> })}
  31. <SessionProvider empty={() => <i>no session</i>}>
  32. {() => renderSlot('trt.chat', {})}
  33. </SessionProvider>
  34. {renderSlot('trt.rows', {})}
  35. </>
  36. )
  37. }
  38. const CHILDREN = {
  39. 'trt.panel': { kind: 'single', scope: 'root' },
  40. 'trt.chat': { kind: 'single', scope: 'session' },
  41. 'trt.rows': { kind: 'list', scope: 'root' },
  42. } as const
  43. async function runtimeWithFrame() {
  44. const runtime = await SlotTestRuntime.create()
  45. await runtime.root.declare(CHILDREN, Frame)
  46. return runtime
  47. }
  48. describe('root declaration and rendering', () => {
  49. it('renders declared slots through the real renderer: fallback, then a live registration, then unload', async () => {
  50. const runtime = await runtimeWithFrame()
  51. const view = runtime.renderRoot()
  52. expect(view.container.textContent).toContain('no panel')
  53. let dispose = (): void => {}
  54. await runtime.flush() // no-op guard: flush outside mutations is safe
  55. await (async () => {
  56. dispose = runtime.slots.register(
  57. { name: 'trt.panel' },
  58. ({ label }: { label?: string }) => <b>panel:{label}</b>)
  59. await runtime.flush()
  60. })()
  61. expect(view.container.textContent).toContain('panel:from-owner')
  62. dispose()
  63. await runtime.flush()
  64. expect(view.container.textContent).toContain('no panel')
  65. await runtime.dispose()
  66. })
  67. it('fails loud when rendering with no root declaration (production boot-order check)', async () => {
  68. const runtime = await SlotTestRuntime.create()
  69. expect(() => runtime.renderRoot()).toThrow(/'root' has no registration/)
  70. await runtime.dispose()
  71. })
  72. })
  73. describe('sessions', () => {
  74. it('drives SessionProvider: empty state, current session, switch, live snapshot updates', async () => {
  75. const runtime = await runtimeWithFrame()
  76. runtime.slots.register({ name: 'trt.chat' }, (props: SessionStandardProps) => {
  77. const running = props.useSession(s => s.running)
  78. return <span>chat:{props.sessionId}:{String(running)}</span>
  79. })
  80. const view = runtime.renderRoot()
  81. expect(view.container.textContent).toContain('no session')
  82. await runtime.sessions.add({ id: 's1' })
  83. expect(view.container.textContent).toContain('chat:s1:false')
  84. await runtime.sessions.updateSnapshot('s1', (draft) => { draft.running = true })
  85. expect(view.container.textContent).toContain('chat:s1:true')
  86. await runtime.sessions.add({ id: 's2' }) // becomes current by default
  87. expect(view.container.textContent).toContain('chat:s2:false')
  88. await runtime.sessions.setCurrent(undefined)
  89. expect(view.container.textContent).toContain('no session')
  90. await runtime.sessions.setCurrent('s1')
  91. expect(view.container.textContent).toContain('chat:s1:true')
  92. await runtime.dispose()
  93. })
  94. it('add with current:false keeps the selection; unknown ids fail loud on the mutators', async () => {
  95. const runtime = await runtimeWithFrame()
  96. await runtime.sessions.add({ id: 's1' })
  97. await runtime.sessions.add({ id: 's2' }, { current: false })
  98. expect(runtime.sessions.list.getSnapshot().current).toBe('s1')
  99. expect(runtime.sessions.list.getSnapshot().ids).toEqual(['s1', 's2'])
  100. await expect(runtime.sessions.add({ id: 's1' })).rejects.toThrow(/already added/)
  101. await expect(runtime.sessions.setCurrent('ghost')).rejects.toThrow(/not added/)
  102. await expect(runtime.sessions.updateSnapshot('ghost', () => {})).rejects.toThrow(/not added/)
  103. await expect(runtime.sessions.remove('ghost')).rejects.toThrow(/not added/)
  104. expect(() => runtime.sessions.behavior('ghost')).toThrow(/not added/)
  105. await runtime.dispose()
  106. })
  107. it('mints REAL-tag scopes lazily and resolves them through the production scopeOf; bindings expose the behavior face', async () => {
  108. const runtime = await runtimeWithFrame()
  109. const prompt = vi.fn()
  110. await runtime.sessions.add({ id: 's1', session: { prompt } })
  111. expect(runtime.sessions.provideInfo('ghost')).toBeUndefined()
  112. expect(runtime.sessions.scope('ghost')).toBeUndefined()
  113. expect(runtime.sessions.binding('ghost')).toBeUndefined()
  114. const scope = runtime.sessions.scope('s1')!
  115. expect(runtime.sessions.scope('s1')).toBe(scope) // stable per session
  116. expect(runtime.sessions.scopeOf(scope)).toBe('s1')
  117. expect(runtime.sessions.scopeOf(runtime.ctx)).toBeUndefined()
  118. // sessionOf resolves the behavior face off the scope tag.
  119. expect(runtime.sessions.sessionOf(scope)).toBe(runtime.sessions.behavior('s1'))
  120. expect(runtime.sessions.sessionOf(runtime.ctx)).toBeUndefined()
  121. const binding = runtime.sessions.binding('s1')!
  122. expect(binding.sessionId).toBe('s1')
  123. expect(binding.ctx).toBe(scope)
  124. ;(binding.session as { prompt: () => void }).prompt()
  125. expect(prompt).toHaveBeenCalledOnce()
  126. expect(runtime.sessions.behavior('s1')).toBe(binding.session)
  127. // The binding's session doubles as the conversation observable face.
  128. expect((binding.session as { getSnapshot(): { sessionId: string } }).getSnapshot().sessionId).toBe('s1')
  129. // A scoped service resolves through the scope ctx (scope-addressed pattern).
  130. runtime.provide('probe', { hello: 'world' })
  131. expect(scope.get('probe')).toEqual({ hello: 'world' })
  132. await runtime.dispose()
  133. })
  134. it('materializes provide bundles: built-in session hook, custom providers, no-session projection', async () => {
  135. const runtime = await runtimeWithFrame()
  136. await runtime.sessions.add({ id: 's1' })
  137. const info = runtime.sessions.provideInfo('s1')!
  138. expect(info.sessionId).toBe('s1')
  139. expect(info.hooks['session']).toBeDefined() // the built-in useSession source
  140. expect(runtime.sessions.provideInfo('s1')).toBe(info) // identity-stable
  141. // A feature provider (the ui-conversation input pattern): declared names
  142. // materialize per session and land in the no-session roster as undefined.
  143. const off = runtime.sessions.provide({
  144. hooks: ['probe'],
  145. props: ['probeActions'],
  146. resolve: binding => ({
  147. hooks: { probe: { getSnapshot: () => binding.sessionId, subscribe: () => () => {} } },
  148. props: { probeActions: { poke: () => {} } },
  149. }),
  150. })
  151. const enriched = runtime.sessions.provideInfo('s1')!
  152. expect(enriched.hooks['probe']?.getSnapshot()).toBe('s1')
  153. expect(enriched.props['probeActions']).toBeDefined()
  154. const maybe = runtime.sessions.maybeProvideInfo(undefined)
  155. expect(maybe.sessionId).toBeUndefined()
  156. expect(Object.keys(maybe.hooks)).toEqual(['session', 'probe'])
  157. expect(runtime.sessions.maybeProvideInfo('s1')).toBe(runtime.sessions.provideInfo('s1'))
  158. expect(runtime.sessions.maybeProvideInfo('ghost').sessionId).toBeUndefined()
  159. // Misdeclared providers fail loud AT REGISTRATION (the production
  160. // channel rebuilds live bundles eagerly and rolls the roster back):
  161. // missing hook, missing prop, duplicate hook, duplicate prop.
  162. expect(() => runtime.sessions.provide({ hooks: ['void'], resolve: () => ({}) }))
  163. .toThrow(/missing hook "void"/)
  164. expect(() => runtime.sessions.provide({ props: ['void'], resolve: () => ({}) }))
  165. .toThrow(/missing prop "void"/)
  166. expect(() => runtime.sessions.provide({
  167. hooks: ['session'],
  168. resolve: () => ({ hooks: { session: { getSnapshot: () => 0, subscribe: () => () => {} } } }),
  169. })).toThrow(/duplicate hook "session"/)
  170. const propA = runtime.sessions.provide({ props: ['twice'], resolve: () => ({ props: { twice: 1 } }) })
  171. expect(() => runtime.sessions.provide({ props: ['twice'], resolve: () => ({ props: { twice: 2 } }) }))
  172. .toThrow(/duplicate prop "twice"/)
  173. propA()
  174. // The rejected registrations rolled back: the roster still materializes.
  175. expect(runtime.sessions.provideInfo('s1')).toBeDefined()
  176. off()
  177. off() // disposer is idempotent
  178. expect(Object.keys(runtime.sessions.maybeProvideInfo(undefined).hooks)).toEqual(['session'])
  179. await runtime.dispose()
  180. })
  181. it('records service-face calls and retains catalog addresses only for addressed selection', async () => {
  182. const runtime = await runtimeWithFrame()
  183. await runtime.sessions.add({ id: 's1' })
  184. await runtime.sessions.add({ id: 's2' })
  185. const address = {
  186. parentSessionId: 's2' as SessionId,
  187. childSessionId: 's1' as SessionId,
  188. mode: 'continuable' as const,
  189. }
  190. runtime.sessions.openSubagent(address)
  191. await runtime.flush()
  192. expect(runtime.sessions.list.getSnapshot()).toMatchObject({ current: 's1', currentAddress: address })
  193. expect(runtime.sessions.subagentAddress('s1' as SessionId)).toEqual(address)
  194. expect(runtime.sessions.subagentAddress('s2' as SessionId)).toBeUndefined()
  195. await runtime.sessions.updateSummary('s1', { displayTitle: 'renamed', running: true })
  196. expect(runtime.sessions.list.getSnapshot().byId['s1' as SessionId])
  197. .toMatchObject({ displayTitle: 'renamed', running: true })
  198. runtime.sessions.setSubagentCatalogOpen('s2' as SessionId, true)
  199. await runtime.sessions.refreshSubagents('s2' as SessionId)
  200. // The confirmed-switch write-back lands on the row it names and ignores
  201. // one the fixture never added, exactly as production's list upsert does.
  202. runtime.sessions.noteAgentPreset('s1' as SessionId, 'minimal')
  203. runtime.sessions.noteAgentPreset('missing' as SessionId, 'minimal')
  204. await runtime.flush()
  205. expect(runtime.sessions.list.getSnapshot().byId['s1' as SessionId])
  206. .toMatchObject({ agentPreset: 'minimal' })
  207. runtime.sessions.open('s1' as SessionId)
  208. await runtime.flush()
  209. expect(runtime.sessions.list.getSnapshot().current).toBe('s1')
  210. expect(runtime.sessions.list.getSnapshot().currentAddress).toBeUndefined()
  211. runtime.sessions.clear()
  212. await runtime.flush()
  213. expect(runtime.sessions.list.getSnapshot().current).toBeUndefined()
  214. await expect(runtime.sessions.fork({
  215. sessionId: 's1' as SessionId, atSeq: 7, increaseTitle: true,
  216. })).resolves.toBe('s1')
  217. expect(runtime.sessions.calls).toEqual([
  218. { method: 'openSubagent', args: [address] },
  219. { method: 'setSubagentCatalogOpen', args: ['s2', true] },
  220. { method: 'refreshSubagents', args: ['s2'] },
  221. { method: 'open', args: ['s1'] },
  222. { method: 'clear', args: [] },
  223. { method: 'fork', args: [{ sessionId: 's1', atSeq: 7, increaseTitle: true }] },
  224. ])
  225. await runtime.dispose()
  226. })
  227. it('answers search with an empty page until a scenario declares hits, recording every call', async () => {
  228. const runtime = await runtimeWithFrame()
  229. await runtime.sessions.add({ id: 's1' })
  230. const signal = new AbortController().signal
  231. expect(runtime.sessions.searchResultLimit).toBeGreaterThan(0)
  232. await expect(runtime.sessions.search('marker', signal))
  233. .resolves.toEqual({ ok: true, value: { items: [], hasMore: false } })
  234. runtime.sessions.stubSearch(query => ({
  235. items: [{ sessionId: 's1' as SessionId, snippet: `hit: ${query}` }],
  236. hasMore: true,
  237. }))
  238. await expect(runtime.sessions.search('marker', signal)).resolves.toEqual({
  239. ok: true,
  240. value: { items: [{ sessionId: 's1', snippet: 'hit: marker' }], hasMore: true },
  241. })
  242. expect(runtime.sessions.calls).toEqual([
  243. { method: 'search', args: ['marker', signal] },
  244. { method: 'search', args: ['marker', signal] },
  245. ])
  246. await runtime.dispose()
  247. })
  248. })
  249. describe('stores', () => {
  250. const createSuiteStore = () => defineStore({
  251. init: () => ({ note: '' }),
  252. persist: 'trt.store',
  253. actions: { setNote: (d, note: string) => { d.note = note } },
  254. })
  255. it('resolves per-session instances via the host face: shared identity, isolation, action-driven re-render', async () => {
  256. const runtime = await runtimeWithFrame()
  257. const handle = createSuiteStore()
  258. runtime.slots.register(
  259. { name: 'trt.chat', store: handle },
  260. (props: SessionStandardProps & { useStore: <S>(sel: (s: { note: string }) => S) => S }) =>
  261. <span>note:{props.useStore(s => s.note)}</span>)
  262. const view = runtime.renderRoot()
  263. await runtime.sessions.add({ id: 's1' })
  264. expect(() => runtime.storeOf('trt.panel')).toThrow(/no registration/)
  265. const store = runtime.storeOf('trt.chat', 's1')
  266. await runtime.flush()
  267. ;(store.actions['setNote'] as (note: string) => void)('hello')
  268. await runtime.flush()
  269. expect(view.container.textContent).toContain('note:hello')
  270. expect(runtime.storeOf('trt.chat', 's1')).toBe(store) // cached per scope key
  271. await runtime.sessions.add({ id: 's2' })
  272. const other = runtime.storeOf('trt.chat', 's2')
  273. expect(other).not.toBe(store)
  274. expect(other.getSnapshot()).toEqual({ note: '' })
  275. await runtime.dispose()
  276. })
  277. it('storeOf guards: before renderRoot, and for storeless entries', async () => {
  278. const runtime = await runtimeWithFrame()
  279. runtime.slots.register({ name: 'trt.panel' }, () => null)
  280. expect(() => runtime.storeOf('trt.panel')).toThrow(/before renderRoot/)
  281. runtime.renderRoot()
  282. expect(() => runtime.storeOf('trt.panel')).toThrow(/declares no store/)
  283. await runtime.dispose()
  284. })
  285. it('remove() prunes the session store scope: persisted state clears, a re-added session starts fresh', async () => {
  286. const runtime = await runtimeWithFrame()
  287. const handle = createSuiteStore()
  288. runtime.slots.register({ name: 'trt.chat', store: handle }, () => null)
  289. runtime.renderRoot()
  290. await runtime.sessions.add({ id: 's1' })
  291. const doomed = runtime.storeOf('trt.chat', 's1')
  292. ;(doomed.actions['setNote'] as (note: string) => void)('buried')
  293. expect(localStorage.getItem('trt.store.s1')).not.toBeNull()
  294. await runtime.sessions.remove('s1')
  295. expect(localStorage.getItem('trt.store.s1')).toBeNull()
  296. expect(runtime.sessions.list.getSnapshot().ids).toEqual([])
  297. expect(runtime.sessions.provideInfo('s1')).toBeUndefined()
  298. await runtime.sessions.add({ id: 's1' })
  299. const reborn = runtime.storeOf('trt.chat', 's1')
  300. expect(reborn).not.toBe(doomed)
  301. expect(reborn.getSnapshot()).toEqual({ note: '' })
  302. await runtime.dispose()
  303. })
  304. it('remove() also disposes a minted scope fiber; removing a non-current session keeps the selection', async () => {
  305. const runtime = await runtimeWithFrame()
  306. await runtime.sessions.add({ id: 's1' })
  307. await runtime.sessions.add({ id: 's2' }, { current: false })
  308. const scope = runtime.sessions.scope('s1')!
  309. await runtime.sessions.remove('s2')
  310. expect(runtime.sessions.list.getSnapshot().current).toBe('s1')
  311. await runtime.sessions.remove('s1')
  312. expect(scope.fiber.uid).toBeNull() // disposed fiber loses its uid
  313. expect(runtime.sessions.list.getSnapshot().current).toBeUndefined()
  314. await runtime.dispose()
  315. })
  316. })
  317. describe('workspaces', () => {
  318. it('feeds useWorkspaces and records/stubs intent actions', async () => {
  319. const runtime = await runtimeWithFrame()
  320. runtime.slots.register(
  321. { name: 'trt.panel' },
  322. (props: { useWorkspaces: <S>(sel: (s: { phase: string }) => S) => S }) =>
  323. <span>ws:{props.useWorkspaces(s => s.phase)}</span>)
  324. const view = runtime.renderRoot()
  325. expect(view.container.textContent).toContain('ws:ready')
  326. await runtime.workspaces.update((draft) => { draft.phase = 'pending' })
  327. expect(view.container.textContent).toContain('ws:pending')
  328. runtime.workspaces.startSession('w1' as WorkspaceId)
  329. await expect(runtime.workspaces.connectWorkspace('w2' as WorkspaceId)).resolves.toBe('session-of-w2')
  330. expect(runtime.workspaces.calls).toEqual([
  331. { method: 'startSession', args: ['w1'] },
  332. { method: 'connectWorkspace', args: ['w2'] },
  333. ])
  334. const stub = vi.fn(() => Promise.resolve('other' as never))
  335. runtime.workspaces.stub('connectWorkspace', stub)
  336. await expect(runtime.workspaces.connectWorkspace('w3' as WorkspaceId)).resolves.toBe('other')
  337. expect(stub).toHaveBeenCalledOnce()
  338. await runtime.dispose()
  339. })
  340. it('records the browse calls: listDirectory serves an empty home, createDirectory joins, stubs override', async () => {
  341. const runtime = await runtimeWithFrame()
  342. // Defaults: an empty home level and parent/name joining.
  343. await expect(runtime.workspaces.listDirectory()).resolves.toMatchObject({ path: '/home/test', entries: [] })
  344. await expect(runtime.workspaces.listDirectory('/home/test')).resolves.toMatchObject({ path: '/home/test' })
  345. await expect(runtime.workspaces.createDirectory('/home/test', 'fresh')).resolves.toBe('/home/test/fresh')
  346. // The recorded signal seat mirrors the production face (undefined here;
  347. // cancellation tests pass and observe a real one).
  348. expect(runtime.workspaces.calls).toEqual([
  349. { method: 'listDirectory', args: [undefined, undefined] },
  350. { method: 'listDirectory', args: ['/home/test', undefined] },
  351. { method: 'createDirectory', args: ['/home/test', 'fresh'] },
  352. ])
  353. // Stubs replace the defaults like every sibling method.
  354. const listing = { path: '/x', home: '/x', crumbs: [], entries: [] }
  355. const listStub = vi.fn(() => Promise.resolve(listing as never))
  356. runtime.workspaces.stub('listDirectory', listStub)
  357. runtime.workspaces.stub('createDirectory', vi.fn(() => Promise.resolve('/x/made' as never)))
  358. const scan = new AbortController()
  359. await expect(runtime.workspaces.listDirectory('/x', scan.signal)).resolves.toBe(listing)
  360. // The stub receives the signal too, like the production face gives the wire.
  361. expect(listStub).toHaveBeenLastCalledWith('/x', scan.signal)
  362. await expect(runtime.workspaces.createDirectory('/x', 'made')).resolves.toBe('/x/made')
  363. await runtime.dispose()
  364. })
  365. })
  366. describe('feature mount and disposal', () => {
  367. it('mounts a plugin on a real fiber; dispose() cascades entries, declared children, and services', async () => {
  368. const runtime = await runtimeWithFrame()
  369. runtime.provide('layout', { openDetails: vi.fn() })
  370. const feature = await runtime.mount({
  371. inject: ['slots', 'layout'],
  372. apply: (ctx: typeof runtime.ctx) => {
  373. ctx.provide('feature-service', { ok: true })
  374. ctx.slots.register({
  375. name: 'trt.rows',
  376. id: 'row-1',
  377. children: { 'trt.rows.hole': { kind: 'single', scope: 'root' } },
  378. } as never, ((props: { renderSlot: (key: string, owner: object) => unknown }) =>
  379. <div data-testid="row">{props.renderSlot('trt.rows.hole', {}) as React.ReactNode}</div>) as never)
  380. },
  381. })
  382. const view = runtime.renderRoot()
  383. expect(view.getByTestId('row')).toBeTruthy()
  384. expect(runtime.ctx.get('feature-service')).toEqual({ ok: true })
  385. expect(runtime.slots.entries('trt.rows')).toHaveLength(1)
  386. await feature.dispose()
  387. await feature.dispose() // idempotent
  388. expect(runtime.slots.entries('trt.rows')).toHaveLength(0)
  389. expect(runtime.slots.spec('trt.rows.hole')).toBeUndefined()
  390. expect(runtime.ctx.get('feature-service')).toBeUndefined()
  391. expect(view.queryByTestId('row')).toBeNull()
  392. await runtime.dispose()
  393. })
  394. it('mount fails loud on missing services instead of suspending forever', async () => {
  395. const runtime = await runtimeWithFrame()
  396. await expect(runtime.mount({ inject: ['slots', 'absent-service'], apply: () => {} }))
  397. .rejects.toThrow(/missing service\(s\) absent-service/)
  398. await runtime.dispose()
  399. })
  400. it('runtime dispose is idempotent, unmounts views, disposes mounted features, and clears persisted state', async () => {
  401. const runtime = await runtimeWithFrame()
  402. const feature = await runtime.mount({
  403. inject: ['slots'],
  404. apply: (ctx: typeof runtime.ctx) => { ctx.slots.register({ name: 'trt.panel' }, () => <b>p</b>) },
  405. })
  406. const view = runtime.renderRoot()
  407. expect(view.container.textContent).toContain('p')
  408. localStorage.setItem('trt.leftover', 'x')
  409. await runtime.dispose()
  410. expect(view.container.innerHTML).toBe('')
  411. expect(feature.fiber.uid).toBeNull()
  412. expect(localStorage.getItem('trt.leftover')).toBeNull()
  413. await runtime.dispose() // idempotent
  414. await expect(runtime.dispose()).resolves.toBeUndefined()
  415. })
  416. })
  417. describe('single-slot mounting (declare + renderSlot)', () => {
  418. it('renders one slot inside its data-slot wrapper and updates owner props in place', async () => {
  419. const runtime = await SlotTestRuntime.create()
  420. await runtime.declare({ 'trt.panel': { kind: 'single', scope: 'root' } })
  421. runtime.slots.register(
  422. { name: 'trt.panel' },
  423. ({ label }: { label?: string }) => <b data-testid="panel">{label ?? 'none'}</b>)
  424. const slot = runtime.renderSlot('trt.panel', { label: 'first' })
  425. expect(slot.container.getAttribute('data-slot')).toBe('trt.panel')
  426. expect(slot.view.getByTestId('panel').textContent).toBe('first')
  427. const panel = slot.view.getByTestId('panel')
  428. slot.update({ label: 'second' })
  429. expect(slot.view.getByTestId('panel').textContent).toBe('second')
  430. // In-place re-render: the element identity survived the owner flip.
  431. expect(slot.view.getByTestId('panel')).toBe(panel)
  432. await runtime.dispose()
  433. })
  434. it('views sibling slots of one tree separately and rejects undeclared keys', async () => {
  435. const runtime = await SlotTestRuntime.create()
  436. await runtime.declare({
  437. 'trt.panel': { kind: 'single', scope: 'root' },
  438. 'trt.rows': { kind: 'list', scope: 'root' },
  439. })
  440. runtime.slots.register({ name: 'trt.panel' }, () => <b>panel</b>)
  441. runtime.slots.register({ name: 'trt.rows', id: 'r1' }, () => <i>row</i>)
  442. const panel = runtime.renderSlot('trt.panel', {})
  443. const rows = runtime.renderSlot('trt.rows', {})
  444. expect(panel.container.textContent).toBe('panel')
  445. expect(rows.container.textContent).toBe('row')
  446. expect(() => runtime.renderSlot('trt.chat', {})).toThrow(/without declare\(\)/)
  447. await runtime.dispose()
  448. })
  449. it('folds class hashes and collapses svg internals in snapshots, leaving the live DOM alone', async () => {
  450. const runtime = await SlotTestRuntime.create()
  451. await runtime.declare({ 'trt.panel': { kind: 'single', scope: 'root' } })
  452. runtime.slots.register({ name: 'trt.panel' }, () => (
  453. <div className="_frame_a1b2c3 plain">
  454. <span className="_label_ff00aa">styled</span>
  455. <svg viewBox="0 0 16 16" aria-hidden="true">
  456. <path d="M0 0L16 16" fill="currentColor" />
  457. </svg>
  458. </div>
  459. ))
  460. const slot = runtime.renderSlot('trt.panel', {})
  461. expect(slot.container).toMatchSnapshot()
  462. // The serializer works on a clone: the live DOM keeps hashes and paths.
  463. expect(slot.container.querySelector('div')!.className).toBe('_frame_a1b2c3 plain')
  464. expect(slot.container.querySelector('svg path')).not.toBeNull()
  465. await runtime.dispose()
  466. })
  467. })
  468. describe('fixture session face', () => {
  469. it('fail-loud stubs name the missing verb; supplied overrides run instead', async () => {
  470. const runtime = await SlotTestRuntime.create()
  471. await runtime.sessions.add({ id: 's1' })
  472. const bare = runtime.sessions.behavior('s1')
  473. expect(() => bare.prompt()).toThrow(/prompt is not stubbed/)
  474. expect(() => bare.readAttachment('att-1' as Parameters<typeof bare.readAttachment>[0])).toThrow(/readAttachment is not stubbed/)
  475. expect(() => bare.updateQueue()).toThrow(/updateQueue is not stubbed/)
  476. expect(() => bare.cancel()).toThrow(/cancel is not stubbed/)
  477. expect(() => bare.command()).toThrow(/command is not stubbed/)
  478. expect(() => bare.loadOlder()).toThrow(/loadOlder is not stubbed/)
  479. expect(() => bare.rename()).toThrow(/rename is not stubbed/)
  480. await runtime.dispose()
  481. })
  482. it('projections faces are identity-stable per key, read absent, and notify on set', async () => {
  483. const runtime = await SlotTestRuntime.create()
  484. await runtime.sessions.add({ id: 's1' })
  485. const session = runtime.sessions.behavior('s1')
  486. const face = session.projections.faceOf('todos')
  487. expect(session.projections.faceOf('todos')).toBe(face)
  488. expect(face.getSnapshot()).toBeUndefined()
  489. const seen: unknown[] = []
  490. const off = face.subscribe(() => { seen.push(face.getSnapshot()) })
  491. session.projections.set('todos', [1, 2])
  492. expect(seen).toEqual([[1, 2]])
  493. off()
  494. session.projections.set('todos', [3])
  495. expect(seen).toEqual([[1, 2]]) // unsubscribed
  496. // A never-subscribed key sets without listeners (the empty-notify arm).
  497. session.projections.set('untouched', 1)
  498. // The provide bundle hands the same store to the render side.
  499. const info = runtime.sessions.provideInfo('s1')!
  500. expect(info.projections?.faceOf('todos').getSnapshot()).toEqual([3])
  501. // A roster change rebuilds the ALREADY-materialized bundle eagerly
  502. // (production channel semantics: mounted entries must see the provider)
  503. // and skips never-materialized records (they pick the roster up lazily).
  504. await runtime.sessions.add({ id: 's-lazy' }, { current: false })
  505. const offProbe = runtime.sessions.provide({
  506. hooks: ['probe2'],
  507. resolve: () => ({ hooks: { probe2: { getSnapshot: () => 1, subscribe: () => () => {} } } }),
  508. })
  509. const rebuilt = runtime.sessions.provideInfo('s1')!
  510. expect(rebuilt).not.toBe(info)
  511. expect(rebuilt.hooks['probe2']).toBeDefined()
  512. offProbe()
  513. await runtime.dispose()
  514. })
  515. })
  516. describe('workspaces action face', () => {
  517. it('records every IWorkspaces verb with inert defaults and honors stubs', async () => {
  518. const runtime = await SlotTestRuntime.create()
  519. const ws = runtime.workspaces
  520. const created = await ws.create({ path: '/tmp/alpha' })
  521. expect(created.title).toBe('/tmp/alpha')
  522. const registered = await ws.create({ path: '/tmp/beta' })
  523. expect(registered.path).toBe('/tmp/beta')
  524. await expect(ws.pickDirectory()).resolves.toBeNull()
  525. const renamed = await ws.rename('w1' as WorkspaceId, 'Renamed')
  526. expect(renamed.title).toBe('Renamed')
  527. await ws.delete('w1' as WorkspaceId)
  528. await ws.openPath('/proj/file.ts')
  529. const moved = await ws.insertSessionBefore('w1' as WorkspaceId, 's1' as SessionId, 's2' as SessionId)
  530. expect(moved.sessionIds).toEqual(['s1'])
  531. // Default archive mirrors the production effect: the id joins the list
  532. // state's archive set (features render against the same snapshot).
  533. await ws.archiveSession('s1' as SessionId)
  534. expect(ws.list.getSnapshot().archivedSessionIds).toEqual(['s1'])
  535. expect(ws.calls.map(c => c.method)).toEqual(
  536. ['create', 'create', 'pickDirectory', 'rename', 'delete', 'openPath', 'insertSessionBefore', 'archiveSession'])
  537. ws.stub('create', () => Promise.resolve({ workspaceId: 'ws-x', title: 'X', path: '/x', sessionIds: [] } as never))
  538. ws.stub('pickDirectory', () => Promise.resolve('/picked'))
  539. ws.stub('rename', () => Promise.resolve({ workspaceId: 'w1', title: 'S', path: '/s', sessionIds: [] } as never))
  540. ws.stub('delete', () => Promise.resolve())
  541. ws.stub('openPath', () => Promise.resolve())
  542. ws.stub('insertSessionBefore', () => Promise.resolve({ workspaceId: 'w1', title: '', path: '', sessionIds: [] } as never))
  543. ws.stub('archiveSession', () => Promise.resolve())
  544. expect((await ws.create({ path: '/y' })).title).toBe('X')
  545. await expect(ws.pickDirectory()).resolves.toBe('/picked')
  546. expect((await ws.rename('w1' as WorkspaceId, 'z')).title).toBe('S')
  547. await ws.delete('w1' as WorkspaceId)
  548. await ws.openPath('/other')
  549. expect((await ws.insertSessionBefore('w1' as WorkspaceId, 's1' as SessionId)).sessionIds).toEqual([])
  550. // The stub replaces the default set mutation: the set stays as-is.
  551. await ws.archiveSession('s2' as SessionId)
  552. expect(ws.list.getSnapshot().archivedSessionIds).toEqual(['s1'])
  553. await runtime.dispose()
  554. })
  555. })
  556. describe('single-slot mounting edge arms', () => {
  557. it('renderSlot fails loud after dispose and after an external unmount', async () => {
  558. const runtime = await SlotTestRuntime.create()
  559. await runtime.declare({ 'trt.panel': { kind: 'single', scope: 'root' } })
  560. runtime.slots.register({ name: 'trt.panel' }, () => <b>p</b>)
  561. runtime.renderSlot('trt.panel', {})
  562. // RTL cleanup empties the mounted tree behind the runtime's back: the
  563. // wrapper lookup names the state instead of returning a dead container.
  564. cleanup()
  565. expect(() => runtime.renderSlot('trt.panel', {})).toThrow(/rendered no wrapper/)
  566. await runtime.dispose()
  567. // After dispose the root registration is gone: the production boot-order
  568. // check fires before any wrapper lookup.
  569. expect(() => runtime.renderSlot('trt.panel', {})).toThrow(/'root' has no registration/)
  570. })
  571. it('serializes childless svg untouched next to scoped classes', async () => {
  572. const runtime = await SlotTestRuntime.create()
  573. await runtime.declare({ 'trt.panel': { kind: 'single', scope: 'root' } })
  574. runtime.slots.register({ name: 'trt.panel' }, () => (
  575. <div className="_frame_a1b2c3">
  576. <svg viewBox="0 0 1 1" aria-hidden="true" />
  577. </div>
  578. ))
  579. const slot = runtime.renderSlot('trt.panel', {})
  580. expect(slot.container).toMatchSnapshot()
  581. await runtime.dispose()
  582. })
  583. })
  584. describe('stubbed settings scope', () => {
  585. it('records both write kinds and publishes a Host acceptance to its listeners', async () => {
  586. const host = stubSettingsScope<{ preference: string }>()
  587. let notified = 0
  588. const stop = host.scope.subscribe(() => { notified += 1 })
  589. expect(host.listenerCount()).toBe(1)
  590. expect(host.scope.getSnapshot()).toMatchObject({
  591. status: 'loading', base: undefined, user: undefined,
  592. })
  593. await host.scope.set('preference', 'dark')
  594. await host.scope.unset('preference')
  595. host.publish({
  596. status: 'ready',
  597. value: { preference: 'system' },
  598. base: { preference: 'system' },
  599. revision: 2,
  600. writable: true,
  601. })
  602. expect(host.set).toHaveBeenCalledWith('preference', 'dark')
  603. expect(host.unset).toHaveBeenCalledWith('preference')
  604. expect(notified).toBe(1)
  605. expect(host.scope.getSnapshot()).toMatchObject({ status: 'ready', revision: 2, writable: true })
  606. stop()
  607. expect(host.listenerCount()).toBe(0)
  608. })
  609. })