* ✨ feat(session): persist and synchronize read state * 🌐 fix(client): complete Japanese labels after base update * 📝 docs: refresh session read-state dependency graph * 🧪 test(web): align session menu and read-state snapshots * 🌐 fix(session): complete Japanese plugin metadata * 🧪 test(web): distinguish unread from pending user input * 🐛 修复会话阅读状态的故障隔离与生命周期 * 🐛 修复阅读状态依赖检查并补齐自动已读覆盖 * 🐛 恢复会话绿点并移除未读标题加粗 * ♻️ Keep shared session reading state in Host memory * 🌐 Complete reading-state metadata for supported locales * 📝 Refresh module graph after removing storage dependency * 🧹 Move storage dependency policy out of memory-only reading * 🐛 Wait for sidebar catalog before replay navigation * 🔧 Give Host TypeScript checks 8 GiB of heap * ✅ Align Host heap checks and Windows diagnostics * ♻️ Keep CI repairs outside the session reading PR * 🐛 Show failed unread turns with an error indicator * 🔧 Adjust npm layout budget for the reading package * 🧪 Scope projection stream assertions to observed units * 🧪 Scope permission and title assertions to their projections * ♻️ Simplify session reading updates to explicit positions * 🐛 Align session reading package with release version * 🧪 Load reading state in LiveShare viewer fixtures * 🧹 Remove persistence-only type link from memory PR * 🧪 Align context menu expectations with reading actions * 🐛 Sync reading package with the release version * 🧪 Include turn boundaries in session summary expectations * ♻️ Derive reading failure facts from Host events instead of a projection The reading service took each completion from the Agent turn-boundary projection, which forced a stateVersion bump and put that projection's whole internal state on the wire for every Session list row. The service now records `turn/end` itself, so `core/agent` and the persisted projection schema are untouched. History that ended before the service started raises no reminder, which keeps "existing history reads as read" without a startup scan. The failure flag therefore describes only turns this Host observed: marking a Session whose last turn failed before a restart shows the ordinary unread reminder. * 🐛 Preserve manual unread until explicit Session interaction * 🧪 Align cold Session reading snapshot with unloaded title * 🔖 chore(session): align session-read-state with 0.2.2-rc.2 Master moved the root and every released manifest to 0.2.2-rc.2, but the new dsh-session-read-state package still declared 0.2.2-rc.1, failing constraints, verify-version-sync, verify-npm-install-layout, and release:verify after the master merge. * ♻️ refactor(gateway): recognize Remote stream carrier loss by error code RemoteStream now decides whether a generation end or failure is a retryable carrier loss by the stable code 'gateway/carrier-lost' instead of `instanceof RemoteStreamCarrierError`. RemoteStreamCarrierError keeps working and carries that code, so existing callers are unchanged, while a Client feature package can return a coded Error from `ended` without importing the class. The new RemoteStreamCarrierFailure type describes such errors; terminal-controller classifies disconnects the same way. * ♻️ refactor(session): move Session reading into ui-session-status Fold the reading feature into the single package packages/client/ui-session-status and delete session-read-state. - Host face: SessionStatusService keeps in-memory reading records and serves the sessionStatus Remote namespace (mark, follow) with session-status/* error codes; its service key is registered only for Gateway discovery and is not declared on Context. - Client face: a package-internal reading model follows the Host stream through RemoteSnapshotStream; ctx.uiSession.sessionStatus folds the records into completionUnread and completionFailed and exposes mark and readingReady; main-view acknowledgement and the session-status/read-intent event live here. No reading service or type is exported. - verify-client-packages lets a packages/client feature package request packages/api rows through dsh.client.external; feature-to-feature requests stay rejected. - ui-workspace, ui-conversation, bundles, remotes, LiveShare, the client test runtime, docs, Agent Notes, and the upgrade guide follow. * ♻️ refactor(session): clear manual unread only when the main view switches to the Session Remove the session-status/read-intent event. ui-session-status now clears an existing manual unread mark when the main view switches to a different Session, including the first selection after a page load, once the reading baseline is ready and the body arrives. Window focus, visibility changes, a replaced binding for the same Session, and activity in the open Session preserve manual unread. ui-conversation returns to master (only the ui-session-status client tsconfig reference remains), and ui-workspace navigation no longer emits the event. Tests, the session-reading Web e2e case, READMEs, and the reading Agent Note follow the new rule. * 🐛 fix(session): address the Session status review findings - Open the reading stream only while ctx.remoteAccess allows sessionStatus/follow, so a LiveShare viewer opens no owner-only stream, keeps readingReady false, and logs no synchronization failure; access changes start or stop the stream. - Hide the unacknowledged completion of the Session the visible, focused main view retains; manual marks stay visible, completionFailed follows completionUnread, and the reminder returns on blur, hiding, or a switch. - Declare ctx.sessionStatus on Context and restore its SERVICE_PAGE and SERVICE_ROLES entries; the service and SessionRead* types document on docs/subsystems/web-client.md, which now owns the reading section with the failed field. - Document that a Host plugin reload can leave the Client with a terminal error until a page reload; drop the redundant types import and the unused publish() result. - Archived Sessions read as read and offer no reading mark in the row menu or the toggle-read shortcut. - session.toggleRead names the open dialog, open panel, or archived Session that blocks it instead of asking to select a Session. - isRemoteStreamCarrierFailure rejects a RemoteError from the Host even when it carries gateway/carrier-lost; the code is Client-local. - ./types is types-only like ui-trajectory, and files no longer ship lib/types JavaScript. * 🐛 fix(session): close the remaining Session status review gaps - The Gateway Client exports isRemoteStreamCarrierFailure, and the terminal view uses it, so a Host RemoteError carrying the carrier code shows as failed rather than disconnected. - Each access grant's reading stream carries a token: frames a revoked or superseded stream still delivers are discarded, and cleanup waits for disposal before leaving reading unavailable unless a newer grant is active. - The status table hides the viewed Session's natural reminder only while that Session is open; the panel case is a documented limitation. - The README limitation and the upgrade guide state that only the main-view switch rule, including a reload restore, clears manual unread automatically. - Add the missing blank line before the next heading in the web-client reading section. * ♻️ refactor(session): install reading under the Session status table - apply returns to master's form plus one line: UiSessionStatus is the root, published as the useSessionStatus source, and installReading() from the new src/client/read.ts follows Host reading records into it. UiSessionStatus takes master's three constructor parameters and creates its own SessionReadModel as the package-internal `reading` member; installSessionStatus is removed and acknowledge.ts stays a separate file. - The viewed Session's snapshot subscription republishes the table only when its openState changes, so streamed events do not rebuild it. - Remove the obsolete Dev Note sentence about failure outcomes. - session.toggleRead passes when the Peer may not mark reading, matching the row menu, and reports readingUnavailable only while unsynchronized. --------- Co-authored-by: imccyu <[email protected]> Co-authored-by: imccyu <[email protected]>
507 lines
22 KiB
TypeScript
507 lines
22 KiB
TypeScript
/**
|
|
* jsdom slot test runtime: a real small runtime — Cordis `Context`, the
|
|
* renderer-owned `SlotRegistry`, the `ui-session` adapter, the
|
|
* `ui-session-status` table, and the UI renderer — assembled around
|
|
* test-owned session/workspace doubles and fail-loud file-upload and reading-mark stubs, so feature specs exercise
|
|
* declaration, registration, scope, store, inject, rendering, updates, and
|
|
* disposal without hand-building the machinery per suite.
|
|
*
|
|
* Not part of the product plugin graph (no `dsh.client`); feature packages
|
|
* depend on it in devDependencies only. It copies no SlotCore/renderer/store
|
|
* machinery — everything mounts the production implementations.
|
|
* @module @deepseek-ai/dsh-client-test-runtime
|
|
*/
|
|
/* oxlint-disable typescript/no-redundant-type-constituents --
|
|
* `keyof SlotMap & string` is the declare-merge key pattern (see ui-slots):
|
|
* this compilation unit sees only the runtime's 'root' row, but consumer
|
|
* programs merge their own keys in; the rule fires on the narrow-map view. */
|
|
import { Context, Inject } from '@deepseek-ai/cordis'
|
|
import type { Fiber, Plugin } from '@deepseek-ai/cordis'
|
|
import { createElement, Fragment, useSyncExternalStore } from 'react'
|
|
import type { ReactNode } from 'react'
|
|
import { act, render, within } from '@testing-library/react'
|
|
import type { RenderResult } from '@testing-library/react'
|
|
import type { queries } from '@testing-library/dom'
|
|
import type { BoundFunctions } from '@testing-library/dom'
|
|
import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
|
|
import { bindSnapshotSelector as bindRendererSnapshotSelector } from '@deepseek-ai/dsh-client-ui-renderer/src/client/bind.ts'
|
|
import { createSlotRenderer as createRenderer } from '@deepseek-ai/dsh-client-ui-renderer/src/client/scoped-slots.tsx'
|
|
import {
|
|
apply as applyUiSession, inject as uiSessionInject,
|
|
} from '@deepseek-ai/dsh-client-ui-session/client'
|
|
import {
|
|
apply as applySessionStatus, inject as sessionStatusInject,
|
|
} from '@deepseek-ai/dsh-client-ui-session-status/client'
|
|
import type { SessionReference } from '@deepseek-ai/dsh-api-session-controller/client'
|
|
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
|
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
|
|
import type { PanelInfo } from '@deepseek-ai/dsh-client-ui-layout/client'
|
|
import type {
|
|
ChildrenDecl, ComposedProps, HostObservable, OwnerOf, RenderOpts, SlotComponent, SlotMap, SlotRenderer,
|
|
ScopedStandardSourceBinding, SessionProviderComponent, SlotEntryDef, SlotFactoryMap, SlotRendererHost, SlotSpec,
|
|
SnapshotSelectorHook, StoredFactory, StoreInstanceLike,
|
|
} from '@deepseek-ai/dsh-client-ui-slots'
|
|
import { registerDomSnapshotSerializer } from './snapshot.ts'
|
|
import { TestRemote } from './remote.ts'
|
|
import { TestSessions } from './sessions.ts'
|
|
import { TestWorkspaces } from './workspaces.ts'
|
|
import type { Stabilizer } from './fixtures.ts'
|
|
import { allowAllAccessPlugin } from './access.ts'
|
|
|
|
export type { UseSession } from '@deepseek-ai/dsh-client-ui-session/client'
|
|
export { domSnapshotSerializer, registerDomSnapshotSerializer } from './snapshot.ts'
|
|
export { FixtureSession, TestSessions } from './sessions.ts'
|
|
export { stubConfigForm } from './config-form.ts'
|
|
export type { StubConfigForm } from './config-form.ts'
|
|
export { TestWorkspaces } from './workspaces.ts'
|
|
export { RemoteError, TestRemote } from './remote.ts'
|
|
export {
|
|
chatSnapshot, conversationSnapshot, sessionSnapshot, workspaceSnapshot,
|
|
} from './fixtures.ts'
|
|
export type {
|
|
FixtureSnapshot, SessionBehaviorOverrides, SessionFixture, SessionFixtureSnapshot, Stabilizer,
|
|
} from './fixtures.ts'
|
|
export { contextMenuHook } from './context-menu.ts'
|
|
export { makeTranslate } from './translate.ts'
|
|
export { allowAllAccess, allowAllAccessPlugin, StaticRemoteAccess, staticAccessPlugin } from './access.ts'
|
|
export type { AccessStandardProps, StaticAccessPlugin } from './access.ts'
|
|
export { usePinnedBrowserLanguages } from './locale-env.ts'
|
|
|
|
/**
|
|
* Bind an observable source to the production renderer's selector hook.
|
|
* @param source - Observable snapshot source.
|
|
* @returns Typed React selector hook.
|
|
*/
|
|
export function bindSnapshotSelector<T>(source: HostObservable<T>): SnapshotSelectorHook<T> {
|
|
return bindRendererSnapshotSelector(source)
|
|
}
|
|
|
|
/**
|
|
* Create the production slot renderer used by client feature tests.
|
|
* @returns Slot renderer instance.
|
|
*/
|
|
export function createSlotRenderer(): SlotRenderer {
|
|
return createRenderer()
|
|
}
|
|
|
|
/** Erased register face for the internal root call (the public declaration contract holds the typing). */
|
|
type ErasedRegister = (options: object, component: unknown) => () => void
|
|
|
|
/** Per-view render options; the caller owns the explicitly supplied Session reference. */
|
|
export interface SlotTestRenderOptions extends RenderOpts {
|
|
readonly session?: SessionReference | undefined
|
|
}
|
|
|
|
/**
|
|
* One rendered slot's local view, from {@link SlotTestRuntime.renderSlot}:
|
|
* the renderer's own `[data-slot]` outlet anchor is the snapshot root
|
|
* (`expect(view.container).toMatchSnapshot()` captures exactly this slot's
|
|
* output), Testing Library queries are bound inside it, and `update`
|
|
* re-renders with new owner props.
|
|
*/
|
|
export interface SlotView<K extends keyof SlotMap & string> {
|
|
/** The renderer's `<div data-slot="<key>">` anchor around the slot's rendered output. */
|
|
readonly container: HTMLElement
|
|
/** Testing Library queries scoped to {@link SlotView.container}. */
|
|
readonly view: BoundFunctions<typeof queries>
|
|
/**
|
|
* Replace the owner props and flush the re-render (the render-site update:
|
|
* in production the owner recomputes the share and React re-renders).
|
|
* @param owner - the next owner props share.
|
|
* @param opts - replacement render options and borrowed reference; omission keeps this view's options.
|
|
*/
|
|
update(owner: OwnerOf<K>, opts?: SlotTestRenderOptions): void
|
|
}
|
|
|
|
/**
|
|
* Mounted feature plugin handle: the live fiber plus an act-wrapped,
|
|
* idempotent dispose (unload cascade: entries, declared child slots, store
|
|
* instances, and provided services all fall together).
|
|
*/
|
|
export interface FeatureHandle {
|
|
/** The plugin's live Cordis fiber (state assertions, escape hatch). */
|
|
readonly fiber: Fiber
|
|
/**
|
|
* Dispose the plugin fiber inside React act; repeated calls no-op.
|
|
* @returns completion of the unload cascade.
|
|
*/
|
|
dispose(): Promise<void>
|
|
}
|
|
|
|
/** Mutable fail-loud file-upload stub installed by {@link SlotTestRuntime}. */
|
|
export interface TestFileUpload {
|
|
/** Test-supplied upload behavior; the default rejects every call. */
|
|
upload: (sessionId: SessionId, ...args: unknown[]) => Promise<unknown>
|
|
/** Test-supplied image upload behavior; the default rejects every call. */
|
|
uploadImage: (sessionId: SessionId, ...args: unknown[]) => Promise<unknown>
|
|
}
|
|
|
|
/**
|
|
* Owner-props cell behind the auto frame: one external store the frame
|
|
* subscribes to, so {@link SlotTestRuntime.renderSlot} and
|
|
* {@link SlotView.update} drive React through the standard uSES boundary.
|
|
*/
|
|
class OwnerPropsCell {
|
|
private readonly owners = new Map<string, { owner: object; opts: SlotTestRenderOptions | undefined }>()
|
|
private readonly listeners = new Set<() => void>()
|
|
private version = 0
|
|
|
|
/** Snapshot version for uSES pairing (bumped on every set). */
|
|
readonly getVersion = (): number => this.version
|
|
|
|
/**
|
|
* Subscribe to owner-props changes.
|
|
* @param fn - change callback.
|
|
* @returns unsubscribe.
|
|
*/
|
|
readonly subscribe = (fn: () => void): (() => void) => {
|
|
this.listeners.add(fn)
|
|
return () => { this.listeners.delete(fn) }
|
|
}
|
|
|
|
/**
|
|
* Install or replace one key's owner props and notify (synchronous; the
|
|
* caller wraps in act).
|
|
* @param key - slot key.
|
|
* @param owner - owner props share.
|
|
* @param opts - explicit keyed or list selection for the render site.
|
|
*/
|
|
set(key: string, owner: object, opts?: SlotTestRenderOptions): void {
|
|
this.owners.set(key, { owner, opts })
|
|
this.version += 1
|
|
for (const fn of [...this.listeners]) fn()
|
|
}
|
|
|
|
/** Keys with supplied owner props, in first-supply order. */
|
|
entries(): readonly (readonly [string, { owner: object; opts: SlotTestRenderOptions | undefined }])[] {
|
|
return [...this.owners.entries()]
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The test-owned 'root' occupant: declares the child slots a suite needs
|
|
* through the REAL `slots.register`, with a caller-supplied minimal frame —
|
|
* the runtime never guesses a feature's page structure.
|
|
*/
|
|
export class TestRoot {
|
|
private disposeEntry: (() => void) | undefined
|
|
|
|
/**
|
|
* @param slots - the runtime SlotRegistry.
|
|
* @param stabilize - the owning runtime's act wrapper.
|
|
*/
|
|
constructor(private readonly slots: SlotRegistry, private readonly stabilize: Stabilizer) {}
|
|
|
|
/**
|
|
* Register the root frame, declaring (and thereby claiming) the child
|
|
* slots. One declaration per runtime — a second call fails loud in the
|
|
* core ('root' is a single slot).
|
|
* @param children - child-slot declaration table (declaration + render authorization + runtime spec).
|
|
* @param frame - minimal frame component; its props derive from the declared keys (composed-props contract).
|
|
* @returns completion of the act-wrapped registration.
|
|
*/
|
|
async declare<const D extends ChildrenDecl>(
|
|
children: D,
|
|
frame: SlotComponent<ComposedProps<'root', never, keyof NoInfer<D> & keyof SlotMap & string, undefined, object>>,
|
|
): Promise<void> {
|
|
await this.stabilize(() => {
|
|
// Erased hop (same pattern as SlotRegistry's own implementation arm);
|
|
// the declaration signature above is the typed contract.
|
|
this.disposeEntry = (this.slots.register as ErasedRegister)({ name: 'root', children }, frame)
|
|
})
|
|
}
|
|
|
|
/** Remove the root registration and collapse its declarations (runtime dispose path). */
|
|
release(): void {
|
|
this.disposeEntry?.()
|
|
this.disposeEntry = undefined
|
|
}
|
|
}
|
|
|
|
/**
|
|
* The assembled test runtime. Obtain via {@link SlotTestRuntime.create};
|
|
* dispose with {@link SlotTestRuntime.dispose} (afterEach). Public mutators
|
|
* are act-wrapped throughout — tests never handle SlotCore microtask
|
|
* batching or React act themselves.
|
|
*/
|
|
export class SlotTestRuntime {
|
|
/** The runtime's Cordis root for owner APIs and explicit test-only services. */
|
|
readonly ctx: Context
|
|
/** The production SlotRegistry mounted on {@link SlotTestRuntime.ctx}. */
|
|
readonly slots: SlotRegistry
|
|
/** The test-owned 'root' occupant. */
|
|
readonly root: TestRoot
|
|
/** Fixture catalog, explicit references, scoped contexts, and behavior faces. */
|
|
readonly sessions: TestSessions
|
|
/** One Remote double shared by every feature mounted in this runtime. */
|
|
readonly remote: TestRemote
|
|
/** Workspaces double (list observable, recorded intent actions). */
|
|
readonly workspaces: TestWorkspaces
|
|
/** Test-owned panel selection used by the framework's usePanelInfo hook. */
|
|
readonly panelInfo = createSnapshotStore<PanelInfo>({ activePanelId: null })
|
|
/** Mutable file-upload stub; replace `upload` in suites that exercise the capability. */
|
|
readonly fileUpload: TestFileUpload
|
|
|
|
private readonly stabilizer: Stabilizer = async (fn) => {
|
|
await act(async () => { await fn() })
|
|
}
|
|
|
|
private host: SlotRendererHost | undefined
|
|
private readonly views: RenderResult[] = []
|
|
private readonly handles: FeatureHandle[] = []
|
|
private disposed = false
|
|
/** Auto-frame state ({@link SlotTestRuntime.declare} / {@link SlotTestRuntime.renderSlot}). */
|
|
private readonly ownerCell = new OwnerPropsCell()
|
|
private readonly autoDeclared = new Set<string>()
|
|
private autoRootView: RenderResult | undefined
|
|
private readonly disposeWorkspaceSource: () => void
|
|
private readonly disposePanelInfoSource: () => void
|
|
|
|
private constructor(ctx: Context, slots: SlotRegistry) {
|
|
this.ctx = ctx
|
|
this.slots = slots
|
|
this.root = new TestRoot(slots, this.stabilizer)
|
|
this.sessions = new TestSessions(this.stabilizer, ctx)
|
|
this.remote = new TestRemote(ctx)
|
|
this.workspaces = new TestWorkspaces(this.stabilizer)
|
|
this.fileUpload = {
|
|
upload: () => Promise.reject(new Error('client test runtime: file upload is not stubbed')),
|
|
uploadImage: () => Promise.reject(new Error('client test runtime: image upload is not stubbed')),
|
|
}
|
|
ctx.provide('sessions', this.sessions)
|
|
ctx.provide('workspaces', this.workspaces)
|
|
ctx.provide('fileUpload', this.fileUpload as never)
|
|
this.remote.provideNamespaces({ sessionStatus: {
|
|
follow: (signal: AbortSignal) => idleReadingStream(signal),
|
|
mark: () => Promise.reject(new Error('client test runtime: reading mark is not stubbed')),
|
|
} })
|
|
this.disposeWorkspaceSource = slots.provideRoot({ hooks: { workspaces: this.workspaces.list } })
|
|
this.disposePanelInfoSource = slots.provideRoot({ hooks: { panelInfo: this.panelInfo } })
|
|
// Capturing install: the production renderer does the rendering; the
|
|
// wrapper only takes the host face for storeOf (no machinery copied).
|
|
const renderer = createSlotRenderer()
|
|
slots.install({
|
|
renderRoot: (host, ownerProps) => {
|
|
this.host = host
|
|
return renderer.renderRoot(host, ownerProps)
|
|
},
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Assemble a runtime: real Context, mounted SlotRegistry, installed
|
|
* renderer, and the session/workspace doubles provided as services.
|
|
* @returns the ready runtime.
|
|
*/
|
|
static async create(): Promise<SlotTestRuntime> {
|
|
registerDomSnapshotSerializer()
|
|
const ctx = new Context()
|
|
const fiber = ctx.plugin(SlotRegistry)
|
|
await fiber.await()
|
|
const runtime = new SlotTestRuntime(ctx, ctx.get('slots') as SlotRegistry)
|
|
await ctx.plugin(allowAllAccessPlugin).await()
|
|
await ctx.plugin({ inject: [...uiSessionInject], apply: applyUiSession }).await()
|
|
await ctx.plugin({ inject: [...sessionStatusInject], apply: applySessionStatus }).await()
|
|
return runtime
|
|
}
|
|
|
|
/**
|
|
* Mount a feature plugin on a real fiber. Required services are prechecked
|
|
* so a missing provider fails loud instead of suspending the fiber forever
|
|
* (deliberate load-order suspension tests use `ctx.plugin` directly).
|
|
* @param plugin - plugin value (function, class, or `{ inject, apply }` object).
|
|
* @returns handle owning the fiber's explicit disposal.
|
|
*/
|
|
async mount(plugin: Plugin): Promise<FeatureHandle> {
|
|
const required = Object.keys(Inject.resolve((plugin as { inject?: Inject }).inject))
|
|
const missing = required.filter(name => this.ctx.get(name) === undefined)
|
|
if (missing.length > 0) {
|
|
throw new Error(`mount would suspend: missing service(s) ${missing.join(', ')} — provide() them first`)
|
|
}
|
|
const fiber = this.ctx.plugin(plugin)
|
|
await this.stabilizer(async () => {
|
|
await fiber.await()
|
|
})
|
|
let disposed = false
|
|
const handle: FeatureHandle = {
|
|
fiber,
|
|
dispose: async () => {
|
|
if (disposed) return
|
|
disposed = true
|
|
await this.stabilizer(() => fiber.dispose())
|
|
},
|
|
}
|
|
this.handles.push(handle)
|
|
return handle
|
|
}
|
|
|
|
/** Release the default Workspace hook before mounting its production owner. */
|
|
releaseWorkspaceSource(): void {
|
|
this.disposeWorkspaceSource()
|
|
}
|
|
|
|
/** Release the default panel hook before mounting the production Layout owner. */
|
|
releasePanelInfoSource(): void {
|
|
this.disposePanelInfoSource()
|
|
}
|
|
|
|
/**
|
|
* Render the root slot tree through the ctx-level entry (the shell's own
|
|
* entry point): `ctx.slots.renderSlot('root', {})` under Testing Library.
|
|
* @returns the Testing Library view.
|
|
*/
|
|
renderRoot(): RenderResult {
|
|
const view = render(createElement(Fragment, null, this.slots.renderSlot('root', {})))
|
|
this.views.push(view)
|
|
return view
|
|
}
|
|
|
|
/**
|
|
* Declare child slots under an auto-generated root frame — the single-slot
|
|
* mounting path for local DOM snapshots. Each key later supplied through
|
|
* {@link SlotTestRuntime.renderSlot} renders inside the renderer's own
|
|
* `<div data-slot="<key>">` outlet anchor (the snapshot root — the frame
|
|
* adds no wrapper of its own). Mutually exclusive with
|
|
* {@link TestRoot.declare} ('root' is a single slot); one call per runtime.
|
|
* @param children - child-slot declaration table (same contract as TestRoot.declare).
|
|
* @returns completion of the act-wrapped registration.
|
|
*/
|
|
async declare(children: ChildrenDecl): Promise<void> {
|
|
for (const key of Object.keys(children)) this.autoDeclared.add(key)
|
|
const cell = this.ownerCell
|
|
const AutoFrame = (props: {
|
|
renderSlot: (key: string, owner: object, opts?: RenderOpts) => ReactNode
|
|
SessionProvider: SessionProviderComponent
|
|
}) => {
|
|
useSyncExternalStore(cell.subscribe, cell.getVersion)
|
|
// Keyed Fragments only: the renderer's outlet anchor is the one
|
|
// `[data-slot]` element — the frame adding its own would nest
|
|
// duplicate anchors under the same key.
|
|
return createElement(Fragment, null, cell.entries().map(([key, { owner, opts }]) => {
|
|
const body = props.renderSlot(key, owner, opts)
|
|
const spec = children[key as keyof typeof children] as SlotSpec<SlotEntryDef>
|
|
if (spec.scope === 'root') return createElement(Fragment, { key }, body)
|
|
return createElement(props.SessionProvider, {
|
|
key,
|
|
session: opts?.session,
|
|
children: body,
|
|
...spec.scope === 'session-maybe' ? { empty: () => body } : {},
|
|
})
|
|
}))
|
|
}
|
|
await this.root.declare(children as never, AutoFrame as never)
|
|
}
|
|
|
|
/**
|
|
* Render one declared slot with its owner props and return the local view.
|
|
* The whole root tree mounts through the production assembly path
|
|
* (renderer, scope providers, store axis); only this key's output lands in
|
|
* the returned container. Call again with another key to view a sibling
|
|
* slot of the same tree.
|
|
* @param key - a key declared through {@link SlotTestRuntime.declare}.
|
|
* @param owner - owner props share for the render site.
|
|
* @param opts - explicit entry selection and borrowed Session reference; retained by view updates.
|
|
* @returns the slot-local view (snapshot container, scoped queries, owner updates).
|
|
*/
|
|
renderSlot<K extends keyof SlotMap & string>(
|
|
key: K,
|
|
owner: OwnerOf<K>,
|
|
opts?: SlotTestRenderOptions,
|
|
): SlotView<K> {
|
|
if (!this.autoDeclared.has(key)) {
|
|
throw new Error(`renderSlot('${key}') without declare() — declare the key first (or use root.declare for a custom frame)`)
|
|
}
|
|
let options = opts
|
|
const install = (next: object, nextOptions = options): void => {
|
|
options = nextOptions
|
|
// Synchronous cell write inside act: the frame re-renders through uSES.
|
|
act(() => {
|
|
this.ownerCell.set(key, next, options)
|
|
})
|
|
}
|
|
install(owner)
|
|
this.autoRootView ??= this.renderRoot()
|
|
const container = this.autoRootView.container.querySelector(`[data-slot="${key}"]`)
|
|
if (!(container instanceof HTMLElement)) {
|
|
throw new Error(`renderSlot('${key}'): the auto frame rendered no wrapper — was the runtime already disposed?`)
|
|
}
|
|
return { container, view: within(container), update: install }
|
|
}
|
|
|
|
/**
|
|
* Resolve the store instance the renderer would hand a slot's component
|
|
* (identity assertions, action-driven writes). Requires a prior
|
|
* {@link SlotTestRuntime.renderRoot} — the host face exists only inside the
|
|
* installed renderer, exactly as in production.
|
|
* @param key - slot key whose first entry declares the store.
|
|
* @param session - retained Session reference for session-scope slots; omit for root scope.
|
|
* @returns the live store instance.
|
|
*/
|
|
storeOf(key: keyof SlotMap & string, session?: SessionReference): StoreInstanceLike {
|
|
if (this.host === undefined) {
|
|
throw new Error('storeOf before renderRoot() — the host face exists only inside the installed renderer')
|
|
}
|
|
const entry = this.host.entriesOf(key)[0]
|
|
if (entry === undefined) throw new Error(`storeOf('${key}'): no registration on the ledger`)
|
|
const adapter = session === undefined ? undefined : this.host.scope('session')
|
|
const resolved = session === undefined ? undefined : adapter?.bindingSource(session).getSnapshot()
|
|
const scopeBinding = resolved?.key === undefined
|
|
? undefined
|
|
: resolved as ScopedStandardSourceBinding
|
|
if (session !== undefined && scopeBinding === undefined) {
|
|
throw new Error(`storeOf('${key}'): no live Session binding for '${session.sessionId}'`)
|
|
}
|
|
const instance = this.host.storeOf(entry, scopeBinding)
|
|
if (instance === undefined) throw new Error(`storeOf('${key}'): the entry declares no store`)
|
|
return instance
|
|
}
|
|
|
|
/**
|
|
* Read one registered Factory definition for direct contract assertions.
|
|
* @param name - registered Factory name.
|
|
* @returns the live Factory definition.
|
|
*/
|
|
factoryOf(name: keyof SlotFactoryMap & string): StoredFactory {
|
|
if (this.host === undefined) throw new Error('factoryOf before renderRoot()')
|
|
const definition = this.host.factoryOf(name)
|
|
if (definition === undefined) throw new Error(`factoryOf('${name}'): no definition`)
|
|
return definition
|
|
}
|
|
|
|
/**
|
|
* Flush pending ledger/store notifications inside act — for mutations made
|
|
* outside the runtime's own methods (e.g. a direct `slots.register`).
|
|
* @returns completion of the act pass.
|
|
*/
|
|
async flush(): Promise<void> {
|
|
await this.stabilizer(() => {})
|
|
}
|
|
|
|
/**
|
|
* Tear down: unmount React trees first, then dispose feature fibers, the
|
|
* root registration and standard sources, minted session scopes, and persisted test state.
|
|
* Idempotent.
|
|
* @returns completion of the teardown.
|
|
*/
|
|
async dispose(): Promise<void> {
|
|
if (this.disposed) return
|
|
this.disposed = true
|
|
this.autoRootView = undefined
|
|
for (const view of this.views.splice(0)) view.unmount()
|
|
for (const handle of this.handles.splice(0)) await handle.dispose()
|
|
this.root.release()
|
|
this.disposeWorkspaceSource()
|
|
this.disposePanelInfoSource()
|
|
await this.sessions.disposeScopes()
|
|
await this.stabilizer(() => this.ctx.fiber.dispose())
|
|
localStorage.clear()
|
|
}
|
|
}
|
|
|
|
/** Empty reading baseline held open until the stream generation is cancelled. */
|
|
async function *idleReadingStream(signal: AbortSignal): AsyncGenerator<{ readonly type: 'baseline'; readonly items: readonly [] }> {
|
|
yield { type: 'baseline', items: [] }
|
|
signal.throwIfAborted()
|
|
await new Promise<void>((resolve) => { signal.addEventListener('abort', () => { resolve() }, { once: true }) })
|
|
}
|