@koinzhang/paseo-plugin-activity 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +26 -1
  2. package/README.md +23 -9
  3. package/client/formatted-time.tsx +23 -0
  4. package/client/hidden-pill-recheck.test.ts +33 -0
  5. package/client/hidden-pill-recheck.ts +22 -0
  6. package/client/panel.tsx +115 -107
  7. package/client/pill-directory.test.ts +92 -0
  8. package/client/pill-directory.ts +79 -0
  9. package/client/pill.tsx +23 -23
  10. package/client/usage-popover.tsx +75 -84
  11. package/client/usage-query.tsx +8 -3
  12. package/client/usage-stats.tsx +2 -2
  13. package/client/use-agent-turn-end.ts +69 -0
  14. package/client/workspace/agent-row.tsx +57 -7
  15. package/client/workspace/agents-section.tsx +7 -0
  16. package/client/workspace/constants.ts +29 -3
  17. package/client/workspace/filters.ts +2 -2
  18. package/client/workspace/list-host-agents.test.ts +45 -0
  19. package/client/workspace/list-host-agents.ts +55 -22
  20. package/client/workspace/panel.tsx +172 -8
  21. package/client/workspace/rank-section.tsx +36 -26
  22. package/client/workspace/running-indicator.tsx +54 -0
  23. package/client/workspace/status-cache.test.ts +62 -0
  24. package/client/workspace/status-cache.ts +19 -0
  25. package/client/workspace/terminal-preview.test.ts +17 -0
  26. package/client/workspace/terminal-preview.ts +10 -0
  27. package/client/workspace/terminals-section.tsx +155 -0
  28. package/index.server.ts +2 -0
  29. package/package.json +3 -3
  30. package/server/agents.test.ts +16 -0
  31. package/server/agents.ts +7 -4
  32. package/server/handlers-query.test.ts +24 -3
  33. package/server/handlers.ts +17 -5
  34. package/server/skill-path.ts +3 -20
  35. package/shared/format.test.ts +35 -31
  36. package/shared/format.ts +21 -36
  37. package/shared/home-path.ts +19 -0
  38. package/shared/usage.ts +9 -0
package/CHANGELOG.md CHANGED
@@ -7,6 +7,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.3.0] - 2026-09-19
11
+
12
+ ### Added
13
+
14
+ - Workspace Activity panel **Terminals** section: lists open terminals via the host SDK (`paseo.terminals.list`), tap-to-expand live output preview (`capture`, latest 8 lines, ANSI stripped, 5s polling), and a per-row close button (`kill`, optimistic removal with rollback toast); terminal cwd collapses the home directory to `~` (new `usage.host-info` RPC); the section is hidden when no terminals are open.
15
+ - Explorer Agents rows show a warning badge (ShieldAlert icon, plus a count when there are multiple) when the host reports pending permission requests; those agents also rank first with other attention-worthy agents.
16
+ - Explorer Agents row bot icon uses theme status colors for attention: success for finished-but-unread turns, warning for pending permissions (badge kept), danger for failed agents; the icon returns to muted once the host clears attention after viewing.
17
+ - Explorer Agents rows show a host-style spinning ring at the bottom-right of the bot icon while `status = "running"`; it disappears when the turn ends.
18
+ - Explorer agent status (permission badge, attention colors, running spinner) accelerates from directory `agent_update` pushes (incremental status cache); the 15s poll remains the completeness guarantee and does not call `agents.list({ subscribe })` (avoids stealing the host's single observation slot on Paseo 0.8).
19
+ - Agent panel / composer pill usage queries refresh on real timeline turn terminal events (`turn_completed` / `turn_failed` / `turn_canceled` / `replacement`, 300ms debounce + 2s ingest settle); Workspace panel gets a best-effort directory hint when an agent leaves `running` / `initializing`, with the 15s query poll owning completeness. Pill empty-state poll slowed from 1.5s to 5s. Global surface and Terminals keep their existing poll intervals.
20
+ - Shared activity time formatting: `FormattedTime` / `formatActivityTime` (app language + locale, 24-hour clock; same-day time only, same-year month/day + time, else include year) used by Agent panel, Workspace rank / Updated meta, and the composer popover.
21
+
22
+ ### Changed
23
+
24
+ - Agent Activity panel and composer popover: Skills / MCP detail uses the same header toggle icon pattern as Workspace rank (no tab strip).
25
+ - Agent Activity panel KPIs use dense `UsageStats` (aligned with Workspace).
26
+ - Workspace skills / MCP rank toggle is hidden when only one kind has data.
27
+
28
+ ### Fixed
29
+
30
+ - Workspace agent status enrichment filters by placement `projectId` (daemon shape), not `projects.list` remote keys — stops the 15s poll from wiping live permission / attention state.
31
+ - In-flight status polls are cancelled before applying a newer directory push, so stale responses cannot overwrite live agent state.
32
+ - Skill path resolution refreshes empty handles and falls back to home roots when project cwd lookup fails.
33
+
10
34
  ## [0.2.0] - 2026-09-19
11
35
 
12
36
  ### Added
@@ -51,6 +75,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
51
75
  - Command Center entries: open panels and export a markdown usage report.
52
76
  - Plugin renamed from `tool-usage` to `activity`, migrating the old data directory automatically.
53
77
 
54
- [Unreleased]: https://github.com/koinzhang/paseo-plugins/compare/activity-v0.2.0...HEAD
78
+ [Unreleased]: https://github.com/koinzhang/paseo-plugins/compare/activity-v0.3.0...HEAD
79
+ [0.3.0]: https://github.com/koinzhang/paseo-plugins/releases/tag/activity-v0.3.0
55
80
  [0.2.0]: https://github.com/koinzhang/paseo-plugins/releases/tag/activity-v0.2.0
56
81
  [0.1.0]: https://github.com/koinzhang/paseo-plugins/releases/tag/activity-v0.1.0
package/README.md CHANGED
@@ -1,22 +1,35 @@
1
1
  # Activity
2
2
 
3
- Local usage analytics for Paseo: tool calls, agents, messages, and model usage.
3
+ Activity for Paseo: local usage analytics **and** workspace agent management.
4
4
 
5
- Activity ingests every agent's Paseo timeline into a local SQLite database and answers "how am I / each provider actually using Paseo". Queries read the local database; the Paseo timeline and `agents.list` are ingestion and backfill sources only.
5
+ It still answers “how am I using Paseo” (tools, messages, models, habits). With the Explorer **Workspace Activity** panel it also becomes a **vertical ops surface** for the agents in the current workspace — sort, filter, search, open, archive — with live attention cues, open terminals, KPIs, and top skills / MCP.
6
+
7
+ | Scope | Role |
8
+ |---|---|
9
+ | **Global** | Cross-workspace habits: heatmap, provider filter, insights, most-used skills / MCP / models |
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
+ | **Agent** | Current session: dense tool KPIs, Skills / MCP header toggle, SKILL.md reader, composer pill; refreshes on timeline turn end |
12
+
13
+ Architecture notes: [docs/architecture.md](./docs/architecture.md).
14
+
15
+ ## What is counted
16
+
17
+ Ingests every agent's Paseo timeline into a local SQLite database. Queries read that database; the timeline and `agents.list` are ingestion / backfill / live-status sources only.
6
18
 
7
19
  | Dimension | What is counted |
8
20
  |---|---|
9
21
  | Tools | Skill / MCP / shell / file calls; skills classified into exact / inferred / low confidence tiers |
10
22
  | Agents | Every created agent (registry with archive metadata) |
11
23
  | Messages | User-sent messages |
12
- | Models | Model at send time (weighted by messages) |
24
+ | Models | Model at send time (weighted by messages; global view) |
13
25
 
14
26
  ## Where it shows up
15
27
 
16
- - **Composer pill** — current agent's skill / MCP summary, hidden when there is no data
17
- - **Agent workspace panel** — per-agent detail (KPI / Skills / MCP / SKILL.md reader)
18
- - **Activity sidebar** — global view grouped by provider; heatmap, KPIs, insights, most used
19
- - **Command Center** — open panels, export a markdown usage report
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
30
+ - **Agent workspace panel** — per-agent tool detail (dense KPI including messages / Skills / MCP toggle / SKILL.md); refreshes on timeline turn terminal events
31
+ - **Composer pill** — current agent's skill / MCP summary (header toggle); hidden when empty; refreshes on timeline turn end (5s empty poll fallback)
32
+ - **Command Center** — Activity · Workspace Activity · Agent Activity
20
33
 
21
34
  ## Data
22
35
 
@@ -48,9 +61,10 @@ paseo plugin ls
48
61
 
49
62
  ## Limitations
50
63
 
51
- - Analytics are local to each daemon: every machine keeps its own database, and there is no cross-host aggregation.
64
+ - Analytics and the agent registry are local to each daemon: every machine keeps its own database, and there is no cross-host aggregation.
52
65
  - Numbers are reconstructed from the Paseo timeline; items that do not report a model or skill cannot be attributed for that dimension.
53
66
  - Skill classification is heuristic (exact / inferred / low confidence); check the tier before trusting a count.
67
+ - Workspace Activity focuses on agent operations for the current workspace; heatmap / provider / model breakdowns stay on the global sidebar.
54
68
 
55
69
  ## Development
56
70
 
@@ -64,7 +78,7 @@ This plugin is spec-driven: read [specs/README.md](./specs/README.md) before cod
64
78
 
65
79
  ## Publish
66
80
 
67
- Release history: [CHANGELOG.md](./CHANGELOG.md). npm releases go through a GitHub Release tag `activity-vX.Y.Z` (not push-to-`main` alone). Steps: [CONTRIBUTING.md § Publishing to npm](../CONTRIBUTING.md#publishing-to-npm).
81
+ Release history: [CHANGELOG.md](./CHANGELOG.md) (current **0.3.0**). npm releases go through a GitHub Release tag `activity-vX.Y.Z` (not push-to-`main` alone). Steps: [CONTRIBUTING.md § Publishing to npm](../CONTRIBUTING.md#publishing-to-npm).
68
82
 
69
83
  ## License
70
84
 
@@ -0,0 +1,23 @@
1
+ import type { ReactNode } from "react";
2
+ import { Text, type TextStyle } from "react-native";
3
+ import { formatActivityTime } from "../shared/format.ts";
4
+ import { useAppLanguage } from "./use-app-language.ts";
5
+
6
+ /**
7
+ * ISO timestamp with app language (fallback `en`) + Intl locale style.
8
+ * Today → time only; same year → month/day + time; otherwise includes the year.
9
+ */
10
+ export function FormattedTime({
11
+ iso,
12
+ style,
13
+ prefix,
14
+ }: {
15
+ iso: string | null | undefined;
16
+ style?: TextStyle;
17
+ /** e.g. `"Last "` — concatenated before the stamp */
18
+ prefix?: string;
19
+ }): ReactNode {
20
+ const locale = useAppLanguage();
21
+ const stamp = formatActivityTime(iso, locale);
22
+ return <Text style={style}>{prefix ? `${prefix}${stamp}` : stamp}</Text>;
23
+ }
@@ -0,0 +1,33 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { createHiddenPillRecheck } from "./hidden-pill-recheck.ts";
4
+ import type { UsagePillData } from "./pill-data-cache.ts";
5
+ const empty: UsagePillData = { skills: [], mcpTools: [] };
6
+ const populated: UsagePillData = { skills: [], mcpTools: [{ server: "paseo", tool: "read", count: 1, failures: 0, lastUsedAt: null }] };
7
+
8
+ test("hidden empty pill stays hidden, but delayed ingestion can show it", async () => {
9
+ let data = empty;
10
+ let shows = 0;
11
+ const check = createHiddenPillRecheck(async () => data, () => true, () => { shows++; });
12
+ await check(); await check();
13
+ assert.equal(shows, 0);
14
+ data = populated;
15
+ await check();
16
+ assert.equal(shows, 1);
17
+ });
18
+
19
+ test("hidden rechecks coalesce and cannot show a removed pill", async () => {
20
+ let finish!: (data: UsagePillData) => void;
21
+ let current = true;
22
+ let loads = 0;
23
+ let shows = 0;
24
+ const check = createHiddenPillRecheck(() => { loads++; return new Promise(resolve => { finish = resolve; }); },
25
+ () => current, () => { shows++; });
26
+ const first = check();
27
+ await check();
28
+ assert.equal(loads, 1);
29
+ current = false;
30
+ finish(populated);
31
+ await first;
32
+ assert.equal(shows, 0);
33
+ });
@@ -0,0 +1,22 @@
1
+ import { pillDataIsEmpty, type UsagePillData } from "./pill-data-cache.ts";
2
+
3
+ /** Recheck hidden pills without showing empty chrome; discard results after removal. */
4
+ export function createHiddenPillRecheck(
5
+ load: () => Promise<UsagePillData>,
6
+ isCurrentAndHidden: () => boolean,
7
+ show: (data: UsagePillData) => void,
8
+ ): () => Promise<void> {
9
+ let running = false;
10
+ return async () => {
11
+ if (running || !isCurrentAndHidden()) return;
12
+ running = true;
13
+ try {
14
+ const data = await load();
15
+ if (isCurrentAndHidden() && !pillDataIsEmpty(data)) show(data);
16
+ } catch (error) {
17
+ if (isCurrentAndHidden()) console.error("[activity] hidden pill recheck failed", error);
18
+ } finally {
19
+ running = false;
20
+ }
21
+ };
22
+ }
package/client/panel.tsx CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type PluginAgentPanelProps, useAgent, useRpc } from "@getpaseo/plugin/client";
2
2
  import { Icon } from "@getpaseo/plugin/client/react-native";
3
- import { useQuery } from "@tanstack/react-query";
3
+ import { useQuery, useQueryClient } from "@tanstack/react-query";
4
4
  import { useEffect, useMemo, useState, type ReactNode } from "react";
5
5
  import {
6
6
  ActivityIndicator,
@@ -17,12 +17,14 @@ import {
17
17
  usageSkillsByNameRpc,
18
18
  usageSummaryRpc,
19
19
  } from "../shared/usage.ts";
20
- import { formatDisplayName, formatLocalDateTime } from "../shared/format.ts";
20
+ import { formatDisplayName } from "../shared/format.ts";
21
+ import { FormattedTime } from "./formatted-time.tsx";
21
22
  import {
22
23
  clearPendingSkillOpen,
23
24
  consumePendingSkillOpen,
24
25
  subscribePendingSkillOpen,
25
26
  } from "./pending-skill.ts";
27
+ import { useAgentTurnEnd } from "./use-agent-turn-end.ts";
26
28
 
27
29
  import { UsageStats } from "./usage-stats.tsx";
28
30
 
@@ -99,6 +101,13 @@ export function UsagePanel({ theme, layout, agentId, navigation }: PluginAgentPa
99
101
  retry: false,
100
102
  });
101
103
 
104
+ const queryClient = useQueryClient();
105
+ useAgentTurnEnd({ agentId }, () => {
106
+ void queryClient.invalidateQueries({ queryKey: ["activity", "skills-by-name", agentId] });
107
+ void queryClient.invalidateQueries({ queryKey: ["activity", "mcp-by-tool", agentId] });
108
+ void queryClient.invalidateQueries({ queryKey: ["activity", "summary", agentId] });
109
+ });
110
+
102
111
  const skillItems = useMemo(() => {
103
112
  return (skillsByName.data?.items ?? [])
104
113
  .filter((item) => item.total > 0)
@@ -152,33 +161,31 @@ export function UsagePanel({ theme, layout, agentId, navigation }: PluginAgentPa
152
161
  },
153
162
  sectionTitle: {
154
163
  color: theme.colors.foreground,
155
- fontSize: layout.compact ? 18 : 20,
164
+ fontSize: 14,
165
+ fontWeight: "600" as const,
166
+ flexShrink: 1,
167
+ letterSpacing: -0.3,
168
+ },
169
+ listSectionTitle: {
170
+ color: theme.colors.foreground,
171
+ fontSize: 15,
156
172
  fontWeight: "600" as const,
157
173
  flexShrink: 1,
158
174
  letterSpacing: -0.3,
159
175
  },
160
- rangeBar: {
176
+ sectionHeaderRow: {
161
177
  flexDirection: "row" as const,
162
178
  alignItems: "center" as const,
163
- alignSelf: "flex-start" as const,
164
- gap: 20,
165
- },
166
- rangeSegment: {
167
- paddingVertical: 8,
168
- },
169
- rangeSegmentActive: {
170
- borderBottomWidth: 1,
171
- borderBottomColor: theme.colors.foreground,
172
- },
173
- chipText: {
174
- color: theme.colors.foregroundMuted,
175
- fontSize: 13,
176
- fontWeight: "500" as const,
179
+ justifyContent: "space-between" as const,
180
+ gap: 8,
177
181
  },
178
- chipTextActive: {
179
- color: theme.colors.foreground,
180
- fontSize: 13,
181
- fontWeight: "600" as const,
182
+ titleAction: {
183
+ width: 24,
184
+ height: 24,
185
+ alignItems: "center" as const,
186
+ justifyContent: "center" as const,
187
+ borderRadius: 6,
188
+ flexShrink: 0,
182
189
  },
183
190
  panel: {
184
191
  gap: 4,
@@ -256,6 +263,11 @@ export function UsagePanel({ theme, layout, agentId, navigation }: PluginAgentPa
256
263
 
257
264
  const loading = skillsByName.isLoading || mcpByTool.isLoading;
258
265
  const error = skillsByName.error ?? mcpByTool.error;
266
+ const showToggle = tabs.length > 1;
267
+ const toggleAction =
268
+ tab === "skills"
269
+ ? { icon: "Plug" as const, accessibilityLabel: "Show MCP", next: "mcp" as const }
270
+ : { icon: "Sparkles" as const, accessibilityLabel: "Show skills", next: "skills" as const };
259
271
 
260
272
  if (skillDetail) {
261
273
  return (
@@ -287,12 +299,9 @@ export function UsagePanel({ theme, layout, agentId, navigation }: PluginAgentPa
287
299
  );
288
300
  }
289
301
 
290
- const compact = layout.compact;
291
-
292
302
  return (
293
303
  <ScrollView style={styles.screen} contentContainerStyle={styles.content}>
294
304
  <View style={{ gap: 6 }}>
295
- {!compact ? <Text style={styles.sectionTitle}>Activity</Text> : null}
296
305
  {openAgent ? (
297
306
  <Text
298
307
  accessibilityRole="link"
@@ -306,7 +315,7 @@ export function UsagePanel({ theme, layout, agentId, navigation }: PluginAgentPa
306
315
  <Text style={styles.listMeta}>{conversationLabel}</Text>
307
316
  )}
308
317
  </View>
309
- {!loading && !error ? <UsageStats compact={layout.compact} colors={theme.colors} items={[
318
+ {!loading && !error ? <UsageStats compact={layout.compact} dense colors={theme.colors} items={[
310
319
  { label: "Skill calls", value: skillItems.reduce((sum, item) => sum + item.total, 0).toLocaleString() },
311
320
  { label: "MCP calls", value: mcpItems.reduce((sum, item) => sum + item.count, 0).toLocaleString() },
312
321
  { label: "Shell calls", value: (usageSummary.data?.shellCalls ?? 0).toLocaleString() },
@@ -315,24 +324,6 @@ export function UsagePanel({ theme, layout, agentId, navigation }: PluginAgentPa
315
324
  { label: "Messages", value: (usageSummary.data?.messageCount ?? 0).toLocaleString() },
316
325
  { label: "Tools explored", value: String(skillItems.length + mcpItems.length) },
317
326
  ]} /> : null}
318
- {tabs.length > 1 ? (
319
- <View style={styles.rangeBar}>
320
- {tabs.map((item) => {
321
- const active = tab === item.id;
322
- return (
323
- <Pressable
324
- key={item.id}
325
- accessibilityRole="tab"
326
- accessibilityState={{ selected: active }}
327
- onPress={() => setTab(item.id)}
328
- style={[styles.rangeSegment, active ? styles.rangeSegmentActive : null]}
329
- >
330
- <Text style={active ? styles.chipTextActive : styles.chipText}>{item.label}</Text>
331
- </Pressable>
332
- );
333
- })}
334
- </View>
335
- ) : null}
336
327
 
337
328
  {loading ? <ActivityIndicator color={theme.colors.accent} /> : null}
338
329
  {error ? (
@@ -342,81 +333,98 @@ export function UsagePanel({ theme, layout, agentId, navigation }: PluginAgentPa
342
333
  ) : null}
343
334
 
344
335
  {!loading && !error && tabs.length === 0 ? (
345
- <View style={{ gap: 12 }}>
346
- {!compact ? <Text style={styles.sectionTitle}>Activity</Text> : null}
347
- <Text style={styles.empty}>No skill or MCP calls yet</Text>
348
- </View>
336
+ <Text style={styles.empty}>No skill or MCP calls yet</Text>
349
337
  ) : null}
350
338
 
351
- {tab === "skills" ? (
339
+ {tab ? (
352
340
  <View style={{ gap: 12 }}>
353
- <Text style={styles.sectionTitle}>Skills</Text>
354
- <View style={styles.panel}>
355
- {skillItems.map((item, index) => {
356
- const name = formatDisplayName(item.skillName);
357
- const title = item.skillPath ? (
358
- <Pressable
359
- accessibilityRole="link"
360
- accessibilityLabel={`Open ${name} SKILL.md`}
361
- onPress={() =>
362
- setSkillDetail({ skillName: item.skillName, path: item.skillPath! })
363
- }
364
- >
365
- <Text style={styles.listLink} numberOfLines={1}>
341
+ <View style={styles.sectionHeaderRow}>
342
+ <Text style={styles.listSectionTitle}>{tab === "skills" ? "Skills" : "MCP"}</Text>
343
+ {showToggle ? (
344
+ <Pressable
345
+ accessibilityRole="button"
346
+ accessibilityLabel={toggleAction.accessibilityLabel}
347
+ hitSlop={8}
348
+ onPress={() => setTab(toggleAction.next)}
349
+ style={styles.titleAction}
350
+ >
351
+ <Icon
352
+ name={toggleAction.icon}
353
+ size={16}
354
+ color={theme.colors.foregroundMuted}
355
+ />
356
+ </Pressable>
357
+ ) : null}
358
+ </View>
359
+ {tab === "skills" ? (
360
+ <View style={styles.panel}>
361
+ {skillItems.map((item, index) => {
362
+ const name = formatDisplayName(item.skillName);
363
+ const title = item.skillPath ? (
364
+ <Pressable
365
+ accessibilityRole="link"
366
+ accessibilityLabel={`Open ${name} SKILL.md`}
367
+ onPress={() =>
368
+ setSkillDetail({ skillName: item.skillName, path: item.skillPath! })
369
+ }
370
+ >
371
+ <Text style={styles.listLink} numberOfLines={1}>
372
+ {name}
373
+ </Text>
374
+ </Pressable>
375
+ ) : (
376
+ <Text style={styles.listTitle} numberOfLines={1}>
366
377
  {name}
367
378
  </Text>
368
- </Pressable>
369
- ) : (
370
- <Text style={styles.listTitle} numberOfLines={1}>
371
- {name}
372
- </Text>
373
- );
374
- return (
379
+ );
380
+ return (
381
+ <View
382
+ key={item.skillName}
383
+ style={[styles.listRow, index === 0 ? styles.listRowFirst : null]}
384
+ >
385
+ <Icon name="Sparkles" size={18} color={theme.colors.foregroundMuted} />
386
+ <View style={styles.listMain}>
387
+ {title}
388
+ <FormattedTime
389
+ iso={item.lastUsedAt}
390
+ prefix="Last "
391
+ style={styles.listMeta}
392
+ />
393
+ </View>
394
+ <CountText value={item.total} styles={styles} />
395
+ </View>
396
+ );
397
+ })}
398
+ </View>
399
+ ) : (
400
+ <View style={styles.panel}>
401
+ {mcpItems.map((item, index) => (
375
402
  <View
376
- key={item.skillName}
403
+ key={`${item.server}.${item.tool}`}
377
404
  style={[styles.listRow, index === 0 ? styles.listRowFirst : null]}
378
405
  >
379
- <Icon name="Sparkles" size={18} color={theme.colors.foregroundMuted} />
406
+ <Icon name="Plug" size={18} color={theme.colors.foregroundMuted} />
380
407
  <View style={styles.listMain}>
381
- {title}
382
- <Text style={styles.listMeta}>
383
- Last {formatLocalDateTime(item.lastUsedAt)}
408
+ <Text style={styles.listTitle} numberOfLines={1}>
409
+ {formatDisplayName(`${item.server}.${item.tool}`)}
384
410
  </Text>
411
+ {item.failures > 0 ? (
412
+ <Text style={styles.listMeta}>{item.failures} failed</Text>
413
+ ) : item.lastUsedAt ? (
414
+ <FormattedTime
415
+ iso={item.lastUsedAt}
416
+ prefix="Last "
417
+ style={styles.listMeta}
418
+ />
419
+ ) : (
420
+ <Text style={styles.listMeta}>—</Text>
421
+ )}
385
422
  </View>
386
- <CountText value={item.total} styles={styles} />
423
+ <CountText value={item.count} styles={styles} />
387
424
  </View>
388
- );
389
- })}
390
- </View>
391
- </View>
392
- ) : null}
393
-
394
- {tab === "mcp" ? (
395
- <View style={{ gap: 12 }}>
396
- <Text style={styles.sectionTitle}>MCP</Text>
397
- <View style={styles.panel}>
398
- {mcpItems.map((item, index) => (
399
- <View
400
- key={`${item.server}.${item.tool}`}
401
- style={[styles.listRow, index === 0 ? styles.listRowFirst : null]}
402
- >
403
- <Icon name="Plug" size={18} color={theme.colors.foregroundMuted} />
404
- <View style={styles.listMain}>
405
- <Text style={styles.listTitle} numberOfLines={1}>
406
- {formatDisplayName(`${item.server}.${item.tool}`)}
407
- </Text>
408
- <Text style={styles.listMeta}>
409
- {item.failures > 0
410
- ? `${item.failures} failed`
411
- : item.lastUsedAt
412
- ? `Last ${formatLocalDateTime(item.lastUsedAt)}`
413
- : "—"}
414
- </Text>
415
- </View>
416
- <CountText value={item.count} styles={styles} />
417
- </View>
418
- ))}
419
- </View>
425
+ ))}
426
+ </View>
427
+ )}
420
428
  </View>
421
429
  ) : null}
422
430
  </ScrollView>
@@ -0,0 +1,92 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { setImmediate } from "node:timers/promises";
4
+ import { watchPillDirectory } from "./pill-directory.ts";
5
+
6
+ type Api = Parameters<typeof watchPillDirectory>[0];
7
+ type Update = Parameters<Parameters<Api["subscribe"]>[0]>[0];
8
+
9
+ test("pill directory pages without observation and replays concurrent removal", async () => {
10
+ let listener!: (update: Update) => void;
11
+ const seen = new Set<string>();
12
+ const cursors: unknown[] = [];
13
+ let unsubscribed = false;
14
+ const api = {
15
+ subscribe: (handler: typeof listener) => { listener = handler; return () => { unsubscribed = true; }; },
16
+ list: async (options: { page: { cursor?: string }; subscribe?: unknown }) => {
17
+ assert.equal(options.subscribe, undefined);
18
+ cursors.push(options.page.cursor);
19
+ if (!options.page.cursor) return {
20
+ entries: [{ agent: { id: "first", workspaceId: "w" } }],
21
+ pageInfo: { hasMore: true, nextCursor: "next" },
22
+ };
23
+ listener({ kind: "remove", agentId: "first" } as Update);
24
+ return { entries: [{ agent: { id: "second", workspaceId: "w" } }], pageInfo: { hasMore: false, nextCursor: null } };
25
+ },
26
+ } as unknown as Api;
27
+ const stop = watchPillDirectory(api, (agent) => seen.add(agent.id), (id) => seen.delete(id));
28
+ try {
29
+ await setImmediate();
30
+ assert.deepEqual(cursors, [undefined, "next"]);
31
+ assert.deepEqual([...seen], ["second"]);
32
+ } finally { stop(); }
33
+ assert.equal(unsubscribed, true);
34
+ });
35
+
36
+ test("unload while a directory request is pending cannot register pills", async () => {
37
+ let finish!: (result: unknown) => void;
38
+ let calls = 0;
39
+ const api = {
40
+ subscribe: () => () => {},
41
+ list: () => new Promise((resolve) => { finish = resolve; }),
42
+ } as unknown as Api;
43
+ const stop = watchPillDirectory(api, () => { calls++; }, () => { calls++; });
44
+ stop();
45
+ finish({ entries: [{ agent: { id: "late" } }], pageInfo: { hasMore: false, nextCursor: null } });
46
+ await setImmediate();
47
+ assert.equal(calls, 0);
48
+ });
49
+
50
+ test("polling discovers agents without any directory push", async () => {
51
+ let reads = 0;
52
+ let found!: () => void;
53
+ const discovery = new Promise<void>((resolve) => { found = resolve; });
54
+ const api = {
55
+ subscribe: () => () => {},
56
+ list: async () => ({
57
+ entries: ++reads === 1 ? [] : [{ agent: { id: "new", workspaceId: "w" } }],
58
+ pageInfo: { hasMore: false, nextCursor: null },
59
+ }),
60
+ } as unknown as Api;
61
+ const stop = watchPillDirectory(api, () => found(), () => {}, 1);
62
+ try { await discovery; assert.equal(reads, 2); } finally { stop(); }
63
+ });
64
+
65
+ test("unchanged idle polls do not revive a pill; new activity and re-add still notify", async () => {
66
+ let listener!: (update: Update) => void;
67
+ let reads = 0;
68
+ let thirdRead!: () => void;
69
+ const polled = new Promise<void>(resolve => { thirdRead = resolve; });
70
+ const agent = { id: "a", workspaceId: "w", status: "idle", updatedAt: "old" };
71
+ let callbacks = 0;
72
+ const stop = watchPillDirectory({
73
+ subscribe: (handler: typeof listener) => { listener = handler; return () => {}; },
74
+ list: async () => {
75
+ if (++reads === 3) thirdRead();
76
+ return { entries: [{ agent }], pageInfo: { hasMore: false, nextCursor: null } };
77
+ },
78
+ } as unknown as Api, () => { callbacks++; }, () => {}, 1);
79
+ try {
80
+ await polled;
81
+ await setImmediate();
82
+ assert.equal(callbacks, 1);
83
+ listener({ kind: "upsert", agent } as Update);
84
+ assert.equal(callbacks, 1);
85
+ // Polling can miss the running transition: newer idle timestamp must revive.
86
+ listener({ kind: "upsert", agent: { ...agent, updatedAt: "new" } } as Update);
87
+ assert.equal(callbacks, 2);
88
+ listener({ kind: "remove", agentId: "a" } as Update);
89
+ listener({ kind: "upsert", agent: { ...agent, updatedAt: "new" } } as Update);
90
+ assert.equal(callbacks, 3);
91
+ } finally { stop(); }
92
+ });