An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Add one-click OCR text clearing https://github.com/siyuan-note/siyuan/issues/20556
Daniel5b96d1fa4867
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 30574a0824..681ba9d6dd 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,6 @@{+ "clearOCRText": "مسح نص OCR",+ "clearOCRTextDone": "تم مسح نص OCR","compactMode": "الوضع المضغوط","compactModeTip": "تقليل المسافات في الواجهة مع الحفاظ على حجم النص؛ قد يختلف التأثير مع سمات المجتمع","ocrTooltipSettings": "تلميحات الصور",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 0f806e5a3b..61a684aba5 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,6 @@{+ "clearOCRText": "OCR-Text löschen",+ "clearOCRTextDone": "OCR-Text gelöscht","compactMode": "Kompaktmodus","compactModeTip": "Abstände der Oberfläche bei gleicher Textgröße verringern; die Wirkung kann je nach Community-Theme variieren","ocrTooltipSettings": "Bildhinweise",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 4b7900ee79..b9c70cc94c 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,6 @@{+ "clearOCRText": "Clear OCR text",+ "clearOCRTextDone": "OCR text cleared","compactMode": "Compact mode","compactModeTip": "Reduce interface spacing while keeping text size; the effect may vary with community themes","ocrTooltipSettings": "Image tooltips",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 7e419db3d0..7ca662b7b9 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,6 @@{+ "clearOCRText": "Borrar texto OCR",+ "clearOCRTextDone": "Texto OCR borrado","compactMode": "Modo compacto","compactModeTip": "Reduce el espaciado de la interfaz sin cambiar el tamaño del texto; el efecto puede variar con los temas de la comunidad","ocrTooltipSettings": "Información de las imágenes",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex 526df6bc4f..8c6ce903a4 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,6 @@{+ "clearOCRText": "Effacer le texte OCR",+ "clearOCRTextDone": "Texte OCR effacé","compactMode": "Mode compact","compactModeTip": "Réduit les espacements de l’interface sans modifier la taille du texte ; l’effet peut varier selon les thèmes de la communauté","ocrTooltipSettings": "Infobulles des images",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex e7981d06cd..7752bd580a 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,6 @@{+ "clearOCRText": "נקה טקסט OCR",+ "clearOCRTextDone": "טקסט OCR נוקה","compactMode": "מצב קומפקטי","compactModeTip": "צמצום המרווחים בממשק תוך שמירה על גודל הטקסט; ההשפעה עשויה להשתנות בהתאם לערכות הנושא של הקהילה","ocrTooltipSettings": "חלוניות מידע של תמונות",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 1073543925..5b19c4a43f 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,6 @@{+ "clearOCRText": "OCR पाठ साफ़ करें",+ "clearOCRTextDone": "OCR पाठ साफ़ कर दिया गया","compactMode": "संक्षिप्त मोड","compactModeTip": "टेक्स्ट का आकार बनाए रखते हुए इंटरफ़ेस में खाली जगह कम करें; समुदाय की थीम के साथ प्रभाव अलग हो सकता है","ocrTooltipSettings": "चित्र टूलटिप",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 56bf251595..d6d2bd368b 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,6 @@{+ "clearOCRText": "Hapus teks OCR",+ "clearOCRTextDone": "Teks OCR dihapus","compactMode": "Mode ringkas","compactModeTip": "Kurangi jarak antarelemen antarmuka tanpa mengubah ukuran teks; efeknya dapat berbeda pada tema komunitas","ocrTooltipSettings": "Tooltip gambar",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 0086498669..3707931462 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,6 @@{+ "clearOCRText": "Cancella testo OCR",+ "clearOCRTextDone": "Testo OCR cancellato","compactMode": "Modalità compatta","compactModeTip": "Riduce gli spazi dell’interfaccia mantenendo le dimensioni del testo; l’effetto può variare con i temi della community","ocrTooltipSettings": "Suggerimenti delle immagini",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex cffbff6613..2f8bb18947 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,6 @@{+ "clearOCRText": "OCR テキストを消去",+ "clearOCRTextDone": "OCR テキストを消去しました","compactMode": "コンパクトモード","compactModeTip": "文字サイズを維持したまま画面の間隔を狭くします。コミュニティテーマでは効果が異なる場合があります","ocrTooltipSettings": "画像のツールチップ",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex f07e992a2e..f9acf3d808 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,6 @@{+ "clearOCRText": "OCR 텍스트 지우기",+ "clearOCRTextDone": "OCR 텍스트를 지웠습니다","compactMode": "간결한 모드","compactModeTip": "텍스트 크기를 유지하면서 인터페이스 간격을 줄입니다. 커뮤니티 테마에 따라 효과가 다를 수 있습니다","ocrTooltipSettings": "이미지 툴팁",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex ce6e571e57..c9a2d1bab2 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,6 @@{+ "clearOCRText": "OCR-tekst wissen",+ "clearOCRTextDone": "OCR-tekst gewist","compactMode": "Compacte modus","compactModeTip": "Verklein de tussenruimte in de interface met behoud van de tekstgrootte; het effect kan per communitythema verschillen","ocrTooltipSettings": "Afbeeldingstooltips",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 1c5721b0fe..d4605b2007 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,6 @@{+ "clearOCRText": "Wyczyść tekst OCR",+ "clearOCRTextDone": "Tekst OCR został wyczyszczony","compactMode": "Tryb kompaktowy","compactModeTip": "Zmniejsza odstępy w interfejsie bez zmiany rozmiaru tekstu; efekt może się różnić w motywach społeczności","ocrTooltipSettings": "Podpowiedzi obrazów",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 1b9cf89331..4b7415cad4 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,6 @@{+ "clearOCRText": "Limpar texto OCR",+ "clearOCRTextDone": "Texto OCR limpo","compactMode": "Modo compacto","compactModeTip": "Reduz o espaçamento da interface sem alterar o tamanho do texto; o efeito pode variar com os temas da comunidade","ocrTooltipSettings": "Dicas de imagens",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 633c407749..09b79de346 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,6 @@{+ "clearOCRText": "Очистить текст OCR",+ "clearOCRTextDone": "Текст OCR очищен","compactMode": "Компактный режим","compactModeTip": "Уменьшает отступы интерфейса, сохраняя размер текста; результат может отличаться в темах сообщества","ocrTooltipSettings": "Подсказки изображений",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex a03b98f126..00912122c2 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,6 @@{+ "clearOCRText": "Vymazať text OCR",+ "clearOCRTextDone": "Text OCR bol vymazaný","compactMode": "Kompaktný režim","compactModeTip": "Zmenší rozostupy v rozhraní pri zachovaní veľkosti textu; účinok sa môže líšiť pri témach komunity","ocrTooltipSettings": "Tipy obrázkov",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex 6fbcaf6b6e..dfaf67de83 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,6 @@{+ "clearOCRText": "Очисти OCR текст",+ "clearOCRTextDone": "OCR текст је очишћен","compactMode": "Компактни режим","compactModeTip": "Смањује размаке у интерфејсу уз задржавање величине текста; ефекат може да се разликује у темама заједнице","ocrTooltipSettings": "Облачићи слике",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 55f482baf4..f3042c3071 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,6 @@{+ "clearOCRText": "ล้างข้อความ OCR",+ "clearOCRTextDone": "ล้างข้อความ OCR แล้ว","compactMode": "โหมดกะทัดรัด","compactModeTip": "ลดระยะห่างในส่วนติดต่อโดยคงขนาดข้อความไว้ ผลลัพธ์อาจแตกต่างกันตามธีมของชุมชน","ocrTooltipSettings": "คำแนะนำรูปภาพ",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 1db3b5f2de..46ddb1f5f2 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,6 @@{+ "clearOCRText": "OCR metnini temizle",+ "clearOCRTextDone": "OCR metni temizlendi","compactMode": "Kompakt mod","compactModeTip": "Metin boyutunu koruyarak arayüz boşluklarını azaltır; etki topluluk temalarına göre değişebilir","ocrTooltipSettings": "Görsel araç ipuçları",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 3916f6a997..a620ece6cc 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,6 @@{+ "clearOCRText": "Очистити текст OCR",+ "clearOCRTextDone": "Текст OCR очищено","compactMode": "Компактний режим","compactModeTip": "Зменшує відступи інтерфейсу, зберігаючи розмір тексту; результат може відрізнятися в темах спільноти","ocrTooltipSettings": "Підказки зображень",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex dc5cabf4af..faaa72f1fb 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,6 @@{+ "clearOCRText": "清空 OCR 文本",+ "clearOCRTextDone": "已清空 OCR 文本","compactMode": "紧凑模式","compactModeTip": "缩小界面间距并保持文字大小,社区主题下的效果可能有所不同","ocrTooltipSettings": "图片提示",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 5453a2ee03..d5da0e0b85 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,6 @@{+ "clearOCRText": "清空 OCR 文字",+ "clearOCRTextDone": "已清空 OCR 文字","compactMode": "緊湊模式","compactModeTip": "縮小介面間距並保持文字大小,社群佈景主題下的效果可能有所不同","ocrTooltipSettings": "圖片提示",diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100744-br924ar.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100744-br924ar.syindex 6ff2ed2b85..28748c127d 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100744-br924ar.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100744-br924ar.sy@@ -6,7 +6,7 @@"id": "20200924100744-br924ar","title": "Assets","type": "doc",- "updated": "20261014140201"+ "updated": "20261014150710"},"Children": [{@@ -1041,7 +1041,7 @@"HeadingLevel": 2,"Properties": {"id": "20230117003636-epvk98g",- "updated": "20261014140201"+ "updated": "20261014150710"},"Children": [{@@ -1549,7 +1549,7 @@"HeadingLevel": 3,"Properties": {"id": "20230414202934-1h96or8",- "updated": "20261014140201"+ "updated": "20261014150710"},"Children": [{@@ -1671,6 +1671,47 @@}]},+ {+ "ID": "20261014150710-z1vm4en",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261014150710-z1vm4en",+ "updated": "20261014150710"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Use "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Image menu"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "OCR"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Clear OCR text"+ },+ {+ "Type": "NodeText",+ "Data": " to clear the asset’s OCR text in one click. This affects all images referencing the same asset and updates the search index. The empty result is retained, so automatic OCR skips the asset; rerun OCR manually from the image menu to restore text."+ }+ ]+ },{"ID": "20260930090802-3zn8sf9","Type": "NodeParagraph",diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200915214115-42b8zma.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200915214115-42b8zma.syindex ab108beef5..7373fac4dd 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200915214115-42b8zma.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200915214115-42b8zma.sy@@ -6,7 +6,7 @@"id": "20200915214115-42b8zma","title": "资源文件","type": "doc",- "updated": "20261014140201"+ "updated": "20261014150710"},"Children": [{@@ -1053,7 +1053,7 @@"HeadingLevel": 2,"Properties": {"id": "20230117002036-vmc0mx4",- "updated": "20261014140201"+ "updated": "20261014150710"},"Children": [{@@ -1553,7 +1553,7 @@"HeadingLevel": 3,"Properties": {"id": "20230414202710-a51lo76",- "updated": "20261014140201"+ "updated": "20261014150710"},"Children": [{@@ -1675,6 +1675,47 @@}]},+ {+ "ID": "20261014150710-trk8l20",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261014150710-trk8l20",+ "updated": "20261014150710"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "可通过 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "图片菜单"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "OCR"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "清空 OCR 文本"+ },+ {+ "Type": "NodeText",+ "Data": " 一键清空该资源的 OCR 文本,同时影响引用同一资源的所有图片并更新搜索索引。清空后保留空结果,自动 OCR 会跳过该资源;如需恢复,可从图片菜单手动重新识别。"+ }+ ]+ },{"ID": "20260930090802-qkecuzx","Type": "NodeParagraph",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123038-4umgpxy.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123038-4umgpxy.syindex 3269e9c96a..8fd9d436d9 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123038-4umgpxy.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123038-4umgpxy.sy@@ -6,7 +6,7 @@"id": "20211226123038-4umgpxy","title": "資料文件","type": "doc",- "updated": "20261014140201"+ "updated": "20261014150710"},"Children": [{@@ -1039,7 +1039,7 @@"HeadingLevel": 2,"Properties": {"id": "20230117003901-ze4mbzz",- "updated": "20261014140201"+ "updated": "20261014150710"},"Children": [{@@ -1539,7 +1539,7 @@"HeadingLevel": 3,"Properties": {"id": "20230414203058-foirrwk",- "updated": "20261014140201"+ "updated": "20261014150710"},"Children": [{@@ -1661,6 +1661,47 @@}]},+ {+ "ID": "20261014150710-p7nr3gx",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261014150710-p7nr3gx",+ "updated": "20261014150710"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "可透過 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "圖片選單"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "OCR"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "清空 OCR 文字"+ },+ {+ "Type": "NodeText",+ "Data": " 一鍵清空該資源的 OCR 文字,同時影響引用同一資源的所有圖片並更新搜尋索引。清空後保留空結果,自動 OCR 會跳過該資源;如需恢復,可從圖片選單手動重新辨識。"+ }+ ]+ },{"ID": "20260930090802-ffpq13r","Type": "NodeParagraph",diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-1m5un7l.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-1m5un7l.syindex 504cec9eae..4c671c4f33 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-1m5un7l.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-1m5un7l.sy@@ -7,7 +7,7 @@"id": "20240530101000-1m5un7l","title": "アセット","type": "doc",- "updated": "20261014140201"+ "updated": "20261014150710"},"Children": [{@@ -1079,7 +1079,7 @@"Properties": {"ID": "20240530101000-5bix8t1","id": "20240530101000-9evyuhr",- "updated": "20261014140201"+ "updated": "20261014150710"},"Children": [{@@ -1588,7 +1588,7 @@"Properties": {"ID": "20240530101000-aefldsk","id": "20240530101000-cpod2qy",- "updated": "20261014140201"+ "updated": "20261014150710"},"Children": [{@@ -1717,6 +1717,43 @@}]},+ {+ "ID": "20261014150710-r6p45ak",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261014150710-r6p45ak",+ "updated": "20261014150710"+ },+ "Children": [+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "画像メニュー"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "OCR"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "OCR テキストを消去"+ },+ {+ "Type": "NodeText",+ "Data": " で、アセットの OCR テキストをワンクリックで消去できます。同じアセットを参照するすべての画像に反映され、検索インデックスも更新されます。空の結果が保持されるため、自動 OCR はそのアセットをスキップします。テキストを復元するには、画像メニューから手動で OCR を再実行してください。"+ }+ ]+ },{"ID": "20240530101000-52fjbe1","Type": "NodeParagraph",diff --git a/app/src/asset/clearImageOCR.test.ts b/app/src/asset/clearImageOCR.test.tsnew file mode 100644index 0000000000..f865217440--- /dev/null+++ b/app/src/asset/clearImageOCR.test.ts@@ -0,0 +1,66 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, ScriptTarget, transpileModule} from "typescript";++const loadClear = () => {+ const requests: {path: string, text: string}[] = [];+ const pending: {resolve: (value: {code: number}) => void, reject: (error: Error) => void}[] = [];+ const invalidated: string[] = [];+ const messages: string[] = [];+ const api = {} as typeof import("./imageOCR");+ runInNewContext(transpileModule(readFileSync("src/asset/imageOCR.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText, {+ exports: api,+ window: {siyuan: {languages: {clearOCRTextDone: "OCR text cleared"}}},+ require: () => ({+ fetchSyncPost: (url: string, body: {path: string, text: string}) => {+ assert.equal(url, "/api/asset/setImageOCRText");+ requests.push({...body});+ return new Promise<{code: number}>((resolve, reject) => pending.push({resolve, reject}));+ },+ invalidateImageOCRStatus: (path: string) => invalidated.push(path),+ showMessage: (message: string) => messages.push(message),+ }),+ });+ return {api, requests, pending, invalidated, messages};+};++test("clearing OCR saves an empty record and refreshes only after success", async () => {+ const {api, requests, pending, invalidated, messages} = loadClear();+ const path = "assets/image.png?box=notebook&width=100#preview";+ const first = api.clearImageOCRText(path);+ await api.clearImageOCRText(path);+ assert.deepEqual(requests, [{path, text: ""}]);+ assert.deepEqual(invalidated, []);+ assert.deepEqual(messages, []);+ pending.shift().resolve({code: 0});+ await first;+ assert.deepEqual(invalidated, [path]);+ assert.deepEqual(messages, ["OCR text cleared"]);+ const again = api.clearImageOCRText(path);+ assert.equal(requests.length, 2);+ pending.shift().resolve({code: 0});+ await again;+});++test("failed OCR clearing does not invalidate or report success and can be retried", async () => {+ const {api, requests, pending, invalidated, messages} = loadClear();+ const failed = api.clearImageOCRText("assets/image.png");+ pending.shift().resolve({code: -1});+ await failed;+ assert.deepEqual(invalidated, []);+ assert.deepEqual(messages, []);+ const disconnected = api.clearImageOCRText("assets/image.png");+ pending.shift().reject(new Error("network unavailable"));+ await disconnected;+ assert.deepEqual(invalidated, []);+ assert.deepEqual(messages, ["network unavailable"]);+ const retry = api.clearImageOCRText("assets/image.png");+ pending.shift().resolve({code: 0});+ await retry;+ assert.equal(requests.length, 3);+ assert.deepEqual(invalidated, ["assets/image.png"]);+});diff --git a/app/src/asset/imageOCR.ts b/app/src/asset/imageOCR.tsindex 4b55eca3e0..57813fefb5 100644--- a/app/src/asset/imageOCR.ts+++ b/app/src/asset/imageOCR.ts@@ -4,6 +4,26 @@ import {fetchPost, fetchSyncPost} from "../util/fetch";import {writeText} from "../protyle/util/compatibility";import {invalidateImageOCRStatus} from "./imageOCRStatus";+const clearing = new Set<string>();++export const clearImageOCRText = async (path: string) => {+ if (clearing.has(path)) {+ return;+ }+ clearing.add(path);+ try {+ const response = await fetchSyncPost("/api/asset/setImageOCRText", {path, text: ""});+ if (response.code === 0) {+ invalidateImageOCRStatus(path);+ showMessage(window.siyuan.languages.clearOCRTextDone);+ }+ } catch (error) {+ showMessage(error.message, 7000, "error");+ } finally {+ clearing.delete(path);+ }+};+export const copyImageOCRText = (path: string) => {fetchPost("/api/asset/getImageOCRText", {path}, (response) => {writeText(response.data.text);diff --git a/app/src/asset/imageOCRAvailability.test.ts b/app/src/asset/imageOCRAvailability.test.tsindex 0ea4e0a164..8d2e03ce8b 100644--- a/app/src/asset/imageOCRAvailability.test.ts+++ b/app/src/asset/imageOCRAvailability.test.ts@@ -68,14 +68,14 @@ test("shared image menus hide unavailable recognition and its separator while re};const modelMenu = getMenu("assets/image.png", "ordinary");assert.equal(modelMenu.submenu.find((item: {id: string}) => item.id === "reOCR").icon, "iconOCR");- assert.deepEqual(visibleItems("https://example.com/image.png", "ordinary"), ["ocrResult", "copyOCRText"]);+ assert.deepEqual(visibleItems("https://example.com/image.png", "ordinary"), ["ocrResult", "copyOCRText", "clearOCRText"]);assert.deepEqual(visibleItems("assets/image.png?box=encrypted", "ordinary"), []);assert.deepEqual(visibleItems("assets/image.png", "encrypted"), []);- assert.deepEqual(visibleItems("assets/image.svg", "ordinary"), ["ocrResult", "copyOCRText", "separator_reOCR", "reOCR"]);- assert.deepEqual(visibleItems("assets/image.heic", "ordinary"), ["ocrResult", "copyOCRText", "separator_reOCR", "reOCR", "reAIOCR"]);- assert.deepEqual(visibleItems("assets/image.png", "ordinary", true), ["ocrResult", "copyOCRText", "separator_reOCR", "reOCR"]);- assert.deepEqual(visibleItems("assets/image.png", "ordinary", false, "tesseract"), ["ocrResult", "copyOCRText", "separator_reOCR", "reOCR", "reAIOCR"]);- assert.deepEqual(visibleItems("assets/image.png", "ordinary", false, "ai"), ["ocrResult", "copyOCRText", "separator_reOCR", "reAIOCR"]);- assert.deepEqual(visibleItems("assets/image.svg", "ordinary", false, "ai"), ["ocrResult", "copyOCRText"]);- assert.deepEqual(visibleItems("assets/image.png", "ordinary", true, "ai"), ["ocrResult", "copyOCRText"]);+ assert.deepEqual(visibleItems("assets/image.svg", "ordinary"), ["ocrResult", "copyOCRText", "clearOCRText", "separator_reOCR", "reOCR"]);+ assert.deepEqual(visibleItems("assets/image.heic", "ordinary"), ["ocrResult", "copyOCRText", "clearOCRText", "separator_reOCR", "reOCR", "reAIOCR"]);+ assert.deepEqual(visibleItems("assets/image.png", "ordinary", true), ["ocrResult", "copyOCRText", "clearOCRText", "separator_reOCR", "reOCR"]);+ assert.deepEqual(visibleItems("assets/image.png", "ordinary", false, "tesseract"), ["ocrResult", "copyOCRText", "clearOCRText", "separator_reOCR", "reOCR", "reAIOCR"]);+ assert.deepEqual(visibleItems("assets/image.png", "ordinary", false, "ai"), ["ocrResult", "copyOCRText", "clearOCRText", "separator_reOCR", "reAIOCR"]);+ assert.deepEqual(visibleItems("assets/image.svg", "ordinary", false, "ai"), ["ocrResult", "copyOCRText", "clearOCRText"]);+ assert.deepEqual(visibleItems("assets/image.png", "ordinary", true, "ai"), ["ocrResult", "copyOCRText", "clearOCRText"]);});diff --git a/app/src/asset/imageOCRStatus.test.ts b/app/src/asset/imageOCRStatus.test.tsindex c1204d0ddf..cd973c8e52 100644--- a/app/src/asset/imageOCRStatus.test.ts+++ b/app/src/asset/imageOCRStatus.test.ts@@ -62,10 +62,10 @@ test("OCR presence caches text and empty results, merges requests, expires and rassert.equal(cache.requests(), 6);});-test("OCR changes invalidate only the resource and stale requests cannot replace the new cache", async () => {+test("OCR changes invalidate shared resource aliases and discard pending stale results", async () => {const {api, pending, requests, events} = loadCache();const old = api.getImageOCRStatus("assets/image.png");- const other = api.getImageOCRStatus("assets/other.png");+ const other = api.getImageOCRStatus("assets/image.png?width=100#preview");api.invalidateImageOCRStatus("assets/image.png");assert.equal(events(), 1);const updated = api.getImageOCRStatus("assets/image.png");@@ -73,10 +73,12 @@ test("OCR changes invalidate only the resource and stale requests cannot replaceassert.equal(await updated, false);pending[0].resolve({code: 0, data: {text: "stale"}});pending[1].resolve({code: 0, data: {text: "other"}});- await Promise.all([old, other]);+ assert.deepEqual(await Promise.all([old, other]), [undefined, undefined]);assert.equal(await api.getImageOCRStatus("assets/image.png"), false);- assert.equal(await api.getImageOCRStatus("assets/other.png"), true);- assert.equal(requests(), 3);+ const alias = api.getImageOCRStatus("assets/image.png?width=100#preview");+ pending[3].resolve({code: 0, data: {text: ""}});+ assert.equal(await alias, false);+ assert.equal(requests(), 4);});test("OCR result cache retains recognition failures separately from saved text and read failures", async () => {diff --git a/app/src/asset/imageOCRStatus.ts b/app/src/asset/imageOCRStatus.tsindex 0b28ff3566..d0d11b2d88 100644--- a/app/src/asset/imageOCRStatus.ts+++ b/app/src/asset/imageOCRStatus.ts@@ -6,14 +6,16 @@ const statuses = new Map<string, {expires: number, result: Promise<ImageOCRTextDtext: Promise<string | undefined>, status: Promise<boolean | undefined>}>();const cacheDuration = 60000;const cacheLimit = 128;+let generation = 0;const getImageOCREntry = (path: string) => {const cached = statuses.get(path);if (cached && cached.expires > Date.now()) {return cached;}+ const currentGeneration = generation;const result = fetchSyncPost("/api/asset/getImageOCRText", {path}, undefined, false).then(response => {- if (response.code !== 0) {+ if (response.code !== 0 || currentGeneration !== generation) {return undefined;}return response.data;@@ -49,6 +51,8 @@ export const getImageOCRText = (path: string): Promise<string | undefined> => geexport const getImageOCRResult = (path: string): Promise<ImageOCRTextData | undefined> => getImageOCREntry(path).result;export const invalidateImageOCRStatus = (path: string) => {- statuses.delete(path);- window.dispatchEvent(new CustomEvent("siyuan-image-ocr"));+ // 同一资源的显示参数和片段可能不同,一并清除缓存及在途读取结果。+ generation++;+ statuses.clear();+ window.dispatchEvent(new CustomEvent("siyuan-image-ocr", {detail: {path}}));};diff --git a/app/src/config/entryVisibility/catalog.test.ts b/app/src/config/entryVisibility/catalog.test.tsindex 5d23877e22..07552aec8d 100644--- a/app/src/config/entryVisibility/catalog.test.ts+++ b/app/src/config/entryVisibility/catalog.test.ts@@ -2,7 +2,7 @@ import {IMAGE_OCR_MENU} from "../../menus/declarations/imageOCRMenu";import {createDeclaredMenu} from "../../menus/declarations/menuDeclaration";const imageOCRContext = {textAvailable: true, localAvailable: true, aiAvailable: true,- getStatus: async () => false, openResult: () => {}, copyText: () => {}, runLocal: () => {}, runAI: () => {},+ getStatus: async () => false, openResult: () => {}, copyText: () => {}, clearText: () => {}, runLocal: () => {}, runAI: () => {},};import * as assert from "node:assert/strict";import {readFileSync} from "node:fs";@@ -67,10 +67,12 @@ test("image OCR actions retain their configurable paths and order", t => {assert.equal(copyImage.sortable, false);assert.equal(getEntryParentPath("editor.image.copyAsPNG"), "editor.image");assert.deepEqual(getEntryCatalogChildren("inline.image.ocr").map(item => item.key), [- "ocrResult", "copyOCRText", "separator_reOCR", "reOCR", "reAIOCR",+ "ocrResult", "copyOCRText", "clearOCRText", "separator_reOCR", "reOCR", "reAIOCR",]);assert.equal(getEntryCatalogNode("inline.image.ocr.copyOCRText").simple, false);assert.equal(getEntryParentPath("inline.image.ocr.copyOCRText"), "inline.image.ocr");+ assert.equal(getEntryCatalogNode("inline.image.ocr.clearOCRText").simple, false);+ assert.equal(getEntryParentPath("inline.image.ocr.clearOCRText"), "inline.image.ocr");assert.equal(getEntryCatalogNode("inline.image.ocr.reAIOCR").simple, false);assert.equal(getEntryParentPath("inline.image.ocr.reAIOCR"), "inline.image.ocr");assert.deepEqual(createDeclaredMenu(IMAGE_OCR_MENU, imageOCRContext).submenu.map(item => item.id),diff --git a/app/src/config/entryVisibility/catalog.ts b/app/src/config/entryVisibility/catalog.tsindex 24e189bdf3..0876b2aed4 100644--- a/app/src/config/entryVisibility/catalog.ts+++ b/app/src/config/entryVisibility/catalog.ts@@ -981,6 +981,7 @@ export const entryCatalog: IEntryCatalogSection[] = [node("delete", lang("delete")),separator("separator_2"),node("rename", lang("rename")),+ // OCR 子菜单的入口、默认顺序与清空操作共用声明。declaredMenuCatalog(IMAGE_OCR_MENU),node("alignCenter", lang("alignCenter")),node("alignLeft", lang("alignLeft")),diff --git a/app/src/config/entryVisibility/order.test.ts b/app/src/config/entryVisibility/order.test.tsindex aeb4e6dd43..b0a8931ffe 100644--- a/app/src/config/entryVisibility/order.test.ts+++ b/app/src/config/entryVisibility/order.test.ts@@ -11,13 +11,13 @@ import {resolveEntryOrderWithBoundaryDefaults,} from "./order";-test("AI OCR merges into saved image menus while retaining plugin slots and valid separators", () => {+test("new OCR actions merge into saved image menus while retaining plugin slots and valid separators", () => {const entries = getEntryCatalogChildren("inline.image.ocr");const defaults = entries.map(item => item.key);const saved = ["copyOCRText", "plugin:example:item", "ocrResult", "separator_reOCR", "reOCR"];const separators = new Set(entries.filter(item => item.type === "separator").map(item => item.key));const merged = mergeEntryOrderPreservingUnknown(defaults, saved, undefined, separators);- assert.deepEqual(merged, [...saved, "reAIOCR"]);+ assert.deepEqual(merged, ["copyOCRText", "plugin:example:item", "clearOCRText", "ocrResult", "separator_reOCR", "reOCR", "reAIOCR"]);assert.deepEqual(resolveEntryOrder([...defaults, "plugin:example:item"], merged, separators), merged);assert.equal(isValidEntryOrder(merged, separators), true);});diff --git a/app/src/menus/declarations/imageOCRMenu.ts b/app/src/menus/declarations/imageOCRMenu.tsindex 7fa945e1dc..8db78c5755 100644--- a/app/src/menus/declarations/imageOCRMenu.ts+++ b/app/src/menus/declarations/imageOCRMenu.ts@@ -7,6 +7,7 @@ export interface IImageOCRMenuContext {getStatus: () => Promise<boolean | undefined>;openResult: () => void;copyText: () => void;+ clearText: () => void;runLocal: () => void;runAI: () => void;}@@ -49,6 +50,13 @@ export const IMAGE_OCR_MENU: IMenuDeclaration<IImageOCRMenuContext> = {type: "entry",icon: "iconCopy",behavior: context => ({click: context.copyText}),+ }, {+ id: "clearOCRText",+ label: () => window.siyuan.languages.clearOCRText,+ simple: false,+ type: "entry",+ icon: "iconTrashcan",+ behavior: context => ({click: context.clearText}),}, {id: "separator_reOCR",label: () => "",diff --git a/app/src/menus/declarations/menuDeclaration.test.ts b/app/src/menus/declarations/menuDeclaration.test.tsindex ff8bb46796..329d05e1ce 100644--- a/app/src/menus/declarations/menuDeclaration.test.ts+++ b/app/src/menus/declarations/menuDeclaration.test.ts@@ -19,7 +19,7 @@ const installLanguages = (t: {after: (callback: () => void) => void}) => {const context = (options: Partial<IImageOCRMenuContext> = {}): IImageOCRMenuContext => ({textAvailable: true, localAvailable: true, aiAvailable: true,- getStatus: async () => false, openResult: () => {}, copyText: () => {}, runLocal: () => {}, runAI: () => {},+ getStatus: async () => false, openResult: () => {}, copyText: () => {}, clearText: () => {}, runLocal: () => {}, runAI: () => {},...options,});@@ -28,11 +28,13 @@ test("OCR declarations drive catalog order, defaults and complete menu actions",const clicked: string[] = [];const menu = createDeclaredMenu(IMAGE_OCR_MENU, context({openResult: () => { clicked.push("result"); }, copyText: () => { clicked.push("copy"); },+ clearText: () => { clicked.push("clear"); },runLocal: () => { clicked.push("local"); }, runAI: () => { clicked.push("ai"); },}));assert.equal(menu.icon, "iconOCR");assert.deepEqual(menu.submenu.map(item => [item.id, item.label, item.icon, item.type]), [["ocrResult", "ocrResult", "iconEdit", undefined], ["copyOCRText", "copy OCR", "iconCopy", undefined],+ ["clearOCRText", "clearOCRText", "iconTrashcan", undefined],["separator_reOCR", "", undefined, "separator"], ["reOCR", "performOCR", "iconOCR", undefined],["reAIOCR", "performAIOCR", "iconSparkles", undefined],]);@@ -40,9 +42,9 @@ test("OCR declarations drive catalog order, defaults and complete menu actions",assert.equal(catalog.key, "ocr");assert.equal(catalog.simple, false);assert.deepEqual(catalog.children.map(item => item.key), menu.submenu.map(item => item.id));- assert.deepEqual(catalog.children.map(item => item.simple), [false, false, true, false, false]);+ assert.deepEqual(catalog.children.map(item => item.simple), [false, false, false, true, false, false]);menu.submenu.forEach(item => item.click?.(undefined, undefined));- assert.deepEqual(clicked, ["result", "copy", "local", "ai"]);+ assert.deepEqual(clicked, ["result", "copy", "clear", "local", "ai"]);});test("conditional OCR availability does not change configurable identities", t => {@@ -52,7 +54,7 @@ test("conditional OCR availability does not change configurable identities", t =for (const aiAvailable of [false, true]) {const menu = createDeclaredMenu(IMAGE_OCR_MENU, context({textAvailable, localAvailable, aiAvailable}));assert.equal(menu.ignore, !textAvailable);- assert.deepEqual(menu.submenu.map(item => item.ignore === true), [false, false,+ assert.deepEqual(menu.submenu.map(item => item.ignore === true), [false, false, false,!localAvailable && !aiAvailable, !localAvailable, !aiAvailable]);assert.deepEqual(menu.submenu.map(item => item.id), declaredMenuCatalog(IMAGE_OCR_MENU).children.map(item => item.key));}diff --git a/app/src/menus/imageOCRMenu.test.ts b/app/src/menus/imageOCRMenu.test.tsindex 43a2da1210..19763f7f23 100644--- a/app/src/menus/imageOCRMenu.test.ts+++ b/app/src/menus/imageOCRMenu.test.ts@@ -36,3 +36,23 @@ test("shared local OCR menu refreshes tooltip state after successful and failedawait Promise.resolve();assert.deepEqual(invalidated, ["assets/image.png", "assets/another.png"]);});++test("shared image menu clears the current resource with its notebook identity", () => {+ const api = {} as typeof import("./imageOCRMenu");+ let currentPath = "assets/image.png?box=first#preview";+ const cleared: string[] = [];+ runInNewContext(transpileModule(readFileSync("src/menus/imageOCRMenu.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},+ }).outputText, {exports: api, window: {siyuan: {config: {ocr: {provider: "ai"}}}}, require: () => ({+ getImageOCRAvailability: () => ({text: true, local: true, ai: true}),+ isDisabledFeature: () => false,+ createDeclaredMenu: (_declaration: unknown, context: unknown) => context,+ clearImageOCRText: async (path: string) => { cleared.push(path); },+ })});+ const context = api.createImageOCRMenu({getAttribute: () => currentPath} as unknown as HTMLElement, "notebook") as unknown as {+ clearText: () => void;+ };+ currentPath = "assets/image.png?box=second#preview";+ context.clearText();+ assert.deepEqual(cleared, [currentPath]);+});diff --git a/app/src/menus/imageOCRMenu.ts b/app/src/menus/imageOCRMenu.tsindex c350f0acfb..ab4cdde41b 100644--- a/app/src/menus/imageOCRMenu.ts+++ b/app/src/menus/imageOCRMenu.ts@@ -1,4 +1,4 @@-import {copyImageOCRText, openImageOCR} from "../asset/imageOCR";+import {clearImageOCRText, copyImageOCRText, openImageOCR} from "../asset/imageOCR";import {reImageAIOCR} from "../asset/imageAIOCR";import {getImageOCRAvailability} from "../asset/imageOCRAvailability";import {getImageOCRStatus, invalidateImageOCRStatus} from "../asset/imageOCRStatus";@@ -17,6 +17,7 @@ export const createImageOCRMenu = (image: HTMLElement, notebookID: string): IMengetStatus: () => getImageOCRStatus(path),openResult: () => openImageOCR(image.getAttribute("data-src")),copyText: () => { copyImageOCRText(image.getAttribute("data-src")); },+ clearText: () => { void clearImageOCRText(image.getAttribute("data-src")); },runAI: () => { void reImageAIOCR(image.getAttribute("data-src")); },runLocal: () => {const currentPath = image.getAttribute("data-src");diff --git a/kernel/api/asset.go b/kernel/api/asset.goindex 5f7df0bf7b..288dfdb380 100644--- a/kernel/api/asset.go+++ b/kernel/api/asset.go@@ -145,10 +145,6 @@ var ocr = contractHandler(apicontract.AssetOCR, func(c *gin.Context, request apiif model.IsEncryptedAssetPath(absPath) {return apicontract.FailureWithTimeout[apicontract.AssetOCRData](-1, model.Conf.Language(380), 3000)}- if err = model.EnsureAssetLocal(absPath); err != nil {- return apicontract.Failure[apicontract.AssetOCRData](-1, err.Error())- }-ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Minute)defer cancel()text, ocrJSON, err := model.OCRAsset(ctx, path)diff --git a/kernel/api/asset_download_authorization_test.go b/kernel/api/asset_download_authorization_test.goindex f252a3622c..ec70aa189e 100644--- a/kernel/api/asset_download_authorization_test.go+++ b/kernel/api/asset_download_authorization_test.go@@ -18,6 +18,7 @@ import ("github.com/gin-gonic/gin""github.com/siyuan-note/dejavu""github.com/siyuan-note/dejavu/cloud"+ "github.com/siyuan-note/dejavu/entity""github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/util"@@ -31,7 +32,7 @@ func TestAPIContractDeferredAssetSymlinkWorkspace(t *testing.T) {testDeferredAssetAPIAuthorizationAndMetadata(t, true)}-func testDeferredAssetAPIAuthorizationAndMetadata(t *testing.T, symlinkWorkspace bool) {+func setupDeferredAssetAPIWorkspace(t *testing.T, symlinkWorkspace bool, plainContent []byte) (map[string][]byte, []*entity.File) {t.Helper()gin.SetMode(gin.TestMode)originalConf := model.Conf@@ -119,6 +120,9 @@ func testDeferredAssetAPIAuthorizationAndMetadata(t *testing.T, symlinkWorkspaceboxID + "/assets/private.bin": []byte("locked ciphertext fixture"),boxID + "/.siyuan/conf.json": boxConfData,}+ if plainContent != nil {+ files["assets/plain.bin"] = plainContent+ }for name, data := range files {absPath := filepath.Join(base, "full", "data", filepath.FromSlash(name))if err = os.MkdirAll(filepath.Dir(absPath), 0755); err != nil {@@ -142,6 +146,13 @@ func testDeferredAssetAPIAuthorizationAndMetadata(t *testing.T, symlinkWorkspaceif err != nil || len(deferred) != 2 {t.Fatalf("expected two deferred assets: %+v, %v", deferred, err)}+ return files, deferred+}++func testDeferredAssetAPIAuthorizationAndMetadata(t *testing.T, symlinkWorkspace bool) {+ t.Helper()+ files, deferred := setupDeferredAssetAPIWorkspace(t, symlinkWorkspace, nil)+ const boxID = "20260905123456-abcdefg"statePath := filepath.Join(util.ConfDir, "asset-downloads.json")stateBefore, err := os.ReadFile(statePath)if err != nil {diff --git a/kernel/api/contract_ocr_clear_test.go b/kernel/api/contract_ocr_clear_test.gonew file mode 100644index 0000000000..cbc6d21306--- /dev/null+++ b/kernel/api/contract_ocr_clear_test.go@@ -0,0 +1,81 @@+package api++import (+ "bytes"+ "image"+ "image/png"+ "io"+ "net/http"+ "net/http/httptest"+ "os"+ "os/exec"+ "path/filepath"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/eventbus"+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAPIContractOCRClearDuringDownload(t *testing.T) {+ const child = "SIYUAN_TEST_OCR_CLEAR_DOWNLOAD"+ if os.Getenv(child) != "1" {+ command := exec.Command(os.Args[0], "-test.run=^TestAPIContractOCRClearDuringDownload$", "-test.timeout=30s", "-test.v")+ command.Env = append(os.Environ(), child+"=1")+ if output, err := command.CombinedOutput(); err != nil {+ t.Fatalf("OCR download subprocess: %v\n%s", err, output)+ }+ return+ }+ var imageData bytes.Buffer+ if err := png.Encode(&imageData, image.NewRGBA(image.Rect(0, 0, 16, 16))); err != nil {+ t.Fatal(err)+ }+ setupDeferredAssetAPIWorkspace(t, false, imageData.Bytes())+ calls := 0+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ calls+++ w.Header().Set("Content-Type", "application/json")+ _, _ = io.WriteString(w, aiOCRSuccess)+ }))+ defer server.Close()+ model.Conf.AI.Store(conf.NewAI())+ model.Conf.AI.Load().Providers = []*conf.Provider{{ID: "provider", Enabled: true, APIKey: "test", BaseURL: server.URL + "/v1",+ Models: []*conf.Model{{ID: "vision", Enabled: true, Name: "vision-test"}}}}+ model.Conf.OCR.Store(&conf.OCR{Provider: "ai", Model: "tiny", AIModelID: "vision"})+ engine := gin.New()+ engine.POST("/api/asset/ocr", ocr)+ engine.POST("/api/asset/setImageOCRText", setImageOCRText)+ engine.POST("/api/asset/getImageOCRText", getImageOCRText)+ const path = "assets/plain.bin"+ defer util.RemoveAssetText(path)+ cleared := false+ if err := eventbus.Subscribe(eventbus.EvtCloudBeforeDownloadChunks, func(_ map[string]interface{}, _ int) {+ if cleared {+ return+ }+ cleared = true+ if _, err := os.Stat(filepath.Join(util.DataDir, filepath.FromSlash(path))); !os.IsNotExist(err) {+ t.Error("OCR download hook ran after the asset was materialized")+ }+ if code := requestOCRProvider(t, engine, "/api/asset/setImageOCRText", `{"path":"assets/plain.bin","text":""}`, nil); code != 0 {+ t.Errorf("clear during download failed: %d", code)+ }+ }); err != nil {+ t.Fatal(err)+ }+ if code := requestOCRProvider(t, engine, "/api/asset/ocr", `{"path":"assets/plain.bin"}`, nil); code != -1 || !cleared || calls != 1 {+ t.Fatalf("in-flight OCR was not canceled after clearing during download: code=%d cleared=%v calls=%d", code, cleared, calls)+ }+ var result apicontract.ImageOCRTextData+ if code := requestOCRProvider(t, engine, "/api/asset/getImageOCRText", `{"path":"assets/plain.bin"}`, &result); code != 0 ||+ !util.ExistsAssetText(path) || result.Text != "" || result.Failed {+ t.Fatalf("downloaded OCR restored cleared text or failure: code=%d result=%+v", code, result)+ }+ if code := requestOCRProvider(t, engine, "/api/asset/ocr", `{"path":"assets/plain.bin"}`, nil); code != 0 || util.GetAssetText(path) == "" {+ t.Fatalf("new manual OCR did not restore text: code=%d text=%q", code, util.GetAssetText(path))+ }+}diff --git a/kernel/model/ocr.go b/kernel/model/ocr.goindex 9c17c07ba5..ec33639a3e 100644--- a/kernel/model/ocr.go+++ b/kernel/model/ocr.go@@ -172,19 +172,21 @@ func OCRAsset(ctx context.Context, path string) (string, []map[string]string, er}func ocrAsset(ctx context.Context, path string, value conf.OCR, automatic bool) (_ string, _ []map[string]string, resultErr error) {- if value.Provider != "ai" {- defer func() {- if !automatic || automaticOCRMatches(value) {- recordOCRFailure(path, resultErr)- }- }()- }if value.Provider == "ai" {text, err := aiOCRAsset(ctx, path, value, automatic)return text, []map[string]string{}, err}+ path = strings.SplitN(strings.TrimSpace(path), "#", 2)[0]+ canonical, boxID, err := assetPathAndBox(path, "")+ if err != nil {+ return "", nil, err+ }+ if boxID != "" {+ canonical += "?box=" + url.QueryEscape(boxID)+ }+ request := beginOCRRequest(canonical)+ defer func() { request.finish(value, automatic, resultErr) }()InitOCR()- path = strings.SplitN(path, "#", 2)[0]if IsEncryptedOCRAsset(path) {return "", nil, errors.New(Conf.Language(380))}@@ -207,18 +209,10 @@ func ocrAsset(ctx context.Context, path string, value conf.OCR, automatic bool)if err != nil {return "", nil, err}- canonical, boxID, err := assetPathAndBox(path, "")- if err != nil {- return "", nil, err- }- if boxID != "" {- canonical += "?box=" + url.QueryEscape(boxID)- }- if automatic && !canSaveAutomaticOCR(value, canonical) {+ text := util.GetOcrJsonText(rows)+ if !request.save(text, value, automatic) {return "", nil, context.Canceled}- text := util.GetOcrJsonText(rows)- SetOCRAssetText(canonical, text)return text, rows, nil}@@ -226,9 +220,16 @@ func SetOCRAssetText(path, text string) {if IsEncryptedOCRAsset(path) {return}- path = util.OCRAssetKey(path)+ path = util.OCRAssetKey(strings.TrimSpace(path))+ ocrRequests.Lock()+ delete(ocrRequests.active, path)util.SetAssetText(path, text)clearOCRFailure(path)+ ocrRequests.Unlock()+ indexOCRAssetText(path)+}++func indexOCRAssetText(path string) {documents, err := sql.QueryOCRAssetDocuments(path)if err != nil {logging.LogErrorf("query OCR asset documents failed: %s", err)diff --git a/kernel/model/ocr_ai.go b/kernel/model/ocr_ai.goindex 31a348eb57..f14307a5cb 100644--- a/kernel/model/ocr_ai.go+++ b/kernel/model/ocr_ai.go@@ -29,17 +29,14 @@ func AIOCRAsset(ctx context.Context, path string) (string, error) {}func aiOCRAsset(ctx context.Context, path string, value conf.OCR, automatic bool) (_ string, resultErr error) {- defer func() {- if !automatic || automaticOCRMatches(value) {- recordOCRFailure(path, resultErr)- }- }()+ path = strings.SplitN(strings.TrimSpace(path), "#", 2)[0]+ attempt := beginOCRRequest(path)+ defer func() { attempt.finish(value, automatic, resultErr) }()confAISnapshot := Conf.LoadAI()if util.IsDisabledFeature("ai") {return "", errors.New(Conf.Language(380))}- path = strings.SplitN(strings.TrimSpace(path), "#", 2)[0]if IsEncryptedOCRAsset(path) {return "", errors.New(Conf.Language(380))}@@ -123,10 +120,9 @@ func aiOCRAsset(ctx context.Context, path string, value conf.OCR, automatic boolreturn "", errors.New(Conf.Language(413))}text := strings.ReplaceAll(response.Choices[0].Message.Content, "\r\n", "\n")- if automatic && !canSaveAutomaticOCR(value, path) {+ if !attempt.save(text, value, automatic) {return "", context.Canceled}- SetOCRAssetText(path, text)return text, nil}diff --git a/kernel/model/ocr_ai_index_test.go b/kernel/model/ocr_ai_index_test.goindex 02789ef580..04b93a33c2 100644--- a/kernel/model/ocr_ai_index_test.go+++ b/kernel/model/ocr_ai_index_test.go@@ -5,6 +5,7 @@ package modelimport ("context""errors"+ "fmt""image""image/png""io"@@ -90,6 +91,7 @@ func testAIOCRAssetIndex(t *testing.T, path, blockID string) {{"reasoning changed", func() { Conf.m.Lock(); Conf.OCR.Load().ReasoningEffort = "none"; Conf.m.Unlock() }, ""},{"AI model disabled", func() { Conf.AI.Load().Providers[0].Models[0].Enabled = false }, ""},{"manually edited", func() { SetOCRAssetText(path, "manual text") }, "manual text"},+ {"manually cleared", func() { SetOCRAssetText(path, "") }, ""},} {t.Run(test.name, func(t *testing.T) {util.RemoveAssetText(path)@@ -106,6 +108,35 @@ func testAIOCRAssetIndex(t *testing.T, path, blockID string) {}})}+ for _, automatic := range []bool{false, true} {+ for _, failed := range []bool{false, true} {+ t.Run(fmt.Sprintf("AI clear automatic=%v failed=%v", automatic, failed), func(t *testing.T) {+ util.RemoveAssetText(path)+ value := conf.OCR{Provider: "ai", Model: "tiny", AIModelID: "vision", Auto: true}+ Conf.OCR.Store(&value)+ providerFailure = failed+ beforeResponse = func() { SetOCRAssetText(path+"?width=200#cleared", "") }+ _, err := aiOCRAsset(context.Background(), path+"?width=100#recognizing", value, automatic)+ beforeResponse = nil+ if err == nil || !failed && !errors.Is(err, context.Canceled) {+ t.Fatalf("unexpected invalidated AI request result: %v", err)+ }+ if !util.ExistsAssetText(path) || util.GetAssetText(path) != "" || HasOCRFailure(path) {+ t.Fatalf("in-flight AI response changed cleared text or status: %q, %v", util.GetAssetText(path), HasOCRFailure(path))+ }+ ocrRequests.Lock()+ active := len(ocrRequests.active)+ ocrRequests.Unlock()+ if active != 0 {+ t.Fatal("completed AI OCR retained request state")+ }+ providerFailure = false+ if _, err = AIOCRAsset(context.Background(), path); err != nil || !strings.Contains(util.GetAssetText(path), "aiocrkeyword") {+ t.Fatalf("manual AI recognition after clearing did not restore text: %v, %q", err, util.GetAssetText(path))+ }+ })+ }+ }beforeResponse = nilConf.AI.Load().Providers[0].Models[0].Enabled = trueConf.OCR.Store(&conf.OCR{Provider: "ai", Model: "tiny", AIModelID: "vision", Auto: true})diff --git a/kernel/model/ocr_index_test.go b/kernel/model/ocr_index_test.goindex 0064e4f468..57f897dfd6 100644--- a/kernel/model/ocr_index_test.go+++ b/kernel/model/ocr_index_test.go@@ -12,6 +12,7 @@ import ("os/exec""path/filepath""strings"+ "sync""testing""github.com/88250/lute/parse"@@ -26,16 +27,20 @@ import ()type ocrFixtureProvider struct {- rows []map[string]string- err error- called bool- path string+ rows []map[string]string+ err error+ called bool+ path string+ beforeResponse func()}func (*ocrFixtureProvider) Available() bool { return true }func (p *ocrFixtureProvider) Recognize(_ context.Context, path string) ([]map[string]string, error) {p.called = truep.path = path+ if p.beforeResponse != nil {+ p.beforeResponse()+ }return p.rows, p.err}@@ -117,6 +122,7 @@ func TestOCRResultReindexesWithoutTesseract(t *testing.T) {if err != nil || len(matches) != 0 {t.Fatalf("obsolete OCR remained in full-text search: %v, %v", matches, err)}+ testOCRClearResults(t, path, provider)provider.err = errors.New("inference failed")testAIOCRAssetIndex(t, path, paragraph.ID)if _, _, err := OCRAsset(context.Background(), path); err == nil {@@ -219,6 +225,115 @@ func TestOCRResultReindexesWithoutTesseract(t *testing.T) {testOCRNotebookIsolation(t, provider, fixture.box.ID)}+func testOCRClearResults(t *testing.T, path string, provider *ocrFixtureProvider) {+ t.Helper()+ recordOCRFailure(path, errors.New("previous failure"))+ SetOCRAssetText(path+"?width=100#preview", "")+ sql.FlushQueue()+ assertCleared := func(t *testing.T) {+ t.Helper()+ if !util.ExistsAssetText(path) || util.GetAssetText(path) != "" || HasOCRFailure(path) {+ t.Fatalf("cleared OCR was not retained: exists=%v text=%q failed=%v", util.ExistsAssetText(path), util.GetAssetText(path), HasOCRFailure(path))+ }+ }+ assertCleared(t)+ matches, err := sql.QueryNoLimit("SELECT id FROM blocks_fts WHERE blocks_fts MATCH 'editedocrkeyword'")+ if err != nil || len(matches) != 0 {+ t.Fatalf("cleared OCR remained in full-text search: %v, %v", matches, err)+ }+ util.SaveAssetsTexts()+ util.RemoveAssetText(path)+ util.LoadAssetsTexts()+ assertCleared(t)+ provider.called = false+ cache.LoadAssets()+ autoOCRAssets()+ if provider.called {+ t.Fatal("automatic OCR reran a cleared result after reload")+ }+ for _, automatic := range []bool{false, true} {+ for _, failed := range []bool{false, true} {+ t.Run(fmt.Sprintf("local clear automatic=%v failed=%v", automatic, failed), func(t *testing.T) {+ util.RemoveAssetText(path)+ provider.err = nil+ if failed {+ provider.err = errors.New("in-flight failure")+ }+ provider.beforeResponse = func() { SetOCRAssetText(path+"?width=200#cleared", "") }+ _, _, err := ocrAsset(context.Background(), path+"?width=100#recognizing", Conf.GetOCR(), automatic)+ provider.beforeResponse = nil+ if failed && !errors.Is(err, provider.err) || !failed && !errors.Is(err, context.Canceled) {+ t.Fatalf("unexpected invalidated request result: %v", err)+ }+ assertCleared(t)+ ocrRequests.Lock()+ active := len(ocrRequests.active)+ ocrRequests.Unlock()+ if active != 0 {+ t.Fatal("completed OCR retained request state")+ }+ provider.err = nil+ if _, _, err = OCRAsset(context.Background(), path); err != nil || !strings.Contains(util.GetAssetText(path), "nativeocrkeyword") {+ t.Fatalf("manual recognition after clearing did not restore text: %v, %q", err, util.GetAssetText(path))+ }+ })+ }+ }+ t.Run("overlapping manual requests", func(t *testing.T) {+ value := Conf.GetOCR()+ first := beginOCRRequest(path)+ second := beginOCRRequest(path + "?width=200#preview")+ if !first.save("first result", value, false) {+ t.Fatal("first manual result was rejected")+ }+ first.finish(value, false, nil)+ if !second.save("second result", value, false) || util.GetAssetText(path) != "second result" {+ t.Fatal("later manual result did not supersede the first")+ }+ second.finish(value, false, nil)+ stale := beginOCRRequest(path)+ SetOCRAssetText(path, "")+ current := beginOCRRequest(path)+ if stale.save("stale result", value, false) {+ t.Fatal("invalidated request overwrote the cleared result")+ }+ stale.finish(value, false, errors.New("stale failure"))+ assertCleared(t)+ if !current.save("new result", value, false) || util.GetAssetText(path) != "new result" {+ t.Fatal("finishing an invalidated request canceled a newer request")+ }+ current.finish(value, false, nil)+ })+ t.Run("concurrent clear and commit", func(t *testing.T) {+ for _, automatic := range []bool{false, true} {+ for range 20 {+ util.RemoveAssetText(path)+ value := Conf.GetOCR()+ request := beginOCRRequest(path)+ start := make(chan struct{})+ var wait sync.WaitGroup+ wait.Add(2)+ go func() {+ defer wait.Done()+ <-start+ request.save("in-flight result", value, automatic)+ request.finish(value, automatic, nil)+ }()+ go func() {+ defer wait.Done()+ <-start+ SetOCRAssetText(path, "")+ }()+ close(start)+ wait.Wait()+ assertCleared(t)+ }+ }+ })+ SetOCRAssetText(path, "editedocrkeyword")+ sql.FlushQueue()+}+func testAutomaticOCRUnsupportedLogging(t *testing.T, path string, provider *ocrFixtureProvider) {t.Helper()logPath := filepath.Join(t.TempDir(), "ocr.log")@@ -337,6 +452,16 @@ func testOCRNotebookIsolation(t *testing.T, provider *ocrFixtureProvider, firstBt.Fatalf("unexpected scoped OCR full-text results for %s: %v, %v", keyword, matches, err)}}+ SetOCRAssetText(first+"&width=300#cleared", "")+ documents[1].want, documents[3].want = "", ""+ sql.FlushQueue()+ check()+ for keyword, count := range map[string]int{"changedocrkeyword": 0, "globalocrkeyword": 1, "secondocrkeyword": 1} {+ matches, err := sql.QueryNoLimitArgs("SELECT id FROM blocks_fts WHERE blocks_fts MATCH ?", keyword)+ if err != nil || len(matches) != count {+ t.Fatalf("clearing shared references changed unrelated OCR for %s: %v, %v", keyword, matches, err)+ }+ }provider.err = errors.New("scoped recognition failed")if _, _, err := OCRAsset(context.Background(), first); err == nil {t.Fatal("failed notebook recognition returned success")@@ -348,8 +473,8 @@ func testOCRNotebookIsolation(t *testing.T, provider *ocrFixtureProvider, firstB}util.LoadAssetsTexts()secondText := util.GetOcrJsonText([]map[string]string{{"text": "secondocrkeyword", "conf": "99"}})- for reference, want := range map[string]string{path: "globalocrkeyword", first: "changedocrkeyword", second: secondText} {- if got := util.GetAssetText(reference); got != want {+ for reference, want := range map[string]string{path: "globalocrkeyword", first: "", second: secondText} {+ if got := util.GetAssetText(reference); !util.ExistsAssetText(reference) || got != want {t.Fatalf("scoped OCR result did not survive reload for %s: %q", reference, got)}}diff --git a/kernel/model/ocr_request.go b/kernel/model/ocr_request.gonew file mode 100644index 0000000000..318c2077a2--- /dev/null+++ b/kernel/model/ocr_request.go@@ -0,0 +1,64 @@+package model++import (+ "strings"+ "sync"++ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++var ocrRequests = struct {+ sync.Mutex+ active map[string]*ocrRequest+}{active: map[string]*ocrRequest{}}++// 同一资源的在途请求共用令牌,手动编辑或清空使整组令牌失效,完成后不保留资源状态。+type ocrRequest struct {+ path string+ pending int+}++func beginOCRRequest(path string) *ocrRequest {+ path = util.OCRAssetKey(strings.TrimSpace(path))+ ocrRequests.Lock()+ defer ocrRequests.Unlock()+ request := ocrRequests.active[path]+ if request == nil {+ request = &ocrRequest{path: path}+ ocrRequests.active[path] = request+ }+ request.pending+++ return request+}++func (request *ocrRequest) finish(value conf.OCR, automatic bool, err error) {+ ocrRequests.Lock()+ defer ocrRequests.Unlock()+ request.pending--+ if ocrRequests.active[request.path] != request {+ return+ }+ if !automatic || automaticOCRMatches(value) {+ recordOCRFailure(request.path, err)+ }+ if request.pending == 0 {+ delete(ocrRequests.active, request.path)+ }+}++func (request *ocrRequest) save(text string, value conf.OCR, automatic bool) bool {+ if IsEncryptedOCRAsset(request.path) {+ return false+ }+ ocrRequests.Lock()+ if ocrRequests.active[request.path] != request || automatic && !canSaveAutomaticOCR(value, request.path) {+ ocrRequests.Unlock()+ return false+ }+ util.SetAssetText(request.path, text)+ clearOCRFailure(request.path)+ ocrRequests.Unlock()+ indexOCRAssetText(request.path)+ return true+}