session-provider.spec.tsx 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. // @vitest-environment jsdom
  2. /**
  3. * SessionProvider behavior account (render-prop form, framework-wired):
  4. * empty/body branching off the host's current-session source, key={sessionId}
  5. * remount semantics, and cell delivery observed through a session slot's
  6. * standard kit — never through the internal context objects (BindingContext
  7. * does not leave the package).
  8. */
  9. import { useEffect, useRef } from 'react'
  10. import { describe, expect, it, vi } from 'vitest'
  11. import { act, render } from '@testing-library/react'
  12. import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots'
  13. import {
  14. createSlotRenderer, SessionProvider,
  15. type SessionCell, type SlotRendererHost,
  16. } from '@deepseek-ai/dsh-client-web-react'
  17. function observable<T>(initial: T) {
  18. let value = initial
  19. const subs = new Set<() => void>()
  20. return {
  21. getSnapshot: () => value,
  22. subscribe: (fn: () => void) => { subs.add(fn); return () => { subs.delete(fn) } },
  23. set: (next: T) => { value = next; for (const fn of [...subs]) fn() },
  24. }
  25. }
  26. /**
  27. * Minimal host: SessionProvider only reads sessions.current/cell, but it must
  28. * render inside the renderer tree (HostContext), so the harness mounts a real
  29. * root entry whose body is the test's render-prop provider.
  30. */
  31. function makeHost(bodies: { root: (rp: (key: string, owner: object) => React.ReactNode) => React.ReactNode }) {
  32. const current = observable<string | undefined>(undefined)
  33. const cells = new Map<string, SessionCell>()
  34. const sessionEntries: StoredEntry[] = []
  35. const rootEntry: StoredEntry = {
  36. component: (props: { renderSlot: (key: string, owner: object) => React.ReactNode }) =>
  37. <>{bodies.root(props.renderSlot)}</>,
  38. options: {},
  39. children: { 'k.session': { kind: 'single', scope: 'session' } },
  40. }
  41. const host: SlotRendererHost = {
  42. subscribe: () => () => {},
  43. getVersion: () => 0,
  44. entriesOf: (key) => key === 'root' ? [rootEntry] : sessionEntries,
  45. specOf: (key) => key === 'k.session' ? { kind: 'single', scope: 'session' } : undefined,
  46. isLive: () => true,
  47. storeOf: () => undefined,
  48. sessions: {
  49. list: observable<unknown>({ ids: [] }),
  50. current,
  51. cell: (id) => cells.get(id),
  52. },
  53. }
  54. return {
  55. host,
  56. current,
  57. addSession: (id: string) => {
  58. // Bare source per cell (identity-stable): the machinery binds useSession from it.
  59. const cell: SessionCell = {
  60. sessionId: id,
  61. session: { getSnapshot: () => ({ sid: id }), subscribe: () => () => {} },
  62. }
  63. cells.set(id, cell)
  64. return cell
  65. },
  66. registerSession: (entry: StoredEntry) => { sessionEntries.push(entry) },
  67. }
  68. }
  69. describe('SessionProvider', () => {
  70. it('renders empty without a current session, switches to the body on select, falls back on an unresolvable id', () => {
  71. const h = makeHost({
  72. root: () => (
  73. <SessionProvider empty={() => <span>empty</span>}>
  74. {(id) => <div data-testid="body">{id}</div>}
  75. </SessionProvider>
  76. ),
  77. })
  78. h.addSession('s1')
  79. const view = render(<>{createSlotRenderer().renderRoot(h.host, {})}</>)
  80. expect(view.container.textContent).toBe('empty')
  81. act(() => { h.current.set('s1') })
  82. expect(view.container.textContent).toBe('s1')
  83. act(() => { h.current.set('ghost') }) // listed nowhere: cell() misses
  84. expect(view.container.textContent).toBe('empty')
  85. })
  86. it('renders null empty state when the empty prop is omitted', () => {
  87. const h = makeHost({
  88. root: () => <SessionProvider>{(id) => <b>{id}</b>}</SessionProvider>,
  89. })
  90. const view = render(<>{createSlotRenderer().renderRoot(h.host, {})}</>)
  91. expect(view.container.textContent).toBe('')
  92. })
  93. it('remounts the body on session switch (key semantics) but not on unrelated re-renders', () => {
  94. let mounts = 0
  95. function Body({ id }: { id: string }) {
  96. const mounted = useRef(false)
  97. useEffect(() => {
  98. /* v8 ignore next -- strict-mode double-invoke guard, not a branch under test */
  99. if (!mounted.current) { mounted.current = true; mounts += 1 }
  100. }, [])
  101. return <div>{id}</div>
  102. }
  103. const h = makeHost({
  104. root: () => <SessionProvider>{(id) => <Body id={id} />}</SessionProvider>,
  105. })
  106. h.addSession('s1')
  107. h.addSession('s2')
  108. const view = render(<>{createSlotRenderer().renderRoot(h.host, {})}</>)
  109. act(() => { h.current.set('s1') })
  110. const afterS1 = mounts
  111. act(() => { h.current.set('s2') })
  112. expect(mounts).toBe(afterS1 + 1)
  113. const afterS2 = mounts
  114. view.rerender(<>{createSlotRenderer().renderRoot(h.host, {})}</>)
  115. expect(mounts).toBe(afterS2)
  116. })
  117. it('delivers the resolved cell to session slots under it (observable behavior, not context internals)', () => {
  118. const seen: Record<string, unknown>[] = []
  119. const h = makeHost({
  120. root: (renderSlot) => <SessionProvider>{() => renderSlot('k.session', {})}</SessionProvider>,
  121. })
  122. h.addSession('s1')
  123. h.addSession('s2')
  124. h.registerSession({
  125. component: (props: { useSession?: <S>(sel: (s: { sid: string }) => S) => S; sessionId?: string }) => {
  126. // The bound hook reads the cell's bare source — asserting through it
  127. // proves the machinery wired THIS session's source, not another's.
  128. seen.push({ sessionId: props.sessionId, read: props.useSession!((s) => s.sid) })
  129. return null
  130. },
  131. options: {},
  132. })
  133. render(<>{createSlotRenderer().renderRoot(h.host, {})}</>)
  134. act(() => { h.current.set('s1') })
  135. expect(seen.at(-1)!['read']).toBe('s1')
  136. expect(seen.at(-1)!['sessionId']).toBe('s1')
  137. act(() => { h.current.set('s2') })
  138. expect(seen.at(-1)!['read']).toBe('s2')
  139. expect(seen.at(-1)!['sessionId']).toBe('s2')
  140. })
  141. it('fails loud when mounted outside the renderer tree (no host channel)', () => {
  142. const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
  143. expect(() => render(
  144. <SessionProvider>{(id) => <b>{id}</b>}</SessionProvider>,
  145. )).toThrow(/outside the installed renderer tree/)
  146. spy.mockRestore()
  147. })
  148. })