Skip to content

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

:bug: Preserve OCR import error feedback and settings borders https://github.com/siyuan-note/siyuan/pull/20506

Daniel9d79dc8a6920
diff --git a/app/src/config/ocr.test.ts b/app/src/config/ocr.test.ts
index 0307d3bdda..893e718cb6 100644
--- a/app/src/config/ocr.test.ts
+++ b/app/src/config/ocr.test.ts
@@ -5,6 +5,8 @@ import {runInNewContext} from "node:vm";
import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
import type {OCRThresholds, SettingOCR} from "../types/api";
import {getReasoningEffortOptions} from "../ai/reasoningEffort";
+import type {SettingBuilder} from "./setting/builder";
+import type {applySettingTabSearchVisibility, clearSettingTabSearch} from "./setting/mount";
const generalRowNames = ["ocrAuto", "ocrProvider", "ocrModel", "ocrImport", "ocrAIModel", "ocrReasoningEffort"];
const advancedRowNames = ["ocrThreshold_detection", "ocrThreshold_box", "ocrThreshold_recognition"];
@@ -60,6 +62,7 @@ test("OCR settings register separate searchable rows in shared desktop and mobil
assert.doesNotMatch(readFileSync("src/config/ocr.ts", "utf8"), /openOCRThresholds/);
const tabs = readFileSync("src/config/setting/tabs.ts", "utf8");
assert.match(tabs, /ocr: setting\.tab\([\s\S]*?afterMount: mountOCRTab,[\s\S]*?registerOCRTab/);
+ assert.match(tabs, /ocr: setting\.tab\([\s\S]*?onShow: updateOCRTabBorders,[\s\S]*?registerOCRTab/);
assert.match(tabs, /ocr: setting\.tab\([\s\S]*?icon: "iconOCR"/);
assert.match(readFileSync("appearance/icons/litheness/icon.js", "utf8"), /<symbol id="iconOCR"/);
assert.match(readFileSync("appearance/icons/index.html", "utf8"), /xlink:href="#iconOCR"/);
@@ -92,7 +95,7 @@ const createOCRPanel = async (initial?: {config?: SettingOCR}) => {
return on;
},
add(name: string) { classes.add(name); },
- remove(name: string) { classes.delete(name); },
+ remove(...names: string[]) { names.forEach(name => classes.delete(name)); },
contains(name: string) { return classes.has(name); },
};
};
@@ -103,22 +106,30 @@ const createOCRPanel = async (initial?: {config?: SettingOCR}) => {
setCustomValidity(message: string) { this.validationMessage = message; },
reportValidity() { return !this.validationMessage; },
classList: createClassList(),
+ getAttribute: () => `ocr.__slot.${id === "ocrImport" ? "button_ocrImport" : id}`,
// 控件自身即配置项,与真实 DOM 中 closest(".config-item") 返回同一元素一致
closest() { return this as unknown as {classList: ReturnType<typeof createClassList>}; },
}]));
- const groupElement = (ids: string[]) => ({
+ const groupElement = (id: string, ids: string[]) => ({
classList: createClassList(),
+ getAttribute: () => id,
querySelectorAll: () => ids.map(id => controls[id]),
});
const groups: Record<string, ReturnType<typeof groupElement>> = {
- general: groupElement(generalIds), advanced: groupElement(advancedIds),
+ general: groupElement("general", generalIds), advanced: groupElement("advanced", advancedIds),
};
const listeners = new Map<string, (event: unknown) => Promise<void>>();
let renders = 0;
const root = {
+ get innerHTML() { return "controls"; },
set innerHTML(_value: string) { renders++; },
querySelector: (selector: string) => groups[/data-config-group-id="(\w+)"/.exec(selector)?.[1] ?? ""] ?? controls[selector.slice(1)],
- querySelectorAll: (selector: string) => selector === "[data-config-group-id]" ? Object.values(groups) : Object.values(controls),
+ querySelectorAll: (selector: string) => {
+ if (selector === "[data-config-search-unavailable-id]") return [];
+ if (selector === "[data-config-group-id]") return Object.values(groups);
+ if (selector === "[data-config-group-id], [data-config-item-id]") return [...Object.values(groups), ...Object.values(controls)];
+ return Object.values(controls);
+ },
addEventListener: (name: string, callback: (event: unknown) => Promise<void>) => listeners.set(name, callback),
};
const requests: Array<{
@@ -129,7 +140,10 @@ const createOCRPanel = async (initial?: {config?: SettingOCR}) => {
const errors: string[] = [];
const notifications = new Map<string, () => void>();
const dialogs: Array<{options: {onImported: () => void, onClosed?: () => void}, destroy: () => void}> = [];
- const exports = {} as {mountOCRSettings: (element: unknown) => () => void};
+ const exports = {} as {
+ mountOCRSettings: (element: unknown) => () => void;
+ updateOCRTabBorders: (element: HTMLElement) => void;
+ };
runInNewContext(compiled, {exports, AbortController, window: {siyuan: {config, languages: {ocrThresholdRange: "invalid threshold"}},
addEventListener: (name: string, callback: () => void, options: {signal: AbortSignal}) => {
notifications.set(name, callback);
@@ -172,6 +186,20 @@ const createOCRPanel = async (initial?: {config?: SettingOCR}) => {
})});
const close = exports.mountOCRSettings(root);
await new Promise(setImmediate);
+ const searchRuntime = {} as {
+ applySettingTabSearchVisibility: typeof applySettingTabSearchVisibility;
+ clearSettingTabSearch: typeof clearSettingTabSearch;
+ };
+ runInNewContext(transpileModule(readFileSync("src/config/setting/mount.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText, {exports: searchRuntime, require: () => ({})});
+ const builderRuntime = {} as {SettingBuilder: typeof SettingBuilder};
+ runInNewContext(transpileModule(readFileSync("src/config/setting/builder.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText, {exports: builderRuntime, require: (name: string) => name === "./mount" ? searchRuntime : {}});
+ const tab = new builderRuntime.SettingBuilder().tab({
+ id: "ocr", icon: "iconOCR", title: () => "OCR", onShow: exports.updateOCRTabBorders,
+ }, () => {});
const inputThreshold = (key: keyof OCRThresholds, value: string, badInput = false) => {
const control = controls[`ocrThreshold_${key}`];
control.value = value;
@@ -180,6 +208,13 @@ const createOCRPanel = async (initial?: {config?: SettingOCR}) => {
};
return {
controls, config, requests, errors, close, renders: () => renders, dialogs, groups,
+ search: (ids: string[]) => tab.mount(root as unknown as HTMLElement, {
+ visibleItemIds: new Set(ids.map(id => controls[id].getAttribute())), visibleGroupIds: new Set(["general"]),
+ }),
+ clearSearch: () => {
+ searchRuntime.clearSettingTabSearch(root as unknown as HTMLElement);
+ return tab.mount(root as unknown as HTMLElement);
+ },
clickImport: () => listeners.get("click")({target: {closest: () => controls.ocrImport}, stopPropagation() {}}),
inputThreshold,
changeThreshold: (key: keyof OCRThresholds, value: string, badInput = false) => {
@@ -341,6 +376,26 @@ test("hidden trailing rows keep the last visible OCR row borderless for every pr
panel.close();
});
+for (const [provider, last] of [["paddleocr", "ocrImport"], ["ai", "ocrReasoningEffort"], ["tesseract", "ocrProvider"]]) {
+ test(`search changes and clearing after a save restore the last visible row for ${provider}`, async () => {
+ const panel = await createOCRPanel({config: {provider, model: "tiny", auto: false}});
+ const borderless = () => generalRowNames.filter(id => panel.controls[id].classList.contains("b3-label--noborder"));
+ await panel.search(["ocrAuto", "ocrProvider"]);
+ assert.deepEqual(borderless(), ["ocrProvider"]);
+ await panel.search(["ocrAuto"]);
+ assert.deepEqual(borderless(), ["ocrAuto"]);
+ const saving = panel.changeAuto(true);
+ await new Promise(setImmediate);
+ panel.requests[0].resolve({code: 0, data: panel.requests[0].config});
+ await saving;
+ await panel.clearSearch();
+ assert.deepEqual(borderless(), [last]);
+ assert.equal(panel.controls.ocrAuto.checked, true);
+ assert.equal(panel.renders(), 0);
+ panel.close();
+ });
+}
+
test("OCR switches save in order without replacing the panel or disabling ordinary controls", async () => {
const panel = await createOCRPanel();
const renders = panel.renders();
diff --git a/app/src/config/ocr.ts b/app/src/config/ocr.ts
index 09a52b3e19..570312c8f0 100644
--- a/app/src/config/ocr.ts
+++ b/app/src/config/ocr.ts
@@ -25,6 +25,16 @@ export const mountOCRTab = (root: HTMLElement) => {
mounts.set(root, mountOCRSettings(root));
};
+/** 按提供商和搜索状态标记每组最后一个可见条目 */
+export const updateOCRTabBorders = (root: HTMLElement) => {
+ root.querySelectorAll<HTMLElement>("[data-config-group-id]").forEach(group => {
+ const items = Array.from(group.querySelectorAll<HTMLElement>(".config-item"));
+ items.forEach(item => item.classList.remove("b3-label--noborder"));
+ items.filter(item => !item.classList.contains("fn__none") && !item.classList.contains("config-search-hidden"))
+ .at(-1)?.classList.add("b3-label--noborder");
+ });
+};
+
const selectRow = (id: string, title: string, desc: string) =>
`<label class="fn__flex b3-label config-item">${genConfigItemMainHtml(title, desc)}
<span class="fn__space"></span><select id="${id}" class="b3-select fn__flex-center fn__size200" disabled></select></label>`;
@@ -126,13 +136,7 @@ export const mountOCRSettings = (root: HTMLElement): (() => void) => {
root.querySelector<HTMLInputElement>(`#ocrThreshold_${field.key}`).disabled = busy || !isPaddleOCR;
});
root.querySelector<HTMLButtonElement>("#ocrImport").disabled = busy || pendingSaves > 0 || !isPaddleOCR;
- // 隐藏的条目仍占末尾子节点,`b3-label:last-child` 选不中,最后一行的下边框需要显式去掉
- root.querySelectorAll<HTMLElement>("[data-config-group-id]").forEach(group => {
- const items = Array.from(group.querySelectorAll<HTMLElement>(".config-item"));
- items.forEach(item => item.classList.remove("b3-label--noborder"));
- items.filter(item => !item.classList.contains("fn__none") && !item.classList.contains("config-search-hidden"))
- .at(-1)?.classList.add("b3-label--noborder");
- });
+ updateOCRTabBorders(root);
};
const providerOptions = () => {
const providers = [...data.providers].sort((left, right) => Number(right.id === "paddleocr") - Number(left.id === "paddleocr"));
diff --git a/app/src/config/ocrImport.test.ts b/app/src/config/ocrImport.test.ts
index b3040fad6b..7f0c36cf0c 100644
--- a/app/src/config/ocrImport.test.ts
+++ b/app/src/config/ocrImport.test.ts
@@ -33,7 +33,7 @@ const createImportDialog = () => {
addEventListener: (name: string, callback: (event: unknown) => unknown) => listeners.set(name, callback),
};
const requests: Array<{url: string, process: boolean, body: Record<string, unknown>,
- resolve: (response: {code: number, msg?: string}) => void}> = [];
+ resolve: (response: {code: number, msg?: string}) => void, reject: (error: Error) => void}> = [];
const messages: string[] = [];
let options: {title?: string, content: string, width?: string, destroyCallback?: () => void};
let destroyed = 0;
@@ -53,8 +53,8 @@ const createImportDialog = () => {
},
showMessage: (message: string) => messages.push(message),
fetchSyncPost: (url: string, data: {apiRequest: Record<string, unknown>}, _headers: unknown, process: boolean) =>
- new Promise<{code: number, msg?: string}>(resolve =>
- requests.push({url, process, body: data.apiRequest, resolve})),
+ new Promise<{code: number, msg?: string}>((resolve, reject) =>
+ requests.push({url, process, body: data.apiRequest, resolve, reject})),
Dialog: class {
public element = element;
constructor(value: typeof options) { options = value; }
@@ -62,13 +62,14 @@ const createImportDialog = () => {
},
}),
});
+ const controller = new AbortController();
const dialog = exports.openOCRImportModelsDialog({
- signal: new AbortController().signal,
+ signal: controller.signal,
onImported: () => opened.push(1),
onClosed: () => { closed++; },
}) as {destroy: () => void};
return {
- options, controls, requests, messages, element, dialog,
+ options, controls, requests, messages, element, dialog, controller,
destroyed: () => destroyed, imported: () => opened.length, closed: () => closed,
choose: (id: string) => {
listeners.get("click")({target: {closest: () => ({dataset: {ocrFile: id}})}});
@@ -146,3 +147,54 @@ test("cancel closes the dialog without importing", () => {
assert.equal(panel.requests.length, 0);
assert.equal(panel.imported(), 0);
});
+
+for (const error of [new TypeError("Failed to fetch"), new SyntaxError("Unexpected end of JSON input")]) {
+ test(`a rejected import reports ${error.name}, preserves file choices and allows retrying`, async () => {
+ const panel = createImportDialog();
+ fileIds.forEach(id => panel.select(id, `${id}.bin`));
+ const choices = fileIds.map(id => panel.controls[id].files);
+ const pending = panel.confirm();
+ panel.requests[0].reject(error);
+ await pending;
+ assert.deepEqual(panel.messages, [error.message]);
+ assert.equal(panel.destroyed(), 0);
+ assert.equal(panel.imported(), 0);
+ assert.equal(panel.controls.ocrImportConfirm.disabled, false);
+ fileIds.forEach((id, index) => assert.equal(panel.controls[id].files, choices[index]));
+ const retry = panel.confirm();
+ panel.requests[1].resolve({code: 0});
+ await retry;
+ assert.equal(panel.imported(), 1);
+ });
+}
+
+for (const state of ["abortError", "aborted", "closed"]) {
+ test(`a rejected import stays quiet when ${state}`, async () => {
+ const panel = createImportDialog();
+ fileIds.forEach(id => panel.select(id, `${id}.bin`));
+ const pending = panel.confirm();
+ if (state === "aborted") panel.controller.abort();
+ if (state === "closed") panel.cancel();
+ const error = new Error("request cancelled");
+ if (state === "abortError") error.name = "AbortError";
+ panel.requests[0].reject(error);
+ await pending;
+ assert.deepEqual(panel.messages, []);
+ assert.equal(panel.imported(), 0);
+ });
+}
+
+for (const state of ["aborted", "closed"]) {
+ test(`a late successful import stays quiet when ${state}`, async () => {
+ const panel = createImportDialog();
+ fileIds.forEach(id => panel.select(id, `${id}.bin`));
+ const pending = panel.confirm();
+ if (state === "aborted") panel.controller.abort();
+ else panel.cancel();
+ panel.requests[0].resolve({code: 0});
+ await pending;
+ assert.deepEqual(panel.messages, []);
+ assert.equal(panel.imported(), 0);
+ assert.equal(panel.destroyed(), state === "closed" ? 1 : 0);
+ });
+}
diff --git a/app/src/config/ocrImport.ts b/app/src/config/ocrImport.ts
index 1ce5c3fd5f..332b75d1c1 100644
--- a/app/src/config/ocrImport.ts
+++ b/app/src/config/ocrImport.ts
@@ -95,9 +95,13 @@ export const openOCRImportModelsDialog = (options: {
recognizerConfig: fileInput(files[3]).files[0],
}), undefined, true, options.signal);
imported = response.code === 0;
+ } catch (error) {
+ if (!closed && !options.signal.aborted && error.name !== "AbortError") {
+ showMessage(error.message);
+ }
} finally {
busy = false;
- if (imported) {
+ if (imported && !closed && !options.signal.aborted) {
showMessage(languages.imported);
dialog.destroy();
options.onImported();
diff --git a/app/src/config/setting/tabs.ts b/app/src/config/setting/tabs.ts
index f7db18147f..dcee84f703 100644
--- a/app/src/config/setting/tabs.ts
+++ b/app/src/config/setting/tabs.ts
@@ -10,7 +10,7 @@ import {mountSyncTabExtras, patchSyncConfig} from "../tabs/syncRuntime";
import {refreshCloudUser} from "../tabs/accountUi";
import {mountAccessTab} from "../tabs/accessRuntime";
import {collectAssetsTabSearchStrings, mountAssetsTab} from "../assets";
-import {mountOCRTab, registerOCRTab} from "../ocr";
+import {mountOCRTab, registerOCRTab, updateOCRTabBorders} from "../ocr";
import {collectBazaarTabSearchStrings, mountBazaarTab} from "../bazaarTab";
/// #if !MOBILE
import {collectKeymapTabSearchStrings, mountKeymapTab} from "../tabs/keymapUi";
@@ -92,6 +92,7 @@ const createSettingTabs = () => {
icon: "iconOCR",
title: () => "OCR",
afterMount: mountOCRTab,
+ onShow: updateOCRTabBorders,
}, registerOCRTab),
export: setting.tab({
id: "export",