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 structured document addressing and recoverable creation plans https://github.com/siyuan-note/siyuan/issues/19938
Daniel0de83272f123
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 626145fce9..a5357a5fe0 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "قد تكون بعض المستندات قد أُنشئت بالفعل. تحقق من الروابط قبل المتابعة. ستحتفظ المتابعة بالمستندات الموجودة وتتخطى خطوات إنشائها المتبقية. الإلغاء ينهي هذه المحاولة.",+ "documentCreationLimit": "أكمل عملية إنشاء مستندات معلقة أو ألغها قبل بدء عملية جديدة","listMindmapRestoreWidth": "استعادة العرض الأصلي","lockScreenReveal": "انقر أو اضغط على مفتاح لتسجيل الدخول","loadAllAndSelectAll": "تحميل المستند بالكامل وتحديد الكل",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 4f4dfd2ef3..14831ece0e 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "Einige Dokumente wurden möglicherweise bereits erstellt. Prüfen Sie die Links, bevor Sie fortfahren. Beim Fortfahren bleiben vorhandene Dokumente erhalten und ihre restlichen Erstellungsschritte werden übersprungen. Abbrechen beendet diesen Vorgang.",+ "documentCreationLimit": "Schließen Sie eine ausstehende Dokumenterstellung ab oder brechen Sie sie ab, bevor Sie eine neue beginnen","listMindmapRestoreWidth": "Ursprüngliche Breiten wiederherstellen","lockScreenReveal": "Zum Anmelden klicken oder eine Taste drücken","loadAllAndSelectAll": "Gesamtes Dokument laden und alles auswählen",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex dab71a93e6..396db86752 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "Some documents may already exist. Check the links before continuing. Continuing keeps existing documents and skips their remaining creation steps. Cancel ends this creation attempt.",+ "documentCreationLimit": "Finish or cancel a pending document creation before starting another","listMindmapRestoreWidth": "Restore original widths","lockScreenReveal": "Click or press a key to sign in","loadAllAndSelectAll": "Load full document and select all",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 467540f3db..ad8baa5b90 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "Es posible que algunos documentos ya se hayan creado. Revise los enlaces antes de continuar. Al continuar se conservan los documentos existentes y se omiten los pasos de creación pendientes. Cancelar finaliza este intento.",+ "documentCreationLimit": "Complete o cancele una creación de documentos pendiente antes de iniciar otra","listMindmapRestoreWidth": "Restaurar los anchos originales","lockScreenReveal": "Haz clic o pulsa una tecla para iniciar sesión","loadAllAndSelectAll": "Cargar el documento completo y seleccionar todo",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex aa17252e47..03594e2307 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "Certains documents existent peut-être déjà. Vérifiez les liens avant de continuer. Continuer conserve les documents existants et ignore leurs étapes de création restantes. Annuler met fin à cette création.",+ "documentCreationLimit": "Terminez ou annulez une création de document en attente avant d’en commencer une autre","listMindmapRestoreWidth": "Restaurer les largeurs initiales","lockScreenReveal": "Cliquez ou appuyez sur une touche pour vous connecter","loadAllAndSelectAll": "Charger le document entier et tout sélectionner",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex 8d4924e972..790bd83129 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "ייתכן שחלק מהמסמכים כבר נוצרו. בדקו את הקישורים לפני ההמשך. המשך ישמור על המסמכים הקיימים וידלג על שלבי היצירה שנותרו. ביטול יסיים ניסיון זה.",+ "documentCreationLimit": "יש להשלים או לבטל יצירת מסמכים ממתינה לפני שמתחילים יצירה חדשה","listMindmapRestoreWidth": "שחזור הרוחב המקורי","lockScreenReveal": "יש ללחוץ על המסך או על מקש כדי להיכנס","loadAllAndSelectAll": "טעינת המסמך המלא ובחירת הכול",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 10ce9f071d..2dcbf066c8 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "कुछ दस्तावेज़ पहले ही बन चुके हो सकते हैं। जारी रखने से पहले लिंक जाँचें। जारी रखने पर मौजूदा दस्तावेज़ सुरक्षित रहेंगे और उनके बचे हुए निर्माण चरण छोड़ दिए जाएँगे। रद्द करने पर यह प्रयास समाप्त होगा।",+ "documentCreationLimit": "नया निर्माण शुरू करने से पहले लंबित दस्तावेज़ निर्माण पूरा करें या रद्द करें","listMindmapRestoreWidth": "मूल चौड़ाई बहाल करें","lockScreenReveal": "लॉगिन करने के लिए क्लिक करें या कोई कुंजी दबाएँ","loadAllAndSelectAll": "पूरा दस्तावेज़ लोड करें और सभी चुनें",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 4d53046ad8..f82714bd21 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "Beberapa dokumen mungkin sudah dibuat. Periksa tautan sebelum melanjutkan. Melanjutkan akan mempertahankan dokumen yang ada dan melewati tahap pembuatan yang tersisa. Membatalkan mengakhiri percobaan ini.",+ "documentCreationLimit": "Selesaikan atau batalkan pembuatan dokumen yang tertunda sebelum memulai yang baru","listMindmapRestoreWidth": "Pulihkan lebar semula","lockScreenReveal": "Klik atau tekan tombol untuk masuk","loadAllAndSelectAll": "Muat seluruh dokumen dan pilih semua",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 4d319dc2a9..1c0fc6c6e3 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "Alcuni documenti potrebbero essere già stati creati. Controlla i collegamenti prima di continuare. Continuando, i documenti esistenti vengono conservati e i passaggi di creazione rimanenti vengono saltati. Annulla termina questo tentativo.",+ "documentCreationLimit": "Completa o annulla una creazione di documenti in sospeso prima di avviarne un’altra","listMindmapRestoreWidth": "Ripristina le larghezze originali","lockScreenReveal": "Fai clic o premi un tasto per accedere","loadAllAndSelectAll": "Carica l'intero documento e seleziona tutto",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex fb54e6ee3c..2b0cb24249 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "一部のドキュメントは作成済みの可能性があります。続行する前にリンクから確認してください。続行すると既存のドキュメントを保持し、残りの作成処理をスキップします。キャンセルすると今回の作成を終了します。",+ "documentCreationLimit": "新たに作成する前に、保留中のドキュメント作成を完了するかキャンセルしてください","listMindmapRestoreWidth": "元の幅に戻す","lockScreenReveal": "クリックまたはキーを押してログイン","loadAllAndSelectAll": "全文を読み込んですべて選択",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex d6dee594bf..cdb754c719 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "일부 문서가 이미 생성되었을 수 있습니다. 계속하기 전에 링크를 확인하세요. 계속하면 기존 문서를 유지하고 남은 생성 단계를 건너뜁니다. 취소하면 이번 생성을 종료합니다.",+ "documentCreationLimit": "새로 시작하기 전에 대기 중인 문서 생성을 완료하거나 취소하세요","listMindmapRestoreWidth": "원래 너비 복원","lockScreenReveal": "화면을 클릭하거나 키를 눌러 로그인","loadAllAndSelectAll": "전체 문서를 불러오고 모두 선택",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 51382ba672..d3fa19161b 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "Sommige documenten zijn mogelijk al aangemaakt. Controleer de links voordat u doorgaat. Doorgaan behoudt bestaande documenten en slaat hun resterende aanmaakstappen over. Annuleren beëindigt deze poging.",+ "documentCreationLimit": "Voltooi of annuleer een lopende documentaanmaak voordat u een nieuwe start","listMindmapRestoreWidth": "Oorspronkelijke breedtes herstellen","lockScreenReveal": "Klik of druk op een toets om aan te melden","loadAllAndSelectAll": "Volledig document laden en alles selecteren",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex ebe69ea339..e0d98afbcb 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "Niektóre dokumenty mogły już zostać utworzone. Przed kontynuowaniem sprawdź łącza. Kontynuacja zachowa istniejące dokumenty i pominie pozostałe etapy ich tworzenia. Anulowanie zakończy tę próbę.",+ "documentCreationLimit": "Zakończ lub anuluj oczekujące tworzenie dokumentów przed rozpoczęciem kolejnego","listMindmapRestoreWidth": "Przywróć pierwotne szerokości","lockScreenReveal": "Kliknij lub naciśnij klawisz, aby się zalogować","loadAllAndSelectAll": "Wczytaj cały dokument i zaznacz wszystko",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 2bf2ec8991..d6642ea9e4 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "Alguns documentos podem já ter sido criados. Verifique os links antes de continuar. Continuar mantém os documentos existentes e ignora as etapas de criação restantes. Cancelar encerra esta tentativa.",+ "documentCreationLimit": "Conclua ou cancele uma criação de documentos pendente antes de iniciar outra","listMindmapRestoreWidth": "Restaurar larguras originais","lockScreenReveal": "Clique ou pressione uma tecla para entrar","loadAllAndSelectAll": "Carregar o documento completo e selecionar tudo",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 70eaa3ba74..5f02c4eb3e 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "Некоторые документы, возможно, уже созданы. Перед продолжением проверьте ссылки. Продолжение сохранит существующие документы и пропустит оставшиеся этапы их создания. Отмена завершит эту попытку.",+ "documentCreationLimit": "Завершите или отмените ожидающее создание документов, прежде чем начать новое","listMindmapRestoreWidth": "Восстановить исходную ширину","lockScreenReveal": "Нажмите на экран или клавишу для входа","loadAllAndSelectAll": "Загрузить весь документ и выделить всё",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex b845972125..97bb28c60a 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "Niektoré dokumenty už možno boli vytvorené. Pred pokračovaním skontrolujte odkazy. Pokračovanie zachová existujúce dokumenty a preskočí zostávajúce kroky ich vytvárania. Zrušenie ukončí tento pokus.",+ "documentCreationLimit": "Pred začatím ďalšieho vytvárania dokumentov dokončite alebo zrušte čakajúce vytváranie","listMindmapRestoreWidth": "Obnoviť pôvodné šírky","lockScreenReveal": "Prihláste sa kliknutím alebo stlačením klávesu","loadAllAndSelectAll": "Načítať celý dokument a vybrať všetko",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex 8d89acb44c..2e40fb2669 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "Неки документи су можда већ направљени. Проверите везе пре него што наставите. Наставак задржава постојеће документе и прескаче преостале кораке њиховог прављења. Отказивање завршава овај покушај.",+ "documentCreationLimit": "Завршите или откажите прављење докумената на чекању пре него што започнете ново","listMindmapRestoreWidth": "Врати првобитне ширине","lockScreenReveal": "Кликните или притисните тастер за пријављивање","loadAllAndSelectAll": "Учитај цео документ и изабери све",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 0973bb56e6..b075159cfd 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "เอกสารบางส่วนอาจถูกสร้างแล้ว โปรดตรวจสอบลิงก์ก่อนดำเนินการต่อ การดำเนินการต่อจะเก็บเอกสารที่มีอยู่และข้ามขั้นตอนการสร้างที่เหลือ การยกเลิกจะสิ้นสุดการสร้างครั้งนี้",+ "documentCreationLimit": "โปรดดำเนินการสร้างเอกสารที่ค้างอยู่ให้เสร็จหรือยกเลิกก่อนเริ่มสร้างใหม่","listMindmapRestoreWidth": "คืนค่าความกว้างเดิม","lockScreenReveal": "คลิกหรือกดปุ่มเพื่อเข้าสู่ระบบ","loadAllAndSelectAll": "โหลดเอกสารทั้งหมดและเลือกทั้งหมด",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 7c6f08f79b..a73d9f52cd 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "Bazı belgeler zaten oluşturulmuş olabilir. Devam etmeden önce bağlantıları kontrol edin. Devam etmek mevcut belgeleri korur ve kalan oluşturma adımlarını atlar. İptal, bu denemeyi sonlandırır.",+ "documentCreationLimit": "Yeni bir belge oluşturma işlemine başlamadan önce bekleyen işlemi tamamlayın veya iptal edin","listMindmapRestoreWidth": "Özgün genişlikleri geri yükle","lockScreenReveal": "Giriş yapmak için tıklayın veya bir tuşa basın","loadAllAndSelectAll": "Belgenin tamamını yükle ve tümünü seç",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex dbec37d141..b8190d6b92 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "Деякі документи, можливо, вже створено. Перед продовженням перевірте посилання. Продовження збереже наявні документи та пропустить решту етапів їх створення. Скасування завершить цю спробу.",+ "documentCreationLimit": "Завершіть або скасуйте незавершене створення документів, перш ніж починати нове","listMindmapRestoreWidth": "Відновити початкову ширину","lockScreenReveal": "Натисніть на екран або клавішу для входу","loadAllAndSelectAll": "Завантажити весь документ і виділити все",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex b312a5222d..e821495090 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "部分文档可能已创建,请先通过链接检查。继续将保留已有文档,并跳过其尚未完成的创建处理。取消会结束本次创建。",+ "documentCreationLimit": "请先完成或取消待处理的文档创建,再开始新的创建","listMindmapRestoreWidth": "恢复原宽度","lockScreenReveal": "点击屏幕或按键以登录","loadAllAndSelectAll": "加载全文并全选",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 72440fb9a3..27635f4b97 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,6 @@{+ "documentCreationRecovery": "部分文件可能已建立,請先透過連結檢查。繼續將保留既有文件,並略過其尚未完成的建立處理。取消會結束本次建立。",+ "documentCreationLimit": "請先完成或取消待處理的文件建立,再開始新的建立","listMindmapRestoreWidth": "還原原始寬度","lockScreenReveal": "點擊畫面或按鍵以登入","loadAllAndSelectAll": "載入全文並全選",diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201204184532-3qm9l8n.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201204184532-3qm9l8n.syindex 36cc526268..9e8ddf64a7 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201204184532-3qm9l8n.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20201204184532-3qm9l8n.sy@@ -6,7 +6,7 @@"id": "20201204184532-3qm9l8n","title": "Template snippet","type": "doc",- "updated": "20261016202856"+ "updated": "20261023030419"},"Children": [{@@ -1821,7 +1821,7 @@"HeadingLevel": 2,"Properties": {"id": "20260830143000-tplen01",- "updated": "20260830143000"+ "updated": "20261023030419"},"Children": [{@@ -1944,7 +1944,7 @@"Type": "NodeParagraph","Properties": {"id": "20260830143000-tplen07",- "updated": "20260830143000"+ "updated": "20261023030419"},"Children": [{@@ -1954,7 +1954,16 @@},{"Type": "NodeText",- "Data": " returns a static list of planned child document descriptions; "+ "Data": " returns the static child-document descriptors in the creation plan; "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "renderDocRef \"id\" <id>"+ },+ {+ "Type": "NodeText",+ "Data": " returns a static block reference to a planned document by its ID, independent of its title or readable path; "},{"Type": "NodeTextMark",@@ -1963,7 +1972,7 @@},{"Type": "NodeText",- "Data": " returns static block-reference text that points to a planned document."+ "Data": " is the legacy query by readable path."}]},diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201204181006-7bkppue.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201204181006-7bkppue.syindex 120c906727..3870c213bd 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201204181006-7bkppue.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20201204181006-7bkppue.sy@@ -6,7 +6,7 @@"id": "20201204181006-7bkppue","title": "模板片段","type": "doc",- "updated": "20261016111305"+ "updated": "20261023030419"},"Children": [{@@ -1833,7 +1833,7 @@"HeadingLevel": 2,"Properties": {"id": "20260830143000-tplcn01",- "updated": "20260830143000"+ "updated": "20261023030419"},"Children": [{@@ -1960,7 +1960,7 @@"Type": "NodeParagraph","Properties": {"id": "20260830143000-tplcn07",- "updated": "20260830143000"+ "updated": "20261023030419"},"Children": [{@@ -1972,6 +1972,15 @@"Type": "NodeText","Data": " 返回创建计划中的静态子文档描述列表;"},+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "renderDocRef \"id\" <id>"+ },+ {+ "Type": "NodeText",+ "Data": " 根据文档 ID 返回指向计划文档的静态块引用文本,不依赖标题或可读路径;"+ },{"Type": "NodeTextMark","TextMarkType": "code",@@ -1979,7 +1988,7 @@},{"Type": "NodeText",- "Data": " 返回指向计划文档的静态块引用文本。"+ "Data": " 为按可读路径查询的兼容入口。"}]},diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123004-dplpw0o.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123004-dplpw0o.syindex 1a641ddc29..581f5cd892 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123004-dplpw0o.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123004-dplpw0o.sy@@ -6,7 +6,7 @@"id": "20211226123004-dplpw0o","title": "範本片段","type": "doc",- "updated": "20261016111305"+ "updated": "20261023030419"},"Children": [{@@ -1810,7 +1810,7 @@"HeadingLevel": 2,"Properties": {"id": "20260830143000-tpltw01",- "updated": "20260830143000"+ "updated": "20261023030419"},"Children": [{@@ -1933,7 +1933,7 @@"Type": "NodeParagraph","Properties": {"id": "20260830143000-tpltw07",- "updated": "20260830143000"+ "updated": "20261023030419"},"Children": [{@@ -1943,7 +1943,16 @@},{"Type": "NodeText",- "Data": " 回傳建立計劃中的靜態子文檔描述清單;"+ "Data": " 傳回建立計畫中的靜態子文件描述清單;"+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "renderDocRef \"id\" <id>"+ },+ {+ "Type": "NodeText",+ "Data": " 根據文件 ID 傳回指向計畫文件的靜態區塊引用文字,不依賴標題或可讀路徑;"},{"Type": "NodeTextMark",@@ -1952,7 +1961,7 @@},{"Type": "NodeText",- "Data": " 回傳指向計劃文檔的靜態區塊引用文字。"+ "Data": " 為依可讀路徑查詢的相容入口。"}]},diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-6x9ivi7.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-6x9ivi7.syindex 2969e33998..8196434667 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-6x9ivi7.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-6x9ivi7.sy@@ -7,7 +7,7 @@"id": "20240530101000-6x9ivi7","title": "テンプレートスニペット","type": "doc",- "updated": "20261016111305"+ "updated": "20261023030419"},"Children": [{@@ -1836,7 +1836,7 @@"ID": "20261012014537-2ursx4t","Properties": {"id": "20261012014537-2ursx4t",- "updated": "20261012014859"+ "updated": "20261023030419"}},{@@ -1954,7 +1954,16 @@},{"Type": "NodeText",- "Data": " は作成計画に含まれるサブドキュメントの情報を静的なリストとして返し、"+ "Data": " は作成計画内の静的な子ドキュメント記述の一覧を返します。"+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "code",+ "TextMarkTextContent": "renderDocRef \"id\" <id>"+ },+ {+ "Type": "NodeText",+ "Data": " はドキュメント ID を使って計画内のドキュメントへの静的なブロック参照を返すため、タイトルや可読パスに依存しません。"},{"Type": "NodeTextMark",@@ -1963,13 +1972,13 @@},{"Type": "NodeText",- "Data": " は作成予定のドキュメントを指す静的なブロック参照テキストを返します。"+ "Data": " は可読パスで検索する互換用の入口です。"}],"ID": "20261012014537-eegumh4","Properties": {"id": "20261012014537-eegumh4",- "updated": "20261012014859"+ "updated": "20261023030419"}},{diff --git a/app/src/dialog/confirmDialog.ts b/app/src/dialog/confirmDialog.tsindex b84afcecaa..d6e2c94630 100644--- a/app/src/dialog/confirmDialog.ts+++ b/app/src/dialog/confirmDialog.ts@@ -75,4 +75,5 @@ export const confirmDialog = (title: string, text: string,}dialog.element.setAttribute("data-key", Constants.DIALOG_CONFIRM);(dialog.element.querySelector("#confirmDialogConfirmBtn") as HTMLButtonElement).focus({preventScroll: true});+ return dialog;};diff --git a/app/src/editor/rename.ts b/app/src/editor/rename.tsindex 1a143f4419..dd2ec7b35a 100644--- a/app/src/editor/rename.ts+++ b/app/src/editor/rename.ts@@ -3,7 +3,8 @@ import {openInputDialog} from "../dialog/inputDialog";import {focusByRange} from "../protyle/util/selectionOffsets";import {hasClosestBlock} from "../protyle/util/hasClosest";import {removeEmbed} from "../protyle/wysiwyg/removeEmbed";-import {getAssetName, getDisplayName, pathPosix, setNotebookName} from "../util/pathName";+import {getAssetName, setNotebookName} from "../util/pathName";+import {documentCreateRequest} from "../util/documentCreate";import {fetchPost, fetchSyncPost} from "../util/fetch";import {Constants} from "../constants";import {showTooltip} from "../dialog/tooltip";@@ -165,10 +166,6 @@ export const newFileContentBySelect = (protyle: IProtyle) => {fileNameShort = fileNameShort.substr(0, 10) + "...";}fileNameShort = replaceFileName(fileNameShort);- fetchPost("/api/filetree/createDoc", {- notebook: protyle.notebookId,- path: pathPosix().join(getDisplayName(protyle.path, false, true), Lute.NewNodeID() + ".sy"),- title: fileNameShort,- md: protyle.lute.BlockDOM2StdMd(html)- });+ fetchPost("/api/filetree/createDocByParent", documentCreateRequest(protyle.notebookId, protyle.path,+ Lute.NewNodeID(), fileNameShort, protyle.lute.BlockDOM2StdMd(html)));};diff --git a/app/src/index.ts b/app/src/index.tsindex 8da2584141..0957f1fc1d 100644--- a/app/src/index.ts+++ b/app/src/index.ts@@ -1,6 +1,7 @@import {Constants} from "./constants";import {refreshSettingConfig} from "./config/setting/sync";import {closeNotebookHistoryDialogs} from "./history/notebookDialogs";+import {clearDocumentCreationPlans} from "./util/configuredDocument";import {closeNotebookLivePhotos} from "./protyle/preview/livePhoto";import {systemConfig} from "./config/systemConfig";import {openStandaloneDatabaseItemByURI} from "./protyle/render/av/openStandaloneDatabaseItem";@@ -216,6 +217,7 @@ export class App {case "closeBox":case "removeBox":closeNotebookHistoryDialogs(data.data.box);+ clearDocumentCreationPlans(data.data.box);closeNotebookLivePhotos(data.data.box);removeBlockPanelEditors({notebookId: data.data.box});getAllTabs().forEach((tab) => {diff --git a/app/src/layout/dock/Inbox.test.ts b/app/src/layout/dock/Inbox.test.tsindex 6d09198540..300b53c274 100644--- a/app/src/layout/dock/Inbox.test.ts+++ b/app/src/layout/dock/Inbox.test.ts@@ -5,6 +5,7 @@ import {join} from "node:path";import {runInNewContext} from "node:vm";import * as ts from "typescript";import {escapeMarkdownPlainText} from "../../util/escape";+import {documentCreateRequest} from "../../util/documentCreate";const loadInbox = (responses: {code: number; data?: Record<string, string>}[]) => {const calls: {url: string; data: Record<string, string>}[] = [];@@ -82,3 +83,70 @@ test("inbox insertion keeps Markdown punctuation in the title as plain text", asassert.equal(calls[1].data.data, "# A \\*bold\\* \\[note\\] \\$x\\$ \\=\\=mark\\=\\= \\& \\#tag\\# 1+2 50%? continued\n\nBody");assert.deepEqual(removed, [["entry"]]);});++const loadMoveInbox = (fetchEntry: (id: string) => Promise<void> = async () => {}) => {+ const removed: string[][] = [];+ const created: string[] = [];+ let picker: {cb: (paths: string[], notebooks: string[]) => Promise<void>};+ const exports: {Inbox?: {prototype: object}} = {};+ runInNewContext(ts.transpileModule(readFileSync(join(__dirname, "Inbox.ts"), "utf8"), {+ compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2020},+ }).outputText, {+ exports, Lute: {NewNodeID: () => `20261023030000-${String(created.length).padStart(7, "0")}`},+ window: {siyuan: {languages: {documentCreationLimit: "Limit", documentCreationRecovery: "Review"}}},+ require: (name: string) => ({+ "../Model": {Model: class {}},+ "../../util/pathName": {movePathTo: (options: typeof picker) => { picker = options; }},+ "../../util/documentCreate": {documentCreateRequest},+ "../../util/fetch": {fetchSyncPost: async (_url: string, data: {id: string}) => {+ await fetchEntry(data.id);+ return {code: 0, data: {oId: data.id, shorthandTitle: data.id, shorthandMd: "Body"}};+ }},+ "../../util/configuredDocument": {createConfiguredDocument: async (input: {id: string}, options: {onCreated: () => void}) => {+ created.push(input.id);+ options.onCreated();+ }},+ "../../editor/rename": {replaceFileName: (value: string) => value},+ "../../util/escape": {escapeHtml: (value: string) => value},+ "../../dialog/message": {showMessage() {}},+ })[name] || {},+ });+ const inbox = Object.assign(Object.create(exports.Inbox.prototype), {+ data: {}, moving: false, moveTargets: new Map(), remove: (ids: string[]) => removed.push(Array.from(ids)),+ }) as {move(ids: string[]): void};+ return {inbox, removed, created, select: () => picker.cb(["/"], ["box"])};+};++test("inbox document batches consume only confirmed entries after a later network failure", async () => {+ const f = loadMoveInbox(async id => { if (id === "second") { throw new Error("offline"); } });+ f.inbox.move(["first", "second"]);+ await f.select();+ assert.equal(f.created.length, 1);+ assert.deepEqual(f.removed, [["first"]]);+});++test("confirmed inbox batches can exceed the unresolved-plan bound and removal retries do not recreate documents", async () => {+ const f = loadMoveInbox();+ const ids = Array.from({length: 64}, (_, i) => `entry-${i}`);+ f.inbox.move(ids);+ await f.select();+ assert.equal(f.created.length, 64);+ assert.deepEqual(f.removed, [ids]);+ f.inbox.move(ids);+ await f.select();+ assert.equal(f.created.length, 64);+ assert.deepEqual(f.removed, [ids, ids]);+});++test("concurrent inbox move callbacks cannot allocate different identities for one source", async () => {+ let resolve: () => void;+ const wait = new Promise<void>(done => { resolve = done; });+ const f = loadMoveInbox(async () => wait);+ f.inbox.move(["first"]);+ const first = f.select();+ await f.select();+ resolve();+ await first;+ assert.equal(f.created.length, 1);+ assert.deepEqual(f.removed, [["first"]]);+});diff --git a/app/src/layout/dock/Inbox.ts b/app/src/layout/dock/Inbox.tsindex 0d1a27c440..616bfe4ff5 100644--- a/app/src/layout/dock/Inbox.ts+++ b/app/src/layout/dock/Inbox.ts@@ -12,7 +12,9 @@ import {needSubscribe} from "../../util/needSubscribe";import {MenuItem} from "../../menus/Menu";import {confirmDialog} from "../../dialog/confirmDialog";import {replaceFileName} from "../../editor/rename";-import {getDisplayName, movePathTo, pathPosix} from "../../util/pathName";+import {movePathTo} from "../../util/pathName";+import {documentCreateRequest} from "../../util/documentCreate";+import {createConfiguredDocument} from "../../util/configuredDocument";import type {App} from "../../index";import {getCloudURL} from "../../config/util/about";import {hasClosestByClassName} from "../../protyle/util/hasClosest";@@ -27,6 +29,8 @@ export class Inbox extends Model {private currentPage = 1;private pageCount = 1;private data: { [key: string]: IInbox } = {};+ private moveTargets = new Map<string, {notebook: string; path: string; id: string; committed?: boolean}>();+ private moving = false;constructor(app: App, tab: Tab | Element) {super({app});@@ -371,6 +375,9 @@ ${data.shorthandContent}if (response.code !== 0) {return;}+ for (const id of removeIds || this.selectIds) {+ this.moveTargets.delete(id);+ }if (removeIds) {this.back();for (let i = this.selectIds.length - 1; i >= 0; i--) {@@ -390,28 +397,76 @@ ${data.shorthandContent}private move(ids: string[]) {movePathTo({cb: async (toPath, toNotebook) => {- for (let i = 0; i < ids.length; i++) {- const idItem = ids[i];- const response = await fetchSyncPost("/api/inbox/getShorthand", {- id: idItem- });- if (response.code !== 0 || !response.data) {- return;+ if (this.moving) {+ return;+ }+ this.moving = true;+ const created: string[] = [];+ let finished = false;+ try {+ for (let i = 0; i < ids.length; i++) {+ const idItem = ids[i];+ let target = this.moveTargets.get(idItem);+ if (target && (target.notebook !== toNotebook[0] || target.path !== toPath[0])) {+ showMessage(`${escapeHtml(window.siyuan.languages.documentCreationRecovery)} ` ++ `<a href="siyuan://blocks/${target.id}">${target.id}</a>`, 0, "error");+ break;+ }+ if (target?.committed) {+ created.push(idItem);+ continue;+ }+ const response = await fetchSyncPost("/api/inbox/getShorthand", {+ id: idItem+ });+ if (response.code !== 0 || !response.data) {+ break;+ }+ this.data[response.data.oId] = response.data;+ let md = response.data.shorthandMd;+ if ("" === md && "" === response.data.shorthandContent && "" != response.data.shorthandURL) {+ md = "[" + response.data.shorthandTitle + "](" + response.data.shorthandURL + ")";+ }+ if (!target) {+ if ([...this.moveTargets.values()].filter(value => !value.committed).length >= 32) {+ showMessage(window.siyuan.languages.documentCreationLimit, 0, "error");+ break;+ }+ target = {notebook: toNotebook[0], path: toPath[0], id: Lute.NewNodeID()};+ this.moveTargets.set(idItem, target);+ }+ const request = documentCreateRequest(target.notebook, target.path, target.id,+ replaceFileName(response.data.shorthandTitle), md);+ let completed = false;+ await createConfiguredDocument({+ notebook: target.notebook, contextID: request.parentID, purpose: "document",+ placement: "child", id: target.id, title: request.title.text,+ }, {+ plan: {notebook: target.notebook, title: request.title.text, steps: [request]},+ listDocTree: true,+ onCreated: () => {+ target.committed = true;+ completed = true;+ if (finished) {+ this.remove([idItem]);+ } else {+ created.push(idItem);+ }+ },+ });+ if (!completed) {+ break;+ }}- this.data[response.data.oId] = response.data;- let md = response.data.shorthandMd;- if ("" === md && "" === response.data.shorthandContent && "" != response.data.shorthandURL) {- md = "[" + response.data.shorthandTitle + "](" + response.data.shorthandURL + ")";+ } catch (error) {+ showMessage(escapeHtml(error instanceof Error ? error.message : String(error)), 0, "error");+ } finally {+ this.moving = false;+ finished = true;+ if (created.length) {+ this.remove(created);}- await fetchSyncPost("/api/filetree/createDoc", {- notebook: toNotebook[0],- path: pathPosix().join(getDisplayName(toPath[0], false, true), Lute.NewNodeID() + ".sy"),- title: replaceFileName(response.data.shorthandTitle),- md,- listDocTree: true,- });}- this.remove(ids);},flashcard: false});diff --git a/app/src/mobile/util/onMessage.ts b/app/src/mobile/util/onMessage.tsindex 458c4ce6f6..583afa7a0c 100644--- a/app/src/mobile/util/onMessage.ts+++ b/app/src/mobile/util/onMessage.ts@@ -1,6 +1,7 @@import {openMobileFileById} from "../editor";import {refreshSettingConfig} from "../../config/setting/sync";import {closeNotebookHistoryDialogs} from "../../history/notebookDialogs";+import {clearDocumentCreationPlans} from "../../util/configuredDocument";import {closeNotebookLivePhotos} from "../../protyle/preview/livePhoto";import {downloadProgress,@@ -131,6 +132,7 @@ export const onMessage = (app: App, data: IWebSocketData) => {case "closeBox":case "removeBox": {closeNotebookHistoryDialogs(data.data.box);+ clearDocumentCreationPlans(data.data.box);closeNotebookLivePhotos(data.data.box);removeMobileBacklinkContent({notebookId: data.data.box});removeMobileReferenceSheet({notebookId: data.data.box});diff --git a/app/src/protyle/hint/index.ts b/app/src/protyle/hint/index.tsindex a4ebdd5d5d..56bbab1b55 100644--- a/app/src/protyle/hint/index.ts+++ b/app/src/protyle/hint/index.ts@@ -47,9 +47,10 @@ import {spinListMindmapDOM} from "../render/listMindmap/create";import {mountNewListMindmap} from "../render/listMindmap";import {assetMenu, imgMenu} from "../../menus/protyle";import {hideElements} from "../ui/hideElements";-import {fetchPost} from "../../util/fetch";+import {fetchSyncPost} from "../../util/fetch";import {escapeHtml, escapeSearchHighlight, stripSearchMark} from "../../util/escape";-import {getDisplayName, isEncryptedBox, pathPosix} from "../../util/pathName";+import {isEncryptedBox} from "../../util/pathName";+import {createdDocumentID, documentCreateRequest} from "../../util/documentCreate";import {addEmoji,EmojiPanelController,@@ -1372,13 +1373,13 @@ ${genHintItemHTML(item)}// 新建子文档const newSubDocId = Lute.NewNodeID();getDocCreateTemplatePath(protyle.notebookId, (docCreateTemplatePath) => {- fetchPost("/api/filetree/createDoc", {- notebook: protyle.notebookId,- path: pathPosix().join(getDisplayName(protyle.path, false, true), newSubDocId + ".sy"),- title: "",- md: "",+ void fetchSyncPost("/api/filetree/createDocByParent", {+ ...documentCreateRequest(protyle.notebookId, protyle.path, newSubDocId, ""),docCreateTemplatePath,- }, () => {+ }).then(response => {+ if (!createdDocumentID(response.data)) {+ return;+ }insertHTML(`<span data-type="block-ref" data-id="${newSubDocId}" data-subtype="d">${getBlockRefAnchorText("")}</span>`, protyle);/// #if MOBILEopenMobileFileById(protyle.app, newSubDocId, [Constants.CB_GET_CONTEXT, Constants.CB_GET_OPENNEW]);@@ -1389,7 +1390,7 @@ ${genHintItemHTML(item)}action: [Constants.CB_GET_CONTEXT, Constants.CB_GET_OPENNEW]});/// #endif- });+ }).catch(error => showMessage(error.message));});return;} else if (value === Constants.ZWSP + 5) {diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 780b8ead2f..14786c8dc8 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -916,6 +916,12 @@ export type CreateAttributeViewItemWithMarkdownRequestInput = { "app"?: string |export type CreateAttributeViewRelationItemRequestInput = { "app"?: string | null; "avID": string; "blockID": string; "cells": Array<AVRelationItemCellInput | null>; "keyID": string; "keyword"?: string | null; "preview": AVRelationItemPreviewInput | null; "session"?: string | null; "useInputName"?: boolean | null; };+export type CreateDocByParentRequest = { "clippingHref"?: string; "docCreateTemplatePath"?: string; "expectedParentRevision"?: string; "expectedTarget"?: DocumentTargetRevision; "id": string; "listDocTree"?: boolean; "markdown": string; "nameConditions"?: Array<DocumentNameCondition>; "notebook": string; "parentID": string | null; "sortPosition"?: "before" | "after"; "sortTargetID"?: string; "sorts"?: Array<string>; "tags"?: string; "title": DocumentCreateTitle; "withMath"?: boolean; };++export type CreateDocByParentRequestInput = { "clippingHref"?: string; "docCreateTemplatePath"?: string; "expectedParentRevision"?: string; "expectedTarget"?: DocumentTargetRevisionInput; "id": string; "listDocTree"?: boolean; "markdown": string; "nameConditions"?: Array<DocumentNameConditionInput>; "notebook": string; "parentID": string | null; "sortPosition"?: "before" | "after"; "sortTargetID"?: string; "sorts"?: Array<string>; "tags"?: string; "title": DocumentCreateTitleInput; "withMath"?: boolean; };++export type CreateDocByParentResult = (CreatedDocumentData & { "commitState"?: never; "completed"?: never; "reason"?: never; "stage"?: never; }) | (DocumentCreateFailure & { "document"?: never; });+export type CreateDocHistoryRequestInput = { "id": string; };export type CreateEncryptedNotebookRequestInput = { "name": string; "password": string; };@@ -930,6 +936,8 @@ export type CreateSnapshotData = { "created": boolean; "id": string; };export type CreateSnapshotRequestInput = { "memo"?: string; };+export type CreatedDocumentData = { "document": DocumentPath; "id": string; };+export type Criterion = { "group": number; "hPath": string; "hasReplace": boolean; "idPath": Array<string> | null; "k": string; "method": number; "name": string; "r": string; "replaceTypes": CriterionReplaceTypes | null; "sort": number; "subTypes": SearchSubTypes; "types": CriterionTypes | null; };export type CriterionInput = { "group"?: number | null; "hPath"?: string | null; "hasReplace"?: boolean | null; "idPath"?: Array<string> | null; "k"?: string | null; "method"?: number | null; "name"?: string | null; "r"?: string | null; "replaceTypes"?: CriterionReplaceTypesInput | null; "sort"?: number | null; "subTypes"?: SearchSubTypesInput | null; "types"?: CriterionTypesInput | null; };@@ -998,8 +1006,50 @@ export type DocVersionRefInput = { "id"?: string | null; "path"?: string | null;export type DocsInfoRequestInput = { "av": boolean; "ids": Array<string>; "refCount": boolean; };+export type DocumentAddressingFailure = { "reason": "invalidTitle" | "parentUnavailable" | "planChanged" | "documentIDConflict" | "legacyPathUnsupported" | "indexUnavailable" | "unsupportedTitleFormat" | "targetModeUnsupported" | "modeConflict" | "writeFailed"; };++export type DocumentCapabilities = { "addressingVersion": number; "indexState": "missing" | "building" | "ready" | "error"; "literalSlash": boolean; "minimumReaderVersion": string | null; "modeState": "legacy" | "structured" | "conflict" | "recovering"; "revision": string; "structuredPaths": boolean; "titleFormats": Array<string> | null; };++export type DocumentCreateFailure = { "commitState": "none" | "committed" | "unknown"; "completed": Array<string> | null; "id"?: string; "reason": "invalidTitle" | "parentUnavailable" | "planChanged" | "documentIDConflict" | "indexUnavailable" | "unsupportedTitleFormat" | "modeConflict" | "writeFailed"; "stage": string; };++export type DocumentCreatePlan = { "existingID"?: string; "notebook": string; "steps": Array<CreateDocByParentRequest>; "title": string; };++export type DocumentCreateTarget = (LegacyDocumentTarget & { "anchor"?: never; "onMissingParent"?: never; "parents"?: never; "title"?: never; "up"?: never; }) | (StructuredDocumentTarget & { "path"?: never; });++export type DocumentCreateTargetData = { "docCreateTemplatePath": string; "revision": string; "target": DocumentCreateTarget; };++export type DocumentCreateTitle = { "format": string; "text": string; };++export type DocumentCreateTitleInput = { "format": string; "text": string; };++export type DocumentLocation = { "id": string | null; "notebook": string; "revision": string; };++export type DocumentNameCondition = { "expectedID": string | null; "parentID": string | null; "title": string; };++export type DocumentNameConditionInput = { "expectedID": string | null; "parentID": string | null; "title": string; };++export type DocumentPath = { "addressingVersion": number; "depth": number; "displayPath": string; "id": string; "notebook": string; "parentID": string | null; "path": string; "revision": string; "segments": Array<DocumentPathSegment> | null; "title": DocumentTitle; };++export type DocumentPathSegment = { "empty": boolean; "id": string; "text": string; };++export type DocumentPathStartInput = { "id"?: string; "kind": "root" | "document"; };++export type DocumentPathsData = { "documents": Array<DocumentPath> | null; "missingIDs": Array<string> | null; };++export type DocumentPathsResult = (DocumentPathsData & { "reason"?: never; }) | (DocumentAddressingFailure & { "documents"?: never; "missingIDs"?: never; });+export type DocumentPreviewImage = { "notebook": string; "src": string; "video"?: string; };+export type DocumentTargetAnchor = { "id"?: string; "kind": "notebookRoot" | "context" | "document"; };++export type DocumentTargetAnchorInput = { "id"?: string; "kind": "notebookRoot" | "context" | "document"; };++export type DocumentTargetRevision = { "notebook": string; "purpose": "document" | "reference" | "dailyNote"; "revision": string; };++export type DocumentTargetRevisionInput = { "notebook": string; "purpose": "document" | "reference" | "dailyNote"; "revision": string; };++export type DocumentTitle = { "empty": boolean; "format": "plain"; "text": string; };+export type DownloadCloudSnapshotRequestInput = { "id": string; "tag": string; };export type DownloadInstallPkgRequestInput = { "downloadInstallPkg": boolean; };@@ -1102,6 +1152,8 @@ export type FileTreeCreateRequestInput = { "docCreateTemplatePath"?: string | nuexport type FileTreeCreateSavePathData = { "box": string; "docCreateTemplatePath": string; "path": string; };+export type FileTreeCreateSavePathResult = (FileTreeCreateSavePathData & { "reason"?: never; }) | (StructuredTemplateRequired & { "box"?: never; "docCreateTemplatePath"?: never; "path"?: never; });+export type FileTreeDailyNoteRequestInput = { "app"?: string | null; "date"?: string | null; "notebook": string; };export type FileTreeDocFile = { "children"?: Array<FileTreeDocFile | null>; "id": string; };@@ -1162,7 +1214,9 @@ export type FileTreeReorderRequestInput = { "position"?: string | null; "previewexport type FileTreeSavePathData = { "box": string; "path": string; };-export type FileTreeSearchDoc = { "alias"?: string; "box": string; "boxIcon": string; "dueFlashcardCount"?: string; "flashcardCount"?: string; "hPath": string; "name"?: string; "newFlashcardCount"?: string; "path": string; };+export type FileTreeSavePathResult = (FileTreeSavePathData & { "reason"?: never; }) | (StructuredTemplateRequired & { "box"?: never; "path"?: never; });++export type FileTreeSearchDoc = { "alias"?: string; "box": string; "boxIcon": string; "dueFlashcardCount"?: string; "flashcardCount"?: string; "hPath": string; "name"?: string; "newFlashcardCount"?: string; "path": string; "title"?: string; };export type FileTreeSearchRequestInput = { "excludeIDs"?: Array<string> | null; "flashcard"?: boolean | null; "k": string; };@@ -1248,6 +1302,10 @@ export type GetCloudRepoSnapshotsRequestInput = { "endTime"?: number; "page": nuexport type GetCurrentAttrViewImagesRequestInput = { "blockID"?: string | null; "groupID"?: string | null; "id": string; "query"?: string | null; "viewID"?: string | null; };+export type GetDocCreateTargetRequestInput = { "notebook": string; "purpose": "document" | "reference" | "dailyNote"; };++export type GetDocPathsRequestInput = { "ids": Array<string>; "notebook": string; };+export type GetEmbedBlockRequestInput = { "breadcrumb"?: boolean | null; "embedBlockID": string; "headingMode"?: number | null; "includeIDs": Array<string>; "notebook"?: string | null; };export type GetInstalledIconRequestInput = { "keyword"?: string | null; };@@ -1426,6 +1484,8 @@ export type JSONValue = null | boolean | number | string | Array<JSONValue> | {export type KernelPetal = { "existed": boolean; "incompatible": boolean; "js": string; };+export type LegacyDocumentTarget = { "notebook": string; "path": string; "version": 1; };+export type ListNotebooksData = { "boxDocEnabled": boolean; "notebooks": Array<Notebook | null> | null; };export type ListNotebooksRequestInput = { "flashcard"?: boolean | null; };@@ -1554,11 +1614,11 @@ export type NotebookArchiveCandidatesData = { "notebooks": Array<NotebookArchiveexport type NotebookArchiveData = { "file": string; "id": string; };-export type NotebookConf = { "boxCrypt": NotebookEncryption | null; "closed": boolean; "dailyNoteSavePath": string; "dailyNoteTemplatePath": string; "docCreateSaveBox": string; "docCreateSavePath": string; "docCreateTemplatePath": string; "encrypted": boolean; "icon": string; "name": string; "refCreateSaveBox": string; "refCreateSavePath": string; "sort": number; "sortMode": number; };+export type NotebookConf = { "boxCrypt": NotebookEncryption | null; "closed": boolean; "dailyNoteSavePath": string; "dailyNoteTarget"?: StructuredDocumentTarget; "dailyNoteTemplatePath": string; "docCreateSaveBox": string; "docCreateSavePath": string; "docCreateTarget"?: StructuredDocumentTarget; "docCreateTemplatePath": string; "encrypted": boolean; "icon": string; "name": string; "refCreateSaveBox": string; "refCreateSavePath": string; "refCreateTarget"?: StructuredDocumentTarget; "sort": number; "sortMode": number; };-export type NotebookConfData = { "box": string; "conf": NotebookConf | null; "name": string; };+export type NotebookConfData = { "box": string; "conf": NotebookConf | null; "documentCapabilities"?: DocumentCapabilities; "name": string; };-export type NotebookConfPatchInput = { "boxCrypt"?: NotebookEncryptionPatchInput | null; "closed"?: boolean | null; "dailyNoteSavePath"?: string | null; "dailyNoteTemplatePath"?: string | null; "docCreateSaveBox"?: string | null; "docCreateSavePath"?: string | null; "docCreateTemplatePath"?: string | null; "encrypted"?: boolean | null; "icon"?: string | null; "name"?: string | null; "refCreateSaveBox"?: string | null; "refCreateSavePath"?: string | null; "sort"?: number | null; "sortMode"?: number | null; };+export type NotebookConfPatchInput = { "boxCrypt"?: NotebookEncryptionPatchInput | null; "closed"?: boolean | null; "dailyNoteSavePath"?: string | null; "dailyNoteTarget"?: StructuredDocumentTargetInput | null; "dailyNoteTemplatePath"?: string | null; "docCreateSaveBox"?: string | null; "docCreateSavePath"?: string | null; "docCreateTarget"?: StructuredDocumentTargetInput | null; "docCreateTemplatePath"?: string | null; "encrypted"?: boolean | null; "icon"?: string | null; "name"?: string | null; "refCreateSaveBox"?: string | null; "refCreateSavePath"?: string | null; "refCreateTarget"?: StructuredDocumentTargetInput | null; "sort"?: number | null; "sortMode"?: number | null; };export type NotebookCryptoAutoLockRequestInput = { "autoLockMinutes": number; };@@ -1638,6 +1698,8 @@ export type Petal = { "css": string; "disabledInPublish": boolean; "disallowInstexport type PinnedDoc = { "alias": string; "bookmark": string; "childrenSortMode": number | null; "hCtime": string; "hMtime": string; "hSize": string; "icon": string; "id": string; "memo": string; "name": string; "name1": string; "notebook": string; "path": string; "subFileCount": number; "unavailable": boolean; };+export type PlanDocCreateRequestInput = { "contextID"?: string | null; "date"?: string; "id": string; "notebook": string; "placement"?: "configured" | "child"; "purpose": "document" | "reference" | "dailyNote"; "reuse"?: boolean; "title"?: string; };+export type PluginPublishInfo = { "fields": Array<string>; "granted": boolean; "resources": Array<string>; };export type PluginPublishRequestInput = { "packageName": string; };@@ -1786,6 +1848,12 @@ export type ResetRiffCardsRequestInput = { "blockIDs"?: Array<string> | null; "dexport type ResetSettingsRequestInput = { "exit"?: boolean; };+export type ResolveDocPathRequestInput = { "notebook": string; "segments": Array<string>; "start": DocumentPathStartInput; };++export type ResolveDocPathResult = (ResolvedDocumentPathData & { "reason"?: never; }) | (DocumentAddressingFailure & { "candidates"?: never; "candidatesTruncated"?: never; "nameConditions"?: never; "nextIndex"?: never; "resolved"?: never; "start"?: never; "status"?: never; });++export type ResolvedDocumentPathData = { "candidates": Array<DocumentPath> | null; "candidatesTruncated": boolean; "nameConditions": Array<DocumentNameCondition> | null; "nextIndex": number; "resolved": DocumentPath | null; "start": DocumentLocation; "status": "resolved" | "missing" | "ambiguous"; };+export type ReviewRiffCardRequestInput = { "cardID": string; "deckID": string; "rating": number; "reviewedCards"?: Array<RiffReviewedCardInput> | null; };export type RichClipboardAssetInput = { "box"?: string; "index": number; "path": string; };@@ -2246,6 +2314,12 @@ export type StorageSetKeysRequestInput = { "app"?: string | null; "keyVals": { [export type StorageSetRequestInput = { "app"?: string | null; "key": string; "val"?: JSONValue | null; };+export type StructuredDocumentTarget = { "anchor": DocumentTargetAnchor; "notebook": string; "onMissingParent": "create" | "error"; "parents": Array<string>; "title": string; "up": number; "version": 2; };++export type StructuredDocumentTargetInput = { "anchor": DocumentTargetAnchorInput; "notebook": string; "onMissingParent": "create" | "error"; "parents": Array<string>; "title": string; "up": number; "version": 2; };++export type StructuredTemplateRequired = { "reason": "structuredTemplateRequired"; };+export type SwapBlockRefRequestInput = { "defID": string; "includeChildren": boolean; "originalToEmbed"?: boolean; "refID": string; };export type SyncAssetDownloadModeData = { "assetDownloadMode": number; };@@ -3304,6 +3378,10 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin"];};+ /**+ * 在隔离目录解压并预检完整输出集合的能力记录及文档源,失败时不写入目标。+ * 实际复制仍重新检查目标;后续并发变化或 I/O 失败可能留下已完成条目,不承诺整批回滚。+ */"/api/archive/unzip": {request: UnzipRequestInput;response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -3311,6 +3389,9 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * 的输出位置遵守笔记本能力及原始文档保护,不能用压缩文件覆盖文档源或能力记录。+ */"/api/archive/zip": {request: ZipRequestInput;response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -5192,6 +5273,7 @@ export interface APIPOSTRoutes {};/*** 在写入前检查笔记本寻址模式,不兼容或试图覆盖本机能力下界记录时返回 -1。+ * 目标为文档 ID 路径时,未知格式和标题冲突均返回 -1;实际写入在文件锁内重新校验现有源,不规范化内容。* 工作空间外的加密资源解密导出仍要求既有授权和操作租约。*/"/api/file/copyFile": {@@ -5217,7 +5299,8 @@ export interface APIPOSTRoutes {authorization?: readonly ["authenticated","admin"];};/**- * 在创建目标目录及复制前预检整批笔记本寻址模式;不兼容时返回 -1,不写入部分目标。+ * 在创建目标目录及复制前预检整批笔记本寻址模式和文档源;预检不兼容时返回 -1,不写入目标。+ * 文档 ID 路径同时检查传入内容及现有源,实际写入前再次校验;后续并发变化或 I/O 失败不回滚已完成的复制。* 不允许覆盖本机能力下界记录;原有敏感路径、加密笔记本和符号链接限制继续生效。*/"/api/file/globalCopyFiles": {@@ -5229,6 +5312,8 @@ export interface APIPOSTRoutes {};/*** 在创建目录、写入内容及更新时间前校验笔记本寻址模式和待写配置;不兼容时返回 -1。+ * 文档 ID 路径检查传入内容及现有源的格式和标题;未知格式或标题冲突返回 -1,原文件和时间保持不变。+ * 实际文档写入在同一文件锁内重新校验现有源,保留请求字节;附件和插件文件不按文档格式解释。* 不允许覆盖本机 conf/document-addressing.json,恢复设置时须使用 importConf 的逐身份合并流程。*/"/api/file/putFile": {@@ -5258,6 +5343,7 @@ export interface APIPOSTRoutes {};/*** 在创建目标父目录或移动源文件前预检笔记本寻址能力,不支持的模式返回 -1。+ * 移入由笔记本及文档 ID 组成的 .sy 路径时检查全部源文档;未知格式或标题冲突返回 -1,保留来源。* 不能借重命名覆盖、移动或删除本机 conf/document-addressing.json;既有加密边界不变。*/"/api/file/renameFile": {@@ -5268,7 +5354,8 @@ export interface APIPOSTRoutes {authorization?: readonly ["authenticated","admin","writable"];};/**- * 在创建目标目录及复制前预检整批笔记本寻址模式;不兼容时返回 -1,不写入部分目标。+ * 在创建目标目录及复制前预检整批笔记本寻址模式和文档源;预检不兼容时返回 -1,不写入目标。+ * 文档 ID 路径同时检查传入内容及现有源,实际写入前再次校验;后续并发变化或 I/O 失败不回滚已完成的复制。* 不允许覆盖本机能力下界记录;原有敏感路径、加密笔记本和符号链接限制继续生效。*/"/api/file/workspaceCopyFiles": {@@ -5307,6 +5394,21 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * 在显式父文档 ID 或 null 根位置创建固定 ID 文档,不接收 path/hPath 或名称回退。+ * title.format 首版只接受 plain,text 可为空;无效字符、超长标题及不支持的格式原样拒绝,不截断或清洗。+ * 可选父路径 revision 与至多 128 项名称条件在源提交前分别校验;条件只能涉及目标祖先和最终父级。+ * ID 冲突不覆盖、不自动更换;错误 data 包含稳定 reason、commitState、阶段及已完成步骤。+ * 已落盘但排序或正文模板失败时保留源文档并返回其 ID,调用方不得把该错误当作未创建而重复提交。+ * 当前兼容阶段仍不允许标题包含 /,不提升已有文档 Spec;加密笔记本使用原有认证写入与响应租约。+ */+ "/api/filetree/createDocByParent": {+ request: CreateDocByParentRequestInput;+ response: { "code": 0; "data": CreateDocByParentResult; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null | CreateDocByParentResult; "msg": string; };+ body: "structJSON";+ /** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */+ authorization?: readonly ["authenticated","admin","writable"];+ };/*** 使用编辑器 Markdown 语法选项,并按 `/api/import/importStdMd` 的规则转换标准脚注。* 转义的脚注语法保留为字面文本;返回创建的文档 ID,访问受笔记本权限限制。@@ -5353,13 +5455,41 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated"];};+ /**+ * 旧模板保持既有渲染及回退;对应的新目标对象生效时返回 structuredTemplateRequired,不读取历史路径。+ */"/api/filetree/getDocCreateSavePath": {request: FileTreeNotebookRequestInput;- response: { "code": 0; "data": FileTreeCreateSavePathData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ response: { "code": 0; "data": FileTreeCreateSavePathResult; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null | FileTreeCreateSavePathResult; "msg": string; };body: "json";/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated"];};+ /**+ * 返回指定用途的有效目标及正文模板,不渲染模板、不猜测上下文或日期。+ * version=1 保留旧路径语法;version=2 独立保存祖先和标题段。revision 覆盖生效配置及继承来源,+ * 由配置创建时传回 expectedTarget,配置变化即返回 planChanged。读取需管理员及源笔记本操作租约。+ */+ "/api/filetree/getDocCreateTarget": {+ request: GetDocCreateTargetRequestInput;+ response: { "code": 0; "data": DocumentCreateTargetData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ /** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */+ authorization?: readonly ["authenticated","admin"];+ };+ /**+ * 在指定笔记本内按文档 ID 读取结构化祖先链,要求管理员权限,加密响应保留操作租约。+ * ids 必须包含 1 至 128 项,按首次出现顺序去重;缺失、其他笔记本或内容块身份列入 missingIDs。+ * 文档标题、segments 与 revision 来自同一快照,displayPath 仅用于显示,不能反向解析身份。+ * 索引未就绪返回 indexUnavailable,源格式和认证错误不能伪装成缺失;批量结果不承诺全局快照。+ */+ "/api/filetree/getDocPaths": {+ request: GetDocPathsRequestInput;+ response: { "code": 0; "data": DocumentPathsResult; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null | DocumentPathsResult; "msg": string; };+ body: "json";+ /** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */+ authorization?: readonly ["authenticated","admin"];+ };"/api/filetree/getFullHPathByID": {request: FileTreeOptionalIDRequestInput;response: { "code": 0; "data": string | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -5422,7 +5552,7 @@ export interface APIPOSTRoutes {};"/api/filetree/getRefCreateSavePath": {request: FileTreeNotebookRequestInput;- response: { "code": 0; "data": FileTreeSavePathData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ response: { "code": 0; "data": FileTreeSavePathResult; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null | FileTreeSavePathResult; "msg": string; };body: "json";/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated"];@@ -5483,6 +5613,20 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * 只读编译有效创建目标,同一次计划使用相同时间,日期可指定为 YYYY-MM-DD。+ * contextID 是源笔记本内的文档,child 使用该位置,configured 使用配置目标;title 可显式替换最终标题。+ * 调用方提前保存最终 id,返回步骤已分配全部祖先 ID。按顺序向 createDocByParent 提交,不承诺跨文件原子性。+ * reuse 仅用于明确允许复用的业务。existingID 非空时不再创建;普通新建应保持 reuse=false。+ * 上一步创建父文档后,将其返回的 revision 传为下一步 expectedParentRevision;错误或响应丢失时保留计划核对 ID。+ */+ "/api/filetree/planDocCreate": {+ request: PlanDocCreateRequestInput;+ response: { "code": 0; "data": DocumentCreatePlan; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ /** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */+ authorization?: readonly ["authenticated","admin"];+ };"/api/filetree/removeDoc": {request: FileTreePathRequestInput;response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -5532,6 +5676,23 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * 从显式根位置或父文档 ID 逐级精确匹配 0 至 128 个非空标题段,只解析不创建。+ * 标题不作 Unicode 归一化、宽窄转换或百分号解码;同父同名返回 ambiguous,不任取候选。+ * candidates 按 ID 排序且最多 128 项,candidatesTruncated 标记截断;nameConditions 保留唯一及缺失条件。+ * 空段数组返回起点,根位置的 resolved 为 null,start.id 为 null;笔记本文档 ID 规范化为逻辑根。+ * 索引未就绪返回 indexUnavailable;普通标题仍遵守兼容模式限制,不隐式启用新字符。+ */+ "/api/filetree/resolveDocPath": {+ request: ResolveDocPathRequestInput;+ response: { "code": 0; "data": ResolveDocPathResult; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null | ResolveDocPathResult; "msg": string; };+ body: "json";+ /** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */+ authorization?: readonly ["authenticated","admin"];+ };+ /**+ * 保留兼容展示 hPath,并单独返回文档或笔记本的纯文本 title;客户端不能从 hPath 拆出标题或层级。+ */"/api/filetree/searchDocs": {request: FileTreeSearchRequestInput;response: { "code": 0; "data": Array<FileTreeSearchDoc | null> | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -6122,6 +6283,15 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * preserves existing configuration and permission filtering. Administrator+ * responses also contain documentCapabilities: structuredPaths advertises the ID/segment APIs,+ * not permission to open a closed or locked notebook. literalSlash remains false until structured+ * title mode is implemented and enabled; minimumReaderVersion is null until a protective release+ * is verified. Revision covers configuration and confirmed capability records, not a document path.+ * Malformed capability records fail the request; authentication, locking and network failures must+ * never be interpreted as an absent capability object or as permission to retry a legacy write.+ */"/api/notebook/getNotebookConf": {request: CloseNotebookRequestInput;response: { "code": 0; "data": NotebookConfData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };diff --git a/app/src/util/configuredDocument.test.ts b/app/src/util/configuredDocument.test.tsnew file mode 100644index 0000000000..ab8f32db76--- /dev/null+++ b/app/src/util/configuredDocument.test.ts@@ -0,0 +1,122 @@+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";+import {DocumentCreationAttempt} from "./documentCreationPlan";+import type {DocumentCreatePlan, DocumentPath, PlanDocCreateRequestInput} from "../types/api";++const plan = (): DocumentCreatePlan => ({notebook: "box", title: "Title", steps: [+ {notebook: "box", parentID: null, id: "fixed", title: {format: "plain", text: "Title"}, markdown: ""},+]});+const location = (): DocumentPath => ({notebook: "box", id: "fixed", parentID: null, path: "/fixed.sy", depth: 1,+ segments: [], displayPath: "/Title", revision: "saved", addressingVersion: 1,+ title: {format: "plain", text: "Title", empty: false}});+const input: Omit<PlanDocCreateRequestInput, "id"> = {notebook: "box", contextID: null, purpose: "document"};++function setup(fetch: (url: string, data: unknown) => Promise<unknown>) {+ const methods = {} as typeof import("./configuredDocument");+ const dialogs: Array<{yes: () => void; no: () => void; destroyed: boolean; destroy: () => void}> = [];+ const messages: string[] = [];+ runInNewContext(transpileModule(readFileSync("src/util/configuredDocument.ts", "utf8"), {+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2022},+ }).outputText, {exports: methods, Lute: {NewNodeID: () => "allocated-once"},+ window: {siyuan: {languages: {documentCreationRecovery: "Review", documentCreationLimit: "Limit"}}},+ require: (name: string) => ({+ "./fetch": {fetchSyncPost: fetch},+ "./documentCreationPlan": {DocumentCreationAttempt},+ "./escape": {escapeHtml: (text: string) => text},+ "../dialog/message": {showMessage: (text: string) => messages.push(text)},+ "../dialog/confirmDialog": {confirmDialog: (_title: string, _message: string, yes: () => void, no: () => void) => {+ const dialog = {yes, no, destroyed: false, destroy() { this.destroyed = true; }};+ dialogs.push(dialog);+ return dialog;+ }},+ })[name] || {},+ });+ return {methods, dialogs, messages};+}+const settle = () => new Promise<void>(resolve => setImmediate(resolve));++test("concurrent clicks share one planning request and a locked notebook cannot publish its response", async () => {+ let resolve: (value: unknown) => void;+ let calls = 0;+ const pending = new Promise(value => { resolve = value; });+ const {methods} = setup(async () => { calls++; return pending; });+ const options = {onCreated() { assert.fail("closed notebook published a created document"); }};+ const first = methods.createConfiguredDocument(input, options);+ await methods.createConfiguredDocument(input, options);+ assert.equal(calls, 1);+ methods.clearDocumentCreationPlans("box");+ resolve({code: 0, data: plan()});+ await first;+ assert.equal(calls, 1);+});++test("canceling an unknown result retains the fixed identity until explicit review", async () => {+ const calls: string[] = [];+ const created: string[] = [];+ const {methods, dialogs} = setup(async url => {+ calls.push(url);+ if (url.endsWith("planDocCreate")) {+ return {code: 0, data: plan()};+ }+ if (url.endsWith("getDocPaths")) {+ return {code: 0, data: {documents: [location()], missingIDs: []}};+ }+ throw new Error("response lost");+ });+ const options = {onCreated: (id: string) => created.push(id)};+ await methods.createConfiguredDocument(input, options);+ dialogs[0].no();+ await methods.createConfiguredDocument(input, options);+ assert.equal(calls.length, 2);+ dialogs[1].yes();+ await settle();+ assert.deepEqual(created, ["fixed"]);+ assert.equal(calls.filter(url => url.endsWith("createDocByParent")).length, 1);+});++test("an explicitly reviewed missing document retries its original ID", async () => {+ const submitted: string[] = [];+ const created: string[] = [];+ const {methods, dialogs} = setup(async (url, request) => {+ if (url.endsWith("planDocCreate")) {+ return {code: 0, data: plan()};+ }+ if (url.endsWith("getDocPaths")) {+ return {code: 0, data: {documents: [], missingIDs: ["fixed"]}};+ }+ submitted.push((request as {id: string}).id);+ if (submitted.length === 1) {+ throw new Error("connection lost");+ }+ return {code: 0, data: {id: "fixed", document: location()}};+ });+ await methods.createConfiguredDocument(input, {onCreated: id => created.push(id)});+ dialogs[0].yes();+ await settle();+ assert.deepEqual(submitted, ["fixed", "fixed"]);+ assert.deepEqual(created, ["fixed"]);+});++test("locking closes recovery dialogs and suppresses their in-flight callbacks", async () => {+ let resolve: (value: unknown) => void;+ const pending = new Promise(value => { resolve = value; });+ const {methods, dialogs, messages} = setup(async url => {+ if (url.endsWith("planDocCreate")) {+ return {code: 0, data: plan()};+ }+ if (url.endsWith("getDocPaths")) {+ return pending;+ }+ throw new Error("connection lost");+ });+ await methods.createConfiguredDocument(input, {onCreated() { assert.fail("locked callback ran"); }});+ methods.clearDocumentCreationPlans("box");+ assert.equal(dialogs[0].destroyed, true);+ dialogs[0].yes();+ resolve({code: 0, data: {documents: [location()], missingIDs: []}});+ await settle();+ assert.equal(messages.length, 0);+});diff --git a/app/src/util/configuredDocument.ts b/app/src/util/configuredDocument.tsnew file mode 100644index 0000000000..40d4d2c619--- /dev/null+++ b/app/src/util/configuredDocument.ts@@ -0,0 +1,144 @@+import {fetchSyncPost} from "./fetch";+import {documentParentID} from "./documentCreate";+import {DocumentCreationAttempt} from "./documentCreationPlan";+import {showMessage} from "../dialog/message";+import {escapeHtml} from "./escape";+import {confirmDialog} from "../dialog/confirmDialog";+import type {Dialog} from "../dialog";+import type {DocumentCreatePlan, PlanDocCreateRequestInput} from "../types/api";++const attempts = new Map<string, {notebooks: string[]; attempt: DocumentCreationAttempt}>();+const maximumAttempts = 32;+const activeInputs = new Set<string>();+let lifecycleRevision = 0;+const recoveryDialogs = new Map<Dialog, string[]>();++export const clearDocumentCreationPlans = (notebook: string) => {+ lifecycleRevision++;+ for (const [dialog, notebooks] of recoveryDialogs) {+ if (notebooks.includes(notebook)) {+ recoveryDialogs.delete(dialog);+ dialog.destroy();+ }+ }+ for (const [key, value] of attempts) {+ if (value.notebooks.includes(notebook)) {+ // 关闭或锁定后不能继续保留标题和已求值模板。+ value.attempt.plan.steps.length = 0;+ value.attempt.plan.title = "";+ attempts.delete(key);+ }+ }+};++export const previewConfiguredDocument = (notebook: string, currentPath: string, purpose: "document" | "reference",+ title?: string, placement: "configured" | "child" = "configured", reuse = false,+ id = Lute.NewNodeID()) => {+ return fetchSyncPost("/api/filetree/planDocCreate", {+ notebook, contextID: documentParentID(currentPath || "/"), purpose, title, placement, reuse, id,+ });+};++export const createConfiguredDocument = async (input: Omit<PlanDocCreateRequestInput, "id"> & {id?: string}, options: {+ isValid?: () => boolean;+ onCreated: (id: string, title: string) => void;+ sortTargetID?: string;+ sortPosition?: "before" | "after";+ listDocTree?: boolean;+ plan?: DocumentCreatePlan;+}) => {+ const key = JSON.stringify(input);+ if (activeInputs.has(key)) {+ return;+ }+ activeInputs.add(key);+ const revision = lifecycleRevision;+ const isValid = () => lifecycleRevision === revision && (!options.isValid || options.isValid());+ let retained = attempts.get(key);+ try {+ if (!isValid()) {+ return;+ }+ if (!retained) {+ if (attempts.size + activeInputs.size > maximumAttempts) {+ showMessage(window.siyuan.languages.documentCreationLimit, 0, "error");+ return;+ }+ let plan = options.plan;+ if (!plan) {+ const response = await fetchSyncPost("/api/filetree/planDocCreate", {...input, id: input.id || Lute.NewNodeID()});+ if (response.code !== 0 || !response.data || !isValid()) {+ return;+ }+ plan = response.data;+ }+ const last = plan.steps[plan.steps.length - 1];+ if (last) {+ last.sortTargetID = options.sortTargetID;+ last.sortPosition = options.sortPosition;+ last.listDocTree = options.listDocTree;+ }+ retained = {notebooks: [input.notebook, plan.notebook], attempt: new DocumentCreationAttempt(plan)};+ attempts.set(key, retained);+ }+ const attempt = retained.attempt;+ const id = await attempt.execute(request => fetchSyncPost("/api/filetree/createDocByParent", request), isValid);+ if (id && attempts.get(key) === retained) {+ attempts.delete(key);+ if (isValid()) {+ options.onCreated(id, attempt.plan.title);+ }+ }+ } catch (error) {+ if (lifecycleRevision !== revision) {+ return;+ }+ const attempt = retained?.attempt;+ // 只展示身份链接;保留原计划,未知结果和已提交副作用不自动继续。+ const ids = [...attempt?.completed || [], ...attempt?.uncertainID ? [attempt.uncertainID] : []];+ const message = `${escapeHtml((error as Error).message)}${ids.map(id =>+ ` <a href="siyuan://blocks/${id}">${id}</a>`).join("")}`;+ if (!attempt || !attempt.completed.length && !attempt.requiresReview) {+ attempts.delete(key);+ showMessage(message, 0, "error");+ return;+ }+ const dialog = confirmDialog(window.siyuan.languages.newFile,+ `${message}<br><br>${escapeHtml(window.siyuan.languages.documentCreationRecovery)}`, () => {+ recoveryDialogs.delete(dialog);+ void (async () => {+ if (attempts.get(key) !== retained || options.isValid && !options.isValid()) {+ return;+ }+ if (attempt.requiresReview) {+ const step = attempt.plan.steps[attempt.next];+ const response = await fetchSyncPost("/api/filetree/getDocPaths", {notebook: step.notebook, ids: [step.id]});+ if (response.code !== 0 || !response.data || !("documents" in response.data)) {+ return;+ }+ if (attempts.get(key) !== retained) {+ return;+ }+ const document = response.data.documents.find(value => value.id === step.id);+ if (!document && !response.data.missingIDs.includes(step.id)) {+ throw new Error(window.siyuan.languages.documentCreationRecovery);+ }+ attempt.review(document);+ }+ await createConfiguredDocument(input, options);+ })().catch(error => {+ if (attempts.get(key) === retained) {+ showMessage(escapeHtml(error.message), 0, "error");+ }+ });+ }, () => {+ recoveryDialogs.delete(dialog);+ if (lifecycleRevision === revision) {+ showMessage(message, 0, "error");+ }+ });+ recoveryDialogs.set(dialog, retained.notebooks);+ } finally {+ activeInputs.delete(key);+ }+};diff --git a/app/src/util/documentCreate.test.ts b/app/src/util/documentCreate.test.tsnew file mode 100644index 0000000000..a4c8680117--- /dev/null+++ b/app/src/util/documentCreate.test.ts@@ -0,0 +1,28 @@+import * as assert from "node:assert/strict";+import {test} from "node:test";+import {createdDocumentID, documentCreateRequest, documentParentID} from "./documentCreate";++const notebook = "20261023000000-box0001";+const parent = "20261023000001-parent1";+const id = "20261023000002-newdoc1";++test("document creation keeps ID location and literal title independent", () => {+ assert.equal(documentParentID("/"), null);+ assert.equal(documentParentID(`/${parent}.sy`), parent);+ assert.equal(documentParentID(`/${notebook}/${parent}.sy`), parent);+ assert.deepEqual(documentCreateRequest(notebook, `/${parent}.sy`, id, "**A/B &**", "Body"), {+ notebook, parentID: parent, id, title: {format: "plain", text: "**A/B &**"}, markdown: "Body",+ });+ assert.equal(documentCreateRequest(notebook, "/", id, "").title.text, "");+ for (const value of ["", "/A/B", "../" + parent, `//${parent}.sy`, `/${parent}/`, `/${parent}/../${id}.sy`]) {+ assert.throws(() => documentParentID(value));+ }+});++test("creation callbacks use only confirmed source identities", () => {+ assert.equal(createdDocumentID({id, document: {id}}), id);+ assert.equal(createdDocumentID({id, commitState: "committed", stage: "template"}), id);+ for (const value of [null, {id}, {id, commitState: "none"}, {id, commitState: "unknown"}, {id: "invalid", document: {}}]) {+ assert.equal(createdDocumentID(value), undefined);+ }+});diff --git a/app/src/util/documentCreate.ts b/app/src/util/documentCreate.tsnew file mode 100644index 0000000000..cf6b86fa9f--- /dev/null+++ b/app/src/util/documentCreate.ts@@ -0,0 +1,35 @@+import type {CreateDocByParentRequestInput} from "../types/api";++const documentIDPattern = /^\d{14}-[a-z0-9]{7}$/;++/** 从已知 ID 数据路径取得父身份,标题和展示路径不能传入这里。 */+export const documentParentID = (dataPath: string): string | null => {+ if (dataPath === "/") {+ return null;+ }+ const segments = dataPath.replace(/\.sy$/, "").split("/");+ if (segments.shift() !== "" || !segments.length || segments.some(segment => !documentIDPattern.test(segment))) {+ throw new Error("Invalid document data path");+ }+ return segments[segments.length - 1];+};++export const documentCreateRequest = (notebook: string, parentPath: string, id: string, title: string,+ markdown = ""): CreateDocByParentRequestInput => ({+ notebook,+ parentID: documentParentID(parentPath),+ id,+ title: {format: "plain", text: title},+ markdown,+});++/** 后续模板失败不抹掉已提交文档的身份;未知提交状态不能当作成功或换 ID 重试。 */+export const createdDocumentID = (data: unknown): string | undefined => {+ if (!data || typeof data !== "object" || !("id" in data) || typeof data.id !== "string" ||+ !documentIDPattern.test(data.id)) {+ return;+ }+ if ("document" in data || "commitState" in data && data.commitState === "committed") {+ return data.id;+ }+};diff --git a/app/src/util/documentCreationPlan.test.ts b/app/src/util/documentCreationPlan.test.tsnew file mode 100644index 0000000000..4dc985de92--- /dev/null+++ b/app/src/util/documentCreationPlan.test.ts@@ -0,0 +1,100 @@+import * as assert from "node:assert/strict";+import {test} from "node:test";+import {DocumentCreationAttempt} from "./documentCreationPlan";+import type {CreateDocByParentRequestInput, DocumentCreatePlan, DocumentPath} from "../types/api";++const fixture = (): DocumentCreatePlan => ({+ notebook: "notebook", title: "Final title",+ steps: [+ {notebook: "notebook", parentID: null, id: "parent", title: {format: "plain", text: "Parent"}, markdown: ""},+ {notebook: "notebook", parentID: "parent", id: "child", title: {format: "plain", text: "Final title"}, markdown: ""},+ ],+});++const document = (id: string): DocumentPath => ({+ id, notebook: "notebook", path: `/${id}.sy`, parentID: null, title: {format: "plain", text: id, empty: false},+ segments: [], depth: 1, displayPath: `/${id}`, revision: `${id}-revision`, addressingVersion: 1,+});++test("the original IDs and committed parent revision are used by the next step", async () => {+ const attempt = new DocumentCreationAttempt(fixture());+ const requests: CreateDocByParentRequestInput[] = [];+ const id = await attempt.execute(async request => {+ requests.push({...request});+ return {code: 0, msg: "", data: {id: request.id, document: document(request.id)}};+ });+ assert.equal(id, "child");+ assert.deepEqual(requests.map(request => request.id), ["parent", "child"]);+ assert.equal(requests[1].expectedParentRevision, "parent-revision");+ assert.deepEqual(attempt.completed, ["parent", "child"]);+});++test("a known uncommitted failure retains the remainder and never recreates completed ancestors", async () => {+ const attempt = new DocumentCreationAttempt(fixture());+ await assert.rejects(attempt.execute(async request => request.id === "parent"+ ? {code: 0, msg: "", data: {id: request.id, document: document(request.id)}}+ : {code: -1, msg: "changed", data: {commitState: "none"}}), /changed/);+ const retried: string[] = [];+ await attempt.execute(async request => {+ retried.push(request.id);+ return {code: 0, msg: "", data: {id: request.id, document: document(request.id)}};+ });+ assert.deepEqual(retried, ["child"]);+});++test("lost responses and committed post-processing failures stop automatic replay", async () => {+ for (const unknown of [false, true]) {+ const attempt = new DocumentCreationAttempt(fixture());+ let requests = 0;+ const submit = async () => {+ requests++;+ if (unknown) {+ throw new Error("connection lost");+ }+ return {code: -1, msg: "template failed", data: {commitState: "committed" as const, id: "parent"}};+ };+ await assert.rejects(attempt.execute(submit));+ await assert.rejects(attempt.execute(submit));+ assert.equal(requests, 1);+ assert.equal(attempt.requiresReview, true);+ assert.equal(unknown ? attempt.uncertainID : attempt.completed[0], "parent");+ }+});++test("invalidated editor context prevents subsequent writes", async () => {+ const attempt = new DocumentCreationAttempt(fixture());+ let valid = true;+ const requests: string[] = [];+ assert.equal(await attempt.execute(async request => {+ requests.push(request.id);+ valid = false;+ return {code: 0, msg: "", data: {id: request.id, document: document(request.id)}};+ }, () => valid), undefined);+ assert.deepEqual(requests, ["parent"]);+});++test("explicit recovery verifies fixed identity and skips committed side effects", async () => {+ const attempt = new DocumentCreationAttempt(fixture());+ await assert.rejects(attempt.execute(async () => {throw new Error("lost");}));+ assert.throws(() => attempt.review({...document("parent"), title: {format: "plain", text: "Changed", empty: false}}));+ attempt.review({...document("parent"), title: {format: "plain", text: "Parent", empty: false}});+ const retried: string[] = [];+ await attempt.execute(async request => {+ retried.push(request.id);+ assert.equal(request.expectedParentRevision, "parent-revision");+ return {code: 0, msg: "", data: {id: request.id, document: document(request.id)}};+ });+ assert.deepEqual(retried, ["child"]);+});++test("an authoritatively missing unknown result retries the original ID after review", async () => {+ const attempt = new DocumentCreationAttempt(fixture());+ await assert.rejects(attempt.execute(async () => {throw new Error("lost");}));+ attempt.review();+ const retried: string[] = [];+ await attempt.execute(async request => {+ retried.push(request.id);+ return {code: 0, msg: "", data: {id: request.id, document: document(request.id)}};+ });+ assert.deepEqual(retried, ["parent", "child"]);+});diff --git a/app/src/util/documentCreationPlan.ts b/app/src/util/documentCreationPlan.tsnew file mode 100644index 0000000000..cd7c4fb627--- /dev/null+++ b/app/src/util/documentCreationPlan.ts@@ -0,0 +1,107 @@+import type {CreateDocByParentRequestInput, DocumentCreatePlan, DocumentPath} from "../types/api";++export type DocumentPlanResponse = {+ code: number;+ msg: string;+ data?: {id: string; document: DocumentPath} | {commitState: "none" | "committed" | "unknown"; id?: string} |+ {closeTimeout: number} | null;+};++/** 一个计划只保留一组 ID;后续处理失败或响应不明时不自动重放副作用。 */+export class DocumentCreationAttempt {+ public next = 0;+ public completed: string[] = [];+ public uncertainID: string;+ public failure: Error;+ public requiresReview = false;+ public running = false;++ constructor(public plan: DocumentCreatePlan) {}++ /** 用户确认后核对固定身份;已存在文档只跳过创建,不重放模板或排序。 */+ review(document?: DocumentPath) {+ if (this.running || !this.requiresReview) {+ return;+ }+ const step = this.plan.steps[this.next];+ if (!step) {+ throw new Error("Document creation plan is no longer available");+ }+ if (document) {+ const sameParent = document.parentID === step.parentID ||+ document.parentID === null && step.parentID === step.notebook;+ const sameTitle = step.title.text === "" ? document.title.empty :+ !document.title.empty && document.title.text === step.title.text;+ if (document.id !== step.id || document.notebook !== step.notebook || !sameParent || !sameTitle) {+ throw new Error("Document changed after creation; review the document before creating another");+ }+ if (!this.completed.includes(document.id)) {+ this.completed.push(document.id);+ }+ this.next++;+ const next = this.plan.steps[this.next];+ if (next?.parentID === document.id) {+ next.expectedParentRevision = document.revision;+ }+ } else if (this.completed.includes(step.id)) {+ throw new Error("The committed document is no longer available");+ }+ this.uncertainID = undefined;+ this.failure = undefined;+ this.requiresReview = false;+ }++ async execute(submit: (request: CreateDocByParentRequestInput) => Promise<DocumentPlanResponse>,+ isValid = () => true): Promise<string | undefined> {+ if (this.running) {+ return;+ }+ if (this.requiresReview) {+ throw this.failure;+ }+ if (this.plan.existingID) {+ return isValid() ? this.plan.existingID : undefined;+ }+ this.running = true;+ try {+ while (this.next < this.plan.steps.length) {+ if (!isValid()) {+ return;+ }+ const step = this.plan.steps[this.next];+ let response: DocumentPlanResponse;+ try {+ response = await submit(step);+ } catch (error) {+ this.uncertainID = step.id;+ this.requiresReview = true;+ throw error;+ }+ if (response.code !== 0 || !response.data || !("document" in response.data)) {+ if (response.data && "commitState" in response.data) {+ if (response.data.commitState === "committed" && response.data.id) {+ this.completed.push(response.data.id);+ this.requiresReview = true;+ } else if (response.data.commitState === "unknown") {+ this.uncertainID = step.id;+ this.requiresReview = true;+ }+ }+ throw new Error(response.msg);+ }+ this.completed.push(response.data.id);+ this.next++;+ const next = this.plan.steps[this.next];+ if (next?.parentID === response.data.id) {+ next.expectedParentRevision = response.data.document.revision;+ }+ }+ return this.completed[this.completed.length - 1];+ } catch (error) {+ this.failure = error instanceof Error ? error : new Error(String(error));+ throw this.failure;+ } finally {+ this.running = false;+ }+ }+}diff --git a/app/src/util/newFile.test.ts b/app/src/util/newFile.test.tsindex c68262acb0..0cea1f217b 100644--- a/app/src/util/newFile.test.ts+++ b/app/src/util/newFile.test.ts@@ -20,17 +20,12 @@ test("an empty detached window creates documents using the first open notebook","../layout/dock/Files": {Files: class {}},"../editor": {Editor: class {}},"./pathName": {getOpenNotebookCount: () => 1},- "./fetch": {fetchPost: (url: string, data: unknown, callback: (response: unknown) => void) => {- requests.push({url, data});- if (url === "/api/filetree/getDocCreateSavePath") {- callback({data: {box: "open", path: "", docCreateTemplatePath: ""}});- }- }},+ "./configuredDocument": {createConfiguredDocument: (data: unknown) => requests.push({url: "configured", data})},})[name] || {},});methods.newFile({} as App);- assert.equal(requests[0].url, "/api/filetree/getDocCreateSavePath");- assert.equal(JSON.stringify(requests[0].data), JSON.stringify({notebook: "open"}));- assert.equal(requests[1].url, "/api/filetree/getHPathByPath");- assert.equal(JSON.stringify(requests[1].data), JSON.stringify({notebook: "open", path: "/"}));+ assert.equal(requests[0].url, "configured");+ assert.equal(JSON.stringify(requests[0].data), JSON.stringify({+ notebook: "open", contextID: null, purpose: "document", placement: "configured",+ }));});diff --git a/app/src/util/newFile.ts b/app/src/util/newFile.tsindex 9f75d504b1..b325601f77 100644--- a/app/src/util/newFile.ts+++ b/app/src/util/newFile.ts@@ -7,19 +7,12 @@ import {openFileById} from "../editor/util";import {getActiveTab, getDockByType} from "../layout/tabUtil";/// #endifimport {fetchPost, fetchSyncPost} from "./fetch";-import {getDisplayName, getOpenNotebookCount, isMoveTargetAllowed, movePathTo, pathPosix} from "./pathName";+import {getOpenNotebookCount, isMoveTargetAllowed, movePathTo} from "./pathName";import {Constants} from "../constants";import {replaceFileName, validateName} from "../editor/rename";import {hideElements} from "../protyle/ui/hideElements";import {openMobileFileById} from "../mobile/editor";import type {App} from "../index";-import {- NewDocTargetByHPath,- NewDocTargetSubDoc,- getNewDocTargetFromSavePath,- getNewDocTargetFromTree,- isCurrentDocSubDocTarget-} from "./parseNewDocTarget";import {selectAll} from "../protyle/util/selection";import {focusByRange} from "../protyle/util/selectionOffsets";import {@@ -31,6 +24,8 @@ import {NewFileSelectionContext} from "./newFileSelection";import {getContenteditableElement} from "../protyle/wysiwyg/getBlock";+import {createdDocumentID, documentCreateRequest, documentParentID} from "./documentCreate";+import {createConfiguredDocument, previewConfiguredDocument} from "./configuredDocument";export const getBlockRefAnchorText = (title: string) => {const trimmed = (title || "").trim();@@ -134,32 +129,16 @@ const insertNewFileRef = (protyle: IProtyle, context: NewFileSelectionContext, i};export const newFileBySelect = (protyle: IProtyle, newFileName: string, context: NewFileSelectionContext,- pathDir: string, targetNotebookId: string, refSubtype: "d" | "s" = "d") => {+ placement: "child" | "configured", refSubtype: "d" | "s" = "d") => {if (!isNewFileSelectionValid(protyle, context)) {return;}- const hPath = pathPosix().join(pathDir, newFileName || window.siyuan.languages._kernel[16]);- fetchPost("/api/filetree/getIDsByHPath", {- path: hPath,- notebook: targetNotebookId- }, (idResponse) => {- const refText = getBlockRefAnchorText(newFileName);- if (idResponse.data && idResponse.data.length > 0) {- insertNewFileRef(protyle, context, idResponse.data[0], refText, refSubtype);- } else {- if (!isNewFileSelectionValid(protyle, context)) {- return;- }- fetchPost("/api/filetree/createDocWithMd", {- notebook: targetNotebookId,- path: hPath,- parentID: context.notebookId === targetNotebookId ? context.rootID : "",- markdown: "",- titleEmpty: newFileName === "",- }, response => {- insertNewFileRef(protyle, context, response.data, refText, refSubtype);- });- }+ void createConfiguredDocument({+ notebook: context.notebookId, contextID: context.rootID, purpose: "reference",+ title: newFileName, placement, reuse: true,+ }, {+ isValid: () => !!isNewFileSelectionValid(protyle, context),+ onCreated: id => insertNewFileRef(protyle, context, id, getBlockRefAnchorText(newFileName), refSubtype),});};@@ -187,55 +166,14 @@ export const newFileBySelectRange = (protyle: IProtyle, range: Range, target: "sif (!selectionContext) {return;}- const sourceNotebookId = selectionContext.notebookId;- const sourcePath = selectionContext.path;const fileName = name === undefined ? (selectText.trim() ||protyle.lute.BlockDOM2Content(nodeElement.outerHTML).replace(/\n/g, "").trim()) : name.trim();const newFileName = replaceFileName(fileName);- if (target === "subDoc") {- fetchPost("/api/filetree/getHPathByPath", {- notebook: sourceNotebookId,- path: sourcePath,- }, (response) => {- newFileBySelect(protyle, newFileName, selectionContext, response.data, sourceNotebookId, refSubtype);- });- } else {- getRefCreateSavePath(sourceNotebookId, sourcePath, (targetNotebookId, hPath) => {- newFileBySelect(protyle, newFileName, selectionContext, hPath, targetNotebookId, refSubtype);- });- }+ newFileBySelect(protyle, newFileName, selectionContext, target === "subDoc" ? "child" : "configured", refSubtype);hideElements(["toolbar"], protyle);};-export const getRefCreateSavePath = (notebookId: string, currentPath: string, cb: (targetNotebookId: string, hPath: string) => void) => {- fetchPost("/api/filetree/getRefCreateSavePath", {- notebook: notebookId- }, (data) => {- let targetPath = currentPath;- if (notebookId !== data.data.box) {- targetPath = data.data.path || "/";- }- if (data.data.path) {- if (data.data.path.startsWith("/")) {- cb(data.data.box, getDisplayName(data.data.path, false, true));- } else {- fetchPost("/api/filetree/getHPathByPath", {- notebook: data.data.box,- path: targetPath- }, (response) => {- cb(data.data.box, getDisplayName(pathPosix().join(response.data, data.data.path), false, true));- });- }- } else {- fetchPost("/api/filetree/getHPathByPath", {- notebook: data.data.box,- path: targetPath- }, (response) => {- cb(data.data.box, getDisplayName(response.data, false, true));- });- }- });-};+function getNewFilePath(): Pick<NewDocRequest, "notebookId" | "currentPath" | "hasFocusTarget"> {let notebookId = "";@@ -279,154 +217,39 @@ function getNewFilePath(): Pick<NewDocRequest, "notebookId" | "currentPath" | "hreturn {notebookId, currentPath, hasFocusTarget};}-function runNewDoc(request: NewDocRequest) {- fetchPost("/api/filetree/getDocCreateSavePath", {notebook: request.notebookId}, (savePathResponse) => {- const templatePath = savePathResponse.data.path as string;- const docCreateTemplatePath = savePathResponse.data.docCreateTemplatePath as string;- const targetNotebookId = savePathResponse.data.box as string;- getNewDocHPath(targetNotebookId, request.notebookId, request.currentPath, (hPath) => {- createNewDoc(request, templatePath, docCreateTemplatePath, targetNotebookId, hPath);- });- });-}--function getNewDocHPath(targetNotebookId: string, currentNotebookId: string, currentPath: string, callback: (hPath: string) => void) {- if (targetNotebookId !== currentNotebookId) {- // 跨笔记本时当前文档路径在目标笔记本中不存在,直接按目标笔记本根路径解析- callback("/");- return;- }- fetchPost("/api/filetree/getHPathByPath", {- notebook: targetNotebookId,- path: currentPath,- }, (hPathResponse) => {- callback(hPathResponse.data);+function runNewDoc(request: NewDocRequest, placement: "configured" | "child" = "configured") {+ void createConfiguredDocument({+ notebook: request.notebookId,+ contextID: request.hasFocusTarget ? documentParentID(request.currentPath || "/") : null,+ purpose: "document", title: request.name, placement,+ }, {+ sortTargetID: request.sortTargetID, sortPosition: request.sortPosition, listDocTree: request.listDocTree,+ onCreated: (id, title) => openCreatedDoc(request.app, id, request.onCreated, title),});}/** 判断配置的新建位置是否与在当前文档下直接创建子文档等价 */-export const isConfiguredCreateTargetCurrentSubDoc = async (- protyle: IProtyle,- type: "doc" | "ref",-) => {+export const isConfiguredCreateTargetCurrentSubDoc = async (protyle: IProtyle, type: "doc" | "ref") => {if (!protyle.notebookId || !protyle.path) {return false;}- const savePathResponse = await fetchSyncPost(- type === "doc" ? "/api/filetree/getDocCreateSavePath" : "/api/filetree/getRefCreateSavePath",- {notebook: protyle.notebookId},- );- if (savePathResponse.code !== 0 || !savePathResponse.data) {+ const response = await previewConfiguredDocument(protyle.notebookId, protyle.path,+ type === "doc" ? "document" : "reference", type === "ref" ? "__siyuan_ref_target__" : undefined);+ if (response.code !== 0 || !response.data || response.data.steps.length !== 1) {return false;}- const targetNotebookId = savePathResponse.data.box as string;- if (targetNotebookId !== protyle.notebookId) {- return false;- }- const templatePath = (savePathResponse.data.path as string || "").trim();- if (!templatePath) {- return true;- }- const hPathResponse = await fetchSyncPost("/api/filetree/getHPathByPath", {- notebook: protyle.notebookId,- path: protyle.path,- });- if (hPathResponse.code !== 0 || typeof hPathResponse.data !== "string") {- return false;- }- const title = type === "ref" ? "__siyuan_ref_target__" : "";- const target = getNewDocTargetFromSavePath({- templatePath,- hPath: hPathResponse.data || "/",- targetNotebookId,- currentNotebookId: protyle.notebookId,- name: title || undefined,- hasFocusTarget: true,- currentPath: protyle.path,- });- return isCurrentDocSubDocTarget({- target,- currentNotebookId: protyle.notebookId,- currentPath: protyle.path,- currentHPath: hPathResponse.data || "/",- title,- });+ const step = response.data.steps[0];+ return step.notebook === protyle.notebookId && step.parentID === documentParentID(protyle.path) &&+ (type === "ref" || step.title.text === "");};-function createNewDoc(request: NewDocRequest, templatePath: string, docCreateTemplatePath: string,- targetNotebookId: string, hPath: string) {- const target = getNewDocTargetFromSavePath({- templatePath,- hPath: hPath || "/",- targetNotebookId,- currentNotebookId: request.notebookId,- name: request.name,- hasFocusTarget: request.hasFocusTarget,- currentPath: request.currentPath,- });- if (target.kind === "hPath") {- createNewDocByHPath(request, target, docCreateTemplatePath);- } else if (target.kind === "subDoc") {- createNewDocAsSubDoc(request, target, docCreateTemplatePath);- }-}-function runNewDocInTree(request: NewDocRequest) {- fetchPost("/api/filetree/getDocCreateSavePath", {notebook: request.notebookId}, (savePathResponse) => {- const target = getNewDocTargetFromTree({- templatePath: savePathResponse.data.path as string,- currentNotebookId: request.notebookId,- currentPath: request.currentPath,- name: request.name,- });- createNewDocAsSubDoc(request, target, savePathResponse.data.docCreateTemplatePath as string);- });-}--/** 同笔记本 + 有聚焦 + 非根路径 时取当前文档 ID */-function getCreateDocParentID(hasFocusTarget: boolean, notebookId: string, currentPath: string, targetNotebookId: string): string | undefined {- return hasFocusTarget && notebookId === targetNotebookId && currentPath !== "/"- ? getDisplayName(currentPath, true, true)- : undefined;-}--function createNewDocByHPath(request: NewDocRequest, target: NewDocTargetByHPath, docCreateTemplatePath: string) {- if (target.title && !validateName(target.title)) {- return;- }- const parentID = getCreateDocParentID(request.hasFocusTarget, request.notebookId, request.currentPath, target.targetNotebookId);- fetchPost("/api/filetree/createDocWithMd", {- notebook: target.targetNotebookId,- path: target.hPath,- parentID,- markdown: "",- titleEmpty: !target.title,- docCreateTemplatePath,- }, (response) => {- openCreatedDoc(request.app, response.data, request.onCreated, target.title);- });-}--function createNewDocAsSubDoc(request: NewDocRequest, target: NewDocTargetSubDoc, docCreateTemplatePath: string) {- const id = Lute.NewNodeID();- const newPath = pathPosix().join(getDisplayName(target.parentPath, false, true), id + ".sy");- fetchPost("/api/filetree/createDoc", {- notebook: target.targetNotebookId,- path: newPath,- title: target.title,- md: "",- docCreateTemplatePath,- sortTargetID: request.sortTargetID,- sortPosition: request.sortPosition,- listDocTree: request.listDocTree,- }, () => {- openCreatedDoc(request.app, id, request.onCreated, target.title);- });+ runNewDoc(request, "child");}export const getDocCreateTemplatePath = (notebookId: string, callback: (templatePath: string) => void) => {- fetchPost("/api/filetree/getDocCreateSavePath", {notebook: notebookId}, (response) => {- callback(response.data.docCreateTemplatePath as string);+ fetchPost("/api/filetree/getDocCreateTarget", {notebook: notebookId, purpose: "document"}, (response) => {+ callback(response.data.docCreateTemplatePath);});};@@ -457,27 +280,10 @@ export const newFileByRefHint = (onCreated?: (id: string, title: string) => void,presetId?: string,) => {- const requestName = replaceFileName(name.trim());- fetchPost("/api/filetree/getRefCreateSavePath", {notebook: protyle.notebookId}, (savePathResponse) => {- const templatePath = savePathResponse.data.path as string;- const targetNotebookId = savePathResponse.data.box as string;- getNewDocHPath(targetNotebookId, protyle.notebookId, protyle.path, (hPath) => {- const target = getNewDocTargetFromSavePath({- templatePath,- hPath: hPath || "/",- targetNotebookId,- currentNotebookId: protyle.notebookId,- name: requestName,- hasFocusTarget: true,- currentPath: protyle.path,- });- if (target.kind === "hPath") {- createRefDocByHPath(protyle, target, onCreated, presetId);- } else {- createRefDocAsSubDoc(target, onCreated, presetId);- }- });- });+ void createConfiguredDocument({+ notebook: protyle.notebookId, contextID: documentParentID(protyle.path), purpose: "reference",+ title: replaceFileName(name.trim()), id: presetId,+ }, {onCreated: (id, title) => onCreated?.(id, title)});};/** 选择本次块引新建位置,创建前后均校验原文档和选区 */@@ -549,50 +355,27 @@ export const newSubDocByRefHint = (onCreated?: (id: string, title: string) => void,presetId?: string,) => {- const target = getNewDocTargetFromTree({- templatePath: "",- currentNotebookId: protyle.notebookId,- currentPath: protyle.path,- name: replaceFileName(name.trim()),- });- createRefDocAsSubDoc(target, onCreated, presetId);+ createRefDocAsSubDoc({+ kind: "subDoc", targetNotebookId: protyle.notebookId, parentPath: protyle.path,+ title: replaceFileName(name.trim()),+ }, onCreated, presetId);};-function createRefDocByHPath(- protyle: IProtyle,- target: NewDocTargetByHPath,- onCreated?: (id: string, title: string) => void,- presetId?: string,-) {- if (target.title && !validateName(target.title)) {- return;- }- const parentID = getCreateDocParentID(true, protyle.notebookId, protyle.path, target.targetNotebookId);- fetchPost("/api/filetree/createDocWithMd", {- notebook: target.targetNotebookId,- path: target.hPath,- parentID,- markdown: "",- titleEmpty: !target.title,- id: presetId,- }, (response) => {- onCreated?.(response.data, target.title || "");- });-}+function createRefDocAsSubDoc(- target: NewDocTargetSubDoc,+ target: {kind: "subDoc"; targetNotebookId: string; parentPath: string; title: string},onCreated?: (id: string, title: string) => void,presetId?: string,) {const id = presetId || Lute.NewNodeID();- const newPath = pathPosix().join(getDisplayName(target.parentPath, false, true), id + ".sy");- fetchPost("/api/filetree/createDoc", {- notebook: target.targetNotebookId,- path: newPath,- title: target.title,- md: "",- }, () => {- onCreated?.(id, target.title || "");+ void fetchSyncPost("/api/filetree/createDocByParent",+ documentCreateRequest(target.targetNotebookId, target.parentPath, id, target.title)).then(response => {+ const createdID = createdDocumentID(response.data);+ if (createdID) {+ onCreated?.(createdID, target.title || "");+ }+ }).catch(error => {+ showMessage(error.message);});}diff --git a/app/src/util/parseNewDocTarget.test.ts b/app/src/util/parseNewDocTarget.test.tsdeleted file mode 100644index bd0a31d200..0000000000--- a/app/src/util/parseNewDocTarget.test.ts+++ /dev/null@@ -1,472 +0,0 @@-import {describe, it} from "node:test";-import * as assert from "node:assert/strict";-import {- getNewDocTargetFromSavePath,- getNewDocTargetFromTree,- isCurrentDocSubDocTarget,- NewDocTarget-} from "./parseNewDocTarget";--const assertSubDoc = (target: NewDocTarget, expected: {- targetNotebookId?: string;- parentPath: string;- title: string;-}) => {- assert.equal(target.kind, "subDoc");- if (target.kind === "subDoc") {- if (expected.targetNotebookId !== undefined) {- assert.equal(target.targetNotebookId, expected.targetNotebookId);- }- assert.equal(target.parentPath, expected.parentPath);- assert.equal(target.title, expected.title);- }-};--const assertHPath = (target: NewDocTarget, expected: {- targetNotebookId?: string;- hPath: string;- title: string;-}) => {- assert.equal(target.kind, "hPath");- if (target.kind === "hPath") {- if (expected.targetNotebookId !== undefined) {- assert.equal(target.targetNotebookId, expected.targetNotebookId);- }- assert.equal(target.hPath, expected.hPath);- assert.equal(target.title, expected.title);- }-};--describe("getNewDocTargetFromSavePath", () => {- // 聚焦嵌套文档:内核路径与人类路径成对出现- const nestedDocPath = "/20260628041644-ndcuikw/20260628040939-kkaajwr.sy";- const nestedHPath = "/parent1/parent2/docName";- // 聚焦根级文档- const rootDocPath = "/20260628041702-kqfrg7p.sy";- const rootHPath = "/docName";- const notebookId = "nb";-- const nestedContext = {- hPath: nestedHPath,- targetNotebookId: notebookId,- currentNotebookId: notebookId,- hasFocusTarget: true,- currentPath: nestedDocPath,- };-- describe("空模板", () => {- it("有页签/选中 + 无 name → 当前文档下子文档", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: ""});- assertSubDoc(target, {targetNotebookId: notebookId, parentPath: nestedDocPath, title: ""});- });-- it("有页签/选中 + 显式标题 → 当前 hPath 下按名称新建", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "", name: "docName2"});- assertHPath(target, {hPath: "/parent1/parent2/docName/docName2", title: "docName2"});- });-- it("聚焦根级文档 + 无 name → 子文档", () => {- const target = getNewDocTargetFromSavePath({- ...nestedContext,- templatePath: "",- hPath: rootHPath,- currentPath: rootDocPath,- });- assertSubDoc(target, {parentPath: rootDocPath, title: ""});- });-- it("聚焦根级文档 + 显式标题 → 当前 hPath 下按名称新建", () => {- const target = getNewDocTargetFromSavePath({- ...nestedContext,- templatePath: "",- hPath: rootHPath,- currentPath: rootDocPath,- name: "docName2",- });- assertHPath(target, {hPath: "/docName/docName2", title: "docName2"});- });-- it("选中笔记本根(currentPath=/)+ 无 name → 子文档", () => {- const target = getNewDocTargetFromSavePath({- ...nestedContext,- templatePath: "",- hPath: "/",- currentPath: "/",- });- assertSubDoc(target, {parentPath: "/", title: ""});- });-- it("无页签无选中 → 笔记本根", () => {- const target = getNewDocTargetFromSavePath({- ...nestedContext,- templatePath: "",- hasFocusTarget: false,- hPath: "/",- currentPath: "/",- });- assertHPath(target, {hPath: "/", title: ""});- });-- it("无页签无选中 + 显式标题 → 笔记本根下按名称新建", () => {- const target = getNewDocTargetFromSavePath({- ...nestedContext,- templatePath: "",- hasFocusTarget: false,- hPath: "/",- name: "docName2",- });- assertHPath(target, {hPath: "/docName2", title: "docName2"});- });- });-- describe("容器路径(尾 /)", () => {- it("绝对 /parent3/", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "/parent3/"});- assertHPath(target, {hPath: "/parent3/", title: ""});- });-- it("绝对 /parent3/ + 显式标题", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "/parent3/", name: "docName2"});- assertHPath(target, {hPath: "/parent3/docName2", title: "docName2"});- });-- it("绝对 /", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "/", hPath: "/"});- assertHPath(target, {hPath: "/", title: ""});- });-- it("绝对 /parent1/parent2/", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "/parent1/parent2/"});- assertHPath(target, {hPath: "/parent1/parent2/", title: ""});- });-- it("相对 parent3/", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "parent3/"});- assertHPath(target, {hPath: "/parent1/parent2/docName/parent3/", title: ""});- });-- it("相对 parent3/parent4/", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "parent3/parent4/"});- assertHPath(target, {hPath: "/parent1/parent2/docName/parent3/parent4/", title: ""});- });-- it("相对 ../", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "../"});- assertHPath(target, {hPath: "/parent1/parent2/", title: ""});- });-- it("相对 ../ + 显式标题", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "../", name: "docName2"});- assertHPath(target, {hPath: "/parent1/parent2/docName2", title: "docName2"});- });-- it("相对 ../../", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "../../"});- assertHPath(target, {hPath: "/parent1/", title: ""});- });-- it("相对 ../parent3/", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "../parent3/"});- assertHPath(target, {hPath: "/parent1/parent2/parent3/", title: ""});- });-- it("相对 ../../parent3/parent4/", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "../../parent3/parent4/"});- assertHPath(target, {hPath: "/parent1/parent3/parent4/", title: ""});- });-- it("已在根时 ../", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "../", hPath: "/"});- assertHPath(target, {hPath: "/", title: ""});- });-- it("模板首尾空白 trim", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: " parent3/ "});- assertHPath(target, {hPath: "/parent1/parent2/docName/parent3/", title: ""});- });- });-- describe("文档名路径", () => {- it("相对 docName2", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "docName2"});- assertHPath(target, {hPath: "/parent1/parent2/docName/docName2", title: "docName2"});- });-- it("相对 docName2 + 显式标题替换末段", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "docName2", name: "docName3"});- assertHPath(target, {hPath: "/parent1/parent2/docName/docName3", title: "docName3"});- });-- it("模板首尾空白 trim", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: " docName2 "});- assertHPath(target, {hPath: "/parent1/parent2/docName/docName2", title: "docName2"});- });-- it("绝对 /docName2", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "/docName2"});- assertHPath(target, {hPath: "/docName2", title: "docName2"});- });-- it("绝对 /docName2 + 显式标题替换末段", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "/docName2", name: "docName3"});- assertHPath(target, {hPath: "/docName3", title: "docName3"});- });-- it("相对 parent3/docName2", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "parent3/docName2"});- assertHPath(target, {hPath: "/parent1/parent2/docName/parent3/docName2", title: "docName2"});- });-- it("绝对 /parent3/docName2", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "/parent3/docName2"});- assertHPath(target, {hPath: "/parent3/docName2", title: "docName2"});- });-- it("相对 ../docName2", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "../docName2"});- assertHPath(target, {hPath: "/parent1/parent2/docName2", title: "docName2"});- });-- it("相对 ../../docName2", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "../../docName2"});- assertHPath(target, {hPath: "/parent1/docName2", title: "docName2"});- });-- it("相对 ../parent3/docName2", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "../parent3/docName2"});- assertHPath(target, {hPath: "/parent1/parent2/parent3/docName2", title: "docName2"});- });-- it("已在根时 ../docName2(.. 在根无效)", () => {- const target = getNewDocTargetFromSavePath({...nestedContext, templatePath: "../docName2", hPath: "/"});- assertHPath(target, {hPath: "/docName2", title: "docName2"});- });- });-- describe("跨笔记本", () => {- const crossNotebook = {- ...nestedContext,- targetNotebookId: "box-b",- currentNotebookId: "box-a",- hPath: "/",- currentPath: nestedDocPath,- };-- it("相对 docName2 → 补 / 后按目标笔记本根解析", () => {- const target = getNewDocTargetFromSavePath({...crossNotebook, templatePath: "docName2"});- assertHPath(target, {targetNotebookId: "box-b", hPath: "/docName2", title: "docName2"});- });-- it("相对 parent3/parent4/ → 补 / 后按目标笔记本根解析", () => {- const target = getNewDocTargetFromSavePath({...crossNotebook, templatePath: "parent3/parent4/"});- assertHPath(target, {targetNotebookId: "box-b", hPath: "/parent3/parent4/", title: ""});- });-- it("相对 ../docName2 → 补 / 后 .. 在根无效", () => {- const target = getNewDocTargetFromSavePath({...crossNotebook, templatePath: "../docName2"});- assertHPath(target, {targetNotebookId: "box-b", hPath: "/docName2", title: "docName2"});- });-- it("绝对 /parent3/docName2 不受影响", () => {- const target = getNewDocTargetFromSavePath({...crossNotebook, templatePath: "/parent3/docName2"});- assertHPath(target, {targetNotebookId: "box-b", hPath: "/parent3/docName2", title: "docName2"});- });-- it("空模板 + 无页签无选中 + 显式标题 → 目标笔记本根下按名称新建", () => {- const target = getNewDocTargetFromSavePath({- ...crossNotebook,- templatePath: "",- hasFocusTarget: false,- name: "docName2",- });- assertHPath(target, {targetNotebookId: "box-b", hPath: "/docName2", title: "docName2"});- });-- it("空模板 + 有聚焦 + 无 name → 回退到目标笔记本根空标题文档", () => {- const target = getNewDocTargetFromSavePath({...crossNotebook, templatePath: ""});- assertHPath(target, {targetNotebookId: "box-b", hPath: "/", title: ""});- });-- it("空模板 + 有聚焦 + 显式标题 → 目标笔记本根下按名称新建(跨笔记本 hPath 基点为 /)", () => {- const target = getNewDocTargetFromSavePath({...crossNotebook, templatePath: "", name: "docName2"});- assertHPath(target, {targetNotebookId: "box-b", hPath: "/docName2", title: "docName2"});- });- });-});--describe("isCurrentDocSubDocTarget", () => {- const currentNotebookId = "nb";- const currentPath = "/20260628041644-ndcuikw/20260628040939-kkaajwr.sy";- const currentHPath = "/parent1/parent2/docName";-- const isCurrentSubDoc = (target: NewDocTarget, title: string) => isCurrentDocSubDocTarget({- target,- currentNotebookId,- currentPath,- currentHPath,- title,- });-- it("直接创建当前文档的空标题子文档", () => {- assert.equal(isCurrentSubDoc({- kind: "subDoc",- targetNotebookId: currentNotebookId,- parentPath: currentPath,- title: "",- }, ""), true);- });-- it("配置路径解析为当前文档下的命名子文档", () => {- assert.equal(isCurrentSubDoc({- kind: "hPath",- targetNotebookId: currentNotebookId,- hPath: currentHPath + "/target",- title: "target",- }, "target"), true);- });-- it("空标题的容器路径解析为当前文档", () => {- assert.equal(isCurrentSubDoc({- kind: "hPath",- targetNotebookId: currentNotebookId,- hPath: currentHPath + "/",- title: "",- }, ""), true);- });-- it("标题不同时不等价", () => {- assert.equal(isCurrentSubDoc({- kind: "hPath",- targetNotebookId: currentNotebookId,- hPath: currentHPath + "/configured-title",- title: "configured-title",- }, ""), false);- });-- it("父路径不是当前文档时不等价", () => {- assert.equal(isCurrentSubDoc({- kind: "hPath",- targetNotebookId: currentNotebookId,- hPath: currentHPath + "/child/target",- title: "target",- }, "target"), false);- });-- it("目标笔记本不同时不等价", () => {- assert.equal(isCurrentSubDoc({- kind: "hPath",- targetNotebookId: "other-nb",- hPath: currentHPath + "/target",- title: "target",- }, "target"), false);- });-});--describe("getNewDocTargetFromTree", () => {- const notebookId = "nb";- // 文档树 data-path:带 .sy 的内核路径- const parentDocPath = "/20260628041644-ndcuikw.sy";- const nestedDocPath = "/20260628041644-ndcuikw/20260628040939-kkaajwr.sy";- // pathPosix().dirname():同级插入时传入的父目录(无 .sy、无尾斜杠)- const parentDirPath = "/20260628041644-ndcuikw";- const rootPath = "/";-- describe("文档树 + 新建子文档(currentPath 为 data-path)", () => {- const treeContext = {currentNotebookId: notebookId, currentPath: parentDocPath};-- it("空模板", () => {- const target = getNewDocTargetFromTree({...treeContext, templatePath: ""});- assertSubDoc(target, {targetNotebookId: notebookId, parentPath: parentDocPath, title: ""});- });-- it("空模板 + 显式标题", () => {- const target = getNewDocTargetFromTree({...treeContext, templatePath: "", name: "docName2"});- assertSubDoc(target, {parentPath: parentDocPath, title: "docName2"});- });-- it("单段模板 docName2", () => {- const target = getNewDocTargetFromTree({...treeContext, templatePath: "docName2"});- assertSubDoc(target, {parentPath: parentDocPath, title: "docName2"});- });-- it("单段模板 docName2 + 显式标题", () => {- const target = getNewDocTargetFromTree({...treeContext, templatePath: "docName2", name: "docName3"});- assertSubDoc(target, {parentPath: parentDocPath, title: "docName3"});- });-- it("多段模板 parent3/docName2(仅取末段为标题,父路径不变)", () => {- const target = getNewDocTargetFromTree({...treeContext, templatePath: "parent3/docName2"});- assertSubDoc(target, {parentPath: parentDocPath, title: "docName2"});- });-- it("绝对模板 /docName2(落点仍为 currentPath,仅影响标题)", () => {- const target = getNewDocTargetFromTree({...treeContext, templatePath: "/docName2"});- assertSubDoc(target, {parentPath: parentDocPath, title: "docName2"});- });-- it("容器模板 docName2/(树入口不解析容器链,无 name 时空标题)", () => {- const target = getNewDocTargetFromTree({...treeContext, templatePath: "docName2/"});- assertSubDoc(target, {parentPath: parentDocPath, title: ""});- });-- it("容器模板 docName2/ + 显式标题", () => {- const target = getNewDocTargetFromTree({...treeContext, templatePath: "docName2/", name: "docName2"});- assertSubDoc(target, {parentPath: parentDocPath, title: "docName2"});- });-- it("模板首尾空白 trim", () => {- const target = getNewDocTargetFromTree({...treeContext, templatePath: " docName2 "});- assertSubDoc(target, {parentPath: parentDocPath, title: "docName2"});- });-- it("嵌套文档下新建子文档", () => {- const target = getNewDocTargetFromTree({- currentNotebookId: notebookId,- currentPath: nestedDocPath,- templatePath: "docName2",- });- assertSubDoc(target, {parentPath: nestedDocPath, title: "docName2"});- });- });-- describe("同级插入(currentPath 为 dirname,无 .sy)", () => {- it("嵌套文档的同级插入", () => {- const target = getNewDocTargetFromTree({- currentNotebookId: notebookId,- currentPath: parentDirPath,- templatePath: "docName2",- });- assertSubDoc(target, {parentPath: parentDirPath, title: "docName2"});- });-- it("根级文档的同级插入(dirname 为 /)", () => {- const target = getNewDocTargetFromTree({- currentNotebookId: notebookId,- currentPath: rootPath,- templatePath: "",- });- assertSubDoc(target, {parentPath: rootPath, title: ""});- });- });-- describe("笔记本根(currentPath 为 /)", () => {- it("空模板", () => {- const target = getNewDocTargetFromTree({- currentNotebookId: notebookId,- currentPath: rootPath,- templatePath: "",- });- assertSubDoc(target, {parentPath: rootPath, title: ""});- });-- it("单段模板 + 显式标题", () => {- const target = getNewDocTargetFromTree({- currentNotebookId: notebookId,- currentPath: rootPath,- templatePath: "docName2",- name: "docName3",- });- assertSubDoc(target, {parentPath: rootPath, title: "docName3"});- });- });-});diff --git a/app/src/util/parseNewDocTarget.ts b/app/src/util/parseNewDocTarget.tsdeleted file mode 100644index f0abaf00fd..0000000000--- a/app/src/util/parseNewDocTarget.ts+++ /dev/null@@ -1,166 +0,0 @@-/**- * 新建文档路径解析。输入为内核渲染后的路径模板。- *- * 调用方先采集 `path`,再转为 `hPath` 传入;跨笔记本时 `hPath` 固定为 `/`。- *- * 标题优先级:`name` > 路径末段(文档名模式)> 空。`name` 替换末段,非拼接。- *- * 三种形态:- * - 尾 `/` → 父文档路径:路径为父文档链,新文档建在最内层父文档内;未传 `name` 时空标题- * - 非尾 `/` → 文档名:末段为标题,其余为父路径- * - 空 → 同笔记本 + 有上下文则当前文档子文档;跨笔记本或无上下文则目标笔记本根路径- *- * `/` 开头从根解析,否则相对 `hPath`;`..` 向上一级,已在根则停在 `/`。- * 跨笔记本时相对路径在开头补 `/`,按目标笔记本根解析;空路径也回退到目标笔记本根路径。- */--import {mergePathSegments} from "./mergePathSegments";--/** 内核 `createDocsByHPath` 按 HPath 逐级创建 */-export type NewDocTargetByHPath = {- kind: "hPath";- targetNotebookId: string;- hPath: string;- title: string;-};--/** 在已知父路径下创建子文档 */-export type NewDocTargetSubDoc = {- kind: "subDoc";- targetNotebookId: string;- parentPath: string;- title: string;-};--export type NewDocTarget = NewDocTargetByHPath | NewDocTargetSubDoc;--/** 判断配置路径的解析结果是否与在当前文档下直接创建子文档等价 */-export const isCurrentDocSubDocTarget = (request: {- target: NewDocTarget;- currentNotebookId: string;- currentPath: string;- currentHPath: string;- title: string;-}) => {- const {target} = request;- if (target.targetNotebookId !== request.currentNotebookId || target.title !== request.title) {- return false;- }- if (target.kind === "subDoc") {- return target.parentPath === request.currentPath;- }-- const segments = target.hPath.split("/").filter(Boolean);- if (target.title) {- segments.pop();- }- const parentHPath = segments.length === 0 ? "/" : "/" + segments.join("/");- const currentHPathSegments = mergePathSegments([], request.currentHPath.split("/").filter(Boolean));- const currentHPath = currentHPathSegments.length === 0 ? "/" : "/" + currentHPathSegments.join("/");- return parentHPath === currentHPath;-};--/** 按保存路径配置解析新建目标 */-export const getNewDocTargetFromSavePath = (request: {- templatePath: string;- hPath: string;- targetNotebookId: string;- currentNotebookId: string;- name?: string;- hasFocusTarget: boolean;- currentPath?: string;-}): NewDocTarget => {- const {targetNotebookId} = request;-- let templatePath = request.templatePath.trim();- let isAbsolute = templatePath.startsWith("/");- if (targetNotebookId !== request.currentNotebookId && templatePath && !isAbsolute) {- // 跨笔记本时相对路径无锚点,在开头补 `/` 按目标笔记本根路径解析- templatePath = "/" + templatePath;- isAbsolute = true;- }-- // 空路径 + 同笔记本 + 有上下文 + 无 name:在已知父路径下建空标题子文档- // 跨笔记本时 currentPath 属于当前笔记本,在目标笔记本中无效,落到下方 hPath 逻辑回退到目标笔记本根- if (!templatePath && request.hasFocusTarget && !request.name- && targetNotebookId === request.currentNotebookId) {- return {- kind: "subDoc",- targetNotebookId,- parentPath: request.currentPath || "/",- title: "",- };- }-- let parentTemplate: string;- let title = "";- if (!templatePath) {- // 空路径 + 有上下文 → 当前路径下;空路径 + 无上下文 → 笔记本根- parentTemplate = request.hasFocusTarget ? "" : "/";- title = request.name || "";- } else if (templatePath.endsWith("/")) {- // 尾部有 `/`:解析父文档链,在最内层父文档内新建- parentTemplate = templatePath;- title = request.name || "";- } else {- const segments = templatePath.split("/").filter(Boolean);- if (segments.length <= 1) {- // 文档名- parentTemplate = isAbsolute ? "/" : "";- } else {- // 路径:去掉末段(文档名),余下段拼成父路径模板- const parentSegmentPath = segments.slice(0, -1).join("/");- parentTemplate = isAbsolute ? "/" + parentSegmentPath : parentSegmentPath;- }- title = request.name || segments[segments.length - 1];- }-- // 将路径模板合并进 hPath- const templateSegments = parentTemplate.split("/").filter(Boolean);- let parentPathSegments: string[];- if (parentTemplate.startsWith("/")) {- // 绝对路径:从笔记本根起算- parentPathSegments = mergePathSegments([], templateSegments);- } else {- // 相对路径:从当前 hPath 起算- parentPathSegments = mergePathSegments(request.hPath.split("/").filter(Boolean), templateSegments);- }-- let hPath: string;- if (title) {- hPath = "/" + [...parentPathSegments, title].join("/");- } else {- // 空标题时保留尾 `/` 使 hPath 末段为空,内核按父文档链在其内新建子文档- hPath = parentPathSegments.length === 0 ? "/" : "/" + parentPathSegments.join("/") + "/";- }-- return {- kind: "hPath",- targetNotebookId,- hPath,- title,- };-};--/** 文件树指定位置:在 `currentPath` 下建子文档,标题规则同保存路径 */-export const getNewDocTargetFromTree = (request: {- templatePath: string;- currentNotebookId: string;- currentPath: string;- name?: string;-}): NewDocTargetSubDoc => {- const templatePath = request.templatePath.trim();- let title = "";- if (request.name) {- title = request.name;- } else if (templatePath && !templatePath.endsWith("/")) {- const segments = templatePath.split("/").filter(Boolean);- title = segments[segments.length - 1];- }- return {- kind: "subDoc",- targetNotebookId: request.currentNotebookId,- parentPath: request.currentPath || "/",- title,- };-};diff --git a/app/src/window/index.ts b/app/src/window/index.tsindex b7f4ecfc5a..2992c01cbf 100644--- a/app/src/window/index.ts+++ b/app/src/window/index.ts@@ -1,5 +1,6 @@import {onWindowWorkspaceStorageChanged} from "./workspace";import {closeNotebookHistoryDialogs} from "../history/notebookDialogs";+import {clearDocumentCreationPlans} from "../util/configuredDocument";import {closeNotebookLivePhotos} from "../protyle/preview/livePhoto";import {Constants} from "../constants";import {refreshSettingConfig} from "../config/setting/sync";@@ -172,6 +173,7 @@ class App {case "closeBox":case "removeBox":closeNotebookHistoryDialogs(data.data.box);+ clearDocumentCreationPlans(data.data.box);closeNotebookLivePhotos(data.data.box);removeBlockPanelEditors({notebookId: data.data.box});getAllTabs().forEach((tab) => {diff --git a/app/tests/newRefDocAtPath.test.js b/app/tests/newRefDocAtPath.test.jsindex 64e16bcc12..1161efbde0 100644--- a/app/tests/newRefDocAtPath.test.js+++ b/app/tests/newRefDocAtPath.test.js@@ -47,6 +47,7 @@ const fixture = () => {hasClosestBlock: node => node.block,Constants: {ZWSP: "\u200b", BLOCK_HINT_KEYS: ["((", "[[", "((", "【【"]},fetchPost: (url, data, cb) => requests.push({url, data, cb}),+ fetchSyncPost: (url, data) => new Promise(resolve => requests.push({url, data, cb: resolve})),focusByRange: value => focused.push(value),getEditorRange: () => range,replaceFileName: value => value,@@ -65,6 +66,7 @@ const fixture = () => {pathPosix: () => path.posix,movePathTo: options => { picker = options; },});+ Object.assign(deps, load("util/documentCreate", deps, window, Lute));const api = load("util/newFile", deps, window, Lute);Object.assign(deps, api);const hintAPI = load("protyle/hint/index", deps, window, Lute);@@ -83,8 +85,9 @@ const fixture = () => {};};-test("selected ID paths create at notebook root or the exact parent, without changing preferences", () => {- for (const parent of ["/", "/same-name-one.sy", "/same-name-two.sy", "/ancestor/parent.sy"]) {+test("selected ID paths create at notebook root or the exact parent, without changing preferences", async () => {+ for (const parent of ["/", "/20260927110000-parent1.sy", "/20260927110001-parent2.sy",+ "/20260927110000-parent1/20260927110002-parent3.sy"]) {const f = fixture();const config = JSON.stringify(f.window.siyuan.config);f.open();@@ -92,12 +95,13 @@ test("selected ID paths create at notebook root or the exact parent, without chaf.picker.cb([parent], ["other"]);assert.equal(f.requests.length, 1);assert.deepEqual(f.requests[0].data, {- notebook: "other", path: path.posix.join(parent.replace(/\.sy$/, ""), "20260927120000-newdoc1.sy"),- title: "New title", md: "",+ notebook: "other", parentID: parent === "/" ? null : path.posix.basename(parent, ".sy"),+ id: "20260927120000-newdoc1", title: {format: "plain", text: "New title"}, markdown: "",});- assert.equal(f.requests[0].url, "/api/filetree/createDoc");+ assert.equal(f.requests[0].url, "/api/filetree/createDocByParent");assert.equal(f.inserted.length, 0);- f.requests[0].cb({code: 0});+ f.requests[0].cb({code: 0, data: {id: "20260927120000-newdoc1", document: {}}});+ await Promise.resolve();assert.equal(f.inserted[0][0], "20260927120000-newdoc1");assert.notEqual(f.inserted[0][1], f.range);assert.equal(JSON.stringify(f.window.siyuan.config), config);@@ -133,12 +137,13 @@ test("changed, detached or navigated source contexts prevent creation and focus}});-test("an invalidated source after creation starts does not receive a reference", () => {+test("an invalidated source after creation starts does not receive a reference", async () => {const f = fixture();f.open();f.picker.cb(["/"], ["other"]);f.protyle.block.rootID = "different";- f.requests[0].cb({code: 0});+ f.requests[0].cb({code: 0, data: {id: "20260927120000-newdoc1", document: {}}});+ await Promise.resolve();assert.equal(f.inserted.length, 0);});@@ -163,7 +168,7 @@ test("encrypted notebook boundaries apply to explicitly selected destinations",}});-test("hint selection preserves reference subtype, anchor text and undo context", () => {+test("hint selection preserves reference subtype, anchor text and undo context", async () => {for (const trigger of ["((", "[[", "((", "【【"]) {for (const staticRef of [true, false]) {const f = fixture();@@ -171,7 +176,8 @@ test("hint selection preserves reference subtype, anchor text and undo context",f.hint.fill(`((newFileAtPath "Original anchor"\u200b'New title${f.Lute.Caret}'))`, f.protyle, false, staticRef);assert.equal(f.inserted.length, 0);f.picker.cb(["/"], ["other"]);- f.requests[0].cb({code: 0});+ f.requests[0].cb({code: 0, data: {id: "20260927120000-newdoc1", document: {}}});+ await Promise.resolve();assert.equal(f.inserted.length, 1);const args = f.inserted[0];assert.equal(args[3].color, `20260927120000-newdoc1\u200b${staticRef ? "s" : "d"}\u200b${staticRef ? "Original anchor" : "New title"}`);@@ -246,12 +252,12 @@ test("database creation binds only after success and preserves item identity andfor (const isDetached of [false, true]) {const f = databaseFixture(view, isDetached);f.openDatabase();- f.picker.cb(["/chosen-parent.sy"], ["other"]);+ f.picker.cb(["/20260927110000-parent1.sy"], ["other"]);assert.equal(f.operations.length, 0);assert.equal(f.animations.length, 0);- assert.equal(f.requests[0].data.path, "/chosen-parent/20260927120000-newdoc1.sy");- f.requests[0].cb({code: 0});- await Promise.resolve();+ assert.equal(f.requests[0].data.parentID, "20260927110000-parent1");+ f.requests[0].cb({code: 0, data: {id: "20260927120000-newdoc1", document: {}}});+ await new Promise(resolve => setImmediate(resolve));assert.equal(f.operations.length, 1);const {doOperations, undoOperations} = f.operations[0];assert.equal(doOperations[0].previousID, "original-item");@@ -299,8 +305,8 @@ test("database context changes before confirmation or after creation starts cann}change(f);if (afterCreate) {- f.requests[0].cb({code: 0});- await Promise.resolve();+ f.requests[0].cb({code: 0, data: {id: "20260927120000-newdoc1", document: {}}});+ await new Promise(resolve => setImmediate(resolve));} else {f.picker.cb(["/"], ["other"]);assert.equal(f.requests.length, 0);diff --git a/docs/API.ja.md b/docs/API.ja.mdindex 2c72e813c4..b054ec7103 100644--- a/docs/API.ja.md+++ b/docs/API.ja.md@@ -329,6 +329,8 @@ if (response.code === 0 && response.data) {}```+管理者への応答には、読み取り専用の省略可能な `documentCapabilities` オブジェクトも含まれます。`structuredPaths` は ID とパス要素の API への対応を示し、閉じたノートブックやロック中のノートブックへのアクセス権限は付与しません。現在の `literalSlash` は `false` で、保護バージョンの検証が完了するまで `minimumReaderVersion` は `null` です。旧サーバーにこのオブジェクトがない場合とリクエストの失敗は区別し、失敗後に従来のパス API で書き込みを再試行しないでください。+### ノートブック設定を保存* `/api/notebook/setNotebookConf`@@ -1477,6 +1479,9 @@ if (response.code === 0 && response.data) {* `/api/file/putFile`ノートブックのアドレス指定モードが未対応の場合、ディレクトリの作成、内容の書き込み、更新日時の変更を行う前に `code: -1` を返します。この API ではローカルの機能要件記録 `conf/document-addressing.json` を上書きできません。++ノートブック ID とドキュメント ID で構成される `.sy` ドキュメントパスへの書き込みでは、入力内容と既存のドキュメントを検証します。未知の形式、不正なドキュメントデータ、互換モードと競合するタイトルは `code: -1` を返し、元のファイルと更新日時を保持します。成功時はタイトルを正規化せず、要求されたバイト列をそのまま保存します。アセットやプラグインのディレクトリ内にある `.sy` ファイルはドキュメントとして解析しません。+* パラメータはHTTP Multipartフォーム* `path`: ワークスペースパス配下のファイルパス@@ -1521,6 +1526,9 @@ if (response.code === 0 && response.data) {* `/api/file/renameFile`移動先ディレクトリの作成やファイルの移動前に、操作全体のノートブックのアドレス指定互換性を検証します。未対応のモード、および `conf/document-addressing.json` の移動や上書きは `code: -1` を返します。++移動先にノートブック ID とドキュメント ID で構成される `.sy` ドキュメントパスが含まれる場合、対象となるすべての入力ドキュメントも検証します。未知の形式、不正なドキュメントデータ、タイトルの競合は `code: -1` を返し、移動先ディレクトリを作成せず、移動元も変更しません。+* パラメータ```jsondiff --git a/docs/API.md b/docs/API.mdindex 3258ef10e2..1352613bea 100644--- a/docs/API.md+++ b/docs/API.md@@ -334,6 +334,8 @@ The close endpoint validates the notebook ID without trimming whitespace. Typed}```+Administrator responses also include the optional read-only `documentCapabilities` object. `structuredPaths` advertises the ID and segment APIs; it does not grant access to closed or locked notebooks. `literalSlash` is currently `false`, and `minimumReaderVersion` is `null` until a protective release is verified. An absent object on an older server differs from a failed request; failures must not trigger a fallback write through legacy path APIs.+### Save notebook configuration* `/api/notebook/setNotebookConf`@@ -1485,6 +1487,9 @@ Block-writing APIs can return after their block-tree transaction is committed bu* `/api/file/putFile`Unsupported notebook addressing modes return `code: -1` before creating directories, writing content, or changing timestamps. This endpoint cannot overwrite the local `conf/document-addressing.json` capability record.++For `.sy` document paths composed of notebook and document IDs, both the incoming content and any existing document are checked. Unknown formats, invalid document sources, or titles conflicting with compatibility mode return `code: -1`, preserving the original file and modification time. Successful writes retain the request bytes without normalizing titles. Files ending in `.sy` inside asset or plugin directories are not parsed as documents.+* The parameter is an HTTP Multipart form* `path`: the file path under the workspace path@@ -1529,6 +1534,9 @@ Partial deletion in a notebook with an unsupported addressing mode returns `code* `/api/file/renameFile`The complete move is checked for notebook addressing compatibility before creating the destination directory or moving files. Unsupported modes and attempts to move or overwrite `conf/document-addressing.json` return `code: -1`.++When the destination includes `.sy` document paths composed of notebook and document IDs, all incoming documents are also checked. Unknown formats, invalid document sources, or conflicting titles return `code: -1` without creating the destination directory or moving the sources.+* Parameters```jsondiff --git a/docs/API.zh-CN.md b/docs/API.zh-CN.mdindex 83ab11e979..3703821e61 100644--- a/docs/API.zh-CN.md+++ b/docs/API.zh-CN.md@@ -334,6 +334,8 @@ if (response.code === 0 && response.data) {}```+管理员响应还包含可选只读对象 `documentCapabilities`。`structuredPaths` 表示服务端支持 ID 与路径段接口,不授予关闭或锁定笔记本的访问权限。目前 `literalSlash` 为 `false`;保护版本验证完成前,`minimumReaderVersion` 为 `null`。旧服务端缺少此对象与请求失败含义不同,不能在请求失败后回退到旧路径接口继续写入。+### 保存笔记本配置* `/api/notebook/setNotebookConf`@@ -1483,6 +1485,9 @@ if (response.code === 0 && response.data) {* `/api/file/putFile`笔记本寻址模式不受支持时返回 `code: -1`,不会创建目录、写入内容或更新时间。此接口不能覆盖本机 `conf/document-addressing.json` 能力记录。++写入由笔记本及文档 ID 组成的 `.sy` 文档路径时,同时检查传入内容和已有文档。未知格式、损坏的文档源或标题与兼容模式冲突时返回 `code: -1`,保留原文件及修改时间;成功写入保留请求中的原始字节,不规范化标题。附件或插件目录中的 `.sy` 文件不作为文档解析。+* 参数为 HTTP Multipart 表单* `path`:工作空间路径下的文件路径@@ -1527,6 +1532,9 @@ if (response.code === 0 && response.data) {* `/api/file/renameFile`创建目标目录或移动文件之前会检查完整操作的笔记本寻址兼容性。不支持的模式,以及移动或覆盖 `conf/document-addressing.json` 的操作,返回 `code: -1`。++目标包含由笔记本及文档 ID 组成的 `.sy` 文档路径时,也会预检全部传入文档;未知格式、损坏的文档源或标题冲突返回 `code: -1`,不创建目标目录,也不移动来源。+* 参数```jsondiff --git a/docs/DOCUMENT-ADDRESSING.md b/docs/DOCUMENT-ADDRESSING.mdindex 88bcb86f26..2f30b17547 100644--- a/docs/DOCUMENT-ADDRESSING.md+++ b/docs/DOCUMENT-ADDRESSING.md@@ -6,6 +6,16 @@ Related issues: [Improve hPath by separating display text from document addressiThis is an implementation design draft defining document titles, hierarchy addressing, readable paths, APIs, and migration behavior. The new fields, endpoints, and version mechanisms below are proposed contracts, not capabilities already supported by the current release. See [Document rename and path indexes](DOCUMENT-HPATH.md) (Chinese) for the current rename and index update mechanism.+### Current implementation scope++The development branch implements a shared title reader, document metadata organized by identity, and recovery markers for source commits. It provides the `getDocPaths`, `resolveDocPath`, `getDocCreateTarget`, `planDocCreate`, and `createDocByParent` contracts. Built-in document and reference creation, daily notes, database creation, and shorthands use identity-based creation or shared creation plans. Export allocates filenames by document identity before using the same mapping for internal links. Existing document IDs, title representations, and applicable `.sy` specifications remain intact; upgrading does not rewrite every source document.++Creation plans retain fixed IDs and never recreate confirmed ancestors. Desktop and mobile share failure handling: an uncertain response or a failure after source commit retains the plan until the user approves an identity check and continuation. Closing or locking a notebook clears its title and template caches. Local shorthands keep a recovery record containing only identities and digests, verify block identities in the actual source before consuming the input, and preserve unresolved input without automatically replaying the operation.++Only compatibility mode `1` is currently available. ASCII `/` remains prohibited in document titles, and public writes of version `2` target configurations remain gated by the notebook mode. Explicit enablement, mode `2` source formats and conflict recovery, notebook-wide rejection of legacy string addressing, and the enablement UI have not shipped; this work must not be described as merely waiting for a release switch. Stage D must also determine the minimum reader version and `DocumentTitleSpec` from actual protective-release verification and complete mixed-version, performance, and platform acceptance before activation. The inline-title extension requirements remain unchanged.++Administrator notebook configuration reads expose `documentCapabilities`, distinguishing structured APIs, the effective addressing mode, and index state. `minimumReaderVersion` stays `null` until a real protective release has been verified; malformed capability records return an error. Whole-notebook native import remaps notebook and anchor IDs in configured targets, while partial import preserves the destination configuration. Encrypted targets retain authenticated locked saves, password rewrapping, and backup recovery.+## Goals and scopeDocument IDs determine identity and hierarchy membership; titles express content; readable paths provide presentation. Creation, moves, and references must not recover document identity by parsing display text. Once the affected entry points have migrated and compatibility has been verified, document titles can contain the ASCII slash `/` while remaining distinct from existing fullwidth slashes `/`.@@ -315,9 +325,15 @@ Business errors use `code: -1` with a stable `data.reason`. `msg` is for human rLegacy `/api/filetree/getDocCreateSavePath` and `/api/filetree/getRefCreateSavePath` retain their responses while their respective effective configurations are legacy templates. When the corresponding new object is active, both return `code: -1`, `data: {reason: "structuredTemplateRequired"}` instead of obsolete paths. This decision follows the configuration source and workflow, not the notebook addressed by an old path or new target; an obsolete destination still using mode `1` does not permit returning historical configuration. Declare the error variant on each legacy contract. Both built-in consumers and plugins use the new reader to avoid reimplementing configuration inheritance independently.+### Planning a configured creation target++`/api/filetree/planDocCreate` accepts `notebook`, `purpose`, and the final document's fixed `id`. Optional `contextID` identifies the current document; omission or `null` means there is no current document. Optional `title` overrides the final title, `placement` is `configured` or `child`, and `reuse` controls whether an existing final document may be reused. The endpoint evaluates and validates without writing documents. Time templates within a plan share one time snapshot. The response contains the final title, target notebook, optional `existingID`, and ordered `steps` with fixed IDs, parent identities, name conditions, and configuration revisions.++The caller submits each `createDocByParent` request in order, updating the next step's parent revision from the previous successful response. The returned identity is authoritative after submission. Failures follow their reported commit state; callers must not allocate a fresh set of IDs and blindly replay. A plan is not a transaction across multiple files, and successful planning does not replace validation at each commit.+### Capability discovery and activation-Add an optional read-only `documentCapabilities` object to `data` in `/api/notebook/getNotebookConf`, retaining existing `box`, `name`, `conf`, and access filtering. It contains `addressingVersion`, `modeState`, `structuredPaths`, `literalSlash`, `titleFormats`, `indexState`, `minimumReaderVersion`, and `revision`. `modeState` is `legacy`, `structured`, `conflict`, or `recovering`. `structuredPaths` means the server implements the new protocol, and `indexState` describes derived-index state; neither replaces mode state. Initially, `titleFormats` is `["plain"]`; `literalSlash` is `true` only in mode `2` with `modeState: "structured"` and a ready index.+Add an optional read-only `documentCapabilities` object to `data` in `/api/notebook/getNotebookConf`, retaining existing `box`, `name`, `conf`, and access filtering. It contains `addressingVersion`, `modeState`, `structuredPaths`, `literalSlash`, `titleFormats`, `indexState`, `minimumReaderVersion`, and `revision`. `modeState` is `legacy`, `structured`, `conflict`, or `recovering`. `structuredPaths` means the server implements the new protocol, and `indexState` describes derived-index state; neither replaces mode state. Administrator responses include this object; other roles retain existing configuration filtering. `minimumReaderVersion` is `null` until the actual protective release has been verified, then contains its version string. Initially, `titleFormats` is `["plain"]`; `literalSlash` is `true` only in mode `2` with `modeState: "structured"` and a ready index.`revision` is the configuration revision relevant to activation, not an individual document's path revision. Capability declarations grant no access; closed or locked notebooks retain existing restrictions, and status reads expose neither titles nor protected template content. When an older server omits the object, plugins use only legacy capabilities. Authorization, locking, and network errors must not be interpreted as unsupported capabilities or trigger fallback writes.@@ -368,6 +384,8 @@ In compatibility mode, inspect the decoded root title for ASCII `/` before tolerTree writes validate both the replacement and the current on-disk source. Authenticate encrypted sources before interpreting them, and hold the same file lock through current-source validation and persistence so stale caches cannot overwrite a newly incompatible source. Automatic repair additionally requires that the source still matches the bytes originally inspected. Validation failures must not fall through to a fallback write or truncate the file. Ordinary documents retain page-based writes; encrypted documents retain atomic ciphertext replacement.+Raw file endpoints apply the same source-format checks to paths composed of notebook and document IDs; uploads, copies, and moves into those paths cannot bypass them. Validate the complete batch before creating destination directories or copying any files. Actual document copies use the validated source bytes and recheck the current destination under the file lock. Concurrent changes or I/O failures after preflight can leave completed copies; batch rollback is not promised. Files ending in `.sy` inside ordinary asset and plugin directories retain raw-file semantics, and encrypted notebooks remain inaccessible through raw file endpoints.+Determine the minimum compatible version through read, write, and rejection tests against actual releases. Clients predating the protective release that ignore capability markers cannot be constrained automatically by new fields and are outside the safe mixed-version promise. All sync devices must upgrade before activation. Offline device state cannot be proven and must be explained. If a supported version still has a path that rewrites data, keep the capability disabled rather than substituting documentation for necessary protection.Mode `2` has no direct switch back to `1`. Even after current titles no longer contain `/`, history and backups can retain new formats. Older clients may use a verified compatible export copy or a complete pre-activation backup restored into a separate workspace; do not overwrite the original workspace with old configuration and continue syncing. Any future downgrade converter requires its own conversion manifest, conflict policy, and recovery design while preserving original data.@@ -489,7 +507,7 @@ Change CI filters or maintenance guides only if existing discovery would miss ne| Source documents and read-only path recovery | [`filesys/tree.go`](../kernel/filesys/tree.go), [`filesys/hpath.go`](../kernel/filesys/hpath.go) || Path refresh, recovery queues, and document indexes | [`treenode/blocktree.go`](../kernel/treenode/blocktree.go), [`treenode/hpath.go`](../kernel/treenode/hpath.go), [`model/hpath_refresh.go`](../kernel/model/hpath_refresh.go), [`sql/queue.go`](../kernel/sql/queue.go) || Search and hierarchy calculations | [`model/search.go`](../kernel/model/search.go), [`sql/block_query.go`](../kernel/sql/block_query.go), [`search/config.ts`](../app/src/search/config.ts) |-| Creation entry points and save path parsing | [`util/newFile.ts`](../app/src/util/newFile.ts), [`util/parseNewDocTarget.ts`](../app/src/util/parseNewDocTarget.ts), [`mobile/util/initFramework.ts`](../app/src/mobile/util/initFramework.ts) |+| Creation entry points and save path parsing | [`util/newFile.ts`](../app/src/util/newFile.ts), [`util/configuredDocument.ts`](../app/src/util/configuredDocument.ts), [`mobile/util/initFramework.ts`](../app/src/mobile/util/initFramework.ts) || Templates, new database items, and shorthands | [`model/template_doc_tree.go`](../kernel/model/template_doc_tree.go), [`model/attribute_view_new_item.go`](../kernel/model/attribute_view_new_item.go), [`model/shortcuts.go`](../kernel/model/shortcuts.go) || Daily-note reuse and legacy creation regressions | [`model/daily_note.go`](../kernel/model/daily_note.go), [`model/file_test.go`](../kernel/model/file_test.go) || Import and export | [`model/import.go`](../kernel/model/import.go), [`model/import_obsidian.go`](../kernel/model/import_obsidian.go), [`model/export.go`](../kernel/model/export.go) |diff --git a/docs/DOCUMENT-ADDRESSING.zh-CN.md b/docs/DOCUMENT-ADDRESSING.zh-CN.mdindex 0df5d319a5..e7540597e6 100644--- a/docs/DOCUMENT-ADDRESSING.zh-CN.md+++ b/docs/DOCUMENT-ADDRESSING.zh-CN.md@@ -6,6 +6,16 @@本文为实施设计草案,规定文档标题、层级定位、可读路径、接口及迁移的目标行为。下文新增的字段、接口和版本机制均为拟实现契约,不表示当前版本已经支持。当前重命名与路径索引的更新机制见 [文档重命名与路径索引](DOCUMENT-HPATH.md)。+### 当前实现范围++开发分支已实现统一标题读取、按身份组织的文档元数据及源提交恢复标记,并提供 `getDocPaths`、`resolveDocPath`、`getDocCreateTarget`、`planDocCreate` 和 `createDocByParent` 契约。内置新建、引用新建、日记、数据库新建和速记使用身份创建或共享创建计划;导出先按文档身份分配文件名,再使用同一映射生成内部链接。源文档仍保留原有 ID、标题表示及适用的 `.sy` 规格,不在升级时批量改写。++创建计划采用固定 ID,已确认提交的祖先不会再次创建。桌面与移动端共用失败处理:响应不明或后续处理失败时保留计划,用户确认并按身份核对后才继续;关闭或锁定笔记本清除相应标题和模板缓存。本地速记使用仅含身份和摘要的恢复记录,核对实际源中的块身份后才清理输入,未确认的结果保留原速记并停止自动重放。++管理员读取笔记本配置时可获取 `documentCapabilities`,区分结构化接口、实际寻址模式和索引状态。未验证真实保护版本时,`minimumReaderVersion` 返回 `null`,不会伪造最低版本;能力记录损坏时明确报错。原生整本导入会同步重映射目标配置中的笔记本和锚点 ID,部分文档导入保留目标笔记本配置。加密目标载荷保持锁定保存、改密及备份恢复的认证边界。++目前只开放兼容模式 `1`,仍拒绝标题中的 ASCII `/`,版本 `2` 目标配置的公开写入仍受模式门槛限制。显式启用入口、模式 `2` 的源格式与冲突恢复、旧字符串接口的整本拒绝以及相应启用界面尚未交付;不能把这些工作视为仅待发布开关。阶段 D 还需结合真实保护版本的验证结果确定最低读取版本和 `DocumentTitleSpec`,完成混合版本、性能及各端验收后开放。行级标题扩展约束保持不变。+## 目标与范围文档使用 ID 确定身份和所属层级,标题用于表达内容,可读路径用于展示。创建、移动和引用不得依赖从展示文本反向解析文档身份。完成相关入口迁移与兼容验证后,文档标题可以包含半角斜杠 `/`,并与原有全角斜杠 `/` 保持区别。@@ -315,9 +325,15 @@旧 `/api/filetree/getDocCreateSavePath` 与 `/api/filetree/getRefCreateSavePath` 在各自生效配置仍为旧模板时保持原响应;对应的新对象生效时均返回 `code: -1`、`data: {reason: "structuredTemplateRequired"}`,不返回已经失效的旧路径。判断依据是配置来源及对应业务,不取决于旧路径或新目标指向哪个笔记本;旧目标仍为模式 `1` 也不能放行历史配置。两个错误变体分别在旧契约中声明。新增读取入口同时服务内置调用方和插件,避免各自重复实现配置继承规则。+### 规划配置中的创建目标++`/api/filetree/planDocCreate` 接收 `notebook`、`purpose` 和最终文档的固定 `id`;可选 `contextID` 提供当前文档,省略或 `null` 表示没有当前文档;可选 `title` 覆盖最终标题,`placement` 为 `configured` 或 `child`,`reuse` 控制是否允许复用已有最终文档。它只求值和校验,不写入文档。一次计划中的时间模板使用同一时间快照,返回最终标题、目标笔记本、可选的 `existingID`,以及包含固定 ID、父身份、名称条件和配置版本的有序 `steps`。++调用方依次提交每个 `createDocByParent` 请求,用上一项成功响应的路径版本更新下一项的父版本。提交后以返回 ID 为准;错误按提交状态处理,不能重新生成一组 ID 并盲目重放。单次计划不是跨文件事务,计划期间的成功校验也不代替每次提交时的复核。+### 能力探测与启用-在 `/api/notebook/getNotebookConf` 的 `data` 中增加可选只读对象 `documentCapabilities`,保留现有 `box`、`name`、`conf` 和权限过滤。对象包含 `addressingVersion`、`modeState`、`structuredPaths`、`literalSlash`、`titleFormats`、`indexState`、`minimumReaderVersion` 和 `revision`。`modeState` 为 `legacy`、`structured`、`conflict` 或 `recovering`;`structuredPaths` 表示服务端实现了新协议,`indexState` 表示派生索引状态,均不代替模式状态。首版 `titleFormats` 为 `["plain"]`,`literalSlash` 仅在模式 `2`、`modeState: "structured"` 且索引就绪时为 `true`。+在 `/api/notebook/getNotebookConf` 的 `data` 中增加可选只读对象 `documentCapabilities`,保留现有 `box`、`name`、`conf` 和权限过滤。对象包含 `addressingVersion`、`modeState`、`structuredPaths`、`literalSlash`、`titleFormats`、`indexState`、`minimumReaderVersion` 和 `revision`。`modeState` 为 `legacy`、`structured`、`conflict` 或 `recovering`;`structuredPaths` 表示服务端实现了新协议,`indexState` 表示派生索引状态,均不代替模式状态。管理员响应包含该对象,其他角色保持原有配置过滤。保护版本尚未验证时 `minimumReaderVersion` 为 `null`;确认真实最低版本后才返回版本字符串。首版 `titleFormats` 为 `["plain"]`,`literalSlash` 仅在模式 `2`、`modeState: "structured"` 且索引就绪时为 `true`。`revision` 是启用流程相关的配置版本;它不等同于某篇文档的路径版本。能力声明不授予访问权限,关闭或锁定笔记本时仍执行原有访问限制;状态读取不得暴露标题或受保护的模板内容。旧服务端没有该对象时,插件只能使用旧能力。鉴权、锁定或网络请求失败不能被当作“服务端不支持”,更不能据此回退后继续写入。@@ -368,6 +384,8 @@文档写入同时校验待写内容及磁盘上的当前源文件。加密源先认证再解释,在同一文件锁内完成当前源校验和落盘,避免旧缓存覆盖后来出现的不兼容源。自动修复还要求当前源与最初检查的字节一致;校验失败不能继续回退写入或截断文件。普通文档保留按页写入方式,加密文档保留密文原子替换。+原始文件接口中的笔记本及文档 ID 路径同样受源格式检查保护,不能通过上传、复制或移入文件绕过。整批预检在创建目标目录及首次复制前完成,实际文档复制使用已经校验的读取字节,并在文件锁内重新检查目标源;检查后的并发变化或 I/O 失败仍可能留下已完成的复制,不承诺整批回滚。普通附件和插件目录下的 `.sy` 文件保持原始文件语义,加密笔记本仍禁止通过原始文件接口读写。+最低兼容版本由真实发布版本的读写及拒绝测试确定。保护版本之前忽略能力标记的客户端无法由新字段自动约束,不在安全混用承诺内。启用前要求所有同步设备升级;系统无法证明离线设备状态,应明确说明这一限制。如果已支持版本仍存在会改写数据的路径,保持新能力关闭,不能以文档提示代替必要保护。模式 `2` 启用后不提供直接改回 `1` 的开关。即使当前标题已不含 `/`,历史和备份仍可能包含新格式。回退客户端只能使用经验证的兼容导出副本,或恢复启用前的完整备份到独立工作空间;不能将旧配置覆盖回原工作空间并继续同步。若未来提供降级转换,应另行设计转换清单、冲突处理和恢复机制,保留原数据。@@ -489,7 +507,7 @@| 源文档与只读路径恢复 | [`filesys/tree.go`](../kernel/filesys/tree.go)、[`filesys/hpath.go`](../kernel/filesys/hpath.go) || 路径刷新、恢复队列与文档索引 | [`treenode/blocktree.go`](../kernel/treenode/blocktree.go)、[`treenode/hpath.go`](../kernel/treenode/hpath.go)、[`model/hpath_refresh.go`](../kernel/model/hpath_refresh.go)、[`sql/queue.go`](../kernel/sql/queue.go) || 搜索及层级计算 | [`model/search.go`](../kernel/model/search.go)、[`sql/block_query.go`](../kernel/sql/block_query.go)、[`search/config.ts`](../app/src/search/config.ts) |-| 新建入口与保存路径解析 | [`util/newFile.ts`](../app/src/util/newFile.ts)、[`util/parseNewDocTarget.ts`](../app/src/util/parseNewDocTarget.ts)、[`mobile/util/initFramework.ts`](../app/src/mobile/util/initFramework.ts) |+| 新建入口与保存路径解析 | [`util/newFile.ts`](../app/src/util/newFile.ts)、[`util/configuredDocument.ts`](../app/src/util/configuredDocument.ts)、[`mobile/util/initFramework.ts`](../app/src/mobile/util/initFramework.ts) || 模板、数据库新建及速记 | [`model/template_doc_tree.go`](../kernel/model/template_doc_tree.go)、[`model/attribute_view_new_item.go`](../kernel/model/attribute_view_new_item.go)、[`model/shortcuts.go`](../kernel/model/shortcuts.go) || 日记复用及旧创建回归 | [`model/daily_note.go`](../kernel/model/daily_note.go)、[`model/file_test.go`](../kernel/model/file_test.go) || 导入与导出 | [`model/import.go`](../kernel/model/import.go)、[`model/import_obsidian.go`](../kernel/model/import_obsidian.go)、[`model/export.go`](../kernel/model/export.go) |diff --git a/kernel/api/archive.go b/kernel/api/archive.goindex 9a835e1d24..310b6a1b78 100644--- a/kernel/api/archive.go+++ b/kernel/api/archive.go@@ -145,6 +145,9 @@ var zip = contractHandler(apicontract.Zip, func(c *gin.Context, request apicontrret.Msg = err.Error()return contractFailure[apicontract.Null](ret)}+ if err = model.CheckDocumentAddressingFileWrite(resolvedZipPath, nil, false); err != nil {+ return apicontract.Failure[apicontract.Null](-1, err.Error())+ }zipFile, err := gulu.Zip.Create(resolvedZipPath)if err != nil {logging.LogErrorf("create zip [%s] failed: %s", zipAbsFilePath, err)@@ -244,13 +247,53 @@ func unzipWorkspaceArchive(zipPath, destination string) error {if err = validateArchiveEntryPath(destination, paths[i]); err != nil {return err}+ if entry.FileInfo().IsDir() {+ if err = model.CheckDocumentAddressingFileWrite(paths[i], nil, true); err != nil {+ return err+ }+ }+ }+ // 解压到隔离目录后预检整个写入集合,拒绝未知模式或源格式时不创建目标目录。+ staging, err := os.MkdirTemp("", "siyuan-archive-*")+ if err != nil {+ return err+ }+ defer os.RemoveAll(staging)+ sources := make([]string, len(reader.File))+ var copySources, copyDestinations []string+ for i, entry := range reader.File {+ if entry.FileInfo().IsDir() {+ continue+ }+ sources[i] = filepath.Join(staging, fmt.Sprint(i))+ if err = extractWorkspaceArchiveEntry(entry, sources[i]); err != nil {+ return err+ }+ copySources = append(copySources, sources[i])+ copyDestinations = append(copyDestinations, paths[i])+ }+ if err = model.CheckDocumentAddressingFileCopies(copySources, copyDestinations); err != nil {+ return err}for i, entry := range reader.File {// 解压前再次检查已有符号链接和加密身份,不复用预检阶段的路径判定结果。if err = validateArchiveEntryPath(destination, paths[i]); err != nil {return err}- if err = extractWorkspaceArchiveEntry(entry, paths[i]); err != nil {+ if entry.FileInfo().IsDir() {+ err = model.CheckDocumentAddressingFileWrite(paths[i], nil, true)+ if err == nil {+ err = os.MkdirAll(paths[i], 0755)+ }+ } else {+ if err = model.CheckDocumentAddressingFileCopies([]string{sources[i]}, []string{paths[i]}); err == nil {+ err = os.MkdirAll(filepath.Dir(paths[i]), 0755)+ }+ if err == nil {+ err = model.CopyFileWithDocumentAddressing(sources[i], paths[i])+ }+ }+ if err != nil {return err}}diff --git a/kernel/api/block.go b/kernel/api/block.goindex 462c2e56b5..5d4bc6e476 100644--- a/kernel/api/block.go+++ b/kernel/api/block.go@@ -723,8 +723,7 @@ var getBlockInfo = contractHandler(apicontract.GetBlockInfo, func(c *gin.Contextif errors.Is(err, model.ErrIndexing) {return apicontract.FailureWithText[apicontract.BlockInfoData](3, ret.Msg, model.Conf.Language(56))}- rootTitle := root.IAL["title"]- rootTitle = html.UnescapeString(rootTitle)+ rootTitle := treenode.ReadDocumentTitle(tree.Root).Texticon := html.UnescapeString(root.IAL["icon"])if publishAccessRequired {return apicontract.Success[apicontract.BlockInfoData](apicontract.PublishedBlockInfo{diff --git a/kernel/api/block_test.go b/kernel/api/block_test.goindex e8596e8791..4bdebe0f7b 100644--- a/kernel/api/block_test.go+++ b/kernel/api/block_test.go@@ -42,7 +42,7 @@ import ()func TestGetBlockInfoRecovery(t *testing.T) {- for _, name := range []string{"document", "child", "explicit", "missing", "indexing", "reader", "encrypted"} {+ for _, name := range []string{"document", "child", "metadataOnly", "literalTitle", "explicit", "missing", "indexing", "reader", "encrypted"} {t.Run(name, func(t *testing.T) {if os.Getenv("SIYUAN_TEST_BLOCK_INFO_RECOVERY") == t.Name() {testGetBlockInfoRecovery(t, name)@@ -93,10 +93,18 @@ func testGetBlockInfoRecovery(t *testing.T, name string) {sql.InitAssetContentDatabase(true)defer sql.CloseDatabase()docID := ast.NewNodeID()- tree := treenode.NewTree(box.ID, "/"+docID+".sy", "/Recovered", "Recovered")+ title := "Recovered"+ if name == "literalTitle" {+ title = "**Literal & title**"+ }+ tree := treenode.NewTree(box.ID, "/"+docID+".sy", "/"+title, title)if _, err := filesys.WriteTree(tree); err != nil {t.Fatal(err)}+ if name != "metadataOnly" {+ // 源提交会立即登记文档摘要;这些用例需要模拟索引整体缺失。+ treenode.RemoveBlockTreesByRootID(box.ID, docID)+ }if name == "encrypted" {// 加密候选即使带有可解析的明文,也不能由普通笔记本恢复路径读取或索引。boxConf.Encrypted = true@@ -108,6 +116,8 @@ func testGetBlockInfoRecovery(t *testing.T, name string) {switch name {case "child":id = tree.Root.FirstChild.ID+ case "metadataOnly":+ id = tree.Root.FirstChild.IDcase "missing":id = ast.NewNodeID()}@@ -150,8 +160,8 @@ func testGetBlockInfoRecovery(t *testing.T, name string) {t.Fatal(err)}switch name {- case "document", "child", "explicit":- if response.Code != 0 || response.Data.RootID != docID || response.Data.RootTitle != "Recovered" {+ case "document", "child", "metadataOnly", "literalTitle", "explicit":+ if response.Code != 0 || response.Data.RootID != docID || response.Data.RootTitle != title {t.Fatalf("document did not recover: %s", recorder.Body.String())}if treenode.GetBlockTree(id) == nil {diff --git a/kernel/api/box_lease_test.go b/kernel/api/box_lease_test.goindex 9f244f363c..9c4659a8a7 100644--- a/kernel/api/box_lease_test.go+++ b/kernel/api/box_lease_test.go@@ -89,6 +89,26 @@ func TestContractDailyNoteInfoNotebookResponseLease(t *testing.T) {runNotebookResponseLease(t, true, false)}+func TestContractDocumentPathsNotebookResponseLease(t *testing.T) {+ runNotebookResponseLease(t, true, false)+}++func TestContractResolveDocumentPathNotebookResponseLease(t *testing.T) {+ runNotebookResponseLease(t, true, false)+}++func TestContractCreateDocumentByParentNotebookResponseLease(t *testing.T) {+ runNotebookResponseLease(t, true, false)+}++func TestContractDocumentCreateTargetNotebookResponseLease(t *testing.T) {+ runNotebookResponseLease(t, true, false)+}++func TestContractDocumentCreatePlanNotebookResponseLease(t *testing.T) {+ runNotebookResponseLease(t, true, false)+}+func TestContractGetDocNotebookResponseLease(t *testing.T) {runNotebookResponseLease(t, true, false)}@@ -211,7 +231,12 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {model.Conf.Export.Store(confSectionValue1)model.Conf.Search.Store(confSectionValue2)}- if t.Name() == "TestContractDailyNoteNotebookResponseLease" || t.Name() == "TestContractDailyNoteInfoNotebookResponseLease" {+ addressingTest := t.Name() == "TestContractDocumentPathsNotebookResponseLease" ||+ t.Name() == "TestContractResolveDocumentPathNotebookResponseLease" ||+ t.Name() == "TestContractDocumentCreateTargetNotebookResponseLease" ||+ t.Name() == "TestContractDocumentCreatePlanNotebookResponseLease" ||+ t.Name() == "TestContractCreateDocumentByParentNotebookResponseLease"+ if addressingTest || t.Name() == "TestContractDailyNoteNotebookResponseLease" || t.Name() == "TestContractDailyNoteInfoNotebookResponseLease" {content, err := os.ReadFile(filepath.Join("..", "..", "app", "appearance", "langs", "en.json"))if err != nil {t.Fatal(err)@@ -259,11 +284,16 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {t.Fatal(err)}treenode.UpsertBlockTree(tree)- if t.Name() == "TestContractDailyNoteNotebookResponseLease" || t.Name() == "TestContractDailyNoteInfoNotebookResponseLease" {+ if addressingTest || t.Name() == "TestContractDailyNoteNotebookResponseLease" || t.Name() == "TestContractDailyNoteInfoNotebookResponseLease" {if _, err := model.Mount(boxID); err != nil {t.Fatal(err)}}+ if addressingTest {+ if err := treenode.SetDocumentMetadataState(boxID, "ready"); err != nil {+ t.Fatal(err)+ }+ }}gin.SetMode(gin.TestMode)engine := gin.New()@@ -275,6 +305,11 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {engine.POST("/api/block/getDocInfo", getDocInfo)engine.POST("/api/filetree/createDailyNote", createDailyNote)engine.POST("/api/filetree/getDailyNoteInfo", getDailyNoteInfo)+ engine.POST("/api/filetree/getDocPaths", getDocPaths)+ engine.POST("/api/filetree/resolveDocPath", resolveDocPath)+ engine.POST("/api/filetree/createDocByParent", createDocByParent)+ engine.POST("/api/filetree/getDocCreateTarget", getDocCreateTarget)+ engine.POST("/api/filetree/planDocCreate", planDocCreate)engine.POST("/api/filetree/getDoc", getDoc)engine.POST("/api/block/getTreeStat", getTreeStat)engine.POST("/api/block/getBlockBreadcrumb", getBlockBreadcrumb)@@ -317,6 +352,22 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {}typedQuery := falseswitch t.Name() {+ case "TestContractDocumentCreateTargetNotebookResponseLease":+ endpoint, typedQuery = "/api/filetree/getDocCreateTarget", true+ args = map[string]any{"notebook": boxIDs[0], "purpose": "document"}+ case "TestContractDocumentCreatePlanNotebookResponseLease":+ endpoint, typedQuery = "/api/filetree/planDocCreate", true+ args = map[string]any{"notebook": boxIDs[0], "purpose": "document", "id": ast.NewNodeID(), "title": "REVIEW-SECRET-TITLE"}+ case "TestContractDocumentPathsNotebookResponseLease":+ endpoint, typedQuery = "/api/filetree/getDocPaths", true+ args = map[string]any{"notebook": boxIDs[0], "ids": []string{boxIDs[0]}}+ case "TestContractResolveDocumentPathNotebookResponseLease":+ endpoint, typedQuery = "/api/filetree/resolveDocPath", true+ args = map[string]any{"notebook": boxIDs[0], "start": map[string]any{"kind": "document", "id": boxIDs[0]}, "segments": []string{}}+ case "TestContractCreateDocumentByParentNotebookResponseLease":+ endpoint, typedQuery = "/api/filetree/createDocByParent", true+ args = map[string]any{"notebook": boxIDs[0], "parentID": nil, "id": ast.NewNodeID(),+ "title": map[string]string{"format": "plain", "text": "REVIEW-SECRET-TITLE"}, "markdown": "REVIEW-SECRET-CONTENT"}case "TestContractBlockSwapReplayNotebookResponseLease":endpoint, typedQuery = "/review/blockSwapLease", truecase "TestContractCheckBlockRefNotebookResponseLease":diff --git a/kernel/api/contract.go b/kernel/api/contract.goindex 7ba52a0da4..04207bbfce 100644--- a/kernel/api/contract.go+++ b/kernel/api/contract.go@@ -21,7 +21,10 @@ func notebookConfContract(value *conf.BoxConf) *apicontract.NotebookConf {return nil}result := &apicontract.NotebookConf{- Name: value.Name, Sort: value.Sort, Icon: value.Icon, Closed: value.Closed,+ DocCreateTarget: documentTargetContract(value.DocCreateTarget),+ RefCreateTarget: documentTargetContract(value.RefCreateTarget),+ DailyNoteTarget: documentTargetContract(value.DailyNoteTarget),+ Name: value.Name, Sort: value.Sort, Icon: value.Icon, Closed: value.Closed,RefCreateSaveBox: value.RefCreateSaveBox, RefCreateSavePath: value.RefCreateSavePath,DocCreateSaveBox: value.DocCreateSaveBox, DocCreateSavePath: value.DocCreateSavePath,DocCreateTemplatePath: value.DocCreateTemplatePath, DailyNoteSavePath: value.DailyNoteSavePath,diff --git a/kernel/api/contract_document_addressing_archive_test.go b/kernel/api/contract_document_addressing_archive_test.gonew file mode 100644index 0000000000..deb3ab7dbe--- /dev/null+++ b/kernel/api/contract_document_addressing_archive_test.go@@ -0,0 +1,77 @@+package api++import (+ archivezip "archive/zip"+ "encoding/json"+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAPIContractDocumentAddressingArchives(t *testing.T) {+ addressingAPIWorkspace(t)+ const document = "20261023000000-rawdoc1.sy"+ ordinary := `{"Spec":"2","Properties":{"title":"A&#47;B"}}`+ future := `{"Spec":"999","Properties":{"title":"Future"}}`+ archive := filepath.Join(util.WorkspaceDir, "source.zip")+ write := func(entries [][2]string) {+ t.Helper()+ file, err := os.Create(archive)+ if err != nil {+ t.Fatal(err)+ }+ writer := archivezip.NewWriter(file)+ for _, entry := range entries {+ out, createErr := writer.Create(entry[0])+ if createErr != nil {+ t.Fatal(createErr)+ }+ if _, err = out.Write([]byte(entry[1])); err != nil {+ t.Fatal(err)+ }+ }+ if err = writer.Close(); err != nil {+ t.Fatal(err)+ }+ if err = file.Close(); err != nil {+ t.Fatal(err)+ }+ }+ name := addressingAPIBox + "/" + document+ for _, entries := range [][][2]string{+ {{"first.txt", "first"}, {name, future}},+ {{"first.txt", "first"}, {addressingAPIBox + "/.siyuan/conf.json", `{"documentAddressingVersion":2}`}},+ {{"first.txt", "first"}, {name, future}, {name, ordinary}},+ } {+ write(entries)+ result := callArchiveAPI(t, unzip, `{"zipPath":"source.zip","path":"data"}`)+ if result.Code == 0 {+ t.Fatal("unzip accepted unsupported source")+ }+ if _, err := os.Stat(filepath.Join(util.DataDir, "first.txt")); !os.IsNotExist(err) {+ t.Fatal("unzip wrote an earlier entry before checking the full batch", err)+ }+ }+ // 采用过更高模式的身份不能复用;兼容成功使用独立笔记本身份。+ name = "20261023000001-rawbox2/" + document+ write([][2]string{{name, ordinary}, {"assets/" + document, "arbitrary attachment"}, {"empty/", ""}})+ if result := callArchiveAPI(t, unzip, `{"zipPath":"source.zip","path":"data"}`); result.Code != 0 {+ t.Fatalf("compatible archive rejected: %+v", result)+ }+ if data, err := os.ReadFile(filepath.Join(util.DataDir, name)); err != nil || string(data) != ordinary {+ t.Fatalf("unzip changed source bytes: %q, %v", data, err)+ }+ addressingAPIWrite(t, filepath.Join(util.DataDir, name), future)+ if result := callArchiveAPI(t, unzip, `{"zipPath":"source.zip","path":"data"}`); result.Code == 0 {+ t.Fatal("unzip overwrote unsupported existing document")+ }+ payload, _ := json.Marshal(map[string]string{"path": "data/assets", "zipPath": "data/" + name})+ if result := callArchiveAPI(t, zip, string(payload)); result.Code == 0 {+ t.Fatal("zip overwrote a document source")+ }+ if data, _ := os.ReadFile(filepath.Join(util.DataDir, name)); string(data) != future {+ t.Fatal("archive API modified protected source")+ }+}diff --git a/kernel/api/contract_document_addressing_test.go b/kernel/api/contract_document_addressing_test.goindex e20d0ba909..473f00e129 100644--- a/kernel/api/contract_document_addressing_test.go+++ b/kernel/api/contract_document_addressing_test.go@@ -182,6 +182,136 @@ func TestAPIContractDocumentAddressingIncomingBatch(t *testing.T) {}}+func TestAPIContractDocumentAddressingDocumentSources(t *testing.T) {+ addressingAPIWorkspace(t)+ const document = "20261022130000-rawdoc1.sy"+ name := "data/" + addressingAPIBox + "/" + document+ abs := filepath.Join(util.WorkspaceDir, name)+ ordinary := `{"Spec":"2","Properties":{"title":"Ordinary"}}`+ for _, unsupported := range []string{+ `{"Spec":"999","Properties":{"title":"Future"}}`,+ `{"Spec":"2","Properties":{"title":"A/B"}}`,+ `{"Spec":"2","Properties":{"title":{"format":"future"}}}`,+ `{"Spec":"999","Spec":"2","Properties":{"title":"Future"}}`,+ `null`,+ } {+ addressingAPIWrite(t, abs, ordinary)+ before, _ := os.Stat(abs)+ if code := addressingAPIPut(t, name, unsupported, false); code != -1 {+ t.Fatalf("put accepted an incompatible document source: %d", code)+ }+ after, _ := os.Stat(abs)+ data, _ := os.ReadFile(abs)+ if string(data) != ordinary || !before.ModTime().Equal(after.ModTime()) {+ t.Fatal("rejected source changed the existing document")+ }+ addressingAPIWrite(t, abs, unsupported)+ before, _ = os.Stat(abs)+ if code := addressingAPIPut(t, name, ordinary, false); code != -1 {+ t.Fatalf("put overwrote an incompatible existing source: %d", code)+ }+ after, _ = os.Stat(abs)+ data, _ = os.ReadFile(abs)+ if string(data) != unsupported || !before.ModTime().Equal(after.ModTime()) {+ t.Fatal("existing incompatible source was modified")+ }+ }+ addressingAPIWrite(t, abs, ordinary)+ for _, title := range []string{"A&#47;B", "A%2FB", "A/B", "**literal**"} {+ source := `{"Spec":"2","Properties":{"title":"` + title + `"}}`+ if code := addressingAPIPut(t, name, source, false); code != 0 {+ t.Fatalf("compatible title was rejected: %d", code)+ }+ data, _ := os.ReadFile(abs)+ if string(data) != source {+ t.Fatal("raw document write normalized source bytes")+ }+ }+ if code := addressingAPIPut(t, "data/assets/"+document, "arbitrary attachment", false); code != 0 {+ t.Fatalf("attachment was treated as a document: %d", code)+ }+}++func TestAPIContractDocumentAddressingDocumentCopies(t *testing.T) {+ addressingAPIWorkspace(t)+ const document = "20261022130000-rawdoc1.sy"+ name := "data/" + addressingAPIBox + "/" + document+ abs := filepath.Join(util.WorkspaceDir, name)+ ordinary := `{"Spec":"2","Properties":{"title":"Ordinary"}}`+ future := `{"Spec":"999","Properties":{"title":"Future"}}`+ source := filepath.Join(util.DataDir, "assets", document)+ addressingAPIWrite(t, source, future)+ addressingAPIWrite(t, abs, ordinary)+ if code := addressingAPIRequest(t, "copyFile", copyFile,+ apicontract.CopyFileRequest{Src: "assets/" + document, Dest: abs}); code != -1 {+ t.Fatalf("copy accepted an incompatible incoming source: %d", code)+ }+ addressingAPIWrite(t, source, ordinary)+ addressingAPIWrite(t, abs, future)+ if code := addressingAPIRequest(t, "copyFile", copyFile,+ apicontract.CopyFileRequest{Src: "assets/" + document, Dest: abs}); code != -1 {+ t.Fatalf("copy overwrote an incompatible existing source: %d", code)+ }+ if data, _ := os.ReadFile(abs); string(data) != future {+ t.Fatal("copy changed the protected destination")+ }+ addressingAPIWrite(t, source, future)+ first := filepath.Join(util.DataDir, "assets", "first.txt")+ addressingAPIWrite(t, first, "ordinary attachment")+ for _, request := range []struct {+ name string+ handler gin.HandlerFunc+ sources []string+ }{+ {"globalCopyFiles", globalCopyFiles, []string{first, source}},+ {"workspaceCopyFiles", workspaceCopyFiles, []string{"data/assets/first.txt", "data/assets/" + document}},+ } {+ if code := addressingAPIRequest(t, request.name, request.handler,+ apicontract.CopyFilesRequest{Srcs: request.sources, DestDir: "data/" + addressingAPIBox}); code != -1 {+ t.Fatalf("%s accepted an incompatible batch: %d", request.name, code)+ }+ if _, err := os.Stat(filepath.Join(util.DataDir, addressingAPIBox, "first.txt")); !os.IsNotExist(err) {+ t.Fatal("batch copied an earlier file before checking all sources", err)+ }+ }+ destination := "data/" + addressingAPIBox + "/20261022130000-parent1/" + document+ if code := addressingAPIRequest(t, "renameFile", renameFile,+ apicontract.RenameFileRequest{Path: "data/assets/" + document, NewPath: destination}); code != -1 {+ t.Fatalf("rename installed an incompatible source as a document: %d", code)+ }+ if data, _ := os.ReadFile(source); string(data) != future {+ t.Fatal("rejected rename changed the source")+ }+ if _, err := os.Stat(filepath.Dir(filepath.Join(util.WorkspaceDir, destination))); !os.IsNotExist(err) {+ t.Fatal("rejected rename created the destination parent", err)+ }+ addressingAPIWrite(t, source, ordinary)+ addressingAPIWrite(t, abs, ordinary)+ for _, request := range []struct {+ name string+ handler gin.HandlerFunc+ body interface{}+ }{+ {"copyFile", copyFile, apicontract.CopyFileRequest{Src: "assets/" + document, Dest: abs}},+ {"globalCopyFiles", globalCopyFiles, apicontract.CopyFilesRequest{Srcs: []string{source}, DestDir: "data/" + addressingAPIBox}},+ {"workspaceCopyFiles", workspaceCopyFiles, apicontract.CopyFilesRequest{Srcs: []string{"data/assets/" + document}, DestDir: "data/" + addressingAPIBox}},+ } {+ if code := addressingAPIRequest(t, request.name, request.handler, request.body); code != 0 {+ t.Fatalf("%s rejected a compatible document: %d", request.name, code)+ }+ if data, _ := os.ReadFile(abs); string(data) != ordinary {+ t.Fatal("compatible document copy changed source bytes")+ }+ }+ if code := addressingAPIRequest(t, "renameFile", renameFile,+ apicontract.RenameFileRequest{Path: "data/assets/" + document, NewPath: destination}); code != 0 {+ t.Fatalf("compatible document move failed: %d", code)+ }+ if data, _ := os.ReadFile(filepath.Join(util.WorkspaceDir, destination)); string(data) != ordinary {+ t.Fatal("compatible document move changed source bytes")+ }+}+func TestAPIContractDocumentAddressingSettingsBackup(t *testing.T) {addressingAPIWorkspace(t)addressingAPIWrite(t, filepath.Join(util.DataDir, addressingAPIBox, ".siyuan", "conf.json"), `{"documentAddressingVersion":2}`)diff --git a/kernel/api/contract_document_capabilities_test.go b/kernel/api/contract_document_capabilities_test.gonew file mode 100644index 0000000000..27f35e101f--- /dev/null+++ b/kernel/api/contract_document_capabilities_test.go@@ -0,0 +1,69 @@+package api++import (+ "bytes"+ "encoding/json"+ "os"+ "path/filepath"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/documentaddressing"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAPIContractDocumentCapabilities(t *testing.T) {+ boxID := documentPathAPIWorkspace(t)+ admin := func(c *gin.Context) {+ c.Set(model.RoleContextKey, model.RoleAdministrator)+ getNotebookConf(c)+ }+ read := func() *apicontract.DocumentCapabilities {+ t.Helper()+ data := documentPathAPIRequest(t, "/api/notebook/getNotebookConf", admin, map[string]string{"notebook": boxID})+ var response struct {+ Code int+ Data apicontract.NotebookConfData+ }+ if err := json.Unmarshal(data, &response); err != nil || response.Code != 0 || response.Data.DocumentCapabilities == nil {+ t.Fatalf("capability response failed: %s, %v", data, err)+ }+ return response.Data.DocumentCapabilities+ }+ capabilities := read()+ public := documentPathAPIRequest(t, "/api/notebook/getNotebookConf", func(c *gin.Context) {+ c.Set(model.RoleContextKey, model.RoleEditor)+ getNotebookConf(c)+ }, map[string]string{"notebook": boxID})+ if bytes.Contains(public, []byte(`"documentCapabilities"`)) {+ t.Fatal("configuration permissions were widened by capability discovery")+ }+ if !capabilities.StructuredPaths || capabilities.LiteralSlash || capabilities.AddressingVersion != 1 ||+ capabilities.ModeState != "legacy" || capabilities.IndexState != "missing" || capabilities.MinimumReaderVersion != nil ||+ len(capabilities.TitleFormats) != 1 || capabilities.TitleFormats[0] != "plain" || capabilities.Revision == "" {+ t.Fatalf("capabilities claimed an unimplemented or unverified feature: %+v", capabilities)+ }+ if err := treenode.SetDocumentMetadataState(boxID, "ready"); err != nil {+ t.Fatal(err)+ }+ if current := read(); current.IndexState != "ready" || current.LiteralSlash || current.Revision != capabilities.Revision {+ t.Fatalf("index readiness enabled new characters or changed the configuration revision: %+v", current)+ }+ name := filepath.Join(util.DataDir, boxID, documentaddressing.FloorPath)+ if err := os.WriteFile(name, []byte(`{"version":1,"notebook":"`+boxID+`","minimumMode":2}`), 0600); err != nil {+ t.Fatal(err)+ }+ if current := read(); current.AddressingVersion != 2 || current.ModeState != "conflict" || current.LiteralSlash || current.Revision == capabilities.Revision {+ t.Fatalf("unsupported mode was reported as writable: %+v", current)+ }+ if err := os.WriteFile(name, []byte(`{"version":99}`), 0600); err != nil {+ t.Fatal(err)+ }+ data := documentPathAPIRequest(t, "/api/notebook/getNotebookConf", admin, map[string]string{"notebook": boxID})+ if !bytes.Contains(data, []byte(`"code":-1`)) || bytes.Contains(data, []byte(`"documentCapabilities"`)) {+ t.Fatalf("damaged capability record silently fell back to legacy mode: %s", data)+ }+}diff --git a/kernel/api/contract_document_path_test.go b/kernel/api/contract_document_path_test.gonew file mode 100644index 0000000000..1155f181ce--- /dev/null+++ b/kernel/api/contract_document_path_test.go@@ -0,0 +1,231 @@+package api++import (+ "bytes"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "path/filepath"+ "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/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func documentPathAPIWorkspace(t *testing.T) string {+ t.Helper()+ addressingAPIWorkspace(t)+ previousConf, previousPath := model.Conf, util.BlockTreeDBPath+ model.Conf = model.NewAppConf()+ model.Conf.FileTree.Store(conf.NewFileTree())+ model.Conf.NotebookCrypto = conf.NewNotebookCrypto()+ model.Conf.Sync.Store(conf.NewSync())+ util.BlockTreeDBPath = filepath.Join(t.TempDir(), "blocktree.db")+ treenode.InitBlockTree(true)+ t.Cleanup(func() {+ treenode.CloseDatabase()+ model.Conf, util.BlockTreeDBPath = previousConf, previousPath+ if previousPath != "" {+ treenode.InitBlockTree(false)+ }+ })+ box := &model.Box{ID: addressingAPIBox}+ boxConf := conf.NewBoxConf()+ boxConf.Name, boxConf.Closed = "Documents", false+ if err := box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ return box.ID+}++func documentPathAPIRequest(t *testing.T, route string, handler gin.HandlerFunc, payload interface{}) []byte {+ t.Helper()+ body, err := json.Marshal(payload)+ if err != nil {+ t.Fatal(err)+ }+ engine := gin.New()+ engine.POST(route, boxLeaseMiddleware, handler)+ recorder := httptest.NewRecorder()+ request := httptest.NewRequest("POST", route, bytes.NewReader(body))+ request.Header.Set("Content-Type", "application/json")+ engine.ServeHTTP(recorder, request)+ requireAPIContract(t, "POST", route, recorder)+ return recorder.Body.Bytes()+}++func TestAPIContractDocumentPaths(t *testing.T) {+ box := documentPathAPIWorkspace(t)+ parent := treenode.NewTree(box, "/20261023010000-parent1.sy", "/A", "A")+ child := treenode.NewTree(box, "/20261023010000-parent1/20261023010001-child01.sy", "/A/B", "B")+ treenode.UpsertBlockTree(parent)+ treenode.UpsertBlockTree(child)+ const missing = "20261023010002-missing"+ request := apicontract.GetDocPathsRequest{Notebook: box, IDs: []string{child.ID, missing, parent.ID, child.ID, child.Root.FirstChild.ID}}+ response := documentPathAPIRequest(t, "/api/filetree/getDocPaths", getDocPaths, request)+ if !bytes.Contains(response, []byte(`"reason":"indexUnavailable"`)) {+ t.Fatalf("unready index was treated as missing: %s", response)+ }+ if err := treenode.SetDocumentMetadataState(box, "ready"); err != nil {+ t.Fatal(err)+ }+ response = documentPathAPIRequest(t, "/api/filetree/getDocPaths", getDocPaths, request)+ var result struct {+ Code int+ Data apicontract.DocumentPathsData+ }+ if err := json.Unmarshal(response, &result); err != nil || result.Code != 0 {+ t.Fatalf("read failed: %s, %v", response, err)+ }+ if len(result.Data.Documents) != 2 || result.Data.Documents[0].ID != child.ID || result.Data.Documents[1].ID != parent.ID ||+ len(result.Data.MissingIDs) != 2 || result.Data.MissingIDs[0] != missing || result.Data.Documents[0].Depth != 2 ||+ result.Data.Documents[0].Segments[0].ID != parent.ID {+ t.Fatalf("identity, order or missing results changed: %s", response)+ }+ for _, ids := range [][]string{{}, make([]string, 129), {"invalid"}} {+ request.IDs = ids+ response = documentPathAPIRequest(t, "/api/filetree/getDocPaths", getDocPaths, request)+ if !bytes.Contains(response, []byte(`"code":-1`)) {+ t.Fatalf("invalid IDs accepted: %s", response)+ }+ }+}++func TestAPIContractCreateDocumentRequest(t *testing.T) {+ box := documentPathAPIWorkspace(t)+ if err := treenode.SetDocumentMetadataState(box, "ready"); err != nil {+ t.Fatal(err)+ }+ const id = "20261023010001-created"+ for _, mutate := range []func(map[string]interface{}){+ func(value map[string]interface{}) { delete(value, "parentID") },+ func(value map[string]interface{}) { delete(value, "markdown") },+ func(value map[string]interface{}) { value["path"] = "/Legacy" },+ func(value map[string]interface{}) { value["hPath"] = "/Legacy" },+ func(value map[string]interface{}) { value["parentID"] = "" },+ func(value map[string]interface{}) { value["expectedParentRevision"] = nil },+ func(value map[string]interface{}) { value["nameConditions"] = nil },+ func(value map[string]interface{}) { value["sorts"] = nil },+ func(value map[string]interface{}) { value["title"] = map[string]interface{}{"format": "plain"} },+ func(value map[string]interface{}) {+ value["title"] = map[string]interface{}{"format": "plain", "text": nil}+ },+ func(value map[string]interface{}) {+ value["nameConditions"] = []map[string]interface{}{{"parentID": nil, "title": "A"}}+ },+ } {+ request := map[string]interface{}{"notebook": box, "parentID": nil, "id": id,+ "title": map[string]string{"format": "plain", "text": "Title"}, "markdown": ""}+ mutate(request)+ response := documentPathAPIRequest(t, "/api/filetree/createDocByParent", createDocByParent, request)+ if !bytes.Contains(response, []byte(`"code":-1`)) {+ t.Fatalf("invalid creation request accepted: %s", response)+ }+ if treenode.GetBlockTreeInExactBox(id, box) != nil {+ t.Fatal("invalid request created an index entry")+ }+ }+}++func TestAPIContractDocumentAddressingAdminAccess(t *testing.T) {+ documentPathAPIWorkspace(t)+ for _, endpoint := range []struct {+ path string+ handler gin.HandlerFunc+ }{+ {"/api/filetree/getDocPaths", getDocPaths},+ {"/api/filetree/resolveDocPath", resolveDocPath},+ {"/api/filetree/createDocByParent", createDocByParent},+ {"/api/filetree/getDocCreateTarget", getDocCreateTarget},+ {"/api/filetree/planDocCreate", planDocCreate},+ } {+ engine := gin.New()+ engine.POST(endpoint.path, func(c *gin.Context) { c.Set(model.RoleContextKey, model.RoleReader) },+ model.CheckAdminRole, endpoint.handler)+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", endpoint.path, bytes.NewBufferString(`{}`)))+ if recorder.Code != http.StatusForbidden || recorder.Body.Len() != 0 {+ t.Fatalf("reader could access document addressing: HTTP %d %s", recorder.Code, recorder.Body.String())+ }+ }+}++func TestAPIContractDocumentCreateTarget(t *testing.T) {+ box := documentPathAPIWorkspace(t)+ for _, purpose := range []string{"document", "reference", "dailyNote"} {+ response := documentPathAPIRequest(t, "/api/filetree/getDocCreateTarget", getDocCreateTarget,+ apicontract.GetDocCreateTargetRequest{Notebook: box, Purpose: purpose})+ var result struct {+ Code int+ Data struct {+ Target apicontract.LegacyDocumentTarget+ DocCreateTemplatePath string+ Revision string+ }+ }+ if err := json.Unmarshal(response, &result); err != nil || result.Code != 0 || result.Data.Target.Version != 1 ||+ result.Data.Target.Notebook != box || result.Data.Revision == "" {+ t.Fatalf("target read failed: %s, %v", response, err)+ }+ if purpose == "dailyNote" && !bytes.Contains([]byte(result.Data.Target.Path), []byte("{{now")) {+ t.Fatal("configuration read rendered a time-sensitive template")+ }+ }+}++func TestAPIContractResolveDocumentPath(t *testing.T) {+ box := documentPathAPIWorkspace(t)+ parent := treenode.NewTree(box, "/20261023010000-parent1.sy", "/A", "A")+ child := treenode.NewTree(box, "/20261023010000-parent1/20261023010001-child01.sy", "/A/B", "B")+ treenode.UpsertBlockTree(parent)+ treenode.UpsertBlockTree(child)+ if err := treenode.SetDocumentMetadataState(box, "ready"); err != nil {+ t.Fatal(err)+ }+ resolve := func(segments []string) apicontract.ResolvedDocumentPathData {+ t.Helper()+ response := documentPathAPIRequest(t, "/api/filetree/resolveDocPath", resolveDocPath,+ apicontract.ResolveDocPathRequest{Notebook: box, Start: apicontract.DocumentPathStart{Kind: "root"}, Segments: segments})+ var result struct {+ Code int+ Data apicontract.ResolvedDocumentPathData+ }+ if err := json.Unmarshal(response, &result); err != nil || result.Code != 0 {+ t.Fatalf("resolve failed: %s, %v", response, err)+ }+ return result.Data+ }+ root := resolve([]string{})+ if root.Status != "resolved" || root.Resolved != nil || root.Start.ID != nil || root.Start.Revision == "" {+ t.Fatalf("root is not an explicit location: %+v", root)+ }+ resolved := resolve([]string{"A", "B"})+ if resolved.Status != "resolved" || resolved.NextIndex != 2 || resolved.Resolved.ID != child.ID || len(resolved.NameConditions) != 2 {+ t.Fatalf("wrong resolution: %+v", resolved)+ }+ missingResult := resolve([]string{"A", "Missing"})+ if missingResult.Status != "missing" || missingResult.NextIndex != 1 || missingResult.Resolved.ID != parent.ID ||+ missingResult.NameConditions[1].ExpectedID != nil || *missingResult.NameConditions[1].ParentID != parent.ID {+ t.Fatalf("missing condition was lost: %+v", missingResult)+ }+ if resolve([]string{"a"}).Status != "missing" {+ t.Fatal("name lookup ignored Unicode case")+ }+ for i := 0; i < 130; i++ {+ id := fmt.Sprintf("20261023020000-%07d", i)+ tree := treenode.NewTree(box, "/"+id+".sy", "/Same", "Same")+ treenode.UpsertBlockTree(tree)+ }+ ambiguous := resolve([]string{"Same"})+ if ambiguous.Status != "ambiguous" || !ambiguous.CandidatesTruncated || len(ambiguous.Candidates) != 128 || len(ambiguous.NameConditions) != 0 {+ t.Fatalf("candidate truncation erased ambiguity: %+v", ambiguous)+ }+ if resolve([]string{}).Start.Revision != root.Start.Revision {+ t.Fatal("unrelated children invalidated root revision")+ }+}diff --git a/kernel/api/contract_document_target_test.go b/kernel/api/contract_document_target_test.gonew file mode 100644index 0000000000..a5c80ceb89--- /dev/null+++ b/kernel/api/contract_document_target_test.go@@ -0,0 +1,54 @@+package api++import (+ "bytes"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/model"+)++func TestAPIContractDocumentTargetPatchAndLegacyReads(t *testing.T) {+ boxID := documentPathAPIWorkspace(t)+ box := model.Conf.Box(boxID)+ value := box.GetConf()+ target := &conf.DocumentTarget{Version: 2, Notebook: boxID, Anchor: conf.DocumentTargetAnchor{Kind: "notebookRoot"},+ Parents: []string{}, Title: "Target", OnMissingParent: "create"}+ value.DocCreateTarget, value.RefCreateTarget = target, target+ if err := box.SaveConf(value); err != nil {+ t.Fatal(err)+ }+ for _, endpoint := range []struct {+ path string+ handler gin.HandlerFunc+ }{+ {"/api/filetree/getDocCreateSavePath", getDocCreateSavePath},+ {"/api/filetree/getRefCreateSavePath", getRefCreateSavePath},+ } {+ response := documentPathAPIRequest(t, endpoint.path, endpoint.handler, map[string]string{"notebook": boxID})+ if !bytes.Contains(response, []byte(`"reason":"structuredTemplateRequired"`)) {+ t.Fatalf("legacy endpoint exposed an obsolete path: %s", response)+ }+ }+ patch := func(fields map[string]interface{}) []byte {+ return documentPathAPIRequest(t, "/api/notebook/setNotebookConf", setNotebookConf,+ map[string]interface{}{"notebook": boxID, "conf": fields})+ }+ if response := patch(map[string]interface{}{"name": "Renamed"}); !bytes.Contains(response, []byte(`"code":0`)) || box.GetConf().DocCreateTarget == nil {+ t.Fatalf("omitted target was cleared: %s", response)+ }+ if response := patch(map[string]interface{}{"docCreateSavePath": "/Changed"}); !bytes.Contains(response, []byte(`"code":-1`)) {+ t.Fatalf("legacy path silently replaced a structured target: %s", response)+ }+ if response := patch(map[string]interface{}{"docCreateTarget": map[string]interface{}{"version": 2, "futureField": true}}); !bytes.Contains(response, []byte(`"code":-1`)) {+ t.Fatalf("unknown structured field was accepted: %s", response)+ }+ if response := patch(map[string]interface{}{"docCreateTarget": nil}); !bytes.Contains(response, []byte(`"code":0`)) ||+ box.GetConf().DocCreateTarget != nil || box.GetConf().RefCreateTarget == nil {+ t.Fatalf("explicit target removal did not stay scoped: %s", response)+ }+ if response := patch(map[string]interface{}{"docCreateTarget": target}); !bytes.Contains(response, []byte(`"code":-1`)) {+ t.Fatalf("compatibility mode enabled a structured target: %s", response)+ }+}diff --git a/kernel/api/document_addressing.go b/kernel/api/document_addressing.gonew file mode 100644index 0000000000..21557e173f--- /dev/null+++ b/kernel/api/document_addressing.go@@ -0,0 +1,196 @@+package api++import (+ "errors"+ "time"++ "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/documentaddressing"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++func documentAddressingFailure(err error) (apicontract.DocumentAddressingFailure, bool) {+ var addressingErr *model.DocumentAddressingError+ if errors.As(err, &addressingErr) {+ return apicontract.DocumentAddressingFailure{Reason: addressingErr.Reason}, true+ }+ if errors.Is(err, documentaddressing.ErrModeConflict) {+ return apicontract.DocumentAddressingFailure{Reason: "modeConflict"}, true+ }+ return apicontract.DocumentAddressingFailure{}, false+}++func documentPathContract(document *treenode.DocumentPath) apicontract.DocumentPath {+ segments := make([]apicontract.DocumentPathSegment, 0, len(document.Segments))+ for _, segment := range document.Segments {+ segments = append(segments, apicontract.DocumentPathSegment{ID: segment.ID, Text: segment.Text, Empty: segment.Empty})+ }+ return apicontract.DocumentPath{+ Notebook: document.Notebook, ID: document.ID, ParentID: document.ParentID, Path: document.Path,+ Title: apicontract.DocumentTitle{Format: document.Title.Format, Text: document.Title.Text, Empty: document.Title.Empty},+ Segments: segments, Depth: document.Depth, DisplayPath: document.DisplayPath,+ Revision: document.Revision, AddressingVersion: document.AddressingVersion,+ }+}++func documentTargetContract(target *conf.DocumentTarget) *apicontract.StructuredDocumentTarget {+ if target == nil {+ return nil+ }+ return &apicontract.StructuredDocumentTarget{Version: target.Version, Notebook: target.Notebook,+ Anchor: apicontract.DocumentTargetAnchor{Kind: target.Anchor.Kind, ID: target.Anchor.ID},+ Up: target.Up, Parents: target.Parents, Title: target.Title, OnMissingParent: target.OnMissingParent}+}++func documentTargetModel(target *apicontract.StructuredDocumentTarget) *conf.DocumentTarget {+ if target == nil {+ return nil+ }+ return &conf.DocumentTarget{Version: target.Version, Notebook: target.Notebook,+ Anchor: conf.DocumentTargetAnchor{Kind: target.Anchor.Kind, ID: target.Anchor.ID},+ Up: target.Up, Parents: target.Parents, Title: target.Title, OnMissingParent: target.OnMissingParent}+}++var getDocPaths = contractHandler(apicontract.GetDocPaths, func(c *gin.Context, request apicontract.GetDocPathsRequest) apicontract.Response[apicontract.DocumentPathsResult] {+ if err := holdEncryptedBoxRequest(c, request.Notebook); err != nil {+ return apicontract.Failure[apicontract.DocumentPathsResult](-1, err.Error())+ }+ documents, missing, err := model.GetDocPaths(request.Notebook, request.IDs)+ if err != nil {+ if failure, ok := documentAddressingFailure(err); ok {+ return apicontract.GetDocPaths.FailureWithData(-1, err.Error(), apicontract.NewDocumentPathsFailure(failure))+ }+ return apicontract.Failure[apicontract.DocumentPathsResult](-1, err.Error())+ }+ data := apicontract.DocumentPathsData{Documents: []apicontract.DocumentPath{}, MissingIDs: missing}+ for _, document := range documents {+ data.Documents = append(data.Documents, documentPathContract(document))+ }+ return apicontract.Success(apicontract.NewDocumentPathsResult(data))+})++var resolveDocPath = contractHandler(apicontract.ResolveDocPath, func(c *gin.Context, request apicontract.ResolveDocPathRequest) apicontract.Response[apicontract.ResolveDocPathResult] {+ if err := holdEncryptedBoxRequest(c, request.Notebook); err != nil {+ return apicontract.Failure[apicontract.ResolveDocPathResult](-1, err.Error())+ }+ resolved, err := model.ResolveDocPath(request.Notebook, request.Start.Kind, request.Start.ID, request.Segments)+ if err != nil {+ if failure, ok := documentAddressingFailure(err); ok {+ return apicontract.ResolveDocPath.FailureWithData(-1, err.Error(), apicontract.NewResolveDocPathFailure(failure))+ }+ return apicontract.Failure[apicontract.ResolveDocPathResult](-1, err.Error())+ }+ data := apicontract.ResolvedDocumentPathData{Status: resolved.Status, NextIndex: resolved.NextIndex,+ Start: apicontract.DocumentLocation{Notebook: resolved.Start.Notebook, ID: resolved.Start.ID, Revision: resolved.Start.Revision},+ CandidatesTruncated: resolved.CandidatesTruncated, Candidates: []apicontract.DocumentPath{},+ NameConditions: []apicontract.DocumentNameCondition{}}+ if resolved.Resolved != nil {+ document := documentPathContract(resolved.Resolved)+ data.Resolved = &document+ }+ for _, candidate := range resolved.Candidates {+ data.Candidates = append(data.Candidates, documentPathContract(candidate))+ }+ for _, condition := range resolved.NameConditions {+ data.NameConditions = append(data.NameConditions, apicontract.DocumentNameCondition{+ ParentID: condition.ParentID, Title: condition.Title, ExpectedID: condition.ExpectedID})+ }+ return apicontract.Success(apicontract.NewResolveDocPathResult(data))+})++var createDocByParent = contractHandler(apicontract.CreateDocByParent, func(c *gin.Context, request apicontract.CreateDocByParentRequest) apicontract.Response[apicontract.CreateDocByParentResult] {+ if err := holdEncryptedBoxRequest(c, request.Notebook); err != nil {+ return apicontract.Failure[apicontract.CreateDocByParentResult](-1, err.Error())+ }+ input := model.DocumentCreateRequest{Notebook: request.Notebook, ParentID: request.ParentID, ID: request.ID,+ TitleFormat: request.Title.Format, Title: request.Title.Text, Markdown: request.Markdown,+ ExpectedParentRevision: request.ExpectedParentRevision, Tags: request.Tags, WithMath: request.WithMath,+ ClippingHref: request.ClippingHref, Sorts: request.Sorts, SortTargetID: request.SortTargetID,+ SortPosition: request.SortPosition, DocCreateTemplatePath: request.DocCreateTemplatePath, ListDocTree: request.ListDocTree}+ if expected := request.ExpectedTarget; expected != nil {+ if err := holdEncryptedBoxRequest(c, expected.Notebook); err != nil {+ return apicontract.Failure[apicontract.CreateDocByParentResult](-1, err.Error())+ }+ input.ExpectedTarget = &model.DocumentTargetRevision{Notebook: expected.Notebook, Purpose: expected.Purpose, Revision: expected.Revision}+ }+ for _, condition := range request.NameConditions {+ input.NameConditions = append(input.NameConditions, treenode.DocumentNameCondition{+ ParentID: condition.ParentID, Title: condition.Title, ExpectedID: condition.ExpectedID})+ }+ document, err := model.CreateDocByParent(input)+ if err != nil {+ var failure *model.DocumentCreateFailure+ if errors.As(err, &failure) {+ return apicontract.CreateDocByParent.FailureWithData(-1, err.Error(), apicontract.NewCreateDocByParentFailure(+ apicontract.DocumentCreateFailure{Reason: failure.Reason, CommitState: failure.CommitState,+ ID: failure.ID, Stage: failure.Stage, Completed: failure.Completed}))+ }+ return apicontract.Failure[apicontract.CreateDocByParentResult](-1, err.Error())+ }+ return apicontract.Success(apicontract.NewCreateDocByParentResult(apicontract.CreatedDocumentData{+ ID: document.ID, Document: documentPathContract(document)}))+})++var getDocCreateTarget = contractHandler(apicontract.GetDocCreateTarget, func(c *gin.Context, request apicontract.GetDocCreateTargetRequest) apicontract.Response[apicontract.DocumentCreateTargetData] {+ if err := holdEncryptedBoxRequest(c, request.Notebook); err != nil {+ return apicontract.Failure[apicontract.DocumentCreateTargetData](-1, err.Error())+ }+ value, err := model.GetDocCreateTarget(request.Notebook, request.Purpose)+ if err != nil {+ return apicontract.Failure[apicontract.DocumentCreateTargetData](-1, err.Error())+ }+ target := apicontract.LegacyCreateTarget(value.Notebook, value.Path)+ if structured := value.Structured; structured != nil {+ target = apicontract.StructuredCreateTarget(*documentTargetContract(structured))+ }+ return apicontract.Success(apicontract.DocumentCreateTargetData{+ Target: target, DocCreateTemplatePath: value.DocCreateTemplatePath, Revision: value.Revision})+})++var planDocCreate = contractHandler(apicontract.PlanDocCreate, func(c *gin.Context, request apicontract.PlanDocCreateRequest) apicontract.Response[apicontract.DocumentCreatePlan] {+ if err := holdEncryptedBoxRequest(c, request.Notebook); err != nil {+ return apicontract.Failure[apicontract.DocumentCreatePlan](-1, err.Error())+ }+ target, err := model.GetDocCreateTarget(request.Notebook, request.Purpose)+ if err != nil {+ return apicontract.Failure[apicontract.DocumentCreatePlan](-1, err.Error())+ }+ if err = holdEncryptedBoxRequest(c, target.Notebook); err != nil {+ return apicontract.Failure[apicontract.DocumentCreatePlan](-1, err.Error())+ }+ input := model.DocumentPlanRequest{Notebook: request.Notebook, Purpose: request.Purpose, ContextID: request.ContextID,+ Title: request.Title, ID: request.ID, Placement: request.Placement, Reuse: request.Reuse}+ if request.Date != nil {+ input.Now, err = time.ParseInLocation("2006-01-02", *request.Date, time.Local)+ if err != nil {+ return apicontract.Failure[apicontract.DocumentCreatePlan](-1, err.Error())+ }+ }+ plan, err := model.PlanDocumentCreation(input)+ if err != nil {+ return apicontract.Failure[apicontract.DocumentCreatePlan](-1, err.Error())+ }+ // 配置可能在读取期间改变,响应实际目标仍须持有租约。+ if err = holdEncryptedBoxRequest(c, plan.Notebook); err != nil {+ return apicontract.Failure[apicontract.DocumentCreatePlan](-1, err.Error())+ }+ result := apicontract.DocumentCreatePlan{Notebook: plan.Notebook, Title: plan.Title, ExistingID: plan.ExistingID,+ Steps: []apicontract.CreateDocByParentRequest{}}+ for _, step := range plan.Steps {+ value := apicontract.CreateDocByParentRequest{Notebook: step.Notebook, ParentID: step.ParentID, ID: step.ID,+ Title: apicontract.DocumentCreateTitle{Format: step.TitleFormat, Text: step.Title}, Markdown: step.Markdown,+ ExpectedParentRevision: step.ExpectedParentRevision, DocCreateTemplatePath: step.DocCreateTemplatePath}+ if expected := step.ExpectedTarget; expected != nil {+ value.ExpectedTarget = &apicontract.DocumentTargetRevision{Notebook: expected.Notebook, Purpose: expected.Purpose, Revision: expected.Revision}+ }+ for _, condition := range step.NameConditions {+ value.NameConditions = append(value.NameConditions, apicontract.DocumentNameCondition{+ ParentID: condition.ParentID, Title: condition.Title, ExpectedID: condition.ExpectedID})+ }+ result.Steps = append(result.Steps, value)+ }+ return apicontract.Success(result)+})diff --git a/kernel/api/file.go b/kernel/api/file.goindex 848a3c2f46..49d85f2eb3 100644--- a/kernel/api/file.go+++ b/kernel/api/file.go@@ -87,7 +87,7 @@ func copyDecryptedAsset(src, dest string) error {if err := model.CheckDocumentAddressingFileWrite(dest, plain, false); err != nil {return err}- if writeErr := os.WriteFile(dest, plain, 0644); writeErr != nil {+ if writeErr := model.WriteFileWithDocumentAddressing(dest, plain); writeErr != nil {return writeErr}return nil@@ -232,7 +232,7 @@ var globalCopyFiles = contractHandler(apicontract.GlobalCopyFiles, func(c *gin.Cret.Msg = "destination path is a symlink, which is not supported"return contractFailure[apicontract.Null](ret)}- if err := filelock.Copy(src, dest); err != nil {+ if err := model.CopyFileWithDocumentAddressing(src, dest); err != nil {logging.LogErrorf("copy file [%s] to [%s] failed: %s", src, dest, err)ret.Code = -1ret.Msg = err.Error()@@ -344,7 +344,7 @@ var workspaceCopyFiles = contractHandler(apicontract.WorkspaceCopyFiles, func(cret.Msg = "destination path is a symlink, which is not supported"return contractFailure[apicontract.Null](ret)}- if err := filelock.Copy(absSrc, dest); err != nil {+ if err := model.CopyFileWithDocumentAddressing(absSrc, dest); err != nil {logging.LogErrorf("copy file [%s] to [%s] failed: %s", absSrc, dest, err)ret.Code = -1ret.Msg = err.Error()@@ -429,7 +429,7 @@ var copyFile = contractHandler(apicontract.CopyFile, func(c *gin.Context, requesif err = model.CheckDocumentAddressingFileCopies([]string{src}, []string{dest}); err != nil {return apicontract.Failure[apicontract.Null](-1, err.Error())}- if err = filelock.Copy(src, dest); err != nil {+ if err = model.CopyFileWithDocumentAddressing(src, dest); err != nil {logging.LogErrorf("copy file [%s] to [%s] failed: %s", src, dest, err)ret.Code = -1ret.Msg = err.Error()@@ -737,7 +737,15 @@ var renameFile = contractHandler(apicontract.RenameFile, func(c *gin.Context, re}}- if err := filelock.RenameWithoutFatal(srcAbsPath, destAbsPath); err != nil {+ if err := model.MutateDocumentAddressingFiles(srcAbsPath, destAbsPath, func() error {+ if err := model.CheckDocumentAddressingFileCopies([]string{srcAbsPath}, []string{destAbsPath}); err != nil {+ return err+ }+ if err := model.CheckDocumentAddressingFileRemoval(srcAbsPath); err != nil {+ return err+ }+ return filelock.RenameWithoutFatal(srcAbsPath, destAbsPath)+ }); err != nil {logging.LogErrorf("rename file failed: %s", err)ret.Code = http.StatusInternalServerErrorret.Msg = http.StatusText(http.StatusInternalServerError) + errMsgSeeKernelLog@@ -794,7 +802,12 @@ var removeFile = contractHandler(apicontract.RemoveFile, func(c *gin.Context, re}affectsSync := model.PathsAffectSync(fileAbsPath)- if err = filelock.RemoveWithoutFatal(fileAbsPath); err != nil {+ if err = model.MutateDocumentAddressingFiles(fileAbsPath, "", func() error {+ if err := model.CheckDocumentAddressingFileRemoval(fileAbsPath); err != nil {+ return err+ }+ return filelock.RemoveWithoutFatal(fileAbsPath)+ }); err != nil {logging.LogErrorf("remove [%s] failed: %s", fileAbsPath, err)ret.Code = http.StatusInternalServerErrorret.Msg = http.StatusText(http.StatusInternalServerError) + errMsgSeeKernelLog@@ -910,7 +923,7 @@ var putFile = contractHandler(apicontract.PutFile, func(c *gin.Context, requestlogging.LogErrorf("put file [%s] make dir [%s] failed: %s", fileAbsPath, dir, err)break}- err = filelock.WriteFile(fileAbsPath, data)+ err = model.WriteFileWithDocumentAddressing(fileAbsPath, data)if err != nil {logging.LogErrorf("write file [%s] failed: %s", fileAbsPath, err)breakdiff --git a/kernel/api/filetree.go b/kernel/api/filetree.goindex c3891ceea8..1ddd40f87c 100644--- a/kernel/api/filetree.go+++ b/kernel/api/filetree.go@@ -862,10 +862,25 @@ func createDocWithMdContract(c *gin.Context, request apicontract.FileTreeCreateMvar getDocCreateSavePath = contractHandler(apicontract.GetDocCreateSavePath, getDocCreateSavePathContract)-func getDocCreateSavePathContract(c *gin.Context, request apicontract.FileTreeNotebookRequest) apicontract.Response[apicontract.FileTreeCreateSavePathData] {+func getDocCreateSavePathContract(c *gin.Context, request apicontract.FileTreeNotebookRequest) apicontract.Response[apicontract.FileTreeCreateSavePathResult] {ret := gulu.Ret.NewResult()notebook := request.Notebook+ if model.Conf.Box(notebook) != nil {+ if err := holdEncryptedBoxRequest(c, notebook); err != nil {+ return apicontract.Failure[apicontract.FileTreeCreateSavePathResult](-1, model.Conf.Language(314))+ }+ target, err := model.GetDocCreateTarget(notebook, "document")+ if err != nil {+ return apicontract.Failure[apicontract.FileTreeCreateSavePathResult](-1, err.Error())+ }+ if target.Structured != nil {+ return apicontract.GetDocCreateSavePath.FailureWithData(-1, "use getDocCreateTarget for a structured template", apicontract.NewFileTreeCreateSavePathFailure())+ }+ if err = holdEncryptedBoxRequest(c, target.Notebook); err != nil {+ return apicontract.Failure[apicontract.FileTreeCreateSavePathResult](-1, model.Conf.Language(314))+ }+ }docCreateSaveBox, docCreateSavePathTpl := model.ResolveDocCreateSaveLocation(notebook)docCreateTemplatePath := model.Conf.FileTree.Load().DocCreateTemplatePathif box := model.Conf.Box(notebook); nil != box {@@ -887,20 +902,35 @@ func getDocCreateSavePathContract(c *gin.Context, request apicontract.FileTreeNoif err != nil {ret.Code = -1ret.Msg = err.Error()- return contractFailure[apicontract.FileTreeCreateSavePathData](ret)+ return contractFailure[apicontract.FileTreeCreateSavePathResult](ret)}- return apicontract.Success(apicontract.FileTreeCreateSavePathData{FileTreeSavePathData: apicontract.FileTreeSavePathData{Box: docCreateSaveBox, Path: docCreateSavePath}, DocCreateTemplatePath: docCreateTemplatePath})+ return apicontract.Success(apicontract.NewFileTreeCreateSavePathResult(apicontract.FileTreeCreateSavePathData{FileTreeSavePathData: apicontract.FileTreeSavePathData{Box: docCreateSaveBox, Path: docCreateSavePath}, DocCreateTemplatePath: docCreateTemplatePath}))}var getRefCreateSavePath = contractHandler(apicontract.GetRefCreateSavePath, getRefCreateSavePathContract)-func getRefCreateSavePathContract(c *gin.Context, request apicontract.FileTreeNotebookRequest) apicontract.Response[apicontract.FileTreeSavePathData] {+func getRefCreateSavePathContract(c *gin.Context, request apicontract.FileTreeNotebookRequest) apicontract.Response[apicontract.FileTreeSavePathResult] {confFileTreeSnapshot := model.Conf.LoadFileTree()ret := gulu.Ret.NewResult()notebook := request.Notebook+ if model.Conf.Box(notebook) != nil {+ if err := holdEncryptedBoxRequest(c, notebook); err != nil {+ return apicontract.Failure[apicontract.FileTreeSavePathResult](-1, model.Conf.Language(314))+ }+ target, err := model.GetDocCreateTarget(notebook, "reference")+ if err != nil {+ return apicontract.Failure[apicontract.FileTreeSavePathResult](-1, err.Error())+ }+ if target.Structured != nil {+ return apicontract.GetRefCreateSavePath.FailureWithData(-1, "use getDocCreateTarget for a structured template", apicontract.NewFileTreeSavePathFailure())+ }+ if err = holdEncryptedBoxRequest(c, target.Notebook); err != nil {+ return apicontract.Failure[apicontract.FileTreeSavePathResult](-1, model.Conf.Language(314))+ }+ }box := model.Conf.Box(notebook)var refCreateSaveBox stringrefCreateSavePathTpl := confFileTreeSnapshot.RefCreateSavePath@@ -936,9 +966,9 @@ func getRefCreateSavePathContract(c *gin.Context, request apicontract.FileTreeNoif err != nil {ret.Code = -1ret.Msg = err.Error()- return contractFailure[apicontract.FileTreeSavePathData](ret)+ return contractFailure[apicontract.FileTreeSavePathResult](ret)}- return apicontract.Success(apicontract.FileTreeSavePathData{Box: refCreateSaveBox, Path: refCreateSavePath})+ return apicontract.Success(apicontract.NewFileTreeSavePathResult(apicontract.FileTreeSavePathData{Box: refCreateSaveBox, Path: refCreateSavePath}))}var getShorthandSavePath = contractHandler(apicontract.GetShorthandSavePath, getShorthandSavePathContract)diff --git a/kernel/api/filetree_contract.go b/kernel/api/filetree_contract.goindex 367252431a..a01cb187e8 100644--- a/kernel/api/filetree_contract.go+++ b/kernel/api/filetree_contract.go@@ -71,7 +71,8 @@ func fileTreeSearchContracts(values []map[string]string) []*apicontract.FileTree}result[i] = &apicontract.FileTreeSearchDoc{Path: value["path"], HPath: value["hPath"], Box: value["box"], BoxIcon: value["boxIcon"],- Name: optional("name"), Alias: optional("alias"), NewFlashcardCount: optional("newFlashcardCount"),+ Title: optional("title"),+ Name: optional("name"), Alias: optional("alias"), NewFlashcardCount: optional("newFlashcardCount"),DueFlashcardCount: optional("dueFlashcardCount"), FlashcardCount: optional("flashcardCount"),}}diff --git a/kernel/api/notebook.go b/kernel/api/notebook.goindex 4e211d0089..71809809b5 100644--- a/kernel/api/notebook.go+++ b/kernel/api/notebook.go@@ -25,6 +25,7 @@ import ("github.com/88250/gulu""github.com/gin-gonic/gin""github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/documentaddressing""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util"@@ -313,11 +314,25 @@ var getNotebookConf = contractHandler(apicontract.GetNotebookConf, func(c *gin.C}boxConf := box.GetConf()+ var capabilities *apicontract.DocumentCapabilitiesif !model.IsAdminRoleContext(c) {model.HideBoxConfSecret(boxConf)+ } else {+ snapshot, err := documentaddressing.InspectBox(util.DataDir, util.ConfDir, notebook)+ if err != nil {+ return apicontract.Failure[apicontract.NotebookConfData](-1, err.Error())+ }+ modeState := "legacy"+ if snapshot.Mode != 1 {+ modeState = "conflict"+ }+ capabilities = &apicontract.DocumentCapabilities{AddressingVersion: snapshot.Mode,+ ModeState: modeState, StructuredPaths: true, LiteralSlash: false, TitleFormats: []string{"plain"},+ IndexState: treenode.DocumentMetadataState(notebook), Revision: snapshot.Revision}}- return apicontract.Success(apicontract.NotebookConfData{Box: box.ID, Name: box.Name, Conf: notebookConfContract(boxConf)})+ return apicontract.Success(apicontract.NotebookConfData{Box: box.ID, Name: box.Name,+ Conf: notebookConfContract(boxConf), DocumentCapabilities: capabilities})})var setNotebookConf = contractHandler(apicontract.SetNotebookConf, func(c *gin.Context, request apicontract.SetNotebookConfRequest) apicontract.Response[*apicontract.NotebookConf] {@@ -344,6 +359,9 @@ var setNotebookConf = contractHandler(apicontract.SetNotebookConf, func(c *gin.CboxConf := box.GetConf()oldSortMode := boxConf.SortMode+ if err := applyNotebookDocumentTargetPatch(notebook, boxConf, request.Conf); err != nil {+ return apicontract.Failure[*apicontract.NotebookConf](-1, err.Error())+ }applyNotebookConfPatch(boxConf, request.Conf)boxConf.DocCreateSavePath = util.TrimSpaceInPath(boxConf.DocCreateSavePath)diff --git a/kernel/api/notebook_patch.go b/kernel/api/notebook_patch.goindex ab3d2043ff..94a6f37634 100644--- a/kernel/api/notebook_patch.go+++ b/kernel/api/notebook_patch.go@@ -1,10 +1,47 @@package apiimport (+ "errors"+"github.com/siyuan-note/siyuan/kernel/apicontract""github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/model")+func applyNotebookDocumentTargetPatch(notebook string, value *conf.BoxConf, patch *apicontract.NotebookConfPatch) error {+ if patch == nil {+ return nil+ }+ for _, item := range []struct {+ name string+ current **conf.DocumentTarget+ next *apicontract.StructuredDocumentTarget+ oldPath string+ newPath *string+ oldBox string+ newBox *string+ }{+ {"docCreateTarget", &value.DocCreateTarget, patch.DocCreateTarget, value.DocCreateSavePath, patch.DocCreateSavePath, value.DocCreateSaveBox, patch.DocCreateSaveBox},+ {"refCreateTarget", &value.RefCreateTarget, patch.RefCreateTarget, value.RefCreateSavePath, patch.RefCreateSavePath, value.RefCreateSaveBox, patch.RefCreateSaveBox},+ {"dailyNoteTarget", &value.DailyNoteTarget, patch.DailyNoteTarget, value.DailyNoteSavePath, patch.DailyNoteSavePath, "", nil},+ } {+ if patch.HasDocumentTarget(item.name) {+ if model.IsEncryptedBox(notebook) && !model.IsBoxUnlocked(notebook) {+ return errors.New("unlock the notebook before changing document targets")+ }+ next := documentTargetModel(item.next)+ if err := model.ValidateNotebookDocumentTarget(notebook, next); err != nil {+ return err+ }+ *item.current = next+ }+ if *item.current != nil && (item.newPath != nil && *item.newPath != item.oldPath || item.newBox != nil && *item.newBox != item.oldBox) {+ return errors.New("structured document target conflicts with the legacy save path")+ }+ }+ return nil+}+// applyNotebookConfPatch 仅更新提供的普通配置字段,加密参数由密钥生命周期接口管理。func applyNotebookConfPatch(value *conf.BoxConf, patch *apicontract.NotebookConfPatch) {if patch == nil {diff --git a/kernel/api/router.go b/kernel/api/router.goindex 80370edd56..bd9de7c510 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -312,6 +312,11 @@ func registerFiletreeRoutes(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/filetree/setSort", contractRouteHandlers(apicontract.SetSort, setSort)...)ginServer.Handle("POST", "/api/filetree/setDocSortMode", contractRouteHandlers(apicontract.SetDocSortMode, setDocSortMode)...)ginServer.Handle("POST", "/api/filetree/createDocWithMd", contractRouteHandlers(apicontract.CreateDocWithMd, createDocWithMd)...)+ ginServer.Handle("POST", "/api/filetree/getDocPaths", contractRouteHandlers(apicontract.GetDocPaths, getDocPaths)...)+ ginServer.Handle("POST", "/api/filetree/resolveDocPath", contractRouteHandlers(apicontract.ResolveDocPath, resolveDocPath)...)+ ginServer.Handle("POST", "/api/filetree/createDocByParent", contractRouteHandlers(apicontract.CreateDocByParent, createDocByParent)...)+ ginServer.Handle("POST", "/api/filetree/getDocCreateTarget", contractRouteHandlers(apicontract.GetDocCreateTarget, getDocCreateTarget)...)+ ginServer.Handle("POST", "/api/filetree/planDocCreate", contractRouteHandlers(apicontract.PlanDocCreate, planDocCreate)...)ginServer.Handle("POST", "/api/filetree/createDailyNote", contractRouteHandlers(apicontract.CreateDailyNote, createDailyNote)...)ginServer.Handle("POST", "/api/filetree/getDailyNoteInfo", contractRouteHandlers(apicontract.GetDailyNoteInfo, getDailyNoteInfo)...)ginServer.Handle("POST", "/api/filetree/createDoc", contractRouteHandlers(apicontract.CreateDoc, createDoc)...)diff --git a/kernel/api/system_export_secrets_test.go b/kernel/api/system_export_secrets_test.goindex 4224d89086..34a85e3c13 100644--- a/kernel/api/system_export_secrets_test.go+++ b/kernel/api/system_export_secrets_test.go@@ -16,9 +16,9 @@ import ()func TestAPIContractSystemExportSecrets(t *testing.T) {- previousConf, previousTemp := model.Conf, util.TempDir- t.Cleanup(func() { model.Conf, util.TempDir = previousConf, previousTemp })- util.TempDir = t.TempDir()+ previousConf, previousTemp, previousConfDir := model.Conf, util.TempDir, util.ConfDir+ t.Cleanup(func() { model.Conf, util.TempDir, util.ConfDir = previousConf, previousTemp, previousConfDir })+ util.TempDir, util.ConfDir = t.TempDir(), t.TempDir()for _, populated := range []bool{true, false} {model.Conf = model.NewAppConf()if populated {diff --git a/kernel/api/system_proxy_import_test.go b/kernel/api/system_proxy_import_test.goindex ba8801054c..8baa1a7d3f 100644--- a/kernel/api/system_proxy_import_test.go+++ b/kernel/api/system_proxy_import_test.go@@ -19,11 +19,12 @@ import (func TestConfTransferPreservesLocalNetworkProxy(t *testing.T) {gin.SetMode(gin.TestMode)- previousConf, previousTemp, previousReadOnly := model.Conf, util.TempDir, util.ReadOnly+ previousConf, previousTemp, previousReadOnly, previousConfDir := model.Conf, util.TempDir, util.ReadOnly, util.ConfDirt.Cleanup(func() {model.Conf, util.TempDir, util.ReadOnly = previousConf, previousTemp, previousReadOnly+ util.ConfDir = previousConfDir})- util.TempDir, util.ReadOnly = t.TempDir(), true+ util.TempDir, util.ConfDir, util.ReadOnly = t.TempDir(), t.TempDir(), trueengine := gin.New()engine.POST("/export", exportConf)engine.POST("/import", importConf)diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex f7ccb69d69..4e9cd79713 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -131,7 +131,14 @@ var SetNotebookConf = define[SetNotebookConfRequest, *NotebookConf]("setNotebookvar ReorderNotebooks = define[ReorderNotebooksRequest, *ReorderData]("reorderNotebooks", "/api/notebook/reorder", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{DataOnError: true}, "POST")var (- OpenNotebook = define[OpenNotebookRequest, Null]("openNotebook", "/api/notebook/openNotebook", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+ OpenNotebook = define[OpenNotebookRequest, Null]("openNotebook", "/api/notebook/openNotebook", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+ // GetNotebookConf preserves existing configuration and permission filtering. Administrator+ // responses also contain documentCapabilities: structuredPaths advertises the ID/segment APIs,+ // not permission to open a closed or locked notebook. literalSlash remains false until structured+ // title mode is implemented and enabled; minimumReaderVersion is null until a protective release+ // is verified. Revision covers configuration and confirmed capability records, not a document path.+ // Malformed capability records fail the request; authentication, locking and network failures must+ // never be interpreted as an absent capability object or as permission to retry a legacy write.GetNotebookConf = define[CloseNotebookRequest, NotebookConfData]("getNotebookConf", "/api/notebook/getNotebookConf", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST"))@@ -480,7 +487,11 @@ var GetDocHeadingLevelTransaction = define[DocHeadingLevelRequest, *DocHeadingLevar GetRecentUpdatedBlocks = define[EmptyRequest, []*SearchBlock]("getRecentUpdatedBlocks", "/api/block/getRecentUpdatedBlocks", AuthenticatedAccess, NoBody, ResponseOptions{}, "POST")+// Zip 的输出位置遵守笔记本能力及原始文档保护,不能用压缩文件覆盖文档源或能力记录。var Zip = define[ZipRequest, Null]("zip", "/api/archive/zip", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")++// Unzip 在隔离目录解压并预检完整输出集合的能力记录及文档源,失败时不写入目标。+// 实际复制仍重新检查目标;后续并发变化或 I/O 失败可能留下已完成条目,不承诺整批回滚。var Unzip = define[UnzipRequest, Null]("unzip", "/api/archive/unzip", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")// 格式化成功写盘后清理文档及关联跨文档撤销记录,并广播更新后的撤销状态。@@ -618,6 +629,7 @@ var GetUniqueFilename = define[FilePathRequest, FilePathData]("getUniqueFilenamevar ReadDirectory = define[ReadDirectoryRequest, []DirectoryEntry]("readDir", "/api/file/readDir", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-3, 403, 404, 409, 500}, NonNullable: true}, "POST")// RenameFile 在创建目标父目录或移动源文件前预检笔记本寻址能力,不支持的模式返回 -1。+// 移入由笔记本及文档 ID 组成的 .sy 路径时检查全部源文档;未知格式或标题冲突返回 -1,保留来源。// 不能借重命名覆盖、移动或删除本机 conf/document-addressing.json;既有加密边界不变。var RenameFile = define[RenameFileRequest, Null]("renameFile", "/api/file/renameFile", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-3, 403, 404, 409, 500}}, "POST")@@ -625,19 +637,24 @@ var RenameFile = define[RenameFileRequest, Null]("renameFile", "/api/file/rename// 不能删除本机 conf/document-addressing.json 或其父目录,既有加密笔记本删除限制不变。var RemoveFile = define[RemoveFileRequest, Null]("removeFile", "/api/file/removeFile", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-3, 403, 404, 500}}, "POST")-// GlobalCopyFiles 在创建目标目录及复制前预检整批笔记本寻址模式;不兼容时返回 -1,不写入部分目标。+// GlobalCopyFiles 在创建目标目录及复制前预检整批笔记本寻址模式和文档源;预检不兼容时返回 -1,不写入目标。+// 文档 ID 路径同时检查传入内容及现有源,实际写入前再次校验;后续并发变化或 I/O 失败不回滚已完成的复制。// 不允许覆盖本机能力下界记录;原有敏感路径、加密笔记本和符号链接限制继续生效。var GlobalCopyFiles = define[CopyFilesRequest, Null]("globalCopyFiles", "/api/file/globalCopyFiles", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-2, -3, 403}}, "POST")-// WorkspaceCopyFiles 在创建目标目录及复制前预检整批笔记本寻址模式;不兼容时返回 -1,不写入部分目标。+// WorkspaceCopyFiles 在创建目标目录及复制前预检整批笔记本寻址模式和文档源;预检不兼容时返回 -1,不写入目标。+// 文档 ID 路径同时检查传入内容及现有源,实际写入前再次校验;后续并发变化或 I/O 失败不回滚已完成的复制。// 不允许覆盖本机能力下界记录;原有敏感路径、加密笔记本和符号链接限制继续生效。var WorkspaceCopyFiles = define[CopyFilesRequest, Null]("workspaceCopyFiles", "/api/file/workspaceCopyFiles", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-2, -3, 403}}, "POST")// CopyFile 在写入前检查笔记本寻址模式,不兼容或试图覆盖本机能力下界记录时返回 -1。+// 目标为文档 ID 路径时,未知格式和标题冲突均返回 -1;实际写入在文件锁内重新校验现有源,不规范化内容。// 工作空间外的加密资源解密导出仍要求既有授权和操作租约。var CopyFile = define[CopyFileRequest, Null]("copyFile", "/api/file/copyFile", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{-2}}, "POST")// PutFile 在创建目录、写入内容及更新时间前校验笔记本寻址模式和待写配置;不兼容时返回 -1。+// 文档 ID 路径检查传入内容及现有源的格式和标题;未知格式或标题冲突返回 -1,原文件和时间保持不变。+// 实际文档写入在同一文件锁内重新校验现有源,保留请求字节;附件和插件文件不按文档格式解释。// 不允许覆盖本机 conf/document-addressing.json,恢复设置时须使用 importConf 的逐身份合并流程。var PutFile = define[PutFileRequest, Null]("putFile", "/api/file/putFile", AuthenticatedAccess|AdminAccess|WritableAccess, FormBody, ResponseOptions{AdditionalCodes: []int{-3, 400, 403, 500}}, "POST")@@ -1040,6 +1057,39 @@ var Li2Doc = define[FileTreeListItemDocRequest, Null]("li2Doc", "/api/filetree/lvar GetHPathByPath = define[FileTreePathRequest, string]("getHPathByPath", "/api/filetree/getHPathByPath", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")var GetHPathsByPaths = define[FileTreePathsRequest, []string]("getHPathsByPaths", "/api/filetree/getHPathsByPaths", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")var GetHPathByID = define[FileTreeIDRequest, string]("getHPathByID", "/api/filetree/getHPathByID", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")++// GetDocPaths 在指定笔记本内按文档 ID 读取结构化祖先链,要求管理员权限,加密响应保留操作租约。+// ids 必须包含 1 至 128 项,按首次出现顺序去重;缺失、其他笔记本或内容块身份列入 missingIDs。+// 文档标题、segments 与 revision 来自同一快照,displayPath 仅用于显示,不能反向解析身份。+// 索引未就绪返回 indexUnavailable,源格式和认证错误不能伪装成缺失;批量结果不承诺全局快照。+var GetDocPaths = define[GetDocPathsRequest, DocumentPathsResult]("getDocPaths", "/api/filetree/getDocPaths", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{DataOnError: true}, "POST")++// ResolveDocPath 从显式根位置或父文档 ID 逐级精确匹配 0 至 128 个非空标题段,只解析不创建。+// 标题不作 Unicode 归一化、宽窄转换或百分号解码;同父同名返回 ambiguous,不任取候选。+// candidates 按 ID 排序且最多 128 项,candidatesTruncated 标记截断;nameConditions 保留唯一及缺失条件。+// 空段数组返回起点,根位置的 resolved 为 null,start.id 为 null;笔记本文档 ID 规范化为逻辑根。+// 索引未就绪返回 indexUnavailable;普通标题仍遵守兼容模式限制,不隐式启用新字符。+var ResolveDocPath = define[ResolveDocPathRequest, ResolveDocPathResult]("resolveDocPath", "/api/filetree/resolveDocPath", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{DataOnError: true}, "POST")++// CreateDocByParent 在显式父文档 ID 或 null 根位置创建固定 ID 文档,不接收 path/hPath 或名称回退。+// title.format 首版只接受 plain,text 可为空;无效字符、超长标题及不支持的格式原样拒绝,不截断或清洗。+// 可选父路径 revision 与至多 128 项名称条件在源提交前分别校验;条件只能涉及目标祖先和最终父级。+// ID 冲突不覆盖、不自动更换;错误 data 包含稳定 reason、commitState、阶段及已完成步骤。+// 已落盘但排序或正文模板失败时保留源文档并返回其 ID,调用方不得把该错误当作未创建而重复提交。+// 当前兼容阶段仍不允许标题包含 /,不提升已有文档 Spec;加密笔记本使用原有认证写入与响应租约。+var CreateDocByParent = define[CreateDocByParentRequest, CreateDocByParentResult]("createDocByParent", "/api/filetree/createDocByParent", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{DataOnError: true}, "POST")++// GetDocCreateTarget 返回指定用途的有效目标及正文模板,不渲染模板、不猜测上下文或日期。+// version=1 保留旧路径语法;version=2 独立保存祖先和标题段。revision 覆盖生效配置及继承来源,+// 由配置创建时传回 expectedTarget,配置变化即返回 planChanged。读取需管理员及源笔记本操作租约。+var GetDocCreateTarget = define[GetDocCreateTargetRequest, DocumentCreateTargetData]("getDocCreateTarget", "/api/filetree/getDocCreateTarget", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")++// PlanDocCreate 只读编译有效创建目标,同一次计划使用相同时间,日期可指定为 YYYY-MM-DD。+// contextID 是源笔记本内的文档,child 使用该位置,configured 使用配置目标;title 可显式替换最终标题。+// 调用方提前保存最终 id,返回步骤已分配全部祖先 ID。按顺序向 createDocByParent 提交,不承诺跨文件原子性。+// reuse 仅用于明确允许复用的业务。existingID 非空时不再创建;普通新建应保持 reuse=false。+// 上一步创建父文档后,将其返回的 revision 传为下一步 expectedParentRevision;错误或响应丢失时保留计划核对 ID。+var PlanDocCreate = define[PlanDocCreateRequest, DocumentCreatePlan]("planDocCreate", "/api/filetree/planDocCreate", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")var GetPathByID = define[FileTreeTrimIDRequest, FileTreeDocPathData]("getPathByID", "/api/filetree/getPathByID", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")var GetFullHPathByID = define[FileTreeOptionalIDRequest, *string]("getFullHPathByID", "/api/filetree/getFullHPathByID", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")var GetIDsByHPath = define[FileTreeOptionalPathRequest, []string]("getIDsByHPath", "/api/filetree/getIDsByHPath", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")@@ -1060,13 +1110,17 @@ var GetDailyNoteInfo = define[DailyNoteInfoRequest, *DailyNoteInfo]("getDailyNot// 使用编辑器 Markdown 语法选项,并按 `/api/import/importStdMd` 的规则转换标准脚注。// 转义的脚注语法保留为字面文本;返回创建的文档 ID,访问受笔记本权限限制。var CreateDocWithMd = define[FileTreeCreateMarkdownRequest, string]("createDocWithMd", "/api/filetree/createDocWithMd", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")-var GetDocCreateSavePath = define[FileTreeNotebookRequest, FileTreeCreateSavePathData]("getDocCreateSavePath", "/api/filetree/getDocCreateSavePath", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")-var GetRefCreateSavePath = define[FileTreeNotebookRequest, FileTreeSavePathData]("getRefCreateSavePath", "/api/filetree/getRefCreateSavePath", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")++// 旧模板保持既有渲染及回退;对应的新目标对象生效时返回 structuredTemplateRequired,不读取历史路径。+var GetDocCreateSavePath = define[FileTreeNotebookRequest, FileTreeCreateSavePathResult]("getDocCreateSavePath", "/api/filetree/getDocCreateSavePath", AuthenticatedAccess, JSONBody, ResponseOptions{DataOnError: true}, "POST")+var GetRefCreateSavePath = define[FileTreeNotebookRequest, FileTreeSavePathResult]("getRefCreateSavePath", "/api/filetree/getRefCreateSavePath", AuthenticatedAccess, JSONBody, ResponseOptions{DataOnError: true}, "POST")var GetShorthandSavePath = define[FileTreeNotebookRequest, FileTreeSavePathData]("getShorthandSavePath", "/api/filetree/getShorthandSavePath", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")var ChangeSort = define[FileTreeChangeSortRequest, Null]("changeSort", "/api/filetree/changeSort", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var ReorderDocs = define[FileTreeReorderRequest, *FileTreeReorderData]("reorderDocs", "/api/filetree/reorderDocs", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{DataOnError: true}, "POST")var SetSort = define[FileTreeSetSortRequest, *FileTreeSetSortData]("setSort", "/api/filetree/setSort", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{DataOnError: true}, "POST")var SetDocSortMode = define[FileTreeSortModeRequest, *FileTreeSortModeData]("setDocSortMode", "/api/filetree/setDocSortMode", AuthenticatedAccess|AdminAccess|WritableAccess, StructJSONBody, ResponseOptions{DataOnError: true}, "POST")++// SearchDocs 保留兼容展示 hPath,并单独返回文档或笔记本的纯文本 title;客户端不能从 hPath 拆出标题或层级。var SearchDocs = define[FileTreeSearchRequest, []*FileTreeSearchDoc]("searchDocs", "/api/filetree/searchDocs", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")var ListDocsByPath = define[FileTreeListRequest, FileTreeListData]("listDocsByPath", "/api/filetree/listDocsByPath", AuthenticatedAccess, JSONBody, ResponseOptions{}, "POST")var GetDoc = define[FileTreeGetDocRequest, FileTreeGetDocData]("getDoc", "/api/filetree/getDoc", AuthenticatedAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1, 3}}, "POST")diff --git a/kernel/apicontract/document_addressing.go b/kernel/apicontract/document_addressing.gonew file mode 100644index 0000000000..140f6f1fe7--- /dev/null+++ b/kernel/apicontract/document_addressing.go@@ -0,0 +1,305 @@+package apicontract++import (+ "bytes"+ "encoding/json"+ "errors"+ "reflect"+)++type DocumentCreateTitle struct {+ Format string `json:"format"`+ Text string `json:"text"`+}++type CreateDocByParentRequest struct {+ Notebook string `json:"notebook"`+ ParentID *string `json:"parentID"`+ ID string `json:"id"`+ Title DocumentCreateTitle `json:"title"`+ Markdown string `json:"markdown"`+ ExpectedParentRevision *string `json:"expectedParentRevision,omitempty" api:"optional,nonnullable"`+ ExpectedTarget *DocumentTargetRevision `json:"expectedTarget,omitempty" api:"optional,nonnullable"`+ NameConditions []DocumentNameCondition `json:"nameConditions,omitempty" api:"optional,nonnullable"`+ Tags string `json:"tags,omitempty" api:"optional"`+ WithMath bool `json:"withMath,omitempty" api:"optional"`+ ClippingHref string `json:"clippingHref,omitempty" api:"optional"`+ Sorts []string `json:"sorts,omitempty" api:"optional,nonnullable"`+ SortTargetID string `json:"sortTargetID,omitempty" api:"optional"`+ SortPosition string `json:"sortPosition,omitempty" api:"optional,enum=before|after"`+ DocCreateTemplatePath string `json:"docCreateTemplatePath,omitempty" api:"optional"`+ ListDocTree bool `json:"listDocTree,omitempty" api:"optional"`+}++// UnmarshalJSON 拒绝 path/hPath 等第二位置来源,并保留空标题、显式根与缺省字段的区别。+func (request *CreateDocByParentRequest) UnmarshalJSON(data []byte) error {+ type plain CreateDocByParentRequest+ var next plain+ decoder := json.NewDecoder(bytes.NewReader(data))+ decoder.DisallowUnknownFields()+ if err := decoder.Decode(&next); err != nil {+ return err+ }+ var fields map[string]json.RawMessage+ if err := json.Unmarshal(data, &fields); err != nil {+ return err+ }+ for _, key := range []string{"notebook", "parentID", "id", "title", "markdown"} {+ if _, exists := fields[key]; !exists || key != "parentID" && bytes.Equal(fields[key], []byte("null")) {+ return errors.New("missing or null required field: " + key)+ }+ }+ for key, value := range fields {+ if key != "parentID" && bytes.Equal(bytes.TrimSpace(value), []byte("null")) {+ return errors.New("null field: " + key)+ }+ }+ var title map[string]json.RawMessage+ if err := json.Unmarshal(fields["title"], &title); err != nil {+ return err+ }+ for _, key := range []string{"format", "text"} {+ if value, exists := title[key]; !exists || bytes.Equal(value, []byte("null")) {+ return errors.New("missing or null title field: " + key)+ }+ }+ var conditions []map[string]json.RawMessage+ if value, exists := fields["nameConditions"]; exists {+ if err := json.Unmarshal(value, &conditions); err != nil {+ return err+ }+ }+ if value, exists := fields["expectedTarget"]; exists {+ var target map[string]json.RawMessage+ if err := json.Unmarshal(value, &target); err != nil {+ return err+ }+ for _, key := range []string{"notebook", "purpose", "revision"} {+ if value, exists := target[key]; !exists || bytes.Equal(bytes.TrimSpace(value), []byte("null")) {+ return errors.New("missing or null target revision field: " + key)+ }+ }+ }+ for _, condition := range conditions {+ for _, key := range []string{"parentID", "title", "expectedID"} {+ if _, exists := condition[key]; !exists {+ return errors.New("missing name condition field: " + key)+ }+ }+ if bytes.Equal(bytes.TrimSpace(condition["title"]), []byte("null")) {+ return errors.New("null name condition title")+ }+ }+ *request = CreateDocByParentRequest(next)+ return nil+}++type CreatedDocumentData struct {+ ID string `json:"id"`+ Document DocumentPath `json:"document"`+}++type DocumentCreateFailure struct {+ Reason string `json:"reason" api:"enum=invalidTitle|parentUnavailable|planChanged|documentIDConflict|indexUnavailable|unsupportedTitleFormat|modeConflict|writeFailed"`+ CommitState string `json:"commitState" api:"enum=none|committed|unknown"`+ ID string `json:"id,omitempty" api:"optional"`+ Stage string `json:"stage"`+ Completed []string `json:"completed"`+}++type CreateDocByParentResult struct {+ value *CreatedDocumentData+ failure *DocumentCreateFailure+}++func NewCreateDocByParentResult(value CreatedDocumentData) CreateDocByParentResult {+ return CreateDocByParentResult{value: &value}+}++func NewCreateDocByParentFailure(value DocumentCreateFailure) CreateDocByParentResult {+ return CreateDocByParentResult{failure: &value}+}++func (value CreateDocByParentResult) MarshalJSON() ([]byte, error) {+ if value.value != nil {+ return json.Marshal(value.value)+ }+ if value.failure != nil {+ return json.Marshal(value.failure)+ }+ return nil, errors.New("document creation response is not set")+}++type DocumentTitle struct {+ Format string `json:"format" api:"enum=plain"`+ Text string `json:"text"`+ Empty bool `json:"empty"`+}++type DocumentPathSegment struct {+ ID string `json:"id"`+ Text string `json:"text"`+ Empty bool `json:"empty"`+}++type DocumentPath struct {+ Notebook string `json:"notebook"`+ ID string `json:"id"`+ ParentID *string `json:"parentID"`+ Path string `json:"path"`+ Title DocumentTitle `json:"title"`+ Segments []DocumentPathSegment `json:"segments"`+ Depth int `json:"depth"`+ DisplayPath string `json:"displayPath"`+ Revision string `json:"revision"`+ AddressingVersion int `json:"addressingVersion"`+}++type GetDocPathsRequest struct {+ Notebook string `json:"notebook"`+ IDs []string `json:"ids"`+}++type DocumentPathsData struct {+ Documents []DocumentPath `json:"documents"`+ MissingIDs []string `json:"missingIDs"`+}++type DocumentPathStart struct {+ Kind string `json:"kind" api:"enum=root|document"`+ ID *string `json:"id,omitempty" api:"optional,nonnullable"`+}++type ResolveDocPathRequest struct {+ Notebook string `json:"notebook"`+ Start DocumentPathStart `json:"start"`+ Segments []string `json:"segments"`+}++type DocumentLocation struct {+ Notebook string `json:"notebook"`+ ID *string `json:"id"`+ Revision string `json:"revision"`+}++type DocumentNameCondition struct {+ ParentID *string `json:"parentID"`+ Title string `json:"title"`+ ExpectedID *string `json:"expectedID"`+}++type ResolvedDocumentPathData struct {+ Status string `json:"status" api:"enum=resolved|missing|ambiguous"`+ Start DocumentLocation `json:"start"`+ Resolved *DocumentPath `json:"resolved"`+ NextIndex int `json:"nextIndex"`+ Candidates []DocumentPath `json:"candidates"`+ CandidatesTruncated bool `json:"candidatesTruncated"`+ NameConditions []DocumentNameCondition `json:"nameConditions"`+}++type DocumentAddressingFailure struct {+ Reason string `json:"reason" api:"enum=invalidTitle|parentUnavailable|planChanged|documentIDConflict|legacyPathUnsupported|indexUnavailable|unsupportedTitleFormat|targetModeUnsupported|modeConflict|writeFailed"`+}++type DocumentPathsResult struct {+ value *DocumentPathsData+ failure *DocumentAddressingFailure+}++func NewDocumentPathsResult(value DocumentPathsData) DocumentPathsResult {+ return DocumentPathsResult{value: &value}+}++func NewDocumentPathsFailure(value DocumentAddressingFailure) DocumentPathsResult {+ return DocumentPathsResult{failure: &value}+}++func (value DocumentPathsResult) MarshalJSON() ([]byte, error) {+ if value.value != nil {+ return json.Marshal(value.value)+ }+ if value.failure != nil {+ return json.Marshal(value.failure)+ }+ return nil, errors.New("document paths response is not set")+}++type ResolveDocPathResult struct {+ value *ResolvedDocumentPathData+ failure *DocumentAddressingFailure+}++func NewResolveDocPathResult(value ResolvedDocumentPathData) ResolveDocPathResult {+ return ResolveDocPathResult{value: &value}+}++func NewResolveDocPathFailure(value DocumentAddressingFailure) ResolveDocPathResult {+ return ResolveDocPathResult{failure: &value}+}++func (value ResolveDocPathResult) MarshalJSON() ([]byte, error) {+ if value.value != nil {+ return json.Marshal(value.value)+ }+ if value.failure != nil {+ return json.Marshal(value.failure)+ }+ return nil, errors.New("document path resolution response is not set")+}++func documentAddressingSchema(b *schemaBuilder, t reflect.Type, input bool) (*Schema, error) {+ if t.Kind() == reflect.Pointer && (t.Elem() == reflect.TypeFor[NotebookConfPatch]() || t.Elem() == reflect.TypeFor[StructuredDocumentTarget]()) {+ value, err := documentAddressingSchema(b, t.Elem(), input)+ if err != nil {+ return nil, err+ }+ return nullable(value), nil+ }+ if t == reflect.TypeFor[CreateDocByParentRequest]() || t == reflect.TypeFor[NotebookConfPatch]() ||+ t == reflect.TypeFor[StructuredDocumentTarget]() {+ name := t.Name()+ if input {+ name += "Input"+ }+ if _, exists := b.definitions[name]; !exists {+ object := &Schema{Type: "object", Properties: map[string]*Schema{}, AdditionalProperties: false}+ b.definitions[name] = object+ if err := b.fields(object, t, input); err != nil {+ return nil, err+ }+ }+ return &Schema{Ref: "#/$defs/" + name}, nil+ }+ var valueType reflect.Type+ failureType := reflect.TypeFor[DocumentAddressingFailure]()+ switch t {+ case reflect.TypeFor[FileTreeCreateSavePathResult]():+ valueType, failureType = reflect.TypeFor[FileTreeCreateSavePathData](), reflect.TypeFor[StructuredTemplateRequired]()+ case reflect.TypeFor[FileTreeSavePathResult]():+ valueType, failureType = reflect.TypeFor[FileTreeSavePathData](), reflect.TypeFor[StructuredTemplateRequired]()+ case reflect.TypeFor[DocumentCreateTarget]():+ valueType, failureType = reflect.TypeFor[LegacyDocumentTarget](), reflect.TypeFor[StructuredDocumentTarget]()+ case reflect.TypeFor[CreateDocByParentResult]():+ valueType, failureType = reflect.TypeFor[CreatedDocumentData](), reflect.TypeFor[DocumentCreateFailure]()+ case reflect.TypeFor[DocumentPathsResult]():+ valueType = reflect.TypeFor[DocumentPathsData]()+ case reflect.TypeFor[ResolveDocPathResult]():+ valueType = reflect.TypeFor[ResolvedDocumentPathData]()+ default:+ return nil, nil+ }+ name := t.Name()+ if _, exists := b.definitions[name]; !exists {+ result := &Schema{}+ b.definitions[name] = result+ for _, member := range []reflect.Type{valueType, failureType} {+ schema, err := b.schema(member, input)+ if err != nil {+ return nil, err+ }+ result.AnyOf = append(result.AnyOf, schema)+ }+ }+ return &Schema{Ref: "#/$defs/" + name}, nil+}diff --git a/kernel/apicontract/document_legacy.go b/kernel/apicontract/document_legacy.gonew file mode 100644index 0000000000..4df4c760ca--- /dev/null+++ b/kernel/apicontract/document_legacy.go@@ -0,0 +1,52 @@+package apicontract++import (+ "encoding/json"+ "errors"+)++type StructuredTemplateRequired struct {+ Reason string `json:"reason" api:"enum=structuredTemplateRequired"`+}++type FileTreeCreateSavePathResult struct {+ value *FileTreeCreateSavePathData+ failure *StructuredTemplateRequired+}++func NewFileTreeCreateSavePathResult(value FileTreeCreateSavePathData) FileTreeCreateSavePathResult {+ return FileTreeCreateSavePathResult{value: &value}+}+func NewFileTreeCreateSavePathFailure() FileTreeCreateSavePathResult {+ return FileTreeCreateSavePathResult{failure: &StructuredTemplateRequired{Reason: "structuredTemplateRequired"}}+}+func (result FileTreeCreateSavePathResult) MarshalJSON() ([]byte, error) {+ if result.value != nil {+ return json.Marshal(result.value)+ }+ if result.failure != nil {+ return json.Marshal(result.failure)+ }+ return nil, errors.New("document save path result is not set")+}++type FileTreeSavePathResult struct {+ value *FileTreeSavePathData+ failure *StructuredTemplateRequired+}++func NewFileTreeSavePathResult(value FileTreeSavePathData) FileTreeSavePathResult {+ return FileTreeSavePathResult{value: &value}+}+func NewFileTreeSavePathFailure() FileTreeSavePathResult {+ return FileTreeSavePathResult{failure: &StructuredTemplateRequired{Reason: "structuredTemplateRequired"}}+}+func (result FileTreeSavePathResult) MarshalJSON() ([]byte, error) {+ if result.value != nil {+ return json.Marshal(result.value)+ }+ if result.failure != nil {+ return json.Marshal(result.failure)+ }+ return nil, errors.New("reference save path result is not set")+}diff --git a/kernel/apicontract/document_target.go b/kernel/apicontract/document_target.gonew file mode 100644index 0000000000..b4d95a1f59--- /dev/null+++ b/kernel/apicontract/document_target.go@@ -0,0 +1,107 @@+package apicontract++import (+ "bytes"+ "encoding/json"+ "errors"+)++type DocumentTargetRevision struct {+ Notebook string `json:"notebook"`+ Purpose string `json:"purpose" api:"enum=document|reference|dailyNote"`+ Revision string `json:"revision"`+}++type GetDocCreateTargetRequest struct {+ Notebook string `json:"notebook"`+ Purpose string `json:"purpose" api:"enum=document|reference|dailyNote"`+}++type LegacyDocumentTarget struct {+ Version int `json:"version" api:"const=1"`+ Notebook string `json:"notebook"`+ Path string `json:"path"`+}++type DocumentTargetAnchor struct {+ Kind string `json:"kind" api:"enum=notebookRoot|context|document"`+ ID string `json:"id,omitempty" api:"optional"`+}++type StructuredDocumentTarget struct {+ Version int `json:"version" api:"const=2"`+ Notebook string `json:"notebook"`+ Anchor DocumentTargetAnchor `json:"anchor"`+ Up int `json:"up"`+ Parents []string `json:"parents" api:"nonnullable"`+ Title string `json:"title"`+ OnMissingParent string `json:"onMissingParent" api:"enum=create|error"`+}++type DocumentCreateTarget struct {+ legacy *LegacyDocumentTarget+ structured *StructuredDocumentTarget+}++func (target *StructuredDocumentTarget) UnmarshalJSON(data []byte) error {+ type plain StructuredDocumentTarget+ var next plain+ decoder := json.NewDecoder(bytes.NewReader(data))+ decoder.DisallowUnknownFields()+ if err := decoder.Decode(&next); err != nil {+ return err+ }+ var fields map[string]json.RawMessage+ if err := json.Unmarshal(data, &fields); err != nil {+ return err+ }+ for _, name := range []string{"version", "notebook", "anchor", "up", "parents", "title", "onMissingParent"} {+ if value, exists := fields[name]; !exists || bytes.Equal(bytes.TrimSpace(value), []byte("null")) {+ return errors.New("missing or null document target field: " + name)+ }+ }+ *target = StructuredDocumentTarget(next)+ return nil+}++func LegacyCreateTarget(notebook, path string) DocumentCreateTarget {+ return DocumentCreateTarget{legacy: &LegacyDocumentTarget{Version: 1, Notebook: notebook, Path: path}}+}++func StructuredCreateTarget(value StructuredDocumentTarget) DocumentCreateTarget {+ return DocumentCreateTarget{structured: &value}+}++func (target DocumentCreateTarget) MarshalJSON() ([]byte, error) {+ if target.legacy != nil {+ return json.Marshal(target.legacy)+ }+ if target.structured != nil {+ return json.Marshal(target.structured)+ }+ return nil, errors.New("document target is not set")+}++type DocumentCreateTargetData struct {+ Target DocumentCreateTarget `json:"target"`+ DocCreateTemplatePath string `json:"docCreateTemplatePath"`+ Revision string `json:"revision"`+}++type PlanDocCreateRequest struct {+ Notebook string `json:"notebook"`+ Purpose string `json:"purpose" api:"enum=document|reference|dailyNote"`+ ContextID *string `json:"contextID,omitempty" api:"optional,nullable"`+ Title *string `json:"title,omitempty" api:"optional,nonnullable"`+ ID string `json:"id"`+ Placement string `json:"placement,omitempty" api:"optional,enum=configured|child"`+ Reuse bool `json:"reuse,omitempty" api:"optional"`+ Date *string `json:"date,omitempty" api:"optional,nonnullable"`+}++type DocumentCreatePlan struct {+ Notebook string `json:"notebook"`+ Title string `json:"title"`+ ExistingID string `json:"existingID,omitempty"`+ Steps []CreateDocByParentRequest `json:"steps" api:"nonnullable"`+}diff --git a/kernel/apicontract/filetree_remaining.go b/kernel/apicontract/filetree_remaining.goindex 3b41a3f412..8603c34c69 100644--- a/kernel/apicontract/filetree_remaining.go+++ b/kernel/apicontract/filetree_remaining.go@@ -237,6 +237,7 @@ type FileTreeSortModeData struct {type FileTreeSearchDoc struct {Path string `json:"path"`HPath string `json:"hPath"`+ Title *string `json:"title,omitempty"`Box string `json:"box"`BoxIcon string `json:"boxIcon"`Name *string `json:"name,omitempty"`diff --git a/kernel/apicontract/notebook.go b/kernel/apicontract/notebook.goindex 040f867ea2..d11dac5615 100644--- a/kernel/apicontract/notebook.go+++ b/kernel/apicontract/notebook.go@@ -28,26 +28,41 @@ type NotebookEncryption struct {}type NotebookConf struct {- Name string `json:"name"`- Sort int `json:"sort"`- Icon string `json:"icon"`- Closed bool `json:"closed"`- RefCreateSaveBox string `json:"refCreateSaveBox"`- RefCreateSavePath string `json:"refCreateSavePath"`- DocCreateSaveBox string `json:"docCreateSaveBox"`- DocCreateSavePath string `json:"docCreateSavePath"`- DocCreateTemplatePath string `json:"docCreateTemplatePath"`- DailyNoteSavePath string `json:"dailyNoteSavePath"`- DailyNoteTemplatePath string `json:"dailyNoteTemplatePath"`- SortMode int `json:"sortMode"`- Encrypted bool `json:"encrypted"`- BoxCrypt *NotebookEncryption `json:"boxCrypt"`+ DocCreateTarget *StructuredDocumentTarget `json:"docCreateTarget,omitempty"`+ RefCreateTarget *StructuredDocumentTarget `json:"refCreateTarget,omitempty"`+ DailyNoteTarget *StructuredDocumentTarget `json:"dailyNoteTarget,omitempty"`+ Name string `json:"name"`+ Sort int `json:"sort"`+ Icon string `json:"icon"`+ Closed bool `json:"closed"`+ RefCreateSaveBox string `json:"refCreateSaveBox"`+ RefCreateSavePath string `json:"refCreateSavePath"`+ DocCreateSaveBox string `json:"docCreateSaveBox"`+ DocCreateSavePath string `json:"docCreateSavePath"`+ DocCreateTemplatePath string `json:"docCreateTemplatePath"`+ DailyNoteSavePath string `json:"dailyNoteSavePath"`+ DailyNoteTemplatePath string `json:"dailyNoteTemplatePath"`+ SortMode int `json:"sortMode"`+ Encrypted bool `json:"encrypted"`+ BoxCrypt *NotebookEncryption `json:"boxCrypt"`}type NotebookConfData struct {- Box string `json:"box"`- Name string `json:"name"`- Conf *NotebookConf `json:"conf"`+ Box string `json:"box"`+ Name string `json:"name"`+ Conf *NotebookConf `json:"conf"`+ DocumentCapabilities *DocumentCapabilities `json:"documentCapabilities,omitempty"`+}++type DocumentCapabilities struct {+ AddressingVersion int `json:"addressingVersion"`+ ModeState string `json:"modeState" api:"enum=legacy|structured|conflict|recovering"`+ StructuredPaths bool `json:"structuredPaths"`+ LiteralSlash bool `json:"literalSlash"`+ TitleFormats []string `json:"titleFormats"`+ IndexState string `json:"indexState" api:"enum=missing|building|ready|error"`+ MinimumReaderVersion *string `json:"minimumReaderVersion"`+ Revision string `json:"revision"`}type ImportNotebookCryptoBackupRequest struct {diff --git a/kernel/apicontract/notebook_patch.go b/kernel/apicontract/notebook_patch.goindex 5553dbc3e1..2411489324 100644--- a/kernel/apicontract/notebook_patch.go+++ b/kernel/apicontract/notebook_patch.go@@ -1,5 +1,7 @@package apicontract+import "encoding/json"+// Base64Bytes 保留 JSON 字节切片的 Base64 字符串及数字数组输入。type Base64Bytes []byte@@ -12,6 +14,10 @@ type NotebookEncryptionPatch struct {}type NotebookConfPatch struct {+ DocCreateTarget *StructuredDocumentTarget `json:"docCreateTarget" api:"optional,nullable"`+ RefCreateTarget *StructuredDocumentTarget `json:"refCreateTarget" api:"optional,nullable"`+ DailyNoteTarget *StructuredDocumentTarget `json:"dailyNoteTarget" api:"optional,nullable"`+ targetFields map[string]boolName *string `json:"name" api:"optional"`Sort *int `json:"sort" api:"optional"`Icon *string `json:"icon" api:"optional"`@@ -32,3 +38,26 @@ type SetNotebookConfRequest struct {Notebook string `json:"notebook"`Conf *NotebookConfPatch `json:"conf" api:"optional,legacyobject"`}++// UnmarshalJSON 为新增目标保留显式 null 删除请求,其余旧字段仍按原有部分更新规则绑定。+func (patch *NotebookConfPatch) UnmarshalJSON(data []byte) error {+ type plain NotebookConfPatch+ var next plain+ if err := json.Unmarshal(data, &next); err != nil {+ return err+ }+ var fields map[string]json.RawMessage+ if err := json.Unmarshal(data, &fields); err != nil {+ return err+ }+ next.targetFields = map[string]bool{}+ for _, name := range []string{"docCreateTarget", "refCreateTarget", "dailyNoteTarget"} {+ _, next.targetFields[name] = fields[name]+ }+ *patch = NotebookConfPatch(next)+ return nil+}++func (patch *NotebookConfPatch) HasDocumentTarget(name string) bool {+ return patch != nil && patch.targetFields[name]+}diff --git a/kernel/apicontract/schema.go b/kernel/apicontract/schema.goindex 7b75bc3cdc..8c001966d2 100644--- a/kernel/apicontract/schema.go+++ b/kernel/apicontract/schema.go@@ -138,6 +138,9 @@ func (b *schemaBuilder) schema(t reflect.Type, input bool) (*Schema, error) {if schema, err := avPayloadSchema(b, t, input); schema != nil || err != nil {return schema, err}+ if schema, err := documentAddressingSchema(b, t, input); schema != nil || err != nil {+ return schema, err+ }if t == reflect.TypeFor[PluginRPCMessage]() {response, err := b.schema(reflect.TypeFor[PluginRPCResponse](), false)if err != nil {diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex 6549ee83ae..e4084abc7f 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -21935,6 +21935,172 @@],"additionalProperties": false},+ "CreateDocByParentRequest": {+ "type": "object",+ "properties": {+ "clippingHref": {+ "type": "string"+ },+ "docCreateTemplatePath": {+ "type": "string"+ },+ "expectedParentRevision": {+ "type": "string"+ },+ "expectedTarget": {+ "$ref": "#/$defs/DocumentTargetRevision"+ },+ "id": {+ "type": "string"+ },+ "listDocTree": {+ "type": "boolean"+ },+ "markdown": {+ "type": "string"+ },+ "nameConditions": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/DocumentNameCondition"+ }+ },+ "notebook": {+ "type": "string"+ },+ "parentID": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "sortPosition": {+ "type": "string",+ "enum": [+ "before",+ "after"+ ]+ },+ "sortTargetID": {+ "type": "string"+ },+ "sorts": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "tags": {+ "type": "string"+ },+ "title": {+ "$ref": "#/$defs/DocumentCreateTitle"+ },+ "withMath": {+ "type": "boolean"+ }+ },+ "required": [+ "notebook",+ "parentID",+ "id",+ "title",+ "markdown"+ ],+ "additionalProperties": false+ },+ "CreateDocByParentRequestInput": {+ "type": "object",+ "properties": {+ "clippingHref": {+ "type": "string"+ },+ "docCreateTemplatePath": {+ "type": "string"+ },+ "expectedParentRevision": {+ "type": "string"+ },+ "expectedTarget": {+ "$ref": "#/$defs/DocumentTargetRevisionInput"+ },+ "id": {+ "type": "string"+ },+ "listDocTree": {+ "type": "boolean"+ },+ "markdown": {+ "type": "string"+ },+ "nameConditions": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/DocumentNameConditionInput"+ }+ },+ "notebook": {+ "type": "string"+ },+ "parentID": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "sortPosition": {+ "type": "string",+ "enum": [+ "before",+ "after"+ ]+ },+ "sortTargetID": {+ "type": "string"+ },+ "sorts": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "tags": {+ "type": "string"+ },+ "title": {+ "$ref": "#/$defs/DocumentCreateTitleInput"+ },+ "withMath": {+ "type": "boolean"+ }+ },+ "required": [+ "notebook",+ "parentID",+ "id",+ "title",+ "markdown"+ ],+ "additionalProperties": false+ },+ "CreateDocByParentResult": {+ "anyOf": [+ {+ "$ref": "#/$defs/CreatedDocumentData"+ },+ {+ "$ref": "#/$defs/DocumentCreateFailure"+ }+ ]+ },"CreateDocHistoryRequestInput": {"type": "object","properties": {@@ -22031,6 +22197,22 @@},"additionalProperties": false},+ "CreatedDocumentData": {+ "type": "object",+ "properties": {+ "document": {+ "$ref": "#/$defs/DocumentPath"+ },+ "id": {+ "type": "string"+ }+ },+ "required": [+ "document",+ "id"+ ],+ "additionalProperties": false+ },"Criterion": {"type": "object","properties": {@@ -23735,6 +23917,484 @@],"additionalProperties": false},+ "DocumentAddressingFailure": {+ "type": "object",+ "properties": {+ "reason": {+ "type": "string",+ "enum": [+ "invalidTitle",+ "parentUnavailable",+ "planChanged",+ "documentIDConflict",+ "legacyPathUnsupported",+ "indexUnavailable",+ "unsupportedTitleFormat",+ "targetModeUnsupported",+ "modeConflict",+ "writeFailed"+ ]+ }+ },+ "required": [+ "reason"+ ],+ "additionalProperties": false+ },+ "DocumentCapabilities": {+ "type": "object",+ "properties": {+ "addressingVersion": {+ "type": "integer"+ },+ "indexState": {+ "type": "string",+ "enum": [+ "missing",+ "building",+ "ready",+ "error"+ ]+ },+ "literalSlash": {+ "type": "boolean"+ },+ "minimumReaderVersion": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "modeState": {+ "type": "string",+ "enum": [+ "legacy",+ "structured",+ "conflict",+ "recovering"+ ]+ },+ "revision": {+ "type": "string"+ },+ "structuredPaths": {+ "type": "boolean"+ },+ "titleFormats": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": [+ "addressingVersion",+ "indexState",+ "literalSlash",+ "minimumReaderVersion",+ "modeState",+ "revision",+ "structuredPaths",+ "titleFormats"+ ],+ "additionalProperties": false+ },+ "DocumentCreateFailure": {+ "type": "object",+ "properties": {+ "commitState": {+ "type": "string",+ "enum": [+ "none",+ "committed",+ "unknown"+ ]+ },+ "completed": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ {+ "type": "null"+ }+ ]+ },+ "id": {+ "type": "string"+ },+ "reason": {+ "type": "string",+ "enum": [+ "invalidTitle",+ "parentUnavailable",+ "planChanged",+ "documentIDConflict",+ "indexUnavailable",+ "unsupportedTitleFormat",+ "modeConflict",+ "writeFailed"+ ]+ },+ "stage": {+ "type": "string"+ }+ },+ "required": [+ "commitState",+ "completed",+ "reason",+ "stage"+ ],+ "additionalProperties": false+ },+ "DocumentCreatePlan": {+ "type": "object",+ "properties": {+ "existingID": {+ "type": "string"+ },+ "notebook": {+ "type": "string"+ },+ "steps": {+ "type": "array",+ "items": {+ "$ref": "#/$defs/CreateDocByParentRequest"+ }+ },+ "title": {+ "type": "string"+ }+ },+ "required": [+ "notebook",+ "steps",+ "title"+ ],+ "additionalProperties": false+ },+ "DocumentCreateTarget": {+ "anyOf": [+ {+ "$ref": "#/$defs/LegacyDocumentTarget"+ },+ {+ "$ref": "#/$defs/StructuredDocumentTarget"+ }+ ]+ },+ "DocumentCreateTargetData": {+ "type": "object",+ "properties": {+ "docCreateTemplatePath": {+ "type": "string"+ },+ "revision": {+ "type": "string"+ },+ "target": {+ "$ref": "#/$defs/DocumentCreateTarget"+ }+ },+ "required": [+ "docCreateTemplatePath",+ "revision",+ "target"+ ],+ "additionalProperties": false+ },+ "DocumentCreateTitle": {+ "type": "object",+ "properties": {+ "format": {+ "type": "string"+ },+ "text": {+ "type": "string"+ }+ },+ "required": [+ "format",+ "text"+ ],+ "additionalProperties": false+ },+ "DocumentCreateTitleInput": {+ "type": "object",+ "properties": {+ "format": {+ "type": "string"+ },+ "text": {+ "type": "string"+ }+ },+ "required": [+ "format",+ "text"+ ],+ "additionalProperties": false+ },+ "DocumentLocation": {+ "type": "object",+ "properties": {+ "id": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "notebook": {+ "type": "string"+ },+ "revision": {+ "type": "string"+ }+ },+ "required": [+ "id",+ "notebook",+ "revision"+ ],+ "additionalProperties": false+ },+ "DocumentNameCondition": {+ "type": "object",+ "properties": {+ "expectedID": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "parentID": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "title": {+ "type": "string"+ }+ },+ "required": [+ "expectedID",+ "parentID",+ "title"+ ],+ "additionalProperties": false+ },+ "DocumentNameConditionInput": {+ "type": "object",+ "properties": {+ "expectedID": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "parentID": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "title": {+ "type": "string"+ }+ },+ "required": [+ "expectedID",+ "parentID",+ "title"+ ],+ "additionalProperties": false+ },+ "DocumentPath": {+ "type": "object",+ "properties": {+ "addressingVersion": {+ "type": "integer"+ },+ "depth": {+ "type": "integer"+ },+ "displayPath": {+ "type": "string"+ },+ "id": {+ "type": "string"+ },+ "notebook": {+ "type": "string"+ },+ "parentID": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "path": {+ "type": "string"+ },+ "revision": {+ "type": "string"+ },+ "segments": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "$ref": "#/$defs/DocumentPathSegment"+ }+ },+ {+ "type": "null"+ }+ ]+ },+ "title": {+ "$ref": "#/$defs/DocumentTitle"+ }+ },+ "required": [+ "addressingVersion",+ "depth",+ "displayPath",+ "id",+ "notebook",+ "parentID",+ "path",+ "revision",+ "segments",+ "title"+ ],+ "additionalProperties": false+ },+ "DocumentPathSegment": {+ "type": "object",+ "properties": {+ "empty": {+ "type": "boolean"+ },+ "id": {+ "type": "string"+ },+ "text": {+ "type": "string"+ }+ },+ "required": [+ "empty",+ "id",+ "text"+ ],+ "additionalProperties": false+ },+ "DocumentPathStartInput": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "kind": {+ "type": "string",+ "enum": [+ "root",+ "document"+ ]+ }+ },+ "required": [+ "kind"+ ],+ "additionalProperties": false+ },+ "DocumentPathsData": {+ "type": "object",+ "properties": {+ "documents": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "$ref": "#/$defs/DocumentPath"+ }+ },+ {+ "type": "null"+ }+ ]+ },+ "missingIDs": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": [+ "documents",+ "missingIDs"+ ],+ "additionalProperties": false+ },+ "DocumentPathsResult": {+ "anyOf": [+ {+ "$ref": "#/$defs/DocumentPathsData"+ },+ {+ "$ref": "#/$defs/DocumentAddressingFailure"+ }+ ]+ },"DocumentPreviewImage": {"type": "object","properties": {@@ -23754,6 +24414,119 @@],"additionalProperties": false},+ "DocumentTargetAnchor": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "kind": {+ "type": "string",+ "enum": [+ "notebookRoot",+ "context",+ "document"+ ]+ }+ },+ "required": [+ "kind"+ ],+ "additionalProperties": false+ },+ "DocumentTargetAnchorInput": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "kind": {+ "type": "string",+ "enum": [+ "notebookRoot",+ "context",+ "document"+ ]+ }+ },+ "required": [+ "kind"+ ],+ "additionalProperties": false+ },+ "DocumentTargetRevision": {+ "type": "object",+ "properties": {+ "notebook": {+ "type": "string"+ },+ "purpose": {+ "type": "string",+ "enum": [+ "document",+ "reference",+ "dailyNote"+ ]+ },+ "revision": {+ "type": "string"+ }+ },+ "required": [+ "notebook",+ "purpose",+ "revision"+ ],+ "additionalProperties": false+ },+ "DocumentTargetRevisionInput": {+ "type": "object",+ "properties": {+ "notebook": {+ "type": "string"+ },+ "purpose": {+ "type": "string",+ "enum": [+ "document",+ "reference",+ "dailyNote"+ ]+ },+ "revision": {+ "type": "string"+ }+ },+ "required": [+ "notebook",+ "purpose",+ "revision"+ ],+ "additionalProperties": false+ },+ "DocumentTitle": {+ "type": "object",+ "properties": {+ "empty": {+ "type": "boolean"+ },+ "format": {+ "type": "string",+ "enum": [+ "plain"+ ]+ },+ "text": {+ "type": "string"+ }+ },+ "required": [+ "empty",+ "format",+ "text"+ ],+ "additionalProperties": false+ },"DownloadCloudSnapshotRequestInput": {"type": "object","properties": {@@ -25638,6 +26411,16 @@],"additionalProperties": false},+ "FileTreeCreateSavePathResult": {+ "anyOf": [+ {+ "$ref": "#/$defs/FileTreeCreateSavePathData"+ },+ {+ "$ref": "#/$defs/StructuredTemplateRequired"+ }+ ]+ },"FileTreeDailyNoteRequestInput": {"type": "object","properties": {@@ -26757,6 +27540,16 @@],"additionalProperties": false},+ "FileTreeSavePathResult": {+ "anyOf": [+ {+ "$ref": "#/$defs/FileTreeSavePathData"+ },+ {+ "$ref": "#/$defs/StructuredTemplateRequired"+ }+ ]+ },"FileTreeSearchDoc": {"type": "object","properties": {@@ -26786,6 +27579,9 @@},"path": {"type": "string"+ },+ "title": {+ "type": "string"}},"required": [@@ -28314,6 +29110,46 @@],"additionalProperties": false},+ "GetDocCreateTargetRequestInput": {+ "type": "object",+ "properties": {+ "notebook": {+ "type": "string"+ },+ "purpose": {+ "type": "string",+ "enum": [+ "document",+ "reference",+ "dailyNote"+ ]+ }+ },+ "required": [+ "notebook",+ "purpose"+ ],+ "additionalProperties": false+ },+ "GetDocPathsRequestInput": {+ "type": "object",+ "properties": {+ "ids": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "notebook": {+ "type": "string"+ }+ },+ "required": [+ "ids",+ "notebook"+ ],+ "additionalProperties": false+ },"GetEmbedBlockRequestInput": {"type": "object","properties": {@@ -31288,6 +32124,29 @@],"additionalProperties": false},+ "LegacyDocumentTarget": {+ "type": "object",+ "properties": {+ "notebook": {+ "type": "string"+ },+ "path": {+ "type": "string"+ },+ "version": {+ "type": "integer",+ "enum": [+ 1+ ]+ }+ },+ "required": [+ "notebook",+ "path",+ "version"+ ],+ "additionalProperties": false+ },"ListNotebooksData": {"type": "object","properties": {@@ -34352,6 +35211,9 @@"dailyNoteSavePath": {"type": "string"},+ "dailyNoteTarget": {+ "$ref": "#/$defs/StructuredDocumentTarget"+ },"dailyNoteTemplatePath": {"type": "string"},@@ -34361,6 +35223,9 @@"docCreateSavePath": {"type": "string"},+ "docCreateTarget": {+ "$ref": "#/$defs/StructuredDocumentTarget"+ },"docCreateTemplatePath": {"type": "string"},@@ -34379,6 +35244,9 @@"refCreateSavePath": {"type": "string"},+ "refCreateTarget": {+ "$ref": "#/$defs/StructuredDocumentTarget"+ },"sort": {"type": "integer"},@@ -34420,6 +35288,9 @@}]},+ "documentCapabilities": {+ "$ref": "#/$defs/DocumentCapabilities"+ },"name": {"type": "string"}@@ -34464,6 +35335,16 @@}]},+ "dailyNoteTarget": {+ "anyOf": [+ {+ "$ref": "#/$defs/StructuredDocumentTargetInput"+ },+ {+ "type": "null"+ }+ ]+ },"dailyNoteTemplatePath": {"anyOf": [{@@ -34494,6 +35375,16 @@}]},+ "docCreateTarget": {+ "anyOf": [+ {+ "$ref": "#/$defs/StructuredDocumentTargetInput"+ },+ {+ "type": "null"+ }+ ]+ },"docCreateTemplatePath": {"anyOf": [{@@ -34554,6 +35445,16 @@}]},+ "refCreateTarget": {+ "anyOf": [+ {+ "$ref": "#/$defs/StructuredDocumentTargetInput"+ },+ {+ "type": "null"+ }+ ]+ },"sort": {"anyOf": [{@@ -36072,6 +36973,57 @@],"additionalProperties": false},+ "PlanDocCreateRequestInput": {+ "type": "object",+ "properties": {+ "contextID": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ]+ },+ "date": {+ "type": "string"+ },+ "id": {+ "type": "string"+ },+ "notebook": {+ "type": "string"+ },+ "placement": {+ "type": "string",+ "enum": [+ "configured",+ "child"+ ]+ },+ "purpose": {+ "type": "string",+ "enum": [+ "document",+ "reference",+ "dailyNote"+ ]+ },+ "reuse": {+ "type": "boolean"+ },+ "title": {+ "type": "string"+ }+ },+ "required": [+ "id",+ "notebook",+ "purpose"+ ],+ "additionalProperties": false+ },"PluginPublishInfo": {"type": "object","properties": {@@ -38266,6 +39218,107 @@},"additionalProperties": false},+ "ResolveDocPathRequestInput": {+ "type": "object",+ "properties": {+ "notebook": {+ "type": "string"+ },+ "segments": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "start": {+ "$ref": "#/$defs/DocumentPathStartInput"+ }+ },+ "required": [+ "notebook",+ "segments",+ "start"+ ],+ "additionalProperties": false+ },+ "ResolveDocPathResult": {+ "anyOf": [+ {+ "$ref": "#/$defs/ResolvedDocumentPathData"+ },+ {+ "$ref": "#/$defs/DocumentAddressingFailure"+ }+ ]+ },+ "ResolvedDocumentPathData": {+ "type": "object",+ "properties": {+ "candidates": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "$ref": "#/$defs/DocumentPath"+ }+ },+ {+ "type": "null"+ }+ ]+ },+ "candidatesTruncated": {+ "type": "boolean"+ },+ "nameConditions": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "$ref": "#/$defs/DocumentNameCondition"+ }+ },+ {+ "type": "null"+ }+ ]+ },+ "nextIndex": {+ "type": "integer"+ },+ "resolved": {+ "anyOf": [+ {+ "$ref": "#/$defs/DocumentPath"+ },+ {+ "type": "null"+ }+ ]+ },+ "start": {+ "$ref": "#/$defs/DocumentLocation"+ },+ "status": {+ "type": "string",+ "enum": [+ "resolved",+ "missing",+ "ambiguous"+ ]+ }+ },+ "required": [+ "candidates",+ "candidatesTruncated",+ "nameConditions",+ "nextIndex",+ "resolved",+ "start",+ "status"+ ],+ "additionalProperties": false+ },"ReviewRiffCardRequestInput": {"type": "object","properties": {@@ -51233,6 +52286,113 @@],"additionalProperties": false},+ "StructuredDocumentTarget": {+ "type": "object",+ "properties": {+ "anchor": {+ "$ref": "#/$defs/DocumentTargetAnchor"+ },+ "notebook": {+ "type": "string"+ },+ "onMissingParent": {+ "type": "string",+ "enum": [+ "create",+ "error"+ ]+ },+ "parents": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "title": {+ "type": "string"+ },+ "up": {+ "type": "integer"+ },+ "version": {+ "type": "integer",+ "enum": [+ 2+ ]+ }+ },+ "required": [+ "version",+ "notebook",+ "anchor",+ "up",+ "parents",+ "title",+ "onMissingParent"+ ],+ "additionalProperties": false+ },+ "StructuredDocumentTargetInput": {+ "type": "object",+ "properties": {+ "anchor": {+ "$ref": "#/$defs/DocumentTargetAnchorInput"+ },+ "notebook": {+ "type": "string"+ },+ "onMissingParent": {+ "type": "string",+ "enum": [+ "create",+ "error"+ ]+ },+ "parents": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "title": {+ "type": "string"+ },+ "up": {+ "type": "integer"+ },+ "version": {+ "type": "integer",+ "enum": [+ 2+ ]+ }+ },+ "required": [+ "version",+ "notebook",+ "anchor",+ "up",+ "parents",+ "title",+ "onMissingParent"+ ],+ "additionalProperties": false+ },+ "StructuredTemplateRequired": {+ "type": "object",+ "properties": {+ "reason": {+ "type": "string",+ "enum": [+ "structuredTemplateRequired"+ ]+ }+ },+ "required": [+ "reason"+ ],+ "additionalProperties": false+ },"SwapBlockRefRequestInput": {"type": "object","properties": {@@ -122152,28 +123312,503 @@"additionalProperties": true}]- },- "additionalErrorStatuses": [- 409- ]+ },+ "additionalErrorStatuses": [+ 409+ ]+ },+ {+ "method": "POST",+ "path": "/api/ai/agent/chat",+ "handler": "agentChat",+ "authorization": [+ "authenticated",+ "admin",+ "writable"+ ],+ "body": "structJSON",+ "request": {+ "$ref": "#/$defs/AIAgentChatRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ },+ "output": "sse",+ "sse": {+ "events": {+ "browser_capability_call": {+ "$ref": "#/$defs/AISSEBrowserCapabilityCall"+ },+ "confirm": {+ "$ref": "#/$defs/AISSEConfirm"+ },+ "content": {+ "$ref": "#/$defs/AISSEToken"+ },+ "done": {+ "$ref": "#/$defs/AISSETurn"+ },+ "error": {+ "$ref": "#/$defs/AISSEMessage"+ },+ "interrupted": {+ "$ref": "#/$defs/AISSEMessage"+ },+ "permission": {+ "$ref": "#/$defs/AIPermissionData"+ },+ "question": {+ "$ref": "#/$defs/AISSEQuestion"+ },+ "reasoning": {+ "$ref": "#/$defs/AISSEToken"+ },+ "retry": {+ "$ref": "#/$defs/AISSERetry"+ },+ "snapshot": {+ "$ref": "#/$defs/AISSESnapshot"+ },+ "thinking": {+ "$ref": "#/$defs/AISSEThinking"+ },+ "tool_call": {+ "$ref": "#/$defs/AISSEToolCall"+ },+ "tool_result": {+ "$ref": "#/$defs/AISSEToolResult"+ },+ "turn": {+ "$ref": "#/$defs/AISSETurn"+ },+ "usage": {+ "$ref": "#/$defs/AISSEUsage"+ }+ }+ },+ "additionalErrorStatuses": [+ 409+ ]+ },+ {+ "method": "POST",+ "path": "/api/ai/agent/confirm",+ "handler": "agentChatConfirm",+ "authorization": [+ "authenticated",+ "admin",+ "writable"+ ],+ "body": "structJSON",+ "request": {+ "$ref": "#/$defs/AIConfirmRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "null"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ },+ "additionalErrorStatuses": [+ 409+ ]+ },+ {+ "method": "POST",+ "path": "/api/ai/agent/getInstructions",+ "handler": "getAgentInstructions",+ "authorization": [+ "authenticated",+ "admin"+ ],+ "body": "none",+ "request": {+ "$ref": "#/$defs/EmptyRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "$ref": "#/$defs/AIAgentInstructionsData"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/ai/agent/getSession",+ "handler": "getSession",+ "authorization": [+ "authenticated",+ "admin"+ ],+ "body": "structJSON",+ "request": {+ "$ref": "#/$defs/AISessionIDRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "anyOf": [+ {+ "$ref": "#/$defs/AISessionExtensionAISessionFields"+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ },+ "additionalErrorStatuses": [+ 500+ ]+ },+ {+ "method": "POST",+ "path": "/api/ai/agent/getSkill",+ "handler": "getSkill",+ "authorization": [+ "authenticated",+ "admin"+ ],+ "body": "structJSON",+ "request": {+ "$ref": "#/$defs/AISkillNameRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "$ref": "#/$defs/AISkillData"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }},{"method": "POST",- "path": "/api/ai/agent/chat",- "handler": "agentChat",+ "path": "/api/ai/agent/lsBuiltinSkills",+ "handler": "lsBuiltinSkills","authorization": ["authenticated",- "admin",- "writable"+ "admin"],- "body": "structJSON",+ "body": "none","request": {- "$ref": "#/$defs/AIAgentChatRequestInput"+ "$ref": "#/$defs/EmptyRequestInput"},"response": {"anyOf": [{- "type": "string"+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "$ref": "#/$defs/AIBuiltinSkillInfo"+ }+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false},{"type": "object",@@ -122215,76 +123850,19 @@"additionalProperties": true}]- },- "output": "sse",- "sse": {- "events": {- "browser_capability_call": {- "$ref": "#/$defs/AISSEBrowserCapabilityCall"- },- "confirm": {- "$ref": "#/$defs/AISSEConfirm"- },- "content": {- "$ref": "#/$defs/AISSEToken"- },- "done": {- "$ref": "#/$defs/AISSETurn"- },- "error": {- "$ref": "#/$defs/AISSEMessage"- },- "interrupted": {- "$ref": "#/$defs/AISSEMessage"- },- "permission": {- "$ref": "#/$defs/AIPermissionData"- },- "question": {- "$ref": "#/$defs/AISSEQuestion"- },- "reasoning": {- "$ref": "#/$defs/AISSEToken"- },- "retry": {- "$ref": "#/$defs/AISSERetry"- },- "snapshot": {- "$ref": "#/$defs/AISSESnapshot"- },- "thinking": {- "$ref": "#/$defs/AISSEThinking"- },- "tool_call": {- "$ref": "#/$defs/AISSEToolCall"- },- "tool_result": {- "$ref": "#/$defs/AISSEToolResult"- },- "turn": {- "$ref": "#/$defs/AISSETurn"- },- "usage": {- "$ref": "#/$defs/AISSEUsage"- }- }- },- "additionalErrorStatuses": [- 409- ]+ }},{"method": "POST",- "path": "/api/ai/agent/confirm",- "handler": "agentChatConfirm",+ "path": "/api/ai/agent/lsSessions",+ "handler": "lsSessions","authorization": ["authenticated",- "admin",- "writable"+ "admin"],"body": "structJSON","request": {- "$ref": "#/$defs/AIConfirmRequestInput"+ "$ref": "#/$defs/AISessionsRequestInput"},"response": {"anyOf": [@@ -122298,7 +123876,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/AISessionList"},"msg": {"type": "string"@@ -122351,15 +123929,12 @@"additionalProperties": true}]- },- "additionalErrorStatuses": [- 409- ]+ }},{"method": "POST",- "path": "/api/ai/agent/getInstructions",- "handler": "getAgentInstructions",+ "path": "/api/ai/agent/lsSkills",+ "handler": "lsSkills","authorization": ["authenticated","admin"@@ -122380,7 +123955,17 @@]},"data": {- "$ref": "#/$defs/AIAgentInstructionsData"+ "anyOf": [+ {+ "type": "array",+ "items": {+ "$ref": "#/$defs/AISkillInfo"+ }+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -122437,15 +124022,15 @@},{"method": "POST",- "path": "/api/ai/agent/getSession",- "handler": "getSession",+ "path": "/api/ai/agent/lsUserSkills",+ "handler": "lsUserSkills","authorization": ["authenticated","admin"],- "body": "structJSON",+ "body": "none","request": {- "$ref": "#/$defs/AISessionIDRequestInput"+ "$ref": "#/$defs/EmptyRequestInput"},"response": {"anyOf": [@@ -122461,7 +124046,10 @@"data": {"anyOf": [{- "$ref": "#/$defs/AISessionExtensionAISessionFields"+ "type": "array",+ "items": {+ "$ref": "#/$defs/AIUserSkillInfo"+ }},{"type": "null"@@ -122519,22 +124107,20 @@"additionalProperties": true}]- },- "additionalErrorStatuses": [- 500- ]+ }},{"method": "POST",- "path": "/api/ai/agent/getSkill",- "handler": "getSkill",+ "path": "/api/ai/agent/manageSkills",+ "handler": "manageSkills","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],- "body": "structJSON",+ "body": "json","request": {- "$ref": "#/$defs/AISkillNameRequestInput"+ "$ref": "#/$defs/AISkillFileRequestInput"},"response": {"anyOf": [@@ -122548,7 +124134,7 @@]},"data": {- "$ref": "#/$defs/AISkillData"+ "$ref": "#/$defs/AISkillFileData"},"msg": {"type": "string"@@ -122605,15 +124191,16 @@},{"method": "POST",- "path": "/api/ai/agent/lsBuiltinSkills",- "handler": "lsBuiltinSkills",+ "path": "/api/ai/agent/question",+ "handler": "agentChatQuestion","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],- "body": "none",+ "body": "structJSON","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/AIQuestionRequestInput"},"response": {"anyOf": [@@ -122627,17 +124214,7 @@]},"data": {- "anyOf": [- {- "type": "array",- "items": {- "$ref": "#/$defs/AIBuiltinSkillInfo"- }- },- {- "type": "null"- }- ]+ "type": "null"},"msg": {"type": "string"@@ -122690,19 +124267,23 @@"additionalProperties": true}]- }+ },+ "additionalErrorStatuses": [+ 409+ ]},{"method": "POST",- "path": "/api/ai/agent/lsSessions",- "handler": "lsSessions",+ "path": "/api/ai/agent/removeSession",+ "handler": "removeSession","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "structJSON","request": {- "$ref": "#/$defs/AISessionsRequestInput"+ "$ref": "#/$defs/AISessionIDRequestInput"},"response": {"anyOf": [@@ -122716,7 +124297,7 @@]},"data": {- "$ref": "#/$defs/AISessionList"+ "type": "null"},"msg": {"type": "string"@@ -122769,19 +124350,24 @@"additionalProperties": true}]- }+ },+ "additionalErrorStatuses": [+ 409,+ 500+ ]},{"method": "POST",- "path": "/api/ai/agent/lsSkills",- "handler": "lsSkills",+ "path": "/api/ai/agent/removeSkill",+ "handler": "removeSkill","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],- "body": "none",+ "body": "structJSON","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/AISkillNameRequestInput"},"response": {"anyOf": [@@ -122795,17 +124381,7 @@]},"data": {- "anyOf": [- {- "type": "array",- "items": {- "$ref": "#/$defs/AISkillInfo"- }- },- {- "type": "null"- }- ]+ "type": "null"},"msg": {"type": "string"@@ -122862,15 +124438,16 @@},{"method": "POST",- "path": "/api/ai/agent/lsUserSkills",- "handler": "lsUserSkills",+ "path": "/api/ai/agent/renameSkill",+ "handler": "renameSkill","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],- "body": "none",+ "body": "structJSON","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/AISkillRenameRequestInput"},"response": {"anyOf": [@@ -122884,17 +124461,7 @@]},"data": {- "anyOf": [- {- "type": "array",- "items": {- "$ref": "#/$defs/AIUserSkillInfo"- }- },- {- "type": "null"- }- ]+ "type": "null"},"msg": {"type": "string"@@ -122951,16 +124518,16 @@},{"method": "POST",- "path": "/api/ai/agent/manageSkills",- "handler": "manageSkills",+ "path": "/api/ai/agent/saveSession",+ "handler": "saveSession","authorization": ["authenticated","admin","writable"],- "body": "json",+ "body": "structJSON","request": {- "$ref": "#/$defs/AISkillFileRequestInput"+ "$ref": "#/$defs/AISessionExtensionAISessionFieldsInput"},"response": {"anyOf": [@@ -122974,7 +124541,7 @@]},"data": {- "$ref": "#/$defs/AISkillFileData"+ "$ref": "#/$defs/AISessionSaveData"},"msg": {"type": "string"@@ -123012,6 +124579,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/AISessionSaveData"}]},@@ -123027,12 +124597,17 @@"additionalProperties": true}]- }+ },+ "additionalErrorStatuses": [+ 400,+ 409,+ 500+ ]},{"method": "POST",- "path": "/api/ai/agent/question",- "handler": "agentChatQuestion",+ "path": "/api/ai/agent/saveSkill",+ "handler": "saveSkill","authorization": ["authenticated","admin",@@ -123040,7 +124615,7 @@],"body": "structJSON","request": {- "$ref": "#/$defs/AIQuestionRequestInput"+ "$ref": "#/$defs/AISkillSaveRequestInput"},"response": {"anyOf": [@@ -123107,23 +124682,20 @@"additionalProperties": true}]- },- "additionalErrorStatuses": [- 409- ]+ }},{"method": "POST",- "path": "/api/ai/agent/removeSession",- "handler": "removeSession",+ "path": "/api/ai/agent/setInstructions",+ "handler": "setAgentInstructions","authorization": ["authenticated","admin","writable"],- "body": "structJSON",+ "body": "json","request": {- "$ref": "#/$defs/AISessionIDRequestInput"+ "$ref": "#/$defs/AIAgentInstructionsSaveRequestInput"},"response": {"anyOf": [@@ -123137,7 +124709,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/AIAgentInstructionsData"},"msg": {"type": "string"@@ -123190,16 +124762,12 @@"additionalProperties": true}]- },- "additionalErrorStatuses": [- 409,- 500- ]+ }},{"method": "POST",- "path": "/api/ai/agent/removeSkill",- "handler": "removeSkill",+ "path": "/api/ai/agent/setPermission",+ "handler": "setAgentSessionPermission","authorization": ["authenticated","admin",@@ -123207,7 +124775,7 @@],"body": "structJSON","request": {- "$ref": "#/$defs/AISkillNameRequestInput"+ "$ref": "#/$defs/AIPermissionRequestInput"},"response": {"anyOf": [@@ -123221,7 +124789,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/AIPermissionData"},"msg": {"type": "string"@@ -123278,16 +124846,16 @@},{"method": "POST",- "path": "/api/ai/agent/renameSkill",- "handler": "renameSkill",+ "path": "/api/ai/agent/setPinned",+ "handler": "setAgentSessionPinned","authorization": ["authenticated","admin","writable"],- "body": "structJSON",+ "body": "json","request": {- "$ref": "#/$defs/AISkillRenameRequestInput"+ "$ref": "#/$defs/AISessionPinnedRequestInput"},"response": {"anyOf": [@@ -123301,7 +124869,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/AISessionPinnedData"},"msg": {"type": "string"@@ -123358,16 +124926,15 @@},{"method": "POST",- "path": "/api/ai/agent/saveSession",- "handler": "saveSession",+ "path": "/api/ai/agent/title",+ "handler": "agentChatTitle","authorization": ["authenticated",- "admin",- "writable"+ "admin"],"body": "structJSON","request": {- "$ref": "#/$defs/AISessionExtensionAISessionFieldsInput"+ "$ref": "#/$defs/AITitleRequestInput"},"response": {"anyOf": [@@ -123381,7 +124948,7 @@]},"data": {- "$ref": "#/$defs/AISessionSaveData"+ "type": "string"},"msg": {"type": "string"@@ -123419,9 +124986,85 @@},{"type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/ai/chatGPT",+ "handler": "chatGPT",+ "authorization": [+ "authenticated",+ "admin"+ ],+ "body": "json",+ "request": {+ "$ref": "#/$defs/AIMessageRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "string"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false},{- "$ref": "#/$defs/AISessionSaveData"+ "type": "null"}]},@@ -123437,25 +125080,19 @@"additionalProperties": true}]- },- "additionalErrorStatuses": [- 400,- 409,- 500- ]+ }},{"method": "POST",- "path": "/api/ai/agent/saveSkill",- "handler": "saveSkill",+ "path": "/api/ai/chatGPTWithAction",+ "handler": "chatGPTWithAction","authorization": ["authenticated",- "admin",- "writable"+ "admin"],- "body": "structJSON",+ "body": "json","request": {- "$ref": "#/$defs/AISkillSaveRequestInput"+ "$ref": "#/$defs/AIActionRequestInput"},"response": {"anyOf": [@@ -123469,7 +125106,7 @@]},"data": {- "type": "null"+ "type": "string"},"msg": {"type": "string"@@ -123526,16 +125163,15 @@},{"method": "POST",- "path": "/api/ai/agent/setInstructions",- "handler": "setAgentInstructions",+ "path": "/api/ai/chatgpt/accounts",+ "handler": "chatGPTAccounts","authorization": ["authenticated",- "admin",- "writable"+ "admin"],- "body": "json",+ "body": "none","request": {- "$ref": "#/$defs/AIAgentInstructionsSaveRequestInput"+ "$ref": "#/$defs/EmptyRequestInput"},"response": {"anyOf": [@@ -123549,7 +125185,10 @@]},"data": {- "$ref": "#/$defs/AIAgentInstructionsData"+ "type": "array",+ "items": {+ "$ref": "#/$defs/ChatGPTAccount"+ }},"msg": {"type": "string"@@ -123606,16 +125245,16 @@},{"method": "POST",- "path": "/api/ai/agent/setPermission",- "handler": "setAgentSessionPermission",+ "path": "/api/ai/chatgpt/cancel",+ "handler": "chatGPTCancel","authorization": ["authenticated","admin","writable"],- "body": "structJSON",+ "body": "json","request": {- "$ref": "#/$defs/AIPermissionRequestInput"+ "$ref": "#/$defs/ChatGPTLoginRequestInput"},"response": {"anyOf": [@@ -123629,7 +125268,7 @@]},"data": {- "$ref": "#/$defs/AIPermissionData"+ "type": "null"},"msg": {"type": "string"@@ -123686,8 +125325,8 @@},{"method": "POST",- "path": "/api/ai/agent/setPinned",- "handler": "setAgentSessionPinned",+ "path": "/api/ai/chatgpt/export",+ "handler": "chatGPTExport","authorization": ["authenticated","admin",@@ -123695,7 +125334,7 @@],"body": "json","request": {- "$ref": "#/$defs/AISessionPinnedRequestInput"+ "$ref": "#/$defs/ChatGPTTransferRequestInput"},"response": {"anyOf": [@@ -123709,7 +125348,7 @@]},"data": {- "$ref": "#/$defs/AISessionPinnedData"+ "$ref": "#/$defs/ExportFileData"},"msg": {"type": "string"@@ -123766,15 +125405,16 @@},{"method": "POST",- "path": "/api/ai/agent/title",- "handler": "agentChatTitle",+ "path": "/api/ai/chatgpt/import",+ "handler": "chatGPTImport","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],- "body": "structJSON",+ "body": "json","request": {- "$ref": "#/$defs/AITitleRequestInput"+ "$ref": "#/$defs/ChatGPTTransferRequestInput"},"response": {"anyOf": [@@ -123788,7 +125428,7 @@]},"data": {- "type": "string"+ "$ref": "#/$defs/ChatGPTAccount"},"msg": {"type": "string"@@ -123845,15 +125485,16 @@},{"method": "POST",- "path": "/api/ai/chatGPT",- "handler": "chatGPT",+ "path": "/api/ai/chatgpt/logout",+ "handler": "chatGPTLogout","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/AIMessageRequestInput"+ "$ref": "#/$defs/ChatGPTAccountRequestInput"},"response": {"anyOf": [@@ -123867,7 +125508,7 @@]},"data": {- "type": "string"+ "$ref": "#/$defs/ChatGPTLogoutResult"},"msg": {"type": "string"@@ -123924,15 +125565,16 @@},{"method": "POST",- "path": "/api/ai/chatGPTWithAction",- "handler": "chatGPTWithAction",+ "path": "/api/ai/chatgpt/remove",+ "handler": "chatGPTRemove","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/AIActionRequestInput"+ "$ref": "#/$defs/ChatGPTAccountRequestInput"},"response": {"anyOf": [@@ -123946,7 +125588,7 @@]},"data": {- "type": "string"+ "$ref": "#/$defs/ChatGPTLogoutResult"},"msg": {"type": "string"@@ -124003,15 +125645,16 @@},{"method": "POST",- "path": "/api/ai/chatgpt/accounts",- "handler": "chatGPTAccounts",+ "path": "/api/ai/chatgpt/start",+ "handler": "chatGPTStart","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],- "body": "none",+ "body": "json","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/ChatGPTAccountRequestInput"},"response": {"anyOf": [@@ -124025,10 +125668,7 @@]},"data": {- "type": "array",- "items": {- "$ref": "#/$defs/ChatGPTAccount"- }+ "$ref": "#/$defs/ChatGPTLogin"},"msg": {"type": "string"@@ -124085,12 +125725,11 @@},{"method": "POST",- "path": "/api/ai/chatgpt/cancel",- "handler": "chatGPTCancel",+ "path": "/api/ai/chatgpt/status",+ "handler": "chatGPTStatus","authorization": ["authenticated",- "admin",- "writable"+ "admin"],"body": "json","request": {@@ -124108,7 +125747,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/ChatGPTLoginStatus"},"msg": {"type": "string"@@ -124165,41 +125804,20 @@},{"method": "POST",- "path": "/api/ai/chatgpt/export",- "handler": "chatGPTExport",+ "path": "/api/ai/editor/chat",+ "handler": "aiEditorChat","authorization": ["authenticated",- "admin",- "writable"+ "admin"],- "body": "json",+ "body": "structJSON","request": {- "$ref": "#/$defs/ChatGPTTransferRequestInput"+ "$ref": "#/$defs/AIEditorChatRequestInput"},"response": {"anyOf": [{- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- 0- ]- },- "data": {- "$ref": "#/$defs/ExportFileData"- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],- "additionalProperties": false+ "type": "string"},{"type": "object",@@ -124241,20 +125859,42 @@"additionalProperties": true}]+ },+ "output": "sse",+ "sse": {+ "events": {+ "content": {+ "$ref": "#/$defs/AISSEToken"+ },+ "done": {+ "$ref": "#/$defs/AISSEFinish"+ },+ "error": {+ "$ref": "#/$defs/AISSEMessage"+ },+ "reasoning": {+ "$ref": "#/$defs/AISSEToken"+ },+ "start": {+ "$ref": "#/$defs/AISSEStart"+ },+ "truncated": {+ "$ref": "#/$defs/AISSEMessage"+ }+ }}},{"method": "POST",- "path": "/api/ai/chatgpt/import",- "handler": "chatGPTImport",+ "path": "/api/ai/editor/lsActions",+ "handler": "lsAIEditorActions","authorization": ["authenticated",- "admin",- "writable"+ "admin"],- "body": "json",+ "body": "none","request": {- "$ref": "#/$defs/ChatGPTTransferRequestInput"+ "$ref": "#/$defs/EmptyRequestInput"},"response": {"anyOf": [@@ -124268,7 +125908,24 @@]},"data": {- "$ref": "#/$defs/ChatGPTAccount"+ "anyOf": [+ {+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/AIEditorAction"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -124325,8 +125982,8 @@},{"method": "POST",- "path": "/api/ai/chatgpt/logout",- "handler": "chatGPTLogout",+ "path": "/api/ai/editor/removeAction",+ "handler": "removeAIEditorAction","authorization": ["authenticated","admin",@@ -124334,7 +125991,7 @@],"body": "json","request": {- "$ref": "#/$defs/ChatGPTAccountRequestInput"+ "$ref": "#/$defs/AIEditorActionIDRequestInput"},"response": {"anyOf": [@@ -124348,7 +126005,7 @@]},"data": {- "$ref": "#/$defs/ChatGPTLogoutResult"+ "type": "null"},"msg": {"type": "string"@@ -124405,8 +126062,8 @@},{"method": "POST",- "path": "/api/ai/chatgpt/remove",- "handler": "chatGPTRemove",+ "path": "/api/ai/editor/saveAction",+ "handler": "saveAIEditorAction","authorization": ["authenticated","admin",@@ -124414,7 +126071,7 @@],"body": "json","request": {- "$ref": "#/$defs/ChatGPTAccountRequestInput"+ "$ref": "#/$defs/AIEditorActionSaveRequestInput"},"response": {"anyOf": [@@ -124428,7 +126085,14 @@]},"data": {- "$ref": "#/$defs/ChatGPTLogoutResult"+ "anyOf": [+ {+ "$ref": "#/$defs/AIEditorAction"+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -124485,16 +126149,15 @@},{"method": "POST",- "path": "/api/ai/chatgpt/start",- "handler": "chatGPTStart",+ "path": "/api/ai/embeddingStat",+ "handler": "embeddingStat","authorization": ["authenticated",- "admin",- "writable"+ "admin"],- "body": "json",+ "body": "none","request": {- "$ref": "#/$defs/ChatGPTAccountRequestInput"+ "$ref": "#/$defs/EmptyRequestInput"},"response": {"anyOf": [@@ -124508,7 +126171,14 @@]},"data": {- "$ref": "#/$defs/ChatGPTLogin"+ "anyOf": [+ {+ "$ref": "#/$defs/AIEmbeddingStat"+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -124565,15 +126235,15 @@},{"method": "POST",- "path": "/api/ai/chatgpt/status",- "handler": "chatGPTStatus",+ "path": "/api/ai/listModels",+ "handler": "listModels","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ChatGPTLoginRequestInput"+ "$ref": "#/$defs/AIProviderRequestInput"},"response": {"anyOf": [@@ -124587,7 +126257,7 @@]},"data": {- "$ref": "#/$defs/ChatGPTLoginStatus"+ "$ref": "#/$defs/AIModelsData"},"msg": {"type": "string"@@ -124644,20 +126314,50 @@},{"method": "POST",- "path": "/api/ai/editor/chat",- "handler": "aiEditorChat",+ "path": "/api/ai/lsCapabilities",+ "handler": "lsCapabilities","authorization": ["authenticated","admin"],- "body": "structJSON",+ "body": "none","request": {- "$ref": "#/$defs/AIEditorChatRequestInput"+ "$ref": "#/$defs/EmptyRequestInput"},"response": {"anyOf": [{- "type": "string"+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "array",+ "items": {+ "$ref": "#/$defs/AICapabilityManifest"+ }+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false},{"type": "object",@@ -124699,35 +126399,12 @@"additionalProperties": true}]- },- "output": "sse",- "sse": {- "events": {- "content": {- "$ref": "#/$defs/AISSEToken"- },- "done": {- "$ref": "#/$defs/AISSEFinish"- },- "error": {- "$ref": "#/$defs/AISSEMessage"- },- "reasoning": {- "$ref": "#/$defs/AISSEToken"- },- "start": {- "$ref": "#/$defs/AISSEStart"- },- "truncated": {- "$ref": "#/$defs/AISSEMessage"- }- }}},{"method": "POST",- "path": "/api/ai/editor/lsActions",- "handler": "lsAIEditorActions",+ "path": "/api/ai/mcpEnvironmentVariables",+ "handler": "mcpEnvironmentVariables","authorization": ["authenticated","admin"@@ -124748,24 +126425,7 @@]},"data": {- "anyOf": [- {- "type": "array",- "items": {- "anyOf": [- {- "$ref": "#/$defs/AIEditorAction"- },- {- "type": "null"- }- ]- }- },- {- "type": "null"- }- ]+ "$ref": "#/$defs/AIMCPEnvironmentData"},"msg": {"type": "string"@@ -124822,8 +126482,8 @@},{"method": "POST",- "path": "/api/ai/editor/removeAction",- "handler": "removeAIEditorAction",+ "path": "/api/ai/mcpOAuthAuthorize",+ "handler": "mcpOAuthAuthorize","authorization": ["authenticated","admin",@@ -124831,7 +126491,7 @@],"body": "json","request": {- "$ref": "#/$defs/AIEditorActionIDRequestInput"+ "$ref": "#/$defs/AIMCPIDRequestInput"},"response": {"anyOf": [@@ -124902,8 +126562,8 @@},{"method": "POST",- "path": "/api/ai/editor/saveAction",- "handler": "saveAIEditorAction",+ "path": "/api/ai/mcpOAuthDisconnect",+ "handler": "mcpOAuthDisconnect","authorization": ["authenticated","admin",@@ -124911,7 +126571,7 @@],"body": "json","request": {- "$ref": "#/$defs/AIEditorActionSaveRequestInput"+ "$ref": "#/$defs/AIMCPIDRequestInput"},"response": {"anyOf": [@@ -124925,14 +126585,7 @@]},"data": {- "anyOf": [- {- "$ref": "#/$defs/AIEditorAction"- },- {- "type": "null"- }- ]+ "type": "null"},"msg": {"type": "string"@@ -124989,8 +126642,8 @@},{"method": "POST",- "path": "/api/ai/embeddingStat",- "handler": "embeddingStat",+ "path": "/api/ai/mcpStatus",+ "handler": "mcpStatus","authorization": ["authenticated","admin"@@ -125013,7 +126666,10 @@"data": {"anyOf": [{- "$ref": "#/$defs/AIEmbeddingStat"+ "type": "array",+ "items": {+ "$ref": "#/$defs/AIMCPStatus"+ }},{"type": "null"@@ -125075,15 +126731,16 @@},{"method": "POST",- "path": "/api/ai/listModels",- "handler": "listModels",+ "path": "/api/ai/ocr",+ "handler": "aiOCR","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/AIProviderRequestInput"+ "$ref": "#/$defs/AssetPathRequestInput"},"response": {"anyOf": [@@ -125097,7 +126754,7 @@]},"data": {- "$ref": "#/$defs/AIModelsData"+ "$ref": "#/$defs/AssetTextData"},"msg": {"type": "string"@@ -125154,11 +126811,12 @@},{"method": "POST",- "path": "/api/ai/lsCapabilities",- "handler": "lsCapabilities",+ "path": "/api/ai/reindexEmbedding",+ "handler": "reindexEmbedding","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "none","request": {@@ -125176,17 +126834,7 @@]},"data": {- "anyOf": [- {- "type": "array",- "items": {- "$ref": "#/$defs/AICapabilityManifest"- }- },- {- "type": "null"- }- ]+ "type": "null"},"msg": {"type": "string"@@ -125243,11 +126891,12 @@},{"method": "POST",- "path": "/api/ai/mcpEnvironmentVariables",- "handler": "mcpEnvironmentVariables",+ "path": "/api/ai/retryFailedEmbedding",+ "handler": "retryFailedEmbedding","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "none","request": {@@ -125265,7 +126914,7 @@]},"data": {- "$ref": "#/$defs/AIMCPEnvironmentData"+ "type": "null"},"msg": {"type": "string"@@ -125322,16 +126971,15 @@},{"method": "POST",- "path": "/api/ai/mcpOAuthAuthorize",- "handler": "mcpOAuthAuthorize",+ "path": "/api/ai/testDecisionModel",+ "handler": "testDecisionModel","authorization": ["authenticated",- "admin",- "writable"+ "admin"],"body": "json","request": {- "$ref": "#/$defs/AIMCPIDRequestInput"+ "$ref": "#/$defs/AIDecisionTestRequestInput"},"response": {"anyOf": [@@ -125345,7 +126993,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/AIDecisionTestData"},"msg": {"type": "string"@@ -125402,16 +127050,15 @@},{"method": "POST",- "path": "/api/ai/mcpOAuthDisconnect",- "handler": "mcpOAuthDisconnect",+ "path": "/api/ai/testEmbeddingModel",+ "handler": "testEmbeddingModel","authorization": ["authenticated",- "admin",- "writable"+ "admin"],- "body": "json",+ "body": "none","request": {- "$ref": "#/$defs/AIMCPIDRequestInput"+ "$ref": "#/$defs/EmptyRequestInput"},"response": {"anyOf": [@@ -125425,7 +127072,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/AIEmbeddingTestData"},"msg": {"type": "string"@@ -125482,15 +127129,15 @@},{"method": "POST",- "path": "/api/ai/mcpStatus",- "handler": "mcpStatus",+ "path": "/api/ai/testModel",+ "handler": "testModel","authorization": ["authenticated","admin"],- "body": "none",+ "body": "json","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/AIModelRequestInput"},"response": {"anyOf": [@@ -125504,17 +127151,7 @@]},"data": {- "anyOf": [- {- "type": "array",- "items": {- "$ref": "#/$defs/AIMCPStatus"- }- },- {- "type": "null"- }- ]+ "$ref": "#/$defs/AIModelTestData"},"msg": {"type": "string"@@ -125571,16 +127208,15 @@},{"method": "POST",- "path": "/api/ai/ocr",- "handler": "aiOCR",+ "path": "/api/ai/testRerankModel",+ "handler": "testRerankModel","authorization": ["authenticated",- "admin",- "writable"+ "admin"],- "body": "json",+ "body": "none","request": {- "$ref": "#/$defs/AssetPathRequestInput"+ "$ref": "#/$defs/EmptyRequestInput"},"response": {"anyOf": [@@ -125594,7 +127230,7 @@]},"data": {- "$ref": "#/$defs/AssetTextData"+ "$ref": "#/$defs/AIRerankTestData"},"msg": {"type": "string"@@ -125651,16 +127287,16 @@},{"method": "POST",- "path": "/api/ai/reindexEmbedding",- "handler": "reindexEmbedding",+ "path": "/api/archive/unzip",+ "handler": "unzip","authorization": ["authenticated","admin","writable"],- "body": "none",+ "body": "json","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/UnzipRequestInput"},"response": {"anyOf": [@@ -125731,16 +127367,16 @@},{"method": "POST",- "path": "/api/ai/retryFailedEmbedding",- "handler": "retryFailedEmbedding",+ "path": "/api/archive/zip",+ "handler": "zip","authorization": ["authenticated","admin","writable"],- "body": "none",+ "body": "json","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/ZipRequestInput"},"response": {"anyOf": [@@ -125811,15 +127447,14 @@},{"method": "POST",- "path": "/api/ai/testDecisionModel",- "handler": "testDecisionModel",+ "path": "/api/asset/cancelLivePhotoPreview",+ "handler": "cancelLivePhotoPreview","authorization": [- "authenticated",- "admin"+ "authenticated"],"body": "json","request": {- "$ref": "#/$defs/AIDecisionTestRequestInput"+ "$ref": "#/$defs/LivePhotoPreviewRequestInput"},"response": {"anyOf": [@@ -125833,7 +127468,7 @@]},"data": {- "$ref": "#/$defs/AIDecisionTestData"+ "type": "null"},"msg": {"type": "string"@@ -125890,15 +127525,16 @@},{"method": "POST",- "path": "/api/ai/testEmbeddingModel",- "handler": "testEmbeddingModel",+ "path": "/api/asset/findAssetReferences",+ "handler": "findAssetReferences","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],- "body": "none",+ "body": "json","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/FindAssetReferencesRequestInput"},"response": {"anyOf": [@@ -125912,7 +127548,7 @@]},"data": {- "$ref": "#/$defs/AIEmbeddingTestData"+ "$ref": "#/$defs/AssetReferencesData"},"msg": {"type": "string"@@ -125950,6 +127586,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/AssetReferencesData"}]},@@ -125969,15 +127608,15 @@},{"method": "POST",- "path": "/api/ai/testModel",- "handler": "testModel",+ "path": "/api/asset/finishLivePhotoPreview",+ "handler": "finishLivePhotoPreview","authorization": ["authenticated","admin"],- "body": "json",+ "body": "multipart","request": {- "$ref": "#/$defs/AIModelRequestInput"+ "$ref": "#/$defs/FinishLivePhotoPreviewRequestInput"},"response": {"anyOf": [@@ -125991,7 +127630,7 @@]},"data": {- "$ref": "#/$defs/AIModelTestData"+ "type": "null"},"msg": {"type": "string"@@ -126048,11 +127687,12 @@},{"method": "POST",- "path": "/api/ai/testRerankModel",- "handler": "testRerankModel",+ "path": "/api/asset/fullReindexAssetContent",+ "handler": "fullReindexAssetContent","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "none","request": {@@ -126070,7 +127710,7 @@]},"data": {- "$ref": "#/$defs/AIRerankTestData"+ "type": "null"},"msg": {"type": "string"@@ -126127,16 +127767,14 @@},{"method": "POST",- "path": "/api/archive/unzip",- "handler": "unzip",+ "path": "/api/asset/getDocAssets",+ "handler": "getDocAssets","authorization": [- "authenticated",- "admin",- "writable"+ "authenticated"],"body": "json","request": {- "$ref": "#/$defs/UnzipRequestInput"+ "$ref": "#/$defs/AssetDocumentAssetsRequestInput"},"response": {"anyOf": [@@ -126150,7 +127788,17 @@]},"data": {- "type": "null"+ "anyOf": [+ {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -126207,16 +127855,14 @@},{"method": "POST",- "path": "/api/archive/zip",- "handler": "zip",+ "path": "/api/asset/getDocImageAssets",+ "handler": "getDocImageAssets","authorization": [- "authenticated",- "admin",- "writable"+ "authenticated"],"body": "json","request": {- "$ref": "#/$defs/ZipRequestInput"+ "$ref": "#/$defs/AssetDocumentRequestInput"},"response": {"anyOf": [@@ -126230,7 +127876,17 @@]},"data": {- "type": "null"+ "anyOf": [+ {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -126287,14 +127943,14 @@},{"method": "POST",- "path": "/api/asset/cancelLivePhotoPreview",- "handler": "cancelLivePhotoPreview",+ "path": "/api/asset/getDocPreviewImages",+ "handler": "getDocPreviewImages","authorization": ["authenticated"],"body": "json","request": {- "$ref": "#/$defs/LivePhotoPreviewRequestInput"+ "$ref": "#/$defs/AssetDocumentRequestInput"},"response": {"anyOf": [@@ -126308,7 +127964,17 @@]},"data": {- "type": "null"+ "anyOf": [+ {+ "type": "array",+ "items": {+ "$ref": "#/$defs/DocumentPreviewImage"+ }+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -126365,16 +128031,14 @@},{"method": "POST",- "path": "/api/asset/findAssetReferences",- "handler": "findAssetReferences",+ "path": "/api/asset/getFileAnnotation",+ "handler": "getFileAnnotation","authorization": [- "authenticated",- "admin",- "writable"+ "authenticated"],"body": "json","request": {- "$ref": "#/$defs/FindAssetReferencesRequestInput"+ "$ref": "#/$defs/AssetPathRequestInput"},"response": {"anyOf": [@@ -126388,7 +128052,7 @@]},"data": {- "$ref": "#/$defs/AssetReferencesData"+ "$ref": "#/$defs/AssetAnnotationData"},"msg": {"type": "string"@@ -126407,7 +128071,9 @@"code": {"type": "integer","enum": [- -1+ -1,+ 1,+ 403]},"data": {@@ -126426,9 +128092,6 @@},{"type": "null"- },- {- "$ref": "#/$defs/AssetReferencesData"}]},@@ -126448,15 +128111,16 @@},{"method": "POST",- "path": "/api/asset/finishLivePhotoPreview",- "handler": "finishLivePhotoPreview",+ "path": "/api/asset/getImageOCRText",+ "handler": "getImageOCRText","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],- "body": "multipart",+ "body": "json","request": {- "$ref": "#/$defs/FinishLivePhotoPreviewRequestInput"+ "$ref": "#/$defs/AssetOCRTextRequestInput"},"response": {"anyOf": [@@ -126470,7 +128134,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/ImageOCRTextData"},"msg": {"type": "string"@@ -126527,30 +128191,49 @@},{"method": "POST",- "path": "/api/asset/fullReindexAssetContent",- "handler": "fullReindexAssetContent",+ "path": "/api/asset/getLivePhotoFrame",+ "handler": "getLivePhotoFrame","authorization": ["authenticated",- "admin",- "writable"+ "admin"],- "body": "none",+ "body": "json","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/LivePhotoFrameRequestInput"},"response": {"anyOf": [+ {+ "type": "string",+ "format": "binary"+ },{"type": "object","properties": {"code": {"type": "integer","enum": [- 0+ -1]},"data": {- "type": "null"+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -126561,7 +128244,29 @@"msg","data"],- "additionalProperties": false+ "additionalProperties": true+ }+ ]+ },+ "output": "binary",+ "errorStatus": 422+ },+ {+ "method": "POST",+ "path": "/api/asset/getLivePhotoPreview",+ "handler": "getLivePhotoPreview",+ "authorization": [+ "authenticated"+ ],+ "body": "json",+ "request": {+ "$ref": "#/$defs/LivePhotoPreviewRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "string",+ "format": "binary"},{"type": "object",@@ -126603,18 +128308,21 @@"additionalProperties": true}]- }+ },+ "output": "binary",+ "errorStatus": 422},{"method": "POST",- "path": "/api/asset/getDocAssets",- "handler": "getDocAssets",+ "path": "/api/asset/getMissingAssets",+ "handler": "getMissingAssets","authorization": [- "authenticated"+ "authenticated",+ "admin"],- "body": "json",+ "body": "none","request": {- "$ref": "#/$defs/AssetDocumentAssetsRequestInput"+ "$ref": "#/$defs/EmptyRequestInput"},"response": {"anyOf": [@@ -126632,7 +128340,14 @@{"type": "array","items": {- "type": "string"+ "anyOf": [+ {+ "$ref": "#/$defs/AssetUnusedItem"+ },+ {+ "type": "null"+ }+ ]}},{@@ -126695,14 +128410,15 @@},{"method": "POST",- "path": "/api/asset/getDocImageAssets",- "handler": "getDocImageAssets",+ "path": "/api/asset/getOCRConfig",+ "handler": "getOCRConfig","authorization": [- "authenticated"+ "authenticated",+ "admin"],"body": "json","request": {- "$ref": "#/$defs/AssetDocumentRequestInput"+ "$ref": "#/$defs/EmptyRequestInput"},"response": {"anyOf": [@@ -126716,17 +128432,7 @@]},"data": {- "anyOf": [- {- "type": "array",- "items": {- "type": "string"- }- },- {- "type": "null"- }- ]+ "$ref": "#/$defs/OCRConfigData"},"msg": {"type": "string"@@ -126783,14 +128489,15 @@},{"method": "POST",- "path": "/api/asset/getDocPreviewImages",- "handler": "getDocPreviewImages",+ "path": "/api/asset/getUnusedAssets",+ "handler": "getUnusedAssets","authorization": [- "authenticated"+ "authenticated",+ "admin"],- "body": "json",+ "body": "none","request": {- "$ref": "#/$defs/AssetDocumentRequestInput"+ "$ref": "#/$defs/EmptyRequestInput"},"response": {"anyOf": [@@ -126808,7 +128515,14 @@{"type": "array","items": {- "$ref": "#/$defs/DocumentPreviewImage"+ "anyOf": [+ {+ "$ref": "#/$defs/AssetUnusedItem"+ },+ {+ "type": "null"+ }+ ]}},{@@ -126871,14 +128585,15 @@},{"method": "POST",- "path": "/api/asset/getFileAnnotation",- "handler": "getFileAnnotation",+ "path": "/api/asset/getUnusedEncryptedBoxAssets",+ "handler": "getUnusedEncryptedBoxAssets","authorization": [- "authenticated"+ "authenticated",+ "admin"],"body": "json","request": {- "$ref": "#/$defs/AssetPathRequestInput"+ "$ref": "#/$defs/EncryptedBoxAssetsRequestInput"},"response": {"anyOf": [@@ -126892,7 +128607,24 @@]},"data": {- "$ref": "#/$defs/AssetAnnotationData"+ "anyOf": [+ {+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/AssetUnusedItem"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -126911,9 +128643,7 @@"code": {"type": "integer","enum": [- -1,- 1,- 403+ -1]},"data": {@@ -126951,16 +128681,16 @@},{"method": "POST",- "path": "/api/asset/getImageOCRText",- "handler": "getImageOCRText",+ "path": "/api/asset/importOCRModels",+ "handler": "importOCRModels","authorization": ["authenticated","admin","writable"],- "body": "json",+ "body": "multipart","request": {- "$ref": "#/$defs/AssetOCRTextRequestInput"+ "$ref": "#/$defs/ImportOCRModelsRequestInput"},"response": {"anyOf": [@@ -126974,7 +128704,7 @@]},"data": {- "$ref": "#/$defs/ImageOCRTextData"+ "$ref": "#/$defs/OCRModel"},"msg": {"type": "string"@@ -127031,49 +128761,30 @@},{"method": "POST",- "path": "/api/asset/getLivePhotoFrame",- "handler": "getLivePhotoFrame",+ "path": "/api/asset/insertCover",+ "handler": "insertCover","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/LivePhotoFrameRequestInput"+ "$ref": "#/$defs/InsertCoverRequestInput"},"response": {"anyOf": [- {- "type": "string",- "format": "binary"- },{"type": "object","properties": {"code": {"type": "integer","enum": [- -1+ 0]},"data": {- "anyOf": [- {- "type": "object",- "properties": {- "closeTimeout": {- "type": "number"- }- },- "required": [- "closeTimeout"- ],- "additionalProperties": false- },- {- "type": "null"- }- ]+ "$ref": "#/$defs/AssetInsertCoverData"},"msg": {"type": "string"@@ -127084,29 +128795,7 @@"msg","data"],- "additionalProperties": true- }- ]- },- "output": "binary",- "errorStatus": 422- },- {- "method": "POST",- "path": "/api/asset/getLivePhotoPreview",- "handler": "getLivePhotoPreview",- "authorization": [- "authenticated"- ],- "body": "json",- "request": {- "$ref": "#/$defs/LivePhotoPreviewRequestInput"- },- "response": {- "anyOf": [- {- "type": "string",- "format": "binary"+ "additionalProperties": false},{"type": "object",@@ -127148,21 +128837,20 @@"additionalProperties": true}]- },- "output": "binary",- "errorStatus": 422+ }},{"method": "POST",- "path": "/api/asset/getMissingAssets",- "handler": "getMissingAssets",+ "path": "/api/asset/insertLocalAssets",+ "handler": "insertLocalAssets","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],- "body": "none",+ "body": "json","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/InsertLocalAssetsRequestInput"},"response": {"anyOf": [@@ -127176,24 +128864,7 @@]},"data": {- "anyOf": [- {- "type": "array",- "items": {- "anyOf": [- {- "$ref": "#/$defs/AssetUnusedItem"- },- {- "type": "null"- }- ]- }- },- {- "type": "null"- }- ]+ "$ref": "#/$defs/AssetUploadData"},"msg": {"type": "string"@@ -127231,6 +128902,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/AssetUploadData"}]},@@ -127250,15 +128924,16 @@},{"method": "POST",- "path": "/api/asset/getOCRConfig",- "handler": "getOCRConfig",+ "path": "/api/asset/ocr",+ "handler": "ocr","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/AssetPathRequestInput"},"response": {"anyOf": [@@ -127272,7 +128947,7 @@]},"data": {- "$ref": "#/$defs/OCRConfigData"+ "$ref": "#/$defs/AssetOCRData"},"msg": {"type": "string"@@ -127329,15 +129004,16 @@},{"method": "POST",- "path": "/api/asset/getUnusedAssets",- "handler": "getUnusedAssets",+ "path": "/api/asset/relinkAsset",+ "handler": "relinkAsset","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],- "body": "none",+ "body": "json","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/RelinkAssetRequestInput"},"response": {"anyOf": [@@ -127350,23 +129026,48 @@0]},+ "data": {+ "$ref": "#/$defs/AssetReferencesData"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },"data": {"anyOf": [{- "type": "array",- "items": {- "anyOf": [- {- "$ref": "#/$defs/AssetUnusedItem"- },- {- "type": "null"- }- ]- }+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false},{"type": "null"+ },+ {+ "$ref": "#/$defs/AssetReferencesData"}]},@@ -127379,6 +129080,47 @@"msg","data"],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/asset/removeUnusedAsset",+ "handler": "removeUnusedAsset",+ "authorization": [+ "authenticated",+ "admin",+ "writable"+ ],+ "body": "json",+ "request": {+ "$ref": "#/$defs/AssetPathRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "$ref": "#/$defs/AssetPathData"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],"additionalProperties": false},{@@ -127425,15 +129167,16 @@},{"method": "POST",- "path": "/api/asset/getUnusedEncryptedBoxAssets",- "handler": "getUnusedEncryptedBoxAssets",+ "path": "/api/asset/removeUnusedAssets",+ "handler": "removeUnusedAssets","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],- "body": "json",+ "body": "none","request": {- "$ref": "#/$defs/EncryptedBoxAssetsRequestInput"+ "$ref": "#/$defs/EmptyRequestInput"},"response": {"anyOf": [@@ -127446,20 +129189,42 @@0]},+ "data": {+ "$ref": "#/$defs/AssetPathsData"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },"data": {"anyOf": [{- "type": "array",- "items": {- "anyOf": [- {- "$ref": "#/$defs/AssetUnusedItem"- },- {- "type": "null"- }- ]- }+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false},{"type": "null"@@ -127475,6 +129240,47 @@"msg","data"],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/asset/removeUnusedEncryptedBoxAssets",+ "handler": "removeUnusedEncryptedBoxAssets",+ "authorization": [+ "authenticated",+ "admin",+ "writable"+ ],+ "body": "json",+ "request": {+ "$ref": "#/$defs/RemoveEncryptedBoxAssetsRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "$ref": "#/$defs/AssetPathsData"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],"additionalProperties": false},{@@ -127521,16 +129327,16 @@},{"method": "POST",- "path": "/api/asset/importOCRModels",- "handler": "importOCRModels",+ "path": "/api/asset/renameAsset",+ "handler": "renameAsset","authorization": ["authenticated","admin","writable"],- "body": "multipart",+ "body": "json","request": {- "$ref": "#/$defs/ImportOCRModelsRequestInput"+ "$ref": "#/$defs/RenameAssetRequestInput"},"response": {"anyOf": [@@ -127544,7 +129350,7 @@]},"data": {- "$ref": "#/$defs/OCRModel"+ "$ref": "#/$defs/AssetRenameData"},"msg": {"type": "string"@@ -127601,16 +129407,15 @@},{"method": "POST",- "path": "/api/asset/insertCover",- "handler": "insertCover",+ "path": "/api/asset/resolveAssetPath",+ "handler": "resolveAssetPath","authorization": ["authenticated",- "admin",- "writable"+ "admin"],"body": "json","request": {- "$ref": "#/$defs/InsertCoverRequestInput"+ "$ref": "#/$defs/AssetPathRequestInput"},"response": {"anyOf": [@@ -127624,7 +129429,7 @@]},"data": {- "$ref": "#/$defs/AssetInsertCoverData"+ "type": "string"},"msg": {"type": "string"@@ -127681,8 +129486,8 @@},{"method": "POST",- "path": "/api/asset/insertLocalAssets",- "handler": "insertLocalAssets",+ "path": "/api/asset/setFileAnnotation",+ "handler": "setFileAnnotation","authorization": ["authenticated","admin",@@ -127690,7 +129495,7 @@],"body": "json","request": {- "$ref": "#/$defs/InsertLocalAssetsRequestInput"+ "$ref": "#/$defs/SetAssetAnnotationRequestInput"},"response": {"anyOf": [@@ -127704,7 +129509,7 @@]},"data": {- "$ref": "#/$defs/AssetUploadData"+ "type": "null"},"msg": {"type": "string"@@ -127742,9 +129547,6 @@},{"type": "null"- },- {- "$ref": "#/$defs/AssetUploadData"}]},@@ -127764,8 +129566,8 @@},{"method": "POST",- "path": "/api/asset/ocr",- "handler": "ocr",+ "path": "/api/asset/setImageOCRText",+ "handler": "setImageOCRText","authorization": ["authenticated","admin",@@ -127773,7 +129575,7 @@],"body": "json","request": {- "$ref": "#/$defs/AssetPathRequestInput"+ "$ref": "#/$defs/SetAssetOCRTextRequestInput"},"response": {"anyOf": [@@ -127787,7 +129589,7 @@]},"data": {- "$ref": "#/$defs/AssetOCRData"+ "type": "null"},"msg": {"type": "string"@@ -127844,8 +129646,8 @@},{"method": "POST",- "path": "/api/asset/relinkAsset",- "handler": "relinkAsset",+ "path": "/api/asset/setOCRConfig",+ "handler": "setOCRConfig","authorization": ["authenticated","admin",@@ -127853,7 +129655,7 @@],"body": "json","request": {- "$ref": "#/$defs/RelinkAssetRequestInput"+ "$ref": "#/$defs/SettingOCRInput"},"response": {"anyOf": [@@ -127867,7 +129669,7 @@]},"data": {- "$ref": "#/$defs/AssetReferencesData"+ "$ref": "#/$defs/SettingOCR"},"msg": {"type": "string"@@ -127905,9 +129707,6 @@},{"type": "null"- },- {- "$ref": "#/$defs/AssetReferencesData"}]},@@ -127927,16 +129726,14 @@},{"method": "POST",- "path": "/api/asset/removeUnusedAsset",- "handler": "removeUnusedAsset",+ "path": "/api/asset/startLivePhotoPreview",+ "handler": "startLivePhotoPreview","authorization": [- "authenticated",- "admin",- "writable"+ "authenticated"],"body": "json","request": {- "$ref": "#/$defs/AssetPathRequestInput"+ "$ref": "#/$defs/StartLivePhotoPreviewRequestInput"},"response": {"anyOf": [@@ -127950,7 +129747,7 @@]},"data": {- "$ref": "#/$defs/AssetPathData"+ "$ref": "#/$defs/LivePhotoPreviewSession"},"msg": {"type": "string"@@ -128007,16 +129804,15 @@},{"method": "POST",- "path": "/api/asset/removeUnusedAssets",- "handler": "removeUnusedAssets",+ "path": "/api/asset/statAsset",+ "handler": "statAsset","authorization": ["authenticated",- "admin",- "writable"+ "admin"],- "body": "none",+ "body": "json","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/AssetPathRequestInput"},"response": {"anyOf": [@@ -128030,7 +129826,7 @@]},"data": {- "$ref": "#/$defs/AssetPathsData"+ "$ref": "#/$defs/AssetStatData"},"msg": {"type": "string"@@ -128049,7 +129845,8 @@"code": {"type": "integer","enum": [- -1+ -1,+ 1]},"data": {@@ -128087,16 +129884,16 @@},{"method": "POST",- "path": "/api/asset/removeUnusedEncryptedBoxAssets",- "handler": "removeUnusedEncryptedBoxAssets",+ "path": "/api/asset/upload",+ "handler": "uploadAsset","authorization": ["authenticated","admin","writable"],- "body": "json",+ "body": "multipart","request": {- "$ref": "#/$defs/RemoveEncryptedBoxAssetsRequestInput"+ "$ref": "#/$defs/UploadAssetRequestInput"},"response": {"anyOf": [@@ -128110,7 +129907,7 @@]},"data": {- "$ref": "#/$defs/AssetPathsData"+ "$ref": "#/$defs/AssetUploadData"},"msg": {"type": "string"@@ -128167,8 +129964,8 @@},{"method": "POST",- "path": "/api/asset/renameAsset",- "handler": "renameAsset",+ "path": "/api/asset/uploadCloud",+ "handler": "uploadCloud","authorization": ["authenticated","admin",@@ -128176,7 +129973,7 @@],"body": "json","request": {- "$ref": "#/$defs/RenameAssetRequestInput"+ "$ref": "#/$defs/AssetCloudUploadRequestInput"},"response": {"anyOf": [@@ -128190,7 +129987,7 @@]},"data": {- "$ref": "#/$defs/AssetRenameData"+ "type": "null"},"msg": {"type": "string"@@ -128247,15 +130044,16 @@},{"method": "POST",- "path": "/api/asset/resolveAssetPath",- "handler": "resolveAssetPath",+ "path": "/api/asset/uploadCloudByAssetsPaths",+ "handler": "uploadCloudByAssetsPaths","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/AssetPathRequestInput"+ "$ref": "#/$defs/AssetPathsCloudUploadRequestInput"},"response": {"anyOf": [@@ -128269,7 +130067,7 @@]},"data": {- "type": "string"+ "type": "null"},"msg": {"type": "string"@@ -128326,16 +130124,14 @@},{"method": "POST",- "path": "/api/asset/setFileAnnotation",- "handler": "setFileAnnotation",+ "path": "/api/attr/batchGetBlockAttrs",+ "handler": "batchGetBlockAttrs","authorization": [- "authenticated",- "admin",- "writable"+ "authenticated"],"body": "json","request": {- "$ref": "#/$defs/SetAssetAnnotationRequestInput"+ "$ref": "#/$defs/BlockIDsRequestInput"},"response": {"anyOf": [@@ -128349,7 +130145,20 @@]},"data": {- "type": "null"+ "type": "object",+ "additionalProperties": {+ "anyOf": [+ {+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }+ },+ {+ "type": "null"+ }+ ]+ }},"msg": {"type": "string"@@ -128406,8 +130215,8 @@},{"method": "POST",- "path": "/api/asset/setImageOCRText",- "handler": "setImageOCRText",+ "path": "/api/attr/batchSetBlockAttrs",+ "handler": "batchSetBlockAttrs","authorization": ["authenticated","admin",@@ -128415,7 +130224,7 @@],"body": "json","request": {- "$ref": "#/$defs/SetAssetOCRTextRequestInput"+ "$ref": "#/$defs/BatchSetBlockAttrsRequestInput"},"response": {"anyOf": [@@ -128486,16 +130295,14 @@},{"method": "POST",- "path": "/api/asset/setOCRConfig",- "handler": "setOCRConfig",+ "path": "/api/attr/getBlockAttrs",+ "handler": "getBlockAttrs","authorization": [- "authenticated",- "admin",- "writable"+ "authenticated"],"body": "json","request": {- "$ref": "#/$defs/SettingOCRInput"+ "$ref": "#/$defs/BlockIDRequestInput"},"response": {"anyOf": [@@ -128509,7 +130316,10 @@]},"data": {- "$ref": "#/$defs/SettingOCR"+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }},"msg": {"type": "string"@@ -128566,14 +130376,14 @@},{"method": "POST",- "path": "/api/asset/startLivePhotoPreview",- "handler": "startLivePhotoPreview",+ "path": "/api/attr/getBookmarkLabels",+ "handler": "getBookmarkLabels","authorization": ["authenticated"],- "body": "json",+ "body": "none","request": {- "$ref": "#/$defs/StartLivePhotoPreviewRequestInput"+ "$ref": "#/$defs/EmptyRequestInput"},"response": {"anyOf": [@@ -128586,42 +130396,13 @@0]},- "data": {- "$ref": "#/$defs/LivePhotoPreviewSession"- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],- "additionalProperties": false- },- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- -1- ]- },"data": {"anyOf": [{- "type": "object",- "properties": {- "closeTimeout": {- "type": "number"- }- },- "required": [- "closeTimeout"- ],- "additionalProperties": false+ "type": "array",+ "items": {+ "type": "string"+ }},{"type": "null"@@ -128637,46 +130418,6 @@"msg","data"],- "additionalProperties": true- }- ]- }- },- {- "method": "POST",- "path": "/api/asset/statAsset",- "handler": "statAsset",- "authorization": [- "authenticated",- "admin"- ],- "body": "json",- "request": {- "$ref": "#/$defs/AssetPathRequestInput"- },- "response": {- "anyOf": [- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- 0- ]- },- "data": {- "$ref": "#/$defs/AssetStatData"- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],"additionalProperties": false},{@@ -128685,8 +130426,7 @@"code": {"type": "integer","enum": [- -1,- 1+ -1]},"data": {@@ -128724,16 +130464,16 @@},{"method": "POST",- "path": "/api/asset/upload",- "handler": "uploadAsset",+ "path": "/api/attr/setBlockAttrs",+ "handler": "setBlockAttrs","authorization": ["authenticated","admin","writable"],- "body": "multipart",+ "body": "json","request": {- "$ref": "#/$defs/UploadAssetRequestInput"+ "$ref": "#/$defs/SetBlockAttrsRequestInput"},"response": {"anyOf": [@@ -128747,7 +130487,7 @@]},"data": {- "$ref": "#/$defs/AssetUploadData"+ "type": "null"},"msg": {"type": "string"@@ -128804,8 +130544,8 @@},{"method": "POST",- "path": "/api/asset/uploadCloud",- "handler": "uploadCloud",+ "path": "/api/av/addAttributeViewBlocks",+ "handler": "addAttributeViewBlocks","authorization": ["authenticated","admin",@@ -128813,7 +130553,7 @@],"body": "json","request": {- "$ref": "#/$defs/AssetCloudUploadRequestInput"+ "$ref": "#/$defs/AddAttributeViewBlocksRequestInput"},"response": {"anyOf": [@@ -128884,8 +130624,8 @@},{"method": "POST",- "path": "/api/asset/uploadCloudByAssetsPaths",- "handler": "uploadCloudByAssetsPaths",+ "path": "/api/av/addAttributeViewKey",+ "handler": "addAttributeViewKey","authorization": ["authenticated","admin",@@ -128893,7 +130633,7 @@],"body": "json","request": {- "$ref": "#/$defs/AssetPathsCloudUploadRequestInput"+ "$ref": "#/$defs/AddAttributeViewKeyRequestInput"},"response": {"anyOf": [@@ -128964,14 +130704,16 @@},{"method": "POST",- "path": "/api/attr/batchGetBlockAttrs",- "handler": "batchGetBlockAttrs",+ "path": "/api/av/appendAttributeViewDetachedBlocksWithValues",+ "handler": "appendAttributeViewDetachedBlocksWithValues","authorization": [- "authenticated"+ "authenticated",+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/BlockIDsRequestInput"+ "$ref": "#/$defs/AppendAttributeViewDetachedBlocksWithValuesRequestInput"},"response": {"anyOf": [@@ -128985,20 +130727,7 @@]},"data": {- "type": "object",- "additionalProperties": {- "anyOf": [- {- "type": "object",- "additionalProperties": {- "type": "string"- }- },- {- "type": "null"- }- ]- }+ "type": "null"},"msg": {"type": "string"@@ -129055,8 +130784,8 @@},{"method": "POST",- "path": "/api/attr/batchSetBlockAttrs",- "handler": "batchSetBlockAttrs",+ "path": "/api/av/batchReplaceAttributeViewBlocks",+ "handler": "batchReplaceAttributeViewBlocks","authorization": ["authenticated","admin",@@ -129064,7 +130793,7 @@],"body": "json","request": {- "$ref": "#/$defs/BatchSetBlockAttrsRequestInput"+ "$ref": "#/$defs/BatchReplaceAttributeViewBlocksRequestInput"},"response": {"anyOf": [@@ -129135,14 +130864,16 @@},{"method": "POST",- "path": "/api/attr/getBlockAttrs",- "handler": "getBlockAttrs",+ "path": "/api/av/batchSetAttributeViewBlockAttrs",+ "handler": "batchSetAttributeViewBlockAttrs","authorization": [- "authenticated"+ "authenticated",+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/BlockIDRequestInput"+ "$ref": "#/$defs/BatchSetAttributeViewBlockAttrsRequestInput"},"response": {"anyOf": [@@ -129156,10 +130887,7 @@]},"data": {- "type": "object",- "additionalProperties": {- "type": "string"- }+ "type": "null"},"msg": {"type": "string"@@ -129216,14 +130944,16 @@},{"method": "POST",- "path": "/api/attr/getBookmarkLabels",- "handler": "getBookmarkLabels",+ "path": "/api/av/changeAttrViewLayout",+ "handler": "changeAttrViewLayout","authorization": [- "authenticated"+ "authenticated",+ "admin",+ "writable"],- "body": "none",+ "body": "json","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/ChangeAttrViewLayoutRequestInput"},"response": {"anyOf": [@@ -129237,17 +130967,7 @@]},"data": {- "anyOf": [- {- "type": "array",- "items": {- "type": "string"- }- },- {- "type": "null"- }- ]+ "$ref": "#/$defs/AVRenderResult"},"msg": {"type": "string"@@ -129285,6 +131005,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/AVRenderResult"}]},@@ -129304,8 +131027,8 @@},{"method": "POST",- "path": "/api/attr/setBlockAttrs",- "handler": "setBlockAttrs",+ "path": "/api/av/createAttributeViewItem",+ "handler": "createAttributeViewItem","authorization": ["authenticated","admin",@@ -129313,7 +131036,7 @@],"body": "json","request": {- "$ref": "#/$defs/SetBlockAttrsRequestInput"+ "$ref": "#/$defs/CreateAttributeViewItemRequestInput"},"response": {"anyOf": [@@ -129327,7 +131050,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/AVCreateItemResult"},"msg": {"type": "string"@@ -129346,7 +131069,8 @@"code": {"type": "integer","enum": [- -1+ -1,+ 1]},"data": {@@ -129365,6 +131089,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/AVCreateItemResult"}]},@@ -129384,8 +131111,8 @@},{"method": "POST",- "path": "/api/av/addAttributeViewBlocks",- "handler": "addAttributeViewBlocks",+ "path": "/api/av/createAttributeViewItemDocs",+ "handler": "createAttributeViewItemDocs","authorization": ["authenticated","admin",@@ -129393,7 +131120,7 @@],"body": "json","request": {- "$ref": "#/$defs/AddAttributeViewBlocksRequestInput"+ "$ref": "#/$defs/CreateAttributeViewItemDocsRequestInput"},"response": {"anyOf": [@@ -129407,7 +131134,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/AVCreateItemDocsResult"},"msg": {"type": "string"@@ -129426,7 +131153,8 @@"code": {"type": "integer","enum": [- -1+ -1,+ 1]},"data": {@@ -129445,6 +131173,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/AVCreateItemDocsResult"}]},@@ -129464,8 +131195,8 @@},{"method": "POST",- "path": "/api/av/addAttributeViewKey",- "handler": "addAttributeViewKey",+ "path": "/api/av/createAttributeViewItemWithMarkdown",+ "handler": "createAttributeViewItemWithMarkdown","authorization": ["authenticated","admin",@@ -129473,7 +131204,7 @@],"body": "json","request": {- "$ref": "#/$defs/AddAttributeViewKeyRequestInput"+ "$ref": "#/$defs/CreateAttributeViewItemWithMarkdownRequestInput"},"response": {"anyOf": [@@ -129487,7 +131218,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/AVCreateItemResult"},"msg": {"type": "string"@@ -129506,7 +131237,8 @@"code": {"type": "integer","enum": [- -1+ -1,+ 1]},"data": {@@ -129525,6 +131257,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/AVCreateItemResult"}]},@@ -129544,8 +131279,8 @@},{"method": "POST",- "path": "/api/av/appendAttributeViewDetachedBlocksWithValues",- "handler": "appendAttributeViewDetachedBlocksWithValues",+ "path": "/api/av/createAttributeViewRelationItem",+ "handler": "createAttributeViewRelationItem","authorization": ["authenticated","admin",@@ -129553,7 +131288,7 @@],"body": "json","request": {- "$ref": "#/$defs/AppendAttributeViewDetachedBlocksWithValuesRequestInput"+ "$ref": "#/$defs/CreateAttributeViewRelationItemRequestInput"},"response": {"anyOf": [@@ -129567,7 +131302,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/AVCreateItemResult"},"msg": {"type": "string"@@ -129586,7 +131321,8 @@"code": {"type": "integer","enum": [- -1+ -1,+ 1]},"data": {@@ -129605,6 +131341,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/AVCreateItemResult"}]},@@ -129624,8 +131363,8 @@},{"method": "POST",- "path": "/api/av/batchReplaceAttributeViewBlocks",- "handler": "batchReplaceAttributeViewBlocks",+ "path": "/api/av/duplicateAttributeViewBlock",+ "handler": "duplicateAttributeViewBlock","authorization": ["authenticated","admin",@@ -129633,7 +131372,7 @@],"body": "json","request": {- "$ref": "#/$defs/BatchReplaceAttributeViewBlocksRequestInput"+ "$ref": "#/$defs/DuplicateAttributeViewBlockRequestInput"},"response": {"anyOf": [@@ -129647,7 +131386,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/AVDuplicateData"},"msg": {"type": "string"@@ -129704,16 +131443,15 @@},{"method": "POST",- "path": "/api/av/batchSetAttributeViewBlockAttrs",- "handler": "batchSetAttributeViewBlockAttrs",+ "path": "/api/av/getAttributeView",+ "handler": "getAttributeView","authorization": ["authenticated",- "admin","writable"],"body": "json","request": {- "$ref": "#/$defs/BatchSetAttributeViewBlockAttrsRequestInput"+ "$ref": "#/$defs/GetAttributeViewRequestInput"},"response": {"anyOf": [@@ -129727,7 +131465,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/AVData"},"msg": {"type": "string"@@ -129784,16 +131522,15 @@},{"method": "POST",- "path": "/api/av/changeAttrViewLayout",- "handler": "changeAttrViewLayout",+ "path": "/api/av/getAttributeViewAddingBlockDefaultValues",+ "handler": "getAttributeViewAddingBlockDefaultValues","authorization": ["authenticated",- "admin",- "writable"+ "admin"],"body": "json","request": {- "$ref": "#/$defs/ChangeAttrViewLayoutRequestInput"+ "$ref": "#/$defs/GetAttributeViewAddingBlockDefaultValuesRequestInput"},"response": {"anyOf": [@@ -129807,7 +131544,7 @@]},"data": {- "$ref": "#/$defs/AVRenderResult"+ "$ref": "#/$defs/AVValuesData"},"msg": {"type": "string"@@ -129845,9 +131582,6 @@},{"type": "null"- },- {- "$ref": "#/$defs/AVRenderResult"}]},@@ -129867,16 +131601,14 @@},{"method": "POST",- "path": "/api/av/createAttributeViewItem",- "handler": "createAttributeViewItem",+ "path": "/api/av/getAttributeViewBacklinks",+ "handler": "getAttributeViewBacklinks","authorization": [- "authenticated",- "admin",- "writable"+ "authenticated"],"body": "json","request": {- "$ref": "#/$defs/CreateAttributeViewItemRequestInput"+ "$ref": "#/$defs/GetAttributeViewBacklinksRequestInput"},"response": {"anyOf": [@@ -129890,7 +131622,14 @@]},"data": {- "$ref": "#/$defs/AVCreateItemResult"+ "anyOf": [+ {+ "$ref": "#/$defs/AVAttributeViewBacklinks"+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -129909,8 +131648,7 @@"code": {"type": "integer","enum": [- -1,- 1+ -1]},"data": {@@ -129929,9 +131667,6 @@},{"type": "null"- },- {- "$ref": "#/$defs/AVCreateItemResult"}]},@@ -129951,16 +131686,15 @@},{"method": "POST",- "path": "/api/av/createAttributeViewItemDocs",- "handler": "createAttributeViewItemDocs",+ "path": "/api/av/getAttributeViewBoundBlockIDsByItemIDs",+ "handler": "getAttributeViewBoundBlockIDsByItemIDs","authorization": ["authenticated",- "admin",- "writable"+ "admin"],"body": "json","request": {- "$ref": "#/$defs/CreateAttributeViewItemDocsRequestInput"+ "$ref": "#/$defs/GetAttributeViewBoundBlockIDsByItemIDsRequestInput"},"response": {"anyOf": [@@ -129973,49 +131707,16 @@0]},- "data": {- "$ref": "#/$defs/AVCreateItemDocsResult"- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],- "additionalProperties": false- },- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- -1,- 1- ]- },"data": {"anyOf": [{"type": "object",- "properties": {- "closeTimeout": {- "type": "number"- }- },- "required": [- "closeTimeout"- ],- "additionalProperties": false+ "additionalProperties": {+ "type": "string"+ }},{"type": "null"- },- {- "$ref": "#/$defs/AVCreateItemDocsResult"}]},@@ -130028,47 +131729,6 @@"msg","data"],- "additionalProperties": true- }- ]- }- },- {- "method": "POST",- "path": "/api/av/createAttributeViewItemWithMarkdown",- "handler": "createAttributeViewItemWithMarkdown",- "authorization": [- "authenticated",- "admin",- "writable"- ],- "body": "json",- "request": {- "$ref": "#/$defs/CreateAttributeViewItemWithMarkdownRequestInput"- },- "response": {- "anyOf": [- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- 0- ]- },- "data": {- "$ref": "#/$defs/AVCreateItemResult"- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],"additionalProperties": false},{@@ -130077,8 +131737,7 @@"code": {"type": "integer","enum": [- -1,- 1+ -1]},"data": {@@ -130097,9 +131756,6 @@},{"type": "null"- },- {- "$ref": "#/$defs/AVCreateItemResult"}]},@@ -130119,8 +131775,8 @@},{"method": "POST",- "path": "/api/av/createAttributeViewRelationItem",- "handler": "createAttributeViewRelationItem",+ "path": "/api/av/getAttributeViewCalendarUndated",+ "handler": "getAttributeViewCalendarUndated","authorization": ["authenticated","admin",@@ -130128,7 +131784,7 @@],"body": "json","request": {- "$ref": "#/$defs/CreateAttributeViewRelationItemRequestInput"+ "$ref": "#/$defs/AVCalendarUndatedRequestInput"},"response": {"anyOf": [@@ -130142,7 +131798,7 @@]},"data": {- "$ref": "#/$defs/AVCreateItemResult"+ "$ref": "#/$defs/AVCalendarUndatedData"},"msg": {"type": "string"@@ -130161,8 +131817,7 @@"code": {"type": "integer","enum": [- -1,- 1+ -1]},"data": {@@ -130181,9 +131836,6 @@},{"type": "null"- },- {- "$ref": "#/$defs/AVCreateItemResult"}]},@@ -130203,16 +131855,15 @@},{"method": "POST",- "path": "/api/av/duplicateAttributeViewBlock",- "handler": "duplicateAttributeViewBlock",+ "path": "/api/av/getAttributeViewFieldViews",+ "handler": "getAttributeViewFieldViews","authorization": ["authenticated",- "admin","writable"],"body": "json","request": {- "$ref": "#/$defs/DuplicateAttributeViewBlockRequestInput"+ "$ref": "#/$defs/GetAttributeViewFieldViewsRequestInput"},"response": {"anyOf": [@@ -130226,7 +131877,7 @@]},"data": {- "$ref": "#/$defs/AVDuplicateData"+ "$ref": "#/$defs/AVFieldViewsData"},"msg": {"type": "string"@@ -130283,15 +131934,16 @@},{"method": "POST",- "path": "/api/av/getAttributeView",- "handler": "getAttributeView",+ "path": "/api/av/getAttributeViewFilterSort",+ "handler": "getAttributeViewFilterSort","authorization": ["authenticated",+ "admin","writable"],"body": "json","request": {- "$ref": "#/$defs/GetAttributeViewRequestInput"+ "$ref": "#/$defs/GetAttributeViewFilterSortRequestInput"},"response": {"anyOf": [@@ -130305,7 +131957,7 @@]},"data": {- "$ref": "#/$defs/AVData"+ "$ref": "#/$defs/AVFilterSortData"},"msg": {"type": "string"@@ -130362,15 +132014,15 @@},{"method": "POST",- "path": "/api/av/getAttributeViewAddingBlockDefaultValues",- "handler": "getAttributeViewAddingBlockDefaultValues",+ "path": "/api/av/getAttributeViewItemIDsByBoundIDs",+ "handler": "getAttributeViewItemIDsByBoundIDs","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/GetAttributeViewAddingBlockDefaultValuesRequestInput"+ "$ref": "#/$defs/GetAttributeViewItemIDsByBoundIDsRequestInput"},"response": {"anyOf": [@@ -130383,88 +132035,13 @@0]},- "data": {- "$ref": "#/$defs/AVValuesData"- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],- "additionalProperties": false- },- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- -1- ]- },"data": {"anyOf": [{"type": "object",- "properties": {- "closeTimeout": {- "type": "number"- }- },- "required": [- "closeTimeout"- ],- "additionalProperties": false- },- {- "type": "null"- }- ]- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],- "additionalProperties": true- }- ]- }- },- {- "method": "POST",- "path": "/api/av/getAttributeViewBacklinks",- "handler": "getAttributeViewBacklinks",- "authorization": [- "authenticated"- ],- "body": "json",- "request": {- "$ref": "#/$defs/GetAttributeViewBacklinksRequestInput"- },- "response": {- "anyOf": [- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- 0- ]- },- "data": {- "anyOf": [- {- "$ref": "#/$defs/AVAttributeViewBacklinks"+ "additionalProperties": {+ "type": "string"+ }},{"type": "null"@@ -130526,15 +132103,16 @@},{"method": "POST",- "path": "/api/av/getAttributeViewBoundBlockIDsByItemIDs",- "handler": "getAttributeViewBoundBlockIDsByItemIDs",+ "path": "/api/av/getAttributeViewItemStatuses",+ "handler": "getAttributeViewItemStatuses","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/GetAttributeViewBoundBlockIDsByItemIDsRequestInput"+ "$ref": "#/$defs/GetAttributeViewItemStatusesRequestInput"},"response": {"anyOf": [@@ -130615,16 +132193,14 @@},{"method": "POST",- "path": "/api/av/getAttributeViewCalendarUndated",- "handler": "getAttributeViewCalendarUndated",+ "path": "/api/av/getAttributeViewKeys",+ "handler": "getAttributeViewKeys","authorization": [- "authenticated",- "admin",- "writable"+ "authenticated"],"body": "json","request": {- "$ref": "#/$defs/AVCalendarUndatedRequestInput"+ "$ref": "#/$defs/GetAttributeViewKeysRequestInput"},"response": {"anyOf": [@@ -130637,42 +132213,20 @@0]},- "data": {- "$ref": "#/$defs/AVCalendarUndatedData"- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],- "additionalProperties": false- },- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- -1- ]- },"data": {"anyOf": [{- "type": "object",- "properties": {- "closeTimeout": {- "type": "number"- }- },- "required": [- "closeTimeout"- ],- "additionalProperties": false+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/AVBlockAttributeViewKeys"+ },+ {+ "type": "null"+ }+ ]+ }},{"type": "null"@@ -130688,46 +132242,6 @@"msg","data"],- "additionalProperties": true- }- ]- }- },- {- "method": "POST",- "path": "/api/av/getAttributeViewFieldViews",- "handler": "getAttributeViewFieldViews",- "authorization": [- "authenticated",- "writable"- ],- "body": "json",- "request": {- "$ref": "#/$defs/GetAttributeViewFieldViewsRequestInput"- },- "response": {- "anyOf": [- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- 0- ]- },- "data": {- "$ref": "#/$defs/AVFieldViewsData"- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],"additionalProperties": false},{@@ -130774,8 +132288,8 @@},{"method": "POST",- "path": "/api/av/getAttributeViewFilterSort",- "handler": "getAttributeViewFilterSort",+ "path": "/api/av/getAttributeViewKeysByAvID",+ "handler": "getAttributeViewKeysByAvID","authorization": ["authenticated","admin",@@ -130783,7 +132297,7 @@],"body": "json","request": {- "$ref": "#/$defs/GetAttributeViewFilterSortRequestInput"+ "$ref": "#/$defs/GetAttributeViewKeysByAvIDRequestInput"},"response": {"anyOf": [@@ -130797,7 +132311,24 @@]},"data": {- "$ref": "#/$defs/AVFilterSortData"+ "anyOf": [+ {+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/AVKey"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -130854,15 +132385,15 @@},{"method": "POST",- "path": "/api/av/getAttributeViewItemIDsByBoundIDs",- "handler": "getAttributeViewItemIDsByBoundIDs",+ "path": "/api/av/getAttributeViewKeysByID",+ "handler": "getAttributeViewKeysByID","authorization": ["authenticated",- "admin"+ "writable"],"body": "json","request": {- "$ref": "#/$defs/GetAttributeViewItemIDsByBoundIDsRequestInput"+ "$ref": "#/$defs/GetAttributeViewKeysByIDRequestInput"},"response": {"anyOf": [@@ -130878,9 +132409,16 @@"data": {"anyOf": [{- "type": "object",- "additionalProperties": {- "type": "string"+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/AVKey"+ },+ {+ "type": "null"+ }+ ]}},{@@ -130943,8 +132481,8 @@},{"method": "POST",- "path": "/api/av/getAttributeViewItemStatuses",- "handler": "getAttributeViewItemStatuses",+ "path": "/api/av/getAttributeViewPasteRows",+ "handler": "getAttributeViewPasteRows","authorization": ["authenticated","admin",@@ -130952,7 +132490,7 @@],"body": "json","request": {- "$ref": "#/$defs/GetAttributeViewItemStatusesRequestInput"+ "$ref": "#/$defs/GetAttributeViewPasteRowsRequestInput"},"response": {"anyOf": [@@ -130966,17 +132504,7 @@]},"data": {- "anyOf": [- {- "type": "object",- "additionalProperties": {- "type": "string"- }- },- {- "type": "null"- }- ]+ "$ref": "#/$defs/AVPasteRowsData"},"msg": {"type": "string"@@ -131033,14 +132561,16 @@},{"method": "POST",- "path": "/api/av/getAttributeViewKeys",- "handler": "getAttributeViewKeys",+ "path": "/api/av/getAttributeViewPrimaryKeyValues",+ "handler": "getAttributeViewPrimaryKeyValues","authorization": [- "authenticated"+ "authenticated",+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/GetAttributeViewKeysRequestInput"+ "$ref": "#/$defs/GetAttributeViewPrimaryKeyValuesRequestInput"},"response": {"anyOf": [@@ -131054,24 +132584,7 @@]},"data": {- "anyOf": [- {- "type": "array",- "items": {- "anyOf": [- {- "$ref": "#/$defs/AVBlockAttributeViewKeys"- },- {- "type": "null"- }- ]- }- },- {- "type": "null"- }- ]+ "$ref": "#/$defs/AVPrimaryValuesData"},"msg": {"type": "string"@@ -131128,8 +132641,8 @@},{"method": "POST",- "path": "/api/av/getAttributeViewKeysByAvID",- "handler": "getAttributeViewKeysByAvID",+ "path": "/api/av/getAttributeViewRelationCandidates",+ "handler": "getAttributeViewRelationCandidates","authorization": ["authenticated","admin",@@ -131137,7 +132650,7 @@],"body": "json","request": {- "$ref": "#/$defs/GetAttributeViewKeysByAvIDRequestInput"+ "$ref": "#/$defs/GetAttributeViewRelationCandidatesRequestInput"},"response": {"anyOf": [@@ -131151,24 +132664,7 @@]},"data": {- "anyOf": [- {- "type": "array",- "items": {- "anyOf": [- {- "$ref": "#/$defs/AVKey"- },- {- "type": "null"- }- ]- }- },- {- "type": "null"- }- ]+ "$ref": "#/$defs/AVRelationCandidatesData"},"msg": {"type": "string"@@ -131225,15 +132721,15 @@},{"method": "POST",- "path": "/api/av/getAttributeViewKeysByID",- "handler": "getAttributeViewKeysByID",+ "path": "/api/av/getAttributeViewRowSort",+ "handler": "getAttributeViewRowSort","authorization": ["authenticated",- "writable"+ "admin"],- "body": "json",+ "body": "structJSON","request": {- "$ref": "#/$defs/GetAttributeViewKeysByIDRequestInput"+ "$ref": "#/$defs/GetAttributeViewRowSortRequestInput"},"response": {"anyOf": [@@ -131247,24 +132743,7 @@]},"data": {- "anyOf": [- {- "type": "array",- "items": {- "anyOf": [- {- "$ref": "#/$defs/AVKey"- },- {- "type": "null"- }- ]- }- },- {- "type": "null"- }- ]+ "$ref": "#/$defs/AVRowSortPreview"},"msg": {"type": "string"@@ -131321,16 +132800,15 @@},{"method": "POST",- "path": "/api/av/getAttributeViewPasteRows",- "handler": "getAttributeViewPasteRows",+ "path": "/api/av/getAttributeViewSearchTarget",+ "handler": "getAttributeViewSearchTarget","authorization": ["authenticated",- "admin","writable"],"body": "json","request": {- "$ref": "#/$defs/GetAttributeViewPasteRowsRequestInput"+ "$ref": "#/$defs/GetAttributeViewSearchTargetRequestInput"},"response": {"anyOf": [@@ -131343,42 +132821,10 @@0]},- "data": {- "$ref": "#/$defs/AVPasteRowsData"- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],- "additionalProperties": false- },- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- -1- ]- },"data": {"anyOf": [{- "type": "object",- "properties": {- "closeTimeout": {- "type": "number"- }- },- "required": [- "closeTimeout"- ],- "additionalProperties": false+ "$ref": "#/$defs/AVAttributeViewSearchTarget"},{"type": "null"@@ -131394,47 +132840,6 @@"msg","data"],- "additionalProperties": true- }- ]- }- },- {- "method": "POST",- "path": "/api/av/getAttributeViewPrimaryKeyValues",- "handler": "getAttributeViewPrimaryKeyValues",- "authorization": [- "authenticated",- "admin",- "writable"- ],- "body": "json",- "request": {- "$ref": "#/$defs/GetAttributeViewPrimaryKeyValuesRequestInput"- },- "response": {- "anyOf": [- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- 0- ]- },- "data": {- "$ref": "#/$defs/AVPrimaryValuesData"- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],"additionalProperties": false},{@@ -131481,16 +132886,14 @@},{"method": "POST",- "path": "/api/av/getAttributeViewRelationCandidates",- "handler": "getAttributeViewRelationCandidates",+ "path": "/api/av/getCurrentAttrViewImages",+ "handler": "getCurrentAttrViewImages","authorization": [- "authenticated",- "admin",- "writable"+ "authenticated"],"body": "json","request": {- "$ref": "#/$defs/GetAttributeViewRelationCandidatesRequestInput"+ "$ref": "#/$defs/GetCurrentAttrViewImagesRequestInput"},"response": {"anyOf": [@@ -131504,7 +132907,17 @@]},"data": {- "$ref": "#/$defs/AVRelationCandidatesData"+ "anyOf": [+ {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -131561,15 +132974,16 @@},{"method": "POST",- "path": "/api/av/getAttributeViewRowSort",- "handler": "getAttributeViewRowSort",+ "path": "/api/av/getMirrorDatabaseBlocks",+ "handler": "getMirrorDatabaseBlocks","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],- "body": "structJSON",+ "body": "json","request": {- "$ref": "#/$defs/GetAttributeViewRowSortRequestInput"+ "$ref": "#/$defs/GetMirrorDatabaseBlocksRequestInput"},"response": {"anyOf": [@@ -131583,7 +132997,7 @@]},"data": {- "$ref": "#/$defs/AVRowSortPreview"+ "$ref": "#/$defs/RefDefsData"},"msg": {"type": "string"@@ -131640,15 +133054,15 @@},{"method": "POST",- "path": "/api/av/getAttributeViewSearchTarget",- "handler": "getAttributeViewSearchTarget",+ "path": "/api/av/getUnusedAttributeViews",+ "handler": "getUnusedAttributeViews","authorization": ["authenticated",- "writable"+ "admin"],- "body": "json",+ "body": "none","request": {- "$ref": "#/$defs/GetAttributeViewSearchTargetRequestInput"+ "$ref": "#/$defs/EmptyRequestInput"},"response": {"anyOf": [@@ -131664,7 +133078,17 @@"data": {"anyOf": [{- "$ref": "#/$defs/AVAttributeViewSearchTarget"+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/AssetUnusedItem"+ },+ {+ "type": "null"+ }+ ]+ }},{"type": "null"@@ -131726,14 +133150,15 @@},{"method": "POST",- "path": "/api/av/getCurrentAttrViewImages",- "handler": "getCurrentAttrViewImages",+ "path": "/api/av/previewAttributeViewCollection",+ "handler": "previewAttributeViewCollection","authorization": [- "authenticated"+ "authenticated",+ "admin"],- "body": "json",+ "body": "structJSON","request": {- "$ref": "#/$defs/GetCurrentAttrViewImagesRequestInput"+ "$ref": "#/$defs/AVBlockCollectionPreviewRequestInput"},"response": {"anyOf": [@@ -131749,10 +133174,7 @@"data": {"anyOf": [{- "type": "array",- "items": {- "type": "string"- }+ "$ref": "#/$defs/AVBlockCollectionPreview"},{"type": "null"@@ -131814,16 +133236,15 @@},{"method": "POST",- "path": "/api/av/getMirrorDatabaseBlocks",- "handler": "getMirrorDatabaseBlocks",+ "path": "/api/av/previewAttributeViewTemplate",+ "handler": "previewAttributeViewTemplate","authorization": ["authenticated",- "admin",- "writable"+ "admin"],- "body": "json",+ "body": "structJSON","request": {- "$ref": "#/$defs/GetMirrorDatabaseBlocksRequestInput"+ "$ref": "#/$defs/AVAutomationTemplatePreviewRequestInput"},"response": {"anyOf": [@@ -131837,7 +133258,14 @@]},"data": {- "$ref": "#/$defs/RefDefsData"+ "anyOf": [+ {+ "$ref": "#/$defs/AVValue"+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -131894,15 +133322,16 @@},{"method": "POST",- "path": "/api/av/getUnusedAttributeViews",- "handler": "getUnusedAttributeViews",+ "path": "/api/av/removeAttributeViewBlocks",+ "handler": "removeAttributeViewBlocks","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],- "body": "none",+ "body": "json","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/RemoveAttributeViewBlocksRequestInput"},"response": {"anyOf": [@@ -131916,24 +133345,7 @@]},"data": {- "anyOf": [- {- "type": "array",- "items": {- "anyOf": [- {- "$ref": "#/$defs/AssetUnusedItem"- },- {- "type": "null"- }- ]- }- },- {- "type": "null"- }- ]+ "type": "null"},"msg": {"type": "string"@@ -131990,15 +133402,16 @@},{"method": "POST",- "path": "/api/av/previewAttributeViewCollection",- "handler": "previewAttributeViewCollection",+ "path": "/api/av/removeAttributeViewKey",+ "handler": "removeAttributeViewKey","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],- "body": "structJSON",+ "body": "json","request": {- "$ref": "#/$defs/AVBlockCollectionPreviewRequestInput"+ "$ref": "#/$defs/RemoveAttributeViewKeyRequestInput"},"response": {"anyOf": [@@ -132012,14 +133425,7 @@]},"data": {- "anyOf": [- {- "$ref": "#/$defs/AVBlockCollectionPreview"- },- {- "type": "null"- }- ]+ "type": "null"},"msg": {"type": "string"@@ -132076,15 +133482,16 @@},{"method": "POST",- "path": "/api/av/previewAttributeViewTemplate",- "handler": "previewAttributeViewTemplate",+ "path": "/api/av/removeUnusedAttributeView",+ "handler": "removeUnusedAttributeView","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],- "body": "structJSON",+ "body": "json","request": {- "$ref": "#/$defs/AVAutomationTemplatePreviewRequestInput"+ "$ref": "#/$defs/RemoveUnusedAttributeViewRequestInput"},"response": {"anyOf": [@@ -132098,14 +133505,7 @@]},"data": {- "anyOf": [- {- "$ref": "#/$defs/AVValue"- },- {- "type": "null"- }- ]+ "$ref": "#/$defs/AVIDData"},"msg": {"type": "string"@@ -132162,16 +133562,16 @@},{"method": "POST",- "path": "/api/av/removeAttributeViewBlocks",- "handler": "removeAttributeViewBlocks",+ "path": "/api/av/removeUnusedAttributeViews",+ "handler": "removeUnusedAttributeViews","authorization": ["authenticated","admin","writable"],- "body": "json",+ "body": "none","request": {- "$ref": "#/$defs/RemoveAttributeViewBlocksRequestInput"+ "$ref": "#/$defs/EmptyRequestInput"},"response": {"anyOf": [@@ -132185,7 +133585,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/AVPathsData"},"msg": {"type": "string"@@ -132242,16 +133642,14 @@},{"method": "POST",- "path": "/api/av/removeAttributeViewKey",- "handler": "removeAttributeViewKey",+ "path": "/api/av/renderAttributeView",+ "handler": "renderAttributeView","authorization": [- "authenticated",- "admin",- "writable"+ "authenticated"],"body": "json","request": {- "$ref": "#/$defs/RemoveAttributeViewKeyRequestInput"+ "$ref": "#/$defs/RenderAttributeViewRequestInput"},"response": {"anyOf": [@@ -132265,7 +133663,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/AVRenderResult"},"msg": {"type": "string"@@ -132303,6 +133701,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/AVRenderResult"}]},@@ -132322,16 +133723,15 @@},{"method": "POST",- "path": "/api/av/removeUnusedAttributeView",- "handler": "removeUnusedAttributeView",+ "path": "/api/av/renderHistoryAttributeView",+ "handler": "renderHistoryAttributeView","authorization": ["authenticated",- "admin",- "writable"+ "admin"],"body": "json","request": {- "$ref": "#/$defs/RemoveUnusedAttributeViewRequestInput"+ "$ref": "#/$defs/RenderHistoryAttributeViewRequestInput"},"response": {"anyOf": [@@ -132345,7 +133745,7 @@]},"data": {- "$ref": "#/$defs/AVIDData"+ "$ref": "#/$defs/AVArchiveRenderData"},"msg": {"type": "string"@@ -132402,16 +133802,15 @@},{"method": "POST",- "path": "/api/av/removeUnusedAttributeViews",- "handler": "removeUnusedAttributeViews",+ "path": "/api/av/renderSnapshotAttributeView",+ "handler": "renderSnapshotAttributeView","authorization": ["authenticated",- "admin",- "writable"+ "admin"],- "body": "none",+ "body": "json","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/RenderSnapshotAttributeViewRequestInput"},"response": {"anyOf": [@@ -132425,7 +133824,7 @@]},"data": {- "$ref": "#/$defs/AVPathsData"+ "$ref": "#/$defs/AVArchiveRenderData"},"msg": {"type": "string"@@ -132482,14 +133881,15 @@},{"method": "POST",- "path": "/api/av/renderAttributeView",- "handler": "renderAttributeView",+ "path": "/api/av/reviewAttributeViewCollection",+ "handler": "reviewAttributeViewCollection","authorization": [- "authenticated"+ "authenticated",+ "admin"],- "body": "json",+ "body": "structJSON","request": {- "$ref": "#/$defs/RenderAttributeViewRequestInput"+ "$ref": "#/$defs/AVCollectionReviewRequestInput"},"response": {"anyOf": [@@ -132503,7 +133903,14 @@]},"data": {- "$ref": "#/$defs/AVRenderResult"+ "anyOf": [+ {+ "$ref": "#/$defs/AVCollectionReview"+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -132541,9 +133948,6 @@},{"type": "null"- },- {- "$ref": "#/$defs/AVRenderResult"}]},@@ -132563,15 +133967,15 @@},{"method": "POST",- "path": "/api/av/renderHistoryAttributeView",- "handler": "renderHistoryAttributeView",+ "path": "/api/av/searchAttributeView",+ "handler": "searchAttributeView","authorization": ["authenticated",- "admin"+ "writable"],"body": "json","request": {- "$ref": "#/$defs/RenderHistoryAttributeViewRequestInput"+ "$ref": "#/$defs/SearchAttributeViewRequestInput"},"response": {"anyOf": [@@ -132585,7 +133989,7 @@]},"data": {- "$ref": "#/$defs/AVArchiveRenderData"+ "$ref": "#/$defs/AVSearchData"},"msg": {"type": "string"@@ -132642,15 +134046,16 @@},{"method": "POST",- "path": "/api/av/renderSnapshotAttributeView",- "handler": "renderSnapshotAttributeView",+ "path": "/api/av/searchAttributeViewRelationKey",+ "handler": "searchAttributeViewRelationKey","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/RenderSnapshotAttributeViewRequestInput"+ "$ref": "#/$defs/SearchAttributeViewRelationKeyRequestInput"},"response": {"anyOf": [@@ -132664,7 +134069,7 @@]},"data": {- "$ref": "#/$defs/AVArchiveRenderData"+ "$ref": "#/$defs/AVKeysData"},"msg": {"type": "string"@@ -132721,15 +134126,16 @@},{"method": "POST",- "path": "/api/av/reviewAttributeViewCollection",- "handler": "reviewAttributeViewCollection",+ "path": "/api/av/searchAttributeViewRollupDestKeys",+ "handler": "searchAttributeViewRollupDestKeys","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],- "body": "structJSON",+ "body": "json","request": {- "$ref": "#/$defs/AVCollectionReviewRequestInput"+ "$ref": "#/$defs/SearchAttributeViewRollupDestKeysRequestInput"},"response": {"anyOf": [@@ -132743,14 +134149,7 @@]},"data": {- "anyOf": [- {- "$ref": "#/$defs/AVCollectionReview"- },- {- "type": "null"- }- ]+ "$ref": "#/$defs/AVKeysData"},"msg": {"type": "string"@@ -132807,15 +134206,16 @@},{"method": "POST",- "path": "/api/av/searchAttributeView",- "handler": "searchAttributeView",+ "path": "/api/av/setAttrViewContextFilter",+ "handler": "setAttrViewContextFilter","authorization": ["authenticated",+ "admin","writable"],"body": "json","request": {- "$ref": "#/$defs/SearchAttributeViewRequestInput"+ "$ref": "#/$defs/SetAttrViewContextFilterRequestInput"},"response": {"anyOf": [@@ -132829,7 +134229,7 @@]},"data": {- "$ref": "#/$defs/AVSearchData"+ "$ref": "#/$defs/AVContextFilterData"},"msg": {"type": "string"@@ -132886,8 +134286,8 @@},{"method": "POST",- "path": "/api/av/searchAttributeViewRelationKey",- "handler": "searchAttributeViewRelationKey",+ "path": "/api/av/setAttrViewFilters",+ "handler": "setAttrViewFilters","authorization": ["authenticated","admin",@@ -132895,7 +134295,7 @@],"body": "json","request": {- "$ref": "#/$defs/SearchAttributeViewRelationKeyRequestInput"+ "$ref": "#/$defs/SetAttrViewFiltersRequestInput"},"response": {"anyOf": [@@ -132909,7 +134309,7 @@]},"data": {- "$ref": "#/$defs/AVKeysData"+ "type": "null"},"msg": {"type": "string"@@ -132966,8 +134366,8 @@},{"method": "POST",- "path": "/api/av/searchAttributeViewRollupDestKeys",- "handler": "searchAttributeViewRollupDestKeys",+ "path": "/api/av/setAttrViewGroup",+ "handler": "setAttrViewGroup","authorization": ["authenticated","admin",@@ -132975,7 +134375,7 @@],"body": "json","request": {- "$ref": "#/$defs/SearchAttributeViewRollupDestKeysRequestInput"+ "$ref": "#/$defs/SetAttrViewGroupRequestInput"},"response": {"anyOf": [@@ -132989,7 +134389,7 @@]},"data": {- "$ref": "#/$defs/AVKeysData"+ "$ref": "#/$defs/AVRenderResult"},"msg": {"type": "string"@@ -133027,6 +134427,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/AVRenderResult"}]},@@ -133046,8 +134449,8 @@},{"method": "POST",- "path": "/api/av/setAttrViewContextFilter",- "handler": "setAttrViewContextFilter",+ "path": "/api/av/setAttrViewSorts",+ "handler": "setAttrViewSorts","authorization": ["authenticated","admin",@@ -133055,7 +134458,7 @@],"body": "json","request": {- "$ref": "#/$defs/SetAttrViewContextFilterRequestInput"+ "$ref": "#/$defs/SetAttrViewSortsRequestInput"},"response": {"anyOf": [@@ -133069,7 +134472,7 @@]},"data": {- "$ref": "#/$defs/AVContextFilterData"+ "type": "null"},"msg": {"type": "string"@@ -133126,8 +134529,8 @@},{"method": "POST",- "path": "/api/av/setAttrViewFilters",- "handler": "setAttrViewFilters",+ "path": "/api/av/setAttributeViewBlockAttr",+ "handler": "setAttributeViewBlockAttr","authorization": ["authenticated","admin",@@ -133135,7 +134538,7 @@],"body": "json","request": {- "$ref": "#/$defs/SetAttrViewFiltersRequestInput"+ "$ref": "#/$defs/SetAttributeViewBlockAttrRequestInput"},"response": {"anyOf": [@@ -133149,7 +134552,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/AVValueData"},"msg": {"type": "string"@@ -133206,8 +134609,8 @@},{"method": "POST",- "path": "/api/av/setAttrViewGroup",- "handler": "setAttrViewGroup",+ "path": "/api/av/setDatabaseBlockView",+ "handler": "setDatabaseBlockView","authorization": ["authenticated","admin",@@ -133215,7 +134618,7 @@],"body": "json","request": {- "$ref": "#/$defs/SetAttrViewGroupRequestInput"+ "$ref": "#/$defs/SetDatabaseBlockViewRequestInput"},"response": {"anyOf": [@@ -133229,7 +134632,7 @@]},"data": {- "$ref": "#/$defs/AVRenderResult"+ "type": "null"},"msg": {"type": "string"@@ -133267,9 +134670,6 @@},{"type": "null"- },- {- "$ref": "#/$defs/AVRenderResult"}]},@@ -133289,8 +134689,8 @@},{"method": "POST",- "path": "/api/av/setAttrViewSorts",- "handler": "setAttrViewSorts",+ "path": "/api/av/sortAttributeViewKey",+ "handler": "sortAttributeViewKey","authorization": ["authenticated","admin",@@ -133298,7 +134698,7 @@],"body": "json","request": {- "$ref": "#/$defs/SetAttrViewSortsRequestInput"+ "$ref": "#/$defs/SortAttributeViewKeyRequestInput"},"response": {"anyOf": [@@ -133369,8 +134769,8 @@},{"method": "POST",- "path": "/api/av/setAttributeViewBlockAttr",- "handler": "setAttributeViewBlockAttr",+ "path": "/api/av/sortAttributeViewViewKey",+ "handler": "sortAttributeViewViewKey","authorization": ["authenticated","admin",@@ -133378,7 +134778,7 @@],"body": "json","request": {- "$ref": "#/$defs/SetAttributeViewBlockAttrRequestInput"+ "$ref": "#/$defs/SortAttributeViewViewKeyRequestInput"},"response": {"anyOf": [@@ -133392,7 +134792,7 @@]},"data": {- "$ref": "#/$defs/AVValueData"+ "type": "null"},"msg": {"type": "string"@@ -133449,8 +134849,8 @@},{"method": "POST",- "path": "/api/av/setDatabaseBlockView",- "handler": "setDatabaseBlockView",+ "path": "/api/bazaar/batchUpdatePackage",+ "handler": "batchUpdatePackage","authorization": ["authenticated","admin",@@ -133458,7 +134858,7 @@],"body": "json","request": {- "$ref": "#/$defs/SetDatabaseBlockViewRequestInput"+ "$ref": "#/$defs/BatchUpdatePackageRequestInput"},"response": {"anyOf": [@@ -133491,7 +134891,8 @@"code": {"type": "integer","enum": [- -1+ -1,+ 1]},"data": {@@ -133529,16 +134930,15 @@},{"method": "POST",- "path": "/api/av/sortAttributeViewKey",- "handler": "sortAttributeViewKey",+ "path": "/api/bazaar/getBazaarIcon",+ "handler": "getBazaarIcon","authorization": ["authenticated",- "admin",- "writable"+ "admin"],"body": "json","request": {- "$ref": "#/$defs/SortAttributeViewKeyRequestInput"+ "$ref": "#/$defs/GetBazaarIconRequestInput"},"response": {"anyOf": [@@ -133552,7 +134952,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/BazaarPackagesData"},"msg": {"type": "string"@@ -133571,7 +134971,8 @@"code": {"type": "integer","enum": [- -1+ -1,+ 1]},"data": {@@ -133609,16 +135010,15 @@},{"method": "POST",- "path": "/api/av/sortAttributeViewViewKey",- "handler": "sortAttributeViewViewKey",+ "path": "/api/bazaar/getBazaarPackage",+ "handler": "getBazaarPackage","authorization": ["authenticated",- "admin",- "writable"+ "admin"],"body": "json","request": {- "$ref": "#/$defs/SortAttributeViewViewKeyRequestInput"+ "$ref": "#/$defs/GetBazaarPackageRequestInput"},"response": {"anyOf": [@@ -133632,7 +135032,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/BazaarPackageDetail"},"msg": {"type": "string"@@ -133651,7 +135051,8 @@"code": {"type": "integer","enum": [- -1+ -1,+ 1]},"data": {@@ -133689,16 +135090,15 @@},{"method": "POST",- "path": "/api/bazaar/batchUpdatePackage",- "handler": "batchUpdatePackage",+ "path": "/api/bazaar/getBazaarPackageREADME",+ "handler": "getBazaarPackageREADME","authorization": ["authenticated",- "admin",- "writable"+ "admin"],"body": "json","request": {- "$ref": "#/$defs/BatchUpdatePackageRequestInput"+ "$ref": "#/$defs/GetBazaarPackageREADMERequestInput"},"response": {"anyOf": [@@ -133712,7 +135112,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/BazaarREADMEData"},"msg": {"type": "string"@@ -133770,15 +135170,15 @@},{"method": "POST",- "path": "/api/bazaar/getBazaarIcon",- "handler": "getBazaarIcon",+ "path": "/api/bazaar/getBazaarPackageRating",+ "handler": "getBazaarPackageRating","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/GetBazaarIconRequestInput"+ "$ref": "#/$defs/GetBazaarPackageRatingRequestInput"},"response": {"anyOf": [@@ -133792,7 +135192,7 @@]},"data": {- "$ref": "#/$defs/BazaarPackagesData"+ "$ref": "#/$defs/BazaarRatingResult"},"msg": {"type": "string"@@ -133831,6 +135231,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/BazaarRatingResult"}]},@@ -133850,15 +135253,15 @@},{"method": "POST",- "path": "/api/bazaar/getBazaarPackage",- "handler": "getBazaarPackage",+ "path": "/api/bazaar/getBazaarPackageRatings",+ "handler": "getBazaarPackageRatings","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/GetBazaarPackageRequestInput"+ "$ref": "#/$defs/GetBazaarPackageRatingsRequestInput"},"response": {"anyOf": [@@ -133872,7 +135275,7 @@]},"data": {- "$ref": "#/$defs/BazaarPackageDetail"+ "$ref": "#/$defs/BazaarRatingsData"},"msg": {"type": "string"@@ -133930,15 +135333,15 @@},{"method": "POST",- "path": "/api/bazaar/getBazaarPackageREADME",- "handler": "getBazaarPackageREADME",+ "path": "/api/bazaar/getBazaarPackageUserRatings",+ "handler": "getBazaarPackageUserRatings","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/GetBazaarPackageREADMERequestInput"+ "$ref": "#/$defs/GetBazaarPackageUserRatingsRequestInput"},"response": {"anyOf": [@@ -133952,7 +135355,7 @@]},"data": {- "$ref": "#/$defs/BazaarREADMEData"+ "$ref": "#/$defs/BazaarUserRatingsResult"},"msg": {"type": "string"@@ -133991,6 +135394,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/BazaarUserRatingsResult"}]},@@ -134010,15 +135416,15 @@},{"method": "POST",- "path": "/api/bazaar/getBazaarPackageRating",- "handler": "getBazaarPackageRating",+ "path": "/api/bazaar/getBazaarPlugin",+ "handler": "getBazaarPlugin","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/GetBazaarPackageRatingRequestInput"+ "$ref": "#/$defs/GetBazaarPluginRequestInput"},"response": {"anyOf": [@@ -134032,7 +135438,7 @@]},"data": {- "$ref": "#/$defs/BazaarRatingResult"+ "$ref": "#/$defs/BazaarPackagesData"},"msg": {"type": "string"@@ -134071,9 +135477,6 @@},{"type": "null"- },- {- "$ref": "#/$defs/BazaarRatingResult"}]},@@ -134093,15 +135496,15 @@},{"method": "POST",- "path": "/api/bazaar/getBazaarPackageRatings",- "handler": "getBazaarPackageRatings",+ "path": "/api/bazaar/getBazaarTemplate",+ "handler": "getBazaarTemplate","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/GetBazaarPackageRatingsRequestInput"+ "$ref": "#/$defs/GetBazaarTemplateRequestInput"},"response": {"anyOf": [@@ -134115,7 +135518,7 @@]},"data": {- "$ref": "#/$defs/BazaarRatingsData"+ "$ref": "#/$defs/BazaarPackagesData"},"msg": {"type": "string"@@ -134173,15 +135576,15 @@},{"method": "POST",- "path": "/api/bazaar/getBazaarPackageUserRatings",- "handler": "getBazaarPackageUserRatings",+ "path": "/api/bazaar/getBazaarTheme",+ "handler": "getBazaarTheme","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/GetBazaarPackageUserRatingsRequestInput"+ "$ref": "#/$defs/GetBazaarThemeRequestInput"},"response": {"anyOf": [@@ -134195,7 +135598,7 @@]},"data": {- "$ref": "#/$defs/BazaarUserRatingsResult"+ "$ref": "#/$defs/BazaarPackagesData"},"msg": {"type": "string"@@ -134234,9 +135637,6 @@},{"type": "null"- },- {- "$ref": "#/$defs/BazaarUserRatingsResult"}]},@@ -134256,15 +135656,15 @@},{"method": "POST",- "path": "/api/bazaar/getBazaarPlugin",- "handler": "getBazaarPlugin",+ "path": "/api/bazaar/getBazaarWidget",+ "handler": "getBazaarWidget","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/GetBazaarPluginRequestInput"+ "$ref": "#/$defs/GetBazaarWidgetRequestInput"},"response": {"anyOf": [@@ -134336,15 +135736,15 @@},{"method": "POST",- "path": "/api/bazaar/getBazaarTemplate",- "handler": "getBazaarTemplate",+ "path": "/api/bazaar/getInstalledIcon",+ "handler": "getInstalledIcon","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/GetBazaarTemplateRequestInput"+ "$ref": "#/$defs/GetInstalledIconRequestInput"},"response": {"anyOf": [@@ -134416,15 +135816,15 @@},{"method": "POST",- "path": "/api/bazaar/getBazaarTheme",- "handler": "getBazaarTheme",+ "path": "/api/bazaar/getInstalledPackageSize",+ "handler": "getInstalledPackageSize","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/GetBazaarThemeRequestInput"+ "$ref": "#/$defs/GetInstalledPackageSizeRequestInput"},"response": {"anyOf": [@@ -134438,7 +135838,7 @@]},"data": {- "$ref": "#/$defs/BazaarPackagesData"+ "$ref": "#/$defs/BazaarPackageSizeData"},"msg": {"type": "string"@@ -134496,15 +135896,15 @@},{"method": "POST",- "path": "/api/bazaar/getBazaarWidget",- "handler": "getBazaarWidget",+ "path": "/api/bazaar/getInstalledPlugin",+ "handler": "getInstalledPlugin","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/GetBazaarWidgetRequestInput"+ "$ref": "#/$defs/GetInstalledPluginRequestInput"},"response": {"anyOf": [@@ -134576,15 +135976,15 @@},{"method": "POST",- "path": "/api/bazaar/getInstalledIcon",- "handler": "getInstalledIcon",+ "path": "/api/bazaar/getInstalledTemplate",+ "handler": "getInstalledTemplate","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/GetInstalledIconRequestInput"+ "$ref": "#/$defs/GetInstalledTemplateRequestInput"},"response": {"anyOf": [@@ -134656,15 +136056,15 @@},{"method": "POST",- "path": "/api/bazaar/getInstalledPackageSize",- "handler": "getInstalledPackageSize",+ "path": "/api/bazaar/getInstalledTheme",+ "handler": "getInstalledTheme","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/GetInstalledPackageSizeRequestInput"+ "$ref": "#/$defs/GetInstalledThemeRequestInput"},"response": {"anyOf": [@@ -134678,7 +136078,7 @@]},"data": {- "$ref": "#/$defs/BazaarPackageSizeData"+ "$ref": "#/$defs/BazaarPackagesData"},"msg": {"type": "string"@@ -134736,15 +136136,15 @@},{"method": "POST",- "path": "/api/bazaar/getInstalledPlugin",- "handler": "getInstalledPlugin",+ "path": "/api/bazaar/getInstalledWidget",+ "handler": "getInstalledWidget","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/GetInstalledPluginRequestInput"+ "$ref": "#/$defs/GetInstalledWidgetRequestInput"},"response": {"anyOf": [@@ -134816,15 +136216,15 @@},{"method": "POST",- "path": "/api/bazaar/getInstalledTemplate",- "handler": "getInstalledTemplate",+ "path": "/api/bazaar/getUpdatedPackage",+ "handler": "getUpdatedPackage","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/GetInstalledTemplateRequestInput"+ "$ref": "#/$defs/GetUpdatedPackageRequestInput"},"response": {"anyOf": [@@ -134838,7 +136238,7 @@]},"data": {- "$ref": "#/$defs/BazaarPackagesData"+ "$ref": "#/$defs/BazaarUpdatedData"},"msg": {"type": "string"@@ -134896,15 +136296,16 @@},{"method": "POST",- "path": "/api/bazaar/getInstalledTheme",- "handler": "getInstalledTheme",+ "path": "/api/bazaar/installBazaarIcon",+ "handler": "installBazaarIcon","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/GetInstalledThemeRequestInput"+ "$ref": "#/$defs/InstallBazaarIconRequestInput"},"response": {"anyOf": [@@ -134918,7 +136319,7 @@]},"data": {- "$ref": "#/$defs/BazaarPackagesData"+ "$ref": "#/$defs/BazaarAppearancePackagesData"},"msg": {"type": "string"@@ -134976,15 +136377,16 @@},{"method": "POST",- "path": "/api/bazaar/getInstalledWidget",- "handler": "getInstalledWidget",+ "path": "/api/bazaar/installBazaarPlugin",+ "handler": "installBazaarPlugin","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/GetInstalledWidgetRequestInput"+ "$ref": "#/$defs/InstallBazaarPluginRequestInput"},"response": {"anyOf": [@@ -135056,15 +136458,16 @@},{"method": "POST",- "path": "/api/bazaar/getUpdatedPackage",- "handler": "getUpdatedPackage",+ "path": "/api/bazaar/installBazaarTemplate",+ "handler": "installBazaarTemplate","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/GetUpdatedPackageRequestInput"+ "$ref": "#/$defs/InstallBazaarTemplateRequestInput"},"response": {"anyOf": [@@ -135078,7 +136481,7 @@]},"data": {- "$ref": "#/$defs/BazaarUpdatedData"+ "$ref": "#/$defs/BazaarPackagesData"},"msg": {"type": "string"@@ -135136,8 +136539,8 @@},{"method": "POST",- "path": "/api/bazaar/installBazaarIcon",- "handler": "installBazaarIcon",+ "path": "/api/bazaar/installBazaarTheme",+ "handler": "installBazaarTheme","authorization": ["authenticated","admin",@@ -135145,7 +136548,7 @@],"body": "json","request": {- "$ref": "#/$defs/InstallBazaarIconRequestInput"+ "$ref": "#/$defs/InstallBazaarThemeRequestInput"},"response": {"anyOf": [@@ -135217,8 +136620,8 @@},{"method": "POST",- "path": "/api/bazaar/installBazaarPlugin",- "handler": "installBazaarPlugin",+ "path": "/api/bazaar/installBazaarWidget",+ "handler": "installBazaarWidget","authorization": ["authenticated","admin",@@ -135226,7 +136629,7 @@],"body": "json","request": {- "$ref": "#/$defs/InstallBazaarPluginRequestInput"+ "$ref": "#/$defs/InstallBazaarWidgetRequestInput"},"response": {"anyOf": [@@ -135298,16 +136701,16 @@},{"method": "POST",- "path": "/api/bazaar/installBazaarTemplate",- "handler": "installBazaarTemplate",+ "path": "/api/bazaar/installLocalBazaarPackage",+ "handler": "installLocalBazaarPackage","authorization": ["authenticated","admin","writable"],- "body": "json",+ "body": "multipart","request": {- "$ref": "#/$defs/InstallBazaarTemplateRequestInput"+ "$ref": "#/$defs/InstallLocalBazaarPackageRequestInput"},"response": {"anyOf": [@@ -135321,7 +136724,7 @@]},"data": {- "$ref": "#/$defs/BazaarPackagesData"+ "$ref": "#/$defs/BazaarLocalInstallResult"},"msg": {"type": "string"@@ -135360,6 +136763,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/BazaarLocalInstallResult"}]},@@ -135379,16 +136785,15 @@},{"method": "POST",- "path": "/api/bazaar/installBazaarTheme",- "handler": "installBazaarTheme",+ "path": "/api/bazaar/setBazaarPackageRating",+ "handler": "setBazaarPackageRating","authorization": ["authenticated",- "admin",- "writable"+ "admin"],"body": "json","request": {- "$ref": "#/$defs/InstallBazaarThemeRequestInput"+ "$ref": "#/$defs/SetBazaarPackageRatingRequestInput"},"response": {"anyOf": [@@ -135402,7 +136807,7 @@]},"data": {- "$ref": "#/$defs/BazaarAppearancePackagesData"+ "$ref": "#/$defs/BazaarRatingResult"},"msg": {"type": "string"@@ -135441,6 +136846,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/BazaarRatingResult"}]},@@ -135460,8 +136868,8 @@},{"method": "POST",- "path": "/api/bazaar/installBazaarWidget",- "handler": "installBazaarWidget",+ "path": "/api/bazaar/uninstallBazaarIcon",+ "handler": "uninstallBazaarIcon","authorization": ["authenticated","admin",@@ -135469,7 +136877,7 @@],"body": "json","request": {- "$ref": "#/$defs/InstallBazaarWidgetRequestInput"+ "$ref": "#/$defs/UninstallBazaarIconRequestInput"},"response": {"anyOf": [@@ -135483,7 +136891,7 @@]},"data": {- "$ref": "#/$defs/BazaarPackagesData"+ "$ref": "#/$defs/BazaarAppearancePackagesData"},"msg": {"type": "string"@@ -135541,16 +136949,16 @@},{"method": "POST",- "path": "/api/bazaar/installLocalBazaarPackage",- "handler": "installLocalBazaarPackage",+ "path": "/api/bazaar/uninstallBazaarPlugin",+ "handler": "uninstallBazaarPlugin","authorization": ["authenticated","admin","writable"],- "body": "multipart",+ "body": "json","request": {- "$ref": "#/$defs/InstallLocalBazaarPackageRequestInput"+ "$ref": "#/$defs/UninstallBazaarPluginRequestInput"},"response": {"anyOf": [@@ -135564,7 +136972,7 @@]},"data": {- "$ref": "#/$defs/BazaarLocalInstallResult"+ "$ref": "#/$defs/BazaarPackagesData"},"msg": {"type": "string"@@ -135603,9 +137011,6 @@},{"type": "null"- },- {- "$ref": "#/$defs/BazaarLocalInstallResult"}]},@@ -135625,15 +137030,16 @@},{"method": "POST",- "path": "/api/bazaar/setBazaarPackageRating",- "handler": "setBazaarPackageRating",+ "path": "/api/bazaar/uninstallBazaarTemplate",+ "handler": "uninstallBazaarTemplate","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/SetBazaarPackageRatingRequestInput"+ "$ref": "#/$defs/UninstallBazaarTemplateRequestInput"},"response": {"anyOf": [@@ -135647,7 +137053,7 @@]},"data": {- "$ref": "#/$defs/BazaarRatingResult"+ "$ref": "#/$defs/BazaarPackagesData"},"msg": {"type": "string"@@ -135686,9 +137092,6 @@},{"type": "null"- },- {- "$ref": "#/$defs/BazaarRatingResult"}]},@@ -135708,8 +137111,8 @@},{"method": "POST",- "path": "/api/bazaar/uninstallBazaarIcon",- "handler": "uninstallBazaarIcon",+ "path": "/api/bazaar/uninstallBazaarTheme",+ "handler": "uninstallBazaarTheme","authorization": ["authenticated","admin",@@ -135717,7 +137120,7 @@],"body": "json","request": {- "$ref": "#/$defs/UninstallBazaarIconRequestInput"+ "$ref": "#/$defs/UninstallBazaarThemeRequestInput"},"response": {"anyOf": [@@ -135789,8 +137192,8 @@},{"method": "POST",- "path": "/api/bazaar/uninstallBazaarPlugin",- "handler": "uninstallBazaarPlugin",+ "path": "/api/bazaar/uninstallBazaarWidget",+ "handler": "uninstallBazaarWidget","authorization": ["authenticated","admin",@@ -135798,7 +137201,7 @@],"body": "json","request": {- "$ref": "#/$defs/UninstallBazaarPluginRequestInput"+ "$ref": "#/$defs/UninstallBazaarWidgetRequestInput"},"response": {"anyOf": [@@ -135870,8 +137273,8 @@},{"method": "POST",- "path": "/api/bazaar/uninstallBazaarTemplate",- "handler": "uninstallBazaarTemplate",+ "path": "/api/bazaar/updateBazaarPackage",+ "handler": "updateBazaarPackage","authorization": ["authenticated","admin",@@ -135879,7 +137282,7 @@],"body": "json","request": {- "$ref": "#/$defs/UninstallBazaarTemplateRequestInput"+ "$ref": "#/$defs/UpdateBazaarPackageRequestInput"},"response": {"anyOf": [@@ -135951,89 +137354,8 @@},{"method": "POST",- "path": "/api/bazaar/uninstallBazaarTheme",- "handler": "uninstallBazaarTheme",- "authorization": [- "authenticated",- "admin",- "writable"- ],- "body": "json",- "request": {- "$ref": "#/$defs/UninstallBazaarThemeRequestInput"- },- "response": {- "anyOf": [- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- 0- ]- },- "data": {- "$ref": "#/$defs/BazaarAppearancePackagesData"- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],- "additionalProperties": false- },- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- -1,- 1- ]- },- "data": {- "anyOf": [- {- "type": "object",- "properties": {- "closeTimeout": {- "type": "number"- }- },- "required": [- "closeTimeout"- ],- "additionalProperties": false- },- {- "type": "null"- }- ]- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],- "additionalProperties": true- }- ]- }- },- {- "method": "POST",- "path": "/api/bazaar/uninstallBazaarWidget",- "handler": "uninstallBazaarWidget",+ "path": "/api/block/appendBlock",+ "handler": "appendBlock","authorization": ["authenticated","admin",@@ -136041,7 +137363,7 @@],"body": "json","request": {- "$ref": "#/$defs/UninstallBazaarWidgetRequestInput"+ "$ref": "#/$defs/AppendBlockRequestInput"},"response": {"anyOf": [@@ -136054,43 +137376,20 @@0]},- "data": {- "$ref": "#/$defs/BazaarPackagesData"- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],- "additionalProperties": false- },- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- -1,- 1- ]- },"data": {"anyOf": [{- "type": "object",- "properties": {- "closeTimeout": {- "type": "number"- }- },- "required": [- "closeTimeout"- ],- "additionalProperties": false+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/BlockTransaction"+ },+ {+ "type": "null"+ }+ ]+ }},{"type": "null"@@ -136106,47 +137405,6 @@"msg","data"],- "additionalProperties": true- }- ]- }- },- {- "method": "POST",- "path": "/api/bazaar/updateBazaarPackage",- "handler": "updateBazaarPackage",- "authorization": [- "authenticated",- "admin",- "writable"- ],- "body": "json",- "request": {- "$ref": "#/$defs/UpdateBazaarPackageRequestInput"- },- "response": {- "anyOf": [- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- 0- ]- },- "data": {- "$ref": "#/$defs/BazaarPackagesData"- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],"additionalProperties": false},{@@ -136155,8 +137413,7 @@"code": {"type": "integer","enum": [- -1,- 1+ -1]},"data": {@@ -136194,8 +137451,8 @@},{"method": "POST",- "path": "/api/block/appendBlock",- "handler": "appendBlock",+ "path": "/api/block/appendDailyNoteBlock",+ "handler": "appendDailyNoteBlock","authorization": ["authenticated","admin",@@ -136203,7 +137460,7 @@],"body": "json","request": {- "$ref": "#/$defs/AppendBlockRequestInput"+ "$ref": "#/$defs/DailyNoteBlockRequestInput"},"response": {"anyOf": [@@ -136291,8 +137548,8 @@},{"method": "POST",- "path": "/api/block/appendDailyNoteBlock",- "handler": "appendDailyNoteBlock",+ "path": "/api/block/appendHeadingChildren",+ "handler": "appendHeadingChildren","authorization": ["authenticated","admin",@@ -136300,7 +137557,7 @@],"body": "json","request": {- "$ref": "#/$defs/DailyNoteBlockRequestInput"+ "$ref": "#/$defs/AppendHeadingChildrenRequestInput"},"response": {"anyOf": [@@ -136314,24 +137571,7 @@]},"data": {- "anyOf": [- {- "type": "array",- "items": {- "anyOf": [- {- "$ref": "#/$defs/BlockTransaction"- },- {- "type": "null"- }- ]- }- },- {- "type": "null"- }- ]+ "type": "null"},"msg": {"type": "string"@@ -136388,8 +137628,8 @@},{"method": "POST",- "path": "/api/block/appendHeadingChildren",- "handler": "appendHeadingChildren",+ "path": "/api/block/batchAppendBlock",+ "handler": "batchAppendBlock","authorization": ["authenticated","admin",@@ -136397,7 +137637,7 @@],"body": "json","request": {- "$ref": "#/$defs/AppendHeadingChildrenRequestInput"+ "$ref": "#/$defs/BatchParentBlockRequestInput"},"response": {"anyOf": [@@ -136411,7 +137651,24 @@]},"data": {- "type": "null"+ "anyOf": [+ {+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/BlockTransaction"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -136468,8 +137725,8 @@},{"method": "POST",- "path": "/api/block/batchAppendBlock",- "handler": "batchAppendBlock",+ "path": "/api/block/batchInsertBlock",+ "handler": "batchInsertBlock","authorization": ["authenticated","admin",@@ -136477,7 +137734,7 @@],"body": "json","request": {- "$ref": "#/$defs/BatchParentBlockRequestInput"+ "$ref": "#/$defs/BatchInsertBlockRequestInput"},"response": {"anyOf": [@@ -136565,8 +137822,8 @@},{"method": "POST",- "path": "/api/block/batchInsertBlock",- "handler": "batchInsertBlock",+ "path": "/api/block/batchPrependBlock",+ "handler": "batchPrependBlock","authorization": ["authenticated","admin",@@ -136574,7 +137831,7 @@],"body": "json","request": {- "$ref": "#/$defs/BatchInsertBlockRequestInput"+ "$ref": "#/$defs/BatchParentBlockRequestInput"},"response": {"anyOf": [@@ -136662,8 +137919,8 @@},{"method": "POST",- "path": "/api/block/batchPrependBlock",- "handler": "batchPrependBlock",+ "path": "/api/block/batchUpdateBlock",+ "handler": "batchUpdateBlock","authorization": ["authenticated","admin",@@ -136671,7 +137928,7 @@],"body": "json","request": {- "$ref": "#/$defs/BatchParentBlockRequestInput"+ "$ref": "#/$defs/BatchUpdateBlockRequestInput"},"response": {"anyOf": [@@ -136759,8 +138016,8 @@},{"method": "POST",- "path": "/api/block/batchUpdateBlock",- "handler": "batchUpdateBlock",+ "path": "/api/block/batchUpdateTaskListItemMarker",+ "handler": "batchUpdateTaskListItemMarker","authorization": ["authenticated","admin",@@ -136768,7 +138025,7 @@],"body": "json","request": {- "$ref": "#/$defs/BatchUpdateBlockRequestInput"+ "$ref": "#/$defs/BatchTaskListMarkerRequestInput"},"response": {"anyOf": [@@ -136856,16 +138113,14 @@},{"method": "POST",- "path": "/api/block/batchUpdateTaskListItemMarker",- "handler": "batchUpdateTaskListItemMarker",+ "path": "/api/block/checkBlockExist",+ "handler": "checkBlockExist","authorization": [- "authenticated",- "admin",- "writable"+ "authenticated"],"body": "json","request": {- "$ref": "#/$defs/BatchTaskListMarkerRequestInput"+ "$ref": "#/$defs/BlockQueryRequestInput"},"response": {"anyOf": [@@ -136878,20 +138133,42 @@0]},+ "data": {+ "type": "boolean"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },"data": {"anyOf": [{- "type": "array",- "items": {- "anyOf": [- {- "$ref": "#/$defs/BlockTransaction"- },- {- "type": "null"- }- ]- }+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false},{"type": "null"@@ -136907,6 +138184,45 @@"msg","data"],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/block/checkBlockFold",+ "handler": "checkBlockFold",+ "authorization": [+ "authenticated"+ ],+ "body": "json",+ "request": {+ "$ref": "#/$defs/BlockQueryRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "$ref": "#/$defs/BlockFoldData"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],"additionalProperties": false},{@@ -136953,14 +138269,16 @@},{"method": "POST",- "path": "/api/block/checkBlockExist",- "handler": "checkBlockExist",+ "path": "/api/block/checkBlockRef",+ "handler": "checkBlockRef","authorization": [- "authenticated"+ "authenticated",+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/BlockQueryRequestInput"+ "$ref": "#/$defs/CheckBlockRefRequestInput"},"response": {"anyOf": [@@ -137012,6 +138330,9 @@},{"type": "null"+ },+ {+ "type": "boolean"}]},@@ -137031,14 +138352,14 @@},{"method": "POST",- "path": "/api/block/checkBlockFold",- "handler": "checkBlockFold",+ "path": "/api/block/checkBlocksExist",+ "handler": "checkBlocksExist","authorization": ["authenticated"],"body": "json","request": {- "$ref": "#/$defs/BlockQueryRequestInput"+ "$ref": "#/$defs/CheckBlocksExistRequestInput"},"response": {"anyOf": [@@ -137052,7 +138373,17 @@]},"data": {- "$ref": "#/$defs/BlockFoldData"+ "anyOf": [+ {+ "type": "object",+ "additionalProperties": {+ "type": "boolean"+ }+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -137109,8 +138440,8 @@},{"method": "POST",- "path": "/api/block/checkBlockRef",- "handler": "checkBlockRef",+ "path": "/api/block/deleteBlock",+ "handler": "deleteBlock","authorization": ["authenticated","admin",@@ -137118,7 +138449,7 @@],"body": "json","request": {- "$ref": "#/$defs/CheckBlockRefRequestInput"+ "$ref": "#/$defs/DeleteBlockRequestInput"},"response": {"anyOf": [@@ -137132,7 +138463,24 @@]},"data": {- "type": "boolean"+ "anyOf": [+ {+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/BlockTransaction"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -137170,9 +138518,86 @@},{"type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/block/foldBlock",+ "handler": "foldBlock",+ "authorization": [+ "authenticated",+ "admin",+ "writable"+ ],+ "body": "json",+ "request": {+ "$ref": "#/$defs/BlockIDRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "null"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false},{- "type": "boolean"+ "type": "null"}]},@@ -137192,14 +138617,14 @@},{"method": "POST",- "path": "/api/block/checkBlocksExist",- "handler": "checkBlocksExist",+ "path": "/api/block/getBlockBreadcrumb",+ "handler": "getBlockBreadcrumb","authorization": ["authenticated"],"body": "json","request": {- "$ref": "#/$defs/CheckBlocksExistRequestInput"+ "$ref": "#/$defs/BlockBreadcrumbRequestInput"},"response": {"anyOf": [@@ -137215,9 +138640,16 @@"data": {"anyOf": [{- "type": "object",- "additionalProperties": {- "type": "boolean"+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/BlockPath"+ },+ {+ "type": "null"+ }+ ]}},{@@ -137280,16 +138712,14 @@},{"method": "POST",- "path": "/api/block/deleteBlock",- "handler": "deleteBlock",+ "path": "/api/block/getBlockBreadcrumbChildren",+ "handler": "getBlockBreadcrumbChildren","authorization": [- "authenticated",- "admin",- "writable"+ "authenticated"],"body": "json","request": {- "$ref": "#/$defs/DeleteBlockRequestInput"+ "$ref": "#/$defs/BlockBreadcrumbChildrenRequestInput"},"response": {"anyOf": [@@ -137305,17 +138735,7 @@"data": {"anyOf": [{- "type": "array",- "items": {- "anyOf": [- {- "$ref": "#/$defs/BlockTransaction"- },- {- "type": "null"- }- ]- }+ "$ref": "#/$defs/BlockBreadcrumbChildren"},{"type": "null"@@ -137377,16 +138797,14 @@},{"method": "POST",- "path": "/api/block/foldBlock",- "handler": "foldBlock",+ "path": "/api/block/getBlockDOM",+ "handler": "getBlockDOM","authorization": [- "authenticated",- "admin",- "writable"+ "authenticated"],"body": "json","request": {- "$ref": "#/$defs/BlockIDRequestInput"+ "$ref": "#/$defs/BlockQueryRequestInput"},"response": {"anyOf": [@@ -137400,7 +138818,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/BlockDOMData"},"msg": {"type": "string"@@ -137457,14 +138875,14 @@},{"method": "POST",- "path": "/api/block/getBlockBreadcrumb",- "handler": "getBlockBreadcrumb",+ "path": "/api/block/getBlockDOMWithEmbed",+ "handler": "getBlockDOMWithEmbed","authorization": ["authenticated"],"body": "json","request": {- "$ref": "#/$defs/BlockBreadcrumbRequestInput"+ "$ref": "#/$defs/BlockQueryRequestInput"},"response": {"anyOf": [@@ -137477,19 +138895,90 @@0]},+ "data": {+ "$ref": "#/$defs/BlockDOMData"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },"data": {"anyOf": [{- "type": "array",- "items": {- "anyOf": [- {- "$ref": "#/$defs/BlockPath"- },- {- "type": "null"- }- ]+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/block/getBlockDOMs",+ "handler": "getBlockDOMs",+ "authorization": [+ "authenticated"+ ],+ "body": "json",+ "request": {+ "$ref": "#/$defs/BlocksQueryRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "additionalProperties": {+ "type": "string"}},{@@ -137552,14 +139041,14 @@},{"method": "POST",- "path": "/api/block/getBlockBreadcrumbChildren",- "handler": "getBlockBreadcrumbChildren",+ "path": "/api/block/getBlockDOMsWithEmbed",+ "handler": "getBlockDOMsWithEmbed","authorization": ["authenticated"],"body": "json","request": {- "$ref": "#/$defs/BlockBreadcrumbChildrenRequestInput"+ "$ref": "#/$defs/BlocksQueryRequestInput"},"response": {"anyOf": [@@ -137575,7 +139064,10 @@"data": {"anyOf": [{- "$ref": "#/$defs/BlockBreadcrumbChildren"+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }},{"type": "null"@@ -137637,14 +139129,14 @@},{"method": "POST",- "path": "/api/block/getBlockDOM",- "handler": "getBlockDOM",+ "path": "/api/block/getBlockDefIDsByRefText",+ "handler": "getBlockDefIDsByRefText","authorization": ["authenticated"],"body": "json","request": {- "$ref": "#/$defs/BlockQueryRequestInput"+ "$ref": "#/$defs/RefTextQueryRequestInput"},"response": {"anyOf": [@@ -137658,7 +139150,7 @@]},"data": {- "$ref": "#/$defs/BlockDOMData"+ "$ref": "#/$defs/RefDefsData"},"msg": {"type": "string"@@ -137715,8 +139207,8 @@},{"method": "POST",- "path": "/api/block/getBlockDOMWithEmbed",- "handler": "getBlockDOMWithEmbed",+ "path": "/api/block/getBlockIndex",+ "handler": "getBlockIndex","authorization": ["authenticated"],@@ -137736,7 +139228,7 @@]},"data": {- "$ref": "#/$defs/BlockDOMData"+ "type": "integer"},"msg": {"type": "string"@@ -137793,14 +139285,14 @@},{"method": "POST",- "path": "/api/block/getBlockDOMs",- "handler": "getBlockDOMs",+ "path": "/api/block/getBlockInfo",+ "handler": "getBlockInfo","authorization": ["authenticated"],"body": "json","request": {- "$ref": "#/$defs/BlocksQueryRequestInput"+ "$ref": "#/$defs/BlockInfoRequestInput"},"response": {"anyOf": [@@ -137813,16 +139305,49 @@0]},+ "data": {+ "$ref": "#/$defs/BlockInfoData"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1,+ 3+ ]+ },"data": {"anyOf": [{"type": "object",- "additionalProperties": {- "type": "string"- }+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false},{"type": "null"+ },+ {+ "type": "string"}]},@@ -137835,6 +139360,45 @@"msg","data"],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/block/getBlockKramdown",+ "handler": "getBlockKramdown",+ "authorization": [+ "authenticated"+ ],+ "body": "json",+ "request": {+ "$ref": "#/$defs/BlockKramdownRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "$ref": "#/$defs/BlockKramdownData"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],"additionalProperties": false},{@@ -137881,14 +139445,14 @@},{"method": "POST",- "path": "/api/block/getBlockDOMsWithEmbed",- "handler": "getBlockDOMsWithEmbed",+ "path": "/api/block/getBlockKramdowns",+ "handler": "getBlockKramdowns","authorization": ["authenticated"],"body": "json","request": {- "$ref": "#/$defs/BlocksQueryRequestInput"+ "$ref": "#/$defs/BlocksKramdownRequestInput"},"response": {"anyOf": [@@ -137969,14 +139533,14 @@},{"method": "POST",- "path": "/api/block/getBlockDefIDsByRefText",- "handler": "getBlockDefIDsByRefText",+ "path": "/api/block/getBlockRelevantIDs",+ "handler": "getBlockRelevantIDs","authorization": ["authenticated"],"body": "json","request": {- "$ref": "#/$defs/RefTextQueryRequestInput"+ "$ref": "#/$defs/BlockQueryRequestInput"},"response": {"anyOf": [@@ -137990,7 +139554,7 @@]},"data": {- "$ref": "#/$defs/RefDefsData"+ "$ref": "#/$defs/BlockRelevantData"},"msg": {"type": "string"@@ -138047,8 +139611,8 @@},{"method": "POST",- "path": "/api/block/getBlockIndex",- "handler": "getBlockIndex",+ "path": "/api/block/getBlockSiblingID",+ "handler": "getBlockSiblingID","authorization": ["authenticated"],@@ -138068,7 +139632,7 @@]},"data": {- "type": "integer"+ "$ref": "#/$defs/BlockSiblingData"},"msg": {"type": "string"@@ -138125,14 +139689,14 @@},{"method": "POST",- "path": "/api/block/getBlockInfo",- "handler": "getBlockInfo",+ "path": "/api/block/getBlockTreeInfos",+ "handler": "getBlockTreeInfos","authorization": ["authenticated"],"body": "json","request": {- "$ref": "#/$defs/BlockInfoRequestInput"+ "$ref": "#/$defs/BlocksQueryRequestInput"},"response": {"anyOf": [@@ -138145,49 +139709,23 @@0]},- "data": {- "$ref": "#/$defs/BlockInfoData"- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],- "additionalProperties": false- },- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- -1,- 3- ]- },"data": {"anyOf": [{"type": "object",- "properties": {- "closeTimeout": {- "type": "number"- }- },- "required": [- "closeTimeout"- ],- "additionalProperties": false+ "additionalProperties": {+ "anyOf": [+ {+ "$ref": "#/$defs/BlockTreeInfo"+ },+ {+ "type": "null"+ }+ ]+ }},{"type": "null"- },- {- "type": "string"}]},@@ -138200,45 +139738,6 @@"msg","data"],- "additionalProperties": true- }- ]- }- },- {- "method": "POST",- "path": "/api/block/getBlockKramdown",- "handler": "getBlockKramdown",- "authorization": [- "authenticated"- ],- "body": "json",- "request": {- "$ref": "#/$defs/BlockKramdownRequestInput"- },- "response": {- "anyOf": [- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- 0- ]- },- "data": {- "$ref": "#/$defs/BlockKramdownData"- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],"additionalProperties": false},{@@ -138285,14 +139784,14 @@},{"method": "POST",- "path": "/api/block/getBlockKramdowns",- "handler": "getBlockKramdowns",+ "path": "/api/block/getBlocksIndexes",+ "handler": "getBlocksIndexes","authorization": ["authenticated"],"body": "json","request": {- "$ref": "#/$defs/BlocksKramdownRequestInput"+ "$ref": "#/$defs/BlocksQueryRequestInput"},"response": {"anyOf": [@@ -138310,7 +139809,7 @@{"type": "object","additionalProperties": {- "type": "string"+ "type": "integer"}},{@@ -138373,14 +139872,14 @@},{"method": "POST",- "path": "/api/block/getBlockRelevantIDs",- "handler": "getBlockRelevantIDs",+ "path": "/api/block/getBlocksWordCount",+ "handler": "getBlocksWordCount","authorization": ["authenticated"],"body": "json","request": {- "$ref": "#/$defs/BlockQueryRequestInput"+ "$ref": "#/$defs/BlocksWordCountRequestInput"},"response": {"anyOf": [@@ -138394,7 +139893,7 @@]},"data": {- "$ref": "#/$defs/BlockRelevantData"+ "$ref": "#/$defs/WordCountData"},"msg": {"type": "string"@@ -138451,10 +139950,11 @@},{"method": "POST",- "path": "/api/block/getBlockSiblingID",- "handler": "getBlockSiblingID",+ "path": "/api/block/getChildBlocks",+ "handler": "getChildBlocks","authorization": [- "authenticated"+ "authenticated",+ "admin"],"body": "json","request": {@@ -138472,7 +139972,17 @@]},"data": {- "$ref": "#/$defs/BlockSiblingData"+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/ChildBlock"+ },+ {+ "type": "null"+ }+ ]+ }},"msg": {"type": "string"@@ -138529,14 +140039,14 @@},{"method": "POST",- "path": "/api/block/getBlockTreeInfos",- "handler": "getBlockTreeInfos",+ "path": "/api/block/getContentWordCount",+ "handler": "getContentWordCount","authorization": ["authenticated"],"body": "json","request": {- "$ref": "#/$defs/BlocksQueryRequestInput"+ "$ref": "#/$defs/ContentWordCountRequestInput"},"response": {"anyOf": [@@ -138550,24 +140060,7 @@]},"data": {- "anyOf": [- {- "type": "object",- "additionalProperties": {- "anyOf": [- {- "$ref": "#/$defs/BlockTreeInfo"- },- {- "type": "null"- }- ]- }- },- {- "type": "null"- }- ]+ "$ref": "#/$defs/WordCountData"},"msg": {"type": "string"@@ -138624,14 +140117,14 @@},{"method": "POST",- "path": "/api/block/getBlocksIndexes",- "handler": "getBlocksIndexes",+ "path": "/api/block/getDOMText",+ "handler": "getDOMText","authorization": ["authenticated"],"body": "json","request": {- "$ref": "#/$defs/BlocksQueryRequestInput"+ "$ref": "#/$defs/DOMTextRequestInput"},"response": {"anyOf": [@@ -138645,17 +140138,7 @@]},"data": {- "anyOf": [- {- "type": "object",- "additionalProperties": {- "type": "integer"- }- },- {- "type": "null"- }- ]+ "type": "string"},"msg": {"type": "string"@@ -138712,14 +140195,14 @@},{"method": "POST",- "path": "/api/block/getBlocksWordCount",- "handler": "getBlocksWordCount",+ "path": "/api/block/getDocBlocksOrders",+ "handler": "getDocBlocksOrders","authorization": ["authenticated"],"body": "json","request": {- "$ref": "#/$defs/BlocksWordCountRequestInput"+ "$ref": "#/$defs/DocOrdersRequestInput"},"response": {"anyOf": [@@ -138733,7 +140216,17 @@]},"data": {- "$ref": "#/$defs/WordCountData"+ "anyOf": [+ {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -138790,15 +140283,16 @@},{"method": "POST",- "path": "/api/block/getChildBlocks",- "handler": "getChildBlocks",+ "path": "/api/block/getDocHeadingLevelTransaction",+ "handler": "getDocHeadingLevelTransaction","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],- "body": "json",+ "body": "structJSON","request": {- "$ref": "#/$defs/BlockQueryRequestInput"+ "$ref": "#/$defs/DocHeadingLevelRequestInput"},"response": {"anyOf": [@@ -138812,17 +140306,14 @@]},"data": {- "type": "array",- "items": {- "anyOf": [- {- "$ref": "#/$defs/ChildBlock"- },- {- "type": "null"- }- ]- }+ "anyOf": [+ {+ "$ref": "#/$defs/DocHeadingLevelData"+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -138879,14 +140370,14 @@},{"method": "POST",- "path": "/api/block/getContentWordCount",- "handler": "getContentWordCount",+ "path": "/api/block/getDocInfo",+ "handler": "getDocInfo","authorization": ["authenticated"],"body": "json","request": {- "$ref": "#/$defs/ContentWordCountRequestInput"+ "$ref": "#/$defs/BlockQueryRequestInput"},"response": {"anyOf": [@@ -138900,7 +140391,14 @@]},"data": {- "$ref": "#/$defs/WordCountData"+ "anyOf": [+ {+ "$ref": "#/$defs/DocInfo"+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -138957,14 +140455,14 @@},{"method": "POST",- "path": "/api/block/getDOMText",- "handler": "getDOMText",+ "path": "/api/block/getDocsInfo",+ "handler": "getDocsInfo","authorization": ["authenticated"],"body": "json","request": {- "$ref": "#/$defs/DOMTextRequestInput"+ "$ref": "#/$defs/DocsInfoRequestInput"},"response": {"anyOf": [@@ -138978,7 +140476,24 @@]},"data": {- "type": "string"+ "anyOf": [+ {+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/DocInfo"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -139035,14 +140550,14 @@},{"method": "POST",- "path": "/api/block/getDocBlocksOrders",- "handler": "getDocBlocksOrders",+ "path": "/api/block/getHeadingChildrenDOM",+ "handler": "getHeadingChildrenDOM","authorization": ["authenticated"],"body": "json","request": {- "$ref": "#/$defs/DocOrdersRequestInput"+ "$ref": "#/$defs/HeadingChildrenRequestInput"},"response": {"anyOf": [@@ -139056,17 +140571,7 @@]},"data": {- "anyOf": [- {- "type": "array",- "items": {- "type": "string"- }- },- {- "type": "null"- }- ]+ "type": "string"},"msg": {"type": "string"@@ -139123,16 +140628,14 @@},{"method": "POST",- "path": "/api/block/getDocHeadingLevelTransaction",- "handler": "getDocHeadingLevelTransaction",+ "path": "/api/block/getHeadingChildrenIDs",+ "handler": "getHeadingChildrenIDs","authorization": [- "authenticated",- "admin",- "writable"+ "authenticated"],- "body": "structJSON",+ "body": "json","request": {- "$ref": "#/$defs/DocHeadingLevelRequestInput"+ "$ref": "#/$defs/BlockIDRequestInput"},"response": {"anyOf": [@@ -139148,7 +140651,10 @@"data": {"anyOf": [{- "$ref": "#/$defs/DocHeadingLevelData"+ "type": "array",+ "items": {+ "type": "string"+ }},{"type": "null"@@ -139210,14 +140716,15 @@},{"method": "POST",- "path": "/api/block/getDocInfo",- "handler": "getDocInfo",+ "path": "/api/block/getHeadingDeleteTransaction",+ "handler": "getHeadingDeleteTransaction","authorization": [- "authenticated"+ "authenticated",+ "admin"],"body": "json","request": {- "$ref": "#/$defs/BlockQueryRequestInput"+ "$ref": "#/$defs/BlockIDRequestInput"},"response": {"anyOf": [@@ -139233,7 +140740,7 @@"data": {"anyOf": [{- "$ref": "#/$defs/DocInfo"+ "$ref": "#/$defs/BlockTransaction"},{"type": "null"@@ -139295,14 +140802,15 @@},{"method": "POST",- "path": "/api/block/getDocsInfo",- "handler": "getDocsInfo",+ "path": "/api/block/getHeadingFoldTransaction",+ "handler": "getHeadingFoldTransaction","authorization": [- "authenticated"+ "authenticated",+ "admin"],"body": "json","request": {- "$ref": "#/$defs/DocsInfoRequestInput"+ "$ref": "#/$defs/HeadingFoldRequestInput"},"response": {"anyOf": [@@ -139318,17 +140826,7 @@"data": {"anyOf": [{- "type": "array",- "items": {- "anyOf": [- {- "$ref": "#/$defs/DocInfo"- },- {- "type": "null"- }- ]- }+ "$ref": "#/$defs/BlockTransaction"},{"type": "null"@@ -139390,88 +140888,11 @@},{"method": "POST",- "path": "/api/block/getHeadingChildrenDOM",- "handler": "getHeadingChildrenDOM",- "authorization": [- "authenticated"- ],- "body": "json",- "request": {- "$ref": "#/$defs/HeadingChildrenRequestInput"- },- "response": {- "anyOf": [- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- 0- ]- },- "data": {- "type": "string"- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],- "additionalProperties": false- },- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- -1- ]- },- "data": {- "anyOf": [- {- "type": "object",- "properties": {- "closeTimeout": {- "type": "number"- }- },- "required": [- "closeTimeout"- ],- "additionalProperties": false- },- {- "type": "null"- }- ]- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],- "additionalProperties": true- }- ]- }- },- {- "method": "POST",- "path": "/api/block/getHeadingChildrenIDs",- "handler": "getHeadingChildrenIDs",+ "path": "/api/block/getHeadingInsertTransaction",+ "handler": "getHeadingInsertTransaction","authorization": [- "authenticated"+ "authenticated",+ "admin"],"body": "json","request": {@@ -139491,10 +140912,7 @@"data": {"anyOf": [{- "type": "array",- "items": {- "type": "string"- }+ "$ref": "#/$defs/BlockTransaction"},{"type": "null"@@ -139556,15 +140974,15 @@},{"method": "POST",- "path": "/api/block/getHeadingDeleteTransaction",- "handler": "getHeadingDeleteTransaction",+ "path": "/api/block/getHeadingLevelTransaction",+ "handler": "getHeadingLevelTransaction","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/BlockIDRequestInput"+ "$ref": "#/$defs/HeadingLevelRequestInput"},"response": {"anyOf": [@@ -139642,15 +141060,15 @@},{"method": "POST",- "path": "/api/block/getHeadingFoldTransaction",- "handler": "getHeadingFoldTransaction",+ "path": "/api/block/getOrderedListContinueStart",+ "handler": "getOrderedListContinueStart","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/HeadingFoldRequestInput"+ "$ref": "#/$defs/BlockQueryRequestInput"},"response": {"anyOf": [@@ -139664,14 +141082,7 @@]},"data": {- "anyOf": [- {- "$ref": "#/$defs/BlockTransaction"- },- {- "type": "null"- }- ]+ "$ref": "#/$defs/OrderedListStartData"},"msg": {"type": "string"@@ -139728,15 +141139,14 @@},{"method": "POST",- "path": "/api/block/getHeadingInsertTransaction",- "handler": "getHeadingInsertTransaction",+ "path": "/api/block/getRecentUpdatedBlocks",+ "handler": "getRecentUpdatedBlocks","authorization": [- "authenticated",- "admin"+ "authenticated"],- "body": "json",+ "body": "none","request": {- "$ref": "#/$defs/BlockIDRequestInput"+ "$ref": "#/$defs/EmptyRequestInput"},"response": {"anyOf": [@@ -139752,7 +141162,17 @@"data": {"anyOf": [{- "$ref": "#/$defs/BlockTransaction"+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/SearchBlock"+ },+ {+ "type": "null"+ }+ ]+ }},{"type": "null"@@ -139814,15 +141234,14 @@},{"method": "POST",- "path": "/api/block/getHeadingLevelTransaction",- "handler": "getHeadingLevelTransaction",+ "path": "/api/block/getRefIDs",+ "handler": "getRefIDs","authorization": [- "authenticated",- "admin"+ "authenticated"],"body": "json","request": {- "$ref": "#/$defs/HeadingLevelRequestInput"+ "$ref": "#/$defs/RefIDsRequestInput"},"response": {"anyOf": [@@ -139836,14 +141255,7 @@]},"data": {- "anyOf": [- {- "$ref": "#/$defs/BlockTransaction"- },- {- "type": "null"- }- ]+ "$ref": "#/$defs/RefIDsData"},"msg": {"type": "string"@@ -139900,15 +141312,14 @@},{"method": "POST",- "path": "/api/block/getOrderedListContinueStart",- "handler": "getOrderedListContinueStart",+ "path": "/api/block/getRefIDsByFileAnnotationID",+ "handler": "getRefIDsByFileAnnotationID","authorization": [- "authenticated",- "admin"+ "authenticated"],"body": "json","request": {- "$ref": "#/$defs/BlockQueryRequestInput"+ "$ref": "#/$defs/FileAnnotationRefRequestInput"},"response": {"anyOf": [@@ -139922,7 +141333,7 @@]},"data": {- "$ref": "#/$defs/OrderedListStartData"+ "$ref": "#/$defs/RefDefsData"},"msg": {"type": "string"@@ -139979,14 +141390,14 @@},{"method": "POST",- "path": "/api/block/getRecentUpdatedBlocks",- "handler": "getRecentUpdatedBlocks",+ "path": "/api/block/getRefText",+ "handler": "getRefText","authorization": ["authenticated"],- "body": "none",+ "body": "json","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/BlockQueryRequestInput"},"response": {"anyOf": [@@ -140000,24 +141411,7 @@]},"data": {- "anyOf": [- {- "type": "array",- "items": {- "anyOf": [- {- "$ref": "#/$defs/SearchBlock"- },- {- "type": "null"- }- ]- }- },- {- "type": "null"- }- ]+ "type": "string"},"msg": {"type": "string"@@ -140074,14 +141468,15 @@},{"method": "POST",- "path": "/api/block/getRefIDs",- "handler": "getRefIDs",+ "path": "/api/block/getTailChildBlocks",+ "handler": "getTailChildBlocks","authorization": [- "authenticated"+ "authenticated",+ "admin"],"body": "json","request": {- "$ref": "#/$defs/RefIDsRequestInput"+ "$ref": "#/$defs/TailChildBlocksRequestInput"},"response": {"anyOf": [@@ -140095,7 +141490,17 @@]},"data": {- "$ref": "#/$defs/RefIDsData"+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/ChildBlock"+ },+ {+ "type": "null"+ }+ ]+ }},"msg": {"type": "string"@@ -140152,14 +141557,14 @@},{"method": "POST",- "path": "/api/block/getRefIDsByFileAnnotationID",- "handler": "getRefIDsByFileAnnotationID",+ "path": "/api/block/getTreeStat",+ "handler": "getTreeStat","authorization": ["authenticated"],"body": "json","request": {- "$ref": "#/$defs/FileAnnotationRefRequestInput"+ "$ref": "#/$defs/TreeStatRequestInput"},"response": {"anyOf": [@@ -140173,7 +141578,7 @@]},"data": {- "$ref": "#/$defs/RefDefsData"+ "$ref": "#/$defs/TreeStatData"},"msg": {"type": "string"@@ -140230,8 +141635,8 @@},{"method": "POST",- "path": "/api/block/getRefText",- "handler": "getRefText",+ "path": "/api/block/getUnfoldedParentID",+ "handler": "getUnfoldedParentID","authorization": ["authenticated"],@@ -140251,7 +141656,7 @@]},"data": {- "type": "string"+ "$ref": "#/$defs/UnfoldedParentData"},"msg": {"type": "string"@@ -140308,15 +141713,16 @@},{"method": "POST",- "path": "/api/block/getTailChildBlocks",- "handler": "getTailChildBlocks",+ "path": "/api/block/insertBlock",+ "handler": "insertBlock","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/TailChildBlocksRequestInput"+ "$ref": "#/$defs/InsertBlockRequestInput"},"response": {"anyOf": [@@ -140330,17 +141736,24 @@]},"data": {- "type": "array",- "items": {- "anyOf": [- {- "$ref": "#/$defs/ChildBlock"- },- {- "type": "null"+ "anyOf": [+ {+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/BlockTransaction"+ },+ {+ "type": "null"+ }+ ]}- ]- }+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -140397,14 +141810,16 @@},{"method": "POST",- "path": "/api/block/getTreeStat",- "handler": "getTreeStat",+ "path": "/api/block/migrateLegacyMindmaps",+ "handler": "migrateLegacyMindmaps","authorization": [- "authenticated"+ "authenticated",+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/TreeStatRequestInput"+ "$ref": "#/$defs/MigrateLegacyMindmapsRequestInput"},"response": {"anyOf": [@@ -140418,7 +141833,7 @@]},"data": {- "$ref": "#/$defs/TreeStatData"+ "$ref": "#/$defs/MigrateLegacyMindmapsData"},"msg": {"type": "string"@@ -140475,14 +141890,16 @@},{"method": "POST",- "path": "/api/block/getUnfoldedParentID",- "handler": "getUnfoldedParentID",+ "path": "/api/block/moveBlock",+ "handler": "moveBlock","authorization": [- "authenticated"+ "authenticated",+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/BlockQueryRequestInput"+ "$ref": "#/$defs/MoveBlockRequestInput"},"response": {"anyOf": [@@ -140496,7 +141913,7 @@]},"data": {- "$ref": "#/$defs/UnfoldedParentData"+ "type": "null"},"msg": {"type": "string"@@ -140553,8 +141970,8 @@},{"method": "POST",- "path": "/api/block/insertBlock",- "handler": "insertBlock",+ "path": "/api/block/moveOutlineHeading",+ "handler": "moveOutlineHeading","authorization": ["authenticated","admin",@@ -140562,7 +141979,7 @@],"body": "json","request": {- "$ref": "#/$defs/InsertBlockRequestInput"+ "$ref": "#/$defs/MoveBlockRequestInput"},"response": {"anyOf": [@@ -140650,168 +142067,8 @@},{"method": "POST",- "path": "/api/block/migrateLegacyMindmaps",- "handler": "migrateLegacyMindmaps",- "authorization": [- "authenticated",- "admin",- "writable"- ],- "body": "json",- "request": {- "$ref": "#/$defs/MigrateLegacyMindmapsRequestInput"- },- "response": {- "anyOf": [- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- 0- ]- },- "data": {- "$ref": "#/$defs/MigrateLegacyMindmapsData"- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],- "additionalProperties": false- },- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- -1- ]- },- "data": {- "anyOf": [- {- "type": "object",- "properties": {- "closeTimeout": {- "type": "number"- }- },- "required": [- "closeTimeout"- ],- "additionalProperties": false- },- {- "type": "null"- }- ]- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],- "additionalProperties": true- }- ]- }- },- {- "method": "POST",- "path": "/api/block/moveBlock",- "handler": "moveBlock",- "authorization": [- "authenticated",- "admin",- "writable"- ],- "body": "json",- "request": {- "$ref": "#/$defs/MoveBlockRequestInput"- },- "response": {- "anyOf": [- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- 0- ]- },- "data": {- "type": "null"- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],- "additionalProperties": false- },- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- -1- ]- },- "data": {- "anyOf": [- {- "type": "object",- "properties": {- "closeTimeout": {- "type": "number"- }- },- "required": [- "closeTimeout"- ],- "additionalProperties": false- },- {- "type": "null"- }- ]- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],- "additionalProperties": true- }- ]- }- },- {- "method": "POST",- "path": "/api/block/moveOutlineHeading",- "handler": "moveOutlineHeading",+ "path": "/api/block/prependBlock",+ "handler": "prependBlock","authorization": ["authenticated","admin",@@ -140819,7 +142076,7 @@],"body": "json","request": {- "$ref": "#/$defs/MoveBlockRequestInput"+ "$ref": "#/$defs/PrependBlockRequestInput"},"response": {"anyOf": [@@ -140907,8 +142164,8 @@},{"method": "POST",- "path": "/api/block/prependBlock",- "handler": "prependBlock",+ "path": "/api/block/prependDailyNoteBlock",+ "handler": "prependDailyNoteBlock","authorization": ["authenticated","admin",@@ -140916,7 +142173,7 @@],"body": "json","request": {- "$ref": "#/$defs/PrependBlockRequestInput"+ "$ref": "#/$defs/DailyNoteBlockRequestInput"},"response": {"anyOf": [@@ -141004,8 +142261,8 @@},{"method": "POST",- "path": "/api/block/prependDailyNoteBlock",- "handler": "prependDailyNoteBlock",+ "path": "/api/block/setBlockReminder",+ "handler": "setBlockReminder","authorization": ["authenticated","admin",@@ -141013,7 +142270,7 @@],"body": "json","request": {- "$ref": "#/$defs/DailyNoteBlockRequestInput"+ "$ref": "#/$defs/BlockReminderRequestInput"},"response": {"anyOf": [@@ -141027,24 +142284,7 @@]},"data": {- "anyOf": [- {- "type": "array",- "items": {- "anyOf": [- {- "$ref": "#/$defs/BlockTransaction"- },- {- "type": "null"- }- ]- }- },- {- "type": "null"- }- ]+ "type": "null"},"msg": {"type": "string"@@ -141101,8 +142341,8 @@},{"method": "POST",- "path": "/api/block/setBlockReminder",- "handler": "setBlockReminder",+ "path": "/api/block/swapBlockRef",+ "handler": "swapBlockRef","authorization": ["authenticated","admin",@@ -141110,7 +142350,7 @@],"body": "json","request": {- "$ref": "#/$defs/BlockReminderRequestInput"+ "$ref": "#/$defs/SwapBlockRefRequestInput"},"response": {"anyOf": [@@ -141181,8 +142421,8 @@},{"method": "POST",- "path": "/api/block/swapBlockRef",- "handler": "swapBlockRef",+ "path": "/api/block/transferBlockRef",+ "handler": "transferBlockRef","authorization": ["authenticated","admin",@@ -141190,7 +142430,7 @@],"body": "json","request": {- "$ref": "#/$defs/SwapBlockRefRequestInput"+ "$ref": "#/$defs/TransferBlockRefRequestInput"},"response": {"anyOf": [@@ -141261,8 +142501,8 @@},{"method": "POST",- "path": "/api/block/transferBlockRef",- "handler": "transferBlockRef",+ "path": "/api/block/unfoldBlock",+ "handler": "unfoldBlock","authorization": ["authenticated","admin",@@ -141270,7 +142510,7 @@],"body": "json","request": {- "$ref": "#/$defs/TransferBlockRefRequestInput"+ "$ref": "#/$defs/BlockIDRequestInput"},"response": {"anyOf": [@@ -141341,8 +142581,8 @@},{"method": "POST",- "path": "/api/block/unfoldBlock",- "handler": "unfoldBlock",+ "path": "/api/block/updateBlock",+ "handler": "updateBlock","authorization": ["authenticated","admin",@@ -141350,7 +142590,7 @@],"body": "json","request": {- "$ref": "#/$defs/BlockIDRequestInput"+ "$ref": "#/$defs/UpdateBlockRequestInput"},"response": {"anyOf": [@@ -141364,7 +142604,24 @@]},"data": {- "type": "null"+ "anyOf": [+ {+ "type": "array",+ "items": {+ "anyOf": [+ {+ "$ref": "#/$defs/BlockTransaction"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -141421,8 +142678,8 @@},{"method": "POST",- "path": "/api/block/updateBlock",- "handler": "updateBlock",+ "path": "/api/block/updateTaskListItemMarker",+ "handler": "updateTaskListItemMarker","authorization": ["authenticated","admin",@@ -141430,7 +142687,7 @@],"body": "json","request": {- "$ref": "#/$defs/UpdateBlockRequestInput"+ "$ref": "#/$defs/TaskListMarkerRequestInput"},"response": {"anyOf": [@@ -141518,16 +142775,14 @@},{"method": "POST",- "path": "/api/block/updateTaskListItemMarker",- "handler": "updateTaskListItemMarker",+ "path": "/api/bookmark/getBookmark",+ "handler": "getBookmark","authorization": [- "authenticated",- "admin",- "writable"+ "authenticated"],- "body": "json",+ "body": "none","request": {- "$ref": "#/$defs/TaskListMarkerRequestInput"+ "$ref": "#/$defs/EmptyRequestInput"},"response": {"anyOf": [@@ -141547,7 +142802,7 @@"items": {"anyOf": [{- "$ref": "#/$defs/BlockTransaction"+ "$ref": "#/$defs/Bookmark"},{"type": "null"@@ -141615,14 +142870,175 @@},{"method": "POST",- "path": "/api/bookmark/getBookmark",- "handler": "getBookmark",+ "path": "/api/bookmark/removeBookmark",+ "handler": "removeBookmark",+ "authorization": [+ "authenticated",+ "admin",+ "writable"+ ],+ "body": "json",+ "request": {+ "$ref": "#/$defs/RemoveBookmarkRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "null"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/bookmark/renameBookmark",+ "handler": "renameBookmark",+ "authorization": [+ "authenticated",+ "admin",+ "writable"+ ],+ "body": "json",+ "request": {+ "$ref": "#/$defs/RenameBookmarkRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "null"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },+ {+ "method": "POST",+ "path": "/api/broadcast/getChannelInfo",+ "handler": "getChannelInfo","authorization": [- "authenticated"+ "authenticated",+ "admin"],- "body": "none",+ "body": "json","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/BroadcastChannelRequestInput"},"response": {"anyOf": [@@ -141636,24 +143052,7 @@]},"data": {- "anyOf": [- {- "type": "array",- "items": {- "anyOf": [- {- "$ref": "#/$defs/Bookmark"- },- {- "type": "null"- }- ]- }- },- {- "type": "null"- }- ]+ "$ref": "#/$defs/BroadcastChannelData"},"msg": {"type": "string"@@ -141710,16 +143109,15 @@},{"method": "POST",- "path": "/api/bookmark/removeBookmark",- "handler": "removeBookmark",+ "path": "/api/broadcast/getChannels",+ "handler": "getChannels","authorization": ["authenticated",- "admin",- "writable"+ "admin"],- "body": "json",+ "body": "none","request": {- "$ref": "#/$defs/RemoveBookmarkRequestInput"+ "$ref": "#/$defs/EmptyRequestInput"},"response": {"anyOf": [@@ -141733,7 +143131,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/BroadcastChannelsData"},"msg": {"type": "string"@@ -141790,16 +143188,15 @@},{"method": "POST",- "path": "/api/bookmark/renameBookmark",- "handler": "renameBookmark",+ "path": "/api/broadcast/postMessage",+ "handler": "postMessage","authorization": ["authenticated",- "admin",- "writable"+ "admin"],"body": "json","request": {- "$ref": "#/$defs/RenameBookmarkRequestInput"+ "$ref": "#/$defs/BroadcastMessageRequestInput"},"response": {"anyOf": [@@ -141813,7 +143210,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/BroadcastChannelData"},"msg": {"type": "string"@@ -141832,7 +143229,8 @@"code": {"type": "integer","enum": [- -1+ -1,+ 1]},"data": {@@ -141870,15 +143268,29 @@},{"method": "POST",- "path": "/api/broadcast/getChannelInfo",- "handler": "getChannelInfo",+ "path": "/api/broadcast/publish",+ "handler": "broadcastPublish","authorization": ["authenticated","admin"],- "body": "json",+ "body": "multipart","request": {- "$ref": "#/$defs/BroadcastChannelRequestInput"+ "type": "object",+ "additionalProperties": {+ "type": "array",+ "items": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "string",+ "format": "binary"+ }+ ]+ }+ }},"response": {"anyOf": [@@ -141892,7 +143304,7 @@]},"data": {- "$ref": "#/$defs/BroadcastChannelData"+ "$ref": "#/$defs/BroadcastPublishData"},"msg": {"type": "string"@@ -141911,7 +143323,8 @@"code": {"type": "integer","enum": [- -1+ -1,+ 1]},"data": {@@ -141949,15 +143362,15 @@},{"method": "POST",- "path": "/api/broadcast/getChannels",- "handler": "getChannels",+ "path": "/api/clipboard/cleanupRichText",+ "handler": "cleanupRichText","authorization": ["authenticated","admin"],- "body": "none",+ "body": "json","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/CleanupRichTextRequestInput"},"response": {"anyOf": [@@ -141971,7 +143384,7 @@]},"data": {- "$ref": "#/$defs/BroadcastChannelsData"+ "type": "null"},"msg": {"type": "string"@@ -142028,15 +143441,16 @@},{"method": "POST",- "path": "/api/broadcast/postMessage",- "handler": "postMessage",+ "path": "/api/clipboard/preparePasteAssets",+ "handler": "preparePasteAssets","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/BroadcastMessageRequestInput"+ "$ref": "#/$defs/PreparePasteAssetsRequestInput"},"response": {"anyOf": [@@ -142050,7 +143464,10 @@]},"data": {- "$ref": "#/$defs/BroadcastChannelData"+ "type": "object",+ "additionalProperties": {+ "type": "string"+ }},"msg": {"type": "string"@@ -142069,8 +143486,7 @@"code": {"type": "integer","enum": [- -1,- 1+ -1]},"data": {@@ -142108,29 +143524,15 @@},{"method": "POST",- "path": "/api/broadcast/publish",- "handler": "broadcastPublish",+ "path": "/api/clipboard/prepareRichText",+ "handler": "prepareRichText","authorization": ["authenticated","admin"],- "body": "multipart",+ "body": "json","request": {- "type": "object",- "additionalProperties": {- "type": "array",- "items": {- "anyOf": [- {- "type": "string"- },- {- "type": "string",- "format": "binary"- }- ]- }- }+ "$ref": "#/$defs/PrepareRichTextRequestInput"},"response": {"anyOf": [@@ -142143,43 +143545,10 @@0]},- "data": {- "$ref": "#/$defs/BroadcastPublishData"- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],- "additionalProperties": false- },- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- -1,- 1- ]- },"data": {"anyOf": [{- "type": "object",- "properties": {- "closeTimeout": {- "type": "number"- }- },- "required": [- "closeTimeout"- ],- "additionalProperties": false+ "$ref": "#/$defs/RichClipboardPrepared"},{"type": "null"@@ -142195,46 +143564,6 @@"msg","data"],- "additionalProperties": true- }- ]- }- },- {- "method": "POST",- "path": "/api/clipboard/cleanupRichText",- "handler": "cleanupRichText",- "authorization": [- "authenticated",- "admin"- ],- "body": "json",- "request": {- "$ref": "#/$defs/CleanupRichTextRequestInput"- },- "response": {- "anyOf": [- {- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- 0- ]- },- "data": {- "type": "null"- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],"additionalProperties": false},{@@ -142281,16 +143610,15 @@},{"method": "POST",- "path": "/api/clipboard/preparePasteAssets",- "handler": "preparePasteAssets",+ "path": "/api/clipboard/readFilePaths",+ "handler": "readFilePaths","authorization": ["authenticated",- "admin",- "writable"+ "admin"],- "body": "json",+ "body": "none","request": {- "$ref": "#/$defs/PreparePasteAssetsRequestInput"+ "$ref": "#/$defs/EmptyRequestInput"},"response": {"anyOf": [@@ -142304,9 +143632,9 @@]},"data": {- "type": "object",- "additionalProperties": {- "type": "string"+ "type": "array",+ "items": {+ "$ref": "#/$defs/ClipboardFile"}},"msg": {@@ -142364,15 +143692,15 @@},{"method": "POST",- "path": "/api/clipboard/prepareRichText",- "handler": "prepareRichText",+ "path": "/api/clipboard/writeFilePath",+ "handler": "writeFilePath","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/PrepareRichTextRequestInput"+ "$ref": "#/$defs/ClipboardPathRequestInput"},"response": {"anyOf": [@@ -142386,14 +143714,7 @@]},"data": {- "anyOf": [- {- "$ref": "#/$defs/RichClipboardPrepared"- },- {- "type": "null"- }- ]+ "type": "null"},"msg": {"type": "string"@@ -142450,8 +143771,8 @@},{"method": "POST",- "path": "/api/clipboard/readFilePaths",- "handler": "readFilePaths",+ "path": "/api/cloud/getCloudSpace",+ "handler": "getCloudSpace","authorization": ["authenticated","admin"@@ -142472,10 +143793,7 @@]},"data": {- "type": "array",- "items": {- "$ref": "#/$defs/ClipboardFile"- }+ "$ref": "#/$defs/CloudSpaceData"},"msg": {"type": "string"@@ -142494,7 +143812,8 @@"code": {"type": "integer","enum": [- -1+ -1,+ 1]},"data": {@@ -142532,15 +143851,16 @@},{"method": "POST",- "path": "/api/clipboard/writeFilePath",- "handler": "writeFilePath",+ "path": "/api/cloud/setCloudReminder",+ "handler": "setCloudReminder","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/ClipboardPathRequestInput"+ "$ref": "#/$defs/CloudReminderRequestInput"},"response": {"anyOf": [@@ -142611,15 +143931,16 @@},{"method": "POST",- "path": "/api/cloud/getCloudSpace",- "handler": "getCloudSpace",+ "path": "/api/convert/pandoc",+ "handler": "pandoc","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],- "body": "none",+ "body": "json","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/PandocRequestInput"},"response": {"anyOf": [@@ -142633,7 +143954,7 @@]},"data": {- "$ref": "#/$defs/CloudSpaceData"+ "$ref": "#/$defs/PandocData"},"msg": {"type": "string"@@ -142652,8 +143973,7 @@"code": {"type": "integer","enum": [- -1,- 1+ -1]},"data": {@@ -142691,8 +144011,8 @@},{"method": "POST",- "path": "/api/cloud/setCloudReminder",- "handler": "setCloudReminder",+ "path": "/api/export/copyExportFile",+ "handler": "copyExportFile","authorization": ["authenticated","admin",@@ -142700,7 +144020,7 @@],"body": "json","request": {- "$ref": "#/$defs/CloudReminderRequestInput"+ "$ref": "#/$defs/CopyExportFileRequestInput"},"response": {"anyOf": [@@ -142733,7 +144053,8 @@"code": {"type": "integer","enum": [- -1+ -1,+ -2]},"data": {@@ -142771,8 +144092,8 @@},{"method": "POST",- "path": "/api/convert/pandoc",- "handler": "pandoc",+ "path": "/api/export/export2Liandi",+ "handler": "export2Liandi","authorization": ["authenticated","admin",@@ -142780,7 +144101,7 @@],"body": "json","request": {- "$ref": "#/$defs/PandocRequestInput"+ "$ref": "#/$defs/ExportIDRequestInput"},"response": {"anyOf": [@@ -142794,7 +144115,7 @@]},"data": {- "$ref": "#/$defs/PandocData"+ "type": "null"},"msg": {"type": "string"@@ -142851,16 +144172,15 @@},{"method": "POST",- "path": "/api/export/copyExportFile",- "handler": "copyExportFile",+ "path": "/api/export/exportAsFile",+ "handler": "exportAsFile","authorization": ["authenticated",- "admin",- "writable"+ "admin"],- "body": "json",+ "body": "multipart","request": {- "$ref": "#/$defs/CopyExportFileRequestInput"+ "$ref": "#/$defs/ExportAsFileRequestInput"},"response": {"anyOf": [@@ -142874,7 +144194,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/ExportFileData"},"msg": {"type": "string"@@ -142893,8 +144213,7 @@"code": {"type": "integer","enum": [- -1,- -2+ -1]},"data": {@@ -142932,12 +144251,11 @@},{"method": "POST",- "path": "/api/export/export2Liandi",- "handler": "export2Liandi",+ "path": "/api/export/exportAsciiDoc",+ "handler": "exportAsciiDoc","authorization": ["authenticated",- "admin",- "writable"+ "admin"],"body": "json","request": {@@ -142955,7 +144273,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/ExportNamedZipData"},"msg": {"type": "string"@@ -143012,15 +144330,15 @@},{"method": "POST",- "path": "/api/export/exportAsFile",- "handler": "exportAsFile",+ "path": "/api/export/exportAttributeView",+ "handler": "exportAttributeView","authorization": ["authenticated","admin"],- "body": "multipart",+ "body": "json","request": {- "$ref": "#/$defs/ExportAsFileRequestInput"+ "$ref": "#/$defs/ExportAttributeViewRequestInput"},"response": {"anyOf": [@@ -143034,7 +144352,7 @@]},"data": {- "$ref": "#/$defs/ExportFileData"+ "$ref": "#/$defs/ExportZipData"},"msg": {"type": "string"@@ -143053,7 +144371,8 @@"code": {"type": "integer","enum": [- -1+ -1,+ 1]},"data": {@@ -143091,15 +144410,15 @@},{"method": "POST",- "path": "/api/export/exportAsciiDoc",- "handler": "exportAsciiDoc",+ "path": "/api/export/exportBrowserHTML",+ "handler": "exportBrowserHTML","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportIDRequestInput"+ "$ref": "#/$defs/ExportBrowserHTMLRequestInput"},"response": {"anyOf": [@@ -143113,7 +144432,7 @@]},"data": {- "$ref": "#/$defs/ExportNamedZipData"+ "$ref": "#/$defs/ExportZipData"},"msg": {"type": "string"@@ -143170,15 +144489,15 @@},{"method": "POST",- "path": "/api/export/exportAttributeView",- "handler": "exportAttributeView",+ "path": "/api/export/exportCodeBlock",+ "handler": "exportCodeBlock","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportAttributeViewRequestInput"+ "$ref": "#/$defs/ExportIDRequestInput"},"response": {"anyOf": [@@ -143192,7 +144511,7 @@]},"data": {- "$ref": "#/$defs/ExportZipData"+ "$ref": "#/$defs/ExportPathData"},"msg": {"type": "string"@@ -143250,15 +144569,15 @@},{"method": "POST",- "path": "/api/export/exportBrowserHTML",- "handler": "exportBrowserHTML",+ "path": "/api/export/exportData",+ "handler": "exportData","authorization": ["authenticated","admin"],- "body": "json",+ "body": "none","request": {- "$ref": "#/$defs/ExportBrowserHTMLRequestInput"+ "$ref": "#/$defs/EmptyRequestInput"},"response": {"anyOf": [@@ -143291,7 +144610,8 @@"code": {"type": "integer","enum": [- -1+ -1,+ 1]},"data": {@@ -143329,15 +144649,15 @@},{"method": "POST",- "path": "/api/export/exportCodeBlock",- "handler": "exportCodeBlock",+ "path": "/api/export/exportDataInFolder",+ "handler": "exportDataInFolder","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportIDRequestInput"+ "$ref": "#/$defs/ExportFolderRequestInput"},"response": {"anyOf": [@@ -143351,7 +144671,7 @@]},"data": {- "$ref": "#/$defs/ExportPathData"+ "$ref": "#/$defs/ExportNameData"},"msg": {"type": "string"@@ -143370,8 +144690,7 @@"code": {"type": "integer","enum": [- -1,- 1+ -1]},"data": {@@ -143409,15 +144728,15 @@},{"method": "POST",- "path": "/api/export/exportData",- "handler": "exportData",+ "path": "/api/export/exportDocx",+ "handler": "exportDocx","authorization": ["authenticated","admin"],- "body": "none",+ "body": "json","request": {- "$ref": "#/$defs/EmptyRequestInput"+ "$ref": "#/$defs/ExportDocxRequestInput"},"response": {"anyOf": [@@ -143431,7 +144750,7 @@]},"data": {- "$ref": "#/$defs/ExportZipData"+ "$ref": "#/$defs/ExportPathData"},"msg": {"type": "string"@@ -143489,15 +144808,15 @@},{"method": "POST",- "path": "/api/export/exportDataInFolder",- "handler": "exportDataInFolder",+ "path": "/api/export/exportEPUB",+ "handler": "exportEPUB","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportFolderRequestInput"+ "$ref": "#/$defs/ExportIDRequestInput"},"response": {"anyOf": [@@ -143511,7 +144830,7 @@]},"data": {- "$ref": "#/$defs/ExportNameData"+ "$ref": "#/$defs/ExportNamedZipData"},"msg": {"type": "string"@@ -143568,15 +144887,15 @@},{"method": "POST",- "path": "/api/export/exportDocx",- "handler": "exportDocx",+ "path": "/api/export/exportHTML",+ "handler": "exportHTML","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportDocxRequestInput"+ "$ref": "#/$defs/ExportHTMLRequestInput"},"response": {"anyOf": [@@ -143590,7 +144909,7 @@]},"data": {- "$ref": "#/$defs/ExportPathData"+ "$ref": "#/$defs/ExportHTMLData"},"msg": {"type": "string"@@ -143609,8 +144928,7 @@"code": {"type": "integer","enum": [- -1,- 1+ -1]},"data": {@@ -143648,15 +144966,15 @@},{"method": "POST",- "path": "/api/export/exportEPUB",- "handler": "exportEPUB",+ "path": "/api/export/exportMd",+ "handler": "exportMd","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportIDRequestInput"+ "$ref": "#/$defs/ExportMarkdownRequestInput"},"response": {"anyOf": [@@ -143727,15 +145045,15 @@},{"method": "POST",- "path": "/api/export/exportHTML",- "handler": "exportHTML",+ "path": "/api/export/exportMdContent",+ "handler": "exportMdContent","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportHTMLRequestInput"+ "$ref": "#/$defs/ExportMarkdownContentRequestInput"},"response": {"anyOf": [@@ -143749,7 +145067,7 @@]},"data": {- "$ref": "#/$defs/ExportHTMLData"+ "$ref": "#/$defs/ExportMarkdownContentData"},"msg": {"type": "string"@@ -143806,15 +145124,15 @@},{"method": "POST",- "path": "/api/export/exportMd",- "handler": "exportMd",+ "path": "/api/export/exportMdHTML",+ "handler": "exportMdHTML","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportMarkdownRequestInput"+ "$ref": "#/$defs/ExportMarkdownHTMLRequestInput"},"response": {"anyOf": [@@ -143828,7 +145146,7 @@]},"data": {- "$ref": "#/$defs/ExportNamedZipData"+ "$ref": "#/$defs/ExportHTMLData"},"msg": {"type": "string"@@ -143885,15 +145203,15 @@},{"method": "POST",- "path": "/api/export/exportMdContent",- "handler": "exportMdContent",+ "path": "/api/export/exportMds",+ "handler": "exportMds","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportMarkdownContentRequestInput"+ "$ref": "#/$defs/ExportDocumentsMarkdownRequestInput"},"response": {"anyOf": [@@ -143907,7 +145225,7 @@]},"data": {- "$ref": "#/$defs/ExportMarkdownContentData"+ "$ref": "#/$defs/ExportNamedZipData"},"msg": {"type": "string"@@ -143964,15 +145282,15 @@},{"method": "POST",- "path": "/api/export/exportMdHTML",- "handler": "exportMdHTML",+ "path": "/api/export/exportMediaWiki",+ "handler": "exportMediaWiki","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportMarkdownHTMLRequestInput"+ "$ref": "#/$defs/ExportIDRequestInput"},"response": {"anyOf": [@@ -143986,7 +145304,7 @@]},"data": {- "$ref": "#/$defs/ExportHTMLData"+ "$ref": "#/$defs/ExportNamedZipData"},"msg": {"type": "string"@@ -144043,15 +145361,15 @@},{"method": "POST",- "path": "/api/export/exportMds",- "handler": "exportMds",+ "path": "/api/export/exportNotebookMd",+ "handler": "exportNotebookMd","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportDocumentsMarkdownRequestInput"+ "$ref": "#/$defs/ExportNotebookMarkdownRequestInput"},"response": {"anyOf": [@@ -144122,8 +145440,8 @@},{"method": "POST",- "path": "/api/export/exportMediaWiki",- "handler": "exportMediaWiki",+ "path": "/api/export/exportNotebookSY",+ "handler": "exportNotebookSY","authorization": ["authenticated","admin"@@ -144144,7 +145462,7 @@]},"data": {- "$ref": "#/$defs/ExportNamedZipData"+ "$ref": "#/$defs/ExportZipData"},"msg": {"type": "string"@@ -144201,15 +145519,15 @@},{"method": "POST",- "path": "/api/export/exportNotebookMd",- "handler": "exportNotebookMd",+ "path": "/api/export/exportNotebooksMd",+ "handler": "exportNotebooksMd","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportNotebookMarkdownRequestInput"+ "$ref": "#/$defs/ExportNotebooksMarkdownRequestInput"},"response": {"anyOf": [@@ -144280,15 +145598,15 @@},{"method": "POST",- "path": "/api/export/exportNotebookSY",- "handler": "exportNotebookSY",+ "path": "/api/export/exportNotebooksSY",+ "handler": "exportNotebooksSY","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportIDRequestInput"+ "$ref": "#/$defs/ExportNotebooksRequestInput"},"response": {"anyOf": [@@ -144359,15 +145677,15 @@},{"method": "POST",- "path": "/api/export/exportNotebooksMd",- "handler": "exportNotebooksMd",+ "path": "/api/export/exportODT",+ "handler": "exportODT","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportNotebooksMarkdownRequestInput"+ "$ref": "#/$defs/ExportIDRequestInput"},"response": {"anyOf": [@@ -144438,15 +145756,15 @@},{"method": "POST",- "path": "/api/export/exportNotebooksSY",- "handler": "exportNotebooksSY",+ "path": "/api/export/exportOPML",+ "handler": "exportOPML","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportNotebooksRequestInput"+ "$ref": "#/$defs/ExportIDRequestInput"},"response": {"anyOf": [@@ -144460,7 +145778,7 @@]},"data": {- "$ref": "#/$defs/ExportZipData"+ "$ref": "#/$defs/ExportNamedZipData"},"msg": {"type": "string"@@ -144517,8 +145835,8 @@},{"method": "POST",- "path": "/api/export/exportODT",- "handler": "exportODT",+ "path": "/api/export/exportOrgMode",+ "handler": "exportOrgMode","authorization": ["authenticated","admin"@@ -144596,15 +145914,15 @@},{"method": "POST",- "path": "/api/export/exportOPML",- "handler": "exportOPML",+ "path": "/api/export/exportPreviewHTML",+ "handler": "exportPreviewHTML","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportIDRequestInput"+ "$ref": "#/$defs/ExportPreviewHTMLRequestInput"},"response": {"anyOf": [@@ -144618,7 +145936,7 @@]},"data": {- "$ref": "#/$defs/ExportNamedZipData"+ "$ref": "#/$defs/ExportPreviewHTMLData"},"msg": {"type": "string"@@ -144675,8 +145993,8 @@},{"method": "POST",- "path": "/api/export/exportOrgMode",- "handler": "exportOrgMode",+ "path": "/api/export/exportRTF",+ "handler": "exportRTF","authorization": ["authenticated","admin"@@ -144754,15 +146072,15 @@},{"method": "POST",- "path": "/api/export/exportPreviewHTML",- "handler": "exportPreviewHTML",+ "path": "/api/export/exportReStructuredText",+ "handler": "exportReStructuredText","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportPreviewHTMLRequestInput"+ "$ref": "#/$defs/ExportIDRequestInput"},"response": {"anyOf": [@@ -144776,7 +146094,7 @@]},"data": {- "$ref": "#/$defs/ExportPreviewHTMLData"+ "$ref": "#/$defs/ExportNamedZipData"},"msg": {"type": "string"@@ -144833,15 +146151,15 @@},{"method": "POST",- "path": "/api/export/exportRTF",- "handler": "exportRTF",+ "path": "/api/export/exportResources",+ "handler": "exportResources","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportIDRequestInput"+ "$ref": "#/$defs/ExportResourcesRequestInput"},"response": {"anyOf": [@@ -144855,7 +146173,7 @@]},"data": {- "$ref": "#/$defs/ExportNamedZipData"+ "$ref": "#/$defs/ExportPathData"},"msg": {"type": "string"@@ -144874,7 +146192,8 @@"code": {"type": "integer","enum": [- -1+ -1,+ 1]},"data": {@@ -144893,6 +146212,9 @@},{"type": "null"+ },+ {+ "type": "string"}]},@@ -144912,8 +146234,8 @@},{"method": "POST",- "path": "/api/export/exportReStructuredText",- "handler": "exportReStructuredText",+ "path": "/api/export/exportSY",+ "handler": "exportSY","authorization": ["authenticated","admin"@@ -144934,7 +146256,7 @@]},"data": {- "$ref": "#/$defs/ExportNamedZipData"+ "$ref": "#/$defs/ExportZipData"},"msg": {"type": "string"@@ -144991,15 +146313,15 @@},{"method": "POST",- "path": "/api/export/exportResources",- "handler": "exportResources",+ "path": "/api/export/exportSYs",+ "handler": "exportSYs","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportResourcesRequestInput"+ "$ref": "#/$defs/ExportIDsRequestInput"},"response": {"anyOf": [@@ -145013,7 +146335,7 @@]},"data": {- "$ref": "#/$defs/ExportPathData"+ "$ref": "#/$defs/ExportZipData"},"msg": {"type": "string"@@ -145032,8 +146354,7 @@"code": {"type": "integer","enum": [- -1,- 1+ -1]},"data": {@@ -145052,9 +146373,6 @@},{"type": "null"- },- {- "type": "string"}]},@@ -145074,15 +146392,15 @@},{"method": "POST",- "path": "/api/export/exportSY",- "handler": "exportSY",+ "path": "/api/export/exportTempContent",+ "handler": "exportTempContent","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportIDRequestInput"+ "$ref": "#/$defs/ExportTempContentRequestInput"},"response": {"anyOf": [@@ -145096,7 +146414,7 @@]},"data": {- "$ref": "#/$defs/ExportZipData"+ "$ref": "#/$defs/ExportURLData"},"msg": {"type": "string"@@ -145115,7 +146433,8 @@"code": {"type": "integer","enum": [- -1+ -1,+ 1]},"data": {@@ -145153,15 +146472,15 @@},{"method": "POST",- "path": "/api/export/exportSYs",- "handler": "exportSYs",+ "path": "/api/export/exportTextile",+ "handler": "exportTextile","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportIDsRequestInput"+ "$ref": "#/$defs/ExportIDRequestInput"},"response": {"anyOf": [@@ -145175,7 +146494,7 @@]},"data": {- "$ref": "#/$defs/ExportZipData"+ "$ref": "#/$defs/ExportNamedZipData"},"msg": {"type": "string"@@ -145232,15 +146551,14 @@},{"method": "POST",- "path": "/api/export/exportTempContent",- "handler": "exportTempContent",+ "path": "/api/export/preview",+ "handler": "exportPreview","authorization": [- "authenticated",- "admin"+ "authenticated"],"body": "json","request": {- "$ref": "#/$defs/ExportTempContentRequestInput"+ "$ref": "#/$defs/ExportIDRequestInput"},"response": {"anyOf": [@@ -145254,7 +146572,7 @@]},"data": {- "$ref": "#/$defs/ExportURLData"+ "$ref": "#/$defs/ExportPreviewData"},"msg": {"type": "string"@@ -145273,8 +146591,7 @@"code": {"type": "integer","enum": [- -1,- 1+ -1]},"data": {@@ -145312,15 +146629,15 @@},{"method": "POST",- "path": "/api/export/exportTextile",- "handler": "exportTextile",+ "path": "/api/export/processPDF",+ "handler": "processPDF","authorization": ["authenticated","admin"],"body": "json","request": {- "$ref": "#/$defs/ExportIDRequestInput"+ "$ref": "#/$defs/ProcessPDFRequestInput"},"response": {"anyOf": [@@ -145334,7 +146651,7 @@]},"data": {- "$ref": "#/$defs/ExportNamedZipData"+ "type": "null"},"msg": {"type": "string"@@ -145391,14 +146708,65 @@},{"method": "POST",- "path": "/api/export/preview",- "handler": "exportPreview",+ "path": "/api/extension/copy",+ "handler": "extensionCopy","authorization": [- "authenticated"+ "authenticated",+ "admin",+ "writable"],- "body": "json",+ "body": "multipart","request": {- "$ref": "#/$defs/ExportIDRequestInput"+ "type": "object",+ "properties": {+ "assets": {+ "type": "string"+ },+ "clipType": {+ "type": "string"+ },+ "dom": {+ "type": "string"+ },+ "href": {+ "type": "string"+ },+ "notebook": {+ "type": "string"+ }+ },+ "required": [+ "dom"+ ],+ "additionalProperties": {+ "anyOf": [+ {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "string",+ "format": "binary"+ }+ ]+ },+ {+ "type": "array",+ "items": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "string",+ "format": "binary"+ }+ ]+ }+ }+ ]+ }},"response": {"anyOf": [@@ -145412,7 +146780,14 @@]},"data": {- "$ref": "#/$defs/ExportPreviewData"+ "anyOf": [+ {+ "$ref": "#/$defs/ExtensionCopyData"+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -145450,6 +146825,16 @@},{"type": "null"+ },+ {+ "anyOf": [+ {+ "$ref": "#/$defs/ExtensionCopyData"+ },+ {+ "type": "null"+ }+ ]}]},@@ -145469,15 +146854,16 @@},{"method": "POST",- "path": "/api/export/processPDF",- "handler": "processPDF",+ "path": "/api/file/copyFile",+ "handler": "copyFile","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/ProcessPDFRequestInput"+ "$ref": "#/$defs/CopyFileRequestInput"},"response": {"anyOf": [@@ -145510,7 +146896,8 @@"code": {"type": "integer","enum": [- -1+ -1,+ -2]},"data": {@@ -145548,97 +146935,20 @@},{"method": "POST",- "path": "/api/extension/copy",- "handler": "extensionCopy",+ "path": "/api/file/getFile",+ "handler": "getFile","authorization": [- "authenticated",- "admin",- "writable"+ "authenticated"],- "body": "multipart",+ "body": "json","request": {- "type": "object",- "properties": {- "assets": {- "type": "string"- },- "clipType": {- "type": "string"- },- "dom": {- "type": "string"- },- "href": {- "type": "string"- },- "notebook": {- "type": "string"- }- },- "required": [- "dom"- ],- "additionalProperties": {- "anyOf": [- {- "anyOf": [- {- "type": "string"- },- {- "type": "string",- "format": "binary"- }- ]- },- {- "type": "array",- "items": {- "anyOf": [- {- "type": "string"- },- {- "type": "string",- "format": "binary"- }- ]- }- }- ]- }+ "$ref": "#/$defs/FilePathRequestInput"},"response": {"anyOf": [{- "type": "object",- "properties": {- "code": {- "type": "integer",- "enum": [- 0- ]- },- "data": {- "anyOf": [- {- "$ref": "#/$defs/ExtensionCopyData"- },- {- "type": "null"- }- ]- },- "msg": {- "type": "string"- }- },- "required": [- "code",- "msg",- "data"- ],- "additionalProperties": false+ "type": "string",+ "format": "binary"},{"type": "object",@@ -145646,7 +146956,13 @@"code": {"type": "integer","enum": [- -1+ -1,+ -3,+ 403,+ 404,+ 409,+ 500,+ 503]},"data": {@@ -145665,16 +146981,6 @@},{"type": "null"- },- {- "anyOf": [- {- "$ref": "#/$defs/ExtensionCopyData"- },- {- "type": "null"- }- ]}]},@@ -145690,20 +146996,21 @@"additionalProperties": true}]- }+ },+ "output": "binary",+ "errorStatus": 202},{"method": "POST",- "path": "/api/file/copyFile",- "handler": "copyFile",+ "path": "/api/file/getUniqueFilename",+ "handler": "getUniqueFilename","authorization": ["authenticated",- "admin",- "writable"+ "admin"],"body": "json","request": {- "$ref": "#/$defs/CopyFileRequestInput"+ "$ref": "#/$defs/FilePathRequestInput"},"response": {"anyOf": [@@ -145717,7 +147024,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/FilePathData"},"msg": {"type": "string"@@ -145737,7 +147044,7 @@"type": "integer","enum": [-1,- -2+ -3]},"data": {@@ -145775,20 +147082,41 @@},{"method": "POST",- "path": "/api/file/getFile",- "handler": "getFile",+ "path": "/api/file/globalCopyFiles",+ "handler": "globalCopyFiles","authorization": [- "authenticated"+ "authenticated",+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/FilePathRequestInput"+ "$ref": "#/$defs/CopyFilesRequestInput"},"response": {"anyOf": [{- "type": "string",- "format": "binary"+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "null"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false},{"type": "object",@@ -145797,12 +147125,9 @@"type": "integer","enum": [-1,+ -2,-3,- 403,- 404,- 409,- 500,- 503+ 403]},"data": {@@ -145836,21 +147161,20 @@"additionalProperties": true}]- },- "output": "binary",- "errorStatus": 202+ }},{"method": "POST",- "path": "/api/file/getUniqueFilename",- "handler": "getUniqueFilename",+ "path": "/api/file/putFile",+ "handler": "putFile","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],- "body": "json",+ "body": "form","request": {- "$ref": "#/$defs/FilePathRequestInput"+ "$ref": "#/$defs/PutFileRequestInput"},"response": {"anyOf": [@@ -145864,7 +147188,7 @@]},"data": {- "$ref": "#/$defs/FilePathData"+ "type": "null"},"msg": {"type": "string"@@ -145884,7 +147208,10 @@"type": "integer","enum": [-1,- -3+ -3,+ 400,+ 403,+ 500]},"data": {@@ -145922,16 +147249,15 @@},{"method": "POST",- "path": "/api/file/globalCopyFiles",- "handler": "globalCopyFiles",+ "path": "/api/file/readDir",+ "handler": "readDir","authorization": ["authenticated",- "admin",- "writable"+ "admin"],"body": "json","request": {- "$ref": "#/$defs/CopyFilesRequestInput"+ "$ref": "#/$defs/ReadDirectoryRequestInput"},"response": {"anyOf": [@@ -145945,7 +147271,10 @@]},"data": {- "type": "null"+ "type": "array",+ "items": {+ "$ref": "#/$defs/DirectoryEntry"+ }},"msg": {"type": "string"@@ -145965,9 +147294,11 @@"type": "integer","enum": [-1,- -2,-3,- 403+ 403,+ 404,+ 409,+ 500]},"data": {@@ -146005,16 +147336,16 @@},{"method": "POST",- "path": "/api/file/putFile",- "handler": "putFile",+ "path": "/api/file/removeFile",+ "handler": "removeFile","authorization": ["authenticated","admin","writable"],- "body": "form",+ "body": "json","request": {- "$ref": "#/$defs/PutFileRequestInput"+ "$ref": "#/$defs/RemoveFileRequestInput"},"response": {"anyOf": [@@ -146049,8 +147380,8 @@"enum": [-1,-3,- 400,403,+ 404,500]},@@ -146089,15 +147420,16 @@},{"method": "POST",- "path": "/api/file/readDir",- "handler": "readDir",+ "path": "/api/file/renameFile",+ "handler": "renameFile","authorization": ["authenticated",- "admin"+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/ReadDirectoryRequestInput"+ "$ref": "#/$defs/RenameFileRequestInput"},"response": {"anyOf": [@@ -146111,10 +147443,7 @@]},"data": {- "type": "array",- "items": {- "$ref": "#/$defs/DirectoryEntry"- }+ "type": "null"},"msg": {"type": "string"@@ -146176,8 +147505,8 @@},{"method": "POST",- "path": "/api/file/removeFile",- "handler": "removeFile",+ "path": "/api/file/workspaceCopyFiles",+ "handler": "workspaceCopyFiles","authorization": ["authenticated","admin",@@ -146185,7 +147514,7 @@],"body": "json","request": {- "$ref": "#/$defs/RemoveFileRequestInput"+ "$ref": "#/$defs/CopyFilesRequestInput"},"response": {"anyOf": [@@ -146219,10 +147548,9 @@"type": "integer","enum": [-1,+ -2,-3,- 403,- 404,- 500+ 403]},"data": {@@ -146260,8 +147588,89 @@},{"method": "POST",- "path": "/api/file/renameFile",- "handler": "renameFile",+ "path": "/api/filetree/authFilePublishAccess",+ "handler": "authFilePublishAccess",+ "authorization": [+ "authenticated"+ ],+ "body": "json",+ "request": {+ "$ref": "#/$defs/FileTreeAuthPublishRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "type": "null"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ },+ "additionalErrorStatuses": [+ 429+ ]+ },+ {+ "method": "POST",+ "path": "/api/filetree/changeSort",+ "handler": "changeSort","authorization": ["authenticated","admin",@@ -146269,7 +147678,7 @@],"body": "json","request": {- "$ref": "#/$defs/RenameFileRequestInput"+ "$ref": "#/$defs/FileTreeChangeSortRequestInput"},"response": {"anyOf": [@@ -146302,12 +147711,7 @@"code": {"type": "integer","enum": [- -1,- -3,- 403,- 404,- 409,- 500+ -1]},"data": {@@ -146345,8 +147749,8 @@},{"method": "POST",- "path": "/api/file/workspaceCopyFiles",- "handler": "workspaceCopyFiles",+ "path": "/api/filetree/createDailyNote",+ "handler": "createDailyNote","authorization": ["authenticated","admin",@@ -146354,7 +147758,7 @@],"body": "json","request": {- "$ref": "#/$defs/CopyFilesRequestInput"+ "$ref": "#/$defs/FileTreeDailyNoteRequestInput"},"response": {"anyOf": [@@ -146368,7 +147772,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/FileTreeCreateData"},"msg": {"type": "string"@@ -146388,9 +147792,7 @@"type": "integer","enum": [-1,- -2,- -3,- 403+ 1]},"data": {@@ -146428,14 +147830,16 @@},{"method": "POST",- "path": "/api/filetree/authFilePublishAccess",- "handler": "authFilePublishAccess",+ "path": "/api/filetree/createDoc",+ "handler": "createDoc","authorization": [- "authenticated"+ "authenticated",+ "admin",+ "writable"],"body": "json","request": {- "$ref": "#/$defs/FileTreeAuthPublishRequestInput"+ "$ref": "#/$defs/FileTreeCreateRequestInput"},"response": {"anyOf": [@@ -146449,7 +147853,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/FileTreeCreateData"},"msg": {"type": "string"@@ -146502,23 +147906,20 @@"additionalProperties": true}]- },- "additionalErrorStatuses": [- 429- ]+ }},{"method": "POST",- "path": "/api/filetree/changeSort",- "handler": "changeSort",+ "path": "/api/filetree/createDocByParent",+ "handler": "createDocByParent","authorization": ["authenticated","admin","writable"],- "body": "json",+ "body": "structJSON","request": {- "$ref": "#/$defs/FileTreeChangeSortRequestInput"+ "$ref": "#/$defs/CreateDocByParentRequestInput"},"response": {"anyOf": [@@ -146532,7 +147933,7 @@]},"data": {- "type": "null"+ "$ref": "#/$defs/CreateDocByParentResult"},"msg": {"type": "string"@@ -146570,6 +147971,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/CreateDocByParentResult"}]},@@ -146589,8 +147993,8 @@},{"method": "POST",- "path": "/api/filetree/createDailyNote",- "handler": "createDailyNote",+ "path": "/api/filetree/createDocWithMd",+ "handler": "createDocWithMd","authorization": ["authenticated","admin",@@ -146598,7 +148002,7 @@],"body": "json","request": {- "$ref": "#/$defs/FileTreeDailyNoteRequestInput"+ "$ref": "#/$defs/FileTreeCreateMarkdownRequestInput"},"response": {"anyOf": [@@ -146612,7 +148016,7 @@]},"data": {- "$ref": "#/$defs/FileTreeCreateData"+ "type": "string"},"msg": {"type": "string"@@ -146631,8 +148035,7 @@"code": {"type": "integer","enum": [- -1,- 1+ -1]},"data": {@@ -146670,8 +148073,8 @@},{"method": "POST",- "path": "/api/filetree/createDoc",- "handler": "createDoc",+ "path": "/api/filetree/doc2Heading",+ "handler": "doc2Heading","authorization": ["authenticated","admin",@@ -146679,7 +148082,7 @@],"body": "json","request": {- "$ref": "#/$defs/FileTreeCreateRequestInput"+ "$ref": "#/$defs/FileTreeDocHeadingRequestInput"},"response": {"anyOf": [@@ -146693,7 +148096,7 @@]},"data": {- "$ref": "#/$defs/FileTreeCreateData"+ "$ref": "#/$defs/FileTreeDocHeadingData"},"msg": {"type": "string"@@ -146750,8 +148153,8 @@},{"method": "POST",- "path": "/api/filetree/createDocWithMd",- "handler": "createDocWithMd",+ "path": "/api/filetree/duplicateDoc",+ "handler": "duplicateDoc","authorization": ["authenticated","admin",@@ -146759,7 +148162,7 @@],"body": "json","request": {- "$ref": "#/$defs/FileTreeCreateMarkdownRequestInput"+ "$ref": "#/$defs/FileTreeIDRequestInput"},"response": {"anyOf": [@@ -146773,7 +148176,7 @@]},"data": {- "type": "string"+ "$ref": "#/$defs/FileTreeDuplicateData"},"msg": {"type": "string"@@ -146830,8 +148233,8 @@},{"method": "POST",- "path": "/api/filetree/doc2Heading",- "handler": "doc2Heading",+ "path": "/api/filetree/duplicateDocTree",+ "handler": "duplicateDocTree","authorization": ["authenticated","admin",@@ -146839,7 +148242,7 @@],"body": "json","request": {- "$ref": "#/$defs/FileTreeDocHeadingRequestInput"+ "$ref": "#/$defs/FileTreeIDRequestInput"},"response": {"anyOf": [@@ -146853,7 +148256,7 @@]},"data": {- "$ref": "#/$defs/FileTreeDocHeadingData"+ "$ref": "#/$defs/FileTreeDuplicateData"},"msg": {"type": "string"@@ -146910,16 +148313,15 @@},{"method": "POST",- "path": "/api/filetree/duplicateDoc",- "handler": "duplicateDoc",+ "path": "/api/filetree/getDailyNoteInfo",+ "handler": "getDailyNoteInfo","authorization": ["authenticated",- "admin",- "writable"+ "admin"],"body": "json","request": {- "$ref": "#/$defs/FileTreeIDRequestInput"+ "$ref": "#/$defs/DailyNoteInfoRequestInput"},"response": {"anyOf": [@@ -146933,7 +148335,14 @@]},"data": {- "$ref": "#/$defs/FileTreeDuplicateData"+ "anyOf": [+ {+ "$ref": "#/$defs/DailyNoteInfo"+ },+ {+ "type": "null"+ }+ ]},"msg": {"type": "string"@@ -146952,7 +148361,8 @@"code": {"type": "integer","enum": [- -1+ -1,+ 1]},"data": {@@ -146990,16 +148400,14 @@},{"method": "POST",- "path": "/api/filetree/duplicateDocTree",- "handler": "duplicateDocTree",+ "path": "/api/filetree/getDoc",+ "handler": "getDoc","authorization": [- "authenticated",- "admin",- "writable"+ "authenticated"],"body": "json","request": {- "$ref": "#/$defs/FileTreeIDRequestInput"+ "$ref": "#/$defs/FileTreeGetDocRequestInput"},"response": {"anyOf": [@@ -147013,7 +148421,7 @@]},"data": {- "$ref": "#/$defs/FileTreeDuplicateData"+ "$ref": "#/$defs/FileTreeGetDocData"},"msg": {"type": "string"@@ -147032,7 +148440,9 @@"code": {"type": "integer","enum": [- -1+ -1,+ 1,+ 3]},"data": {@@ -147070,15 +148480,14 @@},{"method": "POST",- "path": "/api/filetree/getDailyNoteInfo",- "handler": "getDailyNoteInfo",+ "path": "/api/filetree/getDocCreateSavePath",+ "handler": "getDocCreateSavePath","authorization": [- "authenticated",- "admin"+ "authenticated"],"body": "json","request": {- "$ref": "#/$defs/DailyNoteInfoRequestInput"+ "$ref": "#/$defs/FileTreeNotebookRequestInput"},"response": {"anyOf": [@@ -147092,14 +148501,7 @@]},"data": {- "anyOf": [- {- "$ref": "#/$defs/DailyNoteInfo"- },- {- "type": "null"- }- ]+ "$ref": "#/$defs/FileTreeCreateSavePathResult"},"msg": {"type": "string"@@ -147118,8 +148520,7 @@"code": {"type": "integer","enum": [- -1,- 1+ -1]},"data": {@@ -147138,6 +148539,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/FileTreeCreateSavePathResult"}]},@@ -147157,14 +148561,15 @@},{"method": "POST",- "path": "/api/filetree/getDoc",- "handler": "getDoc",+ "path": "/api/filetree/getDocCreateTarget",+ "handler": "getDocCreateTarget","authorization": [- "authenticated"+ "authenticated",+ "admin"],"body": "json","request": {- "$ref": "#/$defs/FileTreeGetDocRequestInput"+ "$ref": "#/$defs/GetDocCreateTargetRequestInput"},"response": {"anyOf": [@@ -147178,7 +148583,7 @@]},"data": {- "$ref": "#/$defs/FileTreeGetDocData"+ "$ref": "#/$defs/DocumentCreateTargetData"},"msg": {"type": "string"@@ -147197,9 +148602,7 @@"code": {"type": "integer","enum": [- -1,- 1,- 3+ -1]},"data": {@@ -147237,14 +148640,15 @@},{"method": "POST",- "path": "/api/filetree/getDocCreateSavePath",- "handler": "getDocCreateSavePath",+ "path": "/api/filetree/getDocPaths",+ "handler": "getDocPaths","authorization": [- "authenticated"+ "authenticated",+ "admin"],"body": "json","request": {- "$ref": "#/$defs/FileTreeNotebookRequestInput"+ "$ref": "#/$defs/GetDocPathsRequestInput"},"response": {"anyOf": [@@ -147258,7 +148662,7 @@]},"data": {- "$ref": "#/$defs/FileTreeCreateSavePathData"+ "$ref": "#/$defs/DocumentPathsResult"},"msg": {"type": "string"@@ -147296,6 +148700,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/DocumentPathsResult"}]},@@ -147993,7 +149400,7 @@]},"data": {- "$ref": "#/$defs/FileTreeSavePathData"+ "$ref": "#/$defs/FileTreeSavePathResult"},"msg": {"type": "string"@@ -148031,6 +149438,9 @@},{"type": "null"+ },+ {+ "$ref": "#/$defs/FileTreeSavePathResult"}]},@@ -148694,6 +150104,85 @@]}},+ {+ "method": "POST",+ "path": "/api/filetree/planDocCreate",+ "handler": "planDocCreate",+ "authorization": [+ "authenticated",+ "admin"+ ],+ "body": "json",+ "request": {+ "$ref": "#/$defs/PlanDocCreateRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "$ref": "#/$defs/DocumentCreatePlan"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },{"method": "POST","path": "/api/filetree/removeDoc",@@ -149271,6 +150760,88 @@]}},+ {+ "method": "POST",+ "path": "/api/filetree/resolveDocPath",+ "handler": "resolveDocPath",+ "authorization": [+ "authenticated",+ "admin"+ ],+ "body": "json",+ "request": {+ "$ref": "#/$defs/ResolveDocPathRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "$ref": "#/$defs/ResolveDocPathResult"+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": false+ },+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ -1+ ]+ },+ "data": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "closeTimeout": {+ "type": "number"+ }+ },+ "required": [+ "closeTimeout"+ ],+ "additionalProperties": false+ },+ {+ "type": "null"+ },+ {+ "$ref": "#/$defs/ResolveDocPathResult"+ }+ ]+ },+ "msg": {+ "type": "string"+ }+ },+ "required": [+ "code",+ "msg",+ "data"+ ],+ "additionalProperties": true+ }+ ]+ }+ },{"method": "POST","path": "/api/filetree/searchDocs",diff --git a/kernel/cli/cmd/display_test.go b/kernel/cli/cmd/display_test.goindex 5f9dd93667..59e541ec82 100644--- a/kernel/cli/cmd/display_test.go+++ b/kernel/cli/cmd/display_test.go@@ -74,7 +74,7 @@ func TestResolveDocumentMovePath(t *testing.T) {name stringuserPath stringhPath string- sourceHPath string+ sourceTitle stringwant stringwantErr bool}{@@ -82,48 +82,48 @@ func TestResolveDocumentMovePath(t *testing.T) {name: "explicit internal path",userPath: "/20260726000000-parent1.sy",hPath: "/missing",- sourceHPath: "/child",+ sourceTitle: "child",want: "/20260726000000-parent1.sy",},- {name: "default root", sourceHPath: "/child", want: "/"},- {name: "root hpath", hPath: "/", sourceHPath: "/child", want: "/"},+ {name: "default root", sourceTitle: "child", want: "/"},+ {name: "root hpath", hPath: "/", sourceTitle: "child", want: "/"},{name: "parent hpath",hPath: "/parent",- sourceHPath: "/child",+ sourceTitle: "child",want: "/20260726000000-parent1.sy",},{name: "parent hpath with trailing slash",hPath: "/parent/",- sourceHPath: "/child",+ sourceTitle: "child",want: "/20260726000000-parent1.sy",},{name: "full destination hpath",hPath: "/parent/child",- sourceHPath: "/child",+ sourceTitle: "child",want: "/20260726000000-parent1.sy",},{name: "nested full destination hpath",hPath: "/grand/parent/child",- sourceHPath: "/child",+ sourceTitle: "child",want: "/20260726000000-grand01/20260726000001-parent1.sy",},{name: "existing target with different source title",hPath: "/existing/child",- sourceHPath: "/source",+ sourceTitle: "source",want: "/20260726000002-existin/20260726000003-child01.sy",},- {name: "missing target", hPath: "/missing", sourceHPath: "/child", wantErr: true},- {name: "missing destination parent", hPath: "/missing/child", sourceHPath: "/child", wantErr: true},+ {name: "missing target", hPath: "/missing", sourceTitle: "child", wantErr: true},+ {name: "missing destination parent", hPath: "/missing/child", sourceTitle: "child", wantErr: true},}for _, test := range tests {t.Run(test.name, func(t *testing.T) {- got, err := resolveDocumentMovePathWithLookup(test.userPath, test.hPath, test.sourceHPath, lookup)+ got, err := resolveDocumentMovePathWithLookup(test.userPath, test.hPath, test.sourceTitle, lookup)if test.wantErr {if nil == err {t.Fatalf("expected an error, got path %q", got)@@ -179,17 +179,19 @@ func TestDocumentSearchDisplayFields(t *testing.T) {doc: map[string]string{"path": "/20260722120000-parent1/20260722123000-child01.sy","hPath": "Notebook/Parent/Document",+ "title": "Literal / title","box": "20260722110000-boxid01",},wantType: "DOCUMENT",wantID: "20260722123000-child01",- wantName: "Document",+ wantName: "Literal / title",},{name: "notebook",doc: map[string]string{"path": "/","hPath": "Notebook/",+ "title": "Notebook","box": "20260722110000-boxid01",},wantType: "NOTEBOOK",diff --git a/kernel/cli/cmd/document.go b/kernel/cli/cmd/document.goindex f956abdeb6..9800def33c 100644--- a/kernel/cli/cmd/document.go+++ b/kernel/cli/cmd/document.go@@ -225,7 +225,7 @@ var documentMoveCmd = &cobra.Command{if err != nil {return err}- targetPath, err := resolveDocumentMovePath(toNotebook, toPath, hpath, tree.HPath)+ targetPath, err := resolveDocumentMovePath(toNotebook, toPath, hpath, treenode.ReadDocumentTitle(tree.Root).Text)if err != nil {return err}@@ -324,8 +324,8 @@ func resolvePathWithLookup(userPath, hpath string, lookup func(string) (string,return "", fmt.Errorf("target human-readable path not found: %s", targetHPath)}-func resolveDocumentMovePath(boxID, userPath, hpath, sourceHPath string) (string, error) {- return resolveDocumentMovePathWithLookup(userPath, hpath, sourceHPath, func(targetHPath string) (string, bool) {+func resolveDocumentMovePath(boxID, userPath, hpath, sourceTitle string) (string, error) {+ return resolveDocumentMovePathWithLookup(userPath, hpath, sourceTitle, func(targetHPath string) (string, bool) {bt := treenode.GetBlockTreeRootByHPath(boxID, targetHPath)if nil == bt {return "", false@@ -335,7 +335,7 @@ func resolveDocumentMovePath(boxID, userPath, hpath, sourceHPath string) (string}func resolveDocumentMovePathWithLookup(- userPath, hpath, sourceHPath string,+ userPath, hpath, sourceTitle string,lookup func(string) (string, bool),) (string, error) {if "" != userPath {@@ -350,7 +350,6 @@ func resolveDocumentMovePathWithLookup(return "/", nil}- sourceTitle := path.Base(path.Clean(sourceHPath))if sourceTitle == path.Base(targetHPath) {targetHPath = path.Dir(targetHPath)if "/" == targetHPath {@@ -397,11 +396,10 @@ var documentSearchCmd = &cobra.Command{}func documentSearchDisplayFields(doc map[string]string) (typ, id, name string) {- hPath := strings.TrimSuffix(doc["hPath"], "/")if "/" == doc["path"] {- return "NOTEBOOK", doc["box"], path.Base(hPath)+ return "NOTEBOOK", doc["box"], doc["title"]}- return "DOCUMENT", strings.TrimSuffix(path.Base(doc["path"]), ".sy"), path.Base(hPath)+ return "DOCUMENT", strings.TrimSuffix(path.Base(doc["path"]), ".sy"), doc["title"]}func printDocumentTable(files []*model.File) {diff --git a/kernel/conf/box.go b/kernel/conf/box.goindex c6a731bd52..afd664e4d6 100644--- a/kernel/conf/box.go+++ b/kernel/conf/box.go@@ -20,20 +20,24 @@ import "github.com/siyuan-note/siyuan/kernel/util"// BoxConf 维护 .siyuan/conf.json 笔记本配置。type BoxConf struct {- Name string `json:"name"` // 笔记本名称- Sort int `json:"sort"` // 排序字段- Icon string `json:"icon"` // 图标- Closed bool `json:"closed"` // 是否处于关闭状态- RefCreateSaveBox string `json:"refCreateSaveBox"` // 块引时新建文档存储笔记本- RefCreateSavePath string `json:"refCreateSavePath"` // 块引时新建文档存储路径- DocCreateSaveBox string `json:"docCreateSaveBox"` // 新建文档存储笔记本- DocCreateSavePath string `json:"docCreateSavePath"` // 新建文档存储路径- DocCreateTemplatePath string `json:"docCreateTemplatePath"` // 新建文档使用的模板路径- DailyNoteSavePath string `json:"dailyNoteSavePath"` // 新建日记存储路径- DailyNoteTemplatePath string `json:"dailyNoteTemplatePath"` // 新建日记使用的模板路径- SortMode int `json:"sortMode"` // 排序方式- Encrypted bool `json:"encrypted"` // 是否为加密笔记本- BoxCrypt *BoxEncryption `json:"boxCrypt"` // 笔记本加密参数,仅 Encrypted=true 时有值+ DocCreateTarget *DocumentTarget `json:"docCreateTarget,omitempty"`+ RefCreateTarget *DocumentTarget `json:"refCreateTarget,omitempty"`+ DailyNoteTarget *DocumentTarget `json:"dailyNoteTarget,omitempty"`+ MetadataVersion int `json:"-"` // 已认证配置载荷版本,只在内存中保存+ Name string `json:"name"` // 笔记本名称+ Sort int `json:"sort"` // 排序字段+ Icon string `json:"icon"` // 图标+ Closed bool `json:"closed"` // 是否处于关闭状态+ RefCreateSaveBox string `json:"refCreateSaveBox"` // 块引时新建文档存储笔记本+ RefCreateSavePath string `json:"refCreateSavePath"` // 块引时新建文档存储路径+ DocCreateSaveBox string `json:"docCreateSaveBox"` // 新建文档存储笔记本+ DocCreateSavePath string `json:"docCreateSavePath"` // 新建文档存储路径+ DocCreateTemplatePath string `json:"docCreateTemplatePath"` // 新建文档使用的模板路径+ DailyNoteSavePath string `json:"dailyNoteSavePath"` // 新建日记存储路径+ DailyNoteTemplatePath string `json:"dailyNoteTemplatePath"` // 新建日记使用的模板路径+ SortMode int `json:"sortMode"` // 排序方式+ Encrypted bool `json:"encrypted"` // 是否为加密笔记本+ BoxCrypt *BoxEncryption `json:"boxCrypt"` // 笔记本加密参数,仅 Encrypted=true 时有值}// BoxEncryption 维护单个加密笔记本的密钥包络参数。WrappedDEK 是用全局 KEK 加密后的 DEK,本身可落盘。diff --git a/kernel/conf/document_target.go b/kernel/conf/document_target.gonew file mode 100644index 0000000000..16b1a19492--- /dev/null+++ b/kernel/conf/document_target.go@@ -0,0 +1,137 @@+package conf++import (+ "bytes"+ "encoding/json"+ "errors"+ "io"+ "strings"++ "github.com/88250/lute/ast"+)++// DocumentTarget 在渲染前保存标题段边界,变量产生的分隔符不改变文档层级。+type DocumentTarget struct {+ Version int `json:"version"`+ Notebook string `json:"notebook"`+ Anchor DocumentTargetAnchor `json:"anchor"`+ Up int `json:"up"`+ Parents []string `json:"parents"`+ Title string `json:"title"`+ OnMissingParent string `json:"onMissingParent"`+}++type DocumentTargetAnchor struct {+ Kind string `json:"kind"`+ ID string `json:"id,omitempty"`+}++type DocumentTargets struct {+ Document *DocumentTarget `json:"docCreateTarget,omitempty"`+ Reference *DocumentTarget `json:"refCreateTarget,omitempty"`+ DailyNote *DocumentTarget `json:"dailyNoteTarget,omitempty"`+}++func (targets DocumentTargets) Empty() bool {+ return targets.Document == nil && targets.Reference == nil && targets.DailyNote == nil+}++func (targets *DocumentTargets) UnmarshalJSON(data []byte) error {+ if _, err := documentTargetFields(data); err != nil {+ return err+ }+ type plain DocumentTargets+ var next plain+ decoder := json.NewDecoder(bytes.NewReader(data))+ decoder.DisallowUnknownFields()+ if err := decoder.Decode(&next); err != nil {+ return err+ }+ *targets = DocumentTargets(next)+ return nil+}++func (target *DocumentTarget) Validate() error {+ if target == nil {+ return nil+ }+ if target.Version != 2 || !ast.IsNodeIDPattern(target.Notebook) || target.Up < 0 || target.Up > 128 ||+ target.Parents == nil || len(target.Parents) > 128 ||+ (target.OnMissingParent != "create" && target.OnMissingParent != "error") {+ return errors.New("invalid structured document target")+ }+ switch target.Anchor.Kind {+ case "notebookRoot", "context":+ if target.Anchor.ID != "" {+ return errors.New("document target anchor must not contain an ID")+ }+ case "document":+ if !ast.IsNodeIDPattern(target.Anchor.ID) {+ return errors.New("document target anchor requires a document ID")+ }+ default:+ return errors.New("invalid document target anchor")+ }+ return nil+}++// UnmarshalJSON 拒绝未知版本及缺省字段,避免把不认识的配置按空目标覆盖。+func (target *DocumentTarget) UnmarshalJSON(data []byte) error {+ fields, err := documentTargetFields(data)+ if err != nil {+ return err+ }+ if _, err = documentTargetFields(fields["anchor"]); err != nil {+ return err+ }+ type plain DocumentTarget+ var next plain+ decoder := json.NewDecoder(bytes.NewReader(data))+ decoder.DisallowUnknownFields()+ if err := decoder.Decode(&next); err != nil {+ return err+ }+ for _, name := range []string{"version", "notebook", "anchor", "up", "parents", "title", "onMissingParent"} {+ if value, exists := fields[name]; !exists || bytes.Equal(bytes.TrimSpace(value), []byte("null")) {+ return errors.New("missing or null document target field: " + name)+ }+ }+ value := DocumentTarget(next)+ if err := value.Validate(); err != nil {+ return err+ }+ *target = value+ return nil+}++// documentTargetFields 保留字段出现次数,避免重复或大小写别名把未来版本遮盖成已知版本。+func documentTargetFields(data []byte) (map[string]json.RawMessage, error) {+ decoder := json.NewDecoder(bytes.NewReader(data))+ if token, err := decoder.Token(); err != nil || token != json.Delim('{') {+ return nil, errors.New("invalid document target object")+ }+ fields, seen := map[string]json.RawMessage{}, map[string]bool{}+ for decoder.More() {+ token, err := decoder.Token()+ if err != nil {+ return nil, err+ }+ name := token.(string)+ if seen[strings.ToLower(name)] {+ return nil, errors.New("duplicate document target field: " + name)+ }+ seen[strings.ToLower(name)] = true+ var value json.RawMessage+ if err = decoder.Decode(&value); err != nil {+ return nil, err+ }+ fields[name] = value+ }+ if token, err := decoder.Token(); err != nil || token != json.Delim('}') {+ return nil, errors.New("invalid document target object")+ }+ if decoder.Decode(new(json.RawMessage)) != io.EOF {+ return nil, errors.New("invalid document target suffix")+ }+ return fields, nil+}diff --git a/kernel/conf/document_target_test.go b/kernel/conf/document_target_test.gonew file mode 100644index 0000000000..4dd7c29047--- /dev/null+++ b/kernel/conf/document_target_test.go@@ -0,0 +1,43 @@+package conf++import (+ "encoding/json"+ "strings"+ "testing"+)++func TestDocumentTargetStrictConfiguration(t *testing.T) {+ const valid = `{"version":2,"notebook":"20261023090000-target1","anchor":{"kind":"notebookRoot"},"up":0,"parents":[],"title":"Literal / title","onMissingParent":"error"}`+ var target DocumentTarget+ if err := json.Unmarshal([]byte(valid), &target); err != nil || target.Title != "Literal / title" {+ t.Fatal("a literal template lost its source text", err)+ }+ for name, invalid := range map[string]string{+ "version duplicate": strings.Replace(valid, `"version":2`, `"version":3,"version":2`, 1),+ "version case duplicate": strings.Replace(valid, `"version":2`, `"version":3,"Version":2`, 1),+ "anchor duplicate": strings.Replace(valid, `"kind":"notebookRoot"`, `"kind":"future","Kind":"notebookRoot"`, 1),+ "unknown anchor": strings.Replace(valid, `"kind":"notebookRoot"`, `"kind":"notebookRoot","future":true`, 1),+ "null parents": strings.Replace(valid, `"parents":[]`, `"parents":null`, 1),+ "missing title": strings.Replace(valid, `"title":"Literal / title",`, ``, 1),+ "unknown version": strings.Replace(valid, `"version":2`, `"version":3`, 1),+ "suffix": valid + `{}`,+ } {+ t.Run(name, func(t *testing.T) {+ if err := json.Unmarshal([]byte(invalid), &target); err == nil {+ t.Fatal("accepted invalid configuration", invalid)+ }+ })+ }+ var targets DocumentTargets+ if err := json.Unmarshal([]byte(`{"docCreateTarget":`+valid+`,"refCreateTarget":null}`), &targets); err != nil || targets.Document == nil {+ t.Fatal("optional configuration fields could not round trip", err)+ }+ for _, invalid := range []string{+ `{"docCreateTarget":` + valid + `,"DocCreateTarget":null}`,+ `{"futureTarget":` + valid + `}`,+ } {+ if err := json.Unmarshal([]byte(invalid), &targets); err == nil {+ t.Fatal("protected target collection ignored an unknown or duplicate field", invalid)+ }+ }+}diff --git a/kernel/documentaddressing/capabilities.go b/kernel/documentaddressing/capabilities.gonew file mode 100644index 0000000000..e7e63491d9--- /dev/null+++ b/kernel/documentaddressing/capabilities.go@@ -0,0 +1,58 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package documentaddressing++import (+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "fmt"+ "path/filepath"++ "github.com/88250/lute/ast"+)++// ModeSnapshot 描述经过校验的能力要求,不代表当前读取器可以处理该模式。+type ModeSnapshot struct {+ Mode int+ Revision string+}++// InspectBox 不读取文档或派生索引。合法的高模式与 CheckBox 一样记入本机下界,+// 配置损坏则返回错误,不向调用方伪装成旧服务端或兼容模式。+func InspectBox(dataDir, confDir, boxID string) (*ModeSnapshot, error) {+ if !ast.IsNodeIDPattern(boxID) {+ return nil, ErrInvalid+ }+ storeLock.Lock()+ defer storeLock.Unlock()+ store, err := loadStore(dataDir, confDir)+ if err != nil {+ return nil, err+ }+ read := directoryReader(filepath.Join(dataDir, boxID))+ sources := map[string]string{}+ mode, err := ReadMode(boxID, func(name string) ([]byte, error) {+ data, readErr := read(name)+ if readErr == nil {+ digest := sha256.Sum256(data)+ sources[name] = hex.EncodeToString(digest[:])+ }+ return data, readErr+ })+ if err != nil {+ return nil, fmt.Errorf("notebook [%s]: %w", boxID, err)+ }+ mode = store.confirm(boxID, mode)+ if err = store.save(); err != nil {+ return nil, err+ }+ data, err := json.Marshal([]interface{}{1, boxID, mode, sources})+ if err != nil {+ return nil, err+ }+ digest := sha256.Sum256(data)+ return &ModeSnapshot{Mode: mode, Revision: "1:" + hex.EncodeToString(digest[:])}, nil+}diff --git a/kernel/documentaddressing/capabilities_test.go b/kernel/documentaddressing/capabilities_test.gonew file mode 100644index 0000000000..8d3b52ffd2--- /dev/null+++ b/kernel/documentaddressing/capabilities_test.go@@ -0,0 +1,45 @@+package documentaddressing++import (+ "errors"+ "os"+ "path/filepath"+ "testing"+)++func TestInspectBoxCapabilities(t *testing.T) {+ root := t.TempDir()+ dataDir, confDir := filepath.Join(root, "data"), filepath.Join(root, "conf")+ first, err := InspectBox(dataDir, confDir, testBox)+ if err != nil || first.Mode != 1 || first.Revision == "" {+ t.Fatal("legacy capability read failed", first, err)+ }+ if _, err = os.Stat(confDir); !errors.Is(err, os.ErrNotExist) {+ t.Fatal("legacy capability read created a floor record", err)+ }+ boxDir := filepath.Join(dataDir, testBox)+ writeTestFile(t, boxDir, ConfigPath, `{"name":"Private configuration"}`)+ second, err := InspectBox(dataDir, confDir, testBox)+ if err != nil || second.Mode != 1 || second.Revision == first.Revision {+ t.Fatal("configuration changes did not invalidate the revision", err)+ }+ writeTestFile(t, boxDir, FloorPath, `{"version":1,"notebook":"`+testBox+`","minimumMode":2}`)+ third, err := InspectBox(dataDir, confDir, testBox)+ if err != nil || third.Mode != 2 || third.Revision == second.Revision {+ t.Fatal("higher capability was hidden", third, err)+ }+ if err = os.Remove(filepath.Join(boxDir, FloorPath)); err != nil {+ t.Fatal(err)+ }+ fourth, err := InspectBox(dataDir, confDir, testBox)+ if err != nil || fourth.Mode != 2 {+ t.Fatal("capability read forgot the confirmed floor", fourth, err)+ }+ if err = CheckBox(dataDir, confDir, testBox); !errors.Is(err, ErrUnsupported) {+ t.Fatal("capability probe enabled an unsupported writer", err)+ }+ writeTestFile(t, boxDir, FloorPath, `{"version":9}`)+ if _, err = InspectBox(dataDir, confDir, testBox); !errors.Is(err, ErrInvalid) {+ t.Fatal("unknown capability record was hidden", err)+ }+}diff --git a/kernel/filesys/document_metadata.go b/kernel/filesys/document_metadata.gonew file mode 100644index 0000000000..e1838c9261--- /dev/null+++ b/kernel/filesys/document_metadata.go@@ -0,0 +1,109 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package filesys++import (+ "os"+ "sort"+ "sync"++ "github.com/88250/lute/parse"+ "github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/cache"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++// 源替换和摘要发布共用提交范围,条件创建可以在这里复核名称后立即落盘。+var documentSourceWriteLock sync.Mutex++func lockDocumentSource() func() {+ documentSourceWriteLock.Lock()+ return documentSourceWriteLock.Unlock+}++// LockDocumentConfiguration 与源提交互斥,配置发布后旧的创建预览不能继续落盘。+// 持锁范围不能调用源写入或等待事务队列;配置反应在释放后执行。+func LockDocumentConfiguration() func() { return lockDocumentSource() }++// RecoverDocumentMetadataWrite 根据认证后的源完成中断写入,不用待写入的标题覆盖实际源。+func RecoverDocumentMetadataWrite(doc *treenode.BlockTree) error {+ unlock := lockDocumentSource()+ defer unlock()+ return recoverDocumentMetadataWrite(doc)+}++func recoverDocumentMetadataWrite(doc *treenode.BlockTree) error {+ cache.RemoveTreeDataInBox(doc.ID, doc.BoxID)+ cache.RemoveDocIALInBox(doc.Path, doc.BoxID)+ cache.RemoveBlockIALInBox(doc.ID, doc.BoxID)+ tree, err := ReadDocumentMetadataTree(doc.BoxID, doc.Path)+ if os.IsNotExist(err) {+ if current := treenode.GetBlockTreeInExactBox(doc.ID, doc.BoxID); current != nil && current.Path != doc.Path {+ // 目录变更失败时源可能仍在原位置,不能按未完成的目标路径删除原摘要。+ tree, err = ReadDocumentMetadataTree(doc.BoxID, current.Path)+ }+ }+ if os.IsNotExist(err) {+ return treenode.FinishDocumentMetadataRecovery(doc.BoxID, doc.ID, true)+ }+ if err != nil {+ return err+ }+ tree.HPath, _, err = ReadDocHPath(doc.BoxID, tree.Path)+ if err != nil {+ return err+ }+ if err = treenode.CommitDocumentMetadataWrite(tree); err != nil {+ return err+ }+ return treenode.FinishDocumentMetadataRecovery(doc.BoxID, doc.ID, false)+}++// MutateDocumentSources 将原始源变更纳入同一提交范围;恢复失败保留标记,不误报源未写入。+// 相同身份的最后一个路径为操作后的预期位置,目录操作按父级先于子级恢复。+func MutateDocumentSources(documents []*treenode.BlockTree, mutate func() error) error {+ if len(documents) == 0 {+ return mutate()+ }+ return MutateDocumentSourceSet(func() ([]*treenode.BlockTree, error) { return documents, nil }, mutate)+}++// MutateDocumentSourceSet 在提交范围内枚举目录,防止遗漏检查期间新增的文档。+func MutateDocumentSourceSet(collect func() ([]*treenode.BlockTree, error), mutate func() error) error {+ unlock := lockDocumentSource()+ defer unlock()+ documents, err := collect()+ if err != nil {+ return err+ }+ unique := map[string]*treenode.BlockTree{}+ for _, doc := range documents {+ unique[doc.BoxID+"/"+doc.ID] = doc+ }+ pending := make([]*treenode.BlockTree, 0, len(unique))+ for _, doc := range unique {+ marked, err := treenode.BeginDocumentMetadataRecovery(doc)+ if err != nil {+ return err+ }+ if marked {+ pending = append(pending, doc)+ }+ }+ err = mutate()+ sort.Slice(pending, func(i, j int) bool { return pending[i].Path < pending[j].Path })+ for _, doc := range pending {+ if recoveryErr := recoverDocumentMetadataWrite(doc); recoveryErr != nil {+ logging.LogErrorf("recover document metadata [%s/%s] failed: %s", doc.BoxID, doc.ID, recoveryErr)+ }+ }+ return err+}++func finishDocumentMetadataWrite(tree *parse.Tree, pending bool, err *error) {+ if pending && *err == nil {+ *err = treenode.CommitDocumentMetadataWrite(tree)+ }+}diff --git a/kernel/filesys/hpath.go b/kernel/filesys/hpath.goindex b758304c99..ead3de854a 100644--- a/kernel/filesys/hpath.go+++ b/kernel/filesys/hpath.go@@ -4,9 +4,29 @@ import ("path/filepath""strings"+ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util")+// ReadDocumentMetadataTree 认证并检查源文件,仅构建根属性,恢复过程不补建或修复正文。+func ReadDocumentMetadataTree(boxID, p string) (*parse.Tree, error) {+ p, err := ValidateBoxRelativePath(boxID, p)+ if err != nil {+ return nil, err+ }+ header, err := readDocumentHeader(filepath.Join(util.DataDir, boxID, p), true)+ if err != nil {+ return nil, err+ }+ root := &ast.Node{Type: ast.NodeDocument, ID: header.ID, Spec: header.Spec}+ for key, value := range header.Properties {+ root.SetIALAttr(key, value)+ }+ return &parse.Tree{ID: root.ID, Box: boxID, Path: "/" + strings.TrimPrefix(filepath.ToSlash(p), "/"), Root: root}, nil+}+// ReadDocHPath 只读文档属性并认证加密源文件,不解析块树、不修复或补建任何文件。func ReadDocHPath(boxID, p string) (hpath string, properties map[string]string, err error) {if p, err = ValidateBoxRelativePath(boxID, p); err != nil {@@ -22,7 +42,7 @@ func ReadDocHPath(boxID, p string) (hpath string, properties map[string]string,if err != nil {return "", nil, err}- title := properties["title"]+ title := treenode.DocumentTitleFromProperties(properties).Textif title == "" && i < len(parts)-1 {title = "Untitled"}diff --git a/kernel/filesys/tree.go b/kernel/filesys/tree.goindex 539d141884..26d933c42f 100644--- a/kernel/filesys/tree.go+++ b/kernel/filesys/tree.go@@ -284,7 +284,7 @@ func LoadTreeByData(data []byte, boxID, p string, luteEngine *lute.Lute) (ret *pparts = parts[1 : len(parts)-1] // 去掉开头的斜杆和结尾的自己if 1 > len(parts) {- ret.HPath = "/" + ret.Root.IALAttr("title")+ ret.HPath = "/" + treenode.ReadDocumentTitle(ret.Root).Textret.Hash = treenode.NodeHash(ret.Root, ret, luteEngine)return}@@ -332,7 +332,7 @@ func LoadTreeByData(data []byte, boxID, p string, luteEngine *lute.Lute) (ret *phPathBuilder.WriteString(title)hPathBuilder.WriteString("/")}- hPathBuilder.WriteString(ret.Root.IALAttr("title"))+ hPathBuilder.WriteString(treenode.ReadDocumentTitle(ret.Root).Text)ret.HPath = hPathBuilder.String()ret.Hash = treenode.NodeHash(ret.Root, ret, luteEngine)return@@ -355,6 +355,21 @@ func readParentDocIAL(absPath string) (map[string]string, error) {}func readDocIAL(absPath string, strict bool) (map[string]string, error) {+ doc, err := readDocumentHeader(absPath, strict)+ if err != nil {+ return nil, err+ }+ return doc.Properties, nil+}++type documentHeader struct {+ ID string+ Type string+ Spec string+ Properties map[string]string+}++func readDocumentHeader(absPath string, strict bool) (*documentHeader, error) {boxID := docIALBoxID(absPath)if boxID != "" {if err := CheckDocumentAddressing(boxID); err != nil {@@ -382,11 +397,7 @@ func readDocIAL(absPath string, strict bool) (map[string]string, error) {if err = treenode.CheckSpecJSON(data); err != nil {return nil, err}- var doc struct {- ID string- Type string- Properties map[string]string- }+ var doc documentHeaderif err = json.Unmarshal(data, &doc); err != nil {return nil, fmt.Errorf("parse parent document [%s]: %w", absPath, err)}@@ -399,7 +410,7 @@ func readDocIAL(absPath string, strict bool) (map[string]string, error) {for key, value := range doc.Properties {doc.Properties[key] = html.UnescapeAttrVal(value)}- return doc.Properties, nil+ return &doc, nil}var ErrInvalidDocIAL = errors.New("invalid document properties")@@ -534,6 +545,18 @@ func TreeSize(tree *parse.Tree) (size uint64) {}func WriteTree(tree *parse.Tree) (size uint64, err error) {+ return WriteTreeWithPreflight(tree, nil)+}++// WriteTreeWithPreflight 在源写入协调范围内检查业务条件,检查失败时不创建目录或发布缓存。+func WriteTreeWithPreflight(tree *parse.Tree, preflight func() error) (size uint64, err error) {+ unlock := lockDocumentSource()+ defer unlock()+ if preflight != nil {+ if err = preflight(); err != nil {+ return+ }+ }timing := util.BeginPerformance("document.save")defer timing.Finish()data, filePath, err := prepareWriteTree(tree)@@ -556,6 +579,11 @@ func WriteTree(tree *parse.Tree) (size uint64, err error) {err = encErrreturn}+ pending, metadataErr := treenode.BeginDocumentMetadataWrite(tree)+ if metadataErr != nil {+ return 0, metadataErr+ }+ defer finishDocumentMetadataWrite(tree, pending, &err)// 缓存与待写入数据一致时跳过落盘;缓存未命中时再读盘比对,避免无变更的重复写入timing.Stage("compare")@@ -596,7 +624,7 @@ func WriteTree(tree *parse.Tree) (size uint64, err error) {}if util.ExceedLargeFileWarningSize(len(data)) {- msg := fmt.Sprintf(util.Langs[util.Lang][268], tree.Root.IALAttr("title")+" "+filepath.Base(filePath), util.LargeFileWarningSize.Load())+ msg := fmt.Sprintf(util.Langs[util.Lang][268], treenode.ReadDocumentTitle(tree.Root).Text+" "+filepath.Base(filePath), util.LargeFileWarningSize.Load())util.PushErrMsg(msg, 7000)}@@ -624,11 +652,11 @@ func prepareWriteTree(tree *parse.Tree) (data []byte, filePath string, err errornewP := treenode.NewParagraph("")tree.Root.AppendChild(newP)tree.Root.SetIALAttr("updated", util.TimeFromID(newP.ID))- treenode.UpsertBlockTree(tree)+ treenode.UpsertBlockTreePending(tree)}if treenode.NormalizeTabs(tree.Root) {- treenode.UpsertBlockTree(tree)+ treenode.UpsertBlockTreePending(tree)}treenode.UpgradeSpec(tree)diff --git a/kernel/filesys/tree_cached_source.go b/kernel/filesys/tree_cached_source.goindex 6dc4a77022..9f5976bb0a 100644--- a/kernel/filesys/tree_cached_source.go+++ b/kernel/filesys/tree_cached_source.go@@ -65,7 +65,7 @@ func (source *CachedTreeSource) Parse(luteEngine *lute.Lute) (*parse.Tree, errorreturn nil, err}tree.Root.Path = source.path- tree.HPath = source.parentHPathPrefix + tree.Root.IALAttr("title")+ tree.HPath = source.parentHPathPrefix + treenode.ReadDocumentTitle(tree.Root).Texttree.Hash = treenode.NodeHash(tree.Root, tree, luteEngine)return tree, nil}diff --git a/kernel/filesys/tree_compare_write.go b/kernel/filesys/tree_compare_write.goindex 1c0e6c1a60..416d79b6bc 100644--- a/kernel/filesys/tree_compare_write.go+++ b/kernel/filesys/tree_compare_write.go@@ -18,7 +18,9 @@ import (// WriteTreeIfUnchanged 仅在文档仍与扫描源的原始文件字节一致时原子替换,防止覆盖并发修改。// 加密源必须先通过认证,落盘沿用现有密文格式,缓存仅在条件写成功后更新。-func WriteTreeIfUnchanged(tree *parse.Tree, original []byte) (uint64, error) {+func WriteTreeIfUnchanged(tree *parse.Tree, original []byte) (size uint64, err error) {+ unlock := lockDocumentSource()+ defer unlock()dek, _, release, err := acquireCryptoLease(tree.Box)if err != nil {return 0, err@@ -39,6 +41,11 @@ func WriteTreeIfUnchanged(tree *parse.Tree, original []byte) (uint64, error) {if err != nil {return 0, err}+ pending, err := treenode.BeginDocumentMetadataWrite(tree)+ if err != nil {+ return 0, err+ }+ defer finishDocumentMetadataWrite(tree, pending, &err)if err = util.WriteFileIfUnchanged(filePath, original, diskData); err != nil {return 0, err}diff --git a/kernel/mcp/tools/document.go b/kernel/mcp/tools/document.goindex af0ed0b874..0c763974f5 100644--- a/kernel/mcp/tools/document.go+++ b/kernel/mcp/tools/document.go@@ -285,11 +285,10 @@ func documentSearchDocs(args map[string]any) (CallToolResult, error) {}func documentSearchDisplayFields(doc map[string]string) (typ, id, name string) {- hPath := strings.TrimSuffix(doc["hPath"], "/")if doc["path"] == "/" {- return "NOTEBOOK", doc["box"], path.Base(hPath)+ return "NOTEBOOK", doc["box"], doc["title"]}- return "DOCUMENT", strings.TrimSuffix(path.Base(doc["path"]), ".sy"), path.Base(hPath)+ return "DOCUMENT", strings.TrimSuffix(path.Base(doc["path"]), ".sy"), doc["title"]}func documentInfo(args map[string]any) (CallToolResult, error) {diff --git a/kernel/mcp/tools/document_test.go b/kernel/mcp/tools/document_test.goindex 8bbc235d51..19f86a160f 100644--- a/kernel/mcp/tools/document_test.go+++ b/kernel/mcp/tools/document_test.go@@ -31,17 +31,19 @@ func TestDocumentSearchDisplayFields(t *testing.T) {doc: map[string]string{"path": "/20260903120000-parent1/20260903123000-child01.sy","hPath": "Notebook/Parent/Document",+ "title": "Literal / title","box": "20260903110000-boxid01",},wantType: "DOCUMENT",wantID: "20260903123000-child01",- wantName: "Document",+ wantName: "Literal / title",},{name: "notebook",doc: map[string]string{"path": "/","hPath": "Notebook/",+ "title": "Notebook","box": "20260903110000-boxid01",},wantType: "NOTEBOOK",diff --git a/kernel/model/asset_relink.go b/kernel/model/asset_relink.goindex dae7c3a327..a3e293457c 100644--- a/kernel/model/asset_relink.go+++ b/kernel/model/asset_relink.go@@ -190,14 +190,14 @@ func (p *assetRelinkPlan) scan() error {rel, _ := filepath.Rel(boxDir, absPath)tree.Box, tree.Path = boxID, "/"+filepath.ToSlash(rel)tree.Root.Box, tree.Root.Path = tree.Box, tree.Path- tree.HPath = "/" + tree.Root.IALAttr("title")+ tree.HPath = "/" + treenode.ReadDocumentTitle(tree.Root).Textif readErr = filesys.NormalizeTreeForRead(tree); readErr != nil {return readErr}if tree.Root.ID != strings.TrimSuffix(entry.Name(), ".sy") {return fmt.Errorf("document ID does not match path: %s", absPath)}- titles[tree.Root.ID] = tree.Root.IALAttr("title")+ titles[tree.Root.ID] = treenode.ReadDocumentTitle(tree.Root).Textbefore := len(p.result.References)p.tree(tree, apicontract.AssetReference{Notebook: boxID, RootID: tree.Root.ID, Path: tree.Path})retain := falsediff --git a/kernel/model/assets.go b/kernel/model/assets.goindex 5389bbd57f..1443ea4f0f 100644--- a/kernel/model/assets.go+++ b/kernel/model/assets.go@@ -1885,7 +1885,7 @@ func RenameAsset(oldPath, newName string) (newPath string, err error) {treenode.UpsertBlockTree(tree)sql.UpsertTreeQueue(tree)- util.PushEndlessProgress(fmt.Sprintf(Conf.Language(111), util.EscapeHTML(tree.Root.IALAttr("title"))))+ util.PushEndlessProgress(fmt.Sprintf(Conf.Language(111), util.EscapeHTML(treenode.ReadDocumentTitle(tree.Root).Text)))}}}diff --git a/kernel/model/attribute_view_new_item.go b/kernel/model/attribute_view_new_item.goindex 7d40703c7f..28d1165851 100644--- a/kernel/model/attribute_view_new_item.go+++ b/kernel/model/attribute_view_new_item.go@@ -19,7 +19,6 @@ package modelimport ("errors""fmt"- "path""strings""sync""time"@@ -38,7 +37,7 @@ type NewItemTemplatePreview struct {HPath string `json:"hPath,omitempty"`Warnings []string `json:"warnings,omitempty"`- parentID string+ plan *DocumentCreatePlan}// CreateAttributeViewItemResult 描述按模板创建数据库条目的结果。@@ -244,7 +243,7 @@ func createAttributeViewItem(avID, blockID, viewID, templateID, previousID, groucontent := preview.PrimaryKeyif !isDetached {if blockTree := treenode.GetBlockTree(boundBlockID); nil != blockTree {- content = path.Base(blockTree.HPath)+ content = documentTitleText(blockTree.BoxID, blockTree.RootID)}}return &CreateAttributeViewItemResult{@@ -311,6 +310,11 @@ func CreateAttributeViewItemDocs(avID, blockID, saveMode string, itemIDs []strinif 0 == len(items) {return ret, nil}+ plans := make([]*DocumentCreatePlan, 0, len(items))+ for _, item := range items {+ plans = append(plans, item.preview.plan)+ }+ coalesceDocumentPlanAncestors(plans)cleanupCreatedDocs := func() error {var cleanupErr error@@ -466,54 +470,25 @@ func resolveAttributeViewItemDocument(blockID, primary string, itemTemplate *av.}primary = normalizeDocTitle(primary)- boxID, pathTemplate, inherited, err := resolveNewItemSaveConfig(blockTree.BoxID, itemTemplate.SaveLocation)- if nil != err {+ target, err := resolveNewItemDocumentTarget(blockTree.BoxID, itemTemplate.SaveLocation)+ if err != nil {return nil, err}- renderedPath, err := RenderGoTemplateAtInBox(pathTemplate, createdAt, boxID)- if nil != err {- return nil, err- }- renderedPath = util.TrimSpaceInPath(strings.TrimSpace(renderedPath))- return newItemDocumentPreview(blockTree, boxID, renderedPath, primary, inherited), nil-}--func newItemDocumentPreview(blockTree *treenode.BlockTree, boxID, renderedPath, primary string, inherited bool) *NewItemTemplatePreview {- preview := &NewItemTemplatePreview{PrimaryKey: primary, BoxID: boxID}- if boxID != blockTree.BoxID && "" != renderedPath && !strings.HasPrefix(renderedPath, "/") {- renderedPath = "/" + renderedPath- }- if "" == primary {- primary = newItemTitleFromPath(renderedPath)- preview.PrimaryKey = primary- }- parentTemplate := newItemParentPathTemplate(renderedPath)- baseHPath := "/"- if boxID == blockTree.BoxID && !strings.HasPrefix(parentTemplate, "/") {- if !IsBoxDoc(blockTree.BoxID, blockTree.RootID) {- baseHPath = blockTree.HPath- preview.parentID = blockTree.RootID+ if treenode.DocumentMetadataState(target.Notebook) != "ready" {+ if err = recoverDocumentMetadata(target.Notebook); err != nil {+ return nil, err}}- parentHPath := path.Clean(path.Join(baseHPath, parentTemplate))- if "." == parentHPath || "" == parentHPath {- parentHPath = "/"- }- if !strings.HasPrefix(parentHPath, "/") {- parentHPath = "/" + parentHPath- }- if "" == primary {- preview.HPath = strings.TrimSuffix(parentHPath, "/") + "/"- if "/" == parentHPath {- preview.HPath = "/"- }- } else {- preview.HPath = path.Join(parentHPath, primary)+ request := DocumentPlanRequest{Notebook: blockTree.BoxID, Purpose: "document", ContextID: &blockTree.RootID,+ ID: ast.NewNodeID(), Now: createdAt, Target: target, SkipContentTemplateCheck: true}+ if primary != "" {+ request.Title = &primary}- if inherited && boxID != blockTree.BoxID {- preview.parentID = ""+ plan, err := PlanDocumentCreation(request)+ if err != nil {+ return nil, err}- return preview+ return &NewItemTemplatePreview{PrimaryKey: plan.Title, BoxID: plan.Notebook, HPath: plan.DisplayPath, plan: plan}, nil}func createAttributeViewItemDocument(preview *NewItemTemplatePreview, itemTemplate *av.NewItemTemplate) (docID string, tree *parse.Tree, err error) {@@ -522,19 +497,22 @@ func createAttributeViewItemDocument(preview *NewItemTemplatePreview, itemTemplafunc createAttributeViewItemDocumentWithMarkdown(preview *NewItemTemplatePreview, itemTemplate *av.NewItemTemplate,document *CreateAttributeViewItemMarkdown) (docID string, tree *parse.Tree, err error) {- docID = ast.NewNodeID()- arg := map[string]any{"titleEmpty": "" == preview.PrimaryKey}- tags, markdown, clippingHref := "", "", ""- withMath := false+ if preview.plan == nil || len(preview.plan.Steps) == 0 {+ return "", nil, errors.New("attribute view document creation plan is missing")+ }+ step := &preview.plan.Steps[len(preview.plan.Steps)-1]+ // 数据库正文模板由下方既有流程处理,避免同时应用普通新建模板。+ step.DocCreateTemplatePath = ""if nil != document {- tags, markdown, clippingHref = document.Tags, document.Markdown, document.ClippingHref- withMath = document.WithMath- arg["listDocTree"] = document.ListDocTree && !itemTemplate.HideInFileTree+ step.Tags, step.Markdown, step.ClippingHref = document.Tags, document.Markdown, document.ClippingHref+ step.WithMath = document.WithMath+ step.ListDocTree = document.ListDocTree && !itemTemplate.HideInFileTree}- docID, err = CreateWithMarkdown(tags, preview.BoxID, preview.HPath, markdown, preview.parentID, docID, withMath, clippingHref, arg)+ _, err = executeDocumentCreationPlan(preview.plan, false)if nil != err {return}+ docID = step.IDif nil == document && "" != itemTemplate.ContentTemplatePath {if err = applyNewItemContentTemplate(itemTemplate.ContentTemplatePath, docID); nil != err {err = newItemCreationError(err, removeCreatedNewItemDoc(docID))@@ -573,25 +551,28 @@ func applyNewItemDocumentAttrs(tree *parse.Tree, itemTemplate *av.NewItemTemplatreturn}-func resolveNewItemSaveConfig(currentBoxID string, location *av.NewItemSaveLocation) (boxID, pathTemplate string, inherited bool, err error) {- if nil != location {- boxID = location.BoxID- if "" == boxID {+func resolveNewItemDocumentTarget(currentBoxID string, location *av.NewItemSaveLocation) (*EffectiveDocumentTarget, error) {+ var target *EffectiveDocumentTarget+ var err error+ if location == nil {+ target, err = GetDocCreateTarget(currentBoxID, "document")+ } else {+ boxID := location.BoxID+ if boxID == "" {boxID = currentBoxID}- if nil == Conf.Box(boxID) {- return "", "", false, ErrBoxNotFound- }- if err = validateNewItemSaveBox(currentBoxID, boxID); nil != err {- return "", "", false, err+ if Conf.Box(boxID) == nil {+ return nil, ErrBoxNotFound}- return boxID, location.PathTemplate, false, nil+ target = &EffectiveDocumentTarget{Notebook: boxID, Path: location.PathTemplate}}-- inherited = true- boxID, pathTemplate = ResolveDocCreateSaveLocation(currentBoxID)- err = validateNewItemSaveBox(currentBoxID, boxID)- return+ if err != nil {+ return nil, err+ }+ if err = validateNewItemSaveBox(currentBoxID, target.Notebook); err != nil {+ return nil, err+ }+ return target, nil}func validateNewItemSaveBox(currentBoxID, targetBoxID string) error {@@ -601,32 +582,6 @@ func validateNewItemSaveBox(currentBoxID, targetBoxID string) error {return nil}-func newItemParentPathTemplate(renderedPath string) string {- if "" == renderedPath || strings.HasSuffix(renderedPath, "/") {- return renderedPath- }- isAbsolute := strings.HasPrefix(renderedPath, "/")- segments := strings.FieldsFunc(renderedPath, func(r rune) bool { return '/' == r })- if 1 >= len(segments) {- if isAbsolute {- return "/"- }- return ""- }- parent := strings.Join(segments[:len(segments)-1], "/")- if isAbsolute {- parent = "/" + parent- }- return parent-}--func newItemTitleFromPath(renderedPath string) string {- if "" == renderedPath || strings.HasSuffix(renderedPath, "/") {- return ""- }- return normalizeDocTitle(path.Base(renderedPath))-}-func resolveNewItemFieldValues(attrView *av.AttributeView, itemTemplate *av.NewItemTemplate, createdAt time.Time,carrierBoxID string) (ret map[string]*av.Value, err error) {ret = map[string]*av.Value{}diff --git a/kernel/model/attribute_view_new_item_test.go b/kernel/model/attribute_view_new_item_test.goindex 99f3de7d84..0937664cd7 100644--- a/kernel/model/attribute_view_new_item_test.go+++ b/kernel/model/attribute_view_new_item_test.go@@ -19,32 +19,23 @@ import ("github.com/siyuan-note/siyuan/kernel/util")-func TestNewItemParentPathTemplate(t *testing.T) {- tests := map[string]string{- "": "",- "/": "/",- "relative": "",- "/Document": "/",- "folder/Document": "folder",- "/folder/Document": "/folder",- "/folder/subfolder/": "/folder/subfolder/",- }- for input, expected := range tests {- if actual := newItemParentPathTemplate(input); expected != actual {- t.Fatalf("newItemParentPathTemplate(%q): expected %q, got %q", input, expected, actual)+func TestNewItemDocumentTargetSegments(t *testing.T) {+ for _, test := range []struct {+ input, title string+ parents int+ }{+ {"", "", 0}, {"/", "", 0}, {"relative", "relative", 0},+ {"/Document", "Document", 0}, {"folder/Document", "Document", 1},+ {"/folder/Document", "Document", 1}, {"/folder/subfolder/", "", 2},+ {"/Daily Notes/2026-07-18", "2026-07-18", 1}, {"/Daily Notes/", "", 1},+ } {+ rendered, err := renderDocumentTarget(&EffectiveDocumentTarget{Notebook: ast.NewNodeID(), Path: test.input}, DocumentPlanRequest{})+ if err != nil || rendered.title != test.title || len(rendered.parents) != test.parents {+ t.Fatalf("target %q: %+v, %v", test.input, rendered, err)}}}-func TestNewItemPathTitleFallback(t *testing.T) {- if expected := "2026-07-18"; expected != newItemTitleFromPath("/Daily Notes/"+expected) {- t.Fatal("the last save path segment should be available as the document title")- }- if "" != newItemTitleFromPath("/Daily Notes/") {- t.Fatal("a save path ending with a slash should not provide a document title")- }-}-func TestNewItemPrimaryKeyUsesClippedTitleFallback(t *testing.T) {createdAt := time.Date(2026, time.August, 13, 12, 0, 0, 0, time.Local)template := &av.NewItemTemplate{TargetType: av.NewItemTargetDetached}@@ -73,13 +64,11 @@ func TestNewItemDocumentPreviewUsesCurrentDatabaseInstance(t *testing.T) {"original": {ID: ast.NewNodeID(), RootID: ast.NewNodeID(), BoxID: boxID, HPath: "/Original"},"mirror": {ID: ast.NewNodeID(), RootID: ast.NewNodeID(), BoxID: boxID, HPath: "/Mirror"},} {- preview := newItemDocumentPreview(blockTree, boxID, template.SaveLocation.PathTemplate, "Child", false)- expectedHPath := "/Original/Child"- if "mirror" == name {- expectedHPath = "/Mirror/Child"- }- if expectedHPath != preview.HPath || blockTree.RootID != preview.parentID {- t.Fatalf("%s database instance resolved to unexpected parent: %+v", name, preview)+ title := "Child"+ rendered, err := renderDocumentTarget(&EffectiveDocumentTarget{Notebook: boxID, Path: template.SaveLocation.PathTemplate},+ DocumentPlanRequest{Notebook: boxID, ContextID: &blockTree.RootID, Title: &title})+ if err != nil || rendered.parentID == nil || *rendered.parentID != blockTree.RootID || rendered.title != title {+ t.Fatalf("%s database instance resolved to unexpected parent: %+v, %v", name, rendered, err)}}}@@ -93,12 +82,12 @@ func TestNewItemDocumentPreviewUsesBoxDocAsLogicalRoot(t *testing.T) {HPath: "/File operation test",}- preview := newItemDocumentPreview(blockTree, fixture.box.ID, "2026/202608/", "Reference", false)- if "/2026/202608/Reference" != preview.HPath {- t.Fatalf("notebook document resolved to unexpected path: %+v", preview)- }- if "" != preview.parentID {- t.Fatalf("notebook document was used as a physical parent: %+v", preview)+ title := "Reference"+ rendered, err := renderDocumentTarget(&EffectiveDocumentTarget{Notebook: fixture.box.ID, Path: "2026/202608/"},+ DocumentPlanRequest{Notebook: fixture.box.ID, ContextID: &blockTree.RootID, Title: &title})+ if err != nil || len(rendered.parents) != 2 || rendered.parents[0] != "2026" || rendered.parents[1] != "202608" ||+ rendered.parentID != nil || rendered.title != title {+ t.Fatalf("notebook document was used as a physical parent: %+v, %v", rendered, err)}}diff --git a/kernel/model/backlink.go b/kernel/model/backlink.goindex a0e0e66c26..8573dcfc3b 100644--- a/kernel/model/backlink.go+++ b/kernel/model/backlink.go@@ -19,7 +19,6 @@ package modelimport ("bytes""fmt"- "path""sort""strings"@@ -752,7 +751,7 @@ func backlinkListPaths(blocks []*Block, boxID string) (ret []*Path) {}block := fromSQLBlock(root, "", 0)ret = append(ret, &Path{- ID: block.ID, Box: block.Box, Name: path.Base(block.HPath), HPath: block.HPath,+ ID: block.ID, Box: block.Box, Name: root.Content, HPath: block.HPath,NodeType: block.Type, Type: "backlink", SubType: block.SubType,Count: counts[block.ID], Updated: block.IAL["updated"], Created: block.ID[:14],})@@ -921,10 +920,11 @@ func matchBacklinkKeyword(block *Block, keywords []string) bool {return true}+ title := documentTitleText(block.Box, block.RootID)for _, k := range keywords {k = strings.ToLower(k)if strings.Contains(strings.ToLower(block.Content), k) ||- strings.Contains(strings.ToLower(path.Base(block.HPath)), k) ||+ strings.Contains(strings.ToLower(title), k) ||strings.Contains(strings.ToLower(block.Name), k) ||strings.Contains(strings.ToLower(block.Alias), k) ||strings.Contains(strings.ToLower(block.Memo), k) ||@@ -1046,7 +1046,7 @@ func buildTreeBackmentionInBox(defSQLBlock *sql.Block, refBlocks []*Block, keywoaliases = sql.QueryBlockAliasesInBox(defSQLBlock.ID, boxID)}if confSearchSnapshot.BacklinkMentionDoc {- fName = path.Base(defSQLBlock.HPath)+ fName = defSQLBlock.Content}rootID = defSQLBlock.ID} else {diff --git a/kernel/model/blockinfo.go b/kernel/model/blockinfo.goindex 919cac9e03..ec17ecbd73 100644--- a/kernel/model/blockinfo.go+++ b/kernel/model/blockinfo.go@@ -77,7 +77,7 @@ func GetDocInfoInBox(blockID, boxID string) (ret *BlockInfo, err error) {func getDocInfoByTree(blockID string, tree *parse.Tree) (ret *BlockInfo) {boxID := tree.Box- title := tree.Root.IALAttr("title")+ title := treenode.ReadDocumentTitle(tree.Root).Textret = &BlockInfo{ID: blockID, RootID: tree.Root.ID, Name: title}ret.IAL = parse.IAL2Map(tree.Root.KramdownIAL)scrollData := ret.IAL["scroll"]@@ -195,7 +195,7 @@ func GetDocsInfo(blockIDs []string, queryRefCount bool, queryAv bool) (rets []*Bif nil == tree {continue}- title := tree.Root.IALAttr("title")+ title := treenode.ReadDocumentTitle(tree.Root).Textret := &BlockInfo{ID: blockID, RootID: tree.Root.ID, Name: title}ret.IAL = parse.IAL2Map(tree.Root.KramdownIAL)scrollData := ret.IAL["scroll"]diff --git a/kernel/model/bookmark.go b/kernel/model/bookmark.goindex 75f3bde3bd..3b1e0a9769 100644--- a/kernel/model/bookmark.go+++ b/kernel/model/bookmark.go@@ -78,7 +78,7 @@ func RemoveBookmark(bookmark string) (err error) {if changed {generateTreeHistory(tree, historyDir)- util.PushEndlessProgress(fmt.Sprintf(Conf.Language(111), util.EscapeHTML(tree.Root.IALAttr("title"))))+ util.PushEndlessProgress(fmt.Sprintf(Conf.Language(111), util.EscapeHTML(treenode.ReadDocumentTitle(tree.Root).Text)))if err = writeTreeUpsertQueue(tree); err != nil {util.ClearPushProgress(100)return@@ -151,7 +151,7 @@ func RenameBookmark(oldBookmark, newBookmark string) (err error) {if changed {generateTreeHistory(tree, historyDir)- util.PushEndlessProgress(fmt.Sprintf(Conf.Language(111), util.EscapeHTML(tree.Root.IALAttr("title"))))+ util.PushEndlessProgress(fmt.Sprintf(Conf.Language(111), util.EscapeHTML(treenode.ReadDocumentTitle(tree.Root).Text)))if err = writeTreeUpsertQueue(tree); err != nil {util.ClearPushProgress(100)returndiff --git a/kernel/model/box.go b/kernel/model/box.goindex be8ab4f02a..912423d1fb 100644--- a/kernel/model/box.go+++ b/kernel/model/box.go@@ -398,6 +398,8 @@ func syncBoxConfCryptoBackup(boxID string, boxConf *conf.BoxConf) error {}func (box *Box) saveConf0(data []byte) error {+ unlock := filesys.LockDocumentConfiguration()+ defer unlock()if !ast.IsNodeIDPattern(box.ID) {return fmt.Errorf("invalid box ID [%s]", box.ID)}@@ -593,6 +595,25 @@ func (box *Box) ListFiles(path string) (ret []*FileInfo) {return}+// listFilesForIndex 传播任一目录的枚举失败,避免将不完整扫描发布为已就绪索引。+func (box *Box) listFilesForIndex(directory string) (ret []*FileInfo, err error) {+ files, _, err := box.Ls(directory)+ if err != nil {+ return nil, err+ }+ for _, file := range files {+ if file.isdir {+ children, walkErr := box.listFilesForIndex(file.path)+ if walkErr != nil {+ return nil, walkErr+ }+ ret = append(ret, children...)+ }+ ret = append(ret, file)+ }+ return+}+func (box *Box) listFiles(files, ret *[]*FileInfo) {for _, file := range *files {if file.isdir {@@ -691,21 +712,23 @@ func isSkipFile(filename string) bool {return strings.HasPrefix(filename, ".") || "node_modules" == filename || "dist" == filename || "target" == filename}-func moveTree(tree *parse.Tree) {+func moveTree(tree *parse.Tree) error {treenode.SetBlockTreePath(tree)sql.MoveTreeQueue(tree)box := Conf.Box(tree.Box)- subFiles := box.ListFiles(tree.Path)- luteEngine := util.NewLute()+ subFiles, err := box.listFilesForIndex(tree.Path)+ if err != nil {+ return err+ }for _, subFile := range subFiles {if !strings.HasSuffix(subFile.path, ".sy") {continue}- subTree, err := filesys.LoadTree(box.ID, subFile.path, luteEngine) // LoadTree 会重新构造 HPath+ subTree, _, err := filesys.ReadTreeSnapshot(box.ID, subFile.path) // 只读源快照重新构造 HPath,避免持有源提交锁时触发修复写入if err != nil {- continue+ return err}treenode.SetBlockTreePath(subTree)@@ -715,6 +738,7 @@ func moveTree(tree *parse.Tree) {}refreshDocInfoWithoutParent(tree)+ return nil}func parseKTree(kramdown []byte) (ret *parse.Tree) {diff --git a/kernel/model/box_conf_crypto.go b/kernel/model/box_conf_crypto.goindex aedbc90f2a..c9251c0d94 100644--- a/kernel/model/box_conf_crypto.go+++ b/kernel/model/box_conf_crypto.go@@ -17,8 +17,13 @@package modelimport (+ "bytes"+ "encoding/json""errors"+ "io""path/filepath"+ "reflect"+ "strings""github.com/88250/gulu""github.com/siyuan-note/filelock"@@ -27,9 +32,11 @@ import ()type encryptedBoxMetadata struct {- Icon string `json:"icon"`- Sort int `json:"sort"`- SortMode int `json:"sortMode"`+ Version int `json:"version,omitempty"`+ DocumentTargets *conf.DocumentTargets `json:"documentTargets,omitempty"`+ Icon string `json:"icon"`+ Sort int `json:"sort"`+ SortMode int `json:"sortMode"`}func encryptBoxMetadata(boxID string, boxConf *conf.BoxConf, dek []byte) error {@@ -41,6 +48,15 @@ func encryptBoxMetadata(boxID string, boxConf *conf.BoxConf, dek []byte) error {Sort: boxConf.Sort,SortMode: boxConf.SortMode,}+ targets := conf.DocumentTargets{Document: boxConf.DocCreateTarget,+ Reference: boxConf.RefCreateTarget, DailyNote: boxConf.DailyNoteTarget}+ if boxConf.MetadataVersion > 2 {+ return errors.New("unsupported encrypted notebook metadata version")+ }+ if boxConf.MetadataVersion == 2 || !targets.Empty() {+ metadata.Version = 2+ metadata.DocumentTargets = &targets+ }plaintext, err := gulu.JSON.MarshalJSON(metadata)if err != nil {return err@@ -62,12 +78,46 @@ func decryptBoxMetadata(boxID string, boxConf *conf.BoxConf, dek []byte) error {return err}metadata := &encryptedBoxMetadata{}- if err = gulu.JSON.UnmarshalJSON(plaintext, metadata); err != nil {+ decoder := json.NewDecoder(bytes.NewReader(plaintext))+ if token, err := decoder.Token(); err != nil || token != json.Delim('{') {+ return errors.New("invalid encrypted notebook metadata")+ }+ seen := map[string]bool{}+ for decoder.More() {+ token, err := decoder.Token()+ if err != nil {+ return err+ }+ name := strings.ToLower(token.(string))+ if seen[name] {+ return errors.New("duplicate encrypted notebook metadata field")+ }+ seen[name] = true+ if err = decoder.Decode(new(json.RawMessage)); err != nil {+ return err+ }+ }+ decoder = json.NewDecoder(bytes.NewReader(plaintext))+ decoder.DisallowUnknownFields()+ if err = decoder.Decode(metadata); err != nil {return err}+ if decoder.Decode(new(json.RawMessage)) != io.EOF {+ return errors.New("invalid encrypted notebook metadata suffix")+ }+ if metadata.Version != 0 && metadata.Version != 1 && metadata.Version != 2 ||+ metadata.Version < 2 && metadata.DocumentTargets != nil {+ return errors.New("unsupported encrypted notebook metadata version")+ }boxConf.Icon = filterBoxIcon(metadata.Icon)boxConf.Sort = metadata.SortboxConf.SortMode = metadata.SortMode+ boxConf.MetadataVersion = max(1, metadata.Version)+ boxConf.DocCreateTarget, boxConf.RefCreateTarget, boxConf.DailyNoteTarget = nil, nil, nil+ if metadata.DocumentTargets != nil {+ boxConf.DocCreateTarget, boxConf.RefCreateTarget, boxConf.DailyNoteTarget =+ metadata.DocumentTargets.Document, metadata.DocumentTargets.Reference, metadata.DocumentTargets.DailyNote+ }return nil}@@ -113,6 +163,8 @@ func prepareBoxConfForSave(boxID string, boxConf *conf.BoxConf) (*conf.BoxConf,if err := reuseBoxMetadataIfUnchanged(boxID, &persisted, dek); err != nil {return nil, err}+ } else if persisted.DocCreateTarget != nil || persisted.RefCreateTarget != nil || persisted.DailyNoteTarget != nil {+ return nil, errors.New("unlock the notebook before changing document targets")} else if len(persisted.BoxCrypt.Metadata) == 0 {existing, err := readRawBoxConf(boxID)if err != nil {@@ -137,9 +189,15 @@ func reuseBoxMetadataIfUnchanged(boxID string, boxConf *conf.BoxConf, dek []byte}if existing != nil && existing.Encrypted && existing.BoxCrypt != nil && len(existing.BoxCrypt.Metadata) > 0 {decrypted := &conf.BoxConf{BoxCrypt: DeepCopyBoxEncryption(existing.BoxCrypt)}- if err = decryptBoxMetadata(boxID, decrypted, dek); err == nil &&- filterBoxIcon(decrypted.Icon) == filterBoxIcon(boxConf.Icon) &&- decrypted.Sort == boxConf.Sort && decrypted.SortMode == boxConf.SortMode {+ if err = decryptBoxMetadata(boxID, decrypted, dek); err != nil {+ return err+ }+ boxConf.MetadataVersion = max(boxConf.MetadataVersion, decrypted.MetadataVersion)+ if filterBoxIcon(decrypted.Icon) == filterBoxIcon(boxConf.Icon) &&+ decrypted.Sort == boxConf.Sort && decrypted.SortMode == boxConf.SortMode &&+ reflect.DeepEqual(decrypted.DocCreateTarget, boxConf.DocCreateTarget) &&+ reflect.DeepEqual(decrypted.RefCreateTarget, boxConf.RefCreateTarget) &&+ reflect.DeepEqual(decrypted.DailyNoteTarget, boxConf.DailyNoteTarget) {boxConf.BoxCrypt.Metadata = append([]byte(nil), existing.BoxCrypt.Metadata...)return nil}@@ -148,6 +206,8 @@ func reuseBoxMetadataIfUnchanged(boxID string, boxConf *conf.BoxConf, dek []byte}func clearBoxMetadata(boxConf *conf.BoxConf) {+ boxConf.DocCreateTarget, boxConf.RefCreateTarget, boxConf.DailyNoteTarget = nil, nil, nil+ boxConf.MetadataVersion = 0boxConf.Icon = ""boxConf.Sort = 0boxConf.SortMode = util.SortModeFileTreediff --git a/kernel/model/box_conf_crypto_test.go b/kernel/model/box_conf_crypto_test.gonew file mode 100644index 0000000000..8a8fc3a813--- /dev/null+++ b/kernel/model/box_conf_crypto_test.go@@ -0,0 +1,205 @@+package model++import (+ "bytes"+ "encoding/json"+ "os"+ "path/filepath"+ "reflect"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestDocumentTargetEncryptedMetadataVersions(t *testing.T) {+ const boxID = "20261023050000-targets"+ dek := bytes.Repeat([]byte{0x31}, 32)+ key := util.DeriveSubKey(dek, "siyuan/box-metadata")+ defer zeroAndClear(key)+ wrap := func(payload string) *conf.BoxConf {+ t.Helper()+ ciphertext, err := util.EncryptWithAAD(key, []byte(payload), boxMetadataAAD(boxID))+ if err != nil {+ t.Fatal(err)+ }+ return &conf.BoxConf{Encrypted: true, BoxCrypt: &conf.BoxEncryption{Metadata: ciphertext}}+ }+ // 既有未版本化载荷保持相同认证用途和笔记本绑定,不按新版默认值重新解释。+ legacy := wrap(`{"icon":"1f4d4","sort":7,"sortMode":4}`)+ if err := decryptBoxMetadata(boxID, legacy, dek); err != nil || legacy.MetadataVersion != 1 || legacy.Icon != "1f4d4" || legacy.Sort != 7 {+ t.Fatalf("legacy metadata read failed: %+v, %v", legacy, err)+ }+ target := &conf.DocumentTarget{Version: 2, Notebook: boxID, Anchor: conf.DocumentTargetAnchor{Kind: "notebookRoot"},+ Parents: []string{"Private / parent"}, Title: "Private title", OnMissingParent: "create"}+ legacy.DocCreateTarget = target+ if err := encryptBoxMetadata(boxID, legacy, dek); err != nil {+ t.Fatal(err)+ }+ clearBoxMetadata(legacy)+ disk, _ := json.Marshal(legacy)+ if bytes.Contains(disk, []byte("Private")) || bytes.Contains(disk, []byte("docCreateTarget")) {+ t.Fatal("protected targets leaked into plaintext configuration")+ }+ if err := decryptBoxMetadata(boxID, legacy, dek); err != nil || legacy.MetadataVersion != 2 || legacy.DocCreateTarget.Title != target.Title {+ t.Fatalf("version 2 read failed: %+v, %v", legacy, err)+ }+ legacy.DocCreateTarget = nil+ if err := encryptBoxMetadata(boxID, legacy, dek); err != nil {+ t.Fatal(err)+ }+ if err := decryptBoxMetadata(boxID, legacy, dek); err != nil || legacy.MetadataVersion != 2 {+ t.Fatal("removing the last target downgraded the payload", err)+ }+ for _, payload := range []string{+ `{"version":3,"icon":"","sort":0,"sortMode":0}`,+ `{"icon":"","sort":0,"sortMode":0,"documentTargets":{}}`,+ `{"version":2,"icon":"","sort":0,"sortMode":0,"futureField":true}`,+ `{"version":3,"version":2,"icon":"","sort":0,"sortMode":0}`,+ `{"version":3,"Version":2,"icon":"","sort":0,"sortMode":0}`,+ `{"version":2,"icon":"","sort":0,"sortMode":0} {}`,+ } {+ future := wrap(payload)+ original := append([]byte(nil), future.BoxCrypt.Metadata...)+ if err := decryptBoxMetadata(boxID, future, dek); err == nil || !bytes.Equal(original, future.BoxCrypt.Metadata) {+ t.Fatal("unsupported metadata was accepted or changed")+ }+ }+ corrupt := wrap(`{"icon":"","sort":0,"sortMode":0}`)+ corrupt.BoxCrypt.Metadata[len(corrupt.BoxCrypt.Metadata)-1] ^= 1+ if err := decryptBoxMetadata(boxID, corrupt, dek); err == nil {+ t.Fatal("authentication failure was ignored")+ }+ if err := decryptBoxMetadata("20261023050001-another", legacy, dek); err == nil {+ t.Fatal("metadata moved across notebook identities")+ }+ previousData := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() { util.DataDir = previousData })+ name := filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json")+ if err := os.MkdirAll(filepath.Dir(name), 0755); err != nil {+ t.Fatal(err)+ }+ data, _ := json.Marshal(corrupt)+ if err := os.WriteFile(name, data, 0644); err != nil {+ t.Fatal(err)+ }+ if err := reuseBoxMetadataIfUnchanged(boxID, legacy, dek); err == nil {+ t.Fatal("save replaced metadata after authentication failure")+ }+ HideBoxConfSecret(legacy)+ if legacy.DocCreateTarget != nil || legacy.RefCreateTarget != nil || legacy.DailyNoteTarget != nil || legacy.BoxCrypt != nil {+ t.Fatal("non-administrator configuration leaked targets")+ }+}++func TestDocumentTargetEncryptedMetadataRecovery(t *testing.T) {+ oldConf, oldData, oldConfDir, oldHistory := Conf, util.DataDir, util.ConfDir, util.HistoryDir+ root := t.TempDir()+ util.DataDir, util.ConfDir, util.HistoryDir = filepath.Join(root, "data"), filepath.Join(root, "conf"), filepath.Join(root, "history")+ t.Cleanup(func() {+ Conf, util.DataDir, util.ConfDir, util.HistoryDir = oldConf, oldData, oldConfDir, oldHistory+ })+ for _, directory := range []string{util.DataDir, util.ConfDir, util.HistoryDir} {+ if err := os.MkdirAll(directory, 0755); err != nil {+ t.Fatal(err)+ }+ }+ Conf = NewAppConf()+ Conf.NotebookCrypto = conf.NewNotebookCrypto()+ Conf.Sync.Store(conf.NewSync())+ if err := EnableEncryptedNotebook("document-target-old-password"); err != nil {+ t.Fatal(err)+ }+ const boxID = "20261023090000-crypt01"+ oldKEK, err := deriveKEK("document-target-old-password")+ if err != nil {+ t.Fatal(err)+ }+ defer zeroAndClear(oldKEK)+ crypt, dek, err := WrapNewDEK(boxID, oldKEK)+ if err != nil {+ t.Fatal(err)+ }+ defer zeroAndClear(dek)+ target := &conf.DocumentTarget{Version: 2, Notebook: boxID, Anchor: conf.DocumentTargetAnchor{Kind: "notebookRoot"},+ Parents: []string{"Private parent"}, Title: "Private title", OnMissingParent: "create"}+ boxConf := conf.NewBoxConf()+ boxConf.Encrypted, boxConf.Closed, boxConf.BoxCrypt = true, true, crypt+ boxConf.DocCreateTarget, boxConf.RefCreateTarget, boxConf.DailyNoteTarget = target, target, target+ if err = encryptBoxMetadata(boxID, boxConf, dek); err != nil {+ t.Fatal(err)+ }+ metadata := bytes.Clone(boxConf.BoxCrypt.Metadata)+ clearBoxMetadata(boxConf)+ box := &Box{ID: boxID}+ if err = box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ removeEncryptedBoxLifecycle(boxID)+ runtimeEncryptedBoxes.Delete(boxID)+ runtimeNormalBoxes.Delete(boxID)+ })+ boxConf = box.GetConf()+ if boxConf.DocCreateTarget != nil || boxConf.RefCreateTarget != nil || boxConf.DailyNoteTarget != nil {+ t.Fatal("locked read exposed protected targets")+ }+ boxConf.Name = "Renamed while locked"+ if err = box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ raw, err := readRawBoxConf(boxID)+ if err != nil || !bytes.Equal(raw.BoxCrypt.Metadata, metadata) {+ t.Fatal("locked configuration save changed protected metadata", err)+ }+ boxConf.DocCreateTarget = target+ if err = box.SaveConf(boxConf); err == nil {+ t.Fatal("locked configuration accepted a protected target update")+ }+ if err = writeNotebookCryptBackup(boxID, raw.BoxCrypt); err != nil {+ t.Fatal(err)+ }+ salt := bytes.Clone(Conf.NotebookCrypto.MasterSalt)+ if err = ChangeMasterPassword("document-target-old-password", "document-target-new-password"); err != nil {+ t.Fatal(err)+ }+ if !bytes.Equal(salt, Conf.NotebookCrypto.MasterSalt) {+ t.Fatal("password change regenerated the master salt")+ }+ newKEK, err := deriveKEK("document-target-new-password")+ if err != nil {+ t.Fatal(err)+ }+ defer zeroAndClear(newKEK)+ check := func() {+ t.Helper()+ recoveredDEK, recoveredCrypt, decryptErr := decryptBoxCrypt(boxID, newKEK)+ if decryptErr != nil {+ t.Fatal(decryptErr)+ }+ defer zeroAndClear(recoveredDEK)+ if !bytes.Equal(dek, recoveredDEK) || !bytes.Equal(metadata, recoveredCrypt.Metadata) {+ t.Fatal("rewrapping or backup recovery changed document keys or metadata")+ }+ recovered := &conf.BoxConf{BoxCrypt: recoveredCrypt}+ if decryptErr = decryptBoxMetadata(boxID, recovered, recoveredDEK); decryptErr != nil || recovered.MetadataVersion != 2 ||+ !reflect.DeepEqual(recovered.DocCreateTarget, target) || !reflect.DeepEqual(recovered.RefCreateTarget, target) ||+ !reflect.DeepEqual(recovered.DailyNoteTarget, target) {+ t.Fatal("recovered metadata lost a structured target", decryptErr)+ }+ }+ check()+ confPath := filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json")+ for _, name := range []string{confPath, notebookCryptoBackupPath(boxID), dataCryptoBackupPath()} {+ data, readErr := os.ReadFile(name)+ if readErr != nil || bytes.Contains(data, []byte("Private")) || bytes.Contains(data, []byte("docCreateTarget")) {+ t.Fatal("configuration or backup leaked protected metadata", name, readErr)+ }+ }+ if err = os.Remove(confPath); err != nil {+ t.Fatal(err)+ }+ // 删除配置后只能从已认证的备份恢复相同 DEK 和目标载荷。+ check()+}diff --git a/kernel/model/box_doc.go b/kernel/model/box_doc.goindex 79a1a0d5f3..ff8f5d76ea 100644--- a/kernel/model/box_doc.go+++ b/kernel/model/box_doc.go@@ -249,7 +249,7 @@ func reconcileBoxDoc(box *Box, boxDocID string) error {if "" == title {title = Conf.Language(16)}- titleChanged := tree.Root.IALAttr("title") != title+ titleChanged := treenode.ReadDocumentTitle(tree.Root).Text != titlechanged := titleChanged || tree.HPath != "/"+title || tree.Root.IALAttr(DocHiddenAttr) != "true" ||tree.Root.IALAttr("icon") != boxConf.Iconif !changed {diff --git a/kernel/model/conf.go b/kernel/model/conf.goindex 5a83021fd6..b589a43f53 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -1167,6 +1167,7 @@ func InitBoxes() {}}+ recoverOpenedDocumentMetadata()recoverDocHPaths()logging.LogInfof("tree/block count [%d/%d]", treenode.CountTrees(), blockCount)}@@ -1270,6 +1271,7 @@ func HideConfSecret(c *AppConf) {func HideBoxConfSecret(c *conf.BoxConf) {if nil != c {c.BoxCrypt = nil+ c.DocCreateTarget, c.RefCreateTarget, c.DailyNoteTarget = nil, nil, nil}}diff --git a/kernel/model/conf_spec.go b/kernel/model/conf_spec.goindex 5fc30b621e..f5626891c2 100644--- a/kernel/model/conf_spec.go+++ b/kernel/model/conf_spec.go@@ -106,10 +106,15 @@ func applySectionLockedAt[C any](spec *SectionSpec[C], next, expected C, checkSoif current == nil {current = Conf}+ unlockTarget := func() {}+ if spec.Namespace == "fileTree" {+ unlockTarget = lockDocumentTargetConfiguration()+ }current.m.Lock()old := spec.Load()if checkSource && !reflect.DeepEqual(old, expected) {current.m.Unlock()+ unlockTarget()return nil, errConfSectionChanged}spec.Store(next)@@ -118,6 +123,7 @@ func applySectionLockedAt[C any](spec *SectionSpec[C], next, expected C, checkSocurrent.saveLocked()}current.m.Unlock()+ unlockTarget()for _, reaction := range spec.Reactions {if !reflect.ValueOf(old).IsZero() && reaction.Changed(old, next) {reaction.Apply(old, next)diff --git a/kernel/model/daily_note.go b/kernel/model/daily_note.goindex 3d4d622ff2..5f622355e7 100644--- a/kernel/model/daily_note.go+++ b/kernel/model/daily_note.go@@ -2,15 +2,13 @@ package modelimport ("errors"- "path""slices"- "strings""time"+ "github.com/88250/lute/ast""github.com/88250/lute/parse""github.com/siyuan-note/siyuan/kernel/sql""github.com/siyuan-note/siyuan/kernel/treenode"- "github.com/siyuan-note/siyuan/kernel/util")type DailyNoteInfo struct {@@ -22,27 +20,36 @@ type DailyNoteInfo struct {// resolveDailyNote 定位日期对应的文档;已有日记以认证后的源文档为准。func resolveDailyNote(box *Box, now time.Time, findByDate bool) (hPath string, tree *parse.Tree, err error) {+ plan, tree, err := resolveDailyNotePlan(box, now, findByDate)+ if plan != nil {+ hPath = plan.DisplayPath+ }+ return+}++func resolveDailyNotePlan(box *Box, now time.Time, findByDate bool) (plan *DocumentCreatePlan, tree *parse.Tree, err error) {boxConf := box.GetConf()- if boxConf.DailyNoteSavePath == "" || boxConf.DailyNoteSavePath == "/" {- return "", nil, errors.New(Conf.Language(49))+ if boxConf.DailyNoteTarget == nil && (boxConf.DailyNoteSavePath == "" || boxConf.DailyNoteSavePath == "/") {+ return nil, nil, errors.New(Conf.Language(49))+ }+ FlushTxQueue()+ if treenode.DocumentMetadataState(box.ID) != "ready" {+ if err = recoverDocumentMetadata(box.ID); err != nil {+ return+ }}- hPath, err = RenderGoTemplateAtInBox(boxConf.DailyNoteSavePath, now, box.ID)+ plan, err = PlanDocumentCreation(DocumentPlanRequest{Notebook: box.ID, Purpose: "dailyNote", ID: ast.NewNodeID(),+ Now: now, Reuse: true, SkipContentTemplateCheck: true})if err != nil {return}- hPath = util.TrimSpaceInPath(strings.TrimSuffix(hPath, ".sy"))- FlushTxQueue()- root := treenode.GetBlockTreeRootByHPath(box.ID, hPath)- rootID := ""- if root != nil {- rootID = root.RootID- }+ rootID := plan.ExistingIDfromDate := falsedate := now.Format("20060102")if findByDate {sql.FlushQueue()var ids []string- ids, err = sql.QueryDailyNoteRootIDsInBox(box.ID, DailyNoteAttrPrefix+date, date)+ ids, err = sql.QueryDailyNoteRootIDsInBox(plan.Notebook, DailyNoteAttrPrefix+date, date)if err != nil {return}@@ -61,9 +68,10 @@ func resolveDailyNote(box *Box, now time.Time, findByDate bool) (hPath string, tif err != nil {return}- if tree.Box != box.ID || (fromDate && tree.Root.IALAttr(DailyNoteAttrPrefix+date) != date) {- return "", nil, ErrBlockNotFound+ if tree.Box != plan.Notebook || (fromDate && tree.Root.IALAttr(DailyNoteAttrPrefix+date) != date) {+ return nil, nil, ErrBlockNotFound}+ plan.ExistingID, plan.Steps = tree.ID, nilreturn}@@ -73,13 +81,13 @@ func GetDailyNoteInfo(boxID string, date time.Time) (info *DailyNoteInfo, err erif box == nil {return nil, ErrBoxNotFound}- hPath, tree, err := resolveDailyNote(box, date, true)+ plan, tree, err := resolveDailyNotePlan(box, date, true)if err != nil {return nil, err}- info = &DailyNoteInfo{HPath: hPath, Title: path.Base(hPath)}+ info = &DailyNoteInfo{HPath: plan.DisplayPath, Title: plan.Title}if tree != nil {- info.ID, info.HPath, info.Title, info.Existed = tree.Root.ID, tree.HPath, tree.Root.IALAttr("title"), true+ info.ID, info.HPath, info.Title, info.Existed = tree.Root.ID, tree.HPath, treenode.ReadDocumentTitle(tree.Root).Text, true}return}diff --git a/kernel/model/document_addressing_file.go b/kernel/model/document_addressing_file.goindex 9985e66086..ab0434fd67 100644--- a/kernel/model/document_addressing_file.go+++ b/kernel/model/document_addressing_file.go@@ -113,8 +113,14 @@ func CheckDocumentAddressingFileWrite(absPath string, data []byte, directory booif err != nil || len(paths) == 0 {return err}- return documentaddressing.CheckBatch(util.DataDir, util.ConfDir, paths, nil,- func(string) ([]byte, error) { return data, nil })+ if err = documentaddressing.CheckBatch(util.DataDir, util.ConfDir, paths, nil,+ func(string) ([]byte, error) { return data, nil }); err != nil {+ return err+ }+ if isDocumentAddressingSource(paths) {+ return checkDocumentAddressingSourceOverwrite(absPath, data)+ }+ return nil}// CheckDocumentAddressingFileCopies 预检全部目标内容,拒绝不兼容批次时不复制任何文件。@@ -124,6 +130,7 @@ func CheckDocumentAddressingFileCopies(sources, destinations []string) error {return documentaddressing.ErrInvalid}upserts := map[string]string{}+ var documents [][2]stringfor i, source := range sources {if err := CheckDocumentAddressingPath(source); err != nil {return err@@ -158,6 +165,9 @@ func CheckDocumentAddressingFileCopies(sources, destinations []string) error {if pathErr != nil {return pathErr}+ if isDocumentAddressingSource(paths) {+ documents = append(documents, [2]string{name, dest})+ }for _, path := range paths {if previous := upserts[path]; previous != "" && previous != name &&(strings.HasSuffix(path, "/"+documentaddressing.ConfigPath) || strings.HasSuffix(path, "/"+documentaddressing.FloorPath)) {@@ -178,8 +188,20 @@ func CheckDocumentAddressingFileCopies(sources, destinations []string) error {for path := range upserts {paths = append(paths, path)}- return documentaddressing.CheckBatch(util.DataDir, util.ConfDir, paths, nil,- func(name string) ([]byte, error) { return filelock.ReadFile(upserts[name]) })+ if err := documentaddressing.CheckBatch(util.DataDir, util.ConfDir, paths, nil,+ func(name string) ([]byte, error) { return filelock.ReadFile(upserts[name]) }); err != nil {+ return err+ }+ for _, document := range documents {+ data, err := filelock.ReadFile(document[0])+ if err != nil {+ return err+ }+ if err = checkDocumentAddressingSourceOverwrite(document[1], data); err != nil {+ return err+ }+ }+ return nil}// CheckDocumentAddressingFileRemoval 保留整本删除语义;部分删除不能抹去能力记录。diff --git a/kernel/model/document_addressing_source.go b/kernel/model/document_addressing_source.gonew file mode 100644index 0000000000..cb612445e8--- /dev/null+++ b/kernel/model/document_addressing_source.go@@ -0,0 +1,233 @@+package model++import (+ "bytes"+ "errors"+ "io/fs"+ "os"+ "path/filepath"+ "runtime"+ "strings"++ "github.com/88250/gulu"+ "github.com/88250/lute/ast"+ "github.com/siyuan-note/filelock"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// isDocumentAddressingSource 只识别以笔记本及文档 ID 组成的源路径,附件中的同名扩展不属于文档。+func isDocumentAddressingSource(paths []string) bool {+ for _, name := range paths {+ if runtime.GOOS == "windows" {+ name = strings.ToLower(name)+ }+ if !strings.HasSuffix(name, ".sy") {+ continue+ }+ parts := strings.Split(strings.TrimSuffix(name, ".sy"), "/")+ valid := len(parts) > 1+ for _, part := range parts {+ valid = valid && ast.IsNodeIDPattern(part)+ }+ if valid {+ return true+ }+ }+ return false+}++func checkDocumentAddressingSource(data []byte) error {+ return treenode.CheckSpecJSON(bytes.TrimPrefix(data, []byte("\xef\xbb\xbf")))+}++// checkDocumentAddressingSourceOverwrite 在创建目录及写入批次前检查新旧文档;不修改原始字节。+func checkDocumentAddressingSourceOverwrite(absPath string, data []byte) error {+ if err := checkDocumentAddressingSource(data); err != nil {+ return err+ }+ current, err := filelock.ReadFile(absPath)+ if errors.Is(err, os.ErrNotExist) {+ return nil+ }+ if err != nil {+ return err+ }+ return checkDocumentAddressingSource(current)+}++// WriteFileWithDocumentAddressing 在文件锁内重新检查当前文档,再原样写入已验证的请求内容。+// 普通附件和插件文件保持原始文件写入语义;此函数不授予路径或加密笔记本访问权限。+func WriteFileWithDocumentAddressing(absPath string, data []byte) error {+ if err := CheckDocumentAddressingFileWrite(absPath, data, false); err != nil {+ return err+ }+ paths, err := documentAddressingDataPaths(absPath)+ if err != nil {+ return err+ }+ if !isDocumentAddressingSource(paths) {+ return filelock.WriteFile(absPath, data)+ }+ return filesys.MutateDocumentSources(documentSourcesFromPaths(paths), func() error {+ return util.WriteFileWithPreflight(absPath, data, false, func(current []byte) error {+ if current == nil {+ return nil+ }+ return checkDocumentAddressingSource(current)+ })+ })+}++func documentSourcesFromPaths(paths []string) (ret []*treenode.BlockTree) {+ for _, name := range paths {+ if runtime.GOOS == "windows" {+ name = strings.ToLower(name)+ }+ if !isDocumentAddressingSource([]string{name}) {+ continue+ }+ parts := strings.Split(name, "/")+ id := strings.TrimSuffix(parts[len(parts)-1], ".sy")+ ret = append(ret, &treenode.BlockTree{BoxID: parts[0], ID: id, RootID: id, Type: "d",+ Path: "/" + strings.Join(parts[1:], "/")})+ }+ return+}++// MutateDocumentAddressingFiles 在移动、删除前记录完整源集合;目标路径按源的相对位置映射。+func MutateDocumentAddressingFiles(source, destination string, mutate func() error) error {+ return filesys.MutateDocumentSourceSet(func() ([]*treenode.BlockTree, error) {+ return collectDocumentAddressingFiles(source, destination)+ }, mutate)+}++func collectDocumentAddressingFiles(source, destination string) ([]*treenode.BlockTree, error) {+ var documents []*treenode.BlockTree+ err := filepath.WalkDir(source, func(name string, entry fs.DirEntry, walkErr error) error {+ if walkErr != nil {+ return walkErr+ }+ if entry.IsDir() {+ return nil+ }+ paths, err := documentAddressingDataPaths(name)+ if err != nil {+ return err+ }+ documents = append(documents, documentSourcesFromPaths(paths)...)+ if destination != "" {+ relative, err := filepath.Rel(source, name)+ if err != nil {+ return err+ }+ paths, err = documentAddressingDataPaths(filepath.Join(destination, relative))+ if err != nil {+ return err+ }+ documents = append(documents, documentSourcesFromPaths(paths)...)+ }+ return nil+ })+ if err != nil {+ return nil, err+ }+ return documents, nil+}++// CopyFileWithDocumentAddressing 保留复制范围、权限和时间;文档使用已验证字节及受保护的目标写入。+// 调用方先检查整个请求批次,此处还会检查当前操作及实际读取的文档,拒绝检查后出现的不兼容源。+func CopyFileWithDocumentAddressing(source, destination string) error {+ if err := CheckDocumentAddressingFileCopies([]string{source}, []string{destination}); err != nil {+ return err+ }+ info, err := os.Stat(source)+ if err != nil {+ return err+ }+ if !info.IsDir() {+ return copyDocumentAddressingFile(source, destination)+ }+ paths, err := documentAddressingDataPaths(destination)+ if err != nil {+ return err+ }+ containsDocuments := false+ for _, name := range paths {+ if runtime.GOOS == "windows" {+ name = strings.ToLower(name)+ }+ valid := true+ for _, part := range strings.Split(name, "/") {+ valid = valid && (name == "" || ast.IsNodeIDPattern(part))+ }+ containsDocuments = containsDocuments || valid+ }+ if !containsDocuments {+ return filelock.Copy(source, destination)+ }+ if gulu.File.IsSubPath(source, destination) {+ return gulu.ErrCopyToSub+ }+ filelock.Lock(source)+ defer filelock.Unlock(source)+ return copyDocumentAddressingDirectory(source, destination)+}++func copyDocumentAddressingDirectory(source, destination string) error {+ info, err := os.Stat(source)+ if err != nil {+ return err+ }+ if err = os.MkdirAll(destination, 0755); err != nil {+ return err+ }+ entries, err := os.ReadDir(source)+ if err != nil {+ return err+ }+ for _, entry := range entries {+ src, dest := filepath.Join(source, entry.Name()), filepath.Join(destination, entry.Name())+ if entry.IsDir() {+ err = copyDocumentAddressingDirectory(src, dest)+ } else {+ err = copyDocumentAddressingFile(src, dest)+ }+ if err != nil {+ return err+ }+ }+ return os.Chtimes(destination, info.ModTime(), info.ModTime())+}++func copyDocumentAddressingFile(source, destination string) error {+ info, err := os.Lstat(source)+ if err != nil || info.Mode()&os.ModeSymlink != 0 {+ return err+ }+ paths, err := documentAddressingDataPaths(destination)+ if err != nil {+ return err+ }+ if !isDocumentAddressingSource(paths) {+ return filelock.Copy(source, destination)+ }+ data, err := filelock.ReadFile(source)+ if err != nil {+ return err+ }+ if err = CheckDocumentAddressingFileWrite(destination, data, false); err != nil {+ return err+ }+ if err = os.MkdirAll(filepath.Dir(destination), 0755); err != nil {+ return err+ }+ if err = WriteFileWithDocumentAddressing(destination, data); err != nil {+ return err+ }+ if err = os.Chmod(destination, info.Mode()); err != nil {+ return err+ }+ return os.Chtimes(destination, info.ModTime(), info.ModTime())+}diff --git a/kernel/model/document_addressing_source_test.go b/kernel/model/document_addressing_source_test.gonew file mode 100644index 0000000000..4dc0f9e41f--- /dev/null+++ b/kernel/model/document_addressing_source_test.go@@ -0,0 +1,204 @@+package model++import (+ "bytes"+ "errors"+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/siyuan-note/siyuan/kernel/documentaddressing"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func documentAddressingSourceWorkspace(t *testing.T) string {+ t.Helper()+ data, conf := util.DataDir, util.ConfDir+ util.DataDir, util.ConfDir = t.TempDir(), t.TempDir()+ t.Cleanup(func() { util.DataDir, util.ConfDir = data, conf })+ box := filepath.Join(util.DataDir, "20261022130000-source1")+ if err := os.MkdirAll(box, 0755); err != nil {+ t.Fatal(err)+ }+ return box+}++func writeDocumentAddressingSource(t *testing.T, name string, data []byte) {+ t.Helper()+ if err := os.MkdirAll(filepath.Dir(name), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(name, data, 0644); err != nil {+ t.Fatal(err)+ }+}++func TestDocumentAddressingRawSourceChanges(t *testing.T) {+ box := documentAddressingSourceWorkspace(t)+ destination := filepath.Join(box, "20261022130000-target1.sy")+ source := filepath.Join(t.TempDir(), "incoming.sy")+ ordinary := []byte(`{"Spec":"2","Properties":{"title":"Ordinary"}}`)+ future := []byte(`{"Spec":"999","Properties":{"title":"Future"}}`)+ conflict := []byte(`{"Spec":"2","Properties":{"title":"A/B"}}`)+ for _, mode := range []string{"write", "copy"} {+ t.Run(mode, func(t *testing.T) {+ writeDocumentAddressingSource(t, destination, ordinary)+ writeDocumentAddressingSource(t, source, ordinary)+ if err := CheckDocumentAddressingFileCopies([]string{source}, []string{destination}); err != nil {+ t.Fatal(err)+ }+ writeDocumentAddressingSource(t, destination, future)+ before, _ := os.Stat(destination)+ var err error+ if mode == "write" {+ err = WriteFileWithDocumentAddressing(destination, ordinary)+ } else {+ err = copyDocumentAddressingFile(source, destination)+ }+ if !errors.Is(err, treenode.ErrSpecTooNew) {+ t.Fatal("a changed destination bypassed source protection", err)+ }+ after, _ := os.Stat(destination)+ actual, _ := os.ReadFile(destination)+ if !bytes.Equal(actual, future) || !after.ModTime().Equal(before.ModTime()) {+ t.Fatal("a rejected write changed the destination")+ }+ })+ }+ writeDocumentAddressingSource(t, destination, ordinary)+ if err := CheckDocumentAddressingFileCopies([]string{source}, []string{destination}); err != nil {+ t.Fatal(err)+ }+ writeDocumentAddressingSource(t, source, conflict)+ if err := copyDocumentAddressingFile(source, destination); !errors.Is(err, documentaddressing.ErrModeConflict) {+ t.Fatal("copy used a source changed after batch preflight", err)+ }+ if actual, _ := os.ReadFile(destination); !bytes.Equal(actual, ordinary) {+ t.Fatal("changed incoming source replaced the destination")+ }+ missing := filepath.Join(box, "20261022130000-parent1", "20261022130000-child01.sy")+ if err := CheckDocumentAddressingFileWrite(missing, conflict, false); !errors.Is(err, documentaddressing.ErrModeConflict) {+ t.Fatal(err)+ }+ if _, err := os.Stat(filepath.Dir(missing)); !os.IsNotExist(err) {+ t.Fatal("source validation created a destination directory", err)+ }+}++func TestDocumentAddressingRawSourceDirectoryCopy(t *testing.T) {+ box := documentAddressingSourceWorkspace(t)+ source := t.TempDir()+ document := filepath.Join("20261022130000-parent1", "20261022130000-child01.sy")+ plain := []byte("\xef\xbb\xbf" + `{"Spec":"2","Properties":{"title":"A&#47;B"}}`)+ files := map[string][]byte{+ document: plain,+ "000-first.txt": []byte("original attachment"),+ filepath.Join("assets", "20261022130000-child01.sy"): []byte("arbitrary asset content"),+ }+ stamp := time.Unix(1750000000, 0)+ for name, data := range files {+ abs := filepath.Join(source, name)+ writeDocumentAddressingSource(t, abs, data)+ if err := os.Chtimes(abs, stamp, stamp); err != nil {+ t.Fatal(err)+ }+ }+ if err := os.Mkdir(filepath.Join(source, "empty"), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.Chtimes(source, stamp, stamp); err != nil {+ t.Fatal(err)+ }+ if err := CopyFileWithDocumentAddressing(source, box); err != nil {+ t.Fatal(err)+ }+ for name, expected := range files {+ data, err := os.ReadFile(filepath.Join(box, name))+ if err != nil || !bytes.Equal(data, expected) {+ t.Fatal("copy did not preserve source bytes", name, err)+ }+ original, _ := os.Stat(filepath.Join(source, name))+ copied, _ := os.Stat(filepath.Join(box, name))+ if original.Mode().Perm() != copied.Mode().Perm() || !original.ModTime().Equal(copied.ModTime()) {+ t.Fatal("copy changed source permissions or modification time", name)+ }+ }+ if info, err := os.Stat(filepath.Join(box, "empty")); err != nil || !info.IsDir() {+ t.Fatal("copy omitted an empty directory", err)+ }+ if info, _ := os.Stat(box); !info.ModTime().Equal(stamp) {+ t.Fatal("directory copy did not preserve modification time")+ }+ writeDocumentAddressingSource(t, filepath.Join(source, "000-first.txt"), []byte("new attachment"))+ writeDocumentAddressingSource(t, filepath.Join(source, document), []byte(`{"Spec":"999"}`))+ if err := CopyFileWithDocumentAddressing(source, box); !errors.Is(err, treenode.ErrSpecTooNew) {+ t.Fatal("directory copy accepted an incompatible descendant", err)+ }+ if data, _ := os.ReadFile(filepath.Join(box, "000-first.txt")); string(data) != "original attachment" {+ t.Fatal("directory copy partially wrote before checking descendants")+ }+ if data, _ := os.ReadFile(filepath.Join(box, document)); !bytes.Equal(data, plain) {+ t.Fatal("directory copy changed the existing document")+ }+}++func TestDocumentAddressingRawSourceAliases(t *testing.T) {+ documentAddressingRawSourceAliases(t, func(link, target string) {+ if err := os.Symlink(target, link); err != nil {+ t.Skipf("symbolic links unavailable: %v", err)+ }+ })+}++func TestDocumentAddressingRawSourceFileLink(t *testing.T) {+ box := documentAddressingSourceWorkspace(t)+ directory := t.TempDir()+ source := filepath.Join(directory, "source.sy")+ link := filepath.Join(directory, "link.sy")+ writeDocumentAddressingSource(t, source, []byte(`{"Spec":"999"}`))+ if err := os.Symlink(source, link); err != nil {+ t.Skipf("symbolic links unavailable: %v", err)+ }+ destination := filepath.Join(box, "20261022130000-target1.sy")+ original := []byte(`{"Spec":"2","Properties":{"title":"Original"}}`)+ writeDocumentAddressingSource(t, destination, original)+ if err := CheckDocumentAddressingFileCopies([]string{link}, []string{destination}); !errors.Is(err, treenode.ErrSpecTooNew) {+ t.Fatal("file link bypassed the preflight shared by copy and rename", err)+ }+ writeDocumentAddressingSource(t, source, []byte(`{"Spec":"2","Properties":{"title":"Incoming"}}`))+ if err := CopyFileWithDocumentAddressing(link, destination); err != nil {+ t.Fatal("compatible file link changed copy behavior", err)+ }+ if data, _ := os.ReadFile(destination); !bytes.Equal(data, original) {+ t.Fatal("ignored file link changed the existing document")+ }+}++func documentAddressingRawSourceAliases(t *testing.T, linkDirectory func(string, string)) {+ t.Helper()+ box := documentAddressingSourceWorkspace(t)+ alias := filepath.Join(t.TempDir(), "alias")+ linkDirectory(alias, box)+ name := "20261022130000-target1.sy"+ ordinary := []byte(`{"Spec":"2","Properties":{"title":"Ordinary"}}`)+ future := []byte(`{"Spec":"999","Properties":{"title":"Future"}}`)+ writeDocumentAddressingSource(t, filepath.Join(box, name), ordinary)+ if err := WriteFileWithDocumentAddressing(filepath.Join(alias, name), future); !errors.Is(err, treenode.ErrSpecTooNew) {+ t.Fatal("linked destination bypassed incoming document validation", err)+ }+ writeDocumentAddressingSource(t, filepath.Join(box, name), future)+ if err := WriteFileWithDocumentAddressing(filepath.Join(alias, name), ordinary); !errors.Is(err, treenode.ErrSpecTooNew) {+ t.Fatal("linked destination bypassed existing document validation", err)+ }+ dataAlias := filepath.Join(t.TempDir(), "data-alias")+ linkDirectory(dataAlias, util.DataDir)+ util.DataDir = dataAlias+ if err := WriteFileWithDocumentAddressing(filepath.Join(box, name), ordinary); !errors.Is(err, treenode.ErrSpecTooNew) {+ t.Fatal("linked workspace bypassed existing document validation", err)+ }+ if actual, _ := os.ReadFile(filepath.Join(box, name)); !bytes.Equal(actual, future) {+ t.Fatal("alias write replaced an incompatible source")+ }+}diff --git a/kernel/model/document_addressing_source_windows_test.go b/kernel/model/document_addressing_source_windows_test.gonew file mode 100644index 0000000000..1db0cc65a5--- /dev/null+++ b/kernel/model/document_addressing_source_windows_test.go@@ -0,0 +1,13 @@+package model++import (+ "testing"++ "github.com/siyuan-note/siyuan/kernel/internal/testutil"+)++func TestDocumentAddressingRawSourceJunctions(t *testing.T) {+ documentAddressingRawSourceAliases(t, func(link, target string) {+ testutil.Junction(t, link, target)+ })+}diff --git a/kernel/model/document_create.go b/kernel/model/document_create.gonew file mode 100644index 0000000000..2f24d539e2--- /dev/null+++ b/kernel/model/document_create.go@@ -0,0 +1,332 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package model++import (+ "errors"+ "os"+ "path"+ "path/filepath"+ "strings"+ "time"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/documentaddressing"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++type DocumentCreateRequest struct {+ Notebook string+ ParentID *string+ ID string+ TitleFormat string+ Title string+ Markdown string+ ExpectedParentRevision *string+ ExpectedTarget *DocumentTargetRevision+ NameConditions []treenode.DocumentNameCondition+ Tags string+ WithMath bool+ ClippingHref string+ Sorts []string+ SortTargetID string+ SortPosition string+ DocCreateTemplatePath string+ ListDocTree bool+ Attributes map[string]string+ TemplateTime *time.Time+ // DOM 仅供已有块身份的内核业务使用,不能经 Markdown 重解析重分配 ID。+ DOM *string+}++type DocumentCreateFailure struct {+ Reason string+ CommitState string+ ID string+ Stage string+ Completed []string+ Cause error+}++func (err *DocumentCreateFailure) Error() string { return err.Cause.Error() }+func (err *DocumentCreateFailure) Unwrap() error { return err.Cause }++func documentCreateFailure(err error, state, id, stage string, completed []string) error {+ reason := "writeFailed"+ var addressingErr *DocumentAddressingError+ if errors.As(err, &addressingErr) {+ reason = addressingErr.Reason+ } else if errors.Is(err, documentaddressing.ErrModeConflict) {+ reason = "modeConflict"+ }+ return &DocumentCreateFailure{Reason: reason, CommitState: state, ID: id, Stage: stage,+ Completed: completed, Cause: err}+}++// documentCreateParent 只沿精确身份读取;不把正文块、外部笔记本或缺失父级转换成根位置。+func documentCreateParent(request *DocumentCreateRequest) (folder, revision string, ancestors map[string]bool, err error) {+ folder, revision = "/", documentRootRevision(request.Notebook)+ ancestors = map[string]bool{"": true}+ if request.ParentID == nil {+ return+ }+ parentID := *request.ParentID+ if !ast.IsNodeIDPattern(parentID) {+ err = documentAddressingError("parentUnavailable", errors.New("invalid parent document ID"))+ return+ }+ parent, readErr := treenode.GetDocumentPath(request.Notebook, parentID, request.Notebook, 1)+ if readErr != nil {+ err = documentAddressingError("parentUnavailable", readErr)+ return+ }+ if IsBoxDoc(request.Notebook, parentID) {+ return+ }+ folder, revision = strings.TrimSuffix(parent.Path, ".sy"), parent.Revision+ for _, segment := range parent.Segments {+ ancestors[segment.ID] = true+ }+ return+}++func checkDocumentCreatePlan(request *DocumentCreateRequest, folder string) error {+ if err := checkDocumentTargetRevision(request); err != nil {+ return err+ }+ if err := checkDocumentPathNotebook(request.Notebook); err != nil {+ return err+ }+ currentFolder, revision, ancestors, err := documentCreateParent(request)+ if err != nil {+ return err+ }+ if currentFolder != folder || request.ExpectedParentRevision != nil && *request.ExpectedParentRevision != revision {+ return documentAddressingError("planChanged", errors.New("parent document changed after planning"))+ }+ for i := range request.NameConditions {+ condition := &request.NameConditions[i]+ parentID := ""+ if condition.ParentID != nil {+ parentID = *condition.ParentID+ if IsBoxDoc(request.Notebook, parentID) {+ condition.ParentID, parentID = nil, ""+ }+ }+ if !ancestors[parentID] {+ return errors.New("name condition is outside the target ancestor chain")+ }+ if condition.Title == "" {+ return documentAddressingError("invalidTitle", errors.New("name condition title must not be empty"))+ }+ if err = ValidateDocumentTitle("plain", condition.Title); err != nil {+ return err+ }+ if condition.ExpectedID != nil && !ast.IsNodeIDPattern(*condition.ExpectedID) {+ return errors.New("invalid expected document ID")+ }+ }+ matched, err := treenode.CheckDocumentNameConditions(request.Notebook, request.Notebook, request.NameConditions)+ if err != nil {+ return documentAddressingError("indexUnavailable", err)+ }+ if !matched {+ return documentAddressingError("planChanged", errors.New("document name matches changed after planning"))+ }+ // 身份索引不是源存在性的替代品,避免外部移除文件后自动重建父目录。+ if folder != "/" {+ if _, err = filesys.ReadDocumentMetadataTree(request.Notebook, folder+".sy"); err != nil {+ return documentAddressingError("parentUnavailable", err)+ }+ }+ if request.SortTargetID != "" {+ target := treenode.GetBlockTreeInExactBox(request.SortTargetID, request.Notebook)+ if !isSortableDocument(target) || path.Dir(target.Path) != folder {+ return documentAddressingError("planChanged", errors.New("sort target is no longer a sibling"))+ }+ }+ return nil+}++// CreateDocByParent 先排空已排队编辑,再锁定父身份;源提交前在公共写入范围内复核名称条件。+// 源一旦提交就不删除或换 ID 重试,排序、正文模板失败返回可恢复的已提交状态。+func CreateDocByParent(request DocumentCreateRequest) (document *treenode.DocumentPath, err error) {+ return createDocByParent(request, false)+}++func createDocByParent(request DocumentCreateRequest, creationLocked bool) (document *treenode.DocumentPath, err error) {+ if !ast.IsNodeIDPattern(request.ID) || len(request.NameConditions) > 128 {+ return nil, errors.New("invalid document ID or too many name conditions")+ }+ if err = ValidateDocumentTitle(request.TitleFormat, request.Title); err != nil {+ return nil, documentCreateFailure(err, "none", "", "validate", []string{})+ }+ if len(request.Sorts) > 0 && request.SortTargetID != "" ||+ (request.SortTargetID == "") != (request.SortPosition == "") ||+ request.SortPosition != "" && request.SortPosition != "before" && request.SortPosition != "after" {+ return nil, errors.New("invalid or conflicting document sort options")+ }+ if err = AcquireEncryptedBoxOperation(request.Notebook); err != nil {+ return+ }+ defer ReleaseEncryptedBoxOperation(request.Notebook)+ if request.ExpectedTarget != nil && request.ExpectedTarget.Notebook != request.Notebook {+ if err = AcquireEncryptedBoxOperation(request.ExpectedTarget.Notebook); err != nil {+ return+ }+ defer ReleaseEncryptedBoxOperation(request.ExpectedTarget.Notebook)+ }+ if !creationLocked {+ createDocLock.Lock()+ defer createDocLock.Unlock()+ }+ var tree *parse.Tree+ var sourceAttempted, sourceWritten bool+ err = func() error {+ flushLock.Lock()+ defer flushLock.Unlock()+ for _, queued := range takeQueuedTransactions() {+ flushTx(queued)+ }+ hpathRefresh.Lock()+ defer hpathRefresh.Unlock()+ if err := checkDocumentPathNotebook(request.Notebook); err != nil {+ return err+ }+ if request.ID == request.Notebook || treenode.GetBlockTree(request.ID) != nil {+ return documentAddressingError("documentIDConflict", errors.New("document ID already exists"))+ }+ folder, _, _, err := documentCreateParent(&request)+ if err != nil {+ return err+ }+ if err = checkDocumentCreatePlan(&request, folder); err != nil {+ return err+ }+ p := path.Join(folder, request.ID+".sy")+ if _, statErr := os.Stat(filepath.Join(util.DataDir, request.Notebook, p)); !os.IsNotExist(statErr) {+ if statErr != nil {+ return statErr+ }+ return documentAddressingError("documentIDConflict", errors.New("document file already exists"))+ }+ validation, err := validateCreateDoc(request.Notebook, p, request.Title, request.Title == "")+ if err != nil {+ return err+ }+ luteEngine := util.NewLute()+ if request.WithMath {+ luteEngine.SetInlineMath(true)+ }+ luteEngine.SetHTMLTag2TextMark(true)+ if strings.HasPrefix(request.ClippingHref, "https://ld246.com/article/") ||+ strings.HasPrefix(request.ClippingHref, "https://liuyun.io/article/") {+ enableLuteInlineSyntax(luteEngine)+ }+ dom := markdownWithFootnotes2BlockDOM(luteEngine, request.Markdown)+ if request.DOM != nil {+ dom = *request.DOM+ }+ attrs := map[string]string{}+ for name, value := range request.Attributes {+ attrs[name] = value+ }+ if request.Tags != "" {+ tags := strings.Split(strings.ReplaceAll(strings.TrimSpace(request.Tags), ",", ","), ",")+ for i := range tags {+ tags[i] = strings.TrimSpace(tags[i])+ }+ attrs["tags"] = strings.Join(tags, ",")+ }+ tree, err = buildCreateDocTree(request.Notebook, validation, dom, attrs)+ if err != nil {+ return err+ }+ var writeErr error+ tx := &Transaction{DoOperations: []*Operation{{Action: "create", Tree: tree}}, fromAPI: true}+ tx.writeTransactionTree = func(source *parse.Tree) error {+ if source.ID != request.ID || source.Box != request.Notebook {+ return writeTreeUpsertQueueWithChanges(source, tx.treeIndexChanges(source))+ }+ size, saveErr := filesys.WriteTreeWithPreflight(source, func() error {+ if err := checkDocumentCreatePlan(&request, folder); err != nil {+ return err+ }+ if _, statErr := os.Stat(filepath.Join(util.DataDir, source.Box, source.Path)); !os.IsNotExist(statErr) {+ if statErr != nil {+ return statErr+ }+ return documentAddressingError("documentIDConflict", errors.New("document file already exists"))+ }+ sourceAttempted = true+ return nil+ })+ sourceWritten = saveErr == nil || size > 0+ if saveErr != nil {+ writeErr = saveErr+ return saveErr+ }+ sql.UpsertTreeQueueWithChanges(source, tx.treeIndexChanges(source))+ refreshDocInfoWithSize(source, size)+ refreshBoxDocInfo(source)+ return nil+ }+ if err = performTxSyncLocked(tx); err != nil {+ if writeErr != nil {+ return writeErr+ }+ return err+ }+ document, err = treenode.GetDocumentPath(tree.Box, tree.ID, tree.Box, 1)+ return err+ }()+ if err != nil {+ state, confirmedID := "none", ""+ completed := []string{}+ if tree != nil && sourceAttempted {+ if sourceWritten {+ state, confirmedID, completed = "committed", tree.ID, []string{"source"}+ } else if _, readErr := os.Stat(filepath.Join(util.DataDir, tree.Box, tree.Path)); !os.IsNotExist(readErr) {+ state = "unknown"+ } else {+ treenode.RemoveBlockTreesByRootID(tree.Box, tree.ID)+ }+ } else if tree != nil {+ if _, statErr := os.Stat(filepath.Join(util.DataDir, tree.Box, tree.Path)); os.IsNotExist(statErr) {+ treenode.RemoveBlockTreesByRootID(tree.Box, tree.ID)+ }+ }+ return nil, documentCreateFailure(err, state, confirmedID, "source", completed)+ }+ box := Conf.Box(tree.Box)+ PushCreate(box, tree.Path, map[string]any{"listDocTree": request.ListDocTree})+ IncSync()+ if request.SortTargetID != "" {+ _, err = ReorderDocs([]string{tree.ID}, request.SortTargetID, request.SortPosition)+ } else if len(request.Sorts) > 0 {+ err = changeFileTreeSort(tree.Box, request.Sorts)+ } else {+ position := "after"+ if *Conf.FileTree.Load().CreateDocAtTop {+ position = "before"+ }+ err = box.placeDocInSiblingOrder(path.Dir(tree.Path), tree.ID, "", position)+ }+ if err != nil {+ return nil, documentCreateFailure(err, "committed", tree.ID, "sort", []string{"source"})+ }+ if request.Markdown == "" && request.DOM == nil && request.DocCreateTemplatePath != "" {+ sql.FlushQueue()+ if err = applyDocContentTemplateAt(request.DocCreateTemplatePath, tree.ID, request.TemplateTime); err != nil {+ return nil, documentCreateFailure(err, "committed", tree.ID, "template", []string{"source", "sort"})+ }+ sql.FlushQueue()+ }+ return+}diff --git a/kernel/model/document_create_test.go b/kernel/model/document_create_test.gonew file mode 100644index 0000000000..9a9deac514--- /dev/null+++ b/kernel/model/document_create_test.go@@ -0,0 +1,171 @@+//go:build fts5++package model++import (+ "context"+ "errors"+ "os"+ "os/exec"+ "path"+ "path/filepath"+ "sync"+ "testing"+ "time"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestDocumentCreateByParent(t *testing.T) {+ if os.Getenv("SIYUAN_TEST_DOCUMENT_CREATE") != "1" {+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)+ defer cancel()+ cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestDocumentCreateByParent$", "-test.v")+ cmd.Env = append(os.Environ(), "SIYUAN_TEST_DOCUMENT_CREATE=1")+ if output, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("document creation subprocess: %v\n%s", err, output)+ }+ return+ }+ prepareHPathRefreshTest(t)+ t.Cleanup(backgroundRefreshWaitGroup.Wait)+ box := &Box{ID: ast.NewNodeID()}+ boxConf := conf.NewBoxConf()+ boxConf.Name, boxConf.Closed = "Creation", false+ if err := box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ parent := newHPathTestDoc(t, box.ID, "/", "Parent", 1)+ if err := treenode.SetDocumentMetadataState(box.ID, "ready"); err != nil {+ t.Fatal(err)+ }+ parentPath, err := treenode.GetDocumentPath(box.ID, parent.ID, box.ID, 1)+ if err != nil {+ t.Fatal(err)+ }+ request := DocumentCreateRequest{Notebook: box.ID, ParentID: &parent.ID, ID: ast.NewNodeID(),+ TitleFormat: "plain", Title: "**Literal & title**", Markdown: "Initial paragraph",+ ExpectedParentRevision: &parentPath.Revision,+ NameConditions: []treenode.DocumentNameCondition{{ParentID: &parent.ID, Title: "**Literal & title**"}}}+ document, err := CreateDocByParent(request)+ if err != nil || document.ID != request.ID || document.Title.Text != request.Title || document.Depth != 2 {+ t.Fatalf("create failed: %+v, %v", document, err)+ }+ loaded, err := filesys.LoadTree(box.ID, document.Path, util.NewLute())+ if err != nil || loaded.ID != request.ID || path.Dir(loaded.Path) != "/"+parent.ID {+ t.Fatalf("source identity changed: %+v, %v", loaded, err)+ }+ failure := func(request DocumentCreateRequest, reason string) {+ t.Helper()+ _, err := CreateDocByParent(request)+ var failed *DocumentCreateFailure+ if !errors.As(err, &failed) || failed.Reason != reason || failed.CommitState != "none" {+ t.Fatalf("want %s before source commit, got %#v, %v", reason, failed, err)+ }+ }+ failure(request, "documentIDConflict")+ request.ID = ast.NewNodeID()+ failure(request, "planChanged")+ request.NameConditions = nil+ if err = RenameDoc(box.ID, parent.Path, "Renamed"); err != nil {+ t.Fatal(err)+ }+ failure(request, "planChanged")+ request.ExpectedParentRevision = nil+ request.Title = ""+ document, err = CreateDocByParent(request)+ if err != nil || !document.Title.Empty || document.Title.Text == "" {+ t.Fatalf("empty title lost its explicit marker: %+v, %v", document, err)+ }+ request.ID, request.Title = ast.NewNodeID(), "Invalid/title"+ failure(request, "invalidTitle")+ request.TitleFormat = "markdown"+ failure(request, "unsupportedTitleFormat")+ request.TitleFormat, request.Title = "plain", "Title"+ missing := ast.NewNodeID()+ request.ParentID = &missing+ failure(request, "parentUnavailable")+ request.ParentID = &parent.Root.FirstChild.ID+ failure(request, "parentUnavailable")+ // 两个请求共享不存在条件时,仅一个可以创建祖先,另一个必须要求重新规划。+ var group sync.WaitGroup+ errorsByRequest := make([]error, 2)+ for i := range errorsByRequest {+ group.Add(1)+ go func(i int) {+ defer group.Done()+ _, errorsByRequest[i] = CreateDocByParent(DocumentCreateRequest{+ Notebook: box.ID, ParentID: &parent.ID, ID: ast.NewNodeID(), TitleFormat: "plain", Title: "Concurrent",+ NameConditions: []treenode.DocumentNameCondition{{ParentID: &parent.ID, Title: "Concurrent"}},+ })+ }(i)+ }+ group.Wait()+ succeeded, changed := 0, 0+ for _, createErr := range errorsByRequest {+ var failure *DocumentCreateFailure+ if createErr == nil {+ succeeded+++ } else if errors.As(createErr, &failure) && failure.Reason == "planChanged" && failure.CommitState == "none" {+ changed+++ } else {+ t.Fatalf("unexpected concurrent creation result: %v", createErr)+ }+ }+ if succeeded != 1 || changed != 1 {+ t.Fatalf("duplicate ancestor creation: %v", errorsByRequest)+ }+ target, err := GetDocCreateTarget(box.ID, "document")+ if err != nil {+ t.Fatal(err)+ }+ configured := DocumentCreateRequest{Notebook: box.ID, ID: ast.NewNodeID(), TitleFormat: "plain", Title: "Configured",+ ExpectedTarget: &DocumentTargetRevision{Notebook: box.ID, Purpose: "document", Revision: target.Revision}}+ boxConf.DocCreateTemplatePath = "Changed.md"+ if err = box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ failure(configured, "planChanged")+ target, err = GetDocCreateTarget(box.ID, "document")+ if err != nil {+ t.Fatal(err)+ }+ configured.ExpectedTarget.Revision = target.Revision+ boxConf.Sort+++ if err = box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ if _, err = CreateDocByParent(configured); err != nil {+ t.Fatal("unrelated configuration invalidated the target", err)+ }+ request.ParentID = nil+ request.DocCreateTemplatePath = "does-not-exist.md"+ request.Markdown = ""+ _, err = CreateDocByParent(request)+ var failed *DocumentCreateFailure+ if !errors.As(err, &failed) || failed.CommitState != "committed" || failed.ID != request.ID || failed.Stage != "template" {+ t.Fatalf("template failure lost committed identity: %#v, %v", failed, err)+ }+ if _, err = filesys.ReadDocumentMetadataTree(box.ID, "/"+request.ID+".sy"); err != nil {+ t.Fatal("template failure removed the committed document", err)+ }+ request.ID, request.DocCreateTemplatePath = ast.NewNodeID(), ""+ sortPath := filepath.Join(util.DataDir, box.ID, ".siyuan", "sort.json")+ if err = os.Remove(sortPath); err != nil {+ t.Fatal(err)+ }+ if err = os.Mkdir(sortPath, 0755); err != nil {+ t.Fatal(err)+ }+ _, err = CreateDocByParent(request)+ if !errors.As(err, &failed) || failed.CommitState != "committed" || failed.ID != request.ID || failed.Stage != "sort" {+ t.Fatalf("sort failure lost committed identity: %#v, %v", failed, err)+ }+ if _, err = filesys.ReadDocumentMetadataTree(box.ID, "/"+request.ID+".sy"); err != nil {+ t.Fatal("sort failure removed source", err)+ }+}diff --git a/kernel/model/document_metadata.go b/kernel/model/document_metadata.gonew file mode 100644index 0000000000..73d6799bb2--- /dev/null+++ b/kernel/model/document_metadata.go@@ -0,0 +1,95 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package model++import (+ "errors"++ "github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++// ReadDocumentTitle 从同一笔记本的索引或已认证源属性取得摘要,不从可读路径提取末段。+func ReadDocumentTitle(boxID, rootID string) (treenode.DocumentTitle, error) {+ if err := AcquireEncryptedBoxOperation(boxID); err != nil {+ return treenode.DocumentTitle{}, err+ }+ defer ReleaseEncryptedBoxOperation(boxID)+ if meta, err := treenode.GetDocumentMetadata(boxID, rootID); err == nil {+ return meta.Title, nil+ }+ root := treenode.GetBlockTreeInExactBox(rootID, boxID)+ if root == nil || root.Type != "d" {+ return treenode.DocumentTitle{}, ErrTreeNotFound+ }+ tree, err := filesys.ReadDocumentMetadataTree(boxID, root.Path)+ if err != nil {+ return treenode.DocumentTitle{}, err+ }+ return treenode.ReadDocumentTitle(tree.Root), nil+}++func documentTitleText(boxID, rootID string) string {+ title, err := ReadDocumentTitle(boxID, rootID)+ if err != nil {+ if !errors.Is(err, ErrTreeNotFound) {+ logging.LogWarnf("read document title [%s/%s] failed: %s", boxID, rootID, err)+ }+ return ""+ }+ return title.Text+}++// recoverDocumentMetadata 从经过认证的源属性补建新增索引,不修改已有文档内容或身份。+func recoverDocumentMetadata(boxID string) (err error) {+ if err := AcquireEncryptedBoxOperation(boxID); err != nil {+ return err+ }+ defer ReleaseEncryptedBoxOperation(boxID)+ // 全量源索引失败时不能只检查已存在的块行就宣告成功;缺失的源必须由重新索引处理。+ if treenode.DocumentMetadataState(boxID) == "error" {+ return treenode.ErrDocumentMetadataUnavailable+ }+ if err = treenode.SetDocumentMetadataState(boxID, "building"); err != nil {+ return err+ }+ defer func() {+ if err != nil {+ _ = treenode.SetDocumentMetadataState(boxID, "error")+ }+ }()+ pending, err := treenode.PendingDocumentMetadata(boxID)+ if err != nil {+ return err+ }+ for _, doc := range pending {+ if err = filesys.RecoverDocumentMetadataWrite(doc); err != nil {+ return err+ }+ }+ missing, err := treenode.MissingDocumentMetadata(boxID)+ if err != nil {+ return err+ }+ for _, doc := range missing {+ tree, readErr := filesys.ReadDocumentMetadataTree(boxID, doc.Path)+ if readErr != nil {+ return readErr+ }+ if err = treenode.RecoverDocumentMetadata(tree); err != nil {+ return err+ }+ }+ return treenode.SetDocumentMetadataState(boxID, "ready")+}++func recoverOpenedDocumentMetadata() {+ for _, box := range Conf.GetOpenedBoxes() {+ if err := recoverDocumentMetadata(box.ID); err != nil {+ logging.LogErrorf("recover document metadata [%s] failed: %s", box.ID, err)+ }+ }+}diff --git a/kernel/model/document_metadata_test.go b/kernel/model/document_metadata_test.gonew file mode 100644index 0000000000..d5c15195e5--- /dev/null+++ b/kernel/model/document_metadata_test.go@@ -0,0 +1,153 @@+//go:build fts5++package model++import (+ "bytes"+ "context"+ "errors"+ "os"+ "os/exec"+ "path/filepath"+ "testing"+ "time"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/render"+ "github.com/siyuan-note/filelock"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestDocumentMetadataSourceRecovery(t *testing.T) {+ if os.Getenv("SIYUAN_TEST_DOCUMENT_METADATA") != "1" {+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)+ defer cancel()+ cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestDocumentMetadataSourceRecovery$", "-test.v")+ cmd.Env = append(os.Environ(), "SIYUAN_TEST_DOCUMENT_METADATA=1")+ if output, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("metadata source subprocess: %v\n%s", err, output)+ }+ return+ }+ prepareHPathRefreshTest(t)+ t.Cleanup(backgroundRefreshWaitGroup.Wait)+ box := &Box{ID: ast.NewNodeID()}+ boxConf := conf.NewBoxConf()+ boxConf.Name, boxConf.Closed = "Metadata", false+ if err := box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ tree := newHPathTestDoc(t, box.ID, "/", "Saved", 1)+ if err := treenode.SetDocumentMetadataState(box.ID, "ready"); err != nil {+ t.Fatal(err)+ }+ stale, source, err := filesys.LoadTreeSnapshot(box.ID, tree.Path, util.NewLute())+ if err != nil {+ t.Fatal(err)+ }+ tree.Root.SetIALAttr("title", "Current")+ tree.HPath = "/Current"+ if _, err = filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ current, _ := os.ReadFile(filepath.Join(util.DataDir, box.ID, tree.Path))+ stale.Root.SetIALAttr("title", "Rejected")+ treenode.UpsertBlockTreePending(stale)+ if _, err = filesys.WriteTreeIfUnchanged(stale, source); !errors.Is(err, util.ErrFileChanged) {+ t.Fatal("conditional save did not fail", err)+ }+ meta, err := treenode.GetDocumentMetadata(box.ID, tree.ID)+ if err != nil || meta.Title.Text != "Current" {+ t.Fatalf("failed source save published a title: %+v, %v", meta, err)+ }+ if err = recoverDocumentMetadata(box.ID); err != nil {+ t.Fatal(err)+ }+ meta, err = treenode.GetDocumentMetadata(box.ID, tree.ID)+ if err != nil || meta.Title.Text != "Current" || treenode.DocumentMetadataState(box.ID) != "ready" {+ t.Fatalf("recovery did not use authenticated source: %+v, %v", meta, err)+ }+ after, _ := os.ReadFile(filepath.Join(util.DataDir, box.ID, tree.Path))+ if !bytes.Equal(current, after) {+ t.Fatal("metadata recovery rewrote source content")+ }+ // 源已经落盘、摘要提交前中断,恢复时必须采用新源,而不是旧摘要或待写入意图。+ tree.Root.SetIALAttr("title", "Recovered source")+ luteEngine := util.NewLute()+ data := render.NewJSONRenderer(tree, luteEngine.RenderOptions, luteEngine.ParseOptions).Render()+ if _, err = treenode.BeginDocumentMetadataWrite(tree); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(filepath.Join(util.DataDir, box.ID, tree.Path), data, 0644); err != nil {+ t.Fatal(err)+ }+ if err = recoverDocumentMetadata(box.ID); err != nil {+ t.Fatal(err)+ }+ meta, err = treenode.GetDocumentMetadata(box.ID, tree.ID)+ if err != nil || meta.Title.Text != "Recovered source" {+ t.Fatalf("crash recovery retained old metadata: %+v, %v", meta, err)+ }+ // 从未创建成功的源不能因恢复而变成空文档。+ unwritten := treenode.NewTree(box.ID, "/"+ast.NewNodeID()+".sy", "/Unwritten", "Unwritten")+ treenode.UpsertBlockTreePending(unwritten)+ if _, err = treenode.BeginDocumentMetadataWrite(unwritten); err != nil {+ t.Fatal(err)+ }+ if err = recoverDocumentMetadata(box.ID); err != nil {+ t.Fatal(err)+ }+ if treenode.GetBlockTreeInExactBox(unwritten.ID, box.ID) != nil {+ t.Fatal("failed creation retained an addressable document")+ }+ // 原始文件接口也必须发布源标题,失败的移动保留原位置,成功移动及删除更新身份索引。+ tree.Root.SetIALAttr("title", "Raw source")+ data = render.NewJSONRenderer(tree, luteEngine.RenderOptions, luteEngine.ParseOptions).Render()+ sourcePath := filepath.Join(util.DataDir, box.ID, tree.Path)+ if err = WriteFileWithDocumentAddressing(sourcePath, data); err != nil {+ t.Fatal(err)+ }+ meta, err = treenode.GetDocumentMetadata(box.ID, tree.ID)+ if err != nil || meta.Title.Text != "Raw source" || treenode.DocumentMetadataState(box.ID) != "ready" {+ t.Fatalf("raw write left stale metadata: %+v, %v", meta, err)+ }+ parent := newHPathTestDoc(t, box.ID, "/", "Destination", 1)+ destination := filepath.Join(util.DataDir, box.ID, parent.ID, tree.ID+".sy")+ failedMove := errors.New("injected move failure")+ if err = MutateDocumentAddressingFiles(sourcePath, destination, func() error { return failedMove }); !errors.Is(err, failedMove) {+ t.Fatal(err)+ }+ meta, err = treenode.GetDocumentMetadata(box.ID, tree.ID)+ if err != nil || meta.Path != tree.Path || treenode.DocumentMetadataState(box.ID) != "ready" {+ t.Fatalf("failed move lost existing document: %+v, %v", meta, err)+ }+ if err = os.MkdirAll(filepath.Dir(destination), 0755); err != nil {+ t.Fatal(err)+ }+ if err = MutateDocumentAddressingFiles(sourcePath, destination, func() error {+ return filelock.RenameWithoutFatal(sourcePath, destination)+ }); err != nil {+ t.Fatal(err)+ }+ meta, err = treenode.GetDocumentMetadata(box.ID, tree.ID)+ if err != nil || meta.ParentID == nil || *meta.ParentID != parent.ID {+ t.Fatalf("raw move retained old parent: %+v, %v", meta, err)+ }+ if err = MutateDocumentAddressingFiles(destination, "", func() error {+ return filelock.RemoveWithoutFatal(destination)+ }); err != nil {+ t.Fatal(err)+ }+ if treenode.GetBlockTreeInExactBox(tree.ID, box.ID) != nil {+ t.Fatal("raw deletion retained document identity")+ }+ if err = treenode.SetDocumentMetadataState(box.ID, "error"); err != nil {+ t.Fatal(err)+ }+ if err = recoverDocumentMetadata(box.ID); !errors.Is(err, treenode.ErrDocumentMetadataUnavailable) {+ t.Fatal("failed full index was silently declared ready", err)+ }+}diff --git a/kernel/model/document_move.go b/kernel/model/document_move.gonew file mode 100644index 0000000000..56fae2ea52--- /dev/null+++ b/kernel/model/document_move.go@@ -0,0 +1,63 @@+package model++import (+ "fmt"+ "os"+ "path"+ "path/filepath"+ "strings"++ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// preflightDocumentMove 检查整棵子树,未知格式、认证失败和目标冲突都先于首次改动。+func preflightDocumentMove(fromBox, fromPath, toBox, toPath string) ([]*treenode.BlockTree, error) {+ if err := filesys.CheckDocumentAddressing(toBox); err != nil {+ return nil, err+ }+ if toPath != "/" {+ if _, err := filesys.ReadDocumentMetadataTree(toBox, toPath); err != nil {+ return nil, err+ }+ }+ paths, err := duplicateDocTreePaths(fromBox, fromPath)+ if err != nil {+ return nil, err+ }+ toFolder := strings.TrimSuffix(toPath, ".sy")+ destinationFolder := filepath.Join(util.DataDir, toBox, toFolder, util.GetTreeID(fromPath))+ if fromBox != toBox || path.Dir(fromPath) != toFolder {+ if _, err := os.Lstat(destinationFolder); !os.IsNotExist(err) {+ if err != nil {+ return nil, err+ }+ return nil, fmt.Errorf("document move destination directory already exists [%s]", util.GetTreeID(fromPath))+ }+ }+ var documents []*treenode.BlockTree+ for _, sourcePath := range paths {+ tree, _, err := filesys.ReadTreeSnapshot(fromBox, sourcePath)+ if err != nil {+ return nil, err+ }+ relative := strings.TrimPrefix(sourcePath, path.Dir(fromPath)+"/")+ if path.Dir(fromPath) == "/" {+ relative = strings.TrimPrefix(sourcePath, "/")+ }+ destination := path.Join(toFolder, relative)+ if fromBox != toBox || sourcePath != destination {+ if _, err := os.Lstat(filepath.Join(util.DataDir, toBox, destination)); !os.IsNotExist(err) {+ if err != nil {+ return nil, err+ }+ return nil, fmt.Errorf("document move destination already exists [%s]", tree.ID)+ }+ }+ documents = append(documents,+ &treenode.BlockTree{BoxID: fromBox, ID: tree.ID, RootID: tree.ID, Path: sourcePath, Type: "d"},+ &treenode.BlockTree{BoxID: toBox, ID: tree.ID, RootID: tree.ID, Path: destination, Type: "d"})+ }+ return documents, nil+}diff --git a/kernel/model/document_move_test.go b/kernel/model/document_move_test.gonew file mode 100644index 0000000000..681c8a430d--- /dev/null+++ b/kernel/model/document_move_test.go@@ -0,0 +1,112 @@+//go:build fts5++package model++import (+ "bytes"+ "context"+ "encoding/json"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestDocumentMovePreflightsEntireBatch(t *testing.T) {+ for _, conflict := range []string{"sourceSpec", "destinationDirectory"} {+ t.Run(conflict, func(t *testing.T) {+ fixture := setupFileOperationTest(t)+ first := addFileOperationTestDoc(t, fixture, ast.NewNodeID(), "First", false)+ childPath := "/" + fixture.sourceID + "/" + ast.NewNodeID() + ".sy"+ child := treenode.NewTree(fixture.box.ID, childPath, "/Source/Child", "Child")+ if _, err := filesys.WriteTree(child); err != nil {+ t.Fatal(err)+ }+ filename := filepath.Join(util.DataDir, fixture.box.ID, childPath)+ if conflict == "sourceSpec" {+ data, _ := os.ReadFile(filename)+ var fields map[string]json.RawMessage+ if err := json.Unmarshal(data, &fields); err != nil {+ t.Fatal(err)+ }+ fields["Spec"] = json.RawMessage(`"999"`)+ data, _ = json.Marshal(fields)+ if err := os.WriteFile(filename, data, 0644); err != nil {+ t.Fatal(err)+ }+ } else {+ if err := os.MkdirAll(filepath.Join(util.DataDir, fixture.box.ID, fixture.targetID, fixture.sourceID), 0755); err != nil {+ t.Fatal(err)+ }+ }+ before, _ := os.ReadFile(filename)+ if err := MoveDocs([]string{first.Path, fixture.sourcePath}, fixture.box.ID, fixture.targetPath, nil); err == nil {+ t.Fatal("incompatible later subtree did not reject the batch")+ }+ if _, err := os.Stat(filepath.Join(util.DataDir, fixture.box.ID, first.Path)); err != nil {+ t.Fatal("earlier source moved before complete preflight", err)+ }+ after, _ := os.ReadFile(filename)+ if !bytes.Equal(before, after) {+ t.Fatal("preflight changed source bytes")+ }+ })+ }+}++func TestDocumentMoveAcrossNotebooksPreservesMetadata(t *testing.T) {+ if os.Getenv("SIYUAN_TEST_DOCUMENT_MOVE") != "1" {+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)+ defer cancel()+ cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestDocumentMoveAcrossNotebooksPreservesMetadata$", "-test.v")+ cmd.Env = append(os.Environ(), "SIYUAN_TEST_DOCUMENT_MOVE=1")+ if output, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("document move subprocess: %v\n%s", err, output)+ }+ return+ }+ prepareHPathRefreshTest(t)+ t.Cleanup(backgroundRefreshWaitGroup.Wait)+ sourceBox := &Box{ID: ast.NewNodeID()}+ other := &Box{ID: ast.NewNodeID()}+ value := conf.NewBoxConf()+ value.Name, value.Closed = "Other", false+ for _, box := range []*Box{sourceBox, other} {+ if err := box.SaveConf(value); err != nil {+ t.Fatal(err)+ }+ }+ source := newHPathTestDoc(t, sourceBox.ID, "/", "Source", 1)+ child := newHPathTestDoc(t, sourceBox.ID, "/"+source.ID, "Child", 1)+ if err := MoveDocs([]string{source.Path}, other.ID, "/", nil); err != nil {+ t.Fatal(err)+ }+ document, err := treenode.GetDocumentPath(other.ID, source.ID, other.ID, 1)+ if err != nil || document.Title.Text != "Source" || document.ParentID != nil {+ t.Fatalf("moved identity disappeared during old-box journal recovery: %+v, %v", document, err)+ }+ if treenode.GetBlockTreeInExactBox(source.ID, sourceBox.ID) != nil {+ t.Fatal("old notebook retained the moved identity")+ }+ for _, boxID := range []string{sourceBox.ID, other.ID} {+ pending, err := treenode.PendingDocumentMetadata(boxID)+ if err != nil || len(pending) != 0 {+ t.Fatalf("move did not finish recovery for %s: %v, %v", boxID, pending, err)+ }+ }+ if strings.Contains(document.DisplayPath, source.ID) {+ t.Fatal("display title was derived from storage IDs")+ }+ childDocument, err := treenode.GetDocumentPath(other.ID, child.ID, other.ID, 1)+ if err != nil || childDocument.Depth != 2 || childDocument.ParentID == nil || *childDocument.ParentID != source.ID {+ t.Fatalf("descendant metadata was not moved: %+v, %v", childDocument, err)+ }+}diff --git a/kernel/model/document_path.go b/kernel/model/document_path.gonew file mode 100644index 0000000000..b551643342--- /dev/null+++ b/kernel/model/document_path.go@@ -0,0 +1,154 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package model++import (+ "database/sql"+ "errors"+ "fmt"+ "path"+ "unicode/utf8"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// documentParentDisplayPath 由存储身份取得父级展示文本,不从旧标题中的斜杠猜测层级。+func documentParentDisplayPath(boxID, documentPath string) (string, error) {+ parentPath := path.Dir(documentPath)+ if parentPath == "/" || parentPath == "." {+ return "", nil+ }+ if parent := treenode.GetBlockTreeInExactBox(util.GetTreeID(parentPath+".sy"), boxID); parent != nil {+ return parent.HPath, nil+ }+ hpath, _, err := filesys.ReadDocHPath(boxID, parentPath+".sy")+ return hpath, err+}++type DocumentAddressingError struct {+ Reason string+ Cause error+}++func (err *DocumentAddressingError) Error() string { return err.Cause.Error() }+func (err *DocumentAddressingError) Unwrap() error { return err.Cause }++func documentAddressingError(reason string, err error) error {+ return &DocumentAddressingError{Reason: reason, Cause: err}+}++func checkDocumentPathNotebook(boxID string) error {+ if !ast.IsNodeIDPattern(boxID) {+ return errors.New("invalid notebook ID")+ }+ if _, err := getOpenedBox(boxID); err != nil {+ return err+ }+ if err := filesys.CheckDocumentAddressing(boxID); err != nil {+ return err+ }+ if treenode.DocumentMetadataState(boxID) != "ready" {+ return documentAddressingError("indexUnavailable", treenode.ErrDocumentMetadataUnavailable)+ }+ return nil+}++// GetDocPaths 仅查询指定笔记本;缺失身份与索引、源格式错误分别返回。+func GetDocPaths(boxID string, ids []string) (documents []*treenode.DocumentPath, missing []string, err error) {+ if len(ids) == 0 || len(ids) > 128 {+ return nil, nil, errors.New("ids must contain 1 to 128 document IDs")+ }+ for _, id := range ids {+ if !ast.IsNodeIDPattern(id) {+ return nil, nil, errors.New("invalid document ID")+ }+ }+ if err = checkDocumentPathNotebook(boxID); err != nil {+ return+ }+ if err = AcquireEncryptedBoxOperation(boxID); err != nil {+ return+ }+ defer ReleaseEncryptedBoxOperation(boxID)+ documents, missing = []*treenode.DocumentPath{}, []string{}+ seen := map[string]bool{}+ for _, id := range ids {+ if seen[id] {+ continue+ }+ seen[id] = true+ document, readErr := treenode.GetDocumentPath(boxID, id, boxID, 1)+ if errors.Is(readErr, sql.ErrNoRows) {+ missing = append(missing, id)+ continue+ }+ if readErr != nil {+ return nil, nil, documentAddressingError("indexUnavailable", readErr)+ }+ documents = append(documents, document)+ }+ return+}++func documentRootRevision(boxID string) string {+ return treenode.DocumentRevision([]interface{}{1, boxID, 1, IsBoxDocEnabled()})+}++// ValidateDocumentTitle 校验新协议的完整输入,不通过截断、修剪或字符替换悄悄改变标题。+func ValidateDocumentTitle(format, text string) error {+ if format != "plain" {+ return documentAddressingError("unsupportedTitleFormat", errors.New("unsupported document title format"))+ }+ if !utf8.ValidString(text) || utf8.RuneCountInString(text) > 512 || text != normalizeDocTitle(text) || text == "." || text == ".." {+ return documentAddressingError("invalidTitle", errors.New("invalid document title"))+ }+ return nil+}++// ResolveDocPath 逐级精确匹配标题,不拆分标题内的字符,也不从同名候选中任取文档。+func ResolveDocPath(boxID, startKind string, startID *string, segments []string) (*treenode.ResolvedDocumentPath, error) {+ if len(segments) > 128 {+ return nil, errors.New("segments must contain at most 128 titles")+ }+ for _, segment := range segments {+ if err := ValidateDocumentTitle("plain", segment); err != nil {+ return nil, err+ }+ if segment == "" {+ return nil, documentAddressingError("invalidTitle", errors.New("empty ancestor title requires a document ID"))+ }+ }+ if startKind == "root" {+ if startID != nil {+ return nil, errors.New("root start must not contain a document ID")+ }+ } else if startKind != "document" || startID == nil || !ast.IsNodeIDPattern(*startID) {+ return nil, errors.New("invalid document path start")+ }+ if err := checkDocumentPathNotebook(boxID); err != nil {+ return nil, err+ }+ if err := AcquireEncryptedBoxOperation(boxID); err != nil {+ return nil, err+ }+ defer ReleaseEncryptedBoxOperation(boxID)+ if startID != nil && IsBoxDoc(boxID, *startID) {+ if bt := treenode.GetBlockTreeInExactBox(*startID, boxID); bt == nil || bt.Type != "d" {+ return nil, documentAddressingError("parentUnavailable", errors.New("notebook document is unavailable"))+ }+ startID = nil+ }+ ret, err := treenode.ResolveDocumentPath(boxID, startID, segments, boxID, documentRootRevision(boxID), 1)+ if errors.Is(err, sql.ErrNoRows) {+ return nil, documentAddressingError("parentUnavailable", fmt.Errorf("parent document is unavailable in notebook [%s]", boxID))+ }+ if err != nil {+ return nil, documentAddressingError("indexUnavailable", err)+ }+ return ret, nil+}diff --git a/kernel/model/document_path_test.go b/kernel/model/document_path_test.gonew file mode 100644index 0000000000..0145b6450f--- /dev/null+++ b/kernel/model/document_path_test.go@@ -0,0 +1,21 @@+package model++import (+ "testing"++ "github.com/siyuan-note/siyuan/kernel/treenode"+)++func TestDocumentRenameUsesStorageParentIdentity(t *testing.T) {+ fixture := setupFileOperationTest(t)+ tree := treenode.NewTree(fixture.box.ID, fixture.sourcePath, "/Old/title", "Old/title")+ if _, _, err := prepareDocRename(tree, "New"); err != nil || tree.HPath != "/New" {+ t.Fatalf("root title was mistaken for hierarchy: %q, %v", tree.HPath, err)+ }+ parent := treenode.NewTree(fixture.box.ID, fixture.targetPath, "/Parent/title", "Parent/title")+ treenode.UpsertBlockTree(parent)+ tree.Path, tree.HPath = "/"+parent.ID+fixture.sourcePath, "/Parent/title/New"+ if _, _, err := prepareDocRename(tree, "Again"); err != nil || tree.HPath != "/Parent/title/Again" {+ t.Fatalf("parent identity or literal display text was lost: %q, %v", tree.HPath, err)+ }+}diff --git a/kernel/model/document_plan.go b/kernel/model/document_plan.gonew file mode 100644index 0000000000..4023520dc2--- /dev/null+++ b/kernel/model/document_plan.go@@ -0,0 +1,368 @@+package model++import (+ "errors"+ "fmt"+ "os"+ "path"+ "path/filepath"+ "strings"+ "time"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++type DocumentPlanRequest struct {+ Notebook string+ Purpose string+ ContextID *string+ Title *string+ ID string+ Placement string+ Reuse bool+ Now time.Time+ SkipContentTemplateCheck bool+ // Target 供有独立保存配置的内核业务使用,不接受 HTTP 输入。+ Target *EffectiveDocumentTarget+}++type DocumentCreatePlan struct {+ Notebook string+ Title string+ ExistingID string+ DisplayPath string+ Steps []DocumentCreateRequest+}++type renderedDocumentTarget struct {+ parentID *string+ parents []string+ title string+ missing string+ legacy bool+}++func documentParentLocation(boxID string, id *string) (*string, error) {+ if id == nil || IsBoxDoc(boxID, *id) {+ return nil, nil+ }+ document, err := treenode.GetDocumentPath(boxID, *id, boxID, 1)+ if err != nil {+ return nil, documentAddressingError("parentUnavailable", err)+ }+ return document.ParentID, nil+}++// renderDocumentTarget 只对旧模板拆分渲染结果;版本 2 的每一段在同一时间快照独立求值。+func renderDocumentTarget(target *EffectiveDocumentTarget, request DocumentPlanRequest) (ret renderedDocumentTarget, err error) {+ ret.missing, ret.legacy = "create", target.Structured == nil+ if request.Now.IsZero() {+ request.Now = time.Now()+ }+ render := func(text string) (string, error) {+ if target.Rendered {+ return text, nil+ }+ return RenderGoTemplateAtInBox(text, request.Now, target.Notebook)+ }+ if target.Structured != nil {+ value := target.Structured+ if err = value.Validate(); err != nil {+ return+ }+ ret.missing = value.OnMissingParent+ if request.Placement == "child" {+ ret.parentID = request.ContextID+ if request.Title != nil {+ ret.title = *request.Title+ } else {+ ret.title, err = render(value.Title)+ }+ return+ }+ switch value.Anchor.Kind {+ case "document":+ ret.parentID = &value.Anchor.ID+ case "context":+ if target.Notebook != request.Notebook || request.ContextID == nil {+ return ret, errors.New("document target requires context in the target notebook")+ }+ ret.parentID = request.ContextID+ }+ for i := 0; i < value.Up; i++ {+ if ret.parentID == nil || IsBoxDoc(target.Notebook, *ret.parentID) {+ return ret, errors.New("document target goes above the notebook root")+ }+ if ret.parentID, err = documentParentLocation(target.Notebook, ret.parentID); err != nil {+ return+ }+ }+ for _, segment := range value.Parents {+ var rendered string+ if rendered, err = render(segment); err != nil {+ return+ }+ ret.parents = append(ret.parents, rendered)+ }+ if request.Title != nil {+ ret.title = *request.Title+ } else {+ ret.title, err = render(value.Title)+ }+ } else {+ var rendered string+ if rendered, err = render(target.Path); err != nil {+ return+ }+ rendered = strings.TrimSpace(strings.TrimSuffix(rendered, ".sy"))+ if target.Notebook == request.Notebook && !strings.HasPrefix(rendered, "/") {+ ret.parentID = request.ContextID+ }+ parts := strings.FieldsFunc(rendered, func(char rune) bool { return char == '/' })+ if rendered != "" && !strings.HasSuffix(rendered, "/") && len(parts) > 0 {+ ret.title, parts = parts[len(parts)-1], parts[:len(parts)-1]+ }+ if request.Title != nil {+ ret.title = *request.Title+ }+ ret.title = normalizeDocTitle(ret.title)+ if request.Placement == "child" {+ ret.parentID, ret.parents = request.ContextID, nil+ return+ }+ for _, segment := range parts {+ switch strings.TrimSpace(segment) {+ case ".", "":+ continue+ case "..":+ if len(ret.parents) > 0 {+ ret.parents = ret.parents[:len(ret.parents)-1]+ } else if ret.parentID, err = documentParentLocation(target.Notebook, ret.parentID); err != nil {+ return+ }+ default:+ ret.parents = append(ret.parents, normalizeDocTitle(segment))+ }+ }+ }+ // 兼容旧 parentID 优先规则:相同展示位置仍使用调用方的实际父身份。+ if ret.legacy && request.ContextID != nil && target.Notebook == request.Notebook && ret.parentID == nil {+ if current, readErr := treenode.GetDocumentPath(target.Notebook, *request.ContextID, target.Notebook, 1); readErr == nil &&+ current.DisplayPath == "/"+strings.Join(ret.parents, "/") {+ ret.parentID, ret.parents = request.ContextID, nil+ }+ }+ if ret.parentID != nil && IsBoxDoc(target.Notebook, *ret.parentID) {+ ret.parentID = nil+ }+ return+}++// PlanDocumentCreation 预先验证整组标题并分配全部 ID,不创建源文件或目录。+// 旧模板保留兼容模式的同名选择,新对象逐级拒绝歧义;执行仍按单篇提交并保留已完成结果。+func PlanDocumentCreation(request DocumentPlanRequest) (*DocumentCreatePlan, error) {+ if !ast.IsNodeIDPattern(request.ID) || request.ContextID != nil && !ast.IsNodeIDPattern(*request.ContextID) ||+ request.Placement != "" && request.Placement != "configured" && request.Placement != "child" {+ return nil, errors.New("invalid document creation context")+ }+ if err := AcquireEncryptedBoxOperation(request.Notebook); err != nil {+ return nil, err+ }+ defer ReleaseEncryptedBoxOperation(request.Notebook)+ var target *EffectiveDocumentTarget+ var err error+ if request.Target != nil {+ copyTarget := *request.Target+ target = ©Target+ } else {+ target, err = GetDocCreateTarget(request.Notebook, request.Purpose)+ if err != nil {+ return nil, err+ }+ }+ if request.Placement == "child" {+ target.Notebook = request.Notebook+ }+ if err = AcquireEncryptedBoxOperation(target.Notebook); err != nil {+ return nil, err+ }+ defer ReleaseEncryptedBoxOperation(target.Notebook)+ if err = checkDocumentPathNotebook(target.Notebook); err != nil {+ return nil, err+ }+ rendered, err := renderDocumentTarget(target, request)+ if err != nil {+ return nil, err+ }+ if err = ValidateDocumentTitle("plain", rendered.title); err != nil {+ return nil, err+ }+ for _, title := range rendered.parents {+ if title == "" {+ return nil, errors.New("document ancestor title must not be empty")+ }+ if err = ValidateDocumentTitle("plain", title); err != nil {+ return nil, err+ }+ }+ if target.DocCreateTemplatePath != "" && !request.SkipContentTemplateCheck {+ if _, err = resolveDocContentTemplatePath(target.DocCreateTemplatePath); err != nil {+ return nil, err+ }+ }+ plan := &DocumentCreatePlan{Notebook: target.Notebook, Title: rendered.title, Steps: []DocumentCreateRequest{}}+ parentID, revision, depth := rendered.parentID, documentRootRevision(target.Notebook), 0+ displayParents := []string{}+ if parentID != nil {+ parent, readErr := treenode.GetDocumentPath(target.Notebook, *parentID, target.Notebook, 1)+ if readErr != nil {+ return nil, documentAddressingError("parentUnavailable", readErr)+ }+ revision, depth = parent.Revision, parent.Depth+ for _, segment := range parent.Segments {+ displayParents = append(displayParents, segment.Text)+ }+ }+ plan.DisplayPath = "/" + strings.Join(append(append(displayParents, rendered.parents...), rendered.title), "/")+ conditions := []treenode.DocumentNameCondition{}+ expected := &DocumentTargetRevision{Notebook: request.Notebook, Purpose: request.Purpose, Revision: target.Revision}+ if request.Placement == "child" || target.Revision == "" {+ expected = nil+ }+ missing := false+ appendStep := func(id, title string, ancestor bool) {+ step := DocumentCreateRequest{Notebook: target.Notebook, ParentID: parentID, ID: id, TitleFormat: "plain", Title: title,+ ExpectedTarget: expected, NameConditions: append([]treenode.DocumentNameCondition{}, conditions...)}+ if !missing {+ value := revision+ step.ExpectedParentRevision = &value+ }+ if ancestor {+ step.NameConditions = append(step.NameConditions, treenode.DocumentNameCondition{ParentID: parentID, Title: title})+ } else {+ step.DocCreateTemplatePath = target.DocCreateTemplatePath+ }+ plan.Steps = append(plan.Steps, step)+ }+ for _, title := range rendered.parents {+ depth+++ if !missing {+ resolved, resolveErr := treenode.ResolveDocumentPath(target.Notebook, parentID, []string{title}, target.Notebook, documentRootRevision(target.Notebook), 1)+ if resolveErr != nil {+ return nil, resolveErr+ }+ if resolved.Status == "ambiguous" {+ if !rendered.legacy {+ return nil, documentAddressingError("planChanged", fmt.Errorf("ambiguous document ancestor [%s]", title))+ }+ resolved.Resolved = legacyDocumentCandidate(target.Notebook, resolved.Candidates)+ resolved.Status = "resolved"+ }+ if resolved.Status == "resolved" {+ id := resolved.Resolved.ID+ if !rendered.legacy {+ conditions = append(conditions, treenode.DocumentNameCondition{ParentID: parentID, Title: title, ExpectedID: &id})+ }+ parentID, revision = &id, resolved.Resolved.Revision+ continue+ }+ }+ if rendered.missing != "create" {+ return nil, documentAddressingError("parentUnavailable", fmt.Errorf("document ancestor [%s] does not exist", title))+ }+ id := ast.NewNodeID()+ appendStep(id, title, true)+ conditions = append(conditions, treenode.DocumentNameCondition{ParentID: parentID, Title: title, ExpectedID: &id})+ parentID, missing = &id, true+ }+ if depth+1 > 7 && !Conf.FileTree.Load().AllowCreateDeeper {+ return nil, errors.New(Conf.Language(118))+ }+ if request.Reuse && !missing && rendered.title != "" {+ resolved, resolveErr := treenode.ResolveDocumentPath(target.Notebook, parentID, []string{rendered.title}, target.Notebook, documentRootRevision(target.Notebook), 1)+ if resolveErr != nil {+ return nil, resolveErr+ }+ if resolved.Status == "resolved" {+ plan.ExistingID = resolved.Resolved.ID+ return plan, nil+ }+ if resolved.Status == "ambiguous" {+ if rendered.legacy {+ plan.ExistingID = legacyDocumentCandidate(target.Notebook, resolved.Candidates).ID+ return plan, nil+ }+ return nil, documentAddressingError("planChanged", errors.New("ambiguous document reuse target"))+ }+ }+ if request.ID == target.Notebook || treenode.GetBlockTree(request.ID) != nil ||+ treenode.GetBlockTreeInExactBox(request.ID, target.Notebook) != nil {+ return nil, documentAddressingError("documentIDConflict", errors.New("document ID already exists"))+ }+ appendStep(request.ID, rendered.title, false)+ plannedPaths, err := documentCreationPlanPaths(plan)+ if err != nil {+ return nil, err+ }+ for _, step := range plan.Steps {+ if _, statErr := os.Lstat(filepath.Join(util.DataDir, step.Notebook, plannedPaths[step.ID])); !os.IsNotExist(statErr) {+ if statErr != nil {+ return nil, statErr+ }+ return nil, documentAddressingError("documentIDConflict", errors.New("planned document file already exists"))+ }+ }+ return plan, nil+}++func documentCreationPlanPaths(plan *DocumentCreatePlan) (map[string]string, error) {+ paths := map[string]string{}+ for _, step := range plan.Steps {+ folder := "/"+ if step.ParentID != nil && !IsBoxDoc(step.Notebook, *step.ParentID) {+ parent := paths[*step.ParentID]+ if parent == "" {+ bt := treenode.GetBlockTreeInExactBox(*step.ParentID, step.Notebook)+ if bt == nil {+ return nil, ErrBlockNotFound+ }+ parent = bt.Path+ }+ folder = strings.TrimSuffix(parent, ".sy")+ }+ paths[step.ID] = path.Join(folder, step.ID+".sy")+ }+ return paths, nil+}++func legacyDocumentCandidate(boxID string, candidates []*treenode.DocumentPath) *treenode.DocumentPath {+ if previous := treenode.GetBlockTreeRootByHPath(boxID, candidates[0].DisplayPath); previous != nil {+ for _, candidate := range candidates {+ if candidate.ID == previous.ID {+ return candidate+ }+ }+ }+ return candidates[0]+}++// executeDocumentCreationPlan 保留已完成文档,下一步使用实际提交后的父版本,不重放正文副作用。+func executeDocumentCreationPlan(plan *DocumentCreatePlan, creationLocked bool) (*treenode.DocumentPath, error) {+ if plan.ExistingID != "" {+ return treenode.GetDocumentPath(plan.Notebook, plan.ExistingID, plan.Notebook, 1)+ }+ var last *treenode.DocumentPath+ for _, step := range plan.Steps {+ if last != nil && step.ParentID != nil && *step.ParentID == last.ID {+ step.ExpectedParentRevision = &last.Revision+ }+ document, err := createDocByParent(step, creationLocked)+ if err != nil {+ return last, err+ }+ last = document+ }+ return last, nil+}diff --git a/kernel/model/document_plan_batch.go b/kernel/model/document_plan_batch.gonew file mode 100644index 0000000000..dbeb9226dc--- /dev/null+++ b/kernel/model/document_plan_batch.go@@ -0,0 +1,41 @@+package model++// coalesceDocumentPlanAncestors 在同一次批量业务计划中合并缺失祖先,保留每篇最终文档的身份。+// 只合并原计划确认不存在的相同父身份和标题,不以展示路径推断相同位置。+func coalesceDocumentPlanAncestors(plans []*DocumentCreatePlan) {+ type key struct{ box, parent, title string }+ ancestors := map[key]string{}+ replacements := map[string]string{}+ replace := func(value *string) *string {+ if value != nil {+ if id, ok := replacements[*value]; ok {+ return &id+ }+ }+ return value+ }+ for _, plan := range plans {+ steps := make([]DocumentCreateRequest, 0, len(plan.Steps))+ for i, step := range plan.Steps {+ step.ParentID = replace(step.ParentID)+ for j := range step.NameConditions {+ step.NameConditions[j].ParentID = replace(step.NameConditions[j].ParentID)+ step.NameConditions[j].ExpectedID = replace(step.NameConditions[j].ExpectedID)+ }+ if i < len(plan.Steps)-1 {+ parent := ""+ if step.ParentID != nil {+ parent = *step.ParentID+ }+ identity := key{plan.Notebook, parent, step.Title}+ if id, exists := ancestors[identity]; exists {+ replacements[step.ID] = id+ continue+ }+ ancestors[identity] = step.ID+ }+ steps = append(steps, step)+ }+ plan.Steps = steps+ }+}diff --git a/kernel/model/document_plan_batch_test.go b/kernel/model/document_plan_batch_test.gonew file mode 100644index 0000000000..871bccda78--- /dev/null+++ b/kernel/model/document_plan_batch_test.go@@ -0,0 +1,29 @@+package model++import (+ "testing"++ "github.com/siyuan-note/siyuan/kernel/treenode"+)++func TestCoalesceDocumentPlanAncestors(t *testing.T) {+ parentA, parentB := "parentA", "parentB"+ childA, childB := "childA", "childB"+ plan := func(parent, child, final string) *DocumentCreatePlan {+ return &DocumentCreatePlan{Notebook: "box", Steps: []DocumentCreateRequest{+ {ID: parent, Title: "A/B"},+ {ID: child, ParentID: &parent, Title: "Child", NameConditions: []treenode.DocumentNameCondition{{Title: "A/B", ExpectedID: &parent}}},+ {ID: final, ParentID: &child, Title: "Final", NameConditions: []treenode.DocumentNameCondition{+ {Title: "A/B", ExpectedID: &parent}, {ParentID: &parent, Title: "Child", ExpectedID: &child}}},+ }}+ }+ first, second := plan(parentA, childA, "finalA"), plan(parentB, childB, "finalB")+ coalesceDocumentPlanAncestors([]*DocumentCreatePlan{first, second})+ if len(first.Steps) != 3 || len(second.Steps) != 1 || second.Steps[0].ID != "finalB" || *second.Steps[0].ParentID != childA {+ t.Fatalf("shared ancestors or final identities changed: %+v, %+v", first, second)+ }+ conditions := second.Steps[0].NameConditions+ if *conditions[0].ExpectedID != parentA || *conditions[1].ParentID != parentA || *conditions[1].ExpectedID != childA {+ t.Fatalf("name conditions still point at discarded planned identities: %+v", conditions)+ }+}diff --git a/kernel/model/document_plan_test.go b/kernel/model/document_plan_test.gonew file mode 100644index 0000000000..2967470578--- /dev/null+++ b/kernel/model/document_plan_test.go@@ -0,0 +1,192 @@+//go:build fts5++package model++import (+ "context"+ "os"+ "os/exec"+ "path"+ "testing"+ "time"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++func TestDocumentCreationPlans(t *testing.T) {+ if os.Getenv("SIYUAN_TEST_DOCUMENT_PLAN") != "1" {+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)+ defer cancel()+ cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestDocumentCreationPlans$", "-test.v")+ cmd.Env = append(os.Environ(), "SIYUAN_TEST_DOCUMENT_PLAN=1")+ if output, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("document planning subprocess: %v\n%s", err, output)+ }+ return+ }+ prepareHPathRefreshTest(t)+ t.Cleanup(backgroundRefreshWaitGroup.Wait)+ box := &Box{ID: ast.NewNodeID()}+ boxConf := conf.NewBoxConf()+ boxConf.Name, boxConf.Closed = "Plans", false+ if err := box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ parent := newHPathTestDoc(t, box.ID, "/", "Parent", 1)+ contextDoc := newHPathTestDoc(t, box.ID, "/"+parent.ID, "Context", 1)+ if err := treenode.SetDocumentMetadataState(box.ID, "ready"); err != nil {+ t.Fatal(err)+ }+ fixedNow := time.Date(2026, 10, 23, 23, 59, 59, 0, time.Local)+ for _, test := range []struct {+ name, template, title, parentID string+ }{+ {"empty is current child", "", "", contextDoc.ID},+ {"relative parent", "../Title", "Title", parent.ID},+ {"absolute root", "/Title", "Title", ""},+ {"trailing separator", "../", "", parent.ID},+ {"root ascent saturates", "../../../../Title", "Title", ""},+ {"time snapshot", "{{now | date \"2006-01-02\"}}", "2026-10-23", contextDoc.ID},+ } {+ t.Run(test.name, func(t *testing.T) {+ boxConf.DocCreateSavePath = test.template+ if err := box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ plan, err := PlanDocumentCreation(DocumentPlanRequest{Notebook: box.ID, Purpose: "document", ContextID: &contextDoc.ID,+ ID: ast.NewNodeID(), Now: fixedNow})+ if err != nil || len(plan.Steps) != 1 || plan.Title != test.title {+ t.Fatalf("unexpected plan: %+v, %v", plan, err)+ }+ step := plan.Steps[0]+ actual := ""+ if step.ParentID != nil {+ actual = *step.ParentID+ }+ if actual != test.parentID || step.ExpectedParentRevision == nil || step.ExpectedTarget == nil {+ t.Fatalf("identity or preview conditions lost: %+v", step)+ }+ })+ }+ boxConf.DocCreateSavePath = "/New ancestor/Second/Title"+ if err := box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ request := DocumentPlanRequest{Notebook: box.ID, Purpose: "document", ContextID: &contextDoc.ID, ID: ast.NewNodeID()}+ plan, err := PlanDocumentCreation(request)+ if err != nil || len(plan.Steps) != 3 {+ t.Fatalf("missing ancestor plan: %+v, %v", plan, err)+ }+ for _, step := range plan.Steps {+ if treenode.GetBlockTree(step.ID) != nil {+ t.Fatal("planning wrote a document")+ }+ }+ var last *treenode.DocumentPath+ for i, step := range plan.Steps {+ if last != nil {+ step.ExpectedParentRevision = &last.Revision+ }+ last, err = CreateDocByParent(step)+ if err != nil || last.ID != step.ID {+ t.Fatalf("step %d failed: %+v, %v", i, last, err)+ }+ }+ if last.Depth != 3 || path.Base(last.Path) != request.ID+".sy" {+ t.Fatal("plan changed final identity or depth", last)+ }+ request.Reuse = true+ plan, err = PlanDocumentCreation(request)+ if err != nil || plan.ExistingID != request.ID || len(plan.Steps) != 0 {+ t.Fatalf("explicit reuse did not find the planned document: %+v, %v", plan, err)+ }+ // 版本 2 保留渲染前的段边界,同一次求值的各段共享时间。+ structured := &EffectiveDocumentTarget{Notebook: box.ID, Structured: &conf.DocumentTarget{+ Version: 2, Notebook: box.ID, Anchor: conf.DocumentTargetAnchor{Kind: "context"}, Up: 1,+ Parents: []string{`{{printf "A/B"}}`, `{{now | date "2006-01-02"}}`},+ Title: `{{now | date "2006-01-02"}}`, OnMissingParent: "create",+ }}+ rendered, err := renderDocumentTarget(structured, DocumentPlanRequest{Notebook: box.ID, ContextID: &contextDoc.ID, Now: fixedNow})+ if err != nil || *rendered.parentID != parent.ID || len(rendered.parents) != 2 || rendered.parents[0] != "A/B" ||+ rendered.parents[1] != "2026-10-23" || rendered.title != "2026-10-23" {+ t.Fatalf("structured target lost boundaries or time: %+v, %v", rendered, err)+ }+ t.Run("legacy frontend parser compatibility", func(t *testing.T) {+ other := &Box{ID: ast.NewNodeID()}+ otherConf := conf.NewBoxConf()+ otherConf.Name, otherConf.Closed = "Other", false+ if err := other.SaveConf(otherConf); err != nil {+ t.Fatal(err)+ }+ if err := treenode.SetDocumentMetadataState(other.ID, "ready"); err != nil {+ t.Fatal(err)+ }+ // 对应原前端 parseNewDocTarget 的根、相对、容器、显式标题、跨本和文件树规则。+ for _, test := range []struct {+ template, title, placement, expected string+ root, cross, explicit bool+ }{+ {"", "", "", "/Parent/Context/", false, false, false},+ {"", "Named", "", "/Parent/Context/Named", false, false, true},+ {"", "", "", "/", true, false, false},+ {"", "Named", "", "/Named", true, false, true},+ {"/Folder/", "", "", "/Folder/", false, false, false},+ {"/Folder/", "Named", "", "/Folder/Named", false, false, true},+ {"/", "", "", "/", false, false, false},+ {"/Parent/", "", "", "/Parent/", false, false, false},+ {"Folder/", "", "", "/Parent/Context/Folder/", false, false, false},+ {"Folder/Sub/", "", "", "/Parent/Context/Folder/Sub/", false, false, false},+ {"../", "", "", "/Parent/", false, false, false},+ {"../", "Named", "", "/Parent/Named", false, false, true},+ {"../../", "", "", "/", false, false, false},+ {"../Folder/", "", "", "/Parent/Folder/", false, false, false},+ {"../../Folder/Sub/", "", "", "/Folder/Sub/", false, false, false},+ {"../", "", "", "/", true, false, false},+ {" Folder/ ", "", "", "/Parent/Context/Folder/", false, false, false},+ {"Named", "", "", "/Parent/Context/Named", false, false, false},+ {"Named", "Override", "", "/Parent/Context/Override", false, false, true},+ {" Named ", "", "", "/Parent/Context/Named", false, false, false},+ {"/Named", "", "", "/Named", false, false, false},+ {"/Named", "Override", "", "/Override", false, false, true},+ {"Folder/Named", "", "", "/Parent/Context/Folder/Named", false, false, false},+ {"/Folder/Named", "", "", "/Folder/Named", false, false, false},+ {"../Named", "", "", "/Parent/Named", false, false, false},+ {"../../Named", "", "", "/Named", false, false, false},+ {"../Folder/Named", "", "", "/Parent/Folder/Named", false, false, false},+ {"../Named", "", "", "/Named", true, false, false},+ {"Named", "", "", "/Named", false, true, false},+ {"Folder/Sub/", "", "", "/Folder/Sub/", false, true, false},+ {"../Named", "", "", "/Named", false, true, false},+ {"/Folder/Named", "", "", "/Folder/Named", false, true, false},+ {"", "Named", "", "/Named", true, true, true},+ {"", "", "", "/", false, true, false},+ {"", "Named", "", "/Named", false, true, true},+ {"", "", "child", "/Parent/Context/", false, false, false},+ {"", "Named", "child", "/Parent/Context/Named", false, false, true},+ {"Named", "", "child", "/Parent/Context/Named", false, false, false},+ {"Folder/Named", "", "child", "/Parent/Context/Named", false, false, false},+ {"/Named", "", "child", "/Parent/Context/Named", false, false, false},+ {"Folder/", "", "child", "/Parent/Context/", false, false, false},+ {"Folder/", "Named", "child", "/Parent/Context/Named", false, false, true},+ {"Named", "Override", "child", "/Override", true, false, true},+ } {+ request := DocumentPlanRequest{Notebook: box.ID, Purpose: "document", ContextID: &contextDoc.ID,+ ID: ast.NewNodeID(), Placement: test.placement, Target: &EffectiveDocumentTarget{Notebook: box.ID, Path: test.template}}+ if test.root {+ request.ContextID = nil+ }+ if test.cross {+ request.Target.Notebook = other.ID+ }+ if test.explicit {+ request.Title = &test.title+ }+ plan, err := PlanDocumentCreation(request)+ if err != nil || plan.DisplayPath != test.expected {+ t.Fatalf("legacy target %+v: %+v, %v", test, plan, err)+ }+ }+ })+}diff --git a/kernel/model/document_target.go b/kernel/model/document_target.gonew file mode 100644index 0000000000..33f9e7b17c--- /dev/null+++ b/kernel/model/document_target.go@@ -0,0 +1,143 @@+package model++import (+ "errors"+ "path/filepath"+ "strings"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/filelock"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/documentaddressing"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++type DocumentTargetRevision struct {+ Notebook string `json:"notebook"`+ Purpose string `json:"purpose"`+ Revision string `json:"revision"`+}++type EffectiveDocumentTarget struct {+ Notebook string+ Path string+ Structured *conf.DocumentTarget+ DocCreateTemplatePath string+ Revision string+ Rendered bool+}++func lockDocumentTargetConfiguration() func() { return filesys.LockDocumentConfiguration() }++func ValidateNotebookDocumentTarget(boxID string, target *conf.DocumentTarget) error {+ if err := target.Validate(); err != nil || target == nil {+ return err+ }+ mode, err := documentaddressing.ReadMode(boxID, func(name string) ([]byte, error) {+ return filelock.ReadFile(filepath.Join(util.DataDir, boxID, name))+ })+ if err != nil {+ return err+ }+ if mode != 2 {+ return errors.New("structured document targets require an enabled notebook")+ }+ return filesys.CheckDocumentAddressing(boxID)+}++// GetDocCreateTarget 只解析继承,不渲染模板;版本仅覆盖参与继承的目标和正文模板字段。+func GetDocCreateTarget(boxID, purpose string) (*EffectiveDocumentTarget, error) {+ if !ast.IsNodeIDPattern(boxID) || purpose != "document" && purpose != "reference" && purpose != "dailyNote" {+ return nil, errors.New("invalid document target source or purpose")+ }+ if err := AcquireEncryptedBoxOperation(boxID); err != nil {+ return nil, err+ }+ defer ReleaseEncryptedBoxOperation(boxID)+ box, err := getOpenedBox(boxID)+ if err != nil {+ return nil, err+ }+ if err = filesys.CheckDocumentAddressing(boxID); err != nil {+ return nil, err+ }+ boxConf, err := readRawBoxConf(box.ID)+ if err != nil {+ return nil, err+ }+ if boxConf == nil {+ return nil, errors.New("notebook configuration is missing")+ }+ if boxConf.Encrypted {+ dek, ok := cachedDEKCopy(box.ID)+ if !ok {+ return nil, errors.New("unlock the notebook before reading document targets")+ }+ defer zeroAndClear(dek)+ if err = decryptBoxMetadata(box.ID, boxConf, dek); err != nil {+ return nil, err+ }+ }+ global := Conf.LoadFileTree()+ ret := &EffectiveDocumentTarget{}+ var localBox, localPath, localTemplate, globalBox, globalPath, globalTemplate string+ switch purpose {+ case "document":+ localBox, localPath, localTemplate = boxConf.DocCreateSaveBox, boxConf.DocCreateSavePath, boxConf.DocCreateTemplatePath+ globalBox, globalPath, globalTemplate = global.DocCreateSaveBox, global.DocCreateSavePath, global.DocCreateTemplatePath+ ret.Structured = boxConf.DocCreateTarget+ case "reference":+ localBox, localPath = boxConf.RefCreateSaveBox, boxConf.RefCreateSavePath+ globalBox, globalPath = global.RefCreateSaveBox, global.RefCreateSavePath+ ret.Structured = boxConf.RefCreateTarget+ case "dailyNote":+ localBox, localPath, localTemplate = boxID, boxConf.DailyNoteSavePath, boxConf.DailyNoteTemplatePath+ ret.Structured = boxConf.DailyNoteTarget+ }+ ret.DocCreateTemplatePath = localTemplate+ if ret.DocCreateTemplatePath == "" {+ ret.DocCreateTemplatePath = globalTemplate+ }+ if ret.Structured != nil {+ if err = ret.Structured.Validate(); err != nil {+ return nil, err+ }+ ret.Notebook = ret.Structured.Notebook+ ret.Revision = treenode.DocumentRevision([]interface{}{1, boxID, purpose, ret.Structured, ret.DocCreateTemplatePath})+ return ret, nil+ }+ ret.Notebook, ret.Path = localBox, localPath+ if localBox == "" && localPath == "" {+ ret.Notebook = globalBox+ }+ if ret.Notebook == "" || Conf.Box(ret.Notebook) == nil {+ ret.Notebook = boxID+ }+ if ret.Path == "" {+ ret.Path = globalPath+ }+ ret.Path = strings.TrimSpace(ret.Path)+ if ret.Notebook != boxID && ret.Path != "" && !strings.HasPrefix(ret.Path, "/") {+ ret.Path = "/" + ret.Path+ }+ ret.Revision = treenode.DocumentRevision([]interface{}{1, boxID, purpose, ret.Notebook, ret.Path,+ ret.DocCreateTemplatePath, localBox, localPath, localTemplate})+ return ret, nil+}++func checkDocumentTargetRevision(request *DocumentCreateRequest) error {+ if request.ExpectedTarget == nil {+ return nil+ }+ expected := request.ExpectedTarget+ target, err := GetDocCreateTarget(expected.Notebook, expected.Purpose)+ if err != nil {+ return err+ }+ if target.Revision != expected.Revision || target.Notebook != request.Notebook {+ return documentAddressingError("planChanged", errors.New("document creation target changed after planning"))+ }+ return nil+}diff --git a/kernel/model/duplicate_doc_tree.go b/kernel/model/duplicate_doc_tree.goindex 48243eb466..b887c75c8b 100644--- a/kernel/model/duplicate_doc_tree.go+++ b/kernel/model/duplicate_doc_tree.go@@ -185,11 +185,15 @@ func prepareDuplicateDocTree(boxID, rootPath string) (*duplicateDocTreePlan, errtree.ID = tree.Root.IDtree.Root.RemoveIALAttr("scroll")if i == 0 {- title := tree.Root.IALAttr("title") + " (Duplicated " + time.Now().Format("2006-01-02 15:04:05") + ")"+ parentHPath, pathErr := documentParentDisplayPath(tree.Box, originalPath)+ if pathErr != nil {+ return nil, pathErr+ }+ title := treenode.ReadDocumentTitle(tree.Root).Text + " (Duplicated " + time.Now().Format("2006-01-02 15:04:05") + ")"tree.Root.SetIALAttr("title", title)- tree.HPath = path.Join(path.Dir(tree.HPath), title)+ tree.HPath = parentHPath + "/" + title} else {- tree.HPath = hpaths[path.Dir(originalPath)+".sy"] + "/" + tree.Root.IALAttr("title")+ tree.HPath = hpaths[path.Dir(originalPath)+".sy"] + "/" + treenode.ReadDocumentTitle(tree.Root).Text}hpaths[originalPath] = tree.HPathparts := strings.Split(strings.TrimSuffix(originalPath, ".sy"), "/")diff --git a/kernel/model/export.go b/kernel/model/export.goindex 741ddace5f..5ac8d1dffd 100644--- a/kernel/model/export.go+++ b/kernel/model/export.go@@ -18,7 +18,6 @@ package modelimport ("bytes"- "crypto/sha1""encoding/csv""encoding/json""errors"@@ -118,7 +117,7 @@ func ExportCodeBlock(blockID string) (filePath string, err error) {return errors.New("code block has no code node")}- name := tree.Root.IALAttr("title") + "-" + util.CurrentTimeSecondsStr() + ".txt"+ name := treenode.ReadDocumentTitle(tree.Root).Text + "-" + util.CurrentTimeSecondsStr() + ".txt"name = util.FilterFileName(name)exportFolder := filepath.Join(util.TempDir, "export")// 加密笔记本的导出归入 boxID 子目录,确保 LockBox 清理和服务端校验锁定状态@@ -475,7 +474,7 @@ func Export2Liandi(id string) (err error) {apiURL += "/" + articleId}- title := path.Base(tree.HPath)+ title := treenode.ReadDocumentTitle(tree.Root).Texttags := tree.Root.IALAttr("tags")content := exportMarkdownContent0(id, tree, markdownExportOptions{Config: conf.Export{@@ -685,7 +684,7 @@ func ExportSYs(ids []string) (zipPath string) {return}box := Conf.Box(block.BoxID)- baseFolderName := path.Base(block.HPath)+ baseFolderName := documentTitleText(block.BoxID, block.RootID)if "." == baseFolderName {baseFolderName = path.Base(block.Path)}@@ -1292,7 +1291,7 @@ func exportMarkdownHTML(id, savePath string, docx, merge bool, mergeHeadingOptioif nil != exportTreeErr {return exportTreeErr}- name = path.Base(tree.HPath)+ name = treenode.ReadDocumentTitle(tree.Root).Textname = util.FilterFileName(name) // 导出 PDF、HTML 和 Word 时未移除不支持的文件名符号 https://github.com/siyuan-note/siyuan/issues/5614savePath = strings.TrimSpace(savePath)@@ -1495,7 +1494,7 @@ func exportHTMLWithTitle(id, savePath string, pdf, keepFold, merge, addTitle booreturn exportTreeErr}adjustHeadingLevel(bt, tree, addTitle)- name = path.Base(tree.HPath)+ name = treenode.ReadDocumentTitle(tree.Root).Textname = util.FilterFileName(name) // 导出 PDF、HTML 和 Word 时未移除不支持的文件名符号 https://github.com/siyuan-note/siyuan/issues/5614if "" != savePath {@@ -2506,7 +2505,7 @@ func exportPandocConvertZipWithConfig(ids []string, pandocTo, ext string, configreturn}box := Conf.Box(block.BoxID)- baseFolderName := path.Base(block.HPath)+ baseFolderName := documentTitleText(block.BoxID, block.RootID)if "." == baseFolderName {baseFolderName = path.Base(block.Path)}@@ -2640,7 +2639,7 @@ func exportNotebookMarkdownPaths(boxes []*Box, trees map[string]*parse.Tree) mapret := map[string]string{}used := map[string]struct{}{}addBox := func(boxID, name string) {- name = util.FilterFileName(name)+ name = exportDocumentFileName(name, boxID)if name == "" {name = boxID}@@ -2894,12 +2893,12 @@ func exportSYZipWithConfig(boxID, rootDirPath, baseFolderName string, docPaths [}trees[tree.ID] = tree- util.PushEndlessProgress(Conf.language(65) + " " + fmt.Sprintf(Conf.language(70), fmt.Sprintf("%d/%d %s", i+1, len(docPaths), tree.Root.IALAttr("title"))))+ util.PushEndlessProgress(Conf.language(65) + " " + fmt.Sprintf(Conf.language(70), fmt.Sprintf("%d/%d %s", i+1, len(docPaths), treenode.ReadDocumentTitle(tree.Root).Text)))}count := 1for _, tree := range trees {- util.PushEndlessProgress(Conf.language(65) + " " + fmt.Sprintf(Conf.language(70), fmt.Sprintf("%d/%d %s", count, len(docPaths), tree.Root.IALAttr("title"))))+ util.PushEndlessProgress(Conf.language(65) + " " + fmt.Sprintf(Conf.language(70), fmt.Sprintf("%d/%d %s", count, len(docPaths), treenode.ReadDocumentTitle(tree.Root).Text)))refs := map[string]*parse.Tree{}exportRefTreesWithConfig(tree, &[]string{}, refs, config)@@ -3397,6 +3396,7 @@ func exportMarkdownContent(rootID string, exportOpts markdownExportOptions) (treReferences: references,FillCSSVar: false,BoxPaths: boxPaths,+ DocumentPaths: exportOpts.DocumentPaths,AVPublishFilter: nil,})docIAL := parse.IAL2Map(tree.Root.KramdownIAL)@@ -3469,6 +3469,9 @@ func exportMarkdownContent0(id string, tree *parse.Tree, exportOpts markdownExpo}currentDocPath := exportMarkdownHPath(tree.Box, tree.HPath, exportOpts.BoxPaths)+ if allocated := exportOpts.DocumentPaths.get(tree.Box, tree.ID); allocated != "" {+ currentDocPath = allocated+ }currentDocDir := path.Dir(currentDocPath)currentDocDir = util.FilterFilePath(currentDocDir)@@ -3520,6 +3523,9 @@ func exportMarkdownContent0(id string, tree *parse.Tree, exportOpts markdownExpo}if nil != bt {href = exportMarkdownHPath(bt.BoxID, bt.HPath+exportOpts.Ext, exportOpts.BoxPaths)+ if allocated := exportOpts.DocumentPaths.get(bt.BoxID, bt.RootID); allocated != "" {+ href = allocated+ }if "d" != bt.Type {href += "#" + defID}@@ -4333,7 +4339,7 @@ func resolveFootnotesDefs(refFootnoteOrder *[]string, refFootnotesByID map[strin}} else if ast.NodeDocument == defNode.Type {docTitle := &ast.Node{ID: defNode.ID, Type: ast.NodeHeading, HeadingLevel: 1}- docTitle.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(defNode.IALAttr("title"))})+ docTitle.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(treenode.ReadDocumentTitle(defNode).Text)})nodes = append(nodes, docTitle)for c := defNode.FirstChild; nil != c; c = c.Next {nodes = append(nodes, c)@@ -4738,7 +4744,12 @@ func exportPandocConvertZip0(exportOpts archiveExportOptions) (zipPath string) {return ""}}- wrotePathHash := map[string]string{}+ documentPaths, err := prepareExportDocumentPaths(exportOpts.DocPaths, exportOpts.BoxPaths, exportOpts.Ext)+ if err != nil {+ logging.LogErrorf("prepare document export paths failed: %s", err)+ util.PushErrMsg(err.Error(), 7000)+ return ""+ }assetsPathMap, err := allAssetAbsPaths()if nil != err {logging.LogWarnf("get assets abs path failed: %s", err)@@ -4752,29 +4763,16 @@ func exportPandocConvertZip0(exportOpts archiveExportOptions) (zipPath string) {rootID := util.GetTreeID(p)tree, md, isEmpty := exportMarkdownContent(rootID, markdownExportOptions{Config: exportOpts.Config, Ext: exportOpts.Ext, DefBlockIDs: exportOpts.DefBlockIDs,- References: references, BoxPaths: exportOpts.BoxPaths,+ References: references, BoxPaths: exportOpts.BoxPaths, DocumentPaths: documentPaths,})if nil == tree {continue}- hPath := exportMarkdownHPath(tree.Box, tree.HPath, exportOpts.BoxPaths)- dir, name = path.Split(hPath)- dir = util.FilterFilePath(dir) // 导出文档时未移除不支持的文件名符号 https://github.com/siyuan-note/siyuan/issues/4590- name = util.FilterFileName(name)- hPath = path.Join(dir, name)- p = hPath + exportOpts.Ext- if 1 == len(exportOpts.DocPaths) && len(exportOpts.BoxPaths) < 1 {- // 如果仅导出单个文档则使用文档标题作为文件名,不使用父路径 https://github.com/siyuan-note/siyuan/issues/13635#issuecomment-3794560233- p = name + exportOpts.Ext+ p = documentPaths.get(tree.Box, rootID)+ if p == "" {+ return ""}-writePath := filepath.Join(exportFolder, p)- hash := fmt.Sprintf("%x", sha1.Sum([]byte(md)))- if gulu.File.IsExist(writePath) && hash != wrotePathHash[writePath] {- // 重名文档加 ID- p = hPath + "-" + rootID + exportOpts.Ext- writePath = filepath.Join(exportFolder, p)- }writeFolder := filepath.Dir(writePath)if err := os.MkdirAll(writeFolder, 0755); err != nil {logging.LogErrorf("create export temp folder [%s] failed: %s", writeFolder, err)@@ -4840,7 +4838,6 @@ func exportPandocConvertZip0(exportOpts archiveExportOptions) (zipPath string) {continue}- wrotePathHash[writePath] = hashutil.PushEndlessProgress(Conf.language(65) + " " + fmt.Sprintf(Conf.language(70), fmt.Sprintf("%d/%d %s", i+1, len(exportOpts.DocPaths), name)))}@@ -5050,7 +5047,7 @@ func prepareExportTreesWithConfig(docPaths []string, config conf.Export, boxIDs}exportRefTreesWithConfig(tree, &defBlockIDs, trees, config)- util.PushEndlessProgress(Conf.language(65) + " " + fmt.Sprintf(Conf.language(70), fmt.Sprintf("%d/%d %s", i+1, len(docPaths), tree.Root.IALAttr("title"))))+ util.PushEndlessProgress(Conf.language(65) + " " + fmt.Sprintf(Conf.language(70), fmt.Sprintf("%d/%d %s", i+1, len(docPaths), treenode.ReadDocumentTitle(tree.Root).Text)))}for _, tree := range trees {diff --git a/kernel/model/export_document_paths.go b/kernel/model/export_document_paths.gonew file mode 100644index 0000000000..c09fb1fc74--- /dev/null+++ b/kernel/model/export_document_paths.go@@ -0,0 +1,180 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package model++import (+ "errors"+ "fmt"+ "path"+ "sort"+ "strings"+ "unicode"+ "unicode/utf8"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+ "golang.org/x/text/unicode/norm"+)++type exportDocumentIdentity struct{ box, id string }+type exportDocumentLocation struct {+ identity exportDocumentIdentity+ parent exportDocumentIdentity+ title string+}+type exportDocumentPaths map[exportDocumentIdentity]string++func (paths exportDocumentPaths) get(box, id string) string {+ return paths[exportDocumentIdentity{box, id}]+}++// exportDocumentFileName 把单个标题转换为单个文件名;不解释斜杠、点段或百分号编码。+func exportDocumentFileName(title, id string) string {+ name := strings.Map(func(r rune) rune {+ if r < 32 || r == 127 || strings.ContainsRune(`/\:*?"<>|`, r) {+ return '_'+ }+ return r+ }, title)+ name = strings.TrimRight(name, ". ")+ for len(name) > 120 {+ _, size := utf8.DecodeLastRuneInString(name)+ name = name[:len(name)-size]+ }+ name = strings.TrimRight(name, ". ")+ if name == "" {+ return id+ }+ stem := strings.ToUpper(strings.SplitN(name, ".", 2)[0])+ if stem == "CON" || stem == "PRN" || stem == "AUX" || stem == "NUL" ||+ (strings.HasPrefix(stem, "COM") || strings.HasPrefix(stem, "LPT")) &&+ strings.Contains("123456789¹²³", strings.TrimPrefix(strings.TrimPrefix(stem, "COM"), "LPT")) &&+ utf8.RuneCountInString(stem) == 4 {+ name = "_" + name+ }+ return name+}++func exportPathComparison(name string) string {+ return strings.Map(func(r rune) rune {+ minimum := r+ for folded := unicode.SimpleFold(r); folded != r; folded = unicode.SimpleFold(folded) {+ if folded < minimum {+ minimum = folded+ }+ }+ return minimum+ }, norm.NFC.String(name))+}++// allocateExportDocumentPaths 先分配完整映射,文件与目录在同一命名空间预留,结果不依赖遍历顺序或正文哈希。+func allocateExportDocumentPaths(locations []exportDocumentLocation, boxPaths map[string]string, ext string) (exportDocumentPaths, error) {+ if !strings.HasPrefix(ext, ".") || strings.ContainsAny(ext, `/\`) {+ return nil, errors.New("invalid export extension")+ }+ children := map[exportDocumentIdentity][]exportDocumentLocation{}+ for _, location := range locations {+ children[location.parent] = append(children[location.parent], location)+ }+ ret := exportDocumentPaths{}+ directories := map[exportDocumentIdentity]string{}+ // 多本导出按既有外层目录隔离;跨本引用未指定目录时仍共享根命名空间。+ usedByDirectory := map[string]map[string]bool{}+ var allocate func(exportDocumentIdentity, string) error+ allocate = func(parent exportDocumentIdentity, directory string) error {+ nodes := children[parent]+ sort.Slice(nodes, func(i, j int) bool {+ return nodes[i].identity.box+nodes[i].identity.id < nodes[j].identity.box+nodes[j].identity.id+ })+ used := usedByDirectory[exportPathComparison(directory)]+ if used == nil {+ used = map[string]bool{"assets": true}+ // 以同一种比较方式保留资源目录。+ used[exportPathComparison("assets")] = true+ usedByDirectory[exportPathComparison(directory)] = used+ }+ for _, node := range nodes {+ name := exportDocumentFileName(node.title, node.identity.id)+ candidate := name+ for suffix := 0; used[exportPathComparison(candidate)] || used[exportPathComparison(candidate+ext)]; suffix++ {+ candidate = name + "-" + node.identity.id+ if suffix > 0 {+ candidate += fmt.Sprintf("-%d", suffix)+ }+ }+ used[exportPathComparison(candidate)], used[exportPathComparison(candidate+ext)] = true, true+ directories[node.identity] = path.Join(directory, candidate)+ ret[node.identity] = directories[node.identity] + ext+ }+ for _, node := range nodes {+ if err := allocate(node.identity, directories[node.identity]); err != nil {+ return err+ }+ }+ return nil+ }+ boxes := map[string]bool{}+ for _, node := range locations {+ boxes[node.identity.box] = true+ }+ ids := make([]string, 0, len(boxes))+ for box := range boxes {+ ids = append(ids, box)+ }+ sort.Strings(ids)+ for _, box := range ids {+ directory := "/"+ if prefix := boxPaths[box]; prefix != "" {+ directory += exportDocumentFileName(prefix, box)+ }+ if err := allocate(exportDocumentIdentity{box: box}, directory); err != nil {+ return nil, err+ }+ }+ if len(ret) != len(locations) {+ return nil, errors.New("export document hierarchy is incomplete")+ }+ return ret, nil+}++func prepareExportDocumentPaths(docPaths []string, boxPaths map[string]string, ext string) (exportDocumentPaths, error) {+ nodes := map[exportDocumentIdentity]exportDocumentLocation{}+ for _, docPath := range docPaths {+ id := util.GetTreeID(docPath)+ tree, err := LoadTreeByBlockID(id)+ if err != nil {+ return nil, err+ }+ ids := strings.Split(strings.Trim(strings.TrimSuffix(tree.Path, ".sy"), "/"), "/")+ if len(docPaths) == 1 && len(boxPaths) == 0 {+ nodes[exportDocumentIdentity{tree.Box, id}] = exportDocumentLocation{+ identity: exportDocumentIdentity{tree.Box, id}, parent: exportDocumentIdentity{box: tree.Box},+ title: treenode.ReadDocumentTitle(tree.Root).Text}+ continue+ }+ parent := exportDocumentIdentity{box: tree.Box}+ for i, ancestorID := range ids {+ if !ast.IsNodeIDPattern(ancestorID) {+ return nil, errors.New("invalid export document data path")+ }+ identity := exportDocumentIdentity{tree.Box, ancestorID}+ if _, exists := nodes[identity]; !exists {+ source, readErr := filesys.ReadDocumentMetadataTree(tree.Box, "/"+strings.Join(ids[:i+1], "/")+".sy")+ if readErr != nil {+ return nil, readErr+ }+ nodes[identity] = exportDocumentLocation{identity: identity, parent: parent, title: treenode.ReadDocumentTitle(source.Root).Text}+ }+ parent = identity+ }+ }+ locations := make([]exportDocumentLocation, 0, len(nodes))+ for _, node := range nodes {+ locations = append(locations, node)+ }+ return allocateExportDocumentPaths(locations, boxPaths, ext)+}diff --git a/kernel/model/export_document_paths_fts5_test.go b/kernel/model/export_document_paths_fts5_test.gonew file mode 100644index 0000000000..189f653073--- /dev/null+++ b/kernel/model/export_document_paths_fts5_test.go@@ -0,0 +1,61 @@+//go:build fts5++package model++import (+ "path"+ "strings"+ "testing"++ "github.com/88250/lute/parse"+)++func TestExportDocumentPathsArchiveAndReferenceCollisions(t *testing.T) {+ const boxID = "20261023030000-export1"+ setupMarkdownReferencesTest(t, boxID)+ Conf.Export.Load().BlockRefMode = 4+ first := newFootnoteTestDoc(t, boxID, "Twin")+ second := newFootnoteTestDoc(t, boxID, "twin")+ child := newFootnoteTestDoc(t, boxID, "Child")+ child.Path, child.HPath = "/"+first.ID+"/"+child.ID+".sy", "/Twin/Child"+ first.Root.FirstChild.AppendChild(newFootnoteTestRef(second.Root.FirstChild.ID))+ child.Root.FirstChild.AppendChild(newFootnoteTestRef(second.Root.FirstChild.ID))+ for _, tree := range []*parse.Tree{first, second, child} {+ writeAssetDownloadDocumentTest(t, tree)+ }+ docPaths := []string{child.Path, first.Path, second.Path}+ paths, err := prepareExportDocumentPaths(docPaths, nil, ".md")+ if err != nil {+ t.Fatal(err)+ }+ archive := openExportArchive(t, exportPandocConvertZip0(archiveExportOptions{+ Config: resolveExportOptions(nil), BoxID: boxID, BaseFolderName: "Collisions", DocPaths: docPaths, Ext: ".md",+ }))+ seen := map[string]bool{}+ contents := map[string]string{}+ for _, file := range archive.File {+ if file.FileInfo().IsDir() {+ continue+ }+ key := exportPathComparison(file.Name)+ if seen[key] {+ t.Fatal("archive overwrote a filesystem-equivalent name", file.Name)+ }+ seen[key] = true+ contents[path.Base(file.Name)] = readZipFile(t, file, file.Name)+ }+ if len(contents) != 3 {+ t.Fatalf("distinct document identities were lost: %v", contents)+ }+ for _, source := range []*parse.Tree{first, child} {+ filename := paths.get(boxID, source.ID)+ md := contents[path.Base(filename)]+ href := exportMarkdownRelativePath(path.Dir(filename), paths.get(boxID, second.ID))+ if !strings.Contains(md, href+"#"+second.Root.FirstChild.ID) {+ t.Fatalf("reference used a display path instead of allocated filename %s: %s", href, md)+ }+ }+ if !strings.Contains(contents[path.Base(paths.get(boxID, second.ID))], `id="`+second.Root.FirstChild.ID+`"`) {+ t.Fatal("collision target lost its block anchor")+ }+}diff --git a/kernel/model/export_document_paths_test.go b/kernel/model/export_document_paths_test.gonew file mode 100644index 0000000000..736987201e--- /dev/null+++ b/kernel/model/export_document_paths_test.go@@ -0,0 +1,60 @@+package model++import (+ "path"+ "reflect"+ "slices"+ "strings"+ "testing"+ "unicode/utf8"+)++func TestExportDocumentPathsPreserveIdentityAndHierarchy(t *testing.T) {+ root := exportDocumentIdentity{box: "box"}+ a := exportDocumentIdentity{"box", "20261023090000-aaaaaaa"}+ b := exportDocumentIdentity{"box", "20261023090000-bbbbbbb"}+ c := exportDocumentIdentity{"box", "20261023090000-ccccccc"}+ d := exportDocumentIdentity{"box", "20261023090000-ddddddd"}+ e := exportDocumentIdentity{"box", "20261023090000-eeeeeee"}+ nodes := []exportDocumentLocation{{a, root, "Parent"}, {b, root, "parent"}, {c, b, "A/B"}, {d, root, "Parent.md"}, {e, root, "assets"}}+ paths, err := allocateExportDocumentPaths(nodes, nil, ".md")+ if err != nil {+ t.Fatal(err)+ }+ if paths[a] != "/Parent.md" || paths[b] == paths[a] || strings.Count(paths[c], "/") != 2 ||+ path.Dir(paths[c]) != strings.TrimSuffix(paths[b], ".md") || strings.TrimSuffix(paths[d], ".md") == paths[a] ||+ paths[e] == "/assets.md" {+ t.Fatalf("identity, hierarchy, or reserved directory lost: %#v", paths)+ }+ seen := map[string]bool{}+ for _, filename := range paths {+ key := exportPathComparison(filename)+ if seen[key] {+ t.Fatal("case-insensitive collision", paths)+ }+ seen[key] = true+ }+ slices.Reverse(nodes)+ reversed, err := allocateExportDocumentPaths(nodes, nil, ".md")+ if err != nil || !reflect.DeepEqual(paths, reversed) {+ t.Fatalf("export order changed allocation: %#v, %v", reversed, err)+ }+}++func TestExportDocumentFileNames(t *testing.T) {+ for _, title := range []string{"", ".", "..", "CON", "con.txt", "LPT1", "COM¹", "LPT².txt", "A/../B", `A\B:*?"<>|`, "end. ", strings.Repeat("界", 200)} {+ name := exportDocumentFileName(title, "20261023090000-aaaaaaa")+ if name == "" || name == "." || name == ".." || strings.ContainsAny(name, `/\:*?"<>|`) ||+ strings.TrimRight(name, ". ") != name || len(name) > 121 || !utf8.ValidString(name) {+ t.Fatalf("unsafe filename for %q: %q", title, name)+ }+ }+ for _, title := range []string{"CON", "COM1", "COM¹", "LPT².txt"} {+ if !strings.HasPrefix(exportDocumentFileName(title, "id"), "_") {+ t.Fatal("reserved Windows filename was not escaped", title)+ }+ }+ if exportPathComparison("e\u0301") != exportPathComparison("É") || exportPathComparison("ſ") != exportPathComparison("S") {+ t.Fatal("filesystem-equivalent names must share collision keys")+ }+}diff --git a/kernel/model/export_merge.go b/kernel/model/export_merge.goindex cb9377a531..6acec8136d 100644--- a/kernel/model/export_merge.go+++ b/kernel/model/export_merge.go@@ -146,7 +146,7 @@ func loadTreeNodes(box string, p string, level int, options MergeHeadingOptions,}heading := &ast.Node{ID: tree.Root.ID, Type: ast.NodeHeading, HeadingLevel: hLevel}- heading.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(tree.Root.IALAttr("title"))})+ heading.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(treenode.ReadDocumentTitle(tree.Root).Text)})tree.Root.PrependChild(heading)for c := tree.Root.FirstChild; nil != c; c = c.Next {ret = append(ret, c)diff --git a/kernel/model/export_options.go b/kernel/model/export_options.goindex ae2d3d761c..91a1b14e68 100644--- a/kernel/model/export_options.go+++ b/kernel/model/export_options.go@@ -42,6 +42,7 @@ type markdownExportOptions struct {DefBlockIDs []stringReferences *markdownExportReferencesBoxPaths map[string]string+ DocumentPaths exportDocumentPathsAVPublishFilter AVExportPublishFilterAccessCheckers []EmbedBlockAccessChecker}diff --git a/kernel/model/file.go b/kernel/model/file.goindex b3836d13ea..490042ccf9 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -278,7 +278,7 @@ func SearchDocs(keyword string, flashcard bool, excludeIDs []string) (ret []map[if 0 < len(keywords) {for _, box := range boxes {if containsSearchDocKeyword(box.Name, keywords, confSearchSnapshot.CaseSensitive) {- data := map[string]string{"path": "/", "hPath": box.Name + "/", "box": box.ID, "boxIcon": box.Icon}+ data := map[string]string{"path": "/", "hPath": box.Name + "/", "title": box.Name, "box": box.ID, "boxIcon": box.Icon}if flashcard {newFlashcardCount, dueFlashcardCount, flashcardCount := countBoxFlashcard(box.ID, deck, deckBlockIDs)if 1 > flashcardCount {@@ -296,7 +296,7 @@ func SearchDocs(keyword string, flashcard bool, excludeIDs []string) (ret []map[rootBlocks = queryRootBlocks(condition, keyword, confSearchSnapshot.Limit, args...)} else {for _, box := range boxes {- data := map[string]string{"path": "/", "hPath": box.Name + "/", "box": box.ID, "boxIcon": box.Icon}+ data := map[string]string{"path": "/", "hPath": box.Name + "/", "title": box.Name, "box": box.ID, "boxIcon": box.Icon}if flashcard {newFlashcardCount, dueFlashcardCount, flashcardCount := countBoxFlashcard(box.ID, deck, deckBlockIDs)if 1 > flashcardCount {@@ -321,7 +321,7 @@ func SearchDocs(keyword string, flashcard bool, excludeIDs []string) (ret []map[}hPath := b.Name + rootBlock.HPathdata := map[string]string{"path": rootBlock.Path, "hPath": hPath, "box": rootBlock.Box, "boxIcon": b.Icon,- "name": rootBlock.Name, "alias": rootBlock.Alias}+ "title": html.UnescapeString(rootBlock.Content), "name": rootBlock.Name, "alias": rootBlock.Alias}if flashcard {newFlashcardCount, dueFlashcardCount, flashcardCount := countTreeFlashcard(rootBlock.ID, deck, deckBlockIDs)if 1 > flashcardCount {@@ -1225,8 +1225,12 @@ func writeTreeUpsertQueue(tree *parse.Tree) (err error) {}func writeTreeUpsertQueueWithChanges(tree *parse.Tree, changes *sql.TreeIndexChanges) (err error) {+ return writeTreeUpsertQueueWithPreflight(tree, changes, nil)+}++func writeTreeUpsertQueueWithPreflight(tree *parse.Tree, changes *sql.TreeIndexChanges, preflight func() error) (err error) {isNew := !filelock.IsExist(filepath.Join(util.DataDir, tree.Box, tree.Path))- size, err := filesys.WriteTree(tree)+ size, err := filesys.WriteTreeWithPreflight(tree, preflight)if err != nil {return}@@ -1239,18 +1243,21 @@ func writeTreeUpsertQueueWithChanges(tree *parse.Tree, changes *sql.TreeIndexCha}func indexWriteTreeIndexQueue(tree *parse.Tree) (err error) {- treenode.IndexBlockTree(tree)_, err = filesys.WriteTree(tree)if err != nil {return}+ treenode.IndexBlockTree(tree)sql.IndexTreeQueue(tree)return}func indexWriteTreeUpsertQueue(tree *parse.Tree) (err error) {+ if err = writeTreeUpsertQueue(tree); err != nil {+ return+ }treenode.UpsertBlockTree(tree)- return writeTreeUpsertQueue(tree)+ return}func renameWriteJSONQueue(tree *parse.Tree) (err error) {@@ -1471,7 +1478,7 @@ func ResolveDocCreateSaveLocation(currentBoxID string) (boxID, pathTemplate striconst (DailyNoteAttrPrefix = "custom-dailynote-"- NodeAttrTitleEmpty = "custom-sy-title-empty"+ NodeAttrTitleEmpty = treenode.DocumentTitleEmptyAttrDocHiddenAttr = "custom-hidden")@@ -1494,8 +1501,7 @@ func createDailyNoteAt(boxID string, now time.Time, findByDate bool) (p string,return}- boxConf := box.GetConf()- hPath, existTree, err := resolveDailyNote(box, now, findByDate)+ plan, existTree, err := resolveDailyNotePlan(box, now, findByDate)if err != nil {return}@@ -1513,33 +1519,22 @@ func createDailyNoteAt(boxID string, now time.Time, findByDate bool) (p string,return}- id, err := createDocsByHPath(box.ID, hPath, "", "", "", false)- if err != nil {- return- }-- if "" != boxConf.DailyNoteTemplatePath {- sql.FlushQueue()- if renderErr := applyDocContentTemplateAt(boxConf.DailyNoteTemplatePath, id, &now); nil != renderErr {- logging.LogWarnf("render daily note template [%s] failed: %s", boxConf.DailyNoteTemplatePath, renderErr)+ last := &plan.Steps[len(plan.Steps)-1]+ if last.DocCreateTemplatePath != "" {+ if _, err = resolveDocContentTemplatePath(last.DocCreateTemplatePath); err != nil {+ return}}- IncSync()-- FlushTxQueue()-- tree, err := LoadTreeByBlockID(id)+ last.Attributes, last.TemplateTime = map[string]string{DailyNoteAttrPrefix + date: date}, &now+ document, err := executeDocumentCreationPlan(plan, true)if err != nil {- logging.LogErrorf("load tree by block id [%s] failed: %v", id, err)return}- p = tree.Path- if err = SetBlockAttrs(tree.ID, map[string]string{DailyNoteAttrPrefix + date: date}); err != nil {+ p = document.Path+ if err = SetBlockAttrs(document.ID, map[string]string{DailyNoteAttrPrefix + date: date}); err != nil {return}- if "" != boxConf.DailyNoteTemplatePath {- sql.FlushQueue()- }+ sql.FlushQueue()return}@@ -1742,6 +1737,20 @@ func moveDocs(fromPaths []string, toBoxID, toPath string, callback any, placeByCif err != nil {return}+ leased := map[string]bool{}+ defer func() {+ for boxID := range leased {+ ReleaseEncryptedBoxOperation(boxID)+ }+ }()+ for _, box := range append([]*Box{toBox}, slices.Collect(maps.Values(pathsBoxes))...) {+ if !leased[box.ID] {+ if err = AcquireEncryptedBoxOperation(box.ID); err != nil {+ return+ }+ leased[box.ID] = true+ }+ }// 在移动任何文档前拒绝自身及后代目标,避免调用方将未执行的移动视为成功。for _, fromPath := range fromPaths {@@ -1806,6 +1815,16 @@ func moveDocs(fromPaths []string, toBoxID, toPath string, callback any, placeByC}FlushTxQueue()+ flushLock.Lock()+ defer flushLock.Unlock()+ for _, queued := range takeQueuedTransactions() {+ flushTx(queued)+ }+ for _, fromPath := range fromPaths {+ if _, err = preflightDocumentMove(pathsBoxes[fromPath].ID, fromPath, toBoxID, toPath); err != nil {+ return+ }+ }luteEngine := util.NewLute()refresh := newMoveDocsRefresh()movedDocs := make([]moveDocResult, 0, len(fromPaths))@@ -1878,6 +1897,8 @@ func countSubDocs(box, p string) (ret int) {}func moveDoc(fromBox *Box, fromPath string, toBox *Box, toPath string, luteEngine *lute.Lute, callback any, refresh *moveDocsRefresh) (newPath string, err error) {+ hpathRefresh.Lock()+ defer hpathRefresh.Unlock()isSameBox := fromBox.ID == toBox.IDif isSameBox {@@ -1940,64 +1961,49 @@ func moveDoc(fromBox *Box, fromPath string, toBox *Box, toPath string, luteEngin}}- // 文件位置和块树索引切换期间暂停后台路径任务,避免将移动中的文档误判为已删除。- hpathRefresh.Lock()- defer hpathRefresh.Unlock()needMoveSubDocs := fromBox.Exist(fromFolder)- if needMoveSubDocs {- // 移动子文档文件夹-- newFolder := path.Join(toFolder, tree.ID)- if isSameBox {- if err = fromBox.Move(fromFolder, newFolder); err != nil {- return- }- } else {- absFromPath := filepath.Join(util.DataDir, fromBox.ID, fromFolder)- absToPath := filepath.Join(util.DataDir, toBox.ID, newFolder)- if filelock.IsExist(absToPath) {- filelock.Remove(absToPath)+ newPath = path.Join(toFolder, tree.ID+".sy")+ err = filesys.MutateDocumentSourceSet(func() ([]*treenode.BlockTree, error) {+ return preflightDocumentMove(fromBox.ID, fromPath, toBox.ID, toPath)+ }, func() error {+ oldFolder := filepath.Join(util.DataDir, fromBox.ID, fromFolder)+ newFolder := filepath.Join(util.DataDir, toBox.ID, toFolder, tree.ID)+ if needMoveSubDocs {+ // 不覆盖目标处已有的目录,即使其中没有当前索引认识的文档。+ if _, err := os.Lstat(newFolder); !os.IsNotExist(err) {+ if err != nil {+ return err+ }+ return errors.New("document move destination directory already exists")}- if err = filelock.Rename(absFromPath, absToPath); err != nil {- msg := fmt.Sprintf(Conf.Language(5), fromBox.Name, fromPath, err)- logging.LogErrorf("move [path=%s] in box [%s] failed: %s", fromPath, fromBox.ID, err)- err = errors.New(msg)- return+ if err := filelock.RenameWithoutFatal(oldFolder, newFolder); err != nil {+ return err}}- }-- newPath = path.Join(toFolder, tree.ID+".sy")-- if isSameBox {- if err = fromBox.Move(fromPath, newPath); err != nil {- return- }-- tree, err = filesys.LoadTree(fromBox.ID, newPath, luteEngine)- if err != nil {- return- }-- moveTree(tree)- } else {- absFromPath := filepath.Join(util.DataDir, fromBox.ID, fromPath)- absToPath := filepath.Join(util.DataDir, toBox.ID, newPath)- if err = filelock.Rename(absFromPath, absToPath); err != nil {- msg := fmt.Sprintf(Conf.Language(5), fromBox.Name, fromPath, err)- logging.LogErrorf("move [path=%s] in box [%s] failed: %s", fromPath, fromBox.ID, err)- err = errors.New(msg)- return+ if err := filelock.RenameWithoutFatal(filepath.Join(util.DataDir, fromBox.ID, fromPath),+ filepath.Join(util.DataDir, toBox.ID, newPath)); err != nil {+ if needMoveSubDocs {+ err = errors.Join(err, filelock.RenameWithoutFatal(newFolder, oldFolder))+ }+ return err}-- tree, err = filesys.LoadTree(toBox.ID, newPath, luteEngine)- if err != nil {- return+ var readErr error+ tree, _, readErr = filesys.ReadTreeSnapshot(toBox.ID, newPath)+ if readErr != nil {+ return readErr}-- moveTree(tree)+ return moveTree(tree)+ })+ if err != nil {+ return+ }+ if !isSameBox {moveSorts(tree.ID, fromBox.ID, toBox.ID)}+ // 只移除确已为空的原父目录,不递归清理其他数据。+ if parent := path.Dir(fromPath); parent != "/" {+ _ = os.Remove(filepath.Join(util.DataDir, fromBox.ID, parent))+ }if needMoveSubDocs {// 将其所有子文档的移动事件推送到前端 https://github.com/siyuan-note/siyuan/issues/11661@@ -2045,6 +2051,8 @@ func RemoveDoc(boxID, p string) error {}FlushTxQueue()+ hpathRefresh.Lock()+ defer hpathRefresh.Unlock()luteEngine := util.NewLute()tree, err := removeDoc(box, p, luteEngine)if err != nil {@@ -2072,6 +2080,8 @@ func RemoveDocs(paths []string) error {}}FlushTxQueue()+ hpathRefresh.Lock()+ defer hpathRefresh.Unlock()luteEngine := util.NewLute()var trees []*parse.Tree@@ -2326,10 +2336,14 @@ func prepareDocRename(tree *parse.Tree, title string) (titleChanged, emptyAttrUpisEmpty = true}// 先规范化输入得到实际会存储的标题,再与旧标题比较- titleChanged = tree.Root.IALAttr("title") != title+ titleChanged = treenode.ReadDocumentTitle(tree.Root).Text != titleif titleChanged {- tree.HPath = path.Join(path.Dir(tree.HPath), title)+ parentHPath, pathErr := documentParentDisplayPath(tree.Box, tree.Path)+ if pathErr != nil {+ return false, false, pathErr+ }+ tree.HPath = parentHPath + "/" + titletree.Root.SetIALAttr("title", title)}@@ -2361,7 +2375,7 @@ func publishDocRename(tree *parse.Tree, titleChanged, emptyAttrUpdated bool) {"box": tree.Box,"id": tree.Root.ID,"path": tree.Path,- "title": tree.Root.IALAttr("title"),+ "title": treenode.ReadDocumentTitle(tree.Root).Text,"empty": tree.Root.IALAttr(NodeAttrTitleEmpty) == "true","refText": refText,}@@ -2479,7 +2493,14 @@ func createDoc0(boxID, p, title, dom string, titleEmpty, syncWrite bool, attribureturn}}+ tree, err = buildCreateDocTree(boxID, validation, dom, attributes...)+ if err == nil {+ err = performCreateDocTransaction(tree, syncWrite)+ }+ return+}+func buildCreateDocTree(boxID string, validation *createDocValidation, dom string, attributes ...map[string]string) (tree *parse.Tree, err error) {luteEngine := util.NewLute()tree = luteEngine.BlockDOM2Tree(dom)tree.Box = boxID@@ -2535,7 +2556,6 @@ func createDoc0(boxID, p, title, dom string, titleEmpty, syncWrite bool, attribureturn nil, err}}- err = performCreateDocTransaction(tree, syncWrite)return}@@ -2760,8 +2780,14 @@ func moveSorts(rootID, fromBox, toBox string) {}func ChangeFileTreeSort(boxID string, paths []string) {+ if err := changeFileTreeSort(boxID, paths); err != nil {+ logging.LogErrorf("change file tree sort failed: %s", err)+ }+}++func changeFileTreeSort(boxID string, paths []string) error {if 1 > len(paths) {- return+ return nil}FlushTxQueue()@@ -2769,7 +2795,7 @@ func ChangeFileTreeSort(boxID string, paths []string) {box := Conf.Box(boxID)if nil == box {fileTreeSortLock.Unlock()- return+ return ErrBoxNotFound}p := paths[0]@@ -2777,25 +2803,23 @@ func ChangeFileTreeSort(boxID string, paths []string) {confDir := filepath.Join(util.DataDir, box.ID, ".siyuan")if err := os.MkdirAll(confDir, 0755); err != nil {fileTreeSortLock.Unlock()- logging.LogErrorf("create conf dir failed: %s", err)- return+ return err}confPath := filepath.Join(confDir, "sort.json")fullSortIDs, err := readSortConfMap(confPath)if err != nil {fileTreeSortLock.Unlock()- return+ return err}currentIDs, err := loadSiblingCustomOrder(boxID, parentPath, fullSortIDs)if err != nil {fileTreeSortLock.Unlock()- logging.LogErrorf("load sibling custom order failed: %s", err)- return+ return err}orderedIDs := mergeRequestedSortOrder(currentIDs, paths)if 1 > len(orderedIDs) || equalStringSlices(currentIDs, orderedIDs) {fileTreeSortLock.Unlock()- return+ return nil}sortFolderIDs := map[string]int{}@@ -2805,13 +2829,14 @@ func ChangeFileTreeSort(boxID string, paths []string) {maps.Copy(fullSortIDs, sortFolderIDs)if err = writeSortConfMap(confPath, fullSortIDs); err != nil {fileTreeSortLock.Unlock()- return+ return err}fileTreeSortLock.Unlock()IncSync()pushFiletreeSortChanged(sortFolderIDs)+ return nil}// ReorderResult 描述相对排序操作的结果。diff --git a/kernel/model/heading.go b/kernel/model/heading.goindex e4f215ed50..9699aa5f68 100644--- a/kernel/model/heading.go+++ b/kernel/model/heading.go@@ -260,7 +260,7 @@ func Doc2Heading(srcID, targetID string, after bool) (srcTreeBox, srcTreePath stsrcTree.Root.RemoveIALAttr("tags")heading := &ast.Node{ID: srcTree.Root.ID, Type: ast.NodeHeading, HeadingLevel: headingLevel, KramdownIAL: srcTree.Root.KramdownIAL}heading.SetIALAttr("updated", util.CurrentTimeSecondsStr())- heading.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(srcTree.Root.IALAttr("title"))})+ heading.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(treenode.ReadDocumentTitle(srcTree.Root).Text)})heading.RemoveIALAttr("title")heading.Box, heading.Path = targetTree.Box, targetTree.Pathif "" != tagIAL && 0 < len(tags) {diff --git a/kernel/model/heading_batch.go b/kernel/model/heading_batch.goindex aab1b61dab..6aee14b32f 100644--- a/kernel/model/heading_batch.go+++ b/kernel/model/heading_batch.go@@ -2,6 +2,7 @@ package modelimport ("github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/treenode")type DocHeadingLevelResult struct {@@ -21,7 +22,7 @@ func GetDocHeadingLevelTransaction(id, notebook string, source, target int, withif tree.Root.ID != id {return nil, ErrTreeNotFound}- result := &DocHeadingLevelResult{Title: tree.Root.IALAttr("title")}+ result := &DocHeadingLevelResult{Title: treenode.ReadDocumentTitle(tree.Root).Text}headings, counts := collectDocHeadingLevelNodes(tree.Root, source)result.Counts = countsfor level, count := range counts {diff --git a/kernel/model/history.go b/kernel/model/history.goindex 23b98ca7f8..e3c505e419 100644--- a/kernel/model/history.go+++ b/kernel/model/history.go@@ -411,7 +411,7 @@ func RollbackDocHistory(historyPath string) (err error) {tree.Box = boxIDtree.Path = filepath.ToSlash(strings.TrimPrefix(destPath, util.DataDir+string(os.PathSeparator)+boxID))- tree.HPath = parentHPath + "/" + tree.Root.IALAttr("title")+ tree.HPath = parentHPath + "/" + treenode.ReadDocumentTitle(tree.Root).Textif needResetTree {resetTree(tree, "", true)@@ -505,7 +505,7 @@ func RollbackDocHistory(historyPath string) (err error) {"box": boxID,"id": tree.Root.ID,"path": tree.Path,- "title": tree.Root.IALAttr("title"),+ "title": treenode.ReadDocumentTitle(tree.Root).Text,"empty": "" != tree.Root.IALAttr(NodeAttrTitleEmpty),"refText": refText,}@@ -1378,7 +1378,7 @@ func indexHistoryDir(name string, luteEngine *lute.Lute) {continue}- title := tree.Root.IALAttr("title")+ title := treenode.ReadDocumentTitle(tree.Root).Textif "" == title {title = Conf.language(16)}diff --git a/kernel/model/history_diff.go b/kernel/model/history_diff.goindex 49ba35a5ba..3db9a6b9f1 100644--- a/kernel/model/history_diff.go+++ b/kernel/model/history_diff.go@@ -273,7 +273,7 @@ func loadDocVersion(ref *DocVersionRef) (ret *loadedDocVersion, err error) {ret.rootID = ret.tree.Root.ID}if nil != ret.tree && "" == ret.title {- ret.title = ret.tree.Root.IALAttr("title")+ ret.title = treenode.ReadDocumentTitle(ret.tree.Root).Text}if "" == ret.title {ret.title = ret.rootID@@ -301,7 +301,7 @@ func loadCurrentDocVersion(id string) (ret *loadedDocVersion, err error) {if nil != ret.parseErr {return ret, nil}- ret.title = ret.tree.Root.IALAttr("title")+ ret.title = treenode.ReadDocumentTitle(ret.tree.Root).Textret.rootID = ret.tree.Root.IDreturn}@@ -385,7 +385,7 @@ func loadHistoryDocVersion(historyPath string) (ret *loadedDocVersion, err error}return &loadedDocVersion{tree: tree,- title: tree.Root.IALAttr("title"),+ title: treenode.ReadDocumentTitle(tree.Root).Text,rootID: tree.Root.ID,raw: data,large: 1024*1024 <= len(data),@@ -454,7 +454,7 @@ func loadSnapshotDocVersion(fileID string) (ret *loadedDocVersion, err error) {}return &loadedDocVersion{tree: tree,- title: tree.Root.IALAttr("title"),+ title: treenode.ReadDocumentTitle(tree.Root).Text,rootID: tree.Root.ID,raw: data,large: 1024*1024 <= len(data),diff --git a/kernel/model/hpath_refresh.go b/kernel/model/hpath_refresh.goindex 7852a5541e..8605ae1fa1 100644--- a/kernel/model/hpath_refresh.go+++ b/kernel/model/hpath_refresh.go@@ -433,15 +433,18 @@ func refreshHPathsTask(task *hpathRefreshTask) (done bool, err error) {}if task.docs == nil {if task.recover {- hpath, properties, loadErr := filesys.ReadDocHPath(root.BoxID, root.Path)+ if err = recoverDocumentMetadata(root.BoxID); err != nil {+ return false, err+ }+ hpath, _, loadErr := filesys.ReadDocHPath(root.BoxID, root.Path)if loadErr != nil {return false, loadErr}- tree := treenode.NewTree(root.BoxID, root.Path, hpath, properties["title"])- tree.Root.KramdownIAL = nil- for key, value := range properties {- tree.Root.SetIALAttr(key, value)+ tree, loadErr := filesys.ReadDocumentMetadataTree(root.BoxID, root.Path)+ if loadErr != nil {+ return false, loadErr}+ tree.HPath = hpathif err = treenode.RefreshDocHPaths(tree); err != nil {return false, err}diff --git a/kernel/model/hpath_refresh_test.go b/kernel/model/hpath_refresh_test.goindex 0d0a9734ca..feed8a2b5b 100644--- a/kernel/model/hpath_refresh_test.go+++ b/kernel/model/hpath_refresh_test.go@@ -124,6 +124,13 @@ func TestDocumentHPathRefresh(t *testing.T) {assertHPathTestDoc(t, database, child, "/Final/Leaf")assertHPathTestDoc(t, database, grandchild, "/Final/Leaf/Grandchild")assertHPathTestDoc(t, database, sibling, "/Parent")+ var title string+ if err := database.QueryRow("SELECT content FROM blocks WHERE id=? AND type='d'", child.ID).Scan(&title); err != nil || title != "Leaf" {+ t.Fatalf("stale queued edit restored the old title: %q, %v", title, err)+ }+ if stale.Root.IALAttr("title") != "Child" {+ t.Fatal("index reconciliation modified the original editing snapshot")+ }})t.Run("interrupted source writes and restart", func(t *testing.T) {diff --git a/kernel/model/import.go b/kernel/model/import.goindex 4af86d6c4b..9820710ae4 100644--- a/kernel/model/import.go+++ b/kernel/model/import.go@@ -328,7 +328,7 @@ func checkEncryptedImportFlashcards(tree *parse.Tree, sourcePath string, encryptreturn nil}- title := tree.Root.IALAttr("title")+ title := treenode.ReadDocumentTitle(tree.Root).Textif "" == title {title = filepath.Base(sourcePath)}@@ -342,7 +342,7 @@ func importedBlockDocTitles(trees map[string]*parse.Tree) map[string]string {if nil == tree || nil == tree.Root {continue}- title := tree.Root.IALAttr("title")+ title := treenode.ReadDocumentTitle(tree.Root).Textast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {if entering && "" != n.ID {ret[n.ID] = title@@ -659,6 +659,21 @@ func importSY0(zipPath, boxID, toPath string, createNotebook, autoDetect bool, strees[tree.ID] = treeutil.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), fmt.Sprintf("%d/%d", i+1, len(syPaths))))}+ if createNotebook && importedBoxConf != nil {+ sourceBoxID := importedBoxDocID+ if sourceBoxID == "" && ast.IsNodeIDPattern(filepath.Base(unzipRootPath)) {+ sourceBoxID = filepath.Base(unzipRootPath)+ }+ box := &Box{ID: boxID}+ boxConf := box.GetConf()+ boxConf.DocCreateTarget = remapImportedDocumentTarget(importedBoxConf.DocCreateTarget, sourceBoxID, boxID, blockIDs)+ boxConf.RefCreateTarget = remapImportedDocumentTarget(importedBoxConf.RefCreateTarget, sourceBoxID, boxID, blockIDs)+ boxConf.DailyNoteTarget = remapImportedDocumentTarget(importedBoxConf.DailyNoteTarget, sourceBoxID, boxID, blockIDs)+ boxConf.MetadataVersion = importedBoxConf.MetadataVersion+ if err = box.SaveConf(boxConf); err != nil {+ return+ }+ }// 加密笔记本不支持闪卡:.sy.zip 内的牌组数据与文档闪卡属性都必须拒绝导入。// 此时块 ID 已完成重映射,可以指出具体是哪些文档的卡片在包内,而不是只提示"不支持该操作"。if encryptedTarget {@@ -684,7 +699,7 @@ func importSY0(zipPath, boxID, toPath string, createNotebook, autoDetect bool, s// 引用和嵌入指向重新生成的块 IDfor _, tree := range trees {treenode.RemapTabsActiveIDs(tree.Root, blockIDs)- util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), tree.Root.IALAttr("title")))+ util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), treenode.ReadDocumentTitle(tree.Root).Text))treenode.WalkWithInlineTitles(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering {return ast.WalkContinue@@ -833,7 +848,7 @@ func importSY0(zipPath, boxID, toPath string, createNotebook, autoDetect bool, s// 重新指向数据库属性值for _, tree := range trees {- util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), tree.Root.IALAttr("title")))+ util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), treenode.ReadDocumentTitle(tree.Root).Text))ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {if !entering || "" == n.ID {return ast.WalkContinue@@ -946,7 +961,7 @@ func importSY0(zipPath, boxID, toPath string, createNotebook, autoDetect bool, s// 写回 .syfor _, tree := range trees {- util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), tree.Root.IALAttr("title")))+ util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), treenode.ReadDocumentTitle(tree.Root).Text))syPath := filepath.Join(unzipRootPath, tree.Path)// 加密前确定最终文件名:tree.ID + ".sy",确保加密 AAD 用的是最终 box-relative pathfinalSyName := tree.ID + ".sy"@@ -1155,7 +1170,7 @@ func importSY0(zipPath, boxID, toPath string, createNotebook, autoDetect bool, s}av.BatchUpsertBlockRel(avNodes)sql.IndexTreeQueue(tree)- util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), tree.Root.IALAttr("title")))+ util.PushEndlessProgress(Conf.language(73) + " " + fmt.Sprintf(Conf.language(70), treenode.ReadDocumentTitle(tree.Root).Text))}if sortErr = applyImportedSYSort(boxID, baseTargetPath, importedSortDocs, sourceSortIDs); nil != sortErr {logging.LogErrorf("apply imported document sort failed: %s", sortErr)diff --git a/kernel/model/import_document_target.go b/kernel/model/import_document_target.gonew file mode 100644index 0000000000..8a7fdcdef2--- /dev/null+++ b/kernel/model/import_document_target.go@@ -0,0 +1,30 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package model++import "github.com/siyuan-note/siyuan/kernel/conf"++// remapImportedDocumentTarget 只改写身份,不把标题模板中的 ID 字面文字当作引用。+// 完整笔记本包共享的 ID 表包含其他笔记本文档;包外身份没有映射,原样保留。+func remapImportedDocumentTarget(target *conf.DocumentTarget, sourceBoxID, boxID string, ids map[string]string) *conf.DocumentTarget {+ if target == nil {+ return nil+ }+ ret := *target+ ret.Parents = append([]string{}, target.Parents...)+ if ret.Notebook == sourceBoxID {+ ret.Notebook = boxID+ } else if id := ids[ret.Notebook]; id != "" {+ ret.Notebook = id+ }+ if ret.Anchor.Kind == "document" {+ if ret.Anchor.ID == sourceBoxID {+ ret.Anchor.ID = boxID+ } else if id := ids[ret.Anchor.ID]; id != "" {+ ret.Anchor.ID = id+ }+ }+ return &ret+}diff --git a/kernel/model/import_document_target_fts5_test.go b/kernel/model/import_document_target_fts5_test.gonew file mode 100644index 0000000000..90121b506e--- /dev/null+++ b/kernel/model/import_document_target_fts5_test.go@@ -0,0 +1,47 @@+//go:build fts5++package model++import (+ "testing"++ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++func TestImportNotebookDocumentTargets(t *testing.T) {+ const sourceBoxID, targetBoxID = "20261023092000-source1", "20261023092001-target1"+ const docID = "20261023092002-documen"+ setupExportRelatedTest(t, sourceBoxID, targetBoxID)+ setupNotebookDocumentImportDatabase(t)+ source := &Box{ID: sourceBoxID}+ sourceConf := source.GetConf()+ sourceConf.DocCreateTarget = &conf.DocumentTarget{Version: 2, Notebook: sourceBoxID,+ Anchor: conf.DocumentTargetAnchor{Kind: "document", ID: docID}, Parents: []string{}, Title: "Literal template", OnMissingParent: "error"}+ sourceConf.RefCreateTarget, sourceConf.DailyNoteTarget = sourceConf.DocCreateTarget, sourceConf.DocCreateTarget+ if err := source.SaveConf(sourceConf); err != nil {+ t.Fatal(err)+ }+ writeExportRelatedTestTree(t, treenode.NewTree(sourceBoxID, "/"+docID+".sy", "/Anchor", "Anchor"))+ if err := writeBoxDocID(sourceBoxID); err != nil {+ t.Fatal(err)+ }+ archive, err := exportedFilePath(ExportNotebookSY(sourceBoxID))+ if err != nil {+ t.Fatal(err)+ }+ ids := map[string]string{}+ if _, err = importSY0(archive, targetBoxID, "/", true, false, ids, true); err != nil {+ t.Fatal(err)+ }+ imported := (&Box{ID: targetBoxID}).GetConf()+ for _, target := range []*conf.DocumentTarget{imported.DocCreateTarget, imported.RefCreateTarget, imported.DailyNoteTarget} {+ if target == nil || target.Notebook != targetBoxID || target.Anchor.ID != ids[docID] || target.Anchor.ID == docID ||+ target.Title != "Literal template" {+ t.Fatal("native notebook import left stale configured identities", target, ids)+ }+ }+ if target := source.GetConf().DocCreateTarget; target.Notebook != sourceBoxID || target.Anchor.ID != docID {+ t.Fatal("native import changed the source notebook")+ }+}diff --git a/kernel/model/import_document_target_test.go b/kernel/model/import_document_target_test.gonew file mode 100644index 0000000000..98f76b0516--- /dev/null+++ b/kernel/model/import_document_target_test.go@@ -0,0 +1,49 @@+package model++import (+ "reflect"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/conf"+)++func TestRemapImportedDocumentTarget(t *testing.T) {+ const source, destination = "20261023090000-source1", "20261023090001-target1"+ const doc, newDoc = "20261023090002-documen", "20261023090003-documen"+ const external, newExternal = "20261023090004-extern1", "20261023090005-extern2"+ for _, kind := range []string{"notebookRoot", "context", "document"} {+ t.Run(kind, func(t *testing.T) {+ target := &conf.DocumentTarget{Version: 2, Notebook: source, Anchor: conf.DocumentTargetAnchor{Kind: kind},+ Parents: []string{source}, Title: doc, OnMissingParent: "error"}+ if kind == "document" {+ target.Anchor.ID = doc+ }+ result := remapImportedDocumentTarget(target, source, destination, map[string]string{doc: newDoc})+ if err := result.Validate(); err != nil || result.Notebook != destination || result.Title != doc ||+ !reflect.DeepEqual(result.Parents, target.Parents) {+ t.Fatal("target lost its template or notebook identity", result, err)+ }+ if kind == "document" && result.Anchor.ID != newDoc {+ t.Fatal("anchor still points to the source document", result)+ }+ result.Parents[0] = "changed"+ if target.Notebook != source || target.Parents[0] != source || kind == "document" && target.Anchor.ID != doc {+ t.Fatal("import changed the source target")+ }+ })+ }+ target := &conf.DocumentTarget{Notebook: external, Anchor: conf.DocumentTargetAnchor{Kind: "document", ID: external}}+ if result := remapImportedDocumentTarget(target, source, destination, nil); result.Notebook != external || result.Anchor.ID != external {+ t.Fatal("an external target was moved into the imported notebook")+ }+ if result := remapImportedDocumentTarget(target, source, destination, map[string]string{external: newExternal}); result.Notebook != newExternal || result.Anchor.ID != newExternal {+ t.Fatal("shared notebook identities were not remapped")+ }+ target.Notebook, target.Anchor.ID = source, source+ if result := remapImportedDocumentTarget(target, source, destination, nil); result.Notebook != destination || result.Anchor.ID != destination {+ t.Fatal("notebook document identity was not remapped")+ }+ if remapImportedDocumentTarget(nil, source, destination, nil) != nil {+ t.Fatal("an absent target became configured")+ }+}diff --git a/kernel/model/index.go b/kernel/model/index.goindex b47bf2dac0..14225ad6de 100644--- a/kernel/model/index.go+++ b/kernel/model/index.go@@ -163,11 +163,25 @@ func indexBox(boxID string) {if nil == box {return}+ if err := treenode.SetDocumentMetadataState(boxID, "building"); err != nil {+ logging.LogErrorf("prepare document metadata [%s] failed: %s", boxID, err)+ return+ }+ metadataReady := false+ defer func() {+ if !metadataReady {+ _ = treenode.SetDocumentMetadataState(boxID, "error")+ }+ }()// 全量索引使用纯 INSERT,开始前必须清理该笔记本的旧数据,避免重复任务叠加相同行。sql.DeleteBoxQueue(boxID)util.SetBootDetails(Conf.Language(303))- files := box.ListFiles("/")+ files, scanErr := box.listFilesForIndex("/")+ if scanErr != nil {+ logging.LogErrorf("enumerate notebook [%s] failed: %s", boxID, scanErr)+ return+ }boxLen := max(1, len(Conf.GetOpenedBoxes()))bootProgressPart := int32(30.0 / float64(boxLen) / float64(len(files)))@@ -176,6 +190,7 @@ func indexBox(boxID string) {var treeCount intvar treeSize int64lock := sync.Mutex{}+ var sourceFailed boolutil.PushStatusBar(fmt.Sprintf("["+html.EscapeString(box.Name)+"] "+Conf.Language(64), len(files)))poolSize := min(runtime.NumCPU(), 4)@@ -192,6 +207,9 @@ func indexBox(boxID string) {lock.Unlock()tree, err := filesys.LoadTree(box.ID, file.path, luteEngine)if err != nil {+ lock.Lock()+ sourceFailed = true+ lock.Unlock()logging.LogErrorf("read box [%s] tree [%s] failed: %s", box.ID, file.path, err)return}@@ -203,6 +221,10 @@ func indexBox(boxID string) {docIAL["updated"] = updatedif _, writeErr := filesys.WriteTree(tree); nil != writeErr {logging.LogErrorf("write tree [%s] failed: %s", tree.Path, writeErr)+ lock.Lock()+ sourceFailed = true+ lock.Unlock()+ return}}@@ -252,6 +274,9 @@ func indexBox(boxID string) {invokeErr := p.Invoke(file)if nil != invokeErr {waitGroup.Done()+ lock.Lock()+ sourceFailed = true+ lock.Unlock()logging.LogErrorf("invoke [%s] failed: %s", file.path, invokeErr)continue}@@ -259,6 +284,21 @@ func indexBox(boxID string) {batchBytes += file.size}flushBatch()+ if !sourceFailed {+ pending, pendingErr := treenode.PendingDocumentMetadata(boxID)+ for _, doc := range pending {+ if pendingErr = filesys.RecoverDocumentMetadataWrite(doc); pendingErr != nil {+ break+ }+ }+ if pendingErr != nil {+ logging.LogErrorf("recover document metadata [%s] failed: %s", boxID, pendingErr)+ } else if err := treenode.SetDocumentMetadataState(boxID, "ready"); err != nil {+ logging.LogErrorf("complete document metadata [%s] failed: %s", boxID, err)+ } else {+ metadataReady = true+ }+ }// 关联数据库和块av.BatchUpsertBlockRel(avNodes)diff --git a/kernel/model/index_fix.go b/kernel/model/index_fix.goindex 97ef16f453..285edb099a 100644--- a/kernel/model/index_fix.go+++ b/kernel/model/index_fix.go@@ -543,6 +543,6 @@ func reindexTree0(tree *parse.Tree, i, size int) {}if 0 == i%64 {- util.PushStatusBar(fmt.Sprintf(Conf.Language(183), i, size, html.EscapeString(path.Base(tree.HPath))))+ util.PushStatusBar(fmt.Sprintf(Conf.Language(183), i, size, html.EscapeString(treenode.ReadDocumentTitle(tree.Root).Text)))}}diff --git a/kernel/model/path.go b/kernel/model/path.goindex 926df57db4..7e9a8f8bd0 100644--- a/kernel/model/path.go+++ b/kernel/model/path.go@@ -162,7 +162,7 @@ func toFlatTree(blocks []*Block, baseDepth int, typ string, tree *parse.Tree) (rtreeNode := &Path{ID: root.ID,Box: root.Box,- Name: path.Base(root.HPath),+ Name: documentTitleText(root.Box, root.RootID),NodeType: root.Type,Type: typ,SubType: root.SubType,diff --git a/kernel/model/push_reload.go b/kernel/model/push_reload.goindex f8527ffaf4..fd59e712ff 100644--- a/kernel/model/push_reload.go+++ b/kernel/model/push_reload.go@@ -271,7 +271,7 @@ func refreshDocInfo0(tree *parse.Tree, size uint64) {docInfo := map[string]any{"box": tree.Box,"rootID": tree.ID,- "name": tree.Root.IALAttr("title"),+ "name": treenode.ReadDocumentTitle(tree.Root).Text,"alias": tree.Root.IALAttr("alias"),"name1": tree.Root.IALAttr("name"),"memo": tree.Root.IALAttr("memo"),diff --git a/kernel/model/ref_title.go b/kernel/model/ref_title.goindex f030b6eba0..eadebb1e09 100644--- a/kernel/model/ref_title.go+++ b/kernel/model/ref_title.go@@ -30,7 +30,7 @@ func SearchExactRefDocTitle(id, rootID, title, boxID string) (blocks []*Block, nif err != nil {return nil, false, err}- if tree == nil || !strings.EqualFold(tree.Root.IALAttr("title"), title) {+ if tree == nil || !strings.EqualFold(treenode.ReadDocumentTitle(tree.Root).Text, title) {return nil, false, fmt.Errorf("document [%s] title index is outdated", targetID)}block := fromSQLBlock(sql.BuildBlockFromNode(tree.Root, tree), "", 0)diff --git a/kernel/model/render.go b/kernel/model/render.goindex 949c9294ae..c599e71ff7 100644--- a/kernel/model/render.go+++ b/kernel/model/render.go@@ -44,7 +44,7 @@ func renderOutline(heading *ast.Node, luteEngine *lute.Lute) (ret string) {}if ast.NodeDocument == heading.Type {- return heading.IALAttr("title")+ return treenode.ReadDocumentTitle(heading).Text}buf := bytes.Buffer{}diff --git a/kernel/model/repository.go b/kernel/model/repository.goindex 46c3535157..267abc3b7b 100644--- a/kernel/model/repository.go+++ b/kernel/model/repository.go@@ -333,7 +333,7 @@ func RollbackRepoSnapshotFile(fileID string) (err error) {tree.Box = boxIDtree.Path = filepath.ToSlash(strings.TrimPrefix(destPath, util.DataDir+string(os.PathSeparator)+boxID))- tree.HPath = parentHPath + "/" + tree.Root.IALAttr("title")+ tree.HPath = parentHPath + "/" + treenode.ReadDocumentTitle(tree.Root).Textif needResetTree {resetTree(tree, "", true)}@@ -417,7 +417,7 @@ func OpenRepoSnapshotFile(fileID string) (title, content string, displayInText blogging.LogErrorf("parse tree from snapshot file [%s] failed", fileID)return}- title = snapshotTree.Root.IALAttr("title")+ title = treenode.ReadDocumentTitle(snapshotTree.Root).Textif !displayInText {renderTree := &parse.Tree{Root: &ast.Node{Type: ast.NodeDocument}}@@ -709,7 +709,7 @@ func parseTitleInSnapshot(fileID string, repo *dejavu.Repo, luteEngine *lute.Lutreturn}- title = tree.Root.IALAttr("title")+ title = treenode.ReadDocumentTitle(tree.Root).TextrootID = tree.Root.ID}return@@ -921,7 +921,7 @@ func ExportRepoFile(id string) (exportPath string, err error) {return}- docTitle = util.FilterFileName(tree.Root.IALAttr("title"))+ docTitle = util.FilterFileName(treenode.ReadDocumentTitle(tree.Root).Text)if docTitle == "" {docTitle = strings.TrimSuffix(name, ".sy")}diff --git a/kernel/model/search.go b/kernel/model/search.goindex 2a5e99a9d9..d4e644ed4f 100644--- a/kernel/model/search.go+++ b/kernel/model/search.go@@ -758,7 +758,7 @@ func findReplaceInBox(keyword, replacement string, replaceTypes map[string]bool,continue}- title := node.IALAttr("title")+ title := treenode.ReadDocumentTitle(node).Texttags := node.IALAttr("tags")if 0 == method {if newTitle, matched := replaceSearchText(title, method, keyword, strings.ReplaceAll(replacement, "/", "/"), r); matched {@@ -1121,7 +1121,7 @@ func writeReplacementTree(tree *parse.Tree, original []byte, title string, renamif rename && IsBoxDocPath(tree.Box, tree.Path) {box := Conf.Box(tree.Box)boxConf := box.GetConf()- boxConf.Name = tree.Root.IALAttr("title")+ boxConf.Name = treenode.ReadDocumentTitle(tree.Root).Textif err = box.SaveConf(boxConf); err != nil {return err}diff --git a/kernel/model/settings_reset.go b/kernel/model/settings_reset.goindex cb5718ac4d..687273170b 100644--- a/kernel/model/settings_reset.go+++ b/kernel/model/settings_reset.go@@ -87,6 +87,8 @@ func ResetSettings() error {if util.ReadOnly {return errors.New("read-only mode")}+ unlockTarget := lockDocumentTargetConfiguration()+ defer unlockTarget()Conf.m.Lock()localStorageLock.Lock()bootAppearanceConfLock.Lock()diff --git a/kernel/model/shortcuts.go b/kernel/model/shortcuts.goindex 63e6720f0c..9deb8d86d9 100644--- a/kernel/model/shortcuts.go+++ b/kernel/model/shortcuts.go@@ -21,7 +21,6 @@ import ("errors""fmt""os"- "path""path/filepath""slices""strconv"@@ -49,15 +48,23 @@ func MoveLocalShorthands(boxID string) (retIDs []string, err error) {}defer syncLock.Unlock()- entries, err := os.ReadDir(shorthandsDir)- if nil != err {- logging.LogErrorf("read dir [%s] failed: %s", shorthandsDir, err)- return- }if !IsShorthandSaveBoxAvailable(boxID) {err = errors.New(Conf.Language(375))return}+ if err = AcquireEncryptedBoxOperation(boxID); err != nil {+ return+ }+ defer ReleaseEncryptedBoxOperation(boxID)+ if recovered, recoveryErr := recoverLocalShorthandCreation(boxID); recoveryErr != nil {+ return nil, recoveryErr+ } else if recovered != "" {+ retIDs = append(retIDs, recovered)+ }+ entries, err := os.ReadDir(shorthandsDir)+ if err != nil {+ return retIDs, err+ }assetsDir := filepath.Join(util.DataDir, "assets")for _, entry := range entries {@@ -93,6 +100,14 @@ func MoveLocalShorthands(boxID string) (retIDs []string, err error) {}var toRemoves []string+ // 中途失败也清理已确认写入的源条目,避免下次消费重复创建之前成功的文档。+ defer func() {+ for _, p := range toRemoves {+ if removeErr := os.Remove(p); removeErr != nil && !os.IsNotExist(removeErr) {+ logging.LogErrorf("remove file [%s] failed: %s", p, removeErr)+ }+ }+ }()if "" == hPath { // hPath 为空的话每一个速记对应创建一个文档记录for _, entry := range entries {@@ -125,7 +140,7 @@ func MoveLocalShorthands(boxID string) (retIDs []string, err error) {dom := shorthandDOM(content, created)docID := util.NodeIDByTime(created)var retID string- retID, err = createShorthandDocByDOM(boxID, hPath, dom, docID)+ retID, err = createShorthandDocByDOM(boxID, hPath, dom, docID, map[string][]byte{p: data})if nil != err {logging.LogErrorf("create doc failed: %s", err)return@@ -144,6 +159,8 @@ func MoveLocalShorthands(boxID string) (retIDs []string, err error) {created time.Time}var shorthands []shorthand+ var pendingRemoves []string+ sources := map[string][]byte{}for _, entry := range entries {if filepath.Ext(entry.Name()) != ".md" {continue@@ -172,11 +189,16 @@ func MoveLocalShorthands(boxID string) (retIDs []string, err error) {created = time.UnixMilli(i)}shorthands = append(shorthands, shorthand{content: content, created: created})- toRemoves = append(toRemoves, p)+ pendingRemoves = append(pendingRemoves, p)+ sources[p] = data}if 0 < len(shorthands) {- bt := treenode.GetBlockTreeRootByHPath(boxID, hPath)+ plan, planErr := planShorthandDocument(boxID, hPath, ast.NewNodeID(), true)+ if planErr != nil {+ return retIDs, planErr+ }+ bt := treenode.GetBlockTreeInExactBox(plan.ExistingID, boxID)if nil == bt {// 目标文档不存在,新建文档:根文档块 ID 取所有速记中最早的输入时刻earliest := shorthands[0].created@@ -192,7 +214,7 @@ func MoveLocalShorthands(boxID string) (retIDs []string, err error) {dom := buff.String()docID := util.NodeIDByTime(earliest)var retID string- retID, err = createShorthandDocByDOM(boxID, hPath, dom, docID)+ retID, err = createShorthandDocByDOM(boxID, hPath, dom, docID, sources)if nil != err {logging.LogErrorf("create doc failed: %s", err)return@@ -223,22 +245,27 @@ func MoveLocalShorthands(boxID string) (retIDs []string, err error) {}}slices.Reverse(nodes)+ blockIDs := make([]string, 0, len(nodes))for _, node := range nodes {last.InsertAfter(node)+ if node.IsBlock() && node.ID != "" {+ blockIDs = append(blockIDs, node.ID)+ }+ }+ if err = beginLocalShorthandCreation(boxID, tree.ID, tree.Path, blockIDs, sources); err != nil {+ return}if err = indexWriteTreeUpsertQueue(tree); nil != err {logging.LogErrorf("upsert shorthand merged tree failed: %s", err)return}+ if _, err = recoverLocalShorthandCreation(boxID); err != nil {+ return+ }util.PushReloadProtyle(tree.ID)}- }- }-- for _, p := range toRemoves {- if removeErr := os.Remove(p); nil != removeErr {- logging.LogErrorf("remove file [%s] failed: %s", p, removeErr)+ toRemoves = append(toRemoves, pendingRemoves...)}}@@ -282,7 +309,7 @@ func shorthandDOM(md string, created time.Time) string {// createShorthandDocByDOM 创建速记文档,使用指定的 DOM 和文档块 ID(均基于速记输入时刻)。// 速记场景无需 tags、父文档、数学公式、剪藏链接等处理,直接基于 DOM 和指定 docID 落盘。-func createShorthandDocByDOM(boxID, hPath, dom, docID string) (retID string, err error) {+func createShorthandDocByDOM(boxID, hPath, dom, docID string, sources ...map[string][]byte) (retID string, err error) {createDocLock.Lock()defer createDocLock.Unlock()@@ -293,22 +320,62 @@ func createShorthandDocByDOM(boxID, hPath, dom, docID string) (retID string, err}FlushTxQueue()- retID, err = createDocsByHPathSync(box.ID, hPath, dom, "", docID, false)+ plan, err := planShorthandDocument(boxID, hPath, docID, false)+ if err != nil {+ return "", err+ }+ plan.Steps[len(plan.Steps)-1].DOM = &dom+ if len(sources) > 0 {+ plannedPaths, pathErr := documentCreationPlanPaths(plan)+ if pathErr != nil {+ return "", pathErr+ }+ var blockIDs []string+ for node := util.NewLute().BlockDOM2Tree(dom).Root.FirstChild; node != nil; node = node.Next {+ if node.IsBlock() && node.ID != "" {+ blockIDs = append(blockIDs, node.ID)+ }+ }+ if err = beginLocalShorthandCreation(boxID, docID, plannedPaths[docID], blockIDs, sources[0]); err != nil {+ return "", err+ }+ }+ document, err := executeDocumentCreationPlan(plan, true)if nil != err {+ var failure *DocumentCreateFailure+ if len(sources) > 0 && errors.As(err, &failure) && failure.CommitState == "none" {+ _ = os.Remove(localShorthandCreationPath())+ }return}+ retID = document.IDbt := treenode.GetBlockTree(retID)if err = verifyShorthandDocPersisted(bt, retID); nil != err {return}- box.setSortByConf(path.Dir(bt.Path), retID)+ if len(sources) > 0 {+ if _, err = recoverLocalShorthandCreation(boxID); err != nil {+ return+ }+ }FlushTxQueue()PushCreate(box, bt.Path, nil)return}+func planShorthandDocument(boxID, template, id string, reuse bool) (*DocumentCreatePlan, error) {+ if treenode.DocumentMetadataState(boxID) != "ready" {+ if err := recoverDocumentMetadata(boxID); err != nil {+ return nil, err+ }+ }+ // 调用方已按原速记规则渲染模板,不再解释其中产生的 Go 模板语法。+ return PlanDocumentCreation(DocumentPlanRequest{Notebook: boxID, Purpose: "document", ID: id, Reuse: reuse,+ Target: &EffectiveDocumentTarget{Notebook: boxID, Path: template, Rendered: true}})+}+func verifyShorthandDocPersisted(bt *treenode.BlockTree, expectedID string) (err error) {if nil == bt {return fmt.Errorf("get block tree by id [%s] failed after create", expectedID)diff --git a/kernel/model/shortcuts_creation.go b/kernel/model/shortcuts_creation.gonew file mode 100644index 0000000000..6fa103f935--- /dev/null+++ b/kernel/model/shortcuts_creation.go@@ -0,0 +1,123 @@+package model++import (+ "bytes"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "os"+ "path"+ "path/filepath"+ "strings"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/filelock"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// 记录只保存身份和摘要,不把加密笔记本标题或速记正文写入明文恢复文件。+type localShorthandCreation struct {+ Version int `json:"version"`+ Notebook string `json:"notebook"`+ ID string `json:"id"`+ Path string `json:"path"`+ Blocks []string `json:"blocks"`+ Sources map[string]string `json:"sources"`+}++func localShorthandCreationPath() string {+ return filepath.Join(util.ShortcutsPath, "shorthands", ".document-creation.json")+}++func beginLocalShorthandCreation(boxID, id, docPath string, blocks []string, sources map[string][]byte) error {+ if len(blocks) == 0 || len(sources) == 0 {+ return errors.New("shorthand creation requires source and block identities")+ }+ if _, err := os.Stat(localShorthandCreationPath()); !os.IsNotExist(err) {+ if err != nil {+ return err+ }+ return errors.New("a shorthand document creation is awaiting recovery")+ }+ record := localShorthandCreation{Version: 1, Notebook: boxID, ID: id, Path: docPath, Blocks: blocks, Sources: map[string]string{}}+ for filename, data := range sources {+ current, err := os.ReadFile(filename)+ if err != nil || !bytes.Equal(data, current) {+ return errors.New("shorthand source changed before document creation")+ }+ digest := sha256.Sum256(data)+ record.Sources[filepath.Base(filename)] = hex.EncodeToString(digest[:])+ }+ data, err := json.Marshal(record)+ if err != nil {+ return err+ }+ return atomicWriteFile(localShorthandCreationPath(), data)+}++// recoverLocalShorthandCreation 核对实际源中的完整块身份后才清理输入;缺失、认证失败和未知结果均不重放。+func recoverLocalShorthandCreation(boxID string) (string, error) {+ data, err := filelock.ReadFile(localShorthandCreationPath())+ if os.IsNotExist(err) {+ return "", nil+ }+ if err != nil {+ return "", err+ }+ var record localShorthandCreation+ decoder := json.NewDecoder(bytes.NewReader(data))+ decoder.DisallowUnknownFields()+ if err = decoder.Decode(&record); err != nil || record.Version != 1 || record.Notebook != boxID ||+ !ast.IsNodeIDPattern(record.ID) || len(record.Blocks) == 0 || len(record.Sources) == 0 {+ return "", errors.New("invalid or mismatched shorthand creation recovery record")+ }+ if decoder.Decode(new(any)) != io.EOF {+ return "", errors.New("invalid shorthand creation recovery record suffix")+ }+ if !strings.HasPrefix(record.Path, "/") || record.Path != path.Clean(record.Path) || path.Ext(record.Path) != ".sy" || util.GetTreeID(record.Path) != record.ID {+ return "", errors.New("invalid shorthand creation recovery path")+ }+ for _, segment := range bytes.Split([]byte(record.Path[1:len(record.Path)-3]), []byte("/")) {+ if !ast.IsNodeIDPattern(string(segment)) {+ return "", errors.New("invalid shorthand creation recovery identity")+ }+ }+ if current := treenode.GetBlockTreeInExactBox(record.ID, boxID); current != nil {+ record.Path = current.Path+ }+ tree, _, err := filesys.ReadTreeSnapshot(boxID, record.Path)+ if err != nil {+ return "", fmt.Errorf("review shorthand document siyuan://blocks/%s before retrying: %w", record.ID, err)+ }+ for _, id := range record.Blocks {+ if !ast.IsNodeIDPattern(id) || treenode.GetNodeInTree(tree, id) == nil {+ return "", fmt.Errorf("review incomplete shorthand document siyuan://blocks/%s before retrying", record.ID)+ }+ }+ for filename, expected := range record.Sources {+ if filepath.Base(filename) != filename || filepath.Ext(filename) != ".md" || len(expected) != 64 {+ return "", errors.New("invalid shorthand source recovery identity")+ }+ filename = filepath.Join(util.ShortcutsPath, "shorthands", filename)+ current, err := os.ReadFile(filename)+ if os.IsNotExist(err) {+ continue+ }+ if err != nil {+ return "", err+ }+ digest := sha256.Sum256(current)+ if hex.EncodeToString(digest[:]) != expected {+ return "", errors.New("shorthand source changed after document creation; keep it for review")+ }+ if err = os.Remove(filename); err != nil {+ return "", err+ }+ }+ return record.ID, filelock.Remove(localShorthandCreationPath())+}diff --git a/kernel/model/shortcuts_creation_test.go b/kernel/model/shortcuts_creation_test.gonew file mode 100644index 0000000000..4201c103a0--- /dev/null+++ b/kernel/model/shortcuts_creation_test.go@@ -0,0 +1,70 @@+package model++import (+ "os"+ "path/filepath"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestLocalShorthandCreationRecovery(t *testing.T) {+ for _, state := range []string{"committed", "missingBlock", "changedSource", "missingDocument"} {+ t.Run(state, func(t *testing.T) {+ fixture := setupFileOperationTest(t)+ original := util.ShortcutsPath+ util.ShortcutsPath = t.TempDir()+ t.Cleanup(func() { util.ShortcutsPath = original })+ directory := filepath.Join(util.ShortcutsPath, "shorthands")+ if err := os.MkdirAll(directory, 0755); err != nil {+ t.Fatal(err)+ }+ filename := filepath.Join(directory, "1234567890123.md")+ source := []byte("keep original source")+ if err := os.WriteFile(filename, source, 0644); err != nil {+ t.Fatal(err)+ }+ block := fixture.childID+ if state == "missingBlock" {+ block = ast.NewNodeID()+ }+ if err := beginLocalShorthandCreation(fixture.box.ID, fixture.sourceID, fixture.sourcePath,+ []string{block}, map[string][]byte{filename: source}); err != nil {+ t.Fatal(err)+ }+ if state == "changedSource" {+ if err := os.WriteFile(filename, []byte("new user input"), 0644); err != nil {+ t.Fatal(err)+ }+ } else if state == "missingDocument" {+ if err := os.Remove(filepath.Join(util.DataDir, fixture.box.ID, fixture.sourcePath)); err != nil {+ t.Fatal(err)+ }+ }+ id, err := recoverLocalShorthandCreation(fixture.box.ID)+ if state == "committed" {+ if err != nil || id != fixture.sourceID {+ t.Fatalf("committed recovery failed: %s, %v", id, err)+ }+ for _, name := range []string{filename, localShorthandCreationPath()} {+ if _, err := os.Stat(name); !os.IsNotExist(err) {+ t.Fatalf("confirmed source or journal was not consumed: %s, %v", name, err)+ }+ }+ if id, err = recoverLocalShorthandCreation(fixture.box.ID); err != nil || id != "" {+ t.Fatal("repeated recovery was not idempotent", id, err)+ }+ } else {+ if err == nil {+ t.Fatal("unverified outcome was accepted")+ }+ for _, name := range []string{filename, localShorthandCreationPath()} {+ if _, err := os.Stat(name); err != nil {+ t.Fatal("recovery discarded unresolved data", err)+ }+ }+ }+ })+ }+}diff --git a/kernel/model/storage.go b/kernel/model/storage.goindex 5df0231557..4259a2ea42 100644--- a/kernel/model/storage.go+++ b/kernel/model/storage.go@@ -20,7 +20,6 @@ import ("errors""fmt""os"- "path""path/filepath""sort""strings"@@ -554,7 +553,7 @@ func getRecentDocs(sortBy string) (ret []*RecentDoc, err error) {}if merged, ok := mergedDocs[bt.RootID]; !ok {- doc.Title = path.Base(bt.HPath) // Recent docs not updated after renaming https://github.com/siyuan-note/siyuan/issues/7827+ doc.Title = documentTitleText(bt.BoxID, bt.RootID)mergedDocs[bt.RootID] = docrootIDs = append(rootIDs, bt.RootID)} else {@@ -638,7 +637,7 @@ func getRecentDocs(sortBy string) (ret []*RecentDoc, err error) {}}// 获取文档标题- title := path.Base(bt.HPath)+ title := documentTitleText(bt.BoxID, bt.RootID)doc := &RecentDoc{RootID: sqlBlock.ID,Icon: icon,diff --git a/kernel/model/tag.go b/kernel/model/tag.goindex 0cf71f7d85..5fbdc2e79f 100644--- a/kernel/model/tag.go+++ b/kernel/model/tag.go@@ -99,7 +99,7 @@ func RemoveTag(label string) (err error) {for _, n := range unlinks {n.Unlink()}- util.PushEndlessProgress(fmt.Sprintf(Conf.Language(111), util.EscapeHTML(tree.Root.IALAttr("title"))))+ util.PushEndlessProgress(fmt.Sprintf(Conf.Language(111), util.EscapeHTML(treenode.ReadDocumentTitle(tree.Root).Text)))if err = writeTreeUpsertQueue(tree); err != nil {util.ClearPushProgress(100)return@@ -204,7 +204,7 @@ func RenameTag(oldLabel, newLabel string) (err error) {updateNodes[node.ID] = node}- util.PushEndlessProgress(fmt.Sprintf(Conf.Language(111), util.EscapeHTML(tree.Root.IALAttr("title"))))+ util.PushEndlessProgress(fmt.Sprintf(Conf.Language(111), util.EscapeHTML(treenode.ReadDocumentTitle(tree.Root).Text)))if err = writeTreeUpsertQueue(tree); err != nil {util.ClearPushProgress(100)returndiff --git a/kernel/model/template.go b/kernel/model/template.goindex 28abf1ec13..3c4c909644 100644--- a/kernel/model/template.go+++ b/kernel/model/template.go@@ -1038,6 +1038,12 @@ func renderTemplateSourceAt(p, id string, mode TemplateRenderMode, content *striif err = validateTemplateCallGraph(tpl, tpl.Name()); nil != err {return}+ var location *treenode.DocumentPath+ location, err = treenode.GetDocumentPath(sourceTree.Box, sourceTree.ID, sourceTree.Box, 1)+ if err != nil {+ return+ }+ collector.rootRevision = location.Revision}buf := &bytes.Buffer{}diff --git a/kernel/model/template_doc_tree.go b/kernel/model/template_doc_tree.goindex d5a3d1d016..ca645b6604 100644--- a/kernel/model/template_doc_tree.go+++ b/kernel/model/template_doc_tree.go@@ -74,15 +74,16 @@ type TemplateDocTreePlanSummary struct {}type templateDocTreePlan struct {- id string- rootID string- boxID string- rootPath string- rootHPath string- nodes []*TemplateDocTreeNode- trees []*parse.Tree- createdAt time.Time- expiresAt time.Time+ id string+ rootID string+ boxID string+ rootPath string+ rootHPath string+ rootRevision string+ nodes []*TemplateDocTreeNode+ trees []*parse.Tree+ createdAt time.Time+ expiresAt time.Time}type templateDocTreeCollector struct {@@ -90,6 +91,7 @@ type templateDocTreeCollector struct {boxID stringrootPath stringrootHPath string+ rootRevision stringtemplatePath stringnodes []*TemplateDocTreeNodeenabled bool@@ -233,7 +235,7 @@ func (collector *templateDocTreeCollector) bindNodes(nodes []*TemplateDocTreeNodfor _, node := range nodes {node.ParentID = parentIDnode.path = strings.TrimSuffix(parentPath, ".sy") + "/" + node.ID + ".sy"- node.HPath = path.Join(parentHPath, node.Title)+ node.HPath = strings.TrimRight(parentHPath, "/") + "/" + node.Titlecollector.bindNodes(node.Children, node.ID, node.path, node.HPath)}}@@ -243,6 +245,17 @@ func (collector *templateDocTreeCollector) renderDocRef(mode string, value any)return nil, errors.New("renderDocRef is only available when manually inserting or previewing a template")}switch mode {+ case "id":+ id, ok := value.(string)+ if !ok || !ast.IsNodeIDPattern(id) {+ return "", errors.New("renderDocRef id target must be a document ID")+ }+ for _, node := range flattenTemplateDocTreeNodes0(collector.nodes) {+ if node.ID == id || node.RootID == id {+ return fmt.Sprintf("((%s %q))", node.RootID, node.Title), nil+ }+ }+ return "", nilcase "children":id, ok := value.(string)if !ok {@@ -359,14 +372,15 @@ func (collector *templateDocTreeCollector) summary(id string) *TemplateDocTreePlfunc (collector *templateDocTreeCollector) storePlan() *TemplateDocTreePlanSummary {id := ast.NewNodeID()plan := &templateDocTreePlan{- id: id,- rootID: collector.rootID,- boxID: collector.boxID,- rootPath: collector.rootPath,- rootHPath: collector.rootHPath,- nodes: flattenTemplateDocTreeNodes0(collector.nodes),- createdAt: time.Now(),- expiresAt: time.Now().Add(templateDocTreePlanTTL),+ id: id,+ rootID: collector.rootID,+ boxID: collector.boxID,+ rootPath: collector.rootPath,+ rootHPath: collector.rootHPath,+ rootRevision: collector.rootRevision,+ nodes: flattenTemplateDocTreeNodes0(collector.nodes),+ createdAt: time.Now(),+ expiresAt: time.Now().Add(templateDocTreePlanTTL),}for _, node := range plan.nodes {plan.trees = append(plan.trees, node.tree)@@ -492,10 +506,15 @@ func AttachTemplateDocTreePlans(transactions []*Transaction) (attached bool, err}rootTree, loadErr := LoadTreeByBlockID(plan.rootID)if nil != loadErr || nil == rootTree || rootTree.Box != plan.boxID || rootTree.Path != plan.rootPath ||- rootTree.HPath != plan.rootHPath {+ plan.rootRevision == "" {+ return false, errors.New("the document used to render the template has changed")+ }+ location, locationErr := treenode.GetDocumentPath(plan.boxID, plan.rootID, plan.boxID, 1)+ if locationErr != nil || location.Revision != plan.rootRevision {return false, errors.New("the document used to render the template has changed")}target.templateDocTreeRootSnapshot = rootTree+ target.templateDocTreeRootRevision = plan.rootRevisionbox := Conf.Box(plan.boxID)if nil == box {return false, ErrBoxNotFounddiff --git a/kernel/model/template_doc_tree_test.go b/kernel/model/template_doc_tree_test.goindex 819cd5df5f..fd35eb086c 100644--- a/kernel/model/template_doc_tree_test.go+++ b/kernel/model/template_doc_tree_test.go@@ -334,6 +334,7 @@ func TestRenderTemplateDocumentReferencesUsePlannedIDs(t *testing.T) {)}.action{range $doc := renderDocRef "children" .id}- ((.action{$doc.RootID} ".action{$doc.HPath}"))+- .action{renderDocRef "id" $doc.ID}.action{end}.action{renderDocRef "path" "/第一章/1.1 概念"}.action{renderDocRef "path" "/Source/第一章/1.1 概念"}`)@@ -590,10 +591,10 @@ func TestAttachTemplateDocTreePlansValidatesTransactionBoundary(t *testing.T) {if !ok {t.Fatalf("document tree plan [%s] was not stored", summary.ID)}- value.(*templateDocTreePlan).rootHPath = "/Changed"+ value.(*templateDocTreePlan).rootRevision = "changed-ancestor-identity-or-title"transaction, _ = newTemplateDocTreeInsertTransaction(summary.ID, fixture.sourceID)if attached, attachErr := AttachTemplateDocTreePlans([]*Transaction{transaction}); nil == attachErr || attached {- t.Fatalf("plan rendered for another human-readable path was accepted: attached=%t, err=%v", attached, attachErr)+ t.Fatalf("plan with a different ancestor revision was accepted: attached=%t, err=%v", attached, attachErr)}clearTemplateDocTreePlansForTest()diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex 1bd9ff6c18..51b332e415 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -2754,25 +2754,27 @@ type Transaction struct {mutatedRootIDs []string // 提交后保留实际修改的文档 ID,避免为查询结果持有文档树boxIcons map[string]string // 事务提交后需要同步的笔记本图标- isGlobalAssetsInit bool // 是否初始化过全局资源判断- isGlobalAssets bool // 是否属于全局资源- assetsDir string // 资源目录路径- removedCreatedDocs []*parse.Tree- removedTemplateCreatedDocs []*parse.Tree- restoredCreatedDocs []*parse.Tree- restoredTemplateCreatedDocs []*parse.Tree- restoredCreatedDocBoxes map[string]string- attemptedTemplateCreatedDocs map[string]*parse.Tree- templateDocTreeRootSnapshot *parse.Tree- removeCreatedDoc func(*Box, string, *lute.Lute) (*parse.Tree, error)- writeTransactionTree func(*parse.Tree) error- blockSwapOriginalTrees []*parse.Tree- attributeViewRollback *attributeViewRollback- attributeViewAutomations *attributeViewAutomationState- pushAutomationMessage func(string, int) string- attributeViewCollections *attributeViewCollectionState- attributeViewItemCreation bool- invalidatedAvHistory map[string]bool+ isGlobalAssetsInit bool // 是否初始化过全局资源判断+ isGlobalAssets bool // 是否属于全局资源+ assetsDir string // 资源目录路径+ removedCreatedDocs []*parse.Tree+ removedTemplateCreatedDocs []*parse.Tree+ restoredCreatedDocs []*parse.Tree+ restoredTemplateCreatedDocs []*parse.Tree+ restoredCreatedDocBoxes map[string]string+ attemptedTemplateCreatedDocs map[string]*parse.Tree+ templateDocTreeRootSnapshot *parse.Tree+ templateDocTreeRootRevision string+ templateDocTreeCommitRevision string+ removeCreatedDoc func(*Box, string, *lute.Lute) (*parse.Tree, error)+ writeTransactionTree func(*parse.Tree) error+ blockSwapOriginalTrees []*parse.Tree+ attributeViewRollback *attributeViewRollback+ attributeViewAutomations *attributeViewAutomationState+ pushAutomationMessage func(string, int) string+ attributeViewCollections *attributeViewCollectionState+ attributeViewItemCreation bool+ invalidatedAvHistory map[string]boolfromAPI bool // 是否来自 /api/transactions HTTP 入口(用于撤销日志捕获判别)isReplay bool // 是否为 undo/redo 重放构造的事务(重放不再进入撤销日志)@@ -2848,6 +2850,9 @@ func (tx *Transaction) WaitForCommit() {func (tx *Transaction) begin() (err error) {expectedTemplateDocTreeRoot := tx.templateDocTreeRootSnapshot+ expectedTemplateDocTreeRevision := tx.templateDocTreeRootRevision+ tx.templateDocTreeCommitRevision = expectedTemplateDocTreeRevision+ tx.templateDocTreeRootRevision = ""tx.templateDocTreeRootSnapshot = niltx.trees = map[string]*parse.Tree{}tx.nodes = map[string]*ast.Node{}@@ -2891,9 +2896,15 @@ func (tx *Transaction) begin() (err error) {}if nil != expectedTemplateDocTreeRoot &&(expectedTemplateDocTreeRoot.ID != snapshot.ID || expectedTemplateDocTreeRoot.Box != snapshot.Box ||- expectedTemplateDocTreeRoot.Path != snapshot.Path || expectedTemplateDocTreeRoot.HPath != snapshot.HPath) {+ expectedTemplateDocTreeRoot.Path != snapshot.Path) {return errors.New("the document used to render the template has changed")}+ if expectedTemplateDocTreeRevision != "" {+ location, err := treenode.GetDocumentPath(snapshot.Box, snapshot.ID, snapshot.Box, 1)+ if err != nil || location.Revision != expectedTemplateDocTreeRevision {+ return errors.New("the document used to render the template has changed")+ }+ }tx.templateDocTreeRootSnapshot = snapshot}if nil == tx.templateDocTreeRootSnapshot || tx.templateDocTreeRootSnapshot.ID != operation.templateDocTreeRootID ||@@ -3007,7 +3018,20 @@ func (tx *Transaction) commit() (err error) {writeTransactionTree := tx.writeTransactionTreeif nil == writeTransactionTree {writeTransactionTree = func(source *parse.Tree) error {- return writeTreeUpsertQueueWithChanges(source, tx.treeIndexChanges(source))+ return writeTreeUpsertQueueWithPreflight(source, tx.treeIndexChanges(source), func() error {+ if tx.templateDocTreeCommitRevision == "" {+ return nil+ }+ root := tx.templateDocTreeRootSnapshot+ if root == nil {+ return errors.New("template document tree parent snapshot is missing")+ }+ location, err := treenode.GetDocumentPath(root.Box, root.ID, root.Box, 1)+ if err != nil || location.Revision != tx.templateDocTreeCommitRevision {+ return errors.New("the document used to render the template has changed")+ }+ return nil+ })}}if err = writeTransactionTree(tree); err != nil {@@ -3299,7 +3323,7 @@ func (tx *Transaction) writeTreeWithIndexChanges(tree *parse.Tree) {if err := tx.captureCollectionTree(tree); err != nil {tx.collectionState().err = err}- treenode.UpsertBlockTree(tree)+ treenode.UpsertBlockTreePending(tree)}func getRefsCacheByDefNode(updateNode *ast.Node, boxID string) (ret []*sql.Ref, changedNodes []*ast.Node) {diff --git a/kernel/model/tree.go b/kernel/model/tree.goindex 7ae7b2318b..cfa13082d9 100644--- a/kernel/model/tree.go+++ b/kernel/model/tree.go@@ -47,7 +47,7 @@ func resetTree(tree *parse.Tree, titleSuffix string, removeAvBinding bool) {oldRootID := tree.Root.IDtree.ID = ast.NewNodeID()tree.Root.ID = tree.ID- title := tree.Root.IALAttr("title")+ title := treenode.ReadDocumentTitle(tree.Root).Textif "" != titleSuffix {if t, parseErr := time.Parse("20060102150405", util.TimeFromID(tree.ID)); nil == parseErr {titleSuffix += " " + t.Format("2006-01-02 15:04:05")@@ -431,7 +431,6 @@ func findUnindexedTreePath(id string, normalOnly bool) (ret string) {}root := filepath.Join(util.DataDir, box.ID)paths := search.FindAllMatchedPaths(root, []string{id})- var rootIDs []stringrootIDPaths := map[string]string{}for _, p := range paths {base := filepath.ToSlash(p)@@ -445,17 +444,10 @@ func findUnindexedTreePath(id string, normalOnly bool) (ret string) {if !ast.IsNodeIDPattern(rootID) {continue}- rootIDs = append(rootIDs, rootID)rootIDPaths[rootID] = p}-- result := treenode.ExistBlockTrees(rootIDs)- for rootID, exist := range result {- if exist {- continue- }-- matchedPath := rootIDPaths[rootID]+ // 文档摘要已经提交不代表正文块索引完整;仍需验证匹配文件中的实际块身份。+ for _, matchedPath := range rootIDPaths {relPath, relErr := filepath.Rel(root, matchedPath)if nil != relErr {return matchedPathdiff --git a/kernel/model/virutalref.go b/kernel/model/virutalref.goindex 06fcc98055..5c31139a74 100644--- a/kernel/model/virutalref.go+++ b/kernel/model/virutalref.go@@ -325,7 +325,7 @@ func getVirtualRefKeywords(root *ast.Node, boxIDs ...string) (ret []string) {// 虚拟引用排除当前文档名 https://github.com/siyuan-note/siyuan/issues/4537// Virtual references exclude the name and aliases from the current document https://github.com/siyuan-note/siyuan/issues/9204- title := root.IALAttr("title")+ title := treenode.ReadDocumentTitle(root).Textret = gulu.Str.ExcludeElem(ret, []string{title})if name := root.IALAttr("name"); "" != name {ret = gulu.Str.ExcludeElem(ret, []string{name})diff --git a/kernel/sql/block.go b/kernel/sql/block.goindex d18609ff97..f07dde5840 100644--- a/kernel/sql/block.go+++ b/kernel/sql/block.go@@ -203,7 +203,7 @@ func nodeStaticContent(node *ast.Node, excludeTypes []string, includeTextMarkATi}if ast.NodeDocument == node.Type {- return html.EscapeHTMLStr(node.IALAttr("title"))+ return html.EscapeHTMLStr(treenode.ReadDocumentTitle(node).Text)}if ast.NodeAttributeView == node.Type {diff --git a/kernel/sql/block_query.go b/kernel/sql/block_query.goindex 98916d6a16..2b3baadb1c 100644--- a/kernel/sql/block_query.go+++ b/kernel/sql/block_query.go@@ -89,7 +89,7 @@ func queryBlockHashes(tx *sql.Tx, rootID string) (ret map[string]string) {func QueryRootBlockByCondition(condition, exactKeyword string, limit int, args ...any) (ret []*Block) {exactCondition, exactArg := rootBlockExactMatchCondition(exactKeyword, caseSensitive.Load())- sqlStmt := "SELECT *, length(hpath) - length(replace(hpath, '/', '')) AS lv FROM blocks WHERE type = 'd' AND " + condition ++ sqlStmt := "SELECT *, length(path) - length(replace(path, '/', '')) AS lv FROM blocks WHERE type = 'd' AND " + condition +" ORDER BY CASE WHEN " + exactCondition + " THEN 0 ELSE 1 END ASC, box DESC, lv ASC LIMIT ?"args = append(args, exactArg...)args = append(args, limit)@@ -113,7 +113,7 @@ func QueryRootBlockByCondition(condition, exactKeyword string, limit int, args .func QueryRootBlockByConditionInBox(condition, exactKeyword string, limit int, boxID string, args ...any) (ret []*Block) {exactCondition, exactArg := rootBlockExactMatchCondition(exactKeyword, caseSensitive.Load())- sqlStmt := "SELECT *, length(hpath) - length(replace(hpath, '/', '')) AS lv FROM blocks WHERE type = 'd' AND " + condition ++ sqlStmt := "SELECT *, length(path) - length(replace(path, '/', '')) AS lv FROM blocks WHERE type = 'd' AND " + condition +" ORDER BY CASE WHEN " + exactCondition + " THEN 0 ELSE 1 END ASC, box DESC, lv ASC LIMIT ?"args = append(args, exactArg...)args = append(args, limit)diff --git a/kernel/sql/block_query_test.go b/kernel/sql/block_query_test.goindex 935fdef27d..7ba12e633f 100644--- a/kernel/sql/block_query_test.go+++ b/kernel/sql/block_query_test.go@@ -113,6 +113,29 @@ func TestRootBlockExactMatchCondition(t *testing.T) {}}+func TestDocumentSearchDepthUsesIdentityPath(t *testing.T) {+ testDB := createGraphTestBlocksTable(t)+ previousDB := db+ db = testDB+ t.Cleanup(func() { db = previousDB })+ for _, doc := range []struct{ id, dataPath, displayPath string }{+ {"nested", "/parent/nested.sy", "/Parent/Child"},+ {"literal", "/literal.sy", "/Literal/title/with/separators"},+ } {+ _, err := testDB.Exec(`INSERT INTO blocks SELECT ?, '', ?, '', 'box', ?, ?, '', '', '', '',+ 'Title', '', '', 0, 'd', '', '', 0, '', ''`, doc.id, doc.id, doc.dataPath, doc.displayPath)+ if err != nil {+ t.Fatal(err)+ }+ }+ for _, result := range [][]*Block{QueryRootBlockByCondition("1=1", "no exact match", 10),+ QueryRootBlockByConditionInBox("1=1", "no exact match", 10, "box")} {+ if len(result) != 2 || result[0].ID != "literal" || result[1].ID != "nested" {+ t.Fatalf("display title changed structural depth: %+v", result)+ }+ }+}+func TestQueryLikeEscape(t *testing.T) {testDB, err := gosql.Open("sqlite3_extended", ":memory:")if err != nil {diff --git a/kernel/sql/database.go b/kernel/sql/database.goindex eeeff25b98..395a92d922 100644--- a/kernel/sql/database.go+++ b/kernel/sql/database.go@@ -1008,7 +1008,7 @@ func buildBlockFromNodeWithHeadingParent(n *ast.Node, tree *parse.Tree, headingPhash := treenode.NodeHashWithHeadingParent(n, tree, luteEngine, headingParent)var length intif ast.NodeDocument == n.Type {- content = n.IALAttr("title")+ content = treenode.ReadDocumentTitle(n).Textfcontent = contentlength = utf8.RuneCountInString(fcontent)} else if n.IsContainerBlock() {diff --git a/kernel/sql/document_title.go b/kernel/sql/document_title.gonew file mode 100644index 0000000000..987c0b7d7c--- /dev/null+++ b/kernel/sql/document_title.go@@ -0,0 +1,30 @@+package sql++import (+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/siyuan/kernel/treenode"+)++// currentDocumentIndexSnapshot 为排队中的索引取得当前标题摘要,只复制根属性,不修改编辑树。+// 此副本仅用于派生索引,不能作为源文档保存,避免旧正文与新标题源混合回写。+func currentDocumentIndexSnapshot(source *parse.Tree) *parse.Tree {+ tree := *source+ tree.HPath = treenode.CurrentTreeHPath(&tree)+ meta, err := treenode.GetDocumentMetadata(tree.Box, tree.ID)+ if err != nil || meta.Path != tree.Path || meta.Title == treenode.ReadDocumentTitle(tree.Root) {+ return &tree+ }+ root := *tree.Root+ root.KramdownIAL = make([][]string, len(tree.Root.KramdownIAL))+ for i, attr := range tree.Root.KramdownIAL {+ root.KramdownIAL[i] = append([]string(nil), attr...)+ }+ root.SetIALAttr("title", meta.Title.Text)+ if meta.Title.Empty {+ root.SetIALAttr(treenode.DocumentTitleEmptyAttr, "true")+ } else {+ root.RemoveIALAttr(treenode.DocumentTitleEmptyAttr)+ }+ tree.Root = &root+ return &tree+}diff --git a/kernel/sql/queue.go b/kernel/sql/queue.goindex 9239389f15..7f046fe2e9 100644--- a/kernel/sql/queue.go+++ b/kernel/sql/queue.go@@ -21,7 +21,6 @@ import ("errors""fmt""os"- "path""runtime/debug""sort""sync"@@ -418,14 +417,10 @@ func execOp(op *dbQueueOperation, tx *sql.Tx, context map[string]any) (err error}}if op.indexTree != nil && op.action != "rename" {- tree := *op.indexTree- tree.HPath = treenode.CurrentTreeHPath(&tree)- op.indexTree = &tree+ op.indexTree = currentDocumentIndexSnapshot(op.indexTree)}if op.upsertTree != nil && op.action == "upsert" {- tree := *op.upsertTree- tree.HPath = treenode.CurrentTreeHPath(&tree)- op.upsertTree = &tree+ op.upsertTree = currentDocumentIndexSnapshot(op.upsertTree)}switch op.action {case "index":@@ -467,7 +462,7 @@ func execOp(op *dbQueueOperation, tx *sql.Tx, context map[string]any) (err errorbreak}- err = updateRootContent(tx, path.Base(op.indexTree.HPath), op.indexTree.Root.IALAttr("updated"), treenode.IALStr(op.indexTree.Root), op.indexTree.ID)+ err = updateRootContent(tx, treenode.ReadDocumentTitle(op.indexTree.Root).Text, op.indexTree.Root.IALAttr("updated"), treenode.IALStr(op.indexTree.Root), op.indexTree.ID)if nil == err {tx.Exec("UPDATE block_embeddings SET box = ?, path = ? WHERE root_id = ?", op.indexTree.Box, op.indexTree.Path, op.indexTree.ID)}diff --git a/kernel/treenode/blocktree.go b/kernel/treenode/blocktree.goindex 7dd7f78292..2bc4564cba 100644--- a/kernel/treenode/blocktree.go+++ b/kernel/treenode/blocktree.go@@ -74,6 +74,9 @@ func initDatabase(forceRebuild bool) {}}if !forceRebuild {+ if err := ensureDocumentMetadata(db); err != nil {+ logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create document metadata failed: %s", err)+ }if err := ensureHPathIndexes(db); err != nil {logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create hpath indexes failed: %s", err)}@@ -96,6 +99,15 @@ func initDatabase(forceRebuild bool) {}func initDBTables() {+ if _, err := db.Exec("DROP TABLE IF EXISTS document_metadata_pending"); err != nil {+ logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "drop document metadata pending failed: %s", err)+ }+ if _, err := db.Exec("DROP TABLE IF EXISTS document_metadata_state"); err != nil {+ logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "drop document metadata state failed: %s", err)+ }+ if _, err := db.Exec("DROP TABLE IF EXISTS document_metadata"); err != nil {+ logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "drop document metadata failed: %s", err)+ }_, err := db.Exec("DROP TABLE IF EXISTS blocktrees")if err != nil {logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "drop table [blocks] failed: %s", err)@@ -125,6 +137,9 @@ func initDBTables() {if err = ensureBlockTreeTypeIndex(db); err != nil {logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create blocktree type index failed: %s", err)}+ if err = ensureDocumentMetadata(db); err != nil {+ logging.LogFatalf(logging.ExitCodeUnavailableDatabase, "create document metadata failed: %s", err)+ }}func ensureBlockTreeTypeIndex(database *sql.DB) (err error) {@@ -534,8 +549,7 @@ func CheckListItemNesting(parentID, childID string) error {}func SetBlockTreePath(tree *parse.Tree) {- RemoveBlockTreesByRootID(tree.Box, tree.ID)- IndexBlockTree(tree)+ indexBlockTree(tree, true)}func RemoveBlockTreesByRootID(boxID, rootID string) {@@ -683,6 +697,10 @@ func RemoveBlockTree(boxID, id string) {var indexBlockTreeLock = sync.Mutex{}func IndexBlockTree(tree *parse.Tree) {+ indexBlockTree(tree, false)+}++func indexBlockTree(tree *parse.Tree, replace bool) {tree.HPath = CurrentParentHPath(tree)var changedNodes []*ast.Nodeast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {@@ -713,6 +731,14 @@ func IndexBlockTree(tree *parse.Tree) {return}+ if replace {+ // 文档行与摘要的删除、重建处于同一事务,不向并发读取暴露短暂的缺失身份。+ if _, err = tx.Exec("DELETE FROM blocktrees WHERE root_id = ?", tree.ID); err != nil {+ tx.Rollback()+ logging.LogErrorf("replace document block tree failed: %s", err)+ return+ }+ }execInsertBlocktrees(tx, tree, changedNodes)if err = tx.Commit(); err != nil {@@ -721,7 +747,18 @@ func IndexBlockTree(tree *parse.Tree) {}func UpsertBlockTree(tree *parse.Tree) {+ upsertBlockTree(tree, true)+}++// UpsertBlockTreePending 供尚未落盘的编辑事务定位块;标题摘要仍保留已提交的源状态。+func UpsertBlockTreePending(tree *parse.Tree) {+ upsertBlockTree(tree, false)+}++func upsertBlockTree(tree *parse.Tree, publishMetadata bool) {tree.HPath = CurrentParentHPath(tree)+ metadata, metadataErr := GetDocumentMetadata(tree.Box, tree.ID)+ metadataChanged := metadataErr != nil || metadata.Revision != documentMetadataFromTree(tree).RevisionoldBts := map[string]*BlockTree{}bts := GetBlockTreesByRootIDInBox(tree.ID, tree.Box)for _, bt := range bts {@@ -735,7 +772,7 @@ func UpsertBlockTree(tree *parse.Tree) {}if oldBt, found := oldBts[n.ID]; found {- if oldBt.Updated != n.IALAttr("updated") || oldBt.Type != TypeAbbr(n.Type.String()) || oldBt.Path != tree.Path || oldBt.BoxID != tree.Box || oldBt.HPath != tree.HPath {+ if (n == tree.Root && metadataChanged) || oldBt.Updated != n.IALAttr("updated") || oldBt.Type != TypeAbbr(n.Type.String()) || oldBt.Path != tree.Path || oldBt.BoxID != tree.Box || oldBt.HPath != tree.HPath {children := ChildBlockNodes(n) // 需要考虑子块,因为一些操作(比如移动块)后需要同时更新子块changedNodes = append(changedNodes, children...)if n.IsContainerBlock() && n.Type != ast.NodeDocument {@@ -780,7 +817,8 @@ func UpsertBlockTree(tree *parse.Tree) {return}- sqlStmt := "DELETE FROM blocktrees WHERE id IN (" + ids.String() + ")"+ // 文档行原地更新,避免未提交事务触发摘要删除。+ sqlStmt := "DELETE FROM blocktrees WHERE type != 'd' AND id IN (" + ids.String() + ")"_, err = tx.Exec(sqlStmt)if err != nil {tx.Rollback()@@ -788,7 +826,7 @@ func UpsertBlockTree(tree *parse.Tree) {return}- execInsertBlocktrees(tx, tree, changedNodes)+ execInsertBlocktreesWithMetadata(tx, tree, changedNodes, publishMetadata)if err = tx.Commit(); err != nil {logging.LogErrorf("commit transaction failed: %s", err)@@ -796,6 +834,17 @@ func UpsertBlockTree(tree *parse.Tree) {}func execInsertBlocktrees(tx *sql.Tx, tree *parse.Tree, changedNodes []*ast.Node) {+ execInsertBlocktreesWithMetadata(tx, tree, changedNodes, true)+}++func execInsertBlocktreesWithMetadata(tx *sql.Tx, tree *parse.Tree, changedNodes []*ast.Node, publishMetadata bool) {+ if publishMetadata {+ if err := upsertDocumentMetadata(tx, tree); err != nil {+ tx.Rollback()+ logging.LogErrorf("update document metadata failed: %s", err)+ return+ }+ }sqlStmt := "INSERT INTO blocktrees (id, root_id, parent_id, box_id, path, hpath, updated, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"stmt, err := tx.Prepare(sqlStmt)if err != nil {@@ -820,6 +869,19 @@ func execInsertBlocktrees(tx *sql.Tx, tree *parse.Tree, changedNodes []*ast.Nodeif nil != n.Parent {parentID = n.Parent.ID}+ if n.Type == ast.NodeDocument {+ result, updateErr := tx.Exec(`UPDATE blocktrees SET root_id=?, parent_id=?, path=?, hpath=?, updated=?+ WHERE box_id=? AND id=? AND type='d'`, tree.ID, parentID, tree.Path, tree.HPath,+ n.IALAttr("updated"), tree.Box, n.ID)+ if updateErr != nil {+ tx.Rollback()+ logging.LogErrorf("update document blocktree failed: %s", updateErr)+ return+ }+ if count, _ := result.RowsAffected(); count > 0 {+ continue+ }+ }if _, err = tx.Exec(sqlStmt, n.ID, tree.ID, parentID, tree.Box, tree.Path, tree.HPath, n.IALAttr("updated"), TypeAbbr(n.Type.String())); err != nil {tx.Rollback()logging.LogErrorf("exec database stmt [%s] failed: %s\n %s", sqlStmt, err, logging.ShortStack())@@ -1031,6 +1093,7 @@ func initEncryptedBlockTreeTables(boxDB *sql.DB) (err error) {if err = cleanupInvalidBlockTrees(boxDB); err != nil {return}+ err = ensureDocumentMetadata(boxDB)return}@@ -1074,6 +1137,9 @@ func beginTxForBox(box string) (tx *sql.Tx, err error) {if IsEncryptedBoxFn != nil && IsEncryptedBoxFn(box) {return nil, errors.New("encrypted blocktree db not opened for box " + box)}+ if db == nil {+ return nil, errBlockTreeDBUnavailable+ }return db.Begin()}diff --git a/kernel/treenode/document_metadata.go b/kernel/treenode/document_metadata.gonew file mode 100644index 0000000000..60e973b818--- /dev/null+++ b/kernel/treenode/document_metadata.go@@ -0,0 +1,381 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package treenode++import (+ "crypto/sha256"+ "database/sql"+ "encoding/hex"+ "encoding/json"+ "errors"+ "path"+ "strings"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+)++var ErrDocumentMetadataUnavailable = errors.New("document metadata is not ready")++// DocumentMetadata 仅是可重建的内部索引;父身份来自 ID 数据路径,不来自展示文字。+type DocumentMetadata struct {+ BoxID string+ ID string+ ParentID *string+ Path string+ Title DocumentTitle+ SourceSpec string+ Revision string+}++type DocumentPathSegment struct {+ ID string `json:"id"`+ Text string `json:"text"`+ Empty bool `json:"empty"`+}++// DocumentPath 的标题与段落边界来自同一个数据库快照,displayPath 仅用于展示。+type DocumentPath struct {+ Notebook string `json:"notebook"`+ ID string `json:"id"`+ ParentID *string `json:"parentID"`+ Path string `json:"path"`+ Title DocumentTitle `json:"title"`+ Segments []DocumentPathSegment `json:"segments"`+ Depth int `json:"depth"`+ DisplayPath string `json:"displayPath"`+ Revision string `json:"revision"`+ AddressingVersion int `json:"addressingVersion"`+}++func ensureDocumentMetadata(database *sql.DB) error {+ for _, stmt := range []string{+ `CREATE TABLE IF NOT EXISTS document_metadata (+ box_id TEXT NOT NULL, id TEXT NOT NULL, parent_id TEXT,+ title_text TEXT NOT NULL COLLATE BINARY, title_empty INTEGER NOT NULL,+ title_format TEXT NOT NULL, source_spec TEXT NOT NULL, revision TEXT NOT NULL,+ PRIMARY KEY (box_id, id))`,+ `CREATE INDEX IF NOT EXISTS idx_document_metadata_parent_title ON document_metadata(box_id, parent_id, title_text, id)`,+ `CREATE TABLE IF NOT EXISTS document_metadata_state (box_id TEXT PRIMARY KEY, version INTEGER NOT NULL, state TEXT NOT NULL)`,+ `CREATE TABLE IF NOT EXISTS document_metadata_pending (+ box_id TEXT NOT NULL, id TEXT NOT NULL, path TEXT NOT NULL, revision TEXT NOT NULL,+ PRIMARY KEY (box_id, id))`,+ `CREATE TRIGGER IF NOT EXISTS delete_document_metadata AFTER DELETE ON blocktrees+ WHEN OLD.type = 'd' BEGIN+ DELETE FROM document_metadata WHERE box_id = OLD.box_id AND id = OLD.id;+ END`,+ } {+ if _, err := database.Exec(stmt); err != nil {+ return err+ }+ }+ return nil+}++// DocumentRevision 使用版本化 JSON 字段边界,避免拼接碰撞及秒级时间戳遗漏连续更改。+func DocumentRevision(value interface{}) string {+ data, _ := json.Marshal(value)+ digest := sha256.Sum256(data)+ return "1:" + hex.EncodeToString(digest[:])+}++func documentMetadataFromTree(tree *parse.Tree) *DocumentMetadata {+ ret := &DocumentMetadata{BoxID: tree.Box, ID: tree.ID, Path: tree.Path,+ Title: ReadDocumentTitle(tree.Root), SourceSpec: tree.Root.Spec}+ if parent := path.Dir(tree.Path); parent != "/" && parent != "." {+ id := path.Base(parent)+ ret.ParentID = &id+ }+ ret.Revision = DocumentRevision([]interface{}{1, ret.BoxID, ret.ID, ret.Path, ret.Title, ret.SourceSpec})+ return ret+}++func upsertDocumentMetadata(tx *sql.Tx, tree *parse.Tree) error {+ meta := documentMetadataFromTree(tree)+ _, err := tx.Exec(`INSERT INTO document_metadata+ (box_id, id, parent_id, title_text, title_empty, title_format, source_spec, revision)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(box_id, id) DO UPDATE SET+ parent_id=excluded.parent_id, title_text=excluded.title_text, title_empty=excluded.title_empty,+ title_format=excluded.title_format, source_spec=excluded.source_spec, revision=excluded.revision`,+ meta.BoxID, meta.ID, meta.ParentID, meta.Title.Text, meta.Title.Empty, meta.Title.Format, meta.SourceSpec, meta.Revision)+ return err+}++const documentMetadataColumns = `m.box_id, m.id, m.parent_id, b.path,+ m.title_text, m.title_empty, m.title_format, m.source_spec, m.revision`+const documentMetadataJoin = `document_metadata m JOIN blocktrees b ON+ b.box_id=m.box_id AND b.id=m.id AND b.type='d'`++func scanDocumentMetadata(row interface{ Scan(...interface{}) error }) (*DocumentMetadata, error) {+ ret := &DocumentMetadata{}+ if err := row.Scan(&ret.BoxID, &ret.ID, &ret.ParentID, &ret.Path,+ &ret.Title.Text, &ret.Title.Empty, &ret.Title.Format, &ret.SourceSpec, &ret.Revision); err != nil {+ return nil, err+ }+ if ret.Title.Format != "plain" || ret.Revision != DocumentRevision([]interface{}{1, ret.BoxID, ret.ID, ret.Path, ret.Title, ret.SourceSpec}) {+ return nil, ErrDocumentMetadataUnavailable+ }+ return ret, nil+}++func DocumentMetadataState(boxID string) string {+ row := queryRowForBox(boxID, "SELECT state FROM document_metadata_state WHERE box_id=? AND version=1", boxID)+ var state string+ if row == nil || row.Scan(&state) != nil {+ return "missing"+ }+ if state == "ready" {+ var pending bool+ row = queryRowForBox(boxID, "SELECT EXISTS(SELECT 1 FROM document_metadata_pending WHERE box_id=?)", boxID)+ if row == nil || row.Scan(&pending) != nil || pending {+ return "building"+ }+ }+ return state+}++// SetDocumentMetadataState 仅在全部文档摘要已补齐时发布 ready,中断的 building 可再次恢复。+func SetDocumentMetadataState(boxID, state string) error {+ indexBlockTreeLock.Lock()+ defer indexBlockTreeLock.Unlock()+ tx, err := beginTxForBox(boxID)+ if err != nil {+ return err+ }+ defer tx.Rollback()+ if state == "ready" {+ var missing bool+ if err = tx.QueryRow(`SELECT EXISTS(SELECT 1 FROM blocktrees b LEFT JOIN document_metadata m+ ON m.box_id=b.box_id AND m.id=b.id WHERE b.box_id=? AND b.type='d' AND m.id IS NULL)+ OR EXISTS(SELECT 1 FROM document_metadata_pending WHERE box_id=?)`, boxID, boxID).Scan(&missing); err != nil {+ return err+ }+ if missing {+ return ErrDocumentMetadataUnavailable+ }+ }+ if _, err = tx.Exec(`INSERT INTO document_metadata_state (box_id, version, state) VALUES (?, 1, ?)+ ON CONFLICT(box_id) DO UPDATE SET version=1, state=excluded.state`, boxID, state); err != nil {+ return err+ }+ return tx.Commit()+}++// BeginDocumentMetadataWrite 在源替换前记录恢复身份;正文保存而摘要未变时不产生额外写入。+// 独立的源文件工具可在索引尚未打开时运行,之后由全量索引建立摘要。+func BeginDocumentMetadataWrite(tree *parse.Tree) (bool, error) {+ indexBlockTreeLock.Lock()+ defer indexBlockTreeLock.Unlock()+ if db == nil && getEncryptedBlockTreeDB(tree.Box) == nil {+ return false, nil+ }+ meta := documentMetadataFromTree(tree)+ current, err := GetDocumentMetadata(tree.Box, tree.ID)+ if err == nil && current.Revision == meta.Revision {+ var pending bool+ row := queryRowForBox(tree.Box, "SELECT EXISTS(SELECT 1 FROM document_metadata_pending WHERE box_id=? AND id=?)", tree.Box, tree.ID)+ if row == nil {+ return false, ErrDocumentMetadataUnavailable+ }+ if err = row.Scan(&pending); err != nil {+ return false, err+ }+ if !pending {+ return false, nil+ }+ }+ _, err = execForBox(tree.Box, `INSERT INTO document_metadata_pending (box_id, id, path, revision)+ VALUES (?, ?, ?, ?) ON CONFLICT(box_id, id) DO UPDATE SET path=excluded.path, revision=excluded.revision`,+ tree.Box, tree.ID, tree.Path, meta.Revision)+ return err == nil, err+}++// BeginDocumentMetadataRecovery 在原始文件变更前登记身份,恢复时只信任实际认证源。+func BeginDocumentMetadataRecovery(doc *BlockTree) (bool, error) {+ indexBlockTreeLock.Lock()+ defer indexBlockTreeLock.Unlock()+ if db == nil && getEncryptedBlockTreeDB(doc.BoxID) == nil {+ return false, nil+ }+ _, err := execForBox(doc.BoxID, `INSERT INTO document_metadata_pending (box_id, id, path, revision)+ VALUES (?, ?, ?, '') ON CONFLICT(box_id, id) DO UPDATE SET path=excluded.path, revision=''`,+ doc.BoxID, doc.ID, doc.Path)+ return err == nil, err+}++// CommitDocumentMetadataWrite 仅在源写入成功后调用,文档行、摘要和恢复标记在同一事务提交。+func CommitDocumentMetadataWrite(tree *parse.Tree) error {+ indexBlockTreeLock.Lock()+ defer indexBlockTreeLock.Unlock()+ tx, err := beginTxForBox(tree.Box)+ if err != nil {+ return err+ }+ defer tx.Rollback()+ execInsertBlocktrees(tx, tree, []*ast.Node{tree.Root})+ if _, err = tx.Exec("DELETE FROM document_metadata_pending WHERE box_id=? AND id=? AND revision=?",+ tree.Box, tree.ID, documentMetadataFromTree(tree).Revision); err != nil {+ return err+ }+ return tx.Commit()+}++func PendingDocumentMetadata(boxID string) ([]*BlockTree, error) {+ rows, err := queryForBox(boxID, "SELECT id, path FROM document_metadata_pending WHERE box_id=? ORDER BY path", boxID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ ret := []*BlockTree{}+ for rows.Next() {+ doc := &BlockTree{BoxID: boxID, Type: "d"}+ if err = rows.Scan(&doc.ID, &doc.Path); err != nil {+ return nil, err+ }+ doc.RootID = doc.ID+ ret = append(ret, doc)+ }+ return ret, rows.Err()+}++// FinishDocumentMetadataRecovery 由源恢复后清除旧的意图版本,或移除从未落盘的新建索引。+func FinishDocumentMetadataRecovery(boxID, id string, missing bool) error {+ indexBlockTreeLock.Lock()+ defer indexBlockTreeLock.Unlock()+ tx, err := beginTxForBox(boxID)+ if err != nil {+ return err+ }+ defer tx.Rollback()+ if missing {+ if _, err = tx.Exec("DELETE FROM blocktrees WHERE box_id=? AND root_id=?", boxID, id); err != nil {+ return err+ }+ }+ if _, err = tx.Exec("DELETE FROM document_metadata_pending WHERE box_id=? AND id=?", boxID, id); err != nil {+ return err+ }+ return tx.Commit()+}++func GetDocumentMetadata(boxID, id string) (*DocumentMetadata, error) {+ row := queryRowForBox(boxID, "SELECT "+documentMetadataColumns+" FROM "+documentMetadataJoin+" WHERE m.box_id=? AND m.id=?", boxID, id)+ if row == nil {+ return nil, ErrDocumentMetadataUnavailable+ }+ return scanDocumentMetadata(row)+}++// GetDocumentPath 按 ID 祖先关系组装路径,不跨笔记本回退,也不拆分可读路径。+// notebookDocumentID 由业务层确认,笔记本文档自身表示逻辑根,不能算作普通文档的祖先。+func GetDocumentPath(boxID, id, notebookDocumentID string, mode int) (*DocumentPath, error) {+ tx, err := beginTxForBox(boxID)+ if err != nil {+ return nil, err+ }+ defer tx.Rollback()+ return documentPathInTx(tx, boxID, id, notebookDocumentID, mode)+}++func documentPathInTx(tx *sql.Tx, boxID, id, notebookDocumentID string, mode int) (*DocumentPath, error) {+ var chain []*DocumentMetadata+ seen := map[string]bool{}+ currentID := id+ for {+ if seen[currentID] {+ return nil, ErrDocumentMetadataUnavailable+ }+ seen[currentID] = true+ meta, err := scanDocumentMetadata(tx.QueryRow("SELECT "+documentMetadataColumns+" FROM "+documentMetadataJoin+" WHERE m.box_id=? AND m.id=?", boxID, currentID))+ if err != nil {+ if errors.Is(err, sql.ErrNoRows) {+ var exists bool+ if queryErr := tx.QueryRow("SELECT EXISTS(SELECT 1 FROM blocktrees WHERE box_id=? AND id=? AND type='d')", boxID, currentID).Scan(&exists); queryErr != nil {+ return nil, queryErr+ }+ if exists || len(chain) > 0 {+ return nil, ErrDocumentMetadataUnavailable+ }+ }+ return nil, err+ }+ if len(chain) > 0 && (currentID == notebookDocumentID || strings.TrimSuffix(meta.Path, ".sy") != path.Dir(chain[len(chain)-1].Path)) {+ return nil, ErrDocumentMetadataUnavailable+ }+ chain = append(chain, meta)+ if meta.ParentID == nil {+ if path.Dir(meta.Path) != "/" {+ return nil, ErrDocumentMetadataUnavailable+ }+ break+ }+ currentID = *meta.ParentID+ }+ leaf := chain[0]+ ret := &DocumentPath{Notebook: boxID, ID: id, ParentID: leaf.ParentID, Path: leaf.Path, Title: leaf.Title,+ Segments: []DocumentPathSegment{}, AddressingVersion: mode}+ var texts, revisions []string+ for i := len(chain) - 1; i >= 0; i-- {+ meta := chain[i]+ revisions = append(revisions, meta.Revision)+ if meta.ID != notebookDocumentID {+ ret.Segments = append(ret.Segments, DocumentPathSegment{ID: meta.ID, Text: meta.Title.Text, Empty: meta.Title.Empty})+ texts = append(texts, meta.Title.Text)+ }+ }+ ret.Depth = len(ret.Segments)+ ret.DisplayPath = "/" + strings.Join(texts, "/")+ ret.Revision = DocumentRevision([]interface{}{1, boxID, id, leaf.Path, mode, revisions})+ return ret, nil+}++// MissingDocumentMetadata 返回需要从源重建的文档身份;不从展示字符串补齐标题。+func MissingDocumentMetadata(boxID string) ([]*BlockTree, error) {+ rows, err := queryForBox(boxID, `SELECT b.id, b.path FROM blocktrees b+ LEFT JOIN document_metadata m ON m.box_id=b.box_id AND m.id=b.id+ WHERE b.box_id=? AND b.type='d' AND m.id IS NULL ORDER BY b.path`, boxID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ ret := []*BlockTree{}+ for rows.Next() {+ bt := &BlockTree{BoxID: boxID, Type: "d"}+ if err = rows.Scan(&bt.ID, &bt.Path); err != nil {+ return nil, err+ }+ bt.RootID = bt.ID+ ret = append(ret, bt)+ }+ return ret, rows.Err()+}++// RecoverDocumentMetadata 只为仍在原位置且没有并发更新的文档补建摘要。+func RecoverDocumentMetadata(tree *parse.Tree) error {+ indexBlockTreeLock.Lock()+ defer indexBlockTreeLock.Unlock()+ tx, err := beginTxForBox(tree.Box)+ if err != nil {+ return err+ }+ defer tx.Rollback()+ var currentPath string+ if err = tx.QueryRow("SELECT path FROM blocktrees WHERE box_id=? AND id=? AND type='d'", tree.Box, tree.ID).Scan(¤tPath); err != nil {+ return err+ }+ if currentPath != tree.Path {+ return ErrDocumentMetadataUnavailable+ }+ var exists int+ if err = tx.QueryRow("SELECT COUNT(*) FROM document_metadata WHERE box_id=? AND id=?", tree.Box, tree.ID).Scan(&exists); err != nil {+ return err+ }+ if exists == 0 {+ if err = upsertDocumentMetadata(tx, tree); err != nil {+ return err+ }+ }+ return tx.Commit()+}diff --git a/kernel/treenode/document_metadata_test.go b/kernel/treenode/document_metadata_test.gonew file mode 100644index 0000000000..d01ceeeb03--- /dev/null+++ b/kernel/treenode/document_metadata_test.go@@ -0,0 +1,178 @@+package treenode++import (+ "database/sql"+ "errors"+ "path/filepath"+ "reflect"+ "testing"++ "github.com/88250/lute/parse"+)++func withDocumentMetadataDB(t *testing.T, encrypted bool) string {+ t.Helper()+ const boxID = "20261023000000-metabox"+ dsn := filepath.Join(t.TempDir(), "blocktree.db")+ if encrypted {+ dsn += "?_key=x'000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f'"+ }+ database, err := sql.Open("sqlite3_extended", dsn)+ if err != nil {+ t.Fatal(err)+ }+ previousDB := db+ if encrypted {+ if err = initEncryptedBlockTreeTables(database); err != nil {+ t.Fatal(err)+ }+ encryptedBlockTreeDBs.Store(boxID, database)+ } else {+ db = database+ initDBTables()+ }+ t.Cleanup(func() {+ if encrypted {+ CloseEncryptedBlockTreeDB(boxID)+ } else {+ db = previousDB+ database.Close()+ }+ })+ return boxID+}++func TestDocumentMetadataIdentityAndTitle(t *testing.T) {+ for _, encrypted := range []bool{false, true} {+ t.Run(map[bool]string{false: "plain", true: "encrypted"}[encrypted], func(t *testing.T) {+ box := withDocumentMetadataDB(t, encrypted)+ root := NewTree(box, "/20261023000001-root001.sy", "/A", "A")+ child := NewTree(box, "/20261023000001-root001/20261023000002-child01.sy", "/A/B", "B")+ slash := NewTree(box, "/20261023000003-slash01.sy", "/A/B", "A/B")+ for _, tree := range []*parse.Tree{root, child, slash} {+ UpsertBlockTree(tree)+ }+ get := func(tree *parse.Tree) *DocumentPath {+ t.Helper()+ ret, err := GetDocumentPath(box, tree.ID, "", 1)+ if err != nil {+ t.Fatal(err)+ }+ return ret+ }+ childPath, slashPath := get(child), get(slash)+ if childPath.DisplayPath != slashPath.DisplayPath || childPath.Depth != 2 || slashPath.Depth != 1 ||+ childPath.ParentID == nil || *childPath.ParentID != root.ID || slashPath.ParentID != nil {+ t.Fatalf("display path changed identity: %+v, %+v", childPath, slashPath)+ }+ previousRevision := childPath.Revision+ root.Root.SetIALAttr("title", "**A/%2F&**")+ root.HPath = "/**A/%2F&**"+ if err := RefreshDocHPaths(root); err != nil {+ t.Fatal(err)+ }+ childPath = get(child)+ if childPath.Revision == previousRevision || childPath.Segments[0].Text != "**A/%2F&**" ||+ GetBlockTreeInExactBox(child.ID, box).HPath != "/**A/%2F&**/B" {+ t.Fatalf("rename did not retain literal title or revision: %+v", childPath)+ }+ // 空标题标志在秒级更新时间未变时也更新,实际占位文字不被抹掉。+ child.Root.SetIALAttr(DocumentTitleEmptyAttr, "true")+ UpsertBlockTree(child)+ childPath = get(child)+ if !childPath.Title.Empty || childPath.Title.Text != "B" || !childPath.Segments[1].Empty {+ t.Fatalf("lost empty title flag: %+v", childPath)+ }+ // 移动与删除都同步清理父身份,不留下可再次匹配的旧行。+ RemoveBlockTreesByRootID(box, child.ID)+ child.Path = "/" + child.ID + ".sy"+ child.HPath = "/B"+ UpsertBlockTree(child)+ if moved := get(child); moved.Depth != 1 || moved.ParentID != nil {+ t.Fatalf("move retained old parent: %+v", moved)+ }+ RemoveBlockTree(box, child.ID)+ if _, err := GetDocumentMetadata(box, child.ID); !errors.Is(err, sql.ErrNoRows) {+ t.Fatalf("delete retained metadata: %v", err)+ }+ if _, err := GetDocumentPath("20261023000009-other01", root.ID, "", 1); err == nil {+ t.Fatal("read crossed notebook ownership")+ }+ })+ }+}++func TestDocumentMetadataMissingAndNotebookRoot(t *testing.T) {+ box := withDocumentMetadataDB(t, false)+ tree := NewTree(box, "/"+box+".sy", "/Notebook", "Notebook")+ UpsertBlockTree(tree)+ root, err := GetDocumentPath(box, tree.ID, box, 1)+ if err != nil || root.Depth != 0 || len(root.Segments) != 0 || root.DisplayPath != "/" {+ t.Fatalf("notebook document is not logical root: %+v, %v", root, err)+ }+ if _, err = db.Exec("DELETE FROM document_metadata"); err != nil {+ t.Fatal(err)+ }+ missing, err := MissingDocumentMetadata(box)+ if err != nil || len(missing) != 1 || missing[0].ID != box {+ t.Fatalf("missing metadata not discoverable: %+v, %v", missing, err)+ }+ if err = RecoverDocumentMetadata(tree); err != nil {+ t.Fatal(err)+ }+ meta, err := GetDocumentMetadata(box, tree.ID)+ if err != nil || !reflect.DeepEqual(meta.Title, ReadDocumentTitle(tree.Root)) || meta.SourceSpec != tree.Root.Spec {+ t.Fatalf("recovery lost source fields: %+v, %v", meta, err)+ }+ // 恢复任务读取后发生的新编辑优先,不能用旧源摘要覆盖。+ tree.Root.SetIALAttr("title", "Edited")+ UpsertBlockTree(tree)+ tree.Root.SetIALAttr("title", "Old snapshot")+ if err = RecoverDocumentMetadata(tree); err != nil {+ t.Fatal(err)+ }+ meta, _ = GetDocumentMetadata(box, tree.ID)+ if meta.Title.Text != "Edited" {+ t.Fatalf("recovery overwrote concurrent edit: %+v", meta)+ }+}++func TestDocumentMetadataPendingWrite(t *testing.T) {+ for _, encrypted := range []bool{false, true} {+ t.Run(map[bool]string{false: "plain", true: "encrypted"}[encrypted], func(t *testing.T) {+ box := withDocumentMetadataDB(t, encrypted)+ tree := NewTree(box, "/20261023000001-root001.sy", "/Saved", "Saved")+ UpsertBlockTree(tree)+ if err := SetDocumentMetadataState(box, "ready"); err != nil {+ t.Fatal(err)+ }+ tree.Root.SetIALAttr("title", "Not yet saved")+ UpsertBlockTreePending(tree)+ meta, err := GetDocumentMetadata(box, tree.ID)+ if err != nil || meta.Title.Text != "Saved" {+ t.Fatalf("editing transaction published an uncommitted title: %+v, %v", meta, err)+ }+ pending, err := BeginDocumentMetadataWrite(tree)+ if err != nil || !pending || DocumentMetadataState(box) != "building" {+ t.Fatalf("missing durable write intent: pending=%v err=%v", pending, err)+ }+ if err = SetDocumentMetadataState(box, "ready"); !errors.Is(err, ErrDocumentMetadataUnavailable) {+ t.Fatal("pending source write was advertised as ready", err)+ }+ intents, err := PendingDocumentMetadata(box)+ if err != nil || len(intents) != 1 || intents[0].Path != tree.Path {+ t.Fatalf("write cannot be recovered: %+v, %v", intents, err)+ }+ if err = CommitDocumentMetadataWrite(tree); err != nil {+ t.Fatal(err)+ }+ meta, err = GetDocumentMetadata(box, tree.ID)+ if err != nil || meta.Title.Text != "Not yet saved" || DocumentMetadataState(box) != "ready" {+ t.Fatalf("successful save did not publish its source: %+v, %v", meta, err)+ }+ if pending, err = BeginDocumentMetadataWrite(tree); err != nil || pending {+ t.Fatal("unchanged title writes an unnecessary intent", pending, err)+ }+ })+ }+}diff --git a/kernel/treenode/document_path.go b/kernel/treenode/document_path.gonew file mode 100644index 0000000000..92bded9b54--- /dev/null+++ b/kernel/treenode/document_path.go@@ -0,0 +1,120 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package treenode++import "database/sql"++type DocumentLocation struct {+ Notebook string `json:"notebook"`+ ID *string `json:"id"`+ Revision string `json:"revision"`+}++type DocumentNameCondition struct {+ ParentID *string `json:"parentID"`+ Title string `json:"title"`+ ExpectedID *string `json:"expectedID"`+}++type ResolvedDocumentPath struct {+ Status string `json:"status"`+ Start DocumentLocation `json:"start"`+ Resolved *DocumentPath `json:"resolved"`+ NextIndex int `json:"nextIndex"`+ Candidates []*DocumentPath `json:"candidates"`+ CandidatesTruncated bool `json:"candidatesTruncated"`+ NameConditions []DocumentNameCondition `json:"nameConditions"`+}++func ResolveDocumentPath(boxID string, parentID *string, segments []string, notebookDocumentID, rootRevision string, mode int) (*ResolvedDocumentPath, error) {+ tx, err := beginTxForBox(boxID)+ if err != nil {+ return nil, err+ }+ defer tx.Rollback()+ ret := &ResolvedDocumentPath{Status: "resolved", Start: DocumentLocation{Notebook: boxID, ID: parentID, Revision: rootRevision},+ Candidates: []*DocumentPath{}, NameConditions: []DocumentNameCondition{}}+ if parentID != nil {+ if ret.Resolved, err = documentPathInTx(tx, boxID, *parentID, notebookDocumentID, mode); err != nil {+ return nil, err+ }+ ret.Start.Revision = ret.Resolved.Revision+ }+ for i, title := range segments {+ ret.NextIndex = i+ ids, queryErr := documentChildrenByTitle(tx, boxID, parentID, title, notebookDocumentID, 129)+ if queryErr != nil {+ return nil, queryErr+ }+ switch len(ids) {+ case 0:+ ret.Status = "missing"+ ret.NameConditions = append(ret.NameConditions, DocumentNameCondition{ParentID: parentID, Title: title})+ return ret, nil+ case 1:+ childID := ids[0]+ ret.NameConditions = append(ret.NameConditions, DocumentNameCondition{ParentID: parentID, Title: title, ExpectedID: &childID})+ parentID = &childID+ if ret.Resolved, err = documentPathInTx(tx, boxID, childID, notebookDocumentID, mode); err != nil {+ return nil, err+ }+ default:+ ret.Status = "ambiguous"+ ret.CandidatesTruncated = len(ids) > 128+ for _, id := range ids[:min(len(ids), 128)] {+ candidate, readErr := documentPathInTx(tx, boxID, id, notebookDocumentID, mode)+ if readErr != nil {+ return nil, readErr+ }+ ret.Candidates = append(ret.Candidates, candidate)+ }+ return ret, nil+ }+ }+ ret.NextIndex = len(segments)+ return ret, nil+}++func documentChildrenByTitle(tx *sql.Tx, boxID string, parentID *string, title, notebookDocumentID string, limit int) ([]string, error) {+ rows, err := tx.Query(`SELECT id FROM document_metadata+ WHERE box_id=? AND parent_id IS ? AND title_text=? COLLATE BINARY AND title_empty=0 AND id<>?+ ORDER BY id LIMIT ?`, boxID, parentID, title, notebookDocumentID, limit)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ ret := []string{}+ for rows.Next() {+ var id string+ if err = rows.Scan(&id); err != nil {+ return nil, err+ }+ ret = append(ret, id)+ }+ return ret, rows.Err()+}++// CheckDocumentNameConditions 在调用方持有文档变更协调范围时复核精确匹配集合。+func CheckDocumentNameConditions(boxID, notebookDocumentID string, conditions []DocumentNameCondition) (bool, error) {+ tx, err := beginTxForBox(boxID)+ if err != nil {+ return false, err+ }+ defer tx.Rollback()+ for _, condition := range conditions {+ ids, queryErr := documentChildrenByTitle(tx, boxID, condition.ParentID, condition.Title, notebookDocumentID, 2)+ if queryErr != nil {+ return false, queryErr+ }+ if condition.ExpectedID == nil {+ if len(ids) != 0 {+ return false, nil+ }+ } else if len(ids) != 1 || ids[0] != *condition.ExpectedID {+ return false, nil+ }+ }+ return true, nil+}diff --git a/kernel/treenode/document_title.go b/kernel/treenode/document_title.gonew file mode 100644index 0000000000..b68dcc6ca2--- /dev/null+++ b/kernel/treenode/document_title.go@@ -0,0 +1,31 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+// SPDX-License-Identifier: AGPL-3.0-or-later++package treenode++import "github.com/88250/lute/ast"++const DocumentTitleEmptyAttr = "custom-sy-title-empty"++// DocumentTitle 是标题源的只读摘要,不能用它覆盖未来格式的完整源内容。+type DocumentTitle struct {+ Format string `json:"format"`+ Text string `json:"text"`+ Empty bool `json:"empty"`+}++// ReadDocumentTitle 只提取已经通过源格式检查的文档标题,不解释 Markdown 或重复解码属性。+// 空标题标志与实际保存的占位文字分别保留,源文档版本由调用方从根节点读取。+func ReadDocumentTitle(root *ast.Node) DocumentTitle {+ return DocumentTitle{+ Format: "plain",+ Text: root.IALAttr("title"),+ Empty: root.IALAttr(DocumentTitleEmptyAttr) == "true",+ }+}++// DocumentTitleFromProperties 接受已经解码的根属性,与节点读取使用相同的摘要语义。+func DocumentTitleFromProperties(properties map[string]string) DocumentTitle {+ return DocumentTitle{Format: "plain", Text: properties["title"], Empty: properties[DocumentTitleEmptyAttr] == "true"}+}diff --git a/kernel/treenode/hpath.go b/kernel/treenode/hpath.goindex 2deeefb2f4..4d44639318 100644--- a/kernel/treenode/hpath.go+++ b/kernel/treenode/hpath.go@@ -62,16 +62,45 @@ func RefreshDocHPaths(tree *parse.Tree) (err error) {return err}defer tx.Rollback()- depth := strings.Count(tree.Path, "/")+ if err = upsertDocumentMetadata(tx, tree); err != nil {+ return err+ }+ prefix := strings.TrimSuffix(tree.Path, ".sy") + "/"+ rows, err := tx.Query(`SELECT m.id, m.title_text FROM document_metadata m JOIN blocktrees b+ ON b.box_id=m.box_id AND b.id=m.id AND b.type='d'+ WHERE b.box_id=? AND (b.path=? OR (b.path>=? AND b.path<?))`, tree.Box, tree.Path, prefix, prefix+"\uffff")+ if err != nil {+ return err+ }+ titles := map[string]string{}+ for rows.Next() {+ var id, title string+ if err = rows.Scan(&id, &title); err != nil {+ rows.Close()+ return err+ }+ titles[id] = title+ }+ err = rows.Err()+ rows.Close()+ if err != nil {+ return err+ }+ paths := map[string]string{tree.Path: tree.HPath}for _, doc := range docs {hpath := tree.HPathif doc.Path != tree.Path {- parts := strings.Split(doc.HPath, "/")- if len(parts) <= depth+1 {- return errors.New("invalid descendant document hpath")+ parentHPath, found := paths[path.Dir(doc.Path)+".sy"]+ if !found {+ return ErrDocumentMetadataUnavailable+ }+ title, found := titles[doc.ID]+ if !found {+ return ErrDocumentMetadataUnavailable}- hpath += "/" + strings.Join(parts[depth+1:], "/")+ hpath = parentHPath + "/" + title}+ paths[doc.Path] = hpathif _, err = tx.Exec("UPDATE blocktrees SET hpath = ? WHERE id = ? AND box_id = ? AND path = ? AND type = 'd' AND hpath != ?", hpath, doc.ID, tree.Box, doc.Path, hpath); err != nil {return err}@@ -97,7 +126,7 @@ func CurrentParentHPath(tree *parse.Tree) string {return tree.HPath}if doc := GetBlockTreeInBox(path.Base(parent), tree.Box); doc != nil && doc.BoxID == tree.Box && doc.Path == parent+".sy" {- return doc.HPath + "/" + tree.Root.IALAttr("title")+ return doc.HPath + "/" + ReadDocumentTitle(tree.Root).Text}return tree.HPath}