@each1024/pi-mini-mode 2.0.18 → 2.0.20

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,5 +1,6 @@
1
1
  import type { Component } from "@earendil-works/pi-tui";
2
2
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import type { UiLanguage } from "./settings.ts";
3
4
  import { compactGoalCard, compactSupervisorNotice } from "./transcript-cards.ts";
4
5
  import { cacheMissLine, formatCacheTokens, isSupervisorReply, record, supervisorNotice } from "./transcript-notices.ts";
5
6
 
@@ -23,6 +24,7 @@ export interface NoticeOptions {
23
24
  supervisor?: {
24
25
  theme: ExtensionContext["ui"]["theme"];
25
26
  expanded: () => boolean;
27
+ language?: () => UiLanguage;
26
28
  handledRunIds?: () => Set<string>;
27
29
  onNotices?: (groups: Map<string | Component, { first: Component; messages: unknown[]; selected: unknown; notice: NonNullable<ReturnType<typeof supervisorNotice>> }>) => void;
28
30
  };
@@ -48,11 +50,12 @@ export function createTurnNoticeRenderer(chat: { children: Component[] }, option
48
50
  return width => {
49
51
  const notices = new Map<number, NoticeRows>();
50
52
  const expanded = options.supervisor?.expanded() ?? false;
53
+ const lang: UiLanguage = options.supervisor?.language?.() ?? "zh";
51
54
  if (expanded !== globalExpanded) { expandedNotices.clear(); globalExpanded = expanded; }
52
55
  const groups = new Map<string | Component, { first: Component; messages: unknown[]; selected: unknown; notice: NonNullable<ReturnType<typeof supervisorNotice>> }>();
53
56
  if (options.supervisor) for (const child of chat.children) {
54
57
  const message = supervisorEnvelope(child);
55
- const notice = supervisorNotice(message);
58
+ const notice = supervisorNotice(message, lang);
56
59
  if (!notice) continue;
57
60
  const key = notice.key ?? child;
58
61
  const group = groups.get(key);
@@ -113,8 +116,8 @@ export function createTurnNoticeRenderer(chat: { children: Component[] }, option
113
116
  continue;
114
117
  }
115
118
  if (child.constructor.name === "CustomEntryComponent"
116
- && !(options.supervisor && supervisorNotice(supervisorEnvelope(child)))) {
117
- const goalRows = options.supervisor && compactGoalCard((child as unknown as { entry?: unknown }).entry, options.supervisor.theme, width, expandedNotices.get(child) ?? false);
119
+ && !(options.supervisor && supervisorNotice(supervisorEnvelope(child), lang))) {
120
+ const goalRows = options.supervisor && compactGoalCard((child as unknown as { entry?: unknown }).entry, options.supervisor.theme, width, expandedNotices.get(child) ?? false, lang);
118
121
  const rows = notices.get(turn) ?? [];
119
122
  if (!goalRows) {
120
123
  rows.push(...child.render(width));
@@ -133,7 +136,7 @@ export function createTurnNoticeRenderer(chat: { children: Component[] }, option
133
136
  if (child.constructor.name === "CustomMessageComponent" || child.constructor.name === "CustomEntryComponent") {
134
137
  const rows = notices.get(turn) ?? [];
135
138
  const message = supervisorEnvelope(child);
136
- const notice = options.supervisor && supervisorNotice(message);
139
+ const notice = options.supervisor && supervisorNotice(message, lang);
137
140
  const key = notice ? notice.key ?? child : child;
138
141
  const group = groups.get(key);
139
142
  if (group && group.first !== child) continue;
@@ -144,11 +147,11 @@ export function createTurnNoticeRenderer(chat: { children: Component[] }, option
144
147
  const open = expandedNotices.get(key) ?? expanded;
145
148
  const label = group.notice.showLabel
146
149
  ? group.notice.label ?? ""
147
- : groups.size > 1 ? group.notice.label || `任务 ${groupKeys.indexOf(key) + 1}` : "";
150
+ : groups.size > 1 ? group.notice.label || (lang === "en" ? `Task ${groupKeys.indexOf(key) + 1}` : `任务 ${groupKeys.indexOf(key) + 1}`) : "";
148
151
  const targets = controls.get(turn) ?? [];
149
152
  targets.push({ y: rows.length, width, key, expanded: open });
150
153
  controls.set(turn, targets);
151
- rows.push(...compactSupervisorNotice(group.selected, options.supervisor.theme, width, open, label, group.messages)!);
154
+ rows.push(...compactSupervisorNotice(group.selected, options.supervisor.theme, width, open, label, group.messages, lang)!);
152
155
  } else rows.push(...child.render(width));
153
156
  notices.set(turn, rows);
154
157
  continue;
@@ -1,9 +1,63 @@
1
1
  import { stripVTControlCharacters } from "node:util";
2
+ import type { UiLanguage } from "./settings.ts";
2
3
 
3
4
  export const record = (value: unknown): Record<string, unknown> | undefined => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
4
5
  export const clean = (text: string) => stripVTControlCharacters(text).replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ").trim();
5
6
  export const isSupervisorReply = (message: unknown) => record(message)?.customType === "subagent_supervisor_reply";
6
7
 
8
+ const NOTICE_COPY: Record<UiLanguage, {
9
+ toolFailures: string;
10
+ completionGuard: string;
11
+ internalState: string;
12
+ internalSummary: string;
13
+ failedState: string;
14
+ completedState: string;
15
+ subtaskFailed: string;
16
+ subtaskCompleted: string;
17
+ attentionState: string;
18
+ workflowFailedSummary: string;
19
+ waitingReply: string;
20
+ questionState: string;
21
+ decisionState: string;
22
+ progressState: string;
23
+ noSummary: string;
24
+ }> = {
25
+ zh: {
26
+ toolFailures: "工具执行失败",
27
+ completionGuard: "任务完成受阻",
28
+ internalState: "内部协作",
29
+ internalSummary: "代理间沟通已收纳",
30
+ failedState: "执行失败",
31
+ completedState: "已完成",
32
+ subtaskFailed: "子任务失败",
33
+ subtaskCompleted: "子任务已完成",
34
+ attentionState: "需要关注",
35
+ workflowFailedSummary: "工作流包含失败子任务",
36
+ waitingReply: "等待回复",
37
+ questionState: "需要提问",
38
+ decisionState: "需要裁决",
39
+ progressState: "进度",
40
+ noSummary: "暂无摘要",
41
+ },
42
+ en: {
43
+ toolFailures: "Tool execution failed",
44
+ completionGuard: "Task completion blocked",
45
+ internalState: "Internal",
46
+ internalSummary: "Subagent communication folded",
47
+ failedState: "Failed",
48
+ completedState: "Completed",
49
+ subtaskFailed: "Subtask failed",
50
+ subtaskCompleted: "Subtask completed",
51
+ attentionState: "Needs attention",
52
+ workflowFailedSummary: "Workflow has failed subtasks",
53
+ waitingReply: "Waiting for reply",
54
+ questionState: "Question",
55
+ decisionState: "Decision needed",
56
+ progressState: "Progress",
57
+ noSummary: "No summary",
58
+ },
59
+ };
60
+
7
61
  /** Structured interview questions are the prompt; IDs and reply hints stay out. */
8
62
  export function formatInterview(interview: unknown): string {
9
63
  const data = record(interview);
@@ -35,7 +89,8 @@ function withInterview(body: string, interview: unknown): string {
35
89
  return body ? `${body}\n${questions}` : questions;
36
90
  }
37
91
 
38
- export function extractNoticeBody(message: unknown): string {
92
+ export function extractNoticeBody(message: unknown, lang: UiLanguage = "zh"): string {
93
+ const copy = NOTICE_COPY[lang] ?? NOTICE_COPY.zh;
39
94
  const item = record(message);
40
95
  if (!item) return typeof message === "string" ? clean(message) : "";
41
96
  const details = record(item.details);
@@ -52,7 +107,7 @@ export function extractNoticeBody(message: unknown): string {
52
107
  if (body) {
53
108
  let cleanBody = stripVTControlCharacters(body).replace(/^UPDATE:\s*/i, "").trim();
54
109
  const failureReason = typeof event?.reason === "string" && ["tool_failures", "completion_guard"].includes(event.reason)
55
- ? event.reason === "tool_failures" ? "工具执行失败" : "任务完成受阻"
110
+ ? event.reason === "tool_failures" ? copy.toolFailures : copy.completionGuard
56
111
  : undefined;
57
112
  if (failureReason && !cleanBody.includes(failureReason)) cleanBody = `[${failureReason}] ${cleanBody}`;
58
113
  return withInterview(cleanBody, interview);
@@ -81,7 +136,8 @@ export function extractNoticeBody(message: unknown): string {
81
136
  }
82
137
 
83
138
  /** Only pi-subagents' known envelopes carry state; prose is never a status signal. */
84
- export function supervisorNotice(message: unknown) {
139
+ export function supervisorNotice(message: unknown, lang: UiLanguage = "zh") {
140
+ const copy = NOTICE_COPY[lang] ?? NOTICE_COPY.zh;
85
141
  const item = record(message);
86
142
  if (item?.customType === "subagent_supervisor_reply") {
87
143
  const data = record(item.data);
@@ -99,9 +155,9 @@ export function supervisorNotice(message: unknown) {
99
155
  agent: data.agent,
100
156
  internal: true,
101
157
  alert: false,
102
- state: "内部协作",
158
+ state: copy.internalState,
103
159
  color: "muted" as const,
104
- summary: "代理间沟通已收纳",
160
+ summary: copy.internalSummary,
105
161
  body: stripVTControlCharacters(data.message).trim(),
106
162
  };
107
163
  }
@@ -126,9 +182,9 @@ export function supervisorNotice(message: unknown) {
126
182
  runIds,
127
183
  internal: false,
128
184
  alert: failed,
129
- state: failed ? "执行失败" : "已完成",
185
+ state: failed ? copy.failedState : copy.completedState,
130
186
  color: failed ? "error" as const : "muted" as const,
131
- summary: error || (failed ? "子任务失败" : "子任务已完成"),
187
+ summary: error || (failed ? copy.subtaskFailed : copy.subtaskCompleted),
132
188
  label: clean(header[2]),
133
189
  showLabel: true,
134
190
  body: content,
@@ -165,10 +221,10 @@ export function supervisorNotice(message: unknown) {
165
221
  runIds,
166
222
  internal: false,
167
223
  alert: failed || attention,
168
- state: failed ? "执行失败" : attention ? "需要关注" : "已完成",
224
+ state: failed ? copy.failedState : attention ? copy.attentionState : copy.completedState,
169
225
  color: failed ? "error" as const : attention ? "warning" as const : "muted" as const,
170
- summary: failed && status === "completed" ? "工作流包含失败子任务"
171
- : clean(preview) || (failed ? "子任务失败" : attention ? "等待回复" : "子任务已完成"),
226
+ summary: failed && status === "completed" ? copy.workflowFailedSummary
227
+ : clean(preview) || (failed ? copy.subtaskFailed : attention ? copy.waitingReply : copy.subtaskCompleted),
172
228
  label: clean(header[2]),
173
229
  showLabel: true,
174
230
  body: content,
@@ -202,10 +258,10 @@ export function supervisorNotice(message: unknown) {
202
258
  const key = runId && Number.isInteger(index) && Number(index) >= 0
203
259
  && !data.nestedRunId && !data.nestingPath ? JSON.stringify([runId, index]) : undefined;
204
260
  return { key, runId, internal, alert: failed || attention,
205
- state: failed ? "执行失败" : ask ? (details.reason === "interview_request" ? "需要提问" : "需要裁决")
206
- : attention ? "需要关注" : internal ? "内部协作" : "进度",
261
+ state: failed ? copy.failedState : ask ? (details.reason === "interview_request" ? copy.questionState : copy.decisionState)
262
+ : attention ? copy.attentionState : internal ? copy.internalState : copy.progressState,
207
263
  color: failed ? "error" as const : attention ? "warning" as const : "muted" as const,
208
- summary: internal ? "代理间沟通已收纳" : question || (ask ? interviewTitle || "等待回复" : "暂无摘要"),
264
+ summary: internal ? copy.internalSummary : question || (ask ? interviewTitle || copy.waitingReply : copy.noSummary),
209
265
  label: typeof data.label === "string" ? clean(data.label) : typeof data.taskPreview === "string" ? clean(data.taskPreview) : undefined,
210
266
  body: question,
211
267
  agent: typeof data.agent === "string" ? data.agent : undefined,
@@ -213,12 +269,12 @@ export function supervisorNotice(message: unknown) {
213
269
  }
214
270
 
215
271
  /** Progress is a status preview, not detail prose; decisions and failures remain inspectable. */
216
- export function supervisorNoticeBody(message: unknown): string {
272
+ export function supervisorNoticeBody(message: unknown, lang: UiLanguage = "zh"): string {
217
273
  const item = record(message);
218
274
  if (item?.customType === "subagent_supervisor_request" && record(item.details)?.reason === "progress_update") return "";
219
- const notice = supervisorNotice(message);
275
+ const notice = supervisorNotice(message, lang);
220
276
  if (item?.type === "custom" && item.customType === "subagent_supervisor_reply") return notice?.body ?? "";
221
- return notice?.alert || notice?.internal ? extractNoticeBody(message) : "";
277
+ return notice?.alert || notice?.internal ? extractNoticeBody(message, lang) : "";
222
278
  }
223
279
 
224
280
  /** Pi writes one warning line per miss (`Cache miss…: N tokens re-billed`). */
@@ -0,0 +1,309 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
+ import { readFileSync } from "node:fs";
4
+ import type { UiLanguage } from "./settings.ts";
5
+
6
+ export const UPDATE_RELEASE_DATE = "2026-11-05";
7
+ const MIN_BANNER_VERSION = "2.0.19";
8
+
9
+ export function isNewerVersion(current: string, previous?: string): boolean {
10
+ if (!/^\d+\.\d+\.\d+$/.test(current)) return false;
11
+ if (!previous) return true;
12
+ if (!/^\d+\.\d+\.\d+$/.test(previous)) return false;
13
+ const curParts = current.split(".").map(Number);
14
+ const prevParts = previous.split(".").map(Number);
15
+ for (let i = 0; i < 3; i++) {
16
+ if (curParts[i] !== prevParts[i]) return curParts[i] > prevParts[i];
17
+ }
18
+ return false;
19
+ }
20
+
21
+ function readPackageVersion(): string {
22
+ try {
23
+ const raw = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version?: unknown };
24
+ if (typeof raw.version === "string" && /^\d+\.\d+\.\d+$/.test(raw.version)) {
25
+ return isNewerVersion(raw.version, MIN_BANNER_VERSION) ? raw.version : MIN_BANNER_VERSION;
26
+ }
27
+ } catch {
28
+ // Fallback to MIN_BANNER_VERSION when package.json cannot be read.
29
+ }
30
+ return MIN_BANNER_VERSION;
31
+ }
32
+
33
+ export const PACKAGE_VERSION: string = readPackageVersion();
34
+
35
+ interface ReleaseNoteText {
36
+ highlights: string;
37
+ features?: readonly string[];
38
+ fixes?: readonly string[];
39
+ }
40
+
41
+ interface ReleaseEntry {
42
+ version: string;
43
+ date: string;
44
+ zh: ReleaseNoteText;
45
+ en: ReleaseNoteText;
46
+ }
47
+
48
+ export const RELEASE_HISTORY: readonly ReleaseEntry[] = [
49
+ {
50
+ version: "2.0.20",
51
+ date: "2026-11-05",
52
+ zh: {
53
+ highlights: "百轮长对话滚动、输入和点击保持流畅。",
54
+ fixes: [
55
+ "150 轮滚动中位响应由约 271ms 降到 7ms,300 轮由约 585ms 降到 11ms",
56
+ "鼠标悬停按行定位,中文、emoji 和链接命中与原来一致",
57
+ "主题切换和旧消息更新时正确清理显示缓存",
58
+ ],
59
+ },
60
+ en: {
61
+ highlights: "Long conversations stay responsive while scrolling, typing, and clicking.",
62
+ fixes: [
63
+ "Median scroll response for 150 turns dropped from about 271ms to 7ms, and for 300 turns from about 585ms to 11ms",
64
+ "Hover hit testing is per line, with the same results for CJK, emoji, and links",
65
+ "Display caches clear on theme changes and in-place updates to older messages",
66
+ ],
67
+ },
68
+ },
69
+ {
70
+ version: "2.0.19",
71
+ date: "2026-11-05",
72
+ zh: {
73
+ highlights: "长会话更流畅,Token 速度更准,子代理过程可见。",
74
+ features: [
75
+ "原生支持 pi -p 子代理过程树与分步用量,Ctrl+S 展开查看每步 Token 与耗时",
76
+ "升级后首次打开显示一次性更新摘要",
77
+ ],
78
+ fixes: [
79
+ "长会话折叠渲染提速 24×,96 轮会话每帧耗时由 121ms 降至 5ms",
80
+ "修正思考场景下 Token 速度虚高(500+ tok/s)",
81
+ ],
82
+ },
83
+ en: {
84
+ highlights: "Smoother long sessions, more accurate token speed, visible subagent progress.",
85
+ features: [
86
+ "Built-in pi -p subagent tree with per-step usage; press Ctrl+S to inspect tokens and duration",
87
+ "One-time release summary shown on first launch after upgrade",
88
+ ],
89
+ fixes: [
90
+ "24× faster collapsed-turn rendering; 96-turn frame time down from 121ms to 5ms",
91
+ "Fixed inflated token speed (500+ tok/s) while thinking",
92
+ ],
93
+ },
94
+ },
95
+ {
96
+ version: "2.0.18",
97
+ date: "2026-11-05",
98
+ zh: {
99
+ highlights: "图片路径展开更清晰。",
100
+ fixes: ["展开时图片路径与相邻非空白字符之间自动补空格"],
101
+ },
102
+ en: {
103
+ highlights: "Clearer image path expansion.",
104
+ fixes: ["Image paths are padded with spaces on expand when adjacent to non-whitespace"],
105
+ },
106
+ },
107
+ {
108
+ version: "2.0.17",
109
+ date: "2026-11-01",
110
+ zh: {
111
+ highlights: "文件链接体验统一。",
112
+ fixes: ["统一终端文件链接,并增加跨终端可用的悬停反馈"],
113
+ },
114
+ en: {
115
+ highlights: "Consistent file links.",
116
+ fixes: ["Unified terminal file links with portable hover feedback"],
117
+ },
118
+ },
119
+ {
120
+ version: "2.0.16",
121
+ date: "2026-10-28",
122
+ zh: {
123
+ highlights: "思考提示语随界面语言显示。",
124
+ fixes: ["思考兜底文案按所选语言本地化"],
125
+ },
126
+ en: {
127
+ highlights: "Thinking text follows the UI language.",
128
+ fixes: ["Thinking fallback text is localized to the selected language"],
129
+ },
130
+ },
131
+ {
132
+ version: "2.0.15",
133
+ date: "2026-10-18",
134
+ zh: {
135
+ highlights: "Token 速度刷新更及时。",
136
+ fixes: ["Token 速度每秒刷新两次"],
137
+ },
138
+ en: {
139
+ highlights: "More responsive token speed.",
140
+ fixes: ["Token speed refreshes twice a second"],
141
+ },
142
+ },
143
+ ];
144
+
145
+ export interface UpdateDay {
146
+ date: string;
147
+ versionLabel: string;
148
+ highlights: string;
149
+ features: string[];
150
+ fixes: string[];
151
+ }
152
+
153
+ function uniq(items: readonly string[]): string[] {
154
+ return [...new Set(items)];
155
+ }
156
+
157
+ export function resolveUpdateDays(
158
+ currentVersion: string,
159
+ previousVersion?: string,
160
+ language: UiLanguage = "zh",
161
+ ): UpdateDay[] {
162
+ const lang: UiLanguage = language === "en" ? "en" : "zh";
163
+ let entries = RELEASE_HISTORY.filter(
164
+ entry => isNewerVersion(entry.version, previousVersion) && !isNewerVersion(entry.version, currentVersion),
165
+ );
166
+ if (!previousVersion || entries.length === 0) {
167
+ const latest = RELEASE_HISTORY[0]?.date;
168
+ entries = RELEASE_HISTORY.filter(entry => entry.date === latest);
169
+ }
170
+ const dates = uniq(entries.map(entry => entry.date)).sort((a, b) => (a < b ? 1 : a > b ? -1 : 0));
171
+ return dates.map(date => {
172
+ const group = entries.filter(entry => entry.date === date);
173
+ const versions = group.map(entry => entry.version);
174
+ const oldest = versions[versions.length - 1];
175
+ const newest = versions[0];
176
+ const versionLabel = oldest === newest ? `v${newest}` : `v${oldest} – v${newest}`;
177
+ const notes = group.map(entry => entry[lang]);
178
+ return {
179
+ date,
180
+ versionLabel,
181
+ highlights: notes.map(n => n.highlights).join(lang === "en" ? " " : ""),
182
+ features: uniq(notes.flatMap(n => n.features ?? [])),
183
+ fixes: uniq(notes.flatMap(n => n.fixes ?? [])),
184
+ };
185
+ });
186
+ }
187
+
188
+ function notesForRelease(version: string, previousVersion: string | undefined, language: UiLanguage): UpdateDay[] {
189
+ if (!previousVersion) {
190
+ const entry = RELEASE_HISTORY.find(item => item.version === version) ?? RELEASE_HISTORY[0];
191
+ if (!entry) return [];
192
+ const note = entry[language];
193
+ return [{
194
+ date: entry.date,
195
+ versionLabel: `v${entry.version}`,
196
+ highlights: note.highlights,
197
+ features: [...(note.features ?? [])],
198
+ fixes: [...(note.fixes ?? [])],
199
+ }];
200
+ }
201
+ return resolveUpdateDays(version, previousVersion, language);
202
+ }
203
+
204
+ export function formatGitHubReleaseNotes(version: string = PACKAGE_VERSION, previousVersion?: string): string {
205
+ const sections: string[] = [];
206
+ for (const lang of ["zh", "en"] as const) {
207
+ const days = notesForRelease(version, previousVersion, lang);
208
+ const zh = lang === "zh";
209
+ const lines: string[] = [];
210
+ for (const day of days) {
211
+ lines.push(`### ${day.date} ${day.versionLabel}`, "");
212
+ lines.push(zh ? `🌈 本次更新重点:${day.highlights}` : `🌈 Highlights: ${day.highlights}`, "");
213
+ if (day.features.length > 0) {
214
+ lines.push(zh ? "✨ 新功能" : "✨ New", "", ...day.features.map(i => `- ${i}`), "");
215
+ }
216
+ if (day.fixes.length > 0) {
217
+ lines.push(zh ? "🐛 修复" : "🐛 Fixes", "", ...day.fixes.map(i => `- ${i}`), "");
218
+ }
219
+ }
220
+ sections.push(lines.join("\n").trimEnd());
221
+ }
222
+ return sections.join("\n\n---\n\n") + "\n";
223
+ }
224
+
225
+ function stripOsc8(text: string): string {
226
+ return text.replace(/\x1b\]8;;[^\x07]*\x07/g, "");
227
+ }
228
+
229
+ function widthOf(text: string): number {
230
+ return visibleWidth(stripOsc8(text));
231
+ }
232
+
233
+ export function renderUpdateBanner(
234
+ theme: Pick<ExtensionContext["ui"]["theme"], "fg" | "bold">,
235
+ width: number,
236
+ options: { version?: string; previousVersion?: string; language?: UiLanguage; collapsed?: boolean } = {},
237
+ ): { rows: string[]; headerRows: number } {
238
+ if (width < 24) return { rows: [], headerRows: 0 };
239
+ const version = options.version ?? PACKAGE_VERSION;
240
+ const lang: UiLanguage = options.language ?? "zh";
241
+ const collapsed = options.collapsed ?? false;
242
+ const days = resolveUpdateDays(version, options.previousVersion, lang);
243
+ const innerWidth = Math.max(1, width - 6);
244
+ const borderV = theme.fg("dim", "│");
245
+ const topBorder = theme.fg("dim", "╭" + "─".repeat(Math.max(0, width - 2)) + "╮");
246
+ const midBorder = theme.fg("dim", "├" + "─".repeat(Math.max(0, width - 2)) + "┤");
247
+ const bottomBorder = theme.fg("dim", "╰" + "─".repeat(Math.max(0, width - 2)) + "╯");
248
+
249
+ const boxLine = (content: string): string => {
250
+ const w = widthOf(content);
251
+ const fitted = w > innerWidth ? truncateToWidth(stripOsc8(content), innerWidth, "…") : content;
252
+ const pad = Math.max(0, innerWidth - widthOf(fitted));
253
+ return `${borderV} ${fitted}${" ".repeat(pad)} ${borderV}`;
254
+ };
255
+
256
+ const splitLine = (left: string, right: string, rightHref?: string): string => {
257
+ const lw = widthOf(left);
258
+ const rw = widthOf(right);
259
+ if (lw + 2 + rw <= innerWidth) {
260
+ const gap = " ".repeat(innerWidth - lw - rw);
261
+ const linkedRight = rightHref ? `\x1b]8;;${rightHref}\x07${right}\x1b]8;;\x07` : right;
262
+ return `${left}${gap}${linkedRight}`;
263
+ }
264
+ if (rw + 4 <= innerWidth) {
265
+ const truncatedLeft = truncateToWidth(stripOsc8(left), Math.max(1, innerWidth - rw - 2), "…");
266
+ const gap = " ".repeat(Math.max(1, innerWidth - widthOf(truncatedLeft) - rw));
267
+ const linkedRight = rightHref ? `\x1b]8;;${rightHref}\x07${right}\x1b]8;;\x07` : right;
268
+ return `${truncatedLeft}${gap}${linkedRight}`;
269
+ }
270
+ return truncateToWidth(stripOsc8(left), innerWidth, "…");
271
+ };
272
+
273
+ const leftHeader = theme.bold(theme.fg("accent", `pi-mini-mode v${version}`));
274
+ const rightHeader = theme.fg(
275
+ "muted",
276
+ collapsed ? (lang === "en" ? "[Expand]" : "[展开]") : (lang === "en" ? "[Collapse]" : "[收起]"),
277
+ );
278
+
279
+ const rows: string[] = [
280
+ topBorder,
281
+ boxLine(splitLine(leftHeader, rightHeader)),
282
+ ];
283
+
284
+ if (collapsed) {
285
+ rows.push(bottomBorder);
286
+ return { rows, headerRows: 3 };
287
+ }
288
+
289
+ const en = lang === "en";
290
+ days.forEach((day, idx) => {
291
+ rows.push(idx === 0 ? boxLine("") : midBorder);
292
+ rows.push(boxLine(theme.bold(theme.fg("text", day.date)) + " " + theme.fg("muted", day.versionLabel)));
293
+ const pushWrapped = (text: string) => {
294
+ for (const line of wrapTextWithAnsi(theme.fg("muted", text), innerWidth)) rows.push(boxLine(line));
295
+ };
296
+ pushWrapped(en ? `🌈 Highlights: ${day.highlights}` : `🌈 本次更新重点:${day.highlights}`);
297
+ if (day.features.length > 0) {
298
+ rows.push(boxLine(theme.bold(theme.fg("text", en ? "✨ New" : "✨ 新功能"))));
299
+ for (const item of day.features) pushWrapped(`- ${item}`);
300
+ }
301
+ if (day.fixes.length > 0) {
302
+ rows.push(boxLine(theme.bold(theme.fg("text", en ? "🐛 Fixes" : "🐛 修复"))));
303
+ for (const item of day.fixes) pushWrapped(`- ${item}`);
304
+ }
305
+ });
306
+
307
+ rows.push(bottomBorder);
308
+ return { rows, headerRows: 3 };
309
+ }
package/lib/usage.ts CHANGED
@@ -64,8 +64,15 @@ export interface CacheWaste {
64
64
  missCount: number;
65
65
  }
66
66
 
67
+ let cachedWaste: { len: number; first: unknown; last: unknown; value: CacheWaste } | undefined;
68
+
67
69
  /** Same noise floor as Pi's cache-miss notice. Compaction resets the baseline. */
68
70
  export function cacheWaste(entries: ReadonlyArray<{ type?: unknown; message?: { role?: unknown; usage?: UsageLike } }>): CacheWaste {
71
+ const first = entries[0];
72
+ const last = entries.at(-1);
73
+ if (cachedWaste && cachedWaste.len === entries.length && cachedWaste.first === first && cachedWaste.last === last) {
74
+ return { ...cachedWaste.value };
75
+ }
69
76
  let prev = 0;
70
77
  let reported = false;
71
78
  const totals = { missedTokens: 0, missCount: 0 };
@@ -83,18 +90,50 @@ export function cacheWaste(entries: ReadonlyArray<{ type?: unknown; message?: {
83
90
  }
84
91
  if (prompt > 0) { prev = prompt; reported ||= cacheRead + cacheWrite > 0; }
85
92
  }
86
- return totals;
93
+ cachedWaste = { len: entries.length, first, last, value: totals };
94
+ return { ...totals };
87
95
  }
88
96
 
97
+ let cachedSessionUsage: { sm: unknown; key: string; first: unknown; last: unknown; value: SessionUsage } | undefined;
98
+
89
99
  /** Aggregate persisted, finalized usage once per active-branch entry. */
90
100
  export function sessionUsage(ctx: ExtensionContext): SessionUsage {
91
- return ctx.sessionManager.getBranch().reduce((total, entry) => {
101
+ const sm = ctx.sessionManager as { getLeafId?(): string | null; getEntries?(): unknown[]; getBranch(): Array<{ type?: unknown; message?: unknown }> };
102
+ const hasFastKey = typeof sm.getLeafId === "function" && typeof sm.getEntries === "function";
103
+ if (hasFastKey) {
104
+ const entries = sm.getEntries!();
105
+ const key = `${sm.getLeafId!() ?? ""}:${entries.length}`;
106
+ const first = entries[0];
107
+ const last = entries.at(-1);
108
+ if (cachedSessionUsage && cachedSessionUsage.sm === sm && cachedSessionUsage.key === key && cachedSessionUsage.first === first && cachedSessionUsage.last === last) {
109
+ return { ...cachedSessionUsage.value };
110
+ }
111
+ const value = sm.getBranch().reduce((total, entry) => {
112
+ if (entry.type !== "message") return total;
113
+ const message = entry.message as { role?: unknown; usage?: UsageLike };
114
+ return message.role === "assistant" || message.role === "toolResult"
115
+ ? addUsage(total, message.usage)
116
+ : total;
117
+ }, { ...EMPTY_USAGE });
118
+ cachedSessionUsage = { sm, key, first, last, value };
119
+ return { ...value };
120
+ }
121
+ const branch = sm.getBranch();
122
+ const key = `b:${branch.length}`;
123
+ const first = branch[0];
124
+ const last = branch.at(-1);
125
+ if (cachedSessionUsage && cachedSessionUsage.sm === sm && cachedSessionUsage.key === key && cachedSessionUsage.first === first && cachedSessionUsage.last === last) {
126
+ return { ...cachedSessionUsage.value };
127
+ }
128
+ const value = branch.reduce((total, entry) => {
92
129
  if (entry.type !== "message") return total;
93
130
  const message = entry.message as { role?: unknown; usage?: UsageLike };
94
131
  return message.role === "assistant" || message.role === "toolResult"
95
132
  ? addUsage(total, message.usage)
96
133
  : total;
97
134
  }, { ...EMPTY_USAGE });
135
+ cachedSessionUsage = { sm, key, first, last, value };
136
+ return { ...value };
98
137
  }
99
138
 
100
139
  export function cacheHit(usage: SessionUsage): number | undefined {
@@ -116,12 +155,6 @@ export function formatSpeed(speed: number, showUnit: boolean): string {
116
155
  return showUnit ? `${value} tok/s` : value;
117
156
  }
118
157
 
119
- export interface ActiveGeneration {
120
- firstTokenAt?: number;
121
- output: number;
122
- lastSampleAt: number;
123
- }
124
-
125
158
  /** Hide sub-100ms bursts (batched usage) and 1-token completions; they are not a decode rate. */
126
159
  export const DECODE_SPEED_MIN_ELAPSED_MS = 100;
127
160
  export const DECODE_SPEED_MIN_OUTPUT = 2;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@each1024/pi-mini-mode",
3
- "version": "2.0.18",
3
+ "version": "2.0.20",
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": {
@@ -29,6 +29,7 @@
29
29
  "tui"
30
30
  ],
31
31
  "pi": {
32
+ "changelogPath": "",
32
33
  "video": "https://raw.githubusercontent.com/eachann1024/pi-mini-mode/main/assets/pi-mini-mode-demo.mp4",
33
34
  "extensions": [
34
35
  "./extensions/footer-status.ts"