@each1024/pi-mini-mode 2.0.18 → 2.0.19

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/lib/settings.ts CHANGED
@@ -27,6 +27,7 @@ export interface MiniLensSettings {
27
27
  "pi-mini-mode-input-enhancements": boolean;
28
28
  "pi-mini-mode-image-preview": "hover" | "inline";
29
29
  onboardingCompleted: boolean;
30
+ lastSeenVersion?: string;
30
31
  footerOrder?: string[];
31
32
  /** Language picked in the settings page; unset follows the system locale. */
32
33
  "pi-mini-mode-language"?: UiLanguage;
@@ -69,7 +70,7 @@ export const DEFAULT_SETTINGS: Readonly<MiniLensSettings> = {
69
70
  onboardingCompleted: false,
70
71
  };
71
72
 
72
- export const SETTING_IDS = Object.keys(DEFAULT_SETTINGS) as Array<Exclude<keyof MiniLensSettings, "footerOrder" | "pi-mini-mode-language">>;
73
+ export const SETTING_IDS = Object.keys(DEFAULT_SETTINGS) as Array<Exclude<keyof MiniLensSettings, "footerOrder" | "pi-mini-mode-language" | "lastSeenVersion">>;
73
74
  export const FOOTER_FIELDS = ["project-branch", "model", "thinking", "branch", "session-tokens", "cache-tokens", "cache-miss", "ch", "cost", "mcp", "context", "context-percent", "speed"] as const;
74
75
  export const FOOTER_STYLE_OPTIONS = ["context-dots", "speed-unit"] as const;
75
76
 
@@ -113,6 +114,9 @@ export function parseSettings(value: unknown): MiniLensSettings {
113
114
  for (const id of FOOTER_FIELDS) if (!settings.footerOrder.includes(id)) settings.footerOrder.push(id);
114
115
  }
115
116
  if (isUiLanguage(candidate["pi-mini-mode-language"])) settings["pi-mini-mode-language"] = candidate["pi-mini-mode-language"];
117
+ if (typeof candidate.lastSeenVersion === "string" && /^\d+\.\d+\.\d+$/.test(candidate.lastSeenVersion)) {
118
+ settings.lastSeenVersion = candidate.lastSeenVersion;
119
+ }
116
120
  if (settings["pi-mini-mode-branch-show"]) settings["pi-mini-mode-project-branch-show"] = false;
117
121
  return settings;
118
122
  }
@@ -157,7 +161,7 @@ export function isLegacyMinimalSetting(id: string): boolean {
157
161
 
158
162
  export function settingsItems(settings: MiniLensSettings): SettingItem[] {
159
163
  const values = ["on", "off"];
160
- const labels: Record<Exclude<keyof MiniLensSettings, "onboardingCompleted" | "footerOrder" | "pi-mini-mode-language" | "pi-mini-mode-image-preview" | "pi-mini-mode-minimal-record-limit">, string> = {
164
+ const labels: Record<Exclude<keyof MiniLensSettings, "onboardingCompleted" | "lastSeenVersion" | "footerOrder" | "pi-mini-mode-language" | "pi-mini-mode-image-preview" | "pi-mini-mode-minimal-record-limit">, string> = {
161
165
  "pi-mini-mode-project-branch-show": "显示项目名称和分支(互斥)",
162
166
  "pi-mini-mode-branch-show": "仅显示分支(思考等级后,互斥)",
163
167
  "pi-mini-mode-model-show": COPY.model, "pi-mini-mode-thinking-show": COPY.thinking, "pi-mini-mode-session-tokens-show": COPY.total, "pi-mini-mode-cache-tokens-show": COPY.cached, "pi-mini-mode-cache-miss-show": COPY.miss, "pi-mini-mode-ch-show": COPY.cacheHit, "pi-mini-mode-cost-show": COPY.price, "pi-mini-mode-mcp-show": COPY.mcp, "pi-mini-mode-context-show": COPY.context, "pi-mini-mode-context-dots-show": COPY.dots, "pi-mini-mode-context-percent-show": COPY.percent, "pi-mini-mode-speed-show": COPY.speed, "pi-mini-mode-speed-unit-show": COPY.speedUnit, "pi-mini-mode-minimal-show": COPY.minimal, "pi-mini-mode-input-enhancements": COPY.inputEnhancements,
@@ -3,7 +3,29 @@ import { finiteNumber, formatSpeed, formatUsd, outputSpeed, speedColor, DECODE_S
3
3
  /** Footer redraw cadence while a turn is streaming. */
4
4
  export const SPEED_REFRESH_MS = 500;
5
5
  /** Recent window used for the live rate. Long enough to absorb one quiet chunk, short enough to follow the current pace. */
6
- export const SPEED_WINDOW_MS = 1_000;
6
+ export const SPEED_WINDOW_MS = 2_500;
7
+
8
+ const CALIBRATION_ALPHA = 0.3;
9
+ const CALIBRATION_MIN = 0.5;
10
+ const CALIBRATION_MAX = 2;
11
+ const RELIABLE_MIN_ELAPSED_MS = 1_000;
12
+ const RELIABLE_MIN_OUTPUT = 16;
13
+ const SPIKE_MIN_TOKENS = 64;
14
+
15
+ export type ModelIdentifier = string | { provider?: unknown; model?: unknown };
16
+
17
+ function normalizeModelKey(model?: ModelIdentifier): string {
18
+ if (typeof model === "string") {
19
+ const trimmed = model.trim().replace(/^\/+|\/+$/g, "");
20
+ return trimmed || "__default__";
21
+ }
22
+ if (model && typeof model === "object") {
23
+ const provider = typeof model.provider === "string" ? model.provider.trim() : "";
24
+ const id = typeof model.model === "string" ? model.model.trim() : "";
25
+ return [provider, id].filter(Boolean).join("/") || "__default__";
26
+ }
27
+ return "__default__";
28
+ }
7
29
 
8
30
  export interface SpeedMetric {
9
31
  label: string;
@@ -90,32 +112,51 @@ export interface StreamUpdate {
90
112
  output?: number;
91
113
  content?: unknown;
92
114
  usage?: UsageLike;
115
+ type?: string;
116
+ delta?: string;
93
117
  }
94
118
 
95
119
  /**
96
- * Live footer speed is the token rate over the last second, republished every
97
- * 500ms. Provider `usage.output` wins when it advances; streamed text keeps the
98
- * rate moving when that sample is stale. The finished turn replaces it with
99
- * the average decode speed.
120
+ * Live footer speed is the token rate over the last 2.5 seconds, republished
121
+ * every 500ms. Provider `usage.output` wins once it advances monotonically at
122
+ * least twice; streamed text keeps the rate moving otherwise. The finished
123
+ * turn replaces it with the reliable weighted decode speed across the run.
100
124
  */
101
125
  export function createTokenSpeedTracker() {
102
126
  let displayed: number | undefined;
127
+ let lastReliable: number | undefined;
103
128
  let lastLive: number | undefined;
104
129
  let streaming = false;
105
130
  let lastPublish = 0;
106
131
  let lastStreamAt = Number.NEGATIVE_INFINITY;
132
+ let lastTokenUpdateAt = Number.NEGATIVE_INFINITY;
107
133
  let lastNow = 0;
108
134
  let turnStartedAt: number | undefined;
109
135
  let assistantStartedAt: number | undefined;
110
136
  let firstTokenAt: number | undefined;
137
+ let decodeStartedAt: number | undefined;
111
138
  let segmentEndedAt: number | undefined;
112
139
  let providerOutput = 0;
140
+ let providerAdvances = 0;
141
+ let firstProviderSample: Sample | undefined;
142
+ let rawStreamTokens = 0;
113
143
  let streamTokens = 0;
144
+ let hasSeenDelta = false;
145
+ let firstSampleTokens = 0;
146
+ let firstSampleRawTokens = 0;
147
+ let liveBaseAt: number | undefined;
148
+ let liveBaseTokens = 0;
114
149
  let samples: Sample[] = [];
115
150
  let usage: UsageSnapshot = {};
116
151
  let frozen: SpeedMetric[] | undefined;
152
+ let runTokens = 0;
153
+ let runElapsedMs = 0;
154
+ let currentModelKey = "__default__";
155
+ const calibrationRatios = new Map<string, number>();
117
156
 
118
- const liveCount = () => Math.max(providerOutput, streamTokens);
157
+ const calibrationRatio = () => calibrationRatios.get(currentModelKey) ?? 1;
158
+ const trustedProvider = () => (providerAdvances >= 2 ? providerOutput : 0);
159
+ const liveCount = () => Math.max(trustedProvider(), streamTokens);
119
160
 
120
161
  const pushSample = (at: number, tokens: number) => {
121
162
  const last = samples[samples.length - 1];
@@ -126,12 +167,12 @@ export function createTokenSpeedTracker() {
126
167
  };
127
168
 
128
169
  const liveRate = (now: number): number | undefined => {
129
- if (firstTokenAt === undefined || now - firstTokenAt < SPEED_REFRESH_MS) return undefined;
170
+ if (liveBaseAt === undefined || now - liveBaseAt < SPEED_REFRESH_MS) return undefined;
130
171
  const tokens = liveCount();
131
- const windowMs = Math.min(SPEED_WINDOW_MS, now - firstTokenAt);
172
+ const windowMs = Math.min(SPEED_WINDOW_MS, now - liveBaseAt);
132
173
  const cut = now - windowMs;
133
- let baseT = firstTokenAt;
134
- let baseTokens = 0;
174
+ let baseT = liveBaseAt;
175
+ let baseTokens = liveBaseTokens;
135
176
  for (const sample of samples) {
136
177
  if (sample.t <= cut) {
137
178
  baseT = sample.t;
@@ -157,12 +198,15 @@ export function createTokenSpeedTracker() {
157
198
  return changed;
158
199
  };
159
200
 
160
- const settledCount = () => usage.output !== undefined && usage.output >= DECODE_SPEED_MIN_OUTPUT ? usage.output : liveCount();
201
+ const settledCount = () => usage.output !== undefined && usage.output >= DECODE_SPEED_MIN_OUTPUT
202
+ ? usage.output
203
+ : Math.max(providerOutput, streamTokens);
161
204
 
162
205
  const runningAverage = (now: number): number | undefined => {
163
- const count = streaming ? liveCount() : settledCount();
164
- const end = streaming ? now : (segmentEndedAt ?? now);
165
- return outputSpeed(count, firstTokenAt, end);
206
+ if (streaming) return outputSpeed(liveCount(), firstTokenAt, now);
207
+ if (displayed !== undefined) return displayed;
208
+ const end = segmentEndedAt ?? now;
209
+ return outputSpeed(settledCount(), decodeStartedAt ?? firstTokenAt, end);
166
210
  };
167
211
 
168
212
  const collect = (): SpeedMetric[] => {
@@ -175,9 +219,10 @@ export function createTokenSpeedTracker() {
175
219
  if (firstTokenAt !== undefined && origin !== undefined && firstTokenAt > origin) {
176
220
  rows.push({ label: "首字吐字", value: formatDuration(firstTokenAt - origin), color: "text" });
177
221
  }
222
+ const decodeStart = streaming ? firstTokenAt : (decodeStartedAt ?? firstTokenAt);
178
223
  const decodeEnd = streaming ? now : segmentEndedAt;
179
- if (firstTokenAt !== undefined && decodeEnd !== undefined && decodeEnd - firstTokenAt >= SPEED_REFRESH_MS) {
180
- rows.push({ label: "解码用时", value: formatDuration(decodeEnd - firstTokenAt), color: "text" });
224
+ if (decodeStart !== undefined && decodeEnd !== undefined && decodeEnd - decodeStart >= SPEED_REFRESH_MS) {
225
+ rows.push({ label: "解码用时", value: formatDuration(decodeEnd - decodeStart), color: "text" });
181
226
  }
182
227
  const counts: Array<[keyof UsageSnapshot, string]> = [
183
228
  ["output", "输出 token"],
@@ -193,8 +238,8 @@ export function createTokenSpeedTracker() {
193
238
  if (value === undefined || value <= 0) continue;
194
239
  rows.push({ label, value: formatCount(value), color: "text" });
195
240
  }
196
- if (usage.output === undefined && !streaming && liveCount() >= DECODE_SPEED_MIN_OUTPUT) {
197
- rows.push({ label: "输出 token", value: formatCount(liveCount()), color: "text" });
241
+ if (usage.output === undefined && !streaming && settledCount() >= DECODE_SPEED_MIN_OUTPUT) {
242
+ rows.push({ label: "输出 token", value: formatCount(settledCount()), color: "text" });
198
243
  }
199
244
  if (usage.cost !== undefined && usage.cost > 0) rows.push({ label: "费用", value: formatUsd(usage.cost), color: "muted" });
200
245
  if (rows.length === 0 && displayed !== undefined) {
@@ -204,46 +249,138 @@ export function createTokenSpeedTracker() {
204
249
  };
205
250
 
206
251
  return {
252
+ onRunStart() {
253
+ runTokens = 0;
254
+ runElapsedMs = 0;
255
+ },
207
256
  onTurnStart(at: number) {
208
257
  lastNow = at;
209
258
  turnStartedAt = at;
210
259
  },
211
- onAssistantStart(at: number) {
260
+ onAssistantStart(at: number, model?: ModelIdentifier) {
212
261
  lastNow = at;
213
262
  streaming = true;
214
263
  lastPublish = at;
215
264
  lastStreamAt = Number.NEGATIVE_INFINITY;
265
+ lastTokenUpdateAt = Number.NEGATIVE_INFINITY;
216
266
  assistantStartedAt = at;
217
267
  firstTokenAt = undefined;
268
+ decodeStartedAt = undefined;
218
269
  segmentEndedAt = undefined;
219
270
  providerOutput = 0;
271
+ providerAdvances = 0;
272
+ firstProviderSample = undefined;
273
+ rawStreamTokens = 0;
220
274
  streamTokens = 0;
275
+ hasSeenDelta = false;
276
+ firstSampleTokens = 0;
277
+ firstSampleRawTokens = 0;
278
+ liveBaseAt = undefined;
279
+ liveBaseTokens = 0;
221
280
  samples = [];
222
281
  usage = {};
223
282
  lastLive = undefined;
283
+ currentModelKey = normalizeModelKey(model);
224
284
  },
225
285
  onStream(update: StreamUpdate): boolean {
226
286
  if (!streaming || update.at < lastStreamAt) return false;
227
- const nextProvider = update.output !== undefined && update.output >= providerOutput ? update.output : providerOutput;
228
- const nextStream = Math.max(streamTokens, estimateContentTokens(update.content));
229
- const nextTokens = Math.max(nextProvider, nextStream);
287
+ let prevCount = liveCount();
288
+
289
+ if (update.output !== undefined && update.output > providerOutput) {
290
+ providerAdvances += 1;
291
+ providerOutput = update.output;
292
+ if (providerAdvances === 1) {
293
+ firstProviderSample = { t: update.at, tokens: update.output };
294
+ } else if (providerAdvances === 2 && firstProviderSample) {
295
+ if (firstTokenAt === undefined || firstProviderSample.t < firstTokenAt) {
296
+ firstTokenAt = firstProviderSample.t;
297
+ decodeStartedAt = firstProviderSample.t;
298
+ firstSampleTokens = firstProviderSample.tokens;
299
+ firstSampleRawTokens = firstProviderSample.tokens;
300
+ liveBaseAt = firstProviderSample.t;
301
+ liveBaseTokens = firstProviderSample.tokens;
302
+ lastTokenUpdateAt = firstProviderSample.t;
303
+ pushSample(firstProviderSample.t, firstProviderSample.tokens);
304
+ } else if (liveBaseAt === firstProviderSample.t) {
305
+ liveBaseTokens = Math.max(liveBaseTokens, firstProviderSample.tokens);
306
+ firstSampleTokens = Math.max(firstSampleTokens, firstProviderSample.tokens);
307
+ pushSample(firstProviderSample.t, liveBaseTokens);
308
+ }
309
+ prevCount = Math.max(prevCount, firstProviderSample.tokens);
310
+ firstProviderSample = undefined;
311
+ }
312
+ }
313
+
314
+ const isDeltaType = update.type === undefined
315
+ || update.type === "text_delta"
316
+ || update.type === "thinking_delta"
317
+ || update.type === "toolcall_delta";
318
+ const isBoundaryType = update.type !== undefined
319
+ && (/(?:^|_)(?:start|end)$/.test(update.type) || update.type === "done" || update.type === "error");
320
+
321
+ let nextRawStream = rawStreamTokens;
322
+ if (typeof update.delta === "string" && isDeltaType) {
323
+ hasSeenDelta = true;
324
+ nextRawStream += estimateTextTokens(update.delta);
325
+ } else if (!hasSeenDelta && !isBoundaryType && update.content !== undefined) {
326
+ nextRawStream = Math.max(rawStreamTokens, estimateContentTokens(update.content));
327
+ }
328
+ const nextStream = nextRawStream * calibrationRatio();
329
+ const nextTokens = Math.max(trustedProvider(), nextStream);
330
+
230
331
  // Regressing or repeated samples must not move the clock. The 500ms timer
231
332
  // still decays the live rate when tokens actually stop arriving.
232
- if (nextTokens <= liveCount() && liveCount() > 0) return false;
333
+ if (nextTokens <= prevCount && prevCount > 0) return false;
334
+
233
335
  lastStreamAt = update.at;
234
336
  lastNow = update.at;
235
- providerOutput = nextProvider;
337
+ rawStreamTokens = nextRawStream;
236
338
  streamTokens = nextStream;
237
339
  readUsage(update.usage, usage);
340
+
238
341
  if (nextTokens > 0) {
239
- if (firstTokenAt === undefined) firstTokenAt = update.at;
240
- pushSample(update.at, nextTokens);
342
+ if (firstTokenAt === undefined) {
343
+ firstTokenAt = update.at;
344
+ decodeStartedAt = update.at;
345
+ firstSampleTokens = nextTokens;
346
+ firstSampleRawTokens = nextRawStream;
347
+ liveBaseAt = update.at;
348
+ liveBaseTokens = nextTokens;
349
+ pushSample(update.at, nextTokens);
350
+ } else if (update.at === firstTokenAt && samples.length <= 1) {
351
+ firstSampleTokens = nextTokens;
352
+ firstSampleRawTokens = nextRawStream;
353
+ liveBaseAt = update.at;
354
+ liveBaseTokens = nextTokens;
355
+ pushSample(update.at, nextTokens);
356
+ } else {
357
+ const singleDelta = nextTokens - prevCount;
358
+ const cut = update.at - SPEED_WINDOW_MS;
359
+ let windowBaseTokens = liveBaseTokens;
360
+ for (const sample of samples) {
361
+ if (sample.t <= cut) windowBaseTokens = sample.tokens;
362
+ else break;
363
+ }
364
+ const otherWindowDeltas = Math.max(0, prevCount - windowBaseTokens);
365
+ const isMidStreamSpike = singleDelta > SPIKE_MIN_TOKENS && (
366
+ (otherWindowDeltas > 0 && singleDelta > otherWindowDeltas)
367
+ || (otherWindowDeltas === 0 && update.at - lastTokenUpdateAt > SPEED_WINDOW_MS)
368
+ );
369
+ if (isMidStreamSpike) {
370
+ liveBaseAt = update.at;
371
+ liveBaseTokens = nextTokens;
372
+ samples = [{ t: update.at, tokens: nextTokens }];
373
+ } else {
374
+ pushSample(update.at, nextTokens);
375
+ }
376
+ }
377
+ lastTokenUpdateAt = update.at;
241
378
  }
242
379
  return publish(update.at);
243
380
  },
244
381
  refresh(at: number): boolean {
245
382
  lastNow = at;
246
- if (streaming && firstTokenAt !== undefined) pushSample(at, liveCount());
383
+ if (streaming && liveBaseAt !== undefined) pushSample(at, liveCount());
247
384
  return publish(at);
248
385
  },
249
386
  onAssistantEnd(finalUsage: UsageLike | undefined, at: number): boolean {
@@ -252,16 +389,52 @@ export function createTokenSpeedTracker() {
252
389
  streaming = false;
253
390
  segmentEndedAt = at;
254
391
  readUsage(finalUsage, usage);
392
+ const visible = rawStreamTokens > 0 ? streamTokens : liveCount();
255
393
  const reported = finiteNumber(finalUsage?.output);
256
394
  if (reported !== undefined && reported >= providerOutput) providerOutput = reported;
257
395
  if (usage.output === undefined && providerOutput > 0) usage.output = providerOutput;
258
396
  const count = reported !== undefined && reported >= DECODE_SPEED_MIN_OUTPUT
259
397
  ? reported
260
- : liveCount();
398
+ : Math.max(providerOutput, streamTokens);
399
+
400
+ if (
401
+ (usage.reasoning === undefined || usage.reasoning === 0)
402
+ && reported !== undefined
403
+ && reported >= 64
404
+ && rawStreamTokens > 0
405
+ ) {
406
+ const rawRatio = reported / rawStreamTokens;
407
+ if (rawRatio > CALIBRATION_MIN && rawRatio < CALIBRATION_MAX) {
408
+ const prevRatio = calibrationRatio();
409
+ const nextRatio = Math.min(
410
+ CALIBRATION_MAX,
411
+ Math.max(CALIBRATION_MIN, prevRatio * (1 - CALIBRATION_ALPHA) + rawRatio * CALIBRATION_ALPHA),
412
+ );
413
+ calibrationRatios.set(currentModelKey, nextRatio);
414
+ }
415
+ }
416
+
261
417
  if (count > 0 && firstTokenAt === undefined) firstTokenAt = assistantStartedAt ?? at;
262
- const average = outputSpeed(count, firstTokenAt, at);
418
+ const hiddenOrBurst = count - visible > Math.max(32, 0.35 * count)
419
+ || firstSampleTokens > 0.5 * count
420
+ || firstSampleRawTokens > 0.5 * count;
421
+ decodeStartedAt = hiddenOrBurst ? (assistantStartedAt ?? firstTokenAt) : firstTokenAt;
422
+
423
+ const elapsedMs = decodeStartedAt !== undefined ? at - decodeStartedAt : 0;
424
+ const reliable = count >= RELIABLE_MIN_OUTPUT && elapsedMs >= RELIABLE_MIN_ELAPSED_MS;
263
425
  lastLive = undefined;
264
- if (average !== undefined) displayed = average;
426
+ let average: number | undefined;
427
+ if (reliable) {
428
+ runTokens += count;
429
+ runElapsedMs += elapsedMs;
430
+ average = outputSpeed(runTokens, 0, runElapsedMs);
431
+ if (average !== undefined) {
432
+ displayed = average;
433
+ lastReliable = average;
434
+ }
435
+ } else {
436
+ displayed = lastReliable;
437
+ }
265
438
  frozen = collect();
266
439
  return average !== undefined;
267
440
  },
@@ -270,6 +443,7 @@ export function createTokenSpeedTracker() {
270
443
  const rate = outputSpeed(output, startedAt, endedAt);
271
444
  if (rate === undefined) return false;
272
445
  displayed = rate;
446
+ lastReliable = rate;
273
447
  lastNow = endedAt;
274
448
  return true;
275
449
  },
@@ -285,20 +459,35 @@ export function createTokenSpeedTracker() {
285
459
  },
286
460
  reset() {
287
461
  displayed = undefined;
462
+ lastReliable = undefined;
288
463
  lastLive = undefined;
289
464
  streaming = false;
290
465
  lastPublish = 0;
291
466
  lastStreamAt = Number.NEGATIVE_INFINITY;
467
+ lastTokenUpdateAt = Number.NEGATIVE_INFINITY;
292
468
  lastNow = 0;
293
469
  turnStartedAt = undefined;
294
470
  assistantStartedAt = undefined;
295
471
  firstTokenAt = undefined;
472
+ decodeStartedAt = undefined;
296
473
  segmentEndedAt = undefined;
297
474
  providerOutput = 0;
475
+ providerAdvances = 0;
476
+ firstProviderSample = undefined;
477
+ rawStreamTokens = 0;
298
478
  streamTokens = 0;
479
+ hasSeenDelta = false;
480
+ firstSampleTokens = 0;
481
+ firstSampleRawTokens = 0;
482
+ liveBaseAt = undefined;
483
+ liveBaseTokens = 0;
299
484
  samples = [];
300
485
  usage = {};
301
486
  frozen = undefined;
487
+ runTokens = 0;
488
+ runElapsedMs = 0;
489
+ currentModelKey = "__default__";
490
+ calibrationRatios.clear();
302
491
  },
303
492
  };
304
493
  }
@@ -0,0 +1,161 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
+ import { readFileSync } from "node:fs";
4
+ import type { UiLanguage } from "./settings.ts";
5
+
6
+ export const UPDATE_RELEASE_DATE = "2026-11-04";
7
+ const MIN_BANNER_VERSION = "2.0.19";
8
+
9
+ export function isNewerVersion(current: string, previous?: string): boolean {
10
+ if (!/^\d+\.\d+\.\d+$/.test(current)) return false;
11
+ if (!previous) return true;
12
+ if (!/^\d+\.\d+\.\d+$/.test(previous)) return false;
13
+ const curParts = current.split(".").map(Number);
14
+ const prevParts = previous.split(".").map(Number);
15
+ for (let i = 0; i < 3; i++) {
16
+ if (curParts[i] !== prevParts[i]) return curParts[i] > prevParts[i];
17
+ }
18
+ return false;
19
+ }
20
+
21
+ function readPackageVersion(): string {
22
+ try {
23
+ const raw = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version?: unknown };
24
+ if (typeof raw.version === "string" && /^\d+\.\d+\.\d+$/.test(raw.version)) {
25
+ return isNewerVersion(raw.version, MIN_BANNER_VERSION) ? raw.version : MIN_BANNER_VERSION;
26
+ }
27
+ } catch {
28
+ // Fallback to MIN_BANNER_VERSION when package.json cannot be read.
29
+ }
30
+ return MIN_BANNER_VERSION;
31
+ }
32
+
33
+ export const PACKAGE_VERSION: string = readPackageVersion();
34
+
35
+ interface UpdateNoteItem {
36
+ title: string;
37
+ desc: string;
38
+ }
39
+
40
+ const UPDATE_ITEMS: Record<UiLanguage, readonly UpdateNoteItem[]> = {
41
+ zh: [
42
+ {
43
+ title: "长会话折叠不卡顿(渲染提速 24×)",
44
+ desc: "已完成的折叠轮次直接复用整块渲染结果并平移鼠标坐标,96 轮长会话每帧耗时由 121ms 降至 5ms。",
45
+ },
46
+ {
47
+ title: "思考场景 Token 速度准确度修复",
48
+ desc: "识别代理整块缓冲的思考突发,改从消息起点计算速度并结合 2.5s 滑窗与 EMA 校准,修正 500+ tok/s 虚高。",
49
+ },
50
+ {
51
+ title: "原生支持 pi -p 子代理过程树与分步用量",
52
+ desc: "无需安装 pi-subagents 即可将 shell 中的 pi -p 调用收纳为子代理行,支持 Ctrl+S 展开查看每步 Token 与耗时。",
53
+ },
54
+ ],
55
+ en: [
56
+ {
57
+ title: "24× Faster Long-Session Rendering",
58
+ desc: "Completed collapsed turns reuse cached block renders with translated mouse coordinates, cutting 96-turn frame time from 121ms to 5ms.",
59
+ },
60
+ {
61
+ title: "Accurate Token Speed with Thinking",
62
+ desc: "Detects buffered thinking bursts, measures from message start, and applies a 2.5s sliding window with EMA calibration.",
63
+ },
64
+ {
65
+ title: "Built-in pi -p Subagent Tree & Step Usage",
66
+ desc: "Collects shell pi -p calls into subagent rows without pi-subagents; press Ctrl+S to inspect per-step tokens and duration.",
67
+ },
68
+ ],
69
+ };
70
+
71
+ function stripOsc8(text: string): string {
72
+ return text.replace(/\x1b\]8;;[^\x07]*\x07/g, "");
73
+ }
74
+
75
+ function widthOf(text: string): number {
76
+ return visibleWidth(stripOsc8(text));
77
+ }
78
+
79
+ export function renderUpdateBanner(
80
+ theme: Pick<ExtensionContext["ui"]["theme"], "fg" | "bold">,
81
+ width: number,
82
+ options: { version?: string; language?: UiLanguage; collapsed?: boolean } = {},
83
+ ): { rows: string[]; headerRows: number } {
84
+ if (width < 24) return { rows: [], headerRows: 0 };
85
+ const version = options.version ?? PACKAGE_VERSION;
86
+ const lang: UiLanguage = options.language ?? "zh";
87
+ const collapsed = options.collapsed ?? false;
88
+ const items = UPDATE_ITEMS[lang] ?? UPDATE_ITEMS.zh;
89
+ const innerWidth = Math.max(1, width - 6);
90
+ const borderV = theme.fg("dim", "│");
91
+ const topBorder = theme.fg("dim", "╭" + "─".repeat(Math.max(0, width - 2)) + "╮");
92
+ const midBorder = theme.fg("dim", "├" + "─".repeat(Math.max(0, width - 2)) + "┤");
93
+ const bottomBorder = theme.fg("dim", "╰" + "─".repeat(Math.max(0, width - 2)) + "╯");
94
+
95
+ const boxLine = (content: string): string => {
96
+ const w = widthOf(content);
97
+ const fitted = w > innerWidth ? truncateToWidth(stripOsc8(content), innerWidth, "…") : content;
98
+ const pad = Math.max(0, innerWidth - widthOf(fitted));
99
+ return `${borderV} ${fitted}${" ".repeat(pad)} ${borderV}`;
100
+ };
101
+
102
+ const splitLine = (left: string, right: string, rightHref?: string): string => {
103
+ const lw = widthOf(left);
104
+ const rw = widthOf(right);
105
+ if (lw + 2 + rw <= innerWidth) {
106
+ const gap = " ".repeat(innerWidth - lw - rw);
107
+ const linkedRight = rightHref ? `\x1b]8;;${rightHref}\x07${right}\x1b]8;;\x07` : right;
108
+ return `${left}${gap}${linkedRight}`;
109
+ }
110
+ if (rw + 4 <= innerWidth) {
111
+ const truncatedLeft = truncateToWidth(stripOsc8(left), Math.max(1, innerWidth - rw - 2), "…");
112
+ const gap = " ".repeat(Math.max(1, innerWidth - widthOf(truncatedLeft) - rw));
113
+ const linkedRight = rightHref ? `\x1b]8;;${rightHref}\x07${right}\x1b]8;;\x07` : right;
114
+ return `${truncatedLeft}${gap}${linkedRight}`;
115
+ }
116
+ return truncateToWidth(stripOsc8(left), innerWidth, "…");
117
+ };
118
+
119
+ const leftHeader = theme.bold(
120
+ theme.fg("accent", lang === "en" ? `pi-mini-mode v${version} Release Notes` : `pi-mini-mode v${version} 更新摘要`),
121
+ );
122
+ const rightHeader = theme.fg(
123
+ "muted",
124
+ collapsed
125
+ ? (lang === "en" ? `${UPDATE_RELEASE_DATE} · ${items.length} updates · [Expand]` : `${UPDATE_RELEASE_DATE} · ${items.length} 项更新 · [展开]`)
126
+ : (lang === "en" ? `${UPDATE_RELEASE_DATE} · ${items.length} updates` : `${UPDATE_RELEASE_DATE} · ${items.length} 项更新`),
127
+ );
128
+
129
+ const rows: string[] = [
130
+ topBorder,
131
+ boxLine(splitLine(leftHeader, rightHeader)),
132
+ ];
133
+
134
+ if (collapsed) {
135
+ rows.push(bottomBorder);
136
+ return { rows, headerRows: 3 };
137
+ }
138
+
139
+ rows.push(boxLine(""));
140
+ for (let idx = 0; idx < items.length; idx++) {
141
+ if (idx > 0) rows.push(boxLine(""));
142
+ const item = items[idx];
143
+ rows.push(boxLine(theme.bold(theme.fg("text", `${idx + 1}. ${item.title}`))));
144
+ const wrapped = wrapTextWithAnsi(theme.fg("muted", item.desc), innerWidth);
145
+ for (const line of wrapped) {
146
+ rows.push(boxLine(line));
147
+ }
148
+ }
149
+
150
+ rows.push(midBorder);
151
+ const leftFooter = theme.fg(
152
+ "muted",
153
+ lang === "en" ? "Scrolls up with chat · Click header to fold" : "发消息后自动随会话向上滚动 · 点击标题栏可随时折叠",
154
+ );
155
+ const rightFooter = theme.fg("accent", `GitHub Release v${version} ↗`);
156
+ const releaseUrl = `https://github.com/eachann1024/pi-mini-mode/releases/tag/v${version}`;
157
+ rows.push(boxLine(splitLine(leftFooter, rightFooter, releaseUrl)));
158
+ rows.push(bottomBorder);
159
+
160
+ return { rows, headerRows: 3 };
161
+ }
package/lib/usage.ts CHANGED
@@ -64,8 +64,15 @@ export interface CacheWaste {
64
64
  missCount: number;
65
65
  }
66
66
 
67
+ let cachedWaste: { len: number; first: unknown; last: unknown; value: CacheWaste } | undefined;
68
+
67
69
  /** Same noise floor as Pi's cache-miss notice. Compaction resets the baseline. */
68
70
  export function cacheWaste(entries: ReadonlyArray<{ type?: unknown; message?: { role?: unknown; usage?: UsageLike } }>): CacheWaste {
71
+ const first = entries[0];
72
+ const last = entries.at(-1);
73
+ if (cachedWaste && cachedWaste.len === entries.length && cachedWaste.first === first && cachedWaste.last === last) {
74
+ return { ...cachedWaste.value };
75
+ }
69
76
  let prev = 0;
70
77
  let reported = false;
71
78
  const totals = { missedTokens: 0, missCount: 0 };
@@ -83,18 +90,50 @@ export function cacheWaste(entries: ReadonlyArray<{ type?: unknown; message?: {
83
90
  }
84
91
  if (prompt > 0) { prev = prompt; reported ||= cacheRead + cacheWrite > 0; }
85
92
  }
86
- return totals;
93
+ cachedWaste = { len: entries.length, first, last, value: totals };
94
+ return { ...totals };
87
95
  }
88
96
 
97
+ let cachedSessionUsage: { sm: unknown; key: string; first: unknown; last: unknown; value: SessionUsage } | undefined;
98
+
89
99
  /** Aggregate persisted, finalized usage once per active-branch entry. */
90
100
  export function sessionUsage(ctx: ExtensionContext): SessionUsage {
91
- return ctx.sessionManager.getBranch().reduce((total, entry) => {
101
+ const sm = ctx.sessionManager as { getLeafId?(): string | null; getEntries?(): unknown[]; getBranch(): Array<{ type?: unknown; message?: unknown }> };
102
+ const hasFastKey = typeof sm.getLeafId === "function" && typeof sm.getEntries === "function";
103
+ if (hasFastKey) {
104
+ const entries = sm.getEntries!();
105
+ const key = `${sm.getLeafId!() ?? ""}:${entries.length}`;
106
+ const first = entries[0];
107
+ const last = entries.at(-1);
108
+ if (cachedSessionUsage && cachedSessionUsage.sm === sm && cachedSessionUsage.key === key && cachedSessionUsage.first === first && cachedSessionUsage.last === last) {
109
+ return { ...cachedSessionUsage.value };
110
+ }
111
+ const value = sm.getBranch().reduce((total, entry) => {
112
+ if (entry.type !== "message") return total;
113
+ const message = entry.message as { role?: unknown; usage?: UsageLike };
114
+ return message.role === "assistant" || message.role === "toolResult"
115
+ ? addUsage(total, message.usage)
116
+ : total;
117
+ }, { ...EMPTY_USAGE });
118
+ cachedSessionUsage = { sm, key, first, last, value };
119
+ return { ...value };
120
+ }
121
+ const branch = sm.getBranch();
122
+ const key = `b:${branch.length}`;
123
+ const first = branch[0];
124
+ const last = branch.at(-1);
125
+ if (cachedSessionUsage && cachedSessionUsage.sm === sm && cachedSessionUsage.key === key && cachedSessionUsage.first === first && cachedSessionUsage.last === last) {
126
+ return { ...cachedSessionUsage.value };
127
+ }
128
+ const value = branch.reduce((total, entry) => {
92
129
  if (entry.type !== "message") return total;
93
130
  const message = entry.message as { role?: unknown; usage?: UsageLike };
94
131
  return message.role === "assistant" || message.role === "toolResult"
95
132
  ? addUsage(total, message.usage)
96
133
  : total;
97
134
  }, { ...EMPTY_USAGE });
135
+ cachedSessionUsage = { sm, key, first, last, value };
136
+ return { ...value };
98
137
  }
99
138
 
100
139
  export function cacheHit(usage: SessionUsage): number | undefined {
@@ -116,12 +155,6 @@ export function formatSpeed(speed: number, showUnit: boolean): string {
116
155
  return showUnit ? `${value} tok/s` : value;
117
156
  }
118
157
 
119
- export interface ActiveGeneration {
120
- firstTokenAt?: number;
121
- output: number;
122
- lastSampleAt: number;
123
- }
124
-
125
158
  /** Hide sub-100ms bursts (batched usage) and 1-token completions; they are not a decode rate. */
126
159
  export const DECODE_SPEED_MIN_ELAPSED_MS = 100;
127
160
  export const DECODE_SPEED_MIN_OUTPUT = 2;