@each1024/pi-mini-mode 1.3.6 → 1.3.8

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,10 +1,12 @@
1
1
  import { AGENT_STATUS_ENTRY, savedAgentStatuses, retainAgentStatuses, agentChildren, agentCall, agentCallDisplay, agentStatusesByTurn, attachAgentWidgets, isAgentTool, liveAgentView, readAgentStatuses, runningGlyph, type AgentCall } from "../lib/agent-view.ts";
2
2
  import { CONFIG_DIR_NAME, getSettingsListTheme, getMarkdownTheme, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
3
3
  import { attachTranscript, type NoticeRows, type TurnNotices } from "../lib/transcript-adapter.ts";
4
- import { diagramMarkdown, minimalMarkdownTheme } from "../lib/minimal-markdown.ts";
4
+ import { diagramMarkdown, isFencedMarkdown, minimalMarkdownTheme } from "../lib/minimal-markdown.ts";
5
5
  import { minimalSurface } from "../lib/minimal-theme.ts";
6
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
+ import type { InputEnhancementsCleanup } from "../lib/input-enhancements.ts";
9
+ import { linkMessageFiles } from "../lib/file-links.ts";
8
10
  import { homedir } from "node:os";
9
11
  import { stripVTControlCharacters } from "node:util";
10
12
  import { dirname, join } from "node:path";
@@ -27,6 +29,7 @@ export interface MiniLensSettings {
27
29
  "pi-mini-mode-speed-show": boolean;
28
30
  "pi-mini-mode-speed-unit-show": boolean;
29
31
  "pi-mini-mode-minimal-show": boolean;
32
+ "pi-mini-mode-input-enhancements": boolean;
30
33
  "pi-mini-mode-minimal-thinking-show": boolean;
31
34
  "pi-mini-mode-minimal-tools-show": boolean;
32
35
  "pi-mini-mode-minimal-output-show": boolean;
@@ -50,6 +53,7 @@ export const DEFAULT_SETTINGS: Readonly<MiniLensSettings> = {
50
53
  "pi-mini-mode-speed-show": true,
51
54
  "pi-mini-mode-speed-unit-show": true,
52
55
  "pi-mini-mode-minimal-show": false,
56
+ "pi-mini-mode-input-enhancements": true,
53
57
  "pi-mini-mode-minimal-thinking-show": true,
54
58
  "pi-mini-mode-minimal-tools-show": true,
55
59
  "pi-mini-mode-minimal-output-show": true,
@@ -63,11 +67,11 @@ const SETTING_IDS = Object.keys(DEFAULT_SETTINGS) as Array<keyof MiniLensSetting
63
67
 
64
68
  const COPY = {
65
69
  title: "Pi Mini Mode 设置", preview: "预览(示例数据)", 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 秒)",
70
+ model: "显示模型", thinking: "显示思考等级", total: "显示会话总 token", cached: "显示会话缓存 token", totalLabel: "Total", cachedLabel: "Cached", cacheHitLabel: "CH", cacheHit: "显示缓存命中率 (CH)", price: "显示会话价格", mcp: "显示已启用 MCP 服务器", context: "显示上下文 token 与进度条", dots: "↳ 使用点阵进度条", percent: "显示上下文百分比", speed: "显示最近生成速度", speedUnit: "↳ 显示 tok/s 单位", inputEnhancements: "输入增强", showThinking: "显示思考", tools: "显示工具调用", output: "显示过程输出", skills: "显示技能", agentUsage: "显示 Agent token 用量", shortcut: "新 Agent 显示 Ctrl+O 提示(6 秒)",
67
71
  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: "/pi-mini-mode-settings 需要 TUI 模式", saveFailed: "无法保存 Pi Mini Mode 设置", minimalRequired: "/pi-mini-mode-minimal 需要 TUI 模式", minimalUsage: "用法:/pi-mini-mode-minimal [on|off]", minimalState: "Pi Mini Mode 折叠回复:", onboarding: "MCP 数量、点阵样式和折叠回复默认关闭;其余项默认开启。", keepDefaults: "保留默认", configureNow: "立即配置",
72
+ enableMinimalDescription: "开启统一折叠思考、工具和技能过程;关闭恢复 Pi 默认会话历史。",
73
+ inputEnhancementsDescription: "原生 Ctrl+V 粘贴图片(Windows/WSL:Alt+V);图片显示为 [image1] 标签,光标移入或全屏悬停可预览。空白后 / 选择技能并在光标处插入。Cmd+点击带下划线的图片标签或消息文件路径,用系统默认应用打开;预览及点击需终端支持。关闭仅恢复原生行为。",
74
+ tuiRequired: "/pi-mini-mode-settings 需要 TUI 模式", saveFailed: "无法保存 Pi Mini Mode 设置", minimalRequired: "/pi-mini-mode-minimal 需要 TUI 模式", minimalUsage: "用法:/pi-mini-mode-minimal [on|off]", minimalState: "Pi Mini Mode 极简输出:", onboarding: "MCP 数量、点阵样式和极简输出默认关闭;其余项默认开启。", keepDefaults: "保留默认", configureNow: "立即配置",
71
75
  } as const;
72
76
 
73
77
  export function settingsPath(agentDir = process.env.PI_MINI_MODE_AGENT_DIR ?? join(homedir(), CONFIG_DIR_NAME, "agent")): string {
@@ -84,6 +88,8 @@ export function parseSettings(value: unknown): MiniLensSettings {
84
88
  for (const id of SETTING_IDS) {
85
89
  if (isBoolean(candidate[id])) settings[id] = candidate[id];
86
90
  }
91
+ // 折叠回复的旧细项已合并进极简输出总开关:旧值不再暗中过滤内容,始终按默认全开。
92
+ for (const id of LEGACY_MINIMAL_SETTING_IDS) settings[id] = true;
87
93
  return settings;
88
94
  }
89
95
 
@@ -363,19 +369,30 @@ export function statusLine(
363
369
  return truncateToWidth(`${content}${content ? gap : ""}${right}`, width, "");
364
370
  }
365
371
 
372
+ const LEGACY_MINIMAL_SETTING_IDS = [
373
+ "pi-mini-mode-minimal-thinking-show", "pi-mini-mode-minimal-tools-show", "pi-mini-mode-minimal-output-show",
374
+ "pi-mini-mode-minimal-skills-show", "pi-mini-mode-agent-usage-show", "pi-mini-mode-agent-shortcut-show",
375
+ ] as const satisfies ReadonlyArray<keyof MiniLensSettings>;
376
+
377
+ /** 模式总开关:设置列表顶部只展示这两项,旧细分项不再展示但仍保留兼容。 */
378
+ const MODE_SETTING_IDS = ["pi-mini-mode-minimal-show", "pi-mini-mode-input-enhancements"] as const;
379
+
380
+ function isModeSetting(id: string): boolean {
381
+ return (MODE_SETTING_IDS as readonly string[]).includes(id);
382
+ }
383
+
366
384
  export function isCollapsedReplyChildSetting(id: string): boolean {
367
- return id === "pi-mini-mode-minimal-thinking-show" || id === "pi-mini-mode-minimal-tools-show" || id === "pi-mini-mode-minimal-output-show"
368
- || id === "pi-mini-mode-minimal-skills-show" || id === "pi-mini-mode-agent-usage-show" || id === "pi-mini-mode-agent-shortcut-show";
385
+ return (LEGACY_MINIMAL_SETTING_IDS as readonly string[]).includes(id);
369
386
  }
370
387
 
371
388
  export function settingsItems(settings: MiniLensSettings): SettingItem[] {
372
389
  const values = ["on", "off"];
373
390
  const labels: Record<Exclude<keyof MiniLensSettings, "onboardingCompleted">, string> = {
374
- "pi-mini-mode-model-show": COPY.model, "pi-mini-mode-thinking-show": COPY.thinking, "pi-mini-mode-session-tokens-show": COPY.total, "pi-mini-mode-cache-tokens-show": COPY.cached, "pi-mini-mode-ch-show": COPY.cacheHit, "pi-mini-mode-cost-show": COPY.price, "pi-mini-mode-mcp-show": COPY.mcp, "pi-mini-mode-context-show": COPY.context, "pi-mini-mode-context-dots-show": COPY.dots, "pi-mini-mode-context-percent-show": COPY.percent, "pi-mini-mode-speed-show": COPY.speed, "pi-mini-mode-speed-unit-show": COPY.speedUnit, "pi-mini-mode-minimal-show": COPY.enableMinimal, "pi-mini-mode-minimal-thinking-show": COPY.showThinking, "pi-mini-mode-minimal-tools-show": COPY.tools, "pi-mini-mode-minimal-output-show": COPY.output, "pi-mini-mode-minimal-skills-show": COPY.skills, "pi-mini-mode-agent-usage-show": COPY.agentUsage, "pi-mini-mode-agent-shortcut-show": COPY.shortcut,
391
+ "pi-mini-mode-model-show": COPY.model, "pi-mini-mode-thinking-show": COPY.thinking, "pi-mini-mode-session-tokens-show": COPY.total, "pi-mini-mode-cache-tokens-show": COPY.cached, "pi-mini-mode-ch-show": COPY.cacheHit, "pi-mini-mode-cost-show": COPY.price, "pi-mini-mode-mcp-show": COPY.mcp, "pi-mini-mode-context-show": COPY.context, "pi-mini-mode-context-dots-show": COPY.dots, "pi-mini-mode-context-percent-show": COPY.percent, "pi-mini-mode-speed-show": COPY.speed, "pi-mini-mode-speed-unit-show": COPY.speedUnit, "pi-mini-mode-minimal-show": COPY.minimal, "pi-mini-mode-input-enhancements": COPY.inputEnhancements, "pi-mini-mode-minimal-thinking-show": COPY.showThinking, "pi-mini-mode-minimal-tools-show": COPY.tools, "pi-mini-mode-minimal-output-show": COPY.output, "pi-mini-mode-minimal-skills-show": COPY.skills, "pi-mini-mode-agent-usage-show": COPY.agentUsage, "pi-mini-mode-agent-shortcut-show": COPY.shortcut,
375
392
  };
376
393
  return (Object.keys(labels) as Array<keyof typeof labels>).map((id) => ({
377
394
  id, label: labels[id],
378
- description: id === "pi-mini-mode-minimal-show" ? COPY.enableMinimalDescription : id === "pi-mini-mode-session-tokens-show" ? COPY.totalDescription : id === "pi-mini-mode-cache-tokens-show" ? COPY.cachedDescription : id === "pi-mini-mode-ch-show" ? COPY.cacheHitDescription : undefined,
395
+ description: id === "pi-mini-mode-minimal-show" ? COPY.enableMinimalDescription : id === "pi-mini-mode-input-enhancements" ? COPY.inputEnhancementsDescription : id === "pi-mini-mode-session-tokens-show" ? COPY.totalDescription : id === "pi-mini-mode-cache-tokens-show" ? COPY.cachedDescription : id === "pi-mini-mode-ch-show" ? COPY.cacheHitDescription : undefined,
379
396
  currentValue: settings[id] ? values[0] : values[1], values,
380
397
  }));
381
398
  }
@@ -555,9 +572,9 @@ function visibleMinimalTurns(settings: MiniLensSettings, turns: MinimalTurn[]):
555
572
  });
556
573
  }
557
574
 
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>()) {
575
+ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], getTurns: () => MinimalTurn[], isExpanded: () => boolean = () => false, showShortcut: (turn: MinimalTurn) => boolean = () => true, showUsage: () => boolean = () => true, subAgentsExpanded: () => boolean = () => false, agentDeadlines = new Map<string, number>(), transformText: (text: string) => string = text => text) {
559
576
  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);
577
+ { color: (value) => theme.fg(process ? "muted" : "text", value) }, { transform: (source, available) => transformText(diagramMarkdown(source, available)) }).render(width);
561
578
  const surface = (rows: string[], width: number, user: boolean) => {
562
579
  const padding = Math.min(2, Math.floor((width - 1) / 2));
563
580
  return ["", ...rows, ""].map((row) => {
@@ -692,10 +709,12 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
692
709
  const questionRows = markdown(turn.question, inner);
693
710
  const loopSummary = piLoopSummary(turn.question);
694
711
  const expanded = expandedPrompts.get(index) === turn.question;
712
+ // A fence is one visual unit; slicing it mid-block looks like raw source.
713
+ const keepFence = !loopSummary && isFencedMarkdown(turn.question);
695
714
  // Loop wakeups are system-generated user messages. Collapse them even when
696
715
  // their short prompt would otherwise fit the normal four-row allowance.
697
- const userRows = expanded ? [...questionRows] : loopSummary ? markdown(loopSummary, inner) : questionRows.slice(0, 4);
698
- if (loopSummary || questionRows.length > 4) {
716
+ const userRows = expanded || keepFence ? [...questionRows] : loopSummary ? markdown(loopSummary, inner) : questionRows.slice(0, 4);
717
+ if (!keepFence && (loopSummary || questionRows.length > 4)) {
699
718
  const label = expanded ? "▴ 收起" : loopSummary ? "▾ 展开" : `▾ 展开 (${questionRows.length} 行)`;
700
719
  const control = truncateToWidth(label, inner, "");
701
720
  promptControls.push({ index, question: turn.question, y: lines.length + 1 + userRows.length,
@@ -858,6 +877,10 @@ export default function (pi: ExtensionAPI) {
858
877
  const minimalToolOutputIndices = new Map<string, number>();
859
878
  let speedTimer: ReturnType<typeof setInterval> | undefined;
860
879
  let settings: MiniLensSettings = { ...DEFAULT_SETTINGS };
880
+ let cleanupInputEnhancements: InputEnhancementsCleanup | undefined;
881
+ let messageCwd = process.cwd();
882
+ const messageLinks = (text: string) => settings["pi-mini-mode-input-enhancements"] ? linkMessageFiles(text, messageCwd) : text;
883
+ pi.registerMarkdownTransformer?.(messageLinks);
861
884
  let saveChain: Promise<void> = Promise.resolve();
862
885
  const configPath = settingsPath();
863
886
 
@@ -926,15 +949,20 @@ export default function (pi: ExtensionAPI) {
926
949
  handledRunIds.clear();
927
950
  return minimalTurns.map((turn, index) => {
928
951
  const turnAgents = assigned.get(index) ?? [];
952
+ for (const status of turnAgents) {
953
+ if (status.runId) handledRunIds.add(String(status.runId));
954
+ if (status.parentWorkflowRunId) handledRunIds.add(String(status.parentWorkflowRunId));
955
+ }
929
956
  const withNotices = agentChildren(turnAgents).map(sub => {
930
957
  if (sub.runId) handledRunIds.add(String(sub.runId));
958
+ if (sub.parentWorkflowRunId) handledRunIds.add(String(sub.parentWorkflowRunId));
931
959
  const n = supervisorNotices.get(String(sub.runId));
932
960
  return n ? { ...sub, notice: n.notice, noticeMessages: n.messages } : sub;
933
961
  });
934
962
  return { ...turn, subAgents: withNotices };
935
963
  });
936
964
  };
937
- const view = minimalOutputComponent(theme, () => visibleMinimalTurns(settings, turnsWithAgents()), () => processExpanded, turn => settings["pi-mini-mode-agent-shortcut-show"] && Date.now() < (turn.shortcutHintUntil ?? 0), () => settings["pi-mini-mode-agent-usage-show"], () => subAgentsExpanded, agentDeadlines);
965
+ const view = minimalOutputComponent(theme, () => visibleMinimalTurns(settings, turnsWithAgents()), () => processExpanded, turn => settings["pi-mini-mode-agent-shortcut-show"] && Date.now() < (turn.shortcutHintUntil ?? 0), () => settings["pi-mini-mode-agent-usage-show"], () => subAgentsExpanded, agentDeadlines, messageLinks);
938
966
  const hintRemaining = (activeMinimalTurn?.shortcutHintUntil ?? 0) - Date.now();
939
967
  if (hintRemaining > 0) {
940
968
  shortcutTimer = setTimeout(() => tui.requestRender(), hintRemaining);
@@ -1055,7 +1083,7 @@ export default function (pi: ExtensionAPI) {
1055
1083
  const onChange = (id: string, value: string) => {
1056
1084
  settings = { ...settings, [id]: value === "on", onboardingCompleted: true };
1057
1085
  items = settingsItems(settings);
1058
- applyCollapseState();
1086
+ cleanupInputEnhancements?.refresh();
1059
1087
  preview.setText(settingsPreviewLine(theme, settings));
1060
1088
  mountMinimalOutput(ctx);
1061
1089
  void persistSettings(ctx);
@@ -1069,31 +1097,16 @@ export default function (pi: ExtensionAPI) {
1069
1097
  label: (text: string, selected: boolean) => {
1070
1098
  const name = text.trimEnd();
1071
1099
  if (selected) highlighted = items.find((item) => item.label === name)?.id as keyof MiniLensSettings | undefined;
1072
- const disabled = name === COPY.minimal && !settings["pi-mini-mode-minimal-show"];
1073
1100
  if (selected) return theme.bg("selectedBg", theme.fg("accent", theme.bold(text)));
1074
- return theme.fg(disabled ? "muted" : "text", text);
1101
+ return theme.fg("text", text);
1075
1102
  },
1076
1103
  value: (text: string, selected: boolean) =>
1077
1104
  selected ? theme.bg("selectedBg", theme.fg("accent", theme.bold(text))) : theme.fg("muted", text),
1078
1105
  };
1079
- const minimalItems = () => settingsItems(settings).filter((item) => isCollapsedReplyChildSetting(item.id));
1080
- const collapseItem: SettingItem = {
1081
- id: "pi-mini-mode-minimal-show", label: COPY.enableMinimal, description: COPY.enableMinimalDescription,
1082
- currentValue: settings["pi-mini-mode-minimal-show"] ? "on" : "off", values: ["on", "off"],
1083
- };
1084
- const minimalGroup: SettingItem = { id: "minimal", label: COPY.minimal, currentValue: "›" };
1085
1106
  const separator: SettingItem = { id: "settings-separator", label: "────────────", currentValue: "" };
1086
- const applyCollapseState = () => {
1087
- const enabled = settings["pi-mini-mode-minimal-show"];
1088
- collapseItem.currentValue = enabled ? "on" : "off";
1089
- minimalGroup.currentValue = enabled ? "›" : "off";
1090
- minimalGroup.description = enabled ? undefined : COPY.minimalLocked;
1091
- if (enabled) minimalGroup.submenu = (_value, back) => new SettingsList(minimalItems(), 8, settingsTheme, onChange, () => back(), { enableSearch: true });
1092
- else delete minimalGroup.submenu;
1093
- };
1094
- applyCollapseState();
1095
- const smallItems = settingsItems(settings).filter((item) => item.id !== "pi-mini-mode-minimal-show" && !isCollapsedReplyChildSetting(item.id));
1096
- const settingsList = new SettingsList([collapseItem, minimalGroup, separator, ...smallItems], 14, settingsTheme, onChange, () => done(undefined), { enableSearch: true });
1107
+ const modeItems = items.filter((item) => isModeSetting(item.id));
1108
+ const lensItems = items.filter((item) => !isModeSetting(item.id) && !isCollapsedReplyChildSetting(item.id));
1109
+ const settingsList = new SettingsList([...modeItems, separator, ...lensItems], 14, settingsTheme, onChange, () => done(undefined), { enableSearch: true });
1097
1110
  container.addChild(settingsList);
1098
1111
  return {
1099
1112
  render: (width: number) => {
@@ -1114,7 +1127,7 @@ export default function (pi: ExtensionAPI) {
1114
1127
  };
1115
1128
 
1116
1129
  pi.registerCommand("pi-mini-mode-minimal", {
1117
- description: "Toggle collapsed replies (off keeps Pi's default conversation history)",
1130
+ description: "Toggle minimal output (off keeps Pi's default conversation history)",
1118
1131
  handler: async (args, ctx) => {
1119
1132
  const normalized = args.trim().toLowerCase();
1120
1133
  if (ctx.mode !== "tui") {
@@ -1178,6 +1191,10 @@ export default function (pi: ExtensionAPI) {
1178
1191
  pi.on("session_start", async (_event, ctx) => {
1179
1192
  const loaded = await loadSettings(configPath);
1180
1193
  settings = loaded.settings;
1194
+ messageCwd = ctx.cwd;
1195
+ // 输入增强只在会话中生效,会话开始时再加载;传 getter 让开关变更即时生效,重复调用是幂等的。
1196
+ const { installInputEnhancements } = await import("../lib/input-enhancements.ts");
1197
+ cleanupInputEnhancements = installInputEnhancements(pi, ctx, () => settings["pi-mini-mode-input-enhancements"]);
1181
1198
  minimalTurns = minimalTurnsFromBranch(ctx.sessionManager.getBranch());
1182
1199
  activeMinimalTurn = undefined;
1183
1200
  pendingMinimalFinal = "";
@@ -1428,6 +1445,8 @@ export default function (pi: ExtensionAPI) {
1428
1445
  refreshMinimalOutput();
1429
1446
  });
1430
1447
  pi.on("session_shutdown", () => {
1448
+ cleanupInputEnhancements?.();
1449
+ cleanupInputEnhancements = undefined;
1431
1450
  persistAgentStatuses?.();
1432
1451
  persistAgentStatuses = undefined;
1433
1452
  agentDeadlines.clear();
package/lib/agent-view.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { diagramMarkdown, isMarkdownProse, minimalMarkdownTheme } from "./minimal-markdown.ts";
2
- import { supervisorNoticeBody } from "./transcript-adapter.ts";
2
+ import { extractNoticeBody, supervisorNoticeBody } from "./transcript-adapter.ts";
3
3
  import { readdirSync, readFileSync, statSync } from "node:fs";
4
4
  import { join, resolve } from "node:path";
5
5
  import { tmpdir } from "node:os";
@@ -57,8 +57,16 @@ export function agentCallRows(calls: AgentCall[], theme: Theme, width: number, e
57
57
 
58
58
  const plain = (text: string) => text.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, "").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").trim();
59
59
 
60
- /** Recover structured final text and raw tool inputs from the child session, never from activity previews. */
61
- const childSessionCache = new Map<string, { stamp: string; thinking: string; finalOutput: string; inputs: Array<{ name: string; value: string }> }>();
60
+ /** Child gate JSON is for the runtime, not the transcript. */
61
+ export function stripAcceptanceReport(output: string): string {
62
+ return output
63
+ .replace(/\n?```acceptance[-_]report\s*\n[\s\S]*?```\s*$/i, "")
64
+ .replace(/\n?ACCEPTANCE_REPORT\s*:\s*\{[\s\S]*\}\s*$/i, "")
65
+ .trimEnd();
66
+ }
67
+
68
+ /** Recover the child's own prose and raw tool inputs from its session, never from activity previews. */
69
+ const childSessionCache = new Map<string, { stamp: string; thinking: string; finalOutput: string; latestText: string; inputs: Array<{ name: string; value: string }> }>();
62
70
  const singleLine = (value: string) => plain(value).replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ");
63
71
  function childSessionData(sessionFile: unknown) {
64
72
  if (typeof sessionFile !== "string") return undefined;
@@ -70,6 +78,7 @@ function childSessionData(sessionFile: unknown) {
70
78
  const inputs: Array<{ name: string; value: string }> = [];
71
79
  let thinking = "";
72
80
  let finalOutput = "";
81
+ let latestText = "";
73
82
  for (const line of readFileSync(sessionFile, "utf8").split(/\r?\n/)) {
74
83
  try {
75
84
  const entry = JSON.parse(line) as { type?: string; thinkingLevel?: string; message?: { role?: string; stopReason?: string; channel?: string; content?: Array<{ type?: string; text?: string; name?: string; input?: Record<string, unknown>; arguments?: Record<string, unknown> } | null> } };
@@ -77,11 +86,15 @@ function childSessionData(sessionFile: unknown) {
77
86
  if (entry.message?.role !== "assistant") continue;
78
87
  const message = entry.message;
79
88
  const content = Array.isArray(message.content) ? message.content : [];
89
+ const text = content.filter(block => block?.type === "text" && typeof block.text === "string").map(block => block!.text).join("\n\n").trim();
80
90
  // Pi persists no channel: only a stopped assistant text reply is a final answer.
81
91
  finalOutput = entry.type === "message" && message.stopReason === "stop"
82
92
  && (message.channel === undefined || message.channel === "final")
83
93
  && !content.some(block => block?.type === "toolCall")
84
- ? content.filter(block => block?.type === "text" && typeof block.text === "string").map(block => block!.text).join("\n\n").trim() : "";
94
+ ? text : "";
95
+ // Narration attached to a tool call is still the child's own prose; it
96
+ // is the only body a running or tool-ended child has.
97
+ if (entry.type === "message" && text) latestText = text;
85
98
  for (const call of content) {
86
99
  if (!call) continue;
87
100
  if (call.type !== "toolCall" || typeof call.name !== "string") continue;
@@ -92,7 +105,7 @@ function childSessionData(sessionFile: unknown) {
92
105
  }
93
106
  } catch { /* A concurrently written session can end with a partial line. */ }
94
107
  }
95
- cached = { stamp, thinking, finalOutput, inputs };
108
+ cached = { stamp, thinking, finalOutput, latestText, inputs };
96
109
  childSessionCache.set(sessionFile, cached);
97
110
  }
98
111
  return cached;
@@ -154,6 +167,14 @@ export function restyleAgentWidget(lines: string[], theme: Theme, width: number,
154
167
  return rows;
155
168
  }
156
169
 
170
+ /** Expanded heading: full-width selectedBg, keeping inner fg after resets.
171
+ * theme.bg only wraps the ends; older themes without getBgAnsi lose fill after \x1b[0m. */
172
+ function paintExpandedHeading(theme: Theme, line: string): string {
173
+ const background = theme.getBgAnsi?.("selectedBg") ?? "";
174
+ return background
175
+ ? background + line.replace(/\x1b\[(?:0|49)?m/g, reset => reset + background) + "\x1b[49m"
176
+ : theme.bg("selectedBg", line);
177
+ }
157
178
  function agentSummary(theme: Theme, width: number, running: number, done: number, errors: number, expanded: boolean): string {
158
179
  const label = `Sub Agent · running ${running}${done ? ` · done ${done}` : ""}${errors ? ` · failed ${errors}` : ""}${done ? ` · Ctrl+S ${expanded ? "collapse" : "expand"}` : ""}`;
159
180
  const summary = truncateToWidth(theme.fg(errors ? "error" : "muted", label), width);
@@ -320,20 +341,14 @@ export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme,
320
341
  const rows: string[] = [];
321
342
  const text = (value: unknown) => typeof value === "string" ? plain(value).replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ") : "";
322
343
  const bodyText = (value: unknown) => typeof value === "string"
323
- ? plain(value).replace(/[\x00-\x09\x0b\x0c\x0e-\x1f\x7f]/g, " ").trim() : "";
344
+ ? stripAcceptanceReport(plain(value).replace(/[\x00-\x09\x0b\x0c\x0e-\x1f\x7f]/g, " ")).trim() : "";
324
345
  const renderBody = (source: string, available: number) => {
346
+ const width = Math.max(1, available);
325
347
  if (isMarkdownProse(source)) return new Markdown(source, 0, 0, minimalMarkdownTheme(getMarkdownTheme()),
326
- { color: value => theme.fg("muted", value) }, { transform: diagramMarkdown }).render(Math.max(1, available));
327
- const rows: string[] = [];
328
- for (const sourceLine of source.split(/\r?\n/)) {
329
- let line = sourceLine;
330
- do {
331
- const row = truncateToWidth(line, Math.max(1, available), "");
332
- rows.push(theme.fg("muted", row));
333
- line = line.slice(row.length);
334
- } while (line);
335
- }
336
- return rows;
348
+ { color: value => theme.fg("muted", value) }, { transform: diagramMarkdown }).render(width);
349
+ // Wrap by visible columns. Do not re-slice truncateToWidth: it appends a
350
+ // reset, so slice(row.length) would drop source characters on every wrap.
351
+ return wrapTextWithAnsi(source, width).map(row => theme.fg("muted", row));
337
352
  };
338
353
  if (width > 0) all.forEach((child, index) => {
339
354
  const runKey = String(child.runId ?? child.displayId);
@@ -369,36 +384,67 @@ export function liveAgentView(statuses: Record<string, unknown>[], theme: Theme,
369
384
  const endedAt = terminal ? timestamp(child.endedAt) ?? deadlines.get(`${elapsedKey}:ended`) ?? now : now;
370
385
  if (terminal) deadlines.set(`${elapsedKey}:ended`, endedAt);
371
386
  const elapsed = formatAgentElapsed(startedAt, endedAt);
372
- const heading = truncateToWidth(theme.fg("dim", `${index === all.length - 1 ? "└─" : "├─"} `)
387
+ const identity = isChildExpanded ? "accent" : color;
388
+ const heading = truncateToWidth(theme.fg(isChildExpanded ? "accent" : "dim", `${index === all.length - 1 ? "└─" : "├─"} `)
373
389
  + theme.fg(failedAgent(child) || notice?.color === "error" ? "error" : notice?.color === "warning" ? "warning" : isRunning && !terminal ? "accent" : "muted", `${glyph} `)
374
- + theme.fg("text", theme.bold("SubAgent"))
375
- + theme.fg(color, ` • ${suffix ? model.slice(0, -suffix[0].length) : model}`)
376
- + (level ? theme.fg("muted", ` ${level}`) : "") + theme.fg(terminal ? "muted" : "success", ` ${elapsed}`) + theme.fg(color, " : "), width, "…");
390
+ + theme.fg(identity, theme.bold("SubAgent"))
391
+ + theme.fg(identity, ` • ${suffix ? model.slice(0, -suffix[0].length) : model}`)
392
+ + (level ? theme.fg("muted", ` ${level}`) : "") + theme.fg(terminal ? "muted" : "success", ` ${elapsed}`) + theme.fg(identity, " : "), width, "…");
377
393
  const bodyBudget = Math.max(0, width - visibleWidth(heading));
378
394
  const progress = !bodyBudget ? "" : truncateToWidth(body, bodyBudget, "…");
379
- const row = heading + theme.fg("muted", progress);
380
- const line = row + " ".repeat(Math.max(0, width - visibleWidth(row)));
395
+ const row = heading + theme.fg(isChildExpanded ? "accent" : "muted", progress);
396
+ const padded = row + " ".repeat(Math.max(0, width - visibleWidth(row)));
397
+ const line = isChildExpanded ? paintExpandedHeading(theme, padded) : padded;
381
398
  subagentControls?.push({ runId: runKey, y: rows.length, width, line });
382
399
  rows.push(line);
383
400
  if (isChildExpanded) {
384
- // Live activity is literal text, not a final answer or Markdown tool output.
401
+ let processShown = false;
385
402
  if (!terminal) {
386
- const details = wrapTextWithAnsi(`当前活动:${text(activity)}`, Math.max(1, width - 3));
387
- rows.push(...details.map(line => truncateToWidth(` ${theme.fg("muted", line)}`, width)));
403
+ const process: Array<{ name: string; args: string }> = tools.slice(-6).map(tool => ({
404
+ name: text(tool.tool) || "tool",
405
+ args: rawToolInput(child.sessionFile, tool.tool, text(tool.args)),
406
+ }));
407
+ if (!process.length && child.currentTool) {
408
+ process.push({ name: text(child.currentTool), args: text(child.currentPath || child.currentToolArgs) });
409
+ }
410
+ for (const item of process) {
411
+ const prefix = ` ${theme.fg("muted", "●")} ${theme.fg("text", theme.bold(item.name))}${item.args ? " " : ""}`;
412
+ rows.push(truncateToWidth(prefix + (item.args ? theme.fg("muted", item.args) : ""), width, "…"));
413
+ processShown = true;
414
+ }
388
415
  }
389
416
  const messages = Array.isArray(child.noticeMessages) ? child.noticeMessages : [];
390
417
  const bodies: string[] = [];
418
+ let latestProgress = "";
391
419
  for (const msg of messages) {
420
+ const item = msg && typeof msg === "object" ? msg as Record<string, unknown> : undefined;
421
+ const details = item?.details && typeof item.details === "object" ? item.details as Record<string, unknown> : undefined;
422
+ if (item?.customType === "subagent_supervisor_request" && details?.reason === "progress_update") {
423
+ const progress = extractNoticeBody(msg);
424
+ if (progress) latestProgress = progress;
425
+ continue;
426
+ }
392
427
  const b = supervisorNoticeBody(msg);
393
428
  if (b && !bodies.includes(b)) bodies.push(b);
394
429
  }
395
- const finalOutput = terminal ? bodyText(childSessionData(child.sessionFile)?.finalOutput ?? child.finalOutput) : "";
430
+ const session = childSessionData(child.sessionFile);
431
+ if (!bodies.length && latestProgress) bodies.push(latestProgress);
432
+ const latestText = bodyText(session?.latestText);
433
+ if (!terminal && latestText && !bodies.length) bodies.push(latestText);
434
+ // A stopped answer outranks the running narration; the narration still
435
+ // covers a child that ended between turns or without a stopped reply.
436
+ const finalOutput = terminal ? bodyText(session?.finalOutput || latestText || child.finalOutput) : "";
396
437
  if (finalOutput && !bodies.includes(finalOutput)) bodies.push(finalOutput);
397
438
  const error = bodyText(child.error);
398
439
  if (error && !bodies.includes(error)) bodies.push(error);
399
- for (const textBody of bodies) {
440
+ if (!terminal && !processShown && !bodies.length) {
441
+ rows.push(truncateToWidth(` ${theme.fg("muted", "●")} ${theme.fg("text", theme.bold(text(state)))}`, width, "…"));
442
+ processShown = true;
443
+ }
444
+ for (const [index, textBody] of bodies.entries()) {
400
445
  // Child/supervisor bodies are Markdown prose; tool logs and JSON are
401
446
  // not placed in this semantic body channel.
447
+ if (processShown || index > 0) rows.push("");
402
448
  for (const line of renderBody(textBody, Math.max(1, width - 3))) {
403
449
  rows.push(truncateToWidth(` ${line}`, width));
404
450
  }
@@ -0,0 +1,80 @@
1
+ import { existsSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, isAbsolute, resolve } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { getCapabilities, sliceByColumn, stripTerminalSequences, visibleWidth } from "@earendil-works/pi-tui";
6
+
7
+ /** Pi 0.85's allowlist predates Otty; preserve explicit opt-outs and multiplexer detection. */
8
+ export function inputCapabilities(env = process.env) {
9
+ const caps = getCapabilities();
10
+ if (env.TERM_PROGRAM?.toLowerCase() !== "otty" || env.TMUX || /^(screen|tmux)/.test(env.TERM ?? "")) return caps;
11
+ return { ...caps, hyperlinks: env.PI_HYPERLINKS === "0" ? false : true,
12
+ images: env.PI_IMAGE_PROTOCOL === "0" || env.PI_IMAGE_PROTOCOL === "none" ? null : caps.images ?? "kitty" as const };
13
+ }
14
+
15
+ export function localPath(path: string, cwd: string): string {
16
+ return path.startsWith("~/") ? resolve(homedir(), path.slice(2)) : isAbsolute(path) ? path : resolve(cwd, path);
17
+ }
18
+
19
+ /** Opening/closing fences must stay intact; quoted paths inside them are not links. */
20
+ function fenceRanges(text: string): Array<[number, number]> {
21
+ const ranges: Array<[number, number]> = [];
22
+ const open = /(^|\n)( {0,3})(`{3,}|~{3,})[^\n]*\n/g;
23
+ for (let match = open.exec(text); match; match = open.exec(text)) {
24
+ const start = match.index + match[1].length;
25
+ const escaped = match[3].replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
26
+ // Search only after the opener, then resume after the closer, so a closing
27
+ // fence can never be read as the next opener and swallow the text behind it.
28
+ const close = new RegExp(`(?:^|\\n) {0,3}${escaped}[ \\t]*(?:\\n|$)`).exec(text.slice(open.lastIndex));
29
+ if (!close) {
30
+ ranges.push([start, text.length]);
31
+ break;
32
+ }
33
+ open.lastIndex += close.index + close[0].length;
34
+ ranges.push([start, open.lastIndex]);
35
+ }
36
+ return ranges;
37
+ }
38
+
39
+ /** Quoted paths may contain spaces; unquoted paths end at prose delimiters. */
40
+ export function filePaths(text: string) {
41
+ const matches: Array<{ path: string; start: number; end: number }> = [];
42
+ const fences = fenceRanges(text);
43
+ const pattern = /(["'`])([^\r\n]*?)\1|[^\s"'`<>()[\]{},。;!?]+/g;
44
+ for (const match of text.matchAll(pattern)) {
45
+ const path = (match[2] ?? match[0]).replace(/[.,;:!?]+$/, "");
46
+ if (!path || /[\x00-\x1f\x7f]/.test(path) || /^[a-z][\w+.-]*:\/\//i.test(path)) continue;
47
+ if (!/^(?:\/|~\/|\.{1,2}\/|[a-z]:[\\/])|[\\/]|\.[a-z\d]{1,12}$/i.test(path)) continue;
48
+ const start = match.index + (match[1] ? 1 : 0);
49
+ const end = start + path.length;
50
+ if (fences.some(([from, to]) => start < to && end > from)) continue;
51
+ matches.push({ path, start, end });
52
+ }
53
+ return matches;
54
+ }
55
+
56
+ // BEL survives Markdown's backslash-escape parsing, unlike the ST terminator.
57
+ export const fileLink = (text: string, path: string) => `\x1b]8;;${pathToFileURL(path).href}\x07\x1b[4m${text}\x1b[24m\x1b]8;;\x07`;
58
+
59
+ /** Display-only: never change persisted messages, existing links, or remote URLs. */
60
+ export function linkMessageFiles(text: string, cwd: string): string {
61
+ if (!inputCapabilities().hyperlinks) return text;
62
+ let imageNumber = 0;
63
+ return text.split(/(\x1b\]8;[^\x07]*(?:\x07)[\s\S]*?\x1b\]8;;\x07|\[[^\]\n]*\]\([^\n]*?\))/g).map((part, index) => {
64
+ if (index % 2) return part;
65
+ const matches = filePaths(part).map(match => ({ ...match, label: /\.(png|jpe?g|gif|webp)$/i.test(match.path) && existsSync(localPath(match.path, cwd)) ? `[image${++imageNumber}]` : match.path }));
66
+ for (const match of matches.reverse()) {
67
+ const path = localPath(match.path, cwd);
68
+ if (!existsSync(path)) continue;
69
+ part = part.slice(0, match.start) + fileLink(match.label, path) + part.slice(match.end);
70
+ }
71
+ return part;
72
+ }).join("");
73
+ }
74
+
75
+ /** Decorate rendered columns without removing the editor's ANSI cursor marker. */
76
+ export function linkRenderedPath(line: string, start: number, end: number, path: string, directory = false): string {
77
+ if (!inputCapabilities().hyperlinks || end <= start) return line;
78
+ return sliceByColumn(line, 0, start) + fileLink(sliceByColumn(line, start, end - start), directory ? dirname(path) : path)
79
+ + sliceByColumn(line, end, Math.max(0, visibleWidth(stripTerminalSequences(line)) - end));
80
+ }
@@ -1,12 +1,7 @@
1
1
  /** Hide noisy footer statuses (LSP / @build / sandbox / write path, etc.). */
2
2
 
3
- type FooterData = {
4
- getExtensionStatuses(): Iterable<[string, string]>;
5
- };
6
-
7
3
  type StatusUi = {
8
4
  setStatus(key: string, text: string | undefined): void;
9
- setFooter(factory: ((tui: unknown, theme: unknown, footerData: FooterData) => { render: () => string[] }) | undefined): void;
10
5
  };
11
6
 
12
7
  type ExtensionCtx = {
@@ -17,6 +12,8 @@ type ExtensionAPILike = {
17
12
  on(event: string, handler: (...args: any[]) => void): void;
18
13
  };
19
14
 
15
+ const HIDDEN_KEYS = ["pi-lens-lsp", "@build", "build", "sandbox"] as const;
16
+
20
17
  function stripAnsi(text: string): string {
21
18
  return String(text || "").replace(/\x1b\[[0-9;]*m/g, "");
22
19
  }
@@ -30,7 +27,7 @@ function tidyText(text: string): string {
30
27
  .trim();
31
28
  }
32
29
 
33
- function hideStatus(key: string, text: string): boolean {
30
+ export function hideStatus(key: string, text: string): boolean {
34
31
  const k = String(key || "").toLowerCase();
35
32
  const v = String(text || "").toLowerCase();
36
33
  if (k === "pi-lens-lsp" || k.includes("lsp")) return true;
@@ -62,61 +59,17 @@ function wrapSetStatus(ctx: ExtensionCtx): StatusUi["setStatus"] {
62
59
  return orig;
63
60
  }
64
61
 
65
- function sweep(origSet: StatusUi["setStatus"], footerData: FooterData): void {
66
- for (const [key, text] of footerData.getExtensionStatuses()) {
67
- if (hideStatus(key, text)) {
68
- origSet(key, undefined);
69
- continue;
70
- }
71
- const visible = stripAnsi(text).replace(/[\r\n\t]/g, " ");
72
- if (/^[ \t·•|●○]+/.test(visible) || /[ \t·•|●○]+$/.test(visible)) {
73
- origSet(key, tidyText(text) || undefined);
74
- }
75
- }
76
- origSet("pi-lens-lsp", undefined);
77
- origSet("@build", undefined);
78
- origSet("build", undefined);
79
- origSet("sandbox", undefined);
62
+ function clearKnownNoise(setStatus: StatusUi["setStatus"]): void {
63
+ for (const key of HIDDEN_KEYS) setStatus(key, undefined);
80
64
  }
81
65
 
82
- /** Attach footer-tidy behavior. Register before the main footer so the first capture runs first. */
66
+ /**
67
+ * Filter noisy setStatus writes.
68
+ * Never call setFooter — swapping the 1-line custom footer with Pi's 2–3 line
69
+ * built-in footer changes height and desyncs differential redraw.
70
+ */
83
71
  export default function attachFooterTidy(pi: ExtensionAPILike): void {
84
- let timer: ReturnType<typeof setInterval> | undefined;
85
- let captured: FooterData | undefined;
86
- let capturing = false;
87
-
88
- const grabFooterData = (ctx: ExtensionCtx) => {
89
- if (capturing || captured) return;
90
- capturing = true;
91
- ctx.ui.setFooter((_tui, _theme, footerData) => {
92
- captured = footerData;
93
- queueMicrotask(() => {
94
- ctx.ui.setFooter(undefined);
95
- capturing = false;
96
- });
97
- return { render: () => [] };
98
- });
99
- };
100
-
101
- const start = (_event: unknown, ctx: ExtensionCtx) => {
102
- const origSet = wrapSetStatus(ctx);
103
- grabFooterData(ctx);
104
- if (timer) clearInterval(timer);
105
- timer = setInterval(() => {
106
- origSet("pi-lens-lsp", undefined);
107
- origSet("@build", undefined);
108
- origSet("build", undefined);
109
- origSet("sandbox", undefined);
110
- if (captured) sweep(origSet, captured);
111
- else grabFooterData(ctx);
112
- }, 250);
113
- timer.unref?.();
114
- };
115
-
116
- pi.on("session_start", start);
117
- pi.on("session_shutdown", () => {
118
- if (timer) clearInterval(timer);
119
- timer = undefined;
120
- captured = undefined;
72
+ pi.on("session_start", (_event: unknown, ctx: ExtensionCtx) => {
73
+ clearKnownNoise(wrapSetStatus(ctx));
121
74
  });
122
75
  }