An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Implement kernel plugin lifecycle management and client plugin API (#17761)
Yingyi / 颖逸16036ae70162
diff --git a/app/src/index.ts b/app/src/index.tsindex b9d596d733..bd76f576f5 100644--- a/app/src/index.ts+++ b/app/src/index.ts@@ -217,6 +217,15 @@ export class App {if (isBrowser() && !isInMobileApp()) {window.location.href = "about:blank";}+ break;+ case "updateKernelPluginState": {+ const {name, state} = data.data as {name: string, state: TKernelPluginState};+ const plugin = this.plugins.find(p => p.name === name);+ if (plugin) {+ plugin.kernel.state.code = state;+ }+ break;+ }}}}diff --git a/app/src/plugin/index.ts b/app/src/plugin/index.tsindex 956f610e1b..2595c5a6a6 100644--- a/app/src/plugin/index.ts+++ b/app/src/plugin/index.ts@@ -19,11 +19,13 @@ import {Constants} from "../constants";import {uninstall} from "./uninstall";import {addPluginDock, afterLoadPlugin, loadPlugins} from "./loader";import {normalizeStoragePath} from "../util/pathName";+import {Kernel} from "./kernel";export class Plugin {private app: App;public i18n: IObject;public eventBus: EventBus;+ public kernel: Kernel;public data: any = {};public displayName: string;public readonly name: string;@@ -73,6 +75,11 @@ export class Plugin {this.i18n = options.i18n;this.displayName = options.displayName;this.eventBus = new EventBus(options.name);+ this.kernel = new Kernel({+ appId: options.app.appId,+ name: options.name,+ eventBus: this.eventBus,+ });// https://github.com/siyuan-note/siyuan/issues/9943Object.defineProperty(this, "name", {diff --git a/app/src/plugin/kernel.ts b/app/src/plugin/kernel.tsnew file mode 100644index 0000000000..fe01be6721--- /dev/null+++ b/app/src/plugin/kernel.ts@@ -0,0 +1,286 @@+import {fetchSyncPost} from "../util/fetch";++import type {EventBus} from "./EventBus";++export class Kernel implements IKernelPlugin {+ public state: IKernelPluginState;+ public rpc: IKernelPluginRpc;++ /**+ * 内核插件所属的应用 ID,用于区分不同应用的内核插件,建立 WebSocket 连接时会携带该 ID,以便内核正确路由消息+ */+ #appId: string;++ /**+ * 内核插件的名称,必须与内核插件注册时使用的名称一致,用于建立 WebSocket 连接和接收通知+ */+ #name: string;++ /**+ * 客户端插件的事件总线+ */+ #eventBus: EventBus;++ /**+ * JSON RPC WebSocket 连接,用于接收内核插件通知类型的 RPC 调用+ *+ * 普通的 RPC 调用使用 POST 请求+ */+ #rpcWs: WebSocket | null;++ /**+ * 内核插件通知类型的 RPC 调用的处理函数+ */+ #handlers: Map<TJsonRpcMethod, Set<TJsonRpcHandler<void>>>;++ #rpcCallUrl: string;++ constructor(options: {+ appId: string;+ name: string;+ eventBus: EventBus;+ }) {+ this.#appId = options.appId;+ this.#name = options.name;+ this.#eventBus = options.eventBus;++ this.#handlers = new Map();+ this.#rpcWs = null;+ this.#rpcCallUrl = this.#createJsonRpcCallUrl();++ this.state = this.#createState();+ this.rpc = this.#createRpc();+ }++ #createState(): IKernelPluginState {+ return new KernelState((state) => {+ switch (state.code) {+ case 2: // running+ if (this.#rpcWs == null) {+ this.#rpcWs = this.#createJsonRpcWebSocket();+ break;+ }++ switch (this.#rpcWs.readyState) {+ case WebSocket.CONNECTING:+ case WebSocket.OPEN:+ // 内核插件正在运行,且 WebSocket 连接已建立或正在建立,无需处理+ break;+ case WebSocket.CLOSING:+ case WebSocket.CLOSED:+ // 内核插件已在运行,但 WebSocket 连接未建立或已断开,尝试重新建立连接+ this.#rpcWs = this.#createJsonRpcWebSocket();+ break;+ }+ break;+ }+ this.#eventBus.emit("kernel-plugin-state-change", state);+ });+ }++ #createRpc(): IKernelPluginRpc {+ const self = this;++ const call = new Proxy({} as Record<TJsonRpcMethod, (...args: TJsonRpcMethodParams) => Promise<any>>, {+ get(_target, method: string) {+ return (...args: TJsonRpcMethodParams) => self.#rpcCall(method, ...args);+ }+ });++ const notify = new Proxy({} as Record<TJsonRpcMethod, (...args: TJsonRpcMethodParams) => void>, {+ get(_target, method: string) {+ return (...args: TJsonRpcMethodParams) => self.#rpcNotify(method, ...args);+ }+ });++ return {+ call,+ notify,+ batch: self.#rpcBatchCall.bind(self),+ bind: (method: TJsonRpcMethod, handler: TJsonRpcHandler<void>) => {+ const handlers = (() => {+ let handlers = self.#handlers.get(method);+ if (!handlers) {+ handlers = new Set();+ self.#handlers.set(method, handlers);+ }+ return handlers;+ })();+ handlers.add(handler);+ },+ unbind: (method: TJsonRpcMethod, handler: TJsonRpcHandler<void>) => {+ const handlers = self.#handlers.get(method);+ if (handlers) {+ handlers.delete(handler);+ if (handlers.size === 0) {+ self.#handlers.delete(method);+ }+ }+ },+ };+ }++ #createJsonRpcWebSocket() {+ const websocketURL = new URL(window.location.origin);+ websocketURL.protocol = websocketURL.protocol === "https:" ? "wss:" : "ws:";+ websocketURL.pathname = "/ws/plugin/rpc";+ websocketURL.searchParams.set("name", this.#name);+ const ws = new WebSocket(websocketURL);+ ws.addEventListener("message", (event) => {+ const message = JSON.parse(event.data);+ // JSON-RPC 通知:无 id 字段,有 method 字段+ if (message.method && message.id === undefined) {+ const handlers = this.#handlers.get(message.method);+ if (handlers) {+ const params = Array.isArray(message.params) ? message.params : [message.params];+ handlers.forEach(async handler => {+ try {+ await handler(...params);+ } catch (error) {+ console.error(`Error handling JSON-RPC notification for method ${message.method}:`, error);+ }+ });+ }+ }+ });+ return ws;+ }++ #createJsonRpcCallUrl() {+ const searchParams = new URLSearchParams({ name: this.#name, appId: this.#appId });+ return `api/plugin/rpc?${searchParams.toString()}`;+ }++ #generateId(): TJsonRpcId {+ return Lute.NewNodeID();+ }++ async #initState() {+ const response = await fetchSyncPost("api/plugin/getLoadedPlugin", { name: this.#name });+ if (this.state.code === -1 && response.data?.stateCode != null) {+ this.state.code = response.data.stateCode;+ }+ }++ async #rpcCall(method: TJsonRpcMethod, ...params: TJsonRpcMethodParams): Promise<any> {+ const id = this.#generateId();++ const response = await fetch(this.#rpcCallUrl, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),+ });++ const data = await response.json();+ if (data.error) {+ throw new JsonRpcError(data.error);+ }+ return data.result;+ }++ #rpcNotify(method: TJsonRpcMethod, ...params: TJsonRpcMethodParams): void {+ fetch(this.#rpcCallUrl, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ jsonrpc: "2.0", method, params }),+ });+ }++ async #rpcBatchCall(...calls: IKernelPluginRpcCall[]): Promise<IKernelPluginRpcError | (IKernelPluginRpcResultResponse | IKernelPluginRpcErrorResponse)[]> {+ const requests = calls.map(call => {+ const request: IKernelPluginRpcRequest = { jsonrpc: "2.0", method: call.method };+ if (call.params != null) {+ request.params = call.params;+ }+ if (!call.notification) {+ request.id = call.id ?? this.#generateId();+ }+ return request;+ });++ const response = await fetch(this.#rpcCallUrl, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(requests),+ });++ const data = await response.json();+ return data;+ }++ public async init() {+ try {+ await this.#initState();+ } catch (error) {+ console.error("Failed to initialize kernel plugin state:", error);+ }+ }++ public async destroy() {+ try {+ this.#rpcWs?.close();+ } catch (error) {+ console.error("Failed to close JSON-RPC WebSocket connection:", error);+ }+ }+}++export class KernelState implements IKernelPluginState {+ #code: TKernelPluginState = -1;+ #description: string = "inactive";++ #onchange: ((state: IKernelPluginState) => void);++ constructor(onchange: ((state: IKernelPluginState) => void)) {+ this.#onchange = onchange;+ }++ set code(state: TKernelPluginState) {+ this.#code = state;+ this.#description = (() => {+ switch (state) {+ case -1:+ return "inactive";+ case 0:+ return "ready";+ case 1:+ return "loading";+ case 2:+ return "running";+ case 3:+ return "stopping";+ case 4:+ return "stopped";+ case 5:+ return "error";+ default:+ return "unknown";+ }+ })();++ this.#onchange({+ code: this.#code,+ description: this.#description,+ });+ }++ get code() {+ return this.#code;+ }++ get description() {+ return this.#description;+ }+}++export class JsonRpcError extends Error implements IKernelPluginRpcError {+ code: number;+ data?: any;++ constructor(error: IKernelPluginRpcError) {+ super(error.message);++ this.code = error.code;+ this.data = error.data;+ }+}diff --git a/app/src/plugin/loader.ts b/app/src/plugin/loader.tsindex df9ab62f1f..7b0d7e6818 100644--- a/app/src/plugin/loader.ts+++ b/app/src/plugin/loader.ts@@ -74,6 +74,7 @@ const loadPluginJS = async (app: App, item: IPluginData) => {} catch (e) {console.error(`plugin ${item.name} onload error:`, e);}+ await plugin.kernel.init();return plugin;};diff --git a/app/src/plugin/uninstall.ts b/app/src/plugin/uninstall.tsindex 24e8d2e7e6..7f1e980793 100644--- a/app/src/plugin/uninstall.ts+++ b/app/src/plugin/uninstall.ts@@ -17,6 +17,7 @@ export const uninstall = (app: App, name: string, isReload: boolean) => {} catch (e) {console.error(`plugin ${plugin.name} onunload error:`, e);}+ plugin.kernel.destroy();if (!isReload) {try {plugin.uninstall();diff --git a/app/src/types/index.d.ts b/app/src/types/index.d.tsindex dfe2128095..8e68dd6f50 100644--- a/app/src/types/index.d.ts+++ b/app/src/types/index.d.ts@@ -91,7 +91,8 @@ type TEventBus = "ws-main" | "sync-start" | "sync-end" | "sync-fail" |"destroy-protyle" |"lock-screen" |"mobile-keyboard-show" | "mobile-keyboard-hide" |- "code-language-update" | "code-language-change"+ "code-language-update" | "code-language-change" |+ "kernel-plugin-state-change"type TAVView = "table" | "gallery" | "kanban"type TAVCol ="text"@@ -132,6 +133,26 @@ type TAVFilterOperator =type TRecentDocsSort = "viewedAt" | "closedAt" | "openAt" | "updated"type TPublishAccessLevel = "public" | "protected" | "hidden" | "private" | "forbidden";+/**+ * 内核插件状态+ * - `-1`: inactive 内核插件未安装或不可用+ * - `0`: ready 内核插件已安装但未启动+ * - `1`: loading 内核插件正在启动+ * - `2`: running 内核插件正在运行, 可正常使用+ * - `3`: stopping 内核插件正在停止+ * - `4`: stopped 内核插件已停止+ * - `5`: error 内核插件出现不可恢复的错误+ */+type TKernelPluginState = -1 | 0 | 1 | 2 | 3 | 4 | 5++type TJsonRpcId = string | number;+type TJsonRpcMethod = string;+type TJsonRpcPositionalParams = any[];+type TJsonRpcNamedParams = Record<string, any>;+type TJsonRpcParams = TJsonRpcPositionalParams | TJsonRpcNamedParams | undefined;+type TJsonRpcMethodParams = TJsonRpcPositionalParams | [TJsonRpcNamedParams] | [];+type TJsonRpcHandler<T = any> = (...args: TJsonRpcMethodParams) => Promise<T> | T;+declare module "blueimp-md5"declare class Highlight {@@ -437,7 +458,7 @@ interface IInbox {interface IPdfAnno {pages?: {index: number- positions: number []+ positions: number[]}[]index?: number,color: string,@@ -635,7 +656,6 @@ interface IOperationSrcs {isDetached: boolean}-interface IObject {[key: string]: string;}@@ -853,7 +873,7 @@ interface IRiffCard {}interface IModels {- editor: import("../editor").Editor [],+ editor: import("../editor").Editor[],graph: import("../layout/dock/Graph").Graph[],outline: import("../layout/dock/Outline").Outline[]backlink: import("../layout/dock/Backlink").Backlink[]@@ -1165,3 +1185,105 @@ interface IPublishAccessItem {disable: booleaniconHTML?: string}++interface IKernelPlugin {+ /**+ * 内核插件的状态管理接口+ */+ state: IKernelPluginState;++ /**+ * 内核插件的 JSON-RPC 调用接口+ */+ rpc: IKernelPluginRpc;+}++interface IKernelPluginState {+ /**+ * 内核插件的当前状态+ */+ code: TKernelPluginState;++ /**+ * 内核插件状态的描述信息+ */+ description: string;+}++interface IKernelPluginRpcCall {+ /**+ * JSON-RPC 2.0 中 method 必须是 string,且插件开发者需要保证传入的方法名与内核插件绑定的方法名一致,否则可能会导致调用失败+ */+ method: TJsonRpcMethod;++ /**+ * JSON-RPC 2.0 中 id 可以是 string、number 或 null,但为了兼容性和实用性,插件系统中不允许使用 null 作为 id+ *+ * 不设置时且 notification 不为 true 时会自动生成一个唯一的 id,设置时必须保证 id 的唯一性,否则可能会导致响应错误或混乱+ */+ id?: TJsonRpcId;++ /**+ * JSON-RPC 2.0 中 params 可以是 array 或 object,插件开发者需要自行保证传入参数与内核插件绑定的方法参数一致+ */+ params?: any[] | Record<string, any>;++ /**+ * 是否为通知,通知不会有响应,且不应传入 id+ * @defaultValue false+ */+ notification?: boolean;+}++interface IKernelPluginRpcRequest extends IKernelPluginRpcCall {+ jsonrpc: "2.0";+}++interface IKernelPluginRpcBaseResponse {+ jsonrpc: "2.0";+}++interface IKernelPluginRpcResultResponse extends IKernelPluginRpcBaseResponse {+ id: TJsonRpcId;+ result?: any;+}++interface IKernelPluginRpcErrorResponse extends IKernelPluginRpcBaseResponse {+ id: TJsonRpcId | null;+ error?: any;+}++interface IKernelPluginRpcError {+ code: number;+ message: string;+ data?: any;+}++++interface IKernelPluginRpc {+ /**+ * 通过 {@link Proxy} 实现的动态方法调用,插件开发者可以直接调用 `call.方法名(params)` 来调用内核插件暴露的方法,无需关心 JSON-RPC 的细节+ */+ call: Record<TJsonRpcMethod, (...args: TJsonRpcMethodParams) => Promise<any>>;++ /**+ * 通过 {@link Proxy} 实现的动态方法调用,插件开发者可以直接调用 `notify.方法名(...args)` 来发送通知给内核插件,无需关心 JSON-RPC 的细节+ */+ notify: Record<TJsonRpcMethod, (...args: TJsonRpcMethodParams) => void>;++ /**+ * 批量调用方法,接受一个方法调用数组,返回一个结果数组,结果数组中的每一项对应方法调用数组中非通知的每一项,包含成功的结果或错误信息+ */+ batch: (...calls: IKernelPluginRpcCall[]) => Promise<IKernelPluginRpcError | (IKernelPluginRpcResultResponse | IKernelPluginRpcErrorResponse)[]>;++ /**+ * 绑定内核插件调用时的事件处理函数,插件开发者可以通过 `bind("方法名", handler)` 来监听内核插件通过 JSON-RPC 推送到客户端插件的通知+ */+ bind: (method: TJsonRpcMethod, handler: TJsonRpcHandler<void>) => void;++ /**+ * 解绑事件处理函数,插件开发者可以通过 `unbind("方法名", handler)` 来停止监听内核插件通过 JSON-RPC 推送到客户端插件的通知+ */+ unbind: (method: TJsonRpcMethod, handler: TJsonRpcHandler<void>) => void;+}diff --git a/app/src/window/closeWin.ts b/app/src/window/closeWin.tsindex b8bb4815dd..aa419b1cca 100644--- a/app/src/window/closeWin.ts+++ b/app/src/window/closeWin.ts@@ -4,11 +4,13 @@ import { ipcRenderer } from "electron";export const closeWindow = async (app: App) => {for (let i = 0; i < app.plugins.length; i++) {+ const plugin = app.plugins[i];try {- await app.plugins[i].onunload();+ await plugin.onunload();} catch (e) {console.error(e);}+ await plugin.kernel.destroy();}ipcRenderer.send(Constants.SIYUAN_CMD, "destroy");};diff --git a/kernel/plugin/api_client.go b/kernel/plugin/api_client.goindex d1377993e9..22d1ba35ac 100644--- a/kernel/plugin/api_client.go+++ b/kernel/plugin/api_client.go@@ -48,25 +48,22 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err elo.Must0(client.Set("fetch", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {promise, resolve, reject := rt.NewPromise()- runErr := p.worker.Run(func(rt *goja.Runtime) (_ any, err error) {- var path string- if goja.IsString(call.Argument(0)) {- path = call.Argument(0).String()- } else {- err = fmt.Errorf("path required")- return- }-- if !strings.HasPrefix(path, "/") {- err = fmt.Errorf("path must start with /")- return- }-- method := "GET"- headers := map[string]string{}- var bodyString string- var bodyBytes []byte-+ var argErr error+ var path string+ method := "GET"+ headers := map[string]string{}+ var bodyString *string+ var bodyBytes *[]byte++ if goja.IsString(call.Argument(0)) {+ path = call.Argument(0).String()+ } else {+ argErr = fmt.Errorf("path required")+ }+ if argErr == nil && !strings.HasPrefix(path, "/") {+ argErr = fmt.Errorf("path must start with /")+ }+ if argErr == nil {if init := call.Argument(1); isJsValueNotNull(init) {if initObj := init.ToObject(rt); initObj != nil {if m := initObj.Get("method"); goja.IsString(m) {@@ -75,26 +72,32 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err eif h := initObj.Get("headers"); isJsValueNotNull(h) {if exportErr := rt.ExportTo(h, &headers); exportErr != nil {- err = fmt.Errorf("failed to export headers: %w", exportErr)- return+ argErr = fmt.Errorf("failed to export headers: %w", exportErr)}}- if b := initObj.Get("body"); isJsValueNotNull(b) {-- if goja.IsString(b) {- bodyString = b.String()- } else {- body := b.Export()- if arrayBuffer, ok := body.(goja.ArrayBuffer); ok {- src := arrayBuffer.Bytes()- bodyBytes = make([]byte, len(src))- copy(bodyBytes, src)+ if argErr == nil {+ if b := initObj.Get("body"); isJsValueNotNull(b) {+ if goja.IsString(b) {+ bodyString = lo.ToPtr(b.String())+ } else {+ body := b.Export()+ if arrayBuffer, ok := body.(goja.ArrayBuffer); ok {+ src := arrayBuffer.Bytes()+ bodyBytes = lo.ToPtr(src)+ }}}}}}+ }++ runErr := p.worker.Run(func(rt *goja.Runtime) (_ any, err error) {+ if argErr != nil {+ err = argErr+ return+ }go func() {var err error@@ -120,10 +123,10 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err e}r.SetHeader(model.XAuthTokenKey, p.token)- if bodyString != "" {- r.SetBody(bodyString)- } else if len(bodyBytes) > 0 {- r.SetBody(bodyBytes)+ if bodyString != nil {+ r.SetBody(*bodyString)+ } else if bodyBytes != nil {+ r.SetBody(*bodyBytes)}resp, sendErr := r.Send(method, targetURL)@@ -192,21 +195,19 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err elo.Must0(client.Set("socket", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {promise, resolve, reject := rt.NewPromise()- runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {- var path string- if goja.IsString(call.Argument(0)) {- path = call.Argument(0).String()- } else {- err = fmt.Errorf("path required")- return- }-- if !strings.HasPrefix(path, "/") {- err = fmt.Errorf("path must start with /")- return- }+ var argErr error+ var path string+ var protocols []string- var protocols []string+ if goja.IsString(call.Argument(0)) {+ path = call.Argument(0).String()+ } else {+ argErr = fmt.Errorf("path required")+ }+ if argErr == nil && !strings.HasPrefix(path, "/") {+ argErr = fmt.Errorf("path must start with /")+ }+ if argErr == nil {if proto := call.Argument(1); isJsValueNotNull(proto) {if protoObj := proto.ToObject(rt); protoObj != nil && protoObj.ClassName() == "Array" {if arr, ok := proto.Export().([]interface{}); ok {@@ -218,6 +219,13 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err eprotocols = []string{proto.String()}}}+ }++ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {+ if argErr != nil {+ err = argErr+ return+ }var gwsConn atomic.Pointer[gws.Conn]var readyState atomic.Int64@@ -355,21 +363,21 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err ews_send := rt.ToValue(func(sendCall goja.FunctionCall, rt *goja.Runtime) goja.Value {sendPromise, sendResolve, sendReject := rt.NewPromise()- sendRunErr := p.worker.Run(func(rt *goja.Runtime) (_ any, err error) {- var messageData []byte- var opcode gws.Opcode- if data := sendCall.Argument(0); isJsValueNotNull(data) {- if arrayBuffer, ok := data.Export().(goja.ArrayBuffer); ok {- opcode = gws.OpcodeBinary- b := arrayBuffer.Bytes()- messageData = make([]byte, len(b))- copy(messageData, b) // ArrayBuffer.Bytes() points into JS engine memory; copy before async send- } else {- opcode = gws.OpcodeText- messageData = []byte(data.String())- }+ var messageData []byte+ var opcode gws.Opcode+ if data := sendCall.Argument(0); isJsValueNotNull(data) {+ if arrayBuffer, ok := data.Export().(goja.ArrayBuffer); ok {+ opcode = gws.OpcodeBinary+ b := arrayBuffer.Bytes()+ messageData = make([]byte, len(b))+ copy(messageData, b) // ArrayBuffer.Bytes() points into JS engine memory; copy before async send+ } else {+ opcode = gws.OpcodeText+ messageData = []byte(data.String())}+ }+ sendRunErr := p.worker.Run(func(rt *goja.Runtime) (_ any, err error) {state := WebSocketState(readyState.Load())if state == WebSocketReadyStateClosing || state == WebSocketReadyStateClosed {err = fmt.Errorf("WebSocket is not open (state: %d)", state)@@ -421,11 +429,12 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err ews_ping := rt.ToValue(func(pingCall goja.FunctionCall, rt *goja.Runtime) goja.Value {pingPromise, pingResolve, pingReject := rt.NewPromise()+ var pingData string+ if isJsValueNotNull(pingCall.Argument(0)) {+ pingData = pingCall.Argument(0).String()+ }+pingRunErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {- var pingData string- if isJsValueNotNull(pingCall.Argument(0)) {- pingData = pingCall.Argument(0).String()- }if c := gwsConn.Load(); c != nil {err = c.WritePing([]byte(pingData))} else {@@ -453,11 +462,12 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err ews_pong := rt.ToValue(func(pongCall goja.FunctionCall, rt *goja.Runtime) goja.Value {pongPromise, pongResolve, pongReject := rt.NewPromise()+ var pongData string+ if isJsValueNotNull(pongCall.Argument(0)) {+ pongData = pongCall.Argument(0).String()+ }+pongRunErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {- var pongData string- if isJsValueNotNull(pongCall.Argument(0)) {- pongData = pongCall.Argument(0).String()- }if c := gwsConn.Load(); c != nil {err = c.WritePong([]byte(pongData))} else {@@ -485,15 +495,16 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err ews_close := rt.ToValue(func(closeCall goja.FunctionCall, rt *goja.Runtime) goja.Value {closePromise, closeResolve, closeReject := rt.NewPromise()+ code := uint16(1000)+ var reason []byte+ if isJsValueNotNull(closeCall.Argument(0)) {+ code = uint16(closeCall.Argument(0).ToInteger())+ }+ if isJsValueNotNull(closeCall.Argument(1)) {+ reason = []byte(closeCall.Argument(1).String())+ }+closeRunErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {- code := uint16(1000)- var reason []byte- if isJsValueNotNull(closeCall.Argument(0)) {- code = uint16(closeCall.Argument(0).ToInteger())- }- if isJsValueNotNull(closeCall.Argument(1)) {- reason = []byte(closeCall.Argument(1).String())- }if c := gwsConn.Load(); c != nil {setReadyState(rt, WebSocketReadyStateClosing)err = c.WriteClose(code, reason)@@ -562,17 +573,20 @@ func injectClient(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err elo.Must0(client.Set("event", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {promise, resolve, reject := rt.NewPromise()- runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {- var path string- if goja.IsString(call.Argument(0)) {- path = call.Argument(0).String()- } else {- err = fmt.Errorf("path required")- return- }+ var argErr error+ var path string+ if goja.IsString(call.Argument(0)) {+ path = call.Argument(0).String()+ } else {+ argErr = fmt.Errorf("path required")+ }+ if argErr == nil && !strings.HasPrefix(path, "/") {+ argErr = fmt.Errorf("path must start with /")+ }- if !strings.HasPrefix(path, "/") {- err = fmt.Errorf("path must start with /")+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {+ if argErr != nil {+ err = argErrreturn}diff --git a/kernel/plugin/api_event.go b/kernel/plugin/api_event.goindex c5c71e3c9b..76e007a30a 100644--- a/kernel/plugin/api_event.go+++ b/kernel/plugin/api_event.go@@ -39,21 +39,26 @@ func injectEvent(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err erlo.Must0(event.Set("emit", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {promise, resolve, reject := rt.NewPromise()- runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {- if len(call.Arguments) < 2 {- err = fmt.Errorf("topic and event required")- return+ var argErr error+ var topic string+ var eventData any+ if len(call.Arguments) < 2 {+ argErr = fmt.Errorf("topic and event required")+ } else {+ topic = call.Argument(0).String()+ if topic == "" {+ argErr = fmt.Errorf("topic required")+ } else {+ eventData = call.Argument(1).Export()}+ }- topic := call.Argument(0).String()- if topic == "" {- err = fmt.Errorf("topic required")+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {+ if argErr != nil {+ err = argErrreturn}-- event := call.Argument(1).Export()-- p.bus.Publish(topic, event)+ p.bus.Publish(topic, eventData)return}, func(rt *goja.Runtime, result any, err error) {if lo.IsNil(err) {diff --git a/kernel/plugin/api_logger.go b/kernel/plugin/api_logger.goindex 09ed5746c5..eb33f9fc60 100644--- a/kernel/plugin/api_logger.go+++ b/kernel/plugin/api_logger.go@@ -75,55 +75,26 @@ func injectLogger(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err e// Logging is synchronous (in-process, no I/O), so resolve is called inline without worker.Run.func loggerWrapper(p *KernelPlugin, logf func(format string, args ...any)) func(goja.FunctionCall, *goja.Runtime) goja.Value {return func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {- promise, resolve, reject := rt.NewPromise()-- runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {- parts := make([]string, 0, len(call.Arguments))- for _, arg := range call.Arguments {- if goja.IsString(arg) {- parts = append(parts, arg.String())- continue- }-- if arg == nil {- parts = append(parts, "null")- continue- }-- if goja.IsUndefined(arg) || goja.IsNull(arg) {- parts = append(parts, arg.String())- continue- }-- argObj := arg.ToObject(rt)- if argObj != nil {- if argJson, marshalErr := argObj.MarshalJSON(); marshalErr == nil {- parts = append(parts, string(argJson))- continue- }- }-+ parts := make([]string, 0, len(call.Arguments))+ for _, arg := range call.Arguments {+ if goja.IsString(arg) {parts = append(parts, arg.String())+ continue}- msg := strings.Join(parts, " ")-- go print(p.Name, msg, logf)- return- }, func(rt *goja.Runtime, result any, err error) {- if lo.IsNil(err) {- if resolveErr := resolve(result); resolveErr != nil {- logging.LogErrorf("[plugin:%s] siyuan.logger resolve: %v", p.Name, resolveErr)- }- } else {- if rejectErr := reject(rt.NewGoError(err)); rejectErr != nil {- logging.LogErrorf("[plugin:%s] siyuan.logger reject: %v", p.Name, rejectErr)+ if arg == nil || goja.IsUndefined(arg) || goja.IsNull(arg) {+ parts = append(parts, arg.String())+ continue+ }+ argObj := arg.ToObject(rt)+ if argObj != nil {+ if argJson, marshalErr := argObj.MarshalJSON(); marshalErr == nil {+ parts = append(parts, string(argJson))+ continue}}- })- if runErr != nil {- logging.LogErrorf("[plugin:%s] siyuan.logger worker run: %v", p.Name, runErr)+ parts = append(parts, arg.String())}-- return rt.ToValue(promise)+ go print(p.Name, strings.Join(parts, " "), logf)+ return goja.Undefined()}}diff --git a/kernel/plugin/api_plugin.go b/kernel/plugin/api_plugin.goindex e82a01eb15..807a455e27 100644--- a/kernel/plugin/api_plugin.go+++ b/kernel/plugin/api_plugin.go@@ -34,7 +34,6 @@ func injectPlugin(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err elifecycle := rt.NewObject()lo.Must0(lifecycle.Set("onload", goja.Null()))- lo.Must0(lifecycle.Set("onloaded", goja.Null()))lo.Must0(lifecycle.Set("onrunning", goja.Null()))lo.Must0(lifecycle.Set("onunload", goja.Null()))lo.Must0(ObjectSeal(rt, lifecycle))diff --git a/kernel/plugin/api_rpc.go b/kernel/plugin/api_rpc.goindex 5923d80dc3..40193e8f46 100644--- a/kernel/plugin/api_rpc.go+++ b/kernel/plugin/api_rpc.go@@ -38,37 +38,41 @@ func injectRpc(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err errolo.Must0(rpc.Set("bind", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {promise, resolve, reject := rt.NewPromise()- runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {- var name string- var method goja.Callable- var descriptions []string-- if len(call.Arguments) < 2 {- err = fmt.Errorf("method name and function required")- return- }+ var argErr error+ var name string+ var method goja.Callable+ var descriptions []string+ if len(call.Arguments) < 2 {+ argErr = fmt.Errorf("method name and function required")+ } else {nameArg := call.Argument(0)methodArg := call.Argument(1)descArgs := call.Arguments[2:]-if goja.IsString(nameArg) {name = nameArg.String()} else {- err = fmt.Errorf("first argument must be method name string")- return+ argErr = fmt.Errorf("first argument must be method name string")}-- if methodJs, ok := goja.AssertFunction(methodArg); ok {- method = methodJs- } else {- err = fmt.Errorf("second argument must be a function")+ if argErr == nil {+ if methodJs, ok := goja.AssertFunction(methodArg); ok {+ method = methodJs+ } else {+ argErr = fmt.Errorf("second argument must be a function")+ }}-- descriptions = make([]string, len(descArgs))- for i, a := range descArgs {- descriptions[i] = a.String()+ if argErr == nil {+ descriptions = make([]string, len(descArgs))+ for i, a := range descArgs {+ descriptions[i] = a.String()+ }}+ }+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {+ if argErr != nil {+ err = argErr+ return+ }err = p.bindRpcMethod(name, method, descriptions...)return}, func(rt *goja.Runtime, result any, err error) {@@ -92,21 +96,21 @@ func injectRpc(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err errolo.Must0(rpc.Set("unbind", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {promise, resolve, reject := rt.NewPromise()- runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {- var name string- if len(call.Arguments) < 1 {- err = fmt.Errorf("method name required")- return- }+ var argErr error+ var name string+ if len(call.Arguments) < 1 {+ argErr = fmt.Errorf("method name required")+ } else if nameArg := call.Argument(0); goja.IsString(nameArg) {+ name = nameArg.String()+ } else {+ argErr = fmt.Errorf("first argument must be method name string")+ }- nameArg := call.Argument(0)- if goja.IsString(nameArg) {- name = nameArg.String()- } else {- err = fmt.Errorf("first argument must be method name string")+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {+ if argErr != nil {+ err = argErrreturn}-err = p.unbindRpcMethod(name)return}, func(rt *goja.Runtime, result any, err error) {@@ -130,36 +134,40 @@ func injectRpc(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (err errolo.Must0(rpc.Set("broadcast", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {promise, resolve, reject := rt.NewPromise()- runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {- if len(call.Arguments) < 1 {- err = fmt.Errorf("method required")- return- }-- var method string+ var argErr error+ var method string+ var params util.Optional[any]+ if len(call.Arguments) < 1 {+ argErr = fmt.Errorf("method required")+ } else {if m := call.Argument(0); goja.IsString(m) {method = m.String()} else {- err = fmt.Errorf("first argument must be method name string")- return+ argErr = fmt.Errorf("first argument must be method name string")}-- var params util.Optional[any]- arg := call.Argument(1)- if goja.IsUndefined(arg) {- params.Value = nil- params.Exists = false- params.IsNull = false- } else if goja.IsNull(arg) {- params.Value = nil- params.Exists = true- params.IsNull = true- } else {- params.Value = arg.Export()- params.Exists = true- params.IsNull = false+ if argErr == nil {+ arg := call.Argument(1)+ if goja.IsUndefined(arg) {+ params.Value = nil+ params.Exists = false+ params.IsNull = false+ } else if goja.IsNull(arg) {+ params.Value = nil+ params.Exists = true+ params.IsNull = true+ } else {+ params.Value = arg.Export()+ params.Exists = true+ params.IsNull = false+ }}+ }+ runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {+ if argErr != nil {+ err = argErr+ return+ }p.BroadcastNotification(method, params)return}, func(rt *goja.Runtime, result any, err error) {diff --git a/kernel/plugin/api_storage.go b/kernel/plugin/api_storage.goindex 9bec63a3ec..2fb5547da5 100644--- a/kernel/plugin/api_storage.go+++ b/kernel/plugin/api_storage.go@@ -51,27 +51,27 @@ func injectStorage(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (errlo.Must0(watcher.Set("add", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {promise, resolve, reject := rt.NewPromise()+ var argErr error+ var path string+ if len(call.Arguments) >= 1 && goja.IsString(call.Argument(0)) {+ path = call.Argument(0).String()+ } else {+ argErr = fmt.Errorf("path required")+ }+runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {- var path string- if len(call.Arguments) >= 1 && goja.IsString(call.Argument(0)) {- path = call.Argument(0).String()- } else {- err = fmt.Errorf("path required")+ if argErr != nil {+ err = argErrreturn}-abs, resolveErr := resolvePath(path)if resolveErr != nil {err = resolveErrreturn}-- addErr := p.addStorageWatch(abs)- if addErr != nil {+ if addErr := p.addStorageWatch(abs); addErr != nil {err = fmt.Errorf("failed to add storage path to watcher: %v", addErr)- return}-return}, func(rt *goja.Runtime, result any, err error) {if lo.IsNil(err) {@@ -95,27 +95,27 @@ func injectStorage(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (errlo.Must0(watcher.Set("remove", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {promise, resolve, reject := rt.NewPromise()+ var argErr error+ var path string+ if len(call.Arguments) >= 1 && goja.IsString(call.Argument(0)) {+ path = call.Argument(0).String()+ } else {+ argErr = fmt.Errorf("path required")+ }+runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {- var path string- if len(call.Arguments) >= 1 && goja.IsString(call.Argument(0)) {- path = call.Argument(0).String()- } else {- err = fmt.Errorf("path required")+ if argErr != nil {+ err = argErrreturn}-abs, resolveErr := resolvePath(path)if resolveErr != nil {err = resolveErrreturn}-- addErr := p.removeStorageWatch(abs)- if addErr != nil {- err = fmt.Errorf("failed to remove storage path from watcher: %v", addErr)- return+ if removeErr := p.removeStorageWatch(abs); removeErr != nil {+ err = fmt.Errorf("failed to remove storage path from watcher: %v", removeErr)}-return}, func(rt *goja.Runtime, result any, err error) {if lo.IsNil(err) {@@ -143,15 +143,19 @@ func injectStorage(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (errlo.Must0(storage.Set("get", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {promise, resolve, reject := rt.NewPromise()+ var argErr error+ var path string+ if len(call.Arguments) >= 1 && goja.IsString(call.Argument(0)) {+ path = call.Argument(0).String()+ } else {+ argErr = fmt.Errorf("path required")+ }+runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {- var path string- if len(call.Arguments) >= 1 && goja.IsString(call.Argument(0)) {- path = call.Argument(0).String()- } else {- err = fmt.Errorf("path required")+ if argErr != nil {+ err = argErrreturn}-abs, resolveErr := resolvePath(path)if resolveErr != nil {err = resolveErr@@ -216,18 +220,25 @@ func injectStorage(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (errlo.Must0(storage.Set("put", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {promise, resolve, reject := rt.NewPromise()+ var argErr error+ var path, content string+ if len(call.Arguments) < 2 {+ argErr = fmt.Errorf("path and content required")+ } else {+ path = call.Argument(0).String()+ content = call.Argument(1).String()+ }+runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {+ if argErr != nil {+ err = argErr+ return+ }if util.ReadOnly {err = fmt.Errorf("The current kernel is in read-only mode, storage.put is not allowed")return}- if len(call.Arguments) < 2 {- err = fmt.Errorf("path and content required")- return- }- path := call.Argument(0).String()- content := call.Argument(1).String()abs, resolveErr := resolvePath(path)if resolveErr != nil {err = resolveErr@@ -284,17 +295,24 @@ func injectStorage(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (errlo.Must0(storage.Set("remove", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {promise, resolve, reject := rt.NewPromise()+ var argErr error+ var path string+ if len(call.Arguments) < 1 {+ argErr = fmt.Errorf("path required")+ } else {+ path = call.Argument(0).String()+ }+runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {+ if argErr != nil {+ err = argErr+ return+ }if util.ReadOnly {err = fmt.Errorf("The current kernel is in read-only mode, storage.remove is not allowed")return}- if len(call.Arguments) < 1 {- err = fmt.Errorf("path required")- return- }- path := call.Argument(0).String()abs, resolveErr := resolvePath(path)if resolveErr != nil {err = resolveErr@@ -351,12 +369,19 @@ func injectStorage(p *KernelPlugin, rt *goja.Runtime, siyuan *goja.Object) (errlo.Must0(storage.Set("list", rt.ToValue(func(call goja.FunctionCall, rt *goja.Runtime) goja.Value {promise, resolve, reject := rt.NewPromise()+ var argErr error+ var path string+ if len(call.Arguments) < 1 {+ argErr = fmt.Errorf("path required")+ } else {+ path = call.Argument(0).String()+ }+runErr := p.worker.Run(func(rt *goja.Runtime) (result any, err error) {- if len(call.Arguments) < 1 {- err = fmt.Errorf("path required")+ if argErr != nil {+ err = argErrreturn}- path := call.Argument(0).String()abs, resolveErr := resolvePath(path)if resolveErr != nil {err = resolveErrdiff --git a/kernel/plugin/manager.go b/kernel/plugin/manager.goindex e04ffe5349..49492bcea3 100644--- a/kernel/plugin/manager.go+++ b/kernel/plugin/manager.go@@ -51,9 +51,10 @@ type PluginManager struct {}type PluginInfo struct {- Name string `json:"name"`- State string `json:"state"`- Methods []*RpcMethodInfo `json:"methods"`+ Name string `json:"name"`+ State string `json:"state"`+ StateCode int `json:"stateCode"`+ Methods []*RpcMethodInfo `json:"methods"`}var (@@ -312,9 +313,10 @@ func (m *PluginManager) GetLoadedPlugin(name string) (plugin *PluginInfo, foundp := m.GetPlugin(name)if p != nil {return &PluginInfo{- Name: p.Name,- State: p.State().String(),- Methods: p.GetRpcMethodsInfo(),+ Name: p.Name,+ State: p.State().String(),+ StateCode: int(p.State()),+ Methods: p.GetRpcMethodsInfo(),}, true}return nil, false@@ -325,9 +327,10 @@ func (m *PluginManager) GetLoadedPluginsInfo() (plugins []*PluginInfo) {m.plugins.Range(func(key, value any) bool {p := value.(*KernelPlugin)plugins = append(plugins, &PluginInfo{- Name: p.Name,- State: p.State().String(),- Methods: p.GetRpcMethodsInfo(),+ Name: p.Name,+ State: p.State().String(),+ StateCode: int(p.State()),+ Methods: p.GetRpcMethodsInfo(),})return true})@@ -346,12 +349,11 @@ func (m *PluginManager) addPluginSourceWatch(name string) {}// removePluginSourceWatch removes the plugin's base directory from the fsnotify watcher when the plugin is stopped.-func (m *PluginManager) removePluginSourceWatch(name string) {+func (m *PluginManager) removePluginSourceWatch(name string) (err error) {if m.watcher == nil {return}path := filepath.Join(m.pluginsDir, name)- if err := m.watcher.Remove(path); err != nil {- logging.LogErrorf("failed to remove kernel plugin source path [%s] from watcher: %s", path, err)- }+ err = m.watcher.Remove(path)+ return}diff --git a/kernel/plugin/plugin.go b/kernel/plugin/plugin.goindex 88175b13cd..ebff1b03b6 100644--- a/kernel/plugin/plugin.go+++ b/kernel/plugin/plugin.go@@ -63,7 +63,6 @@ const (const (PluginStateReady PluginState = iotaPluginStateLoading- PluginStateLoadedPluginStateRunningPluginStateStoppingPluginStateStopped@@ -76,8 +75,6 @@ func (s PluginState) String() string {return "ready"case PluginStateLoading:return "loading"- case PluginStateLoaded:- return "loaded"case PluginStateRunning:return "running"case PluginStateStopping:@@ -148,7 +145,7 @@ func NewKernelPlugin(ctx context.Context, petal *model.Petal) *KernelPlugin {sockets: make(map[*gws.Conn]bool),}- plugin.state.Store(int64(PluginStateReady))+ plugin.updateState(PluginStateReady)return plugin}@@ -166,6 +163,12 @@ func (p *KernelPlugin) State() PluginState {return PluginState(p.state.Load())}+// updateState updates the plugin state atomically and pushes the new state to the frontend via util.PushKernelPluginState.+func (p *KernelPlugin) updateState(state PluginState) {+ p.state.Store(int64(state))+ util.PushKernelPluginState(p.Name, int(state))+}+// InitRuntime initializes the goja runtime and evaluates kernel.js.func (p *KernelPlugin) InitRuntime() (err error) {p.runtime = eventloop.NewEventLoop(eventloop.EnableConsole(true))@@ -226,7 +229,7 @@ func (p *KernelPlugin) error() {logging.LogErrorf("[plugin:%s] failed to close runtime during error handling: %v", p.Name, err)}- p.state.Store(int64(PluginStateError))+ p.updateState(PluginStateError)}// start creates the goja runtime, injects sandbox globals, and evaluates kernel.js.@@ -238,7 +241,7 @@ func (p *KernelPlugin) start() (err error) {}}()- p.state.Store(int64(PluginStateLoading))+ p.updateState(PluginStateLoading)baseDir := filepath.Join(util.DataDir, "storage", "petal", p.Name)if err := os.MkdirAll(baseDir, 0755); err != nil {@@ -258,9 +261,7 @@ func (p *KernelPlugin) start() (err error) {go p.startStorageWatch()p.onLoad()- p.state.Store(int64(PluginStateLoaded))- p.onLoaded()- p.state.Store(int64(PluginStateRunning))+ p.updateState(PluginStateRunning)p.onRunning()p.bus.Publish(EventBusTopicRuntime, createEventMessage("start", nil))@@ -286,7 +287,7 @@ func (p *KernelPlugin) stop() (ok bool, err error) {p.bus.Publish(EventBusTopicRuntime, createEventMessage("stop", nil))- p.state.Store(int64(PluginStateStopping))+ p.updateState(PluginStateStopping)p.onUnload()@@ -303,7 +304,7 @@ func (p *KernelPlugin) stop() (ok bool, err error) {p.unsubscribeEventHandlers()p.close()- p.state.Store(int64(PluginStateStopped))+ p.updateState(PluginStateStopped)logging.LogDebugf("[plugin:%s] stopped", p.Name)@@ -318,13 +319,6 @@ func (p *KernelPlugin) onLoad() {}}-// onLoaded is called after plugin loaded.-func (p *KernelPlugin) onLoaded() {- if p.State() == PluginStateLoaded {- p.invokeHook("onloaded")- }-}-// onRunning is called after plugin running.func (p *KernelPlugin) onRunning() {if p.State() == PluginStateRunning {diff --git a/kernel/util/websocket.go b/kernel/util/websocket.goindex 1cd22e8f0e..238ca092d6 100644--- a/kernel/util/websocket.go+++ b/kernel/util/websocket.go@@ -367,6 +367,10 @@ func PushReloadEmojiConf() {BroadcastByType("main", "reloadEmojiConf", 0, "", nil)}+func PushKernelPluginState(name string, state int) {+ BroadcastByType("main", "updateKernelPluginState", 0, "", map[string]any{"name": name, "state": state})+}+func PushDownloadProgress(id string, percent float32) {evt := NewCmdResult("downloadProgress", 0, PushModeBroadcast)evt.Data = map[string]any{