@koinzhang/paseo-plugin-activity 0.6.0 → 0.8.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 (68) hide show
  1. package/CHANGELOG.md +50 -1
  2. package/README.md +18 -11
  3. package/client/activity-heatmap.tsx +115 -74
  4. package/client/agent-creations.tsx +100 -90
  5. package/client/attention-pill.tsx +17 -6
  6. package/client/attention-popover.tsx +19 -23
  7. package/client/design-tokens.test.ts +39 -0
  8. package/client/design-tokens.ts +180 -0
  9. package/client/formatted-time.tsx +4 -4
  10. package/client/global-surface.tsx +243 -268
  11. package/client/header-button.ts +136 -0
  12. package/client/hourly-activity-timeline.tsx +153 -103
  13. package/client/panel-visibility.test.ts +25 -0
  14. package/client/panel-visibility.ts +45 -0
  15. package/client/panel.tsx +94 -111
  16. package/client/pill.tsx +1 -1
  17. package/client/provider-dropdown.tsx +134 -0
  18. package/client/provider-filter.test.ts +17 -13
  19. package/client/provider-filter.ts +5 -7
  20. package/client/rank-color.ts +3 -3
  21. package/client/ranking-bars.tsx +294 -0
  22. package/client/sidebar-item.tsx +15 -0
  23. package/client/ui.tsx +351 -0
  24. package/client/usage-popover.tsx +72 -137
  25. package/client/usage-stats.tsx +29 -11
  26. package/client/use-agent-turn-end.ts +2 -1
  27. package/client/use-app-language.ts +17 -0
  28. package/client/web.ts +73 -18
  29. package/client/workspace/agent-row.tsx +28 -28
  30. package/client/workspace/agents-section.tsx +42 -57
  31. package/client/workspace/constants.ts +8 -6
  32. package/client/workspace/display-menu.tsx +6 -5
  33. package/client/workspace/filters.test.ts +1 -1
  34. package/client/workspace/filters.ts +4 -2
  35. package/client/workspace/panel.tsx +96 -104
  36. package/client/workspace/rank-section.tsx +40 -65
  37. package/client/workspace/running-indicator.tsx +1 -1
  38. package/client/workspace/terminals-section.tsx +24 -12
  39. package/index.client.tsx +53 -31
  40. package/index.server.ts +55 -73
  41. package/package.json +3 -3
  42. package/paseo-plugin.json +2 -1
  43. package/server/agents.ts +20 -2
  44. package/server/background-sync.ts +34 -4
  45. package/server/handlers-query.test.ts +27 -1
  46. package/server/handlers.ts +75 -31
  47. package/server/host-types.ts +6 -6
  48. package/server/ingest.test.ts +8 -0
  49. package/server/messages.test.ts +96 -1
  50. package/server/prompt-dedupe.ts +52 -0
  51. package/server/rpc-cache.test.ts +74 -0
  52. package/server/rpc-cache.ts +48 -0
  53. package/server/store.test.ts +122 -0
  54. package/server/store.ts +313 -19
  55. package/server/ttl-cache.ts +3 -0
  56. package/server/turn-ingest.test.ts +180 -0
  57. package/server/turn-ingest.ts +71 -0
  58. package/shared/activity.test.ts +36 -0
  59. package/shared/activity.ts +37 -0
  60. package/shared/classify.test.ts +1 -10
  61. package/shared/classify.ts +3 -10
  62. package/shared/format.ts +10 -7
  63. package/shared/i18n.test.ts +34 -0
  64. package/shared/i18n.ts +363 -0
  65. package/shared/insights.test.ts +120 -81
  66. package/shared/insights.ts +125 -64
  67. package/shared/usage.test.ts +121 -0
  68. package/shared/usage.ts +191 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koinzhang/paseo-plugin-activity",
3
- "version": "0.6.0",
3
+ "version": "0.8.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/hidden-pill-recheck.test.ts client/agent-directory.test.ts client/workspace/list-host-agents.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/color-mix.test.ts client/fit-text.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/explorer-agent-display.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/agent-directory.test.ts client/workspace/list-host-agents.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/color-mix.test.ts client/design-tokens.test.ts client/fit-text.test.ts client/provider-filter.test.ts client/range.test.ts client/panel-visibility.test.ts client/workspace/terminal-preview.test.ts shared/activity.test.ts shared/insights.test.ts shared/i18n.test.ts shared/classify.test.ts shared/usage.test.ts shared/format.test.ts shared/explorer-agent-display.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 server/turn-ingest.test.ts server/rpc-cache.test.ts"
26
26
  },
27
27
  "devDependencies": {
28
- "@getpaseo/plugin": "0.9.0-beta.2",
28
+ "@getpaseo/plugin": "0.15.1",
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,7 @@
1
1
  {
2
2
  "id": "activity",
3
+ "description": "Local usage analytics and workspace agent ops: Explorer fleet list, live attention, and terminals",
3
4
  "requirements": {
4
- "paseo": ">=0.9.0-beta.2"
5
+ "paseo": ">=0.15.0"
5
6
  }
6
7
  }
package/server/agents.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { PluginHookAgent } from "@getpaseo/plugin/server";
2
- import type { AgentRow, ToolCallRow } from "./store.ts";
2
+ import type { AgentActivitySpan, AgentRow, ToolCallRow } from "./store.ts";
3
3
 
4
4
  function nowIso(): string {
5
5
  return new Date().toISOString();
@@ -19,6 +19,7 @@ export function agentRowFromHook(
19
19
  createdAt: opts.createdAt ?? updatedAt,
20
20
  archivedAt: opts.archivedAt ?? null,
21
21
  updatedAt,
22
+ cwd: agent.cwd || null,
22
23
  };
23
24
  }
24
25
 
@@ -31,7 +32,8 @@ export function agentRowFromSnapshot(agent: {
31
32
  createdAt: string;
32
33
  updatedAt?: string;
33
34
  archivedAt?: string | null;
34
- }): AgentRow {
35
+ cwd?: string | null;
36
+ }, projectRoot?: string | null): AgentRow {
35
37
  const updatedAt = agent.updatedAt ?? agent.createdAt;
36
38
  return {
37
39
  agentId: agent.id,
@@ -42,9 +44,25 @@ export function agentRowFromSnapshot(agent: {
42
44
  createdAt: agent.createdAt,
43
45
  archivedAt: agent.archivedAt ?? null,
44
46
  updatedAt,
47
+ cwd: agent.cwd || null,
48
+ projectRoot: projectRoot ?? null,
45
49
  };
46
50
  }
47
51
 
52
+ /** Store-aggregated activity spans → registry rows (same shape as `agentsFromToolCalls`). */
53
+ export function agentsFromActivitySpans(spans: readonly AgentActivitySpan[]): AgentRow[] {
54
+ return spans.map((span) => ({
55
+ agentId: span.agentId,
56
+ workspaceId: span.workspaceId,
57
+ parentAgentId: null,
58
+ provider: span.provider,
59
+ title: null,
60
+ createdAt: span.firstAt,
61
+ archivedAt: null,
62
+ updatedAt: span.lastAt,
63
+ }));
64
+ }
65
+
48
66
  /** Earliest tool activity per agentId → approximate created_at for unknown agents. */
49
67
  export function agentsFromToolCalls(rows: readonly ToolCallRow[]): AgentRow[] {
50
68
  const earliest = new Map<
@@ -5,7 +5,7 @@ import { LOG_PREFIX } from "../shared/plugin-id.ts";
5
5
  import { listAllAgentPages } from "../shared/list-agent-pages.ts";
6
6
  import type { UsageStore } from "./store.ts";
7
7
  import { defaultDataDir } from "./store.ts";
8
- import { agentRowFromSnapshot, agentsFromToolCalls } from "./agents.ts";
8
+ import { agentRowFromSnapshot, agentsFromActivitySpans } from "./agents.ts";
9
9
  import { resyncAgents } from "./handlers.ts";
10
10
 
11
11
  type PaseoApi = PluginHandlerContext["paseo"];
@@ -27,6 +27,21 @@ async function listAllAgents(paseo: PaseoApi) {
27
27
  });
28
28
  }
29
29
 
30
+ /** Active workspace id → project root; archived workspaces are not listed (070). */
31
+ async function listWorkspaceProjectRoots(paseo: PaseoApi): Promise<Map<string, string>> {
32
+ const roots = new Map<string, string>();
33
+ let cursor: string | undefined;
34
+ for (let pages = 0; pages < 100; pages++) {
35
+ const page = await paseo.workspaces.list({
36
+ page: { limit: AGENT_LIST_PAGE_LIMIT, ...(cursor ? { cursor } : {}) },
37
+ });
38
+ for (const workspace of page.entries) roots.set(workspace.id, workspace.projectRootPath);
39
+ if (!page.pageInfo.hasMore || !page.pageInfo.nextCursor) break;
40
+ cursor = page.pageInfo.nextCursor;
41
+ }
42
+ return roots;
43
+ }
44
+
30
45
  export function createBackgroundSync(store: UsageStore, options: {
31
46
  path?: string;
32
47
  version?: number;
@@ -60,11 +75,21 @@ export function createBackgroundSync(store: UsageStore, options: {
60
75
 
61
76
  async function check(paseo: PaseoApi) {
62
77
  const listedEntries = await listAllAgents(paseo);
78
+ const projectRoots = await listWorkspaceProjectRoots(paseo).catch((error) => {
79
+ console.error("[activity] workspace project roots unavailable", error);
80
+ return new Map<string, string>();
81
+ });
63
82
  if (controller.signal.aborted) return;
64
83
  // Directory synchronization belongs to the background task, never a UI read.
65
- store.upsertAgents(listedEntries.map(({ agent }) => agentRowFromSnapshot(agent)));
84
+ store.upsertAgents(
85
+ listedEntries.map(({ agent }) =>
86
+ agentRowFromSnapshot(agent, agent.workspaceId ? projectRoots.get(agent.workspaceId) : null),
87
+ ),
88
+ );
66
89
  const known = new Set(store.selectAgents().map(agent => agent.agentId));
67
- store.upsertAgents(agentsFromToolCalls(store.select()).filter(agent => !known.has(agent.agentId)));
90
+ store.upsertAgents(
91
+ agentsFromActivitySpans(store.agentActivitySpans()).filter(agent => !known.has(agent.agentId)),
92
+ );
68
93
  console.log(
69
94
  `${LOG_PREFIX} directory sync listed=${listedEntries.length} (archived=${listedEntries.filter(entry => entry.agent.archivedAt).length}) registry=${known.size}`,
70
95
  );
@@ -85,7 +110,12 @@ export function createBackgroundSync(store: UsageStore, options: {
85
110
  if (agent.archivedAt) continue;
86
111
  const stamp = `${agent.updatedAt}:${agent.lastUserMessageAt ?? ""}`;
87
112
  if (checkpoints[agent.id] === stamp) continue;
88
- const result = await scan(store, paseo, [agent.id], controller.signal, listedEntries);
113
+ // A checkpoint under this BACKFILL_VERSION means earlier rows already carry
114
+ // current classification, so only the new timeline tail needs scanning.
115
+ const incremental = checkpoints[agent.id] !== undefined;
116
+ const result = await scan(store, paseo, [agent.id], controller.signal, listedEntries, {
117
+ incremental,
118
+ });
89
119
  if (controller.signal.aborted) return;
90
120
  if (result.errors.length || result.syncedAgents !== 1) {
91
121
  console.error("[activity] background history scan incomplete", agent.id, result.errors);
@@ -1,5 +1,5 @@
1
1
  import assert from "node:assert/strict";
2
- import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { test } from "node:test";
@@ -12,6 +12,7 @@ import {
12
12
  createAgentsHandler,
13
13
  createByProviderHandler,
14
14
  createRecentMcpCallsHandler,
15
+ createReadSkillHandler,
15
16
  createRecentSkillCallsHandler,
16
17
  createSkillsByNameHandler,
17
18
  } from "./handlers.ts";
@@ -393,3 +394,28 @@ test("skills-by-name keeps counts when agent metadata is unavailable", async ()
393
394
  rmSync(dir, { recursive: true, force: true });
394
395
  }
395
396
  });
397
+
398
+ test("read-skill rejects SKILL.md symlinks to other files but follows symlinked skill dirs (064)", async () => {
399
+ const home = mkdtempSync(join(tmpdir(), "activity-read-skill-"));
400
+ const previousHome = process.env.HOME;
401
+ process.env.HOME = home;
402
+ try {
403
+ const skills = join(home, ".claude", "skills");
404
+ mkdirSync(join(skills, "evil"), { recursive: true });
405
+ writeFileSync(join(home, "secret.txt"), "private key");
406
+ symlinkSync(join(home, "secret.txt"), join(skills, "evil", "SKILL.md"));
407
+ const external = join(home, "dotfiles", "good");
408
+ mkdirSync(external, { recursive: true });
409
+ writeFileSync(join(external, "SKILL.md"), "# good");
410
+ symlinkSync(external, join(skills, "good"));
411
+
412
+ const read = createReadSkillHandler();
413
+ await assert.rejects(read({ path: "~/.claude/skills/evil/SKILL.md" }), /not allowed/);
414
+ const ok = await read({ path: "~/.claude/skills/good/SKILL.md" });
415
+ assert.equal(ok.body, "# good");
416
+ assert.equal(ok.path, "~/.claude/skills/good/SKILL.md");
417
+ } finally {
418
+ process.env.HOME = previousHome;
419
+ rmSync(home, { recursive: true, force: true });
420
+ }
421
+ });
@@ -7,6 +7,7 @@ import { realpathSync, statSync } from "node:fs";
7
7
  import {
8
8
  aggregateAgentCreations,
9
9
  aggregateAgents,
10
+ aggregateByProject,
10
11
  aggregateByProvider,
11
12
  aggregateActivityByHour,
12
13
  aggregateMcpByTool,
@@ -17,12 +18,15 @@ import {
17
18
  isFileWrite,
18
19
  isShellCall,
19
20
  pickLongestAgentLifetime,
21
+ averageEngagedSessionMs,
22
+ countMultiTurnSessions,
20
23
  usageActivityByDayRpc,
21
24
  usageActivityByHourRpc,
22
25
  usageAgentCreationsRpc,
23
26
  usageAgentLifetimeRpc,
24
27
  usageAgentsRpc,
25
28
  usageAgentUnarchiveRpc,
29
+ usageByProjectRpc,
26
30
  usageByProviderRpc,
27
31
  usageExportRpc,
28
32
  usageListRpc,
@@ -130,16 +134,12 @@ export function createListHandler(store: UsageStore) {
130
134
  from: input.from,
131
135
  to: input.to,
132
136
  };
133
- const matched = store.select(filter).sort((a, b) => {
134
- const ta = a.ts ?? a.ingestedAt;
135
- const tb = b.ts ?? b.ingestedAt;
136
- return tb.localeCompare(ta);
137
+ const page = store.selectRecent(filter, {
138
+ limit: input.limit ?? 200,
139
+ offset: input.offset ?? 0,
137
140
  });
138
- const offset = input.offset ?? 0;
139
- const limit = input.limit ?? 200;
140
- const page = matched.slice(offset, offset + limit);
141
141
  return {
142
- total: matched.length,
142
+ total: store.countRows(filter),
143
143
  rows: page.map((row) => ({
144
144
  agentId: row.agentId,
145
145
  callId: row.callId,
@@ -209,13 +209,10 @@ export function createRecentSkillCallsHandler(store: UsageStore) {
209
209
  .map((agent) => [agent.agentId, agent.title?.trim() || null] as const),
210
210
  );
211
211
  const items = store
212
- .select({ workspaceId: input.workspaceId, category: "skill" })
213
- .filter((row) => row.confidence !== "low" && row.skillName?.trim())
214
- .sort((a, b) => {
215
- const byTime = (b.ts ?? b.ingestedAt).localeCompare(a.ts ?? a.ingestedAt);
216
- return byTime || b.callId.localeCompare(a.callId);
217
- })
218
- .slice(0, input.limit ?? 8)
212
+ .selectRecent(
213
+ { workspaceId: input.workspaceId, category: "skill" },
214
+ { limit: input.limit ?? 8, scope: "skill-named" },
215
+ )
219
216
  .map((row) => ({
220
217
  agentId: row.agentId,
221
218
  agentTitle: titles.get(row.agentId) ?? null,
@@ -237,13 +234,10 @@ export function createRecentMcpCallsHandler(store: UsageStore) {
237
234
  .map((agent) => [agent.agentId, agent.title?.trim() || null] as const),
238
235
  );
239
236
  const items = store
240
- .select({ workspaceId: input.workspaceId, category: "mcp" })
241
- .filter((row) => row.mcpServer?.trim() && row.mcpTool?.trim())
242
- .sort((a, b) => {
243
- const byTime = (b.ts ?? b.ingestedAt).localeCompare(a.ts ?? a.ingestedAt);
244
- return byTime || b.callId.localeCompare(a.callId);
245
- })
246
- .slice(0, input.limit ?? 8)
237
+ .selectRecent(
238
+ { workspaceId: input.workspaceId, category: "mcp" },
239
+ { limit: input.limit ?? 8, scope: "mcp-named" },
240
+ )
247
241
  .map((row) => ({
248
242
  agentId: row.agentId,
249
243
  agentTitle: titles.get(row.agentId) ?? null,
@@ -320,18 +314,51 @@ export function createAgentsHandler(store: UsageStore) {
320
314
  };
321
315
  }
322
316
 
323
- /** Longest created→archived agent from the registry alone (049) — no tool-call join. */
317
+ /** Longest created→archived agent (049) plus engaged time and multi-turn counts (072). */
324
318
  export function createAgentLifetimeHandler(store: UsageStore) {
325
319
  return async (
326
320
  input: RpcInput<typeof usageAgentLifetimeRpc>,
327
321
  ): Promise<RpcOutput<typeof usageAgentLifetimeRpc>> => {
328
- return pickLongestAgentLifetime(store.selectAgents({ provider: input.provider }), {
329
- provider: input.provider,
330
- });
322
+ const agents = store.selectAgents({ provider: input.provider });
323
+ const lifetime = pickLongestAgentLifetime(agents, { provider: input.provider });
324
+ const messages = store.selectUserMessages();
325
+ const averageEngagedMs = averageEngagedSessionMs(agents, [...store.select(), ...messages]);
326
+ return { ...lifetime, averageEngagedMs, ...countMultiTurnSessions(agents, messages) };
331
327
  };
332
328
  }
333
329
 
334
330
  /** Daily agent creations with a per-provider breakdown (051) — registry only. */
331
+ /**
332
+ * Per-project totals (070). Project names come from the host project list;
333
+ * an unreachable host still groups by recorded roots / cwd (basename labels).
334
+ */
335
+ export function createByProjectHandler(store: UsageStore) {
336
+ return async (
337
+ input: RpcInput<typeof usageByProjectRpc>,
338
+ context: PluginHandlerContext,
339
+ ): Promise<RpcOutput<typeof usageByProjectRpc>> => {
340
+ let projects: Array<{ root: string; name: string }> = [];
341
+ try {
342
+ const result = await context.paseo.projects.list();
343
+ projects = result.projects.map((project) => ({
344
+ root: project.projectRootPath,
345
+ name: project.projectDisplayName,
346
+ }));
347
+ } catch (error) {
348
+ console.error("[activity] project list unavailable", error);
349
+ }
350
+ return {
351
+ projects: aggregateByProject(
352
+ store.selectAgents(),
353
+ store.select({}),
354
+ store.selectUserMessages({}),
355
+ projects,
356
+ { provider: input.provider },
357
+ ),
358
+ };
359
+ };
360
+ }
361
+
335
362
  export function createAgentCreationsHandler(store: UsageStore) {
336
363
  return async (
337
364
  input: RpcInput<typeof usageAgentCreationsRpc>,
@@ -356,7 +383,7 @@ export function createUnarchiveAgentHandler(store: UsageStore) {
356
383
  input: RpcInput<typeof usageAgentUnarchiveRpc>,
357
384
  ): Promise<RpcOutput<typeof usageAgentUnarchiveRpc>> => {
358
385
  try {
359
- await execFileAsync("paseo", ["agent", "reload", input.agentId], {
386
+ await execFileAsync("paseo", ["agent", "reload", "--", input.agentId], {
360
387
  timeout: 120_000,
361
388
  maxBuffer: 1024 * 1024,
362
389
  });
@@ -439,9 +466,12 @@ function isPathInside(absolute: string, root: string): boolean {
439
466
  return abs === base || abs.startsWith(base.endsWith(sep) ? base : `${base}${sep}`);
440
467
  }
441
468
 
469
+ function isSkillFileName(path: string): boolean {
470
+ return /\/SKILL\.md$/i.test(path.replace(/\\/g, "/"));
471
+ }
472
+
442
473
  function assertAllowedSkillPath(absolute: string, homeDir: string): string {
443
- const normalized = absolute.replace(/\\/g, "/");
444
- if (!/\/SKILL\.md$/i.test(normalized)) {
474
+ if (!isSkillFileName(absolute)) {
445
475
  throw new Error("Skill path must end with SKILL.md");
446
476
  }
447
477
  let real = absolute;
@@ -450,6 +480,11 @@ function assertAllowedSkillPath(absolute: string, homeDir: string): string {
450
480
  } catch {
451
481
  throw new Error("Skill file not found");
452
482
  }
483
+ // Skill dirs are often symlinked outside the roots, so only the file name of the
484
+ // resolved target is enforced; a SKILL.md link must not expose another file.
485
+ if (!isSkillFileName(real)) {
486
+ throw new Error("Skill path not allowed");
487
+ }
453
488
  const roots = buildHomeSkillRoots(homeDir);
454
489
  const underHome =
455
490
  roots.some((root) => isPathInside(absolute, root) || isPathInside(real, root));
@@ -644,6 +679,7 @@ export async function resyncAgents(
644
679
  updatedAt?: string;
645
680
  lastUserMessageAt?: string | null;
646
681
  } }>,
682
+ options: { incremental?: boolean } = {},
647
683
  ): Promise<HistoryScanResult> {
648
684
  if (signal?.aborted) throw new Error("History scan canceled");
649
685
  const homeDir = homedir();
@@ -681,8 +717,10 @@ export async function resyncAgents(
681
717
  });
682
718
  let pageInserted = 0;
683
719
 
684
- // Always full-scan (tail → older). Upserts are idempotent and re-apply
685
- // classification so OpenCode MCP server-list fixes rewrite prior rows.
720
+ // Scan tail → older. Full scans re-apply classification to every row;
721
+ // incremental scans (same epoch, caller vouches for current semantics)
722
+ // stop after the page that reaches the last synced seq. That page is
723
+ // ingested whole so tool lifecycles straddling lastSeq are refreshed.
686
724
  let page = await timeline.refetch({
687
725
  projection: "canonical",
688
726
  direction: "tail",
@@ -696,6 +734,10 @@ export async function resyncAgents(
696
734
  // Timeline replacement reshuffles seq; drop hash-keyed anonymous messages.
697
735
  store.deleteCanonicalUserMessages(agent.id);
698
736
  }
737
+ const stopAtSeq =
738
+ options.incremental && newest && previous && previous.epoch === newest.epoch
739
+ ? previous.lastSeq
740
+ : null;
699
741
  for (;;) {
700
742
  if (signal?.aborted) throw new Error("History scan canceled");
701
743
  pageInserted += ingestCanonicalPage(
@@ -707,6 +749,7 @@ export async function resyncAgents(
707
749
  model,
708
750
  );
709
751
  if (!page.hasOlder || !page.startCursor) break;
752
+ if (stopAtSeq != null && page.startCursor.seq <= stopAtSeq) break;
710
753
  page = await timeline.refetch({
711
754
  projection: "canonical",
712
755
  direction: "before",
@@ -715,6 +758,7 @@ export async function resyncAgents(
715
758
  });
716
759
  if (page.error) throw new Error(page.error);
717
760
  }
761
+ store.pruneReplayDuplicateMessages(agent.id);
718
762
  if (newest) store.setSyncState(agent.id, newest.epoch, newest.seq);
719
763
 
720
764
  syncedAgents += 1;
@@ -1,14 +1,14 @@
1
- import type { PluginHookContext, PluginLifecycleEvents } from "@getpaseo/plugin/server";
1
+ import type { PluginHookContext, PluginHookEvents } from "@getpaseo/plugin/server";
2
2
 
3
3
  /**
4
4
  * Host types re-derived from the plugin SDK.
5
5
  *
6
6
  * Plugins must only import host-provided specifiers (`@getpaseo/plugin*`, zod,
7
- * react, react-native, @tanstack/react-query, node builtins): Paseo compiles
8
- * plugin sources without installing dependencies, so direct `@getpaseo/protocol`
9
- * or `@getpaseo/client` imports fail the runtime-boundary build.
7
+ * react, react-native, @tanstack/react-query, node builtins) or dependencies the
8
+ * plugin installs itself: Paseo compiles plugin sources without installing
9
+ * dependencies, so `@getpaseo/protocol` and `@getpaseo/client` imports fail the
10
+ * runtime-boundary build unless they resolve from the plugin's node_modules.
10
11
  */
11
- export type AgentTimelineItem =
12
- PluginLifecycleEvents["agent.turn_ended"]["timeline"][number];
12
+ export type AgentTimelineItem = PluginHookEvents["agent.turn.after"]["timeline"][number];
13
13
 
14
14
  export type PaseoApi = PluginHookContext["paseo"];
@@ -49,6 +49,11 @@ function fakeStore(): UsageStore & { rows: ToolCallRow[] } {
49
49
  select() {
50
50
  return [...rows];
51
51
  },
52
+ generation: () => 0,
53
+ selectRecent: () => [],
54
+ countRows: () => rows.length,
55
+ agentActivitySpans: () => [],
56
+ terminalCallIds: () => new Set(),
52
57
  upsertAgents(batch) {
53
58
  for (const row of batch) agents.set(row.agentId, row);
54
59
  return batch.length;
@@ -73,6 +78,9 @@ function fakeStore(): UsageStore & { rows: ToolCallRow[] } {
73
78
  deleteCanonicalUserMessages() {
74
79
  return 0;
75
80
  },
81
+ pruneReplayDuplicateMessages() {
82
+ return 0;
83
+ },
76
84
  close() {},
77
85
  };
78
86
  }
@@ -5,7 +5,8 @@ import { tmpdir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import type { PluginHandlerContext } from "@getpaseo/plugin/server";
7
7
  import { ingestUserMessages, ingestTurnTimeline } from "./ingest.ts";
8
- import { createUsageStore } from "./store.ts";
8
+ import { createUsageStore, type UserMessageRow } from "./store.ts";
9
+ import { replayDuplicateMessageIds } from "./prompt-dedupe.ts";
9
10
  import { createActivityByDayHandler, createByProviderHandler, resyncAgents } from "./handlers.ts";
10
11
  import { aggregateActivityByDay, aggregateByProvider } from "../shared/usage.ts";
11
12
  import { computeStreaks } from "../shared/activity.ts";
@@ -154,3 +155,97 @@ test("canceling an in-flight canonical scan prevents writes after the store clos
154
155
  assert.equal(result.errors[0]?.message, "History scan canceled");
155
156
  } finally { rmSync(dir, { recursive: true, force: true }); }
156
157
  });
158
+
159
+ test("incremental resync stops after the page reaching the last synced seq (064)", async () => {
160
+ const dir = mkdtempSync(join(tmpdir(), "activity-incremental-"));
161
+ const store = createUsageStore({ dir, driver: "sqlite" });
162
+ let epoch = "e";
163
+ const requested: Array<number | null> = [];
164
+ // Three pages of one entry each: seq 30 (tail) → 20 → 10.
165
+ const pageAt = (seq: number) => ({
166
+ entries: [{ item: { type: "user_message", text: "", messageId: `m${seq}` }, timestamp: earlier, seqStart: seq }],
167
+ hasOlder: seq > 10,
168
+ startCursor: { epoch, seq },
169
+ endCursor: { epoch, seq: 30 },
170
+ });
171
+ const paseo = { agents: {
172
+ ref: () => ({ timeline: { refetch: async (input: { direction: string; cursor?: { seq: number } }) => {
173
+ requested.push(input.cursor?.seq ?? null);
174
+ return pageAt(input.direction === "tail" ? 30 : input.cursor!.seq - 10);
175
+ } } }),
176
+ } } as unknown as PaseoApi;
177
+ const listed = [{ agent: { ...agent, createdAt: earlier } }];
178
+ try {
179
+ await resyncAgents(store, paseo, undefined, undefined, listed);
180
+ assert.equal(requested.length, 3, "first scan is full");
181
+ requested.length = 0;
182
+ store.setSyncState(agent.id, "e", 20);
183
+ await resyncAgents(store, paseo, undefined, undefined, listed, { incremental: true });
184
+ assert.deepEqual(requested, [null, 30], "stops once a page starts at or before lastSeq");
185
+ requested.length = 0;
186
+ await resyncAgents(store, paseo, undefined, undefined, listed);
187
+ assert.equal(requested.length, 3, "non-incremental callers still scan everything");
188
+ requested.length = 0;
189
+ store.setSyncState(agent.id, "old-epoch", 30);
190
+ epoch = "e2";
191
+ await resyncAgents(store, paseo, undefined, undefined, listed, { incremental: true });
192
+ assert.equal(requested.length, 3, "epoch change forces a full scan");
193
+ } finally { store.close(); rmSync(dir, { recursive: true, force: true }); }
194
+ });
195
+
196
+ function stored(messageId: string, ts: string | null, overrides: Partial<UserMessageRow> = {}): UserMessageRow {
197
+ return {
198
+ agentId: "a1", messageId, workspaceId: "w1", provider: "opencode", model: null,
199
+ turnId: null, seq: null, ts, ingestedAt: ts ?? now, ...overrides,
200
+ };
201
+ }
202
+
203
+ test("replayed prompts carrying provider ids pair with live client ids within two seconds (075)", () => {
204
+ const rows = [
205
+ stored("msg_1789819973671_tb9kbyafp", "2026-09-19T12:12:54.001Z"),
206
+ stored("msg_0b9957171001uZEXtFUs3gMrcW", "2026-09-19T12:12:54.004Z"),
207
+ stored("01a0cd36-50bc-7290-a994-a624afbd6237", "2026-09-19T12:12:55.000Z"),
208
+ stored("msg_0b99af9cb001MoZWG3voc2QESs", "2026-09-19T12:18:56.590Z"),
209
+ stored("draft_msg_1790147439170_uljl6rhxk:initial-message", null),
210
+ ];
211
+ assert.deepEqual(
212
+ [...replayDuplicateMessageIds(rows)].sort(),
213
+ ["01a0cd36-50bc-7290-a994-a624afbd6237", "msg_0b9957171001uZEXtFUs3gMrcW"],
214
+ );
215
+ assert.equal(replayDuplicateMessageIds(rows.slice(1, 4)).size, 0, "no live rows, nothing to pair");
216
+ });
217
+
218
+ test("anonymous replays drop as many newest rows as live prompts sent before them (075)", () => {
219
+ const replayAt = "2026-09-20T08:19:03.031Z";
220
+ const rows = [
221
+ stored("msg_1789739523165_q19qrk03i", "2026-09-18T13:52:15.236Z"),
222
+ stored("msg_1789739600000_abcdefghi", "2026-09-18T13:53:20.000Z"),
223
+ stored("canonical:1", replayAt, { seq: 1 }),
224
+ stored("canonical:2", replayAt, { seq: 5 }),
225
+ stored("canonical:3", replayAt, { seq: 9 }),
226
+ stored("msg_1790000000000_later0000", "2026-09-20T09:00:00.000Z"),
227
+ ];
228
+ assert.deepEqual([...replayDuplicateMessageIds(rows)].sort(), ["canonical:2", "canonical:3"]);
229
+ });
230
+
231
+ for (const driver of ["sqlite", "jsonl"] as const) {
232
+ test(`${driver}: replay duplicates are pruned and stay pruned after reopen (075)`, () => {
233
+ const dir = mkdtempSync(join(tmpdir(), "activity-dedupe-"));
234
+ try {
235
+ const store = createUsageStore({ dir, driver });
236
+ store.upsertUserMessages([
237
+ stored("msg_1789819973671_tb9kbyafp", "2026-09-19T12:12:54.001Z"),
238
+ stored("msg_0b9957171001uZEXtFUs3gMrcW", "2026-09-19T12:12:54.004Z"),
239
+ ]);
240
+ assert.equal(store.pruneReplayDuplicateMessages("a1"), 1);
241
+ assert.equal(store.pruneReplayDuplicateMessages(), 0);
242
+ store.close();
243
+ const reopened = createUsageStore({ dir, driver });
244
+ assert.deepEqual(
245
+ reopened.selectUserMessages({ agentId: "a1" }).map(row => row.messageId),
246
+ ["msg_1789819973671_tb9kbyafp"],
247
+ );
248
+ reopened.close();
249
+ } finally { rmSync(dir, { recursive: true, force: true }); }
250
+ });
251
+ }
@@ -0,0 +1,52 @@
1
+ import type { UserMessageRow } from "./store.ts";
2
+
3
+ /** App client ids (`app/src/types/stream.ts`); provider ids never take this shape. */
4
+ const LIVE_MESSAGE_ID = /^(draft_)?msg_\d{13}_/;
5
+ const TIMED_REPLAY_WINDOW_MS = 2_000;
6
+ const ANONYMOUS_REPLAY_BATCH_MS = 60_000;
7
+
8
+ function time(value: string | null): number | null {
9
+ if (value == null) return null;
10
+ const parsed = Date.parse(value);
11
+ return Number.isNaN(parsed) ? null : parsed;
12
+ }
13
+
14
+ /**
15
+ * Replayed copies of prompts already stored under their live client id, for one
16
+ * agent's rows. The host keeps the provider id of a live prompt internal, so a
17
+ * replay after reload arrives under a different key (075).
18
+ */
19
+ export function replayDuplicateMessageIds(rows: readonly UserMessageRow[]): Set<string> {
20
+ const duplicates = new Set<string>();
21
+ const live = rows.filter(row => LIVE_MESSAGE_ID.test(row.messageId));
22
+ if (live.length === 0) return duplicates;
23
+
24
+ const liveTimes = live.map(row => time(row.ts)).filter((t): t is number => t != null);
25
+ for (const row of rows) {
26
+ if (LIVE_MESSAGE_ID.test(row.messageId) || row.messageId.startsWith("canonical:")) continue;
27
+ const t = time(row.ts);
28
+ if (t != null && liveTimes.some(liveTime => Math.abs(t - liveTime) <= TIMED_REPLAY_WINDOW_MS)) {
29
+ duplicates.add(row.messageId);
30
+ }
31
+ }
32
+
33
+ const anonymous = rows
34
+ .filter(row => row.messageId.startsWith("canonical:"))
35
+ .map(row => ({ row, t: time(row.ts ?? row.ingestedAt) }))
36
+ .filter((entry): entry is { row: UserMessageRow; t: number } => entry.t != null);
37
+ if (anonymous.length === 0) return duplicates;
38
+ const batchStart = Math.min(...anonymous.map(entry => entry.t));
39
+ // Anonymous replays carry the replay instant, so only a count of the live
40
+ // prompts sent before it can pair them; the newest replayed ones are dropped.
41
+ const liveBefore = live.filter(row => {
42
+ const t = time(row.ts ?? row.ingestedAt);
43
+ return t != null && t < batchStart;
44
+ }).length;
45
+ const batch = anonymous
46
+ .filter(entry => entry.t <= batchStart + ANONYMOUS_REPLAY_BATCH_MS)
47
+ .sort((a, b) => (a.row.seq ?? -1) - (b.row.seq ?? -1));
48
+ for (const { row } of batch.slice(batch.length - Math.min(liveBefore, batch.length))) {
49
+ duplicates.add(row.messageId);
50
+ }
51
+ return duplicates;
52
+ }