Skip to content

feat: account spend-pace rows and auth self-recovery - #39

Open
oyardena wants to merge 22 commits into
CodeZeno:mainfrom
oyardena:feat/account-usage-rows
Open

oyardena wants to merge 22 commits into
CodeZeno:mainfrom
oyardena:feat/account-usage-rows

Conversation

@oyardena

@oyardena oyardena commented Jun 20, 2026

Copy link
Copy Markdown

Summary

  • Add enterprise account credit/spend usage rows (Mo/Wk/Dy pace bars) with spend-anchor repair so week/day totals reflect period deltas instead of full-cycle spend.
  • Refresh OAuth on Windows via HTTP (POST /v1/oauth/token) instead of spawning claude -p ., avoiding token burn during poll retries.
  • Stabilize the layered taskbar popup: anchor leftmost placement to visible taskbar chrome (Win11 centered taskbar), keep TOPMOST z-order, and add keepalive plus display-change debouncing so the widget survives sleep/DPI/taskbar moves.
  • Improve taskbar recovery for embedded mode and auth-failure self-recovery paths.

Test plan

  • cargo build --release on Windows (msys64 mingw)
  • Deployed to local WinGet binary; widget visible at visible-chrome left edge with Mo/Wk/Dy values
  • OAuth refresh uses HTTP on Windows (no claude -p . in diagnose log)
  • Spend anchors: Wk/Dy near daily delta, Mo shows cycle total
  • Screen capture verification (_probe_taskbar_context.ps1Pass: True)
  • Upstream maintainer smoke test on multi-monitor Win11 taskbar

@oyardena
oyardena force-pushed the feat/account-usage-rows branch from c87c9e6 to fa5c927 Compare June 20, 2026 15:54
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
oyardena force-pushed the feat/account-usage-rows branch from fa5c927 to a8be4f8 Compare June 21, 2026 20:08
oyardena added 2 commits June 29, 2026 15:29
- 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.
@oyardena oyardena changed the title feat: display enterprise account credit and spend usage rows feat: account spend-pace rows and auth self-recovery Jul 14, 2026
oyardena added 19 commits July 21, 2026 12:27
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant