index.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. /**
  2. * jsdom slot test runtime: a real small runtime — Cordis `Context`, the
  3. * renderer-owned `SlotRegistry`, the `ui-session` adapter, and the UI renderer — assembled around
  4. * test-owned session/workspace doubles and a fail-loud file-upload stub, so feature specs exercise
  5. * declaration, registration, scope, store, inject, rendering, updates, and
  6. * disposal without hand-building the machinery per suite.
  7. *
  8. * Not part of the product plugin graph (no `dsh.client`); feature packages
  9. * depend on it in devDependencies only. It copies no SlotCore/renderer/store
  10. * machinery — everything mounts the production implementations.
  11. * @module @deepseek-ai/dsh-client-test-runtime
  12. */
  13. /* oxlint-disable typescript/no-redundant-type-constituents --
  14. * `keyof SlotMap & string` is the declare-merge key pattern (see ui-slots):
  15. * this compilation unit sees only the runtime's 'root' row, but consumer
  16. * programs merge their own keys in; the rule fires on the narrow-map view. */
  17. import { Context, Inject } from '@deepseek-ai/cordis'
  18. import type { Fiber, Plugin } from '@deepseek-ai/cordis'
  19. import { createElement, Fragment, useSyncExternalStore } from 'react'
  20. import type { ReactNode } from 'react'
  21. import { act, render, within } from '@testing-library/react'
  22. import type { RenderResult } from '@testing-library/react'
  23. import type { queries } from '@testing-library/dom'
  24. import type { BoundFunctions } from '@testing-library/dom'
  25. import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
  26. import { bindSnapshotSelector as bindRendererSnapshotSelector } from '@deepseek-ai/dsh-client-ui-renderer/src/client/bind.ts'
  27. import { createSlotRenderer as createRenderer } from '@deepseek-ai/dsh-client-ui-renderer/src/client/scoped-slots.tsx'
  28. import {
  29. apply as applyUiSession, inject as uiSessionInject,
  30. } from '@deepseek-ai/dsh-client-ui-session/client'
  31. import type { SessionId } from '@deepseek-ai/dsh-session/types'
  32. import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
  33. import type { PanelInfo } from '@deepseek-ai/dsh-client-ui-layout/client'
  34. import type {
  35. ChildrenDecl, ComposedProps, HostObservable, OwnerOf, RenderOpts, SlotComponent, SlotMap, SlotRenderer,
  36. SlotRendererHost, SnapshotSelectorHook, StoreInstanceLike,
  37. } from '@deepseek-ai/dsh-client-ui-slots'
  38. import { registerDomSnapshotSerializer } from './snapshot.ts'
  39. import { TestSessions } from './sessions.ts'
  40. import { TestWorkspaces } from './workspaces.ts'
  41. import type { Stabilizer } from './fixtures.ts'
  42. export type { UseSession } from '@deepseek-ai/dsh-client-ui-session/client'
  43. export { domSnapshotSerializer, registerDomSnapshotSerializer } from './snapshot.ts'
  44. export { FixtureSession, TestSessions } from './sessions.ts'
  45. export { stubSettingsScope } from './settings-scope.ts'
  46. export type { StubSettingsScope } from './settings-scope.ts'
  47. export { TestWorkspaces } from './workspaces.ts'
  48. export { RemoteError, TestRemote } from './remote.ts'
  49. export {
  50. chatSnapshot, conversationSnapshot, sessionSnapshot, workspaceSnapshot,
  51. } from './fixtures.ts'
  52. export type {
  53. FixtureSnapshot, SessionBehaviorOverrides, SessionFixture, SessionFixtureSnapshot, Stabilizer,
  54. } from './fixtures.ts'
  55. export { makeTranslate } from './translate.ts'
  56. export { usePinnedBrowserLanguages } from './locale-env.ts'
  57. /**
  58. * Bind an observable source to the production renderer's selector hook.
  59. * @param source - Observable snapshot source.
  60. * @returns Typed React selector hook.
  61. */
  62. export function bindSnapshotSelector<T>(source: HostObservable<T>): SnapshotSelectorHook<T> {
  63. return bindRendererSnapshotSelector(source)
  64. }
  65. /**
  66. * Create the production slot renderer used by client feature tests.
  67. * @returns Slot renderer instance.
  68. */
  69. export function createSlotRenderer(): SlotRenderer {
  70. return createRenderer()
  71. }
  72. /** Erased register face for the internal root call (the public declaration contract holds the typing). */
  73. type ErasedRegister = (options: object, component: unknown) => () => void
  74. /**
  75. * One rendered slot's local view, from {@link SlotTestRuntime.renderSlot}:
  76. * the renderer's own `[data-slot]` outlet anchor is the snapshot root
  77. * (`expect(view.container).toMatchSnapshot()` captures exactly this slot's
  78. * output), Testing Library queries are bound inside it, and `update`
  79. * re-renders with new owner props.
  80. */
  81. export interface SlotView<K extends keyof SlotMap & string> {
  82. /** The renderer's `<div data-slot="<key>">` anchor around the slot's rendered output. */
  83. readonly container: HTMLElement
  84. /** Testing Library queries scoped to {@link SlotView.container}. */
  85. readonly view: BoundFunctions<typeof queries>
  86. /**
  87. * Replace the owner props and flush the re-render (the render-site update:
  88. * in production the owner recomputes the share and React re-renders).
  89. * @param owner - the next owner props share.
  90. */
  91. update(owner: OwnerOf<K>): void
  92. }
  93. /**
  94. * Mounted feature plugin handle: the live fiber plus an act-wrapped,
  95. * idempotent dispose (unload cascade: entries, declared child slots, store
  96. * instances, and provided services all fall together).
  97. */
  98. export interface FeatureHandle {
  99. /** The plugin's live Cordis fiber (state assertions, escape hatch). */
  100. readonly fiber: Fiber
  101. /**
  102. * Dispose the plugin fiber inside React act; repeated calls no-op.
  103. * @returns completion of the unload cascade.
  104. */
  105. dispose(): Promise<void>
  106. }
  107. /** Mutable fail-loud file-upload stub installed by {@link SlotTestRuntime}. */
  108. export interface TestFileUpload {
  109. /** Availability reported to the feature under test. */
  110. available: boolean
  111. /** Test-supplied upload behavior; the default rejects every call. */
  112. upload: (sessionId: SessionId, ...args: unknown[]) => Promise<unknown>
  113. }
  114. /**
  115. * Owner-props cell behind the auto frame: one external store the frame
  116. * subscribes to, so {@link SlotTestRuntime.renderSlot} and
  117. * {@link SlotView.update} drive React through the standard uSES boundary.
  118. */
  119. class OwnerPropsCell {
  120. private readonly owners = new Map<string, { owner: object; opts: RenderOpts | undefined }>()
  121. private readonly listeners = new Set<() => void>()
  122. private version = 0
  123. /** Snapshot version for uSES pairing (bumped on every set). */
  124. readonly getVersion = (): number => this.version
  125. /**
  126. * Subscribe to owner-props changes.
  127. * @param fn - change callback.
  128. * @returns unsubscribe.
  129. */
  130. readonly subscribe = (fn: () => void): (() => void) => {
  131. this.listeners.add(fn)
  132. return () => { this.listeners.delete(fn) }
  133. }
  134. /**
  135. * Install or replace one key's owner props and notify (synchronous; the
  136. * caller wraps in act).
  137. * @param key - slot key.
  138. * @param owner - owner props share.
  139. * @param opts - explicit keyed or list selection for the render site.
  140. */
  141. set(key: string, owner: object, opts?: RenderOpts): void {
  142. this.owners.set(key, { owner, opts })
  143. this.version += 1
  144. for (const fn of [...this.listeners]) fn()
  145. }
  146. /** Keys with supplied owner props, in first-supply order. */
  147. entries(): readonly (readonly [string, { owner: object; opts: RenderOpts | undefined }])[] {
  148. return [...this.owners.entries()]
  149. }
  150. }
  151. /**
  152. * The test-owned 'root' occupant: declares the child slots a suite needs
  153. * through the REAL `slots.register`, with a caller-supplied minimal frame —
  154. * the runtime never guesses a feature's page structure.
  155. */
  156. export class TestRoot {
  157. private disposeEntry: (() => void) | undefined
  158. /**
  159. * @param slots - the runtime SlotRegistry.
  160. * @param stabilize - the owning runtime's act wrapper.
  161. */
  162. constructor(private readonly slots: SlotRegistry, private readonly stabilize: Stabilizer) {}
  163. /**
  164. * Register the root frame, declaring (and thereby claiming) the child
  165. * slots. One declaration per runtime — a second call fails loud in the
  166. * core ('root' is a single slot).
  167. * @param children - child-slot declaration table (declaration + render authorization + runtime spec).
  168. * @param frame - minimal frame component; its props derive from the declared keys (composed-props contract).
  169. * @returns completion of the act-wrapped registration.
  170. */
  171. async declare<const D extends ChildrenDecl>(
  172. children: D,
  173. frame: SlotComponent<ComposedProps<'root', never, keyof NoInfer<D> & keyof SlotMap & string, undefined, object>>,
  174. ): Promise<void> {
  175. await this.stabilize(() => {
  176. // Erased hop (same pattern as SlotRegistry's own implementation arm);
  177. // the declaration signature above is the typed contract.
  178. this.disposeEntry = (this.slots.register as unknown as ErasedRegister)({ name: 'root', children }, frame)
  179. })
  180. }
  181. /** Remove the root registration and collapse its declarations (runtime dispose path). */
  182. release(): void {
  183. this.disposeEntry?.()
  184. this.disposeEntry = undefined
  185. }
  186. }
  187. /**
  188. * The assembled test runtime. Obtain via {@link SlotTestRuntime.create};
  189. * dispose with {@link SlotTestRuntime.dispose} (afterEach). Public mutators
  190. * are act-wrapped throughout — tests never handle SlotCore microtask
  191. * batching or React act themselves.
  192. */
  193. export class SlotTestRuntime {
  194. /** The runtime's Cordis root for owner APIs and explicit test-only services. */
  195. readonly ctx: Context
  196. /** The production SlotRegistry mounted on {@link SlotTestRuntime.ctx}. */
  197. readonly slots: SlotRegistry
  198. /** The test-owned 'root' occupant. */
  199. readonly root: TestRoot
  200. /** Sessions double (list/current observable, cells, scopes, behavior faces). */
  201. readonly sessions: TestSessions
  202. /** Workspaces double (list observable, recorded intent actions). */
  203. readonly workspaces: TestWorkspaces
  204. /** Test-owned panel selection used by the framework's usePanelInfo hook. */
  205. readonly panelInfo = createSnapshotStore<PanelInfo>({ activePanelId: null })
  206. /** Mutable file-upload stub; replace `upload` in suites that exercise the capability. */
  207. readonly fileUpload: TestFileUpload
  208. private readonly stabilizer: Stabilizer = async (fn) => {
  209. await act(async () => { await fn() })
  210. }
  211. private host: SlotRendererHost | undefined
  212. private readonly views: RenderResult[] = []
  213. private readonly handles: FeatureHandle[] = []
  214. private disposed = false
  215. /** Auto-frame state ({@link SlotTestRuntime.declare} / {@link SlotTestRuntime.renderSlot}). */
  216. private readonly ownerCell = new OwnerPropsCell()
  217. private readonly autoDeclared = new Set<string>()
  218. private autoRootView: RenderResult | undefined
  219. private readonly disposeWorkspaceSource: () => void
  220. private readonly disposePanelInfoSource: () => void
  221. private constructor(ctx: Context, slots: SlotRegistry) {
  222. this.ctx = ctx
  223. this.slots = slots
  224. this.root = new TestRoot(slots, this.stabilizer)
  225. this.sessions = new TestSessions(this.stabilizer, ctx)
  226. this.workspaces = new TestWorkspaces(this.stabilizer)
  227. this.fileUpload = {
  228. available: false,
  229. upload: () => Promise.reject(new Error('client test runtime: file upload is not stubbed')),
  230. }
  231. ctx.provide('sessions', this.sessions)
  232. ctx.provide('workspaces', this.workspaces)
  233. ctx.provide('fileUpload', this.fileUpload as never)
  234. this.disposeWorkspaceSource = slots.provideRoot({ hooks: { workspaces: this.workspaces.list } })
  235. this.disposePanelInfoSource = slots.provideRoot({ hooks: { panelInfo: this.panelInfo } })
  236. // Capturing install: the production renderer does the rendering; the
  237. // wrapper only takes the host face for storeOf (no machinery copied).
  238. const renderer = createSlotRenderer()
  239. slots.install({
  240. renderRoot: (host, ownerProps) => {
  241. this.host = host
  242. return renderer.renderRoot(host, ownerProps)
  243. },
  244. })
  245. }
  246. /**
  247. * Assemble a runtime: real Context, mounted SlotRegistry, installed
  248. * renderer, and the session/workspace doubles provided as services.
  249. * @returns the ready runtime.
  250. */
  251. static async create(): Promise<SlotTestRuntime> {
  252. registerDomSnapshotSerializer()
  253. const ctx = new Context()
  254. const fiber = ctx.plugin(SlotRegistry)
  255. await fiber.await()
  256. const runtime = new SlotTestRuntime(ctx, ctx.get('slots') as SlotRegistry)
  257. await ctx.plugin({ inject: [...uiSessionInject], apply: applyUiSession }).await()
  258. return runtime
  259. }
  260. /**
  261. * Mount a feature plugin on a real fiber. Required services are prechecked
  262. * so a missing provider fails loud instead of suspending the fiber forever
  263. * (deliberate load-order suspension tests use `ctx.plugin` directly).
  264. * @param plugin - plugin value (function, class, or `{ inject, apply }` object).
  265. * @returns handle owning the fiber's explicit disposal.
  266. */
  267. async mount(plugin: Plugin): Promise<FeatureHandle> {
  268. const required = Object.keys(Inject.resolve((plugin as { inject?: Inject }).inject))
  269. const missing = required.filter(name => this.ctx.get(name) === undefined)
  270. if (missing.length > 0) {
  271. throw new Error(`mount would suspend: missing service(s) ${missing.join(', ')} — provide() them first`)
  272. }
  273. const fiber = this.ctx.plugin(plugin)
  274. await this.stabilizer(async () => {
  275. await fiber.await()
  276. })
  277. let disposed = false
  278. const handle: FeatureHandle = {
  279. fiber,
  280. dispose: async () => {
  281. if (disposed) return
  282. disposed = true
  283. await this.stabilizer(() => fiber.dispose())
  284. },
  285. }
  286. this.handles.push(handle)
  287. return handle
  288. }
  289. /** Release the default Workspace hook before mounting its production owner. */
  290. releaseWorkspaceSource(): void {
  291. this.disposeWorkspaceSource()
  292. }
  293. /** Release the default panel hook before mounting the production Layout owner. */
  294. releasePanelInfoSource(): void {
  295. this.disposePanelInfoSource()
  296. }
  297. /**
  298. * Render the root slot tree through the ctx-level entry (the shell's own
  299. * entry point): `ctx.slots.renderSlot('root', {})` under Testing Library.
  300. * @returns the Testing Library view.
  301. */
  302. renderRoot(): RenderResult {
  303. const view = render(createElement(Fragment, null, this.slots.renderSlot('root', {})))
  304. this.views.push(view)
  305. return view
  306. }
  307. /**
  308. * Declare child slots under an auto-generated root frame — the single-slot
  309. * mounting path for local DOM snapshots. Each key later supplied through
  310. * {@link SlotTestRuntime.renderSlot} renders inside the renderer's own
  311. * `<div data-slot="<key>">` outlet anchor (the snapshot root — the frame
  312. * adds no wrapper of its own). Mutually exclusive with
  313. * {@link TestRoot.declare} ('root' is a single slot); one call per runtime.
  314. * @param children - child-slot declaration table (same contract as TestRoot.declare).
  315. * @returns completion of the act-wrapped registration.
  316. */
  317. async declare(children: ChildrenDecl): Promise<void> {
  318. for (const key of Object.keys(children)) this.autoDeclared.add(key)
  319. const cell = this.ownerCell
  320. const AutoFrame = (props: { renderSlot: (key: string, owner: object, opts?: RenderOpts) => ReactNode }) => {
  321. useSyncExternalStore(cell.subscribe, cell.getVersion)
  322. // Keyed Fragments only: the renderer's outlet anchor is the one
  323. // `[data-slot]` element — the frame adding its own would nest
  324. // duplicate anchors under the same key.
  325. return createElement(Fragment, null, cell.entries().map(([key, { owner, opts }]) =>
  326. createElement(Fragment, { key }, props.renderSlot(key, owner, opts))))
  327. }
  328. await this.root.declare(children as never, AutoFrame as never)
  329. }
  330. /**
  331. * Render one declared slot with its owner props and return the local view.
  332. * The whole root tree mounts through the production assembly path
  333. * (renderer, scope providers, store axis); only this key's output lands in
  334. * the returned container. Call again with another key to view a sibling
  335. * slot of the same tree.
  336. * @param key - a key declared through {@link SlotTestRuntime.declare}.
  337. * @param owner - owner props share for the render site.
  338. * @param opts - explicit keyed or list selection; retained by view updates.
  339. * @returns the slot-local view (snapshot container, scoped queries, owner updates).
  340. */
  341. renderSlot<K extends keyof SlotMap & string>(key: K, owner: OwnerOf<K>, opts?: RenderOpts): SlotView<K> {
  342. if (!this.autoDeclared.has(key)) {
  343. throw new Error(`renderSlot('${key}') without declare() — declare the key first (or use root.declare for a custom frame)`)
  344. }
  345. const install = (next: object): void => {
  346. // Synchronous cell write inside act: the frame re-renders through uSES.
  347. act(() => {
  348. this.ownerCell.set(key, next, opts)
  349. })
  350. }
  351. install(owner)
  352. this.autoRootView ??= this.renderRoot()
  353. const container = this.autoRootView.container.querySelector(`[data-slot="${key}"]`)
  354. if (!(container instanceof HTMLElement)) {
  355. throw new Error(`renderSlot('${key}'): the auto frame rendered no wrapper — was the runtime already disposed?`)
  356. }
  357. return { container, view: within(container), update: install }
  358. }
  359. /**
  360. * Resolve the store instance the renderer would hand a slot's component
  361. * (identity assertions, action-driven writes). Requires a prior
  362. * {@link SlotTestRuntime.renderRoot} — the host face exists only inside the
  363. * installed renderer, exactly as in production.
  364. * @param key - slot key whose first entry declares the store.
  365. * @param scopeKey - session id for session-scope slots; omit for root scope.
  366. * @returns the live store instance.
  367. */
  368. storeOf(key: keyof SlotMap & string, scopeKey?: string): StoreInstanceLike {
  369. if (this.host === undefined) {
  370. throw new Error('storeOf before renderRoot() — the host face exists only inside the installed renderer')
  371. }
  372. const entry = this.host.entriesOf(key)[0]
  373. if (entry === undefined) throw new Error(`storeOf('${key}'): no registration on the ledger`)
  374. const scopeBinding = scopeKey === undefined
  375. ? undefined
  376. : this.host.scope('session')?.resolve(scopeKey)
  377. if (scopeKey !== undefined && scopeBinding === undefined) {
  378. throw new Error(`storeOf('${key}'): no live Session binding for '${scopeKey}'`)
  379. }
  380. const instance = this.host.storeOf(entry, scopeBinding)
  381. if (instance === undefined) throw new Error(`storeOf('${key}'): the entry declares no store`)
  382. return instance
  383. }
  384. /**
  385. * Flush pending ledger/store notifications inside act — for mutations made
  386. * outside the runtime's own methods (e.g. a direct `slots.register`).
  387. * @returns completion of the act pass.
  388. */
  389. async flush(): Promise<void> {
  390. await this.stabilizer(() => {})
  391. }
  392. /**
  393. * Tear down: unmount React trees first, then dispose feature fibers, the
  394. * root registration and standard sources, minted session scopes, and persisted test state.
  395. * Idempotent.
  396. * @returns completion of the teardown.
  397. */
  398. async dispose(): Promise<void> {
  399. if (this.disposed) return
  400. this.disposed = true
  401. this.autoRootView = undefined
  402. for (const view of this.views.splice(0)) view.unmount()
  403. for (const handle of this.handles.splice(0)) await handle.dispose()
  404. this.root.release()
  405. this.disposeWorkspaceSource()
  406. this.disposePanelInfoSource()
  407. await this.sessions.disposeScopes()
  408. localStorage.clear()
  409. }
  410. }