@each1024/pi-mini-mode 0.9.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,6 +10,16 @@
10
10
 
11
11
  An everyday refinement for [Pi](https://pi.dev), not just a footer. Preview images at the cursor, fold long messages and process details, inspect subagent work, and keep your session’s essential signals in view.
12
12
 
13
+
14
+
15
+
16
+
17
+ https://github.com/user-attachments/assets/cd972993-a6f9-4399-81a6-6e0d540dec9a
18
+
19
+
20
+
21
+
22
+
13
23
  ## Install
14
24
 
15
25
  ```bash
@@ -43,15 +53,15 @@ Paste images with `Ctrl+V` (`Alt+V` on Windows/WSL). Disabling input enhancement
43
53
 
44
54
  ### 02 / Process, quieter
45
55
 
46
- Enable **Minimal output** in settings, or run `/pi-mini-mode-minimal on`.
56
+ Enable **Minimal output** in `/pi-mini-mode-settings`.
47
57
 
48
- - **Long prompts, folded.** In fullscreen minimal mode, long user messages show the first four rendered rows. Click the fold control to reveal the rest, or select a message with `/pi-mini-mode-prompts`. Complete fenced code blocks stay intact.
58
+ - **Long prompts, folded.** In fullscreen minimal mode, long user messages show the first four rendered rows. Click the fold control to reveal the rest. Complete fenced code blocks stay intact.
49
59
  - **Subagents, in plain sight.** Click a subagent row to expand its available activity and message/final output. A dispatch receipt or returned tool call is not a completed background task.
50
- - **A process tree, not a wall of output.** Thinking, tools and skill reads share one chronological tree. The latest ten summaries stay visible; `Ctrl+O` expands or collapses the full process. New questions start collapsed.
51
- - **Tool details on demand.** Expand a tool/thinking entry using its fold control or `/pi-mini-mode-tools`. Tool details show saved text, not the original custom renderer or image output.
60
+ - **A process tree, not a wall of output.** Thinking, tools and skill reads share one chronological tree. The latest summaries stay visible, including the latest thinking; `Ctrl+O` expands or collapses the full process. New questions start collapsed.
61
+ - **Tool details on demand.** Expand a tool or thinking entry, including the latest thinking, using its fold control. Thinking starts collapsed and only expands or collapses manually, including while running. Tool details show saved text, not the original custom renderer or image output.
52
62
  - **Room for the answer.** Final Markdown streams without extra headings or backgrounds. Failures and interruptions stay explicit. Folding changes presentation, not stored session messages.
53
63
 
54
- `/pi-mini-mode-history` opens complete process entries, five at a time. `/pi-mini-mode-minimal off` restores native Pi history.
64
+ Turn **Minimal output** off in settings to restore native Pi history.
55
65
 
56
66
  ### 03 / Session, in focus
57
67
 
@@ -75,16 +85,11 @@ This earlier screenshot and recording show footer configuration, not the newer i
75
85
  | Command / shortcut | Purpose |
76
86
  | --- | --- |
77
87
  | `/pi-mini-mode-settings` | Configure fields, input enhancements and minimal output |
78
- | `/pi-mini-mode-setup` | Show the first-run setup prompt again |
79
- | `/pi-mini-mode-minimal on` / `off` | Enable minimal output / restore native history |
80
88
  | `Ctrl+O` | Expand or collapse the complete process tree |
81
89
  | `Ctrl+S` | Expand or collapse completed subagent rows; yields to Pi `/model`, `/thinking`, and other selectors |
82
- | `/pi-mini-mode-prompts` | Select and expand/collapse a user message¹ |
83
- | `/pi-mini-mode-tools` | Select and expand/collapse saved tool text or thinking¹ |
84
- | `/pi-mini-mode-history` | Browse full process entries, five at a time |
85
90
  | `/reload` | Reload the extension after installation or source changes |
86
91
 
87
- ¹ Requires fullscreen minimal output. Subagent rows have their own click-to-expand control; supported third-party widgets retain native detail shortcuts.
92
+ Subagent rows have their own click-to-expand control; supported third-party widgets retain native detail shortcuts.
88
93
 
89
94
  ## Compatibility
90
95
 
@@ -105,7 +110,7 @@ On the first interactive TUI session, Pi Mini Mode shows a preview. Almost every
105
110
  deepseek-v4-flash high Total 45K Cached 25K CH 40.0% $0.012 ◇ MCP 3 500/1.0M ⣿⣀⣀⣀⣀⣀⣀⣀⣀⣀ 1% 120 tok/s
106
111
  ```
107
112
 
108
- The first-run picker offers **Keep defaults**, **Configure now**, and **Apply recommended setup**. Keeping defaults saves the default field selection, leaves minimal output on, and prevents the prompt from appearing again; configuring opens the same settings list immediately. Applying the recommendation asks you to choose the bundled `cc-dark` or `cc-light` theme, saves that theme and global `tuiMode=fullscreen` through Pi's settings API, applies the theme immediately, and asks you to restart Pi because the fullscreen renderer is chosen at startup. Project settings and CLI flags may override these global values. Escape/cancel leaves onboarding incomplete; retry with `/pi-mini-mode-setup`. Print, JSON, and other non-interactive modes never prompt.
113
+ The first-run picker offers **Keep defaults**, **Configure now**, and **Apply recommended setup**. Keeping defaults saves the default field selection, leaves minimal output on, and prevents the prompt from appearing again; configuring opens the same settings list immediately. Applying the recommendation asks you to choose the bundled `cc-dark` or `cc-light` theme, saves that theme and global `tuiMode=fullscreen` through Pi's settings API, applies the theme immediately, and asks you to restart Pi because the fullscreen renderer is chosen at startup. Project settings and CLI flags may override these global values. Escape/cancel leaves onboarding incomplete; it runs again on the next interactive session. Print, JSON, and other non-interactive modes never prompt.
109
114
 
110
115
  Open that settings UI any time with:
111
116
 
@@ -196,9 +201,9 @@ For a real terminal smoke test, run `python3 test/minimal-pty.py`. It needs Pyth
196
201
  <details>
197
202
  <summary><strong>Publishing</strong></summary>
198
203
 
199
- Pushes to `main` automatically publish to npm after `npm ci`, `npm run check`, and `npm test`; the workflow also supports manual dispatch on `main`. Each release uses the higher of the local version baseline and npm's latest stable version plus one patch. Versions change only in the runner, with no version commits or tags; raise the baseline in `package.json` and the lockfile for a major/minor release. Already-published commits are skipped. Actions concurrency can replace pending pushes, so not every push (or every commit within a push) is guaranteed a separate package release.
204
+ Normal releases are published from this machine with the npm token in `.npmrc` (`npm publish --access public`). `publish.yml` is only a manual backup (`workflow_dispatch` on `main`): it runs `npm ci`, `npm run check`, and `npm test`, then `scripts/publish.mjs`. That script publishes the higher of the local version baseline and npm's latest stable version plus one patch, changes the version only in the runner (no version commit or tag), and skips commits that are already published. Raise the baseline in `package.json` and the lockfile for a major or minor release.
200
205
 
201
- Releases require the package’s npm Trusted Publisher to be configured for this GitHub repository and `publish.yml`. Subsequent publishing uses OIDC and provenance without an npm token.
206
+ The backup workflow needs the package’s npm Trusted Publisher configured for this GitHub repository and `publish.yml`. It uses OIDC and provenance and does not use an npm token.
202
207
 
203
208
  </details>
204
209
 
package/README.zh-CN.md CHANGED
@@ -51,15 +51,15 @@ pi install git:github.com/eachann1024/pi-mini-mode
51
51
 
52
52
  ### 02 / 过程,更安静
53
53
 
54
- 在设置中开启 **极简输出**,或运行 `/pi-mini-mode-minimal on`。
54
+ 在 `/pi-mini-mode-settings` 中开启 **极简输出**。
55
55
 
56
- - **长消息,自动折叠。** 全屏极简模式下,长用户消息默认保留前四个显示行。点击折叠控件展开全文,或用 `/pi-mini-mode-prompts` 选择消息。完整代码围栏保持完整。
56
+ - **长消息,自动折叠。** 全屏极简模式下,长用户消息默认保留前四个显示行。点击折叠控件展开全文。完整代码围栏保持完整。
57
57
  - **子代理,清晰可查。** 点击子代理行,展开可用的活动记录与消息/最终输出。任务派发回执或工具调用返回,不等于后台任务已完成。
58
- - **过程是一棵树,而非满屏输出。** 思考、工具与技能读取汇入同一棵时间顺序树,显示最新十条摘要;`Ctrl+O` 展开/收起完整过程,新问题默认收起。
59
- - **工具详情,按需展开。** 点击工具/思考条目的折叠控件,或用 `/pi-mini-mode-tools` 选择。工具详情展示保存的文本,不还原原生自定义渲染器或图片输出。
58
+ - **过程是一棵树,而非满屏输出。** 思考、工具与技能读取汇入同一棵时间顺序树,显示最新摘要,包括最新一条思考;`Ctrl+O` 展开/收起完整过程,新问题默认收起。
59
+ - **工具详情,按需展开。** 点击工具或思考条目的折叠控件,最新一条思考也可以展开。思考默认收起,进行中与结束后均只由手动操作展开或收起。工具详情展示保存的文本,不还原原生自定义渲染器或图片输出。
60
60
  - **把空间留给答案。** 最终 Markdown 流式呈现,不添加额外标题或背景。失败和中断明确标记;折叠只改变显示,不删除原始会话消息。
61
61
 
62
- `/pi-mini-mode-history` 每次浏览五条完整过程记录;`/pi-mini-mode-minimal off` 恢复 Pi 原生历史。
62
+ 在设置中关闭 **极简输出** 即恢复 Pi 原生历史。
63
63
 
64
64
  ### 03 / 状态,更清晰
65
65
 
@@ -83,16 +83,11 @@ pi install git:github.com/eachann1024/pi-mini-mode
83
83
  | 命令/快捷键 | 用途 |
84
84
  | --- | --- |
85
85
  | `/pi-mini-mode-settings` | 配置字段、输入增强和极简输出 |
86
- | `/pi-mini-mode-setup` | 再次显示首次设置提示 |
87
- | `/pi-mini-mode-minimal on` / `off` | 开启极简输出/恢复原生历史 |
88
86
  | `Ctrl+O` | 展开/收起完整过程树 |
89
87
  | `Ctrl+S` | 展开/收起已完成的子代理行;打开 `/model`、`/thinking` 等选择器时交给 Pi |
90
- | `/pi-mini-mode-prompts` | 选择并展开/收起用户消息¹ |
91
- | `/pi-mini-mode-tools` | 选择并展开/收起保存的工具文本或思考¹ |
92
- | `/pi-mini-mode-history` | 浏览完整过程记录,每次五条 |
93
88
  | `/reload` | 安装或修改源码后重载扩展 |
94
89
 
95
- ¹ 需要全屏极简输出。子代理行有独立的点击展开控件;受支持的第三方小组件保留原生详情快捷键。
90
+ 子代理行有独立的点击展开控件;受支持的第三方小组件保留原生详情快捷键。
96
91
 
97
92
  ## 兼容性
98
93
 
@@ -113,7 +108,7 @@ pi install git:github.com/eachann1024/pi-mini-mode
113
108
  deepseek-v4-flash high Total 45K Cached 25K CH 40.0% $0.012 ◇ MCP 3 500/1.0M ⣿⣀⣀⣀⣀⣀⣀⣀⣀⣀ 1% 120 tok/s
114
109
  ```
115
110
 
116
- 首次设置会提供 **Keep defaults(保留默认值)**、**Configure now(立即配置)** 和 **Apply recommended setup(应用推荐配置)**。保留默认值会保存默认字段选择、保持极简输出开启,并且不再显示首次设置提示;立即配置会直接打开同一设置列表。应用推荐配置会让你选择内置的 `cc-dark` 或 `cc-light` 主题,通过 Pi 官方设置 API 保存该主题和全局 `tuiMode=fullscreen`,立即应用主题,并提示重启 Pi(全屏渲染器在启动时决定)。项目设置和命令行参数可能覆盖全局设置。按 Esc/取消不会完成首次设置,可稍后用 `/pi-mini-mode-setup` 重试。Print、JSON 等非交互模式不会显示提示。
111
+ 首次设置会提供 **Keep defaults(保留默认值)**、**Configure now(立即配置)** 和 **Apply recommended setup(应用推荐配置)**。保留默认值会保存默认字段选择、保持极简输出开启,并且不再显示首次设置提示;立即配置会直接打开同一设置列表。应用推荐配置会让你选择内置的 `cc-dark` 或 `cc-light` 主题,通过 Pi 官方设置 API 保存该主题和全局 `tuiMode=fullscreen`,立即应用主题,并提示重启 Pi(全屏渲染器在启动时决定)。项目设置和命令行参数可能覆盖全局设置。按 Esc/取消不会完成首次设置,下次交互式会话会再次提示。Print、JSON 等非交互模式不会显示提示。
117
112
 
118
113
  设置保存在 Pi 的 agent 目录中,通常是 `~/.pi/agent/pi-mini-mode.json`;如果 Pi 使用其他配置目录,则保存在对应目录。文件缺失或格式错误时会安全回退到默认设置。设置示例:
119
114
 
@@ -197,12 +192,9 @@ python3 test/minimal-pty.py
197
192
  <details>
198
193
  <summary><strong>发布</strong></summary>
199
194
 
200
- 推送到 `main` 后,GitHub Actions 会在通过 `npm ci`、`npm run check` 和 `npm test` 后自动发布到 npm;也支持在 `main` 上手动触发。每次发布都会取本地版本基线与 npm 最新稳定版本加一个 patch 中的较高者。版本只在 runner 中变更,不创建版本提交或 tag;发布 major/minor 版本时,应同时提高 `package.json` 和 lockfile 中的基线。已经发布过的提交会跳过。Actions 并发策略可能替换等待中的推送,因此不是每次推送或一次推送中的每个提交都保证生成独立版本。
195
+ 日常发布在本机完成,使用 `.npmrc` 中的 npm token(`npm publish --access public`)。`publish.yml` 只作为手动备份(在 `main` 上 `workflow_dispatch`):先执行 `npm ci`、`npm run check` 和 `npm test`,再运行 `scripts/publish.mjs`。该脚本发布本地版本基线与 npm 最新稳定版本再加一个 patch 中的较高者,版本只在 runner 中变更(不创建版本提交或 tag),并跳过已经发布过的提交。发布 major 或 minor 时,同时提高 `package.json` 和 lockfile 中的基线。
201
196
 
202
- 后续发布使用 npm Trusted Publisher、OIDC 和 provenance,无需 npm token。
203
-
204
-
205
- 发布前需为该包配置指向此 GitHub 仓库及 `publish.yml` 的 npm Trusted Publisher。
197
+ 备份流程需要为该包配置指向此 GitHub 仓库及 `publish.yml` 的 npm Trusted Publisher。它使用 OIDC 和 provenance,不使用 npm token。
206
198
 
207
199
  </details>
208
200
 
@@ -23,6 +23,7 @@ export interface MiniLensSettings {
23
23
  "pi-mini-mode-ch-show": boolean;
24
24
  "pi-mini-mode-session-tokens-show": boolean;
25
25
  "pi-mini-mode-cache-tokens-show": boolean;
26
+ "pi-mini-mode-cache-miss-show": boolean;
26
27
  "pi-mini-mode-cost-show": boolean;
27
28
  "pi-mini-mode-mcp-show": boolean;
28
29
  "pi-mini-mode-context-show": boolean;
@@ -49,9 +50,10 @@ export const DEFAULT_SETTINGS: Readonly<MiniLensSettings> = {
49
50
  "pi-mini-mode-branch-show": false,
50
51
  "pi-mini-mode-ch-show": true,
51
52
  "pi-mini-mode-session-tokens-show": true,
52
- "pi-mini-mode-cache-tokens-show": true,
53
+ "pi-mini-mode-cache-tokens-show": false,
54
+ "pi-mini-mode-cache-miss-show": true,
53
55
  "pi-mini-mode-cost-show": true,
54
- "pi-mini-mode-mcp-show": true,
56
+ "pi-mini-mode-mcp-show": false,
55
57
  "pi-mini-mode-context-show": true,
56
58
  "pi-mini-mode-context-dots-show": true,
57
59
  "pi-mini-mode-context-percent-show": true,
@@ -69,16 +71,16 @@ export const DEFAULT_SETTINGS: Readonly<MiniLensSettings> = {
69
71
  };
70
72
 
71
73
  const SETTING_IDS = Object.keys(DEFAULT_SETTINGS) as Array<Exclude<keyof MiniLensSettings, "footerOrder">>;
72
- export const FOOTER_FIELDS = ["project-branch", "model", "thinking", "branch", "session-tokens", "cache-tokens", "ch", "cost", "mcp", "context", "context-percent", "speed"] as const;
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;
73
75
  export const FOOTER_STYLE_OPTIONS = ["context-dots", "speed-unit"] as const;
74
76
 
75
77
  const COPY = {
76
78
  title: "Pi Mini Mode 设置", preview: "预览(示例数据)", lens: "设置", minimal: "极简输出",
77
- model: "显示模型", thinking: "显示思考等级", total: "显示会话总 token", cached: "显示会话缓存 token", totalLabel: "Total", cachedLabel: "Cached", cacheHitLabel: "CH", cacheHit: "显示缓存命中率 (CH)", price: "显示会话价格", mcp: "显示已启用 MCP 服务器", context: "显示上下文 token 与进度条", dots: "↳ 使用点阵进度条", percent: "显示上下文百分比", speed: "显示最近生成速度", speedUnit: "↳ 显示 tok/s 单位", inputEnhancements: "输入增强", showThinking: "显示思考", tools: "显示工具调用", output: "显示过程输出", skills: "显示技能", agentUsage: "显示 Agent token 用量", shortcut: "新 Agent 显示 Ctrl+O 提示(6 秒)",
79
+ model: "显示模型", thinking: "显示思考等级", total: "显示会话总 token", cached: "显示会话缓存 token", miss: "显示缓存 miss", totalLabel: "Total", cachedLabel: "Cached", cacheHitLabel: "CH", cacheHit: "显示缓存命中率 (CH)", price: "显示会话价格", mcp: "显示已启用 MCP 服务器", context: "显示上下文 token 与进度条", dots: "↳ 使用点阵进度条", percent: "显示上下文百分比", speed: "显示最近生成速度", speedUnit: "↳ 显示 tok/s 单位", inputEnhancements: "输入增强", showThinking: "显示思考", tools: "显示工具调用", output: "显示过程输出", skills: "显示技能", agentUsage: "显示 Agent token 用量", shortcut: "新 Agent 显示 Ctrl+O 提示(6 秒)",
78
80
  totalDescription: "Total:当前会话分支上的全部 token,含工具上报的 LLM 用量。", cachedDescription: "Cached:累计 cache-read + cache-write token(包含在 Total 中)。", cacheHitDescription: "CH(cache hit):cache-read / (input + cache-read)。Cache write 不计入此比率。",
79
81
  enableMinimalDescription: "开启统一折叠思考、工具和技能过程;关闭恢复 Pi 默认会话历史。",
80
82
  inputEnhancementsDescription: "原生 Ctrl+V 粘贴图片(Windows/WSL:Alt+V);图片显示为 [image1] 标签,光标移入或全屏悬停可预览。空白后 / 选择技能并在光标处插入。Cmd+点击带下划线的图片标签或消息文件路径,用系统默认应用打开;预览及点击需终端支持。关闭仅恢复原生行为。",
81
- tuiRequired: "/pi-mini-mode-settings 需要 TUI 模式", saveFailed: "无法保存 Pi Mini Mode 设置", minimalRequired: "/pi-mini-mode-minimal 需要 TUI 模式", minimalUsage: "用法:/pi-mini-mode-minimal [on|off]", minimalState: "Pi Mini Mode 极简输出:", onboarding: "几乎全部功能默认开启;仅「仅显示分支」默认关,与「项目与分支」互斥。可用 /pi-mini-mode-settings 再改。", keepDefaults: "保留默认", configureNow: "立即配置", applyRecommended: "应用推荐配置", chooseTheme: "选择 Pi Mini Mode 主题(将保存全局主题和全屏模式;重启后生效)", themeSaved: "已保存推荐主题和全屏模式。请重启 Pi;项目设置或命令行参数可能覆盖全局设置。", themeSaveFailed: "无法保存推荐的 Pi 主题和全屏模式;未完成首次配置。", themeApplyFailed: "推荐设置已保存,但当前主题未能立即应用;请重启 Pi。",
83
+ tuiRequired: "/pi-mini-mode-settings 需要 TUI 模式", saveFailed: "无法保存 Pi Mini Mode 设置", minimalRequired: "/pi-mini-mode-minimal 需要 TUI 模式", minimalUsage: "用法:/pi-mini-mode-minimal [on|off]", minimalState: "Pi Mini Mode 极简输出:", onboarding: "多数功能默认开启;「仅显示分支」「缓存 token」「MCP」默认关,「仅显示分支」与「项目与分支」互斥。可用 /pi-mini-mode-settings 再改。", keepDefaults: "保留默认", configureNow: "立即配置", applyRecommended: "应用推荐配置", chooseTheme: "选择 Pi Mini Mode 主题(将保存全局主题和全屏模式;重启后生效)", themeSaved: "已保存推荐主题和全屏模式。请重启 Pi;项目设置或命令行参数可能覆盖全局设置。", themeSaveFailed: "无法保存推荐的 Pi 主题和全屏模式;未完成首次配置。", themeApplyFailed: "推荐设置已保存,但当前主题未能立即应用;请重启 Pi。",
82
84
  } as const;
83
85
 
84
86
  const RECOMMENDED_THEMES = ["cc-dark", "cc-light"] as const;
@@ -217,6 +219,33 @@ function addUsage(total: SessionUsage, usage: UsageLike | undefined): SessionUsa
217
219
  };
218
220
  }
219
221
 
222
+ export interface CacheWaste {
223
+ missedTokens: number;
224
+ missCount: number;
225
+ }
226
+
227
+ /** Same noise floor as Pi's cache-miss notice. Compaction resets the baseline. */
228
+ export function cacheWaste(entries: ReadonlyArray<{ type?: unknown; message?: { role?: unknown; usage?: UsageLike } }>): CacheWaste {
229
+ let prev = 0;
230
+ let reported = false;
231
+ const totals = { missedTokens: 0, missCount: 0 };
232
+ for (const entry of entries) {
233
+ if (entry.type === "compaction" || entry.type === "branch_summary") { prev = 0; continue; }
234
+ if (entry.type !== "message" || entry.message?.role !== "assistant") continue;
235
+ const usage = entry.message.usage;
236
+ const input = nonNegative(usage?.input);
237
+ const cacheRead = nonNegative(usage?.cacheRead);
238
+ const cacheWrite = nonNegative(usage?.cacheWrite);
239
+ const prompt = input + cacheRead + cacheWrite;
240
+ if (prev > 0 && prompt > 0 && (cacheRead + cacheWrite > 0 || reported)) {
241
+ const missed = Math.min(prev, prompt) - cacheRead;
242
+ if (missed > 1024) { totals.missedTokens += missed; totals.missCount++; }
243
+ }
244
+ if (prompt > 0) { prev = prompt; reported ||= cacheRead + cacheWrite > 0; }
245
+ }
246
+ return totals;
247
+ }
248
+
220
249
  /** Aggregate persisted, finalized usage once per active-branch entry. */
221
250
  export function sessionUsage(ctx: ExtensionContext): SessionUsage {
222
251
  return ctx.sessionManager.getBranch().reduce((total, entry) => {
@@ -337,6 +366,7 @@ export function statusLine(
337
366
  mcpCount?: number,
338
367
  statuses?: ReadonlyMap<string, string>,
339
368
  gitBranch?: string | null,
369
+ waste?: CacheWaste,
340
370
  ): string {
341
371
  if (highlighted === "pi-mini-mode-context-dots-show") highlighted = "pi-mini-mode-context-show";
342
372
  const field = (id: keyof MiniLensSettings, color: Parameters<typeof theme.fg>[0], text: string) =>
@@ -347,6 +377,7 @@ export function statusLine(
347
377
  const hit = cacheHit(usageTotals);
348
378
  const hitText = hit === undefined ? "" : `${COPY.cacheHitLabel} ${hit.toFixed(1)}%`;
349
379
  const cachedTokens = usageTotals.cacheRead + usageTotals.cacheWrite;
380
+ const missText = settings["pi-mini-mode-cache-miss-show"] && waste && waste.missCount > 0 ? `Miss ${formatTokens(waste.missedTokens)}` : "";
350
381
  const price = usageTotals.cost > 0 ? formatUsd(usageTotals.cost) : "";
351
382
  const contextUsage = ctx.getContextUsage();
352
383
  const tokens = finiteNumber(contextUsage?.tokens);
@@ -369,6 +400,7 @@ export function statusLine(
369
400
  model, thinking,
370
401
  "session-tokens": usageTotals.totalTokens > 0 ? `${COPY.totalLabel} ${formatTokens(usageTotals.totalTokens)}` : "",
371
402
  "cache-tokens": cachedTokens > 0 ? `${COPY.cachedLabel} ${formatTokens(cachedTokens)}` : "",
403
+ "cache-miss": missText,
372
404
  ch: hitText, cost: price, mcp: mcpText,
373
405
  context: tokenText,
374
406
  "context-percent": percentText, speed: speed === undefined ? "" : formatSpeed(speed, settings["pi-mini-mode-speed-unit-show"]),
@@ -381,7 +413,7 @@ export function statusLine(
381
413
  }
382
414
  return truncateToWidth([planTag, ...settings.footerOrder.map(id => {
383
415
  const key = `pi-mini-mode-${id}-show` as keyof MiniLensSettings;
384
- const color = id === "speed" ? speedColor(speed) : id === "model" || id === "context-percent" ? "accent" : "muted";
416
+ const color = id === "speed" ? speedColor(speed) : id === "cache-miss" ? "warning" : id === "model" || id === "context-percent" ? "accent" : "muted";
385
417
  return settings[key] && values[id] ? field(key, color, values[id]) : "";
386
418
  })].filter(Boolean).join(" "), width, "…");
387
419
  }
@@ -402,6 +434,7 @@ export function statusLine(
402
434
  branchOnly && branchText && field(branchSetting, "muted", branchText),
403
435
  settings["pi-mini-mode-session-tokens-show"] && usageTotals.totalTokens > 0 && field("pi-mini-mode-session-tokens-show", "text", `${COPY.totalLabel} ${formatTokens(usageTotals.totalTokens)}`),
404
436
  settings["pi-mini-mode-cache-tokens-show"] && cachedTokens > 0 && field("pi-mini-mode-cache-tokens-show", "text", `${COPY.cachedLabel} ${formatTokens(cachedTokens)}`),
437
+ missText && field("pi-mini-mode-cache-miss-show", "warning", missText),
405
438
  settings["pi-mini-mode-ch-show"] && hitText && field("pi-mini-mode-ch-show", "text", hitText),
406
439
  settings["pi-mini-mode-cost-show"] && price && field("pi-mini-mode-cost-show", "muted", price),
407
440
  mcpText && field("pi-mini-mode-mcp-show", "muted", mcpText),
@@ -414,6 +447,7 @@ export function statusLine(
414
447
  branchOnly && branchText,
415
448
  settings["pi-mini-mode-session-tokens-show"] && usageTotals.totalTokens > 0 && `${COPY.totalLabel} ${formatTokens(usageTotals.totalTokens)}`,
416
449
  settings["pi-mini-mode-cache-tokens-show"] && cachedTokens > 0 && `${COPY.cachedLabel} ${formatTokens(cachedTokens)}`,
450
+ missText,
417
451
  settings["pi-mini-mode-ch-show"] && hitText,
418
452
  settings["pi-mini-mode-cost-show"] && price,
419
453
  mcpText,
@@ -456,7 +490,7 @@ export function settingsItems(settings: MiniLensSettings): SettingItem[] {
456
490
  const labels: Record<Exclude<keyof MiniLensSettings, "onboardingCompleted" | "footerOrder">, string> = {
457
491
  "pi-mini-mode-project-branch-show": "显示项目名称和分支(互斥)",
458
492
  "pi-mini-mode-branch-show": "仅显示分支(思考等级后,互斥)",
459
- "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-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, "pi-mini-mode-minimal-thinking-show": COPY.showThinking, "pi-mini-mode-minimal-tools-show": COPY.tools, "pi-mini-mode-minimal-output-show": COPY.output, "pi-mini-mode-minimal-skills-show": COPY.skills, "pi-mini-mode-agent-usage-show": COPY.agentUsage, "pi-mini-mode-agent-shortcut-show": COPY.shortcut,
493
+ "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, "pi-mini-mode-minimal-thinking-show": COPY.showThinking, "pi-mini-mode-minimal-tools-show": COPY.tools, "pi-mini-mode-minimal-output-show": COPY.output, "pi-mini-mode-minimal-skills-show": COPY.skills, "pi-mini-mode-agent-usage-show": COPY.agentUsage, "pi-mini-mode-agent-shortcut-show": COPY.shortcut,
460
494
  };
461
495
  return (Object.keys(labels) as Array<keyof typeof labels>).map((id) => ({
462
496
  id, label: labels[id],
@@ -511,7 +545,6 @@ export interface ThinkingClock {
511
545
  }
512
546
 
513
547
  const PROCESS_PREVIEW_LIMIT = 180;
514
- const THINKING_SCROLL_INTERVAL_MS = 80;
515
548
 
516
549
  function contentText(content: unknown): string {
517
550
  if (typeof content === "string") return content.trim();
@@ -839,7 +872,7 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
839
872
  const control = truncateToWidth(label, inner, "");
840
873
  promptControls.push({ index, question: turn.question, y: lines.length + 1 + userRows.length,
841
874
  x: 0, width, label });
842
- userRows.push(theme.fg("accent", control) + theme.fg("muted", truncateToWidth(" · /pi-mini-mode-prompts", Math.max(0, inner - visibleWidth(control)), "")));
875
+ userRows.push(theme.fg("accent", control));
843
876
  // The expanded control is this message's heading, so it keeps the band in place of the user surface.
844
877
  controlIndex = userRows.length;
845
878
  }
@@ -867,7 +900,12 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
867
900
  const agents = liveAgentView(turn.subAgents ?? [], theme, width, subAgentsExpanded(), true, agentDeadlines, Date.now(), expandedSubagents, agentTurnControls);
868
901
  if (entries.length || turn.running || turn.usage || agents.total) {
869
902
  const expanded = isExpanded();
870
- const shown = expanded ? entries : entries.filter(entry => !entry.thinking || entry.state === "running" || expandedThinking.has(entry.id)).slice(-6);
903
+ const latestThinking = !expanded ? [...entries].reverse().find(entry => entry.thinking) : undefined;
904
+ const busy = entries.some(entry => entry.state === "running") || (turn.waitingTools?.length ?? 0) > 0;
905
+ const working = turn.running && !busy && !turn.final;
906
+ const limit = expanded ? entries.length : Math.max(0, 6 - (working ? 1 : 0));
907
+ const shown = expanded ? entries : entries.filter(entry => !entry.thinking || entry.state === "running" || entry === latestThinking || expandedThinking.has(entry.id)).slice(-limit);
908
+ if (latestThinking && !shown.includes(latestThinking)) shown.splice(Math.min(shown.length, entries.indexOf(latestThinking)), 0, latestThinking);
871
909
  const done = entries.filter(entry => entry.state === "done").length;
872
910
  const progressHeader = theme.bold(theme.fg("text", "Agent")) + (entries.length ? theme.fg("muted", ` · ${done}/${entries.length}`) : "")
873
911
  + (agents.total ? theme.bold(theme.fg("text", " Subagent")) + theme.fg("muted", ` ${agents.done + agents.errors}/${agents.total}`)
@@ -886,10 +924,6 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
886
924
  } else {
887
925
  lines.push("", truncateToWidth(header, width));
888
926
  }
889
- if (!shown.length && turn.running && turn.awaitingResponse && !turn.final) {
890
- const prefix = theme.fg("dim", `${agents.rows.length ? "├─" : "└─"} `) + theme.fg("accent", `${runningGlyph()} `) + theme.fg("text", theme.bold("Thinking")) + theme.fg("success", ` ${formatElapsed(turn.startedAt)}`) + " ";
891
- lines.push(truncateToWidth(prefix + theme.fg("text", "…"), width, ""));
892
- }
893
927
  shown.forEach((entry, row) => {
894
928
  const waiting = turn.waitingTools?.find(tool => tool.id === entry.id);
895
929
  const title = waiting && !entry.title.startsWith("Control ") ? `${waiting.name} running · waiting ${Math.max(0, Math.floor((Date.now() - waiting.startedAt) / 1000))}s` : entry.title;
@@ -902,8 +936,8 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
902
936
  const thinkingElapsed = elapsed ? theme.fg(activeThinking ? "success" : "muted", ` ${elapsed}`) : "";
903
937
  const call = turn.agentCalls?.find(call => call.id === entry.id && !isAgentTool(call.tool ?? call.name));
904
938
  const controlId = call?.id ?? (entry.thinking ? entry.id : "");
905
- const open = call ? expandedTools.has(call.id) : !!(entry.thinking && expandedThinking.has(entry.id));
906
- const identity = open ? "accent" : "text";
939
+ const open = call ? expandedTools.has(call.id) : entry.thinking && expandedThinking.has(entry.id);
940
+ const identity = open || activeThinking ? "accent" : "text";
907
941
  const summary = theme.fg(identity, theme.bold(label)) + thinkingElapsed + " ";
908
942
  if (controlId && width >= 4) toolControls.push({ id: controlId, y: lines.length, width, title: text });
909
943
  if (hoveredTool?.id === controlId && (hoveredTool.y !== lines.length || hoveredTool.width !== width)) clearHover();
@@ -912,19 +946,13 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
912
946
  const keepStatus = entry.state === "running" || (open && entry.state === "error");
913
947
  const glyph = arrow ? (open ? "▼" : "▶") + (keepStatus ? ` ${status}` : "") : status;
914
948
  const glyphColor = entry.state === "error" ? "error" : entry.state === "running" || arrow ? "accent" : "muted";
915
- const last = row === shown.length - 1 && !agents.rows.length;
949
+ const last = row === shown.length - 1 && !working && !agents.rows.length;
916
950
  const prefix = theme.fg(open ? "accent" : "dim", last ? "└─ " : "├─ ") + theme.fg(glyphColor, glyph) + " " + summary;
917
- if (activeThinking) {
918
- const renderedBody = markdown(body, Math.max(1, visibleWidth(body) + 1), true).join(" ").replace(/\s+/g, " ").trim();
919
- const bodyWidth = Math.max(0, width - visibleWidth(prefix));
920
- const overflow = Math.max(0, visibleWidth(renderedBody) - bodyWidth);
921
- const offset = overflow ? Math.max(0, Math.floor((Date.now() - (turn.startedAt ?? Date.now())) / THINKING_SCROLL_INTERVAL_MS) % (overflow + 9) - 4) : 0;
922
- lines.push(bandHeading(truncateToWidth(prefix + (bodyWidth ? sliceByColumn(renderedBody, Math.min(overflow, offset), bodyWidth, true) : ""), width, ""), open));
923
- } else if (label === "Output") {
951
+ if (label === "Output") {
924
952
  // Wrapped output hangs under the body column and keeps the tree rail to the next sibling.
925
953
  const indent = visibleWidth(prefix);
926
954
  const wrapped = markdown(body, Math.max(1, width - indent), true);
927
- const rail = !last && indent > 0 ? theme.fg("dim", "│") + " ".repeat(indent - 1) : " ".repeat(indent);
955
+ const rail = !last && indent > 0 ? theme.fg("dim", "\u2502") + " ".repeat(indent - 1) : " ".repeat(indent);
928
956
  lines.push(truncateToWidth(prefix + (wrapped[0] ?? ""), width, ""));
929
957
  for (const extra of wrapped.slice(1)) lines.push(truncateToWidth(rail + extra, width, ""));
930
958
  } else {
@@ -947,7 +975,7 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
947
975
  const details = entry.detail.split(/\r?\n/).filter(line => line.trim());
948
976
  // ponytail: four diagnostic lines; full output remains in the native transcript.
949
977
  lines.push(...details.slice(1, 5).map(line => truncateToWidth(rail + theme.fg("muted", line), width)));
950
- if (details.length > 5) lines.push(truncateToWidth(rail + theme.fg("muted", `… +${details.length - 5} lines · /pi-mini-mode-minimal off`), width));
978
+ if (details.length > 5) lines.push(truncateToWidth(rail + theme.fg("muted", `… +${details.length - 5} lines`), width));
951
979
  }
952
980
  });
953
981
  const agentStartY = lines.length;
@@ -957,6 +985,11 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
957
985
  if (c.runId === pinnedSubagentId) pinnedSubagent = { id: c.runId, y: control.y, line: c.line, autoScroll: false };
958
986
  }
959
987
  lines.push(...agents.rows);
988
+ if (working) {
989
+ const label = turn.awaitingResponse && !shown.length ? "Thinking" : "Working";
990
+ const prefix = theme.fg("dim", "└─ ") + theme.fg("accent", `${runningGlyph()} `) + theme.fg("text", theme.bold(label)) + theme.fg("success", ` ${formatElapsed(turn.startedAt)}`) + " ";
991
+ lines.push(truncateToWidth(prefix + theme.fg("text", "…"), width, ""));
992
+ }
960
993
  }
961
994
  for (const reply of turn.replies ?? []) lines.push("", ...markdown(reply, width));
962
995
  if (turn.final) lines.push("", ...markdown(turn.final, width));
@@ -1290,7 +1323,7 @@ export default function (pi: ExtensionAPI) {
1290
1323
  let choice: string | undefined;
1291
1324
  try {
1292
1325
  choice = await ctx.ui.select(
1293
- `Pi Mini Mode ${COPY.preview}\n\n deepseek-v4-flash high ${COPY.totalLabel} 45K ${COPY.cachedLabel} 25K ${COPY.cacheHitLabel} 40.0% $0.012 ◇ MCP 3 500/1.0M ⣿⣀⣀⣀⣀⣀⣀⣀⣀⣀ 1% 120 tok/s\n\n${COPY.onboarding}`,
1326
+ `Pi Mini Mode ${COPY.preview}\n\n deepseek-v4-flash high ${COPY.totalLabel} 45K ${COPY.cacheHitLabel} 40.0% $0.012 500/1.0M ⣿⣀⣀⣀⣀⣀⣀⣀⣀⣀ 1% 120 tok/s\n\n${COPY.onboarding}`,
1294
1327
  [COPY.keepDefaults, COPY.configureNow, COPY.applyRecommended],
1295
1328
  );
1296
1329
  } catch (error) {
@@ -1318,72 +1351,17 @@ export default function (pi: ExtensionAPI) {
1318
1351
  await persistSettings(ctx);
1319
1352
  if (choice === COPY.configureNow) await openSettings(ctx);
1320
1353
  };
1321
- pi.registerCommand("pi-mini-mode-minimal", {
1322
- description: "Toggle minimal output (off keeps Pi's default conversation history)",
1323
- handler: async (args, ctx) => {
1324
- const normalized = args.trim().toLowerCase();
1325
- if (ctx.mode !== "tui") {
1326
- ctx.ui.notify(COPY.minimalRequired, "error");
1327
- return;
1328
- }
1329
- if (normalized && normalized !== "on" && normalized !== "off") {
1330
- ctx.ui.notify(COPY.minimalUsage, "warning");
1331
- return;
1332
- }
1333
- settings = {
1334
- ...settings,
1335
- "pi-mini-mode-minimal-show": normalized === "on" ? true : normalized === "off" ? false : !settings["pi-mini-mode-minimal-show"],
1336
- onboardingCompleted: true,
1337
- };
1338
- if (settings["pi-mini-mode-minimal-show"]) nativeOutput = false;
1339
- mountMinimalOutput(ctx);
1340
- await persistSettings(ctx);
1341
- if (settings["pi-mini-mode-minimal-show"] && !restoreTranscript) return;
1342
- ctx.ui.notify(`${COPY.minimalState}${settings["pi-mini-mode-minimal-show"] ? "on" : "off"}`, "info");
1343
- },
1344
- });
1345
- pi.registerCommand("pi-mini-mode-prompts", {
1346
- description: "Expand or collapse a user prompt in fullscreen minimal output",
1347
- handler: async (_args, ctx) => {
1348
- if (ctx.mode !== "tui" || !restoreTranscript || !promptView) {
1349
- if (ctx.hasUI) ctx.ui.notify("Prompt folding requires fullscreen minimal output.", "info");
1350
- return;
1351
- }
1352
- const view = promptView;
1353
- const choices = view.promptChoices();
1354
- if (!choices.length) { ctx.ui.notify("No user prompts exceed four lines at this width.", "info"); return; }
1355
- const labels = choices.map(choice => `${choice.index + 1}. ${choice.label} · ${preview(choice.question)}`);
1356
- const selected = await ctx.ui.select("User prompts · Enter to toggle · Esc to cancel", labels);
1357
- const choice = choices[labels.indexOf(selected ?? "")];
1358
- if (choice && promptView === view) { view.togglePrompt(choice.index, choice.question); refreshMinimalOutput(); }
1359
- },
1360
- });
1361
- pi.registerCommand("pi-mini-mode-tools", {
1362
- description: "Expand or collapse a tool's saved text or thinking in fullscreen minimal output",
1363
- handler: async (_args, ctx) => {
1364
- if (ctx.mode !== "tui" || !restoreTranscript || !promptView) {
1365
- if (ctx.hasUI) ctx.ui.notify("Tool folding requires fullscreen minimal output.", "info");
1366
- return;
1367
- }
1368
- const view = promptView;
1369
- const choices = view.toolChoices();
1370
- if (!choices.length) { ctx.ui.notify("No visible tool calls. Ctrl+O shows older calls.", "info"); return; }
1371
- const labels = choices.map((choice, index) => `${index + 1}. ${choice.expanded ? "收起" : "展开"} · ${preview(choice.title)}`);
1372
- const selected = await ctx.ui.select("Tool results · Enter to toggle · Esc to cancel", labels);
1373
- const choice = choices[labels.indexOf(selected ?? "")];
1374
- if (choice && promptView === view) { view.toggleTool(choice.id); refreshMinimalOutput(); }
1375
- },
1376
- });
1377
1354
  pi.registerCommand("pi-mini-mode-settings", {
1378
1355
  description: "Open HTML settings in the browser",
1379
1356
  handler: async (_args, ctx) => openSettings(ctx),
1380
1357
  });
1381
- pi.registerCommand("pi-mini-mode-setup", {
1382
- description: "Show the first-run setup prompt again",
1383
- handler: async (_args, ctx) => runOnboarding(ctx),
1384
- });
1385
1358
 
1386
1359
  pi.on("session_start", async (_event, ctx) => {
1360
+ (ctx as ExtensionContext & { __applyMinimal?: (on: boolean) => void }).__applyMinimal = (on) => {
1361
+ settings = { ...settings, "pi-mini-mode-minimal-show": on };
1362
+ if (on) nativeOutput = false;
1363
+ mountMinimalOutput(ctx);
1364
+ };
1387
1365
  const loaded = await loadSettings(configPath);
1388
1366
  settings = loaded.settings;
1389
1367
  if (loaded.exists && loaded.backfilled) await persistSettings(ctx);
@@ -1411,7 +1389,7 @@ export default function (pi: ExtensionAPI) {
1411
1389
  mountMinimalOutput(ctx);
1412
1390
  });
1413
1391
  }
1414
- return [statusLine(ctx, theme, width, sessionUsage(ctx), settings, speed, undefined, mcpCount, footerData?.getExtensionStatuses?.(), footerData?.getGitBranch?.())];
1392
+ return [statusLine(ctx, theme, width, sessionUsage(ctx), settings, speed, undefined, mcpCount, footerData?.getExtensionStatuses?.(), footerData?.getGitBranch?.(), cacheWaste(ctx.sessionManager.getBranch()))];
1415
1393
  },
1416
1394
  };
1417
1395
  });
@@ -1699,3 +1677,9 @@ export default function (pi: ExtensionAPI) {
1699
1677
  stopSpeedTimer();
1700
1678
  });
1701
1679
  }
1680
+
1681
+ /** @internal tests flip minimal output without a slash command. */
1682
+ export function applyMinimal(ctx: ExtensionContext, on: boolean): void {
1683
+ const hook = (ctx as ExtensionContext & { __applyMinimal?: (on: boolean) => void }).__applyMinimal;
1684
+ hook?.(on);
1685
+ }
package/lib/file-links.ts CHANGED
@@ -2,12 +2,28 @@ import { existsSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { dirname, isAbsolute, resolve } from "node:path";
4
4
  import { pathToFileURL } from "node:url";
5
- import { getCapabilities, sliceByColumn, stripTerminalSequences, visibleWidth } from "@earendil-works/pi-tui";
5
+ import { Marked, getCapabilities, sliceByColumn, stripTerminalSequences, visibleWidth } from "@earendil-works/pi-tui";
6
+
7
+ const linkParser = new Marked();
8
+ export function webPaths(text: string) {
9
+ let offset = 0;
10
+ return linkParser.Lexer.lexInline(text, { gfm: true }).flatMap(token => {
11
+ const start = offset;
12
+ offset += token.raw.length;
13
+ if (token.type !== "link" || !/^https?:\/\//i.test(token.href) || /[\x00-\x20\x7f]/.test(token.href)) return [];
14
+ try { new URL(token.href); } catch { return []; }
15
+ return [{ path: token.href, start, end: offset }];
16
+ });
17
+ }
6
18
 
7
19
  /** Pi 0.85's allowlist predates Otty; preserve explicit opt-outs and multiplexer detection. */
8
20
  export function inputCapabilities(env = process.env) {
9
21
  const caps = getCapabilities();
10
- if (env.TERM_PROGRAM?.toLowerCase() !== "otty" || env.TMUX || /^(screen|tmux)/.test(env.TERM ?? "")) return caps;
22
+ if (env.TMUX || /^(screen|tmux)/.test(env.TERM ?? "")) return caps;
23
+ // Herdr panes advertise xterm-256color; the user's Kitty-capable fork renders images.
24
+ if (env.HERDR_PANE_ID) return { ...caps, hyperlinks: env.PI_HYPERLINKS !== "0",
25
+ images: env.PI_IMAGE_PROTOCOL === "0" || env.PI_IMAGE_PROTOCOL === "none" ? null : caps.images ?? "kitty" as const };
26
+ if (env.TERM_PROGRAM?.toLowerCase() !== "otty") return caps;
11
27
  return { ...caps, hyperlinks: env.PI_HYPERLINKS === "0" ? false : true,
12
28
  images: env.PI_IMAGE_PROTOCOL === "0" || env.PI_IMAGE_PROTOCOL === "none" ? null : caps.images ?? "kitty" as const };
13
29
  }
@@ -54,19 +70,26 @@ export function filePaths(text: string) {
54
70
  }
55
71
 
56
72
  // BEL survives Markdown's backslash-escape parsing, unlike the ST terminator.
57
- export const fileLink = (text: string, path: string) => `\x1b]8;;${pathToFileURL(path).href}\x07\x1b[4m${text}\x1b[24m\x1b]8;;\x07`;
73
+ export const fileLink = (text: string, path: string, underline = true) => `\x1b]8;;${pathToFileURL(path).href}\x07${underline ? `\x1b[4m${text}\x1b[24m` : text}\x1b]8;;\x07`;
58
74
 
59
- /** Display-only: never change persisted messages, existing links, or remote URLs. */
75
+ /** Display-only: normalize local targets without changing persisted messages or remote URLs. */
60
76
  export function linkMessageFiles(text: string, cwd: string): string {
61
77
  if (!inputCapabilities().hyperlinks) return text;
62
78
  let imageNumber = 0;
63
79
  return text.split(/(\x1b\]8;[^\x07]*(?:\x07)[\s\S]*?\x1b\]8;;\x07|\[[^\]\n]*\]\([^\n]*?\))/g).map((part, index) => {
64
- if (index % 2) return part;
80
+ if (index % 2) {
81
+ return part.replace(/^(\[[^\]\n]*\]\()(<[^>\n]*>|[^\s)]+)([\s\S]*)$/, (original, prefix, target, suffix) => {
82
+ const value = target.startsWith("<") ? target.slice(1, -1) : target;
83
+ if (/^[a-z][\w+.-]*:|^\/\//i.test(value) || /[\x00-\x1f\x7f]/.test(value)) return original;
84
+ const path = localPath(value, cwd);
85
+ return existsSync(path) ? `${prefix}<${pathToFileURL(path).href}>${suffix}` : original;
86
+ });
87
+ }
65
88
  const matches = filePaths(part).map(match => ({ ...match, label: /\.(png|jpe?g|gif|webp)$/i.test(match.path) && existsSync(localPath(match.path, cwd)) ? `[image${++imageNumber}]` : match.path }));
66
89
  for (const match of matches.reverse()) {
67
90
  const path = localPath(match.path, cwd);
68
91
  if (!existsSync(path)) continue;
69
- part = part.slice(0, match.start) + fileLink(match.label, path) + part.slice(match.end);
92
+ part = part.slice(0, match.start) + fileLink(match.label, path, !/^\[image\d+\]$/.test(match.label)) + part.slice(match.end);
70
93
  }
71
94
  return part;
72
95
  }).join("");
@@ -75,6 +98,8 @@ export function linkMessageFiles(text: string, cwd: string): string {
75
98
  /** Decorate rendered columns without removing the editor's ANSI cursor marker. */
76
99
  export function linkRenderedPath(line: string, start: number, end: number, path: string, directory = false): string {
77
100
  if (!inputCapabilities().hyperlinks || end <= start) return line;
78
- return sliceByColumn(line, 0, start) + fileLink(sliceByColumn(line, start, end - start), directory ? dirname(path) : path)
101
+ const label = sliceByColumn(line, start, end - start);
102
+ const link = /^https?:\/\//i.test(path) ? `\x1b]8;;${path}\x07${label}\x1b]8;;\x07` : fileLink(label, directory ? dirname(path) : path, false);
103
+ return sliceByColumn(line, 0, start) + link
79
104
  + sliceByColumn(line, end, Math.max(0, visibleWidth(stripTerminalSequences(line)) - end));
80
105
  }
@@ -16,7 +16,7 @@ import {
16
16
  allocateImageId, getImageDimensions, renderImage, getCapabilities, setCapabilities, getOsc8LinkAtColumn, matchesKey, stripTerminalSequences, truncateToWidth, visibleWidth,
17
17
  type AutocompleteItem, type AutocompleteProvider, type EditorComponent, type TuiMouseEvent, type TUI, type OverlayHandle, type OverlayOptions,
18
18
  } from "@earendil-works/pi-tui";
19
- import { filePaths, inputCapabilities, linkRenderedPath, localPath } from "./file-links.ts";
19
+ import { filePaths, inputCapabilities, linkRenderedPath, localPath, webPaths } from "./file-links.ts";
20
20
  import { open, readFile } from "node:fs/promises";
21
21
  import { homedir } from "node:os";
22
22
  import { dirname, extname, isAbsolute, join, resolve } from "node:path";
@@ -335,10 +335,13 @@ function wrapEditor(inner: EditorComponent, cwd: string, isEnabled: () => boolea
335
335
  for (const match of replacements.reverse()) text = text.slice(0, match.start) + match.label + text.slice(match.end);
336
336
  return text;
337
337
  };
338
- // ponytail: reuse Pi 0.85's editor segmentation/submit hooks; replace with a public attachment API when available.
339
- const core = inner as EditorComponent & { expandPasteMarkers?(text: string): string; segment?(text: string, mode?: string): Array<{ segment: string; index: number; input: string }>; imageAttachments?: Map<string, string> };
338
+ // ponytail: Pi 0.87 image paste calls the private inserter, bypassing the public proxy; replace with a public attachment API when available.
339
+ const core = inner as EditorComponent & { expandPasteMarkers?(text: string): string; insertTextAtCursorInternal?(text: string): void; segment?(text: string, mode?: string): Array<{ segment: string; index: number; input: string }>; imageAttachments?: Map<string, string>; state?: { lines: string[] } };
340
340
  core.imageAttachments = attachments;
341
+ // Rendering reads the stored lines directly, so the submit expansion must not put the temp path back on screen.
342
+ if (core.state) core.state.lines = compact(core.state.lines.join("\n")).split("\n");
341
343
  if (core.expandPasteMarkers) { const original = core.expandPasteMarkers.bind(core); core.expandPasteMarkers = text => expand(original(text)); }
344
+ if (core.insertTextAtCursorInternal) { const insert = core.insertTextAtCursorInternal.bind(core); core.insertTextAtCursorInternal = text => insert(compact(text)); }
342
345
  const pasteEditor = inner as EditorComponent & { handlePaste?(text: string): void };
343
346
  if (pasteEditor.handlePaste) { const paste = pasteEditor.handlePaste.bind(inner); pasteEditor.handlePaste = text => paste(compact(text)); }
344
347
  if (core.segment) {
@@ -355,7 +358,7 @@ function wrapEditor(inner: EditorComponent, cwd: string, isEnabled: () => boolea
355
358
  return new Proxy(inner, {
356
359
  get(target, property, receiver) {
357
360
  if (property === "getText") return () => expand(target.getText());
358
- if (property === "setText" || property === "insertTextAtCursor") return (text: string) => target[property]?.(compact(text));
361
+ if (property === "setText" || property === "insertTextAtCursor" || property === "insertTextAtCursorInternal") return (text: string) => { const insert = (target as EditorComponent & { insertTextAtCursorInternal?(value: string): void })[property] as ((value: string) => void) | undefined; insert?.call(target, compact(text)); };
359
362
  if (property === "render") {
360
363
  return (width: number) => {
361
364
  const lines = target.render(width);
@@ -408,7 +411,7 @@ function editorImagePaths(editor: EditorComponent, text: string): ImagePathMatch
408
411
  return paths.sort((a, b) => a.start - b.start);
409
412
  }
410
413
 
411
- function editorPaths(editor: EditorComponent, row: number, width: number) {
414
+ function editorPaths(editor: EditorComponent, row: number, width: number, includeWeb = false) {
412
415
  const core = editor as EditorComponent & { lastWidth?: number; scrollOffset?: number; renderedVisibleLineCount?: number; getPaddingX?(): number; buildVisualLineMap?(width: number): Array<{ logicalLine: number; startCol: number; length: number }> };
413
416
  if (!core.buildVisualLineMap || !core.lastWidth) return imagePathsInLine(editor.render(width)[row] ?? "");
414
417
  if (row < 1 || row > (core.renderedVisibleLineCount ?? 0)) return [];
@@ -416,7 +419,7 @@ function editorPaths(editor: EditorComponent, row: number, width: number) {
416
419
  if (!chunk) return [];
417
420
  const source = editor.getText().split("\n")[chunk.logicalLine] ?? "";
418
421
  const padding = Math.min(core.getPaddingX?.() ?? 0, Math.max(0, Math.floor((width - 1) / 2)));
419
- return editorImagePaths(editor, source).filter(match => match.end > chunk.startCol && match.start < chunk.startCol + chunk.length).map(match => ({
422
+ return [...editorImagePaths(editor, source), ...(includeWeb ? webPaths(source) : [])].filter(match => match.end > chunk.startCol && match.start < chunk.startCol + chunk.length).map(match => ({
420
423
  ...match,
421
424
  startCol: padding + visibleWidth(source.slice(chunk.startCol, Math.max(chunk.startCol, match.start))),
422
425
  endCol: padding + visibleWidth(source.slice(chunk.startCol, Math.min(chunk.startCol + chunk.length, match.end))),
@@ -426,7 +429,7 @@ function editorPaths(editor: EditorComponent, row: number, width: number) {
426
429
  function linkImagePaths(lines: string[], editor: EditorComponent, cwd: string, width: number): string[] {
427
430
  if (!inputCapabilities().hyperlinks) return lines;
428
431
  return lines.map((line, row) => {
429
- for (const match of editorPaths(editor, row, width).reverse()) line = linkRenderedPath(line, match.startCol, match.endCol, localPath(match.path, cwd));
432
+ for (const match of editorPaths(editor, row, width, true).reverse()) line = linkRenderedPath(line, match.startCol, match.endCol, /^https?:\/\//i.test(match.path) ? match.path : localPath(match.path, cwd));
430
433
  // Isolate editor rows from inherited terminal link/color state.
431
434
  const reset = "\x1b]8;;\x07\x1b[0m";
432
435
  return reset + line + reset;
@@ -434,7 +437,7 @@ function linkImagePaths(lines: string[], editor: EditorComponent, cwd: string, w
434
437
  }
435
438
 
436
439
  export function installInputEnhancements(pi: ExtensionAPI, ctx: ExtensionContext, isEnabled: boolean | (() => boolean)): InputEnhancementsCleanup {
437
- if (process.env.TERM_PROGRAM?.toLowerCase() === "otty") setCapabilities(inputCapabilities());
440
+ if (process.env.TERM_PROGRAM?.toLowerCase() === "otty" || process.env.HERDR_PANE_ID) setCapabilities(inputCapabilities());
438
441
  const enabled = typeof isEnabled === "function" ? isEnabled : () => isEnabled;
439
442
  if (installed && installed.pi !== pi) installed.cleanup();
440
443
  const state = installed?.pi === pi ? installed : (installed = createEnhancements(pi));
@@ -450,8 +453,9 @@ export function installInputEnhancements(pi: ExtensionAPI, ctx: ExtensionContext
450
453
  state.unsubscribeInput = ctx.ui.onTerminalInput?.((data) => handleTerminalInput(state, data)) ?? undefined;
451
454
  ctx.ui.addAutocompleteProvider((current) => createSkillAutocompleteProvider(current, () => readSkillCommands(pi), () => state.enabled()));
452
455
  }
456
+ // /reload clears the editor before session_start, so the saved factory can still be current while the live editor is unwrapped.
453
457
  const active = ctx.ui.getEditorComponent();
454
- if (active !== state.editorFactory || !state.editor) installEditor(ctx, state, active);
458
+ if (active !== state.editorFactory || !state.editor) installEditor(ctx, state, active === state.editorFactory ? state.baseFactory : active);
455
459
  }
456
460
  return state.cleanup;
457
461
  }
package/lib/settings.html CHANGED
@@ -3,12 +3,15 @@
3
3
  <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
4
4
  <title>Pi Mini Mode 设置</title>
5
5
  <style>
6
- :root{color-scheme:light dark;--background:light-dark(#f4f3ef,#141614);--foreground:light-dark(#1f241f,#eceee8);--surface:light-dark(#fffcf7,#1d211d);--muted:light-dark(#667066,#a8b0a4);--border:light-dark(#e2ddd4,#3a4038);--accent:light-dark(#2f5a3e,#b7d4b0);--destructive:light-dark(#a52c26,#ffafa5);--ring:var(--accent);--text-sm:.875rem;--text-base:1rem;--text-lg:2.75rem;--radius:8px}
7
- *{box-sizing:border-box}body{margin:0;background:var(--background);color:var(--foreground);font:var(--text-base)/1.5 ui-sans-serif,system-ui,sans-serif}main{max-width:1080px;margin:auto;padding:40px 24px 72px}header{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;flex-wrap:wrap}h1{font:italic 400 var(--text-lg)/1.05 "Didot","Bodoni 72","Iowan Old Style","Songti SC","STSong",serif;letter-spacing:.04em;margin:0}h2{font-size:var(--text-sm);font-weight:600;margin:0 0 12px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}.tagline{margin:8px 0 0;color:var(--muted);font-size:var(--text-sm)}nav{display:flex;gap:8px;align-items:center}.hint{margin:12px 0 0;color:var(--accent);font-weight:600}section{margin:28px 0}button{font:inherit;color:inherit;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:8px 12px;cursor:pointer}button:disabled{opacity:.4;cursor:default}:focus-visible{outline:2px solid var(--ring);outline-offset:3px}#preview{padding:16px 20px;background:var(--surface);border:1px dashed var(--accent);border-radius:var(--radius);font:var(--text-sm)/1.8 ui-monospace,monospace;display:flex;align-items:center;gap:12px;overflow-x:auto;min-height:72px;white-space:nowrap}#preview button{flex:none;font:inherit;padding:4px 2px;border-color:transparent;cursor:grab;white-space:nowrap}#preview button:hover{border-color:var(--border)}#preview button.over{border-left:2px solid var(--accent)}#preview #preview-context{flex:1;display:flex;align-items:center;gap:8px;min-width:180px}.progress{flex:1;overflow:hidden;text-align:left;color:var(--accent);min-width:0}.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:4px 16px}label{display:flex;align-items:center;gap:10px;padding:10px 0;cursor:pointer}input{accent-color:var(--accent);width:18px;height:18px;flex-shrink:0}.dragging{opacity:.45}#status{min-height:24px;color:var(--accent)}#status.error{color:var(--destructive)}#retry{margin-left:12px}[hidden]{display:none!important}nav button[aria-pressed=true]{border-color:var(--accent);color:var(--accent)}.features{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:12px}.feature{display:flex;flex-direction:column;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:16px 18px}.feature-head{display:flex;align-items:center;justify-content:space-between;gap:12px}.feature-head h3{margin:0;font-size:var(--text-base);font-weight:600}.feature-body{margin:10px 0 0;color:var(--muted);font-size:var(--text-sm);line-height:1.65}.feature-points{margin:10px 0 0;padding-left:1.15em;font-size:var(--text-sm);line-height:1.7}.feature-points li{margin:2px 0}.feature-points li::marker{color:var(--accent)}.feature-hint{margin:auto 0 0;padding-top:12px;color:var(--muted);font:var(--text-sm)/1.6 ui-monospace,monospace;overflow-wrap:anywhere}.feature-hint::before{content:'› ';color:var(--accent)}.switch{display:flex;align-items:center;gap:8px;padding:0;font-size:var(--text-sm);color:var(--muted)}.notice{display:flex;gap:16px;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;margin:20px 0 0;padding:14px 16px;background:var(--surface);border:1px solid var(--accent);border-left-width:4px;border-radius:var(--radius)}.notice strong{font-size:var(--text-sm)}.notice p{margin:6px 0 0;color:var(--muted);font-size:var(--text-sm);line-height:1.6;max-width:640px}.notice code{display:block;margin:0 0 8px;padding:8px 10px;background:var(--background);border:1px solid var(--border);border-radius:var(--radius);font:var(--text-sm)/1.5 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;max-width:520px;color:var(--foreground)}#preview{margin-top:12px}@media(max-width:450px){h1{font-size:2rem}main{padding:24px 16px}}
6
+ :root{color-scheme:light dark;--background:light-dark(#f4f3ef,#141614);--foreground:light-dark(#1f241f,#eceee8);--surface:light-dark(#fffcf7,#1d211d);--muted:light-dark(#667066,#a8b0a4);--border:light-dark(#e2ddd4,#3a4038);--accent:light-dark(#2f5a3e,#b7d4b0);--destructive:light-dark(#a52c26,#ffafa5);--ring:var(--accent);--preview-bg:light-dark(#f7f7f8,#131217);--preview-text:light-dark(#242127,#f5f5f5);--preview-muted:light-dark(#625f68,#a1a1aa);--preview-accent:light-dark(#2563eb,#5e9cff);--preview-warning:light-dark(#a16207,#facc15);--preview-success:light-dark(#15803d,#4ade80);--preview-error:light-dark(#dc2626,#fb7185);--text-sm:.875rem;--text-base:1rem;--text-lg:2.75rem;--radius:8px}
7
+ *{box-sizing:border-box}body{margin:0;background:var(--background);color:var(--foreground);font:var(--text-base)/1.5 ui-sans-serif,system-ui,sans-serif}main{max-width:1080px;margin:auto;padding:40px 24px 72px}header{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;flex-wrap:wrap}h1{font:italic 400 var(--text-lg)/1.05 "Didot","Bodoni 72","Iowan Old Style","Songti SC","STSong",serif;letter-spacing:.04em;margin:0}h2{font-size:var(--text-sm);font-weight:600;margin:0 0 12px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}nav{display:flex;gap:8px;align-items:center}.hint{margin:12px 0 0;color:var(--accent);font-weight:600}section{margin:28px 0}button{font:inherit;color:inherit;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:8px 12px;cursor:pointer}button:disabled{opacity:.4;cursor:default}:focus-visible{outline:2px solid var(--ring);outline-offset:3px}#preview{position:relative;padding:16px 20px;background:var(--preview-bg);color:var(--preview-text);border:1px dashed var(--border);border-radius:var(--radius);font:var(--text-sm)/1.8 ui-monospace,monospace;display:flex;flex-wrap:wrap;align-items:center;gap:4px 12px;height:112px;overflow:auto}#preview button{flex:none;font:inherit;padding:4px 2px;border-color:transparent;background:transparent;color:var(--preview-muted);cursor:grab;white-space:nowrap}#preview button:focus-visible{border-color:var(--accent)}#preview button.over{border-left:2px solid var(--accent)}#preview button.preview-exit{opacity:0;pointer-events:none;transition:opacity 280ms ease-in;position:absolute}#preview .tone-accent{color:var(--preview-accent);font-weight:650}#preview .tone-text{color:var(--preview-text)}#preview .tone-warning{color:var(--preview-warning);font-weight:650}#preview .tone-success{color:var(--preview-success);font-weight:650}#preview .tone-error{color:var(--preview-error);font-weight:650}#preview .tone-muted{color:var(--preview-muted)}#preview #preview-context{flex:1 1 180px;display:flex;align-items:center;gap:8px;min-width:180px}.progress{flex:1;overflow:hidden;text-align:left;color:var(--preview-accent);min-width:0}.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:2px 6px}label{display:flex;align-items:center;gap:10px;padding:10px 0;cursor:pointer;-webkit-user-select:none;user-select:none}.grid label{border:1px solid transparent;border-radius:var(--radius);padding:10px}input{accent-color:var(--accent);width:18px;height:18px;flex-shrink:0}.dragging{opacity:.45}#statusbar{position:fixed;top:12px;right:12px;z-index:2;display:flex;align-items:center;gap:10px;max-width:min(520px,calc(100vw - 24px));padding:8px 12px;background:var(--surface);border:1px solid var(--accent);border-radius:var(--radius);box-shadow:0 6px 20px rgb(0 0 0/.12);color:var(--accent);font-size:var(--text-sm);opacity:0;transform:translateY(-6px);transition:opacity 150ms ease-out,transform 150ms ease-out;pointer-events:none}#statusbar.on{opacity:1;transform:none}#statusbar.error{border-color:var(--destructive);color:var(--destructive)}#statusbar #retry{pointer-events:auto}[hidden]{display:none!important}nav button[aria-pressed=true]{border-color:var(--accent);color:var(--accent)}.features{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:12px}.feature{display:flex;flex-direction:column;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:16px 18px}.feature-head{display:flex;align-items:center;justify-content:space-between;gap:12px}.feature-head h3{margin:0;font-size:var(--text-base);font-weight:600}.feature-body{margin:10px 0 0;color:var(--muted);font-size:var(--text-sm);line-height:1.65}.feature-points{margin:10px 0 0;padding-left:1.15em;font-size:var(--text-sm);line-height:1.7}.feature-points li{margin:2px 0}.feature-points li::marker{color:var(--accent)}.feature-hint{margin:auto 0 0;padding-top:12px;color:var(--muted);font:var(--text-sm)/1.6 ui-monospace,monospace;overflow-wrap:anywhere}.feature-hint::before{content:'› ';color:var(--accent)}.switch{display:flex;align-items:center;gap:8px;padding:0;font-size:var(--text-sm);color:var(--muted)}.notice{display:flex;gap:16px;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;margin:20px 0 0;padding:14px 16px;background:var(--surface);border:1px solid var(--accent);border-left-width:4px;border-radius:var(--radius)}.notice strong{font-size:var(--text-sm)}.notice p{margin:6px 0 0;color:var(--muted);font-size:var(--text-sm);line-height:1.6;max-width:640px}.notice code{display:block;margin:0 0 8px;padding:8px 10px;background:var(--background);border:1px solid var(--border);border-radius:var(--radius);font:var(--text-sm)/1.5 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;max-width:520px;color:var(--foreground)}#preview{margin-top:12px;margin-bottom:20px}@media(max-width:450px){h1{font-size:2rem}main{padding:24px 16px}#statusbar{top:8px;right:8px;max-width:calc(100vw - 16px)}}@media(prefers-reduced-motion:reduce){#preview button.preview-exit{transition-duration:80ms}}@media(prefers-reduced-motion:reduce){#statusbar{transform:none;transition:opacity 80ms ease-out}}
8
+ @media(hover:hover) and (pointer:fine){#preview button:hover,.grid label:hover,.feature:hover{border-color:var(--accent)}}
9
+ #preview button.preview-highlight{border-color:var(--accent)}#preview button.preview-placeholder{border-style:dashed;opacity:1}
8
10
  </style>
9
11
  <main>
12
+ <div id="statusbar" role="status" aria-live="polite"><span id="status"></span><button type="button" id="retry" hidden></button></div>
10
13
  <header>
11
- <div><h1 id="title"></h1><p class="tagline" id="tagline"></p></div>
14
+ <h1 id="title"></h1>
12
15
  <nav>
13
16
  <button type="button" id="lang-zh" aria-pressed="false">中文</button>
14
17
  <button type="button" id="lang-en" aria-pressed="false">EN</button>
@@ -19,7 +22,6 @@
19
22
  <div><strong id="noticeTitle"></strong><p id="noticeBody"></p></div>
20
23
  <div><code id="noticePrompt"></code><button type="button" id="copyPrompt"></button></div>
21
24
  </div>
22
- <div role="status" aria-live="polite"><span id="status"></span><button id="retry" hidden></button></div>
23
25
  <section><h2 id="fieldsHeading"></h2><p class="hint" id="dragHint"></p><div id="preview" role="group" tabindex="0"></div><div class="grid" id="fields"></div></section>
24
26
  <section><h2 id="optionsHeading"></h2><div class="grid" id="options"></div></section>
25
27
  <section><h2 id="featuresHeading"></h2><div class="features" id="features"></div></section>
@@ -30,34 +32,32 @@ history.replaceState(null,'',location.pathname);
30
32
  const I18N={
31
33
  title:{zh:'Pi Mini Mode',en:'Pi Mini Mode'},
32
34
  documentTitle:{zh:'Pi Mini Mode 设置',en:'Pi Mini Mode Settings'},
33
- tagline:{zh:'极简状态栏配置',en:'Minimal status bar setup'},
34
- dragHint:{zh:'拖拽预览中的字段可调整顺序,松手自动保存',en:'Drag items in the preview to reorder · Auto-saves on drop'},
35
+ dragHint:{zh:'拖拽预览中的字段可调整顺序,松手自动保存。',en:'Drag preview items to reorder · saves on drop.'},
35
36
  featuresHeading:{zh:'功能说明',en:'Features'},
36
37
  fieldsHeading:{zh:'状态栏字段与预览',en:'Status bar items & preview'},
37
38
  optionsHeading:{zh:'状态栏样式',en:'Status bar style'},
38
39
  on:{zh:'开启',en:'On'},off:{zh:'关闭',en:'Off'},
39
40
  featureList:{
40
41
  zh:[
41
- {id:'status',title:'状态栏指标',body:'一行看清会话状态,随终端宽度自动取舍,不换行。',points:['模型与思考等级,会话与缓存 Token、缓存命中率、费用估算','上下文用量进度条与百分比','生成速度 tok/s,从第一个输出 token 起算,不含等待首字'],hint:'勾选需要的字段,拖拽预览中的条目即可排序。'},
42
- {id:'minimal',setting:'pi-mini-mode-minimal-show',title:'极简输出',body:'把对话收成结论:思考、工具与技能汇成一棵按时间排序的可折叠过程树。',points:['长用户消息默认保留前四行,点击折叠控件展开全文','子代理行可展开活动记录与最终输出','Ctrl+O 展开或收起完整过程树,新问题默认收起','最终 Markdown 流畅呈现,失败与中断明确标记'],hint:'/pi-mini-mode-minimal on|off · /pi-mini-mode-prompts · /pi-mini-mode-history'},
43
- {id:'input-enhancements',setting:'pi-mini-mode-input-enhancements',title:'输入增强',body:'让输入框和消息里的图片、技能与文件路径直接可用。',points:['光标移入图片路径即可预览,全屏编辑器也支持悬停','图片路径收纳为 [image1] 标签,提交时保留原图','空白后输入 / 就地搜索技能,并在光标处插入','点击图片标签或消息中的文件路径,用系统默认应用打开'],hint:'Ctrl+V 粘贴图片(Windows/WSL 使用 Alt+V)'},
44
- {id:'themes',title:'明暗主题',body:'内置 cc-dark 与 cc-light 两套主题,Markdown、代码高亮、表格与 Mermaid 图表一并适配明暗。',points:['用户消息使用主题的用户背景色,与正文清晰区分','不支持、不完整或过宽的图表保留源文本'],hint:'/pi-mini-mode-settings 配置所有选项'}
42
+ {id:'status',title:'状态栏指标',body:'一行看清会话状态,按终端宽度取舍。',points:['模型与思考等级,会话与缓存 Token、命中率、费用','上下文进度条与百分比','生成速度 tok/s,从首个输出 token 起算,不含等待首字']},
43
+ {id:'minimal',setting:'pi-mini-mode-minimal-show',title:'极简输出',body:'把对话收成结论:思考、工具与技能汇成一棵按时间排序的可折叠过程树。',points:['长用户消息默认保留前四行,点击展开全文','子代理行可展开活动记录与输出','Ctrl+O 展开或收起过程树,新问题默认收起','最终 Markdown 流畅呈现,失败与中断明确标记']},
44
+ {id:'input-enhancements',setting:'pi-mini-mode-input-enhancements',title:'输入增强',body:'让输入框和消息里的图片、技能与文件路径直接可用。',points:['光标移入图片路径即可预览,全屏编辑器同样支持','图片路径收纳为 [image1] 标签,提交时保留原图','空白后输入 / 就地搜索技能并插入光标处','点击图片标签或文件路径,用系统默认应用打开'],hint:'Ctrl+V 粘贴图片(Windows/WSL 使用 Alt+V)'},
45
+ {id:'themes',title:'明暗主题',body:'主题让 Markdown、代码高亮、表格与 Mermaid 图表跟随明暗切换。',points:['用户消息使用主题用户背景色,与正文区分','不支持、不完整或过宽的图表保留源文本'],hint:'回到 Pi,输入 /settings → Theme,选择 cc-dark / cc-light'}
45
46
  ],
46
47
  en:[
47
- {id:'status',title:'Status bar metrics',body:'The whole session state on one line, trimmed to fit narrow terminals instead of wrapping.',points:['Model and thinking level, session and cache tokens, cache hit rate, cost estimate','Context usage bar with percentage','Speed in tok/s, measured from the first output token, excluding time to first token'],hint:'Enable the items you need, then drag entries in the preview to reorder.'},
48
- {id:'minimal',setting:'pi-mini-mode-minimal-show',title:'Minimal transcript',body:'Turns the conversation into conclusions: thinking, tools and skills collapse into one chronological, foldable tree.',points:['Long user messages keep four lines; click the fold control to expand','Subagent rows expand to activity and final output','Ctrl+O expands or collapses the full process tree; new questions start collapsed','Final Markdown streams plainly; failures and interrupts are marked'],hint:'/pi-mini-mode-minimal on|off · /pi-mini-mode-prompts · /pi-mini-mode-history'},
49
- {id:'input-enhancements',setting:'pi-mini-mode-input-enhancements',title:'Input enhancements',body:'Makes images, skills and file paths usable right where you type.',points:['Preview an image as soon as the cursor enters its path; hovering works in fullscreen','Image paths collapse to [image1] labels while keeping the original path on submit','Type / after a space to search skills and insert one at the cursor','Click image labels or file paths in messages to open them in the default app'],hint:'Ctrl+V pastes images (Windows/WSL: Alt+V)'},
50
- {id:'themes',title:'Light and dark themes',body:'Built-in cc-dark and cc-light adapt Markdown, code highlighting, tables and Mermaid diagrams to the color scheme.',points:['User messages use the theme user background to stand apart from the body','Unsupported, incomplete or overly wide diagrams keep their source text'],hint:'/pi-mini-mode-settings to configure all options'}
48
+ {id:'status',title:'Status bar metrics',body:'The whole session state on one line, trimmed to fit narrow terminals.',points:['Model and thinking level, session and cache tokens, hit rate, cost','Context usage bar with percentage','Speed in tok/s, measured from the first output token, excluding time to first token']},
49
+ {id:'minimal',setting:'pi-mini-mode-minimal-show',title:'Minimal transcript',body:'Turns the conversation into conclusions: thinking, tools and skills collapse into one chronological, foldable tree.',points:['Long user messages keep four lines; click to expand','Subagent rows expand to activity and output','Ctrl+O expands or collapses the full process tree; new questions start collapsed','Final Markdown streams plainly; failures and interrupts are marked']},
50
+ {id:'input-enhancements',setting:'pi-mini-mode-input-enhancements',title:'Input enhancements',body:'Makes images, skills and file paths usable right where you type.',points:['Preview an image as soon as the cursor enters its path, in fullscreen too','Image paths collapse to [image1] labels while keeping the original path on submit','Type / after a space to search skills and insert at the cursor','Click image labels or file paths to open them in the default app'],hint:'Ctrl+V pastes images (Windows/WSL: Alt+V)'},
51
+ {id:'themes',title:'Light and dark themes',body:'Themes keep Markdown, code highlighting, tables and Mermaid diagrams in step with light and dark.',points:['User messages use the theme user background to stand out','Unsupported, incomplete or overly wide diagrams keep their source text'],hint:'In Pi, enter /settings → Theme and choose cc-dark or cc-light'}
51
52
  ]
52
53
  },
53
54
  reset:{zh:'恢复默认',en:'Reset defaults'},
54
55
  retry:{zh:'重试',en:'Retry'},
55
56
  confirmReset:{zh:'恢复默认排序与显示设置?',en:'Reset layout and visibility to defaults?'},
56
57
  connecting:{zh:'正在同步…',en:'Connecting…'},
57
- connected:{zh:'已同步',en:'In sync'},
58
+ saved:{zh:'设置已完成',en:'Settings saved'},
58
59
  unsaved:{zh:'未保存修改',en:'Unsaved changes'},
59
60
  saving:{zh:'正在保存…',en:'Saving…'},
60
- saved:{zh:'已保存',en:'Saved'},
61
61
  saveFailed:{zh:'保存失败',en:'Failed to save'},
62
62
  reconnect:{zh:'连接已断开,请从终端重新打开',en:'Disconnected. Please reopen from the terminal.'},
63
63
  noticeTitle:{zh:'极简输出需要全屏渲染器',en:'Minimal transcript needs the fullscreen renderer'},
@@ -74,6 +74,7 @@ const I18N={
74
74
  branch:{zh:'仅分支',en:'Branch Only'},
75
75
  'session-tokens':{zh:'会话 Token',en:'Session Tokens'},
76
76
  'cache-tokens':{zh:'缓存 Token',en:'Cache Tokens'},
77
+ 'cache-miss':{zh:'缓存 miss',en:'Cache miss'},
77
78
  ch:{zh:'缓存命中率',en:'Cache Hit Rate'},
78
79
  cost:{zh:'累计费用',en:'Cost'},
79
80
  mcp:{zh:'MCP 服务数',en:'MCP Count'},
@@ -88,16 +89,24 @@ const I18N={
88
89
  };
89
90
  const FIELD_KEY={minimal:'pi-mini-mode-minimal-show','input-enhancements':'pi-mini-mode-input-enhancements','context-dots':'pi-mini-mode-context-dots-show','speed-unit':'pi-mini-mode-speed-unit-show'};
90
91
  let lang=localStorage.piMiniModeLang||(navigator.language.startsWith('zh')?'zh':'en');
91
- let data,state,order,dragged,saving=false,dirty=false,timer,copyTimer;
92
+ let data,state,order,dragged,hovered,saving=false,dirty=false,timer,copyTimer,statusTimer;
92
93
  const key=id=>'pi-mini-mode-'+id+'-show';
93
94
  const t=(id,fallback='')=>(I18N[id]?.[lang]??fallback);
94
95
  const fieldLabel=id=>I18N.fields[id]?.[lang]||id;
95
- const examples={'project-branch':'pi-mini-mode(main)',model:'deepseek-v4-flash',thinking:'high',branch:'main','session-tokens':'Total 45K','cache-tokens':'Cached 25K',ch:'CH 40.0%',cost:'$0.012',mcp:'◇ MCP 3',context:'500/1.0M','context-percent':'1%',speed:'120 tok/s'};
96
- function status(text,error=false){$('status').textContent=text;$('status').className=error?'error':''}
96
+ const examples={'project-branch':'pi-mini-mode(main)',model:'deepseek-v4-flash',thinking:'high',branch:'main','session-tokens':'Total 45K','cache-tokens':'Cached 25K','cache-miss':'Miss 21K',ch:'CH 40.0%',cost:'$0.012',mcp:'◇ MCP 3',context:'500/1.0M','context-percent':'1%',speed:'120 tok/s'};
97
+ const statusHold=2500;
98
+ function status(text,error=false){
99
+ clearTimeout(statusTimer);
100
+ const bar=$('statusbar');
101
+ bar.classList.toggle('error',!!error);bar.classList.toggle('on',!!text);
102
+ $('status').textContent=text;
103
+ if(!text||error)return; // 连接/保存中短显,错误留在原地等 retry
104
+ statusTimer=setTimeout(()=>{$('status').textContent='';bar.classList.remove('on')},statusHold);
105
+ }
97
106
  function applyLang(){
98
107
  document.documentElement.lang=lang==='zh'?'zh-CN':'en';
99
108
  document.title=t('documentTitle');
100
- for(const id of ['title','tagline','featuresHeading','fieldsHeading','optionsHeading','dragHint']) $(id).textContent=t(id);
109
+ for(const id of ['title','featuresHeading','fieldsHeading','optionsHeading','dragHint']) $(id).textContent=t(id);
101
110
  $('reset').textContent=t('reset');$('retry').textContent=t('retry');
102
111
  $('lang-zh').setAttribute('aria-pressed',String(lang==='zh'));
103
112
  $('lang-en').setAttribute('aria-pressed',String(lang==='en'));
@@ -108,15 +117,48 @@ async function request(method,body){
108
117
  if(!response.ok)throw Error(await response.text()||t('saveFailed'));
109
118
  return response.json();
110
119
  }
120
+ const previewFade=280,previewFadeReduced=80;
121
+ function syncPreviewEmpty(){const panel=$('preview');if(!panel.children.length)panel.textContent=t('emptyPreview')}
122
+ function exitPreview(el){
123
+ if(el.classList.contains('preview-exit'))return;
124
+ const fade=matchMedia('(prefers-reduced-motion: reduce)').matches?previewFadeReduced:previewFade;
125
+ el.style.left=el.offsetLeft+'px';el.style.top=el.offsetTop+'px';
126
+ el.classList.add('preview-exit');el.setAttribute('aria-hidden','true');
127
+ el.disabled=true;el.draggable=false;el.tabIndex=-1;
128
+ setTimeout(()=>{el.remove();syncPreviewEmpty()},fade+60);
129
+ }
130
+ // A hidden field fades out in place; its timer removes only that node, so a stale fade can never delete a newer button.
131
+ function nextPreview(el){let node=el.nextSibling;while(node&&!(node.dataset?.field&&!node.classList.contains('preview-exit')))node=node.nextSibling;return node}
132
+ function hoverField(id){return {'context-dots':'context','speed-unit':'speed'}[id]||id}
111
133
  function preview(){
112
134
  const panel=$('preview'),scroll=panel.scrollLeft;
113
- panel.replaceChildren();
114
- const visible=order.filter(id=>state[key(id)]);
115
- const values={...examples,speed:state['pi-mini-mode-speed-unit-show']?'120 tok/s':'120'};
116
- for(const id of visible){
117
- const button=document.createElement('button');
118
- button.id='preview-'+id;button.type='button';button.textContent=values[id];button.draggable=true;
119
- if(id==='context'){const bar=document.createElement('span');bar.className='progress';bar.setAttribute('aria-hidden','true');bar.textContent=state['pi-mini-mode-context-dots-show']?'⣿'+'⣀'.repeat(300):'█'+'░'.repeat(300);button.append(bar)}
135
+ const highlighted=hoverField(hovered);
136
+ const visible=order.filter(id=>state[key(id)]||id===highlighted);
137
+ const sample={...state};
138
+ if(hovered)sample[FIELD_KEY[hovered]||key(hovered)]=true;
139
+ const values=Object.fromEntries(Object.entries(examples).map(([id,value])=>[id,typeof value==='function'?value():value]));
140
+ values.speed=sample['pi-mini-mode-speed-unit-show']?'120 tok/s':'120';
141
+ for(const node of [...panel.childNodes])if(node.nodeType===3)node.remove();
142
+ const live=new Map();
143
+ for(const el of [...panel.children]){
144
+ const field=el.dataset.field;
145
+ if(!field){el.remove();continue}
146
+ if(!visible.includes(field)){if(el.dataset.ghost==='true')el.remove();else exitPreview(el);continue}
147
+ if(el.classList.contains('preview-exit')){el.remove();continue}
148
+ live.set(field,el);
149
+ }
150
+ let next=null;
151
+ for(let index=visible.length-1;index>=0;index--){
152
+ const id=visible[index];
153
+ const button=live.get(id)??document.createElement('button');
154
+ button.id='preview-'+id;button.type='button';button.textContent=values[id];button.draggable=true;button.dataset.field=id;
155
+ const fast=Number.parseFloat(values.speed)>=100;
156
+ button.className='tone-'+(id==='model'||id==='context-percent'?'accent':id==='cache-miss'?'warning':id==='session-tokens'||id==='cache-tokens'||id==='ch'?'text':id==='speed'?(fast?'success':values.speed.startsWith('0')?'error':'warning'):'muted');
157
+ const ghost=!state[key(id)];
158
+ button.dataset.ghost=String(ghost);button.disabled=ghost;button.draggable=!ghost;button.tabIndex=ghost?-1:0;
159
+ if(ghost)button.setAttribute('aria-hidden','true');else button.removeAttribute('aria-hidden');
160
+ if(id===highlighted){button.classList.add('preview-highlight');if(ghost||!state[FIELD_KEY[hovered]||key(hovered)])button.classList.add('preview-placeholder')}
161
+ if(id==='context'){const bar=document.createElement('span');bar.className='progress';bar.setAttribute('aria-hidden','true');bar.textContent=sample['pi-mini-mode-context-dots-show']?'⣿'+'⣀'.repeat(199):'█'+'░'.repeat(199);button.append(bar)}
120
162
  button.setAttribute('aria-label',fieldLabel(id)+' · '+t('dragHint'));
121
163
  button.ondragstart=event=>{dragged=id;event.dataTransfer.setData('text/plain',id);event.dataTransfer.effectAllowed='move';button.classList.add('dragging')};
122
164
  button.ondragend=()=>{dragged=undefined;button.classList.remove('dragging');document.querySelectorAll('.over').forEach(el=>el.classList.remove('over'))};
@@ -124,15 +166,17 @@ function preview(){
124
166
  button.ondragleave=()=>button.classList.remove('over');
125
167
  button.ondrop=event=>{event.preventDefault();const source=dragged;dragged=undefined;if(source){move(order.indexOf(source),order.indexOf(id));$('preview-'+source)?.focus()}};
126
168
  button.onkeydown=event=>{if(event.key!=='ArrowLeft'&&event.key!=='ArrowRight')return;event.preventDefault();const target=visible[visible.indexOf(id)+(event.key==='ArrowLeft'?-1:1)];if(target){move(order.indexOf(id),order.indexOf(target));$('preview-'+id)?.focus()}};
127
- panel.append(button);
169
+ if(button.parentNode!==panel||nextPreview(button)!==next)panel.insertBefore(button,next);
170
+ next=button;
128
171
  }
129
- if(!visible.length)panel.textContent=t('emptyPreview');
172
+ if(!visible.length)syncPreviewEmpty();
130
173
  panel.scrollLeft=scroll;
131
174
  }
132
- function change(){dirty=true;state.footerOrder=[...order];preview();renderNotice();status(t('unsaved'));clearTimeout(timer);timer=setTimeout(save,250)}
175
+ function change(){hovered=undefined;dirty=true;state.footerOrder=[...order];preview();renderNotice();status(t('unsaved'));clearTimeout(timer);timer=setTimeout(save,250)}
133
176
  async function save(){
134
177
  if(saving)return;saving=true;$('retry').hidden=true;
135
- try{while(dirty){dirty=false;const body=structuredClone(state);status(t('saving'));await request('PUT',body)}status(t('saved'))}
178
+ let wrote=false;
179
+ try{while(dirty){dirty=false;const body=structuredClone(state);status(t('saving'));await request('PUT',body);wrote=true}status(wrote?t('saved'):'')}
136
180
  catch(error){dirty=true;status(t('saveFailed')+':'+error.message,true);$('retry').hidden=false}
137
181
  finally{saving=false}
138
182
  }
@@ -155,8 +199,8 @@ function feature(item){
155
199
  const body=document.createElement('p');body.className='feature-body';body.textContent=item.body;
156
200
  const points=document.createElement('ul');points.className='feature-points';
157
201
  points.append(...item.points.map(point=>{const li=document.createElement('li');li.textContent=point;return li}));
158
- const hint=document.createElement('p');hint.className='feature-hint';hint.textContent=item.hint;
159
- card.append(head,body,points,hint);
202
+ card.append(head,body,points);
203
+ if(item.hint){const hint=document.createElement('p');hint.className='feature-hint';hint.textContent=item.hint;card.append(hint)}
160
204
  return card;
161
205
  }
162
206
  function checkbox(id,settingId){
@@ -165,15 +209,18 @@ function checkbox(id,settingId){
165
209
  change();
166
210
  });
167
211
  label.append(input,document.createTextNode(fieldLabel(id)));
212
+ label.onmouseenter=()=>{if(matchMedia('(hover: hover) and (pointer: fine)').matches){hovered=id;preview()}};
213
+ label.onmouseleave=()=>{if(hovered===id){hovered=undefined;preview()}};
168
214
  return label;
169
215
  }
170
216
  function move(from,to){if(from===to||from<0||to<0||to>=order.length)return;const [id]=order.splice(from,1);order.splice(to,0,id);preview();change()}
171
217
  function render(){
218
+ hovered=undefined;
172
219
  applyLang();
173
220
  renderNotice();
174
- $('fields').replaceChildren(...order.map(id=>checkbox(id,key(id))));
221
+ $('fields').replaceChildren(...order.map(id=>checkbox(id,key(id))),...(data.options||[]).map(id=>checkbox(id,FIELD_KEY[id]||key(id))));
175
222
  $('features').replaceChildren(...t('featureList').map(feature));
176
- $('options').replaceChildren(...(data.options||[]).map(id=>checkbox(id,FIELD_KEY[id]||key(id))));
223
+ $('options').replaceChildren();$('optionsHeading').hidden=true;$('options').hidden=true;
177
224
  preview();
178
225
  }
179
226
  function renderNotice(){
@@ -205,6 +252,6 @@ function mergeOrder(base,all){const next=[...new Set((base||[]).filter(id=>(all|
205
252
  $('reset').onclick=()=>{if(!confirm(t('confirmReset')))return;state={...data.defaults};order=mergeOrder(data.order,data.order);render();change()};
206
253
  window.addEventListener('beforeunload',event=>{if(dirty||saving){event.preventDefault();event.returnValue=''}});
207
254
  applyLang();status(t('connecting'));
208
- request('GET').then(value=>{data=value;state={...data.settings};order=mergeOrder(state.footerOrder||data.order,data.order);render();$('reset').disabled=false;status(t('connected'))}).catch(()=>status(t('reconnect'),true));
255
+ request('GET').then(value=>{data=value;state={...data.settings};order=mergeOrder(state.footerOrder||data.order,data.order);render();$('reset').disabled=false;status('')}).catch(()=>status(t('reconnect'),true));
209
256
  </script>
210
257
  </html>
@@ -304,6 +304,22 @@ function supervisorEnvelope(child: Component): unknown {
304
304
  /** Pi 0.85.x private layout adapter. Never mutates the stored messages or child tree. */
305
305
  export type NoticeRows = string[] & { handleMouse?: Component["handleMouse"] };
306
306
  export type TurnNotices = ReadonlyMap<number, NoticeRows>;
307
+
308
+ /** Pi writes one warning line per miss (`Cache miss…: N tokens re-billed`). */
309
+ export function cacheMissLine(text: string): { label: string; tokens: number } | undefined {
310
+ const plain = stripVTControlCharacters(text).replace(/\s+/g, " ").trim();
311
+ const match = plain.match(/^(Cache miss\b.*?):\s*([\d,.]+)\s*([kKmM])?\s*tokens re-billed\b/);
312
+ if (!match) return;
313
+ const scale = match[3]?.toLowerCase() === "m" ? 1_000_000 : match[3]?.toLowerCase() === "k" ? 1_000 : 1;
314
+ const tokens = Math.round(Number(match[2].replace(/,/g, "")) * scale);
315
+ return Number.isFinite(tokens) ? { label: match[1], tokens } : undefined;
316
+ }
317
+
318
+ function formatCacheTokens(value: number): string {
319
+ if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
320
+ if (value >= 1_000) return `${Math.round(value / 1_000)}k`;
321
+ return String(value);
322
+ }
307
323
  interface TranscriptView extends Component {
308
324
  render(width: number, notices?: TurnNotices): string[];
309
325
  clearHover?(): boolean;
@@ -325,6 +341,8 @@ interface NoticeOptions {
325
341
  /** Blocking extension prompts are native UI, never auto-expiring notices. */
326
342
  isPrompt?: (text: string) => boolean;
327
343
  isTransient?: (text: string) => boolean;
344
+ /** When false, Pi's per-turn cache-miss lines stay in the transcript. Default: fold them. */
345
+ foldCacheMiss?: () => boolean;
328
346
  now?: () => number;
329
347
  schedule?: (callback: () => void, delay: number) => () => void;
330
348
  }
@@ -411,7 +429,21 @@ export function attachTranscript(tui: unknown, view: TranscriptView, options: No
411
429
  let turn = totalTurns - nativeTurns - 1;
412
430
  let nextExpiry = Infinity;
413
431
  const time = now();
432
+ const cacheMisses = new Map<number, { label: string; tokens: number; count: number; rows: string[] }>();
433
+ const flushCache = (index: number) => {
434
+ const miss = cacheMisses.get(index);
435
+ if (!miss) return;
436
+ cacheMisses.delete(index);
437
+ const rows = notices.get(index) ?? [];
438
+ // ponytail: first styled line carries the color; token text is plain digits so one replace is enough.
439
+ const summary = miss.count === 1
440
+ ? miss.rows[0]
441
+ : miss.rows[0].replace(/[\d,.]+\s*[kKmM]?\s*tokens re-billed/, `${miss.count} misses, ${formatCacheTokens(miss.tokens)} tokens re-billed`);
442
+ rows.push(summary);
443
+ notices.set(index, rows);
444
+ };
414
445
  for (const child of chat.children) {
446
+ if (child.constructor.name === "UserMessageComponent") flushCache(turn);
415
447
  if (child.constructor.name === "UserMessageComponent") turn++;
416
448
  // Goal state is stored as a custom entry, not a user message. Adapt only
417
449
  // the known pi-codex-goal envelope so ordinary extension cards stay native.
@@ -468,6 +500,15 @@ export function attachTranscript(tui: unknown, view: TranscriptView, options: No
468
500
  // Pi 0.85 Text stores the unwrapped styled source in text. Width changes
469
501
  // must not restart the timeout; setText updates must restart it.
470
502
  const source = (child as unknown as { text?: unknown }).text;
503
+ const miss = options.foldCacheMiss?.() !== false && typeof source === "string" ? cacheMissLine(source) : undefined;
504
+ if (miss) {
505
+ const current = cacheMisses.get(turn) ?? { label: miss.label, tokens: 0, count: 0, rows: [] as string[] };
506
+ current.tokens += miss.tokens;
507
+ current.count++;
508
+ current.rows.push(...child.render(width));
509
+ cacheMisses.set(turn, current);
510
+ continue;
511
+ }
471
512
  if (typeof source === "string" && !options.isPrompt?.(source) && options.isTransient?.(source)) {
472
513
  let state = noticeTimes.get(child);
473
514
  if (!state || state.text !== source) {
@@ -481,6 +522,7 @@ export function attachTranscript(tui: unknown, view: TranscriptView, options: No
481
522
  rows.push(...child.render(width));
482
523
  notices.set(turn, rows);
483
524
  }
525
+ flushCache(turn);
484
526
  if (Number.isFinite(nextExpiry)) {
485
527
  cancelExpiry = schedule(() => {
486
528
  cancelExpiry = undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@each1024/pi-mini-mode",
3
- "version": "0.9.2",
3
+ "version": "1.0.0",
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": {