Skip to content

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

:bug: Prevent flash shorthands from targeting unavailable notebooks https://github.com/siyuan-note/siyuan/issues/19040

Daniel418272883fa9
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 5584335eeb..952c0268bd 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -2648,6 +2648,7 @@
"371": "المفكرة موجودة بالفعل",
"372": "تمت استعادة المفكرة وستظل مغلقة",
"373": "تحتوي هذه الحزمة المضغوطة على بيانات دفتر ملاحظات. يرجى استيرادها من [شجرة المستندات - المزيد - استيراد دفتر ملاحظات]",
- "374": "قاعدة البيانات [%s]، حقل القالب [%s]، أول عنصر متأثر [%s] (معرّف العنصر: %s)، عدد العناصر المتأثرة: %d، الخطأ: %s"
+ "374": "قاعدة البيانات [%s]، حقل القالب [%s]، أول عنصر متأثر [%s] (معرّف العنصر: %s)، عدد العناصر المتأثرة: %d، الخطأ: %s",
+ "375": "دفتر حفظ الملاحظات السريعة غير متاح. اختر دفتر ملاحظات مفتوحًا وغير مشفر في الإعدادات - المستند"
}
}
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 3712938125..118d565d0a 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -2648,6 +2648,7 @@
"371": "Das Notizbuch ist bereits vorhanden",
"372": "Das Notizbuch wurde wiederhergestellt und bleibt geschlossen",
"373": "Dieses Archiv enthält Notizbuchdaten. Bitte importieren Sie es über [Dokumentenbaum - Mehr - Notizbuch importieren]",
- "374": "Datenbank [%s], Vorlagenfeld [%s], erster betroffener Eintrag [%s] (Element-ID: %s), Anzahl betroffener Einträge: %d, Fehler: %s"
+ "374": "Datenbank [%s], Vorlagenfeld [%s], erster betroffener Eintrag [%s] (Element-ID: %s), Anzahl betroffener Einträge: %d, Fehler: %s",
+ "375": "Das Notizbuch zum Speichern von Kurznotizen ist nicht verfügbar. Wählen Sie unter Einstellungen - Dokument ein geöffnetes, unverschlüsseltes Notizbuch"
}
}
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 82186d797e..3d46f06660 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -2648,6 +2648,7 @@
"371": "The notebook already exists",
"372": "The notebook has been restored and remains closed",
"373": "This archive contains notebook data. Please import it from [Document Tree - More - Import Notebook]",
- "374": "Database [%s], template field [%s], first affected item [%s] (item ID: %s), affected item count: %d, error: %s"
+ "374": "Database [%s], template field [%s], first affected item [%s] (item ID: %s), affected item count: %d, error: %s",
+ "375": "The shorthand save notebook is unavailable. Select an opened non-encrypted notebook in Settings - Document"
}
}
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index 469a364c2c..abbe5148a8 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -2648,6 +2648,7 @@
"371": "El cuaderno ya existe",
"372": "El cuaderno se ha restaurado y permanece cerrado",
"373": "Este archivo contiene datos de cuadernos. Impórtelo desde [Árbol de documentos - Más - Importar cuaderno]",
- "374": "Base de datos [%s], campo de plantilla [%s], primer elemento afectado [%s] (ID del elemento: %s), cantidad de elementos afectados: %d, error: %s"
+ "374": "Base de datos [%s], campo de plantilla [%s], primer elemento afectado [%s] (ID del elemento: %s), cantidad de elementos afectados: %d, error: %s",
+ "375": "El cuaderno para guardar notas rápidas no está disponible. Seleccione un cuaderno abierto y sin cifrar en Configuración - Documento"
}
}
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 3cb2d333c7..7974710ab8 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -2648,6 +2648,7 @@
"371": "Le carnet existe déjà",
"372": "Le carnet a été restauré et reste fermé",
"373": "Cette archive contient des données de carnet. Veuillez l’importer depuis [Arborescence des documents - Plus - Importer un carnet]",
- "374": "Base de données [%s], champ de modèle [%s], premier élément affecté [%s] (ID de l’élément : %s), nombre d’éléments affectés : %d, erreur : %s"
+ "374": "Base de données [%s], champ de modèle [%s], premier élément affecté [%s] (ID de l’élément : %s), nombre d’éléments affectés : %d, erreur : %s",
+ "375": "Le carnet d’enregistrement des notes rapides n’est pas disponible. Sélectionnez un carnet ouvert et non chiffré dans Paramètres - Document"
}
}
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 871b51edcd..ad2d75c3d1 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -2648,6 +2648,7 @@
"371": "המחברת כבר קיימת",
"372": "המחברת שוחזרה ונשארה סגורה",
"373": "ארכיון זה מכיל נתוני מחברת. יש לייבא אותו מתוך [עץ המסמכים - עוד - ייבוא מחברת]",
- "374": "מסד הנתונים [%s], שדה התבנית [%s], הפריט המושפע הראשון [%s] (מזהה פריט: %s), מספר הפריטים המושפעים: %d, שגיאה: %s"
+ "374": "מסד הנתונים [%s], שדה התבנית [%s], הפריט המושפע הראשון [%s] (מזהה פריט: %s), מספר הפריטים המושפעים: %d, שגיאה: %s",
+ "375": "מחברת השמירה של הרשומות המהירות אינה זמינה. יש לבחור מחברת פתוחה ולא מוצפנת בהגדרות - מסמך"
}
}
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index df47062673..b2aa6af526 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -2648,6 +2648,7 @@
"371": "नोटबुक पहले से मौजूद है",
"372": "नोटबुक पुनर्स्थापित हो गई है और बंद रहेगी",
"373": "इस संग्रह में नोटबुक डेटा है। कृपया इसे [दस्तावेज़ ट्री - अधिक - नोटबुक आयात करें] से आयात करें",
- "374": "डेटाबेस [%s], टेम्पलेट फ़ील्ड [%s], पहला प्रभावित आइटम [%s] (आइटम ID: %s), प्रभावित आइटम की संख्या: %d, त्रुटि: %s"
+ "374": "डेटाबेस [%s], टेम्पलेट फ़ील्ड [%s], पहला प्रभावित आइटम [%s] (आइटम ID: %s), प्रभावित आइटम की संख्या: %d, त्रुटि: %s",
+ "375": "त्वरित नोट सहेजने वाली नोटबुक उपलब्ध नहीं है। सेटिंग्स - दस्तावेज़ में कोई खुली और गैर-एन्क्रिप्टेड नोटबुक चुनें"
}
}
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index 7a8e18fa1e..0b00f7a525 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -2648,6 +2648,7 @@
"371": "Buku catatan sudah ada",
"372": "Buku catatan telah dipulihkan dan tetap ditutup",
"373": "Arsip ini berisi data buku catatan. Impor dari [Pohon dokumen - Lainnya - Impor buku catatan]",
- "374": "Basis data [%s], bidang templat [%s], item pertama yang terdampak [%s] (ID item: %s), jumlah item terdampak: %d, kesalahan: %s"
+ "374": "Basis data [%s], bidang templat [%s], item pertama yang terdampak [%s] (ID item: %s), jumlah item terdampak: %d, kesalahan: %s",
+ "375": "Buku catatan penyimpanan catatan cepat tidak tersedia. Pilih buku catatan terbuka dan tidak terenkripsi di Pengaturan - Dokumen"
}
}
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 120aa52506..fd01eef1ab 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -2648,6 +2648,7 @@
"371": "Il taccuino esiste già",
"372": "Il taccuino è stato ripristinato e rimane chiuso",
"373": "Questo archivio contiene dati di un taccuino. Importalo da [Albero dei documenti - Altro - Importa taccuino]",
- "374": "Database [%s], campo modello [%s], primo elemento interessato [%s] (ID elemento: %s), numero di elementi interessati: %d, errore: %s"
+ "374": "Database [%s], campo modello [%s], primo elemento interessato [%s] (ID elemento: %s), numero di elementi interessati: %d, errore: %s",
+ "375": "Il taccuino per il salvataggio delle note rapide non è disponibile. Seleziona un taccuino aperto e non crittografato in Impostazioni - Documento"
}
}
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 216f69b3c6..38b45679cd 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -2648,6 +2648,7 @@
"371": "ノートブックはすでに存在します",
"372": "ノートブックを復元し、閉じた状態を維持しました",
"373": "このアーカイブにはノートブックデータが含まれています。[ドキュメントツリー - その他 - ノートブックをインポート] からインポートしてください",
- "374": "データベース [%s]、テンプレートフィールド [%s]、最初のエラー項目 [%s](項目 ID: %s)、エラー項目数: %d、エラー: %s"
+ "374": "データベース [%s]、テンプレートフィールド [%s]、最初のエラー項目 [%s](項目 ID: %s)、エラー項目数: %d、エラー: %s",
+ "375": "フラッシュメモの保存先ノートブックを使用できません。設定 - ドキュメントで、開いている暗号化されていないノートブックを選択してください"
}
}
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index a28c5b08fe..5c4cfabfc4 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -2648,6 +2648,7 @@
"371": "노트북이 이미 존재합니다",
"372": "노트북이 복원되었으며 닫힌 상태로 유지됩니다",
"373": "이 압축 파일에는 노트북 데이터가 포함되어 있습니다. [문서 트리 - 더보기 - 노트북 가져오기]에서 가져오세요",
- "374": "데이터베이스 [%s], 템플릿 필드 [%s], 첫 번째 오류 항목 [%s](항목 ID: %s), 오류 항목 수: %d, 오류: %s"
+ "374": "데이터베이스 [%s], 템플릿 필드 [%s], 첫 번째 오류 항목 [%s](항목 ID: %s), 오류 항목 수: %d, 오류: %s",
+ "375": "플래시 메모 저장 노트북을 사용할 수 없습니다. 설정 - 문서에서 열려 있는 암호화되지 않은 노트북을 선택하세요"
}
}
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index a87aed1712..07902840cf 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -2648,6 +2648,7 @@
"371": "Het notitieboek bestaat al",
"372": "Het notitieboek is hersteld en blijft gesloten",
"373": "Dit archief bevat notitieboekgegevens. Importeer het via [Documentboom - Meer - Notitieboek importeren]",
- "374": "Database [%s], sjabloonveld [%s], eerste betrokken item [%s] (item-ID: %s), aantal betrokken items: %d, fout: %s"
+ "374": "Database [%s], sjabloonveld [%s], eerste betrokken item [%s] (item-ID: %s), aantal betrokken items: %d, fout: %s",
+ "375": "Het notitieboek voor snelle notities is niet beschikbaar. Selecteer een geopend, niet-versleuteld notitieboek in Instellingen - Document"
}
}
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index aa69914c30..5ed2c83476 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -2648,6 +2648,7 @@
"371": "Notatnik już istnieje",
"372": "Notatnik został przywrócony i pozostaje zamknięty",
"373": "To archiwum zawiera dane notatnika. Zaimportuj je z [Drzewo dokumentów - Więcej - Importuj notatnik]",
- "374": "Baza danych [%s], pole szablonu [%s], pierwszy element z błędem [%s] (ID elementu: %s), liczba elementów z błędem: %d, błąd: %s"
+ "374": "Baza danych [%s], pole szablonu [%s], pierwszy element z błędem [%s] (ID elementu: %s), liczba elementów z błędem: %d, błąd: %s",
+ "375": "Notatnik zapisu szybkich notatek jest niedostępny. Wybierz otwarty, niezaszyfrowany notatnik w Ustawienia - Dokument"
}
}
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index 6cbef9a31e..fdd03bdf8c 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -2648,6 +2648,7 @@
"371": "O caderno já existe",
"372": "O caderno foi restaurado e permanece fechado",
"373": "Este arquivo contém dados de caderno. Importe-o em [Árvore de documentos - Mais - Importar caderno]",
- "374": "Banco de dados [%s], campo de modelo [%s], primeiro item afetado [%s] (ID do item: %s), quantidade de itens afetados: %d, erro: %s"
+ "374": "Banco de dados [%s], campo de modelo [%s], primeiro item afetado [%s] (ID do item: %s), quantidade de itens afetados: %d, erro: %s",
+ "375": "O caderno para salvar notas rápidas não está disponível. Selecione um caderno aberto e não criptografado em Configurações - Documento"
}
}
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index aa28501b94..fa75e522d0 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -2648,6 +2648,7 @@
"371": "Блокнот уже существует",
"372": "Блокнот восстановлен и остаётся закрытым",
"373": "Этот архив содержит данные блокнота. Импортируйте его через [Дерево документов - Ещё - Импортировать блокнот]",
- "374": "База данных [%s], поле шаблона [%s], первый затронутый элемент [%s] (ID элемента: %s), количество затронутых элементов: %d, ошибка: %s"
+ "374": "База данных [%s], поле шаблона [%s], первый затронутый элемент [%s] (ID элемента: %s), количество затронутых элементов: %d, ошибка: %s",
+ "375": "Блокнот для сохранения быстрых заметок недоступен. Выберите открытый незашифрованный блокнот в Настройки - Документ"
}
}
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index 6b82ac708e..cd8a78e02c 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -2648,6 +2648,7 @@
"371": "Zápisník už existuje",
"372": "Zápisník bol obnovený a zostáva zatvorený",
"373": "Tento archív obsahuje údaje zápisníka. Importujte ho cez [Strom dokumentov - Viac - Importovať zápisník]",
- "374": "Databáza [%s], pole šablóny [%s], prvá ovplyvnená položka [%s] (ID položky: %s), počet ovplyvnených položiek: %d, chyba: %s"
+ "374": "Databáza [%s], pole šablóny [%s], prvá ovplyvnená položka [%s] (ID položky: %s), počet ovplyvnených položiek: %d, chyba: %s",
+ "375": "Zápisník na ukladanie rýchlych poznámok nie je k dispozícii. Vyberte otvorený nezašifrovaný zápisník v Nastavenia - Dokument"
}
}
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index 1851e3b5c7..2ad639eca5 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -2648,6 +2648,7 @@
"371": "มีสมุดนี้อยู่แล้ว",
"372": "กู้คืนสมุดแล้วและยังคงปิดอยู่",
"373": "ไฟล์บีบอัดนี้มีข้อมูลสมุดบันทึก โปรดนำเข้าจาก [แผนผังเอกสาร - เพิ่มเติม - นำเข้าสมุดบันทึก]",
- "374": "ฐานข้อมูล [%s] ฟิลด์เทมเพลต [%s] รายการแรกที่ได้รับผลกระทบ [%s] (ID รายการ: %s) จำนวนรายการที่ได้รับผลกระทบ: %d ข้อผิดพลาด: %s"
+ "374": "ฐานข้อมูล [%s] ฟิลด์เทมเพลต [%s] รายการแรกที่ได้รับผลกระทบ [%s] (ID รายการ: %s) จำนวนรายการที่ได้รับผลกระทบ: %d ข้อผิดพลาด: %s",
+ "375": "สมุดบันทึกสำหรับบันทึกโน้ตด่วนไม่พร้อมใช้งาน โปรดเลือกสมุดบันทึกที่เปิดอยู่และไม่ได้เข้ารหัสใน การตั้งค่า - เอกสาร"
}
}
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index 4c96032805..edf6a78eb2 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -2648,6 +2648,7 @@
"371": "Defter zaten mevcut",
"372": "Defter geri yüklendi ve kapalı kalacak",
"373": "Bu arşiv not defteri verileri içeriyor. [Belge ağacı - Diğer - Not defteri içe aktar] menüsünden içe aktarın",
- "374": "Veritabanı [%s], şablon alanı [%s], etkilenen ilk öğe [%s] (öğe kimliği: %s), etkilenen öğe sayısı: %d, hata: %s"
+ "374": "Veritabanı [%s], şablon alanı [%s], etkilenen ilk öğe [%s] (öğe kimliği: %s), etkilenen öğe sayısı: %d, hata: %s",
+ "375": "Hızlı notların kaydedileceği not defteri kullanılamıyor. Ayarlar - Belge bölümünde açık ve şifrelenmemiş bir not defteri seçin"
}
}
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index 28105a88f4..61410916ad 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -2648,6 +2648,7 @@
"371": "Блокнот уже існує",
"372": "Блокнот відновлено й залишено закритим",
"373": "Цей архів містить дані блокнота. Імпортуйте його через [Дерево документів - Більше - Імпортувати блокнот]",
- "374": "База даних [%s], поле шаблону [%s], перший уражений елемент [%s] (ID елемента: %s), кількість уражених елементів: %d, помилка: %s"
+ "374": "База даних [%s], поле шаблону [%s], перший уражений елемент [%s] (ID елемента: %s), кількість уражених елементів: %d, помилка: %s",
+ "375": "Блокнот для збереження швидких нотаток недоступний. Виберіть відкритий незашифрований блокнот у Налаштування - Документ"
}
}
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 7ba21849c5..db773b3db4 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -2648,6 +2648,7 @@
"371": "笔记本已存在",
"372": "笔记本已回滚并保持关闭状态",
"373": "该压缩包包含笔记本数据,请从 [文档树 - 更多 - 导入笔记本] 中导入",
- "374": "数据库 [%s],模板字段 [%s],首个出错条目 [%s](项目 ID:%s),出错条目数:%d,错误:%s"
+ "374": "数据库 [%s],模板字段 [%s],首个出错条目 [%s](项目 ID:%s),出错条目数:%d,错误:%s",
+ "375": "闪念速记存放笔记本不可用,请在设置 - 文档中选择一个已打开的非加密笔记本"
}
}
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 70dc1b8d50..e5e0ae9a11 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -2648,6 +2648,7 @@
"371": "筆記本已存在",
"372": "筆記本已回滾並保持關閉狀態",
"373": "該壓縮檔包含筆記本資料,請從 [文件樹 - 更多 - 導入筆記本] 中導入",
- "374": "資料庫 [%s],範本欄位 [%s],第一個出錯項目 [%s](項目 ID:%s),出錯項目數:%d,錯誤:%s"
+ "374": "資料庫 [%s],範本欄位 [%s],第一個出錯項目 [%s](項目 ID:%s),出錯項目數:%d,錯誤:%s",
+ "375": "閃念速記存放筆記本不可用,請在設定 - 文件中選擇一個已開啟的非加密筆記本"
}
}
diff --git a/app/src/config/tabs/fileTab.ts b/app/src/config/tabs/fileTab.ts
index 931624b5fa..a67136adc4 100644
--- a/app/src/config/tabs/fileTab.ts
+++ b/app/src/config/tabs/fileTab.ts
@@ -198,7 +198,8 @@ const registerFileNewDocumentGroup = (tab: SettingTabBuilder) => {
shorthandDesc,
"fileTree.shorthandSaveBox",
"fileTree.shorthandSavePath",
- genNotebookOption(window.siyuan.config.fileTree.shorthandSaveBox, undefined, true),
+ genNotebookOption(window.siyuan.config.fileTree.shorthandSaveBox, undefined, true,
+ (item) => !item.closed && !item.encrypted),
),
afterMount: (root) => {
const el = root.querySelector<HTMLInputElement>(`#${CSS.escape("fileTree.shorthandSavePath")}`);
diff --git a/app/src/menus/onGetnotebookconf.ts b/app/src/menus/onGetnotebookconf.ts
index f6db1ed04a..a1e4c6d8b2 100644
--- a/app/src/menus/onGetnotebookconf.ts
+++ b/app/src/menus/onGetnotebookconf.ts
@@ -21,7 +21,8 @@ declare interface INotebookConf {
}
}
-export const genNotebookOption = (id: string, notebookId?: string, noCurrent?: boolean) => {
+export const genNotebookOption = (id: string, notebookId?: string, noCurrent?: boolean,
+ filter?: (item: INotebook) => boolean) => {
let html = "";
if (!noCurrent) {
html = `<option value="">${window.siyuan.languages.currentNotebook}</option>`;
@@ -30,9 +31,14 @@ export const genNotebookOption = (id: string, notebookId?: string, noCurrent?: b
Object.keys(Constants.HELP_PATH).forEach((key: "zh-CN") => {
helpIds.push(Constants.HELP_PATH[key]);
});
+ const configuredNotebook = window.siyuan.notebooks.find((item) => item.id === id);
+ if (noCurrent && id && (!configuredNotebook || helpIds.includes(id) || (filter && !filter(configuredNotebook)))) {
+ const name = configuredNotebook?.name || id;
+ html += `<option value="${id}" selected disabled>${escapeHtml(name)} (${window.siyuan.languages.agentCapabilitiesUnavailable})</option>`;
+ }
let firstNotebookId = "";
window.siyuan.notebooks.forEach((item) => {
- if (helpIds.includes(item.id) || item.id === notebookId) {
+ if (helpIds.includes(item.id) || item.id === notebookId || (filter && !filter(item))) {
return;
}
if ("" === firstNotebookId) {
@@ -44,6 +50,9 @@ export const genNotebookOption = (id: string, notebookId?: string, noCurrent?: b
}
html += `<option value="${item.id}" ${selected ? "selected" : ""}>${escapeHtml(item.name)}</option>`;
});
+ if (noCurrent && !firstNotebookId && !id) {
+ html = `<option value="" selected disabled>${window.siyuan.languages.agentCapabilitiesUnavailable}</option>`;
+ }
return html;
};
diff --git a/kernel/api/filetree.go b/kernel/api/filetree.go
index 4c09dd6203..9ca03eaef9 100644
--- a/kernel/api/filetree.go
+++ b/kernel/api/filetree.go
@@ -1101,6 +1101,11 @@ func getShorthandSavePath(c *gin.Context) {
if "" == shorthandSaveBox {
shorthandSaveBox = notebook
}
+ if !model.IsShorthandSaveBoxAvailable(shorthandSaveBox) {
+ ret.Code = -1
+ ret.Msg = model.Conf.Language(375)
+ return
+ }
if shorthandSaveBox != notebook {
if "" != shorthandSavePathTpl && !strings.HasPrefix(shorthandSavePathTpl, "/") {
diff --git a/kernel/model/shortcuts.go b/kernel/model/shortcuts.go
index 996a394bd1..3dfef53dd5 100644
--- a/kernel/model/shortcuts.go
+++ b/kernel/model/shortcuts.go
@@ -47,6 +47,10 @@ func MoveLocalShorthands(boxID string) (retIDs []string, err error) {
logging.LogErrorf("read dir [%s] failed: %s", shorthandsDir, err)
return
}
+ if !IsShorthandSaveBoxAvailable(boxID) {
+ err = errors.New(Conf.Language(375))
+ return
+ }
assetsDir := filepath.Join(util.DataDir, "assets")
for _, entry := range entries {
@@ -304,6 +308,33 @@ func createShorthandDocByDOM(boxID, hPath, dom, docID string) (retID string, err
}
var consumeShorthandsLock = sync.Mutex{}
+var shorthandSaveBoxUnavailableNotified bool
+
+func isShorthandSaveBoxAvailable(box *Box) bool {
+ return nil != box && !box.Closed && !box.Encrypted && !IsUserGuide(box.ID)
+}
+
+func selectShorthandSaveBox(configuredID string, boxes []*Box) *Box {
+ if "" != configuredID {
+ for _, box := range boxes {
+ if nil != box && box.ID == configuredID && isShorthandSaveBoxAvailable(box) {
+ return box
+ }
+ }
+ return nil
+ }
+
+ for _, box := range boxes {
+ if isShorthandSaveBoxAvailable(box) {
+ return box
+ }
+ }
+ return nil
+}
+
+func IsShorthandSaveBoxAvailable(boxID string) bool {
+ return isShorthandSaveBoxAvailable(Conf.GetBox(boxID))
+}
func consumeShorthands() {
if !util.IsMobileContainer() {
@@ -336,33 +367,26 @@ func consumeShorthands() {
}
if !hasShorthand {
+ shorthandSaveBoxUnavailableNotified = false
return
}
- var notebookID string
- notebookID = Conf.FileTree.ShorthandSaveBox
- if "" != notebookID && nil == Conf.Box(notebookID) {
- notebookID = ""
- }
-
- if "" == notebookID {
- boxes := Conf.GetBoxes()
- for _, box := range boxes {
- if !IsUserGuide(box.ID) {
- notebookID = box.ID
- break
- }
- }
- }
-
- if "" == notebookID {
+ boxes := Conf.GetBoxes()
+ box := selectShorthandSaveBox(Conf.FileTree.ShorthandSaveBox, boxes)
+ if nil == box {
logging.LogWarnf("auto consume shorthands failed: no available notebook found")
+ if !shorthandSaveBoxUnavailableNotified {
+ util.PushErrMsg(Conf.Language(375), 7000)
+ shorthandSaveBoxUnavailableNotified = true
+ }
return
}
- if _, err = MoveLocalShorthands(notebookID); nil != err {
+ if _, err = MoveLocalShorthands(box.ID); nil != err {
logging.LogErrorf("auto consume shorthands failed: %s", err)
+ return
}
+ shorthandSaveBoxUnavailableNotified = false
}
func AutoConsumeShorthandsJob() {
diff --git a/kernel/model/shortcuts_test.go b/kernel/model/shortcuts_test.go
new file mode 100644
index 0000000000..c51569e044
--- /dev/null
+++ b/kernel/model/shortcuts_test.go
@@ -0,0 +1,59 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+package model
+
+import "testing"
+
+func TestSelectShorthandSaveBox(t *testing.T) {
+ boxes := []*Box{
+ {ID: "20260830000000-first", Closed: false},
+ {ID: "20260830000001-locked", Closed: true, Encrypted: true},
+ {ID: "20260830000002-encrypted", Closed: false, Encrypted: true},
+ {ID: "20260830000003-closed", Closed: true},
+ {ID: "20260830000004-open", Closed: false},
+ }
+
+ if got := selectShorthandSaveBox("", boxes); nil == got || "20260830000000-first" != got.ID {
+ t.Fatalf("select default shorthand box failed: %v", got)
+ }
+ if got := selectShorthandSaveBox("20260830000004-open", boxes); nil == got || "20260830000004-open" != got.ID {
+ t.Fatalf("select configured shorthand box failed: %v", got)
+ }
+ for _, id := range []string{"20260830000001-locked", "20260830000002-encrypted", "20260830000003-closed", "missing"} {
+ if got := selectShorthandSaveBox(id, boxes); nil != got {
+ t.Fatalf("unavailable shorthand box [%s] should not be selected: %v", id, got)
+ }
+ }
+}
+
+func TestSelectShorthandSaveBoxSkipsUserGuide(t *testing.T) {
+ boxes := []*Box{
+ nil,
+ {ID: "20210808180117-czj9bvb", Closed: false},
+ {ID: "20260830000004-open", Closed: false},
+ }
+ got := selectShorthandSaveBox("", boxes)
+ if nil == got || "20260830000004-open" != got.ID {
+ t.Fatalf("user guide should not be selected: %v", got)
+ }
+ if got = selectShorthandSaveBox("20210808180117-czj9bvb", boxes); nil != got {
+ t.Fatalf("configured user guide should not be selected: %v", got)
+ }
+ if got = selectShorthandSaveBox("", boxes[:2]); nil != got {
+ t.Fatalf("no shorthand box should be selected: %v", got)
+ }
+}