@koinzhang/paseo-plugin-activity 0.4.0 → 0.5.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.
package/CHANGELOG.md CHANGED
@@ -5,7 +5,22 @@ 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.5.0] - 2026-09-20
9
+
10
+ Requires Paseo **>= 0.9.0-beta.2**.
11
+
12
+ ### Changed
13
+
14
+ - Pin the plugin SDK to `0.9.0-beta.2` and use independent, API-owned directory observations, shared within each entry/surface API.
15
+ - Reconcile all pages on bootstrap/reconnect, replay concurrent updates, retain 15s polling, and release observations after the last consumer unmounts.
16
+ - Handle timeline subscription restoration/errors and use SDK cleanup with release error handling.
17
+
18
+ ### Fixed
19
+
20
+ - Restore real-time workspace and attention updates: beta.2 API listeners do not receive the app's directory observation.
21
+ - 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.
22
+ - Reflect host archive/unarchive immediately in workspace rows, preserving usage metrics even if an older RPC finishes later.
23
+ - Remove the host-cache-to-query effect loop that caused React maximum update depth errors; retain stable workspace query keys.
9
24
 
10
25
  ## [0.4.0] - 2026-09-20
11
26
 
@@ -98,7 +113,8 @@ Last release that supports Paseo **0.8.0**. Later versions require Paseo **>= 0.
98
113
  - Command Center entries: open panels and export a markdown usage report.
99
114
  - Plugin renamed from `tool-usage` to `activity`, migrating the old data directory automatically.
100
115
 
101
- [Unreleased]: https://github.com/koinzhang/paseo-plugins/compare/activity-v0.4.0...HEAD
116
+ [Unreleased]: https://github.com/koinzhang/paseo-plugins/compare/activity-v0.5.0...HEAD
117
+ [0.5.0]: https://github.com/koinzhang/paseo-plugins/releases/tag/activity-v0.5.0
102
118
  [0.4.0]: https://github.com/koinzhang/paseo-plugins/releases/tag/activity-v0.4.0
103
119
  [0.3.0]: https://github.com/koinzhang/paseo-plugins/releases/tag/activity-v0.3.0
104
120
  [0.2.0]: https://github.com/koinzhang/paseo-plugins/releases/tag/activity-v0.2.0
package/README.md CHANGED
@@ -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 top skills / MCP (toggle hidden when only one kind has data); 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
 
@@ -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
+ });
@@ -0,0 +1,150 @@
1
+ import type { PluginClientContext } from "@getpaseo/plugin/client";
2
+
3
+ export type AgentsApi = PluginClientContext["paseo"]["agents"];
4
+ export type DirectoryAgent = Awaited<ReturnType<AgentsApi["list"]>>["entries"][number]["agent"];
5
+ type ListResult = Awaited<ReturnType<AgentsApi["list"]>>;
6
+ export type DirectoryUpdate = Parameters<Parameters<AgentsApi["subscribe"]>[0]>[0];
7
+ export type DirectoryListener = (
8
+ agents: ReadonlyMap<string, DirectoryAgent>,
9
+ update?: DirectoryUpdate,
10
+ ) => void;
11
+
12
+ const directories = new WeakMap<AgentsApi, {
13
+ listen(listener: DirectoryListener): () => void;
14
+ }>();
15
+
16
+ /** One owned beta.2 observation per API, shared only by that API's consumers. */
17
+ export function watchAgentDirectory(
18
+ agents: AgentsApi,
19
+ listener: DirectoryListener,
20
+ intervalMs = 15_000,
21
+ ): () => void {
22
+ let directory = directories.get(agents);
23
+ if (!directory) {
24
+ const listeners = new Set<DirectoryListener>();
25
+ let snapshot: Map<string, DirectoryAgent> | undefined;
26
+ let disposed = false;
27
+ let connecting = false;
28
+ let reading = false;
29
+ let generation = 0;
30
+ let pending: DirectoryUpdate[] = [];
31
+ const lifetime = new AbortController();
32
+ let controller: AbortController | undefined;
33
+ let release: (() => Promise<void>) | undefined;
34
+ const report = (error: unknown) => console.error("[activity] agent directory failed", error);
35
+ const safeRelease = () => {
36
+ const stop = release;
37
+ release = undefined;
38
+ if (stop) void stop().catch(report);
39
+ };
40
+ const publish = (update?: DirectoryUpdate) => {
41
+ if (disposed || !snapshot) return;
42
+ for (const callback of listeners) {
43
+ try { callback(snapshot, update); } catch (error) { report(error); }
44
+ }
45
+ };
46
+ const apply = (map: Map<string, DirectoryAgent>, update: DirectoryUpdate) => {
47
+ if (update.kind === "remove") map.delete(update.agentId);
48
+ else map.set(update.agent.id, update.agent);
49
+ };
50
+ async function read(first?: ListResult) {
51
+ const run = ++generation;
52
+ const signal = lifetime.signal;
53
+ reading = true;
54
+ pending = [];
55
+ try {
56
+ let page = first ?? await agents.list({
57
+ filter: { includeArchived: true }, page: { limit: 200 }, signal,
58
+ });
59
+ const next = new Map<string, DirectoryAgent>();
60
+ for (let pages = 0; ; pages++) {
61
+ if (disposed || run !== generation) return;
62
+ for (const { agent } of page.entries) next.set(agent.id, agent);
63
+ if (!page.pageInfo.hasMore) break;
64
+ if (!page.pageInfo.nextCursor || pages >= 99) throw new Error("Incomplete agent directory pagination");
65
+ page = await agents.list({
66
+ filter: { includeArchived: true },
67
+ page: { limit: 200, cursor: page.pageInfo.nextCursor }, signal,
68
+ });
69
+ }
70
+ for (const update of pending) apply(next, update);
71
+ snapshot = next;
72
+ publish();
73
+ } catch (error) {
74
+ if (!disposed && run === generation) report(error);
75
+ } finally {
76
+ if (run === generation) { reading = false; pending = []; }
77
+ }
78
+ }
79
+ async function connect() {
80
+ if (disposed || connecting || release) return;
81
+ connecting = true;
82
+ controller = new AbortController();
83
+ try {
84
+ const result = await agents.list({
85
+ filter: { includeArchived: true }, page: { limit: 200 },
86
+ subscribe: {}, signal: controller.signal,
87
+ });
88
+ if (disposed) {
89
+ await result.subscription.release();
90
+ return;
91
+ }
92
+ release = () => result.subscription.release();
93
+ result.subscription.subscribe({
94
+ // Called immediately and again after reconnect. Rebuild all pages each time.
95
+ snapshot: (page) => { void read(page); },
96
+ update: (message) => {
97
+ if (disposed || message.type !== "agent_update") return;
98
+ const update = message.payload;
99
+ if (reading) pending.push(update);
100
+ if (snapshot) {
101
+ snapshot = new Map(snapshot);
102
+ apply(snapshot, update);
103
+ publish(update);
104
+ }
105
+ },
106
+ error: (error) => {
107
+ if (disposed) return;
108
+ report(error);
109
+ ++generation;
110
+ reading = false;
111
+ controller?.abort();
112
+ safeRelease();
113
+ void read();
114
+ },
115
+ });
116
+ } catch (error) {
117
+ if (!disposed) {
118
+ report(error);
119
+ await read();
120
+ }
121
+ } finally {
122
+ connecting = false;
123
+ }
124
+ }
125
+ const timer = setInterval(() => {
126
+ if (!release) void connect();
127
+ else if (!reading) void read();
128
+ }, intervalMs);
129
+ directory = {
130
+ listen(callback) {
131
+ listeners.add(callback);
132
+ if (snapshot) callback(snapshot);
133
+ return () => {
134
+ listeners.delete(callback);
135
+ if (listeners.size !== 0 || disposed) return;
136
+ disposed = true;
137
+ ++generation;
138
+ clearInterval(timer);
139
+ lifetime.abort();
140
+ controller?.abort();
141
+ safeRelease();
142
+ directories.delete(agents);
143
+ };
144
+ },
145
+ };
146
+ directories.set(agents, directory);
147
+ void connect();
148
+ }
149
+ return directory.listen(listener);
150
+ }
@@ -18,18 +18,12 @@ import {
18
18
  publishAttentionStatuses,
19
19
  useAttentionStatuses,
20
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";
21
+ import { watchAgentDirectory } from "./agent-directory.ts";
22
+ import { agentStatusInfo } from "./workspace/list-host-agents.ts";
27
23
  import type { AgentStatusInfo } from "./workspace/constants.ts";
28
24
 
29
25
  const TITLE = "Needs attention";
30
26
  const PILL_ID = "attention";
31
- /** Completeness backup only — live path is agents.subscribe → store → icon. */
32
- const SYNC_MS = 15_000;
33
27
 
34
28
  type PillEntry = {
35
29
  registration?: PluginButtonRegistration;
@@ -45,25 +39,9 @@ function attentionSignature(
45
39
  return items.map((i) => `${i.agentId}:${i.kind}:${i.permissionCount}`).join("|");
46
40
  }
47
41
 
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
- */
42
+ /** Entry-owned directory drives pill registrations and attention, with 15s reconciliation. */
54
43
  export function contributeAttentionPills(client: PluginClientContext): () => void {
55
44
  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
45
  function applyPill(
68
46
  agentId: string,
69
47
  entry: PillEntry,
@@ -103,43 +81,6 @@ export function contributeAttentionPills(client: PluginClientContext): () => voi
103
81
  }
104
82
  }
105
83
 
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
84
  function createPillIcon(agentId: string) {
144
85
  return function AttentionPillIcon({
145
86
  size,
@@ -189,7 +130,6 @@ export function contributeAttentionPills(client: PluginClientContext): () => voi
189
130
  pills.set(agentId, entry);
190
131
  const cached = getAttentionStatuses(workspaceId);
191
132
  if (cached) applyPill(agentId, entry, cached);
192
- else void syncWorkspace(workspaceId);
193
133
  }
194
134
 
195
135
  function removePill(agentId: string) {
@@ -197,53 +137,25 @@ export function contributeAttentionPills(client: PluginClientContext): () => voi
197
137
  pills.delete(agentId);
198
138
  }
199
139
 
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;
140
+ const stopDirectory = watchAgentDirectory(client.paseo.agents, (snapshot) => {
141
+ const workspaces = new Map<string, Record<string, AgentStatusInfo>>();
142
+ for (const [id, entry] of pills) {
143
+ const agent = snapshot.get(id);
144
+ if (!agent || agent.archivedAt || agent.workspaceId !== entry.workspaceId) removePill(id);
145
+ workspaces.set(entry.workspaceId, {});
213
146
  }
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;
147
+ for (const agent of snapshot.values()) {
148
+ if (agent.archivedAt || !agent.workspaceId) continue;
149
+ const statuses = workspaces.get(agent.workspaceId) ?? {};
150
+ statuses[agent.id] = agentStatusInfo(agent);
151
+ workspaces.set(agent.workspaceId, statuses);
152
+ addPill(agent.id, agent.workspaceId);
224
153
  }
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);
154
+ for (const [workspaceId, statuses] of workspaces) applyWorkspace(workspaceId, statuses);
238
155
  });
239
156
 
240
- scheduleSync();
241
-
242
157
  return () => {
243
- disposed = true;
244
- clearTimeout(timer);
245
- unsubscribeDir();
246
- unsubscribePush();
158
+ stopDirectory();
247
159
  pills.forEach((entry) => entry.registration?.remove());
248
160
  pills.clear();
249
161
  clearAttentionStatuses();
@@ -1,79 +1,31 @@
1
- import type { PluginClientContext } from "@getpaseo/plugin/client";
2
- import { listAllAgentPages } from "../shared/list-agent-pages.ts";
1
+ import { watchAgentDirectory, type AgentsApi, type DirectoryAgent } from "./agent-directory.ts";
3
2
 
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. */
3
+ /** Pill registrations follow the owned directory; archived agents have no composer pill. */
9
4
  export function watchPillDirectory(
10
5
  agents: AgentsApi,
11
- onAgent: (agent: Agent) => void,
6
+ onAgent: (agent: DirectoryAgent) => void,
12
7
  onRemove: (agentId: string) => void,
13
8
  intervalMs = 15_000,
14
- onPolled?: (agent: Agent) => void,
9
+ onPolled?: (agent: DirectoryAgent) => void,
15
10
  ): () => 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
11
  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);
12
+ return watchAgentDirectory(agents, (snapshot, update) => {
13
+ for (const id of versions.keys()) {
14
+ const agent = snapshot.get(id);
15
+ if (!agent || agent.archivedAt) {
16
+ versions.delete(id);
17
+ onRemove(id);
59
18
  }
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);
19
+ }
20
+ for (const agent of snapshot.values()) {
21
+ if (agent.archivedAt) continue;
22
+ const version = JSON.stringify([agent.workspaceId, agent.status, agent.updatedAt,
23
+ agent.lastUserMessageAt, agent.activeTurn?.turnId]);
24
+ if (versions.get(agent.id) !== version) {
25
+ versions.set(agent.id, version);
26
+ onAgent(agent);
65
27
  }
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);
28
+ if (!update) onPolled?.(agent);
71
29
  }
72
- }
73
- void sync();
74
- return () => {
75
- disposed = true;
76
- unsubscribe();
77
- clearTimeout(timer);
78
- };
30
+ }, intervalMs);
79
31
  }