@each1024/pi-mini-mode 1.3.12 → 1.3.14
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 +1 -1
- package/README.zh-CN.md +1 -1
- package/extensions/footer-status.ts +181 -136
- package/lib/agent-view.ts +5 -4
- package/lib/minimal-theme.ts +4 -3
- package/lib/settings-web.ts +119 -0
- package/lib/settings.html +209 -0
- package/lib/sticky-tool.ts +1 -1
- package/lib/transcript-adapter.ts +9 -5
- package/package.json +2 -2
- package/themes/cc-dark.json +1 -1
package/README.md
CHANGED
|
@@ -168,7 +168,7 @@ Settings are stored globally at Pi's agent directory (normally `~/.pi/agent/pi-m
|
|
|
168
168
|
|
|
169
169
|
Session totals are aggregated from each finalized `assistant` and `toolResult` entry on the active session branch. This includes nested LLM work reported by tools (such as a child agent) exactly once. `Total` uses the provider's `totalTokens` when supplied; older/custom results without it fall back to the sum of input, output, cache-read, and cache-write tokens. `Cached` is cache-read + cache-write (included in Total); `CH` is cache-read / (input + cache-read). Only persisted finalized usage is counted, so stream updates cannot double count totals.
|
|
170
170
|
|
|
171
|
-
During an assistant stream, speed
|
|
171
|
+
During an assistant stream, speed is decode TPS: provider `usage.output` divided by elapsed time from the first output token, excluding TTFT/prefill wait. It appears after at least two output tokens and 100ms of decode time, and is refreshed while streaming. The completed rate remains visible while later assistant messages only call tools or wait for output; it is replaced only by a newer measurable main-turn generation. Nested tool LLM usage does not overwrite a measured main-turn rate; it can set the footer only when no main generation has been measured yet. Short or single-token bursts are hidden rather than shown as inflated tok/s. Regressing output samples and non-increasing timestamps are ignored.
|
|
172
172
|
|
|
173
173
|
Before a measurable response exists, the speed field is absent entirely—Pi Mini Mode never displays a `-- tok/s` placeholder. When present, speed is the rightmost footer field (the context percentage, if enabled, is immediately to its left). Its color uses Pi theme semantics: **success** at >=30 tok/s, **warning** at 10–29.9 tok/s, and **error** below 10 tok/s. No colors are hard-coded, so it follows the selected Pi theme.
|
|
174
174
|
|
package/README.zh-CN.md
CHANGED
|
@@ -159,7 +159,7 @@ deepseek-v4-flash high Total 45K Cached 25K CH 40.0% $0.012 500/1.0M █
|
|
|
159
159
|
|
|
160
160
|
会话总量来自当前会话分支中每一条已完成的 `assistant` 和 `toolResult` 记录。工具报告的嵌套 LLM 工作(例如子 Agent)会准确计入一次。若 provider 提供 `totalTokens`,`Total` 使用该值;较旧或自定义结果没有该字段时,则使用输入、输出、缓存读取和缓存写入令牌之和。`Cached` 是缓存读取与写入之和(包含在 `Total` 中);`CH` 是缓存读取量除以输入量与缓存读取量之和。只有已持久化的最终用量会计入,因此流式更新不会重复累计。
|
|
161
161
|
|
|
162
|
-
|
|
162
|
+
助手生成过程中,速度按 decode TPS 计算:用 provider 的 `usage.output` 除以从第一个输出 token 开始的耗时,不包含 TTFT/预填充等待。至少 2 个输出 token 且解码时长达 100ms 后才显示,并在流式过程中刷新。后续助手消息如果只是调用工具或等待输出,之前完成的速度仍会保留;只有新的可测量主回复才会替换它。嵌套工具里的 LLM 用量不会覆盖已测量的主回复速度;只有还没有主生成速度时,嵌套完成才能写入页脚。过短或单 token 突发不显示,避免虚高的 tok/s。倒退的输出样本和不递增的时间戳会被忽略。
|
|
163
163
|
|
|
164
164
|
在获得可测量响应前,速度字段完全不显示,不会出现 `-- tok/s` 占位符。速度位于页脚最右侧;启用上下文百分比时,百分比紧邻其左侧。颜色遵循 Pi 主题语义:至少 30 tok/s 为成功色,10–29.9 tok/s 为警告色,低于 10 tok/s 为错误色。费用是基于当前分支已完成用量和配置的每百万令牌费率得出的估算,并非 provider 账单。窄终端中,页脚会丢弃或截断优先级较低的内容,确保保持单行且不溢出。
|
|
165
165
|
|
|
@@ -1,15 +1,15 @@
|
|
|
1
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,
|
|
2
|
+
import { CONFIG_DIR_NAME, getAgentDir, getMarkdownTheme, SettingsManager, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
import { attachTranscript, type NoticeRows, type TurnNotices } from "../lib/transcript-adapter.ts";
|
|
4
4
|
import { diagramMarkdown, isFencedMarkdown, renderMinimalMarkdown } from "../lib/minimal-markdown.ts";
|
|
5
5
|
import { minimalSurface, paintExpandedHeading } from "../lib/minimal-theme.ts";
|
|
6
|
-
import {
|
|
6
|
+
import { Markdown, matchesKey, isKeyRelease, isKeyRepeat, sliceByColumn, type SettingItem, Text, type TuiMouseEvent, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
7
7
|
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
8
8
|
import type { InputEnhancementsCleanup } from "../lib/input-enhancements.ts";
|
|
9
9
|
import { linkMessageFiles } from "../lib/file-links.ts";
|
|
10
10
|
import { homedir } from "node:os";
|
|
11
11
|
import { stripVTControlCharacters } from "node:util";
|
|
12
|
-
import { dirname, join } from "node:path";
|
|
12
|
+
import { basename, dirname, join } from "node:path";
|
|
13
13
|
import attachFooterTidy from "../lib/footer-tidy.ts";
|
|
14
14
|
import attachTitlePlain from "../lib/title-plain.ts";
|
|
15
15
|
|
|
@@ -18,6 +18,8 @@ export const SETTINGS_FILE_NAME = "pi-mini-mode.json";
|
|
|
18
18
|
export interface MiniLensSettings {
|
|
19
19
|
"pi-mini-mode-model-show": boolean;
|
|
20
20
|
"pi-mini-mode-thinking-show": boolean;
|
|
21
|
+
"pi-mini-mode-project-branch-show": boolean;
|
|
22
|
+
"pi-mini-mode-branch-show": boolean;
|
|
21
23
|
"pi-mini-mode-ch-show": boolean;
|
|
22
24
|
"pi-mini-mode-session-tokens-show": boolean;
|
|
23
25
|
"pi-mini-mode-cache-tokens-show": boolean;
|
|
@@ -37,11 +39,14 @@ export interface MiniLensSettings {
|
|
|
37
39
|
"pi-mini-mode-agent-usage-show": boolean;
|
|
38
40
|
"pi-mini-mode-agent-shortcut-show": boolean;
|
|
39
41
|
onboardingCompleted: boolean;
|
|
42
|
+
footerOrder?: string[];
|
|
40
43
|
}
|
|
41
44
|
|
|
42
45
|
export const DEFAULT_SETTINGS: Readonly<MiniLensSettings> = {
|
|
43
46
|
"pi-mini-mode-model-show": true,
|
|
44
47
|
"pi-mini-mode-thinking-show": true,
|
|
48
|
+
"pi-mini-mode-project-branch-show": true,
|
|
49
|
+
"pi-mini-mode-branch-show": false,
|
|
45
50
|
"pi-mini-mode-ch-show": true,
|
|
46
51
|
"pi-mini-mode-session-tokens-show": true,
|
|
47
52
|
"pi-mini-mode-cache-tokens-show": true,
|
|
@@ -63,7 +68,8 @@ export const DEFAULT_SETTINGS: Readonly<MiniLensSettings> = {
|
|
|
63
68
|
onboardingCompleted: false,
|
|
64
69
|
};
|
|
65
70
|
|
|
66
|
-
const SETTING_IDS = Object.keys(DEFAULT_SETTINGS) as Array<keyof MiniLensSettings
|
|
71
|
+
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;
|
|
67
73
|
|
|
68
74
|
const COPY = {
|
|
69
75
|
title: "Pi Mini Mode 设置", preview: "预览(示例数据)", lens: "设置", minimal: "极简输出",
|
|
@@ -71,7 +77,7 @@ const COPY = {
|
|
|
71
77
|
totalDescription: "Total:当前会话分支上的全部 token,含工具上报的 LLM 用量。", cachedDescription: "Cached:累计 cache-read + cache-write token(包含在 Total 中)。", cacheHitDescription: "CH(cache hit):cache-read / (input + cache-read)。Cache write 不计入此比率。",
|
|
72
78
|
enableMinimalDescription: "开启统一折叠思考、工具和技能过程;关闭恢复 Pi 默认会话历史。",
|
|
73
79
|
inputEnhancementsDescription: "原生 Ctrl+V 粘贴图片(Windows/WSL:Alt+V);图片显示为 [image1] 标签,光标移入或全屏悬停可预览。空白后 / 选择技能并在光标处插入。Cmd+点击带下划线的图片标签或消息文件路径,用系统默认应用打开;预览及点击需终端支持。关闭仅恢复原生行为。",
|
|
74
|
-
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
|
|
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 数量、点阵样式和仅显示分支默认关闭;项目名称和分支默认开启,与仅显示分支互斥。", keepDefaults: "保留默认", configureNow: "立即配置", applyRecommended: "应用推荐配置", chooseTheme: "选择 Pi Mini Mode 主题(将保存全局主题和全屏模式;重启后生效)", themeSaved: "已保存推荐主题和全屏模式。请重启 Pi;项目设置或命令行参数可能覆盖全局设置。", themeSaveFailed: "无法保存推荐的 Pi 主题和全屏模式;未完成首次配置。", themeApplyFailed: "推荐设置已保存,但当前主题未能立即应用;请重启 Pi。",
|
|
75
81
|
} as const;
|
|
76
82
|
|
|
77
83
|
const RECOMMENDED_THEMES = ["cc-dark", "cc-light"] as const;
|
|
@@ -91,6 +97,12 @@ export function parseSettings(value: unknown): MiniLensSettings {
|
|
|
91
97
|
for (const id of SETTING_IDS) {
|
|
92
98
|
if (isBoolean(candidate[id])) settings[id] = candidate[id];
|
|
93
99
|
}
|
|
100
|
+
if (Array.isArray(candidate.footerOrder)) {
|
|
101
|
+
settings.footerOrder = [...new Set(candidate.footerOrder.filter((id): id is typeof FOOTER_FIELDS[number] =>
|
|
102
|
+
typeof id === "string" && (FOOTER_FIELDS as readonly string[]).includes(id)))];
|
|
103
|
+
for (const id of FOOTER_FIELDS) if (!settings.footerOrder.includes(id)) settings.footerOrder.push(id);
|
|
104
|
+
}
|
|
105
|
+
if (settings["pi-mini-mode-branch-show"]) settings["pi-mini-mode-project-branch-show"] = false;
|
|
94
106
|
// 折叠回复的旧细项已合并进极简输出总开关:旧值不再暗中过滤内容,始终按默认全开。
|
|
95
107
|
for (const id of LEGACY_MINIMAL_SETTING_IDS) settings[id] = true;
|
|
96
108
|
return settings;
|
|
@@ -251,6 +263,11 @@ function plannotatorPlanTag(statuses: ReadonlyMap<string, string> | undefined):
|
|
|
251
263
|
return isPlannotatorPlanningStatus(text) ? planCapsule() : "";
|
|
252
264
|
}
|
|
253
265
|
|
|
266
|
+
function progressBar(percent: number, dots: boolean, width: number): string {
|
|
267
|
+
const filled = Math.round(width * Math.max(0, Math.min(100, percent)) / 100);
|
|
268
|
+
return (dots ? "⣿" : "█").repeat(filled) + (dots ? "⣀" : "░").repeat(width - filled);
|
|
269
|
+
}
|
|
270
|
+
|
|
254
271
|
function renderRight(
|
|
255
272
|
theme: ExtensionContext["ui"]["theme"],
|
|
256
273
|
settings: MiniLensSettings,
|
|
@@ -270,6 +287,7 @@ function renderRight(
|
|
|
270
287
|
}
|
|
271
288
|
|
|
272
289
|
const SETTINGS_PREVIEW_CONTEXT = {
|
|
290
|
+
cwd: "/work/pi-mini-mode",
|
|
273
291
|
model: { id: "deepseek-v4-flash" },
|
|
274
292
|
thinkingLevel: "high",
|
|
275
293
|
getContextUsage: () => ({ tokens: 500, contextWindow: 1_000_000, percent: 1 }),
|
|
@@ -290,7 +308,7 @@ export function settingsPreviewLine(
|
|
|
290
308
|
width = 140,
|
|
291
309
|
highlighted?: keyof MiniLensSettings,
|
|
292
310
|
): string {
|
|
293
|
-
return statusLine(SETTINGS_PREVIEW_CONTEXT, theme, width, SETTINGS_PREVIEW_USAGE, settings, 120, highlighted, 3);
|
|
311
|
+
return statusLine(SETTINGS_PREVIEW_CONTEXT, theme, width, SETTINGS_PREVIEW_USAGE, settings, 120, highlighted, 3, undefined, "main");
|
|
294
312
|
}
|
|
295
313
|
|
|
296
314
|
export function statusLine(
|
|
@@ -303,6 +321,7 @@ export function statusLine(
|
|
|
303
321
|
highlighted?: keyof MiniLensSettings,
|
|
304
322
|
mcpCount?: number,
|
|
305
323
|
statuses?: ReadonlyMap<string, string>,
|
|
324
|
+
gitBranch?: string | null,
|
|
306
325
|
): string {
|
|
307
326
|
if (highlighted === "pi-mini-mode-context-dots-show") highlighted = "pi-mini-mode-context-show";
|
|
308
327
|
const field = (id: keyof MiniLensSettings, color: Parameters<typeof theme.fg>[0], text: string) =>
|
|
@@ -324,7 +343,33 @@ export function statusLine(
|
|
|
324
343
|
const showContext = settings["pi-mini-mode-context-show"] && Boolean(tokenText);
|
|
325
344
|
const mcpText = settings["pi-mini-mode-mcp-show"] && mcpCount !== undefined ? `◇ MCP ${mcpCount}` : "";
|
|
326
345
|
const planTag = plannotatorPlanTag(statuses);
|
|
327
|
-
|
|
346
|
+
const branchOnly = settings["pi-mini-mode-branch-show"];
|
|
347
|
+
const branchSetting = branchOnly ? "pi-mini-mode-branch-show" : "pi-mini-mode-project-branch-show";
|
|
348
|
+
const branchText = gitBranch && settings[branchSetting]
|
|
349
|
+
? stripVTControlCharacters(branchOnly ? gitBranch : `${basename(ctx.cwd)}(${gitBranch})`).replace(/[\x00-\x1f\x7f-\x9f]/g, "") : "";
|
|
350
|
+
|
|
351
|
+
if (settings.footerOrder) {
|
|
352
|
+
const values: Record<string, string> = {
|
|
353
|
+
"project-branch": !branchOnly ? branchText : "", branch: branchOnly ? branchText : "",
|
|
354
|
+
model, thinking,
|
|
355
|
+
"session-tokens": usageTotals.totalTokens > 0 ? `${COPY.totalLabel} ${formatTokens(usageTotals.totalTokens)}` : "",
|
|
356
|
+
"cache-tokens": cachedTokens > 0 ? `${COPY.cachedLabel} ${formatTokens(cachedTokens)}` : "",
|
|
357
|
+
ch: hitText, cost: price, mcp: mcpText,
|
|
358
|
+
context: tokenText,
|
|
359
|
+
"context-percent": percentText, speed: speed === undefined ? "" : formatSpeed(speed, settings["pi-mini-mode-speed-unit-show"]),
|
|
360
|
+
};
|
|
361
|
+
const visible = settings.footerOrder.filter(id => settings[`pi-mini-mode-${id}-show` as keyof MiniLensSettings] && values[id]);
|
|
362
|
+
const usedWidth = visibleWidth([planTag, ...visible.map(id => values[id])].filter(Boolean).join(" "));
|
|
363
|
+
const barWidth = Math.max(0, width - usedWidth - 1);
|
|
364
|
+
if (visible.includes("context") && percent !== undefined && barWidth > 0) {
|
|
365
|
+
values.context += ` ${progressBar(percent, settings["pi-mini-mode-context-dots-show"], barWidth)}`;
|
|
366
|
+
}
|
|
367
|
+
return truncateToWidth([planTag, ...settings.footerOrder.map(id => {
|
|
368
|
+
const key = `pi-mini-mode-${id}-show` as keyof MiniLensSettings;
|
|
369
|
+
const color = id === "speed" ? speedColor(speed) : id === "model" || id === "context-percent" ? "accent" : "muted";
|
|
370
|
+
return settings[key] && values[id] ? field(key, color, values[id]) : "";
|
|
371
|
+
})].filter(Boolean).join(" "), width, "…");
|
|
372
|
+
}
|
|
328
373
|
const right = renderRight(theme, settings, percentText, speed, highlighted);
|
|
329
374
|
const rightWidth = visibleWidth(right);
|
|
330
375
|
if (right && width <= rightWidth) {
|
|
@@ -336,8 +381,10 @@ export function statusLine(
|
|
|
336
381
|
|
|
337
382
|
const leftParts = [
|
|
338
383
|
planTag,
|
|
384
|
+
!branchOnly && branchText && field(branchSetting, "muted", branchText),
|
|
339
385
|
settings["pi-mini-mode-model-show"] && model && field("pi-mini-mode-model-show", "accent", model),
|
|
340
386
|
settings["pi-mini-mode-thinking-show"] && thinking && field("pi-mini-mode-thinking-show", "muted", thinking),
|
|
387
|
+
branchOnly && branchText && field(branchSetting, "muted", branchText),
|
|
341
388
|
settings["pi-mini-mode-session-tokens-show"] && usageTotals.totalTokens > 0 && field("pi-mini-mode-session-tokens-show", "text", `${COPY.totalLabel} ${formatTokens(usageTotals.totalTokens)}`),
|
|
342
389
|
settings["pi-mini-mode-cache-tokens-show"] && cachedTokens > 0 && field("pi-mini-mode-cache-tokens-show", "text", `${COPY.cachedLabel} ${formatTokens(cachedTokens)}`),
|
|
343
390
|
settings["pi-mini-mode-ch-show"] && hitText && field("pi-mini-mode-ch-show", "text", hitText),
|
|
@@ -346,8 +393,10 @@ export function statusLine(
|
|
|
346
393
|
].filter((part): part is string => Boolean(part));
|
|
347
394
|
const unstyledLeft = [
|
|
348
395
|
planTag && stripVTControlCharacters(planTag),
|
|
396
|
+
!branchOnly && branchText,
|
|
349
397
|
settings["pi-mini-mode-model-show"] && model,
|
|
350
398
|
settings["pi-mini-mode-thinking-show"] && thinking,
|
|
399
|
+
branchOnly && branchText,
|
|
351
400
|
settings["pi-mini-mode-session-tokens-show"] && usageTotals.totalTokens > 0 && `${COPY.totalLabel} ${formatTokens(usageTotals.totalTokens)}`,
|
|
352
401
|
settings["pi-mini-mode-cache-tokens-show"] && cachedTokens > 0 && `${COPY.cachedLabel} ${formatTokens(cachedTokens)}`,
|
|
353
402
|
settings["pi-mini-mode-ch-show"] && hitText,
|
|
@@ -383,20 +432,15 @@ const LEGACY_MINIMAL_SETTING_IDS = [
|
|
|
383
432
|
"pi-mini-mode-minimal-skills-show", "pi-mini-mode-agent-usage-show", "pi-mini-mode-agent-shortcut-show",
|
|
384
433
|
] as const satisfies ReadonlyArray<keyof MiniLensSettings>;
|
|
385
434
|
|
|
386
|
-
/** 模式总开关:设置列表顶部只展示这两项,旧细分项不再展示但仍保留兼容。 */
|
|
387
|
-
const MODE_SETTING_IDS = ["pi-mini-mode-minimal-show", "pi-mini-mode-input-enhancements"] as const;
|
|
388
|
-
|
|
389
|
-
function isModeSetting(id: string): boolean {
|
|
390
|
-
return (MODE_SETTING_IDS as readonly string[]).includes(id);
|
|
391
|
-
}
|
|
392
|
-
|
|
393
435
|
export function isCollapsedReplyChildSetting(id: string): boolean {
|
|
394
436
|
return (LEGACY_MINIMAL_SETTING_IDS as readonly string[]).includes(id);
|
|
395
437
|
}
|
|
396
438
|
|
|
397
439
|
export function settingsItems(settings: MiniLensSettings): SettingItem[] {
|
|
398
440
|
const values = ["on", "off"];
|
|
399
|
-
const labels: Record<Exclude<keyof MiniLensSettings, "onboardingCompleted">, string> = {
|
|
441
|
+
const labels: Record<Exclude<keyof MiniLensSettings, "onboardingCompleted" | "footerOrder">, string> = {
|
|
442
|
+
"pi-mini-mode-project-branch-show": "显示项目名称和分支(互斥)",
|
|
443
|
+
"pi-mini-mode-branch-show": "仅显示分支(思考等级后,互斥)",
|
|
400
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,
|
|
401
445
|
};
|
|
402
446
|
return (Object.keys(labels) as Array<keyof typeof labels>).map((id) => ({
|
|
@@ -407,16 +451,23 @@ export function settingsItems(settings: MiniLensSettings): SettingItem[] {
|
|
|
407
451
|
}
|
|
408
452
|
|
|
409
453
|
interface ActiveGeneration {
|
|
410
|
-
|
|
454
|
+
firstTokenAt?: number;
|
|
411
455
|
output: number;
|
|
412
456
|
lastSampleAt: number;
|
|
413
457
|
}
|
|
414
458
|
|
|
415
|
-
|
|
459
|
+
/** Hide sub-100ms bursts (batched usage) and 1-token completions; they are not a decode rate. */
|
|
460
|
+
export const DECODE_SPEED_MIN_ELAPSED_MS = 100;
|
|
461
|
+
export const DECODE_SPEED_MIN_OUTPUT = 2;
|
|
462
|
+
|
|
463
|
+
/** Decode TPS: provider `usage.output` / seconds after the first output token (excludes TTFT). */
|
|
464
|
+
export function outputSpeed(output: unknown, firstTokenAt: number | undefined, endedAt = Date.now()): number | undefined {
|
|
416
465
|
const tokenCount = finiteNumber(output);
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
466
|
+
if (firstTokenAt === undefined || tokenCount === undefined || tokenCount < DECODE_SPEED_MIN_OUTPUT) return undefined;
|
|
467
|
+
const elapsedMs = endedAt - firstTokenAt;
|
|
468
|
+
if (elapsedMs < DECODE_SPEED_MIN_ELAPSED_MS) return undefined;
|
|
469
|
+
const rate = tokenCount / (elapsedMs / 1_000);
|
|
470
|
+
return Number.isFinite(rate) ? rate : undefined;
|
|
420
471
|
}
|
|
421
472
|
|
|
422
473
|
export interface MinimalTurn {
|
|
@@ -792,19 +843,20 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
|
|
|
792
843
|
const body = split < 0 ? "" : text.slice(split + 1);
|
|
793
844
|
const activeThinking = entry.thinking && entry.state === "running";
|
|
794
845
|
const thinkingElapsed = entry.thinking ? theme.fg(activeThinking ? "success" : "muted", ` ${formatElapsed(turn.startedAt)}`) : "";
|
|
795
|
-
const summary = theme.fg("text", theme.bold(label)) + thinkingElapsed + " ";
|
|
796
846
|
const call = turn.agentCalls?.find(call => call.id === entry.id && !isAgentTool(call.tool ?? call.name));
|
|
797
847
|
const controlId = call?.id ?? (entry.thinking ? entry.id : "");
|
|
798
848
|
const open = call ? expandedTools.has(call.id) : !!(entry.thinking && expandedThinking.has(entry.id));
|
|
849
|
+
const identity = open ? "accent" : "text";
|
|
850
|
+
const summary = theme.fg(identity, theme.bold(label)) + thinkingElapsed + " ";
|
|
799
851
|
if (controlId && width >= 4) toolControls.push({ id: controlId, y: lines.length, width, title: text });
|
|
800
852
|
if (hoveredTool?.id === controlId && (hoveredTool.y !== lines.length || hoveredTool.width !== width)) clearHover();
|
|
801
|
-
const status = entry.state === "error" ? "
|
|
853
|
+
const status = entry.state === "error" ? "✕" : entry.state === "running" ? runningGlyph() : "●";
|
|
802
854
|
const arrow = !!controlId && (open || hoveredTool?.id === controlId);
|
|
803
855
|
const keepStatus = entry.state === "running" || (open && entry.state === "error");
|
|
804
|
-
const glyph = arrow ? (open ? "
|
|
856
|
+
const glyph = arrow ? (open ? "▼" : "▶") + (keepStatus ? ` ${status}` : "") : status;
|
|
805
857
|
const glyphColor = entry.state === "error" ? "error" : entry.state === "running" || arrow ? "accent" : "muted";
|
|
806
858
|
const last = row === shown.length - 1 && !agents.rows.length;
|
|
807
|
-
const prefix = theme.fg("dim", last ? "└─ " : "├─ ") + theme.fg(glyphColor, glyph) + " " + summary;
|
|
859
|
+
const prefix = theme.fg(open ? "accent" : "dim", last ? "└─ " : "├─ ") + theme.fg(glyphColor, glyph) + " " + summary;
|
|
808
860
|
if (activeThinking) {
|
|
809
861
|
const renderedBody = markdown(body, Math.max(1, visibleWidth(body) + 1), true).join(" ").replace(/\s+/g, " ").trim();
|
|
810
862
|
const bodyWidth = Math.max(0, width - visibleWidth(prefix));
|
|
@@ -819,18 +871,18 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
|
|
|
819
871
|
lines.push(truncateToWidth(prefix + (wrapped[0] ?? ""), width, ""));
|
|
820
872
|
for (const extra of wrapped.slice(1)) lines.push(truncateToWidth(rail + extra, width, ""));
|
|
821
873
|
} else {
|
|
822
|
-
lines.push(bandHeading(truncateToWidth(prefix + (entry.thinking ? markdown(body, Math.max(1, visibleWidth(body) + 1), true).join(" ").replace(/\s+/g, " ").trim() : theme.fg("muted", body)), width, controlId ? "" : "…"), open));
|
|
874
|
+
lines.push(bandHeading(truncateToWidth(prefix + (entry.thinking ? markdown(body, Math.max(1, visibleWidth(body) + 1), true).join(" ").replace(/\s+/g, " ").trim() : theme.fg(open ? "accent" : "muted", body)), width, controlId ? "" : "…"), open));
|
|
823
875
|
}
|
|
824
876
|
if (open && call && call.id === pinnedToolId) pinnedTool = { id: call.id, y: lines.length - 1, line: lines.at(-1)! };
|
|
825
877
|
if (open && call) {
|
|
826
878
|
// ponytail: saved text only; native view retains images, args and custom renderers.
|
|
827
879
|
const output = stripVTControlCharacters(call.output ?? "").replace(/\r\n?/g, "\n").replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "");
|
|
828
|
-
const rail = width > 5 ? (last ? " " : theme.fg("
|
|
880
|
+
const rail = width > 5 ? (last ? " " : theme.fg("accent", "│ ")) : "";
|
|
829
881
|
const detailWidth = Math.max(1, width - visibleWidth(rail));
|
|
830
882
|
const details = new Text(output || (entry.state === "running" ? "等待工具文本结果…" : "无文本结果"), 0, 0).render(detailWidth);
|
|
831
883
|
lines.push(...details.map(line => truncateToWidth(rail + theme.fg("muted", line), width, "")));
|
|
832
884
|
} else if (open && entry.thinking) {
|
|
833
|
-
const rail = width > 5 ? (last ? " " : theme.fg("
|
|
885
|
+
const rail = width > 5 ? (last ? " " : theme.fg("accent", "│ ")) : "";
|
|
834
886
|
const detailWidth = Math.max(1, width - visibleWidth(rail));
|
|
835
887
|
lines.push(...markdown(entry.detail, detailWidth, true).map(line => truncateToWidth(rail + line, width, "")));
|
|
836
888
|
} else if (expanded && entry.state === "error" && entry.detail) {
|
|
@@ -880,7 +932,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
880
932
|
let promptView: ReturnType<typeof minimalOutputComponent> | undefined;
|
|
881
933
|
let lastAttachMode: string | undefined;
|
|
882
934
|
let remountQueued = false;
|
|
883
|
-
let
|
|
935
|
+
let settingsWeb: Awaited<ReturnType<typeof import("../lib/settings-web.ts").startSettingsWeb>> | undefined;
|
|
936
|
+
let settingsWebOpening: Promise<void> | undefined;
|
|
937
|
+
let settingsWebGeneration = 0;
|
|
884
938
|
const agentDeadlines = new Map<string, number>();
|
|
885
939
|
let minimalTurns: MinimalTurn[] = [];
|
|
886
940
|
let activeMinimalTurn: MinimalTurn | undefined;
|
|
@@ -1033,7 +1087,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1033
1087
|
restoreAgentWidgets?.();
|
|
1034
1088
|
restoreAgentWidgets = undefined;
|
|
1035
1089
|
// Settings overlay replaces the transcript; remount after it closes instead of warning.
|
|
1036
|
-
|
|
1090
|
+
ctx.ui.notify(tui.mode === "regular"
|
|
1037
1091
|
? "Minimal output needs the fullscreen renderer. Quit and restart Pi — /reload does not switch TUI mode. Or set TUI mode to fullscreen in /settings."
|
|
1038
1092
|
: "Pi transcript layout not recognized; minimal mode disabled, native output preserved.", "warning");
|
|
1039
1093
|
}
|
|
@@ -1070,7 +1124,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1070
1124
|
};
|
|
1071
1125
|
const refreshStreamingSpeed = () => {
|
|
1072
1126
|
if (!activeGeneration) return;
|
|
1073
|
-
const nextSpeed = outputSpeed(activeGeneration.output, activeGeneration.
|
|
1127
|
+
const nextSpeed = outputSpeed(activeGeneration.output, activeGeneration.firstTokenAt);
|
|
1074
1128
|
if (nextSpeed !== undefined) speed = nextSpeed;
|
|
1075
1129
|
refresh();
|
|
1076
1130
|
};
|
|
@@ -1130,71 +1184,83 @@ export default function (pi: ExtensionAPI) {
|
|
|
1130
1184
|
}
|
|
1131
1185
|
};
|
|
1132
1186
|
const openSettings = async (ctx: ExtensionContext) => {
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
return;
|
|
1136
|
-
}
|
|
1137
|
-
settingsOverlayOpen = true;
|
|
1187
|
+
const generation = settingsWebGeneration;
|
|
1188
|
+
if (ctx.mode !== "tui") { ctx.ui.notify(COPY.tuiRequired, "error"); return; }
|
|
1138
1189
|
try {
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
render: (width: number) => {
|
|
1178
|
-
// SettingsList exposes selection through its theme callback, including search and mouse navigation.
|
|
1179
|
-
highlighted = undefined;
|
|
1180
|
-
settingsList.render(width);
|
|
1181
|
-
preview.setText(settingsPreviewLine(theme, settings, Math.max(0, width - 2), highlighted));
|
|
1182
|
-
return container.render(width);
|
|
1183
|
-
},
|
|
1184
|
-
invalidate: () => container.invalidate(),
|
|
1185
|
-
handleMouse: (event: TuiMouseEvent) => container.handleMouse(event),
|
|
1186
|
-
handleInput: (data: string) => {
|
|
1187
|
-
settingsList.handleInput(data);
|
|
1188
|
-
tui.requestRender();
|
|
1189
|
-
},
|
|
1190
|
-
};
|
|
1191
|
-
});
|
|
1192
|
-
} finally {
|
|
1193
|
-
settingsOverlayOpen = false;
|
|
1194
|
-
mountMinimalOutput(ctx);
|
|
1190
|
+
if (settingsWeb && !settingsWeb.closed) settingsWeb.touch();
|
|
1191
|
+
else settingsWebOpening ??= (async () => {
|
|
1192
|
+
const { startSettingsWeb } = await import("../lib/settings-web.ts");
|
|
1193
|
+
const server = await startSettingsWeb(() => ({
|
|
1194
|
+
settings, defaults: DEFAULT_SETTINGS, order: FOOTER_FIELDS,
|
|
1195
|
+
items: settingsItems(settings).filter(item => !isCollapsedReplyChildSetting(item.id)),
|
|
1196
|
+
// "regular" means minimal output is saved but cannot mount; the page offers a Pi prompt.
|
|
1197
|
+
tuiMode: lastAttachMode ?? null,
|
|
1198
|
+
}), async value => {
|
|
1199
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Invalid settings");
|
|
1200
|
+
const input = value as Record<string, unknown>;
|
|
1201
|
+
for (const [key, entry] of Object.entries(input)) {
|
|
1202
|
+
if (key === "footerOrder") {
|
|
1203
|
+
if (!Array.isArray(entry) || entry.length !== FOOTER_FIELDS.length || new Set(entry).size !== entry.length
|
|
1204
|
+
|| entry.some(id => !(FOOTER_FIELDS as readonly unknown[]).includes(id))) throw new TypeError("Invalid order");
|
|
1205
|
+
} else if (!SETTING_IDS.includes(key as typeof SETTING_IDS[number]) || typeof entry !== "boolean") throw new TypeError("Invalid setting");
|
|
1206
|
+
}
|
|
1207
|
+
const next = parseSettings({ ...settings, ...input, onboardingCompleted: true });
|
|
1208
|
+
await saveSettings(next, configPath);
|
|
1209
|
+
settings = next;
|
|
1210
|
+
cleanupInputEnhancements?.refresh();
|
|
1211
|
+
refresh();
|
|
1212
|
+
mountMinimalOutput(ctx);
|
|
1213
|
+
refreshMinimalOutput();
|
|
1214
|
+
}, { onClose: () => { if (settingsWeb === server) settingsWeb = undefined; } });
|
|
1215
|
+
if (generation !== settingsWebGeneration) { server.close(); return; }
|
|
1216
|
+
settingsWeb = server;
|
|
1217
|
+
})().finally(() => { if (generation === settingsWebGeneration) settingsWebOpening = undefined; });
|
|
1218
|
+
await settingsWebOpening;
|
|
1219
|
+
if (generation !== settingsWebGeneration || !settingsWeb || settingsWeb.closed) return;
|
|
1220
|
+
const url = settingsWeb.url;
|
|
1221
|
+
const result = process.platform === "darwin" ? await pi.exec("open", [url])
|
|
1222
|
+
: process.platform === "win32" ? await pi.exec("rundll32.exe", ["url.dll,FileProtocolHandler", url])
|
|
1223
|
+
: await pi.exec("xdg-open", [url]);
|
|
1224
|
+
if (result.code !== 0) ctx.ui.notify(`请在本机浏览器打开:${url}`, "warning");
|
|
1225
|
+
} catch (error) {
|
|
1226
|
+
if (!settingsWeb) settingsWebOpening = undefined;
|
|
1227
|
+
ctx.ui.notify(`无法打开设置:${error instanceof Error ? error.message : String(error)}${settingsWeb ? `\n${settingsWeb.url}` : ""}`, "error");
|
|
1195
1228
|
}
|
|
1196
1229
|
};
|
|
1197
1230
|
|
|
1231
|
+
const runOnboarding = async (ctx: ExtensionContext) => {
|
|
1232
|
+
if (ctx.mode !== "tui" || !ctx.hasUI) return;
|
|
1233
|
+
let choice: string | undefined;
|
|
1234
|
+
try {
|
|
1235
|
+
choice = await ctx.ui.select(
|
|
1236
|
+
`Pi Mini Mode ${COPY.preview}\n\n deepseek-v4-flash high ${COPY.totalLabel} 45K ${COPY.cachedLabel} 25K ${COPY.cacheHitLabel} 40.0% $0.012 500/1.0M █░░░░░░░░░ 1% 120 tok/s\n\n${COPY.onboarding}`,
|
|
1237
|
+
[COPY.keepDefaults, COPY.configureNow, COPY.applyRecommended],
|
|
1238
|
+
);
|
|
1239
|
+
} catch (error) {
|
|
1240
|
+
ctx.ui.notify(`首次配置未完成:${error instanceof Error ? error.message : String(error)}`, "error");
|
|
1241
|
+
return;
|
|
1242
|
+
}
|
|
1243
|
+
if (!choice) return;
|
|
1244
|
+
if (choice === COPY.applyRecommended) {
|
|
1245
|
+
let themeName: string | undefined;
|
|
1246
|
+
try {
|
|
1247
|
+
const available = RECOMMENDED_THEMES.filter(name => ctx.ui.getTheme(name));
|
|
1248
|
+
if (!available.length) {
|
|
1249
|
+
ctx.ui.notify("未发现 cc-dark 或 cc-light 主题;请确认本包主题已加载。", "error");
|
|
1250
|
+
return;
|
|
1251
|
+
}
|
|
1252
|
+
themeName = await ctx.ui.select(COPY.chooseTheme, available);
|
|
1253
|
+
} catch (error) {
|
|
1254
|
+
ctx.ui.notify(`推荐配置未完成:${error instanceof Error ? error.message : String(error)}`, "error");
|
|
1255
|
+
return;
|
|
1256
|
+
}
|
|
1257
|
+
if (!themeName || !RECOMMENDED_THEMES.includes(themeName as RecommendedTheme)) return;
|
|
1258
|
+
if (!await applyRecommendedHostSettings(ctx, themeName as RecommendedTheme)) return;
|
|
1259
|
+
}
|
|
1260
|
+
settings = { ...settings, onboardingCompleted: true };
|
|
1261
|
+
await persistSettings(ctx);
|
|
1262
|
+
if (choice === COPY.configureNow) await openSettings(ctx);
|
|
1263
|
+
};
|
|
1198
1264
|
pi.registerCommand("pi-mini-mode-minimal", {
|
|
1199
1265
|
description: "Toggle minimal output (off keeps Pi's default conversation history)",
|
|
1200
1266
|
handler: async (args, ctx) => {
|
|
@@ -1219,7 +1285,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
1219
1285
|
ctx.ui.notify(`${COPY.minimalState}${settings["pi-mini-mode-minimal-show"] ? "on" : "off"}`, "info");
|
|
1220
1286
|
},
|
|
1221
1287
|
});
|
|
1222
|
-
|
|
1223
1288
|
pi.registerCommand("pi-mini-mode-prompts", {
|
|
1224
1289
|
description: "Expand or collapse a user prompt in fullscreen minimal output",
|
|
1225
1290
|
handler: async (_args, ctx) => {
|
|
@@ -1252,42 +1317,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
1252
1317
|
if (choice && promptView === view) { view.toggleTool(choice.id); refreshMinimalOutput(); }
|
|
1253
1318
|
},
|
|
1254
1319
|
});
|
|
1255
|
-
|
|
1256
|
-
const runOnboarding = async (ctx: ExtensionContext) => {
|
|
1257
|
-
if (ctx.mode !== "tui" || !ctx.hasUI) return;
|
|
1258
|
-
let choice: string | undefined;
|
|
1259
|
-
try {
|
|
1260
|
-
choice = await ctx.ui.select(
|
|
1261
|
-
`Pi Mini Mode ${COPY.preview}\n\n deepseek-v4-flash high ${COPY.totalLabel} 45K ${COPY.cachedLabel} 25K ${COPY.cacheHitLabel} 40.0% $0.012 500/1.0M █░░░░░░░░░ 1% 120 tok/s\n\n${COPY.onboarding}`,
|
|
1262
|
-
[COPY.keepDefaults, COPY.configureNow, COPY.applyRecommended],
|
|
1263
|
-
);
|
|
1264
|
-
} catch (error) {
|
|
1265
|
-
ctx.ui.notify(`首次配置未完成:${error instanceof Error ? error.message : String(error)}`, "error");
|
|
1266
|
-
return;
|
|
1267
|
-
}
|
|
1268
|
-
if (!choice) return;
|
|
1269
|
-
if (choice === COPY.applyRecommended) {
|
|
1270
|
-
let themeName: string | undefined;
|
|
1271
|
-
try {
|
|
1272
|
-
const available = RECOMMENDED_THEMES.filter(name => ctx.ui.getTheme(name));
|
|
1273
|
-
if (!available.length) {
|
|
1274
|
-
ctx.ui.notify("未发现 cc-dark 或 cc-light 主题;请确认本包主题已加载。", "error");
|
|
1275
|
-
return;
|
|
1276
|
-
}
|
|
1277
|
-
themeName = await ctx.ui.select(COPY.chooseTheme, available);
|
|
1278
|
-
} catch (error) {
|
|
1279
|
-
ctx.ui.notify(`推荐配置未完成:${error instanceof Error ? error.message : String(error)}`, "error");
|
|
1280
|
-
return;
|
|
1281
|
-
}
|
|
1282
|
-
if (!themeName || !RECOMMENDED_THEMES.includes(themeName as RecommendedTheme)) return;
|
|
1283
|
-
if (!await applyRecommendedHostSettings(ctx, themeName as RecommendedTheme)) return;
|
|
1284
|
-
}
|
|
1285
|
-
settings = { ...settings, onboardingCompleted: true };
|
|
1286
|
-
await persistSettings(ctx);
|
|
1287
|
-
if (choice === COPY.configureNow) await openSettings(ctx);
|
|
1288
|
-
};
|
|
1289
1320
|
pi.registerCommand("pi-mini-mode-settings", {
|
|
1290
|
-
description: "
|
|
1321
|
+
description: "Open HTML settings in the browser",
|
|
1291
1322
|
handler: async (_args, ctx) => openSettings(ctx),
|
|
1292
1323
|
});
|
|
1293
1324
|
pi.registerCommand("pi-mini-mode-setup", {
|
|
@@ -1309,6 +1340,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1309
1340
|
ctx.ui.setFooter((tui, theme, footerData) => {
|
|
1310
1341
|
refreshFooter = () => tui.requestRender();
|
|
1311
1342
|
return {
|
|
1343
|
+
dispose: footerData?.onBranchChange?.(() => tui.requestRender()),
|
|
1312
1344
|
invalidate() {},
|
|
1313
1345
|
render(width: number): string[] {
|
|
1314
1346
|
// switchTuiMode does not re-run setWidget; remount once the live renderer is fullscreen.
|
|
@@ -1320,7 +1352,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1320
1352
|
mountMinimalOutput(ctx);
|
|
1321
1353
|
});
|
|
1322
1354
|
}
|
|
1323
|
-
return [statusLine(ctx, theme, width, sessionUsage(ctx), settings, speed, undefined, mcpCount, footerData?.getExtensionStatuses?.())];
|
|
1355
|
+
return [statusLine(ctx, theme, width, sessionUsage(ctx), settings, speed, undefined, mcpCount, footerData?.getExtensionStatuses?.(), footerData?.getGitBranch?.())];
|
|
1324
1356
|
},
|
|
1325
1357
|
};
|
|
1326
1358
|
});
|
|
@@ -1392,8 +1424,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
1392
1424
|
pendingMinimalFinal = "";
|
|
1393
1425
|
// Keep the last completed speed visible until this response produces tokens.
|
|
1394
1426
|
// Tool-call-only assistant messages therefore cannot erase a useful rate.
|
|
1395
|
-
|
|
1396
|
-
|
|
1427
|
+
// Decode clock starts on the first output token, not message_start (TTFT).
|
|
1428
|
+
const sampledAt = Date.now();
|
|
1429
|
+
activeGeneration = { output: 0, lastSampleAt: sampledAt };
|
|
1397
1430
|
startSpeedTimer();
|
|
1398
1431
|
});
|
|
1399
1432
|
pi.on("message_update", (event) => {
|
|
@@ -1421,10 +1454,16 @@ export default function (pi: ExtensionAPI) {
|
|
|
1421
1454
|
const usage = partial?.usage;
|
|
1422
1455
|
const output = finiteNumber(usage?.output);
|
|
1423
1456
|
const timestamp = Date.now();
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
activeGeneration.
|
|
1427
|
-
|
|
1457
|
+
const hasOutputContent = Array.isArray(partial?.content) && partial.content.length > 0;
|
|
1458
|
+
if (activeGeneration && timestamp >= activeGeneration.lastSampleAt) {
|
|
1459
|
+
if (activeGeneration.firstTokenAt === undefined && (hasOutputContent || (output !== undefined && output > 0))) {
|
|
1460
|
+
activeGeneration.firstTokenAt = timestamp;
|
|
1461
|
+
}
|
|
1462
|
+
if (output !== undefined && output >= activeGeneration.output) {
|
|
1463
|
+
activeGeneration.output = output;
|
|
1464
|
+
activeGeneration.lastSampleAt = timestamp;
|
|
1465
|
+
refreshStreamingSpeed();
|
|
1466
|
+
}
|
|
1428
1467
|
}
|
|
1429
1468
|
});
|
|
1430
1469
|
pi.on("message_end", (event) => {
|
|
@@ -1436,7 +1475,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
1436
1475
|
activeMinimalTurn.pendingUsage = undefined;
|
|
1437
1476
|
}
|
|
1438
1477
|
if (activeGeneration) {
|
|
1439
|
-
const finalSpeed = outputSpeed((event.message.usage as UsageLike | undefined)?.output, activeGeneration.
|
|
1478
|
+
const finalSpeed = outputSpeed((event.message.usage as UsageLike | undefined)?.output, activeGeneration.firstTokenAt);
|
|
1440
1479
|
if (finalSpeed !== undefined) speed = finalSpeed;
|
|
1441
1480
|
activeGeneration = undefined;
|
|
1442
1481
|
stopSpeedTimer();
|
|
@@ -1502,7 +1541,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
1502
1541
|
toolStarts.delete(event.toolCallId);
|
|
1503
1542
|
const nestedUsage = (event.result as { usage?: UsageLike } | undefined)?.usage;
|
|
1504
1543
|
if (activeMinimalTurn) activeMinimalTurn.usage = addUsage(activeMinimalTurn.usage ?? EMPTY_USAGE, nestedUsage);
|
|
1505
|
-
|
|
1544
|
+
// Nested tool LLM completions must not overwrite a measured main-turn decode rate.
|
|
1545
|
+
if (startedAt !== undefined && speed === undefined) {
|
|
1506
1546
|
const nestedSpeed = outputSpeed(nestedUsage?.output, startedAt);
|
|
1507
1547
|
if (nestedSpeed !== undefined) speed = nestedSpeed;
|
|
1508
1548
|
}
|
|
@@ -1539,6 +1579,11 @@ export default function (pi: ExtensionAPI) {
|
|
|
1539
1579
|
refreshMinimalOutput();
|
|
1540
1580
|
});
|
|
1541
1581
|
pi.on("session_shutdown", () => {
|
|
1582
|
+
// In-flight startup checks this generation before installing its server.
|
|
1583
|
+
settingsWebGeneration++;
|
|
1584
|
+
settingsWeb?.close();
|
|
1585
|
+
settingsWeb = undefined;
|
|
1586
|
+
settingsWebOpening = undefined;
|
|
1542
1587
|
cleanupInputEnhancements?.();
|
|
1543
1588
|
cleanupInputEnhancements = undefined;
|
|
1544
1589
|
persistAgentStatuses?.();
|
package/lib/agent-view.ts
CHANGED
|
@@ -390,6 +390,7 @@ export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme,
|
|
|
390
390
|
subagentControls?.push({ runId: runKey, y: rows.length, width, line });
|
|
391
391
|
rows.push(line);
|
|
392
392
|
if (isChildExpanded) {
|
|
393
|
+
const rail = theme.fg("accent", "│") + " ";
|
|
393
394
|
let processShown = false;
|
|
394
395
|
if (!terminal) {
|
|
395
396
|
const process: Array<{ name: string; args: string }> = tools.slice(-6).map(tool => ({
|
|
@@ -400,7 +401,7 @@ export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme,
|
|
|
400
401
|
process.push({ name: text(child.currentTool), args: text(child.currentPath || child.currentToolArgs) });
|
|
401
402
|
}
|
|
402
403
|
for (const item of process) {
|
|
403
|
-
const prefix =
|
|
404
|
+
const prefix = `${rail}${theme.fg("muted", "●")} ${theme.fg("text", theme.bold(item.name))}${item.args ? " " : ""}`;
|
|
404
405
|
rows.push(truncateToWidth(prefix + (item.args ? theme.fg("muted", item.args) : ""), width, "…"));
|
|
405
406
|
processShown = true;
|
|
406
407
|
}
|
|
@@ -430,15 +431,15 @@ export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme,
|
|
|
430
431
|
const error = bodyText(child.error);
|
|
431
432
|
if (error && !bodies.includes(error)) bodies.push(error);
|
|
432
433
|
if (!terminal && !processShown && !bodies.length) {
|
|
433
|
-
rows.push(truncateToWidth(
|
|
434
|
+
rows.push(truncateToWidth(`${rail}${theme.fg("muted", "●")} ${theme.fg("text", theme.bold(text(state)))}`, width, "…"));
|
|
434
435
|
processShown = true;
|
|
435
436
|
}
|
|
436
437
|
for (const [index, textBody] of bodies.entries()) {
|
|
437
438
|
// Child/supervisor bodies are Markdown prose; tool logs and JSON are
|
|
438
439
|
// not placed in this semantic body channel.
|
|
439
|
-
if (processShown || index > 0) rows.push("");
|
|
440
|
+
if (processShown || index > 0) rows.push(truncateToWidth(rail, width, ""));
|
|
440
441
|
for (const line of renderBody(textBody, Math.max(1, width - 3))) {
|
|
441
|
-
rows.push(truncateToWidth(
|
|
442
|
+
rows.push(truncateToWidth(`${rail}${line}`, width));
|
|
442
443
|
}
|
|
443
444
|
}
|
|
444
445
|
}
|
package/lib/minimal-theme.ts
CHANGED
|
@@ -27,10 +27,11 @@ export function paintExpandedHeading(theme: ExtensionContext["ui"]["theme"], lin
|
|
|
27
27
|
* A row inside an expanded heading (selected) keeps the band instead: the
|
|
28
28
|
* blended tint and the user surface both collapse into it. */
|
|
29
29
|
export function minimalSurface(theme: ExtensionContext["ui"]["theme"], text: string, user = false, selected = false): string {
|
|
30
|
-
|
|
31
|
-
|
|
30
|
+
if (selected) return paintExpandedHeading(theme, text);
|
|
31
|
+
const background = theme.getBgAnsi?.("userMessageBg") ?? "";
|
|
32
|
+
if (user) return background
|
|
32
33
|
? background + text.replace(/\x1b\[(?:0|49)?m/g, (reset) => reset + background) + "\x1b[49m"
|
|
33
|
-
: theme.bg(
|
|
34
|
+
: theme.bg("userMessageBg", text);
|
|
34
35
|
const base = ansiColor(background);
|
|
35
36
|
const accent = ansiColor(theme.fg("accent", "")) ?? ansiColor(theme.fg("success", ""));
|
|
36
37
|
if (!base || !accent) return theme.bg("userMessageBg", text);
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { createServer } from "node:http";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { readFile } from "node:fs/promises";
|
|
4
|
+
|
|
5
|
+
export interface SettingsWebOptions {
|
|
6
|
+
idleTimeoutMs?: number;
|
|
7
|
+
onClose?: () => void;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const DEFAULT_IDLE_TIMEOUT_MS = 300_000;
|
|
11
|
+
const MIN_IDLE_TIMEOUT_MS = 1_000;
|
|
12
|
+
const MAX_IDLE_TIMEOUT_MS = 3_600_000;
|
|
13
|
+
|
|
14
|
+
/** Env override is validated to 1s..1h; a test override wins and is trusted. */
|
|
15
|
+
function configuredIdleTimeout(override: number | undefined): number {
|
|
16
|
+
if (override !== undefined) {
|
|
17
|
+
if (!Number.isFinite(override) || override <= 0) throw new TypeError("Invalid idle timeout");
|
|
18
|
+
return override;
|
|
19
|
+
}
|
|
20
|
+
const raw = process.env.PI_MINI_MODE_SETTINGS_IDLE_MS;
|
|
21
|
+
const value = Number(raw);
|
|
22
|
+
return raw !== undefined && Number.isInteger(value) && value >= MIN_IDLE_TIMEOUT_MS && value <= MAX_IDLE_TIMEOUT_MS
|
|
23
|
+
? value : DEFAULT_IDLE_TIMEOUT_MS;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** On-demand, loopback-only settings bridge; no polling or third-party runtime. */
|
|
27
|
+
export async function startSettingsWeb(snapshot: () => unknown, update: (value: unknown) => Promise<void>, options: SettingsWebOptions = {}) {
|
|
28
|
+
const token = randomBytes(24).toString("hex");
|
|
29
|
+
const html = await readFile(new URL("./settings.html", import.meta.url));
|
|
30
|
+
const idleTimeoutMs = configuredIdleTimeout(options.idleTimeoutMs);
|
|
31
|
+
let origin = "";
|
|
32
|
+
let queue = Promise.resolve();
|
|
33
|
+
let idleTimer: ReturnType<typeof setTimeout> | undefined;
|
|
34
|
+
let idleDeadline = Date.now() + idleTimeoutMs;
|
|
35
|
+
let closed = false;
|
|
36
|
+
let activeRequests = 0;
|
|
37
|
+
const close = () => {
|
|
38
|
+
if (closed) return;
|
|
39
|
+
closed = true;
|
|
40
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
41
|
+
idleTimer = undefined;
|
|
42
|
+
server.close();
|
|
43
|
+
server.closeAllConnections();
|
|
44
|
+
options.onClose?.();
|
|
45
|
+
};
|
|
46
|
+
const armIdle = () => {
|
|
47
|
+
if (closed || activeRequests > 0) return;
|
|
48
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
49
|
+
idleTimer = setTimeout(close, Math.max(0, idleDeadline - Date.now()));
|
|
50
|
+
idleTimer.unref();
|
|
51
|
+
};
|
|
52
|
+
/** Successful authorized traffic renews; failed or anonymous requests keep the old deadline. */
|
|
53
|
+
const touch = () => {
|
|
54
|
+
idleDeadline = Date.now() + idleTimeoutMs;
|
|
55
|
+
armIdle();
|
|
56
|
+
};
|
|
57
|
+
const server = createServer(async (req, res) => {
|
|
58
|
+
res.setHeader("Cache-Control", "no-store");
|
|
59
|
+
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
60
|
+
res.setHeader("Referrer-Policy", "no-referrer");
|
|
61
|
+
res.setHeader("Content-Security-Policy", "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'");
|
|
62
|
+
if (req.headers.host !== origin.slice(7) || (req.headers.origin && req.headers.origin !== origin)) {
|
|
63
|
+
res.writeHead(403).end(); return;
|
|
64
|
+
}
|
|
65
|
+
if (req.url === "/" && req.method === "GET") {
|
|
66
|
+
res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(html); return;
|
|
67
|
+
}
|
|
68
|
+
if (req.url !== "/settings" || req.headers.authorization !== `Bearer ${token}`) {
|
|
69
|
+
res.writeHead(403).end(); return;
|
|
70
|
+
}
|
|
71
|
+
// Suspend the idle lease while handling so a slow save cannot be cut off;
|
|
72
|
+
// only a successful response re-arms it.
|
|
73
|
+
if (idleTimer) clearTimeout(idleTimer);
|
|
74
|
+
idleTimer = undefined;
|
|
75
|
+
let renewed = false;
|
|
76
|
+
activeRequests++;
|
|
77
|
+
try {
|
|
78
|
+
if (req.method === "PUT") {
|
|
79
|
+
if (req.headers["content-type"] !== "application/json") { res.writeHead(415).end(); return; }
|
|
80
|
+
let body = "";
|
|
81
|
+
for await (const chunk of req) {
|
|
82
|
+
body += chunk;
|
|
83
|
+
if (Buffer.byteLength(body) > 16384) { res.writeHead(413).end(); return; }
|
|
84
|
+
}
|
|
85
|
+
const value: unknown = JSON.parse(body);
|
|
86
|
+
const saving = queue.then(() => update(value));
|
|
87
|
+
queue = saving.catch(() => {});
|
|
88
|
+
await saving;
|
|
89
|
+
} else if (req.method !== "GET") { res.writeHead(405).end(); return; }
|
|
90
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
91
|
+
res.end(JSON.stringify(snapshot()));
|
|
92
|
+
renewed = true;
|
|
93
|
+
} catch (error) {
|
|
94
|
+
res.writeHead(error instanceof TypeError || error instanceof SyntaxError ? 400 : 500);
|
|
95
|
+
res.end("无法保存设置,请检查配置文件权限后重试。");
|
|
96
|
+
} finally {
|
|
97
|
+
activeRequests--;
|
|
98
|
+
if (renewed) touch();
|
|
99
|
+
else armIdle();
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
server.requestTimeout = 10000;
|
|
103
|
+
server.headersTimeout = 10000;
|
|
104
|
+
await new Promise<void>((resolve, reject) => {
|
|
105
|
+
server.once("error", reject);
|
|
106
|
+
server.listen(0, "127.0.0.1", () => { server.off("error", reject); resolve(); });
|
|
107
|
+
});
|
|
108
|
+
const address = server.address();
|
|
109
|
+
if (!address || typeof address === "string") throw new Error("无法启动设置服务");
|
|
110
|
+
origin = `http://127.0.0.1:${address.port}`;
|
|
111
|
+
server.unref();
|
|
112
|
+
touch();
|
|
113
|
+
return {
|
|
114
|
+
url: `${origin}/#${token}`,
|
|
115
|
+
get closed() { return closed; },
|
|
116
|
+
touch,
|
|
117
|
+
close,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="zh-CN">
|
|
3
|
+
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
4
|
+
<title>Pi Mini Mode 设置</title>
|
|
5
|
+
<style>
|
|
6
|
+
:root{color-scheme:light dark;--background:light-dark(#f4f3ef,#141614);--foreground:light-dark(#1f241f,#eceee8);--surface:light-dark(#fffcf7,#1d211d);--muted:light-dark(#667066,#a8b0a4);--border:light-dark(#e2ddd4,#3a4038);--accent:light-dark(#2f5a3e,#b7d4b0);--destructive:light-dark(#a52c26,#ffafa5);--ring:var(--accent);--text-sm:.875rem;--text-base:1rem;--text-lg:2.75rem;--radius:8px}
|
|
7
|
+
*{box-sizing:border-box}body{margin:0;background:var(--background);color:var(--foreground);font:var(--text-base)/1.5 ui-sans-serif,system-ui,sans-serif}main{max-width:1080px;margin:auto;padding:40px 24px 72px}header{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;flex-wrap:wrap}h1{font:italic 400 var(--text-lg)/1.05 "Didot","Bodoni 72","Iowan Old Style","Songti SC","STSong",serif;letter-spacing:.04em;margin:0}h2{font-size:var(--text-sm);font-weight:600;margin:0 0 12px;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}.tagline{margin:8px 0 0;color:var(--muted);font-size:var(--text-sm)}nav{display:flex;gap:8px;align-items:center}.hint{margin:12px 0 0;color:var(--accent);font-weight:600}section{margin:28px 0}button{font:inherit;color:inherit;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:8px 12px;cursor:pointer}button:disabled{opacity:.4;cursor:default}:focus-visible{outline:2px solid var(--ring);outline-offset:3px}#preview{padding:16px 20px;background:var(--surface);border:1px dashed var(--accent);border-radius:var(--radius);font:var(--text-sm)/1.8 ui-monospace,monospace;display:flex;align-items:center;gap:12px;overflow-x:auto;min-height:72px;white-space:nowrap}#preview button{flex:none;font:inherit;padding:4px 2px;border-color:transparent;cursor:grab;white-space:nowrap}#preview button:hover{border-color:var(--border)}#preview button.over{border-left:2px solid var(--accent)}#preview #preview-context{flex:1;display:flex;align-items:center;gap:8px;min-width:180px}.progress{flex:1;overflow:hidden;text-align:left;color:var(--accent);min-width:0}.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(220px,1fr));gap:4px 16px}label{display:flex;align-items:center;gap:10px;padding:10px 0;cursor:pointer}input{accent-color:var(--accent);width:18px;height:18px;flex-shrink:0}.dragging{opacity:.45}#status{min-height:24px;color:var(--accent)}#status.error{color:var(--destructive)}#retry{margin-left:12px}[hidden]{display:none!important}nav button[aria-pressed=true]{border-color:var(--accent);color:var(--accent)}.features{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:12px}.feature{display:flex;flex-direction:column;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:16px 18px}.feature-head{display:flex;align-items:center;justify-content:space-between;gap:12px}.feature-head h3{margin:0;font-size:var(--text-base);font-weight:600}.feature-body{margin:10px 0 0;color:var(--muted);font-size:var(--text-sm);line-height:1.65}.feature-points{margin:10px 0 0;padding-left:1.15em;font-size:var(--text-sm);line-height:1.7}.feature-points li{margin:2px 0}.feature-points li::marker{color:var(--accent)}.feature-hint{margin:auto 0 0;padding-top:12px;color:var(--muted);font:var(--text-sm)/1.6 ui-monospace,monospace;overflow-wrap:anywhere}.feature-hint::before{content:'› ';color:var(--accent)}.switch{display:flex;align-items:center;gap:8px;padding:0;font-size:var(--text-sm);color:var(--muted)}.notice{display:flex;gap:16px;align-items:flex-start;justify-content:space-between;flex-wrap:wrap;margin:20px 0 0;padding:14px 16px;background:var(--surface);border:1px solid var(--accent);border-left-width:4px;border-radius:var(--radius)}.notice strong{font-size:var(--text-sm)}.notice p{margin:6px 0 0;color:var(--muted);font-size:var(--text-sm);line-height:1.6;max-width:640px}.notice code{display:block;margin:0 0 8px;padding:8px 10px;background:var(--background);border:1px solid var(--border);border-radius:var(--radius);font:var(--text-sm)/1.5 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;max-width:520px;color:var(--foreground)}#preview{margin-top:12px}@media(max-width:450px){h1{font-size:2rem}main{padding:24px 16px}}
|
|
8
|
+
</style>
|
|
9
|
+
<main>
|
|
10
|
+
<header>
|
|
11
|
+
<div><h1 id="title"></h1><p class="tagline" id="tagline"></p></div>
|
|
12
|
+
<nav>
|
|
13
|
+
<button type="button" id="lang-zh" aria-pressed="false">中文</button>
|
|
14
|
+
<button type="button" id="lang-en" aria-pressed="false">EN</button>
|
|
15
|
+
<button type="button" id="reset" disabled></button>
|
|
16
|
+
</nav>
|
|
17
|
+
</header>
|
|
18
|
+
<div class="notice" id="notice" hidden>
|
|
19
|
+
<div><strong id="noticeTitle"></strong><p id="noticeBody"></p></div>
|
|
20
|
+
<div><code id="noticePrompt"></code><button type="button" id="copyPrompt"></button></div>
|
|
21
|
+
</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
|
+
<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
|
+
<section><h2 id="optionsHeading"></h2><div class="grid" id="options"></div></section>
|
|
26
|
+
</main>
|
|
27
|
+
<script>
|
|
28
|
+
const $=id=>document.getElementById(id),token=location.hash.slice(1);
|
|
29
|
+
history.replaceState(null,'',location.pathname);
|
|
30
|
+
const I18N={
|
|
31
|
+
title:{zh:'Pi Mini Mode',en:'Pi Mini Mode'},
|
|
32
|
+
documentTitle:{zh:'Pi Mini Mode 设置',en:'Pi Mini Mode Settings'},
|
|
33
|
+
tagline:{zh:'极简状态栏配置',en:'Minimal status bar setup'},
|
|
34
|
+
dragHint:{zh:'拖拽预览中的字段可调整顺序,松手自动保存',en:'Drag items in the preview to reorder · Auto-saves on drop'},
|
|
35
|
+
featuresHeading:{zh:'功能说明',en:'Features'},
|
|
36
|
+
fieldsHeading:{zh:'状态栏字段与预览',en:'Status bar items & preview'},
|
|
37
|
+
optionsHeading:{zh:'状态栏样式',en:'Status bar style'},
|
|
38
|
+
on:{zh:'开启',en:'On'},off:{zh:'关闭',en:'Off'},
|
|
39
|
+
featureList:{
|
|
40
|
+
zh:[
|
|
41
|
+
{id:'status',title:'状态栏指标',body:'一行看清会话状态,随终端宽度自动取舍,不换行。',points:['模型与思考等级,会话与缓存 Token、缓存命中率、费用估算','上下文用量进度条与百分比','生成速度 tok/s,从第一个输出 token 起算,不含等待首字'],hint:'勾选需要的字段,拖拽预览中的条目即可排序。'},
|
|
42
|
+
{id:'minimal',setting:'pi-mini-mode-minimal-show',title:'极简输出',body:'把对话收成结论:思考、工具与技能汇成一棵按时间排序的可折叠过程树。',points:['长用户消息默认保留前四行,点击折叠控件展开全文','子代理行可展开活动记录与最终输出','Ctrl+O 展开或收起完整过程树,新问题默认收起','最终 Markdown 流畅呈现,失败与中断明确标记'],hint:'/pi-mini-mode-minimal on|off · /pi-mini-mode-prompts · /pi-mini-mode-history'},
|
|
43
|
+
{id:'input-enhancements',setting:'pi-mini-mode-input-enhancements',title:'输入增强',body:'让输入框和消息里的图片、技能与文件路径直接可用。',points:['光标移入图片路径即可预览,全屏编辑器也支持悬停','图片路径收纳为 [image1] 标签,提交时保留原图','空白后输入 / 就地搜索技能,并在光标处插入','点击图片标签或消息中的文件路径,用系统默认应用打开'],hint:'Ctrl+V 粘贴图片(Windows/WSL 使用 Alt+V)'},
|
|
44
|
+
{id:'themes',title:'明暗主题',body:'内置 cc-dark 与 cc-light 两套主题,Markdown、代码高亮、表格与 Mermaid 图表一并适配明暗。',points:['用户消息使用主题的用户背景色,与正文清晰区分','不支持、不完整或过宽的图表保留源文本'],hint:'/pi-mini-mode-setup 重新选择主题与全局全屏模式'}
|
|
45
|
+
],
|
|
46
|
+
en:[
|
|
47
|
+
{id:'status',title:'Status bar metrics',body:'The whole session state on one line, trimmed to fit narrow terminals instead of wrapping.',points:['Model and thinking level, session and cache tokens, cache hit rate, cost estimate','Context usage bar with percentage','Speed in tok/s, measured from the first output token, excluding time to first token'],hint:'Enable the items you need, then drag entries in the preview to reorder.'},
|
|
48
|
+
{id:'minimal',setting:'pi-mini-mode-minimal-show',title:'Minimal transcript',body:'Turns the conversation into conclusions: thinking, tools and skills collapse into one chronological, foldable tree.',points:['Long user messages keep four lines; click the fold control to expand','Subagent rows expand to activity and final output','Ctrl+O expands or collapses the full process tree; new questions start collapsed','Final Markdown streams plainly; failures and interrupts are marked'],hint:'/pi-mini-mode-minimal on|off · /pi-mini-mode-prompts · /pi-mini-mode-history'},
|
|
49
|
+
{id:'input-enhancements',setting:'pi-mini-mode-input-enhancements',title:'Input enhancements',body:'Makes images, skills and file paths usable right where you type.',points:['Preview an image as soon as the cursor enters its path; hovering works in fullscreen','Image paths collapse to [image1] labels while keeping the original path on submit','Type / after a space to search skills and insert one at the cursor','Click image labels or file paths in messages to open them in the default app'],hint:'Ctrl+V pastes images (Windows/WSL: Alt+V)'},
|
|
50
|
+
{id:'themes',title:'Light and dark themes',body:'Built-in cc-dark and cc-light adapt Markdown, code highlighting, tables and Mermaid diagrams to the color scheme.',points:['User messages use the theme user background to stand apart from the body','Unsupported, incomplete or overly wide diagrams keep their source text'],hint:'/pi-mini-mode-setup to pick a theme and global fullscreen mode again'}
|
|
51
|
+
]
|
|
52
|
+
},
|
|
53
|
+
reset:{zh:'恢复默认',en:'Reset defaults'},
|
|
54
|
+
retry:{zh:'重试',en:'Retry'},
|
|
55
|
+
confirmReset:{zh:'恢复默认排序与显示设置?',en:'Reset layout and visibility to defaults?'},
|
|
56
|
+
connecting:{zh:'正在同步…',en:'Connecting…'},
|
|
57
|
+
connected:{zh:'已同步',en:'In sync'},
|
|
58
|
+
unsaved:{zh:'未保存修改',en:'Unsaved changes'},
|
|
59
|
+
saving:{zh:'正在保存…',en:'Saving…'},
|
|
60
|
+
saved:{zh:'已保存',en:'Saved'},
|
|
61
|
+
saveFailed:{zh:'保存失败',en:'Failed to save'},
|
|
62
|
+
reconnect:{zh:'连接已断开,请从终端重新打开',en:'Disconnected. Please reopen from the terminal.'},
|
|
63
|
+
noticeTitle:{zh:'极简输出需要全屏渲染器',en:'Minimal transcript needs the fullscreen renderer'},
|
|
64
|
+
noticeBody:{zh:'极简输出已保存,但当前 Pi 运行在普通 TUI 模式,暂不生效。复制下面的提示词发给 Pi,让它帮你把 TUI 模式改为 fullscreen;重启 Pi 后生效(/reload 不会切换渲染器)。',en:'Minimal transcript is saved but inactive: Pi is running in regular TUI mode. Copy the prompt below into Pi to set TUI mode to fullscreen; it takes effect after restarting Pi (/reload does not switch the renderer).'},
|
|
65
|
+
noticePrompt:{zh:'把 Pi 全局设置中的 tuiMode 改为 fullscreen,然后告诉我怎么重启生效',en:'Set tuiMode to fullscreen in Pi global settings, then tell me how to restart for it to take effect'},
|
|
66
|
+
copyPrompt:{zh:'复制提示词',en:'Copy prompt'},
|
|
67
|
+
copied:{zh:'已复制',en:'Copied'},
|
|
68
|
+
copyFailed:{zh:'复制失败,请手动选中',en:'Copy failed — select manually'},
|
|
69
|
+
emptyPreview:{zh:'(未启用任何字段)',en:'(No items enabled)'},
|
|
70
|
+
fields:{
|
|
71
|
+
'project-branch':{zh:'项目与分支',en:'Project & Branch'},
|
|
72
|
+
model:{zh:'模型名称',en:'Model'},
|
|
73
|
+
thinking:{zh:'思考等级',en:'Thinking Level'},
|
|
74
|
+
branch:{zh:'仅分支',en:'Branch Only'},
|
|
75
|
+
'session-tokens':{zh:'会话 Token',en:'Session Tokens'},
|
|
76
|
+
'cache-tokens':{zh:'缓存 Token',en:'Cache Tokens'},
|
|
77
|
+
ch:{zh:'缓存命中率',en:'Cache Hit Rate'},
|
|
78
|
+
cost:{zh:'累计费用',en:'Cost'},
|
|
79
|
+
mcp:{zh:'MCP 服务数',en:'MCP Count'},
|
|
80
|
+
context:{zh:'上下文进度条',en:'Context Bar'},
|
|
81
|
+
'context-percent':{zh:'上下文百分比',en:'Context %'},
|
|
82
|
+
speed:{zh:'生成速度',en:'Speed'},
|
|
83
|
+
'context-dots':{zh:'点阵进度条',en:'Dot-matrix bar'},
|
|
84
|
+
'speed-unit':{zh:'速度附带单位',en:'Speed unit (tok/s)'},
|
|
85
|
+
minimal:{zh:'极简对话输出',en:'Minimal transcript'},
|
|
86
|
+
'input-enhancements':{zh:'输入体验增强',en:'Input enhancements'}
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
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
|
+
let lang=localStorage.piMiniModeLang||(navigator.language.startsWith('zh')?'zh':'en');
|
|
91
|
+
let data,state,order,dragged,saving=false,dirty=false,timer,copyTimer;
|
|
92
|
+
const key=id=>'pi-mini-mode-'+id+'-show';
|
|
93
|
+
const t=(id,fallback='')=>(I18N[id]?.[lang]??fallback);
|
|
94
|
+
const fieldLabel=id=>I18N.fields[id]?.[lang]||id;
|
|
95
|
+
const examples={'project-branch':'pi-mini-mode(main)',model:'deepseek-v4-flash',thinking:'high',branch:'main','session-tokens':'Total 45K','cache-tokens':'Cached 25K',ch:'CH 40.0%',cost:'$0.012',mcp:'◇ MCP 3',context:'500/1.0M','context-percent':'1%',speed:'120 tok/s'};
|
|
96
|
+
function status(text,error=false){$('status').textContent=text;$('status').className=error?'error':''}
|
|
97
|
+
function applyLang(){
|
|
98
|
+
document.documentElement.lang=lang==='zh'?'zh-CN':'en';
|
|
99
|
+
document.title=t('documentTitle');
|
|
100
|
+
for(const id of ['title','tagline','featuresHeading','fieldsHeading','optionsHeading','dragHint']) $(id).textContent=t(id);
|
|
101
|
+
$('reset').textContent=t('reset');$('retry').textContent=t('retry');
|
|
102
|
+
$('lang-zh').setAttribute('aria-pressed',String(lang==='zh'));
|
|
103
|
+
$('lang-en').setAttribute('aria-pressed',String(lang==='en'));
|
|
104
|
+
$('preview').setAttribute('aria-label',t('dragHint'));
|
|
105
|
+
}
|
|
106
|
+
async function request(method,body){
|
|
107
|
+
const response=await fetch('/settings',{method,headers:{Authorization:'Bearer '+token,...(body?{'Content-Type':'application/json'}:{})},body:body?JSON.stringify(body):undefined});
|
|
108
|
+
if(!response.ok)throw Error(await response.text()||t('saveFailed'));
|
|
109
|
+
return response.json();
|
|
110
|
+
}
|
|
111
|
+
function preview(){
|
|
112
|
+
const panel=$('preview'),scroll=panel.scrollLeft;
|
|
113
|
+
panel.replaceChildren();
|
|
114
|
+
const visible=order.filter(id=>state[key(id)]);
|
|
115
|
+
const values={...examples,speed:state['pi-mini-mode-speed-unit-show']?'120 tok/s':'120'};
|
|
116
|
+
for(const id of visible){
|
|
117
|
+
const button=document.createElement('button');
|
|
118
|
+
button.id='preview-'+id;button.type='button';button.textContent=values[id];button.draggable=true;
|
|
119
|
+
if(id==='context'){const bar=document.createElement('span');bar.className='progress';bar.setAttribute('aria-hidden','true');bar.textContent=state['pi-mini-mode-context-dots-show']?'⣿'+'⣀'.repeat(300):'█'+'░'.repeat(300);button.append(bar)}
|
|
120
|
+
button.setAttribute('aria-label',fieldLabel(id)+' · '+t('dragHint'));
|
|
121
|
+
button.ondragstart=event=>{dragged=id;event.dataTransfer.setData('text/plain',id);event.dataTransfer.effectAllowed='move';button.classList.add('dragging')};
|
|
122
|
+
button.ondragend=()=>{dragged=undefined;button.classList.remove('dragging');document.querySelectorAll('.over').forEach(el=>el.classList.remove('over'))};
|
|
123
|
+
button.ondragover=event=>{if(dragged){event.preventDefault();button.classList.add('over')}};
|
|
124
|
+
button.ondragleave=()=>button.classList.remove('over');
|
|
125
|
+
button.ondrop=event=>{event.preventDefault();const source=dragged;dragged=undefined;if(source){move(order.indexOf(source),order.indexOf(id));$('preview-'+source)?.focus()}};
|
|
126
|
+
button.onkeydown=event=>{if(event.key!=='ArrowLeft'&&event.key!=='ArrowRight')return;event.preventDefault();const target=visible[visible.indexOf(id)+(event.key==='ArrowLeft'?-1:1)];if(target){move(order.indexOf(id),order.indexOf(target));$('preview-'+id)?.focus()}};
|
|
127
|
+
panel.append(button);
|
|
128
|
+
}
|
|
129
|
+
if(!visible.length)panel.textContent=t('emptyPreview');
|
|
130
|
+
panel.scrollLeft=scroll;
|
|
131
|
+
}
|
|
132
|
+
function change(){dirty=true;state.footerOrder=[...order];preview();renderNotice();status(t('unsaved'));clearTimeout(timer);timer=setTimeout(save,250)}
|
|
133
|
+
async function save(){
|
|
134
|
+
if(saving)return;saving=true;$('retry').hidden=true;
|
|
135
|
+
try{while(dirty){dirty=false;const body=structuredClone(state);status(t('saving'));await request('PUT',body)}status(t('saved'))}
|
|
136
|
+
catch(error){dirty=true;status(t('saveFailed')+':'+error.message,true);$('retry').hidden=false}
|
|
137
|
+
finally{saving=false}
|
|
138
|
+
}
|
|
139
|
+
function box(settingId,onToggle){
|
|
140
|
+
const input=document.createElement('input');
|
|
141
|
+
input.type='checkbox';input.checked=!!state[settingId];input.id=settingId;
|
|
142
|
+
input.onchange=()=>{state[settingId]=input.checked;onToggle?.(input.checked)};
|
|
143
|
+
return input;
|
|
144
|
+
}
|
|
145
|
+
function feature(item){
|
|
146
|
+
const card=document.createElement('article');card.className='feature';
|
|
147
|
+
const head=document.createElement('div');head.className='feature-head';
|
|
148
|
+
const title=document.createElement('h3');title.textContent=item.title;head.append(title);
|
|
149
|
+
if(item.setting){
|
|
150
|
+
const label=document.createElement('label');label.className='switch';label.htmlFor=item.setting;
|
|
151
|
+
const text=document.createElement('span');text.textContent=state[item.setting]?t('on'):t('off');
|
|
152
|
+
label.append(box(item.setting,checked=>{text.textContent=checked?t('on'):t('off');change()}),text);
|
|
153
|
+
head.append(label);
|
|
154
|
+
}
|
|
155
|
+
const body=document.createElement('p');body.className='feature-body';body.textContent=item.body;
|
|
156
|
+
const points=document.createElement('ul');points.className='feature-points';
|
|
157
|
+
points.append(...item.points.map(point=>{const li=document.createElement('li');li.textContent=point;return li}));
|
|
158
|
+
const hint=document.createElement('p');hint.className='feature-hint';hint.textContent=item.hint;
|
|
159
|
+
card.append(head,body,points,hint);
|
|
160
|
+
return card;
|
|
161
|
+
}
|
|
162
|
+
function checkbox(id,settingId){
|
|
163
|
+
const label=document.createElement('label'),input=box(settingId,()=>{
|
|
164
|
+
if(state[settingId]&&(id==='project-branch'||id==='branch')){const other=key(id==='branch'?'project-branch':'branch');state[other]=false;const peer=$(other);if(peer)peer.checked=false}
|
|
165
|
+
change();
|
|
166
|
+
});
|
|
167
|
+
label.append(input,document.createTextNode(fieldLabel(id)));
|
|
168
|
+
return label;
|
|
169
|
+
}
|
|
170
|
+
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
|
+
function render(){
|
|
172
|
+
applyLang();
|
|
173
|
+
renderNotice();
|
|
174
|
+
$('fields').replaceChildren(...order.map(id=>checkbox(id,key(id))));
|
|
175
|
+
$('features').replaceChildren(...t('featureList').map(feature));
|
|
176
|
+
$('options').replaceChildren(...['context-dots','speed-unit'].map(id=>checkbox(id,FIELD_KEY[id])));
|
|
177
|
+
preview();
|
|
178
|
+
}
|
|
179
|
+
function renderNotice(){
|
|
180
|
+
// Minimal output needs the fullscreen renderer; only a known regular mode warrants the prompt.
|
|
181
|
+
const show=!!data&&data.tuiMode==='regular'&&!!state['pi-mini-mode-minimal-show'];
|
|
182
|
+
$('notice').hidden=!show;
|
|
183
|
+
if(!show)return;
|
|
184
|
+
$('noticeTitle').textContent=t('noticeTitle');
|
|
185
|
+
$('noticeBody').textContent=t('noticeBody');
|
|
186
|
+
$('noticePrompt').textContent=t('noticePrompt');
|
|
187
|
+
$('copyPrompt').textContent=t('copyPrompt');
|
|
188
|
+
}
|
|
189
|
+
$('copyPrompt').onclick=async()=>{
|
|
190
|
+
const button=$('copyPrompt');
|
|
191
|
+
try{await navigator.clipboard.writeText(t('noticePrompt'));button.textContent=t('copied')}
|
|
192
|
+
catch{
|
|
193
|
+
const range=document.createRange();range.selectNodeContents($('noticePrompt'));
|
|
194
|
+
const selection=getSelection();selection?.removeAllRanges();selection?.addRange(range);
|
|
195
|
+
button.textContent=t('copyFailed');
|
|
196
|
+
}
|
|
197
|
+
clearTimeout(copyTimer);
|
|
198
|
+
copyTimer=setTimeout(()=>button.textContent=t('copyPrompt'),1600);
|
|
199
|
+
};
|
|
200
|
+
function setLang(next){lang=next;localStorage.piMiniModeLang=lang;render()}
|
|
201
|
+
$('lang-zh').onclick=()=>setLang('zh');
|
|
202
|
+
$('lang-en').onclick=()=>setLang('en');
|
|
203
|
+
$('retry').onclick=save;
|
|
204
|
+
$('reset').onclick=()=>{if(!confirm(t('confirmReset')))return;state={...data.defaults};order=[...data.order];render();change()};
|
|
205
|
+
window.addEventListener('beforeunload',event=>{if(dirty||saving){event.preventDefault();event.returnValue=''}});
|
|
206
|
+
applyLang();status(t('connecting'));
|
|
207
|
+
request('GET').then(value=>{data=value;state={...data.settings};order=[...(state.footerOrder||data.order)];render();$('reset').disabled=false;status(t('connected'))}).catch(()=>status(t('reconnect'),true));
|
|
208
|
+
</script>
|
|
209
|
+
</html>
|
package/lib/sticky-tool.ts
CHANGED
|
@@ -60,7 +60,7 @@ export function attachStickyTool(tui: unknown, document: Component, view: Sticky
|
|
|
60
60
|
}
|
|
61
61
|
// At the original heading, use its document row rather than duplicating it.
|
|
62
62
|
shown = transcript.scrollTop > target.y ? target : undefined;
|
|
63
|
-
return shown ? [truncateToWidth(width < 5 ? "
|
|
63
|
+
return shown ? [truncateToWidth(width < 5 ? "▼" : shown.line, width, "")] : [];
|
|
64
64
|
},
|
|
65
65
|
handleMouse(event) {
|
|
66
66
|
if (!shown) return;
|
|
@@ -146,19 +146,22 @@ export function supervisorNotice(message: unknown) {
|
|
|
146
146
|
const header = content?.match(/^(?:Background task|Detached foreground task) (completed|failed|paused|stopped):\s+\*\*([^\*\n]+)\*\*/m);
|
|
147
147
|
if (!content || !header) return;
|
|
148
148
|
const status = header[1];
|
|
149
|
-
const failed = status === "failed" || status === "stopped"
|
|
149
|
+
const failed = status === "failed" || status === "stopped"
|
|
150
|
+
|| /^- key=\S+ run=[0-9a-f-]{36} status=failed\s*$/mi.test(content)
|
|
151
|
+
|| /^Child runs:.*\(failed\)/mi.test(content);
|
|
150
152
|
const attention = status === "paused";
|
|
151
153
|
const workflowRunId = content.match(/^Workflow run:\s*([0-9a-f-]{36})\s*$/mi)?.[1]
|
|
152
154
|
?? content.match(/^Workflow receipt:\s*.*?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/mi)?.[1];
|
|
153
155
|
const childRunIds = content.match(/^Child runs:\s*(.+)$/mi)?.[1]
|
|
154
156
|
?.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi) ?? [];
|
|
155
|
-
const
|
|
156
|
-
const
|
|
157
|
+
const directoryRunId = content.match(/^Retention-managed async directory:[ \t]*(?:\r?\n)?[^\r\n]*\/async-subagent-runs\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/?[ \t]*\r?$/mi)?.[1];
|
|
158
|
+
const runIds = [...new Set([workflowRunId, directoryRunId, ...childRunIds].filter((id): id is string => !!id))];
|
|
159
|
+
const runId = workflowRunId || directoryRunId || childRunIds[0];
|
|
157
160
|
const metadata = /^(?:Workflow (?:receipt|run):|Child runs:|Session(?: file| share error)?:|Retention-managed|Reconciled detached|Parallel handoff:|Watchdog blockers:)/i;
|
|
158
161
|
let preview = "";
|
|
159
162
|
for (const line of content.split("\n").slice(1)) {
|
|
160
163
|
const text = line.trim();
|
|
161
|
-
if (!text || text.startsWith("Workflow receipt:")) continue;
|
|
164
|
+
if (!text || text === `${header[2]}:` || text.startsWith("Workflow receipt:")) continue;
|
|
162
165
|
if (metadata.test(text)) break;
|
|
163
166
|
preview = text;
|
|
164
167
|
break;
|
|
@@ -171,7 +174,8 @@ export function supervisorNotice(message: unknown) {
|
|
|
171
174
|
alert: failed || attention,
|
|
172
175
|
state: failed ? "执行失败" : attention ? "需要关注" : "已完成",
|
|
173
176
|
color: failed ? "error" as const : attention ? "warning" as const : "muted" as const,
|
|
174
|
-
summary:
|
|
177
|
+
summary: failed && status === "completed" ? "工作流包含失败子任务"
|
|
178
|
+
: clean(preview) || (failed ? "子任务失败" : attention ? "等待回复" : "子任务已完成"),
|
|
175
179
|
label: clean(header[2]),
|
|
176
180
|
showLabel: true,
|
|
177
181
|
body: content,
|
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@each1024/pi-mini-mode",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.14",
|
|
4
4
|
"description": "A compact Pi footer with live usage metrics, theme-aware settings previews, and configurable progress bars.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"scripts": {
|
|
7
7
|
"check": "tsc --noEmit -p tsconfig.json",
|
|
8
|
-
"test": "node test/footer-tidy.mjs && node test/footer-status-self-check.mjs && node test/settings-interaction.mjs && node test/transcript-adapter.mjs && node test/prompt-folding.mjs && node test/tool-folding.mjs && node test/sticky-tool.mjs && node test/minimal-markdown.mjs && node test/agent-view.mjs && node test/publish-self-check.mjs && node test/compaction-transcript.mjs && node test/input-enhancements.mjs && node test/user-message-surface.mjs"
|
|
8
|
+
"test": "node test/settings-web.mjs && node test/footer-tidy.mjs && node test/footer-status-self-check.mjs && node test/settings-interaction.mjs && node test/transcript-adapter.mjs && node test/prompt-folding.mjs && node test/tool-folding.mjs && node test/sticky-tool.mjs && node test/minimal-markdown.mjs && node test/agent-view.mjs && node test/publish-self-check.mjs && node test/compaction-transcript.mjs && node test/input-enhancements.mjs && node test/user-message-surface.mjs"
|
|
9
9
|
},
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"author": "eachann1024",
|