@koinzhang/paseo-plugin-activity 0.1.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 (60) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/README.md +85 -0
  3. package/client/activity-heatmap.tsx +72 -14
  4. package/client/formatted-time.tsx +23 -0
  5. package/client/global-surface.tsx +24 -25
  6. package/client/hidden-pill-recheck.test.ts +33 -0
  7. package/client/hidden-pill-recheck.ts +22 -0
  8. package/client/panel.tsx +116 -107
  9. package/client/pill-directory.test.ts +92 -0
  10. package/client/pill-directory.ts +79 -0
  11. package/client/pill.tsx +23 -23
  12. package/client/range.ts +20 -0
  13. package/client/usage-popover.tsx +75 -84
  14. package/client/usage-query.tsx +8 -3
  15. package/client/usage-stats.tsx +7 -5
  16. package/client/use-agent-turn-end.ts +69 -0
  17. package/client/workspace/agent-row.tsx +167 -0
  18. package/client/workspace/agents-section.tsx +330 -0
  19. package/client/workspace/constants.ts +147 -0
  20. package/client/workspace/display-menu.tsx +116 -0
  21. package/client/workspace/filters.ts +30 -0
  22. package/client/workspace/list-host-agents.test.ts +45 -0
  23. package/client/workspace/list-host-agents.ts +90 -0
  24. package/client/workspace/panel.tsx +964 -0
  25. package/client/workspace/rank-section.tsx +131 -0
  26. package/client/workspace/running-indicator.tsx +54 -0
  27. package/client/workspace/status-cache.test.ts +62 -0
  28. package/client/workspace/status-cache.ts +19 -0
  29. package/client/workspace/terminal-preview.test.ts +17 -0
  30. package/client/workspace/terminal-preview.ts +10 -0
  31. package/client/workspace/terminals-section.tsx +155 -0
  32. package/client/workspace-panel.tsx +2 -0
  33. package/index.client.tsx +20 -13
  34. package/index.server.ts +13 -0
  35. package/package.json +9 -3
  36. package/server/agents.test.ts +36 -1
  37. package/server/agents.ts +9 -5
  38. package/server/background-sync.test.ts +14 -3
  39. package/server/background-sync.ts +16 -5
  40. package/server/handlers-query.test.ts +82 -3
  41. package/server/handlers.ts +89 -6
  42. package/server/messages.test.ts +8 -2
  43. package/server/skill-path.ts +3 -20
  44. package/server/store.test.ts +13 -0
  45. package/server/store.ts +2 -2
  46. package/shared/activity.test.ts +22 -12
  47. package/shared/activity.ts +8 -13
  48. package/shared/agent-page-size.test.ts +11 -0
  49. package/shared/agent-title-search.test.ts +28 -0
  50. package/shared/agent-title-search.ts +12 -0
  51. package/shared/explorer-agent-display.ts +30 -0
  52. package/shared/format.test.ts +41 -16
  53. package/shared/format.ts +26 -17
  54. package/shared/home-path.ts +19 -0
  55. package/shared/insights.test.ts +38 -18
  56. package/shared/insights.ts +38 -19
  57. package/shared/list-agent-pages.test.ts +51 -0
  58. package/shared/list-agent-pages.ts +31 -0
  59. package/shared/usage.test.ts +248 -0
  60. package/shared/usage.ts +336 -11
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,32 +315,15 @@ 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() },
313
322
  { label: "File reads", value: (usageSummary.data?.fileReads ?? 0).toLocaleString() },
314
323
  { label: "File writes", value: (usageSummary.data?.fileWrites ?? 0).toLocaleString() },
324
+ { label: "Messages", value: (usageSummary.data?.messageCount ?? 0).toLocaleString() },
315
325
  { label: "Tools explored", value: String(skillItems.length + mcpItems.length) },
316
326
  ]} /> : null}
317
- {tabs.length > 1 ? (
318
- <View style={styles.rangeBar}>
319
- {tabs.map((item) => {
320
- const active = tab === item.id;
321
- return (
322
- <Pressable
323
- key={item.id}
324
- accessibilityRole="tab"
325
- accessibilityState={{ selected: active }}
326
- onPress={() => setTab(item.id)}
327
- style={[styles.rangeSegment, active ? styles.rangeSegmentActive : null]}
328
- >
329
- <Text style={active ? styles.chipTextActive : styles.chipText}>{item.label}</Text>
330
- </Pressable>
331
- );
332
- })}
333
- </View>
334
- ) : null}
335
327
 
336
328
  {loading ? <ActivityIndicator color={theme.colors.accent} /> : null}
337
329
  {error ? (
@@ -341,81 +333,98 @@ export function UsagePanel({ theme, layout, agentId, navigation }: PluginAgentPa
341
333
  ) : null}
342
334
 
343
335
  {!loading && !error && tabs.length === 0 ? (
344
- <View style={{ gap: 12 }}>
345
- {!compact ? <Text style={styles.sectionTitle}>Activity</Text> : null}
346
- <Text style={styles.empty}>No skill or MCP calls yet</Text>
347
- </View>
336
+ <Text style={styles.empty}>No skill or MCP calls yet</Text>
348
337
  ) : null}
349
338
 
350
- {tab === "skills" ? (
339
+ {tab ? (
351
340
  <View style={{ gap: 12 }}>
352
- <Text style={styles.sectionTitle}>Skills</Text>
353
- <View style={styles.panel}>
354
- {skillItems.map((item, index) => {
355
- const name = formatDisplayName(item.skillName);
356
- const title = item.skillPath ? (
357
- <Pressable
358
- accessibilityRole="link"
359
- accessibilityLabel={`Open ${name} SKILL.md`}
360
- onPress={() =>
361
- setSkillDetail({ skillName: item.skillName, path: item.skillPath! })
362
- }
363
- >
364
- <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}>
365
377
  {name}
366
378
  </Text>
367
- </Pressable>
368
- ) : (
369
- <Text style={styles.listTitle} numberOfLines={1}>
370
- {name}
371
- </Text>
372
- );
373
- 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) => (
374
402
  <View
375
- key={item.skillName}
403
+ key={`${item.server}.${item.tool}`}
376
404
  style={[styles.listRow, index === 0 ? styles.listRowFirst : null]}
377
405
  >
378
- <Icon name="Sparkles" size={18} color={theme.colors.foregroundMuted} />
406
+ <Icon name="Plug" size={18} color={theme.colors.foregroundMuted} />
379
407
  <View style={styles.listMain}>
380
- {title}
381
- <Text style={styles.listMeta}>
382
- Last {formatLocalDateTime(item.lastUsedAt)}
408
+ <Text style={styles.listTitle} numberOfLines={1}>
409
+ {formatDisplayName(`${item.server}.${item.tool}`)}
383
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
+ )}
384
422
  </View>
385
- <CountText value={item.total} styles={styles} />
423
+ <CountText value={item.count} styles={styles} />
386
424
  </View>
387
- );
388
- })}
389
- </View>
390
- </View>
391
- ) : null}
392
-
393
- {tab === "mcp" ? (
394
- <View style={{ gap: 12 }}>
395
- <Text style={styles.sectionTitle}>MCP</Text>
396
- <View style={styles.panel}>
397
- {mcpItems.map((item, index) => (
398
- <View
399
- key={`${item.server}.${item.tool}`}
400
- style={[styles.listRow, index === 0 ? styles.listRowFirst : null]}
401
- >
402
- <Icon name="Plug" size={18} color={theme.colors.foregroundMuted} />
403
- <View style={styles.listMain}>
404
- <Text style={styles.listTitle} numberOfLines={1}>
405
- {formatDisplayName(`${item.server}.${item.tool}`)}
406
- </Text>
407
- <Text style={styles.listMeta}>
408
- {item.failures > 0
409
- ? `${item.failures} failed`
410
- : item.lastUsedAt
411
- ? `Last ${formatLocalDateTime(item.lastUsedAt)}`
412
- : "—"}
413
- </Text>
414
- </View>
415
- <CountText value={item.count} styles={styles} />
416
- </View>
417
- ))}
418
- </View>
425
+ ))}
426
+ </View>
427
+ )}
419
428
  </View>
420
429
  ) : null}
421
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
+ });
@@ -0,0 +1,79 @@
1
+ import type { PluginClientContext } from "@getpaseo/plugin/client";
2
+ import { listAllAgentPages } from "../shared/list-agent-pages.ts";
3
+
4
+ type AgentsApi = PluginClientContext["paseo"]["agents"];
5
+ type Update = Parameters<Parameters<AgentsApi["subscribe"]>[0]>[0];
6
+ type Agent = Extract<Update, { kind: "upsert" }>["agent"];
7
+
8
+ /** 0.8 has one shared directory slot. Plain paged reads own our fallback, never that slot. */
9
+ export function watchPillDirectory(
10
+ agents: AgentsApi,
11
+ onAgent: (agent: Agent) => void,
12
+ onRemove: (agentId: string) => void,
13
+ intervalMs = 15_000,
14
+ onPolled?: (agent: Agent) => void,
15
+ ): () => void {
16
+ let disposed = false;
17
+ let timer: ReturnType<typeof setTimeout> | undefined;
18
+ let pending: Update[] | null = null;
19
+ let known = new Set<string>();
20
+ const versions = new Map<string, string>();
21
+ function publish(agent: Agent) {
22
+ const version = JSON.stringify([agent.workspaceId, agent.status, agent.updatedAt,
23
+ agent.lastUserMessageAt, agent.activeTurn?.turnId]);
24
+ if (versions.get(agent.id) === version) return;
25
+ versions.set(agent.id, version);
26
+ onAgent(agent);
27
+ }
28
+ function remove(id: string) {
29
+ versions.delete(id);
30
+ onRemove(id);
31
+ }
32
+ function apply(update: Update) {
33
+ if (update.kind === "remove") {
34
+ known.delete(update.agentId);
35
+ remove(update.agentId);
36
+ } else {
37
+ known.add(update.agent.id);
38
+ publish(update.agent);
39
+ }
40
+ }
41
+ // Opportunistic acceleration only; correctness does not depend on host observation.
42
+ const unsubscribe = agents.subscribe((update) => {
43
+ if (disposed) return;
44
+ pending?.push(update);
45
+ apply(update);
46
+ });
47
+ async function sync() {
48
+ pending = [];
49
+ try {
50
+ const entries = await listAllAgentPages((cursor) => agents.list({
51
+ page: { limit: 200, ...(cursor ? { cursor } : {}) },
52
+ }));
53
+ if (disposed) return;
54
+ const snapshot = new Map(entries.map(({ agent }) => [agent.id, agent]));
55
+ // Pushes received during pagination are newer than its snapshot.
56
+ for (const update of pending) {
57
+ if (update.kind === "remove") snapshot.delete(update.agentId);
58
+ else snapshot.set(update.agent.id, update.agent);
59
+ }
60
+ for (const id of known) if (!snapshot.has(id)) remove(id);
61
+ known = new Set(snapshot.keys());
62
+ for (const agent of snapshot.values()) {
63
+ publish(agent);
64
+ onPolled?.(agent);
65
+ }
66
+ } catch (error) {
67
+ if (!disposed) console.error("[activity] could not sync composer pills", error);
68
+ } finally {
69
+ pending = null;
70
+ if (!disposed) timer = setTimeout(() => void sync(), intervalMs);
71
+ }
72
+ }
73
+ void sync();
74
+ return () => {
75
+ disposed = true;
76
+ unsubscribe();
77
+ clearTimeout(timer);
78
+ };
79
+ }
package/client/pill.tsx CHANGED
@@ -1,3 +1,6 @@
1
+ import { createHiddenPillRecheck } from "./hidden-pill-recheck.ts";
2
+ import { writePillDataCache } from "./pill-data-cache.ts";
3
+ import { watchPillDirectory } from "./pill-directory.ts";
1
4
  import {
2
5
  type PluginButtonContentProps,
3
6
  type PluginButtonIconProps,
@@ -6,7 +9,7 @@ import {
6
9
  } from "@getpaseo/plugin/client";
7
10
  import { Icon } from "@getpaseo/plugin/client/react-native";
8
11
  import { useEffect, useRef } from "react";
9
- import { formatUsagePillLabel } from "../shared/usage.ts";
12
+ import { formatUsagePillLabel, usageSkillsByNameRpc, usageMcpByToolRpc } from "../shared/usage.ts";
10
13
  import { useUsagePillData, clearPillDataCache } from "./usage-query.tsx";
11
14
  import { UsagePopover, type SkillDetail } from "./usage-popover.tsx";
12
15
  import { requestOpenSkillInPanel } from "./pending-skill.ts";
@@ -23,6 +26,7 @@ const EMPTY_GRACE_MS_RECHECK = 4_000;
23
26
 
24
27
  type PillEntry = {
25
28
  registration?: PluginButtonRegistration;
29
+ recheck?: () => Promise<void>;
26
30
  /** Host unmounted the icon after a settled empty hide. */
27
31
  hidden: boolean;
28
32
  /** Already completed one empty grace → hide cycle for this agent. */
@@ -161,6 +165,16 @@ export function contributePills(client: PluginClientContext) {
161
165
  },
162
166
  });
163
167
  pills.set(agentId, entry);
168
+ entry.recheck = createHiddenPillRecheck(async () => {
169
+ const [skills, mcp] = await Promise.all([
170
+ client.rpc(usageSkillsByNameRpc, { agentId }),
171
+ client.rpc(usageMcpByToolRpc, { agentId }),
172
+ ]);
173
+ return { skills: skills.items, mcpTools: mcp.items };
174
+ }, () => pills.get(agentId) === entry && entry.hidden, (data) => {
175
+ writePillDataCache(agentId, data);
176
+ reviveHiddenPill(agentId);
177
+ });
164
178
  }
165
179
 
166
180
  function removePill(agentId: string) {
@@ -177,32 +191,18 @@ export function contributePills(client: PluginClientContext) {
177
191
  entry.registration.update({ label: TITLE, visible: true });
178
192
  }
179
193
 
180
- const unsubscribe = client.paseo.agents.subscribe((update) => {
181
- if (update.kind === "remove") {
182
- removePill(update.agentId);
183
- return;
184
- }
185
- const { id, workspaceId, status } = update.agent;
194
+ const unsubscribe = watchPillDirectory(client.paseo.agents, (agent) => {
195
+ const { id, workspaceId, status } = agent;
186
196
  if (!workspaceId) return;
187
- if (pills.has(id)) {
188
- // turn_ended ingest races with idle; remount hidden pills so they can catch up.
189
- if (status === "idle") reviveHiddenPill(id);
190
- return;
191
- }
192
197
  addPill(id, workspaceId);
198
+ // A read/push is a refresh hint, not proof of turn completion.
199
+ if (status === "idle") reviveHiddenPill(id);
200
+ }, removePill, 15_000, (agent) => {
201
+ // Ingest can finish after the empty grace period without another agent update.
202
+ // Keep the fallback query, but only make the pill visible when data exists.
203
+ if (agent.status === "idle") void pills.get(agent.id)?.recheck?.();
193
204
  });
194
205
 
195
- client.paseo.agents
196
- .list()
197
- .then((result) => {
198
- result.entries.forEach(({ agent }) => {
199
- if (agent.workspaceId) addPill(agent.id, agent.workspaceId);
200
- });
201
- })
202
- .catch((error: unknown) => {
203
- console.error("[activity] could not seed composer pills", error);
204
- });
205
-
206
206
  return () => {
207
207
  unsubscribe();
208
208
  pills.forEach((entry) => entry.registration?.remove());
@@ -0,0 +1,20 @@
1
+ export type RangeId = "all" | "7d" | "30d" | "today";
2
+
3
+ export const RANGE_OPTIONS: ReadonlyArray<{ id: RangeId; label: string }> = [
4
+ { id: "all", label: "All time" },
5
+ { id: "today", label: "Today" },
6
+ { id: "7d", label: "7 days" },
7
+ { id: "30d", label: "30 days" },
8
+ ];
9
+
10
+ /** Inclusive lower bound ISO timestamp for a range chip; undefined = all time. */
11
+ export function rangeFrom(id: RangeId): string | undefined {
12
+ if (id === "all") return undefined;
13
+ if (id === "today") {
14
+ const d = new Date();
15
+ d.setHours(0, 0, 0, 0);
16
+ return d.toISOString();
17
+ }
18
+ const days = id === "7d" ? 7 : 30;
19
+ return new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();
20
+ }