An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Diagnose appearance resource failures during startup
Daniel8c0ea5a63979
diff --git a/app/src/boot/loadLanguages.test.ts b/app/src/boot/loadLanguages.test.tsnew file mode 100644index 0000000000..633b519a31--- /dev/null+++ b/app/src/boot/loadLanguages.test.ts@@ -0,0 +1,56 @@+import {it} from "node:test";+import * as assert from "node:assert/strict";+import {loadLanguages} from "./loadLanguages";++it("stops startup and shows the failed language URL when the server returns 404", async () => {+ const originalFetch = globalThis.fetch;+ const originalDocument = globalThis.document;+ const originalConsoleError = console.error;+ let displayed = "";+ let role = "";+ let booted = false;+ globalThis.fetch = async () => new Response("", {status: 404});+ console.error = () => {};+ (globalThis as {document: Document}).document = {+ createElement: (tag: string) => {+ assert.equal(tag, "pre");+ return {+ textContent: "",+ setAttribute: (name: string, value: string) => {+ if (name === "role") {+ role = value;+ }+ },+ };+ },+ body: {+ replaceChildren: (element: {textContent: string}) => displayed = element.textContent,+ },+ } as unknown as Document;+ try {+ await loadLanguages("zh-CN", "3.8.6", () => booted = true);+ assert.equal(booted, false);+ assert.equal(role, "alert");+ assert.match(displayed, /\/appearance\/langs\/zh-CN\.json\?v=3\.8\.6\nError: HTTP 404/);+ } finally {+ globalThis.fetch = originalFetch;+ if (originalDocument === undefined) {+ delete (globalThis as {document?: Document}).document;+ } else {+ globalThis.document = originalDocument;+ }+ console.error = originalConsoleError;+ }+});++it("passes a valid language pack to startup", async () => {+ const originalFetch = globalThis.fetch;+ globalThis.fetch = async () => new Response(JSON.stringify({siyuanNote: "SiYuan"}), {status: 200});+ let loaded: IObject | undefined;+ try {+ await loadLanguages("en", "3.8.6", languages => loaded = languages);+ assert.equal(loaded?.siyuanNote, "SiYuan");+ } finally {+ globalThis.fetch = originalFetch;+ }+});diff --git a/app/src/boot/loadLanguages.ts b/app/src/boot/loadLanguages.tsnew file mode 100644index 0000000000..2851ac0045--- /dev/null+++ b/app/src/boot/loadLanguages.ts@@ -0,0 +1,24 @@+export const loadLanguages = async (lang: string, version: string, onLoaded: (languages: IObject) => void): Promise<void> => {+ const url = `/appearance/langs/${lang}.json?v=${version}`;+ let languages: IObject;+ try {+ const response = await fetch(url, {cache: "no-store"});+ if (!response.ok) {+ throw new Error(`HTTP ${response.status}`);+ }+ const data: unknown = await response.json();+ if (!data || typeof data !== "object" || Array.isArray(data) ||+ typeof (data as Record<string, unknown>).siyuanNote !== "string") {+ throw new SyntaxError("JSON");+ }+ languages = data as IObject;+ } catch (error) {+ console.error(url, error);+ const element = document.createElement("pre");+ element.setAttribute("role", "alert");+ element.textContent = `${url}\n${String(error)}`;+ document.body.replaceChildren(element);+ return;+ }+ onLoaded(languages);+};diff --git a/app/src/index.ts b/app/src/index.tsindex 6b76f9136a..f143e4adf8 100644--- a/app/src/index.ts+++ b/app/src/index.ts@@ -11,7 +11,7 @@ import {initBlockPopover} from "./block/popover";import {applyCloudUserState, onSetaccount} from "./config/tabs/accountUi";import {addScript, addScriptSync} from "./protyle/util/addScript";import {genUUID} from "./util/genID";-import {fetchGet, fetchPost} from "./util/fetch";+import {fetchPost} from "./util/fetch";import {addBaseURL,getDocDisplayName,@@ -63,6 +63,7 @@ import {ensureUILayout} from "./util/ensureUILayout";import {applyEntryVisibility} from "./config/entryVisibility/runtime";import {removeBlockPanelEditors} from "./block/panelRemoval";import {initializeEnglishCommandTranslations} from "./command/english";+import {loadLanguages} from "./boot/loadLanguages";import {installPluginStorageFetchAppId} from "./util/fetchAppId";export class App {@@ -323,11 +324,11 @@ export class App {await notebookPromise;await loadPlugins(this);getLocalStorage(() => {- fetchGet(`/appearance/langs/${window.siyuan.config.appearance.lang}.json?v=${Constants.SIYUAN_VERSION}`, (lauguages: IObject) => {- window.siyuan.languages = lauguages;+ void loadLanguages(window.siyuan.config.appearance.lang, Constants.SIYUAN_VERSION, (languages: IObject) => {+ window.siyuan.languages = languages;void initializeEnglishCommandTranslations(window.siyuan.config.appearance.lang,- lauguages as Record<string, string>,+ languages as Record<string, string>,Constants.SIYUAN_VERSION,);window.siyuan.menus = new Menus(this);diff --git a/app/src/mobile/index.ts b/app/src/mobile/index.tsindex 4c30b7a1b3..1353ba5da8 100644--- a/app/src/mobile/index.ts+++ b/app/src/mobile/index.ts@@ -23,7 +23,7 @@ import {handleTouchStart,handleTouchUp,} from "./util/touch";-import {fetchGet, fetchPost} from "../util/fetch";+import {fetchPost} from "../util/fetch";import {initFramework} from "./util/initFramework";import {finishMobileStartup} from "./util/setEmpty";import {initAssets} from "../util/assets";@@ -70,6 +70,7 @@ import {initHarmonyTextSelectionMenu} from "../util/harmonyTextSelectionMenu";import {updateMobileTopBarLayout} from "./util/mobileTopBar";import {showMobileBars} from "./util/mobileBars";import {initializeEnglishCommandTranslations} from "../command/english";+import {loadLanguages} from "../boot/loadLanguages";import {scrollInputIntoView} from "./util/visibleViewport";import {installPluginStorageFetchAppId} from "../util/fetchAppId";@@ -194,11 +195,11 @@ class App {correctHotkey(siyuanApp);await loadPlugins(this);getLocalStorage(() => {- fetchGet(`/appearance/langs/${window.siyuan.config.appearance.lang}.json?v=${Constants.SIYUAN_VERSION}`, (lauguages: IObject) => {- window.siyuan.languages = lauguages;+ void loadLanguages(window.siyuan.config.appearance.lang, Constants.SIYUAN_VERSION, (languages: IObject) => {+ window.siyuan.languages = languages;void initializeEnglishCommandTranslations(window.siyuan.config.appearance.lang,- lauguages as Record<string, string>,+ languages as Record<string, string>,Constants.SIYUAN_VERSION,);window.siyuan.menus = new Menus(this);diff --git a/app/src/window/index.ts b/app/src/window/index.tsindex cc0918de05..79d4d15c89 100644--- a/app/src/window/index.ts+++ b/app/src/window/index.ts@@ -7,7 +7,7 @@ import "../assets/scss/base.scss";import {initBlockPopover} from "../block/popover";import {addScript, addScriptSync} from "../protyle/util/addScript";import {genUUID} from "../util/genID";-import {fetchGet, fetchPost} from "../util/fetch";+import {fetchPost} from "../util/fetch";import {addBaseURL, getDocDisplayName, redirectToCheckAuth, setNoteBook} from "../util/pathName";import {openFileById} from "../editor/util";import {@@ -41,6 +41,7 @@ import {updateServerAddresses} from "../config/tabs/accessRuntime";import {applyCloudUserState} from "../config/tabs/accountUi";import {emitToPlugins} from "../plugin/EventBusCore";import {initializeEnglishCommandTranslations} from "../command/english";+import {loadLanguages} from "../boot/loadLanguages";import {installPluginStorageFetchAppId} from "../util/fetchAppId";class App {@@ -229,11 +230,11 @@ class App {await notebookPromise;await loadPlugins(this);getLocalStorage(() => {- fetchGet(`/appearance/langs/${window.siyuan.config.appearance.lang}.json?v=${Constants.SIYUAN_VERSION}`, (lauguages: IObject) => {- window.siyuan.languages = lauguages;+ void loadLanguages(window.siyuan.config.appearance.lang, Constants.SIYUAN_VERSION, (languages: IObject) => {+ window.siyuan.languages = languages;void initializeEnglishCommandTranslations(window.siyuan.config.appearance.lang,- lauguages as Record<string, string>,+ languages as Record<string, string>,Constants.SIYUAN_VERSION,);window.siyuan.menus = new Menus(this);diff --git a/kernel/server/appearance_diagnostic.go b/kernel/server/appearance_diagnostic.gonew file mode 100644index 0000000000..5c26a5454b--- /dev/null+++ b/kernel/server/appearance_diagnostic.go@@ -0,0 +1,76 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package server++import (+ "errors"+ "fmt"+ "os"+ "path/filepath"+ "sync"+ "syscall"++ "github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/util"+)++var diagnosedAppearanceRoots sync.Map++// logAppearanceRootDiagnostic 在启动完成后记录一次各级路径的访问结果,定位根目录解析失败的位置。+func logAppearanceRootDiagnostic(root, target string) {+ if !util.IsBooted() {+ return+ }+ if _, loaded := diagnosedAppearanceRoots.LoadOrStore(root, struct{}{}); loaded {+ return+ }++ var ancestors []string+ for current := root; ; current = filepath.Dir(current) {+ ancestors = append(ancestors, current)+ if parent := filepath.Dir(current); parent == current {+ break+ }+ }+ for i := len(ancestors) - 1; i >= 0; i-- {+ path := ancestors[i]+ _, lstatErr := os.Lstat(path)+ _, statErr := os.Stat(path)+ resolved, resolveErr := evalAppearanceSymlinks(path)+ logging.LogWarnf("appearance path diagnostic [%s]: lstat [%s], stat [%s], resolve [%s] [%s]",+ path, appearanceDiagnosticError(lstatErr), appearanceDiagnosticError(statErr),+ resolved, appearanceDiagnosticError(resolveErr))+ }+ for _, path := range []string{root, target} {+ file, err := os.Open(path)+ if err == nil {+ err = file.Close()+ }+ logging.LogWarnf("appearance path diagnostic [%s]: open [%s]", path, appearanceDiagnosticError(err))+ }+}++func appearanceDiagnosticError(err error) string {+ if err == nil {+ return "ok"+ }+ var errno syscall.Errno+ if errors.As(err, &errno) {+ return fmt.Sprintf("%s (errno %d)", err, errno)+ }+ return err.Error()+}diff --git a/kernel/server/appearance_path.go b/kernel/server/appearance_path.goindex 1662bbbbed..4a7b62d522 100644--- a/kernel/server/appearance_path.go+++ b/kernel/server/appearance_path.go@@ -68,6 +68,7 @@ func resolveAppearanceFilePath(root, requestPath string) (string, int) {resolvedRoot, err := evalAppearanceSymlinks(root)if err != nil {logging.LogWarnf("resolve appearance root [%s] failed: %s", root, err)+ logAppearanceRootDiagnostic(root, filepath.Join(append([]string{root}, segments...)...))return "", http.StatusNotFound}root = resolvedRoot