@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.
@@ -1,5 +1,6 @@
1
1
  import { usePaseo } from "@getpaseo/plugin/client";
2
2
  import { useEffect, useRef } from "react";
3
+ import { watchAgentDirectory } from "./agent-directory.ts";
3
4
 
4
5
  const TURN_END_DEBOUNCE_MS = 300;
5
6
  const INGEST_SETTLE_MS = 2_000;
@@ -36,10 +37,26 @@ function useActivityRefresh(scope: AgentTurnEndScope, onTurnEnd: () => void): vo
36
37
  };
37
38
  const unsubscribe = agentId != null
38
39
  ? paseo.agents.ref(agentId).timeline.subscribe(({ event }) => {
39
- if (["turn_completed", "turn_failed", "turn_canceled", "replacement"].includes(event.type)) schedule();
40
+ if (event.type === "subscription_restored") {
41
+ // Live-only after reconnect; refresh in case a turn ended while offline.
42
+ schedule();
43
+ return;
44
+ }
45
+ if (event.type === "error") {
46
+ console.error(
47
+ "[activity] timeline observation stopped; polling remains active",
48
+ "error" in event ? event.error : event,
49
+ );
50
+ return;
51
+ }
52
+ if (["turn_completed", "turn_failed", "turn_canceled", "replacement"].includes(event.type)) {
53
+ schedule();
54
+ }
40
55
  })
41
- : paseo.agents.subscribe((update) => {
56
+ : watchAgentDirectory(paseo.agents, (_snapshot, update) => {
42
57
  // Workspace-wide hint only. The 15s query poll owns completeness.
58
+ // The surface owns its API observation, independently of the entry.
59
+ if (!update) { schedule(); return; }
43
60
  if (update.kind === "remove") {
44
61
  schedule();
45
62
  return;
@@ -1,47 +1,23 @@
1
- import {
2
- usePaseo,
3
- useWorkspace,
4
- } from "@getpaseo/plugin/client";
5
- import { useQuery, useQueryClient } from "@tanstack/react-query";
6
- import { useEffect, useMemo } from "react";
1
+ import { usePaseo } from "@getpaseo/plugin/client";
2
+ import { useEffect, useState } from "react";
3
+ import { watchAgentDirectory } from "./agent-directory.ts";
4
+ import { agentStatusInfo } from "./workspace/list-host-agents.ts";
7
5
  import type { AgentStatusInfo } from "./workspace/constants.ts";
8
- import { loadWorkspaceAgentStatuses } from "./workspace/list-host-agents.ts";
9
- import { updateWorkspaceStatusCache } from "./workspace/status-cache.ts";
10
6
 
11
- export function workspaceAgentStatusQueryKey(
12
- workspaceId: string,
13
- projectId: string | null | undefined,
14
- ) {
15
- return ["activity", "workspace-agent-status", workspaceId, projectId ?? null] as const;
16
- }
17
-
18
- /**
19
- * Shared host agent status map for a workspace (Explorer + attention pill).
20
- * 15s poll owns completeness; subscribe accelerates without list({ subscribe }).
21
- */
7
+ /** Directory snapshots are authoritative; host UI cache absence is not a lifecycle event. */
22
8
  export function useWorkspaceAgentStatuses(workspaceId: string) {
23
9
  const paseo = usePaseo();
24
- const queryClient = useQueryClient();
25
- const projectId = useWorkspace(workspaceId, (workspace) => workspace.projectId);
26
- const queryKey = useMemo(
27
- () => workspaceAgentStatusQueryKey(workspaceId, projectId),
28
- [workspaceId, projectId],
29
- );
30
-
31
- const query = useQuery({
32
- refetchInterval: 15_000,
33
- retry: false,
34
- queryKey,
35
- queryFn: () => loadWorkspaceAgentStatuses(paseo, workspaceId, projectId),
36
- });
37
-
38
- useEffect(
39
- () =>
40
- paseo.agents.subscribe((update) => {
41
- updateWorkspaceStatusCache(queryClient, queryKey, workspaceId, update);
42
- }),
43
- [paseo, queryClient, workspaceId, queryKey],
44
- );
45
-
46
- return query as typeof query & { data: Record<string, AgentStatusInfo> | undefined };
10
+ const [state, setState] = useState<{
11
+ paseo: typeof paseo;
12
+ workspaceId: string;
13
+ data: Record<string, AgentStatusInfo>;
14
+ }>();
15
+ useEffect(() => watchAgentDirectory(paseo.agents, (snapshot) => {
16
+ const data: Record<string, AgentStatusInfo> = {};
17
+ for (const agent of snapshot.values()) {
18
+ if (agent.workspaceId === workspaceId) data[agent.id] = agentStatusInfo(agent);
19
+ }
20
+ setState({ paseo, workspaceId, data });
21
+ }), [paseo, workspaceId]);
22
+ return { data: state?.paseo === paseo && state.workspaceId === workspaceId ? state.data : undefined };
47
23
  }
@@ -13,6 +13,8 @@ export type AgentLifecycleFilter = "idle" | "running" | "error" | "closed";
13
13
  export type MenuFlyout = "sort" | "group" | "show" | "status" | "lifecycle";
14
14
 
15
15
  export type AgentStatusInfo = {
16
+ /** Explicit host archive state; absent means unknown. */
17
+ archivedAt?: string | null;
16
18
  rank: number;
17
19
  updatedAt: string | null;
18
20
  status: string | null;
@@ -0,0 +1,46 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import type { AgentUsageItem } from "../../shared/usage.ts";
4
+ import { reconcileHostArchive } from "./host-archive-sync.ts";
5
+ import { agentStatusInfo } from "./list-host-agents.ts";
6
+
7
+ function item(agentId: string, archivedAt: string | null = null): AgentUsageItem {
8
+ return {
9
+ agentId,
10
+ provider: "cursor",
11
+ title: agentId,
12
+ callCount: 0,
13
+ skillCalls: 0,
14
+ mcpCalls: 0,
15
+ shellCalls: 0,
16
+ fileReads: 0,
17
+ fileWrites: 0,
18
+ messageCount: 0,
19
+ coding: false,
20
+ createdAt: "2026-09-20T00:00:00.000Z",
21
+ updatedAt: "2026-09-20T00:00:00.000Z",
22
+ archivedAt,
23
+ parentAgentId: null,
24
+ lastActivityAt: null,
25
+ };
26
+ }
27
+
28
+ test("missing host cache and closed status do not synthesize archive", () => {
29
+ const rows = [item("a")];
30
+ assert.equal(reconcileHostArchive(rows, undefined)[0], rows[0]);
31
+ assert.equal(reconcileHostArchive(rows, {})[0], rows[0]);
32
+ const statuses = { a: agentStatusInfo({ id: "a", status: "closed", archivedAt: null }) };
33
+ assert.equal(reconcileHostArchive(rows, statuses)[0]?.archivedAt, null);
34
+ });
35
+
36
+ test("explicit host archive and unarchive override delayed DB results without changing metrics", () => {
37
+ const row = { ...item("a"), callCount: 42 };
38
+ const archived = { a: agentStatusInfo({ id: "a", archivedAt: "2026-09-20T08:30:43.446Z" }) };
39
+ const first = reconcileHostArchive([row], archived)[0]!;
40
+ assert.equal(first.archivedAt, archived.a.archivedAt);
41
+ assert.equal(first.callCount, 42);
42
+ assert.equal(row.archivedAt, null);
43
+ assert.equal(reconcileHostArchive([row], archived)[0]?.archivedAt, first.archivedAt);
44
+ const active = { a: agentStatusInfo({ id: "a", archivedAt: null }) };
45
+ assert.equal(reconcileHostArchive([first], active)[0]?.archivedAt, null);
46
+ });
@@ -0,0 +1,15 @@
1
+ import type { AgentUsageItem } from "../../shared/usage.ts";
2
+ import type { AgentStatusInfo } from "./constants.ts";
3
+
4
+ /** Preserve DB metrics while explicit host archive state wins over delayed RPC results. */
5
+ export function reconcileHostArchive(
6
+ items: ReadonlyArray<AgentUsageItem>,
7
+ statuses: Record<string, AgentStatusInfo> | undefined,
8
+ ): AgentUsageItem[] {
9
+ return items.map((item) => {
10
+ const archivedAt = statuses?.[item.agentId]?.archivedAt;
11
+ return archivedAt === undefined || archivedAt === item.archivedAt
12
+ ? item
13
+ : { ...item, archivedAt };
14
+ });
15
+ }
@@ -1,48 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { test } from "node:test";
3
- import { attentionKind } from "./constants.ts";
4
- import { agentStatusInfo, applyAgentStatusUpdate, loadWorkspaceAgentStatuses } from "./list-host-agents.ts";
5
-
6
- test("workspace status uses daemon placement project ID on every page and rejects other workspaces", async () => {
7
- let pages = 0;
8
- const map = await loadWorkspaceAgentStatuses({ agents: { list: async (options) => {
9
- assert.deepEqual(options.filter, { includeArchived: true, projectKeys: ["prj_c187d0857b6da810"] });
10
- pages++;
11
- return {
12
- entries: [{ agent: { id: `a${pages}`, workspaceId: pages === 1 ? "other" : "w", pendingPermissions: [{}] } },
13
- { agent: { id: "unknown" } }],
14
- pageInfo: { hasMore: pages === 1, nextCursor: pages === 1 ? "next" : null },
15
- };
16
- } } }, "w", "prj_c187d0857b6da810");
17
- assert.equal(pages, 2);
18
- assert.deepEqual(Object.keys(map), ["a2"]);
19
- assert.equal(map.a2?.permissionCount, 1);
20
- });
21
-
22
- // Reproduce daemon 0.8's structural filter, including the two different keys.
23
- test("pending questions survive a poll when catalog key differs from placement key", async () => {
24
- const workspace = { id: "w", projectId: "prj_project" };
25
- const project = { projectId: workspace.projectId, projectKey: "remote:github.com/org/repo" };
26
- const entry = {
27
- agent: { id: "waiting", workspaceId: workspace.id, status: "running",
28
- requiresAttention: false, attentionReason: null, pendingPermissions: [{ tool: "question" }] },
29
- project: { projectKey: project.projectId },
30
- };
31
- const paseo = { agents: { list: async (options: { filter?: { projectKeys?: string[] } }) => ({
32
- entries: !options.filter?.projectKeys || options.filter.projectKeys.includes(entry.project.projectKey) ? [entry] : [],
33
- pageInfo: { hasMore: false, nextCursor: null },
34
- }) } };
35
- const incorrect = await loadWorkspaceAgentStatuses(paseo, workspace.id, project.projectKey);
36
- assert.deepEqual(incorrect, {});
37
- for (let poll = 0; poll < 2; poll++) {
38
- const statuses = await loadWorkspaceAgentStatuses(paseo, workspace.id, workspace.projectId);
39
- assert.equal(statuses.waiting?.permissionCount, 1);
40
- assert.equal(statuses.waiting?.rank, 0);
41
- assert.equal(attentionKind(statuses.waiting), "permission");
42
- }
43
- const fallback = await loadWorkspaceAgentStatuses(paseo, workspace.id);
44
- assert.equal(fallback.waiting?.permissionCount, 1);
45
- });
3
+ import { agentStatusInfo, applyAgentStatusUpdate } from "./list-host-agents.ts";
46
4
 
47
5
  test("agentStatusInfo maps parentAgentId and preserves it on partial pushes", () => {
48
6
  const first = agentStatusInfo({ id: "child", workspaceId: "w", parentAgentId: "parent" });
@@ -78,26 +36,16 @@ test("agentStatusInfo falls back to paseo.parent-agent-id label when field is nu
78
36
  assert.equal(prefersField.parentAgentId, "root");
79
37
  });
80
38
 
81
- test("applyAgentStatusUpdate marks remove as closed and merges upserts without workspaceId", () => {
82
- const map = {
83
- a: agentStatusInfo({ id: "a", workspaceId: "w", status: "idle" }),
84
- b: agentStatusInfo({ id: "b", workspaceId: "w", status: "running", pendingPermissions: [{}] }),
39
+ test("remove only removes membership; closed is accepted only from explicit status", () => {
40
+ const map: Record<string, ReturnType<typeof agentStatusInfo>> = {
41
+ a: agentStatusInfo({ id: "a", workspaceId: "w", status: "running" }),
85
42
  };
86
43
  applyAgentStatusUpdate(map, "w", { kind: "remove", agentId: "a" });
87
- assert.equal(map.a.status, "closed");
88
- assert.equal(map.a.permissionCount, 0);
89
- applyAgentStatusUpdate(map, "w", {
90
- kind: "upsert",
91
- agent: { id: "b", status: "closed" },
92
- });
93
- assert.equal(map.b.status, "closed");
94
- assert.equal(map.b.permissionCount, 1);
95
- applyAgentStatusUpdate(map, "w", {
96
- kind: "upsert",
97
- agent: { id: "c", status: "idle" },
98
- });
99
- assert.equal(
100
- (map as Record<string, ReturnType<typeof agentStatusInfo>>).c,
101
- undefined,
102
- );
44
+ assert.equal(Boolean(map.a), false);
45
+ applyAgentStatusUpdate(map, "w", { kind: "upsert", agent: { id: "a", workspaceId: "w", status: "closed", archivedAt: null } });
46
+ assert.equal(map.a?.status, "closed");
47
+ assert.equal(map.a?.archivedAt, null);
48
+ // A new authoritative snapshot can reopen without a timestamp heuristic.
49
+ applyAgentStatusUpdate(map, "w", { kind: "upsert", agent: { id: "a", workspaceId: "w", status: "idle", archivedAt: null } });
50
+ assert.equal(map.a?.status, "idle");
103
51
  });
@@ -1,7 +1,5 @@
1
- import { listAllAgentPages } from "../../shared/list-agent-pages.ts";
2
1
  import {
3
2
  attentionRank,
4
- HOST_AGENT_PAGE_LIMIT,
5
3
  type AgentStatusInfo,
6
4
  } from "./constants.ts";
7
5
 
@@ -10,6 +8,7 @@ export type HostAgentEntry = {
10
8
  id: string;
11
9
  workspaceId?: string;
12
10
  status?: string;
11
+ archivedAt?: string | null;
13
12
  updatedAt?: string;
14
13
  requiresAttention?: boolean;
15
14
  attentionReason?: string | null;
@@ -33,67 +32,13 @@ export function resolveParentAgentId(agent: HostAgentEntry["agent"]): string | n
33
32
  return typeof legacy === "string" && legacy.trim() ? legacy.trim() : null;
34
33
  }
35
34
 
36
- type HostAgentsApi = {
37
- agents: {
38
- subscribe?: (handler: (update: HostAgentUpdate) => void) => () => void;
39
- list: (options: {
40
- filter?: { includeArchived?: boolean; projectKeys?: string[] };
41
- page?: { limit: number; cursor?: string };
42
- }) => Promise<{
43
- entries: ReadonlyArray<HostAgentEntry>;
44
- pageInfo: { hasMore: boolean; nextCursor: string | null };
45
- }>;
46
- };
47
- };
48
-
49
- /**
50
- * Fetch project agents then enforce workspace scope. In daemon 0.8,
51
- * ProjectPlacement.projectKey is projectId; the project catalog's repository
52
- * key is a different identifier and produces an empty agent directory.
53
- */
54
- export async function loadWorkspaceAgentStatuses(
55
- paseo: HostAgentsApi,
56
- workspaceId: string,
57
- projectId?: string | null,
58
- ): Promise<Record<string, AgentStatusInfo>> {
59
- const pending: HostAgentUpdate[] = [];
60
- const unsubscribe = paseo.agents.subscribe?.((update) => pending.push(update));
61
- try {
62
- const entries = await listAllAgentPages(
63
- async (cursor) => {
64
- const result = await paseo.agents.list({
65
- filter: { includeArchived: true, ...(projectId ? { projectKeys: [projectId] } : {}) },
66
- page: { limit: HOST_AGENT_PAGE_LIMIT, ...(cursor ? { cursor } : {}) },
67
- });
68
- return { entries: result.entries, pageInfo: result.pageInfo };
69
- },
70
- );
71
-
72
- const map: Record<string, AgentStatusInfo> = {};
73
- for (const entry of entries) {
74
- const agent = entry.agent;
75
- if (agent.workspaceId !== workspaceId) continue;
76
- map[agent.id] = agentStatusInfo(agent);
77
- }
78
- for (const update of pending) applyAgentStatusUpdate(map, workspaceId, update);
79
- return map;
80
- } finally {
81
- unsubscribe?.();
82
- }
83
- }
84
-
85
35
  export function applyAgentStatusUpdate(
86
36
  map: Record<string, AgentStatusInfo>, workspaceId: string, update: HostAgentUpdate,
87
37
  ): void {
88
38
  const id = update.kind === "remove" ? update.agentId : update.agent.id;
89
39
  if (update.kind === "remove") {
90
- // Keep the row as Closed so Lifecycle filters work until the next list poll.
91
- const previous = map[id];
92
- if (!previous) return;
93
- map[id] = agentStatusInfo(
94
- { id, workspaceId, status: "closed", updatedAt: previous.updatedAt ?? undefined },
95
- previous,
96
- );
40
+ // Removal is directory membership, not Closed or Archived.
41
+ delete map[id];
97
42
  return;
98
43
  }
99
44
  const agentWorkspaceId = update.agent.workspaceId;
@@ -130,6 +75,7 @@ export function agentStatusInfo(
130
75
  ? resolveParentAgentId(agent)
131
76
  : (previous?.parentAgentId ?? null);
132
77
  return {
78
+ archivedAt: agent.archivedAt !== undefined ? agent.archivedAt : previous?.archivedAt,
133
79
  rank: attentionRank({
134
80
  status: agent.status,
135
81
  requiresAttention,
@@ -37,7 +37,7 @@ import { useAppLanguage } from "../use-app-language.ts";
37
37
  import { useWorkspaceActivityRefresh } from "../use-agent-turn-end.ts";
38
38
  import { UsageStats } from "../usage-stats.tsx";
39
39
  import { AgentsSection } from "./agents-section.tsx";
40
- import { WorkspaceAgentLiveStatusSync } from "./agent-live-status-sync.tsx";
40
+ import { reconcileHostArchive } from "./host-archive-sync.ts";
41
41
  import {
42
42
  AGENT_HEADER_HEIGHT,
43
43
  GROUP_OPTIONS,
@@ -122,8 +122,14 @@ export function WorkspaceActivityPanel({
122
122
  const mcpRpc = useRpc(usageMcpByToolRpc);
123
123
  const hostInfoRpc = useRpc(usageHostInfoRpc);
124
124
 
125
- const agentsQueryKey = ["activity", "workspace-agents", workspaceId] as const;
126
- const terminalsQueryKey = ["activity", "workspace-terminals", workspaceId] as const;
125
+ const agentsQueryKey = useMemo(
126
+ () => ["activity", "workspace-agents", workspaceId] as const,
127
+ [workspaceId],
128
+ );
129
+ const terminalsQueryKey = useMemo(
130
+ () => ["activity", "workspace-terminals", workspaceId] as const,
131
+ [workspaceId],
132
+ );
127
133
 
128
134
  const summary = useQuery({
129
135
  refetchInterval: 15_000,
@@ -183,10 +189,9 @@ export function WorkspaceActivityPanel({
183
189
  });
184
190
  });
185
191
 
186
- const agentItems = agents.data?.items ?? [];
187
- const liveStatusAgentIds = useMemo(
188
- () => agentItems.map((item) => item.agentId),
189
- [agentItems],
192
+ const agentItems = useMemo(
193
+ () => reconcileHostArchive(agents.data?.items ?? [], statuses.data),
194
+ [agents.data, statuses.data],
190
195
  );
191
196
  const visibleAgentItems = useMemo(() => {
192
197
  const byId = statuses.data;
@@ -839,10 +844,6 @@ export function WorkspaceActivityPanel({
839
844
 
840
845
  {showAgents ? (
841
846
  <>
842
- <WorkspaceAgentLiveStatusSync
843
- agentIds={liveStatusAgentIds}
844
- workspaceId={workspaceId}
845
- />
846
847
  <AgentsSection
847
848
  theme={theme}
848
849
  styles={styles}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koinzhang/paseo-plugin-activity",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Local usage analytics and workspace agent ops for Paseo: tools, agents, messages, models, Explorer fleet list, and terminals.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -22,10 +22,10 @@
22
22
  ],
23
23
  "scripts": {
24
24
  "typecheck": "tsc --noEmit",
25
- "test": "node --experimental-strip-types --test server/background-sync.test.ts server/handlers-query.test.ts client/attention-agents.test.ts client/latest-user-message.test.ts client/pill-data-cache.test.ts client/pill-directory.test.ts client/hidden-pill-recheck.test.ts client/workspace/list-host-agents.test.ts client/workspace/status-cache.test.ts client/workspace/constants.test.ts client/workspace/filters.test.ts client/rank-color.test.ts client/provider-filter.test.ts client/workspace/terminal-preview.test.ts shared/activity.test.ts shared/insights.test.ts shared/classify.test.ts shared/usage.test.ts shared/format.test.ts shared/agent-title-search.test.ts shared/list-agent-pages.test.ts shared/agent-page-size.test.ts server/store.test.ts server/ingest.test.ts server/skill-path.test.ts server/mcp-servers.test.ts server/agents.test.ts server/migrate-data.test.ts server/messages.test.ts server/resolve-model.test.ts"
25
+ "test": "node --experimental-strip-types --test server/background-sync.test.ts server/handlers-query.test.ts client/attention-agents.test.ts client/latest-user-message.test.ts client/pill-data-cache.test.ts client/hidden-pill-recheck.test.ts client/workspace/list-host-agents.test.ts client/agent-directory.test.ts client/workspace/constants.test.ts client/workspace/filters.test.ts client/workspace/host-archive-sync.test.ts client/rank-color.test.ts client/provider-filter.test.ts client/workspace/terminal-preview.test.ts shared/activity.test.ts shared/insights.test.ts shared/classify.test.ts shared/usage.test.ts shared/format.test.ts shared/agent-title-search.test.ts shared/list-agent-pages.test.ts shared/agent-page-size.test.ts server/store.test.ts server/ingest.test.ts server/skill-path.test.ts server/mcp-servers.test.ts server/agents.test.ts server/migrate-data.test.ts server/messages.test.ts server/resolve-model.test.ts"
26
26
  },
27
27
  "devDependencies": {
28
- "@getpaseo/plugin": "0.8.0",
28
+ "@getpaseo/plugin": "0.9.0-beta.2",
29
29
  "@tanstack/react-query": "^5.90.11",
30
30
  "@types/node": "^24.13.5",
31
31
  "@types/react": "~19.2.0",
package/paseo-plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "activity",
3
3
  "requirements": {
4
- "paseo": ">=0.8.0"
4
+ "paseo": ">=0.9.0-beta.2"
5
5
  }
6
6
  }
@@ -1,92 +0,0 @@
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
- });
@@ -1,103 +0,0 @@
1
- import { useAgent, useWorkspace } from "@getpaseo/plugin/client";
2
- import { useQueryClient } from "@tanstack/react-query";
3
- import { useEffect, type ReactNode } from "react";
4
- import { workspaceAgentStatusQueryKey } from "../use-workspace-agent-statuses.ts";
5
- import type { AgentStatusInfo } from "./constants.ts";
6
- import { updateWorkspaceStatusCache } from "./status-cache.ts";
7
-
8
- type LiveFields = {
9
- status: AgentStatusInfo["status"];
10
- updatedAt: string | null;
11
- requiresAttention: boolean;
12
- attentionReason: AgentStatusInfo["attentionReason"];
13
- parentAgentId: string | null;
14
- };
15
-
16
- function sameLiveFields(current: AgentStatusInfo | undefined, next: LiveFields): boolean {
17
- if (!current) return false;
18
- return (
19
- current.status === next.status &&
20
- current.updatedAt === next.updatedAt &&
21
- current.requiresAttention === next.requiresAttention &&
22
- current.attentionReason === next.attentionReason &&
23
- current.parentAgentId === next.parentAgentId
24
- );
25
- }
26
-
27
- /** Push one host-normalized snapshot into the workspace status query cache (043). */
28
- function AgentLiveStatusSync({
29
- agentId,
30
- workspaceId,
31
- }: {
32
- agentId: string;
33
- workspaceId: string;
34
- }): null {
35
- const queryClient = useQueryClient();
36
- const projectId = useWorkspace(workspaceId, (workspace) => workspace.projectId);
37
- const queryKey = workspaceAgentStatusQueryKey(workspaceId, projectId);
38
- const live = useAgent(agentId, (agent) => ({
39
- status: agent.status,
40
- updatedAt: agent.updatedAt,
41
- requiresAttention: agent.requiresAttention,
42
- attentionReason: agent.attentionReason,
43
- parentAgentId: agent.parentAgentId,
44
- }));
45
-
46
- useEffect(() => {
47
- const previous = queryClient.getQueryData<Record<string, AgentStatusInfo>>(queryKey);
48
- if (!previous) return;
49
-
50
- if (live == null) {
51
- if (!(agentId in previous) || previous[agentId]?.status === "closed") return;
52
- updateWorkspaceStatusCache(queryClient, queryKey, workspaceId, {
53
- kind: "upsert",
54
- agent: { id: agentId, workspaceId, status: "closed" },
55
- });
56
- return;
57
- }
58
-
59
- const next: LiveFields = {
60
- status: live.status,
61
- updatedAt: live.updatedAt,
62
- requiresAttention: live.requiresAttention,
63
- attentionReason: live.attentionReason,
64
- parentAgentId: live.parentAgentId,
65
- };
66
- if (sameLiveFields(previous[agentId], next)) return;
67
-
68
- updateWorkspaceStatusCache(queryClient, queryKey, workspaceId, {
69
- kind: "upsert",
70
- agent: {
71
- id: agentId,
72
- workspaceId,
73
- status: live.status,
74
- updatedAt: live.updatedAt,
75
- requiresAttention: live.requiresAttention,
76
- attentionReason: live.attentionReason,
77
- parentAgentId: live.parentAgentId,
78
- },
79
- });
80
- }, [agentId, live, queryClient, queryKey, workspaceId]);
81
-
82
- return null;
83
- }
84
-
85
- /**
86
- * Official real-time path for lifecycle / attention fields without owning
87
- * `agents.list({ subscribe })`. pendingPermissions still come from list polls.
88
- */
89
- export function WorkspaceAgentLiveStatusSync({
90
- agentIds,
91
- workspaceId,
92
- }: {
93
- agentIds: ReadonlyArray<string>;
94
- workspaceId: string;
95
- }): ReactNode {
96
- return (
97
- <>
98
- {agentIds.map((agentId) => (
99
- <AgentLiveStatusSync key={agentId} agentId={agentId} workspaceId={workspaceId} />
100
- ))}
101
- </>
102
- );
103
- }