An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Harden plugin workflow cancellation and recovery https://github.com/siyuan-note/siyuan/issues/20182
Danieldb36718f1f1e
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex abcbd47f5c..ebbb69fe25 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "سير العمل الرسمي لتطوير إضافات الواجهة الأمامية: بعد موافقتك الصريحة، تُستوضح المتطلبات الناقصة وتُعتمد خطة موجزة ثم يُنفّذ العمل في نسخة مُدارة ويُتحقّق منه وتُجهّز الحزمة؛ يتطلب التثبيت والتفعيل إذنًا منفصلًا","agentPluginRecoveryQuestion": "هل تريد استعادة نقطة حفظ الشفرة المصدرية للمقترح المعتمد سابقًا فقط؟ لا تتراجع الاستعادة عن الملاحظات أو بيانات وقت التشغيل أو الإعدادات الأخرى، ولا تسمح بإجراء تغييرات إضافية على الشفرة المصدرية.","agentPluginFlowQuestion": "هل تريد استخدام سير العمل الرسمي لتطوير الإضافات؟","agentPluginFlowYes": "نعم",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 8fd002cd2d..d6e8dff05c 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "Offizieller Ablauf zur Entwicklung von Frontend-Plugins: Nach deiner ausdrücklichen Zustimmung werden fehlende Anforderungen geklärt, ein kurzer Plan bestätigt und die Umsetzung in einer verwalteten Kopie geprüft und paketiert; Installation und Aktivierung erfordern eine separate Genehmigung","agentPluginRecoveryQuestion": "Nur den Quellcode-Prüfpunkt des zuvor genehmigten Vorschlags wiederherstellen? Die Wiederherstellung setzt weder Notizen noch Laufzeitdaten oder andere Einstellungen zurück und erlaubt keine weiteren Quellcodeänderungen.","agentPluginFlowQuestion": "Den offiziellen Ablauf zur Plugin-Entwicklung verwenden?","agentPluginFlowYes": "Ja",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex 99558f74e6..9a206c5843 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "Official frontend plugin development workflow: after you explicitly opt in, clarify missing requirements, confirm a brief plan, implement in a managed copy, validate, and package; installation and activation require separate authorization","agentPluginRecoveryQuestion": "Restore only the source checkpoint of the previously approved proposal? Recovery will not roll back notes, runtime data, or other settings, and does not authorize further source changes.","agentPluginFlowQuestion": "Use the official plugin development workflow?","agentPluginFlowYes": "Yes",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 6100636d2e..466baef888 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "Flujo oficial de desarrollo de plugins de interfaz: tras tu aceptación explícita, se aclaran los requisitos pendientes, se confirma un plan breve y se implementa, valida y empaqueta en una copia gestionada; la instalación y la activación requieren autorización por separado","agentPluginRecoveryQuestion": "¿Restaurar solo el punto de control del código de la propuesta aprobada anteriormente? La recuperación no revierte notas, datos de ejecución ni otros ajustes, y no autoriza más cambios en el código.","agentPluginFlowQuestion": "¿Usar el flujo oficial de desarrollo de plugins?","agentPluginFlowYes": "Sí",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex fd76c2d6c5..154de65fcf 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "Processus officiel de développement de plugins d’interface : après votre accord explicite, clarifier les exigences manquantes, confirmer un plan succinct, réaliser le développement dans une copie gérée, valider et préparer le paquet ; l’installation et l’activation nécessitent une autorisation distincte","agentPluginRecoveryQuestion": "Restaurer uniquement le point de contrôle du code de la proposition précédemment approuvée ? La restauration ne rétablit ni les notes, ni les données d’exécution, ni les autres paramètres, et n’autorise aucune modification supplémentaire du code.","agentPluginFlowQuestion": "Utiliser le processus officiel de développement de plugins ?","agentPluginFlowYes": "Oui",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex f8d379fee3..936e7bbdc7 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "תהליך העבודה הרשמי לפיתוח תוספי ממשק: לאחר הסכמתך המפורשת, מבררים דרישות חסרות, מאשרים תוכנית קצרה, מממשים בעותק מנוהל, מאמתים ואורזים; התקנה והפעלה דורשות הרשאה נפרדת","agentPluginRecoveryQuestion": "לשחזר רק את נקודת הביקורת של קוד המקור מההצעה שאושרה קודם? השחזור אינו מחזיר לאחור הערות, נתוני זמן ריצה או הגדרות אחרות, ואינו מאשר שינויים נוספים בקוד המקור.","agentPluginFlowQuestion": "להשתמש בתהליך הרשמי לפיתוח תוספים?","agentPluginFlowYes": "כן",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex d1f856b47e..4f49826f29 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "फ़्रंटएंड प्लगइन विकास की आधिकारिक प्रक्रिया: आपकी स्पष्ट सहमति के बाद अधूरी आवश्यकताओं को स्पष्ट करना, संक्षिप्त योजना की पुष्टि करना, प्रबंधित प्रति में कार्यान्वयन करना, जाँचना और पैकेज बनाना; स्थापना और सक्रियण के लिए अलग अनुमति आवश्यक है","agentPluginRecoveryQuestion": "क्या पहले मंज़ूर किए गए प्रस्ताव के केवल स्रोत कोड चेकपॉइंट को पुनर्स्थापित करें? पुनर्स्थापन नोट्स, रनटाइम डेटा या अन्य सेटिंग्स को वापस नहीं करेगा और स्रोत कोड में आगे बदलाव की अनुमति नहीं देता है।","agentPluginFlowQuestion": "क्या आधिकारिक प्लगइन विकास प्रक्रिया का उपयोग करें?","agentPluginFlowYes": "हाँ",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex b648112d3b..1e03690305 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "Alur kerja resmi pengembangan plugin antarmuka: setelah Anda menyetujuinya secara eksplisit, perjelas kebutuhan yang belum lengkap, konfirmasi rencana singkat, implementasikan dalam salinan terkelola, validasi, dan kemas; pemasangan dan pengaktifan memerlukan izin terpisah","agentPluginRecoveryQuestion": "Pulihkan hanya titik pemeriksaan kode sumber dari usulan yang sebelumnya disetujui? Pemulihan tidak mengembalikan catatan, data runtime, atau pengaturan lain, dan tidak mengizinkan perubahan kode sumber lebih lanjut.","agentPluginFlowQuestion": "Gunakan alur pengembangan plugin resmi?","agentPluginFlowYes": "Ya",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex a881153be2..a301cd2769 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "Procedura ufficiale per lo sviluppo di plugin frontend: dopo il tuo consenso esplicito, chiarire i requisiti mancanti, confermare un piano sintetico, implementare in una copia gestita, verificare e creare il pacchetto; l’installazione e l’attivazione richiedono un’autorizzazione separata","agentPluginRecoveryQuestion": "Ripristinare solo il punto di controllo del codice della proposta approvata in precedenza? Il ripristino non annulla le modifiche a note, dati di esecuzione o altre impostazioni e non autorizza ulteriori modifiche al codice.","agentPluginFlowQuestion": "Usare il flusso ufficiale di sviluppo dei plugin?","agentPluginFlowYes": "Sì",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex bcb1521f70..629d4a1aa9 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "公式フロントエンドプラグイン開発フロー:ユーザーが明示的に選択した後、不足している要件を確認し、簡潔な計画に合意したうえで、管理対象のコピーで実装・検証・パッケージ化を行います。インストールと有効化には別途許可が必要です","agentPluginRecoveryQuestion": "以前に承認した提案のソースチェックポイントのみを復元しますか?復元してもノート、実行時データ、その他の設定は元に戻らず、ソースの追加変更も許可されません。","agentPluginFlowQuestion": "公式プラグイン開発フローを使用しますか?","agentPluginFlowYes": "はい",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex 364c1a5ce7..25c5383bc0 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "공식 프런트엔드 플러그인 개발 절차: 사용자가 명시적으로 선택한 후 누락된 요구 사항을 확인하고 간단한 계획에 합의한 뒤 관리되는 사본에서 구현, 검증 및 패키징을 수행하며, 설치와 활성화에는 별도의 승인이 필요합니다","agentPluginRecoveryQuestion": "이전에 승인한 제안의 소스 체크포인트만 복원할까요? 복원해도 노트, 런타임 데이터 또는 기타 설정은 되돌아가지 않으며 추가 소스 변경이 허용되지 않습니다.","agentPluginFlowQuestion": "공식 플러그인 개발 절차를 사용할까요?","agentPluginFlowYes": "예",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 158139aa9b..962d236be6 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "Officiële werkwijze voor frontend-pluginontwikkeling: na je uitdrukkelijke toestemming worden ontbrekende vereisten verduidelijkt, wordt een kort plan bevestigd en wordt de plugin in een beheerde kopie geïmplementeerd, gevalideerd en verpakt; installatie en activering vereisen afzonderlijke toestemming","agentPluginRecoveryQuestion": "Alleen het broncodecontrolepunt van het eerder goedgekeurde voorstel herstellen? Het herstel draait geen notities, runtimegegevens of andere instellingen terug en geeft geen toestemming voor verdere broncodewijzigingen.","agentPluginFlowQuestion": "De officiële workflow voor pluginontwikkeling gebruiken?","agentPluginFlowYes": "Ja",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex d18ea63ca8..867f1b1c47 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "Oficjalny proces tworzenia wtyczek interfejsu: po wyraźnej zgodzie użytkownika następuje doprecyzowanie brakujących wymagań, zatwierdzenie krótkiego planu, implementacja w zarządzanej kopii, weryfikacja i przygotowanie pakietu; instalacja i aktywacja wymagają osobnej zgody","agentPluginRecoveryQuestion": "Przywrócić tylko punkt kontrolny kodu wcześniej zatwierdzonego planu? Odzyskiwanie nie cofa notatek, danych wykonania ani innych ustawień i nie zezwala na dalsze zmiany kodu.","agentPluginFlowQuestion": "Użyć oficjalnego procesu tworzenia wtyczek?","agentPluginFlowYes": "Tak",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex 2d324bc87e..3083bd1e99 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "Fluxo oficial de desenvolvimento de plugins de interface: após sua aceitação explícita, esclarecer os requisitos pendentes, confirmar um plano breve, implementar em uma cópia gerenciada, validar e empacotar; a instalação e a ativação exigem autorização separada","agentPluginRecoveryQuestion": "Restaurar apenas o ponto de controle do código da proposta aprovada anteriormente? A recuperação não reverte notas, dados de execução ou outras configurações e não autoriza novas alterações no código.","agentPluginFlowQuestion": "Usar o fluxo oficial de desenvolvimento de plugins?","agentPluginFlowYes": "Sim",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex f18a7f538d..b63d620767 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "Официальный процесс разработки плагинов интерфейса: после явного согласия пользователя уточняются недостающие требования, утверждается краткий план, выполняются реализация в управляемой копии, проверка и упаковка; установка и активация требуют отдельного разрешения","agentPluginRecoveryQuestion": "Восстановить только контрольную точку исходного кода ранее одобренного плана? Восстановление не откатывает заметки, данные выполнения или другие настройки и не разрешает дальнейшие изменения исходного кода.","agentPluginFlowQuestion": "Использовать официальный процесс разработки плагинов?","agentPluginFlowYes": "Да",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex e6ce1abad7..9c1441991b 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "Oficiálny postup vývoja doplnkov rozhrania: po výslovnom súhlase používateľa sa objasnia chýbajúce požiadavky, potvrdí stručný plán a v spravovanej kópii sa vykoná implementácia, overenie a vytvorenie balíka; inštalácia a aktivácia vyžadujú samostatné povolenie","agentPluginRecoveryQuestion": "Obnoviť iba kontrolný bod zdrojového kódu predtým schváleného návrhu? Obnova nevráti poznámky, údaje za behu ani iné nastavenia a nepovoľuje ďalšie zmeny zdrojového kódu.","agentPluginFlowQuestion": "Použiť oficiálny postup vývoja doplnkov?","agentPluginFlowYes": "Áno",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex 6737ce985d..69c5244285 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "Званични поступак развоја додатака за кориснички интерфејс: након изричите сагласности корисника разјашњавају се недостајући захтеви, потврђује кратак план и у управљаној копији спроводе израда, провера и паковање; инсталација и активирање захтевају посебно одобрење","agentPluginRecoveryQuestion": "Вратити само контролну тачку изворног кода претходно одобреног предлога? Опоравак не враћа белешке, податке извршавања или друга подешавања и не одобрава даље измене изворног кода.","agentPluginFlowQuestion": "Користити званични поступак развоја додатака?","agentPluginFlowYes": "Да",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 71911251aa..48eadbeb90 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "ขั้นตอนการพัฒนาปลั๊กอินส่วนหน้าทางการ: หลังจากผู้ใช้ยินยอมอย่างชัดเจน จึงชี้แจงข้อกำหนดที่ยังขาด ยืนยันแผนโดยย่อ พัฒนาในสำเนาที่จัดการให้ ตรวจสอบ และจัดแพ็กเกจ โดยการติดตั้งและเปิดใช้งานต้องได้รับอนุญาตแยกต่างหาก","agentPluginRecoveryQuestion": "กู้คืนเฉพาะจุดตรวจสอบซอร์สโค้ดของข้อเสนอที่อนุมัติไว้ก่อนหน้านี้หรือไม่? การกู้คืนจะไม่ย้อนคืนบันทึก ข้อมูลขณะทำงาน หรือการตั้งค่าอื่น และไม่อนุญาตให้แก้ไขซอร์สโค้ดเพิ่มเติม","agentPluginFlowQuestion": "ใช้ขั้นตอนการพัฒนาปลั๊กอินอย่างเป็นทางการหรือไม่?","agentPluginFlowYes": "ใช่",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex ceedd97697..b7adbbeb0b 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "Resmî ön yüz eklentisi geliştirme süreci: açık onayınızın ardından eksik gereksinimler netleştirilir, kısa bir plan onaylanır ve yönetilen bir kopyada geliştirme, doğrulama ve paketleme yapılır; yükleme ve etkinleştirme için ayrı izin gerekir","agentPluginRecoveryQuestion": "Yalnızca daha önce onaylanan önerinin kaynak kodu kontrol noktası geri yüklensin mi? Kurtarma; notları, çalışma zamanı verilerini veya diğer ayarları geri almaz ve kaynak kodunda başka değişikliklere izin vermez.","agentPluginFlowQuestion": "Resmî eklenti geliştirme iş akışı kullanılsın mı?","agentPluginFlowYes": "Evet",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 95bf0529de..d1c88a5069 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "Офіційний процес розробки плагінів інтерфейсу: після явної згоди користувача уточнюються відсутні вимоги, затверджується стислий план, виконуються реалізація в керованій копії, перевірка та пакування; установлення й активація потребують окремого дозволу","agentPluginRecoveryQuestion": "Відновити лише контрольну точку вихідного коду раніше схваленого плану? Відновлення не відкочує нотатки, дані виконання чи інші налаштування та не дозволяє подальших змін вихідного коду.","agentPluginFlowQuestion": "Використовувати офіційний процес розробки плагінів?","agentPluginFlowYes": "Так",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 3d583810ec..75b42d0ab6 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "官方前端插件开发流程:在用户明确选择后澄清缺失要求、确认简短方案、使用受管副本实现、验证和打包;安装与启用另行授权","agentPluginRecoveryQuestion": "是否只恢复此前已确认方案的源码检查点?恢复不会回退笔记、运行时数据或其他配置,也不授权继续修改源码。","agentPluginFlowQuestion": "是否使用官方插件开发流程?","agentPluginFlowYes": "是",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex 50d427dccf..e572ea41b1 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,5 @@{+ "agentBuiltinPluginDevelopmentDescription": "官方前端外掛開發流程:在使用者明確選擇後釐清缺漏需求、確認簡短方案、使用受管理的副本實作、驗證及封裝;安裝與啟用須另行授權","agentPluginRecoveryQuestion": "是否僅還原先前已確認方案的原始碼檢查點?還原不會回復筆記、執行階段資料或其他設定,也不授權繼續修改原始碼。","agentPluginFlowQuestion": "是否使用官方外掛開發流程?","agentPluginFlowYes": "是",diff --git a/app/src/config/tabs/ai/aiBuiltinSkillView.test.ts b/app/src/config/tabs/ai/aiBuiltinSkillView.test.tsindex 790f10755d..1d3892b2c6 100644--- a/app/src/config/tabs/ai/aiBuiltinSkillView.test.ts+++ b/app/src/config/tabs/ai/aiBuiltinSkillView.test.ts@@ -3,6 +3,7 @@ import {readFileSync} from "node:fs";import {runInNewContext} from "node:vm";import test from "node:test";import {ModuleKind, transpileModule} from "typescript";+import {escapeAttr, escapeHtml} from "../../../util/escape";import {setBuiltinSkillEnabled, setUserSkillEnabled} from "./aiSkillState";class ElementStub {@@ -30,7 +31,7 @@ class ElementStub {querySelectorAll() { return this.elements.input ? [this.elements.input] : []; }}-const loadView = () => {+const loadView = (languages: Record<string, string> = new Proxy({}, {get: (_object, key) => String(key)})) => {const source = readFileSync("src/config/tabs/ai/aiSkillUi.ts", "utf8");const code = transpileModule(source, {compilerOptions: {module: ModuleKind.CommonJS}}).outputText;const root = new ElementStub();@@ -50,9 +51,9 @@ const loadView = () => {exports,HTMLElement: ElementStub,document: {createElement: () => view},- window: {siyuan: {config, languages: new Proxy({}, {get: (_object, key) => String(key)})}},+ window: {siyuan: {config, languages}},require: (name: string) => {- if (name.endsWith("/escape")) return {escapeHtml: (text: string) => text, escapeAttr: (text: string) => text};+ if (name.endsWith("/escape")) return {escapeHtml, escapeAttr};if (name.endsWith("/fetch")) return {fetchPost: (url: string, _data: unknown, callback: (response: unknown) => void) => new Promise<void>(resolve => {requests.push({url, finish: data => { if (data) callback({data}); resolve(); }});})};@@ -77,6 +78,54 @@ const loadView = () => {const builtin = {id: "builtin:siyuan-plugin-development", name: "siyuan-plugin-development", description: "official", version: "1.0.0", enabled: true};const flush = async () => { await Promise.resolve(); await Promise.resolve(); };+for (const locale of ["en", "ja", "zh-TW"]) {+ test(`official plugin skill description uses the ${locale} UI language without changing metadata`, () => {+ const languages = JSON.parse(readFileSync(`appearance/langs/${locale}.json`, "utf8"));+ const description = languages.agentBuiltinPluginDevelopmentDescription;+ assert.ok(description);+ const skill = {...builtin};+ const state = loadView(languages);+ state.open();+ state.requests[0].finish([skill]);+ assert.ok(state.list.innerHTML.includes(`<div class="b3-label__text">${escapeHtml(description)}</div>`));+ assert.ok(!state.list.innerHTML.includes(`<div class="b3-label__text">${builtin.description}</div>`));+ assert.match(state.list.innerHTML, /builtin:siyuan-plugin-development · 1.0.0/);+ assert.deepEqual(skill, builtin);+ });+}++test("official plugin skill localization does not depend on a metadata description", () => {+ const state = loadView({agentBuiltinPluginDevelopmentDescription: "Localized <workflow> & details"});+ state.open();+ state.requests[0].finish([{...builtin, description: ""}]);+ assert.ok(state.list.innerHTML.includes("Localized <workflow> & details"));+});++test("unknown official skills and user skills preserve their escaped metadata descriptions", () => {+ const languages = {agentBuiltinPluginDevelopmentDescription: "Localized official workflow"};+ for (const {official, id} of [+ {official: true, id: "builtin:future"},+ {official: true, id: builtin.name},+ {official: false, id: builtin.name},+ {official: false, id: builtin.id},+ ]) {+ const state = loadView(languages);+ state.open(official);+ state.requests[0].finish([{...builtin, id, description: "Original <workflow> & details"}]);+ assert.ok(state.list.innerHTML.includes("Original <workflow> & details"));+ assert.ok(!state.list.innerHTML.includes(languages.agentBuiltinPluginDevelopmentDescription));+ }+});++test("official plugin skill falls back to metadata when localization is unavailable", () => {+ for (const languages of [{}, {agentBuiltinPluginDevelopmentDescription: ""}]) {+ const state = loadView(languages);+ state.open();+ state.requests[0].finish([{...builtin, description: "Metadata <workflow> & details"}]);+ assert.ok(state.list.innerHTML.includes("Metadata <workflow> & details"));+ }+});+test("skill settings ignore responses after Back and newer navigation", () => {const state = loadView();state.open();diff --git a/app/src/config/tabs/ai/aiSkillUi.ts b/app/src/config/tabs/ai/aiSkillUi.tsindex f2fc0d5652..e339bb6128 100644--- a/app/src/config/tabs/ai/aiSkillUi.ts+++ b/app/src/config/tabs/ai/aiSkillUi.ts@@ -77,15 +77,19 @@ const renderUserSkills = (root: HTMLElement, skills: IUserSkillInfo[], builtin:list.innerHTML = `<div class="b3-label config-item"><div class="b3-label__text">${builtin ? window.siyuan.languages.empty : window.siyuan.languages.agentUserSkillsEmpty}</div></div>`;return;}- list.innerHTML = `${skills.map((skill) => `<label class="fn__flex b3-label config-item" data-user-skill-id="${escapeAttribute(skill.id)}">+ list.innerHTML = `${skills.map((skill) => {+ const description = builtin && skill.id === "builtin:siyuan-plugin-development" ?+ window.siyuan.languages.agentBuiltinPluginDevelopmentDescription || skill.description : skill.description;+ return `<label class="fn__flex b3-label config-item" data-user-skill-id="${escapeAttribute(skill.id)}"><div class="fn__flex-1"><div class="config-name">${escapeHtml(skill.name)}</div>- ${skill.description ? `<div class="b3-label__text">${escapeHtml(skill.description)}</div>` : ""}+ ${description ? `<div class="b3-label__text">${escapeHtml(description)}</div>` : ""}<div class="b3-label__text"><code>${builtin ? `${escapeHtml(skill.id)} · ${escapeHtml(skill.version || "")}` : `~/.agents/skills/${escapeHtml(skill.id)}`}</code>${skill.shadowed ? ` · ${window.siyuan.languages.agentUserSkillShadowed}` : ""}</div></div><span class="fn__space"></span><input class="b3-switch" data-type="toggleAgentUserSkill" type="checkbox" aria-label="${escapeAttribute(skill.name)}"${skill.enabled ? " checked" : ""}>-</label>`).join("")}`;+</label>`;+ }).join("")}`;};const openUserSkillsView = (settingRoot: HTMLElement, skills: IUserSkillInfo[], builtin: boolean, request: string) => {diff --git a/kernel/bazaar/install.go b/kernel/bazaar/install.goindex ef9d2e72df..bdde9147d5 100644--- a/kernel/bazaar/install.go+++ b/kernel/bazaar/install.go@@ -19,24 +19,25 @@ package bazaarimport ("archive/zip""bytes"+ "context""errors""fmt""os""path/filepath""strings"- "sync""time""github.com/imroc/req/v3""github.com/siyuan-note/httpclient""github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/util"+ "golang.org/x/sync/semaphore""golang.org/x/sync/singleflight")var downloadPackageFlight singleflight.Groupvar bazaarDownloadCloudServer = util.GetCloudServer-var packageInstallLock sync.Mutex+var packageInstallLock = semaphore.NewWeighted(1)// downloadBazaarFile 下载集市文件func downloadBazaarFile(repoURLHash string, pushProgress bool) (data []byte, err error) {@@ -223,8 +224,13 @@ func replacePackageDirectory(sourcePath, installPath string, update bool) error}func replacePackageDirectoryWithOptions(sourcePath, installPath string, update bool, options PackageInstallOptions) (result *PackageInstallResult, err error) {- packageInstallLock.Lock()- defer packageInstallLock.Unlock()+ if err = packageInstallLock.Acquire(options.context(), 1); err != nil {+ return nil, err+ }+ defer packageInstallLock.Release(1)+ if err = options.check(); err != nil {+ return nil, err+ }if err = validateInstalledRevision(options.ExpectedInstalledRevision); err != nil {return}@@ -307,6 +313,10 @@ func replacePackageDirectoryWithOptions(sourcePath, installPath string, update bif finalStagingRevision != stagingRevision {return result, ErrInstalledRevisionConflict}+ // 最后一次取消和授权检查紧邻提交点;开始替换后必须完成提交或回滚并返回真实结果。+ if err = options.check(); err != nil {+ return result, err+ }if targetExists {if err = os.Rename(installPath, backupPath); err != nil {return@@ -355,8 +365,10 @@ func InstallLocalPackageWithOptions(sourcePath, installPath, pkgType, packageNam// UninstallPackage 卸载集市包func UninstallPackage(installPath string) (err error) {- packageInstallLock.Lock()- defer packageInstallLock.Unlock()+ if err = packageInstallLock.Acquire(context.Background(), 1); err != nil {+ return err+ }+ defer packageInstallLock.Release(1)if err = os.RemoveAll(installPath); err != nil {logging.LogErrorf("remove [%s] failed: %s", installPath, err)diff --git a/kernel/bazaar/install_cancel_test.go b/kernel/bazaar/install_cancel_test.gonew file mode 100644index 0000000000..e77df8e80f--- /dev/null+++ b/kernel/bazaar/install_cancel_test.go@@ -0,0 +1,112 @@+package bazaar++import (+ "archive/zip"+ "bytes"+ "context"+ "errors"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++func TestLocalInstallCancellationWhileWaitingForPackageLock(t *testing.T) {+ source, target := useInstallRevisionFixture(t)+ options := installRevisionOptions(target)+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ options.Context = ctx+ if err := packageInstallLock.Acquire(context.Background(), 1); err != nil {+ t.Fatal(err)+ }+ defer packageInstallLock.Release(1)+ done := make(chan error, 1)+ go func() {+ _, err := replacePackageDirectoryWithOptions(source, target, true, options)+ done <- err+ }()+ cancel()+ select {+ case err := <-done:+ if !errors.Is(err, context.Canceled) {+ t.Fatal(err)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("canceled installation kept waiting for the package lock")+ }+ if data, err := os.ReadFile(filepath.Join(target, "index.js")); err != nil || string(data) != "old" {+ t.Fatal("canceled installation replaced target", err)+ }+}++func TestLocalInstallCancellationImmediatelyBeforeReplacement(t *testing.T) {+ source, target := useInstallRevisionFixture(t)+ options := installRevisionOptions(target)+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ options.Context = ctx+ options.BeforeReplace = func() error { cancel(); return nil }+ if _, err := replacePackageDirectoryWithOptions(source, target, true, options); !errors.Is(err, context.Canceled) {+ t.Fatalf("late cancellation was ignored: %v", err)+ }+ if data, err := os.ReadFile(filepath.Join(target, "index.js")); err != nil || string(data) != "old" {+ t.Fatal("late cancellation replaced target", err)+ }+ entries, err := os.ReadDir(filepath.Dir(target))+ if err != nil || len(entries) != 1 {+ t.Fatal("canceled staging directory was retained", entries, err)+ }+}++func TestLocalInstallRechecksApprovalAtReplacement(t *testing.T) {+ source, target := useInstallRevisionFixture(t)+ options := installRevisionOptions(target)+ ready := false+ changed := errors.New("approval is no longer current")+ options.BeforeReplace = func() error { ready = true; return nil }+ options.Recheck = func() error {+ if ready {+ return changed+ }+ return nil+ }+ if _, err := replacePackageDirectoryWithOptions(source, target, true, options); !errors.Is(err, changed) {+ t.Fatalf("approval was not rechecked at replacement: %v", err)+ }+ if data, err := os.ReadFile(filepath.Join(target, "index.js")); err != nil || string(data) != "old" {+ t.Fatal("changed approval replaced target", err)+ }+}++type cancelExtractionContext struct {+ context.Context+ checks int+}++func (ctx *cancelExtractionContext) Err() error {+ ctx.checks+++ if ctx.checks >= 4 {+ return context.Canceled+ }+ return nil+}++func TestLocalPackageExtractionObservesCancellationDuringFile(t *testing.T) {+ content := strings.Repeat("code", 32768)+ data := buildInstallPackageArchive(t, map[string]string{"index.js": content})+ reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))+ if err != nil {+ t.Fatal(err)+ }+ ctx := &cancelExtractionContext{Context: context.Background()}+ destination := t.TempDir()+ if err = extractLocalPackageReaderContext(ctx, reader, destination); !errors.Is(err, context.Canceled) {+ t.Fatalf("extraction ignored cancellation: %v", err)+ }+ info, err := os.Stat(filepath.Join(destination, "index.js"))+ if err != nil || info.Size() <= 0 || info.Size() >= int64(len(content)) {+ t.Fatal("cancellation did not interrupt the file's contents", info, err)+ }+}diff --git a/kernel/bazaar/install_revision.go b/kernel/bazaar/install_revision.goindex d80379d7a7..1eb1804a27 100644--- a/kernel/bazaar/install_revision.go+++ b/kernel/bazaar/install_revision.go@@ -5,6 +5,7 @@package bazaarimport (+ "context""crypto/sha256""encoding/hex""errors"@@ -31,6 +32,27 @@ type PackageInstallOptions struct {ExpectedInstalledRevision stringPrivateTemp boolBeforeReplace func() error+ Context context.Context+ Recheck func() error+}++func (options PackageInstallOptions) context() context.Context {+ if options.Context == nil {+ return context.Background()+ }+ return options.Context+}++func (options PackageInstallOptions) check() error {+ if err := options.context().Err(); err != nil {+ return err+ }+ if options.Recheck != nil {+ if err := options.Recheck(); err != nil {+ return err+ }+ }+ return options.context().Err()}type PackageInstallResult struct {@@ -52,8 +74,10 @@ func validateInstalledRevision(revision string) error {// InstalledPackageRevision 在与安装、卸载相同的锁内读取完整代码目录摘要。func InstalledPackageRevision(installPath string) (string, error) {- packageInstallLock.Lock()- defer packageInstallLock.Unlock()+ if err := packageInstallLock.Acquire(context.Background(), 1); err != nil {+ return "", err+ }+ defer packageInstallLock.Release(1)if err := rejectInstallPathLinks(installPath); err != nil {return "", err}diff --git a/kernel/bazaar/local.go b/kernel/bazaar/local.goindex 2e4862a73d..c4e3458346 100644--- a/kernel/bazaar/local.go+++ b/kernel/bazaar/local.go@@ -19,6 +19,7 @@ package bazaarimport ("archive/zip""bytes"+ "context""crypto/sha256""errors""fmt"@@ -49,17 +50,25 @@ var localPackageManifests = map[string]string{// ExtractLocalPackage 将本地集市包解压到临时目录并识别包类型。func ExtractLocalPackage(archivePath string) (pkgType string, pkg *Package, packagePath string, cleanup func(), err error) {- pkgType, pkg, packagePath, _, cleanup, err = extractLocalPackageWithHash(archivePath, "", false)+ pkgType, pkg, packagePath, _, cleanup, err = extractLocalPackageWithHash(context.Background(), archivePath, "", false)return}// ExtractLocalPackageWithHash 从同一份已核验字节解压,不会在摘要验证后重新打开原始路径。func ExtractLocalPackageWithHash(archivePath, expectedHash string) (pkgType string, pkg *Package, packagePath, packageHash string, cleanup func(), err error) {- return extractLocalPackageWithHash(archivePath, expectedHash, true)+ return ExtractLocalPackageWithHashContext(context.Background(), archivePath, expectedHash)}-func extractLocalPackageWithHash(archivePath, expectedHash string, private bool) (pkgType string, pkg *Package, packagePath, packageHash string, cleanup func(), err error) {+// ExtractLocalPackageWithHashContext 在核验与解压期间响应取消,未提交的临时内容会清理。+func ExtractLocalPackageWithHashContext(ctx context.Context, archivePath, expectedHash string) (pkgType string, pkg *Package, packagePath, packageHash string, cleanup func(), err error) {+ return extractLocalPackageWithHash(ctx, archivePath, expectedHash, true)+}++func extractLocalPackageWithHash(ctx context.Context, archivePath, expectedHash string, private bool) (pkgType string, pkg *Package, packagePath, packageHash string, cleanup func(), err error) {cleanup = func() {}+ if err = ctx.Err(); err != nil {+ return+ }if expectedHash != "" && !validInstallHash(expectedHash) {err = errors.New("invalid package hash")return@@ -73,6 +82,9 @@ func extractLocalPackageWithHash(archivePath, expectedHash string, private bool)err = ErrPackageHashConflictreturn}+ if err = ctx.Err(); err != nil {+ return+ }tempPath := filepath.Join(util.TempDir, "bazaar", "local", gulu.Rand.String(7))if private {root := filepath.Join(installPrivateRoot(), "install-operations")@@ -91,7 +103,7 @@ func extractLocalPackageWithHash(archivePath, expectedHash string, private bool)cleanup()return}- if err = extractLocalPackageReader(reader, tempPath); err != nil {+ if err = extractLocalPackageReaderContext(ctx, reader, tempPath); err != nil {cleanup()return}@@ -145,6 +157,13 @@ func extractLocalPackageArchive(archivePath, destination string) error {}func extractLocalPackageReader(reader *zip.Reader, destination string) error {+ return extractLocalPackageReaderContext(context.Background(), reader, destination)+}++func extractLocalPackageReaderContext(ctx context.Context, reader *zip.Reader, destination string) error {+ if err := ctx.Err(); err != nil {+ return err+ }if err := validateLocalPackageArchive(reader); err != nil {return err}@@ -153,11 +172,14 @@ func extractLocalPackageReader(reader *zip.Reader, destination string) error {}var extractedTotal uint64for _, item := range reader.File {- if err := extractLocalPackageItem(item, destination, &extractedTotal); err != nil {+ if err := ctx.Err(); err != nil {+ return err+ }+ if err := extractLocalPackageItem(ctx, item, destination, &extractedTotal); err != nil {return err}}- return nil+ return ctx.Err()}func validateLocalPackageArchive(reader *zip.Reader) error {@@ -291,7 +313,19 @@ func InspectLocalPackageWithHash(archivePath, expectedHash string) (pkgType strireturn}-func extractLocalPackageItem(item *zip.File, destination string, extractedTotal *uint64) error {+type localPackageContextReader struct {+ ctx context.Context+ reader io.Reader+}++func (reader localPackageContextReader) Read(data []byte) (int, error) {+ if err := reader.ctx.Err(); err != nil {+ return 0, err+ }+ return reader.reader.Read(data)+}++func extractLocalPackageItem(ctx context.Context, item *zip.File, destination string, extractedTotal *uint64) error {name := strings.ReplaceAll(item.Name, "\\", "/")if name == "" || strings.HasPrefix(name, "/") {return errors.New("marketplace package contains an invalid path")@@ -321,7 +355,7 @@ func extractLocalPackageItem(item *zip.File, destination string, extractedTotalif err != nil {return err}- written, copyErr := io.Copy(target, io.LimitReader(source, int64(maxLocalPackageFileSize)+1))+ written, copyErr := io.Copy(target, io.LimitReader(localPackageContextReader{ctx: ctx, reader: source}, int64(maxLocalPackageFileSize)+1))closeErr := target.Close()if copyErr != nil {return copyErrdiff --git a/kernel/mcp/tools/bazaar.go b/kernel/mcp/tools/bazaar.goindex 53a0b0ec25..4b6d8a83eb 100644--- a/kernel/mcp/tools/bazaar.go+++ b/kernel/mcp/tools/bazaar.go@@ -230,6 +230,7 @@ func bazaarHandler(ctx context.Context, args map[string]any) (CallToolResult, erexpectedInstalled, _ := args["expectedInstalledRevision"].(string)var archive stringvar err error+ installOptions := model.LocalBazaarInstallOptions{ExpectedPackageHash: expectedHash, ExpectedInstalledRevision: expectedInstalled, Context: ctx}if util.IsPluginProjectPath(filepath.Join(util.WorkspaceDir, filepath.FromSlash(path))) || bazaar.IsPluginProjectDeliveryPath(filepath.Join(util.WorkspaceDir, filepath.FromSlash(path))) {taskID, _ := args["taskId"].(string)if expectedHash == "" || expectedInstalled == "" {@@ -243,6 +244,7 @@ func bazaarHandler(ctx context.Context, args map[string]any) (CallToolResult, erreturn blockToolError("frontend differs from the approved plugin development plan")}archive, err = bazaar.ResolvePluginProjectArtifact(ctx, taskID, path, expectedHash)+ installOptions.Recheck = func() error { return util.RecheckPluginProjectGrant(ctx, grant) }} else {archive, err = resolvePath(path)}@@ -263,7 +265,7 @@ func bazaarHandler(ctx context.Context, args map[string]any) (CallToolResult, er}}overwrite, _ := args["overwrite"].(bool)- result, err := model.InstallLocalBazaarPackageWithOptions(archive, frontend, overwrite, model.LocalBazaarInstallOptions{ExpectedPackageHash: expectedHash, ExpectedInstalledRevision: expectedInstalled})+ result, err := model.InstallLocalBazaarPackageWithOptions(archive, frontend, overwrite, installOptions)if err != nil {return bazaarProjectError(err, result)}diff --git a/kernel/model/bazaar.go b/kernel/model/bazaar.goindex 505036786c..944ab46405 100644--- a/kernel/model/bazaar.go+++ b/kernel/model/bazaar.go@@ -32,6 +32,7 @@ import ("github.com/siyuan-note/siyuan/kernel/bazaar""github.com/siyuan-note/siyuan/kernel/util""golang.org/x/mod/semver"+ "golang.org/x/sync/semaphore""golang.org/x/sync/singleflight")@@ -114,12 +115,14 @@ type LocalBazaarPackageInstallResult struct {type LocalBazaarInstallOptions struct {ExpectedPackageHash stringExpectedInstalledRevision string+ Context context.Context+ Recheck func() error}var (ErrLocalBazaarPackageExists = errors.New("marketplace package already exists")ErrLocalBazaarPackageIncompatible = errors.New("marketplace package is incompatible")- localBazaarInstallLock sync.Mutex+ localBazaarInstallLock = semaphore.NewWeighted(1))// updatePackages 更新一组集市包;同类型批量更新时,安装后处理只执行一次@@ -662,11 +665,32 @@ func InstallLocalBazaarPackage(archivePath, frontend string, overwrite bool) (re}func InstallLocalBazaarPackageWithOptions(archivePath, frontend string, overwrite bool, options LocalBazaarInstallOptions) (result *LocalBazaarPackageInstallResult, err error) {- pkgType, pkg, sourcePath, packageHash, cleanup, err := bazaar.ExtractLocalPackageWithHash(archivePath, options.ExpectedPackageHash)+ ctx := options.Context+ if ctx == nil {+ ctx = context.Background()+ }+ check := func() error {+ if err := ctx.Err(); err != nil {+ return err+ }+ if options.Recheck != nil {+ if err := options.Recheck(); err != nil {+ return err+ }+ }+ return ctx.Err()+ }+ if err = check(); err != nil {+ return nil, err+ }+ pkgType, pkg, sourcePath, packageHash, cleanup, err := bazaar.ExtractLocalPackageWithHashContext(ctx, archivePath, options.ExpectedPackageHash)if err != nil {return nil, err}defer cleanup()+ if err = check(); err != nil {+ return nil, err+ }result = &LocalBazaarPackageInstallResult{PackageType: pkgType,@@ -689,8 +713,13 @@ func InstallLocalBazaarPackageWithOptions(archivePath, frontend string, overwritreturn result, ErrLocalBazaarPackageIncompatible}- localBazaarInstallLock.Lock()- defer localBazaarInstallLock.Unlock()+ if err = localBazaarInstallLock.Acquire(ctx, 1); err != nil {+ return result, err+ }+ defer localBazaarInstallLock.Release(1)+ if err = check(); err != nil {+ return result, err+ }containsFile, statErr := bazaar.PackageDirContainsFile(installPath)if statErr != nil && !os.IsNotExist(statErr) {return result, statErr@@ -699,7 +728,7 @@ func InstallLocalBazaarPackageWithOptions(archivePath, frontend string, overwritif result.Updated && !overwrite {return result, ErrLocalBazaarPackageExists}- installOptions := bazaar.PackageInstallOptions{ExpectedInstalledRevision: options.ExpectedInstalledRevision}+ installOptions := bazaar.PackageInstallOptions{ExpectedInstalledRevision: options.ExpectedInstalledRevision, Context: ctx, Recheck: check}installed, err := bazaar.InstallLocalPackageWithOptions(sourcePath, installPath, pkgType, pkg.Name, result.Updated, installOptions)if installed != nil {result.InstalledRevision, result.PreviousRevision = installed.InstalledRevision, installed.PreviousRevisiondiff --git a/kernel/model/bazaar_install_cancel_test.go b/kernel/model/bazaar_install_cancel_test.gonew file mode 100644index 0000000000..67e6856bac--- /dev/null+++ b/kernel/model/bazaar_install_cancel_test.go@@ -0,0 +1,76 @@+package model++import (+ "context"+ "errors"+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/siyuan-note/siyuan/kernel/bazaar"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestLocalBazaarInstallCancellationWhileWaitingForModelLock(t *testing.T) {+ setupBoundInstallModel(t)+ archive, hash := writeBoundInstallArchive(t, "new")+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ if err := localBazaarInstallLock.Acquire(context.Background(), 1); err != nil {+ t.Fatal(err)+ }+ defer localBazaarInstallLock.Release(1)+ afterExtraction := make(chan struct{})+ checks := 0+ done := make(chan error, 1)+ go func() {+ _, err := InstallLocalBazaarPackageWithOptions(archive, "", true, LocalBazaarInstallOptions{+ Context: ctx, ExpectedPackageHash: hash, ExpectedInstalledRevision: bazaar.MissingInstalledRevision,+ Recheck: func() error {+ checks+++ if checks == 2 {+ close(afterExtraction)+ }+ return nil+ },+ })+ done <- err+ }()+ select {+ case <-afterExtraction:+ case <-time.After(5 * time.Second):+ t.Fatal("installation did not reach the model lock")+ }+ cancel()+ select {+ case err := <-done:+ if !errors.Is(err, context.Canceled) {+ t.Fatal(err)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("canceled installation kept waiting for the model lock")+ }+ if _, err := os.Stat(filepath.Join(util.DataDir, "plugins", "sample")); !os.IsNotExist(err) {+ t.Fatal("canceled installation created target", err)+ }+}++func TestLocalBazaarInstallKeepsCommittedResultAfterCancellation(t *testing.T) {+ setupBoundInstallModel(t)+ archive, hash := writeBoundInstallArchive(t, "new")+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ previous := pushBazaarChanged+ pushBazaarChanged = func(string) { cancel() }+ t.Cleanup(func() { pushBazaarChanged = previous })+ result, err := InstallLocalBazaarPackageWithOptions(archive, "", true, LocalBazaarInstallOptions{+ Context: ctx, ExpectedPackageHash: hash, ExpectedInstalledRevision: bazaar.MissingInstalledRevision,+ })+ if err != nil || result == nil || result.InstalledRevision == "" || ctx.Err() == nil {+ t.Fatalf("committed installation reported as canceled: %+v, %v", result, err)+ }+ if data, err := os.ReadFile(filepath.Join(util.DataDir, "plugins", "sample", "index.js")); err != nil || string(data) != "new" {+ t.Fatal("committed installation missing", err)+ }+}diff --git a/kernel/util/builtin_skill_test.go b/kernel/util/builtin_skill_test.goindex d45bbc2324..1f691257d1 100644--- a/kernel/util/builtin_skill_test.go+++ b/kernel/util/builtin_skill_test.go@@ -8,6 +8,7 @@ import ("strings""testing""testing/fstest"+ "unicode")func TestBuiltinSkillMetadataAndResources(t *testing.T) {@@ -43,6 +44,28 @@ func TestBuiltinSkillMetadataAndResources(t *testing.T) {}}+func TestBuiltinSkillEnglishMarkdownKeepsMetadataBinding(t *testing.T) {+ info, err := BuiltinPluginSkill(nil)+ if err != nil {+ t.Fatal(err)+ }+ if !strings.HasPrefix(info.Description, "Official frontend plugin development workflow") {+ t.Fatal("builtin metadata description is not in English", info.Description)+ }+ for _, resource := range []string{"SKILL.md", "references/development.md", "references/verification.md"} {+ loaded, err := LoadBuiltinSkill(PluginDevelopmentSkillName+"/"+resource, nil)+ if err != nil {+ t.Fatal(err)+ }+ if loaded.Digest != info.Digest || loaded.Version != info.Version {+ t.Fatalf("resource metadata differs from current content binding: %s", resource)+ }+ if strings.ContainsFunc(loaded.Content, func(r rune) bool { return unicode.Is(unicode.Han, r) }) {+ t.Fatalf("builtin Markdown still contains untranslated Chinese: %s", resource)+ }+ }+}+func TestBuiltinSkillDisabledAndExactNames(t *testing.T) {info, err := BuiltinPluginSkill([]string{BuiltinPluginSkillID, "builtin:future"})if err != nil || info.Enabled {diff --git a/kernel/util/builtin_skills/siyuan-plugin-development/SKILL.md b/kernel/util/builtin_skills/siyuan-plugin-development/SKILL.mdindex 2652a644c8..e0c790dbe8 100644--- a/kernel/util/builtin_skills/siyuan-plugin-development/SKILL.md+++ b/kernel/util/builtin_skills/siyuan-plugin-development/SKILL.md@@ -1,52 +1,52 @@---name: siyuan-plugin-development-description: 官方前端插件开发流程:在用户明确选择后澄清缺失要求、确认简短方案、使用受管副本实现、验证和打包;安装与启用另行授权+description: Official frontend plugin development workflow. After the user explicitly opts in, clarify missing requirements, confirm a short plan, implement in a managed copy, verify, and package. Installation and activation require separate authorization.----# 思源前端插件开发+# SiYuan Frontend Plugin Development-这是随思源发布的只读官方技能。当前范围是前端插件的新建和修改;默认采用无第三方运行依赖的 CommonJS JavaScript。kernel.js 的完整开发、验证与恢复不在此流程范围内。+This is a read-only official skill shipped with SiYuan. Its current scope is creating and modifying frontend plugins, using CommonJS JavaScript without third-party runtime dependencies by default. Full development, verification, and recovery of kernel.js are outside this workflow's scope.-示例占位符(如 ${PLUGIN_NAME})需要按照已确认的方案替换,不把用户变量设置当作官方内容。+Replace example placeholders such as ${PLUGIN_NAME} according to the confirmed plan. Do not treat user-defined variable settings as official content.-## 先取得真实选择,再确认方案+## Obtain an Explicit Choice, Then Confirm the Plan-- 仅在用户明确要求开发或修改插件时使用。普通模板、文档和主题需求不自动升级为插件-- 官方选择由 question 工具的 workflow.action="choose" 发起,questions 可传空数组;服务器显示固定的本地化是/否问题。不要把普通问题、聊天文字、模型自己的 consent 或用户旧答案当作该任务的许可-- 用户选择是之后,以 skill 的 action="load"、source="builtin"、name="siyuan-plugin-development" 加载正文。只有服务器确认成功加载后才继续。拒绝、取消或禁用时不要读取官方正文;仍可按原权限处理用户要求的自定义开发-- 从当前对话提取已知需求,仅补问会改变实现的缺口:功能、入口、触发方式、目标前端、数据读取与写入影响、交付内容。不要重复问已经明确的内容,也不要猜笔记本或扩大到全部平台-- 通过 question 的 workflow.action="plan" 提交短方案,绑定选择返回的 taskId。方案全文清楚说明插件名称、前端、功能与入口、数据变化、交付范围、导入来源及允许打包的文件。服务器冻结并显示整份方案;真正接受确认前不写源码-- 修改已经确认的目标、源码来源、数据影响或打包范围时更新方案并取得新的确认。不要伪造 taskId、方案摘要或已确认状态;旧问题和旧版本不作为新任务授权+- Use this skill only when the user explicitly asks to develop or modify a plugin. Do not automatically turn ordinary template, document, or theme requests into plugins+- Initiate the official choice with workflow.action="choose" in the question tool; questions may be an empty array. The server displays a fixed, localized yes/no question. Do not treat ordinary questions, chat text, the model's own consent, or the user's previous answers as permission for this task+- After the user chooses yes, load the body through skill with action="load", source="builtin", and name="siyuan-plugin-development". Continue only after the server confirms successful loading. Do not read the official body if the user declines or cancels, or if the skill is disabled; user-requested custom development may still proceed under its original permissions+- Extract known requirements from the current conversation, and ask only about gaps that would change the implementation: functionality, entry points, triggers, target frontend, data-read and data-write effects, and deliverables. Do not repeat questions already answered, guess a notebook, or expand the scope to every platform+- Submit a short plan through question with workflow.action="plan", bound to the taskId returned by the choice. The full plan must clearly state the plugin name, frontend, functionality and entry points, data changes, delivery scope, import source, and files allowed in the package. The server freezes and displays the entire plan; do not write source code before actual acceptance is confirmed+- Update the plan and obtain new confirmation when changing a confirmed goal, source-code origin, data effects, or packaging scope. Do not fabricate a taskId, plan digest, or confirmed state; previous questions and versions do not authorize a new task-选择调用示例:{"questions":[],"workflow":{"action":"choose"}}。用户明确要求另一个插件时才用 newTask=true;明确更改当前流程选择时可用 reconsider=true。普通重复调用沿用当前选择,不重复询问。+Example choice call: {"questions":[],"workflow":{"action":"choose"}}. Use newTask=true only when the user explicitly requests another plugin; reconsider=true may be used when the user explicitly changes the current workflow choice. Ordinary repeated calls reuse the current choice without asking again.-方案字段:taskId、proposal(不超过 2000 字符)、packageName、frontend(desktop、desktop-window、browser-desktop、mobile 或 browser-mobile 中一个)、dataEffects 与 deliverables(各不超过 1000 字符)、files(最多 200 个准确的相对文件路径)。导入现有插件前,调用 bazaar 的 project_status,提供 taskId、sourcePath 和准确的 sourceFiles;sourceFiles 必须与待确认的 workflow.files 一致。宿主返回所选现存安全文件的 sourceRevision,方案中一并提供该摘要与 sourcePath;不要隐式读取或计算整个仓库的摘要。排除的 .git、node_modules、config 等路径只列出而不读取内容。新建时省略来源字段。技术清单也会显示给用户,不在确认后增加未批准文件;允许清单可包含尚未存在的可选文件,但入口、manifest 和声明资源不能因此省略。+Plan fields: taskId, proposal (at most 2000 characters), packageName, frontend (one of desktop, desktop-window, browser-desktop, mobile, or browser-mobile), dataEffects and deliverables (at most 1000 characters each), and files (at most 200 exact relative file paths). Before importing an existing plugin, call bazaar's project_status with taskId, sourcePath, and exact sourceFiles; sourceFiles must match the workflow.files awaiting confirmation. The host returns a sourceRevision for the selected existing safe files; include that digest and sourcePath in the plan. Do not implicitly read or hash the entire repository. List excluded paths such as .git, node_modules, and config without reading their contents. Omit source fields when creating a new project. The technical file list is also shown to the user; do not add unapproved files after confirmation. The allowlist may contain optional files that do not yet exist, but this does not permit omitting the entry point, manifest, or declared resources.-## 先核实工具和接口+## Verify Tools and APIs First-先读 references/development.md,所有资源均通过 skill 的 source="builtin" 和 name="siyuan-plugin-development/相对路径" 读取。检查当前可用工具和目标思源版本,按需核实官方 plugin-sample、petal 与目标版本源码。不把类型声明、README 的旧版本或未发布接口当作当前宿主已支持。+Read references/development.md first. Read every resource through skill with source="builtin" and name="siyuan-plugin-development/relative-path". Check the tools currently available and the target SiYuan version; consult the official plugin-sample, petal, and source code for that version as needed. Do not treat type declarations, outdated README versions, or unreleased APIs as evidence of support in the current host.-默认使用 CommonJS JavaScript。只有实际存在并获准使用的依赖与构建工具时才采用 TypeScript;源码不等于可运行的 index.js。原生智能体不保证拥有 shell、依赖安装或任意代码执行能力。缺工具时准确报告阻塞步骤,不编造执行结果,不绕过工具拒绝。若用户指定 TypeScript,先确认替代路线,不擅自改成 JavaScript。+Use CommonJS JavaScript by default. Use TypeScript only when the required dependencies and build tools actually exist and are authorized for use; source code is not equivalent to a runnable index.js. Native agents are not guaranteed to have a shell, dependency-installation tools, or arbitrary code execution. If a tool is missing, report the exact blocked step. Do not invent execution results or bypass a tool denial. If the user specifies TypeScript, confirm an alternative approach before switching to JavaScript.-## 在受管副本中实现+## Implement in a Managed Copy-1. 方案确认后调用 bazaar 的 prepare_project,以 taskId 由宿主创建源码副本和基线检查点;不要自己指定绝对写入目录。导入项目先按明确的 sourceFiles 只读检查,批准来源和所选文件的基线摘要后导入副本;原目录保持原样。已有受管项目重新确认方案后,先用 project_status(taskId) 取得当前源码版本,再调用 prepare_project(taskId, expectedSourceRevision) 建立新检查点;该动作保留当前源码,不重新导入或覆盖它-2. 新文件使用 file.write 的 ifAbsent=true。编辑已有文本之前使用 file.read 的 withMetadata=true;按同一 expectedRevision 和 nextOffsetByte 续读,直到完整覆盖需要修改的原始内容。truncated=true 不是完整文件-3. 局部修改优先使用 file.edit,提供 expectedRevision 与唯一、不重叠的 oldText/newText;需要全文替换才使用带 expectedRevision 的 file.write,且必须先在同一 revision 下完整读取整个文件。遇到冲突先重读并核对,不重试盲写、不把找不到或多处匹配降级为整文件覆盖-4. 使用宿主返回的路径和项目版本;通过 bazaar 的 project_status 核实当前源码、方案和检查点。无法建立检查点就停止写入,部分失败须如实报告;需要恢复时使用 restore_project 并遵守当前版本和工具确认-5. 不使用 copy、unzip、目录改名或 HTTP 文件接口绕过受管源码的条件写入;不触碰宿主控制、备份或制品目录,不直接覆盖真实插件安装目录+1. After plan confirmation, call bazaar's prepare_project with taskId so the host creates a source-code copy and baseline checkpoint; do not specify an absolute write directory yourself. For imports, first perform a read-only inspection of the exact sourceFiles, then import a copy after approval of the source and the selected files' baseline digest; leave the original directory unchanged. After reconfirming a plan for an existing managed project, obtain the current source revision with project_status(taskId), then call prepare_project(taskId, expectedSourceRevision) to establish a new checkpoint. This preserves the current source code without reimporting or overwriting it+2. Use file.write with ifAbsent=true for new files. Before editing existing text, use file.read with withMetadata=true; continue reading with the same expectedRevision and nextOffsetByte until you have fully read the original content that needs changing. truncated=true does not represent a complete file+3. Prefer file.edit for partial changes, providing expectedRevision and unique, nonoverlapping oldText/newText replacements. Use file.write with expectedRevision only when full replacement is necessary, and only after reading the entire file at that same revision. On a conflict, reread and verify first. Do not blindly retry writes or fall back to overwriting the entire file when a match is missing or ambiguous+4. Use the paths and project revisions returned by the host; verify the current source code, plan, and checkpoint through bazaar's project_status. Stop writing if a checkpoint cannot be established, and report partial failures accurately. When recovery is needed, use restore_project and respect the current revision and tool confirmation requirements+5. Do not bypass conditional writes for managed source code through copy, unzip, directory renaming, or HTTP file APIs. Do not touch host-controlled, backup, or artifact directories, or directly overwrite the actual plugin installation directory-取消流程不会自动回退;取消、写入结果未知或部分准备使普通方案无法继续时,用 question 的 questions=[]、workflow.action="recover" 和 taskId 请求仅恢复授权,由服务器展示并绑定最近真正批准的方案及摘要。-确认后可调用 restore_project,或仅为同一冻结的中断准备重试 prepare_project;恢复不回退笔记、运行时数据或其他配置,也不授权继续修改源码,后续普通源码修改仍需正常的方案确认。+Canceling the workflow does not automatically roll back changes. When cancellation, an unknown write result, or partial preparation prevents the ordinary plan from continuing, request recovery-only authorization through question with questions=[], workflow.action="recover", and taskId. The server displays and binds the most recently actually approved plan and its digest.+After confirmation, you may call restore_project, or retry prepare_project only for the same frozen, interrupted preparation. Recovery does not roll back notes, runtime data, or other configuration, and does not authorize further source-code changes; subsequent ordinary source changes still require normal plan confirmation.-参考 examples/index.js 的最小入口模式,按实际功能调整。通过公开 Plugin API 创建入口,通过内核 API 修改笔记,禁止用 fs 或 Electron 直接改 data 文件。界面文案放 i18n,检查返回码、目标缺失、关闭的笔记本、重复点击与迟到响应。onunload 必须处理部分初始化,并清理自有监听器、定时器、观察器和请求;卸载不能撤销已发送的写请求。+Use the minimal entry-point pattern in examples/index.js as a reference and adapt it to the actual functionality. Create entry points through the public Plugin API and modify notes through kernel APIs; never use fs or Electron to modify data files directly. Put UI text in i18n. Handle return codes, missing targets, closed notebooks, repeated clicks, and late responses. onunload must handle partial initialization and clean up the plugin's own listeners, timers, observers, and requests; unloading cannot undo write requests that have already been sent.-## 验证、打包和交付+## Verify, Package, and Deliver-先读 references/verification.md。仅声明实际实现和已验证的前端;没有 kernel.js 不声明 kernels。不要照搬示例作者、仓库、赞助或数据权限,不为本地原型虚构发布身份。+Read references/verification.md first. Declare only frontends that are actually implemented and verified; do not declare kernels without kernel.js. Do not copy the example's author, repository, funding information, or data permissions, or invent a publishing identity for a local prototype.-通过 bazaar 的 package_local,以 taskId 和最新 expectedSourceRevision 请求确定性本地 ZIP。宿主只冻结允许清单中实际存在的安全文件,允许可选路径不存在,但必须存在 plugin.json、index.js 和 manifest 声明的资源;不执行项目脚本、不下载依赖。缺入口、缺声明资源或命中秘密文件时先修正源码或重新确认范围。保留返回的 packageHash、sourceRevision 和验证结果。打包成功不代表 JavaScript 语法、真实安装、前端加载或业务运行通过。+Request a deterministic local ZIP through bazaar's package_local with taskId and the latest expectedSourceRevision. The host freezes only existing safe files on the allowlist. Optional paths may be absent, but plugin.json, index.js, and resources declared by the manifest must exist. It does not execute project scripts or download dependencies. If the entry point or declared resources are missing, or a secret file is detected, first correct the source code or reconfirm the scope. Retain the returned packageHash, sourceRevision, and validation results. Successful packaging does not mean JavaScript syntax, actual installation, frontend loading, or functional execution has passed verification.-分项交付源码、静态检查、构建、ZIP、模拟测试、真实安装、启用配置、前端加载和业务运行的结果与依据。纯 JavaScript 构建写“不适用”;没运行的步骤写“未验证”和原因。SDK 替身或独立 Electron DOM 测试不能称为思源集成测试;桌面 Electron 与桌面浏览器单独验证。+Report separate results and evidence for source code, static checks, builds, ZIP packaging, simulated tests, actual installation, activation configuration, frontend loading, and functional execution. Mark builds for plain JavaScript as "not applicable"; mark steps that were not run as "unverified" and explain why. Tests using SDK substitutes or a standalone Electron DOM environment are not SiYuan integration tests; verify desktop Electron and the desktop browser separately.-安装和启用均需用户明确授权对应动作与目标。已启用插件的覆盖可能立即执行代码;disable 通知没有所有前端卸载确认,不能声称自动保证停止。获得授权后仅使用原生安装接口并绑定宿主返回的包摘要、目标版本,不靠通用文件写入安装。回退旧代码不等于回退用户笔记与配置。+Installation and activation each require the user's explicit authorization for the corresponding action and target. Overwriting an enabled plugin may execute code immediately; a disable notification does not confirm unloading in every frontend, so do not claim it automatically guarantees execution has stopped. Once authorized, use only the native installation interface, bound to the package digest and target revision returned by the host; do not install through generic file writes. Rolling back code does not roll back the user's notes or configuration.diff --git a/kernel/util/builtin_skills/siyuan-plugin-development/references/development.md b/kernel/util/builtin_skills/siyuan-plugin-development/references/development.mdindex 5c92dced6c..d27879bfcd 100644--- a/kernel/util/builtin_skills/siyuan-plugin-development/references/development.md+++ b/kernel/util/builtin_skills/siyuan-plugin-development/references/development.md@@ -1,37 +1,37 @@-# 开发依据与边界+# Development References and Boundaries-## 官方依据+## Official References-- 插件示例:https://github.com/siyuan-note/plugin-sample-- Plugin API 声明:https://github.com/siyuan-note/petal-- 思源目标版本实现:https://github.com/siyuan-note/siyuan+- Plugin sample: https://github.com/siyuan-note/plugin-sample+- Plugin API declarations: https://github.com/siyuan-note/petal+- Implementation of the target SiYuan version: https://github.com/siyuan-note/siyuan-核实当前运行版本及目标前端,再使用该版本的公开接口。前端插件入口 index.js 由宿主加载,CommonJS 使用 require("siyuan") 和 module.exports;不要仅因为 npm 包有某个类型就假设宿主导出了它。目标前端取自当前 manifest 规范,不盲目复用全平台数组。+Verify the currently running version and target frontend, then use the public APIs for that version. The host loads the frontend plugin entry point index.js; CommonJS uses require("siyuan") and module.exports. Do not assume the host exports an API simply because its type exists in an npm package. Take target frontend values from the current manifest specification instead of blindly reusing an all-platform array.-## 最小文件与构建+## Minimum Files and Builds-最小前端包需要 plugin.json 与真实的 index.js,并纳入实际使用的 i18n、README、index.css 及其他资源。manifest 的名称、版本、最低宿主版本和前端声明须符合当前原生安装解析规则。发布元信息需要真实身份;本地原型不虚构作者或仓库。+A minimal frontend package requires plugin.json and a real index.js, together with any i18n, README, index.css, and other resources actually used. The manifest's name, version, minimum host version, and frontend declarations must comply with the current native installer's parsing rules. Publishing metadata requires a real identity; do not invent an author or repository for a local prototype.-examples/index.js 和 examples/en_US.json 是原创的小型无依赖示例,只展示公开入口和生命周期,不是已完成的用户插件,不要把示例文案当用户需求。根据目标版本核实 addTopBar、showMessage 和语言文件键名。布局相关入口在 onLayoutReady 注册,避免重复注册。+examples/index.js and examples/en_US.json are original, small, dependency-free examples that demonstrate only public entry points and lifecycle handling. They are not a completed plugin for the user; do not treat example text as user requirements. Verify addTopBar, showMessage, and language-file keys against the target version. Register layout-related entry points in onLayoutReady and avoid duplicate registration.-TypeScript 只有经过实际可用的构建链才能产生可安装的 index.js;不能把 .ts 改后缀冒充构建。package_local 仅冻结并打包文件,不构建、不执行任意项目脚本。缺构建能力时准确交付源码及阻塞信息,或经用户同意改用纯 JavaScript。+TypeScript produces an installable index.js only through an actually available build toolchain; changing a .ts extension is not a build. package_local only freezes and packages files; it does not build or execute arbitrary project scripts. If build capabilities are unavailable, accurately deliver the source code and blocker details, or switch to plain JavaScript with the user's agreement.-## 导入与再次确认+## Imports and Reconfirmation-导入前以 project_status(taskId, sourcePath, sourceFiles) 检查候选来源。sourceFiles 是准确的相对文件允许清单,必须与方案的 workflow.files 一致;sourceRevision 绑定所选现存安全文件,不是整个仓库。宿主仅列出被排除的路径,不读取其中的 .git、node_modules、config 等内容。允许清单中可选路径尚未存在时可以留待创建,不把它当作已导入文件。+Before importing, inspect the candidate source with project_status(taskId, sourcePath, sourceFiles). sourceFiles is an exact allowlist of relative file paths and must match the plan's workflow.files; sourceRevision binds the selected existing safe files, not the entire repository. The host only lists excluded paths without reading contents such as .git, node_modules, or config. An optional path on the allowlist that does not yet exist may be created later; do not treat it as an imported file.-已经存在的受管项目重新确认方案后,先通过 project_status(taskId) 取得当前 sourceRevision,再使用 prepare_project(taskId, expectedSourceRevision) 建立新检查点;不覆盖当前源码,不重新导入旧来源。版本不符时先只读检查变化,再按实际影响处理。+After reconfirming a plan for an existing managed project, obtain the current sourceRevision through project_status(taskId), then establish a new checkpoint with prepare_project(taskId, expectedSourceRevision). Do not overwrite the current source code or reimport the previous source. If revisions do not match, first inspect the changes read-only, then handle their actual effects.-打包只冻结已确认允许清单中实际存在的安全文件。可选文件缺失可不入包;plugin.json、index.js 及 manifest 声明资源必须完整,不能用可选清单绕过入口或资源校验。+Packaging freezes only existing safe files on the confirmed allowlist. Missing optional files may be omitted from the package, but plugin.json, index.js, and resources declared by the manifest must be complete. Do not use optional allowlist entries to bypass entry-point or resource validation.-## 数据与生命周期+## Data and Lifecycle-通过公开内核 API 读取和修改笔记,检查 code 后才宣告成功;不直接改 .sy、数据库或真实 data 目录。明确目标及影响范围,按现有权限访问加密笔记本,锁定或拒绝时不绕过。+Read and modify notes through public kernel APIs, and check code before reporting success. Do not directly modify .sy files, databases, or the actual data directory. Define the target and scope of effects clearly, access encrypted notebooks under existing permissions, and do not bypass locks or denials.-耗时写入防重复点击,保留请求及实例状态。onunload 清理自有事件、定时器和观察器,取消可取消的读取;异步返回后检查实例仍有效。取消请求或卸载不能保证服务器端写入尚未执行,结果未知时先只读核实。+Prevent duplicate clicks during long-running writes, and retain request and instance state. In onunload, clean up the plugin's own events, timers, and observers, and cancel reads that can be canceled; after an asynchronous response, check that the instance is still valid. Canceling a request or unloading does not guarantee that a server-side write has not already executed. If the result is unknown, verify it read-only first.-## 安装+## Installation-生成本地 ZIP 不授予安装或启用许可。安装使用原生本地包接口,绑定包 hash 和预期安装目标 revision;不可变安装快照与开发源码分开。授权可能执行代码前说明已启用插件覆盖的影响。用户只批准文件交付时停在源码与制品层。+Generating a local ZIP does not grant permission to install or activate it. Install through the native local-package interface, bound to the package hash and expected installation-target revision; keep the immutable installation snapshot separate from development source code. Explain the effects of overwriting an enabled plugin before obtaining authorization for an action that may execute code. If the user approves only file delivery, stop at source code and artifacts.-安装数据恢复使用既有 repo 快照与恢复工具,遵循用户的同步忽略规则。快照覆盖未忽略的 data/plugins 代码与 data/storage/petal 数据,不包含工作空间 conf 或受管项目源码;受管源码仍由 restore_project 恢复。智能体每轮对话的首个本地写入前创建快照,不为每次安装单独创建恢复点,安装器也不另行保留插件代码备份。整库签出会回退全部纳入快照的数据,关闭同步并重载界面;单文件恢复只覆盖所选文件,不删除后来新增的文件。恢复 petals.json 会影响整份插件配置。先核实快照内容及恢复范围,遵循现有工具确认,不自动签出整库,也不承诺停止正在运行的插件代码。+Recover installation data through the existing repo snapshot and recovery tools, respecting the user's sync-ignore rules. Snapshots cover non-ignored code under data/plugins and data under data/storage/petal; they do not include the workspace conf directory or managed-project source code. Managed source code is still restored through restore_project. The agent creates a snapshot before the first local write in each conversation round, rather than creating a separate recovery point for every installation; the installer does not keep a separate plugin-code backup either. A full-repository checkout rolls back all data included in the snapshot, disables sync, and reloads the interface. Single-file recovery overwrites only the selected files and does not delete files added later. Restoring petals.json affects the entire plugin configuration. Verify snapshot contents and recovery scope first, follow the existing tool confirmation requirements, do not automatically check out the entire repository, and do not promise to stop plugin code that is already running.diff --git a/kernel/util/builtin_skills/siyuan-plugin-development/references/verification.md b/kernel/util/builtin_skills/siyuan-plugin-development/references/verification.mdindex 835096f2c7..3d41b3f8d6 100644--- a/kernel/util/builtin_skills/siyuan-plugin-development/references/verification.md+++ b/kernel/util/builtin_skills/siyuan-plugin-development/references/verification.md@@ -1,18 +1,18 @@-# 验证记录+# Verification Record-每一项只报告实际证据:已通过、失败、未验证或不适用。源码和 ZIP 完成不能替代运行证据。+Report only actual evidence for each item: passed, failed, unverified, or not applicable. Completed source code and ZIP files do not replace runtime evidence.-- 源码:实现对应确认的方案,前端与资源声明准确,没有未批准的数据影响-- 静态检查:确实运行的语法、类型或 lint 检查及结果;没有解析器就写未验证-- 构建:TypeScript 实际命令、退出状态与产物;纯 JavaScript 为不适用-- ZIP:package_local 返回的包路径、hash、源码版本、清单和校验结果-- 模拟测试:标明 SDK 替身、DOM 或独立 Electron 环境,不称为真实思源-- 安装:授权的目标、包 hash、安装前后版本及真实原生安装结果-- 启用:实际配置状态,不能从安装成功推断已经启用-- 前端加载:Electron 桌面和桌面浏览器分别检查入口与错误,不能互相代替-- 业务运行:主操作、错误反馈、重复点击、部分初始化卸载、迟到异步响应-- 数据写入:目标、数量、实际返回状态;未知结果先只读核实,避免重复提交+- Source code: implementation matches the confirmed plan, frontend and resource declarations are accurate, and there are no unapproved data effects+- Static checks: syntax, type, or lint checks actually run and their results; mark as unverified if no parser is available+- Build: the actual TypeScript command, exit status, and artifacts; not applicable for plain JavaScript+- ZIP: package path, hash, source revision, file list, and validation results returned by package_local+- Simulated tests: identify SDK substitutes, DOM environments, or standalone Electron environments; do not describe them as an actual SiYuan instance+- Installation: authorized target, package hash, revisions before and after installation, and actual native installation results+- Activation: actual configuration state; successful installation does not imply activation+- Frontend loading: check entry points and errors separately in desktop Electron and the desktop browser; neither substitutes for the other+- Functional execution: main operation, error feedback, repeated clicks, unloading after partial initialization, and late asynchronous responses+- Data writes: target, count, and actual returned status; verify unknown results read-only first to avoid duplicate submissions-没有真实思源实例、目标前端或必要权限时,明确保留未验证阶段。不要安装到用户真实环境来弥补缺少测试环境。代码回退不回退用户数据。+If an actual SiYuan instance, target frontend, or necessary permission is unavailable, explicitly leave the corresponding stages unverified. Do not compensate for a missing test environment by installing into the user's actual environment. Rolling back code does not roll back user data.-恢复不保证自动处理所有进程崩溃:临时文件仅写入部分内容,或条件新建已发布目标但尚未清理临时硬链接时,工具保留两份名称、字节和日志并返回 result_unknown,可能需要人工检查。不要删除不确定的文件、放宽硬链接检查或盲目重试来宣称恢复完成。+Recovery is not guaranteed to handle every process crash automatically. If a temporary file is only partially written, or a conditional create has published the target but has not yet cleaned up the temporary hard link, the tool preserves both names, their bytes, and the logs, and returns result_unknown; manual inspection may be necessary. Do not delete files whose state is uncertain, weaken hard-link checks, or blindly retry to claim that recovery is complete.diff --git a/kernel/util/plugin_project.go b/kernel/util/plugin_project.goindex 53cae82b7c..7da26858c3 100644--- a/kernel/util/plugin_project.go+++ b/kernel/util/plugin_project.go@@ -56,18 +56,21 @@ type PluginProjectArtifact struct {// 项目清单不保存授权状态;每次操作都须重新取得可信运行时授权。type pluginProjectManifest struct {- Version int `json:"version"`- PlanHash string `json:"planHash"`- SourcePath string `json:"sourcePath,omitempty"`- SourceRevision string `json:"sourceRevision,omitempty"`- Preparing bool `json:"preparing,omitempty"`- Baseline map[string]string `json:"baseline"`- BaselineDirectory string `json:"baselineDirectory,omitempty"`- Current map[string]string `json:"current"`- Pending map[string]PluginProjectMutation `json:"pending,omitempty"`- Journal []map[string]PluginProjectMutation `json:"journal,omitempty"`- TemporaryFiles map[string]string `json:"temporaryFiles,omitempty"`- Artifact *PluginProjectArtifact `json:"artifact,omitempty"`+ Version int `json:"version"`+ PlanHash string `json:"planHash"`+ SourcePath string `json:"sourcePath,omitempty"`+ SourceRevision string `json:"sourceRevision,omitempty"`+ Preparing bool `json:"preparing,omitempty"`+ Baseline map[string]string `json:"baseline"`+ BaselineDirectory string `json:"baselineDirectory,omitempty"`+ Current map[string]string `json:"current"`+ Pending map[string]PluginProjectMutation `json:"pending,omitempty"`+ TemporaryFiles map[string]string `json:"temporaryFiles,omitempty"`+ Artifact *PluginProjectArtifact `json:"artifact,omitempty"`+}++func (manifest *pluginProjectManifest) mutationPending() bool {+ return len(manifest.Pending) > 0 || len(manifest.TemporaryFiles) > 0}type PluginProjectStatus struct {@@ -590,7 +593,7 @@ func WithPluginProjectSource(ctx context.Context, write bool, fn func(*PluginDevif manifest.PlanHash != grant.PlanHash {return errors.New("revision_conflict: prepare_project is required for the newly approved plan")}- if len(manifest.Pending) != 0 {+ if manifest.mutationPending() {return errors.New("result_unknown: interrupted mutation requires project_status and restore_project")}if err = validateProjectBaseline(grant, manifest); err != nil {@@ -642,7 +645,7 @@ func PluginProjectArtifactStatus(grant *PluginDevelopmentGrant, root *os.Root) (}files, err := snapshotPluginProject(root, nil, manifest.TemporaryFiles)if err != nil {- if len(manifest.Pending) > 0 {+ if manifest.mutationPending() {return nil, fmt.Errorf("result_unknown: pending project cannot be safely inspected; manual inspection required; source and journal preserved: %w", err)}return nil, err@@ -650,7 +653,7 @@ func PluginProjectArtifactStatus(grant *PluginDevelopmentGrant, root *os.Root) (ret := projectStatus(files)ret.TaskID, ret.Prepared, ret.SourceRoot = grant.TaskID, !manifest.Preparing, workspacePluginProjectPath(grant.SourceRoot)ret.BaselineRevision = PluginProjectTreeRevision(manifest.Baseline)- ret.Pending = manifest.Preparing || len(manifest.Pending) > 0+ ret.Pending = manifest.Preparing || manifest.mutationPending()ret.ExternalChanges = ret.SourceRevision != PluginProjectTreeRevision(manifest.Current)ret.PlanMismatch = manifest.PlanHash != grant.PlanHashif !ret.Pending && !ret.ExternalChanges && !ret.PlanMismatch && manifest.Artifact != nil && manifest.Artifact.SourceRevision == ret.SourceRevision {@@ -666,7 +669,7 @@ func BeginPluginProjectMutations(grant *PluginDevelopmentGrant, changes map[striif err != nil {return err}- if len(changes) == 0 || len(manifest.Pending) > 0 {+ if len(changes) == 0 || manifest.mutationPending() {return errors.New("result_unknown: pending or empty project mutation")}if err = validateProjectBaseline(grant, manifest); err != nil {@@ -718,10 +721,6 @@ func BeginPluginProjectMutations(grant *PluginDevelopmentGrant, changes map[strimanifest.TemporaryFiles[tmp] = change.NewRevision}}- if len(manifest.Journal) >= 512 {- return errors.New("backup_failed: project journal limit reached; recovery history was preserved")- }- manifest.Journal = append(manifest.Journal, changes)if err = savePluginProjectManifest(grant, manifest); err != nil {return fmt.Errorf("backup_failed: mutation journal could not be saved: %w", err)}@@ -785,7 +784,7 @@ func RecordPluginProjectArtifact(grant *PluginDevelopmentGrant, artifact *Pluginif err != nil {return err}- if len(manifest.Pending) > 0 || artifact.SourceRevision != PluginProjectTreeRevision(manifest.Current) {+ if manifest.mutationPending() || artifact.SourceRevision != PluginProjectTreeRevision(manifest.Current) {return errors.New("revision_conflict: artifact source is not the recorded project revision")}manifest.Artifact = artifact@@ -823,7 +822,7 @@ func RestorePluginProject(ctx context.Context, taskID, expectedRevision string)defer root.Close()files, err := snapshotPluginProject(root, nil, manifest.TemporaryFiles)if err != nil {- if len(manifest.Pending) > 0 {+ if manifest.mutationPending() {return fmt.Errorf("result_unknown: pending project cannot be safely restored; manual inspection required; source and journal preserved: %w", err)}return err@@ -882,10 +881,6 @@ func RestorePluginProject(ctx context.Context, taskID, expectedRevision string)}}manifest.Current, manifest.Pending, manifest.Artifact = inventory, changes, nil- if len(manifest.Journal) >= 512 {- return errors.New("backup_failed: project journal limit reached; recovery history was preserved")- }- manifest.Journal = append(manifest.Journal, changes)if manifest.TemporaryFiles == nil {manifest.TemporaryFiles = map[string]string{}}diff --git a/kernel/util/plugin_project_replan.go b/kernel/util/plugin_project_replan.goindex 3266f28be5..773d98fa1a 100644--- a/kernel/util/plugin_project_replan.go+++ b/kernel/util/plugin_project_replan.go@@ -4,9 +4,11 @@ import ("context""errors""fmt"+ "io/fs""os""path""path/filepath"+ "strings")func pluginProjectBaselinePath(grant *PluginDevelopmentGrant, manifest *pluginProjectManifest) string {@@ -26,7 +28,7 @@ func replanPluginProject(ctx context.Context, grant *PluginDevelopmentGrant, allif manifest.SourcePath != grant.SourcePath || manifest.SourceRevision != grant.SourceRevision {return nil, errors.New("revision_conflict: changing import provenance requires a new plugin development task")}- if len(manifest.Pending) > 0 {+ if manifest.mutationPending() {return nil, errors.New("result_unknown: resolve interrupted source mutation before preparing a new plan")}if err = validateProjectBaseline(grant, manifest); err != nil {@@ -56,25 +58,15 @@ func replanPluginProject(ctx context.Context, grant *PluginDevelopmentGrant, all}}if manifest.PlanHash == grant.PlanHash {+ if err = cleanPluginProjectCheckpoints(grant, manifest); err != nil {+ return nil, err+ }return PluginProjectArtifactStatus(grant, source)}checkpoint := "checkpoints/" + PluginProjectDigest([]byte(grant.PlanHash+"\x00"+revision))- private, err := OpenPluginProjectDirectory(PluginProjectPrivateDir(grant.TaskID), false)- if err != nil {+ if err = cleanPluginProjectCheckpoints(grant, manifest, checkpoint); err != nil {return nil, err}- defer private.Close()- if err = private.MkdirAll("checkpoints", 0700); err != nil {- return nil, err- }- entries, err := os.ReadDir(filepath.Join(PluginProjectPrivateDir(grant.TaskID), "checkpoints"))- if err != nil {- return nil, err- }- _, existingErr := private.Lstat(checkpoint)- if len(entries) >= 8 && errors.Is(existingErr, os.ErrNotExist) {- return nil, errors.New("backup_failed: retained plan checkpoint limit reached; previous recovery points were preserved")- }if err = ensurePluginProjectCheckpoint(grant, checkpoint, files); err != nil {return nil, err}@@ -102,5 +94,86 @@ func replanPluginProject(ctx context.Context, grant *PluginDevelopmentGrant, allif err = savePluginProjectManifest(grant, manifest); err != nil {return nil, err}+ if err = cleanPluginProjectCheckpoints(grant, manifest); err != nil {+ return nil, err+ }return PluginProjectArtifactStatus(grant, source)}++// 仅整理宿主检查点命名空间;当前清单指向的基线和待复用检查点始终保留。+// 调用方持有项目锁,且已确认没有待完成写入;清单原子切换后才能删除上一基线。+func cleanPluginProjectCheckpoints(grant *PluginDevelopmentGrant, manifest *pluginProjectManifest, retain ...string) error {+ if manifest.Preparing || manifest.mutationPending() {+ return errors.New("result_unknown: pending project recovery evidence must be preserved")+ }+ if err := validateProjectBaseline(grant, manifest); err != nil {+ return err+ }+ current := manifest.BaselineDirectory+ if current == "" {+ current = "baseline"+ }+ keep := map[string]bool{current: true}+ for _, name := range retain {+ keep[name] = true+ }+ private, err := OpenPluginProjectDirectory(PluginProjectPrivateDir(grant.TaskID), false)+ if err != nil {+ return err+ }+ defer private.Close()+ remove := func(name string) error {+ if keep[name] {+ return nil+ }+ info, statErr := private.Lstat(name)+ if errors.Is(statErr, os.ErrNotExist) {+ return nil+ }+ if statErr != nil {+ return statErr+ }+ if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {+ return nil+ }+ return private.RemoveAll(name)+ }+ if err = remove("baseline"); err != nil {+ return fmt.Errorf("backup_failed: obsolete checkpoint cleanup failed; current baseline preserved: %w", err)+ }+ entries, err := fs.ReadDir(private.FS(), ".")+ if err != nil {+ return err+ }+ for _, entry := range entries {+ name := entry.Name()+ if suffix, ok := strings.CutPrefix(name, ".checkpoint-"); ok && len(suffix) == 26 && strings.Trim(suffix, "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567") == "" {+ if err = remove(name); err != nil {+ return fmt.Errorf("backup_failed: staged checkpoint cleanup failed: %w", err)+ }+ }+ }+ info, err := private.Lstat("checkpoints")+ if errors.Is(err, os.ErrNotExist) {+ return nil+ }+ if err != nil {+ return err+ }+ if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {+ return errors.New("backup_failed: checkpoint directory must be an unlinked directory")+ }+ entries, err = fs.ReadDir(private.FS(), "checkpoints")+ if err != nil {+ return err+ }+ for _, entry := range entries {+ if entry.Name() == PluginProjectMissingRevision || !validPluginProjectRevision(entry.Name()) {+ continue+ }+ if err = remove(path.Join("checkpoints", entry.Name())); err != nil {+ return fmt.Errorf("backup_failed: obsolete checkpoint cleanup failed; current baseline preserved: %w", err)+ }+ }+ return nil+}diff --git a/kernel/util/plugin_project_test.go b/kernel/util/plugin_project_test.goindex 96bc1f72e7..ad12d2b8b4 100644--- a/kernel/util/plugin_project_test.go+++ b/kernel/util/plugin_project_test.go@@ -2,9 +2,12 @@ package utilimport ("context"+ "encoding/json""errors"+ "fmt""os""path/filepath"+ "runtime""strings""testing")@@ -143,8 +146,8 @@ func TestPluginProjectMutationRecoveryAndExternalConflict(t *testing.T) {t.Fatal("restoration incomplete")}manifest, err := readPluginProjectManifest(grant)- if err != nil || len(manifest.Journal) != 2 {- t.Fatal("failure history not preserved", err)+ if err != nil || len(manifest.Pending) != 0 || len(manifest.TemporaryFiles) != 0 {+ t.Fatal("completed recovery journal not cleared", err)}if data, _ := os.ReadFile(filepath.Join(grant.SourceRoot, "index.js")); string(data) != "old" {t.Fatal("baseline not restored")@@ -276,7 +279,7 @@ func TestPluginProjectRequiresTrustedCurrentGrant(t *testing.T) {}}-func TestPluginProjectReplanPreservesCurrentSourceAndPriorCheckpoint(t *testing.T) {+func TestPluginProjectReplanPreservesCurrentSourceAndReplacesCheckpoint(t *testing.T) {ctx, grant := pluginProjectFixture(t, map[string]string{"index.js": "old"})if _, err := PreparePluginProject(ctx, grant.TaskID, nil); err != nil {t.Fatal(err)@@ -309,14 +312,219 @@ func TestPluginProjectReplanPreservesCurrentSourceAndPriorCheckpoint(t *testing.if data, _ := os.ReadFile(filepath.Join(grant.SourceRoot, "index.js")); string(data) != "new" {t.Fatal("replan overwrote current source")}- if data, _ := os.ReadFile(filepath.Join(PluginProjectPrivateDir(grant.TaskID), "baseline", "index.js")); string(data) != "old" {- t.Fatal("prior checkpoint lost")+ if _, err := os.Stat(filepath.Join(PluginProjectPrivateDir(grant.TaskID), "baseline")); !os.IsNotExist(err) {+ t.Fatal("obsolete checkpoint not cleaned", err)}if data, _ := os.ReadFile(filepath.Join(pluginProjectBaselinePath(grant, manifest), "index.js")); string(data) != "new" {t.Fatal("new checkpoint does not cover current code")}}+func TestPluginProjectRepeatedMutationsKeepBoundedRecoveryState(t *testing.T) {+ ctx, grant := pluginProjectFixture(t, map[string]string{"index.js": "initial"})+ if _, err := PreparePluginProject(ctx, grant.TaskID, nil); err != nil {+ t.Fatal(err)+ }+ previous := "initial"+ for i := 0; i < 600; i++ {+ next := fmt.Sprintf("revision %d", i)+ err := WithPluginProjectSource(ctx, true, func(g *PluginDevelopmentGrant, root *os.Root) error {+ if err := BeginPluginProjectMutation(g, "index.js", PluginProjectDigest([]byte(previous)), PluginProjectDigest([]byte(next))); err != nil {+ return err+ }+ if err := root.WriteFile("index.js", []byte(next), 0600); err != nil {+ return err+ }+ return FinishPluginProjectMutation(g, "index.js")+ })+ if err != nil {+ t.Fatalf("mutation %d: %v", i, err)+ }+ previous = next+ }+ manifestPath := filepath.Join(PluginProjectPrivateDir(grant.TaskID), "project.json")+ data, err := os.ReadFile(manifestPath)+ if err != nil {+ t.Fatal(err)+ }+ var stored map[string]any+ if err = json.Unmarshal(data, &stored); err != nil {+ t.Fatal(err)+ }+ if _, found := stored["journal"]; found || len(data) > 2048 {+ t.Fatalf("completed history accumulated: %d bytes", len(data))+ }+ // 最后一次写入故意不完成,恢复必须仍能识别实际落盘的新字节。+ err = WithPluginProjectSource(ctx, true, func(g *PluginDevelopmentGrant, root *os.Root) error {+ if err := BeginPluginProjectMutation(g, "index.js", PluginProjectDigest([]byte(previous)), PluginProjectDigest([]byte("interrupted"))); err != nil {+ return err+ }+ return root.WriteFile("index.js", []byte("interrupted"), 0600)+ })+ if err != nil {+ t.Fatal(err)+ }+ status, err := GetPluginProjectStatus(ctx, grant.TaskID)+ if err != nil || !status.Pending {+ t.Fatal("pending recovery evidence missing", err)+ }+ if _, err = RestorePluginProject(ctx, grant.TaskID, status.SourceRevision); err != nil {+ t.Fatal(err)+ }+ if data, err = os.ReadFile(filepath.Join(grant.SourceRoot, "index.js")); err != nil || string(data) != "initial" {+ t.Fatal("repeated modifications could not be restored", string(data), err)+ }+}++func TestPluginProjectRepeatedReplansKeepOnlyCurrentCheckpoint(t *testing.T) {+ ctx, grant := pluginProjectFixture(t, map[string]string{"index.js": "initial"})+ status, err := PreparePluginProject(ctx, grant.TaskID, nil)+ if err != nil {+ t.Fatal(err)+ }+ unknown := filepath.Join(PluginProjectPrivateDir(grant.TaskID), "checkpoints", "user-notes", "keep.txt")+ if err = os.MkdirAll(filepath.Dir(unknown), 0700); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(unknown, []byte("keep"), 0600); err != nil {+ t.Fatal(err)+ }+ for i := 0; i < 20; i++ {+ grant.PlanHash, grant.PlanVersion = fmt.Sprintf("plan %d", i), i+2+ status, err = PreparePluginProject(ctx, grant.TaskID, nil, status.SourceRevision)+ if err != nil {+ t.Fatalf("replan %d: %v", i, err)+ }+ entries, err := os.ReadDir(filepath.Join(PluginProjectPrivateDir(grant.TaskID), "checkpoints"))+ if err != nil || len(entries) != 2 {+ t.Fatalf("replan retained obsolete checkpoints: %v, %v", entries, err)+ }+ }+ if data, err := os.ReadFile(unknown); err != nil || string(data) != "keep" {+ t.Fatal("unknown content was removed", err)+ }+ if _, err = RestorePluginProject(ctx, grant.TaskID, status.SourceRevision); err != nil {+ t.Fatal("current checkpoint is not recoverable", err)+ }+}++func TestPluginProjectReplanFailuresKeepRecoverableBaseline(t *testing.T) {+ if runtime.GOOS == "windows" || os.Geteuid() == 0 {+ t.Skip("requires Unix directory permissions for ordinary I/O failure injection")+ }+ for _, phase := range []string{"cleanup-before", "manifest-save", "cleanup-after"} {+ t.Run(phase, func(t *testing.T) {+ ctx, grant := pluginProjectFixture(t, map[string]string{"index.js": "initial"})+ status, err := PreparePluginProject(ctx, grant.TaskID, nil)+ if err != nil {+ t.Fatal(err)+ }+ private := PluginProjectPrivateDir(grant.TaskID)+ previousPlan := grant.PlanHash+ grant.PlanHash, grant.PlanVersion = "next plan", 2+ blocked := private+ if phase == "cleanup-before" {+ blocked = filepath.Join(private, "checkpoints", PluginProjectDigest([]byte("obsolete checkpoint")))+ if err = os.MkdirAll(blocked, 0700); err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(filepath.Join(blocked, "index.js"), []byte("obsolete"), 0600); err != nil {+ t.Fatal(err)+ }+ } else if phase == "cleanup-after" {+ blocked = filepath.Join(private, "baseline")+ }+ t.Cleanup(func() { _ = os.Chmod(blocked, 0700) })+ checks := 0+ failing := WithPluginDevelopmentAccess(context.Background(), func(string) (*PluginDevelopmentGrant, error) {+ checks+++ if phase == "cleanup-before" && checks == 1 || phase != "cleanup-before" && checks == 2 {+ if err := os.Chmod(blocked, 0500); err != nil {+ return nil, err+ }+ }+ return grant, nil+ })+ if _, err = PreparePluginProject(failing, grant.TaskID, nil, status.SourceRevision); err == nil {+ t.Fatal("injected checkpoint I/O failure was not reported")+ }+ manifest, err := readPluginProjectManifestForStatus(grant)+ if err != nil {+ t.Fatal("failed replan lost the published manifest", err)+ }+ wantPlan := previousPlan+ if phase == "cleanup-after" {+ wantPlan = grant.PlanHash+ }+ if manifest.PlanHash != wantPlan {+ t.Fatalf("published plan %q, want %q", manifest.PlanHash, wantPlan)+ }+ if err = validateProjectBaseline(grant, manifest); err != nil {+ t.Fatal("failed replan lost the published baseline", err)+ }+ if err = os.Chmod(blocked, 0700); err != nil {+ t.Fatal(err)+ }+ if _, err = PreparePluginProject(ctx, grant.TaskID, nil, status.SourceRevision); err != nil {+ t.Fatal("replan could not resume after the I/O failure", err)+ }+ if _, err = RestorePluginProject(ctx, grant.TaskID, status.SourceRevision); err != nil {+ t.Fatal("published checkpoint is not recoverable", err)+ }+ })+ }+}++func TestPluginProjectRecoveryTailRemainsPendingUntilCompleted(t *testing.T) {+ for _, exists := range []bool{false, true} {+ t.Run(fmt.Sprintf("temporary-file-exists-%t", exists), func(t *testing.T) {+ ctx, grant := pluginProjectFixture(t, map[string]string{"index.js": "initial"})+ if _, err := PreparePluginProject(ctx, grant.TaskID, nil); err != nil {+ t.Fatal(err)+ }+ manifest, err := readPluginProjectManifest(grant)+ if err != nil {+ t.Fatal(err)+ }+ // 源码已恢复,但清理临时文件或清空其记录之前中断。+ name := ".restore-" + PluginProjectDigest([]byte("index.js")) + ".tmp"+ manifest.TemporaryFiles = map[string]string{name: PluginProjectDigest([]byte("initial"))}+ if err = savePluginProjectManifest(grant, manifest); err != nil {+ t.Fatal(err)+ }+ if exists {+ if err = os.WriteFile(filepath.Join(grant.SourceRoot, name), []byte("initial"), 0600); err != nil {+ t.Fatal(err)+ }+ }+ status, err := GetPluginProjectStatus(ctx, grant.TaskID)+ if err != nil || !status.Pending || status.ExternalChanges {+ t.Fatal("unfinished recovery tail was not reported as pending", status, err)+ }+ called := false+ if err = WithPluginProjectSource(ctx, true, func(*PluginDevelopmentGrant, *os.Root) error { called = true; return nil }); err == nil || called {+ t.Fatal("ordinary writes continued before recovery finished", err)+ }+ if _, err = PreparePluginProject(ctx, grant.TaskID, nil, status.SourceRevision); err == nil {+ t.Fatal("preparation discarded the unfinished recovery tail")+ }+ if err = RecordPluginProjectArtifact(grant, &PluginProjectArtifact{SourceRevision: status.SourceRevision}); err == nil {+ t.Fatal("artifact became ready before recovery finished")+ }+ if _, err = RestorePluginProject(ctx, grant.TaskID, status.SourceRevision); err != nil {+ t.Fatal("recovery tail could not resume", err)+ }+ status, err = GetPluginProjectStatus(ctx, grant.TaskID)+ if err != nil || status.Pending || status.ExternalChanges {+ t.Fatal("recovery did not clear pending state", status, err)+ }+ if _, err = PreparePluginProject(ctx, grant.TaskID, nil, status.SourceRevision); err != nil {+ t.Fatal("completed recovery still blocked preparation", err)+ }+ })+ }+}+func TestPluginProjectCrashTemporaryRecovery(t *testing.T) {ctx, grant := pluginProjectFixture(t, map[string]string{"index.js": "old"})if _, err := PreparePluginProject(ctx, grant.TaskID, nil); err != nil {@@ -477,6 +685,13 @@ func TestPluginProjectInterruptedReplanAndProvenance(t *testing.T) {if _, err := PreparePluginProject(interrupted, grant.TaskID, nil, status.SourceRevision); err == nil {t.Fatal("replan cancellation did not trigger")}+ manifest, err := readPluginProjectManifestForStatus(grant)+ if err != nil || manifest.PlanHash == grant.PlanHash {+ t.Fatal("interrupted replan switched the current baseline", err)+ }+ if err = validateProjectBaseline(grant, manifest); err != nil {+ t.Fatal("interrupted replan removed the current baseline", err)+ }if _, err := PreparePluginProject(ctx, grant.TaskID, nil, status.SourceRevision); err != nil {t.Fatal("complete checkpoint could not be reused", err)}