refactor(gui): slot system standard — single register, four props shares, framework store seat

The definitive slot model for the web client, replacing the first-generation
define/register two-step, ScopedSlots whitelist faces, and binding handles:

- 'root' is the only a-priori slot (SlotsService built-in); the shell renders
  exactly ctx.slots.renderSlot('root', {}).
- register is the single API: children = slot declaration + render
  authorization + runtime spec in one options object; misconfiguration fails
  loud at load (duplicate declaration, undeclared contribution, one store
  handle under two scopes).
- Component props arrive in four auto-derived shares: PropsRuntime<K>
  (owner params + session/global standard kits via declare-merge),
  PropsRenderSlots<S>, PropsStore<H>, and the inject business face.
  sessionId is framework-supplied; hooks are framework-made only.
- Framework store seat: defineStore factories declare schema/actions/persist;
  read = useStore, write = baked actions only; store scope derives from the
  mounting entry; per-session persist keys and clearPersisted lifecycle.
- inject factories read the apply closure's own ctx (binding handles retired;
  root-ctx back door closed); SessionProvider is self-wired render-prop.
- Rendering sits behind the SlotRenderer install seam; runtime stays
  React-free; ownership ledger keyed to the single entry axis closes the
  stale-authority window (StaleAuthorizationError probes).

Docs: the slot type-chain note is refreshed in place as the slot system
standard RFC (bilingual pair re-recorded); the web client architecture RFC
defers its slot sections there; packages/client/AGENTS.md gains the slot and
props discipline; gui-testing/web-styling notes drop missions/ references.

Tests: suites rewritten to the standard (props fed directly, real store
engines via createXXXStore().create(), no render machinery); load-time
negative samples for declaration/authorization/store conflicts; verified by
real-host playwright run (three columns, empty state, collapse, keyed session
remount, cross-slot selection sharing).

docs(ui-sidebar): point contract reference at the committed slot standard RFC

missions/ is workspace-local and never committed; the README must not cite it.
This commit is contained in:
imccyu
2026-07-23 01:40:30 +08:00
parent efa4326ff4
commit 1b0ea07bce
95 changed files with 5024 additions and 3322 deletions

View File

@@ -1,10 +1,10 @@
# @deepseek-ai/dsh-client-web-react
ctx↔React glue: createSnapshotStore (zustand vanilla + immer + subscribeWithSelector + rafFlush + opt-in persist), bindSnapshotSelector, SessionProvider (dependency-inverted), scopedSlots outlet, RootBindingProvider, useInvoke. Contract: api-contracts v3 §2.
ctx↔React machinery for the slot terminal design: createSlotRenderer (the SlotRenderer implementation the shell installs into the runtime SlotsService), SessionProvider (framework-wired render prop over the host's current-session source), defineStore (the declarative store shell over the internal zustand engine), bindSnapshotSelector, useInvoke. The snapshot-store engine (createSnapshotStore) is framework-internal via the `./store` subpath; business plugins declare stores through defineStore only.
## Model Experience
None, as the ctx↔React glue runs entirely in the browser; nothing here reaches a model request.
None, as the ctx↔React machinery runs entirely in the browser; nothing here reaches a model request.
#### KV Cache effect
@@ -12,6 +12,6 @@ None; this package neither assembles nor sends a provider request.
## Known Limitations and Deferred Work
- **The persist middleware corrupts primitive-state stores** — it object-spreads state on save, so a `SnapshotStore<string>` round-trips as a character map; consumers with primitive state hand-roll persistence instead (ui-conversation drafts is the precedent).
- **The persist middleware corrupts primitive-state stores** — it object-spreads state on save, so a `SnapshotStore<string>` round-trips as a character map; the engine hand-rolls persistence instead (see `attachPersistence`).
- **`UseSession` is deliberately wide (`object` snapshot)** — the dependency direction (runtime → web-react, never the reverse) keeps the real `ConversationSnapshot` type out of reach; session-slot consumers narrow once at their boundary.
- **renderSlot is the single P-I form** — no Suspense, no per-entry lazy loading; the progressive-rendering surface returns with its own project.

View File

@@ -1,14 +1,22 @@
/**
* ctx-to-React glue: uSES bridge, SessionProvider (dependency-inverted),
* scopedSlots outlet factory, useInvoke. Contract: api-contracts v3 section 2.
* ctx-to-React machinery (slot terminal design §8): createSlotRenderer (the
* install-seam implementation), SessionProvider (framework-wired render
* prop), the defineStore shell, and useInvoke. Contract types (SlotRenderer
* family, store family, four-share props) are ui-slots authority — this face
* re-exports the ones its own values traffic in. The snapshot-store ENGINE
* (createSnapshotStore) is framework-internal — runtime/i18n reach it through
* the './store' subpath; business plugins declare stores via defineStore
* only. React contexts stay in-package: business components see none.
*/
import type { ReactNode } from 'react'
import type { SnapshotSelectorHook } from './store/index.ts'
// -- store: the declarative shell is public; the engine stays off this face --
export type {
ActionsDecl, BakedActions, BoundActions, EngineStoreHandle, EngineStoreInstance,
ObservableSnapshot, SnapshotSelectorHook, SnapshotStore,
StoreFactory, StoreHandle, StoreInstance, StoreSpec,
} from './store/index.ts'
export { createSnapshotStore, shallowEqual } from './store/index.ts'
export { defineStore, shallowEqual } from './store/index.ts'
export { bindSnapshotSelector } from './bind.ts'
/**
@@ -19,23 +27,15 @@ export { bindSnapshotSelector } from './bind.ts'
*/
export type UseSession<Snap extends object = object> = SnapshotSelectorHook<Snap>
/** Session assembly handle narrowed from ui-slots' structural form. */
export interface SessionBinding<Snap extends object = object> {
readonly sessionId: string
readonly session: { useSelector: UseSession<Snap> }
readonly ctx: unknown
}
// -- renderer: the install-seam implementation; contract lives in ui-slots --
export type {
HostObservable, RenderOpts, SessionCell,
SlotRenderer, SlotRendererHost, StoreInstanceLike,
} from '@deepseek-ai/dsh-client-ui-slots'
export { SlotOwnershipError, StaleAuthorizationError } from '@deepseek-ai/dsh-client-ui-slots'
export { createSlotRenderer } from './scoped-slots.tsx'
/** SessionProvider dependency surface (inverted: web-react never imports runtime). */
export interface SessionProviderDeps {
useCurrent: () => string | undefined
resolveBinding: (id: string) => SessionBinding | undefined
/** Assembler-owned body: the shell closes over its own scopedSlots to render the session slots. */
renderBody: (id: string) => ReactNode
}
export { createSessionProvider, RootBindingProvider, SlotAssemblyError, useRootBinding, useSessionBinding } from './session-provider.tsx'
export { scopedSlots } from './scoped-slots.tsx'
// -- session area: the framework-wired provider; binding contexts stay internal --
export { SessionProvider, SlotAssemblyError, type SessionProviderProps } from './session-provider.tsx'
export { useInvoke } from './use-invoke.ts'

View File

@@ -1,62 +1,97 @@
/**
* ScopedSlots factory: the sole render surface over the slot registry.
* renderSlot subscribes through uSES (SlotCore.subscribe/getVersion), renders
* per slot kind, wraps every entry in an error boundary, and merges props from
* three sources: standard injection (session slots get useSession), the
* registrant's cached inject factory, then owner props (owner wins).
*
* Typing model (slot type-chain design §4): the key stays generic (`K`) from
* renderSlot down to the outlet, so `entries<K>()` returns typed entries and
* the per-entry render path is monomorphic — no existential casts in loops.
* createSlotRenderer(): the outlet machinery behind the runtime install seam
* (slot terminal design §8). renderRoot mounts the host channel and renders
* the built-in 'root' key; every deeper slot renders through a per-entry
* renderSlot binding synthesized from the entry's children declaration.
* Standard-kit synthesis per entry: the global useSessions hook, the session
* pair (useSession + sessionId) under SessionProvider, the store pair
* (useStore + actions) for store-declaring entries, and the renderSlot
* binding (entry-identity bound, stale-checked) for children-declaring
* entries. Inject factories run inside the entry component bodies ON PURPOSE
* — the per-entry error boundary contains a throwing factory to its own
* entry; parameters follow the declaration (sessionId for session slots,
* baked actions when a store is declared).
*/
import { Component, useSyncExternalStore, type FC, type ReactNode } from 'react'
import type {
RenderOpts, RootBinding, ScopedSlots, SessionBinding as SlotSessionBinding,
SlotCore, SlotEntry, SlotMap,
import {
SlotOwnershipError, StaleAuthorizationError,
type RenderOpts, type SessionCell, type SlotRenderer, type SlotRendererHost,
type StoredEntry,
} from '@deepseek-ai/dsh-client-ui-slots'
import { SlotAssemblyError, useRootBinding, useSessionBinding } from './session-provider.tsx'
import {
HostContext, SlotAssemblyError, observableHook, useHost, useSessionCell,
} from './session-provider.tsx'
type AnyKey = keyof SlotMap & string
type EntryOf<K extends AnyKey> = SlotEntry<SlotMap[K]>
type InjectedProps = Record<string, unknown>
/**
* Inject results cache: root slots per entry, session slots per (entry x binding).
* WeakMap keys are the entry objects (stable across entries() snapshots per
* the SlotCore contract); values are the registrant's injected share. Storage
* erases the per-entry `I` — the single budgeted cast per cache restores it.
*/
const rootInjectCache = new WeakMap<object, InjectedProps>()
const sessionInjectCache = new WeakMap<object, WeakMap<object, InjectedProps>>()
/** Owner-facing renderSlot binding shape (typed narrowing lands on the wave-1 props seam). */
type RenderSlotBinding = (key: string, owner: object, opts?: RenderOpts) => ReactNode
function cachedRootInject<K extends AnyKey>(entry: EntryOf<K>, binding: RootBinding): InjectedProps {
const inject = entry.options?.inject
/**
* Per-entry renderSlot bindings. The binding is identity-stable per entry
* (memoized components must not resubscribe on unrelated re-renders) and dies
* with the entry: a retained closure calling after the entry's disposal hits
* the in-ledger check and throws.
*/
const renderSlotCache = new WeakMap<StoredEntry, RenderSlotBinding>()
function boundRenderSlot(host: SlotRendererHost, entry: StoredEntry): RenderSlotBinding {
let binding = renderSlotCache.get(entry)
if (!binding) {
binding = (key, owner, opts) => {
if (!host.isLive(entry)) {
throw new StaleAuthorizationError(`renderSlot('${key}') from a disposed registration`)
}
// Plain-JS backstop; typed callers are narrowed to the declared keys.
if (entry.children?.[key] === undefined) {
throw new SlotOwnershipError(`slot '${key}' is not declared by this entry's children`)
}
return <SlotOutlet slotKey={key} ownerProps={owner} opts={opts} />
}
renderSlotCache.set(entry, binding)
}
return binding
}
/**
* Inject results cache: root entries per entry, session entries per
* (entry x session cell). WeakMap keys are entry/cell objects (both
* identity-stable per registration/session scope), so cache lifetime rides
* the same axes as the values it memoizes.
*/
const rootInjectCache = new WeakMap<StoredEntry, InjectedProps>()
const sessionInjectCache = new WeakMap<StoredEntry, WeakMap<SessionCell, InjectedProps>>()
function runInject(entry: StoredEntry, cell: SessionCell | undefined, actions: object | undefined): InjectedProps {
const inject = entry.inject
if (!inject) return {}
// Declaration-derived positional arguments: sessionId for session scope,
// baked actions when a store is declared.
const args: unknown[] = []
if (cell !== undefined) args.push(cell.sessionId)
if (actions !== undefined) args.push(actions)
return (inject as (...args: unknown[]) => InjectedProps)(...args)
}
function cachedRootInject(entry: StoredEntry, actions: object | undefined): InjectedProps {
let props = rootInjectCache.get(entry)
if (!props) {
// Root-scope factories accept RootBinding; the conditional-type parameter
// only fails to dispatch because K is generic here — the outlet's
// spec.scope branch guarantees the scope side (budgeted cast, one per cache).
props = (inject as (b: RootBinding) => InjectedProps)(binding)
props = runInject(entry, undefined, actions)
rootInjectCache.set(entry, props)
}
return props
}
function cachedSessionInject<K extends AnyKey>(entry: EntryOf<K>, binding: SlotSessionBinding): InjectedProps {
const inject = entry.options?.inject
if (!inject) return {}
let perBinding = sessionInjectCache.get(entry)
if (!perBinding) {
perBinding = new WeakMap()
sessionInjectCache.set(entry, perBinding)
function cachedSessionInject(entry: StoredEntry, cell: SessionCell, actions: object | undefined): InjectedProps {
let perCell = sessionInjectCache.get(entry)
if (!perCell) {
perCell = new WeakMap()
sessionInjectCache.set(entry, perCell)
}
let props = perBinding.get(binding)
let props = perCell.get(cell)
if (!props) {
// Same scope-dispatch note as the root cache: the session branch of the
// outlet guarantees this factory's binding side (budgeted cast).
props = (inject as (b: SlotSessionBinding) => InjectedProps)(binding)
perBinding.set(binding, props)
props = runInject(entry, cell, actions)
perCell.set(cell, props)
}
return props
}
@@ -83,68 +118,77 @@ class SlotErrorBoundary extends Component<
}
}
interface OutletProps<K extends AnyKey> {
core: SlotCore
slotKey: K
ownerProps: object
opts?: RenderOpts | undefined
/**
* Standard-kit synthesis shared by both scope branches: the global
* useSessions hook, the store pair when declared, and the renderSlot binding
* when children are declared. Every member is identity-stable (hook cache /
* host store cache / binding cache), so spreading a fresh kit object per
* render never churns child subscriptions.
*/
function standardKit(host: SlotRendererHost, entry: StoredEntry, cell: SessionCell | undefined): {
kit: InjectedProps; actions: object | undefined
} {
const kit: InjectedProps = { useSessions: observableHook(host.sessions.list) }
if (cell !== undefined) {
kit['useSession'] = cell.useSession
kit['sessionId'] = cell.sessionId
}
const store = host.storeOf(entry, cell?.sessionId)
if (store !== undefined) {
kit['useStore'] = store.useSelector
kit['actions'] = store.actions
}
if (entry.children !== undefined) {
kit['renderSlot'] = boundRenderSlot(host, entry)
}
return { kit, actions: store?.actions }
}
/**
* One rendered entry: standard injection + cached inject + owner props.
* Inject factories run inside these component bodies ON PURPOSE — the outlet
* wraps every Entry element in the per-entry error boundary, so a throwing
* factory blacks out only its own entry. The three-source merge composes the
* entry's full props contract; TS cannot prove the composition against
* `SlotMap[K]['props']` (the shares are erased at the registry boundary), so
* each Entry renders through a props-widened view of the component — the
* design-budgeted composition point, one per scope branch.
* One rendered entry: standard kit + cached inject + owner props (owner
* wins). The kit and injected shares are erased at the render boundary — the
* register seam already proved the composed contract — so each Entry renders
* through a props-widened view of the component (the design-budgeted
* composition point, one per scope branch).
*/
function SessionEntry<K extends AnyKey>({ entry, ownerProps }: {
entry: EntryOf<K>; ownerProps: object
}) {
const binding = useSessionBinding()
function SessionEntry({ entry, ownerProps }: { entry: StoredEntry; ownerProps: object }) {
const host = useHost()
const cell = useSessionCell()
const Comp = entry.component as FC<InjectedProps>
const injected = cachedSessionInject(entry, binding)
return <Comp useSession={binding.session.useSelector} {...injected} {...ownerProps} />
const { kit, actions } = standardKit(host, entry, cell)
const injected = cachedSessionInject(entry, cell, actions)
return <Comp {...kit} {...injected} {...ownerProps} />
}
function RootEntry<K extends AnyKey>({ entry, ownerProps }: {
entry: EntryOf<K>; ownerProps: object
}) {
const hasInject = entry.options?.inject !== undefined
function RootEntry({ entry, ownerProps }: { entry: StoredEntry; ownerProps: object }) {
const host = useHost()
const Comp = entry.component as FC<InjectedProps>
// Only inject-bearing entries need the root binding channel; plain entries
// must render fine in shells that never mounted RootBindingProvider.
if (!hasInject) return <Comp {...ownerProps} />
return <RootInjectEntry entry={entry} ownerProps={ownerProps} />
const { kit, actions } = standardKit(host, entry, undefined)
const injected = cachedRootInject(entry, actions)
return <Comp {...kit} {...injected} {...ownerProps} />
}
function RootInjectEntry<K extends AnyKey>({ entry, ownerProps }: {
entry: EntryOf<K>; ownerProps: object
function SlotOutlet({ slotKey, ownerProps, opts }: {
slotKey: string; ownerProps: object; opts?: RenderOpts | undefined
}) {
const binding = useRootBinding()
const Comp = entry.component as FC<InjectedProps>
const injected = cachedRootInject(entry, binding)
return <Comp {...injected} {...ownerProps} />
}
function SlotOutlet<K extends AnyKey>({ core, slotKey, ownerProps, opts }: OutletProps<K>) {
// Version tick drives entries() re-read; SlotCore batches per microtask.
const host = useHost()
// Version tick drives entries() re-read; the host batches per microtask.
useSyncExternalStore(
(fn) => core.subscribe(slotKey, fn),
() => core.getVersion(slotKey),
(fn) => host.subscribe(slotKey, fn),
() => host.getVersion(slotKey),
)
const spec = core.spec(slotKey)
if (!spec) throw new Error(`renderSlot('${slotKey}') before define`)
const entries = core.entries(slotKey)
const Entry: FC<{ entry: EntryOf<K>; ownerProps: object }> =
spec.scope === 'session' ? SessionEntry : RootEntry
const spec = host.specOf(slotKey)
// Undeclared (or no-longer-declared) keys render empty: a declaring entry's
// unload returns the slot to the undeclared state while retained elements
// may still be mounted — natural empty, not an ownership failure (§9).
if (!spec) return null
const entries = host.entriesOf(slotKey)
const Entry = spec.scope === 'session' ? SessionEntry : RootEntry
// The boundary must wrap the Entry ELEMENT, not live inside it: inject
// factories and binding lookups run in the Entry body and must land in the
// factories and kit synthesis run in the Entry body and must land in the
// per-entry fallback rather than escaping to the tree above.
const guarded = (entry: EntryOf<K>, key?: string | number) => (
const guarded = (entry: StoredEntry, key?: string | number) => (
<SlotErrorBoundary slotKey={slotKey} key={key}>
<Entry entry={entry} ownerProps={ownerProps} />
</SlotErrorBoundary>
@@ -156,15 +200,15 @@ function SlotOutlet<K extends AnyKey>({ core, slotKey, ownerProps, opts }: Outle
return guarded(entry)
}
if (spec.kind === 'keyed') {
const entry = entries.find((e) => e.options && 'key' in e.options && e.options.key === opts?.entryKey)
const entry = entries.find((e) => e.options?.key === opts?.entryKey)
if (!entry) return <>{opts?.fallback ?? null}</>
return guarded(entry)
}
// list: registration order refined by explicit order, optional id filter.
const withListOptions = entries.map((entry) => ({
entry,
id: entry.options && 'id' in entry.options ? entry.options.id : undefined,
order: entry.options && 'order' in entry.options ? entry.options.order ?? 0 : 0,
id: entry.options?.id,
order: entry.options?.order ?? 0,
}))
let list = [...withListOptions].sort((a, b) => a.order - b.order)
if (opts?.only !== undefined) list = list.filter((item) => item.id === opts.only)
@@ -172,20 +216,36 @@ function SlotOutlet<K extends AnyKey>({ core, slotKey, ownerProps, opts }: Outle
return <>{list.map((item, i) => guarded(item.entry, item.id ?? i))}</>
}
/** Root outlet: the shell's single ctx-level render entry — an unregistered 'root' is a boot-order failure, never a silent blank (§1). */
function RootOutlet({ ownerProps }: { ownerProps: object }) {
const host = useHost()
useSyncExternalStore(
(fn) => host.subscribe('root', fn),
() => host.getVersion('root'),
)
const entry = host.entriesOf('root')[0]
if (!entry) throw new SlotAssemblyError("renderSlot('root') before any 'root' registration (boot order)")
return (
<SlotErrorBoundary slotKey="root">
<RootEntry entry={entry} ownerProps={ownerProps} />
</SlotErrorBoundary>
)
}
/**
* Build a whitelist-narrowed ScopedSlots render surface over a SlotCore.
* The type parameter narrows compile-time access; the runtime whitelist
* backstops plain-JS callers.
* @param core - the slot registry core.
* @param keys - whitelisted slot keys the caller may render.
* @returns the ScopedSlots facade.
* Build the renderer the shell installs into the runtime SlotsService
* (ctx.slots.install(createSlotRenderer()) at boot; the service owns the
* install/renderSlot seam and the double-install/not-installed throws).
* @returns the renderer.
*/
export function scopedSlots<K extends AnyKey>(core: SlotCore, ...keys: K[]): ScopedSlots<K> {
const allowed = new Set<string>(keys)
export function createSlotRenderer(): SlotRenderer {
return {
renderSlot(key, props, opts) {
if (!allowed.has(key)) throw new Error(`slot '${key}' is not in this ScopedSlots whitelist`)
return <SlotOutlet core={core} slotKey={key} ownerProps={props} opts={opts} />
renderRoot(host, ownerProps) {
return (
<HostContext.Provider value={host}>
<RootOutlet ownerProps={ownerProps} />
</HostContext.Provider>
)
},
}
}

View File

@@ -1,15 +1,15 @@
/**
* SessionProvider (dependency-inverted; never imports runtime) plus the two
* binding contexts the slot outlet reads: per-session {@link BindingContext}
* written here, and the root-binding channel written by the shell through
* {@link RootBindingProvider}.
* SessionProvider (framework-wired render prop, slot terminal design §7) plus
* the two internal channels the render machinery shares: the renderer host
* context (written once by createSlotRenderer's root) and the per-session
* binding context (written here, read by session-scope outlets). Both
* contexts are in-package machinery — they are NOT exported from the package
* index; business components see zero React contexts.
*/
import { createContext, useContext, type FC, type ReactNode } from 'react'
import type { RootBinding } from '@deepseek-ai/dsh-client-ui-slots'
import type { SessionBinding, SessionProviderDeps } from './index.ts'
/** Session binding for the subtree under SessionProvider (module-private write). */
const BindingContext = createContext<SessionBinding | null>(null)
import { createContext, useContext, type ReactNode } from 'react'
import type { HostObservable, SessionCell, SlotRendererHost } from '@deepseek-ai/dsh-client-ui-slots'
import { bindSnapshotSelector } from './bind.ts'
import type { SnapshotSelectorHook } from './store/index.ts'
/**
* A missing-provider assembly error: the shell wired the tree wrong. The slot
@@ -19,56 +19,75 @@ const BindingContext = createContext<SessionBinding | null>(null)
*/
export class SlotAssemblyError extends Error {}
/** Renderer host channel: written by createSlotRenderer's root element (in-package machinery only). */
export const HostContext = createContext<SlotRendererHost | null>(null)
/**
* Read the enclosing session binding; throws outside a SessionProvider
* subtree (session slots must not render without a session).
* @returns the enclosing binding.
* Read the installed renderer host; throws outside the rendered root tree
* (framework components must not render detached from the renderer).
* @returns the host surface.
*/
export function useSessionBinding(): SessionBinding {
const binding = useContext(BindingContext)
if (!binding) throw new SlotAssemblyError('session slot rendered outside SessionProvider')
return binding
export function useHost(): SlotRendererHost {
const host = useContext(HostContext)
if (!host) throw new SlotAssemblyError('slot machinery rendered outside the installed renderer tree')
return host
}
const RootBindingContext = createContext<RootBinding | null>(null)
/** Per-session binding channel for the subtree under SessionProvider (in-package machinery only). */
const BindingContext = createContext<SessionCell | null>(null)
/**
* Root-binding supply channel: the shell mounts this once at the top so root
* slot inject factories receive their assembly handle.
* Read the enclosing session cell; throws outside a SessionProvider subtree
* (session slots must not render without a session).
* @returns the enclosing cell.
*/
export const RootBindingProvider: FC<{ value: RootBinding; children?: ReactNode }> =
({ value, children }) => (
<RootBindingContext.Provider value={value}>{children}</RootBindingContext.Provider>
)
/**
* Read the root binding; throws when the shell forgot to mount
* {@link RootBindingProvider} (root inject factories need ctx).
* @returns the root binding.
*/
export function useRootBinding(): RootBinding {
const binding = useContext(RootBindingContext)
if (!binding) throw new SlotAssemblyError('root slot inject requires RootBindingProvider above')
return binding
export function useSessionCell(): SessionCell {
const cell = useContext(BindingContext)
if (!cell) throw new SlotAssemblyError('session slot rendered outside SessionProvider')
return cell
}
/**
* Build the single SessionProvider component: subscribes to the current
* session id, resolves its binding (stable reference), remounts the body
* under key={id}, and delegates body rendering to the assembler's renderBody
* (slot ownership stays with layout; the provider knows no slot names).
* @param deps - inverted dependencies.
* @returns the provider component.
* Identity-stable selector hook per host observable. uSES resubscribes when
* the subscribe reference changes, so the bound hook must be created once per
* source — cached here by source identity (sources are host-owned singletons).
* @param source - host-provided observable.
* @returns the cached selector hook.
*/
export function createSessionProvider(deps: SessionProviderDeps): FC<{ renderEmpty?: () => ReactNode }> {
return function SessionProvider({ renderEmpty }) {
const id = deps.useCurrent()
const binding = id === undefined ? undefined : deps.resolveBinding(id)
if (id === undefined || !binding) return <>{renderEmpty?.() ?? null}</>
return (
<BindingContext.Provider value={binding} key={id}>
{deps.renderBody(id)}
</BindingContext.Provider>
)
export function observableHook<T>(source: HostObservable<T>): SnapshotSelectorHook<T> {
let hook = hookCache.get(source)
if (hook === undefined) {
hook = bindSnapshotSelector(source)
hookCache.set(source, hook)
}
return hook as SnapshotSelectorHook<T>
}
const hookCache = new WeakMap<object, unknown>()
/** SessionProvider surface: render-prop body plus the no-session branch. */
export interface SessionProviderProps {
/** No-session body (also covers a current id whose session cannot be resolved). */
empty?: (() => ReactNode) | undefined
/** Session body; remounted per session via key={sessionId}. */
children: (sessionId: string) => ReactNode
}
/**
* Framework-wired session area: subscribes to the host's current-session
* source (design fiat ① — selection authority lives with runtime sessions),
* resolves the session cell, and remounts the body under key={sessionId} so
* a session switch rebuilds the whole session subtree. Ids speak plain
* string at this dependency-inverted layer; branding lands on the component
* props seam (PropsRuntime).
*/
export function SessionProvider({ empty, children }: SessionProviderProps) {
const host = useHost()
const id = observableHook(host.sessions.current)((s) => s)
const cell = id === undefined ? undefined : host.sessions.cell(id)
if (id === undefined || cell === undefined) return <>{empty?.() ?? null}</>
return (
<BindingContext.Provider value={cell} key={id}>
{children(id)}
</BindingContext.Provider>
)
}

View File

@@ -1,14 +1,27 @@
/**
* Snapshot store engine (zustand vanilla + immer + subscribeWithSelector +
* rafFlush middleware + opt-in persist + dev freeze). The only data contract
* consumed by React is {@link ObservableSnapshot}.
* rafFlush middleware + opt-in persist + dev freeze) plus the declarative
* shell over it: {@link defineStore} bakes an init/persist/actions literal
* into a {@link StoreHandle}, the registration-side store seat of the slot
* terminal design (§4). The engine ({@link createSnapshotStore}) stays the
* substrate for framework data (runtime sessions/loader/i18n); business
* plugins declare stores through defineStore only.
*/
import { createStore, type StoreApi } from 'zustand/vanilla'
import { subscribeWithSelector } from 'zustand/middleware'
import { shallow } from 'zustand/shallow'
import { produce } from 'immer'
import type {
ActionsDecl, BakedActions, StoreHandle, StoreInstance, StoreSpec,
} from '@deepseek-ai/dsh-client-ui-slots'
import { bindSnapshotSelector } from '../bind.ts'
// Store contract types are ui-slots authority (wave 1); this module re-exports
// them beside the engine so '/store' consumers get one import surface.
export type {
ActionsDecl, BakedActions, BoundActions, StoreFactory, StoreHandle, StoreInstance, StoreSpec,
} from '@deepseek-ai/dsh-client-ui-slots'
/** Minimal observable snapshot source: Session objects and snapshot stores both satisfy it. */
export interface ObservableSnapshot<T> { getSnapshot(): T; subscribe(fn: () => void): () => void }
@@ -152,3 +165,86 @@ function deepFreeze(value: unknown): void {
deepFreeze((value as Record<PropertyKey, unknown>)[key])
}
}
// ---- defineStore shell (slot terminal design §4) ----
// The type authority is ui-slots' store family (create(scopeKey?) and
// clearPersisted() included); this module houses only the engine-backed
// implementation. The one engine-side widening left: instances expose the
// raw engine store for framework/test surfaces.
/** A live engine instance: the contract instance plus the raw engine store. */
export interface EngineStoreInstance<T, A extends ActionsDecl<T>> extends StoreInstance<T, A> {
/** The underlying engine store (framework/test surface; components never see it). */
readonly store: SnapshotStore<T>
}
/** The engine-backed handle: create() narrowed to the engine instance. */
export interface EngineStoreHandle<T, A extends ActionsDecl<T>> extends StoreHandle<T, A> {
/**
* Construct a live engine instance (see the contract JSDoc on
* {@link StoreHandle.create} for scopeKey/persist semantics).
*
* Known boundary: the persist key is the storage identity, so multiple live
* instances created under the same resolved key share (and cross-pollute)
* one localStorage entry. Instance uniqueness per key is the caller's
* responsibility — production is safe because the framework caches one
* instance per handle x scope key; tests wanting isolation use distinct
* scope keys or persist-free declarations (multi-create freedom is a
* feature there, so create() deliberately does not dedupe or throw).
* @param scopeKey - session id for session-scope instances; omitted for root scope.
* @returns the engine instance.
*/
create(scopeKey?: string): EngineStoreInstance<T, A>
}
/**
* Declare a store: initial state, optional persistence, and the full write
* set as pure draft mutators. The returned handle is the registration
* currency of the store seat — its identity keys instance sharing. Satisfies
* ui-slots' DefineStore contract (the handle/instance are the engine-extended
* subtypes).
*
* The `A & ActionsDecl<T>` actions position is load-bearing: T resolves from
* `init` in the first inference round, and the intersection then contextually
* types each mutator's draft parameter (context-sensitive functions defer),
* so call sites write `(d, x: X) => { ... }` with no draft annotation. If a
* future TS version breaks this single-literal inference, the design's
* documented fallback is currying (`defineStore(init).actions({...})`).
* @param decl - init lambda (fresh state per instance), optional persist key, actions table.
* @returns the store handle.
*/
export function defineStore<T, A extends ActionsDecl<T>>(
decl: StoreSpec<T, A> & { actions: A & ActionsDecl<T> }): EngineStoreHandle<T, A> {
return {
spec: decl,
create(scopeKey?: string): EngineStoreInstance<T, A> {
const persistKey = decl.persist === undefined
? undefined
: scopeKey === undefined ? decl.persist : `${decl.persist}.${scopeKey}`
const store = createSnapshotStore<T>(
decl.init(),
persistKey !== undefined ? { persist: { name: persistKey } } : undefined)
const actions = {} as Record<string, (...params: unknown[]) => void>
for (const key of Object.keys(decl.actions)) {
const mutate = decl.actions[key] as (draft: T, ...params: unknown[]) => void
actions[key] = (...params: unknown[]) => { store.update((draft) => { mutate(draft, ...params) }) }
}
return {
useSelector: store.useSelector,
actions: actions as BakedActions<T, A>,
getSnapshot: () => store.getSnapshot(),
subscribe: fn => store.subscribe(fn),
store,
clearPersisted: () => {
if (persistKey === undefined || typeof localStorage === 'undefined') return
try {
localStorage.removeItem(persistKey)
} catch {
// Storage failures (private mode, quota teardown races) only skip
// cleanup — the same non-fatal contract as attachPersistence.
}
},
}
},
}
}

View File

@@ -1,70 +1,121 @@
// @vitest-environment jsdom
/**
* Integration against the real ui-slots SlotCore (T1): the outlet's uSES
* pairing rides the real subscribe/getVersion/entries surfaces, and the
* whitelist narrows at compile time (expect-error negative samples).
* Integration against the real ui-slots SlotCore through a passthrough host:
* registrations go through the real register() (options form, children
* declaration), and the outlets ride the real subscribe/getVersion/entries/
* isLive surfaces — microtask-batched notifications, mutation-stable entry
* references (the cache axis), and ledger-fed stale bindings are the
* real-core semantics the fake-host suite cannot vouch for.
*/
import { describe, expect, it, vi } from 'vitest'
import { act, render } from '@testing-library/react'
import { SlotCore } from '@deepseek-ai/dsh-client-ui-slots'
import { scopedSlots } from '@deepseek-ai/dsh-client-web-react'
import { SlotCore, type PropsRenderSlots, type SlotRendererHost } from '@deepseek-ai/dsh-client-ui-slots'
import { createSlotRenderer, StaleAuthorizationError } from '@deepseek-ai/dsh-client-web-react'
declare module '@deepseek-ai/dsh-client-ui-slots' {
interface SlotMap {
'spec.single': { kind: 'single'; scope: 'root'; props: { label?: string } }
'spec.list': { kind: 'list'; scope: 'root'; props: object }
'spec.off-limits': { kind: 'single'; scope: 'root'; props: object }
// No 'root' merge: the aggregate client program already carries runtime's
// authoritative 'root' declaration (a private merge would TS2717-collide);
// only this suite's own test keys merge here.
'spec.single': { kind: 'single'; scope: 'root'; owner: { label?: string } }
'spec.list': { kind: 'list'; scope: 'root' }
}
}
describe('scopedSlots over the real SlotCore', () => {
it('renders registrations live: define, register, dispose back to fallback', async () => {
type FrameSlots = PropsRenderSlots<'spec.single' | 'spec.list'>
/** Passthrough host over the real core (store/session seats unused here). */
function hostOver(core: SlotCore): SlotRendererHost {
return {
subscribe: (key, fn) => core.subscribe(key, fn),
getVersion: (key) => core.getVersion(key),
entriesOf: (key) => core.entries(key),
specOf: (key) => core.specDynamic(key),
isLive: (entry) => core.isLive(entry),
storeOf: () => undefined,
sessions: {
list: { getSnapshot: () => ({}), subscribe: () => () => {} },
current: { getSnapshot: () => undefined, subscribe: () => () => {} },
cell: () => undefined,
},
}
}
/** Register the root frame (declaring both child keys) and mount the renderer. */
function mountFrame(core: SlotCore, body: (renderSlot: FrameSlots['renderSlot']) => React.ReactNode) {
const dispose = core.register({
name: 'root',
children: {
'spec.single': { kind: 'single', scope: 'root' },
'spec.list': { kind: 'list', scope: 'root' },
},
}, (props: FrameSlots) => <>{body(props.renderSlot)}</>)
const view = render(<>{createSlotRenderer().renderRoot(hostOver(core), {})}</>)
return { view, dispose }
}
describe('createSlotRenderer over the real SlotCore', () => {
it('renders registrations live through real microtask batching: register, dispose back to fallback', async () => {
const core = new SlotCore()
core.define('spec.single', { kind: 'single', scope: 'root' })
const slots = scopedSlots(core, 'spec.single')
const view = render(<>{slots.renderSlot('spec.single', {}, { fallback: <i>none</i> })}</>)
const { view } = mountFrame(core, (renderSlot) =>
renderSlot('spec.single', {}, { fallback: <i>none</i> }))
expect(view.container.textContent).toBe('none')
let dispose = () => {}
// The real core batches subscriber notification per microtask: async act.
await act(async () => { dispose = core.register('spec.single', ({ label }) => <b>{label ?? 'on'}</b>) })
await act(async () => {
dispose = core.register({ name: 'spec.single' }, ({ label }: { label?: string }) => <b>{label ?? 'on'}</b>)
})
expect(view.container.textContent).toBe('on')
await act(async () => { dispose(); dispose() }) // disposer is idempotent in the real core
expect(view.container.textContent).toBe('none')
})
it('passes owner props through and orders list entries', () => {
it('coalesces same-tick mutations into one notification (uSES pairing stays consistent)', async () => {
const core = new SlotCore()
core.define('spec.single', { kind: 'single', scope: 'root' })
core.define('spec.list', { kind: 'list', scope: 'root' })
core.register('spec.single', ({ label }) => <b>{label}</b>)
core.register('spec.list', () => <span>2</span>, { id: 'two', order: 2 })
core.register('spec.list', () => <span>1</span>, { id: 'one', order: 1 })
const slots = scopedSlots(core, 'spec.single', 'spec.list')
const view = render(
<>
{slots.renderSlot('spec.single', { label: 'owner' })}
{slots.renderSlot('spec.list', {})}
</>,
)
expect(view.container.textContent).toBe('owner12')
const notified = vi.fn()
core.subscribe('spec.list', notified)
const { view } = mountFrame(core, (renderSlot) => renderSlot('spec.list', {}))
await act(async () => {
core.register({ name: 'spec.list', id: 'two', order: 2 }, () => <span>2</span>)
core.register({ name: 'spec.list', id: 'one', order: 1 }, () => <span>1</span>)
})
expect(notified).toHaveBeenCalledTimes(1) // two same-tick mutations, one batch
expect(view.container.textContent).toBe('12')
})
it('fails loud when rendering a key that was never defined', () => {
it('passes owner props through and keeps sibling entries() references stable across mutations', async () => {
const core = new SlotCore()
const slots = scopedSlots(core, 'spec.single')
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
expect(() => render(<>{slots.renderSlot('spec.single', {})}</>)).toThrow(/before define/)
spy.mockRestore()
core.register({ name: 'root', children: {
'spec.single': { kind: 'single', scope: 'root' },
'spec.list': { kind: 'list', scope: 'root' },
} }, (props: FrameSlots) => <>
{props.renderSlot('spec.single', { label: 'owner' })}
{props.renderSlot('spec.list', {})}
</>)
core.register({ name: 'spec.single' }, ({ label }: { label?: string }) => <b>{label}</b>)
const view = render(<>{createSlotRenderer().renderRoot(hostOver(core), {})}</>)
expect(view.container.textContent).toBe('owner')
// A mutation on the sibling key leaves this key's entries() reference
// untouched (real-core stability the inject/renderSlot caches key on).
const before = core.entries('spec.single')
await act(async () => { core.register({ name: 'spec.list', id: 'l' }, () => <span>L</span>) })
expect(core.entries('spec.single')).toBe(before)
expect(view.container.textContent).toBe('ownerL')
})
it('narrows the whitelist at compile time and backstops at runtime', () => {
it('feeds stale bindings from the real ledger: a disposed registration throws off isLive', () => {
const core = new SlotCore()
core.define('spec.single', { kind: 'single', scope: 'root' })
core.define('spec.off-limits', { kind: 'single', scope: 'root' })
const slots = scopedSlots(core, 'spec.single')
// @ts-expect-error spec.off-limits is outside this ScopedSlots whitelist
expect(() => slots.renderSlot('spec.off-limits', {})).toThrow(/whitelist/)
// @ts-expect-error unknown keys are rejected even before whitelist narrowing
expect(() => slots.renderSlot('spec.nonexistent', {})).toThrow(/whitelist/)
let captured: FrameSlots['renderSlot'] | undefined
const { view, dispose } = mountFrame(core, (renderSlot) => {
captured = renderSlot
return null
})
expect(captured!('spec.single', {})).not.toBeUndefined() // live binding renders
// Unmount before disposing: an empty 'root' makes a LIVE root outlet
// rethrow boot-order (covered in the fake-host suite); the scenario here
// is a retained closure outliving both tree and registration.
view.unmount()
dispose()
expect(() => captured!('spec.single', {})).toThrow(StaleAuthorizationError)
})
})

View File

@@ -1,142 +1,415 @@
// @vitest-environment jsdom
/**
* createSlotRenderer machinery account over a behavioral fake host: root
* outlet + per-kind child outlets, standard-kit synthesis (renderSlot
* binding, session pair, global useSessions, store pair), inject execution
* point (inside component bodies, contained per entry) and parameter
* derivation, and cache granularity (entry x scope key). Ledger semantics
* (declaration conflicts, store instance accounting) belong to the runtime
* SlotsService suite, not here.
*/
import { describe, expect, it, vi } from 'vitest'
import { act, render } from '@testing-library/react'
import type {
FC } from 'react'
import type {
InjectFactory, RootBinding, SlotCore, SlotEntry, SlotEntryDef, SlotSpec,
} from '@deepseek-ai/dsh-client-ui-slots'
import type { ReactNode } from 'react'
import type { SlotEntryDef, SlotSpec, StoredEntry } from '@deepseek-ai/dsh-client-ui-slots'
import {
createSessionProvider, createSnapshotStore, RootBindingProvider, scopedSlots,
type SessionBinding, type SessionProviderDeps,
createSlotRenderer, defineStore, SessionProvider, SlotOwnershipError,
type RenderOpts, type SessionCell,
type SlotRendererHost, type StoreInstanceLike,
} from '@deepseek-ai/dsh-client-web-react'
type AnyProps = Record<string, unknown>
type RenderSlotFn = (key: string, owner: object, opts?: RenderOpts) => ReactNode
type DeclaredSpec = SlotSpec<SlotEntryDef>
/** Entry literal helper: fake entries default the mandatory options bag. */
const entryOf = (partial: Omit<StoredEntry, 'options'> & { options?: StoredEntry['options'] }): StoredEntry =>
({ options: {}, ...partial })
function observable<T>(initial: T) {
let value = initial
const subs = new Set<() => void>()
return {
getSnapshot: () => value,
subscribe: (fn: () => void) => { subs.add(fn); return () => { subs.delete(fn) } },
set: (next: T) => { value = next; for (const fn of [...subs]) fn() },
}
}
/**
* Behavioral SlotCore fake (the real ui-slots is still a T0 stub): registration
* mutates entries, bumps the key version, and notifies subscribers synchronously
* (batching semantics belong to fw-slots' core, not this package's outlet).
* Behavioral SlotRendererHost fake: registration mutates entries, bumps the
* key version, and notifies synchronously (batching semantics belong to the
* runtime host, not this package's outlets). Store instances resolve through
* the entry's real handle, cached per (entry x scope key) like the real
* ledger; session cells are identity-stable per id.
*/
function makeFakeCore() {
const specs = new Map<string, SlotSpec<SlotEntryDef>>()
const entries = new Map<string, SlotEntry<SlotEntryDef>[]>()
function makeHost() {
const entries = new Map<string, StoredEntry[]>()
const specs = new Map<string, DeclaredSpec>()
const versions = new Map<string, number>()
const subs = new Map<string, Set<() => void>>()
const live = new Set<StoredEntry>()
const storeCache = new Map<StoredEntry, Map<string, StoreInstanceLike>>()
const list = observable<{ ids: string[] }>({ ids: [] })
const current = observable<string | undefined>(undefined)
const cells = new Map<string, SessionCell>()
const bump = (key: string) => {
versions.set(key, (versions.get(key) ?? 0) + 1)
for (const fn of [...(subs.get(key) ?? [])]) fn()
}
const core = {
define: (key: string, spec: SlotSpec<SlotEntryDef>) => {
specs.set(key, spec)
bump(key)
return () => { specs.delete(key); bump(key) }
},
// Options widened beyond SlotOptions<SlotEntryDef>: fake keys ('fake.list')
// are not in SlotMap, so calls resolve against this signature and need the
// list/keyed fields the conditional type would otherwise narrow away.
register: (
key: string, component: FC<object>,
options: { key?: string; id?: string; order?: number; label?: string; inject?: InjectFactory<SlotEntryDef> } = {},
) => {
const list = entries.get(key) ?? []
const entry: SlotEntry<SlotEntryDef> = { component, options }
entries.set(key, [...list, entry])
bump(key)
return () => {
entries.set(key, (entries.get(key) ?? []).filter((e) => e !== entry))
bump(key)
}
},
entries: (key: string) => entries.get(key) ?? [],
spec: (key: string) => specs.get(key),
subscribe: (key: string, fn: () => void) => {
const host: SlotRendererHost = {
subscribe: (key, fn) => {
const set = subs.get(key) ?? new Set()
set.add(fn)
subs.set(key, set)
return () => { set.delete(fn) }
},
getVersion: (key: string) => versions.get(key) ?? 0,
onMutate: () => () => {},
getVersion: (key) => versions.get(key) ?? 0,
entriesOf: (key) => entries.get(key) ?? [],
specOf: (key) => specs.get(key),
isLive: (entry) => live.has(entry),
storeOf: (entry, scopeKey) => {
if (entry.store === undefined) return undefined
let perScope = storeCache.get(entry)
if (!perScope) {
perScope = new Map()
storeCache.set(entry, perScope)
}
const cacheKey = scopeKey ?? ''
let instance = perScope.get(cacheKey)
if (!instance) {
// Fake entries always carry engine handles (never factories), and the
// engine create() takes the scope key (persist suffixing).
const handle = entry.store as { create(scopeKey?: string): StoreInstanceLike }
instance = handle.create(scopeKey)
perScope.set(cacheKey, instance)
}
return instance
},
sessions: {
list,
current,
cell: (id) => cells.get(id),
},
}
return {
host,
list,
current,
declare: (key: string, spec: DeclaredSpec) => { specs.set(key, spec); bump(key) },
add: (key: string, partial: Omit<StoredEntry, 'options'> & { options?: StoredEntry['options'] }) => {
const entry = entryOf(partial)
entries.set(key, [...(entries.get(key) ?? []), entry])
live.add(entry)
bump(key)
return () => {
entries.set(key, (entries.get(key) ?? []).filter((e) => e !== entry))
live.delete(entry)
bump(key)
}
},
addSession: (id: string): SessionCell => {
const cell: SessionCell = { sessionId: id, useSession: { hookTag: id } }
cells.set(id, cell)
return cell
},
}
return core as unknown as SlotCore & typeof core
}
const useSelectorStub = (() => { throw new Error('unused in these specs') }) as never
type Fake = ReturnType<typeof makeHost>
const makeBinding = (sessionId: string): SessionBinding => ({
sessionId, session: { useSelector: useSelectorStub }, ctx: { tag: sessionId },
})
/** Mount ui under a SessionProvider bound to one switchable session. */
function sessionHarness(body: (id: string) => React.ReactNode, bindings: Record<string, SessionBinding>) {
const current = createSnapshotStore<{ id: string | undefined }>({ id: undefined })
const deps: SessionProviderDeps = {
useCurrent: () => current.useSelector((s) => s.id),
resolveBinding: (id) => bindings[id],
renderBody: body,
}
const Provider = createSessionProvider(deps)
return { current, Provider }
/** Mount a root entry whose component renders `body` with its kit renderSlot. */
function mountRoot(h: Fake, children: Record<string, DeclaredSpec>, body: (renderSlot: RenderSlotFn) => ReactNode) {
const dispose = h.add('root', {
component: (props: { renderSlot: RenderSlotFn }) => <>{body(props.renderSlot)}</>,
children,
})
const renderer = createSlotRenderer()
const view = render(<>{renderer.renderRoot(h.host, {})}</>)
return { view, dispose }
}
describe('scopedSlots basics', () => {
it('throws on renderSlot before define and on non-whitelisted keys', () => {
const core = makeFakeCore()
const slots = scopedSlots(core, 'fake.root' as never)
expect(() => slots.renderSlot('fake.session' as never, {})).toThrow(/whitelist/)
const SINGLE_ROOT: DeclaredSpec = { kind: 'single', scope: 'root' }
const SINGLE_SESSION: DeclaredSpec = { kind: 'single', scope: 'session' }
describe('root outlet', () => {
it('renders the root registration and fails loud when root is unregistered (boot order)', () => {
const h = makeHost()
h.add('root', { component: () => <b>shell</b> })
const renderer = createSlotRenderer()
const view = render(<>{renderer.renderRoot(h.host, {})}</>)
expect(view.container.textContent).toBe('shell')
const empty = makeHost()
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
expect(() => render(<>{slots.renderSlot('fake.root' as never, {})}</>)).toThrow(/before define/)
expect(() => render(<>{createSlotRenderer().renderRoot(empty.host, {})}</>))
.toThrow(/boot order/)
spy.mockRestore()
})
it('renders single-kind root slots, falls back when empty, live-updates on register/dispose', () => {
const core = makeFakeCore()
core.define('fake.root', { kind: 'single', scope: 'root' })
const slots = scopedSlots(core, 'fake.root' as never)
const view = render(<>{slots.renderSlot('fake.root' as never, {}, { fallback: <i>none</i> })}</>)
it('passes renderRoot owner props into the root component', () => {
const h = makeHost()
h.add('root', { component: ({ tag }: { tag?: string }) => <b>{tag}</b> })
const view = render(<>{createSlotRenderer().renderRoot(h.host, { tag: 'OWNER' })}</>)
expect(view.container.textContent).toBe('OWNER')
})
})
describe('child outlets and the renderSlot binding', () => {
it('renders declared single slots live: fallback when empty, register, dispose back', () => {
const h = makeHost()
h.declare('k.single', SINGLE_ROOT)
const { view } = mountRoot(h, { 'k.single': SINGLE_ROOT },
(renderSlot) => renderSlot('k.single', {}, { fallback: <i>none</i> }))
expect(view.container.textContent).toBe('none')
let dispose = () => {}
act(() => { dispose = core.register('fake.root', () => <b>SB</b>) })
act(() => { dispose = h.add('k.single', { component: () => <b>SB</b> }) })
expect(view.container.textContent).toBe('SB')
act(() => { dispose() })
expect(view.container.textContent).toBe('none')
})
it('renders list slots in order, honors only-filter, keyed slots dispatch by entryKey', () => {
const core = makeFakeCore()
core.define('fake.list', { kind: 'list', scope: 'root' })
core.define('fake.keyed', { kind: 'keyed', scope: 'root' })
core.register('fake.list', () => <span>b</span>, { id: 'b', order: 2 })
core.register('fake.list', () => <span>a</span>, { id: 'a', order: 1 })
core.register('fake.keyed', () => <span>goal</span>, { key: 'goal' })
const slots = scopedSlots(core, 'fake.list' as never, 'fake.keyed' as never)
const list = render(<>{slots.renderSlot('fake.list' as never, {})}</>)
expect(list.container.textContent).toBe('ab')
const only = render(<>{slots.renderSlot('fake.list' as never, {}, { only: 'b' })}</>)
expect(only.container.textContent).toBe('b')
const hit = render(<>{slots.renderSlot('fake.keyed' as never, {}, { entryKey: 'goal' })}</>)
expect(hit.container.textContent).toBe('goal')
const miss = render(
<>{slots.renderSlot('fake.keyed' as never, {}, { entryKey: 'nope', fallback: <i>fb</i> })}</>)
expect(miss.container.textContent).toBe('fb')
it('renders an undeclared key as empty (declaring entry unloaded = natural blank, not a crash)', () => {
const h = makeHost()
const { view } = mountRoot(h, { 'k.single': SINGLE_ROOT },
(renderSlot) => <main>{renderSlot('k.single', {}, { fallback: <i>fb</i> })}</main>)
// Declared by children (authorization) but absent from the ledger (specOf
// undefined): the outlet renders nothing, not even the fallback path's spec dispatch.
expect(view.container.querySelector('main')!.textContent).toBe('')
})
it('contains a throwing root inject factory to its own entry (P1 whiteout regression)', () => {
const core = makeFakeCore()
core.define('fake.list', { kind: 'list', scope: 'root' })
core.register('fake.list', () => <span>never</span>, {
id: 'bad', order: 1,
inject: (() => { throw new Error('inject boom') }) as unknown as InjectFactory<SlotEntryDef>,
it('orders list entries, honors only-filter, dispatches keyed entries by entryKey', () => {
const h = makeHost()
h.declare('k.list', { kind: 'list', scope: 'root' })
h.declare('k.keyed', { kind: 'keyed', scope: 'root' })
h.add('k.list', { component: () => <span>b</span>, options: { id: 'b', order: 2 } })
h.add('k.list', { component: () => <span>a</span>, options: { id: 'a', order: 1 } })
h.add('k.keyed', { component: () => <span>goal</span>, options: { key: 'goal' } })
const children = { 'k.list': { kind: 'list', scope: 'root' } as DeclaredSpec, 'k.keyed': { kind: 'keyed', scope: 'root' } as DeclaredSpec }
const { view } = mountRoot(h, children, (renderSlot) => <>
<main>{renderSlot('k.list', {})}</main>
<aside>{renderSlot('k.list', {}, { only: 'b' })}</aside>
<nav>{renderSlot('k.keyed', {}, { entryKey: 'goal' })}</nav>
<footer>{renderSlot('k.keyed', {}, { entryKey: 'nope', fallback: <i>fb</i> })}</footer>
</>)
expect(view.container.querySelector('main')!.textContent).toBe('ab')
expect(view.container.querySelector('aside')!.textContent).toBe('b')
expect(view.container.querySelector('nav')!.textContent).toBe('goal')
expect(view.container.querySelector('footer')!.textContent).toBe('fb')
})
it('keeps the binding identity-stable across re-renders and throws SlotOwnershipError off-declaration', () => {
const h = makeHost()
h.declare('k.single', SINGLE_ROOT)
const seen: RenderSlotFn[] = []
mountRoot(h, { 'k.single': SINGLE_ROOT }, (renderSlot) => {
seen.push(renderSlot)
return renderSlot('k.single', {})
})
core.register('fake.list', () => <span>alive</span>, { id: 'ok', order: 2 })
const slots = scopedSlots(core, 'fake.list' as never)
const root: RootBinding = { ctx: {} }
// Bump the 'root' key to force a root-entry re-render (the single-kind
// outlet only reads entries[0], so the extra entry is inert).
act(() => { h.add('root', { component: () => null }) })
expect(seen.length).toBeGreaterThan(1)
expect(seen.at(-1)).toBe(seen[0])
expect(() => seen[0]!('k.undeclared', {})).toThrow(SlotOwnershipError)
})
it('isolates a crashing entry without collapsing siblings', () => {
const h = makeHost()
h.declare('k.list', { kind: 'list', scope: 'root' })
h.add('k.list', { component: () => { throw new Error('entry boom') }, options: { id: 'bad', order: 1 } })
h.add('k.list', { component: () => <span>alive</span>, options: { id: 'ok', order: 2 } })
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
const view = render(
<RootBindingProvider value={root}>
<main>{slots.renderSlot('fake.list' as never, {})}</main>
</RootBindingProvider>,
)
const { view } = mountRoot(h, { 'k.list': { kind: 'list', scope: 'root' } },
(renderSlot) => renderSlot('k.list', {}))
spy.mockRestore()
expect(view.container.textContent).toBe('alive')
expect(view.container.querySelector('[data-slot-error]')).not.toBeNull()
})
})
describe('standard-kit synthesis', () => {
it('delivers a live useSessions hook to every slot component', () => {
const h = makeHost()
h.declare('k.single', SINGLE_ROOT)
h.add('k.single', {
component: ({ useSessions }: { useSessions: <S>(sel: (s: { ids: string[] }) => S) => S }) =>
<b>{useSessions((s) => s.ids.length)}</b>,
})
const { view } = mountRoot(h, { 'k.single': SINGLE_ROOT }, (renderSlot) => renderSlot('k.single', {}))
expect(view.container.textContent).toBe('0')
act(() => { h.list.set({ ids: ['a', 'b'] }) })
expect(view.container.textContent).toBe('2')
})
it('delivers the session pair (useSession identity + sessionId) under SessionProvider', () => {
const h = makeHost()
h.declare('k.session', SINGLE_SESSION)
const cell = h.addSession('s1')
const seen: AnyProps[] = []
h.add('k.session', { component: (props: object) => { seen.push(props as AnyProps); return null } })
mountRoot(h, { 'k.session': SINGLE_SESSION }, (renderSlot) => (
<SessionProvider empty={() => <i>empty</i>}>
{() => renderSlot('k.session', {})}
</SessionProvider>
))
act(() => { h.current.set('s1') })
const props = seen.at(-1)!
expect(props['useSession']).toBe(cell.useSession)
expect(props['sessionId']).toBe('s1')
})
it('fails loud when a session slot renders outside SessionProvider', () => {
const h = makeHost()
h.declare('k.session', SINGLE_SESSION)
h.add('k.session', { component: () => <b>x</b> })
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
expect(() => mountRoot(h, { 'k.session': SINGLE_SESSION },
(renderSlot) => renderSlot('k.session', {}))).toThrow(/outside SessionProvider/)
spy.mockRestore()
})
it('delivers the store pair for store-declaring entries and writes through baked actions', () => {
const h = makeHost()
h.declare('k.single', SINGLE_ROOT)
const handle = defineStore({
init: () => ({ n: 0 }),
actions: { inc: (d) => { d.n += 1 } },
})
let bump = () => {}
h.add('k.single', {
component: ({ useStore, actions }: {
useStore: <S>(sel: (s: { n: number }) => S) => S
actions: { inc: () => void }
}) => {
bump = actions.inc
return <b>{useStore((s) => s.n)}</b>
},
store: handle,
})
const { view } = mountRoot(h, { 'k.single': SINGLE_ROOT }, (renderSlot) => renderSlot('k.single', {}))
expect(view.container.textContent).toBe('0')
act(() => { bump() })
expect(view.container.textContent).toBe('1')
})
it('resolves session-slot stores per scope key: values survive a switch-away and back', () => {
const h = makeHost()
h.declare('k.session', SINGLE_SESSION)
h.addSession('s1')
h.addSession('s2')
const handle = defineStore({
init: () => ({ draft: '' }),
actions: { setDraft: (d, text: string) => { d.draft = text } },
})
let setDraft: (text: string) => void = () => {}
h.add('k.session', {
component: ({ useStore, actions }: {
useStore: <S>(sel: (s: { draft: string }) => S) => S
actions: { setDraft: (text: string) => void }
}) => {
setDraft = actions.setDraft
return <b>{useStore((s) => s.draft) || '(blank)'}</b>
},
store: handle,
})
const { view } = mountRoot(h, { 'k.session': SINGLE_SESSION }, (renderSlot) => (
<SessionProvider>{() => renderSlot('k.session', {})}</SessionProvider>
))
act(() => { h.current.set('s1') })
act(() => { setDraft('draft-one') })
expect(view.container.textContent).toBe('draft-one')
act(() => { h.current.set('s2') })
expect(view.container.textContent).toBe('(blank)') // distinct instance per session
act(() => { h.current.set('s1') })
expect(view.container.textContent).toBe('draft-one') // same scope key = same instance
})
})
describe('inject: execution point, parameter derivation, cache granularity', () => {
it('root inject runs once per entry with no arguments (no store declared)', () => {
const h = makeHost()
h.declare('k.single', SINGLE_ROOT)
const inject = vi.fn(() => ({ tag: 'FROM-INJECT' }))
h.add('k.single', { component: ({ tag }: { tag?: string }) => <b>{tag}</b>, inject })
const { view } = mountRoot(h, { 'k.single': SINGLE_ROOT }, (renderSlot) => renderSlot('k.single', {}))
expect(view.container.textContent).toBe('FROM-INJECT')
act(() => { h.add('k.single', { component: () => null }) }) // sibling bump re-renders the outlet
expect(inject).toHaveBeenCalledTimes(1)
expect(inject).toHaveBeenCalledWith()
})
it('session inject receives sessionId and caches per (entry x session): switch-back reuses', () => {
const h = makeHost()
h.declare('k.session', SINGLE_SESSION)
h.addSession('s1')
h.addSession('s2')
const inject = vi.fn((sessionId: string) => ({ sid: sessionId }))
h.add('k.session', {
component: ({ sid }: { sid?: string }) => <b>{sid}</b>,
inject: inject as unknown as StoredEntry['inject'],
})
const { view } = mountRoot(h, { 'k.session': SINGLE_SESSION }, (renderSlot) => (
<SessionProvider>{() => renderSlot('k.session', {})}</SessionProvider>
))
act(() => { h.current.set('s1') })
expect(view.container.textContent).toBe('s1')
expect(inject).toHaveBeenCalledTimes(1)
expect(inject).toHaveBeenLastCalledWith('s1')
act(() => { h.current.set('s2') })
expect(view.container.textContent).toBe('s2')
expect(inject).toHaveBeenCalledTimes(2)
act(() => { h.current.set('s1') }) // back: (entry x cell) cache hit
expect(view.container.textContent).toBe('s1')
expect(inject).toHaveBeenCalledTimes(2)
})
it('store-declaring entries get baked actions appended to the inject parameters', () => {
const h = makeHost()
h.declare('k.single', SINGLE_ROOT)
h.declare('k.session', SINGLE_SESSION)
h.addSession('s1')
const handle = defineStore({ init: () => ({ n: 0 }), actions: { inc: (d) => { d.n += 1 } } })
const rootInject = vi.fn((actions: { inc: () => void }) => ({ viaRoot: actions }))
const sessionInject = vi.fn((sessionId: string, actions: { inc: () => void }) => ({ sid: sessionId, viaSession: actions }))
const seenRoot: AnyProps[] = []
const seenSession: AnyProps[] = []
h.add('k.single', {
component: (props: object) => { seenRoot.push(props as AnyProps); return null },
inject: rootInject as unknown as StoredEntry['inject'],
store: handle,
})
h.add('k.session', {
component: (props: object) => { seenSession.push(props as AnyProps); return null },
inject: sessionInject as unknown as StoredEntry['inject'],
store: handle,
})
mountRoot(h, { 'k.single': SINGLE_ROOT, 'k.session': SINGLE_SESSION }, (renderSlot) => <>
{renderSlot('k.single', {})}
<SessionProvider>{() => renderSlot('k.session', {})}</SessionProvider>
</>)
act(() => { h.current.set('s1') })
// The inject-received actions are the same baked callbacks the component
// gets as props.actions (one instance per entry x scope key).
expect(rootInject).toHaveBeenCalledTimes(1)
expect(seenRoot.at(-1)!['viaRoot']).toBe(seenRoot.at(-1)!['actions'])
expect(sessionInject).toHaveBeenCalledTimes(1)
expect(sessionInject.mock.calls[0]![0]).toBe('s1')
expect(seenSession.at(-1)!['viaSession']).toBe(seenSession.at(-1)!['actions'])
})
it('contains a throwing inject factory to its own entry (runs inside the component body)', () => {
const h = makeHost()
h.declare('k.list', { kind: 'list', scope: 'root' })
h.add('k.list', {
component: () => <span>never</span>,
options: { id: 'bad', order: 1 },
inject: () => { throw new Error('inject boom') },
})
h.add('k.list', { component: () => <span>alive</span>, options: { id: 'ok', order: 2 } })
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
const { view } = mountRoot(h, { 'k.list': { kind: 'list', scope: 'root' } },
(renderSlot) => <main>{renderSlot('k.list', {})}</main>)
spy.mockRestore()
// The failing entry blacks out alone; the sibling and the tree above survive.
expect(view.container.querySelector('main')).not.toBeNull()
@@ -144,131 +417,20 @@ describe('scopedSlots basics', () => {
expect(view.container.querySelector('[data-slot-error]')).not.toBeNull()
})
it('contains a throwing session inject factory to its own entry', () => {
const core = makeFakeCore()
core.define('fake.session', { kind: 'single', scope: 'session' })
core.register('fake.session', () => <span>never</span>, {
inject: (() => { throw new Error('session inject boom') }) as unknown as InjectFactory<SlotEntryDef>,
it('merges kit, inject, and owner props with owner winning', () => {
const h = makeHost()
h.declare('k.single', SINGLE_ROOT)
const seen: AnyProps[] = []
h.add('k.single', {
component: (props: object) => { seen.push(props as AnyProps); return null },
inject: () => ({ fromInject: 'inject', shared: 'inject' }),
})
const slots = scopedSlots(core, 'fake.session' as never)
const bindings = { s1: makeBinding('s1') }
const { current, Provider } = sessionHarness(
(id) => <main data-shell={id}>{slots.renderSlot('fake.session' as never, {})}</main>, bindings)
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
const view = render(<Provider />)
act(() => { current.update((d) => { d.id = 's1' }) })
spy.mockRestore()
expect(view.container.querySelector('[data-shell]')).not.toBeNull()
expect(view.container.querySelector('[data-slot-error]')).not.toBeNull()
})
it('isolates a crashing entry without collapsing siblings', () => {
const core = makeFakeCore()
core.define('fake.list', { kind: 'list', scope: 'root' })
core.register('fake.list', () => { throw new Error('entry boom') }, { id: 'bad', order: 1 })
core.register('fake.list', () => <span>alive</span>, { id: 'ok', order: 2 })
const slots = scopedSlots(core, 'fake.list' as never)
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
const view = render(<>{slots.renderSlot('fake.list' as never, {})}</>)
spy.mockRestore()
expect(view.container.textContent).toBe('alive')
expect(view.container.querySelector('[data-slot-error]')).not.toBeNull()
})
})
describe('inject caching and props merge', () => {
it('root inject runs once per entry and receives the root binding ctx', () => {
const core = makeFakeCore()
core.define('fake.root', { kind: 'single', scope: 'root' })
const inject = vi.fn((b: RootBinding) => ({ tag: (b.ctx as { tag: string }).tag }))
core.register('fake.root', ({ tag }: { tag?: string }) => <b>{tag}</b>,
{ inject: inject as unknown as InjectFactory<SlotEntryDef> })
const slots = scopedSlots(core, 'fake.root' as never)
const root: RootBinding = { ctx: { tag: 'ROOT' } }
const view = render(
<RootBindingProvider value={root}>
{slots.renderSlot('fake.root' as never, {})}
</RootBindingProvider>,
)
expect(view.container.textContent).toBe('ROOT')
view.rerender(
<RootBindingProvider value={root}>
{slots.renderSlot('fake.root' as never, {})}
</RootBindingProvider>,
)
expect(inject).toHaveBeenCalledTimes(1)
})
it('root slots with inject throw without RootBindingProvider; plain entries do not need it', () => {
const core = makeFakeCore()
core.define('fake.root', { kind: 'single', scope: 'root' })
core.register('fake.root', () => <b>plain</b>)
const slots = scopedSlots(core, 'fake.root' as never)
const view = render(<>{slots.renderSlot('fake.root' as never, {})}</>)
expect(view.container.textContent).toBe('plain')
const core2 = makeFakeCore()
core2.define('fake.root', { kind: 'single', scope: 'root' })
core2.register('fake.root', () => <b>x</b>,
{ inject: (() => ({})) as unknown as InjectFactory<SlotEntryDef> })
const slots2 = scopedSlots(core2, 'fake.root' as never)
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
expect(() => render(<>{slots2.renderSlot('fake.root' as never, {})}</>))
.toThrow(/RootBindingProvider/)
spy.mockRestore()
})
it('session inject caches per (entry x binding): session switch re-invokes, switch-back reuses', () => {
const core = makeFakeCore()
core.define('fake.session', { kind: 'single', scope: 'session' })
const inject = vi.fn((b: { sessionId: string }) => ({ sid: b.sessionId }))
core.register('fake.session', ({ sid }: { sid?: string }) => <b>{sid}</b>,
{ inject: inject as unknown as InjectFactory<SlotEntryDef> })
const slots = scopedSlots(core, 'fake.session' as never)
const bindings = { s1: makeBinding('s1'), s2: makeBinding('s2') }
const { current, Provider } = sessionHarness(
() => slots.renderSlot('fake.session' as never, {}), bindings)
const view = render(<Provider />)
act(() => { current.update((d) => { d.id = 's1' }) })
expect(view.container.textContent).toBe('s1')
expect(inject).toHaveBeenCalledTimes(1)
act(() => { current.update((d) => { d.id = 's2' }) })
expect(view.container.textContent).toBe('s2')
expect(inject).toHaveBeenCalledTimes(2)
act(() => { current.update((d) => { d.id = 's1' }) }) // back: cache hit
expect(view.container.textContent).toBe('s1')
expect(inject).toHaveBeenCalledTimes(2)
})
it('session slots receive standard useSession injection and owner props win the merge', () => {
const core = makeFakeCore()
core.define('fake.session', { kind: 'single', scope: 'session' })
const seen: Record<string, unknown>[] = []
core.register('fake.session', (props: object) => {
seen.push(props as Record<string, unknown>)
return null
}, { inject: (() => ({ fromInject: 'inject', shared: 'inject' })) as unknown as InjectFactory<SlotEntryDef> })
const slots = scopedSlots(core, 'fake.session' as never)
const bindings = { s1: makeBinding('s1') }
const { current, Provider } = sessionHarness(
() => slots.renderSlot('fake.session' as never, { owner: 'owner', shared: 'owner' } as never), bindings)
render(<Provider />)
act(() => { current.update((d) => { d.id = 's1' }) })
mountRoot(h, { 'k.single': SINGLE_ROOT },
(renderSlot) => renderSlot('k.single', { owner: 'owner', shared: 'owner' }))
const props = seen.at(-1)!
expect(props.useSession).toBe(bindings.s1.session.useSelector)
expect(props.fromInject).toBe('inject')
expect(props.owner).toBe('owner')
expect(props.shared).toBe('owner') // three-source merge: owner overrides inject
})
it('session slots outside a SessionProvider fail loud', () => {
const core = makeFakeCore()
core.define('fake.session', { kind: 'single', scope: 'session' })
core.register('fake.session', () => <b>x</b>)
const slots = scopedSlots(core, 'fake.session' as never)
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
expect(() => render(<>{slots.renderSlot('fake.session' as never, {})}</>))
.toThrow(/outside SessionProvider/)
spy.mockRestore()
expect(typeof props['useSessions']).toBe('function') // kit always present
expect(props['fromInject']).toBe('inject')
expect(props['owner']).toBe('owner')
expect(props['shared']).toBe('owner') // owner overrides inject
})
})

View File

@@ -1,106 +1,143 @@
// @vitest-environment jsdom
/**
* SessionProvider behavior account (render-prop form, framework-wired):
* empty/body branching off the host's current-session source, key={sessionId}
* remount semantics, and cell delivery observed through a session slot's
* standard kit — never through the internal context objects (BindingContext
* does not leave the package).
*/
import { useEffect, useRef } from 'react'
import { describe, expect, it, vi } from 'vitest'
import { act, render } from '@testing-library/react'
import type { RootBinding } from '@deepseek-ai/dsh-client-ui-slots'
import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots'
import {
createSessionProvider, createSnapshotStore, RootBindingProvider,
useRootBinding, useSessionBinding,
type SessionBinding, type SessionProviderDeps,
createSlotRenderer, SessionProvider,
type SessionCell, type SlotRendererHost,
} from '@deepseek-ai/dsh-client-web-react'
const makeBinding = (sessionId: string): SessionBinding => ({
sessionId,
session: { useSelector: (() => { throw new Error('unused') }) as never },
ctx: { tag: sessionId },
})
function setup(bindings: Record<string, SessionBinding>) {
const current = createSnapshotStore<{ id: string | undefined }>({ id: undefined })
const resolveBinding = vi.fn((id: string) => bindings[id])
const seen: { id: string; binding: SessionBinding; mountCount: number }[] = []
let mounts = 0
function Body({ id }: { id: string }) {
const binding = useSessionBinding()
const mountRef = useRef(0)
useEffect(() => { mounts += 1; mountRef.current = mounts }, [])
seen.push({ id, binding, mountCount: mountRef.current })
return <div data-testid="body">{id}</div>
function observable<T>(initial: T) {
let value = initial
const subs = new Set<() => void>()
return {
getSnapshot: () => value,
subscribe: (fn: () => void) => { subs.add(fn); return () => { subs.delete(fn) } },
set: (next: T) => { value = next; for (const fn of [...subs]) fn() },
}
const deps: SessionProviderDeps = {
useCurrent: () => current.useSelector((s) => s.id),
resolveBinding,
renderBody: (id) => <Body id={id} />,
}
const SessionProvider = createSessionProvider(deps)
return { current, resolveBinding, SessionProvider, seen, mountCount: () => mounts }
}
describe('createSessionProvider', () => {
it('renders empty without a current session and switches to the body on select', () => {
const { current, SessionProvider } = setup({ s1: makeBinding('s1') })
const view = render(<SessionProvider renderEmpty={() => <span>empty</span>} />)
/**
* Minimal host: SessionProvider only reads sessions.current/cell, but it must
* render inside the renderer tree (HostContext), so the harness mounts a real
* root entry whose body is the test's render-prop provider.
*/
function makeHost(bodies: { root: (rp: (key: string, owner: object) => React.ReactNode) => React.ReactNode }) {
const current = observable<string | undefined>(undefined)
const cells = new Map<string, SessionCell>()
const sessionEntries: StoredEntry[] = []
const rootEntry: StoredEntry = {
component: (props: { renderSlot: (key: string, owner: object) => React.ReactNode }) =>
<>{bodies.root(props.renderSlot)}</>,
options: {},
children: { 'k.session': { kind: 'single', scope: 'session' } },
}
const host: SlotRendererHost = {
subscribe: () => () => {},
getVersion: () => 0,
entriesOf: (key) => key === 'root' ? [rootEntry] : sessionEntries,
specOf: (key) => key === 'k.session' ? { kind: 'single', scope: 'session' } : undefined,
isLive: () => true,
storeOf: () => undefined,
sessions: {
list: observable<unknown>({ ids: [] }),
current,
cell: (id) => cells.get(id),
},
}
return {
host,
current,
addSession: (id: string) => {
const cell: SessionCell = { sessionId: id, useSession: { hookTag: id } }
cells.set(id, cell)
return cell
},
registerSession: (entry: StoredEntry) => { sessionEntries.push(entry) },
}
}
describe('SessionProvider', () => {
it('renders empty without a current session, switches to the body on select, falls back on an unresolvable id', () => {
const h = makeHost({
root: () => (
<SessionProvider empty={() => <span>empty</span>}>
{(id) => <div data-testid="body">{id}</div>}
</SessionProvider>
),
})
h.addSession('s1')
const view = render(<>{createSlotRenderer().renderRoot(h.host, {})}</>)
expect(view.container.textContent).toBe('empty')
act(() => { current.update((d) => { d.id = 's1' }) })
act(() => { h.current.set('s1') })
expect(view.container.textContent).toBe('s1')
act(() => { h.current.set('ghost') }) // listed nowhere: cell() misses
expect(view.container.textContent).toBe('empty')
})
it('renders null empty state when renderEmpty is omitted', () => {
const { SessionProvider } = setup({})
const view = render(<SessionProvider />)
it('renders null empty state when the empty prop is omitted', () => {
const h = makeHost({
root: () => <SessionProvider>{(id) => <b>{id}</b>}</SessionProvider>,
})
const view = render(<>{createSlotRenderer().renderRoot(h.host, {})}</>)
expect(view.container.textContent).toBe('')
})
it('falls back to empty when the binding does not resolve', () => {
const { current, SessionProvider } = setup({})
const view = render(<SessionProvider renderEmpty={() => <span>empty</span>} />)
act(() => { current.update((d) => { d.id = 'ghost' }) })
expect(view.container.textContent).toBe('empty')
it('remounts the body on session switch (key semantics) but not on unrelated re-renders', () => {
let mounts = 0
function Body({ id }: { id: string }) {
const mounted = useRef(false)
useEffect(() => {
/* v8 ignore next -- strict-mode double-invoke guard, not a branch under test */
if (!mounted.current) { mounted.current = true; mounts += 1 }
}, [])
return <div>{id}</div>
}
const h = makeHost({
root: () => <SessionProvider>{(id) => <Body id={id} />}</SessionProvider>,
})
h.addSession('s1')
h.addSession('s2')
const view = render(<>{createSlotRenderer().renderRoot(h.host, {})}</>)
act(() => { h.current.set('s1') })
const afterS1 = mounts
act(() => { h.current.set('s2') })
expect(mounts).toBe(afterS1 + 1)
const afterS2 = mounts
view.rerender(<>{createSlotRenderer().renderRoot(h.host, {})}</>)
expect(mounts).toBe(afterS2)
})
it('passes the resolved binding through context and remounts on session switch', () => {
const bindings = { s1: makeBinding('s1'), s2: makeBinding('s2') }
const { current, SessionProvider, seen, mountCount } = setup(bindings)
render(<SessionProvider />)
act(() => { current.update((d) => { d.id = 's1' }) })
expect(seen.at(-1)!.binding).toBe(bindings.s1)
const mountsAfterS1 = mountCount()
act(() => { current.update((d) => { d.id = 's2' }) })
expect(seen.at(-1)!.binding).toBe(bindings.s2)
// key={id} semantics: switching sessions remounts the body subtree.
expect(mountCount()).toBe(mountsAfterS1 + 1)
it('delivers the resolved cell to session slots under it (observable behavior, not context internals)', () => {
const seen: Record<string, unknown>[] = []
const h = makeHost({
root: (renderSlot) => <SessionProvider>{() => renderSlot('k.session', {})}</SessionProvider>,
})
const s1 = h.addSession('s1')
const s2 = h.addSession('s2')
h.registerSession({ component: (props: object) => { seen.push(props as Record<string, unknown>); return null }, options: {} })
render(<>{createSlotRenderer().renderRoot(h.host, {})}</>)
act(() => { h.current.set('s1') })
expect(seen.at(-1)!['useSession']).toBe(s1.useSession)
expect(seen.at(-1)!['sessionId']).toBe('s1')
act(() => { h.current.set('s2') })
expect(seen.at(-1)!['useSession']).toBe(s2.useSession)
expect(seen.at(-1)!['sessionId']).toBe('s2')
})
it('does not remount the body when unrelated renders happen on the same session', () => {
const bindings = { s1: makeBinding('s1') }
const { current, SessionProvider, mountCount } = setup(bindings)
const view = render(<SessionProvider />)
act(() => { current.update((d) => { d.id = 's1' }) })
const mounts = mountCount()
view.rerender(<SessionProvider />)
expect(mountCount()).toBe(mounts)
})
})
describe('binding contexts', () => {
it('useSessionBinding throws outside a SessionProvider subtree', () => {
it('fails loud when mounted outside the renderer tree (no host channel)', () => {
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
function Naked() { useSessionBinding(); return null }
expect(() => render(<Naked />)).toThrow(/outside SessionProvider/)
spy.mockRestore()
})
it('RootBindingProvider supplies the root binding; absence throws', () => {
const root: RootBinding = { ctx: { tag: 'root' } }
let got: RootBinding | undefined
function Probe() { got = useRootBinding(); return null }
render(<RootBindingProvider value={root}><Probe /></RootBindingProvider>)
expect(got).toBe(root)
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
expect(() => render(<Probe />)).toThrow(/RootBindingProvider/)
expect(() => render(
<SessionProvider>{(id) => <b>{id}</b>}</SessionProvider>,
)).toThrow(/outside the installed renderer tree/)
spy.mockRestore()
})
})

View File

@@ -0,0 +1,136 @@
// @vitest-environment jsdom
/**
* Stale renderSlot bindings (slot terminal design §9): a binding dies with
* its entry — a retained closure invoked after the entry's disposal throws
* StaleAuthorizationError off the ledger check, and an HMR-style reload (new
* entry, same key) mints a NEW binding rather than reviving the old one.
*/
import { describe, expect, it } from 'vitest'
import { act, render } from '@testing-library/react'
import type { ReactNode } from 'react'
import type { SlotEntryDef, SlotSpec, StoredEntry } from '@deepseek-ai/dsh-client-ui-slots'
import {
createSlotRenderer, StaleAuthorizationError,
type RenderOpts, type SlotRendererHost,
} from '@deepseek-ai/dsh-client-web-react'
type RenderSlotFn = (key: string, owner: object, opts?: RenderOpts) => ReactNode
type DeclaredSpec = SlotSpec<SlotEntryDef>
/** Ledger-shaped fake: add/dispose maintain the live set the way the runtime ledger does. */
function makeHost() {
const entries = new Map<string, StoredEntry[]>()
const versions = new Map<string, number>()
const subs = new Map<string, Set<() => void>>()
const live = new Set<StoredEntry>()
const bump = (key: string) => {
versions.set(key, (versions.get(key) ?? 0) + 1)
for (const fn of [...(subs.get(key) ?? [])]) fn()
}
const host: SlotRendererHost = {
subscribe: (key, fn) => {
const set = subs.get(key) ?? new Set()
set.add(fn)
subs.set(key, set)
return () => { set.delete(fn) }
},
getVersion: (key) => versions.get(key) ?? 0,
entriesOf: (key) => entries.get(key) ?? [],
specOf: () => ({ kind: 'single', scope: 'root' }),
isLive: (entry) => live.has(entry),
storeOf: () => undefined,
sessions: {
list: { getSnapshot: () => ({}), subscribe: () => () => {} },
current: { getSnapshot: () => undefined, subscribe: () => () => {} },
cell: () => undefined,
},
}
return {
host,
add: (key: string, entry: StoredEntry) => {
entries.set(key, [...(entries.get(key) ?? []), entry])
live.add(entry)
bump(key)
return () => {
entries.set(key, (entries.get(key) ?? []).filter((e) => e !== entry))
live.delete(entry)
bump(key)
}
},
}
}
const CHILD: DeclaredSpec = { kind: 'single', scope: 'root' }
/**
* Mount a root entry that leaks its binding to the test, then render. The
* returned dispose unmounts the view FIRST: an empty 'root' makes the live
* root outlet rethrow its boot-order failure (fail-loud, covered in the
* scoped-slots suite); the retained-closure scenario under test here is a
* dead entry whose binding outlives the tree.
*/
function mountCapturing(h: ReturnType<typeof makeHost>) {
let captured: RenderSlotFn | undefined
const entry: StoredEntry = {
component: (props: { renderSlot: RenderSlotFn }) => {
captured = props.renderSlot
return null
},
options: {},
children: { 'k.child': CHILD },
}
const disposeEntry = h.add('root', entry)
const view = render(<>{createSlotRenderer().renderRoot(h.host, {})}</>)
return {
binding: captured!,
entry,
dispose: () => {
view.unmount()
disposeEntry()
},
}
}
describe('stale authorization', () => {
it('a live binding renders; the same closure throws after its entry is disposed', () => {
const h = makeHost()
const { binding, dispose } = mountCapturing(h)
expect(binding('k.child', {})).not.toBeUndefined() // live: returns an element
act(() => { dispose() })
expect(() => binding('k.child', {})).toThrow(StaleAuthorizationError)
expect(() => binding('k.child', {})).toThrow(/disposed registration/)
})
it('stale check precedes the ownership check: a dead binding throws stale even for undeclared keys', () => {
const h = makeHost()
const { binding, dispose } = mountCapturing(h)
act(() => { dispose() })
// Were ownership checked first this would be SlotOwnershipError; the dead
// entry must fail on liveness regardless of the key asked for.
expect(() => binding('k.undeclared', {})).toThrow(StaleAuthorizationError)
})
it('HMR reload (same key, new entry) mints a fresh binding; the old one stays dead', () => {
const h = makeHost()
const first = mountCapturing(h)
act(() => { first.dispose() })
// Reload: a new entry object for the same slot key (new registration identity).
let secondBinding: RenderSlotFn | undefined
const secondEntry: StoredEntry = {
component: (props: { renderSlot: RenderSlotFn }) => {
secondBinding = props.renderSlot
return null
},
options: {},
children: { 'k.child': CHILD },
}
h.add('root', secondEntry)
render(<>{createSlotRenderer().renderRoot(h.host, {})}</>)
expect(secondBinding).toBeDefined()
expect(secondBinding).not.toBe(first.binding) // new identity, no revival
expect(secondBinding!('k.child', {})).not.toBeUndefined() // new binding is live
expect(() => first.binding('k.child', {})).toThrow(StaleAuthorizationError) // old stays dead
})
})

View File

@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createSnapshotStore, shallowEqual } from '@deepseek-ai/dsh-client-web-react/store'
import { createSnapshotStore, defineStore, shallowEqual } from '@deepseek-ai/dsh-client-web-react/store'
interface State {
a: { n: number }
@@ -124,6 +124,98 @@ describe('createSnapshotStore', () => {
})
})
describe('defineStore', () => {
const declare = () => defineStore({
init: () => ({ selection: null as string | null, draft: '' }),
actions: {
select: (d, target: string) => { d.selection = target },
setDraft: (d, text: string) => { d.draft = text },
clearDraft: (d) => { d.draft = '' },
},
})
it('create() yields a live instance: fresh init state, selector-visible action writes', () => {
const inst = declare().create()
expect(inst.store.getSnapshot()).toEqual({ selection: null, draft: '' })
inst.actions.setDraft('hello')
inst.actions.select('m1')
expect(inst.store.getSnapshot()).toEqual({ selection: 'm1', draft: 'hello' })
inst.actions.clearDraft()
expect(inst.store.getSnapshot().draft).toBe('')
})
it('bakes draft-stripped actions that write through update (draft mutation, not replacement)', () => {
const inst = declare().create()
const before = inst.store.getSnapshot()
inst.actions.setDraft('x')
const after = inst.store.getSnapshot()
expect(after).not.toBe(before)
expect(after.selection).toBe(before.selection) // untouched branch preserved (immer path)
})
it('creates independent instances per create() call (the handle is a spec, not a singleton)', () => {
const handle = declare()
const a = handle.create()
const b = handle.create()
a.actions.setDraft('only-a')
expect(b.store.getSnapshot().draft).toBe('')
})
it('suffixes the persist key with the scope key: per-session persistence plus clearPersisted cleanup', () => {
const backing = new Map<string, string>()
vi.stubGlobal('localStorage', {
getItem: (k: string) => backing.get(k) ?? null,
setItem: (k: string, v: string) => { backing.set(k, v) },
removeItem: (k: string) => { backing.delete(k) },
})
const handle = defineStore({
init: () => ({ draft: '' }),
persist: 'spec.chat',
actions: { setDraft: (d, text: string) => { d.draft = text } },
})
handle.create('s1').actions.setDraft('one')
handle.create('s2').actions.setDraft('two')
handle.create().actions.setDraft('root')
expect(JSON.parse(backing.get('spec.chat.s1')!)).toEqual({ draft: 'one' })
expect(JSON.parse(backing.get('spec.chat.s2')!)).toEqual({ draft: 'two' })
expect(JSON.parse(backing.get('spec.chat')!)).toEqual({ draft: 'root' })
// Rehydration honors the same suffixed key.
expect(handle.create('s1').store.getSnapshot().draft).toBe('one')
// Scope-death cleanup removes exactly the suffixed key.
handle.create('s1').clearPersisted()
expect(backing.has('spec.chat.s1')).toBe(false)
expect(backing.has('spec.chat.s2')).toBe(true)
expect(backing.has('spec.chat')).toBe(true)
})
it('clearPersisted is a no-op without a persist declaration or without storage', () => {
const inst = declare().create('s1') // no persist key declared
expect(() => { inst.clearPersisted() }).not.toThrow()
const persisting = defineStore({
init: () => ({ n: 0 }),
persist: 'spec.nostorage',
actions: { inc: (d) => { d.n += 1 } },
}).create()
// jsdom-less lane: localStorage may exist here, so simulate its absence.
vi.stubGlobal('localStorage', undefined)
expect(() => { persisting.clearPersisted() }).not.toThrow()
})
it('swallows storage failures in clearPersisted (same non-fatal contract as persistence)', () => {
vi.stubGlobal('localStorage', {
getItem: () => null,
setItem: () => {},
removeItem: () => { throw new Error('quota / private mode') },
})
const inst = defineStore({
init: () => ({ n: 0 }),
persist: 'spec.throwing',
actions: { inc: (d) => { d.n += 1 } },
}).create()
expect(() => { inst.clearPersisted() }).not.toThrow()
})
})
describe('shallowEqual', () => {
it('matches one-level-equal objects and rejects deeper drift', () => {
const leaf = { deep: 1 }