An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:white_check_mark: Isolate CD test runtime and publish asset fixtures
Liang Dingb3998f105483
diff --git a/app/scripts/test.mjs b/app/scripts/test.mjsindex 80c4eb2995..f5f8e13d9c 100644--- a/app/scripts/test.mjs+++ b/app/scripts/test.mjs@@ -1,5 +1,9 @@import {spawnSync} from "node:child_process";import {availableParallelism} from "node:os";+import {createRequire} from "node:module";++// 在启动并行测试前完成 Electron 安装,避免多个子进程同时解压同一运行时。+createRequire(import.meta.url)("electron");// 按可用核心数并行执行,限制上限以避免多个 Electron 子进程耗尽运行资源。const concurrency = Math.min(4, availableParallelism());diff --git a/app/scripts/test.test.js b/app/scripts/test.test.jsnew file mode 100644index 0000000000..61d8ddac04--- /dev/null+++ b/app/scripts/test.test.js@@ -0,0 +1,50 @@+const assert = require("node:assert/strict");+const {spawnSync} = require("node:child_process");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const {test} = require("node:test");++test("test runner prepares Electron before workers and stops on installation failure", t => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-test-runner-"));+ t.after(() => fs.rmSync(root, {recursive: true, force: true}));+ const write = (name, content) => {+ const target = path.join(root, name);+ fs.mkdirSync(path.dirname(target), {recursive: true});+ fs.writeFileSync(target, content);+ };+ write("scripts/test.mjs", fs.readFileSync(path.join(__dirname, "test.mjs")));+ write("node_modules/tsx/package.json", JSON.stringify({name: "tsx", main: "index.js"}));+ write("node_modules/tsx/index.js", "");+ write("node_modules/electron/index.js", `+ const fs = require("node:fs");+ if (process.env.SIYUAN_TEST_INSTALL_FAILURE === "1") {+ throw new Error("Electron installation failed");+ }+ fs.appendFileSync("installations", "prepared\\n");+ module.exports = "electron";+ `);+ // 每类测试均检查父进程已完成准备,不能依靠某个测试抢先安装。+ for (const name of ["src/worker.test.ts", "tests/worker.test.js", "electron/worker.test.js", "scripts/worker.test.js"]) {+ write(name, `+ const fs = require("node:fs");+ require("node:assert/strict").equal(fs.readFileSync("installations", "utf8"), "prepared\\n");+ fs.appendFileSync("workers", "started\\n");+ `);+ }+ const env = {...process.env};+ delete env.NODE_TEST_CONTEXT;+ const run = failure => spawnSync(process.execPath, ["scripts/test.mjs"], {+ cwd: root, encoding: "utf8", timeout: 30000,+ env: {...env, SIYUAN_TEST_INSTALL_FAILURE: failure ? "1" : "0"},+ });+ const success = run(false);+ assert.equal(success.status, 0, success.stdout + success.stderr);+ assert.equal(fs.readFileSync(path.join(root, "installations"), "utf8"), "prepared\n");+ assert.equal(fs.readFileSync(path.join(root, "workers"), "utf8").trim().split("\n").length, 4);+ fs.unlinkSync(path.join(root, "workers"));+ const failure = run(true);+ assert.notEqual(failure.status, 0);+ assert.match(failure.stderr, /Electron installation failed/);+ assert.equal(fs.existsSync(path.join(root, "workers")), false);+});diff --git a/app/src/boot/globalEvent/gutterMargin.test.ts b/app/src/boot/globalEvent/gutterMargin.test.tsindex c09c4f94f7..193c87b2ac 100644--- a/app/src/boot/globalEvent/gutterMargin.test.ts+++ b/app/src/boot/globalEvent/gutterMargin.test.ts@@ -2,9 +2,21 @@ import * as assert from "node:assert/strict";import {readFileSync} from "node:fs";import {test} from "node:test";import {runInNewContext} from "node:vm";-import {isContainerGutterBridge} from "../../protyle/gutter/container";import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+const buildGlobals = ["SIYUAN_VERSION", "NODE_ENV"].map(name => ({+ name, descriptor: Object.getOwnPropertyDescriptor(globalThis, name),+}));+buildGlobals.forEach(({name}) => Object.defineProperty(globalThis, name, {value: "test", configurable: true}));+const {isContainerGutterBridge} = require("../../protyle/gutter/container") as typeof import("../../protyle/gutter/container");+buildGlobals.forEach(({name, descriptor}) => {+ if (descriptor) {+ Object.defineProperty(globalThis, name, descriptor);+ } else {+ Reflect.deleteProperty(globalThis, name);+ }+});+const compiled = transpileModule(readFileSync(__dirname + "/mousemove.ts", "utf8"), {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},}).outputText;diff --git a/app/src/boot/globalEvent/mousemove.test.ts b/app/src/boot/globalEvent/mousemove.test.tsindex 4bc199fe17..48fb20f925 100644--- a/app/src/boot/globalEvent/mousemove.test.ts+++ b/app/src/boot/globalEvent/mousemove.test.ts@@ -3,7 +3,19 @@ import {readFileSync} from "node:fs";import {test} from "node:test";import {runInNewContext} from "node:vm";import {ModuleKind, ScriptTarget, transpileModule} from "typescript";-import {isContainerGutterBridge} from "../../protyle/gutter/container";++const buildGlobals = ["SIYUAN_VERSION", "NODE_ENV"].map(name => ({+ name, descriptor: Object.getOwnPropertyDescriptor(globalThis, name),+}));+buildGlobals.forEach(({name}) => Object.defineProperty(globalThis, name, {value: "test", configurable: true}));+const {isContainerGutterBridge} = require("../../protyle/gutter/container") as typeof import("../../protyle/gutter/container");+buildGlobals.forEach(({name, descriptor}) => {+ if (descriptor) {+ Object.defineProperty(globalThis, name, descriptor);+ } else {+ Reflect.deleteProperty(globalThis, name);+ }+});const source = transpileModule(readFileSync("src/boot/globalEvent/mousemove.ts", "utf8"), {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},diff --git a/app/tests/blockFontStyle.test.js b/app/tests/blockFontStyle.test.jsindex 45e6a1ae2c..655ff66724 100644--- a/app/tests/blockFontStyle.test.js+++ b/app/tests/blockFontStyle.test.js@@ -90,6 +90,7 @@ const runElectron = async () => {app.commandLine.appendSwitch("disable-gpu");await app.whenReady();const win = new BrowserWindow({show: false, webPreferences: {nodeIntegration: true, contextIsolation: false}});+ win.webContents.on("console-message", event => console.error(event.message));let exitCode = 0;try {const ts = require("typescript");@@ -106,10 +107,12 @@ const runElectron = async () => {const modules = {"toolbar/fontFamilyCore": read("toolbar/fontFamilyCore"),"util/hasClosest": read("util/hasClosest"),+ "render/blockDirection": read("render/blockDirection"),"toolbar/fontFamilyMenu": 'import {FONT_FAMILY_EXCLUDED_BLOCK_TYPES, getInlineFontFamilySelection, hasInlineFontFamilyExcludedType} from "./fontFamilyCore";\n' +'import {hasClosestBlock} from "../util/hasClosest"; const Constants = {ZWSP:"\\u200b"};\n' +extract("toolbar/fontFamilyMenu", ["getNodeFontFamily", "getFontFamilyState", "getInlineFontFamilyState"]),- "wysiwyg/transaction": 'const Constants = {ATTRIBUTE_EDITING:"data-editing"}; const cleanHeadingNumberHTML = html => html;\n' ++ "wysiwyg/transaction": 'import {renderBlockDirection} from "../render/blockDirection";\n' ++ 'const Constants = {ATTRIBUTE_EDITING:"data-editing"}; const cleanHeadingNumberHTML = html => html;\n' +"const transaction = (protyle, operations, undoOperations) => window.batches.push({operations, undoOperations});\n" +extract("wysiwyg/transaction", ["updateBatchTransaction"]),"toolbar/Font": 'import {updateBatchTransaction} from "../wysiwyg/transaction";\n' +diff --git a/kernel/model/publish_access_assets_fts5_test.go b/kernel/model/publish_access_assets_fts5_test.gonew file mode 100644index 0000000000..dc974bd2d7--- /dev/null+++ b/kernel/model/publish_access_assets_fts5_test.go@@ -0,0 +1,154 @@+// 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/>.++//go:build fts5++package model++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestFilterAssetContentByPublishAccess(t *testing.T) {+ for _, uncached := range []bool{false, true} {+ name := "current"+ if uncached {+ name = "uncached"+ }+ t.Run(name, func(t *testing.T) {+ t.Run("body", func(t *testing.T) { testPublishDocAssets(t, false, uncached) })+ t.Run("title image", func(t *testing.T) { testPublishDocAssets(t, true, uncached) })+ })+ }+}++func testPublishDocAssets(t *testing.T, titleImage, uncached bool) {+ const (+ boxID = "20260804030000-boxid01"+ publicDocID = "20260804030001-public1"+ protectedDocID = "20260804030002-protect"+ hiddenDocID = "20260804030003-hidden1"+ disabledDocID = "20260804030004-disable"+ publicAsset = "assets/public.png"+ protectedAsset = "assets/protected.png"+ hiddenAsset = "assets/hidden.png"+ disabledAsset = "assets/disabled.png"+ protectedPassword = "password"+ )++ setupExportPublishTest(t)++ newDocTree := func(docID, asset string) {+ tree := treenode.NewTree(boxID, "/"+docID+".sy", "/"+docID, docID)+ tree.Root.FirstChild.Unlink()+ dom := `<div data-node-id="` + ast.NewNodeID() + `" data-type="htmlblock"><img src="` + asset + `" data-src="` + asset + `" /></div>`+ node := util.NewLute().BlockDOM2Tree(dom).Root.FirstChild+ tree.Root.AppendChild(node)+ if titleImage {+ node.Unlink()+ tree.Root.SetIALAttr("title-img", `background-image: url("`+asset+`?v=1&size=large"); background-position: center;`)+ }+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ if uncached {+ // 历史属性中的换行在冷读时订正,确保覆盖订正后的索引入队路径。+ file := filepath.Join(util.DataDir, boxID, docID+".sy")+ data, err := os.ReadFile(file)+ if err != nil {+ t.Fatal(err)+ }+ var document map[string]any+ if err = json.Unmarshal(data, &document); err != nil {+ t.Fatal(err)+ }+ document["Properties"].(map[string]any)["custom-test"] = "legacy\nvalue"+ data, err = json.Marshal(document)+ if err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(file, data, 0644); err != nil {+ t.Fatal(err)+ }+ cache.RemoveTreeDataInBox(docID, boxID)+ }+ treenode.UpsertBlockTree(tree)+ }+ newDocTree(publicDocID, publicAsset)+ newDocTree(protectedDocID, protectedAsset)+ newDocTree(hiddenDocID, hiddenAsset)+ newDocTree(disabledDocID, disabledAsset)++ newAssetContents := func() []*AssetContent {+ return []*AssetContent{+ {ID: publicDocID, Name: "public.png", Path: publicAsset},+ {ID: protectedDocID, Name: "protected.png", Path: protectedAsset},+ {ID: hiddenDocID, Name: "hidden.png", Path: hiddenAsset},+ {ID: disabledDocID, Name: "disabled.png", Path: disabledAsset},+ }+ }+ publishAccess := PublishAccess{+ {ID: protectedDocID, Visible: true, Password: protectedPassword},+ {ID: hiddenDocID, Visible: false},+ {ID: disabledDocID, Visible: true, Disable: true},+ }++ c, _ := gin.CreateTestContext(httptest.NewRecorder())+ c.Request = httptest.NewRequest(http.MethodGet, "/", nil)+ if titleImage {+ assets, err := DocAssets(publicDocID, true)+ if err != nil || len(assets) != 1 || assets[0] != publicAsset+"?v=1&size=large" {+ t.Fatalf("unexpected title image assets with query: %v, %v", assets, err)+ }+ }+ for _, asset := range []string{publicAsset, protectedAsset, disabledAsset, "assets/unreferenced.png"} {+ got := CheckAbsPathAccessableByPublishAccess(c, filepath.Join(util.DataDir, asset), publishAccess)+ if got != (asset == publicAsset) {+ t.Errorf("unexpected unauthenticated access to %s: %v", asset, got)+ }+ }+ filtered := FilterAssetContentByPublishAccess(c, publishAccess, newAssetContents())+ if len(filtered) != 1 || filtered[0].Path != publicAsset {+ t.Fatalf("unexpected unauthenticated asset contents: %+v", filtered)+ }++ c.Request.AddCookie(&http.Cookie{+ Name: "publish-auth-" + protectedDocID,+ Value: util.SHA256Hash([]byte(protectedDocID + protectedPassword)),+ })+ filtered = FilterAssetContentByPublishAccess(c, publishAccess, newAssetContents())+ if !CheckAbsPathAccessableByPublishAccess(c, filepath.Join(util.DataDir, protectedAsset), publishAccess) {+ t.Error("password protected asset should be accessible after authorization")+ }+ if len(filtered) != 2 || filtered[0].Path != publicAsset || filtered[1].Path != protectedAsset {+ t.Fatalf("unexpected authenticated asset contents: %+v", filtered)+ }+ if uncached && Conf.DataIndexState != 1 {+ t.Fatal("uncached document did not enqueue its repaired index")+ }+}diff --git a/kernel/model/publish_access_test.go b/kernel/model/publish_access_test.goindex d3f5ec6d44..3107008799 100644--- a/kernel/model/publish_access_test.go+++ b/kernel/model/publish_access_test.go@@ -30,7 +30,6 @@ import ("github.com/gin-gonic/gin""github.com/siyuan-note/siyuan/kernel/av""github.com/siyuan-note/siyuan/kernel/conf"- "github.com/siyuan-note/siyuan/kernel/filesys""github.com/siyuan-note/siyuan/kernel/sql""github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util"@@ -1743,107 +1742,6 @@ func TestFilterCriteriaByPublishAccess(t *testing.T) {}}-func TestFilterAssetContentByPublishAccess(t *testing.T) {- t.Run("body", func(t *testing.T) { testPublishDocAssets(t, false) })- t.Run("title image", func(t *testing.T) { testPublishDocAssets(t, true) })-}--func testPublishDocAssets(t *testing.T, titleImage bool) {- const (- boxID = "20260804030000-boxid01"- publicDocID = "20260804030001-public1"- protectedDocID = "20260804030002-protect"- hiddenDocID = "20260804030003-hidden1"- disabledDocID = "20260804030004-disable"- publicAsset = "assets/public.png"- protectedAsset = "assets/protected.png"- hiddenAsset = "assets/hidden.png"- disabledAsset = "assets/disabled.png"- protectedPassword = "password"- )-- oldDataDir := util.DataDir- oldBlockTreeDBPath := util.BlockTreeDBPath- util.DataDir = t.TempDir()- util.BlockTreeDBPath = filepath.Join(util.DataDir, "blocktree.db")- treenode.InitBlockTree(true)- invalidateEncryptedPublishAccessCache()- t.Cleanup(func() {- treenode.CloseDatabase()- util.DataDir = oldDataDir- util.BlockTreeDBPath = oldBlockTreeDBPath- invalidateEncryptedPublishAccessCache()- if "" != oldBlockTreeDBPath {- treenode.InitBlockTree(false)- }- })-- newDocTree := func(docID, asset string) {- tree := treenode.NewTree(boxID, "/"+docID+".sy", "/"+docID, docID)- tree.Root.FirstChild.Unlink()- dom := `<div data-node-id="` + docID + `" data-type="htmlblock"><img src="` + asset + `" data-src="` + asset + `" /></div>`- node := util.NewLute().BlockDOM2Tree(dom).Root.FirstChild- tree.Root.AppendChild(node)- if titleImage {- node.Unlink()- tree.Root.SetIALAttr("title-img", `background-image: url("`+asset+`?v=1&size=large"); background-position: center;`)- }- if _, err := filesys.WriteTree(tree); err != nil {- t.Fatal(err)- }- treenode.UpsertBlockTree(tree)- }- newDocTree(publicDocID, publicAsset)- newDocTree(protectedDocID, protectedAsset)- newDocTree(hiddenDocID, hiddenAsset)- newDocTree(disabledDocID, disabledAsset)-- newAssetContents := func() []*AssetContent {- return []*AssetContent{- {ID: publicDocID, Name: "public.png", Path: publicAsset},- {ID: protectedDocID, Name: "protected.png", Path: protectedAsset},- {ID: hiddenDocID, Name: "hidden.png", Path: hiddenAsset},- {ID: disabledDocID, Name: "disabled.png", Path: disabledAsset},- }- }- publishAccess := PublishAccess{- {ID: protectedDocID, Visible: true, Password: protectedPassword},- {ID: hiddenDocID, Visible: false},- {ID: disabledDocID, Visible: true, Disable: true},- }-- c, _ := gin.CreateTestContext(httptest.NewRecorder())- c.Request = httptest.NewRequest(http.MethodGet, "/", nil)- if titleImage {- assets, err := DocAssets(publicDocID, true)- if err != nil || len(assets) != 1 || assets[0] != publicAsset+"?v=1&size=large" {- t.Fatalf("unexpected title image assets with query: %v, %v", assets, err)- }- }- for _, asset := range []string{publicAsset, protectedAsset, disabledAsset, "assets/unreferenced.png"} {- got := CheckAbsPathAccessableByPublishAccess(c, filepath.Join(util.DataDir, asset), publishAccess)- if got != (asset == publicAsset) {- t.Errorf("unexpected unauthenticated access to %s: %v", asset, got)- }- }- filtered := FilterAssetContentByPublishAccess(c, publishAccess, newAssetContents())- if len(filtered) != 1 || filtered[0].Path != publicAsset {- t.Fatalf("unexpected unauthenticated asset contents: %+v", filtered)- }-- c.Request.AddCookie(&http.Cookie{- Name: "publish-auth-" + protectedDocID,- Value: util.SHA256Hash([]byte(protectedDocID + protectedPassword)),- })- filtered = FilterAssetContentByPublishAccess(c, publishAccess, newAssetContents())- if !CheckAbsPathAccessableByPublishAccess(c, filepath.Join(util.DataDir, protectedAsset), publishAccess) {- t.Error("password protected asset should be accessible after authorization")- }- if len(filtered) != 2 || filtered[0].Path != publicAsset || filtered[1].Path != protectedAsset {- t.Fatalf("unexpected authenticated asset contents: %+v", filtered)- }-}-// TestCheckAbsPathAccessableByPublishAccessKeepsHiddenNotebookAccessible 验证原始文件通道// 保持「仅隐藏」语义:显式隐藏(Visible:false)的笔记本不构成机密边界,// 普通文件与 .sy 文档仍可直接访问,禁用与密码保护照常生效。