You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by "xxhZs (via GitHub)" <gi...@apache.org> on 2026/09/14 13:34:06 UTC
[PR] feat(plugins): add unified client plugin runtime [maka]
xxhZs opened a new pull request, #5303:
URL: https://github.com/apache/maka/pull/5303
## Summary
- add an optional Client entry to `maka.extension.json` and carry Client-only or Host+Client packages through the existing package store, immutable generations, composition, restart recovery, and rollback model
- project active `desktop-ui` bundles through a strict Runtime Host protocol, then serve content-addressed JavaScript to the Renderer through a scoped Desktop transport
- add the first typed Client runtime and root Slot, with staged activation, atomic swap, reverse cleanup, dependency-generation refresh, and last-good-UI preservation on failure
- document the bundle ABI, trust boundary, lifecycle, and intentionally deferred PR2/PR3 scope
## Scope
This is PR1 of the Client/UI plugin plan. It establishes one package authority and one lifecycle. More granular recursive Slots, a curated public component SDK, typed Host↔Client RPC, and product events remain follow-up work.
## Testing
- `NODE_NO_WARNINGS=1 npm test`
- `npm run build`
- `npm --workspace @maka/desktop run check:architecture`
- `npm run lint`
- `npm run format:check`
- `npm run check:asf-headers`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
Re: [PR] feat(plugins): add client runtime, UI slots, remote, and events [maka]
Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #5303:
URL: https://github.com/apache/maka/pull/5303#discussion_r4024182930
##########
packages/ui/src/client-plugin-runtime.tsx:
##########
@@ -0,0 +1,745 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import type { ReactNode } from 'react';
+import { useSyncExternalStore } from 'react';
+import type {
+ MakaClientProductEventMap,
+ MakaClientProductEventName,
+ MakaClientProductEventOptions,
+ MakaClientRemoteInput,
+ MakaClientRemoteMethodName,
+ MakaClientRemoteOutput,
+ MakaClientRemoteOptions,
+ MakaClientRemoteStreamInput,
+ MakaClientRemoteStreamItem,
+ MakaClientRemoteStreamName,
+ MakaClientRemoteStreamOptions,
+} from '@maka/core/client-plugin-bridge';
+import {
+ MakaClientSlotCore,
+ MakaClientSlotProvider,
+ type MakaClientLiveSlotNode,
+ type MakaClientSlotRegistrar,
+} from './client-plugin-slots.js';
+import { remoteStream } from './client-plugin-remote-stream.js';
+
+export interface MakaClientPluginDescriptor {
+ readonly entryId: string;
+ readonly extensionId: string;
+ readonly generation: number;
+ readonly contentDigest: string;
+ readonly clientDigest: string;
+ readonly totalBytes: number;
+ readonly dependencies: readonly string[];
+ readonly url: string;
+ readonly config?: Readonly<Record<string, string | number | boolean>>;
+}
+
+export interface MakaClientPluginDiagnostic {
+ readonly entryId?: string;
+ readonly extensionId?: string;
+ readonly diagnostic: string;
+}
+
+export interface MakaClientPluginSnapshot {
+ readonly authorityEpoch: number;
+ readonly revision: string;
+ readonly plugins: readonly MakaClientPluginDescriptor[];
+ readonly failures: readonly MakaClientPluginDiagnostic[];
+}
+
+export interface MakaClientBundleRegistration {
+ readonly id: string;
+ readonly factory: (require: (specifier: string) => unknown) => Record<string, unknown>;
+}
+
+export interface MakaClientModuleLoaderTarget {
+ load(registration: MakaClientBundleRegistration): void;
+ inspect(): MakaClientPluginRuntimeInspection;
+}
+
+declare global {
+ interface Window {
+ /** Stable factory-registration facade used by trusted Client bundles. */
+ __MakaModuleLoader__?: MakaClientModuleLoaderTarget;
+ }
+}
+
+export interface MakaClientRootProps {
+ readonly children: ReactNode;
+}
+
+export type MakaClientRootComponent = (props: MakaClientRootProps) => ReactNode;
+
+export type MakaClientPluginSlots = MakaClientSlotRegistrar & {
+ register(options: { readonly name: 'root' }, component: MakaClientRootComponent): () => void;
+};
+
+export interface MakaClientPluginContext {
+ readonly id: string;
+ readonly extensionId: string;
+ readonly generation: number;
+ readonly slots: MakaClientPluginSlots;
+ readonly remote: {
+ call<const Name extends MakaClientRemoteMethodName>(
+ name: Name,
+ input: MakaClientRemoteInput<Name>,
+ options?: MakaClientRemoteOptions,
+ ): Promise<MakaClientRemoteOutput<Name>>;
+ stream<const Name extends MakaClientRemoteStreamName>(
+ name: Name,
+ input: MakaClientRemoteStreamInput<Name>,
+ options?: MakaClientRemoteStreamOptions,
+ ): AsyncIterable<MakaClientRemoteStreamItem<Name>>;
+ };
+ readonly events: {
+ on<const Name extends MakaClientProductEventName>(
+ name: Name,
+ options: MakaClientProductEventOptions<Name>,
+ listener: (event: MakaClientProductEventMap[Name]) => void,
+ ): () => void;
+ };
+ /** Stage an owned side effect. Setup runs only if the whole snapshot commits. */
+ effect(setup: () => void | (() => void | Promise<void>), label?: string): () => void;
+ /** Stage Client CSS with lifecycle-owned removal. */
+ style(css: string, label?: string): () => void;
+}
+
+export type MakaClientPluginApply = (
+ context: MakaClientPluginContext,
+ config: Readonly<Record<string, string | number | boolean>>,
+) => void | (() => void | Promise<void>) | Promise<void | (() => void | Promise<void>)>;
+
+export interface MakaClientPluginRuntimeInspection {
+ readonly revision: string | null;
+ readonly active: readonly {
+ readonly entryId: string;
+ readonly extensionId: string;
+ readonly generation: number;
+ }[];
+ readonly slots: readonly MakaClientLiveSlotNode[];
+ readonly failure: { readonly revision: string; readonly diagnostic: string } | null;
+}
+
+interface StagedRootRegistration {
+ readonly component: MakaClientRootComponent;
+ cancelled: boolean;
+}
+
+interface StagedEffect {
+ readonly setup: () => void | (() => void | Promise<void>);
+ cancelled: boolean;
+ cleanup?: () => void | Promise<void>;
+}
+
+interface PluginInstance {
+ readonly descriptor: MakaClientPluginDescriptor;
+ readonly roots: StagedRootRegistration[];
+ readonly slotDisposers: Array<() => void>;
+ readonly effects: StagedEffect[];
+ readonly lifetime: AbortController;
+}
+
+interface MakaClientRootSnapshot {
+ readonly components: readonly MakaClientRootComponent[];
+ readonly slots: MakaClientSlotCore;
+}
+
+export class MakaClientRoot {
+ readonly #listeners = new Set<() => void>();
+ #snapshot: MakaClientRootSnapshot = Object.freeze({
+ components: Object.freeze([]),
+ slots: new MakaClientSlotCore(),
+ });
+
+ subscribe = (listener: () => void): (() => void) => {
+ this.#listeners.add(listener);
+ return () => this.#listeners.delete(listener);
+ };
+
+ snapshot = (): MakaClientRootSnapshot => this.#snapshot;
+
+ replace(
+ components: readonly MakaClientRootComponent[],
+ slots: MakaClientSlotCore = new MakaClientSlotCore(),
+ ): void {
+ this.#snapshot = Object.freeze({
+ components: Object.freeze([...components]),
+ slots,
+ });
+ for (const listener of this.#listeners) listener();
+ }
+}
+
+export function MakaClientRootOutlet(props: {
+ readonly root: MakaClientRoot;
+ readonly children: ReactNode;
+}): ReactNode {
+ const snapshot = useSyncExternalStore(
+ props.root.subscribe,
+ props.root.snapshot,
+ props.root.snapshot,
+ );
+ return (
+ <MakaClientSlotProvider core={snapshot.slots}>
+ {snapshot.components.reduceRight<ReactNode>(
Review Comment:
**P1 — root components have no error boundary.** `reduceRight` wraps each plugin root component directly, and `ClientPluginRoot` mounts *above* the app's `ErrorBoundary` — so a render-time throw in any `{ name: 'root' }` component unmounts the entire React tree (white screen), and the committed graph re-crashes on every reload until the plugin is removed from the CLI. Slot entries get `MakaClientSlotBoundary` + abdicate (`client-plugin-slots.tsx:800-856`); root components need the same treatment — wrap each in a boundary that falls back to `children` and abdicates the registration.
##########
apps/desktop/src/main/client-plugin-transport.ts:
##########
@@ -0,0 +1,285 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import type { WebContents } from 'electron';
+import { createHash, randomUUID } from 'node:crypto';
+import type {
+ OperationInput,
+ OperationOutput,
+ PluginClientCompositionEntry,
+ PluginClientQueryInput,
+ PluginClientQueryResult,
+} from '@maka/runtime-host/protocol';
+import { PLUGIN_CLIENT_BUNDLE_MAX_BYTES } from '@maka/runtime-host/protocol';
+import type { MakaClientPluginSnapshot } from '@maka/ui/client-plugin-runtime';
+import { handleReconnectableRead, type ReconnectableReadIpcMain } from './ipc-reconnect-policy.js';
+
+export const MAKA_CLIENT_PLUGIN_SCHEME = 'maka-client-plugin';
+
+type ClientPluginOperation =
+ | 'plugin.client.query'
+ | 'plugin.client.remote.call'
+ | 'plugin.client.remote.stream.open'
+ | 'plugin.client.remote.stream.next'
+ | 'plugin.client.remote.stream.close';
+
+export interface ClientPluginQueryClient {
+ request(
+ operation: 'plugin.client.query',
+ input: PluginClientQueryInput,
+ ): Promise<PluginClientQueryResult>;
+}
+
+export interface ClientPluginRemoteClient {
+ request<K extends ClientPluginOperation>(
+ operation: K,
+ input: OperationInput<K>,
+ ): Promise<OperationOutput<K>>;
+}
+
+type StreamRenderer = Pick<WebContents, 'id' | 'on' | 'once' | 'off'>;
+interface StreamOwner {
+ epoch: number;
+ readonly ids: Set<string>;
+ release(): void;
+}
+
+interface BundleRoute {
+ readonly client: ClientPluginQueryClient;
+ readonly entry: PluginClientCompositionEntry;
+}
+
+/** Bridges Host-owned, content-addressed Client generations into Electron. */
+export class ClientPluginTransport {
+ readonly #streamOwners = new Map<ClientPluginRemoteClient, Map<number, StreamOwner>>();
+ readonly #routes = new Map<string, BundleRoute>();
+ readonly #tokens = new Map<ClientPluginQueryClient, Map<string, string>>();
+
+ async openStream(client: ClientPluginRemoteClient, target: StreamRenderer, input: OperationInput<'plugin.client.remote.stream.open'>) {
+ let owners = this.#streamOwners.get(client);
+ if (!owners) this.#streamOwners.set(client, owners = new Map());
+ let owner = owners.get(target.id);
+ if (!owner) {
+ const close = () => {
+ binding.epoch++;
+ for (const streamId of binding.ids) {
+ void client.request('plugin.client.remote.stream.close', { streamId }).catch(() => undefined);
+ }
+ binding.ids.clear();
+ };
+ const navigate = (_event: unknown, _url: string, inPlace: boolean, mainFrame: boolean) => {
+ if (mainFrame && !inPlace) close();
+ };
+ const binding: StreamOwner = {
+ epoch: 0,
+ ids: new Set(),
+ release: () => {
+ close();
+ target.off('did-start-navigation', navigate);
+ target.off('render-process-gone', close);
+ target.off('destroyed', binding.release);
+ owners.delete(target.id);
+ },
+ };
+ owner = binding;
+ owners.set(target.id, owner);
+ target.on('did-start-navigation', navigate);
+ target.on('render-process-gone', close);
+ target.once('destroyed', binding.release);
+ }
+ const epoch = owner.epoch;
+ const result = await client.request('plugin.client.remote.stream.open', input);
+ if (owner.epoch !== epoch) {
+ await client.request('plugin.client.remote.stream.close', result).catch(() => undefined);
+ // The old document cannot consume this reply. Preserve the wire shape;
+ // a late pull is handled as exhausted by the document ownership check.
+ return result;
+ }
+ owner.ids.add(result.streamId);
+ return result;
+ }
+
+ ownsStream(client: ClientPluginRemoteClient, targetId: number, streamId: string): boolean {
+ return this.#streamOwners.get(client)?.get(targetId)?.ids.has(streamId) ?? false;
+ }
+
+ forgetStream(client: ClientPluginRemoteClient, streamId: string): void {
+ for (const owner of this.#streamOwners.get(client)?.values() ?? []) owner.ids.delete(streamId);
+ }
+
+ async snapshot(client: ClientPluginQueryClient): Promise<MakaClientPluginSnapshot> {
+ const result = await client.request('plugin.client.query', { kind: 'snapshot' });
+ if (result.kind !== 'snapshot') throw new Error('Runtime Host returned a Client bundle page');
+ const previous = this.#tokens.get(client) ?? new Map<string, string>();
+ const next = new Map<string, string>();
+ const plugins = result.entries.map((entry) => {
+ if (entry.totalBytes < 1 || entry.totalBytes > PLUGIN_CLIENT_BUNDLE_MAX_BYTES) {
+ throw new Error(`Client Plugin bundle size is invalid: ${entry.extensionId}`);
+ }
+ const key = bundleKey(entry);
+ const token = previous.get(key) ?? randomUUID();
+ next.set(key, token);
+ this.#routes.set(token, { client, entry });
+ return Object.freeze({
+ ...entry,
+ url: `${MAKA_CLIENT_PLUGIN_SCHEME}://bundle/${token}/${entry.clientDigest}.js`,
+ });
+ });
+ for (const [key, token] of previous) {
+ if (!next.has(key)) this.#routes.delete(token);
+ }
+ this.#tokens.set(client, next);
+ return Object.freeze({
+ authorityEpoch: result.authorityEpoch,
+ revision: result.revision,
+ plugins: Object.freeze(plugins),
+ failures: result.failures,
+ });
+ }
+
+ release(client: ClientPluginQueryClient): void {
+ const remote = client as ClientPluginRemoteClient;
+ for (const owner of this.#streamOwners.get(remote)?.values() ?? []) owner.release();
+ this.#streamOwners.delete(remote);
+ for (const token of this.#tokens.get(client)?.values() ?? []) this.#routes.delete(token);
+ this.#tokens.delete(client);
+ }
+
+ async serve(requestUrl: string): Promise<Response> {
+ const requested = routeRequest(requestUrl);
+ const route = requested ? this.#routes.get(requested.token) : undefined;
+ if (!route || requested?.clientDigest !== route.entry.clientDigest) {
+ return response('Client Plugin bundle is stale or unavailable', 404);
+ }
+ try {
+ const chunks: Buffer[] = [];
+ let offset = 0;
+ while (offset < route.entry.totalBytes) {
+ const result = await route.client.request('plugin.client.query', {
+ kind: 'bundle',
+ extensionId: route.entry.extensionId,
+ contentDigest: route.entry.contentDigest,
+ clientDigest: route.entry.clientDigest,
+ offset,
+ });
+ if (
+ result.kind !== 'bundle' ||
+ result.extensionId !== route.entry.extensionId ||
+ result.contentDigest !== route.entry.contentDigest ||
+ result.clientDigest !== route.entry.clientDigest ||
+ result.offset !== offset ||
+ result.totalBytes !== route.entry.totalBytes
+ ) {
+ throw new Error('Runtime Host returned a mismatched Client Plugin bundle page');
+ }
+ const chunk = Buffer.from(result.content, 'base64');
+ if (chunk.byteLength === 0) throw new Error('Runtime Host returned an empty bundle page');
+ chunks.push(chunk);
+ offset += chunk.byteLength;
+ if (result.nextOffset !== (offset < result.totalBytes ? offset : null)) {
+ throw new Error('Runtime Host returned a discontinuous bundle page');
+ }
+ }
+ const content = Buffer.concat(chunks, route.entry.totalBytes);
+ const digest = `sha256-${createHash('sha256').update(content).digest('hex')}`;
+ if (content.byteLength !== route.entry.totalBytes || digest !== route.entry.clientDigest) {
+ throw new Error('Client Plugin bundle integrity check failed');
+ }
+ return new Response(content, {
+ status: 200,
+ headers: {
+ 'content-type': 'text/javascript; charset=utf-8',
+ 'cache-control': 'no-store',
+ 'content-security-policy': "default-src 'none'",
+ },
+ });
+ } catch {
+ return response('Client Plugin bundle is stale or unavailable', 409);
+ }
+ }
+}
+
+export function registerClientPluginIpc(input: {
+ readonly ipcMain: ReconnectableReadIpcMain;
+ readonly client: ClientPluginQueryClient & ClientPluginRemoteClient;
+ readonly transport: ClientPluginTransport;
+}): void {
+ handleReconnectableRead(input.ipcMain, 'client-plugins:snapshot', () =>
+ input.transport.snapshot(input.client),
+ );
+ input.ipcMain.handle('client-plugins:remote:call', (_event, request) =>
Review Comment:
**P1 — `sessionId` is forwarded still projected, so session-scoped remotes are unreachable on the only real consumer path.** Slots feed plugins `desktopSessionKey` values (`JSON.stringify([hostId, sessionId])`), and every other session channel un-projects via `runtimeHostSessionRef`/`parseDesktopSessionKey` (preload.ts:442-461, 706-710). This handler forwards `request` verbatim; host-side `resolve()` then calls `registry.visible(assertSessionId(target.sessionId))` (`plugin-client-bridge-service.ts:312`), which never matches a session registration under the raw id. Worse than failing: a same-named *profile*-scope registration silently wins and the handler receives the bogus projected id in its context. `ctx.remote.call(name, input, { sessionId })` is dead-or-wrong from the desktop — in-process tests pass raw ids, so nothing catches it. Fix: un-project with `parseDesktopSessionKey` here or in the preload before forwarding, and when a sessionId is present route to that session's
host rather than `invokeActiveRuntimeHost`.
##########
packages/runtime-host/src/server/plugin-platform.ts:
##########
@@ -578,6 +594,145 @@ export class HostPluginPlatform {
return Object.freeze(projections);
}
+ async clientSnapshot(): Promise<Extract<PluginClientQueryResult, { readonly kind: 'snapshot' }>> {
+ this.#assertReadable();
+ const entries: PluginClientCompositionEntry[] = [];
+ const clientEntryIds = new Set<string>();
+ for (const inspection of flattenEntryInspections(this.#composition.inspectTree('desktop-ui'))) {
+ clientEntryIds.add(inspection.id);
+ if (
+ inspection.status !== 'active' ||
+ !inspection.packageId ||
+ inspection.generation === undefined
+ ) {
+ continue;
+ }
+ const pkg = this.#composition.package(inspection.packageId);
+ const bundle = this.#packageLoader.clientBundle(pkg);
Review Comment:
**P1 — this `clientBundle` lookup is broken by `collectGarbage`, which `#reconcileNow` calls unconditionally.** `collectGarbage` clears `#owned` and removes every directory under `plugin-generations-v1` (`plugin-package-loader.ts:144-147`), but the reconcile loop then skips installed-and-healthy packages (`if (installed && !retryPackages.has(extensionId)) continue`), so ownership is never re-registered. Before client entries this was harmless — host modules stay in the ESM cache — but now any transient failure that schedules a reconcile wipes every active client plugin's generation: `clientBundle` returns `undefined`, the snapshot drops the entries, the renderer unmounts them, `serve()` 404s, and remote calls fail the fence — while the platform reports converged/ready until reload or restart. Fix: sweep only directories not in `#owned` (don't clear), or re-register `composition.installedPackages()` before sweeping. Either way, add the regression: reconcile with a live clie
nt plugin must leave it servable.
##########
packages/ui/src/chat-turn.tsx:
##########
@@ -804,6 +805,7 @@ export const TurnView = memo(function TurnView(props: {
)}
{ownsTurnChrome && (props.liveStreaming || props.footerActions?.length) ? (
Review Comment:
**P2 — the turn-footer outlet only mounts when native chrome exists.** `ownsTurnChrome && (liveStreaming || footerActions?.length)` gates `TurnFooter`, which contains the slot — so plugin contributions to `conversation.turn.footer` are silently absent on exactly the turns where they are most valuable (failed, aborted, no native actions). `conversation.header.actions` already solves this via `useMakaClientSlotOccupied` (`chat-view.tsx:587-589`); the footer needs the symmetric check.
##########
packages/runtime-host/src/server/plugin-platform.ts:
##########
@@ -578,6 +594,145 @@ export class HostPluginPlatform {
return Object.freeze(projections);
}
+ async clientSnapshot(): Promise<Extract<PluginClientQueryResult, { readonly kind: 'snapshot' }>> {
+ this.#assertReadable();
+ const entries: PluginClientCompositionEntry[] = [];
+ const clientEntryIds = new Set<string>();
+ for (const inspection of flattenEntryInspections(this.#composition.inspectTree('desktop-ui'))) {
+ clientEntryIds.add(inspection.id);
+ if (
+ inspection.status !== 'active' ||
+ !inspection.packageId ||
+ inspection.generation === undefined
+ ) {
+ continue;
+ }
+ const pkg = this.#composition.package(inspection.packageId);
+ const bundle = this.#packageLoader.clientBundle(pkg);
+ if (!bundle) continue;
+ const installed = await this.#packages.load(inspection.packageId);
+ entries.push(
+ Object.freeze({
+ entryId: inspection.id,
+ extensionId: inspection.packageId,
+ generation: inspection.generation,
+ contentDigest: bundle.contentDigest,
+ clientDigest: bundle.clientDigest,
+ totalBytes: bundle.totalBytes,
+ dependencies: Object.freeze(installed.manifest.dependencies.map(({ id }) => id)),
+ ...(inspection.config === undefined
+ ? {}
+ : {
+ config: inspection.config as Readonly<Record<string, string | number | boolean>>,
+ }),
+ }),
+ );
+ }
+ const clientPackages = new Set(entries.map(({ extensionId }) => extensionId));
+ const failures = Object.freeze(
+ this.#failures.filter(
+ (failure) =>
+ (failure.entryId !== undefined && clientEntryIds.has(failure.entryId)) ||
+ (failure.extensionId !== undefined && clientPackages.has(failure.extensionId)),
+ ),
+ );
+ const revision = `sha256-${createHash('sha256')
+ .update(JSON.stringify({ authorityEpoch: this.#authority.generation, entries, failures }))
+ .digest('hex')}`;
+ return Object.freeze({
+ kind: 'snapshot',
+ authorityEpoch: this.#authority.generation,
+ revision,
+ entries: Object.freeze(entries),
+ failures,
+ });
+ }
+
+ async invokeClientRemote(
+ input: PluginClientRemoteCallInput,
+ signal?: AbortSignal,
+ ): Promise<unknown> {
+ return await this.read(async () => {
Review Comment:
**P1 — the plugin handler is awaited inside the platform-wide serial section.** `this.read()` chains onto `#mutation`, which serializes every plugin operation: `plugin.client.query` (polled every second by the renderer), all other remote calls, install/uninstall/apply, `status()`, and `close()`. A handler that is slow — or never settles — wedges the whole platform and can hang host shutdown, since `close()` awaits `#mutation` and `SHUTDOWN_OPERATION_GRACE_MS` only bounds operation drain, not composition close. Stream `next`/`close` deliberately bypass the lock (`plugin-platform-coordinator.ts:131-174`), so the unary path reads as the one that was missed. Fix: run `#verifyClientRemoteFence` inside the lock and `bridge.invoke`/`open` outside it — a registration retired in between already resolves to `operation_conflict`, so semantics are unchanged.
##########
packages/ui/src/client-plugin-runtime.tsx:
##########
@@ -0,0 +1,745 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import type { ReactNode } from 'react';
+import { useSyncExternalStore } from 'react';
+import type {
+ MakaClientProductEventMap,
+ MakaClientProductEventName,
+ MakaClientProductEventOptions,
+ MakaClientRemoteInput,
+ MakaClientRemoteMethodName,
+ MakaClientRemoteOutput,
+ MakaClientRemoteOptions,
+ MakaClientRemoteStreamInput,
+ MakaClientRemoteStreamItem,
+ MakaClientRemoteStreamName,
+ MakaClientRemoteStreamOptions,
+} from '@maka/core/client-plugin-bridge';
+import {
+ MakaClientSlotCore,
+ MakaClientSlotProvider,
+ type MakaClientLiveSlotNode,
+ type MakaClientSlotRegistrar,
+} from './client-plugin-slots.js';
+import { remoteStream } from './client-plugin-remote-stream.js';
+
+export interface MakaClientPluginDescriptor {
+ readonly entryId: string;
+ readonly extensionId: string;
+ readonly generation: number;
+ readonly contentDigest: string;
+ readonly clientDigest: string;
+ readonly totalBytes: number;
+ readonly dependencies: readonly string[];
+ readonly url: string;
+ readonly config?: Readonly<Record<string, string | number | boolean>>;
+}
+
+export interface MakaClientPluginDiagnostic {
+ readonly entryId?: string;
+ readonly extensionId?: string;
+ readonly diagnostic: string;
+}
+
+export interface MakaClientPluginSnapshot {
+ readonly authorityEpoch: number;
+ readonly revision: string;
+ readonly plugins: readonly MakaClientPluginDescriptor[];
+ readonly failures: readonly MakaClientPluginDiagnostic[];
+}
+
+export interface MakaClientBundleRegistration {
+ readonly id: string;
+ readonly factory: (require: (specifier: string) => unknown) => Record<string, unknown>;
+}
+
+export interface MakaClientModuleLoaderTarget {
+ load(registration: MakaClientBundleRegistration): void;
+ inspect(): MakaClientPluginRuntimeInspection;
+}
+
+declare global {
+ interface Window {
+ /** Stable factory-registration facade used by trusted Client bundles. */
+ __MakaModuleLoader__?: MakaClientModuleLoaderTarget;
+ }
+}
+
+export interface MakaClientRootProps {
+ readonly children: ReactNode;
+}
+
+export type MakaClientRootComponent = (props: MakaClientRootProps) => ReactNode;
+
+export type MakaClientPluginSlots = MakaClientSlotRegistrar & {
+ register(options: { readonly name: 'root' }, component: MakaClientRootComponent): () => void;
+};
+
+export interface MakaClientPluginContext {
+ readonly id: string;
+ readonly extensionId: string;
+ readonly generation: number;
+ readonly slots: MakaClientPluginSlots;
+ readonly remote: {
+ call<const Name extends MakaClientRemoteMethodName>(
+ name: Name,
+ input: MakaClientRemoteInput<Name>,
+ options?: MakaClientRemoteOptions,
+ ): Promise<MakaClientRemoteOutput<Name>>;
+ stream<const Name extends MakaClientRemoteStreamName>(
+ name: Name,
+ input: MakaClientRemoteStreamInput<Name>,
+ options?: MakaClientRemoteStreamOptions,
+ ): AsyncIterable<MakaClientRemoteStreamItem<Name>>;
+ };
+ readonly events: {
+ on<const Name extends MakaClientProductEventName>(
+ name: Name,
+ options: MakaClientProductEventOptions<Name>,
+ listener: (event: MakaClientProductEventMap[Name]) => void,
+ ): () => void;
+ };
+ /** Stage an owned side effect. Setup runs only if the whole snapshot commits. */
+ effect(setup: () => void | (() => void | Promise<void>), label?: string): () => void;
+ /** Stage Client CSS with lifecycle-owned removal. */
+ style(css: string, label?: string): () => void;
+}
+
+export type MakaClientPluginApply = (
+ context: MakaClientPluginContext,
+ config: Readonly<Record<string, string | number | boolean>>,
+) => void | (() => void | Promise<void>) | Promise<void | (() => void | Promise<void>)>;
+
+export interface MakaClientPluginRuntimeInspection {
+ readonly revision: string | null;
+ readonly active: readonly {
+ readonly entryId: string;
+ readonly extensionId: string;
+ readonly generation: number;
+ }[];
+ readonly slots: readonly MakaClientLiveSlotNode[];
+ readonly failure: { readonly revision: string; readonly diagnostic: string } | null;
+}
+
+interface StagedRootRegistration {
+ readonly component: MakaClientRootComponent;
+ cancelled: boolean;
+}
+
+interface StagedEffect {
+ readonly setup: () => void | (() => void | Promise<void>);
+ cancelled: boolean;
+ cleanup?: () => void | Promise<void>;
+}
+
+interface PluginInstance {
+ readonly descriptor: MakaClientPluginDescriptor;
+ readonly roots: StagedRootRegistration[];
+ readonly slotDisposers: Array<() => void>;
+ readonly effects: StagedEffect[];
+ readonly lifetime: AbortController;
+}
+
+interface MakaClientRootSnapshot {
+ readonly components: readonly MakaClientRootComponent[];
+ readonly slots: MakaClientSlotCore;
+}
+
+export class MakaClientRoot {
+ readonly #listeners = new Set<() => void>();
+ #snapshot: MakaClientRootSnapshot = Object.freeze({
+ components: Object.freeze([]),
+ slots: new MakaClientSlotCore(),
+ });
+
+ subscribe = (listener: () => void): (() => void) => {
+ this.#listeners.add(listener);
+ return () => this.#listeners.delete(listener);
+ };
+
+ snapshot = (): MakaClientRootSnapshot => this.#snapshot;
+
+ replace(
+ components: readonly MakaClientRootComponent[],
+ slots: MakaClientSlotCore = new MakaClientSlotCore(),
+ ): void {
+ this.#snapshot = Object.freeze({
+ components: Object.freeze([...components]),
+ slots,
+ });
+ for (const listener of this.#listeners) listener();
+ }
+}
+
+export function MakaClientRootOutlet(props: {
+ readonly root: MakaClientRoot;
+ readonly children: ReactNode;
+}): ReactNode {
+ const snapshot = useSyncExternalStore(
+ props.root.subscribe,
+ props.root.snapshot,
+ props.root.snapshot,
+ );
+ return (
+ <MakaClientSlotProvider core={snapshot.slots}>
+ {snapshot.components.reduceRight<ReactNode>(
+ (children, Component) => <Component>{children}</Component>,
+ props.children,
+ )}
+ </MakaClientSlotProvider>
+ );
+}
+
+export interface ClientPluginRuntimeOptions {
+ readonly root: MakaClientRoot;
+ readonly staticModules: Readonly<Record<string, unknown>>;
+ readonly loadBundle?: (descriptor: MakaClientPluginDescriptor) => Promise<void>;
+ readonly document?: Pick<Document, 'createElement' | 'head'>;
+ readonly remote?: MakaClientRemoteTransport;
+ readonly productEvents?: MakaClientProductEventTransport;
+}
+
+export interface MakaClientRemoteRequest {
+ readonly authorityEpoch: number;
+ readonly revision: string;
+ readonly entryId: string;
+ readonly extensionId: string;
+ readonly generation: number;
+ readonly contentDigest: string;
+ readonly clientDigest: string;
+ readonly method: string;
+ readonly input: unknown;
+ readonly sessionId?: string;
+}
+
+export interface MakaClientRemoteTransport {
+ call(input: MakaClientRemoteRequest): Promise<{ readonly value: unknown }>;
+ open(input: MakaClientRemoteRequest): Promise<{ readonly streamId: string }>;
+ next(input: { readonly streamId: string }): Promise<
+ { readonly done: false; readonly value: unknown } | { readonly done: true }
+ >;
+ close(input: { readonly streamId: string }): Promise<unknown>;
+}
+
+export interface MakaClientProductEventTransport {
+ subscribe<const Name extends MakaClientProductEventName>(
+ name: Name,
+ options: MakaClientProductEventOptions<Name>,
+ listener: (event: MakaClientProductEventMap[Name]) => void,
+ ): () => void;
+}
+
+/** Trusted Renderer module runtime with whole-snapshot stage/swap rollback. */
+export class ClientPluginRuntime {
+ readonly #root: MakaClientRoot;
+ readonly #staticModules: Readonly<Record<string, unknown>>;
+ readonly #loadBundle: (descriptor: MakaClientPluginDescriptor) => Promise<void>;
+ readonly #document: Pick<Document, 'createElement' | 'head'> | undefined;
+ readonly #remote: MakaClientRemoteTransport | undefined;
+ readonly #productEvents: MakaClientProductEventTransport | undefined;
+ readonly #factories = new Map<string, MakaClientBundleRegistration['factory']>();
+ readonly #modules = new Map<string, Record<string, unknown>>();
+ #pending: MakaClientPluginDescriptor | undefined;
+ #active: readonly PluginInstance[] = Object.freeze([]);
+ #slots = new MakaClientSlotCore();
+ #revision: string | null = null;
+ #failure: { readonly revision: string; readonly diagnostic: string } | null = null;
+ #closed = false;
+
+ constructor(options: ClientPluginRuntimeOptions) {
+ this.#root = options.root;
+ this.#staticModules = options.staticModules;
+ this.#document = options.document ?? globalThis.document;
+ this.#loadBundle = options.loadBundle ?? ((descriptor) => this.#loadScript(descriptor));
+ this.#remote = options.remote;
+ this.#productEvents = options.productEvents;
+ }
+
+ readonly loader: MakaClientModuleLoaderTarget = {
+ load: (registration) => this.registerBundle(registration),
+ inspect: () => this.inspect(),
+ };
+
+ attachLoader(target: Window = globalThis.window): () => void {
+ const previous = target.__MakaModuleLoader__;
+ target.__MakaModuleLoader__ = this.loader;
+ return () => {
+ if (target.__MakaModuleLoader__ === this.loader) {
+ target.__MakaModuleLoader__ = previous;
+ }
+ };
+ }
+
+ inspect(): MakaClientPluginRuntimeInspection {
+ return Object.freeze({
+ revision: this.#revision,
+ active: Object.freeze(
+ this.#active.map(({ descriptor }) =>
+ Object.freeze({
+ entryId: descriptor.entryId,
+ extensionId: descriptor.extensionId,
+ generation: descriptor.generation,
+ }),
+ ),
+ ),
+ slots: this.#slots.inspect(),
+ failure: this.#failure,
+ });
+ }
+
+ registerBundle(registration: MakaClientBundleRegistration): void {
+ const pending = this.#pending;
+ if (!pending) throw new Error('Client Plugin bundle registered outside a load request');
+ if (registration.id !== pending.extensionId || typeof registration.factory !== 'function') {
+ throw new Error(
+ `Client Plugin bundle registered as ${registration.id}, expected ${pending.extensionId}`,
+ );
+ }
+ const key = moduleKey(pending);
+ if (this.#factories.has(key)) {
+ throw new Error(`Client Plugin bundle registered twice: ${pending.extensionId}`);
+ }
+ this.#factories.set(key, registration.factory);
+ }
+
+ async reconcile(snapshot: MakaClientPluginSnapshot): Promise<void> {
+ if (this.#closed) throw new Error('Client Plugin Runtime is closed');
+ if (snapshot.revision === this.#revision || snapshot.revision === this.#failure?.revision) return;
Review Comment:
**P2 — a failed snapshot revision is never retried.** Once `reconcile` fails for a revision, every later poll early-returns until `authorityEpoch` changes, so a transient `serve()` 404/409 during a host mutation wedges *all* client plugins for the life of the host process — and `inspect().failure` reaches nothing user-visible. Bounded retry, or clearing `#failure` on a subsequent successful `snapshot()` fetch, closes this.
##########
apps/desktop/src/main/client-plugin-transport.ts:
##########
@@ -0,0 +1,285 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import type { WebContents } from 'electron';
+import { createHash, randomUUID } from 'node:crypto';
+import type {
+ OperationInput,
+ OperationOutput,
+ PluginClientCompositionEntry,
+ PluginClientQueryInput,
+ PluginClientQueryResult,
+} from '@maka/runtime-host/protocol';
+import { PLUGIN_CLIENT_BUNDLE_MAX_BYTES } from '@maka/runtime-host/protocol';
+import type { MakaClientPluginSnapshot } from '@maka/ui/client-plugin-runtime';
+import { handleReconnectableRead, type ReconnectableReadIpcMain } from './ipc-reconnect-policy.js';
+
+export const MAKA_CLIENT_PLUGIN_SCHEME = 'maka-client-plugin';
+
+type ClientPluginOperation =
+ | 'plugin.client.query'
+ | 'plugin.client.remote.call'
+ | 'plugin.client.remote.stream.open'
+ | 'plugin.client.remote.stream.next'
+ | 'plugin.client.remote.stream.close';
+
+export interface ClientPluginQueryClient {
+ request(
+ operation: 'plugin.client.query',
+ input: PluginClientQueryInput,
+ ): Promise<PluginClientQueryResult>;
+}
+
+export interface ClientPluginRemoteClient {
+ request<K extends ClientPluginOperation>(
+ operation: K,
+ input: OperationInput<K>,
+ ): Promise<OperationOutput<K>>;
+}
+
+type StreamRenderer = Pick<WebContents, 'id' | 'on' | 'once' | 'off'>;
+interface StreamOwner {
+ epoch: number;
+ readonly ids: Set<string>;
+ release(): void;
+}
+
+interface BundleRoute {
+ readonly client: ClientPluginQueryClient;
+ readonly entry: PluginClientCompositionEntry;
+}
+
+/** Bridges Host-owned, content-addressed Client generations into Electron. */
+export class ClientPluginTransport {
+ readonly #streamOwners = new Map<ClientPluginRemoteClient, Map<number, StreamOwner>>();
+ readonly #routes = new Map<string, BundleRoute>();
+ readonly #tokens = new Map<ClientPluginQueryClient, Map<string, string>>();
+
+ async openStream(client: ClientPluginRemoteClient, target: StreamRenderer, input: OperationInput<'plugin.client.remote.stream.open'>) {
+ let owners = this.#streamOwners.get(client);
+ if (!owners) this.#streamOwners.set(client, owners = new Map());
+ let owner = owners.get(target.id);
+ if (!owner) {
+ const close = () => {
+ binding.epoch++;
+ for (const streamId of binding.ids) {
+ void client.request('plugin.client.remote.stream.close', { streamId }).catch(() => undefined);
+ }
+ binding.ids.clear();
+ };
+ const navigate = (_event: unknown, _url: string, inPlace: boolean, mainFrame: boolean) => {
+ if (mainFrame && !inPlace) close();
+ };
+ const binding: StreamOwner = {
+ epoch: 0,
+ ids: new Set(),
+ release: () => {
+ close();
+ target.off('did-start-navigation', navigate);
+ target.off('render-process-gone', close);
+ target.off('destroyed', binding.release);
+ owners.delete(target.id);
+ },
+ };
+ owner = binding;
+ owners.set(target.id, owner);
+ target.on('did-start-navigation', navigate);
+ target.on('render-process-gone', close);
+ target.once('destroyed', binding.release);
+ }
+ const epoch = owner.epoch;
+ const result = await client.request('plugin.client.remote.stream.open', input);
+ if (owner.epoch !== epoch) {
+ await client.request('plugin.client.remote.stream.close', result).catch(() => undefined);
+ // The old document cannot consume this reply. Preserve the wire shape;
+ // a late pull is handled as exhausted by the document ownership check.
+ return result;
+ }
+ owner.ids.add(result.streamId);
+ return result;
+ }
+
+ ownsStream(client: ClientPluginRemoteClient, targetId: number, streamId: string): boolean {
+ return this.#streamOwners.get(client)?.get(targetId)?.ids.has(streamId) ?? false;
+ }
+
+ forgetStream(client: ClientPluginRemoteClient, streamId: string): void {
+ for (const owner of this.#streamOwners.get(client)?.values() ?? []) owner.ids.delete(streamId);
+ }
+
+ async snapshot(client: ClientPluginQueryClient): Promise<MakaClientPluginSnapshot> {
+ const result = await client.request('plugin.client.query', { kind: 'snapshot' });
+ if (result.kind !== 'snapshot') throw new Error('Runtime Host returned a Client bundle page');
+ const previous = this.#tokens.get(client) ?? new Map<string, string>();
+ const next = new Map<string, string>();
+ const plugins = result.entries.map((entry) => {
+ if (entry.totalBytes < 1 || entry.totalBytes > PLUGIN_CLIENT_BUNDLE_MAX_BYTES) {
+ throw new Error(`Client Plugin bundle size is invalid: ${entry.extensionId}`);
+ }
+ const key = bundleKey(entry);
+ const token = previous.get(key) ?? randomUUID();
+ next.set(key, token);
+ this.#routes.set(token, { client, entry });
+ return Object.freeze({
+ ...entry,
+ url: `${MAKA_CLIENT_PLUGIN_SCHEME}://bundle/${token}/${entry.clientDigest}.js`,
+ });
+ });
+ for (const [key, token] of previous) {
+ if (!next.has(key)) this.#routes.delete(token);
+ }
+ this.#tokens.set(client, next);
+ return Object.freeze({
+ authorityEpoch: result.authorityEpoch,
+ revision: result.revision,
+ plugins: Object.freeze(plugins),
+ failures: result.failures,
+ });
+ }
+
+ release(client: ClientPluginQueryClient): void {
+ const remote = client as ClientPluginRemoteClient;
+ for (const owner of this.#streamOwners.get(remote)?.values() ?? []) owner.release();
+ this.#streamOwners.delete(remote);
+ for (const token of this.#tokens.get(client)?.values() ?? []) this.#routes.delete(token);
+ this.#tokens.delete(client);
+ }
+
+ async serve(requestUrl: string): Promise<Response> {
+ const requested = routeRequest(requestUrl);
+ const route = requested ? this.#routes.get(requested.token) : undefined;
+ if (!route || requested?.clientDigest !== route.entry.clientDigest) {
+ return response('Client Plugin bundle is stale or unavailable', 404);
+ }
+ try {
+ const chunks: Buffer[] = [];
+ let offset = 0;
+ while (offset < route.entry.totalBytes) {
+ const result = await route.client.request('plugin.client.query', {
+ kind: 'bundle',
+ extensionId: route.entry.extensionId,
+ contentDigest: route.entry.contentDigest,
+ clientDigest: route.entry.clientDigest,
+ offset,
+ });
+ if (
+ result.kind !== 'bundle' ||
+ result.extensionId !== route.entry.extensionId ||
+ result.contentDigest !== route.entry.contentDigest ||
+ result.clientDigest !== route.entry.clientDigest ||
+ result.offset !== offset ||
+ result.totalBytes !== route.entry.totalBytes
+ ) {
+ throw new Error('Runtime Host returned a mismatched Client Plugin bundle page');
+ }
+ const chunk = Buffer.from(result.content, 'base64');
+ if (chunk.byteLength === 0) throw new Error('Runtime Host returned an empty bundle page');
+ chunks.push(chunk);
+ offset += chunk.byteLength;
+ if (result.nextOffset !== (offset < result.totalBytes ? offset : null)) {
+ throw new Error('Runtime Host returned a discontinuous bundle page');
+ }
+ }
+ const content = Buffer.concat(chunks, route.entry.totalBytes);
+ const digest = `sha256-${createHash('sha256').update(content).digest('hex')}`;
+ if (content.byteLength !== route.entry.totalBytes || digest !== route.entry.clientDigest) {
+ throw new Error('Client Plugin bundle integrity check failed');
+ }
+ return new Response(content, {
+ status: 200,
+ headers: {
+ 'content-type': 'text/javascript; charset=utf-8',
+ 'cache-control': 'no-store',
+ 'content-security-policy': "default-src 'none'",
+ },
+ });
+ } catch {
+ return response('Client Plugin bundle is stale or unavailable', 409);
+ }
+ }
+}
+
+export function registerClientPluginIpc(input: {
+ readonly ipcMain: ReconnectableReadIpcMain;
+ readonly client: ClientPluginQueryClient & ClientPluginRemoteClient;
+ readonly transport: ClientPluginTransport;
+}): void {
+ handleReconnectableRead(input.ipcMain, 'client-plugins:snapshot', () =>
+ input.transport.snapshot(input.client),
+ );
+ input.ipcMain.handle('client-plugins:remote:call', (_event, request) =>
+ input.client.request('plugin.client.remote.call', request),
+ );
+ input.ipcMain.handle('client-plugins:remote:stream:open', (event, request) =>
+ input.transport.openStream(input.client, event.sender, request),
+ );
+ input.ipcMain.handle('client-plugins:remote:stream:next', async (event, request) => {
+ const current = () => input.transport.ownsStream(input.client, event.sender.id, request.streamId);
+ if (typeof request?.streamId === 'string' && !current()) return { done: true };
+ try {
+ const result = await input.client.request('plugin.client.remote.stream.next', request);
+ if (result.done) input.transport.forgetStream(input.client, request.streamId);
+ return result;
+ } catch (error) {
+ if (!current()) return { done: true };
+ input.transport.forgetStream(input.client, request.streamId);
+ throw error;
+ }
+ });
+ input.ipcMain.handle('client-plugins:remote:stream:close', async (_event, request) => {
Review Comment:
**P3 — `stream:close` skips the `ownsStream` check that `stream:next` performs.** Unguessable streamIds plus the host's per-connection ownership make this nearly unexploitable, but the asymmetry is unforced — the same PR adds a target check to transcript acks. One line before forwarding.
##########
packages/runtime-host/src/server/plugin-platform.ts:
##########
@@ -578,6 +594,145 @@ export class HostPluginPlatform {
return Object.freeze(projections);
}
+ async clientSnapshot(): Promise<Extract<PluginClientQueryResult, { readonly kind: 'snapshot' }>> {
+ this.#assertReadable();
+ const entries: PluginClientCompositionEntry[] = [];
+ const clientEntryIds = new Set<string>();
+ for (const inspection of flattenEntryInspections(this.#composition.inspectTree('desktop-ui'))) {
+ clientEntryIds.add(inspection.id);
+ if (
+ inspection.status !== 'active' ||
+ !inspection.packageId ||
+ inspection.generation === undefined
+ ) {
+ continue;
+ }
+ const pkg = this.#composition.package(inspection.packageId);
+ const bundle = this.#packageLoader.clientBundle(pkg);
+ if (!bundle) continue;
+ const installed = await this.#packages.load(inspection.packageId);
Review Comment:
**P2 — every snapshot and every fenced remote call re-reads and re-hashes each installed package.** `clientSnapshot` → `packages.load` → `readPackage` reads up to 16 MiB and recomputes `contentDigest` per active entry, and `#verifyClientRemoteFence` calls `clientSnapshot` on every RPC — under the renderer's 1 Hz poll plus remote traffic this is continuous disk IO inside `platform.read`. The snapshot only needs `manifest.dependencies`; cache per `(authorityEpoch, revision)` or `(extensionId, contentDigest)`, and consider a `HostChangeFeed` push instead of the unconditional poll.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
Re: [PR] feat(plugins): add client runtime, UI slots, remote, and events [maka]
Posted by "likun666661 (via GitHub)" <gi...@apache.org>.
likun666661 commented on code in PR #5303:
URL: https://github.com/apache/maka/pull/5303#discussion_r4023494837
##########
packages/ui/src/client-plugin-runtime.tsx:
##########
@@ -0,0 +1,745 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import type { ReactNode } from 'react';
+import { useSyncExternalStore } from 'react';
+import type {
+ MakaClientProductEventMap,
+ MakaClientProductEventName,
+ MakaClientProductEventOptions,
+ MakaClientRemoteInput,
+ MakaClientRemoteMethodName,
+ MakaClientRemoteOutput,
+ MakaClientRemoteOptions,
+ MakaClientRemoteStreamInput,
+ MakaClientRemoteStreamItem,
+ MakaClientRemoteStreamName,
+ MakaClientRemoteStreamOptions,
+} from '@maka/core/client-plugin-bridge';
+import {
+ MakaClientSlotCore,
+ MakaClientSlotProvider,
+ type MakaClientLiveSlotNode,
+ type MakaClientSlotRegistrar,
+} from './client-plugin-slots.js';
+import { remoteStream } from './client-plugin-remote-stream.js';
+
+export interface MakaClientPluginDescriptor {
+ readonly entryId: string;
+ readonly extensionId: string;
+ readonly generation: number;
+ readonly contentDigest: string;
+ readonly clientDigest: string;
+ readonly totalBytes: number;
+ readonly dependencies: readonly string[];
+ readonly url: string;
+ readonly config?: Readonly<Record<string, string | number | boolean>>;
+}
+
+export interface MakaClientPluginDiagnostic {
+ readonly entryId?: string;
+ readonly extensionId?: string;
+ readonly diagnostic: string;
+}
+
+export interface MakaClientPluginSnapshot {
+ readonly authorityEpoch: number;
+ readonly revision: string;
+ readonly plugins: readonly MakaClientPluginDescriptor[];
+ readonly failures: readonly MakaClientPluginDiagnostic[];
+}
+
+export interface MakaClientBundleRegistration {
+ readonly id: string;
+ readonly factory: (require: (specifier: string) => unknown) => Record<string, unknown>;
+}
+
+export interface MakaClientModuleLoaderTarget {
+ load(registration: MakaClientBundleRegistration): void;
+ inspect(): MakaClientPluginRuntimeInspection;
+}
+
+declare global {
+ interface Window {
+ /** Stable factory-registration facade used by trusted Client bundles. */
+ __MakaModuleLoader__?: MakaClientModuleLoaderTarget;
+ }
+}
+
+export interface MakaClientRootProps {
+ readonly children: ReactNode;
+}
+
+export type MakaClientRootComponent = (props: MakaClientRootProps) => ReactNode;
+
+export type MakaClientPluginSlots = MakaClientSlotRegistrar & {
+ register(options: { readonly name: 'root' }, component: MakaClientRootComponent): () => void;
+};
+
+export interface MakaClientPluginContext {
+ readonly id: string;
+ readonly extensionId: string;
+ readonly generation: number;
+ readonly slots: MakaClientPluginSlots;
+ readonly remote: {
+ call<const Name extends MakaClientRemoteMethodName>(
+ name: Name,
+ input: MakaClientRemoteInput<Name>,
+ options?: MakaClientRemoteOptions,
+ ): Promise<MakaClientRemoteOutput<Name>>;
+ stream<const Name extends MakaClientRemoteStreamName>(
+ name: Name,
+ input: MakaClientRemoteStreamInput<Name>,
+ options?: MakaClientRemoteStreamOptions,
+ ): AsyncIterable<MakaClientRemoteStreamItem<Name>>;
+ };
+ readonly events: {
+ on<const Name extends MakaClientProductEventName>(
+ name: Name,
+ options: MakaClientProductEventOptions<Name>,
+ listener: (event: MakaClientProductEventMap[Name]) => void,
+ ): () => void;
+ };
+ /** Stage an owned side effect. Setup runs only if the whole snapshot commits. */
+ effect(setup: () => void | (() => void | Promise<void>), label?: string): () => void;
+ /** Stage Client CSS with lifecycle-owned removal. */
+ style(css: string, label?: string): () => void;
+}
+
+export type MakaClientPluginApply = (
+ context: MakaClientPluginContext,
+ config: Readonly<Record<string, string | number | boolean>>,
+) => void | (() => void | Promise<void>) | Promise<void | (() => void | Promise<void>)>;
+
+export interface MakaClientPluginRuntimeInspection {
+ readonly revision: string | null;
+ readonly active: readonly {
+ readonly entryId: string;
+ readonly extensionId: string;
+ readonly generation: number;
+ }[];
+ readonly slots: readonly MakaClientLiveSlotNode[];
+ readonly failure: { readonly revision: string; readonly diagnostic: string } | null;
+}
+
+interface StagedRootRegistration {
+ readonly component: MakaClientRootComponent;
+ cancelled: boolean;
+}
+
+interface StagedEffect {
+ readonly setup: () => void | (() => void | Promise<void>);
+ cancelled: boolean;
+ cleanup?: () => void | Promise<void>;
+}
+
+interface PluginInstance {
+ readonly descriptor: MakaClientPluginDescriptor;
+ readonly roots: StagedRootRegistration[];
+ readonly slotDisposers: Array<() => void>;
+ readonly effects: StagedEffect[];
+ readonly lifetime: AbortController;
+}
+
+interface MakaClientRootSnapshot {
+ readonly components: readonly MakaClientRootComponent[];
+ readonly slots: MakaClientSlotCore;
+}
+
+export class MakaClientRoot {
+ readonly #listeners = new Set<() => void>();
+ #snapshot: MakaClientRootSnapshot = Object.freeze({
+ components: Object.freeze([]),
+ slots: new MakaClientSlotCore(),
+ });
+
+ subscribe = (listener: () => void): (() => void) => {
+ this.#listeners.add(listener);
+ return () => this.#listeners.delete(listener);
+ };
+
+ snapshot = (): MakaClientRootSnapshot => this.#snapshot;
+
+ replace(
+ components: readonly MakaClientRootComponent[],
+ slots: MakaClientSlotCore = new MakaClientSlotCore(),
+ ): void {
+ this.#snapshot = Object.freeze({
+ components: Object.freeze([...components]),
+ slots,
+ });
+ for (const listener of this.#listeners) listener();
+ }
+}
+
+export function MakaClientRootOutlet(props: {
+ readonly root: MakaClientRoot;
+ readonly children: ReactNode;
+}): ReactNode {
+ const snapshot = useSyncExternalStore(
+ props.root.subscribe,
+ props.root.snapshot,
+ props.root.snapshot,
+ );
+ return (
+ <MakaClientSlotProvider core={snapshot.slots}>
+ {snapshot.components.reduceRight<ReactNode>(
+ (children, Component) => <Component>{children}</Component>,
+ props.children,
+ )}
+ </MakaClientSlotProvider>
+ );
+}
+
+export interface ClientPluginRuntimeOptions {
+ readonly root: MakaClientRoot;
+ readonly staticModules: Readonly<Record<string, unknown>>;
+ readonly loadBundle?: (descriptor: MakaClientPluginDescriptor) => Promise<void>;
+ readonly document?: Pick<Document, 'createElement' | 'head'>;
+ readonly remote?: MakaClientRemoteTransport;
+ readonly productEvents?: MakaClientProductEventTransport;
+}
+
+export interface MakaClientRemoteRequest {
+ readonly authorityEpoch: number;
+ readonly revision: string;
+ readonly entryId: string;
+ readonly extensionId: string;
+ readonly generation: number;
+ readonly contentDigest: string;
+ readonly clientDigest: string;
+ readonly method: string;
+ readonly input: unknown;
+ readonly sessionId?: string;
+}
+
+export interface MakaClientRemoteTransport {
+ call(input: MakaClientRemoteRequest): Promise<{ readonly value: unknown }>;
+ open(input: MakaClientRemoteRequest): Promise<{ readonly streamId: string }>;
+ next(input: { readonly streamId: string }): Promise<
+ { readonly done: false; readonly value: unknown } | { readonly done: true }
+ >;
+ close(input: { readonly streamId: string }): Promise<unknown>;
+}
+
+export interface MakaClientProductEventTransport {
+ subscribe<const Name extends MakaClientProductEventName>(
+ name: Name,
+ options: MakaClientProductEventOptions<Name>,
+ listener: (event: MakaClientProductEventMap[Name]) => void,
+ ): () => void;
+}
+
+/** Trusted Renderer module runtime with whole-snapshot stage/swap rollback. */
+export class ClientPluginRuntime {
+ readonly #root: MakaClientRoot;
+ readonly #staticModules: Readonly<Record<string, unknown>>;
+ readonly #loadBundle: (descriptor: MakaClientPluginDescriptor) => Promise<void>;
+ readonly #document: Pick<Document, 'createElement' | 'head'> | undefined;
+ readonly #remote: MakaClientRemoteTransport | undefined;
+ readonly #productEvents: MakaClientProductEventTransport | undefined;
+ readonly #factories = new Map<string, MakaClientBundleRegistration['factory']>();
+ readonly #modules = new Map<string, Record<string, unknown>>();
+ #pending: MakaClientPluginDescriptor | undefined;
+ #active: readonly PluginInstance[] = Object.freeze([]);
+ #slots = new MakaClientSlotCore();
+ #revision: string | null = null;
+ #failure: { readonly revision: string; readonly diagnostic: string } | null = null;
+ #closed = false;
+
+ constructor(options: ClientPluginRuntimeOptions) {
+ this.#root = options.root;
+ this.#staticModules = options.staticModules;
+ this.#document = options.document ?? globalThis.document;
+ this.#loadBundle = options.loadBundle ?? ((descriptor) => this.#loadScript(descriptor));
+ this.#remote = options.remote;
+ this.#productEvents = options.productEvents;
+ }
+
+ readonly loader: MakaClientModuleLoaderTarget = {
+ load: (registration) => this.registerBundle(registration),
+ inspect: () => this.inspect(),
+ };
+
+ attachLoader(target: Window = globalThis.window): () => void {
+ const previous = target.__MakaModuleLoader__;
+ target.__MakaModuleLoader__ = this.loader;
+ return () => {
+ if (target.__MakaModuleLoader__ === this.loader) {
+ target.__MakaModuleLoader__ = previous;
+ }
+ };
+ }
+
+ inspect(): MakaClientPluginRuntimeInspection {
+ return Object.freeze({
+ revision: this.#revision,
+ active: Object.freeze(
+ this.#active.map(({ descriptor }) =>
+ Object.freeze({
+ entryId: descriptor.entryId,
+ extensionId: descriptor.extensionId,
+ generation: descriptor.generation,
+ }),
+ ),
+ ),
+ slots: this.#slots.inspect(),
+ failure: this.#failure,
+ });
+ }
+
+ registerBundle(registration: MakaClientBundleRegistration): void {
+ const pending = this.#pending;
+ if (!pending) throw new Error('Client Plugin bundle registered outside a load request');
+ if (registration.id !== pending.extensionId || typeof registration.factory !== 'function') {
+ throw new Error(
+ `Client Plugin bundle registered as ${registration.id}, expected ${pending.extensionId}`,
+ );
+ }
+ const key = moduleKey(pending);
+ if (this.#factories.has(key)) {
+ throw new Error(`Client Plugin bundle registered twice: ${pending.extensionId}`);
+ }
+ this.#factories.set(key, registration.factory);
+ }
+
+ async reconcile(snapshot: MakaClientPluginSnapshot): Promise<void> {
+ if (this.#closed) throw new Error('Client Plugin Runtime is closed');
+ if (snapshot.revision === this.#revision || snapshot.revision === this.#failure?.revision) return;
+ const staged: PluginInstance[] = [];
+ const slots = new MakaClientSlotCore();
+ try {
+ const byExtension = indexDescriptors(snapshot.plugins);
+ const ordered = orderDescriptors(snapshot.plugins, byExtension);
+ // A package's exports may retain imports from a dependency generation.
+ // Re-materialize the module graph for every candidate snapshot while
+ // keeping immutable bundle factories cached by digest.
+ this.#modules.clear();
+ for (const descriptor of uniqueBundles(ordered)) await this.#ensureFactory(descriptor);
+ if (this.#closed) throw new Error('Client Plugin Runtime is closed');
+ for (const descriptor of ordered) {
+ staged.push(await this.#stage(descriptor, byExtension, slots, snapshot));
+ }
+ if (this.#closed) throw new Error('Client Plugin Runtime is closed');
+ for (const instance of staged) await commitEffects(instance);
+ if (this.#closed) throw new Error('Client Plugin Runtime is closed');
+ } catch (error) {
+ await disposeInstances(staged);
+ this.#retainFactories(this.#active.map(({ descriptor }) => descriptor));
+ if (!this.#closed) {
+ this.#failure = Object.freeze({
+ revision: snapshot.revision,
+ diagnostic: diagnostic(error),
+ });
+ }
+ return;
+ }
+
+ const previous = this.#active;
+ this.#root.replace(
+ snapshot.plugins.flatMap((descriptor) =>
+ staged
+ .find((instance) => instance.descriptor.entryId === descriptor.entryId)!
+ .roots.filter(({ cancelled }) => !cancelled)
+ .map(({ component }) => component),
+ ),
+ slots,
+ );
+ this.#active = Object.freeze(staged);
+ this.#slots = slots;
+ this.#revision = snapshot.revision;
+ this.#failure = null;
+ this.#retainFactories(snapshot.plugins);
+ await disposeInstances(previous);
+ }
+
+ async close(): Promise<void> {
+ if (this.#closed) return;
+ this.#closed = true;
+ this.#slots = new MakaClientSlotCore();
+ this.#root.replace([], this.#slots);
+ const active = this.#active;
+ this.#active = Object.freeze([]);
+ this.#revision = null;
+ await disposeInstances(active);
+ this.#factories.clear();
+ this.#modules.clear();
+ }
+
+ async #ensureFactory(descriptor: MakaClientPluginDescriptor): Promise<void> {
+ const key = moduleKey(descriptor);
+ if (this.#factories.has(key)) return;
+ if (this.#pending) throw new Error('Client Plugin bundle loads must be serialized');
+ this.#pending = descriptor;
+ try {
+ await this.#loadBundle(descriptor);
+ if (!this.#factories.has(key)) {
+ throw new Error(`Client Plugin bundle did not register: ${descriptor.extensionId}`);
+ }
+ } finally {
+ this.#pending = undefined;
+ }
+ }
+
+ async #loadScript(descriptor: MakaClientPluginDescriptor): Promise<void> {
+ const document = this.#document;
+ if (!document) throw new Error('Client Plugin script loading requires a document');
+ const script = document.createElement('script');
+ script.async = true;
+ script.src = descriptor.url;
+ script.dataset.makaClientPlugin = descriptor.extensionId;
+ try {
+ await new Promise<void>((resolve, reject) => {
+ script.addEventListener('load', () => resolve(), { once: true });
+ script.addEventListener(
+ 'error',
+ () => reject(new Error(`Unable to load Client Plugin ${descriptor.extensionId}`)),
+ { once: true },
+ );
+ document.head.append(script);
+ });
+ } finally {
+ script.remove();
+ }
+ }
+
+ async #stage(
+ descriptor: MakaClientPluginDescriptor,
+ byExtension: ReadonlyMap<string, MakaClientPluginDescriptor>,
+ slots: MakaClientSlotCore,
+ snapshot: MakaClientPluginSnapshot,
+ ): Promise<PluginInstance> {
+ const exports = this.#materialize(descriptor, byExtension, new Set());
+ const apply = exports.apply ?? exports.default;
+ if (typeof apply !== 'function') {
+ throw new Error(`Client Plugin ${descriptor.extensionId} must export apply(ctx)`);
+ }
+ const instance: PluginInstance = {
+ descriptor,
+ roots: [],
+ slotDisposers: [],
+ effects: [],
+ lifetime: new AbortController(),
+ };
+ const context = this.#context(instance, slots, snapshot);
+ try {
+ const cleanup = await (apply as MakaClientPluginApply)(context, descriptor.config ?? {});
+ if (typeof cleanup === 'function') {
+ instance.effects.push({ setup: () => cleanup, cancelled: false });
+ }
+ return instance;
+ } catch (error) {
+ await disposeInstances([instance]);
+ throw error;
+ }
+ }
+
+ #context(
+ instance: PluginInstance,
+ slots: MakaClientSlotCore,
+ snapshot: MakaClientPluginSnapshot,
+ ): MakaClientPluginContext {
+ const register = (options: { readonly name?: string }, component: unknown): (() => void) => {
+ if (options?.name === 'root') {
+ if (typeof component !== 'function') {
+ throw new Error('Client Plugin root Slot component must be a function');
+ }
+ const registration: StagedRootRegistration = {
+ component: component as MakaClientRootComponent,
+ cancelled: false,
+ };
+ instance.roots.push(registration);
+ return () => {
+ registration.cancelled = true;
+ };
+ }
+ const dispose = slots.register(
+ {
+ ...options,
+ registrant: `${instance.descriptor.extensionId}:${instance.descriptor.entryId}`,
+ } as never,
+ component as never,
+ );
+ instance.slotDisposers.push(dispose);
+ return dispose;
+ };
+ return Object.freeze({
+ id: instance.descriptor.entryId,
+ extensionId: instance.descriptor.extensionId,
+ generation: instance.descriptor.generation,
+ slots: Object.freeze({
+ register,
+ }) as MakaClientPluginSlots,
+ remote: Object.freeze({
+ call: async <Name extends MakaClientRemoteMethodName>(
+ name: Name,
+ input: MakaClientRemoteInput<Name>,
+ options?: MakaClientRemoteOptions,
+ ): Promise<MakaClientRemoteOutput<Name>> => {
+ const remote = this.#remote;
+ if (!remote) throw new Error('Client Plugin Remote transport is unavailable');
+ const result = await remote.call(
+ remoteRequest(snapshot, instance.descriptor, name, input, options),
+ );
+ return result.value as MakaClientRemoteOutput<Name>;
+ },
+ stream: <Name extends MakaClientRemoteStreamName>(
+ name: Name,
+ input: MakaClientRemoteStreamInput<Name>,
+ options?: MakaClientRemoteStreamOptions,
+ ): AsyncIterable<MakaClientRemoteStreamItem<Name>> => {
+ const remote = this.#remote;
+ if (!remote) throw new Error('Client Plugin Remote transport is unavailable');
+ const request = remoteRequest(snapshot, instance.descriptor, name, input, options);
+ return remoteStream(remote, request, [instance.lifetime.signal, ...(options?.signal ? [options.signal] : [])]) as AsyncIterable<MakaClientRemoteStreamItem<Name>>;
+ },
+ }),
+ events: Object.freeze({
+ on: <Name extends MakaClientProductEventName>(
+ name: Name,
+ options: MakaClientProductEventOptions<Name>,
+ listener: (event: MakaClientProductEventMap[Name]) => void,
+ ) => {
+ validateProductEventOptions(name, options);
+ if (typeof listener !== 'function') {
+ throw new Error('Client Plugin product event listener must be a function');
+ }
+ const productEvents = this.#productEvents;
+ if (!productEvents) throw new Error('Client Plugin product events are unavailable');
+ return stageEffect(instance, () => productEvents.subscribe(name, options, listener));
+ },
+ }),
+ effect: (setup: () => void | (() => void | Promise<void>)) => {
+ return stageEffect(instance, setup);
+ },
+ style: (css: string, label?: string) => {
+ if (typeof css !== 'string') throw new Error('Client Plugin CSS must be a string');
+ const document = this.#document;
+ if (!document) throw new Error('Client Plugin CSS requires a document');
+ const effect: StagedEffect = {
+ cancelled: false,
+ setup: () => {
+ const element = document.createElement('style');
+ element.dataset.makaClientPlugin = instance.descriptor.extensionId;
+ if (label) element.dataset.makaClientPluginStyle = label;
+ element.textContent = css;
+ document.head.append(element);
+ return () => element.remove();
+ },
+ };
+ instance.effects.push(effect);
+ return () => {
+ effect.cancelled = true;
+ void Promise.resolve().then(() => effect.cleanup?.()).catch(() => undefined);
+ effect.cleanup = undefined;
+ };
+ },
+ });
+ }
+
+ #materialize(
+ descriptor: MakaClientPluginDescriptor,
+ byExtension: ReadonlyMap<string, MakaClientPluginDescriptor>,
+ visiting: Set<string>,
+ ): Record<string, unknown> {
+ const key = moduleKey(descriptor);
+ const cached = this.#modules.get(key);
+ if (cached) return cached;
+ if (visiting.has(descriptor.extensionId)) {
+ throw new Error(`Client Plugin module dependency cycle at ${descriptor.extensionId}`);
+ }
+ const factory = this.#factories.get(key);
+ if (!factory) throw new Error(`Client Plugin factory is unavailable: ${descriptor.extensionId}`);
+ const nextVisiting = new Set(visiting).add(descriptor.extensionId);
+ const exports = factory((specifier) => {
+ if (Object.hasOwn(this.#staticModules, specifier)) return this.#staticModules[specifier];
+ const normalized = normalizeModuleId(specifier);
+ if (Object.hasOwn(this.#staticModules, normalized)) return this.#staticModules[normalized];
+ if (!descriptor.dependencies.includes(normalized)) {
+ throw new Error(
+ `Client Plugin ${descriptor.extensionId} requested undeclared module ${specifier}`,
+ );
+ }
+ const dependency = byExtension.get(normalized);
+ if (!dependency) {
+ throw new Error(`Client Plugin dependency is not composed: ${normalized}`);
+ }
+ return this.#materialize(dependency, byExtension, nextVisiting);
+ });
+ if (!exports || typeof exports !== 'object') {
+ throw new Error(`Client Plugin factory must return exports: ${descriptor.extensionId}`);
+ }
+ this.#modules.set(key, exports);
+ return exports;
+ }
+
+ #retainFactories(descriptors: readonly MakaClientPluginDescriptor[]): void {
+ const retained = new Set(descriptors.map(moduleKey));
+ for (const key of this.#factories.keys()) {
+ if (!retained.has(key)) this.#factories.delete(key);
+ }
+ }
+}
+
+function indexDescriptors(
+ descriptors: readonly MakaClientPluginDescriptor[],
+): ReadonlyMap<string, MakaClientPluginDescriptor> {
+ const entries = new Set<string>();
+ const byExtension = new Map<string, MakaClientPluginDescriptor>();
+ for (const descriptor of descriptors) {
+ if (entries.has(descriptor.entryId)) {
+ throw new Error(`Client Plugin Entry repeats: ${descriptor.entryId}`);
+ }
+ entries.add(descriptor.entryId);
+ const current = byExtension.get(descriptor.extensionId);
+ if (
+ current &&
+ (current.contentDigest !== descriptor.contentDigest ||
+ current.clientDigest !== descriptor.clientDigest)
+ ) {
+ throw new Error(`Client Plugin package has mixed generations: ${descriptor.extensionId}`);
+ }
+ byExtension.set(descriptor.extensionId, current ?? descriptor);
+ }
+ return byExtension;
+}
+
+function orderDescriptors(
+ descriptors: readonly MakaClientPluginDescriptor[],
+ byExtension: ReadonlyMap<string, MakaClientPluginDescriptor>,
+): readonly MakaClientPluginDescriptor[] {
+ const extensions: MakaClientPluginDescriptor[] = [];
+ const state = new Map<string, 'visiting' | 'visited'>();
+ const visit = (descriptor: MakaClientPluginDescriptor): void => {
+ const current = state.get(descriptor.extensionId);
+ if (current === 'visited') return;
+ if (current === 'visiting') {
+ throw new Error(`Client Plugin dependency cycle at ${descriptor.extensionId}`);
+ }
+ state.set(descriptor.extensionId, 'visiting');
+ for (const dependencyId of descriptor.dependencies) {
+ const dependency = byExtension.get(dependencyId);
+ if (dependency) visit(dependency);
+ }
+ state.set(descriptor.extensionId, 'visited');
+ extensions.push(descriptor);
+ };
+ for (const descriptor of descriptors) visit(descriptor);
+ const rank = new Map(extensions.map((descriptor, index) => [descriptor.extensionId, index]));
+ return [...descriptors].sort(
+ (left, right) =>
+ rank.get(left.extensionId)! - rank.get(right.extensionId)! ||
+ descriptors.indexOf(left) - descriptors.indexOf(right),
+ );
+}
+
+function uniqueBundles(
+ descriptors: readonly MakaClientPluginDescriptor[],
+): readonly MakaClientPluginDescriptor[] {
+ const seen = new Set<string>();
+ return descriptors.filter((descriptor) => {
+ const key = moduleKey(descriptor);
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ });
+}
+
+function normalizeModuleId(value: string): string {
+ return value.endsWith('/client') ? value.slice(0, -'/client'.length) : value;
+}
+
+function moduleKey(descriptor: MakaClientPluginDescriptor): string {
+ return `${descriptor.extensionId}\u0000${descriptor.clientDigest}`;
+}
+
+function remoteRequest(
+ snapshot: MakaClientPluginSnapshot,
+ descriptor: MakaClientPluginDescriptor,
+ method: string,
+ input: unknown,
+ options?: MakaClientRemoteOptions,
+): MakaClientRemoteRequest {
+ return Object.freeze({
+ authorityEpoch: snapshot.authorityEpoch,
+ revision: snapshot.revision,
+ entryId: descriptor.entryId,
+ extensionId: descriptor.extensionId,
+ generation: descriptor.generation,
+ contentDigest: descriptor.contentDigest,
+ clientDigest: descriptor.clientDigest,
+ method,
+ input,
+ ...(options?.sessionId ? { sessionId: options.sessionId } : {}),
+ });
+}
+
+function validateProductEventOptions<Name extends MakaClientProductEventName>(
+ name: Name,
+ options: MakaClientProductEventOptions<Name>,
+): void {
+ if (name === 'session.changed') {
+ if (options.sessionId !== undefined) {
+ throw new Error('session.changed does not accept a Session id');
+ }
+ return;
+ }
+ if (!options.sessionId) throw new Error(`${name} requires a Session id`);
+}
+
+function stageEffect(
+ instance: PluginInstance,
+ setup: () => void | (() => void | Promise<void>),
+): () => void {
+ if (typeof setup !== 'function') throw new Error('Client Plugin effect must be a function');
+ const effect: StagedEffect = { setup, cancelled: false };
+ instance.effects.push(effect);
+ return () => {
+ effect.cancelled = true;
+ void Promise.resolve()
+ .then(() => effect.cleanup?.())
Review Comment:
[P1] Effects registered after activation never start, and disposing an already committed effect never runs its cleanup. `commitEffects()` scans `instance.effects` only once during `reconcile()`, but the public `ctx` remains reachable by mounted components, so a later `ctx.events.on()` or `ctx.effect()` only appends an entry that is never committed. For an effect that was committed, this disposer schedules a microtask that reads `effect.cleanup`, then clears `effect.cleanup` synchronously, so the microtask observes `undefined`. Please track whether the instance is active (stage before commit, run immediately after commit), and capture the cleanup before clearing it. Tests should cover a post-activation `events.on()` and explicitly disposing a committed effect.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
Re: [PR] feat(plugins): add client runtime, UI slots, remote, and events [maka]
Posted by "likun666661 (via GitHub)" <gi...@apache.org>.
likun666661 commented on code in PR #5303:
URL: https://github.com/apache/maka/pull/5303#discussion_r4035393295
##########
packages/runtime/src/plugin-client-bridge-service.ts:
##########
@@ -0,0 +1,515 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import type {
+ MakaClientRemoteInput,
+ MakaClientRemoteMethodName,
+ MakaClientRemoteOutput,
+ MakaClientRemoteStreamInput,
+ MakaClientRemoteStreamItem,
+ MakaClientRemoteStreamName,
+} from '@maka/core/client-plugin-bridge';
+import {
+ Service,
+ type Awaitable,
+ type Context,
+ type Disposable,
+ type StandardSchema,
+} from './plugin-kernel.js';
+import { PluginScopeRegistry } from './plugin-scope-registry.js';
+import {
+ MakaPluginRuntimeError,
+ pluginIdentity,
+ registerPluginContribution,
+ type MakaContributionIdentity,
+ type MakaPluginRootId,
+} from './plugin-runtime.js';
+
+declare module './plugin-kernel.js' {
+ interface Context {
+ readonly clientBridge: PluginClientBridgeService;
+ }
+}
+
+export interface PluginClientRemoteContext {
+ readonly sessionId?: string;
+ readonly signal: AbortSignal;
+}
+
+export interface PluginClientRpcDefinition<Input = unknown, Output = unknown> {
+ readonly name: string;
+ readonly input?: StandardSchema;
+ readonly output?: StandardSchema;
+ invoke(input: Input, context: PluginClientRemoteContext): Awaitable<Output>;
+}
+
+export interface PluginClientStreamDefinition<Input = unknown, Item = unknown> {
+ readonly name: string;
+ readonly input?: StandardSchema;
+ readonly item?: StandardSchema;
+ open(input: Input, context: PluginClientRemoteContext): Awaitable<AsyncIterable<Item>>;
+}
+
+export interface PluginClientRemoteTarget {
+ readonly extensionId: string;
+ readonly sessionId?: string;
+}
+
+export interface PluginClientStreamBinding<Item = unknown> {
+ readonly identity: MakaContributionIdentity;
+ next(): Promise<IteratorResult<Item>>;
+ close(): Promise<void>;
+}
+
+interface ActiveInvocation {
+ readonly abort: AbortController;
+ readonly settled: Promise<void>;
+ readonly settle: () => void;
+ readonly onAbort: () => void;
+ readonly signal?: AbortSignal;
+}
+
+interface RegisteredRpc extends MakaContributionIdentity {
+ readonly definition: PluginClientRpcDefinition;
+ readonly token: symbol;
+ readonly active: Set<ActiveInvocation>;
+ retired: boolean;
+}
+
+interface RegisteredStream extends MakaContributionIdentity {
+ readonly definition: PluginClientStreamDefinition;
+ readonly token: symbol;
+ readonly active: Set<ActiveInvocation>;
+ retired: boolean;
+}
+
+export class PluginClientBridgeError extends Error {
+ readonly name = 'PluginClientBridgeError';
+
+ constructor(
+ readonly code: 'not_found' | 'invalid_input' | 'retired',
+ message: string,
+ ) {
+ super(message);
+ }
+}
+
+/** Fiber-owned Host half of one package's typed Client Remote contract. */
+export class PluginClientBridgeService extends Service {
+ private readonly rpcs = new PluginScopeRegistry<RegisteredRpc>();
+ private readonly streams = new PluginScopeRegistry<RegisteredStream>();
+
+ constructor(ctx: Context) {
+ super(ctx, 'clientBridge');
+ }
+
+ rpc<const Name extends MakaClientRemoteMethodName>(
+ definition: Omit<
+ PluginClientRpcDefinition<MakaClientRemoteInput<Name>, MakaClientRemoteOutput<Name>>,
+ 'name'
+ > & { readonly name: Name },
+ ): Disposable<Promise<void>>;
+ rpc(definition: PluginClientRpcDefinition): Disposable<Promise<void>>;
+ rpc(definition: PluginClientRpcDefinition): Disposable<Promise<void>> {
+ validateDefinition(definition, 'RPC');
+ const identity = hostIdentity(this.ctx);
+ return registerPluginContribution(
+ this.ctx,
+ `clientBridge.rpc(${JSON.stringify(definition.name)})`,
+ () => this.publish(this.rpcs, identity, definition),
+ );
+ }
+
+ stream<const Name extends MakaClientRemoteStreamName>(
+ definition: Omit<
+ PluginClientStreamDefinition<
+ MakaClientRemoteStreamInput<Name>,
+ MakaClientRemoteStreamItem<Name>
+ >,
+ 'name'
+ > & { readonly name: Name },
+ ): Disposable<Promise<void>>;
+ stream(definition: PluginClientStreamDefinition): Disposable<Promise<void>>;
+ stream(definition: PluginClientStreamDefinition): Disposable<Promise<void>> {
+ validateDefinition(definition, 'Stream');
+ const identity = hostIdentity(this.ctx);
+ return registerPluginContribution(
+ this.ctx,
+ `clientBridge.stream(${JSON.stringify(definition.name)})`,
+ () => this.publish(this.streams, identity, definition),
+ );
+ }
+
+ async invoke(
+ target: PluginClientRemoteTarget,
+ name: string,
+ input: unknown,
+ signal?: AbortSignal,
+ ): Promise<unknown> {
+ return await this.prepareInvoke(target, name, input, signal)();
+ }
+
+ /** Capture the verified registration before releasing the platform mutation lock. */
+ prepareInvoke(
+ target: PluginClientRemoteTarget,
+ name: string,
+ input: unknown,
+ signal?: AbortSignal,
+ ): () => Promise<unknown> {
+ const entry = resolve(this.rpcs, target, name);
+ return async () => await this.invokeEntry(entry, target, name, input, signal);
+ }
+
+ private async invokeEntry(
+ entry: RegisteredRpc,
+ target: PluginClientRemoteTarget,
+ name: string,
+ input: unknown,
+ signal?: AbortSignal,
+ ): Promise<unknown> {
+ const active = activate(entry, name, signal);
+ try {
+ const decoded = await untilAborted(active.abort.signal, () =>
+ validateInputSchema(entry.definition.input, input, `Client RPC ${name} input`),
+ );
+ const output = await untilAborted(active.abort.signal, () =>
+ entry.definition.invoke(decoded, {
+ ...(target.sessionId ? { sessionId: target.sessionId } : {}),
+ signal: active.abort.signal,
+ }),
+ );
+ if (entry.retired) throw retiredError(name);
+ return await untilAborted(active.abort.signal, () =>
+ validateSchema(entry.definition.output, output, `Client RPC ${name} output`),
+ );
+ } finally {
+ finish(entry, active);
+ }
+ }
+
+ async open(
+ target: PluginClientRemoteTarget,
+ name: string,
+ input: unknown,
+ signal?: AbortSignal,
+ ): Promise<PluginClientStreamBinding> {
+ return await this.prepareOpen(target, name, input, signal)();
+ }
+
+ /** Capture the verified registration before releasing the platform mutation lock. */
+ prepareOpen(
+ target: PluginClientRemoteTarget,
+ name: string,
+ input: unknown,
+ signal?: AbortSignal,
+ ): () => Promise<PluginClientStreamBinding> {
+ const entry = resolve(this.streams, target, name);
+ return async () => await this.openEntry(entry, target, name, input, signal);
+ }
+
+ private async openEntry(
+ entry: RegisteredStream,
+ target: PluginClientRemoteTarget,
+ name: string,
+ input: unknown,
+ signal?: AbortSignal,
+ ): Promise<PluginClientStreamBinding> {
+ const active = activate(entry, name, signal);
+ try {
+ const decoded = await untilAborted(active.abort.signal, () =>
+ validateInputSchema(entry.definition.input, input, `Client Stream ${name} input`),
+ );
+ const iterable = await untilAborted(
+ active.abort.signal,
+ () =>
+ entry.definition.open(decoded, {
+ ...(target.sessionId ? { sessionId: target.sessionId } : {}),
+ signal: active.abort.signal,
+ }),
+ (late) => {
+ void Promise.resolve()
+ .then(() => late[Symbol.asyncIterator]().return?.())
+ .catch(() => undefined);
+ },
+ );
+ if (!iterable || typeof iterable[Symbol.asyncIterator] !== 'function') {
+ throw new TypeError(`Client Stream ${name} did not return an AsyncIterable`);
+ }
+ const iterator = iterable[Symbol.asyncIterator]();
+ let closed = false;
+ const pending = new Set<() => void>();
+ const close = async (): Promise<void> => {
+ if (closed) return;
+ closed = true;
+ active.abort.signal.removeEventListener('abort', onAbort);
+ active.abort.abort();
+ for (const settle of pending) settle();
+ pending.clear();
+ // A generator's return queues behind its pending next. Do not let a
+ // non-cooperative producer block connection cleanup or Fiber retirement.
+ void Promise.resolve()
+ .then(() => iterator.return?.())
+ .catch(() => undefined);
+ finish(entry, active);
+ };
+ const onAbort = () => {
+ void close();
+ };
+ active.abort.signal.addEventListener('abort', onAbort, { once: true });
+ if (active.abort.signal.aborted) await close();
+ return Object.freeze({
+ identity: freezeIdentity(entry),
+ next: async () => {
+ if (closed || entry.retired) throw retiredError(name);
+ let settle!: () => void;
+ const stopped = new Promise<IteratorReturnResult<undefined>>((resolve) => {
+ settle = () => resolve({ done: true, value: undefined });
+ });
+ pending.add(settle);
+ let result: IteratorResult<unknown>;
+ try {
+ result = await Promise.race([iterator.next(), stopped]);
+ } finally {
+ pending.delete(settle);
+ }
+ if (closed || result.done) {
+ await close();
+ return Object.freeze({ done: true, value: undefined });
+ }
+ const value = await validateSchema(
Review Comment:
[P1] Stream retirement cannot interrupt async item validation. `validateSchema()` may return a promise, but after `iterator.next()` resolves this await is no longer raced against `active.abort.signal` or the stream's `stopped` promise. If a plugin-provided item validator never settles, both `stream.next()` and the registration disposer remain pending indefinitely. I reproduced this with a generator that yields immediately and a Standard Schema validator that never resolves; retirement was still blocked after 150 ms. Please make item validation abort-aware, as the RPC/open paths are, and add a non-cooperative item-validator regression test.
##########
packages/runtime-host/src/server/plugin-platform-coordinator.ts:
##########
@@ -60,6 +85,114 @@ export class HostPluginPlatformCoordinator {
constructor(readonly platform: HostPluginPlatform) {}
+ releaseConnection(connectionId: string): void {
+ for (const [streamId, stream] of this.#streams) {
+ if (stream.connectionId !== connectionId) continue;
+ this.#streams.delete(streamId);
+ void stream.binding.close().catch(() => undefined);
+ }
+ }
+
+ async #remoteCall(
+ input: PluginClientRemoteCallInput,
+ context: ConnectionContext,
+ ): Promise<OperationOutcome<'plugin.client.remote.call'>> {
+ try {
+ return {
+ ok: true,
+ result: { value: await this.platform.invokeClientRemote(input, context.inputClosedSignal) },
+ };
+ } catch (error) {
+ return failure(error);
+ }
+ }
+
+ async #remoteStreamOpen(
+ input: PluginClientRemoteCallInput,
+ context: ConnectionContext,
+ ): Promise<OperationOutcome<'plugin.client.remote.stream.open'>> {
+ try {
Review Comment:
[P2] The 32-stream per-connection limit can be bypassed by concurrent opens. Connection requests are dispatched concurrently, and the count is checked before awaiting `openClientRemoteStream()`, while the new stream is inserted only after that await. Forty opens held behind the same barrier all observed zero streams and all 40 succeeded in a minimal reproduction. Reserve capacity before the await (rolling it back on failure), or serialize admission per connection, and cover concurrent opens in a test.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org
Re: [PR] feat(plugins): add client runtime, UI slots, remote, and events [maka]
Posted by "xxhZs (via GitHub)" <gi...@apache.org>.
xxhZs merged PR #5303:
URL: https://github.com/apache/maka/pull/5303
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org