Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(config-sync): add encrypted portable configuration sync

Land8e896474d06
diff --git a/Cargo.lock b/Cargo.lock
index 7b3f83e02..cb4020801 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -8,7 +8,7 @@ version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"
dependencies = [
- "crypto-common",
+ "crypto-common 0.2.2",
"inout",
]
@@ -20,7 +20,7 @@ checksum = "f8eb277bec05f56a0e0591f155a484cbd0f4f07ff2905051a48c72f004f7ed58"
dependencies = [
"cipher",
"cpubits",
- "cpufeatures",
+ "cpufeatures 0.3.0",
]
[[package]]
@@ -61,24 +61,72 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+[[package]]
+name = "argon2"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"
+dependencies = [
+ "base64ct",
+ "blake2",
+ "cpufeatures 0.2.17",
+ "password-hash",
+]
+
+[[package]]
+name = "atomic-waker"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+[[package]]
+name = "base64"
+version = "0.22.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+
[[package]]
name = "base64"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
+[[package]]
+name = "base64ct"
+version = "1.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
+
[[package]]
name = "bitflags"
version = "2.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
+[[package]]
+name = "blake2"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
+dependencies = [
+ "digest 0.10.7",
+]
+
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
[[package]]
name = "block-buffer"
version = "0.12.1"
@@ -126,6 +174,12 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+[[package]]
+name = "cfg_aliases"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+
[[package]]
name = "chacha20"
version = "0.10.1"
@@ -133,8 +187,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"
dependencies = [
"cfg-if",
- "cpufeatures",
- "rand_core",
+ "cpufeatures 0.3.0",
+ "rand_core 0.10.1",
]
[[package]]
@@ -157,8 +211,8 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
dependencies = [
- "block-buffer",
- "crypto-common",
+ "block-buffer 0.12.1",
+ "crypto-common 0.2.2",
"inout",
]
@@ -186,6 +240,15 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "cpufeatures"
version = "0.3.0"
@@ -220,6 +283,16 @@ version = "0.8.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
[[package]]
name = "crypto-common"
version = "0.2.2"
@@ -228,7 +301,7 @@ checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
"getrandom 0.4.3",
"hybrid-array",
- "rand_core",
+ "rand_core 0.10.1",
]
[[package]]
@@ -249,15 +322,26 @@ dependencies = [
"cmov",
]
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer 0.10.4",
+ "crypto-common 0.1.7",
+ "subtle",
+]
+
[[package]]
name = "digest"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
- "block-buffer",
+ "block-buffer 0.12.1",
"const-oid",
- "crypto-common",
+ "crypto-common 0.2.2",
]
[[package]]
@@ -278,9 +362,26 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
- "windows-sys",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "displaydoc"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.3",
]
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
[[package]]
name = "errno"
version = "0.3.14"
@@ -288,7 +389,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
- "windows-sys",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -315,18 +416,48 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d45db016d36b838f563236e9193d0ee6ce38f3f68b6c94e914b4929c96bbb890"
+[[package]]
+name = "fnv"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+
[[package]]
name = "foldhash"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+[[package]]
+name = "form_urlencoded"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
+dependencies = [
+ "percent-encoding",
+]
+
+[[package]]
+name = "futures-channel"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
+dependencies = [
+ "futures-core",
+]
+
[[package]]
name = "futures-core"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
+[[package]]
+name = "futures-sink"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"
+
[[package]]
name = "futures-task"
version = "0.3.34"
@@ -345,6 +476,16 @@ dependencies = [
"slab",
]
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
[[package]]
name = "getrandom"
version = "0.2.17"
@@ -352,8 +493,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
+ "js-sys",
"libc",
"wasi",
+ "wasm-bindgen",
]
[[package]]
@@ -363,9 +506,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
+ "js-sys",
"libc",
"r-efi",
- "rand_core",
+ "rand_core 0.10.1",
+ "wasm-bindgen",
]
[[package]]
@@ -390,6 +535,25 @@ dependencies = [
"regex-syntax",
]
+[[package]]
+name = "h2"
+version = "0.4.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16"
+dependencies = [
+ "atomic-waker",
+ "bytes",
+ "fnv",
+ "futures-core",
+ "futures-sink",
+ "http",
+ "indexmap",
+ "slab",
+ "tokio",
+ "tokio-util",
+ "tracing",
+]
+
[[package]]
name = "hashbrown"
version = "0.16.1"
@@ -429,7 +593,8 @@ version = "0.15.2"
dependencies = [
"aes-gcm",
"anyhow",
- "base64",
+ "argon2",
+ "base64 0.23.1",
"chrono",
"dirs",
"globset",
@@ -438,6 +603,7 @@ dependencies = [
"libc",
"rand",
"regex",
+ "reqwest",
"rusqlite",
"serde",
"serde_json",
@@ -449,9 +615,48 @@ dependencies = [
"tracing-subscriber",
"uuid",
"walkdir",
- "windows-sys",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "http"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
+dependencies = [
+ "bytes",
+ "itoa",
]
+[[package]]
+name = "http-body"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
+dependencies = [
+ "bytes",
+ "http",
+]
+
+[[package]]
+name = "http-body-util"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "httparse"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+
[[package]]
name = "hybrid-array"
version = "0.4.14"
@@ -461,6 +666,66 @@ dependencies = [
"typenum",
]
+[[package]]
+name = "hyper"
+version = "1.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43"
+dependencies = [
+ "atomic-waker",
+ "bytes",
+ "futures-channel",
+ "futures-core",
+ "h2",
+ "http",
+ "http-body",
+ "httparse",
+ "itoa",
+ "pin-project-lite",
+ "smallvec",
+ "tokio",
+ "want",
+]
+
+[[package]]
+name = "hyper-rustls"
+version = "0.27.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53"
+dependencies = [
+ "http",
+ "hyper",
+ "hyper-util",
+ "rustls",
+ "tokio",
+ "tokio-rustls",
+ "tower-service",
+ "webpki-roots",
+]
+
+[[package]]
+name = "hyper-util"
+version = "0.1.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
+dependencies = [
+ "base64 0.22.1",
+ "bytes",
+ "futures-channel",
+ "futures-util",
+ "http",
+ "http-body",
+ "hyper",
+ "ipnet",
+ "libc",
+ "percent-encoding",
+ "pin-project-lite",
+ "socket2",
+ "tokio",
+ "tower-service",
+ "tracing",
+]
+
[[package]]
name = "iana-time-zone"
version = "0.1.65"
@@ -485,6 +750,110 @@ dependencies = [
"cc",
]
+[[package]]
+name = "icu_collections"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"
+dependencies = [
+ "displaydoc",
+ "potential_utf",
+ "utf8_iter",
+ "yoke",
+ "zerofrom",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locale_core"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"
+dependencies = [
+ "displaydoc",
+ "litemap",
+ "tinystr",
+ "writeable",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"
+dependencies = [
+ "icu_collections",
+ "icu_normalizer_data",
+ "icu_properties",
+ "icu_provider",
+ "smallvec",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"
+
+[[package]]
+name = "icu_properties"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"
+dependencies = [
+ "displaydoc",
+ "icu_collections",
+ "icu_locale_core",
+ "icu_properties_data",
+ "icu_provider",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_properties_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"
+
+[[package]]
+name = "icu_provider"
+version = "2.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"
+dependencies = [
+ "displaydoc",
+ "icu_locale_core",
+ "writeable",
+ "yoke",
+ "zerofrom",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "idna"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
+dependencies = [
+ "idna_adapter",
+ "smallvec",
+ "utf8_iter",
+]
+
+[[package]]
+name = "idna_adapter"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
+dependencies = [
+ "icu_normalizer",
+ "icu_properties",
+]
+
[[package]]
name = "ignore"
version = "0.4.33"
@@ -501,6 +870,16 @@ dependencies = [
"winapi-util",
]
+[[package]]
+name = "indexmap"
+version = "2.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.17.1",
+]
+
[[package]]
name = "inout"
version = "0.2.2"
@@ -510,6 +889,12 @@ dependencies = [
"hybrid-array",
]
+[[package]]
+name = "ipnet"
+version = "2.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
+
[[package]]
name = "itoa"
version = "1.0.18"
@@ -565,6 +950,12 @@ version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+[[package]]
+name = "litemap"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
+
[[package]]
name = "lock_api"
version = "0.4.14"
@@ -580,6 +971,12 @@ version = "0.4.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
+[[package]]
+name = "lru-slab"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
+
[[package]]
name = "matchers"
version = "0.2.0"
@@ -603,7 +1000,7 @@ checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427"
dependencies = [
"libc",
"wasi",
- "windows-sys",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -612,7 +1009,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
- "windows-sys",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -659,6 +1056,23 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "password-hash"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"
+dependencies = [
+ "base64ct",
+ "rand_core 0.6.4",
+ "subtle",
+]
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+
[[package]]
name = "pin-project-lite"
version = "0.2.17"
@@ -678,10 +1092,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd"
dependencies = [
"cpubits",
- "cpufeatures",
+ "cpufeatures 0.3.0",
"universal-hash",
]
+[[package]]
+name = "potential_utf"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"
+dependencies = [
+ "zerovec",
+]
+
[[package]]
name = "proc-macro2"
version = "1.0.107"
@@ -692,30 +1115,92 @@ dependencies = [
]
[[package]]
-name = "quote"
-version = "1.0.47"
+name = "quinn"
+version = "0.11.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11"
dependencies = [
- "proc-macro2",
+ "bytes",
+ "cfg_aliases",
+ "pin-project-lite",
+ "quinn-proto",
+ "quinn-udp",
+ "rustc-hash",
+ "rustls",
+ "socket2",
+ "thiserror",
+ "tokio",
+ "tracing",
+ "web-time",
]
[[package]]
-name = "r-efi"
-version = "6.0.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
-
-[[package]]
-name = "rand"
-version = "0.10.2"
+name = "quinn-proto"
+version = "0.11.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
+checksum = "a9746dbde176634f4f2f1faf2404e30a31b2bc1e9cafb5329c95d8177a18c9fc"
dependencies = [
- "chacha20",
+ "bytes",
"getrandom 0.4.3",
- "rand_core",
-]
+ "lru-slab",
+ "rand",
+ "rand_pcg",
+ "ring",
+ "rustc-hash",
+ "rustls",
+ "rustls-pki-types",
+ "slab",
+ "thiserror",
+ "tinyvec",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-udp"
+version = "0.5.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694"
+dependencies = [
+ "cfg_aliases",
+ "libc",
+ "once_cell",
+ "socket2",
+ "tracing",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "rand"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"
+dependencies = [
+ "chacha20",
+ "getrandom 0.4.3",
+ "rand_core 0.10.1",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
[[package]]
name = "rand_core"
@@ -723,6 +1208,15 @@ version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+[[package]]
+name = "rand_pcg"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"
+dependencies = [
+ "rand_core 0.10.1",
+]
+
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -772,6 +1266,59 @@ version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
+[[package]]
+name = "reqwest"
+version = "0.12.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
+dependencies = [
+ "base64 0.22.1",
+ "bytes",
+ "futures-core",
+ "h2",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-rustls",
+ "hyper-util",
+ "js-sys",
+ "log",
+ "percent-encoding",
+ "pin-project-lite",
+ "quinn",
+ "rustls",
+ "rustls-pki-types",
+ "serde",
+ "serde_json",
+ "serde_urlencoded",
+ "sync_wrapper",
+ "tokio",
+ "tokio-rustls",
+ "tower",
+ "tower-http",
+ "tower-service",
+ "url",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+ "webpki-roots",
+]
+
+[[package]]
+name = "ring"
+version = "0.17.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
+dependencies = [
+ "cc",
+ "cfg-if",
+ "getrandom 0.2.17",
+ "libc",
+ "untrusted",
+ "windows-sys 0.52.0",
+]
+
[[package]]
name = "rsqlite-vfs"
version = "0.1.1"
@@ -797,6 +1344,12 @@ dependencies = [
"sqlite-wasm-rs",
]
+[[package]]
+name = "rustc-hash"
+version = "2.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
+
[[package]]
name = "rustix"
version = "1.1.4"
@@ -807,7 +1360,42 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
- "windows-sys",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustls"
+version = "0.23.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
+dependencies = [
+ "once_cell",
+ "ring",
+ "rustls-pki-types",
+ "rustls-webpki",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-pki-types"
+version = "1.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
+dependencies = [
+ "web-time",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-webpki"
+version = "0.103.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
+dependencies = [
+ "ring",
+ "rustls-pki-types",
+ "untrusted",
]
[[package]]
@@ -816,6 +1404,12 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+[[package]]
+name = "ryu"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
+
[[package]]
name = "same-file"
version = "1.0.6"
@@ -874,6 +1468,18 @@ dependencies = [
"zmij",
]
+[[package]]
+name = "serde_urlencoded"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
+dependencies = [
+ "form_urlencoded",
+ "itoa",
+ "ryu",
+ "serde",
+]
+
[[package]]
name = "sha2"
version = "0.11.0"
@@ -881,8 +1487,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
dependencies = [
"cfg-if",
- "cpufeatures",
- "digest",
+ "cpufeatures 0.3.0",
+ "digest 0.11.3",
]
[[package]]
@@ -929,7 +1535,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
- "windows-sys",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -944,6 +1550,12 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+
[[package]]
name = "subtle"
version = "2.6.1"
@@ -972,6 +1584,26 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "sync_wrapper"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
+dependencies = [
+ "futures-core",
+]
+
+[[package]]
+name = "synstructure"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.3",
+]
+
[[package]]
name = "tempfile"
version = "3.27.0"
@@ -982,7 +1614,7 @@ dependencies = [
"getrandom 0.4.3",
"once_cell",
"rustix",
- "windows-sys",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -1014,6 +1646,22 @@ dependencies = [
"cfg-if",
]
+[[package]]
+name = "tinystr"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"
+dependencies = [
+ "displaydoc",
+ "zerovec",
+]
+
+[[package]]
+name = "tinyvec"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
+
[[package]]
name = "tokio"
version = "1.53.1"
@@ -1028,7 +1676,7 @@ dependencies = [
"signal-hook-registry",
"socket2",
"tokio-macros",
- "windows-sys",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -1042,6 +1690,75 @@ dependencies = [
"syn 3.0.3",
]
+[[package]]
+name = "tokio-rustls"
+version = "0.26.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b0c85f2c3ef0b1cd58b36682f4b17aaa995f0e5db534d85692b4903abce21f67"
+dependencies = [
+ "rustls",
+ "tokio",
+]
+
+[[package]]
+name = "tokio-util"
+version = "0.7.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "futures-sink",
+ "libc",
+ "pin-project-lite",
+ "tokio",
+]
+
+[[package]]
+name = "tower"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
+dependencies = [
+ "futures-core",
+ "futures-util",
+ "pin-project-lite",
+ "sync_wrapper",
+ "tokio",
+ "tower-layer",
+ "tower-service",
+]
+
+[[package]]
+name = "tower-http"
+version = "0.6.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
+dependencies = [
+ "bitflags",
+ "bytes",
+ "futures-util",
+ "http",
+ "http-body",
+ "pin-project-lite",
+ "tower",
+ "tower-layer",
+ "tower-service",
+ "url",
+]
+
+[[package]]
+name = "tower-layer"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
+
+[[package]]
+name = "tower-service"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
+
[[package]]
name = "tracing"
version = "0.1.44"
@@ -1103,6 +1820,12 @@ dependencies = [
"tracing-log",
]
+[[package]]
+name = "try-lock"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+
[[package]]
name = "typenum"
version = "1.20.1"
@@ -1121,10 +1844,34 @@ version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96"
dependencies = [
- "crypto-common",
+ "crypto-common 0.2.2",
"ctutils",
]
+[[package]]
+name = "untrusted"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
+
+[[package]]
+name = "url"
+version = "2.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
+dependencies = [
+ "form_urlencoded",
+ "idna",
+ "percent-encoding",
+ "serde",
+]
+
+[[package]]
+name = "utf8_iter"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
+
[[package]]
name = "uuid"
version = "1.24.0"
@@ -1149,6 +1896,12 @@ version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
[[package]]
name = "walkdir"
version = "2.5.0"
@@ -1159,6 +1912,15 @@ dependencies = [
"winapi-util",
]
+[[package]]
+name = "want"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
+dependencies = [
+ "try-lock",
+]
+
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
@@ -1178,6 +1940,16 @@ dependencies = [
"wasm-bindgen-shared",
]
+[[package]]
+name = "wasm-bindgen-futures"
+version = "0.4.77"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b7777d5cc23d0e91404e53ce2d5e8ec7acae3026b16233dba62cd3246457950"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.127"
@@ -1210,13 +1982,42 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "web-sys"
+version = "0.3.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c435338968042f4f59a557f690a253676d47ce13ceb55d70100e7facf6620a30"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "web-time"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "webpki-roots"
+version = "1.0.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
+dependencies = [
+ "rustls-pki-types",
+]
+
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
- "windows-sys",
+ "windows-sys 0.61.2",
]
[[package]]
@@ -1278,6 +2079,15 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "windows-sys"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+dependencies = [
+ "windows-targets",
+]
+
[[package]]
name = "windows-sys"
version = "0.61.2"
@@ -1287,6 +2097,159 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm",
+ "windows_aarch64_msvc",
+ "windows_i686_gnu",
+ "windows_i686_gnullvm",
+ "windows_i686_msvc",
+ "windows_x86_64_gnu",
+ "windows_x86_64_gnullvm",
+ "windows_x86_64_msvc",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
+[[package]]
+name = "writeable"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
+
+[[package]]
+name = "yoke"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
+dependencies = [
+ "stable_deref_trait",
+ "yoke-derive",
+ "zerofrom",
+]
+
+[[package]]
+name = "yoke-derive"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33811428bee40dbceb6d545e95754741d17a6aef9a4849f0fd62e2ba4f412a78"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.3",
+ "synstructure",
+]
+
+[[package]]
+name = "zerofrom"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
+dependencies = [
+ "zerofrom-derive",
+]
+
+[[package]]
+name = "zerofrom-derive"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.3",
+ "synstructure",
+]
+
+[[package]]
+name = "zeroize"
+version = "1.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
+
+[[package]]
+name = "zerotrie"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"
+dependencies = [
+ "displaydoc",
+ "yoke",
+ "zerofrom",
+]
+
+[[package]]
+name = "zerovec"
+version = "0.11.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"
+dependencies = [
+ "yoke",
+ "zerofrom",
+ "zerovec-derive",
+]
+
+[[package]]
+name = "zerovec-derive"
+version = "0.11.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.3",
+]
+
[[package]]
name = "zmij"
version = "1.0.23"
diff --git a/apps/desktop/electron/main/ipc/config-sync-ipc.ts b/apps/desktop/electron/main/ipc/config-sync-ipc.ts
new file mode 100644
index 000000000..f869668cc
--- /dev/null
+++ b/apps/desktop/electron/main/ipc/config-sync-ipc.ts
@@ -0,0 +1,67 @@
+import { IPC } from "@pi-desktop/shared";
+import type { HostProcess } from "../host-process";
+import type { IpcRegistrar } from "./types";
+
+export type ConfigSyncIpcDependencies = {
+ registrar: IpcRegistrar;
+ getHost: () => HostProcess | null;
+ sendToRenderer: (channel: string, payload?: unknown) => void;
+};
+
+/** Keep WebDAV credentials and vault passwords inside Host IPC calls. */
+export function registerConfigSyncIpc({
+ registrar,
+ getHost,
+ sendToRenderer,
+}: ConfigSyncIpcDependencies): void {
+ const callHost = (method: string, params?: unknown) => {
+ const host = getHost();
+ if (!host) throw new Error("host unavailable");
+ return params === undefined ? host.call(method) : host.call(method, params);
+ };
+ const handle = (channel: string, fn: (...args: unknown[]) => Promise<unknown>) => {
+ registrar.handle(channel, async (...args: unknown[]) => {
+ const host = getHost();
+ if (!host) throw new Error("host unavailable");
+ const result = await fn(...args);
+ if (channel !== IPC.invoke.configSyncTest) {
+ sendToRenderer(IPC.event.configSyncChanged, result);
+ }
+ return result;
+ });
+ };
+
+ handle(IPC.invoke.configSyncGetState, () => callHost("configSync.getState"));
+ handle(IPC.invoke.configSyncConfigure, (input: unknown) =>
+ callHost("configSync.configure", input),
+ );
+ handle(IPC.invoke.configSyncTest, (input: unknown) =>
+ callHost("configSync.test", input),
+ );
+ handle(IPC.invoke.configSyncSyncNow, () => callHost("configSync.syncNow"));
+ handle(IPC.invoke.configSyncPause, (input: unknown) =>
+ callHost("configSync.pause", input),
+ );
+ handle(IPC.invoke.configSyncUnlock, (input: unknown) =>
+ callHost("configSync.unlock", input),
+ );
+ handle(IPC.invoke.configSyncApprove, (input: unknown) =>
+ callHost("configSync.approve", input),
+ );
+ handle(IPC.invoke.configSyncReject, (input: unknown) =>
+ callHost("configSync.reject", input),
+ );
+ handle(IPC.invoke.configSyncMapProject, (input: unknown) =>
+ callHost("configSync.mapProject", input),
+ );
+ handle(IPC.invoke.configSyncListHistory, () => callHost("configSync.listHistory"));
+ handle(IPC.invoke.configSyncRestore, (input: unknown) =>
+ callHost("configSync.restore", input),
+ );
+ handle(IPC.invoke.configSyncChangePassword, (input: unknown) =>
+ callHost("configSync.changePassword", input),
+ );
+ handle(IPC.invoke.configSyncDisconnect, () =>
+ callHost("configSync.disconnect"),
+ );
+}
diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.ts
index 6c4818da8..b48a03528 100644
--- a/apps/desktop/electron/main/ipc/register.ts
+++ b/apps/desktop/electron/main/ipc/register.ts
@@ -22,6 +22,7 @@ import { registerPullsIpc } from "./pulls-ipc";
import { registerScheduledIpc } from "./scheduled-ipc";
import { registerSessionIpc } from "./session-ipc";
import { registerSettingsIpc } from "./settings-ipc";
+import { registerConfigSyncIpc } from "./config-sync-ipc";
import { registerSkillsIpc } from "./skills-ipc";
import { registerAgentImportIpc } from "./agent-import-ipc";
import { registerRemoteHostIpc } from "./remote-host-ipc";
@@ -259,6 +260,11 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
applyDeveloperMode,
resolveEffectiveCommandShell,
});
+ registerConfigSyncIpc({
+ registrar,
+ getHost,
+ sendToRenderer,
+ });
registerProviderIpc({
registrar,
getHost,
diff --git a/apps/desktop/electron/main/runtime/host.ts b/apps/desktop/electron/main/runtime/host.ts
index 78472f297..b56755875 100644
--- a/apps/desktop/electron/main/runtime/host.ts
+++ b/apps/desktop/electron/main/runtime/host.ts
@@ -302,6 +302,8 @@ export function createHostRuntime({
);
} else if (method === "plans.changed") {
sendToRenderer(IPC.event.plansChanged, params);
+ } else if (method === "configSync.changed") {
+ sendToRenderer(IPC.event.configSyncChanged, params);
}
});
h.onExit(({ code, signal, intentional }) => {
diff --git a/apps/desktop/src/components/settings/ConfigSyncPage.tsx b/apps/desktop/src/components/settings/ConfigSyncPage.tsx
new file mode 100644
index 000000000..5973349b8
--- /dev/null
+++ b/apps/desktop/src/components/settings/ConfigSyncPage.tsx
@@ -0,0 +1,781 @@
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { useTranslation } from "react-i18next";
+import type {
+ ConfigSyncCategory,
+ ConfigSyncCategorySelection,
+ ConfigSyncHistoryEntry,
+ ConfigSyncPendingApproval,
+ ConfigSyncState,
+} from "@pi-desktop/shared";
+import { api } from "../../lib/api";
+import { Badge, Button, Field, Input, PasswordInput, cx } from "../ui";
+import { IconCloudDown, IconRefresh, IconShield, IconTrash } from "../icons";
+import { SettingsCard, SettingsRow } from "../../features/settings/primitives";
+
+const CATEGORIES: Array<{
+ id: Exclude<ConfigSyncCategory, "credentials" | "memory">;
+ label: string;
+}> = [
+ { id: "application", label: "settings.configSync.categoryApplication" },
+ { id: "providers", label: "settings.configSync.categoryProviders" },
+ { id: "mcp", label: "settings.configSync.categoryMcp" },
+ { id: "skills", label: "settings.configSync.categorySkills" },
+ { id: "subagents", label: "settings.configSync.categorySubagents" },
+ { id: "instructions", label: "settings.configSync.categoryInstructions" },
+ { id: "projects", label: "settings.configSync.categoryProjects" },
+ { id: "plugins", label: "settings.configSync.categoryPlugins" },
+ { id: "automation", label: "settings.configSync.categoryAutomation" },
+];
+
+const DEFAULT_SELECTION: ConfigSyncCategorySelection = {
+ application: true,
+ providers: true,
+ credentials: false,
+ mcp: true,
+ skills: true,
+ subagents: true,
+ instructions: true,
+ projects: true,
+ plugins: true,
+ automation: true,
+ memory: false,
+};
+
+function statusTone(
+ status: ConfigSyncState["status"],
+): "neutral" | "success" | "error" | "warning" {
+ if (status === "upToDate") return "success";
+ if (status === "offline" || status === "error" || status === "unsupportedServer") {
+ return "error";
+ }
+ if (status === "conflict" || status === "awaitingActivation" || status === "locked") {
+ return "warning";
+ }
+ return "neutral";
+}
+
+export function ConfigSyncPage() {
+ const { t } = useTranslation();
+ const [state, setState] = useState<ConfigSyncState | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [busy, setBusy] = useState<
+ | "test"
+ | "configure"
+ | "sync"
+ | "unlock"
+ | "map"
+ | "history"
+ | "restore"
+ | "password"
+ | "disconnect"
+ | null
+ >(null);
+ const [history, setHistory] = useState<ConfigSyncHistoryEntry[]>([]);
+ const [error, setError] = useState<string | null>(null);
+ const [notice, setNotice] = useState<string | null>(null);
+ const [form, setForm] = useState({
+ endpoint: "",
+ username: "",
+ appPassword: "",
+ directory: "pi-desktop",
+ deviceLabel: "",
+ backupPassword: "",
+ currentBackupPassword: "",
+ newBackupPassword: "",
+ });
+ const [selection, setSelection] =
+ useState<ConfigSyncCategorySelection>(DEFAULT_SELECTION);
+
+ const refresh = useCallback(async () => {
+ try {
+ const next = await api.configSyncGetState();
+ setState(next);
+ if (next.configured) {
+ setForm((current) => ({
+ ...current,
+ endpoint: next.endpoint ?? current.endpoint,
+ username: next.username ?? current.username,
+ directory: next.directory ?? current.directory,
+ deviceLabel: next.deviceLabel ?? current.deviceLabel,
+ }));
+ setSelection((current) => ({ ...current, ...next.categories }));
+ if (!next.locked) {
+ try {
+ setHistory(await api.configSyncListHistory());
+ } catch {
+ setHistory([]);
+ }
+ } else {
+ setHistory([]);
+ }
+ }
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : String(cause));
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ const loadHistory = useCallback(async () => {
+ if (!state?.configured || state.locked) return;
+ setBusy("history");
+ try {
+ setHistory(await api.configSyncListHistory());
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : String(cause));
+ } finally {
+ setBusy(null);
+ }
+ }, [state?.configured, state?.locked]);
+
+ useEffect(() => {
+ void refresh();
+ return api.onConfigSyncChanged((next) => setState(next));
+ }, [refresh]);
+
+ const updateForm = (key: keyof typeof form, value: string) =>
+ setForm((current) => ({ ...current, [key]: value }));
+
+ const run = async (
+ operation: "test" | "configure" | "sync" | "unlock" | "disconnect",
+ ) => {
+ setBusy(operation);
+ setError(null);
+ setNotice(null);
+ try {
+ if (operation === "test") {
+ const result = await api.configSyncTest({
+ endpoint: form.endpoint,
+ username: form.username,
+ appPassword: form.appPassword || undefined,
+ directory: form.directory,
+ deviceLabel: form.deviceLabel || t("settings.configSync.defaultDevice"),
+ allowInsecureHttp: false,
+ categories: selection,
+ includeSecrets: selection.credentials,
+ includeMemory: selection.memory,
+ automaticSync: true,
+ });
+ setNotice(
+ result.conditionalWrites
+ ? t("settings.configSync.testSuccess")
+ : t("settings.configSync.testUnsupported"),
+ );
+ } else if (operation === "configure") {
+ await api.configSyncConfigure({
+ endpoint: form.endpoint,
+ username: form.username,
+ appPassword: form.appPassword || undefined,
+ directory: form.directory,
+ deviceLabel: form.deviceLabel || t("settings.configSync.defaultDevice"),
+ backupPassword: form.backupPassword,
+ categories: selection,
+ includeSecrets: selection.credentials,
+ includeMemory: selection.memory,
+ automaticSync: true,
+ });
+ setState(await api.configSyncSyncNow());
+ setForm((current) => ({ ...current, appPassword: "", backupPassword: "" }));
+ setNotice(t("settings.configSync.configured"));
+ } else if (operation === "sync") {
+ setState(await api.configSyncSyncNow());
+ } else if (operation === "unlock") {
+ setState(await api.configSyncUnlock(form.backupPassword));
+ setForm((current) => ({ ...current, backupPassword: "" }));
+ } else {
+ setState(await api.configSyncDisconnect());
+ setHistory([]);
+ setForm((current) => ({ ...current, appPassword: "", backupPassword: "" }));
+ setSelection(DEFAULT_SELECTION);
+ }
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : String(cause));
+ await refresh();
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const changePassword = async () => {
+ setBusy("password");
+ setError(null);
+ setNotice(null);
+ try {
+ setState(
+ await api.configSyncChangePassword({
+ currentPassword: form.currentBackupPassword,
+ newPassword: form.newBackupPassword,
+ }),
+ );
+ setForm((current) => ({
+ ...current,
+ currentBackupPassword: "",
+ newBackupPassword: "",
+ }));
+ setNotice(t("settings.configSync.passwordChanged"));
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : String(cause));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const restore = async (entry: ConfigSyncHistoryEntry) => {
+ if (!window.confirm(t("settings.configSync.restoreConfirm"))) return;
+ setBusy("restore");
+ setError(null);
+ try {
+ setState(
+ await api.configSyncRestore({
+ revisionId: entry.revisionId,
+ acknowledgePropagation: true,
+ }),
+ );
+ setHistory(await api.configSyncListHistory());
+ setNotice(t("settings.configSync.restoreStarted"));
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : String(cause));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const approve = async (approvalId: string, digest: string, accepted: boolean) => {
+ setBusy("sync");
+ setError(null);
+ try {
+ const next = accepted
+ ? await api.configSyncApprove({ approvalId, digest })
+ : await api.configSyncReject({ approvalId, digest });
+ setState(next);
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : String(cause));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const mapProject = async (logicalId: string) => {
+ setBusy("map");
+ setError(null);
+ try {
+ const picked = await api.pickProjectFolders();
+ const paths = picked.folders?.filter(Boolean) ?? [];
+ if (!paths.length) return;
+ setState(
+ await api.configSyncMapProject({
+ logicalId,
+ path: paths[0],
+ paths: paths,
+ }),
+ );
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : String(cause));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const togglePause = async () => {
+ setBusy("sync");
+ setError(null);
+ try {
+ setState(await api.configSyncPause(!state?.paused));
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : String(cause));
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ const statusLabel = useMemo(() => {
+ switch (state?.status ?? "notConfigured") {
+ case "locked":
+ return t("settings.configSync.status.locked");
+ case "upToDate":
+ return t("settings.configSync.status.upToDate");
+ case "localChangesPending":
+ return t("settings.configSync.status.localChangesPending");
+ case "syncing":
+ return t("settings.configSync.status.syncing");
+ case "offline":
+ return t("settings.configSync.status.offline");
+ case "unsupportedServer":
+ return t("settings.configSync.status.unsupportedServer");
+ case "conflict":
+ return t("settings.configSync.status.conflict");
+ case "awaitingActivation":
+ return t("settings.configSync.status.awaitingActivation");
+ case "paused":
+ return t("settings.configSync.status.paused");
+ case "error":
+ return t("settings.configSync.status.error");
+ case "notConfigured":
+ default:
+ return t("settings.configSync.status.notConfigured");
+ }
+ }, [state?.status, t]);
+
+ const approvalReasonLabel = (reason: ConfigSyncPendingApproval["reason"]) => {
+ switch (reason) {
+ case "newDevice":
+ return t("settings.configSync.approvalReason.newDevice");
+ case "securityChange":
+ return t("settings.configSync.approvalReason.securityChange");
+ case "dependency":
+ return t("settings.configSync.approvalReason.dependency");
+ case "mapping":
+ return t("settings.configSync.approvalReason.mapping");
+ case "conflict":
+ return t("settings.configSync.approvalReason.conflict");
+ }
+ };
+
+ if (loading) {
+ return (
+ <div className="settings-recovery" role="status">
+ {t("common.loading")}
+ </div>
+ );
+ }
+
+ const configured = state?.configured === true;
+ const locked = state?.locked === true;
+ const categories = selection;
+
+ return (
+ <div className="settings-stack settings-config-sync">
+ <SettingsCard
+ title={t("settings.configSync.connectionTitle")}
+ description={t("settings.configSync.connectionDescription")}
+ >
+ <div className="settings-config-sync-form">
+ <Field label={t("settings.configSync.endpoint")}>
+ <Input
+ value={form.endpoint}
+ onChange={(event) => updateForm("endpoint", event.target.value)}
+ placeholder={t("settings.configSync.endpointPlaceholder")}
+ aria-label={t("settings.configSync.endpoint")}
+ autoComplete="url"
+ disabled={busy !== null}
+ />
+ </Field>
+ <Field label={t("settings.configSync.username")}>
+ <Input
+ value={form.username}
+ onChange={(event) => updateForm("username", event.target.value)}
+ aria-label={t("settings.configSync.username")}
+ autoComplete="username"
+ disabled={busy !== null}
+ />
+ </Field>
+ <Field label={t("settings.configSync.appPassword")}>
+ <PasswordInput
+ value={form.appPassword}
+ onChange={(event) => updateForm("appPassword", event.target.value)}
+ aria-label={t("settings.configSync.appPassword")}
+ autoComplete="current-password"
+ showLabel={t("settings.configSync.showPassword")}
+ hideLabel={t("settings.configSync.hidePassword")}
+ disabled={busy !== null}
+ />
+ </Field>
+ <Field label={t("settings.configSync.directory")}>
+ <Input
+ value={form.directory}
+ onChange={(event) => updateForm("directory", event.target.value)}
+ aria-label={t("settings.configSync.directory")}
+ autoComplete="off"
+ disabled={busy !== null}
+ />
+ </Field>
+ <Field label={t("settings.configSync.deviceLabel")}>
+ <Input
+ value={form.deviceLabel}
+ onChange={(event) => updateForm("deviceLabel", event.target.value)}
+ placeholder={t("settings.configSync.defaultDevice")}
+ aria-label={t("settings.configSync.deviceLabel")}
+ autoComplete="off"
+ disabled={busy !== null}
+ />
+ </Field>
+ <Field
+ label={
+ configured
+ ? t("settings.configSync.backupPasswordUnlock")
+ : t("settings.configSync.backupPassword")
+ }
+ hint={t("settings.configSync.backupPasswordHint")}
+ >
+ <PasswordInput
+ value={form.backupPassword}
+ onChange={(event) => updateForm("backupPassword", event.target.value)}
+ aria-label={t("settings.configSync.backupPassword")}
+ autoComplete="new-password"
+ showLabel={t("settings.configSync.showPassword")}
+ hideLabel={t("settings.configSync.hidePassword")}
+ disabled={busy !== null}
+ />
+ </Field>
+ </div>
+ <div className="settings-config-sync-actions">
+ <Button
+ variant="secondary"
+ onClick={() => void run("test")}
+ disabled={busy !== null || !form.endpoint}
+ >
+ <IconRefresh size={14} />
+ {t("settings.configSync.test")}
+ </Button>
+ <Button
+ variant="primary"
+ onClick={() => void run("configure")}
+ disabled={busy !== null || !form.endpoint || !form.backupPassword}
+ >
+ <IconCloudDown size={14} />
+ {configured ? t("settings.configSync.save") : t("settings.configSync.enable")}
+ </Button>
+ {configured && !locked ? (
+ <Button
+ variant="secondary"
+ onClick={() => void run("sync")}
+ disabled={busy !== null || state?.paused}
+ >
+ {t("settings.configSync.syncNow")}
+ </Button>
+ ) : null}
+ </div>
+ {error ? (
+ <div className="settings-config-sync-message error" role="alert">
+ {error}
+ </div>
+ ) : null}
+ {notice ? (
+ <div className="settings-config-sync-message" role="status">
+ {notice}
+ </div>
+ ) : null}
+ </SettingsCard>
+
+ {configured ? (
+ <>
+ <SettingsCard title={t("settings.configSync.statusTitle")}>
+ <SettingsRow
+ title={t("settings.configSync.statusLabel")}
+ detail={
+ state?.lastSuccessAt
+ ? t("settings.configSync.lastSuccess", {
+ date: state.lastSuccessAt,
+ })
+ : undefined
+ }
+ >
+ <Badge tone={statusTone(state.status)}>{statusLabel}</Badge>
+ </SettingsRow>
+ {state?.lastError ? (
+ <SettingsRow title={t("settings.configSync.lastError")}>
+ <span className="settings-config-sync-error">{state.lastError}</span>
+ </SettingsRow>
+ ) : null}
+ {locked ? (
+ <SettingsRow
+ title={t("settings.configSync.unlockTitle")}
+ description={t("settings.configSync.unlockDescription")}
+ >
+ <Button
+ variant="primary"
+ onClick={() => void run("unlock")}
+ disabled={busy !== null || !form.backupPassword}
+ >
+ <IconShield size={14} />
+ {t("settings.configSync.unlock")}
+ </Button>
+ </SettingsRow>
+ ) : (
+ <SettingsRow
+ title={t("settings.configSync.pauseTitle")}
+ description={t("settings.configSync.pauseDescription")}
+ >
+ <button
+ type="button"
+ className={cx("settings-toggle", state?.paused && "on")}
+ role="switch"
+ aria-checked={state?.paused === true}
+ aria-label={t("settings.configSync.pauseTitle")}
+ onClick={() => void togglePause()}
+ >
+ <span className="settings-toggle-thumb" />
+ </button>
+ </SettingsRow>
+ )}
+ {!locked ? (
+ <SettingsRow
+ title={t("settings.configSync.changePasswordTitle")}
+ description={t("settings.configSync.changePasswordDescription")}
+ >
+ <div className="settings-config-sync-password-actions">
+ <PasswordInput
+ value={form.currentBackupPassword}
+ onChange={(event) =>
+ updateForm("currentBackupPassword", event.target.value)
+ }
+ aria-label={t("settings.configSync.currentBackupPassword")}
+ placeholder={t("settings.configSync.currentBackupPassword")}
+ autoComplete="current-password"
+ showLabel={t("settings.configSync.showPassword")}
+ hideLabel={t("settings.configSync.hidePassword")}
+ disabled={busy !== null}
+ />
+ <PasswordInput
+ value={form.newBackupPassword}
+ onChange={(event) =>
+ updateForm("newBackupPassword", event.target.value)
+ }
+ aria-label={t("settings.configSync.newBackupPassword")}
+ placeholder={t("settings.configSync.newBackupPassword")}
+ autoComplete="new-password"
+ showLabel={t("settings.configSync.showPassword")}
+ hideLabel={t("settings.configSync.hidePassword")}
+ disabled={busy !== null}
+ />
+ <Button
+ variant="secondary"
+ onClick={() => void changePassword()}
+ disabled={
+ busy !== null ||
+ !form.currentBackupPassword ||
+ !form.newBackupPassword
+ }
+ >
+ {t("settings.configSync.changePassword")}
+ </Button>
+ </div>
+ </SettingsRow>
+ ) : null}
+ </SettingsCard>
+
+ <SettingsCard
+ title={t("settings.configSync.categoriesTitle")}
+ description={t("settings.configSync.categoriesDescription")}
+ >
+ <div className="settings-config-sync-categories">
+ {CATEGORIES.map((category) => (
+ <label key={category.id} className="settings-config-sync-category">
+ <input
+ type="checkbox"
+ checked={categories[category.id] !== false}
+ onChange={(event) =>
+ setSelection((current) => ({
+ ...current,
+ [category.id]: event.target.checked,
+ }))
+ }
+ />
+ <span>{t(category.label)}</span>
+ </label>
+ ))}
+ <label className="settings-config-sync-category">
+ <input
+ type="checkbox"
+ checked={selection.memory}
+ onChange={(event) =>
+ setSelection((current) => ({
+ ...current,
+ memory: event.target.checked,
+ }))
+ }
+ />
+ <span>{t("settings.configSync.categoryMemory")}</span>
+ </label>
+ <label className="settings-config-sync-category settings-config-sync-sensitive">
+ <input
+ type="checkbox"
+ checked={selection.credentials}
+ onChange={(event) =>
+ setSelection((current) => ({
+ ...current,
+ credentials: event.target.checked,
+ }))
+ }
+ />
+ <span>{t("settings.configSync.categoryCredentials")}</span>
+ </label>
+ </div>
+ {selection.credentials ? (
+ <div className="settings-config-sync-warning">
+ {t("settings.configSync.credentialsWarning")}
+ </div>
+ ) : null}
+ </SettingsCard>
+
+ {state?.pendingApprovals.length ? (
+ <SettingsCard
+ title={t("settings.configSync.approvalsTitle")}
+ description={t("settings.configSync.approvalsDescription")}
+ >
+ <div className="settings-config-sync-approvals">
+ {state.pendingApprovals.map((approval) => (
+ <div key={approval.id} className="settings-config-sync-approval">
+ <div>
+ <div className="settings-config-sync-approval-title">
+ {approval.label}
+ </div>
+ <div className="settings-config-sync-approval-meta">
+ {approvalReasonLabel(approval.reason)}
+ </div>
+ </div>
+ <div className="settings-config-sync-actions">
+ {approval.mappingKey ? (
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={() => void mapProject(approval.mappingKey!)}
+ disabled={busy !== null}
+ >
+ {t("settings.configSync.mapFolder")}
+ </Button>
+ ) : null}
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={() => void approve(approval.id, approval.digest, false)}
+ disabled={busy !== null}
+ >
+ {t("settings.configSync.reject")}
+ </Button>
+ <Button
+ size="sm"
+ variant="primary"
+ onClick={() => void approve(approval.id, approval.digest, true)}
+ disabled={busy !== null}
+ >
+ {t("settings.configSync.approve")}
+ </Button>
+ </div>
+ </div>
+ ))}
+ </div>
+ </SettingsCard>
+ ) : null}
+
+ {state?.preview ? (
+ <SettingsCard title={t("settings.configSync.previewTitle")}>
+ <div className="settings-config-sync-preview">
+ <span>
+ {t("settings.configSync.previewSupported", {
+ count: state.preview.supported,
+ })}
+ </span>
+ <span>
+ {t("settings.configSync.previewExcluded", {
+ count: state.preview.excluded,
+ })}
+ </span>
+ <span>
+ {t("settings.configSync.previewSecrets", {
+ count: state.preview.secretBearing,
+ })}
+ </span>
+ <span>
+ {t("settings.configSync.previewMapping", {
+ count: state.preview.mappingRequired,
+ })}
+ </span>
+ </div>
+ </SettingsCard>
+ ) : null}
+
+ {state?.mappings.length ? (
+ <SettingsCard
+ title={t("settings.configSync.mappingsTitle")}
+ description={t("settings.configSync.mappingsDescription")}
+ >
+ <div className="settings-config-sync-mappings">
+ {state.mappings.map((mapping) => (
+ <div key={mapping.logicalId} className="settings-config-sync-mapping">
+ <span className="settings-config-sync-mapping-id">
+ {mapping.logicalId}
+ </span>
+ <code>
+ {mapping.paths?.length
+ ? mapping.paths.join(" · ")
+ : mapping.path ?? t("settings.configSync.mappingUnavailable")}
+ </code>
+ </div>
+ ))}
+ </div>
+ </SettingsCard>
+ ) : null}
+
+ <SettingsCard
+ title={t("settings.configSync.historyTitle")}
+ description={t("settings.configSync.historyDescription")}
+ >
+ <div className="settings-config-sync-history-actions">
+ <Button
+ variant="secondary"
+ onClick={() => void loadHistory()}
+ disabled={busy !== null || locked}
+ >
+ <IconRefresh size={14} />
+ {t("settings.configSync.refreshHistory")}
+ </Button>
+ </div>
+ {history.length ? (
+ <div className="settings-config-sync-history">
+ {history.map((entry) => (
+ <div key={entry.revisionId} className="settings-config-sync-history-row">
+ <div>
+ <div className="settings-config-sync-approval-title">
+ {entry.current
+ ? t("settings.configSync.currentRevision")
+ : entry.revisionId}
+ </div>
+ <div className="settings-config-sync-approval-meta">
+ {entry.createdAt} · {entry.entityCount} {t("settings.configSync.historyItems")}
+ </div>
+ </div>
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={() => void restore(entry)}
+ disabled={busy !== null || entry.current || locked}
+ >
+ {t("settings.configSync.restore")}
+ </Button>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <div className="settings-config-sync-history-empty">
+ {locked
+ ? t("settings.configSync.historyLocked")
+ : t("settings.configSync.historyEmpty")}
+ </div>
+ )}
+ </SettingsCard>
+
+ <SettingsCard>
+ <SettingsRow
+ title={t("settings.configSync.disconnectTitle")}
+ description={t("settings.configSync.disconnectDescription")}
+ >
+ <Button
+ variant="secondary"
+ onClick={() => {
+ if (window.confirm(t("settings.configSync.disconnectConfirm"))) {
+ void run("disconnect");
+ }
+ }}
+ disabled={busy !== null}
+ >
+ <IconTrash size={14} />
+ {t("settings.configSync.disconnect")}
+ </Button>
+ </SettingsRow>
+ </SettingsCard>
+ </>
+ ) : null}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/features/settings/SettingsPage.tsx b/apps/desktop/src/features/settings/SettingsPage.tsx
index d426bb1e4..716731226 100644
--- a/apps/desktop/src/features/settings/SettingsPage.tsx
+++ b/apps/desktop/src/features/settings/SettingsPage.tsx
@@ -30,6 +30,7 @@ import {
IconServer,
IconSliders,
IconSparkles,
+ IconCloudDown,
} from "../../components/icons";
import { Badge, Button, cx } from "../../components/ui";
import { ModelConfigPage } from "../../components/settings/ModelConfigPage";
@@ -59,6 +60,7 @@ import { ImportSection } from "./import-page";
import { PromptEnhancementCard } from "./prompt-enhancement-card";
import { CloseBehaviorSection, DeveloperSection } from "./developer-sections";
import { PluginScenicThemesDestination } from "../../components/settings/PluginScenicThemesDestination";
+import { ConfigSyncPage } from "../../components/settings/ConfigSyncPage";
type SettingsTab = ReturnType<typeof useAppStore.getState>["settingsTab"];
@@ -204,6 +206,7 @@ export function SettingsPage() {
subagents: <IconBot size={14} />,
import: <IconDownload size={14} />,
projects: <IconArchive size={14} />,
+ sync: <IconCloudDown size={14} />,
remoteHosts: <IconGlobe size={14} />,
about: <IconInfo size={14} />,
};
@@ -520,6 +523,8 @@ export function SettingsPage() {
{tab === "projects" && <ProjectsPage />}
+ {tab === "sync" && <ConfigSyncPage />}
+
{tab === "remoteHosts" && !tabHidden && <RemoteHostsPage />}
{tab === "about" && (
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index d2a4c03fb..54efa37e5 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -111,6 +111,13 @@ import type {
UpdateState,
WindowControlAction,
CloseBehavior,
+ ConfigSyncApprovalInput,
+ ConfigSyncChangePasswordInput,
+ ConfigSyncHistoryEntry,
+ ConfigSyncMapProjectInput,
+ ConfigSyncConfigureInput,
+ ConfigSyncRestoreInput,
+ ConfigSyncState,
TrustedExtensionStatusEvent,
TrustedExtensionUiPrompt,
TrustedExtensionUiPromptResponse,
@@ -583,6 +590,32 @@ export const api = {
getSettings: () => invoke<AppSettings>(IPC.invoke.settingsGet).then(normalizeSettings),
setSettings: (settings: AppSettings) =>
invoke(IPC.invoke.settingsSet, validateSettingsWrite(settings)),
+ configSyncGetState: () => invoke<ConfigSyncState>(IPC.invoke.configSyncGetState),
+ configSyncConfigure: (input: ConfigSyncConfigureInput) =>
+ invoke<ConfigSyncState>(IPC.invoke.configSyncConfigure, input),
+ configSyncTest: (input: Omit<ConfigSyncConfigureInput, "backupPassword"> & { backupPassword?: string }) =>
+ invoke<{ ok: boolean; conditionalWrites: boolean; message?: string }>(
+ IPC.invoke.configSyncTest,
+ input,
+ ),
+ configSyncSyncNow: () => invoke<ConfigSyncState>(IPC.invoke.configSyncSyncNow),
+ configSyncPause: (paused: boolean) =>
+ invoke<ConfigSyncState>(IPC.invoke.configSyncPause, { paused }),
+ configSyncUnlock: (backupPassword: string) =>
+ invoke<ConfigSyncState>(IPC.invoke.configSyncUnlock, { backupPassword }),
+ configSyncApprove: (input: ConfigSyncApprovalInput) =>
+ invoke<ConfigSyncState>(IPC.invoke.configSyncApprove, input),
+ configSyncReject: (input: ConfigSyncApprovalInput) =>
+ invoke<ConfigSyncState>(IPC.invoke.configSyncReject, input),
+ configSyncMapProject: (input: ConfigSyncMapProjectInput) =>
+ invoke<ConfigSyncState>(IPC.invoke.configSyncMapProject, input),
+ configSyncListHistory: () =>
+ invoke<ConfigSyncHistoryEntry[]>(IPC.invoke.configSyncListHistory),
+ configSyncRestore: (input: ConfigSyncRestoreInput) =>
+ invoke<ConfigSyncState>(IPC.invoke.configSyncRestore, input),
+ configSyncChangePassword: (input: ConfigSyncChangePasswordInput) =>
+ invoke<ConfigSyncState>(IPC.invoke.configSyncChangePassword, input),
+ configSyncDisconnect: () => invoke<ConfigSyncState>(IPC.invoke.configSyncDisconnect),
testNetworkProxy: (settings: unknown) =>
invoke<{ ok: boolean; error?: string }>(IPC.invoke.networkProxyTest, settings),
/** Installed system font families (Electron main, cached briefly). */
@@ -1489,6 +1522,12 @@ export const api = {
listener((payload ?? {}) as Record<string, unknown>),
);
},
+ onConfigSyncChanged: (listener: (state: ConfigSyncState) => void) => {
+ if (!window.piDesktop?.on) return () => undefined;
+ return window.piDesktop.on(IPC.event.configSyncChanged, (payload) =>
+ listener(payload as ConfigSyncState),
+ );
+ },
onPluginLauncherShown: (listener: () => void) => {
if (!window.piDesktop?.on) return () => undefined;
return window.piDesktop.on(IPC.event.pluginLauncherShown, () => listener());
diff --git a/apps/desktop/src/lib/settings-search.ts b/apps/desktop/src/lib/settings-search.ts
index 44a4b293c..0e9067a25 100644
--- a/apps/desktop/src/lib/settings-search.ts
+++ b/apps/desktop/src/lib/settings-search.ts
@@ -16,6 +16,7 @@ export type SettingsTabId =
| "subagents"
| "import"
| "projects"
+ | "sync"
| "remoteHosts"
| "about";
@@ -237,6 +238,20 @@ export const SETTINGS_NAV: SettingsNavEntry[] = [
"project.delete",
],
},
+ {
+ id: "sync",
+ labelKey: "settings.nav.sync",
+ titleKey: "settings.configSync.title",
+ group: "system",
+ keywordKeys: [
+ "settings.configSync.connectionTitle",
+ "settings.configSync.endpoint",
+ "settings.configSync.statusTitle",
+ "settings.configSync.categoriesTitle",
+ "settings.configSync.approvalsTitle",
+ "settings.configSync.syncNow",
+ ],
+ },
{
id: "remoteHosts",
labelKey: "settings.nav.remoteHosts",
diff --git a/apps/desktop/src/styles/settings.css b/apps/desktop/src/styles/settings.css
index 23d4f77d0..2298b8bf7 100644
--- a/apps/desktop/src/styles/settings.css
+++ b/apps/desktop/src/styles/settings.css
@@ -457,6 +457,203 @@
padding: 12px 14px 14px;
}
+.settings-config-sync-form {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 12px;
+ padding: 14px 16px;
+}
+
+.settings-config-sync-form .field-input,
+.settings-config-sync-form .password-input {
+ width: 100%;
+}
+
+.settings-config-sync-actions {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 8px;
+}
+
+.settings-config-sync > .settings-card-block:first-child .settings-config-sync-actions {
+ padding: 0 16px 14px;
+}
+
+.settings-config-sync-message {
+ margin: 0 16px 14px;
+ color: var(--ds-text-secondary);
+ font-size: var(--text-sm);
+ overflow-wrap: anywhere;
+}
+
+.settings-config-sync-message.error,
+.settings-config-sync-error {
+ color: var(--ds-danger);
+}
+
+.settings-config-sync-categories {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 8px 18px;
+ padding: 14px 16px;
+}
+
+.settings-config-sync-category {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ color: var(--ds-text-secondary);
+ font-size: var(--text-sm);
+}
+
+.settings-config-sync-category input {
+ accent-color: var(--ds-accent);
+}
+
+.settings-config-sync-sensitive {
+ color: var(--ds-warning);
+}
+
+.settings-config-sync-warning {
+ margin: 0 16px 14px;
+ padding: 10px 12px;
+ border-radius: var(--radius-md);
+ background: color-mix(in srgb, var(--ds-warning) 12%, transparent);
+ color: var(--ds-warning);
+ font-size: var(--text-sm);
+}
+
+.settings-config-sync-approvals {
+ display: grid;
+ gap: 6px;
+}
+
+.settings-config-sync-approval {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 14px;
+ padding: 12px 16px;
+ border-radius: var(--radius-md-plus);
+ background: var(--ds-tile);
+}
+
+.settings-config-sync-approval-title {
+ color: var(--ds-text-primary);
+ font-size: var(--text-sm);
+ font-weight: var(--font-weight-medium);
+}
+
+.settings-config-sync-approval-meta,
+.settings-config-sync-preview {
+ color: var(--ds-text-muted);
+ font-size: var(--text-xs);
+}
+
+.settings-config-sync-preview {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px 18px;
+ padding: 14px 16px;
+}
+
+.settings-config-sync-mappings {
+ display: grid;
+ gap: 8px;
+}
+
+.settings-config-sync-mapping {
+ display: grid;
+ grid-template-columns: minmax(0, 0.8fr) minmax(0, 1.2fr);
+ gap: 12px;
+ align-items: center;
+ padding: 8px 10px;
+ border: 1px solid var(--ds-border-subtle);
+ border-radius: var(--radius-md);
+ background: var(--ds-tile);
+ color: var(--ds-text-muted);
+ font-size: var(--text-xs);
+}
+
+.settings-config-sync-mapping-id,
+.settings-config-sync-mapping code {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.settings-config-sync-password-actions {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ justify-content: flex-end;
+ gap: 8px;
+ max-width: 640px;
+}
+
+.settings-config-sync-password-actions .password-input {
+ width: 180px;
+}
+
+.settings-config-sync-history-actions {
+ display: flex;
+ justify-content: flex-end;
+ padding: 0 16px 10px;
+}
+
+.settings-config-sync-history {
+ display: grid;
+ gap: 6px;
+}
+
+.settings-config-sync-history-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 14px;
+ padding: 12px 16px;
+ border-radius: var(--radius-md-plus);
+ background: var(--ds-tile);
+}
+
+.settings-config-sync-history-empty {
+ padding: 4px 16px 14px;
+ color: var(--ds-text-muted);
+ font-size: var(--text-sm);
+}
+
+@media (max-width: 700px) {
+ .settings-config-sync-form,
+ .settings-config-sync-categories {
+ grid-template-columns: minmax(0, 1fr);
+ }
+
+ .settings-config-sync-approval {
+ align-items: flex-start;
+ flex-direction: column;
+ }
+
+ .settings-config-sync-mapping {
+ grid-template-columns: minmax(0, 1fr);
+ }
+
+ .settings-config-sync-password-actions {
+ align-items: stretch;
+ flex-direction: column;
+ width: 100%;
+ }
+
+ .settings-config-sync-password-actions .password-input {
+ width: 100%;
+ }
+
+ .settings-config-sync-history-row {
+ align-items: flex-start;
+ flex-direction: column;
+ }
+}
+
/*
Remote hosts: inventory tiles, one Add form with SSH/Pair tabs, and
Experimental rows. The form keeps a two-column grid; host cards are
diff --git a/apps/desktop/test/config-sync-settings.test.mjs b/apps/desktop/test/config-sync-settings.test.mjs
new file mode 100644
index 000000000..a00aa8864
--- /dev/null
+++ b/apps/desktop/test/config-sync-settings.test.mjs
@@ -0,0 +1,44 @@
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+import { loadStyles } from "./helpers/styles.mjs";
+
+const read = (relativePath) =>
+ readFile(new URL(relativePath, import.meta.url), "utf8");
+
+const settingsPage = await read("../src/features/settings/SettingsPage.tsx");
+const settingsIndex = await read("../src/lib/settings-search.ts");
+const syncPage = await read("../src/components/settings/ConfigSyncPage.tsx");
+const syncIpc = await read("../electron/main/ipc/config-sync-ipc.ts");
+const styles = await loadStyles();
+
+test("cloud sync is a searchable settings destination", () => {
+ assert.match(settingsPage, /tab === "sync" && <ConfigSyncPage \/>/);
+ assert.match(settingsIndex, /id: "sync"/);
+ assert.match(settingsIndex, /settings\.configSync\.connectionTitle/);
+});
+
+test("cloud sync keeps credentials and vault operations on the host boundary", () => {
+ assert.match(syncPage, /api\.configSyncConfigure\(/);
+ assert.match(syncPage, /setState\(await api\.configSyncSyncNow\(\)\)/);
+ assert.match(syncPage, /api\.configSyncUnlock\(/);
+ assert.match(syncPage, /api\.configSyncMapProject\(/);
+ assert.match(syncPage, /api\.configSyncListHistory\(/);
+ assert.match(syncPage, /api\.configSyncRestore\(/);
+ assert.match(syncPage, /api\.configSyncChangePassword\(/);
+ assert.match(syncPage, /paths: paths/);
+ assert.match(syncPage, /window\.confirm\(/);
+ assert.doesNotMatch(syncPage, /lastVaultKey|portableApiKey|decryptedResource/);
+ assert.match(syncIpc, /callHost\("configSync\.configure"/);
+ assert.match(syncIpc, /callHost\("configSync\.mapProject"/);
+ assert.match(syncIpc, /callHost\("configSync\.restore"/);
+ assert.match(syncIpc, /callHost\("configSync\.changePassword"/);
+});
+
+test("cloud sync settings remain usable on narrow surfaces", () => {
+ assert.match(
+ styles,
+ /\.settings-config-sync-form,\n \.settings-config-sync-categories \{\n grid-template-columns: minmax\(0, 1fr\);/s,
+ );
+ assert.match(styles, /\.settings-config-sync-approval \{[\s\S]*flex-direction: column;/s);
+});
diff --git a/crates/host-core/Cargo.toml b/crates/host-core/Cargo.toml
index 78c938889..bf682c542 100644
--- a/crates/host-core/Cargo.toml
+++ b/crates/host-core/Cargo.toml
@@ -27,7 +27,9 @@ tokio = { version = "1", features = ["full"] }
uuid = { version = "1", features = ["v4", "serde"] }
walkdir = "2"
aes-gcm = "0.11"
+argon2 = "0.5"
rand = "0.10"
+reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "http2"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
diff --git a/crates/host-core/src/config_sync/apply.rs b/crates/host-core/src/config_sync/apply.rs
new file mode 100644
index 000000000..063840297
--- /dev/null
+++ b/crates/host-core/src/config_sync/apply.rs
@@ -0,0 +1,768 @@
+use super::*;
+
+fn mapped_project_paths(config: &StoredConfig, payload: &Value) -> Result<Option<Vec<String>>> {
+ let logical_ids = [
+ payload.get("projectGroupLogicalId"),
+ payload.get("projectLogicalId"),
+ payload.get("workspaceProjectLogicalId"),
+ payload.get("logicalId"),
+ ]
+ .into_iter()
+ .flatten()
+ .filter_map(Value::as_str)
+ .collect::<Vec<_>>();
+ if logical_ids.is_empty() {
+ return Ok(None);
+ }
+ let paths = logical_ids
+ .iter()
+ .find_map(|logical_id| config.project_group_mappings.get(*logical_id).cloned())
+ .or_else(|| {
+ logical_ids.iter().find_map(|logical_id| {
+ config
+ .project_mappings
+ .get(*logical_id)
+ .map(|path| vec![path.clone()])
+ })
+ })
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_MAPPING_REQUIRED: project folder is not mapped"))?;
+ if paths.is_empty() {
+ bail!("CONFIG_SYNC_MAPPING_REQUIRED: project folder is not mapped");
+ }
+ for path in &paths {
+ if !Path::new(path).is_dir() {
+ bail!("CONFIG_SYNC_MAPPING_REQUIRED: mapped project folder is unavailable");
+ }
+ }
+ Ok(Some(paths))
+}
+
+fn mapped_project_path(config: &StoredConfig, payload: &Value) -> Result<Option<String>> {
+ let Some(paths) = mapped_project_paths(config, payload)? else {
+ return Ok(None);
+ };
+ let position = payload
+ .get("projectRootPosition")
+ .and_then(Value::as_u64)
+ .map(|value| value as usize);
+ if let Some(position) = position {
+ if let Some(path) = paths.get(position) {
+ return Ok(Some(path.clone()));
+ }
+ bail!("CONFIG_SYNC_MAPPING_REQUIRED: project root mapping is incomplete");
+ }
+ Ok(paths.into_iter().next())
+}
+
+fn required_resource(bundle: &PendingBundle, entity: &PortableEntity) -> Result<String> {
+ let id = entity
+ .resource_ids
+ .first()
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: portable entity has no resource"))?;
+ let bytes = bundle
+ .resources
+ .get(id)
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_REMOTE: portable resource is missing"))?;
+ String::from_utf8(bytes.clone()).context("portable resource is not UTF-8")
+}
+
+fn require_provider_reference(st: &AppState, value: &Value, context: &str) -> Result<()> {
+ let Some(provider_id) = value.get("providerId").and_then(Value::as_str) else {
+ return Ok(());
+ };
+ if providers::get_provider(&st.db, &st.secrets, provider_id)?.is_none() {
+ bail!("CONFIG_SYNC_DEPENDENCY: {context} references missing provider {provider_id}");
+ }
+ Ok(())
+}
+
+pub(crate) fn validate_application_references(st: &AppState, payload: &Value) -> Result<()> {
+ for provider_key in ["defaultProviderId", "promptEnhancementProviderId"] {
+ let Some(provider_id) = payload.get(provider_key).and_then(Value::as_str) else {
+ continue;
+ };
+ if providers::get_provider(&st.db, &st.secrets, provider_id)?.is_none() {
+ bail!(
+ "CONFIG_SYNC_DEPENDENCY: {provider_key} references missing provider {provider_id}"
+ );
+ }
+ }
+ if let Some(binding) = payload.get("imageGeneration") {
+ require_provider_reference(st, binding, "imageGeneration")?;
+ }
+ if let Some(bindings) = payload
+ .get("imageGenerationModels")
+ .and_then(Value::as_array)
+ {
+ for binding in bindings {
+ require_provider_reference(st, binding, "imageGenerationModels")?;
+ }
+ }
+ if let Some(speech) = payload.get("speech").and_then(Value::as_object) {
+ for (role, binding) in speech {
+ require_provider_reference(st, binding, &format!("speech.{role}"))?;
+ }
+ }
+ Ok(())
+}
+
+fn apply_entity(
+ st: &mut AppState,
+ config: &mut StoredConfig,
+ bundle: &PendingBundle,
+ entity: &PortableEntity,
+) -> Result<()> {
+ if entity.domain == domains::DOMAIN_APPLICATION {
+ validate_application_references(st, &entity.payload)?;
+ let mut current = st.db.get_setting("app")?.unwrap_or_else(|| json!({}));
+ if let (Some(current), Some(incoming)) =
+ (current.as_object_mut(), entity.payload.as_object())
+ {
+ for field in domains::PORTABLE_APPLICATION_FIELDS {
+ if !incoming.contains_key(*field) {
+ current.remove(*field);
+ }
+ }
+ current.extend(incoming.clone());
+ }
+ return st.db.set_setting("app", &current);
+ }
+ if entity.domain == domains::DOMAIN_PROVIDERS {
+ let provider_id = entity
+ .payload
+ .get("id")
+ .and_then(Value::as_str)
+ .or_else(|| entity.entity_id.strip_prefix("provider:"))
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: provider entity id is invalid"))?;
+ if entity.deleted {
+ let _ = providers::delete_provider(&st.db, &st.secrets, provider_id)?;
+ return Ok(());
+ }
+ let mut payload = entity.payload.clone();
+ let secret_value = payload
+ .get("portableApiKey")
+ .and_then(Value::as_str)
+ .map(str::to_string);
+ if let Some(object) = payload.as_object_mut() {
+ object.remove("portableApiKey");
+ object.insert("id".into(), Value::String(provider_id.into()));
+ if let Some(secret) = secret_value.as_ref() {
+ object.insert("secretValue".into(), Value::String(secret.clone()));
+ }
+ }
+ let exists = st
+ .db
+ .conn()
+ .query_row(
+ "SELECT 1 FROM providers WHERE id = ?1",
+ rusqlite::params![provider_id],
+ |_| Ok(()),
+ )
+ .optional()?
+ .is_some();
+ let missing_portable_secret = entity.secret_bearing && secret_value.is_none();
+ if exists {
+ let input: ProviderUpdateInput = serde_json::from_value(payload)?;
+ providers::update_provider(&st.db, &st.secrets, input)?;
+ } else {
+ let input: ProviderCreateInput = serde_json::from_value(payload)?;
+ providers::create_provider_with_id(&st.db, &st.secrets, provider_id, input)?;
+ if missing_portable_secret {
+ st.db.conn().execute(
+ "UPDATE providers SET enabled = 0 WHERE id = ?1",
+ rusqlite::params![provider_id],
+ )?;
+ }
+ }
+ return Ok(());
+ }
+ if entity.domain == domains::DOMAIN_MCP {
+ let mut payload = entity.payload.clone();
+ if let Some(path) = mapped_project_path(config, &payload)? {
+ if let Some(object) = payload.as_object_mut() {
+ object.remove("projectLogicalId");
+ object.insert("projectPath".into(), Value::String(path));
+ object.insert("level".into(), Value::String("project".into()));
+ }
+ }
+ let input: McpServerInput = serde_json::from_value(payload)?;
+ let mut input = input;
+ if entity.secret_bearing && input.env.is_none() && input.headers.is_none() {
+ // A credential-excluded MCP record is retained as an explicit,
+ // disabled definition. Approval alone must not claim it is ready
+ // to send requests without the device-local secret values.
+ input.enabled = Some(false);
+ }
+ if entity.deleted {
+ let level = input
+ .level
+ .as_deref()
+ .and_then(|value| CapabilityLevel::parse(Some(value)).ok());
+ let _ = st
+ .mcp_servers
+ .remove(&input.id, level, input.project_path.as_deref())?;
+ } else {
+ st.mcp_servers.upsert(input)?;
+ }
+ return Ok(());
+ }
+ if entity.domain == domains::DOMAIN_SKILLS {
+ let mut input: crate::user_skills::UserSkillInput =
+ serde_json::from_value(entity.payload.clone())?;
+ if let Some(path) = mapped_project_path(config, &entity.payload)? {
+ input.project_path = Some(path);
+ input.level = Some("project".into());
+ }
+ if !entity.deleted {
+ input.body = Some(required_resource(bundle, entity)?);
+ }
+ let package_files =
+ entity
+ .payload
+ .get("packageFiles")
+ .and_then(Value::as_array)
+ .map(|descriptors| {
+ descriptors
+ .iter()
+ .map(|descriptor| {
+ let path = descriptor.get("path").and_then(Value::as_str).ok_or_else(
+ || anyhow!("CONFIG_SYNC_INVALID: skill package path is missing"),
+ )?;
+ let resource_id = descriptor
+ .get("resourceId")
+ .and_then(Value::as_str)
+ .ok_or_else(|| {
+ anyhow!(
+ "CONFIG_SYNC_INVALID: skill package resource is missing"
+ )
+ })?;
+ let bytes =
+ bundle.resources.get(resource_id).cloned().ok_or_else(|| {
+ anyhow!("CONFIG_SYNC_REMOTE: skill package resource is missing")
+ })?;
+ Ok((path.to_string(), bytes))
+ })
+ .collect::<Result<Vec<_>>>()
+ })
+ .transpose()?
+ .unwrap_or_default();
+ if !package_files.is_empty() {
+ input.shape = Some("dir".into());
+ }
+ let id = input.id.clone().unwrap_or_default();
+ let package_project_path = input.project_path.clone();
+ let level = input
+ .level
+ .as_deref()
+ .and_then(|value| CapabilityLevel::parse(Some(value)).ok());
+ if entity.deleted {
+ if !id.is_empty() {
+ st.user_skills
+ .remove(&id, level, input.project_path.as_deref())?;
+ }
+ } else if st.user_skills.update(&id, input.clone())?.is_none() {
+ st.user_skills.create(input)?;
+ }
+ if !entity.deleted {
+ st.user_skills.write_package_files(
+ &id,
+ level.unwrap_or(CapabilityLevel::Global),
+ package_project_path.as_deref(),
+ &package_files,
+ )?;
+ }
+ return Ok(());
+ }
+ if entity.domain == domains::DOMAIN_SUBAGENTS {
+ let mut input: crate::user_subagents::UserSubagentInput =
+ serde_json::from_value(entity.payload.clone())?;
+ if !entity.deleted {
+ input.body = Some(required_resource(bundle, entity)?);
+ }
+ let id = input.id.clone().unwrap_or_default();
+ if entity.deleted {
+ st.user_subagents.remove(&id)?;
+ } else if st.user_subagents.update(&id, input.clone())?.is_none() {
+ st.user_subagents.create(input)?;
+ }
+ return Ok(());
+ }
+ if entity.domain == domains::DOMAIN_MEMORY {
+ let Some(paths) = mapped_project_paths(config, &entity.payload)? else {
+ bail!("CONFIG_SYNC_MAPPING_REQUIRED: project memory needs a local folder");
+ };
+ let group_logical_id = entity
+ .payload
+ .get("projectGroupLogicalId")
+ .and_then(Value::as_str);
+ let is_group_memory =
+ group_logical_id.is_some() && entity.payload.get("projectRootPosition").is_none();
+ if is_group_memory {
+ let group = st.db.stored_project_group_for_path(&paths[0])?;
+ let group_id = if let Some(group) = group {
+ group.id
+ } else if entity.deleted {
+ if let Some(group) = st.db.project_group_for_path(&paths[0])? {
+ st.db.delete_project_memory(&group.primary_path)?;
+ }
+ return Ok(());
+ } else {
+ let name = entity
+ .payload
+ .get("projectGroupName")
+ .and_then(Value::as_str)
+ .unwrap_or("Imported project")
+ .to_string();
+ st.db.create_project_group(&name, &paths)?.id
+ };
+ if entity.deleted {
+ st.db.set_project_group_memory(&group_id, &json!([]))?;
+ } else if let Some(memory) = entity.payload.get("memory") {
+ if let Some(entries) = memory.get("entries") {
+ st.db.set_project_group_memory(&group_id, entries)?;
+ } else {
+ let content = memory
+ .get("content")
+ .and_then(Value::as_str)
+ .unwrap_or_default();
+ let entries = json!([{
+ "id": "imported-content",
+ "title": "Imported memory",
+ "content": content,
+ }]);
+ st.db.set_project_group_memory(&group_id, &entries)?;
+ }
+ }
+ return Ok(());
+ }
+ let Some(path) = mapped_project_path(config, &entity.payload)? else {
+ bail!("CONFIG_SYNC_MAPPING_REQUIRED: project memory needs a local folder");
+ };
+ if entity.deleted {
+ st.db.delete_project_memory(&path)?;
+ } else if let Some(memory) = entity.payload.get("memory") {
+ if let Some(entries) = memory.get("entries") {
+ st.db.set_project_memory_entries(&path, entries)?;
+ } else {
+ st.db.set_project_memory(
+ &path,
+ memory
+ .get("content")
+ .and_then(Value::as_str)
+ .unwrap_or_default(),
+ )?;
+ }
+ }
+ return Ok(());
+ }
+ if entity.domain == domains::DOMAIN_AUTOMATION {
+ let mut payload = entity.payload.clone();
+ if let Some(path) = mapped_project_path(config, &payload)? {
+ if let Some(object) = payload.as_object_mut() {
+ object.remove("workspaceProjectLogicalId");
+ object.insert("workspacePath".into(), Value::String(path));
+ }
+ }
+ let id = payload
+ .get("id")
+ .and_then(Value::as_str)
+ .or_else(|| entity.entity_id.strip_prefix("automation:"))
+ .unwrap_or(&entity.entity_id);
+ if entity.deleted {
+ let _ = crate::scheduled::delete_task(&st.db, id)?;
+ } else if crate::scheduled::get_task(&st.db, id)?.is_some() {
+ let _ = crate::scheduled::update_task(&st.db, &payload)?;
+ } else {
+ // Execution ownership is device-local. A new device must not
+ // start a scheduled task merely because its definition was
+ // approved for import.
+ if let Some(object) = payload.as_object_mut() {
+ object.insert("enabled".into(), Value::Bool(false));
+ }
+ let _ = crate::scheduled::import_tasks(&st.db, std::slice::from_ref(&payload))?;
+ }
+ return Ok(());
+ }
+ if entity.domain == domains::DOMAIN_INSTRUCTIONS {
+ if let Some(scope) = entity.payload.get("scope").and_then(Value::as_str) {
+ if scope == "global" {
+ let path = domains::global_instruction_path_for_sync()?;
+ if entity.deleted {
+ domains::remove_instruction_file(&path)?;
+ } else {
+ let content = entity
+ .payload
+ .get("content")
+ .and_then(Value::as_str)
+ .ok_or_else(|| {
+ anyhow!("CONFIG_SYNC_INVALID: global instructions are missing")
+ })?;
+ domains::write_instruction_file(&path, content)?;
+ }
+ return Ok(());
+ }
+ if scope == "project" {
+ let Some(path) = mapped_project_path(config, &entity.payload)? else {
+ bail!("CONFIG_SYNC_MAPPING_REQUIRED: project instructions need a local folder");
+ };
+ let instruction_path = Path::new(&path).join("AGENTS.md");
+ if entity.deleted {
+ domains::remove_instruction_file(&instruction_path)?;
+ } else {
+ let content = entity
+ .payload
+ .get("content")
+ .and_then(Value::as_str)
+ .ok_or_else(|| {
+ anyhow!("CONFIG_SYNC_INVALID: project instructions are missing")
+ })?;
+ domains::write_instruction_file(&instruction_path, content)?;
+ }
+ return Ok(());
+ }
+ bail!("CONFIG_SYNC_INVALID: unsupported instruction scope");
+ }
+ let paths = mapped_project_paths(config, &entity.payload)?;
+ let group_id = if let Some(paths) = paths {
+ if let Some(group) = st.db.project_group_for_path(&paths[0])? {
+ group.id
+ } else {
+ let name = entity
+ .payload
+ .get("projectGroupName")
+ .and_then(Value::as_str)
+ .unwrap_or("Imported project")
+ .to_string();
+ st.db.create_project_group(&name, &paths)?.id
+ }
+ } else {
+ bail!("CONFIG_SYNC_MAPPING_REQUIRED: project instructions need a group")
+ };
+ st.db.set_project_group_instructions(
+ &group_id,
+ if entity.deleted {
+ ""
+ } else {
+ entity
+ .payload
+ .get("content")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ },
+ )?;
+ return Ok(());
+ }
+ if entity.domain == domains::DOMAIN_PROJECTS {
+ let Some(paths) = mapped_project_paths(config, &entity.payload)? else {
+ bail!("CONFIG_SYNC_MAPPING_REQUIRED: project folder is not mapped");
+ };
+ let logical_id = entity
+ .payload
+ .get("logicalId")
+ .and_then(Value::as_str)
+ .unwrap_or_default();
+ let is_group = logical_id.starts_with("project-group:")
+ || entity
+ .payload
+ .get("roots")
+ .and_then(Value::as_array)
+ .is_some_and(|roots| roots.len() > 1)
+ || paths.len() > 1;
+ if entity.deleted {
+ if is_group {
+ if let Some(group) = st.db.project_group_for_path(&paths[0])? {
+ if !group.legacy {
+ st.db.delete_project_group_record(&group.id)?;
+ }
+ }
+ }
+ } else if is_group {
+ let name = entity
+ .payload
+ .get("name")
+ .and_then(Value::as_str)
+ .unwrap_or("Imported project")
+ .to_string();
+ match st.db.project_group_for_path(&paths[0])? {
+ Some(group) if !group.legacy => {
+ st.db.update_project_group(&group.id, &name, &paths)?;
+ }
+ _ => {
+ st.db.create_project_group(&name, &paths)?;
+ }
+ }
+ } else {
+ st.db.ensure_project(&paths[0], false)?;
+ }
+ return Ok(());
+ }
+ if entity.domain == domains::DOMAIN_PLUGINS {
+ let plugin_id = entity
+ .payload
+ .get("id")
+ .and_then(Value::as_str)
+ .or_else(|| entity.entity_id.strip_prefix("plugin:"))
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: plugin entity id is invalid"))?;
+ if entity.deleted {
+ config.plugin_intents.remove(plugin_id);
+ } else {
+ // Installation and activation remain explicit user actions. The
+ // portable intent is retained locally, but no plugin bytes or
+ // permissions are pulled from WebDAV.
+ config
+ .plugin_intents
+ .insert(plugin_id.to_string(), entity.payload.clone());
+ }
+ return Ok(());
+ }
+ bail!(
+ "CONFIG_SYNC_UNSUPPORTED: unsupported portable domain {}",
+ entity.domain
+ )
+}
+
+fn ready_entity(config: &StoredConfig, bundle: &PendingBundle, entity: &PortableEntity) -> bool {
+ if !selection(config).is_selected(&entity.domain) {
+ return false;
+ }
+ if config.dismissed.get(&approval_key(entity)) == Some(&entity.digest) {
+ return false;
+ }
+ bundle
+ .approvals
+ .iter()
+ .find(|item| {
+ item.entity.entity_id == entity.entity_id && item.entity.domain == entity.domain
+ })
+ .is_none_or(|item| item.approved)
+}
+
+fn deferred_apply_reason(error: &anyhow::Error) -> Option<&'static str> {
+ let message = error.to_string();
+ if message.starts_with("CONFIG_SYNC_DEPENDENCY") {
+ Some("dependency")
+ } else if message.starts_with("CONFIG_SYNC_MAPPING_REQUIRED") {
+ Some("mapping")
+ } else {
+ None
+ }
+}
+
+fn retain_deferred_entity(bundle: &mut PendingBundle, entity: &PortableEntity, reason: &str) {
+ if let Some(item) = bundle.approvals.iter_mut().find(|item| {
+ item.entity.domain == entity.domain && item.entity.entity_id == entity.entity_id
+ }) {
+ item.approved = false;
+ item.reason = reason.to_string();
+ return;
+ }
+ bundle.approvals.push(PendingApproval {
+ approval_id: Uuid::new_v4().to_string(),
+ entity: entity.clone(),
+ reason: reason.to_string(),
+ approved: false,
+ });
+}
+
+fn apply_priority(domain: &str) -> u8 {
+ match domain {
+ // Project roots and providers are prerequisites for scoped capability
+ // files and application-level model bindings.
+ domains::DOMAIN_PROJECTS => 10,
+ domains::DOMAIN_PROVIDERS => 20,
+ domains::DOMAIN_INSTRUCTIONS => 30,
+ domains::DOMAIN_MCP
+ | domains::DOMAIN_SKILLS
+ | domains::DOMAIN_SUBAGENTS
+ | domains::DOMAIN_AUTOMATION
+ | domains::DOMAIN_MEMORY => 40,
+ domains::DOMAIN_PLUGINS => 50,
+ domains::DOMAIN_APPLICATION => 90,
+ _ => 60,
+ }
+}
+
+fn acknowledged_manifest(
+ base: Option<&RevisionManifest>,
+ merged: &RevisionManifest,
+ applied: &BTreeSet<(String, String)>,
+) -> RevisionManifest {
+ let mut values = manifest_map(base);
+ for entity in &merged.entities {
+ let candidate_key = entity_key(entity);
+ if !applied.contains(&candidate_key) {
+ continue;
+ }
+ let mut acknowledged = entity.clone();
+ if let Some(base_id) = conflict_base_id(&acknowledged.entity_id) {
+ acknowledged.entity_id = base_id.to_string();
+ domains::refresh_digest(&mut acknowledged);
+ }
+ let acknowledged_key = entity_key(&acknowledged);
+ values.insert(acknowledged_key, acknowledged);
+ }
+ let mut entities: Vec<_> = values.into_values().collect();
+ entities.sort_by(|left, right| {
+ left.domain
+ .cmp(&right.domain)
+ .then(left.entity_id.cmp(&right.entity_id))
+ });
+ RevisionManifest {
+ format: REVISION_FORMAT.into(),
+ version: 1,
+ revision_id: merged.revision_id.clone(),
+ parents: merged.parents.clone(),
+ created_at: merged.created_at.clone(),
+ resource_ids: merged.resource_ids.clone(),
+ entities,
+ }
+}
+
+fn apply_bundle_locked(
+ st: &mut AppState,
+ config: &mut StoredConfig,
+ key: &VaultKey,
+ base: Option<&RevisionManifest>,
+ local_before: &RevisionManifest,
+ bundle: &PendingBundle,
+) -> Result<()> {
+ // Conflict candidates carry a temporary `:local`/`:remote` entity ID.
+ // Compare them by their original logical ID so an edit made after the
+ // snapshot capture cannot be overwritten merely because the candidate
+ // ID is new.
+ let local_map = logical_manifest_map(Some(local_before));
+ let mut applied = BTreeSet::new();
+ let mut staged = bundle.clone();
+ let mut entities = bundle.manifest.entities.iter().collect::<Vec<_>>();
+ entities.sort_by(|left, right| {
+ apply_priority(&left.domain)
+ .cmp(&apply_priority(&right.domain))
+ .then(left.domain.cmp(&right.domain))
+ .then(left.entity_id.cmp(&right.entity_id))
+ });
+ for entity in entities {
+ let ready = ready_entity(config, &staged, entity);
+ if !ready {
+ continue;
+ }
+ let key_id = entity_key(entity);
+ let logical_key = logical_entity_key(entity);
+ let current = domains::capture(
+ st,
+ key,
+ &selection(config),
+ config.include_secrets,
+ &config.plugin_intents,
+ &identity_overrides(config),
+ )?;
+ let current_map = logical_manifest_map(Some(&current.manifest));
+ if let Some(before) = local_map.get(&logical_key) {
+ if entity.deleted && before.deleted && !current_map.contains_key(&logical_key) {
+ // The local snapshot already represented this tombstone and
+ // the live record is still absent. Acknowledge the deletion
+ // without treating the missing record as a concurrent edit.
+ applied.insert(key_id);
+ continue;
+ }
+ if current_map
+ .get(&logical_key)
+ .map(|value| value.digest.as_str())
+ != Some(before.digest.as_str())
+ {
+ continue;
+ }
+ if entity.digest == before.digest {
+ // The candidate already matches the coherent local snapshot.
+ // Treat it as acknowledged without re-applying it; this is
+ // important for path-bound entities whose local overlay is
+ // valid but cannot be reconstructed from a portable payload.
+ applied.insert(key_id);
+ continue;
+ }
+ } else if current_map.contains_key(&logical_key) {
+ continue;
+ }
+ match apply_entity(st, config, &staged, entity) {
+ Ok(()) => {
+ applied.insert(key_id);
+ }
+ Err(error) => {
+ if let Some(reason) = deferred_apply_reason(&error) {
+ retain_deferred_entity(&mut staged, entity, reason);
+ } else {
+ return Err(error);
+ }
+ }
+ }
+ }
+ let next_base = acknowledged_manifest(base, &bundle.manifest, &applied);
+ store_base(st, key, &next_base)?;
+ let remaining: Vec<_> = staged
+ .approvals
+ .iter()
+ .filter(|item| !item.approved)
+ .cloned()
+ .collect();
+ if remaining.is_empty() {
+ clear_pending(st)?;
+ } else {
+ let mut next = staged;
+ next.approvals = remaining;
+ next.journal_state = "staged".into();
+ store_pending(st, key, &next)?;
+ }
+ let after = domains::capture(
+ st,
+ key,
+ &selection(config),
+ config.include_secrets,
+ &config.plugin_intents,
+ &identity_overrides(config),
+ )?;
+ config.last_local_digest = Some(domains::snapshot_digest(&after));
+ config.local_change_seen_at = None;
+ config.last_success_at = Some(Utc::now().to_rfc3339());
+ config.last_revision_id = Some(bundle.remote_revision_id.clone());
+ clear_error(config);
+ save_config(st, config)?;
+ Ok(())
+}
+
+pub(crate) async fn apply_bundle(
+ state: &Arc<Mutex<AppState>>,
+ config: &mut StoredConfig,
+ key: &VaultKey,
+ base: Option<&RevisionManifest>,
+ local_before: &RevisionManifest,
+ bundle: &PendingBundle,
+) -> Result<()> {
+ let mut st = state.lock().await;
+ apply_bundle_locked(&mut st, config, key, base, local_before, bundle)
+}
+
+fn empty_manifest() -> RevisionManifest {
+ RevisionManifest {
+ format: REVISION_FORMAT.into(),
+ version: 1,
+ revision_id: String::new(),
+ parents: Vec::new(),
+ created_at: String::new(),
+ entities: Vec::new(),
+ resource_ids: Vec::new(),
+ }
+}
+
+pub(crate) fn recover_import_journal(
+ st: &mut AppState,
+ config: &mut StoredConfig,
+ key: &VaultKey,
+ bundle: &PendingBundle,
+) -> Result<()> {
+ let base = load_base(st, key)?;
+ let local_before = bundle
+ .local_before
+ .clone()
+ .or_else(|| base.clone())
+ .unwrap_or_else(empty_manifest);
+ apply_bundle_locked(st, config, key, base.as_ref(), &local_before, bundle)
+}
diff --git a/crates/host-core/src/config_sync/coordinator.rs b/crates/host-core/src/config_sync/coordinator.rs
new file mode 100644
index 000000000..ef0ffc755
--- /dev/null
+++ b/crates/host-core/src/config_sync/coordinator.rs
@@ -0,0 +1,304 @@
+use super::*;
+
+struct SyncProgress(Arc<AtomicBool>);
+
+impl SyncProgress {
+ fn start(flag: Arc<AtomicBool>) -> Self {
+ flag.store(true, Ordering::Relaxed);
+ Self(flag)
+ }
+}
+
+impl Drop for SyncProgress {
+ fn drop(&mut self) {
+ self.0.store(false, Ordering::Relaxed);
+ }
+}
+
+pub(super) async fn sync_once(
+ state: &Arc<Mutex<AppState>>,
+ tx: &mpsc::UnboundedSender<String>,
+) -> Result<()> {
+ let lock = {
+ let st = state.lock().await;
+ st.config_sync_lock.clone()
+ };
+ let _guard = lock.lock().await;
+ let progress = {
+ let st = state.lock().await;
+ SyncProgress::start(st.config_sync_in_progress.clone())
+ };
+ let _progress = progress;
+ {
+ let mut st = state.lock().await;
+ send_state_notification(tx, &mut st);
+ }
+ for _attempt in 0..MAX_RETRIES {
+ let (config, key, base, local, local_digest) = {
+ let mut st = state.lock().await;
+ let mut config = load_config(&st)?
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: sync is not configured"))?;
+ if config.paused {
+ return Ok(());
+ }
+ let key = local_vault_key(&st, &config)?
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_LOCKED: backup vault is locked"))?;
+ let pending_waiting_for_approval = if let Some(pending) = load_pending(&st, &key)? {
+ if pending.journal_state == "applying" {
+ recover_import_journal(&mut st, &mut config, &key, &pending)?;
+ }
+ load_pending(&st, &key)?.is_some_and(|pending| !pending.approvals.is_empty())
+ } else {
+ false
+ };
+ let base = load_base(&st, &key)?;
+ let mut local = domains::capture(
+ &mut st,
+ &key,
+ &selection(&config),
+ config.include_secrets,
+ &config.plugin_intents,
+ &identity_overrides(&config),
+ )?;
+ let local_digest = domains::snapshot_digest(&local);
+ if pending_waiting_for_approval
+ && config.last_local_digest.as_deref() == Some(local_digest.as_str())
+ {
+ // Keep an unresolved remote import staged without publishing
+ // a new identical revision on every scheduler tick. A local
+ // edit changes this digest and is still allowed to reconcile
+ // with unrelated remote edits.
+ return Ok(());
+ }
+ merge::snapshot_with_tombstones(base.as_ref(), &mut local, &selection(&config));
+ config.last_run_at = Some(Utc::now().to_rfc3339());
+ save_config(&st, &config)?;
+ (config, key, base, local, local_digest)
+ };
+ let transport_password = {
+ let st = state.lock().await;
+ webdav_password(&st, &config)?
+ };
+ let transport = transport_with_password(&config, transport_password)?;
+ ensure_remote_collections(&transport, &config).await?;
+ let remote_head = read_remote_head(&transport, &config, &key).await?;
+ let (remote, remote_resources) = if let Some((head, _)) = remote_head.as_ref() {
+ let value = read_remote_revision(&transport, &config, &key, &head.revision_id).await?;
+ (Some(value.0), value.1)
+ } else {
+ (None, BTreeMap::new())
+ };
+ let merged = merge::three_way(base.as_ref(), &local.manifest, remote.as_ref())?;
+ if let (Some((head, _)), Some(remote)) = (remote_head.as_ref(), remote.as_ref()) {
+ // Skip publication when the acknowledged base, current local
+ // snapshot, and remote head agree for every subscribed domain.
+ // A remote-only change in an opted-out category is already
+ // represented by the remote head. A fresh device with selected
+ // remote content still has to stage it for approval and
+ // activation, even though the merge result equals the remote
+ // entities.
+ let no_selected_change =
+ selected_manifests_equal(base.as_ref(), Some(remote), &selection(&config))
+ && selected_manifests_equal(
+ Some(&local.manifest),
+ Some(remote),
+ &selection(&config),
+ );
+ if no_selected_change && remote.entities == merged.entities {
+ let mut st = state.lock().await;
+ let mut next_config = config.clone();
+ next_config.last_success_at = Some(Utc::now().to_rfc3339());
+ next_config.last_revision_id = Some(head.revision_id.clone());
+ next_config.last_local_digest = Some(local_digest);
+ next_config.local_change_seen_at = None;
+ clear_error(&mut next_config);
+ save_config(&st, &next_config)?;
+ send_state_notification(tx, &mut st);
+ return Ok(());
+ }
+ }
+ let mut resources = local.resources.clone();
+ resources.extend(remote_resources);
+ let revision_id = Uuid::new_v4().to_string();
+ let candidate = LocalSnapshot {
+ manifest: RevisionManifest {
+ format: REVISION_FORMAT.into(),
+ version: 1,
+ revision_id: revision_id.clone(),
+ parents: remote_head
+ .as_ref()
+ .map(|(head, _)| vec![head.revision_id.clone()])
+ .unwrap_or_default(),
+ created_at: Utc::now().to_rfc3339(),
+ entities: merged.entities.clone(),
+ resource_ids: resources.keys().cloned().collect(),
+ },
+ resources,
+ };
+ upload_snapshot(&transport, &config, &key, &candidate).await?;
+ let head = RemoteHead {
+ format: FORMAT.into(),
+ version: 1,
+ revision_id: candidate.manifest.revision_id.clone(),
+ };
+ let published = publish_head(
+ &transport,
+ &config,
+ &key,
+ &head,
+ remote_head.as_ref().map(|(_, etag)| etag.as_str()),
+ )
+ .await?;
+ if !published {
+ let jitter_ms = u64::from(Uuid::new_v4().as_bytes()[0] % 31);
+ tokio::time::sleep(std::time::Duration::from_millis(
+ 50 * (_attempt as u64 + 1) + jitter_ms,
+ ))
+ .await;
+ continue;
+ }
+ let pending = build_pending(
+ &config,
+ base.as_ref(),
+ &local.manifest,
+ remote.as_ref(),
+ &merged,
+ &candidate.manifest.revision_id,
+ candidate.resources.clone(),
+ );
+ {
+ let st = state.lock().await;
+ let mut journal = pending.clone();
+ journal.journal_state = "applying".into();
+ store_pending(&st, &key, &journal)?;
+ }
+ let mut next_config = config.clone();
+ let apply_bundle_state = PendingBundle {
+ manifest: candidate.manifest,
+ local_before: Some(local.manifest.clone()),
+ resources: candidate.resources,
+ approvals: pending.approvals,
+ conflicts: pending.conflicts,
+ journal_state: "applying".into(),
+ remote_revision_id: head.revision_id,
+ };
+ apply_bundle(
+ state,
+ &mut next_config,
+ &key,
+ base.as_ref(),
+ &local.manifest,
+ &apply_bundle_state,
+ )
+ .await?;
+ if let Err(error) = cleanup_history(state, &transport, &config, &key).await {
+ tracing::warn!(error = %error, "config sync history cleanup failed after sync");
+ }
+ let mut st = state.lock().await;
+ send_state_notification(tx, &mut st);
+ return Ok(());
+ }
+ bail!("CONFIG_SYNC_CONFLICT: remote head changed while publishing")
+}
+
+pub(crate) async fn sync_now(
+ state: Arc<Mutex<AppState>>,
+ tx: mpsc::UnboundedSender<String>,
+) -> Result<Value> {
+ if let Err(error) = sync_once(&state, &tx).await {
+ let mut st = state.lock().await;
+ if let Some(mut config) = load_config(&st)? {
+ mark_error(&mut config, &error);
+ config.retry_count = config.retry_count.saturating_add(1).min(8);
+ let backoff = 2_i64.saturating_pow(config.retry_count.min(8)).min(300);
+ let jitter = i64::from(Uuid::new_v4().as_bytes()[0] % 7);
+ config.next_retry_at =
+ Some((Utc::now() + chrono::Duration::seconds(backoff + jitter)).to_rfc3339());
+ save_config(&st, &config)?;
+ }
+ send_state_notification(&tx, &mut st);
+ return Err(error);
+ }
+ get_state(state).await
+}
+
+/// Run the configured foreground/background poll. The host process owns this
+/// task so the renderer and Electron main never become a second scheduler.
+pub(crate) async fn sync_if_enabled(
+ state: Arc<Mutex<AppState>>,
+ tx: mpsc::UnboundedSender<String>,
+) -> Result<()> {
+ const LOCAL_DEBOUNCE_SECONDS: i64 = 30;
+ const REMOTE_POLL_SECONDS: i64 = 300;
+ let should_sync = {
+ let mut st = state.lock().await;
+ let Some(mut config) = load_config(&st)? else {
+ return Ok(());
+ };
+ if !config.enabled
+ || !config.automatic_sync
+ || config.paused
+ || matches!(
+ config.last_error_code.as_deref(),
+ Some("LOCKED" | "AUTH_REQUIRED" | "UNSUPPORTED_SERVER")
+ )
+ {
+ return Ok(());
+ }
+ if retry_deadline(&config).is_some_and(|deadline| deadline > Utc::now()) {
+ return Ok(());
+ }
+ let key = local_vault_key(&st, &config)?;
+ let Some(key) = key else {
+ return Ok(());
+ };
+ let snapshot = domains::capture(
+ &mut st,
+ &key,
+ &selection(&config),
+ config.include_secrets,
+ &config.plugin_intents,
+ &identity_overrides(&config),
+ )?;
+ let digest = domains::snapshot_digest(&snapshot);
+ let now = Utc::now();
+ let local_changed = config
+ .last_local_digest
+ .as_deref()
+ .is_some_and(|expected| expected != digest);
+ if local_changed {
+ let seen_at = config
+ .local_change_seen_at
+ .as_deref()
+ .and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok())
+ .map(|value| value.with_timezone(&Utc));
+ if seen_at.is_none_or(|seen| {
+ now.signed_duration_since(seen).num_seconds() < LOCAL_DEBOUNCE_SECONDS
+ }) {
+ if config.local_change_seen_at.is_none() {
+ config.local_change_seen_at = Some(now.to_rfc3339());
+ save_config(&st, &config)?;
+ }
+ return Ok(());
+ }
+ true
+ } else {
+ if config.local_change_seen_at.take().is_some() {
+ save_config(&st, &config)?;
+ }
+ config
+ .last_success_at
+ .as_deref()
+ .and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok())
+ .map(|value| value.with_timezone(&Utc))
+ .is_none_or(|last| {
+ now.signed_duration_since(last).num_seconds() >= REMOTE_POLL_SECONDS
+ })
+ }
+ };
+ if should_sync {
+ sync_now(state, tx).await.map(|_| ())
+ } else {
+ Ok(())
+ }
+}
diff --git a/crates/host-core/src/config_sync/crypto.rs b/crates/host-core/src/config_sync/crypto.rs
new file mode 100644
index 000000000..9c2bbed6d
--- /dev/null
+++ b/crates/host-core/src/config_sync/crypto.rs
@@ -0,0 +1,357 @@
+use aes_gcm::aead::{Aead, KeyInit};
+use aes_gcm::{Aes256Gcm, Nonce};
+use anyhow::{anyhow, bail, Context, Result};
+use argon2::{Algorithm, Argon2, Params, Version};
+use base64::{engine::general_purpose::STANDARD as B64, Engine as _};
+use rand::{rng, RngExt};
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+
+const KEY_BYTES: usize = 32;
+const NONCE_BYTES: usize = 12;
+const FORMAT_VERSION: u32 = 2;
+const MIN_MEMORY_KIB: u32 = 19_456;
+const MAX_MEMORY_KIB: u32 = 1_048_576;
+const MIN_ITERATIONS: u32 = 2;
+const MAX_ITERATIONS: u32 = 12;
+const MIN_PARALLELISM: u32 = 1;
+const MAX_PARALLELISM: u32 = 8;
+
+/// Parameters are part of the authenticated vault header, but are bounded
+/// before Argon2 is invoked so an attacker-controlled remote header cannot
+/// turn unlocking into an unbounded memory or CPU allocation.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct KdfParameters {
+ pub algorithm: String,
+ pub memory_kib: u32,
+ pub iterations: u32,
+ pub parallelism: u32,
+ pub salt: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct VaultHeader {
+ pub format: String,
+ pub version: u32,
+ pub vault_id: String,
+ pub cipher: String,
+ pub kdf: KdfParameters,
+ pub wrap_nonce: String,
+ pub wrapped_key: String,
+}
+
+#[derive(Debug, Clone)]
+pub struct VaultKey(pub [u8; KEY_BYTES]);
+
+impl VaultKey {
+ pub fn as_bytes(&self) -> &[u8; KEY_BYTES] {
+ &self.0
+ }
+}
+
+fn default_kdf() -> KdfParameters {
+ KdfParameters {
+ algorithm: "argon2id".to_string(),
+ memory_kib: 64 * 1024,
+ iterations: 3,
+ parallelism: 1,
+ salt: random_b64(16),
+ }
+}
+
+fn random_b64(bytes: usize) -> String {
+ let mut value = vec![0u8; bytes];
+ rng().fill(value.as_mut_slice());
+ B64.encode(value)
+}
+
+fn checked_kdf(kdf: &KdfParameters) -> Result<Params> {
+ if kdf.algorithm != "argon2id" {
+ bail!("CONFIG_SYNC_UNSUPPORTED: vault KDF is not Argon2id");
+ }
+ if !(MIN_MEMORY_KIB..=MAX_MEMORY_KIB).contains(&kdf.memory_kib)
+ || !(MIN_ITERATIONS..=MAX_ITERATIONS).contains(&kdf.iterations)
+ || !(MIN_PARALLELISM..=MAX_PARALLELISM).contains(&kdf.parallelism)
+ {
+ bail!("CONFIG_SYNC_INVALID: vault KDF parameters are outside the supported bounds");
+ }
+ let salt = B64.decode(&kdf.salt).context("decode vault KDF salt")?;
+ if !(16..=64).contains(&salt.len()) {
+ bail!("CONFIG_SYNC_INVALID: vault KDF salt has an invalid length");
+ }
+ Params::new(
+ kdf.memory_kib,
+ kdf.iterations,
+ kdf.parallelism,
+ Some(KEY_BYTES),
+ )
+ .map_err(|error| anyhow!("invalid vault KDF parameters: {error}"))
+}
+
+fn derive_wrapping_key(password: &str, kdf: &KdfParameters) -> Result<[u8; KEY_BYTES]> {
+ if password.is_empty() {
+ bail!("CONFIG_SYNC_INVALID: backup password is required");
+ }
+ let params = checked_kdf(kdf)?;
+ let salt = B64.decode(&kdf.salt).context("decode vault KDF salt")?;
+ let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
+ let mut key = [0u8; KEY_BYTES];
+ argon
+ .hash_password_into(password.as_bytes(), &salt, &mut key)
+ .map_err(|error| anyhow!("derive vault wrapping key: {error}"))?;
+ Ok(key)
+}
+
+fn aad(purpose: &str, vault_id: &str) -> Vec<u8> {
+ format!("pi-desktop/config-sync/v{FORMAT_VERSION}/{purpose}/{vault_id}").into_bytes()
+}
+
+fn domain_key(key: &[u8; KEY_BYTES], purpose: &str, vault_id: &str) -> [u8; KEY_BYTES] {
+ let mut hasher = Sha256::new();
+ hasher.update(b"pi-desktop/config-sync/key/v2/");
+ hasher.update((purpose.len() as u64).to_be_bytes());
+ hasher.update(purpose.as_bytes());
+ hasher.update((vault_id.len() as u64).to_be_bytes());
+ hasher.update(vault_id.as_bytes());
+ hasher.update(key);
+ hasher.finalize().into()
+}
+
+fn validate_vault_id(vault_id: &str) -> Result<()> {
+ if vault_id.is_empty()
+ || vault_id.len() > 128
+ || vault_id.contains('/')
+ || vault_id.contains('\\')
+ || vault_id.contains("..")
+ || !vault_id
+ .chars()
+ .all(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_'))
+ {
+ bail!("CONFIG_SYNC_INVALID: vault id is unsafe");
+ }
+ Ok(())
+}
+
+fn encrypt_with_key(
+ key: &[u8; KEY_BYTES],
+ purpose: &str,
+ vault_id: &str,
+ plaintext: &[u8],
+) -> Result<Vec<u8>> {
+ let object_key = domain_key(key, purpose, vault_id);
+ let cipher = Aes256Gcm::new_from_slice(&object_key).map_err(|_| anyhow!("invalid AES key"))?;
+ let mut nonce_bytes = [0u8; NONCE_BYTES];
+ rng().fill(&mut nonce_bytes);
+ let nonce =
+ Nonce::try_from(nonce_bytes.as_slice()).map_err(|_| anyhow!("invalid AES-GCM nonce"))?;
+ let ciphertext = cipher
+ .encrypt(
+ &nonce,
+ aes_gcm::aead::Payload {
+ msg: plaintext,
+ aad: &aad(purpose, vault_id),
+ },
+ )
+ .map_err(|_| anyhow!("CONFIG_SYNC_CRYPTO: encryption failed"))?;
+ let mut result = Vec::with_capacity(NONCE_BYTES + ciphertext.len());
+ result.extend_from_slice(&nonce_bytes);
+ result.extend_from_slice(&ciphertext);
+ Ok(result)
+}
+
+fn decrypt_with_key(
+ key: &[u8; KEY_BYTES],
+ purpose: &str,
+ vault_id: &str,
+ ciphertext: &[u8],
+) -> Result<Vec<u8>> {
+ if ciphertext.len() <= NONCE_BYTES {
+ bail!("CONFIG_SYNC_CRYPTO: encrypted object is truncated");
+ }
+ let object_key = domain_key(key, purpose, vault_id);
+ let cipher = Aes256Gcm::new_from_slice(&object_key).map_err(|_| anyhow!("invalid AES key"))?;
+ let nonce = Nonce::try_from(&ciphertext[..NONCE_BYTES])
+ .map_err(|_| anyhow!("invalid AES-GCM nonce"))?;
+ cipher
+ .decrypt(
+ &nonce,
+ aes_gcm::aead::Payload {
+ msg: &ciphertext[NONCE_BYTES..],
+ aad: &aad(purpose, vault_id),
+ },
+ )
+ .map_err(|_| anyhow!("CONFIG_SYNC_CRYPTO: authentication failed"))
+}
+
+pub fn create_vault(password: &str, vault_id: &str) -> Result<(VaultHeader, VaultKey)> {
+ validate_vault_id(vault_id)?;
+ let kdf = default_kdf();
+ let wrapping_key = derive_wrapping_key(password, &kdf)?;
+ let mut raw_key = [0u8; KEY_BYTES];
+ rng().fill(&mut raw_key);
+ let wrapped = encrypt_with_key(&wrapping_key, "vault-key", vault_id, &raw_key)?;
+ let nonce = B64.encode(&wrapped[..NONCE_BYTES]);
+ let ciphertext = B64.encode(&wrapped[NONCE_BYTES..]);
+ Ok((
+ VaultHeader {
+ format: "pi-desktop-config-vault".to_string(),
+ version: FORMAT_VERSION,
+ vault_id: vault_id.to_string(),
+ cipher: "AES-256-GCM".to_string(),
+ kdf,
+ wrap_nonce: nonce,
+ wrapped_key: ciphertext,
+ },
+ VaultKey(raw_key),
+ ))
+}
+
+pub fn rewrap_vault(
+ header: &VaultHeader,
+ key: &VaultKey,
+ new_password: &str,
+) -> Result<VaultHeader> {
+ if header.format != "pi-desktop-config-vault"
+ || header.version != FORMAT_VERSION
+ || header.cipher != "AES-256-GCM"
+ {
+ bail!("CONFIG_SYNC_UNSUPPORTED: unsupported vault format");
+ }
+ validate_vault_id(&header.vault_id)?;
+ let kdf = default_kdf();
+ let wrapping_key = derive_wrapping_key(new_password, &kdf)?;
+ let wrapped = encrypt_with_key(&wrapping_key, "vault-key", &header.vault_id, &key.0)?;
+ Ok(VaultHeader {
+ format: header.format.clone(),
+ version: header.version,
+ vault_id: header.vault_id.clone(),
+ cipher: header.cipher.clone(),
+ kdf,
+ wrap_nonce: B64.encode(&wrapped[..NONCE_BYTES]),
+ wrapped_key: B64.encode(&wrapped[NONCE_BYTES..]),
+ })
+}
+
+pub fn unlock_vault(header: &VaultHeader, password: &str) -> Result<VaultKey> {
+ if header.format != "pi-desktop-config-vault"
+ || header.version != FORMAT_VERSION
+ || header.cipher != "AES-256-GCM"
+ {
+ bail!("CONFIG_SYNC_UNSUPPORTED: unsupported vault format");
+ }
+ validate_vault_id(&header.vault_id)?;
+ let wrapping_key = derive_wrapping_key(password, &header.kdf)?;
+ let nonce = B64
+ .decode(&header.wrap_nonce)
+ .context("decode vault wrap nonce")?;
+ let ciphertext = B64
+ .decode(&header.wrapped_key)
+ .context("decode wrapped vault key")?;
+ if nonce.len() != NONCE_BYTES || ciphertext.is_empty() {
+ bail!("CONFIG_SYNC_CRYPTO: wrapped vault key is malformed");
+ }
+ let mut encrypted = Vec::with_capacity(nonce.len() + ciphertext.len());
+ encrypted.extend_from_slice(&nonce);
+ encrypted.extend_from_slice(&ciphertext);
+ let plaintext = decrypt_with_key(&wrapping_key, "vault-key", &header.vault_id, &encrypted)
+ .context("unlock vault")?;
+ let raw: [u8; KEY_BYTES] = plaintext
+ .try_into()
+ .map_err(|_| anyhow!("CONFIG_SYNC_CRYPTO: vault key has an invalid length"))?;
+ Ok(VaultKey(raw))
+}
+
+pub fn encrypt_object(
+ key: &VaultKey,
+ purpose: &str,
+ vault_id: &str,
+ plaintext: &[u8],
+) -> Result<Vec<u8>> {
+ encrypt_with_key(key.as_bytes(), purpose, vault_id, plaintext)
+}
+
+pub fn decrypt_object(
+ key: &VaultKey,
+ purpose: &str,
+ vault_id: &str,
+ ciphertext: &[u8],
+) -> Result<Vec<u8>> {
+ decrypt_with_key(key.as_bytes(), purpose, vault_id, ciphertext)
+}
+
+pub fn object_id(key: &VaultKey, bytes: &[u8]) -> String {
+ use sha2::{Digest, Sha256};
+ let mut hasher = Sha256::new();
+ hasher.update(b"pi-desktop/config-sync/resource/v1/");
+ hasher.update(key.as_bytes());
+ hasher.update(bytes);
+ hex::encode(hasher.finalize())
+}
+
+pub fn vault_key_b64(key: &VaultKey) -> String {
+ B64.encode(key.as_bytes())
+}
+
+pub fn vault_key_from_b64(value: &str) -> Result<VaultKey> {
+ let raw = B64.decode(value).context("decode local vault key")?;
+ let key = raw
+ .try_into()
+ .map_err(|_| anyhow!("local vault key has an invalid length"))?;
+ Ok(VaultKey(key))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn vault_round_trip_rejects_wrong_password_and_tampering() {
+ let (header, key) =
+ create_vault("correct horse battery staple", "vault-a").expect("create vault");
+ let unlocked = unlock_vault(&header, "correct horse battery staple").expect("unlock");
+ assert_eq!(unlocked.as_bytes(), key.as_bytes());
+ assert!(unlock_vault(&header, "wrong password").is_err());
+
+ let mut ciphertext =
+ encrypt_object(&key, "test", "vault-a", b"portable settings").expect("encrypt");
+ assert_eq!(
+ decrypt_object(&key, "test", "vault-a", &ciphertext).expect("decrypt"),
+ b"portable settings"
+ );
+ let last = ciphertext.len() - 1;
+ ciphertext[last] ^= 1;
+ assert!(decrypt_object(&key, "test", "vault-a", &ciphertext).is_err());
+ }
+
+ #[test]
+ fn untrusted_kdf_parameters_are_bounded() {
+ let mut kdf = default_kdf();
+ kdf.memory_kib = MAX_MEMORY_KIB + 1;
+ assert!(checked_kdf(&kdf).is_err());
+ kdf.memory_kib = MIN_MEMORY_KIB;
+ kdf.iterations = MAX_ITERATIONS + 1;
+ assert!(checked_kdf(&kdf).is_err());
+ }
+
+ #[test]
+ fn rewrap_preserves_the_vault_key_and_changes_the_password() {
+ let (header, key) = create_vault("old-password", "vault-rewrap").expect("create");
+ let rewrapped = rewrap_vault(&header, &key, "new-password").expect("rewrap");
+ assert_eq!(
+ unlock_vault(&rewrapped, "new-password").unwrap().as_bytes(),
+ key.as_bytes()
+ );
+ assert!(unlock_vault(&rewrapped, "old-password").is_err());
+ }
+
+ #[test]
+ fn vault_ids_cannot_escape_the_remote_object_namespace() {
+ assert!(create_vault("password", "../other").is_err());
+ let (header, _) = create_vault("password", "vault-safe").unwrap();
+ let mut unsafe_header = header;
+ unsafe_header.vault_id = "vault/other".into();
+ assert!(unlock_vault(&unsafe_header, "password").is_err());
+ }
+}
diff --git a/crates/host-core/src/config_sync/domains.rs b/crates/host-core/src/config_sync/domains.rs
new file mode 100644
index 000000000..ca6315041
--- /dev/null
+++ b/crates/host-core/src/config_sync/domains.rs
@@ -0,0 +1,741 @@
+use super::{object_id, VaultKey};
+use crate::agent_capabilities::CapabilityLevel;
+use crate::state::AppState;
+use anyhow::Result;
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
+use sha2::{Digest, Sha256};
+use std::collections::BTreeMap;
+use std::fs;
+use std::path::{Path, PathBuf};
+use uuid::Uuid;
+
+#[path = "domains_capture.rs"]
+mod capture_impl;
+pub(crate) use capture_impl::{
+ capture, global_instruction_path_for_sync, remove_instruction_file, write_instruction_file,
+};
+#[cfg(test)]
+pub(crate) use capture_impl::{capture_instructions, capture_memory, capture_projects};
+
+pub const DOMAIN_APPLICATION: &str = "application";
+pub const DOMAIN_PROVIDERS: &str = "providers";
+pub const DOMAIN_MCP: &str = "mcp";
+pub const DOMAIN_SKILLS: &str = "skills";
+pub const DOMAIN_SUBAGENTS: &str = "subagents";
+pub const DOMAIN_INSTRUCTIONS: &str = "instructions";
+pub const DOMAIN_PROJECTS: &str = "projects";
+pub const DOMAIN_PLUGINS: &str = "plugins";
+pub const DOMAIN_AUTOMATION: &str = "automation";
+pub const DOMAIN_MEMORY: &str = "memory";
+pub const MAX_INSTRUCTION_BYTES: usize = 32 * 1024;
+
+pub(crate) const PORTABLE_APPLICATION_FIELDS: &[&str] = &[
+ "theme",
+ "language",
+ "fontFamily",
+ "fontScale",
+ "thinkingDisplayMode",
+ "enterToSend",
+ "largePasteThreshold",
+ "defaultProviderId",
+ "defaultModelId",
+ "defaultMode",
+ "infiniteProviderRetry",
+ "keybindings",
+ "linkOpenTarget",
+ "contextUsageDisplay",
+ "chatContentMaxWidth",
+ "promptEnhancementCustomTemplate",
+ "promptEnhancementUserTemplate",
+ "promptEnhancementProviderId",
+ "promptEnhancementModelId",
+ "promptEnhancementThinkingLevel",
+ "imageGeneration",
+ "imageGenerationModels",
+ "speech",
+];
+
+const PROJECT_IDENTITY_NAMESPACE: &str = "configSyncIdentities";
+const PROJECT_IDENTITY_KEY: &str = "projects";
+const PROJECT_GROUP_IDENTITY_KEY: &str = "groups";
+
+pub const ALL_DOMAINS: [&str; 10] = [
+ DOMAIN_APPLICATION,
+ DOMAIN_PROVIDERS,
+ DOMAIN_MCP,
+ DOMAIN_SKILLS,
+ DOMAIN_SUBAGENTS,
+ DOMAIN_INSTRUCTIONS,
+ DOMAIN_PROJECTS,
+ DOMAIN_PLUGINS,
+ DOMAIN_AUTOMATION,
+ DOMAIN_MEMORY,
+];
+
+/// Contract metadata for each portable domain. Capture/apply code below is
+/// deliberately explicit per domain; this registry keeps the portability,
+/// identity, merge, activation, and recovery policy reviewable in one place.
+#[derive(Debug, Clone, Copy)]
+#[allow(dead_code)]
+pub struct DomainAdapterSpec {
+ pub domain: &'static str,
+ pub schema_version: u32,
+ pub exportable_fields: &'static [&'static str],
+ pub secret_fields: &'static [&'static str],
+ pub local_overlays: &'static [&'static str],
+ pub identity: &'static str,
+ pub references: &'static [&'static str],
+ pub merge_granularity: &'static str,
+ pub activation_policy: &'static str,
+ pub recovery_policy: &'static str,
+}
+
+pub const DOMAIN_ADAPTERS: &[DomainAdapterSpec] = &[
+ DomainAdapterSpec {
+ domain: DOMAIN_APPLICATION,
+ schema_version: 1,
+ exportable_fields: &[
+ "theme",
+ "language",
+ "fontFamily",
+ "fontScale",
+ "thinkingDisplayMode",
+ "enterToSend",
+ "keybindings",
+ "display bindings",
+ "provider/model bindings",
+ ],
+ secret_fields: &[],
+ local_overlays: &[
+ "window geometry",
+ "default command shell",
+ "network proxy",
+ "developer mode",
+ "onboarding state",
+ "permission mode",
+ ],
+ identity: "application",
+ references: &["provider ids", "model ids"],
+ merge_granularity: "field",
+ activation_policy: "immediate-safe-settings-only",
+ recovery_policy: "import journal",
+ },
+ DomainAdapterSpec {
+ domain: DOMAIN_PROVIDERS,
+ schema_version: 1,
+ exportable_fields: &[
+ "provider identity",
+ "models",
+ "aliases",
+ "parameters",
+ "ordering",
+ "defaults",
+ ],
+ secret_fields: &["portableApiKey"],
+ local_overlays: &["OAuth sessions", "readiness flags", "catalog caches"],
+ identity: "user-owned provider id",
+ references: &["model bindings"],
+ merge_granularity: "provider aggregate",
+ activation_policy: "review when credential-bearing or destination changes",
+ recovery_policy: "database plus secret-store journal",
+ },
+ DomainAdapterSpec {
+ domain: DOMAIN_MCP,
+ schema_version: 1,
+ exportable_fields: &[
+ "scope",
+ "transport",
+ "command",
+ "args",
+ "endpoint",
+ "desired enabled state",
+ ],
+ secret_fields: &["env", "headers"],
+ local_overlays: &["device approval", "local path bindings"],
+ identity: "scope plus user-owned MCP id",
+ references: &["project mapping"],
+ merge_granularity: "one definition",
+ activation_policy: "approval required before discovery",
+ recovery_policy: "capability write journal",
+ },
+ DomainAdapterSpec {
+ domain: DOMAIN_SKILLS,
+ schema_version: 1,
+ exportable_fields: &["metadata", "instructions", "bounded package resources"],
+ secret_fields: &[],
+ local_overlays: &[
+ "external symlink targets",
+ "execution approval",
+ "dependencies",
+ ],
+ identity: "scope plus skill id",
+ references: &["project mapping", "package resources"],
+ merge_granularity: "one package",
+ activation_policy: "approval required before discovery",
+ recovery_policy: "bounded package write journal",
+ },
+ DomainAdapterSpec {
+ domain: DOMAIN_SUBAGENTS,
+ schema_version: 1,
+ exportable_fields: &[
+ "definition",
+ "prompt",
+ "model references",
+ "tool preferences",
+ ],
+ secret_fields: &[],
+ local_overlays: &["global-only ownership", "privileges", "execution approval"],
+ identity: "global subagent id",
+ references: &["provider/model ids"],
+ merge_granularity: "one definition",
+ activation_policy: "approval required before discovery",
+ recovery_policy: "capability write journal",
+ },
+ DomainAdapterSpec {
+ domain: DOMAIN_INSTRUCTIONS,
+ schema_version: 1,
+ exportable_fields: &[
+ "fixed global file",
+ "registered project-root file",
+ "group text",
+ ],
+ secret_fields: &["instruction content"],
+ local_overlays: &["unregistered repository files", "symlink targets"],
+ identity: "scope plus project/group identity",
+ references: &["project mapping"],
+ merge_granularity: "one file or group text",
+ activation_policy: "approval required before write",
+ recovery_policy: "atomic file replacement journal",
+ },
+ DomainAdapterSpec {
+ domain: DOMAIN_PROJECTS,
+ schema_version: 1,
+ exportable_fields: &[
+ "logical identity",
+ "name",
+ "group roots",
+ "ordering",
+ "pinned",
+ ],
+ secret_fields: &[],
+ local_overlays: &["absolute folder bindings"],
+ identity: "host-assigned logical project/group id",
+ references: &["root mappings"],
+ merge_granularity: "project or ordered group",
+ activation_policy: "mapping and approval required",
+ recovery_policy: "database import journal",
+ },
+ DomainAdapterSpec {
+ domain: DOMAIN_PLUGINS,
+ schema_version: 1,
+ exportable_fields: &["installation intent", "id/version/source metadata"],
+ secret_fields: &[],
+ local_overlays: &[
+ "binaries",
+ "plugin database",
+ "permission grants",
+ "activation",
+ ],
+ identity: "plugin id",
+ references: &["future validated SDK settings only"],
+ merge_granularity: "one installation intent",
+ activation_policy: "explicit installation and activation",
+ recovery_policy: "overlay journal",
+ },
+ DomainAdapterSpec {
+ domain: DOMAIN_AUTOMATION,
+ schema_version: 1,
+ exportable_fields: &["task definition", "prompt", "schedule", "references"],
+ secret_fields: &["credential references"],
+ local_overlays: &["execution ownership", "enabled state on new device"],
+ identity: "automation id",
+ references: &["project mapping", "provider/model ids"],
+ merge_granularity: "one task",
+ activation_policy: "approval plus local execution ownership",
+ recovery_policy: "database import journal",
+ },
+ DomainAdapterSpec {
+ domain: DOMAIN_MEMORY,
+ schema_version: 1,
+ exportable_fields: &["opt-in app-managed project/group memory"],
+ secret_fields: &["memory content"],
+ local_overlays: &["category subscription"],
+ identity: "project/group identity",
+ references: &["project mapping"],
+ merge_granularity: "one memory unit",
+ activation_policy: "mapping and approval required",
+ recovery_policy: "database import journal",
+ },
+];
+
+pub fn adapter_for(domain: &str) -> Option<&'static DomainAdapterSpec> {
+ DOMAIN_ADAPTERS
+ .iter()
+ .find(|adapter| adapter.domain == domain)
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct PortableEntity {
+ pub domain: String,
+ pub entity_id: String,
+ pub label: String,
+ pub deleted: bool,
+ pub requires_approval: bool,
+ pub secret_bearing: bool,
+ pub mapping_required: bool,
+ pub digest: String,
+ pub payload: Value,
+ #[serde(default)]
+ pub resource_ids: Vec<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct RevisionManifest {
+ pub format: String,
+ pub version: u32,
+ pub revision_id: String,
+ #[serde(default)]
+ pub parents: Vec<String>,
+ pub created_at: String,
+ pub entities: Vec<PortableEntity>,
+ pub resource_ids: Vec<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct LocalSnapshot {
+ pub manifest: RevisionManifest,
+ pub resources: ResourceMap,
+}
+
+pub type ResourceMap = BTreeMap<String, Vec<u8>>;
+
+#[derive(Debug, Clone, Default, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PreviewCounts {
+ pub supported: usize,
+ pub excluded: usize,
+ pub secret_bearing: usize,
+ pub mapping_required: usize,
+ pub pending_activation: usize,
+ pub conflicts: usize,
+ pub categories: Vec<CategoryPreview>,
+}
+
+#[derive(Debug, Clone, Default, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct CategoryPreview {
+ pub category: String,
+ pub supported: usize,
+ pub excluded: usize,
+ pub secret_bearing: usize,
+ pub mapping_required: usize,
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct CategorySelection(pub BTreeMap<String, bool>);
+
+impl CategorySelection {
+ pub fn all_selected() -> Self {
+ let mut values = BTreeMap::new();
+ for domain in ALL_DOMAINS {
+ values.insert(domain.to_string(), true);
+ }
+ values.insert("credentials".to_string(), false);
+ values.insert(DOMAIN_MEMORY.to_string(), false);
+ Self(values)
+ }
+
+ pub fn is_selected(&self, domain: &str) -> bool {
+ self.0.get(domain).copied().unwrap_or(true)
+ }
+
+ pub fn include_secrets(&self, requested: bool) -> bool {
+ requested && self.0.get("credentials").copied().unwrap_or(false)
+ }
+}
+
+/// Local path bindings are overlays. They let a device keep using logical
+/// identifiers received from another device without exporting filesystem
+/// paths as portable data.
+#[derive(Debug, Clone, Default)]
+pub struct ProjectIdentityOverrides {
+ pub project_ids: BTreeMap<String, String>,
+ pub group_ids: BTreeMap<String, String>,
+}
+
+impl ProjectIdentityOverrides {
+ pub fn from_mappings(
+ project_mappings: &BTreeMap<String, String>,
+ project_group_mappings: &BTreeMap<String, Vec<String>>,
+ ) -> Self {
+ let mut overrides = Self::default();
+ for (logical_id, path) in project_mappings {
+ overrides
+ .project_ids
+ .insert(path.clone(), logical_id.clone());
+ }
+ for (logical_id, paths) in project_group_mappings {
+ for path in paths {
+ overrides.group_ids.insert(path.clone(), logical_id.clone());
+ }
+ }
+ overrides
+ }
+}
+
+fn stable_id(prefix: &str, value: &str) -> String {
+ let mut hasher = Sha256::new();
+ hasher.update(prefix.as_bytes());
+ hasher.update([0]);
+ hasher.update(value.trim().to_lowercase().as_bytes());
+ format!("{prefix}:{}", hex::encode(hasher.finalize()))
+}
+
+#[allow(clippy::too_many_arguments)]
+fn digest_entity(
+ domain: &str,
+ entity_id: &str,
+ deleted: bool,
+ requires_approval: bool,
+ secret_bearing: bool,
+ mapping_required: bool,
+ payload: &Value,
+ resource_ids: &[String],
+) -> String {
+ let material = json!({
+ "domain": domain,
+ "entityId": entity_id,
+ "deleted": deleted,
+ "requiresApproval": requires_approval,
+ "secretBearing": secret_bearing,
+ "mappingRequired": mapping_required,
+ "payload": payload,
+ "resourceIds": resource_ids,
+ });
+ let mut hasher = Sha256::new();
+ hasher.update(serde_json::to_vec(&material).unwrap_or_default());
+ hex::encode(hasher.finalize())
+}
+
+pub fn refresh_digest(entity: &mut PortableEntity) {
+ entity.digest = digest_entity(
+ &entity.domain,
+ &entity.entity_id,
+ entity.deleted,
+ entity.requires_approval,
+ entity.secret_bearing,
+ entity.mapping_required,
+ &entity.payload,
+ &entity.resource_ids,
+ );
+}
+
+#[allow(clippy::too_many_arguments)]
+fn entity(
+ domain: &str,
+ entity_id: impl Into<String>,
+ label: impl Into<String>,
+ payload: Value,
+ requires_approval: bool,
+ secret_bearing: bool,
+ mapping_required: bool,
+ resource_ids: Vec<String>,
+) -> PortableEntity {
+ let entity_id = entity_id.into();
+ PortableEntity {
+ domain: domain.to_string(),
+ label: label.into(),
+ digest: digest_entity(
+ domain,
+ &entity_id,
+ false,
+ requires_approval,
+ secret_bearing,
+ mapping_required,
+ &payload,
+ &resource_ids,
+ ),
+ entity_id,
+ deleted: false,
+ requires_approval,
+ secret_bearing,
+ mapping_required,
+ payload,
+ resource_ids,
+ }
+}
+
+fn strip_keys(value: &mut Value, keys: &[&str]) {
+ if let Some(object) = value.as_object_mut() {
+ for key in keys {
+ object.remove(*key);
+ }
+ }
+}
+
+fn project_logical_id(path: &str) -> String {
+ stable_id("project-path", path)
+}
+
+fn project_group_logical_id(
+ st: &mut AppState,
+ group: &crate::db::ProjectGroupRecord,
+) -> Result<String> {
+ if group.legacy {
+ return Ok(project_logical_id(&group.primary_path));
+ }
+ let mut identities = st
+ .db
+ .kv_get(PROJECT_IDENTITY_NAMESPACE, PROJECT_GROUP_IDENTITY_KEY)?
+ .map(serde_json::from_value::<BTreeMap<String, String>>)
+ .transpose()?
+ .unwrap_or_default();
+ if let Some(identity) = identities.get(&group.id) {
+ return Ok(identity.clone());
+ }
+ let identity = format!("project-group:{}", Uuid::new_v4());
+ identities.insert(group.id.clone(), identity.clone());
+ st.db.kv_set(
+ PROJECT_IDENTITY_NAMESPACE,
+ PROJECT_GROUP_IDENTITY_KEY,
+ &serde_json::to_value(identities)?,
+ )?;
+ Ok(identity)
+}
+
+fn project_identity_for_path(st: &mut AppState, path: &str) -> Result<String> {
+ let project = st
+ .db
+ .list_projects()?
+ .into_iter()
+ .find(|project| project.path == path);
+ let Some(project) = project else {
+ return Ok(project_logical_id(path));
+ };
+ let mut identities = st
+ .db
+ .kv_get(PROJECT_IDENTITY_NAMESPACE, PROJECT_IDENTITY_KEY)?
+ .map(serde_json::from_value::<BTreeMap<String, String>>)
+ .transpose()?
+ .unwrap_or_default();
+ if let Some(identity) = identities.get(&project.id.to_string()) {
+ return Ok(identity.clone());
+ }
+ let identity = format!("project:{}", Uuid::new_v4());
+ identities.insert(project.id.to_string(), identity.clone());
+ st.db.kv_set(
+ PROJECT_IDENTITY_NAMESPACE,
+ PROJECT_IDENTITY_KEY,
+ &serde_json::to_value(identities)?,
+ )?;
+ Ok(identity)
+}
+
+fn project_scope(
+ st: &mut AppState,
+ path: &str,
+ overrides: &ProjectIdentityOverrides,
+) -> Result<(String, Option<String>, Option<usize>)> {
+ let mapped_project_id = overrides.project_ids.get(path).cloned();
+ let project_id = mapped_project_id
+ .clone()
+ .unwrap_or(project_identity_for_path(st, path)?);
+ let Some(group) = st.db.project_group_for_path(path)? else {
+ return Ok((project_id, None, None));
+ };
+ if group.legacy {
+ return Ok((project_id, None, None));
+ }
+ let group_id = match overrides
+ .group_ids
+ .get(path)
+ .or_else(|| overrides.group_ids.get(&group.primary_path))
+ .cloned()
+ {
+ Some(group_id) => group_id,
+ None => project_group_logical_id(st, &group)?,
+ };
+ let root_position = group.roots.iter().position(|root| root.path == path);
+ let project_id = mapped_project_id.unwrap_or_else(|| {
+ root_position
+ .map(|position| stable_id("project-root", &format!("{group_id}:{position}")))
+ .unwrap_or(project_id)
+ });
+ Ok((project_id, Some(group_id), root_position))
+}
+
+pub fn snapshot_digest(snapshot: &LocalSnapshot) -> String {
+ let material = json!({
+ "entities": snapshot
+ .manifest
+ .entities
+ .iter()
+ .map(|entity| json!({
+ "domain": entity.domain,
+ "entityId": entity.entity_id,
+ "digest": entity.digest,
+ }))
+ .collect::<Vec<_>>(),
+ "resources": snapshot.resources.keys().collect::<Vec<_>>(),
+ });
+ let mut hasher = Sha256::new();
+ hasher.update(serde_json::to_vec(&material).unwrap_or_default());
+ hex::encode(hasher.finalize())
+}
+
+pub fn preview(snapshot: &LocalSnapshot, selection: &CategorySelection) -> PreviewCounts {
+ let mut counts = PreviewCounts::default();
+ let mut by_category: BTreeMap<String, CategoryPreview> = BTreeMap::new();
+ for entity in &snapshot.manifest.entities {
+ let category =
+ by_category
+ .entry(entity.domain.clone())
+ .or_insert_with(|| CategoryPreview {
+ category: entity.domain.clone(),
+ ..CategoryPreview::default()
+ });
+ if selection.is_selected(&entity.domain) {
+ counts.supported += 1;
+ category.supported += 1;
+ } else {
+ counts.excluded += 1;
+ category.excluded += 1;
+ }
+ if entity.secret_bearing {
+ counts.secret_bearing += 1;
+ category.secret_bearing += 1;
+ }
+ if entity.mapping_required {
+ counts.mapping_required += 1;
+ category.mapping_required += 1;
+ }
+ if entity.requires_approval {
+ counts.pending_activation += 1;
+ }
+ }
+ counts.categories = by_category.into_values().collect();
+ counts
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::state::AppState;
+
+ #[test]
+ fn adapter_registry_covers_every_portable_domain() {
+ assert_eq!(DOMAIN_ADAPTERS.len(), ALL_DOMAINS.len());
+ assert!(!PORTABLE_APPLICATION_FIELDS.contains(&"defaultPermissionMode"));
+ for domain in ALL_DOMAINS {
+ let adapter = adapter_for(domain).expect("portable domain adapter");
+ assert_eq!(adapter.schema_version, 1);
+ assert!(!adapter.identity.is_empty());
+ assert!(!adapter.merge_granularity.is_empty());
+ assert!(!adapter.activation_policy.is_empty());
+ assert!(!adapter.recovery_policy.is_empty());
+ }
+ }
+
+ #[test]
+ fn captures_non_legacy_project_group_memory_as_a_separate_entity() {
+ let data_dir = tempfile::tempdir().unwrap();
+ let first = data_dir.path().join("first");
+ let second = data_dir.path().join("second");
+ std::fs::create_dir_all(&first).unwrap();
+ std::fs::create_dir_all(&second).unwrap();
+
+ let mut state = AppState::open(data_dir.path()).unwrap();
+ let group = state
+ .db
+ .create_project_group(
+ "Workspace",
+ &[
+ first.to_string_lossy().into_owned(),
+ second.to_string_lossy().into_owned(),
+ ],
+ )
+ .unwrap();
+ state
+ .db
+ .set_project_group_memory(
+ &group.id,
+ &json!([{
+ "id": "note-1",
+ "title": "Context",
+ "content": "Keep this with the workspace",
+ }]),
+ )
+ .unwrap();
+
+ let entities = capture_memory(&mut state, &ProjectIdentityOverrides::default()).unwrap();
+ let entity = entities
+ .iter()
+ .find(|entity| entity.payload["projectGroupLogicalId"].is_string())
+ .expect("group memory entity");
+ let logical_id = entity.payload["projectGroupLogicalId"]
+ .as_str()
+ .expect("group logical id");
+ assert_eq!(entity.entity_id, format!("memory:{logical_id}"));
+ assert!(entity.mapping_required);
+ assert!(entity.secret_bearing);
+ assert_eq!(entity.payload["memory"]["entries"][0]["id"], "note-1");
+ }
+
+ #[test]
+ fn captures_only_the_app_managed_project_instruction_file() {
+ let data_dir = tempfile::tempdir().unwrap();
+ let project = data_dir.path().join("project");
+ let nested = project.join("nested");
+ std::fs::create_dir_all(&nested).unwrap();
+ std::fs::write(project.join("AGENTS.md"), "project guidance\n").unwrap();
+ std::fs::write(nested.join("AGENTS.md"), "nested guidance\n").unwrap();
+
+ let mut state = AppState::open(data_dir.path()).unwrap();
+ state
+ .db
+ .ensure_project(&project.to_string_lossy(), false)
+ .unwrap();
+ let entities =
+ capture_instructions(&mut state, &ProjectIdentityOverrides::default()).unwrap();
+ let project_entities = entities
+ .iter()
+ .filter(|entity| entity.payload["scope"] == "project")
+ .collect::<Vec<_>>();
+ assert_eq!(project_entities.len(), 1);
+ assert_eq!(project_entities[0].payload["content"], "project guidance\n");
+ assert!(project_entities[0].mapping_required);
+ }
+
+ #[test]
+ fn project_identities_are_local_stable_and_mapping_overrides_are_used() {
+ let data_dir = tempfile::tempdir().unwrap();
+ let project = data_dir.path().join("project");
+ std::fs::create_dir_all(&project).unwrap();
+ let mut state = AppState::open(data_dir.path()).unwrap();
+ state
+ .db
+ .ensure_project(&project.to_string_lossy(), false)
+ .unwrap();
+
+ let first = capture_projects(&mut state, &ProjectIdentityOverrides::default()).unwrap();
+ let second = capture_projects(&mut state, &ProjectIdentityOverrides::default()).unwrap();
+ assert_eq!(
+ first[0].payload["logicalId"],
+ second[0].payload["logicalId"]
+ );
+ assert!(first[0].payload["logicalId"]
+ .as_str()
+ .is_some_and(|value| value.starts_with("project:")));
+ let stored_path = state.db.list_projects().unwrap()[0].path.clone();
+
+ let mut overrides = ProjectIdentityOverrides::default();
+ overrides
+ .project_ids
+ .insert(stored_path, "project:from-other-device".into());
+ let mapped = capture_projects(&mut state, &overrides).unwrap();
+ assert_eq!(mapped[0].payload["logicalId"], "project:from-other-device");
+ }
+}
diff --git a/crates/host-core/src/config_sync/domains_capture.rs b/crates/host-core/src/config_sync/domains_capture.rs
new file mode 100644
index 000000000..83dacc8cc
--- /dev/null
+++ b/crates/host-core/src/config_sync/domains_capture.rs
@@ -0,0 +1,820 @@
+use super::*;
+
+fn capture_application(st: &AppState) -> Result<PortableEntity> {
+ let mut settings = st.db.get_setting("app")?.unwrap_or_else(|| json!({}));
+ if let Some(object) = settings.as_object_mut() {
+ object.retain(|key, _| PORTABLE_APPLICATION_FIELDS.contains(&key.as_str()));
+ }
+ Ok(entity(
+ DOMAIN_APPLICATION,
+ "application",
+ "Application preferences",
+ settings,
+ false,
+ false,
+ false,
+ Vec::new(),
+ ))
+}
+
+fn capture_providers(st: &AppState) -> Result<Vec<PortableEntity>> {
+ let providers = crate::providers::list_providers(&st.db, &st.secrets, true)?;
+ let mut result = Vec::new();
+ for provider in providers {
+ if provider.owner_plugin_id.is_some() {
+ continue;
+ }
+ let mut payload = serde_json::to_value(&provider)?;
+ strip_keys(
+ &mut payload,
+ &[
+ "hasSecret",
+ "hasOauth",
+ "oauthAccountLabel",
+ "enabled",
+ "supportsReasoning",
+ "supportsVision",
+ "supportedThinkingLevels",
+ "createdAt",
+ "updatedAt",
+ "ownerPluginId",
+ ],
+ );
+ let has_secret = provider.has_secret;
+ result.push(entity(
+ DOMAIN_PROVIDERS,
+ format!("provider:{}", provider.id),
+ provider.name,
+ payload,
+ has_secret,
+ has_secret,
+ false,
+ Vec::new(),
+ ));
+ }
+ Ok(result)
+}
+
+fn capture_mcp(
+ st: &mut AppState,
+ selection: &CategorySelection,
+ include_secrets: bool,
+ identities: &ProjectIdentityOverrides,
+) -> Result<Vec<PortableEntity>> {
+ let mut result = Vec::new();
+ let projects = st.db.list_projects()?;
+ let mut targets: Vec<(CapabilityLevel, Option<String>)> = vec![(CapabilityLevel::Global, None)];
+ targets.extend(
+ projects
+ .into_iter()
+ .map(|project| (CapabilityLevel::Project, Some(project.path))),
+ );
+ for (level, project_path) in targets {
+ for record in st.mcp_servers.list(level, project_path.as_deref())? {
+ let mut payload = serde_json::to_value(&record)?;
+ strip_keys(&mut payload, &["path", "createdAt", "updatedAt"]);
+ let secret_bearing = !record.env.is_empty() || !record.headers.is_empty();
+ let project_scope = record
+ .project_path
+ .as_deref()
+ .map(|path| project_scope(st, path, identities))
+ .transpose()?;
+ let project_logical_id = project_scope.as_ref().map(|scope| scope.0.clone());
+ if let Some(object) = payload.as_object_mut() {
+ object.remove("projectPath");
+ if let Some(project_logical_id) = project_logical_id.as_ref() {
+ object.insert(
+ "projectLogicalId".to_string(),
+ Value::String(project_logical_id.clone()),
+ );
+ }
+ if let Some((_, Some(group_id), root_position)) = project_scope.as_ref() {
+ object.insert(
+ "projectGroupLogicalId".into(),
+ Value::String(group_id.clone()),
+ );
+ if let Some(position) = root_position {
+ object.insert("projectRootPosition".into(), json!(position));
+ }
+ }
+ }
+ if !selection.include_secrets(include_secrets) {
+ if let Some(object) = payload.as_object_mut() {
+ object.remove("env");
+ object.remove("headers");
+ if !record.env.is_empty() {
+ object.insert(
+ "envKeys".to_string(),
+ Value::Array(record.env.keys().cloned().map(Value::String).collect()),
+ );
+ }
+ if !record.headers.is_empty() {
+ object.insert(
+ "headerKeys".to_string(),
+ Value::Array(
+ record.headers.keys().cloned().map(Value::String).collect(),
+ ),
+ );
+ }
+ }
+ }
+ let id = format!(
+ "mcp:{}:{}",
+ record.level.as_deref().unwrap_or("global"),
+ stable_id(
+ "id",
+ &format!(
+ "{}:{}",
+ project_logical_id.as_deref().unwrap_or("global"),
+ record.id
+ ),
+ )
+ );
+ result.push(entity(
+ DOMAIN_MCP,
+ id,
+ record.label,
+ payload,
+ true,
+ secret_bearing,
+ project_logical_id.is_some(),
+ Vec::new(),
+ ));
+ }
+ }
+ Ok(result)
+}
+
+fn capture_skills(
+ st: &mut AppState,
+ key: &VaultKey,
+ selection: &CategorySelection,
+ identities: &ProjectIdentityOverrides,
+) -> Result<(Vec<PortableEntity>, ResourceMap)> {
+ let mut result = Vec::new();
+ let mut resources = BTreeMap::new();
+ let projects = st.db.list_projects()?;
+ let mut targets: Vec<(CapabilityLevel, Option<String>)> = vec![(CapabilityLevel::Global, None)];
+ targets.extend(
+ projects
+ .into_iter()
+ .map(|project| (CapabilityLevel::Project, Some(project.path))),
+ );
+ for (level, project_path) in targets {
+ for record in st.user_skills.list(level, project_path.as_deref())? {
+ let bytes = st
+ .user_skills
+ .read(&record.id, Some(level), record.project_path.as_deref())?
+ .map(|(_, body)| body.into_bytes())
+ .ok_or_else(|| anyhow::anyhow!("skill disappeared while capturing"))?;
+ let resource_id = object_id(key, &bytes);
+ resources.entry(resource_id.clone()).or_insert(bytes);
+ let package_files =
+ st.user_skills
+ .package_files(&record.id, level, record.project_path.as_deref())?;
+ let mut resource_ids = vec![resource_id.clone()];
+ let mut package_descriptors = Vec::with_capacity(package_files.len());
+ for (path, bytes) in package_files {
+ let package_resource_id = object_id(key, &bytes);
+ resources
+ .entry(package_resource_id.clone())
+ .or_insert(bytes);
+ resource_ids.push(package_resource_id.clone());
+ package_descriptors.push(json!({
+ "path": path,
+ "resourceId": package_resource_id,
+ }));
+ }
+ let mut payload = serde_json::to_value(&record)?;
+ strip_keys(
+ &mut payload,
+ &[
+ "path",
+ "projectPath",
+ "workspacePath",
+ "sizeBytes",
+ "createdAt",
+ "updatedAt",
+ ],
+ );
+ let project_scope = record
+ .project_path
+ .as_deref()
+ .map(|path| project_scope(st, path, identities))
+ .transpose()?;
+ let project_logical_id = project_scope.as_ref().map(|scope| scope.0.clone());
+ if let Some(object) = payload.as_object_mut() {
+ object.insert(
+ "bodyResourceId".to_string(),
+ Value::String(resource_id.clone()),
+ );
+ if !package_descriptors.is_empty() {
+ object.insert(
+ "packageFiles".to_string(),
+ Value::Array(package_descriptors),
+ );
+ }
+ if let Some(project_logical_id) = project_logical_id.as_ref() {
+ object.insert(
+ "projectLogicalId".to_string(),
+ Value::String(project_logical_id.clone()),
+ );
+ }
+ if let Some((_, Some(group_id), root_position)) = project_scope.as_ref() {
+ object.insert(
+ "projectGroupLogicalId".into(),
+ Value::String(group_id.clone()),
+ );
+ if let Some(position) = root_position {
+ object.insert("projectRootPosition".into(), json!(position));
+ }
+ }
+ }
+ let id = format!(
+ "skill:{}",
+ stable_id(
+ "skill",
+ &format!(
+ "{}:{}",
+ project_logical_id.as_deref().unwrap_or("global"),
+ record.id
+ ),
+ )
+ );
+ result.push(entity(
+ DOMAIN_SKILLS,
+ id,
+ record.name,
+ payload,
+ true,
+ false,
+ project_logical_id.is_some(),
+ resource_ids,
+ ));
+ }
+ }
+ if !selection.is_selected(DOMAIN_SKILLS) {
+ result.clear();
+ resources.clear();
+ }
+ Ok((result, resources))
+}
+
+fn capture_subagents(
+ st: &mut AppState,
+ key: &VaultKey,
+) -> Result<(Vec<PortableEntity>, ResourceMap)> {
+ let mut result = Vec::new();
+ let mut resources = BTreeMap::new();
+ for record in st.user_subagents.list()? {
+ let bytes = st
+ .user_subagents
+ .read(&record.id)?
+ .map(|(_, body)| body.into_bytes())
+ .ok_or_else(|| anyhow::anyhow!("subagent disappeared while capturing"))?;
+ let resource_id = object_id(key, &bytes);
+ resources.entry(resource_id.clone()).or_insert(bytes);
+ let mut payload = serde_json::to_value(&record)?;
+ strip_keys(
+ &mut payload,
+ &["path", "sizeBytes", "createdAt", "updatedAt"],
+ );
+ if let Some(object) = payload.as_object_mut() {
+ object.insert(
+ "bodyResourceId".to_string(),
+ Value::String(resource_id.clone()),
+ );
+ }
+ result.push(entity(
+ DOMAIN_SUBAGENTS,
+ format!("subagent:{}", record.id),
+ record.name,
+ payload,
+ true,
+ false,
+ false,
+ vec![resource_id],
+ ));
+ }
+ Ok((result, resources))
+}
+
+pub(crate) fn capture_projects(
+ st: &mut AppState,
+ identities: &ProjectIdentityOverrides,
+) -> Result<Vec<PortableEntity>> {
+ let mut result = Vec::new();
+ for project in st.db.list_projects()? {
+ let (project_id, group_id, _) = project_scope(st, &project.path, identities)?;
+ if group_id.is_some() {
+ // Non-legacy project groups are represented by their group entity;
+ // exporting each root as another project would duplicate the
+ // logical configuration and weaken primary-root invariants.
+ continue;
+ }
+ let payload = json!({
+ "logicalId": project_id,
+ "name": project.name,
+ "pinned": project.pinned,
+ });
+ let label = payload["name"].as_str().unwrap_or("Project").to_string();
+ result.push(entity(
+ DOMAIN_PROJECTS,
+ format!("project:{project_id}"),
+ label,
+ payload,
+ true,
+ false,
+ true,
+ Vec::new(),
+ ));
+ }
+ for group in st.db.list_project_groups()? {
+ if group.legacy {
+ continue;
+ }
+ let (_, group_id, _) = project_scope(st, &group.primary_path, identities)?;
+ let logical_id = match group_id {
+ Some(logical_id) => logical_id,
+ None => project_group_logical_id(st, &group)?,
+ };
+ let payload = json!({
+ "logicalId": logical_id,
+ "name": group.name.clone(),
+ "pinned": group.pinned,
+ "roots": group
+ .roots
+ .iter()
+ .map(|root| json!({ "name": root.name, "position": root.position }))
+ .collect::<Vec<_>>(),
+ });
+ result.push(entity(
+ DOMAIN_PROJECTS,
+ format!("project-group:{}", group.id),
+ group.name,
+ payload,
+ true,
+ false,
+ true,
+ Vec::new(),
+ ));
+ }
+ Ok(result)
+}
+
+pub(crate) fn capture_memory(
+ st: &mut AppState,
+ identities: &ProjectIdentityOverrides,
+) -> Result<Vec<PortableEntity>> {
+ let mut result = Vec::new();
+ for project in st.db.list_projects()? {
+ let memory = st.db.get_project_memory(&project.path)?;
+ if memory.content.trim().is_empty() && memory.entries.is_none() {
+ continue;
+ }
+ let project_name = project.name.clone();
+ let (project_id, group_id, root_position) = project_scope(st, &project.path, identities)?;
+ let mut payload = json!({
+ "projectLogicalId": project_id.clone(),
+ "memory": memory,
+ });
+ if let Some(object) = payload.as_object_mut() {
+ if let Some(group_id) = group_id {
+ object.insert("projectGroupLogicalId".into(), Value::String(group_id));
+ }
+ if let Some(position) = root_position {
+ object.insert("projectRootPosition".into(), json!(position));
+ }
+ }
+ result.push(entity(
+ DOMAIN_MEMORY,
+ format!("memory:{project_id}"),
+ project_name,
+ payload,
+ false,
+ true,
+ true,
+ Vec::new(),
+ ));
+ }
+ for group in st.db.list_project_groups()? {
+ if group.legacy {
+ continue;
+ }
+ let memory = st.db.get_project_group_memory(&group.id)?;
+ if memory.content.trim().is_empty() && memory.entries.is_none() {
+ continue;
+ }
+ let logical_id = project_group_logical_id(st, &group)?;
+ result.push(entity(
+ DOMAIN_MEMORY,
+ format!("memory:{logical_id}"),
+ group.name.clone(),
+ json!({
+ "projectGroupLogicalId": logical_id,
+ "projectGroupName": group.name,
+ "memory": memory,
+ }),
+ false,
+ true,
+ true,
+ Vec::new(),
+ ));
+ }
+ Ok(result)
+}
+
+pub(crate) fn capture_instructions(
+ st: &mut AppState,
+ identities: &ProjectIdentityOverrides,
+) -> Result<Vec<PortableEntity>> {
+ let mut result = Vec::new();
+ if let Some(path) = global_instruction_path() {
+ if let Some(content) = read_instruction_file(&path)? {
+ result.push(entity(
+ DOMAIN_INSTRUCTIONS,
+ "instructions:global",
+ "Global instructions",
+ json!({
+ "scope": "global",
+ "content": content,
+ }),
+ true,
+ true,
+ false,
+ Vec::new(),
+ ));
+ }
+ }
+ for group in st.db.list_project_groups()? {
+ if group.legacy {
+ continue;
+ }
+ let logical_id = project_group_logical_id(st, &group)?;
+ let content = st.db.get_project_group_instructions(&group.id)?;
+ if content.trim().is_empty() {
+ continue;
+ }
+ let group_name = group.name.clone();
+ result.push(entity(
+ DOMAIN_INSTRUCTIONS,
+ format!("project-group:{}", group.id),
+ group_name,
+ json!({
+ "projectGroupLogicalId": logical_id,
+ "projectGroupName": group.name,
+ "content": content,
+ }),
+ false,
+ true,
+ true,
+ Vec::new(),
+ ));
+ }
+ for project in st.db.list_projects()? {
+ let path = Path::new(&project.path).join("AGENTS.md");
+ let Some(content) = read_instruction_file(&path)? else {
+ continue;
+ };
+ let (project_id, group_id, root_position) = project_scope(st, &project.path, identities)?;
+ let mut payload = json!({
+ "scope": "project",
+ "projectLogicalId": project_id,
+ "content": content,
+ });
+ if let Some(object) = payload.as_object_mut() {
+ if let Some(group_id) = group_id {
+ object.insert("projectGroupLogicalId".into(), Value::String(group_id));
+ }
+ if let Some(position) = root_position {
+ object.insert("projectRootPosition".into(), json!(position));
+ }
+ }
+ result.push(entity(
+ DOMAIN_INSTRUCTIONS,
+ format!("instructions:project:{project_id}"),
+ project.name,
+ payload,
+ true,
+ true,
+ true,
+ Vec::new(),
+ ));
+ }
+ Ok(result)
+}
+
+fn global_instruction_path() -> Option<PathBuf> {
+ dirs::home_dir().map(|home| home.join(".pi").join("agent").join("AGENTS.md"))
+}
+
+fn read_instruction_file(path: &Path) -> Result<Option<String>> {
+ let Ok(metadata) = fs::symlink_metadata(path) else {
+ return Ok(None);
+ };
+ if metadata.file_type().is_symlink() || !metadata.is_file() {
+ return Ok(None);
+ }
+ let bytes = fs::read(path)?;
+ if bytes.len() > MAX_INSTRUCTION_BYTES {
+ return Err(anyhow::anyhow!(
+ "CONFIG_SYNC_LIMIT_EXCEEDED: instruction file is too large"
+ ));
+ }
+ let content = String::from_utf8(bytes)
+ .map_err(|_| anyhow::anyhow!("CONFIG_SYNC_INVALID: instruction file is not UTF-8"))?;
+ if content.trim().is_empty() {
+ return Ok(None);
+ }
+ Ok(Some(content))
+}
+
+pub(crate) fn global_instruction_path_for_sync() -> Result<PathBuf> {
+ global_instruction_path()
+ .ok_or_else(|| anyhow::anyhow!("CONFIG_SYNC_INVALID: home directory is unavailable"))
+}
+
+pub(crate) fn write_instruction_file(path: &Path, content: &str) -> Result<()> {
+ if content.len() > MAX_INSTRUCTION_BYTES {
+ return Err(anyhow::anyhow!(
+ "CONFIG_SYNC_LIMIT_EXCEEDED: instruction file is too large"
+ ));
+ }
+ if fs::symlink_metadata(path)
+ .map(|metadata| metadata.file_type().is_symlink())
+ .unwrap_or(false)
+ {
+ return Err(anyhow::anyhow!(
+ "CONFIG_SYNC_INVALID: instruction file is a symbolic link"
+ ));
+ }
+ let parent = path
+ .parent()
+ .ok_or_else(|| anyhow::anyhow!("CONFIG_SYNC_INVALID: instruction path has no parent"))?;
+ fs::create_dir_all(parent)?;
+ let filename = path
+ .file_name()
+ .and_then(|value| value.to_str())
+ .ok_or_else(|| anyhow::anyhow!("CONFIG_SYNC_INVALID: instruction path is invalid"))?;
+ let temporary = parent.join(format!(".{filename}.{}.tmp", Uuid::new_v4()));
+ fs::write(&temporary, content.as_bytes())?;
+ fs::rename(&temporary, path).map_err(|error| {
+ let _ = fs::remove_file(&temporary);
+ anyhow::anyhow!("CONFIG_SYNC_IO: replace instruction file: {error}")
+ })?;
+ Ok(())
+}
+
+pub(crate) fn remove_instruction_file(path: &Path) -> Result<()> {
+ let Ok(metadata) = fs::symlink_metadata(path) else {
+ return Ok(());
+ };
+ if metadata.file_type().is_symlink() {
+ return Err(anyhow::anyhow!(
+ "CONFIG_SYNC_INVALID: instruction file is a symbolic link"
+ ));
+ }
+ if metadata.is_file() {
+ fs::remove_file(path)?;
+ }
+ Ok(())
+}
+
+fn capture_automation(
+ st: &mut AppState,
+ identities: &ProjectIdentityOverrides,
+) -> Result<Vec<PortableEntity>> {
+ let mut result = Vec::new();
+ for task in crate::scheduled::list_tasks(&st.db)? {
+ let mut payload = serde_json::to_value(&task)?;
+ strip_keys(
+ &mut payload,
+ &[
+ "createdAt",
+ "updatedAt",
+ "lastRunAt",
+ "nextRunAt",
+ "workspacePath",
+ "enabled",
+ ],
+ );
+ if let Some(workspace_path) = task.workspace_path.as_deref() {
+ if let Some(object) = payload.as_object_mut() {
+ let (project_id, group_id, root_position) =
+ project_scope(st, workspace_path, identities)?;
+ object.insert(
+ "workspaceProjectLogicalId".into(),
+ Value::String(project_id),
+ );
+ if let Some(group_id) = group_id {
+ object.insert("projectGroupLogicalId".into(), Value::String(group_id));
+ }
+ if let Some(position) = root_position {
+ object.insert("projectRootPosition".into(), json!(position));
+ }
+ }
+ }
+ result.push(entity(
+ DOMAIN_AUTOMATION,
+ format!("automation:{}", task.id),
+ task.title,
+ payload,
+ true,
+ true,
+ task.workspace_path.is_some(),
+ Vec::new(),
+ ));
+ }
+ Ok(result)
+}
+
+fn portable_plugin_payload(payload: &Value, fallback_id: &str) -> Value {
+ let mut portable = serde_json::Map::new();
+ if let Some(source) = payload.as_object() {
+ for key in [
+ "id",
+ "name",
+ "version",
+ "source",
+ "description",
+ "author",
+ "marketplace",
+ "autoUpdate",
+ ] {
+ if let Some(value) = source.get(key) {
+ portable.insert(key.to_string(), value.clone());
+ }
+ }
+ }
+ portable
+ .entry("id".to_string())
+ .or_insert_with(|| Value::String(fallback_id.to_string()));
+ Value::Object(portable)
+}
+
+fn capture_plugins(
+ st: &AppState,
+ plugin_intents: &BTreeMap<String, Value>,
+) -> Result<Vec<PortableEntity>> {
+ let mut result = Vec::new();
+ let mut seen = BTreeMap::new();
+ for plugin in st.plugins.list() {
+ if plugin.bundled {
+ continue;
+ }
+ let mut payload = serde_json::to_value(&plugin)?;
+ if let Some(object) = payload.as_object_mut() {
+ object.retain(|key, _| {
+ matches!(
+ key.as_str(),
+ "id" | "name"
+ | "version"
+ | "source"
+ | "description"
+ | "author"
+ | "marketplace"
+ | "autoUpdate"
+ )
+ });
+ }
+ result.push(entity(
+ DOMAIN_PLUGINS,
+ format!("plugin:{}", plugin.id),
+ plugin.name,
+ payload,
+ true,
+ false,
+ false,
+ Vec::new(),
+ ));
+ seen.insert(plugin.id, ());
+ }
+ for (plugin_id, payload) in plugin_intents {
+ if seen.contains_key(plugin_id) {
+ continue;
+ }
+ let label = payload
+ .get("name")
+ .and_then(Value::as_str)
+ .unwrap_or(plugin_id)
+ .to_string();
+ result.push(entity(
+ DOMAIN_PLUGINS,
+ format!("plugin:{plugin_id}"),
+ label,
+ portable_plugin_payload(payload, plugin_id),
+ true,
+ false,
+ false,
+ Vec::new(),
+ ));
+ }
+ Ok(result)
+}
+
+pub(crate) fn capture(
+ st: &mut AppState,
+ key: &VaultKey,
+ selection: &CategorySelection,
+ include_secrets: bool,
+ plugin_intents: &BTreeMap<String, Value>,
+ identities: &ProjectIdentityOverrides,
+) -> Result<LocalSnapshot> {
+ let mut snapshot = LocalSnapshot {
+ manifest: RevisionManifest {
+ format: "pi-desktop-config-revision".to_string(),
+ version: 1,
+ revision_id: uuid::Uuid::new_v4().to_string(),
+ parents: Vec::new(),
+ created_at: chrono::Utc::now().to_rfc3339(),
+ entities: Vec::new(),
+ resource_ids: Vec::new(),
+ },
+ resources: BTreeMap::new(),
+ };
+ if selection.is_selected(DOMAIN_APPLICATION) {
+ snapshot.manifest.entities.push(capture_application(st)?);
+ }
+ if selection.is_selected(DOMAIN_PROVIDERS) {
+ for mut provider in capture_providers(st)? {
+ if include_secrets {
+ let id = provider
+ .entity_id
+ .strip_prefix("provider:")
+ .unwrap_or_default();
+ if let Some(secret) = st
+ .secrets
+ .get(&crate::providers::secret_ref_for_provider(id))?
+ {
+ if let Some(object) = provider.payload.as_object_mut() {
+ object.insert("portableApiKey".into(), Value::String(secret));
+ }
+ provider.digest = digest_entity(
+ &provider.domain,
+ &provider.entity_id,
+ provider.deleted,
+ provider.requires_approval,
+ provider.secret_bearing,
+ provider.mapping_required,
+ &provider.payload,
+ &provider.resource_ids,
+ );
+ }
+ }
+ snapshot.manifest.entities.push(provider);
+ }
+ }
+ if selection.is_selected(DOMAIN_MCP) {
+ snapshot
+ .manifest
+ .entities
+ .extend(capture_mcp(st, selection, include_secrets, identities)?);
+ }
+ if selection.is_selected(DOMAIN_SKILLS) {
+ let (entities, resources) = capture_skills(st, key, selection, identities)?;
+ snapshot.manifest.entities.extend(entities);
+ snapshot.resources.extend(resources);
+ }
+ if selection.is_selected(DOMAIN_SUBAGENTS) {
+ let (entities, resources) = capture_subagents(st, key)?;
+ snapshot.manifest.entities.extend(entities);
+ snapshot.resources.extend(resources);
+ }
+ if selection.is_selected(DOMAIN_INSTRUCTIONS) {
+ snapshot
+ .manifest
+ .entities
+ .extend(capture_instructions(st, identities)?);
+ }
+ if selection.is_selected(DOMAIN_PROJECTS) {
+ snapshot
+ .manifest
+ .entities
+ .extend(capture_projects(st, identities)?);
+ }
+ if selection.is_selected(DOMAIN_PLUGINS) {
+ snapshot
+ .manifest
+ .entities
+ .extend(capture_plugins(st, plugin_intents)?);
+ }
+ if selection.is_selected(DOMAIN_AUTOMATION) {
+ snapshot
+ .manifest
+ .entities
+ .extend(capture_automation(st, identities)?);
+ }
+ if selection.is_selected(DOMAIN_MEMORY) {
+ snapshot
+ .manifest
+ .entities
+ .extend(capture_memory(st, identities)?);
+ }
+ snapshot.manifest.entities.sort_by(|left, right| {
+ left.domain
+ .cmp(&right.domain)
+ .then(left.entity_id.cmp(&right.entity_id))
+ });
+ snapshot.manifest.resource_ids = snapshot.resources.keys().cloned().collect();
+ Ok(snapshot)
+}
diff --git a/crates/host-core/src/config_sync/engine.rs b/crates/host-core/src/config_sync/engine.rs
new file mode 100644
index 000000000..def6f6d82
--- /dev/null
+++ b/crates/host-core/src/config_sync/engine.rs
@@ -0,0 +1,1378 @@
+use super::domains::{self, CategorySelection, LocalSnapshot, PortableEntity, RevisionManifest};
+use super::merge::{self, MergeConflict};
+use super::{
+ create_vault, decrypt_object, encrypt_object, rewrap_vault, unlock_vault, vault_key_b64,
+ vault_key_from_b64, VaultHeader, VaultKey, WebDavConfig, WebDavTransport,
+};
+use crate::agent_capabilities::CapabilityLevel;
+use crate::mcp_servers::McpServerInput;
+use crate::providers::{self, ProviderCreateInput, ProviderUpdateInput};
+use crate::state::AppState;
+use anyhow::{anyhow, bail, Context, Result};
+use chrono::Utc;
+use rusqlite::OptionalExtension;
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
+use std::collections::{BTreeMap, BTreeSet};
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+};
+use tokio::sync::{mpsc, Mutex};
+use uuid::Uuid;
+
+#[path = "apply.rs"]
+mod apply;
+#[path = "coordinator.rs"]
+mod coordinator;
+#[path = "handlers.rs"]
+mod handlers;
+#[path = "engine_history.rs"]
+mod history;
+#[path = "engine_remote.rs"]
+mod remote;
+#[cfg(test)]
+pub(crate) use apply::validate_application_references;
+pub(crate) use apply::{apply_bundle, recover_import_journal};
+pub(crate) use coordinator::{sync_if_enabled, sync_now};
+pub(crate) use handlers::{
+ approve, change_password, configure, disconnect, get_state, list_history, map_project, pause,
+ reject, restore, test, unlock,
+};
+use history::cleanup_history;
+use remote::{
+ ensure_remote_collections, object_path, publish_head, read_remote_head, read_remote_manifest,
+ read_remote_revision, revision_path, upload_snapshot, validate_remote_id,
+};
+
+const CONFIG_NS: &str = "configSync";
+const CONFIG_KEY: &str = "config";
+const WEBDAV_SECRET_REF: &str = "secret:config-sync:webdav-password";
+const FORMAT: &str = "pi-desktop-config-sync";
+const REVISION_FORMAT: &str = "pi-desktop-config-revision";
+const MAX_ENTITIES: usize = 4096;
+const MAX_RESOURCES: usize = 4096;
+const MAX_RETRIES: usize = 3;
+const MAX_HISTORY_SCAN: usize = 256;
+const MAX_RETAINED_REVISIONS: usize = 30;
+const HISTORY_GRACE_SECONDS: i64 = 60 * 60;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct StoredConfig {
+ pub format: String,
+ pub version: u32,
+ pub endpoint: String,
+ pub username: String,
+ pub directory: String,
+ pub device_label: String,
+ pub allow_insecure_http: bool,
+ pub categories: BTreeMap<String, bool>,
+ pub include_secrets: bool,
+ pub include_memory: bool,
+ pub automatic_sync: bool,
+ pub enabled: bool,
+ pub paused: bool,
+ pub vault_id: String,
+ pub vault_header: VaultHeader,
+ #[serde(default)]
+ pub last_run_at: Option<String>,
+ #[serde(default)]
+ pub last_success_at: Option<String>,
+ #[serde(default)]
+ pub last_revision_id: Option<String>,
+ #[serde(default)]
+ pub last_error: Option<String>,
+ #[serde(default)]
+ pub last_error_code: Option<String>,
+ #[serde(default)]
+ pub last_local_digest: Option<String>,
+ #[serde(default)]
+ pub local_change_seen_at: Option<String>,
+ #[serde(default)]
+ pub retry_count: u32,
+ #[serde(default)]
+ pub next_retry_at: Option<String>,
+ #[serde(default)]
+ pub project_mappings: BTreeMap<String, String>,
+ #[serde(default)]
+ pub project_group_mappings: BTreeMap<String, Vec<String>>,
+ #[serde(default)]
+ pub dismissed: BTreeMap<String, String>,
+ /// Approved plugin installation intent without plugin bytes or grants.
+ #[serde(default)]
+ pub plugin_intents: BTreeMap<String, Value>,
+ #[serde(default)]
+ pub recovery_points: Vec<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RemoteHead {
+ pub format: String,
+ pub version: u32,
+ pub revision_id: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct PendingApproval {
+ approval_id: String,
+ entity: PortableEntity,
+ reason: String,
+ #[serde(default)]
+ approved: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct PendingBundle {
+ manifest: RevisionManifest,
+ #[serde(default)]
+ local_before: Option<RevisionManifest>,
+ #[serde(default)]
+ resources: BTreeMap<String, Vec<u8>>,
+ approvals: Vec<PendingApproval>,
+ #[serde(default)]
+ conflicts: Vec<MergeConflict>,
+ #[serde(default = "default_journal_state")]
+ journal_state: String,
+ remote_revision_id: String,
+}
+
+fn default_journal_state() -> String {
+ "staged".into()
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PublicPendingApproval {
+ id: String,
+ domain: String,
+ entity_id: String,
+ label: String,
+ reason: String,
+ digest: String,
+ created_at: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ mapping_key: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PublicProjectMapping {
+ logical_id: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ path: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ paths: Option<Vec<String>>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PublicHistoryEntry {
+ revision_id: String,
+ created_at: String,
+ parent_revision_ids: Vec<String>,
+ entity_count: usize,
+ resource_count: usize,
+ current: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct RecoveryPoint {
+ format: String,
+ version: u32,
+ created_at: String,
+ base: Option<RevisionManifest>,
+ snapshot: LocalSnapshot,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PublicState {
+ configured: bool,
+ enabled: bool,
+ paused: bool,
+ locked: bool,
+ status: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ endpoint: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ username: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ directory: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ device_label: Option<String>,
+ categories: BTreeMap<String, bool>,
+ include_secrets: bool,
+ include_memory: bool,
+ automatic_sync: bool,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ last_run_at: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ last_success_at: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ last_error: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ last_revision_id: Option<String>,
+ pending_approvals: Vec<PublicPendingApproval>,
+ mappings: Vec<PublicProjectMapping>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ preview: Option<domains::PreviewCounts>,
+}
+
+fn default_categories() -> BTreeMap<String, bool> {
+ CategorySelection::all_selected().0
+}
+
+fn selection(config: &StoredConfig) -> CategorySelection {
+ let mut values = default_categories();
+ values.extend(config.categories.clone());
+ values.insert("credentials".to_string(), config.include_secrets);
+ values.insert(domains::DOMAIN_MEMORY.to_string(), config.include_memory);
+ CategorySelection(values)
+}
+
+fn identity_overrides(config: &StoredConfig) -> domains::ProjectIdentityOverrides {
+ domains::ProjectIdentityOverrides::from_mappings(
+ &config.project_mappings,
+ &config.project_group_mappings,
+ )
+}
+
+fn config_dir(st: &AppState) -> PathBuf {
+ st.data_dir.join("config-sync")
+}
+
+fn local_path(st: &AppState, name: &str) -> PathBuf {
+ config_dir(st).join(name)
+}
+
+fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
+ let parent = path
+ .parent()
+ .ok_or_else(|| anyhow!("config sync path has no parent"))?;
+ fs::create_dir_all(parent)?;
+ let name = path
+ .file_name()
+ .map(|value| value.to_string_lossy().to_string())
+ .unwrap_or_else(|| "state".into());
+ let temporary = parent.join(format!(".{name}.{}.tmp", Uuid::new_v4()));
+ fs::write(&temporary, bytes).with_context(|| format!("write {}", temporary.display()))?;
+ fs::rename(&temporary, path).with_context(|| format!("replace {}", path.display()))?;
+ Ok(())
+}
+
+fn persist_encrypted<T: Serialize>(
+ st: &AppState,
+ key: &VaultKey,
+ purpose: &str,
+ path: &Path,
+ value: &T,
+) -> Result<()> {
+ let plain = serde_json::to_vec(value)?;
+ let encrypted = encrypt_object(key, purpose, &keyed_vault_id(st)?, &plain)?;
+ atomic_write(path, &encrypted)
+}
+
+fn load_encrypted<T: for<'de> Deserialize<'de>>(
+ st: &AppState,
+ key: &VaultKey,
+ purpose: &str,
+ path: &Path,
+) -> Result<Option<T>> {
+ if !path.exists() {
+ return Ok(None);
+ }
+ let bytes = fs::read(path).with_context(|| format!("read {}", path.display()))?;
+ if bytes.len() > 64 * 1024 * 1024 {
+ bail!("CONFIG_SYNC_LIMIT_EXCEEDED: local sync state is too large");
+ }
+ let plain = decrypt_object(key, purpose, &keyed_vault_id(st)?, &bytes)?;
+ Ok(Some(
+ serde_json::from_slice(&plain).context("decode local sync state")?,
+ ))
+}
+
+fn keyed_vault_id(st: &AppState) -> Result<String> {
+ let config =
+ load_config(st)?.ok_or_else(|| anyhow!("CONFIG_SYNC_LOCKED: sync is not configured"))?;
+ Ok(config.vault_id)
+}
+
+fn load_config(st: &AppState) -> Result<Option<StoredConfig>> {
+ let Some(value) = st.db.kv_get(CONFIG_NS, CONFIG_KEY)? else {
+ return Ok(None);
+ };
+ let config: StoredConfig =
+ serde_json::from_value(value).context("decode config sync settings")?;
+ if config.format != FORMAT || config.version != 1 {
+ bail!("CONFIG_SYNC_UNSUPPORTED: unsupported local sync settings");
+ }
+ Ok(Some(config))
+}
+
+fn save_config(st: &AppState, config: &StoredConfig) -> Result<()> {
+ st.db
+ .kv_set(CONFIG_NS, CONFIG_KEY, &serde_json::to_value(config)?)
+}
+
+fn secret_ref_for_vault(vault_id: &str) -> String {
+ format!("secret:config-sync:{vault_id}:vault-key")
+}
+
+fn local_vault_key(st: &AppState, config: &StoredConfig) -> Result<Option<VaultKey>> {
+ let Some(encoded) = st.secrets.get(&secret_ref_for_vault(&config.vault_id))? else {
+ return Ok(None);
+ };
+ Ok(Some(vault_key_from_b64(&encoded)?))
+}
+
+fn webdav_password(st: &AppState, config: &StoredConfig) -> Result<String> {
+ if config.username.is_empty() {
+ return Ok(String::new());
+ }
+ st.secrets
+ .get(WEBDAV_SECRET_REF)?
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_LOCKED: WebDAV app password is not available"))
+}
+
+fn transport_with_password(config: &StoredConfig, password: String) -> Result<WebDavTransport> {
+ WebDavTransport::new(&WebDavConfig {
+ endpoint: config.endpoint.clone(),
+ username: config.username.clone(),
+ password,
+ directory: config.directory.clone(),
+ allow_insecure_http: config.allow_insecure_http,
+ })
+}
+
+fn entity_key(entity: &PortableEntity) -> (String, String) {
+ (entity.domain.clone(), entity.entity_id.clone())
+}
+
+fn approval_key(entity: &PortableEntity) -> String {
+ format!("{}:{}", entity.domain, entity.entity_id)
+}
+
+fn conflict_base_id(entity_id: &str) -> Option<&str> {
+ entity_id
+ .strip_suffix(":local")
+ .or_else(|| entity_id.strip_suffix(":remote"))
+}
+
+fn manifest_map(manifest: Option<&RevisionManifest>) -> BTreeMap<(String, String), PortableEntity> {
+ manifest
+ .map(|value| {
+ value
+ .entities
+ .iter()
+ .cloned()
+ .map(|entity| (entity_key(&entity), entity))
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+fn logical_entity_key(entity: &PortableEntity) -> (String, String) {
+ (
+ entity.domain.clone(),
+ conflict_base_id(&entity.entity_id)
+ .unwrap_or(&entity.entity_id)
+ .to_string(),
+ )
+}
+
+fn logical_manifest_map(
+ manifest: Option<&RevisionManifest>,
+) -> BTreeMap<(String, String), PortableEntity> {
+ manifest
+ .map(|value| {
+ value
+ .entities
+ .iter()
+ .cloned()
+ .map(|entity| (logical_entity_key(&entity), entity))
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+fn selected_manifests_equal(
+ left: Option<&RevisionManifest>,
+ right: Option<&RevisionManifest>,
+ selection: &CategorySelection,
+) -> bool {
+ let left = manifest_map(left);
+ let right = manifest_map(right);
+ let keys = left
+ .keys()
+ .chain(right.keys())
+ .cloned()
+ .collect::<BTreeSet<_>>();
+ keys.into_iter().all(|(domain, entity_id)| {
+ !selection.is_selected(&domain)
+ || left.get(&(domain.clone(), entity_id.clone())) == right.get(&(domain, entity_id))
+ })
+}
+
+fn approval_reason(entity: &PortableEntity, conflict: bool, new_device: bool) -> String {
+ if conflict {
+ "conflict".into()
+ } else if new_device {
+ "newDevice".into()
+ } else if entity.mapping_required {
+ "mapping".into()
+ } else if entity.secret_bearing {
+ "dependency".into()
+ } else {
+ "securityChange".into()
+ }
+}
+
+fn build_pending(
+ config: &StoredConfig,
+ base: Option<&RevisionManifest>,
+ local: &RevisionManifest,
+ remote: Option<&RevisionManifest>,
+ merged: &merge::MergeResult,
+ remote_revision_id: &str,
+ resources: BTreeMap<String, Vec<u8>>,
+) -> PendingBundle {
+ let base_map = manifest_map(base);
+ let local_map = manifest_map(Some(local));
+ let remote_map = manifest_map(remote);
+ let selected = selection(config);
+ let conflict_ids: BTreeSet<(String, String)> = merged
+ .conflicts
+ .iter()
+ .map(|conflict| (conflict.domain.clone(), conflict.entity_id.clone()))
+ .collect();
+ let mut approvals = Vec::new();
+ for entity in &merged.entities {
+ if !selected.is_selected(&entity.domain) {
+ continue;
+ }
+ let key = entity_key(entity);
+ let remote_entity = remote_map.get(&key);
+ let remote_changed = remote_entity.is_some_and(|remote| {
+ base_map
+ .get(&key)
+ .is_none_or(|base| base.digest != remote.digest)
+ });
+ let new_device = base.is_none() && remote_entity.is_some();
+ let local_same = local_map
+ .get(&key)
+ .is_some_and(|local| local.digest == entity.digest);
+ let conflict = entity.entity_id.ends_with(":local")
+ || entity.entity_id.ends_with(":remote")
+ || conflict_ids.contains(&key);
+ if (remote_changed || conflict)
+ && !local_same
+ && (entity.requires_approval || entity.mapping_required || conflict)
+ && config.dismissed.get(&approval_key(entity)) != Some(&entity.digest)
+ {
+ approvals.push(PendingApproval {
+ approval_id: Uuid::new_v4().to_string(),
+ entity: entity.clone(),
+ reason: approval_reason(entity, conflict, new_device),
+ approved: false,
+ });
+ }
+ }
+ PendingBundle {
+ manifest: RevisionManifest {
+ format: REVISION_FORMAT.to_string(),
+ version: 1,
+ revision_id: remote_revision_id.to_string(),
+ parents: vec![],
+ created_at: Utc::now().to_rfc3339(),
+ entities: merged.entities.clone(),
+ resource_ids: resources.keys().cloned().collect(),
+ },
+ local_before: Some(local.clone()),
+ resources,
+ approvals,
+ conflicts: merged.conflicts.clone(),
+ journal_state: default_journal_state(),
+ remote_revision_id: remote_revision_id.to_string(),
+ }
+}
+
+fn public_pending(bundle: Option<&PendingBundle>) -> Vec<PublicPendingApproval> {
+ bundle
+ .map(|bundle| {
+ bundle
+ .approvals
+ .iter()
+ .filter(|item| !item.approved)
+ .map(|item| PublicPendingApproval {
+ id: item.approval_id.clone(),
+ domain: item.entity.domain.clone(),
+ entity_id: item.entity.entity_id.clone(),
+ label: item.entity.label.clone(),
+ reason: item.reason.clone(),
+ digest: item.entity.digest.clone(),
+ created_at: Utc::now().to_rfc3339(),
+ mapping_key: item
+ .entity
+ .payload
+ .get("projectGroupLogicalId")
+ .or_else(|| item.entity.payload.get("projectLogicalId"))
+ .or_else(|| item.entity.payload.get("workspaceProjectLogicalId"))
+ .or_else(|| item.entity.payload.get("logicalId"))
+ .and_then(Value::as_str)
+ .map(str::to_string),
+ })
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+fn public_mappings(config: &StoredConfig) -> Vec<PublicProjectMapping> {
+ let mut mappings = config
+ .project_mappings
+ .iter()
+ .map(|(logical_id, path)| {
+ (
+ logical_id.clone(),
+ PublicProjectMapping {
+ logical_id: logical_id.clone(),
+ path: Some(path.clone()),
+ paths: None,
+ },
+ )
+ })
+ .collect::<BTreeMap<_, _>>();
+ for (logical_id, paths) in &config.project_group_mappings {
+ mappings.insert(
+ logical_id.clone(),
+ PublicProjectMapping {
+ logical_id: logical_id.clone(),
+ path: (paths.len() == 1).then(|| paths[0].clone()),
+ paths: (paths.len() > 1).then(|| paths.clone()),
+ },
+ );
+ }
+ mappings.into_values().collect()
+}
+
+fn status(
+ config: Option<&StoredConfig>,
+ key: Option<&VaultKey>,
+ pending: Option<&PendingBundle>,
+ syncing: bool,
+ local_changes_pending: bool,
+) -> String {
+ let Some(config) = config else {
+ return "notConfigured".into();
+ };
+ if config.paused {
+ return "paused".into();
+ }
+ if key.is_none() {
+ return "locked".into();
+ }
+ if syncing {
+ return "syncing".into();
+ }
+ if pending.is_some_and(|value| !value.approvals.is_empty()) {
+ if pending.is_some_and(|value| !value.conflicts.is_empty()) {
+ return "conflict".into();
+ }
+ return "awaitingActivation".into();
+ }
+ if config.last_error_code.as_deref() == Some("CONFLICT") {
+ return "conflict".into();
+ }
+ if config.last_error_code.as_deref() == Some("UNSUPPORTED_SERVER") {
+ return "unsupportedServer".into();
+ }
+ if config.last_error_code.as_deref() == Some("OFFLINE") {
+ return "offline".into();
+ }
+ if config.last_error.is_some() {
+ return "error".into();
+ }
+ if local_changes_pending {
+ return "localChangesPending".into();
+ }
+ if config.last_success_at.is_some() {
+ "upToDate".into()
+ } else {
+ "localChangesPending".into()
+ }
+}
+
+pub fn public_state(st: &mut AppState) -> Result<Value> {
+ let mut config = load_config(st)?;
+ let Some(initial_config) = config.as_ref() else {
+ return Ok(serde_json::to_value(PublicState {
+ configured: false,
+ enabled: false,
+ paused: false,
+ locked: false,
+ status: "notConfigured".into(),
+ endpoint: None,
+ username: None,
+ directory: None,
+ device_label: None,
+ categories: default_categories(),
+ include_secrets: false,
+ include_memory: false,
+ automatic_sync: false,
+ last_run_at: None,
+ last_success_at: None,
+ last_error: None,
+ last_revision_id: None,
+ pending_approvals: vec![],
+ mappings: vec![],
+ preview: None,
+ })?);
+ };
+ let key = local_vault_key(st, initial_config)?;
+ let mut pending = key
+ .as_ref()
+ .map(|key| load_pending(st, key))
+ .transpose()?
+ .flatten();
+ if let (Some(key), Some(bundle)) = (key.as_ref(), pending.as_ref()) {
+ if bundle.journal_state == "applying" {
+ let mut recovered = config
+ .take()
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: sync configuration disappeared"))?;
+ if let Err(error) = recover_import_journal(st, &mut recovered, key, bundle) {
+ mark_error(&mut recovered, &error);
+ save_config(st, &recovered)?;
+ }
+ config = Some(recovered);
+ pending = load_pending(st, key)?;
+ }
+ }
+ let config_ref = config
+ .as_ref()
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: sync configuration disappeared"))?;
+ let syncing = st.config_sync_in_progress.load(Ordering::Relaxed);
+ let preview = if let Some(bundle) = pending.as_ref() {
+ let snapshot = LocalSnapshot {
+ manifest: bundle.manifest.clone(),
+ resources: bundle.resources.clone(),
+ };
+ Some(domains::preview(&snapshot, &selection(config_ref)))
+ } else if let Some(key) = key.as_ref() {
+ let snapshot = domains::capture(
+ st,
+ key,
+ &selection(config_ref),
+ config_ref.include_secrets,
+ &config_ref.plugin_intents,
+ &identity_overrides(config_ref),
+ )?;
+ Some(domains::preview(&snapshot, &selection(config_ref)))
+ } else {
+ None
+ };
+ let local_changes_pending = if syncing {
+ false
+ } else {
+ match (
+ key.as_ref(),
+ config_ref.last_success_at.as_ref(),
+ config_ref.last_local_digest.as_deref(),
+ ) {
+ (Some(key), Some(_), Some(expected)) => {
+ let snapshot = domains::capture(
+ st,
+ key,
+ &selection(config_ref),
+ config_ref.include_secrets,
+ &config_ref.plugin_intents,
+ &identity_overrides(config_ref),
+ )?;
+ domains::snapshot_digest(&snapshot) != expected
+ }
+ _ => false,
+ }
+ };
+ Ok(serde_json::to_value(PublicState {
+ configured: true,
+ enabled: config_ref.enabled,
+ paused: config_ref.paused,
+ locked: key.is_none(),
+ status: status(
+ Some(config_ref),
+ key.as_ref(),
+ pending.as_ref(),
+ syncing,
+ local_changes_pending,
+ ),
+ endpoint: Some(config_ref.endpoint.clone()),
+ username: Some(config_ref.username.clone()),
+ directory: Some(config_ref.directory.clone()),
+ device_label: Some(config_ref.device_label.clone()),
+ categories: config_ref.categories.clone(),
+ include_secrets: config_ref.include_secrets,
+ include_memory: config_ref.include_memory,
+ automatic_sync: config_ref.automatic_sync,
+ last_run_at: config_ref.last_run_at.clone(),
+ last_success_at: config_ref.last_success_at.clone(),
+ last_error: config_ref.last_error.clone(),
+ last_revision_id: config_ref.last_revision_id.clone(),
+ pending_approvals: public_pending(pending.as_ref()),
+ mappings: public_mappings(config_ref),
+ preview,
+ })?)
+}
+
+fn parse_category_selection(
+ value: Option<&Value>,
+ existing: Option<&BTreeMap<String, bool>>,
+ include_memory: bool,
+) -> BTreeMap<String, bool> {
+ let mut selected = existing.cloned().unwrap_or_else(default_categories);
+ if let Some(object) = value.and_then(Value::as_object) {
+ for (key, value) in object {
+ if domains::ALL_DOMAINS.contains(&key.as_str()) && value.is_boolean() {
+ selected.insert(key.clone(), value.as_bool().unwrap_or(true));
+ }
+ }
+ }
+ selected.insert("credentials".into(), false);
+ selected.insert(domains::DOMAIN_MEMORY.into(), include_memory);
+ selected
+}
+
+fn config_from_input(
+ existing: Option<&StoredConfig>,
+ input: &Value,
+ header: VaultHeader,
+) -> Result<StoredConfig> {
+ let endpoint = input
+ .get("endpoint")
+ .and_then(Value::as_str)
+ .or_else(|| existing.map(|value| value.endpoint.as_str()))
+ .unwrap_or_default()
+ .trim()
+ .to_string();
+ let username = input
+ .get("username")
+ .and_then(Value::as_str)
+ .or_else(|| existing.map(|value| value.username.as_str()))
+ .unwrap_or_default()
+ .trim()
+ .to_string();
+ let directory = input
+ .get("directory")
+ .and_then(Value::as_str)
+ .or_else(|| existing.map(|value| value.directory.as_str()))
+ .unwrap_or_default()
+ .trim()
+ .to_string();
+ let device_label = input
+ .get("deviceLabel")
+ .and_then(Value::as_str)
+ .or_else(|| existing.map(|value| value.device_label.as_str()))
+ .unwrap_or("This device")
+ .trim()
+ .to_string();
+ if endpoint.is_empty() || device_label.is_empty() {
+ bail!("CONFIG_SYNC_INVALID: endpoint and device label are required");
+ }
+ let include_memory = input
+ .get("includeMemory")
+ .and_then(Value::as_bool)
+ .or_else(|| existing.map(|value| value.include_memory))
+ .unwrap_or(false);
+ let include_secrets = input
+ .get("includeSecrets")
+ .and_then(Value::as_bool)
+ .or_else(|| existing.map(|value| value.include_secrets))
+ .unwrap_or(false);
+ let mut categories = parse_category_selection(
+ input.get("categories"),
+ existing.map(|value| &value.categories),
+ include_memory,
+ );
+ categories.insert("credentials".into(), include_secrets);
+ Ok(StoredConfig {
+ format: FORMAT.into(),
+ version: 1,
+ endpoint,
+ username,
+ directory,
+ device_label,
+ allow_insecure_http: input
+ .get("allowInsecureHttp")
+ .and_then(Value::as_bool)
+ .or_else(|| existing.map(|value| value.allow_insecure_http))
+ .unwrap_or(false),
+ categories,
+ include_secrets,
+ include_memory,
+ automatic_sync: input
+ .get("automaticSync")
+ .and_then(Value::as_bool)
+ .or_else(|| existing.map(|value| value.automatic_sync))
+ .unwrap_or(true),
+ enabled: true,
+ paused: false,
+ vault_id: header.vault_id.clone(),
+ vault_header: header,
+ last_run_at: existing.and_then(|value| value.last_run_at.clone()),
+ last_success_at: existing.and_then(|value| value.last_success_at.clone()),
+ last_revision_id: existing.and_then(|value| value.last_revision_id.clone()),
+ last_error: None,
+ last_error_code: None,
+ last_local_digest: existing.and_then(|value| value.last_local_digest.clone()),
+ local_change_seen_at: existing.and_then(|value| value.local_change_seen_at.clone()),
+ retry_count: existing.map(|value| value.retry_count).unwrap_or(0),
+ next_retry_at: existing.and_then(|value| value.next_retry_at.clone()),
+ project_mappings: existing
+ .map(|value| value.project_mappings.clone())
+ .unwrap_or_default(),
+ project_group_mappings: existing
+ .map(|value| value.project_group_mappings.clone())
+ .unwrap_or_default(),
+ dismissed: existing
+ .map(|value| value.dismissed.clone())
+ .unwrap_or_default(),
+ plugin_intents: existing
+ .map(|value| value.plugin_intents.clone())
+ .unwrap_or_default(),
+ recovery_points: existing
+ .map(|value| value.recovery_points.clone())
+ .unwrap_or_default(),
+ })
+}
+
+fn mark_error(config: &mut StoredConfig, error: &anyhow::Error) {
+ let message = error.to_string();
+ config.last_error_code = if message.starts_with("CONFIG_SYNC_UNSUPPORTED") {
+ Some("UNSUPPORTED_SERVER".into())
+ } else if message.starts_with("CONFIG_SYNC_CONFLICT") {
+ Some("CONFLICT".into())
+ } else if message.starts_with("CONFIG_SYNC_CRYPTO")
+ || message.contains("401 Unauthorized")
+ || message.contains("403 Forbidden")
+ || message.contains("authentication")
+ {
+ Some("AUTH_REQUIRED".into())
+ } else if super::remote_error_is_offline(error) {
+ Some("OFFLINE".into())
+ } else if message.starts_with("CONFIG_SYNC_LOCKED") {
+ Some("LOCKED".into())
+ } else {
+ Some("ERROR".into())
+ };
+ config.last_error = Some(message.chars().take(500).collect());
+}
+
+fn clear_error(config: &mut StoredConfig) {
+ config.last_error = None;
+ config.last_error_code = None;
+ config.retry_count = 0;
+ config.next_retry_at = None;
+}
+
+fn retry_deadline(config: &StoredConfig) -> Option<chrono::DateTime<Utc>> {
+ config
+ .next_retry_at
+ .as_deref()
+ .and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok())
+ .map(|value| value.with_timezone(&Utc))
+}
+
+fn load_base(st: &AppState, key: &VaultKey) -> Result<Option<RevisionManifest>> {
+ load_encrypted(st, key, "local-base", &local_path(st, "base.bin"))
+}
+
+fn load_pending(st: &AppState, key: &VaultKey) -> Result<Option<PendingBundle>> {
+ load_encrypted(st, key, "local-pending", &local_path(st, "pending.bin"))
+}
+
+fn store_pending(st: &AppState, key: &VaultKey, pending: &PendingBundle) -> Result<()> {
+ persist_encrypted(
+ st,
+ key,
+ "local-pending",
+ &local_path(st, "pending.bin"),
+ pending,
+ )
+}
+
+fn clear_pending(st: &AppState) -> Result<()> {
+ let path = local_path(st, "pending.bin");
+ if path.exists() {
+ fs::remove_file(path)?;
+ }
+ Ok(())
+}
+
+fn store_base(st: &AppState, key: &VaultKey, manifest: &RevisionManifest) -> Result<()> {
+ persist_encrypted(st, key, "local-base", &local_path(st, "base.bin"), manifest)
+}
+
+fn recovery_path(st: &AppState, filename: &str) -> Result<PathBuf> {
+ if !filename.starts_with("recovery-")
+ || !filename.ends_with(".bin")
+ || filename.contains('/')
+ || filename.contains('\\')
+ || filename.contains("..")
+ {
+ bail!("CONFIG_SYNC_INVALID: local recovery filename is unsafe");
+ }
+ Ok(local_path(st, filename))
+}
+
+fn create_recovery_point(
+ st: &AppState,
+ config: &mut StoredConfig,
+ key: &VaultKey,
+ base: Option<RevisionManifest>,
+ snapshot: LocalSnapshot,
+) -> Result<()> {
+ let filename = format!("recovery-{}.bin", Uuid::new_v4());
+ let point = RecoveryPoint {
+ format: "pi-desktop-config-recovery".into(),
+ version: 1,
+ created_at: Utc::now().to_rfc3339(),
+ base,
+ snapshot,
+ };
+ persist_encrypted(
+ st,
+ key,
+ "local-recovery",
+ &recovery_path(st, &filename)?,
+ &point,
+ )?;
+ config.recovery_points.push(filename);
+ while config.recovery_points.len() > MAX_RETAINED_REVISIONS {
+ let old = config.recovery_points.remove(0);
+ if let Ok(path) = recovery_path(st, &old) {
+ if path.exists() {
+ fs::remove_file(path)?;
+ }
+ }
+ }
+ Ok(())
+}
+
+fn send_state_notification(tx: &mpsc::UnboundedSender<String>, st: &mut AppState) {
+ if let Ok(value) = public_state(st) {
+ let note = json!({ "jsonrpc": "2.0", "method": "configSync.changed", "params": value });
+ if let Ok(raw) = serde_json::to_string(&note) {
+ let _ = tx.send(format!("{raw}\n"));
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::config_sync::domains::{
+ DOMAIN_APPLICATION, DOMAIN_MCP, DOMAIN_PROJECTS, DOMAIN_PROVIDERS, DOMAIN_SKILLS,
+ };
+ use crate::mcp_servers::McpServerInput;
+ use crate::user_skills::UserSkillInput;
+ use std::sync::Arc;
+ use tokio::sync::mpsc;
+
+ fn entity(entity_id: &str) -> PortableEntity {
+ PortableEntity {
+ domain: "providers".into(),
+ entity_id: entity_id.into(),
+ label: "Provider".into(),
+ deleted: false,
+ requires_approval: true,
+ secret_bearing: false,
+ mapping_required: false,
+ digest: "digest".into(),
+ payload: json!({}),
+ resource_ids: Vec::new(),
+ }
+ }
+
+ #[test]
+ fn conflict_candidates_use_the_original_logical_entity_key() {
+ let manifest = RevisionManifest {
+ format: REVISION_FORMAT.into(),
+ version: 1,
+ revision_id: "revision".into(),
+ parents: Vec::new(),
+ created_at: String::new(),
+ entities: vec![entity("provider:one:remote")],
+ resource_ids: Vec::new(),
+ };
+
+ let mapped = logical_manifest_map(Some(&manifest));
+ assert!(mapped.contains_key(&("providers".into(), "provider:one".into())));
+ assert!(!mapped.contains_key(&("providers".into(), "provider:one:remote".into())));
+ }
+
+ #[test]
+ fn opted_out_remote_changes_do_not_look_like_local_changes() {
+ let base = RevisionManifest {
+ format: REVISION_FORMAT.into(),
+ version: 1,
+ revision_id: "base".into(),
+ parents: Vec::new(),
+ created_at: String::new(),
+ entities: vec![entity("provider:one")],
+ resource_ids: Vec::new(),
+ };
+ let mut remote_entity = entity("provider:one");
+ remote_entity.payload["name"] = Value::String("Remote edit".into());
+ let remote = RevisionManifest {
+ entities: vec![remote_entity],
+ revision_id: "remote".into(),
+ ..base.clone()
+ };
+ let mut selection = CategorySelection::default();
+ selection.0.insert(DOMAIN_PROVIDERS.into(), false);
+ assert!(selected_manifests_equal(
+ Some(&base),
+ Some(&remote),
+ &selection
+ ));
+ }
+
+ #[test]
+ fn application_references_missing_provider_as_a_deferred_dependency() {
+ let data_dir = tempfile::tempdir().expect("data directory");
+ let state = AppState::open(data_dir.path()).expect("state");
+ let error = validate_application_references(
+ &state,
+ &json!({ "defaultProviderId": "provider-from-remote" }),
+ )
+ .expect_err("missing provider should be staged");
+ assert!(error
+ .to_string()
+ .starts_with("CONFIG_SYNC_DEPENDENCY: defaultProviderId"));
+ }
+
+ fn pending_approvals(value: &Value) -> Vec<(String, String, String)> {
+ value
+ .get("pendingApprovals")
+ .and_then(Value::as_array)
+ .into_iter()
+ .flatten()
+ .map(|item| {
+ (
+ item.get("id")
+ .and_then(Value::as_str)
+ .expect("approval id")
+ .to_string(),
+ item.get("digest")
+ .and_then(Value::as_str)
+ .expect("approval digest")
+ .to_string(),
+ item.get("domain")
+ .and_then(Value::as_str)
+ .expect("approval domain")
+ .to_string(),
+ )
+ })
+ .collect()
+ }
+
+ async fn configure_test_device(
+ data_dir: &Path,
+ endpoint: &str,
+ ) -> Result<Arc<Mutex<AppState>>> {
+ let state = Arc::new(Mutex::new(AppState::open(data_dir)?));
+ configure(
+ state.clone(),
+ json!({
+ "endpoint": endpoint,
+ "username": "",
+ "appPassword": "",
+ "directory": "config-sync-test",
+ "deviceLabel": "test-device",
+ "backupPassword": "portable-backup-password",
+ "allowInsecureHttp": true,
+ "categories": {
+ "application": true,
+ "providers": true,
+ "credentials": true,
+ "mcp": true,
+ "skills": true,
+ "projects": true,
+ },
+ "includeSecrets": true,
+ "automaticSync": false,
+ }),
+ )
+ .await?;
+ Ok(state)
+ }
+
+ #[tokio::test]
+ async fn two_devices_sync_credentials_capabilities_and_disjoint_edit() -> Result<()> {
+ let fixture = crate::config_sync::transport::tests::fixture(false).await;
+ let device_a_dir = tempfile::tempdir()?;
+ let device_b_dir = tempfile::tempdir()?;
+ let device_a = configure_test_device(device_a_dir.path(), &fixture.endpoint).await?;
+ let device_b = configure_test_device(device_b_dir.path(), &fixture.endpoint).await?;
+ let project_a = device_a_dir.path().join("project");
+ let project_b = device_b_dir.path().join("project");
+ std::fs::create_dir_all(&project_a)?;
+ std::fs::create_dir_all(&project_b)?;
+ let project_a = project_a.canonicalize()?;
+ let project_b = project_b.canonicalize()?;
+
+ let provider_id = {
+ let mut state = device_a.lock().await;
+ state
+ .db
+ .ensure_project(&project_a.to_string_lossy(), false)?;
+ let provider = crate::providers::create_provider(
+ &state.db,
+ &state.secrets,
+ serde_json::from_value(json!({
+ "name": "Portable provider",
+ "vendorKey": "portable-test",
+ "type": "openai_compatible",
+ "protocol": "openai_compatible",
+ "baseUrl": "https://provider.example.test/v1",
+ "authKind": "api_key_and_base_url",
+ "secretValue": "portable-api-key",
+ "models": [{
+ "id": "portable-model",
+ "alias": "Portable",
+ "contextWindow": 128000,
+ "maxTokens": 4096,
+ "thinkingLevels": []
+ }]
+ }))?,
+ )?;
+ state
+ .db
+ .set_setting("app", &json!({ "theme": "light", "language": "en" }))?;
+ state.mcp_servers.upsert(McpServerInput {
+ id: "portable-server".into(),
+ label: Some("Portable MCP".into()),
+ level: Some("project".into()),
+ project_path: Some(project_a.to_string_lossy().into_owned()),
+ transport: Some("stdio".into()),
+ command: Some("portable-mcp".into()),
+ args: Some(vec!["--safe".into()]),
+ enabled: Some(true),
+ ..McpServerInput::default()
+ })?;
+ state.user_skills.create(UserSkillInput {
+ id: Some("portable-skill".into()),
+ name: Some("Portable Skill".into()),
+ level: Some("project".into()),
+ project_path: Some(project_a.to_string_lossy().into_owned()),
+ body: Some("Use the portable project workflow.".into()),
+ enabled: Some(true),
+ ..UserSkillInput::default()
+ })?;
+ provider.id
+ };
+
+ {
+ let mut state = device_a.lock().await;
+ let config = load_config(&state)?.expect("configured device");
+ let key = local_vault_key(&state, &config)?.expect("unlocked device");
+ let snapshot = domains::capture(
+ &mut state,
+ &key,
+ &selection(&config),
+ config.include_secrets,
+ &config.plugin_intents,
+ &identity_overrides(&config),
+ )?;
+ let captured = snapshot
+ .manifest
+ .entities
+ .iter()
+ .map(|entity| entity.domain.as_str())
+ .collect::<std::collections::BTreeSet<_>>();
+ assert!(
+ captured.contains(DOMAIN_PROVIDERS),
+ "captured: {captured:?}"
+ );
+ assert!(captured.contains(DOMAIN_MCP), "captured: {captured:?}");
+ assert!(captured.contains(DOMAIN_SKILLS), "captured: {captured:?}");
+ assert!(captured.contains(DOMAIN_PROJECTS), "captured: {captured:?}");
+ }
+
+ let (tx, _rx) = mpsc::unbounded_channel();
+ let initial_a_state = sync_now(device_a.clone(), tx.clone()).await?;
+ assert!(pending_approvals(&initial_a_state).is_empty());
+ {
+ let state = device_a.lock().await;
+ let config = load_config(&state)?.expect("configured device");
+ let key = local_vault_key(&state, &config)?.expect("unlocked device");
+ assert!(load_pending(&state, &key)?.is_none());
+ }
+ {
+ let state = device_b.lock().await;
+ let config = load_config(&state)?.expect("configured device");
+ let key = local_vault_key(&state, &config)?.expect("unlocked device");
+ let transport = transport_with_password(&config, String::new())?;
+ let (head, _) = read_remote_head(&transport, &config, &key)
+ .await?
+ .expect("remote head");
+ let (remote, _) =
+ read_remote_revision(&transport, &config, &key, &head.revision_id).await?;
+ assert!(!remote.entities.is_empty(), "remote entities missing");
+ assert!(
+ load_base(&state, &key)?.is_none(),
+ "device B unexpectedly has base"
+ );
+ assert!(
+ remote
+ .entities
+ .iter()
+ .any(|entity| entity.domain == DOMAIN_PROVIDERS && entity.requires_approval),
+ "remote provider approval flag missing: {:?}",
+ remote
+ .entities
+ .iter()
+ .map(|entity| (&entity.domain, entity.requires_approval))
+ .collect::<Vec<_>>()
+ );
+ }
+ let received = sync_now(device_b.clone(), tx.clone()).await?;
+ assert!(!pending_approvals(&received).is_empty());
+ {
+ let state = device_b.lock().await;
+ state
+ .db
+ .set_setting("app", &json!({ "theme": "dark", "language": "en" }))?;
+ }
+ let after_unapproved_edit = sync_now(device_b.clone(), tx.clone()).await?;
+ assert!(!pending_approvals(&after_unapproved_edit).is_empty());
+ assert_eq!(
+ device_b
+ .lock()
+ .await
+ .db
+ .get_setting("app")?
+ .and_then(|value| {
+ value
+ .get("theme")
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ }),
+ Some("dark".into())
+ );
+ let initial_approvals = pending_approvals(&after_unapproved_edit);
+ let domains = initial_approvals
+ .iter()
+ .map(|(_, _, domain)| domain.as_str())
+ .collect::<std::collections::BTreeSet<_>>();
+ assert!(domains.contains(DOMAIN_PROVIDERS), "domains: {domains:?}");
+ assert!(domains.contains(DOMAIN_MCP), "domains: {domains:?}");
+ assert!(domains.contains(DOMAIN_SKILLS), "domains: {domains:?}");
+ assert!(domains.contains(DOMAIN_PROJECTS), "domains: {domains:?}");
+ let mapping_key = received
+ .get("pendingApprovals")
+ .and_then(Value::as_array)
+ .and_then(|items| {
+ items.iter().find_map(|item| {
+ item.get("mappingKey")
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ })
+ })
+ .expect("project mapping approval");
+ map_project(
+ device_b.clone(),
+ json!({
+ "logicalId": mapping_key,
+ "paths": [project_b.to_string_lossy()]
+ }),
+ )
+ .await?;
+
+ for (approval_id, digest, domain) in initial_approvals {
+ let result = approve(
+ device_b.clone(),
+ json!({ "approvalId": &approval_id, "digest": &digest }),
+ tx.clone(),
+ )
+ .await;
+ assert!(
+ result.is_ok(),
+ "approval failed id={approval_id} domain={domain}: {result:?}"
+ );
+ }
+ let device_b_state = get_state(device_b.clone()).await?;
+ assert!(pending_approvals(&device_b_state).is_empty());
+ let repeated_b_state = sync_now(device_b.clone(), tx.clone()).await?;
+ assert!(pending_approvals(&repeated_b_state).is_empty());
+ {
+ let mut state = device_b.lock().await;
+ let provider = crate::providers::get_provider(&state.db, &state.secrets, &provider_id)?
+ .expect("provider imported");
+ assert!(provider.has_secret);
+ assert!(state
+ .mcp_servers
+ .list(CapabilityLevel::Project, Some(&project_b.to_string_lossy()),)?
+ .iter()
+ .any(|record| record.id == "portable-server"));
+ assert!(state
+ .user_skills
+ .list(CapabilityLevel::Project, Some(&project_b.to_string_lossy()),)?
+ .iter()
+ .any(|record| record.id == "portable-skill"));
+ assert_eq!(
+ state.db.get_setting("app")?.and_then(|value| {
+ value
+ .get("theme")
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ }),
+ Some("dark".into())
+ );
+ }
+
+ {
+ let state = device_b.lock().await;
+ state
+ .db
+ .set_setting("app", &json!({ "theme": "light", "language": "en" }))?;
+ }
+ sync_now(device_b.clone(), tx.clone()).await?;
+ {
+ let state = device_b.lock().await;
+ let config = load_config(&state)?.expect("configured device");
+ let key = local_vault_key(&state, &config)?.expect("unlocked device");
+ let transport = transport_with_password(&config, String::new())?;
+ let (head, _) = read_remote_head(&transport, &config, &key)
+ .await?
+ .expect("remote head after device B edit");
+ let (remote, _) =
+ read_remote_revision(&transport, &config, &key, &head.revision_id).await?;
+ let remote_theme = remote
+ .entities
+ .iter()
+ .find(|entity| entity.domain == DOMAIN_APPLICATION)
+ .and_then(|entity| entity.payload.get("theme"))
+ .and_then(Value::as_str);
+ assert_eq!(remote_theme, Some("light"));
+ }
+ sync_now(device_a.clone(), tx).await?;
+ let state = device_a.lock().await;
+ assert_eq!(
+ state.db.get_setting("app")?.and_then(|value| {
+ value
+ .get("theme")
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ }),
+ Some("light".into())
+ );
+
+ fixture.task.abort();
+ Ok(())
+ }
+}
diff --git a/crates/host-core/src/config_sync/engine_history.rs b/crates/host-core/src/config_sync/engine_history.rs
new file mode 100644
index 000000000..4d59f41f7
--- /dev/null
+++ b/crates/host-core/src/config_sync/engine_history.rs
@@ -0,0 +1,358 @@
+use super::*;
+
+pub(super) async fn history_chain(
+ transport: &WebDavTransport,
+ config: &StoredConfig,
+ key: &VaultKey,
+ head_revision_id: &str,
+) -> Result<Vec<RevisionManifest>> {
+ let mut pending = vec![head_revision_id.to_string()];
+ let mut seen = BTreeSet::new();
+ let mut result = Vec::new();
+ while let Some(revision_id) = pending.pop() {
+ if !seen.insert(revision_id.clone()) {
+ continue;
+ }
+ if seen.len() > MAX_HISTORY_SCAN {
+ bail!("CONFIG_SYNC_LIMIT_EXCEEDED: remote history is too large");
+ }
+ let manifest = read_remote_manifest(transport, config, key, &revision_id).await?;
+ for parent in manifest.parents.iter().rev() {
+ pending.push(parent.clone());
+ }
+ result.push(manifest);
+ }
+ Ok(result)
+}
+
+fn older_than_grace(manifest: &RevisionManifest) -> bool {
+ let Ok(created_at) = chrono::DateTime::parse_from_rfc3339(&manifest.created_at) else {
+ return false;
+ };
+ Utc::now()
+ .signed_duration_since(created_at.with_timezone(&Utc))
+ .num_seconds()
+ >= HISTORY_GRACE_SECONDS
+}
+
+pub(super) async fn cleanup_history(
+ state: &Arc<Mutex<AppState>>,
+ transport: &WebDavTransport,
+ config: &StoredConfig,
+ key: &VaultKey,
+) -> Result<()> {
+ let Some((head, _)) = read_remote_head(transport, config, key).await? else {
+ return Ok(());
+ };
+ let history = history_chain(transport, config, key, &head.revision_id).await?;
+ if history.len() <= MAX_RETAINED_REVISIONS {
+ return Ok(());
+ }
+ let (base_id, protected_ids, protected_resources) = {
+ let st = state.lock().await;
+ let base_id = load_base(&st, key)?.map(|value| value.revision_id);
+ let pending = load_pending(&st, key)?;
+ let mut protected = BTreeSet::new();
+ let mut resources = BTreeSet::new();
+ if let Some(pending) = pending {
+ protected.insert(pending.manifest.revision_id);
+ protected.insert(pending.remote_revision_id);
+ resources.extend(pending.manifest.resource_ids);
+ }
+ for filename in &config.recovery_points {
+ let path = recovery_path(&st, filename)?;
+ if let Some(point) = load_encrypted::<RecoveryPoint>(&st, key, "local-recovery", &path)?
+ {
+ if let Some(base) = point.base {
+ protected.insert(base.revision_id);
+ resources.extend(base.resource_ids);
+ }
+ }
+ }
+ (base_id, protected, resources)
+ };
+ let mut keep = BTreeSet::new();
+ for manifest in history.iter().take(MAX_RETAINED_REVISIONS) {
+ keep.insert(manifest.revision_id.clone());
+ }
+ keep.insert(head.revision_id.clone());
+ if let Some(base_id) = base_id {
+ keep.insert(base_id);
+ }
+ keep.extend(protected_ids);
+
+ let mut deletable = Vec::new();
+ for manifest in history {
+ if !keep.contains(&manifest.revision_id) && older_than_grace(&manifest) {
+ deletable.push(manifest);
+ }
+ }
+ if deletable.is_empty() {
+ return Ok(());
+ }
+ let mut retained_resources: BTreeSet<String> =
+ history_chain(transport, config, key, &head.revision_id)
+ .await?
+ .into_iter()
+ .filter(|manifest| keep.contains(&manifest.revision_id))
+ .flat_map(|manifest| manifest.resource_ids)
+ .collect();
+ retained_resources.extend(protected_resources);
+ let mut candidate_resources = BTreeSet::new();
+ for manifest in &deletable {
+ candidate_resources.extend(manifest.resource_ids.iter().cloned());
+ transport
+ .delete(&revision_path(config, &manifest.revision_id)?)
+ .await?;
+ }
+ for resource_id in candidate_resources.difference(&retained_resources) {
+ transport.delete(&object_path(config, resource_id)?).await?;
+ }
+ Ok(())
+}
+
+pub(super) async fn list_history(state: Arc<Mutex<AppState>>) -> Result<Value> {
+ let (config, key, transport_password) = {
+ let st = state.lock().await;
+ let config = load_config(&st)?
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: sync is not configured"))?;
+ let key = local_vault_key(&st, &config)?
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_LOCKED: backup vault is locked"))?;
+ let password = webdav_password(&st, &config)?;
+ (config, key, password)
+ };
+ let transport = transport_with_password(&config, transport_password)?;
+ let Some((head, _)) = read_remote_head(&transport, &config, &key).await? else {
+ return Ok(json!([]));
+ };
+ let history = history_chain(&transport, &config, &key, &head.revision_id).await?;
+ Ok(serde_json::to_value(
+ history
+ .into_iter()
+ .map(|manifest| PublicHistoryEntry {
+ current: manifest.revision_id == head.revision_id,
+ revision_id: manifest.revision_id,
+ created_at: manifest.created_at,
+ parent_revision_ids: manifest.parents,
+ entity_count: manifest.entities.len(),
+ resource_count: manifest.resource_ids.len(),
+ })
+ .collect::<Vec<_>>(),
+ )?)
+}
+
+fn add_restore_approvals(
+ config: &StoredConfig,
+ local: &RevisionManifest,
+ target: &RevisionManifest,
+ pending: &mut PendingBundle,
+) {
+ let local_map = manifest_map(Some(local));
+ let existing: BTreeSet<(String, String)> = pending
+ .approvals
+ .iter()
+ .map(|item| entity_key(&item.entity))
+ .collect();
+ for entity in &target.entities {
+ if !selection(config).is_selected(&entity.domain)
+ || (!entity.requires_approval && !entity.mapping_required)
+ {
+ continue;
+ }
+ let changed = local_map
+ .get(&entity_key(entity))
+ .is_none_or(|current| current.digest != entity.digest);
+ if changed && !existing.contains(&entity_key(entity)) {
+ pending.approvals.push(PendingApproval {
+ approval_id: Uuid::new_v4().to_string(),
+ entity: entity.clone(),
+ reason: if entity.mapping_required {
+ "mapping".into()
+ } else {
+ "securityChange".into()
+ },
+ approved: false,
+ });
+ }
+ }
+}
+
+pub(super) async fn change_password(state: Arc<Mutex<AppState>>, params: Value) -> Result<Value> {
+ let sync_lock = {
+ let st = state.lock().await;
+ st.config_sync_lock.clone()
+ };
+ let _sync_guard = sync_lock.lock().await;
+ let current_password = params
+ .get("currentPassword")
+ .and_then(Value::as_str)
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: current backup password is required"))?;
+ let new_password = params
+ .get("newPassword")
+ .and_then(Value::as_str)
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: new backup password is required"))?;
+ if new_password.len() < 8 {
+ bail!("CONFIG_SYNC_INVALID: new backup password must be at least 8 characters");
+ }
+ let (mut config, key, transport_password) = {
+ let st = state.lock().await;
+ let config = load_config(&st)?
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: sync is not configured"))?;
+ let key = unlock_vault(&config.vault_header, current_password)?;
+ let password = webdav_password(&st, &config)?;
+ (config, key, password)
+ };
+ let transport = transport_with_password(&config, transport_password)?;
+ let Some((remote_header_bytes, remote_etag)) = transport.get("header").await? else {
+ bail!("CONFIG_SYNC_REMOTE: remote vault header is missing");
+ };
+ let remote_etag = remote_etag.ok_or_else(|| {
+ anyhow!("CONFIG_SYNC_UNSUPPORTED: remote vault header does not expose a strong ETag")
+ })?;
+ let remote_header: VaultHeader =
+ serde_json::from_slice(&remote_header_bytes).context("decode remote vault header")?;
+ if remote_header.vault_id != config.vault_id {
+ bail!("CONFIG_SYNC_CONFLICT: selected WebDAV directory belongs to another vault");
+ }
+ let remote_key = unlock_vault(&remote_header, current_password)?;
+ if remote_key.as_bytes() != key.as_bytes() {
+ bail!("CONFIG_SYNC_CONFLICT: local and remote vault keys do not match");
+ }
+ let next_header = rewrap_vault(&remote_header, &key, new_password)?;
+ let published = transport
+ .put_if_match("header", &remote_etag, serde_json::to_vec(&next_header)?)
+ .await?;
+ if !published {
+ bail!("CONFIG_SYNC_CONFLICT: remote vault header changed while changing password");
+ }
+ config.vault_header = next_header;
+ let mut st = state.lock().await;
+ save_config(&st, &config)?;
+ public_state(&mut st)
+}
+
+pub(super) async fn restore(
+ state: Arc<Mutex<AppState>>,
+ params: Value,
+ tx: mpsc::UnboundedSender<String>,
+) -> Result<Value> {
+ if !params
+ .get("acknowledgePropagation")
+ .and_then(Value::as_bool)
+ .unwrap_or(false)
+ {
+ bail!("CONFIG_SYNC_INVALID: restore propagation warning must be acknowledged");
+ }
+ let revision_id = params
+ .get("revisionId")
+ .and_then(Value::as_str)
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: revisionId is required"))?;
+ validate_remote_id(revision_id, "revision")?;
+ let sync_lock = {
+ let st = state.lock().await;
+ st.config_sync_lock.clone()
+ };
+ let _sync_guard = sync_lock.lock().await;
+ let (mut config, key, base, local, transport_password) = {
+ let mut st = state.lock().await;
+ let config = load_config(&st)?
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: sync is not configured"))?;
+ let key = local_vault_key(&st, &config)?
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_LOCKED: backup vault is locked"))?;
+ let base = load_base(&st, &key)?;
+ let local = domains::capture(
+ &mut st,
+ &key,
+ &selection(&config),
+ config.include_secrets,
+ &config.plugin_intents,
+ &identity_overrides(&config),
+ )?;
+ let password = webdav_password(&st, &config)?;
+ (config, key, base, local, password)
+ };
+ let transport = transport_with_password(&config, transport_password)?;
+ let Some((current_head, current_etag)) = read_remote_head(&transport, &config, &key).await?
+ else {
+ bail!("CONFIG_SYNC_REMOTE: cannot restore from an empty vault");
+ };
+ let (target, target_resources) =
+ read_remote_revision(&transport, &config, &key, revision_id).await?;
+ let candidate_id = Uuid::new_v4().to_string();
+ let candidate = LocalSnapshot {
+ manifest: RevisionManifest {
+ format: REVISION_FORMAT.into(),
+ version: 1,
+ revision_id: candidate_id.clone(),
+ parents: vec![current_head.revision_id.clone()],
+ created_at: Utc::now().to_rfc3339(),
+ entities: target.entities.clone(),
+ resource_ids: target_resources.keys().cloned().collect(),
+ },
+ resources: target_resources,
+ };
+ upload_snapshot(&transport, &config, &key, &candidate).await?;
+ if !publish_head(
+ &transport,
+ &config,
+ &key,
+ &RemoteHead {
+ format: FORMAT.into(),
+ version: 1,
+ revision_id: candidate_id.clone(),
+ },
+ Some(&current_etag),
+ )
+ .await?
+ {
+ bail!("CONFIG_SYNC_CONFLICT: remote head changed while restoring");
+ }
+
+ let merged = merge::MergeResult {
+ entities: candidate.manifest.entities.clone(),
+ conflicts: Vec::new(),
+ };
+ let mut pending = build_pending(
+ &config,
+ base.as_ref(),
+ &local.manifest,
+ Some(&target),
+ &merged,
+ &candidate_id,
+ candidate.resources.clone(),
+ );
+ pending.manifest = candidate.manifest.clone();
+ pending.local_before = Some(local.manifest.clone());
+ add_restore_approvals(&config, &local.manifest, &target, &mut pending);
+ let should_apply = pending.approvals.is_empty();
+ {
+ let st = state.lock().await;
+ create_recovery_point(&st, &mut config, &key, base.clone(), local.clone())?;
+ let mut journal = pending.clone();
+ journal.journal_state = if should_apply { "applying" } else { "staged" }.into();
+ store_pending(&st, &key, &journal)?;
+ if !should_apply {
+ config.last_success_at = Some(Utc::now().to_rfc3339());
+ config.last_revision_id = Some(candidate_id.clone());
+ clear_error(&mut config);
+ save_config(&st, &config)?;
+ }
+ }
+ if should_apply {
+ apply_bundle(
+ &state,
+ &mut config,
+ &key,
+ base.as_ref(),
+ &local.manifest,
+ &pending,
+ )
+ .await?;
+ }
+ if let Err(error) = cleanup_history(&state, &transport, &config, &key).await {
+ tracing::warn!(error = %error, "config sync history cleanup failed after restore");
+ }
+ let mut st = state.lock().await;
+ send_state_notification(&tx, &mut st);
+ public_state(&mut st)
+}
diff --git a/crates/host-core/src/config_sync/engine_remote.rs b/crates/host-core/src/config_sync/engine_remote.rs
new file mode 100644
index 000000000..21dd580e0
--- /dev/null
+++ b/crates/host-core/src/config_sync/engine_remote.rs
@@ -0,0 +1,281 @@
+use super::*;
+
+pub(super) fn remote_prefix(config: &StoredConfig) -> String {
+ format!("vault/{}/", config.vault_id)
+}
+
+pub(super) fn remote_path(config: &StoredConfig, suffix: &str) -> String {
+ format!(
+ "{}{}",
+ remote_prefix(config),
+ suffix.trim_start_matches('/')
+ )
+}
+
+pub(super) fn validate_remote_id(value: &str, kind: &str) -> Result<()> {
+ if value.is_empty()
+ || value.len() > 128
+ || value.contains('/')
+ || value.contains('\\')
+ || value.contains("..")
+ || !value
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | ':' | '.'))
+ {
+ bail!("CONFIG_SYNC_INVALID: unsafe remote {kind} id");
+ }
+ Ok(())
+}
+
+pub(super) async fn ensure_remote_collections(
+ transport: &WebDavTransport,
+ config: &StoredConfig,
+) -> Result<()> {
+ validate_remote_id(&config.vault_id, "vault")?;
+ transport.ensure_collection("vault").await?;
+ transport
+ .ensure_collection(&format!("vault/{}", config.vault_id))
+ .await?;
+ for child in ["objects", "revisions"] {
+ transport
+ .ensure_collection(&format!("vault/{}/{}", config.vault_id, child))
+ .await?;
+ }
+ Ok(())
+}
+
+pub(super) fn revision_path(config: &StoredConfig, revision_id: &str) -> Result<String> {
+ validate_remote_id(&config.vault_id, "vault")?;
+ validate_remote_id(revision_id, "revision")?;
+ Ok(remote_path(config, &format!("revisions/{revision_id}")))
+}
+
+pub(super) fn object_path(config: &StoredConfig, object_id: &str) -> Result<String> {
+ validate_remote_id(&config.vault_id, "vault")?;
+ validate_remote_id(object_id, "object")?;
+ Ok(remote_path(config, &format!("objects/{object_id}")))
+}
+
+pub(super) fn head_path(config: &StoredConfig) -> String {
+ remote_path(config, "head")
+}
+
+pub(super) fn serialize_json<T: Serialize>(value: &T) -> Result<Vec<u8>> {
+ Ok(serde_json::to_vec(value)?)
+}
+
+pub(super) async fn read_remote_head(
+ transport: &WebDavTransport,
+ config: &StoredConfig,
+ key: &VaultKey,
+) -> Result<Option<(RemoteHead, String)>> {
+ validate_remote_id(&config.vault_id, "vault")?;
+ let Some((ciphertext, etag)) = transport.get(&head_path(config)).await? else {
+ return Ok(None);
+ };
+ let etag = etag.ok_or_else(|| {
+ anyhow!("CONFIG_SYNC_UNSUPPORTED: WebDAV head does not expose a strong ETag")
+ })?;
+ let plain = decrypt_object(key, "head", &config.vault_id, &ciphertext)?;
+ let head: RemoteHead = serde_json::from_slice(&plain).context("decode remote head")?;
+ if head.format != FORMAT || head.version != 1 {
+ bail!("CONFIG_SYNC_UNSUPPORTED: remote head format is not supported");
+ }
+ validate_remote_id(&head.revision_id, "revision")?;
+ Ok(Some((head, etag)))
+}
+
+pub(super) async fn read_remote_revision(
+ transport: &WebDavTransport,
+ config: &StoredConfig,
+ key: &VaultKey,
+ revision_id: &str,
+) -> Result<(RevisionManifest, BTreeMap<String, Vec<u8>>)> {
+ let manifest = read_remote_manifest(transport, config, key, revision_id).await?;
+ let mut resource_ids = BTreeSet::new();
+ for entity in &manifest.entities {
+ resource_ids.extend(entity.resource_ids.iter().cloned());
+ }
+ if resource_ids.len() > MAX_RESOURCES {
+ bail!("CONFIG_SYNC_LIMIT_EXCEEDED: remote revision references too many resources");
+ }
+ let mut resources = BTreeMap::new();
+ for object_id in resource_ids {
+ let path = object_path(config, &object_id)?;
+ let Some((ciphertext, _)) = transport.get(&path).await? else {
+ bail!("CONFIG_SYNC_REMOTE: referenced resource is missing");
+ };
+ let bytes = decrypt_object(
+ key,
+ &format!("resource/{object_id}"),
+ &config.vault_id,
+ &ciphertext,
+ )?;
+ if bytes.len() > 128 * 1024 {
+ bail!("CONFIG_SYNC_LIMIT_EXCEEDED: remote resource is too large");
+ }
+ resources.insert(object_id, bytes);
+ }
+ Ok((manifest, resources))
+}
+
+pub(super) async fn read_remote_manifest(
+ transport: &WebDavTransport,
+ config: &StoredConfig,
+ key: &VaultKey,
+ revision_id: &str,
+) -> Result<RevisionManifest> {
+ let path = revision_path(config, revision_id)?;
+ let Some((ciphertext, _)) = transport.get(&path).await? else {
+ bail!("CONFIG_SYNC_REMOTE: referenced revision is missing");
+ };
+ let plain = decrypt_object(
+ key,
+ &format!("manifest/{revision_id}"),
+ &config.vault_id,
+ &ciphertext,
+ )?;
+ let manifest: RevisionManifest =
+ serde_json::from_slice(&plain).context("decode remote revision")?;
+ if manifest.format != REVISION_FORMAT
+ || manifest.version != 1
+ || manifest.revision_id != revision_id
+ || manifest.entities.len() > MAX_ENTITIES
+ || manifest.resource_ids.len() > MAX_RESOURCES
+ {
+ bail!("CONFIG_SYNC_UNSUPPORTED: remote revision is invalid");
+ }
+ for parent in &manifest.parents {
+ validate_remote_id(parent, "revision")?;
+ }
+ for entity in &manifest.entities {
+ if domains::adapter_for(&entity.domain).is_none() {
+ bail!(
+ "CONFIG_SYNC_UNSUPPORTED: remote domain {} is not supported",
+ entity.domain
+ );
+ }
+ if entity.entity_id.len() > 256
+ || entity.label.len() > 512
+ || serde_json::to_vec(&entity.payload)?.len() > 512 * 1024
+ {
+ bail!("CONFIG_SYNC_LIMIT_EXCEEDED: remote entity is too large");
+ }
+ }
+ let mut resource_ids = BTreeSet::new();
+ for entity in &manifest.entities {
+ for object_id in &entity.resource_ids {
+ validate_remote_id(object_id, "object")?;
+ }
+ resource_ids.extend(entity.resource_ids.iter().cloned());
+ }
+ let declared_resources = manifest
+ .resource_ids
+ .iter()
+ .cloned()
+ .collect::<BTreeSet<_>>();
+ for object_id in &declared_resources {
+ validate_remote_id(object_id, "object")?;
+ }
+ if declared_resources != resource_ids {
+ bail!("CONFIG_SYNC_INVALID: remote revision resource references do not match");
+ }
+ if resource_ids.len() > MAX_RESOURCES {
+ bail!("CONFIG_SYNC_LIMIT_EXCEEDED: remote revision references too many resources");
+ }
+ for object_id in resource_ids {
+ validate_remote_id(&object_id, "object")?;
+ }
+ Ok(manifest)
+}
+
+pub(super) async fn upload_snapshot(
+ transport: &WebDavTransport,
+ config: &StoredConfig,
+ key: &VaultKey,
+ snapshot: &LocalSnapshot,
+) -> Result<()> {
+ if snapshot.manifest.entities.len() > MAX_ENTITIES || snapshot.resources.len() > MAX_RESOURCES {
+ bail!("CONFIG_SYNC_LIMIT_EXCEEDED: local revision is too large");
+ }
+ let declared_resources = snapshot
+ .manifest
+ .resource_ids
+ .iter()
+ .cloned()
+ .collect::<BTreeSet<_>>();
+ if declared_resources != snapshot.resources.keys().cloned().collect() {
+ bail!("CONFIG_SYNC_INVALID: local revision resource references do not match");
+ }
+ for entity in &snapshot.manifest.entities {
+ if domains::adapter_for(&entity.domain).is_none()
+ || entity.entity_id.len() > 256
+ || entity.label.len() > 512
+ || serde_json::to_vec(&entity.payload)?.len() > 512 * 1024
+ {
+ bail!("CONFIG_SYNC_LIMIT_EXCEEDED: local entity is too large or unsupported");
+ }
+ }
+ for (object_id, bytes) in &snapshot.resources {
+ let path = object_path(config, object_id)?;
+ let encrypted = encrypt_object(
+ key,
+ &format!("resource/{object_id}"),
+ &config.vault_id,
+ bytes,
+ )?;
+ transport.put_if_none(&path, encrypted).await?;
+ let Some((existing, _)) = transport.get(&path).await? else {
+ bail!("CONFIG_SYNC_REMOTE: immutable resource disappeared after upload");
+ };
+ let verified = decrypt_object(
+ key,
+ &format!("resource/{object_id}"),
+ &config.vault_id,
+ &existing,
+ )?;
+ if verified != *bytes {
+ bail!("CONFIG_SYNC_CRYPTO: immutable resource id collision");
+ }
+ }
+ let manifest_bytes = serialize_json(&snapshot.manifest)?;
+ let encrypted = encrypt_object(
+ key,
+ &format!("manifest/{}", snapshot.manifest.revision_id),
+ &config.vault_id,
+ &manifest_bytes,
+ )?;
+ let path = revision_path(config, &snapshot.manifest.revision_id)?;
+ transport.put_if_none(&path, encrypted).await?;
+ let Some((existing, _)) = transport.get(&path).await? else {
+ bail!("CONFIG_SYNC_REMOTE: immutable revision disappeared after upload");
+ };
+ let verified = decrypt_object(
+ key,
+ &format!("manifest/{}", snapshot.manifest.revision_id),
+ &config.vault_id,
+ &existing,
+ )?;
+ if verified != manifest_bytes {
+ bail!("CONFIG_SYNC_CRYPTO: immutable revision id collision");
+ }
+ Ok(())
+}
+
+pub(super) async fn publish_head(
+ transport: &WebDavTransport,
+ config: &StoredConfig,
+ key: &VaultKey,
+ head: &RemoteHead,
+ etag: Option<&str>,
+) -> Result<bool> {
+ validate_remote_id(&config.vault_id, "vault")?;
+ let encrypted = encrypt_object(key, "head", &config.vault_id, &serialize_json(head)?)?;
+ if let Some(etag) = etag {
+ transport
+ .put_if_match(&head_path(config), etag, encrypted)
+ .await
+ } else {
+ Ok(transport.put_if_none(&head_path(config), encrypted).await?)
+ }
+}
diff --git a/crates/host-core/src/config_sync/handlers.rs b/crates/host-core/src/config_sync/handlers.rs
new file mode 100644
index 000000000..c35077f9d
--- /dev/null
+++ b/crates/host-core/src/config_sync/handlers.rs
@@ -0,0 +1,481 @@
+use super::*;
+
+pub(crate) async fn get_state(state: Arc<Mutex<AppState>>) -> Result<Value> {
+ let mut st = state.lock().await;
+ public_state(&mut st)
+}
+
+pub(crate) async fn list_history(state: Arc<Mutex<AppState>>) -> Result<Value> {
+ history::list_history(state).await
+}
+
+pub(crate) async fn change_password(state: Arc<Mutex<AppState>>, params: Value) -> Result<Value> {
+ history::change_password(state, params).await
+}
+
+pub(crate) async fn restore(
+ state: Arc<Mutex<AppState>>,
+ params: Value,
+ tx: mpsc::UnboundedSender<String>,
+) -> Result<Value> {
+ history::restore(state, params, tx).await
+}
+
+pub(crate) async fn test(state: Arc<Mutex<AppState>>, params: Value) -> Result<Value> {
+ let (config, password) = {
+ let st = state.lock().await;
+ let existing = load_config(&st)?;
+ let endpoint = params
+ .get("endpoint")
+ .and_then(Value::as_str)
+ .unwrap_or_else(|| {
+ existing
+ .as_ref()
+ .map(|value| value.endpoint.as_str())
+ .unwrap_or_default()
+ });
+ let username = params
+ .get("username")
+ .and_then(Value::as_str)
+ .unwrap_or_else(|| {
+ existing
+ .as_ref()
+ .map(|value| value.username.as_str())
+ .unwrap_or_default()
+ });
+ let directory = params
+ .get("directory")
+ .and_then(Value::as_str)
+ .unwrap_or_else(|| {
+ existing
+ .as_ref()
+ .map(|value| value.directory.as_str())
+ .unwrap_or_default()
+ });
+ let allow_insecure = params
+ .get("allowInsecureHttp")
+ .and_then(Value::as_bool)
+ .or_else(|| existing.as_ref().map(|value| value.allow_insecure_http))
+ .unwrap_or(false);
+ let stored_password = st.secrets.get(WEBDAV_SECRET_REF)?;
+ let password = params
+ .get("appPassword")
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ .or(stored_password)
+ .unwrap_or_default();
+ let vault_id = Uuid::new_v4().to_string();
+ let header = create_vault("temporary-test-password", &vault_id)?.0;
+ (
+ StoredConfig {
+ format: FORMAT.into(),
+ version: 1,
+ endpoint: endpoint.trim().into(),
+ username: username.trim().into(),
+ directory: directory.trim().into(),
+ device_label: "test".into(),
+ allow_insecure_http: allow_insecure,
+ categories: default_categories(),
+ include_secrets: false,
+ include_memory: false,
+ automatic_sync: false,
+ enabled: false,
+ paused: false,
+ vault_id,
+ vault_header: header,
+ last_run_at: None,
+ last_success_at: None,
+ last_revision_id: None,
+ last_error: None,
+ last_error_code: None,
+ last_local_digest: None,
+ local_change_seen_at: None,
+ retry_count: 0,
+ next_retry_at: None,
+ project_mappings: BTreeMap::new(),
+ project_group_mappings: BTreeMap::new(),
+ dismissed: BTreeMap::new(),
+ plugin_intents: BTreeMap::new(),
+ recovery_points: Vec::new(),
+ },
+ password,
+ )
+ };
+ let transport = transport_with_password(&config, password)?;
+ let probe = transport.probe().await?;
+ Ok(json!({ "ok": true, "conditionalWrites": probe.conditional_writes }))
+}
+
+pub(crate) async fn configure(state: Arc<Mutex<AppState>>, params: Value) -> Result<Value> {
+ let sync_lock = {
+ let st = state.lock().await;
+ st.config_sync_lock.clone()
+ };
+ let _sync_guard = sync_lock.lock().await;
+ let backup_password = params
+ .get("backupPassword")
+ .and_then(Value::as_str)
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: backup password is required"))?;
+ if backup_password.len() < 8 {
+ bail!("CONFIG_SYNC_INVALID: backup password must be at least 8 characters");
+ }
+ let (mut config, mut key, transport_password, had_existing) = {
+ let st = state.lock().await;
+ let existing = load_config(&st)?;
+ let vault_id = existing
+ .as_ref()
+ .map(|value| value.vault_id.clone())
+ .unwrap_or_else(|| Uuid::new_v4().to_string());
+ let (header, key) = if let Some(existing) = existing.as_ref() {
+ (
+ existing.vault_header.clone(),
+ unlock_vault(&existing.vault_header, backup_password)?,
+ )
+ } else {
+ create_vault(backup_password, &vault_id)?
+ };
+ let config = config_from_input(existing.as_ref(), &params, header)?;
+ let stored_password = if existing
+ .as_ref()
+ .is_some_and(|value| value.username == config.username)
+ {
+ st.secrets.get(WEBDAV_SECRET_REF)?
+ } else {
+ None
+ };
+ let transport_password = params
+ .get("appPassword")
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ .or(stored_password)
+ .unwrap_or_default();
+ if !config.username.is_empty() && transport_password.is_empty() {
+ bail!("CONFIG_SYNC_INVALID: WebDAV app password is required");
+ }
+ (config, key, transport_password, existing.is_some())
+ };
+ let app_password = params
+ .get("appPassword")
+ .and_then(Value::as_str)
+ .map(str::to_string);
+ let transport = transport_with_password(&config, transport_password.clone())?;
+ let probe = transport.probe().await?;
+ if !probe.conditional_writes {
+ bail!("CONFIG_SYNC_UNSUPPORTED: WebDAV server did not prove reliable conditional writes");
+ }
+ transport.ensure_collection("vault").await?;
+ let remote_header = transport.get("header").await?;
+ if let Some((bytes, _)) = remote_header {
+ let remote: VaultHeader =
+ serde_json::from_slice(&bytes).context("decode remote vault header")?;
+ if had_existing && config.vault_id != remote.vault_id {
+ bail!("CONFIG_SYNC_CONFLICT: selected WebDAV directory belongs to another vault");
+ }
+ key = unlock_vault(&remote, backup_password)?;
+ config.vault_id = remote.vault_id.clone();
+ config.vault_header = remote;
+ } else {
+ let created = transport
+ .put_if_none("header", serde_json::to_vec(&config.vault_header)?)
+ .await?;
+ if !created {
+ let Some((bytes, _)) = transport.get("header").await? else {
+ bail!("CONFIG_SYNC_REMOTE: vault header disappeared during initialization");
+ };
+ let remote: VaultHeader = serde_json::from_slice(&bytes)?;
+ key = unlock_vault(&remote, backup_password)?;
+ config.vault_id = remote.vault_id.clone();
+ config.vault_header = remote;
+ }
+ }
+ ensure_remote_collections(&transport, &config).await?;
+ let mut st = state.lock().await;
+ if config.username.is_empty() {
+ st.secrets.delete(WEBDAV_SECRET_REF)?;
+ } else if let Some(password) = app_password {
+ st.secrets.set(WEBDAV_SECRET_REF, &password)?;
+ }
+ st.secrets.set(
+ &secret_ref_for_vault(&config.vault_id),
+ &vault_key_b64(&key),
+ )?;
+ save_config(&st, &config)?;
+ public_state(&mut st)
+}
+
+pub(crate) async fn pause(state: Arc<Mutex<AppState>>, paused: bool) -> Result<Value> {
+ let sync_lock = {
+ let st = state.lock().await;
+ st.config_sync_lock.clone()
+ };
+ let _sync_guard = sync_lock.lock().await;
+ let mut st = state.lock().await;
+ let mut config =
+ load_config(&st)?.ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: sync is not configured"))?;
+ config.paused = paused;
+ save_config(&st, &config)?;
+ public_state(&mut st)
+}
+
+pub(crate) async fn unlock(state: Arc<Mutex<AppState>>, params: Value) -> Result<Value> {
+ let sync_lock = {
+ let st = state.lock().await;
+ st.config_sync_lock.clone()
+ };
+ let _sync_guard = sync_lock.lock().await;
+ let password = params
+ .get("backupPassword")
+ .and_then(Value::as_str)
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: backup password is required"))?;
+ let mut st = state.lock().await;
+ let config =
+ load_config(&st)?.ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: sync is not configured"))?;
+ let key = unlock_vault(&config.vault_header, password)?;
+ st.secrets.set(
+ &secret_ref_for_vault(&config.vault_id),
+ &vault_key_b64(&key),
+ )?;
+ public_state(&mut st)
+}
+
+pub(crate) async fn approve(
+ state: Arc<Mutex<AppState>>,
+ params: Value,
+ tx: mpsc::UnboundedSender<String>,
+) -> Result<Value> {
+ let sync_lock = {
+ let st = state.lock().await;
+ st.config_sync_lock.clone()
+ };
+ let _sync_guard = sync_lock.lock().await;
+ let approval_id = params
+ .get("approvalId")
+ .and_then(Value::as_str)
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: approvalId is required"))?;
+ let digest = params
+ .get("digest")
+ .and_then(Value::as_str)
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: approval digest is required"))?;
+ let (mut config, key, mut pending) = {
+ let st = state.lock().await;
+ let config = load_config(&st)?
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: sync is not configured"))?;
+ let key = local_vault_key(&st, &config)?
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_LOCKED: backup vault is locked"))?;
+ let pending = load_pending(&st, &key)?
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: approval is no longer pending"))?;
+ (config, key, pending)
+ };
+ let item_index = pending
+ .approvals
+ .iter()
+ .position(|item| item.approval_id == approval_id)
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: approval is not pending"))?;
+ let item = pending.approvals[item_index].clone();
+ if item.entity.digest != digest {
+ bail!("CONFIG_SYNC_CONFLICT: approval digest is stale");
+ }
+ pending.approvals[item_index].approved = true;
+ if let Some(base_id) = conflict_base_id(&item.entity.entity_id) {
+ let domain = item.entity.domain.clone();
+ let mut dismissed = Vec::new();
+ pending.approvals.retain(|candidate| {
+ let is_sibling = candidate.approval_id != approval_id
+ && candidate.entity.domain == domain
+ && conflict_base_id(&candidate.entity.entity_id) == Some(base_id);
+ if is_sibling {
+ dismissed.push(candidate.entity.clone());
+ }
+ !is_sibling
+ });
+ for candidate in dismissed {
+ config
+ .dismissed
+ .insert(approval_key(&candidate), candidate.digest);
+ }
+ }
+ pending.journal_state = "applying".into();
+ {
+ let st = state.lock().await;
+ store_pending(&st, &key, &pending)?;
+ save_config(&st, &config)?;
+ }
+ let base = {
+ let st = state.lock().await;
+ load_base(&st, &key)?
+ };
+ let local = {
+ let mut st = state.lock().await;
+ domains::capture(
+ &mut st,
+ &key,
+ &selection(&config),
+ config.include_secrets,
+ &config.plugin_intents,
+ &identity_overrides(&config),
+ )?
+ };
+ apply_bundle(
+ &state,
+ &mut config,
+ &key,
+ base.as_ref(),
+ &local.manifest,
+ &pending,
+ )
+ .await?;
+ let mut st = state.lock().await;
+ send_state_notification(&tx, &mut st);
+ public_state(&mut st)
+}
+
+pub(crate) async fn reject(
+ state: Arc<Mutex<AppState>>,
+ params: Value,
+ tx: mpsc::UnboundedSender<String>,
+) -> Result<Value> {
+ let sync_lock = {
+ let st = state.lock().await;
+ st.config_sync_lock.clone()
+ };
+ let _sync_guard = sync_lock.lock().await;
+ let approval_id = params
+ .get("approvalId")
+ .and_then(Value::as_str)
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: approvalId is required"))?;
+ let digest = params
+ .get("digest")
+ .and_then(Value::as_str)
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: approval digest is required"))?;
+ let mut st = state.lock().await;
+ let mut config =
+ load_config(&st)?.ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: sync is not configured"))?;
+ let key = local_vault_key(&st, &config)?
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_LOCKED: backup vault is locked"))?;
+ let mut pending = load_pending(&st, &key)?
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: approval is no longer pending"))?;
+ let Some(index) = pending
+ .approvals
+ .iter()
+ .position(|item| item.approval_id == approval_id)
+ else {
+ bail!("CONFIG_SYNC_INVALID: approval is not pending");
+ };
+ let item = pending.approvals.remove(index);
+ if item.entity.digest != digest {
+ bail!("CONFIG_SYNC_CONFLICT: approval digest is stale");
+ }
+ config
+ .dismissed
+ .insert(approval_key(&item.entity), item.entity.digest);
+ if pending.approvals.is_empty() {
+ clear_pending(&st)?;
+ } else {
+ store_pending(&st, &key, &pending)?;
+ }
+ save_config(&st, &config)?;
+ send_state_notification(&tx, &mut st);
+ public_state(&mut st)
+}
+
+pub(crate) async fn map_project(state: Arc<Mutex<AppState>>, params: Value) -> Result<Value> {
+ let sync_lock = {
+ let st = state.lock().await;
+ st.config_sync_lock.clone()
+ };
+ let _sync_guard = sync_lock.lock().await;
+ let logical_id = params
+ .get("logicalId")
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|value| !value.is_empty() && value.len() <= 256)
+ .ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: mapping logicalId is required"))?;
+ if logical_id.contains('/') || logical_id.contains('\\') {
+ bail!("CONFIG_SYNC_INVALID: mapping logicalId is unsafe");
+ }
+ let mut raw_paths = params
+ .get("paths")
+ .and_then(Value::as_array)
+ .map(|values| {
+ values
+ .iter()
+ .filter_map(Value::as_str)
+ .map(str::trim)
+ .filter(|value| !value.is_empty())
+ .map(str::to_string)
+ .collect::<Vec<_>>()
+ })
+ .unwrap_or_default();
+ if raw_paths.is_empty() {
+ if let Some(path) = params
+ .get("path")
+ .and_then(Value::as_str)
+ .map(str::trim)
+ .filter(|value| !value.is_empty())
+ {
+ raw_paths.push(path.to_string());
+ }
+ }
+ if raw_paths.is_empty() || raw_paths.len() > 32 {
+ bail!("CONFIG_SYNC_INVALID: one to thirty-two mapping paths are required");
+ }
+ let mut paths = Vec::with_capacity(raw_paths.len());
+ for raw_path in raw_paths {
+ if fs::symlink_metadata(&raw_path)
+ .map(|metadata| metadata.file_type().is_symlink())
+ .unwrap_or(false)
+ {
+ bail!("CONFIG_SYNC_MAPPING_REQUIRED: symbolic links are not valid project mappings");
+ }
+ let path = fs::canonicalize(&raw_path).with_context(|| {
+ "CONFIG_SYNC_MAPPING_REQUIRED: mapped project folder is unavailable"
+ })?;
+ if !path.is_dir() {
+ bail!("CONFIG_SYNC_MAPPING_REQUIRED: mapped path is not a folder");
+ }
+ let normalized = crate::agent_capabilities::normalize_project_path(&path.to_string_lossy());
+ if !paths.iter().any(|candidate| candidate == &normalized) {
+ paths.push(normalized);
+ }
+ }
+ if paths.is_empty() {
+ bail!("CONFIG_SYNC_INVALID: mapping paths are empty");
+ }
+ let mut st = state.lock().await;
+ let mut config =
+ load_config(&st)?.ok_or_else(|| anyhow!("CONFIG_SYNC_INVALID: sync is not configured"))?;
+ if logical_id.starts_with("project-group:") || paths.len() > 1 {
+ config.project_mappings.remove(logical_id);
+ config
+ .project_group_mappings
+ .insert(logical_id.to_string(), paths);
+ } else {
+ config.project_group_mappings.remove(logical_id);
+ config
+ .project_mappings
+ .insert(logical_id.to_string(), paths[0].clone());
+ }
+ save_config(&st, &config)?;
+ public_state(&mut st)
+}
+
+pub(crate) async fn disconnect(state: Arc<Mutex<AppState>>) -> Result<Value> {
+ let sync_lock = {
+ let st = state.lock().await;
+ st.config_sync_lock.clone()
+ };
+ let _sync_guard = sync_lock.lock().await;
+ let mut st = state.lock().await;
+ if let Some(config) = load_config(&st)? {
+ st.secrets.delete(WEBDAV_SECRET_REF)?;
+ st.secrets.delete(&secret_ref_for_vault(&config.vault_id))?;
+ st.db.kv_delete(CONFIG_NS, CONFIG_KEY)?;
+ for file in ["base.bin", "pending.bin"] {
+ let path = local_path(&st, file);
+ if path.exists() {
+ fs::remove_file(path)?;
+ }
+ }
+ }
+ public_state(&mut st)
+}
diff --git a/crates/host-core/src/config_sync/merge.rs b/crates/host-core/src/config_sync/merge.rs
new file mode 100644
index 000000000..5d4cbeafe
--- /dev/null
+++ b/crates/host-core/src/config_sync/merge.rs
@@ -0,0 +1,507 @@
+use super::domains::{
+ refresh_digest, CategorySelection, LocalSnapshot, PortableEntity, RevisionManifest,
+ DOMAIN_APPLICATION,
+};
+use anyhow::{bail, Result};
+use std::collections::{BTreeMap, BTreeSet};
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MergeConflict {
+ pub domain: String,
+ pub entity_id: String,
+ pub label: String,
+ pub local_digest: String,
+ pub remote_digest: String,
+ pub reason: String,
+}
+
+#[derive(Debug, Clone)]
+pub struct MergeResult {
+ pub entities: Vec<PortableEntity>,
+ pub conflicts: Vec<MergeConflict>,
+}
+
+fn key(entity: &PortableEntity) -> (String, String) {
+ (entity.domain.clone(), entity.entity_id.clone())
+}
+
+fn index(manifest: Option<&RevisionManifest>) -> BTreeMap<(String, String), PortableEntity> {
+ manifest
+ .map(|manifest| {
+ manifest
+ .entities
+ .iter()
+ .cloned()
+ .map(|entity| (key(&entity), entity))
+ .collect()
+ })
+ .unwrap_or_default()
+}
+
+fn choose_conflict(
+ local: &PortableEntity,
+ remote: &PortableEntity,
+) -> (PortableEntity, PortableEntity) {
+ let mut local_candidate = local.clone();
+ local_candidate.entity_id = format!("{}:local", local_candidate.entity_id);
+ local_candidate.label = format!("{} (local)", local_candidate.label);
+ let mut remote_candidate = remote.clone();
+ remote_candidate.entity_id = format!("{}:remote", remote_candidate.entity_id);
+ remote_candidate.label = format!("{} (remote)", remote_candidate.label);
+ (local_candidate, remote_candidate)
+}
+
+fn merge_application_fields(
+ base: &PortableEntity,
+ local: &PortableEntity,
+ remote: &PortableEntity,
+) -> Option<PortableEntity> {
+ if base.deleted || local.deleted || remote.deleted {
+ return None;
+ }
+ let (Some(base_object), Some(local_object), Some(remote_object)) = (
+ base.payload.as_object(),
+ local.payload.as_object(),
+ remote.payload.as_object(),
+ ) else {
+ return None;
+ };
+ let mut keys = BTreeSet::new();
+ keys.extend(base_object.keys().cloned());
+ keys.extend(local_object.keys().cloned());
+ keys.extend(remote_object.keys().cloned());
+ let mut merged = serde_json::Map::new();
+ for key in keys {
+ let base_value = base_object.get(&key);
+ let local_value = local_object.get(&key);
+ let remote_value = remote_object.get(&key);
+ let value = if local_value == remote_value {
+ local_value
+ } else if local_value == base_value {
+ remote_value
+ } else if remote_value == base_value {
+ local_value
+ } else {
+ return None;
+ };
+ if let Some(value) = value {
+ merged.insert(key, value.clone());
+ }
+ }
+ let mut result = local.clone();
+ result.payload = serde_json::Value::Object(merged);
+ refresh_digest(&mut result);
+ Some(result)
+}
+
+/// Merge a captured local state and a remote revision against the last
+/// acknowledged common base. A missing entity is meaningful only when it is
+/// present in the base; callers represent that deletion as a tombstone before
+/// invoking this function. This keeps category opt-out from becoming an
+/// accidental remote delete.
+pub fn three_way(
+ base: Option<&RevisionManifest>,
+ local: &RevisionManifest,
+ remote: Option<&RevisionManifest>,
+) -> Result<MergeResult> {
+ let base = index(base);
+ let local = index(Some(local));
+ let remote = index(remote);
+ let mut keys = BTreeSet::new();
+ keys.extend(base.keys().cloned());
+ keys.extend(local.keys().cloned());
+ keys.extend(remote.keys().cloned());
+
+ let mut entities = Vec::new();
+ let mut conflicts = Vec::new();
+ for item in keys {
+ let base_value = base.get(&item);
+ let local_value = local.get(&item);
+ let remote_value = remote.get(&item);
+ let selected = match (base_value, local_value, remote_value) {
+ (None, None, None) => Vec::new(),
+ (None, Some(local), None) => vec![local.clone()],
+ (None, None, Some(remote)) => vec![remote.clone()],
+ (None, Some(local), Some(remote)) if local.digest == remote.digest => {
+ vec![local.clone()]
+ }
+ (None, Some(local), Some(remote)) => {
+ if local.domain == DOMAIN_APPLICATION
+ && local
+ .payload
+ .as_object()
+ .is_some_and(serde_json::Map::is_empty)
+ {
+ let mut empty_base = local.clone();
+ empty_base.payload = serde_json::json!({});
+ if let Some(merged) = merge_application_fields(&empty_base, local, remote) {
+ vec![merged]
+ } else {
+ let (local_candidate, remote_candidate) = choose_conflict(local, remote);
+ conflicts.push(MergeConflict {
+ domain: local.domain.clone(),
+ entity_id: local.entity_id.clone(),
+ label: local.label.clone(),
+ local_digest: local.digest.clone(),
+ remote_digest: remote.digest.clone(),
+ reason: "independent-initial-identities".to_string(),
+ });
+ vec![local_candidate, remote_candidate]
+ }
+ } else {
+ let (local_candidate, remote_candidate) = choose_conflict(local, remote);
+ conflicts.push(MergeConflict {
+ domain: local.domain.clone(),
+ entity_id: local.entity_id.clone(),
+ label: local.label.clone(),
+ local_digest: local.digest.clone(),
+ remote_digest: remote.digest.clone(),
+ reason: "independent-initial-identities".to_string(),
+ });
+ vec![local_candidate, remote_candidate]
+ }
+ }
+ (Some(_base), Some(local), Some(remote)) if local.digest == remote.digest => {
+ vec![local.clone()]
+ }
+ (Some(base), Some(local), Some(remote))
+ if base.domain == DOMAIN_APPLICATION
+ && local.domain == DOMAIN_APPLICATION
+ && remote.domain == DOMAIN_APPLICATION =>
+ {
+ if let Some(merged) = merge_application_fields(base, local, remote) {
+ vec![merged]
+ } else {
+ let (local_candidate, remote_candidate) = choose_conflict(local, remote);
+ conflicts.push(MergeConflict {
+ domain: base.domain.clone(),
+ entity_id: base.entity_id.clone(),
+ label: base.label.clone(),
+ local_digest: local.digest.clone(),
+ remote_digest: remote.digest.clone(),
+ reason: "same-application-field-changed-on-both-devices".to_string(),
+ });
+ vec![local_candidate, remote_candidate]
+ }
+ }
+ (Some(base), Some(local), remote) if local.digest == base.digest => {
+ remote.cloned().into_iter().collect()
+ }
+ (Some(base), local, Some(remote)) if remote.digest == base.digest => {
+ local.cloned().into_iter().collect()
+ }
+ (Some(base), None, Some(remote)) if remote.digest == base.digest => {
+ vec![PortableEntity {
+ domain: base.domain.clone(),
+ entity_id: base.entity_id.clone(),
+ label: base.label.clone(),
+ deleted: true,
+ requires_approval: false,
+ secret_bearing: base.secret_bearing,
+ mapping_required: base.mapping_required,
+ digest: base.digest.clone(),
+ payload: base.payload.clone(),
+ resource_ids: Vec::new(),
+ }]
+ }
+ (Some(base), Some(local), None) if local.digest == base.digest => {
+ vec![PortableEntity {
+ domain: base.domain.clone(),
+ entity_id: base.entity_id.clone(),
+ label: base.label.clone(),
+ deleted: true,
+ requires_approval: false,
+ secret_bearing: base.secret_bearing,
+ mapping_required: base.mapping_required,
+ digest: base.digest.clone(),
+ payload: base.payload.clone(),
+ resource_ids: Vec::new(),
+ }]
+ }
+ (Some(base), None, None) => vec![PortableEntity {
+ domain: base.domain.clone(),
+ entity_id: base.entity_id.clone(),
+ label: base.label.clone(),
+ deleted: true,
+ requires_approval: false,
+ secret_bearing: base.secret_bearing,
+ mapping_required: base.mapping_required,
+ digest: base.digest.clone(),
+ payload: base.payload.clone(),
+ resource_ids: Vec::new(),
+ }],
+ (Some(base), local, remote) => {
+ let local = local.ok_or_else(|| anyhow::anyhow!("local merge state missing"))?;
+ let remote = remote.ok_or_else(|| anyhow::anyhow!("remote merge state missing"))?;
+ let (local_candidate, remote_candidate) = choose_conflict(local, remote);
+ conflicts.push(MergeConflict {
+ domain: base.domain.clone(),
+ entity_id: base.entity_id.clone(),
+ label: base.label.clone(),
+ local_digest: local.digest.clone(),
+ remote_digest: remote.digest.clone(),
+ reason: if local.deleted || remote.deleted {
+ "delete-versus-edit".to_string()
+ } else {
+ "same-merge-unit-changed-on-both-devices".to_string()
+ },
+ });
+ vec![local_candidate, remote_candidate]
+ }
+ };
+ entities.extend(selected);
+ }
+
+ entities.sort_by(|left, right| {
+ left.domain
+ .cmp(&right.domain)
+ .then(left.entity_id.cmp(&right.entity_id))
+ });
+ if entities.len() > 4096 {
+ bail!("CONFIG_SYNC_LIMIT_EXCEEDED: revision contains too many entities");
+ }
+ Ok(MergeResult {
+ entities,
+ conflicts,
+ })
+}
+
+pub fn snapshot_with_tombstones(
+ base: Option<&RevisionManifest>,
+ snapshot: &mut LocalSnapshot,
+ selection: &CategorySelection,
+) {
+ let Some(base) = base else {
+ return;
+ };
+ let selected: BTreeSet<(String, String)> = snapshot.manifest.entities.iter().map(key).collect();
+ for entity in &base.entities {
+ if selected.contains(&key(entity)) {
+ continue;
+ }
+ if entity.deleted {
+ // Tombstones are part of the merge input even when the local
+ // filesystem no longer has a live entity. Keeping them in the
+ // acknowledged baseline prevents a deleted item from being
+ // republished forever and lets an opted-out category rejoin with
+ // an explicit delete-versus-edit review.
+ snapshot.manifest.entities.push(entity.clone());
+ continue;
+ }
+ if selection.is_selected(&entity.domain) {
+ snapshot.manifest.entities.push(PortableEntity {
+ domain: entity.domain.clone(),
+ entity_id: entity.entity_id.clone(),
+ label: entity.label.clone(),
+ deleted: true,
+ requires_approval: entity.requires_approval,
+ secret_bearing: entity.secret_bearing,
+ mapping_required: entity.mapping_required,
+ digest: entity.digest.clone(),
+ payload: entity.payload.clone(),
+ resource_ids: Vec::new(),
+ });
+ } else {
+ // Category opt-out is a subscription policy, not a delete. Keep
+ // the last acknowledged value in the local merge input so remote
+ // changes can be carried forward without being applied locally.
+ snapshot.manifest.entities.push(entity.clone());
+ }
+ }
+ snapshot.manifest.entities.sort_by(|left, right| {
+ left.domain
+ .cmp(&right.domain)
+ .then(left.entity_id.cmp(&right.entity_id))
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn entity(id: &str, value: &str) -> PortableEntity {
+ PortableEntity {
+ domain: "test".into(),
+ entity_id: id.into(),
+ label: id.into(),
+ deleted: false,
+ requires_approval: false,
+ secret_bearing: false,
+ mapping_required: false,
+ digest: value.into(),
+ payload: serde_json::json!({ "value": value }),
+ resource_ids: vec![],
+ }
+ }
+
+ fn manifest(values: Vec<PortableEntity>) -> RevisionManifest {
+ RevisionManifest {
+ format: "test".into(),
+ version: 1,
+ revision_id: "r".into(),
+ parents: vec![],
+ created_at: "2026-01-01T00:00:00Z".into(),
+ entities: values,
+ resource_ids: vec![],
+ }
+ }
+
+ #[test]
+ fn disjoint_edits_merge_and_repeat_is_idempotent() {
+ let base = manifest(vec![entity("a", "0"), entity("b", "0")]);
+ let local = manifest(vec![entity("a", "1"), entity("b", "0")]);
+ let remote = manifest(vec![entity("a", "0"), entity("b", "2")]);
+ let merged = three_way(Some(&base), &local, Some(&remote)).expect("merge");
+ assert!(merged.conflicts.is_empty());
+ assert_eq!(merged.entities[0].digest, "1");
+ assert_eq!(merged.entities[1].digest, "2");
+ let next = manifest(merged.entities.clone());
+ let repeated = three_way(Some(&next), &next, Some(&next)).expect("repeat");
+ assert_eq!(repeated.entities, next.entities);
+ assert!(repeated.conflicts.is_empty());
+ }
+
+ #[test]
+ fn same_unit_edit_retains_both_candidates() {
+ let base = manifest(vec![entity("a", "0")]);
+ let local = manifest(vec![entity("a", "1")]);
+ let remote = manifest(vec![entity("a", "2")]);
+ let merged = three_way(Some(&base), &local, Some(&remote)).expect("merge");
+ assert_eq!(merged.conflicts.len(), 1);
+ assert_eq!(merged.entities.len(), 2);
+ assert!(merged
+ .entities
+ .iter()
+ .any(|item| item.entity_id.ends_with(":local")));
+ assert!(merged
+ .entities
+ .iter()
+ .any(|item| item.entity_id.ends_with(":remote")));
+ }
+
+ #[test]
+ fn category_opt_out_keeps_the_base_value_in_the_merge_input() {
+ let base = manifest(vec![entity("a", "0")]);
+ let mut local = LocalSnapshot {
+ manifest: manifest(vec![]),
+ resources: BTreeMap::new(),
+ };
+ let mut selection = CategorySelection::default();
+ selection.0.insert("test".into(), false);
+ snapshot_with_tombstones(Some(&base), &mut local, &selection);
+ assert_eq!(local.manifest.entities, base.entities);
+
+ let remote = manifest(vec![entity("a", "1")]);
+ let merged = three_way(Some(&base), &local.manifest, Some(&remote)).expect("merge");
+ assert_eq!(merged.entities, remote.entities);
+ assert!(merged.conflicts.is_empty());
+ }
+
+ #[test]
+ fn explicit_tombstone_deletion_converges_without_becoming_an_implicit_delete() {
+ let base = manifest(vec![entity("a", "0")]);
+ let mut deleted = entity("a", "0");
+ deleted.deleted = true;
+ let local = manifest(vec![deleted]);
+ let remote = manifest(vec![entity("a", "0")]);
+ let merged = three_way(Some(&base), &local, Some(&remote)).expect("merge");
+ assert_eq!(merged.entities.len(), 1);
+ assert!(merged.entities[0].deleted);
+
+ let next = manifest(merged.entities.clone());
+ let repeated = three_way(Some(&next), &next, Some(&next)).expect("repeat");
+ assert_eq!(repeated.entities, next.entities);
+ assert!(repeated.conflicts.is_empty());
+ }
+
+ #[test]
+ fn acknowledged_tombstones_stay_in_the_next_local_merge_input() {
+ let mut tombstone = entity("a", "0");
+ tombstone.deleted = true;
+ let base = manifest(vec![tombstone.clone()]);
+ let mut local = LocalSnapshot {
+ manifest: manifest(vec![]),
+ resources: BTreeMap::new(),
+ };
+ snapshot_with_tombstones(Some(&base), &mut local, &CategorySelection::all_selected());
+ assert_eq!(local.manifest.entities, vec![tombstone]);
+ }
+
+ #[test]
+ fn application_preferences_merge_disjoint_fields_but_conflict_on_one_field() {
+ let mut base = entity("application", "base");
+ base.domain = DOMAIN_APPLICATION.into();
+ base.payload = serde_json::json!({"theme": "dark", "language": "en"});
+ refresh_digest(&mut base);
+ let mut local = base.clone();
+ local.payload["theme"] = serde_json::json!("light");
+ refresh_digest(&mut local);
+ let mut remote = base.clone();
+ remote.payload["language"] = serde_json::json!("zh-CN");
+ refresh_digest(&mut remote);
+
+ let merged = three_way(
+ Some(&manifest(vec![base.clone()])),
+ &manifest(vec![local.clone()]),
+ Some(&manifest(vec![remote.clone()])),
+ )
+ .expect("merge disjoint settings");
+ assert!(merged.conflicts.is_empty());
+ assert_eq!(merged.entities[0].payload["theme"], "light");
+ assert_eq!(merged.entities[0].payload["language"], "zh-CN");
+
+ let mut deleted_local = base.clone();
+ deleted_local
+ .payload
+ .as_object_mut()
+ .unwrap()
+ .remove("theme");
+ refresh_digest(&mut deleted_local);
+ let deletion = three_way(
+ Some(&manifest(vec![base.clone()])),
+ &manifest(vec![deleted_local]),
+ Some(&manifest(vec![base.clone()])),
+ )
+ .expect("merge deleted setting");
+ assert!(!deletion.entities[0]
+ .payload
+ .as_object()
+ .unwrap()
+ .contains_key("theme"));
+
+ let mut conflicting_remote = base.clone();
+ conflicting_remote.payload["theme"] = serde_json::json!("system");
+ refresh_digest(&mut conflicting_remote);
+ let conflicting = three_way(
+ Some(&manifest(vec![base])),
+ &manifest(vec![local]),
+ Some(&manifest(vec![conflicting_remote])),
+ )
+ .expect("merge conflicting settings");
+ assert_eq!(conflicting.conflicts.len(), 1);
+ assert_eq!(conflicting.entities.len(), 2);
+ }
+
+ #[test]
+ fn empty_initial_application_state_adopts_remote_fields_without_conflict() {
+ let mut local = entity("application", "empty");
+ local.domain = DOMAIN_APPLICATION.into();
+ local.payload = serde_json::json!({});
+ refresh_digest(&mut local);
+ let mut remote = entity("application", "remote");
+ remote.domain = DOMAIN_APPLICATION.into();
+ remote.payload = serde_json::json!({
+ "theme": "dark",
+ "language": "zh-CN"
+ });
+ refresh_digest(&mut remote);
+
+ let merged = three_way(None, &manifest(vec![local]), Some(&manifest(vec![remote])))
+ .expect("merge initial application state");
+ assert!(merged.conflicts.is_empty());
+ assert_eq!(merged.entities.len(), 1);
+ assert_eq!(merged.entities[0].payload["theme"], "dark");
+ assert_eq!(merged.entities[0].payload["language"], "zh-CN");
+ }
+}
diff --git a/crates/host-core/src/config_sync/mod.rs b/crates/host-core/src/config_sync/mod.rs
new file mode 100644
index 000000000..5c34a1f11
--- /dev/null
+++ b/crates/host-core/src/config_sync/mod.rs
@@ -0,0 +1,11 @@
+mod crypto;
+pub(crate) mod domains;
+pub(crate) mod engine;
+pub(crate) mod merge;
+mod transport;
+
+pub(crate) use crypto::{
+ create_vault, decrypt_object, encrypt_object, object_id, rewrap_vault, unlock_vault,
+ vault_key_b64, vault_key_from_b64, VaultHeader, VaultKey,
+};
+pub(crate) use transport::{remote_error_is_offline, WebDavConfig, WebDavTransport};
diff --git a/crates/host-core/src/config_sync/transport.rs b/crates/host-core/src/config_sync/transport.rs
new file mode 100644
index 000000000..e0b7693d9
--- /dev/null
+++ b/crates/host-core/src/config_sync/transport.rs
@@ -0,0 +1,584 @@
+use anyhow::{bail, Context, Result};
+use reqwest::header::{HeaderMap, HeaderValue, ETAG, IF_MATCH, IF_NONE_MATCH, LOCATION};
+use reqwest::{Client, Method, StatusCode, Url};
+use uuid::Uuid;
+
+const MAX_REMOTE_OBJECT_BYTES: usize = 64 * 1024 * 1024;
+
+#[derive(Debug, Clone)]
+pub struct WebDavConfig {
+ pub endpoint: String,
+ pub username: String,
+ pub password: String,
+ pub directory: String,
+ pub allow_insecure_http: bool,
+}
+
+#[derive(Debug, Clone)]
+pub struct ProbeResult {
+ pub conditional_writes: bool,
+}
+
+#[derive(Debug, Clone)]
+pub struct WebDavTransport {
+ client: Client,
+ base: Url,
+ username: String,
+ password: String,
+ directory: String,
+}
+
+fn validate_relative_directory(value: &str) -> Result<String> {
+ let trimmed = value.trim().trim_matches('/');
+ if trimmed.is_empty() {
+ return Ok(String::new());
+ }
+ let mut parts = Vec::new();
+ for part in trimmed.split('/') {
+ if part.is_empty() || part == "." || part == ".." || part.contains('\\') {
+ bail!("CONFIG_SYNC_INVALID: remote directory contains an unsafe path segment");
+ }
+ if part.len() > 128
+ || !part
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | ' '))
+ {
+ bail!("CONFIG_SYNC_INVALID: remote directory contains an unsupported character");
+ }
+ parts.push(part.to_string());
+ }
+ Ok(parts.join("/"))
+}
+
+fn validate_endpoint(raw: &str, allow_insecure_http: bool) -> Result<Url> {
+ let mut url = Url::parse(raw.trim()).context("parse WebDAV endpoint")?;
+ if !matches!(url.scheme(), "https" | "http") {
+ bail!("CONFIG_SYNC_INVALID: WebDAV endpoint must use HTTPS");
+ }
+ if url.scheme() == "http" && !allow_insecure_http {
+ bail!("CONFIG_SYNC_INVALID: HTTP requires explicit LAN-risk acknowledgement");
+ }
+ if url.host_str().is_none() || !url.username().is_empty() || url.password().is_some() {
+ bail!("CONFIG_SYNC_INVALID: endpoint must not contain userinfo");
+ }
+ url.set_query(None);
+ url.set_fragment(None);
+ let path = url.path().trim_end_matches('/').to_string();
+ url.set_path(&format!("{path}/"));
+ Ok(url)
+}
+
+impl WebDavTransport {
+ pub fn new(config: &WebDavConfig) -> Result<Self> {
+ let base = validate_endpoint(&config.endpoint, config.allow_insecure_http)?;
+ let directory = validate_relative_directory(&config.directory)?;
+ let client = Client::builder()
+ .redirect(reqwest::redirect::Policy::none())
+ .https_only(false)
+ .build()
+ .context("build WebDAV client")?;
+ Ok(Self {
+ client,
+ base,
+ username: config.username.trim().to_string(),
+ password: config.password.clone(),
+ directory,
+ })
+ }
+
+ fn url(&self, relative: &str) -> Result<Url> {
+ if relative.is_empty() || relative.starts_with('/') || relative.contains("..") {
+ bail!("CONFIG_SYNC_INVALID: unsafe remote object path");
+ }
+ let prefix = if self.directory.is_empty() {
+ String::new()
+ } else {
+ format!("{}/", self.directory)
+ };
+ self.base
+ .join(&format!("{prefix}{relative}"))
+ .context("resolve WebDAV object URL")
+ }
+
+ fn authenticated(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
+ if self.username.is_empty() {
+ request
+ } else {
+ request.basic_auth(&self.username, Some(&self.password))
+ }
+ }
+
+ async fn send(
+ &self,
+ method: Method,
+ relative: &str,
+ body: Option<Vec<u8>>,
+ headers: HeaderMap,
+ ) -> Result<reqwest::Response> {
+ let url = self.url(relative)?;
+ let mut request = self.client.request(method, url).headers(headers);
+ if let Some(body) = body {
+ request = request.body(body);
+ }
+ let response = self
+ .authenticated(request)
+ .send()
+ .await
+ .context("WebDAV request failed")?;
+ if response.headers().get(LOCATION).is_some() || response.status().is_redirection() {
+ bail!("CONFIG_SYNC_SECURITY: WebDAV redirects are not permitted");
+ }
+ Ok(response)
+ }
+
+ /// Create a single collection below the configured vault directory. A
+ /// WebDAV server may report 405 when the collection already exists; that
+ /// is a successful idempotent result for this helper. We intentionally do
+ /// not follow redirects or try to infer a different root.
+ pub async fn ensure_collection(&self, relative: &str) -> Result<()> {
+ let response = self
+ .send(
+ Method::from_bytes(b"MKCOL").expect("MKCOL is a valid method"),
+ relative,
+ None,
+ HeaderMap::new(),
+ )
+ .await?;
+ match response.status() {
+ status
+ if status.is_success()
+ || status == StatusCode::METHOD_NOT_ALLOWED
+ || status == StatusCode::PRECONDITION_FAILED =>
+ {
+ Ok(())
+ }
+ status => bail!("CONFIG_SYNC_REMOTE: WebDAV collection create returned {status}"),
+ }
+ }
+
+ async fn limited_bytes(response: reqwest::Response) -> Result<Vec<u8>> {
+ if response
+ .content_length()
+ .is_some_and(|length| length > MAX_REMOTE_OBJECT_BYTES as u64)
+ {
+ bail!("CONFIG_SYNC_LIMIT_EXCEEDED: remote object is too large");
+ }
+ let mut response = response;
+ let mut result = Vec::new();
+ while let Some(chunk) = response.chunk().await.context("read WebDAV response")? {
+ if result.len().saturating_add(chunk.len()) > MAX_REMOTE_OBJECT_BYTES {
+ bail!("CONFIG_SYNC_LIMIT_EXCEEDED: remote object is too large");
+ }
+ result.extend_from_slice(&chunk);
+ }
+ Ok(result)
+ }
+
+ pub async fn get(&self, relative: &str) -> Result<Option<(Vec<u8>, Option<String>)>> {
+ let response = self
+ .send(Method::GET, relative, None, HeaderMap::new())
+ .await?;
+ if response.status() == StatusCode::NOT_FOUND {
+ return Ok(None);
+ }
+ if !response.status().is_success() {
+ bail!(
+ "CONFIG_SYNC_REMOTE: WebDAV GET returned {}",
+ response.status()
+ );
+ }
+ let etag = strong_etag(response.headers());
+ Ok(Some((Self::limited_bytes(response).await?, etag)))
+ }
+
+ pub async fn put_if_none(&self, relative: &str, body: Vec<u8>) -> Result<bool> {
+ let mut headers = HeaderMap::new();
+ headers.insert(IF_NONE_MATCH, HeaderValue::from_static("*"));
+ let response = self
+ .send(Method::PUT, relative, Some(body), headers)
+ .await?;
+ match response.status() {
+ StatusCode::PRECONDITION_FAILED => Ok(false),
+ status if status.is_success() => Ok(true),
+ status => bail!("CONFIG_SYNC_REMOTE: WebDAV create returned {status}"),
+ }
+ }
+
+ pub async fn put_if_match(&self, relative: &str, etag: &str, body: Vec<u8>) -> Result<bool> {
+ let mut headers = HeaderMap::new();
+ headers.insert(
+ IF_MATCH,
+ HeaderValue::from_str(etag).context("invalid WebDAV ETag")?,
+ );
+ let response = self
+ .send(Method::PUT, relative, Some(body), headers)
+ .await?;
+ match response.status() {
+ StatusCode::PRECONDITION_FAILED => Ok(false),
+ status if status.is_success() => Ok(true),
+ status => bail!("CONFIG_SYNC_REMOTE: WebDAV conditional write returned {status}"),
+ }
+ }
+
+ pub async fn delete(&self, relative: &str) -> Result<()> {
+ let response = self
+ .send(Method::DELETE, relative, None, HeaderMap::new())
+ .await?;
+ if response.status() != StatusCode::NOT_FOUND && !response.status().is_success() {
+ bail!(
+ "CONFIG_SYNC_REMOTE: WebDAV delete returned {}",
+ response.status()
+ );
+ }
+ Ok(())
+ }
+
+ pub async fn probe(&self) -> Result<ProbeResult> {
+ self.ensure_collection(".probe").await?;
+ let probe = format!(".probe/{}", Uuid::new_v4());
+ let first_body = b"pi-desktop-config-sync-probe".to_vec();
+ let second_body = b"pi-desktop-config-sync-probe-2".to_vec();
+ let first = self.put_if_none(&probe, first_body.clone()).await?;
+ if !first {
+ bail!("CONFIG_SYNC_REMOTE: probe object unexpectedly existed");
+ }
+ let second = self.put_if_none(&probe, second_body.clone()).await?;
+ let (strong_etag, readable) = self
+ .get(&probe)
+ .await?
+ .map(|(bytes, etag)| (etag, bytes == first_body))
+ .unwrap_or((None, false));
+ let matched_update = if let Some(etag) = strong_etag.as_deref() {
+ self.put_if_match(&probe, etag, second_body.clone())
+ .await
+ .unwrap_or(false)
+ } else {
+ false
+ };
+ let stale_rejected = if matched_update {
+ if let Some(etag) = strong_etag.as_deref() {
+ match self
+ .put_if_match(&probe, etag, b"pi-desktop-config-sync-stale".to_vec())
+ .await
+ {
+ Ok(accepted) => !accepted,
+ Err(_) => false,
+ }
+ } else {
+ false
+ }
+ } else {
+ false
+ };
+ let updated_readable = self
+ .get(&probe)
+ .await?
+ .is_some_and(|(bytes, _)| bytes == second_body);
+ self.delete(&probe).await?;
+ Ok(ProbeResult {
+ conditional_writes: !second
+ && readable
+ && matched_update
+ && stale_rejected
+ && updated_readable,
+ })
+ }
+}
+
+fn strong_etag(headers: &HeaderMap) -> Option<String> {
+ let value = headers.get(ETAG)?.to_str().ok()?.trim();
+ if value.is_empty() || value.starts_with("W/") {
+ return None;
+ }
+ Some(value.to_string())
+}
+
+pub fn remote_error_is_offline(error: &anyhow::Error) -> bool {
+ let text = error.to_string().to_lowercase();
+ text.contains("request failed")
+ || text.contains("timed out")
+ || text.contains("dns")
+ || text.contains("connect")
+}
+
+#[cfg(test)]
+pub(crate) mod tests {
+ use super::*;
+ use std::collections::{HashMap, HashSet};
+ use std::sync::{Arc, Mutex};
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ use tokio::net::{TcpListener, TcpStream};
+
+ #[derive(Default)]
+ struct FixtureState {
+ objects: HashMap<String, Vec<u8>>,
+ etags: HashMap<String, u64>,
+ collections: HashSet<String>,
+ next_etag: u64,
+ weak_etag: bool,
+ }
+
+ async fn read_request(stream: &mut TcpStream) -> Option<(String, String, HeaderMap, Vec<u8>)> {
+ let mut buffer = Vec::new();
+ let header_end;
+ loop {
+ let mut chunk = [0u8; 4096];
+ let read = stream.read(&mut chunk).await.ok()?;
+ if read == 0 {
+ return None;
+ }
+ buffer.extend_from_slice(&chunk[..read]);
+ if let Some(index) = buffer.windows(4).position(|value| value == b"\r\n\r\n") {
+ header_end = index + 4;
+ break;
+ }
+ if buffer.len() > 1024 * 1024 {
+ return None;
+ }
+ }
+ let header_text = String::from_utf8_lossy(&buffer[..header_end]).into_owned();
+ let mut lines = header_text.split("\r\n");
+ let request = lines.next()?.split_whitespace().collect::<Vec<_>>();
+ if request.len() < 2 {
+ return None;
+ }
+ let mut headers = HeaderMap::new();
+ for line in lines {
+ let Some((name, value)) = line.split_once(':') else {
+ continue;
+ };
+ let name = reqwest::header::HeaderName::from_bytes(name.trim().as_bytes()).ok()?;
+ let value = HeaderValue::from_str(value.trim()).ok()?;
+ headers.insert(name, value);
+ }
+ let content_length = headers
+ .get(reqwest::header::CONTENT_LENGTH)
+ .and_then(|value| value.to_str().ok())
+ .and_then(|value| value.parse::<usize>().ok())
+ .unwrap_or(0);
+ while buffer.len() < header_end + content_length {
+ let mut chunk = [0u8; 4096];
+ let read = stream.read(&mut chunk).await.ok()?;
+ if read == 0 {
+ return None;
+ }
+ buffer.extend_from_slice(&chunk[..read]);
+ }
+ Some((
+ request[0].to_string(),
+ request[1].to_string(),
+ headers,
+ buffer[header_end..header_end + content_length].to_vec(),
+ ))
+ }
+
+ async fn write_response(
+ stream: &mut TcpStream,
+ status: u16,
+ headers: &[(&str, String)],
+ body: &[u8],
+ ) {
+ let reason = match status {
+ 200 => "OK",
+ 201 => "Created",
+ 204 => "No Content",
+ 404 => "Not Found",
+ 405 => "Method Not Allowed",
+ 412 => "Precondition Failed",
+ _ => "Bad Request",
+ };
+ let mut response = format!(
+ "HTTP/1.1 {status} {reason}\r\nContent-Length: {}\r\nConnection: close\r\n",
+ body.len()
+ );
+ for (name, value) in headers {
+ response.push_str(&format!("{name}: {value}\r\n"));
+ }
+ response.push_str("\r\n");
+ let _ = stream.write_all(response.as_bytes()).await;
+ let _ = stream.write_all(body).await;
+ }
+
+ async fn handle_fixture_connection(mut stream: TcpStream, state: Arc<Mutex<FixtureState>>) {
+ let Some((method, target, headers, body)) = read_request(&mut stream).await else {
+ return;
+ };
+ let path = target.split('?').next().unwrap_or(&target).to_string();
+ let response = {
+ let mut state = state.lock().expect("fixture state");
+ match method.as_str() {
+ "MKCOL" => {
+ if state.collections.insert(path) {
+ (201, Vec::new(), None)
+ } else {
+ (405, Vec::new(), None)
+ }
+ }
+ "GET" => {
+ if let Some(value) = state.objects.get(&path) {
+ let etag = state.etags.get(&path).copied().unwrap_or_default();
+ let etag = if state.weak_etag {
+ format!("W/\"{etag}\"")
+ } else {
+ format!("\"{etag}\"")
+ };
+ (200, value.clone(), Some(etag))
+ } else {
+ (404, Vec::new(), None)
+ }
+ }
+ "PUT" => {
+ let existing = state.objects.contains_key(&path);
+ let none_match = headers
+ .get(IF_NONE_MATCH)
+ .and_then(|value| value.to_str().ok())
+ .is_some_and(|value| value == "*");
+ let match_ok = headers
+ .get(IF_MATCH)
+ .and_then(|value| value.to_str().ok())
+ .and_then(|value| value.trim_matches('"').parse::<u64>().ok())
+ .is_some_and(|expected| state.etags.get(&path) == Some(&expected));
+ if (none_match && existing) || (headers.contains_key(IF_MATCH) && !match_ok) {
+ (412, Vec::new(), None)
+ } else {
+ state.next_etag = state.next_etag.saturating_add(1);
+ let etag = state.next_etag;
+ state.objects.insert(path.clone(), body);
+ state.etags.insert(path, etag);
+ (201, Vec::new(), None)
+ }
+ }
+ "DELETE" => {
+ state.objects.remove(&path);
+ state.etags.remove(&path);
+ (204, Vec::new(), None)
+ }
+ _ => (400, Vec::new(), None),
+ }
+ };
+ let response_headers = response
+ .2
+ .into_iter()
+ .map(|etag| ("ETag", etag))
+ .collect::<Vec<_>>();
+ write_response(&mut stream, response.0, &response_headers, &response.1).await;
+ }
+
+ pub(crate) struct Fixture {
+ pub(crate) endpoint: String,
+ pub(crate) task: tokio::task::JoinHandle<()>,
+ }
+
+ pub(crate) async fn fixture(weak_etag: bool) -> Fixture {
+ let listener = TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind fixture");
+ let address = listener.local_addr().expect("fixture address");
+ let state = Arc::new(Mutex::new(FixtureState {
+ weak_etag,
+ ..FixtureState::default()
+ }));
+ let task = tokio::spawn(async move {
+ loop {
+ let Ok((stream, _)) = listener.accept().await else {
+ break;
+ };
+ tokio::spawn(handle_fixture_connection(stream, state.clone()));
+ }
+ });
+ Fixture {
+ endpoint: format!("http://{address}/"),
+ task,
+ }
+ }
+
+ fn fixture_transport(endpoint: &str) -> WebDavTransport {
+ WebDavTransport::new(&WebDavConfig {
+ endpoint: endpoint.to_string(),
+ username: String::new(),
+ password: String::new(),
+ directory: "vault".into(),
+ allow_insecure_http: true,
+ })
+ .expect("transport")
+ }
+
+ #[test]
+ fn endpoint_requires_https_unless_explicitly_acknowledged() {
+ assert!(validate_endpoint("http://dav.example.test/root", false).is_err());
+ assert!(validate_endpoint("http://dav.example.test/root", true).is_ok());
+ assert!(validate_endpoint("https://user:[email protected]/root", true).is_err());
+ }
+
+ #[test]
+ fn remote_directory_rejects_traversal_and_unsafe_names() {
+ assert!(validate_relative_directory("vault/../escape").is_err());
+ assert!(validate_relative_directory("vault\\escape").is_err());
+ assert!(validate_relative_directory("vault/%secret").is_err());
+ assert_eq!(
+ validate_relative_directory("/pi-desktop/config/").expect("safe directory"),
+ "pi-desktop/config"
+ );
+ }
+
+ #[test]
+ fn weak_etags_are_not_accepted_for_head_cas() {
+ let mut headers = HeaderMap::new();
+ headers.insert(ETAG, HeaderValue::from_static("W/\"weak\""));
+ assert_eq!(strong_etag(&headers), None);
+ headers.insert(ETAG, HeaderValue::from_static("\"strong\""));
+ assert_eq!(strong_etag(&headers).as_deref(), Some("\"strong\""));
+ }
+
+ #[tokio::test]
+ async fn local_fixture_proves_conditional_writes() {
+ let fixture = fixture(false).await;
+ let transport = fixture_transport(&fixture.endpoint);
+ assert!(transport.probe().await.expect("probe").conditional_writes);
+ fixture.task.abort();
+ }
+
+ #[tokio::test]
+ async fn empty_vault_initialization_has_one_winner() {
+ let fixture = fixture(false).await;
+ let transport = fixture_transport(&fixture.endpoint);
+ let first = transport.put_if_none("header", b"first".to_vec());
+ let second = transport.put_if_none("header", b"second".to_vec());
+ let (first, second) = tokio::join!(first, second);
+ let winners = [first.expect("first"), second.expect("second")]
+ .into_iter()
+ .filter(|value| *value)
+ .count();
+ assert_eq!(winners, 1);
+ fixture.task.abort();
+ }
+
+ #[tokio::test]
+ async fn stale_cas_writer_is_rejected() {
+ let fixture = fixture(false).await;
+ let transport = fixture_transport(&fixture.endpoint);
+ assert!(transport
+ .put_if_none("head", b"first".to_vec())
+ .await
+ .expect("create"));
+ let (_, etag) = transport.get("head").await.expect("get").expect("head");
+ let etag = etag.expect("strong etag");
+ assert!(transport
+ .put_if_match("head", &etag, b"second".to_vec())
+ .await
+ .expect("matching update"));
+ assert!(!transport
+ .put_if_match("head", &etag, b"stale".to_vec())
+ .await
+ .expect("stale update"));
+ fixture.task.abort();
+ }
+
+ #[tokio::test]
+ async fn weak_etag_fixture_is_not_accepted_by_probe() {
+ let fixture = fixture(true).await;
+ let transport = fixture_transport(&fixture.endpoint);
+ assert!(!transport.probe().await.expect("probe").conditional_writes);
+ fixture.task.abort();
+ }
+}
diff --git a/crates/host-core/src/main.rs b/crates/host-core/src/main.rs
index d3ab8eadd..2ebcc1a68 100644
--- a/crates/host-core/src/main.rs
+++ b/crates/host-core/src/main.rs
@@ -2,6 +2,7 @@ mod activation;
mod agent_capabilities;
mod artifacts;
mod audit;
+mod config_sync;
mod db;
mod keyboard;
mod mcp_servers;
diff --git a/crates/host-core/src/providers.rs b/crates/host-core/src/providers.rs
index e13f38ea5..87c0f15ff 100644
--- a/crates/host-core/src/providers.rs
+++ b/crates/host-core/src/providers.rs
@@ -25,6 +25,7 @@ pub use model::{
ProviderUpdateInput,
};
pub use order::{reorder_providers, ProviderReorderInput};
+pub(crate) use repository::create_provider_with_id;
pub use repository::{
create_provider, delete_provider, get_provider, list_providers, set_provider_secret,
update_provider,
diff --git a/crates/host-core/src/providers/repository.rs b/crates/host-core/src/providers/repository.rs
index 934e9e5ca..b99410678 100644
--- a/crates/host-core/src/providers/repository.rs
+++ b/crates/host-core/src/providers/repository.rs
@@ -160,6 +160,99 @@ pub fn create_provider(
get_provider(db, secrets, &id)?.ok_or_else(|| anyhow::anyhow!("provider missing after create"))
}
+/// Import a user-owned provider while preserving its stable id. Ordinary
+/// settings flows continue to use `create_provider` and receive a fresh UUID;
+/// configuration sync is the only caller allowed to restore an existing id so
+/// repeated imports do not create duplicate provider identities.
+pub(crate) fn create_provider_with_id(
+ db: &Database,
+ secrets: &SecretStore,
+ id: &str,
+ input: ProviderCreateInput,
+) -> Result<ProviderPublic> {
+ if id.trim().is_empty() || id.len() > 128 {
+ bail!("PROVIDER_INVALID: provider id is invalid");
+ }
+ if db
+ .conn()
+ .query_row("SELECT 1 FROM providers WHERE id = ?1", params![id], |_| {
+ Ok(())
+ })
+ .optional()?
+ .is_some()
+ {
+ bail!("PROVIDER_INVALID: provider already exists");
+ }
+ if let Some(models) = input.models.as_deref() {
+ validate_model_aliases(models)?;
+ }
+ let now = now_ms();
+ let secret_ref = secret_ref_for_provider(id);
+ let mut backend = None;
+ if let Some(secret) = input.secret_value.as_ref().filter(|s| !s.is_empty()) {
+ let value = secrets.set(&secret_ref, secret)?;
+ upsert_secret_meta(db, &secret_ref, id, &value)?;
+ backend = Some(value);
+ }
+ let vendor_key = input.vendor_key.unwrap_or_else(|| "custom".into());
+ let provider_type = input
+ .provider_type
+ .unwrap_or_else(|| "openai_compatible".into());
+ let protocol = input.protocol.unwrap_or_else(|| "openai_compatible".into());
+ let auth_kind = input
+ .auth_kind
+ .unwrap_or_else(|| "api_key_and_base_url".into());
+ let config_json = build_provider_config_json(
+ input.supports_reasoning,
+ input.supported_thinking_levels.as_deref(),
+ input.models.as_deref(),
+ &LimitOverrides {
+ context_window: input.context_window,
+ max_output_tokens: input.max_output_tokens,
+ temperature: input.temperature,
+ },
+ )?;
+ let config_json = match input.oauth_account_label.as_deref() {
+ Some(label) => config_with_oauth_account_label(&config_json, label)?,
+ None => config_json,
+ };
+ let config_json = match input.headers.as_ref() {
+ Some(headers) => config_with_headers(&config_json, headers)?,
+ None => config_json,
+ };
+ db.conn()
+ .prepare_cached(
+ "INSERT INTO providers (
+ id, name, vendor_key, type, protocol, enabled, base_url, auth_kind, secret_ref,
+ api_style, default_model_id, config_json, created_at, updated_at
+ ) VALUES (?1, ?2, ?3, ?4, ?5, 1, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?12)",
+ )?
+ .execute(params![
+ id,
+ input.name,
+ vendor_key,
+ provider_type,
+ protocol,
+ input.base_url,
+ auth_kind,
+ if backend.is_some() {
+ Some(secret_ref)
+ } else {
+ None
+ },
+ input.api_style,
+ input.default_model_id.or_else(|| {
+ input
+ .models
+ .as_ref()
+ .and_then(|models| models.first().map(|model| model.id.clone()))
+ }),
+ config_json,
+ now,
+ ])?;
+ get_provider(db, secrets, id)?.ok_or_else(|| anyhow::anyhow!("provider missing after import"))
+}
+
pub fn update_provider(
db: &Database,
secrets: &SecretStore,
diff --git a/crates/host-core/src/rpc/config_sync_rpc.rs b/crates/host-core/src/rpc/config_sync_rpc.rs
new file mode 100644
index 000000000..c48a08a8d
--- /dev/null
+++ b/crates/host-core/src/rpc/config_sync_rpc.rs
@@ -0,0 +1,36 @@
+use crate::config_sync::engine;
+use crate::state::AppState;
+use anyhow::Result;
+use serde_json::Value;
+use std::sync::Arc;
+use tokio::sync::{mpsc, Mutex};
+
+pub(crate) async fn handle(
+ state: Arc<Mutex<AppState>>,
+ method: &str,
+ params: Value,
+ tx: mpsc::UnboundedSender<String>,
+) -> Result<Value> {
+ match method {
+ "configSync.getState" => engine::get_state(state).await,
+ "configSync.test" => engine::test(state, params).await,
+ "configSync.configure" => engine::configure(state, params).await,
+ "configSync.syncNow" => engine::sync_now(state, tx).await,
+ "configSync.pause" => {
+ let paused = params
+ .get("paused")
+ .and_then(Value::as_bool)
+ .unwrap_or(true);
+ engine::pause(state, paused).await
+ }
+ "configSync.unlock" => engine::unlock(state, params).await,
+ "configSync.approve" => engine::approve(state, params, tx).await,
+ "configSync.reject" => engine::reject(state, params, tx).await,
+ "configSync.mapProject" => engine::map_project(state, params).await,
+ "configSync.listHistory" => engine::list_history(state).await,
+ "configSync.restore" => engine::restore(state, params, tx).await,
+ "configSync.changePassword" => engine::change_password(state, params).await,
+ "configSync.disconnect" => engine::disconnect(state).await,
+ _ => anyhow::bail!("CONFIG_SYNC_INVALID: unknown config sync method"),
+ }
+}
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 36ac9a85e..9d5b5d9bc 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -1,3 +1,4 @@
+mod config_sync_rpc;
mod scheduled_rpc;
mod scheduled_tools;
@@ -312,6 +313,23 @@ pub async fn serve(state: Arc<Mutex<AppState>>) -> Result<()> {
return Err(anyhow!("host stdin reader unavailable: {error}"));
}
};
+ let config_sync_scheduler = tokio::spawn({
+ let state = state.clone();
+ let tx = tx.clone();
+ async move {
+ // The host owns a short local debounce clock; remote polling is
+ // gated inside the engine to five minutes when no local change is
+ // pending. This lets a quiet app settle filesystem edits without
+ // turning every tick into a WebDAV request.
+ let mut interval = tokio::time::interval(Duration::from_secs(30));
+ interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
+ loop {
+ interval.tick().await;
+ let _ =
+ crate::config_sync::engine::sync_if_enabled(state.clone(), tx.clone()).await;
+ }
+ }
+ });
let mut input_error = None;
let mut writer_done = false;
@@ -435,6 +453,8 @@ pub async fn serve(state: Arc<Mutex<AppState>>) -> Result<()> {
}
}
+ config_sync_scheduler.abort();
+ let _ = config_sync_scheduler.await;
{
let mut st = state.lock().await;
st.shutdown();
@@ -471,6 +491,26 @@ fn rpc_err(code: i64, message: impl Into<String>, error_code: &str) -> JsonRpcEr
}
}
+fn config_sync_rpc_err(error: impl ToString) -> JsonRpcError {
+ let message = error.to_string();
+ let error_code = message
+ .split_once(':')
+ .map(|(code, _)| code.trim())
+ .unwrap_or("INTERNAL")
+ .to_string();
+ let code = match error_code.as_str() {
+ "CONFIG_SYNC_INVALID" | "CONFIG_SYNC_LIMIT_EXCEEDED" => 1002,
+ "CONFIG_SYNC_LOCKED" => 1001,
+ "CONFIG_SYNC_CONFLICT" => 1008,
+ "CONFIG_SYNC_UNSUPPORTED" => 1002,
+ "CONFIG_SYNC_SECURITY" => 1003,
+ "CONFIG_SYNC_CRYPTO" | "CONFIG_SYNC_MAPPING_REQUIRED" => 1002,
+ "CONFIG_SYNC_REMOTE" => 1000,
+ _ => 1000,
+ };
+ rpc_err(code, message, &error_code)
+}
+
fn provider_rpc_err(error: impl ToString) -> JsonRpcError {
let message = error.to_string();
for error_code in ["MODEL_ALIAS_TOO_LONG", "MODEL_BINDINGS_DEGRADED"] {
@@ -1421,6 +1461,12 @@ async fn handle_request(
}
}
+ if method.starts_with("configSync.") {
+ return config_sync_rpc::handle(state, method, params, tx)
+ .await
+ .map_err(config_sync_rpc_err);
+ }
+
match method {
method if method.starts_with("session.collaboration.") => {
let st = state.lock().await;
diff --git a/crates/host-core/src/state.rs b/crates/host-core/src/state.rs
index 2303f63dd..ffe261620 100644
--- a/crates/host-core/src/state.rs
+++ b/crates/host-core/src/state.rs
@@ -1,4 +1,5 @@
use std::collections::HashMap;
+use std::sync::{atomic::AtomicBool, Arc};
use std::time::{Duration, Instant};
use anyhow::Result;
@@ -38,6 +39,12 @@ pub struct AppState {
/// Subagent definitions the user owns, alongside the builtin and per-project
/// ones the runtime discovers itself (D202).
pub user_subagents: UserSubagentRegistry,
+ /// One reconciliation worker per local vault. The lock is separate from
+ /// the AppState mutex so WebDAV I/O never monopolizes the host state lock.
+ pub config_sync_lock: Arc<tokio::sync::Mutex<()>>,
+ /// Process-local status for the single active sync worker. It is never
+ /// persisted and only drives the renderer's transient "syncing" state.
+ pub config_sync_in_progress: Arc<AtomicBool>,
pub started_at: Instant,
pub handshook: bool,
pub shutting_down: bool,
@@ -125,6 +132,8 @@ impl AppState {
mcp_servers,
user_skills,
user_subagents,
+ config_sync_lock: Arc::new(tokio::sync::Mutex::new(())),
+ config_sync_in_progress: Arc::new(AtomicBool::new(false)),
started_at: Instant::now(),
handshook: false,
shutting_down: false,
diff --git a/crates/host-core/src/user_skills.rs b/crates/host-core/src/user_skills.rs
index df71c9f53..aada6e248 100644
--- a/crates/host-core/src/user_skills.rs
+++ b/crates/host-core/src/user_skills.rs
@@ -10,9 +10,12 @@ use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
+use uuid::Uuid;
const MAX_SKILLS: usize = 128;
pub const MAX_SKILL_BYTES: usize = 128 * 1024;
+pub const MAX_SKILL_PACKAGE_FILES: usize = 64;
+pub const MAX_SKILL_PACKAGE_BYTES: usize = 512 * 1024;
const MAX_NAME_CHARS: usize = 120;
const MAX_DESCRIPTION_CHARS: usize = 400;
const SKILL_KIND: &str = "skills";
@@ -443,6 +446,152 @@ fn same_document(record_path: &str, planned: &Path) -> bool {
.eq_ignore_ascii_case(&normalize_project_path(&planned.to_string_lossy()))
}
+fn package_root(
+ record: &UserSkillRecord,
+ level: CapabilityLevel,
+ project_path: Option<&str>,
+) -> Result<Option<PathBuf>> {
+ let skills_dir = capability_dir(level, project_path, SKILL_KIND)?;
+ let path = PathBuf::from(&record.path);
+ if !path
+ .file_name()
+ .and_then(|value| value.to_str())
+ .is_some_and(|value| value.eq_ignore_ascii_case("SKILL.md"))
+ {
+ return Ok(None);
+ }
+ let Some(root) = path.parent() else {
+ return Ok(None);
+ };
+ if root == skills_dir {
+ return Ok(None);
+ }
+ let metadata = fs::symlink_metadata(root)
+ .with_context(|| format!("inspect skill package {}", root.display()))?;
+ if metadata.file_type().is_symlink() || !metadata.is_dir() {
+ bail!("SKILL_INVALID: skill package root must be a real directory");
+ }
+ Ok(Some(root.to_path_buf()))
+}
+
+fn package_relative_path(root: &Path, path: &Path) -> Result<String> {
+ let relative = path
+ .strip_prefix(root)
+ .map_err(|_| anyhow::anyhow!("SKILL_INVALID: package path escapes its root"))?;
+ let mut components = Vec::new();
+ for component in relative.components() {
+ let std::path::Component::Normal(value) = component else {
+ bail!("SKILL_INVALID: package path contains traversal");
+ };
+ let value = value
+ .to_str()
+ .ok_or_else(|| anyhow::anyhow!("SKILL_INVALID: package path is not UTF-8"))?;
+ if value.is_empty() || value.contains(['/', '\\']) {
+ bail!("SKILL_INVALID: package path contains an unsafe name");
+ }
+ components.push(value.to_string());
+ }
+ if components.is_empty() {
+ bail!("SKILL_INVALID: package path is empty");
+ }
+ Ok(components.join("/"))
+}
+
+fn collect_package_files(
+ root: &Path,
+ current: &Path,
+ result: &mut Vec<(String, Vec<u8>)>,
+ total: &mut usize,
+) -> Result<()> {
+ if result.len() > MAX_SKILL_PACKAGE_FILES {
+ bail!("SKILL_LIMIT_EXCEEDED: skill package contains too many files");
+ }
+ for entry in fs::read_dir(current)? {
+ let entry = entry?;
+ let path = entry.path();
+ let metadata = fs::symlink_metadata(&path)?;
+ if metadata.file_type().is_symlink() {
+ bail!("SKILL_INVALID: skill packages cannot contain symbolic links");
+ }
+ if metadata.is_dir() {
+ collect_package_files(root, &path, result, total)?;
+ continue;
+ }
+ if !metadata.is_file() {
+ bail!("SKILL_INVALID: skill package contains a non-file entry");
+ }
+ if path
+ .file_name()
+ .and_then(|value| value.to_str())
+ .is_some_and(|value| value.eq_ignore_ascii_case("SKILL.md"))
+ {
+ continue;
+ }
+ let relative = package_relative_path(root, &path)?;
+ let bytes = fs::read(&path)?;
+ if bytes.len() > MAX_SKILL_BYTES {
+ bail!("SKILL_LIMIT_EXCEEDED: skill package resource is too large");
+ }
+ *total = total.saturating_add(bytes.len());
+ if *total > MAX_SKILL_PACKAGE_BYTES {
+ bail!("SKILL_LIMIT_EXCEEDED: skill package is too large");
+ }
+ result.push((relative, bytes));
+ if result.len() > MAX_SKILL_PACKAGE_FILES {
+ bail!("SKILL_LIMIT_EXCEEDED: skill package contains too many files");
+ }
+ }
+ Ok(())
+}
+
+fn package_destination(root: &Path, relative: &str) -> Result<PathBuf> {
+ if relative.is_empty()
+ || relative.starts_with('/')
+ || relative.starts_with('\\')
+ || relative.contains('\\')
+ {
+ bail!("SKILL_INVALID: package path is unsafe");
+ }
+ let mut target = root.to_path_buf();
+ let mut count = 0usize;
+ for component in relative.split('/') {
+ if component.is_empty() || component == "." || component == ".." {
+ bail!("SKILL_INVALID: package path contains traversal");
+ }
+ count += 1;
+ target.push(component);
+ }
+ if count == 0
+ || target
+ .file_name()
+ .and_then(|value| value.to_str())
+ .is_some_and(|value| value.eq_ignore_ascii_case("SKILL.md"))
+ {
+ bail!("SKILL_INVALID: package path targets the skill document");
+ }
+ Ok(target)
+}
+
+fn ensure_no_symlink_path(root: &Path, target: &Path) -> Result<()> {
+ let relative = target
+ .strip_prefix(root)
+ .map_err(|_| anyhow::anyhow!("SKILL_INVALID: package path escapes its root"))?;
+ let mut current = root.to_path_buf();
+ for component in relative.components() {
+ let std::path::Component::Normal(value) = component else {
+ bail!("SKILL_INVALID: package path contains traversal");
+ };
+ current.push(value);
+ if current.exists() {
+ let metadata = fs::symlink_metadata(&current)?;
+ if metadata.file_type().is_symlink() {
+ bail!("SKILL_INVALID: skill package path cannot traverse a symbolic link");
+ }
+ }
+ }
+ Ok(())
+}
+
impl UserSkillRegistry {
/// Move one skill between the global directory and a project's.
///
@@ -757,7 +906,17 @@ impl UserSkillRegistry {
bail!("SKILL_INVALID: document exceeds {MAX_SKILL_BYTES} bytes");
}
fs::create_dir_all(&directory)?;
- let path = directory.join(format!("{id}.md"));
+ let path = if input
+ .shape
+ .as_deref()
+ .is_some_and(|shape| matches!(shape, "dir" | "directory"))
+ {
+ let package = directory.join(&id);
+ fs::create_dir_all(&package)?;
+ package.join("SKILL.md")
+ } else {
+ directory.join(format!("{id}.md"))
+ };
fs::write(&path, &document).with_context(|| format!("write {}", path.display()))?;
if input.enabled == Some(false) {
self.state
@@ -1022,6 +1181,101 @@ impl UserSkillRegistry {
Ok(Some((record, body)))
}
+ /// Read bounded sibling resources from a directory-shaped skill. The
+ /// skill document itself is captured separately so its body can retain the
+ /// existing update/import semantics.
+ pub fn package_files(
+ &mut self,
+ id: &str,
+ level: CapabilityLevel,
+ project_path: Option<&str>,
+ ) -> Result<Vec<(String, Vec<u8>)>> {
+ let Some(record) = self.find(id, Some(level), project_path)? else {
+ return Ok(Vec::new());
+ };
+ let Some(root) = package_root(&record, level, project_path)? else {
+ return Ok(Vec::new());
+ };
+ let mut result = Vec::new();
+ let mut total = 0usize;
+ collect_package_files(&root, &root, &mut result, &mut total)?;
+ result.sort_by(|left, right| left.0.cmp(&right.0));
+ Ok(result)
+ }
+
+ /// Apply approved, bounded package resources inside the Host-owned skill
+ /// directory. Existing files with different bytes are treated as an
+ /// external edit instead of being overwritten blindly; omitted files are
+ /// retained for the same reason.
+ pub fn write_package_files(
+ &mut self,
+ id: &str,
+ level: CapabilityLevel,
+ project_path: Option<&str>,
+ files: &[(String, Vec<u8>)],
+ ) -> Result<()> {
+ if files.len() > MAX_SKILL_PACKAGE_FILES {
+ bail!("SKILL_LIMIT_EXCEEDED: skill package contains too many files");
+ }
+ let total = files.iter().try_fold(0usize, |total, (_, bytes)| {
+ total
+ .checked_add(bytes.len())
+ .ok_or_else(|| anyhow::anyhow!("SKILL_LIMIT_EXCEEDED: skill package is too large"))
+ })?;
+ if total > MAX_SKILL_PACKAGE_BYTES {
+ bail!("SKILL_LIMIT_EXCEEDED: skill package is too large");
+ }
+ if files.is_empty() {
+ return Ok(());
+ }
+ let Some(record) = self.find(id, Some(level), project_path)? else {
+ bail!("SKILL_INVALID: skill package target was not found");
+ };
+ let Some(root) = package_root(&record, level, project_path)? else {
+ bail!("SKILL_INVALID: package resources require a directory-shaped skill");
+ };
+ let root_metadata = fs::symlink_metadata(&root)?;
+ if root_metadata.file_type().is_symlink() || !root_metadata.is_dir() {
+ bail!("SKILL_INVALID: skill package root is unsafe");
+ }
+ let mut seen = HashSet::new();
+ for (relative, bytes) in files {
+ let target = package_destination(&root, relative)?;
+ if !seen.insert(relative.clone()) {
+ bail!("SKILL_INVALID: skill package contains duplicate paths");
+ }
+ if bytes.len() > MAX_SKILL_BYTES {
+ bail!("SKILL_LIMIT_EXCEEDED: skill package resource is too large");
+ }
+ ensure_no_symlink_path(&root, &target)?;
+ if target.exists() {
+ let metadata = fs::symlink_metadata(&target)?;
+ if metadata.file_type().is_symlink() || !metadata.is_file() {
+ bail!("SKILL_INVALID: skill package destination is unsafe");
+ }
+ if fs::read(&target)? == *bytes {
+ continue;
+ }
+ bail!("CONFIG_SYNC_CONFLICT: skill package resource was edited locally");
+ }
+ if let Some(parent) = target.parent() {
+ fs::create_dir_all(parent)?;
+ ensure_no_symlink_path(&root, parent)?;
+ }
+ let temporary = target.with_file_name(format!(
+ ".{}.{}.tmp",
+ target
+ .file_name()
+ .and_then(|value| value.to_str())
+ .unwrap_or("resource"),
+ Uuid::new_v4()
+ ));
+ fs::write(&temporary, bytes)?;
+ fs::rename(&temporary, &target)?;
+ }
+ Ok(())
+ }
+
pub fn remove(
&mut self,
id: &str,
diff --git a/crates/host-core/src/user_skills/tests.rs b/crates/host-core/src/user_skills/tests.rs
index 3e7534d49..fe30b3c2f 100644
--- a/crates/host-core/src/user_skills/tests.rs
+++ b/crates/host-core/src/user_skills/tests.rs
@@ -829,3 +829,58 @@ fn shape_dir_requires_a_directory_source() {
"err = {err}"
);
}
+
+#[test]
+fn directory_skill_package_resources_round_trip_without_execution() {
+ let app = tempdir().unwrap();
+ let project = app.path().join("project");
+ fs::create_dir_all(&project).unwrap();
+ let mut registry = UserSkillRegistry::new(app.path());
+ let mut payload = input("Packaged", "project", Some(project.to_str().unwrap()));
+ payload.id = Some("packaged".into());
+ payload.shape = Some("dir".into());
+ let record = registry.create(payload).unwrap();
+ registry
+ .write_package_files(
+ &record.id,
+ CapabilityLevel::Project,
+ Some(project.to_str().unwrap()),
+ &[("scripts/check.txt".into(), b"safe bytes".to_vec())],
+ )
+ .unwrap();
+ let files = registry
+ .package_files(
+ &record.id,
+ CapabilityLevel::Project,
+ Some(project.to_str().unwrap()),
+ )
+ .unwrap();
+ assert_eq!(
+ files,
+ vec![("scripts/check.txt".into(), b"safe bytes".to_vec())]
+ );
+ assert!(record.path.ends_with("SKILL.md"));
+}
+
+#[test]
+fn directory_skill_package_rejects_traversal() {
+ let app = tempdir().unwrap();
+ let project = app.path().join("project");
+ fs::create_dir_all(&project).unwrap();
+ let mut registry = UserSkillRegistry::new(app.path());
+ let mut payload = input("Packaged", "project", Some(project.to_str().unwrap()));
+ payload.id = Some("packaged".into());
+ payload.shape = Some("dir".into());
+ let record = registry.create(payload).unwrap();
+ let error = registry
+ .write_package_files(
+ &record.id,
+ CapabilityLevel::Project,
+ Some(project.to_str().unwrap()),
+ &[("../outside.txt".into(), b"unsafe".to_vec())],
+ )
+ .unwrap_err()
+ .to_string();
+ assert!(error.contains("SKILL_INVALID"));
+ assert!(!app.path().join("outside.txt").exists());
+}
diff --git a/docs/adr/0300-host-owned-encrypted-portable-configuration-sync.md b/docs/adr/0300-host-owned-encrypted-portable-configuration-sync.md
new file mode 100644
index 000000000..30fe25c83
--- /dev/null
+++ b/docs/adr/0300-host-owned-encrypted-portable-configuration-sync.md
@@ -0,0 +1,79 @@
+# ADR 0300: Host-owned encrypted portable configuration sync
+
+- Status: Accepted for implementation
+- Date: 2026-09-22
+
+## Context
+
+PI-Desktop has portable preferences and user-owned capabilities spread across
+Rust-owned SQLite, capability files, the host secret store, project groups,
+and plugin metadata. Copying the database or the local secrets directory would
+export device state, break ownership boundaries, and could activate executable
+content on another machine. A cloud backup must also converge concurrent
+edits without trusting WebDAV timestamps or silently replacing local data.
+
+## Decision
+
+Add a host-core configuration-sync subsystem. It uses explicit per-domain
+capture and apply adapters, encrypted immutable revision/resource objects, an
+encrypted CAS head, and the existing host secret store for the WebDAV password
+and local vault-key reference. Argon2id derives a wrapping key from a separate
+backup password; AES-256-GCM authenticates every stored object with
+purpose/vault-derived object keys and domain-separated associated data.
+
+The renderer receives only typed status, preview, conflict, and activation
+summaries. Electron Main is a thin lifecycle/transport bridge. Portable
+secrets require explicit opt-in; OAuth sessions, cookies, local encryption
+keys, readiness flags, plugin binaries, arbitrary files, and local paths are
+not portable. App-managed instructions are limited to the fixed global
+`~/.pi/agent/AGENTS.md` and registered project-root `AGENTS.md` files; nested
+repository files are not scanned. Imported executable or security-sensitive content remains
+staged until the receiving device approves the entity digest. Project and
+workspace bindings are local overlays and require explicit mapping. Standalone
+project identities are assigned and retained by Host metadata; project-group
+roots use the portable group identity plus ordered root position, so absolute
+folder paths never become cross-device identity.
+
+WebDAV initialization and head publication require reliable conditional writes:
+`If-None-Match: *` for creation and strong-ETag `If-Match` for updates. A CAS
+failure restarts reconciliation. Servers that cannot prove this capability are
+reported as unsupported rather than silently using last-writer-wins.
+
+## Consequences
+
+Positive:
+
+- The renderer and Agent Runtime never gain direct access to WebDAV,
+ encryption keys, or raw exported secrets.
+- Existing local persistence owners remain authoritative; no parallel provider,
+ MCP, skill, or subagent database is introduced.
+- Immutable revisions allow authenticated recovery and deterministic three-way
+ merge, while category opt-out remains subscription policy rather than a
+ remote delete.
+- A fresh device cannot activate a synchronized command, endpoint, script, or
+ automation without local review.
+
+Costs and limits:
+
+- A malicious WebDAV server can still deny availability or roll back a fresh
+ device that has no trusted head history; this design protects
+ confidentiality and integrity, not availability.
+- Folder mappings support ordered multi-root project groups. History/restore,
+ backup-password rewrap, bounded Skill package resources, and an in-process
+ WebDAV conditional-write fixture are part of the Host-owned baseline. A
+ restore creates a new revision and a local recovery point; it does not make
+ an old copied vault key revocable.
+- Strong conditional-write behavior is stricter than many simple WebDAV
+ servers; backup-only behavior must be labeled and must not pretend to be
+ bidirectional sync.
+
+## Alternatives rejected
+
+1. Exporting SQLite or the application data directory: violates ownership,
+ leaks device-specific state, and cannot express approval or merge policy.
+2. Uploading a plaintext JSON backup: exposes all configuration and secrets to
+ the WebDAV server and every transport intermediary.
+3. Last-writer-wins based on wall-clock timestamps: loses edits under clock
+ skew and cannot safely resolve delete-versus-edit or executable changes.
+4. Scheduling synchronization in Electron Main or the renderer: creates a
+ second owner for sync lifecycle and weakens host durability guarantees.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 4293dffbe..fa77d818c 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -328,6 +328,7 @@ Each ADR includes:
| 0297 | [Provider-hosted web search as an adapter capability](0297-provider-hosted-web-search-adapter-capability.md) | Accepted |
| 0298 | [The app ships no fonts](0298-remove-bundled-fonts.md) | Accepted (D598; amends ADR 0083 / D232) |
| 0299 | [Subagent context budget and delegate compaction](0299-subagent-context-budget.md) | Accepted for implementation (amends ADR 0064; extends ADR 0062 / ADR 0279) |
+| 0300 | [Host-owned encrypted portable configuration sync](0300-host-owned-encrypted-portable-configuration-sync.md) | Accepted for implementation |
| turn-process-and-thinking-display | [Turn process and thinking presentation](turn-process-and-thinking-display.md) | Accepted |
| provider-display-order | [Provider display order](provider-display-order.md) | Accepted |
| registry-header-variable-spelling | [Remote header variables accept the registry's `{name}` spelling](registry-header-variable-spelling.md) | Proposed |
diff --git a/docs/architecture/allowlist.json b/docs/architecture/allowlist.json
index 10041d47f..b47f432e6 100644
--- a/docs/architecture/allowlist.json
+++ b/docs/architecture/allowlist.json
@@ -13,6 +13,7 @@
"crates/host-core/src/plugins/tests.rs": "Existing plugin-domain test module retained while production plugin code is split.",
"crates/host-core/src/db/tests.rs": "Existing database-domain test module retained while production database code is split.",
"crates/host-core/src/providers/tests.rs": "Existing provider-domain test module retained while production provider code is split.",
- "crates/host-core/src/user_skills.rs": "User-skill catalog crossed the Rust 1000-LOC limit when the scan-and-batch-import path landed (PR #515); the file still holds one cohesive discovery/import lifecycle and is exempted until the batch-import surface is separated."
+ "crates/host-core/src/user_skills.rs": "User-skill catalog crossed the Rust 1000-LOC limit when the scan-and-batch-import path landed (PR #515); the file still holds one cohesive discovery/import lifecycle and is exempted until the batch-import surface is separated.",
+ "crates/host-core/src/config_sync/engine.rs": "Configuration-sync orchestration keeps capture, reconciliation, approval gating, journal recovery, and public state projection in one lifecycle; transport, domain capture, remote history, and apply responsibilities are already separated, and the remaining orchestration will be split after the sync lifecycle stabilises."
}
}
diff --git a/docs/spec/01-product/00-overview.md b/docs/spec/01-product/00-overview.md
index 3ee39ce86..9844fad6b 100644
--- a/docs/spec/01-product/00-overview.md
+++ b/docs/spec/01-product/00-overview.md
@@ -36,6 +36,8 @@ PI-Desktop =
acceptance criteria autonomously in Agent mode
9. Make project sessions, imports, extensions, and scheduled prompts practical
for daily local work
+10. Synchronize explicitly selected portable configuration through a
+ host-owned encrypted WebDAV vault without exporting conversation history
## Non-goals (MVP)
diff --git a/docs/spec/01-product/01-product-scope.md b/docs/spec/01-product/01-product-scope.md
index 7549e2eaf..a6d281fdd 100644
--- a/docs/spec/01-product/01-product-scope.md
+++ b/docs/spec/01-product/01-product-scope.md
@@ -51,6 +51,12 @@ Import sessions from other local agents, prepare file references in the
composer, use the work panel for review/browser/files, manage
notifications, and run scheduled prompts manually or on a remembered cadence.
+### H. Portable configuration sync
+
+Configure an encrypted WebDAV vault for portable preferences and user-owned
+capabilities, review category and credential inclusion, and reconcile changes
+across devices without synchronizing conversation history or source files.
+
## 4. Current shipped scope
- Electron desktop app for macOS arm64 and Intel x64, Windows x64, and Linux x64 release lanes
@@ -72,13 +78,14 @@ notifications, and run scheduled prompts manually or on a remembered cadence.
- Extensions page: local plugins, marketplace packages, MCP, Skills, and
Subagents with activation scopes
- Scheduled task records with manual execution and cadence metadata
+- Host-owned encrypted WebDAV configuration sync with category selection,
+ conditional-write probing, three-way merge, and local activation review
- Rust host core skeleton for privileged operations
## 5. Out of scope (current phase)
- Remote Gateway / browser remote control; local loopback MCP control is the
explicitly bounded exception described by ADR 0203
-- Cloud account sync
- Full IDE experience
- Trusted plugin provenance/signatures and a capability sandbox for raw plugin
Node APIs
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index 072655cf2..07350b524 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -2253,3 +2253,30 @@ returns `{ ok: true }` and forwards to host `providers.reorder`. The sandboxed
preload permits this channel through the shared IPC registry. Invalid placement
or missing providers returns `INVALID_PARAMS`; configuration and defaults are
unchanged. See [provider configuration](12-provider-config-schema.md).
+
+## 15. Cloud configuration sync
+
+The Settings → Cloud sync page uses the following renderer-to-Main channels;
+all are forwarded to the Host-owned `configSync.*` RPC methods:
+
+| IPC channel | Host method | contract |
+|---|---|---|
+| `pi-desktop/configSync/getState` | `configSync.getState` | redacted status, category selections, preview counts, and pending approval summaries |
+| `pi-desktop/configSync/test` | `configSync.test` | WebDAV capability probe using a temporary object; no configuration is persisted |
+| `pi-desktop/configSync/configure` | `configSync.configure` | validates the endpoint, stores encrypted local sync metadata, and enables the vault |
+| `pi-desktop/configSync/syncNow` | `configSync.syncNow` | runs one Host-owned reconciliation cycle |
+| `pi-desktop/configSync/pause` | `configSync.pause` | pauses or resumes this device only |
+| `pi-desktop/configSync/unlock` | `configSync.unlock` | unlocks the local vault for the current process/device |
+| `pi-desktop/configSync/approve` / `reject` | `configSync.approve` / `configSync.reject` | records a digest-bound local activation decision |
+| `pi-desktop/configSync/mapProject` | `configSync.mapProject` | binds one opaque project/group identity to one or more explicitly selected local folders, preserving primary-root order |
+| `pi-desktop/configSync/listHistory` | `configSync.listHistory` | lists redacted reachable revision metadata only |
+| `pi-desktop/configSync/restore` | `configSync.restore` | creates a new propagated revision from an explicitly acknowledged historical revision and stages local approvals/recovery |
+| `pi-desktop/configSync/changePassword` | `configSync.changePassword` | CAS-rewraps the vault key header without returning keys or secret values |
+| `pi-desktop/configSync/disconnect` | `configSync.disconnect` | removes local sync metadata and keys; it does not delete remote vault data |
+
+Input passwords are accepted only for the operation that needs them. No raw
+secret, vault key, decrypted resource, or remote archive crosses back to the
+renderer. The `configSync.changed` event carries the same redacted state and
+is emitted by Host-originated changes, including the Host scheduler. Main is a
+transport/lifecycle coordinator and does not schedule, merge, encrypt, or
+apply configuration.
diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.md
index f643b53ae..7daeb3b9a 100644
--- a/docs/spec/03-runtime/04-data-storage.md
+++ b/docs/spec/03-runtime/04-data-storage.md
@@ -65,6 +65,7 @@ to an absolute path before it reaches host-core as a child-process variable.
│ ├── <sessionId>.revisions.jsonl # regenerate branches, append-only
│ └── <sessionId>.inflight.json # streaming reply checkpoint (D299), transient
├── secrets/ # encrypted secret blobs + .machine-key (unchanged)
+ ├── config-sync/ # encrypted sync base/pending bundles — host-core only
├── attachments/ # content-addressed blobs (sha256 name), refs from messages
├── plugins/ # code + data + registry.json (unchanged, spec 07-11)
├── logs/ # NDJSON app/<category>, host/<category>, agent/<category> logs
@@ -89,6 +90,15 @@ content lives in `sessions/`, attachments and tool outputs beyond the limits
of [16-tool-result-limits](16-tool-result-limits.md) live on disk, referenced
by path/hash.
+### 1.3 Portable configuration sync
+
+Host-core stores sync configuration in the `configSync` key-value namespace.
+The vault key reference and WebDAV password use the existing encrypted secret
+store. `config-sync/base.bin` and `config-sync/pending.bin` are authenticated
+encrypted bundles replaced with temp-file rename; they are not renderer- or
+sidecar-readable files. Sync revisions and resources remain remote immutable
+objects and do not change the SQLite schema or transcript retention.
+
### 2.0 Message-owned review snapshots (ADR 0043)
Successful workspace `Write`/`Edit` tool results carry the bounded
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index b434c91d4..34e823c99 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -1227,3 +1227,37 @@ The optional config_json.calendarConfigured boolean distinguishes an explicitly
### Scheduled tasks: workspace identity
Stored workspace bindings use the existing project canonicalization contract on both write and read. On Windows, slash direction, case, trailing separators and extended path prefixes do not hide a task from its own project's conversation. The distinction between missing legacy bindings and explicit null remains unchanged. Foreign-project tools cannot list or mutate bound tasks.
+
+### Cloud configuration sync
+
+The Host exposes the `configSync.getState`, `configSync.test`,
+`configSync.configure`, `configSync.syncNow`, `configSync.pause`,
+`configSync.unlock`, `configSync.approve`, `configSync.reject`,
+`configSync.mapProject`, `configSync.listHistory`, `configSync.restore`,
+`configSync.changePassword`, and
+`configSync.disconnect` methods through the existing Electron Host bridge.
+These methods operate on the Host-owned encrypted vault and the explicit
+portable-domain adapter registry. They do not expose raw secrets or local
+filesystem bindings to the Renderer.
+
+`configSync.test` performs a capability probe against a temporary remote
+object and reports whether reliable strong conditional writes are available.
+`configSync.syncNow` and the five-minute automatic poll serialize per vault,
+reconcile against the last acknowledged base, publish immutable encrypted
+objects followed by a conditional head update, and retain unresolved
+conflicts/security-sensitive imports as pending state. A failed head
+precondition restarts from the newly read head; it never overwrites blindly.
+
+`configSync.listHistory` returns revision IDs, creation timestamps, parent IDs,
+and counts without decrypting data in the Renderer. `configSync.restore` requires
+an explicit propagation acknowledgement, writes an encrypted local recovery
+point, publishes a new head with a CAS, and keeps executable/security-sensitive
+entities pending until local approval. `configSync.changePassword` updates the
+wrapped-key header with a strong-ETag CAS; it does not revoke copied old vault
+keys.
+
+The public result is a redacted state snapshot. `configSync.changed` is a Host
+notification carrying that same snapshot. Approval and rejection require the
+current entity digest, so a security-relevant edit cannot reuse an older local
+decision. Disconnect deletes only local credentials, vault keys, metadata and
+staging files; remote objects remain intact.
diff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.md
index 4468fd325..c46980df4 100644
--- a/docs/spec/03-runtime/08-error-codes.md
+++ b/docs/spec/03-runtime/08-error-codes.md
@@ -71,6 +71,14 @@ registered; reserved codes in §3.7 remain intentionally absent from
| `HOST_SHUTTING_DOWN` | yes | the host received EOF and is draining; the call was refused rather than started |
| `RATE_LIMITED` | yes | a per-caller host budget (plugin session import, batch operations) was exceeded inside its window |
| `LIMIT_EXCEEDED` | no | a payload exceeded a fixed host bound (item count, byte size, or a 64 MiB NDJSON request line) and was refused |
+| `CONFIG_SYNC_INVALID` | no | invalid sync configuration, password, path, request, or approval input |
+| `CONFIG_SYNC_LOCKED` | no | the local encrypted sync vault is not unlocked |
+| `CONFIG_SYNC_UNSUPPORTED` | no | the vault format or WebDAV server capability is unsupported |
+| `CONFIG_SYNC_REMOTE` | maybe | remote WebDAV object, authentication, quota, or availability failure |
+| `CONFIG_SYNC_CONFLICT` | maybe | remote head, vault identity, or approval digest conflict |
+| `CONFIG_SYNC_CRYPTO` | no | authenticated encryption, object identity, or ciphertext validation failed |
+| `CONFIG_SYNC_MAPPING_REQUIRED` | no | imported project-scoped configuration needs an explicit local folder/group mapping |
+| `CONFIG_SYNC_LIMIT_EXCEEDED` | no | encrypted sync state exceeded an entity, object, resource, archive, or decompression bound |
`HOST_UNAVAILABLE` is reserved for a missing or broken host process/transport,
diff --git a/docs/spec/03-runtime/14-secrets-storage.md b/docs/spec/03-runtime/14-secrets-storage.md
index 2caaad657..af13bc99a 100644
--- a/docs/spec/03-runtime/14-secrets-storage.md
+++ b/docs/spec/03-runtime/14-secrets-storage.md
@@ -91,6 +91,11 @@ Renderer uses provider methods that accept optional `secretValue` on create/upda
5. Uninstall/reset app deletes secrets unless future explicit migrate tool says otherwise
6. Provider delete defaults to deleting linked secret — both the API key and the OAuth credential
7. An OAuth refresh token never crosses a process boundary: only Electron main reads it, and only to mint request auth
+8. Portable configuration sync exports provider API keys or MCP
+ environment/header values only after explicit credential opt-in. Values
+ remain inside host-owned encrypted staging and are restored through the
+ receiving device's local secret store. WebDAV credentials, machine
+ encryption keys, OAuth sessions, and cookies are never portable.
## 7. Redaction policy
diff --git a/docs/spec/03-runtime/22-config-sync.md b/docs/spec/03-runtime/22-config-sync.md
new file mode 100644
index 000000000..7315cc6b3
--- /dev/null
+++ b/docs/spec/03-runtime/22-config-sync.md
@@ -0,0 +1,168 @@
+# Portable configuration sync
+
+Status: implemented baseline for the approved WebDAV configuration-sync slice.
+
+Portable configuration sync is a host-owned, encrypted WebDAV workflow. It
+does not synchronize conversation history, project source files, attachments,
+runtime state, or model weights. The Renderer only receives redacted status,
+preview counts, conflicts, and activation summaries.
+
+## 1. Ownership and boundaries
+
+The process path remains:
+
+```text
+Renderer → Preload IPC → Electron Main → host-core → WebDAV
+```
+
+Host-core owns the vault key, WebDAV transport, revision state, merge base,
+pending approvals, local encrypted staging, and import application. Electron
+Main only registers the IPC handlers and forwards `configSync.changed`.
+Agent Runtime has no sync implementation.
+
+The export path is an explicit per-domain allowlist in
+`crates/host-core/src/config_sync/domains.rs`. It never serializes the
+database, the secrets directory, or an arbitrary filesystem tree. Local paths,
+window state, readiness flags, OAuth sessions, plugin binaries, and device
+approvals are local overlays or excluded data.
+The same module exposes an adapter registry declaring schema version,
+portable/secret fields, local overlays, identity and references, merge
+granularity, activation, and recovery policy for every supported domain.
+
+## 2. Portable domains
+
+The current adapter set covers application preferences, user-owned providers,
+MCP definitions, user skills, global subagents, app-managed global/project
+instructions and projects, plugin installation intent, scheduled automations,
+and optional project memory. Credentials are opt-in. Provider API keys and MCP
+environment variables/headers are included only when the credential category
+is selected; OAuth access/refresh tokens and cookies are never exported.
+The instruction adapter reads only the fixed global `~/.pi/agent/AGENTS.md`
+and each registered project's root `AGENTS.md`; it does not scan nested
+repositories or arbitrary files. Imported instruction files are written only
+after their scope is explicitly selected, mapped where required, and approved.
+Directory-shaped skills carry bounded sibling resources as authenticated
+objects. Package paths, symlinks, collisions, file counts, and total size are
+validated by Host before approved resources are written; scripts are stored as
+bytes and are never executed by import.
+
+Project and workspace bindings are represented by opaque logical identifiers.
+Host-core assigns a persistent logical identity to each registered standalone
+project; project-group roots derive identities from the group identity and
+ordered root position. A device mapping overlays the received logical ID onto
+its local folder, so different absolute paths do not create duplicate
+entities.
+Incoming project-scoped executable content stays staged until a local folder
+mapping and approval exist. No local path is written into the encrypted
+portable entity payload. Plugin data that has no supported adapter is reported
+as unsupported rather than treated as synchronized. Approved plugin installation
+intent is kept in a Host-owned local overlay; it never pulls plugin bytes or
+permission grants.
+
+## 3. Vault and WebDAV protocol
+
+Each vault has a random data key. The backup password is processed with bounded
+Argon2id parameters, and the data key is wrapped with AES-256-GCM. Every head,
+revision manifest, and resource object is separately authenticated with a
+purpose/vault-derived object key, domain-separated associated data, and a
+fresh nonce. Resource object IDs are keyed content identifiers, so plaintext
+global hashes are not required. The vault envelope version is independent from
+the SQLite schema and is bumped when cryptographic derivation changes.
+
+The remote layout is an opaque header plus immutable revision/resource objects
+and one mutable encrypted head:
+
+```text
+<selected-directory>/header
+<selected-directory>/vault/<opaque-vault-id>/head
+<selected-directory>/vault/<opaque-vault-id>/revisions/<revision-id>
+<selected-directory>/vault/<opaque-vault-id>/objects/<object-id>
+```
+
+Initialization uses `If-None-Match: *`. Existing heads require a strong ETag
+and are published with `If-Match`. A failed precondition restarts
+reconciliation from the newly read head; it never overwrites blindly. The
+capability probe writes a temporary object with conditional creation twice,
+obtains a strong ETag, verifies a matching `If-Match` update, and verifies a
+stale `If-Match` is rejected before the object is removed.
+
+HTTPS is required by default. Redirects, endpoint userinfo, path traversal,
+unsafe remote names, oversized objects, weak ETags, and unbounded KDF
+parameters are rejected. An HTTP exception, when exposed by a future UI, must
+be an explicit LAN-risk acknowledgement.
+
+## 4. Merge and activation
+
+The local encrypted base is the last acknowledged common revision. Capture,
+remote read, three-way merge, immutable object upload, CAS head publication,
+and local application are serialized per vault. Scalar settings merge by
+declared entity unit; provider records, MCP records, skill packages, and
+automation definitions are not merged as arbitrary JSON arrays. Tombstones
+represent explicit deletion; an unselected category is not deletion.
+
+Same edits converge and disjoint edits continue. Same-unit edits and
+delete-versus-edit retain both candidates as conflicts. Imported MCP, skills,
+subagents, plugins, and automations require local activation approval; an
+approval is bound to the entity digest. A changed command, endpoint, script,
+instruction, or credential destination therefore invalidates the old approval.
+Missing provider references are retained as dependency approvals instead of
+being written as unusable defaults; unrelated entities can continue applying.
+The host never activates staged executable content merely because a UI flag is
+set. Newly imported automation definitions are also disabled until this
+device explicitly takes execution ownership; an existing local task keeps its
+device-local enabled state.
+
+The import path rechecks the captured local generation before applying each
+entity. Changes made after capture are left in place and are reconciled on the
+next run. A durable encrypted pending bundle records the captured local
+manifest and an `applying` marker; restart recovery finishes the approved
+steps or leaves the bundle visible for retry before the configuration is
+considered converged. Existing direct local MCP creation behavior is
+unchanged.
+
+## 5. Settings workflow
+
+Settings → Cloud sync provides WebDAV endpoint credentials, vault password,
+device label, category selection, a capability test, sync-now, unlock, pause,
+folder mapping, approval/rejection, revision history/restore, vault-password
+rewrap, and disconnect controls. The renderer displays
+`notConfigured`, `locked`, `upToDate`, `localChangesPending`, `syncing`,
+`offline`, `unsupportedServer`, `conflict`, `awaitingActivation`, `paused`,
+and `error` as distinct states. Disconnect keeps local data and does not delete
+remote data.
+
+Credentials and memory are unchecked by default. The setup preview reports
+supported, excluded, secret-bearing, mapping-required, and pending-activation
+counts. Raw secret values, vault keys, and backup passwords never cross the
+renderer boundary.
+
+The host owns an immediate startup check, a 30-second local-change debounce,
+and a bounded five-minute remote poll when automatic sync is enabled. Failed
+network attempts use bounded exponential retry with jitter; paused, locked,
+incompatible, authentication, and wrong-password states do not spin retry
+loops. The worker is cancelled with the host; there is no extra daemon after
+the app exits.
+
+## 6. Durability and compatibility
+
+Sync configuration is stored in the host `kv` namespace. The vault key and
+WebDAV password use the existing host secret store. Local base and pending
+bundles are encrypted and replaced through temp-file rename. A malformed or
+unauthenticated local bundle is an error, not an empty state. Backup format
+versioning is independent from the SQLite schema; a newer format is rejected
+without truncating the local representation.
+
+Remote history retains the newest 30 reachable logical revisions and protects
+the current head, merge base, pending conflict references, and recovery points;
+unreferenced objects are deleted only after a grace period and successful
+publication. Restore publishes a new revision after a pre-restore encrypted
+local recovery point is written. A vault-password change CAS-updates the
+wrapped-key header without changing the vault data key; copied old keys are not
+cryptographically revoked, so device removal is not treated as revocation.
+
+Project-group mappings accept ordered multi-root bindings and preserve the
+primary root invariant. WebDAV tests use an in-process fixture for conditional
+creation, strong-ETag updates, stale-writer rejection, empty-vault races, and
+weak-ETag rejection. The remaining availability limitation is inherent: a
+fresh device without trusted head history cannot prove that a malicious server
+returned the newest valid backup.
diff --git a/docs/spec/03-runtime/README.md b/docs/spec/03-runtime/README.md
index e8b945e50..6a79d719e 100644
--- a/docs/spec/03-runtime/README.md
+++ b/docs/spec/03-runtime/README.md
@@ -24,3 +24,4 @@
| [20-speech.md](20-speech.md) | Host speech (ASR/TTS) |
- [Image generation and editing](21-image-generation.md)
+- [Portable configuration sync](22-config-sync.md)
diff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.md
index a752c4507..05c2c465a 100644
--- a/docs/spec/04-ux/06-settings-ia.md
+++ b/docs/spec/04-ux/06-settings-ia.md
@@ -49,15 +49,16 @@ Settings is a **full-window page** that replaces the app sidebar + main chrome (
8. **Subagents / 子智能体** — Lucide `Bot` (built-in and personal parallel agents)
9. **Import / 导入** — Lucide `Download` (bring sessions and model configuration in from other tools)
10. **Projects / 项目** — Lucide `Archive` (durable project index)
- 11. **Remote Hosts / 远程主机** — Lucide `Globe` (SSH bootstrap and pairing inventory; developer mode only)
- 12. **Info / 信息** — Lucide `Info` (versions, logs, updates, developer)
+ 11. **Cloud sync / 云同步** — Lucide `CloudDownload` (encrypted portable configuration backup and bidirectional sync)
+ 12. **Remote Hosts / 远程主机** — Lucide `Globe` (SSH bootstrap and pairing inventory; developer mode only)
+ 13. **Info / 信息** — Lucide `Info` (versions, logs, updates, developer)
Icons are decorative (`aria-hidden` via the SVG default) and stay monochrome
with the rail label; do not reuse refresh/rotate glyphs here.
- The directory remains a flat searchable list in the same exact order. For
scanability, the destinations are shown in four titled visual clusters:
`Preferences` / `偏好` (General, AI, Shortcuts), `Agent` / `智能体`
(Instructions, Models, Skills, MCP, Subagents), `Workspace` / `工作区`
- (Import, Projects), and `System` / `系统` (Remote Hosts, Info). Headings are
+ (Import, Projects), and `System` / `系统` (Cloud sync, Remote Hosts, Info). Headings are
muted, non-interactive labels and use whitespace for separation; no divider
lines are rendered. These are visual landmarks only, not a second navigation
level.
@@ -143,6 +144,25 @@ Settings is a **full-window page** that replaces the app sidebar + main chrome (
- File-open target, menu-bar behavior, and bottom-panel behavior are not
rendered until their host-backed settings schemas and runtime effects exist.
+### Cloud sync
+
+- **Connection**: WebDAV URL, username, app password, remote directory, device
+ label, and a separate backup/vault password. The test action uses only a
+ temporary remote object and must prove conditional creation and readback.
+- **Portable configuration**: supported categories are selected by default;
+ credentials and project memory are explicit opt-ins. The preview reports
+ supported, excluded, secret-bearing, mapping-required, and pending-approval
+ counts.
+- **Safety**: the page never renders raw credentials or vault keys. Imported
+ MCP, skills, subagents, plugins, automations, and project-scoped data remain
+ pending until local activation approval and any required folder mapping are
+ complete. Disconnect preserves local and remote data.
+- **State and recovery**: show distinct configured, locked, syncing, offline,
+ unsupported-server, conflict, awaiting-activation, paused, and error states.
+ Users can sync now, unlock, pause this device, approve/reject staged items,
+ and disconnect. The page does not imply convergence from an old successful
+ run while a pending state remains.
+
### 全局 AI (`ai` tab)
- **Permissions** card: the global permission-mode control
(ask / accept-edits / auto) that governs how autonomously the agent acts.
@@ -709,9 +729,9 @@ system while preserving their different data ownership:
2. Rail shows the search pill at the top, the back-to-app action pinned at the
foot on the main sidebar's footer icon line, and exactly General / 常规, AI,
Shortcuts / 快捷键, Instructions / 指令, Models / 模型, Skills / 技能, MCP,
- Subagents / 子智能体, Import / 导入, Projects / 项目, and Info / 信息 in
- that order, with Remote Hosts / 远程主机 between Projects and Info only
- while developer mode is on. The rows are grouped under Preferences / 偏好,
+ Subagents / 子智能体, Import / 导入, Projects / 项目, Cloud sync / 云同步,
+ Remote Hosts / 远程主机, and Info / 信息 in that order, with Remote Hosts /
+ 远程主机 present only while developer mode is on. The rows are grouped under Preferences / 偏好,
Agent / 智能体, Workspace / 工作区, and System / 系统. There is no
Usage / 用量 destination.
3. Appearance is part of General and has no standalone rail destination
diff --git a/docs/spec/05-security/01-security.md b/docs/spec/05-security/01-security.md
index 5a181a364..f2bc0f847 100644
--- a/docs/spec/05-security/01-security.md
+++ b/docs/spec/05-security/01-security.md
@@ -134,6 +134,30 @@ redirects do not forward caller headers.
Manual user-owned MCP configuration remains covered by ADR 0142 and may use
explicit local/LAN endpoints; the market path does not widen that policy.
+## 4.3 Portable configuration sync
+
+WebDAV sync is a host-core network boundary. The renderer and Agent Runtime
+cannot access the endpoint, WebDAV password, backup password, vault key, or
+portable secret values. Host-core validates the selected HTTPS endpoint,
+rejects userinfo and redirects, constrains relative paths, bounds remote object
+size and KDF parameters, and requires strong conditional-write behavior before
+publishing a head.
+
+Every remote payload is authenticated ciphertext. The WebDAV server receives
+neither the vault password nor the local machine encryption key. Credentials
+are exported only after explicit category opt-in and are never included in
+status, preview, conflict labels, or logs. Restored provider/MCP secrets are
+written through the host secret store; OAuth sessions and cookies are never
+portable.
+
+Imported commands, endpoints, scripts, skills, plugins, and automations are
+staged behind a digest-bound local approval. Local paths and approvals are
+overlays, not shared entities. A new device therefore cannot execute a
+synchronized capability merely because its desired enabled flag was imported.
+The server can still deny availability or replay a valid old head to a fresh
+device that has no trusted history; sync does not claim availability or
+freshness against a malicious server.
+
## 5. Command execution
- Bash requires confirmation by default (risk-tiered permission cards); in
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 472d771d7..464be41c7 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -8003,6 +8003,36 @@ identify the platform validation still needed.
because the host has no device backend yet, so this scenario stays Draft until
audio lands.
+### E2E-CONFIG-SYNC-webdav-portable-configuration
+
+- **Preconditions:** A built task candidate, isolated host profile, and a local
+ WebDAV fixture that supports strong ETags and conditional PUT. No real
+ WebDAV account, provider, or production desktop.
+- **Steps:** 1) Open Settings → Cloud sync and enter the fixture URL, device
+ label, directory, and backup password. 2) Run the capability test and
+ confirm it uses temporary objects. 3) Select provider/MCP/skill categories
+ while leaving credentials and memory off; enable credentials in a second
+ preview and verify only redacted counts are shown. 4) Configure device A,
+ create a user provider and MCP definition, and sync. 5) Configure device B
+ against the same vault, sync, inspect pending activation/mapping, and verify
+ no command or task runs before approval. 6) Approve a changed safe entity,
+ reject one staged entity, edit disjoint settings on both devices, and sync
+ again. 7) Exercise a concurrent head writer, wrong password, weak ETag,
+ ciphertext corruption, redirect, archive traversal, and network interruption.
+- **Expected:** The test refuses unreliable conditional writes. WebDAV sees
+ only authenticated ciphertext and opaque object names; raw secrets never
+ appear in renderer state or logs. Identical and disjoint edits converge,
+ conflicts remain reviewable, explicit deletions use tombstones, category
+ opt-out is not deletion, and executable imports remain inactive until local
+ approval and mapping. Recovery never exposes a partial local apply.
+- **Specs:** `03-runtime/22-config-sync.md`, `03-runtime/14-secrets-storage.md`,
+ `05-security/01-security.md`, ADR 0300.
+- **Acceptance:** F (persistence), Security, Quality.
+- **Milestone:** M6+.
+- **Status:** Draft; merge/crypto and in-process WebDAV conditional-write
+ coverage exists. The remaining automation is the full two-device process
+ path and checkpoint-level local recovery fault injection.
+
## 8. Traceability Matrix
| Acceptance | Scenarios |
@@ -8010,6 +8040,7 @@ identify the platform validation still needed.
| C / F — Hourly task updates | E2E-SCHEDULED-manual-to-hourly |
| C / F / Quality — Saved project isolation | E2E-SCHEDULED-manual-workspace-binding |
| C / F / Quality — Desktop automations | E2E-SCHEDULED-desktop-automation-lifecycle |
+| F / Security / Quality — Portable configuration sync | E2E-CONFIG-SYNC-webdav-portable-configuration |
| A / C — Unicode stdio framing | E2E-RPC-unicode-separators |
| C / G / Quality — Plugins navigation | E2E-NAV-plugins-button-goes-back |
| C / D / Quality — Sidebar row states | E2E-LAYOUT-sidebar-row-states |
diff --git a/docs/spec/NAV.md b/docs/spec/NAV.md
index e085bacfa..f3ef704db 100644
--- a/docs/spec/NAV.md
+++ b/docs/spec/NAV.md
@@ -43,6 +43,7 @@
- [19-remote-agent-control-protocol.md](03-runtime/19-remote-agent-control-protocol.md)
- [20-speech.md](03-runtime/20-speech.md)
- [21-image-generation.md](03-runtime/21-image-generation.md)
+- [22-config-sync.md](03-runtime/22-config-sync.md)
## 4. UX
- [README.md](04-ux/README.md)
diff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
index 7dd47729b..c55a65deb 100644
--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
@@ -1804,3 +1804,24 @@ returns `{ ok: true }` and forwards to host `providers.reorder`. The sandboxed
preload permits this channel through the shared IPC registry. Invalid placement
or missing providers returns `INVALID_PARAMS`; configuration and defaults are
unchanged. See [provider configuration](12-provider-config-schema.md).
+
+## 15. 云配置同步
+
+设置 → 云同步页面使用以下 Renderer-to-Main 通道;所有通道都会转发到 Host 所有的 `configSync.*` RPC 方法:
+
+| IPC 通道 | Host 方法 | 契约 |
+|---|---|---|
+| `pi-desktop/configSync/getState` | `configSync.getState` | 脱敏状态、类别选择、预览计数和待审批摘要 |
+| `pi-desktop/configSync/test` | `configSync.test` | 使用临时对象进行 WebDAV 能力探测;不持久化配置 |
+| `pi-desktop/configSync/configure` | `configSync.configure` | 校验 endpoint、保存加密的本地同步元数据并启用 vault |
+| `pi-desktop/configSync/syncNow` | `configSync.syncNow` | 执行一次由 Host 所有的协调周期 |
+| `pi-desktop/configSync/pause` | `configSync.pause` | 仅暂停或恢复本设备 |
+| `pi-desktop/configSync/unlock` | `configSync.unlock` | 为当前进程/设备解锁本地 vault |
+| `pi-desktop/configSync/approve` / `reject` | `configSync.approve` / `configSync.reject` | 记录绑定 digest 的本地激活决定 |
+| `pi-desktop/configSync/mapProject` | `configSync.mapProject` | 将一个不透明项目/组身份绑定到一个或多个明确选择的本地文件夹,并保留 primary-root 顺序 |
+| `pi-desktop/configSync/listHistory` | `configSync.listHistory` | 只列出脱敏的可达 revision 元数据 |
+| `pi-desktop/configSync/restore` | `configSync.restore` | 根据明确确认的历史 revision 创建新的传播 revision,并暂存本地审批/恢复信息 |
+| `pi-desktop/configSync/changePassword` | `configSync.changePassword` | CAS 重新包裹 vault key header,不返回 key 或秘密值 |
+| `pi-desktop/configSync/disconnect` | `configSync.disconnect` | 移除本地同步元数据和 key;不会删除远端 vault 数据 |
+
+输入密码只会被传给需要它的操作。原始秘密、vault key、解密资源或远端 archive 不会返回到 Renderer。`configSync.changed` 事件携带相同的脱敏状态,并由 Host 发起的变更(包括 Host scheduler)触发。Main 只是传输/生命周期协调器,不负责调度、合并、加密或应用配置。
diff --git a/docs/zh-CN/spec/03-runtime/08-error-codes.md b/docs/zh-CN/spec/03-runtime/08-error-codes.md
index 204b27dec..6930a4f0d 100644
--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md
+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md
@@ -73,6 +73,14 @@ type AppError = {
| `HOST_SHUTTING_DOWN` | 是的 | 主机收到 EOF 正在排空;调用被拒绝而不是被启动 |
| `RATE_LIMITED` | 是的 | 某个按调用方计的主机预算(插件会话导入、批量操作)在其窗口内被超出 |
| `LIMIT_EXCEEDED` | 不 | 载荷超过了固定的主机上限(条目数、字节数)并被拒绝 |
+| `CONFIG_SYNC_INVALID` | 不 | 同步配置、密码、路径、请求或审批输入无效 |
+| `CONFIG_SYNC_LOCKED` | 不 | 本地加密同步 vault 尚未解锁 |
+| `CONFIG_SYNC_UNSUPPORTED` | 不 | vault 格式或 WebDAV 服务器能力不受支持 |
+| `CONFIG_SYNC_REMOTE` | 也许 | 远端 WebDAV 对象、认证、配额或可用性失败 |
+| `CONFIG_SYNC_CONFLICT` | 也许 | 远端 head、vault 身份或审批 digest 冲突 |
+| `CONFIG_SYNC_CRYPTO` | 不 | 认证加密、对象身份或密文校验失败 |
+| `CONFIG_SYNC_MAPPING_REQUIRED` | 不 | 导入的项目作用域配置需要明确的本地文件夹/项目组映射 |
+| `CONFIG_SYNC_LIMIT_EXCEEDED` | 不 | 加密同步状态超过实体、对象、资源、归档或解压上限 |
`HOST_UNAVAILABLE` 是为丢失或损坏的主机 process/transport 保留的,
不是普通的入学压力。 RPC 容量返回 `HOST_OVERLOADED`,并且
diff --git a/docs/zh-CN/spec/03-runtime/22-config-sync.md b/docs/zh-CN/spec/03-runtime/22-config-sync.md
new file mode 100644
index 000000000..f7d68121a
--- /dev/null
+++ b/docs/zh-CN/spec/03-runtime/22-config-sync.md
@@ -0,0 +1,71 @@
+# 便携式配置同步
+
+> **翻译说明:** 本页是与 [英文源规格](/spec/03-runtime/22-config-sync) 一一对应的机器辅助翻译。代码、协议字段和标识符保持原文;如翻译与英文源事实有歧义,以英文版本为准。
+
+状态:已实现已批准 WebDAV 配置同步切片的基线。
+
+便携式配置同步是由 Host 所有、使用加密 WebDAV 的工作流。它不会同步对话历史、项目源文件、附件、运行时状态或模型权重。Renderer 只接收脱敏后的状态、预览计数、冲突和激活摘要。
+
+## 1. 所有权与边界
+
+进程路径保持不变:
+
+```text
+Renderer → Preload IPC → Electron Main → host-core → WebDAV
+```
+
+Host-core 持有 vault key、WebDAV 传输、修订状态、合并基线、待处理审批、本地加密暂存以及导入应用。Electron Main 只注册 IPC 处理器并转发 `configSync.changed`。Agent Runtime 不实现同步。
+
+导出路径是 `crates/host-core/src/config_sync/domains.rs` 中按域明确列出的 allowlist。它不会序列化数据库、secrets 目录或任意文件系统树。本地路径、窗口状态、就绪标记、OAuth 会话、插件二进制文件和设备审批属于本地覆盖或排除数据。
+同一模块为每个受支持的域暴露适配器注册表,声明 schema 版本、便携/秘密字段、本地覆盖、身份与引用、合并粒度、激活方式以及恢复策略。
+
+## 2. 便携域
+
+当前适配器集合覆盖应用偏好、用户所有的 providers、MCP 定义、用户 skills、全局 subagents、由应用管理的全局/项目指令与项目、插件安装意图、定时自动化任务以及可选的项目记忆。凭据默认需要明确选择。只有选中凭据类别时才会包含 provider API key 和 MCP 环境变量/headers;OAuth access/refresh token 与 cookies 永远不会导出。
+指令适配器只读取固定的全局 `~/.pi/agent/AGENTS.md` 和每个已注册项目根目录的 `AGENTS.md`;不会扫描嵌套仓库或任意文件。导入的指令文件只有在明确选择其作用域、完成必要映射并获得审批后才会写入。
+目录形态的 skills 会将有界的同级资源作为已认证对象携带。Host 会校验 package path、symlink、冲突、文件数量和总大小后才写入已审批的资源;脚本按字节存储,导入时绝不执行。
+
+项目和 workspace 绑定使用不透明的逻辑标识符表示。Host-core 为每个已注册的独立项目分配持久逻辑身份;项目组根目录的身份由组身份和有序根位置派生。设备映射把接收的逻辑 ID 覆盖到本地文件夹,因此不同绝对路径不会产生重复实体。
+传入的项目作用域可执行内容在本地文件夹映射和审批存在前保持暂存。加密的便携实体负载中不会写入本地路径。没有受支持适配器的插件数据会报告为不支持,而不会被声称为已同步。已审批的插件安装意图保存在 Host 所有的本地覆盖中;它不会拉取插件字节或权限授予。
+
+## 3. Vault 与 WebDAV 协议
+
+每个 vault 都有随机 data key。备份密码使用有界的 Argon2id 参数处理,data key 使用 AES-256-GCM 包裹。每个 head、revision manifest 和 resource object 都使用按 purpose/vault 派生的对象密钥、域隔离的关联数据和新鲜 nonce 单独认证。resource object ID 是带密钥的内容标识符,因此不需要明文全局 hash。vault envelope 版本独立于 SQLite schema;密码派生发生变化时会提升该版本。
+
+远端布局是不透明 header、不可变 revision/resource object 和一个可变加密 head:
+
+```text
+<selected-directory>/header
+<selected-directory>/vault/<opaque-vault-id>/head
+<selected-directory>/vault/<opaque-vault-id>/revisions/<revision-id>
+<selected-directory>/vault/<opaque-vault-id>/objects/<object-id>
+```
+
+初始化使用 `If-None-Match: *`。已有 head 必须有 strong ETag,并使用 `If-Match` 发布。前置条件失败时会从重新读取的 head 开始重新协调;绝不会盲目覆盖。能力探测会用临时对象进行两次条件创建,取得 strong ETag,验证匹配的 `If-Match` 更新,并验证旧的 `If-Match` 会被拒绝,然后删除该对象。
+
+默认要求 HTTPS。redirect、endpoint userinfo、路径穿越、不安全远端名称、过大对象、weak ETag 和无界 KDF 参数都会被拒绝。未来 UI 若暴露 HTTP 例外,必须要求明确确认 LAN 风险。
+
+## 4. 合并与激活
+
+本地加密基线是最后一次确认的共同 revision。每个 vault 内的捕获、远端读取、三方合并、不可变对象上传、CAS head 发布和本地应用会串行执行。标量设置按声明的实体单元合并;provider 记录、MCP 记录、skill package 和 automation 定义不会作为任意 JSON 数组合并。tombstone 表示明确删除;未选择的类别不表示删除。
+
+相同编辑会收敛,不相交编辑可以继续。同一单元编辑以及 delete-versus-edit 会将两个候选都保留为冲突。导入的 MCP、skills、subagents、plugins 和 automations 需要本地激活审批;审批绑定实体 digest。因此命令、endpoint、脚本、指令或凭据目的地改变后,旧审批会失效。缺失的 provider 引用会作为依赖审批保留,而不会被写成不可用的默认值;无关实体仍可继续应用。
+Host 绝不会仅因为 UI flag 被设置就激活暂存的可执行内容。新导入的 automation 定义同样会被禁用,直到本设备明确取得执行所有权;已有本地任务继续使用其设备本地启用状态。
+
+导入路径会在应用每个实体前重新检查捕获到的本地 generation。捕获之后发生的修改会保留,并在下一轮重新协调。持久化的加密 pending bundle 会记录捕获的本地 manifest 和 `applying` 标记;重启恢复会完成已审批步骤,或在认为配置已收敛前保留 bundle 供重试。现有的本地 MCP 直接创建行为不变。
+
+## 5. 设置工作流
+
+设置 → 云同步提供 WebDAV endpoint 凭据、vault 密码、设备标签、类别选择、能力测试、立即同步、解锁、暂停、文件夹映射、批准/拒绝、revision history/restore、vault 密码重新包裹以及断开连接控制。Renderer 将 `notConfigured`、`locked`、`upToDate`、`localChangesPending`、`syncing`、`offline`、`unsupportedServer`、`conflict`、`awaitingActivation`、`paused` 和 `error` 显示为不同状态。断开连接会保留本地数据,不会删除远端数据。
+
+凭据和 memory 默认未选中。设置预览报告 supported、excluded、secret-bearing、mapping-required 和 pending-activation 计数。原始秘密值、vault key 和备份密码永远不会跨过 Renderer 边界。
+
+Host 负责自动同步启用后的启动即时检查、30 秒本地变更防抖以及有界的五分钟远端轮询。失败网络请求使用带 jitter 且有上限的指数重试;paused、locked、不兼容、认证和错误密码状态不会启动重试循环。应用退出时 worker 会随 Host 取消;退出后没有额外 daemon。
+
+## 6. 持久性与兼容性
+
+同步配置存储在 Host 的 `kv` namespace 中。vault key 和 WebDAV password 使用现有 Host secret store。本地基线和 pending bundle 会加密,并通过临时文件 rename 替换。格式错误或未认证的本地 bundle 会报告错误,而不是当作空状态。备份格式版本独立于 SQLite schema;遇到更新格式时会拒绝且不截断本地表示。
+
+远端 history 保留最新 30 个可达的逻辑 revision,并保护当前 head、merge base、待处理冲突引用和恢复点;只有在宽限期结束且发布成功后才会删除未引用对象。restore 会先写入恢复前的本地加密恢复点,再发布新的 revision。vault 密码变更会 CAS 更新 wrapped-key header,但不会改变 vault data key;已复制的旧 key 无法被密码变更进行密码学撤销,因此移除设备不等同于撤销访问。
+
+项目组映射接受有序的多根绑定,并保留 primary root 不变量。WebDAV 测试使用进程内 fixture 覆盖条件创建、strong-ETag 更新、旧 writer 拒绝、空 vault 竞争和 weak-ETag 拒绝。剩余的可用性限制是固有的:没有可信 head 历史的新设备无法证明恶意服务器返回的是最新有效备份。
diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index a263ed716..f5f61af31 100644
--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
@@ -5238,6 +5238,7 @@ eleven-tool-round desktop paths are verified by
| C / F — Hourly task updates | E2E-SCHEDULED-manual-to-hourly |
| C / F / Quality — Saved project isolation | E2E-SCHEDULED-manual-workspace-binding |
| C / F / Quality — 桌面定时任务 | E2E-SCHEDULED-desktop-automation-lifecycle |
+| F / Security / Quality — 便携式配置同步 | E2E-CONFIG-SYNC-webdav-portable-configuration |
| A / C — Unicode stdio 成帧 | E2E-RPC-unicode-separators |
| C / G / Quality — Plugins navigation | E2E-NAV-plugins-button-goes-back |
| C / D / Quality — 侧边栏行状态 | E2E-LAYOUT-sidebar-row-states |
@@ -8373,6 +8374,16 @@ the latest destination. These assertions measure work counts, not device FPS.
- **状态:** `node scripts/e2e-scheduled.mjs` 自动化覆盖;按 AGENTS.md 在任务候选
版本上运行,并记录已测提交与基线。
+### E2E-CONFIG-SYNC-webdav-portable-configuration
+
+- **前提:** 已构建的任务候选版本、隔离的 Host 配置,以及支持 strong ETag 和条件 PUT 的本地 WebDAV fixture。不使用真实 WebDAV 账户、provider 或生产桌面。
+- **步骤:** 1)打开设置 → 云同步,填写 fixture URL、设备标签、目录和备份密码。2)运行能力测试,确认使用临时对象。3)选择 provider/MCP/skill 类别,保持凭据和 memory 未选中;在第二次预览中启用凭据,确认只显示脱敏计数。4)配置设备 A,创建 user provider 和 MCP 定义并同步。5)让设备 B 连接同一 vault,同步后检查待激活/映射,并验证审批前不会运行命令或任务。6)批准一个变更后的安全实体,拒绝一个暂存实体,在两台设备上编辑不相交设置并再次同步。7)测试并发 head writer、错误密码、weak ETag、密文损坏、redirect、归档路径穿越和网络中断。
+- **预期:** 测试拒绝不可靠的条件写入。WebDAV 只能看到已认证的密文和不透明对象名;原始秘密不会出现在 Renderer 状态或日志中。相同和不相交的编辑会收敛,冲突保持可审查,明确删除使用 tombstone,类别退出不是删除,可执行导入在本地审批和映射前保持不激活。恢复不会暴露部分应用的本地配置。
+- **规格:** `03-runtime/22-config-sync.md`、`03-runtime/14-secrets-storage.md`、`05-security/01-security.md`、ADR 0300。
+- **验收:** F(持久化)、Security、Quality。
+- **里程碑:** M6+。
+- **状态:** Draft;合并/密码学和进程内 WebDAV 条件写入覆盖已存在。完整双设备进程路径和逐检查点本地恢复故障注入仍待自动化。
+
### E2E-DIALOG-long-text-boundaries
- **前提:** 已构建渲染器,使用隔离的 Electron 组件测试窗口。组件、状态、翻译
diff --git a/docs/zh-CN/spec/NAV.md b/docs/zh-CN/spec/NAV.md
index d51b3af11..3064b461e 100644
--- a/docs/zh-CN/spec/NAV.md
+++ b/docs/zh-CN/spec/NAV.md
@@ -46,6 +46,7 @@
- [19-remote-agent-control-protocol.md](/zh-CN/spec/03-runtime/19-remote-agent-control-protocol)
- [20-speech.md](/zh-CN/spec/03-runtime/20-speech)
- [21-image-generation.md](/zh-CN/spec/03-runtime/21-image-generation)
+- [22-config-sync.md](/zh-CN/spec/03-runtime/22-config-sync)
## 4. 用户体验
- [README.md](/zh-CN/spec/04-ux/README)
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index bf3a8c7de..f14c49f77 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -668,9 +668,118 @@ sklm: {
"subagents": "Subagenten",
"import": "Importieren Sie",
"projects": "Projekte",
+ "sync": "Cloud-Synchronisierung",
"remoteHosts": "Remote-Hosts",
"info": "Informationen"
},
+ "configSync": {
+ title: "Cloud sync",
+ connectionTitle: "WebDAV cloud sync",
+ connectionDescription:
+ "Synchronize portable configuration through an encrypted WebDAV vault. Conversation history, source files, and runtime state are never included.",
+ endpoint: "WebDAV URL",
+ endpointPlaceholder: "https://dav.example.com/",
+ username: "Username",
+ appPassword: "App password",
+ directory: "Remote directory",
+ deviceLabel: "Device label",
+ defaultDevice: "This device",
+ backupPassword: "Backup password",
+ backupPasswordUnlock: "Vault password",
+ backupPasswordHint:
+ "This password encrypts the vault. It never leaves this device.",
+ currentBackupPassword: "Current vault password",
+ newBackupPassword: "New vault password",
+ changePasswordTitle: "Change vault password",
+ changePasswordDescription: "Rewrap the vault key without exposing configuration data.",
+ changePassword: "Change password",
+ passwordChanged: "Vault password changed.",
+ showPassword: "Show password",
+ hidePassword: "Hide password",
+ test: "Test server",
+ testSuccess: "The server supports the required conditional writes.",
+ testUnsupported:
+ "The server did not prove reliable conditional writes; sync is not enabled.",
+ enable: "Enable sync",
+ save: "Save and sync",
+ configured: "Cloud sync configuration saved.",
+ syncNow: "Sync now",
+ statusTitle: "Sync status",
+ statusLabel: "Current state",
+ lastSuccess: "Last successful run: {{date}}",
+ lastError: "Latest error",
+ unlockTitle: "Unlock vault",
+ unlockDescription: "Unlock the local vault before reading or publishing data.",
+ unlock: "Unlock",
+ pauseTitle: "Pause this device",
+ pauseDescription: "Keep local data and stop automatic remote activity.",
+ categoriesTitle: "Portable configuration",
+ categoriesDescription:
+ "All supported configuration is selected by default. Credentials and memory require an explicit opt-in.",
+ categoryApplication: "Application preferences",
+ categoryProviders: "User-owned providers and models",
+ categoryMcp: "MCP definitions",
+ categorySkills: "Skills",
+ categorySubagents: "Subagents",
+ categoryInstructions: "Instructions and prompt templates",
+ categoryProjects: "Projects and folder mappings",
+ categoryPlugins: "Plugin installation intent",
+ categoryAutomation: "Automation definitions",
+ categoryMemory: "Project memory",
+ categoryCredentials: "Portable credentials",
+ credentialsWarning:
+ "Secrets are encrypted in the vault, but a new device still requires local approval and secure storage.",
+ approvalsTitle: "Awaiting local activation",
+ approvalsDescription:
+ "Imported executable or security-sensitive configuration is staged until you approve it on this device.",
+ approve: "Approve",
+ reject: "Reject",
+ mapFolder: "Ordner zuordnen",
+ approvalReason: {
+ newDevice: "New device",
+ securityChange: "Security-sensitive change",
+ dependency: "Secret or dependency required",
+ mapping: "Local folder mapping required",
+ conflict: "Conflict needs review",
+ },
+ previewTitle: "Setup preview",
+ previewSupported: "Supported items: {{count}}",
+ previewExcluded: "Excluded items: {{count}}",
+ previewSecrets: "Secret-bearing items: {{count}}",
+ previewMapping: "Mapping required: {{count}}",
+ mappingsTitle: "Project mappings",
+ mappingsDescription: "Local folders stay device-specific and are never uploaded.",
+ mappingUnavailable: "Folder unavailable",
+ historyTitle: "History and restore",
+ historyDescription: "Restore creates a new revision and propagates it after local approvals.",
+ refreshHistory: "Refresh history",
+ currentRevision: "Current revision",
+ historyItems: "items",
+ historyEmpty: "No remote revisions are available yet.",
+ historyLocked: "Unlock the vault to read revision history.",
+ restore: "Restore",
+ restoreConfirm: "Restore this revision and publish it to subscribed devices?",
+ restoreStarted: "Restore staged. Review pending approvals.",
+ disconnectTitle: "Disconnect",
+ disconnectDescription:
+ "Preserve local data and leave the remote vault untouched.",
+ disconnectConfirm:
+ "Disconnect this device? Local data stays here and remote data will not be deleted.",
+ disconnect: "Disconnect",
+ status: {
+ notConfigured: "Not configured",
+ locked: "Locked",
+ upToDate: "Up to date",
+ localChangesPending: "Local changes pending",
+ syncing: "Syncing",
+ offline: "Offline",
+ unsupportedServer: "Unsupported server",
+ conflict: "Conflict",
+ awaitingActivation: "Awaiting activation",
+ paused: "Paused",
+ error: "Needs attention",
+ },
+ },
"general": "Allgemein",
"ai": "AI",
"shortcuts": "Verknüpfungen",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 39010342e..fd21d488a 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -675,6 +675,7 @@ sklm: {
subagents: "Subagents",
import: "Import",
projects: "Projects",
+ sync: "Cloud sync",
remoteHosts: "Remote hosts",
info: "Info",
},
@@ -917,6 +918,117 @@ sklm: {
transportSsh: "SSH",
experimental: "Experimental",
},
+ configSync: {
+ title: "Cloud sync",
+ connectionTitle: "WebDAV cloud sync",
+ connectionDescription:
+ "Synchronize portable configuration through an encrypted WebDAV vault. Conversation history, source files, and runtime state are never included.",
+ endpoint: "WebDAV URL",
+ endpointPlaceholder: "https://dav.example.com/",
+ username: "Username",
+ appPassword: "App password",
+ directory: "Remote directory",
+ deviceLabel: "Device label",
+ defaultDevice: "This device",
+ backupPassword: "Backup password",
+ backupPasswordUnlock: "Vault password",
+ backupPasswordHint:
+ "This password encrypts the vault. It never leaves this device.",
+ currentBackupPassword: "Current vault password",
+ newBackupPassword: "New vault password",
+ changePasswordTitle: "Change vault password",
+ changePasswordDescription:
+ "Rewrap the vault key without re-encrypting or exposing configuration data.",
+ changePassword: "Change password",
+ passwordChanged: "Vault password changed.",
+ showPassword: "Show password",
+ hidePassword: "Hide password",
+ test: "Test server",
+ testSuccess: "The server supports the required conditional writes.",
+ testUnsupported:
+ "The server did not prove reliable conditional writes; sync is not enabled.",
+ enable: "Enable sync",
+ save: "Save and sync",
+ configured: "Cloud sync configuration saved.",
+ syncNow: "Sync now",
+ statusTitle: "Sync status",
+ statusLabel: "Current state",
+ lastSuccess: "Last successful run: {{date}}",
+ lastError: "Latest error",
+ unlockTitle: "Unlock vault",
+ unlockDescription: "Unlock the local vault before reading or publishing data.",
+ unlock: "Unlock",
+ pauseTitle: "Pause this device",
+ pauseDescription: "Keep local data and stop automatic remote activity.",
+ categoriesTitle: "Portable configuration",
+ categoriesDescription:
+ "All supported configuration is selected by default. Credentials and memory require an explicit opt-in.",
+ categoryApplication: "Application preferences",
+ categoryProviders: "User-owned providers and models",
+ categoryMcp: "MCP definitions",
+ categorySkills: "Skills",
+ categorySubagents: "Subagents",
+ categoryInstructions: "Instructions and prompt templates",
+ categoryProjects: "Projects and folder mappings",
+ categoryPlugins: "Plugin installation intent",
+ categoryAutomation: "Automation definitions",
+ categoryMemory: "Project memory",
+ categoryCredentials: "Portable credentials",
+ credentialsWarning:
+ "Secrets are encrypted in the vault, but a new device still requires local approval and secure storage.",
+ approvalsTitle: "Awaiting local activation",
+ approvalsDescription:
+ "Imported executable or security-sensitive configuration is staged until you approve it on this device.",
+ approve: "Approve",
+ reject: "Reject",
+ mapFolder: "Map folder",
+ approvalReason: {
+ newDevice: "New device",
+ securityChange: "Security-sensitive change",
+ dependency: "Secret or dependency required",
+ mapping: "Local folder mapping required",
+ conflict: "Conflict needs review",
+ },
+ previewTitle: "Setup preview",
+ previewSupported: "Supported items: {{count}}",
+ previewExcluded: "Excluded items: {{count}}",
+ previewSecrets: "Secret-bearing items: {{count}}",
+ previewMapping: "Mapping required: {{count}}",
+ mappingsTitle: "Project mappings",
+ mappingsDescription: "Local folders stay device-specific and are never uploaded.",
+ mappingUnavailable: "Folder unavailable",
+ historyTitle: "History and restore",
+ historyDescription:
+ "Restore creates a new revision and propagates the selected configuration to subscribed devices.",
+ refreshHistory: "Refresh history",
+ currentRevision: "Current revision",
+ historyItems: "items",
+ historyEmpty: "No remote revisions are available yet.",
+ historyLocked: "Unlock the vault to read revision history.",
+ restore: "Restore",
+ restoreConfirm:
+ "Restore this revision? The restored configuration will be published to other subscribed devices after local approvals.",
+ restoreStarted: "Restore staged. Review any pending local approvals.",
+ disconnectTitle: "Disconnect",
+ disconnectDescription:
+ "Preserve local data and leave the remote vault untouched.",
+ disconnectConfirm:
+ "Disconnect this device? Local data stays here and remote data will not be deleted.",
+ disconnect: "Disconnect",
+ status: {
+ notConfigured: "Not configured",
+ locked: "Locked",
+ upToDate: "Up to date",
+ localChangesPending: "Local changes pending",
+ syncing: "Syncing",
+ offline: "Offline",
+ unsupportedServer: "Unsupported server",
+ conflict: "Conflict",
+ awaitingActivation: "Awaiting activation",
+ paused: "Paused",
+ error: "Needs attention",
+ },
+ },
importTitle: "Import from other tools",
importScan: "Scan",
importScanning: "Scanning…",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index c2f8087be..9b2e313db 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -668,9 +668,118 @@ sklm: {
"subagents": "Subagentes",
"import": "Importar",
"projects": "Proyectos",
+ "sync": "Sincronización en la nube",
"remoteHosts": "Hosts remotos",
"info": "Información"
},
+ "configSync": {
+ title: "Cloud sync",
+ connectionTitle: "WebDAV cloud sync",
+ connectionDescription:
+ "Synchronize portable configuration through an encrypted WebDAV vault. Conversation history, source files, and runtime state are never included.",
+ endpoint: "WebDAV URL",
+ endpointPlaceholder: "https://dav.example.com/",
+ username: "Username",
+ appPassword: "App password",
+ directory: "Remote directory",
+ deviceLabel: "Device label",
+ defaultDevice: "This device",
+ backupPassword: "Backup password",
+ backupPasswordUnlock: "Vault password",
+ backupPasswordHint:
+ "This password encrypts the vault. It never leaves this device.",
+ currentBackupPassword: "Current vault password",
+ newBackupPassword: "New vault password",
+ changePasswordTitle: "Change vault password",
+ changePasswordDescription: "Rewrap the vault key without exposing configuration data.",
+ changePassword: "Change password",
+ passwordChanged: "Vault password changed.",
+ showPassword: "Show password",
+ hidePassword: "Hide password",
+ test: "Test server",
+ testSuccess: "The server supports the required conditional writes.",
+ testUnsupported:
+ "The server did not prove reliable conditional writes; sync is not enabled.",
+ enable: "Enable sync",
+ save: "Save and sync",
+ configured: "Cloud sync configuration saved.",
+ syncNow: "Sync now",
+ statusTitle: "Sync status",
+ statusLabel: "Current state",
+ lastSuccess: "Last successful run: {{date}}",
+ lastError: "Latest error",
+ unlockTitle: "Unlock vault",
+ unlockDescription: "Unlock the local vault before reading or publishing data.",
+ unlock: "Unlock",
+ pauseTitle: "Pause this device",
+ pauseDescription: "Keep local data and stop automatic remote activity.",
+ categoriesTitle: "Portable configuration",
+ categoriesDescription:
+ "All supported configuration is selected by default. Credentials and memory require an explicit opt-in.",
+ categoryApplication: "Application preferences",
+ categoryProviders: "User-owned providers and models",
+ categoryMcp: "MCP definitions",
+ categorySkills: "Skills",
+ categorySubagents: "Subagents",
+ categoryInstructions: "Instructions and prompt templates",
+ categoryProjects: "Projects and folder mappings",
+ categoryPlugins: "Plugin installation intent",
+ categoryAutomation: "Automation definitions",
+ categoryMemory: "Project memory",
+ categoryCredentials: "Portable credentials",
+ credentialsWarning:
+ "Secrets are encrypted in the vault, but a new device still requires local approval and secure storage.",
+ approvalsTitle: "Awaiting local activation",
+ approvalsDescription:
+ "Imported executable or security-sensitive configuration is staged until you approve it on this device.",
+ approve: "Approve",
+ reject: "Reject",
+ mapFolder: "Asignar carpeta",
+ approvalReason: {
+ newDevice: "New device",
+ securityChange: "Security-sensitive change",
+ dependency: "Secret or dependency required",
+ mapping: "Local folder mapping required",
+ conflict: "Conflict needs review",
+ },
+ previewTitle: "Setup preview",
+ previewSupported: "Supported items: {{count}}",
+ previewExcluded: "Excluded items: {{count}}",
+ previewSecrets: "Secret-bearing items: {{count}}",
+ previewMapping: "Mapping required: {{count}}",
+ mappingsTitle: "Project mappings",
+ mappingsDescription: "Local folders stay device-specific and are never uploaded.",
+ mappingUnavailable: "Folder unavailable",
+ historyTitle: "History and restore",
+ historyDescription: "Restore creates a new revision and propagates it after local approvals.",
+ refreshHistory: "Refresh history",
+ currentRevision: "Current revision",
+ historyItems: "items",
+ historyEmpty: "No remote revisions are available yet.",
+ historyLocked: "Unlock the vault to read revision history.",
+ restore: "Restore",
+ restoreConfirm: "Restore this revision and publish it to subscribed devices?",
+ restoreStarted: "Restore staged. Review pending approvals.",
+ disconnectTitle: "Disconnect",
+ disconnectDescription:
+ "Preserve local data and leave the remote vault untouched.",
+ disconnectConfirm:
+ "Disconnect this device? Local data stays here and remote data will not be deleted.",
+ disconnect: "Disconnect",
+ status: {
+ notConfigured: "Not configured",
+ locked: "Locked",
+ upToDate: "Up to date",
+ localChangesPending: "Local changes pending",
+ syncing: "Syncing",
+ offline: "Offline",
+ unsupportedServer: "Unsupported server",
+ conflict: "Conflict",
+ awaitingActivation: "Awaiting activation",
+ paused: "Paused",
+ error: "Needs attention",
+ },
+ },
"general": "General",
"ai": "AI",
"shortcuts": "Atajos",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index db98920a8..c4ea52aea 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -668,9 +668,118 @@ sklm: {
"subagents": "Sous-agents",
"import": "Importation",
"projects": "Projets",
+ "sync": "Synchronisation cloud",
"remoteHosts": "Hôtes distants",
"info": "Informations"
},
+ "configSync": {
+ title: "Cloud sync",
+ connectionTitle: "WebDAV cloud sync",
+ connectionDescription:
+ "Synchronize portable configuration through an encrypted WebDAV vault. Conversation history, source files, and runtime state are never included.",
+ endpoint: "WebDAV URL",
+ endpointPlaceholder: "https://dav.example.com/",
+ username: "Username",
+ appPassword: "App password",
+ directory: "Remote directory",
+ deviceLabel: "Device label",
+ defaultDevice: "This device",
+ backupPassword: "Backup password",
+ backupPasswordUnlock: "Vault password",
+ backupPasswordHint:
+ "This password encrypts the vault. It never leaves this device.",
+ currentBackupPassword: "Current vault password",
+ newBackupPassword: "New vault password",
+ changePasswordTitle: "Change vault password",
+ changePasswordDescription: "Rewrap the vault key without exposing configuration data.",
+ changePassword: "Change password",
+ passwordChanged: "Vault password changed.",
+ showPassword: "Show password",
+ hidePassword: "Hide password",
+ test: "Test server",
+ testSuccess: "The server supports the required conditional writes.",
+ testUnsupported:
+ "The server did not prove reliable conditional writes; sync is not enabled.",
+ enable: "Enable sync",
+ save: "Save and sync",
+ configured: "Cloud sync configuration saved.",
+ syncNow: "Sync now",
+ statusTitle: "Sync status",
+ statusLabel: "Current state",
+ lastSuccess: "Last successful run: {{date}}",
+ lastError: "Latest error",
+ unlockTitle: "Unlock vault",
+ unlockDescription: "Unlock the local vault before reading or publishing data.",
+ unlock: "Unlock",
+ pauseTitle: "Pause this device",
+ pauseDescription: "Keep local data and stop automatic remote activity.",
+ categoriesTitle: "Portable configuration",
+ categoriesDescription:
+ "All supported configuration is selected by default. Credentials and memory require an explicit opt-in.",
+ categoryApplication: "Application preferences",
+ categoryProviders: "User-owned providers and models",
+ categoryMcp: "MCP definitions",
+ categorySkills: "Skills",
+ categorySubagents: "Subagents",
+ categoryInstructions: "Instructions and prompt templates",
+ categoryProjects: "Projects and folder mappings",
+ categoryPlugins: "Plugin installation intent",
+ categoryAutomation: "Automation definitions",
+ categoryMemory: "Project memory",
+ categoryCredentials: "Portable credentials",
+ credentialsWarning:
+ "Secrets are encrypted in the vault, but a new device still requires local approval and secure storage.",
+ approvalsTitle: "Awaiting local activation",
+ approvalsDescription:
+ "Imported executable or security-sensitive configuration is staged until you approve it on this device.",
+ approve: "Approve",
+ reject: "Reject",
+ mapFolder: "Associer un dossier",
+ approvalReason: {
+ newDevice: "New device",
+ securityChange: "Security-sensitive change",
+ dependency: "Secret or dependency required",
+ mapping: "Local folder mapping required",
+ conflict: "Conflict needs review",
+ },
+ previewTitle: "Setup preview",
+ previewSupported: "Supported items: {{count}}",
+ previewExcluded: "Excluded items: {{count}}",
+ previewSecrets: "Secret-bearing items: {{count}}",
+ previewMapping: "Mapping required: {{count}}",
+ mappingsTitle: "Project mappings",
+ mappingsDescription: "Local folders stay device-specific and are never uploaded.",
+ mappingUnavailable: "Folder unavailable",
+ historyTitle: "History and restore",
+ historyDescription: "Restore creates a new revision and propagates it after local approvals.",
+ refreshHistory: "Refresh history",
+ currentRevision: "Current revision",
+ historyItems: "items",
+ historyEmpty: "No remote revisions are available yet.",
+ historyLocked: "Unlock the vault to read revision history.",
+ restore: "Restore",
+ restoreConfirm: "Restore this revision and publish it to subscribed devices?",
+ restoreStarted: "Restore staged. Review pending approvals.",
+ disconnectTitle: "Disconnect",
+ disconnectDescription:
+ "Preserve local data and leave the remote vault untouched.",
+ disconnectConfirm:
+ "Disconnect this device? Local data stays here and remote data will not be deleted.",
+ disconnect: "Disconnect",
+ status: {
+ notConfigured: "Not configured",
+ locked: "Locked",
+ upToDate: "Up to date",
+ localChangesPending: "Local changes pending",
+ syncing: "Syncing",
+ offline: "Offline",
+ unsupportedServer: "Unsupported server",
+ conflict: "Conflict",
+ awaitingActivation: "Awaiting activation",
+ paused: "Paused",
+ error: "Needs attention",
+ },
+ },
"general": "Général",
"ai": "AI",
"shortcuts": "Raccourcis",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 45baff3d5..b5c012ba8 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -676,9 +676,118 @@ sklm: {
subagents: "서브에이전트",
import: "가져오기",
projects: "프로젝트",
+ sync: "클라우드 동기화",
remoteHosts: "원격 호스트",
info: "정보",
},
+ configSync: {
+ title: "Cloud sync",
+ connectionTitle: "WebDAV cloud sync",
+ connectionDescription:
+ "Synchronize portable configuration through an encrypted WebDAV vault. Conversation history, source files, and runtime state are never included.",
+ endpoint: "WebDAV URL",
+ endpointPlaceholder: "https://dav.example.com/",
+ username: "Username",
+ appPassword: "App password",
+ directory: "Remote directory",
+ deviceLabel: "Device label",
+ defaultDevice: "This device",
+ backupPassword: "Backup password",
+ backupPasswordUnlock: "Vault password",
+ backupPasswordHint:
+ "This password encrypts the vault. It never leaves this device.",
+ currentBackupPassword: "Current vault password",
+ newBackupPassword: "New vault password",
+ changePasswordTitle: "Change vault password",
+ changePasswordDescription: "Rewrap the vault key without exposing configuration data.",
+ changePassword: "Change password",
+ passwordChanged: "Vault password changed.",
+ showPassword: "Show password",
+ hidePassword: "Hide password",
+ test: "Test server",
+ testSuccess: "The server supports the required conditional writes.",
+ testUnsupported:
+ "The server did not prove reliable conditional writes; sync is not enabled.",
+ enable: "Enable sync",
+ save: "Save and sync",
+ configured: "Cloud sync configuration saved.",
+ syncNow: "Sync now",
+ statusTitle: "Sync status",
+ statusLabel: "Current state",
+ lastSuccess: "Last successful run: {{date}}",
+ lastError: "Latest error",
+ unlockTitle: "Unlock vault",
+ unlockDescription: "Unlock the local vault before reading or publishing data.",
+ unlock: "Unlock",
+ pauseTitle: "Pause this device",
+ pauseDescription: "Keep local data and stop automatic remote activity.",
+ categoriesTitle: "Portable configuration",
+ categoriesDescription:
+ "All supported configuration is selected by default. Credentials and memory require an explicit opt-in.",
+ categoryApplication: "Application preferences",
+ categoryProviders: "User-owned providers and models",
+ categoryMcp: "MCP definitions",
+ categorySkills: "Skills",
+ categorySubagents: "Subagents",
+ categoryInstructions: "Instructions and prompt templates",
+ categoryProjects: "Projects and folder mappings",
+ categoryPlugins: "Plugin installation intent",
+ categoryAutomation: "Automation definitions",
+ categoryMemory: "Project memory",
+ categoryCredentials: "Portable credentials",
+ credentialsWarning:
+ "Secrets are encrypted in the vault, but a new device still requires local approval and secure storage.",
+ approvalsTitle: "Awaiting local activation",
+ approvalsDescription:
+ "Imported executable or security-sensitive configuration is staged until you approve it on this device.",
+ approve: "Approve",
+ reject: "Reject",
+ mapFolder: "폴더 매핑",
+ approvalReason: {
+ newDevice: "New device",
+ securityChange: "Security-sensitive change",
+ dependency: "Secret or dependency required",
+ mapping: "Local folder mapping required",
+ conflict: "Conflict needs review",
+ },
+ previewTitle: "Setup preview",
+ previewSupported: "Supported items: {{count}}",
+ previewExcluded: "Excluded items: {{count}}",
+ previewSecrets: "Secret-bearing items: {{count}}",
+ previewMapping: "Mapping required: {{count}}",
+ mappingsTitle: "Project mappings",
+ mappingsDescription: "Local folders stay device-specific and are never uploaded.",
+ mappingUnavailable: "Folder unavailable",
+ historyTitle: "History and restore",
+ historyDescription: "Restore creates a new revision and propagates it after local approvals.",
+ refreshHistory: "Refresh history",
+ currentRevision: "Current revision",
+ historyItems: "items",
+ historyEmpty: "No remote revisions are available yet.",
+ historyLocked: "Unlock the vault to read revision history.",
+ restore: "Restore",
+ restoreConfirm: "Restore this revision and publish it to subscribed devices?",
+ restoreStarted: "Restore staged. Review pending approvals.",
+ disconnectTitle: "Disconnect",
+ disconnectDescription:
+ "Preserve local data and leave the remote vault untouched.",
+ disconnectConfirm:
+ "Disconnect this device? Local data stays here and remote data will not be deleted.",
+ disconnect: "Disconnect",
+ status: {
+ notConfigured: "Not configured",
+ locked: "Locked",
+ upToDate: "Up to date",
+ localChangesPending: "Local changes pending",
+ syncing: "Syncing",
+ offline: "Offline",
+ unsupportedServer: "Unsupported server",
+ conflict: "Conflict",
+ awaitingActivation: "Awaiting activation",
+ paused: "Paused",
+ error: "Needs attention",
+ },
+ },
general: "일반",
ai: "AI",
shortcuts: "단축키",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index c220b0870..29c94b55c 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -676,9 +676,110 @@ sklm: {
subagents: "Alt ajanlar",
import: "İçe aktar",
projects: "Projeler",
+ sync: "Bulut senkronizasyonu",
remoteHosts: "Uzak ana bilgisayarlar",
info: "Bilgi",
},
+ configSync: {
+ title: "Bulut senkronizasyonu",
+ connectionTitle: "WebDAV bulut senkronizasyonu",
+ connectionDescription: "Şifreli bir WebDAV kasası üzerinden taşınabilir yapılandırmayı senkronize edin.",
+ endpoint: "WebDAV URL'si",
+ endpointPlaceholder: "https://dav.example.com/",
+ username: "Kullanıcı adı",
+ appPassword: "Uygulama parolası",
+ directory: "Uzak dizin",
+ deviceLabel: "Cihaz etiketi",
+ defaultDevice: "Bu cihaz",
+ backupPassword: "Yedekleme parolası",
+ backupPasswordUnlock: "Kasa parolası",
+ backupPasswordHint: "Bu parola kasayı şifreler ve cihazdan ayrılmaz.",
+ currentBackupPassword: "Mevcut kasa parolası",
+ newBackupPassword: "Yeni kasa parolası",
+ changePasswordTitle: "Kasa parolasını değiştir",
+ changePasswordDescription: "Yapılandırma verilerini açığa çıkarmadan kasa anahtarını yeniden sarar.",
+ changePassword: "Parolayı değiştir",
+ passwordChanged: "Kasa parolası değiştirildi.",
+ showPassword: "Parolayı göster",
+ hidePassword: "Parolayı gizle",
+ test: "Sunucuyu test et",
+ testSuccess: "Sunucu gerekli koşullu yazma işlemlerini destekliyor.",
+ testUnsupported: "Sunucu güvenilir koşullu yazmayı kanıtlayamadı; senkronizasyon etkinleştirilmedi.",
+ enable: "Senkronizasyonu etkinleştir",
+ save: "Kaydet ve senkronize et",
+ configured: "Bulut senkronizasyonu yapılandırması kaydedildi.",
+ syncNow: "Şimdi senkronize et",
+ statusTitle: "Senkronizasyon durumu",
+ statusLabel: "Geçerli durum",
+ lastSuccess: "Son başarılı çalışma: {{date}}",
+ lastError: "Son hata",
+ unlockTitle: "Kasayı aç",
+ unlockDescription: "Verileri okumak veya yayınlamak için yerel kasanın kilidini açın.",
+ unlock: "Kilidi aç",
+ pauseTitle: "Bu cihazda duraklat",
+ pauseDescription: "Yerel verileri koruyun ve otomatik uzak etkinliği durdurun.",
+ categoriesTitle: "Taşınabilir yapılandırma",
+ categoriesDescription: "Desteklenen yapılandırmalar varsayılan olarak seçilir. Kimlik bilgileri ve bellek açıkça seçilmelidir.",
+ categoryApplication: "Uygulama tercihleri",
+ categoryProviders: "Kullanıcı sağlayıcıları ve modeller",
+ categoryMcp: "MCP tanımları",
+ categorySkills: "Beceriler",
+ categorySubagents: "Alt ajanlar",
+ categoryInstructions: "Yönergeler ve istem şablonları",
+ categoryProjects: "Projeler ve klasör eşlemeleri",
+ categoryPlugins: "Eklenti yükleme amacı",
+ categoryAutomation: "Otomasyon tanımları",
+ categoryMemory: "Proje belleği",
+ categoryCredentials: "Taşınabilir kimlik bilgileri",
+ credentialsWarning: "Gizli bilgiler kasada şifrelenir; yeni cihaz yine de yerel onay ve güvenli depolama gerektirir.",
+ approvalsTitle: "Yerel etkinleştirme bekleniyor",
+ approvalsDescription: "İçe aktarılan çalıştırılabilir veya güvenlik açısından hassas yapılandırma, bu cihazda onaylanana kadar bekletilir.",
+ approve: "Onayla",
+ reject: "Reddet",
+ mapFolder: "Klasörü eşle",
+ approvalReason: {
+ newDevice: "Yeni cihaz",
+ securityChange: "Güvenlik açısından hassas değişiklik",
+ dependency: "Gizli bilgi veya bağımlılık gerekli",
+ mapping: "Yerel klasör eşlemesi gerekli",
+ conflict: "Çakışma incelemesi gerekli",
+ },
+ previewTitle: "Kurulum önizlemesi",
+ previewSupported: "Desteklenen öğeler: {{count}}",
+ previewExcluded: "Hariç tutulan öğeler: {{count}}",
+ previewSecrets: "Gizli bilgi içeren öğeler: {{count}}",
+ previewMapping: "Eşleme gerekli: {{count}}",
+ mappingsTitle: "Proje eşlemeleri",
+ mappingsDescription: "Yerel klasörler cihaza özeldir ve asla yüklenmez.",
+ mappingUnavailable: "Klasör kullanılamıyor",
+ historyTitle: "Geçmiş ve geri yükleme",
+ historyDescription: "Geri yükleme yeni bir sürüm oluşturur ve yerel onaylardan sonra yayar.",
+ refreshHistory: "Geçmişi yenile",
+ currentRevision: "Geçerli sürüm",
+ historyItems: "öğe",
+ historyEmpty: "Henüz uzak sürüm yok.",
+ historyLocked: "Sürüm geçmişini okumak için kasanın kilidini açın.",
+ restore: "Geri yükle",
+ restoreConfirm: "Bu sürüm geri yüklensin ve abone cihazlara yayınlansın mı?",
+ restoreStarted: "Geri yükleme hazırlandı. Bekleyen onayları inceleyin.",
+ disconnectTitle: "Bağlantıyı kes",
+ disconnectDescription: "Yerel verileri koruyun ve uzak kasaya dokunmayın.",
+ disconnectConfirm: "Bu cihazın bağlantısı kesilsin mi? Yerel veriler kalır ve uzak veriler silinmez.",
+ disconnect: "Bağlantıyı kes",
+ status: {
+ notConfigured: "Yapılandırılmadı",
+ locked: "Kilitli",
+ upToDate: "Güncel",
+ localChangesPending: "Yerel değişiklikler bekliyor",
+ syncing: "Senkronize ediliyor",
+ offline: "Çevrimdışı",
+ unsupportedServer: "Desteklenmeyen sunucu",
+ conflict: "Çakışma",
+ awaitingActivation: "Etkinleştirme bekleniyor",
+ paused: "Duraklatıldı",
+ error: "İlgilenilmesi gerekiyor",
+ },
+ },
general: "Genel",
ai: "AI",
shortcuts: "Kısayollar",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 02dc5da61..cdbfe54b4 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -666,9 +666,110 @@ sklm: {
subagents: "子智能体",
import: "导入",
projects: "项目",
+ sync: "云同步",
remoteHosts: "远程主机",
info: "信息",
},
+ configSync: {
+ title: "云同步",
+ connectionTitle: "WebDAV 云同步",
+ connectionDescription: "通过加密的 WebDAV 保管库同步可移植配置。不会包含对话历史、源文件或运行时状态。",
+ endpoint: "WebDAV 地址",
+ endpointPlaceholder: "https://dav.example.com/",
+ username: "用户名",
+ appPassword: "应用密码",
+ directory: "远程目录",
+ deviceLabel: "设备名称",
+ defaultDevice: "此设备",
+ backupPassword: "备份密码",
+ backupPasswordUnlock: "保管库密码",
+ backupPasswordHint: "此密码用于加密保管库,不会离开本设备。",
+ currentBackupPassword: "当前保管库密码",
+ newBackupPassword: "新的保管库密码",
+ changePasswordTitle: "更改保管库密码",
+ changePasswordDescription: "仅重新包装保管库密钥,不会暴露配置数据。",
+ changePassword: "更改密码",
+ passwordChanged: "保管库密码已更改。",
+ showPassword: "显示密码",
+ hidePassword: "隐藏密码",
+ test: "测试服务器",
+ testSuccess: "服务器支持所需的条件写入。",
+ testUnsupported: "服务器未能证明支持可靠的条件写入,未启用同步。",
+ enable: "启用同步",
+ save: "保存并同步",
+ configured: "云同步配置已保存。",
+ syncNow: "立即同步",
+ statusTitle: "同步状态",
+ statusLabel: "当前状态",
+ lastSuccess: "上次成功运行:{{date}}",
+ lastError: "最近错误",
+ unlockTitle: "解锁保管库",
+ unlockDescription: "解锁本地保管库后才能读取或发布数据。",
+ unlock: "解锁",
+ pauseTitle: "暂停此设备",
+ pauseDescription: "保留本地数据并停止自动远程活动。",
+ categoriesTitle: "可移植配置",
+ categoriesDescription: "默认选择所有受支持的配置。凭据和记忆需要明确选择。",
+ categoryApplication: "应用偏好",
+ categoryProviders: "用户提供商和模型",
+ categoryMcp: "MCP 定义",
+ categorySkills: "技能",
+ categorySubagents: "子智能体",
+ categoryInstructions: "指令和提示词模板",
+ categoryProjects: "项目和文件夹映射",
+ categoryPlugins: "插件安装意图",
+ categoryAutomation: "自动化定义",
+ categoryMemory: "项目记忆",
+ categoryCredentials: "可移植凭据",
+ credentialsWarning: "凭据会在保管库中加密,但新设备仍需本地审批和安全存储。",
+ approvalsTitle: "等待本地启用",
+ approvalsDescription: "导入的可执行或安全敏感配置会暂存,直到你在此设备上批准。",
+ approve: "批准",
+ reject: "拒绝",
+ mapFolder: "映射文件夹",
+ approvalReason: {
+ newDevice: "新设备",
+ securityChange: "安全敏感变更",
+ dependency: "需要凭据或依赖",
+ mapping: "需要本地文件夹映射",
+ conflict: "需要处理冲突",
+ },
+ previewTitle: "设置预览",
+ previewSupported: "受支持项目:{{count}}",
+ previewExcluded: "排除项目:{{count}}",
+ previewSecrets: "包含秘密的项目:{{count}}",
+ previewMapping: "需要映射:{{count}}",
+ mappingsTitle: "项目路径映射",
+ mappingsDescription: "本地文件夹仅保留在设备上,不会上传。",
+ mappingUnavailable: "文件夹不可用",
+ historyTitle: "历史与恢复",
+ historyDescription: "恢复会创建新版本,并在本地审批后同步到已订阅设备。",
+ refreshHistory: "刷新历史",
+ currentRevision: "当前版本",
+ historyItems: "项",
+ historyEmpty: "暂时没有可用的远程版本。",
+ historyLocked: "解锁保管库后才能读取版本历史。",
+ restore: "恢复",
+ restoreConfirm: "恢复此版本,并将其发布到已订阅设备吗?",
+ restoreStarted: "恢复已暂存,请检查待处理的本地审批。",
+ disconnectTitle: "断开连接",
+ disconnectDescription: "保留本地数据,不修改远程保管库。",
+ disconnectConfirm: "断开此设备?本地数据会保留,远程数据不会删除。",
+ disconnect: "断开连接",
+ status: {
+ notConfigured: "未配置",
+ locked: "已锁定",
+ upToDate: "已是最新",
+ localChangesPending: "有本地变更待同步",
+ syncing: "同步中",
+ offline: "离线",
+ unsupportedServer: "服务器不受支持",
+ conflict: "存在冲突",
+ awaitingActivation: "等待启用",
+ paused: "已暂停",
+ error: "需要处理",
+ },
+ },
general: "常规",
ai: "全局 AI",
shortcuts: "快捷键",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index d6f46a189..39f614962 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -666,9 +666,110 @@ sklm: {
subagents: "子智慧體",
import: "匯入",
projects: "專案",
+ sync: "雲端同步",
remoteHosts: "遠端主機",
info: "資訊",
},
+ configSync: {
+ title: "雲端同步",
+ connectionTitle: "WebDAV 雲端同步",
+ connectionDescription: "透過加密的 WebDAV 保管庫同步可攜式設定。不會包含對話記錄、原始碼或執行階段狀態。",
+ endpoint: "WebDAV 網址",
+ endpointPlaceholder: "https://dav.example.com/",
+ username: "使用者名稱",
+ appPassword: "應用程式密碼",
+ directory: "遠端目錄",
+ deviceLabel: "裝置名稱",
+ defaultDevice: "此裝置",
+ backupPassword: "備份密碼",
+ backupPasswordUnlock: "保管庫密碼",
+ backupPasswordHint: "此密碼用於加密保管庫,不會離開此裝置。",
+ currentBackupPassword: "目前保管庫密碼",
+ newBackupPassword: "新的保管庫密碼",
+ changePasswordTitle: "變更保管庫密碼",
+ changePasswordDescription: "只重新包裝保管庫金鑰,不會暴露設定資料。",
+ changePassword: "變更密碼",
+ passwordChanged: "保管庫密碼已變更。",
+ showPassword: "顯示密碼",
+ hidePassword: "隱藏密碼",
+ test: "測試伺服器",
+ testSuccess: "伺服器支援必要的條件寫入。",
+ testUnsupported: "伺服器未能證明支援可靠的條件寫入,因此未啟用同步。",
+ enable: "啟用同步",
+ save: "儲存並同步",
+ configured: "雲端同步設定已儲存。",
+ syncNow: "立即同步",
+ statusTitle: "同步狀態",
+ statusLabel: "目前狀態",
+ lastSuccess: "上次成功執行:{{date}}",
+ lastError: "最近錯誤",
+ unlockTitle: "解鎖保管庫",
+ unlockDescription: "解鎖本機保管庫後才能讀取或發布資料。",
+ unlock: "解鎖",
+ pauseTitle: "暫停此裝置",
+ pauseDescription: "保留本機資料並停止自動遠端活動。",
+ categoriesTitle: "可攜式設定",
+ categoriesDescription: "預設選取所有支援的設定。憑據和記憶需要明確選取。",
+ categoryApplication: "應用程式偏好設定",
+ categoryProviders: "使用者提供者與模型",
+ categoryMcp: "MCP 定義",
+ categorySkills: "技能",
+ categorySubagents: "子代理程式",
+ categoryInstructions: "指令與提示詞範本",
+ categoryProjects: "專案與資料夾對應",
+ categoryPlugins: "外掛程式安裝意圖",
+ categoryAutomation: "自動化定義",
+ categoryMemory: "專案記憶",
+ categoryCredentials: "可攜式憑據",
+ credentialsWarning: "憑據會在保管庫中加密,但新裝置仍需本機核准與安全儲存。",
+ approvalsTitle: "等待本機啟用",
+ approvalsDescription: "匯入的可執行或安全敏感設定會暫存,直到你在此裝置上核准。",
+ approve: "核准",
+ reject: "拒絕",
+ mapFolder: "對應資料夾",
+ approvalReason: {
+ newDevice: "新裝置",
+ securityChange: "安全敏感變更",
+ dependency: "需要憑據或相依項目",
+ mapping: "需要本機資料夾對應",
+ conflict: "需要處理衝突",
+ },
+ previewTitle: "設定預覽",
+ previewSupported: "支援項目:{{count}}",
+ previewExcluded: "排除項目:{{count}}",
+ previewSecrets: "包含秘密的項目:{{count}}",
+ previewMapping: "需要對應:{{count}}",
+ mappingsTitle: "專案路徑對應",
+ mappingsDescription: "本機資料夾只保留在裝置上,不會上傳。",
+ mappingUnavailable: "資料夾無法使用",
+ historyTitle: "歷史與還原",
+ historyDescription: "還原會建立新版本,並在本機核准後同步到已訂閱裝置。",
+ refreshHistory: "重新整理歷史",
+ currentRevision: "目前版本",
+ historyItems: "項",
+ historyEmpty: "目前沒有可用的遠端版本。",
+ historyLocked: "解鎖保管庫後才能讀取版本歷史。",
+ restore: "還原",
+ restoreConfirm: "要還原此版本並發布到已訂閱裝置嗎?",
+ restoreStarted: "還原已暫存,請檢查待處理的本機核准。",
+ disconnectTitle: "中斷連線",
+ disconnectDescription: "保留本機資料,不修改遠端保管庫。",
+ disconnectConfirm: "要中斷此裝置嗎?本機資料會保留,遠端資料不會刪除。",
+ disconnect: "中斷連線",
+ status: {
+ notConfigured: "未設定",
+ locked: "已鎖定",
+ upToDate: "已是最新",
+ localChangesPending: "有本機變更待同步",
+ syncing: "同步中",
+ offline: "離線",
+ unsupportedServer: "伺服器不受支援",
+ conflict: "存在衝突",
+ awaitingActivation: "等待啟用",
+ paused: "已暫停",
+ error: "需要處理",
+ },
+ },
general: "常規",
ai: "全域性 AI",
shortcuts: "快捷鍵",
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index ef28d1ea6..10498500e 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -112,6 +112,19 @@ export const IPC = {
projectOpenFolder: "pi-desktop/project/openFolder",
settingsGet: "pi-desktop/settings/get",
settingsSet: "pi-desktop/settings/set",
+ configSyncGetState: "pi-desktop/configSync/getState",
+ configSyncConfigure: "pi-desktop/configSync/configure",
+ configSyncTest: "pi-desktop/configSync/test",
+ configSyncSyncNow: "pi-desktop/configSync/syncNow",
+ configSyncPause: "pi-desktop/configSync/pause",
+ configSyncUnlock: "pi-desktop/configSync/unlock",
+ configSyncApprove: "pi-desktop/configSync/approve",
+ configSyncReject: "pi-desktop/configSync/reject",
+ configSyncMapProject: "pi-desktop/configSync/mapProject",
+ configSyncListHistory: "pi-desktop/configSync/listHistory",
+ configSyncRestore: "pi-desktop/configSync/restore",
+ configSyncChangePassword: "pi-desktop/configSync/changePassword",
+ configSyncDisconnect: "pi-desktop/configSync/disconnect",
networkProxyTest: "pi-desktop/network/testProxy",
commandShellList: "pi-desktop/commandShell/list",
secretsSet: "pi-desktop/secrets/set",
@@ -323,6 +336,7 @@ export const IPC = {
pluginInstallProgress: "pi-desktop/plugin/event/installProgress",
/** Host-originated app settings mutation (e.g. plugin `app.setTheme`). */
settingsChanged: "pi-desktop/app/event/settingsChanged",
+ configSyncChanged: "pi-desktop/configSync/event/changed",
extensionsUiPrompt: "pi-desktop/extensions/event/uiPrompt",
extensionsStatus: "pi-desktop/extensions/event/status",
pluginLauncherShown: "pi-desktop/pluginLauncher/event/shown",
diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts
index b03d5b7ae..402047cd7 100644
--- a/packages/shared/src/types.ts
+++ b/packages/shared/src/types.ts
@@ -22,3 +22,4 @@ export * from "./types/workpanel.js";
export * from "./types/filesystem.js";
export * from "./types/speech.js";
export * from "./types/remote-host.js";
+export * from "./types/config-sync.js";
diff --git a/packages/shared/src/types/config-sync.ts b/packages/shared/src/types/config-sync.ts
new file mode 100644
index 000000000..d1ea74c80
--- /dev/null
+++ b/packages/shared/src/types/config-sync.ts
@@ -0,0 +1,152 @@
+/**
+ * Public contracts for the Host-owned portable configuration synchronizer.
+ *
+ * These types intentionally contain status and redacted summaries only. Raw
+ * WebDAV credentials, vault keys, backup passwords, and portable secret values
+ * never cross the Host/Preload boundary.
+ */
+
+export const CONFIG_SYNC_CATEGORIES = [
+ "application",
+ "providers",
+ "credentials",
+ "mcp",
+ "skills",
+ "subagents",
+ "instructions",
+ "projects",
+ "plugins",
+ "automation",
+ "memory",
+] as const;
+
+export type ConfigSyncCategory = (typeof CONFIG_SYNC_CATEGORIES)[number];
+
+export type ConfigSyncStatus =
+ | "notConfigured"
+ | "locked"
+ | "upToDate"
+ | "localChangesPending"
+ | "syncing"
+ | "offline"
+ | "unsupportedServer"
+ | "conflict"
+ | "awaitingActivation"
+ | "paused"
+ | "error";
+
+export type ConfigSyncCategorySelection = Record<ConfigSyncCategory, boolean>;
+
+export type ConfigSyncPreferences = {
+ endpoint: string;
+ username: string;
+ directory: string;
+ deviceLabel: string;
+ allowInsecureHttp?: boolean;
+ categories: ConfigSyncCategorySelection;
+ includeSecrets: boolean;
+ includeMemory: boolean;
+ automaticSync: boolean;
+};
+
+export type ConfigSyncPreview = {
+ supported: number;
+ excluded: number;
+ secretBearing: number;
+ mappingRequired: number;
+ conflicts: number;
+ pendingActivation: number;
+ categories: Array<{
+ category: ConfigSyncCategory;
+ supported: number;
+ excluded: number;
+ secretBearing: number;
+ mappingRequired: number;
+ }>;
+};
+
+export type ConfigSyncPendingApproval = {
+ id: string;
+ domain: ConfigSyncCategory;
+ entityId: string;
+ label: string;
+ reason: "newDevice" | "securityChange" | "dependency" | "mapping" | "conflict";
+ digest: string;
+ createdAt: string;
+ mappingKey?: string;
+};
+
+export type ConfigSyncProjectMapping = {
+ logicalId: string;
+ path?: string;
+ paths?: string[];
+};
+
+export type ConfigSyncHistoryEntry = {
+ revisionId: string;
+ createdAt: string;
+ parentRevisionIds: string[];
+ entityCount: number;
+ resourceCount: number;
+ current: boolean;
+};
+
+export type ConfigSyncState = {
+ configured: boolean;
+ enabled: boolean;
+ paused: boolean;
+ locked: boolean;
+ status: ConfigSyncStatus;
+ endpoint?: string;
+ username?: string;
+ directory?: string;
+ deviceLabel?: string;
+ categories: ConfigSyncCategorySelection;
+ includeSecrets: boolean;
+ includeMemory: boolean;
+ automaticSync: boolean;
+ lastRunAt?: string;
+ lastSuccessAt?: string;
+ lastError?: string;
+ lastRevisionId?: string;
+ pendingApprovals: ConfigSyncPendingApproval[];
+ mappings: ConfigSyncProjectMapping[];
+ preview?: ConfigSyncPreview;
+};
+
+export type ConfigSyncConfigureInput = {
+ endpoint: string;
+ username: string;
+ /** Supplied only when changing the WebDAV credential. */
+ appPassword?: string;
+ directory: string;
+ deviceLabel: string;
+ /** Required when creating or unlocking the encrypted vault. */
+ backupPassword: string;
+ allowInsecureHttp?: boolean;
+ categories?: Partial<ConfigSyncCategorySelection>;
+ includeSecrets?: boolean;
+ includeMemory?: boolean;
+ automaticSync?: boolean;
+};
+
+export type ConfigSyncApprovalInput = {
+ approvalId: string;
+ digest: string;
+};
+
+export type ConfigSyncMapProjectInput = {
+ logicalId: string;
+ path?: string;
+ paths?: string[];
+};
+
+export type ConfigSyncChangePasswordInput = {
+ currentPassword: string;
+ newPassword: string;
+};
+
+export type ConfigSyncRestoreInput = {
+ revisionId: string;
+ acknowledgePropagation: boolean;
+};