@each1024/pi-mini-mode 2.0.2 → 2.0.5

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 CHANGED
@@ -10,7 +10,9 @@ An everyday refinement for [Pi](https://pi.dev), not just a footer. Preview imag
10
10
 
11
11
  ## Demo video
12
12
 
13
- <video src="https://github.com/user-attachments/assets/e8a011e1-e61c-44c7-b577-ae41d3a17945" controls muted playsinline width="100%"></video>
13
+ https://github.com/user-attachments/assets/1ad90757-ecea-4901-afd8-f33a68176ae2
14
+
15
+ https://github.com/user-attachments/assets/53c1bcd8-9f0b-42d7-a424-a407dcf666e8
14
16
 
15
17
  Numbers in the footer shots come from a scripted demo session; prices are estimates, not provider bills.
16
18
 
@@ -89,13 +91,11 @@ Turn **Minimal output** off in settings to restore native Pi history.
89
91
  **The useful signals, in one line.** Model and thinking level, session tokens, cache totals and hit rate, estimated cost, context usage and generation speed. Choose your fields in `/pi-mini-mode-settings`; changes take effect immediately, and the footer adapts to narrow terminals.
90
92
 
91
93
  <details>
92
- <summary>See the footer settings and demo</summary>
94
+ <summary>See the footer settings</summary>
93
95
 
94
96
  [![Existing footer settings screenshot](https://raw.githubusercontent.com/eachann1024/pi-mini-mode/main/assets/pi-mini-mode-settings.jpg)](https://raw.githubusercontent.com/eachann1024/pi-mini-mode/main/assets/pi-mini-mode-settings.jpg)
95
97
 
96
- [Watch the footer settings demo](https://github.com/user-attachments/assets/5f2f4816-45ed-4759-b035-d9ee59e8a763)
97
-
98
- This earlier screenshot and recording show footer configuration, not the newer image, folding or subagent features. Settings previews use sample data.
98
+ This earlier screenshot shows footer configuration, not the newer image, folding or subagent features. Settings previews use sample data.
99
99
 
100
100
  </details>
101
101
 
package/README.zh-CN.md CHANGED
@@ -10,7 +10,9 @@
10
10
 
11
11
  ## 演示视频
12
12
 
13
- <video src="https://github.com/user-attachments/assets/cf66fae3-d289-422a-9e2e-636d197ec514" controls muted playsinline width="100%"></video>
13
+ https://github.com/user-attachments/assets/1ad90757-ecea-4901-afd8-f33a68176ae2
14
+
15
+ https://github.com/user-attachments/assets/53c1bcd8-9f0b-42d7-a424-a407dcf666e8
14
16
 
15
17
  页脚画面中的数字来自脚本化的演示会话,价格为估算值,不是服务商账单。
16
18
 
@@ -89,13 +91,11 @@ pi install git:github.com/eachann1024/pi-mini-mode
89
91
  **重要指标,一行看清。** 模型与思考级别、会话令牌、缓存总量与命中率、费用估算、上下文用量与生成速度。在 `/pi-mini-mode-settings` 中选择显示字段,即时生效,页脚自动适配窄终端。
90
92
 
91
93
  <details>
92
- <summary>查看页脚设置截图与演示</summary>
94
+ <summary>查看页脚设置截图</summary>
93
95
 
94
96
  [![已有的页脚设置截图](https://raw.githubusercontent.com/eachann1024/pi-mini-mode/main/assets/pi-mini-mode-settings.jpg)](https://raw.githubusercontent.com/eachann1024/pi-mini-mode/main/assets/pi-mini-mode-settings.jpg)
95
97
 
96
- [观看页脚设置演示](https://github.com/user-attachments/assets/5f2f4816-45ed-4759-b035-d9ee59e8a763)
97
-
98
- 这份已有截图和录屏展示页脚配置,不代表新增图片、折叠与子代理功能的当前界面。设置预览使用示例数据。
98
+ 这张已有截图展示页脚配置,不代表新增图片、折叠与子代理功能的当前界面。设置预览使用示例数据。
99
99
 
100
100
  </details>
101
101
 
@@ -1,13 +1,15 @@
1
1
  import { AGENT_STATUS_ENTRY, savedAgentStatuses, retainAgentStatuses, agentChildren, agentCall, agentCallDisplay, agentStatusesByTurn, attachAgentWidgets, isAgentTool, liveAgentView, readAgentStatuses, runningGlyph, type AgentCall } from "../lib/agent-view.ts";
2
2
  import { CONFIG_DIR_NAME, getAgentDir, getMarkdownTheme, SettingsManager, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
3
3
  import { attachTranscript, type NoticeRows, type TurnNotices } from "../lib/transcript-adapter.ts";
4
+ import { imagePlaceholders, createAssistantImages } from "../lib/assistant-images.ts";
5
+ import { installSeamlessScrollbar } from "../lib/seamless-scrollbar.ts";
4
6
  import { diagramMarkdown, isFencedMarkdown, renderMinimalMarkdown } from "../lib/minimal-markdown.ts";
5
7
  import { minimalSurface, paintExpandedHeading } from "../lib/minimal-theme.ts";
6
8
  import { Markdown, matchesKey, isKeyRelease, isKeyRepeat, sliceByColumn, type SettingItem, Text, type TuiMouseEvent, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
7
9
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
10
  import { installInputEnhancements, type InputEnhancementsCleanup } from "../lib/input-enhancements.ts";
9
11
  import { installTerminalCapabilities } from "../lib/terminal-capabilities.ts";
10
- import { linkMessageFiles } from "../lib/file-links.ts";
12
+ import { linkMessageFiles, linkToolFiles } from "../lib/file-links.ts";
11
13
  import { homedir } from "node:os";
12
14
  import { stripVTControlCharacters } from "node:util";
13
15
  import { basename, dirname, join } from "node:path";
@@ -537,6 +539,7 @@ export interface MinimalTurn {
537
539
  running?: boolean;
538
540
  /** Wall-clock start of this user-request execution; retained across tool and thinking turns. */
539
541
  startedAt?: number;
542
+ endedAt?: number;
540
543
  thinking?: number;
541
544
  /** Per-process-index Thinking clocks. Live rows count; completed rows keep endedAt. */
542
545
  thinkingClocks?: Array<ThinkingClock | undefined>;
@@ -584,6 +587,17 @@ export function formatElapsed(startedAt: number | undefined, now = Date.now()):
584
587
  return minutes >= 60 ? `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, "0")}:${remainder}` : `${minutes}:${remainder}`;
585
588
  }
586
589
 
590
+ /** Compact tool duration, visible from the start of execution. */
591
+ export function formatToolElapsed(startedAt: number | undefined, endedAt = Date.now()): string {
592
+ if (startedAt === undefined) return "";
593
+ const seconds = Math.max(0, Math.floor((endedAt - startedAt) / 1_000));
594
+ if (!seconds) return "1s";
595
+ const hours = Math.floor(seconds / 3_600);
596
+ const minutes = Math.floor(seconds / 60) % 60;
597
+ const remainder = seconds % 60;
598
+ return `${hours ? `${hours}h` : ""}${minutes ? `${minutes}m` : ""}${remainder ? `${remainder}s` : ""}`;
599
+ }
600
+
587
601
  function ensureThinkingClock(turn: MinimalTurn, index: number, startedAt = Date.now()): ThinkingClock {
588
602
  const clocks = turn.thinkingClocks ??= [];
589
603
  return clocks[index] ??= { startedAt: turn.startedAt ?? startedAt };
@@ -610,8 +624,9 @@ export function formatThinkingElapsed(
610
624
  now = Date.now(),
611
625
  ): string {
612
626
  const clock = turn.thinkingClocks?.[processIndex];
613
- if (active) return formatElapsed(clock?.startedAt ?? turn.startedAt, now);
614
- if (clock?.endedAt != null) return formatElapsed(clock.startedAt, clock.endedAt);
627
+ const startedAt = clock?.startedAt ?? turn.startedAt;
628
+ if (active && startedAt != null) return `${(Math.max(0, now - startedAt) / 1_000).toFixed(1)}s`;
629
+ if (clock?.endedAt != null) return `${(Math.max(0, clock.endedAt - clock.startedAt) / 1_000).toFixed(1)}s`;
615
630
  return "";
616
631
  }
617
632
 
@@ -622,6 +637,20 @@ function pushProcess(turn: MinimalTurn | undefined, kind: string, value: unknown
622
637
  if (turn.process.at(-1) !== line) turn.process.push(line);
623
638
  }
624
639
 
640
+ function thinkingText(item: Record<string, unknown>): string {
641
+ const value = item.thinking ?? item.text;
642
+ return typeof value === "string" ? (value.trim() ? value : "") : processText(value);
643
+ }
644
+
645
+ /** Only adjacent empty blocks in the same assistant content share a row. */
646
+ function continuesEmptyThinking(content: Array<Record<string, unknown>>, blockIndex: number): boolean {
647
+ const item = content[blockIndex];
648
+ const previous = content[blockIndex - 1];
649
+ return item?.type === "thinking" && previous?.type === "thinking"
650
+ && !thinkingText(item)
651
+ && !thinkingText(previous);
652
+ }
653
+
625
654
  function skillNames(text: string): string[] {
626
655
  const names = new Set<string>();
627
656
  for (const match of text.matchAll(/\/skill:([\w.-]+)/g)) names.add(match[1]);
@@ -669,10 +698,13 @@ export function minimalTurnsFromBranch(branch: readonly unknown[]): MinimalTurn[
669
698
  if (role !== "assistant" || !Array.isArray(content)) continue;
670
699
  if (turn.final) (turn.replies ??= []).push(turn.final);
671
700
  turn.final = undefined;
672
- for (const item of content as Array<Record<string, unknown>>) {
701
+ for (const [blockIndex, item] of (content as Array<Record<string, unknown>>).entries()) {
673
702
  if (!item || typeof item !== "object") continue;
674
- if (item.type === "thinking") pushProcess(turn, "thinking", item.thinking ?? item.text);
675
- else if (item.type === "toolCall") {
703
+ if (item.type === "thinking") {
704
+ if (!continuesEmptyThinking(content as Array<Record<string, unknown>>, blockIndex)) {
705
+ turn.process.push(`thinking ${thinkingText(item)}`);
706
+ }
707
+ } else if (item.type === "toolCall") {
676
708
  if (item.name) {
677
709
  (turn.agentCalls ??= []).push(agentCall(String(item.id), String(item.name), item.arguments ?? item.input));
678
710
  pushProcess(turn, "call", String(item.id));
@@ -726,9 +758,12 @@ function visibleMinimalTurns(settings: MiniLensSettings, turns: MinimalTurn[]):
726
758
  });
727
759
  }
728
760
 
729
- 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) {
761
+ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], getTurns: () => MinimalTurn[], isExpanded: () => boolean = () => false, showShortcut: (turn: MinimalTurn) => boolean = () => true, showUsage: () => boolean = () => true, subAgentsExpanded: () => boolean = () => false, agentDeadlines = new Map<string, number>(), transformText: (text: string) => string = text => text, imageOptions?: { cwd(): string; requestRender(): void; write?(data: string): void }) {
762
+ const placeholderText = (text: string) => imageOptions ? imagePlaceholders(text, imageOptions.cwd()) : text;
730
763
  const markdown = (text: string, width: number, process = false) => renderMinimalMarkdown(text, width, getMarkdownTheme(), theme.getBgAnsi?.("userMessageBg") ?? "",
731
- { color: (value) => theme.fg(process ? "muted" : "text", value) }, (source, available) => transformText(diagramMarkdown(source, available)));
764
+ { color: (value) => theme.fg(process ? "muted" : "text", value) }, (source, available) => transformText(placeholderText(diagramMarkdown(source, available))));
765
+ const assistantImages = imageOptions && createAssistantImages(imageOptions.cwd, imageOptions.requestRender, imageOptions.write);
766
+ const assistantMarkdown = (text: string, width: number, owner: string) => assistantImages ? assistantImages.render(text, width, markdown, owner) : markdown(text, width);
732
767
  const surface = (rows: string[], width: number, user: boolean, selected = -1, expanded = false) => {
733
768
  const padding = Math.min(2, Math.floor((width - 1) / 2));
734
769
  return ["", ...rows, ""].map((row, index) => {
@@ -741,11 +776,17 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
741
776
  const expandedSubagents = new Set<string>();
742
777
  const expandedTools = new Set<string>();
743
778
  const expandedThinking = new Set<string>();
779
+ const PROCESS_PREVIEW_ROWS = 6;
780
+ const agentModes = new Map<number, "all" | "preview" | "closed">();
781
+ const runningTurns = new Set<number>();
744
782
  let pinnedToolId: string | undefined;
745
783
  let pinnedTool: { id: string; y: number; line: string } | undefined;
784
+ let pinnedAgentIndex: number | undefined;
785
+ let pinnedAgent: { index: number; y: number; line: string } | undefined;
746
786
  let pinnedSubagentId: string | undefined;
747
787
  let pinnedSubagent: { id: string; y: number; line: string; autoScroll?: boolean } | undefined;
748
788
  let toolControls: Array<{ id: string; y: number; width: number; title: string }> = [];
789
+ let agentControls: Array<{ index: number; y: number; width: number }> = [];
749
790
  let hoveredTool: typeof toolControls[number] | undefined;
750
791
  const clearHover = () => { const changed = !!hoveredTool; hoveredTool = undefined; return changed; };
751
792
  const toggleTool = (id: string) => {
@@ -758,6 +799,16 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
758
799
  clearHover();
759
800
  return;
760
801
  }
802
+ if (id.startsWith("agents:")) {
803
+ const index = Number(id.slice(7));
804
+ if (!Number.isInteger(index) || !getTurns()[index]) return;
805
+ const all = (agentModes.get(index) ?? (isExpanded() ? "all" : "preview")) === "all";
806
+ agentModes.set(index, all ? "preview" : "all");
807
+ if (all) { expandedThinking.clear(); expandedTools.clear(); expandedSubagents.clear(); }
808
+ pinnedAgentIndex = all ? undefined : index;
809
+ clearHover();
810
+ return;
811
+ }
761
812
  if (!getTurns().some(turn => turn.agentCalls?.some(call => call.id === id && !isAgentTool(call.tool ?? call.name)))) return;
762
813
  if (expandedTools.has(id)) {
763
814
  expandedTools.delete(id);
@@ -789,10 +840,17 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
789
840
  else expandedPrompts.set(index, question);
790
841
  };
791
842
  return {
843
+ dispose() { assistantImages?.dispose(); },
792
844
  invalidate() { clearHover(); },
845
+ resetProcessView() {
846
+ agentModes.clear(); expandedThinking.clear(); expandedTools.clear(); expandedSubagents.clear();
847
+ pinnedToolId = undefined; pinnedAgentIndex = undefined; pinnedSubagentId = undefined;
848
+ },
793
849
  clearHover,
794
850
  pinnedTool: () => pinnedTool,
795
851
  unpinTool: () => { pinnedToolId = undefined; pinnedTool = undefined; },
852
+ pinnedAgent: () => pinnedAgent,
853
+ unpinAgent: () => { pinnedAgentIndex = undefined; pinnedAgent = undefined; },
796
854
  pinnedSubagent: () => pinnedSubagent,
797
855
  unpinSubagent: () => { pinnedSubagentId = undefined; pinnedSubagent = undefined; },
798
856
  toolChoices: () => toolControls.map(control => ({ ...control, expanded: expandedTools.has(control.id) || expandedThinking.has(control.id) })),
@@ -820,6 +878,17 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
820
878
  }
821
879
  }
822
880
  if (event.button !== "left" || event.shift || event.ctrl || event.alt) return;
881
+ const agent = agentControls.find(control => event.y === control.y && event.x >= 0 && event.x < control.width);
882
+ if (agent && (event.clickCount ?? 1) === 1) {
883
+ if (event.type === "press") return { handled: true };
884
+ if (event.type === "click") {
885
+ const all = (agentModes.get(agent.index) ?? (isExpanded() ? "all" : "preview")) === "all";
886
+ agentModes.set(agent.index, all ? "preview" : "all");
887
+ if (all) { expandedThinking.clear(); expandedTools.clear(); expandedSubagents.clear(); }
888
+ pinnedAgentIndex = all ? undefined : agent.index;
889
+ return { handled: true, render: true };
890
+ }
891
+ }
823
892
  const control = promptControls.find(control => event.y === control.y && event.x >= control.x && event.x < control.x + control.width);
824
893
  if (control && (event.clickCount ?? 1) === 1) {
825
894
  if (event.type === "press") return { handled: true };
@@ -843,7 +912,9 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
843
912
  render(width: number, notices?: TurnNotices): string[] {
844
913
  promptControls = [];
845
914
  toolControls = [];
915
+ agentControls = [];
846
916
  pinnedTool = undefined;
917
+ pinnedAgent = undefined;
847
918
  pinnedSubagent = undefined;
848
919
  subagentControls = [];
849
920
  noticeRegions = [];
@@ -863,6 +934,7 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
863
934
  for (const [index, turn] of turns.entries()) {
864
935
  if (index > 0) lines.push("");
865
936
  if (expandedPrompts.has(index) && expandedPrompts.get(index) !== turn.question) expandedPrompts.delete(index);
937
+ const noticeRows = notices?.get(index) ?? [];
866
938
  const questionRows = markdown(turn.question, inner);
867
939
  const loopSummary = piLoopSummary(turn.question);
868
940
  const expanded = expandedPrompts.get(index) === turn.question;
@@ -885,7 +957,7 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
885
957
  const entries = turn.process.flatMap((entry, processIndex) => {
886
958
  if (entry.startsWith("call ")) {
887
959
  const call = turn.agentCalls?.find(call => call.id === entry.slice(5));
888
- if (call && isAgentTool(call.tool ?? call.name) && !isExpanded()) return [];
960
+ if (call && isAgentTool(call.tool ?? call.name)) return [];
889
961
  const display = call && agentCallDisplay(call);
890
962
  return call && display ? [{ title: `${isAgentTool(call.tool ?? call.name) ? "Control" : call.name} ${display.summary}`.trim(), detail: display.detail, state: call.state, id: call.id, thinking: false, processIndex, activeThinking: false }] : [];
891
963
  }
@@ -897,41 +969,62 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
897
969
  });
898
970
  // Older in-memory turns may predate call markers.
899
971
  for (const call of turn.agentCalls ?? []) {
900
- if (isAgentTool(call.tool ?? call.name) && !isExpanded()) continue;
972
+ if (isAgentTool(call.tool ?? call.name)) continue;
901
973
  const display = agentCallDisplay(call);
902
974
  if (!entries.some(entry => entry.id === call.id)) entries.push({ title: `${isAgentTool(call.tool ?? call.name) ? "Control" : call.name} ${display.summary}`, detail: display.detail, state: call.state, id: call.id, thinking: false, processIndex: -1, activeThinking: false });
903
975
  }
904
976
  const agentTurnControls: Array<{ runId: string; y: number; width: number; line: string }> = [];
905
977
  const agents = liveAgentView(turn.subAgents ?? [], theme, width, subAgentsExpanded(), true, agentDeadlines, Date.now(), expandedSubagents, agentTurnControls);
906
- if (entries.length || turn.running || turn.usage || agents.total) {
907
- const expanded = isExpanded();
908
- const latestThinking = !expanded ? [...entries].reverse().find(entry => entry.thinking) : undefined;
978
+ if (agents.total && !entries.length) entries.push({ title: `SubAgent ${agents.done + agents.errors}/${agents.total}`, detail: "", state: agents.running ? "running" : agents.errors ? "error" : "done", id: `agents:${index}`, thinking: false, processIndex: -1, activeThinking: false });
979
+ const active = !!turn.running || agents.running > 0 || entries.some(entry => entry.state === "running") || (turn.waitingTools?.length ?? 0) > 0;
980
+ if (active) runningTurns.add(index);
981
+ else if (runningTurns.delete(index)) {
982
+ // Return to the six-row preview once; a later click can expand everything again.
983
+ if (agentModes.get(index) === "all") {
984
+ agentModes.set(index, "preview");
985
+ expandedThinking.clear();
986
+ expandedTools.clear();
987
+ expandedSubagents.clear();
988
+ if (pinnedAgentIndex === index) pinnedAgentIndex = undefined;
989
+ }
990
+ }
991
+ if (entries.length || active || turn.usage || agents.total) {
992
+ const mode = agentModes.get(index) ?? (isExpanded() ? "all" : "preview");
993
+ const expanded = mode === "all";
909
994
  const busy = entries.some(entry => entry.state === "running") || (turn.waitingTools?.length ?? 0) > 0;
910
995
  const working = turn.running && !busy && !turn.final;
911
- const limit = expanded ? entries.length : Math.max(0, 6 - (working ? 1 : 0));
912
- const shown = expanded ? entries : entries.filter(entry => !entry.thinking || entry.state === "running" || entry === latestThinking || expandedThinking.has(entry.id)).slice(-limit);
913
- if (latestThinking && !shown.includes(latestThinking)) shown.splice(Math.min(shown.length, entries.indexOf(latestThinking)), 0, latestThinking);
996
+ // Six recent records stay visible while running and after completion.
997
+ const shown = mode === "closed" ? [] : expanded ? entries : entries.slice(-PROCESS_PREVIEW_ROWS);
914
998
  const done = entries.filter(entry => entry.state === "done").length;
915
- const progressHeader = theme.bold(theme.fg("text", "Agent")) + (entries.length ? theme.fg("muted", ` · ${done}/${entries.length}`) : "")
916
- + (agents.total ? theme.bold(theme.fg("text", " Subagent")) + theme.fg("muted", ` ${agents.done + agents.errors}/${agents.total}`)
917
- + (agents.errors ? theme.fg("error", ` · ${agents.errors} failed`) : "") : "");
918
- const header = progressHeader + theme.fg("muted", showShortcut(turn) ? " · Ctrl+O" : "");
999
+ // ponytail: two terminal text frames; use Pi's motion preference if it exposes one.
1000
+ const sparkle = active ? Math.floor(Date.now() / 360) % 2 ? "✧" : "✦" : "✦";
1001
+ const steps = entries.length
1002
+ ? theme.fg("muted", done === entries.length ? ` · 完成 共 ${entries.length} 步` : ` · 第 ${Math.min(entries.length, done + 1)} 步`)
1003
+ : "";
1004
+ const subagents = agents.total
1005
+ ? theme.fg("muted", " · ") + theme.bold(theme.fg("text", "子代理")) + theme.fg("muted", ` ${agents.done + agents.errors}/${agents.total}`)
1006
+ + (agents.errors ? theme.fg("error", ` · ${agents.errors} 失败`) : "")
1007
+ : "";
919
1008
  const usage = addUsage({ ...EMPTY_USAGE, ...turn.usage, cost: turn.usage?.cost ?? 0 }, turn.pendingUsage);
920
1009
  const hasUsage = usage.totalTokens > 0 || usage.cacheRead > 0;
921
1010
  const totals = hasUsage
922
- ? theme.fg("text", "S") + theme.fg("muted", ` ${formatTokens(usage.totalTokens)} / `)
923
- + theme.fg("text", "C") + theme.fg("muted", ` ${formatTokens(usage.cacheRead)}`)
1011
+ ? theme.fg("muted", "会话 ") + theme.bold(theme.fg("text", formatTokens(usage.totalTokens)))
1012
+ + theme.fg("muted", " · 缓存 ") + theme.bold(theme.fg("text", formatTokens(usage.cacheRead)))
924
1013
  : "";
925
- const totalsWidth = visibleWidth(totals);
926
- if (hasUsage && showUsage() && width >= totalsWidth + visibleWidth(agents.total ? progressHeader : "Agent") + 1) {
927
- const left = truncateToWidth(header, width - totalsWidth - 1, "");
928
- lines.push("", left + " ".repeat(width - visibleWidth(left) - totalsWidth) + totals);
929
- } else {
930
- lines.push("", truncateToWidth(header, width));
931
- }
1014
+ const recordCount = entries.filter(entry => !entry.title.startsWith("SubAgent ")).length || agents.total;
1015
+ const progressHeader = theme.fg(active ? "accent" : "muted", sparkle + " ") + theme.bold(theme.fg("text", "Agent")) + theme.fg("muted", recordCount ? ` · ${recordCount}` : "");
1016
+ const showAgentRows = mode !== "closed" && expanded;
1017
+ const caret = theme.fg("muted", expanded ? " ▾" : " ▸");
1018
+ const elapsedHeader = turn.startedAt == null ? "" : theme.fg("muted", " · ") + theme.fg(active ? "success" : "muted", formatElapsed(turn.startedAt, turn.endedAt ?? Date.now()));
1019
+ const left = progressHeader + elapsedHeader + caret;
1020
+ const showTotals = hasUsage && showUsage() && visibleWidth(left) + 2 + visibleWidth(totals) <= width;
1021
+ agentControls.push({ index, y: lines.length + 1, width: Math.min(width, visibleWidth(left)) });
1022
+ if (expanded && pinnedAgentIndex === index) pinnedAgent = { index, y: lines.length + 1, line: truncateToWidth(left, width) };
1023
+ lines.push("", showTotals
1024
+ ? left + " ".repeat(width - visibleWidth(left) - visibleWidth(totals)) + totals
1025
+ : truncateToWidth(left, width));
932
1026
  shown.forEach((entry, row) => {
933
- const waiting = turn.waitingTools?.find(tool => tool.id === entry.id);
934
- const title = waiting && !entry.title.startsWith("Control ") ? `${waiting.name} running · waiting ${Math.max(0, Math.floor((Date.now() - waiting.startedAt) / 1000))}s` : entry.title;
1027
+ const title = entry.title;
935
1028
  const text = title.split(/\r?\n/).find(line => line.trim())?.replace(/\s+/g, " ").trim() ?? "";
936
1029
  const split = text.indexOf(" ");
937
1030
  const label = split < 0 ? text : text.slice(0, split);
@@ -940,10 +1033,12 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
940
1033
  const elapsed = entry.thinking ? formatThinkingElapsed(turn, entry.processIndex, activeThinking) : "";
941
1034
  const thinkingElapsed = elapsed ? theme.fg(activeThinking ? "success" : "muted", ` ${elapsed}`) : "";
942
1035
  const call = turn.agentCalls?.find(call => call.id === entry.id && !isAgentTool(call.tool ?? call.name));
943
- const controlId = call?.id ?? (entry.thinking ? entry.id : "");
1036
+ const controlId = call?.id ?? (entry.thinking || entry.id.startsWith("agents:") ? entry.id : "");
944
1037
  const open = call ? expandedTools.has(call.id) : entry.thinking && expandedThinking.has(entry.id);
945
1038
  const identity = open || activeThinking ? "accent" : "text";
946
- const summary = theme.fg(identity, theme.bold(label)) + thinkingElapsed + " ";
1039
+ const duration = call ? formatToolElapsed(call.startedAt, call.endedAt ?? Date.now()) : "";
1040
+ const toolElapsed = duration ? theme.fg(call?.state === "running" ? "accent" : "muted", ` ${duration}`) : "";
1041
+ const summary = theme.fg(identity, theme.bold(label)) + thinkingElapsed + toolElapsed + " ";
947
1042
  if (controlId && width >= 4) toolControls.push({ id: controlId, y: lines.length, width, title: text });
948
1043
  if (hoveredTool?.id === controlId && (hoveredTool.y !== lines.length || hoveredTool.width !== width)) clearHover();
949
1044
  const status = entry.state === "error" ? "✕" : entry.state === "running" ? runningGlyph() : "●";
@@ -951,17 +1046,30 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
951
1046
  const keepStatus = entry.state === "running" || (open && entry.state === "error");
952
1047
  const glyph = arrow ? (open ? "▼" : "▶") + (keepStatus ? ` ${status}` : "") : status;
953
1048
  const glyphColor = entry.state === "error" ? "error" : entry.state === "running" || arrow ? "accent" : "muted";
954
- const last = row === shown.length - 1 && !working && !agents.rows.length;
955
- const prefix = theme.fg(open ? "accent" : "dim", last ? "└─ " : "├─ ") + theme.fg(glyphColor, glyph) + " " + summary;
1049
+ const last = row === shown.length - 1 && !working && (!showAgentRows || !agents.rows.length);
1050
+ const prefix = theme.fg(open ? "accent" : "dim", "│ ") + (entry.state === "running" || entry.state === "error" || arrow ? theme.fg(glyphColor, glyph) + " " : "") + summary;
956
1051
  if (label === "Output") {
957
1052
  // Wrapped output hangs under the body column and keeps the tree rail to the next sibling.
958
1053
  const indent = visibleWidth(prefix);
959
- const wrapped = markdown(body, Math.max(1, width - indent), true);
960
1054
  const rail = !last && indent > 0 ? theme.fg("dim", "\u2502") + " ".repeat(indent - 1) : " ".repeat(indent);
1055
+ const wrapped = markdown(body, Math.max(1, width - indent), true);
961
1056
  lines.push(truncateToWidth(prefix + (wrapped[0] ?? ""), width, ""));
962
1057
  for (const extra of wrapped.slice(1)) lines.push(truncateToWidth(rail + extra, width, ""));
963
1058
  } else {
964
- lines.push(bandHeading(truncateToWidth(prefix + (entry.thinking ? markdown(body, Math.max(1, visibleWidth(body) + 1), true).join(" ").replace(/\s+/g, " ").trim() : theme.fg(open ? "accent" : "muted", body)), width, controlId ? "" : "…"), open));
1059
+ const displayBody = placeholderText(activeThinking ? stripVTControlCharacters(entry.detail).replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ").trim() : body);
1060
+ const compactBody = entry.thinking ? displayBody
1061
+ : linkToolFiles(displayBody, imageOptions?.cwd() ?? process.cwd(), !open);
1062
+ const available = Math.max(0, width - visibleWidth(prefix));
1063
+ const fittedBody = visibleWidth(compactBody) > available && (activeThinking || (!entry.thinking && !open)) && available > 1
1064
+ ? "…" + sliceByColumn(compactBody, visibleWidth(compactBody) - available + 1, available - 1, true)
1065
+ : truncateToWidth(compactBody, available, "…");
1066
+ const styledBody = activeThinking
1067
+ ? theme.fg("accent", fittedBody)
1068
+ : entry.thinking
1069
+ ? markdown(fittedBody, Math.max(1, visibleWidth(fittedBody) + 1), true).join(" ").replace(/\s+/g, " ").trim()
1070
+ // sliceByColumn may end before OSC 8's closing sequence.
1071
+ : theme.fg(open ? "accent" : "muted", fittedBody + "\x1b]8;;\x07");
1072
+ lines.push(bandHeading(truncateToWidth(prefix + styledBody, width, "…"), open));
965
1073
  }
966
1074
  if (open && call && call.id === pinnedToolId) pinnedTool = { id: call.id, y: lines.length - 1, line: lines.at(-1)! };
967
1075
  if (open && call) {
@@ -983,22 +1091,23 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
983
1091
  if (details.length > 5) lines.push(truncateToWidth(rail + theme.fg("muted", `… +${details.length - 5} lines`), width));
984
1092
  }
985
1093
  });
986
- const agentStartY = lines.length;
987
- for (const c of agentTurnControls) {
988
- const control = { ...c, y: agentStartY + c.y };
989
- subagentControls.push(control);
990
- if (c.runId === pinnedSubagentId) pinnedSubagent = { id: c.runId, y: control.y, line: c.line, autoScroll: false };
1094
+ if (showAgentRows) {
1095
+ const agentStartY = lines.length;
1096
+ for (const c of agentTurnControls) {
1097
+ const control = { ...c, y: agentStartY + c.y };
1098
+ subagentControls.push(control);
1099
+ if (c.runId === pinnedSubagentId) pinnedSubagent = { id: c.runId, y: control.y, line: c.line, autoScroll: false };
1100
+ }
1101
+ lines.push(...agents.rows);
991
1102
  }
992
- lines.push(...agents.rows);
993
- if (working) {
1103
+ if (working && (expanded || !shown.length)) {
994
1104
  const label = turn.awaitingResponse && !shown.length ? "Thinking" : "Working";
995
- const prefix = theme.fg("dim", "└─ ") + theme.fg("accent", `${runningGlyph()} `) + theme.fg("text", theme.bold(label)) + theme.fg("success", ` ${formatElapsed(turn.startedAt)}`) + " ";
1105
+ const prefix = theme.fg("dim", "└─ ") + theme.fg("accent", `${runningGlyph()} `) + theme.fg("text", theme.bold(label)) + " ";
996
1106
  lines.push(truncateToWidth(prefix + theme.fg("text", "…"), width, ""));
997
1107
  }
998
1108
  }
999
- for (const reply of turn.replies ?? []) lines.push("", ...markdown(reply, width));
1000
- if (turn.final) lines.push("", ...markdown(turn.final, width));
1001
- const noticeRows = notices?.get(index) ?? [];
1109
+ for (const [replyIndex, reply] of (turn.replies ?? []).entries()) lines.push("", ...assistantMarkdown(reply, width, `reply:${index}:${replyIndex}`));
1110
+ if (turn.final) lines.push("", ...assistantMarkdown(turn.final, width, `final:${index}`));
1002
1111
  noticeRegions.push({ y: lines.length, rows: noticeRows });
1003
1112
  lines.push(...noticeRows);
1004
1113
  }
@@ -1015,6 +1124,8 @@ export default function (pi: ExtensionAPI) {
1015
1124
  attachFooterTidy(pi);
1016
1125
  attachTitlePlain(pi);
1017
1126
  let refreshFooter: (() => void) | undefined;
1127
+ let restoreScrollbar: (() => void) | undefined;
1128
+ let scrollbarRoot: unknown;
1018
1129
  let refreshMinimal: (() => void) | undefined;
1019
1130
  let processExpanded = false;
1020
1131
  let nativeOutput = false;
@@ -1066,6 +1177,7 @@ export default function (pi: ExtensionAPI) {
1066
1177
  restoreTranscript = undefined;
1067
1178
  restoreAgentWidgets?.();
1068
1179
  restoreAgentWidgets = undefined;
1180
+ promptView?.dispose();
1069
1181
  promptView = undefined;
1070
1182
  if (settings["pi-mini-mode-minimal-show"] && ctx.mode === "tui") unsubscribeMinimalInput = ctx.ui.onTerminalInput?.((data) => {
1071
1183
  const nativeKey = matchesKey(data, "ctrl+alt+o");
@@ -1078,7 +1190,10 @@ export default function (pi: ExtensionAPI) {
1078
1190
  nativeOutput = !nativeOutput;
1079
1191
  mountMinimalOutput(ctx);
1080
1192
  } else if (subAgentKey) subAgentsExpanded = !subAgentsExpanded;
1081
- else processExpanded = !processExpanded;
1193
+ else {
1194
+ processExpanded = !processExpanded;
1195
+ promptView?.resetProcessView();
1196
+ }
1082
1197
  refreshMinimalOutput();
1083
1198
  return { consume: true };
1084
1199
  });
@@ -1133,7 +1248,11 @@ export default function (pi: ExtensionAPI) {
1133
1248
  return { ...turn, subAgents: withNotices };
1134
1249
  });
1135
1250
  };
1136
- 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);
1251
+ 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, {
1252
+ cwd: () => ctx.cwd,
1253
+ requestRender: () => tui.requestRender(),
1254
+ write: data => tui.terminal.write(data),
1255
+ });
1137
1256
  const hintRemaining = (activeMinimalTurn?.shortcutHintUntil ?? 0) - Date.now();
1138
1257
  if (hintRemaining > 0) {
1139
1258
  shortcutTimer = setTimeout(() => tui.requestRender(), hintRemaining);
@@ -1142,6 +1261,9 @@ export default function (pi: ExtensionAPI) {
1142
1261
  // Native info notifications use dim; warning/error notifications retain
1143
1262
  // their position in the transcript. No plugin names or message matching.
1144
1263
  const dimPrefix = theme.fg("dim", "\u0000").split("\u0000")[0];
1264
+ // Startup model diagnostics are reprinted into the resource header by /new and /reload.
1265
+ // Read the live predicate on every frame: the header is replaced after this factory returns.
1266
+ const hideStartupLine = (line: string) => line.replace(/\x1b\[[0-9;]*m/g, "").includes("No models match pattern");
1145
1267
  // Transcript hover wrappers must surround the compact widget handlers;
1146
1268
  // unmount in reverse order so neither adapter resurrects stale handlers.
1147
1269
  restoreAgentWidgets = attachAgentWidgets(tui, theme, () => subAgentsExpanded, undefined, true);
@@ -1178,6 +1300,7 @@ export default function (pi: ExtensionAPI) {
1178
1300
  },
1179
1301
  isPrompt: text => !!activeUIPrompt && (!activeUIPrompt.title || text.includes(activeUIPrompt.title)),
1180
1302
  isTransient: text => !!dimPrefix && text.startsWith(dimPrefix),
1303
+ hideStartupLine,
1181
1304
  });
1182
1305
  lastAttachMode = typeof tui.mode === "string" ? tui.mode : undefined;
1183
1306
  if (!restoreTranscript) {
@@ -1199,7 +1322,7 @@ export default function (pi: ExtensionAPI) {
1199
1322
  saveStatuses();
1200
1323
  lastStatusRead = Date.now();
1201
1324
  }
1202
- if (changed || Date.now() >= view.agentExpiry() || activeMinimalTurn?.running || statuses.some(status => /^(running|active|starting|queued|pending)$/.test(String(status.state)))) tui.requestRender();
1325
+ if (changed || Date.now() >= view.agentExpiry() || activeMinimalTurn?.running || agentChildren(statuses).some(child => /^(running|active|starting|queued|pending)$/.test(String(child.status ?? child.state)))) tui.requestRender();
1203
1326
  }, 100);
1204
1327
  waitingTimer.unref();
1205
1328
  }
@@ -1383,11 +1506,22 @@ export default function (pi: ExtensionAPI) {
1383
1506
  minimalToolOutputIndices.clear();
1384
1507
  mountMinimalOutput(ctx);
1385
1508
  ctx.ui.setFooter((tui, theme, footerData) => {
1509
+ restoreScrollbar?.();
1510
+ scrollbarRoot = undefined;
1511
+ const syncScrollbar = () => {
1512
+ const root = (tui as typeof tui & { layoutRoot?: unknown }).layoutRoot;
1513
+ if (root === scrollbarRoot) return;
1514
+ restoreScrollbar?.();
1515
+ scrollbarRoot = root;
1516
+ restoreScrollbar = installSeamlessScrollbar(tui, theme);
1517
+ };
1518
+ syncScrollbar();
1386
1519
  refreshFooter = () => tui.requestRender();
1387
1520
  return {
1388
1521
  dispose: footerData?.onBranchChange?.(() => tui.requestRender()),
1389
1522
  invalidate() {},
1390
1523
  render(width: number): string[] {
1524
+ syncScrollbar();
1391
1525
  // switchTuiMode does not re-run setWidget; remount once the live renderer is fullscreen.
1392
1526
  if (settings["pi-mini-mode-minimal-show"] && !nativeOutput && ctx.mode === "tui" && !restoreTranscript
1393
1527
  && tui.mode !== "regular" && lastAttachMode === "regular" && !remountQueued) {
@@ -1435,8 +1569,15 @@ export default function (pi: ExtensionAPI) {
1435
1569
  });
1436
1570
  pi.on("model_select", refresh);
1437
1571
  pi.on("thinking_level_select", refresh);
1438
- const writeThinkingLine = (turn: MinimalTurn, blockIndex: number, line: string): number => {
1439
- const existing = minimalMessageIndices.get(blockIndex);
1572
+ const writeThinkingLine = (turn: MinimalTurn, content: Array<Record<string, unknown>>, blockIndex: number, line: string): number => {
1573
+ let existing = minimalMessageIndices.get(blockIndex);
1574
+ if (continuesEmptyThinking(content, blockIndex)) {
1575
+ existing = minimalMessageIndices.get(blockIndex - 1);
1576
+ if (existing !== undefined) minimalMessageIndices.set(blockIndex, existing);
1577
+ } else if (existing !== undefined && [...minimalMessageIndices].some(([block, index]) => block < blockIndex && index === existing)) {
1578
+ // A provisional empty block can acquire its own body on a later update.
1579
+ existing = undefined;
1580
+ }
1440
1581
  if (existing === undefined) {
1441
1582
  const index = turn.process.length;
1442
1583
  minimalMessageIndices.set(blockIndex, index);
@@ -1455,6 +1596,7 @@ export default function (pi: ExtensionAPI) {
1455
1596
  activeMinimalTurn.final = pendingMinimalFinal;
1456
1597
  activeMinimalTurn.running = false;
1457
1598
  activeMinimalTurn.thinking = undefined;
1599
+ promptView?.resetProcessView();
1458
1600
  }
1459
1601
  const question = contentText(event.message.content) || "[Attachment]";
1460
1602
  processExpanded = false;
@@ -1471,6 +1613,10 @@ export default function (pi: ExtensionAPI) {
1471
1613
  }
1472
1614
  if (event.message.role !== "assistant") return;
1473
1615
  // Background completions can start a new assistant turn without a user message.
1616
+ if (!activeMinimalTurn?.running) {
1617
+ processExpanded = false;
1618
+ promptView?.resetProcessView();
1619
+ }
1474
1620
  activeMinimalTurn ??= minimalTurns.at(-1);
1475
1621
  if (activeMinimalTurn) {
1476
1622
  freezeThinkingClock(activeMinimalTurn, activeMinimalTurn.thinking);
@@ -1497,14 +1643,17 @@ export default function (pi: ExtensionAPI) {
1497
1643
  if (partial.content.length) activeMinimalTurn.awaitingResponse = false;
1498
1644
  for (const [blockIndex, item] of partial.content.entries()) {
1499
1645
  if (item.type !== "thinking") continue;
1500
- const line = `thinking ${processText(item.thinking ?? item.text)}`;
1501
- const index = writeThinkingLine(activeMinimalTurn, blockIndex, line);
1646
+ const line = `thinking ${thinkingText(item)}`;
1647
+ const index = writeThinkingLine(activeMinimalTurn, partial.content, blockIndex, line);
1502
1648
  if (blockIndex === partial.content.length - 1 && event.assistantMessageEvent.type !== "thinking_end") {
1503
1649
  activeMinimalTurn.thinking = index;
1504
- } else {
1505
- freezeThinkingClock(activeMinimalTurn, index);
1506
1650
  }
1507
1651
  }
1652
+ for (const index of new Set(minimalMessageIndices.values())) {
1653
+ if (index === activeMinimalTurn.thinking) {
1654
+ delete ensureThinkingClock(activeMinimalTurn, index).endedAt;
1655
+ } else freezeThinkingClock(activeMinimalTurn, index);
1656
+ }
1508
1657
  if (previousThinking !== undefined && previousThinking !== activeMinimalTurn.thinking) {
1509
1658
  freezeThinkingClock(activeMinimalTurn, previousThinking);
1510
1659
  }
@@ -1550,9 +1699,9 @@ export default function (pi: ExtensionAPI) {
1550
1699
  if (activeMinimalTurn && Array.isArray(content)) {
1551
1700
  for (const [blockIndex, item] of (content as Array<Record<string, unknown>>).entries()) {
1552
1701
  if (item.type !== "thinking" && !(item.type === "text" && content.some((block) => block.type === "toolCall"))) continue;
1553
- const line = `${item.type === "thinking" ? "thinking" : "output"} ${processText(item.thinking ?? item.text)}`;
1702
+ const line = `${item.type === "thinking" ? "thinking" : "output"} ${item.type === "thinking" ? thinkingText(item) : processText(item.text)}`;
1554
1703
  if (item.type === "thinking") {
1555
- freezeThinkingClock(activeMinimalTurn, writeThinkingLine(activeMinimalTurn, blockIndex, line));
1704
+ freezeThinkingClock(activeMinimalTurn, writeThinkingLine(activeMinimalTurn, content, blockIndex, line));
1556
1705
  continue;
1557
1706
  }
1558
1707
  const index = minimalMessageIndices.get(blockIndex);
@@ -1578,7 +1727,7 @@ export default function (pi: ExtensionAPI) {
1578
1727
  freezeThinkingClock(activeMinimalTurn, activeMinimalTurn.thinking);
1579
1728
  activeMinimalTurn.thinking = undefined;
1580
1729
  activeMinimalTurn.awaitingResponse = false;
1581
- (activeMinimalTurn.agentCalls ??= []).push(agentCall(event.toolCallId, event.toolName, event.args));
1730
+ (activeMinimalTurn.agentCalls ??= []).push({ ...agentCall(event.toolCallId, event.toolName, event.args), startedAt: toolStarts.get(event.toolCallId) });
1582
1731
  pushProcess(activeMinimalTurn, "call", event.toolCallId);
1583
1732
  (activeMinimalTurn.waitingTools ??= []).push({ id: event.toolCallId, name: event.toolName, startedAt: Date.now() });
1584
1733
  }
@@ -1620,6 +1769,7 @@ export default function (pi: ExtensionAPI) {
1620
1769
  const call = activeMinimalTurn?.agentCalls?.find(call => call.id === event.toolCallId);
1621
1770
  if (call) {
1622
1771
  if (activeMinimalTurn) activeMinimalTurn.waitingTools = activeMinimalTurn.waitingTools?.filter(tool => tool.id !== event.toolCallId);
1772
+ call.endedAt = Date.now();
1623
1773
  call.state = event.isError ? "error" : "done";
1624
1774
  call.output = contentText(event.result) || (event.isError ? "Call failed (no text details)" : "Call returned (background task status below)");
1625
1775
  refresh();
@@ -1644,16 +1794,23 @@ export default function (pi: ExtensionAPI) {
1644
1794
  if (!activeMinimalTurn) return;
1645
1795
  for (const turn of minimalTurns) {
1646
1796
  freezeOpenThinkingClocks(turn);
1797
+ if (turn.running) turn.endedAt = Date.now();
1647
1798
  turn.running = false;
1648
1799
  turn.thinking = undefined;
1649
1800
  }
1650
1801
  activeMinimalTurn.final = pendingMinimalFinal;
1802
+ processExpanded = false;
1803
+ subAgentsExpanded = false;
1804
+ promptView?.resetProcessView();
1651
1805
  activeMinimalTurn = undefined;
1652
1806
  pendingMinimalFinal = "";
1653
1807
  minimalToolOutputIndices.clear();
1654
1808
  refreshMinimalOutput();
1655
1809
  });
1656
1810
  pi.on("session_shutdown", () => {
1811
+ restoreScrollbar?.();
1812
+ restoreScrollbar = undefined;
1813
+ scrollbarRoot = undefined;
1657
1814
  // In-flight startup checks this generation before installing its server.
1658
1815
  settingsWebGeneration++;
1659
1816
  settingsWeb?.close();
@@ -1664,6 +1821,7 @@ export default function (pi: ExtensionAPI) {
1664
1821
  persistAgentStatuses?.();
1665
1822
  persistAgentStatuses = undefined;
1666
1823
  agentDeadlines.clear();
1824
+ promptView?.dispose();
1667
1825
  promptView = undefined;
1668
1826
  if (shortcutTimer) clearTimeout(shortcutTimer);
1669
1827
  shortcutTimer = undefined;
package/lib/agent-view.ts CHANGED
@@ -18,6 +18,8 @@ export interface AgentCall {
18
18
  action?: string;
19
19
  state: "running" | "done" | "error";
20
20
  output?: string;
21
+ startedAt?: number;
22
+ endedAt?: number;
21
23
  }
22
24
  export function agentCallDisplay(call: AgentCall): { summary: string; detail: string } {
23
25
  if (isAgentTool(call.tool ?? call.name)) return {
@@ -0,0 +1,99 @@
1
+ import { Image, Marked, deleteKittyImage, type Component } from "@earendil-works/pi-tui";
2
+ import { fileURLToPath } from "node:url";
3
+ import { existsSync } from "node:fs";
4
+ import { fileLink, localPath } from "./file-links.ts";
5
+ import { imagePathsInLine, readPreview } from "./input-enhancements.ts";
6
+ import { commitImageCursor } from "./image-placement.ts";
7
+
8
+ const parser = new Marked();
9
+ export interface AssistantImageSpan { start: number; end: number; path: string }
10
+
11
+ /** Parse image syntax before bare paths, retaining source offsets for placement. */
12
+ export function assistantImageSpans(source: string, cwd: string): AssistantImageSpan[] {
13
+ const spans: AssistantImageSpan[] = [];
14
+ let cursor = 0;
15
+ let offset = 0;
16
+ const code: Array<[number, number]> = [];
17
+ const tokens = parser.lexer(source);
18
+ for (const token of tokens) {
19
+ if (token.type === "code") code.push([offset, offset + token.raw.length]);
20
+ offset += token.raw.length;
21
+ }
22
+ const inCode = (start: number, end: number) => code.some(([from, to]) => start < to && end > from);
23
+ parser.walkTokens(tokens, token => {
24
+ if (token.type !== "image") return;
25
+ let start = source.indexOf(token.raw, cursor);
26
+ while (start >= 0 && inCode(start, start + token.raw.length)) start = source.indexOf(token.raw, start + token.raw.length);
27
+ if (start < 0) return;
28
+ cursor = start + token.raw.length;
29
+ let path = token.href;
30
+ try {
31
+ if (path.startsWith("file:")) path = fileURLToPath(path);
32
+ else if (/^[a-z][\w+.-]*:|^\/\//i.test(path)) return;
33
+ path = localPath(path, cwd);
34
+ } catch { return; }
35
+ if (/\.(?:png|jpe?g|gif|webp)$/i.test(path)) spans.push({ start, end: cursor, path });
36
+ });
37
+ // The path parser excludes fenced code and handles shell-escaped spaces.
38
+ for (const match of imagePathsInLine(source)) {
39
+ if (!inCode(match.start, match.end) && !spans.some(span => match.start < span.end && match.end > span.start)) {
40
+ spans.push({ start: match.start, end: match.end, path: localPath(match.path, cwd) });
41
+ }
42
+ }
43
+ return spans.filter(span => existsSync(span.path)).sort((a, b) => a.start - b.start);
44
+ }
45
+
46
+ /** User messages and tool steps expose one linked chip without reserving image height. */
47
+ export function imagePlaceholders(source: string, cwd: string): string {
48
+ const spans = assistantImageSpans(source, cwd);
49
+ for (let index = spans.length - 1; index >= 0; index--) {
50
+ const span = spans[index];
51
+ source = source.slice(0, span.start) + fileLink(` 图片 ${index + 1}`, span.path, false) + source.slice(span.end);
52
+ }
53
+ return source;
54
+ }
55
+
56
+ /** Load once outside render, then reuse Pi's Image IDs and complete height rows. */
57
+ export function createAssistantImages(cwd: () => string, requestRender: () => void, write: (data: string) => void = () => {}) {
58
+ const cache = new Map<string, { image?: Component & { getImageId?(): number | undefined }; pending?: Promise<void> }>();
59
+ let disposed = false;
60
+ return {
61
+ render(source: string, width: number, markdown: (text: string, width: number) => string[], owner = source): string[] {
62
+ const spans = assistantImageSpans(source, cwd());
63
+ if (!spans.length) return markdown(source, width);
64
+ const rows: string[] = [];
65
+ let cursor = 0;
66
+ for (const span of spans) {
67
+ const before = source.slice(cursor, span.start).trim();
68
+ if (before) rows.push(...markdown(before, width));
69
+ const key = JSON.stringify([owner, span.start, span.path]);
70
+ let entry = cache.get(key);
71
+ if (!entry) {
72
+ entry = {};
73
+ cache.set(key, entry);
74
+ const target = entry;
75
+ target.pending = readPreview(span.path, cwd()).then(preview => {
76
+ if (disposed) return;
77
+ if (preview?.kind === "image") target.image = new Image(preview.base64, preview.mimeType, { fallbackColor: text => text }, { filename: span.path });
78
+ target.pending = undefined;
79
+ requestRender();
80
+ }).catch(() => { target.pending = undefined; });
81
+ }
82
+ if (entry.image) rows.push(...entry.image.render(width).map(commitImageCursor));
83
+ else rows.push(...markdown(source.slice(span.start, span.end).startsWith("![") ? span.path : source.slice(span.start, span.end), width));
84
+ cursor = span.end;
85
+ }
86
+ const after = source.slice(cursor).trim();
87
+ if (after) rows.push(...markdown(after, width));
88
+ return rows;
89
+ },
90
+ dispose() {
91
+ disposed = true;
92
+ for (const entry of cache.values()) {
93
+ const id = entry.image?.getImageId?.();
94
+ if (id !== undefined) write(deleteKittyImage(id));
95
+ }
96
+ cache.clear();
97
+ },
98
+ };
99
+ }
package/lib/file-links.ts CHANGED
@@ -65,6 +65,26 @@ export function filePaths(text: string) {
65
65
  // BEL survives Markdown's backslash-escape parsing, unlike the ST terminator.
66
66
  export const fileLink = (text: string, path: string, underline = true) => `\x1b]8;;${pathToFileURL(path).href}\x07${underline ? `\x1b[4m${text}\x1b[24m` : text}\x1b]8;;\x07`;
67
67
 
68
+ /** Shorten only visible tool labels; OSC 8 targets retain the complete original path. */
69
+ export function linkToolFiles(text: string, cwd: string, compact: boolean): string {
70
+ const shorten = (label: string) => compact ? label
71
+ .replace(/\/var\/folders\/[^\s]*\/otty-paste\//g, "…/otty-paste/")
72
+ .replace(/node_modules\/@earendil-works\//g, "…/") : label;
73
+ if (!inputCapabilities().hyperlinks) return shorten(text);
74
+ // A path tool's entire argument can contain spaces or punctuation without quotes.
75
+ const matches = text && !/[\x00-\x1f\x7f]/.test(text) && existsSync(localPath(text, cwd))
76
+ ? [{ path: text, start: 0, end: text.length }] : filePaths(text);
77
+ let result = "", offset = 0;
78
+ for (const match of matches) {
79
+ const path = localPath(match.path, cwd);
80
+ result += shorten(text.slice(offset, match.start));
81
+ const label = shorten(text.slice(match.start, match.end));
82
+ result += existsSync(path) ? fileLink(label, path) : label;
83
+ offset = match.end;
84
+ }
85
+ return result + shorten(text.slice(offset));
86
+ }
87
+
68
88
  /** Display-only: normalize local targets without changing persisted messages or remote URLs. */
69
89
  export function linkMessageFiles(text: string, cwd: string): string {
70
90
  if (!inputCapabilities().hyperlinks) return text;
@@ -0,0 +1,42 @@
1
+ /** Use the same cursor-commit workaround as Otty's hover/draft previews:
2
+ * end DEC 2026 before Kitty APCs so placement cannot use a buffered cursor.
3
+ * Resume Pi's frame afterwards, preserving the sequence and metadata ID. */
4
+ function directOtty(): boolean {
5
+ return process.env.TERM_PROGRAM?.toLowerCase() === "otty"
6
+ && !process.env.TMUX && !process.env.STY && !/^(tmux|screen)/i.test(process.env.TERM ?? "");
7
+ }
8
+
9
+ export function commitImageCursor(line: string): string {
10
+ if (!directOtty()) return line;
11
+ const start = line.indexOf("\x1b_G");
12
+ if (start < 0) return line;
13
+ const last = line.lastIndexOf("\x1b_G");
14
+ const end = line.indexOf("\x1b\\", last);
15
+ if (end < 0) return line;
16
+ // The protocol chunks must stay contiguous for Pi's placement cache parser.
17
+ return line.slice(0, start) + "\x1b[?2026l\x1b[0m" + line.slice(start, end + 2)
18
+ + "\x1b[?2026h\x1b[0m" + line.slice(end + 2);
19
+ }
20
+
21
+ /** Pi's fullscreen cache replaces uploads with placement-only commands on scroll.
22
+ * Otty can lose these placements after clearing the previous frame. Retain Pi's
23
+ * cache bookkeeping/eviction, but send the original (possibly cropped) upload.
24
+ * This private adapter is restricted to direct Otty and restored on unmount. */
25
+ export function attachImageRedraw(tui: unknown): (() => void) | undefined {
26
+ if (!directOtty()) return;
27
+ type Prepared = { lines: string[]; evictedImageDeletion: string };
28
+ const host = tui as { mode?: string; prepareKittyScreen?(screen: string[]): Prepared };
29
+ if (host.mode !== "fullscreen" || typeof host.prepareKittyScreen !== "function") return;
30
+ const original = host.prepareKittyScreen;
31
+ const descriptor = Object.getOwnPropertyDescriptor(host, "prepareKittyScreen");
32
+ const prepare = (screen: string[]): Prepared => {
33
+ const result = original.call(host, screen);
34
+ return directOtty() ? { ...result, lines: screen } : result;
35
+ };
36
+ host.prepareKittyScreen = prepare;
37
+ return () => {
38
+ if (host.prepareKittyScreen !== prepare) return;
39
+ if (descriptor) Object.defineProperty(host, "prepareKittyScreen", descriptor);
40
+ else delete host.prepareKittyScreen;
41
+ };
42
+ }
@@ -0,0 +1,14 @@
1
+ import { ScrollView } from "@earendil-works/pi-tui";
2
+ import type { Theme } from "@earendil-works/pi-coding-agent";
3
+
4
+ export function installSeamlessScrollbar(tui: unknown, theme: Theme): (() => void) | undefined {
5
+ const host = tui as { mode?: string; layoutRoot?: { children?: unknown[] } };
6
+ // ponytail: Pi's fullscreen root owns the scroll view; use its public scrollbar style until Pi exposes a scrollbar renderer hook.
7
+ const view = host.mode !== "regular" ? host.layoutRoot?.children?.[0] : undefined;
8
+ if (!(view instanceof ScrollView)) return;
9
+ const scrollbar = view as { scrollbarThumbStyle: (text: string) => string };
10
+ const original = scrollbar.scrollbarThumbStyle;
11
+ // Reverse-video space paints the full cell, avoiding glyph seams between terminal rows.
12
+ scrollbar.scrollbarThumbStyle = () => theme.fg("scrollbarThumb", "\x1b[7m \x1b[27m");
13
+ return () => { scrollbar.scrollbarThumbStyle = original; };
14
+ }
@@ -3,6 +3,7 @@ import { getMarkdownTheme, type ExtensionContext } from "@earendil-works/pi-codi
3
3
  import { diagramMarkdown, isMarkdownProse, renderMinimalMarkdown } from "./minimal-markdown.ts";
4
4
  import { stripVTControlCharacters } from "node:util";
5
5
  import { attachStickyTool } from "./sticky-tool.ts";
6
+ import { attachImageRedraw } from "./image-placement.ts";
6
7
 
7
8
  const record = (value: unknown): Record<string, unknown> | undefined => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
8
9
  const clean = (text: string) => stripVTControlCharacters(text).replace(/[\x00-\x1f\x7f]/g, " ").replace(/\s+/g, " ").trim();
@@ -302,7 +303,10 @@ function supervisorEnvelope(child: Component): unknown {
302
303
  }
303
304
 
304
305
  /** Pi 0.85.x private layout adapter. Never mutates the stored messages or child tree. */
305
- export type NoticeRows = string[] & { handleMouse?: Component["handleMouse"] };
306
+ export type NoticeRows = string[] & {
307
+ handleMouse?: Component["handleMouse"];
308
+
309
+ };
306
310
  export type TurnNotices = ReadonlyMap<number, NoticeRows>;
307
311
 
308
312
  /** Pi writes one warning line per miss (`Cache miss…: N tokens re-billed`). */
@@ -326,6 +330,8 @@ interface TranscriptView extends Component {
326
330
  pinnedTool?(): { id: string; y: number; line: string } | undefined;
327
331
  unpinTool?(): void;
328
332
  toggleTool?(id: string): void;
333
+ pinnedAgent?(): { index: number; y: number; line: string } | undefined;
334
+ unpinAgent?(): void;
329
335
  pinnedSubagent?(): { id: string; y: number; line: string; autoScroll?: boolean } | undefined;
330
336
  unpinSubagent?(): void;
331
337
  toggleSubagent?(id: string): void;
@@ -341,6 +347,8 @@ interface NoticeOptions {
341
347
  /** Blocking extension prompts are native UI, never auto-expiring notices. */
342
348
  isPrompt?: (text: string) => boolean;
343
349
  isTransient?: (text: string) => boolean;
350
+ /** Drop individual startup diagnostic lines, such as an unmatched model pattern. */
351
+ hideStartupLine?: (line: string) => boolean;
344
352
  /** When false, Pi's per-turn cache-miss lines stay in the transcript. Default: fold them. */
345
353
  foldCacheMiss?: () => boolean;
346
354
  now?: () => number;
@@ -360,6 +368,7 @@ export function attachTranscript(tui: unknown, view: TranscriptView, options: No
360
368
  const document = host.children[0] as ContainerLike;
361
369
  if (document.children.length !== 3 || !document.children.every(isContainer)) return;
362
370
  const [header, resources, chat] = document.children as ContainerLike[];
371
+ const restoreImageRedraw = attachImageRedraw(tui);
363
372
  // During /reload Pi replaces the editor with a reload notice until AFTER
364
373
  // session_start. The validated document/container layout remains unchanged.
365
374
  // Custom editors also need not expose getText; do not use editor contents
@@ -496,6 +505,16 @@ export function attachTranscript(tui: unknown, view: TranscriptView, options: No
496
505
  notices.set(turn, rows);
497
506
  continue;
498
507
  }
508
+ // Pi 1.x renders command information (/session, /hotkeys) lazily for theme changes.
509
+ if (child.constructor.name === "ThemedText") {
510
+ const rows = notices.get(turn) ?? [];
511
+ rows.push(...child.render(width));
512
+ notices.set(turn, rows);
513
+ continue;
514
+ }
515
+ // Tool images are step attachments, represented by hover links in the
516
+ // compact view. Only assistant replies own inline image rows.
517
+ if (child.constructor.name === "ToolExecutionComponent") continue;
499
518
  if (child.constructor.name !== "Text") continue;
500
519
  // Pi 0.85 Text stores the unwrapped styled source in text. Width changes
501
520
  // must not restart the timeout; setText updates must restart it.
@@ -509,14 +528,17 @@ export function attachTranscript(tui: unknown, view: TranscriptView, options: No
509
528
  cacheMisses.set(turn, current);
510
529
  continue;
511
530
  }
512
- if (typeof source === "string" && !options.isPrompt?.(source) && options.isTransient?.(source)) {
513
- let state = noticeTimes.get(child);
514
- if (!state || state.text !== source) {
515
- state = { text: source, until: time + 5000 };
516
- noticeTimes.set(child, state);
531
+ if (typeof source === "string" && !options.isPrompt?.(source)) {
532
+ if (options.hideStartupLine?.(source)) continue;
533
+ if (options.isTransient?.(source)) {
534
+ let state = noticeTimes.get(child);
535
+ if (!state || state.text !== source) {
536
+ state = { text: source, until: time + 5000 };
537
+ noticeTimes.set(child, state);
538
+ }
539
+ if (time >= state.until) continue;
540
+ nextExpiry = Math.min(nextExpiry, state.until);
517
541
  }
518
- if (time >= state.until) continue;
519
- nextExpiry = Math.min(nextExpiry, state.until);
520
542
  }
521
543
  const rows = notices.get(turn) ?? [];
522
544
  rows.push(...child.render(width));
@@ -541,7 +563,11 @@ export function attachTranscript(tui: unknown, view: TranscriptView, options: No
541
563
  }
542
564
  };
543
565
  }
544
- const prefix = [...header.render(width), ...resources.render(width)];
566
+ const startupLine = options.hideStartupLine;
567
+ const resourceRows = startupLine
568
+ ? resources.render(width).filter(line => !startupLine(line))
569
+ : resources.render(width);
570
+ const prefix = [...header.render(width), ...resourceRows];
545
571
  prefixNoticeOffset = prefix.length;
546
572
  prefixNotices = notices.get(-1) ?? [];
547
573
  prefix.push(...prefixNotices);
@@ -584,26 +610,32 @@ export function attachTranscript(tui: unknown, view: TranscriptView, options: No
584
610
  else delete dock.handleMouse;
585
611
  };
586
612
  }) : [];
613
+ const hasStickyAgent = view.pinnedAgent && view.unpinAgent;
587
614
  const hasStickyTool = view.pinnedTool && view.unpinTool && view.toggleTool;
588
615
  const hasStickySubagent = view.pinnedSubagent && view.unpinSubagent && view.toggleSubagent;
589
- const restoreSticky = hasStickyTool || hasStickySubagent ? attachStickyTool(tui, document, {
616
+ const restoreSticky = hasStickyAgent || hasStickyTool || hasStickySubagent ? attachStickyTool(tui, document, {
590
617
  pinnedTool: () => {
618
+ const agent = view.pinnedAgent?.();
619
+ if (agent) return { id: `agent:${agent.index}`, y: agent.y + viewOffset, line: agent.line };
591
620
  const target = view.pinnedSubagent?.() ?? view.pinnedTool?.();
592
621
  if (!target) return;
593
622
  const kind = view.pinnedSubagent?.() ? "subagent" : "tool";
594
623
  return { ...target, id: `${kind}:${target.id}`, y: target.y + viewOffset };
595
624
  },
596
625
  unpinTool: () => {
626
+ view.unpinAgent?.();
597
627
  view.unpinSubagent?.();
598
628
  view.unpinTool?.();
599
629
  },
600
630
  toggleTool: id => {
601
631
  const [kind, targetId] = id.split(":", 2);
602
- if (kind === "subagent") view.toggleSubagent?.(targetId);
632
+ if (kind === "agent") view.handleMouse?.({ type: "click", button: "left", x: 0, y: view.pinnedAgent?.()?.y ?? 0, screenX: 0, screenY: 0, width: 1, height: 1, clickCount: 1, shift: false, ctrl: false, alt: false });
633
+ else if (kind === "subagent") view.toggleSubagent?.(targetId);
603
634
  else if (kind === "tool") view.toggleTool?.(targetId);
604
635
  },
605
636
  }, height => { stickyMinHeight = height; }) : undefined;
606
637
  return () => {
638
+ restoreImageRedraw?.();
607
639
  restoreSticky?.();
608
640
  cancelExpiry?.();
609
641
  view.clearHover?.();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@each1024/pi-mini-mode",
3
- "version": "2.0.2",
3
+ "version": "2.0.5",
4
4
  "description": "A compact Pi footer with live usage metrics, theme-aware settings previews, and configurable progress bars.",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -26,7 +26,7 @@
26
26
  "tui"
27
27
  ],
28
28
  "pi": {
29
- "video": "https://raw.githubusercontent.com/eachann1024/pi-mini-mode/main/assets/pi-mini-mode-demo-zh.mp4",
29
+ "video": "https://raw.githubusercontent.com/eachann1024/pi-mini-mode/main/assets/pi-mini-mode-demo.mp4",
30
30
  "extensions": [
31
31
  "./extensions/footer-status.ts"
32
32
  ],
@@ -41,7 +41,7 @@
41
41
  "text": "text",
42
42
  "thinkingText": "muted",
43
43
  "selectedBg": "selectedBg",
44
- "scrollbarThumb": "selectedBg",
44
+ "scrollbarThumb": "accent",
45
45
  "userMessageBg": "userMessageBg",
46
46
  "userMessageText": "text",
47
47
  "customMessageBg": "customMessageBg",
@@ -41,7 +41,7 @@
41
41
  "text": "text",
42
42
  "thinkingText": "muted",
43
43
  "selectedBg": "selectedBg",
44
- "scrollbarThumb": "selectedBg",
44
+ "scrollbarThumb": "accent",
45
45
  "userMessageBg": "userMessageBg",
46
46
  "userMessageText": "text",
47
47
  "customMessageBg": "customMessageBg",