Conversation
oyardena
force-pushed
the
feat/account-usage-rows
branch
from
June 20, 2026 15:54
c87c9e6 to
fa5c927
Compare
For users on an enterprise Claude plan (no five-hour / seven-day rate-limit
buckets), the widget now shows two dedicated rows:
Cr 9%·20/6 — credit remaining (%) and expiry date in system locale format
Sp $12/$50 — spend used / spend limit
For personal (Pro/Free) accounts the rows continue to show the normal 5h/7d
rate-limit bars.
Implementation notes:
- Parses `cinder_cove` and `spend` fields from the usage endpoint response
- Locale-aware date format via GetLocaleInfoW (respects separator and D/M order)
- Disk cache at %APPDATA%\ClaudeCodeUsageMonitor\account_cache.json survives
widget restarts; cleared when plan has no enterprise fields (prevents stale
enterprise rows appearing for Pro users after a 429)
- Tray tooltip uses dynamic row labels ("Cr"/"Sp" vs "5h"/"7d")
- tray_icon.rs: guard empty text before DrawTextW to avoid GDI crash
oyardena
force-pushed
the
feat/account-usage-rows
branch
from
June 21, 2026 20:08
fa5c927 to
a8be4f8
Compare
- native_interop: add move_window_async (SetWindowPos + SWP_ASYNCWINDOWPOS) to reposition WS_CHILD windows in Explorer without cross-process blocking; add detach_from_taskbar, raise_above_taskbar, TIMER_DRAG constant - window: fix drag in embedded mode — replace early-return + move_window with move_window_async; poll mouse via TIMER_DRAG (16 ms) instead of SetCapture (SetCapture on a taskbar child freezes Explorer) - window: widen drag-handle hit target from 3 px to 10 logical px (LEFT_DIVIDER_HIT_W) without changing the visual divider width; this makes the handle reliably hittable at high DPI (e.g. 20 physical px at 200% DPI) - window: add verbose diagnose logging to WM_LBUTTONDOWN / is_drag_handle_point / start_drag_reposition / TIMER_DRAG / update_drag_reposition_from_cursor - window: spawn_taskbar_watchdog improvements — detect stale embeds via window parentage check (GetParent) rather than HWND equality; post WM_APP_RECOVER_TASKBAR to re-attach without relaunching on transient failures; relaunch only after TASKBAR_RECOVER_MAX_ATTEMPTS consecutive failures - spend_pace: new module; .cargo/config.toml: linker config for MinGW cross-build
Keep last-good Mo/Wk/Dy instead of painting !, retry auth polls on a timer rather than only credential-file mtime changes, and refresh Claude tokens on 401. Also repair stuck spend anchors and leftmost tray defaults.
Use HTTP OAuth refresh instead of claude -p on Windows, repair spend anchors so Wk/Dy reflect period deltas, and anchor the layered popup to visible taskbar chrome with TOPMOST z-order. Add keepalive and display- change debouncing so the widget survives sleep/DPI/taskbar moves.
tray_offset -1 used visible-chrome left instead of taskbar_rect.left. Align embedded leftmost mode to x=0 as well.
Mo/Wk/Dy labels were clipped at a fixed 62px column, cutting $2000 down to $200 for 4-digit limits. Widen TEXT_WIDTH to fit. The floating popup is HWND_TOPMOST to track the taskbar's tray icons, which also put it above fullscreen video/games. Poll the foreground window every 500ms and hide the widget when it's genuinely fullscreen (no title bar, covers its monitor, excluding shell overlay classes like Windows.UI.Core.CoreWindow that are always full-monitor-sized). Gate the other periodic re-show paths (tray relayout, keepalive) on that same state so they stop fighting the hide and causing flicker.
Track the last applied popup layout and skip position_at_taskbar / render_layered when nothing moved, instead of re-rendering on every 15s keepalive tick. Cache successful poll results (keyed on a credential-file activity signature) for up to 15 minutes so idle ticks reuse the last usage data instead of hitting the network. Debounce sync_fullscreen_visibility and the taskbar watchdog so they only act on real state transitions, and invalidate both caches on manual refresh, tray icon rebuild, and language/reset actions so those still force an immediate repoll and repaint.
…nd non-leftmost default Three positioning/visibility bugs, root-caused after finding they were never actually fixed in prior sessions despite repeated attempts: - Fullscreen suppression checked only the foreground window's own monitor, never which monitor the widget's own taskbar lives on. A maximized/ fullscreen window on a secondary monitor was hiding the widget on the primary taskbar even though nothing there was fullscreen. should_hide_widget_for_fullscreen now scopes the check to the widget's taskbar monitor. - Default/leftmost position stopped at the left edge of the taskbar's icon cluster instead of the taskbar's own physical left edge (x=0), even when that space was genuinely empty. taskbar_placement_band_left is now hardcoded to 0, unconditionally, with a doc comment recording that this is a deliberate, non-negotiable requirement so it doesn't get "corrected" back to icon-cluster-avoidance by a future session. - Widget disappearing when hovering a taskbar thumbnail preview (Aero Peek): the existing fix was reactive (polling for TaskListThumbnailWnd/ CThumbnailWnd, a 5s latch, z-order raise), which only reacts after the fact to a compositor-level effect. Added the actual fix: exclude the window from DWM's peek ghosting via DwmSetWindowAttribute(DWMWA_EXCLUDED_FROM_PEEK), set once at window creation. Needs the Win32_Graphics_Dwm feature, added to Cargo.toml. Also commits src/proof_capture.rs and CLAUDE.md, which were present in the working tree but untracked.
Both held the app state Mutex guard across a call to a function that locks the same (non-reentrant) mutex again on the same thread: - sync_fullscreen_visibility's "fullscreen ended: restoring widget" branch held the guard while calling position_at_taskbar(), which locks state itself. This is what froze the widget process solid (confirmed via diagnose log going silent exactly at that line, and Get-Process reporting Responding=False) once the earlier monitor- scoping fix made the suppress -> restore transition actually fire for real instead of being masked by the old bug. - position_at_taskbar()'s own taskbar-rebind branch called invalidate_popup_layout() from inside a state.as_mut() block on the same guard, for the same reason. Triggers on taskbar rebinding (Explorer restart, monitor/dock changes, first launch). Both fixed by scoping the lock to just the state mutation, matching the pattern already used correctly everywhere else in this file.
…00ms poll sync_fullscreen_visibility only checked TIMER_FULLSCREEN_CHECK's 500ms tick, so it noticed well after the fact that DWM had dropped this window's composited layered content during a shell/XAML surface transition (Start menu, Search, task switches) - captured live via diagnose logging: pixel dropout correlated with fg_class becoming Windows.UI.Core.CoreWindow or an empty foreground state, lasting 300-620ms, while IsWindowVisible stayed true throughout (confirming this is a DWM compositing gap, not our own suppress logic hiding the window). Added a system-wide EVENT_SYSTEM_FOREGROUND WinEvent hook that posts a message (never calls back synchronously - would deadlock the same way the tray location hook's comment already warns about) to force an immediate repaint the instant focus changes, instead of waiting up to 500ms to notice. Also added diagnose logging to taskbar_hwnd_for_settings_index's fallback path and find_taskbars' primary-exclusion branch, from chasing an earlier, separate taskbar-rebind report that turned out not to reproduce again.
Diagnose log showed a real occurrence: WTS_SESSION_UNLOCK fires, then ~22s later should_hide_widget_for_fullscreen falsely triggers (a transient borderless window from post-unlock agents momentarily covers the monitor), hiding the widget for ~5s before it restores. Add a 30s grace period after session unlock during which fullscreen suppression is skipped entirely, and log the actual foreground window class/rect whenever suppression does fire so any remaining false positive outside that window can be root-caused directly instead of guessed at.
Root cause of the "disappears briefly" reports: on this machine, EnumWindows's top-level walk reproducibly omits the live, fully functional Shell_TrayWnd (independently confirmed healthy via GetWindowRect and its TrayNotifyWnd child) while a plain FindWindow call for the same class finds it every time. Every taskbar lookup in this codebase went through EnumWindows, so when this happened, taskbar_hwnd_for_settings_index fell back to find_taskbars()'s enumeration, which only turned up a stale/bogus Shell_SecondaryTrayWnd with garbage geometry (e.g. rect starting at negative coordinates) — and the widget got positioned there, off-screen. - find_taskbar_by_class now tries FindWindow first, only falling back to the EnumWindows scan if that comes up empty. - find_taskbars() backfills the primary via the same FindWindow-first lookup if EnumWindows's own walk didn't turn up a primary candidate, so multi-monitor resolution can't silently lose it either. - position_at_taskbar() now rejects a resolved taskbar rect that's geometrically implausible (non-positive size, or entirely outside the virtual screen) instead of moving the widget there, as a second line of defense against any other stale-window source. - WM_APP_FOREGROUND_CHANGED now re-resolves the taskbar binding (not just repaints), so any transient bad binding self-corrects on the next foreground event instead of waiting up to 60s for the periodic keepalive.
position_popup_zorder (used by position_above_taskbar, called from render_layered on every foreground change, unlock, and periodic keepalive) reasserted topmost via SetWindowPos(HWND_NOTOPMOST) then immediately SetWindowPos(HWND_TOPMOST). Between those two calls the widget is genuinely at a lower z-order position, behind whatever else is in front there, and a DWM composite frame landing in that gap shows it briefly occluded. This ran unconditionally on essentially every repaint, i.e. very often - a longstanding, previously-unexplained and likely primary source of "disappears briefly", independent of the unlock/taskbar-binding bugs already fixed. Skip the demote/reassert dance when the widget is already the frontmost window in z-order (GetWindow(hwnd, GW_HWNDPREV) is null), which is true for the large majority of calls, and go straight to a single SetWindowPos(HWND_TOPMOST). Only fall back to the two-step reassert when something is genuinely in front of it.
The previous commit's "skip demote/reassert when already frontmost" guard turned out to almost never engage: a live continuous monitor shows GW_HWNDPREV is essentially always non-null for this window (other topmost windows elsewhere on screen coexist normally), so the flicker-prone SetWindowPos(NOTOPMOST) -> SetWindowPos(TOPMOST) dance was still running on nearly every render regardless of that guard. Drop the guard's dependency for this call site entirely: always insert directly after taskbar_hwnd in z-order (one SetWindowPos call, the same pattern already used safely by raise_on_taskbar_band during taskbar peek) instead of trying to force absolute front-of-everything. For a taskbar-corner widget, sitting right above the taskbar's own z-order is sufficient, and removes the two-step dance from the hot render path entirely rather than gating it on a condition that rarely holds.
Confirmed live regression from the previous commit, reported as "I don't see the widget at all" and reproduced directly: SetWindowPos(hwnd, hWndInsertAfter, ...) places hwnd immediately BEHIND hWndInsertAfter in z-order, not in front of it. Passing taskbar_hwnd as hWndInsertAfter (the use_taskbar_band=true path) therefore placed the widget behind the real Shell_TrayWnd, which paints over it - total invisibility, confirmed via GetWindow(GW_HWNDPREV/NEXT) showing the widget sitting behind the taskbar in the live z-order chain, and via screenshots showing no widget content even across a full process restart (ruling out stale state - this was a straightforwardly wrong call every time). position_above_taskbar goes back to the demote/reassert HWND_TOPMOST dance. That path predates this session's changes and was never observed to fail; the flicker theory that motivated the previous two commits remains unconfirmed and lower priority than not hiding the widget outright.
Confirmed live: diagnose log shows foreground_covers_monitor_borderless returning true for fg_class="XamlWindow" with fg_rect=(0,0,2880,1800) - a transient Windows 11 shell XAML surface (Widgets board / notification flyout / similar) that briefly reports covering the entire monitor including the taskbar band. This triggered "fullscreen suppress: hide + lower z-order" and hid the widget for ~2s, correlated against the continuous visibility monitor logging vis=False for the same window. Add it to is_shell_foreground_class alongside the other shell-owned XAML surface classes already excluded there.
The on_foreground_changed hook only logged a raw HWND, which is useless for after-the-fact diagnosis - by the time anyone reads the log the window is long gone, so there was no way to tell whether a given event was the Start menu, Task View, a real app, or anything else. Log the class name too (window_class_name made pub for this).
A fresh-eyes audit (prompted by repeated "issue persists" reports with zero corresponding log anomalies) found a real, distinct bug from the 5 already fixed this session: ensure_popup_visible() - called by the taskbar watchdog thread specifically when it detects the widget has gone invisible - calls position_at_taskbar() to recover, but that function's own popup_layout_unchanged() cache short-circuits before ever reaching the ShowWindow(SW_SHOWNOACTIVATE)/render_layered() call whenever the taskbar geometry hasn't changed - the overwhelmingly common case, since the taskbar didn't move, the widget just isn't showing. The recovery attempt was a silent no-op, invisible in the log since neither the cache check nor its early return ever logs anything. The only thing that eventually fixed it was force_periodic_repaint(), which explicitly invalidates the cache first but only runs once every ~60s - matching the "disappears, then reappears on its own after a while" pattern reported throughout this session. Fix: invalidate_popup_layout() before calling position_at_taskbar() in ensure_popup_visible() whenever the window isn't already visible, matching the pattern every other recovery call site already uses (force_periodic_repaint, fullscreen-restore, foreground-changed, unlock). Same fix applied to the WM_DISPLAYCHANGE/WM_DPICHANGED/ WM_SETTINGCHANGE handler, which had the identical gap. Also added diagnose::log calls on both popup_layout_unchanged early-return sites in position_at_taskbar(), which previously logged nothing at all. Verified live: manually hid the widget via ShowWindow(SW_HIDE) with its position otherwise unchanged (the exact bug scenario) - it now auto-recovers within ~3s via the watchdog's WM_APP_ENSURE_VISIBLE instead of staying hidden. Also fixed a related but separately-triggered deadlock risk found by the same audit: begin_update_check()/begin_update_apply() could call the message-pumping show_info_message() (MessageBoxW) while still holding the state MutexGuard - the same non-reentrant-Mutex class of bug as two other deadlocks fixed earlier this session, just gated behind a narrower manual-update-check trigger. Restructured both to drop the guard first.
Observed live via the new foreground-class logging: this class took foreground immediately before a WM_WTSSESSION_CHANGE unlock event - clearly a lock/sign-in related shell surface, same risk profile as the XamlWindow false positive fixed earlier (transient class that could report covering the whole monitor). This specific occurrence didn't happen to trigger fullscreen-suppress, but excluding it defensively is free and consistent with the other shell surfaces already excluded.
User-confirmed, reproducible-by-description trigger: clicking the Start button makes the widget disappear. Could not reproduce via synthetic mouse clicks despite 30+ trials genuinely opening the Start menu (confirmed via foreground class change) with dense visibility, position, and rendered-pixel-content sampling - so this targets the confirmed trigger directly rather than a mechanism proven by repro. The existing on_foreground_changed repaint fires immediately on the WinEvent, which can race the Start menu's own opening animation/compositor churn. Arm a one-shot 400ms follow-up timer specifically when the new foreground window's class is "Windows.UI.Core.CoreWindow" (Start menu/Search/Action Center's XAML host) that forces invalidate_popup_layout + position_at_taskbar + render_layered again after that transition has had time to settle, independent of whatever the immediate repaint did.
1. monitor_rect_for_taskbar used a width-comparison heuristic (secondary taskbar -> monitor with the MAXIMUM width; primary -> MINIMUM width) instead of asking Windows which monitor a given taskbar_hwnd is actually on. This machine has a bogus ~6880px-wide "ghost" secondary display (stale dock/reconfiguration artifact), wider than the real primary, so a real secondary taskbar would always resolve to that ghost monitor instead of wherever it actually is. A live capture caught the widget's rect landing at y=2784-2880 - not on either known monitor - consistent with this heuristic picking the wrong one. Now uses MonitorFromWindow(taskbar_hwnd) directly, matching the pattern already used correctly elsewhere in this file. 2. The Start-menu follow-up timer added in ac23ccb never actually armed in practice: the class-check that arms it was gated behind the same 100ms repaint debounce as the immediate repaint. A real Start-button click reliably produces a burst of foreground-change events within milliseconds (e.g. a Shell_TrayWnd refocus immediately followed by the CoreWindow taking foreground), so the CoreWindow event routinely landed inside another event's debounce window and returned early before ever reaching the class check - confirmed via diagnose log (CoreWindow logged, but no TIMER_STARTMENU_FOLLOWUP ever followed). The class-check/timer-arm now runs unconditionally before the debounce; confirmed firing on every real Start click afterward.
Found a 100%-reliable repro for the "widget disappears when clicking Start" report: click Start, then move the mouse to 2-3 different points inside the open menu over ~1-2s before closing it. A plain click-wait-click with no movement inside the menu does NOT reproduce it (confirmed clean 5/5 trials) - the trigger is sustained mouse movement inside the open menu, not the click/open itself, which is also why 40+ earlier synthetic click-only tests this session never reproduced it. Confirmed root cause: this widget's composited surface goes blank and stays blank for 7+ seconds, independent of how many times or how frequently render_layered() resubmits. UpdateLayeredWindow reports success on every single call during the failure (now logged when it doesn't, for future diagnosis). Tried and confirmed NOT sufficient, each independently, verified via the same repro: a one-shot follow-up repaint; making it recurring at 400ms; tightening to 60ms (~113 attempts over 7s); DwmFlush() after every UpdateLayeredWindow; RedrawWindow(RDW_INVALIDATE|RDW_UPDATENOW|RDW_FRAME); stripping and re-adding WS_EX_LAYERED every tick to force a fresh surface registration. All reverted (kept only the harmless recurring-repaint timer and interval back at 400ms/30 ticks) since they added real, unconditional cost to render_layered() - this app's hot path - with zero measured benefit; kept only the UpdateLayeredWindow failure logging, which is free when there's no failure to report. This points at a DWM compositor-scheduling decision - likely deprioritizing a WS_EX_NOACTIVATE topmost overlay's frames against the focused Start menu's own high-frequency hover-animation frames - rather than a missed-frame race our own retries can win. Full writeup and an untested next direction (genuine taskbar embedding via SetParent + WM_PAINT instead of a separate layered surface, using the already-present but currently-dead embed_in_taskbar()/paint()) is in the TIMER_STARTMENU_FOLLOWUP handler's comment. Not attempted here: requires also wiring WM_PAINT to call paint() (currently a no-op stub) and was judged too large/risky to land safely under time pressure, not ruled out as unhelpful.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
POST /v1/oauth/token) instead of spawningclaude -p ., avoiding token burn during poll retries.Test plan
cargo build --releaseon Windows (msys64 mingw)claude -p .in diagnose log)_probe_taskbar_context.ps1→Pass: True)