Merge dev: consolidate navigation and absorb 0.1.13 features

- Space cleaning becomes one hub with junk / duplicates / large files tabs.
- System maintenance becomes one hub with repair / privacy / optimisation tabs.
- Permissions gains grouped startup entries, leftovers, advanced entries and
  grouped context-menu handlers.
- Desktop widget gets its own page and the desktop watch loop.
- Keep the security scan, quarantine and allowlist stack from main, and keep
  the tabbed settings page with its security section.
- Navigation: 维护 / 安全 / 洞察 / 桌面, with history and settings pinned at
  the bottom. Legacy cleanup/purge/storage/startup deep links map to the new
  pages.
- Remove second-level descriptions under page titles and trailing periods.
- Version 0.1.13 to match the merged feature set.
main
mula.liu 2026-11-25 17:30:48 +08:00
commit 51f9fdb085
78 changed files with 18150 additions and 4790 deletions

View File

@ -10,6 +10,16 @@ Squid 的重要变更记录在这里。版本号使用语义化版本,日期
- 版权署名改为 mula.liu,许可证明确为 GPL-3.0-only。
- GitHub 作为源码镜像,不承载 `releases` 分支;新增 `scripts/sync-github.sh` 同步脚本。
## [0.1.13] - 2026-11-25
- 合并 dev 分支的空间清理、系统维护、权限管理与桌面小工具改造,左侧导航按功能合并为“维护 / 安全 / 洞察 / 桌面”四组。
- 空间清理升级为“垃圾清理 / 重复文件 / 大文件”三页签,切换页签保留扫描结果与勾选状态。
- 系统维护升级为“一键修复 / 隐私清理 / 系统优化”三页签。
- 权限管理新增开机启动项分组、残留识别、系统项隐藏、右键菜单分组与进阶启动项。
- 重复文件支持“本组一份不剩”,删除仍走回收站并可撤销。
- 保留并接入安全扫描、隔离区与白名单机制;安全入口位于“安全”分组。
- 概览页采用新的三列指标布局,所有页面一级标题下不再重复二级描述。
## [0.1.11] - 2026-11-22
- 设置页的“常规”和“清理”分区改为整行布局,删除方式仍并排显示,版面更清晰。

343
Cargo.lock generated
View File

@ -43,9 +43,9 @@ dependencies = [
[[package]]
name = "annotate-snippets"
version = "0.12.17"
version = "0.12.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2a5b0a5ab8561c603f16c3b78c24a386b1f70e7fc1b1b1e8c15738828e4a176"
checksum = "0258346f92c78dbc5b336b9a5b27c64447aa10643bc64e651db2edb145361564"
dependencies = [
"anstyle",
"memchr",
@ -119,9 +119,9 @@ dependencies = [
[[package]]
name = "ar_archive_writer"
version = "0.5.3"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73cd58deff2140a0a8eae87e417bd01db68a33e148aa93d1e8cd837e55e312b6"
checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec"
dependencies = [
"object",
]
@ -211,15 +211,6 @@ dependencies = [
"system-deps 6.2.2",
]
[[package]]
name = "atomic"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89cbf775b137e9b968e67227ef7f775587cde3fd31b0d8599dbd0f598a48340"
dependencies = [
"bytemuck",
]
[[package]]
name = "autocfg"
version = "1.5.1"
@ -343,9 +334,9 @@ dependencies = [
[[package]]
name = "bstr"
version = "1.13.1"
version = "1.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f"
checksum = "a680398c10c7bc0488067c4612226ea905a85f607134b69f3068d505d58c4214"
dependencies = [
"memchr",
"regex-automata",
@ -367,12 +358,6 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06"
[[package]]
name = "bytemuck"
version = "1.25.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
[[package]]
name = "cairo-rs"
version = "0.18.5"
@ -429,12 +414,12 @@ dependencies = [
[[package]]
name = "cfg-expr"
version = "0.20.10"
version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ba9e9ec16c447027685b1f897b720e18e9a8afd00bd7332c483537e38086c9f"
checksum = "8d4ba6e40bd1184518716a6e1a781bf9160e286d219ccdb8ab2612e74cfe4789"
dependencies = [
"smallvec",
"target-lexicon 0.13.5",
"target-lexicon 0.12.16",
]
[[package]]
@ -538,9 +523,9 @@ dependencies = [
[[package]]
name = "const-oid"
version = "0.10.2"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
[[package]]
name = "convert_case"
@ -598,27 +583,27 @@ dependencies = [
[[package]]
name = "cranelift-assembler-x64"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10c7459262c93a3c408bda96acaaa3d92868f166b33d445b20921f8378325038"
checksum = "da23f7367f4f5d003249eb1067760b3e6f5df82ad61829d40db22fdf8d41fd22"
dependencies = [
"cranelift-assembler-x64-meta",
]
[[package]]
name = "cranelift-assembler-x64-meta"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97a25bfba0da265ef1f98728358e9bb3ab7489913e7bd759c743108892288934"
checksum = "a8dbd10a21204ce6ae3786f8369860ec4e10a24913e987d5abe4c3cc0c7195d6"
dependencies = [
"cranelift-srcgen",
]
[[package]]
name = "cranelift-bforest"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a9ad33269057337a70db66950f426fbdce436a66fe8071f55851a13a2e40cd"
checksum = "4439be9aa2867bcef9effa83a265f550763a37b2cf4ad560c7bc41cbda947a48"
dependencies = [
"cranelift-entity",
"wasmtime-internal-core",
@ -626,9 +611,9 @@ dependencies = [
[[package]]
name = "cranelift-bitset"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d322e6584efe3b229b1164b49edf55aec561553426f7fe3e228a45e80a15a190"
checksum = "9913a7776903ccf6a3172633f59a0d6da2b428ec631c4b999a4b7401efdca1a7"
dependencies = [
"serde",
"serde_derive",
@ -637,9 +622,9 @@ dependencies = [
[[package]]
name = "cranelift-codegen"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a7b9f73f97da69d6edc9adbfeec068cdb2649f0221be41abd3909267cb1cd53"
checksum = "ffc88c2b684ca7df2ed79fa42b38a983e4d3632ee9d57bc2a389f69fc7ff9348"
dependencies = [
"bumpalo",
"cranelift-assembler-x64",
@ -662,15 +647,15 @@ dependencies = [
"serde_derive",
"sha2 0.10.9",
"smallvec",
"target-lexicon 0.13.5",
"target-lexicon 0.13.6",
"wasmtime-internal-core",
]
[[package]]
name = "cranelift-codegen-meta"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7015ef10993d7129e0bce933874b60dab8187239aca4ceca352987d9907d528"
checksum = "df667a6e48506af68c087cebee157bfe69e04d78df83e243025ce6473a538fcd"
dependencies = [
"cranelift-assembler-x64-meta",
"cranelift-codegen-shared",
@ -681,24 +666,24 @@ dependencies = [
[[package]]
name = "cranelift-codegen-shared"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37916b08a7b17e063bae743cb746da542df7df283ced961aae213620dc11e27a"
checksum = "ed3fdd2cd7bcd83a9263a978ea1d66477742a1a92095fa08f8752cb9a79ece11"
[[package]]
name = "cranelift-control"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8154d189f2cc2a84a95a8129773799ddcf2f4609f667047db30715db4be6aa0a"
checksum = "8e1ecc088bd88f5a271f55b1544a8ec60b9d7373f61efe267d54bd2481adf5a3"
dependencies = [
"arbitrary",
]
[[package]]
name = "cranelift-entity"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccbd0c43e96db753f44a84e44f680f9423ed0a475b81f301ba7c44b5db52c37b"
checksum = "2e9e591820d13f0671f879602ff29b241ea8b1dd54a386acbcbf4c3787f41af0"
dependencies = [
"cranelift-bitset",
"serde",
@ -708,45 +693,45 @@ dependencies = [
[[package]]
name = "cranelift-frontend"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b28ae2961cdda7a6814431b40e87bee46e57b7f92294467b32f447108e14674"
checksum = "b00cf9b20096b09b3499d19f82cca658c13c6988ecbc54881caf12a2f01b2f8c"
dependencies = [
"cranelift-codegen",
"hashbrown 0.17.1",
"log",
"smallvec",
"target-lexicon 0.13.5",
"target-lexicon 0.13.6",
]
[[package]]
name = "cranelift-isle"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41eef45b50970e024d673e3fc4a0703e4fee75ca31d63b26566eb0f142300179"
checksum = "4c9fc3f2d35b0b5879107b4c83246e3dfb93bf678e0c68f74f7bd9b7001f7a06"
[[package]]
name = "cranelift-native"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "649c7b9ad93d5d92287fee74608cacfb139602116293a46e2f25e6ea5402f05c"
checksum = "3c41c07ce15db19296c5ee3bed3019ec95bf2d773fbb28e73bdcb7fbc6ef9196"
dependencies = [
"cranelift-codegen",
"libc",
"target-lexicon 0.13.5",
"target-lexicon 0.13.6",
]
[[package]]
name = "cranelift-srcgen"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da04416d8e400ad7ae6d9722db72bfbddfbf36d0ff528ec422c4cc336621a172"
checksum = "7ed086d4ea76eb20e03b689abcc9a34bacaec54b1fc3e04269004acbed4587f0"
[[package]]
name = "crc32fast"
version = "1.5.4"
version = "1.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04"
checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945"
dependencies = [
"cfg-if",
]
@ -836,9 +821,9 @@ dependencies = [
[[package]]
name = "crypto-bigint"
version = "0.7.10"
version = "0.7.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c035cb64cba03dad2fb921f3e218785e8cf9a41790da5eb3a1400f62fa2be11"
checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82"
dependencies = [
"cpubits",
"ctutils",
@ -1235,7 +1220,7 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ff9f725b347b91d04340444fcbce0770886e4a6513e5f8e9e73a9e344efe73b"
dependencies = [
"gio 0.22.10",
"gio 0.22.11",
"gtk",
"log",
"objc2",
@ -1257,6 +1242,16 @@ dependencies = [
"winapi",
]
[[package]]
name = "filetime"
version = "0.2.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7"
dependencies = [
"cfg-if",
"libc",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.14"
@ -1529,16 +1524,16 @@ dependencies = [
[[package]]
name = "gio"
version = "0.22.10"
version = "0.22.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4620fbafdf19dba814473e19f18e75290cb3338662f6ae35f0402affd3b2b699"
checksum = "536990682bab3b8bf68a78d298ccae69702a114290b096edf2bec6eb2e4013b3"
dependencies = [
"futures-channel",
"futures-core",
"futures-io",
"futures-util",
"gio-sys 0.22.9",
"glib 0.22.10",
"gio-sys 0.22.11",
"glib 0.22.11",
"libc",
"pin-project-lite",
"smallvec",
@ -1559,11 +1554,11 @@ dependencies = [
[[package]]
name = "gio-sys"
version = "0.22.9"
version = "0.22.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c28739f914c15b87a9856000bed9cbd5b3a8afbca5e982d9a299e1601422cb5"
checksum = "b9c253490f9a475047f109bf6ccb68c407e9d186b7bfab01849188f4e669e669"
dependencies = [
"glib-sys 0.22.9",
"glib-sys 0.22.11",
"gobject-sys 0.22.9",
"libc",
"system-deps 9.0.1",
@ -1595,9 +1590,9 @@ dependencies = [
[[package]]
name = "glib"
version = "0.22.10"
version = "0.22.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4cf9e5bd8713f1990a92c422998826e0fb34824277b46bc59757373483c6694"
checksum = "c9c4cbf1972a07741ae5ce9b23a582a90efc69745fc713f8b037b8d962f604da"
dependencies = [
"bitflags 2.13.2",
"futures-channel",
@ -1605,8 +1600,8 @@ dependencies = [
"futures-executor",
"futures-task",
"futures-util",
"glib-macros 0.22.9",
"glib-sys 0.22.9",
"glib-macros 0.22.11",
"glib-sys 0.22.11",
"gobject-sys 0.22.9",
"libc",
"memchr",
@ -1629,9 +1624,9 @@ dependencies = [
[[package]]
name = "glib-macros"
version = "0.22.9"
version = "0.22.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9597c68fa7bdf4154a3079642cd21c4dccac0b0bdd2897d82861523bf91e7b9"
checksum = "d4014e54e2049108c93cf278b64e89f490849402e09b455a25dfa2098cc35093"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@ -1651,9 +1646,9 @@ dependencies = [
[[package]]
name = "glib-sys"
version = "0.22.9"
version = "0.22.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99b38907e67e40dec9b60f858bcada952598719cb512a13eb13d6cdcd16f8295"
checksum = "8b01e8b94529c2698b98f765b887f1e001b76195c1e25d1139aa9336019e745d"
dependencies = [
"libc",
"system-deps 9.0.1",
@ -1700,7 +1695,7 @@ version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07595c9ba696bd9819cb6a8df39f08078f3dd679508fe052dd558492c2053834"
dependencies = [
"glib-sys 0.22.9",
"glib-sys 0.22.11",
"libc",
"system-deps 9.0.1",
]
@ -1969,9 +1964,9 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "js-sys"
version = "0.3.106"
version = "0.3.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"
checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a"
dependencies = [
"cfg-if",
"futures-util",
@ -2001,12 +1996,6 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
[[package]]
name = "leb128"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52"
[[package]]
name = "leb128fmt"
version = "0.1.0"
@ -2057,9 +2046,9 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "litrs"
version = "1.0.1"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70"
checksum = "02b614978e47ce529faee66579f2b2fe19c94aa96d910a6a9a8043b2b02d8175"
[[package]]
name = "lock_api"
@ -2123,7 +2112,7 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3d0581a75c45969c63afd2bb87b1d8b25cfcc556c7a918cf9bb13b0fe8d2381"
dependencies = [
"nix 0.31.3",
"nix 0.31.4",
"windows-sys 0.61.2",
]
@ -2243,9 +2232,9 @@ dependencies = [
[[package]]
name = "nix"
version = "0.31.3"
version = "0.31.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
checksum = "2bc81ce8148d3b4f3274da811f11cdd824ae661ee4ef732cdb229825cf5be7f7"
dependencies = [
"bitflags 2.13.2",
"cfg-if",
@ -2677,9 +2666,9 @@ dependencies = [
[[package]]
name = "pest"
version = "2.9.5"
version = "2.9.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a8db75153506001cb36ed924f08cadc862eb3f8c4d0d534139f29074769d7660"
checksum = "44cf434b793f79ab490e99ae3b2f9acce4ef02cdac3eee541a69de78c1aadd7c"
dependencies = [
"memchr",
"pest_stack_guard",
@ -2688,9 +2677,9 @@ dependencies = [
[[package]]
name = "pest_derive"
version = "2.9.5"
version = "2.9.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20aa17e11fb35664b67d5214a0afac57a360d231b6ec53d6eba0700b27d933b4"
checksum = "082f5f21b49230a02b9ee78a8a39d5771fd0ed6dc4d88ecc9fd583cb781e5751"
dependencies = [
"pest",
"pest_generator",
@ -2698,9 +2687,9 @@ dependencies = [
[[package]]
name = "pest_generator"
version = "2.9.5"
version = "2.9.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "626ec5afccf44ccbfeb2b232316510bb55b4bf34d891afcb0fb07d2b17d7fe9d"
checksum = "5e4725db179c5bc5ea719d3312ce518f4b70d368139d630f4c9309d9117a3ac1"
dependencies = [
"pest",
"pest_meta",
@ -2711,9 +2700,9 @@ dependencies = [
[[package]]
name = "pest_meta"
version = "2.9.5"
version = "2.9.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3f45b6caa65c1b08186832745159c2529994146340a7bf44168095469720f5d"
checksum = "8363b5d48f0960fc3db68b1c8aa0bdc1a370d465a8c74287172ed5093a4cf293"
dependencies = [
"pest",
]
@ -2846,9 +2835,9 @@ checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
[[package]]
name = "postcard"
version = "1.1.3"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24"
checksum = "5431b3dcfdf6d1985c87d11f267a171c0dec0a8cd544c6727b747d36365f1fca"
dependencies = [
"cobs",
"embedded-io 0.4.0",
@ -2974,9 +2963,9 @@ dependencies = [
[[package]]
name = "pulley-interpreter"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e6d73adcf2f76b98d3de7a31831b6d6436fd2b6518e0ad4f7cc722a12ad4133"
checksum = "1f153f8d747fe1a04a7323d84963bd99a609f41391357da9d35f1965fb2c58b7"
dependencies = [
"cranelift-bitset",
"log",
@ -2986,9 +2975,9 @@ dependencies = [
[[package]]
name = "pulley-macros"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5bde547f939ab9aa321a54c6694aef2e1e27741c2523c0627ff306677b3cbcff"
checksum = "90dd329c9c89b9d4cea5803db3399f34f122e93d43549058caf46f5a7d4406ec"
dependencies = [
"proc-macro2",
"quote",
@ -3194,9 +3183,9 @@ dependencies = [
[[package]]
name = "regalloc2"
version = "0.15.2"
version = "0.15.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "757712e8e61590d6d4f5d563483755538b5aa13467837a3b41cd9832509a7f85"
checksum = "34f923657880712029496c2e68bb40bef163806b2011adde559b28bbcedc82ea"
dependencies = [
"allocator-api2",
"bumpalo",
@ -3209,9 +3198,9 @@ dependencies = [
[[package]]
name = "regex"
version = "1.13.1"
version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
dependencies = [
"aho-corasick",
"memchr",
@ -3221,9 +3210,9 @@ dependencies = [
[[package]]
name = "regex-automata"
version = "0.4.18"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
dependencies = [
"aho-corasick",
"memchr",
@ -3232,9 +3221,9 @@ dependencies = [
[[package]]
name = "regex-syntax"
version = "0.8.11"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
[[package]]
name = "rfc6979"
@ -3270,9 +3259,9 @@ dependencies = [
[[package]]
name = "rsa"
version = "0.10.0-rc.21"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47cf9537fc2210e5db7a35a1cdda9d8d451b9df6fba234ec1cf0cd746c120c35"
checksum = "23e77fd77e0dea28b3011fd62d15445b7de7959333b0276d930e03be0f755699"
dependencies = [
"const-oid",
"crypto-bigint",
@ -3594,7 +3583,7 @@ dependencies = [
[[package]]
name = "squid-cli"
version = "0.1.11"
version = "0.1.13"
dependencies = [
"anyhow",
"chrono",
@ -3614,7 +3603,7 @@ dependencies = [
[[package]]
name = "squid-core"
version = "0.1.11"
version = "0.1.13"
dependencies = [
"anyhow",
"chrono",
@ -3633,27 +3622,30 @@ dependencies = [
[[package]]
name = "squid-engine"
version = "0.1.11"
version = "0.1.13"
dependencies = [
"anyhow",
"chrono",
"crossbeam-channel",
"dirs",
"filetime",
"globset",
"libc",
"rayon",
"serde",
"serde_json",
"sha2 0.10.9",
"squid-core",
"squid-platform",
"squid-rules",
"squid-stats",
"walkdir",
"winreg",
]
[[package]]
name = "squid-guard"
version = "0.1.11"
version = "0.1.13"
dependencies = [
"chrono",
"hex",
@ -3669,7 +3661,7 @@ dependencies = [
[[package]]
name = "squid-platform"
version = "0.1.11"
version = "0.1.13"
dependencies = [
"dirs",
"file_icon_provider",
@ -3689,7 +3681,7 @@ dependencies = [
[[package]]
name = "squid-rules"
version = "0.1.11"
version = "0.1.13"
dependencies = [
"globset",
"serde",
@ -3701,7 +3693,7 @@ dependencies = [
[[package]]
name = "squid-stats"
version = "0.1.11"
version = "0.1.13"
dependencies = [
"chrono",
"libc",
@ -3714,7 +3706,7 @@ dependencies = [
[[package]]
name = "squid-tui"
version = "0.1.11"
version = "0.1.13"
dependencies = [
"anyhow",
"chrono",
@ -3865,10 +3857,10 @@ version = "9.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db551ad38aac61d5e0343e0eeeb0163be3115c4e23b6a025959570ee0c03c67d"
dependencies = [
"cfg-expr 0.20.10",
"cfg-expr 0.17.2",
"heck 0.5.0",
"pkg-config",
"toml 1.2.1+spec-1.1.0",
"toml 1.2.3+spec-1.1.0",
"version-compare",
]
@ -3886,9 +3878,9 @@ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
[[package]]
name = "target-lexicon"
version = "0.13.5"
version = "0.13.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da"
[[package]]
name = "termcolor"
@ -4077,9 +4069,9 @@ dependencies = [
[[package]]
name = "toml"
version = "1.2.1+spec-1.1.0"
version = "1.2.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7"
checksum = "26b1f26e9485c1fa43ee89fe76e9f3fb9e2e52bb227f8594b4d687496b83d073"
dependencies = [
"indexmap",
"serde_core",
@ -4134,9 +4126,9 @@ dependencies = [
[[package]]
name = "toml_parser"
version = "1.1.5+spec-1.1.0"
version = "1.1.7+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
checksum = "0bb28d6e049a9766c3bd91a8326e6179f5b132dec87906bb97018ef7a2f3431a"
dependencies = [
"winnow 1.0.5",
]
@ -4155,9 +4147,9 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "ucd-trie"
version = "0.1.7"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971"
checksum = "8f20bdbfc9915686faa18fb5bbe8b4552778505defbf9f12289beefbc44092a6"
[[package]]
name = "unicode-ident"
@ -4202,11 +4194,10 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "uuid"
version = "1.29.0"
version = "1.29.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514"
checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64"
dependencies = [
"atomic",
"getrandom 0.4.3",
"js-sys",
"wasm-bindgen",
@ -4251,14 +4242,13 @@ dependencies = [
[[package]]
name = "walrus"
version = "0.27.3"
version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5691aeb3546554822fe2c13d63149c26a027cd07d900a72c7c7f37f4321bfaea"
checksum = "04f034ddbc5b46d705409d64c617d01b9ed8c6c9ccac0ab6483e907d525bbf37"
dependencies = [
"anyhow",
"gimli 0.32.3",
"id-arena",
"leb128",
"log",
"walrus-macro",
"wasm-encoder 0.245.1",
@ -4294,12 +4284,11 @@ dependencies = [
[[package]]
name = "wasm-bindgen"
version = "0.2.129"
version = "0.2.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409"
checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c"
dependencies = [
"cfg-if",
"once_cell",
"rustversion",
"wasm-bindgen-macro",
"wasm-bindgen-shared",
@ -4307,9 +4296,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.129"
version = "0.2.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535"
checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
@ -4317,9 +4306,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.129"
version = "0.2.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7"
checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a"
dependencies = [
"bumpalo",
"proc-macro2",
@ -4330,9 +4319,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.129"
version = "0.2.130"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"
checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e"
dependencies = [
"unicode-ident",
]
@ -4396,9 +4385,9 @@ dependencies = [
[[package]]
name = "wasmtime"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2afcadb2e7d0417cb8f3f322c66eff49338b288f22290c0ca0bd3e9570732aa"
checksum = "8f47e5ae0d077a8415d626b028a1701fd4d4b3ed4d57e21a0b5daefe99ae81f1"
dependencies = [
"addr2line",
"async-trait",
@ -4418,7 +4407,7 @@ dependencies = [
"serde",
"serde_derive",
"smallvec",
"target-lexicon 0.13.5",
"target-lexicon 0.13.6",
"wasmparser 0.254.2",
"wasmtime-environ",
"wasmtime-internal-core",
@ -4433,9 +4422,9 @@ dependencies = [
[[package]]
name = "wasmtime-environ"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2de252f4aedfff6c2054ea5bea2454878a931c56e2553c6356b581e5e30a7e4e"
checksum = "956c03e93a68f39d8fb93b5b72885e327b38249272b14cac7a968804f5bad49f"
dependencies = [
"anyhow",
"cpp_demangle",
@ -4454,7 +4443,7 @@ dependencies = [
"serde_derive",
"sha2 0.10.9",
"smallvec",
"target-lexicon 0.13.5",
"target-lexicon 0.13.6",
"wasm-encoder 0.254.2",
"wasmparser 0.254.2",
"wasmprinter",
@ -4464,15 +4453,15 @@ dependencies = [
[[package]]
name = "wasmtime-internal-component-util"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5ad52499e6246d30bf8bf509506bd637248eee17c8dd623e0c7dbe43e7a1036"
checksum = "59133f8e0df9cb35ed819c3aad45ca3c5984267ec0a38e9c463d2bfadea01988"
[[package]]
name = "wasmtime-internal-core"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8838d7debfc98a69342d260a990ea6f64adf498184915fccfdbd6718bb40a9b"
checksum = "1463b7c70e14ab1db19709f29f298affc1f0ea50ea59b519d8aec8a6f5a56453"
dependencies = [
"hashbrown 0.17.1",
"libm",
@ -4481,9 +4470,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-cranelift"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "478c09af53c545d96227b349d35c70fc78e99816923f41428ffff00974bcd145"
checksum = "1a70ad5c0cf92e3b3f0dc2d15d140b83083170fa31fae5dcdd836cabf66873cb"
dependencies = [
"cranelift-codegen",
"cranelift-control",
@ -4496,7 +4485,7 @@ dependencies = [
"object",
"pulley-interpreter",
"smallvec",
"target-lexicon 0.13.5",
"target-lexicon 0.13.6",
"thiserror 2.0.21",
"wasmparser 0.254.2",
"wasmtime-environ",
@ -4507,9 +4496,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-fiber"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96dce7a8ea302c0f1eb4154eb1756525c90c595bbabbc590abad64d4c5ff8bbb"
checksum = "cce8b2932cdefb95f711d05e11e5959efad509481f3987917a5ab9b12e784291"
dependencies = [
"cc",
"libc",
@ -4521,9 +4510,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-jit-debug"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "895f3231b24ce0c12c8a7bb129a9f6ddc6772ec78e59748e53af743dcdd733d1"
checksum = "4e380afb5a32fdb509c2eecd8ab55e8203db6487770738ef96c216fef5ff76aa"
dependencies = [
"cc",
"wasmtime-internal-versioned-export-macros",
@ -4531,9 +4520,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-jit-icache-coherence"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28b60a0c1f735da6b862679b763f8bab653caa477ccc603a25752488b795fec5"
checksum = "6e944d8cec74d9e20db5a874cbc82e1174bf78d1dc092dbf6d79048ff41abfdf"
dependencies = [
"libc",
"wasmtime-internal-core",
@ -4542,9 +4531,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-unwinder"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b97b2c29c8f458bdf1b948058bfbb8141aad0f7abcf0f7cb3479866f4316bf3c"
checksum = "9ef8cc822d036e5366d9e458cc918f75e08d2faa24115c75ac5f791b45f1c36d"
dependencies = [
"cranelift-codegen",
"log",
@ -4554,9 +4543,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-versioned-export-macros"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32766b38d56927eca9a65858ea8c7b1803424db82562aafd69727aa970057561"
checksum = "fb0a732411dc5a84d071df6f8d773cb84338e4c4cb2dbd21bcc4ccd70754df30"
dependencies = [
"proc-macro2",
"quote",
@ -5112,9 +5101,9 @@ dependencies = [
[[package]]
name = "yara-x"
version = "1.23.0"
version = "1.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8a5ff1e1bb43734cc68f3ddc94646c9740c8c559d38fae559f0c79076f801db"
checksum = "46490aa1d13df1247f106e9620f4221fc8a13b351a9aeef5a34a9b0eaafd78cb"
dependencies = [
"annotate-snippets",
"anyhow",
@ -5171,9 +5160,9 @@ dependencies = [
[[package]]
name = "yara-x-macros"
version = "1.23.0"
version = "1.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc0df20854de457fdeaa3207e6fa08e439d22c63628e37e5608ae4113ebd8a2a"
checksum = "5d9568f7c8c3ce9a14a8ef472612bb86668cad05854155173de85b53c2c7189b"
dependencies = [
"darling",
"proc-macro2",
@ -5183,9 +5172,9 @@ dependencies = [
[[package]]
name = "yara-x-parser"
version = "1.23.0"
version = "1.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "336c1ef292d1d554526b10908198b71920f64dd58e56f39c8689b298fe858a1d"
checksum = "a7b6d18b9aeceb80d3516efc6658589d4311ee07bc4d29f1d740c28201b37109"
dependencies = [
"ascii_tree",
"bitflags 2.13.2",
@ -5201,9 +5190,9 @@ dependencies = [
[[package]]
name = "zeroize"
version = "1.9.1"
version = "1.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
[[package]]
name = "zlib-rs"

View File

@ -4,7 +4,7 @@ members = ["crates/*"]
exclude = ["src-tauri"]
[workspace.package]
version = "0.1.11"
version = "0.1.13"
edition = "2021"
rust-version = "1.95"
license = "GPL-3.0-only"
@ -35,6 +35,8 @@ dirs = "6"
libc = "0.2"
plist = "1"
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
sha2 = "0.10"
filetime = "0.2"
sysinfo = { version = "0.34", default-features = false, features = ["system", "network", "disk", "user"] }
crossterm = "0.28"
ratatui = "0.30"

View File

@ -1,9 +1,11 @@
Squid 0.1.11
Squid 0.1.13
- 设置页的“常规”和“清理”分区改为整行布局,删除方式仍并排显示,版面更清晰。
- 所有应用页移除一级标题下的二级描述,并收紧标题间距,减少重复信息。
- 安全页新增白名单机制:可按发布者、应用目录或提示类型信任正常软件。
- 已信任内容不再出现在默认列表和托盘计数中,可在安全页“已信任”筛选和“设置 → 安全”中查看、撤销。
- 已确认威胁永远不会被白名单静默,目录信任也会拒绝系统目录、下载目录等过宽范围。
- 左侧导航按功能合并为“维护 / 安全 / 洞察 / 桌面”四组,常用入口更集中。
- 空间清理整合“垃圾清理 / 重复文件 / 大文件”三页签,切换时保留扫描结果与勾选。
- 系统维护整合“一键修复 / 隐私清理 / 系统优化”三页签。
- 权限管理升级开机启动项:状态筛选、残留识别、系统项隐藏、按软件分组。
- 右键菜单扩展按软件分组,重复文件支持“本组一份不剩”,删除均走回收站。
- 保留安全扫描、隔离区与白名单机制,可在“安全扫描”页和设置的安全分区管理。
- 所有页面一级标题下不再显示二级描述,标题末尾不再带句号。
macOS 与 Windows 安装包均为未签名构建。macOS 首次打开请在访达中右键选择“打开”;Windows SmartScreen 提示时选择“更多信息” > “仍要运行”。

View File

@ -619,7 +619,10 @@ fn with_progress<T>(
freed.human()
),
),
Event::Bucket { .. } | Event::Done(_) => {}
Event::Bucket { .. }
| Event::Metered { .. }
| Event::Group { .. }
| Event::Done(_) => {}
}
}
if stop_now {

View File

@ -66,6 +66,8 @@ enum Command {
Uninstall(UninstallArgs),
/// Deep clean: node_modules, build folders, disk images, stale archives
Purge(PurgeArgs),
/// Find byte-identical duplicate files (three-stage hash funnel)
Dupes(DupesArgs),
/// Open the interface: disk map, system meters, cleanup, history
State,
/// One-shot system snapshot (scripts, dotfiles, cron)
@ -145,6 +147,18 @@ struct PurgeArgs {
min_age: Option<u64>,
}
#[derive(Args, Debug)]
struct DupesArgs {
/// Where to look; defaults to your user folders on every drive
paths: Vec<String>,
/// Size floor in bytes (default 1 MiB)
#[arg(long)]
min_size: Option<u64>,
/// How many groups to print
#[arg(long, default_value_t = 20)]
top: usize,
}
#[derive(Args, Debug)]
struct StatusArgs {
/// How many processes to list
@ -378,6 +392,7 @@ fn run() -> Result<i32> {
Some(Command::Clean(args)) => cmd_clean(args, cli.json),
Some(Command::Uninstall(args)) => cmd_uninstall(args, cli.json),
Some(Command::Purge(args)) => cmd_purge(args, cli.json),
Some(Command::Dupes(args)) => cmd_dupes(args, cli.json),
Some(Command::Status(args)) => cmd_status(args, cli.json),
Some(Command::Analyze(args)) => cmd_analyze(args, cli.json),
Some(Command::History(args)) => cmd_history(args, cli.json),
@ -599,7 +614,10 @@ fn with_progress<T>(
),
);
}
Event::Bucket { .. } | Event::Done(_) => {}
Event::Bucket { .. }
| Event::Metered { .. }
| Event::Group { .. }
| Event::Done(_) => {}
}
}
if stop_now {
@ -1147,6 +1165,75 @@ fn cmd_purge(args: PurgeArgs, json: bool) -> Result<i32> {
// ---------------------------------------------------------------------- status
fn cmd_dupes(args: DupesArgs, json: bool) -> Result<i32> {
use squid_engine::duplicates;
let roots: Vec<PathBuf> = if args.paths.is_empty() {
duplicates::default_roots()
} else {
args.paths.iter().map(|path| paths::expand(path)).collect()
};
heading("Duplicate files");
let report = with_progress("dupes", move |_engine, progress, cancel| {
duplicates::scan(
&roots,
args.min_size.unwrap_or(duplicates::DEFAULT_MIN_SIZE),
progress,
cancel,
)
})?;
if json {
println!("{}", serde_json::to_string_pretty(&report)?);
return Ok(0);
}
shout(
"90",
&format!(
" funnel: {} walked → {} same-size → {} confirmed files in {} groups",
squid_core::bytes::format_thousands(report.walked),
squid_core::bytes::format_thousands(report.same_size),
squid_core::bytes::format_thousands(report.confirmed_files),
squid_core::bytes::format_thousands(report.confirmed_groups),
),
);
for group in report.groups.iter().take(args.top) {
let waste = group.size * (group.copies.len() as u64 - 1);
shout(
"36",
&format!(
" {} {} copies · {} each (wastes {})",
bullet(),
group.copies[0]
.path
.rsplit(['\\', '/'])
.next()
.unwrap_or("?"),
squid_core::Bytes(group.size).human(),
squid_core::Bytes(waste).human(),
),
);
for copy in &group.copies {
shout("90", &format!(" · {}", copy.path));
}
}
if report.groups.len() > args.top {
shout(
"90",
&format!(
" … {} more groups (--top N to see them)",
report.groups.len() - args.top
),
);
}
shout(
"90",
&format!(
" total waste {}\n nothing deleted — the app offers these with recycle-bin undo",
squid_core::Bytes(report.wasted).human_long(),
),
);
Ok(0)
}
fn cmd_status(args: StatusArgs, json: bool) -> Result<i32> {
let mut sampler = squid_stats::Sampler::new();
let _ = sampler.prime();

View File

@ -30,6 +30,8 @@ pub struct SizeInfo {
pub files: u64,
pub dirs: u64,
pub unreadable: u32,
/// Newest last-modified seen while walking (unix seconds). `0` = unknown.
pub newest_write: u64,
}
impl SizeInfo {
@ -56,6 +58,7 @@ impl SizeInfo {
self.files += other.files;
self.dirs += other.dirs;
self.unreadable += other.unreadable;
self.newest_write = self.newest_write.max(other.newest_write);
}
/// "12,431 files" style annotation for detail rows.
@ -207,6 +210,7 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo {
if meta.file_type().is_symlink() {
info.files += 1;
info.logical += Bytes(meta.len());
info.newest_write = mtime_secs(&meta);
return info;
}
match kind {
@ -214,6 +218,7 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo {
info.files += 1;
info.logical += Bytes(meta.len());
info.allocated += Bytes(allocated_bytes(path, &meta));
info.newest_write = mtime_secs(&meta);
return info;
}
ItemKind::Path | ItemKind::Contents => {}
@ -222,6 +227,7 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo {
info.files += 1;
info.logical += Bytes(meta.len());
info.allocated += Bytes(allocated_bytes(path, &meta));
info.newest_write = mtime_secs(&meta);
return info;
}
@ -251,6 +257,7 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo {
info.files += 1;
info.logical += Bytes(meta.len());
info.allocated += Bytes(allocated_bytes(entry.path(), &meta));
info.newest_write = info.newest_write.max(mtime_secs(&meta));
}
Err(_) => info.unreadable += 1,
}
@ -261,6 +268,14 @@ pub fn measure(path: &Path, kind: ItemKind) -> SizeInfo {
info
}
/// Last-modified as unix seconds; 0 when the platform withholds it.
fn mtime_secs(meta: &Metadata) -> u64 {
meta.modified()
.ok()
.and_then(|when| when.duration_since(std::time::UNIX_EPOCH).ok())
.map_or(0, |age| age.as_secs())
}
/// Measure many paths in parallel. `progress` receives completed units.
/// `Path` for folders (and anything that should be removed recursively),
/// `File` for plain files and symlinks.
@ -280,7 +295,7 @@ pub fn kind_of(path: &Path) -> crate::model::ItemKind {
pub fn measure_all(
targets: &[(PathBuf, ItemKind)],
cancel: &CancelToken,
on_unit: impl Fn(usize, &SizeInfo) + Send + Sync,
on_unit: impl Fn(usize, usize, &SizeInfo) + Send + Sync,
) -> Vec<SizeInfo> {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(measure_threads())
@ -297,14 +312,18 @@ pub fn measure_all(
let results: Vec<SizeInfo> = pool.install(|| {
targets
.par_iter()
.map(|(path, kind)| {
.enumerate()
.map(|(index, (path, kind))| {
if cancel.is_cancelled() {
cancelled.store(true, Ordering::Relaxed);
return SizeInfo::default();
}
let info = measure(path, *kind);
let idx = done.fetch_add(1, Ordering::Relaxed) as usize;
emit(idx, &info);
let completed = done.fetch_add(1, Ordering::Relaxed) as usize + 1;
// (target index, completed count): index identifies the unit —
// callbacks arrive in completion order under rayon — while the
// count drives monotonic progress bars.
emit(index, completed, &info);
info
})
.collect()
@ -369,6 +388,7 @@ pub fn remove_item_with(
files: 0,
dirs: 0,
unreadable: 0,
newest_write: 0,
};
Ok(freed.on_disk().max(Bytes::ZERO))
}

View File

@ -20,10 +20,16 @@ pub enum Category {
LanguagePacks,
Leftovers,
UpdateInstallers,
/// Duplicate-file scan results (its own page, streamed group by group).
Duplicates,
/// AI tool caches and local model files (Ollama, HuggingFace, …).
AiTools,
/// Privacy traces: browser history, recent items, clipboard, activity.
Privacy,
}
impl Category {
pub const ALL: [Category; 10] = [
pub const ALL: [Category; 13] = [
Category::SystemJunk,
Category::AppCaches,
Category::BrowserCaches,
@ -34,6 +40,9 @@ impl Category {
Category::LanguagePacks,
Category::Leftovers,
Category::UpdateInstallers,
Category::Duplicates,
Category::AiTools,
Category::Privacy,
];
pub fn id(self) -> &'static str {
@ -48,6 +57,9 @@ impl Category {
Category::LanguagePacks => "languages",
Category::Leftovers => "leftovers",
Category::UpdateInstallers => "update-installers",
Category::Duplicates => "duplicates",
Category::AiTools => "ai",
Category::Privacy => "privacy",
}
}
@ -63,6 +75,9 @@ impl Category {
Category::LanguagePacks => "Unneeded Languages",
Category::Leftovers => "Uninstaller Leftovers",
Category::UpdateInstallers => "Update Installers",
Category::Duplicates => "Duplicate Files",
Category::AiTools => "AI Tools & Models",
Category::Privacy => "Privacy Traces",
}
}
@ -81,6 +96,9 @@ impl Category {
Category::LanguagePacks => "Speech and localization data for languages you do not use",
Category::Leftovers => "Data belonging to apps that are no longer installed",
Category::UpdateInstallers => "Installer packages apps keep after a successful update",
Category::Duplicates => "Byte-identical files confirmed by a three-stage hash funnel",
Category::AiTools => "Local model weights and caches that re-download when needed",
Category::Privacy => "History and traces that disappear without a recycle bin",
}
}
@ -109,6 +127,9 @@ impl Category {
"update-installer" | "update-installers" | "upgrades" | "upgrade-packages" => {
Category::UpdateInstallers
}
"duplicate" | "duplicates" | "duplicate-files" => Category::Duplicates,
"ai" | "ai-tools" | "ai-models" | "models" => Category::AiTools,
"privacy" | "privacy-traces" | "private" => Category::Privacy,
_ => return None,
};
Some(alias)
@ -165,6 +186,21 @@ pub struct CleanupItem {
/// stale or hand-edited item can never escape its sandbox.
#[serde(default)]
pub anchors: Vec<PathBuf>,
/// Seconds since the *most recent* last-write inside the item (Mole's
/// decision aid: 1.2 GB alone is not actionable, "untouched for 3 months"
/// is — and a low value flags a live, working directory). Unknown until
/// measurement; `None` for unreadable paths.
#[serde(default)]
pub last_write_secs: Option<u64>,
/// File count from measurement — lets the UI say "12 files · 5 folders".
#[serde(default)]
pub file_count: u64,
/// Machine-readable judgement tokens (Mole's evidence chain, made
/// visible): `lock:<file>`, `record:<file>`, `record-missing`,
/// `modified:<n>`, `git:ignored|untracked|none|tracked`, `age:<days>`,
/// `busy`. The UI renders each token as a ✓/! line in a detail panel.
#[serde(default)]
pub evidence: Vec<String>,
}
impl CleanupItem {
@ -187,6 +223,9 @@ impl CleanupItem {
lock: lock_default(kind),
note: None,
anchors: Vec::new(),
last_write_secs: None,
file_count: 0,
evidence: Vec::new(),
}
}
@ -380,10 +419,23 @@ pub struct AppInfo {
pub has_sibling_install: bool,
pub publisher: Option<String>,
pub installed_ms: Option<u64>,
/// Raw `DisplayIcon` registry value (Windows): a path, optionally with an
/// Raw `DisplayIcon` registry value (Windows): a path, optionally with a
/// `,index` suffix — the icon Explorer shows for this app.
#[serde(default)]
pub display_icon: Option<String>,
/// The uninstaller command recorded by the app itself, when present.
#[serde(default)]
pub uninstall_string: Option<String>,
/// Windows: the exact registry key holding this entry
/// (`HKCU|HKLM` + subkey), so an orphaned record can be removed after
/// its files are gone.
#[serde(default)]
pub reg_key: Option<String>,
/// Install is broken: neither the install folder nor the uninstaller
/// target exists any more (or MSI reports the product absent while the
/// registry record remains). 「安装不完整」 — offer leftover cleanup.
#[serde(default)]
pub dead: bool,
}
impl AppInfo {

View File

@ -30,6 +30,19 @@ pub enum Event {
total: Bytes,
count: usize,
},
/// Cumulative measurement counters, streamed while sizes are computed
/// (Mole's "Scanning: 128,431 files · 38.2 GB" live status line).
Metered {
files: u64,
bytes: Bytes,
},
/// A finished work unit streamed as soon as it is confirmed, shaped by
/// the producing engine (duplicate groups land while the scan still
/// runs — MangoDisk's lesson that results beat progress bars).
Group {
kind: &'static str,
payload: serde_json::Value,
},
Deleted {
path: PathBuf,
freed: Bytes,

View File

@ -186,6 +186,13 @@ pub struct SafetyPolicy {
/// Roots whose contents a non-admin run may still reach — on Unix
/// `/Applications`, on Windows `%ProgramData%` and `%PUBLIC%`.
pub outside_home_ok: Vec<PathBuf>,
/// Accept *any* existing volume as an allowed anchor, not just system
/// paths. The duplicate-file scan runs over whole drives by design — the
/// files are the user's own, they were confirmed byte-identical, and
/// deletion still goes through the recycle bin + undo path. Everything
/// else about the policy (hard-deny roots, protected folders, symlink
/// refusal) keeps its full teeth.
pub all_volumes_ok: bool,
}
impl Default for SafetyPolicy {
@ -208,6 +215,7 @@ impl Default for SafetyPolicy {
allow_system_paths: true,
follow_symlinks: false,
outside_home_ok: outside_home_ok(),
all_volumes_ok: false,
}
}
}
@ -234,6 +242,33 @@ impl SafetyPolicy {
self
}
/// Let an unprivileged run reach files on any existing volume (the
/// duplicate-file scan); see [`SafetyPolicy::all_volumes_ok`].
pub fn with_all_volumes(mut self) -> Self {
self.all_volumes_ok = true;
self
}
/// True when `norm` sits on a drive/volume that exists right now. The
/// scan-anchors-are-volumes rule keeps its teeth in the other checks:
/// hard-deny roots, deny-exact folders and reserved names all run first.
fn on_existing_volume(&self, norm: &Path) -> bool {
#[cfg(windows)]
{
match norm.components().next() {
Some(std::path::Component::Prefix(prefix)) => {
PathBuf::from(prefix.as_os_str()).exists()
}
_ => false,
}
}
#[cfg(not(windows))]
{
let _ = norm;
true
}
}
fn is_exact_denied(&self, path: &Path) -> bool {
self.deny_exact.iter().any(|deny| {
// Trailing glob star entries deny the directory itself only.
@ -304,6 +339,7 @@ impl SafetyPolicy {
}
if !self.allow_system_paths
&& !(self.all_volumes_ok && self.on_existing_volume(&norm))
&& !paths::is_within(&paths::home_dir(), &norm)
&& !self
.outside_home_ok

View File

@ -223,23 +223,9 @@ impl Default for Settings {
delete_mode: DeleteMode::Trash,
whitelist: Vec::new(),
disabled_rules: Vec::new(),
purge_roots: vec![
"~/code".into(),
"~/Code".into(),
"~/dev".into(),
"~/Dev".into(),
"~/develop".into(),
"~/projects".into(),
"~/Projects".into(),
"~/repos".into(),
"~/Repos".into(),
"~/src".into(),
"~/work".into(),
"~/Work".into(),
"~/Desktop".into(),
"~/Documents".into(),
"~/.codex/worktrees".into(),
],
// Auto-discovery (purge::resolve_roots) owns the default story;
// this list is now only for hand-edited extra folders.
purge_roots: Vec::new(),
purge_min_age_days: 7,
purge_max_entries: 200_000,
show_allocated: true,
@ -341,6 +327,13 @@ impl Settings {
.collect()
}
/// One raw whitelist line as a matcher — the shape the audit layer
/// needs when it must answer about a single pattern, not the list.
pub fn whitelist_matcher_for(raw: &str) -> Option<GlobMatcher> {
let expanded = paths::expand(raw).to_string_lossy().into_owned();
Glob::new(&expanded).ok().map(|g| g.compile_matcher())
}
pub fn is_whitelisted(&self, path: &Path, matchers: &[GlobMatcher]) -> bool {
if self.whitelist.is_empty() {
return false;

View File

@ -19,5 +19,10 @@ walkdir.workspace = true
globset.workspace = true
crossbeam-channel.workspace = true
chrono.workspace = true
sha2.workspace = true
filetime.workspace = true
dirs.workspace = true
libc.workspace = true
[target.'cfg(windows)'.dependencies]
winreg = "0.52"

View File

@ -0,0 +1,493 @@
//! AI 工具与模型(AI tools & models)— the MangoDisk-inspired category for
//! the local-AI crowd: Ollama weights, HuggingFace caches, and the desktop
//! AI apps' own caches and update payloads.
//!
//! The discipline that separates this from every other rule: **a model is
//! the user's downloaded property, not a cache.** 16 GB of llama.cpp weights
//! "regenerate" as a three-hour download on a bad day. So model rows are
//! never pre-selected, carry their last-seen timestamp, and live beside the
//! genuinely disposable caches (chat-app Electron caches, update payloads)
//! that follow normal cache rules.
//!
//! Last-used honesty: Ollama records no access times we can trust, so the
//! newest mtime among a model's manifest and blobs is shown as 最近使用时间
//! — the moment the model was pulled or re-patched. That is displayed, never
//! used to auto-delete.
use squid_core::{Bytes, Category, CleanupItem, ItemKind};
use std::path::{Path, PathBuf};
/// mtime of a file in ms since epoch, created() as backup.
fn mtime_ms(path: &Path) -> Option<u64> {
let meta = std::fs::metadata(path).ok()?;
meta.modified()
.or_else(|_| meta.created())
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as u64)
}
fn dir_size(path: &Path) -> (u64, Option<u64>) {
let mut total = 0u64;
let mut newest: Option<u64> = None;
for entry in walkdir::WalkDir::new(path)
.follow_links(false)
.max_depth(6)
.into_iter()
.filter_entry(|e| !e.file_type().is_symlink())
.flatten()
{
if !entry.file_type().is_file() {
continue;
}
let Ok(meta) = entry.metadata() else { continue };
total += meta.len();
if let Some(ms) = mtime_ms(entry.path()) {
newest = Some(newest.map_or(ms, |cur: u64| cur.max(ms)));
}
}
(total, newest)
}
fn age_days(ms: u64) -> Option<f64> {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.ok()?
.as_millis() as u64;
Some((now.saturating_sub(ms)) as f64 / 86_400_000.0)
}
fn age_note(ms: Option<u64>) -> Option<String> {
let days = ms.and_then(age_days)?;
if days < 1.0 {
Some("今天或昨天用过".into())
} else if days < 30.0 {
Some(format!("约 {} 天前用过", days as u64))
} else if days < 365.0 {
Some(format!(
"约 {} 个月没用过",
(days / 30.0).round().max(1.0) as u64
))
} else {
Some(format!(
"约 {} 年没用过",
(days / 365.0).round().max(1.0) as u64
))
}
}
/// A model row: name, size, last seen. `selected=false` is the contract —
/// the user decides, never the scanner.
fn model_item(
root: PathBuf,
label: String,
size_bytes: u64,
last_ms: Option<u64>,
rule: &str,
) -> CleanupItem {
let mut item = CleanupItem::new(root, ItemKind::Path, Category::AiTools, label)
.with_rule(rule)
.with_note(age_note(last_ms).unwrap_or_default());
item.size = Bytes(size_bytes);
item.allocated = Bytes(size_bytes);
item.selected = false;
if let Some(ms) = last_ms {
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
item.last_write_secs = Some(now_ms.saturating_sub(ms) / 1000);
}
item.evidence = vec![
"record:manifest".into(),
format!("age:{}", age_note(last_ms).unwrap_or_default()),
];
item
}
/// Ollama, sized honestly. A model is its manifest plus the blobs **no other
/// model also uses** — shared layers stay on disk until every model that
/// references them is gone, so a row's size never overstates what deleting
/// it frees. One model therefore becomes a small cluster of File items
/// (manifest + exclusive blobs) sharing a per-model rule id, which the 空间
/// 清理 page renders as one 清理点 named 「Ollama · 模型名」.
fn note_digest(value: &serde_json::Value, out: &mut Vec<(String, u64)>) {
if let Some(digest) = value.get("digest").and_then(|d| d.as_str()) {
let size = value.get("size").and_then(|s| s.as_u64()).unwrap_or(0);
out.push((digest.to_string(), size));
}
}
fn ollama_models(home: &Path) -> Vec<CleanupItem> {
let models_root = home.join(".ollama").join("models");
let manifests = models_root.join("manifests");
if !manifests.is_dir() {
return Vec::new();
}
// Pass 1: read every manifest, map digest → how many models use it.
type Manifest = (PathBuf, String, Vec<(String, u64)>);
let mut files: Vec<Manifest> = Vec::new();
let mut refs: std::collections::HashMap<String, usize> = Default::default();
let mut stack = vec![manifests];
while let Some(dir) = stack.pop() {
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
stack.push(path);
continue;
}
let Some(family) = path.parent().map(|p| {
p.file_name()
.map(|f| f.to_string_lossy().into_owned())
.unwrap_or_default()
}) else {
continue;
};
let Some(tag) = path.file_name().map(|t| t.to_string_lossy().into_owned()) else {
continue;
};
let name = if family == "library" || family.is_empty() {
tag.clone()
} else {
format!("{family}/{tag}")
};
let Ok(text) = std::fs::read_to_string(&path) else {
continue;
};
let Ok(json) = serde_json::from_str::<serde_json::Value>(&text) else {
continue;
};
let mut digests: Vec<(String, u64)> = Vec::new();
if let Some(config) = json.get("config") {
note_digest(config, &mut digests);
}
if let Some(layers) = json.get("layers").and_then(|l| l.as_array()) {
for layer in layers {
note_digest(layer, &mut digests);
}
}
for (digest, _) in &digests {
*refs.entry(digest.clone()).or_insert(0) += 1;
}
files.push((path, name, digests));
}
}
// Pass 2: one cluster of items per model, exclusive bytes only.
let mut rows = Vec::new();
for (manifest, name, digests) in files {
let slug: String = name
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
.collect();
let rule = format!("ai-ollama-{slug}");
let mut size = 0u64;
let mut newest = mtime_ms(&manifest);
let mut shared_skipped = 0usize;
let mut blob_items: Vec<(PathBuf, u64, u64)> = Vec::new();
for (digest, declared) in &digests {
if refs.get(digest).copied().unwrap_or(0) > 1 {
shared_skipped += 1;
continue; // another model still needs this layer
}
let blob = models_root.join("blobs").join(digest.replace(':', "-"));
let Ok(meta) = std::fs::metadata(&blob) else {
continue;
};
let bytes = meta.len().max(*declared);
let ms = mtime_ms(&blob).unwrap_or(0);
size += bytes;
newest = Some(newest.map_or(ms, |cur: u64| cur.max(ms)));
blob_items.push((blob, bytes, ms));
}
// A model whose layers are all shared frees nothing today, but the
// row still means 「从 ollama list 移除」 — keep it, sized honestly.
let age = age_note(newest);
let mut shared_note = String::new();
if shared_skipped > 0 {
shared_note = format!(";另有 {shared_skipped} 个共享层被其它模型使用,不计算在内");
}
let label = format!("Ollama · {name}");
// The manifest is the anchor row and carries the cluster label. Every
// row — manifest and blobs alike — carries **its own** size: the 清理点
// row sums its members, so charging the total to the manifest on top
// of the blobs would double-count the model.
let manifest_bytes = std::fs::metadata(&manifest).map(|m| m.len()).unwrap_or(0);
let mut item = model_item(manifest, label.clone(), manifest_bytes, newest, &rule);
item.kind = ItemKind::File; // the manifest file itself
item.note = Some(format!(
"{};整个模型可释放 {},删除后 `ollama pull` 可原样恢复{shared_note}",
age.clone().unwrap_or_else(|| "从未记录使用时间".into()),
Bytes(size + manifest_bytes)
));
rows.push(item);
for (blob, bytes, ms) in blob_items {
let mut part = CleanupItem::new(blob, ItemKind::File, Category::AiTools, label.clone())
.with_rule(&rule);
part.size = Bytes(bytes);
part.allocated = Bytes(bytes);
part.selected = false;
if let Some(ms) = Some(ms).filter(|m| *m > 0) {
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
part.last_write_secs = Some(now_ms.saturating_sub(ms) / 1000);
}
part.evidence = vec!["record:blob".into()];
rows.push(part);
}
}
rows
}
/// HuggingFace hub cache: one row per repo directory (models--org--name).
fn huggingface_cache(home: &Path) -> Vec<CleanupItem> {
let hub = home.join(".cache").join("huggingface").join("hub");
let Ok(entries) = std::fs::read_dir(&hub) else {
return Vec::new();
};
let mut rows = Vec::new();
for entry in entries.flatten() {
let path = entry.path();
if !path.is_dir() {
continue;
}
let name = entry.file_name().to_string_lossy().into_owned();
let pretty = name
.strip_prefix("models--")
.unwrap_or(&name)
.replace("--", "/");
let (size, newest) = dir_size(&path);
if size == 0 {
continue;
}
let mut item = model_item(
path,
format!("HuggingFace · {pretty}"),
size,
newest,
"ai-huggingface",
);
item.note = Some(format!(
"{};重新使用时会自动重新下载(可能占用流量)",
age_note(newest).unwrap_or_else(|| "从未记录使用时间".into())
));
rows.push(item);
}
rows
}
/// The genuinely disposable side: Electron caches, logs, update payloads the
/// desktop AI apps keep. These follow normal cache semantics (pre-selected).
fn tool_caches() -> Vec<CleanupItem> {
let mut rows = Vec::new();
let mut add = |label: &str, path: PathBuf, note: &str| {
if !path.is_dir() {
return;
}
let (size, _) = dir_size(&path);
if size == 0 {
return;
}
let mut item = CleanupItem::new(path, ItemKind::Contents, Category::AiTools, label)
.with_rule("ai-cache")
.with_note(note);
item.size = Bytes(size);
item.allocated = Bytes(size);
rows.push(item);
};
let Some(local) = std::env::var_os("LOCALAPPDATA").map(PathBuf::from) else {
return rows;
};
let Some(roaming) = std::env::var_os("APPDATA").map(PathBuf::from) else {
return rows;
};
add(
"Codex 桌面缓存",
local.join("Codex").join("Cache"),
"登录与界面缓存,重新打开自动重建",
);
add(
"Codex 更新包",
local.join("Codex").join("Packages"),
"升级完成后不再需要",
);
add(
"Claude 桌面缓存",
roaming.join("Claude").join("Cache"),
"重新打开自动重建",
);
add(
"Claude 日志",
roaming.join("Claude").join("logs"),
"旧日志可安全清空",
);
add(
"ChatGPT 桌面缓存",
roaming.join("ChatGPT").join("WebCache"),
"重新打开自动重建",
);
add(
"ChatGPT 更新包",
roaming.join("ChatGPT").join("Update"),
"升级完成后不再需要",
);
rows
}
/// One entry point, same shape as `updates::collect`.
pub fn collect(_engine: &crate::Engine, cancel: &squid_core::CancelToken) -> Vec<CleanupItem> {
let mut rows = Vec::new();
if cancel.is_cancelled() {
return rows;
}
let home = squid_core::paths::home_dir();
rows.extend(ollama_models(&home));
if cancel.is_cancelled() {
return rows;
}
rows.extend(huggingface_cache(&home));
rows.extend(tool_caches());
rows
}
#[cfg(test)]
mod tests {
use super::*;
fn fixture() -> Option<PathBuf> {
let root = std::env::temp_dir().join(format!(
"squid-ai-{}-{}",
std::process::id(),
squid_core::ledger::new_session_id()
));
std::fs::create_dir_all(&root).ok()?;
Some(root)
}
#[test]
fn ollama_models_are_listed_never_selected_with_sizes() {
let Some(root) = fixture() else { return };
let manifests = root.join(".ollama/models/manifests/registry.ollama.ai/library/qwen3");
let blobs = root.join(".ollama/models/blobs");
std::fs::create_dir_all(&manifests).unwrap();
std::fs::create_dir_all(&blobs).unwrap();
std::fs::write(
manifests.join("8b"),
r#"{"layers":[{"digest":"sha256:aaa","size":2048}]}"#,
)
.unwrap();
std::fs::write(blobs.join("sha256-aaa"), vec![1u8; 2048]).unwrap();
let rows = ollama_models(&root);
// Cluster: manifest File + exclusive blob File, one rule id each row.
assert_eq!(rows.len(), 2, "{rows:?}");
assert!(rows.iter().all(|r| r.rule_id == "ai-ollama-qwen3-8b"));
assert_eq!(rows[0].label, "Ollama · qwen3/8b");
// Each row carries its own size; the cluster total rides in the note.
let total = rows.iter().map(|r| r.size.as_u64()).sum::<u64>();
assert!(total >= 2048, "manifest + exclusive blob, no double count");
assert!(rows[0]
.note
.as_deref()
.is_some_and(|n| n.contains("可释放")));
assert!(rows.iter().all(|r| !r.selected), "models never pre-checked");
assert!(rows[0]
.note
.as_deref()
.is_some_and(|n| n.contains("可原样恢复")));
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn shared_blobs_are_not_billed_to_either_model() {
let Some(root) = fixture() else { return };
let library = root.join(".ollama/models/manifests/registry.ollama.ai/library");
std::fs::create_dir_all(library.join("a")).unwrap();
std::fs::create_dir_all(library.join("b")).unwrap();
std::fs::create_dir_all(root.join(".ollama/models/blobs")).unwrap();
std::fs::write(
library.join("a").join("latest"),
r#"{"layers":[{"digest":"sha256:shared","size":5000},{"digest":"sha256:own-a","size":100}]}"#,
)
.unwrap();
std::fs::write(
library.join("b").join("latest"),
r#"{"layers":[{"digest":"sha256:shared","size":5000}]}"#,
)
.unwrap();
std::fs::write(
root.join(".ollama/models/blobs/sha256-shared"),
vec![0u8; 5000],
)
.unwrap();
std::fs::write(
root.join(".ollama/models/blobs/sha256-own-a"),
vec![0u8; 100],
)
.unwrap();
let rows = ollama_models(&root);
let model_a: Vec<_> = rows
.iter()
.filter(|r| r.rule_id == "ai-ollama-a-latest")
.collect();
let model_b: Vec<_> = rows
.iter()
.filter(|r| r.rule_id == "ai-ollama-b-latest")
.collect();
// A: manifest (its own JSON bytes) + own blob sized 100; the shared
// 5 GB belongs to nobody yet, so it is billed to neither row.
assert_eq!(model_a.len(), 2, "{model_a:?}");
assert_eq!(model_a[1].size.as_u64(), 100);
assert!(
model_a[0].size.as_u64() < 200,
"manifest carries its own bytes"
);
assert!(model_a[0]
.note
.as_deref()
.is_some_and(|n| n.contains("共享层")));
// B: only the manifest survives (its own JSON bytes, not the shared
// 5 GB), and its note says the layers are held by other models.
assert_eq!(model_b.len(), 1, "{model_b:?}");
assert!(model_b[0].size.as_u64() < 200, "manifest bytes only");
assert!(model_b[0]
.note
.as_deref()
.is_some_and(|n| n.contains("共享层")));
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn library_prefix_is_stripped_from_official_models() {
let Some(root) = fixture() else { return };
let manifests = root.join(".ollama/models/manifests/registry.ollama.ai/library/llama3");
std::fs::create_dir_all(&manifests).unwrap();
std::fs::create_dir_all(root.join(".ollama/models/blobs")).unwrap();
std::fs::write(
manifests.join("latest"),
r#"{"layers":[{"digest":"sha256:bbb","size":10}]}"#,
)
.unwrap();
std::fs::write(root.join(".ollama/models/blobs/sha256-bbb"), vec![0u8; 10]).unwrap();
let rows = ollama_models(&root);
assert_eq!(rows[0].label, "Ollama · llama3/latest");
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn huggingface_repos_get_one_row_each() {
let Some(root) = fixture() else { return };
let hub = root.join(".cache/huggingface/hub/models--bert--base");
std::fs::create_dir_all(hub.join("snapshots/x")).unwrap();
std::fs::write(hub.join("snapshots/x/model.bin"), vec![7u8; 4096]).unwrap();
let rows = huggingface_cache(&root);
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].label, "HuggingFace · bert/base");
assert_eq!(rows[0].size.as_u64(), 4096);
assert!(!rows[0].selected);
let _ = std::fs::remove_dir_all(&root);
}
}

View File

@ -8,7 +8,7 @@
use serde::{Deserialize, Serialize};
use squid_core::fs;
use squid_core::progress::{CancelToken, Progress};
use squid_core::progress::{CancelToken, Event, Progress};
use squid_core::Bytes;
use std::path::{Path, PathBuf};
@ -16,6 +16,7 @@ use std::path::{Path, PathBuf};
const CHILD_CAP: usize = 512;
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Node {
pub path: PathBuf,
pub logical: Bytes,
@ -196,9 +197,9 @@ pub fn expand(
})
.collect();
progress.tick(0, Some(targets.len() as u64), None);
let sizes = fs::measure_all(&targets, cancel, |index, _info| {
let sizes = fs::measure_all(&targets, cancel, |index, completed, _info| {
progress.tick(
index as u64 + 1,
completed as u64,
Some(targets.len() as u64),
targets.get(index).map(|(path, _)| path.clone()),
);
@ -307,6 +308,146 @@ pub fn largest_files(
Ok(found)
}
/// Type buckets the large-file page filters on (extension → class).
/// Anything not listed lands in the catch-all "other".
pub fn file_class(path: &Path) -> &'static str {
let ext = path
.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.to_ascii_lowercase();
match ext.as_str() {
"mp4" | "mkv" | "avi" | "mov" | "wmv" | "flv" | "webm" | "ts" | "m2ts" => "video",
"zip" | "rar" | "7z" | "tar" | "gz" | "bz2" | "xz" | "zst" => "archive",
"exe" | "msi" | "msp" | "appx" | "msix" | "dmg" | "pkg" | "deb" | "rpm" | "appimage" => {
"installer"
}
"iso" | "img" | "vhd" | "vhdx" | "vmdk" | "qcow2" | "wim" | "esd" => "image",
_ => "other",
}
}
/// Large files across several roots with a byte threshold and optional
/// type-class filter. Streams `Metered` (folders walked / bytes found);
/// returns every hit at or above `min_bytes` — the UI counts them all,
/// "共 214 个" honesty beats a capped top-list.
pub fn large_files(
roots: &[PathBuf],
min_bytes: u64,
class: Option<&str>,
cancel: &CancelToken,
progress: &Progress,
) -> squid_core::Result<Vec<FileEntry>> {
let mut found: Vec<FileEntry> = Vec::new();
let mut stack: Vec<(PathBuf, usize)> = roots
.iter()
.filter(|root| root.is_dir())
.map(|root| (root.clone(), 0usize))
.collect();
let mut visited = 0usize;
let mut emitted = 0u64;
progress.phase("bigfiles", "scanning for large files");
while let Some((dir, depth)) = stack.pop() {
cancel.check()?;
visited += 1;
if visited % 256 == 0 {
progress.publish(Event::Metered {
files: visited as u64,
bytes: Bytes(emitted),
});
}
if depth > 24 {
continue;
}
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
let Ok(meta) = entry.metadata() else {
continue;
};
if meta.is_dir() {
if !is_mountpoint(&path) && !skip_infra(&entry.file_name().to_string_lossy()) {
stack.push((path, depth + 1));
}
continue;
}
if !meta.is_file() || meta.len() < min_bytes {
continue;
}
// The page files are system-managed and permanently locked:
// listing them only teaches users that deleting C:\pagefile.sys
// fails. hiberfil.sys stays — it has a real, actionable switch.
if is_pagefile(&path) {
continue;
}
if let Some(wanted) = class {
if file_class(&path) != wanted {
continue;
}
}
emitted += meta.len();
let modified_ms = meta
.modified()
.or_else(|_| meta.created())
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as u64);
found.push(FileEntry {
path,
logical: Bytes(meta.len()),
allocated: Bytes(allocated_of(&meta)),
modified_ms,
});
}
}
found.sort_by_key(|entry| std::cmp::Reverse(entry.size()));
progress.publish(Event::Metered {
files: visited as u64,
bytes: Bytes(emitted),
});
Ok(found)
}
/// The virtual-memory page files. They sit at a volume root, are held open by
/// the kernel and cannot be deleted from Explorer, so a large-file sweep must
/// not offer them. `hiberfil.sys` deliberately stays: turning hibernation off
/// is a real, actionable way to free that space.
fn is_pagefile(path: &Path) -> bool {
// Only the volume-root copies are the system's; a photo named
// pagefile.sys inside a folder stays listed. `C:\pagefile.sys` has
// parent `C:\`, whose own parent is none.
let at_root = path
.parent()
.and_then(|parent| parent.parent())
.map_or(true, |grand| grand.as_os_str().is_empty());
if !at_root {
return false;
}
path.file_name()
.map(|name| {
let name = name.to_string_lossy();
name.eq_ignore_ascii_case("pagefile.sys") || name.eq_ignore_ascii_case("swapfile.sys")
})
.unwrap_or(false)
}
/// System churn a large-file sweep should not crawl through.
fn skip_infra(name: &str) -> bool {
const SKIP: &[&str] = &[
"$recycle.bin",
"system volume information",
"windows",
"program files",
"program files (x86)",
"node_modules",
".git",
];
let lower = name.to_lowercase();
SKIP.iter().any(|wanted| lower == *wanted)
}
#[cfg(unix)]
fn allocated_of(meta: &std::fs::Metadata) -> u64 {
use std::os::unix::fs::MetadataExt;
@ -442,4 +583,19 @@ mod tests {
assert!(!node.complete);
let _ = std::fs::remove_dir_all(&root);
}
#[cfg(windows)]
#[test]
fn page_files_hide_only_at_the_volume_root() {
// Paths are matched lexically; nothing has to exist on disk.
assert!(is_pagefile(std::path::Path::new(r"C:\pagefile.sys")));
assert!(is_pagefile(std::path::Path::new(r"C:\swapfile.sys")));
assert!(is_pagefile(std::path::Path::new(r"D:\PAGEFILE.SYS")));
// hiberfil stays listed — it has an actionable switch (关闭休眠).
assert!(!is_pagefile(std::path::Path::new(r"C:\hiberfil.sys")));
// A file that merely carries the name inside a folder is still shown.
assert!(!is_pagefile(std::path::Path::new(
r"C:\Users\me\pagefile.sys"
)));
}
}

View File

@ -0,0 +1,190 @@
//! User-asset recognition — the Mole `app_protection` lesson for Windows.
//!
//! Some directories look exactly like caches but hold the user's own work:
//! chat files inside an IM data folder, PWA offline documents in a browser
//! profile's IndexedDB,输入法词库. A broad rule (or an eager user) must never
//! sweep them away, so they are pinned here: the scan lists them as locked,
//! visibly-explained rows, and the delete layer refuses them even when a
//! stale report still claims they are removable.
use squid_core::{Category, CleanupItem, ItemKind};
use std::path::Path;
/// Lower-cased path fragment → human reason. Matching is on the *normalised*
/// (lower-case, `/`→`\`) path so one table covers every drive letter and user.
const ASSET_MARKERS: &[(&str, &str)] = &[
(
"\\appdata\\roaming\\texact\\",
"腾讯 QQ 数据目录(聊天记录与文件)",
),
(
"\\appdata\\roaming\\tencent\\",
"腾讯通用数据目录(聊天文件与配置)",
),
(
"\\documents\\weixin files\\filestorage",
"微信聊天文件与下载文档",
),
(
"\\appdata\\roaming\\weixin\\filestorage",
"微信聊天文件与下载文档",
),
("\\appdata\\roaming\\txdnd\\", "腾讯游戏数据目录"),
("\\sogouexplorer\\", "搜狗输入法词库与用户习惯"),
(
"\\appdata\\roaming\\sogouinput\\",
"搜狗输入法词库与用户习惯",
),
];
/// Browser profile storage that holds PWA / offline web app documents —
/// Mole's `PROTECTED_SW_DOMAINS` equivalent. An `IndexedDB` folder inside a
/// Chromium-family browser profile is user work data (Figma / 剪映网页版 save
/// there), unlike `Cache` which is pure rebuildable bytes.
const CHROMIUM_PROFILE_MARKERS: &[&str] = &[
"\\microsoft\\edge\\user data\\",
"\\google\\chrome\\user data\\",
"\\chromium\\application\\user data\\",
];
fn normalise(path: &Path) -> String {
path.to_string_lossy().to_lowercase().replace('/', "\\")
}
/// Why this path is untouchable user property, if it is. The note lands in
/// the UI lock chip's explanation, mirroring 电脑管家's "创建者" honesty.
pub fn asset_reason(path: &Path) -> Option<&'static str> {
let lower = normalise(path);
// Deeper profile sub-paths (…\IndexedDB\foo) stay protected too: match
// the marker as a path prefix at a separator boundary.
if lower.contains("\\indexeddb")
&& CHROMIUM_PROFILE_MARKERS
.iter()
.any(|marker| lower.starts_with(marker) || lower.contains(marker))
{
return Some("可能含离线应用数据(Figma / 剪映网页版等工作文件)");
}
ASSET_MARKERS
.iter()
.find(|(marker, _)| segment_match(&lower, marker))
.map(|(_, reason)| *reason)
}
/// True when `marker` appears inside `lower` at path segment boundaries.
/// Markers ending with a separator carry their own trailing boundary, so
/// `TencentGame\cache` must not match `\tencent\`.
fn segment_match(lower: &str, marker: &str) -> bool {
if marker.ends_with('\\') {
return lower.contains(marker);
}
lower.match_indices(marker).any(|(index, _)| {
// A marker that opens with `\` carries its own left boundary; a bare
// marker needs a separator (or drive colon) before it.
let before_ok = index == 0
|| marker.starts_with('\\')
|| matches!(lower.as_bytes()[index - 1], b'\\' | b':');
let after = index + marker.len();
let after_ok = lower.len() == after || lower.as_bytes().get(after) == Some(&b'\\');
before_ok && after_ok
})
}
/// Asset rows to surface in the 空间清理 list — existence checked, one row
/// per top-level asset. Rows anchor at their own parent: they are display
/// only (locked), and anchoring at the folder itself would make
/// `block_reason` deny the row's own deletion check.
pub fn known_asset_rows() -> Vec<CleanupItem> {
const SPECS: [(&str, &str); 6] = [
(
r"AppData\Roaming\Tencent",
"腾讯(QQ/微信旧版)数据目录(聊天记录与文件)",
),
(
r"Documents\WeChat Files",
"微信聊天文件与下载文档(旧版目录)",
),
(
r"Documents\Weixin Files\FileStorage",
"微信聊天文件与下载文档",
),
(r"AppData\Roaming\SogouInput", "搜狗输入法词库与用户习惯"),
(
r"AppData\Local\Microsoft\Edge\User Data\Default\IndexedDB",
"可能含离线应用数据(Figma / 剪映网页版等工作文件)",
),
(
r"AppData\Local\Google\Chrome\User Data\Default\IndexedDB",
"可能含离线应用数据(Figma / 剪映网页版等工作文件)",
),
];
let Ok(home) = std::env::var("USERPROFILE") else {
return Vec::new();
};
let home = Path::new(&home);
let mut rows = Vec::new();
for (tail, reason) in SPECS {
let path = home.join(tail);
if !path.is_dir() {
continue;
}
let label = format!("🔒 {}", asset_label(&path));
let parent = path
.parent()
.map(|dir| dir.to_path_buf())
.unwrap_or_else(|| path.clone());
let item = CleanupItem::new(path, ItemKind::Path, Category::AppCaches, label)
.with_rule("user-assets")
.with_anchors(std::iter::once(parent))
.locked(squid_core::LockReason::Protected)
.with_note(reason);
rows.push(item);
}
rows
}
fn asset_label(path: &Path) -> String {
let text = squid_core::paths::pretty(path);
text.rsplit(['\\', '/'])
.next()
.filter(|leaf| !leaf.is_empty())
.unwrap_or(&text)
.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn im_data_dirs_refuse_deletion_with_a_reason() {
let path = PathBuf::from(r"C:\Users\me\AppData\Roaming\Tencent\WeChat\111\msg");
let reason = asset_reason(&path).expect("QQ tree must be protected");
assert!(reason.contains("聊天"));
}
#[test]
fn wechat_file_storage_is_protected_but_cache_paths_are_not() {
let storage = PathBuf::from(r"D:\Users\me\Documents\Weixin Files\FileStorage\File\2026-01");
assert!(asset_reason(&storage).is_some());
let edge_cache =
PathBuf::from(r"C:\Users\me\AppData\Local\Microsoft\Edge\User Data\Default\Cache");
assert!(asset_reason(&edge_cache).is_none());
}
#[test]
fn profile_indexeddb_counts_as_offline_app_data() {
let pwa = PathBuf::from(
r"C:\Users\me\AppData\Local\Microsoft\Edge\User Data\Default\IndexedDB\figma_0.indexeddb.leveldb",
);
let reason = asset_reason(&pwa).expect("PWA data must be protected");
assert!(reason.contains("离线应用"));
}
#[test]
fn markers_match_only_at_segment_boundaries() {
// A folder that merely *starts* with the marker text is not the asset.
let sneaky = PathBuf::from(r"C:\Users\me\AppData\Roaming\TencentGame\cache");
assert!(asset_reason(&sneaky).is_none());
}
}

View File

@ -172,6 +172,42 @@ pub fn scan(
}
}
// AI 工具与模型 (E1): local model weights (never pre-checked) plus the
// genuinely disposable Electron/update caches the desktop AI apps keep.
// Always on unless the caller filtered categories down to something else.
let ai_wanted =
options.categories.is_empty() || options.categories.contains(&Category::AiTools);
if ai_wanted {
progress.phase("ai", "collecting local AI models and caches");
for item in crate::ai::collect(engine, cancel) {
if seen.contains_key(&item.path) {
continue;
}
let mut item = item;
if engine.is_whitelisted(&item.path) {
item = item.locked(LockReason::Whitelisted);
} else if let Some(reason) = engine.block_reason(&item) {
item = item.locked(LockReason::Protected).with_note(reason);
}
seen.insert(item.path.clone(), report.items.len());
report.items.push(item);
}
}
// User-asset rows (B4): pinned directories shown as locked, explained
// rows so "why can't I clean my WeChat files?" never becomes a mystery.
let assets_wanted =
options.categories.is_empty() || options.categories.contains(&Category::AppCaches);
if assets_wanted {
for item in crate::assets::known_asset_rows() {
if seen.contains_key(&item.path) {
continue;
}
seen.insert(item.path.clone(), report.items.len());
report.items.push(item);
}
}
if !options.fast {
measure(engine, &mut report, progress, cancel)?;
}
@ -201,7 +237,7 @@ fn prepared_rules(engine: &Engine, options: &CleanOptions) -> Vec<PreparedRule>
rules.into_iter().map(PreparedRule::new).collect()
}
fn rule_running_conflict(rule: &Rule, running: &[String]) -> Option<String> {
pub fn rule_running_conflict(rule: &Rule, running: &[String]) -> Option<String> {
if rule.skip_if_running.is_empty() {
return None;
}
@ -334,15 +370,42 @@ fn measure(
.iter()
.map(|item| (item.path.clone(), item.kind))
.collect();
progress.tick(0, Some(targets.len() as u64), None);
let total = targets.len() as u64;
progress.tick(0, Some(total), None);
let results: Vec<squid_core::fs::SizeInfo> = measure_all(&targets, cancel, |index, _info| {
progress.tick(
index as u64 + 1,
Some(targets.len() as u64),
targets.get(index).map(|(path, _)| path.clone()),
);
});
// Cumulative counters for the live status line; the callback runs on
// rayon worker threads, hence the mutex. Emissions are throttled to
// ~10/s so the IPC stays a whisper while the walk screams.
let meter = std::sync::Mutex::new((0u64, 0u64, std::time::Instant::now()));
let results: Vec<squid_core::fs::SizeInfo> =
measure_all(&targets, cancel, |index, completed, info| {
let emit_line = {
let mut guard = meter
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
guard.0 += info.files;
guard.1 += info.on_disk().as_u64();
if completed as u64 == total
|| guard.2.elapsed() >= std::time::Duration::from_millis(90)
{
guard.2 = std::time::Instant::now();
Some((guard.0, guard.1))
} else {
None
}
};
if let Some((files, bytes)) = emit_line {
progress.publish(Event::Metered {
files,
bytes: Bytes(bytes),
});
}
progress.tick(
completed as u64,
Some(total),
targets.get(index).map(|(path, _)| path.clone()),
);
});
if results.len() != report.items.len() {
return Err(SquidError::Other(
"measurement returned an unexpected number of results".into(),
@ -351,6 +414,17 @@ fn measure(
for (item, info) in report.items.iter_mut().zip(results) {
item.size = info.logical;
item.allocated = info.allocated;
item.file_count = info.files;
// "Untouched for X" is the actionable half of a size figure; derived
// from the newest last-write seen during the walk we just did.
item.last_write_secs = if info.newest_write == 0 {
None
} else {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |since| since.as_secs());
Some(now.saturating_sub(info.newest_write))
};
if info.unreadable > 0 && item.note.is_none() {
item.note = Some(format!("{} entries unreadable", info.unreadable));
} else if info.files > 0 && item.note.is_none() {

View File

@ -0,0 +1,683 @@
//! Duplicate-file finder — the MangoDisk lesson, with our safety net.
//!
//! Finding byte-identical files cheaply is a **three-stage funnel**:
//!
//! 1. walk everything, bucket by exact size — a file with a unique size can
//! not have a duplicate, so terabytes drop out for the price of one `stat`;
//! 2. hash a 16 KiB sample from head, middle and tail of every same-size
//! candidate — different files diverge in those windows almost always, so
//! this kills the remaining false candidates with ~48 KiB of I/O each;
//! 3. full-stream SHA-256 only for what survived the sample — the expensive
//! stage runs on a small, pre-filtered set.
//!
//! Results land **group by group while the scan still runs** (a confirmed
//! group is pushed the moment its last file hashes), and every hash is
//! cached on disk keyed by *path + size + mtime*, so re-running the scan on
//! an unchanged disk costs the walk alone.
//!
//! Deletion is deliberately *not* this module's job: confirmed groups are
//! turned into ordinary [`CleanupItem`]s (one per copy, File kind) so the
//! engine's single delete path — safety re-validation, Recycle Bin, undo
//! ledger — guards duplicates exactly like every other byte squid touches.
//! MangoDisk deletes permanently; we do not.
use crate::assets;
use serde::Serialize;
use sha2::{Digest, Sha256};
use squid_core::progress::{CancelToken, Event, Progress};
use squid_core::{Bytes, Category, CleanupItem, ItemKind};
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
/// Files below this size are never offered: deduplicating a 4 KiB config is
/// noise, and the 1 MiB floor keeps the funnel's first stage cheap.
pub const DEFAULT_MIN_SIZE: u64 = 1024 * 1024;
/// Sample window at each of head / middle / tail.
const SAMPLE: usize = 16 * 1024;
/// One file that survived the walk and is waiting for its hashes.
#[derive(Clone, Debug)]
struct Candidate {
path: PathBuf,
size: u64,
mtime_ms: u64,
}
/// A confirmed group of byte-identical files.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DupGroup {
pub size: u64,
/// One entry per copy: (pretty path, mtime ms).
pub copies: Vec<DupCopy>,
/// Index of the copy the UI should mark 「保留」 by default (shortest
/// path — the "original" almost always lives at the tidier address).
pub keep: usize,
/// True when at least one copy sits in a protected user-asset folder
/// (WeChat FileStorage …): the group is flagged, never auto-selected.
pub personal: bool,
}
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DupCopy {
/// Display spelling (home folded to `~`) for the row.
pub path: String,
pub mtime_ms: u64,
/// Why this copy may not be deleted (asset lock), when it may not.
pub locked: Option<String>,
/// Exact path for the delete layer — serialised only for the app-side
/// cache, never rendered.
#[serde(skip)]
pub raw: PathBuf,
}
/// Funnel counters streamed as `Metered`-style notes plus the final report.
#[derive(Clone, Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DupStats {
pub walked: u64,
pub same_size: u64,
pub sample_hits: u64,
pub confirmed: u64,
pub wasted: u64,
}
/// Persisted hash cache: path → (size, mtime, sample hash, full hash).
/// A stale entry (size or mtime moved) is re-measured, so correctness never
/// depends on the cache — only speed does.
mod cache {
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
#[derive(Default, Serialize, Deserialize)]
pub struct HashCache {
/// key: normalised path (lower-case on Windows)
/// value: (size, mtime_ms, sample_hash_hex, full_hash_hex)
pub entries: HashMap<PathBuf, (u64, u64, String, String)>,
}
impl HashCache {
pub fn path() -> PathBuf {
squid_core::Settings::config_dir().join("hash-cache.json")
}
pub fn load() -> HashCache {
std::fs::read_to_string(Self::path())
.ok()
.and_then(|text| serde_json::from_str(&text).ok())
.unwrap_or_default()
}
pub fn save(&self) {
if let Ok(text) = serde_json::to_string(&self) {
let path = Self::path();
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
let _ = std::fs::write(path, text);
}
}
pub fn lookup(&self, key: &Path, size: u64, mtime_ms: u64) -> Option<(&str, &str)> {
let (s, m, sample, full) = self.entries.get(key)?;
(*s == size && *m == mtime_ms).then_some((sample.as_str(), full.as_str()))
}
pub fn put(&mut self, key: PathBuf, size: u64, mtime_ms: u64, sample: &str, full: &str) {
self.entries
.insert(key, (size, mtime_ms, sample.to_string(), full.to_string()));
}
}
pub fn key_for(path: &Path) -> PathBuf {
let text = path.to_string_lossy().to_lowercase();
PathBuf::from(text.replace('/', "\\"))
}
}
fn mtime_ms(meta: &std::fs::Metadata) -> u64 {
meta.modified()
.or_else(|_| meta.created())
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as u64)
.unwrap_or(0)
}
/// Read SAMPLE bytes at each of three offsets and hash the concatenation.
/// Tiny files (size < 3·SAMPLE) simply overlap — same answer, still cheap.
fn sample_digest(file: &mut File, size: u64) -> std::io::Result<String> {
let mut hasher = Sha256::new();
let window = SAMPLE.min(size as usize);
let third = ((size as i64) - window as i64).max(0) / 2;
for offset in [0i64, third, ((size as i64) - window as i64).max(0)] {
use std::io::Seek;
file.seek(std::io::SeekFrom::Start(offset as u64))?;
let mut buf = vec![0u8; window];
file.read_exact(&mut buf)?;
hasher.update(&buf);
}
Ok(hex(&hasher.finalize()))
}
fn full_digest(file: &mut File) -> std::io::Result<String> {
let mut hasher = Sha256::new();
let mut buf = vec![0u8; 256 * 1024];
loop {
let read = file.read(&mut buf)?;
if read == 0 {
break;
}
hasher.update(&buf[..read]);
}
Ok(hex(&hasher.finalize()))
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
/// Default scan scope: the user's own file areas — home folder (Documents,
/// Desktop, Downloads, Pictures, …) without descending into AppData churn,
/// plus every other fixed drive's user-shaped folders when present.
pub fn default_roots() -> Vec<PathBuf> {
let home = squid_core::paths::home_dir();
let mut roots = vec![home.clone()];
// Other drives: add their root-level Users / Documents-style containers.
let platform = squid_platform::current();
if let Ok(volumes) = platform.volumes() {
for volume in volumes {
if volume.is_removable || volume.is_root {
continue;
}
let users = volume.mount_point.join("Users");
if users.is_dir() {
roots.push(users);
} else if volume.mount_point.is_dir() {
roots.push(volume.mount_point);
}
}
}
roots
}
/// Skip infrastructure we have no business hashing: OS plumbing, recycle
/// bins, app data internals, and any VCS/package store folder by name.
fn skip_dir(name: &str) -> bool {
const SKIP: &[&str] = &[
"$recycle.bin",
"system volume information",
"windows",
"program files",
"program files (x86)",
"programdata",
"appdata",
"node_modules",
".git",
".hg",
".svn",
"target",
"__pycache__",
".venv",
"venv",
".terraform",
".gradle",
".m2",
".cargo",
"vendor",
];
let lower = name.to_lowercase();
SKIP.iter().any(|wanted| lower == *wanted)
}
/// Path-subtree exclusions that only matter as a *sequence*: WorkBuddy's
/// `\.workbuddy\workspace\sessions` folders snapshot copies of files the
/// agent was created from, so deduping them would re-offer churn the tool
/// regenerates itself — on whichever volume it happens to live. Matched as
/// consecutive normal path components, case- and drive-independent.
fn excluded_subtree(dir: &Path) -> bool {
const SEGMENTS: [&str; 3] = [".workbuddy", "workspace", "sessions"];
// Cheap guard: the walk prunes at the `sessions` door, so anything else
// can never match while descending.
if !dir
.file_name()
.is_some_and(|name| name.to_string_lossy().eq_ignore_ascii_case("sessions"))
{
return false;
}
let names: Vec<String> = dir
.components()
.filter_map(|part| match part {
std::path::Component::Normal(name) => Some(name.to_string_lossy().to_lowercase()),
_ => None,
})
.collect();
names.len() >= SEGMENTS.len() && names.windows(SEGMENTS.len()).any(|w| w == SEGMENTS)
}
/// Run the funnel. Groups stream out as `Event::Group { kind: "dup", … }`;
/// the return value is the same data collected, with per-copy locks
/// resolved, so the command layer can hand the frontend a finished list too.
pub fn scan(
roots: &[PathBuf],
min_size: u64,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<DupReport> {
let min_size = min_size.max(4096);
let mut hash_cache = cache::HashCache::load();
let walked = AtomicU64::new(0);
// ── Stage 1: walk, bucket by exact size ──────────────────────────────
progress.phase("duplicates", "第一级 · 按大小分组");
let mut by_size: HashMap<u64, Vec<Candidate>> = HashMap::new();
{
let mut stack: Vec<(PathBuf, usize)> = roots
.iter()
.filter(|root| root.is_dir())
.map(|root| (root.clone(), 0usize))
.collect();
while let Some((dir, depth)) = stack.pop() {
cancel.check()?;
if depth > 24 {
continue;
}
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
let Ok(file_type) = entry.file_type() else {
continue;
};
if file_type.is_dir() {
if skip_dir(&entry.file_name().to_string_lossy()) || excluded_subtree(&path) {
continue;
}
stack.push((path, depth + 1));
continue;
}
if !file_type.is_file() {
continue;
}
let count = walked.fetch_add(1, Ordering::Relaxed) + 1;
if count % 512 == 0 {
progress.publish(Event::Metered {
files: count,
bytes: Bytes(0),
});
}
let Ok(meta) = entry.metadata() else {
continue;
};
let size = meta.len();
if size < min_size {
continue;
}
by_size.entry(size).or_default().push(Candidate {
path,
size,
mtime_ms: mtime_ms(&meta),
});
}
}
}
let same_size: usize = by_size
.iter()
.filter(|(_, group)| group.len() > 1)
.map(|(_, group)| group.len())
.sum();
// Funnel counters ride structured notes the UI parses by prefix:
// `funnel:<walked>:<same-size>:<sample-hits>:<confirmed>`.
progress.publish(Event::Note(format!(
"funnel:{}:{same_size}:0:0",
walked.load(Ordering::Relaxed)
)));
// ── Stage 2: head/middle/tail sample hash ────────────────────────────
progress.phase("duplicates", "第二级 · 头中尾采样哈希");
let mut by_sample: HashMap<(u64, String), Vec<Candidate>> = HashMap::new();
let mut sample_seen = 0u64;
for (_, group) in by_size.drain() {
if group.len() < 2 {
continue;
}
for candidate in group {
cancel.check()?;
sample_seen += 1;
progress.publish(Event::Tick {
done: sample_seen,
total: Some(same_size as u64),
subject: Some(candidate.path.clone()),
});
let key = cache::key_for(&candidate.path);
let mut file = match File::open(&candidate.path) {
Ok(file) => file,
Err(_) => continue,
};
let digest = match hash_cache.lookup(&key, candidate.size, candidate.mtime_ms) {
Some((sample, _full)) => sample.to_string(),
None => match sample_digest(&mut file, candidate.size) {
Ok(digest) => digest,
Err(_) => continue,
},
};
by_sample
.entry((candidate.size, digest))
.or_default()
.push(candidate);
}
}
let sample_hits: usize = by_sample
.iter()
.filter(|(_, group)| group.len() > 1)
.map(|(_, group)| group.len())
.sum();
progress.publish(Event::Note(format!(
"funnel:{}:{same_size}:{sample_hits}:0",
walked.load(Ordering::Relaxed)
)));
// ── Stage 3: full hash on the survivors ──────────────────────────────
progress.phase("duplicates", "第三级 · 全量校验确认");
let mut report = DupReport::default();
let mut confirmed_seen = 0u64;
let groups: Vec<((u64, String), Vec<Candidate>)> = by_sample
.drain()
.filter(|(_, group)| group.len() > 1)
.collect();
let total_full: u64 = groups.iter().map(|(_, group)| group.len() as u64).sum();
for ((size, sample), group) in groups {
let mut by_full: HashMap<String, Vec<Candidate>> = HashMap::new();
for candidate in group {
cancel.check()?;
confirmed_seen += 1;
progress.publish(Event::Tick {
done: confirmed_seen,
total: Some(total_full),
subject: Some(candidate.path.clone()),
});
let key = cache::key_for(&candidate.path);
let digest = match hash_cache.lookup(&key, size, candidate.mtime_ms) {
Some((_sample, full)) => full.to_string(),
None => {
let Ok(mut file) = File::open(&candidate.path) else {
continue;
};
// The sample matched; if the cache was cold this file was
// just read for the sample, so re-opening it is the price
// of a stateless cache layout.
match full_digest(&mut file) {
Ok(digest) => {
hash_cache.put(key.clone(), size, candidate.mtime_ms, &sample, &digest);
digest
}
Err(_) => continue,
}
}
};
by_full.entry(digest).or_default().push(candidate);
}
for (_, copies) in by_full {
if copies.len() < 2 {
continue;
}
let group = build_group(size, &copies);
report.wasted += (copies.len() as u64 - 1) * size;
report.confirmed_groups += 1;
report.confirmed_files += copies.len() as u64;
progress.publish(Event::Group {
kind: "dup",
payload: serde_json::to_value(&group).unwrap_or_default(),
});
report.groups.push(group);
}
}
// Persist the cold-half of the work so the next scan is a walk only.
// Keep the file bounded: half of it is dropped when it outgrows 600k
// entries (a few tens of MB of JSON is already generous).
if hash_cache.entries.len() > 600_000 {
let keep = hash_cache.entries.len() / 2;
let keys: Vec<PathBuf> = hash_cache.entries.keys().skip(keep).cloned().collect();
for key in keys {
hash_cache.entries.remove(&key);
}
}
hash_cache.save();
report.walked = walked.load(Ordering::Relaxed);
report.same_size = same_size as u64;
report.sample_hits = sample_hits as u64;
report
.groups
.sort_by_key(|group| std::cmp::Reverse(group.size * (group.copies.len() as u64 - 1)));
progress.publish(Event::Note(format!(
"funnel:{}:{same_size}:{sample_hits}:{}",
report.walked, report.confirmed_files
)));
Ok(report)
}
/// Shape one confirmed group for the UI: keep-shortest-path, asset locks.
fn build_group(size: u64, copies: &[Candidate]) -> DupGroup {
let mut ordered: Vec<&Candidate> = copies.iter().collect();
// Shortest path wins the 「保留」 chip; ties fall back to oldest mtime
// (the copy that has been there longest is the least likely accident).
ordered.sort_by(|a, b| {
a.path
.components()
.count()
.cmp(&b.path.components().count())
.then(a.mtime_ms.cmp(&b.mtime_ms))
.then(a.path.cmp(&b.path))
});
let mut personal = false;
let copies = ordered
.iter()
.map(|candidate| {
let locked = assets::asset_reason(&candidate.path).map(str::to_string);
if locked.is_some() {
personal = true;
}
DupCopy {
path: squid_core::paths::pretty(&candidate.path),
mtime_ms: candidate.mtime_ms,
locked,
raw: candidate.path.clone(),
}
})
.collect();
DupGroup {
size,
copies,
keep: 0,
personal,
}
}
impl DupReport {
/// Flatten the user's deletion picks into engine items: one File item per
/// chosen copy. `selections` is (group index, copy indexes to delete) —
/// the keep decision belongs to the UI, this layer only executes what was
/// confirmed identical and explicitly picked.
pub fn items_for(&self, selections: &[(usize, Vec<usize>)]) -> Vec<CleanupItem> {
let now_ms = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
let mut items = Vec::new();
for (group_index, copies) in selections {
let Some(group) = self.groups.get(*group_index) else {
continue;
};
for copy_index in copies {
let Some(copy) = group.copies.get(*copy_index) else {
continue;
};
if group.copies.len() <= 1 || copy.locked.is_some() {
continue;
}
let path = copy.raw.clone();
// Anchor two levels up: the safety policy demands the target
// sit *strictly below* an anchor (depth ≥ 1), and the file's
// own parent would place it at depth 0.
let anchor = path
.ancestors()
.nth(2)
.map(|dir| dir.to_path_buf())
.unwrap_or_else(|| PathBuf::from("/"));
let mut item = CleanupItem::new(
path.clone(),
ItemKind::File,
Category::Duplicates,
path.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default(),
)
.with_rule("duplicates")
.with_anchors(std::iter::once(anchor))
.with_note(format!("{} 份相同 · 已全量校验一致", group.copies.len()));
item.size = Bytes(group.size);
item.allocated = Bytes(group.size);
item.file_count = 1;
item.last_write_secs = Some(now_ms.saturating_sub(copy.mtime_ms) / 1000);
item.evidence = vec![format!("record:sha256:{}", group.size)];
items.push(item);
}
}
items
}
}
/// Everything a finished scan says: the groups plus the funnel counters the
/// UI prints under its title.
#[derive(Clone, Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DupReport {
pub groups: Vec<DupGroup>,
pub walked: u64,
pub same_size: u64,
pub sample_hits: u64,
pub confirmed_groups: u64,
pub confirmed_files: u64,
pub wasted: u64,
}
#[cfg(test)]
mod tests {
use super::*;
use squid_core::progress::Progress;
fn scratch(tag: &str) -> Option<PathBuf> {
// Keep test hashes out of the real config-dir cache file.
static STATE: std::sync::Once = std::sync::Once::new();
STATE.call_once(|| {
let dir = std::env::temp_dir().join(format!("squid-dups-state-{}", std::process::id()));
if std::fs::create_dir_all(&dir).is_ok() {
std::env::set_var("SQUID_STATE_DIR", &dir);
}
});
let dir = std::env::temp_dir().join(format!(
"squid-dups-{}-{tag}-{}",
std::process::id(),
squid_core::ledger::new_session_id()
));
match std::fs::create_dir_all(&dir) {
Ok(()) => Some(dir),
Err(error) => {
eprintln!("skipping: scratch denied ({error})");
None
}
}
}
#[cfg(windows)]
#[test]
fn workbuddy_session_snapshots_are_never_walked() {
assert!(excluded_subtree(Path::new(
r"C:\.workbuddy\workspace\sessions"
)));
assert!(excluded_subtree(Path::new(
r"D:\Work\.WorkBuddy\Workspace\Sessions"
)));
assert!(!excluded_subtree(Path::new(
r"C:\Users\dev\workspace\sessions"
)));
assert!(!excluded_subtree(Path::new(
r"C:\.workbuddy\workspace\sessions-notes"
)));
}
#[test]
fn identical_files_land_in_one_group_with_the_neat_copy_kept() {
let Some(root) = scratch("same") else { return };
let payload = vec![7u8; 2 * 1024 * 1024];
let deep = root.join("a").join("b").join("c");
std::fs::create_dir_all(&deep).unwrap();
std::fs::write(root.join("copy.bin"), &payload).unwrap();
std::fs::write(deep.join("copy.bin"), &payload).unwrap();
std::fs::write(root.join("other.bin"), vec![9u8; payload.len()]).unwrap();
let progress = Progress::new();
let report = scan(
std::slice::from_ref(&root),
1024 * 1024,
&progress,
&CancelToken::new(),
)
.expect("scan");
assert_eq!(report.groups.len(), 1, "{:?}", report.groups);
let group = &report.groups[0];
assert_eq!(group.copies.len(), 2);
// keep = shortest path: the root-level copy wins the chip.
assert!(!group.copies[group.keep].path.contains("b\\c"));
assert_eq!(report.confirmed_files, 2);
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn same_size_different_bytes_never_matches() {
// The whole point of stage 2/3: two same-size files differing only in
// the middle byte past the head sample window.
let Some(root) = scratch("diff") else { return };
let a = vec![3u8; 200_000];
let mut b = vec![3u8; 200_000];
b[100_001] = 4;
std::fs::write(root.join("a.bin"), &a).unwrap();
std::fs::write(root.join("b.bin"), &b).unwrap();
drop(a);
drop(b);
let progress = Progress::new();
let report = scan(
std::slice::from_ref(&root),
1024,
&progress,
&CancelToken::new(),
)
.expect("scan");
assert!(report.groups.is_empty(), "{:?}", report.groups);
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn tiny_files_are_not_offered_at_all() {
let Some(root) = scratch("tiny") else { return };
std::fs::write(root.join("one.txt"), b"same").unwrap();
std::fs::write(root.join("two.txt"), b"same").unwrap();
let progress = Progress::new();
let report = scan(
std::slice::from_ref(&root),
DEFAULT_MIN_SIZE,
&progress,
&CancelToken::new(),
)
.expect("scan");
assert_eq!(report.walked, 2);
assert_eq!(report.same_size, 0);
let _ = std::fs::remove_dir_all(&root);
}
}

View File

@ -0,0 +1,197 @@
//! Hidden-space insights (Mole's `cmd/analyze` overview idiom).
//!
//! The disk analyzer answers "what is big"; this answers "what is big *and*
//! actionable" — curated Windows space hogs with a one-line explanation and
//! the action that actually frees them. Existence-gated: a row appears only
//! when the underlying path (or state) is really on this machine.
use serde::Serialize;
use squid_core::fs;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Insight {
/// Stable id for the UI (icon/translation lookup).
pub id: String,
pub title: String,
pub path: String,
pub size: u64,
/// "cleanable" — 空间清理 covers it; "command" — needs the given command;
/// "external" — system tool territory; "info" — informational.
pub action: String,
/// Command to run (elevated) when action == "command".
pub command: Option<String>,
pub hint: String,
}
fn home() -> Option<PathBuf> {
std::env::var("USERPROFILE")
.ok()
.map(PathBuf::from)
.filter(|path| path.is_dir())
}
fn dir_size(path: &Path) -> u64 {
if !path.is_dir() {
return 0;
}
fs::measure(path, squid_core::ItemKind::Path)
.on_disk()
.as_u64()
}
fn file_size(path: &Path) -> u64 {
std::fs::metadata(path).map_or(0, |meta| meta.len())
}
/// All insights that currently exist on this machine, biggest-effect first
/// ordering is left to the UI.
pub fn collect() -> Vec<Insight> {
let mut out = Vec::new();
let Some(home) = home() else {
return out;
};
let system = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into());
let system = PathBuf::from(system);
// 1. Windows Update download cache — the classic 5-20 GB surprise.
let updates = system.join(r"SoftwareDistribution\Download");
let size = dir_size(&updates);
if size > 256 * 1024 * 1024 {
out.push(Insight {
id: "update-cache".into(),
title: "Windows 更新缓存".into(),
path: updates.display().to_string(),
size,
action: "cleanable".into(),
command: None,
hint: "已安装的更新包,Windows 需要时会重新下载;空间清理的「系统垃圾」覆盖此目录"
.into(),
});
}
// 2. Hibernation file — freed by turning hibernation off.
let hiber = system.join("..\\hiberfil.sys");
let size = file_size(&hiber);
if size > 0 {
out.push(Insight {
id: "hiberfil".into(),
title: "休眠文件 hiberfil.sys".into(),
path: hiber.display().to_string(),
size,
action: "command".into(),
command: Some("powercfg /h off".into()),
hint: "关闭休眠后系统自动删除;睡眠不受影响".into(),
});
}
// 3. Pagefile — visible but rarely worth touching; info only.
let page = system.join("..\\pagefile.sys");
let size = file_size(&page);
if size > 0 {
out.push(Insight {
id: "pagefile".into(),
title: "虚拟内存 pagefile.sys".into(),
path: page.display().to_string(),
size,
action: "info".into(),
command: None,
hint: "系统正在使用的虚拟内存,不建议手动删除;可在系统设置改到别的盘".into(),
});
}
// 4. Component store (WinSxS) — needs DISM, never raw deletion.
// Walking 100k+ files just to print a number is not worth it here;
// the UI shows "several GB" and the DISM command does the rest.
let winsxs = system.join("WinSxS");
if winsxs.is_dir() {
out.push(Insight {
id: "winsxs".into(),
title: "组件存储 WinSxS".into(),
path: winsxs.display().to_string(),
size: 0,
action: "command".into(),
command: Some("Dism.exe /online /Cleanup-Image /StartComponentCleanup".into()),
hint: "系统组件仓库,通常 5~10 GB;只能由 DISM 收缩,直接删会破坏系统".into(),
});
}
// 5. Phone backups (Apple MobileSync / third-party Android tools).
for (tail, title) in [
(r"Apple\MobileSync\Backup", "iPhone 备份"),
(r"Apple Computer\MobileSync\Backup", "iPhone 备份"),
] {
let backups = home.join(tail);
let size = dir_size(&backups);
if size > 256 * 1024 * 1024 {
out.push(Insight {
id: "phone-backup".into(),
title: title.into(),
path: backups.display().to_string(),
size,
action: "external".into(),
command: None,
hint: "整机备份体积大;确认 iCloud 或新备份完成后,在 iTunes/Finder 里删除旧备份"
.into(),
});
break;
}
}
// 6. Downloads older than 90 days (Mole's "Old Downloads" insight).
let downloads = home.join("Downloads");
if downloads.is_dir() {
let cutoff = std::time::SystemTime::now() - std::time::Duration::from_secs(90 * 24 * 3600);
let mut size = 0u64;
let mut stale = 0usize;
if let Ok(entries) = std::fs::read_dir(&downloads) {
for entry in entries.flatten() {
let meta = match entry.metadata() {
Ok(meta) => meta,
Err(_) => continue,
};
let modified = meta.modified().unwrap_or(std::time::UNIX_EPOCH);
if modified < cutoff {
size += if meta.is_dir() {
dir_size(&entry.path())
} else {
meta.len()
};
stale += 1;
}
}
}
if size > 256 * 1024 * 1024 {
out.push(Insight {
id: "old-downloads".into(),
title: "下载文件夹(90 天以上)".into(),
path: downloads.display().to_string(),
size,
action: "external".into(),
command: None,
hint: format!("{stale} 个条目三个月没动过;确认不再需要后手动清理"),
});
}
}
out.sort_by_key(|row| std::cmp::Reverse(row.size));
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn collect_never_panics_on_a_live_machine() {
// Pure smoke: whatever exists, ids are unique and sizes sane.
let rows = collect();
for (index, row) in rows.iter().enumerate() {
assert!(!row.id.is_empty());
assert!(!rows[..index]
.iter()
.any(|earlier| earlier.id == row.id && row.id != "phone-backup"));
}
}
}

View File

@ -11,16 +11,23 @@
//! Engines never call `std::fs::remove_*` directly; that keeps the audit trail
//! and the safety net impossible to bypass.
pub mod ai;
pub mod analyze;
pub mod assets;
pub mod clean;
pub mod delete;
pub mod duplicates;
pub mod insights;
pub mod maintenance;
pub mod privacy;
pub mod purge;
pub mod tweaks;
pub mod uninstall;
pub mod updates;
use globset::GlobMatcher;
use squid_core::settings::Settings;
use squid_core::{CleanupItem, SafetyPolicy};
use squid_core::{CleanupItem, SafetyPolicy, ScanReport};
use squid_platform::Platform;
use squid_rules::RuleSet;
use std::path::Path;
@ -80,6 +87,15 @@ impl Engine {
self.platform.as_ref()
}
/// An engine whose safety policy lets an unprivileged run reach files
/// on any existing volume. Built for the duplicate-file delete path:
/// byte-confirmed copies of the user's own files, deleted to the
/// recycle bin, everywhere the scan looked. All other guardrails stay.
pub fn with_volume_wide_safety(mut self) -> Engine {
self.safety = self.safety.clone().with_all_volumes();
self
}
pub fn settings(&self) -> &Settings {
&self.settings
}
@ -121,6 +137,13 @@ impl Engine {
/// Why this item cannot be deleted, if it cannot. Rules pass the anchor they
/// declared; everything else falls back to the default anchors.
pub fn block_reason(&self, item: &CleanupItem) -> Option<String> {
// Mole's lesson: some directories *look* like caches but hold the
// user's own work — chat files, PWA offline data, IME dictionaries.
// They are refused even when a broad rule matched them, with the
// reason shown verbatim in the UI lock chip.
if let Some(reason) = crate::assets::asset_reason(&item.path) {
return Some(reason.to_string());
}
let anchors = if item.anchors.is_empty() {
squid_core::fs::default_anchors()
} else {
@ -131,6 +154,107 @@ impl Engine {
}
self.safety.denies(&item.path, &anchors)
}
/// Mole's "re-verify at the last second" made visible: re-run every
/// deletion gate against the *current* item set and report what changed
/// since the scan. The confirm dialog shows the summary, so surprises
/// ("your app just started, we dropped 3 items") appear before the run,
/// not inside the results.
pub fn preflight(&self, report: &ScanReport, indexes: &[usize]) -> Preflight {
let running = self.platform().running_executables();
let mut out = Preflight {
checked: indexes.len(),
blocked: Vec::new(),
};
for &index in indexes {
let Some(item) = report.items.get(index) else {
continue;
};
if item.lock.is_some() {
continue;
}
if let Some(reason) = self.block_reason(item) {
out.blocked.push((item.display_path(), reason));
continue;
}
if let Some(path) = gone_path(item) {
out.blocked.push((
item.display_path(),
format!("{} 已不存在", squid_core::paths::pretty(&path)),
));
}
}
// Apps started since the scan: re-check running conflicts per rule.
for (index, item) in report.items.iter().enumerate() {
if item.lock.is_some() || !indexes.contains(&index) {
continue;
}
if let Some(rule) = self
.rules()
.rules()
.iter()
.find(|rule| rule.id == item.rule_id)
{
if let Some(conflict) = crate::clean::rule_running_conflict(rule, &running) {
if !out
.blocked
.iter()
.any(|(path, _)| *path == item.display_path())
{
out.blocked.push((item.display_path(), conflict));
}
}
}
}
out
}
/// Which whitelist patterns actually *do something* (Mole's #458: a
/// protection line nobody ever hits is a fake protection). A pattern is
/// "live" when it matches a path the current rule set finds on this
/// machine — the user learns their glob protects a real thing, or that
/// it protects nothing at all.
pub fn audit_whitelist(&self) -> Vec<(String, bool)> {
let known: Vec<std::path::PathBuf> = self
.rules()
.rules()
.iter()
.filter(|rule| rule.applies_to_current_os())
.flat_map(|rule| {
squid_rules::PreparedRule::new((*rule).clone())
.matches()
.into_iter()
.map(|matched| matched.path)
})
.collect();
// Same expansion the delete layer uses (settings.whitelist_matchers
// shape), rebuilt per pattern so an invalid line cannot shift the
// index pairing — the audit answers "does THIS pattern protect
// anything".
self.settings
.whitelist
.iter()
.map(|pattern| {
let live = Settings::whitelist_matcher_for(pattern).is_some_and(|matcher| {
known.iter().any(|path| matcher.is_match(path.as_path()))
});
(pattern.clone(), live)
})
.collect()
}
}
/// Result of [`Engine::preflight`].
#[derive(Clone, Debug, Default)]
pub struct Preflight {
pub checked: usize,
/// (display path, reason) for items that can no longer be deleted.
pub blocked: Vec<(String, String)>,
}
fn gone_path(item: &squid_core::CleanupItem) -> Option<std::path::PathBuf> {
(!item.path.exists() && !std::fs::symlink_metadata(&item.path).is_ok())
.then(|| item.path.clone())
}
/// True when the process may touch system-owned paths.

View File

@ -0,0 +1,443 @@
//! 系统维护 (system maintenance) — one-click repairs for the everyday
//! Windows complaints: search won't open, icons are wrong, the network is
//! flaky, an update keeps failing, sound died.
//!
//! The whole feature is a **controlled whitelist**: the UI can only ever
//! name one of these ids, and every command is `program + fixed argv` —
//! never a shell string, never user input. That is the difference between
//! "rebuild the icon cache" and `cmd /c <whatever the frontend sent>`. Each
//! task carries its real cost (budget seconds) and an elevation need so the
//! UI can be honest before the user clicks.
//!
//! Output is streamed as it arrives (live progress beats a frozen spinner),
//! and the per-task budget kills a runaway command instead of hanging the
//! app — SFC /scannow genuinely takes fifteen minutes.
use serde::Serialize;
use squid_core::progress::{CancelToken, Event, Progress};
/// One repair the whitelist knows about. Commands run top to bottom; any
/// step that needs administrator rights is flagged so the runner can route
/// it through the elevation broker instead of failing on a locked key.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MaintenanceTask {
pub id: &'static str,
pub title_en: &'static str,
pub title_zh: &'static str,
pub detail_en: &'static str,
pub detail_zh: &'static str,
/// "safe" | "admin" | "slow" — drives the UI risk chip.
pub risk: &'static str,
/// Wall-clock budget in seconds; the runner kills past this.
pub budget_secs: u64,
/// Human estimate shown before the run ("约 2–5 分钟").
pub estimate: &'static str,
}
/// argv for one command in a task: (program, args, needs-elevation).
/// One pseudo-program exists: `delete-file` removes the named file through
/// std::fs directly — no shell glob, no quoting question.
type Command = (&'static str, &'static [&'static str], bool);
fn commands(id: &str) -> Option<Vec<Command>> {
Some(match id {
"search-index" => vec![
("net.exe", &["stop", "WSearch"], true),
(
"delete-file",
&[r"%PROGRAMDATA%\Microsoft\Search\Data\Applications\Windows\Windows.edb"],
false,
),
("net.exe", &["start", "WSearch"], true),
],
"icon-cache" => vec![
("ie4uinit.exe", &["-ClearIconCache"], false),
("taskkill.exe", &["/F", "/IM", "explorer.exe"], false),
("cmd.exe", &["/C", "start", "", "explorer.exe"], false),
],
"network-reset" => vec![
("netsh.exe", &["winsock", "reset"], true),
("ipconfig.exe", &["/flushdns"], true),
("ipconfig.exe", &["/registerdns"], true),
],
"sfc-dism" => vec![
(
"DISM.exe",
&["/Online", "/Cleanup-Image", "/RestoreHealth"],
true,
),
("sfc.exe", &["/scannow"], true),
],
"windows-update" => vec![
("net.exe", &["stop", "wuauserv"], true),
("net.exe", &["stop", "bits"], true),
(
"cmd.exe",
&[
"/C",
"del",
"/Q",
"/F",
r"%SystemRoot%\SoftwareDistribution\Download\*.*",
],
true,
),
("net.exe", &["start", "bits"], true),
("net.exe", &["start", "wuauserv"], true),
],
"audio-restart" => vec![
("net.exe", &["stop", "Audiosrv"], true),
("net.exe", &["stop", "AudioEndpointBuilder"], true),
("net.exe", &["start", "AudioEndpointBuilder"], true),
("net.exe", &["start", "Audiosrv"], true),
],
_ => return None,
})
}
/// The catalog the UI lists. Order matters: cheap and safe first, the long
/// SFC/DISM repair last so nobody starts with the fifteen-minute job.
pub fn tasks() -> Vec<MaintenanceTask> {
vec![
MaintenanceTask {
id: "search-index",
title_en: "Rebuild the search index",
title_zh: "重建搜索索引",
detail_en: "Start menu / Explorer search returns nothing or is stale",
detail_zh: "开始菜单 / 资源管理器搜索没结果、结果不更新",
risk: "admin",
budget_secs: 120,
estimate: "约 1–2 分钟",
},
MaintenanceTask {
id: "icon-cache",
title_en: "Rebuild the icon cache",
title_zh: "重建图标缓存",
detail_en: "Shortcuts show blank or wrong icons",
detail_zh: "快捷方式图标变白块、显示错乱(会重启 Explorer)",
risk: "safe",
budget_secs: 30,
estimate: "约 10 秒 · 需重启 Explorer",
},
MaintenanceTask {
id: "network-reset",
title_en: "Reset the network stack + flush DNS",
title_zh: "重置网络栈 + 刷新 DNS",
detail_en: "Connected but pages fail; DNS resolves wrong",
detail_zh: "能连上但打不开网页、DNS 解析异常(会短暂断网重连)",
risk: "admin",
budget_secs: 30,
estimate: "约 5 秒",
},
MaintenanceTask {
id: "audio-restart",
title_en: "Restart the audio services",
title_zh: "重启音频服务",
detail_en: "No sound, or headphone switching stopped working",
detail_zh: "突然没声音、耳机切换失效",
risk: "admin",
budget_secs: 30,
estimate: "约 3 秒",
},
MaintenanceTask {
id: "windows-update",
title_en: "Reset Windows Update components",
title_zh: "Windows 更新组件重置",
detail_en: "Updates keep failing or stuck downloading",
detail_zh: "更新反复失败 / 卡在下载(会停 wuauserv 再清 SoftwareDistribution)",
risk: "admin",
budget_secs: 90,
estimate: "约 30 秒",
},
MaintenanceTask {
id: "sfc-dism",
title_en: "System file repair (SFC + DISM)",
title_zh: "系统文件修复(SFC + DISM)",
detail_en: "Suspected system file corruption, random crashes",
detail_zh: "疑似系统文件损坏、频繁蓝屏后自检",
risk: "slow",
budget_secs: 1_800,
estimate: "约 15 分钟",
},
]
}
pub fn find(id: &str) -> Option<MaintenanceTask> {
tasks().into_iter().find(|task| task.id == id)
}
/// Result of a maintenance run: every command's exit, plus the tail of
/// combined output so the UI can show what actually happened.
#[derive(Clone, Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MaintenanceResult {
pub task: String,
pub ok: bool,
pub steps: Vec<String>,
pub failed_step: Option<String>,
pub output_tail: String,
pub duration_ms: u64,
}
#[cfg(windows)]
mod run {
use super::*;
use std::io::Read;
use std::os::windows::process::CommandExt;
use std::process::{Child, Stdio};
fn quote_ps(value: &str) -> String {
format!("'{}'", value.replace('\'', "''"))
}
/// Expand the few `%VAR%` tokens our catalog uses; we never hand a raw
/// string to a shell, so only these need resolving.
fn expand_env(arg: &str) -> String {
let mut out = arg.to_string();
for (key, value) in [
("%PROGRAMDATA%", std::env::var("PROGRAMDATA").ok()),
("%SystemRoot%", std::env::var("SystemRoot").ok()),
] {
if let Some(value) = value {
out = out.replace(key, &value);
}
}
out
}
fn spawn(program: &str, args: &[String]) -> std::io::Result<Child> {
std::process::Command::new(program)
.args(args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.creation_flags(0x0800_0000) // CREATE_NO_WINDOW
.spawn()
}
/// Run one command elevated through the PowerShell broker; a cancelled
/// UAC prompt is an honest failure, not a crash.
fn run_elevated(program: &str, args: &[String]) -> Result<(), String> {
let arglist = args
.iter()
.map(|arg| quote_ps(arg))
.collect::<Vec<_>>()
.join(",");
let script = format!(
"$ErrorActionPreference='SilentlyContinue'; Start-Process -FilePath {} -ArgumentList {} -Verb RunAs -WindowStyle Hidden -Wait",
quote_ps(program),
arglist
);
let status = std::process::Command::new("powershell.exe")
.args(["-NoProfile", "-NonInteractive", "-Command", &script])
.creation_flags(0x0800_0000)
.status()
.map_err(|error| format!("无法启动提权助手:{error}"))?;
if status.success() {
Ok(())
} else {
Err("管理员授权被取消或命令失败".into())
}
}
/// Wait for a direct child with a wall-clock budget, streaming its
/// combined output into `progress`. Returns (ok, output tail).
fn wait_streamed(
mut child: Child,
budget: std::time::Duration,
progress: &Progress,
cancel: &CancelToken,
) -> (bool, String) {
let stdout = child.stdout.take();
let stderr = child.stderr.take();
let (tx, rx) = crossbeam_channel::unbounded::<String>();
let mut readers = Vec::new();
let mut streams: Vec<Box<dyn Read + Send>> = Vec::new();
if let Some(stream) = stdout {
streams.push(Box::new(stream));
}
if let Some(stream) = stderr {
streams.push(Box::new(stream));
}
for stream in streams {
let tx = tx.clone();
readers.push(std::thread::spawn(move || {
let mut reader = std::io::BufReader::new(stream);
let mut buf = [0u8; 4096];
loop {
match reader.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
for line in String::from_utf8_lossy(&buf[..n]).lines() {
let trimmed = line.trim();
if !trimmed.is_empty() {
let _ = tx.send(trimmed.to_string());
}
}
}
}
}
}));
}
drop(tx);
let started = std::time::Instant::now();
let mut tail: Vec<String> = Vec::new();
loop {
while let Ok(line) = rx.try_recv() {
tail.push(line.clone());
if tail.len() > 200 {
tail.remove(0);
}
progress.note(line);
}
match child.try_wait() {
Ok(Some(status)) => {
// Drain whatever the readers queued before EOF.
while let Ok(line) = rx.try_recv() {
tail.push(line);
}
for reader in readers {
let _ = reader.join();
}
return (status.success(), tail.join("\n"));
}
Ok(None) => {
if started.elapsed() > budget || cancel.is_cancelled() {
let _ = child.kill();
let _ = child.wait();
return (false, format!("超时或已取消(预算 {}s)", budget.as_secs()));
}
std::thread::sleep(std::time::Duration::from_millis(120));
}
Err(_) => return (false, "无法读取命令状态".into()),
}
}
}
pub fn run(
id: &str,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<MaintenanceResult> {
let task = find(id)
.ok_or_else(|| squid_core::SquidError::Other(format!("未知的维护任务:{id}")))?;
let commands = commands(id).unwrap_or_default();
let budget_each = std::time::Duration::from_secs(task.budget_secs);
let started = std::time::Instant::now();
let mut result = MaintenanceResult {
task: id.to_string(),
ok: true,
..Default::default()
};
let total = commands.len() as u64;
for (index, (program, args, elevated)) in commands.into_iter().enumerate() {
cancel.check()?;
progress.publish(Event::Tick {
done: index as u64,
total: Some(total),
subject: Some(std::path::PathBuf::from(format!(
"{program} {}",
args.join(" ")
))),
});
let expanded: Vec<String> = args.iter().map(|arg| expand_env(arg)).collect();
let label = format!("{program} {}", args.join(" "));
let (ok, output) = if program == "delete-file" {
// Direct removal, no shell: the whitelist catalog is the
// only thing that can name a path here.
let path = std::path::PathBuf::from(&expanded[0]);
if !path.exists() {
(true, String::new())
} else {
match std::fs::remove_file(&path) {
Ok(()) => (true, String::new()),
Err(error) => (false, format!("删除 {} 失败:{error}", path.display())),
}
}
} else if elevated {
match run_elevated(program, &expanded) {
Ok(()) => (true, String::new()),
Err(error) => (false, error),
}
} else {
match spawn(program, &expanded) {
Ok(child) => wait_streamed(child, budget_each, progress, cancel),
Err(error) => (false, format!("无法启动 {program}:{error}")),
}
};
result
.steps
.push(format!("{label} — {}", if ok { "完成" } else { "失败" }));
if !output.is_empty() {
result.output_tail = output;
}
if !ok {
result.ok = false;
result.failed_step = Some(label);
break;
}
}
result.duration_ms = started.elapsed().as_millis() as u64;
Ok(result)
}
}
#[cfg(not(windows))]
mod run {
use super::*;
pub fn run(
id: &str,
_progress: &Progress,
_cancel: &CancelToken,
) -> squid_core::Result<MaintenanceResult> {
Ok(MaintenanceResult {
task: id.to_string(),
ok: false,
failed_step: Some("这些维护命令仅在 Windows 提供".into()),
..Default::default()
})
}
}
pub fn run(
id: &str,
progress: &Progress,
cancel: &CancelToken,
) -> squid_core::Result<MaintenanceResult> {
run::run(id, progress, cancel)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_listed_task_has_a_command_list() {
for task in tasks() {
let commands = commands(task.id);
assert!(commands.is_some(), "{} has no commands", task.id);
assert!(!commands.unwrap().is_empty(), "{} is empty", task.id);
assert!(task.budget_secs > 0);
assert!(!task.estimate.is_empty());
}
}
#[test]
fn the_whitelist_rejects_unknown_ids() {
assert!(commands("rm -rf /").is_none());
assert!(find("delete-my-boot").is_none());
assert_eq!(tasks().len(), 6);
}
#[test]
fn slow_jobs_come_last_and_carry_the_biggest_budget() {
let list = tasks();
let last = list.last().expect("tasks");
assert_eq!(last.id, "sfc-dism");
assert!(list.iter().all(|task| task.budget_secs <= last.budget_secs));
for task in &list {
// Nothing outside the six known ids sneaks into the catalog.
assert!(commands(task.id).is_some());
}
}
}

View File

@ -0,0 +1,255 @@
//! 隐私清理 (privacy cleaning) — the traces page.
//!
//! Different from every other engine on purpose: these deletions do **not**
//! go to the Recycle Bin. A browser profile half-restored from the bin is
//! worse than no restore at all (Chrome refuses profiles whose History file
//! was swapped behind its back), so the honest answer is: gone is gone, but
//! *what* was gone is written to the same history ledger, and the browser
//! lock check happens at scan time — an open browser shows a 🔒 chip instead
//! of silently failing mid-delete.
use squid_core::progress::CancelToken;
use squid_core::{Bytes, Category, CleanupItem, ItemKind, LockReason};
use std::path::PathBuf;
/// One privacy target: display copy, the paths it wipes, and the process
/// that must be closed first (browser profiles are exclusively locked).
struct PrivacySpec {
id: &'static str,
label_zh: &'static str,
detail_zh: &'static str,
/// (path, kind) pairs; Contents keeps the folder, deletes its children.
parts: &'static [(&'static str, ItemKind)],
/// Executable (lower-case, no path) that locks these files.
process: &'static str,
}
const SPECS: &[PrivacySpec] = &[
PrivacySpec {
id: "privacy-edge",
label_zh: "Edge 浏览记录与 Cookie",
detail_zh: "历史、Cookie、会话恢复数据;清空后需要重新登录网站",
parts: &[
(
r"AppData\Local\Microsoft\Edge\User Data\Default\History",
ItemKind::File,
),
(
r"AppData\Local\Microsoft\Edge\User Data\Default\History-journal",
ItemKind::File,
),
(
r"AppData\Local\Microsoft\Edge\User Data\Default\Network\Cookies",
ItemKind::File,
),
(
r"AppData\Local\Microsoft\Edge\User Data\Default\Network\Cookies-wal",
ItemKind::File,
),
(
r"AppData\Local\Microsoft\Edge\User Data\Default\Network\Cookies-shm",
ItemKind::File,
),
(
r"AppData\Local\Microsoft\Edge\User Data\Default\Session Storage",
ItemKind::Contents,
),
],
process: "msedge.exe",
},
PrivacySpec {
id: "privacy-chrome",
label_zh: "Chrome 浏览记录与 Cookie",
detail_zh: "历史、Cookie、会话恢复数据;清空后需要重新登录网站",
parts: &[
(
r"AppData\Local\Google\Chrome\User Data\Default\History",
ItemKind::File,
),
(
r"AppData\Local\Google\Chrome\User Data\Default\History-journal",
ItemKind::File,
),
(
r"AppData\Local\Google\Chrome\User Data\Default\Network\Cookies",
ItemKind::File,
),
(
r"AppData\Local\Google\Chrome\User Data\Default\Network\Cookies-wal",
ItemKind::File,
),
(
r"AppData\Local\Google\Chrome\User Data\Default\Network\Cookies-shm",
ItemKind::File,
),
(
r"AppData\Local\Google\Chrome\User Data\Default\Session Storage",
ItemKind::Contents,
),
],
process: "chrome.exe",
},
PrivacySpec {
id: "privacy-recent",
label_zh: "最近使用的文件 / 跳转列表",
detail_zh: "开始菜单与任务栏右键里的最近记录(链接本身,不删文件)",
parts: &[
(
r"AppData\Roaming\Microsoft\Windows\Recent",
ItemKind::Contents,
),
(
r"AppData\Roaming\Microsoft\Windows\Recent\AutomaticDestinations",
ItemKind::Contents,
),
(
r"AppData\Roaming\Microsoft\Windows\Recent\CustomDestinations",
ItemKind::Contents,
),
],
process: "",
},
PrivacySpec {
id: "privacy-clipboard",
label_zh: "剪贴板历史(Win+V)",
detail_zh: "Win+V 面板里缓存的历史条目,删除后列表清空",
parts: &[(r"AppData\Local\Microsoft\Clipboard", ItemKind::Contents)],
process: "",
},
PrivacySpec {
id: "privacy-activity",
label_zh: "活动历史记录(时间线)",
detail_zh: "设置→隐私→活动历史;删除后「恢复上次会话」不再可用",
parts: &[(
r"AppData\Local\ConnectedDevicesPlatform",
ItemKind::Contents,
)],
process: "",
},
];
/// Catalog for the UI: id + copy + estimated size, current lock state.
pub fn collect(engine: &crate::Engine, cancel: &CancelToken) -> Vec<CleanupItem> {
let home = squid_core::paths::home_dir();
let running: Vec<String> = engine
.platform()
.running_executables()
.into_iter()
.map(|proc| {
proc.rsplit(['/', '\\'])
.next()
.unwrap_or_default()
.to_lowercase()
})
.collect();
let mut out = Vec::new();
for spec in SPECS {
if cancel.is_cancelled() {
return out;
}
let blocked = !spec.process.is_empty() && running.iter().any(|p| p == spec.process);
for (tail, kind) in spec.parts {
let path = home.join(tail);
if !path.exists() {
continue;
}
let bytes = if path.is_dir() {
walkdir::WalkDir::new(&path)
.max_depth(4)
.into_iter()
.filter_entry(|e| !e.file_type().is_symlink())
.flatten()
.filter(|e| e.file_type().is_file())
.filter_map(|e| e.metadata().ok())
.map(|m| m.len())
.sum()
} else {
std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0)
};
let mut item = CleanupItem::new(path.clone(), *kind, Category::Privacy, spec.label_zh)
.with_rule(spec.id)
.with_anchors(std::iter::once(home.clone()))
.with_note(spec.detail_zh);
item.size = Bytes(bytes);
item.allocated = Bytes(bytes);
item.selected = false; // privacy deletes are opt-in, always
item.evidence = vec!["record:privacy-trace".into()];
if blocked {
item = item
.locked(LockReason::AppRunning)
.with_note(format!("{}:先完全退出浏览器再清理", spec.process));
}
out.push(item);
}
}
out
}
/// Expand a spec id back into the concrete paths it wipes. The delete layer
/// rebuilds Fresh items from these (never trusting the scan view).
pub fn paths_for(id: &str) -> Vec<(PathBuf, ItemKind)> {
let home = squid_core::paths::home_dir();
let Some(spec) = SPECS.iter().find(|spec| spec.id == id) else {
return Vec::new();
};
spec.parts
.iter()
.map(|(tail, kind)| (home.join(tail), *kind))
.filter(|(path, _)| path.exists())
.collect()
}
/// The lock reason if this spec cannot be cleaned right now.
pub fn lock_reason(engine: &crate::Engine, id: &str) -> Option<String> {
let spec = SPECS.iter().find(|spec| spec.id == id)?;
if spec.process.is_empty() {
return None;
}
let running: Vec<String> = engine
.platform()
.running_executables()
.into_iter()
.map(|proc| {
proc.rsplit(['/', '\\'])
.next()
.unwrap_or_default()
.to_lowercase()
})
.collect();
running
.iter()
.any(|p| p == spec.process)
.then(|| format!("{} 正在运行,请先完全退出", spec.process))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_spec_id_is_unique_and_prefixed() {
let mut seen = std::collections::HashSet::new();
for spec in SPECS {
assert!(spec.id.starts_with("privacy-"), "{}", spec.id);
assert!(seen.insert(spec.id), "duplicate id {}", spec.id);
}
}
#[test]
fn unknown_ids_expand_to_nothing() {
assert!(paths_for("privacy-nonsense").is_empty());
assert!(paths_for("").is_empty());
}
#[test]
fn known_ids_expand_without_panicking() {
// Real machine: some paths exist, some do not — either way the
// expansion must be a subset of the home tree, never a foreign root.
let home = squid_core::paths::home_dir();
for spec in SPECS {
for (path, _) in paths_for(spec.id) {
assert!(path.starts_with(&home) || home.join(&path).starts_with(&home));
}
}
}
}

View File

@ -196,9 +196,17 @@ pub fn scan(
let mut candidates: Vec<Candidate> = Vec::new();
let mut visited = 0usize;
for root in &roots {
let top_level = roots.len() > 1 && root.components().count() <= 3;
let cap = if top_level { depth.min(4) } else { depth };
walk(root, cap, &mut candidates, &mut visited, progress, cancel)?;
// Shallow roots (the home folder itself) only get a depth-reduced
// walk; project containers are worth the full depth.
let cap = if root.shallow { depth.min(4) } else { depth };
walk(
&root.path,
cap,
&mut candidates,
&mut visited,
progress,
cancel,
)?;
}
candidates.sort_by(|a, b| a.path.cmp(&b.path));
candidates.dedup_by(|a, b| a.path == b.path);
@ -222,11 +230,13 @@ pub fn scan(
);
let mut item = item_for(candidate);
// Evidence chain (B3): remember the git verdict + project root + age
// while checking, then attach machine tokens for the UI panel.
let evidence_project =
project_with_git(&candidate.path).unwrap_or_else(|| candidate.project.clone());
let evidence_age = age_days(&candidate.path);
if !options.force {
let project_root = match project_with_git(&candidate.path) {
Some(dir) => dir,
None => candidate.project.clone(),
};
let project_root = evidence_project.clone();
let state = match git_cache.iter().find(|(dir, _)| *dir == project_root) {
Some((_, state)) => *state,
None => {
@ -237,14 +247,22 @@ pub fn scan(
};
match state {
GitState::Tracked => {
item.evidence.push("git:tracked".into());
item = item
.locked(LockReason::Protected)
.with_note("tracked by git — pass --all to delete anyway");
}
GitState::Ignored => item.note = Some("git-ignored build output".into()),
GitState::Untracked => item.note = Some("untracked by git".into()),
GitState::Ignored => {
item.evidence.push("git:ignored".into());
item.note = Some("git-ignored build output".into());
}
GitState::Untracked => {
item.evidence.push("git:untracked".into());
item.note = Some("untracked by git".into());
}
GitState::Unknown => {
let age = age_days(&candidate.path);
item.evidence.push("git:none".into());
let age = evidence_age;
match age {
Some(age) if age >= min_age as f64 => {
item.note = Some(format!("no git repo · {:.0} days old", age));
@ -288,6 +306,7 @@ pub fn scan(
.locked(LockReason::NotOwned)
.with_note("owned by another user");
}
collect_evidence(&mut item, &evidence_project, evidence_age);
report.items.push(item);
}
@ -310,6 +329,77 @@ pub fn scan(
Ok(report)
}
/// Mole's node_modules evidence chain, made visible (B3):
/// a lockfile proves the tree is *reinstallable*; the package manager's
/// install record inside the artefact proves nobody hand-edited it since —
/// any file newer than the record smells like patched code, so we count it.
/// Returns machine tokens for the UI detail panel; empty = not a node tree.
fn node_evidence(project: &Path, artifact: &Path) -> Vec<String> {
const LOCKS: [(&str, &str); 3] = [
("package-lock.json", ".package-lock.json"),
("pnpm-lock.yaml", ".modules.yaml"),
("yarn.lock", ".yarn-integrity"),
];
let mut out = Vec::new();
let Some((lock, record)) = LOCKS.iter().find(|(lock, _)| project.join(lock).is_file()) else {
return out;
};
out.push(format!("lock:{lock}"));
let record_path = artifact.join(record);
let Ok(meta) = std::fs::metadata(&record_path) else {
out.push("record-missing".into());
return out;
};
out.push(format!("record:{record}"));
let Ok(stamp) = meta.modified() else {
return out;
};
let mut modified = 0u32;
let mut seen = 0u32;
for entry in walkdir::WalkDir::new(artifact)
.follow_links(false)
.max_depth(8)
.into_iter()
.filter_map(Result::ok)
{
if !entry.file_type().is_file() {
continue;
}
seen += 1;
if entry
.metadata()
.ok()
.and_then(|file| file.modified().ok())
.is_some_and(|when| when > stamp)
{
modified += 1;
if modified > 50 {
break;
}
}
if seen >= 40_000 {
break;
}
}
out.push(format!("modified:{modified}"));
out
}
/// Collect the evidence tokens for one candidate after its checks ran.
fn collect_evidence(item: &mut CleanupItem, project: &Path, age: Option<f64>) {
if let Some(age) = age {
item.evidence.push(format!("age:{}", age.floor() as u64));
}
let name = item
.path
.file_name()
.map(|name| name.to_string_lossy().to_lowercase())
.unwrap_or_default();
if name == "node_modules" {
item.evidence.extend(node_evidence(project, &item.path));
}
}
fn item_for(candidate: &Candidate) -> CleanupItem {
let category = if candidate.name.eq_ignore_ascii_case("DerivedData") {
Category::Developer
@ -337,26 +427,120 @@ fn item_for(candidate: &Candidate) -> CleanupItem {
.with_note(project)
}
/// Default roots: everything the user configured, plus the home folder itself
/// (shallow) so a project in an unexpected place is still found.
fn resolve_roots(engine: &Engine, options: &PurgeOptions) -> Vec<PathBuf> {
/// Default roots are auto-discovered (Mole habit, but without the config
/// file): the home folder, container-named children of the home
/// (`~/source`, `~/repos`, …) and container-named children sitting directly
/// under each fixed drive root (`D:\Projects`). A user who wants more passes
/// explicit roots; a user who edits `purge_roots` in settings.toml keeps
/// those extras honoured as well.
fn resolve_roots(engine: &Engine, options: &PurgeOptions) -> Vec<RootSpec> {
if !options.roots.is_empty() {
return options
let chosen: Vec<RootSpec> = options
.roots
.iter()
.map(|root| squid_core::paths::expand(&root.to_string_lossy()))
.filter(|path| path.is_dir())
.map(|path| RootSpec {
path,
shallow: false,
})
.collect();
if !chosen.is_empty() {
return chosen;
}
}
let mut roots: Vec<RootSpec> = Vec::new();
let push = |path: PathBuf, shallow: bool, roots: &mut Vec<RootSpec>| {
if path.is_dir()
&& !roots
.iter()
.any(|seen| squid_core::paths::same_path(&seen.path, &path))
{
roots.push(RootSpec { path, shallow });
}
};
// Extras the user maintains by hand in settings.toml (not a UI concept).
for root in engine.settings().purge_root_paths() {
push(root, false, &mut roots);
}
let mut roots = engine.settings().purge_root_paths();
let home = squid_core::paths::home_dir();
if !roots.iter().any(|root| root == &home) {
roots.push(home);
// Container-named homes: full depth, high value.
for container in container_children(&home) {
push(container, false, &mut roots);
}
roots.retain(|root| root.is_dir());
for mount in drive_roots(engine) {
for container in container_children(&mount) {
push(container, false, &mut roots);
}
}
// The home itself last, walked shallow: it still catches projects parked
// on Desktop / Documents without diving through the whole profile.
push(home, true, &mut roots);
roots
}
/// One walk start point. `shallow` roots (the home folder) get the reduced
/// depth cap; project containers are walked to the full depth.
struct RootSpec {
path: PathBuf,
shallow: bool,
}
/// Names that, one level under the home or a drive root, mean "my projects
/// live here". `documents`/`desktop` belong on drive roots (Windows users
/// keep code under `D:\Documents`, VS writes `Documents\source\repos`);
/// under the home folder they are reached by the shallow home walk anyway.
const CONTAINER_NAMES: &[&str] = &[
"repos",
"repo",
"git",
"github",
"code",
"coding",
"dev",
"develop",
"development",
"projects",
"project",
"workspace",
"workspaces",
"work",
"src",
"source",
"documents",
"desktop",
];
fn container_children(dir: &Path) -> Vec<PathBuf> {
let Ok(entries) = std::fs::read_dir(dir) else {
return Vec::new();
};
entries
.flatten()
.filter(|entry| {
let name = entry.file_name().to_string_lossy().into_owned();
CONTAINER_NAMES
.iter()
.any(|wanted| name.eq_ignore_ascii_case(wanted))
&& entry.path().is_dir()
})
.map(|entry| entry.path())
.collect()
}
/// Fixed drive mount points (Windows) / the root volume only elsewhere —
/// removable and network media are not project homes worth walking.
fn drive_roots(engine: &Engine) -> Vec<PathBuf> {
let Ok(volumes) = engine.platform().volumes() else {
return Vec::new();
};
volumes
.into_iter()
.filter(|volume| !volume.is_removable)
.map(|volume| volume.mount_point)
.collect()
}
fn walk(
root: &Path,
max_depth: usize,
@ -509,8 +693,21 @@ fn git_state(project: &Path, artifact: &Path) -> GitState {
}
}
/// Spawn helper: on Windows a GUI parent (Squid) would otherwise get a fresh
/// console window for every short-lived CLI call, flashing on the desktop.
fn hide_console(command: &mut Command) -> &mut Command {
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
}
#[cfg(not(windows))]
let _ = command;
command
}
fn run_git(project: &Path, args: &[&str]) -> Option<bool> {
let output = Command::new("git")
let output = hide_console(&mut Command::new("git"))
.arg("-C")
.arg(project)
.args(args)
@ -522,7 +719,7 @@ fn run_git(project: &Path, args: &[&str]) -> Option<bool> {
}
fn run_git_raw(project: &Path, args: &[&str]) -> Option<String> {
let output = Command::new("git")
let output = hide_console(&mut Command::new("git"))
.arg("-C")
.arg(project)
.args(args)
@ -546,9 +743,31 @@ fn measure(report: &mut ScanReport, progress: &Progress, cancel: &CancelToken) {
return;
}
progress.phase("measure", "measuring artefacts");
let sizes = squid_core::fs::measure_all(&targets, cancel, |index, _info| {
let meter = std::sync::Mutex::new((0u64, 0u64, std::time::Instant::now()));
let sizes = squid_core::fs::measure_all(&targets, cancel, |index, completed, info| {
let emit_line = {
let mut guard = meter
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
guard.0 += info.files;
guard.1 += info.on_disk().as_u64();
if completed as u64 == targets.len() as u64
|| guard.2.elapsed() >= std::time::Duration::from_millis(90)
{
guard.2 = std::time::Instant::now();
Some((guard.0, guard.1))
} else {
None
}
};
if let Some((files, bytes)) = emit_line {
progress.publish(squid_core::progress::Event::Metered {
files,
bytes: Bytes(bytes),
});
}
progress.tick(
index as u64 + 1,
completed as u64,
Some(targets.len() as u64),
targets.get(index).map(|(path, _)| path.clone()),
);
@ -556,6 +775,15 @@ fn measure(report: &mut ScanReport, progress: &Progress, cancel: &CancelToken) {
for (item, info) in report.items.iter_mut().zip(sizes) {
item.size = info.logical;
item.allocated = info.allocated;
item.file_count = info.files;
item.last_write_secs = if info.newest_write == 0 {
None
} else {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |since| since.as_secs());
Some(now.saturating_sub(info.newest_write))
};
if info.unreadable > 0 {
let suffix = format!("{} entries unreadable", info.unreadable);
item.note = Some(match item.note.take() {

View File

@ -0,0 +1,393 @@
//! 系统优化 (system optimisation) — a curated, **reversible** tweaks catalog.
//!
//! MangoDisk keeps 83 Windows settings and a revert registry; we start with
//! the low-dispute subset and one hard rule each tweak must pass before it
//! ships here: (1) registry-only or documented-API, (2) the original value
//! is recorded before the first write, (3) 「恢复全部默认」 puts every recorded
//! value back exactly, (4) verified on a real machine, not just this file.
//!
//! The catalog is data. Each tweak declares its hive/key/value/type and the
//! bytes that mean on/off; everything else (state read, apply, revert) is
//! one shared code path, so adding a tweak cannot introduce new bugs in
//! reading, writing, or undoing.
use serde::Serialize;
use squid_core::Settings;
use std::path::PathBuf;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum TweakKind {
Dword,
String,
NoneMeansZero,
}
/// One catalog entry. `on` is the payload that enables the tweak; `restore`
/// describes what "back to default" means (delete the value, or write the
/// original bytes we recorded).
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Tweak {
pub id: &'static str,
pub title_zh: &'static str,
pub title_en: &'static str,
pub detail_zh: &'static str,
pub detail_en: &'static str,
/// "safe" | "notice" — notice carries a visible side-effect hint.
pub risk: &'static str,
/// HKCU | HKLM (we only ever touch HKCU-approved paths for now).
pub hive: &'static str,
pub key: &'static str,
pub value: &'static str,
pub kind: TweakKind,
/// Payload (DWORD as u32 text, or the string) meaning "enabled".
pub on: &'static str,
/// A restart / Explorer restart is needed to see the effect.
pub restart_hint: bool,
}
/// The catalog — every entry verified on a real Windows 11 machine.
pub fn catalog() -> Vec<Tweak> {
vec![
Tweak {
id: "transparency",
title_zh: "关闭透明效果",
title_en: "Turn off transparency",
detail_zh: "降低 GPU 合成负担,远程桌面里也更清晰",
detail_en: "Less compositor work; sharper over RDP",
risk: "safe",
hive: "HKCU",
key: r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize",
value: "EnableTransparency",
kind: TweakKind::Dword,
on: "0",
restart_hint: false,
},
Tweak {
id: "show-extensions",
title_zh: "资源管理器显示文件扩展名",
title_en: "Show file extensions",
detail_zh: "隐藏扩展名是误删与伪装文件事故的头号来源",
detail_en: "Hidden extensions cause mis-deletes and fake-file tricks",
risk: "safe",
hive: "HKCU",
key: r"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced",
value: "HideFileExt",
kind: TweakKind::Dword,
on: "0",
restart_hint: false,
},
Tweak {
id: "widgets-web",
title_zh: "关闭小组件 Web 内容",
title_en: "Disable Widgets web content",
detail_zh: "任务栏小组件不再拉取新闻,减少后台联网与内存",
detail_en: "Taskbar Widgets stops fetching news feeds",
risk: "safe",
hive: "HKCU",
key: r"Software\Microsoft\Windows\CurrentVersion\Feeds",
value: "ShellWebContentSystemProvisioning",
kind: TweakKind::Dword,
on: "0",
restart_hint: true,
},
Tweak {
id: "location",
title_zh: "禁止位置同步",
title_en: "Disable location",
detail_zh: "应用不能再读取本机地理位置",
detail_en: "Apps can no longer read this device's location",
risk: "safe",
hive: "HKCU",
key: r"Software\Microsoft\Windows\CurrentVersion\CapabilityAccessManager\ConsentStore\location",
value: "Value",
kind: TweakKind::String,
on: "Deny",
restart_hint: false,
},
Tweak {
id: "recent-files",
title_zh: "关闭「最近使用的文件」",
title_en: "Turn off recent files",
detail_zh: "资源管理器与快速访问不再记录最近文件(隐私+微量性能)",
detail_en: "Explorer stops logging recent files",
risk: "notice",
hive: "HKCU",
key: r"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced",
value: "Start_TrackDocs",
kind: TweakKind::Dword,
on: "0",
restart_hint: true,
},
]
}
pub fn find(id: &str) -> Option<Tweak> {
catalog().into_iter().find(|tweak| tweak.id == id)
}
/// Row the UI sees: the tweak plus its live state and revert info.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TweakState {
#[serde(flatten)]
pub tweak: Tweak,
/// True when the on-payload is currently written.
pub enabled: bool,
/// The key/value could not be read at all (missing is NOT an error for
/// NoneMeansZero kinds).
pub unreadable: bool,
/// An original value was recorded → revert is possible.
pub recorded: bool,
}
/// Recorded originals, persisted beside the other app state.
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct TweakBackups {
/// tweak id → (kind marker + original payload text, or "absent")
pub originals: std::collections::HashMap<String, String>,
}
impl TweakBackups {
fn path() -> PathBuf {
Settings::config_dir().join("tweaks.json")
}
pub fn load() -> TweakBackups {
std::fs::read_to_string(Self::path())
.ok()
.and_then(|text| serde_json::from_str(&text).ok())
.unwrap_or_default()
}
fn save(&self) -> std::io::Result<()> {
let path = Self::path();
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(path, serde_json::to_string_pretty(self).unwrap_or_default())
}
/// Record once: the FIRST original value is the one we restore to, no
/// matter how many times the user flips the switch afterwards.
fn record(&mut self, id: &str, original: String) -> std::io::Result<()> {
if self.originals.contains_key(id) {
return Ok(());
}
self.originals.insert(id.to_string(), original);
self.save()
}
}
#[cfg(windows)]
mod registry {
use super::{Tweak, TweakKind};
use winreg::enums::{HKEY_CURRENT_USER, KEY_READ, KEY_WRITE};
use winreg::RegKey;
fn open(hive: &str) -> Result<RegKey, String> {
match hive {
"HKCU" => Ok(RegKey::predef(HKEY_CURRENT_USER)),
other => Err(format!("不支持的注册表根:{other}")),
}
}
/// Read the current payload as text; Ok(None) = value absent.
pub fn read(tweak: &Tweak) -> Result<Option<String>, String> {
let root = open(tweak.hive)?;
let Ok(key) = root.open_subkey_with_flags(tweak.key, KEY_READ) else {
return Ok(None); // key missing → value absent, not an error
};
let value = match tweak.kind {
TweakKind::String => key
.get_value::<String, _>(tweak.value)
.map(Some)
.unwrap_or(None),
_ => key
.get_value::<u32, _>(tweak.value)
.map(|number| Some(number.to_string()))
.unwrap_or(None),
};
Ok(value)
}
/// Write the payload; missing key is created with minimal rights
/// (create_subkey would ask KEY_ALL_ACCESS and security software says no).
pub fn write(tweak: &Tweak, payload: &str) -> Result<(), String> {
let root = open(tweak.hive)?;
let key = root
.create_subkey_with_flags(tweak.key, KEY_READ | KEY_WRITE)
.map_err(|error| format!("无法打开 {}:{error}", tweak.key))?
.0;
match tweak.kind {
TweakKind::String => key
.set_value(tweak.value, &payload.to_string())
.map_err(|error| error.to_string())?,
_ => {
let number: u32 = payload
.parse()
.map_err(|_| format!("不是合法的 DWORD:{payload}"))?;
key.set_value(tweak.value, &number)
.map_err(|error| error.to_string())?;
}
}
Ok(())
}
pub fn remove(tweak: &Tweak) -> Result<(), String> {
let root = open(tweak.hive)?;
if let Ok(key) = root.open_subkey_with_flags(tweak.key, KEY_READ | KEY_WRITE) {
let _ = key.delete_value(tweak.value);
}
Ok(())
}
}
#[cfg(not(windows))]
mod registry {
use super::Tweak;
pub fn read(_tweak: &Tweak) -> Result<Option<String>, String> {
Err("tweaks 仅在 Windows 提供".into())
}
pub fn write(_tweak: &Tweak, _payload: &str) -> Result<(), String> {
Err("tweaks 仅在 Windows 提供".into())
}
pub fn remove(_tweak: &Tweak) -> Result<(), String> {
Ok(())
}
}
pub fn states() -> Vec<TweakState> {
let backups = TweakBackups::load();
catalog()
.into_iter()
.map(|tweak| {
let raw = registry::read(&tweak);
let current = match &raw {
Ok(Some(value)) => Some(value.clone()),
// Absent DWORDs read as their documented default 0.
Ok(None) if tweak.kind != TweakKind::String => Some("0".to_string()),
Ok(None) => None,
Err(_) => None,
};
let enabled = current
.as_ref()
.is_some_and(|value| value.eq_ignore_ascii_case(tweak.on));
TweakState {
tweak: tweak.clone(),
enabled,
unreadable: raw.is_err(),
recorded: backups.originals.contains_key(tweak.id),
}
})
.collect()
}
/// Flip one tweak. The original value (including "absent") is recorded
/// before the first write so 「恢复全部默认」 can always undo the whole page.
pub fn set(id: &str, enabled: bool) -> Result<TweakState, String> {
let tweak = find(id).ok_or_else(|| format!("未知的优化项:{id}"))?;
let mut backups = TweakBackups::load();
let original = registry::read(&tweak)?;
// Absent DWORDs read as their documented default 0 for comparison.
let current = original
.clone()
.or((tweak.kind != TweakKind::String).then(|| "0".to_string()));
let already = current
.as_ref()
.is_some_and(|value| value.eq_ignore_ascii_case(tweak.on))
== enabled;
if already {
// No write, no recorded original — the machine is already where the
// switch says it should be; claiming a change would be a lie.
} else if enabled {
backups
.record(
tweak.id,
original.clone().unwrap_or_else(|| "absent".into()),
)
.map_err(|error| error.to_string())?;
registry::write(&tweak, tweak.on)?;
} else {
// Turning off explicitly = restore the recorded original.
restore_one(&mut backups, &tweak)?;
}
Ok(states()
.into_iter()
.find(|state| state.tweak.id == id)
.expect("catalog round-trips"))
}
fn restore_one(backups: &mut TweakBackups, tweak: &Tweak) -> Result<(), String> {
match backups.originals.get(tweak.id) {
Some(original) if original == "absent" || original.is_empty() => {
registry::remove(tweak)?;
}
Some(original) => {
registry::write(tweak, original)?;
}
None => registry::remove(tweak)?,
}
backups.originals.remove(tweak.id);
backups.save().map_err(|error| error.to_string())
}
/// 「恢复全部默认」: every recorded tweak back to its original value.
pub fn restore_all() -> Vec<String> {
let mut backups = TweakBackups::load();
let mut restored = Vec::new();
for tweak in catalog() {
if backups.originals.contains_key(tweak.id) && restore_one(&mut backups, &tweak).is_ok() {
restored.push(tweak.id.to_string());
}
}
restored
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn catalog_ids_are_unique_and_prefixed_hkcu() {
let mut seen = std::collections::HashSet::new();
for tweak in catalog() {
assert!(seen.insert(tweak.id), "duplicate {}", tweak.id);
assert_eq!(tweak.hive, "HKCU", "batch 1 stays user-hive only");
assert!(!tweak.key.is_empty() && !tweak.value.is_empty());
}
}
#[test]
fn unknown_ids_are_rejected() {
assert!(find("delete-my-boot").is_none());
assert!(set("delete-my-boot", true).is_err());
}
#[cfg(windows)]
#[test]
fn a_tweak_round_trips_through_the_registry() {
// A private scratch value under a key we own; registry access can be
// denied by endpoint protection in sandboxes, so skip politely then.
let probe = find("show-extensions").expect("catalog");
let before = match registry::read(&probe) {
Ok(value) => value,
Err(error) => {
eprintln!("skipping: registry read denied ({error})");
return;
}
};
if registry::write(&probe, "1").is_err() {
eprintln!("skipping: registry write denied");
return;
}
assert_eq!(registry::read(&probe).ok().flatten().as_deref(), Some("1"));
// Restore the machine to exactly how we found it.
match &before {
Some(value) => registry::write(&probe, value).expect("restore"),
None => registry::remove(&probe).expect("remove"),
}
assert_eq!(registry::read(&probe).ok().flatten(), before);
}
}

View File

@ -136,7 +136,14 @@ pub fn build_plan(
Some(version) => format!("{} · {}", app.source, version),
None => app.source.clone(),
});
if system {
if app.dead || app.path.as_os_str().is_empty() {
// 安装不完整: there is no bundle to move to the bin — the plan
// carries only the leftovers and the registry record the page
// offers to drop.
bundle_item = bundle_item
.locked(LockReason::Protected)
.with_note("程序本体已不存在,仅需清理注册表记录与残留");
} else if system {
bundle_item = bundle_item
.locked(LockReason::Protected)
.with_note("system application");
@ -248,9 +255,9 @@ fn measure(
.iter()
.map(|item| (item.path.clone(), item.kind))
.collect();
let sizes = squid_core::fs::measure_all(&targets, cancel, |index, _info| {
let sizes = squid_core::fs::measure_all(&targets, cancel, |index, completed, _info| {
progress.tick(
index as u64 + 1,
completed as u64,
Some(targets.len() as u64),
targets.get(index).map(|(path, _)| path.clone()),
);
@ -473,6 +480,7 @@ mod tests {
publisher: None,
installed_ms: None,
display_icon: None,
..AppInfo::default()
}
}

View File

@ -0,0 +1,551 @@
//! 进阶启动项 (advanced startup) — the Autoruns-shaped tail of the startup
//! story: Winlogon hooks, AppInit, IFEO debuggers, browser BHOs, and the
//! hidden corners of Task Scheduler and Services that ordinary listings
//! skip. Everything here can break boot or logon, so the contract is:
//!
//! * **display first** — the UI lists these read-mostly, with signature
//! trust and the exact registry location on every row;
//! * **disable is reversible** — the first disable records the original
//! value in `advanced-backup.json`; restoring puts the bytes back;
//! * hidden tasks and automatic services ride the *same* id scheme as the
//! normal startup list, so their toggles reuse the proven arms.
//!
//! Signature trust is a batched `Get-AuthenticodeSignature` PowerShell
//! call over the deduplicated exe set — one process, honest status
//! (微软 / 已知厂商 / 未签名 / 失效), no FFI.
use serde::{Deserialize, Serialize};
/// One advanced row. `kind` decides how disabling works.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AdvancedEntry {
/// `adv|<kind>|<hive>|<key>|<value>` (or task/service ids for the
/// reused arms).
pub id: String,
pub kind: String,
pub name: String,
/// Registry command line or task/service target.
pub command: String,
/// Human location, e.g. `HKLM\…\Winlogon\Userinit`.
pub location: String,
pub scope: String,
pub enabled: bool,
/// Digital-signature verdict: `microsoft` | `vendor` | `unsigned` |
/// `invalid` | `unknown` (no exe resolvable / non-Windows).
pub signature: String,
/// Subject of the signing certificate when known.
pub signer: Option<String>,
/// A warning the UI must show: IFEO hijacks a program, Winlogon is
/// boot-critical, etc.
pub warning: Option<String>,
}
#[cfg(windows)]
pub(crate) mod windows {
use super::AdvancedEntry;
use std::path::PathBuf;
use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ};
use winreg::RegKey;
const WINLOGON: &str = r"Software\Microsoft\Windows NT\CurrentVersion\Winlogon";
const IFEO: &str = r"Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options";
fn hive(machine: bool) -> RegKey {
RegKey::predef(if machine {
HKEY_LOCAL_MACHINE
} else {
HKEY_CURRENT_USER
})
}
fn read_string(key: &RegKey, path: &str, value: &str) -> Option<String> {
key.open_subkey_with_flags(path, KEY_READ)
.ok()?
.get_value::<String, _>(value)
.ok()
.map(|text| text.trim().to_string())
.filter(|text| !text.is_empty())
}
/// Strip quotes and arguments from a registry command to reach the exe.
pub(crate) fn exe_of(command: &str) -> Option<String> {
let text = command.trim();
if let Some(rest) = text.strip_prefix('"') {
return rest.split('"').next().map(str::to_string);
}
// Up to the first `.exe` boundary, else the first whitespace token.
if let Some(end) = text.to_ascii_lowercase().find(".exe") {
return Some(text[..end + 4].to_string());
}
text.split_whitespace().next().map(str::to_string)
}
fn winlogon_entries(out: &mut Vec<AdvancedEntry>) {
for (machine, hive_label) in [(true, "HKLM"), (false, "HKCU")] {
let root = hive(machine);
for (value, meaning) in [
("Shell", "登录外壳(正常情况下只有 explorer.exe)"),
(
"Userinit",
"登录初始化链(正常情况下以 userinit.exe, 结尾)",
),
] {
let Some(text) = read_string(&root, WINLOGON, value) else {
continue;
};
// The pristine value is a bare system component; anything
// extra rides alongside and is worth a warning.
let clean = text.split(',').all(|part| {
let part = part.trim().to_ascii_lowercase();
part.is_empty()
|| part
.replace("%systemroot%", "")
.replace("\\system32\\", "")
.starts_with(if value == "Shell" {
"explorer.exe"
} else {
"userinit.exe"
})
});
out.push(AdvancedEntry {
id: format!("adv|winlogon|{hive_label}|{WINLOGON}|{value}"),
kind: "winlogon".into(),
name: format!("Winlogon {value}"),
command: text,
location: format!("{hive_label}\\{WINLOGON} · {value}"),
scope: if machine { "machine" } else { "currentUser" }.into(),
enabled: true,
signature: "unknown".into(),
signer: None,
warning: (!clean)
.then(|| format!("{meaning};存在附加程序,请确认是否认识"))
.or_else(|| Some(format!("{meaning};改动需重启生效"))),
});
}
}
}
fn appinit_entries(out: &mut Vec<AdvancedEntry>) {
const KEY: &str = r"Software\Microsoft\Windows NT\CurrentVersion\Windows";
for (machine, hive_label) in [(true, "HKLM"), (false, "HKCU")] {
let root = hive(machine);
let enabled = read_string(&root, KEY, "LoadAppInit_DLLs").as_deref() == Some("1");
let Some(dlls) = read_string(&root, KEY, "AppInit_DLLs") else {
continue;
};
out.push(AdvancedEntry {
id: format!("adv|appinit|{hive_label}|{KEY}|AppInit_DLLs"),
kind: "appinit".into(),
name: "AppInit_DLLs 全局注入".to_string(),
command: dlls,
location: format!("{hive_label}\\{KEY}"),
scope: if machine { "machine" } else { "currentUser" }.into(),
enabled,
signature: "unknown".into(),
signer: None,
warning: Some("每个 GUI 进程都会加载这些 DLL;除非认识每一个,否则保持关闭".into()),
});
}
}
fn ifeo_entries(out: &mut Vec<AdvancedEntry>) {
for (machine, hive_label) in [(true, "HKLM"), (false, "HKCU")] {
let root = hive(machine);
let Ok(ifeo) = root.open_subkey_with_flags(IFEO, KEY_READ) else {
continue;
};
for name in ifeo.enum_keys().flatten() {
let Some(debugger) = read_string(&ifeo, &name, "Debugger") else {
continue;
};
// A Debugger replaces the program's launch entirely — the
// classic persistence trick. Only flag non-microsoft ones.
let lower = debugger.to_ascii_lowercase();
if lower.contains("mseone")
|| lower.contains("hybridlaunch")
|| lower.contains("msedge.exe --profile-directory")
{
continue; // Edge/IE protocol handlers live here legitimately
}
out.push(AdvancedEntry {
id: format!("adv|ifeo|{hive_label}|{IFEO}\\{name}|Debugger"),
kind: "ifeo".into(),
name: format!("{name} 被调试器接管"),
command: debugger,
location: format!("{hive_label}\\{IFEO}\\{name} · Debugger"),
scope: if machine { "machine" } else { "currentUser" }.into(),
enabled: true,
signature: "unknown".into(),
signer: None,
warning: Some(format!(
"启动 {name} 会先启动调试器;安全软件常用,也可能是流氓持久化"
)),
});
}
}
}
fn bho_entries(out: &mut Vec<AdvancedEntry>) {
const BHO: &str =
r"Software\Microsoft\Windows\CurrentVersion\Explorer\Browser Helper Objects";
let root = hive(true);
let Ok(bho) = root.open_subkey_with_flags(BHO, KEY_READ) else {
return;
};
for clsid in bho.enum_keys().flatten() {
let module = read_string(&root, &format!(r"Classes\{clsid}\InprocServer32"), "");
let friendly = read_string(&root, &format!(r"Classes\{clsid}"), "");
let load = bho
.open_subkey_with_flags(&clsid, KEY_READ)
.ok()
.and_then(|key| key.get_value::<u32, _>("LoadBehavior").ok())
.unwrap_or(3);
out.push(AdvancedEntry {
id: format!("adv|bho|HKLM|{BHO}\\{clsid}|LoadBehavior"),
kind: "bho".into(),
name: friendly.unwrap_or_else(|| clsid.clone()),
command: module.unwrap_or_else(|| clsid.clone()),
location: format!("HKLM\\{BHO}\\{clsid} · LoadBehavior"),
scope: "machine".into(),
enabled: load & 1 != 0,
signature: "unknown".into(),
signer: None,
warning: Some("浏览器加载项(IE 模式);现代浏览器大多不再使用".into()),
});
}
}
pub fn scan() -> Vec<AdvancedEntry> {
let mut out = Vec::new();
winlogon_entries(&mut out);
appinit_entries(&mut out);
ifeo_entries(&mut out);
bho_entries(&mut out);
enrich_signatures(&mut out);
out
}
/// Signature trust is a batch pass: collect the unique exes, grade them
/// all in one PowerShell call, then stamp every entry from the map.
fn enrich_signatures(entries: &mut [AdvancedEntry]) {
let mut exes: Vec<String> = Vec::new();
for entry in entries.iter_mut() {
if let Some(exe) = exe_of(&entry.command).filter(|path| PathBuf::from(path).exists()) {
if !exes.iter().any(|seen| seen.eq_ignore_ascii_case(&exe)) {
exes.push(exe);
}
entry.signature = "pending".into();
}
}
if exes.is_empty() {
return;
}
let grades = signature_grades(&exes);
for entry in entries.iter_mut() {
let Some(exe) = exe_of(&entry.command) else {
continue;
};
if let Some((verdict, signer)) = grades.get(&exe.to_ascii_lowercase()) {
entry.signature = verdict.clone();
entry.signer = signer.clone();
} else if entry.signature == "pending" {
entry.signature = "unknown".into();
}
}
}
/// One PowerShell round-trip grading many binaries at once:
/// lowercase path → (`verdict`, `signer`). Shared with the startup scan so
/// a page never shells out per row.
pub(crate) fn signature_grades(
exes: &[String],
) -> std::collections::HashMap<String, (String, Option<String>)> {
let mut grades: std::collections::HashMap<String, (String, Option<String>)> =
Default::default();
if exes.is_empty() {
return grades;
}
let list = exes
.iter()
.map(|exe| format!("'{}'", exe.replace('\'', "''")))
.collect::<Vec<_>>()
.join(",");
let script = format!(
"$ErrorActionPreference='SilentlyContinue'; {list} | ForEach-Object {{ $s = Get-AuthenticodeSignature -FilePath $_; \"@@|$_|$($s.Status)|$($s.SignerCertificate.Subject)\" }} | Out-String -Width 4096"
);
let mut command = std::process::Command::new("powershell.exe");
command.args(["-NoProfile", "-NonInteractive", "-Command", &script]);
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
// Squid is a GUI app: without this every scan flashed a console
// window for the duration of the signature batch.
command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
}
let Ok(output) = command.output() else {
return grades;
};
let text = String::from_utf8_lossy(&output.stdout);
for line in text.lines() {
// Out-String may pad lines; match on containment of the marker.
let Some(start) = line.find("@@|") else {
continue;
};
let rest = &line[start + 3..];
let mut parts = rest.splitn(3, '|');
let (Some(path), Some(status)) = (parts.next(), parts.next()) else {
continue;
};
let subject = parts.next().unwrap_or_default().to_string();
let signer = subject
.split("CN=")
.nth(1)
.map(|tail| tail.split(',').next().unwrap_or(tail).to_string())
.filter(|name| !name.is_empty());
let verdict = match status {
"Valid" => match &signer {
Some(name) if name.contains("Microsoft") || name.contains("Windows") => {
"microsoft"
}
Some(_) => "vendor",
None => "vendor",
},
"NotSigned" => "unsigned",
"HashMismatch" | "NotTrusted" | "CertificateExpired" | "UnknownError"
| "Missing" => "invalid",
_ => "unknown",
};
grades.insert(path.to_ascii_lowercase(), (verdict.into(), signer));
}
grades
}
}
#[cfg(not(windows))]
mod windows {
use super::AdvancedEntry;
pub fn scan() -> Vec<AdvancedEntry> {
Vec::new()
}
}
pub fn scan_advanced() -> Vec<AdvancedEntry> {
#[cfg(windows)]
{
windows::scan()
}
#[cfg(not(windows))]
{
Vec::new()
}
}
/// Disable/enable one advanced entry. Winlogon/AppInit/IFEO/BHO write
/// registry values (original recorded on first disable); tasks and services
/// are not handled here — the caller routes them through `set_startup_enabled`
/// because their ids use the ordinary scheme.
pub fn set_advanced_enabled(entry: &AdvancedEntry, enabled: bool) -> Result<(), String> {
#[cfg(windows)]
{
windows_set(entry, enabled)
}
#[cfg(not(windows))]
{
let _ = (entry, enabled);
Err("进阶启动项管理仅在 Windows 提供".into())
}
}
#[cfg(windows)]
fn windows_set(entry: &AdvancedEntry, enabled: bool) -> Result<(), String> {
use winreg::enums::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE};
use winreg::RegKey;
// id shape: adv|kind|HIVELABEL|key|value
let parts: Vec<&str> = entry.id.splitn(5, '|').collect();
if parts.len() != 5 {
return Err("无法解析的进阶项 id".into());
}
let (hive_label, key_path, value_name) = (parts[2], parts[3], parts[4]);
let root = RegKey::predef(if hive_label == "HKLM" {
HKEY_LOCAL_MACHINE
} else {
HKEY_CURRENT_USER
});
let mut backups = Backups::load();
match entry.kind.as_str() {
"winlogon" => {
let original = read_raw(&root, key_path, value_name)?;
if enabled {
let restore = backups
.originals
.get(&entry.id)
.cloned()
.unwrap_or_else(|| match value_name {
"Shell" => "explorer.exe".to_string(),
_ => r"C:\Windows\system32\userinit.exe,".to_string(),
});
write_raw(&root, key_path, value_name, &restore)?;
backups.originals.remove(&entry.id);
} else {
// Keep the mandatory piece, drop the third-party tail.
let kept: Vec<&str> = original
.split(',')
.map(str::trim)
.filter(|part| !part.is_empty())
.filter(|part| {
let lower = part.to_ascii_lowercase();
lower.contains("explorer.exe") || lower.contains("userinit.exe")
})
.collect();
let joined = kept.join(",");
if joined != original {
backups
.originals
.entry(entry.id.clone())
.or_insert_with(|| original.clone());
}
write_raw(&root, key_path, value_name, &joined)?;
}
}
"appinit" => {
backups
.originals
.entry(entry.id.clone())
.or_insert_with(|| if enabled { "1".into() } else { "0".into() });
write_dword(
&root,
key_path,
"LoadAppInit_DLLs",
if enabled { 1 } else { 0 },
)?;
}
"ifeo" => {
let original = read_raw(&root, key_path, value_name)?;
if enabled {
let restore = backups
.originals
.get(&entry.id)
.cloned()
.unwrap_or_else(|| original.clone());
write_raw(&root, key_path, value_name, &restore)?;
backups.originals.remove(&entry.id);
} else {
backups.originals.insert(entry.id.clone(), original);
delete_value(&root, key_path, value_name)?;
}
}
"bho" => {
write_dword(&root, key_path, "LoadBehavior", if enabled { 3 } else { 0 })?;
}
other => return Err(format!("不支持的进阶类型:{other}")),
}
backups.save()
}
#[cfg(windows)]
fn read_raw(root: &winreg::RegKey, key: &str, value: &str) -> Result<String, String> {
use winreg::enums::KEY_READ;
Ok(root
.open_subkey_with_flags(key, KEY_READ)
.map_err(|error| error.to_string())?
.get_value::<String, _>(value)
.unwrap_or_default())
}
#[cfg(windows)]
fn write_raw(root: &winreg::RegKey, key: &str, value: &str, text: &str) -> Result<(), String> {
use winreg::enums::{KEY_READ, KEY_WRITE};
root.create_subkey_with_flags(key, KEY_READ | KEY_WRITE)
.map_err(|error| error.to_string())?
.0
.set_value(value, &text.to_string())
.map_err(|error| error.to_string())
}
#[cfg(windows)]
fn write_dword(root: &winreg::RegKey, key: &str, value: &str, number: u32) -> Result<(), String> {
use winreg::enums::{KEY_READ, KEY_WRITE};
root.create_subkey_with_flags(key, KEY_READ | KEY_WRITE)
.map_err(|error| error.to_string())?
.0
.set_value(value, &number)
.map_err(|error| error.to_string())
}
#[cfg(windows)]
fn delete_value(root: &winreg::RegKey, key: &str, value: &str) -> Result<(), String> {
use winreg::enums::{KEY_READ, KEY_WRITE};
root.open_subkey_with_flags(key, KEY_READ | KEY_WRITE)
.map_err(|error| error.to_string())?
.delete_value(value)
.map_err(|error| error.to_string())
}
/// Original values for disabled advanced entries (restore data).
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
struct Backups {
originals: std::collections::HashMap<String, String>,
}
impl Backups {
#[cfg(windows)]
fn path() -> std::path::PathBuf {
squid_core::Settings::config_dir().join("advanced-backup.json")
}
#[cfg(windows)]
fn load() -> Backups {
std::fs::read_to_string(Self::path())
.ok()
.and_then(|text| serde_json::from_str(&text).ok())
.unwrap_or_default()
}
#[cfg(windows)]
fn save(&self) -> Result<(), String> {
let path = Self::path();
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
std::fs::write(
&path,
serde_json::to_string_pretty(self).unwrap_or_default(),
)
.map_err(|error| error.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scan_runs_and_ids_are_prefixed() {
// Real-machine smoke test: the scan must never panic and every id
// must carry the adv| prefix the parser in set_advanced_enabled
// depends on.
for entry in scan_advanced() {
assert!(entry.id.starts_with("adv|"), "{}", entry.id);
assert!(!entry.location.is_empty());
}
}
#[cfg(windows)]
#[test]
fn exe_extraction_handles_quotes_and_arguments() {
assert_eq!(
windows::exe_of(r#""C:\Program Files\Tool\warp.exe" --quiet""#).as_deref(),
Some(r"C:\Program Files\Tool\warp.exe")
);
assert_eq!(
windows::exe_of(r"C:\Windows\System32\userinit.exe,").as_deref(),
Some(r"C:\Windows\System32\userinit.exe")
);
assert_eq!(
windows::exe_of("mscandui.dll"),
Some("mscandui.dll".to_string())
);
}
}

View File

@ -136,6 +136,7 @@ pub fn app_from_bundle(
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as u64),
display_icon: None,
..AppInfo::default()
};
if app.name.to_lowercase() == "safari" {
// Safari cannot be removed and its caches are managed by the OS.

View File

@ -10,6 +10,7 @@ use squid_core::progress::CancelToken;
use squid_core::{AppInfo, Bytes, Volume};
use std::path::{Path, PathBuf};
pub mod advanced;
pub mod apps;
pub mod console;
pub mod currency;

View File

@ -225,6 +225,7 @@ impl Platform for Linux {
publisher: desktop.icon.clone(),
installed_ms: None,
display_icon: None,
..AppInfo::default()
});
}
}
@ -261,6 +262,7 @@ impl Platform for Linux {
publisher: None,
installed_ms: None,
display_icon: None,
..AppInfo::default()
});
}
}

File diff suppressed because it is too large Load Diff

View File

@ -12,7 +12,7 @@ use std::path::{Path, PathBuf};
use std::process::Command;
use sysinfo::{Disks, System};
use winreg::enums::{
HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_32KEY, KEY_WOW64_64KEY,
HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WOW64_32KEY, KEY_WOW64_64KEY, KEY_WRITE,
};
use winreg::RegKey;
@ -23,27 +23,135 @@ const UNINSTALL_SUBKEY: &str = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Unins
const NT_VERSION_KEY: &str = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion";
const BIOS_KEY: &str = r"HARDWARE\DESCRIPTION\System\BIOS";
fn open_uninstall_hives() -> Vec<(RegKey, &'static str)> {
fn open_uninstall_hives() -> Vec<(RegKey, &'static str, &'static str)> {
let mut hives = Vec::new();
let views = [
(KEY_WOW64_64KEY, "Registry (HKLM 64-bit)"),
(KEY_WOW64_32KEY, "Registry (HKLM 32-bit)"),
(KEY_WOW64_64KEY, "Registry (HKLM 64-bit)", "HKLM64"),
(KEY_WOW64_32KEY, "Registry (HKLM 32-bit)", "HKLM32"),
];
for (flag, label) in views {
for (flag, label, tag) in views {
if let Ok(key) = RegKey::predef(HKEY_LOCAL_MACHINE)
.open_subkey_with_flags(UNINSTALL_SUBKEY, KEY_READ | flag)
{
hives.push((key, label));
hives.push((key, label, tag));
}
}
if let Ok(key) =
RegKey::predef(HKEY_CURRENT_USER).open_subkey_with_flags(UNINSTALL_SUBKEY, KEY_READ)
{
hives.push((key, "Registry (HKCU)"));
hives.push((key, "Registry (HKCU)", "HKCU"));
}
hives
}
/// MSI install-state probe (the honest "安装不完整" detector). A registry
/// record whose product state is Unknown/Broken/Removed means the MSI
/// package itself is gone — the record is an orphan no msiexec can honour.
mod msi {
#[link(name = "msi")]
extern "system" {
fn MsiQueryProductStateW(product: *const u16) -> i32;
}
// INSTALLSTATE: 0 Unknown, 1 Broken, 2 Advertised, 3 Removed,
// 4 Installed, 5 Local, 6 Source, 7 Default.
fn wide(text: &str) -> Vec<u16> {
text.encode_utf16().chain(std::iter::once(0)).collect()
}
/// True when the MSI product for `guid` is missing or unusable.
pub fn product_broken(guid: &str) -> bool {
let normalized = guid.to_ascii_uppercase();
let state = unsafe { MsiQueryProductStateW(wide(&normalized).as_ptr()) };
matches!(state, 0 | 1 | 3)
}
}
/// The product GUID inside an `MsiExec.exe /X{GUID}` style command.
fn msi_guid(uninstall_string: &str) -> Option<&str> {
let upper = uninstall_string.to_ascii_uppercase();
if !upper.contains("MSIEXEC") {
return None;
}
let start = uninstall_string.find('{')?;
let end = uninstall_string[start..].find('}')? + start + 1;
Some(&uninstall_string[start..end])
}
/// Which manager owns this install, by path fingerprint (MangoDisk's source
/// merge, cheapened to what the registry already tells us). The badge is
/// honest provenance, not a guess: only well-known layouts qualify.
fn package_source(path: &Path, fallback: &str) -> String {
let lower = path.to_string_lossy().to_lowercase();
if lower.contains("\\windowsapps\\") {
return "Microsoft Store".into();
}
if lower.contains("\\scoop\\apps\\") {
return "scoop".into();
}
if lower.contains("\\chocolatey\\") {
return "Chocolatey".into();
}
if lower.contains("\\winget\\") || lower.contains("\\packages\\desktopappinstaller") {
return "winget".into();
}
if lower.contains("\\jetbrains\\toolbox\\apps\\") {
return "Toolbox".into();
}
fallback.into()
}
/// Remove the 安装不完整 registry record of a dead app (the orphan no
/// msiexec can honour). `reg_key` is the scanner's "HKLM64|<subkey>" tag.
/// HKLM needs admin, so an in-process denial escalates through one UAC
/// prompt via `reg.exe` — the record either goes or the user declines.
pub fn remove_uninstall_record(reg_key: &str) -> std::result::Result<(), String> {
let (tag, name) = reg_key.split_once('|').ok_or("注册表记录标识无效")?;
let hive_path = match tag {
"HKLM64" | "HKLM32" | "HKCU" => UNINSTALL_SUBKEY,
_ => return Err("注册表记录标识无效".into()),
};
if tag != "HKCU" {
use std::os::windows::process::CommandExt;
// reg.exe spells the 32-bit view through WOW6432Node.
let elevated_path = format!(
"HKLM\\{}\\{}",
if tag == "HKLM32" {
r"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
} else {
hive_path
},
name
);
let status = Command::new("reg.exe")
.args(["delete", &elevated_path, "/f"])
.creation_flags(0x0800_0000) // no console flash
.status();
if matches!(&status, Ok(s) if s.success()) {
return Ok(());
}
// Direct write denied (ACL or lack of admin): escalate once.
let script = format!(
"$ErrorActionPreference='Stop'; Start-Process -FilePath 'reg.exe' -ArgumentList 'delete','{}','/f' -Verb RunAs -WindowStyle Hidden -Wait",
elevated_path.replace('\'', "''")
);
let escalated = Command::new("powershell.exe")
.args(["-NoProfile", "-NonInteractive", "-Command", &script])
.creation_flags(0x0800_0000)
.status()
.map_err(|error| format!("无法启动提权助手:{error}"))?;
if !escalated.success() {
return Err("管理员授权被取消,注册表记录未删除".into());
}
return Ok(());
}
let hive = RegKey::predef(HKEY_CURRENT_USER)
.open_subkey_with_flags(hive_path, KEY_READ | KEY_WRITE)
.map_err(|error| format!("无法打开卸载注册表:{error}"))?;
hive.delete_subkey_all(name)
.map_err(|error| format!("删除注册表记录失败:{error}"))
}
fn str_value(key: &RegKey, name: &str) -> Option<String> {
key.get_value::<String, _>(name)
.ok()
@ -254,7 +362,7 @@ impl Platform for Windows {
.map(|p| p.to_lowercase())
.collect();
let mut apps = Vec::new();
for (hive, source) in open_uninstall_hives() {
for (hive, source, tag) in open_uninstall_hives() {
let names = hive
.enum_keys()
.filter_map(|name| name.ok())
@ -295,6 +403,21 @@ impl Platform for Windows {
running.iter().any(|exe| exe.starts_with(&loc))
})
.unwrap_or(false);
// 安装不完整 detection (MangoDisk's cross-check): the record
// exists but the product cannot be found any more — the MSI
// state says gone, or neither the install folder nor the
// uninstaller binary is on disk.
let dead = match uninstall_string.as_deref().and_then(msi_guid) {
Some(guid) => msi::product_broken(guid),
None => {
let uninstaller_gone = uninstall_string
.as_deref()
.and_then(uninstall_program)
.map(|exe| !exe.exists())
.unwrap_or(true);
install_location.is_none() && uninstaller_gone
}
};
// Size: Windows installers report EstimatedSize (KB) for
// Add/Remove Programs — the same number Settings shows.
// Absent that, measure the install folder when asked.
@ -308,6 +431,10 @@ impl Platform for Windows {
.unwrap_or_default(),
None => Bytes::ZERO,
};
let mut source = package_source(&path, source);
if dead {
source.push_str(" · 安装不完整");
}
apps.push(AppInfo {
name: display_name,
bundle_id: None,
@ -315,12 +442,15 @@ impl Platform for Windows {
icon_source: display_icon_path(str_value(&key, "DisplayIcon")),
version: str_value(&key, "DisplayVersion"),
size,
source: source.into(),
source,
running: running_app,
has_sibling_install: false,
publisher: str_value(&key, "Publisher"),
installed_ms: install_date_ms(str_value(&key, "InstallDate")),
display_icon: str_value(&key, "DisplayIcon"),
uninstall_string,
reg_key: Some(format!("{tag}|{name}")),
dead,
});
}
}

View File

@ -889,6 +889,8 @@ impl App {
};
panel.buckets.insert(category, (total, count));
}
Event::Metered { .. } => {}
Event::Group { .. } => {}
Event::Deleted { path, freed } => {
self.push_log(format!(
"removed {} ({})",
@ -2611,6 +2613,7 @@ mod tests {
publisher: None,
installed_ms: None,
display_icon: None,
..AppInfo::default()
};
let items = vec![
CleanupItem::new(
@ -2708,6 +2711,7 @@ mod tests {
publisher: None,
installed_ms: None,
display_icon: None,
..AppInfo::default()
}];
app.uninstall.filter = "Squid".into();
assert_eq!(app.uninstall.visible().len(), 1);

View File

@ -135,6 +135,9 @@ impl Strings {
C::LanguagePacks => "多余语言包",
C::Leftovers => "卸载残留",
C::UpdateInstallers => "升级安装包",
C::Duplicates => "重复文件",
C::AiTools => "AI 工具与模型",
C::Privacy => "隐私痕迹",
C::Trash => self.bin(),
},
})

View File

@ -2054,6 +2054,7 @@ mod tests {
publisher: None,
installed_ms: None,
display_icon: None,
..AppInfo::default()
},
// Sorted the way `build_plan` sorts: biggest first, so the bundle
// is *not* the first item here.
@ -2378,8 +2379,12 @@ mod tests {
screen.contains("12.0 GB"),
"the row and the header should both read 12.0 GB:\n{screen}"
);
// The bug this guards: the 1 TiB logical size leaking into the row
// or the header. Assert the file's *own* inflated numbers are gone —
// never "no TB anywhere": the host's real volumes (6 TB NAS drives)
// legitimately print TB in the disk panel and made this flaky.
assert!(
!screen.contains("TB"),
!screen.contains("1.0 TB") && !screen.contains("1 TiB") && !screen.contains("1024 GB"),
"a sparse file must not inflate the total past the physical disk:\n{screen}"
);
}

View File

@ -1,5 +1,16 @@
# Desktop release and update channel
## 代码仓上传规则(用户指令「上传代码仓」即指本节)
- 地址:`https://git.unissense.tech/mula/nex_squid.git`(origin 已内置账号,
凭据 lijunjie,勿写入其他文件)。
- 分支:**dev**。提交信息用中文,经 `git commit --file -`(或 `-F 文件`)传入,
避免 pwsh 引号问题;发布二进制需 `git add -f`(release 目录不在 .gitignore
白名单内)。
- 打包版上传时同步刷新 `release/<ver>/`(安装包/便携包/SHA256SUMS/
squid-update.json/RELEASE_NOTES),并在 `release/CHANGELOG-SINCE-<上次上传版本>.md`
补每个版本的更新说明,注明本版学习/借鉴的 GitHub 开源项目及链接。
Squid uses the same release model as `nex_shift`: a git branch is the update
server. No object storage or release API is required.

View File

@ -0,0 +1,246 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--primary: #f26a33; --primary-strong: #d94f1f; --primary-soft: #fff0e7; --primary-tint: #fff7f2;
--primary-rgb: 242,106,51; --ink: #342019; --muted: #7d6256; --muted-soft: #a98f80;
--line: rgba(89,51,34,.1); --line-strong: rgba(89,51,34,.16);
--paper: #fbf7f2; --canvas: #f5eee7;
--green: #19a974; --green-soft: #e5f8f0; --orange: #ee844c; --orange-soft: #fff0e7;
--red: #e65a62; --red-soft: #ffeaeb;
}
body {
width: 1320px; background: var(--canvas); color: var(--ink);
font-family: "Segoe UI", "Microsoft YaHei", sans-serif; font-size: 14px;
padding: 30px 40px 44px; font-weight: 540;
}
h1 { font-size: 24px; font-weight: 700; margin-bottom: 4px; }
.sub { color: var(--muted); font-size: 13.5px; margin-bottom: 26px; }
h2 { font-size: 15px; font-weight: 700; margin: 26px 0 10px; color: var(--primary-strong); }
h2 span.en { color: var(--muted-soft); font-weight: 540; font-size: 12.5px; margin-left: 8px; }
.app { background: #fffdfb; border: 1px solid var(--line); border-radius: 16px;
box-shadow: 0 14px 34px rgba(89,51,34,.08); overflow: hidden; }
.tabs { display: flex; gap: 4px; padding: 14px 18px 0; border-bottom: 1px solid var(--line); background: #fffdfb; }
.tab { padding: 9px 16px 11px; font-size: 14.5px; color: var(--muted); border-radius: 10px 10px 0 0; }
.tab.on { color: var(--primary-strong); background: var(--primary-tint);
border: 1px solid rgba(var(--primary-rgb),.14); border-bottom: 2px solid var(--primary); font-weight: 620; }
.tab .n { font-size: 11.5px; background: var(--primary-soft); color: var(--primary-strong);
border-radius: 999px; padding: 1px 7px; margin-left: 6px; }
.rows { padding: 14px 18px 6px; }
.grp { font-size: 12.5px; color: var(--muted); margin: 8px 0 6px; display: flex; align-items: center; gap: 8px; }
.grp::after { content: ""; flex: 1; height: 1px; background: var(--line); }
.row { display: flex; align-items: center; gap: 10px; padding: 7px 8px; border-radius: 9px; font-size: 13.5px; }
.row:hover { background: var(--primary-tint); }
.cb { width: 15px; height: 15px; border-radius: 4.5px; border: 1.5px solid var(--line-strong); flex: 0 0 auto; }
.cb.on { background: var(--primary); border-color: var(--primary); position: relative; }
.cb.on::after { content: "✓"; color: #fff; font-size: 11px; position: absolute; left: 2px; top: -1px; }
.path { font-family: Consolas, monospace; font-size: 12.5px; color: var(--muted); flex: 1 1 auto;
white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.size { font-family: Consolas, monospace; font-size: 12.5px; color: var(--ink); }
.kept { font-size: 11px; color: var(--green); background: var(--green-soft); border-radius: 999px; padding: 1px 8px; }
.fade { opacity: .45; }
/* ===== CleanBar ===== */
.bar-wrap { padding: 12px 18px 16px; }
.cleanbar { border-radius: 12px; border: 1px solid; padding: 12px 16px; }
.cb-row { display: flex; align-items: center; gap: 14px; }
.cb-icon { width: 26px; height: 26px; border-radius: 50%; flex: 0 0 auto; display: flex;
align-items: center; justify-content: center; font-size: 14px; color: #fff; }
.cb-main { flex: 1 1 auto; min-width: 0; }
.cb-title { font-size: 14px; font-weight: 650; }
.cb-detail { font-size: 12px; margin-top: 3px; white-space: nowrap; overflow: hidden;
text-overflow: ellipsis; font-family: Consolas, monospace; }
.btn { border-radius: 10px; padding: 9px 18px; font-size: 13.5px; font-weight: 620;
border: 1px solid var(--line); background: #fff; color: var(--ink); flex: 0 0 auto; }
.btn.primary { background: linear-gradient(145deg, #ff9664, var(--primary) 55%, var(--primary-strong));
color: #fff; border: none; box-shadow: 0 6px 14px rgba(var(--primary-rgb),.25); }
.btn.ghost { border-color: rgba(var(--primary-rgb),.3); color: var(--primary-strong); background: #fff; }
.ready { background: var(--green-soft); border-color: rgba(25,169,116,.28); }
.ready .cb-icon { background: var(--green); }
.ready .cb-detail { color: var(--muted); font-family: inherit; }
.ready .btn { opacity: .55; }
.busy { background: #fff; border-color: rgba(var(--primary-rgb),.4); box-shadow: 0 8px 22px rgba(var(--primary-rgb),.14); }
.track { height: 10px; border-radius: 999px; background: rgba(89,51,34,.08); margin-top: 10px; overflow: hidden; }
.fill { height: 100%; border-radius: 999px; width: 29%;
background: linear-gradient(90deg, #ff9a68, var(--primary));
background-size: 34px 100%; background-image: repeating-linear-gradient(115deg,
rgba(255,255,255,.28) 0 10px, rgba(255,255,255,0) 10px 24px),
linear-gradient(90deg, #ff9a68, var(--primary)); }
.pct { font-family: Consolas, monospace; font-size: 13.5px; color: var(--primary-strong); font-weight: 700; }
.spin { width: 18px; height: 18px; border-radius: 50%; border: 2.5px solid rgba(var(--primary-rgb),.25);
border-top-color: var(--primary); }
.busy .cb-title { color: var(--ink); }
.busy .cb-detail { color: var(--muted); font-size: 11.5px; }
.cur { max-width: 560px; }
.bglink { font-size: 12px; color: var(--muted-soft); border: none; background: none; text-decoration: underline dotted; }
.done { background: var(--green-soft); border-color: rgba(25,169,116,.4); }
.done .cb-icon { background: var(--green); }
.done .cb-detail { color: var(--muted); font-family: inherit; }
.countdown { font-size: 11.5px; color: var(--muted-soft); }
.partial { background: var(--orange-soft); border-color: rgba(238,132,76,.45); }
.partial .cb-icon { background: var(--orange); }
.partial .cb-detail { color: var(--muted); font-family: inherit; }
.note { font-size: 12px; color: var(--muted-soft); margin: 8px 2px 0; }
.pill { display:inline-block; font-size: 11px; background: var(--primary-soft); color: var(--primary-strong);
border-radius: 999px; padding: 2px 9px; margin-right: 6px; }
</style>
</head>
<body>
<h1>Squid 清理进度交互 · 统一 UI 语言</h1>
<div class="sub">重复文件 / 垃圾清理 / 大文件 三处共用同一组件(示意以「重复文件」页为底)。</div>
<h2>① 清理前 <span class="en">现状不变:底部绿色确认条</span></h2>
<div class="app">
<div class="tabs">
<div class="tab">垃圾清理</div>
<div class="tab on">重复文件<span class="n">612 组</span></div>
<div class="tab">大文件</div>
</div>
<div class="rows">
<div class="grp">安装包 · 2 个副本 · 共 1.9 GB</div>
<div class="row"><span class="cb on"></span><span class="path">C:\Users\34798\Downloads\wxworkwindows-4.1.35.6027.exe</span><span class="size">996 MB</span></div>
<div class="row"><span class="kept">建议保留</span><span class="path">D:\Program Files (x86)\WXWork\9999.1.0\WeCom_Setup.exe</span><span class="size">996 MB</span></div>
</div>
<div class="bar-wrap">
<div class="cleanbar ready">
<div class="cb-row">
<div class="cb-icon">✓</div>
<div class="cb-main">
<div class="cb-title">已选中 128 个副本 · 预计释放 3.2 GB</div>
<div class="cb-detail">其中 2 组将「完全删除」,删除后进入回收站,可从历史撤销</div>
</div>
<button class="btn primary">清理 128 个副本</button>
</div>
</div>
</div>
</div>
<h2>② 清理中 <span class="en">确认条就地变形 · 真实逐文件进度 · 橙色流光</span></h2>
<div class="app">
<div class="tabs">
<div class="tab">垃圾清理</div>
<div class="tab on">重复文件<span class="n">612 组</span></div>
<div class="tab">大文件</div>
</div>
<div class="rows">
<div class="grp">安装包 · 2 个副本 · 共 1.9 GB</div>
<div class="row fade"><span class="cb on"></span><span class="path">C:\Users\34798\Downloads\wxworkwindows-4.1.35.6027.exe</span><span class="size">996 MB</span></div>
<div class="row fade"><span class="kept">建议保留</span><span class="path">D:\Program Files (x86)\WXWork\9999.1.0\WeCom_Setup.exe</span><span class="size">996 MB</span></div>
</div>
<div class="bar-wrap">
<div class="cleanbar busy">
<div class="cb-row">
<div class="spin"></div>
<div class="cb-main">
<div class="cb-title">正在清理 37 / 128 个文件 · 已释放 890 MB</div>
<div class="cb-detail cur">当前:C:\Users\34798\Downloads\VisualStudioProjSetup-2022.zip(移入回收站)</div>
</div>
<span class="pct">29%</span>
<button class="bglink">转入后台</button>
</div>
<div class="track"><div class="fill"></div></div>
</div>
<div class="note"><span class="pill">期间</span>可正常切页签 / 浏览其他页面,任务后台继续;按钮防重复提交;超过 10 秒才出现「转入后台」(缩成右下角小胶囊,点它随时唤回)。</div>
</div>
</div>
<h2>③ 清理完成 <span class="en">原地变绿 + 气泡双保险 · 5 秒自动收起</span></h2>
<div class="app">
<div class="tabs">
<div class="tab">垃圾清理</div>
<div class="tab on">重复文件<span class="n">604 组</span></div>
<div class="tab">大文件</div>
</div>
<div class="rows">
<div class="grp" style="margin-top:2px">已删除的 128 个副本从列表实时消失,组徽标同步减 8 组</div>
</div>
<div class="bar-wrap">
<div class="cleanbar done">
<div class="cb-row">
<div class="cb-icon">✓</div>
<div class="cb-main">
<div class="cb-title">清理完成 · 128 个文件已移入回收站 · 释放 3.2 GB</div>
<div class="cb-detail">用时 41 秒 · 可从「历史」一键撤销</div>
</div>
<button class="btn ghost">查看历史</button>
<button class="btn">知道了(5s)</button>
</div>
</div>
</div>
</div>
<h2>④ 部分未处理 <span class="en">琥珀色 · 接入现有「未处理原因」分组页</span></h2>
<div class="app">
<div class="tabs">
<div class="tab">垃圾清理</div>
<div class="tab on">重复文件<span class="n">605 组</span></div>
<div class="tab">大文件</div>
</div>
<div class="rows">
<div class="grp" style="margin-top:2px">与完成态同位置,仅颜色与文案不同</div>
</div>
<div class="bar-wrap">
<div class="cleanbar partial">
<div class="cb-row">
<div class="cb-icon">!</div>
<div class="cb-main">
<div class="cb-title">已清理 120 个 · 释放 3.1 GB · 8 个未处理</div>
<div class="cb-detail">占用中 5 · 需要管理员 2 · 文件已消失 1 · 用时 38 秒</div>
</div>
<button class="btn ghost">查看原因并处理</button>
<button class="btn">知道了(5s)</button>
</div>
</div>
</div>
</div>
<h2>⑤ 另两页同语言 <span class="en">只换名词,组件/颜色/节奏完全一致</span></h2>
<div class="app">
<div class="bar-wrap" style="display:flex; flex-direction:column; gap:12px;">
<div class="cleanbar busy">
<div class="cb-row">
<div class="spin"></div>
<div class="cb-main">
<div class="cb-title">正在清理 214 / 986 项 · 已释放 2.4 GB</div>
<div class="cb-detail cur">当前:Chrome 缓存 · index-dir\…(阶段 2/3:浏览器缓存)</div>
</div>
<span class="pct">22%</span>
<button class="bglink">转入后台</button>
</div>
<div class="track"><div class="fill" style="width:22%"></div></div>
</div>
<div class="cleanbar busy">
<div class="cb-row">
<div class="spin"></div>
<div class="cb-main">
<div class="cb-title">正在清理 4 / 12 个大文件 · 已释放 6.8 GB</div>
<div class="cb-detail cur">当前:D:\VMs\Ubuntu-24.04-disk001.vmdk(移入回收站)</div>
</div>
<span class="pct">33%</span>
<button class="bglink">转入后台</button>
</div>
<div class="track"><div class="fill" style="width:33%"></div></div>
</div>
<div class="cleanbar done">
<div class="cb-row">
<div class="cb-icon">✓</div>
<div class="cb-main">
<div class="cb-title">清理完成 · 986 项已处理 · 释放 11.6 GB</div>
<div class="cb-detail">回收站未清空前仍可恢复 · 用时 1 分 12 秒</div>
</div>
<button class="btn ghost">查看历史</button>
<button class="btn">知道了(5s)</button>
</div>
</div>
</div>
</div>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 195 KiB

View File

@ -1,7 +1,7 @@
{
"name": "squid-desktop",
"private": true,
"version": "0.1.11",
"version": "0.1.13",
"type": "module",
"author": "mula.liu",
"license": "GPL-3.0-only",

345
src-tauri/Cargo.lock generated
View File

@ -58,9 +58,9 @@ dependencies = [
[[package]]
name = "annotate-snippets"
version = "0.12.17"
version = "0.12.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2a5b0a5ab8561c603f16c3b78c24a386b1f70e7fc1b1b1e8c15738828e4a176"
checksum = "0258346f92c78dbc5b336b9a5b27c64447aa10643bc64e651db2edb145361564"
dependencies = [
"anstyle",
"memchr",
@ -462,9 +462,9 @@ dependencies = [
[[package]]
name = "bstr"
version = "1.13.1"
version = "1.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f"
checksum = "a680398c10c7bc0488067c4612226ea905a85f607134b69f3068d505d58c4214"
dependencies = [
"memchr",
"regex-automata",
@ -614,12 +614,12 @@ dependencies = [
[[package]]
name = "cfg-expr"
version = "0.20.10"
version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ba9e9ec16c447027685b1f897b720e18e9a8afd00bd7332c483537e38086c9f"
checksum = "8d4ba6e40bd1184518716a6e1a781bf9160e286d219ccdb8ab2612e74cfe4789"
dependencies = [
"smallvec",
"target-lexicon 0.13.5",
"target-lexicon 0.12.16",
]
[[package]]
@ -689,9 +689,9 @@ dependencies = [
[[package]]
name = "const-oid"
version = "0.10.2"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
[[package]]
name = "cookie"
@ -784,27 +784,27 @@ dependencies = [
[[package]]
name = "cranelift-assembler-x64"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10c7459262c93a3c408bda96acaaa3d92868f166b33d445b20921f8378325038"
checksum = "da23f7367f4f5d003249eb1067760b3e6f5df82ad61829d40db22fdf8d41fd22"
dependencies = [
"cranelift-assembler-x64-meta",
]
[[package]]
name = "cranelift-assembler-x64-meta"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "97a25bfba0da265ef1f98728358e9bb3ab7489913e7bd759c743108892288934"
checksum = "a8dbd10a21204ce6ae3786f8369860ec4e10a24913e987d5abe4c3cc0c7195d6"
dependencies = [
"cranelift-srcgen",
]
[[package]]
name = "cranelift-bforest"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a9ad33269057337a70db66950f426fbdce436a66fe8071f55851a13a2e40cd"
checksum = "4439be9aa2867bcef9effa83a265f550763a37b2cf4ad560c7bc41cbda947a48"
dependencies = [
"cranelift-entity",
"wasmtime-internal-core",
@ -812,9 +812,9 @@ dependencies = [
[[package]]
name = "cranelift-bitset"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d322e6584efe3b229b1164b49edf55aec561553426f7fe3e228a45e80a15a190"
checksum = "9913a7776903ccf6a3172633f59a0d6da2b428ec631c4b999a4b7401efdca1a7"
dependencies = [
"serde",
"serde_derive",
@ -823,9 +823,9 @@ dependencies = [
[[package]]
name = "cranelift-codegen"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a7b9f73f97da69d6edc9adbfeec068cdb2649f0221be41abd3909267cb1cd53"
checksum = "ffc88c2b684ca7df2ed79fa42b38a983e4d3632ee9d57bc2a389f69fc7ff9348"
dependencies = [
"bumpalo",
"cranelift-assembler-x64",
@ -848,15 +848,15 @@ dependencies = [
"serde_derive",
"sha2 0.10.9",
"smallvec",
"target-lexicon 0.13.5",
"target-lexicon 0.13.6",
"wasmtime-internal-core",
]
[[package]]
name = "cranelift-codegen-meta"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7015ef10993d7129e0bce933874b60dab8187239aca4ceca352987d9907d528"
checksum = "df667a6e48506af68c087cebee157bfe69e04d78df83e243025ce6473a538fcd"
dependencies = [
"cranelift-assembler-x64-meta",
"cranelift-codegen-shared",
@ -867,24 +867,24 @@ dependencies = [
[[package]]
name = "cranelift-codegen-shared"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37916b08a7b17e063bae743cb746da542df7df283ced961aae213620dc11e27a"
checksum = "ed3fdd2cd7bcd83a9263a978ea1d66477742a1a92095fa08f8752cb9a79ece11"
[[package]]
name = "cranelift-control"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8154d189f2cc2a84a95a8129773799ddcf2f4609f667047db30715db4be6aa0a"
checksum = "8e1ecc088bd88f5a271f55b1544a8ec60b9d7373f61efe267d54bd2481adf5a3"
dependencies = [
"arbitrary",
]
[[package]]
name = "cranelift-entity"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccbd0c43e96db753f44a84e44f680f9423ed0a475b81f301ba7c44b5db52c37b"
checksum = "2e9e591820d13f0671f879602ff29b241ea8b1dd54a386acbcbf4c3787f41af0"
dependencies = [
"cranelift-bitset",
"serde",
@ -894,45 +894,45 @@ dependencies = [
[[package]]
name = "cranelift-frontend"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b28ae2961cdda7a6814431b40e87bee46e57b7f92294467b32f447108e14674"
checksum = "b00cf9b20096b09b3499d19f82cca658c13c6988ecbc54881caf12a2f01b2f8c"
dependencies = [
"cranelift-codegen",
"hashbrown 0.17.1",
"log",
"smallvec",
"target-lexicon 0.13.5",
"target-lexicon 0.13.6",
]
[[package]]
name = "cranelift-isle"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41eef45b50970e024d673e3fc4a0703e4fee75ca31d63b26566eb0f142300179"
checksum = "4c9fc3f2d35b0b5879107b4c83246e3dfb93bf678e0c68f74f7bd9b7001f7a06"
[[package]]
name = "cranelift-native"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "649c7b9ad93d5d92287fee74608cacfb139602116293a46e2f25e6ea5402f05c"
checksum = "3c41c07ce15db19296c5ee3bed3019ec95bf2d773fbb28e73bdcb7fbc6ef9196"
dependencies = [
"cranelift-codegen",
"libc",
"target-lexicon 0.13.5",
"target-lexicon 0.13.6",
]
[[package]]
name = "cranelift-srcgen"
version = "0.135.8"
version = "0.135.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da04416d8e400ad7ae6d9722db72bfbddfbf36d0ff528ec422c4cc336621a172"
checksum = "7ed086d4ea76eb20e03b689abcc9a34bacaec54b1fc3e04269004acbed4587f0"
[[package]]
name = "crc32fast"
version = "1.5.4"
version = "1.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f97d3416d5337d15c4b0d78c8c91df922ca143f57ec20e2d1c188333047ef04"
checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945"
dependencies = [
"cfg-if",
]
@ -973,9 +973,9 @@ checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
[[package]]
name = "crypto-bigint"
version = "0.7.10"
version = "0.7.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c035cb64cba03dad2fb921f3e218785e8cf9a41790da5eb3a1400f62fa2be11"
checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82"
dependencies = [
"cpubits",
"ctutils",
@ -1622,7 +1622,7 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ff9f725b347b91d04340444fcbce0770886e4a6513e5f8e9e73a9e344efe73b"
dependencies = [
"gio 0.22.10",
"gio 0.22.11",
"gtk",
"log",
"objc2",
@ -1633,6 +1633,16 @@ dependencies = [
"windows 0.62.2",
]
[[package]]
name = "filetime"
version = "0.2.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7"
dependencies = [
"cfg-if",
"libc",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.15"
@ -1983,16 +1993,16 @@ dependencies = [
[[package]]
name = "gio"
version = "0.22.10"
version = "0.22.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4620fbafdf19dba814473e19f18e75290cb3338662f6ae35f0402affd3b2b699"
checksum = "536990682bab3b8bf68a78d298ccae69702a114290b096edf2bec6eb2e4013b3"
dependencies = [
"futures-channel",
"futures-core",
"futures-io",
"futures-util",
"gio-sys 0.22.9",
"glib 0.22.10",
"gio-sys 0.22.11",
"glib 0.22.11",
"libc",
"pin-project-lite",
"smallvec",
@ -2013,11 +2023,11 @@ dependencies = [
[[package]]
name = "gio-sys"
version = "0.22.9"
version = "0.22.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c28739f914c15b87a9856000bed9cbd5b3a8afbca5e982d9a299e1601422cb5"
checksum = "b9c253490f9a475047f109bf6ccb68c407e9d186b7bfab01849188f4e669e669"
dependencies = [
"glib-sys 0.22.9",
"glib-sys 0.22.11",
"gobject-sys 0.22.9",
"libc",
"system-deps 9.0.1",
@ -2049,9 +2059,9 @@ dependencies = [
[[package]]
name = "glib"
version = "0.22.10"
version = "0.22.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e4cf9e5bd8713f1990a92c422998826e0fb34824277b46bc59757373483c6694"
checksum = "c9c4cbf1972a07741ae5ce9b23a582a90efc69745fc713f8b037b8d962f604da"
dependencies = [
"bitflags 2.13.2",
"futures-channel",
@ -2059,8 +2069,8 @@ dependencies = [
"futures-executor",
"futures-task",
"futures-util",
"glib-macros 0.22.9",
"glib-sys 0.22.9",
"glib-macros 0.22.11",
"glib-sys 0.22.11",
"gobject-sys 0.22.9",
"libc",
"memchr",
@ -2083,9 +2093,9 @@ dependencies = [
[[package]]
name = "glib-macros"
version = "0.22.9"
version = "0.22.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9597c68fa7bdf4154a3079642cd21c4dccac0b0bdd2897d82861523bf91e7b9"
checksum = "d4014e54e2049108c93cf278b64e89f490849402e09b455a25dfa2098cc35093"
dependencies = [
"heck 0.5.0",
"proc-macro2",
@ -2105,9 +2115,9 @@ dependencies = [
[[package]]
name = "glib-sys"
version = "0.22.9"
version = "0.22.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99b38907e67e40dec9b60f858bcada952598719cb512a13eb13d6cdcd16f8295"
checksum = "8b01e8b94529c2698b98f765b887f1e001b76195c1e25d1139aa9336019e745d"
dependencies = [
"libc",
"system-deps 9.0.1",
@ -2160,7 +2170,7 @@ version = "0.22.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07595c9ba696bd9819cb6a8df39f08078f3dd679508fe052dd558492c2053834"
dependencies = [
"glib-sys 0.22.9",
"glib-sys 0.22.11",
"libc",
"system-deps 9.0.1",
]
@ -2843,12 +2853,6 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
[[package]]
name = "leb128"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52"
[[package]]
name = "leb128fmt"
version = "0.1.0"
@ -3192,16 +3196,16 @@ dependencies = [
[[package]]
name = "notify-rust"
version = "4.18.2"
version = "4.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4587364a9a0074333429b3df75a30a205340c56a536ca3eb6ca0e59b87bbf8af"
checksum = "57da5b5d3b7809bf71858da5a2818c3404ca4688c02c8abecdda0fcdec235df3"
dependencies = [
"futures-lite",
"log",
"mac-notification-sys",
"serde",
"tauri-winrt-notification",
"zbus",
"zbus 6.5.0",
]
[[package]]
@ -3825,9 +3829,9 @@ dependencies = [
[[package]]
name = "postcard"
version = "1.1.3"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24"
checksum = "5431b3dcfdf6d1985c87d11f267a171c0dec0a8cd544c6727b747d36365f1fca"
dependencies = [
"cobs",
"embedded-io 0.4.0",
@ -3967,9 +3971,9 @@ dependencies = [
[[package]]
name = "pulley-interpreter"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e6d73adcf2f76b98d3de7a31831b6d6436fd2b6518e0ad4f7cc722a12ad4133"
checksum = "1f153f8d747fe1a04a7323d84963bd99a609f41391357da9d35f1965fb2c58b7"
dependencies = [
"cranelift-bitset",
"log",
@ -3979,9 +3983,9 @@ dependencies = [
[[package]]
name = "pulley-macros"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5bde547f939ab9aa321a54c6694aef2e1e27741c2523c0627ff306677b3cbcff"
checksum = "90dd329c9c89b9d4cea5803db3399f34f122e93d43549058caf46f5a7d4406ec"
dependencies = [
"proc-macro2",
"quote",
@ -4032,9 +4036,9 @@ checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09"
[[package]]
name = "rand"
version = "0.10.3"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11"
dependencies = [
"chacha20",
"getrandom 0.4.3",
@ -4114,9 +4118,9 @@ dependencies = [
[[package]]
name = "regalloc2"
version = "0.15.2"
version = "0.15.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "757712e8e61590d6d4f5d563483755538b5aa13467837a3b41cd9832509a7f85"
checksum = "34f923657880712029496c2e68bb40bef163806b2011adde559b28bbcedc82ea"
dependencies = [
"allocator-api2",
"bumpalo",
@ -4129,9 +4133,9 @@ dependencies = [
[[package]]
name = "regex"
version = "1.13.1"
version = "1.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
checksum = "9807af0e638c12e753aa1b4e601791bf2a8f71274023c8bbeec12fc149950857"
dependencies = [
"aho-corasick",
"memchr",
@ -4141,9 +4145,9 @@ dependencies = [
[[package]]
name = "regex-automata"
version = "0.4.18"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
dependencies = [
"aho-corasick",
"memchr",
@ -4152,9 +4156,9 @@ dependencies = [
[[package]]
name = "regex-syntax"
version = "0.8.11"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
[[package]]
name = "reqwest"
@ -4250,9 +4254,9 @@ dependencies = [
[[package]]
name = "rsa"
version = "0.10.0-rc.21"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47cf9537fc2210e5db7a35a1cdda9d8d451b9df6fba234ec1cf0cd746c120c35"
checksum = "23e77fd77e0dea28b3011fd62d15445b7de7959333b0276d930e03be0f755699"
dependencies = [
"const-oid",
"crypto-bigint",
@ -4760,7 +4764,7 @@ dependencies = [
[[package]]
name = "squid-core"
version = "0.1.11"
version = "0.1.13"
dependencies = [
"anyhow",
"chrono",
@ -4779,7 +4783,7 @@ dependencies = [
[[package]]
name = "squid-desktop"
version = "0.1.11"
version = "0.1.13"
dependencies = [
"base64 0.22.1",
"chrono",
@ -4806,27 +4810,30 @@ dependencies = [
[[package]]
name = "squid-engine"
version = "0.1.11"
version = "0.1.13"
dependencies = [
"anyhow",
"chrono",
"crossbeam-channel",
"dirs 6.0.0",
"filetime",
"globset",
"libc",
"rayon",
"serde",
"serde_json",
"sha2 0.10.9",
"squid-core",
"squid-platform",
"squid-rules",
"squid-stats",
"walkdir",
"winreg 0.52.0",
]
[[package]]
name = "squid-guard"
version = "0.1.11"
version = "0.1.13"
dependencies = [
"chrono",
"hex",
@ -4842,7 +4849,7 @@ dependencies = [
[[package]]
name = "squid-platform"
version = "0.1.11"
version = "0.1.13"
dependencies = [
"dirs 6.0.0",
"file_icon_provider",
@ -4862,7 +4869,7 @@ dependencies = [
[[package]]
name = "squid-rules"
version = "0.1.11"
version = "0.1.13"
dependencies = [
"globset",
"serde",
@ -4874,7 +4881,7 @@ dependencies = [
[[package]]
name = "squid-stats"
version = "0.1.11"
version = "0.1.13"
dependencies = [
"chrono",
"libc",
@ -5051,7 +5058,7 @@ version = "9.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db551ad38aac61d5e0343e0eeeb0163be3115c4e23b6a025959570ee0c03c67d"
dependencies = [
"cfg-expr 0.20.10",
"cfg-expr 0.17.2",
"heck 0.5.0",
"pkg-config",
"toml 1.1.8+spec-1.1.0",
@ -5123,9 +5130,9 @@ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
[[package]]
name = "target-lexicon"
version = "0.13.5"
version = "0.13.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da"
[[package]]
name = "tauri"
@ -5303,9 +5310,9 @@ dependencies = [
[[package]]
name = "tauri-plugin-notification"
version = "2.8.0"
version = "2.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5bc6c194a95a535abdfbe3bc1af9a43935b8b9b29c216b8e71af8b59132703cf"
checksum = "14a226bfb8189ec4ab2c1936e66330ad06c44d9f6c54a674338208491dee177f"
dependencies = [
"log",
"notify-rust",
@ -5318,7 +5325,7 @@ dependencies = [
"thiserror 2.0.21",
"time",
"url",
"zbus",
"zbus 5.19.0",
]
[[package]]
@ -5340,7 +5347,7 @@ dependencies = [
"thiserror 2.0.21",
"url",
"windows 0.62.2",
"zbus",
"zbus 5.19.0",
]
[[package]]
@ -5356,7 +5363,7 @@ dependencies = [
"tokio",
"tracing",
"windows-sys 0.61.2",
"zbus",
"zbus 5.19.0",
]
[[package]]
@ -5968,14 +5975,13 @@ dependencies = [
[[package]]
name = "walrus"
version = "0.27.3"
version = "0.28.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5691aeb3546554822fe2c13d63149c26a027cd07d900a72c7c7f37f4321bfaea"
checksum = "04f034ddbc5b46d705409d64c617d01b9ed8c6c9ccac0ab6483e907d525bbf37"
dependencies = [
"anyhow",
"gimli 0.32.3",
"id-arena",
"leb128",
"log",
"walrus-macro",
"wasm-encoder 0.245.1",
@ -6145,9 +6151,9 @@ dependencies = [
[[package]]
name = "wasmtime"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2afcadb2e7d0417cb8f3f322c66eff49338b288f22290c0ca0bd3e9570732aa"
checksum = "8f47e5ae0d077a8415d626b028a1701fd4d4b3ed4d57e21a0b5daefe99ae81f1"
dependencies = [
"addr2line",
"async-trait",
@ -6167,7 +6173,7 @@ dependencies = [
"serde",
"serde_derive",
"smallvec",
"target-lexicon 0.13.5",
"target-lexicon 0.13.6",
"wasmparser 0.254.2",
"wasmtime-environ",
"wasmtime-internal-core",
@ -6182,9 +6188,9 @@ dependencies = [
[[package]]
name = "wasmtime-environ"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2de252f4aedfff6c2054ea5bea2454878a931c56e2553c6356b581e5e30a7e4e"
checksum = "956c03e93a68f39d8fb93b5b72885e327b38249272b14cac7a968804f5bad49f"
dependencies = [
"anyhow",
"cpp_demangle",
@ -6203,7 +6209,7 @@ dependencies = [
"serde_derive",
"sha2 0.10.9",
"smallvec",
"target-lexicon 0.13.5",
"target-lexicon 0.13.6",
"wasm-encoder 0.254.2",
"wasmparser 0.254.2",
"wasmprinter",
@ -6213,15 +6219,15 @@ dependencies = [
[[package]]
name = "wasmtime-internal-component-util"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5ad52499e6246d30bf8bf509506bd637248eee17c8dd623e0c7dbe43e7a1036"
checksum = "59133f8e0df9cb35ed819c3aad45ca3c5984267ec0a38e9c463d2bfadea01988"
[[package]]
name = "wasmtime-internal-core"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8838d7debfc98a69342d260a990ea6f64adf498184915fccfdbd6718bb40a9b"
checksum = "1463b7c70e14ab1db19709f29f298affc1f0ea50ea59b519d8aec8a6f5a56453"
dependencies = [
"hashbrown 0.17.1",
"libm",
@ -6230,9 +6236,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-cranelift"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "478c09af53c545d96227b349d35c70fc78e99816923f41428ffff00974bcd145"
checksum = "1a70ad5c0cf92e3b3f0dc2d15d140b83083170fa31fae5dcdd836cabf66873cb"
dependencies = [
"cranelift-codegen",
"cranelift-control",
@ -6245,7 +6251,7 @@ dependencies = [
"object",
"pulley-interpreter",
"smallvec",
"target-lexicon 0.13.5",
"target-lexicon 0.13.6",
"thiserror 2.0.21",
"wasmparser 0.254.2",
"wasmtime-environ",
@ -6256,9 +6262,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-fiber"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96dce7a8ea302c0f1eb4154eb1756525c90c595bbabbc590abad64d4c5ff8bbb"
checksum = "cce8b2932cdefb95f711d05e11e5959efad509481f3987917a5ab9b12e784291"
dependencies = [
"cc",
"libc",
@ -6270,9 +6276,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-jit-debug"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "895f3231b24ce0c12c8a7bb129a9f6ddc6772ec78e59748e53af743dcdd733d1"
checksum = "4e380afb5a32fdb509c2eecd8ab55e8203db6487770738ef96c216fef5ff76aa"
dependencies = [
"cc",
"wasmtime-internal-versioned-export-macros",
@ -6280,9 +6286,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-jit-icache-coherence"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28b60a0c1f735da6b862679b763f8bab653caa477ccc603a25752488b795fec5"
checksum = "6e944d8cec74d9e20db5a874cbc82e1174bf78d1dc092dbf6d79048ff41abfdf"
dependencies = [
"libc",
"wasmtime-internal-core",
@ -6291,9 +6297,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-unwinder"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b97b2c29c8f458bdf1b948058bfbb8141aad0f7abcf0f7cb3479866f4316bf3c"
checksum = "9ef8cc822d036e5366d9e458cc918f75e08d2faa24115c75ac5f791b45f1c36d"
dependencies = [
"cranelift-codegen",
"log",
@ -6303,9 +6309,9 @@ dependencies = [
[[package]]
name = "wasmtime-internal-versioned-export-macros"
version = "48.0.8"
version = "48.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32766b38d56927eca9a65858ea8c7b1803424db82562aafd69727aa970057561"
checksum = "fb0a732411dc5a84d071df6f8d773cb84338e4c4cb2dbd21bcc4ccd70754df30"
dependencies = [
"proc-macro2",
"quote",
@ -7073,9 +7079,9 @@ dependencies = [
[[package]]
name = "yara-x"
version = "1.23.0"
version = "1.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8a5ff1e1bb43734cc68f3ddc94646c9740c8c559d38fae559f0c79076f801db"
checksum = "46490aa1d13df1247f106e9620f4221fc8a13b351a9aeef5a34a9b0eaafd78cb"
dependencies = [
"annotate-snippets",
"anyhow",
@ -7132,9 +7138,9 @@ dependencies = [
[[package]]
name = "yara-x-macros"
version = "1.23.0"
version = "1.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc0df20854de457fdeaa3207e6fa08e439d22c63628e37e5608ae4113ebd8a2a"
checksum = "5d9568f7c8c3ce9a14a8ef472612bb86668cad05854155173de85b53c2c7189b"
dependencies = [
"darling",
"proc-macro2",
@ -7144,9 +7150,9 @@ dependencies = [
[[package]]
name = "yara-x-parser"
version = "1.23.0"
version = "1.24.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "336c1ef292d1d554526b10908198b71920f64dd58e56f39c8689b298fe858a1d"
checksum = "a7b6d18b9aeceb80d3516efc6658589d4311ee07bc4d29f1d740c28201b37109"
dependencies = [
"ascii_tree",
"bitflags 2.13.2",
@ -7213,11 +7219,38 @@ dependencies = [
"uuid",
"windows-sys 0.61.2",
"winnow 1.0.4",
"zbus_macros",
"zbus_macros 5.19.0",
"zbus_names",
"zvariant",
]
[[package]]
name = "zbus"
version = "6.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a7f9f5dd97fa527c1202ba1cb35d48e07f77d4de8542317c854f7aef22b0668"
dependencies = [
"async-trait",
"bitflags 2.13.2",
"endi",
"futures-core",
"hex",
"libc",
"ordered-stream",
"rustix",
"serde",
"serde_repr",
"socket2",
"uds_windows",
"uuid",
"windows-sys 0.61.2",
"winnow 1.0.4",
"zbus_macros 6.5.0",
"zbus_utils",
"zcheapstr",
"zruntime",
]
[[package]]
name = "zbus_macros"
version = "5.19.0"
@ -7233,6 +7266,18 @@ dependencies = [
"zvariant_utils",
]
[[package]]
name = "zbus_macros"
version = "6.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f5aa7f2c4ea81b7ccfb26bafefdb4d1a44dd9d4f82c8426173a3727311743e4"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"zbus_utils",
]
[[package]]
name = "zbus_names"
version = "4.3.5"
@ -7245,10 +7290,23 @@ dependencies = [
]
[[package]]
name = "zcheapstr"
version = "1.2.0"
name = "zbus_utils"
version = "6.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "939f186d9ecebe044315a5cb6d6f78568bbc21152adc954d5a0c2f58bdbc9920"
checksum = "af55e52da295311b368c45bcae221f020e28e97a2420360170ce389218e76ec7"
dependencies = [
"proc-macro2",
"quote",
"serde",
"syn 3.0.9",
"winnow 1.0.4",
]
[[package]]
name = "zcheapstr"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2da34e7164b75d803c3197b86e6cf61b874106fbd472c5082575a8bc5fbd0907"
dependencies = [
"serde",
]
@ -7325,6 +7383,19 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zruntime"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac67096b97c00742108c4674db6bb6178adb78c4b66a506b0e4a7a9593aa5d9e"
dependencies = [
"futures-core",
"futures-io",
"rustix",
"socket2",
"windows-sys 0.61.2",
]
[[package]]
name = "zvariant"
version = "5.15.1"

View File

@ -1,6 +1,6 @@
[package]
name = "squid-desktop"
version = "0.1.11"
version = "0.1.13"
description = "Squid — a CleanMyMac-inspired cleaner, uninstaller and system monitor."
authors = ["mula.liu"]
edition = "2021"

View File

@ -30,6 +30,9 @@ use tauri::{AppHandle, Emitter, Manager};
pub struct AppState {
jobs: Mutex<HashMap<String, CancelToken>>,
scans: Mutex<HashMap<String, ScanReport>>,
/// Confirmed duplicate groups from the last `duplicates_scan`, keyed by
/// scan id — deletes may only name (group, copy) indices from it.
dup_scans: Mutex<HashMap<String, squid_engine::duplicates::DupReport>>,
plans: Mutex<HashMap<String, UninstallPlan>>,
apps: Mutex<Vec<AppInfo>>,
app_icons: Mutex<HashMap<String, Option<String>>>,
@ -37,6 +40,11 @@ pub struct AppState {
/// Last light snapshot, so the widget window and the main window polling
/// a beat apart share one refresh instead of paying for two.
snapshot_cache: Mutex<Option<(Instant, squid_stats::SystemSnapshot)>>,
/// Mole-style size cache (A⑥): explored storage trees answered from
/// memory until a delete run bumps the epoch and invalidates them.
/// Stamp is wall-clock so the age survives nicely for UI copy.
storage_cache: Mutex<HashMap<String, (u64, std::time::SystemTime, analyze::Node)>>,
clean_epoch: std::sync::atomic::AtomicU64,
}
impl AppState {
@ -46,6 +54,17 @@ impl AppState {
.map_err(|_| "The application state is unavailable; restart Squid.".to_string())
}
fn epoch(&self) -> u64 {
self.clean_epoch.load(std::sync::atomic::Ordering::Relaxed)
}
/// Any successful delete invalidates cached storage sizes (Mole bumps its
/// cache schema whenever deletion semantics change what totals mean).
fn invalidate_storage_cache(&self) {
self.clean_epoch
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
pub(crate) fn begin(&self, job_id: &str) -> Result<CancelToken, String> {
if job_id.trim().is_empty() {
return Err("A job identifier is required.".into());
@ -200,6 +219,32 @@ fn emit_progress(app: &AppHandle, job_id: &str, kind: &str, event: Event) {
subject: None,
freed: None,
},
Event::Metered { files, bytes } => ProgressView {
job_id: job_id.into(),
kind: kind.into(),
event: "metered".into(),
phase: None,
detail: None,
done: Some(files),
total: Some(bytes.as_u64()),
subject: None,
freed: None,
},
Event::Group {
kind: unit,
payload,
} => ProgressView {
job_id: job_id.into(),
kind: kind.into(),
event: "group".into(),
phase: None,
// `dup:{json}` — one confirmed work unit, streamed live.
detail: Some(format!("{unit}:{payload}")),
done: None,
total: None,
subject: None,
freed: None,
},
Event::Done(_) => return,
};
let _ = app.emit("squid://progress", payload);
@ -220,6 +265,9 @@ pub struct CleanupItemView {
selected: bool,
lock: Option<LockReason>,
note: Option<String>,
last_write_secs: Option<u64>,
file_count: u64,
evidence: Vec<String>,
}
impl From<&CleanupItem> for CleanupItemView {
@ -237,6 +285,9 @@ impl From<&CleanupItem> for CleanupItemView {
selected: item.selected,
lock: item.lock,
note: item.note.clone(),
last_write_secs: item.last_write_secs,
file_count: item.file_count,
evidence: item.evidence.clone(),
}
}
}
@ -517,6 +568,7 @@ pub async fn cleanup_delete(
if let Ok(mut scans) = app.state::<AppState>().scans.lock() {
scans.remove(&scan_id);
}
app.state::<AppState>().invalidate_storage_cache();
Ok(DeleteResultView::from_outcome(outcome))
}
@ -600,13 +652,399 @@ pub async fn purge_delete(
if let Ok(mut scans) = app.state::<AppState>().scans.lock() {
scans.remove(&scan_id);
}
app.state::<AppState>().invalidate_storage_cache();
Ok(DeleteResultView::from_outcome(outcome))
}
/// One duplicate-file scan: three-stage funnel, groups streamed live.
#[derive(Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DupsView {
scan_id: String,
report: squid_engine::duplicates::DupReport,
elapsed_ms: u64,
}
#[tauri::command]
pub async fn duplicates_scan(
app: AppHandle,
job_id: String,
roots: Vec<String>,
min_size: Option<u64>,
) -> Result<DupsView, String> {
let token = app.state::<AppState>().begin(&job_id)?;
let progress = Progress::new();
let reporter =
ProgressReporter::start(app.clone(), job_id.clone(), "duplicates", progress.clone());
let started = Instant::now();
let roots: Vec<PathBuf> = if roots.is_empty() {
squid_engine::duplicates::default_roots()
} else {
roots.into_iter().map(|root| paths::expand(&root)).collect()
};
let task = tauri::async_runtime::spawn_blocking(move || {
squid_engine::duplicates::scan(
&roots,
min_size.unwrap_or(squid_engine::duplicates::DEFAULT_MIN_SIZE),
&progress,
&token,
)
})
.await
.map_err(|error| format!("Duplicate scan failed: {error}"))?;
reporter.finish();
app.state::<AppState>().finish(&job_id);
let report = task.map_err(|error| error.to_string())?;
let view = DupsView {
scan_id: job_id.clone(),
report,
elapsed_ms: started.elapsed().as_millis() as u64,
};
app.state::<AppState>()
.dup_scans
.lock()
.map_err(|_| "The scan cache is unavailable.".to_string())?
.insert(job_id, view.report.clone());
Ok(view)
}
/// Delete chosen copies of confirmed duplicate groups — Recycle Bin mode by
/// default, so a wrong click is a restore away, never a loss.
#[tauri::command]
pub async fn duplicates_delete(
app: AppHandle,
job_id: String,
scan_id: String,
selections: Vec<(usize, Vec<usize>)>,
mode: DeleteMode,
) -> Result<DeleteResultView, String> {
let token = app.state::<AppState>().begin(&job_id)?;
let report = app
.state::<AppState>()
.dup_scans
.lock()
.map_err(|_| "The scan cache is unavailable.".to_string())?
.get(&scan_id)
.cloned()
.ok_or_else(|| "This scan has expired. Run it again.".to_string())?;
let items = report.items_for(&selections);
if items.is_empty() {
app.state::<AppState>().finish(&job_id);
return Err("没有可删除的副本(每组至少保留一份)".into());
}
let progress = Progress::new();
let reporter = ProgressReporter::start(app.clone(), job_id.clone(), "delete", progress.clone());
let task = tauri::async_runtime::spawn_blocking(move || {
let engine = Engine::new().with_volume_wide_safety();
let job = DeleteJob::new(items, mode, "Squid · Duplicates");
delete::execute(&engine, &job, &progress, &token)
})
.await
.map_err(|error| format!("Duplicate delete failed: {error}"))?;
reporter.finish();
app.state::<AppState>().finish(&job_id);
let outcome = task.map_err(|error| error.to_string())?;
app.state::<AppState>().invalidate_storage_cache();
Ok(DeleteResultView::from_outcome(outcome))
}
/// Large-file sweep across drives with a threshold and optional type class.
#[derive(Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LargeFileView {
path: String,
display_path: String,
size: u64,
modified_ms: u64,
class: &'static str,
/// A cloud-sync folder sits above this file: 「网盘可能有副本?」.
cloud_hint: bool,
/// Disk-image extension that something (Hyper-V/WSL) may hold open.
maybe_mounted: bool,
}
fn cloud_hint(path: &str) -> bool {
let lower = path.to_lowercase();
[
"onedrive",
"\\wps cloud",
"iclouddrive",
"google drive",
"googledrive",
"dropbox",
"坚果云",
"syncthing",
"baidunetdisk",
"wuying",
]
.iter()
.any(|marker| lower.contains(marker))
}
#[tauri::command]
pub async fn large_files_scan(
app: AppHandle,
job_id: String,
roots: Vec<String>,
min_bytes: Option<u64>,
class: Option<String>,
) -> Result<Vec<LargeFileView>, String> {
let token = app.state::<AppState>().begin(&job_id)?;
let progress = Progress::new();
let reporter =
ProgressReporter::start(app.clone(), job_id.clone(), "bigfiles", progress.clone());
let mut roots: Vec<PathBuf> = roots.into_iter().map(|root| paths::expand(&root)).collect();
if roots.is_empty() {
roots = squid_engine::duplicates::default_roots();
}
let class = class.filter(|value| value != "all");
let task = tauri::async_runtime::spawn_blocking(move || {
analyze::large_files(
&roots,
min_bytes.unwrap_or(100 * 1024 * 1024),
class.as_deref(),
&token,
&progress,
)
})
.await
.map_err(|error| format!("Large file scan failed: {error}"))?;
reporter.finish();
app.state::<AppState>().finish(&job_id);
let files = task.map_err(|error| error.to_string())?;
Ok(files
.iter()
.map(|file| {
let display = file.path.display().to_string();
let image = matches!(squid_engine::analyze::file_class(&file.path), "image");
LargeFileView {
path: display.clone(),
display_path: paths::pretty(&file.path),
size: file.size().as_u64(),
modified_ms: file.modified_ms.unwrap_or(0),
class: squid_engine::analyze::file_class(&file.path),
cloud_hint: cloud_hint(&display),
maybe_mounted: image,
}
})
.collect())
}
/// Delete chosen large files (paths re-validated, Recycle Bin by default).
#[tauri::command]
pub async fn large_files_delete(
app: AppHandle,
job_id: String,
paths: Vec<String>,
mode: DeleteMode,
) -> Result<DeleteResultView, String> {
let token = app.state::<AppState>().begin(&job_id)?;
if paths.is_empty() {
app.state::<AppState>().finish(&job_id);
return Err("没有选中任何文件".into());
}
let items: Vec<CleanupItem> = paths
.iter()
.map(|raw| {
let path = PathBuf::from(raw);
let size = std::fs::metadata(&path).map(|meta| meta.len()).unwrap_or(0);
let anchor = path
.ancestors()
.nth(2)
.map(|dir| dir.to_path_buf())
.unwrap_or_else(paths::home_dir);
let mut item = CleanupItem::new(
path.clone(),
ItemKind::File,
Category::SystemJunk,
path.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default(),
)
.with_rule("large-files")
.with_anchors(std::iter::once(anchor));
item.size = Bytes(size);
item.allocated = Bytes(size);
item.file_count = 1;
item
})
.collect();
let progress = Progress::new();
let reporter = ProgressReporter::start(app.clone(), job_id.clone(), "delete", progress.clone());
let task = tauri::async_runtime::spawn_blocking(move || {
let engine = Engine::new().with_volume_wide_safety();
let job = DeleteJob::new(items, mode, "Squid · Large Files");
delete::execute(&engine, &job, &progress, &token)
})
.await
.map_err(|error| format!("Large file delete failed: {error}"))?;
reporter.finish();
app.state::<AppState>().finish(&job_id);
let outcome = task.map_err(|error| error.to_string())?;
app.state::<AppState>().invalidate_storage_cache();
Ok(DeleteResultView::from_outcome(outcome))
}
/// Maintenance tasks live behind a single global lock key in the jobs map:
/// two repairs racing (SFC while the audio service restarts) can invalidate
/// each other's assumptions, so the second click is refused, not queued.
const MAINTENANCE_LOCK: &str = "maintenance";
#[tauri::command]
pub async fn maintenance_tasks() -> Result<Vec<squid_engine::maintenance::MaintenanceTask>, String>
{
Ok(squid_engine::maintenance::tasks())
}
#[tauri::command]
pub async fn maintenance_run(
app: AppHandle,
job_id: String,
task: String,
) -> Result<squid_engine::maintenance::MaintenanceResult, String> {
let state = app.state::<AppState>();
if job_id.trim().is_empty() {
return Err("A job identifier is required.".into());
}
// One token under both keys: the mutual-exclusion lock and the caller's
// cancel handle always point at the same flag.
let token = CancelToken::new();
{
let mut jobs = AppState::lock(&state.jobs)?;
if jobs.contains_key(MAINTENANCE_LOCK) {
return Err("另一个维护任务正在进行,请先等待它结束。".into());
}
jobs.insert(MAINTENANCE_LOCK.to_string(), token.clone());
jobs.insert(job_id.clone(), token.clone());
}
let progress = Progress::new();
let reporter =
ProgressReporter::start(app.clone(), job_id.clone(), "maintenance", progress.clone());
let task_id = task.clone();
let result = tauri::async_runtime::spawn_blocking(move || {
squid_engine::maintenance::run(&task_id, &progress, &token)
})
.await
.map_err(|error| format!("维护任务中断:{error}"));
reporter.finish();
if let Ok(mut jobs) = state.jobs.lock() {
jobs.remove(MAINTENANCE_LOCK);
jobs.remove(&job_id);
}
let outcome = result?.map_err(|error| error.to_string())?;
Ok(outcome)
}
/// Privacy traces scan: rows never pre-selected, running browsers locked.
#[tauri::command]
pub async fn privacy_scan(app: AppHandle, job_id: String) -> Result<ScanView, String> {
let token = app.state::<AppState>().begin(&job_id)?;
let progress = Progress::new();
let reporter =
ProgressReporter::start(app.clone(), job_id.clone(), "privacy", progress.clone());
let started = Instant::now();
let task = tauri::async_runtime::spawn_blocking(move || {
let engine = Engine::new();
let items = squid_engine::privacy::collect(&engine, &token);
Ok::<ScanReport, squid_core::SquidError>(ScanReport {
items,
scanned_at_ms: 0,
..Default::default()
})
})
.await
.map_err(|error| format!("Privacy scan failed: {error}"))?;
reporter.finish();
app.state::<AppState>().finish(&job_id);
let report = task.map_err(|error| error.to_string())?;
let view = scan_view(
job_id.clone(),
&report,
started.elapsed().as_millis() as u64,
);
app.state::<AppState>()
.scans
.lock()
.map_err(|_| "The scan cache is unavailable.".to_string())?
.insert(job_id, report);
Ok(view)
}
/// Privacy deletes are permanent by design (a bin-restored browser profile
/// is broken worse than a clean one) but land in the same history ledger.
#[tauri::command]
pub async fn privacy_delete(
app: AppHandle,
job_id: String,
scan_id: String,
selected: Vec<usize>,
) -> Result<DeleteResultView, String> {
let token = app.state::<AppState>().begin(&job_id)?;
let mut report = app
.state::<AppState>()
.scans
.lock()
.map_err(|_| "The scan cache is unavailable.".to_string())?
.get(&scan_id)
.cloned()
.ok_or_else(|| "This scan has expired. Run it again.".to_string())?;
select_indices(&mut report, &selected)?;
let items = report.items;
let progress = Progress::new();
let reporter = ProgressReporter::start(app.clone(), job_id.clone(), "delete", progress.clone());
let task = tauri::async_runtime::spawn_blocking(move || {
let engine = Engine::new();
let job = DeleteJob::new(items, DeleteMode::Permanent, "Squid · Privacy");
delete::execute(&engine, &job, &progress, &token)
})
.await
.map_err(|error| format!("Privacy clean failed: {error}"))?;
reporter.finish();
app.state::<AppState>().finish(&job_id);
let outcome = task.map_err(|error| error.to_string())?;
if let Ok(mut scans) = app.state::<AppState>().scans.lock() {
scans.remove(&scan_id);
}
Ok(DeleteResultView::from_outcome(outcome))
}
/// Optimisation tweaks: catalog + live state; writes record the original.
#[tauri::command]
pub async fn tweaks_states() -> Result<Vec<squid_engine::tweaks::TweakState>, String> {
tauri::async_runtime::spawn_blocking(squid_engine::tweaks::states)
.await
.map_err(|error| error.to_string())
}
#[tauri::command]
pub async fn tweaks_set(
id: String,
enabled: bool,
) -> Result<squid_engine::tweaks::TweakState, String> {
tauri::async_runtime::spawn_blocking(move || squid_engine::tweaks::set(&id, enabled))
.await
.map_err(|error| error.to_string())?
}
#[tauri::command]
pub async fn tweaks_restore_all() -> Result<Vec<String>, String> {
tauri::async_runtime::spawn_blocking(squid_engine::tweaks::restore_all)
.await
.map_err(|error| error.to_string())
}
#[derive(Clone, serde::Serialize)]
pub struct AppEntry {
#[serde(flatten)]
app: AppInfo,
/// `data:image/png;base64,…` of the app's icon (Windows only).
icon: Option<String>,
}
#[derive(Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AppsView {
apps: Vec<AppInfo>,
apps: Vec<AppEntry>,
total: u64,
}
@ -617,21 +1055,47 @@ pub async fn apps_scan(app: AppHandle, job_id: String) -> Result<AppsView, Strin
let reporter = ProgressReporter::start(app.clone(), job_id.clone(), "apps", progress.clone());
let task = tauri::async_runtime::spawn_blocking(move || {
let engine = Engine::new();
uninstall::scan_apps(&engine, true, &progress, &token)
let apps = uninstall::scan_apps(&engine, true, &progress, &token)
.map_err(|error| error.to_string())?;
let total = apps.iter().map(|app| app.size.as_u64()).sum();
// Icon extraction touches every binary: run it in this blocking task,
// once per install path.
let mut icons: std::collections::HashMap<String, Option<String>> = Default::default();
let entries = apps
.iter()
.map(|entry| {
let icon = icons
.entry(entry.key())
.or_insert_with(|| {
squid_platform::permissions::app_icon(entry).map(|png| {
use base64::{engine::general_purpose::STANDARD as B64, Engine as _};
format!("data:image/png;base64,{}", B64.encode(&png))
})
})
.clone();
AppEntry {
app: entry.clone(),
icon,
}
})
.collect::<Vec<_>>();
Ok::<_, String>((apps, entries, total))
})
.await
.map_err(|error| format!("Application scan failed: {error}"))?;
reporter.finish();
app.state::<AppState>().finish(&job_id);
let apps = task.map_err(|error| error.to_string())?;
let total = apps.iter().map(|app| app.size.as_u64()).sum();
let (apps, entries, total) = task?;
if let Ok(mut cache) = app.state::<AppState>().apps.lock() {
*cache = apps.clone();
*cache = apps;
}
if let Ok(mut icons) = app.state::<AppState>().app_icons.lock() {
icons.clear();
}
Ok(AppsView { apps, total })
Ok(AppsView {
apps: entries,
total,
})
}
/// Resolve one app's icon lazily so scanning does not pay for artwork the user
@ -763,9 +1227,44 @@ pub async fn app_uninstall(
if let Ok(mut plans) = app.state::<AppState>().plans.lock() {
plans.remove(&plan_id);
}
app.state::<AppState>().invalidate_storage_cache();
Ok(DeleteResultView::from_outcome(outcome))
}
/// 卸载增强: drop the 安装不完整 registry record after its files are gone.
/// HKLM removal escalates through one UAC prompt; a declined prompt is an
/// error the page surfaces, never a silent no-op.
#[tauri::command]
pub async fn app_remove_record(_app: AppHandle, reg_key: String) -> Result<(), String> {
#[cfg(windows)]
{
tauri::async_runtime::spawn_blocking(move || {
squid_platform::windows::remove_uninstall_record(&reg_key)
})
.await
.map_err(|error| error.to_string())?
}
#[cfg(not(windows))]
{
let _ = reg_key;
Err("此系统没有注册表记录".to_string())
}
}
/// What `storage_explore` answers: the tree plus how fresh it is (A⑥).
/// `cached` = served from the in-memory size cache; `measuredAtMs` = age of
/// the measurement so the page can say "12 分钟前" honestly. `Node` itself
/// serializes camelCase, same as before for the frontend contract.
#[derive(Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExploreView {
node: Node,
cached: bool,
measured_at_ms: Option<u64>,
}
const STORAGE_TTL: std::time::Duration = std::time::Duration::from_secs(600);
#[tauri::command]
pub async fn storage_explore(
app: AppHandle,
@ -773,7 +1272,8 @@ pub async fn storage_explore(
path: Option<String>,
depth: Option<usize>,
top: Option<usize>,
) -> Result<Node, String> {
force: Option<bool>,
) -> Result<ExploreView, String> {
let token = app.state::<AppState>().begin(&job_id)?;
let progress = Progress::new();
let reporter =
@ -787,20 +1287,114 @@ pub async fn storage_explore(
reporter.finish();
return Err(format!("{} is not a folder.", root.display()));
}
let depth = depth.unwrap_or(1).clamp(1, 3);
let top = top.unwrap_or(16);
let state = app.state::<AppState>();
let key = format!("{}|{depth}|{top}", root.to_string_lossy().to_lowercase());
let epoch = state.epoch();
if !force.unwrap_or(false) {
if let Ok(cache) = state.storage_cache.lock() {
if let Some((cached_epoch, at, node)) = cache.get(&key) {
let age = std::time::SystemTime::now()
.duration_since(*at)
.unwrap_or_default();
let fresh = epoch == *cached_epoch && age < STORAGE_TTL;
if fresh {
app.state::<AppState>().finish(&job_id);
reporter.finish();
return Ok(ExploreView {
node: node.clone(),
cached: true,
measured_at_ms: Some(u64::try_from(age.as_millis()).unwrap_or(u64::MAX)),
});
}
}
}
}
let task = tauri::async_runtime::spawn_blocking(move || {
analyze::explore(
&root,
depth.unwrap_or(1).clamp(1, 3),
top.unwrap_or(16),
&token,
&progress,
)
analyze::explore(&root, depth, top, &token, &progress)
})
.await
.map_err(|error| format!("Storage analysis failed: {error}"))?;
reporter.finish();
app.state::<AppState>().finish(&job_id);
task.map_err(|error| error.to_string())
let node = task.map_err(|error| error.to_string())?;
if let Ok(mut cache) = state.storage_cache.lock() {
// Tiny memory cap: the epoch clears everything after a delete run.
if cache.len() > 48 {
cache.clear();
}
cache.insert(key, (epoch, std::time::SystemTime::now(), node.clone()));
}
Ok(ExploreView {
node,
cached: false,
measured_at_ms: Some(0),
})
}
#[derive(Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InsightView {
id: String,
title: String,
path: String,
size: u64,
action: String,
command: Option<String>,
hint: String,
}
/// Hidden-space insights for the storage page's curated section (A⑤).
#[tauri::command]
pub async fn storage_insights() -> Result<Vec<InsightView>, String> {
let rows = tauri::async_runtime::spawn_blocking(squid_engine::insights::collect)
.await
.map_err(|error| format!("Insight scan failed: {error}"))?;
Ok(rows
.into_iter()
.map(|row| InsightView {
id: row.id,
title: row.title,
path: row.path,
size: row.size,
action: row.action,
command: row.command,
hint: row.hint,
})
.collect())
}
/// Mole-style last-second re-check surfaced before deletion (B1).
#[tauri::command]
pub async fn cleanup_preflight(
app: AppHandle,
scan_id: String,
selected: Vec<usize>,
) -> Result<serde_json::Value, String> {
let report = app
.state::<AppState>()
.scans
.lock()
.map_err(|_| "The scan cache is unavailable.".to_string())?
.get(&scan_id)
.cloned()
.ok_or_else(|| "This scan has expired. Run it again.".to_string())?;
let view = tauri::async_runtime::spawn_blocking(move || {
let engine = Engine::new();
let preflight = engine.preflight(&report, &selected);
serde_json::json!({
"checked": preflight.checked,
"blocked": preflight
.blocked
.into_iter()
.map(|(path, reason)| serde_json::json!({ "path": path, "reason": reason }))
.collect::<Vec<_>>(),
})
})
.await
.map_err(|error| error.to_string())?;
Ok(view)
}
#[tauri::command]
@ -870,6 +1464,34 @@ pub fn stop_process(app: AppHandle, process: ProcessSample) -> Result<(), String
sampler.stop(&process).map_err(|error| error.to_string())
}
/// Write a UTF-8 text file (B5 clean-list export; the UI picked the path
/// through the save dialog, so this is a plain, bounded write).
#[tauri::command]
pub async fn write_text_file(path: String, contents: String) -> Result<(), String> {
tauri::async_runtime::spawn_blocking(move || {
let target = paths::expand(&path);
std::fs::write(&target, contents.as_bytes())
.map_err(|error| format!("{}: {error}", target.display()))
})
.await
.map_err(|error| error.to_string())?
}
/// B2: which protection patterns actually hit something on this machine.
#[tauri::command]
pub async fn whitelist_audit() -> Result<serde_json::Value, String> {
let rows: Vec<serde_json::Value> = tauri::async_runtime::spawn_blocking(|| {
Engine::new()
.audit_whitelist()
.into_iter()
.map(|(pattern, live)| serde_json::json!({ "pattern": pattern, "live": live }))
.collect::<Vec<_>>()
})
.await
.map_err(|error| error.to_string())?;
Ok(serde_json::Value::Array(rows))
}
#[tauri::command]
pub fn history_list(limit: Option<usize>) -> Vec<Session> {
ledger::load_sessions(limit.unwrap_or(60).clamp(1, 500))
@ -900,6 +1522,7 @@ pub struct SettingsPatch {
language: Option<String>,
show_allocated: Option<bool>,
purge_min_age_days: Option<u64>,
purge_roots: Option<Vec<String>>,
history_keep: Option<usize>,
setup_reviewed: Option<bool>,
}
@ -921,6 +1544,15 @@ pub async fn settings_save(app: AppHandle, patch: SettingsPatch) -> Result<Setti
if let Some(days) = patch.purge_min_age_days {
settings.purge_min_age_days = days.min(3650);
}
if let Some(roots) = patch.purge_roots {
// Empty list = "back to the built-in defaults", mirroring Mole's
// leave-the-file-blank-to-reset habit.
settings.purge_roots = if roots.is_empty() {
Settings::default().purge_roots
} else {
roots
};
}
if let Some(keep) = patch.history_keep {
settings.history_keep = keep.clamp(5, 500);
}
@ -997,10 +1629,18 @@ pub fn reveal_path(app: AppHandle, path: String) -> Result<(), String> {
}
#[cfg(windows)]
{
crate::process::command("explorer.exe")
.arg(format!("/select,{}", target.display()))
.status()
.map_err(|error| error.to_string())?;
use std::os::windows::process::CommandExt;
// Explorer only understands `/select,"C:\path with space\x"` — the
// quotes must sit *inside* the argument, around the path. Handing
// the whole `/select,<path>` as one argument let Rust wrap it in
// one pair of quotes, Explorer failed to parse it and opened its
// default folder instead (定位 jumped to the wrong directory as
// soon as the path contained a space, e.g. Package Cache).
// `raw_arg` writes the argument verbatim, producing the exact
// command line Explorer documents.
let mut cmd = crate::process::command("explorer.exe");
cmd.raw_arg(format!("/select,\"{}\"", target.display()));
cmd.status().map_err(|error| error.to_string())?;
}
#[cfg(not(any(target_os = "macos", windows)))]
{

View File

@ -13,7 +13,7 @@ use security::ScanTarget;
use squid_core::{Locale, Settings};
use tauri::{
menu::{Menu, MenuItem, PredefinedMenuItem},
tray::TrayIconBuilder,
tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent},
AppHandle, Emitter, Manager, WindowEvent,
};
@ -66,22 +66,22 @@ fn tray_menu(app: &AppHandle, locale: Locale) -> tauri::Result<Menu<tauri::Wry>>
if security::scanning(app) {
tray_text(locale, "Scanning…", "正在扫描…")
} else {
tray_text(locale, "Scan for malware", "扫描恶意软件")
tray_text(locale, "Scan malware", "扫描恶意软件")
},
!security::scanning(app),
None::<&str>,
)?;
let startup = MenuItem::with_id(
let permissions = MenuItem::with_id(
app,
"startup",
"permissions",
tray_text(locale, "Manage startup items", "管理启动项"),
true,
None::<&str>,
)?;
let cleanup = MenuItem::with_id(
let space = MenuItem::with_id(
app,
"cleanup",
tray_text(locale, "Daily cleanup", "日常清理"),
"space",
tray_text(locale, "Space cleaning", "空间清理"),
true,
None::<&str>,
)?;
@ -92,13 +92,6 @@ fn tray_menu(app: &AppHandle, locale: Locale) -> tauri::Result<Menu<tauri::Wry>>
true,
None::<&str>,
)?;
let purge = MenuItem::with_id(
app,
"purge",
tray_text(locale, "Deep Clean", "深度清理"),
true,
None::<&str>,
)?;
let quit = MenuItem::with_id(
app,
"quit",
@ -108,7 +101,7 @@ fn tray_menu(app: &AppHandle, locale: Locale) -> tauri::Result<Menu<tauri::Wry>>
)?;
let first_separator = PredefinedMenuItem::separator(app)?;
let last_separator = PredefinedMenuItem::separator(app)?;
// Flips the widget master switch; state is shown on the Real-time monitor.
// Flips the widget master switch; state is shown on the 桌面小工具 page.
let widget_toggle = MenuItem::with_id(
app,
"widget",
@ -122,11 +115,10 @@ fn tray_menu(app: &AppHandle, locale: Locale) -> tauri::Result<Menu<tauri::Wry>>
&open,
&protection,
&scan,
&startup,
&permissions,
&first_separator,
&cleanup,
&space,
&apps,
&purge,
&widget_toggle,
&last_separator,
&quit,
@ -186,14 +178,14 @@ fn create_tray(app: &AppHandle, locale: Locale) -> tauri::Result<()> {
.icon_as_template(cfg!(target_os = "macos"))
.tooltip(tooltip)
.menu(&menu)
.show_menu_on_left_click(true)
// 左键/双击 = 直接打开主界面,右键 = 菜单(电脑管家式交互)。
.show_menu_on_left_click(false)
.on_menu_event(|app, event| match event.id.as_ref() {
"open" => show_main_window(app),
"scan" => security::scan_in_background(app.clone(), ScanTarget::Quick),
"startup" => navigate_to(app, "startup"),
"cleanup" => navigate_to(app, "cleanup"),
"permissions" => navigate_to(app, "permissions"),
"space" => navigate_to(app, "space"),
"applications" => navigate_to(app, "applications"),
"purge" => navigate_to(app, "purge"),
"widget" => {
if let Err(error) = widget::toggle_from_tray(app) {
eprintln!("widget toggle failed: {error}");
@ -202,6 +194,21 @@ fn create_tray(app: &AppHandle, locale: Locale) -> tauri::Result<()> {
"quit" => app.exit(0),
_ => {}
})
.on_tray_icon_event(|tray, event| {
let app = tray.app_handle();
match event {
TrayIconEvent::Click {
button: MouseButton::Left,
button_state: MouseButtonState::Up,
..
}
| TrayIconEvent::DoubleClick {
button: MouseButton::Left,
..
} => show_main_window(app),
_ => {}
}
})
.build(app)?;
Ok(())
}
@ -247,13 +254,28 @@ pub fn run() {
app::cancel_job,
app::cleanup_scan,
app::cleanup_delete,
app::cleanup_preflight,
app::purge_scan,
app::purge_delete,
app::duplicates_scan,
app::duplicates_delete,
app::large_files_scan,
app::large_files_delete,
app::maintenance_tasks,
app::maintenance_run,
app::privacy_scan,
app::privacy_delete,
app::tweaks_states,
app::tweaks_set,
app::tweaks_restore_all,
app::apps_scan,
app::app_plan,
app::app_uninstall,
app::app_remove_record,
app::app_icon,
app::storage_explore,
app::storage_insights,
app::write_text_file,
app::storage_largest_files,
app::system_snapshot,
app::stop_process,
@ -262,6 +284,7 @@ pub fn run() {
app::settings_save,
app::whitelist_add,
app::whitelist_remove,
app::whitelist_audit,
autostart::autostart_status,
autostart::set_autostart,
app::reveal_path,
@ -269,7 +292,10 @@ pub fn run() {
permissions::permission_status,
permissions::open_full_disk_access_settings,
manage::manage_scan,
manage::managed_startup_set_enabled,
manage::startup_set_enabled,
manage::startup_remove_entry,
manage::advanced_scan,
manage::advanced_set_enabled,
manage::extension_set_registered,
manage::popup_list,
manage::popup_close,
@ -301,9 +327,6 @@ pub fn run() {
security::security_update_rules,
security::security_rollback_rules,
security::open_quarantine_folder,
startup::startup_items,
startup::startup_set_enabled,
startup::open_startup_settings,
startup::process_inventory,
startup::process_detail,
startup::process_stop,
@ -315,6 +338,7 @@ pub fn run() {
security::spawn_scheduler(app.handle(), &settings);
manage::spawn_watcher(app.handle().clone());
widget::spawn_startup(app.handle());
widget::spawn_desktop_watch(app.handle());
Ok(())
})
.build(tauri::generate_context!())

View File

@ -135,6 +135,21 @@ pub struct StartupView {
source_label: String,
scope: String,
enabled: bool,
/// Attributed to a real software product (drives the 其他软件 bucket).
named: bool,
/// The binary this row really launches (lnk resolved); empty when unknown.
target: String,
/// False = the target is gone: a 残留项 the UI can offer to delete.
target_exists: bool,
/// `boot` | `logon` | `background` | `unknown`.
trigger: String,
/// Microsoft-signed or under %SystemRoot% — the hideable 系统组件 bucket.
system_item: bool,
/// Signature verdict of `target`: `microsoft` | `vendor` | `unsigned` |
/// `invalid` | `unknown`.
signature: String,
/// Signer subject when the binary carries a certificate.
signer: Option<String>,
}
impl From<&StartupEntry> for StartupView {
@ -149,6 +164,13 @@ impl From<&StartupEntry> for StartupView {
source_label: entry.source_label.clone(),
scope: entry.scope.clone(),
enabled: entry.enabled,
named: entry.named,
target: entry.target.clone(),
target_exists: entry.target_exists,
trigger: entry.trigger.clone(),
system_item: entry.system_item,
signature: entry.signature.clone(),
signer: entry.signer.clone(),
}
}
}
@ -169,6 +191,8 @@ pub struct ExtensionView {
icon: Option<String>,
/// false = currently parked in the app's restore list.
registered: bool,
/// Module carries real product strings — drives the software grouping.
named: bool,
}
impl ExtensionView {
@ -194,6 +218,7 @@ impl From<&ShellExtEntry> for ExtensionView {
publisher: entry.publisher.clone(),
icon: entry.icon.as_deref().map(png_data_url),
registered: true,
named: entry.named,
}
}
}
@ -310,7 +335,7 @@ pub async fn manage_scan(app: AppHandle) -> Result<ManageView, String> {
/// Flip one startup entry (registry / startup folder / scheduled task), then
/// rescan so a partially-applied toggle can never desync the UI.
#[tauri::command]
pub async fn managed_startup_set_enabled(
pub async fn startup_set_enabled(
app: AppHandle,
id: String,
enabled: bool,
@ -332,6 +357,119 @@ pub async fn managed_startup_set_enabled(
Ok(enabled_count)
}
/// Delete one autostart registration — aimed at 残留项 whose program is gone.
/// Only the config (registry value / shortcut / task) is removed, never files;
/// services are disabled instead of uninstalled. Returns the new enabled count.
#[tauri::command]
pub async fn startup_remove_entry(app: AppHandle, id: String) -> Result<usize, String> {
let manage = app.state::<ManageState>();
let entry = ManageState::lock(&manage.startup)?
.iter()
.find(|entry| entry.id == id)
.cloned()
.ok_or_else(|| "请先重新扫描启动项".to_string())?;
tauri::async_runtime::spawn_blocking(move || permissions::remove_startup_entry(&entry))
.await
.map_err(|error| error.to_string())??;
let fresh = tauri::async_runtime::spawn_blocking(permissions::scan_startup_entries)
.await
.map_err(|error| error.to_string())?;
let enabled_count = fresh.iter().filter(|entry| entry.enabled).count();
*ManageState::lock(&manage.startup)? = fresh;
Ok(enabled_count)
}
// ---- 进阶启动项 (advanced startup) ----------------------------------------
/// One advanced row for the UI: registry hooks with signature trust, plus
/// the hidden-task / auto-service tails merged from the ordinary scan.
#[derive(Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdvancedView {
id: String,
kind: String,
name: String,
command: String,
location: String,
scope: String,
enabled: bool,
signature: String,
signer: Option<String>,
warning: Option<String>,
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdvancedScanView {
entries: Vec<AdvancedView>,
/// Hidden scheduled tasks and automatic services, in the ordinary
/// startup shape so their toggles reuse `startup_set_enabled`.
extras: Vec<StartupView>,
}
#[tauri::command]
pub async fn advanced_scan(app: AppHandle) -> Result<AdvancedScanView, String> {
let manage = app.state::<ManageState>();
let (entries, startup) = tauri::async_runtime::spawn_blocking(|| {
(
squid_platform::advanced::scan_advanced(),
permissions::scan_startup_entries(),
)
})
.await
.map_err(|error| format!("进阶扫描失败:{error}"))?;
// Cache the ordinary scan so the extras' toggles can find their entries.
*ManageState::lock(&manage.startup)? = startup.clone();
let extras: Vec<StartupView> = startup
.iter()
.filter(|entry| {
// Only the corners the plain list does not already show:
// hidden-by-default vendor tasks (source marks) and services.
entry.source == "service"
})
.map(StartupView::from)
.collect();
Ok(AdvancedScanView {
entries: entries
.iter()
.map(|entry| AdvancedView {
id: entry.id.clone(),
kind: entry.kind.clone(),
name: entry.name.clone(),
command: entry.command.clone(),
location: entry.location.clone(),
scope: entry.scope.clone(),
enabled: entry.enabled,
signature: entry.signature.clone(),
signer: entry.signer.clone(),
warning: entry.warning.clone(),
})
.collect(),
extras,
})
}
#[tauri::command]
pub async fn advanced_set_enabled(
_app: AppHandle,
id: String,
enabled: bool,
) -> Result<(), String> {
// Advanced rows carry their whole state in the id + a fresh scan match.
let entry = tauri::async_runtime::spawn_blocking(squid_platform::advanced::scan_advanced)
.await
.map_err(|error| error.to_string())?
.into_iter()
.find(|entry| entry.id == id)
.ok_or_else(|| "该进阶项已不存在,请重新扫描".to_string())?;
tauri::async_runtime::spawn_blocking(move || {
squid_platform::advanced::set_advanced_enabled(&entry, enabled)
})
.await
.map_err(|error| error.to_string())??;
Ok(())
}
/// Unregister / restore a context-menu handler. Removal keeps the entry in
/// `manage.json`, which is both the restore recipe and the audit trail.
#[tauri::command]

View File

@ -67,7 +67,6 @@ impl StartupView {
}
}
#[tauri::command]
pub async fn startup_items() -> Result<StartupView, String> {
tauri::async_runtime::spawn_blocking(|| StartupView::of(squid_platform::startup::inventory()))
.await
@ -85,7 +84,6 @@ pub struct StartupChange {
/// Disable or enable one entry. The refreshed inventory comes back with it,
/// because the truth after a launchd reload or a registry write is whatever the
/// system now says, not what this function intended.
#[tauri::command]
pub async fn startup_set_enabled(id: String, enabled: bool) -> Result<StartupChange, String> {
tauri::async_runtime::spawn_blocking(move || {
let item = squid_platform::startup::set_enabled(&id, enabled)?;
@ -129,7 +127,6 @@ pub async fn startup_set_enabled(id: String, enabled: bool) -> Result<StartupCha
/// pane it does not recognise, so the macOS version picks the URL instead of trying
/// one and hoping: Ventura renamed the login-item pane from a Users & Groups anchor
/// to its own extension.
#[tauri::command]
pub fn open_startup_settings() -> Result<(), String> {
#[cfg(target_os = "macos")]
let target = {

View File

@ -8,7 +8,7 @@
//! broadcast on `widget://settings` so both views stay in sync.
use serde::{Deserialize, Serialize};
use squid_core::{Locale, Settings};
use squid_core::Settings;
use std::fs;
use std::path::PathBuf;
use std::sync::{Mutex, MutexGuard};
@ -16,28 +16,141 @@ use tauri::{AppHandle, Emitter, Manager, WebviewUrl, WebviewWindowBuilder};
pub const WIDGET_LABEL: &str = "widget";
/// `HWND_BOTTOM` + no-activate flags: the widget lives on the desktop layer —
/// above wallpaper and icons, below every ordinary app window.
/// Desktop residency (Windows). The widget is a borderless top-level window
/// parked at `HWND_BOTTOM`: above the wallpaper and icons, below every
/// ordinary app window. Pulsar dodges Win+D by living *inside* the taskbar
/// (SetParent into Shell_TrayWnd — the bar is immune to Show Desktop, and a
/// watchdog re-attaches when the parent drifts). The WebView2 widget cannot
/// be re-parented into the desktop tree like Pulsar's raw window: on this
/// machine the shell ejects it again within seconds, and every crossing
/// strands or hides the web content. So we keep Pulsar's *watchdog* idea
/// instead of its parent trick: the shell hides top-level windows on Win+D
/// by minimising or DWM-cloaking them, and a 1.5 s heartbeat puts any
/// shell-hidden-but-wanted widget back (unminimise → show uncloaks → re-park
/// on the desktop layer → one repaint). Ways the app hid the panel itself
/// (master switch off, all panels off, folded away via hide) are respected.
#[cfg(windows)]
mod desktop_layer {
use std::ffi::c_void;
#[link(name = "user32")]
extern "system" {
fn SetWindowPos(
hwnd: *mut core::ffi::c_void,
insert_after: *mut core::ffi::c_void,
hwnd: *mut c_void,
insert_after: *mut c_void,
x: i32,
y: i32,
cx: i32,
cy: i32,
flags: u32,
) -> i32;
fn IsIconic(hwnd: *mut c_void) -> i32;
fn IsWindowVisible(hwnd: *mut c_void) -> i32;
}
const HWND_BOTTOM: *mut core::ffi::c_void = 1usize as *mut core::ffi::c_void;
#[link(name = "dwmapi")]
extern "system" {
fn DwmGetWindowAttribute(
hwnd: *mut c_void,
attribute: u32,
value: *mut i32,
size: u32,
) -> i32;
}
const HWND_BOTTOM: *mut c_void = 1usize as *mut c_void;
const SWP_NOMOVE: u32 = 0x0002;
const SWP_NOSIZE: u32 = 0x0001;
const SWP_NOACTIVATE: u32 = 0x0010;
const DWMWA_CLOAKED: u32 = 14;
const MONITOR_DEFAULTTOPRIMARY: u32 = 1;
pub fn lower(hwnd: *mut core::ffi::c_void) {
#[repr(C)]
struct WinRect {
left: i32,
top: i32,
right: i32,
bottom: i32,
}
#[repr(C)]
struct MonitorInfo {
cb_size: u32,
monitor: WinRect,
work: WinRect,
flags: u32,
}
#[link(name = "user32")]
extern "system" {
fn GetWindowRect(hwnd: *mut c_void, rect: *mut WinRect) -> i32;
fn MonitorFromWindow(hwnd: *mut c_void, flags: u32) -> *mut c_void;
fn GetMonitorInfoW(monitor: *mut c_void, info: *mut MonitorInfo) -> i32;
}
/// (left, top, right, bottom) of the monitor this window sits on — in
/// true physical pixels, bypassing every DPI translation the webview
/// stack applies. (The Tauri `primary_monitor`/`outer_position` pair
/// disagrees with Win32 by the scale factor on a 150% display, which is
/// what let a mid-screen parking spot read as "correctly docked".)
pub fn monitor_rect(hwnd: *mut c_void) -> Option<(i32, i32, i32, i32)> {
// SAFETY: plain queries; the MONITORINFO carries its own size.
let monitor = unsafe { MonitorFromWindow(hwnd, MONITOR_DEFAULTTOPRIMARY) };
if monitor.is_null() {
return None;
}
let mut info = MonitorInfo {
cb_size: std::mem::size_of::<MonitorInfo>() as u32,
monitor: WinRect {
left: 0,
top: 0,
right: 0,
bottom: 0,
},
work: WinRect {
left: 0,
top: 0,
right: 0,
bottom: 0,
},
flags: 0,
};
if unsafe { GetMonitorInfoW(monitor, &mut info) } == 0 {
return None;
}
Some((
info.monitor.left,
info.monitor.top,
info.monitor.right,
info.monitor.bottom,
))
}
/// (x, y, width, height) of the window in physical pixels.
pub fn window_rect(hwnd: *mut c_void) -> Option<(i32, i32, i32, i32)> {
let mut rect = WinRect {
left: 0,
top: 0,
right: 0,
bottom: 0,
};
// SAFETY: plain query on a live handle.
if unsafe { GetWindowRect(hwnd, &mut rect) } == 0 {
return None;
}
Some((
rect.left,
rect.top,
rect.right - rect.left,
rect.bottom - rect.top,
))
}
/// Move (keep size) and re-park on the desktop layer in one call.
pub fn move_to(hwnd: *mut c_void, x: i32, y: i32) {
// SAFETY: z-order/position edit only; NOACTIVATE keeps focus away.
unsafe {
SetWindowPos(hwnd, HWND_BOTTOM, x, y, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE);
}
}
pub fn lower(hwnd: *mut c_void) {
// SAFETY: hwnd comes from Tauri's own window handle; SetWindowPos with
// NOMOVE|NOSIZE|NOACTIVATE only edits the z-order.
unsafe {
@ -52,6 +165,33 @@ mod desktop_layer {
);
}
}
/// Whether the shell (Win+D / 显示桌面) currently has this window put
/// away while we want it shown: minimised, DWM-cloaked, or plain hidden.
/// `minimised_or_cloaked` refines the answer for callers that only want
/// to force a repaint when the shell *actively* took the window down
/// (a window still hidden mid-startup just needs showing, not reloading).
pub fn shell_hidden(hwnd: *mut c_void, minimised_or_cloaked: &mut bool) -> bool {
// SAFETY: plain queries on a live handle.
*minimised_or_cloaked = unsafe { IsIconic(hwnd) != 0 };
if *minimised_or_cloaked {
return true;
}
let mut cloaked = 0i32;
unsafe {
DwmGetWindowAttribute(
hwnd,
DWMWA_CLOAKED,
&mut cloaked,
std::mem::size_of::<i32>() as u32,
);
}
if cloaked != 0 {
*minimised_or_cloaked = true;
return true;
}
unsafe { IsWindowVisible(hwnd) == 0 }
}
}
/// Park the widget at the bottom of the window stack (desktop layer).
@ -73,6 +213,93 @@ pub fn lower_window(app: &AppHandle) {
}
}
/// Desktop residency (Windows): heartbeat that both counters Win+D and
/// guards the docked position.
///
/// Two jobs, one loop:
/// 1. If the shell put the widget away (Win+D / 显示桌面), bring it back
/// within a beat and repaint once (as before).
/// 2. Position guard: compare the window's actual position with where the
/// prefs say it belongs (docked corner, or the remembered drag point).
/// Any mismatch re-docks and re-parks the widget. This catches *every*
/// way the window can end up mid-desktop: an RDP peer connecting
/// disconnects the console session and Windows re-lays-out top-level
/// windows on the next local unlock, a resolution switch, or another
/// program nudging it. The previous fix only watched the monitor size —
/// an RDP round-trip keeps the console resolution constant, so the
/// re-layout went unnoticed. A grace window suppresses re-docking while
/// the user is dragging (position still moving between ticks; the drag
/// persists `position` through widget_set, after which the expected spot
/// *is* the new location, so the guard never fights the pointer).
#[cfg(windows)]
pub fn spawn_desktop_watch(app: &AppHandle) {
let app = app.clone();
std::thread::spawn(move || {
let mut last_pos: Option<(i32, i32)> = None;
let mut grace = std::time::Instant::now();
loop {
std::thread::sleep(std::time::Duration::from_millis(1_500));
let Some(state) = app.try_state::<WidgetState>() else {
continue;
};
let prefs = state.current();
// A panel the user switched off (master switch, or every panel off —
// sync_window hides the empty shell then) is never resurrected; the
// watchdog only ever counters the shell's doing.
let wanted = prefs.enabled
&& (prefs.panel_run
|| prefs.panel_cpu
|| prefs.panel_network
|| prefs.panel_disk
|| prefs.panel_storage);
if !wanted {
continue;
}
let Some(window) = app.get_webview_window(WIDGET_LABEL) else {
continue;
};
let Ok(hwnd) = window.hwnd() else { continue };
let raw: *mut std::ffi::c_void = hwnd.0.cast();
// ── position guard ────────────────────────────────────────────
if let Some((x, y, w, h)) = desktop_layer::window_rect(raw) {
if last_pos != Some((x, y)) {
// The window just moved: someone (the user, most likely)
// is working on it. Re-check shortly instead of yanking
// it mid-drag; the loop's cadence doubles as the grace.
last_pos = Some((x, y));
grace = std::time::Instant::now() + std::time::Duration::from_millis(3_500);
} else if std::time::Instant::now() >= grace {
if let Some(monitor) = desktop_layer::monitor_rect(raw) {
let want = dock_point(monitor, (w, h), &prefs);
if (x - want.0).abs() > 2 || (y - want.1).abs() > 2 {
desktop_layer::move_to(raw, want.0, want.1);
}
}
}
}
// ── Win+D recovery ────────────────────────────────────────────
let mut took_down = false;
if !desktop_layer::shell_hidden(raw, &mut took_down) {
continue;
}
let _ = window.unminimize();
let _ = window.show();
desktop_layer::lower(raw);
// When the shell actively took the window down, Show() clears the
// cloak but the composed page can come back blank; one cheap reload
// makes it honest again. A plain hidden window (mid-startup) just
// needed showing.
if took_down {
place_window(&app, &prefs);
let _ = window.eval("location.reload()");
}
}
});
}
#[cfg(not(windows))]
pub fn spawn_desktop_watch(_app: &AppHandle) {}
fn default_interval_ms() -> u64 {
2_000
}
@ -103,6 +330,15 @@ pub struct WidgetPrefs {
pub collapsed: bool,
/// Last user-dragged position; None re-docks to `corner`.
pub position: Option<(i32, i32)>,
/// Docking scheme generation. Pre-0.1.12 builds persisted drag positions
/// and docked corners in spaces that disagreed (and an RDP session's
/// small-screen numbers survive as "valid" mid-desktop spots on a big
/// display). The first 0.1.12 boot drops the remembered spot once and
/// sets this flag; corner docking becomes deterministic again, and every
/// drag stored from then on is honoured in the same physical space the
/// guard measures.
#[serde(default)]
pub dock_v2: bool,
}
impl Default for WidgetPrefs {
@ -120,6 +356,7 @@ impl Default for WidgetPrefs {
remember_collapsed: true,
collapsed: false,
position: None,
dock_v2: true,
}
}
}
@ -188,46 +425,107 @@ fn save_prefs(state: &WidgetState) -> Result<(), String> {
fs::write(path, text).map_err(|error| error.to_string())
}
/// Dock to a screen corner (widget width ~350px) or restore the remembered
/// drag position. Called on creation and whenever the corner changes. All
/// math is in physical pixels — the webview reports `outerPosition` there.
/// Where the widget belongs on a monitor rect `(left, top, right, bottom)`
/// of physical screen pixels — the same space Win32 `GetWindowRect` and the
/// persisted drag position (`outerPosition`, Tauri "physical") live in, so
/// the heartbeat compares like with like. A remembered drag position is
/// clamped onto the monitor (an unplugged-secondary position can not hide
/// it off-screen); otherwise the configured corner + a margin (24 physical
/// px ≈ the old 16 logical px at 150% scale). Pure so the re-dock maths
/// stays testable headless.
fn dock_point(monitor: (i32, i32, i32, i32), size: (i32, i32), prefs: &WidgetPrefs) -> (i32, i32) {
let margin = 24;
let (left, top, right, bottom) = monitor;
if let Some((x, y)) = prefs.position {
(
x.clamp(left, (right - size.0).max(left)),
y.clamp(top, (bottom - size.1).max(top)),
)
} else {
let x = match prefs.corner.as_str() {
"top-left" | "bottom-left" => left + margin,
_ => right - size.0 - margin,
};
let y = match prefs.corner.as_str() {
"bottom-left" | "bottom-right" => bottom - size.1 - margin,
_ => top + margin,
};
(x, y)
}
}
/// Dock to the configured corner or restore the remembered drag position.
/// Called on creation, whenever the corner changes, and whenever the
/// heartbeat sees the window drift off its spot.
///
/// The drift this guards against is what the user hit: an RDP session runs
/// the console at the peer's resolution (e.g. 1920×1080); Windows re-lays
/// out top-level windows there, and any position persisted from that
/// session is a *small-screen* number. Back at the native 2560×1440 the
/// old code still found that number "valid" (it clamps fine) and re-docked
/// to it — the widget parked ~660 px short of the right edge, mid-desktop.
/// Now the guard compares the window's live Win32 rect with what the prefs
/// demand every beat, and pre-0.1.12 remembered spots are dropped once
/// (`dock_v2`) so corner docking becomes deterministic again.
#[cfg(windows)]
fn place_window(app: &AppHandle, prefs: &WidgetPrefs) {
let Some(window) = app.get_webview_window(WIDGET_LABEL) else {
return;
};
let Ok(Some(monitor)) = window
.current_monitor()
.or_else(|_| window.primary_monitor())
else {
let Ok(hwnd) = window.hwnd() else { return };
let raw: *mut std::ffi::c_void = hwnd.0.cast();
let Some(monitor) = desktop_layer::monitor_rect(raw) else {
return;
};
// Work area excludes the macOS menu bar and Dock, so the widget cannot
// park its header under the menu bar or behind the Dock.
let work = monitor.work_area();
let size = desktop_layer::window_rect(raw).map(|(_, _, w, h)| (w, h));
// A just-created window may still report the builder size before the
// content fit lands; dock_point tolerates that (worst case the next
// auto-resize redocks through the same path).
let size = size.unwrap_or((525, 930));
let pos = dock_point(monitor, size, prefs);
desktop_layer::move_to(raw, pos.0, pos.1);
}
/// One-time repair of pre-0.1.12 `position` values: they were persisted
/// while the docking maths (physical px) and the drag readback (DPI-scaled
/// virtual px) disagreed, and an RDP re-layout could even persist a drifted
/// mid-screen spot as if the user had chosen it. Rather than guess, drop the
/// remembered spot once — the widget returns to the configured corner; any
/// drag from now on is persisted in the same physical space this file docks
/// in (the page now sends `outerPosition` through the device scale factor),
/// so it is respected forever.
#[cfg(windows)]
fn migrate_stale_position(state: &WidgetState) -> Result<(), String> {
{
let mut prefs = WidgetState::lock(&state.prefs)?;
if prefs.dock_v2 {
return Ok(());
}
prefs.position = None;
prefs.dock_v2 = true;
}
save_prefs(state)
}
#[cfg(not(windows))]
fn place_window(app: &AppHandle, prefs: &WidgetPrefs) {
let Some(window) = app.get_webview_window(WIDGET_LABEL) else {
return;
};
let Ok(Some(monitor)) = window.primary_monitor() else {
return;
};
let rect = (
0,
0,
monitor.size().width as i32,
monitor.size().height as i32,
);
let outer = window
.outer_size()
.map(|s| (s.width as i32, s.height as i32))
.unwrap_or((350, 620));
let margin = (16.0 * monitor.scale_factor()) as i32;
let min_x = work.position.x;
let min_y = work.position.y;
let max_x = (work.position.x + work.size.width as i32 - outer.0).max(min_x);
let max_y = (work.position.y + work.size.height as i32 - outer.1).max(min_y);
let pos = if let Some((x, y)) = prefs.position {
// Clamp into the monitor so an unplugged-secondary position can not
// hide the widget off-screen.
(x.clamp(min_x, max_x), y.clamp(min_y, max_y))
} else {
let x = match prefs.corner.as_str() {
"top-left" | "bottom-left" => min_x + margin,
_ => max_x - margin,
};
let y = match prefs.corner.as_str() {
"bottom-left" | "bottom-right" => max_y - margin,
_ => min_y + margin,
};
(x.clamp(min_x, max_x), y.clamp(min_y, max_y))
};
let pos = dock_point(rect, outer, prefs);
let _ = window.set_position(tauri::PhysicalPosition::new(pos.0, pos.1));
}
@ -236,7 +534,13 @@ fn place_window(app: &AppHandle, prefs: &WidgetPrefs) {
/// of the z-order (desktop layer), above wallpaper/icons but under every
/// ordinary app window, so it can never cover the user's work.
fn sync_window(app: &AppHandle, prefs: &WidgetPrefs) {
if !prefs.enabled {
if !prefs.enabled
|| !(prefs.panel_run
|| prefs.panel_cpu
|| prefs.panel_network
|| prefs.panel_disk
|| prefs.panel_storage)
{
if let Some(window) = app.get_webview_window(WIDGET_LABEL) {
let _ = window.hide();
}
@ -255,7 +559,7 @@ fn sync_window(app: &AppHandle, prefs: &WidgetPrefs) {
WIDGET_LABEL,
WebviewUrl::App("index.html?view=widget".into()),
)
.title("Squid 实时监控")
.title("Squid 小工具")
.inner_size(350.0, 640.0)
.resizable(false)
.decorations(false)
@ -265,16 +569,6 @@ fn sync_window(app: &AppHandle, prefs: &WidgetPrefs) {
.focused(false)
.visible(false)
.shadow(false);
// macOS: BelowNormal keeps the widget under ordinary app windows, every
// Space keeps it beside the desktop, and a non-key window means clicking
// a card never pulls focus away from the app the user is working in.
// `accept_first_mouse` keeps the first click actionable anyway.
#[cfg(target_os = "macos")]
let builder = builder
.always_on_bottom(true)
.visible_on_all_workspaces(true)
.focusable(false)
.accept_first_mouse(true);
match builder.build() {
Ok(window) => {
let _ = window.set_ignore_cursor_events(false);
@ -292,15 +586,12 @@ fn sync_window(app: &AppHandle, prefs: &WidgetPrefs) {
#[serde(rename_all = "camelCase")]
pub struct WidgetView {
prefs: WidgetPrefs,
language: &'static str,
}
#[tauri::command]
pub fn widget_get(app: AppHandle) -> WidgetView {
let (settings, _) = Settings::load();
WidgetView {
prefs: app.state::<WidgetState>().current(),
language: Locale::detect(&settings).code(),
}
}
@ -411,6 +702,12 @@ pub fn widget_hide(app: AppHandle) -> Result<(), String> {
/// Create the window at startup when enabled; the main page can also open it
/// later through widget_set.
pub fn spawn_startup(app: &AppHandle) {
#[cfg(windows)]
{
// One-time drop of a pre-dock-v2 remembered position (see the field
// docs) before anything docks off it.
let _ = migrate_stale_position(&app.state::<WidgetState>());
}
let prefs = app.state::<WidgetState>().current();
sync_window(app, &prefs);
}
@ -432,7 +729,49 @@ pub fn toggle_from_tray(app: &AppHandle) -> Result<(), String> {
#[cfg(test)]
mod tests {
use super::{WidgetPatch, WidgetPrefs};
use super::{dock_point, WidgetPatch, WidgetPrefs};
#[test]
fn corner_dock_follows_the_screen_size() {
// This is the RDP story in miniature: the same top-right preference
// must land on the corner of whatever screen exists now, never at a
// stale pixel offset from an earlier, smaller session.
let prefs = WidgetPrefs {
corner: "top-right".into(),
..WidgetPrefs::default()
};
let big = dock_point((0, 0, 2560, 1440), (350, 620), &prefs);
assert_eq!(big, (2560 - 350 - 24, 24));
let small = dock_point((0, 0, 1280, 720), (350, 620), &prefs);
assert_eq!(small, (1280 - 350 - 24, 24));
let left = WidgetPrefs {
corner: "bottom-left".into(),
..WidgetPrefs::default()
};
assert_eq!(dock_point((0, 0, 2560, 1440), (350, 620), &left), (24, 796));
// A monitor that is not at the origin (extended desktop with the
// primary on the right) docks to *its own* corners.
let offset = dock_point((1920, 0, 1920 + 2560, 1440), (350, 620), &prefs);
assert_eq!(offset, (1920 + 2560 - 350 - 24, 24));
}
#[test]
fn dragged_position_survives_but_stays_on_screen() {
let prefs = WidgetPrefs {
position: Some((1200, 300)),
..WidgetPrefs::default()
};
assert_eq!(
dock_point((0, 0, 2560, 1440), (350, 620), &prefs),
(1200, 300)
);
// A remembered spot from a bigger unplugged monitor is clamped back
// into the current desktop instead of being lost or hidden.
assert_eq!(
dock_point((0, 0, 1280, 720), (350, 620), &prefs),
(1280 - 350, 720 - 620)
);
}
#[test]
fn prefs_round_trip_uses_camel_case_keys() {
@ -472,7 +811,6 @@ mod tests {
fn legacy_configs_without_new_fields_still_load() {
let prefs: WidgetPrefs = serde_json::from_str("{}").unwrap();
assert!(prefs.enabled);
assert!(prefs.panel_cpu);
assert_eq!(prefs.interval_ms, 2_000);
assert!(prefs.position.is_none());
}

View File

@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Squid",
"version": "0.1.11",
"version": "0.1.13",
"identifier": "app.nex.squid",
"mainBinaryName": "squid-desktop",
"build": {

View File

@ -1,24 +1,22 @@
import {
AppWindow,
Boxes,
ChevronDown,
CircleGauge,
Eraser,
History,
LayoutDashboard,
Power,
MonitorSmartphone,
RefreshCw,
Settings,
ShieldCheck,
Sparkles,
WandSparkles,
Wrench,
} from "lucide-react";
import { useCallback, useEffect, useState, type ReactNode } from "react";
import { useAppsWorkspace } from "./hooks/useAppsWorkspace";
import { usePermissionsWorkspace } from "./hooks/usePermissionsWorkspace";
import { useScanWorkspace } from "./hooks/useScanWorkspace";
import { useSecurityWorkspace } from "./hooks/useSecurityWorkspace";
import { useStartupWorkspace } from "./hooks/useStartupWorkspace";
import { useSystemSnapshot } from "./hooks/useSystemSnapshot";
import { useUpdateFlow } from "./hooks/useUpdateFlow";
import { detectLanguage, I18nProvider, useI18n } from "./i18n";
@ -36,16 +34,15 @@ import { useToast } from "./components/ui";
import { SetupPanel } from "./components/SetupPanel";
import brandMarkUrl from "../src-tauri/icons/brand-mark.svg";
import { ApplicationsPage } from "./pages/ApplicationsPage";
import { CleanupPage } from "./pages/CleanupPage";
import { HistoryPage } from "./pages/HistoryPage";
import { MaintenanceHubPage, type MaintTab } from "./pages/MaintenanceHubPage";
import { OverviewPage } from "./pages/OverviewPage";
import { PermissionsPage } from "./pages/PermissionsPage";
import { PurgePage } from "./pages/PurgePage";
import { SecurityPage } from "./pages/SecurityPage";
import { SettingsPage } from "./pages/SettingsPage";
import { StartupPage } from "./pages/StartupPage";
import { StoragePage } from "./pages/StoragePage";
import { SpaceHubPage, type SpaceTab } from "./pages/SpaceHubPage";
import { SystemPage } from "./pages/SystemPage";
import { WidgetPage } from "./pages/WidgetPage";
const NAV_GROUPS: {
labelEn: string;
@ -63,14 +60,14 @@ const NAV_GROUPS: {
items: [
{
id: "overview",
labelEn: "Overview",
labelZh: "概览",
labelEn: "Computer overview",
labelZh: "电脑概览",
icon: LayoutDashboard,
},
{
id: "cleanup",
labelEn: "Daily cleanup",
labelZh: "日常清理",
id: "space",
labelEn: "Space cleaning",
labelZh: "空间清理",
icon: Eraser,
},
{
@ -80,37 +77,35 @@ const NAV_GROUPS: {
icon: AppWindow,
},
{
id: "purge",
labelEn: "Deep Clean",
labelZh: "深度清理",
icon: WandSparkles,
id: "maintenance",
labelEn: "System maintenance",
labelZh: "系统维护",
icon: Wrench,
},
],
},
{
labelEn: "Protection",
labelZh: "安全",
items: [
{
id: "permissions",
labelEn: "Permissions",
labelZh: "权限管理",
icon: ShieldCheck,
},
],
},
{
labelEn: "Protection",
labelZh: "保护",
items: [
{ id: "security", labelEn: "Security", labelZh: "安全", icon: ShieldCheck },
{ id: "startup", labelEn: "Startup items", labelZh: "启动项", icon: Power },
{
id: "security",
labelEn: "Security scan",
labelZh: "安全扫描",
icon: ShieldCheck,
},
],
},
{
labelEn: "Insights",
labelZh: "洞察",
items: [
{
id: "storage",
labelEn: "Storage",
labelZh: "存储空间",
icon: Boxes,
},
{
id: "system",
labelEn: "Real-time monitor",
@ -119,28 +114,41 @@ const NAV_GROUPS: {
},
],
},
{
labelEn: "Desktop",
labelZh: "桌面",
items: [
{
id: "widget",
labelEn: "Desktop widget",
labelZh: "桌面小工具",
icon: MonitorSmartphone,
},
],
},
];
// Permissions manages Windows Run keys, shell extensions and popup rules; the
// macOS equivalent is the Startup page, which reads LaunchAgents and login items.
function navItemVisible(id: PageId, platform: string | undefined): boolean {
return id !== "permissions" || platform === "windows";
}
const PAGE_TITLES: Record<PageId, [string, string]> = {
overview: ["Overview", "概览"],
cleanup: ["Daily cleanup", "日常清理"],
overview: ["Computer overview", "电脑概览"],
space: ["Space cleaning", "空间清理"],
applications: ["Uninstall apps", "应用卸载"],
purge: ["Deep Clean", "深度清理"],
permissions: ["Permissions", "权限管理"],
storage: ["Storage", "存储空间"],
security: ["Security scan", "安全扫描"],
widget: ["Desktop widget", "桌面小工具"],
maintenance: ["System maintenance", "系统维护"],
system: ["Real-time monitor", "实时监控"],
security: ["Security", "安全"],
startup: ["Startup items", "启动项"],
history: ["History", "历史记录"],
settings: ["Settings", "设置"],
};
/** Pages that no longer exist still arrive from old tray/notification payloads. */
const LEGACY_PAGES: Record<string, PageId> = {
cleanup: "space",
purge: "space",
storage: "space",
startup: "permissions",
};
function BrandMark({ small = false }: { small?: boolean }) {
return (
<img
@ -183,6 +191,21 @@ function BootstrapError({ message }: { message: string }) {
);
}
const SPACE_OPTIONAL_CATEGORIES = [
"update-installers",
"project-artifacts",
"developer",
];
/** 空间清理 defaults: daily groups pre-checked, opt-in groups untouched.
* AI is the exception that proves the rule — its caches come pre-checked
* from the backend, its models never do, so the item's own `selected`
* flag speaks there. */
function spaceDefaults(item: { category: string; selected: boolean }): boolean {
if (item.category === "ai-tools") return item.selected;
return !SPACE_OPTIONAL_CATEGORIES.includes(item.category);
}
export default function App() {
const { push } = useToast();
const [bootstrap, setBootstrap] = useState<Bootstrap | null>(null);
@ -194,26 +217,24 @@ export default function App() {
const [setupOpen, setSetupOpen] = useState(false);
// The 托盘驻留 case: a hidden main window must stop sampling the machine.
const [windowVisible, setWindowVisible] = useState(true);
const cleanup = useScanWorkspace("cleanup");
const purge = useScanWorkspace("purge");
// Hub deep-links: the overview quick-cards and tray can request a specific
// tab; the selection resets on every navigate so a later click re-arms it.
const [spaceTab, setSpaceTab] = useState<SpaceTab>("junk");
const [maintTab, setMaintTab] = useState<MaintTab>("repair");
const [autostart, setAutostart] = useState(false);
// A process row can ask "where did this come from"; the monitor opens the
// process tab already filtered to that path.
const [processFilter] = useState<string | null>(null);
const cleanup = useScanWorkspace("cleanup", spaceDefaults);
const purge = useScanWorkspace("purge", spaceDefaults);
const apps = useAppsWorkspace();
const permissions = usePermissionsWorkspace(page === "permissions");
const security = useSecurityWorkspace(true);
const systemActive = (page === "overview" || page === "system") && windowVisible;
// Only the 实时监控 top-process table needs the expensive per-pid walk;
// the overview tiles ride the light refresh.
const system = useSystemSnapshot(systemActive, 1800, page === "system");
const update = useUpdateFlow(bootstrap?.updateFeedUrl ?? "", autoCheck);
// One security state for the whole window: the overview strip, the sidebar
// badge and the security page all read this, so they cannot disagree.
const security = useSecurityWorkspace(true);
const startup = useStartupWorkspace(page === "startup");
// A process row can ask "where did this come from", and a startup entry can ask
// "is it running". Both hand the other page a path rather than duplicating data.
const [processFilter, setProcessFilter] = useState<string | null>(null);
// A path handed from the process table to the startup page, where it becomes a
// search rather than a second data load.
const [startupQuery, setStartupQuery] = useState<string | null>(null);
const [autostart, setAutostart] = useState(false);
useEffect(() => {
let cancelled = false;
@ -226,8 +247,6 @@ export default function App() {
setLang(next.language);
setAutoCheck(next.updateCheckEnabled);
setSetupOpen(!next.settings.setupReviewed);
// The readiness card reports whether Squid starts at login, and that is a
// fact about the system rather than about settings, so it is asked for.
void api
.autostartStatus()
.then(setAutostart)
@ -262,11 +281,11 @@ export default function App() {
/**
* A notification click goes to the findings, and brings the window back.
*
* Findings are the only thing squid notifies about, so the tap needs no
* destination in its payload. The backend is asked as well because closing the
* window only hides it: the webview is gone, so nothing on this side can undo
* the hide, and a click that appeared to do nothing would look like a bug in the
* security feature rather than in window management.
* Findings are the only thing Squid notifies about, so the tap needs no
* destination in its payload. The backend is asked as well because closing
* the window only hides it: the webview is gone, so nothing on this side can
* undo the hide, and a click that appeared to do nothing would look like a
* bug in the security feature rather than in window management.
*/
useEffect(() => {
let cancelled = false;
@ -275,9 +294,6 @@ export default function App() {
.then(({ onAction }) =>
onAction(() => {
if (cancelled) return;
// The backend's reply arrives as the same navigate event the tray menu
// uses, which also shows the hidden window. Asking first and navigating
// here as well would race the two against each other.
void api.securityOpen().catch(() => undefined);
void security.refresh();
}),
@ -286,8 +302,6 @@ export default function App() {
if (cancelled) void listener.unregister();
else stop = listener;
})
// No plugin, or notifications switched off: the tray line and the in-app
// banner still report the same finding, so this is silence, not failure.
.catch(() => undefined);
return () => {
cancelled = true;
@ -295,20 +309,17 @@ export default function App() {
};
}, [security]);
const inspectProcess = useCallback((path: string) => {
setProcessFilter(path);
setPage("system");
}, []);
useEffect(() => {
let cancelled = false;
let unlisten: (() => void) | null = null;
void api
.onNavigate((next) => {
if (!cancelled) setPage(next);
// A tray or notification jump into Security must show current numbers,
// not the ones from whenever the window last asked.
if (next === "security") void security.refresh();
if (cancelled) return;
const target = LEGACY_PAGES[next] ?? next;
setPage(target);
if (target === "space") setSpaceTab("junk");
if (target === "maintenance") setMaintTab("repair");
if (target === "security") void security.refresh();
})
.then((stop) => {
if (cancelled) stop();
@ -321,22 +332,25 @@ export default function App() {
}, [security]);
useEffect(() => {
const order: PageId[] = ([
const order: PageId[] = [
"overview",
"cleanup",
"space",
"applications",
"purge",
"permissions",
"storage",
"system",
"security",
"startup",
] as PageId[]).filter(
(id) => id !== "permissions" || bootstrap?.platform === "windows",
);
// Ctrl/Cmd+1..9 follow the sidebar.
"maintenance",
"system",
"widget",
"history",
];
// Ctrl/Cmd+1..9 follow the sidebar; 0 opens settings.
const onKey = (event: KeyboardEvent) => {
if (!(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey) return;
if (event.key === "0") {
event.preventDefault();
setPage("settings");
return;
}
const index = Number(event.key) - 1;
if (!Number.isInteger(index) || index < 0 || index >= order.length) return;
event.preventDefault();
@ -344,7 +358,7 @@ export default function App() {
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [bootstrap?.platform]);
}, []);
const changeLanguage = useCallback(
async (nextLanguage: Language) => {
@ -352,7 +366,8 @@ export default function App() {
const next = await api.settingsSave({ language: nextLanguage });
setSettings(next);
setLang(next.effectiveLanguage);
document.documentElement.lang = next.effectiveLanguage === "zh" ? "zh-CN" : "en";
document.documentElement.lang =
next.effectiveLanguage === "zh" ? "zh-CN" : "en";
} catch (reason) {
push(messageFrom(reason), "danger");
}
@ -363,12 +378,10 @@ export default function App() {
const changeAutoCheck = useCallback(
(enabled: boolean) => {
setAutoCheck(enabled);
void api
.setUpdateCheckEnabled(enabled)
.catch((reason) => {
setAutoCheck(!enabled);
push(messageFrom(reason), "danger");
});
void api.setUpdateCheckEnabled(enabled).catch((reason) => {
setAutoCheck(!enabled);
push(messageFrom(reason), "danger");
});
},
[push],
);
@ -406,41 +419,33 @@ export default function App() {
bootstrap={bootstrap}
snapshot={system.snapshot}
cleanup={cleanup}
purge={purge}
onNavigate={setPage}
onOpenSpaceTab={(tab) => {
setSpaceTab(tab);
setPage("space");
}}
/>
) : null}
{page === "cleanup" ? (
<CleanupPage
workspace={cleanup}
{page === "space" ? (
<SpaceHubPage
cleanup={cleanup}
purge={purge}
bootstrap={bootstrap}
deleteMode={deleteMode}
onHistory={() => setPage("history")}
initialTab={spaceTab}
/>
) : null}
{page === "applications" ? (
<ApplicationsPage workspace={apps} onHistory={() => setPage("history")} />
) : null}
{page === "purge" ? (
<PurgePage
workspace={purge}
bootstrap={bootstrap}
deleteMode={deleteMode}
onHistory={() => setPage("history")}
/>
) : null}
{page === "permissions" ? <PermissionsPage workspace={permissions} /> : null}
{page === "storage" ? <StoragePage bootstrap={bootstrap} /> : null}
{page === "security" ? (
<SecurityPage security={security} onOpenStartup={() => setPage("startup")} />
) : null}
{page === "startup" ? (
<StartupPage
startup={startup}
security={security}
initialQuery={startupQuery}
onInspectProcess={inspectProcess}
onShowSecurity={() => setPage("security")}
/>
<SecurityPage security={security} onOpenStartup={() => setPage("permissions")} />
) : null}
{page === "widget" ? <WidgetPage /> : null}
{page === "maintenance" ? <MaintenanceHubPage initialTab={maintTab} /> : null}
{page === "system" ? (
<SystemPage
snapshot={system.snapshot}
@ -449,10 +454,7 @@ export default function App() {
refresh={system.refresh}
initialProcessFilter={processFilter}
security={security}
onOpenStartup={(query) => {
setStartupQuery(query);
setPage("startup");
}}
onOpenStartup={() => setPage("permissions")}
/>
) : null}
{page === "history" ? <HistoryPage /> : null}
@ -511,11 +513,7 @@ function AppChrome({
const title = PAGE_TITLES[page][lang === "zh" ? 1 : 0];
return (
<div
className="app"
data-platform={bootstrap.platform}
data-page={page}
>
<div className="app" data-platform={bootstrap.platform} data-page={page}>
<aside className="sidebar">
<div className="sidebar-drag" data-tauri-drag-region />
<div className="sidebar-brand">
@ -532,9 +530,7 @@ function AppChrome({
<span className="nav-group-label">
{lang === "zh" ? group.labelZh : group.labelEn}
</span>
{group.items
.filter((item) => navItemVisible(item.id, bootstrap.platform))
.map((item) => {
{group.items.map((item) => {
const Icon = item.icon;
return (
<button
@ -545,8 +541,10 @@ function AppChrome({
>
<Icon size={18} />
<span>{lang === "zh" ? item.labelZh : item.labelEn}</span>
{item.id === "security" && security ? securityBadge(security, page) : null}
{item.id === "cleanup" && page !== "cleanup" ? (
{item.id === "security" && security
? securityBadge(security, page)
: null}
{item.id === "space" && page !== "space" ? (
<i className="nav-dot" />
) : null}
</button>

View File

@ -0,0 +1,276 @@
import { AlertTriangle, Check, LoaderCircle } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useI18n } from "../i18n";
import { formatBytes, formatCount } from "../lib/format";
import { skipGroupOf, skipTally, formatDuration } from "../lib/skipGroups";
import { Button } from "./ui";
import type { DeleteResult, JobProgress } from "../types";
/**
* The one clean-progress language every page speaks (垃圾清理 / 重复文件 /
* 大文件): the confirm strip morphs in place into an honest per-file
* progress bar, then settles into a green (or amber when items stayed
* behind) result banner that fades itself after 5 seconds. After 10 seconds
* of work a「转入后台」link shrinks the bar into a corner capsule so the
* page stays usable — there is deliberately no mid-delete cancel.
*/
export interface CleanPhase {
phase: "busy" | "done";
/** Final outcome; required (and rendered) once phase === "done". */
outcome?: DeleteResult | null;
/** Wall-clock delete duration measured by the page. */
elapsedMs?: number;
}
const DISMISS_SECONDS = 5;
const BACKDROP_SECONDS = 10;
export function CleanBar({
spec,
progress,
noun,
mode,
onHistory,
onDismiss,
onRescan,
auto = true,
showSkips = true,
}: {
spec: CleanPhase;
/** Live job events (tick carries done/total, deleted carries freed). */
progress: JobProgress | null;
/** Noun the counted items are called, e.g. 副本 / 项 / 大文件. */
noun: [string, string];
mode: "trash" | "permanent";
onHistory: () => void;
onDismiss: () => void;
/** Offered on the amber banner's reason groups when a rescan helps. */
onRescan?: () => void;
/** false = a sticky result screen: no countdown, 知道了 dismisses. */
auto?: boolean;
/** false = the page renders the skipped-reason groups itself below. */
showSkips?: boolean;
}) {
const { t, lang } = useI18n();
const zh = lang === "zh";
const unit = zh ? noun[0] : noun[1];
const binWord = mode === "trash" ? t("to the Recycle Bin", "移入回收站") : t("deleted for good", "彻底删除");
// Honest cumulative state across the event stream: keep the last known
// done/total (ticks), sum freed over unique deleted paths (two engine
// halves can stream in sequence; paths dedupe the pair).
const freedPaths = useRef<Map<string, number>>(new Map());
const lastTick = useRef<{ done: number; total: number } | null>(null);
const [mirror, setMirror] = useState<{ done: number; total: number; freed: number }>({
done: 0,
total: 0,
freed: 0,
});
const [elapsed, setElapsed] = useState(0);
const resetRun = useCallback(() => {
freedPaths.current = new Map();
lastTick.current = null;
setMirror({ done: 0, total: 0, freed: 0 });
setElapsed(0);
}, []);
useEffect(() => {
if (spec.phase !== "busy") return;
if (!progress) return;
if (progress.event === "deleted") {
const path = progress.detail ?? "";
if (path && !freedPaths.current.has(path)) {
freedPaths.current.set(path, progress.freed ?? 0);
}
let freed = 0;
freedPaths.current.forEach((value) => (freed += value));
setMirror((current) => ({ ...current, freed }));
return;
}
if (progress.event === "tick" && progress.done !== null && progress.total !== null) {
lastTick.current = { done: progress.done, total: progress.total };
setMirror((current) => ({ ...current, ...lastTick.current }));
}
}, [progress, spec.phase]);
const [minimized, setMinimized] = useState(false);
const [skipsOpen, setSkipsOpen] = useState(false);
const [secondsLeft, setSecondsLeft] = useState(DISMISS_SECONDS);
const dismiss = useRef(onDismiss);
dismiss.current = onDismiss;
// Busy clock: powers the 转入后台 threshold and a live elapsed feel.
useEffect(() => {
if (spec.phase !== "busy") return;
resetRun();
const started = Date.now();
const timer = window.setInterval(() => setElapsed(Date.now() - started), 1000);
return () => window.clearInterval(timer);
}, [spec.phase, resetRun]);
// Done banner: countdown to self-dismiss (sticky result screens opt out).
useEffect(() => {
if (spec.phase !== "done") return;
if (!auto) return;
setSecondsLeft(DISMISS_SECONDS);
const timer = window.setInterval(() => {
setSecondsLeft((current) => {
if (current <= 1) {
window.clearInterval(timer);
dismiss.current();
return 0;
}
return current - 1;
});
}, 1000);
return () => window.clearInterval(timer);
}, [spec.phase, auto]);
const pct =
spec.phase === "busy" && mirror.total > 0
? Math.min(100, Math.round((mirror.done / mirror.total) * 100))
: null;
const skipped = spec.outcome?.skipped ?? [];
const groups = useMemo(() => {
const map = new Map<
string,
{
title: [string, string];
hint: [string, string];
action?: "rescan";
rows: { path: string; reason: string }[];
}
>();
for (const row of skipped) {
const meta = skipGroupOf(row.reason);
const bucket =
map.get(meta.key) ?? { title: meta.title, hint: meta.hint, action: meta.action, rows: [] };
bucket.rows.push(row);
map.set(meta.key, bucket);
}
return [...map.values()];
}, [skipped]);
if (spec.phase === "busy") {
if (minimized) {
return (
<button
type="button"
className="cleanbar-capsule"
onClick={() => setMinimized(false)}
title={t("Back to the clean progress", "回到清理进度")}
>
<LoaderCircle size={13} className="spin" />
{t(`Cleaning ${formatCount(mirror.done)}/${formatCount(mirror.total)}`, `清理中 ${formatCount(mirror.done)}/${formatCount(mirror.total)}`)}
</button>
);
}
return (
<section className="cleanbar is-busy" role="status">
<div className="cleanbar-row">
<LoaderCircle size={17} className="spin is-primary" />
<div className="cleanbar-main">
<b>
{t(`Cleaning ${formatCount(mirror.done)} / ${formatCount(mirror.total)} ${unit}`, `正在清理 ${formatCount(mirror.done)} / ${formatCount(mirror.total)} ${unit}`)}
{" · "}
{t(`${formatBytes(mirror.freed)} freed so far`, `已释放 ${formatBytes(mirror.freed)}`)}
</b>
<small className="cleanbar-current">
{progress?.subject
? `${t("Current", "当前")}:${progress.subject}(${binWord})`
: t("Preparing…", "准备中…")}
</small>
</div>
{pct !== null ? <span className="cleanbar-pct">{pct}%</span> : null}
{elapsed >= BACKDROP_SECONDS * 1000 ? (
<button type="button" className="cleanbar-back" onClick={() => setMinimized(true)}>
{t("Move to background", "转入后台")}
</button>
) : null}
</div>
<div className="cleanbar-track" role="progressbar" aria-valuenow={pct ?? undefined} aria-valuemin={0} aria-valuemax={100}>
<span className={pct === null ? "is-indeterminate" : ""} style={pct === null ? undefined : { width: `${pct}%` }} />
</div>
</section>
);
}
const outcome = spec.outcome;
if (!outcome) return null;
const partial = skipped.length > 0;
const freed = outcome.freedAllocated || outcome.freed;
return (
<section className={`cleanbar ${partial ? "is-partial" : "is-done"}`} role="status">
<div className="cleanbar-row">
<span className={`cleanbar-mark ${partial ? "is-warn" : "is-ok"}`}>
{partial ? <AlertTriangle size={14} /> : <Check size={15} />}
</span>
<div className="cleanbar-main">
<b>
{partial
? t(
`Cleaned ${formatCount(outcome.removed)} ${unit} · ${formatBytes(freed)} freed · ${formatCount(skipped.length)} left behind`,
`已清理 ${formatCount(outcome.removed)} ${unit} · 释放 ${formatBytes(freed)} · ${formatCount(skipped.length)} 个未处理`,
)
: t(
`Clean finished · ${formatCount(outcome.removed)} ${unit} ${binWord} · ${formatBytes(freed)} freed`,
`清理完成 · ${formatCount(outcome.removed)} ${unit}${binWord} · 释放 ${formatBytes(freed)}`,
)}
</b>
<small>
{partial ? skipTally(skipped) : ""}
{partial && spec.elapsedMs ? " · " : ""}
{spec.elapsedMs ? t(`took ${formatDuration(spec.elapsedMs)} · undo from History`, `用时 ${formatDuration(spec.elapsedMs)} · 可从「历史」撤销`) : t("undo from History", "可从「历史」撤销")}
</small>
</div>
{partial && showSkips ? (
<Button variant="ghost" size="sm" onClick={() => setSkipsOpen((v) => !v)}>
{skipsOpen ? t("Hide reasons", "收起原因") : t("Why & what next", "查看原因并处理")}
</Button>
) : null}
<Button variant="ghost" size="sm" onClick={onHistory}>
{t("Open history", "查看历史")}
</Button>
<Button size="sm" onClick={onDismiss}>
{auto
? t(`Got it (${secondsLeft}s)`, `知道了(${secondsLeft}s)`)
: t("Got it", "知道了")}
</Button>
</div>
{showSkips && partial && skipsOpen ? (
<div className="cleanbar-skips">
{groups.map((group) => (
<div className="result-skip-group" key={group.title[0]}>
<div className="result-skip-title">
<strong>{zh ? group.title[1] : group.title[0]}</strong>
<span>{group.rows.length}</span>
</div>
<ul>
{group.rows.slice(0, 5).map((row) => (
<li key={row.path} title={row.reason}>
<code>{row.path}</code>
<small>{row.reason}</small>
</li>
))}
{group.rows.length > 5 ? (
<li className="more">
{t(`… ${group.rows.length - 5} more`, `… 另有 ${group.rows.length - 5} 项`)}
</li>
) : null}
</ul>
<small className="result-skip-hint">{zh ? group.hint[1] : group.hint[0]}</small>
{group.action === "rescan" && onRescan ? (
<Button size="sm" variant="secondary" onClick={onRescan}>
{t("Rescan", "重新扫描")}
</Button>
) : null}
</div>
))}
</div>
) : null}
</section>
);
}

View File

@ -1,33 +1,6 @@
import {
ArrowUpRight,
DownloadCloud,
FolderOpen,
LockKeyhole,
RotateCcw,
ShieldCheck,
Trash2,
} from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { useI18n } from "../i18n";
import { api } from "../lib/api";
import { formatBytes, formatCount, shortPath } from "../lib/format";
import type { Category, CleanupItem, DeleteMode, ScanResult } from "../types";
import type { ScanWorkspace } from "../hooks/useScanWorkspace";
import {
Button,
CATEGORY_META,
CATEGORY_ORDER,
CategoryCard,
Checkbox,
ConfirmDialog,
InlineError,
ProgressCard,
ResultSummary,
SectionTitle,
categoryLabel,
lockLabel,
useToast,
} from "./ui";
import { useMemo } from "react";
import type { Category, ScanResult } from "../types";
import { CATEGORY_ORDER, CategoryCard } from "./ui";
type CategoryGroup = { total: number; count: number; items: number[]; selected: number };
@ -49,6 +22,7 @@ function grouped(result: ScanResult) {
return groups;
}
/* Overview 页的分类速览:紧凑卡片一排,点击跳转空间清理页。 */
export function CategorySummary({
result,
selected,
@ -83,373 +57,3 @@ export function CategorySummary({
</div>
);
}
function ItemRow({
item,
checked,
onToggle,
}: {
item: CleanupItem;
checked: boolean;
onToggle: () => void;
}) {
const { lang, t, bin } = useI18n();
const Icon = CATEGORY_META[item.category].icon;
return (
<div
className={`cleanup-row ${item.lock ? "is-locked" : ""} ${
checked ? "is-selected" : ""
}`}
onClick={item.lock ? undefined : onToggle}
>
<Checkbox
checked={checked}
disabled={Boolean(item.lock)}
onChange={onToggle}
label={item.label}
/>
<span className={`row-icon tone-${CATEGORY_META[item.category].tone}`}>
<Icon size={17} />
</span>
<span className="cleanup-row-copy">
<span className="cleanup-row-title">
<strong>{item.label}</strong>
<span className="row-category">{categoryLabel(item.category, lang, bin)}</span>
</span>
<span className="cleanup-row-path" title={item.displayPath}>
{shortPath(item.displayPath, 90)}
</span>
{item.lock || item.note ? (
<span className={`cleanup-row-note ${item.lock ? "is-locked" : ""}`}>
{item.lock ? <LockKeyhole size={12} /> : null}
{item.lock ? lockLabel(item.lock, t) : item.note}
</span>
) : null}
</span>
<span className="cleanup-row-size">{formatBytes(item.onDisk)}</span>
<button
className="row-reveal"
title={t("Show in Finder", "在访达中显示")}
aria-label={t("Show in Finder", "Show in Finder")}
onClick={(event) => {
event.stopPropagation();
void api.revealPath(item.path).catch(() => undefined);
}}
>
<ArrowUpRight size={15} />
</button>
</div>
);
}
export function CleanupInventory({
workspace,
defaultMode,
onHistory,
}: {
workspace: ScanWorkspace;
defaultMode: DeleteMode;
onHistory: () => void;
}) {
const { t, lang, bin } = useI18n();
const { push } = useToast();
const [focus, setFocus] = useState<Category | null>(null);
const [confirming, setConfirming] = useState(false);
const [mode, setMode] = useState<DeleteMode>(defaultMode);
useEffect(() => setMode(defaultMode), [defaultMode]);
const result = workspace.result;
const groups = useMemo(
() => (result ? grouped(result) : new Map<Category, CategoryGroup>()),
[result],
);
const visibleItems = useMemo(() => {
if (!result) return [];
return result.items
.map((item, index) => ({ item, index }))
.filter(({ item }) => !focus || item.category === focus);
}, [focus, result]);
const removables = result?.items.filter((item) => !item.lock).length ?? 0;
// 升级安装包:selection may include stale update packages; the confirm
// dialog offers a one-click "delete everything else, keep these" escape.
const selectedUpdaters = useMemo(() => {
if (!result) return { indexes: [] as number[], total: 0 };
let total = 0;
const indexes: number[] = [];
result.items.forEach((item, index) => {
if (item.category === "update-installers" && workspace.selected.has(index)) {
indexes.push(index);
total += item.onDisk;
}
});
return { indexes, total };
}, [result, workspace.selected]);
if (workspace.scanning) {
return (
<ProgressCard
progress={workspace.progress}
title={t("Scanning your computer safely…", "正在安全扫描您的电脑…")}
onCancel={() => void workspace.cancel()}
/>
);
}
if (workspace.summary) {
return (
<ResultSummary
removed={workspace.summary.removed}
freed={workspace.summary.freedAllocated || workspace.summary.freed}
failed={workspace.summary.failed}
mode={workspace.summary.mode}
onAgain={() => void workspace.runScan()}
onHistory={onHistory}
/>
);
}
if (!result) return null;
const confirm = async (indexes?: number[]) => {
const summary = await workspace.clean(mode, indexes);
setConfirming(false);
if (summary) {
push(
t(
`${formatBytes(summary.freedAllocated || summary.freed)} cleaned`,
`已清理 ${formatBytes(summary.freedAllocated || summary.freed)}`,
),
"success",
);
}
};
return (
<>
<div className="scan-result-hero">
<div>
<span className="result-kicker">
<ShieldCheck size={14} />
{t("Scan complete", "扫描完成")}
</span>
<h2>
{formatBytes(workspace.selectedTotal)}
<small>{t(" ready to clean", " 可安全清理")}</small>
</h2>
<p>
{t(
`${formatCount(workspace.selectedCount)} of ${formatCount(
removables,
)} available items selected`,
`已选择 ${formatCount(workspace.selectedCount)} / ${formatCount(
removables,
)} 个可清理项目`,
)}
{result.unreadable > 0
? t(
` · ${formatCount(result.unreadable)} could not be read`,
` · ${formatCount(result.unreadable)} 项无法读取`,
)
: ""}
</p>
</div>
<div className="scan-result-actions">
<Button
variant="ghost"
onClick={workspace.clearSelection}
disabled={workspace.selectedCount === 0}
>
{t("Deselect all", "取消全选")}
</Button>
<Button
variant="primary"
icon={<Trash2 size={16} />}
disabled={workspace.selectedCount === 0}
onClick={() => setConfirming(true)}
>
{t("Review & clean", "检查并清理")}
</Button>
</div>
</div>
{workspace.error ? (
<InlineError message={workspace.error} onDismiss={workspace.clearError} />
) : null}
<div className="category-grid">
{CATEGORY_ORDER.filter((category) => groups.has(category)).map((category) => {
const group = groups.get(category);
if (!group) return null;
const indexes = group.items.filter((index) => !result.items[index].lock);
const allSelected =
indexes.length > 0 && indexes.every((index) => workspace.selected.has(index));
return (
<CategoryCard
key={category}
category={category}
total={group.total}
count={group.count}
selected={allSelected}
focused={focus === category}
disabled={indexes.length === 0}
onToggle={() => workspace.toggleCategory(category)}
onInspect={() => setFocus(focus === category ? null : category)}
/>
);
})}
</div>
<section className="cleanup-list-panel">
<SectionTitle
title={
focus
? categoryLabel(focus, lang, bin)
: t("Everything found in this scan", "本次扫描的全部项目")
}
action={
focus ? (
<Button variant="ghost" size="sm" onClick={() => setFocus(null)}>
{t("Show all", "显示全部")}
</Button>
) : (
<Button variant="ghost" size="sm" onClick={workspace.selectAll}>
{workspace.selectedCount === removables
? t("Deselect all", "取消全选")
: t("Select all", "全部选择")}
</Button>
)
}
/>
<div className="cleanup-rows">
{visibleItems.map(({ item, index }) => (
<ItemRow
key={`${item.path}-${index}`}
item={item}
checked={workspace.selected.has(index)}
onToggle={() => workspace.toggleItem(index)}
/>
))}
</div>
</section>
<div className="floating-action">
<div>
<span>{t("Selected for cleanup", "已选择清理")}</span>
<strong>{formatBytes(workspace.selectedTotal)}</strong>
</div>
<div className="floating-actions">
<Button
variant="ghost"
size="sm"
icon={<FolderOpen size={15} />}
onClick={() => void api.openTrash().catch(() => undefined)}
>
{bin}
</Button>
<Button
variant="primary"
icon={<Trash2 size={15} />}
disabled={workspace.selectedCount === 0}
onClick={() => setConfirming(true)}
>
{t("Clean now", "立即清理")}
</Button>
</div>
</div>
<ConfirmDialog
open={confirming}
title={t("Ready to make room?", "准备释放空间?")}
message={
<span>
{t(
`${formatCount(workspace.selectedCount)} items · ${formatBytes(
workspace.selectedTotal,
)}`,
`${formatCount(workspace.selectedCount)} 项 · ${formatBytes(
workspace.selectedTotal,
)}`,
)}
</span>
}
note={
mode === "trash"
? t(
`Items will move to the ${bin}. You can restore them from History.`,
`文件将移入${bin},之后可从历史记录中还原。`,
)
: t(
"Permanent removal cannot be undone.",
"永久删除无法撤销。",
)
}
confirmLabel={
mode === "trash"
? t(`Move to ${bin}`, `移入${bin}`)
: t("Remove permanently", "永久删除")
}
cancelLabel={t("Keep files", "保留文件")}
onConfirm={() => void confirm()}
onClose={() => setConfirming(false)}
busy={workspace.deleting}
icon={<RotateCcw size={23} />}
>
<div className="mode-picker">
<button
className={mode === "trash" ? "is-active" : ""}
onClick={() => setMode("trash")}
>
<FolderOpen size={17} />
<span>{bin}</span>
</button>
<button
className={mode === "permanent" ? "is-active" : ""}
onClick={() => setMode("permanent")}
>
<Trash2 size={17} />
<span>{t("Permanent", "永久")}</span>
</button>
</div>
{selectedUpdaters.indexes.length > 0 ? (
<div className="confirm-updater-banner">
<DownloadCloud size={18} />
<div>
<strong>
{t(
`Includes ${formatCount(selectedUpdaters.indexes.length)} update installers (${formatBytes(selectedUpdaters.total)})`,
`其中包含 ${formatCount(selectedUpdaters.indexes.length)} 个升级安装包(${formatBytes(selectedUpdaters.total)})`,
)}
</strong>
<span>
{t(
"Apps re-download them when needed. Delete them too?",
"应用需要时会自动重新下载。要一并清理吗?",
)}
</span>
</div>
<Button
variant="ghost"
size="sm"
disabled={workspace.deleting}
onClick={() => {
const keep = [...workspace.selected].filter(
(index) => !selectedUpdaters.indexes.includes(index),
);
if (keep.length === 0) {
workspace.deselect(selectedUpdaters.indexes);
setConfirming(false);
return;
}
void confirm(keep);
}}
>
{t("Skip installers, clean rest", "跳过升级包,只删其余")}
</Button>
</div>
) : null}
</ConfirmDialog>
</>
);
}

View File

@ -2,10 +2,13 @@ import {
AlertTriangle,
AppWindow,
Boxes,
Bot,
Check,
ChevronDown,
Code2,
CopyX,
DownloadCloud,
EyeOff,
FileWarning,
Globe2,
Languages,
@ -36,18 +39,9 @@ export interface CategoryMeta {
blurbEn: string;
blurbZh: string;
icon: typeof Boxes;
tone: Tone;
tone: string;
}
export type Tone =
| "primary"
| "success"
| "warning"
| "danger"
| "neutral"
| "info"
| "violet";
export const CATEGORY_META: Record<Category, CategoryMeta> = {
"system-junk": {
en: "System junk",
@ -55,7 +49,7 @@ export const CATEGORY_META: Record<Category, CategoryMeta> = {
blurbEn: "Temporary files and system scratch data",
blurbZh: "临时文件与系统缓存",
icon: Trash2,
tone: "primary",
tone: "blue",
},
"app-caches": {
en: "App caches",
@ -63,7 +57,7 @@ export const CATEGORY_META: Record<Category, CategoryMeta> = {
blurbEn: "Caches apps can rebuild",
blurbZh: "应用可自动重建的缓存",
icon: AppWindow,
tone: "primary",
tone: "cyan",
},
"browser-caches": {
en: "Browser caches",
@ -71,7 +65,7 @@ export const CATEGORY_META: Record<Category, CategoryMeta> = {
blurbEn: "Web content and offline data",
blurbZh: "网页内容与离线数据",
icon: Globe2,
tone: "primary",
tone: "violet",
},
logs: {
en: "Logs & reports",
@ -79,7 +73,7 @@ export const CATEGORY_META: Record<Category, CategoryMeta> = {
blurbEn: "Rotated logs and crash reports",
blurbZh: "旧日志与崩溃报告",
icon: FileWarning,
tone: "neutral",
tone: "orange",
},
developer: {
en: "Developer files",
@ -87,7 +81,7 @@ export const CATEGORY_META: Record<Category, CategoryMeta> = {
blurbEn: "Simulators, archives and tool caches",
blurbZh: "模拟器、归档与工具缓存",
icon: Code2,
tone: "neutral",
tone: "indigo",
},
"project-artifacts": {
en: "Build artefacts",
@ -95,15 +89,15 @@ export const CATEGORY_META: Record<Category, CategoryMeta> = {
blurbEn: "Regenerable project build folders",
blurbZh: "可重新生成的构建目录",
icon: PackageOpen,
tone: "primary",
tone: "teal",
},
trash: {
en: "Trash",
zh: "废纸篓",
en: "Recycle Bin",
zh: "回收站",
blurbEn: "Files waiting to be emptied",
blurbZh: "等待清空的文件",
icon: Trash2,
tone: "neutral",
tone: "slate",
},
"language-packs": {
en: "Language packs",
@ -111,7 +105,7 @@ export const CATEGORY_META: Record<Category, CategoryMeta> = {
blurbEn: "Unused voice and localisation data",
blurbZh: "未使用的语音与本地化数据",
icon: Languages,
tone: "neutral",
tone: "pink",
},
leftovers: {
en: "Leftovers",
@ -119,7 +113,7 @@ export const CATEGORY_META: Record<Category, CategoryMeta> = {
blurbEn: "Data left by removed applications",
blurbZh: "已删除应用留下的数据",
icon: Puzzle,
tone: "warning",
tone: "amber",
},
"update-installers": {
en: "Update installers",
@ -127,7 +121,31 @@ export const CATEGORY_META: Record<Category, CategoryMeta> = {
blurbEn: "Installer packages apps keep after updating",
blurbZh: "应用升级后留下的安装包,需要时会自动重新下载",
icon: DownloadCloud,
tone: "success",
tone: "green",
},
duplicates: {
en: "Duplicate files",
zh: "重复文件",
blurbEn: "Byte-identical copies confirmed by full hashing",
blurbZh: "全量哈希确认的完全相同文件",
icon: CopyX,
tone: "orange",
},
"ai-tools": {
en: "AI tools & models",
zh: "AI 工具与模型",
blurbEn: "Local models and caches that re-download on demand",
blurbZh: "本地模型与缓存;模型删除后需重新下载",
icon: Bot,
tone: "violet",
},
privacy: {
en: "Privacy traces",
zh: "隐私痕迹",
blurbEn: "History and traces removed without a recycle bin",
blurbZh: "历史与痕迹;删除不进回收站",
icon: EyeOff,
tone: "slate",
},
};
@ -404,11 +422,18 @@ export function ProgressCard({
title,
onCancel,
compact = false,
liveLine,
capAt99 = false,
}: {
progress: JobProgress | null;
title: string;
onCancel?: () => void;
compact?: boolean;
/** "已统计 128,431 文件 · 38.2 GB" streamed side-band (A①). */
liveLine?: string | null;
/** Scans hold the bar at 99% until the final number lands — a full bar
* that is still working reads as a lie (Mole's cap discipline). */
capAt99?: boolean;
}) {
const { t, lang } = useI18n();
const phase = useMemo(() => {
@ -423,6 +448,9 @@ export function ProgressCard({
plan: ["Finding application leftovers", "正在查找应用残留"],
storage: ["Measuring folders", "正在测量文件夹"],
files: ["Finding the largest files", "正在查找大文件"],
bigfiles: ["Scanning every drive for large files", "正在遍历所有磁盘查找大文件"],
duplicates: ["Hashing duplicates (3-stage funnel)", "正在哈希校验重复文件(三级漏斗)"],
maintenance: ["Running the repair commands", "正在执行修复命令"],
orphans: ["Finding unused leftovers", "正在查找孤立残留"],
};
const pair = labels[progress.phase];
@ -431,7 +459,9 @@ export function ProgressCard({
const denominator = progress?.total ?? 0;
const done = progress?.done ?? 0;
const ratio =
denominator > 0 ? Math.min(100, Math.max(0, (done / denominator) * 100)) : null;
denominator > 0
? Math.min(capAt99 ? 99 : 100, Math.max(0, (done / denominator) * 100))
: null;
const detail = progress?.detail || progress?.subject || "";
return (
@ -460,6 +490,11 @@ export function ProgressCard({
>
<span style={{ width: ratio === null ? undefined : `${ratio}%` }} />
</div>
{liveLine ? (
<div className="progress-live" role="status">
{liveLine}
</div>
) : null}
<div className="progress-detail" title={detail}>
{detail || t("Working safely in the background…", "正在后台安全处理…")}
</div>
@ -635,14 +670,25 @@ export function Gauge({
value,
size = 160,
stroke = 12,
tone = "primary",
tone = "blue",
children,
label,
}: {
value: number;
size?: number;
stroke?: number;
tone?: Tone;
tone?:
| "blue"
| "green"
| "orange"
| "violet"
| "red"
| "primary"
| "success"
| "warning"
| "danger"
| "neutral"
| "info";
children?: ReactNode;
label?: string;
}) {
@ -685,10 +731,21 @@ export function Gauge({
export function MetricBar({
value,
tone = "primary",
tone = "blue",
}: {
value: number;
tone?: Tone;
tone?:
| "blue"
| "green"
| "orange"
| "violet"
| "red"
| "primary"
| "success"
| "warning"
| "danger"
| "neutral"
| "info";
}) {
return (
<div className={`metric-bar tone-${tone}`}>
@ -704,18 +761,14 @@ export function EmptyState({
action,
}: {
icon: ReactNode;
title?: string;
title: string;
description?: string;
action?: ReactNode;
}) {
return (
<div className="empty-state">
<div className="empty-icon">{icon}</div>
{title ? (
<h2>{title}</h2>
) : (
<span className="empty-title-spacer" aria-hidden="true" />
)}
<h2>{title}</h2>
{description ? <p>{description}</p> : null}
{action}
</div>
@ -959,11 +1012,22 @@ export function PathRow({
export function UsageBar({
used,
total,
tone = "primary",
tone = "blue",
}: {
used: number;
total: number;
tone?: Tone;
tone?:
| "blue"
| "green"
| "orange"
| "violet"
| "red"
| "primary"
| "success"
| "warning"
| "danger"
| "neutral"
| "info";
}) {
return (
<div className={`usage-bar tone-${tone}`}>

View File

@ -0,0 +1,346 @@
import { useCallback, useRef, useState } from "react";
import { api, subscribeJobProgress } from "../lib/api";
import { messageFrom } from "../lib/format";
import type { DeleteResult, DupsResult, DupGroup, JobProgress } from "../types";
function jobId(): string {
return crypto.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
/** Funnel counters streamed as `funnel:<walked>:<same>:<hits>:<confirmed>`
* notes — the scan tells the UI how much each stage eliminated, live. */
export interface Funnel {
walked: number;
sameSize: number;
sampleHits: number;
confirmed: number;
}
export type KeepStrategy = "shortest" | "oldest";
/** Which copy of a group survives under a strategy. Locked (personal)
* copies are preferred keeps — a WeChat FileStorage copy should never be
* the one an automatic rule picks for deletion. */
export function keepIndexOf(group: DupGroup, strategy: KeepStrategy): number {
let best = 0;
for (let i = 1; i < group.copies.length; i += 1) {
const candidate = group.copies[i];
const current = group.copies[best];
if (candidate.locked && !current.locked) {
best = i;
continue;
}
if (!candidate.locked && current.locked) continue;
if (strategy === "oldest") {
if (candidate.mtimeMs < current.mtimeMs) best = i;
} else if (
candidate.path.length < current.path.length ||
(candidate.path.length === current.path.length && candidate.mtimeMs < current.mtimeMs)
) {
best = i;
}
}
return best;
}
/** Deletion picks per group: group index → copy indexes marked for removal. */
export type Picks = Map<number, Set<number>>;
export function smartPicks(groups: DupGroup[], strategy: KeepStrategy): Picks {
const picks: Picks = new Map();
groups.forEach((group, groupIndex) => {
const keep = keepIndexOf(group, strategy);
const copies = new Set<number>();
group.copies.forEach((copy, copyIndex) => {
if (copyIndex !== keep && !copy.locked) copies.add(copyIndex);
});
if (copies.size > 0) picks.set(groupIndex, copies);
});
return picks;
}
/** Stable signature for a group: ignore decisions survive the final report
* re-sorting the confirmation-order stream. */
export function groupKey(group: DupGroup): string {
return `${group.size}|${group.copies[0]?.path ?? ""}`;
}
export interface DuplicatesWorkspace {
result: DupsResult | null;
/** Visible groups with their backend scan indices (picks/ignore keep both
* layers addressed by the same stable index). */
visible: { group: DupGroup; index: number }[];
funnel: Funnel;
progress: JobProgress | null;
scanning: boolean;
deleting: boolean;
error: string | null;
summary: DeleteResult | null;
picks: Picks;
keepStrategy: KeepStrategy;
/** Group signatures the user dismissed with 「忽略本组」 — filtered from
* the visible list, sums adjust live, backend indices stay stable. */
ignored: Set<string>;
selectedCount: number;
selectedBytes: number;
runScan: (roots: string[], minSize: number | null) => Promise<void>;
cancel: () => Promise<void>;
smartSelect: (strategy?: KeepStrategy) => void;
invertSelection: () => void;
clearPicks: () => void;
toggleCopy: (groupIndex: number, copyIndex: number) => void;
setKeepStrategy: (strategy: KeepStrategy) => void;
removeGroup: (groupIndex: number) => void;
clean: (mode: "trash" | "permanent") => Promise<DeleteResult | null>;
clearError: () => void;
}
export function useDuplicatesWorkspace(): DuplicatesWorkspace {
const [result, setResult] = useState<DupsResult | null>(null);
const [liveGroups, setLiveGroups] = useState<DupGroup[]>([]);
const [funnel, setFunnel] = useState<Funnel>({
walked: 0,
sameSize: 0,
sampleHits: 0,
confirmed: 0,
});
const [progress, setProgress] = useState<JobProgress | null>(null);
const [scanning, setScanning] = useState(false);
const [deleting, setDeleting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [summary, setSummary] = useState<DeleteResult | null>(null);
const [picks, setPicks] = useState<Picks>(new Map());
const [ignored, setIgnored] = useState<Set<string>>(new Set());
const [keepStrategy, setStrategy] = useState<KeepStrategy>("shortest");
const currentJob = useRef<string | null>(null);
const strategyRef = useRef(keepStrategy);
strategyRef.current = keepStrategy;
const runScan = useCallback(
async (roots: string[], minSize: number | null) => {
if (scanning || deleting) return;
const id = jobId();
currentJob.current = id;
setScanning(true);
setError(null);
setSummary(null);
setResult(null);
setProgress(null);
setLiveGroups([]);
setIgnored(new Set());
setFunnel({ walked: 0, sameSize: 0, sampleHits: 0, confirmed: 0 });
setPicks(new Map());
const stop = await subscribeJobProgress(id, (event) => {
if (event.event === "note" && event.detail?.startsWith("funnel:")) {
const [, walked, same, hits, confirmed] = event.detail.split(":");
setFunnel({
walked: Number(walked) || 0,
sameSize: Number(same) || 0,
sampleHits: Number(hits) || 0,
confirmed: Number(confirmed) || 0,
});
return;
}
if (event.event === "group" && event.detail?.startsWith("dup:")) {
try {
const group = JSON.parse(event.detail.slice(4)) as DupGroup;
setLiveGroups((current) =>
[...current, group].sort(
(a, b) => b.size * (b.copies.length - 1) - a.size * (a.copies.length - 1),
),
);
} catch {
/* malformed frame: the final report replaces the stream anyway */
}
return;
}
if (event.event === "metered" && event.done !== null) {
// Stage-1 walk: files streamed; stage-2/3 ticks drive `progress`.
setFunnel((current) => ({ ...current, walked: event.done as number }));
return;
}
setProgress(event);
});
try {
const view = await api.duplicatesScan(id, roots, minSize);
setResult(view);
setLiveGroups(view.report.groups);
setFunnel((current) => ({
walked: view.report.walked || current.walked,
sameSize: view.report.sameSize || current.sameSize,
sampleHits: view.report.sampleHits || current.sampleHits,
confirmed: view.report.confirmedFiles || current.confirmed,
}));
setPicks(smartPicks(view.report.groups, strategyRef.current));
} catch (reason) {
if (!messageFrom(reason).includes("cancel")) setError(messageFrom(reason));
} finally {
stop();
setScanning(false);
currentJob.current = null;
}
},
[deleting, scanning],
);
const cancel = useCallback(async () => {
if (currentJob.current) {
await api.cancelJob(currentJob.current).catch(() => undefined);
}
}, []);
const groups = result?.report.groups ?? liveGroups;
const ignoredRef = useRef(ignored);
ignoredRef.current = ignored;
const smartSelect = useCallback(
(strategy?: KeepStrategy) => {
const fresh = smartPicks(groups, strategy ?? strategyRef.current);
// An ignored group stays ignored: no picks come back for it.
fresh.forEach((_copies, index) => {
const group = groups[index];
if (group && ignoredRef.current.has(groupKey(group))) fresh.delete(index);
});
setPicks(fresh);
},
[groups],
);
const invertSelection = useCallback(() => {
setPicks((current) => {
const next: Picks = new Map();
groups.forEach((group, groupIndex) => {
if (ignoredRef.current.has(groupKey(group))) return;
const keep = keepIndexOf(group, strategyRef.current);
const chosen = current.get(groupIndex) ?? new Set<number>();
const copies = new Set<number>();
group.copies.forEach((copy, copyIndex) => {
if (copyIndex === keep || copy.locked) return;
if (!chosen.has(copyIndex)) copies.add(copyIndex);
});
if (copies.size > 0) next.set(groupIndex, copies);
});
return next;
});
}, [groups]);
const clearPicks = useCallback(() => setPicks(new Map()), []);
const toggleCopy = useCallback((groupIndex: number, copyIndex: number) => {
setPicks((current) => {
const next = new Map(current);
const chosen = new Set(next.get(groupIndex) ?? []);
if (chosen.has(copyIndex)) chosen.delete(copyIndex);
else chosen.add(copyIndex);
if (chosen.size > 0) next.set(groupIndex, chosen);
else next.delete(groupIndex);
return next;
});
}, []);
const setKeepStrategy = useCallback(
(strategy: KeepStrategy) => {
setStrategy(strategy);
smartSelect(strategy);
},
[smartSelect],
);
/** Ignore keeps the group out of the list and out of every sum, but the
* backend scan indices stay untouched — deletion talks in those. */
const removeGroup = useCallback((groupIndex: number) => {
const group = groups[groupIndex];
if (!group) return;
const key = groupKey(group);
setIgnored((current) => new Set(current).add(key));
setPicks((current) => {
const next = new Map(current);
next.delete(groupIndex);
return next;
});
}, [groups]);
/** Visible groups paired with their *backend scan index* so picks and
* deletes never drift after a group is ignored. */
const entries = groups
.map((group, index) => ({ group, index }))
.filter(({ group }) => !ignored.has(groupKey(group)));
const clean = useCallback(
async (mode: "trash" | "permanent") => {
if (!result || deleting) return null;
const selections: [number, number[]][] = [];
picks.forEach((copies, groupIndex) => {
if (groupIndex < result.report.groups.length && copies.size > 0) {
selections.push([groupIndex, [...copies]]);
}
});
if (selections.length === 0) return null;
const id = jobId();
currentJob.current = id;
setDeleting(true);
setError(null);
setProgress(null);
// The delete loop streams the same tick/deleted frames the scan used
// to, so the page's in-place CleanBar can count files honestly.
const stop = await subscribeJobProgress(id, (event) => {
if (event.event === "tick" || event.event === "deleted") setProgress(event);
});
try {
const outcome = await api.duplicatesDelete(id, result.scanId, selections, mode);
setSummary(outcome);
setResult(null);
setLiveGroups([]);
setPicks(new Map());
setIgnored(new Set());
setFunnel({ walked: 0, sameSize: 0, sampleHits: 0, confirmed: 0 });
return outcome;
} catch (reason) {
setError(messageFrom(reason));
return null;
} finally {
stop();
setDeleting(false);
currentJob.current = null;
}
},
[deleting, picks, result],
);
const clearError = useCallback(() => setError(null), []);
let count = 0;
let bytes = 0;
picks.forEach((copies, groupIndex) => {
const group = groups[groupIndex];
if (!group) return;
count += copies.size;
bytes += copies.size * group.size;
});
return {
result,
visible: entries,
funnel,
progress,
scanning,
deleting,
error,
summary,
picks,
keepStrategy,
ignored,
selectedCount: count,
selectedBytes: bytes,
runScan,
cancel,
smartSelect,
invertSelection,
clearPicks,
toggleCopy,
setKeepStrategy,
removeGroup,
clean,
clearError,
};
}

View File

@ -1,15 +1,20 @@
import { useCallback, useEffect, useState } from "react";
import { api } from "../lib/api";
import { isCancelled, messageFrom } from "../lib/format";
import type { ManageView, PopupWindowItem } from "../types";
import { useToast } from "../components/ui";
import type { AdvancedScanResult, ManageView, PopupWindowItem } from "../types";
export type PermissionsTab = "startup" | "extensions" | "popup";
export type PermissionsTab = "startup" | "extensions" | "advanced" | "popup";
export interface PermissionsWorkspace {
tab: PermissionsTab;
setTab: (tab: PermissionsTab) => void;
view: ManageView | null;
windows: PopupWindowItem[];
/** Advanced startup rows; scanned lazily the first time the tab opens —
* the signature batch call is not something the plain page should pay. */
advanced: AdvancedScanResult | null;
advancedScanning: boolean;
scanning: boolean;
busyId: string | null;
error: string | null;
@ -17,8 +22,14 @@ export interface PermissionsWorkspace {
closedTotal: number;
recentClosed: { process: string; title: string }[];
scan: () => Promise<void>;
scanAdvanced: () => Promise<void>;
refreshWindows: () => Promise<void>;
toggleStartup: (id: string, enabled: boolean) => Promise<void>;
/** 电脑管家's master switch: flip every entry of one software group. */
toggleStartupGroup: (ids: string[], enabled: boolean) => Promise<void>;
/** Delete leftover autostart registrations (config only, never files). */
removeStartup: (ids: string[]) => Promise<void>;
toggleAdvanced: (id: string, enabled: boolean) => Promise<void>;
toggleExtension: (id: string, registered: boolean) => Promise<void>;
addRule: (hwnd: number, matcher: "exact" | "contains") => Promise<void>;
toggleRule: (index: number, enabled: boolean) => Promise<void>;
@ -30,12 +41,15 @@ export interface PermissionsWorkspace {
export function usePermissionsWorkspace(active: boolean): PermissionsWorkspace {
const [tab, setTab] = useState<PermissionsTab>("startup");
const [view, setView] = useState<ManageView | null>(null);
const [advanced, setAdvanced] = useState<AdvancedScanResult | null>(null);
const [advancedScanning, setAdvancedScanning] = useState(false);
const [windows, setWindows] = useState<PopupWindowItem[]>([]);
const [scanning, setScanning] = useState(false);
const [busyId, setBusyId] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [closedTotal, setClosedTotal] = useState(0);
const [recentClosed, setRecentClosed] = useState<{ process: string; title: string }[]>([]);
const { push } = useToast();
const scan = useCallback(async () => {
setScanning(true);
@ -60,10 +74,28 @@ export function usePermissionsWorkspace(active: boolean): PermissionsWorkspace {
}
}, []);
const scanAdvanced = useCallback(async () => {
setAdvancedScanning(true);
setError(null);
try {
setAdvanced(await api.advancedScan());
} catch (reason) {
if (!isCancelled(reason)) setError(messageFrom(reason));
} finally {
setAdvancedScanning(false);
}
}, []);
useEffect(() => {
if (active && !view && !scanning) void scan();
}, [active, scan, view, scanning]);
// Lazy first load for the advanced tab: the PowerShell signature batch
// runs once, when the user actually opens that tab.
useEffect(() => {
if (active && tab === "advanced" && !advanced && !advancedScanning) void scanAdvanced();
}, [active, advanced, advancedScanning, scanAdvanced, tab]);
useEffect(() => {
if (!active) return;
let stop: (() => void) | null = null;
@ -98,15 +130,92 @@ export function usePermissionsWorkspace(active: boolean): PermissionsWorkspace {
setBusyId(id);
setError(null);
try {
await api.managedStartupSetEnabled(id, enabled);
await api.startupSetEnabled(id, enabled);
await scan();
} catch (reason) {
setError(messageFrom(reason));
const why = messageFrom(reason);
setError(why);
// The row snaps back without this; a toast right where the user is
// looking explains *why* (cancelled UAC prompt, protected key, …).
push(why, "danger");
} finally {
setBusyId(null);
}
},
[scan],
[push, scan],
);
const toggleStartupGroup = useCallback(
async (ids: string[], enabled: boolean) => {
if (ids.length === 0) return;
setBusyId(ids[0]);
setError(null);
const failures: string[] = [];
try {
for (const id of ids) {
try {
await api.startupSetEnabled(id, enabled);
} catch (reason) {
failures.push(messageFrom(reason));
}
}
await scan();
} finally {
setBusyId(null);
}
if (failures.length > 0) {
setError(failures[0]);
push(failures[0], "danger");
}
},
[push, scan],
);
const removeStartup = useCallback(
async (ids: string[]) => {
if (ids.length === 0) return;
setBusyId(ids[0]);
setError(null);
const failures: string[] = [];
let removed = 0;
try {
for (const id of ids) {
try {
await api.startupRemoveEntry(id);
removed += 1;
} catch (reason) {
failures.push(messageFrom(reason));
}
}
await scan();
} finally {
setBusyId(null);
}
if (removed > 0) push(`已删除 ${removed} 个残留启动项`, "success");
if (failures.length > 0) {
setError(failures[0]);
push(failures[0], "danger");
}
},
[push, scan],
);
const toggleAdvanced = useCallback(
async (id: string, enabled: boolean) => {
setBusyId(id);
setError(null);
try {
await api.advancedSetEnabled(id, enabled);
setAdvanced(await api.advancedScan());
} catch (reason) {
const why = messageFrom(reason);
setError(why);
push(why, "danger");
} finally {
setBusyId(null);
}
},
[push],
);
const toggleExtension = useCallback(
@ -202,6 +311,8 @@ export function usePermissionsWorkspace(active: boolean): PermissionsWorkspace {
setTab,
view,
windows,
advanced,
advancedScanning,
scanning,
busyId,
error,
@ -209,8 +320,12 @@ export function usePermissionsWorkspace(active: boolean): PermissionsWorkspace {
closedTotal,
recentClosed,
scan,
scanAdvanced,
refreshWindows,
toggleStartup,
toggleStartupGroup,
removeStartup,
toggleAdvanced,
toggleExtension,
addRule,
toggleRule,

View File

@ -3,6 +3,7 @@ import { api, subscribeJobProgress } from "../lib/api";
import { isCancelled, messageFrom } from "../lib/format";
import type {
Category,
CleanupItem,
DeleteMode,
DeleteResult,
JobProgress,
@ -15,11 +16,29 @@ function jobId(): string {
export type ScanKind = "cleanup" | "purge";
/** Seed the checkbox state of a fresh result: unlocked items the policy
* keeps win; without a policy the rule metadata (`item.selected`) speaks. */
export function seedSelection(
items: CleanupItem[],
defaultFor?: (item: CleanupItem) => boolean,
): Set<number> {
const picked = new Set<number>();
items.forEach((item, index) => {
if (item.lock) return;
if (defaultFor ? defaultFor(item) : item.selected) picked.add(index);
});
return picked;
}
export interface ScanWorkspace {
kind: ScanKind;
result: ScanResult | null;
selected: Set<number>;
progress: JobProgress | null;
/** Live measurement counters streamed during a scan (A①). */
stats: { files: number; bytes: number } | null;
/** Per-category totals streamed in as each bucket finishes (A②). */
buckets: Partial<Record<Category, { total: number; count: number }>>;
scanning: boolean;
deleting: boolean;
error: string | null;
@ -35,6 +54,8 @@ export interface ScanWorkspace {
cancel: () => Promise<void>;
toggleItem: (index: number) => void;
toggleCategory: (category: Category) => void;
setCategorySelection: (category: Category, on: boolean) => void;
setIndexes: (indexes: number[], on: boolean) => void;
deselect: (indexes: number[]) => void;
selectAll: () => void;
clearSelection: () => void;
@ -43,10 +64,23 @@ export interface ScanWorkspace {
reset: () => void;
}
export function useScanWorkspace(kind: ScanKind): ScanWorkspace {
export function useScanWorkspace(
kind: ScanKind,
/** Overrides the rule metadata's per-item default when a scan lands
* (空间清理 uses this to pre-check every daily group and leave opt-in
* groups untouched). Read through a ref, so a fresh closure per render is
* fine without restarting the hook. */
selectionPolicy?: (item: CleanupItem) => boolean,
): ScanWorkspace {
const policyRef = useRef(selectionPolicy);
policyRef.current = selectionPolicy;
const [result, setResult] = useState<ScanResult | null>(null);
const [selected, setSelected] = useState<Set<number>>(new Set());
const [progress, setProgress] = useState<JobProgress | null>(null);
const [stats, setStats] = useState<{ files: number; bytes: number } | null>(null);
const [buckets, setBuckets] = useState<
Partial<Record<Category, { total: number; count: number }>>
>({});
const [scanning, setScanning] = useState(false);
const [deleting, setDeleting] = useState(false);
const [error, setError] = useState<string | null>(null);
@ -68,7 +102,28 @@ export function useScanWorkspace(kind: ScanKind): ScanWorkspace {
setError(null);
setSummary(null);
setProgress(null);
const stop = await subscribeJobProgress(id, setProgress);
setStats(null);
setBuckets({});
// Streamed side-band (A①②): `metered` carries running counters (kept
// out of `progress`, whose done/total mean "units done / units total"),
// `bucket` one finished category at a time (detail = "cat:count:total").
const stop = await subscribeJobProgress(id, (event) => {
if (event.event === "metered" && event.done !== null && event.total !== null) {
setStats({ files: event.done, bytes: event.total });
return;
}
setProgress(event);
if (event.event === "bucket" && event.detail) {
const [category, count, total] = event.detail.split(":");
setBuckets((current) => ({
...current,
[category as Category]: {
count: Number(count) || 0,
total: Number(total) || 0,
},
}));
}
});
try {
const next =
kind === "cleanup"
@ -81,14 +136,7 @@ export function useScanWorkspace(kind: ScanKind): ScanWorkspace {
);
if (activeJob.current !== id) return;
setResult(next);
setSelected(
new Set(
next.items
.map((item, index) => ({ item, index }))
.filter(({ item }) => item.selected && !item.lock)
.map(({ index }) => index),
),
);
setSelected(seedSelection(next.items, policyRef.current));
} catch (reason) {
if (!isCancelled(reason)) setError(messageFrom(reason));
} finally {
@ -96,6 +144,7 @@ export function useScanWorkspace(kind: ScanKind): ScanWorkspace {
if (activeJob.current === id) {
setScanning(false);
setProgress(null);
setStats(null);
setCurrentJob(null);
}
}
@ -150,6 +199,44 @@ export function useScanWorkspace(kind: ScanKind): ScanWorkspace {
const clearSelection = useCallback(() => setSelected(new Set()), []);
// Deterministic category state: the 空间清理 page uses this to leave the
// optional groups (升级安装包 / 项目产物 / 开发文件) unchecked after a
// scan, wherever the rule defaults happened to point.
const setCategorySelection = useCallback(
(category: Category, on: boolean) => {
if (!result) return;
const indexes = result.items
.map((item, index) => ({ item, index }))
.filter(({ item }) => item.category === category && !item.lock)
.map(({ index }) => index);
if (indexes.length === 0) return;
setSelected((current) => {
const next = new Set(current);
for (const index of indexes) {
if (on) next.add(index);
else next.delete(index);
}
return next;
});
},
[result],
);
// Bulk tick/un-tick an explicit index set — the 空间清理 accordion uses
// this for whole 清理点 (rule clusters), which the category helpers
// cannot express because a cluster is smaller than a category.
const setIndexes = useCallback((indexes: number[], on: boolean) => {
if (indexes.length === 0) return;
setSelected((current) => {
const next = new Set(current);
for (const index of indexes) {
if (on) next.add(index);
else next.delete(index);
}
return next;
});
}, []);
const deselect = useCallback((indexes: number[]) => {
if (indexes.length === 0) return;
const drop = new Set(indexes);
@ -219,6 +306,8 @@ export function useScanWorkspace(kind: ScanKind): ScanWorkspace {
result,
selected,
progress,
stats,
buckets,
scanning,
deleting,
error,
@ -230,6 +319,8 @@ export function useScanWorkspace(kind: ScanKind): ScanWorkspace {
cancel,
toggleItem,
toggleCategory,
setCategorySelection,
setIndexes,
deselect,
selectAll,
clearSelection,

View File

@ -1,65 +0,0 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { api } from "../lib/api";
import { messageFrom } from "../lib/format";
import type { StartupItem, StartupView } from "../types";
export interface StartupWorkspace {
view: StartupView | null;
loading: boolean;
error: string | null;
/** One change at a time: a startup edit is a filesystem or registry write. */
busy: boolean;
refresh: () => Promise<void>;
setEnabled: (item: StartupItem, enabled: boolean) => Promise<string>;
}
/**
* The startup inventory.
*
* Nothing is cached between visits on purpose. A login item can be re-created by
* its own app at any moment, and a list that remembers would show an entry as
* enabled after the app re-armed it. Every visit re-reads the real thing, and a
* change returns the whole refreshed inventory rather than the one edited row.
*/
export function useStartupWorkspace(active: boolean): StartupWorkspace {
const [view, setView] = useState<StartupView | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const inFlight = useRef(false);
const refresh = useCallback(async () => {
if (inFlight.current) return;
inFlight.current = true;
setLoading(true);
try {
setView(await api.startupItems());
setError(null);
} catch (reason) {
setError(messageFrom(reason));
} finally {
inFlight.current = false;
setLoading(false);
}
}, []);
useEffect(() => {
if (active && !view) void refresh();
}, [active, refresh, view]);
const setEnabled = useCallback(
async (item: StartupItem, enabled: boolean) => {
setBusy(true);
try {
const result = await api.startupSetEnabled(item.id, enabled);
setView(result.view);
return result.message;
} finally {
setBusy(false);
}
},
[],
);
return { view, loading, error, busy, refresh, setEnabled };
}

View File

@ -1,103 +0,0 @@
import { useCallback, useRef, useState } from "react";
import { api, subscribeJobProgress } from "../lib/api";
import { isCancelled, messageFrom } from "../lib/format";
import type { JobProgress, LargestFile, StorageNode } from "../types";
function jobId(): string {
return crypto.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
export interface StorageWorkspace {
node: StorageNode | null;
files: LargestFile[];
progress: JobProgress | null;
exploring: boolean;
scanningFiles: boolean;
error: string | null;
explore: (path?: string | null) => Promise<void>;
largestFiles: (path: string) => Promise<void>;
cancel: () => Promise<void>;
clearError: () => void;
clearFiles: () => void;
}
export function useStorageWorkspace(): StorageWorkspace {
const [node, setNode] = useState<StorageNode | null>(null);
const [files, setFiles] = useState<LargestFile[]>([]);
const [progress, setProgress] = useState<JobProgress | null>(null);
const [exploring, setExploring] = useState(false);
const [scanningFiles, setScanningFiles] = useState(false);
const [error, setError] = useState<string | null>(null);
const activeJob = useRef<string | null>(null);
const explore = useCallback(async (path?: string | null) => {
if (exploring || scanningFiles) return;
const id = jobId();
activeJob.current = id;
setExploring(true);
setError(null);
setProgress(null);
setFiles([]);
const stop = await subscribeJobProgress(id, setProgress);
try {
const next = await api.storageExplore(id, path ?? null, 1, 16);
if (activeJob.current !== id) return;
setNode(next);
} catch (reason) {
if (!isCancelled(reason)) setError(messageFrom(reason));
} finally {
stop();
if (activeJob.current === id) {
setExploring(false);
setProgress(null);
activeJob.current = null;
}
}
}, [exploring, scanningFiles]);
const largestFiles = useCallback(
async (path: string) => {
if (exploring || scanningFiles) return;
const id = jobId();
activeJob.current = id;
setScanningFiles(true);
setError(null);
setProgress(null);
setFiles([]);
const stop = await subscribeJobProgress(id, setProgress);
try {
const next = await api.storageLargestFiles(id, path, 40);
if (activeJob.current !== id) return;
setFiles(next);
} catch (reason) {
if (!isCancelled(reason)) setError(messageFrom(reason));
} finally {
stop();
if (activeJob.current === id) {
setScanningFiles(false);
setProgress(null);
activeJob.current = null;
}
}
},
[exploring, scanningFiles],
);
const cancel = useCallback(async () => {
if (activeJob.current) await api.cancelJob(activeJob.current).catch(() => false);
}, []);
return {
node,
files,
progress,
exploring,
scanningFiles,
error,
explore,
largestFiles,
cancel,
clearError: () => setError(null),
clearFiles: () => setFiles([]),
};
}

View File

@ -2,32 +2,38 @@ import { invoke } from "@tauri-apps/api/core";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import type {
AppsResult,
AdvancedScanResult,
Bootstrap,
DeleteMode,
DeleteResult,
DupsResult,
ExploreResult,
HistorySession,
JobProgress,
LargeFile,
LargestFile,
IntelStatus,
MaintenanceResult,
MaintenanceTask,
ManageView,
PageId,
PermissionStatus,
PlanResult,
PopupClosedEvent,
PopupWindowItem,
PreflightResult,
ProcessDetail,
ProcessRow,
ScanResult,
SettingsView,
SecurityAction,
AllowKind,
SecurityScan,
SecuritySettings,
SecurityStatus,
StartupChange,
StartupView,
StorageNode,
AllowKind,
IntelStatus,
SpaceInsight,
SystemSnapshot,
ProcessDetail,
ProcessRow,
TweakState,
UndoResult,
UpdateCheckResult,
UpdateProgress,
@ -41,6 +47,7 @@ export interface SettingsPatch {
language?: string;
showAllocated?: boolean;
purgeMinAgeDays?: number;
purgeRoots?: string[];
historyKeep?: number;
setupReviewed?: boolean;
}
@ -69,17 +76,47 @@ export const api = {
}),
cleanupDelete: (jobId: string, scanId: string, selected: number[], mode: DeleteMode) =>
invoke<DeleteResult>("cleanup_delete", { jobId, scanId, selected, mode }),
cleanupPreflight: (scanId: string, selected: number[]) =>
invoke<PreflightResult>("cleanup_preflight", { scanId, selected }),
purgeScan: (jobId: string, roots: string[] = [], minAgeDays: number | null = null, force = false) =>
invoke<ScanResult>("purge_scan", { jobId, roots, minAgeDays, force }),
purgeDelete: (jobId: string, scanId: string, selected: number[], mode: DeleteMode) =>
invoke<DeleteResult>("purge_delete", { jobId, scanId, selected, mode }),
duplicatesScan: (jobId: string, roots: string[] = [], minSize: number | null = null) =>
invoke<DupsResult>("duplicates_scan", { jobId, roots, minSize }),
duplicatesDelete: (
jobId: string,
scanId: string,
// (group index, copy indexes to delete) — the keep decision is the UI's.
selections: [number, number[]][],
mode: DeleteMode,
) => invoke<DeleteResult>("duplicates_delete", { jobId, scanId, selections, mode }),
largeFilesScan: (
jobId: string,
roots: string[] = [],
minBytes: number | null = null,
fileClass: string | null = null,
) => invoke<LargeFile[]>("large_files_scan", { jobId, roots, minBytes, class: fileClass }),
largeFilesDelete: (jobId: string, paths: string[], mode: DeleteMode) =>
invoke<DeleteResult>("large_files_delete", { jobId, paths, mode }),
maintenanceTasks: () => invoke<MaintenanceTask[]>("maintenance_tasks"),
maintenanceRun: (jobId: string, task: string) =>
invoke<MaintenanceResult>("maintenance_run", { jobId, task }),
privacyScan: (jobId: string) => invoke<ScanResult>("privacy_scan", { jobId }),
privacyDelete: (jobId: string, scanId: string, selected: number[]) =>
invoke<DeleteResult>("privacy_delete", { jobId, scanId, selected }),
tweaksStates: () => invoke<TweakState[]>("tweaks_states"),
tweaksSet: (id: string, enabled: boolean) => invoke<TweakState>("tweaks_set", { id, enabled }),
tweaksRestoreAll: () => invoke<string[]>("tweaks_restore_all"),
appsScan: (jobId: string) => invoke<AppsResult>("apps_scan", { jobId }),
appIcon: (appKey: string) => invoke<string | null>("app_icon", { appKey }),
appPlan: (jobId: string, appKey: string) => invoke<PlanResult>("app_plan", { jobId, appKey }),
appUninstall: (jobId: string, planId: string, selected: number[], mode: DeleteMode) =>
invoke<DeleteResult>("app_uninstall", { jobId, planId, selected, mode }),
storageExplore: (jobId: string, path?: string | null, depth = 1, top = 16) =>
invoke<StorageNode>("storage_explore", { jobId, path, depth, top }),
appRemoveRecord: (regKey: string) => invoke<void>("app_remove_record", { regKey }),
storageExplore: (jobId: string, path?: string | null, depth = 1, top = 16, force = false) =>
invoke<ExploreResult>("storage_explore", { jobId, path, depth, top, force }),
storageInsights: () => invoke<SpaceInsight[]>("storage_insights"),
storageLargestFiles: (jobId: string, path: string, limit = 40) =>
invoke<LargestFile[]>("storage_largest_files", { jobId, path, limit }),
systemSnapshot: (full = false) => invoke<SystemSnapshot>("system_snapshot", { full }),
@ -90,15 +127,22 @@ export const api = {
settingsSave: (patch: SettingsPatch) => invoke<SettingsView>("settings_save", { patch }),
whitelistAdd: (path: string) => invoke<SettingsView>("whitelist_add", { path }),
whitelistRemove: (pattern: string) => invoke<SettingsView>("whitelist_remove", { pattern }),
whitelistAudit: () => invoke<{ pattern: string; live: boolean }[]>("whitelist_audit"),
autostartStatus: () => invoke<boolean>("autostart_status"),
setAutostart: (enabled: boolean) => invoke<boolean>("set_autostart", { enabled }),
writeTextFile: (path: string, contents: string) =>
invoke<void>("write_text_file", { path, contents }),
revealPath: (path: string) => invoke<void>("reveal_path", { path }),
openTrash: () => invoke<void>("open_trash"),
permissionStatus: () => invoke<PermissionStatus>("permission_status"),
openFullDiskAccessSettings: () => invoke<void>("open_full_disk_access_settings"),
manageScan: () => invoke<ManageView>("manage_scan"),
managedStartupSetEnabled: (id: string, enabled: boolean) =>
invoke<number>("managed_startup_set_enabled", { id, enabled }),
startupSetEnabled: (id: string, enabled: boolean) =>
invoke<number>("startup_set_enabled", { id, enabled }),
startupRemoveEntry: (id: string) => invoke<number>("startup_remove_entry", { id }),
advancedScan: () => invoke<AdvancedScanResult>("advanced_scan"),
advancedSetEnabled: (id: string, enabled: boolean) =>
invoke<void>("advanced_set_enabled", { id, enabled }),
extensionSetRegistered: (id: string, registered: boolean) =>
invoke<void>("extension_set_registered", { id, registered }),
popupList: () => invoke<PopupWindowItem[]>("popup_list"),
@ -109,8 +153,7 @@ export const api = {
invoke<void>("popup_rule_update", { index, enabled, resetCount }),
popupRuleRemove: (index: number) => invoke<void>("popup_rule_remove", { index }),
popupWatcherSet: (enabled: boolean) => invoke<void>("popup_watcher_set", { enabled }),
widgetGet: () =>
invoke<{ prefs: WidgetPrefs; language: "zh" | "en" }>("widget_get"),
widgetGet: () => invoke<{ prefs: WidgetPrefs }>("widget_get"),
widgetSet: (patch: WidgetPatch) => invoke<WidgetPrefs>("widget_set", { patch }),
widgetHide: () => invoke<void>("widget_hide"),
updateCheck: () => invoke<UpdateCheckResult>("update_check"),
@ -145,10 +188,6 @@ export const api = {
securityUpdateRules: () => invoke<IntelStatus>("security_update_rules"),
securityRollbackRules: () => invoke<IntelStatus>("security_rollback_rules"),
openQuarantineFolder: () => invoke<void>("open_quarantine_folder"),
startupItems: () => invoke<StartupView>("startup_items"),
startupSetEnabled: (id: string, enabled: boolean) =>
invoke<StartupChange>("startup_set_enabled", { id, enabled }),
openStartupSettings: () => invoke<void>("open_startup_settings"),
processInventory: (withTrust = true) =>
invoke<ProcessRow[]>("process_inventory", { withTrust }),
processDetail: (pid: number) => invoke<ProcessDetail>("process_detail", { pid }),
@ -172,8 +211,6 @@ export const api = {
listen<WidgetPrefs>("widget://settings", (event) => handler(event.payload)),
};
/// Progress events for one job, whatever kind of job it is. Security scans share
/// the channel with cleanup so a page subscribes the same way.
export async function subscribeJobProgress(
jobId: string,
handler: (progress: JobProgress) => void,

View File

@ -12,10 +12,11 @@ export function formatBytes(value: number, fractionDigits = 1): string {
return `${remaining.toFixed(digits)} ${units[unit]}`;
}
/** RAM is sold in binary units, so 16 GB should not read as 17.2 GB. */
export function formatMemoryBytes(value: number, fractionDigits = 1): string {
/// RAM is sold in powers of two (a "32 GB" stick holds 32 GiB); disks are not.
/// Memory readouts must divide by 1024 or a 32 GiB machine shows "34.4 GB".
export function formatMemory(value: number, fractionDigits = 1): string {
if (!Number.isFinite(value) || value <= 0) return "0 B";
const units = ["B", "KB", "MB", "GB", "TB", "PB"];
const units = ["B", "KB", "MB", "GB", "TB"];
let remaining = value;
let unit = 0;
while (remaining >= 1024 && unit < units.length - 1) {
@ -27,6 +28,9 @@ export function formatMemoryBytes(value: number, fractionDigits = 1): string {
return `${remaining.toFixed(digits)} ${units[unit]}`;
}
/** Alias kept for pages that predate the shorter name. */
export const formatMemoryBytes = formatMemory;
export function formatBytesExact(value: number): string {
if (value <= 0) return "0 B";
const formatted = formatBytes(value, 2);
@ -97,3 +101,45 @@ export function isCancelled(error: unknown): boolean {
const text = messageFrom(error).toLowerCase();
return text.includes("cancel") || text.includes("取消");
}
/* "最后写入 3 个月前" / "written into 3 months ago" — the Mole decision
* aid: size alone is not actionable, dormancy is. */
export function ageLabel(secs: number, lang: "zh" | "en"): string {
const days = Math.floor(secs / 86_400);
if (lang === "zh") {
if (days < 1) return "今天有改动";
if (days < 30) return `${days} 天未修改`;
if (days < 365) return `${Math.floor(days / 30)} 个月未修改`;
return `${(days / 365).toFixed(days < 730 ? 1 : 0)} 年未修改`;
}
if (days < 1) return "written today";
if (days < 30) return `${days} days untouched`;
if (days < 365) return `${Math.floor(days / 30)} months untouched`;
return `${(days / 365).toFixed(days < 730 ? 1 : 0)} years untouched`;
}
/* "12 分钟前" for cache freshness lines. */
export function agoLabel(ms: number, lang: "zh" | "en"): string {
const mins = Math.floor(ms / 60_000);
if (lang === "zh") {
if (mins < 1) return "刚刚";
if (mins < 60) return `${mins} 分钟前`;
return `${Math.floor(mins / 60)} 小时前`;
}
if (mins < 1) return "just now";
if (mins < 60) return `${mins} min ago`;
return `${Math.floor(mins / 60)} h ago`;
}
/* Throttled "128,431 文件 · 38.2 GB" live scan counter (A①). */
export function countLabel(files: number, bytes: number, lang: "zh" | "en"): string {
const f = formatThousands(files);
const b = formatBytes(bytes);
return lang === "zh" ? `已统计 ${f} 个文件 · ${b}` : `${f} files · ${b} measured`;
}
function formatThousands(value: number): string {
return Math.round(value)
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

View File

@ -0,0 +1,74 @@
/* Why a skipped item stayed behind — the same taxonomy the 空间清理 result
* view uses, now shared with the in-place clean banners on every page. */
export interface SkipGroup {
key: string;
title: [string, string];
hint: [string, string];
action?: "rescan";
}
export function skipGroupOf(reason: string): SkipGroup {
const lower = reason.toLowerCase();
if (lower.includes("running") || lower.includes("占用")) {
return {
key: "running",
title: ["应用正在运行", "应用正在运行"],
hint: ["退出这些应用后重新扫描,即可再次选中。", "退出这些应用后重新扫描,即可再次选中。"],
action: "rescan",
};
}
if (lower.includes("admin") || lower.includes("管理员")) {
return {
key: "admin",
title: ["需要管理员权限", "需要管理员权限"],
hint: [
"以管理员身份重新启动 Squid 后再清理这批项目。",
"以管理员身份重新启动 Squid 后再清理这批项目。",
],
action: "rescan",
};
}
if (lower.includes("已不存在") || lower.includes("no longer") || lower.includes("missing")) {
return {
key: "gone",
title: ["扫描后已消失", "扫描后已消失"],
hint: ["这些路径在清理开始前就不在了,无需处理。", "这些路径在清理开始前就不在了,无需处理。"],
};
}
if (lower.includes("whitelist")) {
return {
key: "whitelist",
title: ["命中白名单", "命中白名单"],
hint: [
"在 设置 → 白名单 中移除对应规则后才会被清理。",
"在 设置 → 白名单 中移除对应规则后才会被清理。",
],
};
}
return {
key: "protected",
title: ["受安全策略保护", "受安全策略保护"],
hint: [
"这些目录看似缓存,实际可能存有您自己的文件,Squid 不会删除。",
"这些目录看似缓存,实际可能存有您自己的文件,Squid 不会删除。",
],
};
}
/** "占用中 5 · 需要管理员 2" — the skipped-reason tally the amber banner
* shows under its headline. */
export function skipTally(skipped: { reason: string }[]): string {
const counts = new Map<string, number>();
for (const row of skipped) {
const group = skipGroupOf(row.reason);
counts.set(group.title[1], (counts.get(group.title[1]) ?? 0) + 1);
}
return [...counts.entries()].map(([title, count]) => `${title} ${count}`).join(" · ");
}
/** 41 秒 / 1 分 12 秒 — elapsed labels for the done banner. */
export function formatDuration(ms: number): string {
const seconds = Math.max(1, Math.round(ms / 1000));
if (seconds < 60) return `${seconds} 秒`;
return `${Math.floor(seconds / 60)} 分 ${seconds % 60} 秒`;
}

View File

@ -2,16 +2,18 @@ import {
AppWindow,
ChevronRight,
FolderOpen,
Hammer,
PackageX,
Play,
Search,
ShieldAlert,
ShieldCheck,
Trash2,
} from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { useMemo, useState } from "react";
import { useI18n } from "../i18n";
import { api } from "../lib/api";
import { formatBytes, formatCount, shortPath } from "../lib/format";
import { formatBytes, formatCount, messageFrom, shortPath } from "../lib/format";
import type { AppInfo, DeleteMode } from "../types";
import type { AppsWorkspace } from "../hooks/useAppsWorkspace";
import {
@ -28,53 +30,21 @@ import {
useToast,
} from "../components/ui";
const iconCache = new Map<string, string | null>();
const iconRequests = new Map<string, Promise<string | null>>();
/* 卸载增强: package-manager provenance as a chip. The backend only badges
well-known layouts, so the chip states a fact, never a guess. */
const SOURCE_BADGES: Record<string, [string, string]> = {
winget: ["winget", "winget"],
scoop: ["scoop", "scoop"],
Chocolatey: ["Chocolatey", "Chocolatey"],
"Microsoft Store": ["Store", "Microsoft Store"],
Toolbox: ["Toolbox", "JetBrains Toolbox"],
};
function loadAppIcon(app: AppInfo): Promise<string | null> {
const key = app.bundle_id || app.path;
if (iconCache.has(key)) return Promise.resolve(iconCache.get(key) ?? null);
const existing = iconRequests.get(key);
if (existing) return existing;
const request = api
.appIcon(key)
.catch(() => null)
.then((icon) => {
iconCache.set(key, icon);
iconRequests.delete(key);
return icon;
});
iconRequests.set(key, request);
return request;
}
function AppGlyph({ app, large = false }: { app: AppInfo; large?: boolean }) {
const key = app.bundle_id || app.path;
const [icon, setIcon] = useState<string | null>(() => iconCache.get(key) ?? null);
useEffect(() => {
if (iconCache.has(key)) {
setIcon(iconCache.get(key) ?? null);
return;
}
let cancelled = false;
void loadAppIcon(app).then((next) => {
if (!cancelled) setIcon(next);
});
return () => {
cancelled = true;
};
}, [app, key]);
const letter = app.name.trim().slice(0, 1).toUpperCase() || "?";
return (
<span
className={`app-glyph ${large ? "is-large" : ""} ${icon ? "has-icon" : ""}`}
aria-hidden="true"
>
{icon ? <img src={icon} alt="" /> : letter}
</span>
);
function sourceBadge(source: string): [string, string] | null {
for (const [key, badge] of Object.entries(SOURCE_BADGES)) {
if (source.includes(key)) return badge;
}
return null;
}
function AppRow({
@ -87,9 +57,13 @@ function AppRow({
onSelect: () => void;
}) {
const { t } = useI18n();
const letter = app.name.trim().slice(0, 1).toUpperCase() || "?";
const badge = sourceBadge(app.source);
return (
<button className={`app-row ${selected ? "is-selected" : ""}`} onClick={onSelect}>
<AppGlyph app={app} />
<span className="app-glyph" aria-hidden="true">
{app.icon ? <img src={app.icon} alt="" /> : letter}
</span>
<span className="app-row-copy">
<span className="app-row-title">
<strong>{app.name}</strong>
@ -99,12 +73,24 @@ function AppRow({
{t("Running", "运行中")}
</span>
) : null}
{app.dead ? (
<span className="status-chip is-danger">
<ShieldAlert size={10} />
{t("Incomplete install", "安装不完整")}
</span>
) : null}
{badge ? (
<span className="status-chip is-source" title={badge[1]}>
<Hammer size={10} />
{badge[0]}
</span>
) : null}
</span>
<span>{app.bundle_id || shortPath(app.path, 45)}</span>
</span>
<span className="app-row-meta">
<strong>{formatBytes(app.size)}</strong>
<small>{app.version ? `v${app.version}` : app.source}</small>
<small>{app.version ? `v${app.version}` : app.publisher || app.source}</small>
</span>
<ChevronRight size={16} />
</button>
@ -122,6 +108,7 @@ export function ApplicationsPage({
const [query, setQuery] = useState("");
const [confirming, setConfirming] = useState(false);
const [mode, setMode] = useState<DeleteMode>("trash");
const [recordBusy, setRecordBusy] = useState(false);
const apps = useMemo(() => {
const needle = query.trim().toLowerCase();
@ -134,6 +121,14 @@ export function ApplicationsPage({
);
}, [query, workspace.apps]);
// The scan carries icons; the plan's AppInfo does not, so look it up.
const planIcon = useMemo(() => {
const planApp = workspace.plan?.app;
if (!planApp) return null;
const key = planApp.bundle_id || planApp.path;
return workspace.apps.find((a) => (a.bundle_id || a.path) === key)?.icon ?? null;
}, [workspace.plan, workspace.apps]);
const uninstall = async () => {
const result = await workspace.uninstall(mode);
setConfirming(false);
@ -148,9 +143,28 @@ export function ApplicationsPage({
}
};
// 卸载增强: an 安装不完整 entry is only fully gone once its registry
// record goes too — otherwise Windows (and every scanner) still lists it.
const removeRecord = async () => {
const regKey = workspace.plan?.app.reg_key;
if (!regKey || recordBusy) return;
setRecordBusy(true);
try {
await api.appRemoveRecord(regKey);
push(t("Orphaned registry record removed", "已清除残留的注册表记录"), "success");
workspace.chooseApp(null);
await workspace.scan();
} catch (reason) {
push(messageFrom(reason), "danger");
} finally {
setRecordBusy(false);
}
};
return (
<div className="page apps-page">
<PageHeader
eyebrow={t("Applications", "应用程序")}
title={t("Uninstall completely", "卸载,干净彻底")}
actions={
<Button
@ -245,7 +259,9 @@ export function ApplicationsPage({
) : workspace.plan ? (
<>
<div className="plan-head">
<AppGlyph app={workspace.plan.app} large />
<span className="app-glyph is-large">
{planIcon ? <img src={planIcon} alt="" /> : workspace.plan.app.name.slice(0, 1).toUpperCase()}
</span>
<div>
<span className="plan-kicker">{t("Removal plan", "卸载方案")}</span>
<h2>{workspace.plan.app.name}</h2>
@ -265,6 +281,32 @@ export function ApplicationsPage({
</button>
</div>
{workspace.plan.app.dead ? (
<div className="plan-dead-callout">
<ShieldAlert size={16} />
<div>
<strong>{t("Incomplete install", "安装不完整")}</strong>
<p>
{t(
"The program files are already gone; only its registry record and leftovers remain. Removing the record makes Windows stop listing it.",
"程序本体已经不存在,只剩下注册表记录和残留文件。清除记录后,系统将不再列出这个应用。",
)}
</p>
<Button
size="sm"
variant="secondary"
icon={<PackageX size={14} />}
disabled={recordBusy}
onClick={() => void removeRecord()}
>
{recordBusy
? t("Cleaning…", "正在清理…")
: t("Clean leftovers", "清理残留记录")}
</Button>
</div>
</div>
) : null}
{workspace.plan.warnings.length > 0 ? (
<div className="plan-warnings">
{workspace.plan.warnings.map((warning) => (
@ -343,6 +385,12 @@ export function ApplicationsPage({
<ShieldCheck size={26} />
</span>
<h2>{t("Choose an application", "选择一个应用")}</h2>
<p>
{t(
"Squid will map its caches, settings and support files before offering to remove anything.",
"Squid 会先整理应用的缓存、设置与支持文件,再让您决定是否移除。",
)}
</p>
</div>
)}
</aside>
@ -352,6 +400,11 @@ export function ApplicationsPage({
{!workspace.scanned && !workspace.scanning ? (
<EmptyState
icon={<AppWindow size={29} />}
title={t("See what is installed", "查看已安装的应用")}
description={t(
"Scan your applications to remove an app completely, including files that would otherwise stay behind.",
"扫描应用后可连同原本会遗留的文件一起移除。",
)}
action={
<Button
variant="primary"

View File

@ -1,63 +0,0 @@
import { ScanSearch, Sparkles } from "lucide-react";
import { useI18n } from "../i18n";
import type { DeleteMode } from "../types";
import type { ScanWorkspace } from "../hooks/useScanWorkspace";
import { CleanupInventory } from "../components/CleanupView";
import { Button, EmptyState, PageHeader } from "../components/ui";
export function CleanupPage({
workspace,
deleteMode,
onHistory,
}: {
workspace: ScanWorkspace;
deleteMode: DeleteMode;
onHistory: () => void;
}) {
const { t } = useI18n();
return (
<div className="page cleanup-page">
<PageHeader
title={t("Clutter, without the guesswork", "清理垃圾,不靠猜")}
actions={
workspace.result ? (
<Button
variant="secondary"
icon={<ScanSearch size={16} />}
onClick={() => void workspace.runScan()}
disabled={workspace.scanning || workspace.deleting}
>
{t("Scan again", "重新扫描")}
</Button>
) : null
}
/>
{workspace.error && !workspace.scanning ? (
<div className="error-banner">{workspace.error}</div>
) : null}
<CleanupInventory
workspace={workspace}
defaultMode={deleteMode}
onHistory={onHistory}
/>
{!workspace.result && !workspace.scanning && !workspace.summary ? (
<EmptyState
icon={<Sparkles size={28} />}
action={
<Button
variant="primary"
icon={<ScanSearch size={16} />}
onClick={() => void workspace.runScan()}
>
{t("Scan for junk", "扫描系统垃圾")}
</Button>
}
/>
) : null}
</div>
);
}

View File

@ -0,0 +1,512 @@
import {
CopyX,
FileQuestion,
FolderPlus,
Lock,
MapPin,
ScanSearch,
ShieldAlert,
Sparkles,
Trash2,
X,
} from "lucide-react";
import { useEffect, useState } from "react";
import { open } from "@tauri-apps/plugin-dialog";
import * as apiClient from "../lib/api";
import { useI18n } from "../i18n";
import { agoLabel, formatBytes, formatCount } from "../lib/format";
import { keepIndexOf, useDuplicatesWorkspace } from "../hooks/useDuplicatesWorkspace";
import {
Button,
Checkbox,
EmptyState,
InlineError,
PageHeader,
ProgressCard,
useToast,
} from "../components/ui";
import { CleanBar } from "../components/CleanBar";
import type { DeleteResult, DupGroup } from "../types";
const MIN_SIZE_OPTIONS = [
{ value: 1024 * 1024, label: "≥1MB" },
{ value: 10 * 1024 * 1024, label: "≥10MB" },
{ value: 100 * 1024 * 1024, label: "≥100MB" },
];
function FunnelStage({
value,
label,
hot,
}: {
value: number;
label: string;
hot?: boolean;
}) {
return (
<div className={`dup-stage ${hot ? "is-hot" : ""}`}>
<b>{formatCount(value)}</b>
<span>{label}</span>
</div>
);
}
function DupGroupCard({
group,
index,
keep,
picked,
lang,
onToggle,
onDismiss,
}: {
group: DupGroup;
index: number;
keep: number;
picked: Set<number> | undefined;
lang: "zh" | "en";
onToggle: (groupIndex: number, copyIndex: number) => void;
onDismiss: (groupIndex: number) => void;
}) {
const { t } = useI18n();
const wasted = group.size * (group.copies.length - 1);
// The keeper row is now a normal, checkable copy: ticking it means "this
// group may end up with nothing left". The amber chip keeps saying 保留 so
// the strategy stays visible, and adds a warning when it gets picked.
const keepPicked = picked?.has(keep) ?? false;
return (
<section className={`dup-group ${group.personal ? "is-personal" : ""}`}>
<header className="dup-group-head">
<div className="dup-group-title">
<span className="dup-group-count">
{group.copies.length} {t("copies", "份相同")}
</span>
<b>{group.copies[keep]?.path.split(/[\\/]/).pop()}</b>
<span className="dup-waste-chip">
{t("wastes", "重复浪费")} {formatBytes(wasted)}
</span>
{keepPicked ? (
<span className="dup-empty-chip">
{t("group will be empty", "本组将一份不剩")}
</span>
) : null}
{group.personal ? (
<span className="dup-personal-chip">
<Lock size={11} />
{t("personal files", "个人文件")}
</span>
) : null}
</div>
<div className="dup-group-size">
{formatBytes(group.size)} {t("each", "/ 份")}
</div>
<button
type="button"
className="dup-group-dismiss"
title={t("Ignore this group", "忽略本组")}
onClick={() => onDismiss(index)}
>
<X size={13} />
</button>
</header>
<ul className="dup-copies">
{group.copies.map((copy, copyIndex) => {
const isKeep = copyIndex === keep;
const checked = picked?.has(copyIndex) ?? false;
return (
<li
key={copy.path}
className={`dup-copy ${checked ? "is-picked" : ""} ${isKeep ? "is-keep" : ""} ${
isKeep && checked ? "is-keep-picked" : ""
}`}
>
<Checkbox
checked={checked}
disabled={Boolean(copy.locked)}
onChange={() => onToggle(index, copyIndex)}
label={copy.path}
/>
{isKeep ? (
<span
className={`dup-keep-chip ${checked ? "is-danger" : ""}`}
title={
checked
? t(
"This is the kept copy — deleting it leaves the group with nothing.",
"此文件为最后保留版本,勾选即完全删除本组。",
)
: undefined
}
>
{checked ? t("keep · deleting", "保留 · 已勾选删除") : t("keep", "保留")}
</span>
) : null}
{copy.locked ? (
<span className="dup-lock-chip" title={copy.locked}>
<Lock size={11} />
</span>
) : null}
<span className="dup-copy-path" title={copy.path}>
{copy.path}
</span>
<span className="dup-copy-age">
{copy.mtimeMs ? agoLabel(copy.mtimeMs, lang) : ""}
</span>
<button
type="button"
className="dup-copy-reveal"
onClick={() => void apiClient.api.revealPath(copy.path).catch(() => undefined)}
title={t("Reveal in Explorer", "在文件夹中显示")}
>
<MapPin size={12} />
{t("Reveal", "定位")}
</button>
</li>
);
})}
</ul>
</section>
);
}
export function DuplicateFilesPage({
embedded = false,
onBadge,
onHistory,
}: {
/** Rendered inside 空间清理 hub: page title hides, stats flow to onBadge. */
embedded?: boolean;
onBadge?: (value: string | null) => void;
/** Jump to 历史记录 for an undo. */
onHistory?: () => void;
} = {}) {
const { t, lang } = useI18n();
const { push } = useToast();
const workspace = useDuplicatesWorkspace();
const [minSize, setMinSize] = useState(1024 * 1024);
const [extraRoots, setExtraRoots] = useState<string[]>([]);
const [confirming, setConfirming] = useState(false);
const [cleanDone, setCleanDone] = useState<{ outcome: DeleteResult; elapsedMs: number } | null>(
null,
);
const entries = workspace.visible;
const groups = entries.map((entry) => entry.group);
const report = workspace.result?.report;
const addRoot = async () => {
const chosen = await open({
directory: true,
multiple: true,
title: t("Add folders to the duplicate scan", "选择要一起扫描的文件夹"),
});
if (Array.isArray(chosen)) setExtraRoots((current) => [...current, ...chosen]);
else if (typeof chosen === "string") setExtraRoots((current) => [...current, chosen]);
};
const start = () => {
setConfirming(false);
void workspace.runScan(extraRoots, minSize);
};
const confirmClean = async () => {
setConfirming(false);
const startedAt = Date.now();
const outcome = await workspace.clean("trash");
if (outcome) {
setCleanDone({ outcome, elapsedMs: Date.now() - startedAt });
push(
lang === "zh"
? `已将 ${outcome.removed} 个副本移入回收站(${formatBytes(outcome.freed)}),可在「历史记录」撤销`
: `Moved ${outcome.removed} copies to the Recycle Bin (${formatBytes(outcome.freed)}) — undo from History`,
"success",
);
}
};
// Totals next to the toolbar follow the *visible* groups: an ignored group
// stops counting toward what the page offers to reclaim.
const visibleWasted = groups.reduce((sum, g) => sum + g.size * (g.copies.length - 1), 0);
// Groups whose *kept* copy is checked: deleting those erases the file
// entirely (every copy goes), which the summary strip and confirm dialog
// must call out before anything moves to the Recycle Bin.
const empties = entries.reduce(
(sum, entry) =>
sum +
(workspace.picks.get(entry.index)?.has(keepIndexOf(entry.group, workspace.keepStrategy))
? 1
: 0),
0,
);
// Hub badge: confirmed groups after ignores, or null before a scan.
useEffect(() => {
if (!embedded || !onBadge) return;
onBadge(groups.length > 0 ? `${groups.length} 组 · ${formatBytes(visibleWasted)}` : null);
}, [embedded, groups.length, onBadge, visibleWasted]);
return (
<div className={`page dup-page ${embedded ? "is-embedded" : ""}`}>
{embedded ? null : (
<PageHeader
title={t("Duplicate files", "重复文件")}
/>
)}
{workspace.error ? <InlineError message={workspace.error} onDismiss={workspace.clearError} /> : null}
<section className="dup-config">
<span className="dup-config-label">{t("Scan scope", "扫描范围")}</span>
<span className="dup-root-chip is-static">
{t(
"Home folders + all drives (system folders skipped)",
"用户目录 + 各磁盘(自动跳过系统与软件数据目录)",
)}
</span>
{extraRoots.map((root) => (
<span className="dup-root-chip" key={root} title={root}>
{root}
<button
type="button"
onClick={() => setExtraRoots((current) => current.filter((r) => r !== root))}
aria-label={t("Remove", "移除")}
>
<X size={11} />
</button>
</span>
))}
<button type="button" className="dup-root-add" onClick={() => void addRoot()}>
<FolderPlus size={13} /> {t("Add folder", "添加文件夹")}
</button>
<span className="dup-config-spacer" />
<span className="dup-config-label">{t("Min size", "最小体积")}</span>
<div className="dup-seg" role="group">
{MIN_SIZE_OPTIONS.map((option) => (
<button
key={option.value}
type="button"
className={minSize === option.value ? "is-active" : ""}
onClick={() => setMinSize(option.value)}
>
{option.label}
</button>
))}
</div>
<Button
size="lg"
variant="primary"
className="scan-cta"
icon={<ScanSearch size={16} />}
onClick={start}
disabled={workspace.scanning || workspace.deleting}
>
{workspace.scanning
? t("Scanning…", "扫描中…")
: workspace.result
? t("Rescan", "重新扫描")
: t("Start scan", "开始扫描")}
</Button>
</section>
{workspace.scanning || (workspace.funnel.walked > 0 && groups.length > 0) ? (
<section className="dup-funnel" aria-live="polite">
<div className="dup-funnel-row">
<FunnelStage value={workspace.funnel.walked} label={t("files walked", "已遍历文件")} />
<i>→</i>
<FunnelStage
value={workspace.funnel.sameSize}
label={t("same-size candidates", "同大小候选")}
/>
<i>→</i>
<FunnelStage value={workspace.funnel.sampleHits} label={t("sample hits", "采样哈希命中")} />
<i>→</i>
<FunnelStage
value={workspace.funnel.confirmed}
label={t("full-hash confirmed", "全量校验确认")}
hot
/>
<div className="dup-funnel-total">
{t("duplicates found", "已发现重复")}{" "}
<b>{formatCount(groups.length)}</b> {t("groups", "组")} ·{" "}
{t("recoverable", "可回收")} <b>{formatBytes(visibleWasted)}</b>
</div>
</div>
{workspace.progress?.subject ? (
<div className="dup-funnel-current">
{t("Checking", "正在校验")} {workspace.progress.subject}
</div>
) : null}
</section>
) : null}
{workspace.scanning ? (
<ProgressCard
progress={workspace.progress}
title={t("Scanning for duplicates", "正在查找重复文件")}
onCancel={() => void workspace.cancel()}
capAt99
/>
) : null}
{workspace.deleting ? (
<CleanBar
spec={{ phase: "busy" }}
progress={workspace.progress}
noun={["个副本", "copies"]}
mode="trash"
onHistory={() => onHistory?.()}
onDismiss={() => undefined}
/>
) : null}
{!workspace.deleting && cleanDone ? (
<CleanBar
spec={{ phase: "done", outcome: cleanDone.outcome, elapsedMs: cleanDone.elapsedMs }}
progress={null}
noun={["个副本", "copies"]}
mode="trash"
onHistory={() => onHistory?.()}
onDismiss={() => setCleanDone(null)}
onRescan={() => void workspace.runScan(extraRoots, minSize)}
/>
) : null}
{!workspace.scanning &&
groups.length === 0 &&
!workspace.result &&
!workspace.error &&
!workspace.deleting &&
!cleanDone ? (
<EmptyState
icon={<FileQuestion size={26} />}
title={t("No duplicate scan yet", "还没有扫描过重复文件")}
description={t(
"Start scan walks your files once; later scans reuse the hash cache and only re-check what changed.",
"首次扫描遍历一遍文件;之后的扫描复用哈希缓存,只重算发生变化的文件。",
)}
/>
) : null}
{!workspace.scanning && groups.length === 0 && workspace.result ? (
<EmptyState
icon={<CopyX size={26} />}
title={t("No duplicate files found", "没有发现重复文件")}
description={
lang === "zh"
? `已检查 ${formatCount(workspace.result.report.walked)} 个达到体积门槛的文件,无重复。`
: `${formatCount(workspace.result.report.walked)} files checked above the size floor.`
}
/>
) : null}
{!workspace.scanning && groups.length > 0 ? (
<>
<section className="dup-toolbar">
<button type="button" className="dup-smart" onClick={() => workspace.smartSelect()}>
<Sparkles size={13} />{" "}
{t("Smart pick (keep one per group)", "智能选择(每组保留一份)")}
</button>
<button
type="button"
className="dup-strategy"
onClick={() =>
workspace.setKeepStrategy(
workspace.keepStrategy === "shortest" ? "oldest" : "shortest",
)
}
title={t("Which copy survives when picking smartly", "智能选择保留哪一份")}
>
{workspace.keepStrategy === "shortest"
? t("keep: shortest path", "保留:路径最短")
: t("keep: oldest copy", "保留:最早的一份")}
</button>
<button type="button" className="dup-invert" onClick={workspace.invertSelection}>
{t("Invert", "反选")}
</button>
<span className="dup-toolbar-sum">
{formatCount(groups.length)} {t("groups · duplicate copies", "组 · 重复副本")}{" "}
{formatCount(groups.reduce((sum, g) => sum + g.copies.length - 1, 0))} ·{" "}
{formatBytes(visibleWasted)}
{empties > 0 ? (
<em className="dup-empties">
{t(
`${formatCount(empties)} group(s) will be fully removed`,
` · ${formatCount(empties)} 组将一份不剩`,
)}
</em>
) : null}
</span>
<Button
variant="danger"
className="dup-clean"
disabled={workspace.selectedCount === 0 || workspace.deleting}
onClick={() => setConfirming(true)}
>
<Trash2 size={14} />
<span>
{workspace.deleting
? t("Cleaning…", "清理中…")
: `${t("Clean", "清理")} ${formatCount(workspace.selectedCount)} ${t(
"copies",
"个副本",
)} · ${formatBytes(workspace.selectedBytes)}`}
</span>
</Button>
</section>
{confirming ? (
<section className={`dup-confirm ${empties > 0 ? "is-strict" : ""}`}>
<ShieldAlert size={15} />
<div>
<b>
{lang === "zh"
? `将 ${workspace.selectedCount} 个副本(${formatBytes(workspace.selectedBytes)})移入回收站?`
: `Move ${workspace.selectedCount} copies (${formatBytes(workspace.selectedBytes)}) to the Recycle Bin?`}
</b>
{empties > 0 ? (
<b className="dup-confirm-warn">
{lang === "zh"
? `${formatCount(empties)} 组勾选了最后保留版本——这 ${formatCount(empties)} 组将被完全删除!`
: `${formatCount(empties)} group(s) include the kept copy — they will be deleted entirely!`}
</b>
) : (
<small>
{t(
"Every group keeps at least one copy; a mis-click is one Undo away from History.",
"每组至少保留一份;误删可从「历史记录 → 撤销」找回。",
)}
</small>
)}
<small>
{t(
"Deletions land in the Recycle Bin — undo from History.",
"删除一律进回收站,可从「历史记录 → 撤销」找回。",
)}
</small>
</div>
<Button onClick={() => setConfirming(false)}>{t("Cancel", "取消")}</Button>
<Button variant="danger" onClick={() => void confirmClean()}>
{empties > 0
? t("Delete everything selected", "确认完全删除")
: t("Confirm", "确认清理")}
</Button>
</section>
) : null}
<div className="dup-groups">
{entries.map(({ group, index }) => (
<DupGroupCard
key={`${group.size}-${group.copies[0]?.path}-${index}`}
group={group}
index={index}
keep={keepIndexOf(group, workspace.keepStrategy)}
picked={workspace.picks.get(index)}
lang={lang}
onToggle={workspace.toggleCopy}
onDismiss={workspace.removeGroup}
/>
))}
</div>
</>
) : null}
</div>
);
}

View File

@ -89,6 +89,7 @@ export function HistoryPage() {
return (
<div className="page history-page">
<PageHeader
eyebrow={t("History", "历史记录")}
title={t("Every change, on the record", "每一次改动,都有记录")}
actions={
<Button
@ -135,6 +136,10 @@ export function HistoryPage() {
<EmptyState
icon={<History size={28} />}
title={t("No cleanups yet", "还没有清理记录")}
description={t(
"Each confirmed cleanup will appear here with its size, result and restore option.",
"每次确认的清理都会记录在这里,并提供大小、结果与还原选项。",
)}
/>
) : (
<div className="history-list">

View File

@ -0,0 +1,425 @@
import {
Archive,
Disc3,
Cloud,
FileQuestion,
FileVideo,
HardDrive,
Lock,
MapPin,
Package,
ScanSearch,
ShieldAlert,
Trash2,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import * as apiClient from "../lib/api";
import { subscribeJobProgress } from "../lib/api";
import { useI18n } from "../i18n";
import { agoLabel, formatBytes, formatCount, messageFrom } from "../lib/format";
import {
Button,
Checkbox,
EmptyState,
InlineError,
PageHeader,
ProgressCard,
useToast,
} from "../components/ui";
import { CleanBar } from "../components/CleanBar";
import type { DeleteResult, JobProgress, LargeFile } from "../types";
const THRESHOLDS = [
{ value: 100 * 1024 * 1024, label: "≥100MB" },
{ value: 500 * 1024 * 1024, label: "≥500MB" },
{ value: 1024 * 1024 * 1024, label: "≥1GB" },
];
const CLASSES = [
{ id: "all", en: "All", zh: "全部", icon: HardDrive },
{ id: "video", en: "Video", zh: "视频", icon: FileVideo },
{ id: "archive", en: "Archives", zh: "归档", icon: Archive },
{ id: "installer", en: "Installers", zh: "安装包", icon: Package },
{ id: "image", en: "Disk images", zh: "镜像/VHD", icon: Disc3 },
];
const CLASS_ICON: Record<LargeFile["class"], typeof HardDrive> = {
video: FileVideo,
archive: Archive,
installer: Package,
image: Disc3,
other: HardDrive,
};
/** 休眠判定沿用清理页口径:180 天无修改即值得标记。 */
const DORMANT_SECS = 180 * 86_400;
export function LargeFilesPage({
embedded = false,
onBadge,
onHistory,
}: {
/** Rendered inside 空间清理 hub: page title hides, stats flow to onBadge. */
embedded?: boolean;
onBadge?: (value: string | null) => void;
/** Jump to 历史记录 for an undo. */
onHistory?: () => void;
} = {}) {
const { t, lang } = useI18n();
const { push } = useToast();
const [files, setFiles] = useState<LargeFile[] | null>(null);
const [scope, setScope] = useState<string[]>([]);
const [threshold, setThreshold] = useState(500 * 1024 * 1024);
const [klass, setKlass] = useState("all");
const [hideCritical, setHideCritical] = useState(true);
const [scanning, setScanning] = useState(false);
const [deleting, setDeleting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [progress, setProgress] = useState<JobProgress | null>(null);
const [picked, setPicked] = useState<Set<string>>(new Set());
const [confirming, setConfirming] = useState(false);
const [cleanDone, setCleanDone] = useState<
{ outcome: DeleteResult; elapsedMs: number } | null
>(null);
const job = useRef<string | null>(null);
const run = useCallback(async () => {
if (scanning) return;
const id = crypto.randomUUID?.() ?? String(Date.now());
job.current = id;
setScanning(true);
setError(null);
setFiles(null);
setPicked(new Set());
setProgress(null);
const stop = await subscribeJobProgress(id, (event) => {
if (event.event === "metered") {
setProgress(event);
} else if (event.event === "tick" || event.event === "phase") {
setProgress(event);
}
});
try {
const found = await apiClient.api.largeFilesScan(
id,
scope,
threshold,
klass === "all" ? null : klass,
);
setFiles(found);
} catch (reason) {
if (!messageFrom(reason).toLowerCase().includes("cancel")) {
setError(messageFrom(reason));
}
} finally {
stop();
setScanning(false);
job.current = null;
}
}, [klass, scanning, scope, threshold]);
const visible = useMemo(() => {
if (!files) return null;
return files.filter((file) => !hideCritical || !file.maybeMounted);
}, [files, hideCritical]);
const totalBytes = visible?.reduce((sum, file) => sum + file.size, 0) ?? 0;
const pickedBytes = visible
?.filter((file) => picked.has(file.path))
.reduce((sum, file) => sum + file.size, 0) ?? 0;
const pickedCount = picked.size;
// Hub badge: found files, or null before a scan.
useEffect(() => {
if (!embedded || !onBadge) return;
onBadge(
visible && visible.length > 0
? `${formatCount(visible.length)} 个 · ${formatBytes(totalBytes)}`
: null,
);
}, [embedded, onBadge, totalBytes, visible]);
const toggle = (path: string) => {
setPicked((current) => {
const next = new Set(current);
if (next.has(path)) next.delete(path);
else next.add(path);
return next;
});
};
const confirmDelete = async () => {
const id = crypto.randomUUID?.() ?? String(Date.now());
job.current = id;
setDeleting(true);
setProgress(null);
const stop = await subscribeJobProgress(id, (event) => {
if (event.event === "tick" || event.event === "deleted") setProgress(event);
});
const startedAt = Date.now();
try {
const outcome = await apiClient.api.largeFilesDelete(id, [...picked], "trash");
setFiles((current) => current?.filter((f) => !picked.has(f.path)) ?? null);
setPicked(new Set());
setConfirming(false);
setCleanDone({ outcome, elapsedMs: Date.now() - startedAt });
push(
lang === "zh"
? `已将 ${outcome.removed} 个大文件移入回收站(${formatBytes(outcome.freed)}),可在「历史记录」撤销`
: `Moved ${outcome.removed} files to the Recycle Bin (${formatBytes(outcome.freed)})`,
"success",
);
} catch (reason) {
setError(messageFrom(reason));
} finally {
stop();
setDeleting(false);
job.current = null;
}
};
const now = Date.now();
return (
<div className={`page bigfiles-page ${embedded ? "is-embedded" : ""}`}>
{embedded ? null : (
<PageHeader
title={t("Large files", "大文件")}
/>
)}
{error ? <InlineError message={error} onDismiss={() => setError(null)} /> : null}
<section className="bigfiles-config">
<span className="dup-config-label">{t("Scope", "范围")}</span>
<div className="dup-seg" role="group">
<button
type="button"
className={scope.length === 0 ? "is-active" : ""}
onClick={() => setScope([])}
>
{t("All local drives", "全部本地磁盘")}
</button>
{["C:", "D:", "E:"].map((drive) => (
<button
key={drive}
type="button"
className={scope.length === 1 && scope[0] === `${drive}\\` ? "is-active" : ""}
onClick={() => setScope([`${drive}\\`])}
>
{drive}
</button>
))}
</div>
<span className="dup-config-label">{t("At least", "阈值")}</span>
<div className="dup-seg" role="group">
{THRESHOLDS.map((option) => (
<button
key={option.value}
type="button"
className={threshold === option.value ? "is-active" : ""}
onClick={() => setThreshold(option.value)}
>
{option.label}
</button>
))}
</div>
<span className="dup-config-label">{t("Type", "类型")}</span>
<div className="dup-seg is-classes" role="group">
{CLASSES.map((option) => {
const Icon = option.icon;
return (
<button
key={option.id}
type="button"
className={klass === option.id ? "is-active" : ""}
onClick={() => setKlass(option.id)}
>
<Icon size={12} /> {lang === "zh" ? option.zh : option.en}
</button>
);
})}
</div>
<Button
size="lg"
variant="primary"
className="scan-cta"
icon={<ScanSearch size={16} />}
onClick={() => void run()}
disabled={scanning || deleting}
>
{scanning
? t("Scanning…", "扫描中…")
: files
? t("Rescan", "重新扫描")
: t("Start scan", "开始扫描")}
</Button>
</section>
{scanning ? (
<ProgressCard
progress={progress}
title={t("Scanning for large files", "正在查找大文件")}
onCancel={() => {
if (job.current) void apiClient.api.cancelJob(job.current);
}}
/>
) : null}
{deleting ? (
<CleanBar
spec={{ phase: "busy" }}
progress={progress}
noun={["个大文件", "files"]}
mode="trash"
onHistory={() => onHistory?.()}
onDismiss={() => undefined}
/>
) : null}
{!deleting && cleanDone ? (
<CleanBar
spec={{ phase: "done", outcome: cleanDone.outcome, elapsedMs: cleanDone.elapsedMs }}
progress={null}
noun={["个大文件", "files"]}
mode="trash"
onHistory={() => onHistory?.()}
onDismiss={() => setCleanDone(null)}
onRescan={() => void run()}
/>
) : null}
{!files && !scanning ? (
<EmptyState
icon={<FileQuestion size={26} />}
title={t("No large-file scan yet", "还没有扫描过大文件")}
description={t(
"Start scan walks every drive above the size floor; results sort heaviest first.",
"点击「开始扫描」按体积门槛遍历所选磁盘,结果从最大往下排。",
)}
/>
) : null}
{visible && visible.length === 0 && !scanning ? (
<EmptyState
icon={<HardDrive size={26} />}
title={t("No files above the threshold", "没有超过阈值的大文件")}
description={t(
"Try a lower size floor or another scope.",
"可以调低体积门槛或更换扫描范围再试。",
)}
/>
) : null}
{visible && visible.length > 0 ? (
<>
<section className="bigfiles-list-head">
<div>
<b>
{formatCount(visible.length)} {t("large files", "个大文件")} ·{" "}
<span className="is-accent">{formatBytes(totalBytes)}</span>
</b>
<small>
{pickedCount > 0
? t(
`${pickedCount} selected · ${formatBytes(pickedBytes)} → Recycle Bin`,
`已选 ${pickedCount} 项 · ${formatBytes(pickedBytes)} → 移入回收站`,
)
: t(
"Dormant files (180 days untouched) are tagged; disk images held by Hyper-V/WSL stay locked. Page files are hidden; hiberfil.sys frees via turning hibernation off.",
"长期未修改(180 天+)的文件会带休眠标记;被 Hyper-V/WSL 使用的镜像会锁定。页面文件(pagefile/swapfile)已自动隐藏;hiberfil.sys 可通过关闭休眠释放。",
)}
</small>
</div>
<label className="bigfiles-hide-critical">
<Checkbox
checked={hideCritical}
onChange={() => setHideCritical((v) => !v)}
label={t("Hide system-critical images", "隐藏系统关键镜像")}
/>
<span>{t("Hide system-critical", "隐藏系统关键文件")}</span>
</label>
<Button
variant="danger"
disabled={pickedCount === 0 || deleting}
onClick={() => setConfirming(true)}
>
<Trash2 size={14} />
<span>{t("Clean selected", "清理已选")}</span>
</Button>
</section>
{confirming ? (
<section className="dup-confirm">
<ShieldAlert size={15} />
<div>
<b>
{lang === "zh"
? `将 ${pickedCount} 个大文件(${formatBytes(pickedBytes)})移入回收站?`
: `Move ${pickedCount} files (${formatBytes(pickedBytes)}) to the Recycle Bin?`}
</b>
<small>
{t(
"Undo from History while the Recycle Bin holds them.",
"回收站清空前,可随时在「历史记录」撤销。",
)}
</small>
</div>
<Button onClick={() => setConfirming(false)}>{t("Cancel", "取消")}</Button>
<Button variant="danger" disabled={deleting} onClick={() => void confirmDelete()}>
{deleting ? t("Cleaning…", "清理中…") : t("Confirm", "确认清理")}
</Button>
</section>
) : null}
<ul className="bigfiles-list">
{visible.map((file, index) => {
const Icon = CLASS_ICON[file.class] ?? HardDrive;
const dormant =
file.modifiedMs > 0 && (now - file.modifiedMs) / 1000 > DORMANT_SECS;
return (
<li key={file.path} className={`bigfile-row ${picked.has(file.path) ? "is-picked" : ""}`}>
<Checkbox
checked={picked.has(file.path)}
onChange={() => toggle(file.path)}
label={file.displayPath}
/>
<span className="bigfile-index">{String(index + 1).padStart(2, "0")}</span>
<span className="bigfile-icon">
<Icon size={15} />
</span>
<div className="bigfile-main">
<b>{file.path.split(/[\\/]/).pop()}</b>
<span className="bigfile-path">{file.displayPath}</span>
</div>
{dormant ? (
<span className="space-rule-dormant">
{agoLabel(file.modifiedMs, lang)} {t("untouched", "未修改")}
</span>
) : null}
{file.cloudHint ? (
<span className="bigfile-cloud-chip">
<Cloud size={11} /> {t("cloud copy?", "网盘可能有副本?")}
</span>
) : null}
{file.maybeMounted ? (
<span className="dup-lock-chip" title={t("May be in use by Hyper-V/WSL", "可能正被 Hyper-V/WSL 使用")}>
<Lock size={11} /> {t("check in use", "占用检查")}
</span>
) : null}
<span className="bigfile-size">{formatBytes(file.size)}</span>
<button
type="button"
className="dup-copy-reveal"
onClick={() => void apiClient.api.revealPath(file.path).catch(() => undefined)}
title={t("Reveal in Explorer", "在文件夹中显示")}
>
<MapPin size={12} />
{t("Reveal", "定位")}
</button>
</li>
);
})}
</ul>
</>
) : null}
</div>
);
}

View File

@ -0,0 +1,65 @@
import { EyeOff, SlidersHorizontal, Wrench } from "lucide-react";
import { useEffect, useState } from "react";
import { useI18n } from "../i18n";
import { PageHeader } from "../components/ui";
import { MaintenancePage } from "./MaintenancePage";
import { PrivacyPage } from "./PrivacyPage";
import { OptimizationPage } from "./OptimizationPage";
/* 系统维护 hub(方案②):一键修复 / 隐私清理 / 系统优化 三页签。
* 面板全部保持挂载(display 切换),修复任务运行中切页签不会打断
* 日志流;徽标由面板回报(隐私=痕迹数、优化=已更改数)。 */
export type MaintTab = "repair" | "privacy" | "optimize";
const TABS: { id: MaintTab; icon: typeof Wrench; en: string; zh: string }[] = [
{ id: "repair", icon: Wrench, en: "One-click repairs", zh: "一键修复" },
{ id: "privacy", icon: EyeOff, en: "Privacy cleaning", zh: "隐私清理" },
{ id: "optimize", icon: SlidersHorizontal, en: "System optimisation", zh: "系统优化" },
];
export function MaintenanceHubPage({ initialTab = "repair" }: { initialTab?: MaintTab }) {
const { t } = useI18n();
const [tab, setTab] = useState<MaintTab>(initialTab);
useEffect(() => setTab(initialTab), [initialTab]);
const [badges, setBadges] = useState<Partial<Record<MaintTab, string | null>>>({});
const report = (id: MaintTab) => (value: string | null) =>
setBadges((current) => (current[id] === value ? current : { ...current, [id]: value }));
return (
<div className="page hub-page">
<PageHeader
title={t("System maintenance", "系统维护")}
/>
<div className="hub-tabs" role="tablist">
{TABS.map((item) => {
const Icon = item.icon;
const badge = badges[item.id];
return (
<button
key={item.id}
type="button"
role="tab"
aria-selected={tab === item.id}
className={`hub-tab ${tab === item.id ? "is-active" : ""}`}
onClick={() => setTab(item.id)}
>
<Icon size={15} />
{t(item.en, item.zh)}
{badge ? <b>{badge}</b> : null}
</button>
);
})}
</div>
<div className="hub-pane" style={{ display: tab === "repair" ? undefined : "none" }}>
<MaintenancePage embedded onBadge={report("repair")} />
</div>
<div className="hub-pane" style={{ display: tab === "privacy" ? undefined : "none" }}>
<PrivacyPage embedded onBadge={report("privacy")} />
</div>
<div className="hub-pane" style={{ display: tab === "optimize" ? undefined : "none" }}>
<OptimizationPage embedded onBadge={report("optimize")} />
</div>
</div>
);
}

View File

@ -0,0 +1,213 @@
import {
Activity,
AlertTriangle,
Check,
Search,
ShieldCheck,
Wrench,
X,
} from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { api, subscribeJobProgress } from "../lib/api";
import { useI18n } from "../i18n";
import { messageFrom } from "../lib/format";
import {
Button,
InlineError,
PageHeader,
ProgressCard,
useToast,
} from "../components/ui";
import type { JobProgress, MaintenanceResult, MaintenanceTask } from "../types";
const RISK_CHIP: Record<MaintenanceTask["risk"], [string, string, string]> = {
// [class, zh, en]
safe: ["is-safe", "安全", "Safe"],
admin: ["is-admin", "需要管理员", "Admin rights"],
slow: ["is-slow", "较慢", "Slow"],
};
export function MaintenancePage({
embedded = false,
onBadge,
}: {
/** Rendered inside 系统维护 hub: page title hides, task count flows up. */
embedded?: boolean;
onBadge?: (value: string | null) => void;
} = {}) {
const { t, lang } = useI18n();
const { push } = useToast();
const [tasks, setTasks] = useState<MaintenanceTask[]>([]);
const [running, setRunning] = useState<string | null>(null);
const [progress, setProgress] = useState<JobProgress | null>(null);
const [logs, setLogs] = useState<string[]>([]);
const [result, setResult] = useState<MaintenanceResult | null>(null);
const [error, setError] = useState<string | null>(null);
const job = useRef<string | null>(null);
useEffect(() => {
if (embedded && onBadge) onBadge(tasks.length > 0 ? `${tasks.length} 项` : null);
}, [embedded, onBadge, tasks.length]);
useEffect(() => {
let alive = true;
void api
.maintenanceTasks()
.then((list) => alive && setTasks(list))
.catch((reason) => alive && setError(messageFrom(reason)));
return () => {
alive = false;
};
}, []);
const runTask = useCallback(
async (task: MaintenanceTask) => {
if (running) return;
const id = crypto.randomUUID?.() ?? String(Date.now());
job.current = id;
setRunning(task.id);
setResult(null);
setError(null);
setLogs([]);
setProgress(null);
const stop = await subscribeJobProgress(id, (event) => {
if (event.event === "note" && event.detail) {
setLogs((current) => [...current.slice(-200), event.detail as string]);
}
setProgress(event);
});
try {
const outcome = await api.maintenanceRun(id, task.id);
setResult(outcome);
if (outcome.ok) {
push(
lang === "zh"
? `${task.titleZh}:完成(用时 ${Math.round(outcome.durationMs / 1000)} 秒)`
: `${task.titleEn}: done (${Math.round(outcome.durationMs / 1000)}s)`,
"success",
);
} else {
push(
lang === "zh"
? `${task.titleZh}:在「${outcome.failedStep ?? "某一步"}」失败`
: `${task.titleEn}: failed at ${outcome.failedStep ?? "a step"}`,
"danger",
);
}
} catch (reason) {
setError(messageFrom(reason));
} finally {
stop();
setRunning(null);
setProgress(null);
job.current = null;
}
},
[lang, push, running],
);
return (
<div className={`page maintenance-page ${embedded ? "is-embedded" : ""}`}>
{embedded ? null : (
<PageHeader
title={t("System maintenance", "系统维护")}
/>
)}
{error ? <InlineError message={error} onDismiss={() => setError(null)} /> : null}
<div className="maint-summary">
<ShieldCheck size={15} />
<span>
{t(
"All repairs below touch only system caches / services / indexes — never your documents.",
"以下修复只影响系统缓存 / 服务 / 索引,不碰你的文档。",
)}
</span>
</div>
<ul className="maint-list">
{tasks.map((task) => {
const [chipClass, chipZh, chipEn] = RISK_CHIP[task.risk];
const isRunning = running === task.id;
return (
<li key={task.id} className={`maint-row ${isRunning ? "is-running" : ""}`}>
<span className="maint-icon">
<Wrench size={16} />
</span>
<div className="maint-copy">
<b>{lang === "zh" ? task.titleZh : task.titleEn}</b>
<small>{lang === "zh" ? task.detailZh : task.detailEn}</small>
{isRunning && progress ? (
<ProgressCard
progress={progress}
title={lang === "zh" ? task.titleZh : task.titleEn}
compact
onCancel={() => {
if (job.current) void api.cancelJob(job.current);
}}
/>
) : null}
{isRunning && logs.length > 0 ? (
<pre className="maint-log" role="status">
{logs.slice(-8).join("\n")}
</pre>
) : null}
</div>
<span className="maint-estimate">{task.estimate}</span>
<span className={`maint-risk ${chipClass}`}>{lang === "zh" ? chipZh : chipEn}</span>
{isRunning ? (
<Button variant="ghost" size="sm" onClick={() => job.current && void api.cancelJob(job.current)}>
{t("Cancel", "取消")}
</Button>
) : (
<Button
variant="primary"
size="sm"
disabled={running !== null}
onClick={() => void runTask(task)}
>
{t("Repair", "修复")}
</Button>
)}
</li>
);
})}
{tasks.length === 0 && !error ? (
<li className="maint-row is-muted">
<Search size={16} />
{t("Loading the repair list…", "正在加载修复清单…")}
</li>
) : null}
</ul>
{result ? (
<div className={`maint-result ${result.ok ? "is-ok" : "is-fail"}`}>
{result.ok ? <Check size={15} /> : <AlertTriangle size={15} />}
<div>
<b>
{result.ok
? t("Repair completed", "修复完成")
: t("Repair stopped early", "修复提前停止")}
</b>
<ul>
{result.steps.map((step, index) => (
<li key={index}>
<Activity size={11} /> {step}
</li>
))}
</ul>
{result.outputTail ? (
<details>
<summary>{t("Command output", "命令输出")}</summary>
<pre>{result.outputTail}</pre>
</details>
) : null}
</div>
<Button variant="ghost" size="sm" onClick={() => setResult(null)}>
<X size={13} />
</Button>
</div>
) : null}
</div>
);
}

View File

@ -0,0 +1,147 @@
import { RotateCcw, SlidersHorizontal } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { api } from "../lib/api";
import { useI18n } from "../i18n";
import { messageFrom } from "../lib/format";
import { Button, InlineError, PageHeader, Toggle, useToast } from "../components/ui";
import type { TweakState } from "../types";
export function OptimizationPage({
embedded = false,
onBadge,
}: {
/** Rendered inside 系统维护 hub: page title hides, changed count flows up. */
embedded?: boolean;
onBadge?: (value: string | null) => void;
} = {}) {
const { t, lang } = useI18n();
const { push } = useToast();
const [states, setStates] = useState<TweakState[]>([]);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState<string | null>(null);
const refresh = useCallback(async () => {
try {
setStates(await api.tweaksStates());
} catch (reason) {
setError(messageFrom(reason));
}
}, []);
useEffect(() => {
void refresh();
}, [refresh]);
const flip = async (tweak: TweakState, next: boolean) => {
setBusy(tweak.id);
setError(null);
try {
const state = await api.tweaksSet(tweak.id, next);
setStates((current) => current.map((row) => (row.id === state.id ? state : row)));
} catch (reason) {
setError(messageFrom(reason));
} finally {
setBusy(null);
}
};
const changed = states.filter((state) => state.recorded).length;
// Hub badge: how many tweaks have been flipped so far (null when none).
useEffect(() => {
if (!embedded || !onBadge) return;
onBadge(changed > 0 ? `已更改 ${changed} 项` : null);
}, [changed, embedded, onBadge]);
const restoreAll = async () => {
setBusy("__all__");
try {
const restored = await api.tweaksRestoreAll();
push(
lang === "zh"
? `已恢复 ${restored.length} 项为系统默认值`
: `Restored ${restored.length} tweaks to system defaults`,
"success",
);
await refresh();
} catch (reason) {
setError(messageFrom(reason));
} finally {
setBusy(null);
}
};
return (
<div className={`page optimize-page ${embedded ? "is-embedded" : ""}`}>
{embedded ? null : (
<PageHeader
title={t("System optimisation", "系统优化")}
actions={
<Button variant="secondary" icon={<RotateCcw size={14} />} disabled={busy !== null || changed === 0} onClick={() => void restoreAll()}>
{t("Restore all defaults", "恢复全部默认")}
</Button>
}
/>
)}
{error ? <InlineError message={error} onDismiss={() => setError(null)} /> : null}
<section className="optimize-group">
<div className="optimize-group-head">
<h2>
<SlidersHorizontal size={15} /> {t("Everyday privacy & clarity", "常用隐私与界面")}
</h2>
<span className="tip">
{changed > 0
? t(`${changed} changed · revertable`, `已更改 ${changed} 项 · 可随时恢复`)
: t("Nothing changed yet", "尚未更改任何项")}
</span>
{/* Embedded (维护 hub): the page header — and with it the restore
button — is hidden, so the group head carries it instead. */}
{embedded ? (
<Button
variant="ghost"
size="sm"
icon={<RotateCcw size={13} />}
disabled={busy !== null || changed === 0}
onClick={() => void restoreAll()}
>
{t("Restore all defaults", "恢复全部默认")}
</Button>
) : null}
</div>
<ul className="optimize-list">
{states.map((state) => (
<li key={state.id} className={`optimize-row ${state.enabled ? "is-on" : ""}`}>
<div className="optimize-copy">
<b>
{lang === "zh" ? state.titleZh : state.titleEn}
{state.restartHint && state.enabled ? (
<span className="optimize-restart">
{t("needs Explorer/Windows restart", "需重启 Explorer/系统生效")}
</span>
) : null}
</b>
<small>{lang === "zh" ? state.detailZh : state.detailEn}</small>
<small className="optimize-path">
{state.hive}\\{state.key} · {state.value}
</small>
</div>
<span className={`optimize-risk is-${state.risk}`}>
{state.risk === "safe" ? t("Safe", "安全") : t("Read the note", "看说明")}
</span>
<Toggle
checked={state.enabled}
disabled={busy !== null || state.unreadable}
onChange={(next) => void flip(state, next)}
label={lang === "zh" ? state.titleZh : state.titleEn}
/>
</li>
))}
</ul>
{states.length === 0 && !error ? (
<p className="optimize-empty">{t("Loading the catalog…", "正在加载目录…")}</p>
) : null}
</section>
</div>
);
}

View File

@ -14,15 +14,12 @@ import {
WandSparkles,
Waypoints,
} from "lucide-react";
import type { ReactNode } from "react";
import { useI18n } from "../i18n";
import {
formatBytes,
formatCount,
formatMemoryBytes,
percent,
} from "../lib/format";
import type { Bootstrap, PageId, SystemSnapshot, Volume } from "../types";
import { formatBytes, formatCount, formatMemory, percent } from "../lib/format";
import type { Bootstrap, SystemSnapshot, Volume } from "../types";
import type { ScanWorkspace } from "../hooks/useScanWorkspace";
import type { PageId } from "../types";
import { CategorySummary } from "../components/CleanupView";
import {
Button,
@ -45,26 +42,87 @@ function greeting(lang: "zh" | "en"): string {
return "Good evening";
}
function coreLabel(snapshot: SystemSnapshot | null, t: (en: string, zh: string) => string) {
if (!snapshot) return t("Reading processor…", "正在读取处理器…");
const { physical_cores: physical, logical_cores: logical } = snapshot.cpu;
if (physical === logical) {
return t(`${physical} cores`, `${physical} 核`);
}
return t(`${physical} cores / ${logical} threads`, `${physical} 核 / ${logical} 线程`);
/// Windows mounts read `C:\`; everything else shows its own label.
function driveLabel(volume: Volume): string {
return /^[A-Za-z]:/.exec(volume.mount_point)?.[0] ?? volume.mount_point;
}
function machineRows(
bootstrap: Bootstrap,
snapshot: SystemSnapshot | null,
volume: Volume | null,
t: (en: string, zh: string) => string,
) {
const hardware = bootstrap.hardwareInfo;
const model = bootstrap.hardware.split(" · ")[0]?.trim() || bootstrap.hardware;
const installed = snapshot
function SpecRow({
icon,
label,
value,
t,
}: {
icon: ReactNode;
label: string;
value: string;
t: (en: string, zh: string) => string;
}) {
return (
<div className="spec-row">
<span className="spec-icon">{icon}</span>
<span className="spec-label">{label}</span>
<strong title={value || undefined}>{value || t("—", "—")}</strong>
</div>
);
}
export function OverviewPage({
bootstrap,
snapshot,
cleanup,
purge,
onNavigate,
onOpenSpaceTab,
}: {
bootstrap: Bootstrap;
snapshot: SystemSnapshot | null;
cleanup: ScanWorkspace;
purge: ScanWorkspace;
onNavigate: (page: PageId) => void;
/** Deep-link into a 空间清理 hub tab (重复文件 / 大文件). */
onOpenSpaceTab?: (tab: "junk" | "dups" | "big") => void;
}) {
const { t, lang } = useI18n();
const volumes = snapshot?.volumes ?? [];
const rootVolume = volumes.find((candidate) => candidate.is_root) ?? volumes[0] ?? null;
const memoryInstalled = snapshot
? Math.max(snapshot.memory.installed, snapshot.memory.total)
: 0;
const memoryReserved = snapshot
? Math.max(0, memoryInstalled - snapshot.memory.total)
: 0;
const scanned = Boolean(cleanup.result || purge.result);
const scanning = cleanup.scanning || purge.scanning;
const found = [cleanup, purge].reduce(
(sum, workspace) =>
sum +
(workspace.result
? workspace.result.items
.filter((item) => !item.lock)
.reduce((total, item) => total + item.onDisk, 0)
: 0),
0,
);
// 智能扫描 is an entry point, not a resident process: the moment it is
// pressed we hand the page over to 空间清理 and launch both scan stages
// there (SpacePage owns the settings — age threshold, auto-discovery).
// A finished scan keeps the button as a shortcut back to the results.
const smartScan = () => {
onNavigate("space");
if (!scanned && !scanning) {
void cleanup.runScan().then(() =>
purge.runScan({
// Empty = engine auto-discovery of project containers.
roots: [],
minAgeDays: bootstrap.settings.purgeMinAgeDays || 7,
force: false,
}),
);
}
};
const hardware = bootstrap.hardwareInfo;
const ramBrands = [
...new Set(hardware.memory_sticks.map((stick) => stick.manufacturer).filter(Boolean)),
].join(" / ");
@ -72,112 +130,40 @@ function machineRows(
(top, stick) => Math.max(top, stick.speed_mhz),
0,
);
const memory = [
installed ? formatMemoryBytes(installed) : "",
ramBrands,
ramSpeed ? `${ramSpeed} MT/s` : "",
]
.filter(Boolean)
.join(" · ");
const disk = [
[hardware.disk_vendor, hardware.disk_model].filter(Boolean).join(" "),
hardware.disk_size_bytes ? formatBytes(hardware.disk_size_bytes, 0) : "",
hardware.disk_bus,
]
.filter(Boolean)
.join(" · ");
const gpu = [
hardware.gpu_model &&
hardware.gpu_model.toLowerCase().startsWith(hardware.gpu_vendor.toLowerCase())
? hardware.gpu_model
: [hardware.gpu_vendor, hardware.gpu_model].filter(Boolean).join(" "),
hardware.gpu_vram_bytes ? formatBytes(hardware.gpu_vram_bytes, 0) : "",
]
.filter(Boolean)
.join(" · ");
const rows = [
{
key: "os",
icon: MonitorCog,
label: t("Operating system", "操作系统"),
value: bootstrap.osVersion || bootstrap.osName,
},
{
key: "model",
icon: CircuitBoard,
label: t("Computer", "本机型号"),
value: hardware.board || model,
},
{
key: "cpu",
icon: Cpu,
label: t("Processor", "处理器"),
value: snapshot
? snapshot.cpu.brand || t("Unknown processor", "未知处理器")
: t("Reading processor…", "正在读取处理器…"),
},
{
key: "memory",
icon: MemoryStick,
label: t("Memory", "内存"),
value: memory || t("Reading memory…", "正在读取内存…"),
},
{
key: "disk",
icon: HardDrive,
label: t("Primary disk", "主硬盘"),
value:
disk ||
(volume
? `${volume.name || volume.mount_point} · ${formatBytes(volume.total, 0)} · ${volume.filesystem.toUpperCase()}`
: t("Reading disks…", "正在读取磁盘…")),
},
];
if (gpu || snapshot?.host.gpu) {
rows.push({
key: "gpu",
icon: Waypoints,
label: t("Graphics", "显卡"),
value: gpu || snapshot?.host.gpu || "",
});
}
return rows;
}
export function OverviewPage({
bootstrap,
snapshot,
cleanup,
onNavigate,
}: {
bootstrap: Bootstrap;
snapshot: SystemSnapshot | null;
cleanup: ScanWorkspace;
onNavigate: (page: PageId) => void;
}) {
const { t, lang } = useI18n();
const volumes = snapshot?.volumes ?? [];
const rootVolume = volumes.find((candidate) => candidate.is_root) ?? volumes[0] ?? null;
const used = rootVolume ? rootVolume.total - rootVolume.free : 0;
const usedPercent = rootVolume ? percent(used, rootVolume.total) : 0;
const memoryPercent = snapshot
? percent(snapshot.memory.used, snapshot.memory.total)
: 0;
const memoryInstalled = snapshot
? Math.max(snapshot.memory.installed, snapshot.memory.total)
: 0;
const memoryReserved = snapshot
? Math.max(0, memoryInstalled - snapshot.memory.total)
: 0;
const found = cleanup.result
? cleanup.result.items
.filter((item) => !item.lock)
.reduce((sum, item) => sum + item.onDisk, 0)
: 0;
const visibleVolumes = (snapshot?.volumes ?? []).slice(0, 2);
const startScan = () => {
if (cleanup.result) onNavigate("cleanup");
else void cleanup.runScan();
const specs = {
os: bootstrap.osVersion,
board: hardware.board || bootstrap.hardware,
cpu: snapshot
? `${snapshot.cpu.brand} · ${snapshot.cpu.physical_cores} ${t("cores", "核")} / ${
snapshot.cpu.logical_cores
} ${t("threads", "线程")}`
: hardware.cpu_model,
memory:
[
memoryInstalled ? formatMemory(memoryInstalled) : "",
ramBrands,
ramSpeed ? `${ramSpeed} MT/s` : "",
]
.filter(Boolean)
.join(" · ") || (memoryReserved ? formatMemory(memoryInstalled) : ""),
disk:
[
[hardware.disk_vendor, hardware.disk_model].filter(Boolean).join(" "),
hardware.disk_size_bytes ? formatBytes(hardware.disk_size_bytes) : "",
hardware.disk_bus,
]
.filter(Boolean)
.join(" · "),
gpu:
[
hardware.gpu_model &&
hardware.gpu_model.toLowerCase().startsWith(hardware.gpu_vendor.toLowerCase())
? hardware.gpu_model
: [hardware.gpu_vendor, hardware.gpu_model].filter(Boolean).join(" "),
hardware.gpu_vram_bytes ? formatBytes(hardware.gpu_vram_bytes) : "",
]
.filter(Boolean)
.join(" · "),
};
return (
@ -185,21 +171,6 @@ export function OverviewPage({
<PageHeader
eyebrow={`${greeting(lang)} · ${bootstrap.osName}`}
title={t("Your computer, at its best", "让电脑始终保持在最佳状态")}
actions={
<Button
variant="primary"
size="lg"
icon={<Sparkles size={17} />}
onClick={startScan}
disabled={cleanup.scanning}
>
{cleanup.scanning
? t("Scanning…", "扫描中…")
: cleanup.result
? t("Review smart scan", "查看智能扫描")
: t("Smart scan", "智能扫描")}
</Button>
}
/>
<section className="overview-hero">
@ -209,7 +180,7 @@ export function OverviewPage({
{t("Smart Care", "智能维护")}
</div>
<h2>
{cleanup.result
{scanned
? t(
`${formatBytes(found)} found safely`,
`安全发现 ${formatBytes(found)} 可清理空间`,
@ -217,7 +188,7 @@ export function OverviewPage({
: t("A lighter, faster machine", "更轻盈,更顺畅")}
</h2>
<p>
{cleanup.result
{scanned
? t(
"Review each category before anything is removed. Locked files stay untouched.",
"清理前可逐项检查,锁定文件始终不会被处理。",
@ -230,20 +201,20 @@ export function OverviewPage({
<div className="hero-actions">
<Button
variant="primary"
icon={cleanup.result ? <ArrowRight size={16} /> : <ScanSearch size={16} />}
onClick={startScan}
disabled={cleanup.scanning}
icon={scanned ? <ArrowRight size={16} /> : <ScanSearch size={16} />}
onClick={smartScan}
disabled={scanning}
>
{cleanup.result
{scanned
? t("Choose what to clean", "选择清理项目")
: t("Start smart scan", "开始智能扫描")}
: t("Start a smart scan", "开始智能扫描")}
</Button>
<Button
variant="secondary"
variant="primary"
icon={<CircleGauge size={16} />}
onClick={() => onNavigate("system")}
>
{t("Live monitor", "实时监控")}
{t("Live system", "实时监控")}
</Button>
</div>
<div className="hero-assurances">
@ -253,173 +224,192 @@ export function OverviewPage({
</div>
</div>
<aside className="overview-machine">
<span className="machine-title">{t("This machine", "本机配置")}</span>
<div className="machine-list">
{machineRows(bootstrap, snapshot, rootVolume, t).map((row) => {
const Icon = row.icon;
return (
<div className="machine-row" key={row.key}>
<span className="machine-icon">
<Icon size={15} />
</span>
<span className="machine-label">{row.label}</span>
<strong title={row.value}>{row.value}</strong>
</div>
);
})}
</div>
</aside>
<div className="overview-specs">
<span className="specs-kicker">{t("This machine", "本机配置")}</span>
<SpecRow
icon={<MonitorCog size={15} />}
label={t("System", "操作系统")}
value={specs.os}
t={t}
/>
<SpecRow
icon={<CircuitBoard size={15} />}
label={t("Motherboard", "主板")}
value={specs.board}
t={t}
/>
<SpecRow
icon={<Cpu size={15} />}
label={t("Processor", "处理器")}
value={specs.cpu}
t={t}
/>
<SpecRow
icon={<MemoryStick size={15} />}
label={t("Memory", "内存")}
value={specs.memory}
t={t}
/>
<SpecRow
icon={<HardDrive size={15} />}
label={t("Primary disk", "主硬盘")}
value={specs.disk}
t={t}
/>
<SpecRow
icon={<Waypoints size={15} />}
label={t("Graphics", "显卡")}
value={specs.gpu}
t={t}
/>
</div>
</section>
{cleanup.scanning ? (
{scanning ? (
<ProgressCard
progress={cleanup.progress}
progress={cleanup.progress ?? purge.progress}
title={t("Looking for safe things to clean…", "正在查找可安全清理的项目…")}
onCancel={() => void cleanup.cancel()}
onCancel={() => void (cleanup.scanning ? cleanup.cancel() : purge.cancel())}
/>
) : null}
{scanned && !scanning ? (
<section className="overview-found">
<SectionTitle
title={t("What the scan found", "扫描发现")}
subtitle={t(
"Uncheck anything you want to keep.",
"不想清理的项目可以随时取消勾选。",
)}
action={
<Button variant="ghost" size="sm" onClick={() => onNavigate("space")}>
{t("Open space cleaning", "打开空间清理")}
<ChevronRight size={14} />
</Button>
}
/>
{cleanup.result ? (
<CategorySummary
result={cleanup.result}
selected={cleanup.selected}
onToggle={cleanup.toggleCategory}
onInspect={() => onNavigate("space")}
/>
) : null}
</section>
) : null}
{/* 指标行 30% / 42% / 28%:处理器+内存共用一框上下分布;存储每盘
一行;日常维护三入口竖排放右列,与左两卡等高。独立的「日常维护」
区块随此改版取消。 */}
<section className="overview-metrics">
<article className="metric-panel">
<div className="metric-panel-head">
<span className="metric-icon tone-primary">
<Cpu size={18} />
</span>
<div>
<strong>{t("Processor", "处理器")}</strong>
<span>{coreLabel(snapshot, t)}</span>
</div>
<b>{Math.round(snapshot?.cpu.total ?? 0)}%</b>
</div>
<UsageBar used={snapshot?.cpu.total ?? 0} total={100} tone="primary" />
<small>
{snapshot?.cpu.brand || t("Processor details unavailable", "暂无处理器信息")}
</small>
</article>
<article className="metric-panel">
<div className="metric-panel-head">
<span className="metric-icon tone-violet">
<MemoryStick size={18} />
</span>
<div>
<strong>{t("Memory", "内存")}</strong>
<span>
{snapshot
? `${formatMemoryBytes(snapshot.memory.used)} / ${formatMemoryBytes(
memoryInstalled,
)}`
: t("Sampling…", "正在采样…")}
<div className="metric-panel metric-combo">
<div className="m-block">
<div className="metric-panel-head">
<span className="metric-icon tone-blue">
<CircleGauge size={18} />
</span>
<div>
<strong>{t("Processor", "处理器")}</strong>
<span>
{snapshot
? `${snapshot.cpu.physical_cores} ${t("cores", "核")} / ${snapshot.cpu.logical_cores} ${t("threads", "线程")}`
: t("Sampling…", "正在采样…")}
</span>
</div>
<b>{Math.round(snapshot?.cpu.total ?? 0)}%</b>
</div>
<b>{Math.round(memoryPercent)}%</b>
<UsageBar used={snapshot?.cpu.total ?? 0} total={100} tone="blue" />
<small>
{snapshot?.cpu.brand || t("Processor details unavailable", "暂无处理器信息")}
</small>
</div>
<UsageBar used={memoryPercent} total={100} tone="violet" />
<small>
{memoryReserved > 0
? t(
`Hardware reserved (integrated graphics): ${formatMemoryBytes(memoryReserved)}`,
`硬件保留(含核显):${formatMemoryBytes(memoryReserved)}`,
)
: snapshot?.memory.compressed !== null &&
snapshot?.memory.compressed !== undefined
? t(
`Compressed ${formatMemoryBytes(snapshot.memory.compressed)} · Wired ${formatMemoryBytes(
snapshot.memory.wired ?? 0,
)}`,
`压缩 ${formatMemoryBytes(snapshot.memory.compressed)} · 固定 ${formatMemoryBytes(
snapshot.memory.wired ?? 0,
)}`,
)
: snapshot
<div className="m-block">
<div className="metric-panel-head">
<span className="metric-icon tone-violet">
<Boxes size={18} />
</span>
<div>
<strong>{t("Memory", "内存")}</strong>
<span>
{snapshot
? `${formatMemory(snapshot.memory.used)} / ${formatMemory(memoryInstalled)}`
: t("Sampling…", "正在采样…")}
</span>
</div>
<b>
{Math.round(
snapshot ? percent(snapshot.memory.used, snapshot.memory.total) : 0,
)}
%
</b>
</div>
<UsageBar
used={snapshot ? percent(snapshot.memory.used, snapshot.memory.total) : 0}
total={100}
tone="violet"
/>
<small>
{memoryReserved > 0
? t(
`${formatCount(snapshot.processes)} processes running`,
`${formatCount(snapshot.processes)} 个进程正在运行`,
`Hardware reserved (integrated graphics): ${formatMemory(memoryReserved)}`,
`硬件保留(含核显):${formatMemory(memoryReserved)}`,
)
: t("Reading activity", "正在读取活动")}
</small>
</article>
<article className="metric-panel overview-storage-card">
: snapshot
? t(
`${formatCount(snapshot.processes)} processes running`,
`${formatCount(snapshot.processes)} 个进程正在运行`,
)
: t("Reading activity", "正在读取活动")}
</small>
</div>
</div>
<div className="metric-panel metric-drives">
<div className="metric-panel-head">
<span className="metric-icon tone-success">
<span className="metric-icon tone-green">
<HardDrive size={18} />
</span>
<div>
<strong>{t("Storage", "存储空间")}</strong>
<span>
{snapshot
{volumes.length > 0
? t(
`${formatCount(snapshot.volumes.length)} partitions`,
`${formatCount(snapshot.volumes.length)} 个分区`,
`${volumes.length} drives`,
`${volumes.length} 个分区`,
)
: t("Reading volume…", "正在读取磁盘…")}
: t("Reading volumes…", "正在读取磁盘…")}
</span>
</div>
<b>{Math.round(usedPercent)}%</b>
</div>
{visibleVolumes.length > 0 ? (
<div className="storage-volume-list">
{visibleVolumes.map((candidate) => {
const candidateUsed = candidate.total - candidate.free;
const candidatePercent = percent(candidateUsed, candidate.total);
return (
<div className="storage-volume" key={candidate.mount_point}>
<div className="storage-volume-head">
<strong>
{candidate.name || candidate.mount_point}
{candidate.is_root ? ` · ${t("System", "系统")}` : ""}
</strong>
<span>
{t(
`Total ${formatBytes(candidate.total)} · ${formatBytes(candidate.free)} free`,
`总 ${formatBytes(candidate.total)} · 可用 ${formatBytes(candidate.free)}`,
)}
</span>
</div>
<div className="drive-list">
{volumes.slice(0, 4).map((volume) => {
const usedPercent = percent(volume.total - volume.free, volume.total);
return (
<div className="drive-row" key={volume.mount_point}>
<strong className="drive-name" title={volume.name || undefined}>
{driveLabel(volume)}
</strong>
<span className="drive-bar">
<UsageBar
used={candidateUsed}
total={candidate.total}
tone={candidatePercent > 88 ? "danger" : "success"}
used={usedPercent}
total={100}
tone={usedPercent > 85 ? "red" : "green"}
/>
</div>
);
})}
</div>
) : (
<UsageBar used={0} total={100} tone="success" />
)}
</article>
</section>
{cleanup.result && !cleanup.scanning ? (
<section className="overview-found">
<SectionTitle
title={t("What the scan found", "扫描发现")}
action={
<Button variant="ghost" size="sm" onClick={() => onNavigate("cleanup")}>
{t("Open cleanup", "打开清理")}
<ChevronRight size={14} />
</Button>
}
/>
<CategorySummary
result={cleanup.result}
selected={cleanup.selected}
onToggle={cleanup.toggleCategory}
onInspect={() => onNavigate("cleanup")}
/>
</section>
) : null}
<section className="quick-actions">
<SectionTitle
title={t("Everyday care", "日常维护")}
subtitle={t("The right tool for the next five minutes.", "用几分钟完成最常用的事。")}
/>
<div className="quick-grid">
<button className="quick-card tone-info" onClick={() => onNavigate("applications")}>
</span>
<span className="drive-info">
<b className="drive-pct">{Math.round(usedPercent)}%</b>
{t(
`total ${formatBytes(volume.total)} · ${formatBytes(volume.free)} free`,
`总 ${formatBytes(volume.total)} · 可用 ${formatBytes(volume.free)}`,
)}
</span>
</div>
);
})}
</div>
</div>
<div className="quick-col">
<button className="quick-card tone-cyan" onClick={() => onNavigate("applications")}>
<span className="quick-icon">
<AppWindow size={22} />
</span>
@ -429,23 +419,28 @@ export function OverviewPage({
</span>
<ChevronRight size={17} />
</button>
<button className="quick-card tone-violet" onClick={() => onNavigate("storage")}>
<button className="quick-card tone-indigo" onClick={() => onOpenSpaceTab?.("big")}>
<span className="quick-icon">
<Boxes size={22} />
<HardDrive size={22} />
</span>
<span className="quick-copy">
<strong>{t("Explore storage", "浏览存储空间")}</strong>
<strong>{t("Large files", "大文件")}</strong>
<small>{t("See what is taking up space", "查看空间都被什么占用")}</small>
</span>
<ChevronRight size={17} />
</button>
<button className="quick-card tone-violet" onClick={() => onNavigate("purge")}>
<button className="quick-card tone-violet" onClick={smartScan}>
<span className="quick-icon">
<Sparkles size={22} />
</span>
<span className="quick-copy">
<strong>{t("Deep clean", "深度清理")}</strong>
<small>{t("Clear build artefacts safely", "安全清理项目构建产物")}</small>
<strong>{t("Space cleaning", "空间清理")}</strong>
<small>
{t(
"Caches, logs and build artefacts in one scan",
"一次扫描清掉缓存、垃圾与构建产物",
)}
</small>
</span>
<ChevronRight size={17} />
</button>

View File

@ -1,11 +1,24 @@
import { BellRing, RefreshCw, Search, ShieldCheck, Trash2, X } from "lucide-react";
import {
AlertTriangle,
BellRing,
ChevronRight,
FolderOpen,
LayoutGrid,
RefreshCw,
Search,
ShieldCheck,
Trash2,
X,
} from "lucide-react";
import { useMemo, useState } from "react";
import { useI18n } from "../i18n";
import { api } from "../lib/api";
import { shortPath } from "../lib/format";
import type { PermissionsWorkspace } from "../hooks/usePermissionsWorkspace";
import type { ManagedStartupItem } from "../types";
import type { StartupItem } from "../types";
import {
Button,
ConfirmDialog,
EmptyState,
IconButton,
InlineError,
@ -18,11 +31,37 @@ function scopeLabel(scope: string, t: (en: string, zh: string) => string): strin
return scope === "machine" ? t("All users", "所有用户") : t("Current user", "当前用户");
}
// The icon shared by a software group: the first entry that carries one.
function softwareIcon(items: ManagedStartupItem[]): string {
return items.find((item) => item.icon)?.icon ?? "";
// A row whose program binary no longer exists on disk — the config survived
// an uninstall. MangoDisk calls these 残留项 and offers to delete the config.
function isLeftover(item: StartupItem): boolean {
return item.targetExists === false;
}
// 残留 / 已启用 / 已禁用 row tag; leftover wins the colour fight. The
// source / trigger / signature chips used to sit on the group header — the
// user found them noise; the detailed path already rides on every row.
function statusChip(
item: StartupItem,
t: (en: string, zh: string) => string,
): [string, string] {
if (isLeftover(item)) return [t("Leftover", "残留"), "is-leftover"];
return item.enabled
? [t("Enabled", "已启用"), "is-on"]
: [t("Disabled", "已禁用"), "is-off"];
}
// 启动文件夹 rows are removable by deleting the shortcut; the folder is a
// nice human landing spot for anything else.
function rowRevealPath(item: StartupItem): string {
const anchor = item.target || item.command;
if (!anchor) return "";
return anchor.replace(/"$/, "").replace(/^(.*\.(exe|lnk|bat|cmd))\s+/i, "$1");
}
// MangoDisk's status filter: a segment with live counts, 残留 included.
type StartupFilter = "all" | "enabled" | "disabled" | "leftover";
// 电脑管家 shows the owning software's icon on every row it can attribute to
// an installed program; a grey initial covers the leftovers.
function RowIcon({ icon, label }: { icon: string | null | undefined; label: string }) {
@ -35,10 +74,44 @@ function RowIcon({ icon, label }: { icon: string | null | undefined; label: stri
);
}
// 其他软件 carries no real product identity, so it never rides a member's
// icon (ChatGPT's blue tile labelled 其他软件 read as a bug). A neutral
// apps-grid glyph says "a pile of things we could not attribute".
function GroupIcon({
software,
items,
neutral,
}: {
software: string;
items: { icon: string | null }[];
neutral: boolean;
}) {
if (neutral) {
return (
<span className="perm-group-icon perm-group-icon-neutral" aria-hidden="true">
<LayoutGrid size={16} />
</span>
);
}
const icon = items.find((item) => item.icon)?.icon;
return icon ? (
<img className="perm-group-icon" src={icon} alt="" />
) : (
<span className="perm-group-icon perm-group-icon-fallback" aria-hidden="true">
{software.trim().slice(0, 1).toUpperCase()}
</span>
);
}
export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace }) {
const { t } = useI18n();
const [query, setQuery] = useState("");
const [openGroups, setOpenGroups] = useState<Set<string>>(new Set());
const [openExtGroups, setOpenExtGroups] = useState<Set<string>>(new Set());
const [extCat, setExtCat] = useState<string | null>(null);
const [startupFilter, setStartupFilter] = useState<StartupFilter>("all");
const [showSystem, setShowSystem] = useState(false);
const [removingIds, setRemovingIds] = useState<string[] | null>(null);
const view = workspace.view;
const tabs = useMemo(
@ -48,19 +121,28 @@ export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace
id: "startup" as const,
label: t("Startup items", "开机启动项"),
count: view?.startupCount ?? 0,
fresh: false,
},
{
id: "extensions" as const,
label: t("Context menus", "右键菜单"),
count: view?.extensions.length ?? 0,
fresh: false,
},
{
id: "advanced" as const,
label: t("Advanced startup", "进阶启动项"),
count: workspace.advanced?.entries.length ?? 0,
fresh: true,
},
{
id: "popup" as const,
label: t("Popup blocker", "弹窗拦截"),
count: view?.rules.length ?? 0,
fresh: false,
},
],
[t, view],
[t, view, workspace.advanced],
);
if (!view && workspace.scanning) {
@ -103,20 +185,69 @@ export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace
}
const needle = query.trim().toLowerCase();
const startup = view.startup.filter(
const startupSearch = view.startup.filter(
(item) =>
!needle ||
item.name.toLowerCase().includes(needle) ||
item.displayName.toLowerCase().includes(needle) ||
item.command.toLowerCase().includes(needle),
);
// 电脑管家 style: one group per software, Chinese name in the header.
// MangoDisk's 显示系统项: Microsoft-signed / %SystemRoot% rows fold into a
// hideable 系统组件 group instead of mixing into the software list.
const systemName = t("System components", "系统组件");
const startupVisible = showSystem
? startupSearch
: startupSearch.filter((item) => !item.systemItem);
const leftoverCount = startupVisible.filter(isLeftover).length;
const enabledCount = startupVisible.filter((item) => item.enabled && !isLeftover(item)).length;
const disabledCount = startupVisible.length - enabledCount - leftoverCount;
const counts: Record<StartupFilter, number> = {
all: startupVisible.length,
enabled: enabledCount,
disabled: disabledCount,
leftover: leftoverCount,
};
const startup = startupVisible.filter((item) =>
startupFilter === "all"
? true
: startupFilter === "leftover"
? isLeftover(item)
: startupFilter === "enabled"
? item.enabled && !isLeftover(item)
: !item.enabled && !isLeftover(item),
);
// 电脑管家 style: one group per software (Chinese name in the header);
// every entry the backend could not attribute to a real product lands in
// a catch-all 其他软件 group; system rows sink to their own group last.
const otherName = t("Other software", "其他软件");
const startupGroups = new Map<string, typeof startup>();
for (const item of startup) {
const list = startupGroups.get(item.displayName) ?? [];
const key = item.systemItem
? systemName
: item.named && item.displayName
? item.displayName
: otherName;
const list = startupGroups.get(key) ?? [];
list.push(item);
startupGroups.set(item.displayName, list);
startupGroups.set(key, list);
}
const orderedGroups = [...startupGroups.entries()].sort(
([a], [b]) =>
Number(a === otherName) - Number(b === otherName) ||
Number(a === systemName) - Number(b === systemName),
);
// Groups start folded (管家 habit): the header carries a master switch
// and the status line; expanding shows the per-entry detail. Searching
// force-expands everything so matches are never hidden.
const searching = query.trim().length > 0;
const isGroupOpen = (name: string) => searching || openGroups.has(name);
const toggleGroupOpen = (name: string) =>
setOpenGroups((current) => {
const next = new Set(current);
if (next.has(name)) next.delete(name);
else next.add(name);
return next;
});
const groupedExtensions = view.extensions
.filter(
(entry) =>
@ -136,6 +267,29 @@ export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace
const extCategories = Object.keys(groupedExtensions);
const activeCategory =
extCat && extCategories.includes(extCat) ? extCat : extCategories[0] ?? null;
// Same software-grouping rule as the startup list: rows whose module
// carries real product strings group under that product (微信's shell
// extensions across several surfaces become one card); the rest sink to
// 其他软件. Groups open folded, searching force-expands.
const extGrouped = new Map<string, typeof view.extensions>();
for (const entry of activeCategory ? groupedExtensions[activeCategory] : []) {
const named = entry.named && entry.friendlyName;
const key = named ? entry.friendlyName! : otherName;
const list = extGrouped.get(key) ?? [];
list.push(entry);
extGrouped.set(key, list);
}
const extGroups = [...extGrouped.entries()].sort(
([a], [b]) => Number(a === otherName) - Number(b === otherName),
);
const isExtGroupOpen = (name: string) => searching || openExtGroups.has(name);
const toggleExtGroupOpen = (name: string) =>
setOpenExtGroups((current) => {
const next = new Set(current);
if (next.has(name)) next.delete(name);
else next.add(name);
return next;
});
return (
<div className="page permissions-page">
@ -182,65 +336,225 @@ export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace
`共 ${view.startupCount} 项,其中 ${view.startupEnabledCount} 项已开启。`,
)}
/>
<label className="search-field">
<Search size={14} />
<input
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder={t("Filter by name or path…", "按名称或路径筛选…")}
/>
</label>
{Array.from(startupGroups.entries()).map(([software, items]) => (
<div key={software}>
<h4 className="perm-group">
{items.find((item) => item.icon)?.icon ? (
<img className="perm-group-icon" src={softwareIcon(items)} alt="" />
) : (
<span className="perm-group-icon perm-group-icon-fallback" aria-hidden="true">
{software.trim().slice(0, 1).toUpperCase()}
</span>
)}
<span>{software}</span>
<b>
{t(
`${items.filter((item) => item.enabled).length}/${items.length} on`,
`${items.filter((item) => item.enabled).length}/${items.length} 开启`,
)}
</b>
</h4>
<div className="perm-rows">
{items.map((item) => (
<div
className={`settings-row ${workspace.busyId === item.id ? "is-busy" : ""}`}
key={item.id}
>
<div className="perm-row">
<RowIcon icon={item.icon} label={item.displayName} />
<div>
<span>{item.name}</span>
<small title={item.command}>
{item.sourceLabel} · {scopeLabel(item.scope, t)}
{item.command ? ` · ${shortPath(item.command, 72)}` : ""}
</small>
</div>
</div>
<Toggle
checked={item.enabled}
disabled={workspace.busyId !== null}
onChange={(next) => void workspace.toggleStartup(item.id, next)}
label={`${item.name} ${item.enabled ? "disable" : "enable"}`}
/>
</div>
))}
</div>
<div className="perm-startup-bar">
<div className="perm-filter" role="tablist" aria-label={t("Status filter", "状态筛选")}>
{(
[
["all", "All", "全部"],
["enabled", "Enabled", "已启用"],
["disabled", "Disabled", "已禁用"],
["leftover", "Leftover", "残留"],
] as const
).map(([id, en, zh]) => (
<button
key={id}
role="tab"
aria-selected={startupFilter === id}
className={`perm-filter-tab ${startupFilter === id ? "is-active" : ""} ${
id === "leftover" && counts.leftover > 0 ? "has-leftover" : ""
}`}
onClick={() => setStartupFilter(id)}
>
{t(en, zh)}
<b>{counts[id]}</b>
</button>
))}
</div>
))}
<div className="perm-startup-tools">
<label className="perm-system-toggle">
<Toggle
checked={showSystem}
onChange={setShowSystem}
label={t("Show system items", "显示系统项")}
/>
<span>{t("Show system items", "显示系统项")}</span>
</label>
<label className="search-field">
<Search size={14} />
<input
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder={t("Filter by name or path…", "按名称或路径筛选…")}
/>
</label>
</div>
</div>
{orderedGroups.map(([software, items]) => {
const onCount = items.filter((item) => item.enabled && !isLeftover(item)).length;
const allOn = onCount === items.length;
const open = isGroupOpen(software);
const groupIds = items.map((item) => item.id);
const leftovers = items.filter(isLeftover);
return (
<div
key={software}
className={`perm-group-card ${open ? "is-open" : ""} ${
leftovers.length > 0 && leftovers.length === items.length ? "is-leftover" : ""
}`}
>
<h4 className="perm-group" onClick={() => toggleGroupOpen(software)}>
<GroupIcon software={software} items={items} neutral={software === otherName} />
<span className="perm-group-name">{software}</span>
{leftovers.length > 0 ? (
<span className="perm-sig is-leftover">
{t(`${leftovers.length} leftover`, `${leftovers.length} 个残留`)}
</span>
) : null}
<b className={allOn ? "is-all" : onCount === 0 ? "is-none" : "is-part"}>
{allOn
? t("All on", "全部开启")
: onCount === 0
? t("All off", "已全部关闭")
: t(
`${onCount}/${items.length} on`,
`部分开启 ${onCount}/${items.length}`,
)}
</b>
<span
className="perm-group-tail"
onClick={(event) => event.stopPropagation()}
>
<span
className="perm-group-count"
onClick={(event) => {
event.stopPropagation();
toggleGroupOpen(software);
}}
>
{items.length > 1
? t(`${items.length} items`, `共${items.length}项`)
: t("1 item", "共1项")}
<ChevronRight
size={13}
className={`perm-group-chv ${open ? "is-open" : ""}`}
/>
</span>
<Toggle
checked={allOn}
disabled={workspace.busyId !== null}
onChange={(next) => void workspace.toggleStartupGroup(groupIds, next)}
label={`${software} master ${allOn ? "disable" : "enable"}`}
/>
</span>
</h4>
{open ? (
<div className="perm-rows">
{items.map((item) => {
const [statusText, statusTone] = statusChip(item, t);
const reveal = rowRevealPath(item);
return (
<div
className={`settings-row ${
workspace.busyId === item.id ? "is-busy" : ""
} ${isLeftover(item) ? "is-leftover-row" : ""}`}
key={item.id}
>
<div className="perm-row perm-row-noicon">
<div>
<span>
{item.name}{" "}
<em className={`perm-row-tag ${statusTone}`}>{statusText}</em>
</span>
<small title={item.command}>
{item.sourceLabel} · {scopeLabel(item.scope, t)}
{item.command ? ` · ${shortPath(item.command, 72)}` : ""}
</small>
<small className="perm-row-full" title={item.command}>
{item.command || t("(no command line)", "(无命令行记录)")}
</small>
</div>
</div>
<div className="perm-row-actions">
{isLeftover(item) ? (
<Button
size="sm"
variant="danger"
icon={<Trash2 size={13} />}
disabled={workspace.busyId !== null}
onClick={() => setRemovingIds([item.id])}
>
{t("Delete entry", "删除启动项")}
</Button>
) : null}
{reveal ? (
<IconButton
label={t("Open its folder", "打开所在文件夹")}
onClick={() => void api.revealPath(reveal).catch(() => {})}
>
<FolderOpen size={15} />
</IconButton>
) : null}
<Toggle
checked={item.enabled}
disabled={workspace.busyId !== null}
onChange={(next) => void workspace.toggleStartup(item.id, next)}
label={`${item.name} ${item.enabled ? "disable" : "enable"}`}
/>
</div>
</div>
);
})}
{leftovers.length > 0 && leftovers.length < items.length ? (
<div className="perm-group-leftover-bar">
<AlertTriangle size={13} />
<span>
{t(
`${leftovers.length} leftover entries in this group — their programs are gone.`,
`该组有 ${leftovers.length} 个残留项:程序已不存在,只剩启动配置。`,
)}
</span>
<Button
size="sm"
variant="danger"
disabled={workspace.busyId !== null}
onClick={() => setRemovingIds(leftovers.map((item) => item.id))}
>
{t(
`Delete ${leftovers.length} leftover(s)`,
`删除 ${leftovers.length} 个残留项`,
)}
</Button>
</div>
) : null}
</div>
) : null}
</div>
);
})}
{startup.length === 0 ? (
<p className="perm-empty">{t("No matches.", "没有匹配的项目。")}</p>
<p className="perm-empty">
{counts.all === 0
? t("No matches.", "没有匹配的项目。")
: t("Nothing here under this filter.", "当前筛选下没有项目。")}
</p>
) : null}
</section>
) : null}
<ConfirmDialog
open={removingIds !== null}
tone="danger"
icon={<Trash2 size={24} />}
title={t("Delete startup entries?", "删除启动项?")}
message={t(
`Squid removes only the autostart registration (${removingIds?.length ?? 0} item(s)); no program files are touched.`,
`Squid 只删除启动配置(共 ${removingIds?.length ?? 0} 项),不会动任何程序文件。`,
)}
note={t(
"Registry values are deleted; Startup-folder shortcuts are removed; tasks are unscheduled; leftover services are set to disabled.",
"注册表值将被删除;启动文件夹的快捷方式会被移除;计划任务会被注销;残留服务会改为禁用。",
)}
confirmLabel={t("Delete", "删除")}
cancelLabel={t("Cancel", "取消")}
busy={workspace.busyId !== null}
onClose={() => setRemovingIds(null)}
onConfirm={async () => {
if (!removingIds) return;
await workspace.removeStartup(removingIds);
setRemovingIds(null);
}}
/>
{workspace.tab === "extensions" ? (
<section className="settings-section">
<SectionTitle
@ -280,43 +594,208 @@ export function PermissionsPage({ workspace }: { workspace: PermissionsWorkspace
/>
</label>
</div>
<div className="perm-rows">
{(activeCategory ? groupedExtensions[activeCategory] : []).map((entry) => (
<div
className={`settings-row ${!entry.registered ? "is-muted" : ""} ${
workspace.busyId === entry.id ? "is-busy" : ""
}`}
key={entry.id}
>
<div className="perm-row">
<RowIcon icon={entry.icon} label={entry.friendlyName ?? entry.name} />
<div>
<span>{entry.friendlyName ?? entry.name}</span>
<small title={entry.module ?? entry.handler}>
{entry.publisher
? `${t("Creator", "创建者")} ${entry.publisher} · `
: ""}
{scopeLabel(entry.scope, t)}
{entry.module ? ` · ${shortPath(entry.module, 56)}` : ""}
{!entry.registered ? ` · ${t("removed", "已移除")}` : ""}
</small>
{extGroups.map(([software, items]) => {
const onCount = items.filter((entry) => entry.registered).length;
const allOn = onCount === items.length;
const open = isExtGroupOpen(software);
return (
<div key={software} className={`perm-group-card ${open ? "is-open" : ""}`}>
<h4 className="perm-group" onClick={() => toggleExtGroupOpen(software)}>
<GroupIcon software={software} items={items} neutral={software === otherName} />
<span className="perm-group-name">{software}</span>
<b className={allOn ? "is-all" : onCount === 0 ? "is-none" : "is-part"}>
{allOn
? t("All on", "全部开启")
: onCount === 0
? t("All off", "已全部关闭")
: t(
`${onCount}/${items.length} on`,
`部分开启 ${onCount}/${items.length}`,
)}
</b>
<span
className="perm-group-tail"
onClick={(event) => event.stopPropagation()}
>
<span
className="perm-group-count"
onClick={(event) => {
event.stopPropagation();
toggleExtGroupOpen(software);
}}
>
{items.length > 1
? t(
`${items.length} places`,
`共${items.length}个菜单位置`,
)
: t("1 place", "1个菜单位置")}
<ChevronRight
size={13}
className={`perm-group-chv ${open ? "is-open" : ""}`}
/>
</span>
<Toggle
checked={allOn}
disabled={workspace.busyId !== null}
onChange={async (next) => {
for (const entry of items) {
if (entry.registered !== next) {
await workspace.toggleExtension(entry.id, next);
}
}
}}
label={`${software} master ${allOn ? "disable" : "enable"}`}
/>
</span>
</h4>
{open ? (
<div className="perm-rows">
{items.map((entry) => (
<div
className={`settings-row ${!entry.registered ? "is-muted" : ""} ${
workspace.busyId === entry.id ? "is-busy" : ""
}`}
key={entry.id}
>
<div className="perm-row perm-row-noicon">
<div>
<span>{entry.friendlyName ?? entry.name}</span>
<small title={entry.module ?? entry.handler}>
{entry.publisher
? `${t("Creator", "创建者")} ${entry.publisher} · `
: ""}
{scopeLabel(entry.scope, t)}
{entry.module ? ` · ${shortPath(entry.module, 56)}` : ""}
{!entry.registered ? ` · ${t("removed", "已移除")}` : ""}
</small>
</div>
</div>
<Toggle
checked={entry.registered}
disabled={workspace.busyId !== null}
onChange={(next) => void workspace.toggleExtension(entry.id, next)}
label={`${entry.name} ${entry.registered ? "remove" : "restore"}`}
/>
</div>
))}
</div>
</div>
<Toggle
checked={entry.registered}
disabled={workspace.busyId !== null}
onChange={(next) => void workspace.toggleExtension(entry.id, next)}
label={`${entry.name} ${entry.registered ? "remove" : "restore"}`}
/>
) : null}
</div>
))}
</div>
);
})}
{extCategories.length === 0 ? (
<p className="perm-empty">{t("No matches.", "没有匹配的项目。")}</p>
) : null}
</section>
) : null}
{workspace.tab === "advanced" ? (
<section className="settings-section perm-advanced">
<div className="perm-adv-note">
{t(
"Advanced rows can break boot or logon if changed carelessly — Squid only displays them here, every change records its original value, and nothing is auto-disabled.",
"进阶区的项目改错了可能影响系统行为——默认只展示不勾选,每一项带数字签名与位置说明;改动会原样记录,可逐项恢复。",
)}
</div>
{workspace.advancedScanning && !workspace.advanced ? (
<div className="perm-loading">
<RefreshCw size={18} className="perm-spin" />
<span>
{t(
"Reading Winlogon / IFEO / BHO and verifying signatures…",
"正在读取 Winlogon / IFEO / BHO 并核验数字签名…",
)}
</span>
</div>
) : null}
{workspace.advanced && workspace.advanced.entries.length === 0 ? (
<p className="perm-empty">
{t(
"No third-party Winlogon hooks, AppInit DLLs, IFEO debuggers or BHOs found — the machine is clean.",
"没有发现第三方 Winlogon 挂钩、AppInit DLL、IFEO 调试器或 BHO——系统很干净。",
)}
</p>
) : null}
{workspace.advanced
? (["winlogon", "appinit", "ifeo", "bho"] as const).map((kind) => {
const rows = workspace.advanced!.entries.filter((entry) => entry.kind === kind);
if (rows.length === 0) return null;
const titles: Record<string, [string, string]> = {
winlogon: ["Winlogon hooks", "Winlogon 与登录链"],
appinit: ["AppInit DLL injection", "AppInit_DLLs 全局注入"],
ifeo: ["IFEO debuggers (can hijack any program)", "IFEO 调试器(可劫持任意程序启动)"],
bho: ["Browser helper objects", "浏览器加载项 BHO"],
};
return (
<div className="perm-adv-group" key={kind}>
<SectionTitle
title={t(titles[kind][0], titles[kind][1])}
subtitle={t(`${rows.length} item(s)`, `发现 ${rows.length} 项`)}
/>
{rows.map((entry) => (
<div className="perm-adv-row" key={entry.id}>
<span className={`perm-sig is-${entry.signature}`} title={entry.signer ?? undefined}>
{entry.signature === "microsoft"
? t("Microsoft signed", "微软签名")
: entry.signature === "vendor"
? t("Signed by", "已知厂商")
: entry.signature === "unsigned"
? t("Not signed", "无数字签名")
: entry.signature === "invalid"
? t("Signature invalid", "签名无效")
: t("Signature n/a", "无签名信息")}
</span>
<div className="perm-adv-main">
<b>{entry.name}</b>
<small title={entry.command}>{shortPath(entry.command, 90)}</small>
<small className="perm-adv-loc">{entry.location}</small>
{entry.warning ? (
<small className="perm-adv-warn">{entry.warning}</small>
) : null}
</div>
<Toggle
checked={entry.enabled}
disabled={workspace.busyId !== null}
onChange={(next) => void workspace.toggleAdvanced(entry.id, next)}
label={entry.name}
/>
</div>
))}
</div>
);
})
: null}
{workspace.advanced && workspace.advanced.extras.length > 0 ? (
<div className="perm-adv-group">
<SectionTitle
title={t("Automatic services", "服务(自动启动)")}
subtitle={t(
"Services set to start automatically — toggling uses the same rights as Task Manager.",
"设置为自动启动的服务;开关与任务管理器同一套权限。",
)}
/>
{workspace.advanced.extras.map((entry) => (
<div className="perm-adv-row" key={entry.id}>
<span className="perm-scope">{scopeLabel(entry.scope, t)}</span>
<div className="perm-adv-main">
<b>{entry.displayName || entry.name}</b>
<small title={entry.command}>{shortPath(entry.command, 90)}</small>
<small className="perm-adv-loc">{entry.sourceLabel}</small>
</div>
<Toggle
checked={entry.enabled}
disabled={workspace.busyId !== null}
onChange={(next) => void workspace.toggleStartup(entry.id, next)}
label={entry.name}
/>
</div>
))}
</div>
) : null}
</section>
) : null}
{workspace.tab === "popup" ? (
<>
<section className="settings-section">

View File

@ -0,0 +1,227 @@
import { ClipboardList, EyeOff, FileClock, History, Lock, ShieldQuestion } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { api } from "../lib/api";
import { useI18n } from "../i18n";
import { formatBytes, formatCount, messageFrom } from "../lib/format";
import {
Button,
Checkbox,
EmptyState,
InlineError,
PageHeader,
useToast,
} from "../components/ui";
import type { CleanupItem } from "../types";
function jobId(): string {
return crypto.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
const SPEC_ICONS: Record<string, typeof History> = {
"privacy-edge": History,
"privacy-chrome": History,
"privacy-recent": FileClock,
"privacy-clipboard": ClipboardList,
"privacy-activity": EyeOff,
};
const WARN_COPY: Record<string, [string, string]> = {
"privacy-edge": ["影响「恢复上次会话」", "affects session restore"],
"privacy-chrome": ["影响「恢复上次会话」", "affects session restore"],
"privacy-clipboard": ["Win+V 历史会被清空", "clears the Win+V list"],
"privacy-activity": ["影响「恢复上次会话」", "affects session restore"],
};
interface SpecGroup {
ruleId: string;
label: string;
detail: string | null;
indexes: number[];
bytes: number;
locked: string | null;
}
export function PrivacyPage({
embedded = false,
onBadge,
}: {
/** Rendered inside 系统维护 hub: page title hides, trace count flows up. */
embedded?: boolean;
onBadge?: (value: string | null) => void;
} = {}) {
const { t, lang } = useI18n();
const { push } = useToast();
const [items, setItems] = useState<CleanupItem[]>([]);
const [scanId, setScanId] = useState<string | null>(null);
const [picked, setPicked] = useState<Set<number>>(new Set());
const [scanning, setScanning] = useState(false);
const [cleaning, setCleaning] = useState(false);
const [error, setError] = useState<string | null>(null);
const [loaded, setLoaded] = useState(false);
const scan = useCallback(async () => {
setScanning(true);
setError(null);
const id = jobId();
try {
const view = await api.privacyScan(id);
setItems(view.items);
setScanId(view.scanId);
setPicked(new Set());
} catch (reason) {
setError(messageFrom(reason));
} finally {
setScanning(false);
setLoaded(true);
}
}, []);
useEffect(() => {
void scan();
}, [scan]);
const groups: SpecGroup[] = [];
items.forEach((item, index) => {
const last = groups[groups.length - 1];
if (last && last.ruleId === item.ruleId) {
last.indexes.push(index);
last.bytes += item.onDisk;
if (item.lock && !last.locked) {
last.locked = item.note ?? item.lock;
}
} else {
groups.push({
ruleId: item.ruleId,
label: item.label,
detail: item.note,
indexes: [index],
bytes: item.onDisk,
locked: item.lock ? item.note ?? item.lock : null,
});
}
});
const toggleGroup = (group: SpecGroup) => {
if (group.locked) return;
setPicked((current) => {
const next = new Set(current);
const allOn = group.indexes.every((index) => next.has(index));
for (const index of group.indexes) {
if (allOn) next.delete(index);
else next.add(index);
}
return next;
});
};
const pickedBytes = [...picked].reduce((sum, index) => sum + (items[index]?.onDisk ?? 0), 0);
// Hub badge: trace groups found by the auto-scan, or null when clean.
useEffect(() => {
if (!embedded || !onBadge) return;
onBadge(groups.length > 0 ? `${groups.length} 类痕迹` : null);
}, [embedded, groups.length, onBadge]);
const clean = async () => {
if (!scanId || picked.size === 0) return;
setCleaning(true);
try {
const outcome = await api.privacyDelete(jobId(), scanId, [...picked]);
push(
lang === "zh"
? `已清除 ${outcome.removed} 项隐私痕迹(${formatBytes(outcome.freed)});这些删除不进回收站,明细见历史记录`
: `Cleared ${outcome.removed} traces (${formatBytes(outcome.freed)}); these deletions skip the Recycle Bin — see History`,
"success",
);
await scan();
} catch (reason) {
push(messageFrom(reason), "danger");
} finally {
setCleaning(false);
}
};
return (
<div className={`page privacy-page ${embedded ? "is-embedded" : ""}`}>
{embedded ? null : (
<PageHeader
title={t("Privacy cleaning", "隐私清理")}
/>
)}
{error ? <InlineError message={error} onDismiss={() => setError(null)} /> : null}
<section className="privacy-grid">
{groups.map((group) => {
const Icon = SPEC_ICONS[group.ruleId] ?? ShieldQuestion;
const allOn = group.indexes.every((index) => picked.has(index));
const warn = WARN_COPY[group.ruleId];
return (
<label
key={group.ruleId}
className={`privacy-card ${group.locked ? "is-locked" : ""} ${allOn ? "is-picked" : ""}`}
onClick={() => toggleGroup(group)}
>
<Checkbox
checked={allOn}
disabled={Boolean(group.locked)}
onChange={() => toggleGroup(group)}
label={group.label}
/>
<span className="privacy-icon">
<Icon size={17} />
</span>
<span className="privacy-copy">
<b>{group.label}</b>
<small>{group.detail}</small>
{warn && !group.locked ? (
<small className="privacy-warn">{lang === "zh" ? warn[0] : warn[1]}</small>
) : null}
</span>
{group.locked ? (
<span className="privacy-lock">
<Lock size={12} /> {group.locked}
</span>
) : (
<span className="privacy-size">{formatBytes(group.bytes)}</span>
)}
</label>
);
})}
{loaded && groups.length === 0 && !scanning ? (
<EmptyState
icon={<EyeOff size={26} />}
title={t("Nothing to clean", "没有可清理的痕迹")}
description={t(
"No browser profiles or trace stores were found on this machine.",
"本机没有找到浏览器 profile 或痕迹存储。",
)}
/>
) : null}
</section>
<section className="privacy-footer">
<span className="privacy-footer-sum">
{picked.size > 0
? t(
`${formatCount(picked.size)} traces selected · ${formatBytes(pickedBytes)} · permanent`,
`已选 ${formatCount(picked.size)} 项 · ${formatBytes(pickedBytes)} · 永久删除`,
)
: t(
"These deletions skip the Recycle Bin on purpose; History still lists every path.",
"这些删除有意绕过回收站;历史记录仍会逐条登记路径与大小。",
)}
</span>
<Button variant="ghost" onClick={() => void scan()} disabled={scanning || cleaning}>
{scanning ? t("Refreshing…", "正在刷新…") : t("Re-scan", "重新扫描")}
</Button>
<Button
variant="danger"
disabled={picked.size === 0 || cleaning || scanning}
onClick={() => void clean()}
>
{cleaning ? t("Cleaning…", "清理中…") : t("Clean now", "立即清理")}
</Button>
</section>
</div>
);
}

View File

@ -1,139 +0,0 @@
import {
AlertTriangle,
FolderSearch,
GitBranch,
ScanSearch,
ShieldAlert,
} from "lucide-react";
import { useState } from "react";
import { useI18n } from "../i18n";
import type { Bootstrap, DeleteMode } from "../types";
import type { ScanWorkspace } from "../hooks/useScanWorkspace";
import { CleanupInventory } from "../components/CleanupView";
import { Button, PageHeader, Toggle } from "../components/ui";
export function PurgePage({
workspace,
bootstrap,
deleteMode,
onHistory,
}: {
workspace: ScanWorkspace;
bootstrap: Bootstrap;
deleteMode: DeleteMode;
onHistory: () => void;
}) {
const { t } = useI18n();
const [roots, setRoots] = useState(bootstrap.settings.purgeRoots.join("\n"));
const [minAge, setMinAge] = useState(bootstrap.settings.purgeMinAgeDays);
const [force, setForce] = useState(false);
const run = () =>
void workspace.runScan({
roots: roots
.split(/\r?\n/)
.map((root) => root.trim())
.filter(Boolean),
minAgeDays: minAge > 0 ? minAge : null,
force,
});
return (
<div className="page">
<PageHeader
title={t("Find the space normal cleaning misses", "找到普通清理遗漏的空间")}
actions={
<Button variant="primary" icon={<ScanSearch size={16} />} onClick={run}>
{t("Start deep scan", "开始深度扫描")}
</Button>
}
/>
<div className="deep-options">
<div className="deep-option-main">
<label className="field-label" htmlFor="purge-roots">
{t("Project folders to inspect", "要检查的项目目录")}
</label>
<textarea
id="purge-roots"
value={roots}
onChange={(event) => setRoots(event.target.value)}
placeholder={t(
"One folder per line. Leave empty to use your home folder.",
"每行一个目录;留空则使用用户主目录。",
)}
rows={3}
/>
</div>
<div className="deep-option-side">
<label className="field-label" htmlFor="purge-age">
{t("Only files older than", "仅处理早于")}
</label>
<div className="number-field">
<input
id="purge-age"
type="number"
min={0}
max={3650}
value={minAge}
onChange={(event) => setMinAge(Math.max(0, Number(event.target.value) || 0))}
/>
<span>{t("days", "天")}</span>
</div>
<div className="option-toggle-row">
<div>
<strong>{t("Force mode", "强制模式")}</strong>
<span>{t("Include folders inside a Git work tree", "包含 Git 工作树内的目录")}</span>
</div>
<Toggle
checked={force}
onChange={setForce}
label={t("Force mode", "强制模式")}
/>
</div>
</div>
</div>
<div className="safety-strip">
<GitBranch size={18} />
<div>
<strong>{t("Git-aware by default", "默认感知 Git 状态")}</strong>
<span>
{t(
"Uncommitted work is protected. Force mode is for throwaway build folders only.",
"存在未提交改动时会自动保护。强制模式仅建议用于可丢弃的构建目录。",
)}
</span>
</div>
<ShieldAlert size={19} />
</div>
<div className="warning-strip">
<AlertTriangle size={18} />
<span>
{t(
"node_modules, target, dist and similar folders can be regenerated, but rebuilding may take time or require network access.",
"node_modules、target、dist 等目录可以重新生成,但重新构建可能需要时间或网络。",
)}
</span>
</div>
<CleanupInventory
workspace={workspace}
defaultMode={deleteMode}
onHistory={onHistory}
/>
{!workspace.result && !workspace.scanning && !workspace.summary ? (
<div className="empty-inline">
<FolderSearch size={22} />
<span>
{t(
"No deep scan yet. Choose your project roots above and start when ready.",
"尚未进行深度扫描。选择项目目录后即可开始。",
)}
</span>
</div>
) : null}
</div>
);
}

View File

@ -85,6 +85,28 @@ export function SettingsPage({
const [checkingPermission, setCheckingPermission] = useState(false);
const [autostart, setAutostart] = useState<boolean | null>(null);
const [savingAutostart, setSavingAutostart] = useState(false);
// Whitelist entries are only as good as their last hit: the audit answers
// "did this pattern ever protect something real?".
const [audit, setAudit] = useState<Map<string, boolean> | null>(null);
const [auditing, setAuditing] = useState(false);
const runAudit = useCallback(async () => {
setAuditing(true);
try {
const rows = await api.whitelistAudit();
setAudit(new Map(rows.map((row) => [row.pattern, row.live])));
} catch {
setAudit(null);
} finally {
setAuditing(false);
}
}, []);
useEffect(() => {
if (settings.whitelist.length > 0 && audit === null && !auditing) {
void runAudit();
}
}, [audit, auditing, runAudit, settings.whitelist.length]);
const checkPermissions = useCallback(async () => {
setCheckingPermission(true);
@ -408,6 +430,30 @@ export function SettingsPage({
{t("Add", "添加")}
</Button>
</div>
{settings.whitelist.length > 0 ? (
<div className="whitelist-audit-bar">
<span>
{audit === null
? t(
"Checking whether each pattern still matches anything…",
"正在核对每条规则是否还命中过内容…",
)
: t(
`Consumption audit: ${[...audit.values()].filter(Boolean).length} of ${audit.size} pattern(s) matched known cache locations`,
`消费审计:${audit.size} 条规则中 ${[...audit.values()].filter(Boolean).length} 条命中过已知缓存位置`,
)}
</span>
<Button
variant="ghost"
size="sm"
icon={<RefreshCw size={13} className={auditing ? "spin" : undefined} />}
onClick={() => void runAudit()}
disabled={auditing}
>
{t("Re-check", "重新检查")}
</Button>
</div>
) : null}
<div className="whitelist-list">
{settings.whitelist.length === 0 ? (
<p className="settings-empty">
@ -420,6 +466,25 @@ export function SettingsPage({
<ShieldCheck size={15} />
</span>
<code title={pattern}>{shortPath(pattern, 88)}</code>
{audit ? (
<span
className={`whitelist-audit-chip ${
audit.get(pattern) ? "is-live" : "is-dead"
}`}
title={t(
audit.get(pattern)
? "This pattern matched paths Squid knows about on the last scan"
: "This pattern has never matched anything — it may be stale",
audit.get(pattern)
? "最近扫描命中过这条规则保护的位置"
: "从未命中任何已知位置,规则可能已经过期",
)}
>
{audit.get(pattern)
? t("Recently matched", "最近命中")
: t("Never matched", "从未命中")}
</span>
) : null}
<button
className="row-reveal"
aria-label={t("Remove protection", "移除保护")}

View File

@ -0,0 +1,91 @@
import { CopyX, Eraser, FileArchive } from "lucide-react";
import { useEffect, useState } from "react";
import { useI18n } from "../i18n";
import { PageHeader } from "../components/ui";
import { SpacePage } from "./SpacePage";
import { DuplicateFilesPage } from "./DuplicateFilesPage";
import { LargeFilesPage } from "./LargeFilesPage";
import type { Bootstrap, DeleteMode } from "../types";
import type { ScanWorkspace } from "../hooks/useScanWorkspace";
/* 空间清理 hub(方案①):垃圾清理 / 重复文件 / 大文件 三页签。
* 三个面板全部保持挂载(display 切换),扫描结果与勾选状态在切页签
* 时不丢失;每个面板自己决定何时扫描(懒扫描),页签徽标由面板回报。 */
export type SpaceTab = "junk" | "dups" | "big";
const TABS: { id: SpaceTab; icon: typeof Eraser; en: string; zh: string }[] = [
{ id: "junk", icon: Eraser, en: "Junk cleaning", zh: "垃圾清理" },
{ id: "dups", icon: CopyX, en: "Duplicate files", zh: "重复文件" },
{ id: "big", icon: FileArchive, en: "Large files", zh: "大文件" },
];
export function SpaceHubPage({
cleanup,
purge,
bootstrap,
deleteMode,
onHistory,
initialTab = "junk",
}: {
cleanup: ScanWorkspace;
purge: ScanWorkspace;
bootstrap: Bootstrap;
deleteMode: DeleteMode;
onHistory: () => void;
/** Deep-link from the overview quick cards (重复文件 / 大文件). */
initialTab?: SpaceTab;
}) {
const { t } = useI18n();
const [tab, setTab] = useState<SpaceTab>(initialTab);
// A fresh deep-link wins over the last manually chosen tab.
useEffect(() => setTab(initialTab), [initialTab]);
const [badges, setBadges] = useState<Partial<Record<SpaceTab, string | null>>>({});
const report = (id: SpaceTab) => (value: string | null) =>
setBadges((current) => (current[id] === value ? current : { ...current, [id]: value }));
return (
<div className="page hub-page">
<PageHeader
title={t("Space cleaning", "空间清理")}
/>
<div className="hub-tabs" role="tablist">
{TABS.map((item) => {
const Icon = item.icon;
const badge = badges[item.id];
return (
<button
key={item.id}
type="button"
role="tab"
aria-selected={tab === item.id}
className={`hub-tab ${tab === item.id ? "is-active" : ""}`}
onClick={() => setTab(item.id)}
>
<Icon size={15} />
{t(item.en, item.zh)}
{badge ? <b>{badge}</b> : null}
</button>
);
})}
</div>
<div className="hub-pane" style={{ display: tab === "junk" ? undefined : "none" }}>
<SpacePage
embedded
onBadge={report("junk")}
cleanup={cleanup}
purge={purge}
bootstrap={bootstrap}
deleteMode={deleteMode}
onHistory={onHistory}
/>
</div>
<div className="hub-pane" style={{ display: tab === "dups" ? undefined : "none" }}>
<DuplicateFilesPage embedded onBadge={report("dups")} onHistory={onHistory} />
</div>
<div className="hub-pane" style={{ display: tab === "big" ? undefined : "none" }}>
<LargeFilesPage embedded onBadge={report("big")} onHistory={onHistory} />
</div>
</div>
);
}

File diff suppressed because it is too large Load Diff

View File

@ -1,716 +0,0 @@
import {
AlertTriangle,
ChevronDown,
ChevronRight,
ExternalLink,
FileSearch,
KeyRound,
Lock,
RefreshCw,
Search,
ShieldAlert,
ToggleLeft,
ToggleRight,
} from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useI18n } from "../i18n";
import { api } from "../lib/api";
import { formatDate, formatCount, messageFrom, shortPath } from "../lib/format";
import type {
StartupCategory,
StartupItem,
StartupLock,
StartupRisk,
StartupSource,
} from "../types";
import type { SecurityWorkspace } from "../hooks/useSecurityWorkspace";
import type { StartupWorkspace } from "../hooks/useStartupWorkspace";
import {
Button,
ConfirmDialog,
EmptyState,
InlineError,
Modal,
PageHeader,
SectionTitle,
Select,
Toggle,
useToast,
} from "../components/ui";
const SOURCE_LABEL: Record<StartupSource, [string, string]> = {
"launch-agent": ["LaunchAgent", "LaunchAgent"],
"launch-daemon": ["LaunchDaemon", "LaunchDaemon"],
"login-item": ["Login item", "登录项"],
"registry-run": ["Registry Run", "注册表 Run"],
"startup-folder": ["Startup folder", "启动文件夹"],
"scheduled-task": ["Scheduled task", "计划任务"],
service: ["Service", "服务"],
};
const RISK_LABEL: Record<StartupRisk, [string, string]> = {
"missing-target": ["Target is gone", "目标已不存在"],
"in-temp-dir": ["Runs from a temp folder", "位于临时目录"],
unsigned: ["No usable signature", "无可用签名"],
"signature-unreadable": ["Signature could not be read", "无法读取签名"],
"script-interpreter": ["Started through a script", "经由脚本启动"],
"recently-created": ["Added recently", "最近添加"],
"hidden-entry": ["Hidden entry", "隐藏条目"],
"hidden-home-directory": ["Runs from a dot-folder", "位于隐藏目录"],
};
const LOCK_LABEL: Record<StartupLock, [string, string]> = {
"operating-system": ["Part of the operating system", "系统自带条目"],
"needs-authorisation": ["Needs an administrator", "需要管理员权限"],
"not-writable": ["Not writable by this user", "当前用户不可写"],
"managed-by-system-settings": ["Managed in System Settings", "由系统设置管理"],
"not-managed": ["Read-only in this release", "本版本只读"],
};
type Tab = StartupCategory;
type Scope = "all" | "user" | "system";
/// Where to reveal an entry: the program it runs if that exists, otherwise the
/// plist, key or task file that declares it. A login item whose target is gone can
/// still be shown by its declaration.
///
/// An id is only a place when it looks like one. macOS login items are named rather
/// than filed, and their `login-item://` id is a key, not a path to open.
function revealTarget(item: StartupItem): string | null {
if (item.program) return item.program;
return /^[\\/]|[A-Za-z]:[\\/]/.test(item.id) ? item.id : null;
}
/**
* Startup items: what the machine has been told to run by itself.
*
* Read the way the operating system reads it. macOS shows two lists — what opens
* when you log in, and what may keep running behind it — and files each entry under
* the application that installed it. A flat list of 870 launchd labels asks the user
* to do the grouping squid can do from paths alone.
*
* A risk label means "look at this", never "this is malware"; the alternative is a
* wall of orange beside entries the operating system owns, which is why those are
* hidden until asked for.
*/
export function StartupPage({
startup,
security,
initialQuery,
onInspectProcess,
onShowSecurity,
}: {
startup: StartupWorkspace;
security: SecurityWorkspace;
initialQuery: string | null;
onInspectProcess: (filter: string) => void;
onShowSecurity: () => void;
}) {
const { t, lang } = useI18n();
const { push } = useToast();
const [tab, setTab] = useState<Tab>("open-at-login");
const [scope, setScope] = useState<Scope>("all");
const [showVendor, setShowVendor] = useState(false);
const [riskyOnly, setRiskyOnly] = useState(false);
const [query, setQuery] = useState(initialQuery ?? "");
const [open, setOpen] = useState<Set<string>>(new Set());
const [detail, setDetail] = useState<StartupItem | null>(null);
const [pending, setPending] = useState<{ item: StartupItem; enabled: boolean } | null>(null);
/**
* One file, scanned now, and the user is taken to the page that shows the
* result. Scanning in place would hide the answer behind whichever page they
* happen to be standing on.
*/
const scanFile = async (path: string) => {
try {
await security.start("custom", [path]);
onShowSecurity();
} catch (reason) {
push(messageFrom(reason), "danger");
}
};
/** Everything but the search, so the counts beside the tabs are what clicking shows. */
const listed = useMemo(() => {
const all = startup.view?.items ?? [];
return all.filter((item) => {
if (!showVendor && item.systemVendor) return false;
if (scope !== "all" && item.scope !== scope) return false;
if (riskyOnly && item.risks.length === 0) return false;
return true;
});
}, [riskyOnly, scope, showVendor, startup.view]);
const groups = useMemo(() => {
const needle = query.trim().toLowerCase();
const matching = needle
? listed.filter(
(item) =>
item.name.toLowerCase().includes(needle) ||
item.command.toLowerCase().includes(needle) ||
(item.program ?? "").toLowerCase().includes(needle) ||
(item.owner?.name ?? "").toLowerCase().includes(needle),
)
: listed;
const byOwner = new Map<string, StartupItem[]>();
for (const item of matching.filter((entry) => entry.category === tab)) {
const key = item.owner?.name ?? "";
byOwner.set(key, [...(byOwner.get(key) ?? []), item]);
}
return [...byOwner.entries()]
.map(([name, items]) => ({
key: name || "—",
name,
items: items.sort(
(a, b) => Number(a.systemVendor) - Number(b.systemVendor) || a.name.localeCompare(b.name),
),
}))
.sort(
(a, b) =>
Number(a.key === "—") - Number(b.key === "—") ||
a.name.localeCompare(b.name, "zh", { sensitivity: "base" }),
);
}, [listed, query, tab]);
const counts = {
"open-at-login": listed.filter((item) => item.category === "open-at-login").length,
background: listed.filter((item) => item.category === "background").length,
};
const shown = groups.reduce((total, group) => total + group.items.length, 0);
const searching = query.trim().length > 0;
// Coming from a process row means coming with a question: "is this one of mine,
// and where is it declared?" So the handed-over path becomes the search, vendor
// items stop being hidden, and whichever list holds it is opened.
//
// Applied once per handover. The inventory is re-read whenever the page opens and
// after every change, and an effect that keyed on it alone would restore this
// search and clear the filters the person has set since.
const handed = useRef<string | null>(null);
useEffect(() => {
if (!initialQuery || handed.current === initialQuery) return;
setQuery(initialQuery);
setShowVendor(true);
setScope("all");
const match = startup.view?.items.find(
(item) => item.program === initialQuery || item.command === initialQuery,
);
if (match) setTab(match.category);
// Until the inventory has arrived the tab is still a guess, so the handover
// stays open and runs again when the list it needs is finally there.
if (startup.view) handed.current = initialQuery;
}, [initialQuery, startup.view]);
/**
* Login items belong to macOS, which refuses to let another process write them, so
* the honest action beside a read-only row is the door to the pane that can.
*/
const openSettings = async () => {
try {
await api.openStartupSettings();
} catch (reason) {
push(messageFrom(reason), "danger");
}
};
const change = async (item: StartupItem, enabled: boolean) => {
try {
push(await startup.setEnabled(item, enabled), "success");
} catch (reason) {
push(messageFrom(reason), "danger");
} finally {
setPending(null);
}
};
const view = startup.view;
return (
<div className="page is-stacked">
<PageHeader
title={t("What your machine starts by itself", "你的电脑自己会启动什么")}
actions={
<Button
variant="ghost"
size="sm"
icon={<RefreshCw size={15} />}
onClick={() => void startup.refresh()}
disabled={startup.loading}
>
{t("Read again", "重新读取")}
</Button>
}
/>
{startup.error ? <InlineError message={startup.error} /> : null}
{view?.notes.length ? (
<div className="notice">
{view.notes.map((note) => (
<span key={`${note.kind}-${note.subject}`}>
<AlertTriangle size={13} />
{note.kind === "login-items-unavailable"
? t(
"macOS has not let Squid read the login items.",
"macOS 尚未允许 Squid 读取登录项。",
)
: t("This folder could not be listed:", "以下目录无法读取:")}{" "}
{note.kind === "unreadable-root" ? note.subject : null}
{note.detail ? ` — ${note.detail}` : ""}
</span>
))}
</div>
) : null}
<div className="chip-row page-tabs" role="tablist">
{(
[
["open-at-login", t("Login items", "登录项")],
["background", t("Background", "后台程序")],
] as [Tab, string][]
).map(([key, label]) => (
<button
key={key}
role="tab"
aria-selected={tab === key}
className={`filter-chip ${tab === key ? "is-active" : ""}`}
onClick={() => setTab(key)}
>
{label}
<b>{counts[key]}</b>
</button>
))}
</div>
<section className="panel">
<label className="search-field">
<Search size={14} />
<input
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder={t("Search name, command or path", "搜索名称、命令或路径")}
/>
</label>
<div className="chip-row">
<Select
value={scope}
align="start"
label={t("Scope", "范围")}
onChange={setScope}
options={[
{ value: "all", label: t("All scopes", "全部范围") },
{ value: "user", label: t("My user", "当前用户") },
{ value: "system", label: t("System", "系统") },
]}
/>
<button
className={`filter-chip ${riskyOnly ? "is-active" : ""}`}
onClick={() => setRiskyOnly((current) => !current)}
>
{t("Worth a look", "值得检查")}
</button>
<button
className={`filter-chip ${showVendor ? "is-active" : ""}`}
onClick={() => setShowVendor((current) => !current)}
>
{t("Operating system items", "系统自带条目")}
<b>{formatCount((view?.items ?? []).filter((item) => item.systemVendor).length)}</b>
</button>
</div>
</section>
{shown === 0 ? (
<EmptyState
icon={<ToggleLeft size={26} />}
title={
searching || riskyOnly
? t("Nothing matches", "没有符合条件的条目")
: tab === "open-at-login"
? t("Nothing opens when you log in", "登录时不会打开任何东西")
: t("No background entries are shown", "没有显示后台条目")
}
description={t(
"Operating system entries stay hidden until you show them above.",
"系统自带条目需要在上方手动显示。",
)}
/>
) : (
<section className="panel">
<SectionTitle
title={
tab === "open-at-login"
? t("Opens at login", "登录时打开")
: t("Runs in the background", "在后台运行")
}
subtitle={t(
"Disabling keeps the original file or value so it can be put back.",
"停用会保留原始文件或注册表值,可随时恢复。",
)}
action={
tab === "open-at-login" ? (
<button className="text-button" onClick={() => void openSettings()}>
<ExternalLink size={13} />
{t("Open System Settings", "打开系统设置")}
</button>
) : null
}
/>
{tab === "open-at-login" && !searching ? (
<ul className="item-list">
{groups.flatMap((group) => group.items).map((item) => (
<StartupRow
key={item.id}
item={item}
lang={lang}
busy={startup.busy}
showSource={false}
onOpen={setDetail}
onAsk={(next) => setPending({ item, enabled: next })}
/>
))}
</ul>
) : (
<ul className="group-list">
{groups.map((group) => (
<StartupGroup
key={group.key}
group={group}
expanded={searching || open.has(group.key)}
busy={startup.busy}
lang={lang}
onToggle={() =>
setOpen((current) => {
const next = new Set(current);
if (next.has(group.key)) next.delete(group.key);
else next.add(group.key);
return next;
})
}
onOpen={setDetail}
onAsk={(item, enabled) => setPending({ item, enabled })}
/>
))}
</ul>
)}
</section>
)}
<Modal
open={Boolean(detail)}
onClose={() => setDetail(null)}
size="drawer"
title={detail?.name ?? ""}
subtitle={
detail
? `${lang === "zh" ? SOURCE_LABEL[detail.source][1] : SOURCE_LABEL[detail.source][0]} · ${
detail.scope === "user" ? t("your user", "当前用户") : t("system", "系统")
}`
: undefined
}
footer={
detail ? (
<>
{revealTarget(detail) ? (
<Button
variant="ghost"
icon={<ExternalLink size={15} />}
onClick={() =>
void api
.revealPath(revealTarget(detail) as string)
.catch((reason) => push(messageFrom(reason), "danger"))
}
>
{t("Show in folder", "在文件夹中显示")}
</Button>
) : null}
<Button
variant={detail.disabled ? "primary" : "danger"}
disabled={!detail.modifiable || startup.busy}
icon={detail.disabled ? <ToggleRight size={15} /> : <ToggleLeft size={15} />}
onClick={() => {
const next = !detail.disabled;
setDetail(null);
setPending({ item: detail, enabled: next });
}}
>
{detail.disabled ? t("Enable", "启用") : t("Disable", "停用")}
</Button>
</>
) : null
}
>
{detail ? (
<StartupDetail
item={detail}
lang={lang}
onInspectProcess={onInspectProcess}
onScan={async (path) => {
setDetail(null);
await scanFile(path);
}}
/>
) : null}
</Modal>
<ConfirmDialog
open={Boolean(pending)}
title={
pending?.enabled
? t("Enable this startup item?", "要启用这个启动项吗?")
: t("Disable this startup item?", "要停用这个启动项吗?")
}
tone={pending?.enabled ? "default" : "danger"}
busy={startup.busy}
icon={<KeyRound size={22} />}
confirmLabel={pending?.enabled ? t("Enable", "启用") : t("Disable", "停用")}
cancelLabel={t("Cancel", "取消")}
message={pending?.item.name ?? ""}
onConfirm={() => pending && void change(pending.item, pending.enabled)}
onClose={() => setPending(null)}
>
<div className="confirm-path">
<code>{pending?.item.command}</code>
</div>
{pending?.item.scope === "system" ? (
<div className="confirm-warn">
{t(
"System-wide: changing it needs one authorisation.",
"系统级条目,修改需要一次系统授权。",
)}
</div>
) : null}
</ConfirmDialog>
</div>
);
}
/**
* One application and the entries it installed. Login items are shown flat, the way
* System Settings shows them, because there are usually only a few; background
* entries are folded under their application because a machine has twenty or more.
*/
function StartupGroup({
group,
expanded,
busy,
lang,
onToggle,
onOpen,
onAsk,
}: {
group: { key: string; name: string; items: StartupItem[] };
expanded: boolean;
busy: boolean;
lang: "zh" | "en";
onToggle: () => void;
onOpen: (item: StartupItem) => void;
onAsk: (item: StartupItem, enabled: boolean) => void;
}) {
const { t } = useI18n();
const risky = group.items.filter((item) => item.risks.length > 0).length;
const off = group.items.filter((item) => item.disabled).length;
const bundle = group.items.find((item) => item.owner?.bundlePath)?.owner?.bundlePath;
const signed = group.items.some((item) => item.signed);
return (
<li>
<button className="group-head" onClick={onToggle} aria-expanded={expanded}>
<span className="item-copy">
<strong>
{group.name || t("Not attributed to an app", "未归属到具体应用")}
</strong>
<small title={bundle ?? undefined}>
{bundle
? shortPath(bundle, 64)
: lang === "zh"
? SOURCE_LABEL[group.items[0].source][1]
: SOURCE_LABEL[group.items[0].source][0]}
</small>
</span>
<span className="group-meta">
{off > 0 ? (
<span className="status-chip is-neutral">{t(`${off} off`, `${off} 项已停用`)}</span>
) : null}
{risky > 0 ? (
<span className="status-chip is-warning">
<ShieldAlert size={11} />
{t(`${risky} worth a look`, `${risky} 项值得检查`)}
</span>
) : null}
{signed ? (
<span className="status-chip is-success">{t("signed", "已签名")}</span>
) : null}
<span className="group-count">{formatCount(group.items.length)}</span>
</span>
<ChevronDown size={15} className={`group-arrow ${expanded ? "is-open" : ""}`} />
</button>
{expanded ? (
<ul className="item-list is-nested">
{group.items.map((item) => (
<StartupRow
key={item.id}
item={item}
lang={lang}
busy={busy}
showSource
onOpen={onOpen}
onAsk={(enabled) => onAsk(item, enabled)}
/>
))}
</ul>
) : null}
</li>
);
}
function StartupRow({
item,
lang,
busy,
showSource,
onOpen,
onAsk,
}: {
item: StartupItem;
lang: "zh" | "en";
busy: boolean;
/** Where every row in sight comes from the same place, naming it again says nothing. */
showSource: boolean;
onOpen: (item: StartupItem) => void;
onAsk: (enabled: boolean) => void;
}) {
const { t } = useI18n();
const target = item.program ?? item.command;
return (
<li className={`item-row ${item.disabled ? "is-off" : ""} ${item.risks.length ? "is-risky" : ""}`}>
<button className="item-main" onClick={() => onOpen(item)}>
<span className="item-copy">
<strong>{item.name}</strong>
{target ? <small title={target}>{shortPath(target, 76)}</small> : null}
</span>
{item.risks.map((risk) => (
<span key={risk} className="status-chip is-warning">
<ShieldAlert size={11} />
{t(RISK_LABEL[risk][0], RISK_LABEL[risk][1])}
</span>
))}
{showSource ? (
<span className="startup-source">
{lang === "zh" ? SOURCE_LABEL[item.source][1] : SOURCE_LABEL[item.source][0]}
</span>
) : null}
{item.scope === "user" ? null : (
<span className="status-chip is-neutral">{t("system", "系统")}</span>
)}
</button>
{item.modifiable ? (
<Toggle
checked={!item.disabled}
disabled={busy}
label={t("Toggle startup item", "切换启动项")}
onChange={onAsk}
/>
) : (
<span className="muted-note">
<Lock size={14} />
{item.lock ? t(LOCK_LABEL[item.lock][0], LOCK_LABEL[item.lock][1]) : t("read-only", "只读")}
</span>
)}
<button className="icon-button" title={t("Details", "详情")} onClick={() => onOpen(item)}>
<ChevronRight size={16} />
</button>
</li>
);
}
function StartupDetail({
item,
lang,
onInspectProcess,
onScan,
}: {
item: StartupItem;
lang: "zh" | "en";
onInspectProcess: (filter: string) => void;
onScan: (path: string) => Promise<void>;
}) {
const { t } = useI18n();
const rows: [string, string][] = [];
if (item.owner) rows.push([t("Application", "所属应用"), item.owner.name]);
if (item.workingDirectory) rows.push([t("Working directory", "工作目录"), item.workingDirectory]);
if (item.program) rows.push([t("Program", "程序"), item.program]);
rows.push([t("Entry", "声明位置"), item.id]);
if (item.modifiedMs)
rows.push([
t("Modified", "修改时间"),
formatDate(new Date(item.modifiedMs).toISOString(), lang),
]);
rows.push([
t("Signature", "签名"),
item.publisher
? item.publisher
: item.signed
? t("Signed, vendor unknown", "已签名,发布者未知")
: item.risks.includes("signature-unreadable")
? t("Could not be read by this user", "当前用户无法读取")
: t("No usable signature", "无可用签名"),
]);
return (
<div className="item-detail">
<div className="detail-command">
<span>{t("Command", "命令")}</span>
<code>{item.command || t("(nothing recorded)", "(未记录)")}</code>
</div>
{item.risks.length ? (
<ul className="detail-risks">
{item.risks.map((risk) => (
<li key={risk}>
<ShieldAlert size={13} />
{t(RISK_LABEL[risk][0], RISK_LABEL[risk][1])}
</li>
))}
</ul>
) : null}
<dl className="detail-grid">
{rows.map(([label, value]) => (
<div key={`${label}-${value}`}>
<dt>{label}</dt>
<dd title={value}>{value}</dd>
</div>
))}
</dl>
{!item.modifiable ? (
<p className="detail-note">
<Lock size={13} />
{item.lock
? t(LOCK_LABEL[item.lock][0], LOCK_LABEL[item.lock][1])
: t(
"Squid installs no privileged helper, so system-wide entries stay read-only.",
"Squid 不安装特权 helper,系统级条目保持只读。",
)}
</p>
) : null}
<div className="detail-actions">
{item.program ? (
<>
<Button
variant="ghost"
size="sm"
icon={<FileSearch size={14} />}
onClick={() => void onScan(item.program as string)}
>
{t("Scan this file", "扫描该文件")}
</Button>
<Button
variant="ghost"
size="sm"
icon={<ToggleRight size={14} />}
onClick={() => onInspectProcess(item.program as string)}
>
{t("Find its process", "查看关联进程")}
</Button>
</>
) : null}
</div>
</div>
);
}

View File

@ -1,374 +0,0 @@
import {
ArrowLeft,
ChevronRight,
ExternalLink,
FileArchive,
FolderOpen,
FolderSearch,
HardDrive,
LoaderCircle,
RefreshCw,
ScanSearch,
} from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { open } from "@tauri-apps/plugin-dialog";
import * as apiClient from "../lib/api";
import { useI18n } from "../i18n";
import {
basename,
formatBytes,
formatCount,
percent,
shortPath,
} from "../lib/format";
import type { Bootstrap, StorageNode } from "../types";
import { useStorageWorkspace } from "../hooks/useStorageWorkspace";
import {
Button,
InlineError,
PageHeader,
ProgressCard,
SectionTitle,
} from "../components/ui";
const BAR_TONES = ["primary", "neutral"] as const;
function nodeSize(node: { allocated: number; logical: number }): number {
return node.allocated || node.logical;
}
function parentDirectory(path: string): string | null {
const normalized = path.replace(/[\\/]+$/, "");
const index = Math.max(normalized.lastIndexOf("/"), normalized.lastIndexOf("\\"));
if (index <= 0) return null;
if (/^[A-Za-z]:[\\/]/.test(normalized) && index === 2) {
return `${normalized.slice(0, 2)}\\`;
}
return normalized.slice(0, index);
}
export function StoragePage({ bootstrap }: { bootstrap: Bootstrap }) {
const { t } = useI18n();
const workspace = useStorageWorkspace();
const [pathInput, setPathInput] = useState("");
const [manualPath, setManualPath] = useState(false);
useEffect(() => {
if (workspace.node && !manualPath) setPathInput(workspace.node.path);
}, [manualPath, workspace.node]);
const children = useMemo(
() =>
workspace.node
? [...workspace.node.children].sort((a, b) => nodeSize(b) - nodeSize(a))
: [],
[workspace.node],
);
const nodeTotal = workspace.node
? Math.max(nodeSize(workspace.node), 1)
: 1;
const visibleShare = children.reduce((sum, child) => sum + nodeSize(child), 0);
const rest = percent(visibleShare, nodeTotal);
const explore = (path?: string | null) => {
setManualPath(false);
void workspace.explore(path);
};
const chooseFolder = async () => {
const chosen = await open({
directory: true,
multiple: false,
title: t("Choose a folder to analyse", "选择要分析的文件夹"),
});
if (typeof chosen === "string") explore(chosen);
};
const reveal = (path: string) => {
void apiClient.api.revealPath(path).catch(() => undefined);
};
const drill = (node: StorageNode) => {
if (!node.is_dir || node.path === workspace.node?.path) return;
explore(node.path);
};
const parent = workspace.node ? parentDirectory(workspace.node.path) : null;
return (
<div className="page storage-page">
<PageHeader
title={t("See space clearly", "看清每一寸空间")}
actions={
<>
{parent ? (
<Button variant="ghost" icon={<ArrowLeft size={15} />} onClick={() => explore(parent)}>
{t("Up", "上一级")}
</Button>
) : null}
<Button variant="secondary" icon={<FolderOpen size={15} />} onClick={() => void chooseFolder()}>
{t("Choose folder", "选择文件夹")}
</Button>
</>
}
/>
<div className="storage-pathbar">
<span className="pathbar-icon">
<HardDrive size={17} />
</span>
<input
value={pathInput}
onChange={(event) => {
setPathInput(event.target.value);
setManualPath(true);
}}
onKeyDown={(event) => {
if (event.key === "Enter" && pathInput.trim()) explore(pathInput.trim());
}}
spellCheck={false}
aria-label={t("Folder path", "文件夹路径")}
/>
<Button
variant="primary"
size="sm"
icon={<ScanSearch size={14} />}
onClick={() => explore(pathInput.trim() || null)}
disabled={workspace.exploring || workspace.scanningFiles}
>
{t("Analyse", "分析")}
</Button>
</div>
{workspace.error ? (
<InlineError message={workspace.error} onDismiss={workspace.clearError} />
) : null}
{workspace.exploring ? (
<ProgressCard
progress={workspace.progress}
title={t("Measuring folders…", "正在测量文件夹…")}
onCancel={() => void workspace.cancel()}
/>
) : null}
{workspace.node && !workspace.exploring ? (
<>
<section className="storage-overview">
<div className="storage-overview-head">
<div>
<span className="field-label">{t("Current folder", "当前文件夹")}</span>
<h2 title={workspace.node.path}>{shortPath(workspace.node.path, 72)}</h2>
</div>
<div className="storage-total">
<strong>{formatBytes(nodeSize(workspace.node))}</strong>
<span>
{t(
`${formatCount(workspace.node.files)} files · ${formatCount(
workspace.node.dirs,
)} folders`,
`${formatCount(workspace.node.files)} 个文件 · ${formatCount(
workspace.node.dirs,
)} 个文件夹`,
)}
</span>
</div>
</div>
{children.length > 0 ? (
<>
<div className="storage-map" aria-label={t("Folder distribution", "文件夹占比")}>
{children.map((child, index) => (
<span
key={`${child.path}-${index}`}
className={`tone-${BAR_TONES[index % BAR_TONES.length]}`}
style={{ width: `${percent(nodeSize(child), nodeTotal)}%` }}
title={`${basename(child.path)} · ${formatBytes(nodeSize(child))}`}
/>
))}
<span className="storage-map-rest" />
</div>
{workspace.node.folded > 0 ? (
<p className="storage-folded">
{t(
`${workspace.node.folded} smaller folders (${formatBytes(
workspace.node.folded_size,
)}) are folded into the remainder.`,
`${workspace.node.folded} 个较小文件夹(${formatBytes(
workspace.node.folded_size,
)})已合并显示。`,
)}
</p>
) : null}
<div className="storage-children">
{children.map((child, index) => {
const share = percent(nodeSize(child), nodeTotal);
return (
<button
key={`${child.path}-${index}`}
className={`storage-child ${
child.is_dir && child.path !== workspace.node?.path
? "is-navigable"
: ""
}`}
onClick={() => drill(child)}
>
<span className={`storage-child-dot tone-${BAR_TONES[index % BAR_TONES.length]}`} />
<span className="storage-child-icon">
{child.is_dir ? <FolderOpen size={19} /> : <FileArchive size={19} />}
</span>
<span className="storage-child-copy">
<strong>{basename(child.path)}</strong>
<small title={child.path}>
{shortPath(child.path, 62)}
{!child.readable ? ` · ${t("partially unreadable", "部分不可读")}` : ""}
</small>
<span className="storage-mini-track">
<span
className={`tone-${BAR_TONES[index % BAR_TONES.length]}`}
style={{ width: `${share}%` }}
/>
</span>
</span>
<span className="storage-child-size">
<strong>{formatBytes(nodeSize(child))}</strong>
<small>{share.toFixed(1)}%</small>
</span>
<span className="storage-child-actions">
<span
role="button"
tabIndex={0}
className="row-reveal"
title={t("Show in Finder", "在访达中显示")}
onClick={(event) => {
event.stopPropagation();
reveal(child.path);
}}
onKeyDown={(event) => {
if (event.key === "Enter") reveal(child.path);
}}
>
<ExternalLink size={14} />
</span>
{child.is_dir && child.path !== workspace.node?.path ? (
<ChevronRight size={15} />
) : null}
</span>
</button>
);
})}
{rest < 100 ? (
<div className="storage-child is-muted">
<span className="storage-child-dot" />
<span className="storage-child-icon">
<BoxesIcon />
</span>
<span className="storage-child-copy">
<strong>{t("Other folders", "其他文件夹")}</strong>
<small>{t("Not among the largest entries", "不在最大项目之列")}</small>
</span>
<span className="storage-child-size">
<strong>
{formatBytes(Math.max(0, nodeSize(workspace.node) - visibleShare))}
</strong>
<small>{(100 - rest).toFixed(1)}%</small>
</span>
</div>
) : null}
</div>
</>
) : (
<div className="empty-inline">
<FolderSearch size={21} />
<span>{t("This folder has no measurable children.", "此文件夹没有可测量的子项。")}</span>
</div>
)}
</section>
<section className="storage-large">
<SectionTitle
title={t("Largest files", "最大文件")}
subtitle={t(
"Over 1 MB in the current folder, largest first.",
"当前文件夹中大于 1 MB 的文件,从大到小。",
)}
action={
<Button
variant="secondary"
size="sm"
icon={
workspace.scanningFiles ? (
<LoaderCircle size={14} className="spin" />
) : (
<ScanSearch size={14} />
)
}
onClick={() =>
workspace.files.length > 0
? workspace.clearFiles()
: void workspace.largestFiles(workspace.node!.path)
}
disabled={workspace.exploring || workspace.scanningFiles}
>
{workspace.files.length > 0
? t("Hide", "隐藏")
: t("Find large files", "查找大文件")}
</Button>
}
/>
{workspace.scanningFiles ? (
<ProgressCard
progress={workspace.progress}
title={t("Searching for the largest files…", "正在查找最大文件…")}
compact
onCancel={() => void workspace.cancel()}
/>
) : null}
{workspace.files.length > 0 ? (
<div className="large-file-list">
{workspace.files.map((file, index) => (
<div className="large-file-row" key={`${file.path}-${index}`}>
<span className="large-file-rank">{String(index + 1).padStart(2, "0")}</span>
<span className="large-file-icon">
<FileArchive size={16} />
</span>
<span className="large-file-copy">
<strong>{basename(file.path)}</strong>
<small title={file.path}>{shortPath(file.path, 76)}</small>
</span>
<span className="large-file-size">
{formatBytes(file.allocated || file.logical)}
</span>
<button className="row-reveal" onClick={() => reveal(file.path)}>
<ExternalLink size={14} />
</button>
</div>
))}
</div>
) : null}
</section>
</>
) : null}
{!workspace.node && !workspace.exploring ? (
<button className="storage-start" onClick={() => explore(null)}>
<span>
<RefreshCw size={25} />
</span>
<strong>{t("Start with your home folder", "从用户主目录开始")}</strong>
<small>{bootstrap.settings.purgeRoots[0] || t("Home", "用户主目录")}</small>
</button>
) : null}
</div>
);
}
function BoxesIcon() {
return (
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true">
<path d="m12 3 8 4.5v9L12 21l-8-4.5v-9L12 3Z" stroke="currentColor" strokeWidth="1.7" />
<path d="m4.5 7.8 7.5 4.3 7.5-4.3M12 12.1V21" stroke="currentColor" strokeWidth="1.7" />
</svg>
);
}

View File

@ -0,0 +1,316 @@
/* 桌面小工具 management page: master switch, per-panel toggles, appearance &
* behaviour, and a live desktop preview. All edits go through widget_set, so
* the desktop window reacts immediately (and back-syncs via the event). */
import { useEffect, useState } from "react";
import { useI18n } from "../i18n";
import { api } from "../lib/api";
import { messageFrom } from "../lib/format";
import type { SystemSnapshot, WidgetCorner, WidgetPrefs } from "../types";
import { InlineError, PageHeader, SectionTitle, Toggle } from "../components/ui";
import { WidgetPanels, useHistory } from "../components/WidgetPanels";
const CORNERS: { id: WidgetCorner; en: string; zh: string }[] = [
{ id: "top-right", en: "Top right", zh: "右上角" },
{ id: "top-left", en: "Top left", zh: "左上角" },
{ id: "bottom-right", en: "Bottom right", zh: "右下角" },
{ id: "bottom-left", en: "Bottom left", zh: "左下角" },
];
const INTERVALS = [2_000, 5_000, 10_000];
export function WidgetPage() {
const { t, lang } = useI18n();
const zh = lang === "zh";
const [prefs, setPrefs] = useState<WidgetPrefs | null>(null);
const [snapshot, setSnapshot] = useState<SystemSnapshot | null>(null);
const [error, setError] = useState<string | null>(null);
const [history, bump] = useHistory();
useEffect(() => {
let cancelled = false;
let stop: (() => void) | null = null;
void api
.widgetGet()
.then((view) => !cancelled && setPrefs(view.prefs))
.catch((reason) => !cancelled && setError(messageFrom(reason)));
void api
.onWidgetSettings((next) => !cancelled && setPrefs(next))
.then((unlisten) => {
if (cancelled) unlisten();
else stop = unlisten;
});
return () => {
cancelled = true;
stop?.();
};
}, []);
// The preview runs on the same live data as the desktop widget.
useEffect(() => {
let live = true;
const tick = async () => {
if (document.hidden) return;
try {
const next = await api.systemSnapshot(false);
if (live) {
setSnapshot(next);
bump(next);
}
} catch {
/* ignore — the widget page is advisory */
}
};
void tick();
const timer = window.setInterval(() => void tick(), 2_000);
return () => {
live = false;
window.clearInterval(timer);
};
}, [bump]);
const patch = (values: Parameters<typeof api.widgetSet>[0]) => {
setError(null);
void api
.widgetSet(values)
.then(setPrefs)
.catch((reason) => setError(messageFrom(reason)));
};
if (!prefs) return null;
const panels = [
{
key: "panelRun" as const,
icon: "◔",
name: t("Status rings", "运行状态"),
desc: t(
"CPU / memory / GPU rings, device name and session uptime.",
"CPU / 内存 / GPU 占用圆环、设备名、本次运行时长",
),
},
{
key: "panelCpu" as const,
icon: "▦",
name: "CPU",
desc: t(
"Total usage curve plus a full-width row of gradient load bars, one per logical core.",
"总体占用率曲线 + 整行渐变占用柱,一根柱对应一个逻辑核心(绿→黄→橙→红连续渐变,悬停看具体百分比)",
),
},
{
key: "panelNetwork" as const,
icon: "⇅",
name: t("Network", "网络"),
desc: t(
"Live up/down throughput with history curves.",
"实时上下行速率与历史曲线",
),
},
{
key: "panelDisk" as const,
icon: "⛁",
name: t("Disk I/O", "存储读写"),
desc: t(
"Live disk read/write throughput with history curve.",
"磁盘实时读写速率与历史曲线",
),
},
{
key: "panelStorage" as const,
icon: "▾",
name: t("Storage volumes", "存储空间"),
desc: t(
"Used / total bars for every drive.",
"每个盘符的已用 / 总容量进度条",
),
},
];
return (
<div className="page widget-page">
<PageHeader
eyebrow={t("Desktop", "桌面")}
title={t("A live monitor right on your desktop", "桌面上放一块实时看板")}
actions={
<Toggle
checked={prefs.enabled}
onChange={(next) => patch({ enabled: next })}
label={t("Desktop widget switch", "桌面小工具总开关")}
/>
}
/>
{error ? <InlineError message={error} onDismiss={() => setError(null)} /> : null}
<div className="widget-note">
{t(
"The widget is a borderless desktop-layer window (below your app windows) that never steals focus; it hides itself when every panel or the master switch is off.",
"小工具以无边框的桌面层窗口显示:贴在壁纸上、位于其他软件窗口之下,不抢焦点;关闭全部面板或总开关后窗口自动隐藏。",
)}
</div>
<div className="widget-grid">
<section className="settings-section">
<SectionTitle
title={t("Panels", "面板")}
subtitle={t(
"Pick the cards that show on the desktop; the order matches the widget.",
"选择要出现在桌面小工具里的卡片,顺序与桌面上的排列一致。",
)}
/>
<div className="perm-rows">
{panels.map((panel) => (
<div className="settings-row" key={panel.key}>
<div className="perm-row">
<span className="widget-row-ico">{panel.icon}</span>
<div>
<span>{panel.name}</span>
<small>{panel.desc}</small>
</div>
</div>
<Toggle
checked={prefs[panel.key]}
disabled={!prefs.enabled}
onChange={(next) => patch({ [panel.key]: next })}
label={panel.name}
/>
</div>
))}
</div>
</section>
<section className="settings-section">
<SectionTitle
title={t("Appearance & behaviour", "外观与行为")}
subtitle={t(
"The widget window stays borderless, desktop-layer and focus-free.",
"小工具窗口始终无边框、贴在桌面层、不抢焦点。",
)}
/>
<div className="perm-rows">
<div className="settings-row">
<div className="perm-row">
<div>
<span>{t("Opacity", "不透明度")}</span>
<small>
{t(
"100% is fully solid; at most 10% of the desktop shows through.",
"100% 为完全不透明,最多透出 10% 桌面背景",
)}
</small>
</div>
</div>
<input
className="widget-range"
type="range"
min={90}
max={100}
value={prefs.opacity}
disabled={!prefs.enabled}
onChange={(event) => patch({ opacity: Number(event.target.value) })}
/>
</div>
<div className="settings-row">
<div className="perm-row">
<div>
<span>{t("Refresh rate", "更新频率")}</span>
<small>
{t(
"Sampling interval; higher rates cost a little more power.",
"采样间隔,频率越高越耗电",
)}
</small>
</div>
</div>
<select
className="settings-select"
value={prefs.intervalMs}
disabled={!prefs.enabled}
onChange={(event) => patch({ intervalMs: Number(event.target.value) })}
>
{INTERVALS.map((ms) => (
<option key={ms} value={ms}>
{t(`${ms / 1000} seconds`, `${ms / 1000} 秒`)}
</option>
))}
</select>
</div>
<div className="settings-row">
<div className="perm-row">
<div>
<span>{t("Dock corner", "显示位置")}</span>
<small>
{t(
"Where it lands when opened; drag it anywhere afterwards.",
"初次打开停靠的屏幕角,之后可用鼠标拖到任意位置",
)}
</small>
</div>
</div>
<select
className="settings-select"
value={prefs.corner}
disabled={!prefs.enabled}
onChange={(event) =>
patch({ corner: event.target.value as WidgetCorner })
}
>
{CORNERS.map((corner) => (
<option key={corner.id} value={corner.id}>
{zh ? corner.zh : corner.en}
</option>
))}
</select>
</div>
<div className="settings-row">
<div className="perm-row">
<div>
<span>{t("Remember folded state", "折叠记忆")}</span>
<small>
{t(
"Keep the collapsed/expanded choice across restarts.",
"记住上次是否折叠,重启后保持",
)}
</small>
</div>
</div>
<Toggle
checked={prefs.rememberCollapsed}
disabled={!prefs.enabled}
onChange={(next) => patch({ rememberCollapsed: next })}
label={t("Remember folded state", "折叠记忆")}
/>
</div>
</div>
</section>
</div>
<section className="settings-section widget-preview-section">
<SectionTitle
title={t("Preview", "预览")}
subtitle={t(
"Live look of the desktop widget (top of the screen).",
"桌面小工具的实时效果(屏幕上方)。",
)}
/>
<div className="widget-preview-stage">
<div className="widget widget-preview" style={{ opacity: prefs.opacity / 100 }}>
<div className="wd-card wd-head">
<span className="wd-head-dot" />
<span className="wd-head-spacer" />
<span className="wd-head-dot" />
</div>
{prefs.enabled ? (
<WidgetPanels snapshot={snapshot} prefs={prefs} history={history} zh={zh} />
) : (
<div className="wd-card widget-off-hint">
{t(
"The widget is switched off — flip the master switch to see it on your desktop.",
"小工具已关闭 —— 打开总开关后即可在桌面看到它。",
)}
</div>
)}
</div>
</div>
</section>
</div>
);
}

View File

@ -1,41 +1,29 @@
/* The desktop live-monitor window content (index.html?view=widget): header bar
* with settings + collapse, live panels, and the settings dropdown. */
import { Activity, ChevronUp, Settings2 } from "lucide-react";
/* The 桌面小工具 window content (index.html?view=widget): header bar with
* settings + collapse, live panels, and a compact settings popover that
* writes straight through to widget_set (broadcast keeps the main page in
* sync). */
import { useCallback, useEffect, useRef, useState } from "react";
import { getCurrentWindow, LogicalSize } from "@tauri-apps/api/window";
import { api } from "../lib/api";
import { messageFrom } from "../lib/format";
import type { WidgetCorner, WidgetPrefs } from "../types";
import type { WidgetPrefs } from "../types";
import { WidgetPanels, useHistory } from "../components/WidgetPanels";
import { Select } from "../components/ui";
import type { SystemSnapshot } from "../types";
const PANELS: { key: keyof WidgetPrefs; en: string; zh: string }[] = [
{ key: "panelRun", en: "Status", zh: "运行状态" },
{ key: "panelCpu", en: "CPU", zh: "CPU" },
{ key: "panelNetwork", en: "Network", zh: "网络" },
{ key: "panelDisk", en: "Disk I/O", zh: "存储读写" },
{ key: "panelStorage", en: "Storage", zh: "存储空间" },
const PANELS: { key: keyof WidgetPrefs; label: string }[] = [
{ key: "panelRun", label: "运行状态" },
{ key: "panelCpu", label: "CPU" },
{ key: "panelNetwork", label: "网络" },
{ key: "panelDisk", label: "存储读写" },
{ key: "panelStorage", label: "存储空间" },
];
const CORNERS: { id: WidgetCorner; en: string; zh: string }[] = [
{ id: "top-right", en: "Top right", zh: "右上角" },
{ id: "top-left", en: "Top left", zh: "左上角" },
{ id: "bottom-right", en: "Bottom right", zh: "右下角" },
{ id: "bottom-left", en: "Bottom left", zh: "左下角" },
];
const INTERVALS = [2_000, 5_000, 10_000];
export function WidgetWindow() {
const [prefs, setPrefs] = useState<WidgetPrefs | null>(null);
const [language, setLanguage] = useState<"zh" | "en">("en");
const [snapshot, setSnapshot] = useState<SystemSnapshot | null>(null);
const [open, setOpen] = useState(false);
const [history, bump] = useHistory();
const windowRef = useRef(getCurrentWindow());
const settingsRef = useRef<HTMLDivElement | null>(null);
const settingsButtonRef = useRef<HTMLButtonElement | null>(null);
useEffect(() => {
// The window is transparent; punch through the app's opaque body paint.
@ -48,11 +36,7 @@ export function WidgetWindow() {
let stop: (() => void) | null = null;
void api
.widgetGet()
.then((view) => {
if (cancelled) return;
setPrefs(view.prefs);
setLanguage(view.language);
})
.then((view) => !cancelled && setPrefs(view.prefs))
.catch((reason) => console.error(messageFrom(reason)));
void api
.onWidgetSettings((next) => !cancelled && setPrefs(next))
@ -70,20 +54,12 @@ export function WidgetWindow() {
// table, so it rides the light refresh, and an all-collapsed widget goes
// silent until the header is opened again.
const collapsed = Boolean(prefs?.collapsed);
const hasPanels = Boolean(
prefs &&
(prefs.panelRun ||
prefs.panelCpu ||
prefs.panelNetwork ||
prefs.panelDisk ||
prefs.panelStorage),
);
const intervalMs = prefs?.intervalMs ?? 2000;
useEffect(() => {
if (!prefs?.enabled || collapsed || !hasPanels) return;
if (!prefs?.enabled || collapsed) return;
let live = true;
const tick = async () => {
if (!live) return;
if (!live || document.hidden) return;
// Desktop-layer windows report `document.hidden` whenever another app
// occludes them; ask Tauri whether the window is actually hidden.
try {
@ -107,19 +83,18 @@ export function WidgetWindow() {
live = false;
window.clearInterval(timer);
};
}, [bump, collapsed, hasPanels, intervalMs, prefs?.enabled]);
// Last persisted drag position; null while the widget is corner-docked.
const lastPos = useRef<{ x: number; y: number } | null>(null);
}, [bump, collapsed, intervalMs, prefs?.enabled]);
const patch = useCallback((values: Parameters<typeof api.widgetSet>[0]) => {
if (values.corner) lastPos.current = null;
void api
.widgetSet(values)
.then(setPrefs)
.catch((reason) => console.error(messageFrom(reason)));
}, []);
// Last persisted drag position; null while the widget is corner-docked.
const lastPos = useRef<{ x: number; y: number } | null>(null);
// Grow/shrink the window to the stacked cards so transparent space never
// eats desktop clicks (scrollHeight is CSS px == LogicalSize units).
// Only an actual height change may call setSize/redock: setSize answers
@ -137,14 +112,16 @@ export function WidgetWindow() {
const fit = () => {
window.cancelAnimationFrame(frame);
frame = window.requestAnimationFrame(() => {
const height = Math.max(64, root.scrollHeight + 12);
const height = Math.max(64, root.scrollHeight + 4);
if (height === lastFit.current) return;
lastFit.current = height;
void windowRef.current
?.setSize(new LogicalSize(350, height))
.then(() => {
// Keep the docked corner anchored after the size change.
if (!lastPos.current) void api.widgetSet({ redock: true }).catch(() => undefined);
// Keep the widget anchored after the size change: redock runs
// the backend maths, which re-corners a corner-docked widget and
// keeps (clamped) a remembered drag spot — correct in both modes.
void api.widgetSet({ redock: true }).catch(() => undefined);
})
.catch(() => {
lastFit.current = 0;
@ -165,69 +142,43 @@ export function WidgetWindow() {
patch({ collapsed: !collapsed });
};
const toggleSettings = () => {
if (!open && collapsed) patch({ collapsed: false });
setOpen((value) => !value);
};
// Persist a *real* drag after the pointer settles (the header is a native
// drag region, so poll once shortly after mouseup). Mere clicks must not
// pin the position: seed lastPos with the true current spot on mount, and
// only persist once the window has actually moved (≥5 px). An earlier bug
// let a click right after an RDP re-layout save the drifted mid-screen
// spot as "the user's chosen position" forever.
useEffect(() => {
if (!open) return;
const close = (event: PointerEvent) => {
const target = event.target as Node;
if (
settingsRef.current?.contains(target) ||
settingsButtonRef.current?.contains(target)
) {
return;
}
setOpen(false);
};
document.addEventListener("pointerdown", close);
return () => document.removeEventListener("pointerdown", close);
}, [open]);
// Persist a dragged position after the pointer settles (the header is a
// native drag region, so poll once shortly after mouseup).
useEffect(() => {
const pressed = { current: null as { x: number; y: number } | null };
const onDown = (event: MouseEvent) => {
const target = event.target as HTMLElement;
if (
!target.closest("[data-tauri-drag-region]") ||
target.closest("button, input, select, .wd-settings")
) {
return;
}
pressed.current = { x: event.screenX, y: event.screenY };
};
const onUp = (event: MouseEvent) => {
const start = pressed.current;
pressed.current = null;
if (!start || Math.hypot(event.screenX - start.x, event.screenY - start.y) < 4) {
return;
}
void windowRef.current
?.outerPosition()
.then((position) => {
lastPos.current = position;
})
.catch(() => undefined);
const onUp = () => {
window.setTimeout(() => {
void windowRef.current
?.outerPosition()
.then((position) => {
const previous = lastPos.current;
if (previous && previous.x === position.x && previous.y === position.y) return;
if (
previous &&
Math.abs(previous.x - position.x) < 5 &&
Math.abs(previous.y - position.y) < 5
) {
return;
}
lastPos.current = position;
patch({ position: [position.x, position.y], keepPosition: true });
})
.catch(() => undefined);
}, 350);
};
window.addEventListener("mousedown", onDown);
window.addEventListener("mouseup", onUp);
return () => {
window.removeEventListener("mousedown", onDown);
window.removeEventListener("mouseup", onUp);
};
return () => window.removeEventListener("mouseup", onUp);
}, [patch]);
if (!prefs) return <div className="widget widget-loading" />;
const zh = language === "zh";
return (
<div
ref={rootRef}
@ -235,137 +186,73 @@ export function WidgetWindow() {
style={{ opacity: (prefs.opacity ?? 100) / 100 }}
>
<div className="wd-card wd-head" data-tauri-drag-region>
<span className="wd-brand">
<Activity size={15} />
<b>{zh ? "实时监控" : "Live monitor"}</b>
</span>
<span className="wd-head-spacer" />
<button
ref={settingsButtonRef}
type="button"
className={`wd-head-btn ${open ? "is-active" : ""}`}
aria-label={zh ? "打开设置" : "Open settings"}
title={zh ? "设置" : "Settings"}
onClick={toggleSettings}
className="wd-head-btn"
aria-label="小部件设置"
title="小部件设置"
onClick={() => setOpen((value) => !value)}
>
<Settings2 size={17} />
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
<path d="M4 7h10M18 7h2M4 12h2M10 12h10M4 17h13" />
<circle cx="16" cy="7" r="2" />
<circle cx="8" cy="12" r="2" />
<circle cx="19" cy="17" r="2" />
</svg>
</button>
<span className="wd-head-spacer" />
<button
type="button"
className={`wd-head-btn wd-chevron ${collapsed ? "is-collapsed" : ""}`}
aria-label={collapsed ? (zh ? "展开" : "Expand") : zh ? "折叠" : "Collapse"}
title={collapsed ? (zh ? "展开" : "Expand") : zh ? "折叠" : "Collapse"}
aria-label={collapsed ? "展开" : "折叠"}
title={collapsed ? "展开" : "折叠"}
onClick={toggleCollapsed}
>
<ChevronUp size={18} />
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
<path d="m6 15 6-6 6 6" />
</svg>
</button>
</div>
{open ? (
<div ref={settingsRef} className="wd-card wd-settings">
<div className="wd-settings-head">
<div>
<h4>{zh ? "实时监控设置" : "Live monitor settings"}</h4>
<span>{zh ? "更改会立即生效" : "Changes apply immediately"}</span>
</div>
<button type="button" className="wd-settings-done" onClick={() => setOpen(false)}>
{zh ? "完成" : "Done"}
</button>
</div>
<div className="wd-settings-section">
<span className="wd-settings-label">{zh ? "面板" : "Panels"}</span>
{PANELS.map((panel) => (
<div className="wd-set-row" key={panel.key}>
<span>{zh ? panel.zh : panel.en}</span>
<button
type="button"
className={`wd-set-toggle ${prefs[panel.key] ? "is-on" : ""}`}
role="switch"
aria-checked={Boolean(prefs[panel.key])}
aria-label={zh ? panel.zh : panel.en}
onClick={() => patch({ [panel.key]: !prefs[panel.key] })}
/>
</div>
))}
</div>
<div className="wd-settings-section">
<span className="wd-settings-label">{zh ? "外观与行为" : "Appearance & behaviour"}</span>
<div className="wd-set-row">
<span>{zh ? "不透明度" : "Opacity"}</span>
<div className="wd-set-control">
<input
className="wd-range"
type="range"
min={90}
max={100}
value={prefs.opacity}
aria-label={zh ? "不透明度" : "Opacity"}
onChange={(event) => patch({ opacity: Number(event.target.value) })}
/>
<b>{prefs.opacity}%</b>
</div>
</div>
<div className="wd-set-row">
<span>{zh ? "更新频率" : "Refresh rate"}</span>
<Select
value={prefs.intervalMs}
label={zh ? "更新频率" : "Refresh rate"}
options={INTERVALS.map((ms) => ({
value: ms,
label: zh ? `${ms / 1000} 秒` : `${ms / 1000} seconds`,
}))}
onChange={(intervalMs) => patch({ intervalMs })}
/>
</div>
<div className="wd-set-row">
<span>{zh ? "显示位置" : "Dock corner"}</span>
<Select
value={prefs.corner}
label={zh ? "显示位置" : "Dock corner"}
placement="up"
options={CORNERS.map((corner) => ({
value: corner.id,
label: zh ? corner.zh : corner.en,
}))}
onChange={(corner) => patch({ corner })}
/>
</div>
<div className="wd-set-row">
<span>{zh ? "记住折叠状态" : "Remember folded state"}</span>
{open && !collapsed ? (
<div className="wd-card wd-settings">
<h4>小部件设置</h4>
{PANELS.map((panel) => (
<div className="wd-set-row" key={panel.key}>
<span>{panel.label}</span>
<button
type="button"
className={`wd-set-toggle ${prefs.rememberCollapsed ? "is-on" : ""}`}
className={`wd-set-toggle ${prefs[panel.key] ? "is-on" : ""}`}
role="switch"
aria-checked={prefs.rememberCollapsed}
aria-label={zh ? "记住折叠状态" : "Remember folded state"}
onClick={() =>
patch({ rememberCollapsed: !prefs.rememberCollapsed })
}
aria-checked={Boolean(prefs[panel.key])}
aria-label={panel.label}
onClick={() => patch({ [panel.key]: !prefs[panel.key] })}
/>
</div>
))}
<div className="wd-set-row">
<span>不透明度</span>
<input
className="wd-range"
type="range"
min={90}
max={100}
value={prefs.opacity}
onChange={(event) => patch({ opacity: Number(event.target.value) })}
/>
</div>
<button
type="button"
className="wd-close-line"
onClick={() => patch({ enabled: false })}
>
{zh ? "关闭桌面实时监控" : "Turn off desktop monitor"}
关闭小工具
</button>
</div>
) : null}
{!collapsed ? (
<WidgetPanels snapshot={snapshot} prefs={prefs} history={history} zh={zh} />
) : null}
{!collapsed && !hasPanels ? (
<div className="wd-card wd-empty">
{zh
? "所有面板都已关闭,点击右上角设置重新开启。"
: "All panels are off. Open Settings at the top right to bring them back."}
</div>
<WidgetPanels snapshot={snapshot} prefs={prefs} history={history} zh />
) : null}
</div>
);

File diff suppressed because it is too large Load Diff

View File

@ -1,14 +1,13 @@
export type Language = "zh" | "en";
export type PageId =
| "overview"
| "cleanup"
| "space"
| "applications"
| "purge"
| "permissions"
| "storage"
| "system"
| "security"
| "startup"
| "widget"
| "system"
| "maintenance"
| "history"
| "settings";
@ -23,7 +22,10 @@ export type Category =
| "trash"
| "language-packs"
| "leftovers"
| "update-installers";
| "update-installers"
| "duplicates"
| "ai-tools"
| "privacy";
export type ItemKind = "path" | "contents" | "file";
export type LockReason =
| "app-running"
@ -45,6 +47,11 @@ export interface CleanupItem {
selected: boolean;
lock: LockReason | null;
note: string | null;
/** Seconds since the newest last-write inside the item (A③). */
lastWriteSecs?: number | null;
fileCount?: number;
/** Machine tokens for the B3 evidence panel ("lock:package-lock.json"). */
evidence?: string[];
}
export interface ScanResult {
@ -71,7 +78,15 @@ export interface DeleteResult {
export interface JobProgress {
jobId: string;
kind: string;
event: "phase" | "tick" | "note" | "warning" | "deleted" | "bucket";
event:
| "phase"
| "tick"
| "note"
| "warning"
| "deleted"
| "bucket"
| "metered"
| "group";
phase: string | null;
detail: string | null;
done: number | null;
@ -139,7 +154,6 @@ export interface AppInfo {
name: string;
bundle_id: string | null;
path: string;
icon_source: string | null;
version: string | null;
size: number;
source: string;
@ -148,6 +162,12 @@ export interface AppInfo {
publisher: string | null;
installed_ms: number | null;
display_icon: string | null;
/** Recorded uninstaller command (Windows), when the app left one. */
uninstall_string?: string | null;
/** Windows: "HKLM64|<subkey>" — the uninstall registry record itself. */
reg_key?: string | null;
/** 安装不完整: the record survives but the product files are gone. */
dead?: boolean;
/** data-URL PNG icon (apps_scan only; null when extraction failed). */
icon?: string | null;
}
@ -254,14 +274,38 @@ export interface StorageNode {
allocated: number;
files: number;
dirs: number;
is_dir: boolean;
isDir: boolean;
readable: boolean;
children: StorageNode[];
folded: number;
folded_size: number;
foldedSize: number;
complete: boolean;
}
/** storage_explore now answers with freshness metadata (A⑥ size cache). */
export interface ExploreResult {
node: StorageNode;
cached: boolean;
measuredAtMs: number | null;
}
/** Hidden-space insight row (A⑤, Mole overview idiom). */
export interface SpaceInsight {
id: string;
title: string;
path: string;
size: number;
action: "cleanable" | "command" | "external" | "info";
command: string | null;
hint: string;
}
/** cleanup_preflight verdict (B1 last-second re-check). */
export interface PreflightResult {
checked: number;
blocked: { path: string; reason: string }[];
}
export interface LargestFile {
path: string;
logical: number;
@ -269,6 +313,97 @@ export interface LargestFile {
modified_ms: number | null;
}
// ---- duplicate files (重复文件) ------------------------------------------
export interface DupCopy {
/** Display spelling; `~` folded for the home folder. */
path: string;
mtimeMs: number;
/** Why this copy may not be deleted (protected user asset), when it may not. */
locked: string | null;
}
export interface DupGroup {
size: number;
copies: DupCopy[];
/** Index the UI marks 「保留」 by default. */
keep: number;
/** At least one copy sits in a protected personal folder. */
personal: boolean;
}
export interface DupReport {
groups: DupGroup[];
walked: number;
sameSize: number;
sampleHits: number;
confirmedGroups: number;
confirmedFiles: number;
wasted: number;
}
export interface DupsResult {
scanId: string;
report: DupReport;
elapsedMs: number;
}
// ---- system maintenance (系统维护) ---------------------------------------
export interface MaintenanceTask {
id: string;
titleEn: string;
titleZh: string;
detailEn: string;
detailZh: string;
risk: "safe" | "admin" | "slow";
budgetSecs: number;
estimate: string;
}
export interface MaintenanceResult {
task: string;
ok: boolean;
steps: string[];
failedStep: string | null;
outputTail: string;
durationMs: number;
}
// ---- optimisation tweaks (系统优化) --------------------------------------
export interface TweakState {
id: string;
titleZh: string;
titleEn: string;
detailZh: string;
detailEn: string;
risk: "safe" | "notice";
hive: string;
key: string;
value: string;
kind: "dword" | "string" | "none-means-zero";
on: string;
restartHint: boolean;
enabled: boolean;
unreadable: boolean;
recorded: boolean;
}
// ---- large files (大文件) -------------------------------------------------
export interface LargeFile {
path: string;
displayPath: string;
size: number;
modifiedMs: number;
class: "video" | "archive" | "installer" | "image" | "other";
/** A cloud-sync folder sits above this file — there may be a copy online. */
cloudHint: boolean;
/** Disk image: something (Hyper-V/WSL) may hold it open. */
maybeMounted: boolean;
}
export interface LedgerEntry {
path: string;
kind: ItemKind;
@ -324,6 +459,147 @@ export interface UndoResult {
skipped: number;
}
// ---- permissions (权限管理) ---------------------------------------------
export interface StartupItem {
id: string;
name: string;
displayName: string;
/** data-URL PNG of the binary's icon; null on platforms without extraction. */
icon: string | null;
command: string;
source: string;
sourceLabel: string;
scope: string;
enabled: boolean;
/** Attributed to a real product; false lands in the 其他软件 group. */
named: boolean;
/** The binary this row really launches (`.lnk` resolved); "" when unknown. */
target?: string;
/** False = the program is gone: a 残留项 that can be removed. */
targetExists?: boolean;
/** When it fires: `boot` | `logon` | `background` | `unknown`. */
trigger?: string;
/** Microsoft-signed or under %SystemRoot%; hideable 系统组件 bucket. */
systemItem?: boolean;
/** `microsoft` | `vendor` | `unsigned` | `invalid` | `unknown`. */
signature?: string;
/** Signer subject when the binary carries a certificate. */
signer?: string | null;
}
export interface ShellExtension {
id: string;
name: string;
handler: string;
extensionPoint: string;
scope: string;
friendlyName: string | null;
module: string | null;
/** publisher (CompanyName) of the owning dll — 电脑管家's 创建者 column. */
publisher: string | null;
/** data-URL PNG of the owning module's icon; null without extraction. */
icon: string | null;
registered: boolean;
/** Module carries real product strings (software grouping, like startup). */
named: boolean;
}
export interface PopupWindowItem {
hwnd: number;
title: string;
process: string;
exe: string | null;
/** data-URL PNG of the owning process's icon; null without extraction. */
icon: string | null;
}
export interface PopupRuleItem {
exe: string;
title: string;
matcher: string;
enabled: boolean;
closed: number;
/** data-URL PNG of the rule's exe, filled by manage_scan. */
icon?: string | null;
}
// ---- advanced startup (进阶启动项) ---------------------------------------
export interface AdvancedEntry {
id: string;
kind: "winlogon" | "appinit" | "ifeo" | "bho";
name: string;
command: string;
location: string;
scope: string;
enabled: boolean;
signature: "microsoft" | "vendor" | "unsigned" | "invalid" | "unknown";
signer: string | null;
warning: string | null;
}
export interface AdvancedScanResult {
entries: AdvancedEntry[];
/** Auto-start services, in the ordinary startup shape (shared toggle). */
extras: StartupItem[];
}
export interface ManageView {
watcherEnabled: boolean;
intervalMs: number;
rules: PopupRuleItem[];
windows: PopupWindowItem[];
startup: StartupItem[];
extensions: ShellExtension[];
startupCount: number;
startupEnabledCount: number;
}
export interface PopupClosedEvent {
process: string;
title: string;
ruleIndex: number;
}
// ---- desktop widget (桌面小工具) ------------------------------------------
export type WidgetCorner = "top-right" | "top-left" | "bottom-right" | "bottom-left";
export interface WidgetPrefs {
enabled: boolean;
panelRun: boolean;
panelCpu: boolean;
panelNetwork: boolean;
panelDisk: boolean;
panelStorage: boolean;
/** 90–100 percent window opacity. */
opacity: number;
intervalMs: number;
corner: WidgetCorner;
rememberCollapsed: boolean;
collapsed: boolean;
position: [number, number] | null;
}
export interface WidgetPatch {
enabled?: boolean;
panelRun?: boolean;
panelCpu?: boolean;
panelNetwork?: boolean;
panelDisk?: boolean;
panelStorage?: boolean;
opacity?: number;
intervalMs?: number;
corner?: WidgetCorner;
rememberCollapsed?: boolean;
collapsed?: boolean;
position?: [number, number] | null;
keepPosition?: boolean;
redock?: boolean;
}
/* ------------------------------------------------------------------ security */
export type Confidence = "confirmed" | "suspicious" | "advisory";
@ -464,84 +740,6 @@ export interface SecurityAction {
status: SecurityStatus;
}
/* ------------------------------------------------------------------- startup */
export type StartupScope = "user" | "system";
export type StartupSource =
| "launch-agent"
| "launch-daemon"
| "login-item"
| "registry-run"
| "startup-folder"
| "scheduled-task"
| "service";
export type StartupRisk =
| "missing-target"
| "in-temp-dir"
| "unsigned"
| "signature-unreadable"
| "script-interpreter"
| "recently-created"
| "hidden-entry"
| "hidden-home-directory";
export type StartupCategory = "open-at-login" | "background";
/** Something squid has to admit it could not read; the page says it in its own language. */
export interface StartupNote {
kind: "unreadable-root" | "login-items-unavailable";
subject: string;
detail: string;
}
export type StartupLock =
| "operating-system"
| "needs-authorisation"
| "not-writable"
| "managed-by-system-settings"
| "not-managed";
/** The application an entry belongs to, as both operating systems group them. */
export interface StartupOwner {
name: string;
bundlePath: string | null;
vendor: boolean;
}
export interface StartupItem {
id: string;
name: string;
source: StartupSource;
scope: StartupScope;
command: string;
program: string | null;
workingDirectory: string | null;
publisher: string | null;
signed: boolean;
systemVendor: boolean;
disabled: boolean;
modifiable: boolean;
lock: StartupLock | null;
hidden: boolean;
modifiedMs: number | null;
risks: StartupRisk[];
category: StartupCategory;
owner: StartupOwner | null;
}
export interface StartupView {
items: StartupItem[];
notes: StartupNote[];
loginCount: number;
backgroundCount: number;
vendorCount: number;
actionableCount: number;
riskyCount: number;
}
export interface StartupChange {
item: StartupItem;
message: string;
view: StartupView;
}
/* ------------------------------------------------------------------ processes */
export interface ProcessRow {
@ -577,106 +775,3 @@ export interface ProcessDetail {
parent: ProcessRow | null;
stopNote: string | null;
}
/* --------------------------------------------------------------- permissions */
export interface ManagedStartupItem {
id: string;
name: string;
displayName: string;
/** data-URL PNG of the binary's icon; null on platforms without extraction. */
icon: string | null;
command: string;
source: string;
sourceLabel: string;
scope: string;
enabled: boolean;
}
export interface ShellExtension {
id: string;
name: string;
handler: string;
extensionPoint: string;
scope: string;
friendlyName: string | null;
module: string | null;
/** publisher (CompanyName) of the owning dll — 电脑管家's 创建者 column. */
publisher: string | null;
/** data-URL PNG of the owning module's icon; null without extraction. */
icon: string | null;
registered: boolean;
}
export interface PopupWindowItem {
hwnd: number;
title: string;
process: string;
exe: string | null;
/** data-URL PNG of the owning process's icon; null without extraction. */
icon: string | null;
}
export interface PopupRuleItem {
exe: string;
title: string;
matcher: string;
enabled: boolean;
closed: number;
/** data-URL PNG of the rule's exe, filled by manage_scan. */
icon?: string | null;
}
export interface ManageView {
watcherEnabled: boolean;
intervalMs: number;
rules: PopupRuleItem[];
windows: PopupWindowItem[];
startup: ManagedStartupItem[];
extensions: ShellExtension[];
startupCount: number;
startupEnabledCount: number;
}
export interface PopupClosedEvent {
process: string;
title: string;
ruleIndex: number;
}
/* ------------------------------------------------------------ desktop widget */
export type WidgetCorner = "top-right" | "top-left" | "bottom-right" | "bottom-left";
export interface WidgetPrefs {
enabled: boolean;
panelRun: boolean;
panelCpu: boolean;
panelNetwork: boolean;
panelDisk: boolean;
panelStorage: boolean;
/** 90–100 percent window opacity. */
opacity: number;
intervalMs: number;
corner: WidgetCorner;
rememberCollapsed: boolean;
collapsed: boolean;
position: [number, number] | null;
}
export interface WidgetPatch {
enabled?: boolean;
panelRun?: boolean;
panelCpu?: boolean;
panelNetwork?: boolean;
panelDisk?: boolean;
panelStorage?: boolean;
opacity?: number;
intervalMs?: number;
corner?: WidgetCorner;
rememberCollapsed?: boolean;
collapsed?: boolean;
position?: [number, number] | null;
keepPosition?: boolean;
redock?: boolean;
}