@koinzhang/paseo-plugin-activity 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,21 @@ All notable changes to `@koinzhang/paseo-plugin-activity` are documented in this
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.8.1] - 2026-11-26
9
+
10
+ Requires Paseo **>= 0.17.4**.
11
+
12
+ ### Changed
13
+
14
+ - Pin the plugin SDK and its client / protocol peers to 0.17.4 in the development lockfile; older SDK types are no longer supported by this checkout.
15
+ - Read the latest complete turn with `timeline.refetch({ direction: "tail", limit: 1, wholeTurns: true })` and keep only entries matching the hook's `turnId`. Historical backfill retains its 500-item pages and checkpoints.
16
+
17
+ ### Fixed
18
+
19
+ - Restore the Workspace running ring's continuous rotation on Web by using the JS animation driver there; iOS and Android retain the native driver (088).
20
+ - Derive timeline item types from the actual refetch result instead of the removed `agent.turn.after.timeline` field.
21
+ - Await real turn ingestion in the hook and honor its cancellation signal, preventing late responses from writing after SQLite closes.
22
+
8
23
  ## [0.8.0] - 2026-11-05
9
24
 
10
25
  Requires Paseo **>= 0.15.0**.
@@ -202,7 +217,8 @@ Last release that supports Paseo **0.8.0**. Later versions require Paseo **>= 0.
202
217
  - Command Center entries: open panels and export a markdown usage report.
203
218
  - Plugin renamed from `tool-usage` to `activity`, migrating the old data directory automatically.
204
219
 
205
- [Unreleased]: https://github.com/koinzhang/paseo-plugins/compare/activity-v0.8.0...HEAD
220
+ [Unreleased]: https://github.com/koinzhang/paseo-plugins/compare/activity-v0.8.1...HEAD
221
+ [0.8.1]: https://github.com/koinzhang/paseo-plugins/releases/tag/activity-v0.8.1
206
222
  [0.8.0]: https://github.com/koinzhang/paseo-plugins/releases/tag/activity-v0.8.0
207
223
  [0.7.0]: https://github.com/koinzhang/paseo-plugins/releases/tag/activity-v0.7.0
208
224
  [0.6.0]: https://github.com/koinzhang/paseo-plugins/releases/tag/activity-v0.6.0
package/README.md CHANGED
@@ -37,15 +37,15 @@ Everything lives on the daemon machine in `~/.paseo/plugin-data/activity/` (SQLi
37
37
 
38
38
  ## Install
39
39
 
40
- Requires Paseo **>= 0.15.0**. Earlier releases keep working on older runtimes: **0.7.0** is the last release that supports Paseo 0.9–0.14, and **0.4.0** the last that supports 0.8.0.
40
+ The current checkout requires Paseo **>= 0.17.4** and pins `@getpaseo/plugin` to **0.17.4**. This is an unreleased compatibility update; earlier published versions retain their own requirements: **0.8.0** requires Paseo >=0.15.0, **0.7.0** supports Paseo 0.9–0.14, and **0.4.0** supports 0.8.0.
41
41
 
42
- From Git (Paseo 0.15 and later):
42
+ From Git (Paseo 0.17.4 and later):
43
43
 
44
44
  ```bash
45
45
  paseo plugin add github:koinzhang/paseo-plugins:activity
46
46
  ```
47
47
 
48
- From npm (Paseo 0.15 and later; this is the source paseo.cafe hands to Paseo). Pin `0.7.0` on Paseo 0.9–0.14, or `0.4.0` on Paseo 0.8:
48
+ From npm (this is the source paseo.cafe hands to Paseo; published releases may lag this checkout). Pin a release whose runtime requirement matches your host, such as `0.8.0` for Paseo 0.15+, `0.7.0` on Paseo 0.9–0.14, or `0.4.0` on Paseo 0.8:
49
49
 
50
50
  ```bash
51
51
  paseo plugin install npm:@koinzhang/paseo-plugin-activity
@@ -0,0 +1,3 @@
1
+ export function shouldUseNativeDriver(platform: string): boolean {
2
+ return platform !== "web";
3
+ }
@@ -0,0 +1,15 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { shouldUseNativeDriver } from "./running-indicator-motion.ts";
4
+
5
+ test("running ring uses JS animation on web (088)", () => {
6
+ assert.equal(shouldUseNativeDriver("web"), false);
7
+ });
8
+
9
+ test("running ring keeps native animation on iOS", () => {
10
+ assert.equal(shouldUseNativeDriver("ios"), true);
11
+ });
12
+
13
+ test("running ring keeps native animation on Android", () => {
14
+ assert.equal(shouldUseNativeDriver("android"), true);
15
+ });
@@ -1,6 +1,7 @@
1
1
  import { useEffect, useRef, type ReactNode } from "react";
2
- import { Animated, Easing, type ViewStyle } from "react-native";
2
+ import { Animated, Easing, Platform, type ViewStyle } from "react-native";
3
3
  import type { WorkspaceTheme } from "./constants.ts";
4
+ import { shouldUseNativeDriver } from "./running-indicator-motion.ts";
4
5
 
5
6
  const SPIN_SIZE = 10;
6
7
  const SPIN_DURATION_MS = 800;
@@ -21,7 +22,7 @@ export function RunningIndicator({
21
22
  toValue: 1,
22
23
  duration: SPIN_DURATION_MS,
23
24
  easing: Easing.linear,
24
- useNativeDriver: true,
25
+ useNativeDriver: shouldUseNativeDriver(Platform.OS),
25
26
  }),
26
27
  );
27
28
  animation.start();
package/index.server.ts CHANGED
@@ -123,20 +123,22 @@ export default function contribute(server: PluginServerContext) {
123
123
 
124
124
  const removeTurnEnded = server.addHook("agent.turn.after", async (event, context) => {
125
125
  void background.request(context.paseo);
126
- void (async () => {
127
- try {
128
- const rows = await ingestTurnAfter(store, context.paseo, event.agent, {
129
- homeDir: homedir(),
130
- });
131
- if (rows > 0) {
132
- console.log(
133
- `[activity] turn.after agent=${event.agent.id} rows=${rows} total=${store.count()}`,
134
- );
135
- }
136
- } catch (error) {
126
+ const signal = context.signal;
127
+ try {
128
+ const rows = await ingestTurnAfter(store, context.paseo, event.agent, event.turnId, {
129
+ homeDir: homedir(),
130
+ signal,
131
+ });
132
+ if (rows > 0 && !signal.aborted) {
133
+ console.log(
134
+ `[activity] turn.after agent=${event.agent.id} rows=${rows} total=${store.count()}`,
135
+ );
136
+ }
137
+ } catch (error) {
138
+ if (!signal.aborted) {
137
139
  console.error("[activity] failed to ingest agent.turn.after", error);
138
140
  }
139
- })();
141
+ }
140
142
  });
141
143
 
142
144
  return () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koinzhang/paseo-plugin-activity",
3
- "version": "0.8.0",
3
+ "version": "0.8.1",
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/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"
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 client/workspace/running-indicator.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.15.1",
28
+ "@getpaseo/plugin": "0.17.4",
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
@@ -2,6 +2,6 @@
2
2
  "id": "activity",
3
3
  "description": "Local usage analytics and workspace agent ops: Explorer fleet list, live attention, and terminals",
4
4
  "requirements": {
5
- "paseo": ">=0.15.0"
5
+ "paseo": ">=0.17.4"
6
6
  }
7
7
  }
@@ -57,6 +57,8 @@ describe("agentRowFromHook", () => {
57
57
  provider: "claude",
58
58
  cwd: "/tmp",
59
59
  title: "Hello",
60
+ background: false,
61
+ metadata: {},
60
62
  },
61
63
  { createdAt: "2026-09-18T00:00:00.000Z" },
62
64
  );
@@ -606,6 +606,8 @@ function agentFromSnapshot(agent: {
606
606
  provider: string;
607
607
  cwd: string;
608
608
  title?: string | null;
609
+ background?: PluginHookAgent["background"];
610
+ metadata?: PluginHookAgent["metadata"];
609
611
  }): PluginHookAgent {
610
612
  return {
611
613
  id: agent.id,
@@ -614,6 +616,8 @@ function agentFromSnapshot(agent: {
614
616
  provider: agent.provider,
615
617
  cwd: agent.cwd,
616
618
  title: agent.title ?? null,
619
+ background: agent.background ?? false,
620
+ metadata: agent.metadata ?? {},
617
621
  };
618
622
  }
619
623
 
@@ -678,6 +682,8 @@ export async function resyncAgents(
678
682
  cwd: string;
679
683
  updatedAt?: string;
680
684
  lastUserMessageAt?: string | null;
685
+ background?: PluginHookAgent["background"];
686
+ metadata?: PluginHookAgent["metadata"];
681
687
  } }>,
682
688
  options: { incremental?: boolean } = {},
683
689
  ): Promise<HistoryScanResult> {
@@ -1,4 +1,4 @@
1
- import type { PluginHookContext, PluginHookEvents } from "@getpaseo/plugin/server";
1
+ import type { PluginHookContext } from "@getpaseo/plugin/server";
2
2
 
3
3
  /**
4
4
  * Host types re-derived from the plugin SDK.
@@ -9,6 +9,7 @@ import type { PluginHookContext, PluginHookEvents } from "@getpaseo/plugin/serve
9
9
  * dependencies, so `@getpaseo/protocol` and `@getpaseo/client` imports fail the
10
10
  * runtime-boundary build unless they resolve from the plugin's node_modules.
11
11
  */
12
- export type AgentTimelineItem = PluginHookEvents["agent.turn.after"]["timeline"][number];
13
-
14
12
  export type PaseoApi = PluginHookContext["paseo"];
13
+
14
+ type AgentHandle = ReturnType<PaseoApi["agents"]["ref"]>;
15
+ export type AgentTimelineItem = Awaited<ReturnType<AgentHandle["timeline"]["refetch"]>>["entries"][number]["item"];
@@ -12,6 +12,8 @@ const agent: PluginHookAgent = {
12
12
  provider: "claude",
13
13
  cwd: "/repo",
14
14
  title: "test agent",
15
+ background: false,
16
+ metadata: {},
15
17
  };
16
18
 
17
19
  const FIXED_NOW = "2026-09-18T12:00:00.000Z";
@@ -13,7 +13,7 @@ import { computeStreaks } from "../shared/activity.ts";
13
13
 
14
14
  type PaseoApi = PluginHandlerContext["paseo"];
15
15
 
16
- const agent = { id: "a1", workspaceId: "w1", parentAgentId: null, provider: "codex", cwd: "/tmp", title: null };
16
+ const agent = { id: "a1", workspaceId: "w1", parentAgentId: null, provider: "codex", cwd: "/tmp", title: null, background: false, metadata: {} };
17
17
  const now = "2026-09-19T12:00:00.000Z";
18
18
  const earlier = "2026-09-18T12:00:00.000Z";
19
19
  const message = { type: "user_message" as const, messageId: "m1", text: "private body" };
@@ -6,7 +6,7 @@ import { test } from "node:test";
6
6
  import type { PluginHookAgent, PluginHookContext } from "@getpaseo/plugin/server";
7
7
  import type { AgentTimelineItem } from "./host-types.ts";
8
8
  import { createUsageStore } from "./store.ts";
9
- import { TURN_TAIL_LIMIT, ingestTurnAfter, refetchTimelineTail } from "./turn-ingest.ts";
9
+ import { ingestTurnAfter, refetchTurnTimeline } from "./turn-ingest.ts";
10
10
 
11
11
  const agent: PluginHookAgent = {
12
12
  id: "agent-1",
@@ -15,29 +15,45 @@ const agent: PluginHookAgent = {
15
15
  provider: "claude",
16
16
  cwd: "/repo",
17
17
  title: "turn ingest agent",
18
+ background: false,
19
+ metadata: {},
18
20
  };
19
21
 
22
+ const TURN_ID = "turn-1";
23
+ type ToolCallItem = Extract<AgentTimelineItem, { type: "tool_call" }>;
24
+ type TimelineEntry = { item: AgentTimelineItem; turnId?: string | null };
20
25
  type RefetchOptions = {
21
- projection?: string;
22
26
  direction?: string;
23
27
  limit?: number;
28
+ wholeTurns?: boolean;
24
29
  };
25
30
 
26
31
  function fakePaseo(
27
- entries: Array<{ item: AgentTimelineItem }>,
28
- options: { error?: string; model?: string | null } = {},
32
+ entries: TimelineEntry[],
33
+ options: {
34
+ error?: string;
35
+ model?: string | null;
36
+ refreshedModel?: string;
37
+ beforeRefresh?: () => void;
38
+ beforeRefetch?: () => void;
39
+ } = {},
29
40
  ) {
30
41
  const requests: RefetchOptions[] = [];
31
42
  const refetch = async (input: RefetchOptions) => {
32
43
  requests.push(input);
44
+ options.beforeRefetch?.();
33
45
  return { entries, error: options.error ?? null };
34
46
  };
35
- const snapshot = options.model ? { model: options.model } : null;
47
+ let snapshot = options.model ? { model: options.model } : null;
36
48
  const paseo = {
37
49
  agents: {
38
50
  ref: () => ({
39
51
  current: () => snapshot,
40
- refresh: async () => snapshot,
52
+ refresh: async () => {
53
+ options.beforeRefresh?.();
54
+ if (options.refreshedModel) snapshot = { model: options.refreshedModel };
55
+ return snapshot;
56
+ },
41
57
  timeline: { refetch },
42
58
  }),
43
59
  },
@@ -45,6 +61,10 @@ function fakePaseo(
45
61
  return { paseo, requests };
46
62
  }
47
63
 
64
+ function turnEntries(items: AgentTimelineItem[], turnId: string = TURN_ID): TimelineEntry[] {
65
+ return items.map((item) => ({ item, turnId }));
66
+ }
67
+
48
68
  function withStore(run: (store: ReturnType<typeof createUsageStore>) => Promise<void>) {
49
69
  return async () => {
50
70
  const dir = mkdtempSync(join(tmpdir(), "activity-turn-ingest-"));
@@ -58,123 +78,226 @@ function withStore(run: (store: ReturnType<typeof createUsageStore>) => Promise<
58
78
  };
59
79
  }
60
80
 
61
- const toolCall = (callId: string, name: string, detail: AgentTimelineItem | undefined): AgentTimelineItem => ({
62
- type: "tool_call",
63
- callId,
64
- name,
65
- detail: detail as never,
66
- status: "completed",
67
- error: null,
81
+ function toolCall(callId: string, name: string, detail: ToolCallItem["detail"]): ToolCallItem {
82
+ return { type: "tool_call", callId, name, detail, status: "completed", error: null };
83
+ }
84
+
85
+ const prompt: AgentTimelineItem = { type: "user_message", messageId: "m-1", text: "hi" };
86
+ const skillCall = toolCall("call-1", "Skill", { type: "plain_text", label: "paseo-plugin" });
87
+ const shellCall = toolCall("call-2", "Bash", { type: "shell", command: "git status", exitCode: 0 });
88
+
89
+ test("refetchTurnTimeline requests the latest complete turn", async () => {
90
+ const { paseo, requests } = fakePaseo(turnEntries([prompt]));
91
+
92
+ assert.deepEqual(await refetchTurnTimeline(paseo, agent.id, TURN_ID), [prompt]);
93
+ assert.deepEqual(requests, [{ direction: "tail", limit: 1, wholeTurns: true }]);
68
94
  });
69
95
 
70
- test("refetchTimelineTail reads canonical recent history", async () => {
71
- const items: AgentTimelineItem[] = [{ type: "user_message", text: "hi" }];
72
- const { paseo, requests } = fakePaseo(items.map((item) => ({ item })));
96
+ test("refetchTurnTimeline surfaces daemon errors", async () => {
97
+ const { paseo } = fakePaseo([], { error: "timeline unavailable" });
73
98
 
74
- const timeline = await refetchTimelineTail(paseo, agent.id);
99
+ await assert.rejects(() => refetchTurnTimeline(paseo, agent.id, TURN_ID), /timeline unavailable/);
100
+ });
75
101
 
76
- assert.deepEqual(requests, [
77
- { projection: "canonical", direction: "tail", limit: TURN_TAIL_LIMIT },
102
+ test("refetchTurnTimeline excludes earlier, later, missing and null turn ids", async () => {
103
+ const { paseo } = fakePaseo([
104
+ { item: prompt, turnId: "older" },
105
+ { item: shellCall, turnId: TURN_ID },
106
+ { item: skillCall, turnId: "newer" },
107
+ { item: prompt },
108
+ { item: prompt, turnId: null },
78
109
  ]);
79
- assert.deepEqual(timeline, items);
110
+
111
+ assert.deepEqual(await refetchTurnTimeline(paseo, agent.id, TURN_ID), [shellCall]);
80
112
  });
81
113
 
82
- test("refetchTimelineTail surfaces daemon errors", async () => {
83
- const { paseo } = fakePaseo([], { error: "timeline unavailable" });
114
+ test("refetchTurnTimeline does not associate a null hook turn id", async () => {
115
+ const { paseo, requests } = fakePaseo(turnEntries([prompt, shellCall]));
84
116
 
85
- await assert.rejects(() => refetchTimelineTail(paseo, agent.id), /timeline unavailable/);
117
+ assert.deepEqual(await refetchTurnTimeline(paseo, agent.id, null), []);
118
+ assert.deepEqual(requests, []);
86
119
  });
87
120
 
88
121
  test(
89
- "ingestTurnAfter records tool calls from the refetched tail",
122
+ "ingestTurnAfter records tool calls, model and confirmed turn id",
90
123
  withStore(async (store) => {
91
- const { paseo } = fakePaseo(
92
- [
93
- { item: { type: "user_message", messageId: "m-1", text: "hi" } },
94
- {
95
- item: {
96
- type: "tool_call",
97
- callId: "call-1",
98
- name: "Skill",
99
- detail: { type: "plain_text", label: "paseo-plugin" },
100
- status: "completed",
101
- error: null,
102
- },
103
- },
104
- {
105
- item: {
106
- type: "tool_call",
107
- callId: "call-2",
108
- name: "Bash",
109
- detail: { type: "shell", command: "git status", exitCode: 0 },
110
- status: "completed",
111
- error: null,
112
- },
113
- },
114
- ],
115
- { model: "claude-sonnet-4" },
116
- );
124
+ const { paseo } = fakePaseo(turnEntries([prompt, skillCall, shellCall]), {
125
+ model: "claude-sonnet-4",
126
+ });
117
127
 
118
- const rows = await ingestTurnAfter(store, paseo, agent, { homeDir: "/home/tester" });
128
+ const rows = await ingestTurnAfter(store, paseo, agent, TURN_ID, { homeDir: "/home/tester" });
119
129
 
120
130
  assert.equal(rows, 2);
121
131
  const stored = store.select({ agentId: agent.id });
122
132
  assert.deepEqual(stored.map((row) => row.callId).sort(), ["call-1", "call-2"]);
133
+ assert.ok(stored.every((row) => row.turnId === TURN_ID));
123
134
  assert.equal(store.getAgent(agent.id)?.title, "turn ingest agent");
124
- assert.equal(store.selectUserMessages({ agentId: agent.id })[0]?.model, "claude-sonnet-4");
135
+ const message = store.selectUserMessages({ agentId: agent.id })[0];
136
+ assert.equal(message?.model, "claude-sonnet-4");
137
+ assert.equal(message?.turnId, TURN_ID);
125
138
  }),
126
139
  );
127
140
 
128
141
  test(
129
142
  "ingestTurnAfter keeps terminal calls and their stored classification",
130
143
  withStore(async (store) => {
131
- const first = fakePaseo([
132
- {
133
- item: {
134
- type: "tool_call",
135
- callId: "call-1",
136
- name: "Skill",
137
- detail: { type: "plain_text", label: "paseo-plugin" },
138
- status: "completed",
139
- error: null,
140
- },
141
- },
142
- ]);
143
- await ingestTurnAfter(store, first.paseo, agent, { homeDir: "/home/tester" });
144
+ const first = fakePaseo(turnEntries([prompt, skillCall]));
145
+ await ingestTurnAfter(store, first.paseo, agent, TURN_ID, { homeDir: "/home/tester" });
144
146
  const before = store.getRow(agent.id, "call-1");
145
147
  assert.equal(before?.category, "skill");
146
148
 
147
- // A later snapshot carries the same terminal call with a different detail.
148
- const second = fakePaseo([
149
- {
150
- item: {
151
- type: "tool_call",
152
- callId: "call-1",
153
- name: "Bash",
154
- detail: { type: "shell", command: "git status", exitCode: 0 },
155
- status: "completed",
156
- error: null,
157
- },
158
- },
159
- ]);
160
- const rows = await ingestTurnAfter(store, second.paseo, agent, { homeDir: "/home/tester" });
149
+ const second = fakePaseo(turnEntries([
150
+ prompt,
151
+ toolCall("call-1", "Bash", { type: "shell", command: "git status", exitCode: 0 }),
152
+ ]));
153
+ const rows = await ingestTurnAfter(store, second.paseo, agent, TURN_ID, { homeDir: "/home/tester" });
161
154
 
162
155
  assert.equal(rows, 0);
163
156
  assert.deepEqual(store.getRow(agent.id, "call-1"), before);
157
+ assert.equal(store.selectUserMessages({ agentId: agent.id }).length, 1);
164
158
  }),
165
159
  );
166
160
 
167
161
  test(
168
162
  "ingestTurnAfter preserves the registry creation time across turns",
169
163
  withStore(async (store) => {
170
- const { paseo } = fakePaseo([], {});
171
- await ingestTurnAfter(store, paseo, agent);
164
+ const { paseo } = fakePaseo([]);
165
+ await ingestTurnAfter(store, paseo, agent, TURN_ID);
172
166
  const createdAt = store.getAgent(agent.id)?.createdAt;
173
167
  assert.ok(createdAt);
174
168
 
175
- await ingestTurnAfter(store, paseo, { ...agent, title: "renamed" });
169
+ await ingestTurnAfter(store, paseo, { ...agent, title: "renamed" }, "turn-2");
176
170
 
177
171
  assert.equal(store.getAgent(agent.id)?.createdAt, createdAt);
178
172
  assert.equal(store.getAgent(agent.id)?.title, "renamed");
179
173
  }),
180
174
  );
175
+
176
+ test(
177
+ "ingestTurnAfter records more than 500 entries in one complete turn",
178
+ withStore(async (store) => {
179
+ const calls = Array.from({ length: 600 }, (_entry, index) =>
180
+ toolCall(`long-${index}`, "Bash", { type: "shell", command: "git status", exitCode: 0 }),
181
+ );
182
+ const { paseo, requests } = fakePaseo(turnEntries([prompt, ...calls]));
183
+ const rows = await ingestTurnAfter(store, paseo, agent, TURN_ID, { homeDir: "/home/tester" });
184
+
185
+ assert.equal(rows, 600);
186
+ assert.deepEqual(requests, [{ direction: "tail", limit: 1, wholeTurns: true }]);
187
+ assert.ok(store.getRow(agent.id, "long-0"));
188
+ assert.ok(store.getRow(agent.id, "long-599"));
189
+ assert.equal(store.selectUserMessages({ agentId: agent.id }).length, 1);
190
+ }),
191
+ );
192
+
193
+ test(
194
+ "ingestTurnAfter preserves stored older turns and only adds the matching turn",
195
+ withStore(async (store) => {
196
+ const older = fakePaseo(turnEntries([prompt, skillCall], "older"));
197
+ await ingestTurnAfter(store, older.paseo, agent, "older", { homeDir: "/home/tester" });
198
+ const storedOlder = store.getRow(agent.id, skillCall.callId);
199
+ const nextPrompt: AgentTimelineItem = { type: "user_message", messageId: "m-2", text: "next" };
200
+ const newerPrompt: AgentTimelineItem = { type: "user_message", messageId: "m-3", text: "later" };
201
+ const mixed = fakePaseo([
202
+ ...turnEntries([prompt, skillCall], "older"),
203
+ ...turnEntries([nextPrompt, shellCall]),
204
+ ...turnEntries([newerPrompt, toolCall("future", "Bash", { type: "shell", command: "pwd" })], "newer"),
205
+ ]);
206
+
207
+ assert.equal(await ingestTurnAfter(store, mixed.paseo, agent, TURN_ID, { homeDir: "/home/tester" }), 1);
208
+ assert.equal(await ingestTurnAfter(store, mixed.paseo, agent, TURN_ID, { homeDir: "/home/tester" }), 0);
209
+ assert.deepEqual(store.getRow(agent.id, skillCall.callId), storedOlder);
210
+ assert.equal(store.getRow(agent.id, shellCall.callId)?.turnId, TURN_ID);
211
+ assert.equal(store.getRow(agent.id, "future"), null);
212
+ const messageIds = store.selectUserMessages({ agentId: agent.id }).map((row) => row.messageId).sort();
213
+ assert.deepEqual(messageIds, ["m-1", "m-2"]);
214
+ }),
215
+ );
216
+
217
+ test(
218
+ "ingestTurnAfter leaves a replaced or null turn for background backfill",
219
+ withStore(async (store) => {
220
+ const { paseo, requests } = fakePaseo(turnEntries([prompt, shellCall], "newer"));
221
+
222
+ assert.equal(await ingestTurnAfter(store, paseo, agent, TURN_ID), 0);
223
+ assert.equal(await ingestTurnAfter(store, paseo, agent, null), 0);
224
+ assert.equal(requests.length, 1);
225
+ assert.equal(store.count(), 0);
226
+ assert.equal(store.selectUserMessages({ agentId: agent.id }).length, 0);
227
+ }),
228
+ );
229
+
230
+ test(
231
+ "ingestTurnAfter resolves and trims a model from a refreshed snapshot",
232
+ withStore(async (store) => {
233
+ const { paseo } = fakePaseo(turnEntries([prompt]), { refreshedModel: " claude-sonnet-4 " });
234
+
235
+ assert.equal(await ingestTurnAfter(store, paseo, agent, TURN_ID), 0);
236
+ assert.equal(store.selectUserMessages({ agentId: agent.id })[0]?.model, "claude-sonnet-4");
237
+ }),
238
+ );
239
+
240
+ test(
241
+ "ingestTurnAfter does not start after cancellation",
242
+ withStore(async (store) => {
243
+ const controller = new AbortController();
244
+ controller.abort();
245
+ const { paseo, requests } = fakePaseo(turnEntries([prompt]));
246
+
247
+ assert.equal(await ingestTurnAfter(store, paseo, agent, TURN_ID, { signal: controller.signal }), 0);
248
+ assert.deepEqual(requests, []);
249
+ assert.equal(store.getAgent(agent.id), null);
250
+ assert.equal(store.selectUserMessages({ agentId: agent.id }).length, 0);
251
+ }),
252
+ );
253
+
254
+ test(
255
+ "ingestTurnAfter stops before refetch when canceled during model refresh",
256
+ withStore(async (store) => {
257
+ const controller = new AbortController();
258
+ const { paseo, requests } = fakePaseo(turnEntries([prompt]), {
259
+ beforeRefresh: () => controller.abort(),
260
+ });
261
+
262
+ assert.equal(await ingestTurnAfter(store, paseo, agent, TURN_ID, { signal: controller.signal }), 0);
263
+ assert.deepEqual(requests, []);
264
+ assert.equal(store.selectUserMessages({ agentId: agent.id }).length, 0);
265
+ assert.equal(store.count(), 0);
266
+ }),
267
+ );
268
+
269
+ test(
270
+ "ingestTurnAfter does not write when canceled during timeline refetch",
271
+ withStore(async (store) => {
272
+ const controller = new AbortController();
273
+ const { paseo } = fakePaseo(turnEntries([prompt, shellCall]), {
274
+ beforeRefetch: () => controller.abort(),
275
+ });
276
+
277
+ assert.equal(await ingestTurnAfter(store, paseo, agent, TURN_ID, { signal: controller.signal }), 0);
278
+ assert.equal(store.selectUserMessages({ agentId: agent.id }).length, 0);
279
+ assert.equal(store.count(), 0);
280
+ }),
281
+ );
282
+
283
+ test("ingestTurnAfter ignores a late timeline response after SQLite closes", async () => {
284
+ const dir = mkdtempSync(join(tmpdir(), "activity-turn-ingest-closed-"));
285
+ const store = createUsageStore({ dir, driver: "sqlite" });
286
+ const controller = new AbortController();
287
+ let closed = false;
288
+ const { paseo } = fakePaseo(turnEntries([prompt]), {
289
+ beforeRefetch: () => {
290
+ controller.abort();
291
+ store.close();
292
+ closed = true;
293
+ },
294
+ });
295
+
296
+ try {
297
+ assert.equal(store.driver, "sqlite");
298
+ assert.equal(await ingestTurnAfter(store, paseo, agent, TURN_ID, { signal: controller.signal }), 0);
299
+ } finally {
300
+ if (!closed) store.close();
301
+ rmSync(dir, { recursive: true, force: true });
302
+ }
303
+ });
@@ -6,35 +6,33 @@ import { ingestTimeline, ingestUserMessages } from "./ingest.ts";
6
6
  import { resolveAgentModel } from "./resolve-model.ts";
7
7
  import type { UsageStore } from "./store.ts";
8
8
 
9
- /** Recent history is enough for immediacy; the background scan owns the full timeline. */
10
- export const TURN_TAIL_LIMIT = 500;
11
-
12
9
  type PaseoApi = PluginHookContext["paseo"];
13
10
 
14
11
  /**
15
- * Paseo 0.13+ sends an empty `timeline` in `agent.turn.after`, so read the recent
16
- * history back through the SDK instead of trusting the hook payload.
12
+ * Read the latest complete turn and keep only entries belonging to the hook's turn.
17
13
  */
18
- export async function refetchTimelineTail(
14
+ export async function refetchTurnTimeline(
19
15
  paseo: PaseoApi,
20
16
  agentId: string,
21
- limit: number = TURN_TAIL_LIMIT,
17
+ turnId: string | null,
22
18
  ): Promise<AgentTimelineItem[]> {
19
+ if (turnId === null) return [];
23
20
  const page = await paseo.agents.ref(agentId).timeline.refetch({
24
- projection: "canonical",
25
21
  direction: "tail",
26
- limit,
22
+ limit: 1,
23
+ wholeTurns: true,
27
24
  });
28
25
  if (page.error) throw new Error(page.error);
29
- return page.entries.map(({ item }) => item);
26
+ return page.entries.filter((entry) => entry.turnId === turnId).map(({ item }) => item);
30
27
  }
31
28
 
32
29
  export interface IngestTurnAfterOptions {
33
30
  homeDir?: string;
31
+ signal?: AbortSignal;
34
32
  }
35
33
 
36
34
  /**
37
- * Ingest one finished turn from a freshly read timeline tail.
35
+ * Ingest one finished turn from a freshly read complete turn.
38
36
  *
39
37
  * Returns the number of tool-call rows upserted. Calls already stored in a
40
38
  * terminal status cannot change from a snapshot, so they are skipped.
@@ -43,8 +41,10 @@ export async function ingestTurnAfter(
43
41
  store: UsageStore,
44
42
  paseo: PaseoApi,
45
43
  agent: PluginHookAgent,
44
+ turnId: string | null,
46
45
  options: IngestTurnAfterOptions = {},
47
46
  ): Promise<number> {
47
+ if (options.signal?.aborted) return 0;
48
48
  const existing = store.getAgent(agent.id);
49
49
  store.upsertAgents([
50
50
  agentRowFromHook(agent, {
@@ -52,17 +52,21 @@ export async function ingestTurnAfter(
52
52
  archivedAt: existing?.archivedAt,
53
53
  }),
54
54
  ]);
55
+ if (turnId === null) return 0;
55
56
 
56
57
  const model = await resolveAgentModel(paseo, agent.id);
57
- const timeline = await refetchTimelineTail(paseo, agent.id);
58
- store.upsertUserMessages(ingestUserMessages(timeline, agent, { model }));
58
+ if (options.signal?.aborted) return 0;
59
+ const timeline = await refetchTurnTimeline(paseo, agent.id, turnId);
60
+ if (options.signal?.aborted) return 0;
61
+ if (timeline.length === 0) return 0;
62
+ store.upsertUserMessages(ingestUserMessages(timeline, agent, { model, turnId }));
59
63
  store.pruneReplayDuplicateMessages(agent.id);
60
64
 
61
65
  const settled = store.terminalCallIds(agent.id);
62
66
  const pending = timeline.filter(
63
67
  (item) => item.type !== "tool_call" || !settled.has(item.callId),
64
68
  );
65
- const rows = ingestTimeline(pending, agent, null, {
69
+ const rows = ingestTimeline(pending, agent, turnId, {
66
70
  homeDir: options.homeDir ?? homedir(),
67
71
  });
68
72
  if (rows.length === 0) return 0;