@each1024/pi-mini-mode 2.0.8 → 2.0.10

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.
@@ -1,143 +1,26 @@
1
- import { AGENT_STATUS_ENTRY, savedAgentStatuses, retainAgentStatuses, agentChildren, agentCall, agentCallDisplay, agentStatusesByTurn, attachAgentWidgets, isAgentTool, liveAgentView, readAgentStatuses, runningGlyph, type AgentCall } from "../lib/agent-view.ts";
2
- import { CONFIG_DIR_NAME, getAgentDir, getMarkdownTheme, SettingsManager, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
3
- import { attachTranscript, type NoticeRows, type TurnNotices } from "../lib/transcript-adapter.ts";
4
- import { imagePlaceholders, createAssistantImages } from "../lib/assistant-images.ts";
1
+ import { AGENT_STATUS_ENTRY, savedAgentStatuses, retainAgentStatuses, agentChildren, agentCall, agentStatusesByTurn, attachAgentWidgets, readAgentStatuses } from "../lib/agent-view.ts";
2
+ import { getAgentDir, SettingsManager, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { matchesKey, isKeyRelease, isKeyRepeat } from "@earendil-works/pi-tui";
4
+ import { attachTranscript } from "../lib/transcript-adapter.ts";
5
5
  import { installSeamlessScrollbar } from "../lib/seamless-scrollbar.ts";
6
- import { diagramMarkdown, isFencedMarkdown, renderMinimalMarkdown } from "../lib/minimal-markdown.ts";
7
- import { minimalSurface, paintExpandedHeading } from "../lib/minimal-theme.ts";
8
- import { Markdown, matchesKey, isKeyRelease, isKeyRepeat, sliceByColumn, type SettingItem, Text, type TuiMouseEvent, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
9
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
10
6
  import { installInputEnhancements, type InputEnhancementsCleanup } from "../lib/input-enhancements.ts";
11
7
  import { installTerminalCapabilities } from "../lib/terminal-capabilities.ts";
12
- import { linkMessageFiles, linkToolFiles } from "../lib/file-links.ts";
13
- import { homedir } from "node:os";
14
- import { stripVTControlCharacters } from "node:util";
15
- import { thinkingPreview } from "../lib/thinking-preview.ts";
16
- import { basename, dirname, join } from "node:path";
8
+ import { linkMessageFiles } from "../lib/file-links.ts";
17
9
  import attachFooterTidy from "../lib/footer-tidy.ts";
18
10
  import attachTitlePlain from "../lib/title-plain.ts";
19
-
20
- export const SETTINGS_FILE_NAME = "pi-mini-mode.json";
21
-
22
- export interface MiniLensSettings {
23
- "pi-mini-mode-model-show": boolean;
24
- "pi-mini-mode-thinking-show": boolean;
25
- "pi-mini-mode-project-branch-show": boolean;
26
- "pi-mini-mode-branch-show": boolean;
27
- "pi-mini-mode-ch-show": boolean;
28
- "pi-mini-mode-session-tokens-show": boolean;
29
- "pi-mini-mode-cache-tokens-show": boolean;
30
- "pi-mini-mode-cache-miss-show": boolean;
31
- "pi-mini-mode-cost-show": boolean;
32
- "pi-mini-mode-mcp-show": boolean;
33
- "pi-mini-mode-context-show": boolean;
34
- "pi-mini-mode-context-dots-show": boolean;
35
- "pi-mini-mode-context-percent-show": boolean;
36
- "pi-mini-mode-speed-show": boolean;
37
- "pi-mini-mode-speed-unit-show": boolean;
38
- "pi-mini-mode-minimal-show": boolean;
39
- "pi-mini-mode-minimal-record-limit": number;
40
- "pi-mini-mode-input-enhancements": boolean;
41
- "pi-mini-mode-image-preview": "hover" | "inline";
42
- "pi-mini-mode-minimal-thinking-show": boolean;
43
- "pi-mini-mode-minimal-tools-show": boolean;
44
- "pi-mini-mode-minimal-output-show": boolean;
45
- "pi-mini-mode-minimal-skills-show": boolean;
46
- "pi-mini-mode-agent-usage-show": boolean;
47
- "pi-mini-mode-agent-shortcut-show": boolean;
48
- onboardingCompleted: boolean;
49
- footerOrder?: string[];
50
- }
51
-
52
- export const DEFAULT_SETTINGS: Readonly<MiniLensSettings> = {
53
- "pi-mini-mode-model-show": true,
54
- "pi-mini-mode-thinking-show": true,
55
- "pi-mini-mode-project-branch-show": true,
56
- "pi-mini-mode-branch-show": false,
57
- "pi-mini-mode-ch-show": true,
58
- "pi-mini-mode-session-tokens-show": true,
59
- "pi-mini-mode-cache-tokens-show": false,
60
- "pi-mini-mode-cache-miss-show": true,
61
- "pi-mini-mode-cost-show": true,
62
- "pi-mini-mode-mcp-show": false,
63
- "pi-mini-mode-context-show": true,
64
- "pi-mini-mode-context-dots-show": true,
65
- "pi-mini-mode-context-percent-show": true,
66
- "pi-mini-mode-speed-show": true,
67
- "pi-mini-mode-speed-unit-show": true,
68
- "pi-mini-mode-minimal-show": true,
69
- "pi-mini-mode-minimal-record-limit": 6,
70
- "pi-mini-mode-input-enhancements": true,
71
- "pi-mini-mode-image-preview": "inline",
72
- "pi-mini-mode-minimal-thinking-show": true,
73
- "pi-mini-mode-minimal-tools-show": true,
74
- "pi-mini-mode-minimal-output-show": true,
75
- "pi-mini-mode-minimal-skills-show": true,
76
- "pi-mini-mode-agent-usage-show": true,
77
- "pi-mini-mode-agent-shortcut-show": true,
78
- onboardingCompleted: false,
79
- };
80
-
81
- const SETTING_IDS = Object.keys(DEFAULT_SETTINGS) as Array<Exclude<keyof MiniLensSettings, "footerOrder">>;
82
- export const FOOTER_FIELDS = ["project-branch", "model", "thinking", "branch", "session-tokens", "cache-tokens", "cache-miss", "ch", "cost", "mcp", "context", "context-percent", "speed"] as const;
83
- export const FOOTER_STYLE_OPTIONS = ["context-dots", "speed-unit"] as const;
84
-
85
- const COPY = {
86
- title: "Pi Mini Mode 设置", preview: "预览(示例数据)", lens: "设置", minimal: "极简输出",
87
- 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 秒)",
88
- totalDescription: "Total:当前会话分支上的全部 token,含工具上报的 LLM 用量。", cachedDescription: "Cached:累计 cache-read + cache-write token(包含在 Total 中)。", cacheHitDescription: "CH(cache hit):cache-read / (input + cache-read)。Cache write 不计入此比率。",
89
- enableMinimalDescription: "开启统一折叠思考、工具和技能过程;关闭恢复 Pi 默认会话历史。",
90
- inputEnhancementsDescription: "原生 Ctrl+V 粘贴图片(Windows/WSL:Alt+V);图片显示为 [image1] 标签,默认在输入框上方显示内联卡片(可切换光标悬停模式)。空白后 / 选择技能并在光标处插入。Cmd+点击带下划线的图片标签或消息文件路径,用系统默认应用打开;预览及点击需终端支持。关闭仅恢复原生行为。",
91
- 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)", themeSaved: "已保存主题和全屏模式。请重启 Pi 以启用全屏;项目设置或命令行参数可能覆盖全局设置。", themeSaveFailed: "无法保存推荐的 Pi 主题和全屏模式;未完成首次配置。", themeApplyFailed: "推荐设置已保存,但当前主题未能立即应用;请重启 Pi。",
92
- } as const;
93
-
94
- const RECOMMENDED_THEMES = ["cc-dark", "cc-light"] as const;
95
- type RecommendedTheme = typeof RECOMMENDED_THEMES[number];
96
-
97
- export function settingsPath(agentDir = process.env.PI_MINI_MODE_AGENT_DIR ?? join(homedir(), CONFIG_DIR_NAME, "agent")): string {
98
- return join(agentDir, SETTINGS_FILE_NAME);
99
- }
100
-
101
- function isBoolean(value: unknown): value is boolean {
102
- return typeof value === "boolean";
103
- }
104
-
105
- function isRecordLimit(value: unknown): value is number {
106
- return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
107
- }
108
-
109
- export function parseSettings(value: unknown): MiniLensSettings {
110
- const candidate = value && typeof value === "object" ? value as Record<string, unknown> : {};
111
- const settings = { ...DEFAULT_SETTINGS };
112
- for (const id of SETTING_IDS) {
113
- if (id === "pi-mini-mode-image-preview") {
114
- if (candidate[id] === "hover" || candidate[id] === "inline") settings[id] = candidate[id];
115
- } else if (id === "pi-mini-mode-minimal-record-limit") {
116
- if (isRecordLimit(candidate[id])) settings[id] = candidate[id];
117
- } else if (isBoolean(candidate[id])) settings[id] = candidate[id];
118
- }
119
- if (Array.isArray(candidate.footerOrder)) {
120
- settings.footerOrder = [...new Set(candidate.footerOrder.filter((id): id is typeof FOOTER_FIELDS[number] =>
121
- typeof id === "string" && (FOOTER_FIELDS as readonly string[]).includes(id)))];
122
- for (const id of FOOTER_FIELDS) if (!settings.footerOrder.includes(id)) settings.footerOrder.push(id);
123
- }
124
- if (settings["pi-mini-mode-branch-show"]) settings["pi-mini-mode-project-branch-show"] = false;
125
- // 折叠回复的旧细项已合并进极简输出总开关:旧值不再暗中过滤内容,始终按默认全开。
126
- for (const id of LEGACY_MINIMAL_SETTING_IDS) settings[id] = true;
127
- return settings;
128
- }
129
-
130
- /** True when saved JSON is missing a setting or a footer field, so defaults can be written back. */
131
- export function settingsNeedBackfill(raw: unknown, parsed: MiniLensSettings): boolean {
132
- if (!raw || typeof raw !== "object") return true;
133
- const candidate = raw as Record<string, unknown>;
134
- for (const id of SETTING_IDS) {
135
- if (!Object.hasOwn(candidate, id)) return true;
136
- }
137
- if (!Array.isArray(candidate.footerOrder)) return false;
138
- const order = parsed.footerOrder ?? [];
139
- return FOOTER_FIELDS.some(id => !order.includes(id));
140
- }
11
+ import { COPY, DEFAULT_SETTINGS, FOOTER_FIELDS, FOOTER_STYLE_OPTIONS, RECOMMENDED_THEMES, SETTING_IDS, isLegacyMinimalSetting, isRecordLimit, loadSettings, parseSettings, saveSettings, settingsItems, settingsPath, type MiniLensSettings, type RecommendedTheme } from "../lib/settings.ts";
12
+ import { addUsage, cacheWaste, EMPTY_USAGE, finiteNumber, outputSpeed, sessionUsage, type ActiveGeneration, type UsageLike } from "../lib/usage.ts";
13
+ import { statusLine } from "../lib/footer-line.ts";
14
+ import { contentText, minimalTurnsFromBranch, processText, pushProcess, skillNames, type MinimalTurn } from "../lib/minimal-turns.ts";
15
+ import { minimalOutputComponent } from "../lib/minimal-output.ts";
16
+ import { createThinkingStream } from "../lib/thinking-stream.ts";
17
+
18
+ // Preserve the existing module entry points for consumers and focused checks.
19
+ export { SETTINGS_FILE_NAME, DEFAULT_SETTINGS, FOOTER_FIELDS, FOOTER_STYLE_OPTIONS, settingsPath, parseSettings, settingsNeedBackfill, loadSettings, saveSettings, settingsItems, type MiniLensSettings } from "../lib/settings.ts";
20
+ export { cacheWaste, sessionUsage, speedColor, formatSpeed, outputSpeed, DECODE_SPEED_MIN_ELAPSED_MS, DECODE_SPEED_MIN_OUTPUT, type CacheWaste, type SessionUsage, type SpeedColor } from "../lib/usage.ts";
21
+ export { isPlannotatorPlanningStatus, planCapsule, settingsPreviewLine, statusLine } from "../lib/footer-line.ts";
22
+ export { formatElapsed, formatToolElapsed, formatThinkingElapsed, minimalTurnsFromBranch, type MinimalTurn, type ThinkingClock } from "../lib/minimal-turns.ts";
23
+ export { minimalOutputComponent } from "../lib/minimal-output.ts";
141
24
 
142
25
  /** Pi /model and other selectors own Ctrl+S; the editor exposes getText. */
143
26
  export function focusedSelectorOwnsKeys(tui?: { getFocusedComponent?(): unknown } | null): boolean {
@@ -145,23 +28,6 @@ export function focusedSelectorOwnsKeys(tui?: { getFocusedComponent?(): unknown
145
28
  return !!focused && typeof focused === "object" && typeof (focused as { getText?: unknown }).getText !== "function";
146
29
  }
147
30
 
148
- export async function loadSettings(path = settingsPath()): Promise<{ settings: MiniLensSettings; exists: boolean; backfilled: boolean }> {
149
- try {
150
- const raw: unknown = JSON.parse(await readFile(path, "utf8"));
151
- const settings = parseSettings(raw);
152
- return { settings, exists: true, backfilled: settingsNeedBackfill(raw, settings) };
153
- } catch {
154
- return { settings: { ...DEFAULT_SETTINGS }, exists: false, backfilled: false };
155
- }
156
- }
157
-
158
- export async function saveSettings(settings: MiniLensSettings, path = settingsPath()): Promise<void> {
159
- await mkdir(dirname(path), { recursive: true });
160
- const temporaryPath = `${path}.tmp`;
161
- await writeFile(temporaryPath, `${JSON.stringify(settings, null, 2)}\n`, "utf8");
162
- await rename(temporaryPath, path);
163
- }
164
-
165
31
  function enabledMcpServerCount(value: unknown): number | undefined {
166
32
  if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
167
33
  const snapshot = value as { version?: unknown; servers?: unknown };
@@ -176,964 +42,6 @@ function enabledMcpServerCount(value: unknown): number | undefined {
176
42
  return count;
177
43
  }
178
44
 
179
- function formatTokens(value: number): string {
180
- if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
181
- if (value >= 1_000) return `${Math.round(value / 1_000)}K`;
182
- return String(Math.round(value));
183
- }
184
-
185
- function finiteNumber(value: unknown): number | undefined {
186
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
187
- }
188
-
189
- function nonNegative(value: unknown): number {
190
- return Math.max(0, finiteNumber(value) ?? 0);
191
- }
192
-
193
- function formatUsd(value: number): string {
194
- if (value < 0.01) return `$${value.toFixed(4)}`;
195
- if (value < 1) return `$${value.toFixed(3)}`;
196
- return `$${value.toFixed(2)}`;
197
- }
198
-
199
- interface UsageLike {
200
- input?: unknown;
201
- output?: unknown;
202
- cacheRead?: unknown;
203
- cacheWrite?: unknown;
204
- totalTokens?: unknown;
205
- cost?: { total?: unknown };
206
- }
207
-
208
- export interface SessionUsage {
209
- totalTokens: number;
210
- input: number;
211
- output: number;
212
- cacheRead: number;
213
- cacheWrite: number;
214
- cost: number;
215
- }
216
-
217
- const EMPTY_USAGE: SessionUsage = { totalTokens: 0, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 };
218
-
219
- function addUsage(total: SessionUsage, usage: UsageLike | undefined): SessionUsage {
220
- if (!usage) return total;
221
- const input = nonNegative(usage.input);
222
- const output = nonNegative(usage.output);
223
- const cacheRead = nonNegative(usage.cacheRead);
224
- const cacheWrite = nonNegative(usage.cacheWrite);
225
- // totalTokens is the provider's authoritative count. Older/custom tool results
226
- // sometimes omit it, so only then derive a complete count from its components.
227
- const reportedTotal = finiteNumber(usage.totalTokens);
228
- return {
229
- totalTokens: total.totalTokens + Math.max(0, reportedTotal ?? input + output + cacheRead + cacheWrite),
230
- input: total.input + input,
231
- output: total.output + output,
232
- cacheRead: total.cacheRead + cacheRead,
233
- cacheWrite: total.cacheWrite + cacheWrite,
234
- cost: total.cost + nonNegative(usage.cost?.total),
235
- };
236
- }
237
-
238
- export interface CacheWaste {
239
- missedTokens: number;
240
- missCount: number;
241
- }
242
-
243
- /** Same noise floor as Pi's cache-miss notice. Compaction resets the baseline. */
244
- export function cacheWaste(entries: ReadonlyArray<{ type?: unknown; message?: { role?: unknown; usage?: UsageLike } }>): CacheWaste {
245
- let prev = 0;
246
- let reported = false;
247
- const totals = { missedTokens: 0, missCount: 0 };
248
- for (const entry of entries) {
249
- if (entry.type === "compaction" || entry.type === "branch_summary") { prev = 0; continue; }
250
- if (entry.type !== "message" || entry.message?.role !== "assistant") continue;
251
- const usage = entry.message.usage;
252
- const input = nonNegative(usage?.input);
253
- const cacheRead = nonNegative(usage?.cacheRead);
254
- const cacheWrite = nonNegative(usage?.cacheWrite);
255
- const prompt = input + cacheRead + cacheWrite;
256
- if (prev > 0 && prompt > 0 && (cacheRead + cacheWrite > 0 || reported)) {
257
- const missed = Math.min(prev, prompt) - cacheRead;
258
- if (missed > 1024) { totals.missedTokens += missed; totals.missCount++; }
259
- }
260
- if (prompt > 0) { prev = prompt; reported ||= cacheRead + cacheWrite > 0; }
261
- }
262
- return totals;
263
- }
264
-
265
- /** Aggregate persisted, finalized usage once per active-branch entry. */
266
- export function sessionUsage(ctx: ExtensionContext): SessionUsage {
267
- return ctx.sessionManager.getBranch().reduce((total, entry) => {
268
- if (entry.type !== "message") return total;
269
- const message = entry.message as { role?: unknown; usage?: UsageLike };
270
- return message.role === "assistant" || message.role === "toolResult"
271
- ? addUsage(total, message.usage)
272
- : total;
273
- }, { ...EMPTY_USAGE });
274
- }
275
-
276
- function cacheHit(usage: SessionUsage): number | undefined {
277
- const cacheBase = usage.input + usage.cacheRead;
278
- return cacheBase === 0 ? undefined : 100 * usage.cacheRead / cacheBase;
279
- }
280
-
281
- export type SpeedColor = "success" | "warning" | "error" | "muted";
282
-
283
- export function speedColor(speed: number | undefined): SpeedColor {
284
- if (speed === undefined) return "muted";
285
- if (speed >= 30) return "success";
286
- if (speed >= 10) return "warning";
287
- return "error";
288
- }
289
-
290
- export function formatSpeed(speed: number, showUnit: boolean): string {
291
- const value = speed.toFixed(speed >= 100 ? 0 : 1);
292
- return showUnit ? `${value} tok/s` : value;
293
- }
294
-
295
- const PLANNOTATOR_STATUS_KEY = "plannotator";
296
- const PLANNOTATOR_PLANNING_LABEL = "⏸ plan";
297
- const PLAN_CAP_LEFT = "\uE0B6";
298
- const PLAN_CAP_RIGHT = "\uE0B4";
299
- const PLAN_BG = "250;204;21";
300
- const PLAN_FG = "19;18;23";
301
-
302
- function plannotatorStatusText(text: string | undefined): string {
303
- return stripVTControlCharacters(text ?? "").replace(/\s+/g, " ").trim();
304
- }
305
-
306
- /** Exact plannotator planning label from @plannotator/pi-extension (`⏸ plan`). */
307
- export function isPlannotatorPlanningStatus(text: string | undefined): boolean {
308
- return plannotatorStatusText(text) === PLANNOTATOR_PLANNING_LABEL;
309
- }
310
-
311
- /** Scheme B PLAN capsule. visibleWidth===1 only protects columns; it is not a font check. */
312
- export function planCapsule(): string {
313
- const paint = (text: string) => `\x1b[48;2;${PLAN_BG}m\x1b[38;2;${PLAN_FG}m${text}\x1b[39m\x1b[49m`;
314
- if (visibleWidth(PLAN_CAP_LEFT) === 1 && visibleWidth(PLAN_CAP_RIGHT) === 1) {
315
- const cap = (ch: string) => `\x1b[38;2;${PLAN_BG}m${ch}\x1b[39m`;
316
- return `${cap(PLAN_CAP_LEFT)}${paint("PLAN")}${cap(PLAN_CAP_RIGHT)}`;
317
- }
318
- return paint(" PLAN ");
319
- }
320
-
321
- function plannotatorPlanTag(statuses: ReadonlyMap<string, string> | undefined): string {
322
- const text = statuses?.get(PLANNOTATOR_STATUS_KEY);
323
- return isPlannotatorPlanningStatus(text) ? planCapsule() : "";
324
- }
325
-
326
- function progressBar(percent: number, dots: boolean, width: number): string {
327
- const filled = Math.round(width * Math.max(0, Math.min(100, percent)) / 100);
328
- return (dots ? "⣿" : "█").repeat(filled) + (dots ? "⣀" : "░").repeat(width - filled);
329
- }
330
-
331
- function renderRight(
332
- theme: ExtensionContext["ui"]["theme"],
333
- settings: MiniLensSettings,
334
- percentText: string,
335
- speed: number | undefined,
336
- highlighted?: keyof MiniLensSettings,
337
- ): string {
338
- const fields: string[] = [];
339
- if (settings["pi-mini-mode-context-percent-show"] && percentText) fields.push(highlighted === "pi-mini-mode-context-percent-show" ? theme.bg("selectedBg", theme.fg("accent", theme.bold(percentText))) : theme.fg("accent", percentText));
340
- if (settings["pi-mini-mode-speed-show"] && speed !== undefined) {
341
- const text = formatSpeed(speed, settings["pi-mini-mode-speed-unit-show"]);
342
- fields.push(highlighted === "pi-mini-mode-speed-show" || highlighted === "pi-mini-mode-speed-unit-show"
343
- ? theme.bg("selectedBg", theme.fg("accent", theme.bold(text)))
344
- : theme.fg(speedColor(speed), text));
345
- }
346
- return fields.join(" ");
347
- }
348
-
349
- const SETTINGS_PREVIEW_CONTEXT = {
350
- cwd: "/work/pi-mini-mode",
351
- model: { id: "deepseek-v4-flash" },
352
- thinkingLevel: "high",
353
- getContextUsage: () => ({ tokens: 500, contextWindow: 1_000_000, percent: 1 }),
354
- } as unknown as ExtensionContext;
355
-
356
- const SETTINGS_PREVIEW_USAGE: SessionUsage = {
357
- totalTokens: 45_000,
358
- input: 15_000,
359
- output: 5_000,
360
- cacheRead: 10_000,
361
- cacheWrite: 15_000,
362
- cost: 0.012,
363
- };
364
-
365
- export function settingsPreviewLine(
366
- theme: ExtensionContext["ui"]["theme"],
367
- settings: MiniLensSettings,
368
- width = 140,
369
- highlighted?: keyof MiniLensSettings,
370
- ): string {
371
- return statusLine(SETTINGS_PREVIEW_CONTEXT, theme, width, SETTINGS_PREVIEW_USAGE, settings, 120, highlighted, 3, undefined, "main");
372
- }
373
-
374
- export function statusLine(
375
- ctx: ExtensionContext,
376
- theme: ExtensionContext["ui"]["theme"],
377
- width: number,
378
- usageTotals: SessionUsage,
379
- settings: MiniLensSettings,
380
- speed: number | undefined,
381
- highlighted?: keyof MiniLensSettings,
382
- mcpCount?: number,
383
- statuses?: ReadonlyMap<string, string>,
384
- gitBranch?: string | null,
385
- waste?: CacheWaste,
386
- ): string {
387
- if (highlighted === "pi-mini-mode-context-dots-show") highlighted = "pi-mini-mode-context-show";
388
- const field = (id: keyof MiniLensSettings, color: Parameters<typeof theme.fg>[0], text: string) =>
389
- id === highlighted ? theme.bg("selectedBg", theme.fg("accent", theme.bold(text))) : theme.fg(color, text);
390
- if (width <= 0) return "";
391
- const model = ctx.model?.id ?? "";
392
- const thinking = ctx.thinkingLevel ?? "";
393
- const hit = cacheHit(usageTotals);
394
- const hitText = hit === undefined ? "" : `${COPY.cacheHitLabel} ${hit.toFixed(1)}%`;
395
- const cachedTokens = usageTotals.cacheRead + usageTotals.cacheWrite;
396
- const missText = settings["pi-mini-mode-cache-miss-show"] && waste && waste.missCount > 0 ? `Miss ${formatTokens(waste.missedTokens)}` : "";
397
- const price = usageTotals.cost > 0 ? formatUsd(usageTotals.cost) : "";
398
- const contextUsage = ctx.getContextUsage();
399
- const tokens = finiteNumber(contextUsage?.tokens);
400
- const contextWindow = finiteNumber(contextUsage?.contextWindow);
401
- const rawPercent = finiteNumber(contextUsage?.percent);
402
- const percent = rawPercent === undefined ? undefined : Math.max(0, Math.min(100, rawPercent));
403
- const percentText = percent === undefined ? "" : `${Math.round(percent)}%`;
404
- const tokenText = tokens === undefined || contextWindow === undefined ? "" : `${formatTokens(Math.max(0, tokens))}/${formatTokens(Math.max(0, contextWindow))}`;
405
- const showContext = settings["pi-mini-mode-context-show"] && Boolean(tokenText);
406
- const mcpText = settings["pi-mini-mode-mcp-show"] && mcpCount !== undefined ? `◇ MCP ${mcpCount}` : "";
407
- const planTag = plannotatorPlanTag(statuses);
408
- const branchOnly = settings["pi-mini-mode-branch-show"];
409
- const branchSetting = branchOnly ? "pi-mini-mode-branch-show" : "pi-mini-mode-project-branch-show";
410
- const branchText = gitBranch && settings[branchSetting]
411
- ? stripVTControlCharacters(branchOnly ? gitBranch : `${basename(ctx.cwd)}(${gitBranch})`).replace(/[\x00-\x1f\x7f-\x9f]/g, "") : "";
412
-
413
- if (settings.footerOrder) {
414
- const values: Record<string, string> = {
415
- "project-branch": !branchOnly ? branchText : "", branch: branchOnly ? branchText : "",
416
- model, thinking,
417
- "session-tokens": usageTotals.totalTokens > 0 ? `${COPY.totalLabel} ${formatTokens(usageTotals.totalTokens)}` : "",
418
- "cache-tokens": cachedTokens > 0 ? `${COPY.cachedLabel} ${formatTokens(cachedTokens)}` : "",
419
- "cache-miss": missText,
420
- ch: hitText, cost: price, mcp: mcpText,
421
- context: tokenText,
422
- "context-percent": percentText, speed: speed === undefined ? "" : formatSpeed(speed, settings["pi-mini-mode-speed-unit-show"]),
423
- };
424
- const visible = settings.footerOrder.filter(id => settings[`pi-mini-mode-${id}-show` as keyof MiniLensSettings] && values[id]);
425
- const usedWidth = visibleWidth([planTag, ...visible.map(id => values[id])].filter(Boolean).join(" "));
426
- const barWidth = Math.max(0, width - usedWidth - 1);
427
- if (visible.includes("context") && percent !== undefined && barWidth > 0) {
428
- values.context += ` ${progressBar(percent, settings["pi-mini-mode-context-dots-show"], barWidth)}`;
429
- }
430
- return truncateToWidth([planTag, ...settings.footerOrder.map(id => {
431
- const key = `pi-mini-mode-${id}-show` as keyof MiniLensSettings;
432
- const color = id === "speed" ? speedColor(speed) : id === "cache-miss" ? "warning" : id === "model" || id === "context-percent" ? "accent" : "muted";
433
- return settings[key] && values[id] ? field(key, color, values[id]) : "";
434
- })].filter(Boolean).join(" "), width, "…");
435
- }
436
- const right = renderRight(theme, settings, percentText, speed, highlighted);
437
- const rightWidth = visibleWidth(right);
438
- if (right && width <= rightWidth) {
439
- const compactRight = settings["pi-mini-mode-speed-show"] && speed !== undefined
440
- ? theme.fg(speedColor(speed), formatSpeed(speed, settings["pi-mini-mode-speed-unit-show"]))
441
- : right;
442
- return truncateToWidth(compactRight, width, "");
443
- }
444
-
445
- const leftParts = [
446
- planTag,
447
- !branchOnly && branchText && field(branchSetting, "muted", branchText),
448
- settings["pi-mini-mode-model-show"] && model && field("pi-mini-mode-model-show", "accent", model),
449
- settings["pi-mini-mode-thinking-show"] && thinking && field("pi-mini-mode-thinking-show", "muted", thinking),
450
- branchOnly && branchText && field(branchSetting, "muted", branchText),
451
- settings["pi-mini-mode-session-tokens-show"] && usageTotals.totalTokens > 0 && field("pi-mini-mode-session-tokens-show", "text", `${COPY.totalLabel} ${formatTokens(usageTotals.totalTokens)}`),
452
- settings["pi-mini-mode-cache-tokens-show"] && cachedTokens > 0 && field("pi-mini-mode-cache-tokens-show", "text", `${COPY.cachedLabel} ${formatTokens(cachedTokens)}`),
453
- missText && field("pi-mini-mode-cache-miss-show", "warning", missText),
454
- settings["pi-mini-mode-ch-show"] && hitText && field("pi-mini-mode-ch-show", "text", hitText),
455
- settings["pi-mini-mode-cost-show"] && price && field("pi-mini-mode-cost-show", "muted", price),
456
- mcpText && field("pi-mini-mode-mcp-show", "muted", mcpText),
457
- ].filter((part): part is string => Boolean(part));
458
- const unstyledLeft = [
459
- planTag && stripVTControlCharacters(planTag),
460
- !branchOnly && branchText,
461
- settings["pi-mini-mode-model-show"] && model,
462
- settings["pi-mini-mode-thinking-show"] && thinking,
463
- branchOnly && branchText,
464
- settings["pi-mini-mode-session-tokens-show"] && usageTotals.totalTokens > 0 && `${COPY.totalLabel} ${formatTokens(usageTotals.totalTokens)}`,
465
- settings["pi-mini-mode-cache-tokens-show"] && cachedTokens > 0 && `${COPY.cachedLabel} ${formatTokens(cachedTokens)}`,
466
- missText,
467
- settings["pi-mini-mode-ch-show"] && hitText,
468
- settings["pi-mini-mode-cost-show"] && price,
469
- mcpText,
470
- ].filter(Boolean).join(" ");
471
- const leftBudget = Math.min(visibleWidth(unstyledLeft), Math.max(1, width - rightWidth - (showContext ? 20 : 1)), Math.max(0, width - rightWidth - 1));
472
- const left = leftParts.length > 0 ? truncateToWidth(leftParts.join(" "), leftBudget, "…") : "";
473
- const leftWidth = visibleWidth(left);
474
- const middleBudget = showContext ? Math.max(0, width - leftWidth - rightWidth - (left && right ? 4 : left || right ? 1 : 0)) : 0;
475
-
476
- let middle = "";
477
- if (middleBudget > 0) {
478
- const visibleToken = truncateToWidth(tokenText, middleBudget, "…");
479
- const visibleTokenWidth = visibleWidth(visibleToken);
480
- const barWidth = middleBudget - visibleTokenWidth - 1;
481
- const filledCell = settings["pi-mini-mode-context-dots-show"] ? "⣿" : "█";
482
- const emptyCell = settings["pi-mini-mode-context-dots-show"] ? "⣀" : "░";
483
- const bar = barWidth >= 2 && percent !== undefined
484
- ? `${field("pi-mini-mode-context-show", "accent", filledCell.repeat(Math.round(barWidth * percent / 100)))}${field("pi-mini-mode-context-show", "borderMuted", emptyCell.repeat(barWidth - Math.round(barWidth * percent / 100)))}`
485
- : "";
486
- middle = `${field("pi-mini-mode-context-show", "muted", visibleToken)}${bar ? ` ${bar}` : ""}`;
487
- }
488
-
489
- const content = [left, middle].filter(Boolean).join(" ");
490
- if (!right) return truncateToWidth(content, width, "");
491
- const gap = " ".repeat(Math.max(1, width - visibleWidth(content) - rightWidth));
492
- return truncateToWidth(`${content}${content ? gap : ""}${right}`, width, "");
493
- }
494
-
495
- const LEGACY_MINIMAL_SETTING_IDS = [
496
- "pi-mini-mode-minimal-thinking-show", "pi-mini-mode-minimal-tools-show", "pi-mini-mode-minimal-output-show",
497
- "pi-mini-mode-minimal-skills-show", "pi-mini-mode-agent-usage-show", "pi-mini-mode-agent-shortcut-show",
498
- ] as const satisfies ReadonlyArray<keyof MiniLensSettings>;
499
-
500
- export function isCollapsedReplyChildSetting(id: string): boolean {
501
- return (LEGACY_MINIMAL_SETTING_IDS as readonly string[]).includes(id);
502
- }
503
-
504
- export function settingsItems(settings: MiniLensSettings): SettingItem[] {
505
- const values = ["on", "off"];
506
- const labels: Record<Exclude<keyof MiniLensSettings, "onboardingCompleted" | "footerOrder" | "pi-mini-mode-image-preview" | "pi-mini-mode-minimal-record-limit">, string> = {
507
- "pi-mini-mode-project-branch-show": "显示项目名称和分支(互斥)",
508
- "pi-mini-mode-branch-show": "仅显示分支(思考等级后,互斥)",
509
- "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,
510
- };
511
- return (Object.keys(labels) as Array<keyof typeof labels>).map((id) => ({
512
- id, label: labels[id],
513
- description: id === "pi-mini-mode-minimal-show" ? COPY.enableMinimalDescription : id === "pi-mini-mode-input-enhancements" ? COPY.inputEnhancementsDescription : id === "pi-mini-mode-session-tokens-show" ? COPY.totalDescription : id === "pi-mini-mode-cache-tokens-show" ? COPY.cachedDescription : id === "pi-mini-mode-ch-show" ? COPY.cacheHitDescription : undefined,
514
- currentValue: settings[id] ? values[0] : values[1], values,
515
- }));
516
- }
517
-
518
- interface ActiveGeneration {
519
- firstTokenAt?: number;
520
- output: number;
521
- lastSampleAt: number;
522
- }
523
-
524
- /** Hide sub-100ms bursts (batched usage) and 1-token completions; they are not a decode rate. */
525
- export const DECODE_SPEED_MIN_ELAPSED_MS = 100;
526
- export const DECODE_SPEED_MIN_OUTPUT = 2;
527
-
528
- /** Decode TPS: provider `usage.output` / seconds after the first output token (excludes TTFT). */
529
- export function outputSpeed(output: unknown, firstTokenAt: number | undefined, endedAt = Date.now()): number | undefined {
530
- const tokenCount = finiteNumber(output);
531
- if (firstTokenAt === undefined || tokenCount === undefined || tokenCount < DECODE_SPEED_MIN_OUTPUT) return undefined;
532
- const elapsedMs = endedAt - firstTokenAt;
533
- if (elapsedMs < DECODE_SPEED_MIN_ELAPSED_MS) return undefined;
534
- const rate = tokenCount / (elapsedMs / 1_000);
535
- return Number.isFinite(rate) ? rate : undefined;
536
- }
537
-
538
- export interface MinimalTurn {
539
- question: string;
540
- shortcutHintUntil?: number;
541
- usage?: SessionUsage;
542
- pendingUsage?: UsageLike;
543
- agentCalls?: AgentCall[];
544
- subAgents?: Record<string, unknown>[];
545
- process: string[];
546
- final?: string;
547
- replies?: string[];
548
- running?: boolean;
549
- /** Wall-clock start of this user-request execution; retained across tool and thinking turns. */
550
- startedAt?: number;
551
- endedAt?: number;
552
- thinking?: number;
553
- /** Per-process-index Thinking clocks. Live rows count; completed rows keep endedAt. */
554
- thinkingClocks?: Array<ThinkingClock | undefined>;
555
- awaitingResponse?: boolean;
556
- waitingTools?: Array<{ id: string; name: string; startedAt: number }>;
557
- }
558
-
559
- export interface ThinkingClock {
560
- startedAt: number;
561
- endedAt?: number;
562
- }
563
-
564
- const PROCESS_PREVIEW_LIMIT = 180;
565
-
566
- function contentText(content: unknown): string {
567
- if (typeof content === "string") return content.trim();
568
- if (content && typeof content === "object" && "content" in content) return contentText(content.content);
569
- if (!Array.isArray(content)) return "";
570
- return content
571
- .filter((item): item is { type?: string; text?: string } => Boolean(item && typeof item === "object"))
572
- .filter((item) => item.type === "text" && typeof item.text === "string")
573
- .map((item) => item.text!.trim())
574
- .filter(Boolean)
575
- .join("\n");
576
- }
577
-
578
- function preview(value: unknown): string {
579
- let raw = contentText(value);
580
- if (!raw && value !== undefined) {
581
- try { raw = JSON.stringify(value) ?? ""; } catch { raw = String(value); }
582
- }
583
- const text = raw.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, "").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, "").replace(/\s+/g, " ").trim();
584
- return text.length > PROCESS_PREVIEW_LIMIT ? `${text.slice(0, PROCESS_PREVIEW_LIMIT - 1)}…` : text;
585
- }
586
-
587
- function processText(value: unknown): string {
588
- return contentText(value) || (value === undefined ? "" : JSON.stringify(value) ?? "");
589
- }
590
-
591
- /** Format an execution duration without losing hours once a long run crosses one. */
592
- export function formatElapsed(startedAt: number | undefined, now = Date.now()): string {
593
- const seconds = Math.max(0, Math.floor((now - (startedAt ?? now)) / 1_000));
594
- const minutes = Math.floor(seconds / 60);
595
- const remainder = String(seconds % 60).padStart(2, "0");
596
- return minutes >= 60 ? `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, "0")}:${remainder}` : `${minutes}:${remainder}`;
597
- }
598
-
599
- /** Compact tool duration, visible from the start of execution. */
600
- export function formatToolElapsed(startedAt: number | undefined, endedAt = Date.now()): string {
601
- if (startedAt === undefined) return "";
602
- const seconds = Math.max(0, Math.floor((endedAt - startedAt) / 1_000));
603
- if (!seconds) return "1s";
604
- const hours = Math.floor(seconds / 3_600);
605
- const minutes = Math.floor(seconds / 60) % 60;
606
- const remainder = seconds % 60;
607
- return `${hours ? `${hours}h` : ""}${minutes ? `${minutes}m` : ""}${remainder ? `${remainder}s` : ""}`;
608
- }
609
-
610
- function ensureThinkingClock(turn: MinimalTurn, index: number, startedAt = Date.now()): ThinkingClock {
611
- const clocks = turn.thinkingClocks ??= [];
612
- return clocks[index] ??= { startedAt };
613
- }
614
-
615
- function freezeThinkingClock(turn: MinimalTurn | undefined, index: number | undefined, endedAt = Date.now()): void {
616
- if (!turn || index === undefined) return;
617
- const clock = turn.thinkingClocks?.[index];
618
- if (clock && clock.endedAt === undefined) clock.endedAt = endedAt;
619
- }
620
-
621
- function freezeOpenThinkingClocks(turn: MinimalTurn | undefined, endedAt = Date.now()): void {
622
- if (!turn?.thinkingClocks) return;
623
- for (const clock of turn.thinkingClocks) {
624
- if (clock && clock.endedAt === undefined) clock.endedAt = endedAt;
625
- }
626
- }
627
-
628
- /** Each Thinking row counts from its own start and keeps its frozen stop time. */
629
- export function formatThinkingElapsed(
630
- turn: Pick<MinimalTurn, "startedAt" | "thinkingClocks">,
631
- processIndex: number,
632
- active: boolean,
633
- now = Date.now(),
634
- ): string {
635
- const clock = turn.thinkingClocks?.[processIndex];
636
- const startedAt = clock?.startedAt;
637
- if (active && startedAt != null) return `${(Math.max(0, now - startedAt) / 1_000).toFixed(1)}s`;
638
- if (clock?.endedAt != null) return `${(Math.max(0, clock.endedAt - clock.startedAt) / 1_000).toFixed(1)}s`;
639
- return "";
640
- }
641
-
642
- function pushProcess(turn: MinimalTurn | undefined, kind: string, value: unknown): void {
643
- if (!turn) return;
644
- const text = processText(value);
645
- const line = text ? `${kind} ${text}` : kind;
646
- if (turn.process.at(-1) !== line) turn.process.push(line);
647
- }
648
-
649
- function thinkingText(item: Record<string, unknown>): string {
650
- const value = item.thinking ?? item.text;
651
- return typeof value === "string" ? (value.trim() ? value : "") : processText(value);
652
- }
653
-
654
- /** Only adjacent empty blocks in the same assistant content share a row. */
655
- function continuesEmptyThinking(content: Array<Record<string, unknown>>, blockIndex: number): boolean {
656
- const item = content[blockIndex];
657
- const previous = content[blockIndex - 1];
658
- return item?.type === "thinking" && previous?.type === "thinking"
659
- && !thinkingText(item)
660
- && !thinkingText(previous);
661
- }
662
-
663
- function skillNames(text: string): string[] {
664
- const names = new Set<string>();
665
- for (const match of text.matchAll(/\/skill:([\w.-]+)/g)) names.add(match[1]);
666
- for (const match of text.matchAll(/<skill[^>]*?(?:name=["']([^"']+)["']|>\s*<name>([^<]+))/gi)) names.add((match[1] ?? match[2]).trim());
667
- return [...names];
668
- }
669
-
670
- /** pi-loop injects its wakeup as a user message; keep its boilerplate out of the compact card. */
671
- function piLoopSummary(question: string): string | undefined {
672
- if (!question.startsWith("[pi-loop]")) return;
673
- const lines = question.split(/\r?\n/).map(line => line.trim()).filter(Boolean);
674
- const title = lines[0] ?? "[pi-loop]";
675
- const prompt = lines.find(line => line !== title && !line.startsWith("[Self-paced loop:"));
676
- return prompt ? `${title} · ${prompt}` : title;
677
- }
678
-
679
- /** Rebuild turns on the selected session branch. */
680
- export function minimalTurnsFromBranch(branch: readonly unknown[]): MinimalTurn[] {
681
- const turns: MinimalTurn[] = [];
682
- let turn: MinimalTurn | undefined;
683
- for (const rawEntry of branch) {
684
- const entry = rawEntry as { type?: string; message?: { role?: string; content?: unknown; usage?: UsageLike; stopReason?: string; errorMessage?: string } } | null;
685
- if (entry?.type !== "message" || !entry.message) continue;
686
- const { role, content } = entry.message;
687
- if (role === "user") {
688
- const question = contentText(content);
689
- turn = { question: question || "[Attachment]", process: [], running: false };
690
- for (const name of skillNames(question)) pushProcess(turn, "skill", name);
691
- turns.push(turn);
692
- continue;
693
- }
694
- if (!turn) continue;
695
- if (role === "assistant" || role === "toolResult") turn.usage = addUsage(turn.usage ?? EMPTY_USAGE, entry.message.usage);
696
- if (role === "toolResult") {
697
- const result = entry.message as { toolCallId?: string; isError?: boolean };
698
- const call = turn.agentCalls?.find(call => call.id === result.toolCallId);
699
- if (call) {
700
- call.state = result.isError ? "error" : "done";
701
- call.output = contentText(content) || "Call returned (no text output)";
702
- continue;
703
- }
704
- pushProcess(turn, "output", content);
705
- continue;
706
- }
707
- if (role !== "assistant" || !Array.isArray(content)) continue;
708
- if (turn.final) (turn.replies ??= []).push(turn.final);
709
- turn.final = undefined;
710
- for (const [blockIndex, item] of (content as Array<Record<string, unknown>>).entries()) {
711
- if (!item || typeof item !== "object") continue;
712
- if (item.type === "thinking") {
713
- if (!continuesEmptyThinking(content as Array<Record<string, unknown>>, blockIndex)) {
714
- turn.process.push(`thinking ${thinkingText(item)}`);
715
- }
716
- } else if (item.type === "toolCall") {
717
- if (item.name) {
718
- (turn.agentCalls ??= []).push(agentCall(String(item.id), String(item.name), item.arguments ?? item.input));
719
- pushProcess(turn, "call", String(item.id));
720
- const path = (item.arguments as { path?: string })?.path;
721
- if (path && /(?:^|\/)SKILL\.md$/i.test(path)) pushProcess(turn, "skill", path.split("/").at(-2));
722
- continue;
723
- }
724
- pushProcess(turn, `tool ${String(item.name ?? "")}`.trim(), item.arguments ?? item.input);
725
- const path = (item.arguments as { path?: unknown })?.path;
726
- if (typeof path === "string" && /(?:^|\/)SKILL\.md$/i.test(path)) pushProcess(turn, "skill", path.split("/").at(-2) ?? path);
727
- }
728
- }
729
- const text = contentText(content);
730
- const hasTools = content.some((item) => item?.type === "toolCall");
731
- if (hasTools) {
732
- if (text) pushProcess(turn, "output", text);
733
- turn.final = undefined;
734
- } else turn.final = text || undefined;
735
- if (entry.message.stopReason === "error" || entry.message.stopReason === "aborted") {
736
- turn.final = [entry.message.stopReason === "aborted" ? "Execution aborted" : "Execution failed", entry.message.errorMessage, turn.final].filter(Boolean).join("\n");
737
- }
738
- }
739
- return turns;
740
- }
741
-
742
- function visibleMinimalTurns(settings: MiniLensSettings, turns: MinimalTurn[]): MinimalTurn[] {
743
- return turns.map((turn) => {
744
- let thinking: number | undefined;
745
- let visibleCount = 0;
746
- const thinkingClocks: Array<ThinkingClock | undefined> = [];
747
- const process = turn.process.filter((line, index) => {
748
- const visible = line.startsWith("thinking ") ? settings["pi-mini-mode-minimal-thinking-show"]
749
- : /^(tool|call) /.test(line) ? settings["pi-mini-mode-minimal-tools-show"]
750
- : line.startsWith("output ") ? settings["pi-mini-mode-minimal-output-show"]
751
- : line.startsWith("skill ") ? settings["pi-mini-mode-minimal-skills-show"] : true;
752
- if (visible) {
753
- if (turn.thinkingClocks?.[index]) thinkingClocks[visibleCount] = turn.thinkingClocks[index];
754
- if (index === turn.thinking) thinking = visibleCount;
755
- visibleCount++;
756
- }
757
- return visible;
758
- });
759
- return {
760
- ...turn,
761
- thinking,
762
- awaitingResponse: turn.awaitingResponse && settings["pi-mini-mode-minimal-thinking-show"],
763
- agentCalls: settings["pi-mini-mode-minimal-tools-show"] ? turn.agentCalls : [],
764
- process,
765
- thinkingClocks: turn.thinkingClocks ? thinkingClocks : undefined,
766
- };
767
- });
768
- }
769
-
770
- export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], getTurns: () => MinimalTurn[], isExpanded: () => boolean = () => false, showShortcut: (turn: MinimalTurn) => boolean = () => true, showUsage: () => boolean = () => true, subAgentsExpanded: () => boolean = () => false, agentDeadlines = new Map<string, number>(), transformText: (text: string) => string = text => text, imageOptions?: { cwd(): string; requestRender(): void; write?(data: string): void }, getRecordLimit: () => number = () => DEFAULT_SETTINGS["pi-mini-mode-minimal-record-limit"]) {
771
- const placeholderText = (text: string) => imageOptions ? imagePlaceholders(text, imageOptions.cwd()) : text;
772
- const markdown = (text: string, width: number, process = false) => renderMinimalMarkdown(text, width, getMarkdownTheme(), theme.getBgAnsi?.("userMessageBg") ?? "",
773
- { color: (value) => theme.fg(process ? "muted" : "text", value) }, (source, available) => transformText(placeholderText(diagramMarkdown(source, available))));
774
- const assistantImages = imageOptions && createAssistantImages(imageOptions.cwd, imageOptions.requestRender, imageOptions.write);
775
- const assistantMarkdown = (text: string, width: number, owner: string) => assistantImages ? assistantImages.render(text, width, markdown, owner) : markdown(text, width);
776
- const surface = (rows: string[], width: number, user: boolean, selected = -1, expanded = false) => {
777
- const padding = Math.min(2, Math.floor((width - 1) / 2));
778
- return ["", ...rows, ""].map((row, index) => {
779
- const line = truncateToWidth(" ".repeat(padding) + row, width, "");
780
- return minimalSurface(theme, line + " ".repeat(Math.max(0, width - visibleWidth(line))), user, expanded && index === selected);
781
- });
782
- };
783
- let agentExpiry = Infinity;
784
- const expandedPrompts = new Map<number, string>();
785
- const expandedSubagents = new Set<string>();
786
- const expandedTools = new Set<string>();
787
- const expandedThinking = new Set<string>();
788
- const thinkingPreviews = new Map<string, { text: string; width: number; rows: number; updatedAt: number }>();
789
- const agentModes = new Map<number, "all" | "preview" | "closed">();
790
- const runningTurns = new Set<number>();
791
- let pinnedToolId: string | undefined;
792
- let pinnedTool: { id: string; y: number; line: string } | undefined;
793
- let pinnedAgentIndex: number | undefined;
794
- let pinnedAgent: { index: number; y: number; line: string } | undefined;
795
- let pinnedSubagentId: string | undefined;
796
- let pinnedSubagent: { id: string; y: number; line: string; autoScroll?: boolean } | undefined;
797
- let toolControls: Array<{ id: string; y: number; width: number; title: string }> = [];
798
- let agentControls: Array<{ index: number; y: number; width: number }> = [];
799
- let hoveredTool: typeof toolControls[number] | undefined;
800
- const clearHover = () => { const changed = !!hoveredTool; hoveredTool = undefined; return changed; };
801
- const toggleTool = (id: string) => {
802
- if (id.startsWith("thinking:")) {
803
- const present = getTurns().some((turn, turnIndex) => turn.process.some((entry, processIndex) =>
804
- entry.startsWith("thinking") && `thinking:${turnIndex}:${processIndex}` === id));
805
- if (!present) return;
806
- if (expandedThinking.has(id)) expandedThinking.delete(id);
807
- else expandedThinking.add(id);
808
- clearHover();
809
- return;
810
- }
811
- if (id.startsWith("agents:")) {
812
- const index = Number(id.slice(7));
813
- if (!Number.isInteger(index) || !getTurns()[index]) return;
814
- const all = (agentModes.get(index) ?? (isExpanded() ? "all" : "preview")) === "all";
815
- agentModes.set(index, all ? "preview" : "all");
816
- if (all) { expandedThinking.clear(); expandedTools.clear(); expandedSubagents.clear(); }
817
- pinnedAgentIndex = all ? undefined : index;
818
- clearHover();
819
- return;
820
- }
821
- if (!getTurns().some(turn => turn.agentCalls?.some(call => call.id === id && !isAgentTool(call.tool ?? call.name)))) return;
822
- if (expandedTools.has(id)) {
823
- expandedTools.delete(id);
824
- if (pinnedToolId === id) pinnedToolId = undefined;
825
- } else {
826
- expandedTools.add(id);
827
- // Only the latest opened tool owns the sticky heading; others stay open.
828
- pinnedToolId = id;
829
- }
830
- clearHover();
831
- };
832
- const toggleSubagent = (runId: string) => {
833
- if (!subagentControls.some(control => control.runId === runId)) return;
834
- if (expandedSubagents.has(runId)) {
835
- expandedSubagents.delete(runId);
836
- if (pinnedSubagentId === runId) pinnedSubagentId = undefined;
837
- } else {
838
- expandedSubagents.add(runId);
839
- // SubAgent details open in place; sticky heading engages only after scrolling.
840
- pinnedSubagentId = runId;
841
- }
842
- };
843
- let promptControls: Array<{ index: number; question: string; y: number; x: number; width: number; label: string }> = [];
844
- let subagentControls: Array<{ runId: string; y: number; width: number; line: string }> = [];
845
- let noticeRegions: Array<{ y: number; rows: NoticeRows }> = [];
846
- const togglePrompt = (index: number, question: string) => {
847
- if (getTurns()[index]?.question !== question) return;
848
- if (expandedPrompts.get(index) === question) expandedPrompts.delete(index);
849
- else expandedPrompts.set(index, question);
850
- };
851
- return {
852
- dispose() { assistantImages?.dispose(); },
853
- invalidate() { clearHover(); },
854
- resetProcessView() {
855
- agentModes.clear(); expandedThinking.clear(); expandedTools.clear(); expandedSubagents.clear();
856
- thinkingPreviews.clear();
857
- pinnedToolId = undefined; pinnedAgentIndex = undefined; pinnedSubagentId = undefined;
858
- },
859
- clearHover,
860
- pinnedTool: () => pinnedTool,
861
- unpinTool: () => { pinnedToolId = undefined; pinnedTool = undefined; },
862
- pinnedAgent: () => pinnedAgent,
863
- unpinAgent: () => { pinnedAgentIndex = undefined; pinnedAgent = undefined; },
864
- pinnedSubagent: () => pinnedSubagent,
865
- unpinSubagent: () => { pinnedSubagentId = undefined; pinnedSubagent = undefined; },
866
- toolChoices: () => toolControls.map(control => ({ ...control, expanded: expandedTools.has(control.id) || expandedThinking.has(control.id) })),
867
- toggleTool,
868
- toggleSubagent,
869
- agentExpiry: () => agentExpiry,
870
- promptChoices: () => promptControls.map(control => ({ ...control })),
871
- togglePrompt,
872
- handleMouse(event: TuiMouseEvent) {
873
- const tool = toolControls.find(control => event.y === control.y && event.x >= 2 && event.x < Math.min(5, control.width));
874
- if (event.type === "move") {
875
- const next = !event.shift && !event.ctrl && !event.alt ? tool : undefined;
876
- if (hoveredTool?.id !== next?.id) {
877
- hoveredTool = next;
878
- return { handled: true, render: true };
879
- }
880
- return;
881
- }
882
- if (event.type === "wheel" || event.type === "drag") { clearHover(); return; }
883
- if (tool && event.button === "left" && !event.shift && !event.ctrl && !event.alt) {
884
- if (event.type === "press") return { handled: true };
885
- if (event.type === "click") {
886
- toggleTool(tool.id);
887
- return { handled: true, render: true };
888
- }
889
- }
890
- if (event.button !== "left" || event.shift || event.ctrl || event.alt) return;
891
- const agent = agentControls.find(control => event.y === control.y && event.x >= 0 && event.x < control.width);
892
- if (agent && (event.clickCount ?? 1) === 1) {
893
- if (event.type === "press") return { handled: true };
894
- if (event.type === "click") {
895
- const all = (agentModes.get(agent.index) ?? (isExpanded() ? "all" : "preview")) === "all";
896
- agentModes.set(agent.index, all ? "preview" : "all");
897
- if (all) { expandedThinking.clear(); expandedTools.clear(); expandedSubagents.clear(); }
898
- pinnedAgentIndex = all ? undefined : agent.index;
899
- return { handled: true, render: true };
900
- }
901
- }
902
- const control = promptControls.find(control => event.y === control.y && event.x >= control.x && event.x < control.x + control.width);
903
- if (control && (event.clickCount ?? 1) === 1) {
904
- if (event.type === "press") return { handled: true };
905
- if (event.type === "click") {
906
- togglePrompt(control.index, control.question);
907
- return { handled: true, render: true };
908
- }
909
- }
910
- const sub = subagentControls.find(control => event.y === control.y && event.x >= 0 && event.x < control.width);
911
- if (sub) {
912
- if (event.type === "press") return { handled: true };
913
- if (event.type === "click") {
914
- toggleSubagent(sub.runId);
915
- return { handled: true, render: true };
916
- }
917
- }
918
- if ((event.clickCount ?? 1) !== 1) return;
919
- const region = noticeRegions.find(region => event.y >= region.y && event.y < region.y + region.rows.length);
920
- return region?.rows.handleMouse?.({ ...event, y: event.y - region.y });
921
- },
922
- render(width: number, notices?: TurnNotices): string[] {
923
- promptControls = [];
924
- toolControls = [];
925
- agentControls = [];
926
- pinnedTool = undefined;
927
- pinnedAgent = undefined;
928
- pinnedSubagent = undefined;
929
- subagentControls = [];
930
- noticeRegions = [];
931
- agentExpiry = Infinity;
932
- if (width <= 0) { clearHover(); return []; }
933
- const turns = getTurns();
934
- const toolIds = new Set(turns.flatMap(turn => (turn.agentCalls ?? []).map(call => call.id)));
935
- for (const id of expandedTools) if (!toolIds.has(id)) expandedTools.delete(id);
936
- const thinkingIds = new Set(turns.flatMap((turn, turnIndex) => turn.process.flatMap((entry, processIndex) =>
937
- entry.startsWith("thinking") ? [`thinking:${turnIndex}:${processIndex}`] : [])));
938
- for (const id of expandedThinking) if (!thinkingIds.has(id)) expandedThinking.delete(id);
939
- for (const id of thinkingPreviews.keys()) if (!thinkingIds.has(id)) thinkingPreviews.delete(id);
940
- const inner = Math.max(1, width - 2 * Math.min(2, Math.floor((width - 1) / 2)));
941
- const lines: string[] = [];
942
- // An open heading wears the same full-width selectedBg band as an expanded SubAgent row.
943
- const bandHeading = (row: string, open: boolean) => open
944
- ? paintExpandedHeading(theme, row + " ".repeat(Math.max(0, width - visibleWidth(row)))) : row;
945
- for (const [index, turn] of turns.entries()) {
946
- if (index > 0) lines.push("");
947
- if (expandedPrompts.has(index) && expandedPrompts.get(index) !== turn.question) expandedPrompts.delete(index);
948
- const noticeRows = notices?.get(index) ?? [];
949
- const questionRows = markdown(turn.question, inner);
950
- const loopSummary = piLoopSummary(turn.question);
951
- const expanded = expandedPrompts.get(index) === turn.question;
952
- // A fence is one visual unit; slicing it mid-block looks like raw source.
953
- const keepFence = !loopSummary && isFencedMarkdown(turn.question);
954
- // Loop wakeups are system-generated user messages. Collapse them even when
955
- // their short prompt would otherwise fit the normal four-row allowance.
956
- const userRows = expanded || keepFence ? [...questionRows] : loopSummary ? markdown(loopSummary, inner) : questionRows.slice(0, 4);
957
- let controlIndex = -1;
958
- if (!keepFence && (loopSummary || questionRows.length > 4)) {
959
- const label = expanded ? "▴ 收起" : loopSummary ? "▾ 展开" : `▾ 展开 (${questionRows.length} 行)`;
960
- const control = truncateToWidth(label, inner, "");
961
- promptControls.push({ index, question: turn.question, y: lines.length + 1 + userRows.length,
962
- x: 0, width, label });
963
- userRows.push(theme.fg("accent", control));
964
- // The expanded control is this message's heading, so it keeps the band in place of the user surface.
965
- controlIndex = userRows.length;
966
- }
967
- lines.push(...surface(userRows, width, true, controlIndex, expanded));
968
- const entries = turn.process.flatMap((entry, processIndex) => {
969
- if (entry.startsWith("call ")) {
970
- const call = turn.agentCalls?.find(call => call.id === entry.slice(5));
971
- if (call && isAgentTool(call.tool ?? call.name)) return [];
972
- const display = call && agentCallDisplay(call);
973
- return call && display ? [{ title: `${isAgentTool(call.tool ?? call.name) ? "Control" : call.name} ${display.summary}`.trim(), detail: display.detail, state: call.state, id: call.id, thinking: false, processIndex, activeThinking: false }] : [];
974
- }
975
- const part = entry.match(/^(tool|output|thinking|skill)(?:\s+|$)([\s\S]*)/);
976
- const thinking = part?.[1] === "thinking";
977
- const activeThinking = thinking && turn.running && turn.thinking === processIndex;
978
- const label = ({ tool: "Tool", output: "Output", thinking: "Thinking", skill: "Skill" } as Record<string, string>)[part?.[1] ?? ""] ?? "Process";
979
- return [{ title: `${label} ${part?.[2] ?? entry}`, detail: part?.[2] ?? entry, state: activeThinking ? "running" : "done", id: thinking ? `thinking:${index}:${processIndex}` : "", thinking, processIndex, activeThinking }];
980
- });
981
- // Older in-memory turns may predate call markers.
982
- for (const call of turn.agentCalls ?? []) {
983
- if (isAgentTool(call.tool ?? call.name)) continue;
984
- const display = agentCallDisplay(call);
985
- if (!entries.some(entry => entry.id === call.id)) entries.push({ title: `${isAgentTool(call.tool ?? call.name) ? "Control" : call.name} ${display.summary}`, detail: display.detail, state: call.state, id: call.id, thinking: false, processIndex: -1, activeThinking: false });
986
- }
987
- const agentTurnControls: Array<{ runId: string; y: number; width: number; line: string }> = [];
988
- const agents = liveAgentView(turn.subAgents ?? [], theme, width, subAgentsExpanded(), true, agentDeadlines, Date.now(), expandedSubagents, agentTurnControls);
989
- const active = !!turn.running || agents.running > 0 || entries.some(entry => entry.state === "running") || (turn.waitingTools?.length ?? 0) > 0;
990
- if (active) runningTurns.add(index);
991
- else if (runningTurns.delete(index)) {
992
- // Return to the configured preview once; a later click can expand everything again.
993
- if (agentModes.get(index) === "all") {
994
- agentModes.set(index, "preview");
995
- expandedThinking.clear();
996
- expandedTools.clear();
997
- expandedSubagents.clear();
998
- if (pinnedAgentIndex === index) pinnedAgentIndex = undefined;
999
- }
1000
- }
1001
- if (entries.length || active || turn.usage || agents.total) {
1002
- const mode = agentModes.get(index) ?? (isExpanded() ? "all" : "preview");
1003
- const expanded = mode === "all";
1004
- const busy = entries.some(entry => entry.state === "running") || (turn.waitingTools?.length ?? 0) > 0;
1005
- const working = turn.running && !busy && !turn.final;
1006
- // Every child keeps its heading; process records share the remaining preview budget.
1007
- const processLimit = Math.max(0, getRecordLimit() - agents.total);
1008
- const shown = mode === "closed" ? [] : expanded ? entries : processLimit ? entries.slice(-processLimit) : [];
1009
- const showWorking = working && (expanded || (!shown.length && !agents.total));
1010
- const done = entries.filter(entry => entry.state === "done").length;
1011
- // ponytail: two terminal text frames; use Pi's motion preference if it exposes one.
1012
- const sparkle = active ? Math.floor(Date.now() / 360) % 2 ? "✧" : "✦" : "✦";
1013
- const steps = entries.length
1014
- ? theme.fg("muted", done === entries.length ? ` · 完成 共 ${entries.length} 步` : ` · 第 ${Math.min(entries.length, done + 1)} 步`)
1015
- : "";
1016
- const subagents = agents.total
1017
- ? theme.fg("muted", " · ") + theme.bold(theme.fg("text", "子代理")) + theme.fg("muted", ` ${agents.done + agents.errors}/${agents.total}`)
1018
- + (agents.errors ? theme.fg("error", ` · ${agents.errors} 失败`) : "")
1019
- : "";
1020
- const usage = addUsage({ ...EMPTY_USAGE, ...turn.usage, cost: turn.usage?.cost ?? 0 }, turn.pendingUsage);
1021
- const hasUsage = usage.totalTokens > 0 || usage.cacheRead > 0;
1022
- const totals = hasUsage
1023
- ? theme.fg("muted", "会话 ") + theme.bold(theme.fg("text", formatTokens(usage.totalTokens)))
1024
- + theme.fg("muted", " · 缓存 ") + theme.bold(theme.fg("text", formatTokens(usage.cacheRead)))
1025
- : "";
1026
- const recordCount = entries.length + agents.total;
1027
- const progressHeader = theme.fg(active ? "accent" : "muted", sparkle + " ") + theme.bold(theme.fg("text", "Agent")) + theme.fg("muted", recordCount ? ` · ${recordCount}` : "");
1028
- const showAgentRows = agents.total > 0;
1029
- const caret = theme.fg("muted", expanded ? " ▾" : " ▸");
1030
- const elapsedHeader = turn.startedAt == null ? "" : theme.fg("muted", " · ") + theme.fg(active ? "success" : "muted", formatElapsed(turn.startedAt, turn.endedAt ?? Date.now()));
1031
- const left = progressHeader + elapsedHeader + caret;
1032
- const showTotals = hasUsage && showUsage() && visibleWidth(left) + 2 + visibleWidth(totals) <= width;
1033
- agentControls.push({ index, y: lines.length + 1, width: Math.min(width, visibleWidth(left)) });
1034
- if (expanded && pinnedAgentIndex === index) pinnedAgent = { index, y: lines.length + 1, line: truncateToWidth(left, width) };
1035
- lines.push("", showTotals
1036
- ? left + " ".repeat(width - visibleWidth(left) - visibleWidth(totals)) + totals
1037
- : truncateToWidth(left, width));
1038
- shown.forEach((entry, row) => {
1039
- const title = entry.title;
1040
- const text = title.split(/\r?\n/).find(line => line.trim())?.replace(/\s+/g, " ").trim() ?? "";
1041
- const split = text.indexOf(" ");
1042
- const label = split < 0 ? text : text.slice(0, split);
1043
- const body = split < 0 ? "" : text.slice(split + 1);
1044
- const activeThinking = !!entry.activeThinking;
1045
- const elapsed = entry.thinking ? formatThinkingElapsed(turn, entry.processIndex, activeThinking) : "";
1046
- const thinkingElapsed = elapsed ? theme.fg(activeThinking ? "success" : "muted", ` ${elapsed}`) : "";
1047
- const call = turn.agentCalls?.find(call => call.id === entry.id && !isAgentTool(call.tool ?? call.name));
1048
- const controlId = call?.id ?? (entry.thinking || entry.id.startsWith("agents:") ? entry.id : "");
1049
- const open = call ? expandedTools.has(call.id) : entry.thinking && expandedThinking.has(entry.id);
1050
- const identity = open || activeThinking ? "accent" : "text";
1051
- const duration = call ? formatToolElapsed(call.startedAt, call.endedAt ?? Date.now()) : "";
1052
- const toolElapsed = duration ? theme.fg(call?.state === "running" ? "accent" : "muted", ` ${duration}`) : "";
1053
- const summary = theme.fg(identity, theme.bold(label)) + thinkingElapsed + toolElapsed + " ";
1054
- if (controlId && width >= 4) toolControls.push({ id: controlId, y: lines.length, width, title: text });
1055
- if (hoveredTool?.id === controlId && (hoveredTool.y !== lines.length || hoveredTool.width !== width)) clearHover();
1056
- const status = entry.state === "error" ? "✕" : entry.state === "running" ? runningGlyph() : "●";
1057
- const arrow = !!controlId && (open || hoveredTool?.id === controlId);
1058
- const keepStatus = entry.state === "running" || (open && entry.state === "error");
1059
- const glyph = arrow ? (open ? "▼" : "▶") + (keepStatus ? ` ${status}` : "") : status;
1060
- const glyphColor = entry.state === "error" ? "error" : entry.state === "running" || arrow ? "accent" : "muted";
1061
- const last = row === shown.length - 1 && !showWorking && !agents.rows.length;
1062
- const prefix = theme.fg(open ? "accent" : "dim", "│ ") + (entry.state === "running" || entry.state === "error" || arrow ? theme.fg(glyphColor, glyph) + " " : "") + summary;
1063
- if (label === "Output") {
1064
- // Wrapped output hangs under the body column and keeps the tree rail to the next sibling.
1065
- const indent = visibleWidth(prefix);
1066
- const rail = !last && indent > 0 ? theme.fg("dim", "\u2502") + " ".repeat(indent - 1) : " ".repeat(indent);
1067
- const wrapped = markdown(body, Math.max(1, width - indent), true);
1068
- lines.push(truncateToWidth(prefix + (wrapped[0] ?? ""), width, ""));
1069
- for (const extra of wrapped.slice(1)) lines.push(truncateToWidth(rail + extra, width, ""));
1070
- } else {
1071
- const available = Math.max(0, width - visibleWidth(prefix));
1072
- if (entry.thinking) {
1073
- const now = Date.now();
1074
- const cached = thinkingPreviews.get(entry.id);
1075
- const previewRows = open ? 1 : 2;
1076
- const reuse = activeThinking && cached?.text && cached.width === available && cached.rows === previewRows && now - cached.updatedAt < 350;
1077
- const display = reuse ? cached.text : thinkingPreview(entry.detail, available, previewRows);
1078
- if (!reuse) thinkingPreviews.set(entry.id, { text: display, width: available, rows: previewRows, updatedAt: now });
1079
- const fallback = activeThinking ? "等待模型返回思考内容" : "模型未提供可显示的思考内容";
1080
- const rows = new Text(display || fallback, 0, 0).render(Math.max(1, available)).slice(0, open ? 1 : 2);
1081
- const color = activeThinking ? "accent" : "muted";
1082
- lines.push(bandHeading(truncateToWidth(prefix + theme.fg(color, rows[0] ?? ""), width, ""), open));
1083
- const rail = theme.fg(last ? color : "dim", last ? " " : "│") + " ".repeat(Math.max(0, visibleWidth(prefix) - 1));
1084
- for (const extra of rows.slice(1)) lines.push(truncateToWidth(rail + theme.fg(color, extra), width, ""));
1085
- } else {
1086
- const displayBody = placeholderText(body);
1087
- const compactBody = linkToolFiles(displayBody, imageOptions?.cwd() ?? process.cwd(), !open);
1088
- const fittedBody = visibleWidth(compactBody) > available && !open && available > 1
1089
- ? "…" + sliceByColumn(compactBody, visibleWidth(compactBody) - available + 1, available - 1, true)
1090
- : truncateToWidth(compactBody, available, "…");
1091
- // sliceByColumn may end before OSC 8's closing sequence.
1092
- const styledBody = theme.fg(open ? "accent" : "muted", fittedBody + "\x1b]8;;\x07");
1093
- lines.push(bandHeading(truncateToWidth(prefix + styledBody, width, "…"), open));
1094
- }
1095
- }
1096
- if (open && call && call.id === pinnedToolId) pinnedTool = { id: call.id, y: lines.length - 1, line: lines.at(-1)! };
1097
- if (open && call) {
1098
- // ponytail: saved text only; native view retains images, args and custom renderers.
1099
- const output = stripVTControlCharacters(call.output ?? "").replace(/\r\n?/g, "\n").replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "");
1100
- const rail = width > 5 ? (last ? " " : theme.fg("accent", "│ ")) : "";
1101
- const detailWidth = Math.max(1, width - visibleWidth(rail));
1102
- const details = new Text(output || (entry.state === "running" ? "等待工具文本结果…" : "无文本结果"), 0, 0).render(detailWidth);
1103
- lines.push(...details.map(line => truncateToWidth(rail + theme.fg("muted", line), width, "")));
1104
- } else if (open && entry.thinking) {
1105
- const rail = width > 5 ? (last ? " " : theme.fg("accent", "│ ")) : "";
1106
- const detailWidth = Math.max(1, width - visibleWidth(rail));
1107
- lines.push(...markdown(entry.detail, detailWidth, true).map(line => truncateToWidth(rail + line, width, "")));
1108
- }
1109
- });
1110
- if (showAgentRows) {
1111
- const agentStartY = lines.length;
1112
- for (const c of agentTurnControls) {
1113
- const control = { ...c, y: agentStartY + c.y };
1114
- subagentControls.push(control);
1115
- if (c.runId === pinnedSubagentId) pinnedSubagent = { id: c.runId, y: control.y, line: c.line, autoScroll: false };
1116
- }
1117
- lines.push(...agents.rows);
1118
- }
1119
- if (showWorking) {
1120
- const label = turn.awaitingResponse && !shown.length ? "Thinking" : "Working";
1121
- const prefix = theme.fg("dim", "└─ ") + theme.fg("accent", `${runningGlyph()} `) + theme.fg("text", theme.bold(label)) + " ";
1122
- lines.push(truncateToWidth(prefix + theme.fg("muted", turn.awaitingResponse ? "等待模型响应" : "等待下一步执行"), width, ""));
1123
- }
1124
- }
1125
- for (const [replyIndex, reply] of (turn.replies ?? []).entries()) lines.push("", ...assistantMarkdown(reply, width, `reply:${index}:${replyIndex}`));
1126
- if (turn.final) lines.push("", ...assistantMarkdown(turn.final, width, `final:${index}`));
1127
- noticeRegions.push({ y: lines.length, rows: noticeRows });
1128
- lines.push(...noticeRows);
1129
- }
1130
- if (hoveredTool && !toolControls.some(control => control.id === hoveredTool!.id)) clearHover();
1131
- for (const deadline of agentDeadlines.values()) if (deadline > Date.now()) agentExpiry = Math.min(agentExpiry, deadline);
1132
- return lines;
1133
- },
1134
- };
1135
- }
1136
-
1137
45
  export default function (pi: ExtensionAPI) {
1138
46
  const restoreTerminalCapabilities = installTerminalCapabilities();
1139
47
  pi.on("session_shutdown", restoreTerminalCapabilities);
@@ -1146,7 +54,6 @@ export default function (pi: ExtensionAPI) {
1146
54
  let processExpanded = false;
1147
55
  let nativeOutput = false;
1148
56
  let subAgentsExpanded = false;
1149
- let shortcutTimer: ReturnType<typeof setTimeout> | undefined;
1150
57
  let waitingTimer: ReturnType<typeof setInterval> | undefined;
1151
58
  let unsubscribeMinimalInput: (() => void) | undefined;
1152
59
  let minimalTui: { getFocusedComponent?(): unknown } | undefined;
@@ -1163,7 +70,7 @@ export default function (pi: ExtensionAPI) {
1163
70
  let minimalTurns: MinimalTurn[] = [];
1164
71
  let activeMinimalTurn: MinimalTurn | undefined;
1165
72
  let pendingMinimalFinal = "";
1166
- const minimalMessageIndices = new Map<number, number>();
73
+ const thinkingStream = createThinkingStream();
1167
74
  let speed: number | undefined;
1168
75
  let mcpCount: number | undefined;
1169
76
  let activeGeneration: ActiveGeneration | undefined;
@@ -1183,8 +90,6 @@ export default function (pi: ExtensionAPI) {
1183
90
  const refreshMinimalOutput = () => refreshMinimal?.();
1184
91
  const mountMinimalOutput = (ctx: ExtensionContext) => {
1185
92
  persistAgentStatuses = undefined;
1186
- if (shortcutTimer) clearTimeout(shortcutTimer);
1187
- shortcutTimer = undefined;
1188
93
  if (waitingTimer) clearInterval(waitingTimer);
1189
94
  waitingTimer = undefined;
1190
95
  unsubscribeMinimalInput?.();
@@ -1264,16 +169,11 @@ export default function (pi: ExtensionAPI) {
1264
169
  return { ...turn, subAgents: withNotices };
1265
170
  });
1266
171
  };
1267
- const view = minimalOutputComponent(theme, () => visibleMinimalTurns(settings, turnsWithAgents()), () => processExpanded, turn => settings["pi-mini-mode-agent-shortcut-show"] && Date.now() < (turn.shortcutHintUntil ?? 0), () => settings["pi-mini-mode-agent-usage-show"], () => subAgentsExpanded, agentDeadlines, messageLinks, {
172
+ const view = minimalOutputComponent(theme, turnsWithAgents, () => processExpanded, () => true, () => subAgentsExpanded, agentDeadlines, messageLinks, {
1268
173
  cwd: () => ctx.cwd,
1269
174
  requestRender: () => tui.requestRender(),
1270
175
  write: data => tui.terminal.write(data),
1271
176
  }, () => settings["pi-mini-mode-minimal-record-limit"]);
1272
- const hintRemaining = (activeMinimalTurn?.shortcutHintUntil ?? 0) - Date.now();
1273
- if (hintRemaining > 0) {
1274
- shortcutTimer = setTimeout(() => tui.requestRender(), hintRemaining);
1275
- shortcutTimer.unref();
1276
- }
1277
177
  // Native info notifications use dim; warning/error notifications retain
1278
178
  // their position in the transcript. No plugin names or message matching.
1279
179
  const dimPrefix = theme.fg("dim", "\u0000").split("\u0000")[0];
@@ -1428,7 +328,7 @@ export default function (pi: ExtensionAPI) {
1428
328
  const { startSettingsWeb } = await import("../lib/settings-web.ts");
1429
329
  const server = await startSettingsWeb(() => ({
1430
330
  settings, defaults: DEFAULT_SETTINGS, order: FOOTER_FIELDS, options: FOOTER_STYLE_OPTIONS,
1431
- items: settingsItems(settings).filter(item => !isCollapsedReplyChildSetting(item.id)),
331
+ items: settingsItems(settings),
1432
332
  // "regular" means minimal output is saved but cannot mount; the page offers a Pi prompt.
1433
333
  tuiMode: lastAttachMode ?? null,
1434
334
  }), async value => {
@@ -1442,6 +342,9 @@ export default function (pi: ExtensionAPI) {
1442
342
  if (entry !== "hover" && entry !== "inline") throw new TypeError("Invalid preview mode");
1443
343
  } else if (key === "pi-mini-mode-minimal-record-limit") {
1444
344
  if (!isRecordLimit(entry)) throw new TypeError("Invalid record limit");
345
+ } else if (isLegacyMinimalSetting(key) && typeof entry === "boolean") {
346
+ // Accept stale settings pages; these former child switches no longer gate output.
347
+ continue;
1445
348
  } else if (!SETTING_IDS.includes(key as typeof SETTING_IDS[number]) || typeof entry !== "boolean") throw new TypeError("Invalid setting");
1446
349
  }
1447
350
  const next = parseSettings({ ...settings, ...input, onboardingCompleted: true });
@@ -1518,6 +421,8 @@ export default function (pi: ExtensionAPI) {
1518
421
  messageCwd = ctx.cwd;
1519
422
  // 输入增强只在会话中生效,会话开始时再加载;传 getter 让开关变更即时生效,重复调用是幂等的。
1520
423
  cleanupInputEnhancements = installInputEnhancements(pi, ctx, () => settings["pi-mini-mode-input-enhancements"], () => settings["pi-mini-mode-image-preview"]);
424
+ thinkingStream.stop(activeMinimalTurn, "aborted");
425
+ thinkingStream.reset();
1521
426
  minimalTurns = minimalTurnsFromBranch(ctx.sessionManager.getBranch());
1522
427
  activeMinimalTurn = undefined;
1523
428
  pendingMinimalFinal = "";
@@ -1557,10 +462,11 @@ export default function (pi: ExtensionAPI) {
1557
462
  if (!settings.onboardingCompleted && ctx.mode === "tui" && ctx.hasUI) await runOnboarding(ctx);
1558
463
  });
1559
464
  const syncMinimalBranch = (_event: unknown, ctx: ExtensionContext) => {
465
+ thinkingStream.stop(activeMinimalTurn, "aborted");
1560
466
  minimalTurns = minimalTurnsFromBranch(ctx.sessionManager.getBranch());
1561
467
  activeMinimalTurn = undefined;
1562
468
  pendingMinimalFinal = "";
1563
- minimalMessageIndices.clear();
469
+ thinkingStream.reset();
1564
470
  minimalToolOutputIndices.clear();
1565
471
  mountMinimalOutput(ctx);
1566
472
  refreshMinimalOutput();
@@ -1587,45 +493,24 @@ export default function (pi: ExtensionAPI) {
1587
493
  });
1588
494
  pi.on("model_select", refresh);
1589
495
  pi.on("thinking_level_select", refresh);
1590
- const writeThinkingLine = (turn: MinimalTurn, content: Array<Record<string, unknown>>, blockIndex: number, line: string): number => {
1591
- let existing = minimalMessageIndices.get(blockIndex);
1592
- if (continuesEmptyThinking(content, blockIndex)) {
1593
- existing = minimalMessageIndices.get(blockIndex - 1);
1594
- if (existing !== undefined) minimalMessageIndices.set(blockIndex, existing);
1595
- } else if (existing !== undefined && [...minimalMessageIndices].some(([block, index]) => block < blockIndex && index === existing)) {
1596
- // A provisional empty block can acquire its own body on a later update.
1597
- existing = undefined;
1598
- }
1599
- if (existing === undefined) {
1600
- const index = turn.process.length;
1601
- minimalMessageIndices.set(blockIndex, index);
1602
- turn.process.push(line);
1603
- ensureThinkingClock(turn, index);
1604
- return index;
1605
- }
1606
- turn.process[existing] = line;
1607
- ensureThinkingClock(turn, existing);
1608
- return existing;
1609
- };
1610
496
  pi.on("message_start", (event) => {
1611
497
  if (event.message.role === "user") {
1612
498
  if (activeMinimalTurn) {
1613
- freezeOpenThinkingClocks(activeMinimalTurn);
499
+ thinkingStream.stop(activeMinimalTurn, "aborted");
1614
500
  activeMinimalTurn.final = pendingMinimalFinal;
1615
501
  activeMinimalTurn.running = false;
502
+ activeMinimalTurn.endedAt ??= Date.now();
1616
503
  activeMinimalTurn.thinking = undefined;
1617
504
  promptView?.resetProcessView();
1618
505
  }
1619
506
  const question = contentText(event.message.content) || "[Attachment]";
1620
507
  processExpanded = false;
1621
508
  subAgentsExpanded = false;
1622
- activeMinimalTurn = { question, process: [], running: true, startedAt: Date.now(), awaitingResponse: true, shortcutHintUntil: Date.now() + 6_000 };
1623
- if (shortcutTimer) clearTimeout(shortcutTimer);
1624
- shortcutTimer = setTimeout(() => refreshMinimalOutput(), 6_000);
1625
- shortcutTimer.unref();
509
+ activeMinimalTurn = { question, process: [], running: true, startedAt: Date.now(), awaitingResponse: true };
1626
510
  for (const name of skillNames(question)) pushProcess(activeMinimalTurn, "skill", name);
1627
511
  pendingMinimalFinal = "";
1628
512
  minimalToolOutputIndices.clear();
513
+ thinkingStream.reset();
1629
514
  minimalTurns.push(activeMinimalTurn);
1630
515
  refreshMinimalOutput();
1631
516
  }
@@ -1637,14 +522,14 @@ export default function (pi: ExtensionAPI) {
1637
522
  }
1638
523
  activeMinimalTurn ??= minimalTurns.at(-1);
1639
524
  if (activeMinimalTurn) {
1640
- freezeThinkingClock(activeMinimalTurn, activeMinimalTurn.thinking);
525
+ thinkingStream.start(activeMinimalTurn, event.message.timestamp);
1641
526
  if (activeMinimalTurn.final) (activeMinimalTurn.replies ??= []).push(activeMinimalTurn.final);
1642
527
  activeMinimalTurn.final = undefined;
1643
528
  activeMinimalTurn.running = true;
529
+ activeMinimalTurn.endedAt = undefined;
1644
530
  activeMinimalTurn.awaitingResponse = true;
1645
531
  activeMinimalTurn.thinking = undefined;
1646
532
  }
1647
- minimalMessageIndices.clear();
1648
533
  pendingMinimalFinal = "";
1649
534
  // Keep the last completed speed visible until this response produces tokens.
1650
535
  // Tool-call-only assistant messages therefore cannot erase a useful rate.
@@ -1656,25 +541,8 @@ export default function (pi: ExtensionAPI) {
1656
541
  pi.on("message_update", (event) => {
1657
542
  const partial = (event.assistantMessageEvent as { partial?: { usage?: UsageLike; content?: Array<Record<string, unknown>> } }).partial;
1658
543
  if (activeMinimalTurn && partial?.content) {
1659
- const previousThinking = activeMinimalTurn.thinking;
1660
- activeMinimalTurn.thinking = undefined;
544
+ if (!thinkingStream.update(activeMinimalTurn, partial.content, event.assistantMessageEvent)) return;
1661
545
  if (partial.content.length) activeMinimalTurn.awaitingResponse = false;
1662
- for (const [blockIndex, item] of partial.content.entries()) {
1663
- if (item.type !== "thinking") continue;
1664
- const line = `thinking ${thinkingText(item)}`;
1665
- const index = writeThinkingLine(activeMinimalTurn, partial.content, blockIndex, line);
1666
- if (blockIndex === partial.content.length - 1 && event.assistantMessageEvent.type !== "thinking_end") {
1667
- activeMinimalTurn.thinking = index;
1668
- }
1669
- }
1670
- for (const index of new Set(minimalMessageIndices.values())) {
1671
- if (index === activeMinimalTurn.thinking) {
1672
- delete ensureThinkingClock(activeMinimalTurn, index).endedAt;
1673
- } else freezeThinkingClock(activeMinimalTurn, index);
1674
- }
1675
- if (previousThinking !== undefined && previousThinking !== activeMinimalTurn.thinking) {
1676
- freezeThinkingClock(activeMinimalTurn, previousThinking);
1677
- }
1678
546
  activeMinimalTurn.final = contentText(partial.content) || undefined;
1679
547
  refreshMinimalOutput();
1680
548
  }
@@ -1700,10 +568,9 @@ export default function (pi: ExtensionAPI) {
1700
568
  pi.on("message_end", (event) => {
1701
569
  if (event.message.role === "assistant") {
1702
570
  if (activeMinimalTurn) {
1703
- freezeThinkingClock(activeMinimalTurn, activeMinimalTurn.thinking);
1704
- freezeOpenThinkingClocks(activeMinimalTurn);
1705
- activeMinimalTurn.thinking = undefined;
1706
- activeMinimalTurn.awaitingResponse = false;
571
+ const content = Array.isArray(event.message.content) ? event.message.content as unknown as Array<Record<string, unknown>> : [];
572
+ const outcome = event.message.stopReason === "error" || event.message.stopReason === "aborted" ? event.message.stopReason : "done";
573
+ if (!thinkingStream.finish(activeMinimalTurn, content, outcome, event.message.timestamp)) return;
1707
574
  activeMinimalTurn.usage = addUsage(activeMinimalTurn.usage ?? EMPTY_USAGE, event.message.usage as UsageLike | undefined);
1708
575
  activeMinimalTurn.pendingUsage = undefined;
1709
576
  }
@@ -1715,16 +582,10 @@ export default function (pi: ExtensionAPI) {
1715
582
  }
1716
583
  const content = (event.message as { content?: unknown }).content;
1717
584
  if (activeMinimalTurn && Array.isArray(content)) {
1718
- for (const [blockIndex, item] of (content as Array<Record<string, unknown>>).entries()) {
1719
- if (item.type !== "thinking" && !(item.type === "text" && content.some((block) => block.type === "toolCall"))) continue;
1720
- const line = `${item.type === "thinking" ? "thinking" : "output"} ${item.type === "thinking" ? thinkingText(item) : processText(item.text)}`;
1721
- if (item.type === "thinking") {
1722
- freezeThinkingClock(activeMinimalTurn, writeThinkingLine(activeMinimalTurn, content, blockIndex, line));
1723
- continue;
585
+ for (const item of content as Array<Record<string, unknown>>) {
586
+ if (item?.type === "text" && content.some((block) => block?.type === "toolCall")) {
587
+ activeMinimalTurn.process.push(`output ${processText(item.text)}`);
1724
588
  }
1725
- const index = minimalMessageIndices.get(blockIndex);
1726
- if (index === undefined) activeMinimalTurn.process.push(line);
1727
- else activeMinimalTurn.process[index] = line;
1728
589
  }
1729
590
  const text = contentText(content);
1730
591
  const message = event.message as { stopReason?: string; errorMessage?: string };
@@ -1742,8 +603,7 @@ export default function (pi: ExtensionAPI) {
1742
603
  pi.on("tool_execution_start", (event) => {
1743
604
  toolStarts.set(event.toolCallId, Date.now());
1744
605
  if (activeMinimalTurn) {
1745
- freezeThinkingClock(activeMinimalTurn, activeMinimalTurn.thinking);
1746
- activeMinimalTurn.thinking = undefined;
606
+ thinkingStream.stop(activeMinimalTurn);
1747
607
  activeMinimalTurn.awaitingResponse = false;
1748
608
  (activeMinimalTurn.agentCalls ??= []).push({ ...agentCall(event.toolCallId, event.toolName, event.args), startedAt: toolStarts.get(event.toolCallId) });
1749
609
  pushProcess(activeMinimalTurn, "call", event.toolCallId);
@@ -1811,7 +671,7 @@ export default function (pi: ExtensionAPI) {
1811
671
  pi.on("agent_settled", () => {
1812
672
  if (!activeMinimalTurn) return;
1813
673
  for (const turn of minimalTurns) {
1814
- freezeOpenThinkingClocks(turn);
674
+ thinkingStream.stop(turn);
1815
675
  if (turn.running) turn.endedAt = Date.now();
1816
676
  turn.running = false;
1817
677
  turn.thinking = undefined;
@@ -1822,10 +682,13 @@ export default function (pi: ExtensionAPI) {
1822
682
  promptView?.resetProcessView();
1823
683
  activeMinimalTurn = undefined;
1824
684
  pendingMinimalFinal = "";
685
+ thinkingStream.reset();
1825
686
  minimalToolOutputIndices.clear();
1826
687
  refreshMinimalOutput();
1827
688
  });
1828
689
  pi.on("session_shutdown", () => {
690
+ thinkingStream.stop(activeMinimalTurn, "aborted");
691
+ thinkingStream.reset();
1829
692
  restoreScrollbar?.();
1830
693
  restoreScrollbar = undefined;
1831
694
  scrollbarRoot = undefined;
@@ -1841,8 +704,6 @@ export default function (pi: ExtensionAPI) {
1841
704
  agentDeadlines.clear();
1842
705
  promptView?.dispose();
1843
706
  promptView = undefined;
1844
- if (shortcutTimer) clearTimeout(shortcutTimer);
1845
- shortcutTimer = undefined;
1846
707
  unsubscribeMcpStatus();
1847
708
  refreshFooter = undefined;
1848
709
  activeGeneration = undefined;