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 explicit save and clear actions for sync configuration https://github.com/siyuan-note/siyuan/issues/20427
Daniel3eb8e4ae0186
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex 69c258b2e6..05410069d9 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,8 @@{+ "syncConfig": "إعدادات خدمة المزامنة",+ "clearSyncConfig": "مسح الإعدادات",+ "clearSyncConfigConfirm": "هل تريد مسح العنوان وبيانات الاعتماد المحفوظة لهذه الخدمة؟ إذا كانت خدمة المزامنة الحالية، فسيتم تعطيل المزامنة أيضًا. لن تُحذف الملاحظات المحلية أو بيانات السحابة.",+ "syncConfigSaveFailed": "تعذر تأكيد تغيير الإعدادات. تحقق من الاتصال وحاول مرة أخرى.","chooseFile": "اختيار ملف","syncConfigNotSaved": "لم يتم حفظ التغييرات، يرجى إكمال الحقول المطلوبة","previousDatabaseRow": "إدخال قاعدة البيانات السابق",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 14ca55e7b3..1500e70474 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,8 @@{+ "syncConfig": "Konfiguration des Synchronisierungsdienstes",+ "clearSyncConfig": "Konfiguration löschen",+ "clearSyncConfigConfirm": "Gespeicherte Adresse und Zugangsdaten dieses Dienstes löschen? Wenn dies der aktuelle Synchronisierungsdienst ist, wird auch die Synchronisierung deaktiviert. Lokale Notizen und Cloud-Daten werden nicht gelöscht.",+ "syncConfigSaveFailed": "Die Konfigurationsänderung konnte nicht bestätigt werden. Prüfen Sie die Verbindung und versuchen Sie es erneut.","chooseFile": "Datei auswählen","syncConfigNotSaved": "Änderungen wurden noch nicht gespeichert; bitte alle Pflichtfelder ausfüllen","previousDatabaseRow": "Vorheriger Datenbankeintrag",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 7d89810974..e7d67d5d72 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,8 @@{+ "syncConfig": "Sync service configuration",+ "clearSyncConfig": "Clear configuration",+ "clearSyncConfigConfirm": "Clear this service's saved address and credentials? If it is the current sync service, sync will also be disabled. Local notes and cloud data will not be deleted.",+ "syncConfigSaveFailed": "Unable to confirm the configuration change. Check the connection and try again.","chooseFile": "Choose file","syncConfigNotSaved": "Changes have not been saved; complete the required fields","previousDatabaseRow": "Previous database entry",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 058c0bf47b..b5250ed090 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,8 @@{+ "syncConfig": "Configuración del servicio de sincronización",+ "clearSyncConfig": "Borrar configuración",+ "clearSyncConfigConfirm": "¿Borrar la dirección y las credenciales guardadas de este servicio? Si es el servicio de sincronización actual, también se desactivará la sincronización. No se eliminarán las notas locales ni los datos en la nube.",+ "syncConfigSaveFailed": "No se pudo confirmar el cambio de configuración. Compruebe la conexión e inténtelo de nuevo.","chooseFile": "Seleccionar archivo","syncConfigNotSaved": "Los cambios no se han guardado; completa los campos obligatorios","previousDatabaseRow": "Entrada anterior de la base de datos",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex 0a6edc2f9d..4b666e0f2d 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,8 @@{+ "syncConfig": "Configuration du service de synchronisation",+ "clearSyncConfig": "Effacer la configuration",+ "clearSyncConfigConfirm": "Effacer l’adresse et les identifiants enregistrés pour ce service ? S’il s’agit du service de synchronisation actuel, la synchronisation sera aussi désactivée. Les notes locales et les données du cloud ne seront pas supprimées.",+ "syncConfigSaveFailed": "Impossible de confirmer la modification de la configuration. Vérifiez la connexion et réessayez.","chooseFile": "Choisir un fichier","syncConfigNotSaved": "Les modifications n’ont pas été enregistrées ; remplissez les champs obligatoires","previousDatabaseRow": "Entrée précédente de la base de données",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex c1d3407f34..e8b70cfd2f 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,8 @@{+ "syncConfig": "הגדרות שירות הסנכרון",+ "clearSyncConfig": "ניקוי ההגדרות",+ "clearSyncConfigConfirm": "לנקות את הכתובת ואת פרטי ההזדהות השמורים של שירות זה? אם זהו שירות הסנכרון הנוכחי, גם הסנכרון יושבת. פתקים מקומיים ונתוני ענן לא יימחקו.",+ "syncConfigSaveFailed": "לא ניתן לאשר את שינוי ההגדרות. יש לבדוק את החיבור ולנסות שוב.","chooseFile": "בחירת קובץ","syncConfigNotSaved": "השינויים טרם נשמרו; יש למלא את כל שדות החובה","previousDatabaseRow": "הרשומה הקודמת במסד הנתונים",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 1b6853e8f5..79b050a196 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,8 @@{+ "syncConfig": "सिंक सेवा कॉन्फ़िगरेशन",+ "clearSyncConfig": "कॉन्फ़िगरेशन साफ़ करें",+ "clearSyncConfigConfirm": "इस सेवा का सहेजा गया पता और क्रेडेंशियल साफ़ करें? यदि यह वर्तमान सिंक सेवा है, तो सिंक भी बंद हो जाएगा। स्थानीय नोट और क्लाउड डेटा नहीं मिटाए जाएँगे।",+ "syncConfigSaveFailed": "कॉन्फ़िगरेशन में बदलाव की पुष्टि नहीं हो सकी। कनेक्शन जाँचें और फिर से कोशिश करें।","chooseFile": "फ़ाइल चुनें","syncConfigNotSaved": "बदलाव अभी सहेजे नहीं गए हैं; कृपया आवश्यक फ़ील्ड भरें","previousDatabaseRow": "पिछली डेटाबेस प्रविष्टि",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex b54265fdc9..8d25412d38 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,8 @@{+ "syncConfig": "Konfigurasi layanan sinkronisasi",+ "clearSyncConfig": "Hapus konfigurasi",+ "clearSyncConfigConfirm": "Hapus alamat dan kredensial yang tersimpan untuk layanan ini? Jika ini layanan sinkronisasi saat ini, sinkronisasi juga akan dinonaktifkan. Catatan lokal dan data cloud tidak akan dihapus.",+ "syncConfigSaveFailed": "Perubahan konfigurasi tidak dapat dikonfirmasi. Periksa koneksi lalu coba lagi.","chooseFile": "Pilih berkas","syncConfigNotSaved": "Perubahan belum disimpan; lengkapi kolom wajib","previousDatabaseRow": "Entri basis data sebelumnya",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex bbcbd5b2b4..ef112fa9fb 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,8 @@{+ "syncConfig": "Configurazione del servizio di sincronizzazione",+ "clearSyncConfig": "Cancella configurazione",+ "clearSyncConfigConfirm": "Cancellare l’indirizzo e le credenziali salvati per questo servizio? Se è il servizio di sincronizzazione attuale, verrà disattivata anche la sincronizzazione. Le note locali e i dati nel cloud non verranno eliminati.",+ "syncConfigSaveFailed": "Impossibile confermare la modifica della configurazione. Controlla la connessione e riprova.","chooseFile": "Scegli file","syncConfigNotSaved": "Le modifiche non sono state salvate; compila i campi obbligatori","previousDatabaseRow": "Voce precedente del database",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex ed516a8ab6..1081248fda 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,8 @@{+ "syncConfig": "同期サービスの設定",+ "clearSyncConfig": "設定を消去",+ "clearSyncConfigConfirm": "このサービスの保存済みアドレスと認証情報を消去しますか?現在の同期サービスの場合は同期も無効になります。ローカルのノートとクラウドのデータは削除されません。",+ "syncConfigSaveFailed": "設定の変更を確認できません。接続を確認して再試行してください。","chooseFile": "ファイルを選択","syncConfigNotSaved": "変更はまだ保存されていません。必須項目をすべて入力してください","previousDatabaseRow": "前のデータベース項目",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex f08cc575b0..0bd456187a 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,8 @@{+ "syncConfig": "동기화 서비스 설정",+ "clearSyncConfig": "설정 지우기",+ "clearSyncConfigConfirm": "이 서비스에 저장된 주소와 인증 정보를 지우시겠습니까? 현재 동기화 서비스인 경우 동기화도 비활성화됩니다. 로컬 노트와 클라우드 데이터는 삭제되지 않습니다.",+ "syncConfigSaveFailed": "설정 변경을 확인할 수 없습니다. 연결을 확인한 후 다시 시도하세요.","chooseFile": "파일 선택","syncConfigNotSaved": "변경 사항이 아직 저장되지 않았습니다. 필수 항목을 모두 입력해 주세요","previousDatabaseRow": "이전 데이터베이스 항목",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex b8b2339d3b..74a23b2654 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,8 @@{+ "syncConfig": "Configuratie van synchronisatiedienst",+ "clearSyncConfig": "Configuratie wissen",+ "clearSyncConfigConfirm": "Het opgeslagen adres en de inloggegevens van deze dienst wissen? Als dit de huidige synchronisatiedienst is, wordt synchronisatie ook uitgeschakeld. Lokale notities en cloudgegevens worden niet verwijderd.",+ "syncConfigSaveFailed": "De configuratiewijziging kon niet worden bevestigd. Controleer de verbinding en probeer het opnieuw.","chooseFile": "Bestand kiezen","syncConfigNotSaved": "De wijzigingen zijn nog niet opgeslagen; vul de verplichte velden in","previousDatabaseRow": "Vorige databasevermelding",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 7aa505860b..411e09f973 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,8 @@{+ "syncConfig": "Konfiguracja usługi synchronizacji",+ "clearSyncConfig": "Wyczyść konfigurację",+ "clearSyncConfigConfirm": "Wyczyścić zapisany adres i dane uwierzytelniające tej usługi? Jeśli jest to bieżąca usługa synchronizacji, synchronizacja również zostanie wyłączona. Lokalne notatki i dane w chmurze nie zostaną usunięte.",+ "syncConfigSaveFailed": "Nie można potwierdzić zmiany konfiguracji. Sprawdź połączenie i spróbuj ponownie.","chooseFile": "Wybierz plik","syncConfigNotSaved": "Zmiany nie zostały zapisane; uzupełnij wymagane pola","previousDatabaseRow": "Poprzedni wpis w bazie danych",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 503b52dfe4..41c775ded8 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,8 @@{+ "syncConfig": "Configuração do serviço de sincronização",+ "clearSyncConfig": "Limpar configuração",+ "clearSyncConfigConfirm": "Limpar o endereço e as credenciais salvos deste serviço? Se ele for o serviço de sincronização atual, a sincronização também será desativada. As notas locais e os dados na nuvem não serão excluídos.",+ "syncConfigSaveFailed": "Não foi possível confirmar a alteração da configuração. Verifique a conexão e tente novamente.","chooseFile": "Selecionar arquivo","syncConfigNotSaved": "As alterações ainda não foram salvas; preencha os campos obrigatórios","previousDatabaseRow": "Entrada anterior do banco de dados",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 809a65c969..9e8ad56345 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,8 @@{+ "syncConfig": "Настройка службы синхронизации",+ "clearSyncConfig": "Очистить настройки",+ "clearSyncConfigConfirm": "Удалить сохранённый адрес и учётные данные этой службы? Если это текущая служба синхронизации, синхронизация также будет отключена. Локальные заметки и облачные данные не будут удалены.",+ "syncConfigSaveFailed": "Не удалось подтвердить изменение настроек. Проверьте подключение и повторите попытку.","chooseFile": "Выбрать файл","syncConfigNotSaved": "Изменения не сохранены; заполните обязательные поля","previousDatabaseRow": "Предыдущая запись базы данных",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex af23721035..2cc6d515f0 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,8 @@{+ "syncConfig": "Nastavenie služby synchronizácie",+ "clearSyncConfig": "Vymazať nastavenie",+ "clearSyncConfigConfirm": "Vymazať uloženú adresu a prihlasovacie údaje tejto služby? Ak ide o aktuálnu službu synchronizácie, synchronizácia sa tiež vypne. Lokálne poznámky a údaje v cloude sa neodstránia.",+ "syncConfigSaveFailed": "Zmenu nastavenia sa nepodarilo potvrdiť. Skontrolujte pripojenie a skúste to znova.","chooseFile": "Vybrať súbor","syncConfigNotSaved": "Zmeny neboli uložené; vyplňte povinné polia","previousDatabaseRow": "Predchádzajúca položka databázy",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex 6256ec29bf..03c39480e2 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,8 @@{+ "syncConfig": "Подешавање услуге синхронизације",+ "clearSyncConfig": "Обриши подешавања",+ "clearSyncConfigConfirm": "Обрисати сачувану адресу и приступне податке ове услуге? Ако је ово тренутна услуга синхронизације, синхронизација ће такође бити искључена. Локалне белешке и подаци у облаку неће бити обрисани.",+ "syncConfigSaveFailed": "Није могуће потврдити промену подешавања. Проверите везу и покушајте поново.","chooseFile": "Изабери датотеку","syncConfigNotSaved": "Промене нису сачуване; попуните обавезна поља","previousDatabaseRow": "Претходни унос базе података",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex f8dfa27410..06c8a86b6b 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,8 @@{+ "syncConfig": "การตั้งค่าบริการซิงค์",+ "clearSyncConfig": "ล้างการตั้งค่า",+ "clearSyncConfigConfirm": "ล้างที่อยู่และข้อมูลรับรองที่บันทึกไว้ของบริการนี้หรือไม่? หากเป็นบริการซิงค์ปัจจุบัน การซิงค์จะถูกปิดด้วย บันทึกในเครื่องและข้อมูลบนคลาวด์จะไม่ถูกลบ",+ "syncConfigSaveFailed": "ไม่สามารถยืนยันการเปลี่ยนแปลงการตั้งค่าได้ โปรดตรวจสอบการเชื่อมต่อแล้วลองอีกครั้ง","chooseFile": "เลือกไฟล์","syncConfigNotSaved": "ยังไม่ได้บันทึกการเปลี่ยนแปลง โปรดกรอกข้อมูลในช่องที่จำเป็นให้ครบ","previousDatabaseRow": "รายการฐานข้อมูลก่อนหน้า",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 7d84dd9777..420e12f832 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,8 @@{+ "syncConfig": "Eşitleme hizmeti yapılandırması",+ "clearSyncConfig": "Yapılandırmayı temizle",+ "clearSyncConfigConfirm": "Bu hizmetin kayıtlı adresi ve kimlik bilgileri temizlensin mi? Geçerli eşitleme hizmetiyse eşitleme de devre dışı bırakılır. Yerel notlar ve bulut verileri silinmez.",+ "syncConfigSaveFailed": "Yapılandırma değişikliği doğrulanamadı. Bağlantıyı kontrol edip tekrar deneyin.","chooseFile": "Dosya seç","syncConfigNotSaved": "Değişiklikler henüz kaydedilmedi; zorunlu alanları doldurun","previousDatabaseRow": "Önceki veritabanı kaydı",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex de60cb9704..948ae38a1c 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,8 @@{+ "syncConfig": "Налаштування служби синхронізації",+ "clearSyncConfig": "Очистити налаштування",+ "clearSyncConfigConfirm": "Видалити збережену адресу й облікові дані цієї служби? Якщо це поточна служба синхронізації, синхронізацію також буде вимкнено. Локальні нотатки та хмарні дані не буде видалено.",+ "syncConfigSaveFailed": "Не вдалося підтвердити зміну налаштувань. Перевірте з’єднання та повторіть спробу.","chooseFile": "Вибрати файл","syncConfigNotSaved": "Зміни не збережено; заповніть обов’язкові поля","previousDatabaseRow": "Попередній запис бази даних",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 0bbec6fb74..05688a0173 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,8 @@{+ "syncConfig": "同步服务配置",+ "clearSyncConfig": "清除配置",+ "clearSyncConfigConfirm": "清除该服务保存的地址和凭据?如果它是当前同步服务,将同时关闭同步。本地笔记和云端数据不会被删除。",+ "syncConfigSaveFailed": "无法确认配置是否已更新,请检查连接后重试。","chooseFile": "选择文件","syncConfigNotSaved": "更改尚未保存,请填写完整的必填项","previousDatabaseRow": "上一条数据库条目",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 6ef821b496..8f944f90aa 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,8 @@{+ "syncConfig": "同步服務設定",+ "clearSyncConfig": "清除設定",+ "clearSyncConfigConfirm": "清除這項服務儲存的位址和憑證?如果它是目前的同步服務,也會關閉同步。本機筆記和雲端資料不會被刪除。",+ "syncConfigSaveFailed": "無法確認設定是否已更新,請檢查連線後重試。","chooseFile": "選擇檔案","syncConfigNotSaved": "變更尚未儲存,請填寫完整的必填項目","previousDatabaseRow": "上一筆資料庫項目",diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20230805231614-vqn28eh/20210808180303-v9awwp0/20210721112206-mhr9wxi.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20230805231614-vqn28eh/20210808180303-v9awwp0/20210721112206-mhr9wxi.syindex 444d68a07f..a1bee768ad 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20230805231614-vqn28eh/20210808180303-v9awwp0/20210721112206-mhr9wxi.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20230805231614-vqn28eh/20210808180303-v9awwp0/20210721112206-mhr9wxi.sy@@ -6,7 +6,7 @@"id": "20210721112206-mhr9wxi","title": "Data sync","type": "doc",- "updated": "20260918195936"+ "updated": "20261011151543"},"Children": [{@@ -428,6 +428,99 @@}]},+ {+ "ID": "20261011151543-4pvea6y",+ "Type": "NodeHeading",+ "HeadingLevel": 3,+ "Properties": {+ "id": "20261011151543-4pvea6y",+ "updated": "20261011151543"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "Configure third-party sync"+ }+ ]+ },+ {+ "ID": "20261011151543-l4oq2bn",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261011151543-l4oq2bn",+ "updated": "20261011151543"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "In "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Settings"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Account & Sync"+ },+ {+ "Type": "NodeText",+ "Data": ", select S3, WebDAV, or the local file system (desktop only), then click the configuration button in the sync service configuration row. Complete the form and click "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Save"+ },+ {+ "Type": "NodeText",+ "Data": ". Typing does not save changes; closing an edited form asks whether to discard the draft."+ }+ ]+ },+ {+ "ID": "20261011151543-h1km9eh",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261011151543-h1km9eh",+ "updated": "20261011151543"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "To stop using a service, click "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "Clear configuration"+ },+ {+ "Type": "NodeText",+ "Data": " in its configuration dialog and confirm. This removes the saved address and credentials, and disables sync if this is the current service. Local notes and cloud data remain intact."+ }+ ]+ },+ {+ "ID": "20261011151543-hbd6s1c",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261011151543-hbd6s1c",+ "updated": "20261011151543"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "If changing or clearing the current source is blocked because resources or historical snapshots are incomplete, restore access to the original source and finish downloading all resources before trying again. A failed save or clear keeps the effective configuration and the draft."+ }+ ]+ },{"ID": "20230219121305-3yj6w9y","Type": "NodeHeading",diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20230805222417-2lj3dvk/20230808120348-orm8sjf/20230808120347-3cob0nb.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20230805222417-2lj3dvk/20230808120348-orm8sjf/20230808120347-3cob0nb.syindex c81d78c6f0..a70effba2a 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20230805222417-2lj3dvk/20230808120348-orm8sjf/20230808120347-3cob0nb.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20230805222417-2lj3dvk/20230808120348-orm8sjf/20230808120347-3cob0nb.sy@@ -6,7 +6,7 @@"id": "20230808120347-3cob0nb","title": "数据同步","type": "doc",- "updated": "20260918195936"+ "updated": "20261011151543"},"Children": [{@@ -424,6 +424,99 @@}]},+ {+ "ID": "20261011151543-be59rg9",+ "Type": "NodeHeading",+ "HeadingLevel": 3,+ "Properties": {+ "id": "20261011151543-be59rg9",+ "updated": "20261011151543"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "配置第三方同步"+ }+ ]+ },+ {+ "ID": "20261011151543-x2jg56f",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261011151543-x2jg56f",+ "updated": "20261011151543"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "在 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "设置"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "账号与同步"+ },+ {+ "Type": "NodeText",+ "Data": " 中选择 S3、WebDAV 或本地文件系统(仅桌面端),然后点击同步服务配置一行的设置按钮。填写完整后点击 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "保存"+ },+ {+ "Type": "NodeText",+ "Data": "。输入过程中不会保存,关闭有修改的表单时会询问是否放弃草稿。"+ }+ ]+ },+ {+ "ID": "20261011151543-p38jv4a",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261011151543-p38jv4a",+ "updated": "20261011151543"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "停止使用某个服务时,可在其配置弹窗中点击 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "清除配置"+ },+ {+ "Type": "NodeText",+ "Data": " 并确认。这会删除已保存的地址和凭据;如果它是当前同步服务,还会关闭同步。本地笔记和云端数据会保留。"+ }+ ]+ },+ {+ "ID": "20261011151543-986cazk",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261011151543-986cazk",+ "updated": "20261011151543"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "如果当前来源的资源或历史快照尚未补齐,修改来源或清除配置会被阻止。请恢复原同步源的访问并完成全部下载后重试。保存或清除失败时,生效配置和草稿都会保留。"+ }+ ]+ },{"ID": "20230808120347-buiv5yn","Type": "NodeHeading",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20230805232636-zh0adz2/20211226121232-23s79xr/20211226121438-xaafdo8.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20230805232636-zh0adz2/20211226121232-23s79xr/20211226121438-xaafdo8.syindex d34057434b..cc7d9f5915 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20230805232636-zh0adz2/20211226121232-23s79xr/20211226121438-xaafdo8.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20230805232636-zh0adz2/20211226121232-23s79xr/20211226121438-xaafdo8.sy@@ -6,7 +6,7 @@"id": "20211226121438-xaafdo8","title": "資料同步","type": "doc",- "updated": "20260918195936"+ "updated": "20261011151543"},"Children": [{@@ -424,6 +424,99 @@}]},+ {+ "ID": "20261011151543-1587etm",+ "Type": "NodeHeading",+ "HeadingLevel": 3,+ "Properties": {+ "id": "20261011151543-1587etm",+ "updated": "20261011151543"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "設定第三方同步"+ }+ ]+ },+ {+ "ID": "20261011151543-j3donul",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261011151543-j3donul",+ "updated": "20261011151543"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "在 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "設定"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "帳號與同步"+ },+ {+ "Type": "NodeText",+ "Data": " 中選擇 S3、WebDAV 或本地檔案系統(僅桌面版),然後點擊同步服務設定一列的設定按鈕。填寫完整後點擊 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "保存"+ },+ {+ "Type": "NodeText",+ "Data": "。輸入過程不會儲存,關閉已修改的表單時會詢問是否放棄草稿。"+ }+ ]+ },+ {+ "ID": "20261011151543-tvc378w",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261011151543-tvc378w",+ "updated": "20261011151543"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "停止使用某個服務時,可在其設定對話框中點擊 "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "清除設定"+ },+ {+ "Type": "NodeText",+ "Data": " 並確認。這會刪除已儲存的位址和憑證;若它是目前的同步服務,也會關閉同步。本地筆記和雲端資料會保留。"+ }+ ]+ },+ {+ "ID": "20261011151543-ard7rnq",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261011151543-ard7rnq",+ "updated": "20261011151543"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "若目前來源的資源或歷史快照尚未補齊,變更來源或清除設定會被阻止。請恢復原同步來源的存取並完成全部下載後重試。儲存或清除失敗時,生效設定和草稿都會保留。"+ }+ ]+ },{"ID": "20230219121211-f7pvncg","Type": "NodeHeading",diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-cb37szr/20240530101000-vhq5afs/20240530101000-wo49zvq.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-cb37szr/20240530101000-vhq5afs/20240530101000-wo49zvq.syindex 45126f8496..dc48a68b78 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-cb37szr/20240530101000-vhq5afs/20240530101000-wo49zvq.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-cb37szr/20240530101000-vhq5afs/20240530101000-wo49zvq.sy@@ -7,7 +7,7 @@"id": "20240530101000-wo49zvq","title": "データ同期","type": "doc",- "updated": "20260918195936"+ "updated": "20261011151543"},"Children": [{@@ -461,6 +461,95 @@}]},+ {+ "ID": "20261011151543-f2vsvp5",+ "Type": "NodeHeading",+ "HeadingLevel": 3,+ "Properties": {+ "id": "20261011151543-f2vsvp5",+ "updated": "20261011151543"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "サードパーティ同期の設定"+ }+ ]+ },+ {+ "ID": "20261011151543-94ddrfk",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261011151543-94ddrfk",+ "updated": "20261011151543"+ },+ "Children": [+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "設定"+ },+ {+ "Type": "NodeText",+ "Data": " - "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "アカウントと同期"+ },+ {+ "Type": "NodeText",+ "Data": " で S3、WebDAV、またはローカルファイルシステム(デスクトップ版のみ)を選び、同期サービスの設定欄にある設定ボタンを押します。必要な項目を入力して "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "保存"+ },+ {+ "Type": "NodeText",+ "Data": " を押してください。入力中は保存されず、変更したフォームを閉じると下書きを破棄するか確認されます。"+ }+ ]+ },+ {+ "ID": "20261011151543-pf8uunp",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261011151543-pf8uunp",+ "updated": "20261011151543"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "サービスの利用をやめる場合は、設定ダイアログで "+ },+ {+ "Type": "NodeTextMark",+ "TextMarkType": "kbd",+ "TextMarkTextContent": "設定を消去"+ },+ {+ "Type": "NodeText",+ "Data": " を押して確認します。保存されたアドレスと認証情報が削除され、現在の同期サービスの場合は同期も無効になります。ローカルのノートとクラウド上のデータは残ります。"+ }+ ]+ },+ {+ "ID": "20261011151543-ykfoii4",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261011151543-ykfoii4",+ "updated": "20261011151543"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "現在の同期元のリソースや履歴スナップショットが完全にダウンロードされていない場合、同期元の変更や設定の消去はできません。元の同期先へのアクセスを復旧し、すべてのリソースをダウンロードしてから再試行してください。保存や消去に失敗しても、有効な設定と下書きは保持されます。"+ }+ ]+ },{"ID": "20240530101000-01df0kh","Type": "NodeHeading",diff --git a/app/src/assets/scss/business/_config.scss b/app/src/assets/scss/business/_config.scssindex 80e5270602..f7b27dadb8 100644--- a/app/src/assets/scss/business/_config.scss+++ b/app/src/assets/scss/business/_config.scss@@ -165,6 +165,23 @@}}+.config-sync-field {+ flex-wrap: wrap;++ > .fn__flex-1 {+ min-width: 0;+ }+}++.config-sync-form {+ min-height: 0;+}++.config-sync-dialog {+ max-height: 90vh;+ max-height: 90dvh;+}+@media screen and (max-width: 750px) {.config-sync-field > .fn__flex-1 {flex: none;diff --git a/app/src/config/tabs/syncUi.test.ts b/app/src/config/tabs/syncUi.test.tsindex c378ab3ddd..d566775f45 100644--- a/app/src/config/tabs/syncUi.test.ts+++ b/app/src/config/tabs/syncUi.test.ts@@ -1,172 +1,235 @@import * as assert from "node:assert/strict";import {readFileSync} from "node:fs";-import {resolve} from "node:path";import {test} from "node:test";import {runInNewContext} from "node:vm";import {ModuleKind, transpileModule} from "typescript";-const setup = (initial: {endpoint?: string, bucket?: string} = {}) => {- const source = readFileSync(resolve(process.cwd(), "src/config/tabs/syncUi.ts"), "utf8");- const code = transpileModule(source + "\nexports.bind = bindProviderConfigEvent;", {- compilerOptions: {module: ModuleKind.CommonJS},- }).outputText;- const s3 = {endpoint: "", accessKey: "", secretKey: "", bucket: "", region: "", timeout: 30,- pathStyle: true, skipTlsVerify: false, concurrentReqs: 4};- const sync = {provider: 2, s3};- Object.assign(s3, initial);- const inputs = Object.fromEntries(Object.keys(s3).map((key) => [key, {- value: "",- focus: () => {},- attributes: {} as Record<string, string>,- setAttribute(name: string, value: string) {this.attributes[name] = value;},+const source = readFileSync("src/config/tabs/syncUi.ts", "utf8");+const code = transpileModule(source + "\nexports.open = openSyncProviderConfigDialog;", {+ compilerOptions: {module: ModuleKind.CommonJS},+}).outputText;++const setup = (provider = 2, mobile = false) => {+ const s3 = {endpoint: "storage.example.com", accessKey: "key", secretKey: "secret", bucket: "notes", region: "auto",+ timeout: 30, pathStyle: true, skipTlsVerify: false, concurrentReqs: 4};+ const webdav = {endpoint: "dav.example.com", username: "user", password: "password", timeout: 30, skipTlsVerify: false, concurrentReqs: 4};+ const local = {endpoint: "/cloud", timeout: 30, concurrentReqs: 4};+ const sync = {provider, enabled: true, s3, webdav, local};+ const config = {sync, readonly: false, system: {container: "std"}};+ const template = provider === 2 ? s3 : provider === 3 ? webdav : local;+ const events: Record<string, (event: unknown) => void> = {};+ const inputs = Object.fromEntries(Object.entries(template).map(([key, value]) => [key, {+ value: "", type: typeof value === "number" ? "number" : "text", disabled: false,+ attributes: {} as Record<string, string>, focused: false, validationMessage: "Invalid number",+ focus() { this.focused = true; },+ setAttribute(name: string, value: string) { this.attributes[name] = value; },+ getAttribute(name: string) { return this.attributes[name]; },+ checkValidity() { return this.value.trim() !== "" && Number.isInteger(Number(this.value)) && Number(this.value) > 0; },}]));- const errors = Object.fromEntries(Object.keys(s3).map(key => [`sync-${key}-error`, {+ const errors = Object.fromEntries(Object.keys(template).map(key => [`sync-${key}-error`, {textContent: "", classList: {toggle() {}},}]));- let unsaved = false;- const status = {classList: {toggle: (_name: string, hidden: boolean) => { unsaved = !hidden; }}};- const messages: string[] = [];- const events: Record<string, (event: unknown) => void> = {};+ const status = {textContent: "", classList: {toggle() {} }};let warningHidden = true;const warning = {classList: {toggle: (_name: string, hidden: boolean) => { warningHidden = hidden; }}};+ const buttons = Object.fromEntries(["save", "cancel", "clear"].map(action => [action, {+ disabled: false, callback: () => {}, addEventListener(_event: string, callback: () => void) {this.callback = callback;},+ getAttribute(name: string) { return name === "data-action" ? action : null; },+ }]));const element = {- querySelector: (selector: string) => selector === '[data-type="s3-endpoint-warning"]' ? warning :- selector === '[data-type="sync-config-unsaved"]' ? status : inputs[selector.slice(1)] || errors[selector.slice(1)] || null,- addEventListener: (name: string, callback: (event: unknown) => void) => { events[name] = callback; },+ querySelector(selector: string) {+ if (selector === ".b3-dialog__container") { return {focus() {}}; }+ if (selector === '[data-type="sync-config-error"]') { return status; }+ if (selector === '[data-type="s3-endpoint-warning"]') { return provider === 2 ? warning : null; }+ if (selector === '[aria-invalid="true"]') { return Object.values(inputs).find(input => input.attributes["aria-invalid"] === "true"); }+ if (selector.startsWith('[data-action="')) { return buttons[selector.slice(14, -2)] || null; }+ return inputs[selector.slice(1)] || errors[selector.slice(1)] || null;+ },+ querySelectorAll: () => [...Object.values(inputs), ...Object.values(buttons)],+ addEventListener(name: string, callback: (event: unknown) => void) {events[name] = callback;},+ setAttribute() {},};- const requests: {data: {s3: typeof s3}, resolve: (response: unknown) => void, reject: (error: Error) => void}[] = [];- const moduleExports = {} as {bind: (config: unknown, root: unknown) => void};+ const root = {isConnected: true, querySelector: (): null => null};+ const enabled = {checked: true};+ const replacement = {querySelector: (selector: string) => selector === '[id="sync.enabled"]' ? enabled : null};+ const requests: {url: string, data: any, resolve: (response: any) => void, reject: () => void}[] = [];+ const confirmations: {confirm: () => void, cancel: () => void}[] = [];+ let closed = 0;+ let dialog: {destroy: () => void};+ let dialogOptions: {width: string, content: string};+ const exports = {} as {open: (root: unknown) => void};runInNewContext(code, {- URL,- exports: moduleExports,- window: {siyuan: {config: {sync}, languages: {_kernel: {142: "Input can not be empty"}}}},- require: (name: string) => {- if (name === "../../util/fetch") {- return {fetchSyncPost: (_url: string, data: {s3: typeof s3}) => new Promise((resolve, reject) => {- requests.push({data, resolve, reject});- })};+ URL, CSS: {escape: (value: string) => value}, exports,+ document: {querySelector: () => ({closest: () => replacement})},+ window: {siyuan: {config, languages: {syncConfigNotSaved: "Required fields missing", syncConfigSaveFailed: "Not confirmed",+ _kernel: {142: "Input cannot be empty"}}}},+ require(name: string) {+ if (name === "../../dialog") {+ return {Dialog: class {+ element = element;+ constructor(options: any) {dialog = {destroy: () => this.destroy()}; dialogOptions = options;}+ destroy() {closed++;}+ }};}- if (name === "../../dialog/message") {- return {showMessage: (message: string) => messages.push(message)};+ if (name === "../../dialog/confirmDialog") {+ return {confirmDialog: (_title: string, _text: string, confirm: () => void, cancel: () => void) => confirmations.push({confirm, cancel})};}- if (name === "../../util/needSubscribe") {- return {isPaidUser: () => true};+ if (name === "../../util/fetch") {+ return {fetchSyncPost: (url: string, data: any) => new Promise((resolve, reject) => requests.push({url, data, resolve, reject}))};}+ if (name === "../../util/functions") { return {isMobile: () => mobile}; }+ if (name === "../../util/needSubscribe") { return {isPaidUser: () => true, needSubscribe: () => false}; }return {};},});- moduleExports.bind(element, element);- const fill = () => {- for (const key of ["endpoint", "accessKey", "secretKey", "bucket", "region"]) {- inputs[key].value = key === "endpoint" ? " storage.example.com " : key;- events.change({target: {matches: () => true}});- }- };- return {sync, inputs, requests, messages, fill, errors, unsaved: () => unsaved, warningHidden: () => warningHidden,- input: () => events.input({}), change: () => events.change({target: {matches: () => true}})};+ exports.open(root);+ return {inputs, sync, config, requests, confirmations, buttons, status, root, events, enabled,+ options: () => dialogOptions, close: () => dialog.destroy(), closed: () => closed,+ click: (action: string) => buttons[action].callback(), input: () => events.input({}),+ warningHidden: () => warningHidden};};-const settle = () => new Promise<void>((resolve) => setImmediate(resolve));+const settle = () => new Promise<void>(resolve => setImmediate(resolve));-for (const key of ["timeout", "concurrentReqs"] as const) {- test(`empty S3 ${key} preserves the input and configuration until corrected`, async () => {- const ui = setup();- ui.fill();- await settle();- const saved = {...ui.requests[0].data.s3};- ui.inputs[key].value = "";- ui.change();- ui.requests[0].resolve({code: 0, data: {s3: saved}});- await settle();+for (const provider of [2, 3, 4]) {+ test(`provider ${provider} submits the complete draft only after Save`, async () => {+ const ui = setup(provider);+ ui.inputs.endpoint.value = "new.example.com";+ ui.input();+ assert.equal(ui.events.change, undefined);+ assert.equal(ui.requests.length, 0);+ const key = provider === 2 ? "s3" : provider === 3 ? "webdav" : "local";+ ui.click("save");+ ui.click("save");assert.equal(ui.requests.length, 1);- assert.equal(ui.inputs[key].value, "");- assert.equal(ui.sync.s3[key], saved[key]);- assert.deepEqual(ui.messages, ["Input can not be empty"]);- ui.inputs[key].value = "7";- ui.change();+ assert.equal(ui.requests[0].data[key].endpoint, "new.example.com");+ assert.equal(ui.buttons.save.disabled, true);+ ui.close();+ assert.equal(ui.closed(), 0);+ ui.requests[0].resolve({code: 0, data: {[key]: {...ui.requests[0].data[key], endpoint: "https://new.example.com"}}});await settle();- assert.equal(ui.requests.length, 2);- assert.equal(ui.requests[1].data.s3[key], 7);+ assert.equal(ui.sync[key].endpoint, "https://new.example.com");+ assert.equal(ui.closed(), 1);});}-test("S3 bucket endpoint warning appears for saved configurations and follows edits without blocking saves", async () => {- const ui = setup({endpoint: "https://my.bucket.s3.example.com", bucket: "my.bucket"});- assert.equal(ui.warningHidden(), false);- for (const endpoint of ["s3.example.com", "https://othermy.bucket.s3.example.com", "https://s3.example.com/my.bucket", "https://"]) {- ui.inputs.endpoint.value = endpoint;- ui.input();- assert.equal(ui.warningHidden(), true, endpoint);+test("required and numeric validation keeps empty or invalid draft values without saving", () => {+ for (const key of ["endpoint", "secretKey", "timeout", "concurrentReqs"]) {+ const ui = setup();+ ui.inputs[key].value = "";+ ui.click("save");+ assert.equal(ui.requests.length, 0, key);+ assert.equal(ui.inputs[key].value, "");+ assert.equal(ui.inputs[key].attributes["aria-invalid"], "true");+ assert.equal(ui.status.textContent, "Required fields missing");}- ui.fill();- await settle();- ui.requests[0].resolve({code: 0, data: {s3: ui.requests[0].data.s3}});- await settle();- ui.inputs.endpoint.value = " BUCKET.s3.example.com ";- ui.inputs.pathStyle.value = "false";- ui.input();- assert.equal(ui.warningHidden(), false);- ui.change();- await settle();- assert.equal(ui.requests.length, 2);- assert.equal(ui.requests[1].data.s3.endpoint, " BUCKET.s3.example.com ");- ui.inputs.bucket.value = "different";- ui.input();- assert.equal(ui.warningHidden(), true);+ const ui = setup();+ ui.inputs.timeout.value = "1.5";+ ui.click("save");+ assert.equal(ui.requests.length, 0);});-test("S3 configuration saves automatically once required fields are complete", async () => {+test("cancel or close confirms dirty drafts and never saves them", () => {+ const pristine = setup();+ pristine.click("cancel");+ assert.equal(pristine.closed(), 1);+ assert.equal(pristine.confirmations.length, 0);const ui = setup();- ui.change();- await settle();- assert.equal(ui.messages.length, 0);+ ui.inputs.secretKey.value = "draft secret";+ ui.click("cancel");+ ui.close();+ assert.equal(ui.confirmations.length, 1);+ assert.equal(ui.closed(), 0);+ ui.confirmations[0].cancel();+ assert.equal(ui.inputs.secretKey.value, "draft secret");+ ui.close();+ ui.confirmations[1].confirm();+ assert.equal(ui.closed(), 1);assert.equal(ui.requests.length, 0);- assert.equal(ui.unsaved(), true);- assert.equal(ui.inputs.endpoint.attributes["aria-invalid"], "true");- assert.equal(ui.errors["sync-endpoint-error"].textContent, "Input can not be empty");- ui.fill();- await settle();- assert.equal(ui.requests.length, 1);- assert.equal(ui.requests[0].data.s3.region, "region");- assert.equal(ui.unsaved(), false);- ui.inputs.endpoint.value = "";- ui.input();- assert.equal(ui.unsaved(), true);- assert.equal(ui.inputs.endpoint.attributes["aria-invalid"], "true");+ assert.equal(ui.sync.s3.secretKey, "secret");});-test("failed S3 saves retain all inputs and allow retry", async () => {+test("failed saves keep drafts after panel replacement and allow retry", async () => {const ui = setup();- ui.fill();- await settle();- ui.requests[0].resolve({code: -1});+ ui.inputs.endpoint.value = "new.example.com";+ ui.root.isConnected = false;+ ui.click("save");+ ui.requests[0].resolve({code: -1, msg: "Download resources first"});await settle();- assert.equal(ui.inputs.endpoint.value, " storage.example.com ");- assert.equal(ui.inputs.secretKey.value, "secretKey");- assert.equal(ui.sync.s3.endpoint, "");- ui.change();+ assert.equal(ui.status.textContent, "Download resources first");+ assert.equal(ui.inputs.endpoint.value, "new.example.com");+ assert.equal(ui.sync.s3.endpoint, "storage.example.com");+ assert.equal(ui.closed(), 0);+ ui.click("save");+ ui.requests[1].reject();await settle();- ui.requests[1].reject(new Error("network"));+ assert.equal(ui.status.textContent, "Not confirmed");+ assert.equal(ui.buttons.save.disabled, false);+ ui.click("save");+ ui.requests[2].resolve({code: 0, data: {s3: ui.requests[2].data.s3}});await settle();- assert.equal(ui.inputs.endpoint.value, " storage.example.com ");+ assert.equal(ui.closed(), 1);});-test("successful S3 saves normalize unchanged fields and preserve edits made while saving", async () => {+test("clear requires confirmation and preserves the source when the kernel refuses", async () => {const ui = setup();- ui.fill();- await settle();- ui.inputs.bucket.value = "another-bucket";- ui.change();+ ui.root.isConnected = false;+ ui.click("clear");+ assert.equal(ui.requests.length, 0);+ ui.confirmations[0].cancel();+ assert.equal(ui.requests.length, 0);+ ui.click("clear");+ ui.confirmations[1].confirm();+ assert.equal(ui.requests[0].url, "/api/sync/clearSyncProviderConfig");+ assert.equal(ui.requests[0].data.provider, 2);+ ui.requests[0].resolve({code: -1, msg: "Incomplete history"});await settle();- assert.equal(ui.requests.length, 1);- ui.requests[0].resolve({code: 0, data: {s3: {...ui.requests[0].data.s3, endpoint: "https://storage.example.com"}}});+ assert.equal(ui.sync.s3.secretKey, "secret");+ assert.equal(ui.sync.enabled, true);+ assert.equal(ui.closed(), 0);+ assert.equal(ui.status.textContent, "Incomplete history");+ ui.click("clear");+ ui.confirmations[2].confirm();+ ui.requests[1].resolve({code: 0, data: {enabled: false, s3: {...ui.sync.s3, endpoint: "", secretKey: ""}}});await settle();- assert.equal(ui.inputs.endpoint.value, "https://storage.example.com");- assert.equal(ui.inputs.bucket.value, "another-bucket");- assert.equal(ui.sync.s3.bucket, "bucket");- assert.equal(ui.requests.length, 2);- assert.equal(ui.requests[1].data.s3.bucket, "another-bucket");- ui.requests[1].resolve({code: 0, data: {s3: ui.requests[1].data.s3}});+ assert.equal(ui.sync.enabled, false);+ assert.equal(ui.enabled.checked, false);+ assert.equal(ui.sync.s3.secretKey, "");+ assert.equal(ui.closed(), 1);+});++test("read-only transitions do not re-enable writes after a pending save", async () => {+ const ui = setup();+ ui.click("save");+ ui.config.readonly = true;+ ui.requests[0].resolve({code: -1, msg: "Read only"});await settle();- assert.equal(ui.sync.s3.bucket, "another-bucket");+ assert.equal(ui.buttons.save.disabled, true);+ assert.equal(ui.buttons.clear.disabled, true);+ assert.equal(ui.buttons.cancel.disabled, false);+ ui.click("save");+ ui.click("clear");+ assert.equal(ui.requests.length, 1);+ assert.equal(ui.confirmations.length, 0);+});++test("draft stays bound to the opened provider even if another window changes the provider", () => {+ const ui = setup();+ ui.sync.provider = 3;+ ui.inputs.endpoint.value = "changed.example.com";+ ui.click("save");+ assert.equal(ui.requests[0].url, "/api/sync/setSyncProviderS3");+ assert.equal(ui.requests[0].data.s3.endpoint, "changed.example.com");+});++test("mobile uses the shared dialog and bucket warnings never submit the draft", () => {+ const ui = setup(2, true);+ assert.equal(ui.options().width, "92vw");+ ui.inputs.endpoint.value = "https://notes.s3.example.com";+ ui.input();+ assert.equal(ui.warningHidden(), false);+ ui.inputs.endpoint.value = "https://s3.example.com";+ ui.input();+ assert.equal(ui.warningHidden(), true);+ assert.equal(ui.requests.length, 0);});diff --git a/app/src/config/tabs/syncUi.ts b/app/src/config/tabs/syncUi.tsindex 51817a1576..717ad55051 100644--- a/app/src/config/tabs/syncUi.ts+++ b/app/src/config/tabs/syncUi.ts@@ -7,6 +7,9 @@ import {isInIOS, saveExportFile} from "../../protyle/util/compatibility";import {isPaidUser, needSubscribe} from "../../util/needSubscribe";import {getCloudURL} from "../util/about";import {getHostCapabilities, sanitizeKernelHTML} from "../../util/hostCapabilities";+import {Dialog} from "../../dialog";+import {escapeHtml} from "../../util/escape";+import {isMobile} from "../../util/functions";/** 按当前配置刷新同步 Tab 可见性与动态面板(供 syncRuntime 调用) */export const refreshSyncTabPanels = (root: Element) => {@@ -258,6 +261,8 @@ const buildProviderConfigKeywords = (): string[] => {window.siyuan.languages.cloudStoragePurge,window.siyuan.languages.import,window.siyuan.languages.export,+ window.siyuan.languages.syncConfig,+ window.siyuan.languages.clearSyncConfig,// 表单标签与选项(硬编码英文)"Endpoint","Access Key",@@ -289,8 +294,10 @@ const renderProviderConfig = (root: Element) => {if (!def.isProviderConfigAllowed()) {html = def.genUnpaidIntro();} else if (isThirdPartySyncProviderDef(def)) {- const warning = def.configKey === "s3" ? `<div data-type="s3-endpoint-warning" class="b3-label b3-label--inner ft__error fn__none" role="status">${window.siyuan.languages.s3EndpointBucketWarning}</div>` : "";- html = `${def.genIntro()}${def.fields.map(genProviderField).join("")}${warning}<div data-type="sync-config-unsaved" class="b3-label b3-label--inner ft__error fn__none" role="status">${window.siyuan.languages.syncConfigNotSaved}</div>${genProviderActionButtons(def.configKey)}`;+ html = `${def.genIntro()}<div class="b3-label b3-label--inner fn__flex">+ <div class="fn__flex-1">${window.siyuan.languages.syncConfig}<div class="b3-label__text ft__breakword">${escapeHtml(def.getConfig().endpoint || "-")}</div></div>+ <div class="fn__space"></div><button class="b3-button b3-button--outline fn__flex-center" data-action="configureSync"${window.siyuan.config.readonly ? " disabled" : ""}>${window.siyuan.languages.config}</button>+</div>${genProviderActionButtons(def.configKey)}`;} else {html = def.genIntro();}@@ -328,12 +335,12 @@ const genProviderFlexPassword = (label: string, id: string) => `<div class="b3-l</div><div id="sync-${id}-error" class="ft__error fn__none" role="status"></div></div></div>`;-const genProviderFlexSelect = (label: string, id: string, optionsHtml: string) => `<div class="b3-label b3-label--inner fn__flex">- <div class="fn__flex-center fn__size200">${label}</div>+const genProviderFlexSelect = (label: string, id: string, optionsHtml: string) => `<div class="b3-label b3-label--inner fn__flex config-sync-field">+ <label for="${id}" class="fn__flex-center fn__size200">${label}</label><div class="fn__space"></div>- <select class="b3-select fn__block" id="${id}">+ <div class="fn__flex-1"><select class="b3-select fn__block" id="${id}">${optionsHtml}- </select>+ </select></div></div>`;const genProviderActionButtons = (dataType: SyncProviderConfigKey) => {@@ -352,18 +359,7 @@ const genProviderActionButtons = (dataType: SyncProviderConfigKey) => {</div>`;};-const syncProviderConfigBoundElements = new WeakSet<Element>();-const syncProviderConfigSaves = new WeakMap<Element, Promise<void>>();-const bindProviderConfigEvent = (configElement: Element, root: Element) => {- const togglePasswordIcon = configElement.querySelector('[data-action="togglePassword"]');- togglePasswordIcon?.addEventListener("click", () => {- const useElement = togglePasswordIcon.firstElementChild;- const isEye = useElement.getAttribute("xlink:href") === "#iconEye";- useElement.setAttribute("xlink:href", isEye ? "#iconEyeoff" : "#iconEye");- (togglePasswordIcon.previousElementSibling as HTMLInputElement).setAttribute("type", isEye ? "text" : "password");- });-const importElement = configElement.querySelector("#importSyncConfig") as HTMLInputElement;importElement?.addEventListener("change", () => {if (!getHostCapabilities().importExport) {@@ -372,6 +368,9 @@ const bindProviderConfigEvent = (configElement: Element, root: Element) => {const formData = new ContractFormData({file: importElement.files[0]});const isS3 = importElement.getAttribute("data-type") === "s3";fetchPost(isS3 ? "/api/sync/importSyncProviderS3" : "/api/sync/importSyncProviderWebDAV", formData, (response: APICallbackResponse<APIPOSTRoutes["/api/sync/importSyncProviderS3" | "/api/sync/importSyncProviderWebDAV"]["response"]>) => {+ if (response.code !== 0 || !response.data) {+ return;+ }if ("s3" in response.data) {window.siyuan.config.sync.s3 = response.data.s3;} else {@@ -398,103 +397,196 @@ const bindProviderConfigEvent = (configElement: Element, root: Element) => {});});- const provider = window.siyuan.config.sync.provider;- const def = SYNC_PROVIDER_DEFS[provider];- if (!isThirdPartySyncProviderDef(def) || !def.isProviderConfigAllowed()) {- return;- }- fillSyncProviderConfigValues(configElement);- if (syncProviderConfigBoundElements.has(configElement)) {- return;- }- syncProviderConfigBoundElements.add(configElement);- configElement.addEventListener("input", () => {- updateS3EndpointWarning(configElement);- if (syncProviderValidationShown.has(configElement)) {- validateSyncProviderRequiredFields(configElement, def);- }- });- configElement.addEventListener("change", (event: Event) => {- const target = event.target as HTMLElement;- if (!target.matches(".b3-text-field, .b3-select")) {- return;- }- updateS3EndpointWarning(configElement);- saveSyncProviderConfigValues(configElement);+ configElement.querySelector('[data-action="configureSync"]')?.addEventListener("click", () => {+ openSyncProviderConfigDialog(root);});};-const syncProviderValidationShown = new WeakSet<Element>();+let syncProviderDialog: Dialog | undefined;-const validateSyncProviderRequiredFields = (configElement: Element, def: SyncThirdPartyProviderDef) => {+const validateSyncProviderFields = (configElement: Element, def: SyncThirdPartyProviderDef) => {let valid = true;- def.requiredFields.forEach(key => {+ def.fields.filter(field => field.type !== "select").forEach(field => {+ const key = field.id;const input = configElement.querySelector<HTMLInputElement>(`#${key}`);- const missing = !input.value.trim();- input.setAttribute("aria-invalid", String(missing));+ const missing = !input.value.trim() && (def.requiredFields.includes(key) || input.type === "number");+ const message = missing ? window.siyuan.languages._kernel[142] :+ input.type === "number" && !input.checkValidity() ? input.validationMessage : "";+ input.setAttribute("aria-invalid", String(!!message));const error = configElement.querySelector<HTMLElement>(`#sync-${key}-error`);- error.textContent = missing ? window.siyuan.languages._kernel[142] : "";- error.classList.toggle("fn__none", !missing);- valid &&= !missing;+ error.textContent = message;+ error.classList.toggle("fn__none", !message);+ valid &&= !message;});- configElement.querySelector('[data-type="sync-config-unsaved"]').classList.toggle("fn__none", valid);return valid;};-const saveSyncProviderConfigValues = (configElement: Element) => {- const provider = window.siyuan.config.sync.provider;- const def = SYNC_PROVIDER_DEFS[provider];- if (!isThirdPartySyncProviderDef(def)) {+const openSyncProviderConfigDialog = (root: Element) => {+ if (window.siyuan.config.readonly) {return;}- syncProviderValidationShown.add(configElement);- if (!validateSyncProviderRequiredFields(configElement, def)) {+ if (syncProviderDialog) {+ syncProviderDialog.element.querySelector<HTMLElement>(".b3-dialog__container").focus();return;}- const template = def.getConfig();- for (const key of ["timeout", "concurrentReqs"] as const) {- if (typeof template[key] !== "number") {- continue;+ const provider = window.siyuan.config.sync.provider;+ const def = SYNC_PROVIDER_DEFS[provider];+ if (!def || !isThirdPartySyncProviderDef(def) || !def.isProviderConfigAllowed()) {+ return;+ }+ const L = window.siyuan.languages;+ const warning = def.configKey === "s3" ? `<div data-type="s3-endpoint-warning" class="b3-label b3-label--inner ft__error fn__none" role="status">${L.s3EndpointBucketWarning}</div>` : "";+ const dialog = new Dialog({+ title: `${L.syncConfig} - ${def.configKey === "s3" ? "S3" : def.configKey === "webdav" ? "WebDAV" : L.localFileSystem}`,+ width: isMobile() ? "92vw" : "680px",+ containerClassName: "config-sync-dialog",+ content: `<div class="b3-dialog__content config-sync-form">${def.fields.map(genProviderField).join("")}${warning}+<div data-type="sync-config-error" class="ft__error fn__none" role="status"></div></div>+<div class="b3-dialog__action">+ <button class="b3-button b3-button--remove" data-action="clear">${L.clearSyncConfig}</button><div class="fn__flex-1"></div><div class="fn__space"></div>+ <button class="b3-button b3-button--cancel" data-action="cancel">${L.cancel}</button><div class="fn__space"></div>+ <button class="b3-button b3-button--text" data-action="save">${L.save}</button>+</div>`,+ destroyCallback: () => {+ if (syncProviderDialog === dialog) {+ syncProviderDialog = undefined;+ }+ },+ });+ syncProviderDialog = dialog;+ const configElement = dialog.element;+ const template = {...def.getConfig()};+ fillSyncProviderConfigValues(configElement, template);+ const fields = def.fields.map(field => configElement.querySelector<HTMLInputElement | HTMLSelectElement>(`#${field.id}`));+ const initialValues = fields.map(field => field.value);+ const destroy = dialog.destroy.bind(dialog);+ let pending = false;+ let confirming = false;+ let validationShown = false;+ const setPending = (value: boolean) => {+ pending = value;+ configElement.querySelectorAll<HTMLInputElement | HTMLSelectElement | HTMLButtonElement>("input, select, button").forEach(element => {+ element.disabled = value || (window.siyuan.config.readonly && element.getAttribute("data-action") !== "cancel");+ });+ configElement.setAttribute("aria-busy", String(value));+ };+ const setError = (message: string) => {+ const error = configElement.querySelector<HTMLElement>('[data-type="sync-config-error"]');+ error.textContent = message;+ error.classList.toggle("fn__none", !message);+ };+ dialog.destroy = () => {+ if (pending || confirming) {+ return;}- const input = configElement.querySelector<HTMLInputElement>(`#${key}`);- if (input && !input.value.trim()) {- showMessage(window.siyuan.languages._kernel[142]);- input.focus();+ if (fields.every((field, index) => field.value === initialValues[index])) {+ destroy();+ } else {+ confirming = true;+ confirmDialog(L.confirm, L.discardUnsavedChanges, () => destroy(), () => { confirming = false; });+ }+ };+ const refresh = () => {+ const currentRoot = root.isConnected ? root : document.querySelector("#syncProviderConfig")?.closest(".config__tab-container");+ if (currentRoot) {+ refreshSyncTabPanels(currentRoot);+ const enabled = currentRoot.querySelector<HTMLInputElement>('[id="sync.enabled"]');+ if (enabled) {+ enabled.checked = window.siyuan.config.sync.enabled;+ }+ }+ };+ const save = async () => {+ if (pending || confirming || window.siyuan.config.readonly) {return;}- }- const data = readProviderConfigFields(configElement, template);- const configKey = def.configKey;- // 记录提交时的控件和值,仅回填未被继续编辑的控件,失败时保留输入。- const fields = def.fields.map((field) => {- const element = configElement.querySelector<HTMLInputElement | HTMLSelectElement>(`#${field.id}`);- return {key: field.id, element, value: element.value};- });- // 同一表单的保存按编辑顺序执行,防止较早的响应覆盖后续配置。- const saving = (syncProviderConfigSaves.get(configElement) || Promise.resolve())- .then(() => fetchSyncPost(def.api, {[configKey]: data}))- .then((response) => {- if (response.code === 0 && response.data?.[configKey]) {- window.siyuan.config.sync[configKey] = response.data[configKey];- fields.forEach(({key, element, value}) => {- if (element.value === value) {- element.value = String(response.data[configKey][key]);- }- });- updateS3EndpointWarning(configElement);+ validationShown = true;+ if (!validateSyncProviderFields(configElement, def)) {+ setError(L.syncConfigNotSaved);+ configElement.querySelector<HTMLElement>('[aria-invalid="true"]')?.focus();+ return;+ }+ setPending(true);+ setError("");+ try {+ const response = await fetchSyncPost(def.api, {[def.configKey]: readProviderConfigFields(configElement, template)});+ if (response.code !== 0 || !response.data?.[def.configKey]) {+ setError(response.msg || L.syncConfigSaveFailed);+ return;+ }+ window.siyuan.config.sync[def.configKey] = response.data[def.configKey];+ refresh();+ destroy();+ } catch {+ setError(L.syncConfigSaveFailed);+ } finally {+ setPending(false);+ }+ };+ configElement.querySelector('[data-action="save"]').addEventListener("click", () => { void save(); });+ configElement.querySelector('[data-action="cancel"]').addEventListener("click", () => dialog.destroy());+ configElement.querySelector('[data-action="clear"]').addEventListener("click", () => {+ if (pending || confirming || window.siyuan.config.readonly) {+ return;+ }+ confirming = true;+ confirmDialog(L.clearSyncConfig, L.clearSyncConfigConfirm, () => {+ confirming = false;+ if (window.siyuan.config.readonly) {+ return;}- })- .catch(() => {});- syncProviderConfigSaves.set(configElement, saving);+ setPending(true);+ setError("");+ void fetchSyncPost("/api/sync/clearSyncProviderConfig", {provider}).then(response => {+ if (response.code !== 0) {+ setError(response.msg || L.syncConfigSaveFailed);+ return;+ }+ if (response.data.s3) {+ window.siyuan.config.sync.s3 = response.data.s3;+ }+ if (response.data.webdav) {+ window.siyuan.config.sync.webdav = response.data.webdav;+ }+ if (response.data.local) {+ window.siyuan.config.sync.local = response.data.local;+ }+ window.siyuan.config.sync.enabled = response.data.enabled;+ refresh();+ destroy();+ }).catch(() => setError(L.syncConfigSaveFailed)).finally(() => setPending(false));+ }, () => { confirming = false; }, true, undefined, L.clearSyncConfig);+ });+ configElement.addEventListener("input", () => {+ updateS3EndpointWarning(configElement);+ if (validationShown) {+ validateSyncProviderFields(configElement, def);+ }+ });+ configElement.addEventListener("keydown", (event: KeyboardEvent) => {+ if (event.isComposing || event.repeat) {+ return;+ }+ if (event.key === "Escape") {+ event.preventDefault();+ event.stopPropagation();+ dialog.destroy();+ } else if (event.key === "Enter" && (event.target as HTMLElement).tagName === "INPUT") {+ event.preventDefault();+ event.stopPropagation();+ void save();+ }+ });+ configElement.querySelector('[data-action="togglePassword"]')?.addEventListener("click", () => {+ const input = configElement.querySelector<HTMLInputElement>('input[id="secretKey"], input[id="password"]');+ const icon = configElement.querySelector('[data-action="togglePassword"] use');+ input.type = input.type === "password" ? "text" : "password";+ icon.setAttribute("xlink:href", input.type === "password" ? "#iconEye" : "#iconEyeoff");+ });+ fields[0].focus();};-const fillSyncProviderConfigValues = (configElement: Element) => {- const provider = window.siyuan.config.sync.provider;- const def = SYNC_PROVIDER_DEFS[provider];- if (!isThirdPartySyncProviderDef(def)) {- return;- }- const data = def.getConfig();+const fillSyncProviderConfigValues = (configElement: Element, data: Config.ISync[SyncProviderConfigKey]) => {(Object.keys(data) as (keyof typeof data & string)[]).forEach((key) => {const el = configElement.querySelector(`#${key}`) as HTMLInputElement | HTMLSelectElement | null;if (el) {diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 765bf5b6ed..82aea2a26f 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -826,6 +826,10 @@ export type ChildBlock = { "content"?: string; "id": string; "markdown"?: stringexport type CleanupRichTextRequestInput = { "batch": string; "groups": Array<string>; };+export type ClearSyncProviderConfigData = { "enabled": boolean; "local"?: SyncLocal; "s3"?: SyncS3; "webdav"?: SyncWebDAV; };++export type ClearSyncProviderConfigRequestInput = { "provider": number; };+export type ClipboardFile = { "isDir": boolean; "name": string; "path": string; "size": number; "updated": number; };export type ClipboardPathRequestInput = { "path": string; };@@ -7000,6 +7004,18 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated"];};+ /**+ * 清除 provider 为 2(S3)、3(WebDAV)或 4(本地文件系统)的配置并同步落盘。+ * 清除当前服务时先验证资源及历史快照完整性,再关闭同步;失败时保留原配置,不删除本地或云端数据。+ * 响应包含当前同步开关及被清除服务的默认配置;其他服务配置、仓库密钥和下载模式保持不变。+ */+ "/api/sync/clearSyncProviderConfig": {+ request: ClearSyncProviderConfigRequestInput;+ response: { "code": 0; "data": ClearSyncProviderConfigData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };+ body: "json";+ /** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */+ authorization?: readonly ["authenticated","admin","writable"];+ };"/api/sync/createCloudSyncDir": {request: SyncNameRequestInput;response: { "code": 0; "data": null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };diff --git a/kernel/api/contract_sync_clear_test.go b/kernel/api/contract_sync_clear_test.gonew file mode 100644index 0000000000..7eea40308b--- /dev/null+++ b/kernel/api/contract_sync_clear_test.go@@ -0,0 +1,48 @@+package api++import (+ "encoding/json"+ "net/http/httptest"+ "path/filepath"+ "strings"+ "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/util"+)++func TestAPIContractSyncClearConfiguration(t *testing.T) {+ syncTestConfiguration(t)+ previousDir, previousRepo, previousData := util.ConfDir, util.RepoDir, util.DataDir+ t.Cleanup(func() { util.ConfDir, util.RepoDir, util.DataDir = previousDir, previousRepo, previousData })+ util.ConfDir = t.TempDir()+ util.RepoDir, util.DataDir = filepath.Join(util.ConfDir, "repo"), filepath.Join(util.ConfDir, "data")+ util.ReadOnly = false+ engine := gin.New()+ const path = "/api/sync/clearSyncProviderConfig"+ engine.POST(path, clearSyncProviderConfig)+ for _, body := range []string{`{}`, `{"provider":null}`, `{"provider":"2"}`, `{"provider":2.5}`, `{"provider":0}`, `{"provider":5}`, `{"provider":2}`} {+ model.Conf.Sync.Provider, model.Conf.Sync.Enabled = conf.ProviderS3, true+ model.Conf.Sync.S3 = &conf.S3{Endpoint: "https://s3.example", SecretKey: "secret"}+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", path, strings.NewReader(body)))+ requireAPIContract(t, "POST", path, recorder)+ var response struct {+ Code int `json:"code"`+ Data *apicontract.ClearSyncProviderConfigData `json:"data"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ if body == `{"provider":2}` {+ if response.Code != 0 || response.Data == nil || response.Data.Enabled || response.Data.S3 == nil || response.Data.S3.SecretKey != "" {+ t.Fatalf("clear response: %s", recorder.Body.String())+ }+ } else if response.Code == 0 || model.Conf.Sync.S3.SecretKey != "secret" || !model.Conf.Sync.Enabled {+ t.Fatalf("invalid clear changed configuration: %s", recorder.Body.String())+ }+ }+}diff --git a/kernel/api/contract_sync_test.go b/kernel/api/contract_sync_test.goindex 55c141e276..5d336ada59 100644--- a/kernel/api/contract_sync_test.go+++ b/kernel/api/contract_sync_test.go@@ -171,8 +171,9 @@ func TestAPIContractSyncBootRole(t *testing.T) {func TestAPIContractSyncPermissionBeforeBody(t *testing.T) {syncTestConfiguration(t)for path, handler := range map[string]gin.HandlerFunc{- "/api/sync/setSyncProviderS3": setSyncProviderS3,- "/api/sync/setSyncProvider": setSyncProvider,+ "/api/sync/setSyncProviderS3": setSyncProviderS3,+ "/api/sync/clearSyncProviderConfig": clearSyncProviderConfig,+ "/api/sync/setSyncProvider": setSyncProvider,} {for _, role := range []model.Role{model.RoleAdministrator, model.RoleReader} {engine := gin.New()diff --git a/kernel/api/router.go b/kernel/api/router.goindex dc50b70d13..923d501763 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -561,6 +561,7 @@ func registerSyncRoutes(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/sync/setSyncProviderS3", contractRouteHandlers(apicontract.SetSyncProviderS3, setSyncProviderS3)...)ginServer.Handle("POST", "/api/sync/setSyncProviderWebDAV", contractRouteHandlers(apicontract.SetSyncProviderWebDAV, setSyncProviderWebDAV)...)ginServer.Handle("POST", "/api/sync/setSyncProviderLocal", contractRouteHandlers(apicontract.SetSyncProviderLocal, setSyncProviderLocal)...)+ ginServer.Handle("POST", "/api/sync/clearSyncProviderConfig", contractRouteHandlers(apicontract.ClearSyncProviderConfig, clearSyncProviderConfig)...)ginServer.Handle("POST", "/api/sync/setCloudSyncDir", contractRouteHandlers(apicontract.SetCloudSyncDir, setCloudSyncDir)...)ginServer.Handle("POST", "/api/sync/setSyncAssetDownloadMode", contractRouteHandlers(apicontract.SetSyncAssetDownloadMode, setSyncAssetDownloadMode)...)ginServer.Handle("POST", "/api/sync/createCloudSyncDir", contractRouteHandlers(apicontract.CreateCloudSyncDir, createCloudSyncDir)...)diff --git a/kernel/api/sync.go b/kernel/api/sync.goindex 0377f9af23..3fad5cd41a 100644--- a/kernel/api/sync.go+++ b/kernel/api/sync.go@@ -602,6 +602,22 @@ func setSyncProviderContract(c *gin.Context, request apicontract.SyncProviderReqvar setSyncProviderS3 = contractHandler(apicontract.SetSyncProviderS3, setSyncProviderS3Contract)+var clearSyncProviderConfig = contractHandler(apicontract.ClearSyncProviderConfig, func(c *gin.Context, request apicontract.ClearSyncProviderConfigRequest) apicontract.Response[apicontract.ClearSyncProviderConfigData] {+ if err := model.ClearSyncProviderConfig(request.Provider); err != nil {+ return apicontract.Failure[apicontract.ClearSyncProviderConfigData](-1, err.Error())+ }+ data := apicontract.ClearSyncProviderConfigData{Enabled: model.Conf.Sync.Enabled}+ switch request.Provider {+ case conf.ProviderS3:+ data.S3 = (*apicontract.SyncS3)(model.Conf.Sync.S3)+ case conf.ProviderWebDAV:+ data.WebDAV = (*apicontract.SyncWebDAV)(model.Conf.Sync.WebDAV)+ case conf.ProviderLocal:+ data.Local = (*apicontract.SyncLocal)(model.Conf.Sync.Local)+ }+ return apicontract.Success(data)+})+func setSyncProviderS3Contract(c *gin.Context, request apicontract.SetSyncS3Request) (ret apicontract.Response[apicontract.SyncS3Data]) {if err := request.ConfigError(); err != nil {diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex c6b7de9370..fdf7d76a97 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -831,6 +831,12 @@ var SetSyncProvider = define[SyncProviderRequest, Null]("setSyncProvider", "/apivar SetSyncProviderS3 = define[SetSyncS3Request, SyncS3Data]("setSyncProviderS3", "/api/sync/setSyncProviderS3", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var SetSyncProviderWebDAV = define[SetSyncWebDAVRequest, SyncWebDAVData]("setSyncProviderWebDAV", "/api/sync/setSyncProviderWebDAV", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var SetSyncProviderLocal = define[SetSyncLocalRequest, SyncLocalData]("setSyncProviderLocal", "/api/sync/setSyncProviderLocal", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")++// ClearSyncProviderConfig 清除 provider 为 2(S3)、3(WebDAV)或 4(本地文件系统)的配置并同步落盘。+// 清除当前服务时先验证资源及历史快照完整性,再关闭同步;失败时保留原配置,不删除本地或云端数据。+// 响应包含当前同步开关及被清除服务的默认配置;其他服务配置、仓库密钥和下载模式保持不变。+var ClearSyncProviderConfig = define[ClearSyncProviderConfigRequest, ClearSyncProviderConfigData]("clearSyncProviderConfig", "/api/sync/clearSyncProviderConfig", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")+var SetCloudSyncDir = define[SyncNameRequest, Null]("setCloudSyncDir", "/api/sync/setCloudSyncDir", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var SetSyncAssetDownloadMode = define[SyncModeRequest, SyncAssetDownloadModeData]("setSyncAssetDownloadMode", "/api/sync/setSyncAssetDownloadMode", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var CreateCloudSyncDir = define[SyncNameRequest, Null]("createCloudSyncDir", "/api/sync/createCloudSyncDir", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex e9e06b0f3a..52e6d9d704 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -20689,6 +20689,39 @@],"additionalProperties": false},+ "ClearSyncProviderConfigData": {+ "type": "object",+ "properties": {+ "enabled": {+ "type": "boolean"+ },+ "local": {+ "$ref": "#/$defs/SyncLocal"+ },+ "s3": {+ "$ref": "#/$defs/SyncS3"+ },+ "webdav": {+ "$ref": "#/$defs/SyncWebDAV"+ }+ },+ "required": [+ "enabled"+ ],+ "additionalProperties": false+ },+ "ClearSyncProviderConfigRequestInput": {+ "type": "object",+ "properties": {+ "provider": {+ "type": "integer"+ }+ },+ "required": [+ "provider"+ ],+ "additionalProperties": false+ },"ClipboardFile": {"type": "object","properties": {@@ -164854,6 +164887,86 @@]}},+ {+ "method": "POST",+ "path": "/api/sync/clearSyncProviderConfig",+ "handler": "clearSyncProviderConfig",+ "authorization": [+ "authenticated",+ "admin",+ "writable"+ ],+ "body": "json",+ "request": {+ "$ref": "#/$defs/ClearSyncProviderConfigRequestInput"+ },+ "response": {+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer",+ "enum": [+ 0+ ]+ },+ "data": {+ "$ref": "#/$defs/ClearSyncProviderConfigData"+ },+ "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/sync/createCloudSyncDir",diff --git a/kernel/apicontract/sync.go b/kernel/apicontract/sync.goindex 2debb0162a..7fa8f89a51 100644--- a/kernel/apicontract/sync.go+++ b/kernel/apicontract/sync.go@@ -23,6 +23,17 @@ type SyncProviderRequest struct {// 显式确认后补齐原来源的资源和历史快照,缺省时只检查完整性。CompleteAssets bool `json:"completeAssets" api:"optional,nullable"`}++type ClearSyncProviderConfigRequest struct {+ Provider int `json:"provider"`+}++type ClearSyncProviderConfigData struct {+ Enabled bool `json:"enabled"`+ S3 *SyncS3 `json:"s3,omitempty"`+ WebDAV *SyncWebDAV `json:"webdav,omitempty"`+ Local *SyncLocal `json:"local,omitempty"`+}type SyncNameRequest struct {Name string `json:"name" api:"trim"`}diff --git a/kernel/model/asset_download_test.go b/kernel/model/asset_download_test.goindex f22ae88685..c34d49543b 100644--- a/kernel/model/asset_download_test.go+++ b/kernel/model/asset_download_test.go@@ -100,6 +100,9 @@ func TestAssetDownloadModePreservesHistoricalRecovery(t *testing.T) {if err = requireCompleteAssetDownloads(); err == nil {t.Fatal("source change allowed with missing current content")}+ if err = ClearSyncProviderConfig(conf.ProviderLocal); err == nil || !Conf.Sync.Enabled || Conf.Sync.Local.Endpoint == "" {+ t.Fatal("clear discarded the source of missing current assets")+ }assetPath := filepath.Join(fullData, "assets", "file.bin")if err = os.WriteFile(assetPath, []byte("version two is different"), 0644); err != nil {t.Fatal(err)@@ -127,6 +130,9 @@ func TestAssetDownloadModePreservesHistoricalRecovery(t *testing.T) {if err = requireCompleteAssetDownloads(); err == nil {t.Fatal("source change allowed with missing historical content")}+ if err = ClearSyncProviderConfig(conf.ProviderLocal); err == nil || !Conf.Sync.Enabled || Conf.Sync.Local.Endpoint == "" {+ t.Fatal("clear discarded the source of missing historical assets")+ }Conf.Sync.Enabled = falseif err = SetSyncAssetDownloadMode(0); err == nil || Conf.Sync.AssetDownloadMode != 1 {t.Fatalf("offline mode switch discarded the previous mode: %v", err)@@ -151,9 +157,12 @@ func TestAssetDownloadModePreservesHistoricalRecovery(t *testing.T) {if data, err = os.ReadFile(localAsset); err != nil || !bytes.Equal(data, []byte("version two is different")) {t.Fatalf("historical read overwrote current asset: %q, %v", data, err)}- if err = clearAssetDownloadState(); err != nil {+ if err = ClearSyncProviderConfig(conf.ProviderLocal); err != nil {t.Fatal(err)}+ if Conf.Sync.Enabled || Conf.Sync.Local.Endpoint != "" {+ t.Fatal("complete source was not cleared and disabled")+ }if exists, err := assetDownloadStateExists(); err != nil || exists {t.Fatalf("authenticated complete state was not cleared: %v", err)}diff --git a/kernel/model/sync_config_clear.go b/kernel/model/sync_config_clear.gonew file mode 100644index 0000000000..1e831abf69--- /dev/null+++ b/kernel/model/sync_config_clear.go@@ -0,0 +1,65 @@+package model++import (+ "errors"+ "path/filepath"++ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// ClearSyncProviderConfig 清除指定第三方配置;当前来源必须完整,清除后关闭同步。+func ClearSyncProviderConfig(provider int) error {+ if util.ReadOnly {+ return errors.New(Conf.Language(34))+ }+ if provider != conf.ProviderS3 && provider != conf.ProviderWebDAV && provider != conf.ProviderLocal {+ return errors.New("invalid sync provider")+ }+ release := lockAssetSourceChange()+ defer release()+ if provider == Conf.Sync.Provider {+ if err := requireCompleteAssetDownloads(); err != nil {+ return err+ }+ if err := clearAssetDownloadState(); err != nil {+ return err+ }+ }+ if err := persistClearedSyncProviderConfig(provider); err != nil {+ return err+ }+ refreshLANSyncManager()+ return nil+}++// persistClearedSyncProviderConfig 先持久化副本,写入失败时保留生效配置。+func persistClearedSyncProviderConfig(provider int) error {+ Conf.m.Lock()+ defer Conf.m.Unlock()+ next := *Conf+ syncConfig := *Conf.Sync+ next.Sync = &syncConfig+ if provider == syncConfig.Provider {+ syncConfig.Enabled = false+ }+ timeout := util.NormalizeTimeout(0)+ concurrentReqs := util.NormalizeConcurrentReqs(0, provider)+ switch provider {+ case conf.ProviderS3:+ syncConfig.S3 = &conf.S3{PathStyle: true, SkipTlsVerify: true, Timeout: timeout, ConcurrentReqs: concurrentReqs}+ case conf.ProviderWebDAV:+ syncConfig.WebDAV = &conf.WebDAV{SkipTlsVerify: true, Timeout: timeout, ConcurrentReqs: concurrentReqs}+ case conf.ProviderLocal:+ syncConfig.Local = &conf.Local{Timeout: timeout, ConcurrentReqs: concurrentReqs}+ }+ data, err := next.marshalForSave()+ if err != nil {+ return err+ }+ if err = atomicWriteFile(filepath.Join(util.ConfDir, "conf.json"), data); err != nil {+ return err+ }+ Conf.Sync = &syncConfig+ return nil+}diff --git a/kernel/model/sync_config_clear_test.go b/kernel/model/sync_config_clear_test.gonew file mode 100644index 0000000000..983c9d36af--- /dev/null+++ b/kernel/model/sync_config_clear_test.go@@ -0,0 +1,109 @@+package model++import (+ "encoding/json"+ "os"+ "path/filepath"+ "reflect"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func prepareSyncConfigClearTest(t *testing.T) {+ t.Helper()+ previous, readOnly := Conf, util.ReadOnly+ confDir, dataDir, repoDir := util.ConfDir, util.DataDir, util.RepoDir+ t.Cleanup(func() {+ Conf, util.ReadOnly = previous, readOnly+ util.ConfDir, util.DataDir, util.RepoDir = confDir, dataDir, repoDir+ })+ root := t.TempDir()+ util.ConfDir, util.DataDir, util.RepoDir = root, filepath.Join(root, "data"), filepath.Join(root, "repo")+ util.ReadOnly = false+ Conf = NewAppConf()+ Conf.Sync, Conf.Repo = conf.NewSync(), conf.NewRepo()+ Conf.Sync.S3 = &conf.S3{Endpoint: "https://s3.example", AccessKey: "access", SecretKey: "secret", Bucket: "notes", Region: "auto"}+ Conf.Sync.WebDAV = &conf.WebDAV{Endpoint: "https://dav.example", Username: "name", Password: "password"}+ Conf.Sync.Local = &conf.Local{Endpoint: filepath.Join(root, "cloud")}+ Conf.Repo.Key = []byte("0123456789abcdef0123456789abcdef")+ Conf.Sync.Enabled = true+ Conf.Sync.AssetDownloadMode = 1+ Conf.Save()+}++func TestClearSyncProviderConfiguration(t *testing.T) {+ for _, provider := range []int{conf.ProviderS3, conf.ProviderWebDAV, conf.ProviderLocal} {+ for _, active := range []bool{true, false} {+ t.Run(conf.ProviderToStr(provider)+"/active="+map[bool]string{true: "true", false: "false"}[active], func(t *testing.T) {+ prepareSyncConfigClearTest(t)+ if active {+ Conf.Sync.Provider = provider+ }+ old := *Conf.Sync+ key := append([]byte(nil), Conf.Repo.Key...)+ if err := ClearSyncProviderConfig(provider); err != nil {+ t.Fatal(err)+ }+ if Conf.Sync.Enabled == active || Conf.Sync.Provider != old.Provider || Conf.Sync.AssetDownloadMode != 1 || !reflect.DeepEqual(Conf.Repo.Key, key) {+ t.Fatal("clear changed unrelated preferences or failed to disable the current service")+ }+ if provider == conf.ProviderS3 {+ if Conf.Sync.S3.Endpoint != "" || Conf.Sync.S3.AccessKey != "" || Conf.Sync.S3.SecretKey != "" || Conf.Sync.S3.Bucket != "" || Conf.Sync.S3.Region != "" || Conf.Sync.S3.Timeout < 7 {+ t.Fatal("S3 configuration was not cleared")+ }+ } else if Conf.Sync.S3 != old.S3 {+ t.Fatal("unrelated S3 configuration changed")+ }+ if provider == conf.ProviderWebDAV {+ if Conf.Sync.WebDAV.Endpoint != "" || Conf.Sync.WebDAV.Username != "" || Conf.Sync.WebDAV.Password != "" || Conf.Sync.WebDAV.Timeout < 7 {+ t.Fatal("WebDAV configuration was not cleared")+ }+ } else if Conf.Sync.WebDAV != old.WebDAV {+ t.Fatal("unrelated WebDAV configuration changed")+ }+ if provider == conf.ProviderLocal {+ if Conf.Sync.Local.Endpoint != "" || Conf.Sync.Local.Timeout < 7 {+ t.Fatal("local configuration was not cleared")+ }+ } else if Conf.Sync.Local != old.Local {+ t.Fatal("unrelated local configuration changed")+ }+ data, err := os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))+ if err != nil {+ t.Fatal(err)+ }+ var saved AppConf+ if err = json.Unmarshal(data, &saved); err != nil || !reflect.DeepEqual(saved.Sync, Conf.Sync) {+ t.Fatalf("cleared configuration was not persisted: %v", err)+ }+ })+ }+ }+}++func TestClearSyncProviderConfigurationFailure(t *testing.T) {+ prepareSyncConfigClearTest(t)+ Conf.Sync.Provider = conf.ProviderS3+ previous := Conf.Sync+ for _, provider := range []int{-1, 0, 1, 5} {+ if err := ClearSyncProviderConfig(provider); err == nil || Conf.Sync != previous {+ t.Fatal("invalid provider changed configuration")+ }+ }+ util.ReadOnly = true+ if err := ClearSyncProviderConfig(conf.ProviderS3); err == nil || Conf.Sync != previous {+ t.Fatal("readonly clear changed configuration")+ }+ util.ReadOnly = false+ if err := os.Remove(filepath.Join(util.ConfDir, "conf.json")); err != nil {+ t.Fatal(err)+ }+ if err := os.Mkdir(filepath.Join(util.ConfDir, "conf.json"), 0755); err != nil {+ t.Fatal(err)+ }+ if err := ClearSyncProviderConfig(conf.ProviderS3); err == nil || Conf.Sync != previous || !Conf.Sync.Enabled {+ t.Fatal("failed persistence discarded the active configuration")+ }+}