-
-
Notifications
You must be signed in to change notification settings - Fork 581
Expand file tree
/
Copy pathtaskbar-ai-quota.wh.cpp
More file actions
9288 lines (8675 loc) · 415 KB
/
Copy pathtaskbar-ai-quota.wh.cpp
File metadata and controls
9288 lines (8675 loc) · 415 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==WindhawkMod==
// @id taskbar-ai-quota
// @name Taskbar AI Quota Bars
// @description Shows configurable AI agent/LLM subscription quota bars for Anthropic, OpenAI, and Google Antigravity on the Windows 11 taskbar
// @version 1.6.2
// @author Cleroth
// @github https://github.com/Cleroth
// @include explorer.exe
// @architecture x86-64
// @license MIT
// @compilerOptions -DWIN32_LEAN_AND_MEAN -lole32 -loleaut32 -lruntimeobject -lwindowsapp -lwinhttp -luser32 -lshell32 -lgdi32 -ladvapi32 -lws2_32 -liphlpapi -lcrypt32 -lbcrypt -lcomctl32 -lcomdlg32
// ==/WindhawkMod==
// ==WindhawkModReadme==
/*
# Taskbar AI Quota Bars
A Windows 11 taskbar mod that shows subscription quota bars next to the system tray.
Supported providers and quotas:
- **Anthropic Claude:** 5-hour, weekly, Fable weekly, and monthly extra usage
- **OpenAI/Codex:** 5-hour, weekly, and prepaid credits against a max you set
- **Google Antigravity:** Gemini pool
Optional notifications warn when usage crosses the configured red threshold.



## Setup
Open the native Settings window from the taskbar to add accounts. Anthropic and OpenAI
use browser sign-in; tokens are encrypted locally with Windows DPAPI. Antigravity uses
its signed-in local app or CLI session, which must remain running.
## Settings
- **Accounts and quota bars:** Add, order, or hide accounts and choose quota windows.
- **Layout and appearance:** Set orientation, size, labels, pace ticks, and colors.
- **Taskbar behavior:** Choose displays, click actions, polling, and alerts.
## Suggestions & bugs
Have a suggestion or found a bug?
[Open an issue](https://github.com/Cleroth/windhawk-taskbar-ai-quota/issues/new).
*/
// ==/WindhawkModReadme==
// Windhawk implicitly includes windhawk_api.h (and thus windows.h) before this file,
// so winsock2.h can't be ordered ahead of windows.h here. WIN32_LEAN_AND_MEAN (set in
// @compilerOptions) keeps that windows.h from pulling in the legacy winsock.h, so
// winsock2.h is included cleanly below without redefinition conflicts.
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windhawk_utils.h>
#include <windows.h>
#include <winternl.h>
#include <shellapi.h>
#include <commctrl.h>
#include <commdlg.h>
#include <winhttp.h>
#include <bcrypt.h>
#include <wincrypt.h>
#include <dpapi.h>
#include <unknwn.h>
#ifdef GetCurrentTime
#undef GetCurrentTime
#endif
#include <winrt/base.h>
#include <winrt/Windows.Data.Json.h>
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.UI.Core.h>
#include <winrt/Windows.UI.Text.h>
#include <winrt/Windows.UI.Xaml.h>
#include <winrt/Windows.UI.Xaml.Controls.h>
#include <winrt/Windows.UI.Xaml.Controls.Primitives.h>
#include <winrt/Windows.UI.Xaml.Documents.h>
#include <winrt/Windows.UI.Xaml.Input.h>
#include <winrt/Windows.UI.Xaml.Media.h>
#include <winrt/Windows.UI.Xaml.Shapes.h>
#include <algorithm>
#include <array>
#include <atomic>
#include <chrono>
#include <cmath>
#include <cwctype>
#include <initializer_list>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
#include <tlhelp32.h>
#include <iphlpapi.h>
using namespace winrt::Windows::Data::Json;
using namespace winrt::Windows::UI::Xaml;
using namespace winrt::Windows::UI::Xaml::Controls;
using namespace winrt::Windows::UI::Xaml::Media;
namespace wuxcp = winrt::Windows::UI::Xaml::Controls::Primitives;
namespace wuxd = winrt::Windows::UI::Xaml::Documents;
namespace wuxi = winrt::Windows::UI::Xaml::Input;
namespace wuxs = winrt::Windows::UI::Xaml::Shapes;
/**********************************************/
// Settings and State
/**********************************************/
enum QuotaBarIndex {
kFiveHourBar,
kWeeklyBar,
kFableWeeklyBar,
kExtraUsageBar,
kQuotaBarCount,
};
struct AccountConfig {
std::wstring provider; // "anthropic", "openai", or "antigravity".
std::wstring label;
std::array<bool, kQuotaBarCount> showBars{true, true, false, false};
// OpenAI only: user-chosen credits ceiling that turns the prepaid balance into a
// used-percent bar in the extra-usage slot. 0 disables the bar.
int creditsMax = 0;
bool hidden = false; // Runtime show/hide toggle (right-click menu), persisted in mod storage.
bool operator==(const AccountConfig&) const = default;
};
enum class TaskbarMonitorMode {
Primary,
All,
Specific,
};
enum class ClickAction {
Refresh,
OpenDashboard,
};
enum class BarLayout {
Stacked,
Vertical,
};
enum class BarMode {
Used,
Remaining,
};
enum class PercentTextAlignment {
Adaptive,
Left,
Center,
Right,
};
enum class PercentTextVisibility {
Never,
Hover,
Always,
};
enum class LabelPosition {
Hidden,
Left,
Top,
Right,
Bottom,
};
enum class PaceTickStyle {
Caret,
Line,
Notch,
Dot,
};
static constexpr COLORREF kDefaultPaceTickColor = RGB(222, 222, 222);
struct Settings {
std::vector<AccountConfig> accounts;
TaskbarMonitorMode taskbarMonitorMode = TaskbarMonitorMode::Primary;
ClickAction clickAction = ClickAction::Refresh;
BarLayout barLayout = BarLayout::Stacked;
BarMode barMode = BarMode::Used;
int taskbarMonitorNumber = 1;
int pollMinutes = 10;
int barLength = 100;
int barThickness = 8;
int labelFontSize = 11;
int percentFontSize = 9;
int accountMargin = 3;
int labelGap = 3;
int barGap = 2;
int rightMargin = 4;
int yellowThreshold = 50;
int orangeThreshold = 75;
int redThreshold = 90;
LabelPosition labelPosition = LabelPosition::Left;
bool showPaceTicks = true;
PaceTickStyle paceTickStyle = PaceTickStyle::Caret;
COLORREF paceTickColor = kDefaultPaceTickColor;
bool showBarLabels = false;
PercentTextVisibility percentTextVisibility = PercentTextVisibility::Hover;
PercentTextAlignment percentTextAlignment = PercentTextAlignment::Adaptive;
// Extra-usage/credits bars show the amount ($ or credits) instead of a percentage.
bool showExtraBarAmounts = false;
// additional_rate_limits lines (Codex Spark, gpt-reserve, ...) and the Spark plan name.
bool showOpenAiExtraLimits = false;
bool colorblindMode = false;
bool showStaleWarning = true;
bool enableNotifications = true;
bool operator==(const Settings&) const = default;
};
static constexpr ULONGLONG kFiveHourWindowMs = 5ULL * 60 * 60 * 1000;
static constexpr ULONGLONG kWeeklyWindowMs = 7ULL * 24 * 60 * 60 * 1000;
struct WindowUsage {
double pct = -1;
ULONGLONG resetUnixMs = 0;
ULONGLONG windowDurationMs = 0;
};
struct AccountData {
WindowUsage win5h;
WindowUsage winWeek;
WindowUsage fableWeek;
WindowUsage extraUsage;
WindowUsage antigravityThirdParty5h;
WindowUsage antigravityThirdPartyWeek;
std::wstring plan;
std::wstring openAiExtraLimitLines;
std::wstring extraLines;
// Amounts behind the extra-usage slot, in dollars (Anthropic) or credits (OpenAI);
// -1 when unknown. Left = limit - used. Used may go negative if a credits balance
// exceeds the configured max.
double extraUsedAmount = -1;
double extraLimitAmount = -1;
// OpenAI prepaid credits; balance is -1 when the API reports none or hides it.
bool hasCredits = false;
bool creditsUnlimited = false;
double creditsBalance = -1;
std::wstring error;
ULONGLONG lastSuccessMs = 0;
ULONGLONG retryDeadlineMs = 0;
bool stale = true;
bool needsLogin = false; // Sign-in required; left-click signs in instead of refreshing.
};
struct AppliedState {
std::array<int, kQuotaBarCount> fillPx{-1, -1, -1, -1};
std::array<uint32_t, kQuotaBarCount> fillColor{0, 0, 0, 0};
std::array<int, kQuotaBarCount> pacePx{-1, -1, -1, -1};
std::array<int, kQuotaBarCount> paceVisible{-1, -1, -1, -1};
std::array<int, kQuotaBarCount> percentAlignments{-1, -1, -1, -1};
std::array<int, kQuotaBarCount> percentDark{-1, -1, -1, -1};
std::wstring tip;
std::array<std::wstring, kQuotaBarCount> percentTexts;
std::wstring labelText;
double labelOpacity = -1;
double columnOpacity = -1;
int barMask = -1;
int visible = -1; // -1 unset, 0 collapsed, 1 visible.
};
struct PointerHandlers {
UIElement element{nullptr};
winrt::event_token tappedToken{};
winrt::event_token pointerEnteredToken{};
winrt::event_token pointerMovedToken{};
winrt::event_token pointerExitedToken{};
winrt::event_token pointerCaptureLostToken{};
winrt::event_token pointerCanceledToken{};
};
struct MenuItemClickHandler {
MenuFlyoutItem item{nullptr};
winrt::event_token token{};
};
struct AccountUiRefs {
StackPanel column{nullptr};
FrameworkElement barArea{nullptr};
ToolTip toolTip{nullptr};
winrt::event_token toolTipOpenedToken{};
DispatcherTimer manualToolTipTimer{nullptr};
winrt::event_token manualToolTipTimerToken{};
std::array<Border, kQuotaBarCount> tracks{
Border{nullptr}, Border{nullptr}, Border{nullptr}, Border{nullptr}};
std::array<Grid, kQuotaBarCount> barItems{
Grid{nullptr}, Grid{nullptr}, Grid{nullptr}, Grid{nullptr}};
std::array<Border, kQuotaBarCount> fills{
Border{nullptr}, Border{nullptr}, Border{nullptr}, Border{nullptr}};
std::array<Border, kQuotaBarCount> paceTicks{
Border{nullptr}, Border{nullptr}, Border{nullptr}, Border{nullptr}};
std::array<TextBlock, kQuotaBarCount> percents{
TextBlock{nullptr}, TextBlock{nullptr}, TextBlock{nullptr}, TextBlock{nullptr}};
TextBlock label{nullptr};
POINT toolTipOpenCursor{};
bool hasToolTipOpenCursor = false;
bool reopenToolTipOnMove = false;
bool manualToolTipOpen = false;
};
struct QuotaUiInstance {
HWND hWnd = nullptr;
DWORD ownerThreadId = 0;
double rasterizationScale = 1.0;
bool windowSubclassed = false;
ULONGLONG buildSettingsGeneration = 0;
bool buildVisualTestMode = false;
Grid quotaGrid{nullptr};
Grid injectionParent{nullptr};
ColumnDefinition quotaColumnDefinition{nullptr};
std::vector<PointerHandlers> pointerHandlers;
std::vector<MenuItemClickHandler> menuItemClickHandlers;
std::vector<AccountUiRefs> accountRefs;
std::vector<AppliedState> applied;
DispatcherTimer paceTimer{nullptr};
winrt::event_token paceTimerToken{};
// Per-account show/hide toggle items, paired with their account index, for cross-instance
// IsChecked sync in UpdateQuotaUi (Click is revoked via menuItemClickHandlers).
std::vector<std::pair<int, ToggleMenuFlyoutItem>> accountToggleItems;
};
static Settings g_settings;
static std::mutex g_settingsMutex;
static std::mutex g_configEditMutex;
static ULONGLONG g_settingsGeneration = 0;
static std::vector<AccountData> g_data;
static std::mutex g_dataMutex;
static std::atomic<bool> g_unloading{false};
static std::atomic<bool> g_refreshing{false};
static std::atomic<uint64_t> g_refreshAccountIdentity{0};
static std::atomic<ULONGLONG> g_refreshGeneration{0};
static std::mutex g_refreshMutex;
static std::atomic<bool> g_uiInjected{false};
static std::atomic<bool> g_visualTestMode{false};
static std::atomic<bool> g_settingsLoadError{false};
static std::atomic<bool> g_fetchThreadStarted{false};
static HANDLE g_stopEvent = nullptr;
static HANDLE g_refreshEvent = nullptr;
static HANDLE g_injectEvent = nullptr;
static HANDLE g_fetchThread = nullptr;
static HANDLE g_retryThread = nullptr;
static std::mutex g_retryThreadMutex;
static std::atomic<bool> g_rebuildQuotaUiBeforeInject{false};
static void* g_mtaUsageCookie = nullptr;
static HRESULT (WINAPI* g_coDecrementMTAUsage)(void*) = nullptr;
static bool g_winsockStarted = false;
static std::atomic<ULONGLONG> g_nextInjectFailureLogMs{0};
static std::mutex g_httpHandlesMutex;
static std::vector<HINTERNET> g_httpHandles;
static HANDLE g_settingsWindowThread = nullptr;
static std::mutex g_settingsWindowMutex;
static std::atomic<HWND> g_settingsWindow{nullptr};
static std::atomic<bool> g_settingsWindowCancelRequested{false};
// Fetch-thread-owned: hidden message-only window that owns the mod's tray icon.
static HWND g_notifyWnd = nullptr;
[[clang::no_destroy]] static std::optional<
std::vector<std::unique_ptr<QuotaUiInstance>>> g_uiInstances{std::in_place};
static std::mutex g_uiInstancesMutex;
static const wchar_t* kRootName = L"AiQuota_Root";
static constexpr ULONGLONG kFileTimeUnixEpochOffsetMs = 11644473600000ULL;
static constexpr ULONGLONG kUnixTimestampMsThreshold = 100000000000ULL;
static constexpr UINT kSettingsRefreshMessage = WM_APP + 20;
static constexpr UINT kExitVisualTestMessage = WM_APP + 21;
static constexpr UINT_PTR kSettingsAutosaveTimer = 1;
using WindowThreadProc = bool (*)(void*);
struct TaskbarDisplayInfo {
HWND hWnd = nullptr;
bool primary = false;
int monitorNumber = 0;
RECT rect{};
};
static bool RunFromWindowThread(HWND hWnd, WindowThreadProc proc, void* param, DWORD timeoutMs = 2000);
static int ScaleForDpi(int value, UINT dpi);
static UINT WindowDpi(HWND hWnd);
static std::vector<TaskbarDisplayInfo> FindCurrentProcessTaskbarDisplays();
static std::vector<HWND> FindCurrentProcessTaskbarWnds();
static QuotaUiInstance* FindUiState(HWND hWnd);
static void UpdateQuotaUi(QuotaUiInstance& state);
static void PostUiUpdate();
static void OpenSettingsWindow();
static void SetVisualTestMode(bool enabled);
static bool SaveOwnedSettings(const Settings& settings);
static void PublishSettings(Settings settings, uint64_t oldIdentity = 0,
uint64_t newIdentity = 0);
static void NotifySettingsWindowChanged() {
if (HWND hWnd = g_settingsWindow.load()) {
PostMessageW(hWnd, kSettingsRefreshMessage, 0, 0);
}
}
static void RemoveQuotaGrid(HWND hWnd);
static void ReleaseQuotaUiState(HWND hWnd);
static void StartRetryInject(bool removeExisting = false);
static LRESULT CALLBACK TaskbarWindowSubclassProc(HWND hWnd, UINT message, WPARAM wParam,
LPARAM lParam, DWORD_PTR refData);
static UINT GetQuotaCleanupMessage() {
static const UINT message = RegisterWindowMessageW(L"Windhawk_CleanupQuotaUi_" WH_MOD_ID);
return message;
}
static UINT GetSettingsActivateMessage() {
static const UINT message =
RegisterWindowMessageW(L"Windhawk_ActivateSettings_" WH_MOD_ID);
return message;
}
/**********************************************/
// Helpers
/**********************************************/
static ULONGLONG NowUnixMs() {
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
ULONGLONG t = ((ULONGLONG)ft.dwHighDateTime << 32) | ft.dwLowDateTime;
return t / 10000 - kFileTimeUnixEpochOffsetMs;
}
static void BuildVisualTestSnapshot(int yellowThreshold, int orangeThreshold,
int redThreshold, ULONGLONG now,
std::vector<AccountConfig>* accounts,
std::vector<AccountData>* data) {
static constexpr std::array<const wchar_t*, 4> kLabels = {
L"OAI", L"CC 1", L"CC 2", L"Go",
};
const std::array<double, 4> percentages = {
yellowThreshold / 2.0,
50.0,
orangeThreshold + (redThreshold - orangeThreshold) / 2.0,
redThreshold + (100 - redThreshold) / 2.0,
};
static constexpr std::array<ULONGLONG, kQuotaBarCount> kDurations = {
kFiveHourWindowMs,
kWeeklyWindowMs,
kWeeklyWindowMs,
30ULL * 24 * 60 * 60 * 1000,
};
static constexpr std::array<double, kQuotaBarCount> kRemainingFractions = {
0.35, 0.5, 0.6, 0.8,
};
accounts->clear();
accounts->reserve(percentages.size());
if (data) {
data->clear();
data->reserve(percentages.size());
}
for (size_t i = 0; i < percentages.size(); i++) {
AccountConfig account;
account.provider = L"anthropic";
account.label = kLabels[i];
account.showBars.fill(false);
for (size_t w = 0; w <= i; w++) account.showBars[w] = true;
accounts->push_back(std::move(account));
if (!data) continue;
AccountData accountData;
std::array<WindowUsage*, kQuotaBarCount> usage = {
&accountData.win5h, &accountData.winWeek,
&accountData.fableWeek, &accountData.extraUsage,
};
for (int w = 0; w < kQuotaBarCount; w++) {
usage[w]->pct = percentages[i];
usage[w]->windowDurationMs = kDurations[w];
usage[w]->resetUnixMs = now +
(ULONGLONG)std::lround(kDurations[w] * kRemainingFractions[w]);
}
accountData.plan = L"Visual test";
accountData.extraUsedAmount = percentages[i] / 2.0;
accountData.extraLimitAmount = 50.0;
accountData.lastSuccessMs = now;
accountData.stale = false;
data->push_back(std::move(accountData));
}
}
static std::wstring Utf8ToWide(const std::string& s) {
if (s.empty()) return {};
int n = MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), nullptr, 0);
if (n <= 0) return {};
std::wstring w(n, 0);
MultiByteToWideChar(CP_UTF8, 0, s.data(), (int)s.size(), w.data(), n);
return w;
}
static std::string WideToUtf8(const std::wstring& s) {
if (s.empty()) return {};
int n = WideCharToMultiByte(CP_UTF8, 0, s.data(), (int)s.size(), nullptr, 0, nullptr, nullptr);
if (n <= 0) return {};
std::string out(n, 0);
WideCharToMultiByte(CP_UTF8, 0, s.data(), (int)s.size(), out.data(), n, nullptr, nullptr);
return out;
}
// Stable identity used to preserve g_data across settings reloads, persist the show/hide
// toggle, and key the encrypted token store. FNV-1a over provider+label; relabeling an
// account therefore points it at a fresh (unsigned-in) identity.
static uint64_t AccountIdentityHash(const AccountConfig& a) {
std::wstring id = a.provider + L"\n" + a.label;
uint64_t h = 1469598103934665603ull;
for (const auto* p = reinterpret_cast<const unsigned char*>(id.data());
p != reinterpret_cast<const unsigned char*>(id.data() + id.size()); ++p) {
h = (h ^ *p) * 1099511628211ull;
}
return h;
}
static ULONGLONG ParseIso8601Ms(const std::wstring& s) {
int y = 0, mo = 0, d = 0, h = 0, mi = 0;
double sec = 0;
if (swscanf(s.c_str(), L"%d-%d-%dT%d:%d:%lf", &y, &mo, &d, &h, &mi, &sec) != 6) {
return 0;
}
SYSTEMTIME st{};
st.wYear = (WORD)y;
st.wMonth = (WORD)mo;
st.wDay = (WORD)d;
st.wHour = (WORD)h;
st.wMinute = (WORD)mi;
st.wSecond = (WORD)sec;
st.wMilliseconds = (WORD)((sec - st.wSecond) * 1000);
FILETIME ft;
if (!SystemTimeToFileTime(&st, &ft)) return 0;
ULONGLONG t = ((ULONGLONG)ft.dwHighDateTime << 32) | ft.dwLowDateTime;
ULONGLONG unixMs = t / 10000 - kFileTimeUnixEpochOffsetMs;
size_t tpos = s.find(L'T');
size_t sign = tpos == std::wstring::npos ? std::wstring::npos : s.find_first_of(L"+-", tpos);
if (sign != std::wstring::npos) {
int oh = 0, om = 0;
PCWSTR p = s.c_str() + sign + 1;
size_t end = s.find_first_not_of(L"0123456789:", sign + 1);
size_t len = (end == std::wstring::npos ? s.size() : end) - sign - 1;
auto digit = [](wchar_t c) { return c >= L'0' && c <= L'9'; };
bool parsedOffset = len >= 2 && digit(p[0]) && digit(p[1]);
if (parsedOffset) {
oh = (p[0] - L'0') * 10 + (p[1] - L'0');
if (len == 5 && p[2] == L':' && digit(p[3]) && digit(p[4])) {
om = (p[3] - L'0') * 10 + (p[4] - L'0');
} else if (len == 4 && digit(p[2]) && digit(p[3])) {
om = (p[2] - L'0') * 10 + (p[3] - L'0');
} else if (len != 2) {
parsedOffset = false;
}
}
if (parsedOffset && oh <= 23 && om <= 59) {
LONGLONG off = ((LONGLONG)oh * 60 + om) * 60000;
unixMs = s[sign] == L'+' ? unixMs - off : unixMs + off;
}
}
return unixMs;
}
static bool UnixMsToLocalSystemTime(ULONGLONG unixMs, SYSTEMTIME* local) {
if (!unixMs || !local) return false;
ULONGLONG t = (unixMs + kFileTimeUnixEpochOffsetMs) * 10000;
FILETIME ft{(DWORD)(t & 0xFFFFFFFF), (DWORD)(t >> 32)};
SYSTEMTIME utc;
return FileTimeToSystemTime(&ft, &utc) &&
SystemTimeToTzSpecificLocalTime(nullptr, &utc, local);
}
static std::wstring FormatLocalTime(SYSTEMTIME const& local) {
wchar_t buf[64];
if (GetTimeFormatEx(LOCALE_NAME_USER_DEFAULT, TIME_NOSECONDS, &local, nullptr, buf,
ARRAYSIZE(buf)) > 0) {
return buf;
}
swprintf(buf, ARRAYSIZE(buf), L"%02u:%02u", local.wHour, local.wMinute);
return buf;
}
static std::wstring FormatReset(ULONGLONG unixMs) {
if (!unixMs) return L"?";
LONGLONG delta = (LONGLONG)(unixMs - NowUnixMs());
if (delta <= 0) return L"now";
ULONGLONG totalMin = ((ULONGLONG)delta + 59999) / 60000;
ULONGLONG days = totalMin / (24 * 60);
ULONGLONG hours = (totalMin / 60) % 24;
ULONGLONG mins = totalMin % 60;
wchar_t rel[64];
if (days > 0) {
if (hours > 0) swprintf(rel, ARRAYSIZE(rel), L"in %llud %lluh", days, hours);
else swprintf(rel, ARRAYSIZE(rel), L"in %llud", days);
} else if (hours > 0) {
if (mins > 0) swprintf(rel, ARRAYSIZE(rel), L"in %lluh %llum", hours, mins);
else swprintf(rel, ARRAYSIZE(rel), L"in %lluh", hours);
} else {
swprintf(rel, ARRAYSIZE(rel), L"in %llum", mins);
}
SYSTEMTIME local;
if (!UnixMsToLocalSystemTime(unixMs, &local)) {
return rel;
}
std::wstring localTime = FormatLocalTime(local);
if (delta < 24LL * 3600 * 1000) {
return std::wstring(rel) + L" (" + localTime + L")";
}
wchar_t day[16] = L"";
GetDateFormatEx(LOCALE_NAME_USER_DEFAULT, 0, &local, L"ddd", day, ARRAYSIZE(day), nullptr);
return std::wstring(rel) + L" (" + day + L" " + localTime + L")";
}
static std::wstring FormatUpdated(ULONGLONG unixMs, bool stale) {
if (!unixMs) return L"updated: no data yet";
SYSTEMTIME local;
if (!UnixMsToLocalSystemTime(unixMs, &local)) {
return L"updated: ?";
}
return std::wstring(L"updated: ") + FormatLocalTime(local) + (stale ? L" (stale)" : L"");
}
static winrt::Windows::UI::Color UsageColor(double pct, bool stale, int yellowThreshold,
int orangeThreshold, int redThreshold,
bool colorblindMode) {
if (stale || pct < 0) return {255, 0x9E, 0x9E, 0x9E};
if (colorblindMode) {
if (pct >= redThreshold) return {255, 0xD5, 0x5E, 0x00};
if (pct >= orangeThreshold) return {255, 0xE6, 0x9F, 0x00};
if (pct >= yellowThreshold) return {255, 0x56, 0xB4, 0xE9};
return {255, 0x00, 0x72, 0xB2};
}
if (pct >= redThreshold) return {255, 0xE5, 0x39, 0x35};
if (pct >= orangeThreshold) return {255, 0xFB, 0x8C, 0x00};
if (pct >= yellowThreshold) return {255, 0xFD, 0xD8, 0x35};
return {255, 0x43, 0xA0, 0x47};
}
static void UpdateQuotaToolTip(ToolTip const& toolTip, std::wstring const& tip, bool hasError) {
constexpr double maxWidth = 460;
auto muted = SolidColorBrush(winrt::Windows::UI::Color{255, 0xD6, 0xD6, 0xD6});
auto quotaLabel = SolidColorBrush(winrt::Windows::UI::Color{255, 0x9A, 0xBE, 0xFF});
auto infoLabel = SolidColorBrush(winrt::Windows::UI::Color{255, 0xC7, 0x9B, 0xFF});
auto creditLabel = SolidColorBrush(winrt::Windows::UI::Color{255, 0xFF, 0xD7, 0x66});
auto duration = SolidColorBrush(winrt::Windows::UI::Color{255, 0xB7, 0xE4, 0xA3});
auto accent = SolidColorBrush(hasError ?
winrt::Windows::UI::Color{255, 0xFF, 0xB4, 0xA9} :
winrt::Windows::UI::Color{255, 0xC7, 0x9B, 0xFF});
auto border = SolidColorBrush(hasError ?
winrt::Windows::UI::Color{0xB8, 0xD1, 0x34, 0x38} :
winrt::Windows::UI::Color{0x72, 0x8A, 0xD1, 0xFF});
size_t firstBreak = tip.find(L'\n');
std::wstring title = firstBreak == std::wstring::npos ? tip : tip.substr(0, firstBreak);
std::wstring body = firstBreak == std::wstring::npos ? L"" : tip.substr(firstBreak + 1);
TextBlock titleBlock;
titleBlock.Text(winrt::hstring(title));
titleBlock.FontSize(12.5);
titleBlock.FontWeight(winrt::Windows::UI::Text::FontWeights::SemiBold());
titleBlock.Foreground(accent);
titleBlock.TextWrapping(TextWrapping::Wrap);
titleBlock.MaxWidth(maxWidth);
titleBlock.IsHitTestVisible(false);
StackPanel content;
content.Orientation(Orientation::Vertical);
content.MaxWidth(maxWidth);
content.IsHitTestVisible(false);
content.Children().Append(titleBlock);
if (!body.empty()) {
auto appendRun = [](TextBlock const& textBlock, std::wstring const& text,
Brush const& brush, bool bold = false) {
if (text.empty()) return;
wuxd::Run run;
run.Text(winrt::hstring(text));
run.Foreground(brush);
if (bold) run.FontWeight(winrt::Windows::UI::Text::FontWeights::SemiBold());
textBlock.Inlines().Append(run);
};
bool firstLine = true;
for (size_t pos = 0; pos <= body.size();) {
size_t next = body.find(L'\n', pos);
std::wstring line = next == std::wstring::npos ? body.substr(pos) : body.substr(pos, next - pos);
TextBlock lineBlock;
lineBlock.FontSize(12);
lineBlock.LineHeight(16);
lineBlock.TextWrapping(TextWrapping::Wrap);
lineBlock.MaxWidth(maxWidth);
lineBlock.Margin(firstLine ? Thickness{0, 4, 0, 0} : Thickness{0, 1, 0, 0});
lineBlock.IsHitTestVisible(false);
Brush labelBrush = muted;
size_t labelEnd = std::wstring::npos;
size_t highlightStart = std::wstring::npos;
size_t highlightEnd = std::wstring::npos;
bool labelBold = false;
bool quotaLine = false;
bool errorLine = false;
if (line.rfind(L"5h:", 0) == 0) {
labelBrush = quotaLabel;
labelEnd = 3;
labelBold = true;
quotaLine = true;
} else if (line.rfind(L"week:", 0) == 0) {
labelBrush = quotaLabel;
labelEnd = 5;
labelBold = true;
quotaLine = true;
} else if (line.rfind(L"Fable week:", 0) == 0) {
labelBrush = quotaLabel;
labelEnd = 11;
labelBold = true;
quotaLine = true;
} else if (line.rfind(L"error:", 0) == 0) {
labelBrush = accent;
labelEnd = 6;
labelBold = true;
errorLine = true;
} else if (line.rfind(L"credits:", 0) == 0) {
labelBrush = creditLabel;
labelEnd = 8;
highlightStart = line.find_first_not_of(L" ", labelEnd);
if (highlightStart != std::wstring::npos) {
highlightEnd = highlightStart;
while (highlightEnd < line.size()) {
wchar_t ch = line[highlightEnd];
if ((ch < L'0' || ch > L'9') && ch != L'.') break;
highlightEnd++;
}
}
labelBold = true;
} else if (line.rfind(L"extra usage:", 0) == 0) {
labelBrush = creditLabel;
labelEnd = 12;
labelBold = true;
quotaLine = true;
} else if (line.rfind(L"updated:", 0) == 0) {
labelBrush = infoLabel;
labelEnd = 8;
highlightStart = line.find(L"no data yet", labelEnd);
if (highlightStart != std::wstring::npos) highlightEnd = highlightStart + 11;
labelBold = true;
}
size_t textStart = 0;
if (labelEnd != std::wstring::npos) {
appendRun(lineBlock, line.substr(0, labelEnd), labelBrush, labelBold);
textStart = labelEnd;
}
if (errorLine) {
appendRun(lineBlock, line.substr(textStart), accent);
content.Children().Append(lineBlock);
firstLine = false;
if (next == std::wstring::npos) break;
pos = next + 1;
continue;
}
size_t cursor = textStart;
if (quotaLine) {
size_t percentEnd = line.find(L"%", cursor);
if (percentEnd != std::wstring::npos) {
size_t percentStart = percentEnd;
while (percentStart > cursor) {
wchar_t ch = line[percentStart - 1];
if ((ch < L'0' || ch > L'9') && ch != L'.') break;
percentStart--;
}
appendRun(lineBlock, line.substr(cursor, percentStart - cursor), muted);
appendRun(lineBlock, line.substr(percentStart, percentEnd + 1 - percentStart), duration, true);
cursor = percentEnd + 1;
}
}
size_t inPos = line.find(L"in ", cursor);
if (inPos != std::wstring::npos) {
size_t durationStart = inPos + 3;
size_t durationEnd = line.find(L" (", durationStart);
size_t dashEnd = line.find(L" - ", durationStart);
if (dashEnd != std::wstring::npos && (durationEnd == std::wstring::npos || dashEnd < durationEnd)) {
durationEnd = dashEnd;
}
if (durationEnd == std::wstring::npos) durationEnd = line.size();
appendRun(lineBlock, line.substr(cursor, durationStart - cursor), muted);
appendRun(lineBlock, line.substr(durationStart, durationEnd - durationStart), duration, true);
appendRun(lineBlock, line.substr(durationEnd), muted);
} else if (highlightStart != std::wstring::npos && highlightStart < highlightEnd) {
appendRun(lineBlock, line.substr(cursor, highlightStart - cursor), muted);
appendRun(lineBlock, line.substr(highlightStart, highlightEnd - highlightStart), duration, true);
appendRun(lineBlock, line.substr(highlightEnd), muted);
} else {
appendRun(lineBlock, line.substr(cursor), muted);
}
content.Children().Append(lineBlock);
firstLine = false;
if (next == std::wstring::npos) break;
pos = next + 1;
}
}
toolTip.BorderBrush(border);
toolTip.Content(content);
}
static void OpenUrl(PCWSTR url) {
if (g_unloading || !url || !*url) return;
ShellExecuteW(nullptr, L"open", url, nullptr, nullptr, SW_SHOWNORMAL);
}
static PCWSTR ProviderDisplayName(const std::wstring& provider) {
if (provider == L"anthropic") return L"Anthropic";
if (provider == L"openai") return L"OpenAI";
return L"Google Antigravity";
}
static void QueueRefresh(uint64_t identityHash) {
if (g_unloading) return;
if (!g_fetchThreadStarted.load(std::memory_order_acquire)) {
{
std::lock_guard<std::mutex> refreshLock(g_refreshMutex);
g_refreshing = false;
g_refreshAccountIdentity = 0;
}
PostUiUpdate();
return;
}
{
std::lock_guard<std::mutex> refreshLock(g_refreshMutex);
g_refreshing = true;
g_refreshAccountIdentity = identityHash;
g_refreshGeneration++;
}
PostUiUpdate();
if (g_refreshEvent) SetEvent(g_refreshEvent);
}
static void RefreshQuotaByIdentity(uint64_t identityHash) {
bool found = false;
{
std::lock_guard<std::mutex> lk(g_settingsMutex);
for (const auto& account : g_settings.accounts) {
if (AccountIdentityHash(account) == identityHash) {
found = true;
break;
}
}
}
if (found) QueueRefresh(identityHash);
}
static void OpenDashboardForIdentity(uint64_t identityHash) {
std::wstring provider;
{
std::lock_guard<std::mutex> lk(g_settingsMutex);
for (const auto& account : g_settings.accounts) {
if (AccountIdentityHash(account) == identityHash) {
provider = account.provider;
break;
}
}
}
if (provider.empty()) return;
if (provider == L"antigravity") {
RefreshQuotaByIdentity(identityHash);
} else {
OpenUrl(provider == L"anthropic" ? L"https://claude.ai/settings/usage"
: L"https://chatgpt.com/codex/cloud/settings/analytics#usage");
}
}
// Right-click menu: flip an account's show/hide state, keep at least one visible, persist the
// hidden-set to mod storage, then wake the fetch thread and refresh all taskbars. Runs on a
// taskbar UI thread (menu click); `sender` is the clicked ToggleMenuFlyoutItem (already flipped).
static void ToggleAccountVisibility(uint64_t identityHash,
winrt::Windows::Foundation::IInspectable const& sender) {
if (g_unloading) return;
auto toggle = sender.try_as<ToggleMenuFlyoutItem>();
bool clickedVisible = toggle && toggle.IsChecked();
std::unique_lock<std::mutex> configLock(g_configEditMutex);
std::wstring hashes;
Settings settingsSnapshot;
bool refreshNow = false;
bool oldHidden = false;
bool rejectedLastVisible = false;
{
std::lock_guard<std::mutex> lk(g_settingsMutex);
int accountIndex = -1;
for (size_t i = 0; i < g_settings.accounts.size(); i++) {
if (AccountIdentityHash(g_settings.accounts[i]) == identityHash) {
accountIndex = (int)i;
break;
}
}
if (accountIndex < 0) return;
oldHidden = g_settings.accounts[accountIndex].hidden;
bool wantVisible = toggle ? clickedVisible : oldHidden;
// Refuse to hide the last visible account: there'd be no bar left to right-click.
if (!wantVisible && !g_settings.accounts[accountIndex].hidden) {
int visibleCount = 0;
for (const auto& a : g_settings.accounts) {
if (!a.hidden) visibleCount++;
}
if (visibleCount <= 1) {
rejectedLastVisible = true;
}
}
if (!rejectedLastVisible) {
bool newHidden = !wantVisible;
settingsSnapshot = g_settings;
settingsSnapshot.accounts[accountIndex].hidden = newHidden;
if (newHidden != oldHidden) {
if (!newHidden) {
// Showing: keep the existing (possibly stale) data and only re-query if it has
// already gone stale, matching the UI's grey-out threshold. This stops repeated
// hide/show from triggering fetches and hitting provider rate limits.
ULONGLONG staleIntervalMin =
settingsSnapshot.accounts[accountIndex].provider == L"antigravity"
? 1
: (ULONGLONG)settingsSnapshot.pollMinutes;
ULONGLONG now = NowUnixMs();
std::lock_guard<std::mutex> lk2(g_dataMutex);
if (accountIndex >= (int)g_data.size()) {
refreshNow = true;
} else {
const AccountData& d = g_data[accountIndex];
refreshNow = d.stale || d.lastSuccessMs == 0 ||
now - d.lastSuccessMs > staleIntervalMin * 2 * 60000;
}
}
}
wchar_t buf[24];
for (const auto& a : settingsSnapshot.accounts) {
if (!a.hidden) continue;
if (!hashes.empty()) hashes += L";";
swprintf(buf, ARRAYSIZE(buf), L"%016llx",
(unsigned long long)AccountIdentityHash(a));
hashes += buf;
}
}
}
if (rejectedLastVisible) {
configLock.unlock();
if (toggle) toggle.IsChecked(true);
return;
}
if (!SaveOwnedSettings(settingsSnapshot)) {
configLock.unlock();
if (toggle) toggle.IsChecked(!oldHidden);
Wh_Log(L"Could not persist account visibility");
NotifySettingsWindowChanged();
return;
}
PublishSettings(settingsSnapshot);
Wh_SetStringValue(L"hiddenAccounts", hashes.c_str());
// RefreshQuota re-queries only this account (and posts the UI); otherwise just repaint so the
// column collapses/reappears with its existing data without any network request.
configLock.unlock();
NotifySettingsWindowChanged();
if (refreshNow) RefreshQuotaByIdentity(identityHash);