An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:recycle: Use file-level theme and icon synchronization https://github.com/siyuan-note/siyuan/issues/19634
Daniel3039f39bc024
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230106104821-9nfphwm.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230106104821-9nfphwm.syindex 9512ea977f..557b17193d 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230106104821-9nfphwm.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20230106104821-9nfphwm.sy@@ -6,7 +6,7 @@"id": "20230106104821-9nfphwm","title": "Workspace","type": "doc",- "updated": "20260917190844"+ "updated": "20260918195936"},"Children": [{@@ -170,7 +170,7 @@{"Type": "NodeTextMark","TextMarkType": "code",- "TextMarkTextContent": "--workspace=\u0026quot;Absolute-path-of-the-workspace\u0026quot;"+ "TextMarkTextContent": "--workspace="Absolute-path-of-the-workspace""},{"Type": "NodeText",@@ -179,7 +179,7 @@{"Type": "NodeTextMark","TextMarkType": "code",- "TextMarkTextContent": "\u0026quot;"+ "TextMarkTextContent": """},{"Type": "NodeText",@@ -188,7 +188,7 @@{"Type": "NodeTextMark","TextMarkType": "code",- "TextMarkTextContent": "--workspace=\u0026quot;F:\\SiYuan\u0026quot;"+ "TextMarkTextContent": "--workspace="F:\\SiYuan""},{"Type": "NodeText",@@ -270,7 +270,7 @@"HeadingLevel": 2,"Properties": {"id": "20230106105213-0cv5aqm",- "updated": "20260917190844"+ "updated": "20260918195936"},"Children": [{@@ -579,12 +579,12 @@"Type": "NodeParagraph","Properties": {"id": "20260917190844-1yo0d58",- "updated": "20260917190844"+ "updated": "20260918195936"},"Children": [{"Type": "NodeText",- "Data": "Third-party themes are stored in data/themes/ and icon packages in data/icons/; both participate in data sync and snapshots. Each device keeps its appearance selection in its local conf/conf.json. Built-in appearance resources are not synced. Upgrade migration preserves the original local files for recovery."+ "Data": "Third-party themes are stored in data/themes/ and icon packages in data/icons/; both participate in data sync and snapshots. Each device keeps its appearance selection in its local conf/conf.json. Built-in appearance resources are not synced. Upgrade migration moves the original directories into data and removes the source copies."}]}diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20230805231614-vqn28eh/20210808180303-v9awwp0/20210721112206-mhr9wxi.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20230805231614-vqn28eh/20210808180303-v9awwp0/20210721112206-mhr9wxi.syindex db70135d0f..444d68a07f 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20230805231614-vqn28eh/20210808180303-v9awwp0/20210721112206-mhr9wxi.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20230805231614-vqn28eh/20210808180303-v9awwp0/20210721112206-mhr9wxi.sy@@ -6,7 +6,7 @@"id": "20210721112206-mhr9wxi","title": "Data sync","type": "doc",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20210721112403-8no39l4",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -52,12 +52,12 @@"Type": "NodeParagraph","Properties": {"id": "20260917190844-p6hrspl",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{"Type": "NodeText",- "Data": "Theme and icon package files, updates, and uninstallations sync between devices; each device chooses its own theme and icons. Images, fonts, and other package resources are always downloaded completely. Older clients can continue syncing notes; the new client handles shared appearance packages and their conflicts."+ "Data": "Theme and icon package files, updates, and uninstallations sync between devices; each device chooses its own theme and icons. Images, fonts, and other package resources are always downloaded completely. Synchronization, deletion, and conflicts follow the same file-level rules as plugins, widgets, and templates. Restoring a snapshot without a package removes it."}]},@@ -719,7 +719,7 @@"HeadingLevel": 2,"Properties": {"id": "20230219121305-n0v0nlb",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -748,7 +748,7 @@"ListData": {},"Properties": {"id": "20220703232248-j1dq9w6",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -788,7 +788,7 @@},"Properties": {"id": "20220703232248-nuapm43",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -811,7 +811,7 @@"ListData": {},"Properties": {"id": "20220703232248-kl3io11",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -851,7 +851,7 @@},"Properties": {"id": "20220703232248-jneoxfm",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -859,12 +859,12 @@"Type": "NodeParagraph","Properties": {"id": "20220703232248-x7l12qz",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{"Type": "NodeText",- "Data": "For ordinary file conflicts, the local file overwrites the cloud file, and the conflicting cloud file is preserved in data history; theme and icon conflicts are handled as complete packages without mixing files from different versions"+ "Data": "For file conflicts, including theme and icon files, the local file overwrites the cloud file, and the conflicting cloud file is preserved in data history"}]}diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230106101434-e6g4av3.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230106101434-e6g4av3.syindex cfde465c1e..165b9270be 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230106101434-e6g4av3.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20230106101434-e6g4av3.sy@@ -6,7 +6,7 @@"id": "20230106101434-e6g4av3","title": "工作空间","type": "doc",- "updated": "20260917190844"+ "updated": "20260918195936"},"Children": [{@@ -169,7 +169,7 @@{"Type": "NodeTextMark","TextMarkType": "code",- "TextMarkTextContent": "--workspace=\u0026quot;工作空间绝对路径\u0026quot;"+ "TextMarkTextContent": "--workspace="工作空间绝对路径""},{"Type": "NodeText",@@ -178,7 +178,7 @@{"Type": "NodeTextMark","TextMarkType": "code",- "TextMarkTextContent": "\u0026quot;"+ "TextMarkTextContent": """},{"Type": "NodeText",@@ -187,7 +187,7 @@{"Type": "NodeTextMark","TextMarkType": "code",- "TextMarkTextContent": "--workspace=\u0026quot;F:\\SiYuan\u0026quot;"+ "TextMarkTextContent": "--workspace="F:\\SiYuan""},{"Type": "NodeText",@@ -269,7 +269,7 @@"HeadingLevel": 2,"Properties": {"id": "20230106104118-wtvw42w",- "updated": "20260917190844"+ "updated": "20260918195936"},"Children": [{@@ -569,12 +569,12 @@"Type": "NodeParagraph","Properties": {"id": "20260917190844-hvlz04n",- "updated": "20260917190844"+ "updated": "20260918195936"},"Children": [{"Type": "NodeText",- "Data": "第三方主题保存在 data/themes/,图标包保存在 data/icons/,参与数据同步和快照。各设备的外观选择仍保存在本机 conf/conf.json 中;内置外观资源不参与同步。升级迁移会保留原有本地文件供恢复。"+ "Data": "第三方主题保存在 data/themes/,图标包保存在 data/icons/,参与数据同步和快照。各设备的外观选择仍保存在本机 conf/conf.json 中;内置外观资源不参与同步。升级迁移将原目录移入数据目录,迁移后移除源副本。"}]}diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20230805222417-2lj3dvk/20230808120348-orm8sjf/20230808120347-3cob0nb.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20230805222417-2lj3dvk/20230808120348-orm8sjf/20230808120347-3cob0nb.syindex ca189d1e3f..c81d78c6f0 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20230805222417-2lj3dvk/20230808120348-orm8sjf/20230808120347-3cob0nb.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20230805222417-2lj3dvk/20230808120348-orm8sjf/20230808120347-3cob0nb.sy@@ -6,7 +6,7 @@"id": "20230808120347-3cob0nb","title": "数据同步","type": "doc",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20230808120347-wx5cr4v",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -52,12 +52,12 @@"Type": "NodeParagraph","Properties": {"id": "20260917190844-x6jwutu",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{"Type": "NodeText",- "Data": "主题和图标包的文件、更新和卸载会在设备间同步,各设备独立选择使用的主题和图标。包内图片、字体等资源始终完整下载。旧客户端可以继续同步笔记,共享外观包及其冲突由新客户端处理。"+ "Data": "主题和图标包的文件、更新和卸载会在设备间同步,各设备独立选择使用的主题和图标。包内图片、字体等资源始终完整下载。同步、删除和冲突与插件、挂件、模板共用文件级规则。恢复的快照中没有某个包时,该包会被删除。"}]},@@ -711,7 +711,7 @@"HeadingLevel": 2,"Properties": {"id": "20230808120347-lptnyvq",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -740,7 +740,7 @@"ListData": {},"Properties": {"id": "20230808120347-j4bqb3a",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -780,7 +780,7 @@},"Properties": {"id": "20230808120347-pvyr15g",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -803,7 +803,7 @@"ListData": {},"Properties": {"id": "20230808120347-vb1ee0l",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -842,7 +842,7 @@},"Properties": {"id": "20230808120347-7p8pzdq",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -850,12 +850,12 @@"Type": "NodeParagraph","Properties": {"id": "20230808120347-t5n8fkj",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{"Type": "NodeText",- "Data": "普通文件发生冲突时,以本地为准覆盖云端,同时拉取到的云端冲突文件会归入数据历史;主题和图标按完整包处理冲突,不会混合不同版本的文件"+ "Data": "文件发生冲突时,以本地为准覆盖云端,同时拉取到的云端冲突文件会归入数据历史;主题和图标文件也遵循此规则"}]}diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230106104645-o838uew.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230106104645-o838uew.syindex f98ab6357f..50369f9f4d 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230106104645-o838uew.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20230106104645-o838uew.sy@@ -6,7 +6,7 @@"id": "20230106104645-o838uew","title": "工作空間","type": "doc",- "updated": "20260917190844"+ "updated": "20260918195936"},"Children": [{@@ -170,7 +170,7 @@{"Type": "NodeTextMark","TextMarkType": "code",- "TextMarkTextContent": "--workspace=\u0026quot;工作空間絕對路徑\u0026quot;"+ "TextMarkTextContent": "--workspace="工作空間絕對路徑""},{"Type": "NodeText",@@ -179,7 +179,7 @@{"Type": "NodeTextMark","TextMarkType": "code",- "TextMarkTextContent": "\u0026quot;"+ "TextMarkTextContent": """},{"Type": "NodeText",@@ -188,7 +188,7 @@{"Type": "NodeTextMark","TextMarkType": "code",- "TextMarkTextContent": "--workspace=\u0026quot;F:\\SiYuan\u0026quot;"+ "TextMarkTextContent": "--workspace="F:\\SiYuan""},{"Type": "NodeText",@@ -270,7 +270,7 @@"HeadingLevel": 2,"Properties": {"id": "20230106104714-4snblro",- "updated": "20260917190844"+ "updated": "20260918195936"},"Children": [{@@ -575,12 +575,12 @@"Type": "NodeParagraph","Properties": {"id": "20260917190844-s9beduz",- "updated": "20260917190844"+ "updated": "20260918195936"},"Children": [{"Type": "NodeText",- "Data": "第三方主題儲存在 data/themes/,圖示套件儲存在 data/icons/,參與資料同步和快照。各裝置的外觀選擇仍儲存在本機 conf/conf.json 中;內建外觀資源不參與同步。升級遷移會保留原有本機檔案供復原。"+ "Data": "第三方主題儲存在 data/themes/,圖示套件儲存在 data/icons/,參與資料同步和快照。各裝置的外觀選擇仍儲存在本機 conf/conf.json 中;內建外觀資源不參與同步。升級遷移將原目錄移入資料目錄,遷移後移除來源副本。"}]}diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20230805232636-zh0adz2/20211226121232-23s79xr/20211226121438-xaafdo8.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20230805232636-zh0adz2/20211226121232-23s79xr/20211226121438-xaafdo8.syindex 21ff42c947..d34057434b 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20230805232636-zh0adz2/20211226121232-23s79xr/20211226121438-xaafdo8.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20230805232636-zh0adz2/20211226121232-23s79xr/20211226121438-xaafdo8.sy@@ -6,7 +6,7 @@"id": "20211226121438-xaafdo8","title": "資料同步","type": "doc",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20211226121454-8vr6fgn",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -52,12 +52,12 @@"Type": "NodeParagraph","Properties": {"id": "20260917190844-m610sh8",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{"Type": "NodeText",- "Data": "主題和圖示套件的檔案、更新和解除安裝會在裝置間同步,各裝置獨立選擇使用的主題和圖示。套件內圖片、字型等資源一律完整下載。舊版客戶端可以繼續同步筆記,共用外觀套件及其衝突由新版客戶端處理。"+ "Data": "主題和圖示套件的檔案、更新和解除安裝會在裝置間同步,各裝置獨立選擇使用的主題和圖示。套件內圖片、字型等資源一律完整下載。同步、刪除及衝突與外掛程式、掛件、範本共用檔案層級規則。還原的快照中沒有某個套件時,該套件會被刪除。"}]},@@ -715,7 +715,7 @@"HeadingLevel": 2,"Properties": {"id": "20211226121454-i5h1wl1",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -744,7 +744,7 @@"ListData": {},"Properties": {"id": "20220703231942-e565c49",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -784,7 +784,7 @@},"Properties": {"id": "20220703231942-xzs4i10",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -807,7 +807,7 @@"ListData": {},"Properties": {"id": "20220703231942-kniy7e9",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -847,7 +847,7 @@},"Properties": {"id": "20220703231942-skyyrpj",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -855,12 +855,12 @@"Type": "NodeParagraph","Properties": {"id": "20220703231942-24cgfdl",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{"Type": "NodeText",- "Data": "一般檔案發生衝突時,以本機為準覆蓋雲端,同時取得的雲端衝突檔案會歸入資料歷史;主題和圖示以完整套件處理衝突,不會混合不同版本的檔案"+ "Data": "檔案發生衝突時,以本機為準覆蓋雲端,同時取得的雲端衝突檔案會歸入資料歷史;主題和圖示檔案也遵循此規則"}]}diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-cb37szr/20240530101000-vhq5afs/20240530101000-wo49zvq.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-cb37szr/20240530101000-vhq5afs/20240530101000-wo49zvq.syindex ee8bc9070e..45126f8496 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-cb37szr/20240530101000-vhq5afs/20240530101000-wo49zvq.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-cb37szr/20240530101000-vhq5afs/20240530101000-wo49zvq.sy@@ -7,7 +7,7 @@"id": "20240530101000-wo49zvq","title": "データ同期","type": "doc",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -17,7 +17,7 @@"Properties": {"ID": "20240530101000-otrm2qw","id": "20240530101000-qw5ujp4",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -54,12 +54,12 @@"Type": "NodeParagraph","Properties": {"id": "20260917190844-vilhr3p",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{"Type": "NodeText",- "Data": "テーマとアイコンパッケージのファイル、更新、アンインストールは端末間で同期されますが、使用するテーマとアイコンは端末ごとに選択できます。パッケージ内の画像やフォントなどは常にすべてダウンロードされます。古いクライアントでも引き続きノートを同期できます。共有する外観パッケージとその競合は新しいクライアントで処理します。"+ "Data": "テーマとアイコンパッケージのファイル、更新、アンインストールは端末間で同期されますが、使用するテーマとアイコンは端末ごとに選択できます。パッケージ内の画像やフォントなどは常にすべてダウンロードされます。同期、削除、競合はプラグイン、ウィジェット、テンプレートと同じファイル単位の規則に従います。パッケージを含まないスナップショットを復元すると、そのパッケージは削除されます。"}]},@@ -772,7 +772,7 @@"Properties": {"ID": "20240530101000-q5e6vx7","id": "20240530101000-ayipniy",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -803,7 +803,7 @@"Properties": {"ID": "20240530101000-ztbegy1","id": "20240530101000-t60qehm",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -846,7 +846,7 @@"Properties": {"ID": "20240530101000-g6lkhbk","id": "20240530101000-8wnwvrn",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -871,7 +871,7 @@"Properties": {"ID": "20240530101000-3quvavd","id": "20240530101000-q0xdonu",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -914,7 +914,7 @@"Properties": {"ID": "20240530101000-7lnae2y","id": "20240530101000-5dmwlq3",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{@@ -923,12 +923,12 @@"Properties": {"ID": "20240530101000-zwjlslj","id": "20240530101000-a04kcnp",- "updated": "20260917202413"+ "updated": "20260918195936"},"Children": [{"Type": "NodeText",- "Data": "通常のファイルが競合した場合はローカルがクラウドを上書きし、クラウド側の競合ファイルはデータ履歴に保存されます。テーマとアイコンの競合はパッケージ全体で処理し、異なるバージョンのファイルを混在させません"+ "Data": "ファイルが競合した場合はローカルがクラウドを上書きし、クラウド側の競合ファイルはデータ履歴に保存されます。テーマとアイコンのファイルにも同じ規則が適用されます"}]}diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-4p096e8.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-4p096e8.syindex 94e8581c89..83c72e6319 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-4p096e8.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-4p096e8.sy@@ -7,7 +7,7 @@"id": "20240530101000-4p096e8","title": "ワークスペース","type": "doc",- "updated": "20260917190844"+ "updated": "20260918195936"},"Children": [{@@ -182,7 +182,7 @@{"Type": "NodeTextMark","TextMarkType": "code",- "TextMarkTextContent": "--workspace=\u0026quot;ワークスペースの絶対パス\u0026quot;"+ "TextMarkTextContent": "--workspace="ワークスペースの絶対パス""},{"Type": "NodeText",@@ -191,7 +191,7 @@{"Type": "NodeTextMark","TextMarkType": "code",- "TextMarkTextContent": "\u0026quot;"+ "TextMarkTextContent": """},{"Type": "NodeText",@@ -200,7 +200,7 @@{"Type": "NodeTextMark","TextMarkType": "code",- "TextMarkTextContent": "--workspace=\u0026quot;F:\\SiYuan\u0026quot;"+ "TextMarkTextContent": "--workspace="F:\\SiYuan""},{"Type": "NodeText",@@ -285,7 +285,7 @@"Properties": {"ID": "20240530101000-j4ly8y7","id": "20240530101000-1mozynr",- "updated": "20260917190844"+ "updated": "20260918195936"},"Children": [{@@ -610,12 +610,12 @@"Type": "NodeParagraph","Properties": {"id": "20260917190844-5om4pnd",- "updated": "20260917190844"+ "updated": "20260918195936"},"Children": [{"Type": "NodeText",- "Data": "サードパーティのテーマは data/themes/、アイコンパッケージは data/icons/ に保存され、データ同期とスナップショットの対象になります。各端末の外観の選択は引き続きローカルの conf/conf.json に保存されます。内蔵の外観リソースは同期されません。アップグレード時の移行では、復元用に元のローカルファイルを保持します。"+ "Data": "サードパーティのテーマは data/themes/、アイコンパッケージは data/icons/ に保存され、データ同期とスナップショットの対象になります。各端末の外観の選択は引き続きローカルの conf/conf.json に保存されます。内蔵の外観リソースは同期されません。アップグレード時に元のディレクトリをデータディレクトリへ移行し、移行後に元のディレクトリを削除します。"}]}diff --git a/docs/APPEARANCE-SYNC.md b/docs/APPEARANCE-SYNC.mdindex 70a6a8aca3..4b3cf04678 100644--- a/docs/APPEARANCE-SYNC.md+++ b/docs/APPEARANCE-SYNC.md@@ -2,214 +2,40 @@[中文](APPEARANCE-SYNC.zh-CN.md)-Related issue: https://github.com/siyuan-note/siyuan/issues/18883+Related issues: [#18883](https://github.com/siyuan-note/siyuan/issues/18883), [#19634](https://github.com/siyuan-note/siyuan/issues/19634), [#19635](https://github.com/siyuan-note/siyuan/issues/19635)-## Feature scope+## File synchronization-Third-party themes and icons synchronize as complete packages, including installation state, updates, and deletions. Desktop and mobile clients share the kernel implementation. Full and on-demand download modes both fetch complete appearance packages, including images, fonts, and other resources required by package code.+Third-party themes in `data/themes/<name>/` and icons in `data/icons/<name>/` use the same file-level synchronization, deletion, conflict handling, and snapshots as plugins, widgets, and templates. Removing a package directory deletes its synchronized files. Changes to different files in the same package can merge; conflicting versions of an individual file follow the ordinary synchronization rules and data history behavior.-Built-in `daylight`, `midnight`, and `litheness` resources remain part of the application and do not enter synchronized package storage. Data directories with these names must not override the built-in resources. Light and dark theme selections, the icon package, appearance mode, and following the system appearance remain device settings in `conf/conf.json`.+Built-in `daylight`, `midnight`, and `litheness` resources remain application resources. Each device keeps its appearance selection in `conf/conf.json`. Receiving a package does not automatically select it. Synchronization and snapshot restoration refresh the package list and the resources used by the current selection. Missing, incompatible, or incomplete packages fall back to built-in resources. Theme frontend compatibility and `minAppVersion` checks remain in effect.-Older clients continue synchronizing notes without upgrading. They transport internal package files using the existing synchronization mechanism; package installation, deletion, conflict resolution, and appearance restoration require a client that supports this feature. Ordinary documents and other data retain their existing file-level synchronization rules.+Snapshots restore the complete data directory. A snapshot without a theme or icon package removes that package, including snapshots created before these directories participated in synchronization.-## User interaction+## Assets and ignore rules-Installing, updating, or uninstalling a third-party theme or icon package publishes a complete package change. Receiving a newly installed package does not automatically select it on another device. After synchronization or snapshot restoration, the client refreshes the available package list and the resources used by the current selection.+On-demand downloading applies only to `/assets/`, `/<boxID>/assets/`, and `/<boxID>/<documentID>/.../assets/`. Notebook and document directory names must have the normal block ID format. Package assets under themes, icons, plugins, widgets, and templates are downloaded with their ordinary files. OCR metadata and annotation files retain their existing full-download behavior.-`theme.json` and `icon.json` do not introduce an author-controlled synchronization switch. Themes continue to use `frontends`: an absent or empty value does not enable mobile support, and `all` supports every frontend. Runtime loading also checks `minAppVersion`. An unavailable local selection falls back to the built-in appearance.+Previously deferred package assets remain readable through the authenticated download-state format. Indexing and synchronization download those files before removing their deferred entries. Download failures retain the entries for retry; existing local edits are preserved.-Users may edit local CSS, scripts, and images. Package digests describe synchronized content; normal runtime loading and exports do not require users to regenerate them after each edit. Before creating a snapshot, the kernel records local changes and verifies the complete package. A package involved in an unfinished installation, an authenticated pending synchronization operation, or legacy deferred resource downloads remains temporarily unavailable. The frontend uses a built-in appearance while retaining the local selection, then refreshes it after recovery.+The ordinary `.siyuan/syncignore` rules apply to individual files and directories. For example, `/themes/example/` excludes a theme and `/themes/example/assets/draft.png` excludes one file. Symbolic links used for local development remain local and are excluded by the ordinary synchronization path policy.-If a package is incomplete or fails validation, the operation returns an error and preserves its directory, state, and recovery history. Recovery must use a consistent complete package or an explicit reinstall. Deleting state files to bypass validation is not a supported recovery procedure.+## Migration-## Data and storage+Startup moves third-party packages from the previous appearance directory into `data/themes/` and `data/icons/`. An existing destination takes precedence. Successfully migrated source directories are removed, so deleting a package or restoring an older snapshot cannot recreate it from the original directory. Built-in resources remain in the application appearance directory.-### Directories and package state+The upgrade removes complete generated `siyuan-appearance-isolation:v1` blocks from `.siyuan/syncignore` once they are encountered. User-written rules outside those blocks retain their contents and order. No isolation block is created or maintained afterward.-| Path | Purpose | Synchronization scope |-|---|---|---|-| `data/themes/<name>/` | Local third-party theme directory | Restored from package events; excluded from ordinary file synchronization |-| `data/icons/<name>/` | Local third-party icon directory | Restored from package events; excluded from ordinary file synchronization |-| `data/storage/bazaar/themes/<name>.json` | Per-theme installation state | Restored with the package event; not synchronized independently |-| `data/storage/bazaar/icons/<name>.json` | Per-icon-package installation state | Restored with the package event; not synchronized independently |-| `data/storage/appearance-v1/` | Immutable package events and format marker | Retained through existing file synchronization and snapshots |-| `conf/conf.json` | Device appearance selection | Excluded from package synchronization |--Themes and icons no longer update the shared `storage/bazaar.json` file. Its existing contents remain a migration fallback for installation time and package source information. Other marketplace package types continue using the existing mechanism.--The state is an internal kernel format, separate from the manifest maintained by a package author:--```json-{- "version": 1,- "deleted": false,- "migration": false,- "installTime": 0,- "updateTime": 0,- "repoURL": "https://github.com/owner/package",- "repoRef": "main",- "files": {- "theme.css": "64-character-lowercase-sha256"- }-}-```--`files` maps relative POSIX paths within the package to the SHA-256 digests of plaintext files. The inventory follows existing synchronization filtering rules: ordinary hidden directories, dot-prefixed files, and `.tmp` files are excluded, while permitted `.siyuan` directories are retained. Unknown versions, invalid paths, case or Unicode normalization collisions, missing files, and digest mismatches return errors and preserve the source material.--A deletion state retains installation source information, sets `deleted: true`, and contains an empty `files` object. Synchronized package files are removed; an empty directory or retained local ignored files do not count as a reinstall or block subsequent snapshots and synchronization. Migration creates a state with `migration: true`. Explicit installation, updates, and local edits create ordinary states. A late migration must not remove an existing deletion record. An explicit reinstall creates a new non-deleted state.--### Immutable package events--DejaVu stores each complete package event at `data/storage/appearance-v1/<kind>/<name>/<sha256>.sypkg`, where `<kind>` is `themes` or `icons`. Each event is a ZIP Store archive containing `appearance.json`, `state.json`, and the payload under `files/`. Entry ordering, timestamps, and permissions are fixed, so identical inputs produce identical archive bytes. The filename digest covers the entire archive. A deletion event contains metadata and deletion state without a payload.--`appearance.json` identifies the format, package, and predecessor events:--```json-{- "version": 1,- "kind": "themes",- "name": "example",- "parents": []-}-```--`parents` contains sorted, unique predecessor digests. Updates, deletions, and merge resolutions create new event paths and never overwrite existing events. The fixed `data/storage/appearance-v1/format.json` marker contains `{"version":1,"type":"siyuan-appearance-events"}` followed by a newline. It distinguishes a snapshot that supports this feature but contains no packages from a legacy snapshot without appearance events.--Archives retain the existing `File.ID` algorithm. That algorithm uses the path and second-resolution modification time, so different local contents can receive the same identifier before either device synchronizes. A cloud lock serializes synchronization operations but cannot distinguish identifiers already created from the same path and second. Immutable event paths include the content digest, so package changes do not rely on modification times for identity. The existing snapshot, chunking, encryption, and authentication formats remain unchanged.--Before publishing a local package directory, the reader verifies the archive filename digest, package identity, predecessor relationships, paths, state format, and all payload digests. The event graph must contain every referenced predecessor and must not contain cycles. The fixed format marker requires separate authentication; a cached object with the expected legacy identifier does not prove that the authoritative source still contains a supported marker.--## Implementation and interfaces--### Merge rules--New clients retain all known shared events before selecting a complete version for each package. Descendants supersede their ancestors. Concurrent events are resolved as complete packages, and a new event records the selected version with all concurrent heads as parents. This preserves the decision across later synchronization operations.--| Situation | Behavior |-|---|---|-| Only one device changes a complete package | Use that device's package |-| Concurrent updates | Use the cloud package and preserve the other complete package in conflict history; use a stable digest ordering when no cloud head distinguishes the candidates |-| Concurrent update and deletion | Prefer deletion and preserve the discarded complete package in history |-| Late migration encounters an existing cloud deletion | Retain the deletion without restoring the old installation |-| Explicit reinstall after observing a deletion | Synchronize a new installation descended from the known deletion |-| Legacy snapshot without the format marker | Retain existing appearances; missing event records do not imply uninstalling packages |-| Restore an earlier package version from a new-format snapshot | Create a new restoration event while retaining current known events and recovery material |-| Archive, state, or payload validation fails | Stop applying the package and preserve source data without publishing a partial directory |--DejaVu's `EnableAppearanceSync` option enables package handling. `AppearanceIgnoreLines` supplies the user's rules after removing the valid managed isolation block. `BeforeAppearanceApply` lets the kernel ensure isolation rules exist after ordinary file restoration and before local appearance directories are applied. The callback must run without holding the appearance lock. These are internal integration interfaces; the feature does not add public HTTP endpoints or change public configuration fields.--Package resources must download together with package code in both full and on-demand modes. Ordinary attachments may still be deferred in on-demand mode. Bidirectional, upload-only, and download-only synchronization use the same complete-package boundary. Existing deferred-download state and version 1 recovery journals remain readable, and legacy deferred appearance resources are completed before applying their package.--### Runtime loading and exports--Resource URLs remain `/appearance/themes/...` and `/appearance/icons/...`. The kernel resolves them to built-in resources or the corresponding local third-party directory. Exports copy the complete theme and icon resource sets, including auxiliary files referenced by scripts.--Runtime loading and exports validate state format and deletion status without automatically rewriting content digests. Packages with authenticated pending operations are not activated. This permits normal manual editing while ensuring that digest regeneration cannot conceal incomplete synchronization.--After synchronization or snapshot recovery, the kernel refreshes available packages, rebinds theme file watchers, and sends the internal `refreshAppearance` notification. The frontend advances a resource cache revision for changed packages while retaining the public theme and icon version fields. Updating a package without changing its declared version therefore still reloads current resources. The desktop main window, detached windows, and mobile frontend use the same notification protocol.--Theme script loading and unloading are serialized. Historical theme scripts retain their unload lifecycle. If a script cannot be safely unloaded, the interface reloads before applying the new appearance.--### Cache and concurrency--Package installation, scanning, resource reads, and publication share an appearance lock. Windows directory replacement may have a brief interval when the directory is unavailable; coordinated reads must not observe a partially replaced package. Before snapshot creation, pending local operations are recovered and local changes are scanned. Indexing verifies the stored chunks again and rejects an inconsistent package if files changed during scanning.--Historical archive metadata uses a bounded in-memory cache. Entries are reused only after complete validation and while the source identity remains unchanged; full package contents are loaded only for event heads. Windows checks file identity, timestamps, and file USN. Supported other systems require complete identity information and a stable high-resolution change time. If reliable change information is unavailable, the archive is read and validated again. The format marker is always authenticated separately and does not use this cache.--Cache keys distinguish repository sources, file contents, chunk sequences, and encryption keys. Validation must detect closed-file rewrites that preserve modification time, ciphertext corruption, and incorrect keys. Archive decoding allocates payload buffers from declared lengths and verifies sizes and CRCs. When multiple packages reuse a font or another content chunk, per-chunk read and write serialization prevents concurrent publication and reading conflicts on Windows. Snapshot change detection remains read-only.--### Related repositories--| Repository | Integration scope |-|---|---|-| `siyuan` | Data directories, migration, installation state, resource routes, runtime fallback, exports, synchronization and snapshot hooks, frontend refresh, and user guides |-| `dejavu` | Archives compatible with legacy file identifiers, event merging, recovery references, complete digest validation, deletion records, complete conflict history, on-demand compatibility, package application, and interrupted-operation recovery |-| `theme-sample`, `icon-sample` | English and Chinese development-directory documentation and theme frontend support documentation |-| `siyuan-testing` | Tests for resources in actual data directories, same-version CSS refresh, and built-in fallback after uninstalling |-| `bazaar` | Existing theme and icon manifest validation remains sufficient; no new author fields or packaging format changes |-| `siyuan-android`, `siyuan-ios`, `siyuan-harmony` | Shared kernel and existing resource URLs; no native bridge changes, with device verification required for upgrades and cold starts |-| `petal`, `plugin-sample`, `siyuan-chrome`, `protyle`, `go-sdk` | No public configuration or HTTP API changes requiring declaration or caller updates |-| `lute`, `riff`, `gulu`, `filelock`, `eventbus`, `httpclient`, `logging`, and other Go dependencies | Existing formats and capabilities remain in use without additional protocol changes |--## Compatibility and recovery--### Existing data and clients--Older clients transport immutable archives as ordinary files and continue synchronizing notes. They do not use the new runtime directories or apply complete appearance packages. No repository-wide upgrade gate or new file identifier format is required.--Existing encrypted notebooks, snapshots, backups, history, and supported deferred-download states remain compatibility baselines. Their authenticated readers and recovery paths must remain available. The feature does not change key envelopes, MasterSalt, AAD semantics, or key derivation. Unknown formats, corruption, and authentication failures preserve original data and return errors; they must not bypass authentication, regenerate MasterSalt, discard keys, or fall back to plaintext. Staging data and derived caches do not replace authenticated source content.--### Migration and ignore rules--Migration copies and validates third-party packages from legacy directories while retaining the originals. Existing destination directories and states take precedence. Untracked directories without synchronizable files remain untouched and are skipped without blocking other packages. The completion marker `conf/appearance-migration.json` is local to the device and prevents repeated startup migration from reimporting uninstalled packages.--For development packages using symbolic links, migration retains a link to the original package. A package-root link without synchronization state remains local, and ordinary synchronization does not follow it into an external directory. A package that already has synchronization state must be explicitly excluded as a whole before being changed to a link, so the change is not interpreted as deletion or reinstallation.--Before creating local appearance directories, the kernel persists this versioned managed block at the end of `.siyuan/syncignore`:--```text-# siyuan-appearance-isolation:v1:begin-/themes/-/icons/-/storage/bazaar/themes/-/storage/bazaar/icons/-# siyuan-appearance-isolation:v1:end-```--Older engines honor these rules, and new clients additionally protect the local directories through path filters. The kernel preserves the user's existing rules and bytes. An unknown, incomplete, or modified managed block returns an error and preserves the original file. If synchronization or snapshot restoration restores earlier rules, isolation must be re-established before the next index or package application.--The local `.siyuan/.appearance-syncignore-clock-v1` file records reserved modification-time seconds for rule updates and is excluded from snapshots and cloud synchronization. A new second is durably reserved before changing the isolation rules, preventing legacy file identifier reuse after restoring old rules or moving the system clock backward. Unknown or corrupt clock records return errors and preserve the original file.--New clients remove only a complete valid managed block when evaluating the user's appearance rules. Existing user rules still apply. For example, `/themes/example/` excludes a complete package; `/themes/` or `/icons/` excludes an entire category. Excluding `/storage/` or `/storage/appearance-v1/` disables the internal appearance protocol. Excluding only part of a tracked package or its state record must not produce an incomplete package: integrity checks return an error. Whole-directory replacement preserves existing ignored files and checks for local edits made during application.--Whole-package exclusion prevents uploading or applying that package. Unknown, damaged, or missing archive payloads belonging to an excluded package are not fetched from the cloud or LAN, are not decoded, and do not block note synchronization. Protocol path, identity, and format-marker checks remain effective. Private local events that were never uploaded must not enter a cloud recovery reference. Already shared cloud events, including deletion records, remain referenced even after their package is excluded; retaining their references does not require downloading, repairing, or re-uploading the excluded payloads.--### Interrupted operations and snapshot restoration--Application first downloads, validates, and stages the complete package. It then backs up the old directory on the same filesystem, replaces the directory, and publishes the state. Synchronization uses the existing asset recovery journal. Local installation uses journals under `data/.siyuan-appearance-ops`, with previous directories retained under `data/.siyuan-appearance-backups`. Synchronization replacements preserve previous directories in history; if a cross-filesystem rename is unavailable, recovery retains a backup on the original volume.--Startup, the next operation, and snapshot preparation can continue an unfinished transaction. Journals record the expected source state. If recovery discovers additional local changes, it preserves current files, staging data, and recovery material and returns an error. Retries must retain changes already applied and must not publish partially verified packages.--A legacy snapshot without the format marker does not imply deletion of current appearances. Restoring a new-format snapshot creates restoration events relative to currently known event heads, preserving later events and recovery material. Single-file cloud restoration must reject package payloads, installation state, and files in the internal archive namespace; these require the complete snapshot and package recovery flow. Complete snapshots and their required content must be available before restoration; partial cloud snapshots must not silently discard package or ordinary workspace data.--### Recovery references and limitations--The internal `.siyuan-appearance-v1` tag references a complete ordinary workspace snapshot containing retained appearance events. It must not reference an appearance-only snapshot, because an older client restoring that snapshot could otherwise delete notes. Publication uploads the complete objects and snapshot first, then publishes the recovery reference, and finally publishes the latest reference. If an older client restores and republishes an early snapshot without appearance events, a new client uses the recovery reference to restore event knowledge, including deletion records.--The cloud recovery reference combines the target workspace snapshot with previously shared cloud events. It must not copy private, unshared events from a local recovery reference. If only excluded events disappear from the latest snapshot and no new events need publication, the previous cloud recovery reference remains unchanged while note synchronization proceeds.--New clients hide and protect the internal tag only after authenticating a snapshot containing this protocol's format marker. They exclude the verified internal tag from the user backup count. A pre-existing user tag with the same name remains visible and editable; automatic publication returns a conflict instead of overwriting it. Internal recovery updates do not consume the quota for creating user backups. An older client may display this ordinary tag and count it as one backup slot; note synchronization remains available.--Event history retains complete shared package versions, so storage grows with package updates. Cloud repositories may reuse unchanged chunks, but local archives still contain complete packages. There is no automatic event-history compaction. Ordinary history cleanup must retain events reachable from the recovery reference. Deliberately removing the recovery tag and all related history removes that recovery material and prevents recovery of otherwise deleted events.--Publishing the recovery reference before the latest reference depends on the existing cloud lock serializing synchronization. Lock acquisition uses a read followed by a write, so extreme simultaneous acquisition or lock loss remains a limitation. The feature does not extend the server lock protocol or guarantee preservation of every reference after arbitrary lock loss followed by cleanup.+The released implementation does not create per-package digest or deletion records, immutable package archives, recovery tags, or an appearance-specific transaction protocol. Installation metadata uses the shared `storage/bazaar.json` mechanism. Alpha leftovers in `data/storage/appearance-v1/`, `data/storage/bazaar/themes/`, `data/storage/bazaar/icons/`, and `conf/appearance-migration.json`, and existing `.siyuan-appearance-v1` tags are not automatically cleaned up or used to restore packages. Existing tags follow ordinary tag behavior.## Verification-### Regression coverage--Regression coverage must include local installation and migration, manual edits, unknown-format preservation, unchanged scans without state rewrites, explicit reinstall, same-second edits and preserved modification times, concurrent updates and deletions, complete conflict history, whole and partial ignore rules, ignored damaged payloads and private-event protection, retained public deletion records, full and on-demand downloads, one-way synchronization, LAN authentication and traffic accounting, interrupted application, snapshot rollback, single-file restoration restrictions, symbolic links, resource reload without a declared version change, and built-in fallback.--Run the appearance-related tests in the kernel's `bazaar`, `util`, `model`, and `server` packages. In DejaVu, run appearance, asset, snapshot, backup, authentication, cloud-lock, and `lansync` regression tests. Cache validation must include closed-file rewrites that preserve modification time, corrupted ciphertext, incorrect keys, bounded memory use, and concurrent use of shared chunks. Run applicable frontend unit tests and `pnpm run lint` from `app/`.--The history benchmark is available from the DejaVu root:+Run the following with the matching local DejaVu dependency:```text-go test . -run ^$ -bench ^BenchmarkAppearanceHistory$ -benchtime=1x -count=1-```+# dejavu/+go test ./... -run "TestAsset|TestPackageFiles|TestIndexReused|TestSyncReused|TestSnapshot|TestDownload|TestUploadTag" -count=1-The benchmark uses ten complete historical versions with a 20 MiB payload each. Large history fixtures belong to the benchmark rather than routine regression tests. Compare unchanged scans and snapshots separately from initial reads, which must fully authenticate content. Performance depends on filesystem support, cache state, history size, and package contents.--End-to-end tests in `siyuan-testing` use an already running dedicated instance with a kernel that includes the feature. Do not build frontend artifacts or compile and restart a running kernel to perform these checks. Official cloud, S3, WebDAV, and desktop and mobile upgrades, cold starts, script unloading, and cross-device refresh require verification in their actual environments. Local automated results do not replace those acceptance checks.--### Mixed-version verification--Run `python scripts/test-appearance-compat.py` from the DejaVu root. The independent legacy driver pins the released module `v0.0.0-20260914113714-464364dd8fad`, rejects local dependency replacements, and verifies dependencies with `go mod verify`. The script freezes the current source into a temporary directory and records versions, source digests, requests, and responses in its report.--The matrix combines full and on-demand downloads with bidirectional and manual upload/download synchronization. Each combination verifies an old client continuing to edit notes, receiving installation and deletion events, restoring an early snapshot without appearance events, resuming synchronization, and purging local and cloud history. A fresh new client must then recover deletion records while retaining the latest notes. In on-demand mode, ordinary attachments may remain deferred while appearance archives download completely.--The test retains evidence of the unmodified legacy `cloud.Local` failure when cloud cleanup encounters tag directories. Only the cleanup compatibility segment uses a test adapter that recursively enumerates every file under `refs/`, satisfying the backend's reference-listing contract. It does not modify the pinned legacy synchronization, cleanup, or authentication source. This verifies that the old engine can retain recovery material through ordinary tags; it does not establish end-to-end acceptance for the official cloud service or mobile devices.--### Dependency release--The kernel depends on the DejaVu package synchronization and recovery interfaces. Publish a DejaVu version containing these interfaces before updating `kernel/go.mod` for release. Local development may use a temporary `replace` pointing to the DejaVu checkout; it must not be committed. Updating only the main repository while retaining a legacy DejaVu dependency omits the complete-package synchronization guarantees. Coordinate release of the main repository, dependency, theme and icon sample documentation, and end-to-end tests.+# siyuan/kernel/+go test -tags "fts5 sqlcipher" ./model ./bazaar ./util ./server -run "Test.*Appearance|Test.*ThemesWatch|Test.*SyncIgnore" -count=1+```diff --git a/docs/APPEARANCE-SYNC.zh-CN.md b/docs/APPEARANCE-SYNC.zh-CN.mdindex ad4ffabc62..fb9f66aca2 100644--- a/docs/APPEARANCE-SYNC.zh-CN.md+++ b/docs/APPEARANCE-SYNC.zh-CN.md@@ -2,206 +2,40 @@[English](APPEARANCE-SYNC.md)-对应需求:https://github.com/siyuan-note/siyuan/issues/18883+相关议题:[#18883](https://github.com/siyuan-note/siyuan/issues/18883)、[#19634](https://github.com/siyuan-note/siyuan/issues/19634)、[#19635](https://github.com/siyuan-note/siyuan/issues/19635)-## 功能范围+## 文件同步-第三方主题和图标以完整包为单位参与数据同步、快照、安装、更新和卸载。桌面主窗口、独立窗口和移动前端共用内核实现及资源 URL。旧客户端可以继续同步笔记,并将内部外观归档作为普通文件运输;外观包的安装、合并和还原由支持此功能的客户端完成。+第三方主题位于 `data/themes/<name>/`,图标包位于 `data/icons/<name>/`,与插件、挂件、模板共用文件级同步、删除、冲突处理及快照逻辑。删除包目录就会删除对应的同步文件。同一个包中不同文件的修改可以合并;单个文件的不同版本发生冲突时,遵循普通文件的同步规则和数据历史行为。-明亮主题、暗黑主题、图标、模式及跟随系统等选择保存在各设备的 `conf/conf.json` 中,不随包安装而自动切换。内置 `daylight`、`midnight` 和 `litheness` 使用应用随附资源,不进入第三方包同步目录,同名数据目录不能覆盖内置资源。+内置的 `daylight`、`midnight`、`litheness` 仍属于程序资源。各设备在 `conf/conf.json` 中独立保存外观选择,收到一个包不会自动选用它。同步和恢复快照后,会刷新包列表及当前选择使用的资源。包缺失、不兼容或必要文件不完整时,回退到内置资源。主题的前端兼容性及 `minAppVersion` 检查保持有效。-`theme.json` 和 `icon.json` 不增加同步开关。主题仍遵守 `frontends`,缺省或空值不支持移动前端,`all` 表示所有前端;运行时同时检查 `minAppVersion`。普通文档和其他数据继续使用原有文件级同步规则。+快照恢复针对整个数据目录。快照中不存在的主题或图标包会被删除,包括恢复主题、图标尚未参与同步时创建的旧快照。-## 用户交互+## 资源文件及忽略规则-安装、更新或卸载包后,同步将完整版本或删除记录传播到其他设备。其他设备收到包不会改变其本机外观选择;当前使用的包被删除或与本机不兼容时,界面回退到内置外观。+按需下载只适用于 `/assets/`、`/<笔记本ID>/assets/` 和 `/<笔记本ID>/<文档ID>/.../assets/`,笔记本和文档目录名必须符合正常的块 ID 格式。主题、图标、插件、挂件及模板中的资源随普通文件完整下载。OCR 元数据及标注文件继续保持原有的完整下载行为。-用户可以在本机编辑包内 CSS、脚本、图片等文件。建立快照前扫描这些修改并更新完整性记录,正常运行及导出不自动重写摘要。未完成安装、同步恢复或旧版延期资源涉及的包暂不可用时,界面显示内置外观并保留本机原选择,恢复完成后刷新。+旧版下载状态中已经延期的包资源仍通过原有格式认证读取。索引和同步会先下载这些文件,再移除对应的延期记录。下载失败时保留记录供重试,已存在的本地修改不会被覆盖。-同版本号的内容更新也会刷新当前资源。主题脚本继续执行卸载生命周期;无法安全卸载时重新加载界面。忽略规则可以排除完整包,但不能通过只排除部分文件或单独排除安装状态来生成不完整包。+普通 `.siyuan/syncignore` 规则同时适用于单个文件和目录。例如,`/themes/example/` 忽略整个主题,`/themes/example/assets/draft.png` 只忽略一个文件。用于本地开发的符号链接继续保留在本机,由普通同步路径策略排除。-## 数据与存储+## 迁移-### 目录与安装状态+启动时将旧外观目录中的第三方包移入 `data/themes/` 和 `data/icons/`,已有目标目录优先。迁移成功后移除源目录,避免删除包或恢复旧快照后又从原目录复活。内置资源仍保留在程序外观目录中。-| 路径 | 用途 | 同步范围 |-|---|---|---|-| `data/themes/<name>/` | 本机第三方主题目录 | 从整包事件还原,不直接进入普通文件同步 |-| `data/icons/<name>/` | 本机第三方图标目录 | 从整包事件还原,不直接进入普通文件同步 |-| `data/storage/bazaar/themes/<name>.json` | 每个主题的安装状态 | 随整包事件还原,不单独同步 |-| `data/storage/bazaar/icons/<name>.json` | 每个图标包的安装状态 | 随整包事件还原,不单独同步 |-| `data/storage/appearance-v1/` | 不可变整包事件及格式标记 | 通过原有文件同步和快照保存 |-| `conf/conf.json` | 本机外观选择 | 不参与包同步 |+升级时一次性移除 `.siyuan/syncignore` 中完整的 `siyuan-appearance-isolation:v1` 系统规则块,保留块外用户规则的内容和顺序。此后不再生成或维护隔离块。-主题和图标不再更新单文件 `storage/bazaar.json`;旧文件只作为迁移安装时间及来源信息的后备,其他类型集市包仍使用原有机制。每个包的状态属于内核内部格式,不是集市作者清单:+正式实现不再生成逐包摘要及删除记录、不可变包归档、恢复标签,也不再使用外观专用事务协议。安装信息复用共享的 `storage/bazaar.json` 机制。Alpha 版本遗留的 `data/storage/appearance-v1/`、`data/storage/bazaar/themes/`、`data/storage/bazaar/icons/`、`conf/appearance-migration.json` 及已有的 `.siyuan-appearance-v1` 标签不做自动清理,也不用于恢复外观包。已有标签按普通标签处理。-```json-{- "version": 1,- "deleted": false,- "migration": false,- "installTime": 0,- "updateTime": 0,- "repoURL": "https://github.com/owner/package",- "repoRef": "main",- "files": {- "theme.css": "64-character-lowercase-sha256"- }-}-```--`files` 使用包内相对 POSIX 路径和明文文件的 SHA-256。文件集合遵守既有过滤约定,排除普通隐藏目录、点前缀文件和 `.tmp`,保留允许的 `.siyuan` 目录。未知版本、非法路径、大小写或 Unicode 等价名称冲突、缺文件和摘要不符必须返回错误并保留原数据。--删除状态保留安装来源信息,设置 `deleted: true` 和空 `files`。已同步的包文件被移除;残留空目录或保留的本机忽略文件不视为重新安装,也不阻断后续快照及同步。迁移生成 `migration: true`;明确安装、更新和本地手工修改形成正常状态。快照前先恢复未完成操作,再扫描本地修改,索引还须验证实际保存的分块,拒绝扫描期间变化产生的不一致包。--### 不可变整包事件--DejaVu 将完整包内容和状态保存到 `data/storage/appearance-v1/<kind>/<name>/<sha256>.sypkg`,其中 `<kind>` 为 `themes` 或 `icons`。归档使用 ZIP Store,包含 `appearance.json`、`state.json` 和 `files/`,条目顺序、时间及权限固定,文件名摘要覆盖全部归档字节。更新和删除均创建新事件,不覆盖既有路径;删除事件只包含元数据和删除状态,不包含包资源。--`appearance.json` 记录版本、包类型、包名及前驱事件:--```json-{- "version": 1,- "kind": "themes",- "name": "example",- "parents": []-}-```--`parents` 是排序且不重复的前驱摘要列表。前驱必须存在,事件图不能包含循环。`data/storage/appearance-v1/format.json` 的固定内容是 `{"version":1,"type":"siyuan-appearance-events"}` 加一个换行符,用于区分支持此功能的空快照与尚无此功能的旧快照。格式标记须单独认证,不能仅凭本地缓存中相同的旧文件标识认定权威来源的内容仍受支持。--归档沿用原有 `File.ID` 算法。不同内容具有不同路径,因此外观更新不依赖文件修改时间区分。原有路径和秒级修改时间可能使不同内容具有相同文件标识;云端锁只串行化同步过程,不能区分同步前已经生成的相同标识。不可变归档解决外观事件的标识问题,不改变普通文件、分块、传输、加密或快照认证格式。--## 实现与接口--### 合并规则--新客户端合并所有参与共享的已知事件,先按因果关系选择事件头,后代覆盖祖先。并发事件按下表选择完整版本,并创建以所有并发头为前驱的新事件,将选择结果持久化。--| 情况 | 处理 |-|---|---|-| 仅一端更改完整包 | 使用该端整包 |-| 两端同时更新 | 使用云端整包,保留另一端完整包的冲突历史;没有云端事件头可区分候选时按稳定摘要顺序选择 |-| 更新与删除并发 | 删除优先,保留被舍弃的完整包历史 |-| 晚迁移遇到已有云端删除记录 | 保留删除,不恢复旧安装 |-| 在已知删除状态上明确重装 | 建立新的本地安装事件并同步 |-| 旧快照没有本功能格式标记 | 保留现有外观,不将缺少记录视为卸载 |-| 新快照还原到早期包版本 | 建立新的恢复事件,保留当前已知事件和恢复材料 |-| 参与共享的归档、状态或内容校验失败 | 停止应用,保留源数据,不发布部分目录 |--应用前验证归档文件名摘要、包身份、前驱关系、路径、状态格式和全部内容摘要。主题和图标的图片、字体等资源必须与代码同时下载,即使普通资源使用按需下载也不延期。同步、仅上传和仅下载入口使用同一整包边界。--DejaVu 的 `EnableAppearanceSync` 选项启用整包处理,`AppearanceIgnoreLines` 提供移除合法受管隔离块后的用户规则,`BeforeAppearanceApply` 在普通文件还原后、外观目录发布前确保持久隔离规则存在。回调执行时不得持有外观锁。这些属于内部集成接口,不增加公开 HTTP 端点,也不改变公开配置字段。--### 运行时加载与导出--资源 URL 保持 `/appearance/themes/...` 和 `/appearance/icons/...`,由内核解析到内置资源或对应本机包目录。正常加载和导出检查状态格式及删除记录,不因用户手工编辑而重写完整性摘要。未完成事务和已经认证的恢复状态由专用检查处理,不得绕过认证加载不完整包。--导出复制整套主题和图标资源,包括脚本引用的附属文件。同步及快照恢复完成后,内核刷新本机可用列表、重新绑定主题文件监听器,并发送内部 `refreshAppearance` 通知。前端按变更包更新缓存修订号,保留公开的主题和图标版本字段;主窗口、独立窗口及移动前端采用相同协议。--### 缓存与并发--历史归档使用有界内存缓存,仅复用已经完整校验且源身份未变的事件元数据,完整内容按事件头载入。缓存键区分仓库源、文件内容、分块序列和加密密钥。Windows 使用文件身份、时间及文件 USN;支持的其他系统要求完整身份和已稳定的高精度变化时间。无法取得可靠变化信息时仍完整读取,格式标记始终单独认证,不使用该缓存。--缓存不得使保留修改时间的闭合文件改写、密文损坏或错误密钥绕过源验证。归档解码按声明长度分配资源缓冲区,并完成大小及 CRC 校验。多个包复用同一字体等内容时,单块读写互斥,避免并行发布与读取冲突。--快照变更预检查保持只读,不下载资源、修复引用或写入分块。--资源请求和包的安装、扫描、提交通过共享外观锁协调,避免读取替换过程中的半个包。Windows 目录替换可能短暂不可用;同步隔离规则回调在普通文件恢复后、外观目录发布前执行,此时不得持有外观锁。--### 关联项目--| 项目 | 联动范围 |-|---|---|-| `siyuan` | 数据目录、迁移、安装状态、资源路由、运行时回退、导出、同步与快照钩子、三端刷新、用户指南 |-| `dejavu` | 内部归档、事件合并、恢复引用、摘要验证、删除记录、完整冲突历史、按需兼容、整包应用及中断恢复 |-| `theme-sample`、`icon-sample` | 中英文开发目录说明及主题前端支持说明 |-| `siyuan-testing` | 真实数据目录资源、同版本 CSS 刷新、卸载后的默认回退测试 |-| `bazaar` | 沿用现有主题、图标清单规则,不增加作者字段或改变打包格式 |-| `siyuan-android`、`siyuan-ios`、`siyuan-harmony` | 使用共享内核和原资源 URL,无需修改原生桥接;升级及冷启动需要实机验证 |-| `petal`、`plugin-sample`、`siyuan-chrome`、`protyle`、`go-sdk` | 公开配置字段和 HTTP API 不变,无需声明或调用方变更 |-| `lute`、`riff`、`gulu`、`filelock`、`eventbus`、`httpclient`、`logging` 及其余 Go 依赖 | 沿用现有格式和能力,无需配套修改 |--## 兼容与恢复--### 已有数据与客户端--旧客户端继续按原协议同步笔记,并运输内部归档;不要求全部客户端升级。旧客户端不采用新的资源目录,也不执行整包安装、合并及还原。已有快照、按需下载状态和第一版恢复日志保持可读,旧状态中延期的外观资源在包应用前补齐。--笔记本加密、密钥、备份及历史数据的认证规则不变,不改变密钥信封、主盐、AAD 或密钥派生。不得通过重新生成主盐、丢弃密钥或明文回退处理未知版本、损坏或认证失败。失败必须保留源数据及恢复材料;暂存和派生缓存不能取代已认证的原始内容。--### 迁移与忽略规则+## 验证-迁移先复制并校验旧外观目录中的第三方包,保留原目录;已有目标目录和已有状态优先。无可同步文件的未安装目录保持原样并跳过,不阻断其他包。完成标记 `conf/appearance-migration.json` 只存在本机,重复启动不再次导入已卸载的包。--开发包使用符号链接时,迁移保留到原包的链接关系;无同步状态的包根链接仅在本机使用,普通同步不跟随链接到外部目录。已有同步状态的包改成链接时,必须明确排除整个包,避免误判删除或重新安装。--首次生成本机外观目录前,在 `.siyuan/syncignore` 末尾持久化带显式版本的受管注释块:+使用对应的本地 DejaVu 依赖执行:```text-# siyuan-appearance-isolation:v1:begin-/themes/-/icons/-/storage/bazaar/themes/-/storage/bazaar/icons/-# siyuan-appearance-isolation:v1:end-```--旧引擎遵守这些规则,新客户端另以路径过滤器保护本机目录。必须保留用户原规则及字节;未知或损坏的受管块保留原件并报错。同步或快照恢复改回早期规则后,在下一次索引及外观还原前重新确保隔离规则存在。--本机 `.siyuan/.appearance-syncignore-clock-v1` 记录已预留的规则修改秒数,不参与快照和云同步。更新隔离规则前先持久预留,避免还原旧规则或时钟回退时复用本机已分配的文件标识;未知或损坏记录保留原件并报错。--判断用户忽略意图时仅去除完整合法的受管块,用户原有规则继续生效。`/themes/example/` 可排除整个包,`/themes/`、`/icons/` 或对应内部归档目录可排除更大范围。排除 `/storage/` 或 `/storage/appearance-v1/` 会停用内部外观协议。只排除部分文件或单独排除状态记录必须报错,不生成不完整包;整包替换仍须保留原有忽略文件并检查应用期间的本地变化。--被整体忽略的包不进入上传或本机应用。忽略范围内损坏、未知或缺失的归档负载不通过云端或局域网下载,也不解码,不因此阻断笔记同步;路径身份及格式标记的安全检查仍有效。云端恢复引用已经保留的公开事件和删除记录继续保留,尚未分享的私有忽略事件不得混入云端恢复引用。--### 中断恢复与快照还原--下载先完成校验及暂存,再在同一文件系统中备份旧目录、替换整个目录并发布状态。同步应用复用原有资源恢复日志;本机安装使用隐藏的 `data/.siyuan-appearance-ops` 日志,旧目录保留在 `data/.siyuan-appearance-backups` 中。同步替换的旧目录保留在历史目录,跨文件系统不能重命名时保留同卷备份。--启动、下一次操作及快照前可以继续未完成事务。日志记录源状态;恢复期间发现新的本地修改时,必须保留原文件、暂存及恢复材料并返回错误。暂不可用的包恢复完成后再刷新前端,不得通过直接删除状态文件绕过完整性校验。--还原支持本功能的快照时,以目标版本创建新的因果事件,而不是删除当前已知历史。还原无格式标记的旧快照时,缺少外观记录不能解释为卸载。还原前必须取得完整快照及所需内容,云端快照缺项不得静默丢弃包或普通工作区数据。单文件云端还原不得单独还原包内文件、安装状态或内部归档命名空间中的文件;这些内容必须通过完整快照及整包恢复流程应用。--### 恢复引用与限制--内部恢复标签 `.siyuan-appearance-v1` 引用包含事件集合的完整工作区快照,沿用云端普通标签机制保留恢复材料。必须先上传完整对象和快照,再发布恢复引用,最后发布最新引用。新客户端遇到旧客户端还原早期快照时,从恢复引用补回事件,防止丢失删除记录。--恢复引用不得指向只含外观的快照,避免旧客户端还原它时误删笔记。同名既有用户标签必须保留并报冲突,不能直接覆盖。新客户端仅对经过认证且具有本协议格式标记的内部标签隐藏显示、禁止手工覆盖或删除,并从用户备份数量中扣除;同名普通用户标签仍可见、可操作。--云端恢复引用合并目标工作区快照及此前已经公开的云端事件,不得从本机恢复引用复制尚未分享的私有事件。如果最新快照只缺少被排除的事件,且没有新事件需要发布,则保留原云端恢复引用并继续同步笔记。--旧客户端可能显示该标签,并按原规则占用一个备份名额;笔记同步不受此限制。内部恢复引用的更新不使用用户手动备份数量配额。内部事件保留已经分享的完整版本,存储占用随包更新次数增长;云端可复用未变化的分块,本机归档仍保存完整包,当前没有自动压缩事件历史的策略。普通历史清理不会删除恢复引用仍使用的事件。主动删除内部恢复标签及全部相关历史会丢失恢复材料,不能再保证恢复已删除事件。+# dejavu/+go test ./... -run "TestAsset|TestPackageFiles|TestIndexReused|TestSyncReused|TestSnapshot|TestDownload|TestUploadTag" -count=1-恢复引用先于最新引用发布的保证以既有云锁正常串行为前提。现有锁采用先读后写,仍存在极端同时抢锁或失锁的风险;该功能不扩展服务端锁协议,不保证任意失锁及随后清理仍保留所有引用。--## 验证范围--### 回归覆盖--回归范围包含安装、迁移、手工修改、显式重装、未知版本保留、同秒并发更新及删除、完整冲突历史、整包与部分忽略、忽略范围内损坏负载和私有事件保护、完整与按需下载、单向同步、局域网认证及流量计数、中断恢复、快照回退、单文件还原限制、符号链接、同版本资源重载及默认回退。--内核检查 `bazaar`、`util`、`model`、`server` 的相关回归,DejaVu 检查外观、资源、快照、备份、认证、云锁及 `lansync` 测试。缓存回归覆盖保留修改时间的闭合文件改写、密文损坏、错误密钥、有界缓存及共享分块并发读写。前端在 `app/` 中运行相关单元测试及 `pnpm run lint`。--在 DejaVu 根目录运行历史基准:--```text-go test . -run ^$ -bench ^BenchmarkAppearanceHistory$ -benchtime=1x -count=1+# siyuan/kernel/+go test -tags "fts5 sqlcipher" ./model ./bazaar ./util ./server -run "Test.*Appearance|Test.*ThemesWatch|Test.*SyncIgnore" -count=1```--基准使用十个 20 MiB 历史版本,测量无变化检查及快照的耗时和累计内存分配。常规测试不生成该大容量夹具,首次读取仍须完整认证,结果需结合文件系统及缓存状态解释。--端到端用例位于 `siyuan-testing`,需要运行包含此功能的新内核。静态检查和本地云适配器测试不能替代官方云、S3/WebDAV 及桌面和移动端的实机验收;升级、冷启动、运行时脚本卸载和跨端刷新需要在真实环境验证。开发验证不得通过构建前端产物、编译或重启正在使用的内核执行。--### 混版验证--在 DejaVu 根目录运行 `python scripts/test-appearance-compat.py`,覆盖完整下载/按需下载与双向同步/手动上传下载四种组合。独立旧版驱动固定已发布的 `v0.0.0-20260914113714-464364dd8fad`,禁止本地替换并通过 `go mod verify` 校验依赖;当前源码冻结到临时目录,报告保存版本、源码摘要、请求和响应。--每组包含旧端继续编辑笔记、接收安装和卸载事件、还原到无外观事件的早期快照、继续同步、清理本地及云端历史,再由全新客户端恢复删除记录并保留最新笔记。按需模式下普通资源仍可延期,外观归档必须完整下载。--固定旧 `cloud.Local` 在包含标签目录时,云端清理会将目录当成对象读取并失败。测试保留原始失败证据,清理兼容段仅通过测试适配器递归枚举全部 `refs/` 文件,补齐后端列举契约,不修改旧版同步、清理或认证源码。此测试验证旧引擎能沿普通标签保留恢复材料,不等同于真实云服务的端到端验收。--### 依赖发布--内核依赖 DejaVu 的整包事件、恢复状态及同步接口。发布时必须先发布包含相关实现的 DejaVu 版本,再更新 `kernel/go.mod`;只更新主仓库而继续使用旧依赖会缺少整包保护。本地开发可以临时 `replace` 指向 DejaVu 检出,但该替换不得提交。主仓库、依赖、主题和图标示例文档及端到端用例需要协调发布。diff --git a/docs/WORKSPACE.md b/docs/WORKSPACE.mdindex 2fa6aeb812..fab8510a37 100644--- a/docs/WORKSPACE.md+++ b/docs/WORKSPACE.md@@ -19,7 +19,7 @@ A SiYuan workspace is a **self-describing** directory tree: notebooks, documents├── .lock # Runtime workspace lock├── conf/│ ├── conf.json # ★Workspace-level config (appearance/system/sync/editor...)-│ ├── appearance/ # Built-in appearance resources and local migration backups+│ ├── appearance/ # Built-in appearance resources│ ├── ca.crt / ca.key / cert.pem / key.pem # TLS certificates and keys│ └── windowState.json # Desktop window state├── data/ # DataDir — root of all notebook data@@ -30,8 +30,8 @@ A SiYuan workspace is a **self-describing** directory tree: notebooks, documents│ ├── templates/ # Global templates (.md)│ ├── widgets/ # Widgets│ ├── plugins/ # Plugins-│ ├── themes/ # Local theme directories restored from synced packages-│ ├── icons/ # Local icon directories restored from synced packages+│ ├── themes/ # Third-party themes, synchronized as ordinary files+│ ├── icons/ # Third-party icons, synchronized as ordinary files│ ├── emojis/ # Custom emoji│ ├── snippets/ # Code snippets (CSS/JS)│ ├── public/ # Static resources@@ -100,7 +100,7 @@ That is, the physical path segments `assets` / `templates` / `widgets` / `emojis### Persistent data vs rebuildable indexes-Third-party themes live in `data/themes/<name>/` and icon packages in `data/icons/<name>/`. Immutable archives in `data/storage/appearance-v1/` carry their complete contents, updates, and uninstallations through data sync and snapshots; the local theme and icon directories are excluded from ordinary file sync. Each device keeps its selection in `conf/conf.json`. Built-in themes and icons remain application resources. Package resources are downloaded completely even when asset downloads are on demand. Older clients can continue syncing notes; new clients restore appearance packages and handle their conflicts. Migration retains the original local files for recovery. See [Appearance sync](APPEARANCE-SYNC.md) for migration and conflict behavior.+Third-party themes live in `data/themes/<name>/` and icon packages in `data/icons/<name>/`. They use the same file-level synchronization, deletion, conflict handling, and snapshots as plugins, widgets, and templates. Each device keeps its selection in `conf/conf.json`; built-in resources remain application resources. Package assets are downloaded completely even when notebook assets use on-demand downloading. Migration moves the original directories into data without retaining source copies. A snapshot without a package removes it. See [Appearance sync](APPEARANCE-SYNC.md).`data/storage/` contains persistent structured data such as attribute-view definitions and plugin state. The SQLite files in `temp/` are derived indexes and caches: normal notebooks use the global `siyuan.db` and `blocktree.db`, while each unlocked encrypted notebook uses independent SQLCipher databases. Therefore, deleting or rebuilding an index must not be confused with deleting the source `.sy`, asset, or database-definition files.diff --git a/docs/WORKSPACE.zh-CN.md b/docs/WORKSPACE.zh-CN.mdindex 82906e3316..94718adb30 100644--- a/docs/WORKSPACE.zh-CN.md+++ b/docs/WORKSPACE.zh-CN.md@@ -19,7 +19,7 @@ SiYuan 工作区是一棵**自描述**的目录树:笔记本、文档和资源├── .lock # 运行时工作区锁├── conf/│ ├── conf.json # ★工作区总配置(appearance/system/sync/editor...)-│ ├── appearance/ # 内置外观资源和本地迁移备份+│ ├── appearance/ # 内置外观资源│ ├── ca.crt / ca.key / cert.pem / key.pem # TLS 证书和密钥│ └── windowState.json # 桌面端窗口状态├── data/ # DataDir — 所有笔记本数据的根@@ -30,8 +30,8 @@ SiYuan 工作区是一棵**自描述**的目录树:笔记本、文档和资源│ ├── templates/ # 全局模板(.md)│ ├── widgets/ # 挂件│ ├── plugins/ # 插件-│ ├── themes/ # 从同步包还原的本机主题目录-│ ├── icons/ # 从同步包还原的本机图标目录+│ ├── themes/ # 第三方主题,按普通文件同步+│ ├── icons/ # 第三方图标,按普通文件同步│ ├── emojis/ # 自定义 emoji│ ├── snippets/ # 代码片段(CSS/JS)│ ├── public/ # 静态资源@@ -100,7 +100,7 @@ func IsReservedFilename(baseName string) bool {### 持久化数据与可重建索引-第三方主题位于 `data/themes/<name>/`,图标包位于 `data/icons/<name>/`。完整包内容、更新和卸载通过 `data/storage/appearance-v1/` 中不可变的内部归档参与数据同步及快照,本机主题和图标目录不直接进入普通文件同步。各设备在 `conf/conf.json` 中独立保存外观选择。内置主题和图标仍属于程序资源。即使资源文件设置为按需下载,外观包资源也会完整下载。旧客户端可以继续同步笔记,新客户端负责还原外观包及处理冲突。迁移会保留原有本地文件供恢复。迁移和冲突行为详见[外观同步](APPEARANCE-SYNC.zh-CN.md)。+第三方主题位于 `data/themes/<name>/`,图标包位于 `data/icons/<name>/`,与插件、挂件、模板共用文件级同步、删除、冲突处理和快照逻辑。各设备在 `conf/conf.json` 中独立保存外观选择,内置资源仍属于程序资源。即使笔记本资源设置为按需下载,包内资源也会完整下载。迁移将原目录移入数据目录,不保留源副本。恢复的快照中没有某个包时,该包会被删除。详见[外观同步](APPEARANCE-SYNC.zh-CN.md)。`data/storage/` 保存属性视图定义和插件状态等持久化结构化数据。`temp/` 中的 SQLite 文件是派生索引和缓存:普通笔记本使用全局 `siyuan.db` 和 `blocktree.db`,每个已解锁的加密笔记本则使用独立的 SQLCipher 数据库。因此删除或重建索引不能与删除源 `.sy`、资源文件或数据库定义文件混为一谈。diff --git a/kernel/bazaar/appearance_install_test.go b/kernel/bazaar/appearance_install_test.gonew file mode 100644index 0000000000..7022de6e72--- /dev/null+++ b/kernel/bazaar/appearance_install_test.go@@ -0,0 +1,59 @@+package bazaar++import (+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAppearanceInstallUsesOrdinaryMetadata(t *testing.T) {+ useTestBazaarInfo(t)+ for _, kind := range []string{"themes", "icons"} {+ t.Run(kind, func(t *testing.T) {+ manifest, entry := "theme.json", "theme.css"+ if kind == "icons" {+ manifest, entry = "icon.json", "icon.js"+ }+ source := t.TempDir()+ for name, data := range map[string]string{manifest: `{"name":"sample","version":"1.0.0"}`, entry: "first", "stale.txt": "stale"} {+ if err := os.WriteFile(filepath.Join(source, name), []byte(data), 0644); err != nil {+ t.Fatal(err)+ }+ }+ target := filepath.Join(util.DataDir, kind, "sample")+ if err := InstallLocalPackage(source, target, kind, "sample", false); err != nil {+ t.Fatal(err)+ }+ installed, updated := getPackageTimes(kind, "sample", target)+ if installed == 0 || updated != 0 {+ t.Fatalf("invalid install metadata: %d, %d", installed, updated)+ }+ if err := os.Remove(filepath.Join(source, "stale.txt")); err != nil {+ t.Fatal(err)+ }+ if err := InstallLocalPackage(source, target, kind, "sample", true); err != nil {+ t.Fatal(err)+ }+ if nextInstalled, updated := getPackageTimes(kind, "sample", target); nextInstalled != installed || updated == 0 {+ t.Fatalf("invalid update metadata: %d, %d", nextInstalled, updated)+ }+ if _, err := os.Stat(filepath.Join(target, "stale.txt")); !os.IsNotExist(err) {+ t.Fatalf("stale file survived update: %v", err)+ }+ if err := UninstallPackage(target); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(target); !os.IsNotExist(err) {+ t.Fatalf("uninstalled package remains: %v", err)+ }+ if _, err := os.Stat(filepath.Join(util.DataDir, "storage", "bazaar", kind, "sample.json")); !os.IsNotExist(err) {+ t.Fatalf("unexpected package state: %v", err)+ }+ })+ }+ if _, err := os.Stat(filepath.Join(util.DataDir, "storage", "bazaar.json")); err != nil {+ t.Fatalf("shared metadata missing: %v", err)+ }+}diff --git a/kernel/bazaar/appearance_runtime.go b/kernel/bazaar/appearance_runtime.godeleted file mode 100644index 8676a65288..0000000000--- a/kernel/bazaar/appearance_runtime.go+++ /dev/null@@ -1,76 +0,0 @@-// SiYuan - From thought to insight, with agents-// Copyright (c) 2020-present, b3log.org-// SPDX-License-Identifier: AGPL-3.0-or-later--package bazaar--import (- "encoding/json"- "errors"- "fmt"- "os"- "path/filepath"- "sort"-)--var ErrAppearancePackageDeleted = errors.New("appearance package is deleted")--// ValidateAppearancePackageForUse 允许编辑已安装包,仅校验状态格式和删除标记,不重写同步摘要。-func ValidateAppearancePackageForUse(kind, name string) error {- _, statePath, err := appearancePackagePaths(kind, name)- if err != nil {- return err- }- state, err := readAppearanceState(statePath)- if os.IsNotExist(err) {- return nil- }- if err != nil {- return err- }- if state.Deleted {- return fmt.Errorf("%w: %s/%s", ErrAppearancePackageDeleted, kind, name)- }- return nil-}--// PendingAppearancePackages 在调用方持有外观锁时读取本机安装事务,不执行恢复或修改文件。-func PendingAppearancePackages() ([]string, error) {- entries, err := os.ReadDir(appearanceOperationsPath())- if os.IsNotExist(err) {- return nil, nil- }- if err != nil {- return nil, err- }- keys := map[string]bool{}- for _, entry := range entries {- if !entry.IsDir() {- continue- }- data, readErr := os.ReadFile(filepath.Join(appearanceOperationsPath(), entry.Name(), "operation.json"))- if os.IsNotExist(readErr) {- continue- }- if readErr != nil {- return nil, readErr- }- var operation appearanceOperation- if readErr = json.Unmarshal(data, &operation); readErr != nil || operation.Version != 1 {- return nil, fmt.Errorf("invalid pending appearance operation: %s", entry.Name())- }- if err = validateAppearanceState(&operation.State); err != nil {- return nil, err- }- if _, _, err = appearancePackagePaths(operation.Kind, operation.Name); err != nil {- return nil, err- }- keys["/"+operation.Kind+"/"+operation.Name] = true- }- ret := make([]string, 0, len(keys))- for key := range keys {- ret = append(ret, key)- }- sort.Strings(ret)- return ret, nil-}diff --git a/kernel/bazaar/appearance_state.go b/kernel/bazaar/appearance_state.godeleted file mode 100644index e015563166..0000000000--- a/kernel/bazaar/appearance_state.go+++ /dev/null@@ -1,620 +0,0 @@-package bazaar--import (- "crypto/sha256"- "encoding/hex"- "encoding/json"- "errors"- "fmt"- "io/fs"- "os"- "path"- "path/filepath"- "reflect"- "strings"- "time"-- "github.com/siyuan-note/dejavu"- "github.com/siyuan-note/filelock"- "github.com/siyuan-note/siyuan/kernel/util"-)--// AppearancePackageState 将包内容和安装状态绑定为同一个同步单元。-type AppearancePackageState struct {- Version int `json:"version"`- Deleted bool `json:"deleted"`- Migration bool `json:"migration"`- PackageInfo- Files map[string]string `json:"files"`-}--// ErrAppearancePackageEmpty 表示包中没有可同步的文件,迁移可保留原目录并跳过。-var ErrAppearancePackageEmpty = errors.New("appearance package contains no synchronizable files")--func isAppearanceKind(kind string) bool { return kind == "themes" || kind == "icons" }--func appearancePackagePaths(kind, name string) (payload, state string, err error) {- payload = util.AppearancePackagePath(kind, name)- if payload == "" || !IsValidPackageName(name) || !isAppearanceKind(kind) ||- (kind == "themes" && (strings.EqualFold(name, "daylight") || strings.EqualFold(name, "midnight"))) ||- (kind == "icons" && strings.EqualFold(name, "litheness")) {- return "", "", fmt.Errorf("invalid third-party appearance package: %s/%s", kind, name)- }- return payload, filepath.Join(util.DataDir, "storage", "bazaar", kind, name+".json"), nil-}--func appearanceLockPath() string { return filepath.Join(util.DataDir, ".siyuan-appearance") }--func readAppearanceState(filePath string) (*AppearancePackageState, error) {- data, err := os.ReadFile(filePath)- if err != nil {- return nil, err- }- var state AppearancePackageState- if err = json.Unmarshal(data, &state); err != nil {- return nil, err- }- if err = validateAppearanceState(&state); err != nil {- return nil, fmt.Errorf("%s: %w", filePath, err)- }- return &state, nil-}--func validateAppearanceState(state *AppearancePackageState) error {- if state.Version != 1 || state.Files == nil || (state.Deleted && len(state.Files) != 0) || (!state.Deleted && len(state.Files) == 0) {- return errors.New("unsupported or invalid appearance state")- }- paths := map[string]bool{}- for name, digest := range state.Files {- if name == "" || name == "." || strings.HasPrefix(name, "/") || strings.HasPrefix(name, "../") ||- path.Clean(name) != name || strings.ContainsAny(name, "\\:\x00") || len(digest) != 64 || strings.ToLower(digest) != digest {- return fmt.Errorf("invalid appearance file record: %s", name)- }- folded := strings.ToLower(name)- if paths[folded] {- return fmt.Errorf("appearance file path collision: %s", name)- }- paths[folded] = true- if _, err := hex.DecodeString(digest); err != nil {- return err- }- }- return nil-}--func writeAppearanceState(filePath string, state *AppearancePackageState) error {- if err := validateAppearanceState(state); err != nil {- return err- }- data, err := json.MarshalIndent(state, "", "\t")- if err != nil {- return err- }- if err = os.MkdirAll(filepath.Dir(filePath), 0755); err != nil {- return err- }- return filelock.WriteFile(filePath, data)-}--func appearanceFiles(root string) (map[string]string, error) {- ret := map[string]string{}- err := filepath.WalkDir(root, func(filePath string, entry fs.DirEntry, walkErr error) error {- if walkErr != nil {- return walkErr- }- if entry.Type()&os.ModeSymlink != 0 {- if filePath != root && (strings.HasPrefix(entry.Name(), ".") || strings.HasSuffix(entry.Name(), ".tmp")) {- return nil- }- return fmt.Errorf("appearance synchronization does not follow symlinks: %s", filePath)- }- if filePath == root {- return nil- }- info, err := entry.Info()- if err != nil {- return err- }- rel, err := filepath.Rel(root, filePath)- if err != nil {- return err- }- ignored, err := dejavu.IgnorePath(info, filePath, filepath.ToSlash(rel), "", ".siyuan")- if err != nil {- return err- }- if ignored || entry.IsDir() {- return nil- }- data, err := filelock.ReadFile(filePath)- if err != nil {- return err- }- digest := sha256.Sum256(data)- ret[filepath.ToSlash(rel)] = hex.EncodeToString(digest[:])- return nil- })- return ret, err-}--// GetAppearancePackageInfo 读取独立包状态;旧记录只作为迁移时的只读后备。-func GetAppearancePackageInfo(kind, name string) (*PackageInfo, error) {- _, statePath, err := appearancePackagePaths(kind, name)- if err != nil {- return nil, err- }- state, err := readAppearanceState(statePath)- if err == nil {- return &state.PackageInfo, nil- }- if !os.IsNotExist(err) {- return nil, err- }- getBazaarInfo()- bazaarInfoCacheLock.RLock()- defer bazaarInfoCacheLock.RUnlock()- if bazaarInfoCache != nil && bazaarInfoCache.Packages[kind] != nil {- if info := bazaarInfoCache.Packages[kind][name]; info != nil {- copy := *info- return ©, nil- }- }- return &PackageInfo{}, nil-}--// ValidateAppearancePackage 拒绝加载不完整或未知格式的已记录外观包,保留没有状态文件的本地开发包。-func ValidateAppearancePackage(kind, name string) error {- payload, statePath, err := appearancePackagePaths(kind, name)- if err != nil {- return err- }- state, err := readAppearanceState(statePath)- if os.IsNotExist(err) {- return nil- }- if err != nil {- return err- }- if state.Deleted {- return fmt.Errorf("appearance package is deleted: %s/%s", kind, name)- }- files, err := appearanceFiles(payload)- if err != nil {- return err- }- if !reflect.DeepEqual(files, state.Files) {- return fmt.Errorf("appearance package content does not match state: %s/%s", kind, name)- }- return nil-}--// PrepareAppearancePackages 在恢复完成后、建立快照前记录本地手工修改和删除。-func PrepareAppearancePackages(ignored ...func(kind, name string) bool) error {- if err := util.EnsureAppearanceSyncIsolation(); err != nil {- return err- }- filelock.Lock(appearanceLockPath())- defer filelock.Unlock(appearanceLockPath())- if err := recoverAppearanceOperations(); err != nil {- return err- }- for _, kind := range []string{"themes", "icons"} {- names := map[string]bool{}- entries, err := os.ReadDir(filepath.Join(util.DataDir, kind))- if err != nil && !os.IsNotExist(err) {- return err- }- for _, entry := range entries {- if strings.HasPrefix(entry.Name(), ".") {- continue- }- if entry.IsDir() || entry.Type()&os.ModeSymlink != 0 {- names[entry.Name()] = true- }- }- entries, err = os.ReadDir(filepath.Join(util.DataDir, "storage", "bazaar", kind))- if err != nil && !os.IsNotExist(err) {- return err- }- for _, entry := range entries {- if !entry.IsDir() && strings.HasSuffix(entry.Name(), ".json") {- names[strings.TrimSuffix(entry.Name(), ".json")] = true- }- }- for name := range names {- if len(ignored) > 0 && ignored[0] != nil && ignored[0](kind, name) {- continue- }- payload, statePath, pathErr := appearancePackagePaths(kind, name)- if pathErr != nil {- continue- }- state, readErr := readAppearanceState(statePath)- if readErr != nil && !os.IsNotExist(readErr) {- return readErr- }- _, statErr := os.Lstat(payload)- if state == nil {- if stat, linkErr := os.Lstat(payload); linkErr == nil && stat.Mode()&os.ModeSymlink != 0 {- continue- }- }- deleted := os.IsNotExist(statErr)- if statErr != nil && !deleted {- return statErr- }- files := map[string]string{}- if !deleted {- var scanErr error- files, scanErr = appearanceFiles(payload)- if scanErr != nil {- return scanErr- }- if len(files) == 0 {- // 删除后保留的空目录和本机忽略文件不构成重新安装。- if state == nil || state.Deleted {- continue- }- return fmt.Errorf("%w: %s/%s", ErrAppearancePackageEmpty, kind, name)- }- }- if state != nil && state.Deleted && !deleted {- return fmt.Errorf("appearance package has a deletion record; reinstall explicitly: %s/%s", kind, name)- }- if state != nil && state.Deleted == deleted && reflect.DeepEqual(state.Files, files) {- continue- }- if state == nil {- info, infoErr := GetAppearancePackageInfo(kind, name)- if infoErr != nil {- return infoErr- }- if info.InstallTime == 0 {- if stat, statErr := os.Stat(payload); statErr == nil {- info.InstallTime = stat.ModTime().UnixMilli()- }- }- state = &AppearancePackageState{Version: 1, PackageInfo: *info}- } else {- state.UpdateTime = time.Now().UnixMilli()- state.Migration = false- }- state.Deleted, state.Files = deleted, files- if err = writeAppearanceState(statePath, state); err != nil {- return err- }- }- }- return nil-}--// HasAppearancePackageSymlink 判定需要保留在本机的开发包,不遍历链接指向的外部目录。-func HasAppearancePackageSymlink(root string) (bool, error) {- found := false- err := filepath.WalkDir(root, func(filePath string, entry fs.DirEntry, walkErr error) error {- if walkErr != nil {- return walkErr- }- if entry.Type()&os.ModeSymlink != 0 {- if filePath != root && (strings.HasPrefix(entry.Name(), ".") || strings.HasSuffix(entry.Name(), ".tmp")) {- return nil- }- found = true- return filepath.SkipAll- }- if filePath != root && entry.IsDir() && strings.HasPrefix(entry.Name(), ".") && entry.Name() != ".siyuan" {- return filepath.SkipDir- }- return nil- })- return found, err-}--type appearanceOperation struct {- Version int `json:"version"`- Kind string `json:"kind"`- Name string `json:"name"`- State AppearancePackageState `json:"state"`- BeforeExists bool `json:"beforeExists"`- Before map[string]string `json:"before"`- BeforeLink string `json:"beforeLink,omitempty"`- BeforeState string `json:"beforeState"`-}--func appearanceOperationsPath() string { return filepath.Join(util.DataDir, ".siyuan-appearance-ops") }--// PublishAppearancePackage 用可恢复的整目录事务发布包及其摘要,安装中断后继续完成同一事务。-func PublishAppearancePackage(sourcePath, kind, name string, info PackageInfo, migration, update bool) error {- if err := util.EnsureAppearanceSyncIsolation(); err != nil {- return err- }- filelock.Lock(appearanceLockPath())- defer filelock.Unlock(appearanceLockPath())- if err := recoverAppearanceOperations(); err != nil {- return err- }- payload, statePath, err := appearancePackagePaths(kind, name)- if err != nil {- return err- }- if _, err = readAppearanceState(statePath); err != nil && !os.IsNotExist(err) {- return err- }- contains, err := PackageDirContainsFile(payload)- if err != nil && !os.IsNotExist(err) {- return err- }- if !update && contains {- return errors.New("marketplace package install path already exists")- }- if update && os.IsNotExist(err) {- return os.ErrNotExist- }- files, err := appearanceFiles(sourcePath)- if err != nil {- return err- }- if len(files) == 0 {- return ErrAppearancePackageEmpty- }- state := AppearancePackageState{Version: 1, Migration: migration, PackageInfo: info, Files: files}- return publishAppearanceOperation(&appearanceOperation{Version: 1, Kind: kind, Name: name, State: state}, sourcePath)-}--// DeleteAppearancePackage 保留同步删除标记,并在记录发布前保留旧包以支持中断恢复。-func DeleteAppearancePackage(kind, name string) error {- if err := util.EnsureAppearanceSyncIsolation(); err != nil {- return err- }- filelock.Lock(appearanceLockPath())- defer filelock.Unlock(appearanceLockPath())- if err := recoverAppearanceOperations(); err != nil {- return err- }- info, err := GetAppearancePackageInfo(kind, name)- if err != nil {- return err- }- info.UpdateTime = time.Now().UnixMilli()- state := AppearancePackageState{Version: 1, Deleted: true, PackageInfo: *info, Files: map[string]string{}}- return publishAppearanceOperation(&appearanceOperation{Version: 1, Kind: kind, Name: name, State: state}, "")-}--func publishAppearanceOperation(operation *appearanceOperation, sourcePath string) error {- if err := validateAppearanceState(&operation.State); err != nil {- return err- }- payload, statePath, err := appearancePackagePaths(operation.Kind, operation.Name)- if err != nil {- return err- }- stat, err := os.Lstat(payload)- if err != nil && !os.IsNotExist(err) {- return err- }- operation.BeforeExists = err == nil- if operation.BeforeExists {- if stat.Mode()&os.ModeSymlink != 0 {- operation.BeforeLink, err = os.Readlink(payload)- } else {- operation.Before, err = appearanceFiles(payload)- }- if err != nil {- return err- }- }- operation.BeforeState, err = appearanceStateDigest(statePath)- if err != nil {- return err- }- if err := os.MkdirAll(appearanceOperationsPath(), 0755); err != nil {- return err- }- opDir, err := os.MkdirTemp(appearanceOperationsPath(), "package-")- if err != nil {- return err- }- if sourcePath != "" {- if err = filelock.Copy(sourcePath, filepath.Join(opDir, "staging")); err != nil {- _ = os.RemoveAll(opDir)- return err- }- files, scanErr := appearanceFiles(filepath.Join(opDir, "staging"))- if scanErr != nil || !reflect.DeepEqual(files, operation.State.Files) {- _ = os.RemoveAll(opDir)- return fmt.Errorf("appearance package changed while staging: %v", scanErr)- }- }- if err = verifyAppearanceOperationBefore(payload, statePath, operation); err != nil {- _ = os.RemoveAll(opDir)- return err- }- data, err := json.Marshal(operation)- if err != nil {- return err- }- if err = filelock.WriteFile(filepath.Join(opDir, "operation.json"), data); err != nil {- return err- }- return applyAppearanceOperation(opDir, operation)-}--func applyAppearanceOperation(opDir string, operation *appearanceOperation) error {- if operation.Version != 1 || operation.State.Version != 1 || operation.State.Files == nil {- return errors.New("unsupported appearance operation")- }- if err := validateAppearanceState(&operation.State); err != nil {- return err- }- payload, statePath, err := appearancePackagePaths(operation.Kind, operation.Name)- if err != nil {- return err- }- if err = os.MkdirAll(filepath.Dir(payload), 0755); err != nil {- return err- }- staging, backup := filepath.Join(opDir, "staging"), filepath.Join(opDir, "backup")- _, stageErr := os.Stat(staging)- if !operation.State.Deleted && stageErr == nil {- files, scanErr := appearanceFiles(staging)- if scanErr != nil {- return scanErr- }- if !reflect.DeepEqual(files, operation.State.Files) {- return errors.New("appearance recovery staging does not match state")- }- }- if operation.State.Deleted || stageErr == nil {- if _, backupErr := os.Lstat(backup); os.IsNotExist(backupErr) {- if err = verifyAppearanceOperationBefore(payload, statePath, operation); err != nil {- return err- }- if _, targetErr := os.Lstat(payload); targetErr == nil {- if err = os.Rename(payload, backup); err != nil {- return err- }- } else if !os.IsNotExist(targetErr) {- return targetErr- }- } else if backupErr != nil {- return backupErr- }- if !operation.State.Deleted {- if err = os.Rename(staging, payload); err != nil {- return err- }- }- } else if !os.IsNotExist(stageErr) {- return stageErr- }- if !operation.State.Deleted {- files, scanErr := appearanceFiles(payload)- if scanErr != nil {- return scanErr- }- if !reflect.DeepEqual(files, operation.State.Files) {- return errors.New("appearance recovery target does not match staged package")- }- } else if _, targetErr := os.Lstat(payload); !os.IsNotExist(targetErr) {- return errors.New("appearance deletion recovery target reappeared")- }- if err = verifyAppearanceOperationState(statePath, operation); err != nil {- return err- }- if err = writeAppearanceState(statePath, &operation.State); err != nil {- return err- }- // 保留旧目录,避免外部编辑器仍持有旧文件句柄时丢失迟到的写入。- if _, backupErr := os.Lstat(backup); backupErr == nil {- backupRoot := filepath.Join(util.DataDir, ".siyuan-appearance-backups")- if err = os.MkdirAll(backupRoot, 0755); err != nil {- return err- }- if err = os.Rename(backup, filepath.Join(backupRoot, filepath.Base(opDir))); err != nil {- return err- }- } else if !os.IsNotExist(backupErr) {- return backupErr- }- return os.RemoveAll(opDir)-}--func appearanceStateDigest(statePath string) (string, error) {- data, err := os.ReadFile(statePath)- if os.IsNotExist(err) {- return "", nil- }- if err != nil {- return "", err- }- digest := sha256.Sum256(data)- return hex.EncodeToString(digest[:]), nil-}--func verifyAppearanceOperationState(statePath string, operation *appearanceOperation) error {- digest, err := appearanceStateDigest(statePath)- if err != nil {- return err- }- if digest != operation.BeforeState {- current, readErr := readAppearanceState(statePath)- if readErr != nil || !reflect.DeepEqual(current, &operation.State) {- return errors.New("appearance metadata changed during pending operation")- }- }- return nil-}--func verifyAppearanceOperationBefore(payload, statePath string, operation *appearanceOperation) error {- if err := verifyAppearanceOperationState(statePath, operation); err != nil {- return err- }- stat, err := os.Lstat(payload)- if err != nil && !os.IsNotExist(err) {- return err- }- if operation.State.Deleted && os.IsNotExist(err) {- current, stateErr := readAppearanceState(statePath)- if stateErr == nil && reflect.DeepEqual(current, &operation.State) {- return nil- }- }- if !operation.BeforeExists && os.IsNotExist(err) {- return nil- }- if operation.BeforeExists && err == nil {- if operation.BeforeLink != "" && stat.Mode()&os.ModeSymlink != 0 {- link, linkErr := os.Readlink(payload)- if linkErr == nil && link == operation.BeforeLink {- return nil- }- } else if stat.Mode()&os.ModeSymlink == 0 {- files, scanErr := appearanceFiles(payload)- if scanErr == nil && reflect.DeepEqual(files, operation.Before) {- return nil- }- }- }- return errors.New("appearance package changed during pending operation; original files and recovery journal preserved")-}--func recoverAppearanceOperations() error {- entries, err := os.ReadDir(appearanceOperationsPath())- if os.IsNotExist(err) {- return nil- }- if err != nil {- return err- }- for _, entry := range entries {- if !entry.IsDir() {- continue- }- opDir := filepath.Join(appearanceOperationsPath(), entry.Name())- data, readErr := os.ReadFile(filepath.Join(opDir, "operation.json"))- if os.IsNotExist(readErr) {- continue- }- if readErr != nil {- return readErr- }- var operation appearanceOperation- if err = json.Unmarshal(data, &operation); err != nil {- return err- }- if err = applyAppearanceOperation(opDir, &operation); err != nil {- return err- }- }- return nil-}--// RecoverAppearancePackages 在启动和外观目录迁移前完成本机安装事务。-func RecoverAppearancePackages() error {- if err := util.EnsureAppearanceSyncIsolation(); err != nil {- return err- }- filelock.Lock(appearanceLockPath())- defer filelock.Unlock(appearanceLockPath())- return recoverAppearanceOperations()-}diff --git a/kernel/bazaar/appearance_state_test.go b/kernel/bazaar/appearance_state_test.godeleted file mode 100644index ccee44cd4b..0000000000--- a/kernel/bazaar/appearance_state_test.go+++ /dev/null@@ -1,553 +0,0 @@-package bazaar--import (- "encoding/json"- "errors"- "os"- "path/filepath"- "reflect"- "strings"- "testing"-- "github.com/siyuan-note/dejavu"- "github.com/siyuan-note/dejavu/cloud"- "github.com/siyuan-note/siyuan/kernel/util"-)--func setupAppearanceStateTest(t *testing.T) {- t.Helper()- oldData, oldThemes, oldIcons := util.DataDir, util.ThemesPath, util.IconsPath- util.DataDir = t.TempDir()- util.ThemesPath, util.IconsPath = filepath.Join(util.DataDir, "themes"), filepath.Join(util.DataDir, "icons")- t.Cleanup(func() { util.DataDir, util.ThemesPath, util.IconsPath = oldData, oldThemes, oldIcons })-}--func TestAppearanceStateIgnoresUntrackedEmptyDirectories(t *testing.T) {- setupAppearanceStateTest(t)- for _, name := range []string{"empty", "ignored"} {- if err := os.MkdirAll(filepath.Join(util.ThemesPath, name), 0755); err != nil {- t.Fatal(err)- }- }- writeAppearanceTestFile(t, util.ThemesPath, "ignored/.draft", "keep draft")- if err := PrepareAppearancePackages(); err != nil {- t.Fatal(err)- }- for _, name := range []string{"empty", "ignored"} {- _, statePath, err := appearancePackagePaths("themes", name)- if err != nil {- t.Fatal(err)- }- if _, err = os.Stat(statePath); !os.IsNotExist(err) {- t.Fatalf("untracked empty directory received state: %s: %v", name, err)- }- }- if err := PublishAppearancePackage(t.TempDir(), "themes", "explicit", PackageInfo{}, false, false); !errors.Is(err, ErrAppearancePackageEmpty) {- t.Fatalf("empty explicit installation was accepted: %v", err)- }-- source := t.TempDir()- writeAppearanceTestFile(t, source, "theme.css", "recorded")- if err := PublishAppearancePackage(source, "themes", "recorded", PackageInfo{}, false, false); err != nil {- t.Fatal(err)- }- payload, statePath, _ := appearancePackagePaths("themes", "recorded")- before, err := os.ReadFile(statePath)- if err != nil {- t.Fatal(err)- }- if err = os.Remove(filepath.Join(payload, "theme.css")); err != nil {- t.Fatal(err)- }- if err = PrepareAppearancePackages(); !errors.Is(err, ErrAppearancePackageEmpty) {- t.Fatalf("incomplete recorded package was accepted: %v", err)- }- after, err := os.ReadFile(statePath)- if err != nil || string(before) != string(after) {- t.Fatalf("incomplete package state was overwritten: %s %v", after, err)- }-}--func TestAppearanceStateRestoresIsolationBeforePackageChanges(t *testing.T) {- setupAppearanceStateTest(t)- source := t.TempDir()- writeAppearanceTestFile(t, source, "theme.css", "base css")- if err := PublishAppearancePackage(source, "themes", "example", PackageInfo{}, false, false); err != nil {- t.Fatal(err)- }- rulePath := filepath.Join(util.DataDir, ".siyuan", "syncignore")- if err := os.WriteFile(rulePath, []byte("/assets/private/\n"), 0644); err != nil {- t.Fatal(err)- }- if err := DeleteAppearancePackage("themes", "example"); err != nil {- t.Fatal(err)- }- rules, err := os.ReadFile(rulePath)- if err != nil || !strings.HasPrefix(string(rules), "/assets/private/\n") || !strings.Contains(string(rules), "# siyuan-appearance-isolation:v1:begin\n/themes/\n") {- t.Fatalf("restored user rules were not isolated before deletion: %s %v", rules, err)- }- _, statePath, _ := appearancePackagePaths("themes", "example")- before, err := os.ReadFile(statePath)- if err != nil {- t.Fatal(err)- }- unknown := []byte("# siyuan-appearance-isolation:v2:begin\n")- if err = os.WriteFile(rulePath, unknown, 0644); err != nil {- t.Fatal(err)- }- if err = PublishAppearancePackage(source, "themes", "example", PackageInfo{}, false, false); err == nil {- t.Fatal("package was published through unknown isolation rules")- }- for target, want := range map[string][]byte{rulePath: unknown, statePath: before} {- got, readErr := os.ReadFile(target)- if readErr != nil || string(got) != string(want) {- t.Fatalf("failed publication changed recovery material: %s: %v", target, readErr)- }- }- if _, err = os.Stat(filepath.Join(util.ThemesPath, "example")); !os.IsNotExist(err) {- t.Fatalf("failed publication recreated the deleted package: %v", err)- }-}--func TestAppearanceStateDeletedPreservesIgnoredDirectories(t *testing.T) {- for _, kind := range []string{"themes", "icons"} {- for _, contents := range []string{"empty", "ignored"} {- t.Run(kind+"/"+contents, func(t *testing.T) {- setupAppearanceStateTest(t)- if err := DeleteAppearancePackage(kind, "example"); err != nil {- t.Fatal(err)- }- payload, statePath, _ := appearancePackagePaths(kind, "example")- before, err := os.ReadFile(statePath)- if err != nil {- t.Fatal(err)- }- if err = os.MkdirAll(payload, 0755); err != nil {- t.Fatal(err)- }- ignored := map[string]string{}- if contents == "ignored" {- ignored = map[string]string{".git/config": "local repository", ".draft": "draft", "cache.tmp": "cache"}- for name, content := range ignored {- writeAppearanceTestFile(t, payload, name, content)- }- }- if err = PrepareAppearancePackages(); err != nil {- t.Fatalf("deleted package blocked snapshot preparation: %v", err)- }- after, err := os.ReadFile(statePath)- if err != nil || string(after) != string(before) {- t.Fatalf("deleted state changed: %s %v", after, err)- }- for name, content := range ignored {- data, readErr := os.ReadFile(filepath.Join(payload, filepath.FromSlash(name)))- if readErr != nil || string(data) != content {- t.Fatalf("ignored local file changed: %s: %s %v", name, data, readErr)- }- }- writeAppearanceTestFile(t, payload, ".siyuan/settings.json", "{}")- if err = PrepareAppearancePackages(); err == nil {- t.Fatal("synchronizable files resurrected a deleted package without explicit installation")- }- after, err = os.ReadFile(statePath)- if err != nil || string(after) != string(before) {- t.Fatalf("rejected reinstall changed deleted state: %s %v", after, err)- }- })- }- }-}--func TestAppearanceStateCloudIntegration(t *testing.T) {- for _, onDemand := range []bool{false, true} {- t.Run(map[bool]string{false: "full", true: "on-demand"}[onDemand], func(t *testing.T) {- setupAppearanceStateTest(t)- base, remote := t.TempDir(), t.TempDir()- newRepo := func(device string) *dejavu.Repo {- root := filepath.Join(base, device)- repoPath := filepath.Join(root, "repo")- backend := cloud.NewLocal(&cloud.BaseCloud{Conf: &cloud.Conf{Dir: "main", RepoPath: repoPath, AvailableSize: 1024 * 1024 * 1024, Local: &cloud.ConfLocal{Endpoint: remote}}})- isolation := []string{"/themes/", "/icons/", "/storage/bazaar/themes/", "/storage/bazaar/icons/"}- repo, err := dejavu.NewRepoWithOptions(dejavu.Options{DataPath: filepath.Join(root, "data"), RepoPath: repoPath, HistoryPath: filepath.Join(root, "history"), TempPath: filepath.Join(root, "temp"), DeviceID: device, DeviceName: device, DeviceOS: "windows", AESKey: []byte("0123456789abcdef0123456789abcdef"), Cloud: backend, IgnoreRulePath: ".siyuan/syncignore", IgnoreLines: isolation, EnableAppearanceSync: true})- if err != nil {- t.Fatal(err)- }- writeAppearanceTestFile(t, repo.DataPath, "seed.txt", "seed")- writeAppearanceTestFile(t, repo.DataPath, ".siyuan/syncignore", "# siyuan-appearance-isolation:v1:begin\n/themes/\n/icons/\n/storage/bazaar/themes/\n/storage/bazaar/icons/\n# siyuan-appearance-isolation:v1:end\n")- if err = repo.ConfigureAssetDownloads(onDemand, filepath.Join(root, "conf", "assets"), "test-scope"); err != nil {- t.Fatal(err)- }- return repo- }- a, b := newRepo("a"), newRepo("b")- selectRepo := func(repo *dejavu.Repo) {- util.DataDir = repo.DataPath- util.ThemesPath = filepath.Join(repo.DataPath, "themes")- util.IconsPath = filepath.Join(repo.DataPath, "icons")- }- syncRepo := func(repo *dejavu.Repo) {- t.Helper()- selectRepo(repo)- if err := PrepareAppearancePackages(); err != nil {- t.Fatal(err)- }- if _, err := repo.Index("integration", true, nil); err != nil {- t.Fatal(err)- }- if _, _, err := repo.Sync(nil); err != nil {- t.Fatal(err)- }- id, _, err := repo.AssetDownloadChanges()- if err != nil {- t.Fatal(err)- }- if err = repo.AcknowledgeAssetDownloadChanges(id); err != nil {- t.Fatal(err)- }- }- install := func(repo *dejavu.Repo, css, asset string, update bool) {- t.Helper()- selectRepo(repo)- source := t.TempDir()- writeAppearanceTestFile(t, source, "theme.json", `{"name":"example","version":"1.0.0"}`)- writeAppearanceTestFile(t, source, "theme.css", css)- writeAppearanceTestFile(t, source, "assets/font.woff", asset)- writeAppearanceTestFile(t, source, ".siyuan/settings.json", css)- writeAppearanceTestFile(t, source, "assets/.siyuan/settings.json", asset)- writeAppearanceTestFile(t, source, "assets.tmp/font.woff", asset)- if err := PublishAppearancePackage(source, "themes", "example", PackageInfo{InstallTime: 1}, false, update); err != nil {- t.Fatal(err)- }- }- selectRepo(a)- if err := PrepareAppearancePackages(); err != nil {- t.Fatal(err)- }- empty, err := a.Index("before installation", true, nil)- if err != nil {- t.Fatal(err)- }- install(a, "base css", "base font", false)- syncRepo(a)- syncRepo(b)- install(a, "cloud complete css", "cloud complete font", true)- install(b, "local competing css edited", "local competing font edited", true)- syncRepo(a)- syncRepo(b)- if err := ValidateAppearancePackage("themes", "example"); err != nil {- t.Fatal(err)- }- for name, want := range map[string]string{- "theme.css": "cloud complete css", "assets/font.woff": "cloud complete font",- ".siyuan/settings.json": "cloud complete css", "assets/.siyuan/settings.json": "cloud complete font",- "assets.tmp/font.woff": "cloud complete font",- } {- data, err := os.ReadFile(filepath.Join(util.ThemesPath, "example", filepath.FromSlash(name)))- if err != nil || string(data) != want {- t.Fatalf("mixed kernel/DejaVu package %s: %s %v", name, data, err)- }- }- deferred, err := b.DeferredAssets()- if err != nil || len(deferred) != 0 {- t.Fatalf("appearance asset deferred: %v %v", deferred, err)- }- if changed, checkErr := b.CheckSnapshot(); checkErr != nil || changed {- t.Fatalf("unchanged package kept changing snapshot: %t %v", changed, checkErr)- }- writeAppearanceTestFile(t, b.DataPath, "themes/example/.git/config", "local development state")- selectRepo(a)- if err = DeleteAppearancePackage("themes", "example"); err != nil {- t.Fatal(err)- }- syncRepo(a)- syncRepo(b)- _, statePath, _ := appearancePackagePaths("themes", "example")- state, err := readAppearanceState(statePath)- if err != nil || !state.Deleted {- t.Fatalf("kernel tombstone did not converge: %+v %v", state, err)- }- writeAppearanceTestFile(t, b.DataPath, "after-delete.txt", "note after package deletion")- syncRepo(b)- syncRepo(a)- data, err := os.ReadFile(filepath.Join(a.DataPath, "after-delete.txt"))- if err != nil || string(data) != "note after package deletion" {- t.Fatalf("package deletion blocked ordinary note sync: %s %v", data, err)- }- data, err = os.ReadFile(filepath.Join(b.DataPath, "themes", "example", ".git", "config"))- if err != nil || string(data) != "local development state" {- t.Fatalf("package deletion discarded ignored files: %s %v", data, err)- }- install(a, "reinstalled css", "reinstalled font", false)- syncRepo(a)- if _, _, err = a.Checkout(empty.ID, nil); err != nil {- t.Fatal(err)- }- _, statePath, _ = appearancePackagePaths("themes", "example")- state, err = readAppearanceState(statePath)- if err != nil || !state.Deleted {- t.Fatalf("snapshot did not restore deletion: %+v %v", state, err)- }- syncRepo(a)- syncRepo(b)- })- }-}--func writeAppearanceTestFile(t *testing.T, root, name, content string) {- t.Helper()- filePath := filepath.Join(root, filepath.FromSlash(name))- if err := os.MkdirAll(filepath.Dir(filePath), 0755); err != nil {- t.Fatal(err)- }- if err := os.WriteFile(filePath, []byte(content), 0644); err != nil {- t.Fatal(err)- }-}--func TestAppearanceStateWholePackageLifecycle(t *testing.T) {- setupAppearanceStateTest(t)- source := t.TempDir()- writeAppearanceTestFile(t, source, "theme.css", "old")- writeAppearanceTestFile(t, source, "removed.js", "old only")- writeAppearanceTestFile(t, source, ".git/config", "local")- writeAppearanceTestFile(t, source, "cache.tmp", "local")- legacy := `{"packages":{"themes":{"example":{"installTime":123,"repoURL":"https://github.com/owner/theme","repoRef":"main"}}}}`- writeAppearanceTestFile(t, util.DataDir, "storage/bazaar.json", legacy)- info, err := GetAppearancePackageInfo("themes", "example")- if err != nil || info.InstallTime != 123 {- t.Fatalf("legacy source: %+v %v", info, err)- }- if err = PublishAppearancePackage(source, "themes", "example", *info, true, false); err != nil {- t.Fatal(err)- }- payload, statePath, _ := appearancePackagePaths("themes", "example")- state, err := readAppearanceState(statePath)- if err != nil || len(state.Files) != 2 || !state.Migration {- t.Fatalf("state: %+v %v", state, err)- }- if err = ValidateAppearancePackage("themes", "example"); err != nil {- t.Fatal(err)- }- next := t.TempDir()- writeAppearanceTestFile(t, next, "theme.css", "new, same version")- info.UpdateTime = 456- if err = PublishAppearancePackage(next, "themes", "example", *info, false, true); err != nil {- t.Fatal(err)- }- if _, err = os.Stat(filepath.Join(payload, "removed.js")); !os.IsNotExist(err) {- t.Fatalf("obsolete file remains: %v", err)- }- if err = ValidateAppearancePackage("themes", "example"); err != nil {- t.Fatal(err)- }- if err = DeleteAppearancePackage("themes", "example"); err != nil {- t.Fatal(err)- }- state, err = readAppearanceState(statePath)- if err != nil || !state.Deleted || len(state.Files) != 0 || state.Migration {- t.Fatalf("tombstone: %+v %v", state, err)- }- if _, err = os.Stat(payload); !os.IsNotExist(err) {- t.Fatalf("deleted payload: %v", err)- }- if err = PrepareAppearancePackages(); err != nil {- t.Fatal(err)- }- writeAppearanceTestFile(t, payload, "theme.css", "late migration")- if err = PrepareAppearancePackages(); err == nil {- t.Fatal("unobserved reinstall resurrected tombstone")- }- if err = PublishAppearancePackage(next, "themes", "example", *info, false, true); err != nil {- t.Fatal(err)- }- state, err = readAppearanceState(statePath)- if err != nil || state.Deleted || state.Migration {- t.Fatalf("explicit reinstall: %+v %v", state, err)- }- actual, err := os.ReadFile(filepath.Join(util.DataDir, "storage", "bazaar.json"))- if err != nil || string(actual) != legacy {- t.Fatalf("legacy metadata rewritten: %s %v", actual, err)- }-}--func TestAppearanceStateCorruptionPreservesOriginal(t *testing.T) {- setupAppearanceStateTest(t)- source := t.TempDir()- writeAppearanceTestFile(t, source, "icon.js", "original")- if err := PublishAppearancePackage(source, "icons", "example", PackageInfo{InstallTime: 1}, false, false); err != nil {- t.Fatal(err)- }- payload, statePath, _ := appearancePackagePaths("icons", "example")- if err := os.WriteFile(statePath, []byte(`{"version":99,"deleted":false,"files":{}}`), 0644); err != nil {- t.Fatal(err)- }- before, _ := os.ReadFile(statePath)- for _, operation := range []func() error{- func() error { return ValidateAppearancePackage("icons", "example") },- func() error { return PrepareAppearancePackages() },- func() error { return PublishAppearancePackage(source, "icons", "example", PackageInfo{}, false, true) },- func() error { return DeleteAppearancePackage("icons", "example") },- } {- if err := operation(); err == nil {- t.Fatal("unknown version accepted")- }- }- after, _ := os.ReadFile(statePath)- if !reflect.DeepEqual(before, after) {- t.Fatal("unknown state changed")- }- data, err := os.ReadFile(filepath.Join(payload, "icon.js"))- if err != nil || string(data) != "original" {- t.Fatalf("original changed: %s %v", data, err)- }-}--func TestAppearanceStateManualChangesAndIgnore(t *testing.T) {- setupAppearanceStateTest(t)- payload := filepath.Join(util.ThemesPath, "manual")- writeAppearanceTestFile(t, payload, "theme.css", "one")- if err := PrepareAppearancePackages(); err != nil {- t.Fatal(err)- }- _, statePath, _ := appearancePackagePaths("themes", "manual")- before, _ := os.ReadFile(statePath)- if err := PrepareAppearancePackages(); err != nil {- t.Fatal(err)- }- after, _ := os.ReadFile(statePath)- if !reflect.DeepEqual(before, after) {- t.Fatal("unchanged scan rewrites state")- }- writeAppearanceTestFile(t, payload, "theme.css", "two")- if err := ValidateAppearancePackage("themes", "manual"); err == nil {- t.Fatal("unrecorded mutation accepted")- }- if err := PrepareAppearancePackages(); err != nil {- t.Fatal(err)- }- if err := ValidateAppearancePackage("themes", "manual"); err != nil {- t.Fatal(err)- }- if err := os.RemoveAll(payload); err != nil {- t.Fatal(err)- }- if err := PrepareAppearancePackages(func(kind, name string) bool { return kind == "themes" && name == "manual" }); err != nil {- t.Fatal(err)- }- state, _ := readAppearanceState(statePath)- if state.Deleted {- t.Fatal("ignored package removal changed shared state")- }- if err := PrepareAppearancePackages(); err != nil {- t.Fatal(err)- }- state, _ = readAppearanceState(statePath)- if !state.Deleted {- t.Fatal("manual deletion not recorded")- }-}--func TestAppearanceOperationRecovery(t *testing.T) {- for _, boundary := range []string{"staged", "backed-up", "renamed", "state-written", "corrupt-stage", "modified-before-recovery", "unknown-state-after-rename"} {- t.Run(boundary, func(t *testing.T) {- setupAppearanceStateTest(t)- payload, statePath, _ := appearancePackagePaths("themes", "example")- writeAppearanceTestFile(t, payload, "old.css", "recover me")- opDir := filepath.Join(appearanceOperationsPath(), "package-test")- stage := filepath.Join(opDir, "staging")- writeAppearanceTestFile(t, stage, "theme.css", "new")- files, err := appearanceFiles(stage)- if err != nil {- t.Fatal(err)- }- before, _ := appearanceFiles(payload)- op := appearanceOperation{Version: 1, Kind: "themes", Name: "example", State: AppearancePackageState{Version: 1, Files: files}, BeforeExists: true, Before: before}- data, _ := json.Marshal(op)- writeAppearanceTestFile(t, opDir, "operation.json", string(data))- if boundary == "modified-before-recovery" {- writeAppearanceTestFile(t, payload, "old.css", "offline edit")- if err = RecoverAppearancePackages(); err == nil {- t.Fatal("offline change overwritten")- }- actual, readErr := os.ReadFile(filepath.Join(payload, "old.css"))- if readErr != nil || string(actual) != "offline edit" {- t.Fatal("offline change lost", readErr)- }- return- }- if boundary == "corrupt-stage" {- writeAppearanceTestFile(t, stage, "theme.css", "corrupted")- if err = RecoverAppearancePackages(); err == nil {- t.Fatal("corrupted staging accepted")- }- if _, err = os.Stat(filepath.Join(payload, "old.css")); err != nil {- t.Fatal("original displaced before validation", err)- }- return- }- if boundary != "staged" {- if err = os.Rename(payload, filepath.Join(opDir, "backup")); err != nil {- t.Fatal(err)- }- }- if boundary == "renamed" || boundary == "state-written" || boundary == "unknown-state-after-rename" {- if err = os.Rename(stage, payload); err != nil {- t.Fatal(err)- }- }- if boundary == "unknown-state-after-rename" {- writeAppearanceTestFile(t, filepath.Dir(statePath), filepath.Base(statePath), `{"version":99,"files":{}}`)- if err = RecoverAppearancePackages(); err == nil {- t.Fatal("unknown state overwritten after rename")- }- actual, readErr := os.ReadFile(statePath)- if readErr != nil || string(actual) != `{"version":99,"files":{}}` {- t.Fatal("unknown state lost", readErr)- }- if _, err = os.Stat(filepath.Join(opDir, "backup", "old.css")); err != nil {- t.Fatal("original backup lost", err)- }- return- }- if boundary == "state-written" {- if err = writeAppearanceState(statePath, &op.State); err != nil {- t.Fatal(err)- }- }- if err = RecoverAppearancePackages(); err != nil {- t.Fatal(err)- }- if err = ValidateAppearancePackage("themes", "example"); err != nil {- t.Fatal(err)- }- if _, err = os.Stat(opDir); !os.IsNotExist(err) {- t.Fatalf("completed journal remains: %v", err)- }- if err = RecoverAppearancePackages(); err != nil {- t.Fatal("recovery not idempotent", err)- }- })- }-}--func TestAppearanceDeleteRecoveryAfterBackupArchive(t *testing.T) {- setupAppearanceStateTest(t)- _, statePath, _ := appearancePackagePaths("themes", "example")- opDir := filepath.Join(appearanceOperationsPath(), "package-deleted")- op := appearanceOperation{Version: 1, Kind: "themes", Name: "example", BeforeExists: true, Before: map[string]string{}, State: AppearancePackageState{Version: 1, Deleted: true, Files: map[string]string{}}}- data, _ := json.Marshal(op)- writeAppearanceTestFile(t, opDir, "operation.json", string(data))- writeAppearanceTestFile(t, filepath.Join(util.DataDir, ".siyuan-appearance-backups", filepath.Base(opDir)), "theme.css", "original")- if err := writeAppearanceState(statePath, &op.State); err != nil {- t.Fatal(err)- }- if err := RecoverAppearancePackages(); err != nil {- t.Fatal(err)- }- if _, err := os.Stat(opDir); !os.IsNotExist(err) {- t.Fatal("completed deletion journal remains", err)- }- if _, err := os.Stat(filepath.Join(util.DataDir, ".siyuan-appearance-backups", filepath.Base(opDir), "theme.css")); err != nil {- t.Fatal("archived original lost", err)- }-}diff --git a/kernel/bazaar/install.go b/kernel/bazaar/install.goindex 683477d7a8..0531b7502c 100644--- a/kernel/bazaar/install.go+++ b/kernel/bazaar/install.go@@ -109,16 +109,14 @@ func InstallPackage(repoURL, repoHash, repoRef, installPath, systemID, pkgType,if err != nil {return err}- if err = installPackageWithSource(data, installPath, pkgType, packageName, update, repoURL, repoRef); err != nil {+ if err = installPackage(data, installPath, pkgType, packageName, update); err != nil {return err}RemoveInstalledPackageSizeCache(pkgType, packageName)// 记录首次安装时间或最近更新时间now := time.Now()- if !isAppearanceKind(pkgType) {- recordPackageOperationTime(pkgType, packageName, now, fallbackInstallTime, update, repoURL, repoRef)- }+ recordPackageOperationTime(pkgType, packageName, now, fallbackInstallTime, update, repoURL, repoRef)// 文件夹的修改时间设置为当前操作时间if err = os.Chtimes(installPath, now, now); err != nil {@@ -130,10 +128,6 @@ func InstallPackage(repoURL, repoHash, repoRef, installPath, systemID, pkgType,}func installPackage(data []byte, installPath, pkgType, packageName string, update bool) (err error) {- return installPackageWithSource(data, installPath, pkgType, packageName, update, "", "")-}--func installPackageWithSource(data []byte, installPath, pkgType, packageName string, update bool, repoURL, repoRef string) (err error) {// 非更新安装时目标目录已存在且非空则拒绝覆盖,防止把其他包的内容写入已有包目录// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-rpx2-p6hp-x5gjif !update {@@ -188,44 +182,12 @@ func installPackageWithSource(data []byte, installPath, pkgType, packageName strreturn fmt.Errorf("marketplace package name mismatch: expected [%s], got [%s]", packageName, pkg.Name)}- if err = publishInstalledPackage(srcPath, installPath, pkgType, packageName, update, repoURL, repoRef); err != nil {+ if err = replacePackageDirectory(srcPath, installPath, update); err != nil {return}return}-// publishInstalledPackage 将外观包内容和安装元数据放入同一个可恢复事务。-func publishInstalledPackage(sourcePath, installPath, pkgType, packageName string, update bool, repoURL, repoRef string) error {- if !isAppearanceKind(pkgType) {- return replacePackageDirectory(sourcePath, installPath, update)- }- expectedPath, _, err := appearancePackagePaths(pkgType, packageName)- if err != nil {- return err- }- if filepath.Clean(installPath) != filepath.Clean(expectedPath) {- return errors.New("invalid appearance package install path")- }- info, err := GetAppearancePackageInfo(pkgType, packageName)- if err != nil {- return err- }- now := time.Now()- if update {- if info.InstallTime < 1 {- info.InstallTime = now.UnixMilli()- if stat, statErr := os.Stat(installPath); statErr == nil {- info.InstallTime = stat.ModTime().UnixMilli()- }- }- info.UpdateTime = now.UnixMilli()- } else {- info.InstallTime, info.UpdateTime = now.UnixMilli(), 0- }- info.RepoURL, info.RepoRef = normalizeGitHubPackageSource(repoURL, repoRef)- return PublishAppearancePackage(sourcePath, pkgType, packageName, *info, false, update)-}-// replacePackageDirectory 将 sourcePath 整目录替换到 installPath。// 先拷到安装目录同级的 staging,更新时再把旧目录 rename 成 backup,最后把 staging rename 成目标路径。// 这样新包已删除的文件不会残留,失败时也可以把 backup rename 回去。@@ -290,15 +252,13 @@ func InstallLocalPackage(sourcePath, installPath, pkgType, packageName string, uif info, statErr := os.Stat(installPath); statErr == nil {fallbackInstallTime = info.ModTime()}- if err = publishInstalledPackage(sourcePath, installPath, pkgType, packageName, update, "", ""); err != nil {+ if err = replacePackageDirectory(sourcePath, installPath, update); err != nil {return}RemoveInstalledPackageSizeCache(pkgType, packageName)now := time.Now()- if !isAppearanceKind(pkgType) {- recordPackageOperationTime(pkgType, packageName, now, fallbackInstallTime, update, "", "")- }+ recordPackageOperationTime(pkgType, packageName, now, fallbackInstallTime, update, "", "")if chtimesErr := os.Chtimes(installPath, now, now); chtimesErr != nil {logging.LogWarnf("set package [%s] folder mtime failed: %s", packageName, chtimesErr)}@@ -307,12 +267,6 @@ func InstallLocalPackage(sourcePath, installPath, pkgType, packageName string, u// UninstallPackage 卸载集市包func UninstallPackage(installPath string) (err error) {- if relativePath, relErr := filepath.Rel(util.DataDir, installPath); relErr == nil {- parts := strings.Split(filepath.ToSlash(relativePath), "/")- if len(parts) == 2 && isAppearanceKind(parts[0]) {- return DeleteAppearancePackage(parts[0], parts[1])- }- }packageInstallLock.Lock()defer packageInstallLock.Unlock()diff --git a/kernel/bazaar/install_test.go b/kernel/bazaar/install_test.goindex 5f94c40c20..78f47d9a23 100644--- a/kernel/bazaar/install_test.go+++ b/kernel/bazaar/install_test.go@@ -22,7 +22,6 @@ import ("net/http/httptest""os""path/filepath"- "reflect""testing""github.com/siyuan-note/siyuan/kernel/util"@@ -280,78 +279,3 @@ func buildInstallPackageArchive(t *testing.T, files map[string]string) []byte {}return data}--func TestAppearanceInstallUpdateAndDeletePublishPackageState(t *testing.T) {- useTestBazaarInfo(t)- oldTemp, oldThemes, oldIcons := util.TempDir, util.ThemesPath, util.IconsPath- util.TempDir = t.TempDir()- util.ThemesPath, util.IconsPath = filepath.Join(util.DataDir, "themes"), filepath.Join(util.DataDir, "icons")- t.Cleanup(func() { util.TempDir, util.ThemesPath, util.IconsPath = oldTemp, oldThemes, oldIcons })- for _, kind := range []string{"themes", "icons"} {- t.Run(kind, func(t *testing.T) {- manifest, entry := "theme.json", "theme.css"- if kind == "icons" {- manifest, entry = "icon.json", "icon.js"- }- installPath := util.AppearancePackagePath(kind, "sample")- data := buildInstallPackageArchive(t, map[string]string{- manifest: `{"name":"sample","version":"1.0.0"}`, entry: "version one", "stale.txt": "stale",- })- if err := installPackageWithSource(data, installPath, kind, "sample", false, "https://github.com/owner/repo", "v1"); err != nil {- t.Fatal(err)- }- if err := ValidateAppearancePackage(kind, "sample"); err != nil {- t.Fatal(err)- }- initial, err := GetAppearancePackageInfo(kind, "sample")- if err != nil || initial.InstallTime == 0 || initial.UpdateTime != 0 || initial.RepoRef != "v1" {- t.Fatalf("invalid install state: %+v, %v", initial, err)- }- source := t.TempDir()- for name, content := range map[string]string{manifest: `{"name":"sample","version":"2.0.0"}`, entry: "version two"} {- if err = os.WriteFile(filepath.Join(source, name), []byte(content), 0644); err != nil {- t.Fatal(err)- }- }- if err = InstallLocalPackage(source, installPath, kind, "sample", true); err != nil {- t.Fatal(err)- }- updated, err := GetAppearancePackageInfo(kind, "sample")- if err != nil || updated.InstallTime != initial.InstallTime || updated.UpdateTime == 0 || updated.RepoURL != "" {- t.Fatalf("invalid update state: %+v, %v", updated, err)- }- if _, err = os.Stat(filepath.Join(installPath, "stale.txt")); !os.IsNotExist(err) {- t.Fatalf("stale file survived update: %v", err)- }- if err = ValidateAppearancePackage(kind, "sample"); err != nil {- t.Fatal(err)- }- if err = UninstallPackage(installPath); err != nil {- t.Fatal(err)- }- _, statePath, err := appearancePackagePaths(kind, "sample")- if err != nil {- t.Fatal(err)- }- state, err := readAppearanceState(statePath)- if err != nil || !state.Deleted || len(state.Files) != 0 {- t.Fatalf("invalid deletion state: %+v, %v", state, err)- }- if _, err = os.Stat(installPath); !os.IsNotExist(err) {- t.Fatalf("package survived deletion: %v", err)- }- if err = InstallLocalPackage(source, installPath, kind, "sample", false); err != nil {- t.Fatal(err)- }- if err = ValidateAppearancePackage(kind, "sample"); err != nil {- t.Fatalf("explicit reinstall did not clear deletion: %v", err)- }- if info, err := GetAppearancePackageInfo(kind, "sample"); err != nil || reflect.DeepEqual(info, updated) || info.UpdateTime != 0 {- t.Fatalf("reinstall did not reset operation state: %+v, %v", info, err)- }- })- }- if _, err := os.Stat(filepath.Join(util.DataDir, "storage", "bazaar.json")); !os.IsNotExist(err) {- t.Fatalf("appearance installation unexpectedly rewrote shared bazaar metadata: %v", err)- }-}diff --git a/kernel/bazaar/installed.go b/kernel/bazaar/installed.goindex 6275d0c8ef..5768ad9b59 100644--- a/kernel/bazaar/installed.go+++ b/kernel/bazaar/installed.go@@ -331,9 +331,6 @@ func saveBazaarInfo() {// recordPackageOperationTime 记录集市包的首次安装时间或最近更新时间func recordPackageOperationTime(pkgType, pkgName string, operationTime, fallbackInstallTime time.Time, update bool,repoURL, repoRef string) {- if isAppearanceKind(pkgType) {- return- }getBazaarInfo()repoURL, repoRef = normalizeGitHubPackageSource(repoURL, repoRef)@@ -372,14 +369,6 @@ func recordPackageOperationTime(pkgType, pkgName string, operationTime, fallback}func getPackageSource(pkgType, pkgName string) (repoURL, repoRef string) {- if isAppearanceKind(pkgType) {- info, err := GetAppearancePackageInfo(pkgType, pkgName)- if err == nil {- return normalizeGitHubPackageSource(info.RepoURL, info.RepoRef)- }- logging.LogErrorf("read appearance metadata failed: %s", err)- return- }getBazaarInfo()bazaarInfoCacheLock.RLock()defer bazaarInfoCacheLock.RUnlock()@@ -399,9 +388,6 @@ func getPackageRepoRef(pkgType, pkgName string) string {// ensurePackageInstallTime 在没有首次安装时间时进行初始化func ensurePackageInstallTime(pkgType, pkgName string, fallbackInstallTime time.Time) (installTime, updateTime int64) {- if isAppearanceKind(pkgType) {- return fallbackInstallTime.UnixMilli(), 0- }getBazaarInfo()bazaarInfoCacheLock.Lock()@@ -430,20 +416,6 @@ func ensurePackageInstallTime(pkgType, pkgName string, fallbackInstallTime time.// getPackageTimes 获取集市包的首次安装时间和最近更新时间func getPackageTimes(pkgType, pkgName, installPath string) (installTime, updateTime int64) {- if isAppearanceKind(pkgType) {- info, err := GetAppearancePackageInfo(pkgType, pkgName)- if err != nil {- logging.LogErrorf("read appearance metadata failed: %s", err)- return- }- if info.InstallTime > 0 {- return info.InstallTime, info.UpdateTime- }- if stat, statErr := os.Stat(installPath); statErr == nil {- return stat.ModTime().UnixMilli(), 0- }- return- }getBazaarInfo()bazaarInfoCacheLock.RLock()if bazaarInfoCache != nil && bazaarInfoCache.Packages[pkgType] != nil {@@ -469,9 +441,6 @@ func getPackageTimes(pkgType, pkgName, installPath string) (installTime, updateT// RemovePackageInfo 删除集市包的持久化信息func RemovePackageInfo(pkgType, pkgName string) {- if isAppearanceKind(pkgType) {- return- }getBazaarInfo()bazaarInfoCacheLock.Lock()diff --git a/kernel/go.mod b/kernel/go.modindex e6499c9ee9..e8c36a238c 100644--- a/kernel/go.mod+++ b/kernel/go.mod@@ -72,7 +72,7 @@ require (github.com/sashabaranov/go-openai v1.42.0github.com/shirou/gopsutil/v4 v4.26.7github.com/siyuan-note/dataparser v0.0.0-20260115084335-b57cb8bc7c17- github.com/siyuan-note/dejavu v0.0.0-20260918093653-181204de4bc3+ github.com/siyuan-note/dejavu v0.0.0-20260918121655-fd4a6f8ff54cgithub.com/siyuan-note/encryption v0.0.0-20260715062728-9cb8e9548044github.com/siyuan-note/eventbus v0.0.0-20260530125927-d77c74260dcegithub.com/siyuan-note/filelock v0.0.0-20260831011452-393425122aaadiff --git a/kernel/go.sum b/kernel/go.sumindex f9c8083b45..d7d5dd6f05 100644--- a/kernel/go.sum+++ b/kernel/go.sum@@ -508,6 +508,8 @@ github.com/siyuan-note/dejavu v0.0.0-20260918053354-05b0966e6b3b h1:3cOHb8aNE3lQgithub.com/siyuan-note/dejavu v0.0.0-20260918053354-05b0966e6b3b/go.mod h1:ixj6rxm+wkjoV8pBDGbuCyfMiPQh3MlxBwHG5OvtEQU=github.com/siyuan-note/dejavu v0.0.0-20260918093653-181204de4bc3 h1:xWDz0Qx7YrWtEaJGzwwPOUFYf/Nc0MofCcWQYyM6uwg=github.com/siyuan-note/dejavu v0.0.0-20260918093653-181204de4bc3/go.mod h1:ixj6rxm+wkjoV8pBDGbuCyfMiPQh3MlxBwHG5OvtEQU=+github.com/siyuan-note/dejavu v0.0.0-20260918121655-fd4a6f8ff54c h1:Fd6XDq7vNFf6cN3ZVh/a+y3KGPzRIcHC1X8GljrsISY=+github.com/siyuan-note/dejavu v0.0.0-20260918121655-fd4a6f8ff54c/go.mod h1:ixj6rxm+wkjoV8pBDGbuCyfMiPQh3MlxBwHG5OvtEQU=github.com/siyuan-note/encryption v0.0.0-20260715062728-9cb8e9548044 h1:b1/Q4DSREDvGh1/NbzR9873EKrjakdoUtsNlghWxUOI=github.com/siyuan-note/encryption v0.0.0-20260715062728-9cb8e9548044/go.mod h1:t6jXpJdrXzRsdQF+XGaw35f16JVZcDyIkk5/6//ywnY=github.com/siyuan-note/eventbus v0.0.0-20260530125927-d77c74260dce h1:356bfC3pucxXuYpZIwaQ3viVCbq5RbRuvBhb4xtoBR0=diff --git a/kernel/model/appearance.go b/kernel/model/appearance.goindex 4c97f3108e..505c4eb660 100644--- a/kernel/model/appearance.go+++ b/kernel/model/appearance.go@@ -61,36 +61,29 @@ func InitAppearance() {// refreshAppearanceConfig 按完整可用的包刷新本机外观选择,缺失或不兼容时使用内置资源。func refreshAppearanceConfig() {- lockPath := filepath.Join(util.DataDir, ".siyuan-appearance")- filelock.Lock(lockPath)- defer filelock.Unlock(lockPath)- runtimeState := newAppearanceRuntimeState()- loadThemes(runtimeState)- loadIcons(runtimeState)+ LoadThemes()+ LoadIcons()var reloadThemes, reloadIcons boolConf.m.Lock()- if !containTheme(Conf.Appearance.ThemeDark, Conf.Appearance.DarkThemes) &&- !runtimeState.preserveSelection("themes", Conf.Appearance.ThemeDark) {+ if !containTheme(Conf.Appearance.ThemeDark, Conf.Appearance.DarkThemes) {Conf.Appearance.ThemeDark = "midnight"reloadThemes = true}- if !containTheme(Conf.Appearance.ThemeLight, Conf.Appearance.LightThemes) &&- !runtimeState.preserveSelection("themes", Conf.Appearance.ThemeLight) {+ if !containTheme(Conf.Appearance.ThemeLight, Conf.Appearance.LightThemes) {Conf.Appearance.ThemeLight = "daylight"reloadThemes = true}- if !containIcon(Conf.Appearance.Icon, Conf.Appearance.Icons) &&- !runtimeState.preserveSelection("icons", Conf.Appearance.Icon) {+ if !containIcon(Conf.Appearance.Icon, Conf.Appearance.Icons) {Conf.Appearance.Icon = "litheness"reloadIcons = true}Conf.m.Unlock()if reloadThemes {- loadThemes(runtimeState)+ LoadThemes()}if reloadIcons {- loadIcons(runtimeState)+ LoadIcons()}Conf.Save()}@@ -187,13 +180,6 @@ func appearancePackageNames(kind string) ([]string, error) {}func LoadThemes() {- lockPath := filepath.Join(util.DataDir, ".siyuan-appearance")- filelock.Lock(lockPath)- defer filelock.Unlock(lockPath)- loadThemes(newAppearanceRuntimeState())-}--func loadThemes(runtimeState *appearanceRuntimeState) {themeNames, err := appearancePackageNames("themes")if err != nil {logging.LogErrorf("read appearance themes folder failed: %s", err)@@ -210,12 +196,6 @@ func loadThemes(runtimeState *appearanceRuntimeState) {themeDark := Conf.Appearance.ThemeDarkfor _, name := range themeNames {themePath := util.AppearancePackagePath("themes", name)- if !isBuiltInTheme(name) {- if err := runtimeState.validate("themes", name); err != nil {- logging.LogWarnf("skip unavailable theme [%s]: %s", name, err)- continue- }- }themeConf, parseErr := bazaar.ParsePackageJSON(filepath.Join(themePath, "theme.json"))if nil != parseErr || !bazaar.IsValidInstalledPackage(themeConf, name) ||bazaar.IsBelowRequiredAppVersion(themeConf) || !gulu.File.IsExist(filepath.Join(themePath, "theme.css")) {@@ -287,13 +267,6 @@ func loadThemes(runtimeState *appearanceRuntimeState) {}func LoadIcons() {- lockPath := filepath.Join(util.DataDir, ".siyuan-appearance")- filelock.Lock(lockPath)- defer filelock.Unlock(lockPath)- loadIcons(newAppearanceRuntimeState())-}--func loadIcons(runtimeState *appearanceRuntimeState) {iconNames, err := appearancePackageNames("icons")if err != nil {logging.LogErrorf("read appearance icons folder failed: %s", err)@@ -306,12 +279,6 @@ func loadIcons(runtimeState *appearanceRuntimeState) {currentIcon := Conf.Appearance.Iconfor _, name := range iconNames {iconPath := util.AppearancePackagePath("icons", name)- if !isBuiltInIcon(name) {- if err := runtimeState.validate("icons", name); err != nil {- logging.LogWarnf("skip unavailable icon [%s]: %s", name, err)- continue- }- }iconConf, err := bazaar.ParsePackageJSON(filepath.Join(iconPath, "icon.json"))if err != nil || !bazaar.IsValidInstalledPackage(iconConf, name) ||bazaar.IsBelowRequiredAppVersion(iconConf) || !gulu.File.IsExist(filepath.Join(iconPath, "icon.js")) {diff --git a/kernel/model/appearance_export.go b/kernel/model/appearance_export.goindex 1d0f25950c..bc0bb14d94 100644--- a/kernel/model/appearance_export.go+++ b/kernel/model/appearance_export.go@@ -26,10 +26,6 @@ import (// copyExportAppearance 将完整外观包复制到导出目录,并保留默认主题和图标作为后备。func copyExportAppearance(savePath, theme, icon string) error {- lockPath := filepath.Join(util.DataDir, ".siyuan-appearance")- filelock.Lock(lockPath)- defer filelock.Unlock(lockPath)- runtimeState := newAppearanceRuntimeState()packages := map[string][]string{"themes": {"daylight", "midnight", theme},"icons": {"litheness", icon},@@ -44,11 +40,6 @@ func copyExportAppearance(savePath, theme, icon string) error {if from == "" {return fmt.Errorf("invalid appearance package [%s/%s]", kind, name)}- if (kind == "themes" && !isBuiltInTheme(name)) || (kind == "icons" && !isBuiltInIcon(name)) {- if err := runtimeState.validate(kind, name); err != nil {- return err- }- }// 解析包目录本身的符号链接,使导出保留完整资源而不携带本机路径。from, err := filepath.EvalSymlinks(from)if err != nil {diff --git a/kernel/model/appearance_migration.go b/kernel/model/appearance_migration.godeleted file mode 100644index 4d0d9a593d..0000000000--- a/kernel/model/appearance_migration.go+++ /dev/null@@ -1,124 +0,0 @@-package model--import (- "encoding/json"- "errors"- "fmt"- "os"- "path/filepath"- "sync"-- "github.com/siyuan-note/filelock"- "github.com/siyuan-note/siyuan/kernel/bazaar"- "github.com/siyuan-note/siyuan/kernel/util"-)--var appearanceMigrationMu sync.Mutex--type appearanceMigrationState struct {- Version int `json:"version"`- Completed bool `json:"completed"`-}--// MigrateAppearancePackages 保留原目录并逐包迁移;已有目标或删除记录优先,完成标记仅保存在本机。-func MigrateAppearancePackages() error {- appearanceMigrationMu.Lock()- defer appearanceMigrationMu.Unlock()- journalPath := filepath.Join(util.ConfDir, "appearance-migration.json")- completed := false- data, err := os.ReadFile(journalPath)- if err == nil {- var state appearanceMigrationState- if err = json.Unmarshal(data, &state); err != nil {- return err- }- if state.Version != 1 {- return fmt.Errorf("unsupported appearance migration version: %d", state.Version)- }- completed = state.Completed- } else if !os.IsNotExist(err) {- return err- }- if err = util.EnsureAppearanceSyncIsolation(); err != nil {- return err- }- for _, root := range []string{util.ThemesPath, util.IconsPath} {- if err = os.MkdirAll(root, 0755); err != nil {- return err- }- }- if err = bazaar.RecoverAppearancePackages(); err != nil {- return err- }- if completed {- return nil- }-- sourceRoot := util.AppearancePath- if util.Mode == "dev" {- sourceRoot = filepath.Join(util.WorkingDir, "appearance")- }- for _, kind := range []string{"themes", "icons"} {- entries, readErr := bazaar.ReadInstalledPackageDirs(filepath.Join(sourceRoot, kind))- if readErr != nil {- return readErr- }- for _, entry := range entries {- name := entry.Name()- if (kind == "themes" && isBuiltInTheme(name)) || (kind == "icons" && isBuiltInIcon(name)) {- continue- }- target := util.AppearancePackagePath(kind, name)- if target == "" {- continue- }- if _, statErr := os.Lstat(target); statErr == nil {- continue- } else if !os.IsNotExist(statErr) {- return statErr- }- statePath := filepath.Join(util.DataDir, "storage", "bazaar", kind, name+".json")- if _, statErr := os.Lstat(statePath); statErr == nil {- continue- } else if !os.IsNotExist(statErr) {- return statErr- }- source := filepath.Join(sourceRoot, kind, name)- linked, linkErr := bazaar.HasAppearancePackageSymlink(source)- if linkErr != nil {- return linkErr- }- if linked {- // 开发包保留链接关系和原目录,仅普通目录进入同步。- linkTarget, resolveErr := filepath.EvalSymlinks(source)- if resolveErr != nil {- return resolveErr- }- if err = os.Symlink(linkTarget, target); err != nil {- return err- }- continue- }- info, infoErr := bazaar.GetAppearancePackageInfo(kind, name)- if infoErr != nil {- return infoErr- }- if info.InstallTime < 1 {- stat, statErr := os.Stat(source)- if statErr != nil {- return statErr- }- info.InstallTime = stat.ModTime().UnixMilli()- }- if err = bazaar.PublishAppearancePackage(source, kind, name, *info, true, false); err != nil &&- !errors.Is(err, bazaar.ErrAppearancePackageEmpty) {- return err- }- }- }- data, err = json.Marshal(appearanceMigrationState{Version: 1, Completed: true})- if err != nil {- return err- }- return filelock.WriteFile(journalPath, data)-}diff --git a/kernel/model/appearance_migration_test.go b/kernel/model/appearance_migration_test.godeleted file mode 100644index 03562a970e..0000000000--- a/kernel/model/appearance_migration_test.go+++ /dev/null@@ -1,199 +0,0 @@-package model--import (- "os"- "path/filepath"- "strings"- "testing"-- "github.com/siyuan-note/siyuan/kernel/bazaar"- "github.com/siyuan-note/siyuan/kernel/util"-)--func setupAppearanceMigrationTest(t *testing.T) string {- t.Helper()- oldData, oldConf, oldAppearance, oldThemes, oldIcons, oldMode := util.DataDir, util.ConfDir, util.AppearancePath, util.ThemesPath, util.IconsPath, util.Mode- root := t.TempDir()- util.DataDir, util.ConfDir = filepath.Join(root, "data"), filepath.Join(root, "conf")- util.AppearancePath = filepath.Join(util.ConfDir, "appearance")- util.ThemesPath, util.IconsPath, util.Mode = filepath.Join(util.DataDir, "themes"), filepath.Join(util.DataDir, "icons"), "prod"- t.Cleanup(func() {- util.DataDir, util.ConfDir, util.AppearancePath, util.ThemesPath, util.IconsPath, util.Mode = oldData, oldConf, oldAppearance, oldThemes, oldIcons, oldMode- })- return root-}--func writeMigrationTestFile(t *testing.T, root, name, data string) {- t.Helper()- filePath := filepath.Join(root, filepath.FromSlash(name))- if err := os.MkdirAll(filepath.Dir(filePath), 0755); err != nil {- t.Fatal(err)- }- if err := os.WriteFile(filePath, []byte(data), 0644); err != nil {- t.Fatal(err)- }-}--func TestAppearanceMigrationPreservesSourceAndDeletion(t *testing.T) {- setupAppearanceMigrationTest(t)- writeMigrationTestFile(t, util.AppearancePath, "themes/daylight/theme.css", "builtin")- writeMigrationTestFile(t, util.AppearancePath, "themes/example/theme.css", "legacy")- writeMigrationTestFile(t, util.AppearancePath, "icons/removed/icon.js", "must not return")- writeMigrationTestFile(t, util.AppearancePath, "themes/existing/theme.css", "old legacy")- writeMigrationTestFile(t, util.ThemesPath, "existing/theme.css", "current data")- if err := bazaar.DeleteAppearancePackage("icons", "removed"); err != nil {- t.Fatal(err)- }- if err := MigrateAppearancePackages(); err != nil {- t.Fatal(err)- }- for _, root := range []string{util.AppearancePath, util.DataDir} {- data, err := os.ReadFile(filepath.Join(root, "themes", "example", "theme.css"))- if err != nil || string(data) != "legacy" {- t.Fatalf("migration/source: %s %v", data, err)- }- }- for _, name := range []string{"themes/daylight", "icons/removed"} {- if _, err := os.Stat(filepath.Join(util.DataDir, filepath.FromSlash(name))); !os.IsNotExist(err) {- t.Fatalf("unexpected migrated package %s: %v", name, err)- }- }- data, err := os.ReadFile(filepath.Join(util.ThemesPath, "existing", "theme.css"))- if err != nil || string(data) != "current data" {- t.Fatalf("existing target overwritten: %s %v", data, err)- }- state, _ := os.ReadFile(filepath.Join(util.DataDir, "storage", "bazaar", "themes", "example.json"))- if !strings.Contains(string(state), `"migration": true`) {- t.Fatalf("migration origin missing: %s", state)- }- if err = bazaar.DeleteAppearancePackage("themes", "example"); err != nil {- t.Fatal(err)- }- if err = MigrateAppearancePackages(); err != nil {- t.Fatal(err)- }- if _, err = os.Stat(filepath.Join(util.ThemesPath, "example")); !os.IsNotExist(err) {- t.Fatal("migration resurrected removed package", err)- }-}--func TestAppearanceMigrationUnknownJournalPreserved(t *testing.T) {- setupAppearanceMigrationTest(t)- writeMigrationTestFile(t, util.ConfDir, "appearance-migration.json", `{"version":2,"completed":false}`)- writeMigrationTestFile(t, util.AppearancePath, "themes/example/theme.css", "original")- if err := MigrateAppearancePackages(); err == nil {- t.Fatal("unknown migration accepted")- }- data, _ := os.ReadFile(filepath.Join(util.ConfDir, "appearance-migration.json"))- if string(data) != `{"version":2,"completed":false}` {- t.Fatal("unknown migration journal overwritten")- }- if _, err := os.Stat(filepath.Join(util.ThemesPath, "example")); !os.IsNotExist(err) {- t.Fatal("unknown migration wrote payload")- }-}--func TestAppearanceMigrationSkipsEmptyDirectories(t *testing.T) {- setupAppearanceMigrationTest(t)- for _, name := range []string{"empty", "ignored"} {- if err := os.MkdirAll(filepath.Join(util.AppearancePath, "themes", name), 0755); err != nil {- t.Fatal(err)- }- }- writeMigrationTestFile(t, util.AppearancePath, "themes/ignored/.draft", "keep original")- writeMigrationTestFile(t, util.AppearancePath, "themes/example/theme.css", "legacy")- if err := MigrateAppearancePackages(); err != nil {- t.Fatal(err)- }- for _, name := range []string{"empty", "ignored"} {- if _, err := os.Stat(filepath.Join(util.AppearancePath, "themes", name)); err != nil {- t.Fatalf("source directory was not preserved: %v", err)- }- for _, target := range []string{- filepath.Join(util.ThemesPath, name),- filepath.Join(util.DataDir, "storage", "bazaar", "themes", name+".json"),- } {- if _, err := os.Stat(target); !os.IsNotExist(err) {- t.Fatalf("empty directory received synchronized state: %s: %v", target, err)- }- }- }- data, err := os.ReadFile(filepath.Join(util.AppearancePath, "themes", "ignored", ".draft"))- if err != nil || string(data) != "keep original" {- t.Fatalf("ignored source file changed: %s %v", data, err)- }- if err = bazaar.ValidateAppearancePackage("themes", "example"); err != nil {- t.Fatal(err)- }- if _, err = os.Stat(filepath.Join(util.ThemesPath, "example", "theme.css")); err != nil {- t.Fatalf("nonempty package was not migrated: %v", err)- }-}--func TestAppearanceStatePayloadPath(t *testing.T) {- for input, want := range map[string]string{- "/storage/bazaar/themes/example.json": "themes/example/",- "/storage/bazaar/icons/example.json": "icons/example/",- "/storage/bazaar.json": "",- "/storage/bazaar/plugins/example.json": "",- "/themes/example/theme.css": "",- } {- if got := appearanceStatePayloadPath(input); got != want {- t.Fatalf("%s = %s; want %s", input, got, want)- }- }-}--func TestAppearanceMigrationPreservesLinkedPackages(t *testing.T) {- for _, nested := range []bool{false, true} {- name := "root"- if nested {- name = "nested"- }- t.Run(name, func(t *testing.T) {- setupAppearanceMigrationTest(t)- source := filepath.Join(util.AppearancePath, "themes", "linked")- original := t.TempDir()- writeMigrationTestFile(t, original, "theme.css", "original")- if err := os.MkdirAll(filepath.Dir(source), 0755); err != nil {- t.Fatal(err)- }- if nested {- writeMigrationTestFile(t, source, "theme.json", `{"name":"linked","version":"1.0.0","modes":["light"]}`)- writeMigrationTestFile(t, source, "real.css", "original")- if err := os.Symlink("real.css", filepath.Join(source, "theme.css")); err != nil {- t.Skipf("symlinks unavailable: %s", err)- }- } else if err := os.Symlink(original, source); err != nil {- t.Skipf("symlinks unavailable: %s", err)- }- if err := MigrateAppearancePackages(); err != nil {- t.Fatal(err)- }- target := util.AppearancePackagePath("themes", "linked")- info, err := os.Lstat(target)- if err != nil || info.Mode()&os.ModeSymlink == 0 {- t.Fatalf("linked development package was not preserved: %v", err)- }- for _, root := range []string{source, target} {- data, readErr := os.ReadFile(filepath.Join(root, "theme.css"))- if readErr != nil || string(data) != "original" {- t.Fatalf("source or migrated package changed: %s %v", data, readErr)- }- }- if err = bazaar.PrepareAppearancePackages(); err != nil {- t.Fatal(err)- }- statePath := filepath.Join(util.DataDir, "storage", "bazaar", "themes", "linked.json")- if _, err = os.Stat(statePath); !os.IsNotExist(err) {- t.Fatalf("linked development package received synchronization state: %v", err)- }- if ignored, filterErr := syncPathFilter(util.DataDir, info, target); !ignored || filterErr != nil {- t.Fatalf("linked package was included in synchronization: %t %v", ignored, filterErr)- }- if err = MigrateAppearancePackages(); err != nil {- t.Fatalf("repeated linked package migration failed: %s", err)- }- })- }-}diff --git a/kernel/model/appearance_packages_test.go b/kernel/model/appearance_packages_test.goindex e6faeb07ff..6e81713d3b 100644--- a/kernel/model/appearance_packages_test.go+++ b/kernel/model/appearance_packages_test.go@@ -13,9 +13,7 @@ import ("os""path/filepath""testing"- "time"- "github.com/siyuan-note/filelock""github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/util")@@ -180,38 +178,3 @@ func TestRefreshAppearanceConfigFallsBackAfterRemoval(t *testing.T) {t.Fatalf("appearance fallback retained stale package state: %+v", Conf.Appearance)}}--func TestAppearanceLoadWaitsForPackagePublication(t *testing.T) {- setupAppearancePackagesTest(t)- for name, load := range map[string]func(){"themes": LoadThemes, "icons": LoadIcons, "config": refreshAppearanceConfig} {- t.Run(name, func(t *testing.T) {- lockPath := filepath.Join(util.DataDir, ".siyuan-appearance")- filelock.Lock(lockPath)- released := false- defer func() {- if !released {- filelock.Unlock(lockPath)- }- }()- started, done := make(chan struct{}), make(chan struct{})- go func() {- close(started)- load()- close(done)- }()- <-started- select {- case <-done:- t.Fatal("appearance loaded during package publication")- case <-time.After(50 * time.Millisecond):- }- filelock.Unlock(lockPath)- released = true- select {- case <-done:- case <-time.After(3 * time.Second):- t.Fatal("appearance loading did not resume after package publication")- }- })- }-}diff --git a/kernel/model/appearance_paths_migration.go b/kernel/model/appearance_paths_migration.gonew file mode 100644index 0000000000..3259d8a5a8--- /dev/null+++ b/kernel/model/appearance_paths_migration.go@@ -0,0 +1,100 @@+package model++import (+ "os"+ "path/filepath"+ "sync"++ "github.com/siyuan-note/filelock"+ "github.com/siyuan-note/siyuan/kernel/bazaar"+ "github.com/siyuan-note/siyuan/kernel/util"+)++var appearanceMigrationMu sync.Mutex++// MigrateAppearancePackages 将第三方外观目录移入数据目录,已有目标优先,迁移成功后移除原目录。+func MigrateAppearancePackages() error {+ appearanceMigrationMu.Lock()+ defer appearanceMigrationMu.Unlock()+ if err := util.MigrateAppearanceSyncIgnore(); err != nil {+ return err+ }+ sourceRoot := util.AppearancePath+ if util.Mode == "dev" {+ sourceRoot = filepath.Join(util.WorkingDir, "appearance")+ }+ for _, kind := range []string{"themes", "icons"} {+ targetRoot := filepath.Join(util.DataDir, kind)+ if err := os.MkdirAll(targetRoot, 0755); err != nil {+ return err+ }+ entries, err := bazaar.ReadInstalledPackageDirs(filepath.Join(sourceRoot, kind))+ if err != nil {+ return err+ }+ for _, entry := range entries {+ name := entry.Name()+ if (kind == "themes" && isBuiltInTheme(name)) || (kind == "icons" && isBuiltInIcon(name)) {+ continue+ }+ source, target := filepath.Join(sourceRoot, kind, name), util.AppearancePackagePath(kind, name)+ if target == "" || filepath.Clean(source) == filepath.Clean(target) {+ continue+ }+ if err = moveAppearancePackage(source, target); err != nil {+ return err+ }+ }+ }+ return nil+}++func moveAppearancePackage(source, target string) error {+ if _, err := os.Lstat(target); err == nil {+ sourceInfo, sourceErr := os.Stat(source)+ targetInfo, targetErr := os.Stat(target)+ if sourceErr != nil {+ return sourceErr+ }+ if targetErr != nil {+ return targetErr+ }+ if os.SameFile(sourceInfo, targetInfo) {+ return nil+ }+ return os.RemoveAll(source)+ } else if !os.IsNotExist(err) {+ return err+ }+ info, err := os.Lstat(source)+ if err != nil {+ return err+ }+ if info.Mode()&os.ModeSymlink != 0 {+ // 将相对链接转换为绝对链接,迁移目录后仍指向同一份开发文件。+ link, err := filepath.EvalSymlinks(source)+ if err != nil {+ return err+ }+ if err = os.Symlink(link, target); err != nil {+ return err+ }+ return os.Remove(source)+ }+ if err = os.Rename(source, target); err == nil {+ return nil+ }+ // 跨文件系统时先完整复制到临时目录,发布成功后才移除来源。+ staging, err := os.MkdirTemp(filepath.Dir(target), ".appearance-migrate-")+ if err != nil {+ return err+ }+ defer os.RemoveAll(staging)+ if err = filelock.Copy(source, staging); err != nil {+ return err+ }+ if err = os.Rename(staging, target); err != nil {+ return err+ }+ return os.RemoveAll(source)+}diff --git a/kernel/model/appearance_paths_migration_test.go b/kernel/model/appearance_paths_migration_test.gonew file mode 100644index 0000000000..c5a6b64fbf--- /dev/null+++ b/kernel/model/appearance_paths_migration_test.go@@ -0,0 +1,82 @@+package model++import (+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestAppearanceMigrationMovesDirectoriesAndKeepsResiduals(t *testing.T) {+ setupAppearancePackagesTest(t)+ for _, kind := range []string{"themes", "icons"} {+ writeAppearanceTestFile(t, filepath.Join(util.AppearancePath, kind, "migrated", "assets", "file"), "legacy")+ writeAppearanceTestFile(t, filepath.Join(util.AppearancePath, kind, "custom", "file"), "superseded")+ }+ residuals := []string{+ filepath.Join(util.DataDir, "storage", "appearance-v1", "old.sypkg"),+ filepath.Join(util.DataDir, "storage", "bazaar", "themes", "migrated.json"),+ filepath.Join(util.DataDir, "storage", "bazaar", "icons", "migrated.json"),+ filepath.Join(util.ConfDir, "appearance-migration.json"),+ }+ for _, p := range residuals {+ writeAppearanceTestFile(t, p, "alpha residual")+ }+ if err := MigrateAppearancePackages(); err != nil {+ t.Fatal(err)+ }+ for _, kind := range []string{"themes", "icons"} {+ if data, err := os.ReadFile(filepath.Join(util.DataDir, kind, "migrated", "assets", "file")); err != nil || string(data) != "legacy" {+ t.Fatalf("package not migrated: %s: %q, %v", kind, data, err)+ }+ for _, name := range []string{"migrated", "custom"} {+ if _, err := os.Lstat(filepath.Join(util.AppearancePath, kind, name)); !os.IsNotExist(err) {+ t.Fatalf("source remains: %s/%s: %v", kind, name, err)+ }+ }+ if _, err := os.Stat(filepath.Join(util.DataDir, kind, "custom", "file")); !os.IsNotExist(err) {+ t.Fatalf("existing target overwritten: %v", err)+ }+ }+ for _, p := range residuals {+ if data, err := os.ReadFile(p); err != nil || string(data) != "alpha residual" {+ t.Fatalf("alpha residual changed: %s: %q, %v", p, data, err)+ }+ }+ if err := os.RemoveAll(filepath.Join(util.ThemesPath, "migrated")); err != nil {+ t.Fatal(err)+ }+ if err := MigrateAppearancePackages(); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(filepath.Join(util.ThemesPath, "migrated")); !os.IsNotExist(err) {+ t.Fatalf("deleted package reappeared: %v", err)+ }+ if _, err := os.Stat(filepath.Join(util.AppearancePath, "themes", "daylight", "theme.css")); err != nil {+ t.Fatalf("built-in theme moved: %v", err)+ }+}++func TestAppearanceMigrationPreservesDevelopmentLink(t *testing.T) {+ setupAppearancePackagesTest(t)+ external := t.TempDir()+ writeAppearanceTestFile(t, filepath.Join(external, "theme.css"), "development")+ source := filepath.Join(util.AppearancePath, "themes", "linked")+ if err := os.Symlink(external, source); err != nil {+ t.Skipf("symlinks unavailable: %v", err)+ }+ if err := MigrateAppearancePackages(); err != nil {+ t.Fatal(err)+ }+ target := filepath.Join(util.ThemesPath, "linked")+ if info, err := os.Lstat(target); err != nil || info.Mode()&os.ModeSymlink == 0 {+ t.Fatalf("development link not preserved: %v", err)+ }+ if data, err := os.ReadFile(filepath.Join(target, "theme.css")); err != nil || string(data) != "development" {+ t.Fatalf("development files lost: %q, %v", data, err)+ }+ if _, err := os.Lstat(source); !os.IsNotExist(err) {+ t.Fatalf("original link remains: %v", err)+ }+}diff --git a/kernel/model/appearance_runtime.go b/kernel/model/appearance_runtime.godeleted file mode 100644index de4704e137..0000000000--- a/kernel/model/appearance_runtime.go+++ /dev/null@@ -1,76 +0,0 @@-// SiYuan - From thought to insight, with agents-// Copyright (c) 2020-present, b3log.org-// SPDX-License-Identifier: AGPL-3.0-or-later--package model--import (- "errors"- "fmt"- "os"- "path/filepath"-- "github.com/siyuan-note/dejavu"- "github.com/siyuan-note/logging"- "github.com/siyuan-note/siyuan/kernel/bazaar"- "github.com/siyuan-note/siyuan/kernel/util"-)--type appearanceRuntimeState struct {- pending map[string]bool- blocked map[string]bool- err error-}--// newAppearanceRuntimeState 在外观锁内一次性读取恢复状态,无法认证时保留本机选择并暂缓加载第三方包。-func newAppearanceRuntimeState() *appearanceRuntimeState {- ret := &appearanceRuntimeState{pending: map[string]bool{}, blocked: map[string]bool{}}- keys, err := bazaar.PendingAppearancePackages()- if err == nil {- for _, key := range keys {- ret.pending[key] = true- }- var exists bool- exists, err = assetDownloadStateExists()- if err == nil && exists {- if Conf == nil || Conf.Repo == nil || len(Conf.Repo.Key) == 0 {- err = fmt.Errorf("appearance recovery state cannot be authenticated without repository key")- } else {- keys, err = dejavu.ReadPendingAppearancePackages(assetDownloadStatePath(), Conf.Repo.Key)- for _, key := range keys {- ret.pending[key] = true- }- }- }- }- ret.err = err- if err != nil {- logging.LogWarnf("read appearance recovery state failed: %s", err)- }- return ret-}--func (state *appearanceRuntimeState) preserveSelection(kind, name string) bool {- key := "/" + kind + "/" + name- return state.err != nil || state.pending[key] || state.blocked[key]-}--func (state *appearanceRuntimeState) validate(kind, name string) (err error) {- key := "/" + kind + "/" + name- defer func() {- if err != nil && !errors.Is(err, bazaar.ErrAppearancePackageDeleted) {- state.blocked[key] = true- }- }()- if state.err != nil {- return state.err- }- if state.pending[key] {- // 待恢复包必须仍与已记录的完整版本一致,缺少记录时不能按本地开发包放行。- if _, err = os.Stat(filepath.Join(util.DataDir, "storage", "bazaar", kind, name+".json")); err != nil {- return err- }- return bazaar.ValidateAppearancePackage(kind, name)- }- return bazaar.ValidateAppearancePackageForUse(kind, name)-}diff --git a/kernel/model/appearance_runtime_test.go b/kernel/model/appearance_runtime_test.godeleted file mode 100644index 23791a7091..0000000000--- a/kernel/model/appearance_runtime_test.go+++ /dev/null@@ -1,184 +0,0 @@-// SiYuan - From thought to insight, with agents-// Copyright (c) 2020-present, b3log.org-// SPDX-License-Identifier: AGPL-3.0-or-later--package model--import (- "bytes"- "encoding/json"- "os"- "path/filepath"- "strings"- "testing"-- "github.com/siyuan-note/dejavu"- "github.com/siyuan-note/dejavu/entity"- dejavuutil "github.com/siyuan-note/dejavu/util"- "github.com/siyuan-note/siyuan/kernel/bazaar"- "github.com/siyuan-note/siyuan/kernel/conf"- "github.com/siyuan-note/siyuan/kernel/util"-)--func setupRecordedAppearanceRuntimeTest(t *testing.T) string {- t.Helper()- setupAppearancePackagesTest(t)- Conf.Repo = conf.NewRepo()- Conf.Repo.Key = []byte("0123456789abcdef0123456789abcdef")- Conf.Appearance.ThemeLight, Conf.Appearance.Icon = "custom", "custom"- if err := bazaar.PrepareAppearancePackages(); err != nil {- t.Fatal(err)- }- return filepath.Join(util.DataDir, "storage", "bazaar", "themes", "custom.json")-}--func writeAppearanceRecoveryRuntimeTest(t *testing.T, state any) []byte {- t.Helper()- data, err := json.Marshal(state)- if err != nil {- t.Fatal(err)- }- store, err := dejavu.NewStore(t.TempDir(), Conf.Repo.Key)- if err != nil {- t.Fatal(err)- }- chunk := &entity.Chunk{ID: dejavuutil.Hash(data), Data: data}- if err = store.PutChunk(chunk); err != nil {- t.Fatal(err)- }- _, objectPath := store.AbsPath(chunk.ID)- ciphertext, err := os.ReadFile(objectPath)- if err != nil {- t.Fatal(err)- }- if err = os.WriteFile(assetDownloadStatePath(), ciphertext, 0600); err != nil {- t.Fatal(err)- }- return ciphertext-}--func TestAppearanceRuntimeManualEditRemainsLoadableAndExportable(t *testing.T) {- statePath := setupRecordedAppearanceRuntimeTest(t)- before, err := os.ReadFile(statePath)- if err != nil {- t.Fatal(err)- }- writeAppearanceTestFile(t, filepath.Join(util.ThemesPath, "custom", "theme.css"), "manually edited CSS")- writeAppearanceTestFile(t, filepath.Join(util.ThemesPath, "custom", "theme.js"), "manually added script")- if err = bazaar.ValidateAppearancePackage("themes", "custom"); err == nil {- t.Fatal("strict snapshot validation accepted an unrecorded change")- }- refreshAppearanceConfig()- if Conf.Appearance.ThemeLight != "custom" || !Conf.Appearance.ThemeJS || !containTheme("custom", Conf.Appearance.LightThemes) {- t.Fatal("manual edit disabled the current theme")- }- destination := t.TempDir()- if err = copyExportAppearance(destination, "custom", "custom"); err != nil {- t.Fatal(err)- }- data, err := os.ReadFile(filepath.Join(destination, "appearance", "themes", "custom", "theme.css"))- if err != nil || string(data) != "manually edited CSS" {- t.Fatalf("manual edit was not exported: %s %v", data, err)- }- after, _ := os.ReadFile(statePath)- if !bytes.Equal(before, after) {- t.Fatal("runtime loading or export rewrote synchronization state")- }-}--func TestAppearanceRuntimePendingPreservesSelectionAndStrictness(t *testing.T) {- statePath := setupRecordedAppearanceRuntimeTest(t)- before, _ := os.ReadFile(statePath)- writeAppearanceTestFile(t, filepath.Join(util.ThemesPath, "custom", "theme.css"), "unrecorded pending contents")- file := &entity.File{ID: strings.Repeat("1", 40), Path: "/themes/custom/theme.css", Chunks: []string{strings.Repeat("2", 40)}}- state := map[string]any{"version": 1, "scope": "runtime-test", "deferred": map[string]*entity.File{}, "pending": map[string]any{- "index": &entity.Index{}, "base": &entity.Index{}, "deferred": map[string]*entity.File{},- "before": map[string]*entity.File{}, "upserts": []*entity.File{file},- }}- writeAppearanceRecoveryRuntimeTest(t, state)- refreshAppearanceConfig()- if Conf.Appearance.ThemeLight != "custom" || containTheme("custom", Conf.Appearance.LightThemes) || Conf.Appearance.ThemeJS {- t.Fatal("pending package was loaded or its local selection was discarded")- }- if !containIcon("custom", Conf.Appearance.Icons) {- t.Fatal("unrelated package was disabled by a pending theme")- }- if err := copyExportAppearance(t.TempDir(), "custom", "custom"); err == nil {- t.Fatal("pending unverified package was exported")- }- after, _ := os.ReadFile(statePath)- if !bytes.Equal(before, after) {- t.Fatal("pending package state was rewritten")- }- delete(state, "pending")- writeAppearanceRecoveryRuntimeTest(t, state)- refreshAppearanceConfig()- if Conf.Appearance.ThemeLight != "custom" || !containTheme("custom", Conf.Appearance.LightThemes) {- t.Fatal("selection did not become available after recovery completed")- }-}--func TestAppearanceRuntimeUnknownRecoveryPreservesSelection(t *testing.T) {- setupRecordedAppearanceRuntimeTest(t)- ciphertext := writeAppearanceRecoveryRuntimeTest(t, map[string]any{"version": 99, "scope": "runtime-test", "deferred": map[string]any{}})- refreshAppearanceConfig()- if Conf.Appearance.ThemeLight != "custom" || Conf.Appearance.Icon != "custom" ||- containTheme("custom", Conf.Appearance.LightThemes) || containIcon("custom", Conf.Appearance.Icons) {- t.Fatal("unknown recovery state was accepted or discarded the local selection")- }- if !containTheme("daylight", Conf.Appearance.LightThemes) || !containIcon("litheness", Conf.Appearance.Icons) {- t.Fatal("unknown recovery state disabled built-in resources")- }- after, _ := os.ReadFile(assetDownloadStatePath())- if !bytes.Equal(ciphertext, after) {- t.Fatal("unknown recovery state was modified")- }-}--func TestAppearanceRuntimeLegacyDeferredIsUnavailable(t *testing.T) {- setupAppearancePackagesTest(t)- Conf.Repo = conf.NewRepo()- Conf.Repo.Key = []byte("0123456789abcdef0123456789abcdef")- Conf.Appearance.ThemeLight = "custom"- file := &entity.File{ID: strings.Repeat("1", 40), Path: "/themes/custom/assets/font.woff2", Chunks: []string{strings.Repeat("2", 40)}}- state := map[string]any{"version": 1, "scope": "runtime-test", "deferred": map[string]*entity.File{file.Path: file}}- writeAppearanceRecoveryRuntimeTest(t, state)- refreshAppearanceConfig()- if Conf.Appearance.ThemeLight != "custom" || containTheme("custom", Conf.Appearance.LightThemes) {- t.Fatal("legacy theme with deferred resources was loaded or its selection discarded")- }- state["deferred"] = map[string]*entity.File{}- writeAppearanceRecoveryRuntimeTest(t, state)- refreshAppearanceConfig()- if Conf.Appearance.ThemeLight != "custom" || !containTheme("custom", Conf.Appearance.LightThemes) {- t.Fatal("legacy theme did not become available after resources completed")- }-}--func TestAppearanceRuntimeLocalPendingAndDeletedFallback(t *testing.T) {- statePath := setupRecordedAppearanceRuntimeTest(t)- state, err := os.ReadFile(statePath)- if err != nil {- t.Fatal(err)- }- operation := map[string]any{"version": 1, "kind": "themes", "name": "custom", "state": json.RawMessage(state)}- data, err := json.Marshal(operation)- if err != nil {- t.Fatal(err)- }- opPath := filepath.Join(util.DataDir, ".siyuan-appearance-ops", "package-runtime", "operation.json")- writeAppearanceTestFile(t, opPath, string(data))- writeAppearanceTestFile(t, filepath.Join(util.ThemesPath, "custom", "theme.css"), "pending local replacement")- refreshAppearanceConfig()- if Conf.Appearance.ThemeLight != "custom" || containTheme("custom", Conf.Appearance.LightThemes) {- t.Fatal("pending local replacement was loaded or its selection discarded")- }- if err = os.Remove(opPath); err != nil {- t.Fatal(err)- }- writeAppearanceTestFile(t, statePath, `{"version":1,"deleted":true,"files":{}}`)- refreshAppearanceConfig()- if Conf.Appearance.ThemeLight != "daylight" || containTheme("custom", Conf.Appearance.LightThemes) {- t.Fatal("deleted package with residual files did not fall back permanently")- }-}diff --git a/kernel/model/appearance_sync.go b/kernel/model/appearance_sync.goindex 2c43f4f193..3cccf978ac 100644--- a/kernel/model/appearance_sync.go+++ b/kernel/model/appearance_sync.go@@ -1,18 +1,16 @@package modelimport (- "path/filepath""sort""strings""time"- ignore "github.com/sabhiram/go-gitignore""github.com/siyuan-note/dejavu""github.com/siyuan-note/siyuan/kernel/bazaar""github.com/siyuan-note/siyuan/kernel/util")-// appearanceChangedPackages 将包内容和状态文件的变更归并为需要刷新的包名。+// appearanceChangedPackages 将包文件的变更归并为需要刷新的包名。func appearanceChangedPackages(result *dejavu.MergeResult) (themes, icons []string) {changed := map[string]map[string]bool{"themes": {}, "icons": {}}paths := make([]string, 0, len(result.Upserts)+len(result.Removes))@@ -26,9 +24,6 @@ func appearanceChangedPackages(result *dejavu.MergeResult) (themes, icons []striparts := strings.Split(strings.TrimPrefix(filePath, "/"), "/")if len(parts) >= 3 && (parts[0] == "themes" || parts[0] == "icons") {changed[parts[0]][parts[1]] = true- } else if len(parts) == 4 && parts[0] == "storage" && parts[1] == "bazaar" &&- (parts[2] == "themes" || parts[2] == "icons") && strings.HasSuffix(parts[3], ".json") {- changed[parts[2]][strings.TrimSuffix(parts[3], ".json")] = true}}for name := range changed["themes"] {@@ -42,7 +37,7 @@ func appearanceChangedPackages(result *dejavu.MergeResult) (themes, icons []strireturn}-// refreshAppearancePackages 只在整包发布之后重建本机外观列表,并通知各前端清除资源缓存。+// refreshAppearancePackages 在同步或快照恢复之后重建本机外观列表,并通知各前端清除资源缓存。func refreshAppearancePackages(themes, icons []string) {if len(themes)+len(icons) == 0 {return@@ -61,27 +56,3 @@ func refreshAppearancePackages(themes, icons []string) {"revision": time.Now().UTC().Format("20060102150405.000000000"),})}--// appearanceStatePayloadPath 为忽略规则提供与包状态对应的目录路径。-func appearanceStatePayloadPath(rel string) string {- parts := strings.Split(strings.TrimPrefix(filepath.ToSlash(rel), "/"), "/")- if len(parts) == 4 && parts[0] == "storage" && parts[1] == "bazaar" &&- (parts[2] == "themes" || parts[2] == "icons") && strings.HasSuffix(parts[3], ".json") {- return parts[2] + "/" + strings.TrimSuffix(parts[3], ".json") + "/"- }- return ""-}--func prepareAppearancePackages() error {- if err := util.EnsureAppearanceSyncIsolation(); err != nil {- return err- }- lines, err := loadAppearanceSyncIgnoreLines()- if err != nil {- return err- }- matcher := ignore.CompileIgnoreLines(lines...)- return bazaar.PrepareAppearancePackages(func(kind, name string) bool {- return matcher.MatchesPath(kind + "/" + name + "/")- })-}diff --git a/kernel/model/appearance_sync_test.go b/kernel/model/appearance_sync_test.goindex 2cce60f07f..116bd743c8 100644--- a/kernel/model/appearance_sync_test.go+++ b/kernel/model/appearance_sync_test.go@@ -1,87 +1,17 @@package modelimport (- "os"- "path/filepath""reflect"- "strings""testing""github.com/siyuan-note/dejavu""github.com/siyuan-note/dejavu/entity"- "github.com/siyuan-note/siyuan/kernel/bazaar"- "github.com/siyuan-note/siyuan/kernel/util")-func TestAppearanceIgnorePairsState(t *testing.T) {- for _, rule := range []string{"/themes/example/", "/themes/", "/themes/example/theme.css"} {- t.Run(rule, func(t *testing.T) {- setupAppearanceMigrationTest(t)- writeMigrationTestFile(t, util.DataDir, ".siyuan/syncignore", rule+"\n")- statePath := filepath.Join(util.DataDir, "storage", "bazaar", "themes", "example.json")- ignored, err := syncPathFilter(util.DataDir, nil, statePath)- if err != nil {- t.Fatal(err)- }- if want := rule != "/themes/example/theme.css"; ignored != want {- t.Fatalf("state excluded=%t, want %t", ignored, want)- }- })- }-}--func TestAppearanceIgnoreLinkedPackageState(t *testing.T) {- setupAppearanceMigrationTest(t)- if err := os.MkdirAll(util.ThemesPath, 0755); err != nil {- t.Fatal(err)- }- if err := os.Symlink(t.TempDir(), filepath.Join(util.ThemesPath, "example")); err != nil {- t.Skipf("symlinks unavailable: %s", err)- }- for _, name := range []string{"themes/example/theme.css", "storage/bazaar/themes/example.json"} {- ignored, err := syncPathFilter(util.DataDir, nil, filepath.Join(util.DataDir, filepath.FromSlash(name)))- if err != nil || !ignored {- t.Fatalf("linked package component %s: ignored=%t, error=%v", name, ignored, err)- }- }-}-func TestAppearanceChangedPackages(t *testing.T) {- result := &dejavu.MergeResult{Upserts: []*entity.File{{Path: "/themes/example/theme.css"}, {Path: "/themes/example/assets/font.woff"}, {Path: "/storage/bazaar/icons/other.json"}, {Path: "/storage/bazaar.json"}, {Path: "/storage/appearance-v1/themes/shared/version.sypkg"}}, Removes: []*entity.File{{Path: "/icons/other/icon.js"}, {Path: "/storage/bazaar/themes/deleted.json"}, {Path: "/storage/appearance-v1/icons/shared/version.sypkg"}}}+ result := &dejavu.MergeResult{Upserts: []*entity.File{{Path: "/themes/example/theme.css"}, {Path: "/themes/example/assets/font.woff"}, {Path: "/storage/bazaar/icons/other.json"}, {Path: "/storage/bazaar.json"}, {Path: "/storage/appearance-v1/themes/shared/version.sypkg"}}, Removes: []*entity.File{{Path: "/icons/other/icon.js"}, {Path: "/themes/deleted/theme.css"}, {Path: "/storage/bazaar/themes/old.json"}, {Path: "/storage/appearance-v1/icons/shared/version.sypkg"}}}themes, icons := appearanceChangedPackages(result)if !reflect.DeepEqual(themes, []string{"deleted", "example"}) || !reflect.DeepEqual(icons, []string{"other"}) {t.Fatalf("unexpected refresh: themes=%v icons=%v", themes, icons)}}--func TestAppearancePrepareSeparatesUserIgnoreFromIsolation(t *testing.T) {- setupAppearanceMigrationTest(t)- writeMigrationTestFile(t, util.DataDir, ".siyuan/syncignore", "/icons/\n/themes/local/\n")- for _, name := range []string{"shared", "local"} {- writeMigrationTestFile(t, util.ThemesPath, name+"/theme.css", "local css")- }- writeMigrationTestFile(t, util.IconsPath, "local/icon.js", "local icon")- if err := prepareAppearancePackages(); err != nil {- t.Fatal(err)- }- if err := bazaar.ValidateAppearancePackage("themes", "shared"); err != nil {- t.Fatal(err)- }- if _, err := os.Stat(filepath.Join(util.DataDir, "storage", "bazaar", "themes", "shared.json")); err != nil {- t.Fatalf("isolation incorrectly disabled appearance synchronization: %v", err)- }- for _, name := range []string{"themes/local.json", "icons/local.json"} {- if _, err := os.Stat(filepath.Join(util.DataDir, "storage", "bazaar", filepath.FromSlash(name))); !os.IsNotExist(err) {- t.Fatalf("user-ignored package received state: %s: %v", name, err)- }- }- userLines, err := loadAppearanceSyncIgnoreLines()- if err != nil {- t.Fatal(err)- }- for _, line := range userLines {- if strings.HasPrefix(line, "# siyuan-appearance-isolation:") || line == "/themes/" || line == "/storage/bazaar/themes/" {- t.Fatalf("managed rule remained in user intent: %s", line)- }- }-}diff --git a/kernel/model/repository.go b/kernel/model/repository.goindex 6654285d58..9b9c8254a8 100644--- a/kernel/model/repository.go+++ b/kernel/model/repository.go@@ -1356,7 +1356,7 @@ func checkoutRepo(id string) (err error) {CloseWatchEmojis()defer WatchEmojis()- // 整包恢复期间暂停监听,完成后重新绑定实际目录。+ // 快照恢复期间暂停监听,完成后重新绑定实际目录。CloseWatchThemes()defer WatchThemes()@@ -1373,9 +1373,6 @@ func checkoutRepo(id string) (err error) {if err = processAssetDownloadRecovery(repo, true); err != nil {return}- if err = prepareAppearancePackages(); err != nil {- return- }_, err = repo.Index("Backup before checkout", false, map[string]any{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBarAndProgress})if err != nil {logging.LogErrorf("index repository failed: %s", err)@@ -1819,9 +1816,6 @@ func CreateRepoSnapshot(memo string) (id string, created bool, err error) {if err = processAssetDownloadRecovery(repo, true); err != nil {return}- if err = prepareAppearancePackages(); err != nil {- return- }index, created, err := repo.IndexWithResult(memo, true, map[string]any{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBarAndProgress,dejavu.CtxAssetDownloadsAllowed: checkAssetDownloadAccess() == nil,@@ -2925,9 +2919,6 @@ func indexRepoBeforeCloudSync(repo *dejavu.Repo) (beforeIndex, afterIndex *entit}checkChunks := true- if err = prepareAppearancePackages(); err != nil {- return- }if util.IsMobileContainer() {// 因为移动端私有数据空间不会存在外部操作导致分块损坏的情况,所以不需要检查分块以提升性能 https://github.com/siyuan-note/siyuan/issues/13216checkChunks = false@@ -3030,18 +3021,12 @@ func newRepositoryWithAssetSourceLocked() (ret *dejavu.Repo, err error) {if err != nil {return nil, err}- appearanceIgnoreLines, err := loadAppearanceSyncIgnoreLines()- if err != nil {- return nil, err- }dataDir := util.DataDirret, err = dejavu.NewRepoWithOptions(dejavu.Options{DataPath: util.DataDir, RepoPath: util.RepoDir, HistoryPath: util.HistoryDir, TempPath: util.TempDir,DeviceID: Conf.System.ID, DeviceName: Conf.System.Name, DeviceOS: Conf.System.OS,AESKey: Conf.Repo.Key, IgnoreLines: ignoreLines, Cloud: cloudRepo,- EnableAppearanceSync: true, AppearanceIgnoreLines: appearanceIgnoreLines,- BeforeAppearanceApply: util.EnsureAppearanceSyncIsolation,- IgnoreRulePath: syncIgnoreRulePath, HiddenDirectoryNames: []string{".siyuan"},+ IgnoreRulePath: syncIgnoreRulePath, HiddenDirectoryNames: []string{".siyuan"},PathFilter: func(info os.FileInfo, absPath string) (bool, error) {return syncPathFilter(dataDir, info, absPath)},diff --git a/kernel/model/sync.go b/kernel/model/sync.goindex 49f71f2030..d249022e06 100644--- a/kernel/model/sync.go+++ b/kernel/model/sync.go@@ -994,14 +994,6 @@ func bootSyncRepoWithDNSRetry() (err error) {}func loadSyncIgnoreLines() (ret []string, err error) {- return readSyncIgnoreLines(false)-}--func loadAppearanceSyncIgnoreLines() ([]string, error) {- return readSyncIgnoreLines(true)-}--func readSyncIgnoreLines(forAppearance bool) (ret []string, err error) {// 忽略旧版同步配置,读取用户规则失败时仍需保留此规则。defer func() {ret = append(ret, "/.siyuan/conf.json")@@ -1028,12 +1020,6 @@ func readSyncIgnoreLines(forAppearance bool) (ret []string, err error) {dataStr := string(data)dataStr = strings.ReplaceAll(dataStr, "\r\n", "\n")ret = strings.Split(dataStr, "\n")- if forAppearance {- ret, err = util.AppearanceUserSyncIgnoreLines(ret)- if err != nil {- return nil, err- }- }// 忽略用户指南for _, id := range userGuideIDs {diff --git a/kernel/model/sync_ignore.go b/kernel/model/sync_ignore.goindex 2069ec7c0b..e471978824 100644--- a/kernel/model/sync_ignore.go+++ b/kernel/model/sync_ignore.go@@ -127,18 +127,6 @@ func syncPathFilter(dataDir string, info os.FileInfo, absPath string) (bool, err}return true, nil}- if payload := appearanceStatePayloadPath(rel); payload != "" {- if stat, err := os.Lstat(filepath.Join(dataDir, filepath.FromSlash(payload))); err == nil && stat.Mode()&os.ModeSymlink != 0 {- return true, nil- }- _, matcher, err := getSyncIgnoreRules()- if err != nil {- return false, err- }- if matcher.MatchesPath(payload) {- return true, nil- }- }if info != nil && info.IsDir() {if info.Name() == "filesys_status_check" {return true, filepath.SkipDirdiff --git a/kernel/server/appearance_path.go b/kernel/server/appearance_path.goindex 2879d1b8e1..c8abf3cadd 100644--- a/kernel/server/appearance_path.go+++ b/kernel/server/appearance_path.go@@ -26,16 +26,6 @@ import ("github.com/siyuan-note/siyuan/kernel/util")-func isThirdPartyAppearanceRequest(requestPath string) bool {- parts := strings.SplitN(requestPath, "/", 3)- if len(parts) < 2 {- return false- }- parts[0] = strings.ToLower(parts[0])- return (parts[0] == "themes" && !strings.EqualFold(parts[1], "daylight") && !strings.EqualFold(parts[1], "midnight")) ||- (parts[0] == "icons" && !strings.EqualFold(parts[1], "litheness"))-}-// resolveAppearanceFile 在读取前限定真实路径,仅允许主题和图标包目录链接到外部目录。func resolveAppearanceFile(root, requestPath string) (string, int) {filePath, status := resolveAppearanceFilePath(root, requestPath)diff --git a/kernel/server/serve.go b/kernel/server/serve.goindex b7e32edb87..1cc84f510b 100644--- a/kernel/server/serve.go+++ b/kernel/server/serve.go@@ -42,7 +42,6 @@ import ("github.com/gin-gonic/gin""github.com/mssola/useragent""github.com/olahol/melody"- "github.com/siyuan-note/filelock""github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/agent""github.com/siyuan-note/siyuan/kernel/api"@@ -793,11 +792,6 @@ func serveAppearance(ginServer *gin.Engine) {appearancePath := util.BuiltInAppearancePath()siyuan.GET("/appearance/*filepath", func(c *gin.Context) {requestPath := strings.TrimPrefix(c.Request.URL.Path, "/appearance/")- if isThirdPartyAppearanceRequest(requestPath) {- lockPath := filepath.Join(util.DataDir, ".siyuan-appearance")- filelock.Lock(lockPath)- defer filelock.Unlock(lockPath)- }filePath, status := resolveAppearanceFile(appearancePath, requestPath)if status != 0 {c.Status(status)diff --git a/kernel/util/appearance_ignore_migration.go b/kernel/util/appearance_ignore_migration.gonew file mode 100644index 0000000000..cab110f553--- /dev/null+++ b/kernel/util/appearance_ignore_migration.go@@ -0,0 +1,67 @@+package util++import (+ "bytes"+ "errors"+ "os"+ "path/filepath"+ "strings"++ "github.com/88250/gulu"+ "github.com/siyuan-note/filelock"+)++// MigrateAppearanceSyncIgnore 移除旧版生成的隔离块,保留用户规则、换行和编码标记;没有隔离块时不写文件。+func MigrateAppearanceSyncIgnore() error {+ rulePath := filepath.Join(DataDir, ".siyuan", "syncignore")+ filelock.Lock(rulePath)+ defer filelock.Unlock(rulePath)+ info, err := os.Lstat(rulePath)+ if os.IsNotExist(err) {+ return nil+ }+ if err != nil {+ return err+ }+ if !info.Mode().IsRegular() {+ return errors.New("appearance migration requires a regular syncignore file")+ }+ original, err := os.ReadFile(rulePath)+ if err != nil {+ return err+ }+ updated, err := removeAppearanceIsolationBlock(original)+ if err != nil || bytes.Equal(original, updated) {+ return err+ }+ return gulu.File.WriteFileSafer(rulePath, updated, info.Mode().Perm())+}++func removeAppearanceIsolationBlock(original []byte) ([]byte, error) {+ const marker = "# siyuan-appearance-isolation:"+ block := []string{marker + "v1:begin", "/themes/", "/icons/", "/storage/bazaar/themes/", "/storage/bazaar/icons/", marker + "v1:end"}+ bom := []byte("\xef\xbb\xbf")+ data := bytes.TrimPrefix(original, bom)+ lines := bytes.SplitAfter(data, []byte("\n"))+ var ret []byte+ if bytes.HasPrefix(original, bom) {+ ret = append(ret, bom...)+ }+ for i := 0; i < len(lines); i++ {+ line := strings.TrimSuffix(strings.TrimSuffix(string(lines[i]), "\n"), "\r")+ if !strings.HasPrefix(line, marker) {+ ret = append(ret, lines[i]...)+ continue+ }+ if len(lines)-i < len(block) {+ return nil, errors.New("incomplete appearance sync isolation block")+ }+ for j, expected := range block {+ if strings.TrimSuffix(strings.TrimSuffix(string(lines[i+j]), "\n"), "\r") != expected {+ return nil, errors.New("unknown or modified appearance sync isolation block")+ }+ }+ i += len(block) - 1+ }+ return ret, nil+}diff --git a/kernel/util/appearance_ignore_migration_test.go b/kernel/util/appearance_ignore_migration_test.gonew file mode 100644index 0000000000..012a429e85--- /dev/null+++ b/kernel/util/appearance_ignore_migration_test.go@@ -0,0 +1,49 @@+package util++import (+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func TestAppearanceIgnoreMigration(t *testing.T) {+ block := "# siyuan-appearance-isolation:v1:begin\n/themes/\n/icons/\n/storage/bazaar/themes/\n/storage/bazaar/icons/\n# siyuan-appearance-isolation:v1:end\n"+ for _, newline := range []string{"\n", "\r\n"} {+ for _, bom := range []string{"", "\ufeff"} {+ t.Run(newline+bom, func(t *testing.T) {+ old := DataDir+ DataDir = t.TempDir()+ t.Cleanup(func() { DataDir = old })+ p := filepath.Join(DataDir, ".siyuan", "syncignore")+ if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil {+ t.Fatal(err)+ }+ original := bom + strings.ReplaceAll(block+"/themes/\n# custom\n"+block+"!/icons/custom/", "\n", newline)+ want := bom + strings.ReplaceAll("/themes/\n# custom\n!/icons/custom/", "\n", newline)+ if err := os.WriteFile(p, []byte(original), 0644); err != nil {+ t.Fatal(err)+ }+ if err := MigrateAppearanceSyncIgnore(); err != nil {+ t.Fatal(err)+ }+ if got, err := os.ReadFile(p); err != nil || string(got) != want {+ t.Fatalf("user rules changed: %q, %v", got, err)+ }+ before, _ := os.Stat(p)+ if err := MigrateAppearanceSyncIgnore(); err != nil {+ t.Fatal(err)+ }+ after, _ := os.Stat(p)+ if !before.ModTime().Equal(after.ModTime()) {+ t.Fatal("completed migration rewrote syncignore")+ }+ })+ }+ }+ for _, bad := range []string{strings.ReplaceAll(block, "v1", "v2"), strings.ReplaceAll(block, "/themes/", "/custom/"), "# siyuan-appearance-isolation:v1:begin\n"} {+ if _, err := removeAppearanceIsolationBlock([]byte(bad)); err == nil {+ t.Fatal("modified block silently removed")+ }+ }+}diff --git a/kernel/util/appearance_sync_isolation.go b/kernel/util/appearance_sync_isolation.godeleted file mode 100644index 39eb7607bc..0000000000--- a/kernel/util/appearance_sync_isolation.go+++ /dev/null@@ -1,306 +0,0 @@-package util--import (- "bytes"- "encoding/json"- "errors"- "fmt"- "io"- "os"- "path/filepath"- "runtime"- "strings"- "time"-- "github.com/siyuan-note/filelock"-)--const appearanceIsolationMarker = "# siyuan-appearance-isolation:"-const appearanceIsolationClockName = ".appearance-syncignore-clock-v1"-const maxAppearanceIsolationSecond int64 = (1<<63 - 1) / 1000--type appearanceIsolationClock struct {- Version int `json:"version"`- Modified int64 `json:"modified"`-}--var appearanceIsolationBlock = []string{- appearanceIsolationMarker + "v1:begin",- "/themes/",- "/icons/",- "/storage/bazaar/themes/",- "/storage/bazaar/icons/",- appearanceIsolationMarker + "v1:end",-}--// EnsureAppearanceSyncIsolation 在生成本地外观目录前持久化旧引擎可识别的隔离规则;调用方不能持有外观锁。-func EnsureAppearanceSyncIsolation() error {- rulePath := filepath.Join(DataDir, ".siyuan", "syncignore")- filelock.Lock(rulePath)- defer filelock.Unlock(rulePath)-- original, info, err := readAppearanceIsolationRules(rulePath)- if err != nil {- return err- }- updated, err := updateAppearanceIsolationRules(original)- if err != nil {- return err- }- if bytes.Equal(original, updated) {- if _, err = reserveAppearanceIsolationTime(rulePath, info, false); err != nil {- return err- }- return syncAppearanceIsolationDirectory(filepath.Dir(rulePath))- }- if err = os.MkdirAll(filepath.Dir(rulePath), 0755); err != nil {- return err- }- if err = syncAppearanceIsolationDirectory(filepath.Dir(filepath.Dir(rulePath))); err != nil {- return err- }- if err = writeAppearanceIsolationRules(rulePath, original, updated, info); err != nil {- return err- }- return nil-}--// AppearanceUserSyncIgnoreLines 仅移除完整的受管规则,保留用户自行编写的同名规则及其顺序。-func AppearanceUserSyncIgnoreLines(lines []string) ([]string, error) {- ranges, err := appearanceIsolationRanges(lines)- if err != nil {- return nil, err- }- ret := make([]string, 0, len(lines))- start := 0- for _, block := range ranges {- ret = append(ret, lines[start:block[0]]...)- start = block[1]- }- return append(ret, lines[start:]...), nil-}--func appearanceIsolationRanges(lines []string) ([][2]int, error) {- var ret [][2]int- for i := 0; i < len(lines); i++ {- line := strings.TrimSuffix(lines[i], "\r")- if i == 0 {- line = strings.TrimPrefix(line, "\ufeff")- }- if !strings.HasPrefix(line, appearanceIsolationMarker) {- continue- }- if line != appearanceIsolationBlock[0] || len(lines)-i < len(appearanceIsolationBlock) {- return nil, errors.New("unsupported or incomplete appearance sync isolation block")- }- for j, expected := range appearanceIsolationBlock {- actual := strings.TrimSuffix(lines[i+j], "\r")- if i+j == 0 {- actual = strings.TrimPrefix(actual, "\ufeff")- }- if actual != expected {- return nil, fmt.Errorf("invalid appearance sync isolation block at line %d", i+j+1)- }- }- ret = append(ret, [2]int{i, i + len(appearanceIsolationBlock)})- i += len(appearanceIsolationBlock) - 1- }- return ret, nil-}--func updateAppearanceIsolationRules(original []byte) ([]byte, error) {- rawLines := bytes.SplitAfter(original, []byte("\n"))- lines := make([]string, len(rawLines))- for i, raw := range rawLines {- lines[i] = string(bytes.TrimSuffix(raw, []byte("\n")))- }- ranges, err := appearanceIsolationRanges(lines)- if err != nil {- return nil, err- }- var updated []byte- start := 0- for _, block := range ranges {- updated = append(updated, bytes.Join(rawLines[start:block[0]], nil)...)- start = block[1]- }- updated = append(updated, bytes.Join(rawLines[start:], nil)...)- if bytes.HasPrefix(original, []byte("\xef\xbb\xbf")) && !bytes.HasPrefix(updated, []byte("\xef\xbb\xbf")) {- updated = append([]byte("\xef\xbb\xbf"), updated...)- }- newline := "\n"- if bytes.Contains(original, []byte("\r\n")) {- newline = "\r\n"- }- if len(updated) != 0 && updated[len(updated)-1] != '\n' {- updated = append(updated, newline...)- }- updated = append(updated, strings.Join(appearanceIsolationBlock, newline)...)- return append(updated, newline...), nil-}--func readAppearanceIsolationRules(rulePath string) ([]byte, os.FileInfo, error) {- info, err := os.Lstat(rulePath)- if errors.Is(err, os.ErrNotExist) {- return nil, nil, nil- }- if err != nil {- return nil, nil, err- }- if !info.Mode().IsRegular() {- return nil, nil, errors.New("appearance sync isolation requires a regular syncignore file")- }- data, err := os.ReadFile(rulePath)- return data, info, err-}--func writeAppearanceIsolationRules(rulePath string, original, updated []byte, previous os.FileInfo) error {- modified, err := reserveAppearanceIsolationTime(rulePath, previous, true)- if err != nil {- return err- }- temp, err := os.CreateTemp(filepath.Dir(rulePath), ".appearance-syncignore-*.tmp")- if err != nil {- return err- }- tempPath := temp.Name()- defer os.Remove(tempPath)- defer temp.Close()- if _, err = temp.Write(updated); err != nil {- return err- }- mode := os.FileMode(0644)- if previous != nil {- mode = previous.Mode().Perm()- }- if err = temp.Chmod(mode); err != nil {- return err- }- if err = os.Chtimes(tempPath, modified, modified); err != nil {- return err- }- if err = temp.Sync(); err != nil {- return err- }- if err = temp.Close(); err != nil {- return err- }- current, info, err := readAppearanceIsolationRules(rulePath)- if err != nil {- return err- }- if !bytes.Equal(current, original) || (previous == nil) != (info == nil) ||- (previous != nil && (!os.SameFile(previous, info) || !previous.ModTime().Equal(info.ModTime()))) {- return errors.New("syncignore changed while preparing appearance isolation")- }- if err = os.Rename(tempPath, rulePath); err != nil {- return err- }- return syncAppearanceIsolationDirectory(filepath.Dir(rulePath))-}--// reserveAppearanceIsolationTime 先持久预留秒数,规则快照还原或时钟回退后也不会复用本机已发布的旧文件标识。-func reserveAppearanceIsolationTime(rulePath string, previous os.FileInfo, advance bool) (time.Time, error) {- clockPath := filepath.Join(filepath.Dir(rulePath), appearanceIsolationClockName)- data, info, err := readAppearanceIsolationRules(clockPath)- if err != nil {- return time.Time{}, err- }- clock := appearanceIsolationClock{Version: 1}- if info != nil {- clock.Version = 0- decoder := json.NewDecoder(bytes.NewReader(data))- start, tokenErr := decoder.Token()- if tokenErr != nil || start != json.Delim('{') {- return time.Time{}, errors.New("invalid appearance isolation clock")- }- seen := map[string]bool{}- for decoder.More() {- token, fieldErr := decoder.Token()- name, ok := token.(string)- if fieldErr != nil || !ok || seen[name] {- return time.Time{}, errors.New("invalid appearance isolation clock fields")- }- seen[name] = true- switch name {- case "version":- err = decoder.Decode(&clock.Version)- case "modified":- err = decoder.Decode(&clock.Modified)- default:- return time.Time{}, errors.New("unsupported appearance isolation clock field")- }- if err != nil {- return time.Time{}, err- }- }- end, tokenErr := decoder.Token()- if tokenErr != nil || end != json.Delim('}') || !seen["version"] || !seen["modified"] ||- clock.Version != 1 || clock.Modified <= 0 || clock.Modified >= maxAppearanceIsolationSecond {- return time.Time{}, errors.New("unsupported or invalid appearance isolation clock")- }- if err = decoder.Decode(new(interface{})); err != io.EOF {- return time.Time{}, errors.New("invalid trailing appearance isolation clock data")- }- }- seconds := clock.Modified- if previous != nil && previous.ModTime().Unix() > seconds {- seconds = previous.ModTime().Unix()- }- if advance || info == nil {- if now := time.Now().Unix(); now > seconds {- seconds = now- }- }- if advance {- seconds++- }- if seconds <= 0 || seconds >= maxAppearanceIsolationSecond {- return time.Time{}, errors.New("invalid appearance isolation timestamp")- }- if info != nil && seconds == clock.Modified {- return time.Unix(seconds, 0), nil- }- clock.Modified = seconds- data, err = json.Marshal(clock)- if err != nil {- return time.Time{}, err- }- temp, err := os.CreateTemp(filepath.Dir(rulePath), ".appearance-clock-*.tmp")- if err != nil {- return time.Time{}, err- }- tempPath := temp.Name()- defer os.Remove(tempPath)- defer temp.Close()- if _, err = temp.Write(data); err != nil {- return time.Time{}, err- }- if err = temp.Sync(); err != nil {- return time.Time{}, err- }- if err = temp.Close(); err != nil {- return time.Time{}, err- }- if err = os.Rename(tempPath, clockPath); err != nil {- return time.Time{}, err- }- if err = syncAppearanceIsolationDirectory(filepath.Dir(rulePath)); err != nil {- return time.Time{}, err- }- return time.Unix(seconds, 0), nil-}--func syncAppearanceIsolationDirectory(directory string) error {- if runtime.GOOS != "windows" {- dir, openErr := os.Open(directory)- if openErr != nil {- return openErr- }- defer dir.Close()- if err := dir.Sync(); err != nil {- return err- }- }- return nil-}diff --git a/kernel/util/appearance_sync_isolation_test.go b/kernel/util/appearance_sync_isolation_test.godeleted file mode 100644index 2858bc5d6c..0000000000--- a/kernel/util/appearance_sync_isolation_test.go+++ /dev/null@@ -1,368 +0,0 @@-package util--import (- "bytes"- "encoding/json"- "os"- "path/filepath"- "reflect"- "strings"- "testing"- "time"-- ignore "github.com/sabhiram/go-gitignore"- "github.com/siyuan-note/dejavu"- "github.com/siyuan-note/filelock"-)--func setupAppearanceIsolationTest(t *testing.T) string {- t.Helper()- oldData := DataDir- DataDir = t.TempDir()- t.Cleanup(func() { DataDir = oldData })- return filepath.Join(DataDir, ".siyuan", "syncignore")-}--func writeAppearanceIsolationTestRules(t *testing.T, name string, data []byte) {- t.Helper()- if err := os.MkdirAll(filepath.Dir(name), 0755); err != nil {- t.Fatal(err)- }- if err := os.WriteFile(name, data, 0644); err != nil {- t.Fatal(err)- }-}--func readAppearanceIsolationTestRules(t *testing.T, name string) []byte {- t.Helper()- data, err := os.ReadFile(name)- if err != nil {- t.Fatal(err)- }- return data-}--func TestAppearanceSyncIsolationPreservesRules(t *testing.T) {- for _, original := range []string{- "", "/themes/private/\n/assets/private/\n!/themes/custom/**",- "\ufeff# existing rules\r\n/themes/private/\r\n/icons/\r\n!/themes/custom/**\r\n",- } {- t.Run(strings.ReplaceAll(original, "/", "_"), func(t *testing.T) {- rulePath := setupAppearanceIsolationTest(t)- writeAppearanceIsolationTestRules(t, rulePath, []byte(original))- previous := time.Now().Add(time.Hour).Truncate(time.Second)- if err := os.Chtimes(rulePath, previous, previous); err != nil {- t.Fatal(err)- }- if err := EnsureAppearanceSyncIsolation(); err != nil {- t.Fatal(err)- }- data := readAppearanceIsolationTestRules(t, rulePath)- if !bytes.HasPrefix(data, []byte(original)) {- t.Fatalf("user bytes changed: %q", data)- }- lines := strings.Split(strings.ReplaceAll(string(data), "\r\n", "\n"), "\n")- matcher := ignore.CompileIgnoreLines(lines...)- for _, p := range []string{"themes/custom/theme.css", "icons/custom/icon.js", "storage/bazaar/themes/custom.json", "storage/bazaar/icons/custom.json"} {- if !matcher.MatchesPath(p) {- t.Errorf("old engine isolation missing: %s", p)- }- }- if matcher.MatchesPath("storage/appearance-v1/themes/custom/event.sypkg") {- t.Fatal("transport archive was excluded")- }- userLines, err := AppearanceUserSyncIgnoreLines(lines)- if err != nil {- t.Fatal(err)- }- want := strings.Split(strings.TrimSuffix(strings.ReplaceAll(original, "\r\n", "\n"), "\n"), "\n")- if !reflect.DeepEqual(nonemptyAppearanceIsolationLines(userLines), nonemptyAppearanceIsolationLines(want)) {- t.Fatalf("user rule order changed: %q != %q", userLines, want)- }- userMatcher := ignore.CompileIgnoreLines(userLines...)- if userMatcher.MatchesPath("themes/shared/theme.css") {- t.Fatal("managed isolation was treated as a user exclusion")- }- info, err := os.Stat(rulePath)- if err != nil {- t.Fatal(err)- }- if info.ModTime().Unix() <= previous.Unix() {- t.Fatal("rule change reused the previous legacy file ID")- }- if err = EnsureAppearanceSyncIsolation(); err != nil {- t.Fatal(err)- }- again, err := os.Stat(rulePath)- if err != nil {- t.Fatal(err)- }- if !bytes.Equal(data, readAppearanceIsolationTestRules(t, rulePath)) || !again.ModTime().Equal(info.ModTime()) {- t.Fatal("idempotent bootstrap rewrote the rule file")- }- })- }-}--func nonemptyAppearanceIsolationLines(lines []string) []string {- var ret []string- for _, line := range lines {- if line != "" {- ret = append(ret, line)- }- }- return ret-}--func TestAppearanceSyncIsolationMovesBlockAfterUserRules(t *testing.T) {- rulePath := setupAppearanceIsolationTest(t)- initial := "/themes/private/\n"- writeAppearanceIsolationTestRules(t, rulePath, []byte(initial))- if err := EnsureAppearanceSyncIsolation(); err != nil {- t.Fatal(err)- }- data := append(readAppearanceIsolationTestRules(t, rulePath), []byte("!/themes/shared/**\n/icons/private/\n")...)- writeAppearanceIsolationTestRules(t, rulePath, data)- if err := EnsureAppearanceSyncIsolation(); err != nil {- t.Fatal(err)- }- data = readAppearanceIsolationTestRules(t, rulePath)- if bytes.Count(data, []byte(appearanceIsolationBlock[0])) != 1 ||- !bytes.HasSuffix(data, []byte(strings.Join(appearanceIsolationBlock, "\n")+"\n")) {- t.Fatalf("managed block was duplicated or not moved: %q", data)- }- lines, err := AppearanceUserSyncIgnoreLines(strings.Split(string(data), "\n"))- if err != nil {- t.Fatal(err)- }- want := []string{"/themes/private/", "!/themes/shared/**", "/icons/private/"}- if !reflect.DeepEqual(nonemptyAppearanceIsolationLines(lines), want) {- t.Fatalf("user rules lost: %q", lines)- }- user := ignore.CompileIgnoreLines(lines...)- if !user.MatchesPath("themes/private/theme.css") || !user.MatchesPath("icons/private/icon.js") || user.MatchesPath("themes/shared/theme.css") {- t.Fatal("user whole-package selection changed")- }- if !ignore.CompileIgnoreLines(strings.Split(string(data), "\n")...).MatchesPath("themes/shared/theme.css") {- t.Fatal("later user rule bypassed old-engine isolation")- }-}--func TestAppearanceSyncIsolationRepairsRestoredRules(t *testing.T) {- rulePath := setupAppearanceIsolationTest(t)- if err := EnsureAppearanceSyncIsolation(); err != nil {- t.Fatal(err)- }- oldRules := []byte("/assets/old-private/\n")- writeAppearanceIsolationTestRules(t, rulePath, oldRules)- if err := EnsureAppearanceSyncIsolation(); err != nil {- t.Fatal(err)- }- data := readAppearanceIsolationTestRules(t, rulePath)- if !bytes.HasPrefix(data, oldRules) || bytes.Count(data, []byte(appearanceIsolationBlock[0])) != 1 {- t.Fatalf("restored rule file not isolated: %q", data)- }- for _, kind := range []string{"themes", "icons"} {- if _, err := os.Lstat(filepath.Join(DataDir, kind)); !os.IsNotExist(err) {- t.Fatal("isolation helper created appearance projections")- }- }-}--func TestAppearanceSyncIsolationRejectsUnknownOrBrokenBlock(t *testing.T) {- valid := strings.Join(appearanceIsolationBlock, "\n") + "\n"- for name, content := range map[string]string{- "unknown": strings.ReplaceAll(valid, ":v1:", ":v2:"),- "missing-end": strings.TrimSuffix(valid, appearanceIsolationBlock[len(appearanceIsolationBlock)-1]+"\n"),- "changed-rule": strings.Replace(valid, "/themes/", "/widgets/", 1),- "orphan-end": appearanceIsolationBlock[len(appearanceIsolationBlock)-1] + "\n",- } {- t.Run(name, func(t *testing.T) {- rulePath := setupAppearanceIsolationTest(t)- writeAppearanceIsolationTestRules(t, rulePath, []byte(content))- info, err := os.Stat(rulePath)- if err != nil {- t.Fatal(err)- }- if err = EnsureAppearanceSyncIsolation(); err == nil {- t.Fatal("invalid isolation block accepted")- }- if _, err = AppearanceUserSyncIgnoreLines(strings.Split(content, "\n")); err == nil {- t.Fatal("invalid block produced usable user rules")- }- after, err := os.Stat(rulePath)- if err != nil || !after.ModTime().Equal(info.ModTime()) || !bytes.Equal(readAppearanceIsolationTestRules(t, rulePath), []byte(content)) {- t.Fatal("invalid rule source changed")- }- })- }-}--func TestAppearanceSyncIsolationRejectsNonregularRuleFile(t *testing.T) {- for _, kind := range []string{"directory", "symlink"} {- t.Run(kind, func(t *testing.T) {- rulePath := setupAppearanceIsolationTest(t)- if err := os.MkdirAll(filepath.Dir(rulePath), 0755); err != nil {- t.Fatal(err)- }- if kind == "directory" {- if err := os.Mkdir(rulePath, 0755); err != nil {- t.Fatal(err)- }- } else {- target := filepath.Join(t.TempDir(), "rules")- writeAppearanceIsolationTestRules(t, target, []byte("/private/\n"))- if err := os.Symlink(target, rulePath); err != nil {- t.Skipf("symlinks unavailable: %v", err)- }- t.Cleanup(func() {- if !bytes.Equal(readAppearanceIsolationTestRules(t, target), []byte("/private/\n")) {- t.Error("external rule source changed")- }- })- }- if err := EnsureAppearanceSyncIsolation(); err == nil {- t.Fatal("nonregular rule file accepted")- }- if _, err := os.Lstat(rulePath); err != nil {- t.Fatal("nonregular rule source removed")- }- })- }-}--func TestAppearanceSyncIsolationWaitsForRuleLock(t *testing.T) {- rulePath := setupAppearanceIsolationTest(t)- filelock.Lock(rulePath)- done := make(chan error, 1)- go func() { done <- EnsureAppearanceSyncIsolation() }()- select {- case err := <-done:- filelock.Unlock(rulePath)- t.Fatalf("bootstrap ignored rule-file lock: %v", err)- case <-time.After(30 * time.Millisecond):- }- filelock.Unlock(rulePath)- select {- case err := <-done:- if err != nil {- t.Fatal(err)- }- case <-time.After(5 * time.Second):- t.Fatal("bootstrap did not resume after rule-file unlock")- }-}--func TestAppearanceSyncIsolationRestoreDoesNotReuseTimestamp(t *testing.T) {- rulePath := setupAppearanceIsolationTest(t)- old := time.Now().Add(-time.Hour).Truncate(time.Second)- last := int64(0)- for _, rules := range []string{"/assets/a/\n", "/assets/b/\n", "/assets/c/\n"} {- writeAppearanceIsolationTestRules(t, rulePath, []byte(rules))- if err := os.Chtimes(rulePath, old, old); err != nil {- t.Fatal(err)- }- if err := EnsureAppearanceSyncIsolation(); err != nil {- t.Fatal(err)- }- info, err := os.Stat(rulePath)- if err != nil {- t.Fatal(err)- }- if info.ModTime().Unix() <= last {- t.Fatal("restored rules reused a previously published legacy file ID")- }- last = info.ModTime().Unix()- }- clockPath := filepath.Join(filepath.Dir(rulePath), appearanceIsolationClockName)- clock, err := os.Stat(clockPath)- if err != nil {- t.Fatal(err)- }- if ignored, err := dejavu.IgnorePath(clock, clockPath, "/.siyuan/"+appearanceIsolationClockName,- ".siyuan/syncignore", ".siyuan"); !ignored || err != nil {- t.Fatalf("local clock can enter an ordinary snapshot: %v", err)- }- contents := readAppearanceIsolationTestRules(t, clockPath)- if err = EnsureAppearanceSyncIsolation(); err != nil {- t.Fatal(err)- }- again, err := os.Stat(clockPath)- if err != nil || !again.ModTime().Equal(clock.ModTime()) || !os.SameFile(clock, again) ||- !bytes.Equal(contents, readAppearanceIsolationTestRules(t, clockPath)) {- t.Fatal("unchanged rules rewrote the reserved clock")- }-}--func TestAppearanceSyncIsolationClockSurvivesBackwardTime(t *testing.T) {- rulePath := setupAppearanceIsolationTest(t)- writeAppearanceIsolationTestRules(t, rulePath, []byte("/assets/private/\n"))- future := time.Now().Add(24 * time.Hour).Unix()- clockPath := filepath.Join(filepath.Dir(rulePath), appearanceIsolationClockName)- clock, err := json.Marshal(appearanceIsolationClock{Version: 1, Modified: future})- if err != nil {- t.Fatal(err)- }- writeAppearanceIsolationTestRules(t, clockPath, clock)- if err = EnsureAppearanceSyncIsolation(); err != nil {- t.Fatal(err)- }- info, err := os.Stat(rulePath)- if err != nil || info.ModTime().Unix() <= future {- t.Fatalf("wall-clock rollback reused a reserved timestamp: %v", err)- }-}--func TestAppearanceSyncIsolationRejectsUnknownClock(t *testing.T) {- for _, contents := range []string{- `{"version":2,"modified":100}`, `{"version":1,"modified":0}`, `{"version":1,"modified":100,"future":true}`,- `{"version":1,"modified":100} {}`, "{broken", `{"version":1,"modified":9223372036854775807}`,- `{"version":2,"version":1,"modified":100}`, `{"version":1,"modified":200,"modified":100}`,- `{"version":null,"modified":100}`,- } {- t.Run(contents, func(t *testing.T) {- rulePath := setupAppearanceIsolationTest(t)- original := []byte("/assets/private/\n")- writeAppearanceIsolationTestRules(t, rulePath, original)- clockPath := filepath.Join(filepath.Dir(rulePath), appearanceIsolationClockName)- writeAppearanceIsolationTestRules(t, clockPath, []byte(contents))- info, err := os.Stat(rulePath)- if err != nil {- t.Fatal(err)- }- if err = EnsureAppearanceSyncIsolation(); err == nil {- t.Fatal("unknown clock accepted")- }- after, err := os.Stat(rulePath)- if err != nil || !after.ModTime().Equal(info.ModTime()) || !os.SameFile(info, after) ||- !bytes.Equal(original, readAppearanceIsolationTestRules(t, rulePath)) ||- !bytes.Equal([]byte(contents), readAppearanceIsolationTestRules(t, clockPath)) {- t.Fatal("unknown clock changed source rules or local recovery material")- }- })- }-}--func TestAppearanceSyncIsolationReservesBeforePublishing(t *testing.T) {- rulePath := setupAppearanceIsolationTest(t)- original := []byte("/assets/private/\n")- writeAppearanceIsolationTestRules(t, rulePath, original)- info, err := os.Stat(rulePath)- if err != nil {- t.Fatal(err)- }- reserved, err := reserveAppearanceIsolationTime(rulePath, info, true)- if err != nil {- t.Fatal(err)- }- if !bytes.Equal(original, readAppearanceIsolationTestRules(t, rulePath)) {- t.Fatal("reserving the timestamp published rule bytes")- }- if err = EnsureAppearanceSyncIsolation(); err != nil {- t.Fatal(err)- }- after, err := os.Stat(rulePath)- if err != nil || after.ModTime().Unix() <= reserved.Unix() {- t.Fatalf("interrupted publication reused a reserved timestamp: %v", err)- }-}