@koinzhang/paseo-plugin-activity 0.6.0 → 0.7.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 (62) hide show
  1. package/CHANGELOG.md +35 -1
  2. package/README.md +14 -7
  3. package/client/activity-heatmap.tsx +115 -74
  4. package/client/agent-creations.tsx +97 -88
  5. package/client/attention-pill.tsx +16 -5
  6. package/client/attention-popover.tsx +19 -23
  7. package/client/design-tokens.test.ts +39 -0
  8. package/client/design-tokens.ts +168 -0
  9. package/client/formatted-time.tsx +4 -4
  10. package/client/global-surface.tsx +236 -268
  11. package/client/header-button.ts +136 -0
  12. package/client/hourly-activity-timeline.tsx +136 -103
  13. package/client/panel-visibility.test.ts +25 -0
  14. package/client/panel-visibility.ts +45 -0
  15. package/client/panel.tsx +83 -108
  16. package/client/provider-dropdown.tsx +131 -0
  17. package/client/provider-filter.test.ts +17 -13
  18. package/client/provider-filter.ts +5 -7
  19. package/client/rank-color.ts +3 -3
  20. package/client/ranking-bars.tsx +291 -0
  21. package/client/ui.tsx +339 -0
  22. package/client/usage-popover.tsx +62 -134
  23. package/client/usage-stats.tsx +29 -11
  24. package/client/use-agent-turn-end.ts +2 -1
  25. package/client/use-app-language.ts +17 -0
  26. package/client/web.ts +73 -18
  27. package/client/workspace/agent-row.tsx +18 -25
  28. package/client/workspace/agents-section.tsx +23 -20
  29. package/client/workspace/constants.ts +6 -6
  30. package/client/workspace/display-menu.tsx +5 -4
  31. package/client/workspace/filters.test.ts +1 -1
  32. package/client/workspace/filters.ts +4 -2
  33. package/client/workspace/panel.tsx +89 -103
  34. package/client/workspace/rank-section.tsx +36 -62
  35. package/client/workspace/terminals-section.tsx +13 -9
  36. package/index.client.tsx +40 -20
  37. package/index.server.ts +53 -51
  38. package/package.json +2 -2
  39. package/paseo-plugin.json +2 -1
  40. package/server/agents.ts +20 -2
  41. package/server/background-sync.ts +34 -4
  42. package/server/handlers-query.test.ts +27 -1
  43. package/server/handlers.ts +75 -31
  44. package/server/ingest.test.ts +8 -0
  45. package/server/messages.test.ts +96 -1
  46. package/server/prompt-dedupe.ts +52 -0
  47. package/server/rpc-cache.test.ts +74 -0
  48. package/server/rpc-cache.ts +48 -0
  49. package/server/store.test.ts +122 -0
  50. package/server/store.ts +313 -19
  51. package/server/ttl-cache.ts +3 -0
  52. package/shared/activity.test.ts +36 -0
  53. package/shared/activity.ts +37 -0
  54. package/shared/classify.test.ts +1 -10
  55. package/shared/classify.ts +3 -10
  56. package/shared/format.ts +10 -7
  57. package/shared/i18n.test.ts +34 -0
  58. package/shared/i18n.ts +363 -0
  59. package/shared/insights.test.ts +120 -81
  60. package/shared/insights.ts +124 -63
  61. package/shared/usage.test.ts +121 -0
  62. package/shared/usage.ts +191 -2
@@ -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;
@@ -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
+ }
@@ -0,0 +1,74 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { createRpcCache } from "./rpc-cache.ts";
4
+
5
+ function fixture(options: { ttlMs?: number; maxEntries?: number } = {}) {
6
+ let generation = 0;
7
+ let clock = 0;
8
+ let calls = 0;
9
+ const cache = createRpcCache({
10
+ generation: () => generation,
11
+ now: () => clock,
12
+ ...options,
13
+ });
14
+ const handler = cache.wrap("usage.test", async (input: { n: number }) => {
15
+ calls += 1;
16
+ return input.n * 2;
17
+ });
18
+ return {
19
+ handler,
20
+ cache,
21
+ calls: () => calls,
22
+ bump: () => { generation += 1; },
23
+ advance: (ms: number) => { clock += ms; },
24
+ };
25
+ }
26
+
27
+ test("identical input hits the cache; different input does not", async () => {
28
+ const f = fixture();
29
+ assert.equal(await f.handler({ n: 1 }, undefined), 2);
30
+ assert.equal(await f.handler({ n: 1 }, undefined), 2);
31
+ assert.equal(f.calls(), 1);
32
+ await f.handler({ n: 2 }, undefined);
33
+ assert.equal(f.calls(), 2);
34
+ });
35
+
36
+ test("store writes and TTL expiry invalidate", async () => {
37
+ const f = fixture({ ttlMs: 1_000 });
38
+ await f.handler({ n: 1 }, undefined);
39
+ f.bump();
40
+ await f.handler({ n: 1 }, undefined);
41
+ assert.equal(f.calls(), 2);
42
+ f.advance(999);
43
+ await f.handler({ n: 1 }, undefined);
44
+ assert.equal(f.calls(), 2);
45
+ f.advance(1);
46
+ await f.handler({ n: 1 }, undefined);
47
+ assert.equal(f.calls(), 3);
48
+ });
49
+
50
+ test("evicts least recently used entries beyond the cap", async () => {
51
+ const f = fixture({ maxEntries: 2 });
52
+ await f.handler({ n: 1 }, undefined);
53
+ await f.handler({ n: 2 }, undefined);
54
+ await f.handler({ n: 1 }, undefined);
55
+ await f.handler({ n: 3 }, undefined);
56
+ assert.equal(f.calls(), 3);
57
+ await f.handler({ n: 1 }, undefined);
58
+ assert.equal(f.calls(), 3, "recently used entry survives");
59
+ await f.handler({ n: 2 }, undefined);
60
+ assert.equal(f.calls(), 4, "least recently used entry was evicted");
61
+ });
62
+
63
+ test("rejected results are not cached", async () => {
64
+ let calls = 0;
65
+ const cache = createRpcCache({ generation: () => 0 });
66
+ const handler = cache.wrap("usage.fail", async () => {
67
+ calls += 1;
68
+ if (calls === 1) throw new Error("boom");
69
+ return "ok";
70
+ });
71
+ await assert.rejects(handler({}, undefined), /boom/);
72
+ assert.equal(await handler({}, undefined), "ok");
73
+ assert.equal(calls, 2);
74
+ });
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Memoize read RPC results until the store is written or the TTL passes.
3
+ *
4
+ * Panels poll every 15s with identical inputs; without this each poll re-reads
5
+ * and re-aggregates whole tables synchronously on the plugin process.
6
+ */
7
+ export function createRpcCache(options: {
8
+ generation: () => number;
9
+ ttlMs?: number;
10
+ maxEntries?: number;
11
+ now?: () => number;
12
+ }) {
13
+ const ttlMs = options.ttlMs ?? 30_000;
14
+ const maxEntries = options.maxEntries ?? 64;
15
+ const now = options.now ?? Date.now;
16
+ const entries = new Map<string, { generation: number; at: number; value: Promise<unknown> }>();
17
+
18
+ function wrap<I, C, O>(
19
+ name: string,
20
+ handler: (input: I, context: C) => Promise<O>,
21
+ ): (input: I, context: C) => Promise<O> {
22
+ return (input, context) => {
23
+ const key = `${name}\0${JSON.stringify(input ?? null)}`;
24
+ const generation = options.generation();
25
+ const at = now();
26
+ const hit = entries.get(key);
27
+ if (hit && hit.generation === generation && at - hit.at < ttlMs) {
28
+ entries.delete(key);
29
+ entries.set(key, hit);
30
+ return hit.value as Promise<O>;
31
+ }
32
+ const value = handler(input, context);
33
+ entries.delete(key);
34
+ entries.set(key, { generation, at, value });
35
+ value.catch(() => {
36
+ if (entries.get(key)?.value === value) entries.delete(key);
37
+ });
38
+ while (entries.size > maxEntries) {
39
+ const oldest = entries.keys().next().value;
40
+ if (oldest === undefined) break;
41
+ entries.delete(oldest);
42
+ }
43
+ return value;
44
+ };
45
+ }
46
+
47
+ return { wrap, clear: () => entries.clear() };
48
+ }
@@ -232,3 +232,125 @@ test("sqlite: epoch replace deletes canonical user messages", () => {
232
232
  assert.equal(store.selectUserMessages({ agentId: "agent-1" })[0]?.messageId, "real-id");
233
233
  store.close();
234
234
  });
235
+
236
+ for (const driver of ["sqlite", "jsonl"] as const) {
237
+ test(`${driver}: selectRecent / countRows page newest-first with scopes (064)`, () => {
238
+ const store = createUsageStore({ dir: tempDir(), driver });
239
+ store.upsertMany([
240
+ row({ callId: "a", ts: "2026-09-18T01:00:00.000Z", category: "skill", skillName: "alpha", confidence: "exact" }),
241
+ row({ callId: "b", ts: "2026-09-18T03:00:00.000Z", category: "skill", skillName: "low", confidence: "low" }),
242
+ row({ callId: "c", ts: "2026-09-18T02:00:00.000Z", category: "skill", skillName: " ", confidence: "exact" }),
243
+ row({ callId: "d", ts: null, ingestedAt: "2026-09-18T04:00:00.000Z", category: "skill", skillName: "beta", confidence: "inferred" }),
244
+ row({ callId: "e", ts: "2026-09-18T05:00:00.000Z", workspaceId: "ws-2", category: "skill", skillName: "other", confidence: "exact" }),
245
+ row({ callId: "f", ts: "2026-09-18T02:00:00.000Z", category: "mcp", mcpServer: "paseo", mcpTool: "list" }),
246
+ row({ callId: "g", ts: "2026-09-18T06:00:00.000Z", category: "mcp", mcpServer: "paseo", mcpTool: null }),
247
+ ]);
248
+ const skill = { workspaceId: "ws-1", category: "skill" as const };
249
+ assert.deepEqual(
250
+ store.selectRecent(skill, { limit: 10, scope: "skill-named" }).map((r) => r.callId),
251
+ ["d", "a"],
252
+ );
253
+ assert.deepEqual(
254
+ store.selectRecent({ workspaceId: "ws-1", category: "mcp" }, { limit: 10, scope: "mcp-named" })
255
+ .map((r) => r.callId),
256
+ ["f"],
257
+ );
258
+ assert.deepEqual(
259
+ store.selectRecent({ workspaceId: "ws-1" }, { limit: 2, offset: 1 }).map((r) => r.callId),
260
+ ["d", "b"],
261
+ );
262
+ assert.equal(store.countRows({ workspaceId: "ws-1" }), 6);
263
+ assert.equal(store.countRows(skill), 4);
264
+ store.close();
265
+ });
266
+
267
+ test(`${driver}: generation, activity spans and terminal call ids (064)`, () => {
268
+ const store = createUsageStore({ dir: tempDir(), driver });
269
+ const g0 = store.generation();
270
+ store.upsertMany([
271
+ row({ callId: "x", ts: "2026-09-18T05:00:00.000Z", status: "completed", provider: "codex", workspaceId: "late" }),
272
+ row({ callId: "y", ts: "2026-09-18T01:00:00.000Z", status: "running", provider: "claude", workspaceId: "early" }),
273
+ row({ agentId: "agent-2", callId: "z", ts: "2026-09-18T02:00:00.000Z", status: "failed" }),
274
+ ]);
275
+ assert.ok(store.generation() > g0);
276
+ const g1 = store.generation();
277
+ store.select();
278
+ assert.equal(store.generation(), g1, "reads do not bump generation");
279
+ const spans = store.agentActivitySpans().sort((a, b) => a.agentId.localeCompare(b.agentId));
280
+ assert.deepEqual(spans[0], {
281
+ agentId: "agent-1",
282
+ provider: "claude",
283
+ workspaceId: "early",
284
+ firstAt: "2026-09-18T01:00:00.000Z",
285
+ lastAt: "2026-09-18T05:00:00.000Z",
286
+ });
287
+ assert.equal(spans.length, 2);
288
+ assert.deepEqual([...store.terminalCallIds("agent-1")], ["x"]);
289
+ assert.deepEqual([...store.terminalCallIds("agent-2")], ["z"]);
290
+ store.close();
291
+ });
292
+
293
+ test(`${driver}: rescans keep the earliest event time, never after first ingest (074)`, () => {
294
+ const store = createUsageStore({ dir: tempDir(), driver });
295
+ const ts = (callId: string) => store.getRow("agent-1", callId)?.ts ?? null;
296
+ store.upsertMany([
297
+ row({ callId: "known", ts: "2026-09-18T10:00:00.000Z" }),
298
+ row({ callId: "live", ts: null }),
299
+ row({ callId: "live-real", ts: null }),
300
+ ]);
301
+ store.upsertMany([
302
+ row({ callId: "known", ts: "2026-09-20T08:00:00.000Z", ingestedAt: "2026-09-20T08:00:01.000Z" }),
303
+ row({ callId: "live", ts: "2026-09-20T08:00:00.000Z", ingestedAt: "2026-09-20T08:00:01.000Z" }),
304
+ row({ callId: "live-real", ts: "2026-09-18T11:30:00.000Z" }),
305
+ ]);
306
+ assert.equal(ts("known"), "2026-09-18T10:00:00.000Z");
307
+ assert.equal(ts("live"), null);
308
+ assert.equal(ts("live-real"), "2026-09-18T11:30:00.000Z");
309
+ store.upsertMany([row({ callId: "known", ts: "2026-09-18T09:00:00.000Z" }), row({ callId: "known", ts: null })]);
310
+ assert.equal(ts("known"), "2026-09-18T09:00:00.000Z");
311
+
312
+ const message = {
313
+ agentId: "agent-1",
314
+ messageId: "m1",
315
+ workspaceId: "ws",
316
+ provider: "cursor",
317
+ model: null,
318
+ turnId: null,
319
+ seq: 1,
320
+ ts: null,
321
+ ingestedAt: "2026-09-18T12:00:00.000Z",
322
+ };
323
+ store.upsertUserMessages([message]);
324
+ store.upsertUserMessages([{ ...message, ts: "2026-09-20T08:00:00.000Z", ingestedAt: "2026-09-20T08:00:01.000Z" }]);
325
+ assert.equal(store.selectUserMessages({ agentId: "agent-1" })[0]?.ts, null);
326
+ store.upsertUserMessages([{ ...message, ts: "2026-09-18T11:00:00.000Z" }]);
327
+ assert.equal(store.selectUserMessages({ agentId: "agent-1" })[0]?.ts, "2026-09-18T11:00:00.000Z");
328
+ store.close();
329
+ });
330
+
331
+ test(`${driver}: reopening clears event times later than first ingest (074)`, () => {
332
+ const dir = tempDir();
333
+ const store = createUsageStore({ dir, driver });
334
+ store.upsertMany([
335
+ row({ callId: "stamped", ts: "2026-09-20T08:00:00.000Z" }),
336
+ row({ callId: "fine", ts: "2026-09-18T11:00:00.000Z" }),
337
+ ]);
338
+ store.upsertUserMessages([{
339
+ agentId: "agent-1",
340
+ messageId: "m1",
341
+ workspaceId: "ws",
342
+ provider: "cursor",
343
+ model: null,
344
+ turnId: null,
345
+ seq: 1,
346
+ ts: "2026-09-20T08:00:00.000Z",
347
+ ingestedAt: "2026-09-18T12:00:00.000Z",
348
+ }]);
349
+ store.close();
350
+ const reopened = createUsageStore({ dir, driver });
351
+ assert.equal(reopened.getRow("agent-1", "stamped")?.ts, null);
352
+ assert.equal(reopened.getRow("agent-1", "fine")?.ts, "2026-09-18T11:00:00.000Z");
353
+ assert.equal(reopened.selectUserMessages({ agentId: "agent-1" })[0]?.ts, null);
354
+ reopened.close();
355
+ });
356
+ }