@koinzhang/paseo-plugin-activity 0.2.0 → 0.4.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 (55) hide show
  1. package/CHANGELOG.md +50 -1
  2. package/README.md +26 -11
  3. package/client/attention-agents.test.ts +94 -0
  4. package/client/attention-agents.ts +67 -0
  5. package/client/attention-pill.tsx +254 -0
  6. package/client/attention-popover.tsx +161 -0
  7. package/client/attention-status-store.ts +47 -0
  8. package/client/formatted-time.tsx +23 -0
  9. package/client/global-surface.tsx +3 -1
  10. package/client/hidden-pill-recheck.test.ts +33 -0
  11. package/client/hidden-pill-recheck.ts +22 -0
  12. package/client/latest-user-message.test.ts +34 -0
  13. package/client/latest-user-message.ts +96 -0
  14. package/client/open-agent.ts +32 -0
  15. package/client/panel.tsx +117 -107
  16. package/client/pill-directory.test.ts +92 -0
  17. package/client/pill-directory.ts +79 -0
  18. package/client/pill.tsx +23 -23
  19. package/client/usage-popover.tsx +75 -84
  20. package/client/usage-query.tsx +8 -3
  21. package/client/usage-stats.tsx +2 -2
  22. package/client/use-agent-turn-end.ts +72 -0
  23. package/client/use-latest-user-message.ts +15 -0
  24. package/client/use-workspace-agent-statuses.ts +47 -0
  25. package/client/workspace/agent-live-status-sync.tsx +103 -0
  26. package/client/workspace/agent-row.tsx +105 -28
  27. package/client/workspace/agents-section.tsx +92 -17
  28. package/client/workspace/constants.test.ts +66 -0
  29. package/client/workspace/constants.ts +66 -4
  30. package/client/workspace/filters.test.ts +59 -0
  31. package/client/workspace/filters.ts +11 -2
  32. package/client/workspace/list-host-agents.test.ts +103 -0
  33. package/client/workspace/list-host-agents.ts +113 -23
  34. package/client/workspace/panel.tsx +192 -12
  35. package/client/workspace/rank-section.tsx +36 -26
  36. package/client/workspace/running-indicator.tsx +54 -0
  37. package/client/workspace/status-cache.test.ts +62 -0
  38. package/client/workspace/status-cache.ts +23 -0
  39. package/client/workspace/terminal-preview.test.ts +17 -0
  40. package/client/workspace/terminal-preview.ts +10 -0
  41. package/client/workspace/terminals-section.tsx +155 -0
  42. package/index.client.tsx +7 -1
  43. package/index.server.ts +2 -0
  44. package/package.json +3 -3
  45. package/server/agents.test.ts +16 -0
  46. package/server/agents.ts +7 -4
  47. package/server/handlers-query.test.ts +24 -3
  48. package/server/handlers.ts +17 -5
  49. package/server/skill-path.ts +3 -20
  50. package/shared/explorer-agent-display.ts +1 -1
  51. package/shared/format.test.ts +35 -31
  52. package/shared/format.ts +21 -36
  53. package/shared/home-path.ts +19 -0
  54. package/shared/usage.test.ts +8 -2
  55. package/shared/usage.ts +16 -0
package/CHANGELOG.md CHANGED
@@ -7,6 +7,53 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.4.0] - 2026-09-20
11
+
12
+ Last release that supports Paseo **0.8.0**. Later versions require Paseo **>= 0.9.0**.
13
+
14
+ ### Added
15
+
16
+ - Composer **Needs attention** pill (same workspace): one shared entry for other agents with finished / permission / error attention; click always opens the same popover list (Explorer-style rows); icon tint follows aggregate priority.
17
+ - Explorer Agents rows show the direct subagent count at the bottom-right of the bot icon when the local registry has children (`parentAgentId`); the count follows the Agents Status filter (Active / Archived / both). Host list also resolves the legacy `paseo.parent-agent-id` label. The running spinner keeps priority on that corner.
18
+ - Explorer Agents **Show → Prompt**: optional row meta for the latest user message preview (host timeline; same path as the attention pill).
19
+
20
+ ### Changed
21
+
22
+ - Attention pill no longer direct-jumps when only one peer needs attention — always popover for finished / permission / error.
23
+ - Attention popover row meta shows the latest user message preview (host timeline tail; not stored in usage.db) instead of finished / needs-attention labels.
24
+ - Attention pill icon switches with attention kind: `Bell` for permission, `CircleAlert` for error, `CircleCheck` for finished (priority permission > error > finished when mixed).
25
+
26
+ ### Fixed
27
+
28
+ - Explorer Agents lifecycle **Closed** updates near-real-time via host `useAgent` snapshots (no `list({ subscribe })`); directory `remove` keeps the row as Closed instead of dropping status; missing `workspaceId` on pushes still merges when the agent is already tracked.
29
+ - Attention pill icon/list now follow the same `agents.subscribe` in-memory store as visibility (no separate 15s react-query path), so tint updates with pushes; partial directory pushes keep prior permission/attention fields; background polls no longer disable the pill.
30
+ - Attention pill row open uses the existing `navigation.openAgent` bridge (registered by Agent / Workspace / Global panels); no `openPanel("usage")` fallback. Preview fetch tries projected then canonical timeline tail.
31
+ - Attention pill visibility is synced from the contribute layer (directory + subscribe + 15s poll). Starting at `visible: false` previously unmounted the icon, so the show effect never ran and the pill stayed hidden even when peers needed attention.
32
+
33
+ ## [0.3.0] - 2026-09-19
34
+
35
+ ### Added
36
+
37
+ - 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.
38
+ - 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.
39
+ - 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.
40
+ - 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.
41
+ - 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).
42
+ - 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.
43
+ - 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.
44
+
45
+ ### Changed
46
+
47
+ - Agent Activity panel and composer popover: Skills / MCP detail uses the same header toggle icon pattern as Workspace rank (no tab strip).
48
+ - Agent Activity panel KPIs use dense `UsageStats` (aligned with Workspace).
49
+ - Workspace skills / MCP rank toggle is hidden when only one kind has data.
50
+
51
+ ### Fixed
52
+
53
+ - 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.
54
+ - In-flight status polls are cancelled before applying a newer directory push, so stale responses cannot overwrite live agent state.
55
+ - Skill path resolution refreshes empty handles and falls back to home roots when project cwd lookup fails.
56
+
10
57
  ## [0.2.0] - 2026-09-19
11
58
 
12
59
  ### Added
@@ -51,6 +98,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
51
98
  - Command Center entries: open panels and export a markdown usage report.
52
99
  - Plugin renamed from `tool-usage` to `activity`, migrating the old data directory automatically.
53
100
 
54
- [Unreleased]: https://github.com/koinzhang/paseo-plugins/compare/activity-v0.2.0...HEAD
101
+ [Unreleased]: https://github.com/koinzhang/paseo-plugins/compare/activity-v0.4.0...HEAD
102
+ [0.4.0]: https://github.com/koinzhang/paseo-plugins/releases/tag/activity-v0.4.0
103
+ [0.3.0]: https://github.com/koinzhang/paseo-plugins/releases/tag/activity-v0.3.0
55
104
  [0.2.0]: https://github.com/koinzhang/paseo-plugins/releases/tag/activity-v0.2.0
56
105
  [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 Activity pill; **Needs attention** pill jumps to other same-workspace finished/permission/error sessions |
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 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
+ - **Command Center** — Activity · Workspace Activity · Agent Activity
20
33
 
21
34
  ## Data
22
35
 
@@ -24,7 +37,7 @@ Everything lives on the daemon machine in `~/.paseo/plugin-data/activity/` (SQLi
24
37
 
25
38
  ## Install
26
39
 
27
- Requires Paseo >= 0.8.0.
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.
28
41
 
29
42
  From Git (Paseo 0.8 and later):
30
43
 
@@ -32,10 +45,11 @@ From Git (Paseo 0.8 and later):
32
45
  paseo plugin add koinzhang/paseo-plugins --path activity
33
46
  ```
34
47
 
35
- From npm (Paseo 0.9 and later; this is the source paseo.cafe hands to Paseo 0.9+):
48
+ From npm (Paseo 0.9 and later; this is the source paseo.cafe hands to Paseo 0.9+). Pin `0.4.0` on Paseo 0.8:
36
49
 
37
50
  ```bash
38
51
  paseo plugin install npm:@koinzhang/paseo-plugin-activity
52
+ # Paseo 0.8: npm:@koinzhang/paseo-plugin-activity@0.4.0
39
53
  ```
40
54
 
41
55
  After source changes, reload and check status:
@@ -48,9 +62,10 @@ paseo plugin ls
48
62
 
49
63
  ## Limitations
50
64
 
51
- - Analytics are local to each daemon: every machine keeps its own database, and there is no cross-host aggregation.
65
+ - Analytics and the agent registry are local to each daemon: every machine keeps its own database, and there is no cross-host aggregation.
52
66
  - Numbers are reconstructed from the Paseo timeline; items that do not report a model or skill cannot be attributed for that dimension.
53
67
  - Skill classification is heuristic (exact / inferred / low confidence); check the tier before trusting a count.
68
+ - Workspace Activity focuses on agent operations for the current workspace; heatmap / provider / model breakdowns stay on the global sidebar.
54
69
 
55
70
  ## Development
56
71
 
@@ -64,7 +79,7 @@ This plugin is spec-driven: read [specs/README.md](./specs/README.md) before cod
64
79
 
65
80
  ## Publish
66
81
 
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).
82
+ Release history: [CHANGELOG.md](./CHANGELOG.md) (current **0.4.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
83
 
69
84
  ## License
70
85
 
@@ -0,0 +1,94 @@
1
+ import assert from "node:assert/strict";
2
+ import { describe, it } from "node:test";
3
+ import {
4
+ attentionPillIconName,
5
+ attentionPillTint,
6
+ filterAttentionAgents,
7
+ } from "./attention-agents.ts";
8
+ import type { AgentStatusInfo } from "./workspace/constants.ts";
9
+
10
+ function status(partial: Partial<AgentStatusInfo>): AgentStatusInfo {
11
+ return {
12
+ rank: 0,
13
+ updatedAt: null,
14
+ status: null,
15
+ permissionCount: 0,
16
+ requiresAttention: false,
17
+ attentionReason: null,
18
+ parentAgentId: null,
19
+ ...partial,
20
+ };
21
+ }
22
+
23
+ describe("filterAttentionAgents", () => {
24
+ it("keeps finished, permission, and error; drops current and idle", () => {
25
+ const statuses = {
26
+ self: status({ requiresAttention: true, attentionReason: "finished" }),
27
+ done: status({
28
+ requiresAttention: true,
29
+ attentionReason: "finished",
30
+ updatedAt: "2026-09-20T10:00:00Z",
31
+ }),
32
+ wait: status({
33
+ permissionCount: 1,
34
+ updatedAt: "2026-09-20T09:00:00Z",
35
+ }),
36
+ fail: status({
37
+ status: "error",
38
+ requiresAttention: true,
39
+ attentionReason: "error",
40
+ updatedAt: "2026-09-20T08:00:00Z",
41
+ }),
42
+ idle: status({ status: "idle" }),
43
+ };
44
+ const items = filterAttentionAgents(statuses, "self");
45
+ assert.deepEqual(
46
+ items.map((item) => item.agentId),
47
+ ["wait", "fail", "done"],
48
+ );
49
+ assert.deepEqual(
50
+ items.map((item) => item.kind),
51
+ ["permission", "error", "finished"],
52
+ );
53
+ });
54
+
55
+ it("returns empty when statuses missing", () => {
56
+ assert.deepEqual(filterAttentionAgents(undefined, "a"), []);
57
+ });
58
+ });
59
+
60
+ describe("attentionPillTint", () => {
61
+ it("prefers permission, then error, then finished", () => {
62
+ assert.equal(attentionPillTint([]), null);
63
+ assert.equal(
64
+ attentionPillTint([
65
+ { agentId: "a", kind: "finished", permissionCount: 0, updatedAt: null },
66
+ ]),
67
+ "finished",
68
+ );
69
+ assert.equal(
70
+ attentionPillTint([
71
+ { agentId: "a", kind: "finished", permissionCount: 0, updatedAt: null },
72
+ { agentId: "b", kind: "error", permissionCount: 0, updatedAt: null },
73
+ ]),
74
+ "error",
75
+ );
76
+ assert.equal(
77
+ attentionPillTint([
78
+ { agentId: "a", kind: "finished", permissionCount: 0, updatedAt: null },
79
+ { agentId: "b", kind: "error", permissionCount: 0, updatedAt: null },
80
+ { agentId: "c", kind: "permission", permissionCount: 1, updatedAt: null },
81
+ ]),
82
+ "permission",
83
+ );
84
+ });
85
+ });
86
+
87
+ describe("attentionPillIconName", () => {
88
+ it("maps tint to lucide names", () => {
89
+ assert.equal(attentionPillIconName(null), "Bell");
90
+ assert.equal(attentionPillIconName("permission"), "Bell");
91
+ assert.equal(attentionPillIconName("error"), "CircleAlert");
92
+ assert.equal(attentionPillIconName("finished"), "CircleCheck");
93
+ });
94
+ });
@@ -0,0 +1,67 @@
1
+ import {
2
+ attentionKind,
3
+ type AgentAttentionKind,
4
+ type AgentStatusInfo,
5
+ } from "./workspace/constants.ts";
6
+
7
+ export type AttentionAgentItem = {
8
+ agentId: string;
9
+ kind: NonNullable<AgentAttentionKind>;
10
+ permissionCount: number;
11
+ updatedAt: string | null;
12
+ };
13
+
14
+ const KIND_ORDER: Record<NonNullable<AgentAttentionKind>, number> = {
15
+ permission: 0,
16
+ error: 1,
17
+ finished: 2,
18
+ };
19
+
20
+ /** Same-workspace interrupt targets: finished / permission / error; never current. */
21
+ export function filterAttentionAgents(
22
+ statuses: Record<string, AgentStatusInfo> | undefined,
23
+ currentAgentId: string,
24
+ ): AttentionAgentItem[] {
25
+ if (!statuses) return [];
26
+ const items: AttentionAgentItem[] = [];
27
+ for (const [agentId, info] of Object.entries(statuses)) {
28
+ if (agentId === currentAgentId) continue;
29
+ const kind = attentionKind(info);
30
+ if (kind == null) continue;
31
+ items.push({
32
+ agentId,
33
+ kind,
34
+ permissionCount: info.permissionCount,
35
+ updatedAt: info.updatedAt,
36
+ });
37
+ }
38
+ return items.sort(compareAttentionAgents);
39
+ }
40
+
41
+ function compareAttentionAgents(a: AttentionAgentItem, b: AttentionAgentItem): number {
42
+ const byKind = KIND_ORDER[a.kind] - KIND_ORDER[b.kind];
43
+ if (byKind !== 0) return byKind;
44
+ const aAt = a.updatedAt ?? "";
45
+ const bAt = b.updatedAt ?? "";
46
+ if (aAt !== bAt) return aAt < bAt ? 1 : -1;
47
+ return a.agentId.localeCompare(b.agentId);
48
+ }
49
+
50
+ /** Pill icon tint: permission > error > finished. */
51
+ export function attentionPillTint(
52
+ items: ReadonlyArray<AttentionAgentItem>,
53
+ ): NonNullable<AgentAttentionKind> | null {
54
+ if (items.length === 0) return null;
55
+ if (items.some((item) => item.kind === "permission")) return "permission";
56
+ if (items.some((item) => item.kind === "error")) return "error";
57
+ return "finished";
58
+ }
59
+
60
+ /** Lucide name: Bell = permission, CircleAlert = error, CircleCheck = finished. */
61
+ export function attentionPillIconName(
62
+ tint: NonNullable<AgentAttentionKind> | null,
63
+ ): "Bell" | "CircleAlert" | "CircleCheck" {
64
+ if (tint === "finished") return "CircleCheck";
65
+ if (tint === "error") return "CircleAlert";
66
+ return "Bell";
67
+ }
@@ -0,0 +1,254 @@
1
+ import {
2
+ type PluginButtonIconProps,
3
+ type PluginButtonRegistration,
4
+ type PluginClientContext,
5
+ } from "@getpaseo/plugin/client";
6
+ import { Icon } from "@getpaseo/plugin/client/react-native";
7
+ import { useMemo } from "react";
8
+ import {
9
+ attentionPillIconName,
10
+ attentionPillTint,
11
+ filterAttentionAgents,
12
+ type AttentionAgentItem,
13
+ } from "./attention-agents.ts";
14
+ import { AttentionPopover } from "./attention-popover.tsx";
15
+ import {
16
+ clearAttentionStatuses,
17
+ getAttentionStatuses,
18
+ publishAttentionStatuses,
19
+ useAttentionStatuses,
20
+ } from "./attention-status-store.ts";
21
+ import { watchPillDirectory } from "./pill-directory.ts";
22
+ import {
23
+ applyAgentStatusUpdate,
24
+ loadWorkspaceAgentStatuses,
25
+ type HostAgentUpdate,
26
+ } from "./workspace/list-host-agents.ts";
27
+ import type { AgentStatusInfo } from "./workspace/constants.ts";
28
+
29
+ const TITLE = "Needs attention";
30
+ const PILL_ID = "attention";
31
+ /** Completeness backup only — live path is agents.subscribe → store → icon. */
32
+ const SYNC_MS = 15_000;
33
+
34
+ type PillEntry = {
35
+ registration?: PluginButtonRegistration;
36
+ workspaceId: string;
37
+ /** Last applied sync signature (avoid no-op updates that close surfaces). */
38
+ signature: string;
39
+ };
40
+
41
+ function attentionSignature(
42
+ items: ReadonlyArray<{ agentId: string; kind: string; permissionCount: number }>,
43
+ ): string {
44
+ if (items.length === 0) return "0";
45
+ return items.map((i) => `${i.agentId}:${i.kind}:${i.permissionCount}`).join("|");
46
+ }
47
+
48
+ /**
49
+ * Composer pill for other same-workspace agents needing attention.
50
+ *
51
+ * Live updates: `agents.subscribe` → in-memory store → pill visibility + icon tint.
52
+ * 15s poll is completeness only. Icon reads the same store (not a separate 15s query).
53
+ */
54
+ export function contributeAttentionPills(client: PluginClientContext): () => void {
55
+ const pills = new Map<string, PillEntry>();
56
+ const inflight = new Map<string, Promise<void>>();
57
+ let disposed = false;
58
+ let timer: ReturnType<typeof setTimeout> | undefined;
59
+
60
+ function setWorkspacePillsDisabled(workspaceId: string, disabled: boolean) {
61
+ for (const entry of pills.values()) {
62
+ if (entry.workspaceId !== workspaceId) continue;
63
+ entry.registration?.update({ disabled });
64
+ }
65
+ }
66
+
67
+ function applyPill(
68
+ agentId: string,
69
+ entry: PillEntry,
70
+ statuses: Record<string, AgentStatusInfo> | undefined,
71
+ ) {
72
+ const pill = entry.registration;
73
+ if (!pill) return;
74
+ const items = filterAttentionAgents(statuses, agentId);
75
+ const tint = attentionPillTint(items);
76
+ const signature = `${attentionSignature(items)}:${tint ?? ""}`;
77
+ if (entry.signature === signature) return;
78
+ entry.signature = signature;
79
+
80
+ if (items.length === 0) {
81
+ pill.update({ visible: false, label: TITLE, disabled: false });
82
+ return;
83
+ }
84
+
85
+ // One shared pill for finished / permission / error; always the same popover list.
86
+ pill.update({
87
+ visible: true,
88
+ label: String(items.length),
89
+ title: TITLE,
90
+ disabled: false,
91
+ behavior: {
92
+ kind: "popover",
93
+ Content: AttentionPopover,
94
+ },
95
+ });
96
+ }
97
+
98
+ function applyWorkspace(workspaceId: string, statuses: Record<string, AgentStatusInfo>) {
99
+ publishAttentionStatuses(workspaceId, statuses);
100
+ for (const [agentId, entry] of pills) {
101
+ if (entry.workspaceId !== workspaceId) continue;
102
+ applyPill(agentId, entry, statuses);
103
+ }
104
+ }
105
+
106
+ function syncWorkspace(workspaceId: string): Promise<void> {
107
+ const existing = inflight.get(workspaceId);
108
+ if (existing) return existing;
109
+ const firstLoad = getAttentionStatuses(workspaceId) == null;
110
+ // Only block clicks on the cold first fetch — background polls stay interactive.
111
+ if (firstLoad) setWorkspacePillsDisabled(workspaceId, true);
112
+ const run = (async () => {
113
+ try {
114
+ const statuses = await loadWorkspaceAgentStatuses(client.paseo, workspaceId, null);
115
+ if (disposed) return;
116
+ applyWorkspace(workspaceId, statuses);
117
+ } catch (error) {
118
+ if (!disposed) console.error("[activity] attention pill sync failed", workspaceId, error);
119
+ } finally {
120
+ inflight.delete(workspaceId);
121
+ if (!disposed && firstLoad) setWorkspacePillsDisabled(workspaceId, false);
122
+ }
123
+ })();
124
+ inflight.set(workspaceId, run);
125
+ return run;
126
+ }
127
+
128
+ function syncAllWorkspaces() {
129
+ const ids = new Set<string>();
130
+ for (const entry of pills.values()) ids.add(entry.workspaceId);
131
+ for (const workspaceId of ids) void syncWorkspace(workspaceId);
132
+ }
133
+
134
+ function scheduleSync() {
135
+ clearTimeout(timer);
136
+ if (disposed) return;
137
+ timer = setTimeout(() => {
138
+ syncAllWorkspaces();
139
+ scheduleSync();
140
+ }, SYNC_MS);
141
+ }
142
+
143
+ function createPillIcon(agentId: string) {
144
+ return function AttentionPillIcon({
145
+ size,
146
+ color,
147
+ theme,
148
+ workspaceId,
149
+ }: PluginButtonIconProps) {
150
+ // Same push-driven store as contribute visibility — not the 15s Explorer query.
151
+ const statuses = useAttentionStatuses(workspaceId);
152
+ const items = useMemo(
153
+ () => filterAttentionAgents(statuses, agentId),
154
+ [statuses, agentId],
155
+ );
156
+ const tint = attentionPillTint(items);
157
+ const iconColor =
158
+ tint === "permission"
159
+ ? theme.colors.statusWarning
160
+ : tint === "error"
161
+ ? theme.colors.statusDanger
162
+ : tint === "finished"
163
+ ? theme.colors.statusSuccess
164
+ : color;
165
+ return <Icon name={attentionPillIconName(tint)} size={size} color={iconColor} />;
166
+ };
167
+ }
168
+
169
+ function addPill(agentId: string, workspaceId: string) {
170
+ if (pills.has(agentId)) return;
171
+ const entry: PillEntry = { workspaceId, signature: "" };
172
+ entry.registration = client.addComposerPill({
173
+ id: PILL_ID,
174
+ workspaceId,
175
+ agentId,
176
+ button: {
177
+ title: TITLE,
178
+ label: TITLE,
179
+ visible: false,
180
+ icon: createPillIcon(agentId),
181
+ behavior: {
182
+ kind: "action",
183
+ onPress() {
184
+ /* replaced on first successful sync with peers */
185
+ },
186
+ },
187
+ },
188
+ });
189
+ pills.set(agentId, entry);
190
+ const cached = getAttentionStatuses(workspaceId);
191
+ if (cached) applyPill(agentId, entry, cached);
192
+ else void syncWorkspace(workspaceId);
193
+ }
194
+
195
+ function removePill(agentId: string) {
196
+ pills.get(agentId)?.registration?.remove();
197
+ pills.delete(agentId);
198
+ }
199
+
200
+ function onHostUpdate(update: HostAgentUpdate) {
201
+ if (disposed) return;
202
+ if (update.kind === "remove") {
203
+ for (const workspaceId of [...new Set(
204
+ [...pills.values()].map((entry) => entry.workspaceId),
205
+ )]) {
206
+ const map = getAttentionStatuses(workspaceId);
207
+ if (!map || !(update.agentId in map)) continue;
208
+ const next = { ...map };
209
+ delete next[update.agentId];
210
+ applyWorkspace(workspaceId, next);
211
+ }
212
+ return;
213
+ }
214
+ const workspaceId = update.agent.workspaceId;
215
+ if (!workspaceId) return;
216
+ const map = getAttentionStatuses(workspaceId);
217
+ if (!map) {
218
+ // Apply the push immediately so icon/visibility update without waiting for full poll.
219
+ const next: Record<string, AgentStatusInfo> = {};
220
+ applyAgentStatusUpdate(next, workspaceId, update);
221
+ applyWorkspace(workspaceId, next);
222
+ void syncWorkspace(workspaceId);
223
+ return;
224
+ }
225
+ const next = { ...map };
226
+ applyAgentStatusUpdate(next, workspaceId, update);
227
+ applyWorkspace(workspaceId, next);
228
+ }
229
+
230
+ const unsubscribeDir = watchPillDirectory(client.paseo.agents, (agent) => {
231
+ const { id, workspaceId } = agent;
232
+ if (!workspaceId) return;
233
+ addPill(id, workspaceId);
234
+ }, removePill);
235
+
236
+ const unsubscribePush = client.paseo.agents.subscribe((update) => {
237
+ onHostUpdate(update as HostAgentUpdate);
238
+ });
239
+
240
+ scheduleSync();
241
+
242
+ return () => {
243
+ disposed = true;
244
+ clearTimeout(timer);
245
+ unsubscribeDir();
246
+ unsubscribePush();
247
+ pills.forEach((entry) => entry.registration?.remove());
248
+ pills.clear();
249
+ clearAttentionStatuses();
250
+ };
251
+ }
252
+
253
+ /** Exported for tests / popover typing only. */
254
+ export type { AttentionAgentItem };