forked from aqua5230/usage
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmenubar.py
More file actions
1939 lines (1736 loc) · 73.3 KB
/
Copy pathmenubar.py
File metadata and controls
1939 lines (1736 loc) · 73.3 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
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright (C) 2026 lollapalooza <https://github.com/aqua5230>
#
# Part of "usage". Free software licensed under the GNU Affero General Public
# License v3.0 only; see the LICENSE file for full terms and the warranty disclaimer.
# mypy: disable-error-code="import-untyped,misc"
# PyObjC modules do not ship type stubs, and their base classes resolve to Any in mypy.
from __future__ import annotations
import asyncio
import contextlib
import io
import json
import logging
import os
import threading
import time
import tomllib
import webbrowser
from datetime import UTC, datetime, timedelta
from importlib import metadata
from pathlib import Path
from typing import Any
import objc
from AppKit import (
NSAlert,
NSAnimationContext,
NSApp,
NSApplication,
NSApplicationActivationPolicyAccessory,
NSAttributedString,
NSFont,
NSFontAttributeName,
NSImage,
NSMakePoint,
NSMakeRect,
NSMakeSize,
NSMenu,
NSMenuItem,
NSMinYEdge,
NSMutableAttributedString,
NSPopover,
NSPopoverBehaviorTransient,
NSStatusBar,
NSTextAttachment,
NSVariableStatusItemLength,
NSView,
NSViewController,
NSViewHeightSizable,
NSViewWidthSizable,
NSWindowCollectionBehaviorCanJoinAllSpaces,
NSWindowCollectionBehaviorFullScreenAuxiliary,
)
from Foundation import NSObject, NSRunLoop, NSRunLoopCommonModes, NSTimer, NSUserDefaults
from Quartz import CGColorCreateGenericRGB
import codex_loader
import critter_frames
import login_item
import menubar_state
import panels
import update_checker
import update_gate
import usage_diagnosis_snapshot
from burn_rate import BurnRateTracker
from fsevents_watch import cleanup_fsevents, setup_fsevents
from history_loader import UsageEntry, load_entries
from i18n import _t, packaged_resource_path
from menubar_prefs import (
_auto_update_check_enabled,
_hide_claude_enabled,
_hide_codex_enabled,
_quota_notification_thresholds,
_quota_notifications_enabled,
)
from menubar_state import (
CLAUDE_COLOR as CLAUDE_COLOR,
)
from menubar_state import (
CODEX_COLOR as CODEX_COLOR,
)
from menubar_state import (
DANGER_COLOR as DANGER_COLOR,
)
from menubar_state import (
WARN_COLOR as WARN_COLOR,
)
from menubar_state import (
WEEKLY_FORECAST_MIN_SPAN_SECONDS,
WEEKLY_FORECAST_WINDOW_SECONDS,
CodexStaleState,
PopoverState,
QuotaRowState,
_missing_row,
_quota_row,
)
from menubar_state import (
_bar_color as _bar_color,
)
from menubar_state import (
_format_percent as _format_percent,
)
from menubar_state import (
_group_name as _group_name,
)
from menubar_state import (
format_human_time as format_human_time,
)
from panels.base import Panel as UsagePanel
from panels.base import load_active_panel_id, resolve_resource, save_active_panel_id
from prefs import _load_preferences, _save_preferences
from pricing import calculate_cost, warm_up_pricing
from statusline_settings import (
_claude_settings_path as _claude_settings_path,
)
from statusline_settings import (
_disable_statusline_settings as _disable_statusline_settings,
)
from statusline_settings import (
_enable_statusline_settings as _enable_statusline_settings,
)
from statusline_settings import (
_load_claude_settings as _load_claude_settings,
)
from statusline_settings import (
_save_claude_settings as _save_claude_settings,
)
from statusline_settings import (
_set_forwarder_mode_prompt_dismissed as _set_forwarder_mode_prompt_dismissed,
)
from statusline_settings import (
_statusline_command_target_exists as _statusline_command_target_exists,
)
from statusline_settings import (
_statusline_enabled as _statusline_enabled,
)
from statusline_settings import (
_toggle_statusline_settings as _toggle_statusline_settings,
)
from usage_client import ClaudeUsageClient, PollOutcome, PollState
from usage_lang import detect_lang
from usage_notifications import NotificationEvent, QuotaNotifier
from usage_rate import UsageRateTracker
__all__ = [
"CLAUDE_COLOR",
"CODEX_COLOR",
"DANGER_COLOR",
"WARN_COLOR",
"WEEKLY_FORECAST_MIN_SPAN_SECONDS",
"WEEKLY_FORECAST_WINDOW_SECONDS",
"CodexStaleState",
"PopoverState",
"QuotaRowState",
"_bar_color",
"_format_percent",
"_group_name",
"_missing_row",
"_quota_row",
"format_human_time",
"_auto_update_check_enabled",
"_hide_claude_enabled",
"_hide_codex_enabled",
"_quota_notification_thresholds",
"_quota_notifications_enabled",
]
BUTTON_HEIGHT = 32.0
INSTALL_BUTTON_EXTRA_HEIGHT = BUTTON_HEIGHT + 10.0
UPDATE_DISMISS_SECONDS = 24 * 3600
UPDATE_ALERT_BODY_LIMIT = 2000
CRITTERS_DEFAULTS_KEY = "usage.critters_enabled"
logger = logging.getLogger(__name__)
def _detect_language() -> str:
return detect_lang()
def _panel_title(panel: UsagePanel, language: str) -> str:
return _t(language, panel.i18n_key)
def _session_resume_enabled() -> bool:
# State lives in ~/.claude/settings.json (a hook), not in usage's prefs file.
try:
import setup_hook
return setup_hook.is_resume_enabled()
except Exception:
return False
_ALERT_ICON: Any = None
_ALERT_ICON_LOADED = False
_CLAUDE_MENUBAR_ICON: Any = None
_CLAUDE_MENUBAR_ICON_LOADED = False
_CODEX_MENUBAR_ICON: Any = None
_CODEX_MENUBAR_ICON_LOADED = False
_CRITTER_IMAGE_CACHE: dict[str, Any] = {}
class _NoopAlert:
def setIcon_(self, icon: Any) -> None:
return
def setMessageText_(self, text: str) -> None:
return
def setInformativeText_(self, text: str) -> None:
return
def addButtonWithTitle_(self, title: str) -> None:
return
def runModal(self) -> int:
return 0
def _alert_icon() -> Any:
# NSAlert defaults to the application icon, which from source (and for an
# accessory app with no Dock presence) is py2app's / Python's rocket. Setting
# NSApp.applicationIconImage does not propagate to NSAlert, so each alert must
# set the branded icon explicitly. Loaded once and cached.
global _ALERT_ICON, _ALERT_ICON_LOADED
if not _ALERT_ICON_LOADED:
_ALERT_ICON_LOADED = True
try:
_ALERT_ICON = NSImage.alloc().initWithContentsOfFile_(resolve_resource("usage.icns"))
except Exception:
_ALERT_ICON = None
if os.environ.get("USAGE_DEBUG") == "1":
logger.warning("load alert icon failed", exc_info=True)
return _ALERT_ICON
def _load_menubar_color_icon(filename: str) -> Any:
image = NSImage.alloc().initWithContentsOfFile_(resolve_resource(filename))
if image is not None:
image.setTemplate_(False)
image.setSize_(NSMakeSize(14, 14))
return image
def _claude_menubar_icon() -> Any:
global _CLAUDE_MENUBAR_ICON, _CLAUDE_MENUBAR_ICON_LOADED
if not _CLAUDE_MENUBAR_ICON_LOADED:
_CLAUDE_MENUBAR_ICON_LOADED = True
try:
_CLAUDE_MENUBAR_ICON = _load_menubar_color_icon("claude_color_menubar.png")
except Exception:
_CLAUDE_MENUBAR_ICON = None
if os.environ.get("USAGE_DEBUG") == "1":
logger.warning("load Claude menubar icon failed", exc_info=True)
return _CLAUDE_MENUBAR_ICON
def _codex_menubar_icon() -> Any:
global _CODEX_MENUBAR_ICON, _CODEX_MENUBAR_ICON_LOADED
if not _CODEX_MENUBAR_ICON_LOADED:
_CODEX_MENUBAR_ICON_LOADED = True
try:
_CODEX_MENUBAR_ICON = _load_menubar_color_icon("codex_color_menubar.png")
except Exception:
_CODEX_MENUBAR_ICON = None
if os.environ.get("USAGE_DEBUG") == "1":
logger.warning("load Codex menubar icon failed", exc_info=True)
return _CODEX_MENUBAR_ICON
def _menubar_icon_attachment_string(image: Any) -> Any:
attachment = NSTextAttachment.alloc().init()
attachment.setImage_(image)
attachment.setBounds_(NSMakeRect(0, -2.5, 14, 14))
return NSAttributedString.attributedStringWithAttachment_(attachment)
def _critter_icon_attachment_string(image: Any) -> Any:
attachment = NSTextAttachment.alloc().init()
attachment.setImage_(image)
attachment.setBounds_(NSMakeRect(0, -4.0, 18, 18))
return NSAttributedString.attributedStringWithAttachment_(attachment)
def _critter_frame_image(path: str) -> Any:
cached = _CRITTER_IMAGE_CACHE.get(path)
if cached is not None:
return cached
image = NSImage.alloc().initWithContentsOfFile_(resolve_resource(path))
if image is not None:
image.setTemplate_(True)
image.setSize_(NSMakeSize(18, 18))
_CRITTER_IMAGE_CACHE[path] = image
return image
def _critters_enabled(defaults: Any | None = None) -> bool:
store = defaults if defaults is not None else NSUserDefaults.standardUserDefaults()
return bool(store.boolForKey_(CRITTERS_DEFAULTS_KEY))
def _save_critters_enabled(enabled: bool, defaults: Any | None = None) -> None:
store = defaults if defaults is not None else NSUserDefaults.standardUserDefaults()
store.setBool_forKey_(enabled, CRITTERS_DEFAULTS_KEY)
if hasattr(store, "synchronize"):
store.synchronize()
def _make_alert() -> Any:
try:
alert = NSAlert.alloc().init()
except Exception:
if os.environ.get("USAGE_DEBUG") == "1":
logger.warning("create alert failed", exc_info=True)
return _NoopAlert()
if alert is None:
if os.environ.get("USAGE_DEBUG") == "1":
logger.warning("create alert returned None")
return _NoopAlert()
icon = _alert_icon()
if icon is not None:
try:
alert.setIcon_(icon)
except Exception:
if os.environ.get("USAGE_DEBUG") == "1":
logger.warning("set alert icon failed", exc_info=True)
return alert
def _user_notification_center() -> tuple[Any, dict[str, int]]:
from UserNotifications import (
UNAuthorizationOptionAlert,
UNAuthorizationOptionBadge,
UNAuthorizationOptionSound,
UNUserNotificationCenter,
)
_register_user_notification_block_metadata()
return (
UNUserNotificationCenter.currentNotificationCenter(),
{
"alert": int(UNAuthorizationOptionAlert),
"badge": int(UNAuthorizationOptionBadge),
"sound": int(UNAuthorizationOptionSound),
},
)
def _user_notification_classes() -> tuple[Any, Any, Any]:
_register_user_notification_block_metadata()
from UserNotifications import (
UNMutableNotificationContent,
UNNotificationRequest,
UNNotificationSound,
)
return UNMutableNotificationContent, UNNotificationRequest, UNNotificationSound
def _register_user_notification_block_metadata() -> None:
objc.registerMetaDataForSelector(
b"UNUserNotificationCenter",
b"requestAuthorizationWithOptions:completionHandler:",
{
"arguments": {
3: {
"callable": {
"retval": {"type": b"v"},
"arguments": {
0: {"type": b"^v"},
1: {"type": b"Z"},
2: {"type": b"@"},
},
},
},
},
},
)
objc.registerMetaDataForSelector(
b"UNUserNotificationCenter",
b"addNotificationRequest:withCompletionHandler:",
{
"arguments": {
3: {
"callable": {
"retval": {"type": b"v"},
"arguments": {
0: {"type": b"^v"},
1: {"type": b"@"},
},
},
},
},
},
)
def _notification_tool(channel: str) -> str:
return "Claude" if channel.startswith("claude_") else "Codex"
def _notification_scope(language: str, channel: str) -> str:
if channel.endswith("_session"):
return _t(language, "session_label")
return _t(language, "weekly_label")
def _notification_row(state: PopoverState, channel: str) -> QuotaRowState:
rows = {
"claude_session": state.claude_session,
"claude_weekly": state.claude_weekly,
"codex_session": state.codex_session,
"codex_weekly": state.codex_weekly,
}
return rows[channel]
def _update_dismissed_recently(prefs: dict[str, Any]) -> bool:
dismissed_at = prefs.get("update_dismissed_at")
if isinstance(dismissed_at, int | float):
return (time.time() - float(dismissed_at)) < UPDATE_DISMISS_SECONDS
return False
def _current_version() -> str:
try:
return metadata.version("usage")
except metadata.PackageNotFoundError as exc:
pyproject = packaged_resource_path(
"pyproject.toml", Path(__file__).with_name("pyproject.toml")
)
data = tomllib.loads(pyproject.read_text(encoding="utf-8"))
version = data.get("project", {}).get("version")
if isinstance(version, str):
return version
raise RuntimeError("project.version missing from pyproject.toml") from exc
_APP_DELEGATE: AppDelegate | None = None
MAX_CACHED_PANEL_VIEWS = 6
PANEL_TRANSITION_TIMEOUT_SECONDS = 1.5
PANEL_TRANSITION_FADE_SECONDS = 0.18
class PopoverViewController(NSViewController):
content_view = objc.ivar()
panel = objc.ivar()
delegate = objc.ivar()
panel_views = objc.ivar()
panel_lru = objc.ivar()
transition_overlays = objc.ivar()
latest_state = objc.ivar()
def initWithPanel_delegate_(self, panel: UsagePanel, delegate: Any) -> PopoverViewController:
self = objc.super(PopoverViewController, self).init()
if self is None:
return None
self.panel = panel
self.delegate = delegate
self.panel_views = {}
self.panel_lru = []
self.transition_overlays = {}
self.latest_state = None
self.content_view = panel.build_view(delegate)
container = NSView.alloc().initWithFrame_(self.content_view.frame())
container.setWantsLayer_(True)
self.setView_(container)
self.preparePanelView_(self.content_view)
container.addSubview_(self.content_view)
# Only cache a real web view; a failed build (ErrorPanelView, no JS
# bridge) is shown but left uncached so a later switch rebuilds it.
if hasattr(self.content_view, "evaluateJavaScript_completionHandler_"):
self.panel_views[panel.id] = self.content_view
self.panel_lru.append(panel.id)
return self
def setState_(self, state: PopoverState) -> None:
self.latest_state = state
self.view().setFrameSize_(_popover_size(state, self.panel))
self.syncPanelFrames()
self.panel.apply_state(self.content_view, state)
def switchToPanel_(self, panel: UsagePanel) -> None:
previous = self.content_view
self.panel = panel
content_view = self.panel_views.get(panel.id)
if content_view is None:
content_view = panel.build_view(self.delegate)
content_view.setHidden_(True)
self.preparePanelView_(content_view)
self.view().addSubview_(content_view)
# Only cache a real web view. A failed build returns ErrorPanelView
# (no JS bridge); caching it would pin the error even after the file
# recovers, so leave it uncached and rebuild on the next switch.
if hasattr(content_view, "evaluateJavaScript_completionHandler_"):
self.panel_views[panel.id] = content_view
self.beginPanelTransitionForPanelId_view_(panel.id, content_view)
# Drop the previously shown view if it was an uncached error fallback,
# so it doesn't linger stacked in the container behind the new panel.
if (
previous is not None
and previous is not content_view
and previous not in self.panel_views.values()
):
if hasattr(previous, "teardown"):
previous.teardown()
previous.removeFromSuperview()
self.content_view = content_view
if panel.id in self.panel_views:
self.markPanelUsed_(panel.id)
for panel_id, view in list(self.panel_views.items()):
view.setHidden_(panel_id != panel.id)
content_view.setHidden_(False)
if self.latest_state is not None:
self.setState_(self.latest_state)
self.evictPanelViewsIfNeeded()
def currentContentView(self) -> Any:
return self.content_view
def panelDidFirstPaint_(self, view: Any) -> None:
if view is self.content_view:
self.endPanelTransitionForPanelView_(view)
def beginPanelTransitionForPanelId_view_(self, panel_id: str, view: Any) -> None:
self.removeTransitionOverlay_(panel_id)
overlay = NSView.alloc().initWithFrame_(view.bounds())
overlay.setWantsLayer_(True)
overlay.setAlphaValue_(1.0)
overlay.setAutoresizingMask_(int(NSViewWidthSizable) | int(NSViewHeightSizable))
layer = overlay.layer()
if layer is not None:
layer.setBackgroundColor_(
CGColorCreateGenericRGB(10 / 255, 15 / 255, 20 / 255, 1.0)
)
view.addSubview_(overlay)
self.transition_overlays[panel_id] = overlay
self.performSelector_withObject_afterDelay_(
"transitionTimeoutElapsed:",
overlay,
PANEL_TRANSITION_TIMEOUT_SECONDS,
)
def transitionTimeoutElapsed_(self, overlay: Any) -> None:
# Match by the overlay object itself, not the panel id: if this panel was
# evicted and rebuilt, a stale timer must not fade the new overlay. A timer
# whose overlay is already gone from the map simply finds nothing and stops.
for panel_id, current_overlay in list(self.transition_overlays.items()):
if current_overlay is overlay:
self.endPanelTransitionForPanelId_(panel_id)
return
def endPanelTransitionForPanelView_(self, view: Any) -> None:
for panel_id, panel_view in list(self.panel_views.items()):
if panel_view is view:
self.endPanelTransitionForPanelId_(panel_id)
return
def endPanelTransitionForPanelId_(self, panel_id: str) -> None:
overlay = self.transition_overlays.pop(panel_id, None)
if overlay is None:
return
def _fade(context: Any) -> None:
context.setDuration_(PANEL_TRANSITION_FADE_SECONDS)
overlay.animator().setAlphaValue_(0.0)
def _remove() -> None:
overlay.removeFromSuperview()
NSAnimationContext.runAnimationGroup_completionHandler_(_fade, _remove)
def teardown(self) -> None:
for panel_id, view in list(self.panel_views.items()):
self.removeTransitionOverlay_(panel_id)
if hasattr(view, "teardown"):
view.teardown()
view.removeFromSuperview()
self.panel_views.clear()
self.panel_lru.clear()
self.content_view = None
def preparePanelView_(self, view: Any) -> None:
view.setFrame_(self.view().bounds() if self.view() is not None else view.frame())
view.setAutoresizingMask_(int(NSViewWidthSizable) | int(NSViewHeightSizable))
def syncPanelFrames(self) -> None:
bounds = self.view().bounds()
for view in self.panel_views.values():
view.setFrame_(bounds)
def markPanelUsed_(self, panel_id: str) -> None:
self.panel_lru = [cached_id for cached_id in self.panel_lru if cached_id != panel_id]
self.panel_lru.append(panel_id)
def evictPanelViewsIfNeeded(self) -> None:
while len(self.panel_views) > MAX_CACHED_PANEL_VIEWS:
evict_id = next(
(panel_id for panel_id in self.panel_lru if panel_id != self.panel.id),
None,
)
if evict_id is None:
return
self.panel_lru = [panel_id for panel_id in self.panel_lru if panel_id != evict_id]
view = self.panel_views.pop(evict_id, None)
self.removeTransitionOverlay_(evict_id)
if view is None:
continue
if hasattr(view, "teardown"):
view.teardown()
view.removeFromSuperview()
def removeTransitionOverlay_(self, panel_id: str) -> None:
overlay = self.transition_overlays.pop(panel_id, None)
if overlay is not None:
overlay.removeFromSuperview()
class AppDelegate(NSObject):
status_item = objc.ivar()
popover = objc.ivar()
popover_controller = objc.ivar()
timer = objc.ivar()
mock = objc.ivar()
interval = objc.ivar()
tracker = objc.ivar()
codex_tracker = objc.ivar()
latest_state = objc.ivar()
active_panel = objc.ivar()
codex_5h_pct = objc.ivar()
codex_model = objc.ivar()
burn_rate_trackers = objc.ivar()
_refresh_in_flight = objc.ivar()
_refresh_queued = objc.ivar()
_fs_stream = objc.ivar()
_history_entries_cache = objc.ivar()
_history_entries_cache_fingerprint = objc.ivar()
_history_load_error_key = objc.ivar()
_quota_notifier = objc.ivar()
_switch_menu_action_taken = objc.ivar()
critters_enabled = objc.ivar()
critter_timer = objc.ivar()
critter_frame = objc.ivar()
critter_interval = objc.ivar()
dragon_timer = objc.ivar()
dragon_frame = objc.ivar()
dragon_interval = objc.ivar()
language = objc.ivar()
def initWithMock_interval_(self, mock: bool, interval: int) -> AppDelegate:
self = objc.super(AppDelegate, self).init()
if self is None:
return None
self.mock = mock
self.interval = max(30, interval)
self.tracker = UsageRateTracker(mock=mock)
self.codex_tracker = UsageRateTracker(mock=mock, load=codex_loader.load_entries)
self.language = _detect_language()
self.codex_5h_pct = None
self.codex_model = "unknown"
self.latest_state = _empty_state(self.language)
self.active_panel = panels.get_panel(load_active_panel_id())
self.burn_rate_trackers = {
"claude_session": BurnRateTracker(),
"claude_weekly": BurnRateTracker(),
"codex_session": BurnRateTracker(),
"codex_weekly": BurnRateTracker(),
}
self._quota_notifier = QuotaNotifier(_quota_notification_thresholds())
self._refresh_in_flight = False
self._refresh_queued = False
self._fs_stream = None
self._history_entries_cache = None
self._history_entries_cache_fingerprint = None
self._history_load_error_key = None
self._switch_menu_action_taken = False
self.critters_enabled = _critters_enabled()
self.critter_timer = None
self.critter_frame = 0
self.critter_interval = 0.0
self.dragon_timer = None
self.dragon_frame = 0
self.dragon_interval = 0.0
self._last_button_title_key: tuple[str, bool, int | None, int | None] | None = None
return self
def applicationDidFinishLaunching_(self, notification: Any) -> None:
NSApp.setActivationPolicy_(NSApplicationActivationPolicyAccessory)
self.status_item = NSStatusBar.systemStatusBar().statusItemWithLength_(
NSVariableStatusItemLength,
)
# Do not change this string; it is the stable identity for saved menu bar position.
self.status_item.setAutosaveName_("usage")
button = self.status_item.button()
button.setTitle_("🐾 ...")
button.setTarget_(self)
button.setAction_("togglePopover:")
self.popover_controller = PopoverViewController.alloc().initWithPanel_delegate_(
self.active_panel,
self,
)
self.popover = NSPopover.alloc().init()
self.popover.setBehavior_(NSPopoverBehaviorTransient)
self.popover.setContentSize_(_popover_size(self.latest_state, self.active_panel))
self.popover.setContentViewController_(self.popover_controller)
self._request_notification_authorization()
self._refresh()
self.timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
self.interval,
self,
"timerFired:",
None,
True,
)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSRunLoopCommonModes)
self._fs_stream = setup_fsevents(self)
warm_up_pricing(self._refresh_after_pricing_warm_up)
thread = threading.Thread(target=self._maybe_check_update_in_background, daemon=True)
thread.start()
def _refresh_after_pricing_warm_up(self) -> None:
self.performSelectorOnMainThread_withObject_waitUntilDone_(
"refreshNow:",
None,
False,
)
def timerFired_(self, timer: Any) -> None:
self._refresh()
self._clear_stale_update_cache()
def refreshNow_(self, sender: Any) -> None:
self._refresh(queue_if_busy=True)
def installHook_(self, sender: Any) -> None:
thread = threading.Thread(target=self._install_hook_in_background, daemon=True)
thread.start()
def toggleStatusline_(self, sender: Any) -> None:
thread = threading.Thread(target=self._toggle_statusline_in_background, daemon=True)
thread.start()
def installStatusline_(self, sender: Any) -> None:
thread = threading.Thread(
target=self._statusline_action_in_background,
args=("install",),
daemon=True,
)
thread.start()
def uninstallStatusline_(self, sender: Any) -> None:
thread = threading.Thread(
target=self._statusline_action_in_background,
args=("uninstall",),
daemon=True,
)
thread.start()
def analyzeUsage_(self, sender: Any) -> None:
period = _analysis_period_from_project_range(str(sender or "30d"))
thread = threading.Thread(
target=self._analyze_usage_in_background,
args=(period,),
daemon=True,
)
thread.start()
def quitApp_(self, sender: Any) -> None:
if self.timer is not None:
self.timer.invalidate()
NSApp.terminate_(sender)
def applicationWillTerminate_(self, notification: Any) -> None:
cleanup_fsevents(self._fs_stream)
self._fs_stream = None
self._stop_critter_timer()
self._stop_dragon_timer()
if hasattr(self, "popover_controller") and self.popover_controller is not None:
self.popover_controller.teardown()
def switchPanel_(self, sender: Any) -> None:
menu = NSMenu.alloc().initWithTitle_(_t(self.language, "switch_panel"))
critters_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
_t(
self.language,
"dismiss_critters" if self.critters_enabled else "summon_critters",
),
"toggleCritters:",
"",
)
critters_item.setTarget_(self)
critters_item.setState_(1 if self.critters_enabled else 0)
menu.addItem_(critters_item)
menu.addItem_(NSMenuItem.separatorItem())
# Panel themes live in a submenu so the menu stays short — one "面板主題 ▸"
# row that expands on demand instead of nine inline rows.
panel_submenu = NSMenu.alloc().initWithTitle_(_t(self.language, "switch_panel"))
for panel in panels.all_panels():
item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
_panel_title(panel, self.language),
"selectPanel:",
"",
)
item.setTarget_(self)
item.setRepresentedObject_(panel.id)
item.setState_(1 if panel.id == self.active_panel.id else 0)
panel_submenu.addItem_(item)
panel_parent = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
_t(self.language, "switch_panel"), "", ""
)
panel_parent.setSubmenu_(panel_submenu)
menu.addItem_(panel_parent)
# Provider visibility lives in one "Hide Sections ▸" submenu row, grouped
# with the panel-themes submenu: both are drill-in rows that shape what
# the popover shows.
hide_submenu = NSMenu.alloc().initWithTitle_(_t(self.language, "hide_sections_menu"))
hide_claude_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
_t(self.language, "claude_name"),
"toggleHideClaude:",
"",
)
hide_claude_item.setTarget_(self)
hide_claude_item.setState_(1 if _hide_claude_enabled() else 0)
hide_submenu.addItem_(hide_claude_item)
hide_codex_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
_t(self.language, "codex_name"),
"toggleHideCodex:",
"",
)
hide_codex_item.setTarget_(self)
hide_codex_item.setState_(1 if _hide_codex_enabled() else 0)
hide_submenu.addItem_(hide_codex_item)
hide_parent = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
_t(self.language, "hide_sections_menu"), "", ""
)
hide_parent.setSubmenu_(hide_submenu)
menu.addItem_(hide_parent)
# Plain on/off switches sit together in the second group.
menu.addItem_(NSMenuItem.separatorItem())
launch_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
_t(self.language, "launch_at_login"),
"toggleLaunchAtLogin:",
"",
)
launch_item.setTarget_(self)
launch_item.setState_(1 if login_item.is_enabled() else 0)
menu.addItem_(launch_item)
quota_notifications_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
_t(self.language, "quota_notifications_menu"),
"toggleQuotaNotifications:",
"",
)
quota_notifications_item.setTarget_(self)
quota_notifications_item.setState_(1 if _quota_notifications_enabled() else 0)
menu.addItem_(quota_notifications_item)
# Project Butler: one toggle that hands last session's progress to the next
# one. Tooltip carries the full explanation so the menu line stays short.
menu.addItem_(NSMenuItem.separatorItem())
butler_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
_t(self.language, "project_butler"),
"toggleSessionResume:",
"",
)
butler_item.setTarget_(self)
butler_item.setState_(1 if _session_resume_enabled() else 0)
butler_item.setToolTip_(_t(self.language, "project_butler_tooltip"))
menu.addItem_(butler_item)
self._switch_menu_action_taken = False
menu.popUpMenuPositioningItem_atLocation_inView_(None, NSMakePoint(0, 0), sender)
if self._switch_menu_action_taken:
self._resync_popover_after_menu()
else:
self._close_popover_after_menu()
def selectPanel_(self, sender: Any) -> None:
self._mark_switch_menu_action()
panel_id = str(sender.representedObject())
self._set_active_panel_id(panel_id)
def toggleCritters_(self, sender: Any) -> None:
self._mark_switch_menu_action()
enabled = not bool(self.critters_enabled)
self.critters_enabled = enabled
_save_critters_enabled(enabled)
self.critter_frame = 0
self.dragon_frame = 0
if hasattr(sender, "setState_"):
sender.setState_(1 if enabled else 0)
if hasattr(sender, "setTitle_"):
sender.setTitle_(
_t(self.language, "dismiss_critters" if enabled else "summon_critters")
)
self._set_button_title(self.latest_state)
def toggleLaunchAtLogin_(self, sender: Any) -> None:
self._mark_switch_menu_action()
try:
if login_item.is_enabled():
login_item.disable()
else:
login_item.enable()
except Exception:
if os.environ.get("USAGE_DEBUG") == "1":
logger.warning("toggle launch at login failed", exc_info=True)
def toggleHideClaude_(self, sender: Any) -> None:
self._mark_switch_menu_action()
prefs = _load_preferences()
enabled = not _hide_claude_enabled(prefs)
prefs["hide_claude_section"] = enabled
_save_preferences(prefs)
if hasattr(sender, "setState_"):
sender.setState_(1 if enabled else 0)
self.latest_state.hide_claude = enabled
self.popover_controller.setState_(self.latest_state)
self._set_button_title(self.latest_state)
def toggleHideCodex_(self, sender: Any) -> None:
self._mark_switch_menu_action()
prefs = _load_preferences()
enabled = not _hide_codex_enabled(prefs)
prefs["hide_codex_section"] = enabled
_save_preferences(prefs)
if hasattr(sender, "setState_"):
sender.setState_(1 if enabled else 0)
self.latest_state.hide_codex = enabled
self.popover_controller.setState_(self.latest_state)
self._set_button_title(self.latest_state)
def toggleQuotaNotifications_(self, sender: Any) -> None:
self._mark_switch_menu_action()
prefs = _load_preferences()
enabled = not _quota_notifications_enabled(prefs)
prefs["quota_notifications"] = enabled
_save_preferences(prefs)
if hasattr(sender, "setState_"):
sender.setState_(1 if enabled else 0)
if enabled:
self._request_notification_authorization()
def toggleSessionResume_(self, sender: Any) -> None:
self._mark_switch_menu_action()
thread = threading.Thread(target=self._toggle_session_resume_in_background, daemon=True)
thread.start()
def _toggle_session_resume_in_background(self) -> None:
import setup_hook
output = io.StringIO()
ok = True
enabled = False
try:
with contextlib.redirect_stdout(output), contextlib.redirect_stderr(output):
if setup_hook.is_resume_enabled():
setup_hook.disable_session_resume()
else:
ok = setup_hook.enable_session_resume() == 0
enabled = ok
except SystemExit as exc:
if exc.code:
ok = False
print(exc.code, file=output)
except Exception as exc:
ok = False
print(f"{type(exc).__name__}: {exc}", file=output)
self.performSelectorOnMainThread_withObject_waitUntilDone_(
"_finishSessionResume:",
{"ok": ok, "enabled": enabled, "output": output.getvalue().strip()},
False,
)
def _finishSessionResume_(self, result: dict[str, Any]) -> None:
alert = _make_alert()
if result.get("ok", True):
key = "resume_enabled_restart" if result.get("enabled") else "resume_disabled_msg"
alert.setMessageText_(_t(self.language, key))
else:
alert.setMessageText_(_t(self.language, "resume_action_failed"))
alert.setInformativeText_(str(result.get("output") or ""))
alert.runModal()
self._refresh()
def _clear_stale_update_cache(self) -> None:
try:
current_version = _current_version()
prefs = _load_preferences()
updated_cache = update_gate.stale_cache_reset(prefs, current_version)
if updated_cache is not None:
prefs["last_update_check"] = updated_cache
_save_preferences(prefs)
except Exception:
pass
def _maybe_check_update_in_background(self) -> None: