A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.
Refactor MultiWindowView to optimize rendering logic and remove unused OpenCode functionality
CristianOlivera1a11a433db2dd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dfc5b06..b620610 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,15 @@ copia la sección de la versión que se publica a la release de GitHub.### English+- A folder or window picker left open no longer re-sends its unchanged visuals+ to the compositor every 50–60 ms: once open, it redraws only when the item+ under the pointer changes, so Windows does no composition work while it rests.+- Fixed island popup edge cases: AI cards stay within the display at high DPI,+ with clipped scrolling and reachable buttons. Volume drags cancel safely when+ the layout changes; audio-only updates reuse current system/provider data.+ Popups without room for their trigger close, repeated refresh clicks are+ disabled while busy, and failed media reads no longer retain the previous song.+ Scrolling reuses GPU visuals without extra idle polling or quota requests.- Music now shows circular Windows media artwork in the island and its popup,with a bundled offline fallback. The popup adds system volume and mute controls;the thumb and percentage respond immediately, with coalesced audio writes and@@ -65,15 +74,14 @@ copia la sección de la versión que se publica a la release de GitHub.last reading for 30 minutes while it sleeps, as Logitech's own tools do, andeach request waits longer for a reply over the radio. Unplugging thereceiver still removes it at once.-- OpenCode now distinguishes Go quotas from Zen's estimated cost on this device- over the last 30 days. Both appear in one theme-aware card; Go also shows its- monthly window. Zen opens the official Console for the real account balance,- which is not exposed by its public API. Local history is read only, bounded,- and refreshed by the existing worker without extra background polling.+- OpenCode shows only measured Go quotas and their reset times, including the+ monthly window. Zen's local spending estimate and balance link are removed,+ together with the history queries and bundled SQLite dependency. A Zen-only+ connection shows no OpenCode indicator; missing quota data never becomes 0%.- Fixed OpenCode Go account discovery: read its `opencode-go` credential, respect`XDG_DATA_HOME`, and fall back from an empty environment key to the saved login.- The usage card now identifies Go explicitly and provides a working connection- guide button instead of an inert sign-in instruction.+ Only saved Go keys or an explicit environment key are used for quota requests;+ saved Zen keys are not queried.- Fixed a blocking "Ordinal 381 Not Found" system dialog when launching applicationswith Uninstall Tool (`utshellext.dll`) or other third-party shell extensions installed(issue #23). `muelle.exe` now embeds an application manifest declaring a dependency on@@ -88,6 +96,16 @@ copia la sección de la versión que se publica a la release de GitHub.### Español+- Una carpeta o un selector de ventanas abierto ya no reenvía al compositor sus+ visuales sin cambios cada 50–60 ms: una vez abierto, solo se redibuja cuando+ cambia el elemento bajo el puntero, así que Windows no compone nada mientras reposa.+- Corregidos casos límite de los popups: las tarjetas de IA caben en la pantalla+ con escala alta, con desplazamiento y botones limitados al área visible. El+ arrastre de volumen se cancela si cambia su posición; los cambios de audio+ reutilizan los datos del sistema y proveedores. Los popups sin espacio para+ su acceso se cierran, actualizar se desactiva mientras está ocupado y los+ errores de lectura multimedia no conservan la pista anterior. Desplazar la+ lista reutiliza visuales GPU, sin sondeo en reposo ni consultas de cuota extra.- La isla y el popup de música muestran la carátula circular de Windows, conuna imagen incluida como respaldo. El popup incorpora volumen del sistema ysilencio: tirador y porcentaje responden al instante, reutilizando sus visuales@@ -167,13 +185,12 @@ copia la sección de la versión que se publica a la release de GitHub.- Corregida la detección de cuentas OpenCode Go: se lee la credencial `opencode-go`,se respeta `XDG_DATA_HOME` y una variable de clave vacía permite usar la sesión- guardada. La tarjeta identifica Go e incluye un botón funcional con instrucciones- de conexión, en lugar de un texto de inicio de sesión sin acción.-- OpenCode distingue las cuotas de Go del gasto estimado de Zen en este equipo- durante los últimos 30 días, en una misma tarjeta que respeta el tema. Go muestra- también su ventana mensual. Zen permite abrir la consola oficial para consultar- el saldo real, que no expone su API pública. El historial se lee sin modificarlo,- con límites de trabajo y usando el worker e intervalo existentes.+ guardada. Las consultas usan únicamente la clave guardada de Go o una clave+ explícita de entorno; no se consulta con claves guardadas de Zen.+- OpenCode muestra solo cuotas medidas de Go y sus reinicios, incluido el mes.+ Se retiran el gasto local de Zen y el enlace al saldo, las consultas al historial+ y la dependencia SQLite. Una conexión solo Zen no muestra el indicador de+ OpenCode; la ausencia de cuotas nunca se convierte en 0 %.- Los manifiestos de WinGet usan `/S` en ambos modos desatendidos y declaranlas dependencias de Visual C++ x64 y WebView2. Se corrigen riesgos de interfazen la primera instalación y de runtimes ausentes; falta revalidar con Microsoft.diff --git a/Cargo.lock b/Cargo.lockindex ec09fbd..69406c5 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1026,18 +1026,6 @@ dependencies = ["pin-project-lite",]-[[package]]-name = "fallible-iterator"-version = "0.3.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"--[[package]]-name = "fallible-streaming-iterator"-version = "0.1.9"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"-[[package]]name = "fastrand"version = "2.5.0"@@ -2129,17 +2117,6 @@ dependencies = ["libc",]-[[package]]-name = "libsqlite3-sys"-version = "0.40.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b06e69070b7e12262b0cd90832f0a7396f142a2b330181255562decf9f0c6215"-dependencies = [- "cc",- "pkg-config",- "vcpkg",-]-[[package]]name = "linux-raw-sys"version = "0.12.1"@@ -2285,7 +2262,6 @@ dependencies = ["muelle-shell","png","reqwest",- "rusqlite","serde","serde_json","windows",@@ -3240,19 +3216,6 @@ dependencies = ["windows-sys 0.52.0",]-[[package]]-name = "rusqlite"-version = "0.43.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f172c4812a19b26d1c23cdb0070e69db335503dfa378b910eb857386e5b8beba"-dependencies = [- "bitflags 2.13.2",- "fallible-iterator",- "fallible-streaming-iterator",- "libsqlite3-sys",- "smallvec",-]-[[package]]name = "rustc-hash"version = "2.1.3"@@ -4776,12 +4739,6 @@ dependencies = ["wasm-bindgen",]-[[package]]-name = "vcpkg"-version = "0.2.15"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"-[[package]]name = "version-compare"version = "0.2.1"diff --git a/apps/dock/Cargo.toml b/apps/dock/Cargo.tomlindex 305ba67..d9ddd14 100644--- a/apps/dock/Cargo.toml+++ b/apps/dock/Cargo.toml@@ -21,7 +21,6 @@ muelle-core.workspace = truemuelle-shell.workspace = truepng = "0.18"reqwest = { version = "0.13", default-features = false, features = ["blocking", "rustls", "system-proxy"] }-rusqlite = { version = "0.43", default-features = false, features = ["bundled", "hooks", "limits"] }serde.workspace = trueserde_json = "1"windows-core.workspace = truediff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rsindex 60abaf3..e7154e6 100644--- a/apps/dock/src/app.rs+++ b/apps/dock/src/app.rs@@ -4652,6 +4652,13 @@ pub fn menu_bar_volume_press(x: f32, y: f32) {});}+pub fn menu_bar_scrolled(point: POINT, delta: i16) -> bool {+ with_app_value("desplazar uso de IA", |app| match &mut app.menubar {+ Some(bar) => bar.scroll_usage_at(point, delta),+ None => Ok(false),+ })+}+pub fn menu_bar_volume_release(x: Option<f32>) -> bool {with_app_value("volumen", |app| match &mut app.menubar {Some(bar) => bar.release_volume(x),diff --git a/apps/dock/src/group_view.rs b/apps/dock/src/group_view.rsindex 9c9bb71..694a58f 100644--- a/apps/dock/src/group_view.rs+++ b/apps/dock/src/group_view.rs@@ -354,6 +354,10 @@ pub struct GroupView {pressed: Option<(usize, POINT)>,mouse_was_down: bool,foreground: isize,+ /// The app lit when the unfolded view was last drawn. Once unfolded, only+ /// that changes what it shows, so a tick that finds it the same touches+ /// nothing: no composition batch and no DWM work while the view rests.+ drawn: Option<Option<usize>>,}impl GroupView {@@ -413,6 +417,7 @@ impl GroupView {scale: place.scale,theme: place.theme,opened: Instant::now(),+ drawn: None,animated: animations_enabled(),pressed: None,mouse_was_down: false,@@ -613,14 +618,37 @@ impl GroupView {((self.anchor.left + self.anchor.right) / 2 - self.layout.bounds.left) as f32,(self.anchor.top - self.layout.bounds.top) as f32,);- let mut moving = false;+ // The last app starts unfolding last; the panel fades in with the first.+ let last_start = self.visuals.len().saturating_sub(1) as f32 * STAGGER_SECONDS;+ let moving = self.animated && elapsed < last_start + OPEN_SECONDS;+ if moving || self.drawn != Some(lit) {+ self.draw(elapsed, start, lit)?;+ }+ self.drawn = (!moving).then_some(lit);+ // Quick while unfolding; then just often enough to follow the pointer.+ // SAFETY: Our own timer; setting it again replaces it.+ unsafe {+ SetTimer(+ Some(self.hwnd),+ TIMER,+ if moving || self.pressed.is_some() {+ 16+ } else {+ 50+ },+ None,+ )+ };+ Ok(())+ }++ fn draw(&self, elapsed: f32, start: (f32, f32), lit: Option<usize>) -> Result<()> {for (index, (visual, icon)) in self.visuals.iter().zip(&self.layout.icons).enumerate() {let progress = if self.animated {((elapsed - index as f32 * STAGGER_SECONDS) / OPEN_SECONDS).clamp(0.0, 1.0)} else {1.0};- moving |= progress < 1.0;let eased = 1.0 - (1.0 - progress).powi(3);let side = (icon.right - icon.left) as f32;let (left, top) = (icon.left as f32, icon.top as f32);@@ -653,20 +681,6 @@ impl GroupView {};panel.SetOpacity(1.0 - (1.0 - progress).powi(3))?;}- // Quick while unfolding; then just often enough to follow the pointer.- // SAFETY: Our own timer; setting it again replaces it.- unsafe {- SetTimer(- Some(self.hwnd),- TIMER,- if moving || self.pressed.is_some() {- 16- } else {- 50- },- None,- )- };Ok(())}diff --git a/apps/dock/src/media.rs b/apps/dock/src/media.rsindex 3801de9..a031a6c 100644--- a/apps/dock/src/media.rs+++ b/apps/dock/src/media.rs@@ -242,6 +242,10 @@ impl Current {}fn update_track(&mut self) {+ // A failed read belongs to this metadata change, not to the previous+ // song. Never pair yesterday's title/artist with the current session.+ self.title.clear();+ self.artist.clear();self.artwork = None;if let Some(properties) = self.sessiondiff --git a/apps/dock/src/menubar.rs b/apps/dock/src/menubar.rsindex 13243cf..28ba553 100644--- a/apps/dock/src/menubar.rs+++ b/apps/dock/src/menubar.rs@@ -59,9 +59,10 @@ use windows::{PBT_POWERSETTINGCHANGE, PostMessageW, RegisterClassW, SWP_HIDEWINDOW, SWP_NOACTIVATE,SWP_SHOWWINDOW, SetCursor, SetTimer, SetWindowPos, SetWindowsHookExW,UnhookWindowsHookEx, WH_MOUSE_LL, WM_APP, WM_CAPTURECHANGED, WM_LBUTTONDOWN,- WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MOUSEMOVE, WM_NCHITTEST, WM_RBUTTONDOWN, WM_SETCURSOR,- WM_SETTINGCHANGE, WM_TIMECHANGE, WM_TIMER, WM_XBUTTONDOWN, WNDCLASSW, WS_EX_NOACTIVATE,- WS_EX_NOREDIRECTIONBITMAP, WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,+ WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_NCHITTEST,+ WM_RBUTTONDOWN, WM_SETCURSOR, WM_SETTINGCHANGE, WM_TIMECHANGE, WM_TIMER,+ WM_XBUTTONDOWN, WNDCLASSW, WS_EX_NOACTIVATE, WS_EX_NOREDIRECTIONBITMAP,+ WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_POPUP,},},core::{BOOL, Interface, h, w},@@ -249,18 +250,32 @@ fn accessory_readings(snapshot: &AccessorySnapshot) -> [Option<AccessoryReading>}impl Look {- fn panel_height(&self) -> f32 {+ fn panel_content_height(&self) -> f32 {match self.panel {Some(Island::Music) => 184.0,Some(Island::Usage) => {- 74.0 + island_providers(self)- .iter()- .map(|(_, usage, _)| usage_row_height(usage))+ 74.0 + Provider::ALL+ .into_iter()+ .filter(|provider| self.active_providers.has(*provider))+ .map(|provider| usage_row_height(self.usage.get(provider))).sum::<f32>()}None => 0.0,}}++ fn panel_height(&self) -> f32 {+ let natural = self.panel_content_height();+ if self.panel == Some(Island::Usage) {+ let available = (self.screen.bottom - self.screen.top) as f32 / self.scale+ - HEIGHT+ - PANEL_GAP+ - PANEL_SHADOW_MARGIN;+ natural.min(available.max(0.0))+ } else {+ natural+ }+ }}#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -269,7 +284,7 @@ enum Island {Usage,}-#[derive(Clone, Copy, Default)]+#[derive(Clone, Copy, Default, PartialEq)]struct Span {left: f32,right: f32,@@ -288,15 +303,26 @@ enum IslandAction {Volume(Span),Mute,Refresh,- OpenCodeConnectionHelp,- OpenCodeConsole,+ ScrollUsage(i8),}+#[derive(Clone, Copy)]struct IslandHit {bounds: (f32, f32, f32, f32),action: IslandAction,}+/// A retained, clipped body. Wheel/arrow input only changes its transform and+/// arrow opacity; no quota queries or redraws.+struct UsageViewport {+ content: ContainerVisual,+ maximum: f32,+ scale: f32,+ bounds: (f32, f32, f32, f32),+ up: SpriteVisual,+ down: SpriteVisual,+}+impl IslandHit {fn at(&self, x: f32, y: f32) -> bool {let (left, top, right, bottom) = self.bounds;@@ -407,6 +433,8 @@ pub struct MenuBar {pending_volume: Option<u8>,volume_target: Option<u8>,volume_controls: Option<VolumeControls>,+ usage_scroll: f32,+ usage_viewport: Option<UsageViewport>,suppress_volume_release: bool,panel: Option<Island>,visual_height: i32,@@ -444,6 +472,17 @@ unsafe extern "system" fn bar_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -app::menu_bar_pointer_moved(f32::from(x), f32::from(y));}WM_MOUSELEAVE => app::menu_bar_check_pointer(),+ WM_MOUSEWHEEL => {+ let delta = (w.0 >> 16) as u16 as i16;+ let point = POINT {+ x: (l.0 & 0xFFFF) as i16 as i32,+ y: (l.0 >> 16) as i16 as i32,+ };+ if app::menu_bar_scrolled(point, delta) {+ return LRESULT(0);+ }+ return unsafe { DefWindowProcW(hwnd, msg, w, l) };+ }WM_TIMER if w.0 == POINTER_TIMER => app::menu_bar_check_pointer(),WM_TIMER if w.0 == VOLUME_TIMER => app::menu_bar_volume_flush(),WM_CAPTURECHANGED => {@@ -787,7 +826,7 @@ fn draw_usage_row(add_panel_text(gfx,layers,- usage.name(provider),+ provider.name(),left + px(53.0),y + px(10.0),scale,@@ -800,11 +839,7 @@ fn draw_usage_row(add_panel_text(gfx,layers,- &if provider == Provider::OpenCode {- format!("Go · {}", main.title())- } else {- main.title()- },+ &main.title(),left + px(53.0),y + px(30.0),scale,@@ -941,13 +976,9 @@ fn draw_usage_row()?;}}- } else if !usage- .opencode- .is_some_and(|details| !details.go && details.zen)- {+ } else {let message = match usage.state {State::Loading => text.usage_loading,- State::SignIn if provider == Provider::OpenCode => text.usage_opencode_connect,State::SignIn => text.usage_sign_in,State::Ready | State::Unavailable => text.usage_unavailable,};@@ -964,81 +995,11 @@ fn draw_usage_row(0.72,)?;}- if let Some(details) = usage.opencode.filter(|details| details.zen) {- let offset = zen_row_offset(usage);- add_panel_text(- gfx,- layers,- text.usage_zen_local,- left + px(14.0),- y + px(offset),- scale,- 11.0,- false,- ink,- 0.78,- )?;- if let Some(spend) = details.spend {- add_panel_text_right(- gfx,- layers,- &spend.amount(),- right - px(14.0),- y + px(offset + 19.0),- scale,- 16.0,- true,- ink,- 1.0,- )?;- } else {- add_panel_text_right(- gfx,- layers,- text.usage_no_local,- right - px(14.0),- y + px(offset + 21.0),- scale,- 11.0,- false,- ink,- 0.7,- )?;- }- add_panel_text(- gfx,- layers,- text.usage_device_scope,- left + px(14.0),- y + px(offset + 43.0),- scale,- 10.5,- false,- ink,- 0.65,- )?;- }Ok(())}-fn quota_row_height(usage: &ProviderUsage) -> f32 {- ISLAND_ROW_HEIGHT + usage.windows.len().saturating_sub(2) as f32 * 26.0-}--fn zen_row_offset(usage: &ProviderUsage) -> f32 {- if usage.opencode.is_some_and(|details| details.go) {- quota_row_height(usage) - 5.0- } else {- 50.0- }-}-fn usage_row_height(usage: &ProviderUsage) -> f32 {- if usage.opencode.is_some_and(|details| details.zen) {- zen_row_offset(usage) + 102.0- } else {- quota_row_height(usage)- }+ ISLAND_ROW_HEIGHT + usage.windows.len().saturating_sub(2) as f32 * 26.0}impl MenuBar {@@ -1135,6 +1096,8 @@ impl MenuBar {pending_volume: None,volume_target: None,volume_controls: None,+ usage_scroll: 0.0,+ usage_viewport: None,suppress_volume_release: false,panel: None,visual_height: 0,@@ -1636,8 +1599,8 @@ impl MenuBar {self.refresh(gfx)}- /// Audio notifications never requery the network, registry, providers or- /// clock. A default-device change still restarts the accessory reader.+ /// Ordinary audio notifications do not requery network, registry, providers+ /// or clock. A default-device change still restarts enabled accessories.pub fn audio_changed(&mut self, gfx: &Gfx) -> Result<()> {let volume = self.audio.as_mut().and_then(AudioWatch::volume);if self@@ -1667,9 +1630,13 @@ impl MenuBar {}return Ok(());}- // Availability, mute and speaker-glyph changes affect the status bar's- // layout. Those rare transitions continue through the normal renderer.- self.refresh(gfx)+ // Availability, mute and speaker-glyph changes affect layout, but do+ // not justify a new provider/process or system-status scan either.+ let Some(mut look) = self.look.clone() else {+ return self.refresh(gfx);+ };+ look.status.volume = volume;+ self.apply_look(gfx, look)}fn update_status(&mut self) {@@ -1719,20 +1686,6 @@ impl MenuBar {usage.refresh(true);}}- IslandAction::OpenCodeConnectionHelp => {- // Shell extensions and browser activation run in the- // existing disposable worker, never on the bar's UI thread.- crate::shell_work::dispatch(crate::shell_work::Action::Open {- id: "https://opencode.ai/docs/providers/".to_owned(),- })- .inspect_err(|_| crate::shell_work::notify_not_started())?;- }- IslandAction::OpenCodeConsole => {- crate::shell_work::dispatch(crate::shell_work::Action::Open {- id: "https://opencode.ai/console".to_owned(),- })- .inspect_err(|_| crate::shell_work::notify_not_started())?;- }IslandAction::Media(control) => {if let Some(media) = &self.media&& let Some(track) = self.look.as_ref().and_then(|look| look.track.as_ref())@@ -1746,7 +1699,11 @@ impl MenuBar {if let Some(audio) = &mut self.audio {audio.toggle_mute()?;}- self.update_status();+ return self.audio_changed(gfx);+ }+ IslandAction::ScrollUsage(direction) => {+ self.scroll_usage(f32::from(direction) * 72.0)?;+ return Ok(());}}return self.refresh(gfx);@@ -1865,8 +1822,19 @@ impl MenuBar {self.apply_look(gfx, look)}- fn apply_look(&mut self, gfx: &Gfx, look: Look) -> Result<()> {- if look.panel != Some(Island::Music) {+ fn apply_look(&mut self, gfx: &Gfx, mut look: Look) -> Result<()> {+ look.active_providers = look.usage.visible_providers(look.active_providers);+ look.usage_enabled &= look.active_providers.any();+ self.panel = available_panel(look.panel, look.track.is_some(), look.usage_enabled);+ look.panel = self.panel;+ if look.panel != Some(Island::Usage) {+ self.usage_scroll = 0.0;+ }+ let moved = self+ .look+ .as_ref()+ .is_some_and(|old| old.screen != look.screen || old.scale != look.scale);+ if look.panel != Some(Island::Music) || moved {self.release_volume(None)?;}if self.look.as_ref() == Some(&look) {@@ -1877,6 +1845,13 @@ impl MenuBar {.as_ref().and_then(|old| usage_moment(&old.usage, &look.usage, &look.active_providers));self.build(gfx, &look)?;+ // A crowded bar can have no room even for a compact trigger. Do not+ // keep a ghost popup that reappears by itself when space returns.+ if look.panel.is_some() && self.panel_span.width() <= 0.0 {+ self.panel = None;+ look.panel = None;+ self.build(gfx, &look)?;+ }self.look = Some(look);if let Some((provider, act)) = moment&& let Some(&(_, x)) = self.usage_anchors.iter().find(|(p, _)| *p == provider)@@ -2102,9 +2077,19 @@ impl MenuBar {self.island_hits.clear();self.volume_controls = None;+ self.usage_viewport = None;self.triggers_span = Span::default();self.panel_span = Span::default();self.draw_island(gfx, look, &layers, width, height, left_end, right)?;+ if let Some(drag) = self.volume_drag {+ let new_span = self.island_hits.iter().find_map(|hit| match hit.action {+ IslandAction::Volume(span) => Some(span),+ _ => None,+ });+ if new_span != Some(drag) {+ self.release_volume(None)?;+ }+ }self.surface.SetSize(Vector2 {X: width,Y: visual_height,@@ -2399,21 +2384,38 @@ impl MenuBar {button_label.width,button_label.height,)?;- self.island_hits.push(geometry.hit(- button_left,- button_top,- button_width,- button_height,- IslandAction::Refresh,- ));- let mut row_top = 48.0;+ if !look.usage_refreshing {+ self.island_hits.push(geometry.hit(+ button_left,+ button_top,+ button_width,+ button_height,+ IslandAction::Refresh,+ ));+ }+ let body_top = px(42.0);+ let body_height = (island_height - body_top - px(26.0)).max(0.0);+ let content_height = px((look.panel_content_height() - 68.0).max(0.0));+ let maximum = ((content_height - body_height) / scale).max(0.0);+ self.usage_scroll = self.usage_scroll.clamp(0.0, maximum);+ let viewport = c.CreateContainerVisual()?;+ viewport.SetOffset(Vector3::new(0.0, body_top, 0.0))?;+ viewport.SetSize(Vector2::new(island_width, body_height))?;+ viewport.SetClip(&c.CreateInsetClip()?)?;+ let body = c.CreateContainerVisual()?;+ body.SetSize(Vector2::new(island_width, content_height))?;+ body.SetOffset(Vector3::new(0.0, -px(self.usage_scroll), 0.0))?;+ viewport.Children()?.InsertAtTop(&body)?;+ content.InsertAtTop(&viewport)?;+ let rows = body.Children()?;+ let mut row_top = 6.0;for (provider, usage, accent) in providers {let y = px(row_top);row_top += usage_row_height(usage);let inset = px(23.0);add_visual(c,- content,+ &rows,&c.CreateColorBrushWithColor(geometry.border())?.cast()?,inset,y - px(6.0),@@ -2422,7 +2424,7 @@ impl MenuBar {)?;draw_usage_row(gfx,- content,+ &rows,*provider,usage,*accent,@@ -2431,46 +2433,47 @@ impl MenuBar {island_width,y,)?;- let connection = (*provider == Provider::OpenCode && usage.state == State::SignIn)- .then_some((- title.usage_connection_help,- 65.0,- IslandAction::OpenCodeConnectionHelp,- ));- let console = usage.opencode.filter(|details| details.zen).map(|_| {- (- title.usage_open_console,- zen_row_offset(usage) + 67.0,- IslandAction::OpenCodeConsole,- )- });- for (text, offset, action) in connection.into_iter().chain(console) {- let label = gfx.text_brush_sized(text, scale, 11.0, true, ink)?;- let (left, top) = (px(37.0), y + px(offset));- let (width, height) = (label.width + px(20.0), px(25.0));- add_rounded_box(- c,- content,- left,- top,- width,- height,- px(12.5),- geometry.control_fill(),- Some(geometry.border()),- )?;- add_visual(+ }+ let bounds = (+ geometry.left,+ geometry.top + body_top,+ geometry.left + island_width,+ geometry.top + body_top + body_height,+ );+ if maximum > 0.0 {+ let [up, down] = [+ ('\u{E70E}', body_top + px(2.0), -1),+ ('\u{E70D}', body_top + body_height - px(22.0), 1),+ ]+ .map(|(symbol, top, direction)| -> Result<SpriteVisual> {+ let label = gfx.glyph_brush(&[(symbol, 1.0)], scale * 0.7, ink)?;+ let visual = add_visual(c,content,&label.brush.cast()?,- left + px(10.0),- top + (height - label.height) / 2.0,+ island_width - px(22.0) + (px(18.0) - label.width) / 2.0,+ top + (px(20.0) - label.height) / 2.0,label.width,label.height,)?;- self.island_hits- .push(geometry.hit(left, top, width, height, action));- }+ self.island_hits.push(geometry.hit(+ island_width - px(22.0),+ top,+ px(18.0),+ px(20.0),+ IslandAction::ScrollUsage(direction),+ ));+ Ok(visual)+ });+ self.usage_viewport = Some(UsageViewport {+ content: body,+ maximum,+ scale,+ bounds,+ up: up?,+ down: down?,+ });+ self.position_usage_body()?;}let newest_age = providers.iter()@@ -2771,6 +2774,57 @@ impl MenuBar {self.paint_volume_preview(gfx)}+ pub fn scroll_usage_at(&mut self, point: POINT, delta: i16) -> Result<bool> {+ if !self.visible || (self.auto_hide && !self.revealed) || delta == 0 {+ return Ok(false);+ }+ let Some(viewport) = &self.usage_viewport else {+ return Ok(false);+ };+ let (x, y) = (+ (point.x - self.bounds.left) as f32,+ (point.y - self.bounds.top) as f32,+ );+ let (left, top, right, bottom) = viewport.bounds;+ if x < left || x >= right || y < top || y >= bottom {+ return Ok(false);+ }+ self.scroll_usage(-f32::from(delta) / 120.0 * 48.0)+ }++ fn scroll_usage(&mut self, delta: f32) -> Result<bool> {+ let Some(viewport) = &self.usage_viewport else {+ return Ok(false);+ };+ let next = (self.usage_scroll + delta).clamp(0.0, viewport.maximum);+ if next != self.usage_scroll {+ self.usage_scroll = next;+ self.position_usage_body()?;+ }+ Ok(true)+ }++ fn position_usage_body(&mut self) -> Result<()> {+ let Some(viewport) = &self.usage_viewport else {+ return Ok(());+ };+ let offset = (self.usage_scroll * viewport.scale).round();+ viewport+ .content+ .SetOffset(Vector3::new(0.0, -offset, 0.0))?;+ viewport+ .up+ .SetOpacity(if self.usage_scroll > 0.0 { 0.8 } else { 0.22 })?;+ viewport+ .down+ .SetOpacity(if self.usage_scroll < viewport.maximum {+ 0.8+ } else {+ 0.22+ })?;+ Ok(())+ }+fn paint_volume_preview(&mut self, gfx: &Gfx) -> Result<()> {if let Some(percent) = self.volume_target&& let Some(controls) = &mut self.volume_controls@@ -3374,9 +3428,7 @@ fn draw_compact_usage()?;}}- if half >= px(84.0)- && (usage.main_window().is_some() || usage.opencode.is_none_or(|details| !details.zen))- {+ if half >= px(84.0) {let ring = gfx.usage_ring(usage.main_window().map(|window| window.used_percent),scale,@@ -3656,6 +3708,193 @@ impl Drop for MenuBar {mod island_tests {use super::*;+ #[test]+ #[ignore = "Native popup layout/input regression; hidden window, no audio writes"]+ fn native_popup_overflow_and_layout_changes_keep_input_in_sync() -> Result<()> {+ use anyhow::Context;+ use windows::Win32::System::WinRT::{+ CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT,+ DispatcherQueueOptions,+ };+ // SAFETY: All composition objects stay on this test's STA thread.+ let _queue = unsafe {+ CreateDispatcherQueueController(DispatcherQueueOptions {+ dwSize: size_of::<DispatcherQueueOptions>() as u32,+ threadType: DQTYPE_THREAD_CURRENT,+ apartmentType: DQTAT_COM_STA,+ })?+ };+ let gfx = Gfx::new()?;+ let mut bar = MenuBar::create(&gfx, false, false, true, MenuBarWidgets::default())?;+ bar.set_visible(false)?;+ bar.audio = None;+ let mut look = bar.look.clone().context("initial look")?;+ look.screen = RECT {+ left: -1920,+ top: -768,+ right: 0,+ bottom: 0,+ };+ look.track = None;+ look.panel = Some(Island::Usage);+ look.usage_enabled = true;+ look.active_providers.0.fill(true);+ for provider in Provider::ALL {+ look.usage.providers[provider as usize] = ProviderUsage {+ state: State::Ready,+ windows: [300, 10_080]+ .into_iter()+ .map(|minutes| usage::Window {+ label: None,+ minutes,+ used_percent: 30,+ resets_at: None,+ })+ .collect(),+ fetched_at: Some(std::time::SystemTime::now()),+ };+ }+ let opencode = &mut look.usage.providers[Provider::OpenCode as usize];+ opencode.windows.push(usage::Window {+ label: None,+ minutes: 43_200,+ used_percent: 10,+ resets_at: None,+ });+ for style in [IslandStyle::Notch, IslandStyle::Bubble] {+ look.widgets.island_style = style;+ for scale in [1.0, 1.5, 2.0] {+ look.scale = scale;+ for light in [false, true] {+ look.light = light;+ bar.usage_scroll = 0.0;+ bar.build(&gfx, &look)?;+ assert!(bar.visual_height <= 769, "popup must fit a 768 px display");+ if scale == 1.0 {+ assert!(bar.usage_viewport.is_none());+ continue;+ }+ let viewport = bar+ .usage_viewport+ .as_ref()+ .context("overflow needs a viewport")?;+ let bounds = viewport.bounds;+ let maximum = viewport.maximum;+ assert!(maximum > 0.0);+ let body = viewport.content.clone();+ let down = viewport.down.clone();+ let root = bar.surface.Children()?.First()?.Current()?;+ for _ in 0..20 {+ assert!(bar.scroll_usage(48.0)?);+ }+ assert_eq!(bar.surface.Children()?.First()?.Current()?, root);+ assert_eq!(bar.usage_scroll, maximum);+ assert_eq!(body.Offset()?.Y, -(maximum * scale).round());+ assert_eq!(down.Opacity()?, 0.22);+ let up = bar+ .island_hits+ .iter()+ .find(|hit| matches!(hit.action, IslandAction::ScrollUsage(-1)))+ .context("scroll up button")?;+ let (left, top, right, bottom) = up.bounds;+ assert!(+ left >= bounds.0+ && top >= bounds.1+ && right <= bounds.2+ && bottom <= bounds.3+ );+ bar.click(&gfx, (left + right) / 2.0, (top + bottom) / 2.0)?;+ assert!(bar.usage_scroll < maximum);+ assert_eq!(bar.surface.Children()?.First()?.Current()?, root);+ assert!(bar.scroll_usage(-10_000.0)?);+ assert_eq!(bar.usage_scroll, 0.0);+ }+ }+ }+ // A busy refresh is not another active input target.+ look.usage_refreshing = true;+ bar.build(&gfx, &look)?;+ assert!(+ !bar.island_hits+ .iter()+ .any(|hit| matches!(hit.action, IslandAction::Refresh))+ );+ look.usage_refreshing = false;+ bar.scroll_usage(10_000.0)?;+ look.active_providers.0.fill(false);+ look.active_providers.0[Provider::Codex as usize] = true;+ bar.build(&gfx, &look)?;+ assert_eq!(bar.usage_scroll, 0.0); // A refresh that removes rows clamps the offset.+ assert!(bar.usage_viewport.is_none());++ look.panel = Some(Island::Music);+ look.track = Some(Track::test_fixture());+ bar.panel = look.panel;+ bar.status.volume = Some(Volume {+ level: 2,+ muted: false,+ percent: 50,+ });+ bar.apply_look(&gfx, look.clone())?;+ bar.apply_volume_reading(+ &gfx,+ Some(Volume {+ level: 0,+ muted: true,+ percent: 0,+ }),+ )?;+ // Mute/glyph changes render the current snapshot; a full refresh would+ // replace this monitor and scan live processes/system status again.+ assert!(+ bar.look+ .as_ref()+ .is_some_and(|current| current.screen == look.screen+ && current.status.volume.is_some_and(|volume| volume.muted))+ );+ let span = bar+ .island_hits+ .iter()+ .find_map(|hit| match hit.action {+ IslandAction::Volume(span) => Some(span),+ _ => None,+ })+ .context("slider")?;+ bar.volume_drag = Some(span); // Never capture the user's mouse in a test.+ bar.queue_volume(span, span.left);+ look.scale = 1.5;+ bar.apply_look(&gfx, look.clone())?;+ assert!(+ bar.volume_drag.is_none()+ && bar.pending_volume.is_none()+ && bar.volume_target.is_none()+ );+ assert!(bar.release_volume(Some(span.right))?); // Late up must not activate another button.+ let span = bar+ .island_hits+ .iter()+ .find_map(|hit| match hit.action {+ IslandAction::Volume(span) => Some(span),+ _ => None,+ })+ .context("new slider")?;+ bar.volume_drag = Some(span);+ bar.queue_volume(span, span.right);+ look.active_providers.0.fill(true); // Changes popup placement without changing monitor/DPI.+ bar.apply_look(&gfx, look.clone())?;+ assert!(bar.volume_drag.is_none() && bar.pending_volume.is_none());++ // A trigger that cannot fit must not leave a latent open popup.+ look.screen.right = look.screen.left + 160;+ bar.apply_look(&gfx, look.clone())?;+ assert!(bar.panel.is_none() && bar.look.as_ref().is_some_and(|look| look.panel.is_none()));+ let mut wide = bar.look.clone().context("crowded look")?;+ wide.screen.right = wide.screen.left + 1920;+ bar.apply_look(&gfx, wide)?;+ assert!(bar.panel_span.width() <= 0.0 && bar.usage_viewport.is_none());+ Ok(())+ }+#[test]fn volume_coordinates_clamp_and_round_at_both_ends() {let span = Span {@@ -3720,7 +3959,7 @@ mod island_tests {})?};let gfx = Gfx::new()?;- let mut bar = MenuBar::create(&gfx, true, false, false, MenuBarWidgets::default())?;+ let mut bar = MenuBar::create(&gfx, false, false, true, MenuBarWidgets::default())?;bar.set_visible(false)?;bar.audio = None; // This fixture can never change the user's audio.bar.status.volume = Some(Volume {@@ -3872,13 +4111,14 @@ mod island_tests {}#[test]- #[ignore = "Requires Windows desktop composition; keeps the test bar hidden"]- fn opencode_connection_help_is_clickable_and_inactive_codex_stays_hidden() -> Result<()> {+ #[ignore = "Requires Windows composition; hidden window and no provider requests"]+ fn opencode_only_measured_go_appears_in_both_island_styles() -> Result<()> {use anyhow::Context;use windows::Win32::System::WinRT::{CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT,DispatcherQueueOptions,};+ // SAFETY: The dispatcher and hidden composition objects belong to this thread.let _queue = unsafe {CreateDispatcherQueueController(DispatcherQueueOptions {dwSize: size_of::<DispatcherQueueOptions>() as u32,@@ -3887,21 +4127,13 @@ mod island_tests {})?};let gfx = Gfx::new()?;- let mut bar = MenuBar::create(&gfx, false, true, true, MenuBarWidgets::default())?;+ let mut bar = MenuBar::create(&gfx, false, false, true, MenuBarWidgets::default())?;bar.set_visible(false)?;- let mut look = bar.look.clone().context("missing initial look")?;+ let mut look = bar.look.clone().context("initial look")?;look.track = None;- look.panel = Some(Island::Usage);- look.usage_enabled = true;look.active_providers = ActiveProviders::default();look.active_providers.0[Provider::OpenCode as usize] = true;- look.usage.providers[Provider::OpenCode as usize] = ProviderUsage {- state: State::SignIn,- windows: Vec::new(),- fetched_at: None,- opencode: None,- };- // Yesterday's saved reading is not evidence that Codex is running now.+ // Yesterday's saved quota is not evidence that Codex is running now.look.usage.providers[Provider::Codex as usize] = ProviderUsage {state: State::Ready,windows: vec![usage::Window {@@ -3911,102 +4143,65 @@ mod island_tests {resets_at: None,}],fetched_at: Some(std::time::SystemTime::now() - Duration::from_secs(24 * 60 * 60)),- opencode: None,};- assert!(- island_providers(&look)- .iter()- .all(|entry| entry.0 == Provider::OpenCode)- );- for scale in [1.0, 1.25, 1.5, 2.0] {- for light in [false, true] {+ let quota: Vec<_> = [300, 10_080, 43_200]+ .into_iter()+ .map(|minutes| usage::Window {+ label: None,+ minutes,+ used_percent: 15,+ resets_at: Some(chrono::Utc::now() + chrono::Duration::hours(2)),+ })+ .collect();+ for style in [IslandStyle::Notch, IslandStyle::Bubble] {+ look.widgets.island_style = style;+ for scale in [1.0, 1.25, 1.5, 2.0] {look.scale = scale;- look.light = light;- bar.build(&gfx, &look)?;- let hit = bar- .island_hits- .iter()- .find(|hit| matches!(hit.action, IslandAction::OpenCodeConnectionHelp))- .context("OpenCode connection help has no click target")?;- let (left, top, right, bottom) = hit.bounds;- let first = bar- .island_hits- .iter()- .find(|hit| hit.at((left + right) / 2.0, (top + bottom) / 2.0))- .context("connection help cannot be clicked")?;- assert!(matches!(first.action, IslandAction::OpenCodeConnectionHelp));- }- }- look.usage.providers[Provider::OpenCode as usize].state = State::Ready;- bar.build(&gfx, &look)?;- assert!(- !bar.island_hits- .iter()- .any(|hit| matches!(hit.action, IslandAction::OpenCodeConnectionHelp))- );- // Real compositor coverage for Zen-only and combined cards, including- // a large currency label and all three Go windows.- for (go, spend) in [- (false, None),- (- false,- Some(usage::LocalSpend {- micro_usd: 9_999_990_000,- requests: 40,- }),- ),- (- true,- Some(usage::LocalSpend {- micro_usd: 1_250_000,- requests: 3,- }),- ),- ] {- let reading = &mut look.usage.providers[Provider::OpenCode as usize];- reading.opencode = Some(usage::OpenCodeDetails {- go,- zen: true,- spend,- });- reading.windows = if go {- [300, 10_080, 43_200]- .into_iter()- .map(|minutes| usage::Window {- label: None,- minutes,- used_percent: 15,- resets_at: Some(chrono::Utc::now() + chrono::Duration::hours(2)),- })- .collect()- } else {- Vec::new()- };- for style in [IslandStyle::Notch, IslandStyle::Bubble] {- look.widgets.island_style = style;- for scale in [1.0, 1.25, 1.5, 2.0] {- look.scale = scale;- for (light, glass) in [(true, true), (false, true), (false, false)] {- look.light = light;- look.glass = glass;- bar.build(&gfx, &look)?;- let hit = bar- .island_hits+ for (light, glass) in [(true, true), (false, true), (true, false), (false, false)] {+ look.light = light;+ look.glass = glass;+ look.panel = Some(Island::Usage);+ look.usage_enabled = true;+ look.usage.providers[Provider::OpenCode as usize] = ProviderUsage::default();+ bar.apply_look(&gfx, look.clone())?;+ assert!(bar.island_hits.is_empty() && bar.panel.is_none());+ assert_eq!(bar.triggers_span.width(), 0.0);+ look.usage.providers[Provider::OpenCode as usize] = ProviderUsage {+ state: State::Ready,+ windows: quota.clone(),+ fetched_at: Some(std::time::SystemTime::now()),+ };+ bar.apply_look(&gfx, look.clone())?;+ let current = bar.look.as_ref().context("rendered Go")?;+ let providers = island_providers(current);+ assert_eq!(providers.len(), 1);+ assert!(providers.iter().all(|entry| entry.0 == Provider::OpenCode));+ assert_eq!(+ current.panel_content_height(),+ 74.0 + ISLAND_ROW_HEIGHT + 26.0+ );+ assert!(bar.panel_span.width() > 0.0);+ assert!(+ bar.island_hits.iter()- .find(|hit| matches!(hit.action, IslandAction::OpenCodeConsole))- .context("Zen console has no click target")?;- let (left, top, right, bottom) = hit.bounds;- assert!(left >= bar.panel_span.left && right <= bar.panel_span.right);- let first = bar- .island_hits+ .any(|hit| matches!(hit.action, IslandAction::Toggle(Island::Usage)))+ );+ assert!(+ bar.island_hits.iter()- .find(|hit| hit.at((left + right) / 2.0, (top + bottom) / 2.0))- .context("Zen console cannot be clicked")?;- assert!(matches!(first.action, IslandAction::OpenCodeConsole));- }+ .any(|hit| matches!(hit.action, IslandAction::Refresh))+ );}}}+ // Removing Go credentials/quota closes its open popup and removes the trigger.+ look.usage.providers[Provider::OpenCode as usize] = ProviderUsage {+ state: State::SignIn,+ ..ProviderUsage::default()+ };+ bar.apply_look(&gfx, look)?;+ assert!(bar.panel.is_none() && bar.panel_span.width() == 0.0);+ assert!(bar.island_hits.is_empty() && bar.usage_viewport.is_none());Ok(())}@@ -4494,7 +4689,6 @@ mod mascot_tests {resets_at: None,}],fetched_at: None,- opencode: None,};}snapshotdiff --git a/apps/dock/src/multi_window_view.rs b/apps/dock/src/multi_window_view.rsindex 0060382..3e0d583 100644--- a/apps/dock/src/multi_window_view.rs+++ b/apps/dock/src/multi_window_view.rs@@ -177,6 +177,10 @@ pub struct MultiWindowView {pressed: Option<usize>,mouse_was_down: bool,foreground: isize,+ /// The card lit when the opened view was last drawn. Once open, only that+ /// changes what it shows, so a tick that finds it the same touches+ /// nothing: no composition batch and no DWM work while the view rests.+ drawn: Option<Option<usize>>,}/// Where the view opens: the app's icon and display, and the screen edge@@ -236,6 +240,7 @@ impl MultiWindowView {page: 0,cards: Vec::new(),opened: Instant::now(),+ drawn: None,animated: animations_enabled(),left_at: None,pressed: None,@@ -414,6 +419,7 @@ impl MultiWindowView {target.SetRoot(&root)?;}self.opened = Instant::now();+ self.drawn = None;Ok(())}@@ -426,6 +432,9 @@ impl MultiWindowView {};let eased = 1.0 - (1.0 - progress).powi(3);let hovered = self.layout.hit(self.local_cursor()?);+ if progress >= 1.0 && self.drawn == Some(hovered) {+ return Ok(());+ }let center = (self.anchor.left + (self.anchor.right - self.anchor.left) / 2- self.layout.bounds.left) as f32;let travel = (1.0 - eased) * 36.0 * self.scale;@@ -461,6 +470,7 @@ impl MultiWindowView {);}}+ self.drawn = (progress >= 1.0).then_some(hovered);// Run quickly only during the opening view animation. Nothing is polled// when the popup is closed, and thumbnail pixels are maintained by DWM.unsafe {diff --git a/apps/dock/src/strings.rs b/apps/dock/src/strings.rsindex 95cc94a..b8fb3af 100644--- a/apps/dock/src/strings.rs+++ b/apps/dock/src/strings.rs@@ -32,12 +32,6 @@ pub struct Strings {pub usage_refresh: &'static str,pub usage_refreshing: &'static str,pub usage_sign_in: &'static str,- pub usage_opencode_connect: &'static str,- pub usage_connection_help: &'static str,- pub usage_zen_local: &'static str,- pub usage_device_scope: &'static str,- pub usage_no_local: &'static str,- pub usage_open_console: &'static str,pub usage_unavailable: &'static str,pub usage_loading: &'static str,pub usage_stale: &'static str,@@ -84,12 +78,6 @@ const ES: Strings = Strings {usage_refresh: "Actualizar",usage_refreshing: "Actualizando…",usage_sign_in: "Inicia sesión en el cliente",- usage_opencode_connect: "En OpenCode: /connect → Go o Zen",- usage_connection_help: "Cómo conectar",- usage_zen_local: "Zen · gasto local estimado (30 d)",- usage_device_scope: "Este equipo · todas las cuentas · no es el saldo",- usage_no_local: "Gasto local no disponible",- usage_open_console: "Ver saldo en OpenCode",usage_unavailable: "No disponible",usage_loading: "Cargando…",usage_stale: "Sin actualizar",@@ -133,12 +121,6 @@ const EN: Strings = Strings {usage_refresh: "Refresh",usage_refreshing: "Refreshing…",usage_sign_in: "Sign in to the client",- usage_opencode_connect: "In OpenCode: /connect → Go or Zen",- usage_connection_help: "Connection guide",- usage_zen_local: "Zen · estimated local cost (30 d)",- usage_device_scope: "This device · all accounts · not your balance",- usage_no_local: "Local cost unavailable",- usage_open_console: "View balance in OpenCode",usage_unavailable: "Unavailable",usage_loading: "Loading…",usage_stale: "Not updated",@@ -182,12 +164,6 @@ const FR: Strings = Strings {usage_refresh: "Actualiser",usage_refreshing: "Actualisation…",usage_sign_in: "Se connecter dans le client",- usage_opencode_connect: "Dans OpenCode : /connect → Go ou Zen",- usage_connection_help: "Comment connecter",- usage_zen_local: "Zen · coût local estimé (30 j)",- usage_device_scope: "Cet appareil · tous les comptes · pas votre solde",- usage_no_local: "Coût local indisponible",- usage_open_console: "Voir le solde dans OpenCode",usage_unavailable: "Indisponible",usage_loading: "Chargement…",usage_stale: "Non actualisé",diff --git a/apps/dock/src/usage.rs b/apps/dock/src/usage.rsindex 120a68d..bf81ee5 100644--- a/apps/dock/src/usage.rs+++ b/apps/dock/src/usage.rs@@ -30,9 +30,6 @@ use windows::Win32::{const REFRESH_INTERVAL: Duration = Duration::from_secs(5 * 60);-mod opencode;-pub use opencode::{LocalSpend, OpenCodeDetails};-#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]pub enum State {Loading,@@ -76,8 +73,6 @@ pub struct ProviderUsage {pub state: State,pub windows: Vec<Window>,pub fetched_at: Option<SystemTime>,- #[serde(default, skip_serializing_if = "Option::is_none")]- pub opencode: Option<OpenCodeDetails>,}impl Default for ProviderUsage {@@ -86,28 +81,14 @@ impl Default for ProviderUsage {state: State::Loading,windows: Vec::new(),fetched_at: None,- opencode: None,}}}impl ProviderUsage {- pub fn name(&self, provider: Provider) -> &'static str {- match (provider, self.opencode.as_ref()) {- (Provider::OpenCode, Some(details)) => match (details.go, details.zen) {- (true, false) => "OpenCode Go",- (false, true) => "OpenCode Zen",- _ => "OpenCode",- },- _ => provider.name(),- }- }-pub fn compact_text(&self) -> String {if let Some(window) = self.main_window() {format!("{}%", window.used_percent)- } else if let Some(spend) = self.opencode.as_ref().and_then(|details| details.spend) {- spend.amount()} else {"—".to_owned()}@@ -131,6 +112,13 @@ impl Snapshot {pub fn get(&self, provider: Provider) -> &ProviderUsage {&self.providers[provider as usize]}++ /// OpenCode's process also serves Zen and unrelated providers. Only real+ /// Go quota windows justify its indicator; a running process alone does not.+ pub fn visible_providers(&self, mut active: ActiveProviders) -> ActiveProviders {+ active.0[Provider::OpenCode as usize] &= !self.get(Provider::OpenCode).windows.is_empty();+ active+ }}#[derive(Clone, Copy, PartialEq, Eq)]@@ -150,7 +138,7 @@ impl Provider {match self {Self::Claude => "Claude",Self::Codex => "Codex",- Self::OpenCode => "OpenCode",+ Self::OpenCode => "OpenCode Go",Self::Gemini => "Gemini",}}@@ -309,6 +297,11 @@ impl Monitor {return;}let active = active_providers();+ if !active.any() {+ self.running.store(false, Ordering::Release);+ self.mark_inactive();+ return;+ }if !force&& active == self.last_active&& self@@ -375,12 +368,8 @@ impl Drop for Monitor {}fn merge(previous: &mut ProviderUsage, fetched: ProviderUsage) {- if fetched.state == State::Unavailable- && !previous.windows.is_empty()- && fetched.opencode.is_none_or(|details| details.go)- {+ if fetched.state == State::Unavailable && !previous.windows.is_empty() {previous.state = State::Unavailable;- previous.opencode = fetched.opencode;} else {*previous = fetched;}@@ -432,7 +421,6 @@ fn ready(windows: Vec<Window>) -> ProviderUsage {state: State::Ready,windows,fetched_at: Some(SystemTime::now()),- opencode: None,}}@@ -534,46 +522,9 @@ fn fetch_opencode(client: &Client) -> ProviderUsage {let api_key = env::var("OPENCODE_API_KEY").ok();let data_home = env::var_os("XDG_DATA_HOME").map(PathBuf::from);let home = home();- let path = opencode_auth_path(data_home.as_deref(), home.as_deref());- // One bounded read, shared by both credential detection and the Go request.- let auth = path.as_deref().and_then(read_opencode_auth);- let token = opencode_key(api_key.as_deref(), auth.as_ref());- // OPENCODE_API_KEY can belong to either service. An environment key alone- // is not evidence of a Go subscription: require its saved ID or real quotas.- let go_key = auth- .as_ref()- .is_some_and(|auth| opencode_entry(auth, "opencode-go").is_some());- let zen_key = auth- .as_ref()- .is_some_and(|auth| opencode_entry(auth, "opencode").is_some());- let spend = path+ opencode_token(api_key.as_deref(), data_home.as_deref(), home.as_deref()).as_deref()- .and_then(Path::parent)- .and_then(|directory| {- opencode::local_spend(&directory.join("opencode.db"), Utc::now())- .ok()- .flatten()- });- let quota = token.map_or_else(sign_in, |token| fetch_opencode_go(client, token));- combine_opencode(quota, go_key, zen_key, spend)-}--fn combine_opencode(- mut quota: ProviderUsage,- go_key: bool,- zen_key: bool,- spend: Option<LocalSpend>,-) -> ProviderUsage {- let go = go_key || !quota.windows.is_empty();- let zen = zen_key || spend.is_some();- // Zen's local cost history needs no authentication. Lack of a Go subscription- // must not produce a misleading sign-in prompt for a Zen-only connection.- if !go && zen {- quota.state = State::Ready;- quota.fetched_at = Some(SystemTime::now());- }- quota.opencode = Some(OpenCodeDetails { go, zen, spend });- quota+ .map_or_else(sign_in, |token| fetch_opencode_go(client, token))}fn fetch_opencode_go(client: &Client, token: &str) -> ProviderUsage {@@ -622,11 +573,9 @@ fn opencode_auth_path(data_home: Option<&Path>, home: Option<&Path>) -> Option<Pfn opencode_key<'a>(api_key: Option<&'a str>, auth: Option<&'a Value>) -> Option<&'a str> {api_key.and_then(opencode_usable_key).or_else(|| {- // Go has its own provider ID. Keep the legacy Zen API-key entry as a- // fallback, but never forward another provider's OAuth or API secrets.- ["opencode-go", "opencode"]- .into_iter()- .find_map(|id| opencode_entry(auth?, id))+ // Zen keys do not establish a Go subscription. Never probe a saved+ // Zen-only connection or forward another provider's credentials.+ opencode_entry(auth?, "opencode-go")})}@@ -653,7 +602,6 @@ fn read_opencode_auth(path: &Path) -> Option<Value> {serde_json::from_slice(&bytes).ok()}-#[cfg(test)]fn opencode_token(api_key: Option<&str>,data_home: Option<&Path>,@@ -1074,7 +1022,6 @@ fn scan_rollout(path: &std::path::Path) -> Option<ProviderUsage> {state: State::Ready,windows,fetched_at,- opencode: None,});}None@@ -1173,53 +1120,52 @@ mod tests {}#[test]- fn opencode_zen_without_go_never_requests_a_go_login_or_invents_a_quota() {- let usage = combine_opencode(unavailable(), false, true, None);- assert!(usage.state == State::Ready);- assert_eq!(usage.name(Provider::OpenCode), "OpenCode Zen");- assert!(usage.main_window().is_none());- assert_eq!(usage.compact_text(), "—");- let usage = combine_opencode(- sign_in(),- false,- false,- Some(LocalSpend {- micro_usd: 1_250_000,- requests: 3,- }),- );- assert_eq!(usage.name(Provider::OpenCode), "OpenCode Zen");- assert_eq!(usage.compact_text(), "$1.25");+ fn opencode_only_shows_measured_go_quotas_for_a_running_client() {+ let mut snapshot = Snapshot::default();+ let mut active = ActiveProviders::default();+ active.0[Provider::OpenCode as usize] = true;+ active.0[Provider::Claude as usize] = true;+ assert!(!snapshot.visible_providers(active).has(Provider::OpenCode));+ assert!(snapshot.visible_providers(active).has(Provider::Claude));+ snapshot.providers[Provider::OpenCode as usize] = ready(parse_opencode(&json!({"usage": {+ "rolling": {"percent": 15}, "weekly": {"percent": 35}, "monthly": {"percent": 50}+ }})));+ assert!(snapshot.visible_providers(active).has(Provider::OpenCode));+ assert_eq!(Provider::OpenCode.name(), "OpenCode Go");+ assert_eq!(snapshot.get(Provider::OpenCode).compact_text(), "15%");+ assert_eq!(snapshot.get(Provider::OpenCode).windows.len(), 3);+ active.0[Provider::OpenCode as usize] = false;+ assert!(!snapshot.visible_providers(active).has(Provider::OpenCode));}#[test]- fn opencode_keeps_go_quotas_and_zen_cost_separate_in_the_same_snapshot() {- let quota = ready(parse_opencode(&json!({"usage": {- "rolling": {"percent": 15}, "weekly": {"percent": 35}, "monthly": {"percent": 50}- }})));- let usage = combine_opencode(- quota,- true,- true,- Some(LocalSpend {- micro_usd: 4_200_000,- requests: 5,- }),- );- assert_eq!(usage.name(Provider::OpenCode), "OpenCode");- assert_eq!(usage.compact_text(), "15%");- assert_eq!(usage.windows.len(), 3);- assert_eq!(- usage- .opencode- .and_then(|details| details.spend)- .map(LocalSpend::amount)- .as_deref(),- Some("$4.20")- );- let only_go = combine_opencode(sign_in(), true, false, None);- assert!(only_go.state == State::SignIn);- assert_eq!(only_go.name(Provider::OpenCode), "OpenCode Go");+ fn opencode_missing_or_invalid_windows_never_become_a_quota() {+ for value in [+ json!({"balance": 20}),+ json!({"usage": {}}),+ json!({"usage": {"rolling": {"percent": null}}}),+ json!({"usage": {"rolling": {"percent": -1}}}),+ json!({"usage": {"rolling": {"percent": 150}}}),+ ] {+ assert!(parse_opencode(&value).is_empty());+ }+ let zero = parse_opencode(&json!({"usage": {"rolling": {"percent": 0}}}));+ assert_eq!(zero.len(), 1);+ assert_eq!(zero[0].used_percent, 0);+ }++ #[test]+ fn opencode_failed_refresh_keeps_measured_quotas_stale_but_logout_clears_them() {+ let mut previous = ready(parse_opencode(+ &json!({"usage": {"rolling": {"percent": 42}}}),+ ));+ let fetched_at = previous.fetched_at;+ merge(&mut previous, unavailable());+ assert!(previous.state == State::Unavailable);+ assert_eq!(previous.compact_text(), "42%");+ assert_eq!(previous.fetched_at, fetched_at);+ merge(&mut previous, sign_in());+ assert!(previous.windows.is_empty());}#[test]@@ -1269,7 +1215,7 @@ mod tests {}#[test]- fn opencode_go_credentials_take_precedence_over_legacy_zen() {+ fn opencode_go_credentials_ignore_saved_zen_keys() {let auth = json!({"opencode-go": {"type": "api", "key": "go-fixture"},"opencode": {"type": "api", "key": "zen-fixture"}@@ -1292,7 +1238,7 @@ mod tests {assert_eq!(opencode_key(None, Some(&auth)), None);assert_eq!(opencode_key(Some("invalid\r\nheader"), Some(&auth)), None);let legacy = json!({"opencode": {"type": "api", "key": " legacy-fixture "}});- assert_eq!(opencode_key(None, Some(&legacy)), Some("legacy-fixture"));+ assert_eq!(opencode_key(None, Some(&legacy)), None);}#[test]@@ -1335,9 +1281,14 @@ mod tests {&default_path,br#"{"opencode":{"type":"api","key":"other-account-fixture"}}"#,)?;+ assert!(opencode_token(None, None, Some(&home)).is_none());+ fs::write(+ &default_path,+ br#"{"opencode-go":{"type":"api","key":"other-go-account-fixture"}}"#,+ )?;assert_eq!(opencode_token(None, None, Some(&home)).as_deref(),- Some("other-account-fixture")+ Some("other-go-account-fixture"));// A missing explicit account must not fall back to another directory.assert!(opencode_token(None, Some(&root.join("missing")), Some(&home)).is_none());diff --git a/apps/dock/src/usage/opencode.rs b/apps/dock/src/usage/opencode.rsdeleted file mode 100644index 2398f09..0000000--- a/apps/dock/src/usage/opencode.rs+++ /dev/null@@ -1,286 +0,0 @@-//! Device-local Zen cost history. This is not an account balance or invoice.-//! Reads only the provider, cost and ID columns of recent assistant records.--use std::{- collections::HashSet,- path::Path,- time::{Duration, Instant},-};--use chrono::{DateTime, Utc};-use rusqlite::{Connection, OpenFlags, limits::Limit};-use serde::{Deserialize, Serialize};--const LOOKBACK_DAYS: i64 = 30;-const MAX_ROWS: usize = 25_000;--#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]-pub struct LocalSpend {- pub micro_usd: u64,- pub requests: u64,-}--impl LocalSpend {- pub fn amount(self) -> String {- let cents = self.micro_usd.saturating_add(5_000) / 10_000;- format!("${}.{:02}", cents / 100, cents % 100)- }-}--#[derive(Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-pub struct OpenCodeDetails {- pub go: bool,- pub zen: bool,- pub spend: Option<LocalSpend>,-}--pub(super) fn local_spend(path: &Path, now: DateTime<Utc>) -> rusqlite::Result<Option<LocalSpend>> {- if !path.is_file() {- return Ok(None);- }- let mut db = Connection::open_with_flags(- path,- OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,- )?;- db.busy_timeout(Duration::from_millis(20))?;- // Connection-local settings: no schema, index, journal or checkpoint changes.- db.pragma_update(None, "query_only", true)?;- db.pragma_update(None, "trusted_schema", false)?;- db.pragma_update(None, "cache_size", -512)?;- db.set_limit(Limit::SQLITE_LIMIT_LENGTH, 1024 * 1024)?;- let started = Instant::now();- let mut steps = 0;- db.progress_handler(- 1_000,- Some(move || {- steps += 1;- steps > 2_500 || started.elapsed() > Duration::from_millis(250)- }),- )?;- read_spend(&db, now)-}--fn read_spend(db: &Connection, now: DateTime<Utc>) -> rusqlite::Result<Option<LocalSpend>> {- let since = (now - chrono::Duration::days(LOOKBACK_DAYS)).timestamp_millis();- let until = now.timestamp_millis();- let mut seen = HashSet::new();- let mut total = LocalSpend {- micro_usd: 0,- requests: 0,- };- // A migrated message can exist in both schemas. Prefer v2 and count its ID- // only once; never sum step-finish parts on top of their assistant's cost.- for (table, predicate) in [- (- "session_message",- "type = 'assistant' AND json_extract(data, '$.model.providerID') = 'opencode'",- ),- (- "message",- "json_extract(data, '$.role') = 'assistant' AND json_extract(data, '$.providerID') = 'opencode'",- ),- ] {- let exists: bool = db.query_row(- "SELECT EXISTS(SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = ?1)",- [table],- |row| row.get(0),- )?;- if !exists {- continue;- }- // Table and predicate are compile-time constants, not external input.- let sql = format!(- "SELECT id, json_extract(data, '$.cost') FROM {table}- WHERE time_created >= ?1 AND time_created <= ?2- AND CASE WHEN json_valid(data) THEN ({predicate}- AND json_type(data, '$.cost') IN ('integer', 'real')) ELSE 0 END- LIMIT {}",- MAX_ROWS + 1- );- let mut statement = db.prepare(&sql)?;- let mut rows = statement.query([since, until])?;- let mut read = 0;- while let Some(row) = rows.next()? {- read += 1;- if read > MAX_ROWS {- return Err(rusqlite::Error::InvalidQuery);- }- let id: String = row.get(0)?;- if id.len() > 256 {- return Err(rusqlite::Error::InvalidQuery);- }- if !seen.insert(id) {- continue;- }- if seen.len() > MAX_ROWS {- return Err(rusqlite::Error::InvalidQuery);- }- let dollars: f64 = row.get(1)?;- // Reject corrupt totals instead of presenting a partial/overflowed- // number as a reliable financial measurement.- if !dollars.is_finite() || !(0.0..=1_000_000.0).contains(&dollars) {- return Err(rusqlite::Error::InvalidQuery);- }- total.micro_usd = total- .micro_usd- .checked_add((dollars * 1_000_000.0).round() as u64)- .ok_or(rusqlite::Error::InvalidQuery)?;- total.requests += 1;- }- }- Ok((total.requests > 0).then_some(total))-}--#[cfg(test)]-mod tests {- use super::*;- use anyhow::Result;-- fn fixture(db: &Connection) -> Result<()> {- db.execute_batch("CREATE TABLE message(id TEXT PRIMARY KEY, time_created INTEGER, data TEXT);- CREATE TABLE session_message(id TEXT PRIMARY KEY, type TEXT, time_created INTEGER, data TEXT);")?;- Ok(())- }-- #[test]- fn zen_cost_excludes_go_other_providers_user_messages_and_outside_the_period() -> Result<()> {- let db = Connection::open_in_memory()?;- fixture(&db)?;- let now = Utc::now();- for (id, role, provider, cost, time) in [- ("zen", "assistant", "opencode", 1.25, now),- ("free", "assistant", "opencode", 0.0, now),- ("go", "assistant", "opencode-go", 12.0, now),- ("codex", "assistant", "openai", 14.0, now),- ("user", "user", "opencode", 15.0, now),- (- "old",- "assistant",- "opencode",- 20.0,- now - chrono::Duration::days(31),- ),- (- "future",- "assistant",- "opencode",- 30.0,- now + chrono::Duration::days(1),- ),- ] {- let data = serde_json::json!({"role": role, "providerID": provider, "cost": cost});- db.execute(- "INSERT INTO message VALUES (?1, ?2, ?3)",- rusqlite::params![id, time.timestamp_millis(), data.to_string()],- )?;- }- assert_eq!(- read_spend(&db, now)?,- Some(LocalSpend {- micro_usd: 1_250_000,- requests: 2- })- );- Ok(())- }-- #[test]- fn migrated_messages_are_counted_once_and_invalid_json_is_ignored() -> Result<()> {- let db = Connection::open_in_memory()?;- fixture(&db)?;- let now = Utc::now();- let legacy = r#"{"role":"assistant","providerID":"opencode","cost":5}"#;- let current = r#"{"model":{"providerID":"opencode"},"cost":2.5}"#;- db.execute(- "INSERT INTO message VALUES ('same', ?1, ?2)",- rusqlite::params![now.timestamp_millis(), legacy],- )?;- db.execute(- "INSERT INTO session_message VALUES ('same','assistant',?1,?2)",- rusqlite::params![now.timestamp_millis(), current],- )?;- db.execute(- "INSERT INTO message VALUES ('broken',?1,'invalid json')",- [now.timestamp_millis()],- )?;- assert_eq!(- read_spend(&db, now)?,- Some(LocalSpend {- micro_usd: 2_500_000,- requests: 1- })- );- Ok(())- }-- #[test]- fn missing_history_is_unknown_and_corrupt_costs_do_not_become_zero() -> Result<()> {- let db = Connection::open_in_memory()?;- fixture(&db)?;- let now = Utc::now();- assert_eq!(read_spend(&db, now)?, None);- db.execute(- "INSERT INTO message VALUES ('bad',?1,?2)",- rusqlite::params![- now.timestamp_millis(),- r#"{"role":"assistant","providerID":"opencode","cost":-4}"#- ],- )?;- assert!(read_spend(&db, now).is_err());- Ok(())- }-- #[test]- fn excessive_history_returns_unknown_instead_of_a_truncated_total() -> Result<()> {- let db = Connection::open_in_memory()?;- fixture(&db)?;- let now = Utc::now();- db.execute(- "WITH RECURSIVE n(x) AS (VALUES(1) UNION ALL SELECT x+1 FROM n WHERE x < ?1)- INSERT INTO message SELECT 'msg_' || x, ?2,- '{\"role\":\"assistant\",\"providerID\":\"opencode\",\"cost\":0.01}' FROM n",- rusqlite::params![i64::try_from(MAX_ROWS + 1)?, now.timestamp_millis()],- )?;- assert!(read_spend(&db, now).is_err());- Ok(())- }-- #[test]- fn wal_reads_do_not_modify_the_database_or_block_its_writer() -> Result<()> {- let root = std::env::temp_dir().join(format!(- "muelle-zen-{}-{}",- std::process::id(),- std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)?- .as_nanos()- ));- std::fs::create_dir(&root)?;- let result = (|| -> Result<()> {- let path = root.join("opencode.db");- let db = Connection::open(&path)?;- db.pragma_update(None, "journal_mode", "WAL")?;- fixture(&db)?;- let now = Utc::now();- db.execute(- "INSERT INTO message VALUES ('zen',?1,?2)",- rusqlite::params![- now.timestamp_millis(),- r#"{"role":"assistant","providerID":"opencode","cost":0.25}"#- ],- )?;- let before = std::fs::read(&path)?;- db.execute_batch("BEGIN IMMEDIATE")?;- assert_eq!(- local_spend(&path, now)?.map(LocalSpend::amount).as_deref(),- Some("$0.25")- );- db.execute_batch("ROLLBACK")?;- assert_eq!(std::fs::read(&path)?, before);- assert!(local_spend(&root.join("missing.db"), now)?.is_none());- assert!(!root.join("missing.db").exists());- Ok(())- })();- std::fs::remove_dir_all(&root)?;- result- }-}diff --git a/muelle/src/components/layout/SiteFooter.astro b/muelle/src/components/layout/SiteFooter.astroindex c588b48..8cedaee 100644--- a/muelle/src/components/layout/SiteFooter.astro+++ b/muelle/src/components/layout/SiteFooter.astro@@ -47,8 +47,7 @@ import { author, organization, site } from "@/data/site";<div class="mt-12 flex flex-wrap justify-between gap-3 border-t border-line pt-5 text-[13px] text-mute"><span>© 2026 {site.name}. Independent project; not affiliated with Apple, Microsoft or the listed AI providers.</span><span>- Made by <a href={author.profile} class="text-fg underline-offset-4 hover:text-signal hover:underline">{author.shortName}</a>- at <a href={organization.url} class="text-fg underline-offset-4 hover:text-signal hover:underline">{organization.name}</a>.+ Made by <a href={author.profile} class="text-fg underline-offset-4 hover:text-signal hover:underline">{author.shortName}</a>{' '}at <a href={organization.url} class="text-fg underline-offset-4 hover:text-signal hover:underline">{organization.name}</a>.Open source, built in Rust.</span></div>