@each1024/pi-mini-mode 0.9.1 → 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 +25 -19
- package/README.zh-CN.md +23 -22
- package/extensions/footer-status.ts +95 -91
- package/lib/file-links.ts +32 -7
- package/lib/input-enhancements.ts +13 -9
- package/lib/settings.html +86 -38
- package/lib/transcript-adapter.ts +42 -0
- package/package.json +1 -1
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
|
|
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
|
|
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
|
|
51
|
-
- **Tool details on demand.** Expand a tool
|
|
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
|
-
|
|
64
|
+
Turn **Minimal output** off in settings to restore native Pi history.
|
|
55
65
|
|
|
56
66
|
### 03 / Session, in focus
|
|
57
67
|
|
|
@@ -75,15 +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-minimal on` / `off` | Enable minimal output / restore native history |
|
|
79
88
|
| `Ctrl+O` | Expand or collapse the complete process tree |
|
|
80
89
|
| `Ctrl+S` | Expand or collapse completed subagent rows; yields to Pi `/model`, `/thinking`, and other selectors |
|
|
81
|
-
| `/pi-mini-mode-prompts` | Select and expand/collapse a user message¹ |
|
|
82
|
-
| `/pi-mini-mode-tools` | Select and expand/collapse saved tool text or thinking¹ |
|
|
83
|
-
| `/pi-mini-mode-history` | Browse full process entries, five at a time |
|
|
84
90
|
| `/reload` | Reload the extension after installation or source changes |
|
|
85
91
|
|
|
86
|
-
|
|
92
|
+
Subagent rows have their own click-to-expand control; supported third-party widgets retain native detail shortcuts.
|
|
87
93
|
|
|
88
94
|
## Compatibility
|
|
89
95
|
|
|
@@ -98,13 +104,13 @@ This earlier screenshot and recording show footer configuration, not the newer i
|
|
|
98
104
|
<details>
|
|
99
105
|
<summary><strong>First run & configuration</strong> — defaults, controls, and settings file</summary>
|
|
100
106
|
|
|
101
|
-
On the first interactive TUI session, Pi Mini Mode shows a preview.
|
|
107
|
+
On the first interactive TUI session, Pi Mini Mode shows a preview. Almost every feature is on by default; only **branch-only** is off (it is mutually exclusive with **project & branch**). Change anything later with `/pi-mini-mode-settings`.
|
|
102
108
|
|
|
103
109
|
```text
|
|
104
|
-
deepseek-v4-flash high Total 45K Cached 25K CH 40.0% $0.012 500/1.0M
|
|
110
|
+
deepseek-v4-flash high Total 45K Cached 25K CH 40.0% $0.012 ◇ MCP 3 500/1.0M ⣿⣀⣀⣀⣀⣀⣀⣀⣀⣀ 1% 120 tok/s
|
|
105
111
|
```
|
|
106
112
|
|
|
107
|
-
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;
|
|
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.
|
|
108
114
|
|
|
109
115
|
Open that settings UI any time with:
|
|
110
116
|
|
|
@@ -126,9 +132,9 @@ Settings are stored globally at Pi's agent directory (normally `~/.pi/agent/pi-m
|
|
|
126
132
|
"pi-mini-mode-session-tokens-show": true,
|
|
127
133
|
"pi-mini-mode-cache-tokens-show": true,
|
|
128
134
|
"pi-mini-mode-cost-show": true,
|
|
129
|
-
"pi-mini-mode-mcp-show":
|
|
135
|
+
"pi-mini-mode-mcp-show": true,
|
|
130
136
|
"pi-mini-mode-context-show": true,
|
|
131
|
-
"pi-mini-mode-context-dots-show":
|
|
137
|
+
"pi-mini-mode-context-dots-show": true,
|
|
132
138
|
"pi-mini-mode-context-percent-show": true,
|
|
133
139
|
"pi-mini-mode-speed-show": true,
|
|
134
140
|
"pi-mini-mode-speed-unit-show": true,
|
|
@@ -146,9 +152,9 @@ Settings are stored globally at Pi's agent directory (normally `~/.pi/agent/pi-m
|
|
|
146
152
|
| `pi-mini-mode-session-tokens-show` | `true` | Accumulated session tokens (`Total`) |
|
|
147
153
|
| `pi-mini-mode-cache-tokens-show` | `true` | Accumulated cache read + cache write tokens |
|
|
148
154
|
| `pi-mini-mode-cost-show` | `true` | Estimated session list price |
|
|
149
|
-
| `pi-mini-mode-mcp-show` | `
|
|
155
|
+
| `pi-mini-mode-mcp-show` | `true` | Enabled MCP server count |
|
|
150
156
|
| `pi-mini-mode-context-show` | `true` | Used/total context tokens and progress bar |
|
|
151
|
-
| `pi-mini-mode-context-dots-show` | `
|
|
157
|
+
| `pi-mini-mode-context-dots-show` | `true` | Use a single-line dot-matrix bar instead of the solid bar |
|
|
152
158
|
| `pi-mini-mode-context-percent-show` | `true` | Context-use percentage |
|
|
153
159
|
| `pi-mini-mode-speed-show` | `true` | Generation speed at the far right |
|
|
154
160
|
| `pi-mini-mode-speed-unit-show` | `true` | Generation-speed sub-setting: append `tok/s` to the numeric value |
|
|
@@ -195,9 +201,9 @@ For a real terminal smoke test, run `python3 test/minimal-pty.py`. It needs Pyth
|
|
|
195
201
|
<details>
|
|
196
202
|
<summary><strong>Publishing</strong></summary>
|
|
197
203
|
|
|
198
|
-
|
|
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.
|
|
199
205
|
|
|
200
|
-
|
|
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.
|
|
201
207
|
|
|
202
208
|
</details>
|
|
203
209
|
|
package/README.zh-CN.md
CHANGED
|
@@ -6,10 +6,15 @@
|
|
|
6
6
|
|
|
7
7
|
# Pi Mini Mode
|
|
8
8
|
|
|
9
|
+
|
|
9
10
|
**少一点干扰。多一点专注。**
|
|
10
11
|
|
|
11
12
|
为 [Pi](https://pi.dev) 的日常工作做一点精细的改进,不止于页脚。光标处预览图片,折叠长消息和过程详情,展开子代理工作,让重要的会话状态始终清晰。
|
|
12
13
|
|
|
14
|
+
<img width="1259" height="1020" alt="file-5ec414a82040ac062f4cda734fc10769" src="https://github.com/user-attachments/assets/0a894706-9ae6-46e5-bf85-3c7f85cf0273" />
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
13
18
|
## 安装
|
|
14
19
|
|
|
15
20
|
```bash
|
|
@@ -41,17 +46,20 @@ pi install git:github.com/eachann1024/pi-mini-mode
|
|
|
41
46
|
|
|
42
47
|
使用 `Ctrl+V` 粘贴图片,Windows/WSL 使用 `Alt+V`。关闭输入增强不会关闭 Pi 原生剪贴板功能。
|
|
43
48
|
|
|
49
|
+
<img width="1225" height="918" alt="image" src="https://github.com/user-attachments/assets/4cde0f64-35c9-4b15-9650-d8ba48863e6a" />
|
|
50
|
+
|
|
51
|
+
|
|
44
52
|
### 02 / 过程,更安静
|
|
45
53
|
|
|
46
|
-
|
|
54
|
+
在 `/pi-mini-mode-settings` 中开启 **极简输出**。
|
|
47
55
|
|
|
48
|
-
- **长消息,自动折叠。**
|
|
56
|
+
- **长消息,自动折叠。** 全屏极简模式下,长用户消息默认保留前四个显示行。点击折叠控件展开全文。完整代码围栏保持完整。
|
|
49
57
|
- **子代理,清晰可查。** 点击子代理行,展开可用的活动记录与消息/最终输出。任务派发回执或工具调用返回,不等于后台任务已完成。
|
|
50
|
-
- **过程是一棵树,而非满屏输出。**
|
|
51
|
-
- **工具详情,按需展开。**
|
|
58
|
+
- **过程是一棵树,而非满屏输出。** 思考、工具与技能读取汇入同一棵时间顺序树,显示最新摘要,包括最新一条思考;`Ctrl+O` 展开/收起完整过程,新问题默认收起。
|
|
59
|
+
- **工具详情,按需展开。** 点击工具或思考条目的折叠控件,最新一条思考也可以展开。思考默认收起,进行中与结束后均只由手动操作展开或收起。工具详情展示保存的文本,不还原原生自定义渲染器或图片输出。
|
|
52
60
|
- **把空间留给答案。** 最终 Markdown 流式呈现,不添加额外标题或背景。失败和中断明确标记;折叠只改变显示,不删除原始会话消息。
|
|
53
61
|
|
|
54
|
-
|
|
62
|
+
在设置中关闭 **极简输出** 即恢复 Pi 原生历史。
|
|
55
63
|
|
|
56
64
|
### 03 / 状态,更清晰
|
|
57
65
|
|
|
@@ -75,15 +83,11 @@ pi install git:github.com/eachann1024/pi-mini-mode
|
|
|
75
83
|
| 命令/快捷键 | 用途 |
|
|
76
84
|
| --- | --- |
|
|
77
85
|
| `/pi-mini-mode-settings` | 配置字段、输入增强和极简输出 |
|
|
78
|
-
| `/pi-mini-mode-minimal on` / `off` | 开启极简输出/恢复原生历史 |
|
|
79
86
|
| `Ctrl+O` | 展开/收起完整过程树 |
|
|
80
87
|
| `Ctrl+S` | 展开/收起已完成的子代理行;打开 `/model`、`/thinking` 等选择器时交给 Pi |
|
|
81
|
-
| `/pi-mini-mode-prompts` | 选择并展开/收起用户消息¹ |
|
|
82
|
-
| `/pi-mini-mode-tools` | 选择并展开/收起保存的工具文本或思考¹ |
|
|
83
|
-
| `/pi-mini-mode-history` | 浏览完整过程记录,每次五条 |
|
|
84
88
|
| `/reload` | 安装或修改源码后重载扩展 |
|
|
85
89
|
|
|
86
|
-
|
|
90
|
+
子代理行有独立的点击展开控件;受支持的第三方小组件保留原生详情快捷键。
|
|
87
91
|
|
|
88
92
|
## 兼容性
|
|
89
93
|
|
|
@@ -98,13 +102,13 @@ pi install git:github.com/eachann1024/pi-mini-mode
|
|
|
98
102
|
<details>
|
|
99
103
|
<summary><strong>首次使用与配置</strong></summary>
|
|
100
104
|
|
|
101
|
-
首次进入交互式 TUI 会话时,Pi Mini Mode
|
|
105
|
+
首次进入交互式 TUI 会话时,Pi Mini Mode 显示设置预览。几乎全部功能默认开启;仅「仅显示分支」默认关,与「项目与分支」互斥。之后可用 `/pi-mini-mode-settings` 再改。
|
|
102
106
|
|
|
103
107
|
```text
|
|
104
|
-
deepseek-v4-flash high Total 45K Cached 25K CH 40.0% $0.012 500/1.0M
|
|
108
|
+
deepseek-v4-flash high Total 45K Cached 25K CH 40.0% $0.012 ◇ MCP 3 500/1.0M ⣿⣀⣀⣀⣀⣀⣀⣀⣀⣀ 1% 120 tok/s
|
|
105
109
|
```
|
|
106
110
|
|
|
107
|
-
首次设置会提供 **Keep defaults(保留默认值)**、**Configure now(立即配置)** 和 **Apply recommended setup(应用推荐配置)**。保留默认值会保存默认字段选择、保持极简输出开启,并且不再显示首次设置提示;立即配置会直接打开同一设置列表。应用推荐配置会让你选择内置的 `cc-dark` 或 `cc-light` 主题,通过 Pi 官方设置 API 保存该主题和全局 `tuiMode=fullscreen`,立即应用主题,并提示重启 Pi(全屏渲染器在启动时决定)。项目设置和命令行参数可能覆盖全局设置。按 Esc
|
|
111
|
+
首次设置会提供 **Keep defaults(保留默认值)**、**Configure now(立即配置)** 和 **Apply recommended setup(应用推荐配置)**。保留默认值会保存默认字段选择、保持极简输出开启,并且不再显示首次设置提示;立即配置会直接打开同一设置列表。应用推荐配置会让你选择内置的 `cc-dark` 或 `cc-light` 主题,通过 Pi 官方设置 API 保存该主题和全局 `tuiMode=fullscreen`,立即应用主题,并提示重启 Pi(全屏渲染器在启动时决定)。项目设置和命令行参数可能覆盖全局设置。按 Esc/取消不会完成首次设置,下次交互式会话会再次提示。Print、JSON 等非交互模式不会显示提示。
|
|
108
112
|
|
|
109
113
|
设置保存在 Pi 的 agent 目录中,通常是 `~/.pi/agent/pi-mini-mode.json`;如果 Pi 使用其他配置目录,则保存在对应目录。文件缺失或格式错误时会安全回退到默认设置。设置示例:
|
|
110
114
|
|
|
@@ -116,9 +120,9 @@ deepseek-v4-flash high Total 45K Cached 25K CH 40.0% $0.012 500/1.0M █
|
|
|
116
120
|
"pi-mini-mode-session-tokens-show": true,
|
|
117
121
|
"pi-mini-mode-cache-tokens-show": true,
|
|
118
122
|
"pi-mini-mode-cost-show": true,
|
|
119
|
-
"pi-mini-mode-mcp-show":
|
|
123
|
+
"pi-mini-mode-mcp-show": true,
|
|
120
124
|
"pi-mini-mode-context-show": true,
|
|
121
|
-
"pi-mini-mode-context-dots-show":
|
|
125
|
+
"pi-mini-mode-context-dots-show": true,
|
|
122
126
|
"pi-mini-mode-context-percent-show": true,
|
|
123
127
|
"pi-mini-mode-speed-show": true,
|
|
124
128
|
"pi-mini-mode-speed-unit-show": true,
|
|
@@ -136,9 +140,9 @@ deepseek-v4-flash high Total 45K Cached 25K CH 40.0% $0.012 500/1.0M █
|
|
|
136
140
|
| `pi-mini-mode-session-tokens-show` | `true` | 显示会话累计令牌(`Total`) |
|
|
137
141
|
| `pi-mini-mode-cache-tokens-show` | `true` | 显示缓存读取与写入令牌(已包含在 Total 中) |
|
|
138
142
|
| `pi-mini-mode-cost-show` | `true` | 显示会话费用估算 |
|
|
139
|
-
| `pi-mini-mode-mcp-show` | `
|
|
143
|
+
| `pi-mini-mode-mcp-show` | `true` | 显示已启用的 MCP 服务器数量 |
|
|
140
144
|
| `pi-mini-mode-context-show` | `true` | 显示已用/总上下文令牌和进度条 |
|
|
141
|
-
| `pi-mini-mode-context-dots-show` | `
|
|
145
|
+
| `pi-mini-mode-context-dots-show` | `true` | 使用单行点阵进度条替代实心进度条 |
|
|
142
146
|
| `pi-mini-mode-context-percent-show` | `true` | 显示上下文使用百分比 |
|
|
143
147
|
| `pi-mini-mode-speed-show` | `true` | 显示最新生成速度 |
|
|
144
148
|
| `pi-mini-mode-speed-unit-show` | `true` | 速度子设置:在数字后追加 `tok/s` |
|
|
@@ -188,12 +192,9 @@ python3 test/minimal-pty.py
|
|
|
188
192
|
<details>
|
|
189
193
|
<summary><strong>发布</strong></summary>
|
|
190
194
|
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
后续发布使用 npm Trusted Publisher、OIDC 和 provenance,无需 npm token。
|
|
194
|
-
|
|
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 中的基线。
|
|
195
196
|
|
|
196
|
-
|
|
197
|
+
备份流程需要为该包配置指向此 GitHub 仓库及 `publish.yml` 的 npm Trusted Publisher。它使用 OIDC 和 provenance,不使用 npm token。
|
|
197
198
|
|
|
198
199
|
</details>
|
|
199
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,11 +50,12 @@ 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":
|
|
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
56
|
"pi-mini-mode-mcp-show": false,
|
|
55
57
|
"pi-mini-mode-context-show": true,
|
|
56
|
-
"pi-mini-mode-context-dots-show":
|
|
58
|
+
"pi-mini-mode-context-dots-show": true,
|
|
57
59
|
"pi-mini-mode-context-percent-show": true,
|
|
58
60
|
"pi-mini-mode-speed-show": true,
|
|
59
61
|
"pi-mini-mode-speed-unit-show": true,
|
|
@@ -69,15 +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;
|
|
75
|
+
export const FOOTER_STYLE_OPTIONS = ["context-dots", "speed-unit"] as const;
|
|
73
76
|
|
|
74
77
|
const COPY = {
|
|
75
78
|
title: "Pi Mini Mode 设置", preview: "预览(示例数据)", lens: "设置", minimal: "极简输出",
|
|
76
|
-
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 秒)",
|
|
77
80
|
totalDescription: "Total:当前会话分支上的全部 token,含工具上报的 LLM 用量。", cachedDescription: "Cached:累计 cache-read + cache-write token(包含在 Total 中)。", cacheHitDescription: "CH(cache hit):cache-read / (input + cache-read)。Cache write 不计入此比率。",
|
|
78
81
|
enableMinimalDescription: "开启统一折叠思考、工具和技能过程;关闭恢复 Pi 默认会话历史。",
|
|
79
82
|
inputEnhancementsDescription: "原生 Ctrl+V 粘贴图片(Windows/WSL:Alt+V);图片显示为 [image1] 标签,光标移入或全屏悬停可预览。空白后 / 选择技能并在光标处插入。Cmd+点击带下划线的图片标签或消息文件路径,用系统默认应用打开;预览及点击需终端支持。关闭仅恢复原生行为。",
|
|
80
|
-
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: "MCP
|
|
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。",
|
|
81
84
|
} as const;
|
|
82
85
|
|
|
83
86
|
const RECOMMENDED_THEMES = ["cc-dark", "cc-light"] as const;
|
|
@@ -108,17 +111,31 @@ export function parseSettings(value: unknown): MiniLensSettings {
|
|
|
108
111
|
return settings;
|
|
109
112
|
}
|
|
110
113
|
|
|
114
|
+
/** True when saved JSON is missing a boolean key or a footer field, so defaults can be written back. */
|
|
115
|
+
export function settingsNeedBackfill(raw: unknown, parsed: MiniLensSettings): boolean {
|
|
116
|
+
if (!raw || typeof raw !== "object") return true;
|
|
117
|
+
const candidate = raw as Record<string, unknown>;
|
|
118
|
+
for (const id of SETTING_IDS) {
|
|
119
|
+
if (!Object.hasOwn(candidate, id)) return true;
|
|
120
|
+
}
|
|
121
|
+
if (!Array.isArray(candidate.footerOrder)) return false;
|
|
122
|
+
const order = parsed.footerOrder ?? [];
|
|
123
|
+
return FOOTER_FIELDS.some(id => !order.includes(id));
|
|
124
|
+
}
|
|
125
|
+
|
|
111
126
|
/** Pi /model and other selectors own Ctrl+S; the editor exposes getText. */
|
|
112
127
|
export function focusedSelectorOwnsKeys(tui?: { getFocusedComponent?(): unknown } | null): boolean {
|
|
113
128
|
const focused = tui?.getFocusedComponent?.();
|
|
114
129
|
return !!focused && typeof focused === "object" && typeof (focused as { getText?: unknown }).getText !== "function";
|
|
115
130
|
}
|
|
116
131
|
|
|
117
|
-
export async function loadSettings(path = settingsPath()): Promise<{ settings: MiniLensSettings; exists: boolean }> {
|
|
132
|
+
export async function loadSettings(path = settingsPath()): Promise<{ settings: MiniLensSettings; exists: boolean; backfilled: boolean }> {
|
|
118
133
|
try {
|
|
119
|
-
|
|
134
|
+
const raw: unknown = JSON.parse(await readFile(path, "utf8"));
|
|
135
|
+
const settings = parseSettings(raw);
|
|
136
|
+
return { settings, exists: true, backfilled: settingsNeedBackfill(raw, settings) };
|
|
120
137
|
} catch {
|
|
121
|
-
return { settings: { ...DEFAULT_SETTINGS }, exists: false };
|
|
138
|
+
return { settings: { ...DEFAULT_SETTINGS }, exists: false, backfilled: false };
|
|
122
139
|
}
|
|
123
140
|
}
|
|
124
141
|
|
|
@@ -202,6 +219,33 @@ function addUsage(total: SessionUsage, usage: UsageLike | undefined): SessionUsa
|
|
|
202
219
|
};
|
|
203
220
|
}
|
|
204
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
|
+
|
|
205
249
|
/** Aggregate persisted, finalized usage once per active-branch entry. */
|
|
206
250
|
export function sessionUsage(ctx: ExtensionContext): SessionUsage {
|
|
207
251
|
return ctx.sessionManager.getBranch().reduce((total, entry) => {
|
|
@@ -322,6 +366,7 @@ export function statusLine(
|
|
|
322
366
|
mcpCount?: number,
|
|
323
367
|
statuses?: ReadonlyMap<string, string>,
|
|
324
368
|
gitBranch?: string | null,
|
|
369
|
+
waste?: CacheWaste,
|
|
325
370
|
): string {
|
|
326
371
|
if (highlighted === "pi-mini-mode-context-dots-show") highlighted = "pi-mini-mode-context-show";
|
|
327
372
|
const field = (id: keyof MiniLensSettings, color: Parameters<typeof theme.fg>[0], text: string) =>
|
|
@@ -332,6 +377,7 @@ export function statusLine(
|
|
|
332
377
|
const hit = cacheHit(usageTotals);
|
|
333
378
|
const hitText = hit === undefined ? "" : `${COPY.cacheHitLabel} ${hit.toFixed(1)}%`;
|
|
334
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)}` : "";
|
|
335
381
|
const price = usageTotals.cost > 0 ? formatUsd(usageTotals.cost) : "";
|
|
336
382
|
const contextUsage = ctx.getContextUsage();
|
|
337
383
|
const tokens = finiteNumber(contextUsage?.tokens);
|
|
@@ -354,6 +400,7 @@ export function statusLine(
|
|
|
354
400
|
model, thinking,
|
|
355
401
|
"session-tokens": usageTotals.totalTokens > 0 ? `${COPY.totalLabel} ${formatTokens(usageTotals.totalTokens)}` : "",
|
|
356
402
|
"cache-tokens": cachedTokens > 0 ? `${COPY.cachedLabel} ${formatTokens(cachedTokens)}` : "",
|
|
403
|
+
"cache-miss": missText,
|
|
357
404
|
ch: hitText, cost: price, mcp: mcpText,
|
|
358
405
|
context: tokenText,
|
|
359
406
|
"context-percent": percentText, speed: speed === undefined ? "" : formatSpeed(speed, settings["pi-mini-mode-speed-unit-show"]),
|
|
@@ -366,7 +413,7 @@ export function statusLine(
|
|
|
366
413
|
}
|
|
367
414
|
return truncateToWidth([planTag, ...settings.footerOrder.map(id => {
|
|
368
415
|
const key = `pi-mini-mode-${id}-show` as keyof MiniLensSettings;
|
|
369
|
-
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";
|
|
370
417
|
return settings[key] && values[id] ? field(key, color, values[id]) : "";
|
|
371
418
|
})].filter(Boolean).join(" "), width, "…");
|
|
372
419
|
}
|
|
@@ -387,6 +434,7 @@ export function statusLine(
|
|
|
387
434
|
branchOnly && branchText && field(branchSetting, "muted", branchText),
|
|
388
435
|
settings["pi-mini-mode-session-tokens-show"] && usageTotals.totalTokens > 0 && field("pi-mini-mode-session-tokens-show", "text", `${COPY.totalLabel} ${formatTokens(usageTotals.totalTokens)}`),
|
|
389
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),
|
|
390
438
|
settings["pi-mini-mode-ch-show"] && hitText && field("pi-mini-mode-ch-show", "text", hitText),
|
|
391
439
|
settings["pi-mini-mode-cost-show"] && price && field("pi-mini-mode-cost-show", "muted", price),
|
|
392
440
|
mcpText && field("pi-mini-mode-mcp-show", "muted", mcpText),
|
|
@@ -399,6 +447,7 @@ export function statusLine(
|
|
|
399
447
|
branchOnly && branchText,
|
|
400
448
|
settings["pi-mini-mode-session-tokens-show"] && usageTotals.totalTokens > 0 && `${COPY.totalLabel} ${formatTokens(usageTotals.totalTokens)}`,
|
|
401
449
|
settings["pi-mini-mode-cache-tokens-show"] && cachedTokens > 0 && `${COPY.cachedLabel} ${formatTokens(cachedTokens)}`,
|
|
450
|
+
missText,
|
|
402
451
|
settings["pi-mini-mode-ch-show"] && hitText,
|
|
403
452
|
settings["pi-mini-mode-cost-show"] && price,
|
|
404
453
|
mcpText,
|
|
@@ -441,7 +490,7 @@ export function settingsItems(settings: MiniLensSettings): SettingItem[] {
|
|
|
441
490
|
const labels: Record<Exclude<keyof MiniLensSettings, "onboardingCompleted" | "footerOrder">, string> = {
|
|
442
491
|
"pi-mini-mode-project-branch-show": "显示项目名称和分支(互斥)",
|
|
443
492
|
"pi-mini-mode-branch-show": "仅显示分支(思考等级后,互斥)",
|
|
444
|
-
"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,
|
|
445
494
|
};
|
|
446
495
|
return (Object.keys(labels) as Array<keyof typeof labels>).map((id) => ({
|
|
447
496
|
id, label: labels[id],
|
|
@@ -496,7 +545,6 @@ export interface ThinkingClock {
|
|
|
496
545
|
}
|
|
497
546
|
|
|
498
547
|
const PROCESS_PREVIEW_LIMIT = 180;
|
|
499
|
-
const THINKING_SCROLL_INTERVAL_MS = 80;
|
|
500
548
|
|
|
501
549
|
function contentText(content: unknown): string {
|
|
502
550
|
if (typeof content === "string") return content.trim();
|
|
@@ -824,7 +872,7 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
|
|
|
824
872
|
const control = truncateToWidth(label, inner, "");
|
|
825
873
|
promptControls.push({ index, question: turn.question, y: lines.length + 1 + userRows.length,
|
|
826
874
|
x: 0, width, label });
|
|
827
|
-
userRows.push(theme.fg("accent", control)
|
|
875
|
+
userRows.push(theme.fg("accent", control));
|
|
828
876
|
// The expanded control is this message's heading, so it keeps the band in place of the user surface.
|
|
829
877
|
controlIndex = userRows.length;
|
|
830
878
|
}
|
|
@@ -852,7 +900,12 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
|
|
|
852
900
|
const agents = liveAgentView(turn.subAgents ?? [], theme, width, subAgentsExpanded(), true, agentDeadlines, Date.now(), expandedSubagents, agentTurnControls);
|
|
853
901
|
if (entries.length || turn.running || turn.usage || agents.total) {
|
|
854
902
|
const expanded = isExpanded();
|
|
855
|
-
const
|
|
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);
|
|
856
909
|
const done = entries.filter(entry => entry.state === "done").length;
|
|
857
910
|
const progressHeader = theme.bold(theme.fg("text", "Agent")) + (entries.length ? theme.fg("muted", ` · ${done}/${entries.length}`) : "")
|
|
858
911
|
+ (agents.total ? theme.bold(theme.fg("text", " Subagent")) + theme.fg("muted", ` ${agents.done + agents.errors}/${agents.total}`)
|
|
@@ -871,10 +924,6 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
|
|
|
871
924
|
} else {
|
|
872
925
|
lines.push("", truncateToWidth(header, width));
|
|
873
926
|
}
|
|
874
|
-
if (!shown.length && turn.running && turn.awaitingResponse && !turn.final) {
|
|
875
|
-
const prefix = theme.fg("dim", `${agents.rows.length ? "├─" : "└─"} `) + theme.fg("accent", `${runningGlyph()} `) + theme.fg("text", theme.bold("Thinking")) + theme.fg("success", ` ${formatElapsed(turn.startedAt)}`) + " ";
|
|
876
|
-
lines.push(truncateToWidth(prefix + theme.fg("text", "…"), width, ""));
|
|
877
|
-
}
|
|
878
927
|
shown.forEach((entry, row) => {
|
|
879
928
|
const waiting = turn.waitingTools?.find(tool => tool.id === entry.id);
|
|
880
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;
|
|
@@ -887,8 +936,8 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
|
|
|
887
936
|
const thinkingElapsed = elapsed ? theme.fg(activeThinking ? "success" : "muted", ` ${elapsed}`) : "";
|
|
888
937
|
const call = turn.agentCalls?.find(call => call.id === entry.id && !isAgentTool(call.tool ?? call.name));
|
|
889
938
|
const controlId = call?.id ?? (entry.thinking ? entry.id : "");
|
|
890
|
-
const open = call ? expandedTools.has(call.id) :
|
|
891
|
-
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";
|
|
892
941
|
const summary = theme.fg(identity, theme.bold(label)) + thinkingElapsed + " ";
|
|
893
942
|
if (controlId && width >= 4) toolControls.push({ id: controlId, y: lines.length, width, title: text });
|
|
894
943
|
if (hoveredTool?.id === controlId && (hoveredTool.y !== lines.length || hoveredTool.width !== width)) clearHover();
|
|
@@ -897,19 +946,13 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
|
|
|
897
946
|
const keepStatus = entry.state === "running" || (open && entry.state === "error");
|
|
898
947
|
const glyph = arrow ? (open ? "▼" : "▶") + (keepStatus ? ` ${status}` : "") : status;
|
|
899
948
|
const glyphColor = entry.state === "error" ? "error" : entry.state === "running" || arrow ? "accent" : "muted";
|
|
900
|
-
const last = row === shown.length - 1 && !agents.rows.length;
|
|
949
|
+
const last = row === shown.length - 1 && !working && !agents.rows.length;
|
|
901
950
|
const prefix = theme.fg(open ? "accent" : "dim", last ? "└─ " : "├─ ") + theme.fg(glyphColor, glyph) + " " + summary;
|
|
902
|
-
if (
|
|
903
|
-
const renderedBody = markdown(body, Math.max(1, visibleWidth(body) + 1), true).join(" ").replace(/\s+/g, " ").trim();
|
|
904
|
-
const bodyWidth = Math.max(0, width - visibleWidth(prefix));
|
|
905
|
-
const overflow = Math.max(0, visibleWidth(renderedBody) - bodyWidth);
|
|
906
|
-
const offset = overflow ? Math.max(0, Math.floor((Date.now() - (turn.startedAt ?? Date.now())) / THINKING_SCROLL_INTERVAL_MS) % (overflow + 9) - 4) : 0;
|
|
907
|
-
lines.push(bandHeading(truncateToWidth(prefix + (bodyWidth ? sliceByColumn(renderedBody, Math.min(overflow, offset), bodyWidth, true) : ""), width, ""), open));
|
|
908
|
-
} else if (label === "Output") {
|
|
951
|
+
if (label === "Output") {
|
|
909
952
|
// Wrapped output hangs under the body column and keeps the tree rail to the next sibling.
|
|
910
953
|
const indent = visibleWidth(prefix);
|
|
911
954
|
const wrapped = markdown(body, Math.max(1, width - indent), true);
|
|
912
|
-
const rail = !last && indent > 0 ? theme.fg("dim", "
|
|
955
|
+
const rail = !last && indent > 0 ? theme.fg("dim", "\u2502") + " ".repeat(indent - 1) : " ".repeat(indent);
|
|
913
956
|
lines.push(truncateToWidth(prefix + (wrapped[0] ?? ""), width, ""));
|
|
914
957
|
for (const extra of wrapped.slice(1)) lines.push(truncateToWidth(rail + extra, width, ""));
|
|
915
958
|
} else {
|
|
@@ -932,7 +975,7 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
|
|
|
932
975
|
const details = entry.detail.split(/\r?\n/).filter(line => line.trim());
|
|
933
976
|
// ponytail: four diagnostic lines; full output remains in the native transcript.
|
|
934
977
|
lines.push(...details.slice(1, 5).map(line => truncateToWidth(rail + theme.fg("muted", line), width)));
|
|
935
|
-
if (details.length > 5) lines.push(truncateToWidth(rail + theme.fg("muted", `… +${details.length - 5} lines
|
|
978
|
+
if (details.length > 5) lines.push(truncateToWidth(rail + theme.fg("muted", `… +${details.length - 5} lines`), width));
|
|
936
979
|
}
|
|
937
980
|
});
|
|
938
981
|
const agentStartY = lines.length;
|
|
@@ -942,6 +985,11 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
|
|
|
942
985
|
if (c.runId === pinnedSubagentId) pinnedSubagent = { id: c.runId, y: control.y, line: c.line, autoScroll: false };
|
|
943
986
|
}
|
|
944
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
|
+
}
|
|
945
993
|
}
|
|
946
994
|
for (const reply of turn.replies ?? []) lines.push("", ...markdown(reply, width));
|
|
947
995
|
if (turn.final) lines.push("", ...markdown(turn.final, width));
|
|
@@ -1233,7 +1281,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1233
1281
|
else settingsWebOpening ??= (async () => {
|
|
1234
1282
|
const { startSettingsWeb } = await import("../lib/settings-web.ts");
|
|
1235
1283
|
const server = await startSettingsWeb(() => ({
|
|
1236
|
-
settings, defaults: DEFAULT_SETTINGS, order: FOOTER_FIELDS,
|
|
1284
|
+
settings, defaults: DEFAULT_SETTINGS, order: FOOTER_FIELDS, options: FOOTER_STYLE_OPTIONS,
|
|
1237
1285
|
items: settingsItems(settings).filter(item => !isCollapsedReplyChildSetting(item.id)),
|
|
1238
1286
|
// "regular" means minimal output is saved but cannot mount; the page offers a Pi prompt.
|
|
1239
1287
|
tuiMode: lastAttachMode ?? null,
|
|
@@ -1242,8 +1290,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
1242
1290
|
const input = value as Record<string, unknown>;
|
|
1243
1291
|
for (const [key, entry] of Object.entries(input)) {
|
|
1244
1292
|
if (key === "footerOrder") {
|
|
1245
|
-
if (!Array.isArray(entry) ||
|
|
1246
|
-
|| entry.some(id => !(FOOTER_FIELDS as readonly
|
|
1293
|
+
if (!Array.isArray(entry) || new Set(entry).size !== entry.length
|
|
1294
|
+
|| entry.some(id => typeof id !== "string" || !(FOOTER_FIELDS as readonly string[]).includes(id))) throw new TypeError("Invalid order");
|
|
1247
1295
|
} else if (!SETTING_IDS.includes(key as typeof SETTING_IDS[number]) || typeof entry !== "boolean") throw new TypeError("Invalid setting");
|
|
1248
1296
|
}
|
|
1249
1297
|
const next = parseSettings({ ...settings, ...input, onboardingCompleted: true });
|
|
@@ -1275,7 +1323,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1275
1323
|
let choice: string | undefined;
|
|
1276
1324
|
try {
|
|
1277
1325
|
choice = await ctx.ui.select(
|
|
1278
|
-
`Pi Mini Mode ${COPY.preview}\n\n deepseek-v4-flash high ${COPY.totalLabel} 45K ${COPY.
|
|
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}`,
|
|
1279
1327
|
[COPY.keepDefaults, COPY.configureNow, COPY.applyRecommended],
|
|
1280
1328
|
);
|
|
1281
1329
|
} catch (error) {
|
|
@@ -1303,70 +1351,20 @@ export default function (pi: ExtensionAPI) {
|
|
|
1303
1351
|
await persistSettings(ctx);
|
|
1304
1352
|
if (choice === COPY.configureNow) await openSettings(ctx);
|
|
1305
1353
|
};
|
|
1306
|
-
pi.registerCommand("pi-mini-mode-minimal", {
|
|
1307
|
-
description: "Toggle minimal output (off keeps Pi's default conversation history)",
|
|
1308
|
-
handler: async (args, ctx) => {
|
|
1309
|
-
const normalized = args.trim().toLowerCase();
|
|
1310
|
-
if (ctx.mode !== "tui") {
|
|
1311
|
-
ctx.ui.notify(COPY.minimalRequired, "error");
|
|
1312
|
-
return;
|
|
1313
|
-
}
|
|
1314
|
-
if (normalized && normalized !== "on" && normalized !== "off") {
|
|
1315
|
-
ctx.ui.notify(COPY.minimalUsage, "warning");
|
|
1316
|
-
return;
|
|
1317
|
-
}
|
|
1318
|
-
settings = {
|
|
1319
|
-
...settings,
|
|
1320
|
-
"pi-mini-mode-minimal-show": normalized === "on" ? true : normalized === "off" ? false : !settings["pi-mini-mode-minimal-show"],
|
|
1321
|
-
onboardingCompleted: true,
|
|
1322
|
-
};
|
|
1323
|
-
if (settings["pi-mini-mode-minimal-show"]) nativeOutput = false;
|
|
1324
|
-
mountMinimalOutput(ctx);
|
|
1325
|
-
await persistSettings(ctx);
|
|
1326
|
-
if (settings["pi-mini-mode-minimal-show"] && !restoreTranscript) return;
|
|
1327
|
-
ctx.ui.notify(`${COPY.minimalState}${settings["pi-mini-mode-minimal-show"] ? "on" : "off"}`, "info");
|
|
1328
|
-
},
|
|
1329
|
-
});
|
|
1330
|
-
pi.registerCommand("pi-mini-mode-prompts", {
|
|
1331
|
-
description: "Expand or collapse a user prompt in fullscreen minimal output",
|
|
1332
|
-
handler: async (_args, ctx) => {
|
|
1333
|
-
if (ctx.mode !== "tui" || !restoreTranscript || !promptView) {
|
|
1334
|
-
if (ctx.hasUI) ctx.ui.notify("Prompt folding requires fullscreen minimal output.", "info");
|
|
1335
|
-
return;
|
|
1336
|
-
}
|
|
1337
|
-
const view = promptView;
|
|
1338
|
-
const choices = view.promptChoices();
|
|
1339
|
-
if (!choices.length) { ctx.ui.notify("No user prompts exceed four lines at this width.", "info"); return; }
|
|
1340
|
-
const labels = choices.map(choice => `${choice.index + 1}. ${choice.label} · ${preview(choice.question)}`);
|
|
1341
|
-
const selected = await ctx.ui.select("User prompts · Enter to toggle · Esc to cancel", labels);
|
|
1342
|
-
const choice = choices[labels.indexOf(selected ?? "")];
|
|
1343
|
-
if (choice && promptView === view) { view.togglePrompt(choice.index, choice.question); refreshMinimalOutput(); }
|
|
1344
|
-
},
|
|
1345
|
-
});
|
|
1346
|
-
pi.registerCommand("pi-mini-mode-tools", {
|
|
1347
|
-
description: "Expand or collapse a tool's saved text or thinking in fullscreen minimal output",
|
|
1348
|
-
handler: async (_args, ctx) => {
|
|
1349
|
-
if (ctx.mode !== "tui" || !restoreTranscript || !promptView) {
|
|
1350
|
-
if (ctx.hasUI) ctx.ui.notify("Tool folding requires fullscreen minimal output.", "info");
|
|
1351
|
-
return;
|
|
1352
|
-
}
|
|
1353
|
-
const view = promptView;
|
|
1354
|
-
const choices = view.toolChoices();
|
|
1355
|
-
if (!choices.length) { ctx.ui.notify("No visible tool calls. Ctrl+O shows older calls.", "info"); return; }
|
|
1356
|
-
const labels = choices.map((choice, index) => `${index + 1}. ${choice.expanded ? "收起" : "展开"} · ${preview(choice.title)}`);
|
|
1357
|
-
const selected = await ctx.ui.select("Tool results · Enter to toggle · Esc to cancel", labels);
|
|
1358
|
-
const choice = choices[labels.indexOf(selected ?? "")];
|
|
1359
|
-
if (choice && promptView === view) { view.toggleTool(choice.id); refreshMinimalOutput(); }
|
|
1360
|
-
},
|
|
1361
|
-
});
|
|
1362
1354
|
pi.registerCommand("pi-mini-mode-settings", {
|
|
1363
1355
|
description: "Open HTML settings in the browser",
|
|
1364
1356
|
handler: async (_args, ctx) => openSettings(ctx),
|
|
1365
1357
|
});
|
|
1366
1358
|
|
|
1367
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
|
+
};
|
|
1368
1365
|
const loaded = await loadSettings(configPath);
|
|
1369
1366
|
settings = loaded.settings;
|
|
1367
|
+
if (loaded.exists && loaded.backfilled) await persistSettings(ctx);
|
|
1370
1368
|
messageCwd = ctx.cwd;
|
|
1371
1369
|
// 输入增强只在会话中生效,会话开始时再加载;传 getter 让开关变更即时生效,重复调用是幂等的。
|
|
1372
1370
|
const { installInputEnhancements } = await import("../lib/input-enhancements.ts");
|
|
@@ -1391,12 +1389,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
1391
1389
|
mountMinimalOutput(ctx);
|
|
1392
1390
|
});
|
|
1393
1391
|
}
|
|
1394
|
-
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()))];
|
|
1395
1393
|
},
|
|
1396
1394
|
};
|
|
1397
1395
|
});
|
|
1398
1396
|
refresh();
|
|
1399
|
-
if (!
|
|
1397
|
+
if (!settings.onboardingCompleted && ctx.mode === "tui" && ctx.hasUI) await runOnboarding(ctx);
|
|
1400
1398
|
});
|
|
1401
1399
|
const syncMinimalBranch = (_event: unknown, ctx: ExtensionContext) => {
|
|
1402
1400
|
minimalTurns = minimalTurnsFromBranch(ctx.sessionManager.getBranch());
|
|
@@ -1679,3 +1677,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
1679
1677
|
stopSpeedTimer();
|
|
1680
1678
|
});
|
|
1681
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.
|
|
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
|
|
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:
|
|
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)
|
|
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
|
-
|
|
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:
|
|
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)}
|
|
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
|
-
<
|
|
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,10 +22,9 @@
|
|
|
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
|
-
<section><h2 id="featuresHeading"></h2><div class="features" id="features"></div></section>
|
|
24
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>
|
|
25
26
|
<section><h2 id="optionsHeading"></h2><div class="grid" id="options"></div></section>
|
|
27
|
+
<section><h2 id="featuresHeading"></h2><div class="features" id="features"></div></section>
|
|
26
28
|
</main>
|
|
27
29
|
<script>
|
|
28
30
|
const $=id=>document.getElementById(id),token=location.hash.slice(1);
|
|
@@ -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
|
-
|
|
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:'
|
|
42
|
-
{id:'minimal',setting:'pi-mini-mode-minimal-show',title:'极简输出',body:'把对话收成结论:思考、工具与技能汇成一棵按时间排序的可折叠过程树。',points:['
|
|
43
|
-
{id:'input-enhancements',setting:'pi-mini-mode-input-enhancements',title:'输入增强',body:'让输入框和消息里的图片、技能与文件路径直接可用。',points:['
|
|
44
|
-
{id:'themes',title:'明暗主题',body:'
|
|
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
|
|
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
|
|
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
|
|
50
|
-
{id:'themes',title:'Light and dark themes',body:'
|
|
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
|
-
|
|
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
|
-
|
|
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','
|
|
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
|
-
|
|
114
|
-
const visible=order.filter(id=>state[key(id)]);
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
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.
|
|
169
|
+
if(button.parentNode!==panel||nextPreview(button)!==next)panel.insertBefore(button,next);
|
|
170
|
+
next=button;
|
|
128
171
|
}
|
|
129
|
-
if(!visible.length)
|
|
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
|
-
|
|
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
|
-
|
|
159
|
-
card.append(
|
|
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(
|
|
223
|
+
$('options').replaceChildren();$('optionsHeading').hidden=true;$('options').hidden=true;
|
|
177
224
|
preview();
|
|
178
225
|
}
|
|
179
226
|
function renderNotice(){
|
|
@@ -201,9 +248,10 @@ function setLang(next){lang=next;localStorage.piMiniModeLang=lang;render()}
|
|
|
201
248
|
$('lang-zh').onclick=()=>setLang('zh');
|
|
202
249
|
$('lang-en').onclick=()=>setLang('en');
|
|
203
250
|
$('retry').onclick=save;
|
|
204
|
-
|
|
251
|
+
function mergeOrder(base,all){const next=[...new Set((base||[]).filter(id=>(all||[]).includes(id)))];for(const id of all||[])if(!next.includes(id))next.push(id);return next}
|
|
252
|
+
$('reset').onclick=()=>{if(!confirm(t('confirmReset')))return;state={...data.defaults};order=mergeOrder(data.order,data.order);render();change()};
|
|
205
253
|
window.addEventListener('beforeunload',event=>{if(dirty||saving){event.preventDefault();event.returnValue=''}});
|
|
206
254
|
applyLang();status(t('connecting'));
|
|
207
|
-
request('GET').then(value=>{data=value;state={...data.settings};order=
|
|
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));
|
|
208
256
|
</script>
|
|
209
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