pi-status-footer 1.0.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/LICENSE +21 -0
- package/README.md +132 -0
- package/package.json +40 -0
- package/stats-footer.ts +545 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 pi-status-footer contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABLITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILTY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# pi-status-footer
|
|
2
|
+
|
|
3
|
+
A compact, zero-config two-line status footer for [pi](https://github.com/earendil-works/pi-coding-agent) β shows everything you want at a glance, fits on any terminal width.
|
|
4
|
+
|
|
5
|
+
## What it looks like
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
π€ openai/gpt-4o π medium β5.2k β8.1k β‘42 t/s πΎ63% π¦38%/128k
|
|
9
|
+
π my-project βΈ ξ₯ main +3 -1 β± working 4:32 β± turn 1:18
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
**Line 1 β Model & stats:** provider/model, thinking level with themed color, input/output tokens, tokens per second (live while streaming), cache hit rate, context window usage with color-coded fullness (green < 60%, yellow < 80%, red β₯ 80%).
|
|
13
|
+
|
|
14
|
+
**Line 2 β Project & timers:** repo folder name, git branch, live working-tree diff from HEAD (+N added lines, -M deleted), agent run timer, current turn timer.
|
|
15
|
+
|
|
16
|
+
Everything auto-fits to your terminal width β lower-priority segments drop off when space is tight (model name is always shown, truncated if needed).
|
|
17
|
+
|
|
18
|
+
## Features
|
|
19
|
+
|
|
20
|
+
- **Zero config** β drop it in and it works
|
|
21
|
+
- **Live TPS** β shows tokens/second during generation, stays visible between turns
|
|
22
|
+
- **Git awareness** β asynchronous, debounced `git diff --shortstat HEAD` so typing never blocks; branch changes detected automatically via `footerData.onBranchChange`
|
|
23
|
+
- **Cache hit rate** β percentage of prompt tokens served from cache
|
|
24
|
+
- **Context gauge** β percentage and raw max; shifts from green β yellow β red as you approach the limit
|
|
25
|
+
- **Thinking level** β color-coded to match pi's thinking theme
|
|
26
|
+
- **Segments drop gracefully** β only the model name is mandatory; everything else fits to width
|
|
27
|
+
- **East Asian safe** β explicit ambiguous-width handling for CJK-friendly terminals
|
|
28
|
+
- **Safe at all times** β footer rendering never crashes the TUI, even on edge cases
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
# Option 1: git (recommended, no npm account needed)
|
|
34
|
+
pi install git:github.com/kslamph/pi-status-footer@v1.0.0
|
|
35
|
+
|
|
36
|
+
# Option 2: npm
|
|
37
|
+
pi install npm:pi-status-footer
|
|
38
|
+
|
|
39
|
+
# Option 3: local directory
|
|
40
|
+
pi install /path/to/pi-status-footer
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
After installation, the footer appears automatically on the next pi TUI session. No configuration or activation needed.
|
|
44
|
+
|
|
45
|
+
## Display reference
|
|
46
|
+
|
|
47
|
+
### Line 1 β Model & stats
|
|
48
|
+
|
|
49
|
+
| Segment | Example | Source |
|
|
50
|
+
|---|---|---|
|
|
51
|
+
| π€ model | `π€ openai/gpt-4o` | `ctx.model.provider / ctx.model.id` |
|
|
52
|
+
| π thinking | `π high` | `ctx.thinkingLevel`, themed via `theme.fg()` |
|
|
53
|
+
| βinput βoutput | `β5.2k β8.1k` | Session `usage.input / usage.output` (accumulated across all entries) |
|
|
54
|
+
| β‘tps | `β‘42 t/s` | Live during generation; last completed rate shown between turns |
|
|
55
|
+
| πΎcache | `πΎ63%` | `cacheRead / (input + cacheRead + cacheWrite)` |
|
|
56
|
+
| π¦context | `π¦38%/128k` | `ctx.getContextUsage()`, color-coded by percent |
|
|
57
|
+
|
|
58
|
+
### Line 2 β Project & timers
|
|
59
|
+
|
|
60
|
+
| Segment | Example | Source |
|
|
61
|
+
|---|---|---|
|
|
62
|
+
| π repo | `π my-project` | Git repo root basename (from `ctx.cwd` walk-up) |
|
|
63
|
+
| βΈ ξ₯ branch | `βΈ ξ₯ main` | `footerData.getGitBranch()`, auto-updates |
|
|
64
|
+
| +N -M diff | `+3 -1` | Async `git diff --shortstat HEAD` (1s debounced) |
|
|
65
|
+
| β± working | `β± working 4:32` | Elapsed time since `agent_start`, HH:MM:SS above 1h |
|
|
66
|
+
| β± turn | `β± turn 1:18` | Elapsed time since last `turn_start` |
|
|
67
|
+
|
|
68
|
+
## How it works
|
|
69
|
+
|
|
70
|
+
The extension hooks into six pi lifecycle events:
|
|
71
|
+
|
|
72
|
+
- **`session_start`** β registers the footer via `ctx.ui.setFooter()`, discovers repo root, starts branch-change listener
|
|
73
|
+
- **`agent_start` / `agent_settled`** β controls the agent-run timer and a 1-second interval that triggers git diff refresh
|
|
74
|
+
- **`turn_start` / `turn_end`** β drives the per-turn timer
|
|
75
|
+
- **`message_start` / `message_update` / `message_end`** β tracks the generation window for live TPS
|
|
76
|
+
- **`model_select`** β clears stale TPS on model switch
|
|
77
|
+
- **`session_shutdown`** β cleans up all state
|
|
78
|
+
|
|
79
|
+
Git diff is fetched asynchronously via `execFile` with a 1-second debounce and `--no-optional-locks` to avoid contention. The render function caches the last result, so the footer stays responsive regardless of repo size.
|
|
80
|
+
|
|
81
|
+
## Requirements
|
|
82
|
+
|
|
83
|
+
- pi coding agent (any recent version with `ctx.ui.setFooter` and `footerData` support)
|
|
84
|
+
- git available on `PATH` for git diff and branch features (optional β footer degrades gracefully without it)
|
|
85
|
+
|
|
86
|
+
## Development
|
|
87
|
+
|
|
88
|
+
The extension is a single TypeScript file (`stats-footer.ts`) that pi loads via [jiti](https://github.com/unjs/jiti). There is no build step.
|
|
89
|
+
|
|
90
|
+
TypeScript types are provided by the pi runtime packages:
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
# Install peer dependencies for type checking (optional)
|
|
94
|
+
npm install --save-dev @earendil-works/pi-ai @earendil-works/pi-coding-agent @earendil-works/pi-tui
|
|
95
|
+
npx tsc --noEmit stats-footer.ts
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Releasing to npm
|
|
99
|
+
|
|
100
|
+
A GitHub Action (`.github/workflows/release.yml`) auto-publishes to npm via trusted publishing (OIDC) on tag push.
|
|
101
|
+
|
|
102
|
+
1. Bump the version in `package.json` and commit on `main`.
|
|
103
|
+
2. Tag the commit β the tag must match the version, e.g. `v1.0.1`:
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
git tag v1.0.1
|
|
107
|
+
git push origin v1.0.1
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
3. The workflow verifies the tag/version match, dry-runs `npm pack`, then publishes with [npm provenance](https://docs.npmjs.com/generating-provenance-statements).
|
|
111
|
+
|
|
112
|
+
### One-time setup
|
|
113
|
+
|
|
114
|
+
Before the first tag push, bind the GitHub Actions workflow as a trusted publisher. You must be logged into npm:
|
|
115
|
+
|
|
116
|
+
```bash
|
|
117
|
+
npm adduser # if not already logged in (2FA required)
|
|
118
|
+
npm publish --access public # first publish β creates the package on npm
|
|
119
|
+
npm trust github pi-status-footer \
|
|
120
|
+
--repo kslamph/pi-status-footer \
|
|
121
|
+
--file release.yml -y
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
This claims the `pi-status-footer` package name, publishes v1.0.0, and authorises the `release.yml` workflow to publish via OIDC without any token. After this one-time setup, just push a `vX.Y.Z` tag and the action takes over.
|
|
125
|
+
|
|
126
|
+
### Pre-release versions
|
|
127
|
+
|
|
128
|
+
Tags like `v1.0.1-beta.1` publish to the `next` dist-tag instead of `latest`.
|
|
129
|
+
|
|
130
|
+
## License
|
|
131
|
+
|
|
132
|
+
MIT β see [LICENSE](./LICENSE).
|
package/package.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "pi-status-footer",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Compact two-line status footer for pi: model, thinking level, tokens, TPS, cache hit rate, context usage, live git diff, and working/turn timers.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"pi-package",
|
|
7
|
+
"pi",
|
|
8
|
+
"pi-extension",
|
|
9
|
+
"footer",
|
|
10
|
+
"statusline",
|
|
11
|
+
"status-bar",
|
|
12
|
+
"tui",
|
|
13
|
+
"git",
|
|
14
|
+
"tokens",
|
|
15
|
+
"context"
|
|
16
|
+
],
|
|
17
|
+
"license": "MIT",
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/kslamph/pi-status-footer.git"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"stats-footer.ts",
|
|
24
|
+
"README.md",
|
|
25
|
+
"LICENSE"
|
|
26
|
+
],
|
|
27
|
+
"peerDependencies": {
|
|
28
|
+
"@earendil-works/pi-ai": "*",
|
|
29
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
30
|
+
"@earendil-works/pi-tui": "*"
|
|
31
|
+
},
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public"
|
|
34
|
+
},
|
|
35
|
+
"pi": {
|
|
36
|
+
"extensions": [
|
|
37
|
+
"./stats-footer.ts"
|
|
38
|
+
]
|
|
39
|
+
}
|
|
40
|
+
}
|
package/stats-footer.ts
ADDED
|
@@ -0,0 +1,545 @@
|
|
|
1
|
+
/** Compact, responsive status footer for pi. */
|
|
2
|
+
|
|
3
|
+
import type { AssistantMessage, Usage } from "@earendil-works/pi-ai";
|
|
4
|
+
import type {
|
|
5
|
+
ExtensionAPI,
|
|
6
|
+
SessionEntry,
|
|
7
|
+
} from "@earendil-works/pi-coding-agent";
|
|
8
|
+
import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
9
|
+
import { execFile } from "node:child_process";
|
|
10
|
+
import { existsSync } from "node:fs";
|
|
11
|
+
import { basename, dirname, join } from "node:path";
|
|
12
|
+
|
|
13
|
+
type UsageTotals = Pick<
|
|
14
|
+
Usage,
|
|
15
|
+
"input" | "output" | "cacheRead" | "cacheWrite"
|
|
16
|
+
> & {
|
|
17
|
+
cost: number;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
type RenderTui = { requestRender(force?: boolean): void };
|
|
21
|
+
|
|
22
|
+
const THINKING_THEME_COLOR = {
|
|
23
|
+
off: "thinkingOff",
|
|
24
|
+
minimal: "thinkingMinimal",
|
|
25
|
+
low: "thinkingLow",
|
|
26
|
+
medium: "thinkingMedium",
|
|
27
|
+
high: "thinkingHigh",
|
|
28
|
+
xhigh: "thinkingXhigh",
|
|
29
|
+
max: "thinkingMax",
|
|
30
|
+
} as const;
|
|
31
|
+
|
|
32
|
+
export function formatTokens(count: number): string {
|
|
33
|
+
if (count < 1_000) return String(count);
|
|
34
|
+
if (count < 10_000) return `${(count / 1_000).toFixed(1)}k`;
|
|
35
|
+
if (count < 1_000_000) return `${Math.round(count / 1_000)}k`;
|
|
36
|
+
if (count < 10_000_000) return `${(count / 1_000_000).toFixed(1)}M`;
|
|
37
|
+
return `${Math.round(count / 1_000_000)}M`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function formatDuration(ms: number): string {
|
|
41
|
+
const totalSeconds = Math.max(0, Math.floor(ms / 1_000));
|
|
42
|
+
const hours = Math.floor(totalSeconds / 3_600);
|
|
43
|
+
const minutes = Math.floor((totalSeconds % 3_600) / 60);
|
|
44
|
+
const seconds = totalSeconds % 60;
|
|
45
|
+
const pad = (n: number): string => String(n).padStart(2, "0");
|
|
46
|
+
// Clock style: 1:02:03 = 1h 2m 3s; below one hour M:SS, e.g. 2:01.
|
|
47
|
+
if (hours > 0) return `${hours}:${pad(minutes)}:${pad(seconds)}`;
|
|
48
|
+
return `${minutes}:${pad(seconds)}`;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Output tokens per second for an assistant message generation window.
|
|
53
|
+
* Returns null when too little time has elapsed for a meaningful rate.
|
|
54
|
+
*/
|
|
55
|
+
export function computeTps(
|
|
56
|
+
outputTokens: number,
|
|
57
|
+
startMs: number,
|
|
58
|
+
nowMs = Date.now(),
|
|
59
|
+
): number | null {
|
|
60
|
+
const elapsedSec = (nowMs - startMs) / 1000;
|
|
61
|
+
if (elapsedSec < 0.25) return null;
|
|
62
|
+
return outputTokens / elapsedSec;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function emptyUsageTotals(): UsageTotals {
|
|
66
|
+
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function addUsage(totals: UsageTotals, usage: Usage | undefined): void {
|
|
70
|
+
if (!usage) return;
|
|
71
|
+
totals.input += usage.input;
|
|
72
|
+
totals.output += usage.output;
|
|
73
|
+
totals.cacheRead += usage.cacheRead;
|
|
74
|
+
totals.cacheWrite += usage.cacheWrite;
|
|
75
|
+
totals.cost += usage.cost.total;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function collectSessionStats(entries: readonly SessionEntry[]): {
|
|
79
|
+
usage: UsageTotals;
|
|
80
|
+
} {
|
|
81
|
+
const usage = emptyUsageTotals();
|
|
82
|
+
|
|
83
|
+
for (const entry of entries) {
|
|
84
|
+
if (entry.type === "message" && entry.message.role === "assistant") {
|
|
85
|
+
const message = entry.message as AssistantMessage;
|
|
86
|
+
addUsage(usage, message.usage);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (entry.type === "message" && entry.message.role === "toolResult") {
|
|
90
|
+
addUsage(usage, entry.message.usage);
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
if (entry.type === "branch_summary" || entry.type === "compaction") {
|
|
94
|
+
addUsage(usage, entry.usage);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return { usage };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function calculateCacheHitRate(usage: UsageTotals): number | null {
|
|
102
|
+
const promptTokens = usage.input + usage.cacheRead + usage.cacheWrite;
|
|
103
|
+
return promptTokens > 0 ? (usage.cacheRead / promptTokens) * 100 : null;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* East Asian Ambiguous code point ranges (inclusive [start, end] pairs),
|
|
108
|
+
* flat. Derived from the Unicode EastAsianWidth=A property (same data set
|
|
109
|
+
* used by get-east-asian-width). Many CJK terminals and fonts render these
|
|
110
|
+
* as double-width while wcwidth-style helpers count them as 1 column.
|
|
111
|
+
*/
|
|
112
|
+
const AMBIGUOUS_RANGES: readonly number[] = [
|
|
113
|
+
161, 161, 164, 164, 167, 168, 170, 170, 173, 174, 176, 180,
|
|
114
|
+
182, 186, 188, 191, 198, 198, 208, 208, 215, 216, 222, 225,
|
|
115
|
+
230, 230, 232, 234, 236, 237, 240, 240, 242, 243, 247, 250,
|
|
116
|
+
252, 252, 254, 254, 257, 257, 273, 273, 275, 275, 283, 283,
|
|
117
|
+
294, 295, 299, 299, 305, 307, 312, 312, 319, 322, 324, 324,
|
|
118
|
+
328, 331, 333, 333, 338, 339, 358, 359, 363, 363, 462, 462,
|
|
119
|
+
464, 464, 466, 466, 468, 468, 470, 470, 472, 472, 474, 474,
|
|
120
|
+
476, 476, 593, 593, 609, 609, 708, 708, 711, 711, 713, 715,
|
|
121
|
+
717, 717, 720, 720, 728, 731, 733, 733, 735, 735, 768, 879,
|
|
122
|
+
913, 929, 931, 937, 945, 961, 963, 969, 1025, 1025, 1040, 1103,
|
|
123
|
+
1105, 1105, 8208, 8208, 8211, 8214, 8216, 8217, 8220, 8221, 8224, 8226,
|
|
124
|
+
8228, 8231, 8240, 8240, 8242, 8243, 8245, 8245, 8251, 8251, 8254, 8254,
|
|
125
|
+
8308, 8308, 8319, 8319, 8321, 8324, 8364, 8364, 8451, 8451, 8453, 8453,
|
|
126
|
+
8457, 8457, 8467, 8467, 8470, 8470, 8481, 8482, 8486, 8486, 8491, 8491,
|
|
127
|
+
8531, 8532, 8539, 8542, 8544, 8555, 8560, 8569, 8585, 8585, 8592, 8601,
|
|
128
|
+
8632, 8633, 8658, 8658, 8660, 8660, 8679, 8679, 8704, 8704, 8706, 8707,
|
|
129
|
+
8711, 8712, 8715, 8715, 8719, 8719, 8721, 8721, 8725, 8725, 8730, 8730,
|
|
130
|
+
8733, 8736, 8739, 8739, 8741, 8741, 8743, 8748, 8750, 8750, 8756, 8759,
|
|
131
|
+
8764, 8765, 8776, 8776, 8780, 8780, 8786, 8786, 8800, 8801, 8804, 8807,
|
|
132
|
+
8810, 8811, 8814, 8815, 8834, 8835, 8838, 8839, 8853, 8853, 8857, 8857,
|
|
133
|
+
8869, 8869, 8895, 8895, 8978, 8978, 9312, 9449, 9451, 9547, 9552, 9587,
|
|
134
|
+
9600, 9615, 9618, 9621, 9632, 9633, 9635, 9641, 9650, 9651, 9654, 9655,
|
|
135
|
+
9660, 9661, 9664, 9665, 9670, 9672, 9675, 9675, 9678, 9681, 9698, 9701,
|
|
136
|
+
9711, 9711, 9733, 9734, 9737, 9737, 9742, 9743, 9756, 9756, 9758, 9758,
|
|
137
|
+
9792, 9792, 9794, 9794, 9824, 9825, 9827, 9829, 9831, 9834, 9836, 9837,
|
|
138
|
+
9839, 9839, 9886, 9887, 9919, 9919, 9926, 9933, 9935, 9939, 9941, 9953,
|
|
139
|
+
9955, 9955, 9960, 9961, 9963, 9969, 9972, 9972, 9974, 9977, 9979, 9980,
|
|
140
|
+
9982, 9983, 10045, 10045, 10102, 10111, 11094, 11097, 12872, 12879, 57344, 63743,
|
|
141
|
+
65024, 65039, 65533, 65533, 127232, 127242, 127248, 127277, 127280, 127337, 127344, 127373,
|
|
142
|
+
127375, 127376, 127387, 127404, 917760, 917999, 983040, 1048573, 1048576, 1114109,
|
|
143
|
+
];
|
|
144
|
+
|
|
145
|
+
function isAmbiguousCodePoint(cp: number): boolean {
|
|
146
|
+
let lo = 0;
|
|
147
|
+
let hi = AMBIGUOUS_RANGES.length / 2 - 1;
|
|
148
|
+
while (lo <= hi) {
|
|
149
|
+
const mid = (lo + hi) >> 1;
|
|
150
|
+
const start = AMBIGUOUS_RANGES[mid * 2]!;
|
|
151
|
+
const end = AMBIGUOUS_RANGES[mid * 2 + 1]!;
|
|
152
|
+
if (cp < start) hi = mid - 1;
|
|
153
|
+
else if (cp > end) lo = mid + 1;
|
|
154
|
+
else return true;
|
|
155
|
+
}
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Extra columns a CJK terminal may add for ambiguous-width characters. */
|
|
160
|
+
function ambiguousExtraWidth(str: string): number {
|
|
161
|
+
let extra = 0;
|
|
162
|
+
for (const ch of str) {
|
|
163
|
+
const cp = ch.codePointAt(0)!;
|
|
164
|
+
if (cp >= 161 && isAmbiguousCodePoint(cp)) extra += 1;
|
|
165
|
+
}
|
|
166
|
+
return extra;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Conservative terminal width: like visibleWidth(), but East Asian
|
|
171
|
+
* Ambiguous characters (β β β Β· β β¦ β β etc.) count as 2 columns.
|
|
172
|
+
* Terminals/fonts in CJK locales frequently render them double-width;
|
|
173
|
+
* counting them narrowly is what makes a "fitted" footer line wrap onto
|
|
174
|
+
* an extra row and scroll the pane (clobbering the tmux status bar).
|
|
175
|
+
*/
|
|
176
|
+
export function measureWidth(str: string): number {
|
|
177
|
+
return visibleWidth(str) + ambiguousExtraWidth(str);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* truncateToWidth(), but re-trims until the *conservative* width fits,
|
|
182
|
+
* so the result never wraps even on ambiguous-wide terminals.
|
|
183
|
+
*/
|
|
184
|
+
export function truncateSafe(
|
|
185
|
+
str: string,
|
|
186
|
+
maxWidth: number,
|
|
187
|
+
ellipsis = "...",
|
|
188
|
+
): string {
|
|
189
|
+
let out = truncateToWidth(str, maxWidth, ellipsis);
|
|
190
|
+
let budget = maxWidth;
|
|
191
|
+
while (measureWidth(out) > maxWidth && budget > 0) {
|
|
192
|
+
budget -= 1;
|
|
193
|
+
out = truncateToWidth(str, budget, ellipsis);
|
|
194
|
+
}
|
|
195
|
+
return out;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Extra column reserved at the right edge to absorb font quirks. */
|
|
199
|
+
const SAFETY_MARGIN = 1;
|
|
200
|
+
|
|
201
|
+
function joinSegments(segments: string[], separator: string): string {
|
|
202
|
+
return segments.filter(Boolean).join(separator);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function fitSegments(
|
|
206
|
+
segments: string[],
|
|
207
|
+
separator: string,
|
|
208
|
+
width: number,
|
|
209
|
+
): string {
|
|
210
|
+
if (width <= 0 || segments.length === 0) return "";
|
|
211
|
+
// The first segment (model + thinking level) has top priority. If it
|
|
212
|
+
// alone is wider than the terminal, show a truncated prefix of it
|
|
213
|
+
// instead of skipping it in favor of lower-priority segments.
|
|
214
|
+
if (measureWidth(segments[0]!) > width) {
|
|
215
|
+
return truncateSafe(segments[0]!, width, "...");
|
|
216
|
+
}
|
|
217
|
+
const fitted: string[] = [segments[0]!];
|
|
218
|
+
for (const segment of segments.slice(1)) {
|
|
219
|
+
const candidate = joinSegments([...fitted, segment], separator);
|
|
220
|
+
if (measureWidth(candidate) <= width) fitted.push(segment);
|
|
221
|
+
}
|
|
222
|
+
return truncateSafe(joinSegments(fitted, separator), width, "");
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Walk up from cwd to find the git repo root directory (or null). */
|
|
226
|
+
function findRepoRoot(startDir: string): string | null {
|
|
227
|
+
let dir = startDir;
|
|
228
|
+
while (true) {
|
|
229
|
+
if (existsSync(join(dir, ".git"))) return dir;
|
|
230
|
+
const parent = dirname(dir);
|
|
231
|
+
if (parent === dir) return null;
|
|
232
|
+
dir = parent;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Parse `git diff --shortstat` output into added/deleted line counts. */
|
|
237
|
+
function parseShortStat(output: string): { added: number; deleted: number } {
|
|
238
|
+
const ins = output.match(/(\d+) insertion/);
|
|
239
|
+
const del = output.match(/(\d+) deletion/);
|
|
240
|
+
return {
|
|
241
|
+
added: ins ? Number(ins[1]) : 0,
|
|
242
|
+
deleted: del ? Number(del[1]) : 0,
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
export default function statsFooter(pi: ExtensionAPI) {
|
|
247
|
+
let tuiRef: RenderTui | null = null;
|
|
248
|
+
let timer: ReturnType<typeof setInterval> | null = null;
|
|
249
|
+
let runStart: number | null = null;
|
|
250
|
+
let lastRunDuration = 0;
|
|
251
|
+
// Turn timer: elapsed time since the current turn began (frozen at turn_end).
|
|
252
|
+
let turnStart: number | null = null;
|
|
253
|
+
let lastTurnDuration = 0;
|
|
254
|
+
// Tokens-per-second tracking: generation window of the current assistant
|
|
255
|
+
// message (genStart β message_end) plus the last completed message's rate.
|
|
256
|
+
let genStart: number | null = null;
|
|
257
|
+
let liveOutput = 0;
|
|
258
|
+
let lastTps: number | null = null;
|
|
259
|
+
// Git status: repo folder name + working-tree diff stats (+N -M), fetched
|
|
260
|
+
// asynchronously (render is synchronous, so results are cached).
|
|
261
|
+
let sessionCwd: string | null = null;
|
|
262
|
+
// Working-folder label: git repo root's basename when cwd is inside a repo,
|
|
263
|
+
// otherwise the basename of cwd itself β so the folder always shows even
|
|
264
|
+
// when there is no git repo.
|
|
265
|
+
let folderName: string | null = null;
|
|
266
|
+
let repoName: string | null = null;
|
|
267
|
+
let gitAdded = 0;
|
|
268
|
+
let gitDeleted = 0;
|
|
269
|
+
let gitFetching = false;
|
|
270
|
+
let lastGitFetch = 0;
|
|
271
|
+
|
|
272
|
+
const rerender = () => tuiRef?.requestRender();
|
|
273
|
+
const stopTimer = () => {
|
|
274
|
+
if (timer !== null) clearInterval(timer);
|
|
275
|
+
timer = null;
|
|
276
|
+
};
|
|
277
|
+
// Ask git for `git diff --shortstat HEAD` (staged + unstaged vs HEAD) and
|
|
278
|
+
// cache the result for the synchronous render. Debounced to 1s so heavy
|
|
279
|
+
// repos aren't hammered; non-blocking execFile keeps the TUI responsive.
|
|
280
|
+
const fetchGitDiff = (cwd: string) => {
|
|
281
|
+
if (gitFetching) return;
|
|
282
|
+
const now = Date.now();
|
|
283
|
+
if (now - lastGitFetch < 1_000) return;
|
|
284
|
+
lastGitFetch = now;
|
|
285
|
+
gitFetching = true;
|
|
286
|
+
execFile(
|
|
287
|
+
"git",
|
|
288
|
+
["--no-optional-locks", "diff", "--shortstat", "HEAD"],
|
|
289
|
+
{ cwd, timeout: 3_000 },
|
|
290
|
+
(err, stdout) => {
|
|
291
|
+
gitFetching = false;
|
|
292
|
+
if (err) {
|
|
293
|
+
gitAdded = 0;
|
|
294
|
+
gitDeleted = 0;
|
|
295
|
+
} else {
|
|
296
|
+
({ added: gitAdded, deleted: gitDeleted } = parseShortStat(stdout));
|
|
297
|
+
}
|
|
298
|
+
rerender();
|
|
299
|
+
},
|
|
300
|
+
);
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
pi.on("session_start", (_event, ctx) => {
|
|
304
|
+
stopTimer();
|
|
305
|
+
runStart = null;
|
|
306
|
+
lastRunDuration = 0;
|
|
307
|
+
turnStart = null;
|
|
308
|
+
lastTurnDuration = 0;
|
|
309
|
+
genStart = null;
|
|
310
|
+
liveOutput = 0;
|
|
311
|
+
lastTps = null;
|
|
312
|
+
sessionCwd = ctx.cwd;
|
|
313
|
+
folderName = basename(ctx.cwd);
|
|
314
|
+
const repoRoot = findRepoRoot(ctx.cwd);
|
|
315
|
+
repoName = repoRoot === null ? null : basename(repoRoot);
|
|
316
|
+
gitAdded = 0;
|
|
317
|
+
gitDeleted = 0;
|
|
318
|
+
if (ctx.mode !== "tui") return;
|
|
319
|
+
|
|
320
|
+
ctx.ui.setFooter((tui, theme, footerData) => {
|
|
321
|
+
tuiRef = tui;
|
|
322
|
+
fetchGitDiff(ctx.cwd);
|
|
323
|
+
const unsubscribeBranch = footerData.onBranchChange(() => {
|
|
324
|
+
fetchGitDiff(ctx.cwd);
|
|
325
|
+
rerender();
|
|
326
|
+
});
|
|
327
|
+
|
|
328
|
+
return {
|
|
329
|
+
dispose() {
|
|
330
|
+
unsubscribeBranch();
|
|
331
|
+
stopTimer();
|
|
332
|
+
tuiRef = null;
|
|
333
|
+
},
|
|
334
|
+
invalidate() {},
|
|
335
|
+
render(width: number): string[] {
|
|
336
|
+
if (width <= 0) return [];
|
|
337
|
+
try {
|
|
338
|
+
const entries = ctx.sessionManager.getEntries() as SessionEntry[];
|
|
339
|
+
const { usage } = collectSessionStats(entries);
|
|
340
|
+
const cacheRate = calculateCacheHitRate(usage);
|
|
341
|
+
const context = ctx.getContextUsage();
|
|
342
|
+
const contextWindow =
|
|
343
|
+
context?.contextWindow ?? ctx.model?.contextWindow ?? 0;
|
|
344
|
+
const contextPercent = context?.percent ?? null;
|
|
345
|
+
|
|
346
|
+
let contextColor: "dim" | "success" | "warning" | "error" = "dim";
|
|
347
|
+
if (contextPercent !== null) {
|
|
348
|
+
if (contextPercent >= 80) contextColor = "error";
|
|
349
|
+
else if (contextPercent >= 60) contextColor = "warning";
|
|
350
|
+
else contextColor = "success";
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const modelId = ctx.model
|
|
354
|
+
? `${ctx.model.provider}/${ctx.model.id}`
|
|
355
|
+
: "no-model";
|
|
356
|
+
const thinkingLevel = ctx.thinkingLevel || "off";
|
|
357
|
+
const contextText =
|
|
358
|
+
contextPercent === null
|
|
359
|
+
? `?/${formatTokens(contextWindow)}`
|
|
360
|
+
: `${contextPercent.toFixed(0)}%/${formatTokens(contextWindow)}`;
|
|
361
|
+
const separator = " "; // two spaces β clean icon-bar look
|
|
362
|
+
const elapsed =
|
|
363
|
+
runStart === null ? lastRunDuration : Date.now() - runStart;
|
|
364
|
+
const turnElapsed =
|
|
365
|
+
turnStart === null ? lastTurnDuration : Date.now() - turnStart;
|
|
366
|
+
const thinkingColor =
|
|
367
|
+
THINKING_THEME_COLOR[
|
|
368
|
+
thinkingLevel as keyof typeof THINKING_THEME_COLOR
|
|
369
|
+
] ?? "thinkingMedium";
|
|
370
|
+
let thinkingText: string;
|
|
371
|
+
try {
|
|
372
|
+
thinkingText = `π ${theme.fg(thinkingColor, thinkingLevel)}`;
|
|
373
|
+
} catch {
|
|
374
|
+
// thinkingMax is optional in themes; fall back to a vivid level.
|
|
375
|
+
thinkingText = `π ${theme.fg("thinkingHigh", thinkingLevel)}`;
|
|
376
|
+
}
|
|
377
|
+
// TPS: live rate while the current assistant message streams,
|
|
378
|
+
// falling back to the last completed message's rate so the value
|
|
379
|
+
// keeps a fixed position instead of flashing only at message_end.
|
|
380
|
+
let tpsSuffix = "";
|
|
381
|
+
const liveTps =
|
|
382
|
+
genStart !== null && liveOutput > 0
|
|
383
|
+
? computeTps(liveOutput, genStart, Date.now())
|
|
384
|
+
: null;
|
|
385
|
+
const tpsValue = liveTps ?? lastTps;
|
|
386
|
+
tpsSuffix = ` β‘${Math.round(tpsValue ?? 0)} t/s`;
|
|
387
|
+
// Line 1 β model + tokens/stats, each segment icon-prefixed.
|
|
388
|
+
const statsLine = fitSegments(
|
|
389
|
+
[
|
|
390
|
+
`π€ ${theme.fg("accent", modelId)} ${thinkingText}`,
|
|
391
|
+
theme.fg(
|
|
392
|
+
"dim",
|
|
393
|
+
`β${formatTokens(usage.input)} β${formatTokens(usage.output)}${tpsSuffix}`,
|
|
394
|
+
),
|
|
395
|
+
theme.fg(
|
|
396
|
+
"dim",
|
|
397
|
+
`πΎ ${cacheRate === null ? "-" : `${cacheRate.toFixed(0)}%`}`,
|
|
398
|
+
),
|
|
399
|
+
`π¦ ${theme.fg(contextColor, contextText)}`,
|
|
400
|
+
],
|
|
401
|
+
separator,
|
|
402
|
+
Math.max(0, width - SAFETY_MARGIN),
|
|
403
|
+
);
|
|
404
|
+
// Line 2 β folder/git status + working/turn timers. The folder
|
|
405
|
+
// name always shows (repo root basename, or plain cwd basename
|
|
406
|
+
// when not inside a git repo); branch + diff only when git is
|
|
407
|
+
// present.
|
|
408
|
+
const branch = footerData.getGitBranch();
|
|
409
|
+
const gitSegments: string[] = [];
|
|
410
|
+
if (folderName !== null) {
|
|
411
|
+
const folderLabel = repoName ?? folderName;
|
|
412
|
+
const folderText = `π ${theme.fg("accent", folderLabel)}`;
|
|
413
|
+
if (repoName !== null) {
|
|
414
|
+
const branchText = branch
|
|
415
|
+
? ` βΈ ξ₯ ${branch}`
|
|
416
|
+
: "";
|
|
417
|
+
gitSegments.push(
|
|
418
|
+
folderText + branchText +
|
|
419
|
+
` ${theme.fg("toolDiffAdded", `+${gitAdded}`)} ${theme.fg("toolDiffRemoved", `-${gitDeleted}`)}`,
|
|
420
|
+
);
|
|
421
|
+
} else {
|
|
422
|
+
gitSegments.push(folderText);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
gitSegments.push(
|
|
426
|
+
`β± ${theme.fg("accent", `working ${formatDuration(elapsed)}`)}`,
|
|
427
|
+
`β± ${theme.fg("accent", `turn ${formatDuration(turnElapsed)}`)}`,
|
|
428
|
+
);
|
|
429
|
+
const gitLine = fitSegments(
|
|
430
|
+
gitSegments,
|
|
431
|
+
separator,
|
|
432
|
+
Math.max(0, width - SAFETY_MARGIN),
|
|
433
|
+
);
|
|
434
|
+
|
|
435
|
+
return [
|
|
436
|
+
truncateSafe(statsLine, width, ""),
|
|
437
|
+
truncateSafe(gitLine, width, ""),
|
|
438
|
+
];
|
|
439
|
+
} catch {
|
|
440
|
+
// Footer rendering must never crash the TUI, even on very
|
|
441
|
+
// narrow terminals or unexpected context shapes.
|
|
442
|
+
return [];
|
|
443
|
+
}
|
|
444
|
+
},
|
|
445
|
+
};
|
|
446
|
+
});
|
|
447
|
+
});
|
|
448
|
+
|
|
449
|
+
pi.on("agent_start", () => {
|
|
450
|
+
if (runStart === null) runStart = Date.now();
|
|
451
|
+
lastRunDuration = 0;
|
|
452
|
+
stopTimer();
|
|
453
|
+
timer = setInterval(() => {
|
|
454
|
+
if (sessionCwd !== null) fetchGitDiff(sessionCwd);
|
|
455
|
+
rerender();
|
|
456
|
+
}, 1_000);
|
|
457
|
+
rerender();
|
|
458
|
+
});
|
|
459
|
+
pi.on("agent_settled", () => {
|
|
460
|
+
if (runStart !== null) lastRunDuration = Date.now() - runStart;
|
|
461
|
+
runStart = null;
|
|
462
|
+
genStart = null;
|
|
463
|
+
liveOutput = 0;
|
|
464
|
+
stopTimer();
|
|
465
|
+
rerender();
|
|
466
|
+
});
|
|
467
|
+
// --- Turn timer ---
|
|
468
|
+
// A turn is one userβassistant cycle inside the agent loop. "working" spans
|
|
469
|
+
// the whole agent run; "turn" shows only the current turn's elapsed time.
|
|
470
|
+
pi.on("turn_start", () => {
|
|
471
|
+
turnStart = Date.now();
|
|
472
|
+
lastTurnDuration = 0;
|
|
473
|
+
});
|
|
474
|
+
pi.on("turn_end", () => {
|
|
475
|
+
if (turnStart !== null) lastTurnDuration = Date.now() - turnStart;
|
|
476
|
+
turnStart = null;
|
|
477
|
+
rerender();
|
|
478
|
+
});
|
|
479
|
+
pi.on("session_shutdown", () => {
|
|
480
|
+
stopTimer();
|
|
481
|
+
tuiRef = null;
|
|
482
|
+
runStart = null;
|
|
483
|
+
lastRunDuration = 0;
|
|
484
|
+
turnStart = null;
|
|
485
|
+
lastTurnDuration = 0;
|
|
486
|
+
genStart = null;
|
|
487
|
+
liveOutput = 0;
|
|
488
|
+
lastTps = null;
|
|
489
|
+
sessionCwd = null;
|
|
490
|
+
folderName = null;
|
|
491
|
+
repoName = null;
|
|
492
|
+
gitAdded = 0;
|
|
493
|
+
gitDeleted = 0;
|
|
494
|
+
lastGitFetch = 0;
|
|
495
|
+
});
|
|
496
|
+
|
|
497
|
+
// --- Tokens-per-second tracking ---
|
|
498
|
+
// Each assistant message's generation window is measured from its
|
|
499
|
+
// message_start (streaming begins) to message_end (stream done).
|
|
500
|
+
// message_update carries progressively updated usage.output, giving a
|
|
501
|
+
// live rate while streaming; message_end carries the final usage, whose
|
|
502
|
+
// rate is kept as lastTps for display while idle.
|
|
503
|
+
pi.on("message_start", (event) => {
|
|
504
|
+
if (event.message.role !== "assistant") return;
|
|
505
|
+
genStart = Date.now();
|
|
506
|
+
liveOutput = (event.message as AssistantMessage).usage?.output ?? 0;
|
|
507
|
+
});
|
|
508
|
+
pi.on("message_update", (event) => {
|
|
509
|
+
if (event.message.role !== "assistant") return;
|
|
510
|
+
// The raw stream event's partial message carries the most current
|
|
511
|
+
// usage.output (Anthropic reports it progressively; OpenAI only at the
|
|
512
|
+
// end), so prefer it over the session message's usage field.
|
|
513
|
+
const assistantEvent = event.assistantMessageEvent;
|
|
514
|
+
const partial =
|
|
515
|
+
assistantEvent && "partial" in assistantEvent
|
|
516
|
+
? (assistantEvent as { partial?: AssistantMessage }).partial
|
|
517
|
+
: undefined;
|
|
518
|
+
const output =
|
|
519
|
+
partial?.usage?.output ??
|
|
520
|
+
(event.message as AssistantMessage).usage?.output;
|
|
521
|
+
if (typeof output === "number" && output > liveOutput) liveOutput = output;
|
|
522
|
+
});
|
|
523
|
+
pi.on("message_end", (event) => {
|
|
524
|
+
if (event.message.role === "assistant") {
|
|
525
|
+
const output =
|
|
526
|
+
(event.message as AssistantMessage).usage?.output ?? liveOutput;
|
|
527
|
+
if (genStart !== null && output > 0) {
|
|
528
|
+
const tps = computeTps(output, genStart, Date.now());
|
|
529
|
+
lastTps = tps === null ? null : Math.round(tps);
|
|
530
|
+
}
|
|
531
|
+
genStart = null;
|
|
532
|
+
liveOutput = 0;
|
|
533
|
+
}
|
|
534
|
+
rerender();
|
|
535
|
+
});
|
|
536
|
+
pi.on("thinking_level_select", rerender);
|
|
537
|
+
pi.on("model_select", () => {
|
|
538
|
+
// A different model streams at a different rate; drop any stale number.
|
|
539
|
+
lastTps = null;
|
|
540
|
+
genStart = null;
|
|
541
|
+
liveOutput = 0;
|
|
542
|
+
rerender();
|
|
543
|
+
});
|
|
544
|
+
pi.on("session_info_changed", rerender);
|
|
545
|
+
}
|