@jack-yang/pi-tps-meter 0.1.1 → 0.3.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 +21 -0
- package/README.md +24 -15
- package/extensions/index.ts +202 -16
- package/package.json +2 -2
- package/src/config.ts +37 -7
- package/src/core.ts +7 -0
- package/src/footer.ts +27 -0
- package/src/format.ts +36 -1
- package/src/spinner.ts +84 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,26 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.3.0] - 2026-11-04
|
|
4
|
+
|
|
5
|
+
- New default display `footer`: the meter sits at the right end of pi's footer line with the
|
|
6
|
+
working directory, in line with the model name below it, without taking an extra line. pi's
|
|
7
|
+
own `FooterComponent` still renders the whole footer (the stats and status lines are
|
|
8
|
+
byte-for-byte pi's); the meter is merged into its first line. On a narrow terminal the
|
|
9
|
+
directory is shortened first, so the reading stays whole.
|
|
10
|
+
- If pi's footer cannot be wrapped (for example a future pi changes its internals), pi's own
|
|
11
|
+
footer is restored and the meter falls back to `right`, with a one-time notice.
|
|
12
|
+
- `/tps` cycles footer → right → status → widget → off; a saved `mode` still wins.
|
|
13
|
+
|
|
14
|
+
## [0.2.0] - 2026-11-03
|
|
15
|
+
|
|
16
|
+
- New default display `right`: one line below the editor, right-aligned so it ends in the last
|
|
17
|
+
column, directly above the footer. Other extensions' footer statuses (such as pi-lens's
|
|
18
|
+
`LSP Inactive`) can no longer push it around. `/tps` now cycles right → status → widget → off;
|
|
19
|
+
a saved `mode` in config.json still wins.
|
|
20
|
+
- The thinking particle stream from opencode-tps-meter is back: while the model streams its
|
|
21
|
+
reasoning, braille particles flow away from the reading, newest brightest, fading per cell.
|
|
22
|
+
Configurable via `spinner` (`theme` tech / red / none, `colors`, `intervalMs`, `cells`, `enabled`).
|
|
23
|
+
|
|
3
24
|
## [0.1.1] - 2026-11-03
|
|
4
25
|
|
|
5
26
|
- Published from GitHub Actions through npm Trusted Publishing, so this and later versions
|
package/README.md
CHANGED
|
@@ -9,20 +9,17 @@
|
|
|
9
9
|
## 显示效果
|
|
10
10
|
|
|
11
11
|
```
|
|
12
|
-
TPS 42.5 | AVG 38.2 | TTFT 0.8s
|
|
12
|
+
⠔⠀⠈⠀⠤⠔ TPS 42.5 | AVG 38.2 | TTFT 0.8s
|
|
13
13
|
```
|
|
14
14
|
|
|
15
|
-
|
|
15
|
+
默认显示在 footer 的目录那一行右端(`/tps footer`),和下一行的模型名右对齐,不额外占行;其他扩展的 footer 状态(比如 pi-lens 的 `LSP Inactive`)也挤不动它。下图是模型思考时的样子,读数左边是思考粒子流:
|
|
16
16
|
|
|
17
|
-

|
|
17
|
+

|
|
22
18
|
|
|
23
19
|
- **TPS**:流式输出时的实时速度,基于 5 秒滑动窗口,约 10Hz 刷新;超过 1.5 秒没有新 token 时显示 `--`。
|
|
24
20
|
- **AVG**:会话级累计平均。所有已完成消息的权威 token 数之和,除以各消息生成时长之和。
|
|
25
21
|
- **TTFT**:从本轮请求开始到第一个文本或思考 token 的时间。首个 token 到达立即显示,一直保留到下一次生成开始。
|
|
22
|
+
- **思考粒子流**:模型流式输出思考内容时,一串盲文点从读数旁流出:最新的一格最亮,越旧越淡,亮色随时间沿渐变色漂移;开始输出正文就消失。只在思考时出现,平时不占位。
|
|
26
23
|
|
|
27
24
|
流结束后 AVG / TTFT 摘要不会清空:工具执行期间、等待下一轮响应期间都保持可见,下一条助手消息开始时才更新。
|
|
28
25
|
|
|
@@ -65,32 +62,44 @@ pi -e npm:@jack-yang/pi-tps-meter # 只在本次启动试用,不写
|
|
|
65
62
|
|
|
66
63
|
| 命令 | 作用 |
|
|
67
64
|
|---|---|
|
|
68
|
-
| `/tps` | 循环切换 status → widget → off |
|
|
69
|
-
| `/tps
|
|
70
|
-
| `/tps
|
|
65
|
+
| `/tps` | 循环切换 footer → right → status → widget → off |
|
|
66
|
+
| `/tps footer` | footer 的目录那一行右端(默认),不额外占行 |
|
|
67
|
+
| `/tps right` | 编辑器下方单独一行,右对齐,紧贴 footer |
|
|
68
|
+
| `/tps status` | footer 的扩展状态行,和其他扩展共用一行,按扩展名排序 |
|
|
69
|
+
| `/tps widget` | 编辑器上方的单行组件 |
|
|
71
70
|
| `/tps off` | 完全隐藏。计量仍在后台进行,切回来立即显示当前读数 |
|
|
72
71
|
|
|
73
72
|
模式写入配置文件,下次启动沿用。
|
|
74
73
|
|
|
74
|
+
`footer` 模式是怎么做的:pi 的 footer 没有给扩展留定位的口子(扩展状态只能左对齐拼在最后一行),所以这里用 `setFooter` 挂了一个包装层:里面跑的就是 pi 自己导出的 `FooterComponent`,统计行、状态行都由 pi 自己渲染,实测和原装 footer 逐字符、连颜色都一致;只是在目录那一行右端补上读数。终端变窄时先截短目录(和 pi 一样用 `...`),读数保持完整;中文目录名按双宽字符计算。如果将来某个 pi 版本改了 footer 内部导致包装失败,会自动恢复 pi 原装 footer、退回 `right` 模式并提示一次,不会把 footer 弄坏。
|
|
75
|
+
|
|
76
|
+
如果也嫌 pi-lens 的 `LSP Inactive` 占地方,pi-lens 自己有开关:在 `~/.pi-lens/config.json` 里设 `ui.compactLspStatus: true`(压成一个图标)或 `ui.hideLspStatus: true`(不显示)。
|
|
77
|
+
|
|
75
78
|
## 配置
|
|
76
79
|
|
|
77
80
|
配置文件位于 `~/.pi/agent/pi-tps-meter/config.json`;设置了 `PI_CODING_AGENT_DIR` 时,位于该目录下的 `pi-tps-meter/config.json`。
|
|
78
81
|
|
|
79
82
|
```json
|
|
80
83
|
{
|
|
81
|
-
"mode": "
|
|
84
|
+
"mode": "footer",
|
|
82
85
|
"tiers": {
|
|
83
86
|
"tps": { "slow": 20, "normal": 50, "fast": 100 },
|
|
84
87
|
"ttft": { "fast": 10000, "ok": 20000 }
|
|
85
|
-
}
|
|
88
|
+
},
|
|
89
|
+
"spinner": { "theme": "tech", "intervalMs": 100, "cells": 6 }
|
|
86
90
|
}
|
|
87
91
|
```
|
|
88
92
|
|
|
89
93
|
| 键 | 默认值 | 说明 |
|
|
90
94
|
|---|---|---|
|
|
91
|
-
| `mode` | `"
|
|
95
|
+
| `mode` | `"footer"` | `footer` / `right` / `status` / `widget` / `off`。`/tps` 只改写这个键,其他内容原样保留 |
|
|
92
96
|
| `tiers.tps` | `{ slow: 20, normal: 50, fast: 100 }` | TPS 与 AVG 的分档阈值(tok/s) |
|
|
93
97
|
| `tiers.ttft` | `{ fast: 10000, ok: 20000 }` | TTFT 分档阈值(毫秒) |
|
|
98
|
+
| `spinner.theme` | `"tech"` | 粒子流配色:`"tech"`(青 → 蓝 → 紫)、`"red"`(KITT 风格红);`"none"` 关闭粒子流 |
|
|
99
|
+
| `spinner.colors` | 随 theme | 自定义渐变色,`"#rrggbb"` / `"#rgb"` 数组,优先于 theme |
|
|
100
|
+
| `spinner.intervalMs` | `100` | 粒子前进一格的间隔(毫秒) |
|
|
101
|
+
| `spinner.cells` | `6` | 粒子流格数(宽度),至少 2 |
|
|
102
|
+
| `spinner.enabled` | `true` | `false` 关闭粒子流 |
|
|
94
103
|
|
|
95
104
|
- 所有键都可省略,按字段覆盖默认值,例如只写 `{ "tiers": { "tps": { "fast": 80 } } }`。不是数字的值会被忽略。
|
|
96
105
|
- 文件在会话启动时读取,手动修改后执行 `/reload` 生效。
|
|
@@ -138,14 +147,14 @@ TTFT 从 `turn_start` 开始计时(在 pi 里,一个 turn 就是一次模型
|
|
|
138
147
|
- 下一条助手消息开始时清空 TTFT,原版要等到下一个首 token 才覆盖。
|
|
139
148
|
- toolcall delta 计入 TPS 和校准,因为 pi 的 `usage.output` 包含工具调用参数的 token;原版只统计文本和推理。TTFT 仍然只认文本和思考。
|
|
140
149
|
- 权威 token 数直接用 `usage.output`:pi 的 output 已经包含推理 token,原版需要把 output 和 reasoning 相加。
|
|
141
|
-
-
|
|
150
|
+
- 思考粒子流已移植(配色预设、渐变、FIFO 流动、配置项都和原版一致),并做了原版想做但受限于 opencode 做不到的一点:每个粒子单独着色,真正从亮到暗渐隐(原版受 opentui 限制,整串只能用一种颜色)。右对齐时粒子流放在读数左边、方向镜像,读数本身不会移动。
|
|
142
151
|
- 颜色用 ANSI 基本色:红 31、黄 33、绿 32、青 36,标签用暗色;原版用的是 opencode 主题槽位。
|
|
143
152
|
|
|
144
153
|
## 已知限制
|
|
145
154
|
|
|
146
155
|
- **不流式输出的推理**:有些模型按推理 token 计费,但不把推理内容流式发出来。这时校准比率会顶到 3.0 上限,AVG 也会偏高(原版同样如此)。
|
|
147
156
|
- **一次性返回工具参数的 provider**(如 Gemini):消息末尾会出现一个短暂的 TPS 尖峰,消息结束后立即清除。
|
|
148
|
-
-
|
|
157
|
+
- **`footer` 和其他替换 footer 的扩展互斥**:pi 同一时间只有一个 footer,后设置的生效。如果还开着 awesome-pi-themes 的 look-pack 这类扩展,改用 `/tps right`。`status` 模式也依赖 pi 的默认 footer(look-pack 不渲染扩展状态)。
|
|
149
158
|
- **AVG 和校准只在当前会话内累计**:`/new`、`/resume`、`/fork`、`/reload` 会重新开始;不会从历史记录里重建。
|
|
150
159
|
- **TTFT 包含客户端准备时间**:包括请求前的上下文处理(实测约 7ms)和 provider 层的自动重试等待,也就是用户实际等待的时间。
|
|
151
160
|
- **时间戳取自 pi 把事件派发给扩展的时刻**:其他扩展的慢 handler 会推迟派发,从而影响读数。
|
package/extensions/index.ts
CHANGED
|
@@ -1,39 +1,211 @@
|
|
|
1
1
|
// pi-tps-meter — live TPS / AVG / TTFT for the pi coding agent.
|
|
2
2
|
//
|
|
3
|
-
// Port of opencode-tps-meter: the measurement core (src/core.ts)
|
|
4
|
-
// (src/
|
|
5
|
-
//
|
|
3
|
+
// Port of opencode-tps-meter: the measurement core (src/core.ts), the formatting (src/format.ts)
|
|
4
|
+
// and the thinking particle stream (src/spinner.ts) are the original's. This file is the replaced
|
|
5
|
+
// host layer: pi events in; the meter out on pi's footer line (by wrapping pi's own footer), a
|
|
6
|
+
// right-aligned line below the editor, a footer status, or a line above the editor.
|
|
6
7
|
|
|
7
|
-
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent"
|
|
8
|
+
import type { ExtensionAPI, ExtensionContext, ReadonlyFooterDataProvider } from "@earendil-works/pi-coding-agent"
|
|
8
9
|
import { DISPLAY_MODES, isDisplayMode, loadConfig, nextMode, resolveConfig, saveMode, type DisplayMode, type MeterConfig } from "../src/config.ts"
|
|
9
10
|
import { abandonMessage, completeMessage, createMeterState, readMeter, recordDelta, startMessage, startTurn, type DeltaKind, type MeterState } from "../src/core.ts"
|
|
10
|
-
import {
|
|
11
|
+
import { mergeFooterLine } from "../src/footer.ts"
|
|
12
|
+
import { alignRight, renderLine, withSpinner } from "../src/format.ts"
|
|
13
|
+
import { advanceSpinner, createSpinner, spinnerCells, type Rgb, type SpinnerState } from "../src/spinner.ts"
|
|
11
14
|
|
|
12
|
-
// One key for
|
|
15
|
+
// One key for every surface: the footer status entry and the widget.
|
|
13
16
|
const KEY = "tps-meter"
|
|
14
17
|
|
|
15
18
|
// ~10Hz: smooth enough for a rolling number without re-rendering on every delta.
|
|
16
19
|
const REFRESH_MS = 100
|
|
17
20
|
|
|
21
|
+
// Older particles fade toward this neutral grey (the original faded toward the theme's muted text).
|
|
22
|
+
const SPINNER_MUTED: Rgb = { r: 128, g: 132, b: 142 }
|
|
23
|
+
|
|
18
24
|
type UI = ExtensionContext["ui"]
|
|
25
|
+
type Model = NonNullable<ExtensionContext["model"]>
|
|
26
|
+
|
|
27
|
+
// The part of pi's AgentSession that pi's FooterComponent reads, rebuilt from what an extension
|
|
28
|
+
// can see. pi does not hand extensions its session, but its footer only needs these members.
|
|
29
|
+
export type SessionView = {
|
|
30
|
+
readonly sessionManager: ExtensionContext["sessionManager"]
|
|
31
|
+
readonly model: ExtensionContext["model"]
|
|
32
|
+
readonly state: { model: ExtensionContext["model"]; thinkingLevel: string }
|
|
33
|
+
readonly routedModel: { model: Model; thinkingLevel?: string } | undefined
|
|
34
|
+
readonly modelRuntime: { isUsingSubscription(provider: string): boolean }
|
|
35
|
+
getContextUsage(): ReturnType<ExtensionContext["getContextUsage"]>
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export type FooterLike = { render(width: number): string[]; invalidate(): void; dispose?(): void; setAutoCompactEnabled(enabled: boolean): void }
|
|
39
|
+
|
|
40
|
+
// pi runtime pieces the footer mode needs; loaded on demand (and injected in tests, which run on
|
|
41
|
+
// plain Node without pi).
|
|
42
|
+
export type FooterKit = {
|
|
43
|
+
createFooter(session: SessionView, footerData: ReadonlyFooterDataProvider): FooterLike
|
|
44
|
+
visibleWidth(text: string): number
|
|
45
|
+
truncateToWidth(text: string, width: number, ellipsis?: string): string
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export type Deps = { loadFooterKit?: () => Promise<FooterKit> }
|
|
49
|
+
|
|
50
|
+
async function loadPiFooterKit(): Promise<FooterKit> {
|
|
51
|
+
const [core, tuiLib] = await Promise.all([import("@earendil-works/pi-coding-agent"), import("@earendil-works/pi-tui")])
|
|
52
|
+
type Session = ConstructorParameters<typeof core.FooterComponent>[0]
|
|
53
|
+
return {
|
|
54
|
+
createFooter: (session, footerData) => {
|
|
55
|
+
// SAFETY: FooterComponent is typed to take pi's whole AgentSession, which extensions never
|
|
56
|
+
// get. In pi 1.5.0 (dist/modes/interactive/components/footer.js) it reads exactly the members
|
|
57
|
+
// SessionView provides: sessionManager.{getCwd, getEntries, getEntryCount, getLeafId,
|
|
58
|
+
// getSessionId, getSessionName}, model, state.{model, thinkingLevel}, routedModel,
|
|
59
|
+
// modelRuntime.isUsingSubscription and getContextUsage(). If a later pi reads anything else,
|
|
60
|
+
// render() throws, the wrapper catches it, and fallBack() restores pi's own footer.
|
|
61
|
+
const agentSession = session as unknown as Session
|
|
62
|
+
return new core.FooterComponent(agentSession, footerData)
|
|
63
|
+
},
|
|
64
|
+
visibleWidth: tuiLib.visibleWidth,
|
|
65
|
+
truncateToWidth: tuiLib.truncateToWidth,
|
|
66
|
+
}
|
|
67
|
+
}
|
|
19
68
|
|
|
20
69
|
export default function tpsMeter(pi: ExtensionAPI): void {
|
|
70
|
+
createTpsMeter(pi)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function createTpsMeter(pi: ExtensionAPI, deps: Deps = {}): void {
|
|
74
|
+
const loadFooterKit = deps.loadFooterKit ?? loadPiFooterKit
|
|
21
75
|
let state: MeterState = createMeterState()
|
|
22
76
|
// Defaults until session_start reads the file: the factory may run in invocations that never
|
|
23
77
|
// start a session, so it does no IO and starts no timers.
|
|
24
78
|
let config: MeterConfig = resolveConfig(undefined)
|
|
79
|
+
let ctxRef: ExtensionContext | undefined
|
|
25
80
|
let ui: UI | undefined
|
|
26
|
-
let
|
|
81
|
+
let tui = false
|
|
27
82
|
let ticker: ReturnType<typeof setInterval> | undefined
|
|
83
|
+
let spinner: SpinnerState | undefined
|
|
28
84
|
// What is on screen right now, so unchanged readings cost no re-render.
|
|
29
85
|
let shownMode: DisplayMode | undefined
|
|
30
86
|
let shownLine: string | undefined
|
|
87
|
+
// The mounted component's host (widget or footer), told to redraw when the line changes.
|
|
88
|
+
let host: { requestRender(): void } | undefined
|
|
89
|
+
// Bumped on every mode change, so a footer mount still loading for an older mode is dropped.
|
|
90
|
+
let mountEpoch = 0
|
|
31
91
|
|
|
32
92
|
// Handlers re-bind from their own ctx; the ticker only ever uses the latest binding.
|
|
33
93
|
const bind = (ctx: ExtensionContext): void => {
|
|
94
|
+
ctxRef = ctx
|
|
34
95
|
ui = ctx.hasUI ? ctx.ui : undefined
|
|
35
|
-
// The TUI renders ANSI
|
|
36
|
-
|
|
96
|
+
// The TUI renders ANSI and components; RPC clients get plain text lines.
|
|
97
|
+
tui = ctx.mode === "tui"
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// The particle stream exists only while reasoning streams, and only in the TUI (in RPC it would
|
|
101
|
+
// just be noise at 10Hz). A fresh stream starts each time thinking starts. Next to a
|
|
102
|
+
// right-aligned reading it goes on the left, so the reading itself never moves.
|
|
103
|
+
const decorate = (target: UI, line: string, now: number): string => {
|
|
104
|
+
if (!tui || !config.spinner.enabled || !state.thinking) {
|
|
105
|
+
spinner = undefined
|
|
106
|
+
return line
|
|
107
|
+
}
|
|
108
|
+
if (spinner === undefined) spinner = createSpinner(config.spinner.cells, now, Math.random)
|
|
109
|
+
else advanceSpinner(spinner, config.spinner, now, Math.random)
|
|
110
|
+
const paint = (text: string, c: Rgb) => target.theme.style(text, { fg: { kind: "rgb", r: c.r, g: c.g, b: c.b } })
|
|
111
|
+
const side = config.mode === "right" || config.mode === "footer" ? "before" : "after"
|
|
112
|
+
return withSpinner(line, spinnerCells(spinner, config.spinner, SPINNER_MUTED), paint, side)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// A component rather than a string widget: it right-aligns itself to the width of every render,
|
|
116
|
+
// so it stays in the corner across terminal resizes, and an update is only a redraw request.
|
|
117
|
+
const mountRight = (target: UI): void => {
|
|
118
|
+
target.setWidget(KEY, (h) => {
|
|
119
|
+
host = h
|
|
120
|
+
return { render: (width: number) => [alignRight(shownLine ?? "", width)], invalidate() {} }
|
|
121
|
+
}, { placement: "belowEditor" })
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// pi's own footer, fed a SessionView, with the meter merged into its first (directory) line.
|
|
125
|
+
// Everything else on the footer stays pi's rendering.
|
|
126
|
+
const sessionView: SessionView = {
|
|
127
|
+
// Only read inside a mounted footer, which exists only after bind(); a throw here is caught
|
|
128
|
+
// by the footer's render() and ends in fallBack().
|
|
129
|
+
get sessionManager() {
|
|
130
|
+
if (!ctxRef) throw new Error("no session bound")
|
|
131
|
+
return ctxRef.sessionManager
|
|
132
|
+
},
|
|
133
|
+
get model() { return ctxRef?.model },
|
|
134
|
+
get state() { return { model: ctxRef?.model, thinkingLevel: pi.getThinkingLevel() } },
|
|
135
|
+
// As pi's AgentSession.routedModel: under a virtual model, the physical model of the latest
|
|
136
|
+
// successful response.
|
|
137
|
+
get routedModel() {
|
|
138
|
+
const model = ctxRef?.model
|
|
139
|
+
if (!ctxRef || !model || model.api !== "pi-virtual") return undefined
|
|
140
|
+
const branch = ctxRef.sessionManager.getBranch()
|
|
141
|
+
for (let i = branch.length - 1; i >= 0; i--) {
|
|
142
|
+
const entry = branch[i]
|
|
143
|
+
if (entry.type !== "message" || entry.message.role !== "assistant") continue
|
|
144
|
+
const m = entry.message
|
|
145
|
+
if (m.stopReason === "error" || m.stopReason === "aborted") continue
|
|
146
|
+
const physical = ctxRef.modelRegistry.find(m.provider, m.model)
|
|
147
|
+
return physical ? { model: physical, thinkingLevel: (m as { thinkingLevel?: string }).thinkingLevel } : undefined
|
|
148
|
+
}
|
|
149
|
+
return undefined
|
|
150
|
+
},
|
|
151
|
+
// As pi's ModelRuntime.isUsingSubscription: OAuth credentials for a subscription provider.
|
|
152
|
+
// The footer asks this about the current model's provider; ModelRegistry.isUsingOAuth takes
|
|
153
|
+
// the model and reads its provider.
|
|
154
|
+
modelRuntime: {
|
|
155
|
+
isUsingSubscription: (provider) => {
|
|
156
|
+
const registry = ctxRef?.modelRegistry
|
|
157
|
+
const model = ctxRef?.model
|
|
158
|
+
if (!registry || model?.provider !== provider || !registry.isUsingOAuth(model)) return false
|
|
159
|
+
const p = registry.getProvider(provider) as { auth?: { oauth?: { isSubscription?: boolean } } } | undefined
|
|
160
|
+
return p?.auth?.oauth?.isSubscription === true
|
|
161
|
+
},
|
|
162
|
+
},
|
|
163
|
+
getContextUsage: () => ctxRef?.getContextUsage(),
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// If pi's footer cannot be wrapped (an older or newer pi changed it), never leave the user
|
|
167
|
+
// without a footer: restore pi's, fall back to the line below the editor, say so once.
|
|
168
|
+
// If pi's footer cannot be wrapped (an older or newer pi changed it), never leave the user
|
|
169
|
+
// without a footer: fall back to the line below the editor (leaving footer mode is what restores
|
|
170
|
+
// pi's own footer, in render()) and say so once. A mount that is no longer current (the mode
|
|
171
|
+
// changed, or the session was replaced, since it started) is ignored, so a stale UI is never used.
|
|
172
|
+
const fallBack = (target: UI, epoch: number, reason: unknown): void => {
|
|
173
|
+
if (epoch !== mountEpoch || ui !== target || config.mode !== "footer") return
|
|
174
|
+
config = { ...config, mode: "right" }
|
|
175
|
+
target.notify(`tps-meter: footer mode unavailable here (${reason instanceof Error ? reason.message : String(reason)}), using right`, "warning")
|
|
176
|
+
render()
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const mountFooter = (target: UI, epoch: number): void => {
|
|
180
|
+
loadFooterKit().then((kit) => {
|
|
181
|
+
if (epoch !== mountEpoch || ui !== target) return
|
|
182
|
+
target.setFooter((h, theme, footerData) => {
|
|
183
|
+
host = h
|
|
184
|
+
const inner = kit.createFooter(sessionView, footerData)
|
|
185
|
+
const unsubscribe = footerData.onBranchChange(() => h.requestRender())
|
|
186
|
+
const fns = { visibleWidth: kit.visibleWidth, truncate: (text: string, width: number) => kit.truncateToWidth(text, width, theme.fg("dim", "...")) }
|
|
187
|
+
return {
|
|
188
|
+
render(width: number): string[] {
|
|
189
|
+
try {
|
|
190
|
+
// pi feeds this flag to its own footer instance; ours reads the same setting.
|
|
191
|
+
inner.setAutoCompactEnabled(pi.getSettings().compaction?.enabled ?? true)
|
|
192
|
+
const lines = inner.render(width)
|
|
193
|
+
if (lines.length > 0 && shownLine) lines[0] = mergeFooterLine(lines[0], shownLine, width, fns)
|
|
194
|
+
return lines
|
|
195
|
+
} catch (err) {
|
|
196
|
+
// Not from inside pi's render pass: swap the footer once this frame is done.
|
|
197
|
+
queueMicrotask(() => fallBack(target, epoch, err))
|
|
198
|
+
return []
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
invalidate() { inner.invalidate() },
|
|
202
|
+
dispose() {
|
|
203
|
+
unsubscribe()
|
|
204
|
+
inner.dispose?.()
|
|
205
|
+
},
|
|
206
|
+
}
|
|
207
|
+
})
|
|
208
|
+
}, (err: unknown) => fallBack(target, epoch, err))
|
|
37
209
|
}
|
|
38
210
|
|
|
39
211
|
const render = (): void => {
|
|
@@ -42,16 +214,26 @@ export default function tpsMeter(pi: ExtensionAPI): void {
|
|
|
42
214
|
if (mode !== shownMode) {
|
|
43
215
|
// Exactly one surface (or none) shows the meter: clear the one being left.
|
|
44
216
|
if (shownMode === "status") ui.setStatus(KEY, undefined)
|
|
45
|
-
if (shownMode === "widget") ui.setWidget(KEY, undefined)
|
|
217
|
+
if (shownMode === "widget" || shownMode === "right" || (shownMode === "footer" && !tui)) ui.setWidget(KEY, undefined)
|
|
218
|
+
if (shownMode === "footer" && tui) ui.setFooter(undefined)
|
|
219
|
+
host = undefined
|
|
220
|
+
mountEpoch++
|
|
46
221
|
shownMode = mode
|
|
47
222
|
shownLine = undefined
|
|
223
|
+
if (mode === "right" && tui) mountRight(ui)
|
|
224
|
+
if (mode === "footer" && tui) mountFooter(ui, mountEpoch)
|
|
48
225
|
}
|
|
49
226
|
if (mode === "off") return
|
|
50
|
-
const
|
|
227
|
+
const now = Date.now()
|
|
228
|
+
const line = decorate(ui, renderLine(readMeter(state, now), config.tiers, tui), now)
|
|
51
229
|
if (line === shownLine) return
|
|
52
230
|
shownLine = line
|
|
53
231
|
if (mode === "status") ui.setStatus(KEY, line)
|
|
54
|
-
else ui.setWidget(KEY, [line])
|
|
232
|
+
else if (mode === "widget") ui.setWidget(KEY, [line])
|
|
233
|
+
// RPC has no custom footers or component widgets; there the line goes out as plain text
|
|
234
|
+
// below the editor.
|
|
235
|
+
else if (tui) host?.requestRender()
|
|
236
|
+
else ui.setWidget(KEY, [line], { placement: "belowEditor" })
|
|
55
237
|
}
|
|
56
238
|
|
|
57
239
|
const stopTicker = (): void => {
|
|
@@ -126,14 +308,18 @@ export default function tpsMeter(pi: ExtensionAPI): void {
|
|
|
126
308
|
})
|
|
127
309
|
|
|
128
310
|
pi.on("session_shutdown", () => {
|
|
129
|
-
// pi resets extension UI itself when it reloads or replaces the runtime
|
|
130
|
-
//
|
|
311
|
+
// pi resets extension UI itself when it reloads or replaces the runtime (including a custom
|
|
312
|
+
// footer); the timer and the references to this session are the only things left to drop.
|
|
131
313
|
stopTicker()
|
|
314
|
+
mountEpoch++
|
|
132
315
|
ui = undefined
|
|
316
|
+
ctxRef = undefined
|
|
317
|
+
host = undefined
|
|
318
|
+
spinner = undefined
|
|
133
319
|
})
|
|
134
320
|
|
|
135
321
|
pi.registerCommand("tps", {
|
|
136
|
-
description: "TPS meter display: /tps cycles status → widget → off, /tps status|widget|off sets it",
|
|
322
|
+
description: "TPS meter display: /tps cycles footer → right → status → widget → off, /tps footer|right|status|widget|off sets it",
|
|
137
323
|
getArgumentCompletions: (prefix) => {
|
|
138
324
|
// Only strict prefixes: pi's editor makes Enter apply an open argument completion instead
|
|
139
325
|
// of submitting, so a fully typed mode must close the popup or `/tps off` needs two Enters.
|
|
@@ -145,7 +331,7 @@ export default function tpsMeter(pi: ExtensionAPI): void {
|
|
|
145
331
|
bind(ctx)
|
|
146
332
|
const arg = args.trim().toLowerCase()
|
|
147
333
|
if (arg && !isDisplayMode(arg)) {
|
|
148
|
-
ctx.ui.notify(`tps-meter: unknown mode "${arg}" (use status | widget | off)`, "error")
|
|
334
|
+
ctx.ui.notify(`tps-meter: unknown mode "${arg}" (use footer | right | status | widget | off)`, "error")
|
|
149
335
|
return
|
|
150
336
|
}
|
|
151
337
|
const mode = isDisplayMode(arg) ? arg : nextMode(config.mode)
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package.json",
|
|
3
3
|
"name": "@jack-yang/pi-tps-meter",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.3.0",
|
|
5
5
|
"description": "Live TPS / AVG / TTFT meter for the pi coding agent, calibrated against authoritative token counts (port of opencode-tps-meter)",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"keywords": [
|
|
@@ -36,7 +36,7 @@
|
|
|
36
36
|
"extensions": [
|
|
37
37
|
"./extensions/index.ts"
|
|
38
38
|
],
|
|
39
|
-
"image": "https://raw.githubusercontent.com/yangwudong/pi-tps-meter/main/docs/screenshot-
|
|
39
|
+
"image": "https://raw.githubusercontent.com/yangwudong/pi-tps-meter/main/docs/screenshot-footer.png"
|
|
40
40
|
},
|
|
41
41
|
"engines": {
|
|
42
42
|
"node": ">=22.19.0"
|
package/src/config.ts
CHANGED
|
@@ -1,22 +1,27 @@
|
|
|
1
|
-
// Display mode persistence and
|
|
1
|
+
// Display mode persistence, tier and spinner overrides — the only module that touches the filesystem.
|
|
2
2
|
//
|
|
3
3
|
// File: <agent dir>/pi-tps-meter/config.json, where <agent dir> is $PI_CODING_AGENT_DIR or
|
|
4
4
|
// ~/.pi/agent, resolved the same way pi resolves its own config directory.
|
|
5
5
|
//
|
|
6
|
-
// { "mode": "
|
|
7
|
-
//
|
|
6
|
+
// { "mode": "right",
|
|
7
|
+
// "tiers": { "tps": { "slow": 20, "normal": 50, "fast": 100 }, "ttft": { "fast": 10000, "ok": 20000 } },
|
|
8
|
+
// "spinner": { "theme": "tech", "colors": ["#00e5ff", "#2979ff"], "intervalMs": 100, "cells": 6, "enabled": true } }
|
|
8
9
|
|
|
9
10
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
|
|
10
11
|
import { homedir } from "node:os"
|
|
11
12
|
import { dirname, join } from "node:path"
|
|
12
13
|
import type { Tiers } from "./format.ts"
|
|
14
|
+
import { parseHex, THEME_PRESETS, type Rgb, type SpinnerConfig } from "./spinner.ts"
|
|
13
15
|
|
|
14
|
-
|
|
16
|
+
// footer: the right end of pi's own footer line with the working directory (pi's footer is wrapped,
|
|
17
|
+
// not replaced); right: one line below the editor, right-aligned; status: pi's footer status line;
|
|
18
|
+
// widget: a line above the editor.
|
|
19
|
+
export type DisplayMode = "footer" | "right" | "status" | "widget" | "off"
|
|
15
20
|
|
|
16
21
|
// Also the cycle order of a bare `/tps`.
|
|
17
|
-
export const DISPLAY_MODES: readonly DisplayMode[] = ["status", "widget", "off"]
|
|
22
|
+
export const DISPLAY_MODES: readonly DisplayMode[] = ["footer", "right", "status", "widget", "off"]
|
|
18
23
|
|
|
19
|
-
export type MeterConfig = { mode: DisplayMode; tiers: Tiers }
|
|
24
|
+
export type MeterConfig = { mode: DisplayMode; tiers: Tiers; spinner: SpinnerConfig }
|
|
20
25
|
|
|
21
26
|
export type LoadedConfig = { config: MeterConfig; warning?: string }
|
|
22
27
|
|
|
@@ -33,17 +38,29 @@ export function nextMode(mode: DisplayMode): DisplayMode {
|
|
|
33
38
|
// The original's resolveConfig override shape: `tiers.tps` / `tiers.ttft`, field by field over
|
|
34
39
|
// the defaults. Values that are not finite numbers fall back to the default instead of reaching
|
|
35
40
|
// the tier comparisons, where a string or null would silently mis-tier every reading.
|
|
41
|
+
// `spinner` follows the original too: custom `colors` win over the `theme` preset, theme "none"
|
|
42
|
+
// or `enabled: false` turns the stream off, `cells` is at least 2.
|
|
36
43
|
export function resolveConfig(raw: unknown): MeterConfig {
|
|
37
44
|
const o = isObject(raw) ? raw : {}
|
|
38
45
|
const tiers = isObject(o.tiers) ? o.tiers : {}
|
|
39
46
|
const tp = isObject(tiers.tps) ? tiers.tps : {}
|
|
40
47
|
const tt = isObject(tiers.ttft) ? tiers.ttft : {}
|
|
48
|
+
const sp = isObject(o.spinner) ? o.spinner : {}
|
|
49
|
+
const theme = typeof sp.theme === "string" ? sp.theme : "tech"
|
|
50
|
+
const custom = hexColors(sp.colors)
|
|
51
|
+
const preset = hexColors(THEME_PRESETS[theme] ?? THEME_PRESETS.tech)
|
|
41
52
|
return {
|
|
42
|
-
mode: isDisplayMode(o.mode) ? o.mode : "
|
|
53
|
+
mode: isDisplayMode(o.mode) ? o.mode : "footer",
|
|
43
54
|
tiers: {
|
|
44
55
|
tps: { slow: num(tp.slow, 20), normal: num(tp.normal, 50), fast: num(tp.fast, 100) },
|
|
45
56
|
ttft: { fast: num(tt.fast, 10_000), ok: num(tt.ok, 20_000) },
|
|
46
57
|
},
|
|
58
|
+
spinner: {
|
|
59
|
+
enabled: sp.enabled !== false && theme !== "none",
|
|
60
|
+
colors: custom.length > 0 ? custom : preset,
|
|
61
|
+
intervalMs: positive(sp.intervalMs) ?? 100,
|
|
62
|
+
cells: (positive(sp.cells) ?? 0) >= 2 ? Math.floor(sp.cells as number) : 6,
|
|
63
|
+
},
|
|
47
64
|
}
|
|
48
65
|
}
|
|
49
66
|
|
|
@@ -105,3 +122,16 @@ function isObject(value: unknown): value is Record<string, unknown> {
|
|
|
105
122
|
function num(value: unknown, fallback: number): number {
|
|
106
123
|
return typeof value === "number" && Number.isFinite(value) ? value : fallback
|
|
107
124
|
}
|
|
125
|
+
|
|
126
|
+
function positive(value: unknown): number | undefined {
|
|
127
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// The valid "#rrggbb" / "#rgb" entries of a config value, in order; anything else is dropped.
|
|
131
|
+
function hexColors(value: unknown): Rgb[] {
|
|
132
|
+
if (!Array.isArray(value)) return []
|
|
133
|
+
return value.flatMap((c) => {
|
|
134
|
+
const rgb = typeof c === "string" ? parseHex(c) : undefined
|
|
135
|
+
return rgb ? [rgb] : []
|
|
136
|
+
})
|
|
137
|
+
}
|
package/src/core.ts
CHANGED
|
@@ -36,6 +36,7 @@ export type MeterState = {
|
|
|
36
36
|
lastDeltaAt: number | undefined // lastDeltaByMessage
|
|
37
37
|
estimatedTokens: number // estimatedTokensByMessage
|
|
38
38
|
ttftMs: number | undefined // liveTtftBySession
|
|
39
|
+
thinking: boolean // thinkingBySession: the latest delta was reasoning (drives the particle stream)
|
|
39
40
|
}
|
|
40
41
|
|
|
41
42
|
export type MeterReading = {
|
|
@@ -93,6 +94,7 @@ export function createMeterState(): MeterState {
|
|
|
93
94
|
lastDeltaAt: undefined,
|
|
94
95
|
estimatedTokens: 0,
|
|
95
96
|
ttftMs: undefined,
|
|
97
|
+
thinking: false,
|
|
96
98
|
}
|
|
97
99
|
}
|
|
98
100
|
|
|
@@ -118,6 +120,7 @@ export function startMessage(state: MeterState, at: number): void {
|
|
|
118
120
|
state.lastDeltaAt = undefined
|
|
119
121
|
state.estimatedTokens = 0
|
|
120
122
|
state.samples = []
|
|
123
|
+
state.thinking = false
|
|
121
124
|
}
|
|
122
125
|
|
|
123
126
|
// One streamed chunk (the original's recordDelta). Every kind feeds the window, the span and the
|
|
@@ -133,6 +136,9 @@ export function recordDelta(state: MeterState, at: number, delta: string, kind:
|
|
|
133
136
|
if (state.firstDeltaAt === undefined) state.firstDeltaAt = at
|
|
134
137
|
state.lastDeltaAt = at
|
|
135
138
|
state.estimatedTokens += rawTokens
|
|
139
|
+
// As the original's setThinking: reasoning turns it on; text and the tool-call stream (the
|
|
140
|
+
// original cleared it on tool input start) turn it off.
|
|
141
|
+
state.thinking = kind === "thinking"
|
|
136
142
|
if (kind === "toolcall" || state.ttftMs !== undefined || state.ttftOrigin === undefined) return false
|
|
137
143
|
state.ttftMs = Math.max(0, at - state.ttftOrigin)
|
|
138
144
|
return true
|
|
@@ -178,6 +184,7 @@ function endMessage(state: MeterState): void {
|
|
|
178
184
|
state.lastDeltaAt = undefined
|
|
179
185
|
state.estimatedTokens = 0
|
|
180
186
|
state.samples = []
|
|
187
|
+
state.thinking = false
|
|
181
188
|
}
|
|
182
189
|
|
|
183
190
|
// What the meter shows at `now` (the original's MeterDisplay sync).
|
package/src/footer.ts
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// Puts the meter on the right end of the first line of pi's own footer (the working directory
|
|
2
|
+
// line), the way pi itself right-aligns the model name on the line below. Pure: the terminal
|
|
3
|
+
// width functions are injected (pi-tui's in pi, simple ones in tests), so this runs on plain Node.
|
|
4
|
+
|
|
5
|
+
export type WidthFns = {
|
|
6
|
+
// Terminal columns of a string: ANSI codes take none, CJK characters take two.
|
|
7
|
+
visibleWidth(text: string): number
|
|
8
|
+
// Cut a string to at most `width` columns; the caller decides the ellipsis (pi uses a dim "...").
|
|
9
|
+
truncate(text: string, width: number): string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
// Columns kept free between the directory and the meter.
|
|
13
|
+
export const FOOTER_GAP = 2
|
|
14
|
+
|
|
15
|
+
// The meter is the point of this line, so on a narrow terminal the directory gives way first
|
|
16
|
+
// (truncated with an ellipsis, as pi itself does); the meter is only dropped when even it alone
|
|
17
|
+
// would not fit. Returns exactly `width` columns, padded between the two parts.
|
|
18
|
+
export function mergeFooterLine(left: string, meter: string, width: number, fns: WidthFns): string {
|
|
19
|
+
const meterWidth = fns.visibleWidth(meter)
|
|
20
|
+
if (meter === "" || meterWidth > width) return left
|
|
21
|
+
const room = width - meterWidth - FOOTER_GAP
|
|
22
|
+
let head = left
|
|
23
|
+
if (room <= 0) head = ""
|
|
24
|
+
else if (fns.visibleWidth(left) > room) head = fns.truncate(left, room)
|
|
25
|
+
const pad = width - fns.visibleWidth(head) - meterWidth
|
|
26
|
+
return head + " ".repeat(Math.max(0, pad)) + meter
|
|
27
|
+
}
|
package/src/format.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
// Display formatting and tier colouring, ported from opencode-tps-meter/tui.tsx
|
|
1
|
+
// Display formatting and tier colouring, ported from opencode-tps-meter/tui.tsx, plus the layout
|
|
2
|
+
// of the thinking particle stream and right alignment.
|
|
2
3
|
// Pure: no pi imports. The caller decides whether the host renders ANSI.
|
|
3
4
|
|
|
4
5
|
import type { MeterReading } from "./core.ts"
|
|
6
|
+
import type { Rgb, SpinnerCell } from "./spinner.ts"
|
|
5
7
|
|
|
6
8
|
export type TpsTiers = { slow: number; normal: number; fast: number }
|
|
7
9
|
export type TtftTiers = { fast: number; ok: number }
|
|
@@ -102,3 +104,36 @@ export function renderLine(reading: MeterReading, tiers: Tiers, color: boolean):
|
|
|
102
104
|
]
|
|
103
105
|
return cells.map((c) => (color ? paint(c.text, c.hue) : c.text)).join("")
|
|
104
106
|
}
|
|
107
|
+
|
|
108
|
+
// Gaps in the stream are U+2800, the empty braille cell: one column, blank on screen, and not
|
|
109
|
+
// whitespace. pi's footer sanitizer collapses runs of spaces and trims both ends of a status (JS
|
|
110
|
+
// trim() also strips no-break spaces), either of which would make the stream jitter in width.
|
|
111
|
+
const GAP = "\u2800"
|
|
112
|
+
|
|
113
|
+
// The particle stream flows away from the meter. After the reading (status / widget) it runs
|
|
114
|
+
// left to right, newest cell next to TTFT, as in the original. Before a right-aligned reading it
|
|
115
|
+
// is mirrored, newest cell next to TPS, so the reading itself never moves.
|
|
116
|
+
export function withSpinner(
|
|
117
|
+
line: string,
|
|
118
|
+
cells: SpinnerCell[],
|
|
119
|
+
paintRgb: (text: string, color: Rgb) => string,
|
|
120
|
+
side: "before" | "after",
|
|
121
|
+
): string {
|
|
122
|
+
const ordered = side === "after" ? cells : [...cells].reverse()
|
|
123
|
+
const stream = ordered.map((c) => (c.glyph === " " ? GAP : paintRgb(c.glyph, c.color))).join("")
|
|
124
|
+
return side === "after" ? `${line} ${stream}` : `${stream} ${line}`
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Terminal columns of a string produced here: ANSI SGR codes take none, and every character used
|
|
128
|
+
// (ASCII, braille) takes exactly one.
|
|
129
|
+
export function visibleWidth(text: string): number {
|
|
130
|
+
return [...text.replace(/\x1b\[[0-9;]*m/g, "")].length
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Pads `line` so it ends in the last column. A line too wide for the terminal loses its colours and
|
|
134
|
+
// is cut, because a TUI line must never exceed the width it is given.
|
|
135
|
+
export function alignRight(line: string, width: number): string {
|
|
136
|
+
const w = visibleWidth(line)
|
|
137
|
+
if (w <= width) return " ".repeat(width - w) + line
|
|
138
|
+
return [...line.replace(/\x1b\[[0-9;]*m/g, "")].slice(w - width).join("")
|
|
139
|
+
}
|
package/src/spinner.ts
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// The "thinking" particle stream, ported from opencode-tps-meter/tui.tsx: while reasoning streams,
|
|
2
|
+
// a short FIFO of braille dots flows away from the meter, newest cell brightest, older cells fading
|
|
3
|
+
// into the muted colour, the bright colour drifting along a gradient over time.
|
|
4
|
+
//
|
|
5
|
+
// Pure: randomness and the clock are parameters. Colours are plain sRGB; the extension paints them
|
|
6
|
+
// through pi's theme, which converts to truecolor or 256 colours for the terminal.
|
|
7
|
+
|
|
8
|
+
export type Rgb = { r: number; g: number; b: number }
|
|
9
|
+
|
|
10
|
+
export type SpinnerConfig = { enabled: boolean; colors: Rgb[]; intervalMs: number; cells: number }
|
|
11
|
+
|
|
12
|
+
export type SpinnerState = { stream: string[]; hueFrame: number; lastFrameAt: number }
|
|
13
|
+
|
|
14
|
+
export type SpinnerCell = { glyph: string; color: Rgb }
|
|
15
|
+
|
|
16
|
+
export type Random = () => number
|
|
17
|
+
|
|
18
|
+
const DOT_GLYPHS = ["⠁", "⠂", "⠄", "⠈", "⠐", "⠠", "⠒", "⠑", "⠡", "⠢", "⠤", "⠨", "⠰", "⠸", "⠘", "⠔", "⠖", "⠦"]
|
|
19
|
+
|
|
20
|
+
// One full sweep of the gradient takes this many frames (6s at the default 100ms).
|
|
21
|
+
const HUE_FRAMES = 60
|
|
22
|
+
|
|
23
|
+
export const THEME_PRESETS: Record<string, string[]> = {
|
|
24
|
+
tech: ["#00e5ff", "#2979ff", "#651fff"],
|
|
25
|
+
red: ["#ff1744", "#ff5252", "#ff8a80"],
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// "#rrggbb" or "#rgb". The leading # is required: without it, words such as "bad" or "add" would
|
|
29
|
+
// read as three-digit colours.
|
|
30
|
+
export function parseHex(hex: string): Rgb | undefined {
|
|
31
|
+
const m = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(hex.trim())
|
|
32
|
+
if (!m) return undefined
|
|
33
|
+
const h = m[1].length === 3 ? [...m[1]].map((c) => c + c).join("") : m[1]
|
|
34
|
+
return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16) }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function lerp(a: number, b: number, t: number): number {
|
|
38
|
+
return a + (b - a) * t
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function lerpColor(a: Rgb, b: Rgb, t: number): Rgb {
|
|
42
|
+
return { r: Math.round(lerp(a.r, b.r, t)), g: Math.round(lerp(a.g, b.g, t)), b: Math.round(lerp(a.b, b.b, t)) }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Position t in [0, 1] along a multi-stop gradient.
|
|
46
|
+
export function gradientColor(colors: Rgb[], t: number): Rgb {
|
|
47
|
+
if (colors.length === 0) return { r: 136, g: 136, b: 136 }
|
|
48
|
+
if (colors.length === 1) return colors[0]
|
|
49
|
+
const c = Math.max(0, Math.min(1, t))
|
|
50
|
+
const seg = c * (colors.length - 1)
|
|
51
|
+
const i = Math.min(Math.floor(seg), colors.length - 2)
|
|
52
|
+
return lerpColor(colors[i], colors[i + 1], seg - i)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Roughly one cell in five is a gap, so the stream reads as particles rather than a solid bar.
|
|
56
|
+
function spawnGlyph(random: Random): string {
|
|
57
|
+
return random() < 0.18 ? " " : DOT_GLYPHS[Math.floor(random() * DOT_GLYPHS.length)]
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// A fresh stream each time thinking starts, so consecutive thinking spans do not look identical.
|
|
61
|
+
export function createSpinner(cells: number, now: number, random: Random): SpinnerState {
|
|
62
|
+
return { stream: Array.from({ length: cells }, () => spawnGlyph(random)), hueFrame: 0, lastFrameAt: now }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Frames follow wall time (one per `intervalMs`), not render calls, so the stream keeps its speed
|
|
66
|
+
// whatever the refresh rate. The frame count is capped so a long pause cannot loop for ages.
|
|
67
|
+
export function advanceSpinner(state: SpinnerState, cfg: SpinnerConfig, now: number, random: Random): void {
|
|
68
|
+
const due = Math.floor((now - state.lastFrameAt) / cfg.intervalMs)
|
|
69
|
+
if (due <= 0) return
|
|
70
|
+
for (let i = 0; i < Math.min(due, cfg.cells); i++) {
|
|
71
|
+
state.stream.unshift(spawnGlyph(random))
|
|
72
|
+
if (state.stream.length > cfg.cells) state.stream.length = cfg.cells
|
|
73
|
+
}
|
|
74
|
+
state.hueFrame += due
|
|
75
|
+
state.lastFrameAt += due * cfg.intervalMs
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Cell 0 is the newest and carries the current gradient colour; each older cell fades a step
|
|
79
|
+
// further toward `muted`. Gaps stay muted.
|
|
80
|
+
export function spinnerCells(state: SpinnerState, cfg: SpinnerConfig, muted: Rgb): SpinnerCell[] {
|
|
81
|
+
const bright = gradientColor(cfg.colors, (state.hueFrame % HUE_FRAMES) / HUE_FRAMES)
|
|
82
|
+
const last = Math.max(1, state.stream.length - 1)
|
|
83
|
+
return state.stream.map((glyph, i) => ({ glyph, color: glyph === " " ? muted : lerpColor(bright, muted, i / last) }))
|
|
84
|
+
}
|