@each1024/pi-mini-mode 1.3.1 → 1.3.2
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 +11 -7
- package/extensions/footer-status.ts +620 -150
- package/lib/agent-view.ts +393 -26
- package/lib/footer-tidy.ts +122 -0
- package/lib/minimal-markdown.ts +103 -2
- package/lib/sticky-tool.ts +100 -0
- package/lib/title-plain.ts +57 -0
- package/lib/transcript-adapter.ts +448 -11
- package/package.json +8 -3
- package/themes/README.md +5 -0
- package/themes/cc-dark.json +91 -0
- package/themes/cc-light.json +91 -0
- package/README.zh-CN.md +0 -178
|
@@ -1,12 +1,15 @@
|
|
|
1
|
-
import { agentCall, attachAgentWidgets, type AgentCall } from "../lib/agent-view.ts";
|
|
1
|
+
import { AGENT_STATUS_ENTRY, savedAgentStatuses, retainAgentStatuses, agentChildren, agentCall, agentCallDisplay, agentStatusesByTurn, attachAgentWidgets, isAgentTool, liveAgentView, readAgentStatuses, runningGlyph, type AgentCall } from "../lib/agent-view.ts";
|
|
2
2
|
import { CONFIG_DIR_NAME, getSettingsListTheme, getMarkdownTheme, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
3
|
-
import { attachTranscript, type TurnNotices } from "../lib/transcript-adapter.ts";
|
|
4
|
-
import { diagramMarkdown } from "../lib/minimal-markdown.ts";
|
|
3
|
+
import { attachTranscript, type NoticeRows, type TurnNotices } from "../lib/transcript-adapter.ts";
|
|
4
|
+
import { diagramMarkdown, minimalMarkdownTheme } from "../lib/minimal-markdown.ts";
|
|
5
5
|
import { minimalSurface } from "../lib/minimal-theme.ts";
|
|
6
|
-
import { Container, Markdown, matchesKey, isKeyRelease, isKeyRepeat, type SettingItem, SettingsList, Text, type TuiMouseEvent, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
6
|
+
import { Container, Markdown, matchesKey, isKeyRelease, isKeyRepeat, sliceByColumn, type SettingItem, SettingsList, Text, type TuiMouseEvent, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
|
|
7
7
|
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
8
8
|
import { homedir } from "node:os";
|
|
9
|
+
import { stripVTControlCharacters } from "node:util";
|
|
9
10
|
import { dirname, join } from "node:path";
|
|
11
|
+
import attachFooterTidy from "../lib/footer-tidy.ts";
|
|
12
|
+
import attachTitlePlain from "../lib/title-plain.ts";
|
|
10
13
|
|
|
11
14
|
export const SETTINGS_FILE_NAME = "mini-lens.json";
|
|
12
15
|
|
|
@@ -46,7 +49,7 @@ export const DEFAULT_SETTINGS: Readonly<MiniLensSettings> = {
|
|
|
46
49
|
"mini-lens-context-percent-show": true,
|
|
47
50
|
"mini-lens-speed-show": true,
|
|
48
51
|
"mini-lens-speed-unit-show": true,
|
|
49
|
-
"mini-lens-minimal-show":
|
|
52
|
+
"mini-lens-minimal-show": false,
|
|
50
53
|
"mini-lens-minimal-thinking-show": true,
|
|
51
54
|
"mini-lens-minimal-tools-show": true,
|
|
52
55
|
"mini-lens-minimal-output-show": true,
|
|
@@ -58,6 +61,15 @@ export const DEFAULT_SETTINGS: Readonly<MiniLensSettings> = {
|
|
|
58
61
|
|
|
59
62
|
const SETTING_IDS = Object.keys(DEFAULT_SETTINGS) as Array<keyof MiniLensSettings>;
|
|
60
63
|
|
|
64
|
+
const COPY = {
|
|
65
|
+
title: "Mini Lens 设置", preview: "预览(示例数据)", lens: "Lens", minimal: "极简输出",
|
|
66
|
+
model: "显示模型", thinking: "显示思考等级", total: "显示会话总 token", cached: "显示会话缓存 token", totalLabel: "Total", cachedLabel: "Cached", cacheHitLabel: "CH", cacheHit: "显示缓存命中率 (CH)", price: "显示会话价格", mcp: "显示已启用 MCP 服务器", context: "显示上下文 token 与进度条", dots: "↳ 使用点阵进度条", percent: "显示上下文百分比", speed: "显示最近生成速度", speedUnit: "↳ 显示 tok/s 单位", enableMinimal: "折叠回复", showThinking: "显示思考", tools: "显示工具调用", output: "显示过程输出", skills: "显示技能", agentUsage: "显示 Agent token 用量", shortcut: "新 Agent 显示 Ctrl+O 提示(6 秒)",
|
|
67
|
+
totalDescription: "Total:当前会话分支上的全部 token,含工具上报的 LLM 用量。", cachedDescription: "Cached:累计 cache-read + cache-write token(包含在 Total 中)。", cacheHitDescription: "CH(cache hit):cache-read / (input + cache-read)。Cache write 不计入此比率。",
|
|
68
|
+
enableMinimalDescription: "关闭后保留 Pi 默认会话历史。",
|
|
69
|
+
minimalLocked: "打开「折叠回复」后才能配置这些选项。",
|
|
70
|
+
tuiRequired: "/mini-lens-settings 需要 TUI 模式", saveFailed: "无法保存 Mini Lens 设置", minimalRequired: "/mini-lens-minimal 需要 TUI 模式", minimalUsage: "用法:/mini-lens-minimal [on|off]", minimalState: "Mini Lens 折叠回复:", onboarding: "MCP 数量、点阵样式和折叠回复默认关闭;其余项默认开启。", keepDefaults: "保留默认", configureNow: "立即配置",
|
|
71
|
+
} as const;
|
|
72
|
+
|
|
61
73
|
export function settingsPath(agentDir = process.env.MINI_LENS_AGENT_DIR ?? join(homedir(), CONFIG_DIR_NAME, "agent")): string {
|
|
62
74
|
return join(agentDir, SETTINGS_FILE_NAME);
|
|
63
75
|
}
|
|
@@ -68,7 +80,11 @@ function isBoolean(value: unknown): value is boolean {
|
|
|
68
80
|
|
|
69
81
|
export function parseSettings(value: unknown): MiniLensSettings {
|
|
70
82
|
const candidate = value && typeof value === "object" ? value as Record<string, unknown> : {};
|
|
71
|
-
|
|
83
|
+
const settings = { ...DEFAULT_SETTINGS };
|
|
84
|
+
for (const id of SETTING_IDS) {
|
|
85
|
+
if (isBoolean(candidate[id])) settings[id] = candidate[id];
|
|
86
|
+
}
|
|
87
|
+
return settings;
|
|
72
88
|
}
|
|
73
89
|
|
|
74
90
|
export async function loadSettings(path = settingsPath()): Promise<{ settings: MiniLensSettings; exists: boolean }> {
|
|
@@ -189,6 +205,37 @@ export function formatSpeed(speed: number, showUnit: boolean): string {
|
|
|
189
205
|
return showUnit ? `${value} tok/s` : value;
|
|
190
206
|
}
|
|
191
207
|
|
|
208
|
+
const PLANNOTATOR_STATUS_KEY = "plannotator";
|
|
209
|
+
const PLANNOTATOR_PLANNING_LABEL = "⏸ plan";
|
|
210
|
+
const PLAN_CAP_LEFT = "\uE0B6";
|
|
211
|
+
const PLAN_CAP_RIGHT = "\uE0B4";
|
|
212
|
+
const PLAN_BG = "250;204;21";
|
|
213
|
+
const PLAN_FG = "19;18;23";
|
|
214
|
+
|
|
215
|
+
function plannotatorStatusText(text: string | undefined): string {
|
|
216
|
+
return stripVTControlCharacters(text ?? "").replace(/\s+/g, " ").trim();
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Exact plannotator planning label from @plannotator/pi-extension (`⏸ plan`). */
|
|
220
|
+
export function isPlannotatorPlanningStatus(text: string | undefined): boolean {
|
|
221
|
+
return plannotatorStatusText(text) === PLANNOTATOR_PLANNING_LABEL;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Scheme B PLAN capsule. visibleWidth===1 only protects columns; it is not a font check. */
|
|
225
|
+
export function planCapsule(): string {
|
|
226
|
+
const paint = (text: string) => `\x1b[48;2;${PLAN_BG}m\x1b[38;2;${PLAN_FG}m${text}\x1b[39m\x1b[49m`;
|
|
227
|
+
if (visibleWidth(PLAN_CAP_LEFT) === 1 && visibleWidth(PLAN_CAP_RIGHT) === 1) {
|
|
228
|
+
const cap = (ch: string) => `\x1b[38;2;${PLAN_BG}m${ch}\x1b[39m`;
|
|
229
|
+
return `${cap(PLAN_CAP_LEFT)}${paint("PLAN")}${cap(PLAN_CAP_RIGHT)}`;
|
|
230
|
+
}
|
|
231
|
+
return paint(" PLAN ");
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function plannotatorPlanTag(statuses: ReadonlyMap<string, string> | undefined): string {
|
|
235
|
+
const text = statuses?.get(PLANNOTATOR_STATUS_KEY);
|
|
236
|
+
return isPlannotatorPlanningStatus(text) ? planCapsule() : "";
|
|
237
|
+
}
|
|
238
|
+
|
|
192
239
|
function renderRight(
|
|
193
240
|
theme: ExtensionContext["ui"]["theme"],
|
|
194
241
|
settings: MiniLensSettings,
|
|
@@ -240,6 +287,7 @@ export function statusLine(
|
|
|
240
287
|
speed: number | undefined,
|
|
241
288
|
highlighted?: keyof MiniLensSettings,
|
|
242
289
|
mcpCount?: number,
|
|
290
|
+
statuses?: ReadonlyMap<string, string>,
|
|
243
291
|
): string {
|
|
244
292
|
if (highlighted === "mini-lens-context-dots-show") highlighted = "mini-lens-context-show";
|
|
245
293
|
const field = (id: keyof MiniLensSettings, color: Parameters<typeof theme.fg>[0], text: string) =>
|
|
@@ -248,7 +296,7 @@ export function statusLine(
|
|
|
248
296
|
const model = ctx.model?.id ?? "";
|
|
249
297
|
const thinking = ctx.thinkingLevel ?? "";
|
|
250
298
|
const hit = cacheHit(usageTotals);
|
|
251
|
-
const hitText = hit === undefined ? "" :
|
|
299
|
+
const hitText = hit === undefined ? "" : `${COPY.cacheHitLabel} ${hit.toFixed(1)}%`;
|
|
252
300
|
const cachedTokens = usageTotals.cacheRead + usageTotals.cacheWrite;
|
|
253
301
|
const price = usageTotals.cost > 0 ? formatUsd(usageTotals.cost) : "";
|
|
254
302
|
const contextUsage = ctx.getContextUsage();
|
|
@@ -260,6 +308,7 @@ export function statusLine(
|
|
|
260
308
|
const tokenText = tokens === undefined || contextWindow === undefined ? "" : `${formatTokens(Math.max(0, tokens))}/${formatTokens(Math.max(0, contextWindow))}`;
|
|
261
309
|
const showContext = settings["mini-lens-context-show"] && Boolean(tokenText);
|
|
262
310
|
const mcpText = settings["mini-lens-mcp-show"] && mcpCount !== undefined ? `◇ MCP ${mcpCount}` : "";
|
|
311
|
+
const planTag = plannotatorPlanTag(statuses);
|
|
263
312
|
|
|
264
313
|
const right = renderRight(theme, settings, percentText, speed, highlighted);
|
|
265
314
|
const rightWidth = visibleWidth(right);
|
|
@@ -271,19 +320,21 @@ export function statusLine(
|
|
|
271
320
|
}
|
|
272
321
|
|
|
273
322
|
const leftParts = [
|
|
323
|
+
planTag,
|
|
274
324
|
settings["mini-lens-model-show"] && model && field("mini-lens-model-show", "accent", model),
|
|
275
325
|
settings["mini-lens-thinking-show"] && thinking && field("mini-lens-thinking-show", "muted", thinking),
|
|
276
|
-
settings["mini-lens-session-tokens-show"] && field("mini-lens-session-tokens-show", "text",
|
|
277
|
-
settings["mini-lens-cache-tokens-show"] && field("mini-lens-cache-tokens-show", "text",
|
|
326
|
+
settings["mini-lens-session-tokens-show"] && usageTotals.totalTokens > 0 && field("mini-lens-session-tokens-show", "text", `${COPY.totalLabel} ${formatTokens(usageTotals.totalTokens)}`),
|
|
327
|
+
settings["mini-lens-cache-tokens-show"] && cachedTokens > 0 && field("mini-lens-cache-tokens-show", "text", `${COPY.cachedLabel} ${formatTokens(cachedTokens)}`),
|
|
278
328
|
settings["mini-lens-ch-show"] && hitText && field("mini-lens-ch-show", "text", hitText),
|
|
279
329
|
settings["mini-lens-cost-show"] && price && field("mini-lens-cost-show", "muted", price),
|
|
280
330
|
mcpText && field("mini-lens-mcp-show", "muted", mcpText),
|
|
281
331
|
].filter((part): part is string => Boolean(part));
|
|
282
332
|
const unstyledLeft = [
|
|
333
|
+
planTag && stripVTControlCharacters(planTag),
|
|
283
334
|
settings["mini-lens-model-show"] && model,
|
|
284
335
|
settings["mini-lens-thinking-show"] && thinking,
|
|
285
|
-
settings["mini-lens-session-tokens-show"] &&
|
|
286
|
-
settings["mini-lens-cache-tokens-show"] &&
|
|
336
|
+
settings["mini-lens-session-tokens-show"] && usageTotals.totalTokens > 0 && `${COPY.totalLabel} ${formatTokens(usageTotals.totalTokens)}`,
|
|
337
|
+
settings["mini-lens-cache-tokens-show"] && cachedTokens > 0 && `${COPY.cachedLabel} ${formatTokens(cachedTokens)}`,
|
|
287
338
|
settings["mini-lens-ch-show"] && hitText,
|
|
288
339
|
settings["mini-lens-cost-show"] && price,
|
|
289
340
|
mcpText,
|
|
@@ -312,40 +363,20 @@ export function statusLine(
|
|
|
312
363
|
return truncateToWidth(`${content}${content ? gap : ""}${right}`, width, "");
|
|
313
364
|
}
|
|
314
365
|
|
|
315
|
-
function
|
|
366
|
+
export function isCollapsedReplyChildSetting(id: string): boolean {
|
|
367
|
+
return id === "mini-lens-minimal-thinking-show" || id === "mini-lens-minimal-tools-show" || id === "mini-lens-minimal-output-show"
|
|
368
|
+
|| id === "mini-lens-minimal-skills-show" || id === "mini-lens-agent-usage-show" || id === "mini-lens-agent-shortcut-show";
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
export function settingsItems(settings: MiniLensSettings): SettingItem[] {
|
|
372
|
+
const values = ["on", "off"];
|
|
316
373
|
const labels: Record<Exclude<keyof MiniLensSettings, "onboardingCompleted">, string> = {
|
|
317
|
-
"mini-lens-model-show": "
|
|
318
|
-
"mini-lens-thinking-show": "Show thinking level",
|
|
319
|
-
"mini-lens-session-tokens-show": "Show total session tokens",
|
|
320
|
-
"mini-lens-cache-tokens-show": "Show session cache tokens",
|
|
321
|
-
"mini-lens-ch-show": "Show cache hit rate (CH)",
|
|
322
|
-
"mini-lens-cost-show": "Show session price",
|
|
323
|
-
"mini-lens-mcp-show": "Show enabled MCP servers",
|
|
324
|
-
"mini-lens-context-show": "Show context tokens and progress bar",
|
|
325
|
-
"mini-lens-context-dots-show": "↳ Use dot-matrix progress bar",
|
|
326
|
-
"mini-lens-context-percent-show": "Show context percentage",
|
|
327
|
-
"mini-lens-speed-show": "Show latest generation speed",
|
|
328
|
-
"mini-lens-speed-unit-show": "↳ Show tok/s unit",
|
|
329
|
-
"mini-lens-minimal-show": "启用极简模式",
|
|
330
|
-
"mini-lens-minimal-thinking-show": "显示思考",
|
|
331
|
-
"mini-lens-minimal-tools-show": "显示工具调用",
|
|
332
|
-
"mini-lens-minimal-output-show": "显示执行输出",
|
|
333
|
-
"mini-lens-minimal-skills-show": "显示 skill",
|
|
334
|
-
"mini-lens-agent-usage-show": "显示 Agent Token 用量",
|
|
335
|
-
"mini-lens-agent-shortcut-show": "新 Agent 显示 Ctrl+O 提示(6 秒)",
|
|
374
|
+
"mini-lens-model-show": COPY.model, "mini-lens-thinking-show": COPY.thinking, "mini-lens-session-tokens-show": COPY.total, "mini-lens-cache-tokens-show": COPY.cached, "mini-lens-ch-show": COPY.cacheHit, "mini-lens-cost-show": COPY.price, "mini-lens-mcp-show": COPY.mcp, "mini-lens-context-show": COPY.context, "mini-lens-context-dots-show": COPY.dots, "mini-lens-context-percent-show": COPY.percent, "mini-lens-speed-show": COPY.speed, "mini-lens-speed-unit-show": COPY.speedUnit, "mini-lens-minimal-show": COPY.enableMinimal, "mini-lens-minimal-thinking-show": COPY.showThinking, "mini-lens-minimal-tools-show": COPY.tools, "mini-lens-minimal-output-show": COPY.output, "mini-lens-minimal-skills-show": COPY.skills, "mini-lens-agent-usage-show": COPY.agentUsage, "mini-lens-agent-shortcut-show": COPY.shortcut,
|
|
336
375
|
};
|
|
337
|
-
return (Object.keys(labels) as Array<
|
|
338
|
-
id,
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
? "Total: all tokens used on the current session branch, including tool-reported LLM usage."
|
|
342
|
-
: id === "mini-lens-cache-tokens-show"
|
|
343
|
-
? "Cached: cumulative cache-read + cache-write tokens (part of Total)."
|
|
344
|
-
: id === "mini-lens-ch-show"
|
|
345
|
-
? "CH (cache hit): cache-read / (input + cache-read). Cache writes are not included in this rate."
|
|
346
|
-
: undefined,
|
|
347
|
-
currentValue: settings[id] ? "on" : "off",
|
|
348
|
-
values: ["on", "off"],
|
|
376
|
+
return (Object.keys(labels) as Array<keyof typeof labels>).map((id) => ({
|
|
377
|
+
id, label: labels[id],
|
|
378
|
+
description: id === "mini-lens-minimal-show" ? COPY.enableMinimalDescription : id === "mini-lens-session-tokens-show" ? COPY.totalDescription : id === "mini-lens-cache-tokens-show" ? COPY.cachedDescription : id === "mini-lens-ch-show" ? COPY.cacheHitDescription : undefined,
|
|
379
|
+
currentValue: settings[id] ? values[0] : values[1], values,
|
|
349
380
|
}));
|
|
350
381
|
}
|
|
351
382
|
|
|
@@ -368,13 +399,20 @@ export interface MinimalTurn {
|
|
|
368
399
|
usage?: SessionUsage;
|
|
369
400
|
pendingUsage?: UsageLike;
|
|
370
401
|
agentCalls?: AgentCall[];
|
|
402
|
+
subAgents?: Record<string, unknown>[];
|
|
371
403
|
process: string[];
|
|
372
404
|
final?: string;
|
|
405
|
+
replies?: string[];
|
|
373
406
|
running?: boolean;
|
|
407
|
+
/** Wall-clock start of this user-request execution; retained across tool and thinking turns. */
|
|
408
|
+
startedAt?: number;
|
|
409
|
+
thinking?: number;
|
|
410
|
+
awaitingResponse?: boolean;
|
|
374
411
|
waitingTools?: Array<{ id: string; name: string; startedAt: number }>;
|
|
375
412
|
}
|
|
376
413
|
|
|
377
414
|
const PROCESS_PREVIEW_LIMIT = 180;
|
|
415
|
+
const THINKING_SCROLL_INTERVAL_MS = 80;
|
|
378
416
|
|
|
379
417
|
function contentText(content: unknown): string {
|
|
380
418
|
if (typeof content === "string") return content.trim();
|
|
@@ -401,6 +439,14 @@ function processText(value: unknown): string {
|
|
|
401
439
|
return contentText(value) || (value === undefined ? "" : JSON.stringify(value) ?? "");
|
|
402
440
|
}
|
|
403
441
|
|
|
442
|
+
/** Format an execution duration without losing hours once a long run crosses one. */
|
|
443
|
+
export function formatElapsed(startedAt: number | undefined, now = Date.now()): string {
|
|
444
|
+
const seconds = Math.max(0, Math.floor((now - (startedAt ?? now)) / 1_000));
|
|
445
|
+
const minutes = Math.floor(seconds / 60);
|
|
446
|
+
const remainder = String(seconds % 60).padStart(2, "0");
|
|
447
|
+
return minutes >= 60 ? `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, "0")}:${remainder}` : `${minutes}:${remainder}`;
|
|
448
|
+
}
|
|
449
|
+
|
|
404
450
|
function pushProcess(turn: MinimalTurn | undefined, kind: string, value: unknown): void {
|
|
405
451
|
if (!turn) return;
|
|
406
452
|
const text = processText(value);
|
|
@@ -415,6 +461,15 @@ function skillNames(text: string): string[] {
|
|
|
415
461
|
return [...names];
|
|
416
462
|
}
|
|
417
463
|
|
|
464
|
+
/** pi-loop injects its wakeup as a user message; keep its boilerplate out of the compact card. */
|
|
465
|
+
function piLoopSummary(question: string): string | undefined {
|
|
466
|
+
if (!question.startsWith("[pi-loop]")) return;
|
|
467
|
+
const lines = question.split(/\r?\n/).map(line => line.trim()).filter(Boolean);
|
|
468
|
+
const title = lines[0] ?? "[pi-loop]";
|
|
469
|
+
const prompt = lines.find(line => line !== title && !line.startsWith("[Self-paced loop:"));
|
|
470
|
+
return prompt ? `${title} · ${prompt}` : title;
|
|
471
|
+
}
|
|
472
|
+
|
|
418
473
|
/** Rebuild turns on the selected session branch. */
|
|
419
474
|
export function minimalTurnsFromBranch(branch: readonly unknown[]): MinimalTurn[] {
|
|
420
475
|
const turns: MinimalTurn[] = [];
|
|
@@ -425,7 +480,7 @@ export function minimalTurnsFromBranch(branch: readonly unknown[]): MinimalTurn[
|
|
|
425
480
|
const { role, content } = entry.message;
|
|
426
481
|
if (role === "user") {
|
|
427
482
|
const question = contentText(content);
|
|
428
|
-
turn = { question: question || "[
|
|
483
|
+
turn = { question: question || "[Attachment]", process: [], running: false };
|
|
429
484
|
for (const name of skillNames(question)) pushProcess(turn, "skill", name);
|
|
430
485
|
turns.push(turn);
|
|
431
486
|
continue;
|
|
@@ -437,13 +492,15 @@ export function minimalTurnsFromBranch(branch: readonly unknown[]): MinimalTurn[
|
|
|
437
492
|
const call = turn.agentCalls?.find(call => call.id === result.toolCallId);
|
|
438
493
|
if (call) {
|
|
439
494
|
call.state = result.isError ? "error" : "done";
|
|
440
|
-
call.output = contentText(content) || "
|
|
495
|
+
call.output = contentText(content) || "Call returned (no text output)";
|
|
441
496
|
continue;
|
|
442
497
|
}
|
|
443
498
|
pushProcess(turn, "output", content);
|
|
444
499
|
continue;
|
|
445
500
|
}
|
|
446
501
|
if (role !== "assistant" || !Array.isArray(content)) continue;
|
|
502
|
+
if (turn.final) (turn.replies ??= []).push(turn.final);
|
|
503
|
+
turn.final = undefined;
|
|
447
504
|
for (const item of content as Array<Record<string, unknown>>) {
|
|
448
505
|
if (!item || typeof item !== "object") continue;
|
|
449
506
|
if (item.type === "thinking") pushProcess(turn, "thinking", item.thinking ?? item.text);
|
|
@@ -467,29 +524,40 @@ export function minimalTurnsFromBranch(branch: readonly unknown[]): MinimalTurn[
|
|
|
467
524
|
turn.final = undefined;
|
|
468
525
|
} else turn.final = text || undefined;
|
|
469
526
|
if (entry.message.stopReason === "error" || entry.message.stopReason === "aborted") {
|
|
470
|
-
turn.final = [entry.message.stopReason === "aborted" ? "
|
|
527
|
+
turn.final = [entry.message.stopReason === "aborted" ? "Execution aborted" : "Execution failed", entry.message.errorMessage, turn.final].filter(Boolean).join("\n");
|
|
471
528
|
}
|
|
472
529
|
}
|
|
473
530
|
return turns;
|
|
474
531
|
}
|
|
475
532
|
|
|
476
533
|
function visibleMinimalTurns(settings: MiniLensSettings, turns: MinimalTurn[]): MinimalTurn[] {
|
|
477
|
-
return turns.map((turn) =>
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
process
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
534
|
+
return turns.map((turn) => {
|
|
535
|
+
let thinking: number | undefined;
|
|
536
|
+
let visibleCount = 0;
|
|
537
|
+
const process = turn.process.filter((line, index) => {
|
|
538
|
+
const visible = line.startsWith("thinking ") ? settings["mini-lens-minimal-thinking-show"]
|
|
539
|
+
: /^(tool|call) /.test(line) ? settings["mini-lens-minimal-tools-show"]
|
|
540
|
+
: line.startsWith("output ") ? settings["mini-lens-minimal-output-show"]
|
|
541
|
+
: line.startsWith("skill ") ? settings["mini-lens-minimal-skills-show"] : true;
|
|
542
|
+
if (visible) {
|
|
543
|
+
if (index === turn.thinking) thinking = visibleCount;
|
|
544
|
+
visibleCount++;
|
|
545
|
+
}
|
|
546
|
+
return visible;
|
|
547
|
+
});
|
|
548
|
+
return {
|
|
549
|
+
...turn,
|
|
550
|
+
thinking,
|
|
551
|
+
awaitingResponse: turn.awaitingResponse && settings["mini-lens-minimal-thinking-show"],
|
|
552
|
+
agentCalls: settings["mini-lens-minimal-tools-show"] ? turn.agentCalls : [],
|
|
553
|
+
process,
|
|
554
|
+
};
|
|
555
|
+
});
|
|
488
556
|
}
|
|
489
557
|
|
|
490
|
-
export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], getTurns: () => MinimalTurn[], isExpanded: () => boolean = () => false, showShortcut: (turn: MinimalTurn) => boolean = () => true, showUsage: () => boolean = () => true) {
|
|
491
|
-
const markdown = (text: string, width: number) => new Markdown(text, 0, 0, getMarkdownTheme(),
|
|
492
|
-
{ color: (value) => theme.fg("text", value) }, { transform: (source, available) => diagramMarkdown(source, available) }).render(width);
|
|
558
|
+
export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], getTurns: () => MinimalTurn[], isExpanded: () => boolean = () => false, showShortcut: (turn: MinimalTurn) => boolean = () => true, showUsage: () => boolean = () => true, subAgentsExpanded: () => boolean = () => false, agentDeadlines = new Map<string, number>()) {
|
|
559
|
+
const markdown = (text: string, width: number, process = false) => new Markdown(text, 0, 0, minimalMarkdownTheme(getMarkdownTheme()),
|
|
560
|
+
{ color: (value) => theme.fg(process ? "muted" : "text", value) }, { transform: (source, available) => diagramMarkdown(source, available) }).render(width);
|
|
493
561
|
const surface = (rows: string[], width: number, user: boolean) => {
|
|
494
562
|
const padding = Math.min(2, Math.floor((width - 1) / 2));
|
|
495
563
|
return ["", ...rows, ""].map((row) => {
|
|
@@ -497,79 +565,286 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
|
|
|
497
565
|
return minimalSurface(theme, line + " ".repeat(Math.max(0, width - visibleWidth(line))), user);
|
|
498
566
|
});
|
|
499
567
|
};
|
|
568
|
+
let agentExpiry = Infinity;
|
|
569
|
+
const expandedPrompts = new Map<number, string>();
|
|
570
|
+
const expandedSubagents = new Set<string>();
|
|
571
|
+
const expandedTools = new Set<string>();
|
|
572
|
+
const expandedThinking = new Set<string>();
|
|
573
|
+
let pinnedToolId: string | undefined;
|
|
574
|
+
let pinnedTool: { id: string; y: number; line: string } | undefined;
|
|
575
|
+
let pinnedSubagentId: string | undefined;
|
|
576
|
+
let pinnedSubagent: { id: string; y: number; line: string; autoScroll?: boolean } | undefined;
|
|
577
|
+
let toolControls: Array<{ id: string; y: number; width: number; title: string }> = [];
|
|
578
|
+
let hoveredTool: typeof toolControls[number] | undefined;
|
|
579
|
+
const clearHover = () => { const changed = !!hoveredTool; hoveredTool = undefined; return changed; };
|
|
580
|
+
const toggleTool = (id: string) => {
|
|
581
|
+
if (id.startsWith("thinking:")) {
|
|
582
|
+
const present = getTurns().some((turn, turnIndex) => turn.process.some((entry, processIndex) =>
|
|
583
|
+
entry.startsWith("thinking") && `thinking:${turnIndex}:${processIndex}` === id));
|
|
584
|
+
if (!present) return;
|
|
585
|
+
if (expandedThinking.has(id)) expandedThinking.delete(id);
|
|
586
|
+
else expandedThinking.add(id);
|
|
587
|
+
clearHover();
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
if (!getTurns().some(turn => turn.agentCalls?.some(call => call.id === id && !isAgentTool(call.tool ?? call.name)))) return;
|
|
591
|
+
if (expandedTools.has(id)) {
|
|
592
|
+
expandedTools.delete(id);
|
|
593
|
+
if (pinnedToolId === id) pinnedToolId = undefined;
|
|
594
|
+
} else {
|
|
595
|
+
expandedTools.add(id);
|
|
596
|
+
// Only the latest opened tool owns the sticky heading; others stay open.
|
|
597
|
+
pinnedToolId = id;
|
|
598
|
+
}
|
|
599
|
+
clearHover();
|
|
600
|
+
};
|
|
601
|
+
const toggleSubagent = (runId: string) => {
|
|
602
|
+
if (!subagentControls.some(control => control.runId === runId)) return;
|
|
603
|
+
if (expandedSubagents.has(runId)) {
|
|
604
|
+
expandedSubagents.delete(runId);
|
|
605
|
+
if (pinnedSubagentId === runId) pinnedSubagentId = undefined;
|
|
606
|
+
} else {
|
|
607
|
+
expandedSubagents.add(runId);
|
|
608
|
+
// SubAgent details open in place; sticky heading engages only after scrolling.
|
|
609
|
+
pinnedSubagentId = runId;
|
|
610
|
+
}
|
|
611
|
+
};
|
|
612
|
+
let promptControls: Array<{ index: number; question: string; y: number; x: number; width: number; label: string }> = [];
|
|
613
|
+
let subagentControls: Array<{ runId: string; y: number; width: number; line: string }> = [];
|
|
614
|
+
let noticeRegions: Array<{ y: number; rows: NoticeRows }> = [];
|
|
615
|
+
const togglePrompt = (index: number, question: string) => {
|
|
616
|
+
if (getTurns()[index]?.question !== question) return;
|
|
617
|
+
if (expandedPrompts.get(index) === question) expandedPrompts.delete(index);
|
|
618
|
+
else expandedPrompts.set(index, question);
|
|
619
|
+
};
|
|
500
620
|
return {
|
|
501
|
-
invalidate() {},
|
|
621
|
+
invalidate() { clearHover(); },
|
|
622
|
+
clearHover,
|
|
623
|
+
pinnedTool: () => pinnedTool,
|
|
624
|
+
unpinTool: () => { pinnedToolId = undefined; pinnedTool = undefined; },
|
|
625
|
+
pinnedSubagent: () => pinnedSubagent,
|
|
626
|
+
unpinSubagent: () => { pinnedSubagentId = undefined; pinnedSubagent = undefined; },
|
|
627
|
+
toolChoices: () => toolControls.map(control => ({ ...control, expanded: expandedTools.has(control.id) || expandedThinking.has(control.id) })),
|
|
628
|
+
toggleTool,
|
|
629
|
+
toggleSubagent,
|
|
630
|
+
agentExpiry: () => agentExpiry,
|
|
631
|
+
promptChoices: () => promptControls.map(control => ({ ...control })),
|
|
632
|
+
togglePrompt,
|
|
633
|
+
handleMouse(event: TuiMouseEvent) {
|
|
634
|
+
const tool = toolControls.find(control => event.y === control.y && event.x >= 2 && event.x < Math.min(5, control.width));
|
|
635
|
+
if (event.type === "move") {
|
|
636
|
+
const next = !event.shift && !event.ctrl && !event.alt ? tool : undefined;
|
|
637
|
+
if (hoveredTool?.id !== next?.id) {
|
|
638
|
+
hoveredTool = next;
|
|
639
|
+
return { handled: true, render: true };
|
|
640
|
+
}
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
if (event.type === "wheel" || event.type === "drag") { clearHover(); return; }
|
|
644
|
+
if (tool && event.button === "left" && !event.shift && !event.ctrl && !event.alt) {
|
|
645
|
+
if (event.type === "press") return { handled: true };
|
|
646
|
+
if (event.type === "click") {
|
|
647
|
+
toggleTool(tool.id);
|
|
648
|
+
return { handled: true, render: true };
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
if (event.button !== "left" || event.shift || event.ctrl || event.alt || (event.clickCount ?? 1) !== 1) return;
|
|
652
|
+
const control = promptControls.find(control => event.y === control.y && event.x >= control.x && event.x < control.x + control.width);
|
|
653
|
+
if (control) {
|
|
654
|
+
if (event.type === "press") return { handled: true };
|
|
655
|
+
if (event.type === "click") {
|
|
656
|
+
togglePrompt(control.index, control.question);
|
|
657
|
+
return { handled: true, render: true };
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
const sub = subagentControls.find(control => event.y === control.y && event.x >= 0 && event.x < control.width);
|
|
661
|
+
if (sub) {
|
|
662
|
+
if (event.type === "press") return { handled: true };
|
|
663
|
+
if (event.type === "click") {
|
|
664
|
+
toggleSubagent(sub.runId);
|
|
665
|
+
return { handled: true, render: true };
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
const region = noticeRegions.find(region => event.y >= region.y && event.y < region.y + region.rows.length);
|
|
669
|
+
return region?.rows.handleMouse?.({ ...event, y: event.y - region.y });
|
|
670
|
+
},
|
|
502
671
|
render(width: number, notices?: TurnNotices): string[] {
|
|
503
|
-
|
|
672
|
+
promptControls = [];
|
|
673
|
+
toolControls = [];
|
|
674
|
+
pinnedTool = undefined;
|
|
675
|
+
pinnedSubagent = undefined;
|
|
676
|
+
subagentControls = [];
|
|
677
|
+
noticeRegions = [];
|
|
678
|
+
agentExpiry = Infinity;
|
|
679
|
+
if (width <= 0) { clearHover(); return []; }
|
|
680
|
+
const turns = getTurns();
|
|
681
|
+
const toolIds = new Set(turns.flatMap(turn => (turn.agentCalls ?? []).map(call => call.id)));
|
|
682
|
+
for (const id of expandedTools) if (!toolIds.has(id)) expandedTools.delete(id);
|
|
683
|
+
const thinkingIds = new Set(turns.flatMap((turn, turnIndex) => turn.process.flatMap((entry, processIndex) =>
|
|
684
|
+
entry.startsWith("thinking") ? [`thinking:${turnIndex}:${processIndex}`] : [])));
|
|
685
|
+
for (const id of expandedThinking) if (!thinkingIds.has(id)) expandedThinking.delete(id);
|
|
504
686
|
const inner = Math.max(1, width - 2 * Math.min(2, Math.floor((width - 1) / 2)));
|
|
505
687
|
const lines: string[] = [];
|
|
506
|
-
for (const [index, turn] of
|
|
688
|
+
for (const [index, turn] of turns.entries()) {
|
|
507
689
|
if (index > 0) lines.push("");
|
|
508
|
-
|
|
509
|
-
const
|
|
690
|
+
if (expandedPrompts.has(index) && expandedPrompts.get(index) !== turn.question) expandedPrompts.delete(index);
|
|
691
|
+
const questionRows = markdown(turn.question, inner);
|
|
692
|
+
const loopSummary = piLoopSummary(turn.question);
|
|
693
|
+
const expanded = expandedPrompts.get(index) === turn.question;
|
|
694
|
+
// Loop wakeups are system-generated user messages. Collapse them even when
|
|
695
|
+
// their short prompt would otherwise fit the normal four-row allowance.
|
|
696
|
+
const userRows = expanded ? [...questionRows] : loopSummary ? markdown(loopSummary, inner) : questionRows.slice(0, 4);
|
|
697
|
+
if (loopSummary || questionRows.length > 4) {
|
|
698
|
+
const label = expanded ? "▴ 收起" : loopSummary ? "▾ 展开" : `▾ 展开 (${questionRows.length} 行)`;
|
|
699
|
+
const control = truncateToWidth(label, inner, "");
|
|
700
|
+
promptControls.push({ index, question: turn.question, y: lines.length + 1 + userRows.length,
|
|
701
|
+
x: 0, width, label });
|
|
702
|
+
userRows.push(theme.fg("accent", control) + theme.fg("muted", truncateToWidth(" · /mini-lens-prompts", Math.max(0, inner - visibleWidth(control)), "")));
|
|
703
|
+
}
|
|
704
|
+
lines.push(...surface(userRows, width, true));
|
|
705
|
+
const entries = turn.process.flatMap((entry, processIndex) => {
|
|
510
706
|
if (entry.startsWith("call ")) {
|
|
511
707
|
const call = turn.agentCalls?.find(call => call.id === entry.slice(5));
|
|
512
|
-
|
|
708
|
+
if (call && isAgentTool(call.tool ?? call.name) && !isExpanded()) return [];
|
|
709
|
+
const display = call && agentCallDisplay(call);
|
|
710
|
+
return call && display ? [{ title: `${isAgentTool(call.tool ?? call.name) ? "Control" : call.name} ${display.summary}`.trim(), detail: display.detail, state: call.state, id: call.id, thinking: false }] : [];
|
|
513
711
|
}
|
|
514
712
|
const part = entry.match(/^(tool|output|thinking|skill)(?:\s+|$)([\s\S]*)/);
|
|
515
|
-
const
|
|
516
|
-
|
|
713
|
+
const thinking = part?.[1] === "thinking";
|
|
714
|
+
const activeThinking = thinking && turn.running && turn.thinking === processIndex;
|
|
715
|
+
const label = ({ tool: "Tool", output: "Output", thinking: "Thinking", skill: "Skill" } as Record<string, string>)[part?.[1] ?? ""] ?? "Process";
|
|
716
|
+
return [{ title: `${label} ${part?.[2] ?? entry}`, detail: part?.[2] ?? entry, state: activeThinking ? "running" : "done", id: thinking ? `thinking:${index}:${processIndex}` : "", thinking }];
|
|
517
717
|
});
|
|
518
718
|
// Older in-memory turns may predate call markers.
|
|
519
719
|
for (const call of turn.agentCalls ?? []) {
|
|
520
|
-
if (
|
|
720
|
+
if (isAgentTool(call.tool ?? call.name) && !isExpanded()) continue;
|
|
721
|
+
const display = agentCallDisplay(call);
|
|
722
|
+
if (!entries.some(entry => entry.id === call.id)) entries.push({ title: `${isAgentTool(call.tool ?? call.name) ? "Control" : call.name} ${display.summary}`, detail: display.detail, state: call.state, id: call.id, thinking: false });
|
|
521
723
|
}
|
|
522
|
-
|
|
724
|
+
const agentTurnControls: Array<{ runId: string; y: number; width: number; line: string }> = [];
|
|
725
|
+
const agents = liveAgentView(turn.subAgents ?? [], theme, width, subAgentsExpanded(), true, agentDeadlines, Date.now(), expandedSubagents, agentTurnControls);
|
|
726
|
+
if (entries.length || turn.running || turn.usage || agents.total) {
|
|
523
727
|
const expanded = isExpanded();
|
|
524
|
-
const shown = expanded ? entries : entries.slice(-
|
|
728
|
+
const shown = expanded ? entries : entries.filter(entry => !entry.thinking || entry.state === "running" || expandedThinking.has(entry.id)).slice(-10);
|
|
525
729
|
const done = entries.filter(entry => entry.state === "done").length;
|
|
526
|
-
const
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
730
|
+
const progressHeader = theme.bold(theme.fg("text", "Agent")) + (entries.length ? theme.fg("muted", ` · ${done}/${entries.length}`) : "")
|
|
731
|
+
+ (agents.total ? theme.bold(theme.fg("text", " Subagent")) + theme.fg("muted", ` ${agents.done + agents.errors}/${agents.total}`)
|
|
732
|
+
+ (agents.errors ? theme.fg("error", ` · ${agents.errors} failed`) : "") : "");
|
|
733
|
+
const header = progressHeader + theme.fg("muted", showShortcut(turn) ? " · Ctrl+O" : "");
|
|
734
|
+
const usage = addUsage({ ...EMPTY_USAGE, ...turn.usage, cost: turn.usage?.cost ?? 0 }, turn.pendingUsage);
|
|
735
|
+
const hasUsage = usage.totalTokens > 0 || usage.cacheRead > 0;
|
|
736
|
+
const totals = hasUsage
|
|
737
|
+
? theme.fg("text", "S") + theme.fg("muted", ` ${formatTokens(usage.totalTokens)} / `)
|
|
738
|
+
+ theme.fg("text", "C") + theme.fg("muted", ` ${formatTokens(usage.cacheRead)}`)
|
|
739
|
+
: "";
|
|
530
740
|
const totalsWidth = visibleWidth(totals);
|
|
531
|
-
if (showUsage() && width >= totalsWidth + visibleWidth("Agent") + 1) {
|
|
741
|
+
if (hasUsage && showUsage() && width >= totalsWidth + visibleWidth(agents.total ? progressHeader : "Agent") + 1) {
|
|
532
742
|
const left = truncateToWidth(header, width - totalsWidth - 1, "");
|
|
533
743
|
lines.push("", left + " ".repeat(width - visibleWidth(left) - totalsWidth) + totals);
|
|
534
744
|
} else {
|
|
535
745
|
lines.push("", truncateToWidth(header, width));
|
|
536
746
|
}
|
|
537
|
-
if (!shown.length
|
|
747
|
+
if (!shown.length && turn.running && turn.awaitingResponse && !turn.final) {
|
|
748
|
+
const prefix = theme.fg("dim", `${agents.rows.length ? "├─" : "└─"} `) + theme.fg("accent", `${runningGlyph()} `) + theme.fg("text", theme.bold("Thinking")) + theme.fg("success", ` ${formatElapsed(turn.startedAt)}`) + " ";
|
|
749
|
+
lines.push(truncateToWidth(prefix + theme.fg("text", "…"), width, ""));
|
|
750
|
+
}
|
|
538
751
|
shown.forEach((entry, row) => {
|
|
539
752
|
const waiting = turn.waitingTools?.find(tool => tool.id === entry.id);
|
|
540
|
-
const title = waiting ?
|
|
541
|
-
const text = title.replace(/\s+/g, " ").trim();
|
|
542
|
-
const
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
const
|
|
547
|
-
const
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
753
|
+
const title = waiting && !entry.title.startsWith("Control ") ? `${waiting.name} running · waiting ${Math.max(0, Math.floor((Date.now() - waiting.startedAt) / 1000))}s` : entry.title;
|
|
754
|
+
const text = title.split(/\r?\n/).find(line => line.trim())?.replace(/\s+/g, " ").trim() ?? "";
|
|
755
|
+
const split = text.indexOf(" ");
|
|
756
|
+
const label = split < 0 ? text : text.slice(0, split);
|
|
757
|
+
const body = split < 0 ? "" : text.slice(split + 1);
|
|
758
|
+
const activeThinking = entry.thinking && entry.state === "running";
|
|
759
|
+
const thinkingElapsed = entry.thinking ? theme.fg(activeThinking ? "success" : "muted", ` ${formatElapsed(turn.startedAt)}`) : "";
|
|
760
|
+
const summary = theme.fg("text", theme.bold(label)) + thinkingElapsed + " ";
|
|
761
|
+
const call = turn.agentCalls?.find(call => call.id === entry.id && !isAgentTool(call.tool ?? call.name));
|
|
762
|
+
const controlId = call?.id ?? (entry.thinking ? entry.id : "");
|
|
763
|
+
const open = call ? expandedTools.has(call.id) : !!(entry.thinking && expandedThinking.has(entry.id));
|
|
764
|
+
if (controlId && width >= 4) toolControls.push({ id: controlId, y: lines.length, width, title: text });
|
|
765
|
+
if (hoveredTool?.id === controlId && (hoveredTool.y !== lines.length || hoveredTool.width !== width)) clearHover();
|
|
766
|
+
const status = entry.state === "error" ? "×" : entry.state === "running" ? runningGlyph() : "●";
|
|
767
|
+
const arrow = !!controlId && (open || hoveredTool?.id === controlId);
|
|
768
|
+
const keepStatus = entry.state === "running" || (open && entry.state === "error");
|
|
769
|
+
const glyph = arrow ? (open ? "▾" : "▸") + (keepStatus ? ` ${status}` : "") : status;
|
|
770
|
+
const glyphColor = entry.state === "error" ? "error" : entry.state === "running" || arrow ? "accent" : "muted";
|
|
771
|
+
const last = row === shown.length - 1 && !agents.rows.length;
|
|
772
|
+
const prefix = theme.fg("dim", last ? "└─ " : "├─ ") + theme.fg(glyphColor, glyph) + " " + summary;
|
|
773
|
+
if (activeThinking) {
|
|
774
|
+
const renderedBody = markdown(body, Math.max(1, visibleWidth(body) + 1), true).join(" ").replace(/\s+/g, " ").trim();
|
|
775
|
+
const bodyWidth = Math.max(0, width - visibleWidth(prefix));
|
|
776
|
+
const overflow = Math.max(0, visibleWidth(renderedBody) - bodyWidth);
|
|
777
|
+
const offset = overflow ? Math.max(0, Math.floor((Date.now() - (turn.startedAt ?? Date.now())) / THINKING_SCROLL_INTERVAL_MS) % (overflow + 9) - 4) : 0;
|
|
778
|
+
lines.push(truncateToWidth(prefix + (bodyWidth ? sliceByColumn(renderedBody, Math.min(overflow, offset), bodyWidth, true) : ""), width, ""));
|
|
779
|
+
} else if (label === "Output") {
|
|
780
|
+
// Wrapped output hangs under the body column and keeps the tree rail to the next sibling.
|
|
781
|
+
const indent = visibleWidth(prefix);
|
|
782
|
+
const wrapped = markdown(body, Math.max(1, width - indent), true);
|
|
783
|
+
const rail = !last && indent > 0 ? theme.fg("dim", "│") + " ".repeat(indent - 1) : " ".repeat(indent);
|
|
784
|
+
lines.push(truncateToWidth(prefix + (wrapped[0] ?? ""), width, ""));
|
|
785
|
+
for (const extra of wrapped.slice(1)) lines.push(truncateToWidth(rail + extra, width, ""));
|
|
786
|
+
} else {
|
|
787
|
+
lines.push(truncateToWidth(prefix + (entry.thinking ? markdown(body, Math.max(1, visibleWidth(body) + 1), true).join(" ").replace(/\s+/g, " ").trim() : theme.fg("muted", body)), width, controlId ? "" : "…"));
|
|
788
|
+
}
|
|
789
|
+
if (open && call && call.id === pinnedToolId) pinnedTool = { id: call.id, y: lines.length - 1, line: lines.at(-1)! };
|
|
790
|
+
if (open && call) {
|
|
791
|
+
// ponytail: saved text only; native view retains images, args and custom renderers.
|
|
792
|
+
const output = stripVTControlCharacters(call.output ?? "").replace(/\r\n?/g, "\n").replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "");
|
|
793
|
+
const rail = width > 5 ? (last ? " " : theme.fg("dim", "│ ")) : "";
|
|
794
|
+
const detailWidth = Math.max(1, width - visibleWidth(rail));
|
|
795
|
+
const details = new Text(output || (entry.state === "running" ? "等待工具文本结果…" : "无文本结果"), 0, 0).render(detailWidth);
|
|
796
|
+
lines.push(...details.map(line => truncateToWidth(rail + theme.fg("muted", line), width, "")));
|
|
797
|
+
} else if (open && entry.thinking) {
|
|
798
|
+
const rail = width > 5 ? (last ? " " : theme.fg("dim", "│ ")) : "";
|
|
799
|
+
const detailWidth = Math.max(1, width - visibleWidth(rail));
|
|
800
|
+
lines.push(...markdown(entry.detail, detailWidth, true).map(line => truncateToWidth(rail + line, width, "")));
|
|
801
|
+
} else if (expanded && entry.state === "error" && entry.detail) {
|
|
802
|
+
const rail = last ? " " : theme.fg("dim", "│ ");
|
|
803
|
+
const details = entry.detail.split(/\r?\n/).filter(line => line.trim());
|
|
804
|
+
// ponytail: four diagnostic lines; full output remains in the native transcript.
|
|
805
|
+
lines.push(...details.slice(1, 5).map(line => truncateToWidth(rail + theme.fg("muted", line), width)));
|
|
806
|
+
if (details.length > 5) lines.push(truncateToWidth(rail + theme.fg("muted", `… +${details.length - 5} lines · /mini-lens-minimal off`), width));
|
|
552
807
|
}
|
|
553
808
|
});
|
|
809
|
+
const agentStartY = lines.length;
|
|
810
|
+
for (const c of agentTurnControls) {
|
|
811
|
+
const control = { ...c, y: agentStartY + c.y };
|
|
812
|
+
subagentControls.push(control);
|
|
813
|
+
if (c.runId === pinnedSubagentId) pinnedSubagent = { id: c.runId, y: control.y, line: c.line, autoScroll: false };
|
|
814
|
+
}
|
|
815
|
+
lines.push(...agents.rows);
|
|
554
816
|
}
|
|
817
|
+
for (const reply of turn.replies ?? []) lines.push("", ...markdown(reply, width));
|
|
555
818
|
if (turn.final) lines.push("", ...markdown(turn.final, width));
|
|
556
|
-
|
|
819
|
+
const noticeRows = notices?.get(index) ?? [];
|
|
820
|
+
noticeRegions.push({ y: lines.length, rows: noticeRows });
|
|
821
|
+
lines.push(...noticeRows);
|
|
557
822
|
}
|
|
823
|
+
if (hoveredTool && !toolControls.some(control => control.id === hoveredTool!.id)) clearHover();
|
|
824
|
+
for (const deadline of agentDeadlines.values()) if (deadline > Date.now()) agentExpiry = Math.min(agentExpiry, deadline);
|
|
558
825
|
return lines;
|
|
559
826
|
},
|
|
560
827
|
};
|
|
561
828
|
}
|
|
562
829
|
|
|
563
830
|
export default function (pi: ExtensionAPI) {
|
|
831
|
+
attachFooterTidy(pi);
|
|
832
|
+
attachTitlePlain(pi);
|
|
564
833
|
let refreshFooter: (() => void) | undefined;
|
|
565
834
|
let refreshMinimal: (() => void) | undefined;
|
|
566
835
|
let processExpanded = false;
|
|
836
|
+
let nativeOutput = false;
|
|
567
837
|
let subAgentsExpanded = false;
|
|
568
838
|
let shortcutTimer: ReturnType<typeof setTimeout> | undefined;
|
|
569
839
|
let waitingTimer: ReturnType<typeof setInterval> | undefined;
|
|
570
840
|
let unsubscribeMinimalInput: (() => void) | undefined;
|
|
571
841
|
let restoreAgentWidgets: (() => void) | undefined;
|
|
572
842
|
let restoreTranscript: (() => void) | undefined;
|
|
843
|
+
let persistAgentStatuses: (() => void) | undefined;
|
|
844
|
+
let promptView: ReturnType<typeof minimalOutputComponent> | undefined;
|
|
845
|
+
let lastAttachMode: string | undefined;
|
|
846
|
+
let remountQueued = false;
|
|
847
|
+
const agentDeadlines = new Map<string, number>();
|
|
573
848
|
let minimalTurns: MinimalTurn[] = [];
|
|
574
849
|
let activeMinimalTurn: MinimalTurn | undefined;
|
|
575
850
|
let pendingMinimalFinal = "";
|
|
@@ -577,6 +852,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
577
852
|
let speed: number | undefined;
|
|
578
853
|
let mcpCount: number | undefined;
|
|
579
854
|
let activeGeneration: ActiveGeneration | undefined;
|
|
855
|
+
let activeUIPrompt: { kind: string; title?: string } | undefined;
|
|
580
856
|
const toolStarts = new Map<string, number>();
|
|
581
857
|
const minimalToolOutputIndices = new Map<string, number>();
|
|
582
858
|
let speedTimer: ReturnType<typeof setInterval> | undefined;
|
|
@@ -587,24 +863,77 @@ export default function (pi: ExtensionAPI) {
|
|
|
587
863
|
const refresh = () => refreshFooter?.();
|
|
588
864
|
const refreshMinimalOutput = () => refreshMinimal?.();
|
|
589
865
|
const mountMinimalOutput = (ctx: ExtensionContext) => {
|
|
866
|
+
persistAgentStatuses = undefined;
|
|
590
867
|
if (shortcutTimer) clearTimeout(shortcutTimer);
|
|
591
868
|
shortcutTimer = undefined;
|
|
592
869
|
if (waitingTimer) clearInterval(waitingTimer);
|
|
593
870
|
waitingTimer = undefined;
|
|
594
871
|
unsubscribeMinimalInput?.();
|
|
595
872
|
unsubscribeMinimalInput = undefined;
|
|
596
|
-
restoreAgentWidgets?.();
|
|
597
|
-
restoreAgentWidgets = undefined;
|
|
598
873
|
restoreTranscript?.();
|
|
599
874
|
restoreTranscript = undefined;
|
|
600
|
-
|
|
875
|
+
restoreAgentWidgets?.();
|
|
876
|
+
restoreAgentWidgets = undefined;
|
|
877
|
+
promptView = undefined;
|
|
878
|
+
if (settings["mini-lens-minimal-show"] && ctx.mode === "tui") unsubscribeMinimalInput = ctx.ui.onTerminalInput?.((data) => {
|
|
879
|
+
const nativeKey = matchesKey(data, "ctrl+alt+o");
|
|
880
|
+
const subAgentKey = matchesKey(data, "ctrl+s");
|
|
881
|
+
if (!nativeKey && (!restoreTranscript || (!subAgentKey && !matchesKey(data, "ctrl+o")))) return;
|
|
882
|
+
// Input listeners run before Pi filters Kitty release/repeat events.
|
|
883
|
+
if (isKeyRelease(data) || isKeyRepeat(data)) return { consume: true };
|
|
884
|
+
if (nativeKey) {
|
|
885
|
+
nativeOutput = !nativeOutput;
|
|
886
|
+
mountMinimalOutput(ctx);
|
|
887
|
+
} else if (subAgentKey) subAgentsExpanded = !subAgentsExpanded;
|
|
888
|
+
else processExpanded = !processExpanded;
|
|
889
|
+
refreshMinimalOutput();
|
|
890
|
+
return { consume: true };
|
|
891
|
+
});
|
|
892
|
+
if (nativeOutput || !settings["mini-lens-minimal-show"] || ctx.mode !== "tui") {
|
|
893
|
+
lastAttachMode = undefined;
|
|
601
894
|
ctx.ui.setWidget?.("mini-lens-minimal-output", undefined);
|
|
895
|
+
refreshMinimalOutput();
|
|
602
896
|
refreshMinimal = undefined;
|
|
603
897
|
return;
|
|
604
898
|
}
|
|
605
899
|
ctx.ui.setWidget("mini-lens-minimal-output", (tui, theme) => {
|
|
606
900
|
refreshMinimal = () => tui.requestRender();
|
|
607
|
-
|
|
901
|
+
// Retain children under their originating user turn, including while idle,
|
|
902
|
+
// after a follow-up user message, and when rebuilding a saved session.
|
|
903
|
+
const sessionKey = ctx.sessionManager.getSessionFile?.() ?? ctx.sessionManager.getSessionId?.() ?? "";
|
|
904
|
+
let statuses = savedAgentStatuses(ctx.sessionManager.getBranch());
|
|
905
|
+
const persisted = new Map(statuses.map(status => [String(status.runId), JSON.stringify(status)]));
|
|
906
|
+
const saveStatuses = () => {
|
|
907
|
+
for (const status of statuses) {
|
|
908
|
+
const value = JSON.stringify(status);
|
|
909
|
+
const key = String(status.runId);
|
|
910
|
+
if (persisted.get(key) === value) continue;
|
|
911
|
+
pi.appendEntry(AGENT_STATUS_ENTRY, status);
|
|
912
|
+
persisted.set(key, value);
|
|
913
|
+
}
|
|
914
|
+
};
|
|
915
|
+
statuses = retainAgentStatuses(statuses, readAgentStatuses(sessionKey));
|
|
916
|
+
persistAgentStatuses = saveStatuses;
|
|
917
|
+
saveStatuses();
|
|
918
|
+
let lastStatusRead = Date.now();
|
|
919
|
+
const supervisorNotices = new Map<string, { notice: any; messages: any[] }>();
|
|
920
|
+
const handledRunIds = new Set<string>();
|
|
921
|
+
const turnsWithAgents = () => {
|
|
922
|
+
// A status directory is session-wide. Never attach an unclaimed snapshot
|
|
923
|
+
// to the newest turn: an older async child may report after a follow-up.
|
|
924
|
+
const assigned = agentStatusesByTurn(statuses, minimalTurns);
|
|
925
|
+
handledRunIds.clear();
|
|
926
|
+
return minimalTurns.map((turn, index) => {
|
|
927
|
+
const turnAgents = assigned.get(index) ?? [];
|
|
928
|
+
const withNotices = agentChildren(turnAgents).map(sub => {
|
|
929
|
+
if (sub.runId) handledRunIds.add(String(sub.runId));
|
|
930
|
+
const n = supervisorNotices.get(String(sub.runId));
|
|
931
|
+
return n ? { ...sub, notice: n.notice, noticeMessages: n.messages } : sub;
|
|
932
|
+
});
|
|
933
|
+
return { ...turn, subAgents: withNotices };
|
|
934
|
+
});
|
|
935
|
+
};
|
|
936
|
+
const view = minimalOutputComponent(theme, () => visibleMinimalTurns(settings, turnsWithAgents()), () => processExpanded, turn => settings["mini-lens-agent-shortcut-show"] && Date.now() < (turn.shortcutHintUntil ?? 0), () => settings["mini-lens-agent-usage-show"], () => subAgentsExpanded, agentDeadlines);
|
|
608
937
|
const hintRemaining = (activeMinimalTurn?.shortcutHintUntil ?? 0) - Date.now();
|
|
609
938
|
if (hintRemaining > 0) {
|
|
610
939
|
shortcutTimer = setTimeout(() => tui.requestRender(), hintRemaining);
|
|
@@ -613,35 +942,109 @@ export default function (pi: ExtensionAPI) {
|
|
|
613
942
|
// Native info notifications use dim; warning/error notifications retain
|
|
614
943
|
// their position in the transcript. No plugin names or message matching.
|
|
615
944
|
const dimPrefix = theme.fg("dim", "\u0000").split("\u0000")[0];
|
|
945
|
+
// Transcript hover wrappers must surround the compact widget handlers;
|
|
946
|
+
// unmount in reverse order so neither adapter resurrects stale handlers.
|
|
947
|
+
restoreAgentWidgets = attachAgentWidgets(tui, theme, () => subAgentsExpanded, undefined, true);
|
|
616
948
|
restoreTranscript = attachTranscript(tui, view, {
|
|
949
|
+
turnCount: () => minimalTurns.length,
|
|
950
|
+
supervisor: {
|
|
951
|
+
theme,
|
|
952
|
+
expanded: () => processExpanded,
|
|
953
|
+
handledRunIds: () => handledRunIds,
|
|
954
|
+
onNotices: groups => {
|
|
955
|
+
let changed = false;
|
|
956
|
+
for (const group of groups.values()) {
|
|
957
|
+
const runId = String(group.notice.runId ?? "");
|
|
958
|
+
if (runId) {
|
|
959
|
+
const prev = supervisorNotices.get(runId);
|
|
960
|
+
if (!prev || JSON.stringify(prev) !== JSON.stringify({ notice: group.notice, messages: group.messages })) {
|
|
961
|
+
supervisorNotices.set(runId, { notice: group.notice, messages: group.messages });
|
|
962
|
+
changed = true;
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
if (changed) {
|
|
967
|
+
// Preserve notices inside their owning snapshot as well as Pi's original message.
|
|
968
|
+
statuses = statuses.map(status => {
|
|
969
|
+
const children = agentChildren([status]).map(child => {
|
|
970
|
+
const notice = supervisorNotices.get(String(child.runId));
|
|
971
|
+
return notice ? { ...child, notice: notice.notice, noticeMessages: notice.messages } : child;
|
|
972
|
+
});
|
|
973
|
+
return children.length ? { ...status, steps: children, workflowChildren: undefined, children: undefined } : status;
|
|
974
|
+
});
|
|
975
|
+
tui.requestRender();
|
|
976
|
+
}
|
|
977
|
+
},
|
|
978
|
+
},
|
|
979
|
+
isPrompt: text => !!activeUIPrompt && (!activeUIPrompt.title || text.includes(activeUIPrompt.title)),
|
|
617
980
|
isTransient: text => !!dimPrefix && text.startsWith(dimPrefix),
|
|
618
981
|
});
|
|
982
|
+
lastAttachMode = typeof tui.mode === "string" ? tui.mode : undefined;
|
|
619
983
|
if (!restoreTranscript) {
|
|
620
|
-
|
|
984
|
+
restoreAgentWidgets?.();
|
|
985
|
+
restoreAgentWidgets = undefined;
|
|
986
|
+
ctx.ui.notify(tui.mode === "regular"
|
|
987
|
+
? "Minimal output needs the fullscreen renderer. Quit and restart Pi — /reload does not switch TUI mode. Or set TUI mode to fullscreen in /settings."
|
|
988
|
+
: "Pi transcript layout not recognized; minimal mode disabled, native output preserved.", "warning");
|
|
621
989
|
}
|
|
622
990
|
if (restoreTranscript) {
|
|
623
|
-
|
|
991
|
+
promptView = view;
|
|
624
992
|
waitingTimer = setInterval(() => {
|
|
625
|
-
|
|
626
|
-
|
|
993
|
+
let changed = false;
|
|
994
|
+
if (Date.now() - lastStatusRead >= 1000) {
|
|
995
|
+
const next = retainAgentStatuses(statuses, readAgentStatuses(sessionKey, undefined, statuses));
|
|
996
|
+
changed = JSON.stringify(next) !== JSON.stringify(statuses);
|
|
997
|
+
statuses = next;
|
|
998
|
+
saveStatuses();
|
|
999
|
+
lastStatusRead = Date.now();
|
|
1000
|
+
}
|
|
1001
|
+
if (changed || Date.now() >= view.agentExpiry() || activeMinimalTurn?.running || statuses.some(status => /^(running|active|starting|queued|pending)$/.test(String(status.state)))) tui.requestRender();
|
|
1002
|
+
}, 100);
|
|
627
1003
|
waitingTimer.unref();
|
|
628
|
-
unsubscribeMinimalInput = ctx.ui.onTerminalInput?.((data) => {
|
|
629
|
-
const subAgentKey = matchesKey(data, "ctrl+s");
|
|
630
|
-
if (!subAgentKey && !matchesKey(data, "ctrl+o")) return;
|
|
631
|
-
// Input listeners run before Pi filters Kitty release events.
|
|
632
|
-
// Consume release/repeat without toggling the same key twice.
|
|
633
|
-
if (isKeyRelease(data) || isKeyRepeat(data)) return { consume: true };
|
|
634
|
-
if (subAgentKey) subAgentsExpanded = !subAgentsExpanded;
|
|
635
|
-
else processExpanded = !processExpanded;
|
|
636
|
-
tui.requestRender();
|
|
637
|
-
return { consume: true };
|
|
638
|
-
});
|
|
639
1004
|
}
|
|
640
1005
|
tui.requestRender();
|
|
641
1006
|
// Factory acquires the renderer only; never duplicate content in the dock.
|
|
642
1007
|
return { render: () => [], invalidate() {} };
|
|
643
1008
|
});
|
|
644
1009
|
};
|
|
1010
|
+
pi.registerCommand("mini-lens-prompts", {
|
|
1011
|
+
description: "Expand or collapse a user prompt in fullscreen minimal output",
|
|
1012
|
+
handler: async (_args, ctx) => {
|
|
1013
|
+
if (ctx.mode !== "tui" || !restoreTranscript || !promptView) {
|
|
1014
|
+
if (ctx.hasUI) ctx.ui.notify("Prompt folding requires fullscreen minimal output.", "info");
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
1017
|
+
const view = promptView;
|
|
1018
|
+
const choices = view.promptChoices();
|
|
1019
|
+
if (!choices.length) { ctx.ui.notify("No user prompts exceed four lines at this width.", "info"); return; }
|
|
1020
|
+
const labels = choices.map(choice => `${choice.index + 1}. ${choice.label} · ${preview(choice.question)}`);
|
|
1021
|
+
const selected = await ctx.ui.select("User prompts · Enter to toggle · Esc to cancel", labels);
|
|
1022
|
+
const choice = choices[labels.indexOf(selected ?? "")];
|
|
1023
|
+
if (choice && promptView === view) {
|
|
1024
|
+
view.togglePrompt(choice.index, choice.question);
|
|
1025
|
+
refreshMinimalOutput();
|
|
1026
|
+
}
|
|
1027
|
+
},
|
|
1028
|
+
});
|
|
1029
|
+
pi.registerCommand("mini-lens-tools", {
|
|
1030
|
+
description: "Expand or collapse a tool's saved text or thinking in fullscreen minimal output",
|
|
1031
|
+
handler: async (_args, ctx) => {
|
|
1032
|
+
if (ctx.mode !== "tui" || !restoreTranscript || !promptView) {
|
|
1033
|
+
if (ctx.hasUI) ctx.ui.notify("Tool folding requires fullscreen minimal output.", "info");
|
|
1034
|
+
return;
|
|
1035
|
+
}
|
|
1036
|
+
const view = promptView;
|
|
1037
|
+
const choices = view.toolChoices();
|
|
1038
|
+
if (!choices.length) { ctx.ui.notify("No visible tool calls. Ctrl+O shows older calls.", "info"); return; }
|
|
1039
|
+
const labels = choices.map((choice, index) => `${index + 1}. ${choice.expanded ? "收起" : "展开"} · ${preview(choice.title)}`);
|
|
1040
|
+
const selected = await ctx.ui.select("Tool results · Enter to toggle · Esc to cancel", labels);
|
|
1041
|
+
const choice = choices[labels.indexOf(selected ?? "")];
|
|
1042
|
+
if (choice && promptView === view) {
|
|
1043
|
+
view.toggleTool(choice.id);
|
|
1044
|
+
refreshMinimalOutput();
|
|
1045
|
+
}
|
|
1046
|
+
},
|
|
1047
|
+
});
|
|
645
1048
|
// All factories run before session_start; retain startup broadcasts until the footer mounts.
|
|
646
1049
|
const unsubscribeMcpStatus = pi.events.on("pi-mcp-adapter/status/v1", (value: unknown) => {
|
|
647
1050
|
const count = enabledMcpServerCount(value);
|
|
@@ -668,51 +1071,73 @@ export default function (pi: ExtensionAPI) {
|
|
|
668
1071
|
saveChain = saveChain
|
|
669
1072
|
.catch(() => undefined)
|
|
670
1073
|
.then(() => saveSettings(snapshot, configPath))
|
|
671
|
-
.catch(() => ctx.ui.notify(
|
|
1074
|
+
.catch(() => ctx.ui.notify(COPY.saveFailed, "error"));
|
|
672
1075
|
return saveChain;
|
|
673
1076
|
};
|
|
674
1077
|
const openSettings = async (ctx: ExtensionContext) => {
|
|
675
1078
|
if (ctx.mode !== "tui") {
|
|
676
|
-
ctx.ui.notify(
|
|
1079
|
+
ctx.ui.notify(COPY.tuiRequired, "error");
|
|
677
1080
|
return;
|
|
678
1081
|
}
|
|
679
1082
|
await ctx.ui.custom((tui, theme, _keybindings, done) => {
|
|
680
1083
|
const container = new Container();
|
|
681
1084
|
const preview = new Text(settingsPreviewLine(theme, settings), 1, 1);
|
|
682
|
-
|
|
683
|
-
|
|
1085
|
+
const title = new Text(theme.fg("accent", theme.bold(COPY.title)), 1, 1);
|
|
1086
|
+
const previewLabel = new Text(theme.fg("muted", COPY.preview), 1, 0);
|
|
1087
|
+
container.addChild(title);
|
|
1088
|
+
container.addChild(previewLabel);
|
|
684
1089
|
container.addChild(preview);
|
|
685
|
-
|
|
1090
|
+
let items = settingsItems(settings);
|
|
686
1091
|
let highlighted: keyof MiniLensSettings | undefined;
|
|
687
1092
|
const onChange = (id: string, value: string) => {
|
|
688
1093
|
settings = { ...settings, [id]: value === "on", onboardingCompleted: true };
|
|
1094
|
+
items = settingsItems(settings);
|
|
1095
|
+
applyCollapseState();
|
|
689
1096
|
preview.setText(settingsPreviewLine(theme, settings));
|
|
690
1097
|
mountMinimalOutput(ctx);
|
|
691
1098
|
void persistSettings(ctx);
|
|
692
1099
|
refresh();
|
|
693
1100
|
refreshMinimalOutput();
|
|
694
1101
|
};
|
|
1102
|
+
const baseSettingsTheme = getSettingsListTheme();
|
|
695
1103
|
const settingsTheme = {
|
|
696
|
-
...
|
|
1104
|
+
...baseSettingsTheme,
|
|
697
1105
|
cursor: theme.bg("selectedBg", theme.fg("accent", theme.bold("→ "))),
|
|
698
1106
|
label: (text: string, selected: boolean) => {
|
|
699
|
-
|
|
700
|
-
|
|
1107
|
+
const name = text.trimEnd();
|
|
1108
|
+
if (selected) highlighted = items.find((item) => item.label === name)?.id as keyof MiniLensSettings | undefined;
|
|
1109
|
+
const disabled = name === COPY.minimal && !settings["mini-lens-minimal-show"];
|
|
1110
|
+
if (selected) return theme.bg("selectedBg", theme.fg("accent", theme.bold(text)));
|
|
1111
|
+
return theme.fg(disabled ? "muted" : "text", text);
|
|
701
1112
|
},
|
|
702
|
-
value: (text: string, selected: boolean) =>
|
|
1113
|
+
value: (text: string, selected: boolean) =>
|
|
1114
|
+
selected ? theme.bg("selectedBg", theme.fg("accent", theme.bold(text))) : theme.fg("muted", text),
|
|
1115
|
+
};
|
|
1116
|
+
const lensItems = () => settingsItems(settings).filter((item) => item.id !== "mini-lens-minimal-show" && !isCollapsedReplyChildSetting(item.id));
|
|
1117
|
+
const minimalItems = () => settingsItems(settings).filter((item) => isCollapsedReplyChildSetting(item.id));
|
|
1118
|
+
const collapseItem: SettingItem = {
|
|
1119
|
+
id: "mini-lens-minimal-show", label: COPY.enableMinimal, description: COPY.enableMinimalDescription,
|
|
1120
|
+
currentValue: settings["mini-lens-minimal-show"] ? "on" : "off", values: ["on", "off"],
|
|
703
1121
|
};
|
|
1122
|
+
const minimalGroup: SettingItem = { id: "minimal", label: COPY.minimal, currentValue: "›" };
|
|
1123
|
+
const applyCollapseState = () => {
|
|
1124
|
+
const enabled = settings["mini-lens-minimal-show"];
|
|
1125
|
+
collapseItem.currentValue = enabled ? "on" : "off";
|
|
1126
|
+
minimalGroup.currentValue = enabled ? "›" : "off";
|
|
1127
|
+
minimalGroup.description = enabled ? undefined : COPY.minimalLocked;
|
|
1128
|
+
if (enabled) {
|
|
1129
|
+
minimalGroup.submenu = (_value, back) => new SettingsList(minimalItems(), 8, settingsTheme, onChange, () => back(), { enableSearch: true });
|
|
1130
|
+
} else {
|
|
1131
|
+
delete minimalGroup.submenu;
|
|
1132
|
+
}
|
|
1133
|
+
};
|
|
1134
|
+
applyCollapseState();
|
|
704
1135
|
const groups: SettingItem[] = [
|
|
705
|
-
{ id: "lens", label:
|
|
706
|
-
|
|
1136
|
+
{ id: "lens", label: COPY.lens, currentValue: "›", submenu: (_value, back) => new SettingsList(lensItems(), 12, settingsTheme, onChange, () => back(), { enableSearch: true }) },
|
|
1137
|
+
collapseItem,
|
|
1138
|
+
minimalGroup,
|
|
707
1139
|
];
|
|
708
|
-
const settingsList = new SettingsList(
|
|
709
|
-
groups,
|
|
710
|
-
12,
|
|
711
|
-
settingsTheme,
|
|
712
|
-
onChange,
|
|
713
|
-
() => done(undefined),
|
|
714
|
-
{ enableSearch: true },
|
|
715
|
-
);
|
|
1140
|
+
const settingsList = new SettingsList(groups, 12, settingsTheme, onChange, () => done(undefined), { enableSearch: true });
|
|
716
1141
|
container.addChild(settingsList);
|
|
717
1142
|
return {
|
|
718
1143
|
render: (width: number) => {
|
|
@@ -733,7 +1158,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
733
1158
|
};
|
|
734
1159
|
|
|
735
1160
|
pi.registerCommand("mini-lens-settings", {
|
|
736
|
-
description: "Configure
|
|
1161
|
+
description: "Configure Lens, collapsed replies, and Minimal output",
|
|
737
1162
|
handler: async (_args, ctx) => openSettings(ctx),
|
|
738
1163
|
});
|
|
739
1164
|
pi.registerCommand("mini-lens-history", {
|
|
@@ -741,7 +1166,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
741
1166
|
handler: async (_args, ctx) => {
|
|
742
1167
|
if (ctx.mode !== "tui" || minimalTurns.length === 0) return;
|
|
743
1168
|
const labels = minimalTurns.map((turn, index) => `${index + 1}. ${preview(turn.question)}`);
|
|
744
|
-
const selected = await ctx.ui.select("
|
|
1169
|
+
const selected = await ctx.ui.select("Select process entry (keep collapsed view)", labels);
|
|
745
1170
|
const index = selected === undefined ? -1 : labels.indexOf(selected);
|
|
746
1171
|
if (index < 0) return;
|
|
747
1172
|
const snapshot = [...minimalTurns[index].process];
|
|
@@ -752,8 +1177,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
752
1177
|
render(width: number) {
|
|
753
1178
|
const page = snapshot.slice(offset, offset + 5);
|
|
754
1179
|
return [
|
|
755
|
-
truncateToWidth(theme.fg("accent",
|
|
756
|
-
...page.flatMap((line) => new Markdown(line, 0, 0, getMarkdownTheme(), undefined, { transform: diagramMarkdown }).render(Math.max(1, width))),
|
|
1180
|
+
truncateToWidth(theme.fg("accent", `Process ${offset + 1}–${Math.min(offset + 5, snapshot.length)} / ${snapshot.length} · ↑↓ Browse · Esc Close`), width),
|
|
1181
|
+
...page.flatMap((line) => new Markdown(line, 0, 0, minimalMarkdownTheme(getMarkdownTheme()), undefined, { transform: diagramMarkdown }).render(Math.max(1, width))),
|
|
757
1182
|
];
|
|
758
1183
|
},
|
|
759
1184
|
handleInput(data: string) {
|
|
@@ -767,15 +1192,15 @@ export default function (pi: ExtensionAPI) {
|
|
|
767
1192
|
},
|
|
768
1193
|
});
|
|
769
1194
|
pi.registerCommand("mini-lens-minimal", {
|
|
770
|
-
description: "Toggle
|
|
1195
|
+
description: "Toggle collapsed replies (off keeps Pi's default conversation history)",
|
|
771
1196
|
handler: async (args, ctx) => {
|
|
772
1197
|
const normalized = args.trim().toLowerCase();
|
|
773
1198
|
if (ctx.mode !== "tui") {
|
|
774
|
-
ctx.ui.notify(
|
|
1199
|
+
ctx.ui.notify(COPY.minimalRequired, "error");
|
|
775
1200
|
return;
|
|
776
1201
|
}
|
|
777
1202
|
if (normalized && normalized !== "on" && normalized !== "off") {
|
|
778
|
-
ctx.ui.notify(
|
|
1203
|
+
ctx.ui.notify(COPY.minimalUsage, "warning");
|
|
779
1204
|
return;
|
|
780
1205
|
}
|
|
781
1206
|
settings = {
|
|
@@ -783,9 +1208,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
783
1208
|
"mini-lens-minimal-show": normalized === "on" ? true : normalized === "off" ? false : !settings["mini-lens-minimal-show"],
|
|
784
1209
|
onboardingCompleted: true,
|
|
785
1210
|
};
|
|
1211
|
+
if (settings["mini-lens-minimal-show"]) nativeOutput = false;
|
|
786
1212
|
mountMinimalOutput(ctx);
|
|
787
1213
|
await persistSettings(ctx);
|
|
788
|
-
|
|
1214
|
+
// The mount already explains unsupported layouts; do not contradict it
|
|
1215
|
+
// with a success notification when only the preference was saved.
|
|
1216
|
+
if (settings["mini-lens-minimal-show"] && !restoreTranscript) return;
|
|
1217
|
+
ctx.ui.notify(`${COPY.minimalState}${settings["mini-lens-minimal-show"] ? "on" : "off"}`, "info");
|
|
789
1218
|
},
|
|
790
1219
|
});
|
|
791
1220
|
|
|
@@ -797,28 +1226,37 @@ export default function (pi: ExtensionAPI) {
|
|
|
797
1226
|
pendingMinimalFinal = "";
|
|
798
1227
|
minimalToolOutputIndices.clear();
|
|
799
1228
|
mountMinimalOutput(ctx);
|
|
800
|
-
ctx.ui.setFooter((tui, theme) => {
|
|
1229
|
+
ctx.ui.setFooter((tui, theme, footerData) => {
|
|
801
1230
|
refreshFooter = () => tui.requestRender();
|
|
802
1231
|
return {
|
|
803
1232
|
invalidate() {},
|
|
804
1233
|
render(width: number): string[] {
|
|
805
|
-
|
|
1234
|
+
// switchTuiMode does not re-run setWidget; remount once the live renderer is fullscreen.
|
|
1235
|
+
if (settings["mini-lens-minimal-show"] && !nativeOutput && ctx.mode === "tui" && !restoreTranscript
|
|
1236
|
+
&& tui.mode !== "regular" && lastAttachMode === "regular" && !remountQueued) {
|
|
1237
|
+
remountQueued = true;
|
|
1238
|
+
queueMicrotask(() => {
|
|
1239
|
+
remountQueued = false;
|
|
1240
|
+
mountMinimalOutput(ctx);
|
|
1241
|
+
});
|
|
1242
|
+
}
|
|
1243
|
+
return [statusLine(ctx, theme, width, sessionUsage(ctx), settings, speed, undefined, mcpCount, footerData?.getExtensionStatuses?.())];
|
|
806
1244
|
},
|
|
807
1245
|
};
|
|
808
1246
|
});
|
|
809
1247
|
refresh();
|
|
810
1248
|
if (!loaded.exists && ctx.mode === "tui" && ctx.hasUI) {
|
|
811
1249
|
const choice = await ctx.ui.select(
|
|
812
|
-
|
|
813
|
-
[
|
|
1250
|
+
`Mini Lens ${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}`,
|
|
1251
|
+
[COPY.keepDefaults, COPY.configureNow],
|
|
814
1252
|
);
|
|
815
1253
|
settings = { ...settings, onboardingCompleted: true };
|
|
816
1254
|
try {
|
|
817
1255
|
await persistSettings(ctx);
|
|
818
1256
|
} catch {
|
|
819
|
-
ctx.ui.notify(
|
|
1257
|
+
ctx.ui.notify(`${COPY.saveFailed} (${CONFIG_DIR_NAME})`, "error");
|
|
820
1258
|
}
|
|
821
|
-
if (choice ===
|
|
1259
|
+
if (choice === COPY.configureNow) await openSettings(ctx);
|
|
822
1260
|
}
|
|
823
1261
|
});
|
|
824
1262
|
const syncMinimalBranch = (_event: unknown, ctx: ExtensionContext) => {
|
|
@@ -842,16 +1280,27 @@ export default function (pi: ExtensionAPI) {
|
|
|
842
1280
|
for (const name of skillNames(event.prompt)) pushProcess(activeMinimalTurn, "skill", name);
|
|
843
1281
|
refreshMinimalOutput();
|
|
844
1282
|
});
|
|
1283
|
+
pi.on("ui_prompt_start", (event) => {
|
|
1284
|
+
activeUIPrompt = event;
|
|
1285
|
+
refreshMinimalOutput();
|
|
1286
|
+
});
|
|
1287
|
+
pi.on("ui_prompt_end", () => {
|
|
1288
|
+
activeUIPrompt = undefined;
|
|
1289
|
+
refreshMinimalOutput();
|
|
1290
|
+
});
|
|
845
1291
|
pi.on("model_select", refresh);
|
|
846
1292
|
pi.on("thinking_level_select", refresh);
|
|
847
1293
|
pi.on("message_start", (event) => {
|
|
848
1294
|
if (event.message.role === "user") {
|
|
849
1295
|
if (activeMinimalTurn) {
|
|
850
1296
|
activeMinimalTurn.final = pendingMinimalFinal;
|
|
1297
|
+
activeMinimalTurn.running = false;
|
|
1298
|
+
activeMinimalTurn.thinking = undefined;
|
|
851
1299
|
}
|
|
852
|
-
const question = contentText(event.message.content) || "[
|
|
1300
|
+
const question = contentText(event.message.content) || "[Attachment]";
|
|
853
1301
|
processExpanded = false;
|
|
854
|
-
|
|
1302
|
+
subAgentsExpanded = false;
|
|
1303
|
+
activeMinimalTurn = { question, process: [], running: true, startedAt: Date.now(), awaitingResponse: true, shortcutHintUntil: Date.now() + 6_000 };
|
|
855
1304
|
if (shortcutTimer) clearTimeout(shortcutTimer);
|
|
856
1305
|
shortcutTimer = setTimeout(() => refreshMinimalOutput(), 6_000);
|
|
857
1306
|
shortcutTimer.unref();
|
|
@@ -862,6 +1311,15 @@ export default function (pi: ExtensionAPI) {
|
|
|
862
1311
|
refreshMinimalOutput();
|
|
863
1312
|
}
|
|
864
1313
|
if (event.message.role !== "assistant") return;
|
|
1314
|
+
// Background completions can start a new assistant turn without a user message.
|
|
1315
|
+
activeMinimalTurn ??= minimalTurns.at(-1);
|
|
1316
|
+
if (activeMinimalTurn) {
|
|
1317
|
+
if (activeMinimalTurn.final) (activeMinimalTurn.replies ??= []).push(activeMinimalTurn.final);
|
|
1318
|
+
activeMinimalTurn.final = undefined;
|
|
1319
|
+
activeMinimalTurn.running = true;
|
|
1320
|
+
activeMinimalTurn.awaitingResponse = true;
|
|
1321
|
+
activeMinimalTurn.thinking = undefined;
|
|
1322
|
+
}
|
|
865
1323
|
minimalMessageIndices.clear();
|
|
866
1324
|
pendingMinimalFinal = "";
|
|
867
1325
|
// Keep the last completed speed visible until this response produces tokens.
|
|
@@ -873,6 +1331,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
873
1331
|
pi.on("message_update", (event) => {
|
|
874
1332
|
const partial = (event.assistantMessageEvent as { partial?: { usage?: UsageLike; content?: Array<Record<string, unknown>> } }).partial;
|
|
875
1333
|
if (activeMinimalTurn && partial?.content) {
|
|
1334
|
+
activeMinimalTurn.thinking = undefined;
|
|
1335
|
+
if (partial.content.length) activeMinimalTurn.awaitingResponse = false;
|
|
876
1336
|
for (const [blockIndex, item] of partial.content.entries()) {
|
|
877
1337
|
if (item.type !== "thinking") continue;
|
|
878
1338
|
const line = `${item.type === "thinking" ? "thinking" : "output"} ${processText(item.thinking ?? item.text)}`;
|
|
@@ -881,6 +1341,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
881
1341
|
minimalMessageIndices.set(blockIndex, activeMinimalTurn.process.length);
|
|
882
1342
|
activeMinimalTurn.process.push(line);
|
|
883
1343
|
} else activeMinimalTurn.process[index] = line;
|
|
1344
|
+
if (blockIndex === partial.content.length - 1 && event.assistantMessageEvent.type !== "thinking_end") activeMinimalTurn.thinking = minimalMessageIndices.get(blockIndex);
|
|
884
1345
|
}
|
|
885
1346
|
activeMinimalTurn.final = contentText(partial.content) || undefined;
|
|
886
1347
|
refreshMinimalOutput();
|
|
@@ -901,6 +1362,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
901
1362
|
pi.on("message_end", (event) => {
|
|
902
1363
|
if (event.message.role === "assistant") {
|
|
903
1364
|
if (activeMinimalTurn) {
|
|
1365
|
+
activeMinimalTurn.thinking = undefined;
|
|
1366
|
+
activeMinimalTurn.awaitingResponse = false;
|
|
904
1367
|
activeMinimalTurn.usage = addUsage(activeMinimalTurn.usage ?? EMPTY_USAGE, event.message.usage as UsageLike | undefined);
|
|
905
1368
|
activeMinimalTurn.pendingUsage = undefined;
|
|
906
1369
|
}
|
|
@@ -924,7 +1387,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
924
1387
|
activeMinimalTurn.final = undefined;
|
|
925
1388
|
pendingMinimalFinal = content.some((item) => item?.type === "toolCall") ? "" : text;
|
|
926
1389
|
if (message.stopReason === "error" || message.stopReason === "aborted") {
|
|
927
|
-
pendingMinimalFinal = [message.stopReason === "aborted" ? "
|
|
1390
|
+
pendingMinimalFinal = [message.stopReason === "aborted" ? "Execution aborted" : "Execution failed", message.errorMessage, pendingMinimalFinal].filter(Boolean).join("\n");
|
|
928
1391
|
}
|
|
929
1392
|
activeMinimalTurn.final = pendingMinimalFinal || undefined;
|
|
930
1393
|
}
|
|
@@ -935,6 +1398,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
935
1398
|
pi.on("tool_execution_start", (event) => {
|
|
936
1399
|
toolStarts.set(event.toolCallId, Date.now());
|
|
937
1400
|
if (activeMinimalTurn) {
|
|
1401
|
+
activeMinimalTurn.thinking = undefined;
|
|
1402
|
+
activeMinimalTurn.awaitingResponse = false;
|
|
938
1403
|
(activeMinimalTurn.agentCalls ??= []).push(agentCall(event.toolCallId, event.toolName, event.args));
|
|
939
1404
|
pushProcess(activeMinimalTurn, "call", event.toolCallId);
|
|
940
1405
|
(activeMinimalTurn.waitingTools ??= []).push({ id: event.toolCallId, name: event.toolName, startedAt: Date.now() });
|
|
@@ -977,14 +1442,14 @@ export default function (pi: ExtensionAPI) {
|
|
|
977
1442
|
if (call) {
|
|
978
1443
|
if (activeMinimalTurn) activeMinimalTurn.waitingTools = activeMinimalTurn.waitingTools?.filter(tool => tool.id !== event.toolCallId);
|
|
979
1444
|
call.state = event.isError ? "error" : "done";
|
|
980
|
-
call.output = contentText(event.result) || (event.isError ? "
|
|
1445
|
+
call.output = contentText(event.result) || (event.isError ? "Call failed (no text details)" : "Call returned (background task status below)");
|
|
981
1446
|
refresh();
|
|
982
1447
|
refreshMinimalOutput();
|
|
983
1448
|
return;
|
|
984
1449
|
}
|
|
985
1450
|
if (activeMinimalTurn) {
|
|
986
1451
|
activeMinimalTurn.waitingTools = activeMinimalTurn.waitingTools?.filter((tool) => tool.id !== event.toolCallId);
|
|
987
|
-
const text = contentText(event.result) || (event.isError ? "
|
|
1452
|
+
const text = contentText(event.result) || (event.isError ? "Tool failed (no text details)" : "Tool completed (no text output)");
|
|
988
1453
|
const line = `${event.isError ? "output error" : "output"} ${text}`;
|
|
989
1454
|
const index = minimalToolOutputIndices.get(event.toolCallId);
|
|
990
1455
|
if (index === undefined) activeMinimalTurn.process.push(line);
|
|
@@ -998,7 +1463,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
998
1463
|
pi.on("agent_end", refresh);
|
|
999
1464
|
pi.on("agent_settled", () => {
|
|
1000
1465
|
if (!activeMinimalTurn) return;
|
|
1001
|
-
for (const turn of minimalTurns) turn.running = false;
|
|
1466
|
+
for (const turn of minimalTurns) { turn.running = false; turn.thinking = undefined; }
|
|
1002
1467
|
activeMinimalTurn.final = pendingMinimalFinal;
|
|
1003
1468
|
activeMinimalTurn = undefined;
|
|
1004
1469
|
pendingMinimalFinal = "";
|
|
@@ -1006,11 +1471,16 @@ export default function (pi: ExtensionAPI) {
|
|
|
1006
1471
|
refreshMinimalOutput();
|
|
1007
1472
|
});
|
|
1008
1473
|
pi.on("session_shutdown", () => {
|
|
1474
|
+
persistAgentStatuses?.();
|
|
1475
|
+
persistAgentStatuses = undefined;
|
|
1476
|
+
agentDeadlines.clear();
|
|
1477
|
+
promptView = undefined;
|
|
1009
1478
|
if (shortcutTimer) clearTimeout(shortcutTimer);
|
|
1010
1479
|
shortcutTimer = undefined;
|
|
1011
1480
|
unsubscribeMcpStatus();
|
|
1012
1481
|
refreshFooter = undefined;
|
|
1013
1482
|
activeGeneration = undefined;
|
|
1483
|
+
activeUIPrompt = undefined;
|
|
1014
1484
|
toolStarts.clear();
|
|
1015
1485
|
minimalToolOutputIndices.clear();
|
|
1016
1486
|
refreshMinimal = undefined;
|
|
@@ -1018,10 +1488,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
1018
1488
|
waitingTimer = undefined;
|
|
1019
1489
|
unsubscribeMinimalInput?.();
|
|
1020
1490
|
unsubscribeMinimalInput = undefined;
|
|
1021
|
-
restoreAgentWidgets?.();
|
|
1022
|
-
restoreAgentWidgets = undefined;
|
|
1023
1491
|
restoreTranscript?.();
|
|
1024
1492
|
restoreTranscript = undefined;
|
|
1493
|
+
restoreAgentWidgets?.();
|
|
1494
|
+
restoreAgentWidgets = undefined;
|
|
1025
1495
|
stopSpeedTimer();
|
|
1026
1496
|
});
|
|
1027
1497
|
}
|