From 3038cd5eeda3dadab178c94ff0f9a88645a7e5e6 Mon Sep 17 00:00:00 2001 From: Jeroen Schweitzer Date: Sat, 23 May 2026 22:49:37 +0200 Subject: [PATCH] =?UTF-8?q?add=20Claude=20meta=20sidebar=20=E2=80=94=20act?= =?UTF-8?q?ivity=20+=20team=20roster?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An always-pickable left-panel tab. Shows Claude activity read from ~/.claude/stats-cache.json (latest day's messages/sessions/tool-calls + lifetime totals, polled) and, when a tmux agent team is running, a roster of its members (colour · name · agent type · model) from the observer's join/left events — nothing re-tailed here. Scoped down from the original ticket: the account/team token budget isn't programmatically exposed under subscription auth (TUI-only; upstream #44328) and live per-member status needs the teammate status stream wired onto the bus — filed as T-158 and T-157 respectively. T-141. Co-Authored-By: Claude Opus 4.7 (1M context) --- .pql/changelog/ticket_history/2026-05.sql | 1 + .pql/changelog/tickets/2026-05.sql | 3 + CHANGELOG.md | 4 + .../claude/src/claude_meta_sidebar.dart | 174 ++++++++++++++++++ lib/builtin/claude/src/claude_stats.dart | 68 +++++++ lib/builtin/claude/src/extension.dart | 12 ++ .../claude/claude_meta_sidebar_test.dart | 66 +++++++ test/builtin/claude/claude_stats_test.dart | 54 ++++++ 8 files changed, 382 insertions(+) create mode 100644 lib/builtin/claude/src/claude_meta_sidebar.dart create mode 100644 lib/builtin/claude/src/claude_stats.dart create mode 100644 test/builtin/claude/claude_meta_sidebar_test.dart create mode 100644 test/builtin/claude/claude_stats_test.dart diff --git a/.pql/changelog/ticket_history/2026-05.sql b/.pql/changelog/ticket_history/2026-05.sql index f54fe37a..08bba666 100644 --- a/.pql/changelog/ticket_history/2026-05.sql +++ b/.pql/changelog/ticket_history/2026-05.sql @@ -2215,3 +2215,4 @@ INSERT INTO ticket_history (ticket_id, field, old_value, new_value, changed_by, INSERT INTO ticket_history (ticket_id, field, old_value, new_value, changed_by, changed_at, created_at, updated_at, deleted_at, hash, canonical_version) VALUES ('T-155', 'status', 'in_progress', 'done', NULL, '2026-05-23 14:50:17', '2026-05-23 14:50:17', '2026-05-23 14:50:17', NULL, 'b471e923f78ed91f05ca6f2dcbd5c85c', 1) ON CONFLICT(hash) DO NOTHING; INSERT INTO ticket_history (ticket_id, field, old_value, new_value, changed_by, changed_at, created_at, updated_at, deleted_at, hash, canonical_version) VALUES ('T-148', 'status', 'backlog', 'in_progress', NULL, '2026-05-23 14:51:55', '2026-05-23 14:51:55', '2026-05-23 14:51:55', NULL, '3002f91cea5919aaefc3e4bc530c7ac2', 1) ON CONFLICT(hash) DO NOTHING; INSERT INTO ticket_history (ticket_id, field, old_value, new_value, changed_by, changed_at, created_at, updated_at, deleted_at, hash, canonical_version) VALUES ('T-141', 'status', 'backlog', 'in_progress', NULL, '2026-05-23 14:51:55', '2026-05-23 14:51:55', '2026-05-23 14:51:55', NULL, '76975080bd78de4d6f69937fd256d4ef', 1) ON CONFLICT(hash) DO NOTHING; +INSERT INTO ticket_history (ticket_id, field, old_value, new_value, changed_by, changed_at, created_at, updated_at, deleted_at, hash, canonical_version) VALUES ('T-148', 'status', 'in_progress', 'done', NULL, '2026-05-23 15:05:29', '2026-05-23 15:05:29', '2026-05-23 15:05:29', NULL, 'd9d9e4c96d94060f929c7c09935d127c', 1) ON CONFLICT(hash) DO NOTHING; diff --git a/.pql/changelog/tickets/2026-05.sql b/.pql/changelog/tickets/2026-05.sql index 08a3f975..9e378d8d 100644 --- a/.pql/changelog/tickets/2026-05.sql +++ b/.pql/changelog/tickets/2026-05.sql @@ -2641,3 +2641,6 @@ Team-wide: Acceptance: roster matches list-panes/config; each row mirrors the member''s model + accept-edits/plan badge + context-usage; status verb and token deltas update live; account budget refreshes on its timer; panel appears only when a team is active. Depends on T-145 (status source) + T-139 (done). ', 'in_progress', 'medium', NULL, NULL, NULL, '2026-05-22 15:59:34', '2026-05-23 14:51:55', NULL, 'e674a22d7a2c67d4fcefc12968185118', 1) ON CONFLICT(id) DO UPDATE SET type=excluded.type, parent_id=excluded.parent_id, title=excluded.title, description=excluded.description, status=excluded.status, priority=excluded.priority, assigned_to=excluded.assigned_to, team=excluded.team, decision_ref=excluded.decision_ref, updated_at=excluded.updated_at, deleted_at=excluded.deleted_at, hash=excluded.hash, canonical_version=excluded.canonical_version WHERE excluded.updated_at > tickets.updated_at OR (excluded.updated_at = tickets.updated_at AND excluded.hash > tickets.hash); +INSERT INTO tickets (id, type, parent_id, title, description, status, priority, assigned_to, team, decision_ref, created_at, updated_at, deleted_at, hash, canonical_version) VALUES ('T-148', 'task', 'T-132', 'Claude transcript disk-usage indicator + cleanup button', 'Surface transcript/session disk usage in the Claude panel with a cleanup affordance so the user can pick and choose what to remove. Per-session sizes (the /*.jsonl files + subagents/), a total, and a button to delete selected sessions'' transcripts. User-driven only — clide never auto-deletes transcript content. Future/''at some point'' per user. Relates to T-146 (session ids) and D-75.', 'done', 'low', NULL, NULL, NULL, '2026-05-23 07:03:18', '2026-05-23 15:05:29', NULL, '90efd726ef844874609653bf21fcfa5c', 1) ON CONFLICT(id) DO UPDATE SET type=excluded.type, parent_id=excluded.parent_id, title=excluded.title, description=excluded.description, status=excluded.status, priority=excluded.priority, assigned_to=excluded.assigned_to, team=excluded.team, decision_ref=excluded.decision_ref, updated_at=excluded.updated_at, deleted_at=excluded.deleted_at, hash=excluded.hash, canonical_version=excluded.canonical_version WHERE excluded.updated_at > tickets.updated_at OR (excluded.updated_at = tickets.updated_at AND excluded.hash > tickets.hash); +INSERT INTO tickets (id, type, parent_id, title, description, status, priority, assigned_to, team, decision_ref, created_at, updated_at, deleted_at, hash, canonical_version) VALUES ('T-157', 'task', 'T-132', 'Team sidebar: live per-member status (mode + context)', 'Extend the Claude meta sidebar (T-141) roster rows with each teammate''s LIVE status — permission-mode badge (default/accept-edits/plan/bypass) and context-token usage — mirroring the per-session strip (T-145/T-150). The data exists: TeamObserver creates a TranscriptPublisher per teammate whose statusStream emits SessionStatus, but it is NEVER published to the MessageBus. Wire it: in team_observer _joined, subscribe to the publisher''s statusStream and publish {agentId, model, permissionMode, contextTokens} to a new ClaudeConversation.memberStatusChannel; cancel on _left. The sidebar subscribes to that channel and updates the matching roster row. Do NOT re-tail transcripts (D-75) — reuse the existing stream. Acceptance: a running team shows each member''s mode badge + context tokens, updating live; module is the single status-forwarding point; tests; coverage >= floor.', 'backlog', 'low', NULL, NULL, NULL, '2026-05-23 20:48:31', '2026-05-23 20:48:31', NULL, 'e7b13a20df653bee06b7b7ac031d29db', 1) ON CONFLICT(id) DO UPDATE SET type=excluded.type, parent_id=excluded.parent_id, title=excluded.title, description=excluded.description, status=excluded.status, priority=excluded.priority, assigned_to=excluded.assigned_to, team=excluded.team, decision_ref=excluded.decision_ref, updated_at=excluded.updated_at, deleted_at=excluded.deleted_at, hash=excluded.hash, canonical_version=excluded.canonical_version WHERE excluded.updated_at > tickets.updated_at OR (excluded.updated_at = tickets.updated_at AND excluded.hash > tickets.hash); +INSERT INTO tickets (id, type, parent_id, title, description, status, priority, assigned_to, team, decision_ref, created_at, updated_at, deleted_at, hash, canonical_version) VALUES ('T-158', 'task', 'T-132', 'Team sidebar: account/team token budget (blocked on upstream)', 'Show the account/subscription usage budget (5-hour + weekly limits, % used, reset times) in the Claude meta sidebar (T-141). BLOCKED: this data is not programmatically exposed under subscription (OAuth) auth as of claude 2.1.150 — verified empirically + via docs (2026-05-23). /usage is TUI-only (headless ''claude -p /usage'' returns only a one-liner); stats-cache.json has activity counts only; the stream-json rate_limit_event is undocumented + needs a billed turn; ''claude auth status --json'' shows plan only. A ''claude usage --json'' + a /v1/organizations/{org}/usage/subscription endpoint are an OPEN, unshipped feature request (GitHub anthropics/claude-code#44328). Revisit when #44328 ships or an API-key usage path exists. See project memory ''claude-usage-budget-not-exposed''.', 'backlog', 'low', NULL, NULL, NULL, '2026-05-23 20:48:38', '2026-05-23 20:48:38', NULL, '4e239019c4cf4982bd653e5dd2c96990', 1) ON CONFLICT(id) DO UPDATE SET type=excluded.type, parent_id=excluded.parent_id, title=excluded.title, description=excluded.description, status=excluded.status, priority=excluded.priority, assigned_to=excluded.assigned_to, team=excluded.team, decision_ref=excluded.decision_ref, updated_at=excluded.updated_at, deleted_at=excluded.deleted_at, hash=excluded.hash, canonical_version=excluded.canonical_version WHERE excluded.updated_at > tickets.updated_at OR (excluded.updated_at = tickets.updated_at AND excluded.hash > tickets.hash); diff --git a/CHANGELOG.md b/CHANGELOG.md index 8851f38f..86754d84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,10 @@ heading, and (b) bumping `pubspec.yaml` `version:` in the same commit. ### Added +- Claude meta sidebar (T-141) — an always-pickable left-panel tab showing + Claude activity (the latest day's messages/sessions/tool-calls plus + lifetime totals, from `stats-cache.json`) and, when a tmux team is + running, a roster of its members (colour · name · agent type · model). - Claude session storage view (T-148) — the `claude.session-storage` command opens a modal listing the workspace's session transcripts with their on-disk sizes and a total, each removable with a two-click diff --git a/lib/builtin/claude/src/claude_meta_sidebar.dart b/lib/builtin/claude/src/claude_meta_sidebar.dart new file mode 100644 index 00000000..288a8473 --- /dev/null +++ b/lib/builtin/claude/src/claude_meta_sidebar.dart @@ -0,0 +1,174 @@ +/// Claude meta sidebar (T-141): an always-pickable left-panel tab showing +/// Claude *activity* (from `~/.claude/stats-cache.json`, polled) and, when a +/// tmux agent team is running, a roster of its members (from the +/// TeamObserver's join/left events — not re-tailed here). +/// +/// The account/team token budget is intentionally absent: it isn't +/// programmatically exposed under subscription auth (see project memory / +/// GitHub anthropics/claude-code#44328). Live per-member status (mode / +/// context) is a follow-up that needs the teammate status stream on the bus. +library; + +import 'dart:async'; +import 'dart:io'; + +import 'package:clide/builtin/claude/src/claude_stats.dart'; +import 'package:clide/builtin/claude/src/claude_status.dart' show shortModelLabel; +import 'package:clide/builtin/claude/src/team_panel_host.dart' show teamColor; +import 'package:clide/kernel/kernel.dart'; +import 'package:clide/widgets/widgets.dart'; +import 'package:flutter/widgets.dart'; + +class ClaudeMetaSidebar extends StatefulWidget { + const ClaudeMetaSidebar({super.key, this.statsLoader, this.pollInterval = const Duration(seconds: 20)}); + + /// Loads the activity stats; defaults to reading `~/.claude/stats-cache.json`. + /// Injected in tests so they don't touch the real filesystem. + final Future Function()? statsLoader; + + /// How often to reload the stats. `Duration.zero` disables polling + /// (initial load only) — used by tests to avoid a pending timer. + final Duration pollInterval; + + @override + State createState() => _ClaudeMetaSidebarState(); +} + +class _ClaudeMetaSidebarState extends State { + ClaudeStats _stats = const ClaudeStats(); + final List _members = []; + StreamSubscription? _joinSub; + StreamSubscription? _leftSub; + Timer? _timer; + late final Future Function() _load; + bool _subscribed = false; + + @override + void initState() { + super.initState(); + _load = widget.statsLoader ?? _fileLoader(); + unawaited(_refreshStats()); + if (widget.pollInterval > Duration.zero) { + _timer = Timer.periodic(widget.pollInterval, (_) => unawaited(_refreshStats())); + } + } + + static Future Function() _fileLoader() { + final home = Platform.environment['HOME']; + final file = home == null ? null : File('$home/.claude/stats-cache.json'); + return () async { + if (file == null || !await file.exists()) return const ClaudeStats(); + try { + return parseClaudeStats(await file.readAsString()); + } catch (_) { + return const ClaudeStats(); + } + }; + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + if (_subscribed) return; + _subscribed = true; + final events = ClideKernel.of(context).events; + _joinSub = events.on().listen((m) { + if (_members.any((x) => x.agentId == m.agentId)) return; + setState(() => _members.add(m)); + }); + _leftSub = events.on().listen((m) { + setState(() => _members.removeWhere((x) => x.agentId == m.agentId)); + }); + } + + Future _refreshStats() async { + final stats = await _load(); + if (mounted) setState(() => _stats = stats); + } + + @override + void dispose() { + _timer?.cancel(); + _joinSub?.cancel(); + _leftSub?.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final tokens = ClideTheme.of(context).surface; + return ListView( + padding: const EdgeInsets.all(12), + children: [ + _sectionHeader(tokens, 'Activity'), + _activity(tokens), + const SizedBox(height: 16), + _sectionHeader(tokens, 'Team${_members.isEmpty ? '' : ' · ${_members.length}'}'), + _roster(tokens), + ], + ); + } + + Widget _sectionHeader(SurfaceTokens tokens, String label) => Padding( + padding: const EdgeInsets.only(bottom: 6), + child: ClideText(label, fontSize: clideFontSmall, color: tokens.globalTextMuted), + ); + + Widget _activity(SurfaceTokens tokens) { + final latest = _stats.latest; + if (latest == null) { + return ClideText('No activity recorded yet.', muted: true, fontSize: clideFontSmall); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ClideText(latest.date, fontSize: clideFontSmall, color: tokens.globalForeground), + const SizedBox(height: 2), + ClideText( + '${latest.messageCount} msgs · ${latest.sessionCount} sessions · ${latest.toolCallCount} tools', + muted: true, + fontSize: clideFontSmall, + ), + const SizedBox(height: 6), + ClideText( + 'Lifetime: ${_stats.lifetimeMessages} msgs over ${_stats.activeDays} days', + muted: true, + fontSize: clideFontSmall, + ), + ], + ); + } + + Widget _roster(SurfaceTokens tokens) { + if (_members.isEmpty) { + return ClideText('No team active.', muted: true, fontSize: clideFontSmall); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [for (final m in _members) _memberRow(tokens, m)], + ); + } + + Widget _memberRow(SurfaceTokens tokens, TeamMemberJoined m) { + final color = teamColor(m.color, fallback: tokens.globalForeground); + final sub = [m.agentType, if (m.model != null) shortModelLabel(m.model!)].join(' · '); + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + children: [ + Container(width: 8, height: 8, decoration: BoxDecoration(color: color, shape: BoxShape.circle)), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + ClideText(m.name, fontSize: clideFontSmall, color: tokens.globalForeground, maxLines: 1, overflow: TextOverflow.ellipsis), + ClideText(sub, muted: true, fontSize: clideFontSmall, maxLines: 1, overflow: TextOverflow.ellipsis), + ], + ), + ), + ], + ), + ); + } +} diff --git a/lib/builtin/claude/src/claude_stats.dart b/lib/builtin/claude/src/claude_stats.dart new file mode 100644 index 00000000..1690fb89 --- /dev/null +++ b/lib/builtin/claude/src/claude_stats.dart @@ -0,0 +1,68 @@ +/// Reads Claude Code's `~/.claude/stats-cache.json` — per-day activity +/// (message / session / tool-call counts) — for the meta sidebar (T-141). +/// Flutter-free so it unit-tests under `dart test`. This is activity, not the +/// account budget; the budget isn't programmatically exposed (see +/// project memory / GitHub anthropics/claude-code#44328). +library; + +import 'dart:convert'; + +class DailyActivity { + const DailyActivity({ + required this.date, + required this.messageCount, + required this.sessionCount, + required this.toolCallCount, + }); + + final String date; // "YYYY-MM-DD" (sorts chronologically as a string) + final int messageCount; + final int sessionCount; + final int toolCallCount; +} + +class ClaudeStats { + const ClaudeStats({this.lastComputed, this.daily = const []}); + + final String? lastComputed; + final List daily; + + /// The most recent day on record, or null if there's no activity. + DailyActivity? get latest { + if (daily.isEmpty) return null; + return daily.reduce((a, b) => a.date.compareTo(b.date) >= 0 ? a : b); + } + + int get activeDays => daily.length; + int get lifetimeMessages => daily.fold(0, (a, d) => a + d.messageCount); + int get lifetimeSessions => daily.fold(0, (a, d) => a + d.sessionCount); + int get lifetimeToolCalls => daily.fold(0, (a, d) => a + d.toolCallCount); +} + +/// Parse the stats-cache JSON. Returns empty stats on any malformed input — +/// the sidebar degrades to "no activity" rather than throwing. +ClaudeStats parseClaudeStats(String jsonStr) { + Object? j; + try { + j = jsonDecode(jsonStr); + } catch (_) { + return const ClaudeStats(); + } + if (j is! Map) return const ClaudeStats(); + final daily = []; + final da = j['dailyActivity']; + if (da is List) { + for (final e in da) { + if (e is! Map) continue; + daily.add(DailyActivity( + date: '${e['date']}', + messageCount: _int(e['messageCount']), + sessionCount: _int(e['sessionCount']), + toolCallCount: _int(e['toolCallCount']), + )); + } + } + return ClaudeStats(lastComputed: j['lastComputedDate'] as String?, daily: daily); +} + +int _int(Object? v) => v is num ? v.toInt() : 0; diff --git a/lib/builtin/claude/src/extension.dart b/lib/builtin/claude/src/extension.dart index daa6b4b4..f722762d 100644 --- a/lib/builtin/claude/src/extension.dart +++ b/lib/builtin/claude/src/extension.dart @@ -6,6 +6,7 @@ import 'package:clide/builtin/claude/src/claude_config.dart'; import 'package:clide/builtin/claude/src/claude_session_host.dart'; import 'package:clide/builtin/claude/src/session_naming.dart'; import 'package:clide/builtin/claude/src/pane_context_status.dart'; +import 'package:clide/builtin/claude/src/claude_meta_sidebar.dart'; import 'package:clide/builtin/claude/src/session_index.dart'; import 'package:clide/builtin/claude/src/session_storage.dart'; import 'package:clide/builtin/claude/src/team_observer.dart'; @@ -13,6 +14,7 @@ import 'package:clide/builtin/claude/src/team_panel_host.dart'; import 'package:clide/builtin/claude/src/tmux_session.dart' as tmux; import 'package:clide/extension/extension.dart'; import 'package:clide/kernel/kernel.dart'; +import 'package:clide/widgets/widgets.dart'; import 'package:flutter/widgets.dart'; class ClaudeExtension extends ClideExtension { @@ -68,6 +70,16 @@ class ClaudeExtension extends ClideExtension { title: 'Claude: session storage (disk usage + cleanup)', run: _manageStorage, ), + // Always-pickable left-panel tab: Claude activity (from + // stats-cache.json) + the team roster when a team is running (T-141). + TabContribution( + id: 'claude.meta', + slot: Slots.sidebar, + title: 'Activity', + icon: PhosphorIcons.robot, + priority: 60, + build: (_) => const ClaudeMetaSidebar(), + ), // In-pane status slot (T-145): the active Claude pane publishes // its model · permission-mode · context line here. StatusItemContribution( diff --git a/test/builtin/claude/claude_meta_sidebar_test.dart b/test/builtin/claude/claude_meta_sidebar_test.dart new file mode 100644 index 00000000..5f09bf96 --- /dev/null +++ b/test/builtin/claude/claude_meta_sidebar_test.dart @@ -0,0 +1,66 @@ +import 'package:clide/builtin/claude/src/claude_meta_sidebar.dart'; +import 'package:clide/builtin/claude/src/claude_stats.dart'; +import 'package:clide/kernel/kernel.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../../helpers/kernel_fixture.dart'; +import '../../helpers/widget_harness.dart'; + +void main() { + late KernelFixture f; + setUp(() async => f = await KernelFixture.create()); + tearDown(() => f.dispose()); + + ClaudeMetaSidebar sidebar({ClaudeStats stats = const ClaudeStats()}) => ClaudeMetaSidebar( + statsLoader: () async => stats, + pollInterval: Duration.zero, + ); + + testWidgets('shows the latest day + lifetime activity from stats', (tester) async { + const stats = ClaudeStats( + lastComputed: '2026-05-22', + daily: [ + DailyActivity(date: '2026-05-01', messageCount: 100, sessionCount: 2, toolCallCount: 30), + DailyActivity(date: '2026-05-22', messageCount: 250, sessionCount: 5, toolCallCount: 80), + ], + ); + await tester.pumpWidget(harness(f, sidebar(stats: stats))); + await tester.pumpAndSettle(); + + expect(find.text('2026-05-22'), findsOneWidget); + expect(find.text('250 msgs · 5 sessions · 80 tools'), findsOneWidget); + expect(find.text('Lifetime: 350 msgs over 2 days'), findsOneWidget); + expect(find.text('No team active.'), findsOneWidget); + }); + + testWidgets('adds and removes team members from the roster', (tester) async { + await tester.pumpWidget(harness(f, sidebar())); + await tester.pumpAndSettle(); + + f.services.events.emit(const TeamMemberJoined( + team: 't', + agentId: 'a1', + name: 'Scout', + agentType: 'explorer', + paneId: '%1', + model: 'claude-opus-4-7', + color: 'blue', + )); + await tester.pump(); + await tester.pump(); + expect(find.text('Scout'), findsOneWidget); + expect(find.text('explorer · opus 4.7'), findsOneWidget); + + f.services.events.emit(const TeamMemberLeft(team: 't', agentId: 'a1', paneId: '%1')); + await tester.pump(); + await tester.pump(); + expect(find.text('Scout'), findsNothing); + expect(find.text('No team active.'), findsOneWidget); + }); + + testWidgets('degrades to a no-activity message with empty stats', (tester) async { + await tester.pumpWidget(harness(f, sidebar())); + await tester.pumpAndSettle(); + expect(find.text('No activity recorded yet.'), findsOneWidget); + }); +} diff --git a/test/builtin/claude/claude_stats_test.dart b/test/builtin/claude/claude_stats_test.dart new file mode 100644 index 00000000..a8c779b7 --- /dev/null +++ b/test/builtin/claude/claude_stats_test.dart @@ -0,0 +1,54 @@ +import 'dart:convert'; + +import 'package:clide/builtin/claude/src/claude_stats.dart'; +import 'package:test/test.dart'; + +void main() { + group('parseClaudeStats', () { + test('parses daily activity, latest day, and lifetime totals', () { + final json = jsonEncode({ + 'version': 3, + 'lastComputedDate': '2026-05-22', + 'dailyActivity': [ + {'date': '2026-05-01', 'messageCount': 100, 'sessionCount': 2, 'toolCallCount': 30}, + {'date': '2026-05-22', 'messageCount': 250, 'sessionCount': 5, 'toolCallCount': 80}, + ], + }); + final s = parseClaudeStats(json); + expect(s.lastComputed, '2026-05-22'); + expect(s.activeDays, 2); + expect(s.latest!.date, '2026-05-22'); // most recent, not last in array + expect(s.latest!.messageCount, 250); + expect(s.lifetimeMessages, 350); + expect(s.lifetimeSessions, 7); + expect(s.lifetimeToolCalls, 110); + }); + + test('picks the latest day regardless of array order', () { + final json = jsonEncode({ + 'dailyActivity': [ + {'date': '2026-05-22', 'messageCount': 1, 'sessionCount': 1, 'toolCallCount': 1}, + {'date': '2026-05-02', 'messageCount': 9, 'sessionCount': 9, 'toolCallCount': 9}, + ], + }); + expect(parseClaudeStats(json).latest!.date, '2026-05-22'); + }); + + test('missing counts default to zero', () { + final json = jsonEncode({ + 'dailyActivity': [ + {'date': '2026-05-22'}, + ], + }); + final s = parseClaudeStats(json); + expect(s.latest!.messageCount, 0); + expect(s.lifetimeToolCalls, 0); + }); + + test('malformed or empty input yields empty stats', () { + expect(parseClaudeStats('{ not json').daily, isEmpty); + expect(parseClaudeStats('[]').daily, isEmpty); + expect(parseClaudeStats('{}').latest, isNull); + }); + }); +}