Skip to content

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

:bug: Merge PDF annotation saves with conflict detection https://github.com/siyuan-note/siyuan/issues/20990

Daniel8ca1e1f51c26
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index abae26b970..85631a85cf 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "تعذر حفظ تعليقات PDF التوضيحية. أعد فتح ملف PDF لتحميل أحدث التعليقات قبل متابعة التحرير",
"skipExitSync": "تخطي المزامنة والخروج",
"skipExitSyncConfirm": "لم تكتمل المزامنة. هل تريد تخطيها والخروج؟ ستبقى التغييرات غير المتزامنة محفوظة على هذا الجهاز",
"automationCollectionReference": "هدف المرجع",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 7f25e115e0..18f5e5e2ba 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "PDF-Anmerkungen konnten nicht gespeichert werden. Öffne die PDF erneut, um vor weiteren Änderungen die aktuellen Anmerkungen zu laden",
"skipExitSync": "Synchronisierung überspringen und beenden",
"skipExitSyncConfirm": "Die Synchronisierung ist noch nicht abgeschlossen. Überspringen und beenden? Nicht synchronisierte Änderungen bleiben auf diesem Gerät gespeichert",
"automationCollectionReference": "Referenzziel",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 6cfce1b2f1..fe639f1a8b 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "Unable to save PDF annotations. Reopen the PDF to load the latest annotations before editing again",
"skipExitSync": "Skip sync and exit",
"skipExitSyncConfirm": "Synchronization has not finished. Skip it and exit? Unsynced changes will remain saved on this device",
"automationCollectionReference": "Reference target",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 767dfa0600..2975ebfb0f 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "No se pudieron guardar las anotaciones del PDF. Vuelve a abrir el PDF para cargar las anotaciones más recientes antes de seguir editando",
"skipExitSync": "Omitir sincronización y salir",
"skipExitSyncConfirm": "La sincronización no ha terminado. ¿Omitirla y salir? Los cambios sin sincronizar permanecerán guardados en este dispositivo",
"automationCollectionReference": "Destino de la referencia",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index fd466f6da8..041a1cdd39 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "Impossible d’enregistrer les annotations du PDF. Rouvrez le PDF pour charger les dernières annotations avant de poursuivre les modifications",
"skipExitSync": "Ignorer la synchronisation et quitter",
"skipExitSyncConfirm": "La synchronisation n’est pas terminée. L’ignorer et quitter ? Les modifications non synchronisées resteront enregistrées sur cet appareil",
"automationCollectionReference": "Cible de référence",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index a3f4a82f64..e4ccf2ce3a 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "לא ניתן לשמור את הערות ה-PDF. יש לפתוח מחדש את ה-PDF כדי לטעון את ההערות העדכניות לפני המשך העריכה",
"skipExitSync": "דלג על הסנכרון וצא",
"skipExitSyncConfirm": "הסנכרון עדיין לא הושלם. לדלג עליו ולצאת? השינויים שלא סונכרנו יישארו שמורים במכשיר זה",
"automationCollectionReference": "יעד ההפניה",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 62444164cb..9857daf7da 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "PDF टिप्पणियाँ सहेजी नहीं जा सकीं। दोबारा संपादन करने से पहले नवीनतम टिप्पणियाँ लोड करने के लिए PDF फिर से खोलें",
"skipExitSync": "सिंक छोड़ें और बाहर निकलें",
"skipExitSyncConfirm": "सिंक अभी पूरा नहीं हुआ है। इसे छोड़कर बाहर निकलें? सिंक न किए गए बदलाव इस डिवाइस पर सहेजे रहेंगे",
"automationCollectionReference": "संदर्भ लक्ष्य",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index d131c01b18..c9beff2a7f 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "Anotasi PDF tidak dapat disimpan. Buka kembali PDF untuk memuat anotasi terbaru sebelum melanjutkan penyuntingan",
"skipExitSync": "Lewati sinkronisasi dan keluar",
"skipExitSyncConfirm": "Sinkronisasi belum selesai. Lewati dan keluar? Perubahan yang belum disinkronkan akan tetap tersimpan di perangkat ini",
"automationCollectionReference": "Tujuan referensi",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index ed168a66e6..a10e510c28 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "Impossibile salvare le annotazioni PDF. Riapri il PDF per caricare le annotazioni più recenti prima di continuare a modificare",
"skipExitSync": "Salta la sincronizzazione ed esci",
"skipExitSyncConfirm": "La sincronizzazione non è terminata. Saltarla e uscire? Le modifiche non sincronizzate rimarranno salvate su questo dispositivo",
"automationCollectionReference": "Destinazione del riferimento",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index d9f8a51cb0..03bcc619b1 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "PDF の注釈を保存できませんでした。編集を続ける前に PDF を開き直して最新の注釈を読み込んでください",
"skipExitSync": "同期をスキップして終了",
"skipExitSyncConfirm": "同期が完了していません。スキップして終了しますか?未同期の変更はこの端末に保存されたままになります",
"automationCollectionReference": "参照先",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index c63fa96b62..fdde26cc31 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "PDF 주석을 저장할 수 없습니다. 다시 편집하기 전에 PDF를 다시 열어 최신 주석을 불러오세요",
"skipExitSync": "동기화를 건너뛰고 종료",
"skipExitSyncConfirm": "동기화가 완료되지 않았습니다. 건너뛰고 종료할까요? 동기화되지 않은 변경 사항은 이 기기에 저장된 상태로 유지됩니다",
"automationCollectionReference": "참조 대상",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 2b7b9ab6b1..9f5076a633 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "PDF-annotaties kunnen niet worden opgeslagen. Open de PDF opnieuw om de nieuwste annotaties te laden voordat je verder bewerkt",
"skipExitSync": "Synchronisatie overslaan en afsluiten",
"skipExitSyncConfirm": "De synchronisatie is nog niet voltooid. Overslaan en afsluiten? Niet-gesynchroniseerde wijzigingen blijven op dit apparaat opgeslagen",
"automationCollectionReference": "Verwijzingsdoel",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index f58a9792d1..3f1978bd07 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "Nie można zapisać adnotacji PDF. Otwórz ponownie plik PDF, aby wczytać najnowsze adnotacje przed dalszą edycją",
"skipExitSync": "Pomiń synchronizację i wyjdź",
"skipExitSyncConfirm": "Synchronizacja nie została zakończona. Pominąć ją i wyjść? Niezsynchronizowane zmiany pozostaną zapisane na tym urządzeniu",
"automationCollectionReference": "Cel odwołania",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 8700cf7c20..9b43c6f42d 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "Não foi possível salvar as anotações do PDF. Reabra o PDF para carregar as anotações mais recentes antes de continuar editando",
"skipExitSync": "Ignorar sincronização e sair",
"skipExitSyncConfirm": "A sincronização não terminou. Ignorar e sair? As alterações não sincronizadas permanecerão salvas neste dispositivo",
"automationCollectionReference": "Destino da referência",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index c52209ce5a..a7455c8a31 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "Не удалось сохранить аннотации PDF. Откройте PDF заново, чтобы загрузить последние аннотации перед дальнейшим редактированием",
"skipExitSync": "Пропустить синхронизацию и выйти",
"skipExitSyncConfirm": "Синхронизация ещё не завершена. Пропустить её и выйти? Несинхронизированные изменения останутся сохранёнными на этом устройстве",
"automationCollectionReference": "Цель ссылки",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 13f4855dc8..ac7a399e5f 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "Anotácie PDF sa nepodarilo uložiť. Pred ďalšími úpravami znova otvorte PDF a načítajte najnovšie anotácie",
"skipExitSync": "Preskočiť synchronizáciu a skončiť",
"skipExitSyncConfirm": "Synchronizácia sa ešte neskončila. Preskočiť ju a skončiť? Nesynchronizované zmeny zostanú uložené v tomto zariadení",
"automationCollectionReference": "Cieľ odkazu",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index e09d7b0761..f5d0acbda5 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "Није могуће сачувати PDF напомене. Поново отворите PDF да бисте учитали најновије напомене пре даљег уређивања",
"skipExitSync": "Прескочи синхронизацију и изађи",
"skipExitSyncConfirm": "Синхронизација није завршена. Прескочити је и изаћи? Несинхронизоване измене остаће сачуване на овом уређају",
"automationCollectionReference": "Циљ референце",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 290fe94bfa..c9b2eee4d3 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "ไม่สามารถบันทึกคำอธิบายประกอบ PDF ได้ โปรดเปิด PDF ใหม่เพื่อโหลดคำอธิบายประกอบล่าสุดก่อนแก้ไขต่อ",
"skipExitSync": "ข้ามการซิงค์และออก",
"skipExitSyncConfirm": "การซิงค์ยังไม่เสร็จสิ้น ต้องการข้ามและออกหรือไม่? การเปลี่ยนแปลงที่ยังไม่ได้ซิงค์จะยังคงบันทึกอยู่ในอุปกรณ์นี้",
"automationCollectionReference": "เป้าหมายการอ้างอิง",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 315341e737..18119f5665 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "PDF açıklamaları kaydedilemedi. Düzenlemeye devam etmeden önce en son açıklamaları yüklemek için PDF dosyasını yeniden açın",
"skipExitSync": "Eşitlemeyi atla ve çık",
"skipExitSyncConfirm": "Eşitleme henüz tamamlanmadı. Atlayıp çıkılsın mı? Eşitlenmemiş değişiklikler bu cihazda kayıtlı kalacak",
"automationCollectionReference": "Başvuru hedefi",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 6bb041822a..ad1b44125a 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "Не вдалося зберегти анотації PDF. Відкрийте PDF знову, щоб завантажити останні анотації перед подальшим редагуванням",
"skipExitSync": "Пропустити синхронізацію та вийти",
"skipExitSyncConfirm": "Синхронізацію ще не завершено. Пропустити її та вийти? Несинхронізовані зміни залишаться збереженими на цьому пристрої",
"automationCollectionReference": "Ціль посилання",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index fbd58eb723..d24fe0dc32 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "无法保存 PDF 标注,请重新打开 PDF 加载最新标注后再编辑",
"skipExitSync": "跳过同步并退出",
"skipExitSyncConfirm": "同步尚未完成,是否跳过本次同步并退出?未同步的更改会保留在本机",
"automationCollectionReference": "引用目标",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 37b49d5577..c9da9cc585 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,5 @@
{
+ "pdfAnnotationSaveFailed": "無法儲存 PDF 標註,請重新開啟 PDF 載入最新標註後再編輯",
"skipExitSync": "略過同步並結束",
"skipExitSyncConfirm": "同步尚未完成,是否略過本次同步並結束?未同步的變更會保留在本機",
"automationCollectionReference": "引用目標",
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20210127203829-qe2mzof.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20210127203829-qe2mzof.sy
index 02c180047f..977b0eb29e 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20210127203829-qe2mzof.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20210127203829-qe2mzof.sy
@@ -6,7 +6,7 @@
"id": "20210127203829-qe2mzof",
"title": "PDF annotation",
"type": "doc",
- "updated": "20260614112547"
+ "updated": "20261027103930"
},
"Children": [
{
@@ -15,7 +15,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260614112546-8xr6fj9",
- "updated": "20260614112546"
+ "updated": "20261027103930"
},
"Children": [
{
@@ -38,6 +38,20 @@
}
]
},
+ {
+ "ID": "20261027103930-m3bd0w0",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261027103930-m3bd0w0",
+ "updated": "20261027103930"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "When the same PDF is open in multiple viewers, saves merge changes to different annotations. If another viewer has already changed or deleted the same annotation, an outdated save is rejected and a message asks you to reopen the PDF. Check and copy any unsaved changes you need, then reopen the PDF to load the latest annotations before editing again."
+ }
+ ]
+ },
{
"ID": "20260614112546-0nfcwzb",
"Type": "NodeHeading",
@@ -542,7 +556,7 @@
{
"Type": "NodeTextMark",
"TextMarkType": "code",
- "TextMarkTextContent": "\u0026lt;\u0026lt;assets/xxx.pdf/annotationID \"selected text\"\u0026gt;\u0026gt;"
+ "TextMarkTextContent": "<<assets/xxx.pdf/annotationID \"selected text\">>"
},
{
"Type": "NodeText",
@@ -643,4 +657,4 @@
}
}
]
-}
\ No newline at end of file
+}
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20210127202655-2334vvv.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20210127202655-2334vvv.sy
index 4e621a645b..af72727fc7 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20210127202655-2334vvv.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20210127202655-2334vvv.sy
@@ -6,7 +6,7 @@
"id": "20210127202655-2334vvv",
"title": "PDF 标注",
"type": "doc",
- "updated": "20260614112550"
+ "updated": "20261027103930"
},
"Children": [
{
@@ -15,7 +15,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260614112525-7f8cngf",
- "updated": "20260614112525"
+ "updated": "20261027103930"
},
"Children": [
{
@@ -38,6 +38,20 @@
}
]
},
+ {
+ "ID": "20261027103930-yptymdx",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261027103930-yptymdx",
+ "updated": "20261027103930"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "在多个查看器中打开同一 PDF 时,对不同标注的修改会在保存时合并。如果同一条标注已被其他查看器修改或删除,过期保存会被拒绝,并提示重新打开 PDF。请先检查并复制需要保留的未保存修改,再重新打开 PDF 加载最新标注后继续编辑。"
+ }
+ ]
+ },
{
"ID": "20260614112525-phcs46z",
"Type": "NodeHeading",
@@ -542,7 +556,7 @@
{
"Type": "NodeTextMark",
"TextMarkType": "code",
- "TextMarkTextContent": "\u0026lt;\u0026lt;assets/xxx.pdf/标注ID \"选中内容\"\u0026gt;\u0026gt;"
+ "TextMarkTextContent": "<<assets/xxx.pdf/标注ID \"选中内容\">>"
},
{
"Type": "NodeText",
@@ -643,4 +657,4 @@
}
}
]
-}
\ No newline at end of file
+}
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122943-st7fpcj.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122943-st7fpcj.sy
index 13cd854546..29580eed8c 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122943-st7fpcj.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122943-st7fpcj.sy
@@ -6,7 +6,7 @@
"id": "20211226122943-st7fpcj",
"title": "PDF 標注",
"type": "doc",
- "updated": "20260614112631"
+ "updated": "20261027103930"
},
"Children": [
{
@@ -15,7 +15,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260614112630-wl3an62",
- "updated": "20260614112630"
+ "updated": "20261027103930"
},
"Children": [
{
@@ -38,6 +38,20 @@
}
]
},
+ {
+ "ID": "20261027103930-cfww159",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261027103930-cfww159",
+ "updated": "20261027103930"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "在多個檢視器中開啟同一 PDF 時,對不同標註的修改會在儲存時合併。如果同一條標註已被其他檢視器修改或刪除,過期儲存會被拒絕,並提示重新開啟 PDF。請先檢查並複製需要保留的未儲存修改,再重新開啟 PDF 載入最新標註後繼續編輯。"
+ }
+ ]
+ },
{
"ID": "20260614112630-v4stv84",
"Type": "NodeHeading",
@@ -542,7 +556,7 @@
{
"Type": "NodeTextMark",
"TextMarkType": "code",
- "TextMarkTextContent": "\u0026lt;\u0026lt;assets/xxx.pdf/標註ID \"選取內容\"\u0026gt;\u0026gt;"
+ "TextMarkTextContent": "<<assets/xxx.pdf/標註ID \"選取內容\">>"
},
{
"Type": "NodeText",
@@ -643,4 +657,4 @@
}
}
]
-}
\ No newline at end of file
+}
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-to5uvpi.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-to5uvpi.sy
index 76b780e38e..d2d5c336f1 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-to5uvpi.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-to5uvpi.sy
@@ -7,7 +7,7 @@
"id": "20240530101000-to5uvpi",
"title": "PDF 注釈",
"type": "doc",
- "updated": "20260614112612"
+ "updated": "20261027103930"
},
"Children": [
{
@@ -16,7 +16,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20260614112611-ydoehak",
- "updated": "20260614112611"
+ "updated": "20261027103930"
},
"Children": [
{
@@ -39,6 +39,20 @@
}
]
},
+ {
+ "ID": "20261027103930-tbpnc0f",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261027103930-tbpnc0f",
+ "updated": "20261027103930"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "同じ PDF を複数のビューアーで開いている場合、異なる注釈への変更は保存時に統合されます。同じ注釈が別のビューアーですでに変更または削除されていると、古い状態に基づく保存は拒否され、PDF を開き直すよう表示されます。必要な未保存の変更を確認してコピーしてから、PDF を開き直して最新の注釈を読み込み、編集を続けてください。"
+ }
+ ]
+ },
{
"ID": "20260614112611-gzxk32l",
"Type": "NodeHeading",
@@ -543,7 +557,7 @@
{
"Type": "NodeTextMark",
"TextMarkType": "code",
- "TextMarkTextContent": "\u0026lt;\u0026lt;assets/xxx.pdf/注釈ID \"選択テキスト\"\u0026gt;\u0026gt;"
+ "TextMarkTextContent": "<<assets/xxx.pdf/注釈ID \"選択テキスト\">>"
},
{
"Type": "NodeText",
@@ -644,4 +658,4 @@
}
}
]
-}
\ No newline at end of file
+}
diff --git a/app/src/asset/anno.ts b/app/src/asset/anno.ts
index 66b55a8be0..6194825a7d 100644
--- a/app/src/asset/anno.ts
+++ b/app/src/asset/anno.ts
@@ -1,4 +1,4 @@
-import {fetchPost} from "../util/fetch";
+import {fetchPost, fetchSyncPost} from "../util/fetch";
import {setPosition} from "../util/setPosition";
import {hasClosestByAttribute, hasClosestByClassName} from "../protyle/util/hasClosest";
import {readText, writeText} from "../protyle/util/compatibility";
@@ -37,11 +37,30 @@ import {appendPdfAnnotationId} from "../editor/pdfAssetLink";
import {isPdfRectAnnotation, mergePdfTextAnnotationRects} from "./pdfTextAnnotation";
import {pdfRectToViewport} from "./pdfCoordinates";
import {getPdfSelectionText} from "./pdfSelectionText";
+import {AnnotationSaveQueue} from "./annotationSave";
export {destroyAnno, registerPdfInstance, unregisterPdfInstance} from "./annoRuntime";
const RECT_RESIZE_MIN_SIZE = 8;
const rectCopyRequests = new WeakMap<HTMLElement, object>();
+const annotationSaveQueues = new WeakMap<object, {file: string; queue: AnnotationSaveQueue}>();
+
+const getAnnotationSaveQueue = (pdf: any, config: Record<string, IPdfAnno>) => {
+ const file = pdf.appConfig.file;
+ let state = annotationSaveQueues.get(pdf);
+ if (!state || state.file !== file) {
+ state = {file, queue: new AnnotationSaveQueue(JSON.stringify(config), (baseData, data) =>
+ fetchSyncPost("/api/asset/setFileAnnotation", {
+ path: file.replace(location.origin, "").substr(1) + ".sya", baseData, data,
+ }), () => showMessage(window.siyuan.languages.pdfAnnotationSaveFailed, 0, "error"))};
+ annotationSaveQueues.set(pdf, state);
+ }
+ return state.queue;
+};
+
+const saveConfig = (pdf: any, config: Record<string, IPdfAnno>) => {
+ void getAnnotationSaveQueue(pdf, config).save(JSON.stringify(config));
+};
export const initAnno = (element: HTMLElement, pdf: any) => {
destroyAnno(element);
@@ -317,10 +336,7 @@ export const initAnno = (element: HTMLElement, pdf: any) => {
pageItem.positions = [position];
annoItem.mode = "rect";
target.dataset.mode = "rect";
- fetchPost("/api/asset/setFileAnnotation", {
- path: pdf.appConfig.file.replace(location.origin, "").substr(1) + ".sya",
- data: JSON.stringify(config),
- });
+ saveConfig(pdf, config);
hideToolbarMenu(element);
copyAnno(appendPdfAnnotationId(pdf.appConfig.file.replace(location.origin, "").substr(1), id),
"", pdf, target, true);
@@ -420,10 +436,7 @@ export const initAnno = (element: HTMLElement, pdf: any) => {
getRectElementsByNodeId(element, rectElement.getAttribute("data-node-id")).forEach(rectItem => {
rectItem.style.setProperty("--pdf-annotation-color", color);
});
- fetchPost("/api/asset/setFileAnnotation", {
- path: pdf.appConfig.file.replace(location.origin, "").substr(1) + ".sya",
- data: JSON.stringify(config),
- });
+ saveConfig(pdf, config);
} else {
const coords = getHightlightCoordsByRange(pdf, color);
if (coords) {
@@ -484,10 +497,7 @@ export const initAnno = (element: HTMLElement, pdf: any) => {
getRectElementsByNodeId(element, rectElement.getAttribute("data-node-id")).forEach(rectItem => {
rectItem.dataset.type = annoItem.type;
});
- fetchPost("/api/asset/setFileAnnotation", {
- path: pdf.appConfig.file.replace(location.origin, "").substr(1) + ".sya",
- data: JSON.stringify(config),
- });
+ saveConfig(pdf, config);
event.preventDefault();
event.stopPropagation();
processed = true;
@@ -584,10 +594,7 @@ const setRelation = (pdf: any) => {
};
const updateRelation = (pdf: any, config: any) => {
- fetchPost("/api/asset/setFileAnnotation", {
- path: pdf.appConfig.file.replace(location.origin, "").substr(1) + ".sya",
- data: JSON.stringify(config),
- });
+ saveConfig(pdf, config);
};
const inputElement = dialog.element.querySelector(".b3-text-field") as HTMLInputElement;
@@ -1154,7 +1161,6 @@ async function getRectImgData(pdfObj: any, pageNumber: number, position: number[
const removeAnno = (pdf: any, element: HTMLElement, id: string) => {
const file = pdf.appConfig.file;
- const urlPath = file.replace(location.origin, "").substr(1);
const isCurrent = () => element.isConnected && getRegisteredPdfInstance(element) === pdf && pdf.appConfig.file === file;
const remove = () => {
if (!isCurrent()) {
@@ -1168,10 +1174,7 @@ const removeAnno = (pdf: any, element: HTMLElement, id: string) => {
getRectElementsByNodeId(element, id).forEach(item => {
item.remove();
});
- fetchPost("/api/asset/setFileAnnotation", {
- path: urlPath + ".sya",
- data: JSON.stringify(config),
- });
+ saveConfig(pdf, config);
};
fetchPost("/api/block/getRefIDsByFileAnnotationID", {
id,
@@ -1194,28 +1197,36 @@ const removeAnno = (pdf: any, element: HTMLElement, id: string) => {
const setConfig = (pdf: any, id: string, data: IPdfAnno) => {
const config = getConfig(pdf);
config[id] = data;
- fetchPost("/api/asset/setFileAnnotation", {
- path: pdf.appConfig.file.replace(location.origin, "").substr(1) + ".sya",
- data: JSON.stringify(config),
- });
+ saveConfig(pdf, config);
};
const getConfig = (pdf: any) => {
if (pdf.appConfig.config) {
+ getAnnotationSaveQueue(pdf, pdf.appConfig.config);
return pdf.appConfig.config;
}
- const urlPath = pdf.appConfig.file.replace(location.origin, "").substr(1) + ".sya";
+ const file = pdf.appConfig.file;
+ const urlPath = file.replace(location.origin, "").substr(1) + ".sya";
fetchPost("/api/asset/getFileAnnotation", {
path: urlPath,
}, (response) => {
- let config = {};
+ if (pdf.appConfig.file !== file || pdf.appConfig.config || (response.code !== 0 && response.code !== 1)) {
+ return;
+ }
+ let config: Record<string, IPdfAnno> = {};
if (response.code === 0) {
try {
config = JSON.parse(response.data.data);
} catch (e) {
- config = {};
+ showMessage(window.siyuan.languages.pdfAnnotationSaveFailed, 0, "error");
+ return;
}
}
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
+ showMessage(window.siyuan.languages.pdfAnnotationSaveFailed, 0, "error");
+ return;
+ }
pdf.appConfig.config = config;
+ getAnnotationSaveQueue(pdf, config);
});
};
diff --git a/app/src/asset/annotationSave.test.ts b/app/src/asset/annotationSave.test.ts
new file mode 100644
index 0000000000..30357333cf
--- /dev/null
+++ b/app/src/asset/annotationSave.test.ts
@@ -0,0 +1,44 @@
+import assert from "node:assert/strict";
+import {test} from "node:test";
+import {AnnotationSaveQueue} from "./annotationSave";
+
+test("viewer saves are serialized and advance the baseline only after confirmation", async () => {
+ const requests: Array<{base: string; data: string}> = [];
+ let release: () => void;
+ const first = new Promise<void>(resolve => { release = resolve; });
+ const queue = new AnnotationSaveQueue("{}", async (base, data) => {
+ requests.push({base, data});
+ if (requests.length === 1) await first;
+ return {code: 0, msg: ""};
+ }, () => assert.fail("save should succeed"));
+ const saving = queue.save('{"a":1}');
+ const second = queue.save('{"a":2,"b":1}');
+ await Promise.resolve();
+ assert.deepEqual(requests, [{base: "{}", data: '{"a":1}'}]);
+ release();
+ await Promise.all([saving, second]);
+ assert.deepEqual(requests[1], {base: '{"a":1}', data: '{"a":2,"b":1}'});
+});
+
+test("conflicts and unconfirmed network failures stop queued saves until the viewer is reopened", async () => {
+ for (const failure of ["conflict", "network"]) {
+ const requests: string[] = [], messages: string[] = [];
+ const queue = new AnnotationSaveQueue('{"a":1}', async base => {
+ requests.push(base);
+ if (failure === "network") throw new Error("connection closed");
+ return {code: -1, msg: "annotation revision conflict"};
+ }, message => messages.push(message));
+ await Promise.all([queue.save('{"a":2}'), queue.save("{}")]);
+ assert.equal(messages.length, 1);
+ await queue.save('{"b":1}');
+ assert.deepEqual(requests, ['{"a":1}']);
+ assert.equal(messages.length, 2, "later edits must repeat the reload prompt without sending another save");
+ let reopenedBase: string;
+ const reopened = new AnnotationSaveQueue('{"a":3}', async base => {
+ reopenedBase = base;
+ return {code: 0, msg: ""};
+ }, () => assert.fail("reopened viewer should save"));
+ await reopened.save('{"a":4}');
+ assert.equal(reopenedBase, '{"a":3}');
+ }
+});
diff --git a/app/src/asset/annotationSave.ts b/app/src/asset/annotationSave.ts
new file mode 100644
index 0000000000..b8e2f08fc5
--- /dev/null
+++ b/app/src/asset/annotationSave.ts
@@ -0,0 +1,34 @@
+// Each viewer advances its own baseline only after a confirmed save. The server
+// merges changes to other annotations; serializing saves preserves local order.
+export class AnnotationSaveQueue {
+ private pending = Promise.resolve();
+ private failed = false;
+ private failureMessage = "";
+
+ constructor(private baseData: string,
+ private persist: (baseData: string, data: string) => Promise<{code: number; msg: string}>,
+ private reportFailure: (message: string) => void) {
+ }
+
+ save(data: string): Promise<void> {
+ if (this.failed) {
+ this.reportFailure(this.failureMessage);
+ return Promise.resolve();
+ }
+ this.pending = this.pending.then(async () => {
+ if (this.failed) {
+ return;
+ }
+ const response = await this.persist(this.baseData, data);
+ if (response.code !== 0) {
+ throw new Error(response.msg);
+ }
+ this.baseData = data;
+ }).catch(error => {
+ this.failed = true;
+ this.failureMessage = error.message;
+ this.reportFailure(error.message);
+ });
+ return this.pending;
+ }
+}
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 722fdead8c..2227ab94fb 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -1978,7 +1978,7 @@ export type SetAIRequestInput = { "agent"?: SettingAgentInput | null; "decision"
export type SetAppearanceRequestInput = { "bodyGradient"?: SettingBodyGradientInput | null; "closeButtonBehavior"?: number | null; "codeBlockThemeDark"?: string | null; "codeBlockThemeLight"?: string | null; "compactMode"?: boolean | null; "darkThemes"?: Array<SettingAppearanceThemeInput | null> | null; "entryVisibility"?: SettingEntryVisibilityInput | null; "globalFontFamilies"?: Array<SettingEditorFontInput | null> | null; "hideStatusBar"?: boolean | null; "hideToolbar"?: boolean | null; "icon"?: string | null; "iconVer"?: string | null; "icons"?: Array<SettingAppearanceIconInput | null> | null; "lang"?: string | null; "lightThemes"?: Array<SettingAppearanceThemeInput | null> | null; "lockScreenWallpaper"?: boolean | null; "menuMouseScroll"?: boolean | null; "mobileBars"?: SettingMobileBarsInput | null; "mode"?: number | null; "modeOS"?: boolean | null; "notifications"?: SettingNotificationsInput | null; "outlineKeepCurrentExpand"?: boolean | null; "pdfTheme"?: SettingPDFThemeInput | null; "statusBar"?: SettingStatusBarInput | null; "themeDark"?: string | null; "themeJS"?: boolean | null; "themeLight"?: string | null; "themeVer"?: string | null; };
-export type SetAssetAnnotationRequestInput = { "data": string; "path": string; };
+export type SetAssetAnnotationRequestInput = { "baseData"?: string | null; "data": string; "path": string; };
export type SetAssetOCRTextRequestInput = { "path": string; "text": string; };
@@ -3669,6 +3669,12 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin"];
};
+ /**
+ * 保存 PDF 标注映射。省略 baseData 或传 null 保持旧版整份替换语义。
+ * 提供 baseData 时,将 data 相对该读取基线的逐条变化合并到当前映射,保留其他查看器对不同标注的修改。
+ * 同一标注已被不同内容修改或删除时返回 -1 / "annotation revision conflict",不写入文件;重复的相同结果可成功。
+ * 基线和 data 必须为 JSON 对象字符串;加密笔记本先认证当前密文,租约和文件格式保持不变。
+ */
"/api/asset/setFileAnnotation": {
request: SetAssetAnnotationRequestInput;
response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
diff --git a/app/tests/annoSave.test.js b/app/tests/annoSave.test.js
new file mode 100644
index 0000000000..41d44182cc
--- /dev/null
+++ b/app/tests/annoSave.test.js
@@ -0,0 +1,65 @@
+const assert = require("node:assert/strict");
+const {readFileSync} = require("node:fs");
+const {test} = require("node:test");
+const {runInNewContext} = require("node:vm");
+const ts = require("typescript");
+
+const source = ts.createSourceFile("anno.ts", readFileSync("src/asset/anno.ts", "utf8"), ts.ScriptTarget.ES2021, true);
+const names = new Set(["annotationSaveQueues", "getAnnotationSaveQueue", "saveConfig", "getConfig", "setConfig"]);
+const code = source.statements.filter(statement => ts.isVariableStatement(statement) &&
+ statement.declarationList.declarations.some(item => names.has(item.name.getText(source))))
+ .map(statement => statement.getText(source)).join("\n");
+const transpile = text => ts.transpileModule(text, {compilerOptions: {target: ts.ScriptTarget.ES2021, module: ts.ModuleKind.CommonJS}}).outputText;
+const queueExports = {};
+new Function("exports", transpile(readFileSync("src/asset/annotationSave.ts", "utf8")))(queueExports);
+
+const setup = config => {
+ const requests = [], reads = [], messages = [];
+ const pdf = {appConfig: {file: "http://localhost/assets/document.pdf?box=20261003000000-abcdefg", config}};
+ const api = runInNewContext(transpile(code + "\n({getConfig, setConfig});"), {
+ AnnotationSaveQueue: queueExports.AnnotationSaveQueue,
+ location: {origin: "http://localhost"},
+ window: {siyuan: {languages: {pdfAnnotationSaveFailed: "Reopen the PDF"}}},
+ showMessage: message => messages.push(message),
+ fetchPost: (url, data, callback) => reads.push({url, data, callback}),
+ fetchSyncPost: async (url, data) => { requests.push({url, data}); return {code: 0, msg: ""}; },
+ });
+ return {api, pdf, requests, reads, messages};
+};
+
+test("annotation saves keep the pre-edit baseline and notebook-qualified path", async () => {
+ const state = setup({old: {content: "original"}});
+ state.api.setConfig(state.pdf, "new", {content: "addition"});
+ await new Promise(resolve => setImmediate(resolve));
+ const request = state.requests[0];
+ assert.equal(request.url, "/api/asset/setFileAnnotation");
+ assert.equal(request.data.path, "assets/document.pdf?box=20261003000000-abcdefg.sya");
+ assert.deepEqual(JSON.parse(request.data.baseData), {old: {content: "original"}});
+ assert.deepEqual(JSON.parse(request.data.data), {old: {content: "original"}, new: {content: "addition"}});
+});
+
+test("loaded snapshots initialize the baseline, while stale or invalid reads cannot replace local state", async () => {
+ const state = setup(undefined);
+ state.api.getConfig(state.pdf);
+ const read = state.reads[0];
+ assert.equal(read.data.path, "assets/document.pdf?box=20261003000000-abcdefg.sya");
+ read.callback({code: 0, data: {data: '{"old":{"content":"loaded"}}'}});
+ state.api.setConfig(state.pdf, "new", {content: "new"});
+ read.callback({code: 0, data: {data: "{}"}});
+ await new Promise(resolve => setImmediate(resolve));
+ assert.equal(state.pdf.appConfig.config.old.content, "loaded");
+ assert.deepEqual(JSON.parse(state.requests[0].data.baseData), {old: {content: "loaded"}});
+ for (const raw of ["broken", "null", "[]"]) {
+ const invalid = setup(undefined);
+ invalid.api.getConfig(invalid.pdf);
+ invalid.reads[0].callback({code: 0, data: {data: raw}});
+ assert.equal(invalid.pdf.appConfig.config, undefined);
+ assert.equal(invalid.messages.length, 1);
+ assert.equal(invalid.requests.length, 0);
+ }
+ const replaced = setup(undefined);
+ replaced.api.getConfig(replaced.pdf);
+ replaced.pdf.appConfig.file = "http://localhost/assets/other.pdf";
+ replaced.reads[0].callback({code: 0, data: {data: "{}"}});
+ assert.equal(replaced.pdf.appConfig.config, undefined);
+});
diff --git a/app/tests/pdfAnnotationDelete.test.js b/app/tests/pdfAnnotationDelete.test.js
index 8d1fd091a5..66061c5417 100644
--- a/app/tests/pdfAnnotationDelete.test.js
+++ b/app/tests/pdfAnnotationDelete.test.js
@@ -14,6 +14,7 @@ const code = ts.transpileModule(declaration.getText(source) + "\nremoveAnno;", {
const setup = (file = "http://localhost/assets/document.pdf") => {
const requests = [];
const confirmations = [];
+ const saves = [];
const config = {annotation: {page: 1}, other: {page: 2}};
const pdf = {appConfig: {file, config}};
const element = {isConnected: true};
@@ -25,6 +26,7 @@ const setup = (file = "http://localhost/assets/document.pdf") => {
window: {siyuan: {languages: {deleteOpConfirm: "Delete", pdfAnnotationDeleteRefConfirm: "Referenced by ${x} blocks"}}},
getRegisteredPdfInstance: () => registered,
getConfig: () => config,
+ saveConfig: (owner, data) => { assert.equal(owner, pdf); saves.push(JSON.parse(JSON.stringify(data))); },
getRectElementsByNodeId: (owner, id) => {
assert.equal(owner, element);
assert.equal(id, "annotation");
@@ -34,7 +36,7 @@ const setup = (file = "http://localhost/assets/document.pdf") => {
confirmDialog: (title, text, confirm, cancel, isDelete) => { confirmations.push({title, text, confirm, cancel, isDelete}); },
});
removeAnno(pdf, element, "annotation");
- return {requests, confirmations, config, pdf, element, removed: () => removed, replaceViewer: () => { registered = {}; }};
+ return {requests, confirmations, saves, config, pdf, element, removed: () => removed, replaceViewer: () => { registered = {}; }};
};
test("referenced PDF annotations remain intact until deletion is confirmed", () => {
@@ -55,10 +57,8 @@ test("referenced PDF annotations remain intact until deletion is confirmed", ()
confirmation.confirm();
assert.equal(state.removed(), 1);
assert.equal(state.config.annotation, undefined);
- const save = state.requests[1];
- assert.equal(save.url, "/api/asset/setFileAnnotation");
- assert.equal(save.data.path, "assets/document.pdf?box=20261003000000-abcdefg.sya");
- assert.deepEqual(JSON.parse(save.data.data), {other: {page: 2}, latest: {page: 3}});
+ assert.equal(state.requests.length, 1);
+ assert.deepEqual(state.saves, [{other: {page: 2}, latest: {page: 3}}]);
});
test("unreferenced PDF annotations are deleted without a confirmation", () => {
@@ -67,7 +67,7 @@ test("unreferenced PDF annotations are deleted without a confirmation", () => {
state.requests[0].callback({code: 0, data: {refDefs: []}});
assert.equal(state.confirmations.length, 0);
assert.equal(state.removed(), 1);
- assert.equal(state.requests[1].data.path, "assets/document.pdf.sya");
+ assert.deepEqual(state.saves, [{other: {page: 2}}]);
});
test("a failed reference query preserves PDF annotations", () => {
@@ -76,6 +76,7 @@ test("a failed reference query preserves PDF annotations", () => {
assert.equal(state.requests.length, 1);
assert.ok(state.config.annotation);
assert.equal(state.removed(), 0);
+ assert.equal(state.saves.length, 0);
});
test("closing or replacing the PDF viewer prevents delayed annotation deletion", () => {
@@ -86,11 +87,13 @@ test("closing or replacing the PDF viewer prevents delayed annotation deletion",
pending.requests[0].callback({code: 0, data: {refDefs: []}});
assert.equal(pending.removed(), 0);
assert.equal(pending.requests.length, 1);
+ assert.equal(pending.saves.length, 0);
const confirmed = setup();
confirmed.requests[0].callback({code: 0, data: {refDefs: [{refID: "block"}]}});
invalidate(confirmed);
confirmed.confirmations[0].confirm();
assert.equal(confirmed.removed(), 0);
assert.ok(confirmed.config.annotation);
+ assert.equal(confirmed.saves.length, 0);
}
});
diff --git a/app/tests/pdfViewerBundle.cjs b/app/tests/pdfViewerBundle.cjs
index c2e8cace86..b949e80445 100644
--- a/app/tests/pdfViewerBundle.cjs
+++ b/app/tests/pdfViewerBundle.cjs
@@ -19,8 +19,12 @@ module.exports = async ({annotations = false} = {}) => {
}
const annotationMocks = {
"../util/fetch": `export const fetchPost = (url, data, callback) => {
- if (url.endsWith('/setFileAnnotation')) window.pdfSavedAnnotations = JSON.parse(data.data);
callback?.({code: 0, data: {data: JSON.stringify(window.pdfSavedAnnotations || {})}});
+ };
+ export const fetchSyncPost = async (url, data) => {
+ if (typeof data.baseData !== 'string') throw new Error('Missing annotation save baseline');
+ if (url.endsWith('/setFileAnnotation')) window.pdfSavedAnnotations = JSON.parse(data.data);
+ return {code: 0, msg: '', data: null};
};`,
"../layout/getAll": "export const getAllModels = () => ({asset: []});",
"../protyle/util/compatibility": "export const readText = async () => ''; export const writeText = text => {window.pdfCopiedText = text;};",
diff --git a/kernel/api/asset.go b/kernel/api/asset.go
index 6b2a0fa4c6..ca56df122e 100644
--- a/kernel/api/asset.go
+++ b/kernel/api/asset.go
@@ -231,8 +231,21 @@ var setFileAnnotation = contractHandler(apicontract.SetFileAnnotation, func(c *g
if err = holdEncryptedBoxRequest(c, boxID); err != nil {
return apicontract.Failure[apicontract.Null](-1, err.Error())
}
+ fileAnnotationMu.Lock()
+ defer fileAnnotationMu.Unlock()
+ if request.BaseData != nil {
+ merged, mergeErr := mergeFileAnnotations(writePath, boxID, *request.BaseData, data)
+ if mergeErr != nil {
+ return apicontract.Failure[apicontract.Null](-1, mergeErr.Error())
+ }
+ normalized, marshalErr := json.Marshal(merged)
+ if marshalErr != nil {
+ return apicontract.Failure[apicontract.Null](-1, marshalErr.Error())
+ }
+ data = string(normalized)
+ }
if "{}" == data {
- if err = filelock.Remove(writePath); err != nil {
+ if err = filelock.Remove(writePath); err != nil && !(request.BaseData != nil && os.IsNotExist(err)) {
return apicontract.Failure[apicontract.Null](-1, err.Error())
}
} else {
@@ -285,13 +298,15 @@ var getFileAnnotation = contractHandler(apicontract.GetFileAnnotation, func(c *g
return apicontract.Failure[apicontract.AssetAnnotationData](http.StatusForbidden, http.StatusText(http.StatusForbidden))
}
}
- if !filelock.IsExist(readPath) {
- return apicontract.Failure[apicontract.AssetAnnotationData](1, "")
- }
boxID := model.ExtractBoxIDFromAssetsPath(readPath)
if err = holdEncryptedBoxRequest(c, boxID); err != nil {
return apicontract.Failure[apicontract.AssetAnnotationData](-1, err.Error())
}
+ fileAnnotationMu.Lock()
+ defer fileAnnotationMu.Unlock()
+ if !filelock.IsExist(readPath) {
+ return apicontract.Failure[apicontract.AssetAnnotationData](1, "")
+ }
data, err := filelock.ReadFile(readPath)
if err != nil {
diff --git a/kernel/api/asset_annotation.go b/kernel/api/asset_annotation.go
new file mode 100644
index 0000000000..1a656b5b53
--- /dev/null
+++ b/kernel/api/asset_annotation.go
@@ -0,0 +1,92 @@
+package api
+
+import (
+ "encoding/json"
+ "errors"
+ "os"
+ "path/filepath"
+ "reflect"
+ "sync"
+
+ "github.com/siyuan-note/filelock"
+ "github.com/siyuan-note/siyuan/kernel/model"
+)
+
+// Serialize annotation snapshots and read/merge/write operations across viewers.
+var fileAnnotationMu sync.Mutex
+
+var errAnnotationConflict = errors.New("annotation revision conflict")
+
+func parseFileAnnotations(data string) (map[string]fileAnno, error) {
+ var annotations map[string]fileAnno
+ if err := json.Unmarshal([]byte(data), &annotations); err != nil {
+ return nil, err
+ }
+ if annotations == nil {
+ return nil, errors.New("invalid annotation")
+ }
+ return annotations, nil
+}
+
+func readFileAnnotationData(filePath, boxID string) ([]byte, error) {
+ data, err := filelock.ReadFile(filePath)
+ if err != nil {
+ return nil, err
+ }
+ if boxID != "" && model.IsEncryptedBox(boxID) {
+ dek, err := model.GetDEKIfUnlocked(boxID)
+ if err != nil {
+ return nil, err
+ }
+ return model.DecryptAsset(boxID, filepath.Base(filePath), dek, data)
+ }
+ return data, nil
+}
+
+func mergeFileAnnotations(filePath, boxID, baseData, data string) (map[string]fileAnno, error) {
+ base, err := parseFileAnnotations(baseData)
+ if err != nil {
+ return nil, err
+ }
+ desired, err := parseFileAnnotations(data)
+ if err != nil {
+ return nil, err
+ }
+ current := map[string]fileAnno{}
+ stored, err := readFileAnnotationData(filePath, boxID)
+ if err != nil && !os.IsNotExist(err) {
+ return nil, err
+ }
+ if err == nil {
+ if current, err = parseFileAnnotations(string(stored)); err != nil {
+ return nil, err
+ }
+ }
+ ids := map[string]bool{}
+ for id := range base {
+ ids[id] = true
+ }
+ for id := range desired {
+ ids[id] = true
+ }
+ for id := range ids {
+ before, hadBefore := base[id]
+ after, hasAfter := desired[id]
+ if hadBefore == hasAfter && reflect.DeepEqual(before, after) {
+ continue
+ }
+ latest, hasLatest := current[id]
+ if hasLatest == hasAfter && reflect.DeepEqual(latest, after) {
+ continue
+ }
+ if hasLatest != hadBefore || !reflect.DeepEqual(latest, before) {
+ return nil, errAnnotationConflict
+ }
+ if hasAfter {
+ current[id] = after
+ } else {
+ delete(current, id)
+ }
+ }
+ return current, nil
+}
diff --git a/kernel/api/asset_annotation_test.go b/kernel/api/asset_annotation_test.go
new file mode 100644
index 0000000000..186bb20e08
--- /dev/null
+++ b/kernel/api/asset_annotation_test.go
@@ -0,0 +1,244 @@
+package api
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "reflect"
+ "sync"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "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/sql"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func annotationContractEngine() *gin.Engine {
+ engine := gin.New()
+ engine.Use(boxLeaseMiddleware, func(c *gin.Context) { c.Set(model.RoleContextKey, model.RoleAdministrator); c.Next() })
+ engine.POST("/api/asset/setFileAnnotation", setFileAnnotation)
+ engine.POST("/api/asset/getFileAnnotation", getFileAnnotation)
+ return engine
+}
+
+func annotationContractSave(t *testing.T, engine *gin.Engine, path, data string, base *string) (int, string) {
+ t.Helper()
+ body, err := json.Marshal(apicontract.SetAssetAnnotationRequest{Path: path, Data: data, BaseData: base})
+ if err != nil {
+ t.Fatal(err)
+ }
+ // A nil optional pointer must be omitted, as real legacy callers do.
+ if base == nil {
+ body, _ = json.Marshal(map[string]string{"path": path, "data": data})
+ }
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/asset/setFileAnnotation", bytes.NewReader(body)))
+ requireAPIContract(t, "POST", "/api/asset/setFileAnnotation", recorder)
+ var response struct {
+ Code int
+ Msg string
+ }
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
+ t.Fatal(err)
+ }
+ return response.Code, response.Msg
+}
+
+func TestAssetAnnotationContractMerge(t *testing.T) {
+ assets := setupAssetContractWorkspace(t)
+ if err := os.WriteFile(filepath.Join(assets, "fixture.pdf"), []byte("PDF"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ file := filepath.Join(assets, "fixture.pdf.sya")
+ engine := annotationContractEngine()
+ base := `{"s":{"content":"original"}}`
+ for _, test := range []struct {
+ name, first, second, want string
+ conflict bool
+ }{
+ {"distinct additions", `{"s":{"content":"original"},"a":{"content":"A"}}`, `{"s":{"content":"original"},"b":{"content":"B"}}`, `{"s":{"content":"original"},"a":{"content":"A"},"b":{"content":"B"}}`, false},
+ {"edit preserves additions", `{"s":{"content":"original"},"a":{"content":"A"}}`, `{"s":{"content":"edited"}}`, `{"s":{"content":"edited"},"a":{"content":"A"}}`, false},
+ {"delete last cached annotation", `{"s":{"content":"original"},"a":{"content":"A"}}`, `{}`, `{"a":{"content":"A"}}`, false},
+ {"same annotation edit", `{"s":{"content":"new"}}`, `{"s":{"content":"other"}}`, `{"s":{"content":"new"}}`, true},
+ {"stale delete", `{"s":{"content":"new"}}`, `{}`, `{"s":{"content":"new"}}`, true},
+ {"edit deleted annotation", `{}`, `{"s":{"content":"new"}}`, `{}`, true},
+ {"same addition ID", `{"s":{"content":"original"},"a":{"content":"A"}}`, `{"s":{"content":"original"},"a":{"content":"B"}}`, `{"s":{"content":"original"},"a":{"content":"A"}}`, true},
+ {"idempotent edit", `{"s":{"content":"new"}}`, `{"s":{"content":"new"}}`, `{"s":{"content":"new"}}`, false},
+ {"idempotent delete", `{}`, `{}`, `{}`, false},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ if code, msg := annotationContractSave(t, engine, "assets/fixture.pdf.sya", base, nil); code != 0 {
+ t.Fatalf("legacy setup: %d %s", code, msg)
+ }
+ if code, msg := annotationContractSave(t, engine, "assets/fixture.pdf.sya", test.first, &base); code != 0 {
+ t.Fatalf("first viewer: %d %s", code, msg)
+ }
+ before, _ := os.ReadFile(file)
+ code, msg := annotationContractSave(t, engine, "assets/fixture.pdf.sya", test.second, &base)
+ if (code != 0) != test.conflict || (test.conflict && msg != errAnnotationConflict.Error()) {
+ t.Fatalf("second viewer: %d %s", code, msg)
+ }
+ data, err := os.ReadFile(file)
+ if test.conflict && !bytes.Equal(before, data) {
+ t.Fatal("conflict changed original bytes")
+ }
+ if test.want == "{}" {
+ if !os.IsNotExist(err) {
+ t.Fatalf("empty mapping must be removed: %v", err)
+ }
+ return
+ }
+ actual, err := parseFileAnnotations(string(data))
+ if err != nil {
+ t.Fatal(err)
+ }
+ want, _ := parseFileAnnotations(test.want)
+ if !reflect.DeepEqual(actual, want) {
+ t.Fatalf("got %s, want %s", data, test.want)
+ }
+ })
+ }
+ for _, invalid := range []string{"null", "[]", "broken"} {
+ if err := os.WriteFile(file, []byte("corrupt source"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if code, _ := annotationContractSave(t, engine, "assets/fixture.pdf.sya", "{}", &invalid); code == 0 {
+ t.Fatal("invalid baseline was accepted")
+ }
+ if code, _ := annotationContractSave(t, engine, "assets/fixture.pdf.sya", "{}", new("{}")); code == 0 {
+ t.Fatal("corrupt source was overwritten")
+ }
+ if data, _ := os.ReadFile(file); string(data) != "corrupt source" {
+ t.Fatal("invalid input changed source")
+ }
+ }
+ // Competing edits from the same baseline must serialize into one success.
+ annotationContractSave(t, engine, "assets/fixture.pdf.sya", base, nil)
+ var wg sync.WaitGroup
+ results := make(chan int, 2)
+ for _, data := range []string{`{"s":{"content":"one"}}`, `{"s":{"content":"two"}}`} {
+ wg.Go(func() {
+ code, _ := annotationContractSave(t, engine, "assets/fixture.pdf.sya", data, &base)
+ results <- code
+ })
+ }
+ wg.Wait()
+ if first, second := <-results, <-results; first+second != -1 {
+ t.Fatalf("concurrent results: %d, %d", first, second)
+ }
+}
+
+func TestAssetAnnotationContractEncryptedMerge(t *testing.T) {
+ const child = "SIYUAN_TEST_ANNOTATION_ENCRYPTED_MERGE"
+ if os.Getenv(child) == "" {
+ command := exec.Command(os.Args[0], "-test.run=^TestAssetAnnotationContractEncryptedMerge$", "-test.timeout=60s", "-test.v")
+ command.Env = append(os.Environ(), child+"=1")
+ if output, err := command.CombinedOutput(); err != nil {
+ t.Fatalf("%v\n%s", err, output)
+ }
+ return
+ }
+ setupAssetContractWorkspace(t)
+ root := util.WorkspaceDir
+ util.TempDir, util.ConfDir, util.HistoryDir = filepath.Join(root, "temp"), filepath.Join(root, "conf"), filepath.Join(root, "history")
+ util.QueueDir = filepath.Join(util.TempDir, "queue")
+ util.DBPath, util.HistoryDBPath, util.AssetContentDBPath, util.BlockTreeDBPath = filepath.Join(util.TempDir, "siyuan.db"), filepath.Join(util.TempDir, "history.db"), filepath.Join(util.TempDir, "asset_content.db"), filepath.Join(util.TempDir, "blocktree.db")
+ for _, directory := range []string{util.TempDir, util.ConfDir, util.HistoryDir} {
+ if err := os.MkdirAll(directory, 0700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ model.Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ model.Conf.FileTree.Store(conf.NewFileTree())
+ model.Conf.Editor.Store(conf.NewEditor())
+ model.Conf.Export.Store(conf.NewExport())
+ model.Conf.Search.Store(conf.NewSearch())
+ sql.InitDatabase(true)
+ sql.InitHistoryDatabase(true)
+ if err := sql.InitAssetContentDatabase(true); err != nil {
+ t.Fatal(err)
+ }
+ defer sql.CloseDatabase()
+ if err := model.EnableEncryptedNotebook("annotation-password"); err != nil {
+ t.Fatal(err)
+ }
+ boxID, err := model.CreateEncryptedBox("Annotations", "annotation-password")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer model.LockBox(boxID)
+ dek, err := model.GetDEKIfUnlocked(boxID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer clear(dek)
+ asset := filepath.Join(util.DataDir, boxID, "assets", "fixture.pdf")
+ if err = os.MkdirAll(filepath.Dir(asset), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(asset, []byte("PDF"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ file := asset + ".sya"
+ // Supported existing authenticated format, created without the new API.
+ base := `{"s":{"content":"old"}}`
+ ciphertext, err := model.EncryptAsset(boxID, filepath.Base(file), filepath.Base(file), dek, []byte(base))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(file, ciphertext, 0600); err != nil {
+ t.Fatal(err)
+ }
+ engine := annotationContractEngine()
+ path := "assets/fixture.pdf?box=" + boxID + ".sya"
+ for _, data := range []string{`{"s":{"content":"old"},"a":{"content":"A"}}`, `{"s":{"content":"old"},"b":{"content":"B"}}`} {
+ if code, msg := annotationContractSave(t, engine, path, data, &base); code != 0 {
+ t.Fatalf("encrypted merge: %d %s", code, msg)
+ }
+ }
+ stored, err := os.ReadFile(file)
+ if err != nil {
+ t.Fatal(err)
+ }
+ plain, err := model.DecryptAsset(boxID, filepath.Base(file), dek, stored)
+ if err != nil {
+ t.Fatal(err)
+ }
+ annotations, err := parseFileAnnotations(string(plain))
+ if err != nil || len(annotations) != 3 || bytes.Contains(stored, []byte("content")) {
+ t.Fatalf("encrypted result: %s, %v", plain, err)
+ }
+ corrupt := append([]byte(nil), stored...)
+ corrupt[len(corrupt)-1] ^= 1
+ if err = os.WriteFile(file, corrupt, 0600); err != nil {
+ t.Fatal(err)
+ }
+ if code, _ := annotationContractSave(t, engine, path, "{}", &base); code == 0 {
+ t.Fatal("corrupt ciphertext deletion succeeded")
+ }
+ if actual, _ := os.ReadFile(file); !bytes.Equal(actual, corrupt) {
+ t.Fatal("authentication failure changed ciphertext")
+ }
+ if err = os.WriteFile(file, stored, 0600); err != nil {
+ t.Fatal(err)
+ }
+ model.LockBox(boxID)
+ if code, _ := annotationContractSave(t, engine, path, "{}", &base); code == 0 {
+ t.Fatal("locked notebook mutation succeeded")
+ }
+ if actual, _ := os.ReadFile(file); !bytes.Equal(actual, stored) {
+ t.Fatal("locked save changed ciphertext")
+ }
+ if err = model.UnlockBox(boxID, "annotation-password", (&model.Box{ID: boxID}).GetConf().BoxCrypt); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = readFileAnnotationData(file, boxID); err != nil {
+ t.Fatalf("unlock recovery: %v", err)
+ }
+}
diff --git a/kernel/apicontract/asset.go b/kernel/apicontract/asset.go
index 72f639aa42..397ab67716 100644
--- a/kernel/apicontract/asset.go
+++ b/kernel/apicontract/asset.go
@@ -56,8 +56,9 @@ type AssetDocumentAssetsRequest struct {
}
type SetAssetAnnotationRequest struct {
- Path string `json:"path"`
- Data string `json:"data"`
+ Path string `json:"path"`
+ Data string `json:"data"`
+ BaseData *string `json:"baseData,omitempty" api:"optional"`
}
type AssetCloudUploadRequest struct {
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 8dda7d4573..2c5bb59c03 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -1314,6 +1314,11 @@ var GetLivePhotoPreview = define[LivePhotoPreviewRequest, BinaryContent]("getLiv
// 取消会话并释放在途转换资源,已完成的缓存仍可在下一次播放时复用。
var CancelLivePhotoPreview = define[LivePhotoPreviewRequest, Null]("cancelLivePhotoPreview", "/api/asset/cancelLivePhotoPreview", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")
var GetDocAssets = define[AssetDocumentAssetsRequest, []string]("getDocAssets", "/api/asset/getDocAssets", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")
+
+// 保存 PDF 标注映射。省略 baseData 或传 null 保持旧版整份替换语义。
+// 提供 baseData 时,将 data 相对该读取基线的逐条变化合并到当前映射,保留其他查看器对不同标注的修改。
+// 同一标注已被不同内容修改或删除时返回 -1 / "annotation revision conflict",不写入文件;重复的相同结果可成功。
+// 基线和 data 必须为 JSON 对象字符串;加密笔记本先认证当前密文,租约和文件格式保持不变。
var SetFileAnnotation = define[SetAssetAnnotationRequest, Null]("setFileAnnotation", "/api/asset/setFileAnnotation", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
var GetFileAnnotation = define[AssetPathRequest, AssetAnnotationData]("getFileAnnotation", "/api/asset/getFileAnnotation", AuthenticatedAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1, 403}}, "POST")
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index a970f81498..05e6772edd 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -41846,6 +41846,16 @@
"SetAssetAnnotationRequestInput": {
"type": "object",
"properties": {
+ "baseData": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"data": {
"type": "string"
},