@koinzhang/paseo-plugin-activity 0.5.0 → 0.7.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 (74) hide show
  1. package/CHANGELOG.md +78 -1
  2. package/README.md +15 -8
  3. package/client/activity-heatmap.tsx +126 -93
  4. package/client/agent-creations.tsx +216 -0
  5. package/client/attention-pill.tsx +16 -5
  6. package/client/attention-popover.tsx +19 -23
  7. package/client/color-mix.test.ts +27 -0
  8. package/client/color-mix.ts +38 -0
  9. package/client/design-tokens.test.ts +39 -0
  10. package/client/design-tokens.ts +168 -0
  11. package/client/fit-text.test.ts +41 -0
  12. package/client/fit-text.ts +33 -0
  13. package/client/formatted-time.tsx +4 -4
  14. package/client/global-surface.tsx +316 -275
  15. package/client/header-button.ts +136 -0
  16. package/client/hourly-activity-timeline.tsx +425 -0
  17. package/client/measured-width.ts +72 -0
  18. package/client/panel-visibility.test.ts +25 -0
  19. package/client/panel-visibility.ts +45 -0
  20. package/client/panel.tsx +83 -108
  21. package/client/provider-dropdown.tsx +131 -0
  22. package/client/provider-filter.test.ts +17 -13
  23. package/client/provider-filter.ts +5 -7
  24. package/client/range.test.ts +44 -0
  25. package/client/range.ts +14 -0
  26. package/client/rank-color.test.ts +108 -14
  27. package/client/rank-color.ts +261 -48
  28. package/client/ranking-bars.tsx +291 -0
  29. package/client/ui.tsx +339 -0
  30. package/client/usage-popover.tsx +62 -134
  31. package/client/usage-stats.tsx +137 -8
  32. package/client/use-agent-turn-end.ts +2 -1
  33. package/client/use-app-language.ts +17 -0
  34. package/client/web.ts +73 -18
  35. package/client/workspace/agent-row.tsx +18 -25
  36. package/client/workspace/agents-section.tsx +23 -20
  37. package/client/workspace/constants.ts +6 -6
  38. package/client/workspace/display-menu.tsx +5 -4
  39. package/client/workspace/filters.test.ts +1 -1
  40. package/client/workspace/filters.ts +4 -2
  41. package/client/workspace/panel.tsx +176 -104
  42. package/client/workspace/rank-section.tsx +157 -44
  43. package/client/workspace/terminals-section.tsx +13 -9
  44. package/index.client.tsx +40 -20
  45. package/index.server.ts +63 -31
  46. package/package.json +2 -2
  47. package/paseo-plugin.json +2 -1
  48. package/server/agents.ts +20 -2
  49. package/server/background-sync.test.ts +43 -0
  50. package/server/background-sync.ts +43 -4
  51. package/server/handlers-query.test.ts +252 -1
  52. package/server/handlers.ts +174 -13
  53. package/server/ingest.test.ts +8 -0
  54. package/server/messages.test.ts +96 -1
  55. package/server/prompt-dedupe.ts +52 -0
  56. package/server/rpc-cache.test.ts +74 -0
  57. package/server/rpc-cache.ts +48 -0
  58. package/server/store.test.ts +122 -0
  59. package/server/store.ts +313 -19
  60. package/server/ttl-cache.ts +3 -0
  61. package/shared/activity.test.ts +159 -6
  62. package/shared/activity.ts +140 -5
  63. package/shared/classify.test.ts +1 -0
  64. package/shared/classify.ts +4 -1
  65. package/shared/explorer-agent-display.test.ts +61 -0
  66. package/shared/explorer-agent-display.ts +21 -2
  67. package/shared/format.test.ts +28 -3
  68. package/shared/format.ts +25 -2
  69. package/shared/i18n.test.ts +34 -0
  70. package/shared/i18n.ts +363 -0
  71. package/shared/insights.test.ts +162 -80
  72. package/shared/insights.ts +136 -61
  73. package/shared/usage.test.ts +330 -0
  74. package/shared/usage.ts +471 -0
@@ -1,8 +1,11 @@
1
1
  import type { ActivityDay, ProviderUsageItem } from "./usage.ts";
2
- import { isActiveDay } from "./activity.ts";
3
- import { formatDisplayName } from "./format.ts";
2
+ import { computeStreaks, isActiveDay } from "./activity.ts";
3
+ import { formatCount, formatDisplayName, formatDuration } from "./format.ts";
4
+ import { messagesFor } from "./i18n.ts";
4
5
 
5
6
  export type InsightRow = { label: string; value: string };
7
+ export type KpiComparison = { text: string; direction: "up" | "down" | "flat" | "unknown" };
8
+ export type KpiRow = InsightRow & { comparison?: KpiComparison };
6
9
 
7
10
  export type InsightSummary = {
8
11
  skills: number;
@@ -13,19 +16,11 @@ export type InsightSummary = {
13
16
  codingAgents?: number;
14
17
  /** Active non-coding agents (018); empty creations excluded. */
15
18
  chatAgents?: number;
16
- longestStreak?: number;
17
19
  };
18
20
 
19
21
  /** Shared cap for Activity insights and Most used skills / MCP / models. */
20
22
  export const ACTIVITY_LIST_LIMIT = 8;
21
23
 
22
- function formatRatio(numerator: number, denominator: number): string {
23
- if (denominator <= 0) return "—";
24
- const value = numerator / denominator;
25
- if (Number.isInteger(value)) return String(value);
26
- return value.toFixed(1).replace(/\.0$/, "");
27
- }
28
-
29
24
  function formatDayLabel(dateKey: string, locale: string): string {
30
25
  const [y, m, d] = dateKey.split("-").map(Number);
31
26
  if (!y || !m || !d) return dateKey;
@@ -67,36 +62,49 @@ function pickBusiestDay(days: readonly ActivityDay[]): ActivityDay | null {
67
62
 
68
63
  function formatBusiest(day: ActivityDay, locale: string): string {
69
64
  const label = formatDayLabel(day.date, locale);
70
- if (day.messages > 0) return `${label} · ${day.messages} messages`;
65
+ const { units } = messagesFor(locale);
66
+ if (day.messages > 0) return `${label} · ${units.prompts(day.messages)}`;
71
67
  const calls = day.skills + day.mcp;
72
- if (calls > 0) return `${label} · ${calls} calls`;
73
- if (day.agents > 0) return `${label} · ${day.agents} agents`;
68
+ if (calls > 0) return `${label} · ${units.calls(calls)}`;
69
+ if (day.agents > 0) return `${label} · ${units.sessions(day.agents)}`;
74
70
  return label;
75
71
  }
76
72
 
77
- /** All view only: messages-weighted top provider. Filtered or empty → `—`. */
78
- function topProviderValue(
73
+ /** `label · pct%`; `—` when there is no label or no denominator (069). */
74
+ function withShare(label: string | undefined, count: number, total: number): string {
75
+ if (!label || total <= 0) return "—";
76
+ return `${label} · ${Math.round((count / total) * 100)}%`;
77
+ }
78
+
79
+ /**
80
+ * Messages-weighted top provider (050) with its share of all providers' messages
81
+ * (069). A selected provider is shown with its own share.
82
+ */
83
+ function topProviderStats(
79
84
  providers: readonly ProviderUsageItem[],
85
+ allProviders: readonly ProviderUsageItem[],
80
86
  providerFilter: string,
81
- ): string {
82
- if (providerFilter !== "all") return "—";
87
+ ): { value: string; label: string | undefined } {
88
+ const total = allProviders.reduce((sum, p) => sum + p.messageCount, 0);
89
+ if (providerFilter !== "all") {
90
+ const selected = providers.find((p) => p.provider === providerFilter);
91
+ return { value: withShare(selected?.label, selected?.messageCount ?? 0, total), label: selected && selected.messageCount > 0 ? selected.label : undefined };
92
+ }
83
93
  const ranked = [...providers]
84
94
  .filter((p) => p.messageCount > 0)
85
95
  .sort(
86
96
  (a, b) =>
87
97
  b.messageCount - a.messageCount || a.provider.localeCompare(b.provider),
88
- );
98
+ );
89
99
  const top = ranked[0];
90
- if (!top) return "—";
91
- const total = ranked.reduce((sum, p) => sum + p.messageCount, 0);
92
- const pct = total > 0 ? Math.round((top.messageCount / total) * 100) : 0;
93
- return `${top.label} · ${pct}%`;
100
+ return { value: withShare(top?.label, top?.messageCount ?? 0, total), label: top?.label };
94
101
  }
95
102
 
96
- function topModelValue(
103
+ /** Messages-weighted top model (050) with its share of in-filter model messages (069). */
104
+ function topModelStats(
97
105
  providers: readonly ProviderUsageItem[],
98
106
  providerFilter: string,
99
- ): string {
107
+ ): { value: string; label: string | undefined } {
100
108
  const map = new Map<string, number>();
101
109
  const source =
102
110
  providerFilter === "all"
@@ -111,21 +119,34 @@ function topModelValue(
111
119
  (a, b) => b[1] - a[1] || a[0].localeCompare(b[0]),
112
120
  );
113
121
  const top = ranked[0];
114
- if (!top || top[1] <= 0) return "—";
122
+ if (!top || top[1] <= 0) return { value: "—", label: undefined };
115
123
  const total = ranked.reduce((sum, [, count]) => sum + count, 0);
116
- const pct = total > 0 ? Math.round((top[1] / total) * 100) : 0;
117
- return `${formatDisplayName(top[0])} · ${pct}%`;
124
+ const label = formatDisplayName(top[0]);
125
+ return { value: withShare(label, top[1], total), label };
126
+ }
127
+
128
+ function comparison(current: number, previous: number, locale: string): KpiComparison {
129
+ const suffix = messagesFor(locale).kpi.previous7Days;
130
+ if (previous === 0 && current > 0) return { text: `— ${suffix}`, direction: "unknown" };
131
+ const change = previous === 0 ? 0 : Math.round(((current - previous) / previous) * 100);
132
+ const direction = change > 0 ? "up" : change < 0 ? "down" : "flat";
133
+ const arrow = direction === "up" ? "↑" : direction === "down" ? "↓" : "→";
134
+ return { text: `${arrow}${Math.abs(change).toLocaleString(locale)}% ${suffix}`, direction };
135
+ }
136
+
137
+ function previousLeader(label: string | undefined, locale: string): KpiComparison {
138
+ return { text: `${label ?? "—"} ${messagesFor(locale).kpi.previous7DaysBare}`, direction: "unknown" };
118
139
  }
119
140
 
120
141
  /** Share of active agents that are coding (018); empty creations excluded. */
121
- function codingVsChatValue(codingAgents: number, chatAgents: number): string {
142
+ function codingVsChatValue(codingAgents: number, chatAgents: number, locale: string): string {
122
143
  const total = codingAgents + chatAgents;
123
144
  if (total <= 0) return "—";
124
145
  const pct = Math.round((codingAgents / total) * 100);
125
- return `${pct}% coding`;
146
+ return messagesFor(locale).insights.codingShare(pct);
126
147
  }
127
148
 
128
- /** Weekday with the highest activity volume among active days. */
149
+ /** Weekday with the highest activity volume among active days (full name, 072). */
129
150
  function peakWeekdayValue(days: readonly ActivityDay[], locale: string): string {
130
151
  const volumes = [0, 0, 0, 0, 0, 0, 0];
131
152
  for (const day of days) {
@@ -143,65 +164,119 @@ function peakWeekdayValue(days: readonly ActivityDay[], locale: string): string
143
164
  }
144
165
  }
145
166
  if (bestDow < 0 || bestVol <= 0) return "—";
146
- // 2026-03-08 was a Sunday — use a known Sunday + offset for locale short name.
167
+ // 2026-03-08 was a Sunday — use a known Sunday + offset for the locale name.
147
168
  const probe = new Date(2026, 2, 8 + bestDow);
148
- return probe.toLocaleDateString(locale, { weekday: "short" });
169
+ return probe.toLocaleDateString(locale, { weekday: "long" });
170
+ }
171
+
172
+ /** Share of prompted sessions with ≥2 prompts (072); empty creations excluded. */
173
+ function multiTurnValue(
174
+ multiTurn: { multiTurnSessions: number; promptedSessions: number } | null,
175
+ ): string {
176
+ if (!multiTurn || multiTurn.promptedSessions <= 0) return "—";
177
+ return `${Math.round((multiTurn.multiTurnSessions / multiTurn.promptedSessions) * 100)}%`;
149
178
  }
150
179
 
151
180
  /**
152
- * Fixed 8-row habit insights. Avoids KPI totals and Most used entity lists.
181
+ * Fixed 8-row insights (072 / 080): habit (active days, busiest day, streak,
182
+ * peak weekday, workspaces, coding share) → session shape (multi-turn share,
183
+ * engaged time).
153
184
  */
154
185
  export function buildActivityInsights(input: {
155
186
  days: readonly ActivityDay[];
156
187
  summary: InsightSummary;
157
- providers: readonly ProviderUsageItem[];
158
- providerFilter: string;
188
+ /** Distinct workspaces among sessions (011). */
189
+ workspaces: number;
190
+ /** Mean engaged time per session from `usage.agent-lifetime` (072). */
191
+ averageSessionMs?: number | null;
192
+ /** Sessions with ≥2 / ≥1 prompts from `usage.agent-lifetime` (072). */
193
+ multiTurn?: { multiTurnSessions: number; promptedSessions: number } | null;
159
194
  locale?: string;
160
- /** Max rows (default {@link ACTIVITY_LIST_LIMIT}). */
161
- limit?: number;
195
+ today?: Date;
162
196
  }): InsightRow[] {
163
197
  const locale = input.locale ?? "en";
164
- const limit = input.limit ?? ACTIVITY_LIST_LIMIT;
165
- const activeDays = input.days.filter(isActiveDay).length;
166
198
  const busiest = pickBusiestDay(input.days);
167
- const longest = input.summary.longestStreak;
199
+ const activeDays = input.days.filter(isActiveDay).length;
200
+ const { longest } = computeStreaks(input.days, input.today);
168
201
  const codingAgents = input.summary.codingAgents ?? 0;
169
202
  const chatAgents = input.summary.chatAgents ?? 0;
203
+ const { insights: m, units } = messagesFor(locale);
204
+ const averageSessionMs = input.averageSessionMs;
170
205
 
171
- const rows: InsightRow[] = [
172
- { label: "Active days", value: String(activeDays) },
206
+ return [
207
+ { label: m.activeDays, value: activeDays.toLocaleString(locale) },
173
208
  {
174
- label: "Longest streak",
175
- value:
176
- longest != null
177
- ? `${longest} day${longest === 1 ? "" : "s"}`
178
- : "—",
209
+ label: m.busiestDay,
210
+ value: busiest ? formatBusiest(busiest, locale) : "—",
179
211
  },
212
+ { label: m.longestStreak, value: longest > 0 ? units.days(longest) : "—" },
213
+ { label: m.peakWeekday, value: peakWeekdayValue(input.days, locale) },
214
+ { label: m.workspaces, value: formatCount(input.workspaces) },
180
215
  {
181
- label: "Busiest day",
182
- value: busiest ? formatBusiest(busiest, locale) : "—",
216
+ label: m.codingVsChat,
217
+ value: codingVsChatValue(codingAgents, chatAgents, locale),
183
218
  },
219
+ { label: m.multiTurnSessions, value: multiTurnValue(input.multiTurn ?? null) },
184
220
  {
185
- label: "Peak weekday",
186
- value: peakWeekdayValue(input.days, locale),
221
+ label: m.avgSessionDuration,
222
+ value: averageSessionMs == null ? "—" : formatDuration(averageSessionMs, locale),
187
223
  },
224
+ ];
225
+ }
226
+
227
+ /**
228
+ * Fixed 4-tile KPI row (069 / 070 / 072): sessions, prompts, top provider ·
229
+ * share, top model · share. Active days lives in Insights.
230
+ */
231
+ export function buildActivityKpi(input: {
232
+ sessions: number;
233
+ messages: number;
234
+ locale?: string;
235
+ /** Provider rows after the provider filter. */
236
+ providers: readonly ProviderUsageItem[];
237
+ /** Every provider; denominator of the top-provider share. */
238
+ allProviders: readonly ProviderUsageItem[];
239
+ providerFilter: string;
240
+ /** Two adjacent seven-day windows, when the comparison query has loaded. */
241
+ comparison?: {
242
+ current: readonly ProviderUsageItem[];
243
+ previous: readonly ProviderUsageItem[];
244
+ };
245
+ }): KpiRow[] {
246
+ const locale = input.locale ?? "en";
247
+ const m = messagesFor(locale).kpi;
248
+ const topProvider = topProviderStats(input.providers, input.allProviders, input.providerFilter);
249
+ const topModel = topModelStats(input.providers, input.providerFilter);
250
+ const current = input.comparison?.current ?? [];
251
+ const previous = input.comparison?.previous ?? [];
252
+ const previousProvider = topProviderStats(previous, previous, input.providerFilter);
253
+ const previousModel = topModelStats(previous, input.providerFilter);
254
+ const count = (items: readonly ProviderUsageItem[], field: "agentCount" | "messageCount") =>
255
+ items.reduce(
256
+ (sum, item) => sum + (input.providerFilter === "all" || item.provider === input.providerFilter ? item[field] : 0),
257
+ 0,
258
+ );
259
+ const trend = input.comparison;
260
+ return [
188
261
  {
189
- label: "Top provider",
190
- value: topProviderValue(input.providers, input.providerFilter),
262
+ label: m.sessions,
263
+ value: input.sessions.toLocaleString(locale),
264
+ comparison: trend ? comparison(count(current, "agentCount"), count(previous, "agentCount"), locale) : undefined,
191
265
  },
192
266
  {
193
- label: "Top model",
194
- value: topModelValue(input.providers, input.providerFilter),
267
+ label: m.prompts,
268
+ value: input.messages.toLocaleString(locale),
269
+ comparison: trend ? comparison(count(current, "messageCount"), count(previous, "messageCount"), locale) : undefined,
195
270
  },
196
271
  {
197
- label: "Messages per agent",
198
- value: formatRatio(input.summary.messages, input.summary.agents),
272
+ label: m.topProvider,
273
+ value: topProvider.value,
274
+ comparison: trend ? previousLeader(previousProvider.label, locale) : undefined,
199
275
  },
200
276
  {
201
- label: "Coding vs chat",
202
- value: codingVsChatValue(codingAgents, chatAgents),
277
+ label: m.topModel,
278
+ value: topModel.value,
279
+ comparison: trend ? previousLeader(previousModel.label, locale) : undefined,
203
280
  },
204
281
  ];
205
-
206
- return rows.slice(0, limit);
207
282
  }
@@ -1,9 +1,14 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { describe, it } from "node:test";
3
3
  import {
4
+ aggregateActivityByHour,
4
5
  aggregateActivityByDay,
6
+ aggregateAgentCreations,
5
7
  aggregateAgents,
8
+ aggregateByProject,
6
9
  aggregateByProvider,
10
+ OTHER_PROJECT_KEY,
11
+ resolveAgentProjects,
7
12
  aggregateMcpByTool,
8
13
  aggregateShellTop,
9
14
  aggregateSkillsByName,
@@ -12,6 +17,9 @@ import {
12
17
  isFileRead,
13
18
  isFileWrite,
14
19
  isShellCall,
20
+ pickLongestAgentLifetime,
21
+ averageEngagedSessionMs,
22
+ countMultiTurnSessions,
15
23
  shellCommandHead,
16
24
  shellLooksMutating,
17
25
  } from "./usage.ts";
@@ -813,6 +821,86 @@ describe("aggregateActivityByDay", () => {
813
821
  });
814
822
  });
815
823
 
824
+ describe("aggregateActivityByHour (059)", () => {
825
+ it("zero-fills consecutive absolute hours and aggregates all activity kinds", () => {
826
+ const hours = aggregateActivityByHour(
827
+ [
828
+ row({
829
+ callId: "s1",
830
+ provider: "codex",
831
+ category: "skill",
832
+ confidence: "exact",
833
+ ts: "2026-09-21T09:15:00.000Z",
834
+ }),
835
+ row({
836
+ callId: "s-low",
837
+ provider: "codex",
838
+ category: "skill",
839
+ confidence: "low",
840
+ ts: "2026-09-21T09:20:00.000Z",
841
+ }),
842
+ row({
843
+ callId: "m1",
844
+ provider: "codex",
845
+ category: "mcp",
846
+ ts: "2026-09-21T11:59:59.000Z",
847
+ }),
848
+ ],
849
+ {
850
+ start: new Date("2026-09-21T09:00:00.000Z"),
851
+ hours: 4,
852
+ provider: "codex",
853
+ agents: [{ provider: "codex", createdAt: "2026-09-21T10:01:00.000Z" }],
854
+ messages: [{
855
+ provider: "codex",
856
+ ts: null,
857
+ ingestedAt: "2026-09-21T10:30:00.000Z",
858
+ }],
859
+ },
860
+ );
861
+
862
+ assert.equal(hours.length, 4);
863
+ assert.deepEqual(hours.map((hour) => hour.start), [
864
+ "2026-09-21T09:00:00.000Z",
865
+ "2026-09-21T10:00:00.000Z",
866
+ "2026-09-21T11:00:00.000Z",
867
+ "2026-09-21T12:00:00.000Z",
868
+ ]);
869
+ assert.deepEqual(hours.map((hour) => hour.total), [1, 2, 1, 0]);
870
+ assert.equal(hours[0]?.skills, 1);
871
+ assert.equal(hours[1]?.agents, 1);
872
+ assert.equal(hours[1]?.messages, 1);
873
+ assert.equal(hours[2]?.mcp, 1);
874
+ assert.equal(new Set(hours.map((hour) => hour.key)).size, 4);
875
+ });
876
+
877
+ it("filters every activity kind by normalized provider and ignores out-of-window rows", () => {
878
+ const hours = aggregateActivityByHour(
879
+ [
880
+ row({ callId: "1", provider: "codex/gpt-5.4", category: "mcp", ts: "2026-09-21T09:00:00.000Z" }),
881
+ row({ callId: "2", provider: "claude", category: "mcp", ts: "2026-09-21T09:00:00.000Z" }),
882
+ row({ callId: "3", provider: "codex", category: "mcp", ts: "2026-09-21T08:59:59.000Z" }),
883
+ ],
884
+ {
885
+ start: new Date("2026-09-21T09:00:00.000Z"),
886
+ hours: 1,
887
+ provider: "codex",
888
+ agents: [{ provider: "claude", createdAt: "2026-09-21T09:10:00.000Z" }],
889
+ messages: [{ provider: "codex", ts: "invalid", ingestedAt: "2026-09-21T09:20:00.000Z" }],
890
+ },
891
+ );
892
+ assert.deepEqual(hours[0], {
893
+ key: String(Date.parse("2026-09-21T09:00:00.000Z")),
894
+ start: "2026-09-21T09:00:00.000Z",
895
+ skills: 0,
896
+ mcp: 1,
897
+ agents: 0,
898
+ messages: 0,
899
+ total: 1,
900
+ });
901
+ });
902
+ });
903
+
816
904
  describe("aggregateAgents (024)", () => {
817
905
  it("groups by agent, excludes low from skillCalls, and merges the registry", () => {
818
906
  const items = aggregateAgents(
@@ -920,3 +1008,245 @@ describe("aggregateAgents (024)", () => {
920
1008
  assert.equal(a3.lastActivityAt, null);
921
1009
  });
922
1010
  });
1011
+
1012
+ describe("countMultiTurnSessions (072)", () => {
1013
+ it("counts prompted and ≥2-prompt sessions among known agents", () => {
1014
+ const agents = [{ agentId: "a" }, { agentId: "b" }, { agentId: "empty" }];
1015
+ const messages = [{ agentId: "a" }, { agentId: "a" }, { agentId: "b" }, { agentId: "gone" }, { agentId: "gone" }];
1016
+ assert.deepEqual(countMultiTurnSessions(agents, messages), { promptedSessions: 2, multiTurnSessions: 1 });
1017
+ });
1018
+ });
1019
+
1020
+ describe("averageEngagedSessionMs (072)", () => {
1021
+ const min = 60_000;
1022
+ const at = (offsetMin: number) => new Date(Date.parse("2026-09-19T00:00:00.000Z") + offsetMin * min).toISOString();
1023
+ it("sums gaps between events, skips idle gaps, excludes sessions without events", () => {
1024
+ const agents = [
1025
+ { agentId: "a", createdAt: at(0) },
1026
+ { agentId: "b", createdAt: at(0) },
1027
+ { agentId: "idle", createdAt: at(0) },
1028
+ ];
1029
+ const events = [
1030
+ { agentId: "a", ts: at(5), ingestedAt: at(99) },
1031
+ { agentId: "a", ts: null, ingestedAt: at(20) },
1032
+ // 3-day gap: resumed later, counts only the 4 min after resuming.
1033
+ { agentId: "a", ts: at(3 * 1440), ingestedAt: at(3 * 1440) },
1034
+ { agentId: "a", ts: at(3 * 1440 + 4), ingestedAt: at(3 * 1440 + 4) },
1035
+ { agentId: "b", ts: at(10), ingestedAt: at(10) },
1036
+ { agentId: "unknown", ts: at(1), ingestedAt: at(1) },
1037
+ ];
1038
+ // a: 5 + 15 + 4 = 24 min; b: 10 min → mean 17 min.
1039
+ assert.equal(averageEngagedSessionMs(agents, events), 17 * min);
1040
+ assert.equal(averageEngagedSessionMs(agents, []), null);
1041
+ });
1042
+ });
1043
+
1044
+ describe("pickLongestAgentLifetime (049 / 051)", () => {
1045
+ const agent = (
1046
+ agentId: string,
1047
+ createdAt: string,
1048
+ archivedAt: string | null,
1049
+ provider = "claude",
1050
+ ) => ({ agentId, provider, workspaceId: "w1", title: agentId, createdAt, archivedAt });
1051
+ const NOW = Date.parse("2026-09-20T00:00:00.000Z");
1052
+
1053
+ it("returns the widest created→archived span", () => {
1054
+ const result = pickLongestAgentLifetime(
1055
+ [
1056
+ agent("short", "2026-09-19T00:00:00.000Z", "2026-09-19T01:00:00.000Z"),
1057
+ agent("long", "2026-09-07T03:34:09.656Z", "2026-09-18T17:18:18.001Z"),
1058
+ agent("active", "2026-09-19T00:00:00.000Z", null),
1059
+ ],
1060
+ { now: NOW },
1061
+ );
1062
+ assert.equal(result.longest?.agentId, "long");
1063
+ assert.equal(
1064
+ result.longest?.durationMs,
1065
+ Date.parse("2026-09-18T17:18:18.001Z") - Date.parse("2026-09-07T03:34:09.656Z"),
1066
+ );
1067
+ assert.equal(result.longest?.title, "long");
1068
+ assert.equal(result.longest?.archivedAt, "2026-09-18T17:18:18.001Z");
1069
+ assert.equal(result.sampleSize, 3);
1070
+ });
1071
+
1072
+ it("counts active agents up to now and reports them as active", () => {
1073
+ const result = pickLongestAgentLifetime(
1074
+ [
1075
+ agent("archived", "2026-09-15T00:00:00.000Z", "2026-09-16T00:00:00.000Z"),
1076
+ agent("still-running", "2026-09-01T00:00:00.000Z", null),
1077
+ ],
1078
+ { now: NOW },
1079
+ );
1080
+ assert.equal(result.longest?.agentId, "still-running");
1081
+ assert.equal(result.longest?.archivedAt, null);
1082
+ assert.equal(result.longest?.durationMs, NOW - Date.parse("2026-09-01T00:00:00.000Z"));
1083
+ });
1084
+
1085
+ it("skips rows without a usable span and keeps ties on the earlier creation", () => {
1086
+ const result = pickLongestAgentLifetime(
1087
+ [
1088
+ agent("no-created", "not-a-date", "2026-09-19T01:00:00.000Z"),
1089
+ agent("reversed", "2026-09-19T02:00:00.000Z", "2026-09-19T01:00:00.000Z"),
1090
+ agent("later", "2026-09-10T00:00:00.000Z", "2026-09-11T00:00:00.000Z"),
1091
+ agent("earlier", "2026-09-01T00:00:00.000Z", "2026-09-02T00:00:00.000Z"),
1092
+ ],
1093
+ { now: NOW },
1094
+ );
1095
+ assert.equal(result.longest?.agentId, "earlier");
1096
+ assert.equal(result.sampleSize, 2);
1097
+ });
1098
+
1099
+ it("filters by normalized provider", () => {
1100
+ const result = pickLongestAgentLifetime(
1101
+ [
1102
+ agent("claude-agent", "2026-09-01T00:00:00.000Z", "2026-09-02T00:00:00.000Z", "claude-code"),
1103
+ agent("codex-agent", "2026-09-01T00:00:00.000Z", "2026-09-18T00:00:00.000Z", "codex"),
1104
+ ],
1105
+ { provider: "claude", now: NOW },
1106
+ );
1107
+ assert.equal(result.longest?.agentId, "claude-agent");
1108
+ assert.equal(result.sampleSize, 1);
1109
+ assert.equal(pickLongestAgentLifetime([], { provider: "codex" }).longest, null);
1110
+ });
1111
+ });
1112
+
1113
+ describe("aggregateAgentCreations (051)", () => {
1114
+ const agent = (provider: string, createdAt: string) => ({ provider, createdAt });
1115
+
1116
+ it("buckets by local day and normalized provider, highest count first", () => {
1117
+ const days = aggregateAgentCreations([
1118
+ agent("claude-code", "2026-09-19T01:00:00.000Z"),
1119
+ agent("claude", "2026-09-19T02:00:00.000Z"),
1120
+ agent("codex", "2026-09-19T03:00:00.000Z"),
1121
+ agent("codex", "2026-09-20T03:00:00.000Z"),
1122
+ ]);
1123
+ const first = days[0]!;
1124
+ assert.equal(first.date, "2026-09-19");
1125
+ assert.equal(first.total, 3);
1126
+ assert.deepEqual(first.providers, [
1127
+ { provider: "claude", label: "Claude", count: 2 },
1128
+ { provider: "codex", label: "Codex", count: 1 },
1129
+ ]);
1130
+ assert.deepEqual(days[1]?.providers, [{ provider: "codex", label: "Codex", count: 1 }]);
1131
+ });
1132
+
1133
+ it("keeps Oh My Pi (omp) distinct from Pi in creation buckets", () => {
1134
+ const days = aggregateAgentCreations([
1135
+ agent("pi", "2026-09-19T01:00:00.000Z"),
1136
+ agent("omp", "2026-09-19T02:00:00.000Z"),
1137
+ agent("omp", "2026-09-19T03:00:00.000Z"),
1138
+ ]);
1139
+ assert.deepEqual(days[0]?.providers, [
1140
+ { provider: "omp", label: "Oh My Pi", count: 2 },
1141
+ { provider: "pi", label: "Pi", count: 1 },
1142
+ ]);
1143
+ assert.deepEqual(aggregateAgentCreations([agent("omp", "2026-09-19T02:00:00.000Z"), agent("pi", "2026-09-19T01:00:00.000Z")], { provider: "omp" })[0]?.total, 1);
1144
+ });
1145
+
1146
+ it("keeps Oh My Pi (omp) and Pi as separate providers (071)", () => {
1147
+ const result = aggregateByProvider(
1148
+ [],
1149
+ [
1150
+ { agentId: "a", provider: "pi" },
1151
+ { agentId: "b", provider: "omp" },
1152
+ { agentId: "c", provider: "omp" },
1153
+ ],
1154
+ [{ agentId: "b", provider: "omp" }],
1155
+ );
1156
+ assert.deepEqual(
1157
+ result.providers.map((item) => [item.provider, item.label, item.agentCount, item.messageCount]),
1158
+ [
1159
+ ["omp", "Oh My Pi", 2, 1],
1160
+ ["pi", "Pi", 1, 0],
1161
+ ],
1162
+ );
1163
+ });
1164
+
1165
+ it("honours provider, from and to filters and skips invalid timestamps", () => {
1166
+ const rows = [
1167
+ agent("codex", "2026-09-19T03:00:00.000Z"),
1168
+ agent("claude", "2026-09-19T04:00:00.000Z"),
1169
+ agent("codex", "2026-08-01T03:00:00.000Z"),
1170
+ agent("codex", "not-a-date"),
1171
+ ];
1172
+ assert.deepEqual(
1173
+ aggregateAgentCreations(rows, { provider: "CODEX" }).map((day) => [day.date, day.total]),
1174
+ [
1175
+ ["2026-08-01", 1],
1176
+ ["2026-09-19", 1],
1177
+ ],
1178
+ );
1179
+ assert.deepEqual(
1180
+ aggregateAgentCreations(rows, { from: "2026-09-01T00:00:00.000Z" }).map((day) => day.date),
1181
+ ["2026-09-19"],
1182
+ );
1183
+ assert.deepEqual(
1184
+ aggregateAgentCreations(rows, { to: "2026-09-01T00:00:00.000Z" }).map((day) => day.date),
1185
+ ["2026-08-01"],
1186
+ );
1187
+ });
1188
+ });
1189
+
1190
+ describe("projects (070)", () => {
1191
+ const projects = [
1192
+ { root: "/w/app", name: "App" },
1193
+ { root: "/w/app/packages/lib", name: "Lib" },
1194
+ { root: "/w/tools/", name: "Tools" },
1195
+ ];
1196
+
1197
+ it("resolves recorded roots, longest containing root, worktree siblings, cwd, then Other", () => {
1198
+ const map = resolveAgentProjects(
1199
+ [
1200
+ { agentId: "recorded", cwd: "/h/.paseo/worktrees/abc/feat", projectRoot: "/w/app" },
1201
+ { agentId: "sibling", cwd: "/h/.paseo/worktrees/abc/fix" },
1202
+ { agentId: "orphan-worktree", cwd: "/h/.paseo/worktrees/zzz/fix" },
1203
+ { agentId: "nested", cwd: "/w/app/packages/lib/src" },
1204
+ { agentId: "slash", cwd: "/w/tools" },
1205
+ { agentId: "loose", cwd: "/tmp/scratch/" },
1206
+ { agentId: "none" },
1207
+ ],
1208
+ projects,
1209
+ );
1210
+ assert.deepEqual(Object.fromEntries(map), {
1211
+ recorded: "/w/app",
1212
+ sibling: "/w/app",
1213
+ "orphan-worktree": OTHER_PROJECT_KEY,
1214
+ nested: "/w/app/packages/lib",
1215
+ slash: "/w/tools",
1216
+ loose: "/tmp/scratch",
1217
+ none: OTHER_PROJECT_KEY,
1218
+ });
1219
+ });
1220
+
1221
+ it("counts sessions, prompts, skills (low excluded) and MCP per project with a provider filter", () => {
1222
+ const agents = [
1223
+ { agentId: "a", provider: "codex", cwd: "/w/app" },
1224
+ { agentId: "b", provider: "claude", cwd: "/w/app/x" },
1225
+ { agentId: "c", provider: "codex", cwd: "/tmp/scratch" },
1226
+ ];
1227
+ const rows = [
1228
+ { agentId: "a", provider: "codex", category: "skill", confidence: "exact" },
1229
+ { agentId: "a", provider: "codex", category: "skill", confidence: "low" },
1230
+ { agentId: "b", provider: "claude", category: "mcp", confidence: null },
1231
+ { agentId: "ghost", provider: "codex", category: "mcp", confidence: null },
1232
+ ];
1233
+ const messages = [
1234
+ { agentId: "a", provider: "codex" },
1235
+ { agentId: "b", provider: "claude" },
1236
+ { agentId: "c", provider: "codex" },
1237
+ ];
1238
+ assert.deepEqual(aggregateByProject(agents, rows, messages, projects), [
1239
+ { key: "/w/app", label: "App", agentCount: 2, messageCount: 2, skillCalls: 1, mcpCalls: 1 },
1240
+ { key: "/tmp/scratch", label: "scratch", agentCount: 1, messageCount: 1, skillCalls: 0, mcpCalls: 0 },
1241
+ { key: OTHER_PROJECT_KEY, label: "", agentCount: 0, messageCount: 0, skillCalls: 0, mcpCalls: 1 },
1242
+ ]);
1243
+ assert.deepEqual(
1244
+ aggregateByProject(agents, rows, messages, projects, { provider: "claude" }).map((item) => [
1245
+ item.key,
1246
+ item.agentCount,
1247
+ item.mcpCalls,
1248
+ ]),
1249
+ [["/w/app", 1, 1]],
1250
+ );
1251
+ });
1252
+ });