An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Support theme and icon synchronization across devices https://github.com/siyuan-note/siyuan/issues/18883
Daniel77aec09ac5d1
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100717-yzwzn64.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100717-yzwzn64.syindex dc79a4605b..b31adb7fd7 100644--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100717-yzwzn64.sy+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100717-yzwzn64.sy@@ -6,7 +6,7 @@"id": "20200924100717-yzwzn64","title": "Kernel parameter","type": "doc",- "updated": "20260914011526"+ "updated": "20260917190844"},"Children": [{@@ -458,7 +458,7 @@"HeadingLevel": 3,"Properties": {"id": "20220601091217-g6ohtlq",- "updated": "20220601091217"+ "updated": "20260917190844"},"Children": [{@@ -514,7 +514,7 @@"Type": "NodeParagraph","Properties": {"id": "20220601091217-nnqyj25",- "updated": "20220601091217"+ "updated": "20260917190844"},"Children": [{@@ -537,7 +537,7 @@},{"Type": "NodeText",- "Data": "."+ "Data": ". This appearance folder contains built-in resources. Third-party themes and icon packages always use workspace/data/themes/ and workspace/data/icons/, regardless of the runtime mode."}]},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 e8fbdde342..9512ea977f 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": "20260829104731"+ "updated": "20260917190844"},"Children": [{@@ -270,7 +270,7 @@"HeadingLevel": 2,"Properties": {"id": "20230106105213-0cv5aqm",- "updated": "20230106105213"+ "updated": "20260917190844"},"Children": [{@@ -573,6 +573,20 @@]}]+ },+ {+ "ID": "20260917190844-1yo0d58",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260917190844-1yo0d58",+ "updated": "20260917190844"+ },+ "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."+ }+ ]}]}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 989fca1995..db70135d0f 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": "20260905191024"+ "updated": "20260917202413"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20210721112403-8no39l4",- "updated": "20260905184908"+ "updated": "20260917202413"},"Children": [{@@ -29,7 +29,7 @@"Type": "NodeParagraph","Properties": {"id": "20210721112403-0ft3r91",- "updated": "20260905184908"+ "updated": "20260917202413"},"Children": [{@@ -43,7 +43,21 @@},{"Type": "NodeText",- "Data": " folder logically consistent across devices, including assets, custom icons, plugins, code snippets, templates, widgets, and document data. With on-demand downloads, some asset content may not yet be stored on this device."+ "Data": " folder logically consistent across devices, including assets, custom icons, third-party theme and icon packages, plugins, code snippets, templates, widgets, and document data. With on-demand downloads, some asset content may not yet be stored on this device."+ }+ ]+ },+ {+ "ID": "20260917190844-p6hrspl",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260917190844-p6hrspl",+ "updated": "20260917202413"+ },+ "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."}]},@@ -705,7 +719,7 @@"HeadingLevel": 2,"Properties": {"id": "20230219121305-n0v0nlb",- "updated": "20230219121539"+ "updated": "20260917202413"},"Children": [{@@ -734,7 +748,7 @@"ListData": {},"Properties": {"id": "20220703232248-j1dq9w6",- "updated": "20220703232358"+ "updated": "20260917202413"},"Children": [{@@ -774,7 +788,7 @@},"Properties": {"id": "20220703232248-nuapm43",- "updated": "20220703232358"+ "updated": "20260917202413"},"Children": [{@@ -797,7 +811,7 @@"ListData": {},"Properties": {"id": "20220703232248-kl3io11",- "updated": "20220703232358"+ "updated": "20260917202413"},"Children": [{@@ -837,7 +851,7 @@},"Properties": {"id": "20220703232248-jneoxfm",- "updated": "20220703232358"+ "updated": "20260917202413"},"Children": [{@@ -845,12 +859,12 @@"Type": "NodeParagraph","Properties": {"id": "20220703232248-x7l12qz",- "updated": "20220703232358"+ "updated": "20260917202413"},"Children": [{"Type": "NodeText",- "Data": "If there is a file conflict, the local will overwrite the cloud, and the conflicting files from the cloud will be generated in the data history."+ "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"}]}diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200828105441-r76vmu5.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200828105441-r76vmu5.syindex 165b5bda29..138f9ea259 100644--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200828105441-r76vmu5.sy+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200828105441-r76vmu5.sy@@ -6,7 +6,7 @@"id": "20200828105441-r76vmu5","title": "内核参数","type": "doc",- "updated": "20260914011526"+ "updated": "20260917190844"},"Children": [{@@ -548,7 +548,7 @@"HeadingLevel": 3,"Properties": {"id": "20220601085956-e4x7vfb",- "updated": "20220601085956"+ "updated": "20260917190844"},"Children": [{@@ -604,7 +604,7 @@"Type": "NodeParagraph","Properties": {"id": "20220601090153-w4lmqvd",- "updated": "20220601091012"+ "updated": "20260917190844"},"Children": [{@@ -627,7 +627,7 @@},{"Type": "NodeText",- "Data": "。"+ "Data": "。这里的外观文件夹保存内置资源;第三方主题和图标包统一使用工作空间/data/themes/ 和工作空间/data/icons/,不随运行模式改变。"}]},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 e6c39e108a..cfde465c1e 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": "20260829104731"+ "updated": "20260917190844"},"Children": [{@@ -269,7 +269,7 @@"HeadingLevel": 2,"Properties": {"id": "20230106104118-wtvw42w",- "updated": "20230106104127"+ "updated": "20260917190844"},"Children": [{@@ -563,6 +563,20 @@]}]+ },+ {+ "ID": "20260917190844-hvlz04n",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260917190844-hvlz04n",+ "updated": "20260917190844"+ },+ "Children": [+ {+ "Type": "NodeText",+ "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 673270f509..ca189d1e3f 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": "20260905191024"+ "updated": "20260917202413"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20230808120347-wx5cr4v",- "updated": "20260905184908"+ "updated": "20260917202413"},"Children": [{@@ -29,7 +29,7 @@"Type": "NodeParagraph","Properties": {"id": "20230808120347-q4v034g",- "updated": "20260905184908"+ "updated": "20260917202413"},"Children": [{@@ -43,7 +43,21 @@},{"Type": "NodeText",- "Data": " 文件夹中的数据在逻辑上保持一致,包括资源文件、自定义图标、插件、代码片段、模板、挂件和文档数据。按需下载模式允许资源文件的内容暂不保存到本机。"+ "Data": " 文件夹中的数据在逻辑上保持一致,包括资源文件、自定义图标、第三方主题和图标包、插件、代码片段、模板、挂件和文档数据。按需下载模式允许资源文件的内容暂不保存到本机。"+ }+ ]+ },+ {+ "ID": "20260917190844-x6jwutu",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260917190844-x6jwutu",+ "updated": "20260917202413"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "主题和图标包的文件、更新和卸载会在设备间同步,各设备独立选择使用的主题和图标。包内图片、字体等资源始终完整下载。旧客户端可以继续同步笔记,共享外观包及其冲突由新客户端处理。"}]},@@ -697,7 +711,7 @@"HeadingLevel": 2,"Properties": {"id": "20230808120347-lptnyvq",- "updated": "20230219121525"+ "updated": "20260917202413"},"Children": [{@@ -726,7 +740,7 @@"ListData": {},"Properties": {"id": "20230808120347-j4bqb3a",- "updated": "20220703230810"+ "updated": "20260917202413"},"Children": [{@@ -766,7 +780,7 @@},"Properties": {"id": "20230808120347-pvyr15g",- "updated": "20220703230810"+ "updated": "20260917202413"},"Children": [{@@ -789,7 +803,7 @@"ListData": {},"Properties": {"id": "20230808120347-vb1ee0l",- "updated": "20220703230810"+ "updated": "20260917202413"},"Children": [{@@ -828,7 +842,7 @@},"Properties": {"id": "20230808120347-7p8pzdq",- "updated": "20220703230810"+ "updated": "20260917202413"},"Children": [{@@ -836,12 +850,12 @@"Type": "NodeParagraph","Properties": {"id": "20230808120347-t5n8fkj",- "updated": "20220703230810"+ "updated": "20260917202413"},"Children": [{"Type": "NodeText",- "Data": "如果存在文件冲突,则以本地为准覆盖云端,同时拉取到的云端冲突文件会归入到数据历史中"+ "Data": "普通文件发生冲突时,以本地为准覆盖云端,同时拉取到的云端冲突文件会归入数据历史;主题和图标按完整包处理冲突,不会混合不同版本的文件"}]}diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122358-hctqcn5.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122358-hctqcn5.syindex 4c0d1df117..664f9a50ea 100644--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122358-hctqcn5.sy+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226122358-hctqcn5.sy@@ -6,7 +6,7 @@"id": "20211226122358-hctqcn5","title": "Kernel 參數","type": "doc",- "updated": "20260914011526"+ "updated": "20260917190844"},"Children": [{@@ -548,7 +548,7 @@"HeadingLevel": 3,"Properties": {"id": "20220601091152-z1gdkxi",- "updated": "20220601091152"+ "updated": "20260917190844"},"Children": [{@@ -604,7 +604,7 @@"Type": "NodeParagraph","Properties": {"id": "20220601091152-7qrn8ca",- "updated": "20220601091152"+ "updated": "20260917190844"},"Children": [{@@ -627,7 +627,7 @@},{"Type": "NodeText",- "Data": "。"+ "Data": "。這裡的外觀資料夾儲存內建資源;第三方主題和圖示套件統一使用工作空間/data/themes/ 和工作空間/data/icons/,不隨執行模式改變。"}]},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 d656672082..f98ab6357f 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": "20260829104731"+ "updated": "20260917190844"},"Children": [{@@ -270,7 +270,7 @@"HeadingLevel": 2,"Properties": {"id": "20230106104714-4snblro",- "updated": "20230106104714"+ "updated": "20260917190844"},"Children": [{@@ -569,6 +569,20 @@]}]+ },+ {+ "ID": "20260917190844-s9beduz",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260917190844-s9beduz",+ "updated": "20260917190844"+ },+ "Children": [+ {+ "Type": "NodeText",+ "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 64ab5b3b46..21ff42c947 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": "20260905191024"+ "updated": "20260917202413"},"Children": [{@@ -15,7 +15,7 @@"HeadingLevel": 2,"Properties": {"id": "20211226121454-8vr6fgn",- "updated": "20260905184908"+ "updated": "20260917202413"},"Children": [{@@ -29,7 +29,7 @@"Type": "NodeParagraph","Properties": {"id": "20211226121454-2wnvrmj",- "updated": "20260905184908"+ "updated": "20260917202413"},"Children": [{@@ -43,7 +43,21 @@},{"Type": "NodeText",- "Data": " 資料夾中的資料在邏輯上保持一致,包括資源檔案、自訂圖示、外掛程式、程式碼片段、範本、掛件和文件資料。按需下載模式允許資源檔案的內容暫不儲存於本機。"+ "Data": " 資料夾中的資料在邏輯上保持一致,包括資源檔案、自訂圖示、第三方主題和圖示套件、外掛程式、程式碼片段、範本、掛件和文件資料。按需下載模式允許資源檔案的內容暫不儲存於本機。"+ }+ ]+ },+ {+ "ID": "20260917190844-m610sh8",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260917190844-m610sh8",+ "updated": "20260917202413"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "主題和圖示套件的檔案、更新和解除安裝會在裝置間同步,各裝置獨立選擇使用的主題和圖示。套件內圖片、字型等資源一律完整下載。舊版客戶端可以繼續同步筆記,共用外觀套件及其衝突由新版客戶端處理。"}]},@@ -701,7 +715,7 @@"HeadingLevel": 2,"Properties": {"id": "20211226121454-i5h1wl1",- "updated": "20230219121531"+ "updated": "20260917202413"},"Children": [{@@ -730,7 +744,7 @@"ListData": {},"Properties": {"id": "20220703231942-e565c49",- "updated": "20220703231942"+ "updated": "20260917202413"},"Children": [{@@ -770,7 +784,7 @@},"Properties": {"id": "20220703231942-xzs4i10",- "updated": "20220703231942"+ "updated": "20260917202413"},"Children": [{@@ -793,7 +807,7 @@"ListData": {},"Properties": {"id": "20220703231942-kniy7e9",- "updated": "20220703231942"+ "updated": "20260917202413"},"Children": [{@@ -833,7 +847,7 @@},"Properties": {"id": "20220703231942-skyyrpj",- "updated": "20220703231942"+ "updated": "20260917202413"},"Children": [{@@ -841,12 +855,12 @@"Type": "NodeParagraph","Properties": {"id": "20220703231942-24cgfdl",- "updated": "20220703231942"+ "updated": "20260917202413"},"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 bfe755085b..ee8bc9070e 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": "20260905191024"+ "updated": "20260917202413"},"Children": [{@@ -17,7 +17,7 @@"Properties": {"ID": "20240530101000-otrm2qw","id": "20240530101000-qw5ujp4",- "updated": "20260905184908"+ "updated": "20260917202413"},"Children": [{@@ -31,7 +31,7 @@"Type": "NodeParagraph","Properties": {"id": "20240530101000-6vtiz1y",- "updated": "20260905184908"+ "updated": "20260917202413"},"Children": [{@@ -45,7 +45,21 @@},{"Type": "NodeText",- "Data": " フォルダのデータを論理的に一致させることです。リソースファイル、カスタムアイコン、プラグイン、コードスニペット、テンプレート、ウィジェット、ドキュメントデータが含まれます。必要時にダウンロードするモードでは、一部のリソースファイルの内容が端末にまだ保存されていない場合があります。"+ "Data": " フォルダのデータを論理的に一致させることです。リソースファイル、カスタムアイコン、サードパーティのテーマとアイコンパッケージ、プラグイン、コードスニペット、テンプレート、ウィジェット、ドキュメントデータが含まれます。必要時にダウンロードするモードでは、一部のリソースファイルの内容が端末にまだ保存されていない場合があります。"+ }+ ]+ },+ {+ "ID": "20260917190844-vilhr3p",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260917190844-vilhr3p",+ "updated": "20260917202413"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "テーマとアイコンパッケージのファイル、更新、アンインストールは端末間で同期されますが、使用するテーマとアイコンは端末ごとに選択できます。パッケージ内の画像やフォントなどは常にすべてダウンロードされます。古いクライアントでも引き続きノートを同期できます。共有する外観パッケージとその競合は新しいクライアントで処理します。"}]},@@ -758,7 +772,7 @@"Properties": {"ID": "20240530101000-q5e6vx7","id": "20240530101000-ayipniy",- "updated": "20240530101000"+ "updated": "20260917202413"},"Children": [{@@ -789,7 +803,7 @@"Properties": {"ID": "20240530101000-ztbegy1","id": "20240530101000-t60qehm",- "updated": "20240530101000"+ "updated": "20260917202413"},"Children": [{@@ -832,7 +846,7 @@"Properties": {"ID": "20240530101000-g6lkhbk","id": "20240530101000-8wnwvrn",- "updated": "20240530101000"+ "updated": "20260917202413"},"Children": [{@@ -857,7 +871,7 @@"Properties": {"ID": "20240530101000-3quvavd","id": "20240530101000-q0xdonu",- "updated": "20240530101000"+ "updated": "20260917202413"},"Children": [{@@ -900,7 +914,7 @@"Properties": {"ID": "20240530101000-7lnae2y","id": "20240530101000-5dmwlq3",- "updated": "20240530101000"+ "updated": "20260917202413"},"Children": [{@@ -909,12 +923,12 @@"Properties": {"ID": "20240530101000-zwjlslj","id": "20240530101000-a04kcnp",- "updated": "20240530101000"+ "updated": "20260917202413"},"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 c90cb79750..94e8581c89 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": "20260829104731"+ "updated": "20260917190844"},"Children": [{@@ -285,7 +285,7 @@"Properties": {"ID": "20240530101000-j4ly8y7","id": "20240530101000-1mozynr",- "updated": "20240530101000"+ "updated": "20260917190844"},"Children": [{@@ -604,6 +604,20 @@]}]+ },+ {+ "ID": "20260917190844-5om4pnd",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20260917190844-5om4pnd",+ "updated": "20260917190844"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "サードパーティのテーマは data/themes/、アイコンパッケージは data/icons/ に保存され、データ同期とスナップショットの対象になります。各端末の外観の選択は引き続きローカルの conf/conf.json に保存されます。内蔵の外観リソースは同期されません。アップグレード時の移行では、復元用に元のローカルファイルを保持します。"+ }+ ]}]}diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xq26o73.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xq26o73.syindex 76e2aafbb2..d5994109e0 100644--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xq26o73.sy+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-xq26o73.sy@@ -7,7 +7,7 @@"id": "20240530101000-xq26o73","title": "カーネルパラメータ","type": "doc",- "updated": "20260914011526"+ "updated": "20260917190844"},"Children": [{@@ -478,7 +478,7 @@"Properties": {"ID": "20240530101000-jc2iusi","id": "20240530101000-au2afuj",- "updated": "20240530101000"+ "updated": "20260917190844"},"Children": [{@@ -536,7 +536,7 @@"Properties": {"ID": "20240530101000-tgko9uw","id": "20240530101000-ykliek4",- "updated": "20240530101000"+ "updated": "20260917190844"},"Children": [{@@ -568,7 +568,7 @@},{"Type": "NodeText",- "Data": " が使用されます。"+ "Data": " が使用されます。この外観フォルダには内蔵リソースを保存します。サードパーティのテーマとアイコンパッケージは、実行モードに関係なく workspace/data/themes/ と workspace/data/icons/ を使用します。"}]},diff --git a/app/src/config/tabs/appearanceRuntime.test.ts b/app/src/config/tabs/appearanceRuntime.test.tsindex 813eda8d8a..3f664fa5c1 100644--- a/app/src/config/tabs/appearanceRuntime.test.ts+++ b/app/src/config/tabs/appearanceRuntime.test.ts@@ -9,7 +9,7 @@ const {parse} = require("ifdef-loader/preprocessor");for (const mobile of [true, false]) {for (const change of ["gradient", "duplicate", "theme", "initial"] as const) {- test(`appearance updates preserve gradient controls without skipping theme initialization (${change}, mobile=${mobile})`, () => {+ test(`appearance updates preserve gradient controls without skipping theme initialization (${change}, mobile=${mobile})`, async () => {const source = readFileSync(resolve(process.cwd(), "src/config/tabs/appearanceRuntime.ts"), "utf8");const processed = parse(source, {MOBILE: mobile, BROWSER: true}, false, true);const code = transpileModule(processed, {compilerOptions: {module: ModuleKind.CommonJS}}).outputText;@@ -21,6 +21,7 @@ for (const mobile of [true, false]) {};const siyuan = {config: {appearance}};const calls: string[] = [];+ let pending: Promise<void>;const moduleExports: {appearanceConfigApi?: {apply: (data: unknown) => void}} = {};runInNewContext(code, {exports: moduleExports,@@ -33,10 +34,15 @@ for (const mobile of [true, false]) {if (name === "../../util/themeCompatibility") {return {shouldUnloadThemeScript: () => false};}+ if (name === "../../util/assets") {+ return new Proxy({}, {get: (_, key) => key === "enqueueAppearanceUpdate" ?+ (apply: () => Promise<void>) => pending = apply() : () => calls.push(String(key))});+ }return new Proxy({}, {get: (_, key) => () => calls.push(String(key))});},});moduleExports.appearanceConfigApi.apply(next);+ await pending;assert.equal(siyuan.config.appearance, next);const updatesInPlace = change === "gradient" || change === "duplicate";assert.equal(calls.includes("syncBodyGradient"), updatesInPlace);@@ -46,3 +52,80 @@ for (const mobile of [true, false]) {});}}++for (const mobile of [true, false]) {+ for (const affected of ["selected", "other", "icon", "removed", "cannot-unload"] as const) {+ test(`synced appearance packages refresh without changing manifest versions (${affected}, mobile=${mobile})`, async () => {+ const source = readFileSync(resolve(process.cwd(), "src/config/tabs/appearanceRuntime.ts"), "utf8");+ const processed = parse(source, {MOBILE: mobile, BROWSER: true}, false, true);+ const code = transpileModule(processed, {compilerOptions: {module: ModuleKind.CommonJS}}).outputText;+ const appearance = {+ lang: "en", mode: 0, themeLight: "selected", themeDark: "midnight", themeVer: "1.0.0",+ icon: "custom", iconVer: "1.0.0", themeJS: true, bodyGradient: {mode: "auto"},+ };+ const next = {...appearance, themeLight: affected === "removed" ? "daylight" : "selected"};+ const siyuan: {config: {appearance: typeof appearance}; mobile: {editor: null}} = {+ config: {appearance}, mobile: {editor: null},+ };+ const calls: string[] = [];+ const moduleExports: {refreshAppearance?: (data: unknown) => Promise<void>} = {};+ runInNewContext(code, {+ exports: moduleExports,+ window: {siyuan, location: {reload: () => calls.push("reload")}},+ document: {getElementById: (): HTMLElement | null => null},+ require: (name: string) => {+ if (name === "../util/namespaceApi") {+ return {createConfigNamespaceApi: () => ({})};+ }+ if (name === "../../util/themeCompatibility") {+ return {+ shouldUnloadThemeScript: () => false,+ getCurrentThemeName: (data: typeof appearance) => data.themeLight,+ isCurrentThemeSupported: () => true,+ };+ }+ if (name === "../../util/assets") {+ return new Proxy({}, {get: (_, key) => {+ if (key === "enqueueAppearanceUpdate") {+ return (apply: () => Promise<void>) => apply();+ }+ if (key === "invalidateAppearancePackages") {+ return (themes: string[], icons: string[], revision: string) => {+ assert.equal(revision, "sync-123");+ calls.push("invalidate");+ return {themes, icons};+ };+ }+ if (key === "unloadThemeScript") {+ return async () => {+ calls.push("unload");+ return affected !== "cannot-unload";+ };+ }+ return () => calls.push(String(key));+ }});+ }+ if (name === "../../layout/util") {+ return {exportLayout: (options: {cb: () => void}) => options.cb()};+ }+ return new Proxy({}, {get: (_, key) => () => calls.push(String(key))});+ },+ });+ await moduleExports.refreshAppearance({+ appearance: next, revision: "sync-123",+ themes: affected === "icon" ? [] : [affected === "other" ? "other" : "selected"],+ icons: affected === "icon" ? ["custom"] : [],+ });+ const shouldUnload = affected !== "other" && affected !== "icon";+ assert.equal(calls.includes("unload"), shouldUnload);+ assert.equal(calls.includes("syncBodyGradient"), false);+ assert.equal(calls.includes("reload"), affected === "cannot-unload");+ assert.equal(calls.includes("loadAssets"), affected !== "cannot-unload");+ if (shouldUnload && affected !== "cannot-unload") {+ assert.ok(calls.indexOf("unload") < calls.indexOf("loadAssets"));+ }+ assert.equal(siyuan.config.appearance.themeVer, "1.0.0");+ assert.equal(siyuan.config.appearance.iconVer, "1.0.0");+ });+ }+}diff --git a/app/src/config/tabs/appearanceRuntime.ts b/app/src/config/tabs/appearanceRuntime.tsindex 2ab6c58c51..78ffae5b67 100644--- a/app/src/config/tabs/appearanceRuntime.ts+++ b/app/src/config/tabs/appearanceRuntime.ts@@ -6,9 +6,18 @@ import {exportLayout} from "../../layout/util";import {syncHideToolbarLayout, updateBarModeIcon} from "../../layout/topBar";/// #endifimport {fetchPost} from "../../util/fetch";-import {loadAssets, refreshHeadingNumberMeasurements, setBodyHighlight, setInlineStyle, unloadThemeScript} from "../../util/assets";+import {+ enqueueAppearanceUpdate,+ invalidateAppearancePackages,+ loadAssets,+ markAppearanceReloadPending,+ refreshHeadingNumberMeasurements,+ setBodyHighlight,+ setInlineStyle,+ unloadThemeScript+} from "../../util/assets";import {getFrontend} from "../../util/functions";-import {shouldUnloadThemeScript} from "../../util/themeCompatibility";+import {getCurrentThemeName, isCurrentThemeSupported, shouldUnloadThemeScript} from "../../util/themeCompatibility";import {remountOpenSettingTab} from "../setting/mount";import {createConfigNamespaceApi} from "../util/namespaceApi";import {syncBodyGradient} from "./bodyGradient";@@ -36,8 +45,16 @@ const reloadUI = async () => {};/// #endif-const applyAppearanceConfig = async (data: Config.IAppearance) => {+interface IAppearanceRefresh {+ appearance: Config.IAppearance;+ themes: string[] | null;+ icons: string[] | null;+ revision: string;+}++const applyAppearanceConfig = async (data: Config.IAppearance, refresh?: IAppearanceRefresh) => {if (data.lang !== window.siyuan.config.appearance.lang) {+ markAppearanceReloadPending();/// #if MOBILEvoid reloadUI();/// #else@@ -52,10 +69,13 @@ const applyAppearanceConfig = async (data: Config.IAppearance) => {}const prevAppearance = window.siyuan.config.appearance;+ const changedPackages = refresh && invalidateAppearancePackages(refresh.themes || [], refresh.icons || [], refresh.revision);+ const themeChanged = changedPackages?.themes.some(name => name === getCurrentThemeName(prevAppearance) ||+ name === getCurrentThemeName(data));// 仅更新背景渐变时原位同步控件,避免整页重建期间的布局变化引起滚动抖动。// 启动初始化传入当前配置本身,需要完整加载外观资源;重复推送仍使用原位同步。const appearanceKeys = Object.keys({...prevAppearance, ...data}) as Array<keyof Config.IAppearance>;- if (prevAppearance !== data &&+ if (!refresh && prevAppearance !== data &&appearanceKeys.every(key => key === "bodyGradient" ||JSON.stringify(prevAppearance[key]) === JSON.stringify(data[key]))) {window.siyuan.config.appearance = data;@@ -63,7 +83,9 @@ const applyAppearanceConfig = async (data: Config.IAppearance) => {syncBodyGradient();return;}- if (shouldUnloadThemeScript(prevAppearance, data, getFrontend()) && !await unloadThemeScript()) {+ const unloadChangedTheme = themeChanged && prevAppearance.themeJS && isCurrentThemeSupported(prevAppearance, getFrontend());+ if ((unloadChangedTheme || shouldUnloadThemeScript(prevAppearance, data, getFrontend())) && !await unloadThemeScript()) {+ markAppearanceReloadPending();/// #if MOBILEvoid reloadUI();/// #else@@ -90,7 +112,7 @@ const applyAppearanceConfig = async (data: Config.IAppearance) => {updateBarModeIcon();/// #endif- loadAssets(data);+ await loadAssets(data);if (JSON.stringify(data.globalFontFamilies) !== JSON.stringify(prevAppearance.globalFontFamilies)) {await setInlineStyle();refreshHeadingNumberMeasurements();@@ -100,12 +122,15 @@ const applyAppearanceConfig = async (data: Config.IAppearance) => {/// #endif};+export const refreshAppearance = (data: IAppearanceRefresh) =>+ enqueueAppearanceUpdate(() => applyAppearanceConfig(data.appearance, data));+/** 外观 Tab 命名空间:设置面板注册项 save */export const appearanceConfigApi = createConfigNamespaceApi<Config.IAppearance>({namespace: "appearance",getConfig: () => window.siyuan.config.appearance,setConfig: (data) => {- void applyAppearanceConfig(data);+ void enqueueAppearanceUpdate(() => applyAppearanceConfig(data));},apiPath: "/api/setting/setAppearance",applyFromResponse: false,diff --git a/app/src/index.ts b/app/src/index.tsindex ee9a4a2131..d09c5b2d82 100644--- a/app/src/index.ts+++ b/app/src/index.ts@@ -54,7 +54,7 @@ import {ipcRenderer} from "electron";import {getDockByType} from "./layout/tabUtil";import {Files} from "./layout/dock/Files";import {Tag} from "./layout/dock/Tag";-import {appearanceConfigApi} from "./config/tabs/appearanceRuntime";+import {appearanceConfigApi, refreshAppearance} from "./config/tabs/appearanceRuntime";import {renderSnippet} from "./config/util/snippets";import {refreshThemeStyle, reloadInlineStyles, setBodyHighlight} from "./util/assets";import {reloadSync} from "./util/reloadSync";@@ -92,6 +92,9 @@ export class App {case "setAppearance":appearanceConfigApi.apply(data.data);break;+ case "refreshAppearance":+ void refreshAppearance(data.data);+ break;case "reloadInlineStyles":void reloadInlineStyles();break;diff --git a/app/src/mobile/util/onMessage.ts b/app/src/mobile/util/onMessage.tsindex 23f714f2f7..2c002c6c79 100644--- a/app/src/mobile/util/onMessage.ts+++ b/app/src/mobile/util/onMessage.ts@@ -22,7 +22,7 @@ import {reloadInlineStyles} from "../../util/assets";import {renderMobileBottomBar} from "./mobileBottomBar";import {Constants} from "../../constants";import {MOBILE_SIDE_PANEL_CONFIG_CHANGE_EVENT} from "./mobileSidePanelConfig";-import {appearanceConfigApi} from "../../config/tabs/appearanceRuntime";+import {appearanceConfigApi, refreshAppearance} from "../../config/tabs/appearanceRuntime";import {applyCloudUserState} from "../../config/tabs/accountUi";import {isInMobileApp} from "../../protyle/util/compatibility";import {handleMobileKernelExit} from "./kernelExit";@@ -65,6 +65,9 @@ export const onMessage = (app: App, data: IWebSocketData) => {case "setAppearance":appearanceConfigApi.apply(data.data);break;+ case "refreshAppearance":+ void refreshAppearance(data.data);+ break;case "reloadInlineStyles":void reloadInlineStyles();break;diff --git a/app/src/util/appearanceAssets.test.ts b/app/src/util/appearanceAssets.test.tsnew file mode 100644index 0000000000..c9e2dae2c5--- /dev/null+++ b/app/src/util/appearanceAssets.test.ts@@ -0,0 +1,159 @@+import * as assert from "node:assert/strict";+import {readFileSync} from "node:fs";+import {resolve} from "node:path";+import {test} from "node:test";+import {runInNewContext} from "node:vm";+import {ModuleKind, transpileModule} from "typescript";+import * as themeCompatibility from "./themeCompatibility";++const {parse} = require("ifdef-loader/preprocessor");++const createAssets = () => {+ const source = readFileSync(resolve(process.cwd(), "src/util/assets.ts"), "utf8");+ const processed = parse(source, {MOBILE: false, BROWSER: true}, false, true);+ const code = transpileModule(processed, {compilerOptions: {module: ModuleKind.CommonJS}}).outputText;+ const removedElements: string[] = [];+ const element = (attributes: Record<string, string>) => ({+ attributes,+ getAttribute: (key: string) => attributes[key],+ setAttribute: (key: string, value: string) => attributes[key] = value,+ addEventListener: () => {},+ remove: () => removedElements.push(attributes.href || attributes.src),+ });+ const elements = {+ themeDefaultStyle: element({href: "/appearance/themes/daylight/theme.css?v=3.8.5"}),+ themeStyle: element({href: "/appearance/themes/custom/theme.css?v=1.0.0"}),+ iconDefaultScript: element({src: "/appearance/icons/litheness/icon.js?v=3.8.5"}),+ iconScript: element({src: "/appearance/icons/custom/icon.js?v=1.0.0"}),+ };+ const html = element({"data-theme-mode": "light"});+ const appearance = {+ lang: "en", mode: 0, modeOS: false, themeLight: "custom", themeDark: "midnight", themeVer: "1.0.0",+ icon: "custom", iconVer: "1.0.0", themeJS: false,+ lightThemes: [{name: "custom", label: "Custom", frontends: ["all"]}],+ icons: [{name: "custom", label: "Custom"}],+ };+ const moduleExports: {+ enqueueAppearanceUpdate?: (apply: () => Promise<void>) => Promise<void>;+ markAppearanceReloadPending?: () => void;+ invalidateAppearancePackages?: (themes: string[], icons: string[], revision: string) => {themes: string[]; icons: string[]};+ loadAssets?: (data: unknown) => Promise<void>;+ } = {};+ const errors: string[] = [];+ const scriptURLs: string[] = [];+ runInNewContext(code, {+ exports: moduleExports,+ URL,+ console: {error: (message: string) => errors.push(message)},+ window: {+ siyuan: {config: {appearance}, storage: {pdf: {light: "light", dark: "dark"}}},+ location: {href: "http://localhost/stage/build/desktop/"},+ navigator: {},+ matchMedia: () => ({matches: false}),+ setTimeout: () => 0,+ clearTimeout: () => {},+ },+ document: {+ documentElement: {style: {setProperty: () => {}, removeProperty: () => {}}},+ body: {children: []},+ getElementsByTagName: () => [html],+ getElementById: (id: keyof typeof elements) => elements[id],+ querySelectorAll: (): unknown[] => [],+ },+ require: (name: string) => {+ if (name === "../constants") {+ return {Constants: {SIYUAN_VERSION: "3.8.5", LOCAL_PDFTHEME: "pdf"}};+ }+ if (name === "./hostCapabilities") {+ return {getHostCapabilities: () => ({customAppearance: true})};+ }+ if (name === "./themeCompatibility") {+ return themeCompatibility;+ }+ if (name === "../layout/getAll") {+ return {getAllModels: (): {graph: unknown[]} => ({graph: []})};+ }+ if (name === "../protyle/util/addScript") {+ return {addScript: async (url: string, id: keyof typeof elements) => {+ scriptURLs.push(url);+ elements[id]?.setAttribute("src", url);+ }};+ }+ return new Proxy({}, {get: () => (): undefined => undefined});+ },+ });+ return {assets: moduleExports, appearance, elements, errors, scriptURLs, removedElements};+};++test("missing appearance packages use built-in resources without replacing the saved choices", async () => {+ const {assets, appearance, elements, scriptURLs, removedElements} = createAssets();+ appearance.lightThemes = [];+ appearance.icons = [];+ appearance.themeJS = true;+ await assets.loadAssets(appearance);+ assert.ok(removedElements.includes("/appearance/themes/custom/theme.css?v=1.0.0"));+ assert.ok(removedElements.includes("/appearance/icons/custom/icon.js?v=1.0.0"));+ assert.equal(elements.themeDefaultStyle.getAttribute("href"), "/appearance/themes/daylight/theme.css?v=3.8.5");+ assert.equal(elements.iconDefaultScript.getAttribute("src"), "/appearance/icons/litheness/icon.js?v=3.8.5");+ assert.deepEqual(scriptURLs, []);+ assert.equal(appearance.themeLight, "custom");+ assert.equal(appearance.icon, "custom");+ assert.equal(appearance.themeVer, "1.0.0");+ assert.equal(appearance.iconVer, "1.0.0");+});++test("appearance resource revisions refresh only affected packages without changing versions", async () => {+ const {assets, appearance, elements, scriptURLs} = createAssets();+ assets.invalidateAppearancePackages(["other"], ["other"], "unrelated");+ await assets.loadAssets(appearance);+ assert.equal(elements.themeStyle.getAttribute("href"), "/appearance/themes/custom/theme.css?v=1.0.0");+ assert.deepEqual(scriptURLs, []);++ assets.invalidateAppearancePackages(["custom"], ["custom"], "sync 1");+ await assets.loadAssets(appearance);+ assert.equal(elements.themeStyle.getAttribute("href"), "/appearance/themes/custom/theme.css?v=1.0.0&revision=sync%201");+ assert.equal(elements.iconScript.getAttribute("src"), "/appearance/icons/custom/icon.js?v=1.0.0&revision=sync%201");+ assert.equal(appearance.themeVer, "1.0.0");+ assert.equal(appearance.iconVer, "1.0.0");+ const repeated = assets.invalidateAppearancePackages(["custom"], ["custom"], "sync 1");+ assert.equal(repeated.themes.length, 0);+ assert.equal(repeated.icons.length, 0);+});++test("appearance updates wait for pending work and continue after an update rejects", async () => {+ const {assets, errors} = createAssets();+ const calls: string[] = [];+ let release: () => void;+ const waiting = new Promise<void>(resolve => release = resolve);+ const first = assets.enqueueAppearanceUpdate(async () => {+ calls.push("first-start");+ await waiting;+ calls.push("first-end");+ });+ const second = assets.enqueueAppearanceUpdate(async () => {+ calls.push("second");+ throw new Error("test update failed");+ });+ const third = assets.enqueueAppearanceUpdate(async () => {+ calls.push("third");+ });+ await Promise.resolve();+ assert.deepEqual(calls, ["first-start"]);+ release();+ await Promise.all([first, second, third]);+ assert.deepEqual(calls, ["first-start", "first-end", "second", "third"]);+ assert.equal(errors.length, 1);+});++test("appearance updates stop after a page reload has been requested", async () => {+ const {assets} = createAssets();+ const calls: string[] = [];+ await assets.enqueueAppearanceUpdate(async () => {+ calls.push("reload");+ assets.markAppearanceReloadPending();+ });+ await assets.enqueueAppearanceUpdate(async () => {+ calls.push("load-again");+ });+ assert.deepEqual(calls, ["reload"]);+});diff --git a/app/src/util/assets.ts b/app/src/util/assets.tsindex a8a3c766f4..d80900690b 100644--- a/app/src/util/assets.ts+++ b/app/src/util/assets.ts@@ -33,9 +33,43 @@ import {refreshChartTheme} from "../protyle/render/chartRender";import {getHostCapabilities} from "./hostCapabilities";let headingNumberMeasurementRefreshTimer: number;+let appearanceUpdate = Promise.resolve();+let appearanceReloadPending = false;+const appearancePackageRevisions = new Map<string, string>();const DEJAVU_EMOJI_PRESENTATION_UNICODE_RANGE = "U+25fd-25fe, U+2614-2615, U+2648-2653, U+267f, U+2693, U+26a1, " +"U+26aa-26ab, U+1f0cf, U+1f311-1f318, U+1f42d-1f42e, U+1f431, U+1f435, U+1f600-1f64f";+// 串行应用外观变更,等待脚本加载和卸载完成后再处理下一次推送。+export const enqueueAppearanceUpdate = (apply: () => Promise<void>) => {+ appearanceUpdate = appearanceUpdate.then(async () => {+ if (!appearanceReloadPending) {+ await apply();+ }+ }).catch(error => {+ console.error("apply appearance error: " + error);+ });+ return appearanceUpdate;+};++export const markAppearanceReloadPending = () => {+ appearanceReloadPending = true;+};++export const invalidateAppearancePackages = (themes: string[], icons: string[], revision: string) => {+ const changed = {+ themes: themes.filter(name => appearancePackageRevisions.get(`themes/${name}`) !== revision),+ icons: icons.filter(name => appearancePackageRevisions.get(`icons/${name}`) !== revision),+ };+ themes.forEach(name => appearancePackageRevisions.set(`themes/${name}`, revision));+ icons.forEach(name => appearancePackageRevisions.set(`icons/${name}`, revision));+ return changed;+};++const appearancePackageVersion = (kind: "themes" | "icons", name: string, version: string) => {+ const revision = appearancePackageRevisions.get(`${kind}/${name}`);+ return encodeURIComponent(version) + (revision ? `&revision=${encodeURIComponent(revision)}` : "");+};+export const refreshHeadingNumberMeasurements = () => {invalidateHeadingNumberMeasurements();getAllEditor().forEach(item => renderHeadingNumbers(item.protyle));@@ -99,7 +133,8 @@ export const refreshThemeStyle = (themeAddress: string) => {}};-export const loadAssets = (appearance: Config.IAppearance) => {+export const loadAssets = async (appearance: Config.IAppearance) => {+ const scriptLoads: Promise<unknown>[] = [];setBodyHighlight(appearance.bodyGradient);const data = getHostCapabilities().customAppearance ? appearance : {...appearance,@@ -157,9 +192,10 @@ export const loadAssets = (appearance: Config.IAppearance) => {const themeSupported = isCurrentThemeSupported(data, getFrontend());if (themeSupported && ((data.mode === 1 && data.themeDark !== "midnight") ||(data.mode === 0 && data.themeLight !== "daylight"))) {- const themeAddress = `/appearance/themes/${data.mode === 1 ? data.themeDark : data.themeLight}/theme.css?v=${data.themeVer}`;+ const themeName = data.mode === 1 ? data.themeDark : data.themeLight;+ const themeAddress = `/appearance/themes/${themeName}/theme.css?v=${appearancePackageVersion("themes", themeName, data.themeVer)}`;if (styleElement) {- if (!styleElement.getAttribute("href").startsWith(themeAddress)) {+ if (styleElement.getAttribute("href") !== themeAddress) {changedThemeStyleElements.push(styleElement as HTMLLinkElement);themeStylesChanged = true;styleElement.setAttribute("href", themeAddress);@@ -206,26 +242,28 @@ export const loadAssets = (appearance: Config.IAppearance) => {/// #endifsetCodeTheme();- const themeScriptAddress = `/appearance/themes/${data.mode === 1 ? data.themeDark : data.themeLight}/theme.js?v=${data.themeVer}`;+ const themeName = data.mode === 1 ? data.themeDark : data.themeLight;+ const themeScriptAddress = `/appearance/themes/${themeName}/theme.js?v=${appearancePackageVersion("themes", themeName, data.themeVer)}`;const themeScriptURL = new URL(themeScriptAddress, window.location.href).href;const themeScriptElements = getThemeScriptElements();if (!data.themeJS || !themeSupported) {removeThemeScriptElements();} else if (!themeScriptElements.some((item) => item.src === themeScriptURL)) {removeThemeScriptElements();- addScript(themeScriptAddress, "themeScript");+ scriptLoads.push(addScript(themeScriptAddress, "themeScript"));}// load icons- const isBuiltInIcon = data.icon === "litheness";+ const iconName = data.icon === "litheness" || data.icons?.some(icon => icon.name === data.icon) ? data.icon : "litheness";+ const isBuiltInIcon = iconName === "litheness";const iconScriptElement = document.getElementById("iconScript");const iconDefaultScriptElement = document.getElementById("iconDefaultScript");// 不能使用 data.iconVer,因为其他主题也需要加载默认图标,此时 data.iconVer 为其他图标的版本号const iconDefaultURL = `/appearance/icons/litheness/icon.js?v=${Constants.SIYUAN_VERSION}`;- const iconThirdURL = `/appearance/icons/${data.icon}/icon.js?v=${data.iconVer}`;+ const iconThirdURL = `/appearance/icons/${iconName}/icon.js?v=${appearancePackageVersion("icons", iconName, data.iconVer)}`;if ((isBuiltInIcon && iconDefaultScriptElement && iconDefaultScriptElement.getAttribute("src").startsWith(iconDefaultURL)) ||- (!isBuiltInIcon && iconScriptElement && iconScriptElement.getAttribute("src").startsWith(iconThirdURL))) {+ (!isBuiltInIcon && iconScriptElement && iconScriptElement.getAttribute("src") === iconThirdURL)) {// 第三方图标切换到默认 lithenessif (isBuiltInIcon) {iconScriptElement?.remove();@@ -235,21 +273,22 @@ export const loadAssets = (appearance: Config.IAppearance) => {}});}+ await Promise.all(scriptLoads);return;}- addScript(iconDefaultURL, "iconDefaultScript").then(() => {+ scriptLoads.push(addScript(iconDefaultURL, "iconDefaultScript").then(async () => {iconScriptElement?.remove();if (!isBuiltInIcon) {- addScript(iconThirdURL, "iconScript").then(() => {- Array.from(document.body.children).forEach((item, index) => {- if (item.tagName === "svg" &&- index !== 0 && !item.getAttribute("data-name") && "iconsLitheness" !== item.id) {- item.remove();- }- });+ await addScript(iconThirdURL, "iconScript");+ Array.from(document.body.children).forEach((item, index) => {+ if (item.tagName === "svg" &&+ index !== 0 && !item.getAttribute("data-name") && "iconsLitheness" !== item.id) {+ item.remove();+ }});}- });+ }));+ await Promise.all(scriptLoads);};export const initAssets = () => {@@ -272,24 +311,27 @@ export const initAssets = () => {}fetchPost("/api/system/setAppearanceMode", {mode: OSTheme === "light" ? 0 : 1- }, async response => {- const nextAppearance = response.data.appearance as Config.IAppearance;- if (shouldUnloadThemeScript(window.siyuan.config.appearance, nextAppearance, getFrontend()) &&- !await unloadThemeScript()) {- /// #if !MOBILE- exportLayout({- cb() {- window.location.reload();- },- errorExit: false,- });- /// #else- window.location.reload();- /// #endif- return;- }- window.siyuan.config.appearance = nextAppearance;- loadAssets(nextAppearance);+ }, response => {+ void enqueueAppearanceUpdate(async () => {+ const nextAppearance = response.data.appearance as Config.IAppearance;+ if (shouldUnloadThemeScript(window.siyuan.config.appearance, nextAppearance, getFrontend()) &&+ !await unloadThemeScript()) {+ markAppearanceReloadPending();+ /// #if !MOBILE+ exportLayout({+ cb() {+ window.location.reload();+ },+ errorExit: false,+ });+ /// #else+ window.location.reload();+ /// #endif+ return;+ }+ window.siyuan.config.appearance = nextAppearance;+ await loadAssets(nextAppearance);+ });});});};diff --git a/app/src/util/themeCompatibility.test.ts b/app/src/util/themeCompatibility.test.tsindex d215679783..c6073776ab 100644--- a/app/src/util/themeCompatibility.test.ts+++ b/app/src/util/themeCompatibility.test.ts@@ -38,9 +38,21 @@ describe("theme frontend compatibility", () => {assert.equal(getCurrentAppearanceTheme(appearance({mode: 1}))?.name, "dark-theme");});- it("falls back according to the current frontend when theme metadata is unavailable", () => {- assert.equal(isCurrentThemeSupported(appearance({lightThemes: []}), "mobile"), false);- assert.equal(isCurrentThemeSupported(appearance({lightThemes: []}), "desktop"), true);+ it("does not load a missing custom theme while preserving its selection", () => {+ for (const frontend of ["desktop", "desktop-window", "browser-desktop", "mobile", "browser-mobile"]) {+ const missing = appearance({lightThemes: []});+ assert.equal(isCurrentThemeSupported(missing, frontend), false);+ assert.equal(isCurrentThemeSupported(appearance({lightThemes: undefined}), frontend), false);+ assert.equal(isCurrentThemeSupported(appearance({mode: 1, darkThemes: []}), frontend), false);+ assert.equal(missing.themeLight, "light-theme");+ }+ });++ it("keeps built-in themes available without package metadata", () => {+ for (const frontend of ["desktop", "browser-desktop", "mobile", "browser-mobile"]) {+ assert.equal(isCurrentThemeSupported(appearance({themeLight: "daylight", lightThemes: []}), frontend), true);+ assert.equal(isCurrentThemeSupported(appearance({mode: 1, themeDark: "midnight", darkThemes: []}), frontend), true);+ }});it("uses each mode's frontend declaration", () => {@@ -63,6 +75,7 @@ describe("theme script lifecycle", () => {lightThemes: [{name: "light-theme", label: "Light", frontends: ["mobile"]}],});assert.equal(shouldUnloadThemeScript(previous, appearance(), "mobile"), true);+ assert.equal(shouldUnloadThemeScript(appearance(), appearance({lightThemes: []}), "desktop"), true);});it("keeps a compatible unchanged script", () => {diff --git a/app/src/util/themeCompatibility.ts b/app/src/util/themeCompatibility.tsindex d95bcce27e..efab90583b 100644--- a/app/src/util/themeCompatibility.ts+++ b/app/src/util/themeCompatibility.ts@@ -22,7 +22,12 @@ export const getCurrentThemeName = (appearance: Config.IAppearance) => {};export const isCurrentThemeSupported = (appearance: Config.IAppearance, frontend: string) => {- return isThemeFrontendSupported(getCurrentAppearanceTheme(appearance)?.frontends, frontend);+ const name = getCurrentThemeName(appearance);+ if (name === "daylight" || name === "midnight") {+ return true;+ }+ const theme = getCurrentAppearanceTheme(appearance);+ return !!theme && isThemeFrontendSupported(theme.frontends, frontend);};export const shouldUnloadThemeScript = (diff --git a/app/src/window/index.ts b/app/src/window/index.tsindex 42641d8737..fcd53000aa 100644--- a/app/src/window/index.ts+++ b/app/src/window/index.ts@@ -28,7 +28,7 @@ import {loadPlugins} from "../plugin/loader";import {applyPluginReload, syncGlobalPluginConfig} from "../plugin/globalState";import {hideAllElements} from "../protyle/ui/hideElements";import {reloadEmoji} from "../emoji";-import {appearanceConfigApi} from "../config/tabs/appearanceRuntime";+import {appearanceConfigApi, refreshAppearance} from "../config/tabs/appearanceRuntime";import {renderSnippet} from "../config/util/snippets";import {refreshThemeStyle, reloadInlineStyles, setBodyHighlight} from "../util/assets";import {reloadSync} from "../util/reloadSync";@@ -64,6 +64,9 @@ class App {case "setAppearance":appearanceConfigApi.apply(data.data);break;+ case "refreshAppearance":+ void refreshAppearance(data.data);+ break;case "reloadInlineStyles":void reloadInlineStyles();break;diff --git a/docs/APPEARANCE-SYNC.md b/docs/APPEARANCE-SYNC.mdnew file mode 100644index 0000000000..4b10344b9b--- /dev/null+++ b/docs/APPEARANCE-SYNC.md@@ -0,0 +1,215 @@+# Theme and icon synchronization++[中文](APPEARANCE-SYNC.zh-CN.md)++Related issue: https://github.com/siyuan-note/siyuan/issues/18883++## Feature scope++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.++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`.++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.++## User interaction++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.++`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.++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.++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.++## Data and storage++### Directories and package state++| 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; the package directory is absent. 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.++## 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:++```text+go test . -run ^$ -bench ^BenchmarkAppearanceHistory$ -benchtime=1x -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.diff --git a/docs/APPEARANCE-SYNC.zh-CN.md b/docs/APPEARANCE-SYNC.zh-CN.mdnew file mode 100644index 0000000000..09036f3418--- /dev/null+++ b/docs/APPEARANCE-SYNC.zh-CN.md@@ -0,0 +1,207 @@+# 主题和图标同步++[English](APPEARANCE-SYNC.md)++对应需求:https://github.com/siyuan-note/siyuan/issues/18883++## 功能范围++第三方主题和图标以完整包为单位参与数据同步、快照、安装、更新和卸载。桌面主窗口、独立窗口和移动前端共用内核实现及资源 URL。旧客户端可以继续同步笔记,并将内部外观归档作为普通文件运输;外观包的安装、合并和还原由支持此功能的客户端完成。++明亮主题、暗黑主题、图标、模式及跟随系统等选择保存在各设备的 `conf/conf.json` 中,不随包安装而自动切换。内置 `daylight`、`midnight` 和 `litheness` 使用应用随附资源,不进入第三方包同步目录,同名数据目录不能覆盖内置资源。++`theme.json` 和 `icon.json` 不增加同步开关。主题仍遵守 `frontends`,缺省或空值不支持移动前端,`all` 表示所有前端;运行时同时检查 `minAppVersion`。普通文档和其他数据继续使用原有文件级同步规则。++## 用户交互++安装、更新或卸载包后,同步将完整版本或删除记录传播到其他设备。其他设备收到包不会改变其本机外观选择;当前使用的包被删除或与本机不兼容时,界面回退到内置外观。++用户可以在本机编辑包内 CSS、脚本、图片等文件。建立快照前扫描这些修改并更新完整性记录,正常运行及导出不自动重写摘要。未完成安装、同步恢复或旧版延期资源涉及的包暂不可用时,界面显示内置外观并保留本机原选择,恢复完成后刷新。++同版本号的内容更新也会刷新当前资源。主题脚本继续执行卸载生命周期;无法安全卸载时重新加载界面。忽略规则可以排除完整包,但不能通过只排除部分文件或单独排除安装状态来生成不完整包。++## 数据与存储++### 目录与安装状态++| 路径 | 用途 | 同步范围 |+|---|---|---|+| `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` | 本机外观选择 | 不参与包同步 |++主题和图标不再更新单文件 `storage/bazaar.json`;旧文件只作为迁移安装时间及来源信息的后备,其他类型集市包仍使用原有机制。每个包的状态属于内核内部格式,不是集市作者清单:++```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` 末尾持久化带显式版本的受管注释块:++```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` 引用包含事件集合的完整工作区快照,沿用云端普通标签机制保留恢复材料。必须先上传完整对象和快照,再发布恢复引用,最后发布最新引用。新客户端遇到旧客户端还原早期快照时,从恢复引用补回事件,防止丢失删除记录。++恢复引用不得指向只含外观的快照,避免旧客户端还原它时误删笔记。同名既有用户标签必须保留并报冲突,不能直接覆盖。新客户端仅对经过认证且具有本协议格式标记的内部标签隐藏显示、禁止手工覆盖或删除,并从用户备份数量中扣除;同名普通用户标签仍可见、可操作。++云端恢复引用合并目标工作区快照及此前已经公开的云端事件,不得从本机恢复引用复制尚未分享的私有事件。如果最新快照只缺少被排除的事件,且没有新事件需要发布,则保留原云端恢复引用并继续同步笔记。++旧客户端可能显示该标签,并按原规则占用一个备份名额;笔记同步不受此限制。内部恢复引用的更新不使用用户手动备份数量配额。内部事件保留已经分享的完整版本,存储占用随包更新次数增长;云端可复用未变化的分块,本机归档仍保存完整包,当前没有自动压缩事件历史的策略。普通历史清理不会删除恢复引用仍使用的事件。主动删除内部恢复标签及全部相关历史会丢失恢复材料,不能再保证恢复已删除事件。++恢复引用先于最新引用发布的保证以既有云锁正常串行为前提。现有锁采用先读后写,仍存在极端同时抢锁或失锁的风险;该功能不扩展服务端锁协议,不保证任意失锁及随后清理仍保留所有引用。++## 验证范围++### 回归覆盖++回归范围包含安装、迁移、手工修改、显式重装、未知版本保留、同秒并发更新及删除、完整冲突历史、整包与部分忽略、忽略范围内损坏负载和私有事件保护、完整与按需下载、单向同步、局域网认证及流量计数、中断恢复、快照回退、单文件还原限制、符号链接、同版本资源重载及默认回退。++内核检查 `bazaar`、`util`、`model`、`server` 的相关回归,DejaVu 检查外观、资源、快照、备份、认证、云锁及 `lansync` 测试。缓存回归覆盖保留修改时间的闭合文件改写、密文损坏、错误密钥、有界缓存及共享分块并发读写。前端在 `app/` 中运行相关单元测试及 `pnpm run lint`。++在 DejaVu 根目录运行历史基准:++```text+go test . -run ^$ -bench ^BenchmarkAppearanceHistory$ -benchtime=1x -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/README.md b/docs/README.mdindex fcf1025d65..a872369e27 100644--- a/docs/README.md+++ b/docs/README.md@@ -7,6 +7,7 @@| Document | English | 中文 ||---|---|---|| Kernel API type contracts | [API-CONTRACTS.md](API-CONTRACTS.md) | [API-CONTRACTS.zh-CN.md](API-CONTRACTS.zh-CN.md) |+| Theme and icon synchronization | [APPEARANCE-SYNC.md](APPEARANCE-SYNC.md) | [APPEARANCE-SYNC.zh-CN.md](APPEARANCE-SYNC.zh-CN.md) || On-demand asset downloads | [ASSET-DOWNLOAD.md](ASSET-DOWNLOAD.md) | [ASSET-DOWNLOAD.zh-CN.md](ASSET-DOWNLOAD.zh-CN.md) || Encrypted notebooks | [ENCRYPTED-NOTEBOOK.md](ENCRYPTED-NOTEBOOK.md) | [ENCRYPTED-NOTEBOOK.zh-CN.md](ENCRYPTED-NOTEBOOK.zh-CN.md) || Pinned documents | [PINNED-DOCUMENTS.md](PINNED-DOCUMENTS.md) | [PINNED-DOCUMENTS.zh-CN.md](PINNED-DOCUMENTS.zh-CN.md) |@@ -23,7 +24,7 @@ Except for public API documentation, maintain paired English `NAME.md` and Simpl## Feature design structure-On-demand assets, encrypted notebooks, pinned documents, tab blocks, and template management use these second-level sections. Place topic-specific details under third-level headings within the appropriate section.+Theme and icon synchronization, on-demand assets, encrypted notebooks, pinned documents, tab blocks, and template management use these second-level sections. Place topic-specific details under third-level headings within the appropriate section.| Section | Content ||---|---|diff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.mdindex ef6b0a7024..8866d16b1d 100644--- a/docs/README.zh-CN.md+++ b/docs/README.zh-CN.md@@ -7,6 +7,7 @@| 文档 | English | 中文 ||---|---|---|| 内核接口类型契约 | [API-CONTRACTS.md](API-CONTRACTS.md) | [API-CONTRACTS.zh-CN.md](API-CONTRACTS.zh-CN.md) |+| 主题和图标同步 | [APPEARANCE-SYNC.md](APPEARANCE-SYNC.md) | [APPEARANCE-SYNC.zh-CN.md](APPEARANCE-SYNC.zh-CN.md) || 资源文件按需下载 | [ASSET-DOWNLOAD.md](ASSET-DOWNLOAD.md) | [ASSET-DOWNLOAD.zh-CN.md](ASSET-DOWNLOAD.zh-CN.md) || 加密笔记本 | [ENCRYPTED-NOTEBOOK.md](ENCRYPTED-NOTEBOOK.md) | [ENCRYPTED-NOTEBOOK.zh-CN.md](ENCRYPTED-NOTEBOOK.zh-CN.md) || 文档树面板置顶区 | [PINNED-DOCUMENTS.md](PINNED-DOCUMENTS.md) | [PINNED-DOCUMENTS.zh-CN.md](PINNED-DOCUMENTS.zh-CN.md) |@@ -23,7 +24,7 @@## 功能设计文档结构-资源按需下载、加密笔记本、文档置顶、页签块和模板管理使用以下二级章节,专题细节置于对应章节的三级标题下。+主题和图标同步、资源按需下载、加密笔记本、文档置顶、页签块和模板管理使用以下二级章节,专题细节置于对应章节的三级标题下。| 章节 | 内容 ||---|---|diff --git a/docs/WORKSPACE.md b/docs/WORKSPACE.mdindex 6ce69c82d9..2fa6aeb812 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/ # Installed themes, icons, and language resources+│ ├── appearance/ # Built-in appearance resources and local migration backups│ ├── 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,6 +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│ ├── emojis/ # Custom emoji│ ├── snippets/ # Code snippets (CSS/JS)│ ├── public/ # Static resources@@ -80,7 +82,7 @@ Workspace-root entries:The first level of `data/` mixes two kinds of entries:-1. **Fixed data directories:** `.siyuan/`, `assets/`, `templates/`, `widgets/`, `plugins/`, `emojis/`, `snippets/`, `public/`, `storage/`.+1. **Fixed data directories:** `.siyuan/`, `assets/`, `templates/`, `widgets/`, `plugins/`, `themes/`, `icons/`, `emojis/`, `snippets/`, `public/`, `storage/`.2. **Notebook directories:** each is a folder named with the notebook ID.### Reserved-filename list@@ -98,6 +100,8 @@ 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.+`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.### How a notebook is recognizeddiff --git a/docs/WORKSPACE.zh-CN.md b/docs/WORKSPACE.zh-CN.mdindex 3fba851e28..82906e3316 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,6 +30,8 @@ SiYuan 工作区是一棵**自描述**的目录树:笔记本、文档和资源│ ├── templates/ # 全局模板(.md)│ ├── widgets/ # 挂件│ ├── plugins/ # 插件+│ ├── themes/ # 从同步包还原的本机主题目录+│ ├── icons/ # 从同步包还原的本机图标目录│ ├── emojis/ # 自定义 emoji│ ├── snippets/ # 代码片段(CSS/JS)│ ├── public/ # 静态资源@@ -80,7 +82,7 @@ SiYuan 工作区是一棵**自描述**的目录树:笔记本、文档和资源`data/` 第一层是两类东西混排:-1. **固定数据目录**:`.siyuan/`、`assets/`、`templates/`、`widgets/`、`plugins/`、`emojis/`、`snippets/`、`public/`、`storage/`。+1. **固定数据目录**:`.siyuan/`、`assets/`、`templates/`、`widgets/`、`plugins/`、`themes/`、`icons/`、`emojis/`、`snippets/`、`public/`、`storage/`。2. **笔记本目录**:每个是一个以笔记本 ID 命名的文件夹。### 保留文件名清单@@ -98,6 +100,8 @@ func IsReservedFilename(baseName string) bool {### 持久化数据与可重建索引+第三方主题位于 `data/themes/<name>/`,图标包位于 `data/icons/<name>/`。完整包内容、更新和卸载通过 `data/storage/appearance-v1/` 中不可变的内部归档参与数据同步及快照,本机主题和图标目录不直接进入普通文件同步。各设备在 `conf/conf.json` 中独立保存外观选择。内置主题和图标仍属于程序资源。即使资源文件设置为按需下载,外观包资源也会完整下载。旧客户端可以继续同步笔记,新客户端负责还原外观包及处理冲突。迁移会保留原有本地文件供恢复。迁移和冲突行为详见[外观同步](APPEARANCE-SYNC.zh-CN.md)。+`data/storage/` 保存属性视图定义和插件状态等持久化结构化数据。`temp/` 中的 SQLite 文件是派生索引和缓存:普通笔记本使用全局 `siyuan.db` 和 `blocktree.db`,每个已解锁的加密笔记本则使用独立的 SQLCipher 数据库。因此删除或重建索引不能与删除源 `.sy`、资源文件或数据库定义文件混为一谈。### 笔记本的判定规则diff --git a/kernel/bazaar/appearance_runtime.go b/kernel/bazaar/appearance_runtime.gonew file mode 100644index 0000000000..8676a65288--- /dev/null+++ b/kernel/bazaar/appearance_runtime.go@@ -0,0 +1,76 @@+// 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.gonew file mode 100644index 0000000000..0adaaa8850--- /dev/null+++ b/kernel/bazaar/appearance_state.go@@ -0,0 +1,619 @@+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 {+ 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.gonew file mode 100644index 0000000000..e1d8066529--- /dev/null+++ b/kernel/bazaar/appearance_state_test.go@@ -0,0 +1,462 @@+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 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)+ if err := PublishAppearancePackage(source, "themes", "example", PackageInfo{InstallTime: 1}, false, update); 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"} {+ 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)+ }+ 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)+ }+ })+ }+}++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 0531b7502c..683477d7a8 100644--- a/kernel/bazaar/install.go+++ b/kernel/bazaar/install.go@@ -109,14 +109,16 @@ func InstallPackage(repoURL, repoHash, repoRef, installPath, systemID, pkgType,if err != nil {return err}- if err = installPackage(data, installPath, pkgType, packageName, update); err != nil {+ if err = installPackageWithSource(data, installPath, pkgType, packageName, update, repoURL, repoRef); err != nil {return err}RemoveInstalledPackageSizeCache(pkgType, packageName)// 记录首次安装时间或最近更新时间now := time.Now()- recordPackageOperationTime(pkgType, packageName, now, fallbackInstallTime, update, repoURL, repoRef)+ if !isAppearanceKind(pkgType) {+ recordPackageOperationTime(pkgType, packageName, now, fallbackInstallTime, update, repoURL, repoRef)+ }// 文件夹的修改时间设置为当前操作时间if err = os.Chtimes(installPath, now, now); err != nil {@@ -128,6 +130,10 @@ 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 {@@ -182,12 +188,44 @@ func installPackage(data []byte, installPath, pkgType, packageName string, updatreturn fmt.Errorf("marketplace package name mismatch: expected [%s], got [%s]", packageName, pkg.Name)}- if err = replacePackageDirectory(srcPath, installPath, update); err != nil {+ if err = publishInstalledPackage(srcPath, installPath, pkgType, packageName, update, repoURL, repoRef); 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 回去。@@ -252,13 +290,15 @@ func InstallLocalPackage(sourcePath, installPath, pkgType, packageName string, uif info, statErr := os.Stat(installPath); statErr == nil {fallbackInstallTime = info.ModTime()}- if err = replacePackageDirectory(sourcePath, installPath, update); err != nil {+ if err = publishInstalledPackage(sourcePath, installPath, pkgType, packageName, update, "", ""); err != nil {return}RemoveInstalledPackageSizeCache(pkgType, packageName)now := time.Now()- recordPackageOperationTime(pkgType, packageName, now, fallbackInstallTime, update, "", "")+ if !isAppearanceKind(pkgType) {+ 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)}@@ -267,6 +307,12 @@ 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 78f47d9a23..5f94c40c20 100644--- a/kernel/bazaar/install_test.go+++ b/kernel/bazaar/install_test.go@@ -22,6 +22,7 @@ import ("net/http/httptest""os""path/filepath"+ "reflect""testing""github.com/siyuan-note/siyuan/kernel/util"@@ -279,3 +280,78 @@ 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 5768ad9b59..6275d0c8ef 100644--- a/kernel/bazaar/installed.go+++ b/kernel/bazaar/installed.go@@ -331,6 +331,9 @@ 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)@@ -369,6 +372,14 @@ 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()@@ -388,6 +399,9 @@ 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()@@ -416,6 +430,20 @@ 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 {@@ -441,6 +469,9 @@ 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 c93a97c1d6..6b4478b06a 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-20260914113714-464364dd8fad+ github.com/siyuan-note/dejavu v0.0.0-20260917132718-25fabf493e2egithub.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 7b43baf0e4..2b72aede35 100644--- a/kernel/go.sum+++ b/kernel/go.sum@@ -494,6 +494,8 @@ github.com/siyuan-note/dejavu v0.0.0-20260913022125-a81c0754dcb7 h1:+NSzydozQJsqgithub.com/siyuan-note/dejavu v0.0.0-20260913022125-a81c0754dcb7/go.mod h1:ixj6rxm+wkjoV8pBDGbuCyfMiPQh3MlxBwHG5OvtEQU=github.com/siyuan-note/dejavu v0.0.0-20260914113714-464364dd8fad h1:RsPhy4gxwu/gm/Y4grTGb5RoOkhLiCKampXiPK8xMlQ=github.com/siyuan-note/dejavu v0.0.0-20260914113714-464364dd8fad/go.mod h1:ixj6rxm+wkjoV8pBDGbuCyfMiPQh3MlxBwHG5OvtEQU=+github.com/siyuan-note/dejavu v0.0.0-20260917132718-25fabf493e2e h1:T+CINyHH37GINJmlAiRD3EeTiUI9x7PYtYV9gfoe+a8=+github.com/siyuan-note/dejavu v0.0.0-20260917132718-25fabf493e2e/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 f389bb25bf..5ef68c0047 100644--- a/kernel/model/appearance.go+++ b/kernel/model/appearance.go@@ -33,6 +33,11 @@ import (func InitAppearance() {util.SetBootDetails(Conf.Language(302))+ if err := MigrateAppearancePackages(); err != nil {+ logging.LogErrorf("migrate appearance packages failed: %s", err)+ util.ReportFileSysFatalError(err)+ return+ }if err := os.Mkdir(util.AppearancePath, 0755); err != nil && !os.IsExist(err) {logging.LogErrorf("create appearance folder [%s] failed: %s", util.AppearancePath, err)util.ReportFileSysFatalError(err)@@ -46,26 +51,44 @@ func InitAppearance() {return}- LoadThemes()- LoadIcons()+ refreshAppearanceConfig()+ util.InitEmojiChars()+}++// refreshAppearanceConfig 按完整可用的包刷新本机外观选择,缺失或不兼容时使用内置资源。+func refreshAppearanceConfig() {+ lockPath := filepath.Join(util.DataDir, ".siyuan-appearance")+ filelock.Lock(lockPath)+ defer filelock.Unlock(lockPath)+ runtimeState := newAppearanceRuntimeState()+ loadThemes(runtimeState)+ loadIcons(runtimeState)+ var reloadThemes, reloadIcons boolConf.m.Lock()- if !containTheme(Conf.Appearance.ThemeDark, Conf.Appearance.DarkThemes) {+ if !containTheme(Conf.Appearance.ThemeDark, Conf.Appearance.DarkThemes) &&+ !runtimeState.preserveSelection("themes", Conf.Appearance.ThemeDark) {Conf.Appearance.ThemeDark = "midnight"- Conf.Appearance.ThemeJS = false+ reloadThemes = true}- if !containTheme(Conf.Appearance.ThemeLight, Conf.Appearance.LightThemes) {+ if !containTheme(Conf.Appearance.ThemeLight, Conf.Appearance.LightThemes) &&+ !runtimeState.preserveSelection("themes", Conf.Appearance.ThemeLight) {Conf.Appearance.ThemeLight = "daylight"- Conf.Appearance.ThemeJS = false+ reloadThemes = true}- if !containIcon(Conf.Appearance.Icon, Conf.Appearance.Icons) {+ if !containIcon(Conf.Appearance.Icon, Conf.Appearance.Icons) &&+ !runtimeState.preserveSelection("icons", Conf.Appearance.Icon) {Conf.Appearance.Icon = "litheness"+ reloadIcons = true}Conf.m.Unlock()-+ if reloadThemes {+ loadThemes(runtimeState)+ }+ if reloadIcons {+ loadIcons(runtimeState)+ }Conf.Save()-- util.InitEmojiChars()}func SetIcon(icon string) error {@@ -119,7 +142,7 @@ func SetTheme(theme string, modes []int, appearanceMode string) error {func containTheme(name string, themes []*conf.AppearanceTheme) bool {for _, t := range themes {- if t.Name == name {+ if t != nil && t.Name == name {return true}}@@ -128,15 +151,46 @@ func containTheme(name string, themes []*conf.AppearanceTheme) bool {func containIcon(name string, icons []*conf.AppearanceIcon) bool {for _, i := range icons {- if i.Name == name {+ if i != nil && i.Name == name {return true}}return false}+// appearancePackageNames 保留内置包,并从数据目录读取第三方包,避免同名包覆盖内置资源。+func appearancePackageNames(kind string) ([]string, error) {+ root, names := util.ThemesPath, []string{"daylight", "midnight"}+ if kind == "icons" {+ root, names = util.IconsPath, []string{"litheness"}+ }+ dirs, err := os.ReadDir(root)+ if os.IsNotExist(err) {+ return names, nil+ }+ if err != nil {+ return nil, err+ }+ for _, dir := range dirs {+ name := dir.Name()+ if !util.IsDirRegularOrSymlink(dir) || !bazaar.IsValidPackageName(name) ||+ (kind == "themes" && isBuiltInTheme(name)) || (kind == "icons" && isBuiltInIcon(name)) {+ continue+ }+ names = append(names, name)+ }+ return names, nil+}+func LoadThemes() {- themeDirs, err := os.ReadDir(util.ThemesPath)+ 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)util.ReportFileSysFatalError(err)@@ -150,13 +204,17 @@ func LoadThemes() {mode := Conf.Appearance.ModethemeLight := Conf.Appearance.ThemeLightthemeDark := Conf.Appearance.ThemeDark- for _, themeDir := range themeDirs {- if !util.IsDirRegularOrSymlink(themeDir) {- continue+ for _, 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+ }}- name := themeDir.Name()- themeConf, parseErr := bazaar.ParsePackageJSON(filepath.Join(util.ThemesPath, name, "theme.json"))- if nil != parseErr || !bazaar.IsValidInstalledPackage(themeConf, name) {+ 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")) {continue}@@ -199,18 +257,22 @@ func LoadThemes() {if 0 == mode {if themeLight == name {themeVer = themeConf.Version- themeJS = gulu.File.IsExist(filepath.Join(util.ThemesPath, name, "theme.js"))+ themeJS = gulu.File.IsExist(filepath.Join(themePath, "theme.js"))}} else {if themeDark == name {themeVer = themeConf.Version- themeJS = gulu.File.IsExist(filepath.Join(util.ThemesPath, name, "theme.js"))+ themeJS = gulu.File.IsExist(filepath.Join(themePath, "theme.js"))}}}- lightThemes = append([]*conf.AppearanceTheme{daylightTheme}, lightThemes...)- darkThemes = append([]*conf.AppearanceTheme{midnightTheme}, darkThemes...)+ if daylightTheme != nil {+ lightThemes = append([]*conf.AppearanceTheme{daylightTheme}, lightThemes...)+ }+ if midnightTheme != nil {+ darkThemes = append([]*conf.AppearanceTheme{midnightTheme}, darkThemes...)+ }Conf.m.Lock()Conf.Appearance.DarkThemes = darkThemes@@ -221,7 +283,14 @@ func LoadThemes() {}func LoadIcons() {- iconDirs, err := os.ReadDir(util.IconsPath)+ 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)util.ReportFileSysFatalError(err)@@ -231,13 +300,17 @@ func LoadIcons() {var icons []*conf.AppearanceIconvar iconVer stringcurrentIcon := Conf.Appearance.Icon- for _, iconDir := range iconDirs {- if !util.IsDirRegularOrSymlink(iconDir) {- continue+ for _, 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+ }}- name := iconDir.Name()- iconConf, err := bazaar.ParsePackageJSON(filepath.Join(util.IconsPath, name, "icon.json"))- if err != nil || !bazaar.IsValidInstalledPackage(iconConf, name) {+ 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")) {continue}t := &conf.AppearanceIcon{Name: name}@@ -303,7 +376,7 @@ func currentThemeDir() string {if "" == themeName || "." == themeName || ".." == themeName || filepath.Base(themeName) != themeName {return ""}- return filepath.Clean(filepath.Join(util.ThemesPath, themeName))+ return util.AppearancePackagePath("themes", themeName)}func broadcastRefreshThemeIfCurrent(themeCssPath string) {@@ -312,8 +385,7 @@ func broadcastRefreshThemeIfCurrent(themeCssPath string) {}// 只处理主题根目录中的 theme.cssthemeDir := filepath.Clean(filepath.Dir(themeCssPath))- themesRoot := filepath.Clean(util.ThemesPath)- if themeDir != filepath.Join(themesRoot, filepath.Base(themeDir)) {+ if themeDir != util.AppearancePackagePath("themes", filepath.Base(themeDir)) {return}themeName := isCurrentUseTheme(themeCssPath)diff --git a/kernel/model/appearance_export.go b/kernel/model/appearance_export.gonew file mode 100644index 0000000000..4654844ca8--- /dev/null+++ b/kernel/model/appearance_export.go@@ -0,0 +1,65 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package model++import (+ "fmt"+ "path/filepath"++ "github.com/siyuan-note/filelock"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// 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},+ }+ for kind, names := range packages {+ copied := map[string]bool{}+ for _, name := range names {+ if name == "" || copied[name] {+ continue+ }+ from := util.AppearancePackagePath(kind, name)+ 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 {+ return err+ }+ to := filepath.Join(savePath, "appearance", kind, name)+ if err = filelock.Copy(from, to); err != nil {+ return fmt.Errorf("copy appearance package [%s/%s]: %w", kind, name, err)+ }+ copied[name] = true+ }+ }+ return nil+}diff --git a/kernel/model/appearance_migration.go b/kernel/model/appearance_migration.gonew file mode 100644index 0000000000..4d0d9a593d--- /dev/null+++ b/kernel/model/appearance_migration.go@@ -0,0 +1,124 @@+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.gonew file mode 100644index 0000000000..03562a970e--- /dev/null+++ b/kernel/model/appearance_migration_test.go@@ -0,0 +1,199 @@+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.gonew file mode 100644index 0000000000..d7dfcb07a4--- /dev/null+++ b/kernel/model/appearance_packages_test.go@@ -0,0 +1,188 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.++package model++import (+ "encoding/json"+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/siyuan-note/filelock"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func setupAppearancePackagesTest(t *testing.T) {+ t.Helper()+ oldAppearance, oldThemes, oldIcons, oldMode, oldConf := util.AppearancePath, util.ThemesPath, util.IconsPath, util.Mode, Conf+ oldDataDir := util.DataDir+ oldConfDir := util.ConfDir+ oldRepoDir := util.RepoDir+ t.Cleanup(func() {+ util.AppearancePath, util.ThemesPath, util.IconsPath, util.Mode, Conf = oldAppearance, oldThemes, oldIcons, oldMode, oldConf+ util.DataDir = oldDataDir+ util.ConfDir = oldConfDir+ util.RepoDir = oldRepoDir+ })+ root := t.TempDir()+ util.AppearancePath = filepath.Join(root, "conf", "appearance")+ util.ConfDir = filepath.Join(root, "conf")+ util.RepoDir = filepath.Join(root, "repo")+ util.DataDir = filepath.Join(root, "data")+ util.ThemesPath, util.IconsPath = filepath.Join(root, "data", "themes"), filepath.Join(root, "data", "icons")+ util.Mode = "prod"+ Conf = NewAppConf()+ Conf.Appearance = conf.NewAppearance()+ for _, name := range []string{"daylight", "midnight", "custom"} {+ writeAppearanceTestPackage(t, "themes", name, "1.0.0", "")+ }+ for _, name := range []string{"litheness", "custom"} {+ writeAppearanceTestPackage(t, "icons", name, "1.0.0", "")+ }+}++func writeAppearanceTestFile(t *testing.T, path, content string) {+ t.Helper()+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(path, []byte(content), 0644); err != nil {+ t.Fatal(err)+ }+}++func writeAppearanceTestPackage(t *testing.T, kind, name, version, minVersion string) {+ t.Helper()+ manifest, entry := "theme.json", "theme.css"+ if kind == "icons" {+ manifest, entry = "icon.json", "icon.js"+ }+ data, err := json.Marshal(map[string]any{+ "name": name, "version": version, "minAppVersion": minVersion, "modes": []string{"light", "dark"},+ })+ if err != nil {+ t.Fatal(err)+ }+ root := util.AppearancePackagePath(kind, name)+ writeAppearanceTestFile(t, filepath.Join(root, manifest), string(data))+ writeAppearanceTestFile(t, filepath.Join(root, entry), "resource "+name)+}++func TestLoadAppearancePackagesPreservesBuiltInsAndChecksVersion(t *testing.T) {+ setupAppearancePackagesTest(t)+ writeAppearanceTestPackage(t, "themes", "future", "2.0.0", "999.0.0")+ writeAppearanceTestPackage(t, "icons", "future", "2.0.0", "999.0.0")+ writeAppearanceTestFile(t, filepath.Join(util.ThemesPath, "daylight", "theme.json"), `{"name":"daylight","version":"99.0.0"}`)+ writeAppearanceTestFile(t, filepath.Join(util.IconsPath, "litheness", "icon.json"), `{"name":"litheness","version":"99.0.0"}`)+ Conf.Appearance.ThemeLight, Conf.Appearance.Icon = "custom", "custom"+ LoadThemes()+ LoadIcons()+ if !containTheme("daylight", Conf.Appearance.LightThemes) || !containTheme("midnight", Conf.Appearance.DarkThemes) ||+ !containIcon("litheness", Conf.Appearance.Icons) {+ t.Fatal("built-in packages were not retained")+ }+ if !containTheme("custom", Conf.Appearance.LightThemes) || !containIcon("custom", Conf.Appearance.Icons) {+ t.Fatal("data packages were not loaded")+ }+ if containTheme("future", Conf.Appearance.LightThemes) || containIcon("future", Conf.Appearance.Icons) {+ t.Fatal("packages requiring a newer application were loaded")+ }+ if Conf.Appearance.ThemeLight != "custom" || Conf.Appearance.Icon != "custom" ||+ Conf.Appearance.ThemeVer != "1.0.0" || Conf.Appearance.IconVer != "1.0.0" {+ t.Fatal("local selection or package version changed unexpectedly")+ }+ if err := os.Remove(filepath.Join(util.IconsPath, "custom", "icon.js")); err != nil {+ t.Fatal(err)+ }+ LoadIcons()+ if containIcon("custom", Conf.Appearance.Icons) {+ t.Fatal("incomplete icon package was loaded")+ }+}++func TestExportAppearancePackagesUsesDataAndCopiesResources(t *testing.T) {+ setupAppearancePackagesTest(t)+ writeAppearanceTestFile(t, filepath.Join(util.ThemesPath, "custom", "assets", "font.woff2"), "font")+ writeAppearanceTestFile(t, filepath.Join(util.IconsPath, "custom", "assets", "image.png"), "image")+ writeAppearanceTestFile(t, filepath.Join(util.AppearancePath, "themes", "custom", "theme.css"), "legacy")+ destination := t.TempDir()+ if err := copyExportAppearance(destination, "custom", "custom"); err != nil {+ t.Fatal(err)+ }+ for name, expected := range map[string]string{+ "themes/custom/theme.css": "resource custom",+ "themes/custom/assets/font.woff2": "font",+ "themes/daylight/theme.css": "resource daylight",+ "themes/midnight/theme.css": "resource midnight",+ "icons/custom/assets/image.png": "image",+ "icons/litheness/icon.js": "resource litheness",+ } {+ data, err := os.ReadFile(filepath.Join(destination, "appearance", name))+ if err != nil || string(data) != expected {+ t.Errorf("%s: got %q, error %v", name, data, err)+ }+ }+}++func TestRefreshAppearanceConfigFallsBackAfterRemoval(t *testing.T) {+ setupAppearancePackagesTest(t)+ writeAppearanceTestFile(t, filepath.Join(util.ThemesPath, "custom", "theme.js"), "script")+ Conf.Appearance.ThemeLight, Conf.Appearance.Icon = "custom", "custom"+ Conf.Appearance.ThemeDark = "missing"+ refreshAppearanceConfig()+ if !Conf.Appearance.ThemeJS || Conf.Appearance.ThemeLight != "custom" || Conf.Appearance.ThemeDark != "midnight" {+ t.Fatal("fallback for an unused mode changed the current theme script")+ }+ if err := os.Remove(filepath.Join(util.ThemesPath, "custom", "theme.json")); err != nil {+ t.Fatal(err)+ }+ writeAppearanceTestPackage(t, "icons", "custom", "2.0.0", "999.0.0")+ refreshAppearanceConfig()+ if Conf.Appearance.ThemeLight != "daylight" || Conf.Appearance.Icon != "litheness" || Conf.Appearance.ThemeJS ||+ Conf.Appearance.ThemeVer != "1.0.0" || Conf.Appearance.IconVer != "1.0.0" {+ 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_runtime.go b/kernel/model/appearance_runtime.gonew file mode 100644index 0000000000..de4704e137--- /dev/null+++ b/kernel/model/appearance_runtime.go@@ -0,0 +1,76 @@+// 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.gonew file mode 100644index 0000000000..23791a7091--- /dev/null+++ b/kernel/model/appearance_runtime_test.go@@ -0,0 +1,184 @@+// 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.gonew file mode 100644index 0000000000..2c43f4f193--- /dev/null+++ b/kernel/model/appearance_sync.go@@ -0,0 +1,87 @@+package model++import (+ "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 将包内容和状态文件的变更归并为需要刷新的包名。+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))+ for _, file := range result.Upserts {+ paths = append(paths, file.Path)+ }+ for _, file := range result.Removes {+ paths = append(paths, file.Path)+ }+ for _, filePath := range paths {+ parts := 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"] {+ themes = append(themes, name)+ }+ for name := range changed["icons"] {+ icons = append(icons, name)+ }+ sort.Strings(themes)+ sort.Strings(icons)+ return+}++// refreshAppearancePackages 只在整包发布之后重建本机外观列表,并通知各前端清除资源缓存。+func refreshAppearancePackages(themes, icons []string) {+ if len(themes)+len(icons) == 0 {+ return+ }+ CloseWatchThemes()+ defer WatchThemes()+ for _, name := range themes {+ bazaar.RemoveInstalledPackageSizeCache("themes", name)+ }+ for _, name := range icons {+ bazaar.RemoveInstalledPackageSizeCache("icons", name)+ }+ refreshAppearanceConfig()+ util.BroadcastByType("main", "refreshAppearance", 0, "", map[string]any{+ "appearance": Conf.Appearance, "themes": themes, "icons": icons,+ "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.gonew file mode 100644index 0000000000..2cce60f07f--- /dev/null+++ b/kernel/model/appearance_sync_test.go@@ -0,0 +1,87 @@+package model++import (+ "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"}}}+ 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/bazaar.go b/kernel/model/bazaar.goindex 9600a97fd3..8f02f8485a 100644--- a/kernel/model/bazaar.go+++ b/kernel/model/bazaar.go@@ -564,7 +564,7 @@ func finishInstall(pkgType string, items []batchInstallItem, themeOptions *Themeif !item.meta.update && nil != themeOptions {// 新安装主题时才自动切换 https://github.com/siyuan-note/siyuan/issues/4966applied := false- theme, err := bazaar.ParsePackageJSON(filepath.Join(util.ThemesPath, item.name, "theme.json"))+ theme, err := bazaar.ParsePackageJSON(filepath.Join(util.AppearancePackagePath("themes", item.name), "theme.json"))if nil == err && nil != theme && nil != theme.Modes {for _, mode := range *theme.Modes {switch mode {@@ -586,13 +586,16 @@ func finishInstall(pkgType string, items []batchInstallItem, themeOptions *Theme}Conf.Appearance.Mode = themeOptions.ModeConf.Appearance.ModeOS = themeOptions.ModeOS- Conf.Appearance.ThemeJS = gulu.File.IsExist(filepath.Join(util.ThemesPath, item.name, "theme.js"))+ Conf.Appearance.ThemeJS = gulu.File.IsExist(filepath.Join(util.AppearancePackagePath("themes", item.name), "theme.js"))Conf.Save()}}- InitAppearance()- WatchThemes()- util.BroadcastByType("main", "setAppearance", 0, "", Conf.Appearance)+ var names []string+ for _, item := range items {+ names = append(names, item.name)+ }+ refreshAppearancePackages(names, nil)+ IncSync()case "icons":for _, item := range items {if !item.meta.update && applyNewAppearance {@@ -601,8 +604,12 @@ func finishInstall(pkgType string, items []batchInstallItem, themeOptions *ThemeConf.Save()}}- InitAppearance()- util.BroadcastByType("main", "setAppearance", 0, "", Conf.Appearance)+ var names []string+ for _, item := range items {+ names = append(names, item.name)+ }+ refreshAppearancePackages(nil, names)+ IncSync()}}@@ -733,12 +740,11 @@ func UninstallPackage(pkgType, packageName string) error {uninstallPluginSet := hashset.New(packageName)PushReloadPlugin(uninstallPluginSet, nil, nil, nil, "", "")case "themes":- InitAppearance()- WatchThemes()- util.BroadcastByType("main", "setAppearance", 0, "", Conf.Appearance)+ refreshAppearancePackages([]string{packageName}, nil)+ IncSync()case "icons":- InitAppearance()- util.BroadcastByType("main", "setAppearance", 0, "", Conf.Appearance)+ refreshAppearancePackages(nil, []string{packageName})+ IncSync()}return nildiff --git a/kernel/model/conf.go b/kernel/model/conf.goindex 335bb3f160..5d19a3ab4b 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -375,8 +375,8 @@ func InitConf() {// v3.7.0 移除了 ant/material 图标包,如果用户之前选择了这两个其中之一,升级后改为 litheness 图标包,避免图标显示异常 https://github.com/siyuan-note/siyuan/issues/7976Conf.Appearance.Icon = "litheness"}- os.RemoveAll(filepath.Join(util.IconsPath, "ant"))- os.RemoveAll(filepath.Join(util.IconsPath, "material"))+ os.RemoveAll(filepath.Join(util.AppearancePath, "icons", "ant"))+ os.RemoveAll(filepath.Join(util.AppearancePath, "icons", "material"))if nil == Conf.UILayout {Conf.UILayout = &conf.UILayout{}}diff --git a/kernel/model/export.go b/kernel/model/export.goindex aed031306f..7d100fec8f 100644--- a/kernel/model/export.go+++ b/kernel/model/export.go@@ -1277,55 +1277,8 @@ func exportMarkdownHTML(id, savePath string, docx, merge bool, mergeHeadingOptioif 1 == Conf.Appearance.Mode {theme = Conf.Appearance.ThemeDark}- // 复制主题文件夹- srcs = []string{"themes/" + theme}- appearancePath := util.AppearancePath- if util.IsSymlinkPath(util.AppearancePath) {- // Support for symlinked theme folder when exporting HTML https://github.com/siyuan-note/siyuan/issues/9173- var readErr error- appearancePath, readErr = filepath.EvalSymlinks(util.AppearancePath)- if nil != readErr {- logging.LogErrorf("readlink [%s] failed: %s", util.AppearancePath, readErr)- return readErr- }- }-- for _, src := range srcs {- from := filepath.Join(appearancePath, src)- to := filepath.Join(savePath, "appearance", src)- if err := filelock.Copy(from, to); err != nil {- logging.LogErrorf("copy appearance from [%s] to [%s] failed: %s", from, savePath, err)- return err- }- }-- // 只复制图标文件夹中的 icon.js 文件- iconName := Conf.Appearance.Icon- // 如果使用的不是内建图标(litheness),需要复制 litheness 作为后备- if iconName != "litheness" && iconName != "" {- srcIconFile := filepath.Join(appearancePath, "icons", "litheness", "icon.js")- toIconDir := filepath.Join(savePath, "appearance", "icons", "litheness")- if err := os.MkdirAll(toIconDir, 0755); err != nil {- logging.LogErrorf("mkdir [%s] failed: %s", toIconDir, err)- return err- }- toIconFile := filepath.Join(toIconDir, "icon.js")- if err := filelock.Copy(srcIconFile, toIconFile); err != nil {- logging.LogWarnf("copy icon file from [%s] to [%s] failed: %s", srcIconFile, toIconFile, err)- }- }- // 复制当前使用的图标文件- if iconName != "" {- srcIconFile := filepath.Join(appearancePath, "icons", iconName, "icon.js")- toIconDir := filepath.Join(savePath, "appearance", "icons", iconName)- if err := os.MkdirAll(toIconDir, 0755); err != nil {- logging.LogErrorf("mkdir [%s] failed: %s", toIconDir, err)- return err- }- toIconFile := filepath.Join(toIconDir, "icon.js")- if err := filelock.Copy(srcIconFile, toIconFile); err != nil {- logging.LogWarnf("copy icon file from [%s] to [%s] failed: %s", srcIconFile, toIconFile, err)- }+ if err := copyExportAppearance(savePath, theme, Conf.Appearance.Icon); err != nil {+ return err}// 复制自定义表情图片@@ -1488,53 +1441,8 @@ func ExportHTMLWithTitle(id, savePath string, pdf, keepFold, merge, addTitle booif 1 == Conf.Appearance.Mode {theme = Conf.Appearance.ThemeDark}- // 复制主题文件夹- srcs = []string{"themes/" + theme}- appearancePath := util.AppearancePath- if util.IsSymlinkPath(util.AppearancePath) {- // Support for symlinked theme folder when exporting HTML https://github.com/siyuan-note/siyuan/issues/9173- var readErr error- appearancePath, readErr = filepath.EvalSymlinks(util.AppearancePath)- if nil != readErr {- logging.LogErrorf("readlink [%s] failed: %s", util.AppearancePath, readErr)- return readErr- }- }- for _, src := range srcs {- from := filepath.Join(appearancePath, src)- to := filepath.Join(savePath, "appearance", src)- if err := filelock.Copy(from, to); err != nil {- logging.LogErrorf("copy appearance from [%s] to [%s] failed: %s", from, savePath, err)- }- }-- // 只复制图标文件夹中的 icon.js 文件- iconName := Conf.Appearance.Icon- // 如果使用的不是内建图标(litheness),需要复制 litheness 作为后备- if iconName != "litheness" && iconName != "" {- srcIconFile := filepath.Join(appearancePath, "icons", "litheness", "icon.js")- toIconDir := filepath.Join(savePath, "appearance", "icons", "litheness")- if err := os.MkdirAll(toIconDir, 0755); err != nil {- logging.LogErrorf("mkdir [%s] failed: %s", toIconDir, err)- return err- }- toIconFile := filepath.Join(toIconDir, "icon.js")- if err := filelock.Copy(srcIconFile, toIconFile); err != nil {- logging.LogWarnf("copy icon file from [%s] to [%s] failed: %s", srcIconFile, toIconFile, err)- }- }- // 复制当前使用的图标文件- if iconName != "" {- srcIconFile := filepath.Join(appearancePath, "icons", iconName, "icon.js")- toIconDir := filepath.Join(savePath, "appearance", "icons", iconName)- if err := os.MkdirAll(toIconDir, 0755); err != nil {- logging.LogErrorf("mkdir [%s] failed: %s", toIconDir, err)- return err- }- toIconFile := filepath.Join(toIconDir, "icon.js")- if err := filelock.Copy(srcIconFile, toIconFile); err != nil {- logging.LogWarnf("copy icon file from [%s] to [%s] failed: %s", srcIconFile, toIconFile, err)- }+ if err := copyExportAppearance(savePath, theme, Conf.Appearance.Icon); err != nil {+ return err}// 复制自定义表情图片diff --git a/kernel/model/repository.go b/kernel/model/repository.goindex 34117d096d..d068ceab4c 100644--- a/kernel/model/repository.go+++ b/kernel/model/repository.go@@ -1356,9 +1356,9 @@ func checkoutRepo(id string) (err error) {CloseWatchEmojis()defer WatchEmojis()- // 若主题支持同步,需关闭监听器- // CloseWatchThemes()- // defer WatchThemes()+ // 整包恢复期间暂停监听,完成后重新绑定实际目录。+ CloseWatchThemes()+ defer WatchThemes()// 恢复快照时自动暂停同步,避免刚刚恢复后的数据又被同步覆盖syncEnabled := Conf.Sync.Enabled@@ -1370,6 +1370,12 @@ func checkoutRepo(id string) (err error) {// 回滚快照时默认为当前数据创建一个快照// When rolling back a snapshot, a snapshot is created for the current data by default https://github.com/siyuan-note/siyuan/issues/12470+ 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)@@ -1402,7 +1408,9 @@ func checkoutRepo(id string) (err error) {// checkoutRepoSnapshot 恢复失败前可能已有文件落盘,返回结果前同步更新索引、缓存和界面。func checkoutRepoSnapshot(repo *dejavu.Repo, id string, refresh func(error)) error {- _, _, err := repo.Checkout(id, map[string]any{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBarAndProgress})+ upserts, removes, err := repo.Checkout(id, map[string]any{eventbus.CtxPushMsg: eventbus.CtxPushMsgToStatusBarAndProgress})+ themes, icons := appearanceChangedPackages(&dejavu.MergeResult{Upserts: upserts, Removes: removes})+ refreshAppearancePackages(themes, icons)refresh(err)return err}@@ -1799,6 +1807,12 @@ func CreateRepoSnapshot(memo string) (id string, created bool, err error) {defer util.PushClearProgress()start := time.Now()+ 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,@@ -2383,6 +2397,8 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,mergeResult.ConflictCount(), len(mergeResult.Upserts), len(mergeResult.Removes))//logSyncMergeResult(mergeResult)+ themes, icons := appearanceChangedPackages(mergeResult)+ refreshAppearancePackages(themes, icons)var needReloadFiletree boolconflictCount := mergeResult.ConflictCount()@@ -2917,6 +2933,9 @@ 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@@ -3019,12 +3038,18 @@ 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,- IgnoreRulePath: syncIgnoreRulePath, HiddenDirectoryNames: []string{".siyuan"},+ EnableAppearanceSync: true, AppearanceIgnoreLines: appearanceIgnoreLines,+ BeforeAppearanceApply: util.EnsureAppearanceSyncIsolation,+ 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 d249022e06..49f71f2030 100644--- a/kernel/model/sync.go+++ b/kernel/model/sync.go@@ -994,6 +994,14 @@ 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")@@ -1020,6 +1028,12 @@ func loadSyncIgnoreLines() (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 8860dff044..2069ec7c0b 100644--- a/kernel/model/sync_ignore.go+++ b/kernel/model/sync_ignore.go@@ -114,6 +114,31 @@ func syncPathFilter(dataDir string, info os.FileInfo, absPath string) (bool, errif ignored, err := dejavu.IgnorePath(info, absPath, rel, syncIgnoreRulePath, ".siyuan"); ignored || err != nil {return ignored, err}+ parts := strings.Split(strings.TrimPrefix(filepath.ToSlash(rel), "/"), "/")+ if len(parts) >= 2 && (parts[0] == "themes" || parts[0] == "icons") {+ if stat, err := os.Lstat(filepath.Join(dataDir, parts[0], parts[1])); err == nil && stat.Mode()&os.ModeSymlink != 0 {+ return true, nil+ }+ }+ if len(parts) >= 2 && ((parts[0] == "themes" && isBuiltInTheme(parts[1])) ||+ (parts[0] == "icons" && isBuiltInIcon(parts[1]))) {+ if info != nil && info.IsDir() {+ return true, filepath.SkipDir+ }+ 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/model/theme.go b/kernel/model/theme.goindex ecf4ede740..c756d1664d 100644--- a/kernel/model/theme.go+++ b/kernel/model/theme.go@@ -367,7 +367,7 @@ func getThemeStyleVar(theme string, isDarkMode bool) (ret map[string]string) {// 第三方主题可能缺少基础变量,先加载默认主题作为基础defaultTheme := map[bool]string{false: "daylight", true: "midnight"}[isDarkMode]if theme != defaultTheme {- defaultData, err := os.ReadFile(filepath.Join(util.ThemesPath, defaultTheme, "theme.css"))+ defaultData, err := os.ReadFile(filepath.Join(util.AppearancePackagePath("themes", defaultTheme), "theme.css"))if err != nil {logging.LogErrorf("read default theme [%s] css file failed: %s", defaultTheme, err)} else {@@ -376,7 +376,11 @@ func getThemeStyleVar(theme string, isDarkMode bool) (ret map[string]string) {}// 拼接主题 CSS,后面的规则覆盖前面的规则- userData, err := os.ReadFile(filepath.Join(util.ThemesPath, theme, "theme.css"))+ themePath := util.AppearancePackagePath("themes", theme)+ if themePath == "" {+ return ret+ }+ userData, err := os.ReadFile(filepath.Join(themePath, "theme.css"))if err != nil {logging.LogErrorf("read theme [%s] css file failed: %s", theme, err)return retdiff --git a/kernel/model/theme_test.go b/kernel/model/theme_test.goindex 5f3cb23153..2b90d03baa 100644--- a/kernel/model/theme_test.go+++ b/kernel/model/theme_test.go@@ -200,17 +200,20 @@ func inlineStyleThemeTestTree(style string) (tree *parse.Tree, node *ast.Node) {func setupThemeTest(t *testing.T, theme, css string) {t.Helper()oldDataDir, oldThemesPath, oldConf := util.DataDir, util.ThemesPath, Conf+ oldAppearancePath, oldMode := util.AppearancePath, util.ModetempDir := t.TempDir()util.DataDir = filepath.Join(tempDir, "data")util.ThemesPath = filepath.Join(tempDir, "themes")+ util.AppearancePath, util.Mode = filepath.Join(tempDir, "appearance"), "prod"Conf = NewAppConf()Conf.Appearance = conf.NewAppearance()Conf.Sync = conf.NewSync()t.Cleanup(func() {util.DataDir, util.ThemesPath, Conf = oldDataDir, oldThemesPath, oldConf+ util.AppearancePath, util.Mode = oldAppearancePath, oldMode})- themeDir := filepath.Join(util.ThemesPath, theme)+ themeDir := util.AppearancePackagePath("themes", theme)if err := os.MkdirAll(themeDir, 0755); err != nil {t.Fatal(err)}diff --git a/kernel/model/themes_watcher_test.go b/kernel/model/themes_watcher_test.goindex 530eaecfb3..a8393b0ad1 100644--- a/kernel/model/themes_watcher_test.go+++ b/kernel/model/themes_watcher_test.go@@ -29,30 +29,39 @@ import (func TestWatchThemesCurrentThemeOnly(t *testing.T) {originalConf, originalThemesPath := Conf, util.ThemesPath+ originalAppearancePath, originalMode := util.AppearancePath, util.Modet.Cleanup(func() {CloseWatchThemes()Conf = originalConfutil.ThemesPath = originalThemesPath+ util.AppearancePath, util.Mode = originalAppearancePath, originalMode})themesDir := t.TempDir()+ util.ThemesPath = themesDir+ util.AppearancePath, util.Mode = t.TempDir(), "prod"for _, name := range []string{"daylight", "midnight", "unused"} {- if err := os.Mkdir(filepath.Join(themesDir, name), 0755); err != nil {+ if err := os.MkdirAll(util.AppearancePackagePath("themes", name), 0755); err != nil {t.Fatal(err)}}Conf = NewAppConf()Conf.Appearance = conf.NewAppearance()- util.ThemesPath = themesDirWatchThemes()- assertThemesWatchList(t, themesDir, filepath.Join(themesDir, "daylight"))+ assertThemesWatchList(t, themesDir, util.AppearancePackagePath("themes", "daylight"))Conf.m.Lock()Conf.Appearance.Mode = 1Conf.m.Unlock()WatchThemes()- assertThemesWatchList(t, themesDir, filepath.Join(themesDir, "midnight"))+ assertThemesWatchList(t, themesDir, util.AppearancePackagePath("themes", "midnight"))++ Conf.m.Lock()+ Conf.Appearance.ThemeDark = "unused"+ Conf.m.Unlock()+ WatchThemes()+ assertThemesWatchList(t, themesDir, filepath.Join(themesDir, "unused"))Conf.m.Lock()Conf.Appearance.Mode = -1diff --git a/kernel/server/appearance_path.go b/kernel/server/appearance_path.goindex b831eaec99..57a8c33f6c 100644--- a/kernel/server/appearance_path.go+++ b/kernel/server/appearance_path.go@@ -23,8 +23,19 @@ import ("strings""github.com/88250/gulu"+ "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) {relativePath, ok := cleanStaticRelativePath(requestPath)@@ -35,6 +46,19 @@ func resolveAppearanceFile(root, requestPath string) (string, int) {if relativePath == "boot" {relativePath = filepath.Join(relativePath, "index.html")}+ segments := strings.Split(filepath.ToSlash(relativePath), "/")+ packageRootIndex := -1+ kind := strings.ToLower(segments[0])+ if len(segments) >= 2 && (kind == "themes" || kind == "icons") {+ packagePath := util.AppearancePackagePath(kind, segments[1])+ if packagePath == "" {+ return "", http.StatusForbidden+ }+ root = filepath.Dir(packagePath)+ segments[1] = filepath.Base(packagePath)+ segments = segments[1:]+ packageRootIndex = 0+ }root, err := filepath.Abs(root)if err != nil {return "", http.StatusInternalServerError@@ -44,7 +68,6 @@ func resolveAppearanceFile(root, requestPath string) (string, int) {return "", http.StatusNotFound}allowedRoot, target := root, root- segments := strings.Split(filepath.ToSlash(relativePath), "/")for i, segment := range segments {target = filepath.Join(target, segment)info, statErr := os.Lstat(target)@@ -61,7 +84,7 @@ func resolveAppearanceFile(root, requestPath string) (string, int) {return "", http.StatusForbidden}}- if i == 1 && (segments[0] == "themes" || segments[0] == "icons") {+ if i == packageRootIndex {info, err = os.Stat(target)if err != nil || !info.IsDir() {return "", http.StatusNotFounddiff --git a/kernel/server/appearance_path_test.go b/kernel/server/appearance_path_test.goindex ba05037391..ee97876279 100644--- a/kernel/server/appearance_path_test.go+++ b/kernel/server/appearance_path_test.go@@ -31,11 +31,14 @@ import (func TestAppearanceFileBoundaries(t *testing.T) {gin.SetMode(gin.TestMode)originalPath, originalMode, originalConf := util.AppearancePath, util.Mode, model.Conf+ originalThemesPath, originalIconsPath := util.ThemesPath, util.IconsPathutil.AppearancePath, util.Mode = filepath.Join(t.TempDir(), "conf", "appearance"), "prod"+ util.ThemesPath, util.IconsPath = filepath.Join(t.TempDir(), "themes"), filepath.Join(t.TempDir(), "icons")model.Conf = model.NewAppConf()model.Conf.AccessAuthCode = "test-password"t.Cleanup(func() {util.AppearancePath, util.Mode, model.Conf = originalPath, originalMode, originalConf+ util.ThemesPath, util.IconsPath = originalThemesPath, originalIconsPath})outside := t.TempDir()write := func(name, content string) {@@ -48,8 +51,13 @@ func TestAppearanceFileBoundaries(t *testing.T) {}}for _, name := range []string{"themes/local/theme.css", "icons/local/icon.js", "fonts/font.woff"} {- write(filepath.Join(util.AppearancePath, name), "resource")+ write(appearanceTestResourcePath(name), "resource")}+ write(filepath.Join(util.AppearancePath, "themes/local/old.css"), "legacy")+ write(filepath.Join(util.AppearancePath, "themes/daylight/theme.css"), "built-in")+ write(filepath.Join(util.ThemesPath, "daylight/theme.css"), "shadow")+ write(filepath.Join(util.AppearancePath, "icons/litheness/icon.js"), "built-in")+ write(filepath.Join(util.IconsPath, "litheness/icon.js"), "shadow")write(filepath.Join(util.AppearancePath, "langs/en.json"), `{"fallback":"English"}`)write(filepath.Join(util.AppearancePath, "langs/fr.json"), `{"label":"French"}`)write(filepath.Join(filepath.Dir(util.AppearancePath), "conf.json"), `{"secret":"credential"}`)@@ -67,6 +75,12 @@ func TestAppearanceFileBoundaries(t *testing.T) {}}check("themes/local/theme.css", 200, "resource")+ check("themes/local/old.css", 404, "")+ check("Themes/local/old.css", 404, "")+ check("Themes/local/theme.css", 200, "resource")+ check("themes/daylight/theme.css", 200, "built-in")+ check("icons/litheness/icon.js", 200, "built-in")+ check("Icons/LITHENESS/icon.js", 200, "built-in")check("icons/local/icon.js", 200, "resource")check("fonts/font.woff", 200, "resource")check("langs/fr.json", 200, `"fallback":"English"`)@@ -87,7 +101,7 @@ func TestAppearanceFileBoundaries(t *testing.T) {check("boot/", 404, "")link := func(target, name string) {t.Helper()- if err := os.Symlink(target, filepath.Join(util.AppearancePath, name)); err != nil {+ if err := os.Symlink(target, appearanceTestResourcePath(name)); err != nil {t.Skipf("symlinks unavailable: %s", err)}}@@ -118,3 +132,15 @@ func TestAppearanceFileBoundaries(t *testing.T) {check("langs/fr.json", 403, "")check("langs/en.json", 403, "")}++func appearanceTestResourcePath(name string) string {+ parts := strings.SplitN(name, "/", 3)+ if len(parts) >= 2 && (parts[0] == "themes" || parts[0] == "icons") {+ root := util.AppearancePackagePath(parts[0], parts[1])+ if len(parts) == 3 {+ return filepath.Join(root, parts[2])+ }+ return root+ }+ return filepath.Join(util.AppearancePath, name)+}diff --git a/kernel/server/serve.go b/kernel/server/serve.goindex 8f1883d46e..b7e32edb87 100644--- a/kernel/server/serve.go+++ b/kernel/server/serve.go@@ -42,6 +42,7 @@ 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"@@ -789,18 +790,22 @@ func serveAppearance(ginServer *gin.Engine) {c.Redirect(302, location.String())})- appearancePath := util.AppearancePath- if "dev" == util.Mode {- appearancePath = filepath.Join(util.WorkingDir, "appearance")- }+ appearancePath := util.BuiltInAppearancePath()siyuan.GET("/appearance/*filepath", func(c *gin.Context) {- filePath, status := resolveAppearanceFile(appearancePath, strings.TrimPrefix(c.Request.URL.Path, "/appearance/"))+ 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)return}- if strings.HasPrefix(c.Request.URL.Path, "/appearance/themes/") {+ resourceKind := strings.ToLower(strings.SplitN(requestPath, "/", 2)[0])+ if resourceKind == "themes" || resourceKind == "icons" {c.Header("Cache-Control", "private, no-store")}if strings.HasSuffix(c.Request.URL.Path, "/theme.js") {diff --git a/kernel/server/serve_static_test.go b/kernel/server/serve_static_test.goindex 5dd62bec3e..fe188e7b5b 100644--- a/kernel/server/serve_static_test.go+++ b/kernel/server/serve_static_test.go@@ -355,12 +355,15 @@ func TestLanguageResponseDisablesCache(t *testing.T) {func TestThemeResponseDisablesCache(t *testing.T) {gin.SetMode(gin.TestMode)originalAppearancePath, originalMode := util.AppearancePath, util.Mode+ originalThemesPath := util.ThemesPathutil.AppearancePath, util.Mode = t.TempDir(), "prod"+ util.ThemesPath = filepath.Join(t.TempDir(), "themes")t.Cleanup(func() {util.AppearancePath, util.Mode = originalAppearancePath, originalMode+ util.ThemesPath = originalThemesPath})- themeDir := filepath.Join(util.AppearancePath, "themes", "example", "style", "module")+ themeDir := filepath.Join(util.ThemesPath, "example", "style", "module")if err := os.MkdirAll(themeDir, 0755); err != nil {t.Fatal(err)}diff --git a/kernel/util/appearance_path.go b/kernel/util/appearance_path.gonew file mode 100644index 0000000000..cb56f3bd84--- /dev/null+++ b/kernel/util/appearance_path.go@@ -0,0 +1,57 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package util++import (+ "path/filepath"+ "strings"+)++// BuiltInAppearancePath 返回当前运行模式下内置外观资源的目录。+func BuiltInAppearancePath() string {+ if Mode == "dev" {+ return filepath.Join(WorkingDir, "appearance")+ }+ return AppearancePath+}++// AppearancePackagePath 按包名区分内置资源和参与同步的第三方资源。+func AppearancePackagePath(kind, name string) string {+ if name == "" || strings.HasPrefix(name, ".") || strings.TrimSpace(name) != name ||+ strings.ContainsAny(name, `/\:`) || filepath.Base(name) != name || strings.Contains(name, "..") {+ return ""+ }+ var root string+ switch kind {+ case "themes":+ if strings.EqualFold(name, "daylight") || strings.EqualFold(name, "midnight") {+ return filepath.Join(BuiltInAppearancePath(), kind, strings.ToLower(name))+ }+ root = ThemesPath+ case "icons":+ if strings.EqualFold(name, "litheness") {+ return filepath.Join(BuiltInAppearancePath(), kind, "litheness")+ }+ root = IconsPath+ default:+ return ""+ }+ if root == "" {+ return ""+ }+ return filepath.Join(root, name)+}diff --git a/kernel/util/appearance_path_test.go b/kernel/util/appearance_path_test.gonew file mode 100644index 0000000000..25ae595d24--- /dev/null+++ b/kernel/util/appearance_path_test.go@@ -0,0 +1,43 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.++package util++import (+ "path/filepath"+ "testing"+)++func TestAppearancePackagePaths(t *testing.T) {+ oldAppearance, oldThemes, oldIcons, oldWorking, oldMode := AppearancePath, ThemesPath, IconsPath, WorkingDir, Mode+ t.Cleanup(func() {+ AppearancePath, ThemesPath, IconsPath, WorkingDir, Mode = oldAppearance, oldThemes, oldIcons, oldWorking, oldMode+ })+ root := t.TempDir()+ AppearancePath, WorkingDir = filepath.Join(root, "conf", "appearance"), filepath.Join(root, "app")+ ThemesPath, IconsPath = filepath.Join(root, "data", "themes"), filepath.Join(root, "data", "icons")+ for _, mode := range []string{"prod", "dev"} {+ Mode = mode+ for _, test := range []struct{ kind, name, expected string }{+ {"themes", "daylight", filepath.Join(BuiltInAppearancePath(), "themes", "daylight")},+ {"themes", "MIDNIGHT", filepath.Join(BuiltInAppearancePath(), "themes", "midnight")},+ {"icons", "litheness", filepath.Join(BuiltInAppearancePath(), "icons", "litheness")},+ {"themes", "custom", filepath.Join(ThemesPath, "custom")},+ {"icons", "custom", filepath.Join(IconsPath, "custom")},+ {"plugins", "custom", ""},+ {"themes", "../conf", ""},+ {"themes", `..\conf`, ""},+ {"themes", "C:secret", ""},+ {"themes", "", ""},+ } {+ if actual := AppearancePackagePath(test.kind, test.name); actual != test.expected {+ t.Errorf("%s %s/%s: got %q, want %q", mode, test.kind, test.name, actual, test.expected)+ }+ }+ }+}diff --git a/kernel/util/appearance_sync_isolation.go b/kernel/util/appearance_sync_isolation.gonew file mode 100644index 0000000000..39eb7607bc--- /dev/null+++ b/kernel/util/appearance_sync_isolation.go@@ -0,0 +1,306 @@+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.gonew file mode 100644index 0000000000..2858bc5d6c--- /dev/null+++ b/kernel/util/appearance_sync_isolation_test.go@@ -0,0 +1,368 @@+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)+ }+}diff --git a/kernel/util/working.go b/kernel/util/working.goindex 6fe4d20975..6bdca151ee 100644--- a/kernel/util/working.go+++ b/kernel/util/working.go@@ -109,13 +109,8 @@ func InitWorkspace(workspacePath, wdPath string) {initPathDir()AppearancePath = filepath.Join(ConfDir, "appearance")- if "dev" == Mode {- ThemesPath = filepath.Join(WorkingDir, "appearance", "themes")- IconsPath = filepath.Join(WorkingDir, "appearance", "icons")- } else {- ThemesPath = filepath.Join(AppearancePath, "themes")- IconsPath = filepath.Join(AppearancePath, "icons")- }+ ThemesPath = filepath.Join(DataDir, "themes")+ IconsPath = filepath.Join(DataDir, "icons")LogPath = filepath.Join(TempDir, "siyuan.log")}@@ -271,8 +266,8 @@ var (AssetContentDBPath string // SQLite 资源文件内容数据库文件路径BlockTreeDBPath string // 区块树数据库文件路径AppearancePath string // 配置目录下的外观目录 appearance/ 路径- ThemesPath string // 配置目录下的外观目录下的 themes/ 路径- IconsPath string // 配置目录下的外观目录下的 icons/ 路径+ ThemesPath string // 数据目录下的第三方主题 themes/ 路径+ IconsPath string // 数据目录下的第三方图标 icons/ 路径SnippetsPath string // 数据目录下的 snippets/ 路径ShortcutsPath string // 用户家目录下的快捷方式目录路径 home/.config/siyuan/shortcuts/diff --git a/kernel/util/working_mobile.go b/kernel/util/working_mobile.goindex ad469ab09f..aa55db3806 100644--- a/kernel/util/working_mobile.go+++ b/kernel/util/working_mobile.go@@ -136,8 +136,8 @@ func initWorkspaceDirMobile(workspaceBaseDir string) {ShortcutsPath = filepath.Join(userHomeConfDir, "shortcuts")AppearancePath = filepath.Join(ConfDir, "appearance")- ThemesPath = filepath.Join(AppearancePath, "themes")- IconsPath = filepath.Join(AppearancePath, "icons")+ ThemesPath = filepath.Join(DataDir, "themes")+ IconsPath = filepath.Join(DataDir, "icons")LogPath = filepath.Join(TempDir, "siyuan.log")logging.SetLogPath(LogPath)