Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

7.6 KB
Raw Blame
import {Constants} from "../constants";
/// #if !MOBILE
import type {Tab} from "./Tab";
/// #endif
import type {App} from "../index";

interface IConnectOptions {
    id: string,
    type?: TWS,
    callback?: () => void,
    msgCallback?: (data: IWebSocketData) => void
}

export class Model {
    public ws: WebSocket;
    public reqId: number;
    private socketDisposed = false;
    private reconnectTimer: ReturnType<typeof setTimeout>;
    private mainMessageQueue: {
        data: string,
        callback: (data: IWebSocketData) => void
    }[] = [];

    public parent:

        /// #if !MOBILE
        Tab;
    /// #else
    // @ts-ignore
    null;
    /// #endif
    public app: App;

    constructor(options: {
        app: App,
    }) {
        this.app = options.app;
    }

    private processWebSocketMessage(data: string, callback: (data: IWebSocketData) => void) {
        // 消息处理依赖面板子类,调用时加载以避免基类初始化期间形成循环依赖。
        const {processMessage}: typeof import("../util/processMessage") = require("../util/processMessage");
        const message = processMessage(JSON.parse(data));
        if (message && message.cmd === "bazaarChanged") {
            const {refreshMountedBazaar}: typeof import("../config/bazaarTab") = require("../config/bazaarTab");
            void refreshMountedBazaar(message.data);
        }
        callback.call(this, message);
    }

    public flushMainMessages() {
        if (this.socketDisposed) return;
        const messages = this.mainMessageQueue.splice(0);
        messages.forEach((message) => {
            if (this.socketDisposed) return;
            try {
                this.processWebSocketMessage(message.data, message.callback);
            } catch (error) {
                console.error("Failed to process queued WebSocket message:", error);
            }
        });
        if (!this.socketDisposed && window.siyuan.isReady) {
            this.send("ready", {});
            const {refreshSettingConfig}: typeof import("../config/setting/sync") = require("../config/setting/sync");
            void refreshSettingConfig();
            const {reconcileSyncCheckout}: typeof import("../sync/checkoutProgress") = require("../sync/checkoutProgress");
            void reconcileSyncCheckout(new URL(this.ws.url).searchParams.get("id"));
        }
    }

    public connect(options: IConnectOptions) {
        if (this.socketDisposed) return;
        clearTimeout(this.reconnectTimer);
        const websocketURL = `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.host}/ws`;
        const ws = new WebSocket(`${websocketURL}?app=${Constants.SIYUAN_APPID}&id=${options.id}${options.type === "main" ? "&ready=false" : ""}${options.type ? "&type=" + options.type : ""}`);
        ws.onopen = () => {
            if (this.socketDisposed || this.ws !== ws) return;
            if (options.type === "main") {
                const {markKernelConnectionAlive}: typeof import("../util/kernelConnection") = require("../util/kernelConnection");
                markKernelConnectionAlive();
            }
            if (options.type === "main" && window.siyuan.isReady) {
                this.send("ready", {});
                const {reconcileSyncCheckout}: typeof import("../sync/checkoutProgress") = require("../sync/checkoutProgress");
                void reconcileSyncCheckout(options.id, true);
                const {reloadSettingsResetOnReconnect}: typeof import("../config/setting/reset") = require("../config/setting/reset");
                if (reloadSettingsResetOnReconnect()) return;
                const {resetSettingTaskRevision}: typeof import("../config/setting/taskBlocker") = require("../config/setting/taskBlocker");
                resetSettingTaskRevision();
                const {refreshSettingConfig}: typeof import("../config/setting/sync") = require("../config/setting/sync");
                void refreshSettingConfig();
            }
            if (options.callback) {
                options.callback.call(this);
            }
            const logElement = document.getElementById("errorLog");
            if (logElement) {
                const {reloadSync}: typeof import("../util/reloadSync") = require("../util/reloadSync");
                // 内核中断后无法 catch fetch 请求错误,重连会导致无法执行 transactionsTimeout
                reloadSync(this.app, {upsertRootIDs: [], removeRootIDs: []});
                window.siyuan.dialogs.find(item => {
                    if (item.element.id === "errorLog") {
                        item.destroy();
                        return true;
                    }
                });
            }
        };
        ws.onmessage = (event) => {
            if (this.socketDisposed || this.ws !== ws || !options.msgCallback) {
                return;
            }
            if (options.type === "main" && !window.siyuan.isReady) {
                this.mainMessageQueue.push({
                    data: event.data,
                    callback: options.msgCallback,
                });
                return;
            }
            // 非主 WebSocket 在界面初始化后创建,保留配置保护以避免异常连接提前处理消息。
            if (window.siyuan.config) {
                this.processWebSocketMessage(event.data, options.msgCallback);
            }
        };
        ws.onclose = (ev) => {
            if (this.socketDisposed || this.ws !== ws) return;
            if (0 <= ev.reason.indexOf("unauthenticated")) {
                return;
            }

            if (0 > ev.reason.indexOf("close websocket")) {
                console.warn("WebSocket is closed. Reconnect will be attempted in 3 second.", ev);
                this.reconnectTimer = setTimeout(() => {
                    this.connect(options);
                }, 3000);
            }
        };
        ws.onerror = (err: Event & { target: { url: string, readyState: number } }) => {
            if (this.socketDisposed || this.ws !== ws) return;
            if (err.target.url.endsWith("&type=main") && err.target.readyState === 3) {
                const {kernelError}: typeof import("../util/kernelFault") = require("../util/kernelFault");
                void kernelError(() => this.socketDisposed || this.ws !== ws);
            }
        };
        if (this.ws) {
            this.ws.onclose = null;
            this.ws.close();
        }
        this.ws = ws;
    }

    public send(cmd: string, param: Record<string, unknown>, process = false) {
        if (this.socketDisposed || !this.ws ||
            this.ws.readyState === WebSocket.CONNECTING ||
            this.ws.readyState === WebSocket.CLOSING ||
            this.ws.readyState === WebSocket.CLOSED) { // Inbox 无 WebSocket,关闭中的连接不能继续发送
            return;
        }
        this.reqId = process ? 0 : Date.now();
        this.ws.send(JSON.stringify({
            cmd,
            reqId: this.reqId,
            param,
            // pushMode
            // 0: 所有应用所有会话广播
            // 1:自我应用会话单播
            // 2:非自我会话广播
            // 4:非自我应用所有会话广播
            // 5:单个应用内所有会话广播
            // 6:非自我应用主会话广播
        }));
    }

    public destroy() {
        if (this.socketDisposed) return;
        this.socketDisposed = true;
        clearTimeout(this.reconnectTimer);
        this.mainMessageQueue.length = 0;
        if (this.ws) {
            this.ws.onopen = null;
            this.ws.onmessage = null;
            this.ws.onclose = null;
            this.ws.onerror = null;
            this.ws.close();
        }
    }
}