diff --git a/Cargo.lock b/Cargo.lock index 002623e..a0d9740 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -109,6 +109,137 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix", +] + +[[package]] +name = "async-recursion" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "atk" version = "0.18.2" @@ -223,6 +354,19 @@ dependencies = [ "objc2", ] +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + [[package]] name = "brotli" version = "8.0.4" @@ -253,6 +397,16 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "bstr" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +dependencies = [ + "memchr", + "serde_core", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -464,6 +618,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "constant_time_eq" version = "0.4.2" @@ -905,6 +1068,33 @@ version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -922,6 +1112,36 @@ dependencies = [ "typeid", ] +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + [[package]] name = "fastrand" version = "2.5.0" @@ -1044,6 +1264,19 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + [[package]] name = "futures-macro" version = "0.3.34" @@ -1192,6 +1425,17 @@ dependencies = [ "version_check", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -1300,6 +1544,19 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" +[[package]] +name = "globset" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07c34a9410465b45bd9787443bc7370f37735bad04b0f0cd57ff1a3186c98988" +dependencies = [ + "aho-corasick", + "bstr", + "log", + "regex-automata", + "regex-syntax", +] + [[package]] name = "gobject-sys" version = "0.18.0" @@ -1398,6 +1655,12 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + [[package]] name = "hex" version = "0.4.3" @@ -1646,6 +1909,22 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "ignore" +version = "0.4.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b69833ed729dc5aa7d19541d96d6cf8e9137194207a04916d658e43168402f" +dependencies = [ + "crossbeam-deque", + "globset", + "log", + "memchr", + "regex-automata", + "same-file", + "walkdir", + "winapi-util", +] + [[package]] name = "indexmap" version = "1.9.3" @@ -1919,6 +2198,12 @@ dependencies = [ "libc", ] +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "litemap" version = "0.8.3" @@ -2036,7 +2321,7 @@ dependencies = [ [[package]] name = "mwm-app" -version = "5.1.0" +version = "5.6.3" dependencies = [ "anyhow", "mwm-core", @@ -2045,11 +2330,12 @@ dependencies = [ "tauri", "tauri-build", "tauri-plugin-dialog", + "tauri-plugin-single-instance", ] [[package]] name = "mwm-cli" -version = "5.1.0" +version = "5.6.3" dependencies = [ "anyhow", "clap", @@ -2061,7 +2347,7 @@ dependencies = [ [[package]] name = "mwm-core" -version = "5.1.0" +version = "5.6.3" dependencies = [ "aho-corasick", "anyhow", @@ -2070,6 +2356,8 @@ dependencies = [ "flate2", "getrandom 0.3.4", "goblin", + "ignore", + "libc", "md-5", "regex", "serde", @@ -2375,6 +2663,16 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + [[package]] name = "pango" version = "0.18.3" @@ -2400,6 +2698,12 @@ dependencies = [ "system-deps", ] +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + [[package]] name = "parking_lot" version = "0.12.5" @@ -2488,6 +2792,17 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -2539,6 +2854,20 @@ dependencies = [ "miniz_oxide 0.8.9", ] +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi", + "pin-project-lite", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "portable-atomic" version = "1.15.0" @@ -2819,6 +3148,20 @@ dependencies = [ "windows-sys 0.60.2", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rustc-hash" version = "2.1.3" @@ -2834,6 +3177,54 @@ dependencies = [ "semver", ] +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -3142,6 +3533,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + [[package]] name = "simd-adler32" version = "0.3.10" @@ -3260,6 +3661,12 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "swift-rs" version = "1.0.8" @@ -3578,6 +3985,22 @@ dependencies = [ "url", ] +[[package]] +name = "tauri-plugin-single-instance" +version = "2.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db817fe9295e19b7d8357e900af31edb93703dd9fb6de524b007b47b6afc63b0" +dependencies = [ + "serde", + "serde_json", + "tauri", + "thiserror 2.0.20", + "tokio", + "tracing", + "windows-sys 0.60.2", + "zbus", +] + [[package]] name = "tauri-runtime" version = "2.11.3" @@ -3678,6 +4101,19 @@ dependencies = [ "toml 1.1.6+spec-1.1.0", ] +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + [[package]] name = "tendril" version = "0.5.1" @@ -3984,9 +4420,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ "pin-project-lite", + "tracing-attributes", "tracing-core", ] +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "tracing-core" version = "0.1.36" @@ -4054,6 +4502,17 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + [[package]] name = "unic-char-property" version = "0.9.0" @@ -4107,6 +4566,12 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "ureq" version = "2.12.1" @@ -4116,9 +4581,12 @@ dependencies = [ "base64 0.22.1", "log", "once_cell", + "rustls", + "rustls-pki-types", "serde", "serde_json", "url", + "webpki-roots 0.26.11", ] [[package]] @@ -4376,6 +4844,24 @@ dependencies = [ "system-deps", ] +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.10", +] + +[[package]] +name = "webpki-roots" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "webview2-com" version = "0.38.2" @@ -4701,6 +5187,15 @@ dependencies = [ "windows-targets 0.42.2", ] +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-sys" version = "0.59.0" @@ -5075,6 +5570,76 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow 1.0.4", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 3.0.6", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +dependencies = [ + "serde", + "winnow 1.0.4", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473" +dependencies = [ + "serde", +] + [[package]] name = "zerofrom" version = "0.1.8" @@ -5096,6 +5661,12 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + [[package]] name = "zerotrie" version = "0.2.5" @@ -5140,3 +5711,44 @@ name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow 1.0.4", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 3.0.6", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.6", + "winnow 1.0.4", +] diff --git a/app/ui/app.css b/app/ui/app.css index 58a16ee..ce57d17 100644 --- a/app/ui/app.css +++ b/app/ui/app.css @@ -323,3 +323,93 @@ select.search { min-width: 0; } .cc-product-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(190px,1fr)); gap:9px; margin-top:14px; } .cc-product { display:flex; flex-direction:column; align-items:flex-start; gap:4px; padding:12px; background:var(--side); border:1px solid var(--line); border-radius:9px; } .cc-product .pill { margin-top:4px; } + +/* ---------- live device topology ---------- */ +.device-hero { display:flex; justify-content:space-between; align-items:center; gap:20px; margin-bottom:14px; } +.device-hero h2 { margin:4px 0 5px; font-size:25px; } +.device-hero p { margin:0; color:var(--muted); } +.device-hero .row { flex-wrap:wrap; justify-content:flex-end; } +.device-metrics { margin-bottom:14px; } +.device-metrics .card { min-height:104px; } +.device-topology { padding:22px; } +.device-network-top { width:min(560px,100%); margin:0 auto; } +.device-network-top .device-card { width:100%; } +.device-connector { height:23px; width:2px; margin:auto; background:linear-gradient(180deg,var(--accent-2),var(--accent)); opacity:.8; } +.device-lan { width:max-content; max-width:100%; margin:auto; padding:7px 15px; border:1px solid #346e5e; border-radius:999px; color:var(--accent); background:#11251f; font-weight:700; } +.device-branch { width:min(900px,80%); height:20px; margin:auto; border-top:1px solid #346e5e; } +.device-domain-grid { display:grid; grid-template-columns:minmax(210px,.8fr) minmax(300px,1.25fr) minmax(300px,1.25fr); gap:15px; align-items:start; margin-top:-20px; } +.device-section-head { display:flex; justify-content:space-between; align-items:start; gap:10px; margin:0 0 10px; } +.device-section-head h3 { margin:0 0 2px; font-size:15px; } +.device-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); gap:10px; } +.device-card { min-width:0; min-height:126px; padding:13px 14px; display:flex; flex-direction:column; gap:8px; } +.device-card-head { display:flex; align-items:center; gap:8px; min-width:0; } +.device-card-head strong { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; flex:1; } +.device-card-head .pill { flex:none; } +.device-glyph { display:inline-flex; width:25px; height:25px; align-items:center; justify-content:center; color:var(--accent-2); flex:none; } +.device-glyph svg { width:21px; height:21px; stroke:currentColor; fill:none; stroke-width:1.8; } +.device-address { overflow-wrap:anywhere; } +.device-detail { min-height:18px; } +.device-actions { margin-top:auto; flex-wrap:wrap; } +.device-guests { margin-top:14px; } +.device-guests h3 { margin:0; } +.device-guest-list { display:flex; flex-wrap:wrap; gap:7px; margin-top:13px; } +.device-foot { margin-top:12px; font-size:12px; } +@media(max-width:1200px) { + .device-domain-grid { grid-template-columns:1fr 1fr; } + .device-domain-grid > section:last-child { grid-column:1 / -1; } +} +@media(max-width:760px) { + .device-hero { align-items:stretch; flex-direction:column; } + .device-hero .row { justify-content:flex-start; } + .device-domain-grid { grid-template-columns:1fr; margin-top:0; } + .device-domain-grid > section:last-child { grid-column:auto; } + .device-branch { display:none; } + .device-topology { padding:14px; } + .device-grid { grid-template-columns:1fr; } +} + +/* dense, unified all-device snapshot */ +.device-snapshot-summary { grid-template-columns:repeat(6,minmax(118px,1fr)); gap:8px; margin-bottom:12px; } +.device-snapshot-summary .card { min-width:0; min-height:82px; padding:11px 12px; } +.device-snapshot-summary .big { font-size:20px; line-height:1.15; } +.device-snapshot-section { margin-top:12px; } +.device-snapshot-section .device-section-head { margin-bottom:7px; } +.device-snapshot-section .device-section-head h3 { font-size:14px; } +.device-snapshot-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(min(100%,310px),1fr)); gap:8px; align-items:start; } +.device-snapshot-card { min-width:0; padding:10px; display:flex; flex-direction:column; gap:6px; } +.device-snapshot-head { display:flex; align-items:center; gap:7px; min-width:0; } +.device-snapshot-head .device-glyph { width:20px; height:20px; } +.device-snapshot-head .device-glyph svg { width:18px; height:18px; } +.device-title-wrap { min-width:0; flex:1; display:flex; flex-direction:column; gap:2px; } +.device-title-wrap strong { font-size:12px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } +.device-title-wrap small { color:var(--muted); font-size:9.5px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } +.device-snapshot-head .pill { font-size:9px; padding:2px 6px; flex:none; } +.device-snapshot-address { min-height:13px; display:flex; flex-wrap:wrap; gap:6px; align-items:center; color:var(--muted); font-size:9.5px; line-height:1.25; overflow-wrap:anywhere; } +.device-snapshot-address .device-address { font-size:9.5px; } +.device-stat-grid { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:4px; } +.device-stat { min-width:0; padding:5px 6px; background:var(--side); border:1px solid var(--line); border-radius:6px; overflow:hidden; } +.device-stat-label { color:var(--muted); font-size:8px; letter-spacing:.035em; font-weight:700; white-space:nowrap; } +.device-stat-value { margin-top:2px; font-size:11px; line-height:1.2; font-weight:750; overflow-wrap:anywhere; } +.device-stat-sub { margin-top:2px; color:var(--muted); font-size:8.5px; line-height:1.2; min-height:10px; overflow-wrap:anywhere; } +.device-facts { display:flex; flex-direction:column; gap:2px; } +.device-fact { display:grid; grid-template-columns:78px minmax(0,1fr); gap:5px; color:var(--muted); font-size:9px; line-height:1.25; } +.device-fact b { color:var(--text); font-weight:650; } +.device-fact span { min-width:0; overflow-wrap:anywhere; } +.device-volumes { padding-top:3px; border-top:1px solid var(--line); color:var(--muted); font-size:9px; } +.device-volumes summary { cursor:pointer; font-weight:650; color:var(--text); } +.device-volume-list { display:flex; flex-direction:column; gap:2px; margin-top:4px; } +.device-volume-list > div { display:flex; justify-content:space-between; gap:8px; } +.device-volume-list b { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; color:var(--muted); font-weight:500; } +.device-volume-list span { flex:none; text-align:right; } +.device-snapshot-actions { margin-top:auto; padding-top:3px; } +.device-snapshot-actions .btn { font-size:10px; padding:4px 9px; min-height:24px; } +.device-snapshot-card.is-offline { border-color:#703638; } +.device-appliance-card { border-top:2px solid var(--accent-2); } +.device-inventory-card { background:color-mix(in srgb,var(--card) 75%,var(--side)); } +.device-foot { font-size:10px; } +@media(max-width:1200px) { .device-snapshot-summary { grid-template-columns:repeat(3,minmax(110px,1fr)); } } +@media(max-width:700px) { + .device-snapshot-summary { grid-template-columns:repeat(2,minmax(0,1fr)); } + .device-snapshot-grid { grid-template-columns:1fr; } + .device-fact { grid-template-columns:68px minmax(0,1fr); } +} diff --git a/app/ui/app.js b/app/ui/app.js index 0946b66..e0415ef 100644 --- a/app/ui/app.js +++ b/app/ui/app.js @@ -1,1010 +1,1012 @@ -/* MWM - Move Weight Manager. Plain JS UI over the Tauri commands in main.rs. - Outside Tauri (a normal browser) it runs against demo data in demo.js. */ -"use strict"; - -const TAURI = window.__TAURI__; -// Three hosts, one UI: the desktop app (Tauri), `mwm serve` on a server (the -// page carries ), or a plain static host = demo data. -const WEB = !TAURI && !!document.querySelector('meta[name="mwm-web"]'); -const DEMO = !TAURI && !WEB; -async function webCall(cmd, args) { - const r = await fetch(`api/${cmd}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(args || {}), credentials: "same-origin" }); - const t = await r.text(); - if (r.status === 401) { location.reload(); throw "Session expired"; } - if (!r.ok) throw t || r.statusText; - return t ? JSON.parse(t) : null; -} -/** Folder / file pickers and "save as" that work in the app and in a browser. */ -async function pickFolder(current = "") { - if (TAURI) return TAURI.dialog.open({ directory: true, multiple: false }); - return ask("Choose folder", "Folder path on the machine running MWM", current, "Use folder"); -} -async function pickFiles() { - if (TAURI) return [].concat((await TAURI.dialog.open({ multiple: true })) || []); - const p = await ask("Choose file", "Full path on the machine running MWM", "", "Use"); - return p ? [p] : []; -} -async function saveText(name, text, ext = "html") { - if (TAURI) { - const path = await TAURI.dialog.save({ defaultPath: name, filters: [{ name: ext.toUpperCase(), extensions: [ext] }] }); - if (!path) return null; - await invoke("files_write", { path, text }); - return path; - } - const a = document.createElement("a"); - a.href = URL.createObjectURL(new Blob([text], { type: ext === "html" ? "text/html" : "text/plain" })); - a.download = name; - a.click(); - setTimeout(() => URL.revokeObjectURL(a.href), 5000); - return name; -} -const localInvoke = (cmd, args = {}) => - DEMO ? window.MWM_DEMO(cmd, args) - : WEB ? webCall(cmd, args) - : cmd === "relaunch_admin" ? TAURI.core.invoke(cmd) - : TAURI.core.invoke("api", { cmd, args }); -// Which machine the UI is driving: "" = this one, otherwise a saved connection id. -let TARGET = (() => { try { return localStorage.getItem("mwm.target") || ""; } catch { return ""; } })(); -const LOCAL_ONLY = new Set(["remote_access_status", "remote_access_start", "remote_access_stop", "remote_access_new_token", "relaunch_admin", "open_default", "edit_file", "terminal", "reveal", "launch_tool", "conn_list", "conn_save", "conn_remove", "remote_call"]); -const invoke = (cmd, args = {}) => - TARGET && !LOCAL_ONLY.has(cmd) ? localInvoke("remote_call", { id: TARGET, cmd, args }) : localInvoke(cmd, args); - -// ------------------------------------------------------------ helpers ---- -const $ = (s, r = document) => r.querySelector(s); -const $$ = (s, r = document) => [...r.querySelectorAll(s)]; -const esc = (v) => String(v ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); -function bytes(n) { - if (!n) return "0 B"; - const u = ["B", "KB", "MB", "GB", "TB"]; - let i = 0; - while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; } - return `${n.toFixed(i && n < 100 ? 1 : 0)} ${u[i]}`; -} -const num = (n) => Number(n || 0).toLocaleString(); -async function copyText(t) { - try { await navigator.clipboard.writeText(t); } - catch { - const ta = document.createElement("textarea"); - ta.value = t; document.body.appendChild(ta); ta.select(); document.execCommand("copy"); ta.remove(); - } - toast("Copied to clipboard."); -} -function toast(msg, err = false) { - const t = document.createElement("div"); - t.className = "toast" + (err ? " err" : ""); - t.textContent = msg; - $("#toasts").appendChild(t); - setTimeout(() => t.remove(), err ? 7000 : 4200); -} -const loading = (msg) => `
${esc(msg)}
`; -function modal(html) { $("#modal-card").innerHTML = html; $("#modal").classList.remove("hidden"); } -function closeModal() { $("#modal").classList.add("hidden"); document.dispatchEvent(new CustomEvent("mwm-modal-closed")); } -document.addEventListener("keydown", (e) => { if (e.key === "Escape" && modalOpen()) closeModal(); }); -const modalOpen = () => !$("#modal").classList.contains("hidden"); -/** Small promise-based prompt: resolves to the entered string or null. */ -function ask(title, label, value = "", okText = "OK", note = "") { - return new Promise((resolve) => { - modal(`

${esc(title)}

${note ? `

${note}

` : ""} - -
`); - const inp = $("#ask-v"); - inp.focus(); - const dot = value.lastIndexOf("."); - inp.setSelectionRange(0, dot > 0 ? dot : value.length); - const done = (v) => { closeModal(); resolve(v); }; - $("#ask-ok").onclick = () => done(inp.value); - $("#ask-no").onclick = () => done(null); - inp.onkeydown = (e) => { if (e.key === "Enter") done(inp.value); if (e.key === "Escape") done(null); }; - }); -} -/** Promise-based choice dialog: resolves to the chosen key or null. */ -function choose(title, html, buttons) { - return new Promise((resolve) => { - modal(`

${title}

${html}
${buttons.map(([k, t, cls]) => ``).join("")}
`); - $$("[data-ch]").forEach((b) => (b.onclick = () => { closeModal(); resolve(b.dataset.ch || null); })); - const primary = $$("[data-ch]").pop(); - primary && primary.focus(); - }); -} -async function guard(fn) { - try { return await fn(); } catch (e) { toast(String(e?.message || e), true); console.error(e); } -} - -const I = { - health: '', - clean: '', - apps: '', - uninstall: '', - startup: '', - updates: '', - dupes: '', - disk: '', - perf: '', - drivers: '', - tools: '', - shred: '', - about: '', - shield: '', - folder: '', - play: '', - search: '', - report: '', - wrench: '', - net: '', - alert: '', - key: '', - server: '', - weight: '', -}; -const icon = (k) => `${I[k] || ""}`; - -// -------------------------------------------------------------- state ---- -const S = { - info: null, - scan: null, // cleaner scan items - checked: new Set(), - apps: null, - startup: null, - updates: null, - lastClean: null, -}; - -const PAGES = [ - { sec: "Overview" }, - { id: "health", label: "Health Check", icon: "health" }, - { id: "command", label: "Command Center", icon: "server" }, - { id: "fleet", label: "Machines", icon: "server" }, - { sec: "Clean" }, - { id: "offload", label: "Move Weight", icon: "weight" }, - { id: "cleaner", label: "Custom Clean", icon: "clean" }, - { id: "dupes", label: "Duplicate Finder", icon: "dupes" }, - { id: "disk", label: "Disk Analyzer", icon: "disk" }, - { sec: "Files" }, - { id: "files", label: "Commander", icon: "folder" }, - { sec: "Programs" }, - { id: "uninstaller", label: "Uninstaller", icon: "uninstall" }, - { id: "startup", label: "Startup Manager", icon: "startup" }, - { id: "updates", label: "Software Updater", icon: "updates" }, - { id: "perf", label: "Performance", icon: "perf" }, - { id: "drivers", label: "Drivers", icon: "drivers" }, - { sec: "Tech Toolkit" }, - { id: "report", label: "System Report", icon: "report" }, - { id: "keys", label: "Keys & Licenses", icon: "key" }, - { id: "vault", label: "Vault", icon: "key" }, - { id: "repair", label: "Repair", icon: "wrench" }, - { id: "security", label: "Security", icon: "shield" }, - { id: "lab", label: "Malware Lab", icon: "shield" }, - { id: "rescue", label: "Rescue Center", icon: "shield" }, - { id: "network", label: "Network", icon: "net" }, - { id: "events", label: "Crashes & Events", icon: "alert" }, - { id: "server", label: "Server / NAS", icon: "server" }, - { id: "plugins", label: "Service Plugins", icon: "server" }, - { sec: "Privacy & tools" }, - { id: "privacy", label: "Shredder & Wipe", icon: "shred" }, - { id: "tools", label: "System Tools", icon: "tools" }, - { id: "about", label: "About MWM", icon: "about" }, -]; -let current = "health"; - -// Background activity per page (long jobs keep running across tab changes). -// ACT = UI-side jobs; JOBS = engine jobs (copies, repairs) polled from Rust. -const ACT = {}; -const JOBS = { list: [], watchers: {}, timer: null }; -function setAct(page, text) { - if (text) ACT[page] = text; else delete ACT[page]; - renderNav(); - renderActivity(); -} -const pageBusy = (id) => !!ACT[id] || JOBS.list.some((j) => j.state === "running" && j.page === id); -function jobPct(j) { - if (j.total_bytes) return Math.min(100, (j.done_bytes / j.total_bytes) * 100); - if (j.total_items) return Math.min(100, (j.done_items / j.total_items) * 100); - return null; -} -function renderActivity() { - const box = document.getElementById("activity"); - if (!box) return; - const ui = Object.entries(ACT).map(([p, t]) => `
${esc(t)}
`); - const eng = JOBS.list.filter((j) => j.state === "running").map((j) => { - const pct = jobPct(j); - return `
${esc(j.title)}${pct !== null ? ` ${pct.toFixed(0)}%` : ""}${pct !== null ? `` : ""}
`; - }); - box.innerHTML = ui.concat(eng).join(""); -} -/** Track an engine job; `onDone(job)` runs when it finishes, whatever page is open. */ -function watchJob(id, onDone, quiet = false) { - JOBS.watchers[id] = { onDone, quiet }; - pollJobs(); -} -function pollJobs() { if (!JOBS.timer) JOBS.timer = setTimeout(jobTick, 60); } -async function jobTick() { - JOBS.timer = null; - try { JOBS.list = await invoke("jobs_list"); } catch { JOBS.list = []; } - for (const j of JOBS.list) { - const w = JOBS.watchers[j.id]; - if (w && j.state !== "running") { - delete JOBS.watchers[j.id]; - if (!w.quiet) toast(`${j.title} - ${j.message || j.state}`, j.state === "failed"); - try { w.onDone && w.onDone(j); } catch (e) { console.error(e); } - } - } - renderActivity(); - renderNav(); - document.dispatchEvent(new CustomEvent("mwm-jobs")); - if (JOBS.list.some((j) => j.state === "running") || Object.keys(JOBS.watchers).length) JOBS.timer = setTimeout(jobTick, 600); -} -document.addEventListener("click", (e) => { - const c = e.target.closest("[data-cancel]"); - if (c) { e.stopPropagation(); invoke("job_cancel", { id: +c.dataset.cancel }); } -}, true); - -function renderNav() { - $("#nav").innerHTML = PAGES.map((p) => - p.sec - ? `` - : `` - ).join(""); -} - -function go(id) { - if (current !== id) document.dispatchEvent(new CustomEvent("mwm-leave", { detail: current })); - current = id; - renderNav(); - const p = PAGES.find((x) => x.id === id); - $("#title").textContent = p.label; - $("#top-actions").innerHTML = ""; - $("#page").scrollTop = 0; - VIEWS[id](); -} - -document.addEventListener("click", (e) => { - const g = e.target.closest("[data-go]"); - if (g) go(g.dataset.go); - if (e.target.id === "modal" || e.target.closest("[data-close]")) closeModal(); -}); - -function adminNote(needed) { - if (!needed || S.info?.elevated) return ""; - return `
Some items need administrator rights. Restart MWM as administrator to include them.
`; -} -document.addEventListener("click", (e) => { - if (e.target.closest("[data-admin]")) { - e.preventDefault(); - guard(() => invoke("relaunch_admin")); - } -}); - -// ======================================================= HEALTH CHECK ==== -function gauge(pct, big, sub) { - const r = 62, c = 2 * Math.PI * r; - const off = c * (1 - Math.max(0, Math.min(1, pct))); - return ` - - ${esc(big)}${esc(sub)}`; -} - -const VIEWS = {}; -VIEWS.health = async function () { - const sys = S.info; - const main = sys?.disks?.find((d) => /^[A-Z]:\\?$/i.test(d.mount) && d.mount.toUpperCase().startsWith("C")) || sys?.disks?.[0]; - const junk = S.scan ? S.scan.filter((i) => i.default_on && (!i.admin || sys?.elevated)).reduce((a, i) => a + i.bytes, 0) : null; - const enabledStartup = S.startup ? S.startup.filter((i) => i.enabled && (i.kind === "run" || i.kind === "folder")).length : null; - const upd = S.updates ? S.updates.length : null; - const scanned = S.scan && S.startup; - const usedPct = main ? 1 - main.free / main.total : 0; - const cleaned = S.lastClean; - - $("#top-actions").innerHTML = ``; - $("#page").innerHTML = ` -
- ${gauge(scanned ? usedPct : 0, main ? `${Math.round(usedPct * 100)}%` : "--", main ? `${esc(main.mount)} used` : "disk")} -
-
Junk weight on this machine
-

${ - cleaned ? `You just moved ${bytes(cleaned)} of junk.` - : junk === null ? "Let's see what's weighing your PC down." - : junk > 0 ? `${bytes(junk)} of junk is ready to go.` - : "Lean and clean. Nothing to move right now." - }

-
${main ? `${bytes(main.free)} free of ${bytes(main.total)} on ${esc(main.mount)}` : ""}${ - main && main.free / main.total < 0.05 ? `  - critically low` : "" - }
-
-
1Scan
-
2Review
-
3Move the weight
-
-
-
- -
Cleans only the safe, default items.
-
-
-
-
Junk files
${junk === null ? '' : bytes(junk)}
Temp, caches, recycle bin
-
Startup apps
${enabledStartup === null ? '' : enabledStartup}
Launch when you sign in
-
Outdated apps
${upd === null ? '' : upd}
Security & bug fixes waiting
-
Installed programs
${S.apps ? S.apps.length : ''}
Review what you never use
-
-
-
Drives
${(sys?.disks || []) - .map((d) => { - const p = 1 - d.free / d.total; - return `
${esc(d.mount)}${bytes(d.free)} free / ${bytes(d.total)}
`; - }) - .join("")}
-
Biggest junk right now
${ - S.scan - ? S.scan.filter((i) => i.bytes > 0).sort((a, b) => b.bytes - a.bytes).slice(0, 6) - .map((i) => `
${esc(i.category)} - ${esc(i.name)}${i.default_on ? "" : ' (opt-in)'}${bytes(i.bytes)}
`).join("") || '
Nothing found.
' - : loading("Scanning...") - }
-
`; - - $("#hc-scan").onclick = () => { S.scan = S.startup = S.updates = S.apps = null; S.lastClean = null; healthScan(); VIEWS.health(); }; - $("#hc-clean").onclick = async () => { - const ids = S.scan.filter((i) => i.default_on && i.bytes > 0 && (!i.admin || S.info?.elevated)).map((i) => i.id); - $("#hc-clean").disabled = true; - $("#hc-clean").innerHTML = ' Cleaning...'; - const res = await guard(() => invoke("cleaner_clean", { ids })); - if (res) { - S.lastClean = res.reduce((a, r) => a + r.bytes_freed, 0); - toast(`Moved ${bytes(S.lastClean)} of junk.`); - S.scan = null; - S.info = await invoke("system_info"); - healthScan(); - } - if (current === "health") VIEWS.health(); - }; - if (!S.scan && !healthScan.running) healthScan(); -}; - -async function healthScan() { - if (healthScan.running) return; - healthScan.running = true; - const redraw = () => current === "health" && VIEWS.health(); - const jobs = [ - invoke("cleaner_scan").then((r) => { S.scan = r; redraw(); }), - invoke("startup_list").then((r) => { S.startup = r; redraw(); }), - invoke("apps_list", { store: false }).then((r) => { S.apps = S.apps || r; redraw(); }), - invoke("updates_list").then((r) => { if (!S.updates) { S.updates = r; r.forEach((u) => updSel.add(u.id)); } renderNav(); redraw(); }).catch(() => { S.updates = []; redraw(); }), - ]; - await Promise.allSettled(jobs); - healthScan.running = false; -} - -// ======================================================= CUSTOM CLEAN ==== -let cleanTab = "junk"; -VIEWS.cleaner = async function () { - $("#top-actions").innerHTML = ""; - if (!S.scan) { - $("#page").innerHTML = loading("Measuring junk across every cleaning rule..."); - S.scan = await guard(() => invoke("cleaner_scan")); - if (!S.scan) return; - if (current !== "cleaner") { S.scan.forEach((i) => i.default_on && S.checked.add(i.id)); return; } - S.scan.forEach((i) => i.default_on && S.checked.add(i.id)); - } - if (!S.checked.size && !VIEWS.cleaner.init) S.scan.forEach((i) => i.default_on && S.checked.add(i.id)); - VIEWS.cleaner.init = true; - drawCleaner(); -}; - -function drawCleaner() { - const groups = { junk: "Junk & caches", browser: "Browsers", privacy: "Privacy" }; - const items = S.scan.filter((i) => i.group === cleanTab); - const cats = [...new Set(items.map((i) => i.category))]; - const sel = S.scan.filter((i) => S.checked.has(i.id)); - const selBytes = sel.reduce((a, i) => a + (i.admin && !S.info?.elevated ? 0 : i.bytes), 0); - const needAdmin = sel.some((i) => i.admin); - - $("#page").innerHTML = ` -
${Object.entries(groups) - .map(([k, v]) => ``) - .join("")}
- ${adminNote(needAdmin)} -
-
- ${cats.map((c) => { - const its = items.filter((i) => i.category === c); - const on = its.filter((i) => S.checked.has(i.id)).length; - return `
-
${esc(c)}${on}/${its.length}▾
-
${its.map((i) => `
${i.bytes ? bytes(i.bytes) : ""}
`).join("")}
-
`; - }).join("")} -
-
-
- ${items.filter((i) => i.bytes > 0 || S.checked.has(i.id)).sort((a, b) => b.bytes - a.bytes).map((i) => ` - - - `).join("") || ``} -
ItemFilesSize
${esc(i.category)} - ${esc(i.name)} ${i.admin ? 'admin' : ""}
${esc(i.description)}${i.warning ? ` ${esc(i.warning)}` : ""}
${num(i.files)}${bytes(i.bytes)}
${icon("shield")}

Nothing to clean here

This section is already light.
-
-
- `; - - $$("[data-ctab]").forEach((b) => (b.onclick = () => { cleanTab = b.dataset.ctab; drawCleaner(); })); - $$(".cat-head").forEach((h) => (h.onclick = (e) => { if (e.target.matches("input")) return; h.parentElement.classList.toggle("open"); })); - $$("[data-rule]").forEach((cb) => (cb.onchange = () => { cb.checked ? S.checked.add(cb.dataset.rule) : S.checked.delete(cb.dataset.rule); drawCleaner(); })); - $$("[data-catcb]").forEach((cb) => (cb.onchange = () => { - items.filter((i) => i.category === cb.dataset.catcb).forEach((i) => (cb.checked ? S.checked.add(i.id) : S.checked.delete(i.id))); - drawCleaner(); - })); - $("#cl-rescan").onclick = () => { S.scan = null; VIEWS.cleaner(); }; - $("#cl-clean").onclick = () => { - const risky = sel.filter((i) => i.warning || i.id === "win.downloads"); - modal(`

Clean ${sel.length} item${sel.length === 1 ? "" : "s"}?

-

About ${bytes(selBytes)} will be permanently removed. Files that are in use are skipped automatically.

- ${risky.length ? `
Heads up: ${risky.map((i) => `${esc(i.category)} - ${esc(i.name)}`).join(", ")}. ${risky.map((i) => esc(i.warning || "Review before cleaning.")).join(" ")}
` : ""} -
`); - $("#cl-go").onclick = async () => { - $("#modal-card").innerHTML = loading("Moving junk weight..."); - const res = await guard(() => invoke("cleaner_clean", { ids: sel.map((i) => i.id) })); - if (!res) return closeModal(); - const freed = res.reduce((a, r) => a + r.bytes_freed, 0); - const skipped = res.reduce((a, r) => a + r.skipped, 0); - S.lastClean = freed; - modal(`

Done - ${bytes(freed)} moved

-

${num(res.reduce((a, r) => a + r.files_deleted, 0))} files removed${skipped ? `, ${num(skipped)} in-use or protected files skipped` : ""}.

- ${res.sort((a, b) => b.bytes_freed - a.bytes_freed).map((r) => ``).join("")}
${esc(r.name)}${bytes(r.bytes_freed)}${r.skipped ? r.skipped + " skipped" : ""}
-
`); - S.scan = null; - S.info = await invoke("system_info"); - if (current === "cleaner") VIEWS.cleaner(); - }; - }; -} - -// ======================================================== UNINSTALLER ==== -let appFilter = "", appSort = "name", appSel = null, showStore = false; -VIEWS.uninstaller = async function () { - $("#top-actions").innerHTML = ` - `; - $("#u-q").oninput = (e) => { appFilter = e.target.value; drawApps(); }; - $("#u-store").onchange = (e) => { showStore = e.target.checked; S.apps = null; VIEWS.uninstaller(); }; - if (!S.apps || (showStore && !S.apps.some((a) => a.source === "store"))) { - $("#page").innerHTML = loading("Reading installed programs..."); - S.apps = await guard(() => invoke("apps_list", { store: showStore })); - if (!S.apps || current !== "uninstaller") return; - } - drawApps(); -}; - -function drawApps() { - const q = appFilter.toLowerCase(); - let list = S.apps.filter((a) => !q || a.name.toLowerCase().includes(q) || a.publisher.toLowerCase().includes(q)); - const key = { name: (a) => a.name.toLowerCase(), size: (a) => -a.size_bytes, date: (a) => (a.install_date ? -Number(a.install_date.replace(/-/g, "")) : 0), publisher: (a) => a.publisher.toLowerCase() }[appSort]; - list = list.slice().sort((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0)); - const total = S.apps.reduce((a, x) => a + x.size_bytes, 0); - const sel = S.apps.find((a) => a.id === appSel); - $("#page").innerHTML = ` -
${num(S.apps.length)} programs - ${bytes(total)} reported by installers
-
- - ${list.map((a) => ` - - `).join("")} -
ProgramPublisherVersionInstalledSize
${esc(a.name)}
${a.source === "store" ? "Microsoft Store app" : a.source === "win32-user" ? "Installed for you only" : esc(a.source)}
${esc(a.publisher)}${esc(a.version)}${esc(a.install_date)}${a.size_bytes ? bytes(a.size_bytes) : ""}
- `; - $$("[data-app]").forEach((r) => (r.onclick = () => { appSel = r.dataset.app; drawApps(); })); - $$("[data-sort]").forEach((h) => (h.onclick = () => { appSort = h.dataset.sort; drawApps(); })); - if (sel) { - $("#u-go").onclick = () => uninstallFlow(sel); - $("#u-left").onclick = () => leftoverFlow(sel, false); - } -} - -function uninstallFlow(app) { - modal(`

Uninstall ${esc(app.name)}?

-

MWM runs the program's own uninstaller first, then hunts for leftover folders, shortcuts and registry keys.

-
Nothing is lost for good: leftovers go to the Recycle Bin and registry keys are backed up as .reg files before removal.
-
`); - $("#un-go").onclick = async () => { - $("#modal-card").innerHTML = loading(`Running the ${app.name} uninstaller - finish its window if one opens...`); - const out = await guard(() => invoke("app_uninstall", { app, quiet: false })); - if (!out) return closeModal(); - if (!out.ok) { - modal(`

The uninstaller didn't finish

${esc(out.message)}

-
`); - $("#un-force").onclick = () => leftoverFlow(app, true); - return; - } - leftoverFlow(app, true, out.message); - }; -} - -async function leftoverFlow(app, afterUninstall, msg = "") { - modal(loading(`Hunting leftovers of ${app.name}...`)); - const items = await guard(() => invoke("app_leftovers", { app })); - if (!items) return closeModal(); - const chosen = new Set(items.map((_, i) => i)); - const draw = () => { - const tot = items.filter((_, i) => chosen.has(i)).reduce((a, l) => a + l.bytes, 0); - modal(`

${afterUninstall ? `${esc(app.name)} removed` : `Leftovers of ${esc(app.name)}`}

-

${esc(msg)} ${items.length ? `Found ${items.length} leftover item${items.length === 1 ? "" : "s"}.` : "No leftovers found - clean exit."}

- ${!afterUninstall && items.length ? '
This program is still installed. Removing its folders may break it - use this only for broken installs.
' : ""} - ${items.length ? `
${items.map((l, i) => ` - - `).join("")}
${l.kind === "regkey" ? "registry" : l.kind}${esc(l.path)}${l.bytes ? bytes(l.bytes) : ""}
` : ""} -
${items.length ? `` : ""}
`); - $$("[data-lo]").forEach((cb) => (cb.onchange = () => { cb.checked ? chosen.add(+cb.dataset.lo) : chosen.delete(+cb.dataset.lo); draw(); })); - $("#lo-close").onclick = done; - if ($("#lo-go")) $("#lo-go").onclick = async () => { - $("#modal-card").innerHTML = loading("Removing leftovers..."); - const rep = await guard(() => invoke("leftovers_remove", { items: items.filter((_, i) => chosen.has(i)) })); - if (rep) { - modal(`

Leftovers removed

${rep.removed.length} removed${rep.failed.length ? `, ${rep.failed.length} could not be removed` : ""}.${rep.backup ? ` Registry backups: ${esc(rep.backup)}` : ""}

- ${rep.failed.map(([p, e]) => `
${esc(p)} - ${esc(e)}
`).join("")} -
`); - $("#lo-ok").onclick = done; - } - }; - }; - const done = () => { closeModal(); if (afterUninstall) { S.apps = null; appSel = null; if (current === "uninstaller") VIEWS.uninstaller(); } }; - draw(); -} - -// ============================================================ STARTUP ==== -let stTab = "apps"; -VIEWS.startup = async function () { - $("#top-actions").innerHTML = ``; - $("#st-re").onclick = () => { S.startup = null; VIEWS.startup(); }; - if (!S.startup) { - $("#page").innerHTML = loading("Reading startup entries, scheduled tasks and services..."); - S.startup = await guard(() => invoke("startup_list")); - if (!S.startup || current !== "startup") return; - } - drawStartup(); -}; - -function drawStartup() { - const tabs = { - apps: { label: "Startup apps", kinds: ["run", "folder", "autostart", "launchagent"] }, - tasks: { label: "Scheduled tasks", kinds: ["task"] }, - services: { label: "Services", kinds: ["service", "systemd"] }, - }; - const t = tabs[stTab]; - const items = S.startup.filter((i) => t.kinds.includes(i.kind)).sort((a, b) => a.name.localeCompare(b.name)); - const isSvc = stTab === "services"; - $("#page").innerHTML = ` -
${Object.entries(tabs).map(([k, v]) => ``).join("")}
- ${adminNote(items.some((i) => i.admin))} - ${stTab === "apps" ? '

Turning an app off works exactly like Task Manager - nothing is deleted and you can turn it back on any time.

' : ""} - ${isSvc ? '

Third-party services only - Windows\' own services are hidden so you can\'t break the OS by accident.

' : ""} -
- - ${items.map((i) => ` - - - `).join("") || ''} -
Name${isSvc ? "Start mode / state" : "Command"}${isSvc ? "Start mode" : "Starts"}
${esc(i.name)}
${esc(i.kind === "task" ? i.location : i.scope === "machine" ? "All users" : "You")}${i.admin ? ' admin' : ""}
${esc(isSvc ? i.detail : i.command)}${isSvc && i.kind === "service" - ? `` - : ``}
Nothing here.
`; - $$("[data-st]").forEach((b) => (b.onclick = () => { stTab = b.dataset.st; drawStartup(); })); - $$("[data-toggle]").forEach((b) => (b.onclick = async () => { - const item = S.startup.find((i) => i.id === b.dataset.toggle); - b.disabled = true; - const r = await guard(() => invoke("startup_set", { id: item.id, enabled: !item.enabled })); - if (r?.ok) { item.enabled = !item.enabled; toast(`${item.name} ${item.enabled ? "will start" : "won't start"} automatically.`); } - else if (r) toast(r.message, true); - drawStartup(); - })); - $$("[data-svc]").forEach((s) => (s.onchange = async () => { - const r = await guard(() => invoke("service_mode", { name: s.dataset.svc, mode: s.value })); - if (r?.ok) { const it = S.startup.find((i) => i.location === s.dataset.svc); it.detail = `${s.value} - ${it.detail.split(" - ")[1] || ""}`; toast(`Service set to ${s.value}.`); } - else if (r) { toast(r.message, true); drawStartup(); } - })); -} - -// ============================================================ UPDATES ==== -// Update state lives outside the page so a run keeps going - and stays -// visible - while you use other tabs. -const updSel = new Set(); -const updState = {}; // id -> { s: "queued" | "run" | "ok" | "fail", msg } -let updRunning = false; -const updPending = () => (S.updates || []).filter((u) => updState[u.id]?.s !== "ok"); - -VIEWS.updates = async function () { - $("#top-actions").innerHTML = ``; - $("#up-re").onclick = () => { S.updates = null; Object.keys(updState).forEach((k) => delete updState[k]); VIEWS.updates(); }; - if (!S.updates) { - $("#page").innerHTML = loading("Asking winget which apps have updates..."); - const list = await guard(() => invoke("updates_list")); - if (!list) return; - S.updates = list; - S.updates.forEach((u) => updSel.add(u.id)); - renderNav(); - if (current !== "updates") return; - } - drawUpdates(); -}; - -function updCell(id) { - const st = updState[id]; - if (!st) return ""; - if (st.s === "queued") return 'Queued'; - if (st.s === "run") return ' updating'; - if (st.s === "ok") return 'Updated'; - return `Failed`; -} - -function drawUpdates() { - if (current !== "updates") return; - const u = S.updates; - const done = u.filter((x) => updState[x.id]?.s === "ok").length; - $("#page").innerHTML = u.length - ? `

Updates come straight from each publisher through Windows Package Manager (winget) - free, no Pro tier. ${updRunning ? "Updates keep running if you switch tabs." : ""}

-
- - ${u.map((x) => ` - `).join("")}
SoftwareCurrentNew version
${esc(x.name)}
${esc(x.id)}
${esc(x.current)}${esc(x.available)}${updCell(x.id)}
- ` - : `
${icon("shield")}

Everything is up to date

No outdated apps found.
`; - if (!u.length) return; - $("#up-all").onchange = (e) => { u.forEach((x) => (e.target.checked && updState[x.id]?.s !== "ok" ? updSel.add(x.id) : updSel.delete(x.id))); drawUpdates(); }; - $$("[data-up]").forEach((cb) => (cb.onchange = () => { cb.checked ? updSel.add(cb.dataset.up) : updSel.delete(cb.dataset.up); drawUpdates(); })); - $("#up-go").onclick = runUpdates; -} - -async function runUpdates() { - if (updRunning) return; - const ids = [...updSel]; - updRunning = true; - ids.forEach((id) => (updState[id] = { s: "queued" })); - let ok = 0, n = 0; - for (const id of ids) { - n++; - updState[id] = { s: "run" }; - setAct("updates", `Updating ${n}/${ids.length}`); - drawUpdates(); - const r = await invoke("update_apply", { id }).catch((e) => ({ ok: false, message: String(e) })); - updState[id] = r.ok ? { s: "ok" } : { s: "fail", msg: r.message }; - if (r.ok) { ok++; updSel.delete(id); } - drawUpdates(); - } - updRunning = false; - setAct("updates", null); - drawUpdates(); - toast(`${ok} of ${ids.length} app${ids.length === 1 ? "" : "s"} updated.`, ok < ids.length); -} - -// ========================================================= DUPLICATES ==== -let dupRoot = "", dupMin = 1, dupGroups = null; -const dupDel = new Set(); -VIEWS.dupes = function () { - const home = S.info?.platform === "windows" ? "C:\\Users" : "/home"; - dupRoot = dupRoot || home; - drawDupes(); -}; -function drawDupes() { - const wasted = dupGroups ? dupGroups.reduce((a, g) => a + g.wasted, 0) : 0; - const delBytes = dupGroups ? dupGroups.reduce((a, g) => a + g.files.filter((f) => dupDel.has(f.path)).length * g.size, 0) : 0; - $("#page").innerHTML = ` -
- - - - -
-
${dupGroups === null ? `
${icon("dupes")}

Find identical files

Files are compared by content (BLAKE3 hash), not by name. Windows, AppData and program folders are skipped.
` : - dupGroups.length ? `
${num(dupGroups.length)} groups - ${bytes(wasted)} reclaimable
-
${dupGroups.slice(0, 400).map((g) => `${g.files.map((f) => ``).join("")}`).join("")}
${bytes(g.size)} x ${g.files.length} copies
${esc(f.path)}${f.modified ? new Date(f.modified * 1000).toLocaleDateString() : ""}
- ` : `
${icon("shield")}

No duplicates

Nothing identical in that folder.
`}
`; - $("#d-root").oninput = (e) => (dupRoot = e.target.value); - $("#d-min").onchange = (e) => (dupMin = +e.target.value); - $("#d-pick").onclick = async () => { - const p = await pickFolder(dupRoot); - if (p) { dupRoot = p; drawDupes(); } - }; - $("#d-go").onclick = async () => { - $("#d-res").innerHTML = loading("Comparing file contents - big folders take a while..."); - setAct("dupes", "Finding duplicates"); - dupGroups = await guard(() => invoke("dupes_find", { roots: [dupRoot], minSize: dupMin * 1048576 })); - setAct("dupes", null); - dupDel.clear(); - if (current === "dupes") drawDupes(); - }; - if (!dupGroups?.length) return; - $("#d-auto").onclick = () => { dupDel.clear(); dupGroups.forEach((g) => g.files.slice(1).forEach((f) => dupDel.add(f.path))); drawDupes(); }; - $$("[data-dup]").forEach((cb) => (cb.onchange = () => { - const g = dupGroups.find((x) => x.files.some((f) => f.path === cb.dataset.dup)); - if (cb.checked && g.files.every((f) => f.path === cb.dataset.dup || dupDel.has(f.path))) { cb.checked = false; return toast("Keep at least one copy of every file.", true); } - cb.checked ? dupDel.add(cb.dataset.dup) : dupDel.delete(cb.dataset.dup); - drawDupes(); - })); - $("#d-del").onclick = async () => { - const r = await guard(() => invoke("dupes_remove", { paths: [...dupDel] })); - if (!r) return; - toast(`${r.removed.length} duplicates moved to the Recycle Bin${r.failed.length ? `, ${r.failed.length} failed` : ""}.`, !!r.failed.length); - const gone = new Set(r.removed); - dupGroups = dupGroups.map((g) => ({ ...g, files: g.files.filter((f) => !gone.has(f.path)) })).filter((g) => g.files.length > 1).map((g) => ({ ...g, wasted: g.size * (g.files.length - 1) })); - dupDel.clear(); - drawDupes(); - }; -} - -// ============================================================== DISK ==== -let diskRoot = "", diskRep = null; -VIEWS.disk = function () { - diskRoot = diskRoot || (S.info?.disks?.[0]?.mount ?? "C:\\"); - drawDisk(); -}; -function drawDisk() { - const r = diskRep; - const max = r?.children?.[0]?.bytes || 1; - $("#page").innerHTML = ` -
- ${(S.info?.disks || []).map((d) => ``).join("")} - - - -
-
${!r ? `
${icon("disk")}

Where did the space go?

Pick a drive or folder to see what is heavy.
` : ` -
-
Largest folders in ${esc(r.root)}
${bytes(r.bytes)} - ${num(r.files)} files
- ${r.children.slice(0, 22).map((c) => `
${c.is_dir ? "📁 " : ""}${esc(c.name)}${bytes(c.bytes)}
`).join("")}
-
Largest files
- ${r.largest_files.slice(0, 22).map((f) => `
${esc(f.path)}${bytes(f.bytes)}
`).join("")} -
By file type
- ${r.by_type.map(([t, b]) => `.${esc(t)} ${bytes(b)}`).join("")}
-
`}
`; - $$("[data-drive]").forEach((b) => (b.onclick = () => { diskRoot = b.dataset.drive; drawDisk(); })); - $("#dk-root").oninput = (e) => (diskRoot = e.target.value); - $("#dk-pick").onclick = async () => { const p = await pickFolder(diskRoot); if (p) { diskRoot = p; drawDisk(); } }; - $("#dk-go").onclick = async () => { - $("#page").lastElementChild.innerHTML = loading(`Measuring ${diskRoot} - a whole drive can take a minute...`); - setAct("disk", `Analyzing ${diskRoot}`); - diskRep = await guard(() => invoke("disk_analyze", { root: diskRoot })); - setAct("disk", null); - if (current === "disk") drawDisk(); - }; - $$("[data-drill]").forEach((d) => d.dataset.drill && (d.onclick = () => { diskRoot = d.dataset.drill; $("#dk-go").click(); })); - $$("[data-reveal]").forEach((d) => (d.onclick = () => invoke("reveal", { path: d.dataset.reveal }))); -} - -// ======================================================= PERFORMANCE ==== -VIEWS.perf = async function () { - $("#top-actions").innerHTML = ``; - $("#pf-re").onclick = () => VIEWS.perf(); - $("#page").innerHTML = loading("Sampling running programs..."); - const ps = await guard(() => invoke("procs_list")); - if (!ps || current !== "perf") return; - const mem = S.info?.memory_total || 1; - $("#page").innerHTML = `

Heaviest programs right now. To stop one from coming back after a restart, turn it off in Startup Manager.

-
- ${ps.slice(0, 120).map((p, i) => ` - - `).join("")}
ProgramImpactMemoryCPU
${esc(p.name)} ${p.pids.length > 1 ? `x${p.pids.length}` : ""}
${esc(p.exe)}
${esc(p.impact)}${bytes(p.memory)} ${((p.memory / mem) * 100).toFixed(1)}%${p.cpu.toFixed(1)}%
`; - $$("[data-kill]").forEach((b) => (b.onclick = () => { - const p = ps[+b.dataset.kill]; - modal(`

End ${esc(p.name)}?

Unsaved work in this program will be lost.

`); - $("#k-go").onclick = async () => { const n = await guard(() => invoke("procs_kill", { pids: p.pids })); closeModal(); toast(`Ended ${n} process${n === 1 ? "" : "es"}.`); if (current === "perf") VIEWS.perf(); }; - })); -}; - -// =========================================================== DRIVERS ==== -VIEWS.drivers = async function () { - $("#top-actions").innerHTML = ``; - $("#page").innerHTML = loading("Reading installed drivers..."); - const d = await guard(() => invoke("drivers_list")); - if (!d || current !== "drivers") return; - const old = d.filter((x) => x.age_years >= 3).length; - $("#page").innerHTML = `
MWM never downloads drivers from third-party mirrors - that's how "driver updater" tools spread malware and broken drivers. Get driver updates from Windows Update → Optional updates or your PC/GPU maker. ${old ? `${old} drivers are over 3 years old.` : ""}
-
- ${d.map((x) => ``).join("")}
DeviceProviderVersionDate
${esc(x.device)}
${esc(x.class)}
${esc(x.provider)}${esc(x.version)}${esc(x.date)}
`; -}; -document.addEventListener("click", (e) => { - const t = e.target.closest("[data-tool]"); - if (t) guard(() => invoke("launch_tool", { tool: t.dataset.tool })); -}); - -// ============================================================ PRIVACY ==== -VIEWS.privacy = function () { - const drives = S.info?.disks || []; - $("#page").innerHTML = ` -
-
${icon("shred").replace("Unrecoverable Delete
-
Overwrites files with random data, then zeros, scrambles the name and deletes them. Recovery tools get nothing back.
-
-
-
-
-
On SSDs, wear-levelling can keep old copies of blocks - combine with the free-space wipe below.
-
${icon("shield").replace("Evidence Remover - wipe free space
-
Files you already deleted normally still sit in "free" space until overwritten. This overwrites all free space on a drive (Windows uses the built-in cipher /w).
-
-
-
Takes a long time on big drives and briefly fills the disk. Your existing files are not touched.
-
`; - let picked = []; - const show = () => { $("#sh-list").innerHTML = picked.map(esc).join("
"); $("#sh-go").disabled = !picked.length; }; - $("#sh-files").onclick = async () => { const p = await pickFiles(); if (p.length) { picked = p; show(); } }; - $("#sh-dir").onclick = async () => { const p = await pickFolder(); if (p) { picked = [p]; show(); } }; - $("#sh-go").onclick = () => { - modal(`

Destroy ${picked.length} item${picked.length > 1 ? "s" : ""} forever?

This cannot be undone - shredded files skip the Recycle Bin and cannot be recovered by anyone, including you.

-
${picked.map(esc).join("
")}
-
`); - $("#sh-yes").onclick = async () => { - $("#modal-card").innerHTML = loading("Shredding..."); - const r = await guard(() => invoke("shred_paths", { paths: picked, passes: +$("#sh-pass").value })); - closeModal(); - if (r) toast(`Shredded ${r.files} files (${bytes(r.bytes)})${r.failed.length ? `, ${r.failed.length} failed` : ""}.`, !!r.failed.length); - picked = []; show(); - }; - }; - $("#wf-go").onclick = () => { - const d = $("#wf-drive").value; - modal(`

Wipe free space on ${esc(d)}?

This can take an hour or more on a large drive. You can keep using the PC, but it will be slower.

-
`); - $("#wf-yes").onclick = async () => { - closeModal(); - toast(`Wiping free space on ${d}... MWM will tell you when it's finished.`); - setAct("privacy", `Wiping free space on ${d}`); - const r = await guard(() => invoke("wipe_free", { dir: d })); - setAct("privacy", null); - if (r) toast(r); - }; - }; -}; - -// ============================================================== TOOLS ==== -VIEWS.tools = function () { - const tools = [ - ["cleanmgr", "Disk Cleanup", "Windows' own cleaner, incl. old Windows installs"], - ["storage", "Storage Sense", "Automatic cleanup settings"], - ["restore", "System Restore", "Roll back system changes"], - ["devmgmt", "Device Manager", "Hardware and drivers"], - ["services", "Services", "Every Windows service"], - ["taskschd", "Task Scheduler", "All scheduled tasks"], - ["eventvwr", "Event Viewer", "System logs and errors"], - ["diskmgmt", "Disk Management", "Partitions and volumes"], - ["msinfo", "System Information", "Full hardware report"], - ["resmon", "Resource Monitor", "Live CPU, disk, network"], - ["taskmgr", "Task Manager", "Processes and startup"], - ["sysprops", "System Properties", "Performance, env vars"], - ["defrag", "Optimize Drives", "TRIM / defragment"], - ["apps", "Apps & features", "Windows' uninstall list"], - ["winupdate", "Windows Update", "OS updates"], - ["regedit", "Registry Editor", "For experts"], - ]; - $("#page").innerHTML = `${DEMO || TARGET || S.info?.platform !== "windows" ? "" : `
File Explorer takeover

Open folders in MWM Commander

-
Double-clicking any folder or drive in Windows opens MWM Commander instead of File Explorer. Commander does everything Explorer does - copy/cut/paste, rename, search, pack - plus dual panes, multi-rename, folder sizes, malware analysis and Recycle-safe delete. Per-user registry only, fully reversible.
-
`} -

Shortcuts to the tools already built into Windows.

-
${tools.map(([k, n, d]) => `
${icon("tools")}${esc(n)}${esc(d)}
`).join("")}
`; - if (!DEMO && !TARGET && S.info?.platform === "windows") drawTakeover(); -}; - -// ------------------------------------------- Explorer takeover panel ---- -async function drawTakeover() { - const t = $("#tk-toggle"); - if (!t) return; - const st = await localInvoke("explorer_takeover_status").catch(() => null); - if (!st || !st.available) { const m = $("#tk-msg"); if (m) m.textContent = "Not available here."; return; } - t.className = "toggle" + (st.enabled ? " on" : ""); - const msg = $("#tk-msg"); - msg.innerHTML = st.enabled - ? 'Active Folders and drives now open in MWM Commander. Turn this off to hand them back to File Explorer instantly.' - : 'Off - Windows File Explorer opens folders as usual.'; - t.onclick = async () => { - const want = !st.enabled; - if (want && !(await choose("Take over folder opening?", '

After this, double-clicking a folder or drive opens MWM Commander instead of File Explorer. Explorer itself keeps working (Win+E, desktop, taskbar). You can undo this any time from Tools.

', [["go", "Take over", "primary"]]))) return; - const r = await guard(() => localInvoke("explorer_takeover_set", { enabled: want })); - if (r) { toast(r.enabled ? "MWM Commander now opens folders." : "File Explorer restored."); drawTakeover(); } - }; -} - -// ============================================================== ABOUT ==== -VIEWS.about = function () { - const i = S.info || {}; - $("#page").innerHTML = `
-
MWM
Move Weight Manager - v${esc(i.version || "")}
-
Free and open source. No ads, no "Pro" upsell, no telemetry. One lightweight app for cleaning, uninstalling, repair and recovery.
-
License: GPL-3.0-or-later - Made by the MoveWeight Foundation.
-
${i.elevated ? 'Running as administrator' : ''}
-
This machine
- - - - - - -
Computer${esc(i.hostname)}
System${esc(i.os)}
Processor${esc(i.cpu)} (${esc(i.cores)} threads)
Memory${bytes(i.memory_used)} used of ${bytes(i.memory_total)}
Up since${i.uptime_secs ? new Date(Date.now() - i.uptime_secs * 1000).toLocaleString() : ""}
- ${WEB || TARGET ? "" : `
Remote access
Loading...
`} -
Updates

App version

You are running v${esc(i.version || "?")}. Check GitHub for the newest MWM release.
-
How MWM keeps you safe
-
    -
  • Scans never delete anything. Cleaning only touches caches and temp files, and skips anything in use.
  • -
  • Uninstall leftovers go to the Recycle Bin; registry keys are exported to .reg backups before removal.
  • -
  • Startup items are switched off the same way Task Manager does it - never deleted.
  • -
  • Updates come from winget (the publisher's own installers); drivers only from Windows Update or the maker.
  • -
`; - drawRemoteAccess(); - drawUpdateCheck(); -}; - -// ------------------------------------------------- app update check ---- -function drawUpdateCheck() { - const btn = $("#upd-check"); - const out = $("#upd-check-result"); - if (!btn || !out) return; - btn.onclick = async () => { - btn.disabled = true; - out.innerHTML = '
Asking GitHub for the latest release...
'; - try { - const r = await invoke("app_latest_release"); - const newer = r.update_available; - const notes = (r.notes || "").trim().split("\n").slice(0, 6).map(esc).join("
"); - out.innerHTML = `
-
${newer ? `New version available: ${esc(r.tag)}
Published ${r.published ? new Date(r.published).toLocaleString() : ""}
` : `Up to date ${esc(r.tag)} is the latest release (${r.published ? new Date(r.published).toLocaleDateString() : ""}).`}
- ${newer ? `
Open release ↗${DEMO || TARGET ? "" : ``}
` : ""}
- ${notes ? `
Release notes
${notes}
` : ""} -
${TARGET ? "This checks the machine you are managing." : (S.info || {}).platform === "windows" ? "Windows: the MWM Portable Updater task also installs new releases automatically (checksum-verified) when the app is closed." : "Servers: mwm-self-update installs new releases automatically from the verified GitHub release."}
`; - const open = $("#upd-open"); - if (open && newer) open.onclick = () => localInvoke("open_default", { path: r.url }); - if (newer) toast(`MWM ${r.tag} is available.`); - } catch (e) { - out.innerHTML = `
Couldn't reach GitHub: ${esc(String(e))}
`; - } - btn.disabled = false; - }; -} - -// ------------------------------------------------------ remote access ---- -async function drawRemoteAccess() { - const box = $("#ra-card"); - if (!box) return; - const st = await localInvoke("remote_access_status").catch((e) => ({ error: String(e) })); - if (st.error) { box.innerHTML = `
Remote access
${esc(st.error)}
`; return; } - box.innerHTML = `
Remote access

Manage this ${S.info?.platform === "windows" ? "PC" : "machine"} from another MWM or a browser

-
Runs MWM's secure web server here. Anyone with the access token can manage this machine - share it only with yourself.
-
-
- -
- ${st.running ? `
On another MWM: Machines → Add machine, paste this link:
${esc(st.link.replace(/token=.*/, "token=" + "•".repeat(12)))} -
-
Plain HTTP - fine on your home network; use a VPN (Tailscale, WireGuard) to reach it from outside.${S.info?.platform === "windows" ? " Windows may ask to allow MWM through the firewall - allow it on Private networks." : ""}
` : ""}`; - $("#ra-toggle").onclick = async () => { - const r = st.running ? await guard(() => localInvoke("remote_access_stop")) : await guard(() => localInvoke("remote_access_start", { bind: $("#ra-bind").value.trim(), readOnly: $("#ra-ro").checked })); - if (r) toast(r.running ? "Remote access is on." : "Remote access is off."); - drawRemoteAccess(); - }; - if (st.running) { - $("#ra-copy").onclick = () => copyText(st.link); - $("#ra-new").onclick = async () => { - if (!(await choose("New access token?", '

Every MWM that uses the old token loses access until you give it the new link.

', [["go", "Make a new token", "primary"]]))) return; - await localInvoke("remote_access_new_token"); - toast("New token made."); - drawRemoteAccess(); - }; - } -} - -// ============================================================== boot ==== -document.addEventListener("DOMContentLoaded", async function boot() { - renderNav(); - try { - S.info = await invoke("system_info"); - } catch (e) { - // Last-used remote machine is unreachable: start on this PC instead. - if (TARGET) { TARGET = ""; try { localStorage.setItem("mwm.target", ""); } catch {} toast(`Couldn't reach the last machine - showing this PC. (${e})`, true); } - S.info = await invoke("system_info").catch(() => ({ disks: [], elevated: false })); - } - await renderSwitcher(); - $("#elev").className = "elev" + (S.info.elevated ? " admin" : ""); - $("#elev").innerHTML = `${S.info.elevated ? "Administrator" : `Standard user - elevate`}`; - $("#ver").textContent = `v${S.info.version || ""}${DEMO ? " - web demo" : ""} - ${S.info.hostname || ""}`; - if (!WEB && !DEMO && !TARGET) { - const pending = await localInvoke("pending_open_dir").catch(() => null); - if (pending) { go("files"); setTimeout(() => loadPane(CMD.panes[0], pending, false), 350); return; } - } - go(WEB ? "command" : "health"); -}); +/* MWM - Move Weight Manager. Plain JS UI over the Tauri commands in main.rs. + Outside Tauri (a normal browser) it runs against demo data in demo.js. */ +"use strict"; + +const TAURI = window.__TAURI__; +// Three hosts, one UI: the desktop app (Tauri), `mwm serve` on a server (the +// page carries ), or a plain static host = demo data. +const WEB = !TAURI && !!document.querySelector('meta[name="mwm-web"]'); +const DEMO = !TAURI && !WEB; +async function webCall(cmd, args) { + const r = await fetch(`api/${cmd}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(args || {}), credentials: "same-origin" }); + const t = await r.text(); + if (r.status === 401) { location.reload(); throw "Session expired"; } + if (!r.ok) throw t || r.statusText; + return t ? JSON.parse(t) : null; +} +/** Folder / file pickers and "save as" that work in the app and in a browser. */ +async function pickFolder(current = "") { + if (TAURI) return TAURI.dialog.open({ directory: true, multiple: false }); + return ask("Choose folder", "Folder path on the machine running MWM", current, "Use folder"); +} +async function pickFiles() { + if (TAURI) return [].concat((await TAURI.dialog.open({ multiple: true })) || []); + const p = await ask("Choose file", "Full path on the machine running MWM", "", "Use"); + return p ? [p] : []; +} +async function saveText(name, text, ext = "html") { + if (TAURI) { + const path = await TAURI.dialog.save({ defaultPath: name, filters: [{ name: ext.toUpperCase(), extensions: [ext] }] }); + if (!path) return null; + await invoke("files_write", { path, text }); + return path; + } + const a = document.createElement("a"); + a.href = URL.createObjectURL(new Blob([text], { type: ext === "html" ? "text/html" : "text/plain" })); + a.download = name; + a.click(); + setTimeout(() => URL.revokeObjectURL(a.href), 5000); + return name; +} +const localInvoke = (cmd, args = {}) => + DEMO ? window.MWM_DEMO(cmd, args) + : WEB ? webCall(cmd, args) + : cmd === "relaunch_admin" ? TAURI.core.invoke(cmd) + : TAURI.core.invoke("api", { cmd, args }); +// Which machine the UI is driving: "" = this one, otherwise a saved connection id. +let TARGET = (() => { try { return localStorage.getItem("mwm.target") || ""; } catch { return ""; } })(); +const LOCAL_ONLY = new Set(["remote_access_status", "remote_access_start", "remote_access_stop", "remote_access_new_token", "relaunch_admin", "open_default", "edit_file", "terminal", "reveal", "launch_tool", "conn_list", "conn_save", "conn_remove", "remote_call"]); +const invoke = (cmd, args = {}) => + TARGET && !LOCAL_ONLY.has(cmd) ? localInvoke("remote_call", { id: TARGET, cmd, args }) : localInvoke(cmd, args); + +// ------------------------------------------------------------ helpers ---- +const $ = (s, r = document) => r.querySelector(s); +const $$ = (s, r = document) => [...r.querySelectorAll(s)]; +const esc = (v) => String(v ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); +function bytes(n) { + if (!n) return "0 B"; + const u = ["B", "KB", "MB", "GB", "TB"]; + let i = 0; + while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; } + return `${n.toFixed(i && n < 100 ? 1 : 0)} ${u[i]}`; +} +const num = (n) => Number(n || 0).toLocaleString(); +async function copyText(t) { + try { await navigator.clipboard.writeText(t); } + catch { + const ta = document.createElement("textarea"); + ta.value = t; document.body.appendChild(ta); ta.select(); document.execCommand("copy"); ta.remove(); + } + toast("Copied to clipboard."); +} +function toast(msg, err = false) { + const t = document.createElement("div"); + t.className = "toast" + (err ? " err" : ""); + t.textContent = msg; + $("#toasts").appendChild(t); + setTimeout(() => t.remove(), err ? 7000 : 4200); +} +const loading = (msg) => `
${esc(msg)}
`; +function modal(html) { $("#modal-card").innerHTML = html; $("#modal").classList.remove("hidden"); } +function closeModal() { $("#modal").classList.add("hidden"); document.dispatchEvent(new CustomEvent("mwm-modal-closed")); } +document.addEventListener("keydown", (e) => { if (e.key === "Escape" && modalOpen()) closeModal(); }); +const modalOpen = () => !$("#modal").classList.contains("hidden"); +/** Small promise-based prompt: resolves to the entered string or null. */ +function ask(title, label, value = "", okText = "OK", note = "") { + return new Promise((resolve) => { + modal(`

${esc(title)}

${note ? `

${note}

` : ""} + +
`); + const inp = $("#ask-v"); + inp.focus(); + const dot = value.lastIndexOf("."); + inp.setSelectionRange(0, dot > 0 ? dot : value.length); + const done = (v) => { closeModal(); resolve(v); }; + $("#ask-ok").onclick = () => done(inp.value); + $("#ask-no").onclick = () => done(null); + inp.onkeydown = (e) => { if (e.key === "Enter") done(inp.value); if (e.key === "Escape") done(null); }; + }); +} +/** Promise-based choice dialog: resolves to the chosen key or null. */ +function choose(title, html, buttons) { + return new Promise((resolve) => { + modal(`

${title}

${html}
${buttons.map(([k, t, cls]) => ``).join("")}
`); + $$("[data-ch]").forEach((b) => (b.onclick = () => { closeModal(); resolve(b.dataset.ch || null); })); + const primary = $$("[data-ch]").pop(); + primary && primary.focus(); + }); +} +async function guard(fn) { + try { return await fn(); } catch (e) { toast(String(e?.message || e), true); console.error(e); } +} + +const I = { + health: '', + clean: '', + apps: '', + uninstall: '', + startup: '', + updates: '', + dupes: '', + disk: '', + perf: '', + drivers: '', + tools: '', + shred: '', + about: '', + shield: '', + folder: '', + play: '', + search: '', + report: '', + wrench: '', + net: '', + alert: '', + key: '', + server: '', + weight: '', +}; +const icon = (k) => `${I[k] || ""}`; + +// -------------------------------------------------------------- state ---- +const S = { + info: null, + scan: null, // cleaner scan items + checked: new Set(), + apps: null, + startup: null, + updates: null, + lastClean: null, +}; + +const PAGES = [ + { sec: "Overview" }, + { id: "topology", label: "Devices", icon: "net" }, + { id: "health", label: "Health Check", icon: "health" }, + { id: "command", label: "Command Center", icon: "server" }, + { id: "appliances", label: "Network & Media", icon: "net" }, + { id: "fleet", label: "Machines", icon: "server" }, + { sec: "Clean" }, + { id: "offload", label: "Move Weight", icon: "weight" }, + { id: "cleaner", label: "Custom Clean", icon: "clean" }, + { id: "dupes", label: "Duplicate Finder", icon: "dupes" }, + { id: "disk", label: "Disk Analyzer", icon: "disk" }, + { sec: "Files" }, + { id: "files", label: "Commander", icon: "folder" }, + { sec: "Programs" }, + { id: "uninstaller", label: "Uninstaller", icon: "uninstall" }, + { id: "startup", label: "Startup Manager", icon: "startup" }, + { id: "updates", label: "Software Updater", icon: "updates" }, + { id: "perf", label: "Performance", icon: "perf" }, + { id: "drivers", label: "Drivers", icon: "drivers" }, + { sec: "Tech Toolkit" }, + { id: "report", label: "System Report", icon: "report" }, + { id: "keys", label: "Keys & Licenses", icon: "key" }, + { id: "vault", label: "Vault", icon: "key" }, + { id: "repair", label: "Repair", icon: "wrench" }, + { id: "security", label: "Security", icon: "shield" }, + { id: "lab", label: "Malware Lab", icon: "shield" }, + { id: "rescue", label: "Rescue Center", icon: "shield" }, + { id: "network", label: "Network", icon: "net" }, + { id: "events", label: "Crashes & Events", icon: "alert" }, + { id: "server", label: "Server / NAS", icon: "server" }, + { id: "plugins", label: "Service Plugins", icon: "server" }, + { sec: "Privacy & tools" }, + { id: "privacy", label: "Shredder & Wipe", icon: "shred" }, + { id: "tools", label: "System Tools", icon: "tools" }, + { id: "about", label: "About MWM", icon: "about" }, +]; +let current = DEMO && location.pathname.startsWith("/demo") ? "appliances" : "topology"; + +// Background activity per page (long jobs keep running across tab changes). +// ACT = UI-side jobs; JOBS = engine jobs (copies, repairs) polled from Rust. +const ACT = {}; +const JOBS = { list: [], watchers: {}, timer: null }; +function setAct(page, text) { + if (text) ACT[page] = text; else delete ACT[page]; + renderNav(); + renderActivity(); +} +const pageBusy = (id) => !!ACT[id] || JOBS.list.some((j) => j.state === "running" && j.page === id); +function jobPct(j) { + if (j.total_bytes) return Math.min(100, (j.done_bytes / j.total_bytes) * 100); + if (j.total_items) return Math.min(100, (j.done_items / j.total_items) * 100); + return null; +} +function renderActivity() { + const box = document.getElementById("activity"); + if (!box) return; + const ui = Object.entries(ACT).map(([p, t]) => `
${esc(t)}
`); + const eng = JOBS.list.filter((j) => j.state === "running").map((j) => { + const pct = jobPct(j); + return `
${esc(j.title)}${pct !== null ? ` ${pct.toFixed(0)}%` : ""}${pct !== null ? `` : ""}
`; + }); + box.innerHTML = ui.concat(eng).join(""); +} +/** Track an engine job; `onDone(job)` runs when it finishes, whatever page is open. */ +function watchJob(id, onDone, quiet = false) { + JOBS.watchers[id] = { onDone, quiet }; + pollJobs(); +} +function pollJobs() { if (!JOBS.timer) JOBS.timer = setTimeout(jobTick, 60); } +async function jobTick() { + JOBS.timer = null; + try { JOBS.list = await invoke("jobs_list"); } catch { JOBS.list = []; } + for (const j of JOBS.list) { + const w = JOBS.watchers[j.id]; + if (w && j.state !== "running") { + delete JOBS.watchers[j.id]; + if (!w.quiet) toast(`${j.title} - ${j.message || j.state}`, j.state === "failed"); + try { w.onDone && w.onDone(j); } catch (e) { console.error(e); } + } + } + renderActivity(); + renderNav(); + document.dispatchEvent(new CustomEvent("mwm-jobs")); + if (JOBS.list.some((j) => j.state === "running") || Object.keys(JOBS.watchers).length) JOBS.timer = setTimeout(jobTick, 600); +} +document.addEventListener("click", (e) => { + const c = e.target.closest("[data-cancel]"); + if (c) { e.stopPropagation(); invoke("job_cancel", { id: +c.dataset.cancel }); } +}, true); + +function renderNav() { + $("#nav").innerHTML = PAGES.map((p) => + p.sec + ? `` + : `` + ).join(""); +} + +function go(id) { + if (current !== id) document.dispatchEvent(new CustomEvent("mwm-leave", { detail: current })); + current = id; + renderNav(); + const p = PAGES.find((x) => x.id === id); + $("#title").textContent = p.label; + $("#top-actions").innerHTML = ""; + $("#page").scrollTop = 0; + VIEWS[id](); +} + +document.addEventListener("click", (e) => { + const g = e.target.closest("[data-go]"); + if (g) go(g.dataset.go); + if (e.target.id === "modal" || e.target.closest("[data-close]")) closeModal(); +}); + +function adminNote(needed) { + if (!needed || S.info?.elevated) return ""; + return `
Some items need administrator rights. Restart MWM as administrator to include them.
`; +} +document.addEventListener("click", (e) => { + if (e.target.closest("[data-admin]")) { + e.preventDefault(); + guard(() => invoke("relaunch_admin")); + } +}); + +// ======================================================= HEALTH CHECK ==== +function gauge(pct, big, sub) { + const r = 62, c = 2 * Math.PI * r; + const off = c * (1 - Math.max(0, Math.min(1, pct))); + return ` + + ${esc(big)}${esc(sub)}`; +} + +const VIEWS = {}; +VIEWS.health = async function () { + const sys = S.info; + const main = sys?.disks?.find((d) => /^[A-Z]:\\?$/i.test(d.mount) && d.mount.toUpperCase().startsWith("C")) || sys?.disks?.[0]; + const junk = S.scan ? S.scan.filter((i) => i.default_on && (!i.admin || sys?.elevated)).reduce((a, i) => a + i.bytes, 0) : null; + const enabledStartup = S.startup ? S.startup.filter((i) => i.enabled && (i.kind === "run" || i.kind === "folder")).length : null; + const upd = S.updates ? S.updates.length : null; + const scanned = S.scan && S.startup; + const usedPct = main ? 1 - main.free / main.total : 0; + const cleaned = S.lastClean; + + $("#top-actions").innerHTML = ``; + $("#page").innerHTML = ` +
+ ${gauge(scanned ? usedPct : 0, main ? `${Math.round(usedPct * 100)}%` : "--", main ? `${esc(main.mount)} used` : "disk")} +
+
Junk weight on this machine
+

${ + cleaned ? `You just moved ${bytes(cleaned)} of junk.` + : junk === null ? "Let's see what's weighing your PC down." + : junk > 0 ? `${bytes(junk)} of junk is ready to go.` + : "Lean and clean. Nothing to move right now." + }

+
${main ? `${bytes(main.free)} free of ${bytes(main.total)} on ${esc(main.mount)}` : ""}${ + main && main.free / main.total < 0.05 ? `  - critically low` : "" + }
+
+
1Scan
+
2Review
+
3Move the weight
+
+
+
+ +
Cleans only the safe, default items.
+
+
+
+
Junk files
${junk === null ? '' : bytes(junk)}
Temp, caches, recycle bin
+
Startup apps
${enabledStartup === null ? '' : enabledStartup}
Launch when you sign in
+
Outdated apps
${upd === null ? '' : upd}
Security & bug fixes waiting
+
Installed programs
${S.apps ? S.apps.length : ''}
Review what you never use
+
+
+
Drives
${(sys?.disks || []) + .map((d) => { + const p = 1 - d.free / d.total; + return `
${esc(d.mount)}${bytes(d.free)} free / ${bytes(d.total)}
`; + }) + .join("")}
+
Biggest junk right now
${ + S.scan + ? S.scan.filter((i) => i.bytes > 0).sort((a, b) => b.bytes - a.bytes).slice(0, 6) + .map((i) => `
${esc(i.category)} - ${esc(i.name)}${i.default_on ? "" : ' (opt-in)'}${bytes(i.bytes)}
`).join("") || '
Nothing found.
' + : loading("Scanning...") + }
+
`; + + $("#hc-scan").onclick = () => { S.scan = S.startup = S.updates = S.apps = null; S.lastClean = null; healthScan(); VIEWS.health(); }; + $("#hc-clean").onclick = async () => { + const ids = S.scan.filter((i) => i.default_on && i.bytes > 0 && (!i.admin || S.info?.elevated)).map((i) => i.id); + $("#hc-clean").disabled = true; + $("#hc-clean").innerHTML = ' Cleaning...'; + const res = await guard(() => invoke("cleaner_clean", { ids })); + if (res) { + S.lastClean = res.reduce((a, r) => a + r.bytes_freed, 0); + toast(`Moved ${bytes(S.lastClean)} of junk.`); + S.scan = null; + S.info = await invoke("system_info"); + healthScan(); + } + if (current === "health") VIEWS.health(); + }; + if (!S.scan && !healthScan.running) healthScan(); +}; + +async function healthScan() { + if (healthScan.running) return; + healthScan.running = true; + const redraw = () => current === "health" && VIEWS.health(); + const jobs = [ + invoke("cleaner_scan").then((r) => { S.scan = r; redraw(); }), + invoke("startup_list").then((r) => { S.startup = r; redraw(); }), + invoke("apps_list", { store: false }).then((r) => { S.apps = S.apps || r; redraw(); }), + invoke("updates_list").then((r) => { if (!S.updates) { S.updates = r; r.forEach((u) => updSel.add(u.id)); } renderNav(); redraw(); }).catch(() => { S.updates = []; redraw(); }), + ]; + await Promise.allSettled(jobs); + healthScan.running = false; +} + +// ======================================================= CUSTOM CLEAN ==== +let cleanTab = "junk"; +VIEWS.cleaner = async function () { + $("#top-actions").innerHTML = ""; + if (!S.scan) { + $("#page").innerHTML = loading("Measuring junk across every cleaning rule..."); + S.scan = await guard(() => invoke("cleaner_scan")); + if (!S.scan) return; + if (current !== "cleaner") { S.scan.forEach((i) => i.default_on && S.checked.add(i.id)); return; } + S.scan.forEach((i) => i.default_on && S.checked.add(i.id)); + } + if (!S.checked.size && !VIEWS.cleaner.init) S.scan.forEach((i) => i.default_on && S.checked.add(i.id)); + VIEWS.cleaner.init = true; + drawCleaner(); +}; + +function drawCleaner() { + const groups = { junk: "Junk & caches", browser: "Browsers", privacy: "Privacy" }; + const items = S.scan.filter((i) => i.group === cleanTab); + const cats = [...new Set(items.map((i) => i.category))]; + const sel = S.scan.filter((i) => S.checked.has(i.id)); + const selBytes = sel.reduce((a, i) => a + (i.admin && !S.info?.elevated ? 0 : i.bytes), 0); + const needAdmin = sel.some((i) => i.admin); + + $("#page").innerHTML = ` +
${Object.entries(groups) + .map(([k, v]) => ``) + .join("")}
+ ${adminNote(needAdmin)} +
+
+ ${cats.map((c) => { + const its = items.filter((i) => i.category === c); + const on = its.filter((i) => S.checked.has(i.id)).length; + return `
+
${esc(c)}${on}/${its.length}▾
+
${its.map((i) => `
${i.bytes ? bytes(i.bytes) : ""}
`).join("")}
+
`; + }).join("")} +
+
+
+ ${items.filter((i) => i.bytes > 0 || S.checked.has(i.id)).sort((a, b) => b.bytes - a.bytes).map((i) => ` + + + `).join("") || ``} +
ItemFilesSize
${esc(i.category)} - ${esc(i.name)} ${i.admin ? 'admin' : ""}
${esc(i.description)}${i.warning ? ` ${esc(i.warning)}` : ""}
${num(i.files)}${bytes(i.bytes)}
${icon("shield")}

Nothing to clean here

This section is already light.
+
+
+ `; + + $$("[data-ctab]").forEach((b) => (b.onclick = () => { cleanTab = b.dataset.ctab; drawCleaner(); })); + $$(".cat-head").forEach((h) => (h.onclick = (e) => { if (e.target.matches("input")) return; h.parentElement.classList.toggle("open"); })); + $$("[data-rule]").forEach((cb) => (cb.onchange = () => { cb.checked ? S.checked.add(cb.dataset.rule) : S.checked.delete(cb.dataset.rule); drawCleaner(); })); + $$("[data-catcb]").forEach((cb) => (cb.onchange = () => { + items.filter((i) => i.category === cb.dataset.catcb).forEach((i) => (cb.checked ? S.checked.add(i.id) : S.checked.delete(i.id))); + drawCleaner(); + })); + $("#cl-rescan").onclick = () => { S.scan = null; VIEWS.cleaner(); }; + $("#cl-clean").onclick = () => { + const risky = sel.filter((i) => i.warning || i.id === "win.downloads"); + modal(`

Clean ${sel.length} item${sel.length === 1 ? "" : "s"}?

+

About ${bytes(selBytes)} will be permanently removed. Files that are in use are skipped automatically.

+ ${risky.length ? `
Heads up: ${risky.map((i) => `${esc(i.category)} - ${esc(i.name)}`).join(", ")}. ${risky.map((i) => esc(i.warning || "Review before cleaning.")).join(" ")}
` : ""} +
`); + $("#cl-go").onclick = async () => { + $("#modal-card").innerHTML = loading("Moving junk weight..."); + const res = await guard(() => invoke("cleaner_clean", { ids: sel.map((i) => i.id) })); + if (!res) return closeModal(); + const freed = res.reduce((a, r) => a + r.bytes_freed, 0); + const skipped = res.reduce((a, r) => a + r.skipped, 0); + S.lastClean = freed; + modal(`

Done - ${bytes(freed)} moved

+

${num(res.reduce((a, r) => a + r.files_deleted, 0))} files removed${skipped ? `, ${num(skipped)} in-use or protected files skipped` : ""}.

+ ${res.sort((a, b) => b.bytes_freed - a.bytes_freed).map((r) => ``).join("")}
${esc(r.name)}${bytes(r.bytes_freed)}${r.skipped ? r.skipped + " skipped" : ""}
+
`); + S.scan = null; + S.info = await invoke("system_info"); + if (current === "cleaner") VIEWS.cleaner(); + }; + }; +} + +// ======================================================== UNINSTALLER ==== +let appFilter = "", appSort = "name", appSel = null, showStore = false; +VIEWS.uninstaller = async function () { + $("#top-actions").innerHTML = ` + `; + $("#u-q").oninput = (e) => { appFilter = e.target.value; drawApps(); }; + $("#u-store").onchange = (e) => { showStore = e.target.checked; S.apps = null; VIEWS.uninstaller(); }; + if (!S.apps || (showStore && !S.apps.some((a) => a.source === "store"))) { + $("#page").innerHTML = loading("Reading installed programs..."); + S.apps = await guard(() => invoke("apps_list", { store: showStore })); + if (!S.apps || current !== "uninstaller") return; + } + drawApps(); +}; + +function drawApps() { + const q = appFilter.toLowerCase(); + let list = S.apps.filter((a) => !q || a.name.toLowerCase().includes(q) || a.publisher.toLowerCase().includes(q)); + const key = { name: (a) => a.name.toLowerCase(), size: (a) => -a.size_bytes, date: (a) => (a.install_date ? -Number(a.install_date.replace(/-/g, "")) : 0), publisher: (a) => a.publisher.toLowerCase() }[appSort]; + list = list.slice().sort((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0)); + const total = S.apps.reduce((a, x) => a + x.size_bytes, 0); + const sel = S.apps.find((a) => a.id === appSel); + $("#page").innerHTML = ` +
${num(S.apps.length)} programs - ${bytes(total)} reported by installers
+
+ + ${list.map((a) => ` + + `).join("")} +
ProgramPublisherVersionInstalledSize
${esc(a.name)}
${a.source === "store" ? "Microsoft Store app" : a.source === "win32-user" ? "Installed for you only" : esc(a.source)}
${esc(a.publisher)}${esc(a.version)}${esc(a.install_date)}${a.size_bytes ? bytes(a.size_bytes) : ""}
+ `; + $$("[data-app]").forEach((r) => (r.onclick = () => { appSel = r.dataset.app; drawApps(); })); + $$("[data-sort]").forEach((h) => (h.onclick = () => { appSort = h.dataset.sort; drawApps(); })); + if (sel) { + $("#u-go").onclick = () => uninstallFlow(sel); + $("#u-left").onclick = () => leftoverFlow(sel, false); + } +} + +function uninstallFlow(app) { + modal(`

Uninstall ${esc(app.name)}?

+

MWM runs the program's own uninstaller first, then hunts for leftover folders, shortcuts and registry keys.

+
Nothing is lost for good: leftovers go to the Recycle Bin and registry keys are backed up as .reg files before removal.
+
`); + $("#un-go").onclick = async () => { + $("#modal-card").innerHTML = loading(`Running the ${app.name} uninstaller - finish its window if one opens...`); + const out = await guard(() => invoke("app_uninstall", { app, quiet: false })); + if (!out) return closeModal(); + if (!out.ok) { + modal(`

The uninstaller didn't finish

${esc(out.message)}

+
`); + $("#un-force").onclick = () => leftoverFlow(app, true); + return; + } + leftoverFlow(app, true, out.message); + }; +} + +async function leftoverFlow(app, afterUninstall, msg = "") { + modal(loading(`Hunting leftovers of ${app.name}...`)); + const items = await guard(() => invoke("app_leftovers", { app })); + if (!items) return closeModal(); + const chosen = new Set(items.map((_, i) => i)); + const draw = () => { + const tot = items.filter((_, i) => chosen.has(i)).reduce((a, l) => a + l.bytes, 0); + modal(`

${afterUninstall ? `${esc(app.name)} removed` : `Leftovers of ${esc(app.name)}`}

+

${esc(msg)} ${items.length ? `Found ${items.length} leftover item${items.length === 1 ? "" : "s"}.` : "No leftovers found - clean exit."}

+ ${!afterUninstall && items.length ? '
This program is still installed. Removing its folders may break it - use this only for broken installs.
' : ""} + ${items.length ? `
${items.map((l, i) => ` + + `).join("")}
${l.kind === "regkey" ? "registry" : l.kind}${esc(l.path)}${l.bytes ? bytes(l.bytes) : ""}
` : ""} +
${items.length ? `` : ""}
`); + $$("[data-lo]").forEach((cb) => (cb.onchange = () => { cb.checked ? chosen.add(+cb.dataset.lo) : chosen.delete(+cb.dataset.lo); draw(); })); + $("#lo-close").onclick = done; + if ($("#lo-go")) $("#lo-go").onclick = async () => { + $("#modal-card").innerHTML = loading("Removing leftovers..."); + const rep = await guard(() => invoke("leftovers_remove", { items: items.filter((_, i) => chosen.has(i)) })); + if (rep) { + modal(`

Leftovers removed

${rep.removed.length} removed${rep.failed.length ? `, ${rep.failed.length} could not be removed` : ""}.${rep.backup ? ` Registry backups: ${esc(rep.backup)}` : ""}

+ ${rep.failed.map(([p, e]) => `
${esc(p)} - ${esc(e)}
`).join("")} +
`); + $("#lo-ok").onclick = done; + } + }; + }; + const done = () => { closeModal(); if (afterUninstall) { S.apps = null; appSel = null; if (current === "uninstaller") VIEWS.uninstaller(); } }; + draw(); +} + +// ============================================================ STARTUP ==== +let stTab = "apps"; +VIEWS.startup = async function () { + $("#top-actions").innerHTML = ``; + $("#st-re").onclick = () => { S.startup = null; VIEWS.startup(); }; + if (!S.startup) { + $("#page").innerHTML = loading("Reading startup entries, scheduled tasks and services..."); + S.startup = await guard(() => invoke("startup_list")); + if (!S.startup || current !== "startup") return; + } + drawStartup(); +}; + +function drawStartup() { + const tabs = { + apps: { label: "Startup apps", kinds: ["run", "folder", "autostart", "launchagent"] }, + tasks: { label: "Scheduled tasks", kinds: ["task"] }, + services: { label: "Services", kinds: ["service", "systemd"] }, + }; + const t = tabs[stTab]; + const items = S.startup.filter((i) => t.kinds.includes(i.kind)).sort((a, b) => a.name.localeCompare(b.name)); + const isSvc = stTab === "services"; + $("#page").innerHTML = ` +
${Object.entries(tabs).map(([k, v]) => ``).join("")}
+ ${adminNote(items.some((i) => i.admin))} + ${stTab === "apps" ? '

Turning an app off works exactly like Task Manager - nothing is deleted and you can turn it back on any time.

' : ""} + ${isSvc ? '

Third-party services only - Windows\' own services are hidden so you can\'t break the OS by accident.

' : ""} +
+ + ${items.map((i) => ` + + + `).join("") || ''} +
Name${isSvc ? "Start mode / state" : "Command"}${isSvc ? "Start mode" : "Starts"}
${esc(i.name)}
${esc(i.kind === "task" ? i.location : i.scope === "machine" ? "All users" : "You")}${i.admin ? ' admin' : ""}
${esc(isSvc ? i.detail : i.command)}${isSvc && i.kind === "service" + ? `` + : ``}
Nothing here.
`; + $$("[data-st]").forEach((b) => (b.onclick = () => { stTab = b.dataset.st; drawStartup(); })); + $$("[data-toggle]").forEach((b) => (b.onclick = async () => { + const item = S.startup.find((i) => i.id === b.dataset.toggle); + b.disabled = true; + const r = await guard(() => invoke("startup_set", { id: item.id, enabled: !item.enabled })); + if (r?.ok) { item.enabled = !item.enabled; toast(`${item.name} ${item.enabled ? "will start" : "won't start"} automatically.`); } + else if (r) toast(r.message, true); + drawStartup(); + })); + $$("[data-svc]").forEach((s) => (s.onchange = async () => { + const r = await guard(() => invoke("service_mode", { name: s.dataset.svc, mode: s.value })); + if (r?.ok) { const it = S.startup.find((i) => i.location === s.dataset.svc); it.detail = `${s.value} - ${it.detail.split(" - ")[1] || ""}`; toast(`Service set to ${s.value}.`); } + else if (r) { toast(r.message, true); drawStartup(); } + })); +} + +// ============================================================ UPDATES ==== +// Update state lives outside the page so a run keeps going - and stays +// visible - while you use other tabs. +const updSel = new Set(); +const updState = {}; // id -> { s: "queued" | "run" | "ok" | "fail", msg } +let updRunning = false; +const updPending = () => (S.updates || []).filter((u) => updState[u.id]?.s !== "ok"); + +VIEWS.updates = async function () { + $("#top-actions").innerHTML = ``; + $("#up-re").onclick = () => { S.updates = null; Object.keys(updState).forEach((k) => delete updState[k]); VIEWS.updates(); }; + if (!S.updates) { + $("#page").innerHTML = loading("Asking winget which apps have updates..."); + const list = await guard(() => invoke("updates_list")); + if (!list) return; + S.updates = list; + S.updates.forEach((u) => updSel.add(u.id)); + renderNav(); + if (current !== "updates") return; + } + drawUpdates(); +}; + +function updCell(id) { + const st = updState[id]; + if (!st) return ""; + if (st.s === "queued") return 'Queued'; + if (st.s === "run") return ' updating'; + if (st.s === "ok") return 'Updated'; + return `Failed`; +} + +function drawUpdates() { + if (current !== "updates") return; + const u = S.updates; + const done = u.filter((x) => updState[x.id]?.s === "ok").length; + $("#page").innerHTML = u.length + ? `

Updates come straight from each publisher through Windows Package Manager (winget) - free, no Pro tier. ${updRunning ? "Updates keep running if you switch tabs." : ""}

+
+ + ${u.map((x) => ` + `).join("")}
SoftwareCurrentNew version
${esc(x.name)}
${esc(x.id)}
${esc(x.current)}${esc(x.available)}${updCell(x.id)}
+ ` + : `
${icon("shield")}

Everything is up to date

No outdated apps found.
`; + if (!u.length) return; + $("#up-all").onchange = (e) => { u.forEach((x) => (e.target.checked && updState[x.id]?.s !== "ok" ? updSel.add(x.id) : updSel.delete(x.id))); drawUpdates(); }; + $$("[data-up]").forEach((cb) => (cb.onchange = () => { cb.checked ? updSel.add(cb.dataset.up) : updSel.delete(cb.dataset.up); drawUpdates(); })); + $("#up-go").onclick = runUpdates; +} + +async function runUpdates() { + if (updRunning) return; + const ids = [...updSel]; + updRunning = true; + ids.forEach((id) => (updState[id] = { s: "queued" })); + let ok = 0, n = 0; + for (const id of ids) { + n++; + updState[id] = { s: "run" }; + setAct("updates", `Updating ${n}/${ids.length}`); + drawUpdates(); + const r = await invoke("update_apply", { id }).catch((e) => ({ ok: false, message: String(e) })); + updState[id] = r.ok ? { s: "ok" } : { s: "fail", msg: r.message }; + if (r.ok) { ok++; updSel.delete(id); } + drawUpdates(); + } + updRunning = false; + setAct("updates", null); + drawUpdates(); + toast(`${ok} of ${ids.length} app${ids.length === 1 ? "" : "s"} updated.`, ok < ids.length); +} + +// ========================================================= DUPLICATES ==== +let dupRoot = "", dupMin = 1, dupGroups = null; +const dupDel = new Set(); +VIEWS.dupes = function () { + const home = S.info?.platform === "windows" ? "C:\\Users" : "/home"; + dupRoot = dupRoot || home; + drawDupes(); +}; +function drawDupes() { + const wasted = dupGroups ? dupGroups.reduce((a, g) => a + g.wasted, 0) : 0; + const delBytes = dupGroups ? dupGroups.reduce((a, g) => a + g.files.filter((f) => dupDel.has(f.path)).length * g.size, 0) : 0; + $("#page").innerHTML = ` +
+ + + + +
+
${dupGroups === null ? `
${icon("dupes")}

Find identical files

Files are compared by content (BLAKE3 hash), not by name. Windows, AppData and program folders are skipped.
` : + dupGroups.length ? `
${num(dupGroups.length)} groups - ${bytes(wasted)} reclaimable
+
${dupGroups.slice(0, 400).map((g) => `${g.files.map((f) => ``).join("")}`).join("")}
${bytes(g.size)} x ${g.files.length} copies
${esc(f.path)}${f.modified ? new Date(f.modified * 1000).toLocaleDateString() : ""}
+ ` : `
${icon("shield")}

No duplicates

Nothing identical in that folder.
`}
`; + $("#d-root").oninput = (e) => (dupRoot = e.target.value); + $("#d-min").onchange = (e) => (dupMin = +e.target.value); + $("#d-pick").onclick = async () => { + const p = await pickFolder(dupRoot); + if (p) { dupRoot = p; drawDupes(); } + }; + $("#d-go").onclick = async () => { + $("#d-res").innerHTML = loading("Comparing file contents - big folders take a while..."); + setAct("dupes", "Finding duplicates"); + dupGroups = await guard(() => invoke("dupes_find", { roots: [dupRoot], minSize: dupMin * 1048576 })); + setAct("dupes", null); + dupDel.clear(); + if (current === "dupes") drawDupes(); + }; + if (!dupGroups?.length) return; + $("#d-auto").onclick = () => { dupDel.clear(); dupGroups.forEach((g) => g.files.slice(1).forEach((f) => dupDel.add(f.path))); drawDupes(); }; + $$("[data-dup]").forEach((cb) => (cb.onchange = () => { + const g = dupGroups.find((x) => x.files.some((f) => f.path === cb.dataset.dup)); + if (cb.checked && g.files.every((f) => f.path === cb.dataset.dup || dupDel.has(f.path))) { cb.checked = false; return toast("Keep at least one copy of every file.", true); } + cb.checked ? dupDel.add(cb.dataset.dup) : dupDel.delete(cb.dataset.dup); + drawDupes(); + })); + $("#d-del").onclick = async () => { + const r = await guard(() => invoke("dupes_remove", { paths: [...dupDel] })); + if (!r) return; + toast(`${r.removed.length} duplicates moved to the Recycle Bin${r.failed.length ? `, ${r.failed.length} failed` : ""}.`, !!r.failed.length); + const gone = new Set(r.removed); + dupGroups = dupGroups.map((g) => ({ ...g, files: g.files.filter((f) => !gone.has(f.path)) })).filter((g) => g.files.length > 1).map((g) => ({ ...g, wasted: g.size * (g.files.length - 1) })); + dupDel.clear(); + drawDupes(); + }; +} + +// ============================================================== DISK ==== +let diskRoot = "", diskRep = null; +VIEWS.disk = function () { + diskRoot = diskRoot || (S.info?.disks?.[0]?.mount ?? "C:\\"); + drawDisk(); +}; +function drawDisk() { + const r = diskRep; + const max = r?.children?.[0]?.bytes || 1; + $("#page").innerHTML = ` +
+ ${(S.info?.disks || []).map((d) => ``).join("")} + + + +
+
${!r ? `
${icon("disk")}

Where did the space go?

Pick a drive or folder to see what is heavy.
` : ` +
+
Largest folders in ${esc(r.root)}
${bytes(r.bytes)} - ${num(r.files)} files
+ ${r.children.slice(0, 22).map((c) => `
${c.is_dir ? "📁 " : ""}${esc(c.name)}${bytes(c.bytes)}
`).join("")}
+
Largest files
+ ${r.largest_files.slice(0, 22).map((f) => `
${esc(f.path)}${bytes(f.bytes)}
`).join("")} +
By file type
+ ${r.by_type.map(([t, b]) => `.${esc(t)} ${bytes(b)}`).join("")}
+
`}
`; + $$("[data-drive]").forEach((b) => (b.onclick = () => { diskRoot = b.dataset.drive; drawDisk(); })); + $("#dk-root").oninput = (e) => (diskRoot = e.target.value); + $("#dk-pick").onclick = async () => { const p = await pickFolder(diskRoot); if (p) { diskRoot = p; drawDisk(); } }; + $("#dk-go").onclick = async () => { + $("#page").lastElementChild.innerHTML = loading(`Measuring ${diskRoot} - a whole drive can take a minute...`); + setAct("disk", `Analyzing ${diskRoot}`); + diskRep = await guard(() => invoke("disk_analyze", { root: diskRoot })); + setAct("disk", null); + if (current === "disk") drawDisk(); + }; + $$("[data-drill]").forEach((d) => d.dataset.drill && (d.onclick = () => { diskRoot = d.dataset.drill; $("#dk-go").click(); })); + $$("[data-reveal]").forEach((d) => (d.onclick = () => invoke("reveal", { path: d.dataset.reveal }))); +} + +// ======================================================= PERFORMANCE ==== +VIEWS.perf = async function () { + $("#top-actions").innerHTML = ``; + $("#pf-re").onclick = () => VIEWS.perf(); + $("#page").innerHTML = loading("Sampling running programs..."); + const ps = await guard(() => invoke("procs_list")); + if (!ps || current !== "perf") return; + const mem = S.info?.memory_total || 1; + $("#page").innerHTML = `

Heaviest programs right now. To stop one from coming back after a restart, turn it off in Startup Manager.

+
+ ${ps.slice(0, 120).map((p, i) => ` + + `).join("")}
ProgramImpactMemoryCPU
${esc(p.name)} ${p.pids.length > 1 ? `x${p.pids.length}` : ""}
${esc(p.exe)}
${esc(p.impact)}${bytes(p.memory)} ${((p.memory / mem) * 100).toFixed(1)}%${p.cpu.toFixed(1)}%
`; + $$("[data-kill]").forEach((b) => (b.onclick = () => { + const p = ps[+b.dataset.kill]; + modal(`

End ${esc(p.name)}?

Unsaved work in this program will be lost.

`); + $("#k-go").onclick = async () => { const n = await guard(() => invoke("procs_kill", { pids: p.pids })); closeModal(); toast(`Ended ${n} process${n === 1 ? "" : "es"}.`); if (current === "perf") VIEWS.perf(); }; + })); +}; + +// =========================================================== DRIVERS ==== +VIEWS.drivers = async function () { + $("#top-actions").innerHTML = ``; + $("#page").innerHTML = loading("Reading installed drivers..."); + const d = await guard(() => invoke("drivers_list")); + if (!d || current !== "drivers") return; + const old = d.filter((x) => x.age_years >= 3).length; + $("#page").innerHTML = `
MWM never downloads drivers from third-party mirrors - that's how "driver updater" tools spread malware and broken drivers. Get driver updates from Windows Update → Optional updates or your PC/GPU maker. ${old ? `${old} drivers are over 3 years old.` : ""}
+
+ ${d.map((x) => ``).join("")}
DeviceProviderVersionDate
${esc(x.device)}
${esc(x.class)}
${esc(x.provider)}${esc(x.version)}${esc(x.date)}
`; +}; +document.addEventListener("click", (e) => { + const t = e.target.closest("[data-tool]"); + if (t) guard(() => invoke("launch_tool", { tool: t.dataset.tool })); +}); + +// ============================================================ PRIVACY ==== +VIEWS.privacy = function () { + const drives = S.info?.disks || []; + $("#page").innerHTML = ` +
+
${icon("shred").replace("Unrecoverable Delete
+
Overwrites files with random data, then zeros, scrambles the name and deletes them. Recovery tools get nothing back.
+
+
+
+
+
On SSDs, wear-levelling can keep old copies of blocks - combine with the free-space wipe below.
+
${icon("shield").replace("Evidence Remover - wipe free space
+
Files you already deleted normally still sit in "free" space until overwritten. This overwrites all free space on a drive (Windows uses the built-in cipher /w).
+
+
+
Takes a long time on big drives and briefly fills the disk. Your existing files are not touched.
+
`; + let picked = []; + const show = () => { $("#sh-list").innerHTML = picked.map(esc).join("
"); $("#sh-go").disabled = !picked.length; }; + $("#sh-files").onclick = async () => { const p = await pickFiles(); if (p.length) { picked = p; show(); } }; + $("#sh-dir").onclick = async () => { const p = await pickFolder(); if (p) { picked = [p]; show(); } }; + $("#sh-go").onclick = () => { + modal(`

Destroy ${picked.length} item${picked.length > 1 ? "s" : ""} forever?

This cannot be undone - shredded files skip the Recycle Bin and cannot be recovered by anyone, including you.

+
${picked.map(esc).join("
")}
+
`); + $("#sh-yes").onclick = async () => { + $("#modal-card").innerHTML = loading("Shredding..."); + const r = await guard(() => invoke("shred_paths", { paths: picked, passes: +$("#sh-pass").value })); + closeModal(); + if (r) toast(`Shredded ${r.files} files (${bytes(r.bytes)})${r.failed.length ? `, ${r.failed.length} failed` : ""}.`, !!r.failed.length); + picked = []; show(); + }; + }; + $("#wf-go").onclick = () => { + const d = $("#wf-drive").value; + modal(`

Wipe free space on ${esc(d)}?

This can take an hour or more on a large drive. You can keep using the PC, but it will be slower.

+
`); + $("#wf-yes").onclick = async () => { + closeModal(); + toast(`Wiping free space on ${d}... MWM will tell you when it's finished.`); + setAct("privacy", `Wiping free space on ${d}`); + const r = await guard(() => invoke("wipe_free", { dir: d })); + setAct("privacy", null); + if (r) toast(r); + }; + }; +}; + +// ============================================================== TOOLS ==== +VIEWS.tools = function () { + const tools = [ + ["cleanmgr", "Disk Cleanup", "Windows' own cleaner, incl. old Windows installs"], + ["storage", "Storage Sense", "Automatic cleanup settings"], + ["restore", "System Restore", "Roll back system changes"], + ["devmgmt", "Device Manager", "Hardware and drivers"], + ["services", "Services", "Every Windows service"], + ["taskschd", "Task Scheduler", "All scheduled tasks"], + ["eventvwr", "Event Viewer", "System logs and errors"], + ["diskmgmt", "Disk Management", "Partitions and volumes"], + ["msinfo", "System Information", "Full hardware report"], + ["resmon", "Resource Monitor", "Live CPU, disk, network"], + ["taskmgr", "Task Manager", "Processes and startup"], + ["sysprops", "System Properties", "Performance, env vars"], + ["defrag", "Optimize Drives", "TRIM / defragment"], + ["apps", "Apps & features", "Windows' uninstall list"], + ["winupdate", "Windows Update", "OS updates"], + ["regedit", "Registry Editor", "For experts"], + ]; + $("#page").innerHTML = `${DEMO || TARGET || S.info?.platform !== "windows" ? "" : `
File Explorer takeover

Open folders in MWM Commander

+
Double-clicking any folder or drive in Windows opens MWM Commander instead of File Explorer. Commander does everything Explorer does - copy/cut/paste, rename, search, pack - plus dual panes, multi-rename, folder sizes, malware analysis and Recycle-safe delete. Per-user registry only, fully reversible.
+
`} +

Shortcuts to the tools already built into Windows.

+
${tools.map(([k, n, d]) => `
${icon("tools")}${esc(n)}${esc(d)}
`).join("")}
`; + if (!DEMO && !TARGET && S.info?.platform === "windows") drawTakeover(); +}; + +// ------------------------------------------- Explorer takeover panel ---- +async function drawTakeover() { + const t = $("#tk-toggle"); + if (!t) return; + const st = await localInvoke("explorer_takeover_status").catch(() => null); + if (!st || !st.available) { const m = $("#tk-msg"); if (m) m.textContent = "Not available here."; return; } + t.className = "toggle" + (st.enabled ? " on" : ""); + const msg = $("#tk-msg"); + msg.innerHTML = st.enabled + ? 'Active Folders and drives now open in MWM Commander. Turn this off to hand them back to File Explorer instantly.' + : 'Off - Windows File Explorer opens folders as usual.'; + t.onclick = async () => { + const want = !st.enabled; + if (want && !(await choose("Take over folder opening?", '

After this, double-clicking a folder or drive opens MWM Commander instead of File Explorer. Explorer itself keeps working (Win+E, desktop, taskbar). You can undo this any time from Tools.

', [["go", "Take over", "primary"]]))) return; + const r = await guard(() => localInvoke("explorer_takeover_set", { enabled: want })); + if (r) { toast(r.enabled ? "MWM Commander now opens folders." : "File Explorer restored."); drawTakeover(); } + }; +} + +// ============================================================== ABOUT ==== +VIEWS.about = function () { + const i = S.info || {}; + $("#page").innerHTML = `
+
MWM
Move Weight Manager - v${esc(i.version || "")}
+
Free and open source. No ads, no "Pro" upsell, no telemetry. One lightweight app for cleaning, uninstalling, repair and recovery.
+
License: GPL-3.0-or-later - Made by the MoveWeight Foundation.
+
${i.elevated ? 'Running as administrator' : ''}
+
This machine
+ + + + + + +
Computer${esc(i.hostname)}
System${esc(i.os)}
Processor${esc(i.cpu)} (${esc(i.cores)} threads)
Memory${bytes(i.memory_used)} used of ${bytes(i.memory_total)}
Up since${i.uptime_secs ? new Date(Date.now() - i.uptime_secs * 1000).toLocaleString() : ""}
+ ${WEB || TARGET ? "" : `
Remote access
Loading...
`} +
Updates

App version

You are running v${esc(i.version || "?")}. Check GitHub for the newest MWM release.
+
How MWM keeps you safe
+
    +
  • Scans never delete anything. Cleaning only touches caches and temp files, and skips anything in use.
  • +
  • Uninstall leftovers go to the Recycle Bin; registry keys are exported to .reg backups before removal.
  • +
  • Startup items are switched off the same way Task Manager does it - never deleted.
  • +
  • Updates come from winget (the publisher's own installers); drivers only from Windows Update or the maker.
  • +
`; + drawRemoteAccess(); + drawUpdateCheck(); +}; + +// ------------------------------------------------- app update check ---- +function drawUpdateCheck() { + const btn = $("#upd-check"); + const out = $("#upd-check-result"); + if (!btn || !out) return; + btn.onclick = async () => { + btn.disabled = true; + out.innerHTML = '
Asking GitHub for the latest release...
'; + try { + const r = await invoke("app_latest_release"); + const newer = r.update_available; + const notes = (r.notes || "").trim().split("\n").slice(0, 6).map(esc).join("
"); + out.innerHTML = `
+
${newer ? `New version available: ${esc(r.tag)}
Published ${r.published ? new Date(r.published).toLocaleString() : ""}
` : `Up to date ${esc(r.tag)} is the latest release (${r.published ? new Date(r.published).toLocaleDateString() : ""}).`}
+ ${newer ? `
Open release ↗${DEMO || TARGET ? "" : ``}
` : ""}
+ ${notes ? `
Release notes
${notes}
` : ""} +
${TARGET ? "This checks the machine you are managing." : (S.info || {}).platform === "windows" ? "Windows: the MWM Portable Updater task also installs new releases automatically (checksum-verified) when the app is closed." : "Servers: mwm-self-update installs new releases automatically from the verified GitHub release."}
`; + const open = $("#upd-open"); + if (open && newer) open.onclick = () => localInvoke("open_default", { path: r.url }); + if (newer) toast(`MWM ${r.tag} is available.`); + } catch (e) { + out.innerHTML = `
Couldn't reach GitHub: ${esc(String(e))}
`; + } + btn.disabled = false; + }; +} + +// ------------------------------------------------------ remote access ---- +async function drawRemoteAccess() { + const box = $("#ra-card"); + if (!box) return; + const st = await localInvoke("remote_access_status").catch((e) => ({ error: String(e) })); + if (st.error) { box.innerHTML = `
Remote access
${esc(st.error)}
`; return; } + box.innerHTML = `
Remote access

Manage this ${S.info?.platform === "windows" ? "PC" : "machine"} from another MWM or a browser

+
Runs MWM's secure web server here. Anyone with the access token can manage this machine - share it only with yourself.
+
+
+ +
+ ${st.running ? `
On another MWM: Machines → Add machine, paste this link:
${esc(st.link.replace(/token=.*/, "token=" + "•".repeat(12)))} +
+
Plain HTTP - fine on your home network; use a VPN (Tailscale, WireGuard) to reach it from outside.${S.info?.platform === "windows" ? " Windows may ask to allow MWM through the firewall - allow it on Private networks." : ""}
` : ""}`; + $("#ra-toggle").onclick = async () => { + const r = st.running ? await guard(() => localInvoke("remote_access_stop")) : await guard(() => localInvoke("remote_access_start", { bind: $("#ra-bind").value.trim(), readOnly: $("#ra-ro").checked })); + if (r) toast(r.running ? "Remote access is on." : "Remote access is off."); + drawRemoteAccess(); + }; + if (st.running) { + $("#ra-copy").onclick = () => copyText(st.link); + $("#ra-new").onclick = async () => { + if (!(await choose("New access token?", '

Every MWM that uses the old token loses access until you give it the new link.

', [["go", "Make a new token", "primary"]]))) return; + await localInvoke("remote_access_new_token"); + toast("New token made."); + drawRemoteAccess(); + }; + } +} + +// ============================================================== boot ==== +document.addEventListener("DOMContentLoaded", async function boot() { + renderNav(); + try { + S.info = await invoke("system_info"); + } catch (e) { + // Last-used remote machine is unreachable: start on this PC instead. + if (TARGET) { TARGET = ""; try { localStorage.setItem("mwm.target", ""); } catch {} toast(`Couldn't reach the last machine - showing this PC. (${e})`, true); } + S.info = await invoke("system_info").catch(() => ({ disks: [], elevated: false })); + } + await renderSwitcher(); + $("#elev").className = "elev" + (S.info.elevated ? " admin" : ""); + $("#elev").innerHTML = `${S.info.elevated ? "Administrator" : `Standard user - elevate`}`; + $("#ver").textContent = `v${S.info.version || ""}${DEMO ? " - web demo" : ""} - ${S.info.hostname || ""}`; + if (!WEB && !DEMO && !TARGET) { + const pending = await localInvoke("pending_open_dir").catch(() => null); + if (pending) { go("files"); setTimeout(() => loadPane(CMD.panes[0], pending, false), 350); return; } + } + go(DEMO && location.pathname.startsWith("/demo") ? "appliances" : "topology"); +}); diff --git a/app/ui/appliances.js b/app/ui/appliances.js new file mode 100644 index 0000000..7b5fddc --- /dev/null +++ b/app/ui/appliances.js @@ -0,0 +1,70 @@ +/* Unified physical appliances and application-only maintenance. */ +"use strict"; +const OPS={source:null,network:null,media:null,watching:false}; +const opsCall=(cmd,args={})=>OPS.source?localInvoke('remote_call',{id:OPS.source,cmd,args}):localInvoke(cmd,args); +async function opsLocate(){ + const conns=await localInvoke('conn_list').catch(()=>[]); + const choices=[TARGET||'',...conns.filter(c=>c.url.includes('192.168.0.6')).map(c=>c.id),'',...conns.map(c=>c.id)]; + for(const id of [...new Set(choices)]){ + try{const d=id?await localInvoke('remote_call',{id,cmd:'appliance_status',args:{}}):await localInvoke('appliance_status');if(d?.available){OPS.source=id;OPS.network=d;return;}}catch{} + } + throw Error('Select the updated fleet controller in Machines. Its appliance adapter is not available on this machine.'); +} +const OPS_DEMO_APPS=[ + {name:"Plex Media Server · Library A",host:"media-node-1",version:"1.43.5",available:null,status:"Healthy"}, + {name:"Plex Media Server · Library B",host:"media-node-2",version:"1.43.5",available:null,status:"Healthy"}, + {name:"Jellyfin",host:"media-node-2",version:"10.10.7",available:"10.11.0",status:"Healthy"}, + {name:"Sonarr",host:"media-node-1",version:"4.0.19",available:"4.0.20",status:"Healthy"}, + {name:"Radarr",host:"media-node-1",version:"6.4.3",available:"6.4.4",status:"Healthy"}, + {name:"Prowlarr",host:"media-node-1",version:"2.6.4",available:"2.6.5",status:"Healthy"}, + {name:"RomM",host:"media-node-2",version:"4.0.0",available:"4.1.0",status:"Healthy"} +]; +let opsDemoEvents=["MWM connected to the example firewall and access point.","Proxmox cluster quorum: 3 of 3 nodes.","Media service checks passed."]; +function opsDemoDraw(){ + $('#top-actions').innerHTML=''; + $('#page').innerHTML=`
Interactive fleet demo
SIMULATED · no real devices

Network & media

This sample shows how MWM links your gateway, Wi-Fi, servers, and media apps. Demo buttons change only this page in your browser.

Open your manager with SSO
+

Connected topology

MWM control plane · connected
Internet / WAN→OPNsense firewall · 192.0.2.1→2.5 GbE switch · 192.0.2.3→3-node Proxmox cluster
TP-Link Wi-Fi 7 access point · 192.0.2.2 → switchAI nodeWindows devices

Management links are authenticated independently. Example IPs use a documentation-only range.

+

OPNsense firewall

online · API connected

192.0.2.1 · WAN + LAN gateway

Suricata IDS · threat feed · daily rule updates

Gateway: healthy   DNS: 2 resolvers healthy

TP-Link Archer BE3600

online

192.0.2.2 · Access Point mode

Connected to the core switch; OPNsense supplies routing and DHCP.

+

Server fleet

MWM manages the Proxmox hosts, Linux services, AI node, and Windows PCs from the same fleet view.

Proxmox A · onlineProxmox B · onlineProxmox C · onlineAI node · onlineWindows PC · online

Protection & backups

Firewall rules active DNS healthy

IDS in alert-only mode; safe update controls check backup coverage before applying app updates.

+

Plex · Jellyfin · ARR · RomM

Sample app inventory

Try an update to see the workflow. This demo never contacts a server or downloads software.

${OPS_DEMO_APPS.map((a,i)=>`
${esc(a.name)}${esc(a.status)}

${esc(a.host)} · API health check passed

${esc(a.version)}${a.available?` → ${esc(a.available)}`:' · current'}

${a.available?``:'Up to date'}
`).join('')}
+

Recent activity

${opsDemoEvents.map(x=>`

✓ ${esc(x)}

`).join('')}
`; + const event=(msg)=>{opsDemoEvents.unshift(new Date().toLocaleTimeString()+" · "+msg);opsDemoEvents=opsDemoEvents.slice(0,5);$('#ops-demo-events').innerHTML=opsDemoEvents.map(x=>`

✓ ${esc(x)}

`).join('');}; + $('#ops-demo-refresh').onclick=()=>{event('Health dashboard refreshed (simulation).');toast('Demo health view refreshed.');}; + $('#ops-demo-check').onclick=()=>{event('Health check passed: firewall, access point, 5 hosts, and 7 media apps.');toast('Demo health check passed.');}; + $('#ops-demo-firewall').onclick=$('#ops-demo-firewall-detail').onclick=()=>{event('OPNsense API check passed; gateway, DNS, and IDS are healthy (simulation).');toast('Demo firewall control succeeded.');}; + $('#ops-demo-ap').onclick=()=>{event('TP-Link access point is reachable from the switch (simulation).');toast('Demo access point check passed.');}; + $('#ops-demo-recovery').onclick=()=>{event('DNS recovery sequence completed (simulation only).');toast('Demo recovery completed.');}; + $$('[data-ops-demo-update]').forEach(b=>b.onclick=()=>{const a=OPS_DEMO_APPS[+b.dataset.opsDemoUpdate];if(!a?.available)return;a.version=a.available;a.available=null;event(`${a.name} updated successfully (simulation).`);toast(`${a.name} updated in the demo.`);opsDemoDraw();}); +} +VIEWS.appliances=async function(){ + if(DEMO){opsDemoDraw();return;} + $('#top-actions').innerHTML=''; + $('#ops-refresh').onclick=()=>VIEWS.appliances();$('#ops-scan').onclick=()=>opsJob('media_app_scan'); + $('#page').innerHTML=loading('Reading firewall, Wi-Fi access point and media application health…'); + try{await opsLocate();OPS.media=await opsCall('media_app_report');if(current==='appliances')opsDraw();} + catch(e){if(current==='appliances')$('#page').innerHTML=`
${esc(String(e))}
`;} +}; +function opsBadge(ok,label){return `${esc(label||(ok?'online':'unreachable'))}`;} +function opsDraw(){ + const devices=OPS.network?.devices||[],fw=devices.find(x=>x.id==='opnsense'),ap=devices.find(x=>x.id==='tplink'),apps=OPS.media?.applications||[]; + const stats=Object.entries(fw?.interfaces?.statistics||{}).filter(([,x])=>['igb0','igb3'].includes(x.name)); + const services=(fw?.services?.rows||[]),restarts=new Set(['unbound','dnsmasq','dhcpd','ntpd','chrony','kea-dhcp4','kea-dhcp6']); + $('#page').innerHTML=`
Fleet operations

Network & media

Physical firewall, Wi-Fi, media services and application updates alongside your server and Windows connections.

+
${devices.map(d=>`

${esc(d.name)}

${opsBadge(d.online)}

${esc(d.address)}

${esc(d.role)}${d.mode?' · '+esc(d.mode):''}

${d.id==='opnsense'?`

${esc(d.system?.versions?.[0]||'Version unavailable')} · ${opsBadge(d.api_connected,'API '+(d.api_connected?'connected':'unavailable'))}

LAN ${esc(d.lan_interface)} · WAN ${esc(d.wan_interface)} · gateway alias ${esc(d.legacy_gateway)}

${esc(d.lte)}

${d.ids?`
Suricata LAN intrusion detection${opsBadge(d.ids.running, d.ids.status||'unknown')}

PCAP alert-only · ${d.ids.active_rulesets.length} rulesets enabled · daily rule updates · 7 alert logs retained

${d.ids.active_rulesets.map(x=>esc(x.name)).join(' · ')}

Alert files: ${(d.ids.alert_logs||[]).length} · latest ${esc(d.ids.alert_logs?.[0]?.modified||'none')}

`:''}`:`

Live management-page reachability: ${d.latency_ms??'—'} ms. Wi-Fi clients, settings and firmware controls open in TP-Link’s native interface.

`}
${d.id==='opnsense'?'':''}
${d.error?`

${esc(d.error)}

`:''}
`).join('')}
+ ${fw?`

Firewall interfaces & gateway

${(fw.gateways?.items||[]).map(g=>`${esc(g.name)} · ${esc(g.status_translated||g.status)} · ${esc(g.address)}`).join('')}
${stats.map(([name,x])=>``).join('')}
InterfaceReceivedSentErrorsDrops
${esc(name)}${bytes(x['received-bytes'])}${bytes(x['sent-bytes'])}${num((+x['received-errors']||0)+(+x['send-errors']||0))}${num(x['dropped-packets'])}

Firewall services

${services.map(s=>`
${esc(s.name)} ${opsBadge(!!s.running,s.running?'running':'stopped')} ${!s.locked&&restarts.has(s.id)?``:''}
`).join('')}
${fw.interfaces?.error?`

${esc(fw.interfaces.error)}

`:''}

Firewall and OS upgrades are held. Checking firmware does not install it.

`:''} +

Media applications

${OPS.media?.generated_at?esc(new Date(OPS.media.generated_at).toLocaleString()):'Scan not run'}

Application updates preserve verified native backups plus snapshots where supported, or application binary rollback archives. OS upgrades are separate. Custom installations and missing backup coverage are shown for review.

${apps.map(a=>`
${esc(a.server_name||a.name)}${opsBadge(a.online,a.state?.replaceAll('_',' ')||a.guest_status)}

${esc(a.node)} · CT ${esc(a.vmid)} · ${esc(a.ip||'')}

${esc(a.version||a.installed_package||'Version not reported')}${a.update_version?' → '+esc(a.update_version):''}

${a.active_sessions!=null?`

${a.active_sessions} active Plex sessions

`:''}${a.error?`

${esc(a.error)}

`:''}${a.note?`

${esc(a.note)}

`:''}${a.health?.length?`
${a.health.length} health messages${a.health.map(h=>`

${esc(h.message)}

`).join('')}
`:''}
${a.ip?``:''}${a.update_supported&&(a.update_version||a.restart_needed)?``:''}
`).join('')}
+

Docker application projects

${(OPS.media?.docker?.projects||[]).filter(x=>x.project).map(p=>`
${esc(p.project)} · ${esc(p.node)} / CT ${esc(p.vmid)} · ${esc(p.status)}${p.backup_ready?'Backup coverage configured':'Backup coverage needs attention'}
`).join('')}
`;
+ $$('[data-device-open]').forEach(b=>b.onclick=()=>opsOpen(b.dataset.deviceOpen));
+ $('#ops-fw-check')?.addEventListener('click',()=>opsJob('appliance_action',{action:'check_updates'}));
+ $$('[data-fw-restart]').forEach(b=>b.onclick=async()=>{if(await choose('Restart firewall service?',`

${esc(b.dataset.fwRestart)} may briefly interrupt DNS or DHCP.

`,[['yes','Restart','danger']]))opsJob('appliance_action',{action:'restart_service',service:b.dataset.fwRestart});}); + $$('[data-app-update]').forEach(b=>b.onclick=async()=>{if(await choose('Update this application?',`

CT ${esc(b.dataset.appUpdate)} may restart its application. MWM will preserve a native backup and a snapshot or application rollback archive first. OS upgrades remain held.

`,[['yes','Update application','primary']]))opsJob('media_app_update',{vmid:b.dataset.appUpdate});}); + $$('[data-media-open]').forEach(b=>b.onclick=()=>{const ports={sonarr:8989,radarr:7878,lidarr:8686,prowlarr:9696,plex1:32400,plex2:32400,jellyfin:8096,romm:8080,seerr:5055,qbittorrent:8080};opsOpen('http://'+b.dataset.mediaIp+':'+(ports[b.dataset.mediaOpen]||80));}); +} +function opsOpen(url){if(TAURI)localInvoke('open_default',{path:url});else window.open(url,'_blank','noopener,noreferrer');} +async function opsJob(cmd,args={}){ + if(OPS.watching){toast('A maintenance job is already being tracked.',true);return;} + try{const r=await opsCall(cmd,args);if(!r?.job){toast('Request completed.');return;}OPS.watching=true;toast('Maintenance job started on the fleet controller.'); + const provider=OPS.source,call=(c)=>provider?localInvoke('remote_call',{id:provider,cmd:c,args:{}}):localInvoke(c); + for(let n=0;n<600;n++){await new Promise(r=>setTimeout(r,2000));const j=(await call('jobs_list')).find(x=>x.id===r.job);if(!j)break;const log=$('#ops-joblog');if(log)log.textContent=[j.title,j.state,j.message,...(j.output||[])].join('\n');if(j.state!=='running'){toast(j.message||j.state,j.state!=='done');break;}} + }catch(e){toast(String(e),true);}finally{OPS.watching=false;if(current==='appliances')VIEWS.appliances();} +} diff --git a/app/ui/command.js b/app/ui/command.js index 0a064ec..8db9b7a 100644 --- a/app/ui/command.js +++ b/app/ui/command.js @@ -65,7 +65,7 @@ function drawCommand() { $("#page").innerHTML = `
MWM v5 · your infrastructure

Command Center

One place for the machines, LXCs, apps and domains behind your products.

${esc(d.inventory?.cluster?.name || CENTER.pve?.cluster?.name || "Proxmox fleet")}${esc(fresh)}
-
+
Nodes
${d.nodes.length}
${d.nodes.filter((n) => n.status === "online").length} online
diff --git a/app/ui/devices.js b/app/ui/devices.js new file mode 100644 index 0000000..7c55d68 --- /dev/null +++ b/app/ui/devices.js @@ -0,0 +1,336 @@ +/* Dense live snapshot for every managed MWM host and known network device. */ +"use strict"; + +const DEVICE_VIEW = { connections: [], local: null, localSrv: null, pve: null, network: null, map: [], remotes: [], updated: null }; +const deviceRows = (v) => Array.isArray(v) ? v : Array.isArray(v?.devices) ? v.devices : []; +const deviceHost = (v) => { try { return new URL(v).hostname; } catch { return ""; } }; +const deviceTry = async (fn) => { try { return await fn(); } catch { return null; } }; +const deviceSame = (a, b) => !!a && !!b && String(a).trim().toLowerCase() === String(b).trim().toLowerCase(); +function dNum(v) { if (v === null || v === undefined || v === "") return null; const n = Number(v); return Number.isFinite(n) ? n : null; } +function dBytes(v) { const n = dNum(v); return n === null ? "Unavailable" : bytes(n); } +function dPct(used, total) { const u = dNum(used), t = dNum(total); return u === null || !t ? null : Math.max(0, Math.min(100, u * 100 / t)); } +function dDuration(v) { + const n = dNum(v); if (n === null) return "Unavailable"; + let s = Math.max(0, Math.floor(n)); const d = Math.floor(s / 86400); s %= 86400; + const h = Math.floor(s / 3600); s %= 3600; const m = Math.floor(s / 60); + return (d ? d + "d " : "") + (h ? h + "h " : "") + m + "m"; +} +function dState(v, detail) { + if (v === true || v === "online" || v === "running") return ["ONLINE", "low"]; + if (v === false || v === "offline" || v === "stopped") return ["OFFLINE", "high"]; + if (v === "planned") return ["PLANNED", ""]; + if (v === "leased") return ["LEASE", "medium"]; + if (v === "last_seen" || (v === "unknown" && /Last observed|Last seen/i.test(detail || ""))) return ["LAST SEEN", "medium"]; + return ["UNKNOWN", "medium"]; +} +function dMetric(label, value, sub, title) { + return '
' + esc(label) + '
' + esc(value || "Unavailable") + '
' + esc(sub || "") + '
'; +} +function dFact(label, value) { + return '
' + esc(label) + '' + esc(value || "Unavailable") + '
'; +} +function dLoad(srv, cores) { + const raw = String(srv?.load || "").trim(); + if (!raw) return ["Unavailable", "Load average is not reported on this OS"]; + const a = raw.split(/\s+/).slice(0, 3).map(Number).filter(Number.isFinite); + if (!a.length) return ["Unavailable", "Load average not reported"]; + const per = cores ? " · " + (a[0] / cores).toFixed(2) + "/core" : ""; + return ["1m " + a[0].toFixed(2) + per, "5m " + (a[1] ?? a[0]).toFixed(2) + " · 15m " + (a[2] ?? a[0]).toFixed(2)]; +} +function dVolumes(info, srv) { + const sysDisks = Array.isArray(info?.disks) ? info.disks : []; + const mounts = Array.isArray(srv?.mounts) && srv.mounts.length ? srv.mounts : sysDisks; + return mounts.filter((x) => dNum(x.total) > 0).sort((a, b) => (dNum(b.total) || 0) - (dNum(a.total) || 0)); +} +function dPrimaryDisk(info, srv, pveNode) { + if (pveNode && dNum(pveNode.maxdisk) > 0) return { total: pveNode.maxdisk, used: pveNode.disk, free: Math.max(0, Number(pveNode.maxdisk) - Number(pveNode.disk)), mount: "Proxmox node root" }; + const v = dVolumes(info, srv); + if (!v.length) return null; + const x = v.find((x) => x.mount === "/" || x.mount === "C:\\" || x.mount === "C:/") || v[0]; + return { total: x.total, used: x.used ?? (Number(x.total) - Number(x.free)), free: x.free ?? (Number(x.total) - Number(x.used || 0)), mount: x.mount || x.name || "Volume" }; +} +function dGpuRows(srv) { return Array.isArray(srv?.gpus) ? srv.gpus : []; } +function dHostCard(m) { + const i = m.info || {}, s = m.srv || {}, n = m.pveNode || null; + const cores = dNum(n?.maxcpu) || dNum(i.cores) || 0; + const cpuPct = n ? (dNum(n.cpu) === null ? null : dNum(n.cpu) * 100) : dNum(s.cpu_usage_pct); + const ramTotal = dNum(n?.maxmem) || dNum(i.memory_total) || 0; + const ramUsed = dNum(n?.mem) ?? dNum(i.memory_used); + const ramPct = dPct(ramUsed, ramTotal); + const disk = dPrimaryDisk(i, s, n); + const diskPct = disk ? dPct(disk.used, disk.total) : null; + const gpus = dGpuRows(s); + const vramTotal = gpus.reduce((a, g) => a + (dNum(g.vram_total_bytes) || 0), 0); + const vramUsed = gpus.reduce((a, g) => a + (dNum(g.vram_used_bytes) || 0), 0); + const gpuLoad = gpus.map((g) => dNum(g.utilization_pct)).filter((x) => x !== null); + const gpuTemp = gpus.map((g) => dNum(g.temp_c)).filter((x) => x !== null); + const load = dLoad(s, cores); + const drives = (Array.isArray(s.drives) && s.drives.length ? s.drives : Array.isArray(s.smart) && s.smart.length ? s.smart : Array.isArray(s.unraid?.disks) ? s.unraid.disks : []).filter((x) => !String(x.device || x.name || "").startsWith("/dev/bus/")); + const volumes = dVolumes(i, s); + const issues = []; + if (arr(s.failed).length) issues.push(arr(s.failed).length + " failed services"); + if (arr(s.zfs).some((x) => x.health && x.health !== "ONLINE")) issues.push("degraded ZFS"); + if (drives.some((x) => x.passed === false)) issues.push("SMART failure"); + if (diskPct !== null && diskPct >= 90) issues.push("disk " + Math.round(diskPct) + "% used"); + const isUp = m.online !== undefined ? !!m.online : (n?.status === "online"); + const [label, tone] = dState(isUp); + const alert = issues.length > 0; + const status = !isUp ? ["OFFLINE", "high"] : alert ? ["ATTENTION", "medium"] : [label, tone]; + const addr = m.address ? '' + esc(m.address) + '' : ""; + const os = i.os || ({ linux: "Linux", windows: "Windows", macos: "macOS" }[i.platform] || i.platform || "Host"); + const title = m.name || i.hostname || n?.node || "MWM host"; + const hostSub = [i.hostname, os, m.latency ? m.latency + " ms" : ""].filter(Boolean).join(" · "); + const coreText = cores ? cores + " logical cores" : "Core count unavailable"; + const cpuValue = cpuPct === null ? "Unavailable" : Math.round(cpuPct) + "%"; + const cpuSub = coreText + (n ? " · Proxmox node" : " · sampled by MWM"); + const ramValue = ramPct === null ? "Unavailable" : Math.round(ramPct) + "%"; + const ramSub = ramTotal ? dBytes(ramUsed) + " / " + dBytes(ramTotal) : "Memory totals unavailable"; + const vramValue = gpus.length ? (vramTotal ? dBytes(vramUsed) + " / " + dBytes(vramTotal) : "VRAM unavailable") : "No GPU reported"; + const vramSub = gpus.length ? gpus.map((g) => g.name || "GPU").join(", ") + (gpuLoad.length ? " · " + Math.round(gpuLoad.reduce((a,b)=>a+b,0)/gpuLoad.length) + "% GPU" : "") + (gpuTemp.length ? " · " + Math.round(gpuTemp.reduce((a,b)=>a+b,0)/gpuTemp.length) + "°C" : "") : "Telemetry missing or no GPU"; + const diskValue = disk ? dBytes(disk.free) + " free" : "Unavailable"; + const diskSub = disk ? dBytes(disk.used) + " used / " + dBytes(disk.total) + " · " + (diskPct === null ? "usage n/a" : Math.round(diskPct) + "% used") : "No disk totals reported"; + const uptime = n?.uptime ?? i.uptime_secs; + const guestCount = n && DEVICE_VIEW.pve?.guests ? DEVICE_VIEW.pve.guests.filter((g) => g.node === n.node) : []; + const guestUp = guestCount.filter((g) => g.status === "running").length; + const metrics = [ + dMetric("CPU / CORES", cpuValue, cpuSub, i.cpu || "CPU model not reported"), + dMetric("LOAD", load[0], load[1], "Load average is runnable work, shown separately from CPU utilization."), + dMetric("RAM", ramValue, ramSub), + dMetric("GPU / VRAM", vramValue, vramSub), + dMetric("DISK SPACE", diskValue, diskSub, disk?.mount || ""), + dMetric("UPTIME", dDuration(uptime), n ? guestUp + "/" + guestCount.length + " guests on this node" : "MWM host uptime") + ].join(""); + const driveFacts = drives.length ? drives.map((d) => { + const cap = dBytes(d.capacity || d.total); + const health = d.passed === false ? "SMART FAIL" : d.passed === true ? "SMART OK" : (d.status || "health unavailable"); + const temp = d.temp !== undefined && d.temp !== null ? " · " + d.temp + "°C" : ""; + return (d.model || d.name || d.device || "Drive") + " · " + cap + " · " + health + temp; + }).join(" | ") : "Physical drive / bay telemetry not reported"; + const gpuFacts = gpus.length ? gpus.map((g) => (g.name || "GPU") + " · " + (dNum(g.vram_used_bytes) !== null ? dBytes(g.vram_used_bytes) + " / " + dBytes(g.vram_total_bytes) : "VRAM usage unavailable") + (dNum(g.utilization_pct) !== null ? " · " + Math.round(Number(g.utilization_pct)) + "% load" : "") + (dNum(g.temp_c) !== null ? " · " + Math.round(Number(g.temp_c)) + "°C" : "")).join(" | ") : "No GPU telemetry reported"; + const volumeMarkup = volumes.length ? '
All volumes (' + volumes.length + ')
' + volumes.map((v) => { + const free = dNum(v.free) ?? Math.max(0, (dNum(v.total) || 0) - (dNum(v.used) || 0)); + const used = dNum(v.used) ?? Math.max(0, (dNum(v.total) || 0) - free); + const pct = dPct(used, v.total); + return '
' + esc(v.mount || v.name || "Volume") + '' + esc(dBytes(free) + " free / " + dBytes(v.total) + (pct === null ? "" : " · " + Math.round(pct) + "% used")) + '
'; + }).join("") + '
' : ""; + const facts = '
' + + dFact("Processor", i.cpu || "CPU model unavailable") + + dFact("Graphics / VRAM", gpuFacts) + + dFact("Physical drives / bays", drives.length ? drives.length + " reported · " + driveFacts : driveFacts) + + (n ? dFact("Node guests", guestUp + " running / " + guestCount.length + " total") : "") + + (issues.length ? dFact("Attention", issues.join(" · ")) : "") + + volumeMarkup + '
'; + const manage = m.connection ? '' : ''; + return '
' + + '
' + icon(m.icon || "server") + '
' + esc(title) + '' + esc(hostSub) + '
' + + '' + status[0] + '
' + + '
' + addr + (m.detail ? '' + esc(m.detail) + '' : "") + '
' + + '
' + metrics + '
' + facts + + '
' + manage + '
'; +} +function dInterface(fw, name, label) { + const stats = fw?.interfaces?.statistics || {}; + const entries = Object.entries(stats).filter(([,v]) => v.name === name); + const picked = entries.find(([,v]) => v.mtu !== undefined && v["received-bytes"] !== undefined) || entries.find(([,v]) => v["received-bytes"] !== undefined); + if (!picked) return label + " " + name + ": counters unavailable"; + const x = picked[1]; + return label + " " + name + " · RX " + dBytes(x["received-bytes"]) + " · TX " + dBytes(x["sent-bytes"]) + + " · errors " + ((Number(x["received-errors"]) || 0) + (Number(x["send-errors"]) || 0)) + + " · drops " + (Number(x["dropped-packets"]) || 0); +} +function dApplianceCard(d) { + const online = d.online === true; + const [label, tone] = dState(d.online); + const fw = d.id === "opnsense"; + if (!fw) { + const fields = [ + dMetric("CPU / CORES", "Not exposed", "Router API does not report processor data"), + dMetric("LOAD", "Not exposed", "No load average endpoint"), + dMetric("RAM", "Not exposed", "Router API does not report memory"), + dMetric("GPU / VRAM", "N/A", "Access point"), + dMetric("DISK / BAYS", "Not exposed", "No disk inventory endpoint"), + dMetric("UPTIME", "Not exposed", "No uptime endpoint") + ].join(""); + const detail = [d.role, d.mode, d.http_status ? "HTTP " + d.http_status : "", d.latency_ms !== undefined ? d.latency_ms + " ms HTTP response" : "", d.firmware_update].filter(Boolean).join(" · "); + return '
' + icon("net") + '
' + esc(d.name) + '' + esc(d.address || "") + '
' + label + '
' + esc(detail || d.error || "No device telemetry") + '
' + fields + '
' + dFact("Device", d.role || "TP-Link network device") + dFact("Live check", online ? "Management page reachable" : d.error || "Management page unreachable") + dFact("Client count", "Not exposed by current integration") + '
'; + } + const memory = d.resources?.memory || {}; + const ramTotal = dNum(memory.total), ramUsed = dNum(memory.used); + const ramPct = dPct(ramUsed, ramTotal); + const rt = d.system_time || {}; + const root = (d.system_disk?.devices || []).find((x) => x.mountpoint === "/"); + const gw = (d.gateways?.items || []).find((x) => x.name === "WAN_DHCP") || (d.gateways?.items || [])[0]; + const services = d.services?.rows || []; + const running = services.filter((x) => Number(x.running) === 1).length; + const versions = (d.system?.versions || []).join(" · "); + const fields = [ + dMetric("CPU / CORES", "Not exposed", "Firewall API does not return model or core count"), + dMetric("LOAD", rt.loadavg || "Unavailable", "System load average"), + dMetric("RAM", ramPct === null ? "Unavailable" : Math.round(ramPct) + "%", ramTotal ? dBytes(ramUsed) + " / " + dBytes(ramTotal) : "Memory unavailable"), + dMetric("GPU / VRAM", "N/A", "Firewall appliance"), + dMetric("DISK SPACE", root ? dBytes(root.available_bytes) + " free" : "Unavailable", root ? dBytes(root.used_bytes) + " used / " + dBytes(root.total_bytes) + " · " + (root.used_pct ?? "?") + "% used" : "Root filesystem not reported"), + dMetric("UPTIME", rt.uptime || "Unavailable", rt.datetime || "System time unavailable") + ].join(""); + const networkFacts = dFact("WAN", dInterface(d, d.wan_interface || "igb3", "WAN")) + + dFact("LAN", dInterface(d, d.lan_interface || "igb0", "LAN")); + const leasesError = d.leases?.error ? "DHCP API: " + d.leases.error + "; saved clients are last-seen only" : "Live DHCP leases: " + (deviceRows(d.leases).length || 0); + return '
' + icon("shield") + '
' + esc(d.name) + '' + esc(d.address || "") + ' · ' + esc(versions) + '
' + label + '
Gateway ' + esc(gw?.status_translated || gw?.status || "unknown") + ' · ' + esc(gw?.address || "no WAN address") + ' · API ' + (d.api_connected ? "connected" : "unavailable") + '
' + fields + '
' + dFact("Services", running + " running / " + (d.services?.rowCount ?? services.length) + " reported") + dFact("IDS / Suricata", d.ids?.status || "Not reported") + networkFacts + dFact("DHCP inventory", leasesError) + dFact("Firmware", d.firmware?.product?.CORE_VERSION || versions) + '
'; +} +function dArrisCard(d) { + const [label, tone] = dState(d.online); + const login = d.login_required === true || d.access_state === "login_required"; + const access = !d.online ? (d.error || "Modem management page is unreachable") : login ? "Management page reachable; sign in required for modem telemetry" : "Management page reachable"; + const fields = [ + dMetric("CPU / CORES", "Not exposed", "Embedded modem telemetry is not available"), + dMetric("LOAD", "Not exposed", "No modem load endpoint"), + dMetric("RAM", "Not exposed", "No modem memory endpoint"), + dMetric("GPU / VRAM", "N/A", "Cable modem"), + dMetric("DISK / BAYS", "Not exposed", "No modem storage inventory endpoint"), + dMetric("UPTIME", "Login required", "Not available without modem telemetry access") + ].join(""); + const detail = [d.role || "Cable modem", d.standard || "DOCSIS version unavailable", d.latency_ms !== undefined ? d.latency_ms + " ms response" : "", d.http_status ? "HTTP " + d.http_status : ""].filter(Boolean).join(" | "); + return '
' + icon("net") + '
' + esc(d.name || "ARRIS SURFboard G36") + '' + esc(d.address || "192.168.100.1") + '
' + label + '
' + esc(detail) + '
' + fields + '
' + + dFact("Model", d.model || "ARRIS SURFboard G36") + + dFact("Cable standard", d.standard || "DOCSIS 3.1") + + dFact("Signal levels / channels", login ? "Login required; not sampled" : "Unavailable from current unauthenticated check") + + dFact("Firmware / registration / uptime", login ? "Login required; not sampled" : "Unavailable from current unauthenticated check") + + dFact("Management check", access) + + '
'; +} +function dInventoryCard(d) { + const [label, tone] = dState(d.state, d.detail); + const fields = [ + dMetric("CPU / CORES", "No MWM telemetry", "Host agent not connected"), + dMetric("LOAD", "Unavailable", "No live host sample"), + dMetric("RAM", "Unavailable", "No live host sample"), + dMetric("GPU / VRAM", "Unavailable", "No live host sample"), + dMetric("DISK / BAYS", "Unavailable", "No live host sample"), + dMetric("UPTIME", "Unavailable", "No live host sample") + ].join(""); + const action = d.href ? 'Open management ↗' : ""; + return '
' + icon(d.icon || "net") + '
' + esc(d.name || "LAN client") + '' + esc(d.role || "Network inventory") + '
' + label + '
' + (d.address ? '' + esc(d.address) + '' : "") + '
' + fields + '
' + dFact("Inventory", d.detail || "No live MWM connection") + '
' + action + '
'; +} +function dSection(title, subtitle, cards) { + return '

' + esc(title) + '

' + esc(subtitle) + '
' + cards.length + '
' + (cards.length ? cards.join("") : '
No devices reported.
') + '
'; +} +function drawDeviceTopology() { + if (current !== "topology") return; + const remotes = DEVICE_VIEW.remotes; + const clusterSource = remotes.find((r) => Array.isArray(r.srv?.nodes) && r.srv.nodes.length); + const nodes = clusterSource?.srv.nodes || []; + const guests = clusterSource?.srv.proxmox?.guests || []; + DEVICE_VIEW.pve = clusterSource ? { nodes, guests } : null; + const nodeModels = nodes.map((n) => { + const c = remotes.find((x) => deviceSame(deviceHost(x.connection.url), n.ip) || deviceSame(x.info?.hostname, n.node)); + return { name: n.node, address: n.ip, pveNode: n, connection: c?.connection, online: n.status === "online", latency: c?.ms, info: c?.info || null, srv: c?.srv || null, detail: (c?.online ? "MWM connected" : c ? "PVE node up · MWM endpoint offline" : "PVE telemetry only") }; + }); + const pveAddresses = new Set(nodes.map((n) => String(n.ip || "").toLowerCase()).filter(Boolean)); + const nodeNames = new Set(nodes.map((n) => String(n.node || "").toLowerCase())); + const otherHosts = remotes.filter((c) => !pveAddresses.has(deviceHost(c.connection.url).toLowerCase()) && !nodeNames.has(String(c.info?.hostname || "").toLowerCase())).map((c) => ({ + name: c.connection.name || c.info?.hostname || "MWM host", address: deviceHost(c.connection.url), connection: c.connection, + info: c.info, srv: c.srv, online: c.online, latency: c.ms, detail: c.online ? "Managed MWM endpoint" : c.error || "Saved endpoint did not respond", + icon: c.online ? "server" : "alert" + })); + const local = DEVICE_VIEW.local || {}; + const localModel = { name: local.hostname || "This PC", info: local, srv: DEVICE_VIEW.localSrv || {}, online: true, detail: "This MWM · local Windows/Linux/macOS host", icon: "server" }; + const primary = []; + primary.push(dHostCard(localModel)); + nodeModels.forEach((m) => primary.push(dHostCard(m))); + otherHosts.forEach((m) => primary.push(dHostCard(m))); + const network = deviceRows(DEVICE_VIEW.network); + const fw = network.find((d) => d.id === "opnsense"); + const ap = network.find((d) => d.id === "tplink"); + const modem = network.find((d) => d.id === "arris_g36") || DEVICE_VIEW.map.find((d) => d.kind === "modem"); + primary.push(fw ? dApplianceCard(fw) : dInventoryCard({ name: "OPNsense firewall", address: "192.168.0.1", state: "unknown", role: "Firewall / gateway", detail: "Live firewall status unavailable", icon: "shield" })); + primary.push(ap ? dApplianceCard(ap) : dInventoryCard({ name: "TP-Link access point", address: "192.168.0.2", state: "unknown", role: "Wi-Fi access point", detail: "Live router status unavailable", icon: "net" })); + primary.push(modem?.id === "arris_g36" ? dArrisCard(modem) : dInventoryCard({ name: "ARRIS SURFboard G36", address: "192.168.100.1", state: "unknown", role: "DOCSIS 3.1 cable modem", detail: "Live modem check unavailable", icon: "net", href: "https://192.168.100.1/" })); + const already = new Set([ + ...nodes.map((n) => n.ip), + ...remotes.map((c) => deviceHost(c.connection.url)), + ...network.map((d) => d.address), + local.hostname + ].filter(Boolean).map((x) => String(x).toLowerCase())); + const inventory = DEVICE_VIEW.map.filter((d) => d.kind !== "modem" && !already.has(String(d.address || "").toLowerCase()) && !nodeNames.has(String(d.name || "").toLowerCase())).map((d) => ({ + name: d.name, address: d.address, state: d.state || "unknown", role: d.role, detail: d.detail, icon: d.icon, href: d.href + })); + const liveLeases = deviceRows(fw?.leases).filter((l) => l.address && !already.has(String(l.address).toLowerCase()) && !inventory.some((d) => deviceSame(d.address, l.address))).map((l) => ({ + name: l.hostname || "LAN client", address: l.address, state: "leased", role: "Active DHCP lease", + detail: (l.lease_type === "static" ? "Static reservation" : "Lease present") + (l.hwaddr ? " · " + l.hwaddr : "") + })); + const allHostModels = [localModel].concat(nodeModels, otherHosts); + const liveHosts = allHostModels.filter((m) => m.online); + const cores = liveHosts.reduce((sum, m) => sum + (dNum(m.pveNode?.maxcpu) || dNum(m.info?.cores) || 0), 0); + const ramTotal = liveHosts.reduce((sum, m) => sum + (dNum(m.pveNode?.maxmem) || dNum(m.info?.memory_total) || 0), 0); + let cpuWeighted = 0, cpuWeight = 0, totalVram = 0, gpuCount = 0; + for (const m of liveHosts) { + const count = dNum(m.pveNode?.maxcpu) || dNum(m.info?.cores) || 0; + const pct = m.pveNode ? (dNum(m.pveNode.cpu) === null ? null : dNum(m.pveNode.cpu) * 100) : dNum(m.srv?.cpu_usage_pct); + if (pct !== null && count > 0) { cpuWeighted += pct * count; cpuWeight += count; } + for (const g of dGpuRows(m.srv)) { const vram = dNum(g.vram_total_bytes); if (vram !== null && vram > 0) gpuCount++; totalVram += vram || 0; } + } + const cpuSummary = cpuWeight ? Math.round(cpuWeighted / cpuWeight) + "% avg" : "Unavailable"; + const netLive = network.filter((d) => d.online === true).length; + const hostTotal = allHostModels.length; + const hostOnline = liveHosts.length; + const guestUp = guests.filter((g) => g.status === "running").length; + const clusterName = "Proxmox cluster"; + const now = DEVICE_VIEW.updated ? new Date(DEVICE_VIEW.updated).toLocaleTimeString() : "now"; + const primaryCount = primary.length + inventory.length + liveLeases.length; + const offlineCount = allHostModels.filter((m) => !m.online).length + network.filter((d) => d.online === false).length; + $("#top-actions").innerHTML = ''; + $("#devices-refresh").onclick = () => VIEWS.topology(); + $("#devices-connect").onclick = () => go("fleet"); + const metrics = [ + '
LIVE HOSTS
' + hostOnline + ' / ' + hostTotal + '
MWM or Proxmox node checks
', + '
CPU
' + esc(cpuSummary) + '
' + cores + ' logical cores across live hosts
', + '
TOTAL RAM
' + esc(dBytes(ramTotal)) + '
Installed memory across live hosts
', + '
GPU / VRAM
' + (gpuCount ? gpuCount + " GPUs" : "No GPU telemetry") + '
' + (totalVram ? esc(dBytes(totalVram)) + " VRAM reported" : "VRAM totals unavailable") + '
', + '
PVE GUESTS
' + (guests.length ? guestUp + " / " + guests.length : "Unavailable") + '
Cluster total counted once
', + '
NETWORK
' + netLive + ' / ' + network.length + '
Firewall, access point and Arris modem live checks
' + ].join(""); + $("#page").innerHTML = '
REAL DEVICE SNAPSHOT · UPDATED ' + esc(now) + '

All devices

Hardware and live status from MWM agents, Proxmox, OPNsense, TP-Link and ARRIS G36. Each value is labeled by its source.

' + offlineCount + ' offline / attention
' + + '
' + metrics + '
' + + dSection("Managed hosts and network equipment", "CPU utilization, load averages, cores, RAM, VRAM, disks, physical-drive reporting, uptime, firewall counters and device reachability.", primary) + + dSection("Other LAN devices", "Devices without an MWM agent are included from inventory. DHCP records are labeled last-seen and are not treated as live checks.", inventory.concat(liveLeases).map(dInventoryCard)) + + '
Snapshot time: ' + esc(DEVICE_VIEW.updated ? new Date(DEVICE_VIEW.updated).toLocaleString() : "Unavailable") + '. CPU usage is sampled briefly by MWM; load average, RAM, VRAM and disk readings come from each source. Missing fields are shown as unavailable rather than estimated.
'; + $$("[data-go]").forEach((b) => b.onclick = () => go(b.dataset.go)); + $$("[data-device-target]").forEach((b) => b.onclick = () => switchTo(b.dataset.deviceTarget)); +} +async function deviceSource(cmd, valid) { + const local = await deviceTry(() => invoke(cmd)); + if (valid(local)) return local; + const ordered = DEVICE_VIEW.connections.slice().sort((a, b) => Number(deviceHost(b.url) === "192.168.0.6") - Number(deviceHost(a.url) === "192.168.0.6")); + for (const c of ordered) { + const v = await deviceTry(() => localInvoke("remote_call", { id: c.id, cmd, args: {} })); + if (valid(v)) return v; + } + return local; +} +VIEWS.topology = async function () { + $("#top-actions").innerHTML = ''; + $("#page").innerHTML = loading("Reading host, Proxmox, firewall and router metrics…"); + const [local, localSrv, connections] = await Promise.all([ + deviceTry(() => localInvoke("system_info")), + deviceTry(() => localInvoke("server_info")), + deviceTry(() => localInvoke("conn_list")) + ]); + DEVICE_VIEW.local = local || S.info || {}; + DEVICE_VIEW.localSrv = localSrv || {}; + DEVICE_VIEW.connections = Array.isArray(connections) ? connections : []; + DEVICE_VIEW.remotes = await Promise.all(DEVICE_VIEW.connections.map(async (connection) => { + const start = Date.now(); + const [info, srv] = await Promise.all([ + deviceTry(() => localInvoke("remote_call", { id: connection.id, cmd: "system_info", args: {} })), + deviceTry(() => localInvoke("remote_call", { id: connection.id, cmd: "server_info", args: {} })) + ]); + return { connection, info, srv, online: !!info, ms: Date.now() - start }; + })); + const [network, map] = await Promise.all([ + deviceSource("appliance_status", (v) => Array.isArray(v?.devices)), + deviceSource("device_map", (v) => deviceRows(v).length > 0) + ]); + DEVICE_VIEW.network = network; + DEVICE_VIEW.map = deviceRows(map); + DEVICE_VIEW.updated = new Date().toISOString(); + if (current === "topology") drawDeviceTopology(); +}; \ No newline at end of file diff --git a/app/ui/index.html b/app/ui/index.html index ae71648..3dc37e0 100644 --- a/app/ui/index.html +++ b/app/ui/index.html @@ -51,6 +51,8 @@

+ + diff --git a/app/ui/plugins.js b/app/ui/plugins.js index 3ecd23b..d225771 100644 --- a/app/ui/plugins.js +++ b/app/ui/plugins.js @@ -1,25 +1,32 @@ /* Service plugins discovered across connected Proxmox hosts. */ "use strict"; -const PLUG = { rows: [], error: "", mcp: null, mcpSource: "", mcpHost: "", hosts: 0 }; +const PLUG = { rows: [], error: "", mcp: null, mcpSource: "", mcpHost: "", pveMcp: null, pveMcpSource: "", pveMcpHost: "", hosts: 0 }; const arrMcpInvoke = (cmd, args = {}) => PLUG.mcpSource === TARGET ? invoke(cmd, args) : localInvoke("remote_call", { id: PLUG.mcpSource, cmd, args }); +const pveMcpInvoke = (cmd, args = {}) => PLUG.pveMcpSource === TARGET + ? invoke(cmd, args) + : localInvoke("remote_call", { id: PLUG.pveMcpSource, cmd, args }); + VIEWS.plugins = async function () { $("#top-actions").innerHTML = ''; $("#plug-refresh").onclick = () => VIEWS.plugins(); $("#page").innerHTML = loading("Discovering services across connected Proxmox nodes..."); const connections = arr(await localInvoke("conn_list").catch(() => [])); const sources = [{ id: "", name: "This machine" }, ...connections]; - const [results, bridges] = await Promise.all([ + const [results, bridges, pveBridges] = await Promise.all([ Promise.allSettled(sources.map((source) => source.id ? localInvoke("remote_call", { id: source.id, cmd: "plugins_list", args: {} }) : localInvoke("plugins_list"))), Promise.allSettled(sources.map((source) => source.id ? localInvoke("remote_call", { id: source.id, cmd: "arr_mcp_status", args: {} }) : localInvoke("arr_mcp_status"))), + Promise.allSettled(sources.map((source) => source.id + ? localInvoke("remote_call", { id: source.id, cmd: "pve_mcp_status", args: {} }) + : localInvoke("pve_mcp_status"))), ]); const seen = new Set(), errors = []; PLUG.rows = []; @@ -42,6 +49,11 @@ VIEWS.plugins = async function () { PLUG.mcpSource = sources[chosen].id; PLUG.mcpHost = sources[chosen].name; PLUG.mcp = bridges[chosen].status === "fulfilled" ? bridges[chosen].value : { configured: false, reachable: false, error: String(bridges[chosen].reason) }; + const pveAvailable = pveBridges.findIndex((result) => result.status === "fulfilled" && result.value?.reachable); + const pveChosen = pveAvailable >= 0 ? pveAvailable : selected; + PLUG.pveMcpSource = sources[pveChosen].id; + PLUG.pveMcpHost = sources[pveChosen].name; + PLUG.pveMcp = pveBridges[pveChosen].status === "fulfilled" ? pveBridges[pveChosen].value : { configured: false, reachable: false, error: String(pveBridges[pveChosen].reason) }; if (current === "plugins") drawPlugins(); }; @@ -52,9 +64,11 @@ function drawPlugins() { ${rows.map((r, i) => `${esc(r.label)}${esc(r.vmid)} · ${esc(r.node)}${statePill(r.state)}${r.info?.auth_required ? 'login required' : r.info?.reachable ? 'reachable' : `${r.state === "stopped" ? "off" : "unreachable"}`}${r.info?.health ?? "—"}${r.info?.queue ?? "—"}${esc(r.info?.version || "")}`).join("")}
` : `

No supported services found

Connect the owning Proxmox nodes in Machines, then refresh.${PLUG.error ? `

${esc(PLUG.error)}

` : ""}
`} ${rows.some((r) => r.info?.error) ? `

API details

${rows.filter((r) => r.info?.error).map((r) => `
${esc(r.label)}: ${esc(r.info.error)}
`).join("")}
` : ""}`; - $("#page").insertAdjacentHTML("beforeend", drawArrBridge()); + $("#page").insertAdjacentHTML("beforeend", drawArrBridge() + drawPveMcpBridge()); $("#arr-mcp-connect").onclick = connectArrBridge; $("#arr-mcp-tools").onclick = showArrTools; + $("#pve-mcp-connect").onclick = connectPveMcp; + $("#pve-mcp-tools").onclick = showPveMcpTools; $$("[data-plugin]").forEach((tr) => { tr.onclick = () => pluginDetails(PLUG.rows[+tr.dataset.plugin]); tr.onkeydown = (e) => { if (e.key === "Enter") pluginDetails(PLUG.rows[+tr.dataset.plugin]); }; @@ -101,6 +115,60 @@ function runArrTool(tool) { }; } + +function drawPveMcpBridge() { + const s = PLUG.pveMcp || {}; + return '

Proxmox MCP

ry-ops server
' + + '

Browse upstream Proxmox API tools through the selected MWM host. Keep the MCP endpoint on that host loopback; MWM carries the authenticated remote connection.

' + + '
' + (s.reachable ? "connected · " + (s.read_only_count ?? 0) + " read-only tools" : s.configured ? "offline" : "not connected") + 'via ' + esc(PLUG.pveMcpHost) + '' + esc(s.url || "127.0.0.1:8811/mcp") + '
' + + (s.error ? '

' + esc(s.error) + '

' : '') + + '
'; +} + +async function connectPveMcp() { + const url = await ask("Connect Proxmox MCP", "Loopback Streamable HTTP endpoint on the selected MWM host", PLUG.pveMcp?.url || "http://127.0.0.1:8811/mcp", "Connect", "Start proxmox-mcp-server-http on that host, bound to 127.0.0.1. MWM rejects non-loopback addresses."); + if (!url) return; + await guard(async () => { await pveMcpInvoke("pve_mcp_configure", { url }); toast("Proxmox MCP connected."); await VIEWS.plugins(); }); +} + +async function showPveMcpTools() { + await guard(async () => { + const tools = arr(await pveMcpInvoke("pve_mcp_tools")); + const cards = tools.map((t, i) => '').join(""); + modal('

Proxmox MCP tools

' + tools.length + ' upstream tools on ' + esc(PLUG.pveMcpHost) + '. MWM routes reads and writes separately; writes require confirmation and remain limited by the upstream server role.

' + cards + '
'); + $$("[data-pve-mcp-tool]").forEach((b) => b.onclick = () => runPveMcpTool(tools[+b.dataset.pveMcpTool])); + }); +} + +function runPveMcpTool(tool) { + const readOnly = tool.annotations?.readOnlyHint === true; + const destructive = tool.annotations?.destructiveHint === true; + modal('

' + esc(tool.name) + '

' + esc(tool.description || "") + '

Arguments expected by this tool
' + esc(JSON.stringify(tool.inputSchema || {}, null, 2)) + '

Arguments (JSON object)

'); + $("#pve-mcp-cancel").onclick = closeModal; + $("#pve-mcp-run").onclick = async () => { + let args; + try { + args = JSON.parse($("#pve-mcp-args").value); + if (!args || Array.isArray(args) || typeof args !== "object") throw Error("Enter a JSON object"); + } catch (e) { toast("Invalid arguments: " + e.message, true); return; } + if (!readOnly) { + const note = "

" + esc(tool.name) + " can change your cluster." + + (destructive ? " It may stop, delete, wipe, roll back, or run commands inside a guest." : "") + + " Review the arguments and upstream role before continuing.

" + esc(JSON.stringify(args, null, 2)) + "
"; + const action = await choose(destructive ? "Run destructive Proxmox tool?" : "Run Proxmox write tool?", note, [["yes", "Run tool", destructive ? "danger" : "primary"]]); + if (!action) return; + } + closeModal(); + await guard(async () => { + const cmd = readOnly ? "pve_mcp_call_read" : "pve_mcp_call_write"; + const result = await pveMcpInvoke(cmd, { name: tool.name, args }); + modal('

' + esc(tool.name) + ' result

' + esc(JSON.stringify(result, null, 2)) + '
'); + }); + }; +} + function pluginOpen(r) { if (!r.url) return; if (TAURI) invoke("open_default", { path: r.url }); diff --git a/crates/mwm-core/src/api.rs b/crates/mwm-core/src/api.rs index cdfbfdb..b3d23de 100644 --- a/crates/mwm-core/src/api.rs +++ b/crates/mwm-core/src/api.rs @@ -1,121 +1,121 @@ -//! One command table for every front end: the desktop app (Tauri `invoke`) -//! and `mwm serve` (HTTP) both call `call(cmd, args)`. Argument names are the -//! camelCase keys the UI sends. - -use std::path::PathBuf; - -use serde::de::DeserializeOwned; -use serde_json::{json, Value}; - -use crate::{apps, cleaner, disk, drivers, dupes, files, jobs, keys, procs, remote, server, shred, startup, sys, toolkit, updater}; - -fn arg(a: &Value, k: &str) -> Result { - serde_json::from_value(a.get(k).cloned().unwrap_or(Value::Null)).map_err(|e| format!("argument `{k}`: {e}")) -} - -fn ok(v: T) -> Result { - serde_json::to_value(v).map_err(|e| e.to_string()) -} - -fn e(r: anyhow::Result) -> Result { - r.map_err(|x| x.to_string()).and_then(ok) -} - -/// Commands that change the machine. `mwm serve --read-only` refuses them. -pub fn is_mutating(cmd: &str) -> bool { - matches!( - cmd, - "cleaner_clean" | "app_uninstall" | "leftovers_remove" | "startup_set" | "service_mode" | "update_apply" | "dupes_remove" - | "shred_paths" | "wipe_free" | "procs_kill" | "files_mkdir" | "files_rename" | "files_transfer" | "files_delete" - | "files_pack" | "files_unpack" | "files_multi_rename" | "files_write" | "toolkit_run" | "server_action" +//! One command table for every front end: the desktop app (Tauri `invoke`) +//! and `mwm serve` (HTTP) both call `call(cmd, args)`. Argument names are the +//! camelCase keys the UI sends. + +use std::path::PathBuf; + +use serde::de::DeserializeOwned; +use serde_json::{json, Value}; + +use crate::{apps, cleaner, disk, drivers, dupes, files, jobs, keys, procs, remote, server, shred, startup, sys, toolkit, updater}; + +fn arg(a: &Value, k: &str) -> Result { + serde_json::from_value(a.get(k).cloned().unwrap_or(Value::Null)).map_err(|e| format!("argument `{k}`: {e}")) +} + +fn ok(v: T) -> Result { + serde_json::to_value(v).map_err(|e| e.to_string()) +} + +fn e(r: anyhow::Result) -> Result { + r.map_err(|x| x.to_string()).and_then(ok) +} + +/// Commands that change the machine. `mwm serve --read-only` refuses them. +pub fn is_mutating(cmd: &str) -> bool { + matches!( + cmd, + "appliance_action" | "media_app_scan" | "media_app_update" | "cleaner_clean" | "app_uninstall" | "leftovers_remove" | "startup_set" | "service_mode" | "update_apply" | "dupes_remove" + | "shred_paths" | "wipe_free" | "procs_kill" | "files_mkdir" | "files_rename" | "files_transfer" | "files_delete" + | "files_pack" | "files_unpack" | "files_multi_rename" | "files_write" | "toolkit_run" | "server_action" | "conn_save" | "conn_remove" | "guest_docker_action" | "deploy_node" | "pve_op" | "pve_create_lxc" | "lab_quarantine" | "lab_quarantine_restore" | "lab_quarantine_delete" | "arkana_configure" | "arkana_connect_lxc" | "arkana_install" | "arkana_control" | "arkana_tool" | "arkana_analyze" - | "arr_mcp_configure" | "arr_mcp_call" + | "arr_mcp_configure" | "arr_mcp_call" | "pve_mcp_configure" | "pve_mcp_call_write" | "hestia_action" | "hestia_dns_add" | "hestia_dns_delete" | "rescue_fetch" | "integrity_baseline" | "integrity_verify" | "explorer_takeover_set" | "lxc_fs_write" | "lxc_fs_mkdir" | "lxc_fs_delete" | "lxc_updates_policy_set" | "lxc_updates_scan" | "lxc_updates_apply" | "pve_updates_policy_set" | "pve_updates_scan" | "pve_updates_apply" | "docker_updates_policy_set" | "docker_updates_scan" | "docker_updates_apply" | "vault_store" - | "offload_policy_set" | "offload_run" | "offload_guard_now" - ) -} - -/// Like `is_mutating`, but looks inside `remote_call` at the proxied command. -pub fn is_mutating_call(cmd: &str, args: &Value) -> bool { - if cmd == "remote_call" { - return args.get("cmd").and_then(|c| c.as_str()).map(is_mutating).unwrap_or(true); - } - is_mutating(cmd) -} - -pub fn call(cmd: &str, a: &Value) -> Result { - match cmd { - "system_info" => ok(sys::info()), - "cleaner_scan" => ok(cleaner::scan_all()), - "cleaner_clean" => ok(cleaner::clean(&arg::>(a, "ids")?)), - "apps_list" => ok(apps::list(arg::>(a, "store")?.unwrap_or(false))), - "app_uninstall" => ok(apps::uninstall(&arg(a, "app")?, arg::>(a, "quiet")?.unwrap_or(false))), - "app_leftovers" => ok(apps::leftovers(&arg(a, "app")?)), - "leftovers_remove" => ok(apps::remove_leftovers(&arg::>(a, "items")?)), - "startup_list" => ok(startup::list()), - "startup_set" => ok(startup::set_enabled(&arg::(a, "id")?, arg(a, "enabled")?)), - "service_mode" => ok(startup::set_service_mode(&arg::(a, "name")?, &arg::(a, "mode")?)), - "updates_list" => e(updater::list()), - "update_apply" => ok(updater::apply(&arg::(a, "id")?)), - "dupes_find" => { - let roots: Vec = arg::>(a, "roots")?.into_iter().map(PathBuf::from).collect(); - ok(dupes::find(&roots, arg::>(a, "minSize")?.unwrap_or(1), false)) - } - "dupes_remove" => { - let (removed, failed) = dupes::remove(&arg::>(a, "paths")?); - ok(json!({ "removed": removed, "failed": failed })) - } - "disk_analyze" => ok(disk::analyze(&PathBuf::from(arg::(a, "root")?), 60)), - "shred_paths" => ok(shred::shred(&arg::>(a, "paths")?, arg::>(a, "passes")?.unwrap_or(1))), - "wipe_free" => e(shred::wipe_free_space(&arg::(a, "dir")?)), - "drivers_list" => ok(drivers::list()), - "procs_list" => ok(procs::list()), - "procs_kill" => ok(procs::kill(&arg::>(a, "pids")?)), - "reveal" => e(sys::reveal(&arg::(a, "path")?)), - "launch_tool" => e(sys::launch_tool(&arg::(a, "tool")?)), - // Commander - "files_roots" => ok(files::roots()), - "files_list" => e(files::list(&arg::(a, "dir")?)), - "files_mkdir" => e(files::mkdir(&arg::(a, "parent")?, &arg::(a, "name")?)), - "files_rename" => e(files::rename(&arg::(a, "path")?, &arg::(a, "name")?)), - "files_conflicts" => ok(files::conflicts(&arg::>(a, "sources")?, &arg::(a, "dest")?)), - "files_transfer" => ok(files::transfer(arg(a, "sources")?, arg(a, "dest")?, arg::>(a, "mode")?.unwrap_or_else(|| "skip".into()), arg::>(a, "isMove")?.unwrap_or(false))), - "files_delete" => ok(files::delete(arg(a, "paths")?, arg::>(a, "permanent")?.unwrap_or(false))), - "files_pack" => ok(files::pack(arg(a, "sources")?, arg(a, "archive")?)), - "files_unpack" => ok(files::unpack(arg(a, "archive")?, arg(a, "dest")?)), - "files_search" => ok(files::search(arg(a, "root")?, arg::>(a, "pattern")?.unwrap_or_default(), arg::>(a, "text")?.unwrap_or_default())), - "files_preview" => e(files::preview(&arg::(a, "path")?)), - "files_props" => e(files::properties(&arg::(a, "path")?)), - "files_dir_sizes" => ok(files::dir_sizes(&arg::>(a, "paths")?)), - "files_multi_rename" => e(files::multi_rename(&arg::>(a, "plan")?)), - "files_write" => e(files::write_text(&arg::(a, "path")?, &arg::(a, "text")?)), - "open_default" => e(sys::open_default(&arg::(a, "path")?)), - "edit_file" => e(sys::edit(&arg::(a, "path")?)), - "terminal" => e(sys::terminal(&arg::(a, "dir")?)), - // Jobs - "jobs_list" => ok(jobs::list()), - "job_cancel" => { - jobs::cancel(arg(a, "id")?); - ok(true) - } - "jobs_clear" => { - jobs::clear_finished(); - ok(true) - } - // Toolkit - "toolkit_tasks" => ok(toolkit::TASKS.to_vec()), - "toolkit_run" => e(toolkit::run_task(&arg::(a, "id")?)), - "toolkit_report" => ok(toolkit::report()), - "toolkit_security" => ok(toolkit::security()), - "toolkit_events" => ok(toolkit::events()), - "toolkit_network" => ok(toolkit::network()), - "toolkit_wifi" => ok(toolkit::wifi()), + | "offload_policy_set" | "offload_run" | "offload_guard_now" + ) +} + +/// Like `is_mutating`, but looks inside `remote_call` at the proxied command. +pub fn is_mutating_call(cmd: &str, args: &Value) -> bool { + if cmd == "remote_call" { + return args.get("cmd").and_then(|c| c.as_str()).map(is_mutating).unwrap_or(true); + } + is_mutating(cmd) +} + +pub fn call(cmd: &str, a: &Value) -> Result { + match cmd { + "system_info" => ok(sys::info()), + "cleaner_scan" => ok(cleaner::scan_all()), + "cleaner_clean" => ok(cleaner::clean(&arg::>(a, "ids")?)), + "apps_list" => ok(apps::list(arg::>(a, "store")?.unwrap_or(false))), + "app_uninstall" => ok(apps::uninstall(&arg(a, "app")?, arg::>(a, "quiet")?.unwrap_or(false))), + "app_leftovers" => ok(apps::leftovers(&arg(a, "app")?)), + "leftovers_remove" => ok(apps::remove_leftovers(&arg::>(a, "items")?)), + "startup_list" => ok(startup::list()), + "startup_set" => ok(startup::set_enabled(&arg::(a, "id")?, arg(a, "enabled")?)), + "service_mode" => ok(startup::set_service_mode(&arg::(a, "name")?, &arg::(a, "mode")?)), + "updates_list" => e(updater::list()), + "update_apply" => ok(updater::apply(&arg::(a, "id")?)), + "dupes_find" => { + let roots: Vec = arg::>(a, "roots")?.into_iter().map(PathBuf::from).collect(); + ok(dupes::find(&roots, arg::>(a, "minSize")?.unwrap_or(1), false)) + } + "dupes_remove" => { + let (removed, failed) = dupes::remove(&arg::>(a, "paths")?); + ok(json!({ "removed": removed, "failed": failed })) + } + "disk_analyze" => ok(disk::analyze(&PathBuf::from(arg::(a, "root")?), 60)), + "shred_paths" => ok(shred::shred(&arg::>(a, "paths")?, arg::>(a, "passes")?.unwrap_or(1))), + "wipe_free" => e(shred::wipe_free_space(&arg::(a, "dir")?)), + "drivers_list" => ok(drivers::list()), + "procs_list" => ok(procs::list()), + "procs_kill" => ok(procs::kill(&arg::>(a, "pids")?)), + "reveal" => e(sys::reveal(&arg::(a, "path")?)), + "launch_tool" => e(sys::launch_tool(&arg::(a, "tool")?)), + // Commander + "files_roots" => ok(files::roots()), + "files_list" => e(files::list(&arg::(a, "dir")?)), + "files_mkdir" => e(files::mkdir(&arg::(a, "parent")?, &arg::(a, "name")?)), + "files_rename" => e(files::rename(&arg::(a, "path")?, &arg::(a, "name")?)), + "files_conflicts" => ok(files::conflicts(&arg::>(a, "sources")?, &arg::(a, "dest")?)), + "files_transfer" => ok(files::transfer(arg(a, "sources")?, arg(a, "dest")?, arg::>(a, "mode")?.unwrap_or_else(|| "skip".into()), arg::>(a, "isMove")?.unwrap_or(false))), + "files_delete" => ok(files::delete(arg(a, "paths")?, arg::>(a, "permanent")?.unwrap_or(false))), + "files_pack" => ok(files::pack(arg(a, "sources")?, arg(a, "archive")?)), + "files_unpack" => ok(files::unpack(arg(a, "archive")?, arg(a, "dest")?)), + "files_search" => ok(files::search(arg(a, "root")?, arg::>(a, "pattern")?.unwrap_or_default(), arg::>(a, "text")?.unwrap_or_default())), + "files_preview" => e(files::preview(&arg::(a, "path")?)), + "files_props" => e(files::properties(&arg::(a, "path")?)), + "files_dir_sizes" => ok(files::dir_sizes(&arg::>(a, "paths")?)), + "files_multi_rename" => e(files::multi_rename(&arg::>(a, "plan")?)), + "files_write" => e(files::write_text(&arg::(a, "path")?, &arg::(a, "text")?)), + "open_default" => e(sys::open_default(&arg::(a, "path")?)), + "edit_file" => e(sys::edit(&arg::(a, "path")?)), + "terminal" => e(sys::terminal(&arg::(a, "dir")?)), + // Jobs + "jobs_list" => ok(jobs::list()), + "job_cancel" => { + jobs::cancel(arg(a, "id")?); + ok(true) + } + "jobs_clear" => { + jobs::clear_finished(); + ok(true) + } + // Toolkit + "toolkit_tasks" => ok(toolkit::TASKS.to_vec()), + "toolkit_run" => e(toolkit::run_task(&arg::(a, "id")?)), + "toolkit_report" => ok(toolkit::report()), + "toolkit_security" => ok(toolkit::security()), + "toolkit_events" => ok(toolkit::events()), + "toolkit_network" => ok(toolkit::network()), + "toolkit_wifi" => ok(toolkit::wifi()), "keys_list" => ok(keys::list()), "vault_load" => e(crate::vault::load()), "vault_store" => e(crate::vault::store(&arg::(a, "expectedRevision")?, a.get("blob").ok_or("missing encrypted vault blob")?)), @@ -136,11 +136,33 @@ pub fn call(cmd: &str, a: &Value) -> Result { "arkana_analyze" => e(crate::arkana::analyze(&arg::(a, "path")?)), "plugins_list" => e(crate::plugins::list()), "app_latest_release" => e(crate::release::latest()), + "appliance_status" => e(crate::appliances::status()), + "device_map" => { + let path = crate::util::data_dir().join("device-map.json"); + let value = std::fs::read(&path).ok().and_then(|b| serde_json::from_slice::(&b).ok()).unwrap_or_else(|| json!({"devices": []})); + let rows = value.get("devices").and_then(Value::as_array).ok_or("device map must contain a devices array")?; + let allowed = ["id", "name", "kind", "icon", "role", "address", "state", "detail", "go", "action"]; + let devices = rows.iter().map(|row| { + let mut clean = serde_json::Map::new(); + for key in allowed { if let Some(value) = row.get(key) { clean.insert(key.into(), value.clone()); } } + Value::Object(clean) + }).collect::>(); + Ok(json!({"devices": devices})) + }, + "appliance_action" => e(crate::appliances::action(&arg::(a, "action")?, &arg::>(a, "service")?.unwrap_or_default())), + "media_app_report" => e(crate::appliances::media_report()), + "media_app_scan" => e(crate::appliances::media_job("scan", "")), + "media_app_update" => e(crate::appliances::media_job("update", &arg::(a, "vmid")?)), "fleet_inventory" => e(crate::fleet_inventory::read()), "arr_mcp_status" => ok(crate::mcp_arr::status()), "arr_mcp_configure" => e(crate::mcp_arr::configure(&arg::(a, "url")?)), "arr_mcp_tools" => e(crate::mcp_arr::tools()), "arr_mcp_call" => e(crate::mcp_arr::call(&arg::(a, "name")?, a.get("args").unwrap_or(&Value::Null))), + "pve_mcp_status" => ok(crate::mcp_proxmox::status()), + "pve_mcp_configure" => e(crate::mcp_proxmox::configure(&arg::(a, "url")?)), + "pve_mcp_tools" => e(crate::mcp_proxmox::tools()), + "pve_mcp_call_read" => e(crate::mcp_proxmox::call(&arg::(a, "name")?, a.get("args").unwrap_or(&Value::Null), false)), + "pve_mcp_call_write" => e(crate::mcp_proxmox::call(&arg::(a, "name")?, a.get("args").unwrap_or(&Value::Null), true)), // HestiaCP hosting (via the hosting LXC) "hestia_users" => e(crate::hestia::users()), "hestia_domains" => e(crate::hestia::domains()), @@ -160,11 +182,11 @@ pub fn call(cmd: &str, a: &Value) -> Result { "explorer_takeover_status" => e(crate::explorer::status()), "explorer_takeover_set" => e(crate::explorer::set_takeover(arg::(a, "enabled")?)), "pending_open_dir" => ok(crate::sys::take_pending_dir().unwrap_or_default()), - // Servers (Proxmox / Unraid / ZFS / Docker / SMART) - "server_info" => e(server::info_on(&arg::>(a, "node")?.unwrap_or_default())), + // Servers (Proxmox / Unraid / ZFS / Docker / SMART) + "server_info" => e(server::info_on(&arg::>(a, "node")?.unwrap_or_default())), "pve_overview" => e(crate::pve::overview()), "pve_provision_options" => e(crate::pve::provision_options()), - "pve_create_lxc" => e(crate::pve::create_lxc(a.get("params").unwrap_or(&Value::Null))), + "pve_create_lxc" => e(crate::pve::create_lxc(a.get("params").unwrap_or(&Value::Null))), "lxc_updates_report" => e(crate::lxc_updates::report()), "lxc_updates_policy" => e(crate::lxc_updates::policy()), "lxc_updates_policy_set" => e(crate::lxc_updates::set_policy(&arg::>(a, "ids")?)), @@ -180,39 +202,39 @@ pub fn call(cmd: &str, a: &Value) -> Result { "docker_updates_policy_set" => e(crate::docker_updates::set_policy(&arg::>(a, "items")?)), "docker_updates_scan" => e(crate::docker_updates::scan()), "docker_updates_apply" => e(crate::docker_updates::apply(&arg::(a, "node")?, &arg::(a, "vmid")?, &arg::(a, "project")?)), - "pve_guest" => e(crate::pve::guest(&arg::(a, "node")?, &arg::(a, "kind")?, &arg::(a, "vmid")?)), - "pve_op" => e(crate::pve::guest_op(&arg::(a, "node")?, &arg::(a, "kind")?, &arg::(a, "vmid")?, &arg::(a, "op")?, a.get("params").unwrap_or(&Value::Null))), + "pve_guest" => e(crate::pve::guest(&arg::(a, "node")?, &arg::(a, "kind")?, &arg::(a, "vmid")?)), + "pve_op" => e(crate::pve::guest_op(&arg::(a, "node")?, &arg::(a, "kind")?, &arg::(a, "vmid")?, &arg::(a, "op")?, a.get("params").unwrap_or(&Value::Null))), "pve_task_log" => e(crate::pve::task_log(&arg::(a, "node")?, &arg::(a, "upid")?)), "lxc_fs_list" => e(crate::lxc_fs::list(&arg::(a, "node")?, &arg::(a, "vmid")?, &arg::(a, "dir")?)), "lxc_fs_read" => e(crate::lxc_fs::read(&arg::(a, "node")?, &arg::(a, "vmid")?, &arg::(a, "path")?)), "lxc_fs_write" => e(crate::lxc_fs::write(&arg::(a, "node")?, &arg::(a, "vmid")?, &arg::(a, "path")?, &arg::(a, "data")?)), "lxc_fs_mkdir" => e(crate::lxc_fs::mkdir(&arg::(a, "node")?, &arg::(a, "vmid")?, &arg::(a, "path")?)), "lxc_fs_delete" => e(crate::lxc_fs::delete(&arg::(a, "node")?, &arg::(a, "vmid")?, &arg::(a, "path")?)), - "deploy_node" => e(server::deploy_node(&arg::(a, "node")?)), - "server_action" => e(server::action(&arg::(a, "action")?, &arg::>(a, "target")?.unwrap_or_default())), - "guest_docker" => e(server::guest_docker(&arg::(a, "node")?, &arg::(a, "vmid")?)), - "guest_docker_action" => e(server::guest_docker_action(&arg::(a, "node")?, &arg::(a, "vmid")?, &arg::(a, "action")?, &arg::>(a, "target")?.unwrap_or_default())), - "docker_scan_cluster" => ok(server::docker_scan_cluster()), - // This machine's own server (desktop "Remote access" switch). - "remote_access_status" => ok(crate::web::ra_status()), - "remote_access_start" => e(crate::web::ra_start(&arg::>(a, "bind")?.unwrap_or_else(|| "0.0.0.0:7777".into()), arg::>(a, "readOnly")?.unwrap_or(false))), - "remote_access_stop" => e(crate::web::ra_stop()), - "remote_access_new_token" => ok(crate::web::ra_new_token()), - // Other machines - "conn_list" => ok(remote::list()), - "conn_save" => e(remote::save(arg(a, "id")?, &arg::(a, "name")?, &arg::(a, "url")?, &arg::>(a, "token")?.unwrap_or_default())), - "conn_remove" => e(remote::remove(&arg::(a, "id")?)), - // Move Weight: heavy folders to your own server, and keep them off. - "offload_status" => ok(crate::offload::status()), - "offload_policy_set" => e(crate::offload::set_policy(&arg::(a, "policy")?)), - "offload_server_check" => ok(crate::offload::server_check()), - "offload_scan" => ok(crate::offload::scan_job()), - "offload_run" => ok(crate::offload::run_job(arg::>(a, "paths")?)), - "offload_guard_now" => { - std::thread::spawn(crate::offload::guard_run); - ok(true) - } - "remote_call" => remote::call(&arg::(a, "id")?, &arg::(a, "cmd")?, a.get("args").unwrap_or(&Value::Null)), - other => Err(format!("unknown command `{other}`")), - } -} + "deploy_node" => e(server::deploy_node(&arg::(a, "node")?)), + "server_action" => e(server::action(&arg::(a, "action")?, &arg::>(a, "target")?.unwrap_or_default())), + "guest_docker" => e(server::guest_docker(&arg::(a, "node")?, &arg::(a, "vmid")?)), + "guest_docker_action" => e(server::guest_docker_action(&arg::(a, "node")?, &arg::(a, "vmid")?, &arg::(a, "action")?, &arg::>(a, "target")?.unwrap_or_default())), + "docker_scan_cluster" => ok(server::docker_scan_cluster()), + // This machine's own server (desktop "Remote access" switch). + "remote_access_status" => ok(crate::web::ra_status()), + "remote_access_start" => e(crate::web::ra_start(&arg::>(a, "bind")?.unwrap_or_else(|| "0.0.0.0:7777".into()), arg::>(a, "readOnly")?.unwrap_or(false))), + "remote_access_stop" => e(crate::web::ra_stop()), + "remote_access_new_token" => ok(crate::web::ra_new_token()), + // Other machines + "conn_list" => ok(remote::list()), + "conn_save" => e(remote::save(arg(a, "id")?, &arg::(a, "name")?, &arg::(a, "url")?, &arg::>(a, "token")?.unwrap_or_default())), + "conn_remove" => e(remote::remove(&arg::(a, "id")?)), + // Move Weight: heavy folders to your own server, and keep them off. + "offload_status" => ok(crate::offload::status()), + "offload_policy_set" => e(crate::offload::set_policy(&arg::(a, "policy")?)), + "offload_server_check" => ok(crate::offload::server_check()), + "offload_scan" => ok(crate::offload::scan_job()), + "offload_run" => ok(crate::offload::run_job(arg::>(a, "paths")?)), + "offload_guard_now" => { + std::thread::spawn(crate::offload::guard_run); + ok(true) + } + "remote_call" => remote::call(&arg::(a, "id")?, &arg::(a, "cmd")?, a.get("args").unwrap_or(&Value::Null)), + other => Err(format!("unknown command `{other}`")), + } +} diff --git a/crates/mwm-core/src/appliances.rs b/crates/mwm-core/src/appliances.rs new file mode 100644 index 0000000..d64348e --- /dev/null +++ b/crates/mwm-core/src/appliances.rs @@ -0,0 +1,33 @@ +//! Appliance adapters and application-only update jobs. Credentials stay in root-owned helper configuration. +use anyhow::{bail, Context, Result}; +use serde_json::{json, Value}; +use crate::{jobs, util}; +const NETWORK: &str = "/usr/local/libexec/mwm-network-devices"; +const MEDIA: &str = "/usr/local/libexec/mwm-media-apps"; +fn capture(script: &str, args: &[&str]) -> Result { + if !std::path::Path::new(script).exists() { bail!("Fleet adapter is not installed on this machine; select the fleet controller"); } + let mut command=vec![script]; command.extend_from_slice(args); + let (code,out)=util::run_capture("python3",&command)?; + if code!=0 { bail!("{}",out.trim()); } + serde_json::from_str(out.trim()).context("Invalid fleet adapter response") +} +pub fn status() -> Result { capture(NETWORK,&["status"]) } +pub fn action(action: &str, service: &str) -> Result { + if !matches!(action,"check_updates"|"restart_service") || !service.bytes().all(|c| c.is_ascii_alphanumeric() || c==b'-') { bail!("Invalid appliance action"); } + let action=action.to_owned(); let service=service.to_owned(); + let id=jobs::start("appliance","OPNsense management","appliances",move |job| { + let r=capture(NETWORK,&[&action,&service])?;job.line(r.to_string());Ok("Appliance action completed".into()) + });Ok(json!({"job":id})) +} +pub fn media_report() -> Result { + let path="/var/lib/mwm/media-apps.json"; + if !std::path::Path::new(path).exists() { return Ok(json!({"generated_at":null,"applications":[],"note":"Run an application scan"})); } + let data=std::fs::read(path)?; if data.len()>4*1024*1024 {bail!("Application report is too large");} Ok(serde_json::from_slice(&data)?) +} +pub fn media_job(action: &str, vmid: &str) -> Result { + if !matches!(action,"scan"|"update") || (action=="update" && (vmid.is_empty() || vmid.len()>9 || !vmid.bytes().all(|c|c.is_ascii_digit()))) {bail!("Invalid application target");} + let action=action.to_owned();let vmid=vmid.to_owned(); + let id=jobs::start("media_app","Media application maintenance","appliances",move |job| { + let r=capture(MEDIA,&[&action,&vmid])?;job.line(r.to_string());Ok("Application maintenance completed; OS packages unchanged".into()) + });Ok(json!({"job":id})) +} diff --git a/crates/mwm-core/src/lib.rs b/crates/mwm-core/src/lib.rs index 036cd73..09f2ba6 100644 --- a/crates/mwm-core/src/lib.rs +++ b/crates/mwm-core/src/lib.rs @@ -5,6 +5,7 @@ //! each module, so the UI never has to care where it is running. pub mod api; +pub mod appliances; pub mod arkana; pub mod apps; pub mod cleaner; @@ -22,6 +23,7 @@ pub mod lxc_updates; pub mod pve_updates; pub mod docker_updates; pub mod mcp_arr; +pub mod mcp_proxmox; pub mod offload; pub mod plugins; pub mod fsutil; diff --git a/crates/mwm-core/src/mcp_proxmox.rs b/crates/mwm-core/src/mcp_proxmox.rs new file mode 100644 index 0000000..a23857d --- /dev/null +++ b/crates/mwm-core/src/mcp_proxmox.rs @@ -0,0 +1,188 @@ +//! Optional bridge to ry-ops/proxmox-mcp-server over loopback Streamable HTTP. +//! The endpoint stays on the Proxmox host; MWM's authenticated remote API is +//! the boundary used by desktop clients. The upstream server owns Proxmox API +//! credentials and enforces its read-only / role policy. + +use std::{path::PathBuf, time::Duration}; + +use anyhow::{bail, Context, Result}; +use serde_json::{json, Value}; + +use crate::util; + +fn file() -> PathBuf { util::data_dir().join("mcp-proxmox.json") } + +fn configured_url() -> String { + std::fs::read_to_string(file()).ok() + .and_then(|s| serde_json::from_str::(&s).ok()) + .and_then(|v| v["url"].as_str().map(str::to_string)) + .unwrap_or_default() +} + +/// The upstream server is intentionally reached only through loopback on this +/// MWM host. This keeps its bearer/API credentials off the LAN. +fn normalize_url(raw: &str) -> Result { + let raw = raw.trim().trim_end_matches('/'); + let raw = raw.strip_prefix("http://").unwrap_or(raw); + if raw.contains("https://") || raw.contains('@') || raw.contains('?') || raw.contains('#') || raw.contains('\\') { + bail!("use a loopback Proxmox MCP address without credentials or query parameters"); + } + let (hostport, path) = raw.split_once('/').unwrap_or((raw, "")); + let (host, port) = if let Some(rest) = hostport.strip_prefix('[') { + let (h, tail) = rest.split_once(']').ok_or_else(|| anyhow::anyhow!("invalid loopback address"))?; + (format!("[{h}]"), tail.strip_prefix(':').unwrap_or("8811")) + } else { + let (h, p) = hostport.split_once(':').unwrap_or((hostport, "8811")); + (h.to_string(), p) + }; + if !matches!(host.as_str(), "127.0.0.1" | "localhost" | "[::1]") || port.parse::().ok().filter(|p| *p > 0).is_none() { + bail!("Proxmox MCP must listen on this MWM host's loopback address (127.0.0.1:8811)"); + } + if !path.is_empty() && path != "mcp" { + bail!("the MCP endpoint path must be /mcp"); + } + Ok(format!("http://{host}:{port}/mcp")) +} + +fn response(body: &str, id: u64) -> Result { + let candidates: Vec<&str> = if body.trim_start().starts_with('{') { + vec![body.trim()] + } else { + body.lines().filter_map(|l| l.strip_prefix("data:")).map(str::trim).collect() + }; + for candidate in candidates.iter().rev() { + if let Ok(v) = serde_json::from_str::(candidate) { + if v["id"].as_u64() == Some(id) { + if let Some(error) = v.get("error") { + bail!("Proxmox MCP: {}", error["message"].as_str().unwrap_or("request failed")); + } + return Ok(v["result"].clone()); + } + } + } + bail!("Proxmox MCP returned no JSON-RPC reply") +} + +struct Client { + agent: ureq::Agent, + url: String, + session: Option, + next: u64, +} + +impl Client { + fn post(&self, message: Value, timeout: u64) -> Result<(String, Option)> { + let mut req = self.agent.post(&self.url) + .timeout(Duration::from_secs(timeout)) + .set("Content-Type", "application/json") + .set("Accept", "application/json, text/event-stream"); + if let Some(session) = &self.session { req = req.set("Mcp-Session-Id", session); } + match req.send_string(&message.to_string()) { + Ok(reply) => { + let session = reply.header("mcp-session-id").map(str::to_string); + Ok((reply.into_string().unwrap_or_default(), session)) + } + Err(ureq::Error::Status(401, _)) => bail!("Proxmox MCP rejected the request; check its local authentication configuration"), + Err(ureq::Error::Status(code, _)) => bail!("Proxmox MCP returned HTTP {code}"), + Err(e) => bail!("cannot reach Proxmox MCP: {e}"), + } + } + + fn connect(url: &str) -> Result { + let mut client = Self { + agent: ureq::AgentBuilder::new().timeout_connect(Duration::from_secs(3)).redirects(0).build(), + url: normalize_url(url)?, session: None, next: 2, + }; + let init = json!({"jsonrpc":"2.0", "id":1, "method":"initialize", "params":{ + "protocolVersion":"2025-03-26", "capabilities":{}, + "clientInfo":{"name":"mwm", "version":crate::VERSION} + }}); + let (body, session) = client.post(init, 10)?; + response(&body, 1)?; + client.session = session; + let _ = client.post(json!({"jsonrpc":"2.0", "method":"notifications/initialized"}), 5); + Ok(client) + } + + fn request(&mut self, method: &str, params: Value) -> Result { + let id = self.next; + self.next += 1; + let (body, _) = self.post(json!({"jsonrpc":"2.0", "id":id, "method":method, "params":params}), 60)?; + response(&body, id) + } +} + +fn client() -> Result { + let url = configured_url(); + if url.is_empty() { bail!("connect the Proxmox MCP server on this machine first"); } + Client::connect(&url) +} + +pub fn status() -> Value { + let url = configured_url(); + if url.is_empty() { return json!({"configured":false,"reachable":false,"url":"","tool_count":0,"error":""}); } + match Client::connect(&url).and_then(|mut c| c.request("tools/list", json!({}))) { + Ok(result) => { + let tools = result["tools"].as_array().cloned().unwrap_or_default(); + let read_only = tools.iter().filter(|t| t["annotations"]["readOnlyHint"] == true).count(); + json!({"configured":true,"reachable":true,"url":url,"tool_count":tools.len(),"read_only_count":read_only,"error":""}) + } + Err(e) => json!({"configured":true,"reachable":false,"url":url,"tool_count":0,"error":e.to_string()}), + } +} + +pub fn configure(raw: &str) -> Result { + let url = normalize_url(raw)?; + let mut c = Client::connect(&url).context("start proxmox-mcp-server-http on this machine, bound to 127.0.0.1")?; + let result = c.request("tools/list", json!({}))?; + if result["tools"].as_array().is_none_or(|tools| tools.is_empty()) { + bail!("Proxmox MCP connected but did not advertise any tools"); + } + let path = file(); + std::fs::write(&path, serde_json::to_vec_pretty(&json!({"url":url}))?)?; + #[cfg(unix)] { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?; + } + Ok(status()) +} + +pub fn tools() -> Result { + let result = client()?.request("tools/list", json!({}))?; + Ok(result["tools"].clone()) +} + +pub fn call(name: &str, args: &Value, write: bool) -> Result { + if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { + bail!("invalid Proxmox MCP tool name"); + } + if !args.is_object() && !args.is_null() { bail!("tool arguments must be an object"); } + let mut client = client()?; + let listed = client.request("tools/list", json!({}))?; + let tool = listed["tools"].as_array() + .and_then(|tools| tools.iter().find(|t| t["name"] == name)) + .ok_or_else(|| anyhow::anyhow!("Proxmox MCP does not advertise tool {name}"))?; + let read_only = tool["annotations"]["readOnlyHint"] == true; + if write && read_only { bail!("{name} is read-only; call it through MWM's read path"); } + if !write && !read_only { bail!("{name} can change Proxmox; call it through the confirmed write path"); } + let result = client.request("tools/call", json!({"name":name, "arguments":if args.is_null() { json!({}) } else { args.clone() }}))?; + if result["isError"] == true { + let message = result["content"].as_array().map(|blocks| blocks.iter() + .filter_map(|v| v["text"].as_str()).collect::>().join("\n")).unwrap_or_default(); + bail!("Proxmox MCP {name}: {}", message.chars().take(500).collect::()); + } + Ok(result) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn loopback_only() { + assert_eq!(normalize_url("127.0.0.1:8811").unwrap(), "http://127.0.0.1:8811/mcp"); + assert_eq!(normalize_url("http://localhost:8811/mcp").unwrap(), "http://localhost:8811/mcp"); + for url in ["http://192.168.0.6:8811/mcp", "https://localhost:8811/mcp", "localhost:0", "localhost:8811/admin", "localhost:8811@evil/mcp"] { + assert!(normalize_url(url).is_err(), "accepted {url}"); + } + } +} diff --git a/crates/mwm-core/src/server.rs b/crates/mwm-core/src/server.rs index bf5b6cf..9b5961b 100644 --- a/crates/mwm-core/src/server.rs +++ b/crates/mwm-core/src/server.rs @@ -285,12 +285,104 @@ fn smart() -> Value { json!(disks) } +fn gpu_inventory() -> Value { + if let Some(out) = run("nvidia-smi", &[ + "--query-gpu=name,utilization.gpu,memory.used,memory.total,temperature.gpu", + "--format=csv,noheader,nounits", + ]) { + let rows: Vec = out.lines().filter_map(|line| { + let f: Vec<&str> = line.split(',').map(str::trim).collect(); + if f.len() < 5 || f[0].is_empty() { return None; } + let mb = |s: &str| s.parse::().ok().map(|n| n * 1024 * 1024); + Some(json!({ + "name": f[0], + "utilization_pct": f[1].parse::().ok(), + "vram_used_bytes": mb(f[2]), + "vram_total_bytes": mb(f[3]), + "temp_c": f[4].parse::().ok(), + })) + }).collect(); + if !rows.is_empty() { return json!(rows); } + } + + #[cfg(windows)] + { + let rows = util::powershell_json( + "Get-CimInstance Win32_VideoController | Select-Object @{Name='name';Expression={$_.Name}},@{Name='vram_total_bytes';Expression={$_.AdapterRAM}} | ConvertTo-Json -Compress" + ).unwrap_or_default(); + let values: Vec = rows.into_iter().filter_map(|r| { + let name = r["name"].as_str()?.trim(); + if name.is_empty() { return None; } + Some(json!({ + "name": name, "utilization_pct": null, "vram_used_bytes": null, + "vram_total_bytes": r["vram_total_bytes"].as_u64(), "temp_c": null, + })) + }).collect(); + if !values.is_empty() { return json!(values); } + } + + #[cfg(target_os = "linux")] + { + let mut values = Vec::new(); + for n in 0..16 { + let base = format!("/sys/class/drm/card{n}/device"); + let Some(vendor) = read(&format!("{base}/vendor")) else { continue }; + let Some(device) = read(&format!("{base}/device")) else { continue }; + let total = read(&format!("{base}/mem_info_vram_total")).and_then(|s| s.trim().parse::().ok()); + let used = read(&format!("{base}/mem_info_vram_used")).and_then(|s| s.trim().parse::().ok()); + let brand = match vendor.trim() { "0x10de" => "NVIDIA", "0x1002" => "AMD", "0x8086" => "Intel", _ => "PCI" }; + values.push(json!({ + "name": format!("{brand} GPU {}", device.trim()), + "utilization_pct": null, "vram_used_bytes": used, + "vram_total_bytes": total, "temp_c": null, + })); + } + if !values.is_empty() { return json!(values); } + } + + #[cfg(target_os = "macos")] + { + if let Some(out) = run("system_profiler", &["SPDisplaysDataType"]) { + let mut values = Vec::new(); + let mut name = String::new(); + for line in out.lines() { + if let Some(v) = line.trim().strip_prefix("Chipset Model:") { + name = v.trim().to_string(); + values.push(json!({ + "name": name, "utilization_pct": null, "vram_used_bytes": null, + "vram_total_bytes": null, "temp_c": null, + })); + } + } + if !values.is_empty() { return json!(values); } + } + } + json!([]) +} + +#[cfg(windows)] +fn windows_physical_drives() -> Value { + let rows = util::powershell_json( + "Get-CimInstance Win32_DiskDrive | Select-Object @{Name='device';Expression={$_.DeviceID}},@{Name='model';Expression={$_.Model}},@{Name='capacity';Expression={$_.Size}},@{Name='status';Expression={$_.Status}},@{Name='interface';Expression={$_.InterfaceType}} | ConvertTo-Json -Compress" + ).unwrap_or_default(); + json!(rows) +} pub fn info() -> Value { + let mut cpu = sysinfo::System::new(); + cpu.refresh_cpu_all(); + std::thread::sleep(std::time::Duration::from_millis(250)); + cpu.refresh_cpu_all(); + let cpu_usage_pct = cpu.global_cpu_usage() as f64; let loadavg = read("/proc/loadavg").map(|s| s.split_whitespace().take(3).collect::>().join(" ")).unwrap_or_default(); let failed: Vec = run("systemctl", &["--failed", "--no-legend", "--plain"]) .map(|o| o.lines().filter_map(|l| l.split_whitespace().next().map(String::from)).collect()) .unwrap_or_default(); let kernel = run("uname", &["-r"]).unwrap_or_default().trim().to_string(); + let smart_data = smart(); + let drives = if smart_data.as_array().map(|a| !a.is_empty()).unwrap_or(false) { smart_data.clone() } else { + #[cfg(windows)] { windows_physical_drives() } + #[cfg(not(windows))] { smart_data.clone() } + }; let kernels: Vec = run("dpkg-query", &["-W", "-f=${Package} ${db:Status-Abbrev}\\n", "proxmox-kernel-*", "pve-kernel-*", "linux-image-[0-9]*"]) .map(|o| o.lines().filter(|l| l.contains(" ii")).filter_map(|l| l.split_whitespace().next().map(String::from)).filter(|p| p.chars().any(|c| c.is_ascii_digit()) && !p.ends_with("-signed")).collect()) .unwrap_or_default(); @@ -302,12 +394,15 @@ pub fn info() -> Value { "kernel": kernel, "kernels": kernels, "load": loadavg, + "cpu_usage_pct": cpu_usage_pct, + "gpus": gpu_inventory(), + "drives": drives, "failed": failed, "proxmox": proxmox(), "unraid": unraid(), "zfs": zfs(), "docker": docker(), - "smart": smart(), + "smart": smart_data, }) } diff --git a/crates/mwm-core/src/web.rs b/crates/mwm-core/src/web.rs index d276360..6741d0a 100644 --- a/crates/mwm-core/src/web.rs +++ b/crates/mwm-core/src/web.rs @@ -23,6 +23,8 @@ const FILES: &[(&str, &str, &str)] = &[ ("toolkit.js", "text/javascript; charset=utf-8", include_str!("../../../app/ui/toolkit.js")), ("server.js", "text/javascript; charset=utf-8", include_str!("../../../app/ui/server.js")), ("fleet.js", "text/javascript; charset=utf-8", include_str!("../../../app/ui/fleet.js")), + ("appliances.js", "text/javascript; charset=utf-8", include_str!("../../../app/ui/appliances.js")), + ("devices.js", "text/javascript; charset=utf-8", include_str!("../../../app/ui/devices.js")), ("command.js", "text/javascript; charset=utf-8", include_str!("../../../app/ui/command.js")), ("ctx.js", "text/javascript; charset=utf-8", include_str!("../../../app/ui/ctx.js")), ("cluster.js", "text/javascript; charset=utf-8", include_str!("../../../app/ui/cluster.js")), @@ -286,30 +288,30 @@ pub fn ra_autostart() { if cfg.enabled { let _ = ra_start(&cfg.bind, cfg.read_only); } -} - -/// Every asset index.html references must be embedded here. A missing entry -/// silently 404s a panel on the server web UI while the desktop works fine. -#[cfg(test)] -mod asset_tests { - use super::FILES; - #[test] - fn index_assets_embedded() { - let html = include_str!("../../../app/ui/index.html"); - let mut missing = Vec::new(); - for needle in ["src=\"", "href=\""] { - let mut rest = html; - while let Some(i) = rest.find(needle) { - rest = &rest[i + needle.len()..]; - let path = &rest[..rest.find('"').unwrap_or(rest.len())]; - if path.starts_with("http") || path.starts_with('#') || path.is_empty() { - continue; - } - if !FILES.iter().any(|(n, _, _)| *n == path) { - missing.push(path.to_string()); - } - } - } - assert!(missing.is_empty(), "index.html references assets not embedded in mwm serve: {missing:?}"); - } -} +} + +/// Every asset index.html references must be embedded here. A missing entry +/// silently 404s a panel on the server web UI while the desktop works fine. +#[cfg(test)] +mod asset_tests { + use super::FILES; + #[test] + fn index_assets_embedded() { + let html = include_str!("../../../app/ui/index.html"); + let mut missing = Vec::new(); + for needle in ["src=\"", "href=\""] { + let mut rest = html; + while let Some(i) = rest.find(needle) { + rest = &rest[i + needle.len()..]; + let path = &rest[..rest.find('"').unwrap_or(rest.len())]; + if path.starts_with("http") || path.starts_with('#') || path.is_empty() { + continue; + } + if !FILES.iter().any(|(n, _, _)| *n == path) { + missing.push(path.to_string()); + } + } + } + assert!(missing.is_empty(), "index.html references assets not embedded in mwm serve: {missing:?}"); + } +} diff --git a/deploy/media_apps.py b/deploy/media_apps.py new file mode 100644 index 0000000..1928c70 --- /dev/null +++ b/deploy/media_apps.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Application-only maintenance. Never runs apt upgrade or upgrades an OS.""" +import concurrent.futures, datetime as dt, hashlib, io, json, os, pathlib, shlex, socket, subprocess, sys, time, zipfile +REPORT=pathlib.Path('/var/lib/mwm/media-apps.json') +ARCHIVE=pathlib.Path('/opt/repos/ai-state/wadei/mwm-application-backups') +ARR={'sonarr':(8989,'v3'),'radarr':(7878,'v3'),'lidarr':(8686,'v1'),'prowlarr':(9696,'v1')} +NAMES=set(ARR)|{'plex1','plex2','jellyfin','romm','seerr','qbittorrent','rommarr','maintainerr','cleanuparr','tautulli','nzbget','komga','flaresolverr'} +def run(args,timeout=60): + p=subprocess.run(args,capture_output=True,timeout=timeout) + if p.returncode:raise RuntimeError(p.stderr.decode(errors='replace')[-350:] or 'Remote command failed') + return p.stdout + +def guests(): + return [x for x in json.loads(run(['pvesh','get','/cluster/resources','--type','vm','--output-format','json'])) if x.get('type')=='lxc' and x.get('name','').lower() in NAMES] +def ips():return {k:v['ip'] for k,v in json.loads(pathlib.Path('/etc/pve/.members').read_text())['nodelist'].items()} +def nodecmd(node,args): + if node.lower()==socket.gethostname().lower():return args + return ['ssh','-o','BatchMode=yes','-o','ConnectTimeout=6','root@'+ips()[node],shlex.join(args)] +def guest(g,args,timeout=90):return run(nodecmd(g['node'],['pct','exec',str(g['vmid']),'--']+args),timeout) +def arr(g,op): + name=g['name'].lower();port,version=ARR[name] + code=r""" +import datetime,hashlib,json,os,pathlib,time,urllib.request,xml.etree.ElementTree as ET +app=APP;operation=OP;root='http://127.0.0.1:PORT/api/VER';key=ET.parse('/var/lib/'+app+'/config.xml').getroot().findtext('ApiKey') +def req(path,data=None): + r=urllib.request.Request(root+'/'+path,data=None if data is None else json.dumps(data).encode(),headers={'X-Api-Key':key,'Content-Type':'application/json'}) + with urllib.request.urlopen(r,timeout=20) as f:return json.load(f) +if operation=='scan': + s=req('system/status');u=req('update');new=next((x for x in u if x.get('installable') and not x.get('installed')),None);print(json.dumps({'version':s.get('version'),'update_version':new.get('version') if new else None,'health':req('health'),'update_supported':True})) +elif operation=='backup': + c=req('command',{'name':'Backup'});end=time.time()+180 + while time.time()2 else ''))) + except Exception as e:print(json.dumps({'error':str(e)}));sys.exit(1)