oc-flight-deck 0.19.1 → 0.20.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 +26 -0
- package/README.md +181 -75
- package/dist/tui/index.js +433 -108
- package/flight-deck.example.jsonc +52 -12
- package/flight-deck.schema.json +39 -5
- package/package.json +3 -2
- package/src/tui/clipboard.ts +99 -28
- package/src/tui/config.ts +104 -7
- package/src/tui/host-clipboard.ts +50 -12
- package/src/tui/index.tsx +20 -2
- package/src/tui/notify.ts +21 -0
- package/src/tui/presentation.ts +3 -0
- package/src/tui/realtime-tps.ts +433 -0
- package/src/tui/rows.ts +41 -9
- package/src/tui/session-tps.ts +133 -101
- package/src/tui/stat-fields.ts +25 -6
- package/src/tui/stats.ts +9 -3
- package/src/tui/throughput.ts +20 -110
|
@@ -4,23 +4,61 @@
|
|
|
4
4
|
// only thing those tests replace, so they can stand in a fake host write while
|
|
5
5
|
// the renderer stays real.
|
|
6
6
|
//
|
|
7
|
-
// Production
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
7
|
+
// Production uses the REAL host clipboard: `createHostClipboard` imported from
|
|
8
|
+
// `@opentui/core` resolves to the host's own core instance, because that
|
|
9
|
+
// specifier is host-served to plugins (the host rewrites it to its own copy)
|
|
10
|
+
// and `scripts/build.ts` keeps `@opentui/*` external, so nothing of theirs is
|
|
11
|
+
// ever bundled. The `HostClipboardLike` shape stays structural so tests can
|
|
12
|
+
// keep standing in a fake without importing the toolkit.
|
|
12
13
|
|
|
13
|
-
|
|
14
|
-
|
|
14
|
+
import { createHostClipboard as createCoreHostClipboard } from "@opentui/core";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The subset of a host clipboard service the copy path uses.
|
|
18
|
+
*
|
|
19
|
+
* `writeText` carries the copy; `read` is the read-back the OSC52 fallback is
|
|
20
|
+
* verified with. It is optional so a fake (or a future backend without reads)
|
|
21
|
+
* can offer writes only — the copy path skips verification when it is absent
|
|
22
|
+
* and reports the dispatch as unconfirmed rather than throwing. The options
|
|
23
|
+
* mirror `@opentui/core`: `preferredTypes: ["text/plain"]` with
|
|
24
|
+
* `selection: "clipboard"`, and on `status === "read"` the
|
|
25
|
+
* `representation.bytes` hold the clipboard text as a `Uint8Array`.
|
|
26
|
+
*/
|
|
27
|
+
export interface HostClipboardLike {
|
|
15
28
|
writeText(text: string): Promise<{ readonly status: string }>;
|
|
29
|
+
read?(options: {
|
|
30
|
+
readonly preferredTypes: readonly [string, ...string[]];
|
|
31
|
+
readonly selection?: "clipboard" | "primary";
|
|
32
|
+
}): Promise<{ readonly status: string; readonly representation?: { readonly bytes: Uint8Array } }>;
|
|
16
33
|
}
|
|
17
34
|
|
|
18
35
|
/**
|
|
19
|
-
* The
|
|
20
|
-
*
|
|
21
|
-
* copy
|
|
22
|
-
|
|
36
|
+
* The lazily created process-wide host clipboard service. One singleton per
|
|
37
|
+
* module instance: creating it once avoids paying backend setup per click, and
|
|
38
|
+
* every copy in the session shares the same OS handle.
|
|
39
|
+
*/
|
|
40
|
+
let cached: HostClipboardLike | undefined;
|
|
41
|
+
let attempted = false;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The default host clipboard factory: the real host-served clipboard.
|
|
45
|
+
*
|
|
46
|
+
* Never throws: a backend that cannot even be constructed degrades to
|
|
47
|
+
* `undefined` ("no host service at all"), so the copy path reports
|
|
48
|
+
* `no-backend` when no renderer can take the OSC52 fallback either.
|
|
49
|
+
*
|
|
50
|
+
* The singleton is never disposed. It wraps process-wide OS clipboard state
|
|
51
|
+
* owned by the host, not by this plugin — disposing it from here could break
|
|
52
|
+
* the host's own clipboard — and a plugin reload re-imports a fresh module
|
|
53
|
+
* instance with its own cache anyway, so nothing here can leak across one.
|
|
23
54
|
*/
|
|
24
55
|
export function createHostClipboard(): HostClipboardLike | undefined {
|
|
25
|
-
return
|
|
56
|
+
if (attempted) return cached;
|
|
57
|
+
attempted = true;
|
|
58
|
+
try {
|
|
59
|
+
cached = createCoreHostClipboard();
|
|
60
|
+
} catch {
|
|
61
|
+
cached = undefined;
|
|
62
|
+
}
|
|
63
|
+
return cached;
|
|
26
64
|
}
|
package/src/tui/index.tsx
CHANGED
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
} from "./caution.js";
|
|
11
11
|
import { copyFeedback, copyToClipboard } from "./clipboard.js";
|
|
12
12
|
import { cautionThresholds, mergeOptions, resolveConfig } from "./config.js";
|
|
13
|
+
import { shouldNotify } from "./notify.js";
|
|
13
14
|
import { loadConfigFile } from "./file-config.js";
|
|
14
15
|
import { createGoLookReader } from "./go-look.js";
|
|
15
16
|
import { footerLine, railLineSpans, railLines, railLineStyle, type RailLine } from "./presentation.js";
|
|
@@ -21,6 +22,7 @@ import { startGoBridge } from "./go.js";
|
|
|
21
22
|
import { startTicker } from "./ticker.js";
|
|
22
23
|
import { asCount, asRecord, type SessionLike } from "./coerce.js";
|
|
23
24
|
import { createProjectTotals } from "./project-totals.js";
|
|
25
|
+
import { createRealtimeTps } from "./realtime-tps.js";
|
|
24
26
|
import { createSessionReads, locationOf } from "./session-reads.js";
|
|
25
27
|
import { createTpsReader } from "./session-tps.js";
|
|
26
28
|
|
|
@@ -58,7 +60,7 @@ export default Plugin.define({
|
|
|
58
60
|
console.warn(`[flight-deck] ${file.issue}`);
|
|
59
61
|
}
|
|
60
62
|
const problems = file.issue !== undefined ? [file.issue, ...issues] : issues;
|
|
61
|
-
if (problems.length > 0) {
|
|
63
|
+
if (problems.length > 0 && shouldNotify(config.notifications, "config")) {
|
|
62
64
|
const extra = problems.length > 1 ? ` (+${problems.length - 1} more)` : "";
|
|
63
65
|
context.ui.toast.show({
|
|
64
66
|
title: "Flight Deck",
|
|
@@ -70,6 +72,14 @@ export default Plugin.define({
|
|
|
70
72
|
const footer = footerLine(config);
|
|
71
73
|
const releases: Array<() => void> = [];
|
|
72
74
|
|
|
75
|
+
// The plugin's first host subscription: the realtime TPS tracker listens
|
|
76
|
+
// to the host's streaming delta events from here on, so the `tps` row can
|
|
77
|
+
// watch a turn stream instead of only seeing its tokens after it settles.
|
|
78
|
+
// A host with no subscription surface degrades the tracker to a zero
|
|
79
|
+
// reader rather than failing setup, and disposal below drops the
|
|
80
|
+
// subscriptions so nothing leaks on unload.
|
|
81
|
+
const realtime = createRealtimeTps(context);
|
|
82
|
+
|
|
73
83
|
// One themed line, in the exact form the sidebar draws: the line resolves
|
|
74
84
|
// its own look from `config.style` (fixed lines use `style.lines`, every
|
|
75
85
|
// live row its own entry or the wildcard), and `themeColor`/`attributeMask`
|
|
@@ -128,6 +138,7 @@ export default Plugin.define({
|
|
|
128
138
|
const result = await copyToClipboard(context.renderer, copyId);
|
|
129
139
|
const fb = copyFeedback(result, copyId);
|
|
130
140
|
if (fb.ok) return;
|
|
141
|
+
if (!shouldNotify(config.notifications, "copy")) return;
|
|
131
142
|
context.ui.toast.show({
|
|
132
143
|
title: "Flight Deck",
|
|
133
144
|
message: fb.message,
|
|
@@ -180,6 +191,7 @@ export default Plugin.define({
|
|
|
180
191
|
elapsedMsOf: (id, now) => sessionElapsed(id, now),
|
|
181
192
|
},
|
|
182
193
|
config.sidebar.tps.scope,
|
|
194
|
+
realtime,
|
|
183
195
|
);
|
|
184
196
|
|
|
185
197
|
// Recent turn sizes, oldest first. Drawn from messages the host already
|
|
@@ -342,7 +354,12 @@ export default Plugin.define({
|
|
|
342
354
|
// `sidebar.content` render, which exists only when the sidebar is enabled,
|
|
343
355
|
// so without it this timer could never fire and would leak a live interval.
|
|
344
356
|
const toastMs = Math.max(1_000, config.refresh > 0 ? config.refresh : 1_000);
|
|
345
|
-
if (
|
|
357
|
+
if (
|
|
358
|
+
config.sidebar.enabled &&
|
|
359
|
+
config.caution.enabled &&
|
|
360
|
+
config.caution.toast &&
|
|
361
|
+
shouldNotify(config.notifications, "caution")
|
|
362
|
+
) {
|
|
346
363
|
watchTimer = setInterval(() => {
|
|
347
364
|
const sessionID = watchedSession;
|
|
348
365
|
if (sessionID === undefined) return;
|
|
@@ -461,6 +478,7 @@ export default Plugin.define({
|
|
|
461
478
|
return () => {
|
|
462
479
|
if (watchTimer !== undefined) clearInterval(watchTimer);
|
|
463
480
|
watchTimer = undefined;
|
|
481
|
+
realtime.dispose();
|
|
464
482
|
ticker?.dispose();
|
|
465
483
|
bridge?.dispose();
|
|
466
484
|
goBridge?.dispose();
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// The notification silencing layer: one pure predicate over the
|
|
2
|
+
// `notifications` config section.
|
|
3
|
+
//
|
|
4
|
+
// The plugin raises three kinds of toast - an invalid-config warning, a copy
|
|
5
|
+
// outcome, and the opt-in caution toast - and every one of them is gated here.
|
|
6
|
+
// `enabled` is the master switch; each per-kind flag silences only its kind.
|
|
7
|
+
// `caution.toast` stays the feature opt-in (default off); this section only
|
|
8
|
+
// ever silences, never enables.
|
|
9
|
+
|
|
10
|
+
import type { NotificationsConfig } from "./config.js";
|
|
11
|
+
|
|
12
|
+
/** The toast kinds the plugin can raise. */
|
|
13
|
+
export type NotifyKind = "config" | "copy" | "caution";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Whether a toast of `kind` may be shown under `config`. Pure: no reads, no
|
|
17
|
+
* writes, never throws.
|
|
18
|
+
*/
|
|
19
|
+
export function shouldNotify(config: NotificationsConfig, kind: NotifyKind): boolean {
|
|
20
|
+
return config.enabled && config[kind];
|
|
21
|
+
}
|
package/src/tui/presentation.ts
CHANGED
|
@@ -43,11 +43,14 @@ export function railLines(config: FlightDeckConfig, source: StatSource = {}): re
|
|
|
43
43
|
|
|
44
44
|
// The display side of the config, which the row renderer reads alongside its
|
|
45
45
|
// geometry. `format` is a top-level section, so it is mapped here.
|
|
46
|
+
// `tpsDisplay` is the `tps` row's view of `sidebar.tps.display`: which of
|
|
47
|
+
// the pair's figures draws (the settled-turn average by default).
|
|
46
48
|
const layout = {
|
|
47
49
|
...config.layout,
|
|
48
50
|
persist: config.sidebar.persist,
|
|
49
51
|
placeholder: config.sidebar.placeholder,
|
|
50
52
|
durationStyle: config.format.duration,
|
|
53
|
+
tpsDisplay: config.sidebar.tps.display,
|
|
51
54
|
// Decided from the whole row list, the way `statRows` decides it: `cost`
|
|
52
55
|
// folds the subagent total into itself only when no `total` row was asked
|
|
53
56
|
// for, even if the cap later drops that row.
|
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
// Realtime generation rate, estimated from the host's own streaming delta
|
|
2
|
+
// events — the plugin's FIRST host subscription (nothing else here subscribes
|
|
3
|
+
// to host events: the guard and go bridges poll, the ticker writes a frame).
|
|
4
|
+
//
|
|
5
|
+
// Why events and not polls: an in-flight assistant message carries no
|
|
6
|
+
// streaming text and no token counts — the host fills the message record's
|
|
7
|
+
// text only at `session.text.ended`, its per-turn progress living in an
|
|
8
|
+
// "ephemeral progress history" outside the durable record
|
|
9
|
+
// (packages/core/src/session/message-updater.ts:342), and `draft.tokens` is
|
|
10
|
+
// set only at `session.step.ended`. So any poll of `session.message.list` can
|
|
11
|
+
// only see a turn's tokens AFTER it settles — the old poll-delta tracker
|
|
12
|
+
// (`createInstantTps`) could never watch a turn stream. The realtime figure
|
|
13
|
+
// must come from the host's own delta events instead, following the oc-tps
|
|
14
|
+
// design: subscribe to `session.text.delta` / `session.reasoning.delta` and
|
|
15
|
+
// estimate tokens from delta bytes.
|
|
16
|
+
//
|
|
17
|
+
// ESTIMATE, not a measurement: the host publishes real counts only at step
|
|
18
|
+
// end. Each non-empty delta is estimated at `max(1, ceil(bytes / 5))` tokens
|
|
19
|
+
// (an empty delta carries nothing: 0); the settled average beside it stays
|
|
20
|
+
// the real figure.
|
|
21
|
+
//
|
|
22
|
+
// Pure except for the subscription itself: samples are timestamped with an
|
|
23
|
+
// injectable clock so tests pin the window without sleeping.
|
|
24
|
+
|
|
25
|
+
// In-memory for the plugin's lifetime only: steps observed while the plugin
|
|
26
|
+
// ran. A restart forgets every ring — the same limitation as oc-tps, whose
|
|
27
|
+
// averages the host never persisted either. The mean covers finalized steps:
|
|
28
|
+
// a step's TTFT appears once that step settles, never while it streams.
|
|
29
|
+
|
|
30
|
+
import type { Plugin } from "@opencode/plugin/tui";
|
|
31
|
+
import { asCount, asRecord, asText } from "./coerce.js";
|
|
32
|
+
import { smoothTpsRate, TPS_EWMA_ALPHA, tpsNeedsRepaint } from "./throughput.js";
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* How long one delta sample stays in the per-session ring. Deltas older than
|
|
36
|
+
* this never enter the rate: a turn that streamed a minute ago is history,
|
|
37
|
+
* not speed.
|
|
38
|
+
*/
|
|
39
|
+
export const RT_SAMPLE_WINDOW_MS = 5_000;
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* How long after its last sample a session still counts. A session with no
|
|
43
|
+
* sample for this long is stale and contributes 0 — the decoder is between
|
|
44
|
+
* turns or done, so there is nothing to pace.
|
|
45
|
+
*/
|
|
46
|
+
export const RT_STALE_MS = 1_500;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The maximum finalized step values retained per session. The TTFT mean
|
|
50
|
+
* covers the most recent finalized steps, so the ring drops whole values
|
|
51
|
+
* oldest-first — a mean over retained values can never be negative or
|
|
52
|
+
* fabricated, unlike adjustments against an aggregate that can be evicted
|
|
53
|
+
* and recreated underneath a pending correction.
|
|
54
|
+
*/
|
|
55
|
+
export const RT_MAX_STEPS = 100;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Bound on the per-session sample map, mirroring the old poll tracker's
|
|
59
|
+
* `MAX_TRACKERS` discipline: without eviction a TUI lifetime of
|
|
60
|
+
* session-hopping grows this map forever. Eviction only drops samples — a
|
|
61
|
+
* revisit restarts from zero, exactly like a first sight.
|
|
62
|
+
*/
|
|
63
|
+
export const RT_MAX_SESSIONS = 50;
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* One delta sample: its estimated tokens, stamped on the host event's own
|
|
67
|
+
* clock (`event.created`), never on a clock this process keeps.
|
|
68
|
+
*/
|
|
69
|
+
interface RealtimeSample {
|
|
70
|
+
readonly at: number;
|
|
71
|
+
readonly tokens: number;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Estimate one delta's tokens from its raw bytes.
|
|
76
|
+
*
|
|
77
|
+
* The delta is measured as sent — `Buffer.byteLength` over the full string,
|
|
78
|
+
* never trimmed: a whitespace-only delta still moved the decoder, so `" "`
|
|
79
|
+
* estimates 1 token and `" abcde "` estimates 2. An empty delta carries
|
|
80
|
+
* nothing and estimates 0, never 1. An ESTIMATE, documented at the module
|
|
81
|
+
* top: the host publishes real counts only at step end, and the settled
|
|
82
|
+
* average stays the real figure.
|
|
83
|
+
*/
|
|
84
|
+
export function estimateDeltaTokens(delta: string): number {
|
|
85
|
+
const bytes = Buffer.byteLength(delta, "utf8");
|
|
86
|
+
return bytes > 0 ? Math.max(1, Math.ceil(bytes / 5)) : 0;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The realtime tracker: `active` is false when the host offers no subscription surface. */
|
|
90
|
+
export interface RealtimeTps {
|
|
91
|
+
/** False when the host has no `data.on` (or it threw): the rate reads 0, never a guess. */
|
|
92
|
+
readonly active: boolean;
|
|
93
|
+
/**
|
|
94
|
+
* The smoothed realtime rate for one displayed session over `ids`.
|
|
95
|
+
*
|
|
96
|
+
* Scope `"session"` passes the displayed session alone; scope `"family"`
|
|
97
|
+
* passes the displayed session plus its family ids. Tokens sum across the
|
|
98
|
+
* ids while the denominator is the WINDOW's wall-clock coverage — merged
|
|
99
|
+
* sample times, so concurrent decoders share wall clock, the same choice
|
|
100
|
+
* the old poll figure and `elapsed` made.
|
|
101
|
+
*
|
|
102
|
+
* A scope with no sample reads 0 (first sight, never a guess), and so does
|
|
103
|
+
* a scope whose newest sample is older than `RT_STALE_MS`. Staleness leaves
|
|
104
|
+
* the smoother untouched, so the next fresh sample resumes from the held
|
|
105
|
+
* figure rather than from zero. There are no baselines to set — samples ARE
|
|
106
|
+
* deltas already — and no backwards-counter branch: deltas are always
|
|
107
|
+
* additive, so a reset can never arrive.
|
|
108
|
+
*
|
|
109
|
+
* Fresh on every call: no cache here. The 1s cache stays on the
|
|
110
|
+
* settled-average scan only.
|
|
111
|
+
*/
|
|
112
|
+
rate(displayedSessionID: string, ids: readonly string[]): number;
|
|
113
|
+
/**
|
|
114
|
+
* The mean time to first token over `ids`, in seconds — the oc-tps third
|
|
115
|
+
* figure, reachable from the same event stream.
|
|
116
|
+
*
|
|
117
|
+
* The mean covers the most recent finalized steps observed while the
|
|
118
|
+
* plugin ran (in-memory lifetime): per step, the earliest text/reasoning
|
|
119
|
+
* delta's event time for its `assistantMessageID` minus the step's
|
|
120
|
+
* `started` ("Request dispatch time, before waiting for provider
|
|
121
|
+
* output"), clamped at 0, pushed into the session's ring when the step
|
|
122
|
+
* ends or fails. A step's TTFT appears once that step settles — never
|
|
123
|
+
* while it streams — and a step that settles without any delta contributes
|
|
124
|
+
* nothing. Scope `"session"` means the displayed session's own ring;
|
|
125
|
+
* `"family"` pools every member's rings into one mean. `undefined` while
|
|
126
|
+
* no finalized value is retained — the both line omits the segment rather
|
|
127
|
+
* than inventing one.
|
|
128
|
+
*
|
|
129
|
+
* Fresh on every call: it means the retained values, never a held figure.
|
|
130
|
+
*/
|
|
131
|
+
ttft(ids: readonly string[]): number | undefined;
|
|
132
|
+
/** Drop the host subscriptions and the samples. Idempotent. */
|
|
133
|
+
dispose(): void;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** One delta event's untrusted payload, coerced before use. */
|
|
137
|
+
interface DeltaReading {
|
|
138
|
+
readonly sessionID: string;
|
|
139
|
+
readonly delta: string;
|
|
140
|
+
readonly at: number;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function createRealtimeTps(
|
|
144
|
+
context: Plugin.Context,
|
|
145
|
+
opts?: { readonly now?: () => number },
|
|
146
|
+
): RealtimeTps {
|
|
147
|
+
const now = opts?.now ?? Date.now;
|
|
148
|
+
const samples = new Map<string, RealtimeSample[]>();
|
|
149
|
+
const shown = new Map<string, { smoothed: number | undefined; displayed: number | undefined }>();
|
|
150
|
+
// TTFT state, same lifetime as the samples: pending steps keyed by
|
|
151
|
+
// `assistantMessageID`, and per-session rings of finalized step values.
|
|
152
|
+
// Corrections happen ONLY inside the pending entry — the earliest delta
|
|
153
|
+
// stamp seen — so no session-level arithmetic can drift: the mean derives
|
|
154
|
+
// from retained values on read, and eviction drops whole values. Both maps
|
|
155
|
+
// are bounded: pending steps by the sample ring's bound, rings by session
|
|
156
|
+
// count and per-session value count.
|
|
157
|
+
const pendingStarts = new Map<string, { sessionID: string; started: number; earliest: number | undefined }>();
|
|
158
|
+
const ttftRings = new Map<string, number[]>();
|
|
159
|
+
let disposed = false;
|
|
160
|
+
let active = false;
|
|
161
|
+
const releases: Array<() => void> = [];
|
|
162
|
+
|
|
163
|
+
const remember = (sessionID: string, sample: RealtimeSample): void => {
|
|
164
|
+
const known = samples.get(sessionID);
|
|
165
|
+
if (known !== undefined) {
|
|
166
|
+
// Recency refreshes on every sample, so the streaming session is the
|
|
167
|
+
// last one evicted — the same discipline the old tracker map used.
|
|
168
|
+
samples.delete(sessionID);
|
|
169
|
+
known.push(sample);
|
|
170
|
+
samples.set(sessionID, known);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
if (samples.size >= RT_MAX_SESSIONS) {
|
|
174
|
+
for (const oldest of samples.keys()) {
|
|
175
|
+
samples.delete(oldest);
|
|
176
|
+
break;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
samples.set(sessionID, [sample]);
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
const readDelta = (event: unknown): DeltaReading | undefined => {
|
|
183
|
+
const record = asRecord(event);
|
|
184
|
+
const data = asRecord(record?.["data"]);
|
|
185
|
+
const sessionID = asText(data?.["sessionID"]);
|
|
186
|
+
// The delta is byte-measured, never coerced: `asText` trims and rejects
|
|
187
|
+
// whitespace-only strings, which would estimate a whitespace-first token
|
|
188
|
+
// as nothing and hide it from TTFT. A raw string — even empty or blank —
|
|
189
|
+
// is a real decoder event with a real timestamp.
|
|
190
|
+
const raw = data?.["delta"];
|
|
191
|
+
const delta = typeof raw === "string" ? raw : undefined;
|
|
192
|
+
if (sessionID === undefined || delta === undefined) return undefined;
|
|
193
|
+
// The host's own event clock, not ours: `created` is when the decoder
|
|
194
|
+
// moved. A missing stamp falls back to now rather than dropping work.
|
|
195
|
+
const at = asCount(record?.["created"]) ?? now();
|
|
196
|
+
return { sessionID, delta, at };
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
const ingest = (event: unknown): void => {
|
|
200
|
+
if (disposed) return;
|
|
201
|
+
const reading = readDelta(event);
|
|
202
|
+
if (reading === undefined) return;
|
|
203
|
+
remember(reading.sessionID, { at: reading.at, tokens: estimateDeltaTokens(reading.delta) });
|
|
204
|
+
noteDelta(event, reading.at);
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Record one step's delta timestamp while the step is pending.
|
|
209
|
+
*
|
|
210
|
+
* Delivery order is not trusted: the earliest stamp wins, so a
|
|
211
|
+
* later-received delta carrying an earlier time corrects the step in place.
|
|
212
|
+
* A delta at or after the best stamp is a duplicate, never a re-count. No
|
|
213
|
+
* session-level arithmetic happens here — the mean derives from finalized
|
|
214
|
+
* values on read, so a correction can never drift or negate a total.
|
|
215
|
+
*/
|
|
216
|
+
const noteDelta = (event: unknown, at: number): void => {
|
|
217
|
+
const messageID = asText(asRecord(asRecord(event)?.["data"])?.["assistantMessageID"]);
|
|
218
|
+
if (messageID === undefined) return;
|
|
219
|
+
const pending = pendingStarts.get(messageID);
|
|
220
|
+
if (pending === undefined) return;
|
|
221
|
+
if (pending.earliest === undefined || at < pending.earliest) pending.earliest = at;
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
const stepStarted = (event: unknown): void => {
|
|
225
|
+
if (disposed) return;
|
|
226
|
+
const data = asRecord(asRecord(event)?.["data"]);
|
|
227
|
+
const sessionID = asText(data?.["sessionID"]);
|
|
228
|
+
const messageID = asText(data?.["assistantMessageID"]);
|
|
229
|
+
// `started` is the dispatch clock: "Request dispatch time, before waiting
|
|
230
|
+
// for provider output" — used uniformly for every step, never the
|
|
231
|
+
// execution start. A step without a usable dispatch stamp cannot time
|
|
232
|
+
// its first token, so it is skipped rather than guessed at.
|
|
233
|
+
const started = asCount(data?.["started"]);
|
|
234
|
+
if (sessionID === undefined || messageID === undefined || started === undefined) return;
|
|
235
|
+
pendingStarts.delete(messageID);
|
|
236
|
+
if (pendingStarts.size >= RT_MAX_SESSIONS) {
|
|
237
|
+
for (const oldest of pendingStarts.keys()) {
|
|
238
|
+
pendingStarts.delete(oldest);
|
|
239
|
+
break;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
pendingStarts.set(messageID, { sessionID, started, earliest: undefined });
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
const stepSettled = (event: unknown): void => {
|
|
246
|
+
if (disposed) return;
|
|
247
|
+
const messageID = asText(asRecord(asRecord(event)?.["data"])?.["assistantMessageID"]);
|
|
248
|
+
if (messageID === undefined) return;
|
|
249
|
+
const pending = pendingStarts.get(messageID);
|
|
250
|
+
// Finalize: the pending entry is always dropped. A step that settled
|
|
251
|
+
// without any delta contributes nothing; otherwise its single value —
|
|
252
|
+
// the earliest delta's event time minus dispatch, clamped at 0 — is
|
|
253
|
+
// pushed into the session's ring. The ring drops whole values
|
|
254
|
+
// oldest-first when full, so eviction can only omit steps, never invent
|
|
255
|
+
// or negate them.
|
|
256
|
+
pendingStarts.delete(messageID);
|
|
257
|
+
if (pending === undefined || pending.earliest === undefined) return;
|
|
258
|
+
const value = Math.max(0, pending.earliest - pending.started);
|
|
259
|
+
const ring = ttftRings.get(pending.sessionID);
|
|
260
|
+
if (ring !== undefined) {
|
|
261
|
+
ttftRings.delete(pending.sessionID);
|
|
262
|
+
ring.push(value);
|
|
263
|
+
if (ring.length > RT_MAX_STEPS) ring.splice(0, ring.length - RT_MAX_STEPS);
|
|
264
|
+
ttftRings.set(pending.sessionID, ring);
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
if (ttftRings.size >= RT_MAX_SESSIONS) {
|
|
268
|
+
for (const oldest of ttftRings.keys()) {
|
|
269
|
+
ttftRings.delete(oldest);
|
|
270
|
+
break;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
ttftRings.set(pending.sessionID, [value]);
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
// Each subscription stands on its own: the release is retained the moment
|
|
277
|
+
// the call succeeds, so a host that rejects one event keeps the ones it
|
|
278
|
+
// accepted — partial data, with the missing figures degrading naturally —
|
|
279
|
+
// and a failure can never strand an earlier release. The tracker is live
|
|
280
|
+
// while at least one subscription landed.
|
|
281
|
+
try {
|
|
282
|
+
const on = (context as { data?: { on?: unknown } }).data?.on;
|
|
283
|
+
if (typeof on === "function") {
|
|
284
|
+
const subscribe = on as Plugin.Context["data"]["on"];
|
|
285
|
+
const track = (
|
|
286
|
+
type: "session.text.delta" | "session.reasoning.delta" | "session.step.started" | "session.step.ended" | "session.step.failed",
|
|
287
|
+
handler: (event: unknown) => void,
|
|
288
|
+
): void => {
|
|
289
|
+
try {
|
|
290
|
+
releases.push(subscribe(type, handler));
|
|
291
|
+
} catch {
|
|
292
|
+
// This event stays unsubscribed; the releases already held survive.
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
track("session.text.delta", ingest);
|
|
296
|
+
track("session.reasoning.delta", ingest);
|
|
297
|
+
track("session.step.started", stepStarted);
|
|
298
|
+
track("session.step.ended", stepSettled);
|
|
299
|
+
track("session.step.failed", stepSettled);
|
|
300
|
+
active = releases.length > 0;
|
|
301
|
+
}
|
|
302
|
+
} catch {
|
|
303
|
+
// No subscription surface on this host (missing or throwing): the tracker
|
|
304
|
+
// stays degraded and the rate reads 0, never a guess.
|
|
305
|
+
active = false;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Wall-clock coverage of merged sample times, in the oc-tps shape: the gaps
|
|
310
|
+
* between consecutive samples plus the tail to now — concurrent decoders
|
|
311
|
+
* interleave into the same gaps, so they share wall clock instead of adding
|
|
312
|
+
* it. One lone sample clamps to [250, 1000] ms: a single delta proves the
|
|
313
|
+
* decoder moved, but picosecond precision would fake a rate the sample never
|
|
314
|
+
* had.
|
|
315
|
+
*/
|
|
316
|
+
const coverageMs = (ordered: readonly RealtimeSample[], at: number): number => {
|
|
317
|
+
const first = ordered[0];
|
|
318
|
+
if (first === undefined) return 0;
|
|
319
|
+
if (ordered.length === 1) {
|
|
320
|
+
return Math.min(Math.max(at - first.at, 250), 1_000);
|
|
321
|
+
}
|
|
322
|
+
let duration = 0;
|
|
323
|
+
for (let index = 1; index < ordered.length; index += 1) {
|
|
324
|
+
duration += Math.max(0, (ordered[index]?.at ?? 0) - (ordered[index - 1]?.at ?? 0));
|
|
325
|
+
}
|
|
326
|
+
duration += Math.max(0, at - (ordered[ordered.length - 1]?.at ?? at));
|
|
327
|
+
return duration;
|
|
328
|
+
};
|
|
329
|
+
|
|
330
|
+
const shownOf = (displayedSessionID: string): { smoothed: number | undefined; displayed: number | undefined } => {
|
|
331
|
+
const known = shown.get(displayedSessionID);
|
|
332
|
+
if (known !== undefined) {
|
|
333
|
+
shown.delete(displayedSessionID);
|
|
334
|
+
shown.set(displayedSessionID, known);
|
|
335
|
+
return known;
|
|
336
|
+
}
|
|
337
|
+
const fresh = { smoothed: undefined as number | undefined, displayed: undefined as number | undefined };
|
|
338
|
+
if (shown.size >= RT_MAX_SESSIONS) {
|
|
339
|
+
for (const oldest of shown.keys()) {
|
|
340
|
+
shown.delete(oldest);
|
|
341
|
+
break;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
shown.set(displayedSessionID, fresh);
|
|
345
|
+
return fresh;
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
const rate = (displayedSessionID: string, ids: readonly string[]): number => {
|
|
349
|
+
if (!active || disposed) return 0;
|
|
350
|
+
const at = now();
|
|
351
|
+
const seen = new Set<string>();
|
|
352
|
+
const windowed: RealtimeSample[] = [];
|
|
353
|
+
let newest = Number.NEGATIVE_INFINITY;
|
|
354
|
+
for (const id of ids) {
|
|
355
|
+
if (typeof id !== "string" || seen.has(id)) continue;
|
|
356
|
+
seen.add(id);
|
|
357
|
+
const ring = samples.get(id);
|
|
358
|
+
if (ring === undefined) continue;
|
|
359
|
+
const kept = ring.filter((sample) => at - sample.at <= RT_SAMPLE_WINDOW_MS);
|
|
360
|
+
if (kept.length !== ring.length) {
|
|
361
|
+
// Lazy prune: no timer, so the window is enforced on read. An emptied
|
|
362
|
+
// ring leaves no trace — the session reads as a first sight again.
|
|
363
|
+
if (kept.length === 0) samples.delete(id);
|
|
364
|
+
else samples.set(id, kept);
|
|
365
|
+
}
|
|
366
|
+
// Per-session staleness: a member with no sample for ~1.5s contributes
|
|
367
|
+
// 0, even while a sibling still streams — the decoder is between turns
|
|
368
|
+
// or done, so its history must not pace the family.
|
|
369
|
+
let idNewest = Number.NEGATIVE_INFINITY;
|
|
370
|
+
for (const sample of kept) {
|
|
371
|
+
if (sample.at > idNewest) idNewest = sample.at;
|
|
372
|
+
}
|
|
373
|
+
if (kept.length === 0 || at - idNewest > RT_STALE_MS) continue;
|
|
374
|
+
for (const sample of kept) {
|
|
375
|
+
windowed.push(sample);
|
|
376
|
+
if (sample.at > newest) newest = sample.at;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
// First sight reads 0: no samples, no rate — never a guess. Staleness
|
|
380
|
+
// reads 0 too, with the smoother untouched so recovery resumes held.
|
|
381
|
+
if (windowed.length === 0 || at - newest > RT_STALE_MS) return 0;
|
|
382
|
+
windowed.sort((a, b) => a.at - b.at);
|
|
383
|
+
const durationMs = coverageMs(windowed, at);
|
|
384
|
+
if (!(durationMs > 0)) return 0;
|
|
385
|
+
const tokens = windowed.reduce((sum, sample) => sum + sample.tokens, 0);
|
|
386
|
+
const instant = tokens / (durationMs / 1_000);
|
|
387
|
+
if (!Number.isFinite(instant) || instant <= 0) return 0;
|
|
388
|
+
const state = shownOf(displayedSessionID);
|
|
389
|
+
state.smoothed = smoothTpsRate(state.smoothed, instant, TPS_EWMA_ALPHA);
|
|
390
|
+
if (tpsNeedsRepaint(state.displayed, state.smoothed)) state.displayed = state.smoothed;
|
|
391
|
+
return state.displayed ?? 0;
|
|
392
|
+
};
|
|
393
|
+
|
|
394
|
+
const ttft = (ids: readonly string[]): number | undefined => {
|
|
395
|
+
if (!active || disposed) return undefined;
|
|
396
|
+
const seen = new Set<string>();
|
|
397
|
+
let totalMs = 0;
|
|
398
|
+
let count = 0;
|
|
399
|
+
for (const id of ids) {
|
|
400
|
+
if (typeof id !== "string" || seen.has(id)) continue;
|
|
401
|
+
seen.add(id);
|
|
402
|
+
const ring = ttftRings.get(id);
|
|
403
|
+
if (ring === undefined) continue;
|
|
404
|
+
for (const value of ring) {
|
|
405
|
+
totalMs += value;
|
|
406
|
+
count += 1;
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
// No finalized value retained: unknown, never a guess — the both line
|
|
410
|
+
// omits the segment rather than inventing one.
|
|
411
|
+
if (count === 0) return undefined;
|
|
412
|
+
return totalMs / count / 1_000;
|
|
413
|
+
};
|
|
414
|
+
|
|
415
|
+
const dispose = (): void => {
|
|
416
|
+
if (disposed) return;
|
|
417
|
+
disposed = true;
|
|
418
|
+
for (const release of releases) {
|
|
419
|
+
try {
|
|
420
|
+
release();
|
|
421
|
+
} catch {
|
|
422
|
+
// A failing unsubscribe must not break plugin unload.
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
releases.length = 0;
|
|
426
|
+
samples.clear();
|
|
427
|
+
shown.clear();
|
|
428
|
+
pendingStarts.clear();
|
|
429
|
+
ttftRings.clear();
|
|
430
|
+
};
|
|
431
|
+
|
|
432
|
+
return { get active() { return active && !disposed; }, rate, ttft, dispose };
|
|
433
|
+
}
|