@each1024/pi-mini-mode 2.0.14 → 2.0.16

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/README.md CHANGED
@@ -188,7 +188,7 @@ Settings are stored globally at Pi's agent directory (normally `~/.pi/agent/pi-m
188
188
 
189
189
  Session totals are aggregated from each finalized `assistant` and `toolResult` entry on the active session branch. This includes nested LLM work reported by tools (such as a child agent) exactly once. `Total` uses the provider's `totalTokens` when supplied; older/custom results without it fall back to the sum of input, output, cache-read, and cache-write tokens. `Cached` is cache-read + cache-write (included in Total); `CH` is cache-read / (input + cache-read). Only persisted finalized usage is counted, so stream updates cannot double count totals.
190
190
 
191
- During an assistant stream, speed is decode TPS: provider `usage.output` divided by elapsed time from the first output token, excluding TTFT/prefill wait. It appears after at least two output tokens and 100ms of decode time, and is refreshed while streaming. The completed rate remains visible while later assistant messages only call tools or wait for output; it is replaced only by a newer measurable main-turn generation. Nested tool LLM usage does not overwrite a measured main-turn rate; it can set the footer only when no main generation has been measured yet. Short or single-token bursts are hidden rather than shown as inflated tok/s. Regressing output samples and non-increasing timestamps are ignored.
191
+ During an assistant stream, the footer shows the recent decode rate: tokens over the last second, redrawn every 500ms. Provider `usage.output` is the count when it advances. If that sample stays put while text is still streaming, the rate follows the streamed text instead of the stale total. When the assistant message finishes, the indicator switches to that turn's average (output tokens divided by time after the first output token, excluding TTFT). Hovering the indicator opens a floating panel beside it, above the status bar, with the average, the live rate while streaming, time to first token, and any usage fields the provider actually reported. The completed average remains visible while a later assistant message only calls tools or waits for output; it is replaced when the new reply produces a live sample. Nested tool LLM usage does not overwrite a measured main-turn rate; it can set the footer only when no speed has been measured yet. Short or single-token bursts are hidden rather than shown as inflated tok/s. Regressing output samples and non-increasing timestamps are ignored.
192
192
 
193
193
  Before a measurable response exists, the speed field is absent entirely—Pi Mini Mode never displays a `-- tok/s` placeholder. When present, speed is the rightmost footer field (the context percentage, if enabled, is immediately to its left). Its color uses Pi theme semantics: **success** at >=30 tok/s, **warning** at 10–29.9 tok/s, and **error** below 10 tok/s. No colors are hard-coded, so it follows the selected Pi theme.
194
194
 
package/README.zh-CN.md CHANGED
@@ -180,7 +180,7 @@ deepseek-v4-flash high Total 45K Cached 25K CH 40.0% $0.012 ◇ MCP 3 500
180
180
 
181
181
  会话总量来自当前会话分支中每一条已完成的 `assistant` 和 `toolResult` 记录。工具报告的嵌套 LLM 工作(例如子 Agent)会准确计入一次。若 provider 提供 `totalTokens`,`Total` 使用该值;较旧或自定义结果没有该字段时,则使用输入、输出、缓存读取和缓存写入令牌之和。`Cached` 是缓存读取与写入之和(包含在 `Total` 中);`CH` 是缓存读取量除以输入量与缓存读取量之和。只有已持久化的最终用量会计入,因此流式更新不会重复累计。
182
182
 
183
- 助手生成过程中,速度按 decode TPS 计算:用 provider 的 `usage.output` 除以从第一个输出 token 开始的耗时,不包含 TTFT/预填充等待。至少 2 个输出 token 且解码时长达 100ms 后才显示,并在流式过程中刷新。后续助手消息如果只是调用工具或等待输出,之前完成的速度仍会保留;只有新的可测量主回复才会替换它。嵌套工具里的 LLM 用量不会覆盖已测量的主回复速度;只有还没有主生成速度时,嵌套完成才能写入页脚。过短或单 token 突发不显示,避免虚高的 tok/s。倒退的输出样本和不递增的时间戳会被忽略。
183
+ 助手生成过程中,页脚显示最近一秒的解码速度,每 500ms 刷新一次。provider 的 `usage.output` 在前进时作为 token 数;如果这个样本不再增长、正文仍在流出,速度改为跟随已流出的文本,而不是停在过期的累计值上。助手消息结束后,指示器切换为本轮平均速度(输出 token 除以第一个输出 token 之后的时间,不含首字等待)。鼠标悬停在指示器上会在状态栏上方打开一块浮动面板,显示平均速度、生成过程中的实时速度、首字吐字时间,以及 provider 实际报告的用量;没有的指标不会编造。之后的助手消息如果只是调用工具或等待输出,完成时的平均速度会保留,直到新回复产生实时速度。嵌套工具里的 LLM 用量不会覆盖已测量的主回复速度;只有还没有任何速度时,嵌套完成才能写入页脚。过短或单 token 突发不显示,避免虚高的 tok/s。倒退的输出样本和不递增的时间戳会被忽略。
184
184
 
185
185
  在获得可测量响应前,速度字段完全不显示,不会出现 `-- tok/s` 占位符。速度位于页脚最右侧;启用上下文百分比时,百分比紧邻其左侧。颜色遵循 Pi 主题语义:至少 30 tok/s 为成功色,10–29.9 tok/s 为警告色,低于 10 tok/s 为错误色。费用是基于当前分支已完成用量和配置的每百万令牌费率得出的估算,并非 provider 账单。窄终端中,页脚会丢弃或截断优先级较低的内容,确保保持单行且不溢出。
186
186
 
@@ -1,6 +1,6 @@
1
1
  import { AGENT_STATUS_ENTRY, savedAgentStatuses, retainAgentStatuses, agentChildren, agentCall, agentStatusesByTurn, attachAgentWidgets, readAgentStatuses } from "../lib/agent-view.ts";
2
2
  import { getAgentDir, SettingsManager, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
3
- import { matchesKey, isKeyRelease, isKeyRepeat } from "@earendil-works/pi-tui";
3
+ import { matchesKey, isKeyRelease, isKeyRepeat, type TuiMouseEvent } from "@earendil-works/pi-tui";
4
4
  import { attachTranscript } from "../lib/transcript-adapter.ts";
5
5
  import { installSeamlessScrollbar } from "../lib/seamless-scrollbar.ts";
6
6
  import { installInputEnhancements, type InputEnhancementsCleanup } from "../lib/input-enhancements.ts";
@@ -8,8 +8,10 @@ import { installTerminalCapabilities } from "../lib/terminal-capabilities.ts";
8
8
  import { linkMessageFiles } from "../lib/file-links.ts";
9
9
  import attachFooterTidy from "../lib/footer-tidy.ts";
10
10
  import attachTitlePlain from "../lib/title-plain.ts";
11
- import { COPY, DEFAULT_SETTINGS, FOOTER_FIELDS, FOOTER_STYLE_OPTIONS, RECOMMENDED_THEMES, SETTING_IDS, isLegacyMinimalSetting, isRecordLimit, loadSettings, parseSettings, saveSettings, settingsItems, settingsPath, type MiniLensSettings, type RecommendedTheme } from "../lib/settings.ts";
12
- import { addUsage, cacheWaste, EMPTY_USAGE, finiteNumber, outputSpeed, sessionUsage, type ActiveGeneration, type UsageLike } from "../lib/usage.ts";
11
+ import { COPY, DEFAULT_SETTINGS, FOOTER_FIELDS, FOOTER_STYLE_OPTIONS, RECOMMENDED_THEMES, SETTING_IDS, isLegacyMinimalSetting, isRecordLimit, isUiLanguage, loadSettings, parseSettings, saveSettings, settingsItems, settingsPath, uiLanguage, type MiniLensSettings, type RecommendedTheme } from "../lib/settings.ts";
12
+ import { attachSpeedHover, speedHit, type SpeedHover } from "../lib/speed-popup.ts";
13
+ import { createTokenSpeedTracker, SPEED_REFRESH_MS } from "../lib/token-speed.ts";
14
+ import { addUsage, cacheWaste, EMPTY_USAGE, finiteNumber, formatSpeed, sessionUsage, type UsageLike } from "../lib/usage.ts";
13
15
  import { statusLine } from "../lib/footer-line.ts";
14
16
  import { contentText, minimalTurnsFromBranch, processText, pushProcess, skillNames, type MinimalTurn } from "../lib/minimal-turns.ts";
15
17
  import { minimalOutputComponent } from "../lib/minimal-output.ts";
@@ -18,6 +20,8 @@ import { createThinkingStream } from "../lib/thinking-stream.ts";
18
20
  // Preserve the existing module entry points for consumers and focused checks.
19
21
  export { SETTINGS_FILE_NAME, DEFAULT_SETTINGS, FOOTER_FIELDS, FOOTER_STYLE_OPTIONS, settingsPath, parseSettings, settingsNeedBackfill, loadSettings, saveSettings, settingsItems, type MiniLensSettings } from "../lib/settings.ts";
20
22
  export { cacheWaste, sessionUsage, speedColor, formatSpeed, outputSpeed, DECODE_SPEED_MIN_ELAPSED_MS, DECODE_SPEED_MIN_OUTPUT, type CacheWaste, type SessionUsage, type SpeedColor } from "../lib/usage.ts";
23
+ export { placeSpeedPopup, SPEED_POPUP_GAP, SPEED_POPUP_WIDTH } from "../lib/speed-popup.ts";
24
+ export { SPEED_REFRESH_MS } from "../lib/token-speed.ts";
21
25
  export { isPlannotatorPlanningStatus, planCapsule, settingsPreviewLine, statusLine } from "../lib/footer-line.ts";
22
26
  export { formatElapsed, formatToolElapsed, formatThinkingElapsed, minimalTurnsFromBranch, type MinimalTurn, type ThinkingClock } from "../lib/minimal-turns.ts";
23
27
  export { minimalOutputComponent } from "../lib/minimal-output.ts";
@@ -71,9 +75,10 @@ export default function (pi: ExtensionAPI) {
71
75
  let activeMinimalTurn: MinimalTurn | undefined;
72
76
  let pendingMinimalFinal = "";
73
77
  const thinkingStream = createThinkingStream();
74
- let speed: number | undefined;
78
+ const speeds = createTokenSpeedTracker();
79
+ let speedHover: SpeedHover | undefined;
80
+ let speedHitBox: { start: number; end: number } | undefined;
75
81
  let mcpCount: number | undefined;
76
- let activeGeneration: ActiveGeneration | undefined;
77
82
  let activeUIPrompt: { kind: string; title?: string } | undefined;
78
83
  const toolStarts = new Map<string, number>();
79
84
  const minimalToolOutputIndices = new Map<string, number>();
@@ -173,7 +178,7 @@ export default function (pi: ExtensionAPI) {
173
178
  cwd: () => ctx.cwd,
174
179
  requestRender: () => tui.requestRender(),
175
180
  write: data => tui.terminal.write(data),
176
- }, () => settings["pi-mini-mode-minimal-record-limit"]);
181
+ }, () => settings["pi-mini-mode-minimal-record-limit"], () => uiLanguage(settings));
177
182
  // Native info notifications use dim; warning/error notifications retain
178
183
  // their position in the transcript. No plugin names or message matching.
179
184
  const dimPrefix = theme.fg("dim", "\u0000").split("\u0000")[0];
@@ -259,14 +264,14 @@ export default function (pi: ExtensionAPI) {
259
264
  speedTimer = undefined;
260
265
  };
261
266
  const refreshStreamingSpeed = () => {
262
- if (!activeGeneration) return;
263
- const nextSpeed = outputSpeed(activeGeneration.output, activeGeneration.firstTokenAt);
264
- if (nextSpeed !== undefined) speed = nextSpeed;
267
+ if (!speeds.refresh(Date.now())) return;
265
268
  refresh();
269
+ speedHover?.relayout();
266
270
  };
267
271
  const startSpeedTimer = () => {
268
272
  stopSpeedTimer();
269
- speedTimer = setInterval(refreshStreamingSpeed, 250);
273
+ speedTimer = setInterval(refreshStreamingSpeed, SPEED_REFRESH_MS);
274
+ speedTimer.unref?.();
270
275
  };
271
276
  const persistSettings = (ctx: ExtensionContext) => {
272
277
  const snapshot = { ...settings };
@@ -342,6 +347,8 @@ export default function (pi: ExtensionAPI) {
342
347
  if (entry !== "hover" && entry !== "inline") throw new TypeError("Invalid preview mode");
343
348
  } else if (key === "pi-mini-mode-minimal-record-limit") {
344
349
  if (!isRecordLimit(entry)) throw new TypeError("Invalid record limit");
350
+ } else if (key === "pi-mini-mode-language") {
351
+ if (!isUiLanguage(entry)) throw new TypeError("Invalid language");
345
352
  } else if (isLegacyMinimalSetting(key) && typeof entry === "boolean") {
346
353
  // Accept stale settings pages; these former child switches no longer gate output.
347
354
  continue;
@@ -440,9 +447,24 @@ export default function (pi: ExtensionAPI) {
440
447
  };
441
448
  syncScrollbar();
442
449
  refreshFooter = () => tui.requestRender();
450
+ speedHover?.dispose();
451
+ speedHover = attachSpeedHover(tui, theme, () => ({
452
+ metrics: settings["pi-mini-mode-speed-show"] ? speeds.metrics() : [],
453
+ hit: speedHitBox,
454
+ }));
455
+ const onBranchChange = footerData?.onBranchChange?.(() => tui.requestRender());
443
456
  return {
444
- dispose: footerData?.onBranchChange?.(() => tui.requestRender()),
457
+ dispose() {
458
+ onBranchChange?.();
459
+ speedHover?.dispose();
460
+ speedHover = undefined;
461
+ },
445
462
  invalidate() {},
463
+ handleMouse(event: TuiMouseEvent) {
464
+ if (event.type === "move" && event.y === 0) speedHover?.hover(event.screenX, event.screenY, true);
465
+ else if (event.type !== "move") speedHover?.hover(event.screenX, event.screenY, false);
466
+ return undefined;
467
+ },
446
468
  render(width: number): string[] {
447
469
  syncScrollbar();
448
470
  // switchTuiMode does not re-run setWidget; remount once the live renderer is fullscreen.
@@ -454,7 +476,13 @@ export default function (pi: ExtensionAPI) {
454
476
  mountMinimalOutput(ctx);
455
477
  });
456
478
  }
457
- return [statusLine(ctx, theme, width, sessionUsage(ctx), settings, speed, undefined, mcpCount, footerData?.getExtensionStatuses?.(), footerData?.getGitBranch?.(), cacheWaste(ctx.sessionManager.getBranch()))];
479
+ const speed = speeds.displayed();
480
+ const line = statusLine(ctx, theme, width, sessionUsage(ctx), settings, speed, undefined, mcpCount, footerData?.getExtensionStatuses?.(), footerData?.getGitBranch?.(), cacheWaste(ctx.sessionManager.getBranch()));
481
+ const speedText = settings["pi-mini-mode-speed-show"] && speed !== undefined
482
+ ? formatSpeed(speed, settings["pi-mini-mode-speed-unit-show"])
483
+ : "";
484
+ speedHitBox = speedHit(line, speedText);
485
+ return [line];
458
486
  },
459
487
  };
460
488
  });
@@ -531,15 +559,17 @@ export default function (pi: ExtensionAPI) {
531
559
  activeMinimalTurn.thinking = undefined;
532
560
  }
533
561
  pendingMinimalFinal = "";
534
- // Keep the last completed speed visible until this response produces tokens.
562
+ // Keep the last completed average visible until this response produces a live sample.
535
563
  // Tool-call-only assistant messages therefore cannot erase a useful rate.
536
- // Decode clock starts on the first output token, not message_start (TTFT).
537
- const sampledAt = Date.now();
538
- activeGeneration = { output: 0, lastSampleAt: sampledAt };
564
+ speeds.onAssistantStart(Date.now());
539
565
  startSpeedTimer();
540
566
  });
541
567
  pi.on("message_update", (event) => {
542
568
  const partial = (event.assistantMessageEvent as { partial?: { usage?: UsageLike; content?: Array<Record<string, unknown>> } }).partial;
569
+ if (speeds.onStream({ at: Date.now(), output: finiteNumber(partial?.usage?.output), content: partial?.content, usage: partial?.usage })) {
570
+ refresh();
571
+ speedHover?.relayout();
572
+ }
543
573
  if (activeMinimalTurn && partial?.content) {
544
574
  if (!thinkingStream.update(activeMinimalTurn, partial.content, event.assistantMessageEvent)) return;
545
575
  if (partial.content.length) activeMinimalTurn.awaitingResponse = false;
@@ -550,36 +580,22 @@ export default function (pi: ExtensionAPI) {
550
580
  activeMinimalTurn.pendingUsage = partial.usage;
551
581
  refreshMinimalOutput();
552
582
  }
553
- const usage = partial?.usage;
554
- const output = finiteNumber(usage?.output);
555
- const timestamp = Date.now();
556
- const hasOutputContent = Array.isArray(partial?.content) && partial.content.length > 0;
557
- if (activeGeneration && timestamp >= activeGeneration.lastSampleAt) {
558
- if (activeGeneration.firstTokenAt === undefined && (hasOutputContent || (output !== undefined && output > 0))) {
559
- activeGeneration.firstTokenAt = timestamp;
560
- }
561
- if (output !== undefined && output >= activeGeneration.output) {
562
- activeGeneration.output = output;
563
- activeGeneration.lastSampleAt = timestamp;
564
- refreshStreamingSpeed();
565
- }
566
- }
567
583
  });
568
584
  pi.on("message_end", (event) => {
569
585
  if (event.message.role === "assistant") {
586
+ speeds.onAssistantEnd(event.message.usage as UsageLike | undefined, Date.now());
587
+ stopSpeedTimer();
588
+ speedHover?.relayout();
570
589
  if (activeMinimalTurn) {
571
590
  const content = Array.isArray(event.message.content) ? event.message.content as unknown as Array<Record<string, unknown>> : [];
572
591
  const outcome = event.message.stopReason === "error" || event.message.stopReason === "aborted" ? event.message.stopReason : "done";
573
- if (!thinkingStream.finish(activeMinimalTurn, content, outcome, event.message.timestamp)) return;
592
+ if (!thinkingStream.finish(activeMinimalTurn, content, outcome, event.message.timestamp)) {
593
+ refresh();
594
+ return;
595
+ }
574
596
  activeMinimalTurn.usage = addUsage(activeMinimalTurn.usage ?? EMPTY_USAGE, event.message.usage as UsageLike | undefined);
575
597
  activeMinimalTurn.pendingUsage = undefined;
576
598
  }
577
- if (activeGeneration) {
578
- const finalSpeed = outputSpeed((event.message.usage as UsageLike | undefined)?.output, activeGeneration.firstTokenAt);
579
- if (finalSpeed !== undefined) speed = finalSpeed;
580
- activeGeneration = undefined;
581
- stopSpeedTimer();
582
- }
583
599
  const content = (event.message as { content?: unknown }).content;
584
600
  if (activeMinimalTurn && Array.isArray(content)) {
585
601
  for (const item of content as Array<Record<string, unknown>>) {
@@ -640,10 +656,7 @@ export default function (pi: ExtensionAPI) {
640
656
  const nestedUsage = (event.result as { usage?: UsageLike } | undefined)?.usage;
641
657
  if (activeMinimalTurn) activeMinimalTurn.usage = addUsage(activeMinimalTurn.usage ?? EMPTY_USAGE, nestedUsage);
642
658
  // Nested tool LLM completions must not overwrite a measured main-turn decode rate.
643
- if (startedAt !== undefined && speed === undefined) {
644
- const nestedSpeed = outputSpeed(nestedUsage?.output, startedAt);
645
- if (nestedSpeed !== undefined) speed = nestedSpeed;
646
- }
659
+ if (startedAt !== undefined) speeds.noteNested(nestedUsage?.output, startedAt, Date.now());
647
660
  const call = activeMinimalTurn?.agentCalls?.find(call => call.id === event.toolCallId);
648
661
  if (call) {
649
662
  if (activeMinimalTurn) activeMinimalTurn.waitingTools = activeMinimalTurn.waitingTools?.filter(tool => tool.id !== event.toolCallId);
@@ -666,6 +679,10 @@ export default function (pi: ExtensionAPI) {
666
679
  refresh();
667
680
  refreshMinimalOutput();
668
681
  });
682
+ pi.on("turn_start", (event) => {
683
+ const startedAt = finiteNumber((event as { timestamp?: unknown }).timestamp) ?? Date.now();
684
+ speeds.onTurnStart(startedAt);
685
+ });
669
686
  pi.on("agent_start", refresh);
670
687
  pi.on("agent_end", refresh);
671
688
  pi.on("agent_settled", () => {
@@ -706,7 +723,9 @@ export default function (pi: ExtensionAPI) {
706
723
  promptView = undefined;
707
724
  unsubscribeMcpStatus();
708
725
  refreshFooter = undefined;
709
- activeGeneration = undefined;
726
+ speeds.reset();
727
+ speedHover?.dispose();
728
+ speedHover = undefined;
710
729
  activeUIPrompt = undefined;
711
730
  toolStarts.clear();
712
731
  minimalToolOutputIndices.clear();
@@ -7,12 +7,18 @@ import { linkToolFiles } from "./file-links.ts";
7
7
  import { diagramMarkdown, isFencedMarkdown, renderMinimalMarkdown } from "./minimal-markdown.ts";
8
8
  import { minimalSurface, paintExpandedHeading } from "./minimal-theme.ts";
9
9
  import { formatElapsed, formatThinkingElapsed, formatToolElapsed, piLoopSummary, type MinimalTurn } from "./minimal-turns.ts";
10
- import { DEFAULT_SETTINGS } from "./settings.ts";
10
+ import { DEFAULT_SETTINGS, uiLanguage, type UiLanguage } from "./settings.ts";
11
11
  import { thinkingPreview } from "./thinking-preview.ts";
12
12
  import type { NoticeRows, TurnNotices } from "./transcript-adapter.ts";
13
13
  import { addUsage, EMPTY_USAGE, formatTokens } from "./usage.ts";
14
14
 
15
- export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], getTurns: () => MinimalTurn[], isExpanded: () => boolean = () => false, showUsage: () => boolean = () => true, subAgentsExpanded: () => boolean = () => false, agentDeadlines = new Map<string, number>(), transformText: (text: string) => string = text => text, imageOptions?: { cwd(): string; requestRender(): void; write?(data: string): void }, getRecordLimit: () => number = () => DEFAULT_SETTINGS["pi-mini-mode-minimal-record-limit"]) {
15
+ /** Shown when a thinking block has no displayable summary. */
16
+ const THINKING_FALLBACK: Record<UiLanguage, Record<"active" | "aborted" | "error" | "ended", string>> = {
17
+ zh: { active: "正在思考,等待可显示摘要", aborted: "思考已中断,未返回可显示摘要", error: "思考失败,未返回可显示摘要", ended: "思考已结束,未返回可显示摘要" },
18
+ en: { active: "Waiting for a displayable summary", aborted: "Interrupted, no displayable summary returned", error: "Failed, no displayable summary returned", ended: "Finished, no displayable summary returned" },
19
+ };
20
+
21
+ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], getTurns: () => MinimalTurn[], isExpanded: () => boolean = () => false, showUsage: () => boolean = () => true, subAgentsExpanded: () => boolean = () => false, agentDeadlines = new Map<string, number>(), transformText: (text: string) => string = text => text, imageOptions?: { cwd(): string; requestRender(): void; write?(data: string): void }, getRecordLimit: () => number = () => DEFAULT_SETTINGS["pi-mini-mode-minimal-record-limit"], getLanguage: () => UiLanguage = () => uiLanguage({})) {
16
22
  const placeholderText = (text: string) => imageOptions ? imagePlaceholders(text, imageOptions.cwd()) : text;
17
23
  const markdown = (text: string, width: number, process = false) => renderMinimalMarkdown(text, width, getMarkdownTheme(), theme.getBgAnsi?.("userMessageBg") ?? "",
18
24
  { color: (value) => theme.fg(process ? "muted" : "text", value) }, (source, available) => transformText(placeholderText(diagramMarkdown(source, available))));
@@ -316,9 +322,10 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
316
322
  const display = reuse ? cached.text : thinkingPreview(entry.detail, available, previewRows, activeThinking);
317
323
  if (!reuse) thinkingPreviews.set(entry.id, { text: display, source: entry.detail, width: available, rows: previewRows, live: activeThinking });
318
324
  const outcome = turn.thinkingOutcomes?.[entry.processIndex];
319
- const fallback = activeThinking ? "正在思考,等待可显示摘要"
320
- : outcome === "aborted" ? "思考已中断,未返回可显示摘要"
321
- : outcome === "error" ? "思考失败,未返回可显示摘要" : "思考已结束,未返回可显示摘要";
325
+ const fallbackCopy = THINKING_FALLBACK[getLanguage()];
326
+ const fallback = activeThinking ? fallbackCopy.active
327
+ : outcome === "aborted" ? fallbackCopy.aborted
328
+ : outcome === "error" ? fallbackCopy.error : fallbackCopy.ended;
322
329
  const color = entry.state === "error" ? "error" : activeThinking ? "accent" : "muted";
323
330
  const rows = available > 0
324
331
  ? renderMinimalMarkdown(display || fallback, available, getMarkdownTheme(), theme.getBgAnsi?.("userMessageBg") ?? "",
package/lib/settings.html CHANGED
@@ -275,7 +275,7 @@ $('copyPrompt').onclick=async()=>{
275
275
  clearTimeout(copyTimer);
276
276
  copyTimer=setTimeout(()=>button.textContent=t('copyPrompt'),1600);
277
277
  };
278
- function setLang(next){lang=next;localStorage.piMiniModeLang=lang;render()}
278
+ function setLang(next){lang=next;localStorage.piMiniModeLang=lang;if(state){state['pi-mini-mode-language']=lang;render();change()}else render()}
279
279
  $('lang-zh').onclick=()=>setLang('zh');
280
280
  $('lang-en').onclick=()=>setLang('en');
281
281
  $('retry').onclick=save;
@@ -283,6 +283,11 @@ function mergeOrder(base,all){const next=[...new Set((base||[]).filter(id=>(all|
283
283
  $('reset').onclick=()=>{if(!confirm(t('confirmReset')))return;state={...data.defaults};order=mergeOrder(data.order,data.order);render();change()};
284
284
  window.addEventListener('beforeunload',event=>{if(dirty||saving){event.preventDefault();event.returnValue=''}});
285
285
  applyLang();status(t('connecting'));
286
- request('GET').then(value=>{data=value;state={...data.settings};order=mergeOrder(state.footerOrder||data.order,data.order);render();$('reset').disabled=false;status('')}).catch(error=>status(error instanceof TypeError?t('reconnect'):error.message||t('reconnect'),true));
286
+ request('GET').then(value=>{data=value;state={...data.settings};order=mergeOrder(state.footerOrder||data.order,data.order);
287
+ // The saved choice drives Pi's transcript copy; a page-only choice from older versions is saved once.
288
+ const saved=state['pi-mini-mode-language'],local=localStorage.piMiniModeLang;
289
+ if(saved==='en'||saved==='zh'){lang=saved;localStorage.piMiniModeLang=lang}
290
+ render();$('reset').disabled=false;status('');
291
+ if(!saved&&(local==='en'||local==='zh')){state['pi-mini-mode-language']=local;change()}}).catch(error=>status(error instanceof TypeError?t('reconnect'):error.message||t('reconnect'),true));
287
292
  </script>
288
293
  </html>
package/lib/settings.ts CHANGED
@@ -28,6 +28,22 @@ export interface MiniLensSettings {
28
28
  "pi-mini-mode-image-preview": "hover" | "inline";
29
29
  onboardingCompleted: boolean;
30
30
  footerOrder?: string[];
31
+ /** Language picked in the settings page; unset follows the system locale. */
32
+ "pi-mini-mode-language"?: UiLanguage;
33
+ }
34
+
35
+ export type UiLanguage = "en" | "zh";
36
+
37
+ export function isUiLanguage(value: unknown): value is UiLanguage {
38
+ return value === "en" || value === "zh";
39
+ }
40
+
41
+ /** The saved choice wins; otherwise a zh* system locale keeps Chinese and everything else is English. */
42
+ export function uiLanguage(settings: Pick<MiniLensSettings, "pi-mini-mode-language">, env: NodeJS.ProcessEnv = process.env): UiLanguage {
43
+ const saved = settings["pi-mini-mode-language"];
44
+ if (saved) return saved;
45
+ const locale = env.LC_ALL || env.LC_MESSAGES || env.LANG || Intl.DateTimeFormat().resolvedOptions().locale;
46
+ return /^zh/i.test(locale) ? "zh" : "en";
31
47
  }
32
48
 
33
49
  export const DEFAULT_SETTINGS: Readonly<MiniLensSettings> = {
@@ -53,7 +69,7 @@ export const DEFAULT_SETTINGS: Readonly<MiniLensSettings> = {
53
69
  onboardingCompleted: false,
54
70
  };
55
71
 
56
- export const SETTING_IDS = Object.keys(DEFAULT_SETTINGS) as Array<Exclude<keyof MiniLensSettings, "footerOrder">>;
72
+ export const SETTING_IDS = Object.keys(DEFAULT_SETTINGS) as Array<Exclude<keyof MiniLensSettings, "footerOrder" | "pi-mini-mode-language">>;
57
73
  export const FOOTER_FIELDS = ["project-branch", "model", "thinking", "branch", "session-tokens", "cache-tokens", "cache-miss", "ch", "cost", "mcp", "context", "context-percent", "speed"] as const;
58
74
  export const FOOTER_STYLE_OPTIONS = ["context-dots", "speed-unit"] as const;
59
75
 
@@ -96,6 +112,7 @@ export function parseSettings(value: unknown): MiniLensSettings {
96
112
  typeof id === "string" && (FOOTER_FIELDS as readonly string[]).includes(id)))];
97
113
  for (const id of FOOTER_FIELDS) if (!settings.footerOrder.includes(id)) settings.footerOrder.push(id);
98
114
  }
115
+ if (isUiLanguage(candidate["pi-mini-mode-language"])) settings["pi-mini-mode-language"] = candidate["pi-mini-mode-language"];
99
116
  if (settings["pi-mini-mode-branch-show"]) settings["pi-mini-mode-project-branch-show"] = false;
100
117
  return settings;
101
118
  }
@@ -140,7 +157,7 @@ export function isLegacyMinimalSetting(id: string): boolean {
140
157
 
141
158
  export function settingsItems(settings: MiniLensSettings): SettingItem[] {
142
159
  const values = ["on", "off"];
143
- const labels: Record<Exclude<keyof MiniLensSettings, "onboardingCompleted" | "footerOrder" | "pi-mini-mode-image-preview" | "pi-mini-mode-minimal-record-limit">, string> = {
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> = {
144
161
  "pi-mini-mode-project-branch-show": "显示项目名称和分支(互斥)",
145
162
  "pi-mini-mode-branch-show": "仅显示分支(思考等级后,互斥)",
146
163
  "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,
@@ -0,0 +1,221 @@
1
+ import type { OverlayOptions } from "@earendil-works/pi-tui";
2
+ import { stripTerminalSequences, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
3
+ import type { SpeedMetric } from "./token-speed.ts";
4
+
5
+ export const SPEED_POPUP_WIDTH = 36;
6
+ /** Blank terminal rows between the popup's bottom border and the status-bar indicator. */
7
+ export const SPEED_POPUP_GAP = 1;
8
+
9
+ type Theme = {
10
+ fg(color: string, text: string): string;
11
+ bg(color: string, text: string): string;
12
+ };
13
+
14
+ export interface SpeedHit {
15
+ start: number;
16
+ end: number;
17
+ }
18
+
19
+ export interface PopupPlace {
20
+ row: number;
21
+ col: number;
22
+ width: number;
23
+ height: number;
24
+ }
25
+
26
+ /** Column span of the speed text. String indexes are converted to terminal columns. */
27
+ export function speedHit(line: string, speedText: string): SpeedHit | undefined {
28
+ if (!speedText) return undefined;
29
+ const plain = stripTerminalSequences(line);
30
+ const index = plain.lastIndexOf(speedText);
31
+ if (index < 0) return undefined;
32
+ const start = visibleWidth(plain.slice(0, index));
33
+ return { start, end: start + visibleWidth(speedText) };
34
+ }
35
+
36
+ /**
37
+ * Pin the popup above the status bar, right edge on the indicator.
38
+ * One blank row stays between the bottom border and the indicator so the
39
+ * speed text is not covered. `pinRight` keeps that edge fixed so later
40
+ * redraws do not follow the pointer.
41
+ */
42
+ export function placeSpeedPopup(input: {
43
+ rows: number;
44
+ columns: number;
45
+ width: number;
46
+ height: number;
47
+ indicatorRow: number;
48
+ indicatorEnd: number;
49
+ pinRight?: number;
50
+ }): PopupPlace {
51
+ const columns = Math.max(1, input.columns);
52
+ const width = Math.max(1, Math.min(input.width, columns));
53
+ const above = Math.max(0, input.indicatorRow);
54
+ const gap = above > SPEED_POPUP_GAP ? SPEED_POPUP_GAP : 0;
55
+ const height = Math.max(1, Math.min(input.height, Math.max(1, above - gap)));
56
+ const right = input.pinRight ?? input.indicatorEnd;
57
+ let col = right - width;
58
+ col = Math.max(0, Math.min(col, columns - width));
59
+ let row = above > 0 ? input.indicatorRow - gap - height : 0;
60
+ if (row < 0) row = 0;
61
+ if (above > 0 && row + height > input.indicatorRow - gap) row = Math.max(0, input.indicatorRow - gap - height);
62
+ return { row, col, width, height };
63
+ }
64
+
65
+ function pad(text: string, width: number): string {
66
+ const gap = width - visibleWidth(text);
67
+ return gap > 0 ? text + " ".repeat(gap) : text;
68
+ }
69
+
70
+ export function renderSpeedPopup(theme: Theme, metrics: readonly SpeedMetric[], width: number): string[] {
71
+ const inner = Math.max(1, width - 2);
72
+ const body = metrics.map((metric) => {
73
+ const label = theme.fg("muted", metric.label);
74
+ const value = theme.fg(metric.color ?? "text", metric.value);
75
+ const gap = inner - visibleWidth(label) - visibleWidth(value);
76
+ const line = gap >= 1 ? `${label}${" ".repeat(gap)}${value}` : `${label} ${value}`;
77
+ return truncateToWidth(line, inner, "…");
78
+ });
79
+ const border = (left: string, fill: string, right: string) => theme.fg("border", `${left}${fill.repeat(inner)}${right}`);
80
+ const row = (text: string) => `${theme.fg("border", "│")}${theme.bg("customMessageBg", pad(text, inner))}${theme.fg("border", "│")}`;
81
+ return [border("╭", "─", "╮"), ...body.map(row), border("╰", "─", "╯")];
82
+ }
83
+
84
+ interface HoverTui {
85
+ terminal?: { rows: number; columns: number; write?: (data: string) => void };
86
+ requestRender?: () => void;
87
+ showOverlay?: (
88
+ component: { render: (width: number) => string[]; invalidate: () => void; handleMouse?: (event: { type: string }) => { handled?: boolean; render?: boolean } | undefined },
89
+ options: OverlayOptions,
90
+ ) => { hide: () => void; getBounds: () => { row: number; col: number; width: number; height: number } | undefined };
91
+ handleViewportInput?: (data: string) => unknown;
92
+ }
93
+
94
+ export interface SpeedHover {
95
+ hover(x: number, y: number, moving: boolean): void;
96
+ relayout(): void;
97
+ dispose(): void;
98
+ }
99
+
100
+ export function attachSpeedHover(
101
+ tui: HoverTui,
102
+ theme: Theme,
103
+ read: () => { metrics: SpeedMetric[]; hit?: SpeedHit },
104
+ ): SpeedHover {
105
+ let open = false;
106
+ let pointer = false;
107
+ let pinRight: number | undefined;
108
+ let placed: PopupPlace | undefined;
109
+ let indicatorRow = Math.max(0, (tui.terminal?.rows ?? 1) - 1);
110
+ const options: OverlayOptions = {
111
+ width: SPEED_POPUP_WIDTH,
112
+ row: 0,
113
+ col: 0,
114
+ nonCapturing: true,
115
+ visible: () => open,
116
+ };
117
+ let handle: { hide: () => void; getBounds: () => { row: number; col: number; width: number; height: number } | undefined } | undefined;
118
+ const component = {
119
+ render(width: number) {
120
+ return renderSpeedPopup(theme, read().metrics, width);
121
+ },
122
+ invalidate() {},
123
+ handleMouse(event: { type: string }) {
124
+ if (event.type === "move") return { handled: true, render: false };
125
+ close();
126
+ return { handled: true, render: true };
127
+ },
128
+ };
129
+
130
+ const setPointer = (next: boolean) => {
131
+ if (pointer === next || !tui.terminal?.write) return;
132
+ pointer = next;
133
+ tui.terminal.write(`\x1b]22;${next ? "pointer" : "default"}\x07`);
134
+ };
135
+
136
+ const layout = () => {
137
+ const metrics = read().metrics;
138
+ const columns = Math.max(1, tui.terminal?.columns ?? SPEED_POPUP_WIDTH);
139
+ const rows = Math.max(1, tui.terminal?.rows ?? indicatorRow + 1);
140
+ indicatorRow = Math.min(indicatorRow, rows - 1);
141
+ const width = Math.min(SPEED_POPUP_WIDTH, columns);
142
+ const height = renderSpeedPopup(theme, metrics, width).length;
143
+ const hit = read().hit;
144
+ const indicatorEnd = hit?.end ?? columns;
145
+ const place = placeSpeedPopup({
146
+ rows, columns, width, height, indicatorRow, indicatorEnd, pinRight,
147
+ });
148
+ if (pinRight === undefined) pinRight = place.col + place.width;
149
+ placed = place;
150
+ options.width = place.width;
151
+ options.row = place.row;
152
+ options.col = place.col;
153
+ options.maxHeight = place.height;
154
+ const gap = indicatorRow > SPEED_POPUP_GAP ? SPEED_POPUP_GAP : 0;
155
+ options.margin = { top: 0, left: 0, right: 0, bottom: Math.max(0, rows - indicatorRow) + gap };
156
+ };
157
+
158
+ const ensure = () => {
159
+ if (handle || !tui.showOverlay) return;
160
+ handle = tui.showOverlay(component, options);
161
+ };
162
+
163
+ const close = () => {
164
+ if (!open && !pointer) return;
165
+ open = false;
166
+ pinRight = undefined;
167
+ placed = undefined;
168
+ setPointer(false);
169
+ tui.requestRender?.();
170
+ };
171
+
172
+ const hover = (x: number, y: number, moving: boolean) => {
173
+ const { metrics, hit } = read();
174
+ const rows = Math.max(1, tui.terminal?.rows ?? y + 1);
175
+ if (y >= 0 && y < rows && hit && y === rows - 1) indicatorRow = y;
176
+ const onIndicator = !!hit && moving && y === indicatorRow && x >= hit.start && x < hit.end;
177
+ const onPopup = !!placed && open && x >= placed.col && x < placed.col + placed.width && y >= placed.row && y < placed.row + placed.height;
178
+ if (!moving || (!onIndicator && !onPopup) || metrics.length === 0) {
179
+ close();
180
+ return;
181
+ }
182
+ const wasOpen = open;
183
+ if (!wasOpen) pinRight = undefined;
184
+ layout();
185
+ open = true;
186
+ ensure();
187
+ setPointer(onIndicator);
188
+ if (!wasOpen) tui.requestRender?.();
189
+ };
190
+
191
+ const previous = tui.handleViewportInput?.bind(tui);
192
+ const wrapped = (data: string) => {
193
+ if (data === "\x1b[O") close();
194
+ const mouse = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(data);
195
+ if (mouse && (Number(mouse[1]) & 64) === 0) {
196
+ const button = Number(mouse[1]);
197
+ const x = Number(mouse[2]) - 1;
198
+ const y = Number(mouse[3]) - 1;
199
+ const moving = (button & 32) !== 0 && mouse[4] === "M";
200
+ hover(x, y, moving);
201
+ }
202
+ return previous?.(data);
203
+ };
204
+ if (previous) tui.handleViewportInput = wrapped;
205
+
206
+ return {
207
+ hover,
208
+ relayout() {
209
+ if (!open) return;
210
+ layout();
211
+ tui.requestRender?.();
212
+ },
213
+ dispose() {
214
+ open = false;
215
+ setPointer(false);
216
+ handle?.hide();
217
+ handle = undefined;
218
+ if (previous && tui.handleViewportInput === wrapped) tui.handleViewportInput = previous;
219
+ },
220
+ };
221
+ }
@@ -0,0 +1,304 @@
1
+ import { finiteNumber, formatSpeed, formatUsd, outputSpeed, speedColor, DECODE_SPEED_MIN_OUTPUT, type SpeedColor, type UsageLike } from "./usage.ts";
2
+
3
+ /** Footer redraw cadence while a turn is streaming. */
4
+ export const SPEED_REFRESH_MS = 500;
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;
7
+
8
+ export interface SpeedMetric {
9
+ label: string;
10
+ value: string;
11
+ color?: SpeedColor | "text" | "muted";
12
+ }
13
+
14
+ interface Sample {
15
+ t: number;
16
+ tokens: number;
17
+ }
18
+
19
+ interface UsageSnapshot {
20
+ input?: number;
21
+ output?: number;
22
+ cacheRead?: number;
23
+ cacheWrite?: number;
24
+ cacheWrite1h?: number;
25
+ reasoning?: number;
26
+ totalTokens?: number;
27
+ cost?: number;
28
+ }
29
+
30
+ function speedKey(value: number | undefined): string {
31
+ return value === undefined ? "" : formatSpeed(value, false);
32
+ }
33
+
34
+ /** ASCII ~4 chars/token; CJK and other non-ASCII ~1 token each. */
35
+ export function estimateTextTokens(text: string): number {
36
+ let ascii = 0;
37
+ let other = 0;
38
+ for (const char of text) {
39
+ const code = char.codePointAt(0) ?? 0;
40
+ if (code <= 0x7f) ascii += 1;
41
+ else other += 1;
42
+ }
43
+ return ascii / 4 + other;
44
+ }
45
+
46
+ export function estimateContentTokens(content: unknown): number {
47
+ if (!Array.isArray(content)) return 0;
48
+ let tokens = 0;
49
+ for (const block of content) {
50
+ if (!block || typeof block !== "object") continue;
51
+ const item = block as Record<string, unknown>;
52
+ if (typeof item.text === "string") tokens += estimateTextTokens(item.text);
53
+ if (typeof item.thinking === "string") tokens += estimateTextTokens(item.thinking);
54
+ if (typeof item.name === "string") tokens += estimateTextTokens(item.name);
55
+ if (typeof item.arguments === "string") tokens += estimateTextTokens(item.arguments);
56
+ else if (item.arguments && typeof item.arguments === "object") tokens += estimateTextTokens(JSON.stringify(item.arguments));
57
+ }
58
+ return tokens;
59
+ }
60
+
61
+ function formatCount(value: number): string {
62
+ return Math.round(value).toLocaleString("en-US");
63
+ }
64
+
65
+ export function formatDuration(ms: number): string {
66
+ if (ms < 1_000) return `${Math.max(0, Math.round(ms))}ms`;
67
+ const seconds = ms / 1_000;
68
+ return `${seconds >= 10 ? seconds.toFixed(1) : seconds.toFixed(2)}s`;
69
+ }
70
+
71
+ function readUsage(usage: UsageLike | undefined, into: UsageSnapshot): void {
72
+ if (!usage) return;
73
+ const extra = usage as UsageLike & { reasoning?: unknown; totalTokens?: unknown; cacheWrite1h?: unknown };
74
+ const take = (key: keyof UsageSnapshot, value: unknown) => {
75
+ const number = finiteNumber(value);
76
+ if (number !== undefined) into[key] = number;
77
+ };
78
+ take("input", usage.input);
79
+ take("output", usage.output);
80
+ take("cacheRead", usage.cacheRead);
81
+ take("cacheWrite", usage.cacheWrite);
82
+ take("cacheWrite1h", extra.cacheWrite1h);
83
+ take("reasoning", extra.reasoning);
84
+ take("totalTokens", extra.totalTokens);
85
+ take("cost", usage.cost?.total);
86
+ }
87
+
88
+ export interface StreamUpdate {
89
+ at: number;
90
+ output?: number;
91
+ content?: unknown;
92
+ usage?: UsageLike;
93
+ }
94
+
95
+ /**
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.
100
+ */
101
+ export function createTokenSpeedTracker() {
102
+ let displayed: number | undefined;
103
+ let lastLive: number | undefined;
104
+ let streaming = false;
105
+ let lastPublish = 0;
106
+ let lastStreamAt = Number.NEGATIVE_INFINITY;
107
+ let lastNow = 0;
108
+ let turnStartedAt: number | undefined;
109
+ let assistantStartedAt: number | undefined;
110
+ let firstTokenAt: number | undefined;
111
+ let segmentEndedAt: number | undefined;
112
+ let providerOutput = 0;
113
+ let streamTokens = 0;
114
+ let samples: Sample[] = [];
115
+ let usage: UsageSnapshot = {};
116
+ let frozen: SpeedMetric[] | undefined;
117
+
118
+ const liveCount = () => Math.max(providerOutput, streamTokens);
119
+
120
+ const pushSample = (at: number, tokens: number) => {
121
+ const last = samples[samples.length - 1];
122
+ if (last && last.t === at) last.tokens = tokens;
123
+ else samples.push({ t: at, tokens });
124
+ const cutoff = at - SPEED_WINDOW_MS * 3;
125
+ if (samples.length > 12) samples = samples.filter((sample) => sample.t >= cutoff);
126
+ };
127
+
128
+ const liveRate = (now: number): number | undefined => {
129
+ if (firstTokenAt === undefined || now - firstTokenAt < SPEED_REFRESH_MS) return undefined;
130
+ const tokens = liveCount();
131
+ const windowMs = Math.min(SPEED_WINDOW_MS, now - firstTokenAt);
132
+ const cut = now - windowMs;
133
+ let baseT = firstTokenAt;
134
+ let baseTokens = 0;
135
+ for (const sample of samples) {
136
+ if (sample.t <= cut) {
137
+ baseT = sample.t;
138
+ baseTokens = sample.tokens;
139
+ } else break;
140
+ }
141
+ const elapsed = now - baseT;
142
+ if (elapsed < SPEED_REFRESH_MS / 2) return undefined;
143
+ const delta = tokens - baseTokens;
144
+ if (delta < 0) return undefined;
145
+ const rate = delta / (elapsed / 1_000);
146
+ return Number.isFinite(rate) ? rate : undefined;
147
+ };
148
+
149
+ const publish = (now: number): boolean => {
150
+ if (!streaming || now - lastPublish < SPEED_REFRESH_MS) return false;
151
+ const rate = liveRate(now);
152
+ if (rate === undefined) return false;
153
+ lastPublish = now;
154
+ lastLive = rate;
155
+ const changed = speedKey(displayed) !== speedKey(rate);
156
+ displayed = rate;
157
+ return changed;
158
+ };
159
+
160
+ const settledCount = () => usage.output !== undefined && usage.output >= DECODE_SPEED_MIN_OUTPUT ? usage.output : liveCount();
161
+
162
+ 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);
166
+ };
167
+
168
+ const collect = (): SpeedMetric[] => {
169
+ const rows: SpeedMetric[] = [];
170
+ const now = lastNow || Date.now();
171
+ 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) });
174
+ const origin = turnStartedAt ?? assistantStartedAt;
175
+ if (firstTokenAt !== undefined && origin !== undefined && firstTokenAt > origin) {
176
+ rows.push({ label: "首字吐字", value: formatDuration(firstTokenAt - origin), color: "text" });
177
+ }
178
+ 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" });
181
+ }
182
+ 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"],
190
+ ];
191
+ for (const [key, label] of counts) {
192
+ const value = usage[key];
193
+ if (value === undefined || value <= 0) continue;
194
+ rows.push({ label, value: formatCount(value), color: "text" });
195
+ }
196
+ if (usage.output === undefined && !streaming && liveCount() >= DECODE_SPEED_MIN_OUTPUT) {
197
+ rows.push({ label: "输出 token", value: formatCount(liveCount()), color: "text" });
198
+ }
199
+ if (usage.cost !== undefined && usage.cost > 0) rows.push({ label: "费用", value: formatUsd(usage.cost), color: "muted" });
200
+ if (rows.length === 0 && displayed !== undefined) {
201
+ rows.push({ label: "平均速度", value: formatSpeed(displayed, true), color: speedColor(displayed) });
202
+ }
203
+ return rows;
204
+ };
205
+
206
+ return {
207
+ onTurnStart(at: number) {
208
+ lastNow = at;
209
+ turnStartedAt = at;
210
+ },
211
+ onAssistantStart(at: number) {
212
+ lastNow = at;
213
+ streaming = true;
214
+ lastPublish = at;
215
+ lastStreamAt = Number.NEGATIVE_INFINITY;
216
+ assistantStartedAt = at;
217
+ firstTokenAt = undefined;
218
+ segmentEndedAt = undefined;
219
+ providerOutput = 0;
220
+ streamTokens = 0;
221
+ samples = [];
222
+ usage = {};
223
+ lastLive = undefined;
224
+ },
225
+ onStream(update: StreamUpdate): boolean {
226
+ 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);
230
+ // Regressing or repeated samples must not move the clock. The 500ms timer
231
+ // still decays the live rate when tokens actually stop arriving.
232
+ if (nextTokens <= liveCount() && liveCount() > 0) return false;
233
+ lastStreamAt = update.at;
234
+ lastNow = update.at;
235
+ providerOutput = nextProvider;
236
+ streamTokens = nextStream;
237
+ readUsage(update.usage, usage);
238
+ if (nextTokens > 0) {
239
+ if (firstTokenAt === undefined) firstTokenAt = update.at;
240
+ pushSample(update.at, nextTokens);
241
+ }
242
+ return publish(update.at);
243
+ },
244
+ refresh(at: number): boolean {
245
+ lastNow = at;
246
+ if (streaming && firstTokenAt !== undefined) pushSample(at, liveCount());
247
+ return publish(at);
248
+ },
249
+ onAssistantEnd(finalUsage: UsageLike | undefined, at: number): boolean {
250
+ if (at >= lastStreamAt) lastStreamAt = at;
251
+ lastNow = at;
252
+ streaming = false;
253
+ segmentEndedAt = at;
254
+ readUsage(finalUsage, usage);
255
+ const reported = finiteNumber(finalUsage?.output);
256
+ if (reported !== undefined && reported >= providerOutput) providerOutput = reported;
257
+ if (usage.output === undefined && providerOutput > 0) usage.output = providerOutput;
258
+ const count = reported !== undefined && reported >= DECODE_SPEED_MIN_OUTPUT
259
+ ? reported
260
+ : liveCount();
261
+ if (count > 0 && firstTokenAt === undefined) firstTokenAt = assistantStartedAt ?? at;
262
+ const average = outputSpeed(count, firstTokenAt, at);
263
+ lastLive = undefined;
264
+ if (average !== undefined) displayed = average;
265
+ frozen = collect();
266
+ return average !== undefined;
267
+ },
268
+ noteNested(output: unknown, startedAt: number, endedAt: number): boolean {
269
+ if (displayed !== undefined) return false;
270
+ const rate = outputSpeed(output, startedAt, endedAt);
271
+ if (rate === undefined) return false;
272
+ displayed = rate;
273
+ lastNow = endedAt;
274
+ return true;
275
+ },
276
+ displayed(): number | undefined {
277
+ return displayed;
278
+ },
279
+ streaming(): boolean {
280
+ return streaming;
281
+ },
282
+ metrics(): SpeedMetric[] {
283
+ if (streaming && lastLive === undefined && frozen?.length) return frozen;
284
+ return collect();
285
+ },
286
+ reset() {
287
+ displayed = undefined;
288
+ lastLive = undefined;
289
+ streaming = false;
290
+ lastPublish = 0;
291
+ lastStreamAt = Number.NEGATIVE_INFINITY;
292
+ lastNow = 0;
293
+ turnStartedAt = undefined;
294
+ assistantStartedAt = undefined;
295
+ firstTokenAt = undefined;
296
+ segmentEndedAt = undefined;
297
+ providerOutput = 0;
298
+ streamTokens = 0;
299
+ samples = [];
300
+ usage = {};
301
+ frozen = undefined;
302
+ },
303
+ };
304
+ }
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@each1024/pi-mini-mode",
3
- "version": "2.0.14",
3
+ "version": "2.0.16",
4
4
  "description": "A compact Pi footer with live usage metrics, theme-aware settings previews, and configurable progress bars.",
5
5
  "type": "module",
6
6
  "scripts": {
7
- "check": "tsc --noEmit -p tsconfig.json",
7
+ "check": "node scripts/typecheck.mjs --noEmit -p tsconfig.json",
8
8
  "test": "node scripts/check-focused.mjs",
9
9
  "check:focused": "node scripts/check-focused.mjs",
10
10
  "check:syntax": "node scripts/check-syntax.mjs",
@@ -57,6 +57,7 @@
57
57
  "@earendil-works/pi-server": "0.85.0",
58
58
  "@earendil-works/pi-tui": "^0.85.0",
59
59
  "@types/node": "^26.4.1",
60
+ "tsrs": "0.18.0-ts7.1.0-dev.20260929",
60
61
  "typescript": "^5.9.3"
61
62
  },
62
63
  "dependencies": {