paseo-turn-speed 1.3.0 → 1.4.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/README.md CHANGED
@@ -1,11 +1,11 @@
1
1
  # turn-speed — live token-rate meter for Paseo agents
2
2
 
3
3
  A composer pill per agent that shows how fast the model is actually decoding:
4
- `⚡ 138 tok/s` while a turn runs, `⏸ 43 tok/s` while it waits for your answer,
5
- `12.4 tok/s · 2 sub` while subagents do the heavy lifting, and the final rate
6
- once the turn ends — with a popover breakdown (prefill/TTFT, in/out tokens,
7
- prompt cache hit rate, steps, tool wait, user wait, per-subagent rates,
8
- context occupancy). Numbers measured from real provider usage are exact; before
4
+ `⚡ 138 tok/s` while a turn runs, `⏸ 43 tok/s` while it waits for your answer or
5
+ for a tool to return, `12.4 tok/s · 2 sub` while subagents do the heavy lifting,
6
+ and the final rate once the turn ends — with a popover breakdown
7
+ (prefill/TTFT, in/out tokens, prompt cache hit rate, steps, tool time, user
8
+ wait, per-subagent rates, context occupancy). Numbers measured from real provider usage are exact; before
9
9
  the first usage event they are character estimates marked with `≈`. For
10
10
  reasoning models whose provider subtracts thinking from the reported output
11
11
  (measured on OpenCode + local models via oMLX), the thinking tokens are
@@ -33,7 +33,7 @@ Desktop — the composer pill while a turn decodes, and the paused variant
33
33
  <img src="images/desktop-pill-live.png" alt="Live pill: 74.4 tok/s" width="200"> <img src="images/desktop-pill-waiting.png" alt="Waiting pill: 43.6 tok/s" width="200">
34
34
 
35
35
  The popover behind the pill — decode and whole-turn rates, prefill/TTFT,
36
- token totals, steps, tool wait and context occupancy:
36
+ token totals, steps, tool time and context occupancy:
37
37
 
38
38
  <img src="images/desktop-popover.png" alt="Turn breakdown popover" width="420">
39
39
 
@@ -88,21 +88,40 @@ provider config) — it feeds the `context 34k / 131k` line in the popover.
88
88
  - **TTFT / prefill** — from turn start to the first streamed character. Reported
89
89
  separately, never mixed into tok/s.
90
90
  - **decode tok/s** — output tokens from usage deltas divided by decode windows
91
- only. Tool waits, thinking pauses longer than 2 s, and the prefill of the next
92
- model call are excluded. This is why the pill shows ~139 tok/s on short
93
- answers instead of 6.
94
- - **Whole-turn tok/s** — optional alternative basis in settings; it includes
95
- tool time and is always lower. Time spent waiting for you and time delegated
96
- to subagents are excluded.
91
+ only: the stretches in which the model was generating. Tool calls, user waits,
92
+ delegation to subagents, thinking pauses longer than 2 s, and the prefill of
93
+ the next model call are excluded. This is why the pill shows ~139 tok/s on
94
+ short answers instead of 6. Parking tool calls matters because providers
95
+ report a step's usage *after* the call the step asked for: measured on a real
96
+ turn, a 20 s `sleep` inside a step window printed 2.3 tok/s for 2.2 s of
97
+ actual decoding, and a parent waiting on a subagent printed 0.17 tok/s over a
98
+ 20 minute window.
99
+ - **Whole-turn tok/s** — optional alternative basis in settings: tokens over
100
+ turn time minus everything the agent was not generating for — blocked on you,
101
+ delegated to subagents, or waiting on a tool. It stays at or below the decode
102
+ rate because it still pays for what the meter cannot attribute (the tail of
103
+ argument generation, an unobserved stall).
104
+ - **Tool calls** — while a call is open (shell, edit, fetch, …) the model
105
+ produces nothing, so the interval is subtracted from both rates and shown as
106
+ a `tool time` row; the pill switches to ⏸ with a `· tool` suffix, because the
107
+ number on screen is the last decoded rate rather than a live one. Intervals
108
+ come from the host's running → terminal item transitions, so concurrent calls
109
+ share one stretch and a lost terminal item parks the turn until the turn ends
110
+ (the same exposure a permission wait has). Subagent calls are deliberately not
111
+ in this set: they park the parent as delegation, and parking them twice would
112
+ subtract the same seconds from both rates.
113
+ - **Steps · gaps** — the `gaps` figure is the wall time between steps that no
114
+ window claimed. With tool calls parked it holds only what is genuinely
115
+ unattributed: the argument tail, a prefill the provider did not report.
97
116
  - **Waiting for you** — when the model asks a question or waits for a permission
98
117
  or plan approval it is asleep until you answer. Those intervals are taken from
99
118
  the provider's permission/question requests (and restored from agent snapshots
100
- after reloads and reconnects), and are removed from decode windows, tool-wait
101
- time and the whole-turn rate. `turn time` stays wall-clock; the popover shows a
102
- separate `waiting for you` row and the pill switches to a ⏸ icon meanwhile.
119
+ after reloads and reconnects), and are removed from decode windows and the
120
+ whole-turn rate. `turn time` stays wall-clock; the popover shows a separate
121
+ `waiting for you` row and the pill switches to a ⏸ icon meanwhile.
103
122
  - **Delegation to subagents** — while the agent's work runs in subagents, the
104
- parent's own model produces nothing, so that stretch is removed from its
105
- whole-turn rate like a user wait. A subagent's reply reaching the parent is
123
+ parent's own model produces nothing, so that stretch is removed from both of
124
+ its rates like a user wait. A subagent's reply reaching the parent is
106
125
  a tool result: it lands in the parent's *input* tokens (`in`/`cached`),
107
126
  never in its output. Delegation is detected from the parent's timeline
108
127
  (`sub_agent` tool details where the provider reports them, and the
@@ -226,8 +245,14 @@ check:client` runs the real Hermes syntax check too.
226
245
  [Prompt cache hit rate](#how-the-numbers-are-computed) for the exact formula
227
246
  and the plumbing already in place for when the protocol gains the field.
228
247
  - Usage that arrives late from a previous turn (typically after an interrupted
229
- message) is dropped by the plausibility guard, so that turn's token totals can
248
+ message) is dropped by the plausibility guard, and a delta whose window is
249
+ too short to resolve a rate (measured: 3 tokens over 8 ms, which would read
250
+ as 375 tok/s) is kept in the totals without one — so a turn's token totals can
230
251
  be slightly low; rates stay honest.
252
+ - A tool call that was already running when the plugin attached is not parked:
253
+ its `running` item predates the subscription, and timeline items carry no
254
+ start timestamp to reconstruct it from. That stretch is charged to the turn
255
+ rather than guessed away.
231
256
  - Every closed and dropped step is logged to the app log
232
257
  (`~/Library/Logs/Paseo/main.log`, prefix `turn-speed:`) if you want to audit
233
258
  where a number came from.
@@ -200,8 +200,15 @@ export function makeSpeedDetails(
200
200
  <Row
201
201
  styles={styles}
202
202
  label="steps"
203
- value={`${summary.steps}${summary.waitMs > 0 ? ` \u00b7 tools waited ${fmtDuration(summary.waitMs)}` : ""}`}
203
+ value={`${summary.steps}${summary.waitMs > 0 ? ` \u00b7 gaps ${fmtDuration(summary.waitMs)}` : ""}`}
204
204
  />
205
+ {summary.toolMs > 0 || summary.tooling ? (
206
+ <Row
207
+ styles={styles}
208
+ label={summary.tooling ? "in a tool" : "tool time"}
209
+ value={fmtDuration(summary.toolMs)}
210
+ />
211
+ ) : null}
205
212
  {summary.userWaitMs > 0 || summary.waiting ? (
206
213
  <Row
207
214
  styles={styles}
package/client/meter.ts CHANGED
@@ -48,6 +48,12 @@ export const DEFAULT_CHARS_PER_TOKEN = 3.6;
48
48
  * usage (e.g. a previous message's late step-finish landing in this turn)
49
49
  * and folded into the baseline instead of opening a step. */
50
50
  export const DEFAULT_MAX_TOK_PER_SEC = 400;
51
+ /** Below this a usage window cannot resolve a rate: a trailing delta of a few
52
+ * tokens that lands milliseconds after its own step would otherwise be
53
+ * charged as a burst of hundreds of tok/s (measured: 3 tokens over 8 ms).
54
+ * Real streamed steps decode over hundreds of milliseconds, so the floor only
55
+ * ever catches deltas that never had a window of their own. */
56
+ export const MIN_MEASURABLE_WINDOW_MS = 100;
51
57
  /** Message keys remembered across turns, so a snapshot of an older message
52
58
  * arriving late is recognised as "no growth" instead of a fresh text flood. */
53
59
  const MAX_TEXT_KEYS = 32;
@@ -195,6 +201,12 @@ export interface MeterState {
195
201
  delegatedWaits: readonly UserWaitInterval[];
196
202
  /** Start of the open delegation interval, null while the agent runs alone. */
197
203
  delegatedAt: number | null;
204
+ /** Completed intervals where a tool (shell, edit, fetch, …) was running.
205
+ * The model generates nothing while a call is open, whatever the provider's
206
+ * usage deltas say about when the step ended. */
207
+ toolWaits: readonly UserWaitInterval[];
208
+ /** Start of the open tool interval, null while no call is in flight. */
209
+ toolAt: number | null;
198
210
  /** True once any real usage step landed during this turn. */
199
211
  sawUsage: boolean;
200
212
  /** Set when a usage delta was dropped as physically impossible. */
@@ -222,6 +234,13 @@ export type MeterAction =
222
234
  | { t: "delegated_started"; at: number }
223
235
  /** All subagents finished: the agent works alone again. */
224
236
  | { t: "delegated_ended"; at: number }
237
+ /** A tool call is running (shell, edit, fetch, …): the model produces
238
+ * nothing until it returns. The caller opens one interval for a batch of
239
+ * concurrent calls, exactly like the user-wait and delegation pairs: the
240
+ * end closes whatever is open, so the caller only transitions on empty↔full. */
241
+ | { t: "tool_started"; at: number }
242
+ /** The last open tool call returned. */
243
+ | { t: "tool_ended"; at: number }
225
244
  | { t: "turn_ended"; at: number; kind: "completed" | "failed" | "canceled"; usage?: UsageSnapshot; maxTokPerSec?: number; note?: string | null; turnId?: string | null; provisional?: boolean }
226
245
  /** The agent switched model (or its identity just became known): a
227
246
  * thinking-exclusion verdict learned on another model must not carry. */
@@ -264,6 +283,8 @@ export function initialMeterState(): MeterState {
264
283
  pausedAt: null,
265
284
  delegatedWaits: [],
266
285
  delegatedAt: null,
286
+ toolWaits: [],
287
+ toolAt: null,
267
288
  sawUsage: false,
268
289
  stepRejected: null,
269
290
  calibInput: null,
@@ -350,17 +371,21 @@ function delta(value: number | null, previous: number): { amount: number; next:
350
371
  : { amount: value, next: value };
351
372
  }
352
373
 
353
- /** Milliseconds inside [from, to] during which the model was blocked on the
354
- * user; those must not be charged to decode or tool-run windows. An open
355
- * interval counts up to `to`. */
374
+ /** Milliseconds inside [from, to] during which the model produced nothing
375
+ * itself — blocked on the user, delegated to subagents, or waiting for a tool
376
+ * to return; none of those may be charged to a decode window. Overlapping
377
+ * stretches count once, and an open interval counts up to `to`. */
356
378
  function waitOverlap(state: MeterState, from: number, to: number): number {
357
379
  if (to <= from) return 0;
358
- let total = 0;
359
- for (const wait of state.userWaits) {
360
- total += Math.max(0, Math.min(wait.end, to) - Math.max(wait.start, from));
361
- }
362
- if (state.pausedAt !== null) total += Math.max(0, to - Math.max(state.pausedAt, from));
363
- return Math.min(total, to - from);
380
+ const asleep: UserWaitInterval[] = [
381
+ ...state.userWaits,
382
+ ...state.delegatedWaits,
383
+ ...state.toolWaits,
384
+ ];
385
+ if (state.pausedAt !== null) asleep.push({ start: state.pausedAt, end: to });
386
+ if (state.delegatedAt !== null) asleep.push({ start: state.delegatedAt, end: to });
387
+ if (state.toolAt !== null) asleep.push({ start: state.toolAt, end: to });
388
+ return unionOverlapMs(asleep, from, to);
364
389
  }
365
390
 
366
391
  /** Move the open user-wait interval into the completed list. */
@@ -388,6 +413,20 @@ function closeDelegated(state: MeterState, at: number): MeterState {
388
413
  };
389
414
  }
390
415
 
416
+ /** Move the open tool interval into the completed list. */
417
+ function closeTool(state: MeterState, at: number): MeterState {
418
+ return state.toolAt === null
419
+ ? state
420
+ : {
421
+ ...state,
422
+ toolAt: null,
423
+ toolWaits: [
424
+ ...state.toolWaits,
425
+ { start: state.toolAt, end: Math.max(at, state.toolAt) },
426
+ ],
427
+ };
428
+ }
429
+
391
430
  /** Milliseconds inside [from, to] covered by at least one interval, counting
392
431
  * overlapping intervals once (a user wait during a delegation is one pause,
393
432
  * not two). */
@@ -461,10 +500,14 @@ function applyUsage(
461
500
  // A delta implying more tokens than the window could physically decode is
462
501
  // not this turn's work: typically the previous (interrupted) message's
463
502
  // step-finish landing late. Absorb it into the baseline, keep the window.
503
+ // The other direction is just as unusable: a window of a few milliseconds
504
+ // (a trailing delta of 2-3 tokens landing right behind its own step) has no
505
+ // rate resolution at all, and prints hundreds of tok/s. Both kinds of token
506
+ // stay in the turn totals, they just do not buy a window.
464
507
  const threshold = maxTokPerSec ?? DEFAULT_MAX_TOK_PER_SEC;
465
508
  const impliedRate =
466
509
  stepDecodeMs > 0 ? outDelta.amount / (stepDecodeMs / 1000) : Number.POSITIVE_INFINITY;
467
- if (impliedRate > threshold) {
510
+ if (stepDecodeMs < MIN_MEASURABLE_WINDOW_MS || impliedRate > threshold) {
468
511
  return {
469
512
  ...withCounters,
470
513
  calibInput: null,
@@ -575,9 +618,9 @@ function endTurn(
575
618
  : state;
576
619
  if (withUsage.phase === "running") {
577
620
  // A turn that ends while a question is still open closes the wait there;
578
- // same for an ongoing delegation.
621
+ // same for an ongoing delegation or an in-flight tool call.
579
622
  return {
580
- ...closeDelegated(closeWait(withUsage, at), at),
623
+ ...closeTool(closeDelegated(closeWait(withUsage, at), at), at),
581
624
  phase: kind,
582
625
  endedAt: at,
583
626
  endNote: note,
@@ -666,6 +709,14 @@ export function reduceMeter(state: MeterState, action: MeterAction): MeterState
666
709
  case "delegated_ended":
667
710
  // An end for a delegation we never saw is a no-op.
668
711
  return state.delegatedAt === null ? state : closeDelegated(state, action.at);
712
+ case "tool_started":
713
+ return state.phase === "running" && state.toolAt === null
714
+ ? { ...state, toolAt: action.at }
715
+ : state;
716
+ case "tool_ended":
717
+ // An end for a call we never saw opened (started before attach) is a
718
+ // no-op: there is no interval to close.
719
+ return state.toolAt === null ? state : closeTool(state, action.at);
669
720
  case "turn_ended":
670
721
  return endTurn(
671
722
  state,
@@ -742,8 +793,12 @@ export interface TurnSummary {
742
793
  delegatedMs: number;
743
794
  /** True while at least one subagent is running right now. */
744
795
  delegated: boolean;
796
+ /** Wall milliseconds spent inside tool calls (shell, edit, fetch, …). */
797
+ toolMs: number;
798
+ /** True while a tool call is in flight: the model generates nothing. */
799
+ tooling: boolean;
745
800
  tokPerSecDecode: number | null;
746
- /** Tokens per second over turn time minus user waits. */
801
+ /** Tokens per second over turn time minus user waits and tool calls. */
747
802
  tokPerSecTurn: number | null;
748
803
  steps: number;
749
804
  /** Prompt tokens consumed across the turn's calls. */
@@ -906,12 +961,21 @@ export function summarizeTurn(
906
961
  let delegatedMs = 0;
907
962
  for (const wait of state.delegatedWaits) delegatedMs += Math.max(0, wait.end - wait.start);
908
963
  if (state.delegatedAt !== null && end !== null) delegatedMs += Math.max(0, end - state.delegatedAt);
964
+ let toolMs = 0;
965
+ for (const wait of state.toolWaits) toolMs += Math.max(0, wait.end - wait.start);
966
+ if (state.toolAt !== null && end !== null) toolMs += Math.max(0, end - state.toolAt);
909
967
  // The turn's productive time: wall clock minus the stretches where the
910
- // agent produced nothing itself — blocked on the user or delegated to
911
- // subagents. Overlapping stretches count once.
912
- const asleep: UserWaitInterval[] = [...state.userWaits, ...state.delegatedWaits];
968
+ // agent produced nothing itself — blocked on the user, delegated to
969
+ // subagents, or waiting for a tool to return. Overlapping stretches count
970
+ // once.
971
+ const asleep: UserWaitInterval[] = [
972
+ ...state.userWaits,
973
+ ...state.delegatedWaits,
974
+ ...state.toolWaits,
975
+ ];
913
976
  if (state.pausedAt !== null && end !== null) asleep.push({ start: state.pausedAt, end });
914
977
  if (state.delegatedAt !== null && end !== null) asleep.push({ start: state.delegatedAt, end });
978
+ if (state.toolAt !== null && end !== null) asleep.push({ start: state.toolAt, end });
915
979
  const activeMs =
916
980
  totalMs !== null && state.startedAt !== null && end !== null
917
981
  ? Math.max(0, totalMs - unionOverlapMs(asleep, state.startedAt, end))
@@ -946,6 +1010,8 @@ export function summarizeTurn(
946
1010
  waiting: state.pausedAt !== null && state.phase === "running",
947
1011
  delegatedMs,
948
1012
  delegated: state.delegatedAt !== null && state.phase === "running",
1013
+ toolMs,
1014
+ tooling: state.toolAt !== null && state.phase === "running",
949
1015
  tokPerSecDecode,
950
1016
  tokPerSecTurn,
951
1017
  steps: state.steps.length,
package/client/pill.tsx CHANGED
@@ -1,10 +1,25 @@
1
- import type { PluginButton, PluginButtonRegistration } from "@getpaseo/plugin/client";
2
1
  import { approx, fmtDuration, fmtPercent, fmtRate, fmtTokens } from "./format";
3
2
  import type { AgentSpeedStore } from "./store";
4
3
  import type { TeamView } from "./team";
5
- import type { Preferences } from "../shared/preferences";
6
4
 
7
- const PILL_REFRESH_MS = 500;
5
+ export const PILL_REFRESH_MS = 500;
6
+
7
+ /** Preference fields the pill reads, kept structural so pill logic stays
8
+ * testable without pulling in the settings schema. */
9
+ export interface PillPreferences {
10
+ liveWindowSec: number;
11
+ numerator: "live" | "decode" | "turn";
12
+ showIdlePills: boolean;
13
+ tokenFormat: "compact" | "plain";
14
+ showCacheInPill: boolean;
15
+ maxPlausibleTokPerSec: number;
16
+ }
17
+
18
+ /** Minimal button registration contract, satisfied by `PluginButtonRegistration`. */
19
+ export interface PillRegistration {
20
+ update(patch: PillView): void;
21
+ remove(): void;
22
+ }
8
23
 
9
24
  export interface PillView {
10
25
  label: string;
@@ -13,10 +28,19 @@ export interface PillView {
13
28
  title: string;
14
29
  }
15
30
 
31
+ export function samePillView(a: PillView, b: PillView): boolean {
32
+ return (
33
+ a.label === b.label &&
34
+ a.icon === b.icon &&
35
+ a.visible === b.visible &&
36
+ a.title === b.title
37
+ );
38
+ }
39
+
16
40
  /** Number the pill leads with, per the speed-basis preference. Rates above
17
41
  * the plausibility limit are bookkeeping artifacts, not speed: show nothing
18
42
  * rather than a fabricated burst. */
19
- function headlineTokPerSec(store: AgentSpeedStore, prefs: Preferences, now: number): number | null {
43
+ function headlineTokPerSec(store: AgentSpeedStore, prefs: PillPreferences, now: number): number | null {
20
44
  const summary = store.summary(now);
21
45
  const plausible = (rate: number | null): number | null =>
22
46
  rate !== null && rate > prefs.maxPlausibleTokPerSec ? null : rate;
@@ -31,7 +55,7 @@ function headlineTokPerSec(store: AgentSpeedStore, prefs: Preferences, now: numb
31
55
 
32
56
  export function computePillView(
33
57
  store: AgentSpeedStore,
34
- prefs: Preferences,
58
+ prefs: PillPreferences,
35
59
  now: number,
36
60
  team?: TeamView | null,
37
61
  ): PillView {
@@ -51,6 +75,10 @@ export function computePillView(
51
75
  const rateText = rate === null ? "\u2014" : `${approx(fmtRate(rate), isApprox)} tok/s`;
52
76
  const running = phase === "running";
53
77
  const waiting = summary.waiting;
78
+ // A tool call in flight is the other way a turn produces nothing: the rate
79
+ // on screen is whatever was last decoded, not a live speed, so the pill says
80
+ // so instead of looking like a model that slowed down.
81
+ const tooling = summary.tooling;
54
82
  const teamRunning = team && phase === "running" && team.running > 0 ? team : null;
55
83
  // The composer track is narrow: the pill carries the decode rate plus the
56
84
  // turn's cache hit rate (when enabled) and the subagent count (when the work
@@ -62,10 +90,12 @@ export function computePillView(
62
90
  labelParts.push(`\u00b7 ${fmtPercent(summary.cacheHitRate)} cached`);
63
91
  }
64
92
  if (teamRunning) labelParts.push(`\u00b7 ${teamRunning.running} sub`);
93
+ if (tooling) labelParts.push("\u00b7 tool");
65
94
  if (phase === "failed") labelParts.push("\u00b7 failed");
66
95
  if (phase === "canceled") labelParts.push("\u00b7 canceled");
67
96
  const titleParts = [`Turn speed ${rateText} decode`];
68
97
  if (waiting) titleParts.push("waiting");
98
+ if (tooling) titleParts.push("tool running");
69
99
  if (teamRunning) {
70
100
  // Keep the sheet title on one phone line: the short `N sub` form matches
71
101
  // the pill label; the full breakdown is in the popover body.
@@ -83,36 +113,69 @@ export function computePillView(
83
113
  if (summary.cacheHitRate !== null) titleParts.push(`cache ${fmtPercent(summary.cacheHitRate)}`);
84
114
  return {
85
115
  label: labelParts.join(" "),
86
- icon: waiting ? "Pause" : running ? "Zap" : "Activity",
116
+ icon: waiting || tooling ? "Pause" : running ? "Zap" : "Activity",
87
117
  visible: true,
88
118
  title: titleParts.join(" \u00b7 "),
89
119
  };
90
120
  }
91
121
 
92
122
  export interface PillRegistrationHandle {
123
+ /** Re-evaluates the pill immediately (e.g. after a settings change) without
124
+ * waiting for the next store event. Still a no-op when the view is unchanged. */
125
+ refresh(): void;
93
126
  destroy(): void;
94
127
  }
95
128
 
96
129
  /**
97
130
  * Registers a composer pill for one agent and keeps its label fresh: redraws
98
- * on store changes (throttled) and on a slow timer so the live number keeps
99
- * moving between events.
131
+ * on store changes (throttled), runs a slow heartbeat only while a turn is
132
+ * running, and skips `registration.update()` whenever the rendered fields are
133
+ * unchanged so idle agents do not churn the host button store.
100
134
  */
101
135
  export function bindPill(
102
- register: (button: PluginButton) => PluginButtonRegistration,
103
- buttonBase: Omit<PluginButton, "label" | "icon" | "visible" | "title">,
136
+ register: (initial: PillView) => PillRegistration,
104
137
  store: AgentSpeedStore,
105
- getPrefs: () => Preferences,
138
+ getPrefs: () => PillPreferences,
106
139
  now: () => number,
107
140
  getTeam?: () => TeamView | null,
108
141
  ): PillRegistrationHandle {
109
- const view = (t: number) => computePillView(store, getPrefs(), t, getTeam ? getTeam() : null);
142
+ const view = (t: number) =>
143
+ computePillView(store, getPrefs(), t, store.isRunning() && getTeam ? getTeam() : null);
110
144
  const first = view(now());
111
- let registration = register({ ...buttonBase, ...first });
112
- let lastPaint = 0;
145
+ const registration = register(first);
146
+ let lastView: PillView = first;
147
+ let lastPaint = Number.NEGATIVE_INFINITY;
113
148
  let pendingTimer: ReturnType<typeof setTimeout> | null = null;
149
+ let heartbeat: ReturnType<typeof setInterval> | null = null;
150
+ let wasRunning = store.isRunning();
151
+ let destroyed = false;
152
+
153
+ const stopHeartbeat = () => {
154
+ if (heartbeat !== null) {
155
+ clearInterval(heartbeat);
156
+ heartbeat = null;
157
+ }
158
+ };
159
+
160
+ const syncHeartbeat = () => {
161
+ if (destroyed) return;
162
+ if (store.isRunning()) {
163
+ if (heartbeat === null) {
164
+ heartbeat = setInterval(() => {
165
+ if (destroyed || !store.isRunning()) {
166
+ stopHeartbeat();
167
+ return;
168
+ }
169
+ paint(false);
170
+ }, PILL_REFRESH_MS);
171
+ }
172
+ } else {
173
+ stopHeartbeat();
174
+ }
175
+ };
114
176
 
115
177
  const paint = (force: boolean) => {
178
+ if (destroyed) return;
116
179
  const t = now();
117
180
  if (!force && t - lastPaint < PILL_REFRESH_MS) {
118
181
  if (pendingTimer === null) {
@@ -123,8 +186,14 @@ export function bindPill(
123
186
  }
124
187
  return;
125
188
  }
189
+ if (pendingTimer !== null) {
190
+ clearTimeout(pendingTimer);
191
+ pendingTimer = null;
192
+ }
126
193
  lastPaint = t;
127
194
  const viewNow = view(t);
195
+ if (samePillView(lastView, viewNow)) return;
196
+ lastView = viewNow;
128
197
  registration.update({
129
198
  label: viewNow.label,
130
199
  icon: viewNow.icon,
@@ -133,17 +202,33 @@ export function bindPill(
133
202
  });
134
203
  };
135
204
 
136
- const unsubscribe = store.subscribe(() => paint(false));
137
- // A slow heartbeat keeps the live tok/s and elapsed time honest while the
138
- // agent streams but the reducer has not changed on a given tick.
139
- const heartbeat = setInterval(() => paint(false), PILL_REFRESH_MS);
140
- paint(true);
205
+ const unsubscribe = store.subscribe(() => {
206
+ const running = store.isRunning();
207
+ const phaseChanged = running !== wasRunning;
208
+ wasRunning = running;
209
+ syncHeartbeat();
210
+ // Flush phase transitions (start/end) immediately so a finished turn never
211
+ // lingers with a running icon or a dangling throttle timer.
212
+ paint(phaseChanged);
213
+ });
214
+ syncHeartbeat();
141
215
 
142
216
  return {
217
+ refresh() {
218
+ if (destroyed) return;
219
+ wasRunning = store.isRunning();
220
+ syncHeartbeat();
221
+ paint(true);
222
+ },
143
223
  destroy() {
224
+ if (destroyed) return;
225
+ destroyed = true;
144
226
  unsubscribe();
145
- if (pendingTimer !== null) clearTimeout(pendingTimer);
146
- clearInterval(heartbeat);
227
+ if (pendingTimer !== null) {
228
+ clearTimeout(pendingTimer);
229
+ pendingTimer = null;
230
+ }
231
+ stopHeartbeat();
147
232
  registration.remove();
148
233
  },
149
234
  };
package/client/store.ts CHANGED
@@ -174,9 +174,10 @@ export function createAgentSpeedStore(deps: AgentSpeedStoreDeps): AgentSpeedStor
174
174
  if (line !== lastRejectionLog) {
175
175
  lastRejectionLog = line;
176
176
  console.log(
177
- `turn-speed: step dropped as implausible [${deps.agentId.slice(0, 8)}]` +
177
+ `turn-speed: step kept without a window [${deps.agentId.slice(0, 8)}]` +
178
178
  ` tokens=${next.stepRejected.tokens} windowMs=${Math.round(next.stepRejected.windowMs)}` +
179
- " (late or aggregated usage; kept in the turn totals as unattributed tokens)",
179
+ " (implied rate above the plausibility cap, or too short to measure;" +
180
+ " kept in the turn totals as unattributed tokens)",
180
181
  );
181
182
  }
182
183
  }
package/index.client.tsx CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { PluginClientContext } from "@getpaseo/plugin/client";
2
2
  import { settingsRpc } from "@getpaseo/plugin";
3
3
  import { createAgentSpeedStore, type AgentSpeedStore } from "./client/store";
4
- import { bindPill } from "./client/pill";
4
+ import { bindPill, type PillRegistrationHandle } from "./client/pill";
5
5
  import { makeSpeedDetails } from "./client/details";
6
6
  import { parentAgentIdOf } from "./client/links";
7
7
  import {
@@ -32,9 +32,18 @@ type AgentEntry = AgentListResult["entries"][number];
32
32
 
33
33
  interface Attachment {
34
34
  store: AgentSpeedStore;
35
+ refreshPill(): void;
35
36
  detach(): void;
36
37
  }
37
38
 
39
+ /** Every preference is a primitive, so the compared keys come from the schema
40
+ * defaults: a field added to `preferences.schema` is diffed without touching
41
+ * this function, instead of silently reading as "no change" forever. */
42
+ function samePreferences(a: Preferences, b: Preferences): boolean {
43
+ const keys = Object.keys(DEFAULT_PREFERENCES) as (keyof Preferences)[];
44
+ return keys.every((key) => a[key] === b[key]);
45
+ }
46
+
38
47
  /** Paseo normalizes subagent-spawning tool calls to the name "subagent";
39
48
  * providers that map them richly use the `sub_agent` detail type instead.
40
49
  * (Measured on Paseo 0.12 + OpenCode: name="subagent", detail.type="unknown".) */
@@ -44,6 +53,17 @@ function isSubAgentCall(item: { name: string; detail: { type?: string } }): bool
44
53
  return item.detail.type === "sub_agent" || SUB_AGENT_TOOL_NAME.test(item.name);
45
54
  }
46
55
 
56
+ /** Open calls of one attached agent, with the callbacks that re-derive the
57
+ * meter's parked intervals whenever a set changes. */
58
+ interface OpenCalls {
59
+ /** Running subagent calls: the parent's own model is delegated. */
60
+ subCalls: Set<string>;
61
+ /** Running tool calls (shell, edit, fetch, …): the model waits for a result. */
62
+ toolCalls: Set<string>;
63
+ onSubChange(): void;
64
+ onToolChange(): void;
65
+ }
66
+
47
67
  const CAL_FLUSH_MS = 2000;
48
68
 
49
69
  export default function contribute(client: PluginClientContext) {
@@ -153,7 +173,13 @@ export default function contribute(client: PluginClientContext) {
153
173
  const read = await client.rpc(settingsRpc(preferences.id).read, {});
154
174
  if (read.status === "ready") {
155
175
  const parsed = preferences.schema.safeParse(read.values);
156
- if (parsed.success) prefs = parsed.data;
176
+ if (parsed.success) {
177
+ const changed = !samePreferences(prefs, parsed.data);
178
+ prefs = parsed.data;
179
+ if (changed) {
180
+ for (const attachment of attached.values()) attachment.refreshPill();
181
+ }
182
+ }
157
183
  }
158
184
  } catch (error) {
159
185
  logError("reading preferences failed", error);
@@ -253,14 +279,14 @@ export default function contribute(client: PluginClientContext) {
253
279
  reseed: () => void,
254
280
  waits: Set<string>,
255
281
  agentId: string,
256
- subCalls: Set<string>,
257
- onSubChange: () => void,
282
+ calls: OpenCalls,
258
283
  ): void {
259
284
  const at = Date.now();
260
285
  switch (event.type) {
261
286
  case "turn_started": {
262
287
  waits.clear();
263
- subCalls.clear();
288
+ calls.subCalls.clear();
289
+ calls.toolCalls.clear();
264
290
  // Anchor to the daemon's timestamp from this very message: a ref()
265
291
  // snapshot updates on another channel and can still hold the previous
266
292
  // turn's start, which would charge that whole turn to this one.
@@ -270,13 +296,15 @@ export default function contribute(client: PluginClientContext) {
270
296
  at: start.at,
271
297
  turnId: event.turnId || null,
272
298
  });
273
- onSubChange();
299
+ calls.onSubChange();
300
+ calls.onToolChange();
274
301
  break;
275
302
  }
276
303
  case "turn_completed":
277
304
  if (!belongsToCurrentTurn(store, event.turnId)) break;
278
305
  waits.clear();
279
- subCalls.clear();
306
+ calls.subCalls.clear();
307
+ calls.toolCalls.clear();
280
308
  store.dispatch({
281
309
  t: "turn_ended",
282
310
  at,
@@ -285,13 +313,15 @@ export default function contribute(client: PluginClientContext) {
285
313
  usage: event.usage ? mapUsage(event.usage) : undefined,
286
314
  maxTokPerSec: prefs.maxPlausibleTokPerSec,
287
315
  });
288
- onSubChange();
316
+ calls.onSubChange();
317
+ calls.onToolChange();
289
318
  void refreshPrefs();
290
319
  break;
291
320
  case "turn_failed":
292
321
  if (!belongsToCurrentTurn(store, event.turnId)) break;
293
322
  waits.clear();
294
- subCalls.clear();
323
+ calls.subCalls.clear();
324
+ calls.toolCalls.clear();
295
325
  store.dispatch({
296
326
  t: "turn_ended",
297
327
  at,
@@ -299,12 +329,14 @@ export default function contribute(client: PluginClientContext) {
299
329
  turnId: event.turnId || null,
300
330
  note: event.error,
301
331
  });
302
- onSubChange();
332
+ calls.onSubChange();
333
+ calls.onToolChange();
303
334
  break;
304
335
  case "turn_canceled":
305
336
  if (!belongsToCurrentTurn(store, event.turnId)) break;
306
337
  waits.clear();
307
- subCalls.clear();
338
+ calls.subCalls.clear();
339
+ calls.toolCalls.clear();
308
340
  store.dispatch({
309
341
  t: "turn_ended",
310
342
  at,
@@ -312,7 +344,8 @@ export default function contribute(client: PluginClientContext) {
312
344
  turnId: event.turnId || null,
313
345
  note: event.reason,
314
346
  });
315
- onSubChange();
347
+ calls.onSubChange();
348
+ calls.onToolChange();
316
349
  break;
317
350
  case "permission_requested":
318
351
  case "permission_resolved": {
@@ -361,12 +394,29 @@ export default function contribute(client: PluginClientContext) {
361
394
  if (childId) linkChild(childId, agentId);
362
395
  if (item.callId) {
363
396
  if (item.status === "running") {
364
- if (!subCalls.has(item.callId)) {
365
- subCalls.add(item.callId);
366
- onSubChange();
397
+ if (!calls.subCalls.has(item.callId)) {
398
+ calls.subCalls.add(item.callId);
399
+ calls.onSubChange();
367
400
  }
368
- } else if (subCalls.delete(item.callId)) {
369
- onSubChange();
401
+ } else if (calls.subCalls.delete(item.callId)) {
402
+ calls.onSubChange();
403
+ }
404
+ }
405
+ } else if (item.type === "tool_call") {
406
+ // Any other call (shell, edit, fetch, …): the model generates
407
+ // nothing while it runs, and providers land the step's usage after
408
+ // the result — so without parking the stretch, a two-minute build
409
+ // is billed to the decode window as if it were slow decoding.
410
+ // Subagent calls stay out of this set: they park the parent as
411
+ // delegation, and counting them here would subtract them twice.
412
+ if (item.callId) {
413
+ if (item.status === "running") {
414
+ if (!calls.toolCalls.has(item.callId)) {
415
+ calls.toolCalls.add(item.callId);
416
+ calls.onToolChange();
417
+ }
418
+ } else if (calls.toolCalls.delete(item.callId)) {
419
+ calls.onToolChange();
370
420
  }
371
421
  }
372
422
  }
@@ -376,9 +426,11 @@ export default function contribute(client: PluginClientContext) {
376
426
  case "subscription_restored":
377
427
  // Do not replay history we never saw; the live window is local anyway.
378
428
  waits.clear();
379
- subCalls.clear();
429
+ calls.subCalls.clear();
430
+ calls.toolCalls.clear();
380
431
  store.dispatch({ t: "reset" });
381
- onSubChange();
432
+ calls.onSubChange();
433
+ calls.onToolChange();
382
434
  // Provider counters kept moving while we were blind: re-read them so
383
435
  // the next delta is the new work, not the whole unseen gap.
384
436
  reseed();
@@ -464,6 +516,31 @@ export default function contribute(client: PluginClientContext) {
464
516
  console.log(`turn-speed: delegation ${should ? "on" : "off"} [${agent.id.slice(0, 8)}]`);
465
517
  store.dispatch({ t: should ? "delegated_started" : "delegated_ended", at: Date.now() });
466
518
  };
519
+ // Tools: while any call is open the agent's own model produces nothing, so
520
+ // the meter parks that stretch out of the decode windows and the turn rate.
521
+ // Concurrent calls share one interval, and a `running` item the host
522
+ // re-delivers must not open a second one.
523
+ const toolCalls = new Set<string>();
524
+ let toolingNow = false;
525
+ const syncToolWaits = (): void => {
526
+ const should = toolCalls.size > 0;
527
+ if (store.state.phase !== "running") {
528
+ // Outside a turn there is no interval to open or close; drop the flag
529
+ // so the next turn re-evaluates from scratch.
530
+ toolingNow = false;
531
+ return;
532
+ }
533
+ if (should === toolingNow) return;
534
+ toolingNow = should;
535
+ console.log(`turn-speed: tool ${should ? "running" : "idle"} [${agent.id.slice(0, 8)}]`);
536
+ store.dispatch({ t: should ? "tool_started" : "tool_ended", at: Date.now() });
537
+ };
538
+ const calls: OpenCalls = {
539
+ subCalls,
540
+ toolCalls,
541
+ onSubChange: syncDelegated,
542
+ onToolChange: syncToolWaits,
543
+ };
467
544
  // One snapshot, one ordered set of actions: identify the turn, restore the
468
545
  // waits that belong to it, then end a turn whose terminal event was lost.
469
546
  // The last step is provisional, so a real terminal event still decides the
@@ -478,6 +555,7 @@ export default function contribute(client: PluginClientContext) {
478
555
  store.dispatch(action);
479
556
  if (action.t === "turn_ended" && action.provisional) {
480
557
  subCalls.clear();
558
+ toolCalls.clear();
481
559
  void refreshPrefs();
482
560
  }
483
561
  }
@@ -487,6 +565,11 @@ export default function contribute(client: PluginClientContext) {
487
565
  // that attaches after its children would count their work as its own
488
566
  // until the next child event.
489
567
  syncDelegated();
568
+ // A call whose `running` item landed while this agent was attaching
569
+ // found no turn to park; re-check now that the snapshot has established
570
+ // one. A call that started before the subscription stays unparked: items
571
+ // carry no start timestamp to reconstruct it from.
572
+ syncToolWaits();
490
573
  }
491
574
  // A ref() handle starts empty: without a real snapshot, the first usage
492
575
  // event after a reload would count the session-cumulative counters as
@@ -532,14 +615,19 @@ export default function contribute(client: PluginClientContext) {
532
615
  },
533
616
  team,
534
617
  );
535
- let pillHandle: { destroy(): void } | null = null;
618
+ let pillHandle: PillRegistrationHandle | null = null;
536
619
  try {
537
620
  pillHandle = bindPill(
538
- (button) =>
539
- client.addComposerPill({ id: "speed", workspaceId, agentId: agent.id, button }),
540
- {
541
- behavior: { kind: "popover", Content: details },
542
- },
621
+ (initial) =>
622
+ client.addComposerPill({
623
+ id: "speed",
624
+ workspaceId,
625
+ agentId: agent.id,
626
+ button: {
627
+ behavior: { kind: "popover", Content: details },
628
+ ...initial,
629
+ },
630
+ }),
543
631
  store,
544
632
  () => prefs,
545
633
  () => Date.now(),
@@ -571,8 +659,7 @@ export default function contribute(client: PluginClientContext) {
571
659
  reseed,
572
660
  pendingWaits,
573
661
  agent.id,
574
- subCalls,
575
- syncDelegated,
662
+ calls,
576
663
  );
577
664
  } catch (error) {
578
665
  logError(`timeline event failed for ${agent.id}`, error);
@@ -591,6 +678,9 @@ export default function contribute(client: PluginClientContext) {
591
678
 
592
679
  attached.set(agent.id, {
593
680
  store,
681
+ refreshPill() {
682
+ pillHandle?.refresh();
683
+ },
594
684
  detach() {
595
685
  storeTeamWatch?.();
596
686
  storeTeamWatch = null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "paseo-turn-speed",
3
- "version": "1.3.0",
3
+ "version": "1.4.1",
4
4
  "description": "Live decode tok/s, prefill and token breakdown for every agent turn",
5
5
  "license": "MIT",
6
6
  "author": "Bogdan Yanysh <acidlol@live.ru>",
package/paseo-plugin.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "id": "turn-speed",
3
3
  "description": "Live decode tok/s, prefill/TTFT, and a token breakdown for every agent turn, right in the composer.",
4
+ "icon": "assets/icon.png",
4
5
  "requirements": {
5
6
  "paseo": ">=0.11.0"
6
7
  }