@koinzhang/paseo-plugin-activity 0.4.0 → 0.6.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 (52) hide show
  1. package/CHANGELOG.md +61 -2
  2. package/README.md +3 -3
  3. package/client/activity-heatmap.tsx +17 -25
  4. package/client/agent-creations.tsx +207 -0
  5. package/client/agent-directory.test.ts +191 -0
  6. package/client/agent-directory.ts +150 -0
  7. package/client/attention-pill.tsx +17 -105
  8. package/client/color-mix.test.ts +27 -0
  9. package/client/color-mix.ts +38 -0
  10. package/client/fit-text.test.ts +41 -0
  11. package/client/fit-text.ts +33 -0
  12. package/client/global-surface.tsx +104 -31
  13. package/client/hourly-activity-timeline.tsx +392 -0
  14. package/client/measured-width.ts +72 -0
  15. package/client/pill-directory.ts +20 -68
  16. package/client/range.test.ts +44 -0
  17. package/client/range.ts +14 -0
  18. package/client/rank-color.test.ts +108 -14
  19. package/client/rank-color.ts +261 -48
  20. package/client/usage-stats.tsx +116 -5
  21. package/client/use-agent-turn-end.ts +19 -2
  22. package/client/use-workspace-agent-statuses.ts +18 -42
  23. package/client/workspace/constants.ts +2 -0
  24. package/client/workspace/host-archive-sync.test.ts +46 -0
  25. package/client/workspace/host-archive-sync.ts +15 -0
  26. package/client/workspace/list-host-agents.test.ts +11 -63
  27. package/client/workspace/list-host-agents.ts +4 -58
  28. package/client/workspace/panel.tsx +99 -12
  29. package/client/workspace/rank-section.tsx +150 -11
  30. package/index.server.ts +30 -0
  31. package/package.json +3 -3
  32. package/paseo-plugin.json +1 -1
  33. package/server/background-sync.test.ts +43 -0
  34. package/server/background-sync.ts +9 -0
  35. package/server/handlers-query.test.ts +225 -0
  36. package/server/handlers.ts +117 -0
  37. package/shared/activity.test.ts +123 -6
  38. package/shared/activity.ts +103 -5
  39. package/shared/classify.test.ts +10 -0
  40. package/shared/classify.ts +10 -0
  41. package/shared/explorer-agent-display.test.ts +61 -0
  42. package/shared/explorer-agent-display.ts +21 -2
  43. package/shared/format.test.ts +28 -3
  44. package/shared/format.ts +22 -2
  45. package/shared/insights.test.ts +113 -70
  46. package/shared/insights.ts +53 -39
  47. package/shared/usage.test.ts +209 -0
  48. package/shared/usage.ts +283 -1
  49. package/client/pill-directory.test.ts +0 -92
  50. package/client/workspace/agent-live-status-sync.tsx +0 -103
  51. package/client/workspace/status-cache.test.ts +0 -62
  52. package/client/workspace/status-cache.ts +0 -23
package/CHANGELOG.md CHANGED
@@ -5,7 +5,64 @@ All notable changes to `@koinzhang/paseo-plugin-activity` are documented in this
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
- ## [Unreleased]
8
+ ## [0.6.0] - 2026-09-22
9
+
10
+ Requires Paseo **>= 0.9.0-beta.2**.
11
+
12
+ ### Added
13
+
14
+ - Workspace Activity Skills and MCP can switch from call-count rankings to newest-first timelines; each call shows its agent title and time, timeline nodes use accent for active agents and gray for archived agents, active-agent rows open their conversations, and both sections share one host-scoped persisted view choice.
15
+ - `usage.recent-skill-calls` RPC returns recent exact / inferred skill calls for a workspace with agent titles.
16
+ - `usage.recent-mcp-calls` RPC returns recent MCP calls for a workspace with agent titles.
17
+ - Global Activity **Agent creations** histogram: a fixed 30-local-day window of daily bars stacked by provider, with per-provider colours and a hover / focus / click card listing every provider's count for that day plus the date.
18
+ - `usage.agent-creations` RPC: daily creation counts with per-provider slices, read from the agent registry alone (no tool-call or message joins).
19
+ - `usage.agent-lifetime` now includes still-active agents (`createdAt → now`, marked `· active` in the KPI) instead of archived agents only.
20
+ - Directory sync lists archived agents (`includeArchived`) so archive metadata (`archivedAt`) is backfilled for agents archived before or between observations; archived entries are registered but never timeline-scanned.
21
+
22
+ ### Changed
23
+
24
+ - Workspace Activity Skills / MCP default to the newest-call timeline; an explicitly saved ranked view is kept.
25
+ - Global KPI reordered to lead with Top / Longest: Agents, Longest agent, Top provider, Top model, Peak weekday, Longest streak; Insights fixed at 8 rows.
26
+ - Agent creations histogram ignores the range chips (always the last 30 local days) and no longer depends on `usage.activity-by-day`.
27
+ - `mcpServerColor` renamed to `entityColor`; the same accent-derived stable colour now covers MCP servers and providers.
28
+ - KPI values and labels shrink to fit their tile instead of wrapping onto a second line (Global / Workspace / Agent share `UsageStats`); line height is fixed so the label baselines stay aligned.
29
+ - Top provider / Top model KPI tiles show the name only (no share), matching the provider-filtered shape; shares stay available from `usage.by-provider`.
30
+ - Agent creations bars round only the top segment's top corners — stacked joints and bar bottoms are square.
31
+ - Agent creations day bars are a single soft provider-colour gradient (tiny middle shares omitted so they cannot notch the bar; remaining colours blend evenly) instead of hard stacked segments; single-provider days stay solid.
32
+ - Global KPI tile 3 and Insights row 3 swapped: `Peak weekday` moved to the KPI (penultimate tile, next to `Longest streak`) and `Workspaces` reads with the volume counts in Insights.
33
+ - Agent creations / MCP rank colours use a soft fixed chart palette (light + dark, inferred from `surface0` luminance) instead of accent-hue hashing; known Paseo providers map to stable slots.
34
+ - Agent creations stacked segments follow window-wide provider rank (largest series at the bottom on every bar), not each day's local count order.
35
+ - Agent creations header no longer shows `N agents · last 30 days` (title is `Agents` only).
36
+ - Chart palette: light / dark colour sets swapped (bright fills on light UI, deep fills on dark UI).
37
+ - Agent creations colours: branded providers keep brand accents; unbranded catalog providers and any future ACP id fall back to the soft chart palette (no theme `accent` for the window leader).
38
+ - Agent creations hover card lists only providers with creations that day (no `: 0` rows); empty days still show the date alone.
39
+ - Agent creations day bars use the same theme-accent intensity steps as the Activity heatmap; provider brand colours remain only on the hover card chips.
40
+ - Activity heatmap rows are weekdays again (row 1 Sunday … row 7 Saturday) and each column is one Sunday-start calendar week, matching GitHub / Codex contribution graphs. The window is still 52 columns × 7 rows ending with the current week; days after today in the last column stay blank.
41
+ - Heatmap `Daily / Weekly / Cumulative` tabs use the month-axis label size (12) instead of their own 13 / 15 scale.
42
+ - Global Activity adds a rolling 168-hour timeline below the Agents histogram: a diverging filled line chart with messages above the time axis and agents below it. The viewport shows 24 hours at a time and starts at the current hour; press and drag the chart to pan through the rest of the week (no scrollbar). Empty hours keep their slot, and hovering or focusing an hour reveals its local range with agents, messages, skill calls, and MCP calls; the window is independent of range chips.
43
+
44
+ ### Fixed
45
+
46
+ - Switching back to Activity no longer re-lays out the heatmap or the 168-hour timeline. A hidden page reports width 0 to `onLayout` (and a hidden app window runs no rendering updates at all, so `onLayout` never fires), which collapsed the grid to nothing until the next measurement. Both sections now ignore zero widths, remember the last real width across remounts, and re-measure synchronously from the DOM node on mount, resize, and `visibilitychange`.
47
+ - Global Activity section rhythm: the heatmap month row no longer reserves a fixed 24px band, the 168-hour timeline's inner gap matches the other chart sections, and the insights / rank-list titles share the same 10 / 12 title gap. Sections now read as one evenly spaced stack (container gap 24 / 32 unchanged; list row density untouched).
48
+ - Longest-agent metric was understated: agents archived before the plugin could observe them had no `archived_at`, so the tile only ever saw live-hook archives.
49
+
50
+ ## [0.5.0] - 2026-09-20
51
+
52
+ Requires Paseo **>= 0.9.0-beta.2**.
53
+
54
+ ### Changed
55
+
56
+ - Pin the plugin SDK to `0.9.0-beta.2` and use independent, API-owned directory observations, shared within each entry/surface API.
57
+ - Reconcile all pages on bootstrap/reconnect, replay concurrent updates, retain 15s polling, and release observations after the last consumer unmounts.
58
+ - Handle timeline subscription restoration/errors and use SDK cleanup with release error handling.
59
+
60
+ ### Fixed
61
+
62
+ - Restore real-time workspace and attention updates: beta.2 API listeners do not receive the app's directory observation.
63
+ - Read lifecycle and archive state from explicit directory fields. Missing host UI snapshots, directory removals, and Closed no longer synthesize an archive or permanently lock lifecycle state.
64
+ - Reflect host archive/unarchive immediately in workspace rows, preserving usage metrics even if an older RPC finishes later.
65
+ - Remove the host-cache-to-query effect loop that caused React maximum update depth errors; retain stable workspace query keys.
9
66
 
10
67
  ## [0.4.0] - 2026-09-20
11
68
 
@@ -98,7 +155,9 @@ Last release that supports Paseo **0.8.0**. Later versions require Paseo **>= 0.
98
155
  - Command Center entries: open panels and export a markdown usage report.
99
156
  - Plugin renamed from `tool-usage` to `activity`, migrating the old data directory automatically.
100
157
 
101
- [Unreleased]: https://github.com/koinzhang/paseo-plugins/compare/activity-v0.4.0...HEAD
158
+ [Unreleased]: https://github.com/koinzhang/paseo-plugins/compare/activity-v0.6.0...HEAD
159
+ [0.6.0]: https://github.com/koinzhang/paseo-plugins/releases/tag/activity-v0.6.0
160
+ [0.5.0]: https://github.com/koinzhang/paseo-plugins/releases/tag/activity-v0.5.0
102
161
  [0.4.0]: https://github.com/koinzhang/paseo-plugins/releases/tag/activity-v0.4.0
103
162
  [0.3.0]: https://github.com/koinzhang/paseo-plugins/releases/tag/activity-v0.3.0
104
163
  [0.2.0]: https://github.com/koinzhang/paseo-plugins/releases/tag/activity-v0.2.0
package/README.md CHANGED
@@ -6,7 +6,7 @@ It still answers “how am I using Paseo” (tools, messages, models, habits). W
6
6
 
7
7
  | Scope | Role |
8
8
  |---|---|
9
- | **Global** | Cross-workspace habits: heatmap, provider filter, insights, most-used skills / MCP / models |
9
+ | **Global** | Cross-workspace habits: heatmap, rolling 168-hour activity timeline, provider filter, insights, most-used skills / MCP / models |
10
10
  | **Workspace** | Per-workspace agent fleet: ranked list + display prefs + archive; live status (permission / finished / error / running); open Terminals; shell / file / messages KPIs; times via shared `FormattedTime` |
11
11
  | **Agent** | Current session: dense tool KPIs, Skills / MCP header toggle, SKILL.md reader, composer Activity pill; **Needs attention** pill jumps to other same-workspace finished/permission/error sessions |
12
12
 
@@ -26,7 +26,7 @@ Ingests every agent's Paseo timeline into a local SQLite database. Queries read
26
26
  ## Where it shows up
27
27
 
28
28
  - **Sidebar Activity** — global view by provider (heatmap, KPIs, insights, most used)
29
- - **Explorer → Activity** — workspace agents as a management list (search / sort / group / status / lifecycle / archive), live attention (permission badge, status colors, running spinner; directory push + 15s poll), open Terminals (list / preview / close), plus workspace KPIs and top skills / MCP (toggle hidden when only one kind has data); usage queries get a best-effort refresh hint when agents leave running
29
+ - **Explorer → Activity** — workspace agents as a management list (search / sort / group / status / lifecycle / archive), live attention (permission badge, status colors, running spinner; API-owned directory observation + explicit lifecycle/archive fields + 15s reconciliation), open Terminals (list / preview / close), plus workspace KPIs and Skills / MCP ranked or newest-call timeline views (with agent titles and one shared persisted view choice); usage queries get a best-effort refresh hint when agents leave running
30
30
  - **Agent workspace panel** — per-agent tool detail (dense KPI including messages / Skills / MCP toggle / SKILL.md); refreshes on timeline turn terminal events
31
31
  - **Composer pills** — Activity: current agent's skill / MCP summary (hidden when empty); **Needs attention**: other same-workspace agents with finished / permission / error (hidden when none; click opens shared list)
32
32
  - **Command Center** — Activity · Workspace Activity · Agent Activity
@@ -37,7 +37,7 @@ Everything lives on the daemon machine in `~/.paseo/plugin-data/activity/` (SQLi
37
37
 
38
38
  ## Install
39
39
 
40
- Requires Paseo >= 0.8.0. **0.4.0** is the last release that supports Paseo 0.8.0; later versions will require Paseo >= 0.9.0.
40
+ Requires Paseo **>= 0.9.0-beta.2** (current package targets **0.9.0-beta.2**). **0.4.0** is the last release that supports Paseo 0.8.0.
41
41
 
42
42
  From Git (Paseo 0.8 and later):
43
43
 
@@ -3,6 +3,8 @@ import { Pressable, ScrollView, Text, View } from "react-native";
3
3
  import type { ActivityDay } from "../shared/usage.ts";
4
4
  import { activityLevel, buildActivityCalendar, type HeatmapMode } from "../shared/activity.ts";
5
5
  import { useAppLanguage } from "./use-app-language.ts";
6
+ import { useMeasuredWidth } from "./measured-width.ts";
7
+ import { ACTIVITY_MIX_STEPS, mixColor } from "./color-mix.ts";
6
8
  export { computeStreaks, type HeatmapMode } from "../shared/activity.ts";
7
9
 
8
10
  type ThemeColors = {
@@ -12,23 +14,9 @@ type ThemeColors = {
12
14
 
13
15
  type HoveredMonth = { year: number; month: number };
14
16
 
15
- // Derive the activity palette from the active theme.
16
- function mix(base: string, accent: string, amount: number): string {
17
- const parse = (value: string): number[] | null => {
18
- const hex = value.replace("#", "").trim();
19
- const expanded = hex.length === 3 || hex.length === 4
20
- ? hex.split("").map((c) => c + c).join("")
21
- : hex;
22
- // Use first 6 digits only — ignore trailing alpha on 8-digit hex.
23
- const rgb = expanded.slice(0, 6);
24
- if (!/^[0-9a-fA-F]{6}$/.test(rgb)) return null;
25
- return [0, 2, 4].map((i) => parseInt(rgb.slice(i, i + 2), 16));
26
- };
27
- const a = parse(base);
28
- const b = parse(accent);
29
- if (!a || !b) return base;
30
- return `rgb(${a.map((v, i) => Math.round(v + (b[i]! - v) * amount)).join(",")})`;
31
- }
17
+ // Month-axis labels and the mode tabs share one size: both are secondary labels under
18
+ // the section title, so a separate 13 / 15 scale made the tabs outrank the axis.
19
+ const LABEL_FONT_SIZE = 12;
32
20
 
33
21
  function plural(count: number, singular: string, pluralForm = `${singular}s`): string {
34
22
  return `${count.toLocaleString()} ${count === 1 ? singular : pluralForm}`;
@@ -46,7 +34,7 @@ export function ActivityHeatmap({ days, from, colors, compact, mode, onModeChang
46
34
  modeOptions: ReadonlyArray<{ id: HeatmapMode; label: string }>;
47
35
  }) {
48
36
  const locale = useAppLanguage();
49
- const [width, setWidth] = useState(0);
37
+ const [width, widthRef, onWidthLayout] = useMeasuredWidth("global:heatmap");
50
38
  const [gridTop, setGridTop] = useState(0);
51
39
  const [scrollX, setScrollX] = useState(0);
52
40
  const [tooltipSize, setTooltipSize] = useState({ width: 220, height: 28 });
@@ -67,7 +55,7 @@ export function ActivityHeatmap({ days, from, colors, compact, mode, onModeChang
67
55
  : 0;
68
56
  const gridWidth = weeks.length > 0 ? weeks.length * (cellSize + gap) - gap : 0;
69
57
  const needsScroll = gridWidth > width + 0.5;
70
- const palette = [colors.surface2, ...[0.22, 0.43, 0.68, 1].map(n => mix(colors.surface2, colors.accent, n))];
58
+ const palette = [colors.surface2, ...ACTIVITY_MIX_STEPS.map(n => mixColor(colors.surface2, colors.accent, n))];
71
59
  const activeKey = hovered ?? selected;
72
60
  const activeIndex = weeks.flat().findIndex(cell => cell.key === activeKey);
73
61
  const active = activeIndex >= 0 ? weeks.flat()[activeIndex] : undefined;
@@ -89,13 +77,17 @@ export function ActivityHeatmap({ days, from, colors, compact, mode, onModeChang
89
77
  const modeLabel = mode === "weekly" ? "Week containing" : mode === "cumulative" ? "Through" : "";
90
78
  const monthFocus = hoveredMonth != null;
91
79
  return (
92
- <View style={{ gap: compact ? 10 : 12 }} onLayout={event => setWidth(event.nativeEvent.layout.width)}>
80
+ <View
81
+ ref={widthRef}
82
+ style={{ gap: compact ? 10 : 12 }}
83
+ onLayout={onWidthLayout}
84
+ >
93
85
  <View style={{ flexDirection: "row", flexWrap: "wrap", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
94
86
  <Text style={{ color: colors.foreground, fontSize: compact ? 13 : 15, fontWeight: "500" }}>Activity</Text>
95
87
  <View style={{ flexDirection: "row", gap: compact ? 14 : 20 }}>
96
88
  {modeOptions.map(option => (
97
89
  <Pressable key={option.id} accessibilityRole="tab" accessibilityState={{ selected: mode === option.id }} onPress={() => onModeChange(option.id)} style={{ paddingVertical: 6 }}>
98
- <Text style={{ color: mode === option.id ? colors.foreground : colors.foregroundMuted, fontSize: compact ? 13 : 15 }}>{option.label}</Text>
90
+ <Text style={{ color: mode === option.id ? colors.foreground : colors.foregroundMuted, fontSize: LABEL_FONT_SIZE }}>{option.label}</Text>
99
91
  </Pressable>
100
92
  ))}
101
93
  </View>
@@ -108,7 +100,7 @@ export function ActivityHeatmap({ days, from, colors, compact, mode, onModeChang
108
100
  onScroll={event => setScrollX(event.nativeEvent.contentOffset.x)}
109
101
  scrollEventThrottle={16}
110
102
  >
111
- <View style={{ width: Math.max(0, axisWidth), paddingBottom: 4 }}>
103
+ <View style={{ width: Math.max(0, axisWidth) }}>
112
104
  <View style={{ flexDirection: "row", gap }}>
113
105
  {weeks.map((week, i) => (
114
106
  <View key={i} style={{ gap }}>
@@ -123,7 +115,7 @@ export function ActivityHeatmap({ days, from, colors, compact, mode, onModeChang
123
115
  hidden
124
116
  ? base
125
117
  : monthFocus && inMonth
126
- ? mix(base, colors.accent, 0.04)
118
+ ? mixColor(base, colors.accent, 0.04)
127
119
  : base;
128
120
  const opacity = hidden
129
121
  ? 0
@@ -149,7 +141,7 @@ export function ActivityHeatmap({ days, from, colors, compact, mode, onModeChang
149
141
  </View>
150
142
  ))}
151
143
  </View>
152
- <View style={{ height: 24, marginTop: 10, flexDirection: "row", justifyContent: "space-between" }}>
144
+ <View style={{ marginTop: 10, flexDirection: "row", justifyContent: "space-between" }}>
153
145
  {months.map((item, i) => {
154
146
  const activeMonth =
155
147
  hoveredMonth?.year === item.year && hoveredMonth.month === item.month;
@@ -168,7 +160,7 @@ export function ActivityHeatmap({ days, from, colors, compact, mode, onModeChang
168
160
  numberOfLines={1}
169
161
  style={{
170
162
  color: activeMonth ? colors.foreground : colors.foregroundMuted,
171
- fontSize: 12,
163
+ fontSize: LABEL_FONT_SIZE,
172
164
  }}
173
165
  >
174
166
  {item.label}
@@ -0,0 +1,207 @@
1
+ import { useEffect, useMemo, useState } from "react";
2
+ import { Pressable, Text, View } from "react-native";
3
+ import {
4
+ buildAgentCreationBuckets,
5
+ rankCreationProviders,
6
+ stackCreationProviders,
7
+ type CreationBucket,
8
+ type CreationProviderSlice,
9
+ } from "../shared/activity.ts";
10
+ import type { AgentCreationDay } from "../shared/usage.ts";
11
+ import { creationBarColor } from "./color-mix.ts";
12
+ import { chartColorScheme, creationProviderColors } from "./rank-color.ts";
13
+ import { fixedWindowFrom } from "./range.ts";
14
+
15
+ type ThemeColors = {
16
+ accent: string;
17
+ border: string;
18
+ foreground: string;
19
+ foregroundMuted: string;
20
+ surface0: string;
21
+ surface2: string;
22
+ };
23
+
24
+ function bucketDate(key: string): Date {
25
+ const [year, month, day] = key.split("-").map(Number);
26
+ return new Date(year!, month! - 1, day!);
27
+ }
28
+
29
+ /** Locale month + day, e.g. `Sep 6` / `9月6日`. */
30
+ function dayLabel(key: string, locale: string): string {
31
+ return bucketDate(key).toLocaleDateString(locale, { month: "short", day: "numeric" });
32
+ }
33
+
34
+ function agentCountText(count: number): string {
35
+ return `${count} ${count === 1 ? "agent" : "agents"}`;
36
+ }
37
+
38
+ /**
39
+ * Agent creations per local day over a fixed window (051 / 057): the last
40
+ * `windowDays` days ending today, independent of the range chips. Each day is
41
+ * one accent-intensity bar (057); hovering shows a provider breakdown card
42
+ * (nonzero that day only, 056) with brand-coloured chips and the date.
43
+ */
44
+ export function AgentCreations({ days, windowDays, colors, compact, locale }: {
45
+ days: readonly AgentCreationDay[];
46
+ windowDays: number;
47
+ colors: ThemeColors;
48
+ compact?: boolean;
49
+ locale: string;
50
+ }) {
51
+ const from = fixedWindowFrom(windowDays);
52
+ const buckets = useMemo(
53
+ () => buildAgentCreationBuckets(days, { from }),
54
+ [days, from],
55
+ );
56
+ const providers = useMemo(() => rankCreationProviders(buckets), [buckets]);
57
+ const [hovered, setHovered] = useState<string | null>(null);
58
+ const [selected, setSelected] = useState<string | null>(null);
59
+ const [width, setWidth] = useState(0);
60
+ const [tooltipSize, setTooltipSize] = useState({ width: 150, height: 0 });
61
+ useEffect(() => {
62
+ setHovered(null);
63
+ setSelected(null);
64
+ // Only the window start invalidates the selection: refetching the same
65
+ // window must not close a tooltip the pointer is resting on (051).
66
+ }, [from]);
67
+
68
+ const activeKey = hovered ?? selected;
69
+ const total = buckets.reduce((sum, bucket) => sum + bucket.count, 0);
70
+ const max = buckets.reduce((peak, bucket) => Math.max(peak, bucket.count), 0);
71
+ const activeIndex = buckets.findIndex((bucket) => bucket.key === activeKey);
72
+ const active = activeIndex >= 0 ? buckets[activeIndex] : undefined;
73
+ const chartHeight = compact ? 56 : 72;
74
+ const gap = compact ? 2 : 3;
75
+ const slot = buckets.length > 0 ? (width + gap) / buckets.length : 0;
76
+ const anchorX = activeIndex >= 0 ? activeIndex * slot + (slot - gap) / 2 : 0;
77
+ const tooltipLeft = Math.max(0, Math.min(anchorX - tooltipSize.width / 2, width - tooltipSize.width));
78
+ const scheme = chartColorScheme(colors.surface0);
79
+ const colorByProvider = creationProviderColors(
80
+ providers.map((item) => item.provider),
81
+ scheme,
82
+ );
83
+ const tooltipProviders = active
84
+ ? stackCreationProviders(providers, active.providers)
85
+ : [];
86
+ const first = buckets[0];
87
+
88
+ return (
89
+ <View style={{ gap: compact ? 10 : 12 }}>
90
+ <Text style={{ color: colors.foreground, fontSize: compact ? 13 : 15, fontWeight: "500" }}>
91
+ Agents
92
+ </Text>
93
+
94
+ {total === 0 ? (
95
+ <Text style={{ color: colors.foregroundMuted, fontSize: 14 }}>
96
+ No agents created in the last {windowDays} days
97
+ </Text>
98
+ ) : (
99
+ <View style={{ gap: 6 }}>
100
+ <View style={{ position: "relative" }} onLayout={(event) => setWidth(event.nativeEvent.layout.width)}>
101
+ <View style={{ flexDirection: "row", alignItems: "flex-end", gap, height: chartHeight }}>
102
+ {buckets.map((bucket) => (
103
+ <Pressable
104
+ key={bucket.key}
105
+ accessibilityRole="button"
106
+ accessibilityLabel={`${dayLabel(bucket.key, locale)}: ${agentCountText(bucket.count)}${providerBreakdown(bucket, providers)}`}
107
+ accessibilityState={{ selected: activeKey === bucket.key }}
108
+ onHoverIn={() => setHovered(bucket.key)}
109
+ onHoverOut={() => setHovered(null)}
110
+ onFocus={() => setHovered(bucket.key)}
111
+ onBlur={() => setHovered(null)}
112
+ onPress={() => setSelected((prev) => (prev === bucket.key ? null : bucket.key))}
113
+ style={{
114
+ flex: 1,
115
+ minWidth: 3,
116
+ height: chartHeight,
117
+ justifyContent: "flex-end",
118
+ }}
119
+ >
120
+ {bucket.providers.length === 0 ? (
121
+ <View style={{ height: 2, backgroundColor: colors.surface2 }} />
122
+ ) : (
123
+ <View
124
+ style={{
125
+ height: max > 0 ? Math.max(2, Math.round((bucket.count / max) * chartHeight)) : 2,
126
+ backgroundColor: creationBarColor(
127
+ bucket.count,
128
+ max,
129
+ colors.surface2,
130
+ colors.accent,
131
+ ),
132
+ borderTopLeftRadius: 3,
133
+ borderTopRightRadius: 3,
134
+ }}
135
+ />
136
+ )}
137
+ </Pressable>
138
+ ))}
139
+ </View>
140
+ {active && width > 0 ? (
141
+ <View
142
+ pointerEvents="none"
143
+ onLayout={(event) =>
144
+ setTooltipSize({
145
+ width: event.nativeEvent.layout.width,
146
+ height: event.nativeEvent.layout.height,
147
+ })
148
+ }
149
+ style={{
150
+ position: "absolute",
151
+ left: tooltipLeft,
152
+ bottom: chartHeight + 6,
153
+ zIndex: 10,
154
+ paddingHorizontal: 12,
155
+ paddingVertical: 8,
156
+ borderRadius: 10,
157
+ backgroundColor: colors.surface2,
158
+ borderWidth: 1,
159
+ borderColor: colors.border,
160
+ gap: 4,
161
+ }}
162
+ >
163
+ {tooltipProviders.map((item) => (
164
+ <View key={item.provider} style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
165
+ <View
166
+ style={{
167
+ width: 10,
168
+ height: 10,
169
+ borderRadius: 3,
170
+ backgroundColor: colorByProvider.get(item.provider) ?? colors.accent,
171
+ }}
172
+ />
173
+ <Text style={{ color: colors.foreground, fontSize: 13 }}>
174
+ {item.label}: {item.count}
175
+ </Text>
176
+ </View>
177
+ ))}
178
+ <Text
179
+ accessibilityLiveRegion="polite"
180
+ style={{ color: colors.foregroundMuted, fontSize: 12, marginTop: 2 }}
181
+ >
182
+ {dayLabel(active.key, locale)}
183
+ </Text>
184
+ </View>
185
+ ) : null}
186
+ </View>
187
+ <View style={{ flexDirection: "row", justifyContent: "space-between" }}>
188
+ <Text style={{ color: colors.foregroundMuted, fontSize: 12 }}>
189
+ {first ? dayLabel(first.key, locale) : ""}
190
+ </Text>
191
+ <Text style={{ color: colors.foregroundMuted, fontSize: 12 }}>Today</Text>
192
+ </View>
193
+ </View>
194
+ )}
195
+ </View>
196
+ );
197
+ }
198
+
199
+ function providerBreakdown(
200
+ bucket: CreationBucket,
201
+ ranked: readonly CreationProviderSlice[],
202
+ ): string {
203
+ const stacked = stackCreationProviders(ranked, bucket.providers);
204
+ if (stacked.length === 0) return "";
205
+ // Top→bottom to match the painted stack.
206
+ return ` — ${stacked.map((slice) => `${slice.label} ${slice.count}`).join(", ")}`;
207
+ }
@@ -0,0 +1,191 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { setImmediate } from "node:timers/promises";
4
+ import { createPaseoApi } from "@getpaseo/client";
5
+ import { watchAgentDirectory, type DirectoryAgent } from "./agent-directory.ts";
6
+ import { watchPillDirectory } from "./pill-directory.ts";
7
+
8
+ type Page = { entries: Array<{ agent: DirectoryAgent }>; pageInfo: { hasMore: boolean; nextCursor: string | null }; subscriptionId?: string };
9
+ const agent = (id: string, extra: object = {}) => ({ id, workspaceId: "w", status: "idle", archivedAt: null, ...extra }) as DirectoryAgent;
10
+ const page = (agents: DirectoryAgent[], nextCursor: string | null = null): Page => ({ entries: agents.map(agent => ({ agent })), pageInfo: { hasMore: nextCursor !== null, nextCursor } });
11
+ function deferred<T>() {
12
+ let resolve!: (value: T) => void;
13
+ let reject!: (error: Error) => void;
14
+ const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no; });
15
+ return { promise, resolve, reject };
16
+ }
17
+ function harness(initial = page([agent("a")])) {
18
+ type Observer = { snapshot(page: Page): void; update(message: unknown): void; error?(error: Error): void };
19
+ const owned: Array<{ emit(update: object): void; reconnect(value: Page): void; fail(): void; released: boolean; signal?: AbortSignal }> = [];
20
+ let reads = 0;
21
+ let read: (options: any) => Promise<Page> = async () => initial;
22
+ let bootstrap: Promise<Page> | undefined;
23
+ let rejectRelease = false;
24
+ const daemon = {
25
+ fetchAgents: (options: unknown) => { reads++; return read(options); },
26
+ observeAgents(options: { signal?: AbortSignal }) {
27
+ let observer: Observer | undefined;
28
+ const entry = {
29
+ signal: options.signal,
30
+ released: false,
31
+ emit(payload: object) { observer?.update({ type: "agent_update", payload }); },
32
+ reconnect(value: Page) { observer?.snapshot({ ...value, subscriptionId: "restored" }); },
33
+ fail() { observer?.error?.(new Error("subscription lost")); },
34
+ };
35
+ owned.push(entry);
36
+ return {
37
+ ready: bootstrap ?? Promise.resolve({ ...initial, subscriptionId: String(owned.length) }),
38
+ subscribe(next: Observer) { observer = next; next.snapshot(initial); return () => { observer = undefined; }; },
39
+ async release() { entry.released = true; if (rejectRelease) throw new Error("release failed"); },
40
+ };
41
+ },
42
+ };
43
+ return {
44
+ api: () => createPaseoApi(daemon as unknown as Parameters<typeof createPaseoApi>[0]),
45
+ owned,
46
+ setRead(fn: typeof read) { read = fn; },
47
+ setBootstrap(value: Promise<Page>) { bootstrap = value; },
48
+ setReleaseFailure() { rejectRelease = true; },
49
+ get reads() { return reads; },
50
+ };
51
+ }
52
+
53
+ test("real beta.2 API isolates owners; watchers share only their own API and release last", async () => {
54
+ const h = harness();
55
+ const host = h.api(), plugin = h.api(), surface = h.api();
56
+ await host.agents.list({ subscribe: {} });
57
+ let seen: ReadonlyMap<string, DirectoryAgent> | undefined;
58
+ const stop = watchAgentDirectory(plugin.agents, (value) => { seen = value; });
59
+ const stop2 = watchAgentDirectory(plugin.agents, () => {});
60
+ const stopSurface = watchAgentDirectory(surface.agents, () => {});
61
+ await setImmediate();
62
+ assert.equal(h.owned.length, 3);
63
+ h.owned[0]!.emit({ kind: "remove", agentId: "a" });
64
+ assert.equal(seen?.has("a"), true);
65
+ h.owned[1]!.emit({ kind: "upsert", agent: agent("a", { status: "running" }) });
66
+ assert.equal(seen?.get("a")?.status, "running");
67
+ stop();
68
+ assert.equal(h.owned[1]!.released, false);
69
+ stop2(); stopSurface();
70
+ await setImmediate();
71
+ assert.equal(h.owned[1]!.released, true);
72
+ assert.equal(h.owned[2]!.released, true);
73
+ assert.equal(h.owned[0]!.released, false);
74
+ await host.dispose();
75
+ });
76
+
77
+ test("bootstrap pagination replays concurrent updates and reconnect rebuilds all pages", async () => {
78
+ const h = harness(page([agent("a")], "next"));
79
+ const tail = deferred<Page>();
80
+ h.setRead(async (options) => { assert.equal(options.page.cursor, "next"); return tail.promise; });
81
+ const api = h.api();
82
+ let seen: ReadonlyMap<string, DirectoryAgent> | undefined;
83
+ const stop = watchAgentDirectory(api.agents, value => { seen = value; });
84
+ try {
85
+ await setImmediate();
86
+ assert.equal(Boolean(seen), false);
87
+ h.owned[0]!.emit({ kind: "remove", agentId: "a" });
88
+ h.owned[0]!.emit({ kind: "upsert", agent: agent("b", { status: "running" }) });
89
+ tail.resolve(page([agent("b")]));
90
+ await setImmediate();
91
+ assert.equal(seen?.has("a"), false);
92
+ assert.equal(seen?.get("b")?.status, "running");
93
+ h.setRead(async () => page([agent("d")]));
94
+ h.owned[0]!.reconnect(page([agent("c")], "restored-next"));
95
+ await setImmediate();
96
+ assert.deepEqual([...seen!.keys()], ["c", "d"]);
97
+ } finally { stop(); }
98
+ });
99
+
100
+ test("a stale poll cannot overwrite a newer live update", async () => {
101
+ const h = harness();
102
+ const pending = deferred<Page>();
103
+ h.setRead(() => pending.promise);
104
+ let seen: ReadonlyMap<string, DirectoryAgent> | undefined;
105
+ const stop = watchAgentDirectory(h.api().agents, value => { seen = value; }, 1);
106
+ try {
107
+ while (!h.reads) await setImmediate();
108
+ h.owned[0]!.emit({ kind: "upsert", agent: agent("a", { status: "closed", archivedAt: null }) });
109
+ pending.resolve(page([agent("a")]));
110
+ h.setRead(async () => page([agent("a", { status: "closed", archivedAt: null })]));
111
+ await setImmediate();
112
+ assert.equal(seen?.get("a")?.status, "closed");
113
+ } finally { stop(); }
114
+ });
115
+
116
+ test("unmount during bootstrap aborts demand and releases a late handle without publishing", async () => {
117
+ const h = harness();
118
+ const pending = deferred<Page>();
119
+ h.setBootstrap(pending.promise);
120
+ let calls = 0;
121
+ const stop = watchAgentDirectory(h.api().agents, () => { calls++; });
122
+ stop();
123
+ assert.equal(h.owned[0]?.signal?.aborted, true);
124
+ pending.resolve(page([agent("late")]));
125
+ await setImmediate();
126
+ assert.equal(h.owned[0]?.released, true);
127
+ assert.equal(calls, 0);
128
+ });
129
+
130
+ test("subscription failure retries, and release failure is handled", async (t) => {
131
+ const errors: unknown[] = [];
132
+ t.mock.method(console, "error", (...args: unknown[]) => { errors.push(args); });
133
+ const h = harness();
134
+ const stop = watchAgentDirectory(h.api().agents, () => {}, 1);
135
+ await setImmediate();
136
+ h.owned[0]!.fail();
137
+ while (h.owned.length < 2) await setImmediate();
138
+ await setImmediate();
139
+ assert.equal(h.owned[0]?.released, true);
140
+ h.setReleaseFailure();
141
+ stop();
142
+ await setImmediate();
143
+ assert.ok(errors.some(args => String(args).includes("release failed")));
144
+ });
145
+
146
+ test("pill directory observes archive/unarchive and does not revive unchanged idle pills", async () => {
147
+ const h = harness();
148
+ const seen = new Set<string>();
149
+ let published = 0;
150
+ const stop = watchPillDirectory(h.api().agents, value => { published++; seen.add(value.id); }, id => seen.delete(id));
151
+ try {
152
+ await setImmediate();
153
+ assert.deepEqual([...seen], ["a"]);
154
+ h.owned[0]!.emit({ kind: "upsert", agent: agent("a") });
155
+ assert.equal(published, 1);
156
+ h.owned[0]!.emit({ kind: "upsert", agent: agent("a", { status: "closed", archivedAt: "2026-09-20" }) });
157
+ assert.equal(seen.size, 0);
158
+ h.owned[0]!.emit({ kind: "upsert", agent: agent("a") });
159
+ assert.deepEqual([...seen], ["a"]);
160
+ assert.equal(published, 2);
161
+ } finally { stop(); }
162
+ });
163
+
164
+ test("bootstrap subscription rejection still falls back to plain reads", async (t) => {
165
+ t.mock.method(console, "error", () => {});
166
+ const h = harness();
167
+ h.setBootstrap(Promise.reject(new Error("observation unavailable")));
168
+ let seen: ReadonlyMap<string, DirectoryAgent> | undefined;
169
+ const stop = watchAgentDirectory(h.api().agents, value => { seen = value; });
170
+ try {
171
+ await setImmediate();
172
+ assert.equal(h.reads, 1);
173
+ assert.equal(seen?.has("a"), true);
174
+ } finally { stop(); }
175
+ });
176
+
177
+ test("a restored snapshot supersedes an outstanding pre-reconnect poll", async () => {
178
+ const h = harness();
179
+ const oldRead = deferred<Page>();
180
+ h.setRead(() => oldRead.promise);
181
+ let seen: ReadonlyMap<string, DirectoryAgent> | undefined;
182
+ const stop = watchAgentDirectory(h.api().agents, value => { seen = value; }, 1);
183
+ try {
184
+ while (!h.reads) await setImmediate();
185
+ h.owned[0]!.reconnect(page([agent("restored")]));
186
+ oldRead.resolve(page([agent("stale")]));
187
+ h.setRead(async () => page([agent("restored")]));
188
+ await setImmediate();
189
+ assert.deepEqual([...seen!.keys()], ["restored"]);
190
+ } finally { stop(); }
191
+ });