session-provider.spec.tsx 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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. workspaces: { list: observable<unknown>({ items: [] }) },
  54. }
  55. return {
  56. host,
  57. current,
  58. addSession: (id: string) => {
  59. // Bare source per cell (identity-stable): the machinery binds useSession from it.
  60. const cell: SessionCell = {
  61. sessionId: id,
  62. session: { getSnapshot: () => ({ sid: id }), subscribe: () => () => {} },
  63. }
  64. cells.set(id, cell)
  65. return cell
  66. },
  67. registerSession: (entry: StoredEntry) => { sessionEntries.push(entry) },
  68. }
  69. }
  70. describe('SessionProvider', () => {
  71. it('renders empty without a current session, switches to the body on select, falls back on an unresolvable id', () => {
  72. const h = makeHost({
  73. root: () => (
  74. <SessionProvider empty={() => <span>empty</span>}>
  75. {(id) => <div data-testid="body">{id}</div>}
  76. </SessionProvider>
  77. ),
  78. })
  79. h.addSession('s1')
  80. const view = render(<>{createSlotRenderer().renderRoot(h.host, {})}</>)
  81. expect(view.container.textContent).toBe('empty')
  82. act(() => { h.current.set('s1') })
  83. expect(view.container.textContent).toBe('s1')
  84. act(() => { h.current.set('ghost') }) // listed nowhere: cell() misses
  85. expect(view.container.textContent).toBe('empty')
  86. })
  87. it('renders null empty state when the empty prop is omitted', () => {
  88. const h = makeHost({
  89. root: () => <SessionProvider>{(id) => <b>{id}</b>}</SessionProvider>,
  90. })
  91. const view = render(<>{createSlotRenderer().renderRoot(h.host, {})}</>)
  92. expect(view.container.textContent).toBe('')
  93. })
  94. it('remounts the body on session switch (key semantics) but not on unrelated re-renders', () => {
  95. let mounts = 0
  96. function Body({ id }: { id: string }) {
  97. const mounted = useRef(false)
  98. useEffect(() => {
  99. /* v8 ignore next -- strict-mode double-invoke guard, not a branch under test */
  100. if (!mounted.current) { mounted.current = true; mounts += 1 }
  101. }, [])
  102. return <div>{id}</div>
  103. }
  104. const h = makeHost({
  105. root: () => <SessionProvider>{(id) => <Body id={id} />}</SessionProvider>,
  106. })
  107. h.addSession('s1')
  108. h.addSession('s2')
  109. const view = render(<>{createSlotRenderer().renderRoot(h.host, {})}</>)
  110. act(() => { h.current.set('s1') })
  111. const afterS1 = mounts
  112. act(() => { h.current.set('s2') })
  113. expect(mounts).toBe(afterS1 + 1)
  114. const afterS2 = mounts
  115. view.rerender(<>{createSlotRenderer().renderRoot(h.host, {})}</>)
  116. expect(mounts).toBe(afterS2)
  117. })
  118. it('delivers the resolved cell to session slots under it (observable behavior, not context internals)', () => {
  119. const seen: Record<string, unknown>[] = []
  120. const h = makeHost({
  121. root: (renderSlot) => <SessionProvider>{() => renderSlot('k.session', {})}</SessionProvider>,
  122. })
  123. h.addSession('s1')
  124. h.addSession('s2')
  125. h.registerSession({
  126. component: (props: { useSession?: <S>(sel: (s: { sid: string }) => S) => S; sessionId?: string }) => {
  127. // The bound hook reads the cell's bare source — asserting through it
  128. // proves the machinery wired THIS session's source, not another's.
  129. seen.push({ sessionId: props.sessionId, read: props.useSession!((s) => s.sid) })
  130. return null
  131. },
  132. options: {},
  133. })
  134. render(<>{createSlotRenderer().renderRoot(h.host, {})}</>)
  135. act(() => { h.current.set('s1') })
  136. expect(seen.at(-1)!['read']).toBe('s1')
  137. expect(seen.at(-1)!['sessionId']).toBe('s1')
  138. act(() => { h.current.set('s2') })
  139. expect(seen.at(-1)!['read']).toBe('s2')
  140. expect(seen.at(-1)!['sessionId']).toBe('s2')
  141. })
  142. it('fails loud when mounted outside the renderer tree (no host channel)', () => {
  143. const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
  144. expect(() => render(
  145. <SessionProvider>{(id) => <b>{id}</b>}</SessionProvider>,
  146. )).toThrow(/outside the installed renderer tree/)
  147. spy.mockRestore()
  148. })
  149. })