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: Support managing remote connections via GUI https://github.com/siyuan-note/siyuan/issues/19204
Daniel96169e979812
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex ae908942ed..21e049bd39 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "الاتصال بنواة بعيدة...",+ "remoteConnection": "بعيد",+ "localConnection": "محلي",+ "switchConnectionRestartTip": "يؤدي تبديل الاتصال إلى حفظ مساحات العمل الحالية وإغلاقها ثم إعادة تشغيل عميل سطح المكتب؛ وتستمر النوى البعيدة في العمل",+ "remoteKernelAddressTip": "أدخل عنوان HTTPS دون مسار أو استعلام أو بيانات اعتماد مضمنة",+ "checkingRemoteKernel": "جارٍ التحقق من الاتصال...",+ "remoteKernelVersionMismatch": "يجب أن يتطابق إصدار النواة البعيدة مع إصدار العميل",+ "remoteKernelConnectionFailed": "تعذر الاتصال؛ تحقق من العنوان والشبكة وشهادة TLS",+ "backToLocalWorkspace": "العودة إلى مساحة العمل المحلية",+ "invalidLocalWorkspace": "حدد مجلد مساحة عمل محلية موجودة","tableCellRichEnable": "تحويل إلى نص منسق","tableCellRichEdit": "تحرير النص المنسق","tableCellRichDisable": "تحويل إلى محتوى ضمن السطر",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex e0d7755996..611ead6de0 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "Mit entferntem Kernel verbinden...",+ "remoteConnection": "Remote",+ "localConnection": "Lokal",+ "switchConnectionRestartTip": "Beim Wechsel werden die aktuellen Arbeitsbereiche gespeichert und geschlossen und der Desktop-Client neu gestartet; entfernte Kernel laufen weiter",+ "remoteKernelAddressTip": "HTTPS-Adresse ohne Pfad, Abfrageparameter oder eingebettete Zugangsdaten eingeben",+ "checkingRemoteKernel": "Verbindung wird geprüft...",+ "remoteKernelVersionMismatch": "Die Version des entfernten Kernels muss mit der Client-Version übereinstimmen",+ "remoteKernelConnectionFailed": "Verbindung fehlgeschlagen; Adresse, Netzwerk und TLS-Zertifikat prüfen",+ "backToLocalWorkspace": "Zum lokalen Arbeitsbereich zurückkehren",+ "invalidLocalWorkspace": "Wählen Sie einen vorhandenen lokalen Arbeitsbereichsordner","tableCellRichEnable": "In Rich Text umwandeln","tableCellRichEdit": "Rich Text bearbeiten","tableCellRichDisable": "In Inline-Inhalt umwandeln",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 4693fb1fea..9665c7c89a 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "Connect to remote kernel...",+ "remoteConnection": "Remote",+ "localConnection": "Local",+ "switchConnectionRestartTip": "Switching saves and closes current workspaces, then restarts the desktop client; remote kernels keep running",+ "remoteKernelAddressTip": "Enter an HTTPS origin without a path, query, or embedded credentials",+ "checkingRemoteKernel": "Checking connection...",+ "remoteKernelVersionMismatch": "The remote kernel version must match the client",+ "remoteKernelConnectionFailed": "Unable to connect; check the address, network, and TLS certificate",+ "backToLocalWorkspace": "Return to local workspace",+ "invalidLocalWorkspace": "Select an existing local workspace directory","tableCellRichEnable": "Convert to rich text","tableCellRichEdit": "Edit rich text","tableCellRichDisable": "Convert to inline content",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 5e99f7b0e8..eaa47d0ebc 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "Conectar a un núcleo remoto...",+ "remoteConnection": "Remoto",+ "localConnection": "Local",+ "switchConnectionRestartTip": "Al cambiar de conexión se guardan y cierran los espacios de trabajo actuales y se reinicia el cliente de escritorio; los núcleos remotos siguen funcionando",+ "remoteKernelAddressTip": "Introduce una dirección HTTPS sin ruta, parámetros de consulta ni credenciales incorporadas",+ "checkingRemoteKernel": "Comprobando conexión...",+ "remoteKernelVersionMismatch": "La versión del núcleo remoto debe coincidir con la del cliente",+ "remoteKernelConnectionFailed": "No se puede conectar; comprueba la dirección, la red y el certificado TLS",+ "backToLocalWorkspace": "Volver al espacio de trabajo local",+ "invalidLocalWorkspace": "Selecciona una carpeta de espacio de trabajo local existente","tableCellRichEnable": "Convertir a texto enriquecido","tableCellRichEdit": "Editar texto enriquecido","tableCellRichDisable": "Convertir a contenido en línea",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex ee4d25853a..536616bf50 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "Se connecter à un noyau distant...",+ "remoteConnection": "Distant",+ "localConnection": "Local",+ "switchConnectionRestartTip": "Le changement de connexion enregistre et ferme les espaces de travail actuels, puis redémarre le client de bureau ; les noyaux distants restent actifs",+ "remoteKernelAddressTip": "Saisissez une adresse HTTPS sans chemin, paramètres de requête ni identifiants intégrés",+ "checkingRemoteKernel": "Vérification de la connexion...",+ "remoteKernelVersionMismatch": "La version du noyau distant doit correspondre à celle du client",+ "remoteKernelConnectionFailed": "Connexion impossible ; vérifiez l’adresse, le réseau et le certificat TLS",+ "backToLocalWorkspace": "Revenir à l’espace de travail local",+ "invalidLocalWorkspace": "Sélectionnez le dossier d’un espace de travail local existant","tableCellRichEnable": "Convertir en texte enrichi","tableCellRichEdit": "Modifier le texte enrichi","tableCellRichDisable": "Convertir en contenu en ligne",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex fad1e4a1d1..77638e1b85 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "התחברות לליבה מרוחקת...",+ "remoteConnection": "מרוחק",+ "localConnection": "מקומי",+ "switchConnectionRestartTip": "החלפת החיבור שומרת וסוגרת את סביבות העבודה הנוכחיות ומפעילה מחדש את יישום שולחן העבודה; הליבות המרוחקות ממשיכות לפעול",+ "remoteKernelAddressTip": "יש להזין כתובת HTTPS ללא נתיב, שאילתה או פרטי הזדהות מוטמעים",+ "checkingRemoteKernel": "בודק חיבור...",+ "remoteKernelVersionMismatch": "גרסת הליבה המרוחקת חייבת להתאים לגרסת הלקוח",+ "remoteKernelConnectionFailed": "לא ניתן להתחבר; יש לבדוק את הכתובת, הרשת ותעודת TLS",+ "backToLocalWorkspace": "חזרה לסביבת עבודה מקומית",+ "invalidLocalWorkspace": "יש לבחור תיקייה קיימת של סביבת עבודה מקומית","tableCellRichEnable": "המרה לטקסט עשיר","tableCellRichEdit": "עריכת טקסט עשיר","tableCellRichDisable": "המרה לתוכן בתוך השורה",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex a9cbb3bd2a..a6288b8d0a 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "दूरस्थ कर्नेल से कनेक्ट करें...",+ "remoteConnection": "दूरस्थ",+ "localConnection": "स्थानीय",+ "switchConnectionRestartTip": "कनेक्शन बदलने पर मौजूदा कार्यस्थान सहेजकर बंद किए जाते हैं और डेस्कटॉप क्लाइंट फिर से शुरू होता है; दूरस्थ कर्नेल चलते रहते हैं",+ "remoteKernelAddressTip": "पथ, क्वेरी या अंतर्निहित क्रेडेंशियल के बिना HTTPS पता दर्ज करें",+ "checkingRemoteKernel": "कनेक्शन जाँचा जा रहा है...",+ "remoteKernelVersionMismatch": "दूरस्थ कर्नेल का संस्करण क्लाइंट से मेल खाना चाहिए",+ "remoteKernelConnectionFailed": "कनेक्ट नहीं हो सका; पता, नेटवर्क और TLS प्रमाणपत्र जाँचें",+ "backToLocalWorkspace": "स्थानीय कार्यस्थान पर लौटें",+ "invalidLocalWorkspace": "मौजूदा स्थानीय कार्यस्थान की निर्देशिका चुनें","tableCellRichEnable": "रिच टेक्स्ट में बदलें","tableCellRichEdit": "रिच टेक्स्ट संपादित करें","tableCellRichDisable": "इनलाइन सामग्री में बदलें",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex d04c275e18..71385167b0 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "Hubungkan ke kernel jarak jauh...",+ "remoteConnection": "Jarak jauh",+ "localConnection": "Lokal",+ "switchConnectionRestartTip": "Pergantian koneksi menyimpan dan menutup ruang kerja saat ini, lalu memulai ulang klien desktop; kernel jarak jauh tetap berjalan",+ "remoteKernelAddressTip": "Masukkan alamat HTTPS tanpa jalur, kueri, atau kredensial tertanam",+ "checkingRemoteKernel": "Memeriksa koneksi...",+ "remoteKernelVersionMismatch": "Versi kernel jarak jauh harus sama dengan klien",+ "remoteKernelConnectionFailed": "Tidak dapat terhubung; periksa alamat, jaringan, dan sertifikat TLS",+ "backToLocalWorkspace": "Kembali ke ruang kerja lokal",+ "invalidLocalWorkspace": "Pilih direktori ruang kerja lokal yang sudah ada","tableCellRichEnable": "Ubah menjadi teks kaya","tableCellRichEdit": "Edit teks kaya","tableCellRichDisable": "Ubah menjadi konten sebaris",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex e3919c8c2c..0bd3740dfa 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "Connetti a un kernel remoto...",+ "remoteConnection": "Remoto",+ "localConnection": "Locale",+ "switchConnectionRestartTip": "Il cambio di connessione salva e chiude gli spazi di lavoro attuali, poi riavvia il client desktop; i kernel remoti restano in esecuzione",+ "remoteKernelAddressTip": "Inserisci un indirizzo HTTPS senza percorso, query o credenziali incorporate",+ "checkingRemoteKernel": "Verifica della connessione...",+ "remoteKernelVersionMismatch": "La versione del kernel remoto deve corrispondere a quella del client",+ "remoteKernelConnectionFailed": "Connessione impossibile; controlla indirizzo, rete e certificato TLS",+ "backToLocalWorkspace": "Torna allo spazio di lavoro locale",+ "invalidLocalWorkspace": "Seleziona una cartella di spazio di lavoro locale esistente","tableCellRichEnable": "Converti in testo formattato","tableCellRichEdit": "Modifica testo formattato","tableCellRichDisable": "Converti in contenuto in linea",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex 1a32532cd9..ca788c973d 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "リモートカーネルに接続...",+ "remoteConnection": "リモート",+ "localConnection": "ローカル",+ "switchConnectionRestartTip": "接続を切り替えると現在のワークスペースを保存して閉じ、デスクトップクライアントを再起動します。リモートカーネルは動作を継続します",+ "remoteKernelAddressTip": "パス、クエリ、認証情報を含まない HTTPS アドレスを入力してください",+ "checkingRemoteKernel": "接続を確認中...",+ "remoteKernelVersionMismatch": "リモートカーネルとクライアントのバージョンを一致させてください",+ "remoteKernelConnectionFailed": "接続できません。アドレス、ネットワーク、TLS 証明書を確認してください",+ "backToLocalWorkspace": "ローカルワークスペースに戻る",+ "invalidLocalWorkspace": "既存のローカルワークスペースのフォルダーを選択してください","tableCellRichEnable": "リッチテキストに変換","tableCellRichEdit": "リッチテキストを編集","tableCellRichDisable": "インラインコンテンツに変換",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 1a14762fe1..d1a0d5f574 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "원격 커널에 연결...",+ "remoteConnection": "원격",+ "localConnection": "로컬",+ "switchConnectionRestartTip": "연결을 전환하면 현재 작업 공간을 저장하고 닫은 후 데스크톱 클라이언트를 다시 시작합니다. 원격 커널은 계속 실행됩니다",+ "remoteKernelAddressTip": "경로, 쿼리 또는 인증 정보가 포함되지 않은 HTTPS 주소를 입력하세요",+ "checkingRemoteKernel": "연결 확인 중...",+ "remoteKernelVersionMismatch": "원격 커널과 클라이언트의 버전이 일치해야 합니다",+ "remoteKernelConnectionFailed": "연결할 수 없습니다. 주소, 네트워크 및 TLS 인증서를 확인하세요",+ "backToLocalWorkspace": "로컬 작업 공간으로 돌아가기",+ "invalidLocalWorkspace": "기존 로컬 작업 공간 폴더를 선택하세요","tableCellRichEnable": "서식 있는 텍스트로 변환","tableCellRichEdit": "서식 있는 텍스트 편집","tableCellRichDisable": "인라인 콘텐츠로 변환",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex d32582f032..9885e89eb1 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "Verbinden met externe kernel...",+ "remoteConnection": "Extern",+ "localConnection": "Lokaal",+ "switchConnectionRestartTip": "Bij het wisselen worden de huidige werkruimten opgeslagen en gesloten en wordt de desktopclient herstart; externe kernels blijven actief",+ "remoteKernelAddressTip": "Voer een HTTPS-adres in zonder pad, query of ingesloten inloggegevens",+ "checkingRemoteKernel": "Verbinding controleren...",+ "remoteKernelVersionMismatch": "De versie van de externe kernel moet overeenkomen met die van de client",+ "remoteKernelConnectionFailed": "Verbinding mislukt; controleer het adres, het netwerk en het TLS-certificaat",+ "backToLocalWorkspace": "Terug naar lokale werkruimte",+ "invalidLocalWorkspace": "Selecteer een bestaande lokale werkruimtemap","tableCellRichEnable": "Omzetten naar opgemaakte tekst","tableCellRichEdit": "Opgemaakte tekst bewerken","tableCellRichDisable": "Omzetten naar inline-inhoud",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex 2d4f49f511..d9cac46994 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "Połącz ze zdalnym jądrem...",+ "remoteConnection": "Zdalne",+ "localConnection": "Lokalne",+ "switchConnectionRestartTip": "Zmiana połączenia zapisuje i zamyka bieżące obszary robocze, a następnie uruchamia ponownie klienta; zdalne jądra nadal działają",+ "remoteKernelAddressTip": "Wpisz adres HTTPS bez ścieżki, zapytania ani osadzonych danych logowania",+ "checkingRemoteKernel": "Sprawdzanie połączenia...",+ "remoteKernelVersionMismatch": "Wersja zdalnego jądra musi odpowiadać wersji klienta",+ "remoteKernelConnectionFailed": "Nie można połączyć; sprawdź adres, sieć i certyfikat TLS",+ "backToLocalWorkspace": "Wróć do lokalnego obszaru roboczego",+ "invalidLocalWorkspace": "Wybierz istniejący katalog lokalnego obszaru roboczego","tableCellRichEnable": "Konwertuj na tekst sformatowany","tableCellRichEdit": "Edytuj tekst sformatowany","tableCellRichDisable": "Konwertuj na treść w wierszu",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 9ef5a34cdb..c817402d93 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "Conectar ao kernel remoto...",+ "remoteConnection": "Remoto",+ "localConnection": "Local",+ "switchConnectionRestartTip": "A troca de conexão salva e fecha os espaços de trabalho atuais e reinicia o cliente de desktop; os kernels remotos continuam em execução",+ "remoteKernelAddressTip": "Insira um endereço HTTPS sem caminho, consulta ou credenciais incorporadas",+ "checkingRemoteKernel": "Verificando conexão...",+ "remoteKernelVersionMismatch": "A versão do kernel remoto deve corresponder à do cliente",+ "remoteKernelConnectionFailed": "Não foi possível conectar; verifique o endereço, a rede e o certificado TLS",+ "backToLocalWorkspace": "Voltar ao espaço de trabalho local",+ "invalidLocalWorkspace": "Selecione uma pasta de espaço de trabalho local existente","tableCellRichEnable": "Converter em texto formatado","tableCellRichEdit": "Editar texto formatado","tableCellRichDisable": "Converter em conteúdo em linha",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex f0162a2ae1..1206f05918 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "Подключиться к удалённому ядру...",+ "remoteConnection": "Удалённое",+ "localConnection": "Локальное",+ "switchConnectionRestartTip": "При смене подключения текущие рабочие пространства сохраняются и закрываются, затем клиент перезапускается; удалённые ядра продолжают работать",+ "remoteKernelAddressTip": "Введите адрес HTTPS без пути, параметров запроса и встроенных учётных данных",+ "checkingRemoteKernel": "Проверка подключения...",+ "remoteKernelVersionMismatch": "Версия удалённого ядра должна совпадать с версией клиента",+ "remoteKernelConnectionFailed": "Не удалось подключиться; проверьте адрес, сеть и сертификат TLS",+ "backToLocalWorkspace": "Вернуться к локальному рабочему пространству",+ "invalidLocalWorkspace": "Выберите папку существующего локального рабочего пространства","tableCellRichEnable": "Преобразовать в форматированный текст","tableCellRichEdit": "Редактировать форматированный текст","tableCellRichDisable": "Преобразовать в строчное содержимое",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 7bfd2f1958..e19e5d629c 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "Pripojiť k vzdialenému jadru...",+ "remoteConnection": "Vzdialené",+ "localConnection": "Lokálne",+ "switchConnectionRestartTip": "Zmena pripojenia uloží a zatvorí aktuálne pracovné priestory a reštartuje desktopového klienta; vzdialené jadrá zostanú spustené",+ "remoteKernelAddressTip": "Zadajte adresu HTTPS bez cesty, parametrov dotazu alebo vložených prihlasovacích údajov",+ "checkingRemoteKernel": "Kontroluje sa pripojenie...",+ "remoteKernelVersionMismatch": "Verzia vzdialeného jadra sa musí zhodovať s verziou klienta",+ "remoteKernelConnectionFailed": "Nedá sa pripojiť; skontrolujte adresu, sieť a certifikát TLS",+ "backToLocalWorkspace": "Späť do lokálneho pracovného priestoru",+ "invalidLocalWorkspace": "Vyberte existujúci priečinok lokálneho pracovného priestoru","tableCellRichEnable": "Previesť na formátovaný text","tableCellRichEdit": "Upraviť formátovaný text","tableCellRichDisable": "Previesť na obsah v riadku",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 721651eed4..15d19360ea 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "เชื่อมต่อเคอร์เนลระยะไกล...",+ "remoteConnection": "ระยะไกล",+ "localConnection": "ภายในเครื่อง",+ "switchConnectionRestartTip": "การสลับการเชื่อมต่อจะบันทึกและปิดพื้นที่ทำงานปัจจุบัน แล้วเริ่มไคลเอนต์เดสก์ท็อปใหม่ โดยเคอร์เนลระยะไกลยังทำงานต่อไป",+ "remoteKernelAddressTip": "ป้อนที่อยู่ HTTPS ที่ไม่มีพาธ คิวรี หรือข้อมูลรับรองฝังอยู่",+ "checkingRemoteKernel": "กำลังตรวจสอบการเชื่อมต่อ...",+ "remoteKernelVersionMismatch": "เวอร์ชันเคอร์เนลระยะไกลต้องตรงกับไคลเอนต์",+ "remoteKernelConnectionFailed": "เชื่อมต่อไม่ได้ โปรดตรวจสอบที่อยู่ เครือข่าย และใบรับรอง TLS",+ "backToLocalWorkspace": "กลับไปยังพื้นที่ทำงานในเครื่อง",+ "invalidLocalWorkspace": "เลือกโฟลเดอร์พื้นที่ทำงานในเครื่องที่มีอยู่","tableCellRichEnable": "แปลงเป็นข้อความแบบมีรูปแบบ","tableCellRichEdit": "แก้ไขข้อความแบบมีรูปแบบ","tableCellRichDisable": "แปลงเป็นเนื้อหาในบรรทัด",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex 88fd0b91e4..20df37cbcc 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "Uzak çekirdeğe bağlan...",+ "remoteConnection": "Uzak",+ "localConnection": "Yerel",+ "switchConnectionRestartTip": "Bağlantı değiştirildiğinde mevcut çalışma alanları kaydedilip kapatılır ve masaüstü istemcisi yeniden başlatılır; uzak çekirdekler çalışmaya devam eder",+ "remoteKernelAddressTip": "Yol, sorgu veya gömülü kimlik bilgisi içermeyen bir HTTPS adresi girin",+ "checkingRemoteKernel": "Bağlantı denetleniyor...",+ "remoteKernelVersionMismatch": "Uzak çekirdek sürümü istemci sürümüyle eşleşmelidir",+ "remoteKernelConnectionFailed": "Bağlanılamadı; adresi, ağı ve TLS sertifikasını denetleyin",+ "backToLocalWorkspace": "Yerel çalışma alanına dön",+ "invalidLocalWorkspace": "Mevcut bir yerel çalışma alanı dizini seçin","tableCellRichEnable": "Zengin metne dönüştür","tableCellRichEdit": "Zengin metni düzenle","tableCellRichDisable": "Satır içi içeriğe dönüştür",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 6870d3cd9e..9484fd092d 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "Підключитися до віддаленого ядра...",+ "remoteConnection": "Віддалене",+ "localConnection": "Локальне",+ "switchConnectionRestartTip": "Зміна підключення зберігає та закриває поточні робочі простори й перезапускає настільний клієнт; віддалені ядра продовжують працювати",+ "remoteKernelAddressTip": "Введіть адресу HTTPS без шляху, параметрів запиту та вбудованих облікових даних",+ "checkingRemoteKernel": "Перевірка підключення...",+ "remoteKernelVersionMismatch": "Версія віддаленого ядра має збігатися з версією клієнта",+ "remoteKernelConnectionFailed": "Не вдалося підключитися; перевірте адресу, мережу та сертифікат TLS",+ "backToLocalWorkspace": "Повернутися до локального робочого простору",+ "invalidLocalWorkspace": "Виберіть папку наявного локального робочого простору","tableCellRichEnable": "Перетворити на форматований текст","tableCellRichEdit": "Редагувати форматований текст","tableCellRichDisable": "Перетворити на вміст у рядку",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 48834b51c0..a0c7fe8aa8 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "连接远程内核...",+ "remoteConnection": "远程",+ "localConnection": "本地",+ "switchConnectionRestartTip": "切换连接会保存并关闭当前工作空间,然后自动重启桌面客户端;远程内核不受影响",+ "remoteKernelAddressTip": "请输入 HTTPS 地址,不支持路径、查询参数或地址内凭据",+ "checkingRemoteKernel": "正在检查连接...",+ "remoteKernelVersionMismatch": "远程内核版本必须与客户端一致",+ "remoteKernelConnectionFailed": "无法连接,请检查地址、网络和 TLS 证书",+ "backToLocalWorkspace": "返回本地工作空间",+ "invalidLocalWorkspace": "请选择已有的本地工作空间目录","tableCellRichEnable": "转换为富文本","tableCellRichEdit": "编辑富文本","tableCellRichDisable": "转换为行级内容",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex d18f550b17..5f34e735da 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,14 @@{+ "connectRemoteKernel": "連線至遠端核心...",+ "remoteConnection": "遠端",+ "localConnection": "本機",+ "switchConnectionRestartTip": "切換連線會儲存並關閉目前工作空間,然後自動重新啟動桌面用戶端;遠端核心不受影響",+ "remoteKernelAddressTip": "請輸入 HTTPS 網址,不支援路徑、查詢參數或網址內的憑證",+ "checkingRemoteKernel": "正在檢查連線...",+ "remoteKernelVersionMismatch": "遠端核心版本必須與用戶端一致",+ "remoteKernelConnectionFailed": "無法連線,請檢查網址、網路和 TLS 憑證",+ "backToLocalWorkspace": "返回本機工作空間",+ "invalidLocalWorkspace": "請選擇既有的本機工作空間目錄","tableCellRichEnable": "轉換為富文字","tableCellRichEdit": "編輯富文字","tableCellRichDisable": "轉換為行內內容",diff --git a/app/electron/boot.html b/app/electron/boot.htmlindex e61971cf10..939216d32f 100644--- a/app/electron/boot.html+++ b/app/electron/boot.html@@ -559,5 +559,6 @@}})()</script>+<script src="connectionEntry.js"></script></body></html>diff --git a/app/electron/connectionEntry.js b/app/electron/connectionEntry.jsnew file mode 100644index 0000000000..172af0be11--- /dev/null+++ b/app/electron/connectionEntry.js@@ -0,0 +1,31 @@+(() => {+ if (location.pathname.endsWith("/boot.html") && !new URLSearchParams(location.search).has("remote")) {+ return;+ }+ const {ipcRenderer} = require("electron");+ const fs = require("node:fs");+ const path = require("node:path");+ const button = document.createElement("button");+ button.type = "button";+ button.className = "b3-button";+ const langSelect = document.querySelector(".lang");+ const language = () => langSelect?.value || new URLSearchParams(location.search).get("lang") || "en";+ const update = () => {+ let lang = language();+ if (!/^[a-z]{2}(?:-[A-Z]{2})?$/.test(lang)) {+ lang = "en";+ }+ try {+ button.textContent = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "appearance", "langs", lang + ".json"),+ "utf8")).workspaceList;+ } catch (error) {+ button.textContent = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "appearance", "langs", "en.json"),+ "utf8")).workspaceList;+ }+ };+ button.style.cssText = "position:fixed;bottom:16px;right:16px;z-index:1000;-webkit-app-region:no-drag;width:auto";+ button.addEventListener("click", () => ipcRenderer.send("siyuan-manage-connections", {lang: language()}));+ langSelect?.addEventListener("change", update);+ update();+ document.body.append(button);+})();diff --git a/app/electron/connectionManager.js b/app/electron/connectionManager.jsnew file mode 100644index 0000000000..16bd217654--- /dev/null+++ b/app/electron/connectionManager.js@@ -0,0 +1,288 @@+const {app, BrowserWindow, ipcMain, session, net, dialog, safeStorage} = require("electron");+const crypto = require("node:crypto");+const fs = require("node:fs");+const path = require("node:path");+const {pathToFileURL} = require("node:url");+const {normalizeRemoteKernelOrigin, getRemoteKernelVersionStatus, getUnsafeRemoteChromiumSwitchName} = require("./remoteKernel");+const {probeRemoteKernelAuthentication} = require("./remoteKernelAuth");+const {readConnections, writeConnections, remotePartition} = require("./connectionStore");++const getRemoteSession = (target) => session.fromPartition(remotePartition(target.origin));++const createConnectionManager = ({confDir, languageDir, restart, currentTarget, version, log, showWindow = true}) => {+ const file = path.join(confDir, "connections.json");+ const page = pathToFileURL(path.join(__dirname, "connections.html")).href;+ let window;+ let language = "en";+ let initialOrigin = "";+ let initialError = "";+ let controller;+ let checkedOrigin;+ let authenticatedOrigin;+ try {+ for (const name of fs.readdirSync(confDir)) {+ if (/^connection-session-[a-f0-9]{48}\.bin$/.test(name)) {+ const handoff = path.join(confDir, name);+ if (fs.statSync(handoff).mtimeMs < Date.now() - 300000) {+ fs.unlinkSync(handoff);+ }+ }+ }+ } catch (error) {+ if (error.code !== "ENOENT") {+ log("clean expired connection sessions: " + error.message);+ }+ }+ const languages = () => {+ try {+ return JSON.parse(fs.readFileSync(path.join(languageDir, language + ".json"), "utf8"));+ } catch (error) {+ return JSON.parse(fs.readFileSync(path.join(languageDir, "en.json"), "utf8"));+ }+ };+ const updateHistory = (change) => {+ const data = readConnections(file);+ change(data);+ writeConnections(file, data);+ };+ const remember = (origin) => updateHistory(history => {+ history.origins = [origin, ...history.origins.filter(item => item !== origin)].slice(0, 50);+ });+ // 仅为本次客户端重启短暂交接会话 Cookie,使用系统加密,不保存原始授权码。+ const stageSession = async (origin) => {+ const cookies = (await getRemoteSession({origin}).cookies.get({url: origin})).filter(cookie => cookie.session);+ if (cookies.length === 0 || !safeStorage.isEncryptionAvailable() ||+ (process.platform === "linux" && safeStorage.getSelectedStorageBackend() === "basic_text")) {+ return;+ }+ const token = crypto.randomBytes(24).toString("hex");+ const payload = {version: 1, origin, expires: Date.now() + 300000, cookies};+ fs.writeFileSync(path.join(confDir, "connection-session-" + token + ".bin"),+ safeStorage.encryptString(JSON.stringify(payload)), {mode: 0o600, flag: "wx"});+ return token;+ };+ const restoreSession = async (target, token) => {+ if (!token) {+ return;+ }+ if (!/^[a-f0-9]{48}$/.test(token)) {+ throw new Error("Invalid session handoff");+ }+ const handoff = path.join(confDir, "connection-session-" + token + ".bin");+ if (!fs.existsSync(handoff)) {+ return;+ }+ const payload = JSON.parse(safeStorage.decryptString(fs.readFileSync(handoff)));+ if (payload.version !== 1 || payload.origin !== target.origin || !Array.isArray(payload.cookies)) {+ throw new Error("Invalid session handoff target");+ }+ if (payload.expires > Date.now()) {+ for (const cookie of payload.cookies) {+ await setSessionCookie(getRemoteSession(target), target.origin, cookie);+ }+ }+ await getRemoteSession(target).cookies.flushStore();+ fs.unlinkSync(handoff);+ };+ const setSessionCookie = (remoteSession, origin, cookie) => {+ const details = {...cookie};+ delete details.hostOnly;+ delete details.session;+ if (cookie.hostOnly) {+ delete details.domain;+ }+ return remoteSession.cookies.set({...details, url: origin + cookie.path});+ };+ // 首次使用独立会话时迁移现有登录 Cookie,不影响已有远程连接的登录状态。+ const prepareSession = async (target) => {+ const remoteSession = getRemoteSession(target);+ const history = readConnections(file);+ if (!(history.migrated || []).includes(target.origin)) {+ const cookies = await session.defaultSession.cookies.get({url: target.origin});+ for (const cookie of cookies) {+ await setSessionCookie(remoteSession, target.origin, cookie);+ }+ await remoteSession.cookies.flushStore();+ updateHistory(data => {+ data.migrated = [...new Set([...(data.migrated || []), target.origin])];+ });+ }+ return remoteSession;+ };+ const request = async (origin, pathname, signal, options = {}) => {+ const response = await getRemoteSession({origin}).fetch(origin + pathname, {+ ...options, credentials: "include", bypassCustomProtocolHandlers: true, redirect: "manual",+ signal,+ });+ if (!response.ok) {+ await response.body?.cancel();+ throw new Error("HTTP " + response.status);+ }+ return response;+ };+ const list = () => {+ let local = [];+ try {+ local = JSON.parse(fs.readFileSync(path.join(confDir, "workspace.json"), "utf8"));+ } catch (error) {+ if (error.code !== "ENOENT") {+ throw error;+ }+ }+ return [...local.filter(item => typeof item === "string").reverse().map(item => ({mode: "local", path: item})),+ ...readConnections(file).origins.map(origin => ({mode: "remote", origin}))];+ };+ ipcMain.handle("siyuan-connections", async (event, data) => {+ // 管理操作仅接受本机管理窗口主框架发出的请求。+ if (!window || window.isDestroyed() || event.sender !== window.webContents ||+ event.senderFrame !== window.webContents.mainFrame || event.senderFrame.url !== page) {+ return {error: "Invalid connection manager sender"};+ }+ try {+ if (data.cmd === "init") {+ let entries = [];+ let error = initialError;+ try {+ entries = list();+ } catch (cause) {+ error = String(cause.message);+ }+ return {languages: languages(), lang: language, origin: initialOrigin, error, entries};+ }+ if (data.cmd === "cancel") {+ controller?.abort();+ checkedOrigin = undefined;+ authenticatedOrigin = undefined;+ return {};+ }+ if (data.cmd === "remove") {+ const origin = normalizeRemoteKernelOrigin(data.origin);+ updateHistory(history => {+ history.origins = history.origins.filter(item => item !== origin);+ });+ return {entries: list()};+ }+ if (data.cmd === "local") {+ let workspacePath = data.path;+ if (workspacePath === undefined) {+ const selected = await dialog.showOpenDialog(window, {properties: ["openDirectory"]});+ if (selected.canceled) {+ return {};+ }+ workspacePath = selected.filePaths[0];+ }+ if (workspacePath) {+ try {+ if (!path.isAbsolute(workspacePath) || !fs.statSync(workspacePath).isDirectory() ||+ !fs.readFileSync(path.join(workspacePath, "conf", "conf.json"), "utf8").includes("kernelVersion")) {+ throw new Error("Invalid workspace");+ }+ } catch (error) {+ throw new Error(languages().invalidLocalWorkspace);+ }+ }+ await restart({mode: "local", path: workspacePath, lang: language});+ return {};+ }+ let origin;+ try {+ origin = normalizeRemoteKernelOrigin(data.origin);+ } catch (error) {+ throw new Error(languages().remoteKernelAddressTip);+ }+ if (data.cmd === "open") {+ if (checkedOrigin !== origin || authenticatedOrigin !== origin) {+ throw new Error(languages().remoteKernelConnectionFailed);+ }+ await getRemoteSession({origin}).cookies.flushStore();+ remember(origin);+ await restart({mode: "remote", origin, lang: language, sessionHandoff: await stageSession(origin)});+ return {};+ }+ controller?.abort();+ controller = new AbortController();+ const activeController = controller;+ const timer = setTimeout(() => activeController.abort(), 10000);+ try {+ if (process.argv.some(getUnsafeRemoteChromiumSwitchName)) {+ throw new Error(languages().remoteKernelConnectionFailed + " (Chromium)");+ }+ await prepareSession({origin});+ if (activeController.signal.aborted) {+ throw new Error("Canceled");+ }+ if (data.cmd === "check") {+ checkedOrigin = undefined;+ authenticatedOrigin = undefined;+ const versionData = await (await request(origin, "/api/system/version", activeController.signal)).json();+ if (getRemoteKernelVersionStatus(versionData, version) !== "compatible") {+ throw new Error(languages().remoteKernelVersionMismatch + " (" + version + ")");+ }+ const authenticated = await probeRemoteKernelAuthentication(net, getRemoteSession({origin}),+ origin + "/stage/build/app/");+ if (activeController.signal.aborted) {+ throw new Error("Canceled");+ }+ checkedOrigin = origin;+ authenticatedOrigin = authenticated ? origin : undefined;+ return {authenticated};+ }+ if (data.cmd === "login" && checkedOrigin === origin) {+ const result = await (await request(origin, "/api/system/loginAuth", activeController.signal, {+ method: "POST", headers: {"Content-Type": "application/json"},+ body: JSON.stringify({authCode: data.authCode, captcha: data.captcha, rememberMe: data.rememberMe}),+ })).json();+ if (activeController.signal.aborted) {+ throw new Error("Canceled");+ }+ authenticatedOrigin = result.code === 0 ? origin : undefined;+ return {authenticated: result.code === 0, captcha: result.code === 1, error: result.msg};+ }+ if (data.cmd === "captcha" && checkedOrigin === origin) {+ const response = await request(origin, "/api/system/getCaptcha?v=" + Date.now(), activeController.signal);+ return {image: "data:image/png;base64," + Buffer.from(await response.arrayBuffer()).toString("base64")};+ }+ throw new Error("Invalid connection operation");+ } finally {+ clearTimeout(timer);+ }+ } catch (error) {+ log("connection manager: " + error.message);+ return {error: (["check", "login", "captcha"].includes(data.cmd)+ ? languages().remoteKernelConnectionFailed + "\n" : "") + String(error.message)};+ }+ });+ const show = (options = {}) => {+ if (window && !window.isDestroyed()) {+ if (options.origin || options.error) {+ window.webContents.send("siyuan-connection-target", {origin: options.origin, error: options.error});+ }+ window.show();+ window.focus();+ return window.id;+ }+ language = /^[a-z]{2}(?:-[A-Z]{2})?$/.test(options.lang || "") ? options.lang : app.getLocale();+ initialOrigin = options.origin || currentTarget()?.origin || "";+ initialError = options.error || "";+ checkedOrigin = undefined;+ authenticatedOrigin = undefined;+ window = new BrowserWindow({width: 720, height: 600, minWidth: 560, minHeight: 480, show: showWindow,+ title: languages().workspaceList, autoHideMenuBar: true,+ webPreferences: {nodeIntegration: true, contextIsolation: false, webSecurity: true,+ partition: "siyuan-connection-manager"}});+ window.webContents.on("will-navigate", event => event.preventDefault());+ window.webContents.setWindowOpenHandler(() => ({action: "deny"}));+ window.on("closed", () => {+ controller?.abort();+ window = undefined;+ if (BrowserWindow.getAllWindows().length === 0) {+ app.quit();+ }+ });+ window.loadURL(page);+ return window.id;+ };+ return {show, prepareSession, restoreSession, remember};+};++module.exports = {createConnectionManager, getRemoteSession};diff --git a/app/electron/connectionManager.test.js b/app/electron/connectionManager.test.jsnew file mode 100644index 0000000000..9e953c025a--- /dev/null+++ b/app/electron/connectionManager.test.js@@ -0,0 +1,150 @@+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");++if (!process.versions.electron) {+ const {test} = require("node:test");+ const {execFile} = require("node:child_process");+ const {promisify} = require("node:util");+ test("connection manager UI, authentication, cancellation and session migration", async () => {+ const profile = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-connections-ui-"));+ const env = {...process.env};+ delete env.ELECTRON_RUN_AS_NODE;+ try {+ const {stdout} = await promisify(execFile)(require("electron"), [__filename, profile], {+ env, timeout: 60000, windowsHide: true,+ });+ assert.match(stdout, /Connection manager passed/);+ } finally {+ assert.equal(path.dirname(path.resolve(profile)), path.resolve(os.tmpdir()));+ fs.rmSync(profile, {recursive: true, force: true, maxRetries: 5, retryDelay: 200});+ }+ });+} else {+ const {app, BrowserWindow, ipcMain, session, net} = require("electron");+ const {EventEmitter} = require("node:events");+ const {createConnectionManager, getRemoteSession} = require("./connectionManager");+ const {readConnections} = require("./connectionStore");+ const profile = process.argv[2];+ app.setPath("userData", profile);+ app.disableHardwareAcceleration();+ app.whenReady().then(async () => {+ const origin = "https://example.com";+ let authenticated = false;+ let serverVersion = "1.0.0";+ let slow = false;+ let lastSignal;+ const requests = [];+ const restarts = [];+ let handler;+ const handle = ipcMain.handle.bind(ipcMain);+ ipcMain.handle = (name, callback) => {+ if (name === "siyuan-connections") {+ handler = callback;+ }+ handle(name, callback);+ };+ net.request = () => {+ const request = new EventEmitter();+ request.abort = () => {};+ request.end = () => setImmediate(() => {+ const response = new EventEmitter();+ response.statusCode = authenticated ? 200 : 401;+ request.emit("response", response);+ });+ return request;+ };+ const remoteSession = getRemoteSession({origin});+ remoteSession.fetch = async (url, options) => {+ requests.push({url, options});+ assert.equal(options.redirect, "manual");+ assert.equal(options.bypassCustomProtocolHandlers, true);+ lastSignal = options.signal;+ if (slow) {+ await new Promise((resolve, reject) => options.signal.addEventListener("abort", () => reject(new Error("Canceled"))));+ }+ if (url.endsWith("/api/system/version")) {+ return Response.json({code: 0, data: serverVersion});+ }+ if (url.endsWith("/api/system/loginAuth")) {+ authenticated = JSON.parse(options.body).authCode === "valid";+ if (authenticated) {+ await remoteSession.cookies.set({url: origin, name: "auth", value: "secret-session", secure: true});+ }+ return Response.json({code: authenticated ? 0 : 1, msg: authenticated ? "" : "Invalid code"});+ }+ return new Response(Buffer.from("image"));+ };+ try {+ await session.defaultSession.cookies.set({url: origin, name: "legacy", value: "retained", secure: true});+ const manager = createConnectionManager({confDir: profile, languageDir: path.join(__dirname, "../appearance/langs"),+ version: "1.0.0", currentTarget: () => ({origin}), log: () => {},+ restart: target => restarts.push(target), showWindow: false});+ await manager.prepareSession({origin});+ assert.equal((await remoteSession.cookies.get({url: origin}))[0].value, "retained");+ await remoteSession.cookies.remove(origin, "legacy");+ await manager.prepareSession({origin});+ assert.equal((await remoteSession.cookies.get({url: origin})).length, 0);+ assert.notEqual(remoteSession, getRemoteSession({origin: "https://example.com:8443"}));+ assert.match((await handler({sender: {}}, {cmd: "init"})).error, /sender/);+ const id = manager.show({lang: "zh-CN"});+ const window = BrowserWindow.fromId(id);+ await new Promise(resolve => window.webContents.once("did-finish-load", resolve));+ const evaluate = code => window.webContents.executeJavaScript(code);+ await evaluate(`new Promise(resolve => {+ const ready = () => document.getElementById("title").textContent ? resolve() : setTimeout(ready, 20);+ ready();+ })`);+ const invoke = data => evaluate(`require("electron").ipcRenderer.invoke("siyuan-connections", ${JSON.stringify(data)})`);+ assert.ok(await evaluate('document.getElementById("restartTip").textContent.length > 10'));+ fs.writeFileSync(path.join(os.tmpdir(), "siyuan-connections-preview.png"), (await window.webContents.capturePage()).toPNG());+ assert.match((await invoke({cmd: "open", origin})).error, /./);+ serverVersion = "2.0.0";+ assert.ok((await invoke({cmd: "check", origin})).error);+ serverVersion = "1.0.0";+ await evaluate('document.getElementById("connectionForm").requestSubmit()');+ await evaluate(`new Promise(resolve => {+ const ready = () => !document.getElementById("auth").hidden && !document.getElementById("connect").disabled+ ? resolve() : setTimeout(ready, 20);+ ready();+ })`);+ assert.equal(await evaluate('document.getElementById("auth").hidden'), false);+ fs.writeFileSync(path.join(os.tmpdir(), "siyuan-connections-auth-preview.png"), (await window.webContents.capturePage()).toPNG());+ assert.equal((await invoke({cmd: "check", origin})).authenticated, false);+ assert.ok((await invoke({cmd: "open", origin})).error);+ assert.equal((await invoke({cmd: "login", origin, authCode: "bad"})).captcha, true);+ assert.equal((await invoke({cmd: "login", origin, authCode: "valid", rememberMe: true})).authenticated, true);+ assert.deepEqual(await invoke({cmd: "open", origin}), {});+ assert.equal(restarts[0].origin, origin);+ if (restarts[0].sessionHandoff) {+ const token = restarts[0].sessionHandoff;+ const handoff = path.join(profile, "connection-session-" + token + ".bin");+ assert.equal(fs.readFileSync(handoff).includes(Buffer.from("secret-session")), false);+ await assert.rejects(manager.restoreSession({origin: "https://other.example"}, token));+ assert.ok(fs.existsSync(handoff));+ await remoteSession.cookies.remove(origin, "auth");+ await manager.restoreSession({origin}, token);+ assert.equal((await remoteSession.cookies.get({url: origin}))[0].value, "secret-session");+ assert.equal(fs.existsSync(handoff), false);+ }+ assert.deepEqual(readConnections(path.join(profile, "connections.json")).origins, [origin]);+ assert.ok((await invoke({cmd: "remove", origin})).entries);+ assert.deepEqual(readConnections(path.join(profile, "connections.json")).origins, []);+ slow = true;+ const pending = invoke({cmd: "check", origin});+ await new Promise(resolve => setTimeout(resolve, 50));+ await invoke({cmd: "cancel"});+ assert.equal(lastSignal.aborted, true);+ assert.ok((await pending).error);+ assert.ok((await invoke({cmd: "open", origin})).error);+ assert.ok(requests.every(item => item.url.startsWith(origin + "/api/system/")));+ window.destroy();+ console.log("Connection manager passed");+ app.exit(0);+ } catch (error) {+ console.error(error);+ app.exit(1);+ }+ }).catch(error => { console.error(error); app.exit(1); });+}diff --git a/app/electron/connectionStore.js b/app/electron/connectionStore.jsnew file mode 100644index 0000000000..7393d10cc0--- /dev/null+++ b/app/electron/connectionStore.js@@ -0,0 +1,81 @@+const fs = require("node:fs");+const path = require("node:path");+const crypto = require("node:crypto");+const {normalizeRemoteKernelOrigin, getUnsafeRemoteChromiumSwitchName} = require("./remoteKernel");++const remotePartition = (origin) => "persist:siyuan-remote-" ++ crypto.createHash("sha256").update(normalizeRemoteKernelOrigin(origin)).digest("hex");++// 只保留地址记录,会话凭据由 Electron 会话存储管理。+const readConnections = (file) => {+ try {+ const data = JSON.parse(fs.readFileSync(file, "utf8"));+ if (data.version !== 1 || !Array.isArray(data.origins) ||+ (data.migrated !== undefined && !Array.isArray(data.migrated))) {+ throw new Error("Unsupported connection history");+ }+ return {...data, origins: [...new Set(data.origins.map(normalizeRemoteKernelOrigin))],+ migrated: (data.migrated || []).map(normalizeRemoteKernelOrigin)};+ } catch (error) {+ if (error.code === "ENOENT") {+ return {version: 1, origins: [], migrated: []};+ }+ throw error;+ }+};++const writeConnections = (file, data) => {+ fs.mkdirSync(path.dirname(file), {recursive: true});+ const temporary = file + "." + crypto.randomBytes(8).toString("hex") + ".tmp";+ try {+ fs.writeFileSync(temporary, JSON.stringify(data, null, 2), {mode: 0o600});+ fs.renameSync(temporary, file);+ } finally {+ if (fs.existsSync(temporary)) {+ fs.unlinkSync(temporary);+ }+ }+};++// 切换时移除目标相关参数,避免把本地安全开关或远程扩展信任带到另一个连接。+const connectionArgs = (args, target, currentOrigin) => {+ const removed = new Set(["--remote", "--workspace", "--port", "--safe-mode", "--openAsHidden",+ "--trust-remote-extensions", "--no-proxy-server", "--connection-session"]);+ const result = args.filter(arg => !removed.has(arg.split("=", 1)[0]) &&+ !arg.startsWith("siyuan://") && !getUnsafeRemoteChromiumSwitchName(arg));+ if (target.mode === "remote") {+ const origin = normalizeRemoteKernelOrigin(target.origin);+ result.push("--remote=" + origin);+ if (/^[a-f0-9]{48}$/.test(target.sessionHandoff || "")) {+ result.push("--connection-session=" + target.sessionHandoff);+ }+ if (origin === currentOrigin && args.includes("--trust-remote-extensions")) {+ result.push("--trust-remote-extensions");+ }+ } else if (target.mode === "local") {+ if (target.path) {+ if (!path.isAbsolute(target.path)) {+ throw new Error("Invalid workspace path");+ }+ result.push("--workspace=" + target.path);+ }+ } else {+ throw new Error("Invalid connection type");+ }+ if (/^[a-z]{2}(?:-[A-Z]{2})?$/.test(target.lang || "")) {+ return [...result.filter(arg => !arg.startsWith("--lang=")), "--lang=" + target.lang];+ }+ return result;+};++// 独立窗口先完成自己的保存与关闭流程,再退出工作空间主窗口。+const closeConnectionWindows = (windows) => Promise.all(windows.map(window => new Promise(resolve => {+ if (window.isDestroyed()) {+ resolve();+ return;+ }+ window.once("closed", resolve);+ window.close();+})));++module.exports = {connectionArgs, readConnections, writeConnections, remotePartition, closeConnectionWindows};diff --git a/app/electron/connectionStore.test.js b/app/electron/connectionStore.test.jsnew file mode 100644index 0000000000..48f36994c2--- /dev/null+++ b/app/electron/connectionStore.test.js@@ -0,0 +1,66 @@+const assert = require("node:assert/strict");+const fs = require("node:fs");+const os = require("node:os");+const path = require("node:path");+const test = require("node:test");+const {connectionArgs, remotePartition, readConnections, writeConnections, closeConnectionWindows} = require("./connectionStore");++test("connection restart waits for every detached window to finish closing", async () => {+ const {EventEmitter} = require("node:events");+ const windows = [new EventEmitter(), new EventEmitter()];+ let completed = false;+ windows.forEach(window => {+ window.isDestroyed = () => false;+ window.close = () => { window.requested = true; };+ });+ const closing = closeConnectionWindows(windows).then(() => { completed = true; });+ assert.ok(windows.every(window => window.requested));+ windows[0].emit("closed");+ await Promise.resolve();+ assert.equal(completed, false);+ windows[1].emit("closed");+ await closing;+ assert.equal(completed, true);+});++test("switching removes stale connection flags and keeps unrelated launch settings", () => {+ const args = ["main.js", "--workspace=D:/notes", "--port=6806", "--safe-mode=1", "--openAsHidden",+ "--remote=https://a.example", "--trust-remote-extensions", "--ignore-certificate-errors",+ "--disable-web-security", "--no-proxy-server", "--lang=en", "siyuan://blocks/test", "--foo=bar"];+ assert.deepEqual(connectionArgs(args, {mode: "remote", origin: "https://B.example:443/", lang: "ja"},+ "https://a.example"), ["main.js", "--foo=bar", "--remote=https://b.example", "--lang=ja"]);+ assert.equal(connectionArgs(args, {mode: "local"}).some(arg => arg.startsWith("--remote")), false);+ assert.equal(connectionArgs(args, {mode: "remote", origin: "https://a.example"}, "https://a.example")+ .includes("--trust-remote-extensions"), true);+ assert.throws(() => connectionArgs(args, {mode: "remote", origin: "http://example.com"}));+ assert.throws(() => connectionArgs(args, {mode: "local", path: "relative"}));+ const localPath = path.join(os.tmpdir(), "notes with spaces");+ assert.ok(connectionArgs(args, {mode: "local", path: localPath}).includes("--workspace=" + localPath));+});++test("remote sessions isolate normalized origins including ports", () => {+ assert.equal(remotePartition("https://EXAMPLE.com:443/"), remotePartition("https://example.com"));+ assert.notEqual(remotePartition("https://example.com:8443"), remotePartition("https://example.com"));+ assert.notEqual(remotePartition("https://b.example.com"), remotePartition("https://example.com"));+ assert.match(remotePartition("https://example.com"), /^persist:siyuan-remote-[a-f0-9]{64}$/);+});++test("connection history preserves corrupt or unsupported files and writes atomically", () => {+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "siyuan-connections-test-"));+ const file = path.join(directory, "connections.json");+ try {+ assert.deepEqual(readConnections(file), {version: 1, origins: [], migrated: []});+ writeConnections(file, {version: 1, origins: ["https://EXAMPLE.com:443/", "https://example.com"], migrated: []});+ assert.deepEqual(readConnections(file).origins, ["https://example.com"]);+ assert.deepEqual(fs.readdirSync(directory), ["connections.json"]);+ for (const contents of ["corrupt", '{"version":2,"origins":[]}',+ '{"version":1,"origins":["http://example.com"]}']) {+ fs.writeFileSync(file, contents);+ assert.throws(() => readConnections(file));+ assert.equal(fs.readFileSync(file, "utf8"), contents);+ }+ } finally {+ assert.equal(path.dirname(path.resolve(directory)), path.resolve(os.tmpdir()));+ fs.rmSync(directory, {recursive: true, force: true});+ }+});diff --git a/app/electron/connections.css b/app/electron/connections.cssnew file mode 100644index 0000000000..9388aebfce--- /dev/null+++ b/app/electron/connections.css@@ -0,0 +1,21 @@+body { margin: 0; font: 14px/1.6 system-ui, sans-serif; color: #222; background: #fff; }+main { max-width: 680px; margin: auto; padding: 24px; }+h1 { font-size: 22px; margin: 0 0 12px; }+h2 { font-size: 16px; }+p { margin: 8px 0; }+input:not([type="checkbox"]) { box-sizing: border-box; width: 100%; padding: 8px; border: 1px solid #888; border-radius: 4px; background: transparent; color: inherit; }+button { padding: 6px 12px; border: 1px solid #888; border-radius: 4px; background: transparent; color: inherit; cursor: pointer; }+button:hover { background: #8882; }+button:disabled { opacity: .5; cursor: default; }+#connect { background: #3573f0; color: white; border-color: #3573f0; }+#addressTip, #restartTip { opacity: .75; }+#message { overflow-wrap: anywhere; min-height: 24px; }+fieldset { border: 0; padding: 8px 0; margin: 0; }+.actions, .entry { display: flex; gap: 8px; margin-top: 12px; }+.entry { align-items: center; }+.entry > button:first-child { flex: 1; text-align: start; overflow-wrap: anywhere; min-width: 0; }+#captchaRow { margin: 8px 0; }+#captchaImage { vertical-align: middle; max-width: 160px; }+@media (prefers-color-scheme: dark) {+ body { color: #dadada; background: #1e1e1e; }+}diff --git a/app/electron/connections.html b/app/electron/connections.htmlnew file mode 100644index 0000000000..c49290e706--- /dev/null+++ b/app/electron/connections.html@@ -0,0 +1,32 @@+<!DOCTYPE html>+<html>+<head>+ <meta charset="UTF-8">+ <meta name="color-scheme" content="light dark">+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self'; img-src data:">+ <title>SiYuan</title>+ <link rel="stylesheet" href="connections.css">+</head>+<body>+ <main>+ <h1 id="title"></h1>+ <p id="restartTip"></p>+ <form id="connectionForm">+ <label id="addressLabel" for="origin"></label>+ <input id="origin" type="url" placeholder="https://siyuan.example.com" required autofocus>+ <p id="addressTip"></p>+ <fieldset id="auth" hidden>+ <input id="authCode" type="password" autocomplete="current-password">+ <div id="captchaRow" hidden><input id="captcha" autocomplete="off"><button id="refreshCaptcha" type="button"><img id="captchaImage"></button></div>+ <label><input id="rememberMe" type="checkbox"><span id="rememberLabel"></span></label>+ </fieldset>+ <div class="actions"><button id="connect" type="submit"></button><button id="cancel" type="button"></button></div>+ </form>+ <p id="message" role="status" aria-live="polite"></p>+ <h2 id="historyTitle"></h2>+ <div id="history"></div>+ <div class="actions"><button id="local" type="button"></button><button id="localDefault" type="button"></button></div>+ </main>+ <script src="connections.js"></script>+</body>+</html>diff --git a/app/electron/connections.js b/app/electron/connections.jsnew file mode 100644index 0000000000..9c6583169b--- /dev/null+++ b/app/electron/connections.js@@ -0,0 +1,162 @@+const {ipcRenderer} = require("electron");+const element = (id) => document.getElementById(id);+const invoke = (cmd, data = {}) => ipcRenderer.invoke("siyuan-connections", {cmd, ...data});+let languages;+let checked = false;+let authenticated = false;+let sequence = 0;+const message = (value) => { element("message").textContent = value || ""; };+const reset = () => {+ sequence++;+ checked = false;+ authenticated = false;+ element("auth").hidden = true;+ element("captchaRow").hidden = true;+ element("authCode").value = "";+ element("captcha").value = "";+ element("connect").disabled = false;+ message("");+ void invoke("cancel");+};+const refreshCaptcha = async () => {+ const requestSequence = sequence;+ const result = await invoke("captcha", {origin: element("origin").value.trim()});+ if (sequence !== requestSequence) {+ return;+ }+ if (result.image) {+ element("captchaImage").src = result.image;+ } else {+ message(result.error);+ }+};+const renderHistory = (entries) => {+ element("history").replaceChildren();+ entries.forEach(entry => {+ const row = document.createElement("div");+ row.className = "entry";+ const open = document.createElement("button");+ open.type = "button";+ open.textContent = (entry.mode === "remote" ? languages.remoteConnection : languages.localConnection) ++ " · " + (entry.origin || entry.path);+ open.addEventListener("click", async () => {+ reset();+ if (entry.mode === "remote") {+ element("origin").value = entry.origin;+ element("connectionForm").requestSubmit();+ } else {+ const result = await invoke("local", {path: entry.path});+ message(result.error);+ }+ });+ row.append(open);+ if (entry.mode === "remote") {+ const remove = document.createElement("button");+ remove.type = "button";+ remove.textContent = languages.remove;+ remove.addEventListener("click", async () => {+ const result = await invoke("remove", {origin: entry.origin});+ if (result.entries) {+ renderHistory(result.entries);+ }+ message(result.error);+ });+ row.append(remove);+ }+ element("history").append(row);+ });+};+element("origin").addEventListener("input", reset);+ipcRenderer.on("siyuan-connection-target", (event, data) => {+ reset();+ if (data.origin) {+ element("origin").value = data.origin;+ }+ message(data.error);+ element("origin").focus();+});+element("cancel").addEventListener("click", reset);+element("refreshCaptcha").addEventListener("click", refreshCaptcha);+element("local").addEventListener("click", async () => {+ reset();+ message((await invoke("local")).error);+});+element("localDefault").addEventListener("click", async () => {+ reset();+ message((await invoke("local", {path: ""})).error);+});+element("connectionForm").addEventListener("submit", async (event) => {+ event.preventDefault();+ const requestSequence = ++sequence;+ const origin = element("origin").value.trim();+ element("connect").disabled = true;+ message(languages.checkingRemoteKernel);+ try {+ let result;+ if (!checked) {+ result = await invoke("check", {origin});+ } else if (!authenticated) {+ result = await invoke("login", {origin, authCode: element("authCode").value.trim(),+ captcha: element("captcha").value, rememberMe: element("rememberMe").checked});+ element("authCode").value = "";+ } else {+ result = {authenticated: true};+ }+ if (sequence !== requestSequence) {+ return;+ }+ if (typeof result.authenticated === "boolean") {+ checked = true;+ authenticated = result.authenticated;+ }+ if (authenticated) {+ message((await invoke("open", {origin})).error || languages.switchConnectionRestartTip);+ } else {+ message(result.error);+ element("auth").hidden = !checked;+ if (result.captcha) {+ element("captchaRow").hidden = false;+ await refreshCaptcha();+ }+ if (checked) {+ element("authCode").focus();+ }+ }+ } catch (error) {+ if (sequence === requestSequence) {+ message(String(error.message));+ }+ } finally {+ if (sequence === requestSequence) {+ element("connect").disabled = false;+ }+ }+});+void invoke("init").then(result => {+ if (!result.languages) {+ message(result.error);+ return;+ }+ languages = result.languages;+ document.documentElement.lang = result.lang;+ document.documentElement.dir = ["ar", "he"].includes(result.lang) ? "rtl" : "ltr";+ document.title = languages.workspaceList;+ element("title").textContent = languages.connectRemoteKernel;+ element("addressLabel").textContent = languages.remoteConnection;+ element("addressTip").textContent = languages.remoteKernelAddressTip;+ element("restartTip").textContent = languages.switchConnectionRestartTip;+ element("connect").textContent = languages.connectRemoteKernel;+ element("cancel").textContent = languages.cancel;+ element("historyTitle").textContent = languages.workspaceList;+ element("local").textContent = languages.localConnection + " · " + languages.openBy;+ element("localDefault").textContent = languages.backToLocalWorkspace;+ element("authCode").placeholder = languages._kernel["173"];+ element("authCode").ariaLabel = languages._kernel["173"];+ element("captcha").placeholder = languages._kernel["175"];+ element("captcha").ariaLabel = languages._kernel["175"];+ element("refreshCaptcha").ariaLabel = languages.refresh;+ element("rememberLabel").textContent = languages._kernel["257"];+ element("origin").value = result.origin;+ message(result.error);+ renderHistory(result.entries);+});diff --git a/app/electron/init.html b/app/electron/init.htmlindex c96a78ae08..c1dedbfcb6 100644--- a/app/electron/init.html+++ b/app/electron/init.html@@ -97,5 +97,6 @@})})</script>+<script src="connectionEntry.js"></script></body></html>diff --git a/app/electron/main.js b/app/electron/main.jsindex 6266ea2b12..5998ca8577 100644--- a/app/electron/main.js+++ b/app/electron/main.js@@ -43,6 +43,8 @@ const gNet = require("net");const childProcess = require("child_process");const remote = require("@electron/remote/main");const {probeRemoteKernelAuthentication} = require("./remoteKernelAuth");+const {createConnectionManager, getRemoteSession} = require("./connectionManager");+const {connectionArgs, readConnections, closeConnectionWindows} = require("./connectionStore");const {rawFormatType, readClipboardBuffer, readClipboardText, getClipboardFormats, parseClipboardFilePaths} = require("./clipboard");@@ -482,6 +484,15 @@ const createLocalKernelTarget = (port = kernelPort) => ({let remoteKernelTarget;let remoteKernelArgError;+let connectionManager;+let remoteBootCanceled = false;+let pendingConnectionArgs;+const relaunchConnection = () => {+ if (pendingConnectionArgs) {+ app.relaunch({args: pendingConnectionArgs});+ pendingConnectionArgs = undefined;+ }+};const remoteKernelArg = getArg("--remote");if (remoteKernelArg !== undefined) {try {@@ -692,7 +703,7 @@ if (!app.isPackaged) {for (let i = argStart; i < process.argv.length; i++) {let arg = process.argv[i];if (arg.startsWith("--workspace=") || arg.startsWith("--openAsHidden") || arg.startsWith("--port=") ||- arg.startsWith("--safe-mode=") || arg.startsWith("--lang=") || arg === "--remote" ||+ arg.startsWith("--safe-mode=") || arg.startsWith("--lang=") || arg.startsWith("--connection-session=") || arg === "--remote" ||arg.startsWith("--remote=") || arg === "--trust-remote-extensions" ||arg.startsWith("--trust-remote-extensions=") ||arg.startsWith("siyuan://")) {@@ -1190,6 +1201,7 @@ const exitWorkspace = (workspace, errorWindowId) => {if (keepAppOpenDuringSystemShutdown || keepAppOpenDuringUpdate) {mainWindow.destroy();} else {+ relaunchConnection();app.exit();}}@@ -1313,7 +1325,8 @@ const installRemoteFrontendProtocol = (target) => {return;}const scheme = new URL(target.origin).protocol.slice(0, -1);- session.defaultSession.webRequest.onBeforeRequest((details, callback) => {+ const remoteSession = getRemoteSession(target);+ remoteSession.webRequest.onBeforeRequest((details, callback) => {const destination = getRemoteKernelWebRequestDestination(details.resourceType);let requestPolicy = "remote";if (destination) {@@ -1338,8 +1351,8 @@ const installRemoteFrontendProtocol = (target) => {requestPolicy === "deny-active-content",});});- session.defaultSession.protocol.handle(scheme, async (request) => {- const forwardRequest = (includeCredentials = false) => session.defaultSession.fetch(request, {+ remoteSession.protocol.handle(scheme, async (request) => {+ const forwardRequest = (includeCredentials = false) => remoteSession.fetch(request, {bypassCustomProtocolHandlers: true,redirect: "manual",...(includeCredentials ? {credentials: "include"} : {}),@@ -1416,7 +1429,7 @@ const installRemoteFrontendProtocol = (target) => {if (localDocumentRequest &&["/stage/build/app/", "/stage/build/app/window.html"].includes(requestURL.pathname)) {try {- if (!await probeRemoteKernelAuthentication(net, session.defaultSession, requestURL.href)) {+ if (!await probeRemoteKernelAuthentication(net, remoteSession, requestURL.href)) {const authURL = new URL("/check-auth", target.origin);authURL.searchParams.set("to", requestURL.pathname + requestURL.search);authURL.searchParams.set("lang", resolveAppLanguage(app.getPreferredSystemLanguages()));@@ -1896,6 +1909,10 @@ const sleep = (ms) => {};const showErrorWindow = (titleZh, titleEn, content, emoji = "⚠️", logPath = "") => {+ if (connectionManager && (remoteKernelTarget || remoteKernelArgError)) {+ return connectionManager.show({lang: getArg("--lang"), error: titleZh + "\n" + titleEn + "\n" ++ content.replace(/<[^>]*>/g, " ")});+ }let errorHTMLPath = path.join(appDir, "app", "electron", "error.html");if (isDevEnv) {errorHTMLPath = path.join(appDir, "electron", "error.html");@@ -2023,6 +2040,7 @@ const initMainWindow = (kernel = kernelPort, remoteAuthenticated = true) => {nodeIntegrationInWorker: false,webviewTag: kernelTarget.mode !== "remote",webSecurity: kernelTarget.mode === "remote",+ ...(kernelTarget.mode === "remote" ? {session: getRemoteSession(kernelTarget)} : {}),contextIsolation: false,autoplayPolicy: "user-gesture-required" // 桌面端禁止自动播放多媒体 https://github.com/siyuan-note/siyuan/issues/7587},@@ -2298,7 +2316,7 @@ const loadBootWindow = (disableAppearance = false) => {if (disableAppearance) {bootAppearanceFallback = true;}- const query = {v: appVer, port: kernelPort};+ const query = {v: appVer, port: kernelPort, lang: getArg("--lang") || resolveAppLanguage(app.getPreferredSystemLanguages())};if (remoteKernelTarget) {query.remote = remoteKernelTarget.origin;query.appearance = "0";@@ -2555,7 +2573,7 @@ const fetchWithTimeout = async (url, options = {}, timeout = 5000) => {const abortController = new AbortController();const timer = setTimeout(() => abortController.abort(), timeout);try {- return await session.defaultSession.fetch(url, Object.assign({+ return await getRemoteSession({origin: new URL(url).origin}).fetch(url, Object.assign({credentials: "include",bypassCustomProtocolHandlers: true,redirect: "manual",@@ -2575,9 +2593,12 @@ const requestRemoteKernelVersion = async (target) => {};const isRemoteKernelAuthenticated = (target) =>- probeRemoteKernelAuthentication(net, session.defaultSession, target.origin + "/stage/build/app/");+ probeRemoteKernelAuthentication(net, getRemoteSession(target), target.origin + "/stage/build/app/");const initRemoteKernel = async (target) => {+ remoteBootCanceled = false;+ await connectionManager.prepareSession(target);+ await connectionManager.restoreSession(target, getArg("--connection-session"));createBootWindow();if (!await showAppleSiliconWarning(getArg("--lang") || "")) {bootWindow.destroy();@@ -2592,7 +2613,7 @@ const initRemoteKernel = async (target) => {}try {- await session.defaultSession.clearStorageData({+ await getRemoteSession(target).clearStorageData({origin: target.origin,storages: remoteKernelActiveStorageTypes,});@@ -2602,22 +2623,31 @@ const initRemoteKernel = async (target) => {writeLog("connecting to remote kernel [origin=" + target.origin + "]");let versionData;+ let connectionError = "";for (let count = 0; count < 5; count++) {+ if (remoteBootCanceled) {+ return;+ }try {versionData = await requestRemoteKernelVersion(target);break;} catch (error) {+ connectionError = error.message;writeLog("get remote kernel version failed: " + error.message);if (count < 4) {await sleep(500);}}}+ if (remoteBootCanceled) {+ return;+ }const versionStatus = getRemoteKernelVersionStatus(versionData, appVer);if (versionStatus === "invalid") {showErrorWindow("连接远程内核失败", "Failed to connect to the remote kernel","<div>无法连接远程内核,请检查地址、网络和 TLS 证书。</div>" +- "<div>Unable to connect to the remote kernel. Check the address, network, and TLS certificate.</div>");+ "<div>Unable to connect to the remote kernel. Check the address, network, and TLS certificate.</div>" ++ "<div>" + escapeHTML(connectionError) + "</div>");bootWindow.destroy();return;}@@ -2633,7 +2663,7 @@ const initRemoteKernel = async (target) => {const bootShowStart = Date.now();let booted = false;- while (Date.now() - bootShowStart <= 300000) {+ while (!remoteBootCanceled && Date.now() - bootShowStart <= 300000) {try {const response = await fetchWithTimeout(target.origin + "/api/system/bootProgress");if (!response.ok) {@@ -2650,6 +2680,9 @@ const initRemoteKernel = async (target) => {}await sleep(500);}+ if (remoteBootCanceled) {+ return;+ }if (!booted) {showErrorWindow("连接远程内核超时", "Remote kernel connection timed out","<div>等待远程内核完成启动超时。</div><div>Timed out waiting for the remote kernel to finish booting.</div>");@@ -2662,11 +2695,19 @@ const initRemoteKernel = async (target) => {authenticated = await isRemoteKernelAuthenticated(target);} catch (error) {writeLog("probe remote kernel authentication failed: " + error.message);+ if (remoteBootCanceled) {+ return;+ }showErrorWindow("检查远程内核鉴权失败", "Failed to check remote kernel authentication",- "<div>无法检查远程内核的鉴权状态。</div><div>Unable to check the remote kernel authentication state.</div>");+ "<div>无法检查远程内核的鉴权状态。</div><div>Unable to check the remote kernel authentication state.</div>" ++ "<div>" + escapeHTML(error.message) + "</div>");bootWindow.destroy();return;}+ if (remoteBootCanceled) {+ return;+ }+ connectionManager.remember(target.origin);installRemoteFrontendProtocol(target);return {target,@@ -2675,6 +2716,43 @@ const initRemoteKernel = async (target) => {};app.whenReady().then(() => {+ connectionManager = createConnectionManager({+ confDir,+ languageDir: path.join(appDir, "appearance", "langs"),+ version: appVer,+ currentTarget: () => remoteKernelTarget,+ log: writeLog,+ restart: async (target) => {+ if (pendingConnectionArgs || updateInstallPromise || systemShutdownState !== systemShutdownNone) {+ return;+ }+ pendingConnectionArgs = connectionArgs(process.argv.slice(1), target, remoteKernelTarget?.origin);+ try {+ await closeConnectionWindows(BrowserWindow.getAllWindows().filter(window =>+ windowKernelTargets.has(window.webContents.id) &&+ getWindowPathname(window) === "/stage/build/app/window.html"));+ } catch (error) {+ pendingConnectionArgs = undefined;+ throw error;+ }+ // 先通过现有保存与退出流程关闭全部工作空间,最后一个窗口退出后再安排重启。+ app.quit();+ },+ });+ ipcMain.on("siyuan-manage-connections", (event, options) => {+ const target = getWindowKernelTarget(event.sender.id);+ const localPages = ["init.html", "workspace.html", ...(remoteKernelTarget ? ["boot.html"] : [])].map(name =>+ pathToFileURL(path.join(__dirname, name)).href);+ const localPage = localPages.includes(event.senderFrame?.url.split("?")[0]);+ if (event.senderFrame === event.sender.mainFrame && (localPage || (target &&+ ["/stage/build/app/", "/check-auth"].includes(getWindowPathname(BrowserWindow.fromWebContents(event.sender)))))) {+ connectionManager.show({lang: options?.lang, origin: options?.origin});+ if (remoteKernelTarget && bootWindow && !bootWindow.isDestroyed()) {+ remoteBootCanceled = true;+ bootWindow.destroy();+ }+ }+ });if ("darwin" === process.platform) {Menu.setApplicationMenu(Menu.buildFromTemplate([{role: "appMenu"}]));} else {@@ -2882,6 +2960,17 @@ app.whenReady().then(() => {app.exit();});ipcMain.handle("siyuan-get", async (event, data) => {+ if (data.cmd === "remoteConnections") {+ if (!getWindowKernelTarget(event.sender.id) || event.senderFrame !== event.sender.mainFrame) {+ return [];+ }+ try {+ return readConnections(path.join(confDir, "connections.json")).origins;+ } catch (error) {+ writeLog("read connection history failed: " + error.message);+ return [];+ }+ }if (data.cmd === "kernelConnection") {return getKernelConnection(getWindowKernelTarget(event.sender.id));}@@ -3484,6 +3573,7 @@ app.whenReady().then(() => {nodeIntegrationInWorker: false,webviewTag: kernelTarget.mode !== "remote",webSecurity: kernelTarget.mode === "remote",+ ...(kernelTarget.mode === "remote" ? {session: getRemoteSession(kernelTarget)} : {}),autoplayPolicy: "user-gesture-required" // 桌面端禁止自动播放多媒体 https://github.com/siyuan-note/siyuan/issues/7587},});@@ -3985,7 +4075,7 @@ app.whenReady().then(() => {workspaces.forEach(item => {const server = item.kernelTarget.origin;writeLog("sync after system resume [" + server + "/api/sync/performSync" + "]");- session.defaultSession.fetch(server + "/api/sync/performSync", {+ (item.ownsKernel ? session.defaultSession : getRemoteSession(item.kernelTarget)).fetch(server + "/api/sync/performSync", {method: "POST",credentials: item.ownsKernel ? "omit" : "include",bypassCustomProtocolHandlers: !item.ownsKernel,@@ -4206,6 +4296,8 @@ app.on("before-quit", (event) => {});});+app.on("will-quit", relaunchConnection);+function writeLog(out) {console.log(out);const logFile = path.join(confDir, "app.log");diff --git a/app/electron/remote-auth.html b/app/electron/remote-auth.htmlindex cf62a4d303..b9f20975a1 100644--- a/app/electron/remote-auth.html+++ b/app/electron/remote-auth.html@@ -123,6 +123,7 @@<button id="submit" type="submit"></button></form><p id="message" role="alert"></p>+ <button id="connections" type="button"></button></main><script>(() => {@@ -184,6 +185,9 @@ipcRenderer.send("siyuan-quit", window.location.port);}});+ document.getElementById("connections").addEventListener("click", () => {+ ipcRenderer?.send("siyuan-manage-connections", {lang: language});+ });const refreshCaptcha = () => {captchaImageElement.src = "/api/system/getCaptcha?v=" + Date.now();@@ -235,6 +239,7 @@.catch(() => fetch("/appearance/langs/en.json", {cache: "no-store"}).then((response) => response.json())).then((languages) => {document.title = languages._kernel["178"];+ document.getElementById("connections").textContent = languages.workspaceList;document.getElementById("closeWindow").ariaLabel = languages._kernel["177"];document.getElementById("title").textContent = languages._kernel["176"];document.getElementById("origin").textContent = window.location.origin;diff --git a/app/electron/workspace.html b/app/electron/workspace.htmlindex d97ea456ae..f503ba8c05 100644--- a/app/electron/workspace.html+++ b/app/electron/workspace.html@@ -442,5 +442,6 @@});});</script>+<script src="connectionEntry.js"></script></body></html>diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20260903150000-s4hctea.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20260903150000-s4hctea.syindex 5ee8a5c781..2298b9047b 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20260903150000-s4hctea.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20260903150000-s4hctea.sy@@ -6,11 +6,16 @@"id": "20260903150000-s4hctea","title": "Connect to a Remote Kernel","type": "doc",- "updated": "20260908082237"+ "updated": "20260908100358"},"Children": [{"ID": "20260903150000-mz3r596", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-mz3r596", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "Overview"}]},{"ID": "20260903150000-dood0bb", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-dood0bb", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "The desktop app can connect to a SiYuan kernel running on another device and use the local desktop interface for editing. Remote mode only connects to an existing kernel and does not start a kernel on the local device."}]},+ {"ID": "20260908100358-97gqv2l", "Type": "NodeHeading", "Properties": {"id": "20260908100358-97gqv2l", "updated": "20260908100358"}, "Children": [{"Type": "NodeText", "Data": "Connect and switch through the desktop interface"}], "HeadingLevel": 2},+ {"ID": "20260908100358-kpwyker", "Type": "NodeParagraph", "Properties": {"id": "20260908100358-kpwyker", "updated": "20260908100358"}, "Children": [{"Type": "NodeText", "Data": "In the desktop workspace menu, select "}, {"Type": "NodeTextMark", "TextMarkType": "kbd", "TextMarkTextContent": "Workspaces"}, {"Type": "NodeText", "Data": " - "}, {"Type": "NodeTextMark", "TextMarkType": "kbd", "TextMarkTextContent": "Connect to remote kernel..."}, {"Type": "NodeText", "Data": ", enter the remote server’s HTTPS address, and connect. The address must not contain a path, query, username, or password. The client checks the kernel version and login state, then displays an access authorization code field when authentication is required. You can choose to remember your login."}]},+ {"ID": "20260908100358-nvq3oum", "Type": "NodeParagraph", "Properties": {"id": "20260908100358-nvq3oum", "updated": "20260908100358"}, "Children": [{"Type": "NodeText", "Data": "The connection window lists local workspaces and remote connection history together. Select a remote address to reconnect, choose an existing local workspace, or return to the last local workspace. Removing a remote history entry only removes its address; it does not delete server data or clear the login session."}]},+ {"ID": "20260908100358-67icxqc", "Type": "NodeParagraph", "Properties": {"id": "20260908100358-67icxqc", "updated": "20260908100358"}, "Children": [{"Type": "NodeText", "Data": "Switching connections saves and safely closes the open workspaces, then automatically restarts the desktop client with the selected connection. It does not stop or restart remote kernels. Wait for saving and shutdown to finish."}]},+ {"ID": "20260908100358-h2ypcuv", "Type": "NodeParagraph", "Properties": {"id": "20260908100358-h2ypcuv", "updated": "20260908100358"}, "Children": [{"Type": "NodeText", "Data": "The first launch, remote startup, and authentication pages provide access to workspace selection. Connection failures open the connection window, where you can edit the address, retry, or return to a local workspace. Checks can be canceled. Remote history is stored on the client, and authorization codes are not saved as plaintext configuration. GUI connections do not enable remote extension trust by default. Command-line startup remains available."}]},{"ID": "20260903150000-c2oh8cr", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-c2oh8cr", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "Start"}]},{"ID": "20260903150000-601s61t", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-601s61t", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "After completely exiting the SiYuan desktop client, start the desktop app from a command line and append "}, {"Type": "NodeTextMark", "TextMarkType": "code", "TextMarkTextContent": "--remote=https://host[:port]"}, {"Type": "NodeText", "Data": ". If an instance is already running, the single-instance mechanism does not switch its current connection."}]},{"ID": "20260903150000-rir445a", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-rir445a", "updated": "20260908082237"}, "Children": [{"Type": "NodeText", "Data": "Security and Version"}]},diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20260903150000-u4065fm.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20260903150000-u4065fm.syindex ebb216e1a8..dfaf9c4ff8 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20260903150000-u4065fm.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20260903150000-u4065fm.sy@@ -6,7 +6,7 @@"id": "20260903150000-u4065fm","title": "连接远程内核","type": "doc",- "updated": "20260908082237"+ "updated": "20260908100338"},"Children": [{@@ -38,6 +38,11 @@}]},+ {"ID": "20260908100338-b5ef1sw", "Type": "NodeHeading", "Properties": {"id": "20260908100338-b5ef1sw", "updated": "20260908100338"}, "Children": [{"Type": "NodeText", "Data": "图形界面连接与切换"}], "HeadingLevel": 2},+ {"ID": "20260908100338-7lr3clk", "Type": "NodeParagraph", "Properties": {"id": "20260908100338-7lr3clk", "updated": "20260908100338"}, "Children": [{"Type": "NodeText", "Data": "在桌面端的工作空间菜单中选择 "}, {"Type": "NodeTextMark", "TextMarkType": "kbd", "TextMarkTextContent": "工作空间"}, {"Type": "NodeText", "Data": " - "}, {"Type": "NodeTextMark", "TextMarkType": "kbd", "TextMarkTextContent": "连接远程内核..."}, {"Type": "NodeText", "Data": ",输入远程服务器的 HTTPS 地址,然后连接。地址不能包含路径、查询参数或用户名和密码。客户端会检查内核版本和登录状态,需要鉴权时显示访问授权码输入框;可选择记住登录状态。"}]},+ {"ID": "20260908100338-yvellnc", "Type": "NodeParagraph", "Properties": {"id": "20260908100338-yvellnc", "updated": "20260908100338"}, "Children": [{"Type": "NodeText", "Data": "连接窗口统一列出本地工作空间和远程连接历史。点击远程地址可重新连接,也可选择已有的本地工作空间或返回上次使用的本地工作空间。移除远程历史只删除地址记录,不删除服务器上的数据或清除登录状态。"}]},+ {"ID": "20260908100338-5tea9ns", "Type": "NodeParagraph", "Properties": {"id": "20260908100338-5tea9ns", "updated": "20260908100338"}, "Children": [{"Type": "NodeText", "Data": "切换连接时,客户端会通过保存和安全退出流程关闭当前打开的工作空间,然后自动重启并连接所选目标。远程内核不会因此停止或重启。请等待保存和退出完成。"}]},+ {"ID": "20260908100338-ri3ltil", "Type": "NodeParagraph", "Properties": {"id": "20260908100338-ri3ltil", "updated": "20260908100338"}, "Children": [{"Type": "NodeText", "Data": "首次启动页、远程启动等待页和鉴权页提供工作空间入口。连接失败时会打开连接窗口,可修改地址、重试或返回本地;检查过程中可取消。远程连接历史保存在客户端,授权码不会作为明文配置保存。图形界面连接默认不启用远程扩展信任;命令行启动方式仍可使用。"}]},{"ID": "20260903150000-15zokfv","Type": "NodeHeading",diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20260903150000-3qa6edk.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20260903150000-3qa6edk.syindex f4f7bd1a54..1ad7e1ab0e 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20260903150000-3qa6edk.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20260903150000-3qa6edk.sy@@ -6,11 +6,16 @@"id": "20260903150000-3qa6edk","title": "連線至遠端內核","type": "doc",- "updated": "20260908082237"+ "updated": "20260908100358"},"Children": [{"ID": "20260903150000-jrf9aw4", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-jrf9aw4", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "概述"}]},{"ID": "20260903150000-6shebfx", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-6shebfx", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "桌面端可以連線至其他裝置上執行的思源內核,並使用本機桌面介面進行編輯。遠端模式僅用於連線至現有內核,不會在本機啟動內核。"}]},+ {"ID": "20260908100358-u9jb6fe", "Type": "NodeHeading", "Properties": {"id": "20260908100358-u9jb6fe", "updated": "20260908100358"}, "Children": [{"Type": "NodeText", "Data": "圖形介面連線與切換"}], "HeadingLevel": 2},+ {"ID": "20260908100358-1qurfwt", "Type": "NodeParagraph", "Properties": {"id": "20260908100358-1qurfwt", "updated": "20260908100358"}, "Children": [{"Type": "NodeText", "Data": "在桌面端的工作空間選單中選擇 "}, {"Type": "NodeTextMark", "TextMarkType": "kbd", "TextMarkTextContent": "工作空間"}, {"Type": "NodeText", "Data": " - "}, {"Type": "NodeTextMark", "TextMarkType": "kbd", "TextMarkTextContent": "連線至遠端核心..."}, {"Type": "NodeText", "Data": ",輸入遠端伺服器的 HTTPS 網址,然後連線。網址不能包含路徑、查詢參數或使用者名稱和密碼。用戶端會檢查核心版本與登入狀態,需要驗證時顯示存取授權碼輸入框;可選擇記住登入狀態。"}]},+ {"ID": "20260908100358-es7xe07", "Type": "NodeParagraph", "Properties": {"id": "20260908100358-es7xe07", "updated": "20260908100358"}, "Children": [{"Type": "NodeText", "Data": "連線視窗統一列出本機工作空間與遠端連線記錄。點選遠端網址可重新連線,也可選擇既有的本機工作空間或返回上次使用的本機工作空間。移除遠端記錄只刪除網址記錄,不刪除伺服器上的資料或清除登入狀態。"}]},+ {"ID": "20260908100358-wba4bpx", "Type": "NodeParagraph", "Properties": {"id": "20260908100358-wba4bpx", "updated": "20260908100358"}, "Children": [{"Type": "NodeText", "Data": "切換連線時,用戶端會透過儲存與安全結束流程關閉目前開啟的工作空間,然後自動重新啟動並連線至所選目標。遠端核心不會因此停止或重新啟動。請等待儲存與結束完成。"}]},+ {"ID": "20260908100358-f7rav2z", "Type": "NodeParagraph", "Properties": {"id": "20260908100358-f7rav2z", "updated": "20260908100358"}, "Children": [{"Type": "NodeText", "Data": "首次啟動頁、遠端啟動等待頁與驗證頁提供工作空間入口。連線失敗時會開啟連線視窗,可修改網址、重試或返回本機;檢查過程中可取消。遠端連線記錄儲存在用戶端,授權碼不會以明文設定儲存。圖形介面連線預設不啟用遠端擴充套件信任;命令列啟動方式仍可使用。"}]},{"ID": "20260903150000-o9vrit3", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-o9vrit3", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "啟動方式"}]},{"ID": "20260903150000-m5fkfh5", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-m5fkfh5", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "完全結束思源桌面用戶端後,從命令列啟動桌面端並加入參數 "}, {"Type": "NodeTextMark", "TextMarkType": "code", "TextMarkTextContent": "--remote=https://host[:port]"}, {"Type": "NodeText", "Data": "。如果已有執行中的實例,單一實例機制不會切換目前的連線。"}]},{"ID": "20260903150000-l1lghrh", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-l1lghrh", "updated": "20260908082237"}, "Children": [{"Type": "NodeText", "Data": "安全性與版本"}]},diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20260903150000-hpfmx4t.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20260903150000-hpfmx4t.syindex 99263cd391..3fecb0b5c1 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20260903150000-hpfmx4t.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20260903150000-hpfmx4t.sy@@ -6,11 +6,16 @@"id": "20260903150000-hpfmx4t","title": "リモートカーネルへの接続","type": "doc",- "updated": "20260908082237"+ "updated": "20260908100358"},"Children": [{"ID": "20260903150000-ekjy0ld", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-ekjy0ld", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "概要"}]},{"ID": "20260903150000-0adfpc3", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-0adfpc3", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "デスクトップ版では、別のデバイスで動作している SiYuan カーネルに接続し、ローカルのデスクトップ UI から編集できます。リモートモードは既存のカーネルへの接続専用であり、ローカルではカーネルを起動しません。"}]},+ {"ID": "20260908100358-365wfm2", "Type": "NodeHeading", "Properties": {"id": "20260908100358-365wfm2", "updated": "20260908100358"}, "Children": [{"Type": "NodeText", "Data": "画面からの接続と切り替え"}], "HeadingLevel": 2},+ {"ID": "20260908100358-0tb3jc9", "Type": "NodeParagraph", "Properties": {"id": "20260908100358-0tb3jc9", "updated": "20260908100358"}, "Children": [{"Type": "NodeText", "Data": "デスクトップのワークスペースメニューで "}, {"Type": "NodeTextMark", "TextMarkType": "kbd", "TextMarkTextContent": "ワークスペース"}, {"Type": "NodeText", "Data": " - "}, {"Type": "NodeTextMark", "TextMarkType": "kbd", "TextMarkTextContent": "リモートカーネルに接続..."}, {"Type": "NodeText", "Data": " を選択し、リモートサーバーの HTTPS アドレスを入力して接続します。アドレスにパス、クエリ、ユーザー名、パスワードは含められません。クライアントはカーネルのバージョンとログイン状態を確認し、認証が必要な場合はアクセス認証コードの入力欄を表示します。ログイン状態を記憶することもできます。"}]},+ {"ID": "20260908100358-tt94c3t", "Type": "NodeParagraph", "Properties": {"id": "20260908100358-tt94c3t", "updated": "20260908100358"}, "Children": [{"Type": "NodeText", "Data": "接続ウィンドウにはローカルワークスペースとリモート接続履歴がまとめて表示されます。リモートアドレスを選んで再接続するか、既存のローカルワークスペースを選ぶか、最後に使用したローカルワークスペースに戻れます。リモート履歴の削除はアドレスの記録のみを削除し、サーバー上のデータやログイン状態には影響しません。"}]},+ {"ID": "20260908100358-z5xdi86", "Type": "NodeParagraph", "Properties": {"id": "20260908100358-z5xdi86", "updated": "20260908100358"}, "Children": [{"Type": "NodeText", "Data": "接続を切り替えると、開いているワークスペースを保存して安全に終了した後、デスクトップクライアントが自動的に再起動し、選択した接続先を開きます。リモートカーネルは停止も再起動もしません。保存と終了が完了するまでお待ちください。"}]},+ {"ID": "20260908100358-4piqgjo", "Type": "NodeParagraph", "Properties": {"id": "20260908100358-4piqgjo", "updated": "20260908100358"}, "Children": [{"Type": "NodeText", "Data": "初回起動画面、リモート起動待機画面、認証画面からワークスペースを選択できます。接続に失敗すると接続ウィンドウが開き、アドレスの変更、再試行、ローカルへの復帰ができます。確認中の処理はキャンセルできます。リモート接続履歴はクライアントに保存され、認証コードを平文の設定として保存することはありません。画面からの接続では、リモート拡張機能への信頼は既定で無効です。コマンドラインからの起動も引き続き利用できます。"}]},{"ID": "20260903150000-c8khz3k", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-c8khz3k", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "起動方法"}]},{"ID": "20260903150000-bqc7crd", "Type": "NodeParagraph", "Properties": {"id": "20260903150000-bqc7crd", "updated": "20260903150000"}, "Children": [{"Type": "NodeText", "Data": "SiYuan デスクトップクライアントを完全に終了してから、コマンドラインでデスクトップ版を起動し、"}, {"Type": "NodeTextMark", "TextMarkType": "code", "TextMarkTextContent": "--remote=https://host[:port]"}, {"Type": "NodeText", "Data": " パラメーターを追加します。既存のインスタンスが実行中の場合、シングルインスタンス機構によって現在の接続先が切り替わることはありません。"}]},{"ID": "20260903150000-csljqix", "Type": "NodeHeading", "HeadingLevel": 2, "Properties": {"id": "20260903150000-csljqix", "updated": "20260908082237"}, "Children": [{"Type": "NodeText", "Data": "セキュリティとバージョン"}]},diff --git a/app/src/menus/workspace.ts b/app/src/menus/workspace.tsindex 812cb29895..db64ee2299 100644--- a/app/src/menus/workspace.ts+++ b/app/src/menus/workspace.ts@@ -244,12 +244,19 @@ const getZoomSubMenu = () => {return submenu;};-export const workspaceMenu = (app: App, rect: DOMRect) => {+export const workspaceMenu = async (app: App, rect: DOMRect) => {if (!window.siyuan.menus.menu.element.classList.contains("fn__none") &&window.siyuan.menus.menu.element.getAttribute("data-name") === Constants.MENU_BAR_WORKSPACE) {window.siyuan.menus.menu.remove();return;}+ let remoteConnections: string[] = [];+ /// #if !BROWSER+ remoteConnections = await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "remoteConnections"});+ const manageConnections = (origin?: string) => ipcRenderer.send("siyuan-manage-connections", {+ lang: window.siyuan.config.lang, origin,+ });+ /// #endifconst renderMenu = (workspaces: IWorkspace[]) => {window.siyuan.menus.menu.remove();window.siyuan.menus.menu.element.setAttribute("data-name", Constants.MENU_BAR_WORKSPACE);@@ -289,14 +296,19 @@ export const workspaceMenu = (app: App, rect: DOMRect) => {type: "submenu",submenu: dockMenu}).element);- if (!window.siyuan.config.readonly && getHostCapabilities().workspaces) {+ if ((!window.siyuan.config.readonly && getHostCapabilities().workspaces) || !isBrowser()) {let workspaceSubMenu: IMenu[];/// #if !BROWSERworkspaceSubMenu = [{id: "newOrOpenBy",- label: `${window.siyuan.languages.new} / ${window.siyuan.languages.openBy}`,+ label: getHostCapabilities().workspaces+ ? `${window.siyuan.languages.new} / ${window.siyuan.languages.openBy}` : window.siyuan.languages.openBy,iconHTML: "",click: async () => {+ if (!getHostCapabilities().workspaces) {+ manageConnections();+ return;+ }const localPath = await ipcRenderer.invoke(Constants.SIYUAN_GET, {cmd: "showOpenDialog",defaultPath: window.siyuan.config.system.homeDir,@@ -316,10 +328,23 @@ export const workspaceMenu = (app: App, rect: DOMRect) => {});}}];- workspaceSubMenu.push({id: "separator_1", type: "separator"});+ workspaceSubMenu.push({+ id: "connectRemoteKernel",+ label: window.siyuan.languages.connectRemoteKernel,+ icon: "iconCloud",+ click: () => manageConnections(),+ });+ if (workspaces.length + remoteConnections.length > 0) {+ workspaceSubMenu.push({id: "separator_1", type: "separator"});+ }workspaces.forEach((item: IWorkspace) => {workspaceSubMenu.push(workspaceItem(item) as IMenu);});+ remoteConnections.forEach(origin => workspaceSubMenu.push({+ label: escapeHtml(window.siyuan.languages.remoteConnection + " · " + origin),+ icon: "iconCloud",+ click: () => manageConnections(origin),+ }));/// #elseworkspaceSubMenu = [{id: "new",