runtime.client.spec.tsx 26 KB

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