cc-pets 2.2.1 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/CC_BRIDGE.md +5 -2
  2. package/CC_BRIDGE.zh-CN.md +4 -2
  3. package/CHANGELOG.md +60 -0
  4. package/CHANGELOG.zh-CN.md +60 -0
  5. package/CONTRIBUTING.md +13 -10
  6. package/CONTRIBUTING.zh-CN.md +11 -10
  7. package/README.md +113 -24
  8. package/README.zh-CN.md +89 -28
  9. package/Resources/zh-Hans.lproj/Localizable.strings +568 -17
  10. package/Sources/CCPets/{CCPetsAppDelegate+AgentEvents.m → App/CCPetsAppDelegate+AgentEvents.m} +15 -5
  11. package/Sources/CCPets/{CCPetsAppDelegate+AgentStatus.m → App/CCPetsAppDelegate+AgentStatus.m} +82 -23
  12. package/Sources/CCPets/{CCPetsAppDelegate+Bridge.m → App/CCPetsAppDelegate+Bridge.m} +35 -24
  13. package/Sources/CCPets/{CCPetsAppDelegate+Pets.m → App/CCPetsAppDelegate+Pets.m} +17 -3
  14. package/Sources/CCPets/{CCPetsAppDelegate+Private.h → App/CCPetsAppDelegate+Private.h} +70 -22
  15. package/Sources/CCPets/App/CCPetsAppDelegate+Profiles.m +238 -0
  16. package/Sources/CCPets/{CCPetsAppDelegate+Quota.m → App/CCPetsAppDelegate+Quota.m} +47 -32
  17. package/Sources/CCPets/{CCPetsAppDelegate+Settings.m → App/CCPetsAppDelegate+Settings.m} +86 -98
  18. package/Sources/CCPets/{CCPetsAppDelegate+Speech.m → App/CCPetsAppDelegate+Speech.m} +8 -4
  19. package/Sources/CCPets/App/CCPetsAppDelegate+Workbench.m +139 -0
  20. package/Sources/CCPets/{CCPetsAppDelegate.h → App/CCPetsAppDelegate.h} +15 -0
  21. package/Sources/CCPets/{CCPetsAppDelegate.m → App/CCPetsAppDelegate.m} +107 -11
  22. package/Sources/CCPets/App/CCPetsOpenCommand.h +13 -0
  23. package/Sources/CCPets/App/CCPetsOpenCommand.m +99 -0
  24. package/Sources/CCPets/{main.m → App/main.m} +68 -1
  25. package/Sources/CCPets/{CCPetsBridge.h → Bridge/CCPetsBridge.h} +17 -4
  26. package/Sources/CCPets/{CCPetsBridge.m → Bridge/CCPetsBridge.m} +32 -17
  27. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.h +10 -0
  28. package/Sources/CCPets/Bridge/CCPetsBridgeCLI.m +792 -0
  29. package/Sources/CCPets/Bridge/CCPetsBridgeCore.h +60 -0
  30. package/Sources/CCPets/Bridge/CCPetsBridgeCore.m +558 -0
  31. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.h +24 -0
  32. package/Sources/CCPets/Bridge/CCPetsBridgeSetup.m +501 -0
  33. package/Sources/CCPets/Bridge/CCPetsBridgeStore.h +103 -0
  34. package/Sources/CCPets/Bridge/CCPetsBridgeStore.m +779 -0
  35. package/Sources/CCPets/Integrations/CCPetsCLISupport.h +75 -0
  36. package/Sources/CCPets/Integrations/CCPetsCLISupport.m +342 -0
  37. package/Sources/CCPets/Integrations/CCPetsEvents.h +15 -0
  38. package/Sources/CCPets/{CCPetsEvents.m → Integrations/CCPetsEvents.m} +23 -0
  39. package/Sources/CCPets/Integrations/CCPetsIntegrations.h +51 -0
  40. package/Sources/CCPets/Integrations/CCPetsIntegrations.m +662 -0
  41. package/Sources/CCPets/Integrations/CCPetsProfiles.h +38 -0
  42. package/Sources/CCPets/Integrations/CCPetsProfiles.m +516 -0
  43. package/Sources/CCPets/{CCPetsTerminalFocus.m → Integrations/CCPetsTerminalFocus.m} +42 -12
  44. package/Sources/CCPets/Pet/CCPetsPetStore.h +12 -0
  45. package/Sources/CCPets/Pet/CCPetsPetStore.m +476 -0
  46. package/Sources/CCPets/{CCPetsPhrases.h → Pet/CCPetsPhrases.h} +11 -2
  47. package/Sources/CCPets/{CCPetsPhrases.m → Pet/CCPetsPhrases.m} +19 -2
  48. package/Sources/CCPets/{CCPetsPhrasesEditor.m → Pet/CCPetsPhrasesEditor.m} +4 -1
  49. package/Sources/CCPets/Pet/PetView+Interaction.m +207 -0
  50. package/Sources/CCPets/Pet/PetView+Menu.m +598 -0
  51. package/Sources/CCPets/Pet/PetView+MicroBehavior.m +234 -0
  52. package/Sources/CCPets/Pet/PetView+Private.h +81 -0
  53. package/Sources/CCPets/{PetView.h → Pet/PetView.h} +3 -5
  54. package/Sources/CCPets/Pet/PetView.m +635 -0
  55. package/Sources/CCPets/Support/CCPetsDoctor.h +25 -0
  56. package/Sources/CCPets/Support/CCPetsDoctor.m +632 -0
  57. package/Sources/CCPets/Support/CCPetsJSON.h +27 -0
  58. package/Sources/CCPets/Support/CCPetsJSON.m +397 -0
  59. package/Sources/CCPets/{CCPetsL10n.h → Support/CCPetsL10n.h} +3 -1
  60. package/Sources/CCPets/{CCPetsL10n.m → Support/CCPetsL10n.m} +30 -1
  61. package/Sources/CCPets/Support/CCPetsPreferences.h +31 -0
  62. package/Sources/CCPets/Support/CCPetsPreferences.m +85 -0
  63. package/Sources/CCPets/UI/CCPetsDiagnosticsPage.h +25 -0
  64. package/Sources/CCPets/UI/CCPetsDiagnosticsPage.m +440 -0
  65. package/Sources/CCPets/UI/CCPetsFormBuilder.h +42 -0
  66. package/Sources/CCPets/UI/CCPetsFormBuilder.m +268 -0
  67. package/Sources/CCPets/{CCPetsGlassView.h → UI/CCPetsGlassView.h} +5 -1
  68. package/Sources/CCPets/{CCPetsGlassView.m → UI/CCPetsGlassView.m} +25 -7
  69. package/Sources/CCPets/UI/CCPetsMainWindow.h +55 -0
  70. package/Sources/CCPets/UI/CCPetsMainWindow.m +730 -0
  71. package/Sources/CCPets/UI/CCPetsSettingsPage.h +62 -0
  72. package/Sources/CCPets/UI/CCPetsSettingsPage.m +917 -0
  73. package/Sources/CCPets/UI/CCPetsUIStyle.h +132 -0
  74. package/Sources/CCPets/UI/CCPetsUIStyle.m +816 -0
  75. package/Sources/CCPets/UI/CCPetsUsageChartView.h +15 -0
  76. package/Sources/CCPets/UI/CCPetsUsageChartView.m +284 -0
  77. package/Sources/CCPets/UI/CCPetsUsagePage.h +32 -0
  78. package/Sources/CCPets/UI/CCPetsUsagePage.m +717 -0
  79. package/Sources/CCPets/UI/CCPetsUsageShared.h +53 -0
  80. package/Sources/CCPets/UI/CCPetsUsageStore.m +120 -0
  81. package/Sources/CCPets/UI/CCPetsUsageWidgets.h +30 -0
  82. package/Sources/CCPets/UI/CCPetsUsageWidgets.m +201 -0
  83. package/Sources/CCPets/UI/CCPetsWorkbench.h +40 -0
  84. package/Sources/CCPets/UI/CCPetsWorkbenchPages.h +13 -0
  85. package/Sources/CCPets/UI/CCPetsWorkbenchPages.m +783 -0
  86. package/Sources/CCPets/{MenuToggleSwitch.m → UI/MenuToggleSwitch.m} +1 -0
  87. package/Sources/CCPets/{CCPetsCodexRateLimits.h → Usage/CCPetsCodexRateLimits.h} +1 -0
  88. package/Sources/CCPets/{CCPetsCodexRateLimits.m → Usage/CCPetsCodexRateLimits.m} +10 -3
  89. package/Sources/CCPets/{CCPetsQuotaHistory.h → Usage/CCPetsQuotaHistory.h} +3 -0
  90. package/Sources/CCPets/{CCPetsQuotaHistory.m → Usage/CCPetsQuotaHistory.m} +58 -0
  91. package/Sources/CCPets/Usage/CCPetsUsage+ClaudeReader.m +436 -0
  92. package/Sources/CCPets/Usage/CCPetsUsage+CodexReader.m +392 -0
  93. package/Sources/CCPets/Usage/CCPetsUsage+CodexSessions.m +484 -0
  94. package/Sources/CCPets/Usage/CCPetsUsage+Internal.h +96 -0
  95. package/Sources/CCPets/Usage/CCPetsUsage+Models.m +285 -0
  96. package/Sources/CCPets/Usage/CCPetsUsage+TokenTotals.m +655 -0
  97. package/Sources/CCPets/Usage/CCPetsUsage.h +57 -0
  98. package/Sources/CCPets/Usage/CCPetsUsage.m +225 -0
  99. package/Sources/CCPets/Usage/CCPetsUsageMode.h +10 -0
  100. package/Sources/CCPets/Usage/CCPetsUsageMode.m +163 -0
  101. package/Sources/CCPets/{CCPetsUsageMonitor.h → Usage/CCPetsUsageMonitor.h} +3 -0
  102. package/Sources/CCPets/{CCPetsUsageMonitor.m → Usage/CCPetsUsageMonitor.m} +163 -6
  103. package/Sources/CCPets/Usage/QuotaDashboardView+Primitives.m +328 -0
  104. package/Sources/CCPets/Usage/QuotaDashboardView+Private.h +103 -0
  105. package/Sources/CCPets/Usage/QuotaDashboardView+Rendering.m +616 -0
  106. package/Sources/CCPets/{QuotaDashboardView.h → Usage/QuotaDashboardView.h} +17 -0
  107. package/Sources/CCPets/Usage/QuotaDashboardView.m +587 -0
  108. package/THIRD_PARTY_NOTICES.md +1 -1
  109. package/THIRD_PARTY_NOTICES.zh-CN.md +1 -1
  110. package/bin/cc-pets +8 -6
  111. package/bin/claude-with-pet +10 -2
  112. package/bin/codex-with-pet +13 -5
  113. package/package.json +1 -1
  114. package/scripts/build.sh +7 -3
  115. package/scripts/i18n.zsh +9 -52
  116. package/scripts/install-app.sh +4 -0
  117. package/scripts/install-shell-integration.sh +17 -10
  118. package/scripts/uninstall-shell-integration.sh +6 -1
  119. package/Sources/CCPets/CCPetsEvents.h +0 -10
  120. package/Sources/CCPets/CCPetsUsage.h +0 -36
  121. package/Sources/CCPets/CCPetsUsage.m +0 -2069
  122. package/Sources/CCPets/PetView.m +0 -1839
  123. package/Sources/CCPets/QuotaDashboardView.m +0 -1145
  124. package/scripts/bridge/cli.mjs +0 -237
  125. package/scripts/bridge/core.mjs +0 -228
  126. package/scripts/bridge/hook.mjs +0 -150
  127. package/scripts/bridge/install.mjs +0 -311
  128. package/scripts/bridge/mcp-server.mjs +0 -308
  129. package/scripts/bridge/options.mjs +0 -87
  130. package/scripts/bridge/process.mjs +0 -151
  131. package/scripts/bridge/reservations.mjs +0 -248
  132. package/scripts/bridge/store.mjs +0 -433
  133. package/scripts/bridge/watch.mjs +0 -69
  134. package/scripts/check-l10n.mjs +0 -168
  135. package/scripts/configure-updater.mjs +0 -43
  136. package/scripts/detect-cli.mjs +0 -68
  137. package/scripts/doctor.mjs +0 -470
  138. package/scripts/i18n.mjs +0 -122
  139. package/scripts/install-claude-hooks.mjs +0 -253
  140. package/scripts/install-codex-hooks.mjs +0 -78
  141. package/scripts/integration-markers.mjs +0 -51
  142. package/scripts/locales/zh-Hans.json +0 -366
  143. package/scripts/pet-store.mjs +0 -415
  144. package/scripts/uninstall-integrations.mjs +0 -205
  145. /package/Sources/CCPets/{CCPetsAppDelegate+Update.m → App/CCPetsAppDelegate+Update.m} +0 -0
  146. /package/Sources/CCPets/{CCPetsVersion.h → App/CCPetsVersion.h} +0 -0
  147. /package/Sources/CCPets/{CCPetsVersion.m → App/CCPetsVersion.m} +0 -0
  148. /package/Sources/CCPets/{CCPetsTerminalFocus.h → Integrations/CCPetsTerminalFocus.h} +0 -0
  149. /package/Sources/CCPets/{CCPetsImageLoader.h → Pet/CCPetsImageLoader.h} +0 -0
  150. /package/Sources/CCPets/{CCPetsImageLoader.m → Pet/CCPetsImageLoader.m} +0 -0
  151. /package/Sources/CCPets/{CCPetsPetSize.h → Pet/CCPetsPetSize.h} +0 -0
  152. /package/Sources/CCPets/{CCPetsPetSize.m → Pet/CCPetsPetSize.m} +0 -0
  153. /package/Sources/CCPets/{CCPetsPhrasesEditor.h → Pet/CCPetsPhrasesEditor.h} +0 -0
  154. /package/Sources/CCPets/{CCPetsPreviews.h → Pet/CCPetsPreviews.h} +0 -0
  155. /package/Sources/CCPets/{CCPetsPreviews.m → Pet/CCPetsPreviews.m} +0 -0
  156. /package/Sources/CCPets/Resources/{/351/273/230/350/256/244.webp" → ByteMochi.webp} +0 -0
  157. /package/Sources/CCPets/{CCPetsCleanup.h → Support/CCPetsCleanup.h} +0 -0
  158. /package/Sources/CCPets/{CCPetsCleanup.m → Support/CCPetsCleanup.m} +0 -0
  159. /package/Sources/CCPets/{CCPetsPaths.h → Support/CCPetsPaths.h} +0 -0
  160. /package/Sources/CCPets/{CCPetsPaths.m → Support/CCPetsPaths.m} +0 -0
  161. /package/Sources/CCPets/{CCPetsSystemMonitor.h → Support/CCPetsSystemMonitor.h} +0 -0
  162. /package/Sources/CCPets/{CCPetsSystemMonitor.m → Support/CCPetsSystemMonitor.m} +0 -0
  163. /package/Sources/CCPets/{CCPetsGlassMenu.h → UI/CCPetsGlassMenu.h} +0 -0
  164. /package/Sources/CCPets/{CCPetsGlassMenu.m → UI/CCPetsGlassMenu.m} +0 -0
  165. /package/Sources/CCPets/{MenuChoiceRow.h → UI/MenuChoiceRow.h} +0 -0
  166. /package/Sources/CCPets/{MenuChoiceRow.m → UI/MenuChoiceRow.m} +0 -0
  167. /package/Sources/CCPets/{MenuHintView.h → UI/MenuHintView.h} +0 -0
  168. /package/Sources/CCPets/{MenuHintView.m → UI/MenuHintView.m} +0 -0
  169. /package/Sources/CCPets/{MenuPetSizeView.h → UI/MenuPetSizeView.h} +0 -0
  170. /package/Sources/CCPets/{MenuPetSizeView.m → UI/MenuPetSizeView.m} +0 -0
  171. /package/Sources/CCPets/{MenuToggleSwitch.h → UI/MenuToggleSwitch.h} +0 -0
@@ -0,0 +1,783 @@
1
+ #import "CCPetsWorkbenchPages.h"
2
+ #import "CCPetsDiagnosticsPage.h"
3
+ #import "CCPetsFormBuilder.h"
4
+ #import "CCPetsL10n.h"
5
+ #import "CCPetsMainWindow.h"
6
+ #import "CCPetsUIStyle.h"
7
+ #import "CCPetsUsagePage.h"
8
+ #import "CCPetsWorkbench.h"
9
+ #import <QuartzCore/QuartzCore.h>
10
+ #import <objc/runtime.h>
11
+
12
+ static id<CCPetsWorkbenchSource> WorkbenchSource(void) {
13
+ id delegate = NSApp.delegate;
14
+ return [delegate respondsToSelector:@selector(workbenchSessions)] ? delegate : nil;
15
+ }
16
+
17
+ static NSDictionary *PetCardSnapshot(void) {
18
+ id delegate = NSApp.delegate;
19
+ return [delegate conformsToProtocol:@protocol(CCPetsPetCardSource)] ? [delegate petCardSnapshot] : nil;
20
+ }
21
+
22
+ static NSString *RelativeTime(NSTimeInterval timestamp) {
23
+ NSTimeInterval age = fmax(0, NSDate.date.timeIntervalSince1970 - timestamp);
24
+ if (age < 5) return L(@"just now");
25
+ if (age < 60) return [NSString stringWithFormat:L(@"%.0fs ago"), age];
26
+ if (age < 3600) return [NSString stringWithFormat:L(@"%.0fm ago"), floor(age / 60)];
27
+ return [NSString stringWithFormat:L(@"%.0fh ago"), floor(age / 3600)];
28
+ }
29
+
30
+ // 控件的 target 只能是对象,用它把 action 转成 block。
31
+ @interface CCPetsWorkbenchHandler : NSObject
32
+ @property(nonatomic, copy) void (^block)(id sender);
33
+ - (void)invoke:(id)sender;
34
+ @end
35
+
36
+ @implementation CCPetsWorkbenchHandler
37
+ - (void)invoke:(id)sender {
38
+ if (self.block) self.block(sender);
39
+ }
40
+ @end
41
+
42
+ // 带 block 的小按钮。handler 挂在按钮上(关联对象),按钮释放时一起释放。
43
+ static NSButton *ActionButton(NSString *title, BOOL prominent, void (^action)(void)) {
44
+ NSButton *button = [NSButton buttonWithTitle:title target:nil action:nil];
45
+ button.controlSize = NSControlSizeSmall;
46
+ button.font = [NSFont systemFontOfSize:NSFont.smallSystemFontSize weight:prominent ? NSFontWeightSemibold
47
+ : NSFontWeightRegular];
48
+ if (prominent) button.bezelColor = CCPetsAccentColor();
49
+ CCPetsWorkbenchHandler *handler = [CCPetsWorkbenchHandler new];
50
+ handler.block = ^(id sender) { action(); };
51
+ button.target = handler;
52
+ button.action = @selector(invoke:);
53
+ static char HandlerKey;
54
+ objc_setAssociatedObject(button, &HandlerKey, handler, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
55
+ [button setContentHuggingPriority:NSLayoutPriorityRequired forOrientation:NSLayoutConstraintOrientationHorizontal];
56
+ [button setContentCompressionResistancePriority:NSLayoutPriorityRequired
57
+ forOrientation:NSLayoutConstraintOrientationHorizontal];
58
+ return button;
59
+ }
60
+
61
+ #pragma mark - 部件
62
+
63
+ // 环形进度:底轨 + 剩余量的弧。
64
+ @interface CCPetsRingView : NSView
65
+ @property(nonatomic) double fraction;
66
+ @property(nonatomic) NSColor *color;
67
+ @end
68
+
69
+ @implementation CCPetsRingView
70
+ - (NSSize)intrinsicContentSize { return NSMakeSize(44, 44); }
71
+ - (void)drawRect:(NSRect)dirtyRect {
72
+ NSRect box = NSInsetRect(self.bounds, 3, 3);
73
+ NSPoint center = NSMakePoint(NSMidX(box), NSMidY(box));
74
+ NSBezierPath *track = [NSBezierPath bezierPathWithOvalInRect:box];
75
+ track.lineWidth = 5;
76
+ [CCPetsRingTrackColor() set];
77
+ [track stroke];
78
+ double fraction = MIN(1, MAX(0, self.fraction));
79
+ if (fraction <= 0) return;
80
+ NSBezierPath *arc = [NSBezierPath bezierPath];
81
+ [arc appendBezierPathWithArcWithCenter:center radius:NSWidth(box) / 2 startAngle:90
82
+ endAngle:90 - 360 * fraction clockwise:YES];
83
+ arc.lineWidth = 5;
84
+ arc.lineCapStyle = NSLineCapStyleRound;
85
+ [self.color set];
86
+ [arc stroke];
87
+ }
88
+ @end
89
+
90
+ // 概览的宠物卡:底色从卡片色淡淡过渡到强调青,宠物站在左边。
91
+ @interface CCPetsHeroCard : CCPetsCardView
92
+ @end
93
+
94
+ @interface CCPetsHeroCard ()
95
+ @property(nonatomic) CAGradientLayer *gradient;
96
+ @end
97
+
98
+ @implementation CCPetsHeroCard
99
+ - (void)updateLayer {
100
+ [super updateLayer];
101
+ if (!self.gradient) {
102
+ self.gradient = [CAGradientLayer layer];
103
+ self.gradient.startPoint = CGPointMake(0, 0.5);
104
+ self.gradient.endPoint = CGPointMake(1, 0.5);
105
+ [self.layer insertSublayer:self.gradient atIndex:0];
106
+ }
107
+ self.gradient.frame = self.layer.bounds;
108
+ self.gradient.colors = @[(id)CCPetsSelectionColor().CGColor, (id)CCPetsCardColor().CGColor];
109
+ }
110
+ - (void)layout {
111
+ [super layout];
112
+ self.needsDisplay = YES;
113
+ }
114
+ @end
115
+
116
+ #pragma mark - 概览
117
+
118
+ @interface CCPetsOverviewPage ()
119
+ @property(nonatomic) CCPetsFormBuilder *form;
120
+ @end
121
+
122
+ @implementation CCPetsOverviewPage
123
+
124
+ - (void)loadView {
125
+ self.form = [[CCPetsFormBuilder alloc] initWithTitle:L(@"Overview") subtitle:[self dateText]];
126
+ self.view = self.form.view;
127
+ for (NSNotificationName name in @[CCPetsPetCardDidChangeNotification, CCPetsUsageStoreDidChangeNotification,
128
+ CCPetsDiagnosticsDidChangeNotification, CCPetsWorkbenchQuotasDidChangeNotification]) {
129
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(dataDidChange:) name:name object:nil];
130
+ }
131
+ [self render];
132
+ [CCPetsUsageStore loadIfStale];
133
+ [CCPetsDiagnosticsStore refreshIfStale];
134
+ }
135
+
136
+ - (void)dealloc {
137
+ [NSNotificationCenter.defaultCenter removeObserver:self];
138
+ }
139
+
140
+ - (NSString *)dateText {
141
+ NSDateFormatter *formatter = [NSDateFormatter new];
142
+ formatter.locale = [NSLocale localeWithLocaleIdentifier:CCPetsCurrentLanguage()];
143
+ [formatter setLocalizedDateFormatFromTemplate:@"EEEEMMMMd"];
144
+ return [formatter stringFromDate:NSDate.date];
145
+ }
146
+
147
+ // 名片通知一条 Agent 事件会来好几次,合并到下一轮 runloop 只重排一次。
148
+ - (void)dataDidChange:(NSNotification *)notification {
149
+ [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(render) object:nil];
150
+ [self performSelector:@selector(render) withObject:nil afterDelay:0];
151
+ }
152
+
153
+ - (void)render {
154
+ [self.form removeAllContent];
155
+ [self.form addView:[self heroCard]];
156
+ NSView *notice = [self diagnosticsNotice];
157
+ if (notice) [self.form addView:notice];
158
+ NSView *quotas = [self quotaCards];
159
+ if (quotas) [self.form addView:quotas];
160
+ }
161
+
162
+ #pragma mark 宠物卡
163
+
164
+ // 今天的用量:取 90 天数据的最后一天(就是今天),两家相加。
165
+ - (NSArray<NSArray<NSString *> *> *)todayStats {
166
+ NSDictionary *results = CCPetsUsageStore.results;
167
+ if (!results) {
168
+ NSString *waiting = L(@"Reading…");
169
+ return @[@[L(@"Total today"), @"–", waiting],
170
+ @[L(@"Input"), @"–", @""],
171
+ @[L(@"Output"), @"–", @""],
172
+ @[L(@"Cached Input"), @"–", @""],
173
+ @[L(@"Requests"), @"–", @""]];
174
+ }
175
+ NSMutableArray<NSDictionary *> *days = [NSMutableArray array];
176
+ NSMutableSet<NSString *> *models = [NSMutableSet set];
177
+ for (NSString *provider in results) {
178
+ NSDictionary *today = [results[provider][@"daily"] lastObject];
179
+ [days addObject:CCPetsUsageDayTotals(today)];
180
+ for (NSString *model in today[@"models"]) {
181
+ if ([today[@"models"][model][@"requests"] unsignedLongLongValue] > 0) {
182
+ [models addObject:[provider stringByAppendingString:model]];
183
+ }
184
+ }
185
+ }
186
+ return CCPetsUsageMetricItems(L(@"Total today"), CCPetsUsageSum(days), models.count);
187
+ }
188
+
189
+ static const CGFloat HeroExtraPadding = 15;
190
+
191
+ - (NSView *)heroCard {
192
+ NSDictionary *snapshot = PetCardSnapshot();
193
+ NSString *state = snapshot[@"state"] ?: @"idle";
194
+ CCPetsHeroCard *card = [CCPetsHeroCard new];
195
+
196
+ CCPetsSpriteView *sprite = [[CCPetsSpriteView alloc] initWithFrame:NSZeroRect];
197
+ [sprite setSheet:snapshot[@"sheet"] rowCount:[snapshot[@"rowCount"] integerValue] ?: 9];
198
+ sprite.state = state;
199
+ // 脚下一团淡影,宠物不会像贴在卡片上。
200
+ CCPetsColorDot *floor = [[CCPetsColorDot alloc] initWithColor:CCPetsHoverColor() diameter:8];
201
+ [floor removeConstraints:floor.constraints];
202
+ NSMutableArray<NSView *> *views = [NSMutableArray arrayWithObjects:floor, sprite, nil];
203
+
204
+ // 宠物此刻在说的那句(状态卡副行),没有 Agent 在跑时不显示。
205
+ NSString *line = snapshot[@"detail"];
206
+ NSView *bubble = nil;
207
+ if (line.length > 0) {
208
+ NSTextField *text = CCPetsLabel(line, 11, NSFontWeightMedium, CCPetsCardColor());
209
+ CCPetsCardView *pill = [CCPetsCardView new];
210
+ pill.cornerRadius = 9;
211
+ pill.fillColor = CCPetsInkColor();
212
+ text.translatesAutoresizingMaskIntoConstraints = NO;
213
+ [pill addSubview:text];
214
+ [NSLayoutConstraint activateConstraints:@[
215
+ [text.leadingAnchor constraintEqualToAnchor:pill.leadingAnchor constant:10],
216
+ [text.trailingAnchor constraintEqualToAnchor:pill.trailingAnchor constant:-10],
217
+ [text.topAnchor constraintEqualToAnchor:pill.topAnchor constant:4],
218
+ [text.bottomAnchor constraintEqualToAnchor:pill.bottomAnchor constant:-4],
219
+ [pill.widthAnchor constraintLessThanOrEqualToConstant:220],
220
+ ]];
221
+ bubble = pill;
222
+ [views addObject:pill];
223
+ }
224
+
225
+ NSTextField *name = CCPetsLabel(snapshot[@"name"] ?: @"CC Pets", 17, NSFontWeightBold, CCPetsInkColor());
226
+ CCPetsChipView *chip = [[CCPetsChipView alloc] initWithText:snapshot[@"status"] ?: L(@"Idle")
227
+ kind:CCPetsStatusKindForAgentState(state)];
228
+ NSStackView *nameLine = [NSStackView stackViewWithViews:@[name, chip]];
229
+ nameLine.spacing = 8;
230
+ nameLine.alignment = NSLayoutAttributeCenterY;
231
+ NSView *statRow = CCPetsMetricRow([self todayStats]);
232
+ NSStackView *side = [NSStackView stackViewWithViews:@[nameLine, statRow]];
233
+ side.orientation = NSUserInterfaceLayoutOrientationVertical;
234
+ side.alignment = NSLayoutAttributeLeading;
235
+ // 数字这一排和名字之间 22pt;整组居中点同时下移一半,名字不动,只有数字往下 8pt。
236
+ side.spacing = 22;
237
+ [views addObject:side];
238
+
239
+ for (NSView *view in views) {
240
+ view.translatesAutoresizingMaskIntoConstraints = NO;
241
+ [card addSubview:view];
242
+ }
243
+ NSMutableArray<NSLayoutConstraint *> *constraints = [NSMutableArray arrayWithArray:@[
244
+ // 素材格子是 140×150,按同样比例放大一些当主角。
245
+ [sprite.widthAnchor constraintEqualToConstant:122],
246
+ [sprite.heightAnchor constraintEqualToConstant:131],
247
+ [sprite.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:32],
248
+ // 卡片上下各留 15pt 余量(比内容高 30pt),宠物和数字在卡片里居中,不显得挤。
249
+ [sprite.bottomAnchor constraintEqualToAnchor:card.bottomAnchor constant:-18 - HeroExtraPadding],
250
+ [floor.centerXAnchor constraintEqualToAnchor:sprite.centerXAnchor],
251
+ [floor.centerYAnchor constraintEqualToAnchor:sprite.bottomAnchor constant:-2],
252
+ [floor.widthAnchor constraintEqualToConstant:84],
253
+ [floor.heightAnchor constraintEqualToConstant:10],
254
+ [side.leadingAnchor constraintEqualToAnchor:sprite.trailingAnchor constant:32],
255
+ [side.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-24],
256
+ [statRow.widthAnchor constraintEqualToAnchor:side.widthAnchor],
257
+ [side.centerYAnchor constraintEqualToAnchor:card.centerYAnchor constant:4],
258
+ ]];
259
+ if (bubble) {
260
+ [constraints addObjectsFromArray:@[
261
+ [bubble.topAnchor constraintEqualToAnchor:card.topAnchor constant:16 + HeroExtraPadding],
262
+ [bubble.centerXAnchor constraintEqualToAnchor:sprite.centerXAnchor constant:10],
263
+ [bubble.leadingAnchor constraintGreaterThanOrEqualToAnchor:card.leadingAnchor constant:12],
264
+ [sprite.topAnchor constraintEqualToAnchor:bubble.bottomAnchor constant:4],
265
+ ]];
266
+ } else {
267
+ [constraints addObject:[sprite.topAnchor constraintEqualToAnchor:card.topAnchor constant:22 + HeroExtraPadding]];
268
+ }
269
+ [NSLayoutConstraint activateConstraints:constraints];
270
+ return card;
271
+ }
272
+
273
+ #pragma mark 诊断提醒
274
+
275
+ - (NSView *)diagnosticsNotice {
276
+ NSUInteger count = CCPetsDiagnosticsStore.issueCount;
277
+ if (count == 0) return nil;
278
+ NSMutableArray<NSString *> *titles = [NSMutableArray array];
279
+ for (NSDictionary *section in CCPetsDiagnosticsStore.sections) {
280
+ for (NSDictionary *result in section[@"results"]) {
281
+ if ([result[@"level"] isEqualToString:@"warn"] || [result[@"level"] isEqualToString:@"fail"]) {
282
+ [titles addObject:result[@"title"]];
283
+ }
284
+ }
285
+ }
286
+ CCPetsCardView *card = [CCPetsCardView new];
287
+ card.stripeColor = CCPetsStatusColor(CCPetsStatusWarn);
288
+ NSTextField *title = CCPetsLabel(count == 1 ? L(@"Diagnostics found 1 item to fix")
289
+ : [NSString stringWithFormat:L(@"Diagnostics found %lu items to fix"), (unsigned long)count],
290
+ 13, NSFontWeightSemibold, CCPetsInkColor());
291
+ NSTextField *detail = CCPetsLabel([[titles subarrayWithRange:NSMakeRange(0, MIN(2, titles.count))]
292
+ componentsJoinedByString:L(@"; ")], 11, NSFontWeightRegular, CCPetsSecondaryInkColor());
293
+ [detail setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow
294
+ forOrientation:NSLayoutConstraintOrientationHorizontal];
295
+ NSButton *open = ActionButton(L(@"View"), NO, ^{
296
+ [CCPetsMainWindowController presentPage:CCPetsMainWindowPageDiagnostics];
297
+ });
298
+ for (NSView *view in @[title, detail, open]) {
299
+ view.translatesAutoresizingMaskIntoConstraints = NO;
300
+ [card addSubview:view];
301
+ }
302
+ [NSLayoutConstraint activateConstraints:@[
303
+ [title.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:16],
304
+ [title.topAnchor constraintEqualToAnchor:card.topAnchor constant:10],
305
+ [title.trailingAnchor constraintLessThanOrEqualToAnchor:open.leadingAnchor constant:-12],
306
+ [detail.leadingAnchor constraintEqualToAnchor:title.leadingAnchor],
307
+ [detail.topAnchor constraintEqualToAnchor:title.bottomAnchor constant:2],
308
+ [detail.trailingAnchor constraintLessThanOrEqualToAnchor:open.leadingAnchor constant:-12],
309
+ [detail.bottomAnchor constraintEqualToAnchor:card.bottomAnchor constant:-10],
310
+ [open.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-14],
311
+ [open.centerYAnchor constraintEqualToAnchor:card.centerYAnchor],
312
+ ]];
313
+ return card;
314
+ }
315
+
316
+ #pragma mark 额度
317
+
318
+ - (NSView *)quotaCards {
319
+ NSArray<NSDictionary *> *quotas = [WorkbenchSource() workbenchQuotas];
320
+ if (quotas.count == 0) return nil;
321
+ NSMutableArray<NSView *> *cards = [NSMutableArray array];
322
+ for (NSDictionary *quota in quotas) {
323
+ CCPetsCardView *card = [CCPetsCardView new];
324
+ CCPetsColorDot *dot = [[CCPetsColorDot alloc] initWithColor:CCPetsProviderColor(quota[@"provider"]) diameter:8];
325
+ dot.layer.cornerRadius = 2;
326
+ NSString *quotaName = quota[@"profileName"] ?: quota[@"provider"];
327
+ NSTextField *name = CCPetsLabel(quotaName, 13, NSFontWeightSemibold, CCPetsInkColor());
328
+ name.lineBreakMode = NSLineBreakByTruncatingMiddle;
329
+ name.toolTip = quotaName;
330
+ [name setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow
331
+ forOrientation:NSLayoutConstraintOrientationHorizontal];
332
+ NSStackView *title = [NSStackView stackViewWithViews:@[dot, name]];
333
+ title.spacing = 7;
334
+ title.alignment = NSLayoutAttributeCenterY;
335
+ if ([quota[@"hasDiagnosticIssues"] boolValue]) {
336
+ [title addArrangedSubview:ActionButton(L(@"Check Diagnostics"), NO, ^{
337
+ [CCPetsMainWindowController presentPage:CCPetsMainWindowPageDiagnostics];
338
+ })];
339
+ }
340
+ BOOL api = [quota[@"apiMode"] boolValue];
341
+ CCPetsChipView *badge = nil;
342
+ if (api) {
343
+ badge = [[CCPetsChipView alloc] initWithText:L(@"API") kind:CCPetsStatusIdle];
344
+ } else if (quota[@"paceLevel"]) {
345
+ NSInteger level = [quota[@"paceLevel"] integerValue];
346
+ CCPetsStatusKind kind = level >= 3 ? CCPetsStatusError : (level == 2 ? CCPetsStatusWarn
347
+ : (level == 0 ? CCPetsStatusOK : CCPetsStatusIdle));
348
+ badge = [[CCPetsChipView alloc] initWithText:quota[@"pace"] kind:kind];
349
+ }
350
+ badge.hidesDot = YES;
351
+ NSView *left, *right;
352
+ if (api) {
353
+ NSDictionary *usage = quota[@"usage"];
354
+ NSDictionary *tokens = [usage[@"tokenUsage"] isKindOfClass:NSDictionary.class] ? usage[@"tokenUsage"] : nil;
355
+ NSDictionary *month = [tokens[@"month"] isKindOfClass:NSDictionary.class] ? tokens[@"month"] : nil;
356
+ NSArray *daily = [tokens[@"monthDaily"] isKindOfClass:NSArray.class] ? tokens[@"monthDaily"] : @[];
357
+ NSUInteger elapsedDays = 0;
358
+ NSTimeInterval now = NSDate.date.timeIntervalSince1970;
359
+ for (NSDictionary *day in daily) if ([day[@"timestamp"] doubleValue] <= now) elapsedDays++;
360
+ NSNumber *calls = [month[@"request_count"] isKindOfClass:NSNumber.class] ? month[@"request_count"] : nil;
361
+ NSNumber *total = [month[@"total_tokens"] isKindOfClass:NSNumber.class] ? month[@"total_tokens"] : nil;
362
+ NSNumber *output = [month[@"output_tokens"] isKindOfClass:NSNumber.class] ? month[@"output_tokens"] : nil;
363
+ NSString *average = calls ? [NSString stringWithFormat:L(@"%@/day avg"),
364
+ [NSNumberFormatter localizedStringFromNumber:@(llround(calls.doubleValue / MAX((NSUInteger)1, elapsedDays)))
365
+ numberStyle:NSNumberFormatterDecimalStyle]] : L(@"--/day avg");
366
+ NSString *inputText = total ? CCPetsFormatTokens((unsigned long long)fmax(0, total.doubleValue - output.doubleValue)) : @"–";
367
+ NSString *outputText = total ? CCPetsFormatTokens(output.unsignedLongLongValue) : @"–";
368
+ NSString *split = [NSString stringWithFormat:@"%@ %@ · %@ %@", L(@"Input"), inputText, L(@"Output"), outputText];
369
+ left = [self apiMetric:calls title:L(@"Calls this month") tokens:NO detail:average];
370
+ right = [self apiMetric:total title:L(@"Tokens this month") tokens:YES detail:split];
371
+ } else {
372
+ left = [self ringWithRemaining:quota[@"fiveRemaining"] title:L(@"5-hour left") reset:quota[@"fiveReset"]];
373
+ right = [self ringWithRemaining:quota[@"weekRemaining"] title:L(@"Weekly left") reset:quota[@"weekReset"]];
374
+ }
375
+ NSStackView *metrics = [NSStackView stackViewWithViews:@[left, right]];
376
+ metrics.distribution = NSStackViewDistributionFillEqually;
377
+ metrics.alignment = NSLayoutAttributeTop;
378
+ metrics.spacing = 12;
379
+ for (NSView *view in @[title, metrics]) {
380
+ view.translatesAutoresizingMaskIntoConstraints = NO;
381
+ [card addSubview:view];
382
+ }
383
+ NSMutableArray *constraints = [NSMutableArray arrayWithArray:@[
384
+ [title.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:14],
385
+ [title.topAnchor constraintEqualToAnchor:card.topAnchor constant:12],
386
+ [metrics.leadingAnchor constraintEqualToAnchor:card.leadingAnchor constant:14],
387
+ [metrics.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-14],
388
+ [metrics.topAnchor constraintEqualToAnchor:title.bottomAnchor constant:12],
389
+ [metrics.bottomAnchor constraintEqualToAnchor:card.bottomAnchor constant:-14],
390
+ ]];
391
+ if (badge) {
392
+ badge.translatesAutoresizingMaskIntoConstraints = NO;
393
+ [card addSubview:badge];
394
+ [constraints addObjectsFromArray:@[
395
+ [badge.trailingAnchor constraintEqualToAnchor:card.trailingAnchor constant:-12],
396
+ [badge.centerYAnchor constraintEqualToAnchor:title.centerYAnchor],
397
+ [title.trailingAnchor constraintLessThanOrEqualToAnchor:badge.leadingAnchor constant:-8],
398
+ ]];
399
+ } else {
400
+ [constraints addObject:[title.trailingAnchor constraintLessThanOrEqualToAnchor:card.trailingAnchor constant:-14]];
401
+ }
402
+ [NSLayoutConstraint activateConstraints:constraints];
403
+ [cards addObject:card];
404
+ }
405
+ NSStackView *grid = [NSStackView stackViewWithViews:@[]];
406
+ grid.orientation = NSUserInterfaceLayoutOrientationVertical;
407
+ grid.alignment = NSLayoutAttributeLeading;
408
+ grid.spacing = 12;
409
+ for (NSUInteger index = 0; index < cards.count; index += 2) {
410
+ NSView *right = index + 1 < cards.count ? cards[index + 1] : [NSView new];
411
+ NSStackView *row = [NSStackView stackViewWithViews:@[cards[index], right]];
412
+ row.distribution = NSStackViewDistributionFillEqually;
413
+ row.alignment = NSLayoutAttributeTop;
414
+ row.spacing = 12;
415
+ [grid addArrangedSubview:row];
416
+ [row.widthAnchor constraintEqualToAnchor:grid.widthAnchor].active = YES;
417
+ }
418
+ // 所有账号卡片使用相同高度,由内容最多的卡片决定,API 文案换行时也保持对齐。
419
+ for (NSUInteger index = 1; index < cards.count; index++) {
420
+ [cards[index].heightAnchor constraintEqualToAnchor:cards.firstObject.heightAnchor].active = YES;
421
+ }
422
+ return grid;
423
+ }
424
+
425
+ - (NSString *)resetText:(NSNumber *)reset {
426
+ if (!reset) return L(@"Waiting for data");
427
+ NSDateFormatter *formatter = [NSDateFormatter new];
428
+ formatter.locale = [NSLocale localeWithLocaleIdentifier:CCPetsCurrentLanguage()];
429
+ [formatter setLocalizedDateFormatFromTemplate:reset.doubleValue - NSDate.date.timeIntervalSince1970 < 86400
430
+ ? @"HH:mm" : @"EEEHH:mm"];
431
+ return [NSString stringWithFormat:L(@"Resets %@"),
432
+ [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:reset.doubleValue]]];
433
+ }
434
+
435
+ - (NSView *)ringWithRemaining:(NSNumber *)remaining title:(NSString *)title reset:(NSNumber *)reset {
436
+ CCPetsRingView *ring = [CCPetsRingView new];
437
+ [ring.widthAnchor constraintEqualToConstant:44].active = YES;
438
+ [ring.heightAnchor constraintEqualToConstant:44].active = YES;
439
+ ring.fraction = remaining.doubleValue / 100;
440
+ ring.color = remaining && remaining.doubleValue < 20 ? CCPetsStatusColor(CCPetsStatusWarn) : CCPetsAccentColor();
441
+ NSTextField *percent = CCPetsNumberLabel(remaining ? [NSString stringWithFormat:@"%.0f%%", remaining.doubleValue] : @"–",
442
+ 17, NSFontWeightBold, CCPetsInkColor());
443
+ NSStackView *texts = [NSStackView stackViewWithViews:@[percent,
444
+ CCPetsLabel(title, 11, NSFontWeightRegular, CCPetsSecondaryInkColor()),
445
+ CCPetsLabel([self resetText:reset], 11, NSFontWeightRegular, CCPetsTertiaryInkColor())]];
446
+ texts.orientation = NSUserInterfaceLayoutOrientationVertical;
447
+ texts.alignment = NSLayoutAttributeLeading;
448
+ texts.spacing = 0;
449
+ NSStackView *block = [NSStackView stackViewWithViews:@[ring, texts]];
450
+ block.spacing = 10;
451
+ block.alignment = NSLayoutAttributeCenterY;
452
+ return block;
453
+ }
454
+
455
+ - (NSView *)apiMetric:(NSNumber *)value title:(NSString *)title tokens:(BOOL)tokens detail:(NSString *)detail {
456
+ NSString *text = !value ? @"–" : (tokens ? CCPetsFormatTokens(value.unsignedLongLongValue)
457
+ : [NSNumberFormatter localizedStringFromNumber:value numberStyle:NSNumberFormatterDecimalStyle]);
458
+ NSTextField *caption = CCPetsWrappingLabel(detail, 11, NSFontWeightRegular, CCPetsTertiaryInkColor());
459
+ NSStackView *stack = [NSStackView stackViewWithViews:@[
460
+ CCPetsLabel(title, 11, NSFontWeightRegular, CCPetsSecondaryInkColor()),
461
+ CCPetsNumberLabel(text, 20, NSFontWeightBold, CCPetsInkColor()), caption]];
462
+ stack.orientation = NSUserInterfaceLayoutOrientationVertical;
463
+ stack.alignment = NSLayoutAttributeLeading;
464
+ stack.spacing = 3;
465
+ [caption.widthAnchor constraintEqualToAnchor:stack.widthAnchor].active = YES;
466
+ return stack;
467
+ }
468
+
469
+ @end
470
+
471
+ #pragma mark - 会话
472
+
473
+ // 会话表的列宽:状态胶囊、最近活动、按钮固定,会话名和当前在做平分剩下的。
474
+ static const CGFloat SessionStateWidth = 92, SessionTimeWidth = 72, SessionActionWidth = 82;
475
+
476
+ @interface CCPetsSessionsPage ()
477
+ @property(nonatomic) CCPetsFormBuilder *form;
478
+ @property(nonatomic) NSTimer *timer;
479
+ // 上一次渲染用的数据和相对时间。走表时没变就不重排,免得按钮在鼠标底下被换掉。
480
+ @property(nonatomic) NSArray *renderedState;
481
+ @end
482
+
483
+ @implementation CCPetsSessionsPage
484
+
485
+ - (void)loadView {
486
+ self.form = [[CCPetsFormBuilder alloc] initWithTitle:L(@"Sessions") subtitle:@""];
487
+ self.view = self.form.view;
488
+ [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(dataDidChange:)
489
+ name:CCPetsPetCardDidChangeNotification object:nil];
490
+ [self render];
491
+ }
492
+
493
+ - (void)viewDidAppear {
494
+ [super viewDidAppear];
495
+ [WorkbenchSource() markWorkbenchMessagesSeen];
496
+ [self.timer invalidate];
497
+ // 最近活动的"几分钟前"和 Bridge 消息要走表才会更新;会话状态本身有通知,不靠它。
498
+ __weak typeof(self) weakSelf = self;
499
+ self.timer = [NSTimer scheduledTimerWithTimeInterval:5 repeats:YES block:^(NSTimer *timer) {
500
+ CCPetsSessionsPage *page = weakSelf;
501
+ if (!page.view.window.isVisible || page.view.window.isMiniaturized) return;
502
+ [page render];
503
+ }];
504
+ self.timer.tolerance = 1;
505
+ }
506
+
507
+ - (void)viewWillDisappear {
508
+ [super viewWillDisappear];
509
+ [self.timer invalidate];
510
+ self.timer = nil;
511
+ }
512
+
513
+ - (void)dealloc {
514
+ [_timer invalidate];
515
+ [NSNotificationCenter.defaultCenter removeObserver:self];
516
+ }
517
+
518
+ - (void)dataDidChange:(NSNotification *)notification {
519
+ [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(render) object:nil];
520
+ [self performSelector:@selector(render) withObject:nil afterDelay:0];
521
+ }
522
+
523
+ - (void)render {
524
+ id<CCPetsWorkbenchSource> source = WorkbenchSource();
525
+ NSArray<NSDictionary *> *sessions = [source workbenchSessions] ?: @[];
526
+ NSDictionary *messages = [source workbenchMessages] ?: @{};
527
+ NSArray *deliveries = messages[@"deliveries"] ?: @[];
528
+ NSArray *pending = messages[@"pending"] ?: @[];
529
+ NSMutableArray<NSString *> *times = [NSMutableArray array];
530
+ for (NSDictionary *session in sessions) [times addObject:RelativeTime([session[@"updatedAt"] doubleValue])];
531
+ NSArray *state = @[sessions, messages, times];
532
+ if ([state isEqual:self.renderedState]) return;
533
+ self.renderedState = state;
534
+ NSUInteger waiting = 0;
535
+ for (NSDictionary *entry in pending) waiting += [entry[@"count"] unsignedIntegerValue];
536
+ NSMutableArray<NSString *> *summary = [NSMutableArray arrayWithObject:sessions.count == 1
537
+ ? L(@"1 session online") : [NSString stringWithFormat:L(@"%ld sessions online"), (long)sessions.count]];
538
+ if ([messages[@"enabled"] boolValue]) {
539
+ [summary addObject:[NSString stringWithFormat:L(@"%lu CC Bridge messages recently"), (unsigned long)deliveries.count]];
540
+ }
541
+ self.form.subtitleLabel.stringValue = [summary componentsJoinedByString:@" · "];
542
+
543
+ NSPoint scroll = self.form.scrollView.contentView.bounds.origin;
544
+ [self.form removeAllContent];
545
+ [self.form addView:[self sessionsTable:sessions]];
546
+ [self.form addGroupTitle:@"CC Bridge" note:waiting > 0 ? [NSString stringWithFormat:L(@"%lu waiting in an inbox"),
547
+ (unsigned long)waiting] : nil info:L(@"Only message exchanges are displayed")];
548
+ [self.form addView:[self messagesCard:messages]];
549
+ // 定时重排不要把用户滚到一半的位置弹回顶部。
550
+ [self.form.scrollView.documentView layoutSubtreeIfNeeded];
551
+ [self.form.scrollView.contentView scrollToPoint:scroll];
552
+ [self.form.scrollView reflectScrolledClipView:self.form.scrollView.contentView];
553
+ }
554
+
555
+ #pragma mark 会话表
556
+
557
+ - (NSView *)cardWithRows:(NSArray<NSView *> *)rows {
558
+ NSStackView *stack = [NSStackView stackViewWithViews:@[]];
559
+ stack.orientation = NSUserInterfaceLayoutOrientationVertical;
560
+ stack.spacing = 0;
561
+ stack.translatesAutoresizingMaskIntoConstraints = NO;
562
+ for (NSView *row in rows) {
563
+ if (stack.arrangedSubviews.count > 0) {
564
+ NSView *rule = [CCPetsFormBuilder separator];
565
+ [stack addArrangedSubview:rule];
566
+ [rule.widthAnchor constraintEqualToAnchor:stack.widthAnchor].active = YES;
567
+ }
568
+ row.translatesAutoresizingMaskIntoConstraints = NO;
569
+ [stack addArrangedSubview:row];
570
+ [row.widthAnchor constraintEqualToAnchor:stack.widthAnchor].active = YES;
571
+ }
572
+ CCPetsCardView *card = [CCPetsCardView new];
573
+ [card addSubview:stack];
574
+ [NSLayoutConstraint activateConstraints:@[
575
+ [stack.leadingAnchor constraintEqualToAnchor:card.leadingAnchor],
576
+ [stack.trailingAnchor constraintEqualToAnchor:card.trailingAnchor],
577
+ [stack.topAnchor constraintEqualToAnchor:card.topAnchor],
578
+ [stack.bottomAnchor constraintEqualToAnchor:card.bottomAnchor],
579
+ ]];
580
+ return card;
581
+ }
582
+
583
+ // 五列:状态、会话、当前在做、最近活动、操作。cells 里 nil 的位置用空视图占位。
584
+ - (NSView *)sessionRowWithCells:(NSArray<NSView *> *)cells height:(CGFloat)height {
585
+ NSView *row = [NSView new];
586
+ for (NSView *cell in cells) {
587
+ cell.translatesAutoresizingMaskIntoConstraints = NO;
588
+ [row addSubview:cell];
589
+ [cell.centerYAnchor constraintEqualToAnchor:row.centerYAnchor].active = YES;
590
+ }
591
+ NSView *state = cells[0], *name = cells[1], *doing = cells[2], *time = cells[3], *action = cells[4];
592
+ [NSLayoutConstraint activateConstraints:@[
593
+ [row.heightAnchor constraintEqualToConstant:height],
594
+ [state.leadingAnchor constraintEqualToAnchor:row.leadingAnchor constant:14],
595
+ [name.leadingAnchor constraintEqualToAnchor:row.leadingAnchor constant:14 + SessionStateWidth + 12],
596
+ [doing.leadingAnchor constraintEqualToAnchor:name.trailingAnchor constant:12],
597
+ [doing.widthAnchor constraintEqualToAnchor:name.widthAnchor multiplier:1.15],
598
+ [time.leadingAnchor constraintEqualToAnchor:doing.trailingAnchor constant:12],
599
+ [time.widthAnchor constraintEqualToConstant:SessionTimeWidth],
600
+ [action.leadingAnchor constraintEqualToAnchor:time.trailingAnchor constant:12],
601
+ [action.widthAnchor constraintEqualToConstant:SessionActionWidth],
602
+ [action.trailingAnchor constraintEqualToAnchor:row.trailingAnchor constant:-14],
603
+ ]];
604
+ [state.trailingAnchor constraintLessThanOrEqualToAnchor:name.leadingAnchor constant:-8].active = YES;
605
+ return row;
606
+ }
607
+
608
+ - (NSView *)sessionsTable:(NSArray<NSDictionary *> *)sessions {
609
+ NSMutableArray<NSView *> *headerCells = [NSMutableArray array];
610
+ for (NSString *title in @[L(@"Status"), L(@"Session"), L(@"Doing"), L(@"Last Active"), @""]) {
611
+ NSTextField *label = CCPetsLabel(title, 11, NSFontWeightSemibold, CCPetsTertiaryInkColor());
612
+ [headerCells addObject:label];
613
+ }
614
+ ((NSTextField *)headerCells[3]).alignment = NSTextAlignmentRight;
615
+ NSMutableArray<NSView *> *rows = [NSMutableArray arrayWithObject:[self sessionRowWithCells:headerCells height:30]];
616
+ if (sessions.count == 0) {
617
+ NSTextField *empty = CCPetsLabel(L(@"No sessions online."), 12, NSFontWeightRegular, CCPetsTertiaryInkColor());
618
+ NSView *row = [NSView new];
619
+ empty.translatesAutoresizingMaskIntoConstraints = NO;
620
+ [row addSubview:empty];
621
+ [NSLayoutConstraint activateConstraints:@[
622
+ [empty.leadingAnchor constraintEqualToAnchor:row.leadingAnchor constant:14],
623
+ [empty.centerYAnchor constraintEqualToAnchor:row.centerYAnchor],
624
+ [row.heightAnchor constraintEqualToConstant:52],
625
+ ]];
626
+ [rows addObject:row];
627
+ }
628
+ for (NSDictionary *session in sessions) {
629
+ NSString *state = session[@"state"];
630
+ BOOL approval = [state isEqualToString:@"approval"];
631
+ CCPetsChipView *chip = [[CCPetsChipView alloc] initWithText:session[@"status"]
632
+ kind:CCPetsStatusKindForAgentState(state)];
633
+ [chip.widthAnchor constraintLessThanOrEqualToConstant:SessionStateWidth].active = YES;
634
+
635
+ NSString *title = [session[@"name"] length] > 0 ? session[@"name"] : session[@"provider"];
636
+ NSTextField *name = CCPetsLabel(title, 13, NSFontWeightSemibold, CCPetsInkColor());
637
+ NSMutableArray<NSString *> *parts = [NSMutableArray arrayWithObject:session[@"provider"]];
638
+ if ([session[@"terminal"] length] > 0) [parts addObject:session[@"terminal"]];
639
+ NSUInteger mail = [session[@"pendingMessages"] unsignedIntegerValue];
640
+ if (mail > 0) [parts addObject:[NSString stringWithFormat:L(@"%lu waiting"), (unsigned long)mail]];
641
+ NSTextField *detail = CCPetsLabel([parts componentsJoinedByString:@" · "], 11, NSFontWeightRegular,
642
+ CCPetsTertiaryInkColor());
643
+ NSStackView *nameCell = [NSStackView stackViewWithViews:@[name, detail]];
644
+ nameCell.orientation = NSUserInterfaceLayoutOrientationVertical;
645
+ nameCell.alignment = NSLayoutAttributeLeading;
646
+ nameCell.spacing = 1;
647
+ for (NSView *view in @[name, detail, nameCell]) {
648
+ [view setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow
649
+ forOrientation:NSLayoutConstraintOrientationHorizontal];
650
+ }
651
+
652
+ NSString *tool = session[@"tool"];
653
+ NSTextField *doing = CCPetsLabel(tool.length > 0 ? tool : @"–", 12, NSFontWeightRegular,
654
+ tool.length > 0 ? CCPetsInkColor() : CCPetsTertiaryInkColor());
655
+ if (tool.length > 0) doing.font = [NSFont monospacedSystemFontOfSize:11 weight:NSFontWeightRegular];
656
+ [doing setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow
657
+ forOrientation:NSLayoutConstraintOrientationHorizontal];
658
+
659
+ NSTextField *time = CCPetsNumberLabel(RelativeTime([session[@"updatedAt"] doubleValue]), 12,
660
+ NSFontWeightRegular, approval ? CCPetsStatusColor(CCPetsStatusWarn) : CCPetsSecondaryInkColor());
661
+ time.alignment = NSTextAlignmentRight;
662
+
663
+ NSString *sessionID = session[@"id"];
664
+ NSButton *jump = ActionButton(L(@"Go to Terminal"), approval, ^{
665
+ [WorkbenchSource() focusWorkbenchSessionWithID:sessionID];
666
+ });
667
+ NSView *actionCell = [NSView new];
668
+ jump.translatesAutoresizingMaskIntoConstraints = NO;
669
+ [actionCell addSubview:jump];
670
+ [NSLayoutConstraint activateConstraints:@[
671
+ [jump.trailingAnchor constraintEqualToAnchor:actionCell.trailingAnchor],
672
+ [jump.centerYAnchor constraintEqualToAnchor:actionCell.centerYAnchor],
673
+ [actionCell.heightAnchor constraintEqualToAnchor:jump.heightAnchor],
674
+ ]];
675
+ [rows addObject:[self sessionRowWithCells:@[chip, nameCell, doing, time, actionCell] height:50]];
676
+ }
677
+ return [self cardWithRows:rows];
678
+ }
679
+
680
+ #pragma mark 消息
681
+
682
+ - (NSView *)messageRowWithLeading:(NSView *)leading title:(NSView *)title detail:(NSView *)detail
683
+ trailing:(NSArray<NSView *> *)trailing {
684
+ NSView *row = [NSView new];
685
+ NSStackView *right = [NSStackView stackViewWithViews:trailing];
686
+ right.spacing = 8;
687
+ right.alignment = NSLayoutAttributeCenterY;
688
+ [right setContentHuggingPriority:NSLayoutPriorityRequired forOrientation:NSLayoutConstraintOrientationHorizontal];
689
+ [right setContentCompressionResistancePriority:NSLayoutPriorityRequired
690
+ forOrientation:NSLayoutConstraintOrientationHorizontal];
691
+ for (NSView *view in @[leading, title, detail, right]) {
692
+ view.translatesAutoresizingMaskIntoConstraints = NO;
693
+ [row addSubview:view];
694
+ [view.centerYAnchor constraintEqualToAnchor:row.centerYAnchor].active = YES;
695
+ }
696
+ [title setContentHuggingPriority:NSLayoutPriorityDefaultHigh forOrientation:NSLayoutConstraintOrientationHorizontal];
697
+ [detail setContentCompressionResistancePriority:NSLayoutPriorityDefaultLow
698
+ forOrientation:NSLayoutConstraintOrientationHorizontal];
699
+ [NSLayoutConstraint activateConstraints:@[
700
+ [row.heightAnchor constraintEqualToConstant:40],
701
+ [leading.leadingAnchor constraintEqualToAnchor:row.leadingAnchor constant:14],
702
+ [leading.widthAnchor constraintEqualToConstant:44],
703
+ // 标题不设宽度上限:右边空着时名字能完整显示,最宽只到 detail / 右侧按钮之前。
704
+ [title.leadingAnchor constraintEqualToAnchor:leading.trailingAnchor constant:8],
705
+ [detail.leadingAnchor constraintEqualToAnchor:title.trailingAnchor constant:12],
706
+ [detail.trailingAnchor constraintLessThanOrEqualToAnchor:right.leadingAnchor constant:-12],
707
+ [right.trailingAnchor constraintEqualToAnchor:row.trailingAnchor constant:-14],
708
+ ]];
709
+ return row;
710
+ }
711
+
712
+ // 发件人 → 收件人,名字加粗,箭头淡一些。
713
+ - (NSTextField *)routeFrom:(NSString *)from to:(NSString *)to {
714
+ NSMutableAttributedString *text = [NSMutableAttributedString new];
715
+ NSDictionary *strong = @{NSFontAttributeName: [NSFont systemFontOfSize:12 weight:NSFontWeightSemibold],
716
+ NSForegroundColorAttributeName: CCPetsInkColor()};
717
+ [text appendAttributedString:[[NSAttributedString alloc] initWithString:from ?: @"" attributes:strong]];
718
+ [text appendAttributedString:[[NSAttributedString alloc] initWithString:@" → " attributes:@{
719
+ NSFontAttributeName: [NSFont systemFontOfSize:12], NSForegroundColorAttributeName: CCPetsTertiaryInkColor()}]];
720
+ [text appendAttributedString:[[NSAttributedString alloc] initWithString:to ?: @"" attributes:strong]];
721
+ // 富文本标签默认会折行;这里一律单行,名字太长就在末尾省略,不把"→ 收件人"挤到第二行。
722
+ // 抗压缩优先级比右边的说明高:位置不够时先让说明让位。
723
+ NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
724
+ paragraph.lineBreakMode = NSLineBreakByTruncatingTail;
725
+ [text addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, text.length)];
726
+ NSTextField *label = [NSTextField labelWithAttributedString:text];
727
+ label.usesSingleLineMode = YES;
728
+ label.cell.wraps = NO;
729
+ label.maximumNumberOfLines = 1;
730
+ label.lineBreakMode = NSLineBreakByTruncatingTail;
731
+ // 窗口太窄仍被截断时,悬停能看到完整的发件人和收件人。
732
+ label.toolTip = [NSString stringWithFormat:@"%@ → %@", from ?: @"", to ?: @""];
733
+ [label setContentCompressionResistancePriority:NSLayoutPriorityDefaultHigh
734
+ forOrientation:NSLayoutConstraintOrientationHorizontal];
735
+ return label;
736
+ }
737
+
738
+ - (NSView *)messagesCard:(NSDictionary *)messages {
739
+ NSMutableArray<NSView *> *rows = [NSMutableArray array];
740
+ if (![messages[@"enabled"] boolValue]) {
741
+ NSView *row = [CCPetsFormBuilder rowWithTitle:L(@"CC Bridge is off")
742
+ subtitle:L(@"Turn it on from the pet's right-click menu to let sessions message each other.") controls:@[]];
743
+ return [self cardWithRows:@[row]];
744
+ }
745
+ for (NSDictionary *entry in messages[@"pending"]) {
746
+ NSString *session = entry[@"session"];
747
+ NSUInteger count = [entry[@"count"] unsignedIntegerValue];
748
+ NSTextField *icon = CCPetsLabel(@"", 12, NSFontWeightRegular, CCPetsTertiaryInkColor());
749
+ NSTextField *name = CCPetsLabel(entry[@"name"], 12, NSFontWeightSemibold, CCPetsInkColor());
750
+ NSTextField *detail = CCPetsLabel(count == 1 ? L(@"1 message waiting. Say anything in that terminal to deliver it.")
751
+ : [NSString stringWithFormat:L(@"%lu messages waiting. Say anything in that terminal to deliver them."),
752
+ (unsigned long)count], 12, NSFontWeightRegular, CCPetsSecondaryInkColor());
753
+ CCPetsChipView *chip = [[CCPetsChipView alloc] initWithText:L(@"Waiting") kind:CCPetsStatusWarn];
754
+ NSButton *jump = ActionButton(L(@"Go to Terminal"), YES, ^{
755
+ [WorkbenchSource() focusBridgeSessionWithID:session];
756
+ });
757
+ [rows addObject:[self messageRowWithLeading:icon title:name detail:detail trailing:@[chip, jump]]];
758
+ }
759
+ NSArray *deliveries = messages[@"deliveries"];
760
+ for (NSDictionary *delivery in deliveries) {
761
+ NSDate *date = [NSDate dateWithTimeIntervalSince1970:[delivery[@"at"] doubleValue]];
762
+ NSTextField *time = CCPetsNumberLabel([NSDateFormatter localizedStringFromDate:date
763
+ dateStyle:NSDateFormatterNoStyle timeStyle:NSDateFormatterShortStyle], 12, NSFontWeightRegular,
764
+ CCPetsTertiaryInkColor());
765
+ NSTextField *route = [self routeFrom:delivery[@"from"] to:delivery[@"to"]];
766
+ NSTextField *detail = CCPetsLabel(@"", 12, NSFontWeightRegular, CCPetsSecondaryInkColor());
767
+ BOOL unseen = [delivery[@"unseen"] boolValue];
768
+ CCPetsChipView *chip = [[CCPetsChipView alloc] initWithText:unseen ? L(@"Unread") : L(@"Delivered")
769
+ kind:unseen ? CCPetsStatusWork : CCPetsStatusOK];
770
+ NSString *session = delivery[@"toSession"];
771
+ NSButton *jump = ActionButton(L(@"Go to Terminal"), NO, ^{
772
+ [WorkbenchSource() focusBridgeSessionWithID:session];
773
+ });
774
+ jump.toolTip = [NSString stringWithFormat:L(@"Jump to %@'s terminal"), delivery[@"to"]];
775
+ [rows addObject:[self messageRowWithLeading:time title:route detail:detail trailing:@[chip, jump]]];
776
+ }
777
+ if (rows.count == 0) {
778
+ [rows addObject:[CCPetsFormBuilder rowWithTitle:L(@"No messages recently") controls:@[]]];
779
+ }
780
+ return [self cardWithRows:rows];
781
+ }
782
+
783
+ @end