@koinzhang/paseo-plugin-activity 0.5.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.
- package/CHANGELOG.md +78 -1
- package/README.md +15 -8
- package/client/activity-heatmap.tsx +126 -93
- package/client/agent-creations.tsx +216 -0
- package/client/attention-pill.tsx +16 -5
- package/client/attention-popover.tsx +19 -23
- package/client/color-mix.test.ts +27 -0
- package/client/color-mix.ts +38 -0
- package/client/design-tokens.test.ts +39 -0
- package/client/design-tokens.ts +168 -0
- package/client/fit-text.test.ts +41 -0
- package/client/fit-text.ts +33 -0
- package/client/formatted-time.tsx +4 -4
- package/client/global-surface.tsx +316 -275
- package/client/header-button.ts +136 -0
- package/client/hourly-activity-timeline.tsx +425 -0
- package/client/measured-width.ts +72 -0
- package/client/panel-visibility.test.ts +25 -0
- package/client/panel-visibility.ts +45 -0
- package/client/panel.tsx +83 -108
- package/client/provider-dropdown.tsx +131 -0
- package/client/provider-filter.test.ts +17 -13
- package/client/provider-filter.ts +5 -7
- package/client/range.test.ts +44 -0
- package/client/range.ts +14 -0
- package/client/rank-color.test.ts +108 -14
- package/client/rank-color.ts +261 -48
- package/client/ranking-bars.tsx +291 -0
- package/client/ui.tsx +339 -0
- package/client/usage-popover.tsx +62 -134
- package/client/usage-stats.tsx +137 -8
- package/client/use-agent-turn-end.ts +2 -1
- package/client/use-app-language.ts +17 -0
- package/client/web.ts +73 -18
- package/client/workspace/agent-row.tsx +18 -25
- package/client/workspace/agents-section.tsx +23 -20
- package/client/workspace/constants.ts +6 -6
- package/client/workspace/display-menu.tsx +5 -4
- package/client/workspace/filters.test.ts +1 -1
- package/client/workspace/filters.ts +4 -2
- package/client/workspace/panel.tsx +176 -104
- package/client/workspace/rank-section.tsx +157 -44
- package/client/workspace/terminals-section.tsx +13 -9
- package/index.client.tsx +40 -20
- package/index.server.ts +63 -31
- package/package.json +2 -2
- package/paseo-plugin.json +2 -1
- package/server/agents.ts +20 -2
- package/server/background-sync.test.ts +43 -0
- package/server/background-sync.ts +43 -4
- package/server/handlers-query.test.ts +252 -1
- package/server/handlers.ts +174 -13
- package/server/ingest.test.ts +8 -0
- package/server/messages.test.ts +96 -1
- package/server/prompt-dedupe.ts +52 -0
- package/server/rpc-cache.test.ts +74 -0
- package/server/rpc-cache.ts +48 -0
- package/server/store.test.ts +122 -0
- package/server/store.ts +313 -19
- package/server/ttl-cache.ts +3 -0
- package/shared/activity.test.ts +159 -6
- package/shared/activity.ts +140 -5
- package/shared/classify.test.ts +1 -0
- package/shared/classify.ts +4 -1
- package/shared/explorer-agent-display.test.ts +61 -0
- package/shared/explorer-agent-display.ts +21 -2
- package/shared/format.test.ts +28 -3
- package/shared/format.ts +25 -2
- package/shared/i18n.test.ts +34 -0
- package/shared/i18n.ts +363 -0
- package/shared/insights.test.ts +162 -80
- package/shared/insights.ts +136 -61
- package/shared/usage.test.ts +330 -0
- package/shared/usage.ts +471 -0
package/server/handlers.ts
CHANGED
|
@@ -5,8 +5,11 @@ import { homedir } from "node:os";
|
|
|
5
5
|
import { basename, dirname, resolve, sep } from "node:path";
|
|
6
6
|
import { realpathSync, statSync } from "node:fs";
|
|
7
7
|
import {
|
|
8
|
+
aggregateAgentCreations,
|
|
8
9
|
aggregateAgents,
|
|
10
|
+
aggregateByProject,
|
|
9
11
|
aggregateByProvider,
|
|
12
|
+
aggregateActivityByHour,
|
|
10
13
|
aggregateMcpByTool,
|
|
11
14
|
aggregateShellTop,
|
|
12
15
|
aggregateSkillsByName,
|
|
@@ -14,14 +17,23 @@ import {
|
|
|
14
17
|
isFileRead,
|
|
15
18
|
isFileWrite,
|
|
16
19
|
isShellCall,
|
|
20
|
+
pickLongestAgentLifetime,
|
|
21
|
+
averageEngagedSessionMs,
|
|
22
|
+
countMultiTurnSessions,
|
|
17
23
|
usageActivityByDayRpc,
|
|
24
|
+
usageActivityByHourRpc,
|
|
25
|
+
usageAgentCreationsRpc,
|
|
26
|
+
usageAgentLifetimeRpc,
|
|
18
27
|
usageAgentsRpc,
|
|
19
28
|
usageAgentUnarchiveRpc,
|
|
29
|
+
usageByProjectRpc,
|
|
20
30
|
usageByProviderRpc,
|
|
21
31
|
usageExportRpc,
|
|
22
32
|
usageListRpc,
|
|
23
33
|
usageMcpByToolRpc,
|
|
24
34
|
usageReadSkillRpc,
|
|
35
|
+
usageRecentMcpCallsRpc,
|
|
36
|
+
usageRecentSkillCallsRpc,
|
|
25
37
|
usageSkillsByNameRpc,
|
|
26
38
|
usageSummaryRpc,
|
|
27
39
|
} from "../shared/usage.ts";
|
|
@@ -122,16 +134,12 @@ export function createListHandler(store: UsageStore) {
|
|
|
122
134
|
from: input.from,
|
|
123
135
|
to: input.to,
|
|
124
136
|
};
|
|
125
|
-
const
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
return tb.localeCompare(ta);
|
|
137
|
+
const page = store.selectRecent(filter, {
|
|
138
|
+
limit: input.limit ?? 200,
|
|
139
|
+
offset: input.offset ?? 0,
|
|
129
140
|
});
|
|
130
|
-
const offset = input.offset ?? 0;
|
|
131
|
-
const limit = input.limit ?? 200;
|
|
132
|
-
const page = matched.slice(offset, offset + limit);
|
|
133
141
|
return {
|
|
134
|
-
total:
|
|
142
|
+
total: store.countRows(filter),
|
|
135
143
|
rows: page.map((row) => ({
|
|
136
144
|
agentId: row.agentId,
|
|
137
145
|
callId: row.callId,
|
|
@@ -191,6 +199,57 @@ export function createSkillsByNameHandler(store: UsageStore) {
|
|
|
191
199
|
};
|
|
192
200
|
}
|
|
193
201
|
|
|
202
|
+
export function createRecentSkillCallsHandler(store: UsageStore) {
|
|
203
|
+
return async (
|
|
204
|
+
input: RpcInput<typeof usageRecentSkillCallsRpc>,
|
|
205
|
+
): Promise<RpcOutput<typeof usageRecentSkillCallsRpc>> => {
|
|
206
|
+
const titles = new Map(
|
|
207
|
+
store
|
|
208
|
+
.selectAgents({ workspaceId: input.workspaceId })
|
|
209
|
+
.map((agent) => [agent.agentId, agent.title?.trim() || null] as const),
|
|
210
|
+
);
|
|
211
|
+
const items = store
|
|
212
|
+
.selectRecent(
|
|
213
|
+
{ workspaceId: input.workspaceId, category: "skill" },
|
|
214
|
+
{ limit: input.limit ?? 8, scope: "skill-named" },
|
|
215
|
+
)
|
|
216
|
+
.map((row) => ({
|
|
217
|
+
agentId: row.agentId,
|
|
218
|
+
agentTitle: titles.get(row.agentId) ?? null,
|
|
219
|
+
callId: row.callId,
|
|
220
|
+
skillName: row.skillName!.trim(),
|
|
221
|
+
calledAt: row.ts ?? row.ingestedAt,
|
|
222
|
+
}));
|
|
223
|
+
return { items };
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export function createRecentMcpCallsHandler(store: UsageStore) {
|
|
228
|
+
return async (
|
|
229
|
+
input: RpcInput<typeof usageRecentMcpCallsRpc>,
|
|
230
|
+
): Promise<RpcOutput<typeof usageRecentMcpCallsRpc>> => {
|
|
231
|
+
const titles = new Map(
|
|
232
|
+
store
|
|
233
|
+
.selectAgents({ workspaceId: input.workspaceId })
|
|
234
|
+
.map((agent) => [agent.agentId, agent.title?.trim() || null] as const),
|
|
235
|
+
);
|
|
236
|
+
const items = store
|
|
237
|
+
.selectRecent(
|
|
238
|
+
{ workspaceId: input.workspaceId, category: "mcp" },
|
|
239
|
+
{ limit: input.limit ?? 8, scope: "mcp-named" },
|
|
240
|
+
)
|
|
241
|
+
.map((row) => ({
|
|
242
|
+
agentId: row.agentId,
|
|
243
|
+
agentTitle: titles.get(row.agentId) ?? null,
|
|
244
|
+
callId: row.callId,
|
|
245
|
+
server: row.mcpServer!.trim(),
|
|
246
|
+
tool: row.mcpTool!.trim(),
|
|
247
|
+
calledAt: row.ts ?? row.ingestedAt,
|
|
248
|
+
}));
|
|
249
|
+
return { items };
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
194
253
|
export function createMcpByToolHandler(store: UsageStore) {
|
|
195
254
|
return async (
|
|
196
255
|
input: RpcInput<typeof usageMcpByToolRpc>,
|
|
@@ -255,6 +314,64 @@ export function createAgentsHandler(store: UsageStore) {
|
|
|
255
314
|
};
|
|
256
315
|
}
|
|
257
316
|
|
|
317
|
+
/** Longest created→archived agent (049) plus engaged time and multi-turn counts (072). */
|
|
318
|
+
export function createAgentLifetimeHandler(store: UsageStore) {
|
|
319
|
+
return async (
|
|
320
|
+
input: RpcInput<typeof usageAgentLifetimeRpc>,
|
|
321
|
+
): Promise<RpcOutput<typeof usageAgentLifetimeRpc>> => {
|
|
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) };
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
|
|
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
|
+
|
|
362
|
+
export function createAgentCreationsHandler(store: UsageStore) {
|
|
363
|
+
return async (
|
|
364
|
+
input: RpcInput<typeof usageAgentCreationsRpc>,
|
|
365
|
+
): Promise<RpcOutput<typeof usageAgentCreationsRpc>> => {
|
|
366
|
+
const agents = store.selectAgents({
|
|
367
|
+
provider: input.provider,
|
|
368
|
+
from: input.from,
|
|
369
|
+
to: input.to,
|
|
370
|
+
});
|
|
371
|
+
return { days: aggregateAgentCreations(agents, input) };
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
|
|
258
375
|
/**
|
|
259
376
|
* 0.8 SDK has no reload API (handle.refresh is a read). Run CLI on this daemon's
|
|
260
377
|
* machine, inheriting PATH and PASEO_HOME / PASEO_HOST / PASEO_LISTEN. CLI also
|
|
@@ -266,7 +383,7 @@ export function createUnarchiveAgentHandler(store: UsageStore) {
|
|
|
266
383
|
input: RpcInput<typeof usageAgentUnarchiveRpc>,
|
|
267
384
|
): Promise<RpcOutput<typeof usageAgentUnarchiveRpc>> => {
|
|
268
385
|
try {
|
|
269
|
-
await execFileAsync("paseo", ["agent", "reload", input.agentId], {
|
|
386
|
+
await execFileAsync("paseo", ["agent", "reload", "--", input.agentId], {
|
|
270
387
|
timeout: 120_000,
|
|
271
388
|
maxBuffer: 1024 * 1024,
|
|
272
389
|
});
|
|
@@ -314,6 +431,33 @@ export function createActivityByDayHandler(store: UsageStore) {
|
|
|
314
431
|
};
|
|
315
432
|
}
|
|
316
433
|
|
|
434
|
+
export function createActivityByHourHandler(
|
|
435
|
+
store: UsageStore,
|
|
436
|
+
now: () => Date = () => new Date(),
|
|
437
|
+
) {
|
|
438
|
+
return async (
|
|
439
|
+
input: RpcInput<typeof usageActivityByHourRpc>,
|
|
440
|
+
): Promise<RpcOutput<typeof usageActivityByHourRpc>> => {
|
|
441
|
+
const end = now();
|
|
442
|
+
const endMs = end.getTime();
|
|
443
|
+
const currentHourMs = Math.floor(endMs / (60 * 60 * 1000)) * 60 * 60 * 1000;
|
|
444
|
+
const start = new Date(currentHourMs - (input.hours - 1) * 60 * 60 * 1000);
|
|
445
|
+
const filter = {
|
|
446
|
+
from: start.toISOString(),
|
|
447
|
+
to: end.toISOString(),
|
|
448
|
+
};
|
|
449
|
+
return {
|
|
450
|
+
hours: aggregateActivityByHour(store.select(filter), {
|
|
451
|
+
start,
|
|
452
|
+
hours: input.hours,
|
|
453
|
+
provider: input.provider,
|
|
454
|
+
agents: store.selectAgents({ ...filter, provider: input.provider }),
|
|
455
|
+
messages: store.selectUserMessages(filter),
|
|
456
|
+
}),
|
|
457
|
+
};
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
|
|
317
461
|
const MAX_SKILL_BYTES = 512 * 1024;
|
|
318
462
|
|
|
319
463
|
function isPathInside(absolute: string, root: string): boolean {
|
|
@@ -322,9 +466,12 @@ function isPathInside(absolute: string, root: string): boolean {
|
|
|
322
466
|
return abs === base || abs.startsWith(base.endsWith(sep) ? base : `${base}${sep}`);
|
|
323
467
|
}
|
|
324
468
|
|
|
469
|
+
function isSkillFileName(path: string): boolean {
|
|
470
|
+
return /\/SKILL\.md$/i.test(path.replace(/\\/g, "/"));
|
|
471
|
+
}
|
|
472
|
+
|
|
325
473
|
function assertAllowedSkillPath(absolute: string, homeDir: string): string {
|
|
326
|
-
|
|
327
|
-
if (!/\/SKILL\.md$/i.test(normalized)) {
|
|
474
|
+
if (!isSkillFileName(absolute)) {
|
|
328
475
|
throw new Error("Skill path must end with SKILL.md");
|
|
329
476
|
}
|
|
330
477
|
let real = absolute;
|
|
@@ -333,6 +480,11 @@ function assertAllowedSkillPath(absolute: string, homeDir: string): string {
|
|
|
333
480
|
} catch {
|
|
334
481
|
throw new Error("Skill file not found");
|
|
335
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
|
+
}
|
|
336
488
|
const roots = buildHomeSkillRoots(homeDir);
|
|
337
489
|
const underHome =
|
|
338
490
|
roots.some((root) => isPathInside(absolute, root) || isPathInside(real, root));
|
|
@@ -527,6 +679,7 @@ export async function resyncAgents(
|
|
|
527
679
|
updatedAt?: string;
|
|
528
680
|
lastUserMessageAt?: string | null;
|
|
529
681
|
} }>,
|
|
682
|
+
options: { incremental?: boolean } = {},
|
|
530
683
|
): Promise<HistoryScanResult> {
|
|
531
684
|
if (signal?.aborted) throw new Error("History scan canceled");
|
|
532
685
|
const homeDir = homedir();
|
|
@@ -564,8 +717,10 @@ export async function resyncAgents(
|
|
|
564
717
|
});
|
|
565
718
|
let pageInserted = 0;
|
|
566
719
|
|
|
567
|
-
//
|
|
568
|
-
//
|
|
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.
|
|
569
724
|
let page = await timeline.refetch({
|
|
570
725
|
projection: "canonical",
|
|
571
726
|
direction: "tail",
|
|
@@ -579,6 +734,10 @@ export async function resyncAgents(
|
|
|
579
734
|
// Timeline replacement reshuffles seq; drop hash-keyed anonymous messages.
|
|
580
735
|
store.deleteCanonicalUserMessages(agent.id);
|
|
581
736
|
}
|
|
737
|
+
const stopAtSeq =
|
|
738
|
+
options.incremental && newest && previous && previous.epoch === newest.epoch
|
|
739
|
+
? previous.lastSeq
|
|
740
|
+
: null;
|
|
582
741
|
for (;;) {
|
|
583
742
|
if (signal?.aborted) throw new Error("History scan canceled");
|
|
584
743
|
pageInserted += ingestCanonicalPage(
|
|
@@ -590,6 +749,7 @@ export async function resyncAgents(
|
|
|
590
749
|
model,
|
|
591
750
|
);
|
|
592
751
|
if (!page.hasOlder || !page.startCursor) break;
|
|
752
|
+
if (stopAtSeq != null && page.startCursor.seq <= stopAtSeq) break;
|
|
593
753
|
page = await timeline.refetch({
|
|
594
754
|
projection: "canonical",
|
|
595
755
|
direction: "before",
|
|
@@ -598,6 +758,7 @@ export async function resyncAgents(
|
|
|
598
758
|
});
|
|
599
759
|
if (page.error) throw new Error(page.error);
|
|
600
760
|
}
|
|
761
|
+
store.pruneReplayDuplicateMessages(agent.id);
|
|
601
762
|
if (newest) store.setSyncState(agent.id, newest.epoch, newest.seq);
|
|
602
763
|
|
|
603
764
|
syncedAgents += 1;
|
package/server/ingest.test.ts
CHANGED
|
@@ -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
|
}
|
package/server/messages.test.ts
CHANGED
|
@@ -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
|
+
}
|