Spaces:
Paused
Paused
File size: 12,871 Bytes
4e7644b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 | /**
* hostExternals.ts
*
* Exposes shared host dependencies and a reactive plugin registry on
* `window.QwenPaw` so plugin bundles can register routes and tool renderers
* without bundling their own copies of React / antd.
*
* Call `installHostExternals()` once at application startup (main.tsx).
*/
import React from "react";
import ReactDOM from "react-dom";
import * as antd from "antd";
import * as antdIcons from "@ant-design/icons";
import { getApiUrl, getApiToken } from "../api/config";
import {
buildAuditNamespace,
buildMenuNamespace,
buildRouteNamespace,
buildSlotNamespace,
type QwenPawAuditNamespace,
type QwenPawMenuNamespace,
type QwenPawRouteNamespace,
type QwenPawSlotNamespace,
} from "./registry/sdk";
import { menuRegistry, routeRegistry } from "./registry/store";
import type {
HostAgentInfo,
HostSessionInfo,
HostThemeMode,
QwenPawChatNamespace,
} from "./types/qwenpaw";
import { pawSdkFactory } from "./pawapp-sdk";
import type { PawSdkFactory } from "./pawapp-sdk/types";
declare const VITE_API_BASE_URL: string;
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Public types
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/** Shared host dependencies exposed to plugin bundles via `window.QwenPaw.host`. */
export interface HostExternals {
React: typeof React;
ReactDOM: typeof ReactDOM;
antd: typeof antd;
antdIcons: typeof antdIcons;
apiBaseUrl: string;
getApiUrl: typeof getApiUrl;
getApiToken: typeof getApiToken;
// ββ Hooks + helpers attached later by installHostSdk() βββββββββββββββββββββ
useTheme?: () => HostThemeMode;
useLocale?: () => string;
useSelectedAgent?: () => HostAgentInfo;
useCurrentSession?: () => HostSessionInfo | null;
getSelectedAgentId?: () => string;
getCurrentSessionId?: () => string | null;
fetch?: (path: string, init?: RequestInit) => Promise<Response>;
}
export interface PluginRouteDeclaration {
/** Full URL path, e.g. "/plugin/my-plugin/dashboard". */
path: string;
component: React.ComponentType;
/** Sidebar display label. */
label: string;
/** Emoji or short icon text. */
icon?: string;
/** Lower number = appears earlier in sidebar. Defaults to 0. */
priority?: number;
}
/** Internal per-plugin registration record. */
export interface PluginRegistration {
pluginId: string;
/** When true, this plugin's tool renderers are treated as fallback defaults.
* External (non-builtin) renderers for the same tool name take priority. */
isBuiltin: boolean;
routes: PluginRouteDeclaration[];
toolRenderers: Record<string, React.FC<any>>;
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// PluginSystem β reactive singleton
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class PluginSystem {
private records = new Map<string, PluginRegistration>();
private listeners = new Set<() => void>();
// ββ Write API βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
addRoutes(pluginId: string, routes: PluginRouteDeclaration[]): void {
const rec = this._record(pluginId);
rec.routes.push(...routes);
this._notify();
}
addToolRenderers(
pluginId: string,
renderers: Record<string, React.FC<any>>,
options?: { isBuiltin?: boolean },
): void {
const rec = this._record(pluginId);
if (options?.isBuiltin) rec.isBuiltin = true;
Object.assign(rec.toolRenderers, renderers);
this._notify();
}
removePlugin(pluginId: string): void {
if (this.records.delete(pluginId)) this._notify();
}
// ββ Read API (consumed by PluginContext / usePlugins) ββββββββββββββββββββ
/** Merged map of all tool renderers across all plugins.
* Builtin renderers are applied first, then external plugin renderers
* overlay on top β so external plugins take priority over builtins. */
getToolRenderConfig(): Record<string, React.FC<any>> {
const builtinRenderers: Record<string, React.FC<any>> = {};
const externalRenderers: Record<string, React.FC<any>> = {};
for (const rec of this.records.values()) {
const target = rec.isBuiltin ? builtinRenderers : externalRenderers;
Object.assign(target, rec.toolRenderers);
}
return { ...builtinRenderers, ...externalRenderers };
}
/** Flat list of all page routes across all plugins, sorted by priority. */
getRoutes(): PluginRouteDeclaration[] {
const out: PluginRouteDeclaration[] = [];
for (const rec of this.records.values()) out.push(...rec.routes);
return out.sort((a, b) => (a.priority ?? 0) - (b.priority ?? 0));
}
// ββ Subscription βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/** Subscribe to any registration change. Returns an unsubscribe function. */
subscribe(fn: () => void): () => void {
this.listeners.add(fn);
return () => this.listeners.delete(fn);
}
// ββ Internals ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
private _record(pluginId: string): PluginRegistration {
if (!this.records.has(pluginId)) {
this.records.set(pluginId, {
pluginId,
isBuiltin: false,
routes: [],
toolRenderers: {},
});
}
return this.records.get(pluginId)!;
}
private _notify(): void {
this.listeners.forEach((fn) => fn());
}
}
/** Global singleton β imported by PluginContext to subscribe to changes. */
export const pluginSystem = new PluginSystem();
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Global declarations
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/** Namespace object. */
export interface WindowNamespace {
/** Shared host dependencies (React, antd, API helpers). */
host: HostExternals;
/**
* Mutable module registry. Host modules are registered at startup.
* Plugins can access and modify module exports to monkey-patch host functions.
*/
modules: Record<string, Record<string, unknown>>;
/** Register page routes for a plugin. Translates to menu.add + route.add. */
registerRoutes?: (pluginId: string, routes: PluginRouteDeclaration[]) => void;
/** Register tool-call renderers for a plugin. */
registerToolRender?: (
pluginId: string,
renderers: Record<string, React.FC<any>>,
) => void;
/** Console-wide plugin Menu API. Attached by installHostExternals(). */
menu?: QwenPawMenuNamespace;
/** Console-wide plugin Route API. */
route?: QwenPawRouteNamespace;
/** Console-wide plugin Slot API (header.left, sider.bottom, β¦). */
slot?: QwenPawSlotNamespace;
/** Chat-surface customization API. Attached by installHostSdk(). */
chat?: QwenPawChatNamespace;
/** Override audit log (debug). Attached by installHostExternals(). */
audit?: QwenPawAuditNamespace;
/** App-scoped PawApp SDK. */
paw?: PawSdkFactory;
}
declare global {
interface Window {
QwenPaw: WindowNamespace;
}
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Install (call once in main.tsx)
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Synthesize the `plugins-group` parent menu the first time a legacy
* `registerRoutes` call lands. Idempotent via menuRegistry snapshot check β
* if a plugin (or test) has already created `plugins-group` (via the new API
* or a prior synthesis call), we skip. No mutable module flag, so behaviour
* is correct under test reset / hot reload.
*/
function ensurePluginsGroup(): void {
const exists = menuRegistry
.snapshot("primary.settings")
.some((i) => i.id === "plugins-group");
if (exists) return;
menuRegistry.addBuiltin([
{
id: "plugins-group",
location: "primary.settings",
label: "Plugins",
isGroup: true,
order: 999,
},
]);
}
export function installHostExternals(): void {
const apiBaseUrl =
typeof VITE_API_BASE_URL !== "undefined" ? VITE_API_BASE_URL : "";
if (!window.QwenPaw) {
(window as any).QwenPaw = {} as WindowNamespace;
}
if (!window.QwenPaw.host) {
window.QwenPaw.host = {
React,
ReactDOM,
antd,
antdIcons,
apiBaseUrl,
getApiUrl,
getApiToken,
};
}
// ββ Console-wide extension API βββββββββββββββββββββββββββββββββββββββββ
if (!window.QwenPaw.menu) window.QwenPaw.menu = buildMenuNamespace();
if (!window.QwenPaw.route) window.QwenPaw.route = buildRouteNamespace();
if (!window.QwenPaw.slot) window.QwenPaw.slot = buildSlotNamespace();
if (!window.QwenPaw.audit) window.QwenPaw.audit = buildAuditNamespace();
if (!window.QwenPaw.paw) window.QwenPaw.paw = pawSdkFactory;
// ββ Back-compat shim βββββββββββββββββββββββββββββββββββββββββββββββββββ
// Legacy registerRoutes(pluginId, routes[]) fans out to:
// 1. route.add with id = `legacy:<pluginId>:<path>`
// 2. menu.add under the synthesized `plugins-group` (settings location).
// Visual output matches the pre-refactor Sidebar plugins-group rendering.
//
// EXCEPTION: PawApp routes (path starting with `/apps/`) register the
// route only β NO sidebar menu entry. PawApps are reachable exclusively
// through the App Center, which renders them inline via routeRegistry.
if (!window.QwenPaw.registerRoutes) {
window.QwenPaw.registerRoutes = (pluginId, routes) => {
for (const r of routes) {
const id = `legacy:${pluginId}:${r.path.replace(/^\//, "")}`;
routeRegistry.add(pluginId, {
id,
path: r.path,
component: r.component,
});
// PawApp pages are surfaced only in the App Center β never as a
// standalone sidebar menu item.
if (/^\/apps\//.test(r.path)) continue;
ensurePluginsGroup();
menuRegistry.add(pluginId, {
id,
location: "primary.settings",
parentId: "plugins-group",
label: r.label,
// Emoji string in original API β wrap to match prior Sidebar font-size styling.
icon: React.createElement(
"span",
{ style: { fontSize: 16 } },
r.icon,
),
route: id,
order: r.priority ?? 0,
});
}
// Keep the legacy pluginSystem in sync so usePlugins().pluginRoutes still works
// for any consumer that has not migrated yet (e.g. the chat-extension branch).
pluginSystem.addRoutes(pluginId, routes);
console.info(
`[plugin:${pluginId}] registerRoutes β ${routes.length} route(s) (translated to menu+route)`,
);
};
}
if (!window.QwenPaw.registerToolRender) {
window.QwenPaw.registerToolRender = (pluginId, renderers) => {
pluginSystem.addToolRenderers(pluginId, renderers);
console.info(
`[plugin:${pluginId}] registerToolRender β ${Object.keys(
renderers,
).join(", ")}`,
);
};
}
}
|