Skip to content

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

:white_check_mark: Repair alpha test harnesses and export readiness

Liang Ding98c36b23b05d
diff --git a/app/src/mobile/util/keyboardReference.test.ts b/app/src/mobile/util/keyboardReference.test.ts
index e0b8ec1c63..9f13fbfb9c 100644
--- a/app/src/mobile/util/keyboardReference.test.ts
+++ b/app/src/mobile/util/keyboardReference.test.ts
@@ -40,6 +40,7 @@ test("mobile reference remains available at a caret without exposing other selec
stripSemanticMarkersFromRangeText: () => hasText ? "selected" : "",
Constants: {ZWSP: "\u200b"}, getEntryOrder: (): string[] => [], isEntryVisible: () => false,
TOOLBAR_ENTRY_ROOT_PATH: "editor.toolbar", MOBILE_TOOLBAR_NAMES: ["block-ref", "strong"],
+ MOBILE_TOOLBAR_ACTION_NAMES: [],
applyMobileToolbarEntries: (_element: unknown, _toolbar: unknown, options: {
isAvailable: (name: string) => boolean, isVisible: (key: string) => boolean,
}) => {
diff --git a/app/src/protyle/export/imageLayout.test.ts b/app/src/protyle/export/imageLayout.test.ts
index 80951acef1..ab850348ca 100644
--- a/app/src/protyle/export/imageLayout.test.ts
+++ b/app/src/protyle/export/imageLayout.test.ts
@@ -108,15 +108,20 @@ const browserCases = async (layoutSource: string, exportSource: string, mobile:
};
const exported: {exportImage: (id: string, copyOnly?: boolean) => void} = new Function("exports", "require",
`${exportSource}; return exports;`)({}, (name: string) => dependencies[name] || {});
- const waitForActions = async () => {
- for (let i = 0; i < 500; i++) {
+ const waitForActions = async (phase: string, timeout = 5000) => {
+ const started = Date.now();
+ while (Date.now() - started < timeout) {
if (!document.body.contains(dialog.element) ||
!(dialog.element.querySelector('[data-type="copy"]') as HTMLButtonElement).disabled) {
return;
}
await new Promise(resolve => setTimeout(resolve, 10));
}
- check.fail("Export actions did not become available");
+ check.fail("Export actions did not become available: " + JSON.stringify({
+ phase, elapsedMs: Date.now() - started, engine, mobile,
+ visibility: document.visibilityState, messages, captured: !!captured,
+ table: dialog.element.querySelector("table")?.getBoundingClientRect().toJSON(),
+ }));
};
const table = (columns: number, wide = true) => `<div class="table" data-node-id="table"><div><table><tbody><tr>${
Array.from({length: columns}, (_, index) => `<td${wide ? ' style="min-width:400px"' : ""}>column ${index}
@@ -128,7 +133,7 @@ ${index === columns - 1 ? '<span class="marker" style="display:block;width:20px;
captured = undefined;
messages.length = 0;
exported.exportImage("root", copyOnly);
- await waitForActions();
+ await waitForActions(copyOnly ? "automatic copy" : "preview", copyOnly ? 15000 : 5000);
return dialog.element.querySelector<HTMLElement>(".b3-dialog__content");
};
const verifyCaptured = async () => {
@@ -153,7 +158,7 @@ ${index === columns - 1 ? '<span class="marker" style="display:block;width:20px;
};
const capture = async (type = "copy") => {
(dialog.element.querySelector(`[data-type="${type}"]`) as HTMLButtonElement).click();
- await waitForActions();
+ await waitForActions(type, 15000);
await verifyCaptured();
};
for (const renderer of ["html", "modern"]) {
@@ -172,9 +177,17 @@ ${index === columns - 1 ? '<span class="marker" style="display:block;width:20px;
check.ok(wide.querySelector("table").getBoundingClientRect().right <= imageElement.getBoundingClientRect().right,
"Image must cover the whole table");
wide.querySelector<HTMLElement>("table").style.width = "2200px";
- await new Promise(resolve => setTimeout(resolve, 100));
+ const deadline = Date.now() + 5000;
+ while (wide.querySelector("table").getBoundingClientRect().right > imageElement.getBoundingClientRect().right &&
+ Date.now() < deadline) {
+ await new Promise(resolve => setTimeout(resolve, 25));
+ }
check.ok(wide.querySelector("table").getBoundingClientRect().right <= imageElement.getBoundingClientRect().right,
- "Preview border must follow table width changes without resizing the dialog");
+ "Preview border must follow table width changes without resizing the dialog: " + JSON.stringify({
+ renderer, mobile, visibility: document.visibilityState, minWidth: imageElement.style.minWidth,
+ table: wide.querySelector("table").getBoundingClientRect().toJSON(),
+ image: imageElement.getBoundingClientRect().toJSON(),
+ }));
wide.scrollLeft = wide.scrollWidth - wide.clientWidth;
const oldScroll = wide.scrollLeft;
await capture();
@@ -218,7 +231,7 @@ ${index === columns - 1 ? '<span class="marker" style="display:block;width:20px;
large.querySelector<HTMLElement>("table").style.width = "20000px";
dialog.resize();
(dialog.element.querySelector('[data-type="copy"]') as HTMLButtonElement).click();
- await waitForActions();
+ await waitForActions("oversized image");
check.equal(captured, undefined);
check.ok(messages.includes("Image too large"), "Oversized image must show a size error");
check.equal(large.style.overflow, "");
@@ -250,7 +263,7 @@ ${index === columns - 1 ? '<span class="marker" style="display:block;width:20px;
test("wide PNG exports preserve text and all columns in both screenshot engines and viewport sizes", {
skip: process.platform === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY,
- timeout: 60000,
+ timeout: 95000,
}, async () => {
const sass = require("sass");
const css = sass.compileString('@use "component/dialog"; @use "protyle/wysiwyg"; ' +
@@ -280,7 +293,7 @@ app.whenReady().then(async () => {
for (const mobile of [false, true]) {
phase = "load viewport " + mobile;
win = new BrowserWindow({show:false,width:mobile ? 390 : 1000,height:850,
- webPreferences:{nodeIntegration:true,contextIsolation:false}});
+ webPreferences:{nodeIntegration:true,contextIsolation:false,backgroundThrottling:false}});
await win.loadURL("data:text/html,<html><head></head><body></body></html>");
await win.webContents.executeJavaScript(${JSON.stringify(`const style = document.createElement("style");
style.textContent = ${JSON.stringify(css)}; document.head.append(style);
@@ -304,10 +317,10 @@ ${libraries.map(source => `new Function("module", "exports", ${JSON.stringify(so
delete env.ELECTRON_RUN_AS_NODE;
try {
const result = await promisify(execFile)(require("electron") as unknown as string, [script], {
- env, timeout: 55000, windowsHide: true,
+ env, timeout: 90000, windowsHide: true,
});
- assert.match(result.stdout, /Image exports passed \(mobile=false\)/);
- assert.match(result.stdout, /Image exports passed \(mobile=true\)/);
+ assert.match(result.stdout, /Image exports passed \(mobile=false\)/, result.stderr);
+ assert.match(result.stdout, /Image exports passed \(mobile=true\)/, result.stderr);
} finally {
rmSync(temporary, {recursive: true, force: true});
}
diff --git a/app/src/protyle/util/paste.test.ts b/app/src/protyle/util/paste.test.ts
index 0095bc8f3d..9e374fd8a8 100644
--- a/app/src/protyle/util/paste.test.ts
+++ b/app/src/protyle/util/paste.test.ts
@@ -5,6 +5,7 @@ import {join} from "node:path";
import {runInNewContext} from "node:vm";
import * as ts from "typescript";
import {getAVRichTextSafeURL} from "../render/av/richTextValue";
+import {normalizePictureImages} from "./pictureImages";
// 执行粘贴入口,替换剪贴板和上传接口,检查图片不会在受限片段中被丢弃。
const source = ts.transpileModule(readFileSync(join(process.cwd(), "src/protyle/util/paste.ts"), "utf8"), {
@@ -21,6 +22,7 @@ const createHarness = (disabled = false, richPaste = false) => {
let checkedBlockDOM = "";
const restrictedFallback = new Error("restricted fallback");
const mocks: Record<string, unknown> = {
+ "./pictureImages": {normalizePictureImages},
"../../constants": {Constants: {SIYUAN_ASSETS_IMAGE: [".png", ".jpg"]}},
"../runtimeCapabilities": {
getProtyleBlockDOMSanitizer: () => (html: string) => html,
@@ -193,6 +195,7 @@ describe("restricted cell selected text paste", () => {
isUploadInsertPositionAvailable: () => true,
},
"./selection": {getEditorRange: () => range},
+ "./pictureImages": {normalizePictureImages},
"./tableCellRichContext": {getTableCellRichContext: () => options.tableCell ? {} : undefined},
"./hasClosest": {hasClosestBlock: () => block},
"./compatibility": {isInHarmony: () => false},
@@ -212,7 +215,9 @@ describe("restricted cell selected text paste", () => {
};
const module = {exports: {}};
runInNewContext(source, {module, exports: module.exports, require: (id: string) => mocks[id] || {},
- DOMParser: class {parseFromString() {return {querySelector: (): null => null, body: {innerHTML: ""}};}},
+ DOMParser: class {parseFromString() {
+ return {querySelector: (): null => null, querySelectorAll: (): Element[] => [], body: {innerHTML: ""}};
+ }},
Lute: {Sanitize: (value: string) => value},
window: {siyuan: {languages: {cellPasteUnsupported: "Unsupported: ${x}"}}},
});
diff --git a/app/src/protyle/util/tableCellRichLute.test.ts b/app/src/protyle/util/tableCellRichLute.test.ts
index 1641b6c4bf..c4fe683dfd 100644
--- a/app/src/protyle/util/tableCellRichLute.test.ts
+++ b/app/src/protyle/util/tableCellRichLute.test.ts
@@ -14,12 +14,13 @@ const browserCases = async (source: string, enterSource: string, hintSource: str
const api = new Function("Constants", source + "\nreturn {getAgentLute, configureAVRichTextLute, getTableCellEditorLute, " +
"canEnterCodeBlock, hasCodeBlockFence, getTableCellInlineHTML, serializeTableCellRich, " +
"updateTableCellEditingValue, getTableCellRichBlockDOM, sanitizeAVRichTextBlockDOM, restoreTableVirtualizationDOM, " +
- "copyTableCellContent, renderTableCellRich};")({
+ "copyTableCellContent, renderTableCellRich, prepareInlineElementBoundaryMutation};")({
CUSTOM_SY_CODE_TAB_SPACES: codeTabAttribute,
}) as
typeof import("../render/setLute") & typeof import("../render/av/richTextValue") &
typeof import("./tableCellRichLute") & typeof import("../wysiwyg/codeBlockEnter") &
- typeof import("./tableCellRich") & typeof import("../render/av/richText") & typeof import("./tableVirtualizationDOM");
+ typeof import("./tableCellRich") & typeof import("../render/av/richText") & typeof import("./tableVirtualizationDOM") &
+ typeof import("./inlineElementBoundary");
const base = api.configureAVRichTextLute(api.getAgentLute({emojiSite: "/emojis", emojis: {},
headingAnchor: false, listStyle: false, paragraphBeginningSpace: true, sanitize: true}));
const lute = api.getTableCellEditorLute(base);
diff --git a/app/tests/markdownClipboard.test.js b/app/tests/markdownClipboard.test.js
index 3585ef8728..feb8160831 100644
--- a/app/tests/markdownClipboard.test.js
+++ b/app/tests/markdownClipboard.test.js
@@ -11,6 +11,7 @@ const sources = () => {
return {
clipboard: compile("protyle/util/markdownClipboard.ts"),
paste: compile("protyle/util/paste.ts"),
+ pictureImages: compile("protyle/util/pictureImages.ts"),
localAssets: compile("protyle/upload/htmlLocalAssets.ts"),
uploadResult: compile("protyle/upload/uploadResult.ts"),
fixture: JSON.parse(readFileSync(path.join(__dirname, "fixtures/doubao-clipboard.json"), "utf8")),
@@ -109,6 +110,7 @@ const runCases = async source => {
const mocks = {
"../../constants": {Constants: {ZWSP: "\u200b"}},
"./markdownClipboard": clipboard,
+ "./pictureImages": load(source.pictureImages),
"../runtimeCapabilities": {
getProtyleBlockDOMSanitizer: () => restricted ? value => value : undefined,
isProtyleRichHTMLPasteEnabled: () => restricted,
diff --git a/app/tests/tabsFocus.test.js b/app/tests/tabsFocus.test.js
index f8dbae325b..445c94b61e 100644
--- a/app/tests/tabsFocus.test.js
+++ b/app/tests/tabsFocus.test.js
@@ -22,6 +22,7 @@ const sources = () => {
compile("protyle/render/tabsVisibility.ts", ["isHiddenTabContent"]),
compile("protyle/render/tabsRender.ts"),
compile("protyle/wysiwyg/tabsFocus.ts"),
+ compile("protyle/wysiwyg/tabsReading.ts"),
compile("protyle/wysiwyg/tabsRemoval.ts", ["repairActiveTab"]),
compile("protyle/util/tabsCopy.ts", ["preserveTabTask"]),
compile("protyle/wysiwyg/transactionUpdate.ts"),
diff --git a/app/tests/taskStatus.test.js b/app/tests/taskStatus.test.js
index 9c6e6e5994..c9eada9903 100644
--- a/app/tests/taskStatus.test.js
+++ b/app/tests/taskStatus.test.js
@@ -64,7 +64,8 @@ const sources = () => {
extract("protyle/render/tabsState.ts", ["resolveTabID", "tabKeyboardTarget"]) +
extract("protyle/render/tabsAttributes.ts", ["clearTabsAttributes", "renderTabsAttributes"]),
menu: extract("protyle/wysiwyg/taskStatusDialog.ts", ["getTaskStatusItems"]),
- tabMenu: extract("protyle/wysiwyg/tabs.ts", ["canEdit", "openTabsMenu"]),
+ tabMenu: extract("protyle/wysiwyg/tabsFocus.ts", ["canFocusTabItem"]) +
+ extract("protyle/wysiwyg/tabs.ts", ["canEdit", "openTabsMenu"]),
normalizeSeparators: extract("config/entryVisibility/runtime.ts", ["normalizeSeparators"]),
css: require("sass").compile(path.join(__dirname, "../src/assets/scss/protyle/_wysiwyg.scss")).css +
require("sass").compile(path.join(__dirname, "../src/assets/scss/component/_typography.scss")).css,
@@ -108,7 +109,7 @@ const cases = async source => {
const root = document.createElement("div");
root.className = "protyle-wysiwyg";
document.body.append(root);
- const protyle = {lute, disabled: false, options: {action: []}, block: {rootID: "doc"}, wysiwyg: {element: root}};
+ const protyle = {lute, element: root, disabled: false, options: {action: []}, block: {rootID: "doc"}, wysiwyg: {element: root}};
const taskStyle = document.createElement("style");
taskStyle.textContent = source.css;
document.head.append(taskStyle);
@@ -145,9 +146,11 @@ const cases = async source => {
addSeparator(item) { this.items.push({...item, type: "separator"}); }
open() {}
}
- const openTabMenu = new Function("Menu", "Constants", "getTabTask", "getTaskStatusItems", "setTabTask", "copySubMenu",
+ let focusedTab;
+ const openTabMenu = new Function("Menu", "Constants", "getTabTask", "getTaskStatusItems", "setTabTask", "copySubMenu", "zoomOut",
source.tabMenu + "; return openTabsMenu;")(
- TestMenu, {CB_GET_HISTORY: "history"}, api.getTabTask, getMenu, api.setTabTask, () => []);
+ TestMenu, {CB_GET_HISTORY: "history"}, api.getTabTask, getMenu, api.setTabTask, () => [],
+ options => { focusedTab = options; });
const menuFixture = reset();
openTabMenu(protyle, menuFixture.from, menuFixture.item, menuFixture.item);
const expectedStates = ["taskStatusTodo", "taskStatusInProgress", "taskStatusDone", "taskStatusCanceled", "customTaskStatus"];
@@ -187,7 +190,10 @@ const cases = async source => {
check.equal(api.getTabTask(menuFixture.item), "/");
protyle.disabled = true;
openTabMenu(protyle, menuFixture.from, menuFixture.item, menuFixture.item);
- check.deepEqual(openedMenu.items.map(item => item.icon), ["iconCopy"]);
+ check.deepEqual(openedMenu.items.map(item => item.icon), ["iconCopy", "iconEnter"]);
+ openedMenu.items.find(item => item.icon === "iconEnter").click();
+ check.equal(focusedTab.protyle, protyle);
+ check.equal(focusedTab.id, menuFixture.item.dataset.nodeId);
protyle.disabled = false;
const apply = operations => operations.forEach(operation => {
const item = find(operation.id);
diff --git a/kernel/model/file_annotation_test.go b/kernel/model/file_annotation_test.go
index 89de99f4b6..0a68261803 100644
--- a/kernel/model/file_annotation_test.go
+++ b/kernel/model/file_annotation_test.go
@@ -163,7 +163,7 @@ func TestFileAnnotationExportRejectsInvalidData(t *testing.T) {
util.WorkspaceDir = t.TempDir()
util.DataDir = filepath.Join(util.WorkspaceDir, "data")
t.Cleanup(func() { util.WorkspaceDir, util.DataDir = oldWorkspace, oldDataDir })
- for _, data := range []string{"invalid", "{}", `{"` + testFileAnnotationID + `":{"pages":[]}}`,
+ for _, data := range []string{"invalid", `{"` + testFileAnnotationID + `":{}}`, `{"` + testFileAnnotationID + `":{"pages":[]}}`,
`{"` + testFileAnnotationID + `":{"pages":[{"index":-1}]}}`} {
writeFileAnnotationTestAsset(t, filepath.Join(util.DataDir, "assets/a.pdf"), []byte(data))
node := newFileAnnotationTestNode("assets/a.pdf/" + testFileAnnotationID)