Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/ui-facade-ssr-and-primitive-expose.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"everything-dev": minor
"every-plugin": minor
---

The `@/ui` facade renders real markup server-side and the expose slims to shadcn primitives (issue #1260). SSR: the host compose threads a session-bound expose resolver through `constructTree` into the generated routeConfig loaders, which register it into the caller's bundled `everything-dev/ui/remote` before route modules evaluate — so facade components resolve through the SAME container generation the tree was minted from (integrity-verified, generation-keyed caches), and the client hydrates the same components once the browser expose lands, with React selective hydration keeping server HTML visible until then. The `render-null-on-server` gate in `remoteComponent` is gone; the `null` fallback only shows without server HTML. Generated routeConfig loaders take the optional resolver argument and register it; client construction omits it. The core ui's node container now ships the `./components` expose. The expose ships shadcn primitives only (`ui/src/components/expose.ts` — everything under `ui/`); app-flavored components (ConfirmDialog, Markdown, stepper, info rows, error surface, …) stay source-owned in the core barrel and never ride the expose, and the scaffold prune protects the expose file so child providers keep the capability surface. SSR documents preload the expose's static dependency chunks (resolved from the core's mf-manifest, best-effort) instead of discovering them after remoteEntry → manifest → hydrate. The published manifest carries the expose surface (`components: [{ expose, exports }]`) for agent-facing discovery, and `remoteComponent` is documented provider-indirection: any composed source's exposes resolve server-side, not just the core's.
113 changes: 113 additions & 0 deletions docs/adr/0064-facade-ssr-and-primitive-expose.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# 0064 — The facade resolves server-side; the expose ships primitives only

Date: 2026-12-02
Status: Accepted

Amends: [ADR 0059](./0059-host-surface-and-federated-capabilities.md) §4 (the SSR story
spike verdict 077 item 2 left open, and the expose surface line), and the compose
contract ([ADR 0008](./0008-manifest-composition-and-plugin-mounts.md) — the
`ConstructInput` seam). Closes issue #1260.

## Context

The typed `@/ui` facade shipped client-only: `remoteComponent` rendered `null` on the
server and the document carried an empty pending gate for every facade component.
First use serialized gate → hydration → first-render fetch → render. The `./components`
expose carried app-flavored components alongside the shadcn primitives, so a cold
consumer paid for the core's page furniture (Markdown's react-markdown stack,
ConfirmDialog, the error surface) it would never render.

## Decision

### 1. SSR: the facade resolves through the composition's own containers

Server-side facade resolution rides the compose session — not a second loading path:

- The host builds ONE session-bound expose resolver per compose (`ssrExposeResolverOf`)
and hands it to `constructTree`. Resolution is an integrity-verified expose load
through `FederationLoader` — the same generation-keyed caches every other expose load
rides, so a cached module can never serve into a newer generation's render.
- The engine forwards the resolver to every generated routeConfig loader
(`RouteConfigRef` takes it as an optional argument). Each loader registers it into the
caller's own bundled `everything-dev/ui/remote` (`registerSsrExposeResolver`) BEFORE
dynamically importing its route module, so the facade components those modules create
resolve through the stash at render time.
- The stash is module-level per container graph. Each generation's containers are
distinct module instances, so the binding is generation-scoped by construction — no
global registry that a concurrent compose could repoint mid-render, no new shared
singleton, no AsyncLocalStorage. The resolver crosses containers as a plain function
argument, and the stash module is deliberately import-free: a routeConfig expose with
any static import splits into an external chunk that the dev loopback plane would
otherwise resolve against the plugin's web dev server (see Dev loopback below).
- Client construction omits the resolver; the client path is unchanged (compose-payload
registration + `loadRemote`). On the server without a session (CSR shell), component
loads hold the boundary in its fallback and `remoteModule` fails with a named error —
the previous behavior.

The `render-null-on-server` gate in `remoteComponent` is deleted. The server streams the
resolved component; the client hydrates the same component once the browser expose
lands, and until then React's selective hydration keeps the server HTML visible — no
mismatch, no flash. The `null` fallback only shows where there is no server HTML
(client-side navigations before the expose is cached).

The core ui's node container ships the `./components` expose — resolution happens
against the same built artifacts the browser gets, not a parallel server bundle.

Preload: the SSR document preloads the expose's STATIC dependency chunks
(`assets.js.sync` from the core's browser mf-manifest, attached to the core remote in
the compose payload and emitted by the head links). The manifest's async list is the
app's whole dynamic graph and is never a preload source. Resolution is best-effort —
an absent or unparseable manifest yields no hints, never a compose failure.

Dev loopback: the loopback plane rewrites the SSR container entry's stamped publicPath
to its own loopback directory. Served unmodified, the container fetches expose chunks
from the plugin's web dev server, where a same-named web chunk (routeConfig ships in
both environments) shadows the node bytes and executes `self`-style web chunks in
node.

Discovery: the core's manifest carries the expose surface
(`components: [{ expose, exports }]`), generated from the expose files at manifest
generation — the agent-facing catalog ADR 0059 §4 promised.

### 2. The expose ships shadcn primitives only

`./components` points at `ui/src/components/expose.ts`: everything under `ui/`, nothing
else. App-flavored components (ConfirmDialog, Markdown, stepper, info rows, local-date,
UnderConstruction) and the error surface (RootError, RootNotFound, RouterError,
DocumentFallback) stay source-owned in the core barrel (`index.ts` re-exports the
expose plus the app-flavored files, so the core's own `@/components` surface is
unchanged). A facade consumer that needs an app-flavored component owns its source —
the same choice ADR 0059 makes the default everywhere else.

The scaffold prune protects the expose file: a child runtime acts as its own provider,
and `bos mf check` gates the capability against the expose, so pruning it would break
the child's own facade contract.

## Consequences

- Facade components render in the SSR document; the docs search input and settings tabs
land in the server HTML.
- First-use cost on a cold consumer drops to the primitives' chunk set; the
react-markdown stack leaves the expose graph entirely.
- Plugin exposes resolve server-side too (the resolver maps any composed source key) —
the auth profile section remotes get the same SSR treatment for free.
- Mixed-generation renders stay impossible: resolution goes through the session the
tree was built from, not a global.
- A rebuild of every ui workspace is required (the generated routeConfig shape changed);
mixed old-plugin/new-host compositions fail at generation skew, loudly, as always.

## Alternatives rejected

- **Imports from source inside the SSR container**: build-time coupling between plugin
bundles and the core's source; breaks provider replacement entirely.
- **A global resolver registry keyed by provider name**: a concurrent compose of a new
generation repoints it mid-render — mixed generations mix React copies (the exact
crash class ADR 0049 eliminated).
- **A React context + `everything-dev/ui/remote` as a new shared singleton**: correct
generation scoping, but it widens the strict-singleton trust surface and forces a
fleet rebuild for a seam one function argument provides for free.
- **A second `./app-components` expose**: keeps app-flavored components facade-loadable,
but nothing promises they stay coherent at runtime (they are page furniture, not
capabilities) — source ownership is the honest contract for them.
- **Preloading the manifest's async chunk list**: that list is the app's whole dynamic
graph (~9.6 MB in this build), not the expose's dependencies.
21 changes: 17 additions & 4 deletions host/src/services/local-dist-server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { existsSync, readFileSync, statSync } from "node:fs";
import { createServer, type Server } from "node:http";
import path from "node:path";
import { UI_REMOTE_SERVER_ENTRY_FILENAME } from "everything-dev/ui/manifest";

export interface LocalDistServer {
baseUrl: string;
Expand All @@ -24,9 +25,9 @@ const contentTypeOf = (filePath: string) =>
MIME_TYPES[path.extname(filePath).toLowerCase()] ?? "application/octet-stream";

/**
* Serves a built ui dist directory over loopback HTTP so the host's standard
* remote-loading flow can consume the local node container. Dev only —
* production ui sources always arrive over HTTP from the CDN.
* Serves a built ui dist over loopback HTTP for the host's remote-loading
* flow (dev only). The SSR entry response rewrites the container's stamped
* dev-server publicPath to its own loopback directory (why: ADR 0064).
*/
export async function startLocalDistServer(rootDir: string): Promise<LocalDistServer> {
const normalizedRoot = path.resolve(rootDir);
Expand All @@ -51,7 +52,19 @@ export async function startLocalDistServer(rootDir: string): Promise<LocalDistSe
res.statusCode = 200;
res.setHeader("access-control-allow-origin", "*");
res.setHeader("content-type", contentTypeOf(filePath));
res.end(readFileSync(filePath));
if (relativePath.endsWith(`${UI_REMOTE_SERVER_ENTRY_FILENAME}`) === false) {
res.end(readFileSync(filePath));
return;
}
const origin = `http://${req.headers.host ?? "127.0.0.1"}`;
const source = readFileSync(filePath, "utf8");
const containerDir = `${origin}${relativePath.slice(0, relativePath.lastIndexOf("/"))}/`;
res.end(
source.replace(
/__webpack_require__\.p = "https?:\/\/[^"]*";/g,
`__webpack_require__.p = "${containerDir}";`,
),
);
});

await new Promise<void>((resolve, reject) => {
Expand Down
152 changes: 134 additions & 18 deletions host/src/services/ui-compose.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
/**
* Manifest composition for SSR (ADR 0008): manifests + route configs in →
* host-built tree out, digest-cached per resolved config.
*
* Production: the core ui's `./compose` engine (executing inside the core
* container's module graph — constructed routes are minted by the same
* react/router instance that renders them) + `./routeConfig` import maps over
* MF, plugin remotes as consumers (`import: false` — the core provides).
* Local dev: the same modules imported from source — one module graph, one
* React by construction, no MF in the server path.
* host-built tree out, digest-cached per resolved config. Production: the
* core ui's `./compose` engine (executing inside the core container's module
* graph) + `./routeConfig` import maps over MF; local dev: the same exposes
* from the loopback container server — one React by construction.
*
* The digest covers plugin keys + MF names + manifests + the imported
* MOUNT_REGISTRY_VERSION; deployment URLs are excluded so disk and prod
Expand All @@ -24,11 +20,14 @@ import {
digestOf,
entryUrls,
MANIFEST_FILENAME,
MF_MANIFEST_FILENAME,
manifestBaseOf,
type NavManifest,
type PluginManifest,
parsePluginManifest,
type RemoteEntry,
type RouteConfigModule,
type SsrExposeResolver,
UI_REMOTE_SERVER_ENTRY_FILENAME,
} from "everything-dev/ui/manifest";
import { asDigest, fetchVerified } from "everything-dev/verify";
Expand Down Expand Up @@ -201,10 +200,21 @@ export interface UiComposeCacheState {
remoteManifests: Map<string, CachedManifest>;
variants: Map<string, CachedComposeVariant>;
lastGood: CachedLastGood | null;
facadePreload: Map<string, CachedFacadePreload>;
}

interface CachedFacadePreload {
chunks: string[];
fetchedAt: number;
}

export function createUiComposeCacheState(): UiComposeCacheState {
return { remoteManifests: new Map(), variants: new Map(), lastGood: null };
return {
remoteManifests: new Map(),
variants: new Map(),
lastGood: null,
facadePreload: new Map(),
};
}

const runFetch = (url: string, init?: RequestInit): Promise<Response> => fetch(url, init);
Expand Down Expand Up @@ -437,25 +447,84 @@ const digestOfSources = Effect.fn("digestOfSources")(function* (composable: Comp
});
});

const clientPayloadOf = (composable: ComposableSource[], digest: string): ComposePayload => ({
const clientPayloadOf = (
composable: ComposableSource[],
digest: string,
facadePreload?: string[],
): ComposePayload => ({
digest,
remotes: composable.flatMap(({ source, manifest }) => {
if (!source.uiEntry) return [];
return [
{
// The client matches remotes to manifests by `key === manifest.name`;
// the manifest name IS the composition identity (ADR 0008 §2). The
// MF container name is separate deployment detail.
// the manifest name IS the composition identity (ADR 0008 §2); the
// MF container name is separate deployment detail
key: manifest.name,
name: source.mfName,
entry: source.uiEntry,
...(source.browserManifestUrl ? { manifestUrl: source.browserManifestUrl } : {}),
...(source.key === CORE_UI_KEY && facadePreload?.length ? { preload: facadePreload } : {}),
},
];
}),
manifests: composable.map(({ manifest }) => manifest),
});

/** The core's components-expose static chunks (assets.js.sync) from its
* mf-manifest — SSR preload hints. The async list is the app's whole graph. */
export function facadeChunkUrlsOf(doc: unknown, base: string): string[] {
if (!doc || typeof doc !== "object") return [];
const exposes = (doc as { exposes?: unknown }).exposes;
if (!Array.isArray(exposes)) return [];
const paths: string[] = [];
const collect = (node: unknown): void => {
if (typeof node === "string") {
if (node.endsWith(".js")) paths.push(node);
} else if (Array.isArray(node)) {
for (const child of node) collect(child);
}
};
for (const entry of exposes) {
if (!entry || typeof entry !== "object") continue;
const { name, assets } = entry as { name?: unknown; assets?: unknown };
if (typeof name !== "string" || name.replace(/^\.\//, "") !== "components") continue;
collect((assets as { js?: { sync?: unknown } } | undefined)?.js?.sync);
}
return [
...new Set(
paths.map((path) => (/^https?:\/\//.test(path) ? path : `${base}${path.replace(/^\//, "")}`)),
),
];
}

/** Dev-local ui sources carry no browser-manifest URL — the dev server serves
* it beside the fixed-name entry. */
function browserManifestUrlOf(source: UiSource): string | undefined {
if (source.browserManifestUrl) return source.browserManifestUrl;
const entry = source.uiEntry;
if (!entry) return undefined;
const base = entry.split("?")[0]?.replace(/\/remoteEntry\.js$/, "");
return base ? `${base}/${MF_MANIFEST_FILENAME}` : undefined;
}

const coreFacadePreloadOf = Effect.fn("coreFacadePreloadOf")(function* (
source: UiSource,
cache: UiComposeCacheState,
) {
const url = browserManifestUrlOf(source);
if (!url) return [];
const cached = cache.facadePreload.get(url);
const now = yield* Clock.currentTimeMillis;
if (cached && now - cached.fetchedAt < MANIFEST_TTL_MS) return cached.chunks;
const chunks = yield* Effect.tryPromise(async () => {
const response = await runFetch(url);
if (!response.ok) throw new Error(`mf-manifest fetch ${response.status} for ${url}`);
return facadeChunkUrlsOf(JSON.parse(await response.text()), manifestBaseOf(url));
}).pipe(Effect.catch(() => Effect.succeed([] as string[])));
cache.facadePreload.set(url, { chunks, fetchedAt: now });
return chunks;
});

function rememberVariant(
cache: UiComposeCacheState,
variantKey: string,
Expand All @@ -469,10 +538,8 @@ function rememberVariant(
* Wait for one local source's SSR container, or recover to the last-good
* generation (#940): while a previous compose succeeded, an unavailable
* container (a concurrent build's transient wipe) serves that generation
* loud instead of failing the request — bounded by the recovery budget so
* requests never park behind bytes a build is rewriting. Without a last-good
* generation there is nothing to serve: the failure stays loud (cold boots
* keep the full wait budget).
* loud instead of failing the request — bounded by the recovery budget. No
* last-good generation: the failure stays loud (cold boots keep the budget).
*/
const waitOrLastGood = Effect.fn("waitOrLastGood")(function* (
entry: RemoteEntry,
Expand Down Expand Up @@ -507,6 +574,45 @@ const waitOrLastGood = Effect.fn("waitOrLastGood")(function* (
return lastGood.variant;
});

interface SsrResolverDeps {
env: BosEnv;
loader: FederationLoader["Service"];
session: CompositionSession;
entryBySourceKey: Map<string, RemoteEntry>;
}

/** The session-bound expose resolver handed to `constructTree`: facades
* resolve through the generation the tree was minted from. */
function ssrExposeResolverOf(deps: SsrResolverDeps): SsrExposeResolver {
return (providerKey, expose) => {
const entry = deps.entryBySourceKey.get(providerKey);
if (!entry) {
return Promise.reject(
new Error(
`ssr expose resolution: source "${providerKey}" is not part of this composition's healthy set`,
),
);
}
return Effect.gen(function* () {
const entryUrl = requireSsrEntryUrl(entry, deps.env);
yield* deps.loader.verifyIntegrity({
remoteName: entry.name,
remoteUrl: entry.ssrUrl,
entryUrl,
integrity: entry.ssrIntegrity,
});
return yield* deps.loader.loadExpose<unknown>({
remoteName: entry.name,
entryUrl,
expose: `${entry.name}/${expose.replace(/^\.\//, "")}`,
unwrapDefault: false,
bypassModuleCache: false,
session: deps.session,
});
}).pipe(Effect.timeout("30 seconds"), Effect.runPromise);
};
}

/** Variant cache identity: the structural digest plus a variant key
* component — the deployment digest (SSR integrity) in prod, the src
* manifest mtime AND built container mtime in dev — so a code-only
Expand Down Expand Up @@ -635,6 +741,7 @@ export const composeUi = Effect.fn("composeUi")(function* (

const digest = yield* digestOfSources(healthy);

const facadePreload = yield* coreFacadePreloadOf(core, cache);
const variantKey = `${digest}::${variantCacheKey(healthySources)}`;
const isDev = healthySources.some((source) => source.localRoot);
const now = yield* Clock.currentTimeMillis;
Expand All @@ -659,6 +766,15 @@ export const composeUi = Effect.fn("composeUi")(function* (
return { key: ref.key, manifest, routeConfig: routeConfigFor };
},
rootOptions: coreRouteConfig.rootMeta,
ssrExposeResolver: ssrExposeResolverOf({
env: config.env,
loader,
session,
entryBySourceKey: new Map<string, RemoteEntry>([
[core.key, coreEntry],
...nonCore.map(({ source }, i) => [source.key, pluginEntries[i]!] as const),
]),
}),
}),
);

Expand All @@ -681,7 +797,7 @@ export const composeUi = Effect.fn("composeUi")(function* (
routeTree: constructed.rootRoute,
digest,
nav: constructed.nav,
clientPayload: clientPayloadOf(healthy, digest),
clientPayload: clientPayloadOf(healthy, digest, facadePreload),
};
rememberVariant(
cache,
Expand Down
Loading
Loading