Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): sharpen and resize Windows taskbar badges (#4547)
Lizi24bb640a0161
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.tsindex ebfcc74004..3e6b77166a 100644--- a/apps/desktop/forge.config.ts+++ b/apps/desktop/forge.config.ts@@ -1127,6 +1127,27 @@ function buildWindowsGamepadHelper(platform: ForgePlatform, arch: ForgeArch): vobuildWindowsInputHelper('micro', platform, arch);}+function buildWindowsTaskbarAddon(platform: ForgePlatform, arch: ForgeArch): void {+ if (process.platform !== 'win32' || platform !== 'win32') return;+ const target = arch === 'arm64' ? 'aarch64-pc-windows-msvc' : arch === 'x64' ? 'x86_64-pc-windows-msvc' : null;+ if (!target) throw new Error(`[forge] Unsupported Windows taskbar architecture: ${arch}`);+ const source = path.join(__dirname, 'native', 'windows-taskbar');+ const build = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-taskbar-build-'));+ try {+ const userCargo = path.join(os.homedir(), '.cargo', 'bin', 'cargo.exe');+ const result = spawnSync(fs.existsSync(userCargo) ? userCargo : 'cargo', [+ 'build', '--release', '--locked', '--target', target,+ '--manifest-path', path.join(source, 'Cargo.toml'), '--target-dir', build,+ ], { stdio: 'inherit', windowsHide: true });+ if (result.error || result.status !== 0) throw new Error(`[forge] Windows taskbar build failed: ${result.error?.message ?? result.status}`);+ const dest = path.join(__dirname, 'resources', 'tools', 'windows-taskbar');+ fs.mkdirSync(dest, { recursive: true });+ fs.copyFileSync(path.join(build, target, 'release', 'cindy_windows_taskbar.dll'), path.join(dest, 'cindy-windows-taskbar.node'));+ } finally {+ fs.rmSync(build, { recursive: true, force: true });+ }+}+function buildWindowsInputHelper(kind: 'gamepad' | 'micro', platform: ForgePlatform, arch: ForgeArch): void {if (process.platform !== 'win32' || platform !== 'win32') return;const target = arch === 'arm64' ? 'aarch64-pc-windows-msvc' : arch === 'x64' ? 'x86_64-pc-windows-msvc' : null;@@ -1670,6 +1691,7 @@ const config: ForgeConfig = {buildMacVoiceInputTextInsertionHelper(platform, arch);buildMacXboxGamepadHelper(platform, arch);buildWindowsGamepadHelper(platform, arch);+ buildWindowsTaskbarAddon(platform, arch);buildMacVoiceInputModifierShortcutListener(platform, arch);buildMacAgentIslandHelper(platform, arch);buildMacComputerPermissionGuideHelper(platform, arch);diff --git a/apps/desktop/native/windows-taskbar/Cargo.lock b/apps/desktop/native/windows-taskbar/Cargo.locknew file mode 100644index 0000000000..ca7c4684b9--- /dev/null+++ b/apps/desktop/native/windows-taskbar/Cargo.lock@@ -0,0 +1,342 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "aho-corasick"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"+dependencies = [+ "memchr",+]++[[package]]+name = "bitflags"+version = "2.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"++[[package]]+name = "cfg-if"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"++[[package]]+name = "cindy-windows-taskbar"+version = "0.1.0"+dependencies = [+ "napi",+ "napi-build",+ "napi-derive",+ "windows",+]++[[package]]+name = "convert_case"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca"+dependencies = [+ "unicode-segmentation",+]++[[package]]+name = "ctor"+version = "0.2.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a2785755761f3ddc1492979ce1e48d2c00d09311c39e4466429188f3dd6501"+dependencies = [+ "quote",+ "syn",+]++[[package]]+name = "libloading"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"+dependencies = [+ "cfg-if",+ "windows-link",+]++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "napi"+version = "2.16.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "55740c4ae1d8696773c78fdafd5d0e5fe9bc9f1b071c7ba493ba5c413a9184f3"+dependencies = [+ "bitflags",+ "ctor",+ "napi-derive",+ "napi-sys",+ "once_cell",+]++[[package]]+name = "napi-build"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1c0f5d67ee408a4685b61f5ab7e58605c8ae3f2b4189f0127d804ff13d5560a"++[[package]]+name = "napi-derive"+version = "2.16.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7cbe2585d8ac223f7d34f13701434b9d5f4eb9c332cccce8dee57ea18ab8ab0c"+dependencies = [+ "cfg-if",+ "convert_case",+ "napi-derive-backend",+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "napi-derive-backend"+version = "1.0.75"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1639aaa9eeb76e91c6ae66da8ce3e89e921cd3885e99ec85f4abacae72fc91bf"+dependencies = [+ "convert_case",+ "once_cell",+ "proc-macro2",+ "quote",+ "regex",+ "semver",+ "syn",+]++[[package]]+name = "napi-sys"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "427802e8ec3a734331fec1035594a210ce1ff4dc5bc1950530920ab717964ea3"+dependencies = [+ "libloading",+]++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "regex"+version = "1.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"++[[package]]+name = "semver"+version = "1.0.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "unicode-ident"+version = "1.0.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"++[[package]]+name = "unicode-segmentation"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"++[[package]]+name = "windows"+version = "0.58.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd04d41d93c4992d421894c18c8b43496aa748dd4c081bac0dc93eb0489272b6"+dependencies = [+ "windows-core",+ "windows-targets",+]++[[package]]+name = "windows-core"+version = "0.58.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ba6d44ec8c2591c134257ce647b7ea6b20335bf6379a27dac5f1641fcf59f99"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-result",+ "windows-strings",+ "windows-targets",+]++[[package]]+name = "windows-implement"+version = "0.58.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2bbd5b46c938e506ecbce286b6628a02171d56153ba733b6c741fc627ec9579b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "windows-interface"+version = "0.58.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053c4c462dc91d3b1504c6fe5a726dd15e216ba718e84a0e46a88fbe5ded3515"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-result"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1d1043d8214f791817bab27572aaa8af63732e11bf84aa21a45a78d6c317ae0e"+dependencies = [+ "windows-targets",+]++[[package]]+name = "windows-strings"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4cd9b125c486025df0eabcb585e62173c6c9eddcec5d117d3b6e8c30e2ee4d10"+dependencies = [+ "windows-result",+ "windows-targets",+]++[[package]]+name = "windows-targets"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"+dependencies = [+ "windows_aarch64_gnullvm",+ "windows_aarch64_msvc",+ "windows_i686_gnu",+ "windows_i686_gnullvm",+ "windows_i686_msvc",+ "windows_x86_64_gnu",+ "windows_x86_64_gnullvm",+ "windows_x86_64_msvc",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"++[[package]]+name = "windows_aarch64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"++[[package]]+name = "windows_i686_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"++[[package]]+name = "windows_i686_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"++[[package]]+name = "windows_i686_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"++[[package]]+name = "windows_x86_64_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"++[[package]]+name = "windows_x86_64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"diff --git a/apps/desktop/native/windows-taskbar/Cargo.toml b/apps/desktop/native/windows-taskbar/Cargo.tomlnew file mode 100644index 0000000000..c4b5ae25f3--- /dev/null+++ b/apps/desktop/native/windows-taskbar/Cargo.toml@@ -0,0 +1,22 @@+[package]+name = "cindy-windows-taskbar"+version = "0.1.0"+edition = "2021"+license = "Apache-2.0"++[lib]+crate-type = ["cdylib"]++[build-dependencies]+napi-build = "=2.1.3"++[dependencies]+napi = { version = "2", default-features = false, features = ["napi6"] }+napi-derive = "2"+windows = { version = "0.58", features = ["Win32_Foundation", "Win32_System_Com", "Win32_System_Threading", "Win32_UI_Shell", "Win32_UI_WindowsAndMessaging", "Win32_Graphics_Gdi"] }++[profile.release]+panic = "abort"+lto = true+opt-level = "s"+strip = truediff --git a/apps/desktop/native/windows-taskbar/build.rs b/apps/desktop/native/windows-taskbar/build.rsnew file mode 100644index 0000000000..0f1b01002b--- /dev/null+++ b/apps/desktop/native/windows-taskbar/build.rs@@ -0,0 +1,3 @@+fn main() {+ napi_build::setup();+}diff --git a/apps/desktop/native/windows-taskbar/src/lib.rs b/apps/desktop/native/windows-taskbar/src/lib.rsnew file mode 100644index 0000000000..6e05faac19--- /dev/null+++ b/apps/desktop/native/windows-taskbar/src/lib.rs@@ -0,0 +1,166 @@+//! Main-only taskbar bridge. Electron 41 always resizes overlays to 16 physical+//! pixels; pass the original DPI-sized image to the Shell instead.+use napi::bindgen_prelude::Buffer;+use napi_derive::napi;+use windows::{+ core::{w, PCWSTR},+ Win32::{+ Foundation::{HWND, RPC_E_CHANGED_MODE},+ System::{+ Com::{+ CoCreateInstance, CoInitializeEx, CoUninitialize, CLSCTX_INPROC_SERVER,+ COINIT_APARTMENTTHREADED,+ },+ Threading::GetCurrentProcessId,+ },+ UI::{+ Shell::{ITaskbarList3, TaskbarList},+ WindowsAndMessaging::{+ CreateIconFromResourceEx, DestroyIcon, GetWindowThreadProcessId, IsWindow,+ RegisterWindowMessageW, HICON, LR_DEFAULTCOLOR,+ },+ },+ },+};++fn failure(error: impl std::fmt::Display) -> napi::Error {+ napi::Error::from_reason(format!("Windows taskbar: {error}"))+}++// Only balance successful CoInitializeEx calls; Electron normally already owns+// the apartment. A different existing apartment is usable without reinitializing.+struct Apartment(bool);+impl Drop for Apartment {+ fn drop(&mut self) {+ if self.0 {+ unsafe { CoUninitialize() };+ }+ }+}++struct Icon(HICON);+impl Drop for Icon {+ fn drop(&mut self) {+ if !self.0.is_invalid() {+ let _ = unsafe { DestroyIcon(self.0) };+ }+ }+}++fn window_from_bytes(bytes: &[u8]) -> napi::Result<HWND> {+ let handle: [u8; std::mem::size_of::<usize>()] = bytes+ .try_into()+ .map_err(|_| failure("invalid window handle"))?;+ let window = HWND(usize::from_le_bytes(handle) as *mut _);+ let mut pid = 0;+ unsafe {+ GetWindowThreadProcessId(window, Some(&mut pid));+ if !IsWindow(window).as_bool() || pid != GetCurrentProcessId() {+ return Err(failure("window is not owned by this process"));+ }+ }+ Ok(window)+}++fn png_size(bytes: &[u8]) -> napi::Result<i32> {+ if bytes.len() < 24 || bytes.len() > 128 * 1024 || &bytes[..8] != b"\x89PNG\r\n\x1a\n" {+ return Err(failure("invalid badge PNG"));+ }+ let width = u32::from_be_bytes(bytes[16..20].try_into().unwrap());+ let height = u32::from_be_bytes(bytes[20..24].try_into().unwrap());+ if width != height || !(16..=128).contains(&width) {+ return Err(failure("invalid badge dimensions"));+ }+ Ok(width as i32)+}++fn icon_from_png(bytes: &[u8]) -> napi::Result<Icon> {+ let size = png_size(bytes)?;+ // Windows Vista+ accepts a PNG-compressed icon resource. Keep its exact+ // physical dimensions: do not go through Electron's 16px bitmap conversion.+ unsafe { CreateIconFromResourceEx(bytes, true, 0x00030000, size, size, LR_DEFAULTCOLOR) }+ .map(Icon)+ .map_err(failure)+}++#[napi]+pub fn taskbar_button_created_message() -> u32 {+ unsafe { RegisterWindowMessageW(w!("TaskbarButtonCreated")) }+}++#[napi]+pub fn set_overlay_icon(+ handle: Buffer,+ png: Option<Buffer>,+ description: String,+) -> napi::Result<()> {+ let window = window_from_bytes(&handle)?;+ if description.len() > 4096 || description.contains('\0') {+ return Err(failure("invalid badge description"));+ }+ let icon = match png {+ Some(bytes) => icon_from_png(&bytes)?,+ None => Icon(HICON::default()),+ };+ let description: Vec<u16> = description.encode_utf16().chain(Some(0)).collect();+ unsafe {+ let initialized = CoInitializeEx(None, COINIT_APARTMENTTHREADED);+ if initialized.is_err() && initialized != RPC_E_CHANGED_MODE {+ return Err(failure(initialized));+ }+ let _apartment = Apartment(initialized.is_ok());+ let taskbar: ITaskbarList3 =+ CoCreateInstance(&TaskbarList, None, CLSCTX_INPROC_SERVER).map_err(failure)?;+ taskbar.HrInit().map_err(failure)?;+ // The Shell copies HICON before returning, so Icon can always release it.+ taskbar+ .SetOverlayIcon(window, icon.0, PCWSTR(description.as_ptr()))+ .map_err(failure)+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use windows::Win32::Graphics::Gdi::{DeleteObject, GetObjectW, BITMAP};+ use windows::Win32::UI::WindowsAndMessaging::{GetIconInfo, ICONINFO};++ // A 24px opaque PNG: 150% DPI must remain 24px after conversion to HICON.+ const PNG: &[u8] = &[+ 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 24, 0, 0, 0, 24, 8,+ 6, 0, 0, 0, 224, 119, 61, 248, 0, 0, 0, 4, 115, 66, 73, 84, 8, 8, 8, 8, 124, 8, 100, 136,+ 0, 0, 0, 1, 115, 82, 71, 66, 0, 174, 206, 28, 233, 0, 0, 0, 39, 73, 68, 65, 84, 72, 137,+ 99, 100, 96, 96, 248, 207, 64, 67, 192, 68, 75, 195, 71, 45, 24, 181, 96, 212, 130, 81, 11,+ 70, 45, 24, 181, 96, 212, 130, 81, 11, 168, 7, 0, 238, 203, 1, 47, 243, 63, 198, 173, 0, 0,+ 0, 0, 73, 69, 78, 68, 174, 66, 96, 130,+ ];++ #[test]+ fn hicon_keeps_physical_resolution() {+ let icon = icon_from_png(PNG).unwrap();+ let mut info = ICONINFO::default();+ unsafe {+ GetIconInfo(icon.0, &mut info).unwrap();+ let mut bitmap = BITMAP::default();+ let result = GetObjectW(+ info.hbmColor,+ std::mem::size_of::<BITMAP>() as i32,+ Some((&mut bitmap as *mut BITMAP).cast()),+ );+ let _ = DeleteObject(info.hbmColor);+ let _ = DeleteObject(info.hbmMask);+ assert_ne!(result, 0);+ assert_eq!((bitmap.bmWidth, bitmap.bmHeight), (24, 24));+ }+ }++ #[test]+ fn rejects_invalid_dimensions_and_handles() {+ assert!(png_size(&[]).is_err());+ let mut nonsquare = PNG.to_vec();+ nonsquare[23] = 16;+ assert!(png_size(&nonsquare).is_err());+ assert!(window_from_bytes(&[0]).is_err());+ assert!(window_from_bytes(&[0; std::mem::size_of::<usize>()]).is_err());+ }+}diff --git a/apps/desktop/resources/THIRD-PARTY-NOTICES.txt b/apps/desktop/resources/THIRD-PARTY-NOTICES.txtindex ac1031429d..24840a7bca 100644--- a/apps/desktop/resources/THIRD-PARTY-NOTICES.txt+++ b/apps/desktop/resources/THIRD-PARTY-NOTICES.txt@@ -5167,7 +5167,7 @@ SECTION 2: npm packages (930 packages)- [email protected] — MIT — https://github.com/wooorm/zwitch==============================================================================-SECTION 3: cargo packages (292 packages)+SECTION 3: cargo packages (293 packages)==============================================================================- [email protected] — 0BSD OR MIT OR Apache-2.0 — https://github.com/oyvindln/adler2@@ -5187,6 +5187,7 @@ SECTION 3: cargo packages (292 packages)- [email protected] — MIT OR Apache-2.0 — https://github.com/bitflags/bitflags- [email protected] — MIT OR Apache-2.0 — https://github.com/bitflags/bitflags- [email protected] — MIT OR Apache-2.0 — https://github.com/bitflags/bitflags+- [email protected] — MIT OR Apache-2.0 — https://github.com/bitflags/bitflags- [email protected] — MIT OR Apache-2.0 — https://github.com/RustCrypto/utils- [email protected] — BSD-3-Clause AND MIT — https://github.com/dropbox/rust-brotli- [email protected] — BSD-3-Clause OR MIT — https://github.com/dropbox/rust-brotli-decompressor@@ -6670,7 +6671,7 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHERDEALINGS IN THE SOFTWARE.-------------------------------------------------------------------------------[8] Applies to: cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected]+[8] Applies to: cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected]------------------------------------------------------------------------------Apache LicenseVersion 2.0, January 2004diff --git a/apps/desktop/src/main/__tests__/appBadgeService.test.ts b/apps/desktop/src/main/__tests__/appBadgeService.test.tsindex e1a1de0c46..e620b2f5fb 100644--- a/apps/desktop/src/main/__tests__/appBadgeService.test.ts+++ b/apps/desktop/src/main/__tests__/appBadgeService.test.ts@@ -36,6 +36,13 @@ function publish(}vi.mock('../windowsBadgeIcon', () => ({ createWindowsBadgeIcon }));+vi.mock('../windowsTaskbarBadge', () => ({+ setWindowsTaskbarBadge: (+ win: { setOverlayIcon: typeof setOverlayIcon },+ count: number,+ description: string,+ ) => win.setOverlayIcon(createWindowsBadgeIcon(count), description),+}));vi.mock('../i18n', () => ({ t: () => badgeDescription }));vi.mock('../security/trustedAppRenderer', () => ({ assertTrustedAppRendererEvent }));diff --git a/apps/desktop/src/main/__tests__/windowsBadgeIcon.test.ts b/apps/desktop/src/main/__tests__/windowsBadgeIcon.test.tsindex 643d468479..aeb6e5c9c3 100644--- a/apps/desktop/src/main/__tests__/windowsBadgeIcon.test.ts+++ b/apps/desktop/src/main/__tests__/windowsBadgeIcon.test.ts@@ -10,6 +10,15 @@ vi.mock('electron', () => ({ nativeImage: { createEmpty: () => icon } }));import { createWindowsBadgeIcon, renderWindowsBadgePng } from '../windowsBadgeIcon';describe('Windows numeric taskbar badge', () => {+ it.each([1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4, 8])(+ 'renders exact physical dimensions at %s scale for the native Shell bridge',+ (scale) => {+ const png = renderWindowsBadgePng(1, scale);+ expect(png.readUInt32BE(16)).toBe(Math.round(16 * scale));+ expect(png.readUInt32BE(20)).toBe(Math.round(16 * scale));+ },+ );+it('provides PNGs at common Windows display scales and clears at zero', () => {expect(createWindowsBadgeIcon(3)).toBe(icon);expect(addRepresentation.mock.calls.map(([rep]) => rep.scaleFactor)).toEqual([diff --git a/apps/desktop/src/main/__tests__/windowsTaskbarBadge.test.ts b/apps/desktop/src/main/__tests__/windowsTaskbarBadge.test.tsnew file mode 100644index 0000000000..d806884871--- /dev/null+++ b/apps/desktop/src/main/__tests__/windowsTaskbarBadge.test.ts@@ -0,0 +1,164 @@+import { EventEmitter } from 'node:events';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { BrowserWindow } from 'electron';++const mocks = vi.hoisted(() => ({+ load: vi.fn(),+ warn: vi.fn(),+ displays: vi.fn(),+ render: vi.fn((count: number, scale: number) => Buffer.from(`${count}@${scale}`)),+}));+const { screen } = await vi.hoisted(async () => {+ const { EventEmitter } = await import('node:events');+ return { screen: new EventEmitter() };+});+vi.mock('electron', () => ({ screen: Object.assign(screen, { getAllDisplays: mocks.displays }) }));+vi.mock('../logger', () => ({ createLogger: () => ({ warn: mocks.warn }) }));+vi.mock('../windowsTaskbarNative', () => ({ loadWindowsTaskbarNative: mocks.load }));+vi.mock('../windowsBadgeIcon', () => ({+ renderWindowsBadgePng: mocks.render,+ createWindowsBadgeIcon: (count: number) => (count > 0 ? `fallback:${count}` : null),+}));+import { setWindowsTaskbarBadge } from '../windowsTaskbarBadge';++/** In-memory window with the same event lifetime as a BrowserWindow. */+class Window extends EventEmitter {+ destroyed = false;+ setOverlayIcon = vi.fn();+ getNativeWindowHandle = () => Buffer.alloc(8, 1);+ isDestroyed = () => this.destroyed;+ hookWindowMessage = vi.fn();+ badge(count: number, description = `Attention: ${count}`) {+ setWindowsTaskbarBadge(this as unknown as BrowserWindow, count, count ? description : '');+ }+ close() {+ this.destroyed = true;+ this.emit('closed');+ }+}+const native = { setOverlayIcon: vi.fn(), taskbarButtonCreatedMessage: () => 0xc123 };+const flush = async () => {+ await new Promise<void>((resolve) => setImmediate(resolve));+};+const platform = process.platform;++beforeEach(() => {+ vi.clearAllMocks();+ screen.removeAllListeners();+ Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });+ mocks.displays.mockReturnValue([{ scaleFactor: 1.5 }]);+ mocks.load.mockResolvedValue(native);+ native.setOverlayIcon.mockReset();+});+afterEach(() => {+ Object.defineProperty(process, 'platform', { value: platform, configurable: true });+});++describe('DPI-aware Windows taskbar badge', () => {+ it('delivers the densest monitor image directly to the Shell and keeps the exact count description', async () => {+ mocks.displays.mockReturnValue([{ scaleFactor: 1.25 }, { scaleFactor: 2.5 }]);+ const win = new Window();+ win.badge(123);+ await flush();+ expect(native.setOverlayIcon).toHaveBeenLastCalledWith(+ win.getNativeWindowHandle(),+ Buffer.from('[email protected]'),+ 'Attention: 123',+ );+ win.setOverlayIcon.mockClear();+ win.badge(124);+ expect(win.setOverlayIcon).not.toHaveBeenCalled();+ expect(native.setOverlayIcon).toHaveBeenLastCalledWith(+ win.getNativeWindowHandle(),+ Buffer.from('[email protected]'),+ 'Attention: 124',+ );+ });++ it('uses the latest count after loading, including clearing a badge while compilation is pending', async () => {+ let ready!: (value: typeof native) => void;+ mocks.load.mockReturnValue(+ new Promise((resolve) => {+ ready = resolve;+ }),+ );+ const win = new Window();+ win.badge(3);+ win.badge(4);+ win.badge(0);+ expect(mocks.load).toHaveBeenCalledTimes(1);+ expect(win.setOverlayIcon).toHaveBeenLastCalledWith(null, '');+ ready(native);+ await flush();+ expect(native.setOverlayIcon).toHaveBeenCalledTimes(1);+ expect(native.setOverlayIcon).toHaveBeenLastCalledWith(win.getNativeWindowHandle(), null, '');+ expect(mocks.render).not.toHaveBeenCalled();+ });++ it('does not load native code for an empty badge or repaint a destroyed window', async () => {+ const empty = new Window();+ empty.badge(0);+ expect(mocks.load).not.toHaveBeenCalled();+ const win = new Window();+ win.badge(1);+ win.close();+ await flush();+ expect(native.setOverlayIcon).not.toHaveBeenCalled();+ expect(win.hookWindowMessage).not.toHaveBeenCalled();+ empty.close();+ expect(screen.eventNames()).toEqual([]);+ });++ it('redraws after display and Shell changes without changing or flashing the count', async () => {+ const win = new Window();+ win.badge(7);+ await flush();+ mocks.displays.mockReturnValue([{ scaleFactor: 1.75 }]);+ screen.emit('display-metrics-changed');+ expect(native.setOverlayIcon).toHaveBeenLastCalledWith(+ win.getNativeWindowHandle(),+ Buffer.from('[email protected]'),+ 'Attention: 7',+ );+ native.setOverlayIcon.mockClear();+ win.hookWindowMessage.mock.calls[0][1]();+ await flush();+ expect(native.setOverlayIcon).toHaveBeenCalledTimes(1);+ win.close();+ expect(screen.eventNames()).toEqual([]);+ });++ it('falls back after load failure without repeated builds or warnings', async () => {+ mocks.load.mockRejectedValue(new Error('unavailable'));+ const win = new Window();+ win.badge(3);+ await flush();+ win.badge(4);+ win.badge(0);+ expect(mocks.load).toHaveBeenCalledTimes(1);+ expect(mocks.warn).toHaveBeenCalledTimes(1);+ expect(win.setOverlayIcon).toHaveBeenLastCalledWith(null, '');+ });++ it('recovers from a transient native failure and can still clear the badge', async () => {+ const win = new Window();+ win.badge(2);+ await flush();+ native.setOverlayIcon.mockImplementationOnce(() => {+ throw new Error('Shell restarting');+ });+ win.badge(3);+ expect(win.setOverlayIcon).toHaveBeenLastCalledWith('fallback:3', 'Attention: 3');+ win.badge(0);+ expect(native.setOverlayIcon).toHaveBeenLastCalledWith(win.getNativeWindowHandle(), null, '');+ });++ it('leaves non-Windows platforms untouched', () => {+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });+ const win = new Window();+ win.badge(2);+ expect(mocks.load).not.toHaveBeenCalled();+ expect(win.setOverlayIcon).not.toHaveBeenCalled();+ expect(screen.eventNames()).toEqual([]);+ });+});diff --git a/apps/desktop/src/main/__tests__/windowsTaskbarNative.test.ts b/apps/desktop/src/main/__tests__/windowsTaskbarNative.test.tsnew file mode 100644index 0000000000..738f6de9d6--- /dev/null+++ b/apps/desktop/src/main/__tests__/windowsTaskbarNative.test.ts@@ -0,0 +1,131 @@+import path from 'node:path';+import os from 'node:os';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ app: { isPackaged: true, getAppPath: vi.fn(), getPath: vi.fn() },+ exec: vi.fn(),+ require: vi.fn(),+ fs: {+ access: vi.fn(),+ readFile: vi.fn(),+ mkdtemp: vi.fn(),+ mkdir: vi.fn(),+ copyFile: vi.fn(),+ rename: vi.fn(),+ rm: vi.fn(),+ },+}));+vi.mock('electron', () => ({ app: mocks.app }));+vi.mock('node:fs/promises', () => ({ default: mocks.fs }));+vi.mock('node:module', () => ({ createRequire: () => mocks.require }));+vi.mock('node:child_process', () => ({ execFile: vi.fn() }));+vi.mock('node:util', () => ({ promisify: () => mocks.exec }));++const platform = process.platform;+const arch = process.arch;+const root = path.join(os.tmpdir(), 'taskbar-in-memory-fixture');+const addon = { setOverlayIcon() {}, taskbarButtonCreatedMessage: () => 0xc123 };++beforeEach(() => {+ vi.resetModules();+ vi.resetAllMocks();+ Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });+ Object.defineProperty(process, 'arch', { value: 'x64', configurable: true });+ mocks.app.isPackaged = false;+ mocks.app.getAppPath.mockReturnValue(path.join(root, 'app'));+ mocks.app.getPath.mockReturnValue(path.join(root, 'profile'));+ mocks.fs.readFile.mockResolvedValue(Buffer.from('source version'));+ mocks.fs.access.mockRejectedValue(new Error('missing'));+ mocks.fs.mkdtemp.mockResolvedValue(path.join(root, 'build'));+ mocks.fs.rename.mockResolvedValue(undefined);+ mocks.require.mockReturnValue(addon);+});+afterEach(() => {+ Object.defineProperty(process, 'platform', { value: platform, configurable: true });+ Object.defineProperty(process, 'arch', { value: arch, configurable: true });+});++describe('Windows taskbar native loading', () => {+ it('loads the packaged addon without a compiler or source files', async () => {+ mocks.app.isPackaged = true;+ const resources = process.resourcesPath;+ Object.defineProperty(process, 'resourcesPath', {+ value: path.join(root, 'resources'),+ configurable: true,+ });+ try {+ const { loadWindowsTaskbarNative } = await import('../windowsTaskbarNative');+ expect(await loadWindowsTaskbarNative()).toBe(addon);+ expect(mocks.require).toHaveBeenCalledWith(+ path.join(root, 'resources', 'tools', 'windows-taskbar', 'cindy-windows-taskbar.node'),+ );+ expect(mocks.fs.readFile).not.toHaveBeenCalled();+ expect(mocks.exec).not.toHaveBeenCalled();+ } finally {+ Object.defineProperty(process, 'resourcesPath', { value: resources, configurable: true });+ }+ });++ it('coalesces dev builds, uses the right architecture and cleans temporary outputs', async () => {+ Object.defineProperty(process, 'arch', { value: 'arm64', configurable: true });+ const { loadWindowsTaskbarNative } = await import('../windowsTaskbarNative');+ const first = loadWindowsTaskbarNative();+ expect(loadWindowsTaskbarNative()).toBe(first);+ expect(await first).toBe(addon);+ expect(mocks.exec).toHaveBeenCalledWith(+ 'cargo',+ expect.arrayContaining([+ '--locked',+ '--target',+ 'aarch64-pc-windows-msvc',+ '--target-dir',+ path.join(root, 'build'),+ ]),+ expect.objectContaining({ windowsHide: true }),+ );+ expect(mocks.fs.copyFile).toHaveBeenCalledWith(+ path.join(root, 'build', 'aarch64-pc-windows-msvc', 'release', 'cindy_windows_taskbar.dll'),+ expect.stringContaining(path.join(root, 'profile', 'windows-taskbar')),+ );+ expect(mocks.fs.rename).toHaveBeenCalledTimes(1);+ expect(mocks.fs.rm).toHaveBeenCalledWith(path.join(root, 'build'), {+ recursive: true,+ force: true,+ });+ });++ it('reuses only the cache for the current source bytes', async () => {+ mocks.fs.access.mockResolvedValue(undefined);+ let loader = await import('../windowsTaskbarNative');+ await loader.loadWindowsTaskbarNative();+ const firstPath = mocks.require.mock.calls[0][0];+ vi.resetModules();+ mocks.fs.readFile.mockResolvedValue(Buffer.from('changed source version'));+ loader = await import('../windowsTaskbarNative');+ await loader.loadWindowsTaskbarNative();+ expect(mocks.require.mock.calls[1][0]).not.toBe(firstPath);+ expect(mocks.exec).not.toHaveBeenCalled();+ });++ it('cleans a failed build and does not repeat it on every badge update', async () => {+ mocks.exec.mockRejectedValue(new Error('compiler unavailable'));+ const { loadWindowsTaskbarNative } = await import('../windowsTaskbarNative');+ await expect(loadWindowsTaskbarNative()).rejects.toThrow('compiler unavailable');+ await expect(loadWindowsTaskbarNative()).rejects.toThrow('compiler unavailable');+ expect(mocks.exec).toHaveBeenCalledTimes(1);+ expect(mocks.fs.rm).toHaveBeenCalledWith(path.join(root, 'build'), {+ recursive: true,+ force: true,+ });+ expect(mocks.require).not.toHaveBeenCalled();+ });++ it('does not build or load on another platform', async () => {+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });+ const { loadWindowsTaskbarNative } = await import('../windowsTaskbarNative');+ await expect(loadWindowsTaskbarNative()).rejects.toThrow('Windows-only');+ expect(mocks.exec).not.toHaveBeenCalled();+ expect(mocks.require).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/appBadgeService.ts b/apps/desktop/src/main/appBadgeService.tsindex 6720be44e5..8c7bdadb3b 100644--- a/apps/desktop/src/main/appBadgeService.ts+++ b/apps/desktop/src/main/appBadgeService.ts@@ -7,7 +7,7 @@ import {} from '../shared/sessionAttention';import { createLogger } from './logger';import { assertTrustedAppRendererEvent } from './security/trustedAppRenderer';-import { createWindowsBadgeIcon } from './windowsBadgeIcon';+import { setWindowsTaskbarBadge } from './windowsTaskbarBadge';import { t } from './i18n';import { throwIpcError } from './utils/ipcValidate';import { getActiveAppSession } from './appSessionState';@@ -204,8 +204,9 @@ function applyWindowsBadge(count: number, updateFlash = true): void {if (!win || win.isDestroyed()) return;try {if (updateFlash) win.flashFrame(count > 0);- win.setOverlayIcon(- createWindowsBadgeIcon(count),+ setWindowsTaskbarBadge(+ win,+ count,count > 0 ? t('appBadge.attentionCount').replace('{{count}}', String(count)) : '',);} catch (err) {diff --git a/apps/desktop/src/main/windowsBadgeIcon.ts b/apps/desktop/src/main/windowsBadgeIcon.tsindex 2eb27eb20d..d970996403 100644--- a/apps/desktop/src/main/windowsBadgeIcon.ts+++ b/apps/desktop/src/main/windowsBadgeIcon.ts@@ -7,6 +7,7 @@ const requireFromMain = createRequire(__filename);// 视觉合同见 DESIGN.md §2 的 Windows taskbar attention badge。const BADGE_COLORS = { background: '#D91F37', foreground: '#FFFFFF' } as const;const SCALE_FACTORS = [1, 1.25, 1.5, 2, 3] as const;+const BADGE_CONTENT_SCALE = 0.8;export function renderWindowsBadgePng(count: number, scaleFactor: number): Buffer {// 已随正式包附带的 N-API canvas;只在绘制时加载,macOS 启动不加载原生绘图库。@@ -14,16 +15,17 @@ export function renderWindowsBadgePng(count: number, scaleFactor: number): Buffeconst size = Math.round(16 * scaleFactor);const canvas = createCanvas(size, size);const ctx = canvas.getContext('2d');- ctx.scale(scaleFactor, scaleFactor);+ ctx.scale(size / 16, size / 16);+ // Keep the OS's 16-DIP canvas and shrink the artwork inside it. Shrinking the+ // PNG itself would make the Shell scale it back up, losing both size and clarity.+ ctx.translate(8, 8);+ ctx.scale(BADGE_CONTENT_SCALE, BADGE_CONTENT_SCALE);+ ctx.translate(-8, -8);const label = count > 99 ? '99+' : String(count);ctx.fillStyle = BADGE_COLORS.background;ctx.beginPath();ctx.roundRect(0.5, 0.5, 15, 15, label.length === 1 ? 7.5 : 5);ctx.fill();- // 细白边让角标在深浅任务栏和不同应用图标底色上都有清晰轮廓。- ctx.strokeStyle = BADGE_COLORS.foreground;- ctx.lineWidth = 0.75;- ctx.stroke();const fontSize = label.length === 1 ? 12 : label.length === 2 ? 10 : 8;ctx.font = `bold ${fontSize}px "Segoe UI", sans-serif`;ctx.fillStyle = BADGE_COLORS.foreground;diff --git a/apps/desktop/src/main/windowsTaskbarBadge.ts b/apps/desktop/src/main/windowsTaskbarBadge.tsnew file mode 100644index 0000000000..4eb2302b87--- /dev/null+++ b/apps/desktop/src/main/windowsTaskbarBadge.ts@@ -0,0 +1,102 @@+import { screen, type BrowserWindow } from 'electron';+import { createLogger } from './logger';+import { createWindowsBadgeIcon, renderWindowsBadgePng } from './windowsBadgeIcon';+import { loadWindowsTaskbarNative, type WindowsTaskbarNative } from './windowsTaskbarNative';++const log = createLogger('windowsTaskbarBadge');+const states = new WeakMap<BrowserWindow, BadgeState>();++/** The latest projection survives addon loading and Shell/DPI changes, never an old count. */+interface BadgeState {+ count: number;+ description: string;+ native?: WindowsTaskbarNative;+ loading: boolean;+ failed: boolean;+ warned: boolean;+}++export function setWindowsTaskbarBadge(+ win: BrowserWindow,+ count: number,+ description: string,+): void {+ if (process.platform !== 'win32' || win.isDestroyed()) return;+ let state = states.get(win);+ if (!state) {+ state = { count, description, loading: false, failed: false, warned: false };+ states.set(win, state);+ const current = state;+ const redraw = () => {+ if (!win.isDestroyed()) paint(win, current);+ };+ screen.on('display-added', redraw);+ screen.on('display-removed', redraw);+ screen.on('display-metrics-changed', redraw);+ win.on('show', redraw);+ win.once('closed', () => {+ screen.removeListener('display-added', redraw);+ screen.removeListener('display-removed', redraw);+ screen.removeListener('display-metrics-changed', redraw);+ states.delete(win);+ });+ }+ state.count = count;+ state.description = description;+ paint(win, state);+}++function warnOnce(state: BadgeState, error: unknown): void {+ if (state.warned) return;+ state.warned = true;+ log.warn('Native taskbar badge unavailable; using Electron overlay:', error);+}++function paint(win: BrowserWindow, state: BadgeState): void {+ if (state.native) {+ try {+ // One HICON is shared by all taskbars. Render for the densest display so+ // none has to upscale; the Shell can downsample on lower-DPI monitors.+ const scale = Math.min(8, Math.max(1, ...screen.getAllDisplays().map((d) => d.scaleFactor)));+ state.native.setOverlayIcon(+ win.getNativeWindowHandle(),+ state.count > 0 ? renderWindowsBadgePng(state.count, scale) : null,+ state.description,+ );+ return;+ } catch (error) {+ warnOnce(state, error);+ // A Shell restart can temporarily reject COM calls. Keep the bridge for+ // the next projection or TaskbarButtonCreated event, with no retry loop.+ }+ }+ try {+ win.setOverlayIcon(createWindowsBadgeIcon(state.count), state.description);+ } catch (error) {+ warnOnce(state, error);+ }+ if (state.native || state.loading || state.failed || state.count <= 0) return;+ state.loading = true;+ void loadWindowsTaskbarNative()+ .then((native) => {+ if (win.isDestroyed()) return;+ const message = native.taskbarButtonCreatedMessage();+ if (message) {+ win.hookWindowMessage(message, () => {+ // Paint after Electron's own handling of the Shell message completes.+ setImmediate(() => {+ if (!win.isDestroyed()) paint(win, state);+ });+ });+ }+ state.native = native;+ paint(win, state);+ })+ .catch((error: unknown) => {+ state.failed = true;+ warnOnce(state, error);+ })+ .finally(() => {+ state.loading = false;+ });+}diff --git a/apps/desktop/src/main/windowsTaskbarNative.ts b/apps/desktop/src/main/windowsTaskbarNative.tsnew file mode 100644index 0000000000..38e485746d--- /dev/null+++ b/apps/desktop/src/main/windowsTaskbarNative.ts@@ -0,0 +1,95 @@+import { execFile } from 'node:child_process';+import { createHash } from 'node:crypto';+import fs from 'node:fs/promises';+import { createRequire } from 'node:module';+import os from 'node:os';+import path from 'node:path';+import { promisify } from 'node:util';+import { app } from 'electron';++const exec = promisify(execFile);+const requireFromMain = createRequire(__filename);+const binaryName = 'cindy-windows-taskbar.node';++/** Main-owned bridge: no renderer input, exported handles or additional IPC. */+export interface WindowsTaskbarNative {+ setOverlayIcon(handle: Buffer, png: Buffer | null, description: string): void;+ taskbarButtonCreatedMessage(): number;+}++let loading: Promise<WindowsTaskbarNative> | undefined;++export function loadWindowsTaskbarNative(): Promise<WindowsTaskbarNative> {+ // A missing compiler/addon must not trigger another build on every count change.+ return (loading ??= resolveBinary().then(+ (binary) => requireFromMain(binary) as WindowsTaskbarNative,+ ));+}++async function resolveBinary(): Promise<string> {+ if (process.platform !== 'win32') throw new Error('Windows taskbar is Windows-only');+ if (app.isPackaged)+ return path.join(process.resourcesPath, 'tools', 'windows-taskbar', binaryName);+ const target =+ process.arch === 'arm64'+ ? 'aarch64-pc-windows-msvc'+ : process.arch === 'x64'+ ? 'x86_64-pc-windows-msvc'+ : null;+ if (!target) throw new Error('Unsupported Windows taskbar architecture');+ const source = path.join(app.getAppPath(), 'native', 'windows-taskbar');+ const digest = createHash('sha256').update(target);+ for (const file of ['Cargo.toml', 'Cargo.lock', 'build.rs', path.join('src', 'lib.rs')]) {+ digest.update(await fs.readFile(path.join(source, file)));+ }+ const directory = path.join(app.getPath('userData'), 'windows-taskbar', digest.digest('hex'));+ const binary = path.join(directory, binaryName);+ try {+ await fs.access(binary);+ return binary;+ } catch {+ // Development only: compile this exact source version outside the checkout.+ }+ const buildDirectory = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-taskbar-build-'));+ try {+ const userCargo = path.join(os.homedir(), '.cargo', 'bin', 'cargo.exe');+ const cargo = await fs.access(userCargo).then(+ () => userCargo,+ () => 'cargo',+ );+ await exec(+ cargo,+ [+ 'build',+ '--release',+ '--locked',+ '--target',+ target,+ '--manifest-path',+ path.join(source, 'Cargo.toml'),+ '--target-dir',+ buildDirectory,+ ],+ { timeout: 180_000, windowsHide: true },+ );+ await fs.mkdir(directory, { recursive: true });+ // Rename a complete copy; another dev instance may already have loaded its copy.+ const temporary = path.join(directory, `${binaryName}.${process.pid}.tmp`);+ try {+ await fs.copyFile(+ path.join(buildDirectory, target, 'release', 'cindy_windows_taskbar.dll'),+ temporary,+ );+ await fs.rename(temporary, binary).catch(async (error: unknown) => {+ await fs.access(binary).catch(() => {+ throw error;+ });+ });+ } finally {+ await fs.rm(temporary, { force: true });+ }+ return binary;+ } finally {+ await fs.rm(buildDirectory, { recursive: true, force: true });+ }+}diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.mdindex 026c52ab6d..2de8dcd3d3 100644--- a/docs/design-rules/DESIGN.md+++ b/docs/design-rules/DESIGN.md@@ -89,7 +89,7 @@ The grayscale rule is near-absolute. The following are the **only** sanctioned n> **Additional narrowly-scoped exceptions** (documented in their respective component specs, do NOT generalize as system semantic colors):>-> - **Windows taskbar attention badge** — the native OS overlay uses a fixed red background (`#D91F37`) and white digits/border (`#FFFFFF`) in both Light and Dark taskbars. This is the app-wide count of active tasks needing attention, not an error-only status. The image-specific semantic pair lives in `apps/desktop/src/main/windowsBadgeIcon.ts`; it is not an in-app theme token. Render at 16 logical pixels with 100/125/150/200/300% representations; use a circle for one digit, a rounded square for multiple digits, and `99+` above 99. The accessibility description keeps the exact total. Only the OS image may use its fitted 8–12px system-font digits; web typography and status-dot color rules are unchanged.+> - **Windows taskbar attention badge** — the native OS overlay uses a fixed red background (`#D91F37`) and white digits with no outline (`#FFFFFF`) in both Light and Dark taskbars. This is the app-wide count of active tasks needing attention, not an error-only status. The image-specific semantic pair lives in `apps/desktop/src/main/windowsBadgeIcon.ts`; it is not an in-app theme token. Keep a 16-logical-pixel transparent canvas and center the circle and digits at 80% of their original size (user refinement, 2026-09-16). Render using the highest connected display scale and pass that physical-size image directly to the Windows Shell through the native taskbar bridge (Electron 41 otherwise forces overlays to 16 physical pixels). Redraw after display/DPI changes and taskbar recreation; keep the multi-resolution Electron overlay as a failure fallback. Use a circle for one digit, a rounded square for multiple digits, and `99+` above 99. The accessibility description keeps the exact total. Only the OS image may use its fitted 8–12px system-font digits; web typography and status-dot color rules are unchanged.> - **Toast Info / Success / Warning / Error** — `#417CDD` / `#2AAE5B` / `#F3A115` / `#D91F37`(finalized 2026-07-17; Toast exemption lifted) — used ONLY on the 16×16 lucide icon inside Toast pill notifications. The pill body (background, text, border, close icon) remains strictly grayscale. Info blue #417CDD equals the focus-ring / Auto Approval value (originally #3B82F6, added 2026-07-14, now finalized); success/warning/error equal the global status colors (done green / status error / warning foreground).> - **Usage History category color (owner-approved 2026-09-08, extended 2026-09-09).** The registered usage heatmap uses a blue intensity scale. Daily token bars and their corresponding model-table swatches/share marks use `--usage-model-1` … `--usage-model-5` as the seed palette; additional models receive theme-derived hues without a top-five cutoff. All model identities in the full history are included, even when absent from the last 30 days. Agent/harness swatches, share marks and the stacked share strip reuse the existing engine identity tokens: `--engine-badge-cc` (terracotta orange), `--engine-badge-codex` (blue), and `--usage-model-1` (owner-chosen teal for pi, to distinguish it from Codex blue). Claude/Codex retain their cross-mode fixed-value contract; pi follows the existing Light/Dark teal values. `--usage-heatmap-high` supplies the high end of the heatmap. The heatmap retains its process-blue alias; category colors do not inherit process/status semantics. Task marks, text and control frames stay neutral. See [the component specification](./usage-history-charts.md); colors.ts remains the seed-value source, with runtime derivation under governance §3.4.> - **Resource Usage Process Categories** — the Resource Usage table may color only its 14px process-type glyphs so dense rows can be scanned by category (user-requested 2026-08-06). The six category pairs are task Agent blue `#2563EB / #60A5FA`, Agent service purple `#7C3AED / #A78BFA`, main-process pink `#DB2777 / #F472B6`, renderer cyan `#0891B2 / #22D3EE`, GPU amber `#D97706 / #F59E0B`, and utility green `#059669 / #34D399` (Light / Dark). These colors encode process category, **not health or status**; row backgrounds, labels, metrics, selection and actions remain on the neutral system. Direct use is confined to `resource-usage` process glyphs; the explicitly registered Usage History heatmap alias above may also reference the task-blue value. No other table or process UI inherits this permission. Tokens: `--process-agent-task-icon`, `--process-agent-service-icon`, `--process-main-icon`, `--process-renderer-icon`, `--process-gpu-icon`, `--process-utility-icon`.diff --git a/docs/legal/notices/THIRD-PARTY-NOTICES.txt b/docs/legal/notices/THIRD-PARTY-NOTICES.txtindex 130d42b9e3..ad60c5dbe2 100644--- a/docs/legal/notices/THIRD-PARTY-NOTICES.txt+++ b/docs/legal/notices/THIRD-PARTY-NOTICES.txt@@ -6424,7 +6424,7 @@ SECTION 2: npm packages (1442 packages)- [email protected] — MIT — https://github.com/wooorm/zwitch==============================================================================-SECTION 3: cargo packages (292 packages)+SECTION 3: cargo packages (293 packages)==============================================================================- [email protected] — 0BSD OR MIT OR Apache-2.0 — https://github.com/oyvindln/adler2@@ -6444,6 +6444,7 @@ SECTION 3: cargo packages (292 packages)- [email protected] — MIT OR Apache-2.0 — https://github.com/bitflags/bitflags- [email protected] — MIT OR Apache-2.0 — https://github.com/bitflags/bitflags- [email protected] — MIT OR Apache-2.0 — https://github.com/bitflags/bitflags+- [email protected] — MIT OR Apache-2.0 — https://github.com/bitflags/bitflags- [email protected] — MIT OR Apache-2.0 — https://github.com/RustCrypto/utils- [email protected] — BSD-3-Clause AND MIT — https://github.com/dropbox/rust-brotli- [email protected] — BSD-3-Clause OR MIT — https://github.com/dropbox/rust-brotli-decompressor@@ -7927,7 +7928,7 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHERDEALINGS IN THE SOFTWARE.-------------------------------------------------------------------------------[8] Applies to: cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected]+[8] Applies to: cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected]------------------------------------------------------------------------------Apache LicenseVersion 2.0, January 2004diff --git a/docs/legal/notices/desktop-win.txt b/docs/legal/notices/desktop-win.txtindex 3d192991a1..2164ed88af 100644--- a/docs/legal/notices/desktop-win.txt+++ b/docs/legal/notices/desktop-win.txt@@ -4586,7 +4586,7 @@ SECTION 2: npm packages (902 packages)- [email protected] — MIT — https://github.com/wooorm/zwitch==============================================================================-SECTION 3: cargo packages (292 packages)+SECTION 3: cargo packages (293 packages)==============================================================================- [email protected] — 0BSD OR MIT OR Apache-2.0 — https://github.com/oyvindln/adler2@@ -4606,6 +4606,7 @@ SECTION 3: cargo packages (292 packages)- [email protected] — MIT OR Apache-2.0 — https://github.com/bitflags/bitflags- [email protected] — MIT OR Apache-2.0 — https://github.com/bitflags/bitflags- [email protected] — MIT OR Apache-2.0 — https://github.com/bitflags/bitflags+- [email protected] — MIT OR Apache-2.0 — https://github.com/bitflags/bitflags- [email protected] — MIT OR Apache-2.0 — https://github.com/RustCrypto/utils- [email protected] — BSD-3-Clause AND MIT — https://github.com/dropbox/rust-brotli- [email protected] — BSD-3-Clause OR MIT — https://github.com/dropbox/rust-brotli-decompressor@@ -6089,7 +6090,7 @@ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHERDEALINGS IN THE SOFTWARE.-------------------------------------------------------------------------------[8] Applies to: cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected]+[8] Applies to: cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected], cargo:[email protected]------------------------------------------------------------------------------Apache LicenseVersion 2.0, January 2004diff --git a/docs/legal/notices/sbom/desktop-win.spdx.json b/docs/legal/notices/sbom/desktop-win.spdx.jsonindex 94c5496e87..feac62d8af 100644--- a/docs/legal/notices/sbom/desktop-win.spdx.json+++ b/docs/legal/notices/sbom/desktop-win.spdx.json@@ -3,9 +3,9 @@"dataLicense": "CC0-1.0","SPDXID": "SPDXRef-DOCUMENT","name": "cindy-desktop-win",- "documentNamespace": "https://cindy.app/spdx/desktop-win/3ddb80e258c193e3c9413fb3918c9916e1d463463e69433f164655fea8a64dd6",+ "documentNamespace": "https://cindy.app/spdx/desktop-win/bd303f92c7516f986d25d2b0e8d1678fce0593db824497b4c2462f2f2e1933a4","creationInfo": {- "created": "2026-09-10T10:12:32Z",+ "created": "2026-09-16T04:54:18Z","creators": ["Tool: scripts/generate-third-party-notices.mjs"]@@ -460,6 +460,23 @@}]},+ {+ "name": "bitflags",+ "SPDXID": "SPDXRef-Package-ca671449c7f6168e",+ "versionInfo": "2.13.2",+ "downloadLocation": "https://github.com/bitflags/bitflags",+ "filesAnalyzed": false,+ "licenseConcluded": "MIT OR Apache-2.0",+ "licenseDeclared": "MIT OR Apache-2.0",+ "copyrightText": "NOASSERTION",+ "externalRefs": [+ {+ "referenceCategory": "PACKAGE-MANAGER",+ "referenceType": "purl",+ "referenceLocator": "pkg:cargo/[email protected]"+ }+ ]+ },{"name": "block-buffer","SPDXID": "SPDXRef-Package-2b433e1d401a6c68",@@ -20636,6 +20653,11 @@"relationshipType": "DESCRIBES","relatedSpdxElement": "SPDXRef-Package-ebf2f9b3d70482e9"},+ {+ "spdxElementId": "SPDXRef-DOCUMENT",+ "relationshipType": "DESCRIBES",+ "relatedSpdxElement": "SPDXRef-Package-ca671449c7f6168e"+ },{"spdxElementId": "SPDXRef-DOCUMENT","relationshipType": "DESCRIBES",diff --git a/scripts/generate-third-party-notices.mjs b/scripts/generate-third-party-notices.mjsindex 737301758f..54d619144f 100644--- a/scripts/generate-third-party-notices.mjs+++ b/scripts/generate-third-party-notices.mjs@@ -33,6 +33,7 @@ const MOBILE_DIR = path.join(REPO_ROOT, "apps", "mobile");const NOTICES_DIR = path.join(REPO_ROOT, "docs", "legal", "notices");const SBOM_DIR = path.join(NOTICES_DIR, "sbom");const CARGO_MANIFESTS = [+ path.join(DESKTOP_DIR, "native", "windows-taskbar", "Cargo.toml"),path.join(DESKTOP_DIR, "native", "xbox-gamepad", "windows-gamepad-helper", "Cargo.toml"),path.join(DESKTOP_DIR, "native", "worklouder", "windows-micro-helper", "Cargo.toml"),path.join(DESKTOP_DIR, "native", "remote-desktop", "windows-input", "Cargo.toml"),