@each1024/pi-mini-mode 2.0.18 → 2.0.20

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,
@@ -1,9 +1,32 @@
1
+ import type { UiLanguage } from "./settings.ts";
1
2
  import { finiteNumber, formatSpeed, formatUsd, outputSpeed, speedColor, DECODE_SPEED_MIN_OUTPUT, type SpeedColor, type UsageLike } from "./usage.ts";
2
3
 
3
4
  /** Footer redraw cadence while a turn is streaming. */
4
5
  export const SPEED_REFRESH_MS = 500;
5
6
  /** 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;
7
+ export const SPEED_WINDOW_MS = 2_500;
8
+
9
+ const CALIBRATION_ALPHA = 0.3;
10
+ const CALIBRATION_MIN = 0.5;
11
+ const CALIBRATION_MAX = 2;
12
+ const RELIABLE_MIN_ELAPSED_MS = 1_000;
13
+ const RELIABLE_MIN_OUTPUT = 16;
14
+ const SPIKE_MIN_TOKENS = 64;
15
+
16
+ export type ModelIdentifier = string | { provider?: unknown; model?: unknown };
17
+
18
+ function normalizeModelKey(model?: ModelIdentifier): string {
19
+ if (typeof model === "string") {
20
+ const trimmed = model.trim().replace(/^\/+|\/+$/g, "");
21
+ return trimmed || "__default__";
22
+ }
23
+ if (model && typeof model === "object") {
24
+ const provider = typeof model.provider === "string" ? model.provider.trim() : "";
25
+ const id = typeof model.model === "string" ? model.model.trim() : "";
26
+ return [provider, id].filter(Boolean).join("/") || "__default__";
27
+ }
28
+ return "__default__";
29
+ }
7
30
 
8
31
  export interface SpeedMetric {
9
32
  label: string;
@@ -11,6 +34,50 @@ export interface SpeedMetric {
11
34
  color?: SpeedColor | "text" | "muted";
12
35
  }
13
36
 
37
+ const SPEED_COPY: Record<UiLanguage, {
38
+ average: string;
39
+ live: string;
40
+ ttft: string;
41
+ decode: string;
42
+ output: string;
43
+ input: string;
44
+ cacheRead: string;
45
+ cacheWrite: string;
46
+ cacheWrite1h: string;
47
+ reasoning: string;
48
+ totalTokens: string;
49
+ cost: string;
50
+ }> = {
51
+ zh: {
52
+ average: "平均速度",
53
+ live: "实时速度",
54
+ ttft: "首字吐字",
55
+ decode: "解码用时",
56
+ output: "输出 token",
57
+ input: "输入 token",
58
+ cacheRead: "缓存读取",
59
+ cacheWrite: "缓存写入",
60
+ cacheWrite1h: "写入 1h",
61
+ reasoning: "推理 token",
62
+ totalTokens: "合计 token",
63
+ cost: "费用",
64
+ },
65
+ en: {
66
+ average: "Avg speed",
67
+ live: "Live speed",
68
+ ttft: "First token",
69
+ decode: "Decode time",
70
+ output: "Output tokens",
71
+ input: "Input tokens",
72
+ cacheRead: "Cache read",
73
+ cacheWrite: "Cache write",
74
+ cacheWrite1h: "Cache write 1h",
75
+ reasoning: "Reasoning tokens",
76
+ totalTokens: "Total tokens",
77
+ cost: "Cost",
78
+ },
79
+ };
80
+
14
81
  interface Sample {
15
82
  t: number;
16
83
  tokens: number;
@@ -90,32 +157,51 @@ export interface StreamUpdate {
90
157
  output?: number;
91
158
  content?: unknown;
92
159
  usage?: UsageLike;
160
+ type?: string;
161
+ delta?: string;
93
162
  }
94
163
 
95
164
  /**
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.
165
+ * Live footer speed is the token rate over the last 2.5 seconds, republished
166
+ * every 500ms. Provider `usage.output` wins once it advances monotonically at
167
+ * least twice; streamed text keeps the rate moving otherwise. The finished
168
+ * turn replaces it with the reliable weighted decode speed across the run.
100
169
  */
101
170
  export function createTokenSpeedTracker() {
102
171
  let displayed: number | undefined;
172
+ let lastReliable: number | undefined;
103
173
  let lastLive: number | undefined;
104
174
  let streaming = false;
105
175
  let lastPublish = 0;
106
176
  let lastStreamAt = Number.NEGATIVE_INFINITY;
177
+ let lastTokenUpdateAt = Number.NEGATIVE_INFINITY;
107
178
  let lastNow = 0;
108
179
  let turnStartedAt: number | undefined;
109
180
  let assistantStartedAt: number | undefined;
110
181
  let firstTokenAt: number | undefined;
182
+ let decodeStartedAt: number | undefined;
111
183
  let segmentEndedAt: number | undefined;
112
184
  let providerOutput = 0;
185
+ let providerAdvances = 0;
186
+ let firstProviderSample: Sample | undefined;
187
+ let rawStreamTokens = 0;
113
188
  let streamTokens = 0;
189
+ let hasSeenDelta = false;
190
+ let firstSampleTokens = 0;
191
+ let firstSampleRawTokens = 0;
192
+ let liveBaseAt: number | undefined;
193
+ let liveBaseTokens = 0;
114
194
  let samples: Sample[] = [];
115
195
  let usage: UsageSnapshot = {};
116
- let frozen: SpeedMetric[] | undefined;
196
+ let frozen: Record<UiLanguage, SpeedMetric[]> | undefined;
197
+ let runTokens = 0;
198
+ let runElapsedMs = 0;
199
+ let currentModelKey = "__default__";
200
+ const calibrationRatios = new Map<string, number>();
117
201
 
118
- const liveCount = () => Math.max(providerOutput, streamTokens);
202
+ const calibrationRatio = () => calibrationRatios.get(currentModelKey) ?? 1;
203
+ const trustedProvider = () => (providerAdvances >= 2 ? providerOutput : 0);
204
+ const liveCount = () => Math.max(trustedProvider(), streamTokens);
119
205
 
120
206
  const pushSample = (at: number, tokens: number) => {
121
207
  const last = samples[samples.length - 1];
@@ -126,12 +212,12 @@ export function createTokenSpeedTracker() {
126
212
  };
127
213
 
128
214
  const liveRate = (now: number): number | undefined => {
129
- if (firstTokenAt === undefined || now - firstTokenAt < SPEED_REFRESH_MS) return undefined;
215
+ if (liveBaseAt === undefined || now - liveBaseAt < SPEED_REFRESH_MS) return undefined;
130
216
  const tokens = liveCount();
131
- const windowMs = Math.min(SPEED_WINDOW_MS, now - firstTokenAt);
217
+ const windowMs = Math.min(SPEED_WINDOW_MS, now - liveBaseAt);
132
218
  const cut = now - windowMs;
133
- let baseT = firstTokenAt;
134
- let baseTokens = 0;
219
+ let baseT = liveBaseAt;
220
+ let baseTokens = liveBaseTokens;
135
221
  for (const sample of samples) {
136
222
  if (sample.t <= cut) {
137
223
  baseT = sample.t;
@@ -157,93 +243,190 @@ export function createTokenSpeedTracker() {
157
243
  return changed;
158
244
  };
159
245
 
160
- const settledCount = () => usage.output !== undefined && usage.output >= DECODE_SPEED_MIN_OUTPUT ? usage.output : liveCount();
246
+ const settledCount = () => usage.output !== undefined && usage.output >= DECODE_SPEED_MIN_OUTPUT
247
+ ? usage.output
248
+ : Math.max(providerOutput, streamTokens);
161
249
 
162
250
  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);
251
+ if (streaming) return outputSpeed(liveCount(), firstTokenAt, now);
252
+ if (displayed !== undefined) return displayed;
253
+ const end = segmentEndedAt ?? now;
254
+ return outputSpeed(settledCount(), decodeStartedAt ?? firstTokenAt, end);
166
255
  };
167
256
 
168
- const collect = (): SpeedMetric[] => {
257
+ const collect = (lang: UiLanguage = "zh"): SpeedMetric[] => {
258
+ const copy = SPEED_COPY[lang] ?? SPEED_COPY.zh;
169
259
  const rows: SpeedMetric[] = [];
170
260
  const now = lastNow || Date.now();
171
261
  const average = runningAverage(now);
172
- if (average !== undefined) rows.push({ label: "平均速度", value: formatSpeed(average, true), color: speedColor(average) });
173
- if (streaming && lastLive !== undefined) rows.push({ label: "实时速度", value: formatSpeed(lastLive, true), color: speedColor(lastLive) });
262
+ if (average !== undefined) rows.push({ label: copy.average, value: formatSpeed(average, true), color: speedColor(average) });
263
+ if (streaming && lastLive !== undefined) rows.push({ label: copy.live, value: formatSpeed(lastLive, true), color: speedColor(lastLive) });
174
264
  const origin = turnStartedAt ?? assistantStartedAt;
175
265
  if (firstTokenAt !== undefined && origin !== undefined && firstTokenAt > origin) {
176
- rows.push({ label: "首字吐字", value: formatDuration(firstTokenAt - origin), color: "text" });
266
+ rows.push({ label: copy.ttft, value: formatDuration(firstTokenAt - origin), color: "text" });
177
267
  }
268
+ const decodeStart = streaming ? firstTokenAt : (decodeStartedAt ?? firstTokenAt);
178
269
  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" });
270
+ if (decodeStart !== undefined && decodeEnd !== undefined && decodeEnd - decodeStart >= SPEED_REFRESH_MS) {
271
+ rows.push({ label: copy.decode, value: formatDuration(decodeEnd - decodeStart), color: "text" });
181
272
  }
182
273
  const counts: Array<[keyof UsageSnapshot, string]> = [
183
- ["output", "输出 token"],
184
- ["input", "输入 token"],
185
- ["cacheRead", "缓存读取"],
186
- ["cacheWrite", "缓存写入"],
187
- ["cacheWrite1h", "写入 1h"],
188
- ["reasoning", "推理 token"],
189
- ["totalTokens", "合计 token"],
274
+ ["output", copy.output],
275
+ ["input", copy.input],
276
+ ["cacheRead", copy.cacheRead],
277
+ ["cacheWrite", copy.cacheWrite],
278
+ ["cacheWrite1h", copy.cacheWrite1h],
279
+ ["reasoning", copy.reasoning],
280
+ ["totalTokens", copy.totalTokens],
190
281
  ];
191
282
  for (const [key, label] of counts) {
192
283
  const value = usage[key];
193
284
  if (value === undefined || value <= 0) continue;
194
285
  rows.push({ label, value: formatCount(value), color: "text" });
195
286
  }
196
- if (usage.output === undefined && !streaming && liveCount() >= DECODE_SPEED_MIN_OUTPUT) {
197
- rows.push({ label: "输出 token", value: formatCount(liveCount()), color: "text" });
287
+ if (usage.output === undefined && !streaming && settledCount() >= DECODE_SPEED_MIN_OUTPUT) {
288
+ rows.push({ label: copy.output, value: formatCount(settledCount()), color: "text" });
198
289
  }
199
- if (usage.cost !== undefined && usage.cost > 0) rows.push({ label: "费用", value: formatUsd(usage.cost), color: "muted" });
290
+ if (usage.cost !== undefined && usage.cost > 0) rows.push({ label: copy.cost, value: formatUsd(usage.cost), color: "muted" });
200
291
  if (rows.length === 0 && displayed !== undefined) {
201
- rows.push({ label: "平均速度", value: formatSpeed(displayed, true), color: speedColor(displayed) });
292
+ rows.push({ label: copy.average, value: formatSpeed(displayed, true), color: speedColor(displayed) });
202
293
  }
203
294
  return rows;
204
295
  };
205
296
 
206
297
  return {
298
+ onRunStart() {
299
+ runTokens = 0;
300
+ runElapsedMs = 0;
301
+ },
207
302
  onTurnStart(at: number) {
208
303
  lastNow = at;
209
304
  turnStartedAt = at;
210
305
  },
211
- onAssistantStart(at: number) {
306
+ onAssistantStart(at: number, model?: ModelIdentifier) {
212
307
  lastNow = at;
213
308
  streaming = true;
214
309
  lastPublish = at;
215
310
  lastStreamAt = Number.NEGATIVE_INFINITY;
311
+ lastTokenUpdateAt = Number.NEGATIVE_INFINITY;
216
312
  assistantStartedAt = at;
217
313
  firstTokenAt = undefined;
314
+ decodeStartedAt = undefined;
218
315
  segmentEndedAt = undefined;
219
316
  providerOutput = 0;
317
+ providerAdvances = 0;
318
+ firstProviderSample = undefined;
319
+ rawStreamTokens = 0;
220
320
  streamTokens = 0;
321
+ hasSeenDelta = false;
322
+ firstSampleTokens = 0;
323
+ firstSampleRawTokens = 0;
324
+ liveBaseAt = undefined;
325
+ liveBaseTokens = 0;
221
326
  samples = [];
222
327
  usage = {};
223
328
  lastLive = undefined;
329
+ currentModelKey = normalizeModelKey(model);
224
330
  },
225
331
  onStream(update: StreamUpdate): boolean {
226
332
  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);
333
+ let prevCount = liveCount();
334
+
335
+ if (update.output !== undefined && update.output > providerOutput) {
336
+ providerAdvances += 1;
337
+ providerOutput = update.output;
338
+ if (providerAdvances === 1) {
339
+ firstProviderSample = { t: update.at, tokens: update.output };
340
+ } else if (providerAdvances === 2 && firstProviderSample) {
341
+ if (firstTokenAt === undefined || firstProviderSample.t < firstTokenAt) {
342
+ firstTokenAt = firstProviderSample.t;
343
+ decodeStartedAt = firstProviderSample.t;
344
+ firstSampleTokens = firstProviderSample.tokens;
345
+ firstSampleRawTokens = firstProviderSample.tokens;
346
+ liveBaseAt = firstProviderSample.t;
347
+ liveBaseTokens = firstProviderSample.tokens;
348
+ lastTokenUpdateAt = firstProviderSample.t;
349
+ pushSample(firstProviderSample.t, firstProviderSample.tokens);
350
+ } else if (liveBaseAt === firstProviderSample.t) {
351
+ liveBaseTokens = Math.max(liveBaseTokens, firstProviderSample.tokens);
352
+ firstSampleTokens = Math.max(firstSampleTokens, firstProviderSample.tokens);
353
+ pushSample(firstProviderSample.t, liveBaseTokens);
354
+ }
355
+ prevCount = Math.max(prevCount, firstProviderSample.tokens);
356
+ firstProviderSample = undefined;
357
+ }
358
+ }
359
+
360
+ const isDeltaType = update.type === undefined
361
+ || update.type === "text_delta"
362
+ || update.type === "thinking_delta"
363
+ || update.type === "toolcall_delta";
364
+ const isBoundaryType = update.type !== undefined
365
+ && (/(?:^|_)(?:start|end)$/.test(update.type) || update.type === "done" || update.type === "error");
366
+
367
+ let nextRawStream = rawStreamTokens;
368
+ if (typeof update.delta === "string" && isDeltaType) {
369
+ hasSeenDelta = true;
370
+ nextRawStream += estimateTextTokens(update.delta);
371
+ } else if (!hasSeenDelta && !isBoundaryType && update.content !== undefined) {
372
+ nextRawStream = Math.max(rawStreamTokens, estimateContentTokens(update.content));
373
+ }
374
+ const nextStream = nextRawStream * calibrationRatio();
375
+ const nextTokens = Math.max(trustedProvider(), nextStream);
376
+
230
377
  // Regressing or repeated samples must not move the clock. The 500ms timer
231
378
  // still decays the live rate when tokens actually stop arriving.
232
- if (nextTokens <= liveCount() && liveCount() > 0) return false;
379
+ if (nextTokens <= prevCount && prevCount > 0) return false;
380
+
233
381
  lastStreamAt = update.at;
234
382
  lastNow = update.at;
235
- providerOutput = nextProvider;
383
+ rawStreamTokens = nextRawStream;
236
384
  streamTokens = nextStream;
237
385
  readUsage(update.usage, usage);
386
+
238
387
  if (nextTokens > 0) {
239
- if (firstTokenAt === undefined) firstTokenAt = update.at;
240
- pushSample(update.at, nextTokens);
388
+ if (firstTokenAt === undefined) {
389
+ firstTokenAt = update.at;
390
+ decodeStartedAt = update.at;
391
+ firstSampleTokens = nextTokens;
392
+ firstSampleRawTokens = nextRawStream;
393
+ liveBaseAt = update.at;
394
+ liveBaseTokens = nextTokens;
395
+ pushSample(update.at, nextTokens);
396
+ } else if (update.at === firstTokenAt && samples.length <= 1) {
397
+ firstSampleTokens = nextTokens;
398
+ firstSampleRawTokens = nextRawStream;
399
+ liveBaseAt = update.at;
400
+ liveBaseTokens = nextTokens;
401
+ pushSample(update.at, nextTokens);
402
+ } else {
403
+ const singleDelta = nextTokens - prevCount;
404
+ const cut = update.at - SPEED_WINDOW_MS;
405
+ let windowBaseTokens = liveBaseTokens;
406
+ for (const sample of samples) {
407
+ if (sample.t <= cut) windowBaseTokens = sample.tokens;
408
+ else break;
409
+ }
410
+ const otherWindowDeltas = Math.max(0, prevCount - windowBaseTokens);
411
+ const isMidStreamSpike = singleDelta > SPIKE_MIN_TOKENS && (
412
+ (otherWindowDeltas > 0 && singleDelta > otherWindowDeltas)
413
+ || (otherWindowDeltas === 0 && update.at - lastTokenUpdateAt > SPEED_WINDOW_MS)
414
+ );
415
+ if (isMidStreamSpike) {
416
+ liveBaseAt = update.at;
417
+ liveBaseTokens = nextTokens;
418
+ samples = [{ t: update.at, tokens: nextTokens }];
419
+ } else {
420
+ pushSample(update.at, nextTokens);
421
+ }
422
+ }
423
+ lastTokenUpdateAt = update.at;
241
424
  }
242
425
  return publish(update.at);
243
426
  },
244
427
  refresh(at: number): boolean {
245
428
  lastNow = at;
246
- if (streaming && firstTokenAt !== undefined) pushSample(at, liveCount());
429
+ if (streaming && liveBaseAt !== undefined) pushSample(at, liveCount());
247
430
  return publish(at);
248
431
  },
249
432
  onAssistantEnd(finalUsage: UsageLike | undefined, at: number): boolean {
@@ -252,17 +435,53 @@ export function createTokenSpeedTracker() {
252
435
  streaming = false;
253
436
  segmentEndedAt = at;
254
437
  readUsage(finalUsage, usage);
438
+ const visible = rawStreamTokens > 0 ? streamTokens : liveCount();
255
439
  const reported = finiteNumber(finalUsage?.output);
256
440
  if (reported !== undefined && reported >= providerOutput) providerOutput = reported;
257
441
  if (usage.output === undefined && providerOutput > 0) usage.output = providerOutput;
258
442
  const count = reported !== undefined && reported >= DECODE_SPEED_MIN_OUTPUT
259
443
  ? reported
260
- : liveCount();
444
+ : Math.max(providerOutput, streamTokens);
445
+
446
+ if (
447
+ (usage.reasoning === undefined || usage.reasoning === 0)
448
+ && reported !== undefined
449
+ && reported >= 64
450
+ && rawStreamTokens > 0
451
+ ) {
452
+ const rawRatio = reported / rawStreamTokens;
453
+ if (rawRatio > CALIBRATION_MIN && rawRatio < CALIBRATION_MAX) {
454
+ const prevRatio = calibrationRatio();
455
+ const nextRatio = Math.min(
456
+ CALIBRATION_MAX,
457
+ Math.max(CALIBRATION_MIN, prevRatio * (1 - CALIBRATION_ALPHA) + rawRatio * CALIBRATION_ALPHA),
458
+ );
459
+ calibrationRatios.set(currentModelKey, nextRatio);
460
+ }
461
+ }
462
+
261
463
  if (count > 0 && firstTokenAt === undefined) firstTokenAt = assistantStartedAt ?? at;
262
- const average = outputSpeed(count, firstTokenAt, at);
464
+ const hiddenOrBurst = count - visible > Math.max(32, 0.35 * count)
465
+ || firstSampleTokens > 0.5 * count
466
+ || firstSampleRawTokens > 0.5 * count;
467
+ decodeStartedAt = hiddenOrBurst ? (assistantStartedAt ?? firstTokenAt) : firstTokenAt;
468
+
469
+ const elapsedMs = decodeStartedAt !== undefined ? at - decodeStartedAt : 0;
470
+ const reliable = count >= RELIABLE_MIN_OUTPUT && elapsedMs >= RELIABLE_MIN_ELAPSED_MS;
263
471
  lastLive = undefined;
264
- if (average !== undefined) displayed = average;
265
- frozen = collect();
472
+ let average: number | undefined;
473
+ if (reliable) {
474
+ runTokens += count;
475
+ runElapsedMs += elapsedMs;
476
+ average = outputSpeed(runTokens, 0, runElapsedMs);
477
+ if (average !== undefined) {
478
+ displayed = average;
479
+ lastReliable = average;
480
+ }
481
+ } else {
482
+ displayed = lastReliable;
483
+ }
484
+ frozen = { zh: collect("zh"), en: collect("en") };
266
485
  return average !== undefined;
267
486
  },
268
487
  noteNested(output: unknown, startedAt: number, endedAt: number): boolean {
@@ -270,6 +489,7 @@ export function createTokenSpeedTracker() {
270
489
  const rate = outputSpeed(output, startedAt, endedAt);
271
490
  if (rate === undefined) return false;
272
491
  displayed = rate;
492
+ lastReliable = rate;
273
493
  lastNow = endedAt;
274
494
  return true;
275
495
  },
@@ -279,26 +499,42 @@ export function createTokenSpeedTracker() {
279
499
  streaming(): boolean {
280
500
  return streaming;
281
501
  },
282
- metrics(): SpeedMetric[] {
283
- if (streaming && lastLive === undefined && frozen?.length) return frozen;
284
- return collect();
502
+ metrics(lang: UiLanguage = "zh"): SpeedMetric[] {
503
+ const resolved = lang === "en" ? "en" : "zh";
504
+ if (streaming && lastLive === undefined && frozen?.[resolved]?.length) return frozen[resolved];
505
+ return collect(resolved);
285
506
  },
286
507
  reset() {
287
508
  displayed = undefined;
509
+ lastReliable = undefined;
288
510
  lastLive = undefined;
289
511
  streaming = false;
290
512
  lastPublish = 0;
291
513
  lastStreamAt = Number.NEGATIVE_INFINITY;
514
+ lastTokenUpdateAt = Number.NEGATIVE_INFINITY;
292
515
  lastNow = 0;
293
516
  turnStartedAt = undefined;
294
517
  assistantStartedAt = undefined;
295
518
  firstTokenAt = undefined;
519
+ decodeStartedAt = undefined;
296
520
  segmentEndedAt = undefined;
297
521
  providerOutput = 0;
522
+ providerAdvances = 0;
523
+ firstProviderSample = undefined;
524
+ rawStreamTokens = 0;
298
525
  streamTokens = 0;
526
+ hasSeenDelta = false;
527
+ firstSampleTokens = 0;
528
+ firstSampleRawTokens = 0;
529
+ liveBaseAt = undefined;
530
+ liveBaseTokens = 0;
299
531
  samples = [];
300
532
  usage = {};
301
533
  frozen = undefined;
534
+ runTokens = 0;
535
+ runElapsedMs = 0;
536
+ currentModelKey = "__default__";
537
+ calibrationRatios.clear();
302
538
  },
303
539
  };
304
540
  }
@@ -44,8 +44,10 @@ export function attachTranscript(tui: unknown, view: TranscriptView, options: No
44
44
  // as a transcript identity check.
45
45
  const renderDescriptor = Object.getOwnPropertyDescriptor(document, "render");
46
46
  const mouseDescriptor = Object.getOwnPropertyDescriptor(document, "handleMouse");
47
+ const invalidateDescriptor = Object.getOwnPropertyDescriptor(document, "invalidate");
47
48
  const originalRender = document.render;
48
49
  const originalMouse = document.handleMouse;
50
+ const originalInvalidate = document.invalidate;
49
51
  const now = options.now ?? Date.now;
50
52
  const schedule = options.schedule ?? ((callback, delay) => {
51
53
  const timer = setTimeout(callback, delay);
@@ -103,8 +105,16 @@ export function attachTranscript(tui: unknown, view: TranscriptView, options: No
103
105
  if (event.y < viewOffset || event.y >= viewOffset + viewHeight) return;
104
106
  return view.handleMouse?.({ ...event, y: event.y - viewOffset, height: viewHeight });
105
107
  };
108
+ // Theme changes call ui.invalidate(), which reaches this document but not the
109
+ // minimal view: it is not a TUI child, and the widget invalidate is a no-op.
110
+ // Turn-line caches omit theme, so refresh them here. Native children still run.
111
+ const invalidate: NonNullable<Component["invalidate"]> = () => {
112
+ originalInvalidate?.call(document);
113
+ view.invalidate?.();
114
+ };
106
115
  document.render = render;
107
116
  document.handleMouse = mouse;
117
+ document.invalidate = invalidate;
108
118
  // Dock events never reach the document. Observe normalized events without
109
119
  // stealing wheel/selection or changing Pi's mouse protocol/listener order.
110
120
  const restoreDock = view.clearHover ? host.children.slice(1).map(child => {
@@ -162,5 +172,9 @@ export function attachTranscript(tui: unknown, view: TranscriptView, options: No
162
172
  if (mouseDescriptor) Object.defineProperty(document, "handleMouse", mouseDescriptor);
163
173
  else { delete document.handleMouse; if (document.handleMouse !== originalMouse) document.handleMouse = originalMouse; }
164
174
  }
175
+ if (document.invalidate === invalidate) {
176
+ if (invalidateDescriptor) Object.defineProperty(document, "invalidate", invalidateDescriptor);
177
+ else { delete (document as Partial<Component>).invalidate; if (document.invalidate !== originalInvalidate) document.invalidate = originalInvalidate; }
178
+ }
165
179
  };
166
180
  }
@@ -1,13 +1,14 @@
1
1
  import { Text, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
2
2
  import { getMarkdownTheme, type ExtensionContext } from "@earendil-works/pi-coding-agent";
3
3
  import { diagramMarkdown, isMarkdownProse, renderMinimalMarkdown } from "./minimal-markdown.ts";
4
+ import type { UiLanguage } from "./settings.ts";
4
5
  import { clean, record, supervisorNotice, supervisorNoticeBody } from "./transcript-notices.ts";
5
6
 
6
7
  const renderMarkdownBody = (body: string, width: number, theme?: ExtensionContext["ui"]["theme"]) => isMarkdownProse(body)
7
8
  ? renderMinimalMarkdown(body, Math.max(1, width), getMarkdownTheme(), theme?.getBgAnsi?.("userMessageBg") ?? "", undefined, diagramMarkdown)
8
9
  : new Text(body, 0, 0).render(Math.max(1, width));
9
10
 
10
- export function compactGoalCard(entry: unknown, theme: ExtensionContext["ui"]["theme"], width: number, expanded: boolean): string[] | undefined {
11
+ export function compactGoalCard(entry: unknown, theme: ExtensionContext["ui"]["theme"], width: number, expanded: boolean, lang: UiLanguage = "zh"): string[] | undefined {
11
12
  const item = record(entry);
12
13
  if (item?.customType !== "pi-codex-goal") return;
13
14
  const data = record(item.data);
@@ -17,7 +18,7 @@ export function compactGoalCard(entry: unknown, theme: ExtensionContext["ui"]["t
17
18
  // worth adding to the compact transcript.
18
19
  if (!objective || width <= 0) return;
19
20
  const status = typeof goal?.status === "string" ? clean(goal.status) : "active";
20
- const control = truncateToWidth(expanded ? "[收起]" : "[详情]", width, "");
21
+ const control = truncateToWidth(lang === "en" ? (expanded ? "[Collapse]" : "[Details]") : (expanded ? "[收起]" : "[详情]"), width, "");
21
22
  const title = theme.fg(expanded ? "accent" : "muted", `${control} ◉ Goal · ${status}`);
22
23
  const hint = theme.fg(expanded ? "accent" : "muted", " · Ctrl+O");
23
24
  const summary = truncateToWidth(objective, Math.max(0, width - visibleWidth(title) - visibleWidth(hint) - 3), "…");
@@ -26,13 +27,13 @@ export function compactGoalCard(entry: unknown, theme: ExtensionContext["ui"]["t
26
27
  return rows;
27
28
  }
28
29
 
29
- export function compactSupervisorNotice(message: unknown, theme: ExtensionContext["ui"]["theme"], width: number, expanded: boolean, label = "", history: unknown[] = [message]): string[] | undefined {
30
- const notice = supervisorNotice(message);
30
+ export function compactSupervisorNotice(message: unknown, theme: ExtensionContext["ui"]["theme"], width: number, expanded: boolean, label = "", history: unknown[] = [message], lang: UiLanguage = "zh"): string[] | undefined {
31
+ const notice = supervisorNotice(message, lang);
31
32
  if (!notice) return;
32
33
  if (width <= 0) return [];
33
34
  const { state, color, summary } = notice;
34
35
  const effectiveLabel = label || (notice.showLabel ? notice.label ?? "" : "");
35
- const control = truncateToWidth(expanded ? "[收起]" : "[详情]", width, "");
36
+ const control = truncateToWidth(lang === "en" ? (expanded ? "[Collapse]" : "[Details]") : (expanded ? "[收起]" : "[详情]"), width, "");
36
37
  const hint = " · Ctrl+O";
37
38
  let heading: string;
38
39
  let summaryText: string;
@@ -56,7 +57,7 @@ export function compactSupervisorNotice(message: unknown, theme: ExtensionContex
56
57
  if (expanded) {
57
58
  const bodies: string[] = [];
58
59
  for (const original of history) {
59
- const body = supervisorNoticeBody(original);
60
+ const body = supervisorNoticeBody(original, lang);
60
61
  if (body && !bodies.includes(body)) bodies.push(body);
61
62
  }
62
63
  for (const body of bodies) {