@each1024/pi-mini-mode 2.0.3 → 2.0.6

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,9 +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/bcd1b6db-7401-46a5-a537-7a9ad9f4df73" controls muted playsinline width="100%"></video>
13
+ https://github.com/user-attachments/assets/1ad90757-ecea-4901-afd8-f33a68176ae2
14
14
 
15
- <video src="https://github.com/user-attachments/assets/5c3f2d9f-20ca-4174-9095-9324f8df397e" controls muted playsinline width="100%"></video>
15
+ https://github.com/user-attachments/assets/53c1bcd8-9f0b-42d7-a424-a407dcf666e8
16
16
 
17
17
  Numbers in the footer shots come from a scripted demo session; prices are estimates, not provider bills.
18
18
 
@@ -91,13 +91,11 @@ Turn **Minimal output** off in settings to restore native Pi history.
91
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.
92
92
 
93
93
  <details>
94
- <summary>See the footer settings and demo</summary>
94
+ <summary>See the footer settings</summary>
95
95
 
96
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)
97
97
 
98
- [Watch the footer settings demo](https://github.com/user-attachments/assets/5f2f4816-45ed-4759-b035-d9ee59e8a763)
99
-
100
- 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.
101
99
 
102
100
  </details>
103
101
 
@@ -219,7 +217,7 @@ For a real terminal smoke test, run `python3 test/minimal-pty.py`. It needs Pyth
219
217
  <details>
220
218
  <summary><strong>Publishing</strong></summary>
221
219
 
222
- Normal releases are published from this machine with the npm token in `.npmrc` (`npm publish --access public`). `publish.yml` is only a manual backup (`workflow_dispatch` on `main`): it runs `npm ci`, `npm run check`, and `npm test`, then `scripts/publish.mjs`. That script publishes the higher of the local version baseline and npm's highest historically published stable version plus one patch, changes the version only in the runner (no version commit or tag), and skips commits that are already published. Raise the baseline in `package.json` and the lockfile for a major or minor release.
220
+ Complete and commit the task, then run `npm run release` from a clean checkout. It selects one version above every historically published stable npm version, updates package.json and the lockfile, checks types, commits and pushes to main, publishes to npm, verifies the package and latest tag, and creates the matching Git tag. Versions start at `2.0.6`; the final number continues through 100 and beyond and does not reset when the feature version changes. Pi uses the same npm version. Ordinary pushes do not publish. The manual CI backup publishes the committed version exactly and never changes it. Failed publication stops without a second publish.
223
221
 
224
222
  The backup workflow needs the package’s npm Trusted Publisher configured for this GitHub repository and `publish.yml`. It uses OIDC and provenance and does not use an npm token.
225
223
 
package/README.zh-CN.md CHANGED
@@ -10,9 +10,9 @@
10
10
 
11
11
  ## 演示视频
12
12
 
13
- <video src="https://github.com/user-attachments/assets/bcd1b6db-7401-46a5-a537-7a9ad9f4df73" controls muted playsinline width="100%"></video>
13
+ https://github.com/user-attachments/assets/1ad90757-ecea-4901-afd8-f33a68176ae2
14
14
 
15
- <video src="https://github.com/user-attachments/assets/5c3f2d9f-20ca-4174-9095-9324f8df397e" controls muted playsinline width="100%"></video>
15
+ https://github.com/user-attachments/assets/53c1bcd8-9f0b-42d7-a424-a407dcf666e8
16
16
 
17
17
  页脚画面中的数字来自脚本化的演示会话,价格为估算值,不是服务商账单。
18
18
 
@@ -91,13 +91,11 @@ pi install git:github.com/eachann1024/pi-mini-mode
91
91
  **重要指标,一行看清。** 模型与思考级别、会话令牌、缓存总量与命中率、费用估算、上下文用量与生成速度。在 `/pi-mini-mode-settings` 中选择显示字段,即时生效,页脚自动适配窄终端。
92
92
 
93
93
  <details>
94
- <summary>查看页脚设置截图与演示</summary>
94
+ <summary>查看页脚设置截图</summary>
95
95
 
96
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)
97
97
 
98
- [观看页脚设置演示](https://github.com/user-attachments/assets/5f2f4816-45ed-4759-b035-d9ee59e8a763)
99
-
100
- 这份已有截图和录屏展示页脚配置,不代表新增图片、折叠与子代理功能的当前界面。设置预览使用示例数据。
98
+ 这张已有截图展示页脚配置,不代表新增图片、折叠与子代理功能的当前界面。设置预览使用示例数据。
101
99
 
102
100
  </details>
103
101
 
@@ -212,7 +210,7 @@ python3 test/minimal-pty.py
212
210
  <details>
213
211
  <summary><strong>发布</strong></summary>
214
212
 
215
- 日常发布在本机完成,使用 `.npmrc` 中的 npm token(`npm publish --access public`)。`publish.yml` 只作为手动备份(在 `main` 上 `workflow_dispatch`):先执行 `npm ci`、`npm run check` 和 `npm test`,再运行 `scripts/publish.mjs`。该脚本发布本地版本基线与 npm 最新稳定版本再加一个 patch 中的较高者,版本只在 runner 中变更(不创建版本提交或 tag),并跳过已经发布过的提交。发布 major 或 minor 时,同时提高 `package.json` 和 lockfile 中的基线。
213
+ 每轮改动完成并提交后,在干净的工作区运行 `npm run release`。入口统一确定高于 npm 全部历史稳定版本的版本号,同步 package.json 与 lockfile,执行类型检查,提交并推送 main,发布 npm,核验包内容与 latest,最后创建同名 Git 标签。新流程从 `2.0.6` 开始,末位持续累加,可超过 100,功能版本升级也不归零。Pi 使用同一 npm 版本。普通推送不触发发布;手动 CI 备用入口只发布已提交的版本,不自行升号。发布失败立即停止,不重复发布。
216
214
 
217
215
  备份流程需要为该包配置指向此 GitHub 仓库及 `publish.yml` 的 npm Trusted Publisher。它使用 OIDC 和 provenance,不使用 npm token。
218
216
 
@@ -1,15 +1,18 @@
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";
15
+ import { thinkingPreview } from "../lib/thinking-preview.ts";
13
16
  import { basename, dirname, join } from "node:path";
14
17
  import attachFooterTidy from "../lib/footer-tidy.ts";
15
18
  import attachTitlePlain from "../lib/title-plain.ts";
@@ -537,6 +540,7 @@ export interface MinimalTurn {
537
540
  running?: boolean;
538
541
  /** Wall-clock start of this user-request execution; retained across tool and thinking turns. */
539
542
  startedAt?: number;
543
+ endedAt?: number;
540
544
  thinking?: number;
541
545
  /** Per-process-index Thinking clocks. Live rows count; completed rows keep endedAt. */
542
546
  thinkingClocks?: Array<ThinkingClock | undefined>;
@@ -584,6 +588,17 @@ export function formatElapsed(startedAt: number | undefined, now = Date.now()):
584
588
  return minutes >= 60 ? `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, "0")}:${remainder}` : `${minutes}:${remainder}`;
585
589
  }
586
590
 
591
+ /** Compact tool duration, visible from the start of execution. */
592
+ export function formatToolElapsed(startedAt: number | undefined, endedAt = Date.now()): string {
593
+ if (startedAt === undefined) return "";
594
+ const seconds = Math.max(0, Math.floor((endedAt - startedAt) / 1_000));
595
+ if (!seconds) return "1s";
596
+ const hours = Math.floor(seconds / 3_600);
597
+ const minutes = Math.floor(seconds / 60) % 60;
598
+ const remainder = seconds % 60;
599
+ return `${hours ? `${hours}h` : ""}${minutes ? `${minutes}m` : ""}${remainder ? `${remainder}s` : ""}`;
600
+ }
601
+
587
602
  function ensureThinkingClock(turn: MinimalTurn, index: number, startedAt = Date.now()): ThinkingClock {
588
603
  const clocks = turn.thinkingClocks ??= [];
589
604
  return clocks[index] ??= { startedAt: turn.startedAt ?? startedAt };
@@ -610,8 +625,9 @@ export function formatThinkingElapsed(
610
625
  now = Date.now(),
611
626
  ): string {
612
627
  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);
628
+ const startedAt = clock?.startedAt ?? turn.startedAt;
629
+ if (active && startedAt != null) return `${(Math.max(0, now - startedAt) / 1_000).toFixed(1)}s`;
630
+ if (clock?.endedAt != null) return `${(Math.max(0, clock.endedAt - clock.startedAt) / 1_000).toFixed(1)}s`;
615
631
  return "";
616
632
  }
617
633
 
@@ -622,6 +638,20 @@ function pushProcess(turn: MinimalTurn | undefined, kind: string, value: unknown
622
638
  if (turn.process.at(-1) !== line) turn.process.push(line);
623
639
  }
624
640
 
641
+ function thinkingText(item: Record<string, unknown>): string {
642
+ const value = item.thinking ?? item.text;
643
+ return typeof value === "string" ? (value.trim() ? value : "") : processText(value);
644
+ }
645
+
646
+ /** Only adjacent empty blocks in the same assistant content share a row. */
647
+ function continuesEmptyThinking(content: Array<Record<string, unknown>>, blockIndex: number): boolean {
648
+ const item = content[blockIndex];
649
+ const previous = content[blockIndex - 1];
650
+ return item?.type === "thinking" && previous?.type === "thinking"
651
+ && !thinkingText(item)
652
+ && !thinkingText(previous);
653
+ }
654
+
625
655
  function skillNames(text: string): string[] {
626
656
  const names = new Set<string>();
627
657
  for (const match of text.matchAll(/\/skill:([\w.-]+)/g)) names.add(match[1]);
@@ -669,10 +699,13 @@ export function minimalTurnsFromBranch(branch: readonly unknown[]): MinimalTurn[
669
699
  if (role !== "assistant" || !Array.isArray(content)) continue;
670
700
  if (turn.final) (turn.replies ??= []).push(turn.final);
671
701
  turn.final = undefined;
672
- for (const item of content as Array<Record<string, unknown>>) {
702
+ for (const [blockIndex, item] of (content as Array<Record<string, unknown>>).entries()) {
673
703
  if (!item || typeof item !== "object") continue;
674
- if (item.type === "thinking") pushProcess(turn, "thinking", item.thinking ?? item.text);
675
- else if (item.type === "toolCall") {
704
+ if (item.type === "thinking") {
705
+ if (!continuesEmptyThinking(content as Array<Record<string, unknown>>, blockIndex)) {
706
+ turn.process.push(`thinking ${thinkingText(item)}`);
707
+ }
708
+ } else if (item.type === "toolCall") {
676
709
  if (item.name) {
677
710
  (turn.agentCalls ??= []).push(agentCall(String(item.id), String(item.name), item.arguments ?? item.input));
678
711
  pushProcess(turn, "call", String(item.id));
@@ -726,9 +759,12 @@ function visibleMinimalTurns(settings: MiniLensSettings, turns: MinimalTurn[]):
726
759
  });
727
760
  }
728
761
 
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) {
762
+ 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 }) {
763
+ const placeholderText = (text: string) => imageOptions ? imagePlaceholders(text, imageOptions.cwd()) : text;
730
764
  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)));
765
+ { color: (value) => theme.fg(process ? "muted" : "text", value) }, (source, available) => transformText(placeholderText(diagramMarkdown(source, available))));
766
+ const assistantImages = imageOptions && createAssistantImages(imageOptions.cwd, imageOptions.requestRender, imageOptions.write);
767
+ const assistantMarkdown = (text: string, width: number, owner: string) => assistantImages ? assistantImages.render(text, width, markdown, owner) : markdown(text, width);
732
768
  const surface = (rows: string[], width: number, user: boolean, selected = -1, expanded = false) => {
733
769
  const padding = Math.min(2, Math.floor((width - 1) / 2));
734
770
  return ["", ...rows, ""].map((row, index) => {
@@ -741,11 +777,18 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
741
777
  const expandedSubagents = new Set<string>();
742
778
  const expandedTools = new Set<string>();
743
779
  const expandedThinking = new Set<string>();
780
+ const thinkingPreviews = new Map<string, { text: string; width: number; rows: number; updatedAt: number }>();
781
+ const PROCESS_PREVIEW_ROWS = 6;
782
+ const agentModes = new Map<number, "all" | "preview" | "closed">();
783
+ const runningTurns = new Set<number>();
744
784
  let pinnedToolId: string | undefined;
745
785
  let pinnedTool: { id: string; y: number; line: string } | undefined;
786
+ let pinnedAgentIndex: number | undefined;
787
+ let pinnedAgent: { index: number; y: number; line: string } | undefined;
746
788
  let pinnedSubagentId: string | undefined;
747
789
  let pinnedSubagent: { id: string; y: number; line: string; autoScroll?: boolean } | undefined;
748
790
  let toolControls: Array<{ id: string; y: number; width: number; title: string }> = [];
791
+ let agentControls: Array<{ index: number; y: number; width: number }> = [];
749
792
  let hoveredTool: typeof toolControls[number] | undefined;
750
793
  const clearHover = () => { const changed = !!hoveredTool; hoveredTool = undefined; return changed; };
751
794
  const toggleTool = (id: string) => {
@@ -758,6 +801,16 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
758
801
  clearHover();
759
802
  return;
760
803
  }
804
+ if (id.startsWith("agents:")) {
805
+ const index = Number(id.slice(7));
806
+ if (!Number.isInteger(index) || !getTurns()[index]) return;
807
+ const all = (agentModes.get(index) ?? (isExpanded() ? "all" : "preview")) === "all";
808
+ agentModes.set(index, all ? "preview" : "all");
809
+ if (all) { expandedThinking.clear(); expandedTools.clear(); expandedSubagents.clear(); }
810
+ pinnedAgentIndex = all ? undefined : index;
811
+ clearHover();
812
+ return;
813
+ }
761
814
  if (!getTurns().some(turn => turn.agentCalls?.some(call => call.id === id && !isAgentTool(call.tool ?? call.name)))) return;
762
815
  if (expandedTools.has(id)) {
763
816
  expandedTools.delete(id);
@@ -789,10 +842,18 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
789
842
  else expandedPrompts.set(index, question);
790
843
  };
791
844
  return {
845
+ dispose() { assistantImages?.dispose(); },
792
846
  invalidate() { clearHover(); },
847
+ resetProcessView() {
848
+ agentModes.clear(); expandedThinking.clear(); expandedTools.clear(); expandedSubagents.clear();
849
+ thinkingPreviews.clear();
850
+ pinnedToolId = undefined; pinnedAgentIndex = undefined; pinnedSubagentId = undefined;
851
+ },
793
852
  clearHover,
794
853
  pinnedTool: () => pinnedTool,
795
854
  unpinTool: () => { pinnedToolId = undefined; pinnedTool = undefined; },
855
+ pinnedAgent: () => pinnedAgent,
856
+ unpinAgent: () => { pinnedAgentIndex = undefined; pinnedAgent = undefined; },
796
857
  pinnedSubagent: () => pinnedSubagent,
797
858
  unpinSubagent: () => { pinnedSubagentId = undefined; pinnedSubagent = undefined; },
798
859
  toolChoices: () => toolControls.map(control => ({ ...control, expanded: expandedTools.has(control.id) || expandedThinking.has(control.id) })),
@@ -820,6 +881,17 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
820
881
  }
821
882
  }
822
883
  if (event.button !== "left" || event.shift || event.ctrl || event.alt) return;
884
+ const agent = agentControls.find(control => event.y === control.y && event.x >= 0 && event.x < control.width);
885
+ if (agent && (event.clickCount ?? 1) === 1) {
886
+ if (event.type === "press") return { handled: true };
887
+ if (event.type === "click") {
888
+ const all = (agentModes.get(agent.index) ?? (isExpanded() ? "all" : "preview")) === "all";
889
+ agentModes.set(agent.index, all ? "preview" : "all");
890
+ if (all) { expandedThinking.clear(); expandedTools.clear(); expandedSubagents.clear(); }
891
+ pinnedAgentIndex = all ? undefined : agent.index;
892
+ return { handled: true, render: true };
893
+ }
894
+ }
823
895
  const control = promptControls.find(control => event.y === control.y && event.x >= control.x && event.x < control.x + control.width);
824
896
  if (control && (event.clickCount ?? 1) === 1) {
825
897
  if (event.type === "press") return { handled: true };
@@ -843,7 +915,9 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
843
915
  render(width: number, notices?: TurnNotices): string[] {
844
916
  promptControls = [];
845
917
  toolControls = [];
918
+ agentControls = [];
846
919
  pinnedTool = undefined;
920
+ pinnedAgent = undefined;
847
921
  pinnedSubagent = undefined;
848
922
  subagentControls = [];
849
923
  noticeRegions = [];
@@ -855,6 +929,7 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
855
929
  const thinkingIds = new Set(turns.flatMap((turn, turnIndex) => turn.process.flatMap((entry, processIndex) =>
856
930
  entry.startsWith("thinking") ? [`thinking:${turnIndex}:${processIndex}`] : [])));
857
931
  for (const id of expandedThinking) if (!thinkingIds.has(id)) expandedThinking.delete(id);
932
+ for (const id of thinkingPreviews.keys()) if (!thinkingIds.has(id)) thinkingPreviews.delete(id);
858
933
  const inner = Math.max(1, width - 2 * Math.min(2, Math.floor((width - 1) / 2)));
859
934
  const lines: string[] = [];
860
935
  // An open heading wears the same full-width selectedBg band as an expanded SubAgent row.
@@ -863,6 +938,7 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
863
938
  for (const [index, turn] of turns.entries()) {
864
939
  if (index > 0) lines.push("");
865
940
  if (expandedPrompts.has(index) && expandedPrompts.get(index) !== turn.question) expandedPrompts.delete(index);
941
+ const noticeRows = notices?.get(index) ?? [];
866
942
  const questionRows = markdown(turn.question, inner);
867
943
  const loopSummary = piLoopSummary(turn.question);
868
944
  const expanded = expandedPrompts.get(index) === turn.question;
@@ -885,7 +961,7 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
885
961
  const entries = turn.process.flatMap((entry, processIndex) => {
886
962
  if (entry.startsWith("call ")) {
887
963
  const call = turn.agentCalls?.find(call => call.id === entry.slice(5));
888
- if (call && isAgentTool(call.tool ?? call.name) && !isExpanded()) return [];
964
+ if (call && isAgentTool(call.tool ?? call.name)) return [];
889
965
  const display = call && agentCallDisplay(call);
890
966
  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
967
  }
@@ -897,41 +973,62 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
897
973
  });
898
974
  // Older in-memory turns may predate call markers.
899
975
  for (const call of turn.agentCalls ?? []) {
900
- if (isAgentTool(call.tool ?? call.name) && !isExpanded()) continue;
976
+ if (isAgentTool(call.tool ?? call.name)) continue;
901
977
  const display = agentCallDisplay(call);
902
978
  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
979
  }
904
980
  const agentTurnControls: Array<{ runId: string; y: number; width: number; line: string }> = [];
905
981
  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;
982
+ 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 });
983
+ const active = !!turn.running || agents.running > 0 || entries.some(entry => entry.state === "running") || (turn.waitingTools?.length ?? 0) > 0;
984
+ if (active) runningTurns.add(index);
985
+ else if (runningTurns.delete(index)) {
986
+ // Return to the six-row preview once; a later click can expand everything again.
987
+ if (agentModes.get(index) === "all") {
988
+ agentModes.set(index, "preview");
989
+ expandedThinking.clear();
990
+ expandedTools.clear();
991
+ expandedSubagents.clear();
992
+ if (pinnedAgentIndex === index) pinnedAgentIndex = undefined;
993
+ }
994
+ }
995
+ if (entries.length || active || turn.usage || agents.total) {
996
+ const mode = agentModes.get(index) ?? (isExpanded() ? "all" : "preview");
997
+ const expanded = mode === "all";
909
998
  const busy = entries.some(entry => entry.state === "running") || (turn.waitingTools?.length ?? 0) > 0;
910
999
  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);
1000
+ // Six recent records stay visible while running and after completion.
1001
+ const shown = mode === "closed" ? [] : expanded ? entries : entries.slice(-PROCESS_PREVIEW_ROWS);
914
1002
  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" : "");
1003
+ // ponytail: two terminal text frames; use Pi's motion preference if it exposes one.
1004
+ const sparkle = active ? Math.floor(Date.now() / 360) % 2 ? "✧" : "✦" : "✦";
1005
+ const steps = entries.length
1006
+ ? theme.fg("muted", done === entries.length ? ` · 完成 共 ${entries.length} 步` : ` · 第 ${Math.min(entries.length, done + 1)} 步`)
1007
+ : "";
1008
+ const subagents = agents.total
1009
+ ? theme.fg("muted", " · ") + theme.bold(theme.fg("text", "子代理")) + theme.fg("muted", ` ${agents.done + agents.errors}/${agents.total}`)
1010
+ + (agents.errors ? theme.fg("error", ` · ${agents.errors} 失败`) : "")
1011
+ : "";
919
1012
  const usage = addUsage({ ...EMPTY_USAGE, ...turn.usage, cost: turn.usage?.cost ?? 0 }, turn.pendingUsage);
920
1013
  const hasUsage = usage.totalTokens > 0 || usage.cacheRead > 0;
921
1014
  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)}`)
1015
+ ? theme.fg("muted", "会话 ") + theme.bold(theme.fg("text", formatTokens(usage.totalTokens)))
1016
+ + theme.fg("muted", " · 缓存 ") + theme.bold(theme.fg("text", formatTokens(usage.cacheRead)))
924
1017
  : "";
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
- }
1018
+ const recordCount = entries.filter(entry => !entry.title.startsWith("SubAgent ")).length || agents.total;
1019
+ const progressHeader = theme.fg(active ? "accent" : "muted", sparkle + " ") + theme.bold(theme.fg("text", "Agent")) + theme.fg("muted", recordCount ? ` · ${recordCount}` : "");
1020
+ const showAgentRows = mode !== "closed" && expanded;
1021
+ const caret = theme.fg("muted", expanded ? " ▾" : " ▸");
1022
+ const elapsedHeader = turn.startedAt == null ? "" : theme.fg("muted", " · ") + theme.fg(active ? "success" : "muted", formatElapsed(turn.startedAt, turn.endedAt ?? Date.now()));
1023
+ const left = progressHeader + elapsedHeader + caret;
1024
+ const showTotals = hasUsage && showUsage() && visibleWidth(left) + 2 + visibleWidth(totals) <= width;
1025
+ agentControls.push({ index, y: lines.length + 1, width: Math.min(width, visibleWidth(left)) });
1026
+ if (expanded && pinnedAgentIndex === index) pinnedAgent = { index, y: lines.length + 1, line: truncateToWidth(left, width) };
1027
+ lines.push("", showTotals
1028
+ ? left + " ".repeat(width - visibleWidth(left) - visibleWidth(totals)) + totals
1029
+ : truncateToWidth(left, width));
932
1030
  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;
1031
+ const title = entry.title;
935
1032
  const text = title.split(/\r?\n/).find(line => line.trim())?.replace(/\s+/g, " ").trim() ?? "";
936
1033
  const split = text.indexOf(" ");
937
1034
  const label = split < 0 ? text : text.slice(0, split);
@@ -940,10 +1037,12 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
940
1037
  const elapsed = entry.thinking ? formatThinkingElapsed(turn, entry.processIndex, activeThinking) : "";
941
1038
  const thinkingElapsed = elapsed ? theme.fg(activeThinking ? "success" : "muted", ` ${elapsed}`) : "";
942
1039
  const call = turn.agentCalls?.find(call => call.id === entry.id && !isAgentTool(call.tool ?? call.name));
943
- const controlId = call?.id ?? (entry.thinking ? entry.id : "");
1040
+ const controlId = call?.id ?? (entry.thinking || entry.id.startsWith("agents:") ? entry.id : "");
944
1041
  const open = call ? expandedTools.has(call.id) : entry.thinking && expandedThinking.has(entry.id);
945
1042
  const identity = open || activeThinking ? "accent" : "text";
946
- const summary = theme.fg(identity, theme.bold(label)) + thinkingElapsed + " ";
1043
+ const duration = call ? formatToolElapsed(call.startedAt, call.endedAt ?? Date.now()) : "";
1044
+ const toolElapsed = duration ? theme.fg(call?.state === "running" ? "accent" : "muted", ` ${duration}`) : "";
1045
+ const summary = theme.fg(identity, theme.bold(label)) + thinkingElapsed + toolElapsed + " ";
947
1046
  if (controlId && width >= 4) toolControls.push({ id: controlId, y: lines.length, width, title: text });
948
1047
  if (hoveredTool?.id === controlId && (hoveredTool.y !== lines.length || hoveredTool.width !== width)) clearHover();
949
1048
  const status = entry.state === "error" ? "✕" : entry.state === "running" ? runningGlyph() : "●";
@@ -951,17 +1050,40 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
951
1050
  const keepStatus = entry.state === "running" || (open && entry.state === "error");
952
1051
  const glyph = arrow ? (open ? "▼" : "▶") + (keepStatus ? ` ${status}` : "") : status;
953
1052
  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;
1053
+ const last = row === shown.length - 1 && !working && (!showAgentRows || !agents.rows.length);
1054
+ const prefix = theme.fg(open ? "accent" : "dim", "│ ") + (entry.state === "running" || entry.state === "error" || arrow ? theme.fg(glyphColor, glyph) + " " : "") + summary;
956
1055
  if (label === "Output") {
957
1056
  // Wrapped output hangs under the body column and keeps the tree rail to the next sibling.
958
1057
  const indent = visibleWidth(prefix);
959
- const wrapped = markdown(body, Math.max(1, width - indent), true);
960
1058
  const rail = !last && indent > 0 ? theme.fg("dim", "\u2502") + " ".repeat(indent - 1) : " ".repeat(indent);
1059
+ const wrapped = markdown(body, Math.max(1, width - indent), true);
961
1060
  lines.push(truncateToWidth(prefix + (wrapped[0] ?? ""), width, ""));
962
1061
  for (const extra of wrapped.slice(1)) lines.push(truncateToWidth(rail + extra, width, ""));
963
1062
  } 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));
1063
+ const available = Math.max(0, width - visibleWidth(prefix));
1064
+ if (entry.thinking) {
1065
+ const now = Date.now();
1066
+ const cached = thinkingPreviews.get(entry.id);
1067
+ const previewRows = open ? 1 : 2;
1068
+ const reuse = activeThinking && cached?.text && cached.width === available && cached.rows === previewRows && now - cached.updatedAt < 350;
1069
+ const display = reuse ? cached.text : thinkingPreview(entry.detail, available, previewRows);
1070
+ if (!reuse) thinkingPreviews.set(entry.id, { text: display, width: available, rows: previewRows, updatedAt: now });
1071
+ const fallback = activeThinking ? "等待模型返回思考内容" : "模型未提供可显示的思考内容";
1072
+ const rows = new Text(display || fallback, 0, 0).render(Math.max(1, available)).slice(0, open ? 1 : 2);
1073
+ const color = activeThinking ? "accent" : "muted";
1074
+ lines.push(bandHeading(truncateToWidth(prefix + theme.fg(color, rows[0] ?? ""), width, ""), open));
1075
+ const rail = theme.fg(last ? color : "dim", last ? " " : "│") + " ".repeat(Math.max(0, visibleWidth(prefix) - 1));
1076
+ for (const extra of rows.slice(1)) lines.push(truncateToWidth(rail + theme.fg(color, extra), width, ""));
1077
+ } else {
1078
+ const displayBody = placeholderText(body);
1079
+ const compactBody = linkToolFiles(displayBody, imageOptions?.cwd() ?? process.cwd(), !open);
1080
+ const fittedBody = visibleWidth(compactBody) > available && !open && available > 1
1081
+ ? "…" + sliceByColumn(compactBody, visibleWidth(compactBody) - available + 1, available - 1, true)
1082
+ : truncateToWidth(compactBody, available, "…");
1083
+ // sliceByColumn may end before OSC 8's closing sequence.
1084
+ const styledBody = theme.fg(open ? "accent" : "muted", fittedBody + "\x1b]8;;\x07");
1085
+ lines.push(bandHeading(truncateToWidth(prefix + styledBody, width, "…"), open));
1086
+ }
965
1087
  }
966
1088
  if (open && call && call.id === pinnedToolId) pinnedTool = { id: call.id, y: lines.length - 1, line: lines.at(-1)! };
967
1089
  if (open && call) {
@@ -975,30 +1097,25 @@ export function minimalOutputComponent(theme: ExtensionContext["ui"]["theme"], g
975
1097
  const rail = width > 5 ? (last ? " " : theme.fg("accent", "│ ")) : "";
976
1098
  const detailWidth = Math.max(1, width - visibleWidth(rail));
977
1099
  lines.push(...markdown(entry.detail, detailWidth, true).map(line => truncateToWidth(rail + line, width, "")));
978
- } else if (expanded && entry.state === "error" && entry.detail) {
979
- const rail = last ? " " : theme.fg("dim", "│ ");
980
- const details = entry.detail.split(/\r?\n/).filter(line => line.trim());
981
- // ponytail: four diagnostic lines; full output remains in the native transcript.
982
- lines.push(...details.slice(1, 5).map(line => truncateToWidth(rail + theme.fg("muted", line), width)));
983
- if (details.length > 5) lines.push(truncateToWidth(rail + theme.fg("muted", `… +${details.length - 5} lines`), width));
984
1100
  }
985
1101
  });
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 };
1102
+ if (showAgentRows) {
1103
+ const agentStartY = lines.length;
1104
+ for (const c of agentTurnControls) {
1105
+ const control = { ...c, y: agentStartY + c.y };
1106
+ subagentControls.push(control);
1107
+ if (c.runId === pinnedSubagentId) pinnedSubagent = { id: c.runId, y: control.y, line: c.line, autoScroll: false };
1108
+ }
1109
+ lines.push(...agents.rows);
991
1110
  }
992
- lines.push(...agents.rows);
993
- if (working) {
1111
+ if (working && (expanded || !shown.length)) {
994
1112
  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)}`) + " ";
996
- lines.push(truncateToWidth(prefix + theme.fg("text", "…"), width, ""));
1113
+ const prefix = theme.fg("dim", "└─ ") + theme.fg("accent", `${runningGlyph()} `) + theme.fg("text", theme.bold(label)) + " ";
1114
+ lines.push(truncateToWidth(prefix + theme.fg("muted", turn.awaitingResponse ? "等待模型响应" : "等待下一步执行"), width, ""));
997
1115
  }
998
1116
  }
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) ?? [];
1117
+ for (const [replyIndex, reply] of (turn.replies ?? []).entries()) lines.push("", ...assistantMarkdown(reply, width, `reply:${index}:${replyIndex}`));
1118
+ if (turn.final) lines.push("", ...assistantMarkdown(turn.final, width, `final:${index}`));
1002
1119
  noticeRegions.push({ y: lines.length, rows: noticeRows });
1003
1120
  lines.push(...noticeRows);
1004
1121
  }
@@ -1015,6 +1132,8 @@ export default function (pi: ExtensionAPI) {
1015
1132
  attachFooterTidy(pi);
1016
1133
  attachTitlePlain(pi);
1017
1134
  let refreshFooter: (() => void) | undefined;
1135
+ let restoreScrollbar: (() => void) | undefined;
1136
+ let scrollbarRoot: unknown;
1018
1137
  let refreshMinimal: (() => void) | undefined;
1019
1138
  let processExpanded = false;
1020
1139
  let nativeOutput = false;
@@ -1066,6 +1185,7 @@ export default function (pi: ExtensionAPI) {
1066
1185
  restoreTranscript = undefined;
1067
1186
  restoreAgentWidgets?.();
1068
1187
  restoreAgentWidgets = undefined;
1188
+ promptView?.dispose();
1069
1189
  promptView = undefined;
1070
1190
  if (settings["pi-mini-mode-minimal-show"] && ctx.mode === "tui") unsubscribeMinimalInput = ctx.ui.onTerminalInput?.((data) => {
1071
1191
  const nativeKey = matchesKey(data, "ctrl+alt+o");
@@ -1078,7 +1198,10 @@ export default function (pi: ExtensionAPI) {
1078
1198
  nativeOutput = !nativeOutput;
1079
1199
  mountMinimalOutput(ctx);
1080
1200
  } else if (subAgentKey) subAgentsExpanded = !subAgentsExpanded;
1081
- else processExpanded = !processExpanded;
1201
+ else {
1202
+ processExpanded = !processExpanded;
1203
+ promptView?.resetProcessView();
1204
+ }
1082
1205
  refreshMinimalOutput();
1083
1206
  return { consume: true };
1084
1207
  });
@@ -1133,7 +1256,11 @@ export default function (pi: ExtensionAPI) {
1133
1256
  return { ...turn, subAgents: withNotices };
1134
1257
  });
1135
1258
  };
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);
1259
+ 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, {
1260
+ cwd: () => ctx.cwd,
1261
+ requestRender: () => tui.requestRender(),
1262
+ write: data => tui.terminal.write(data),
1263
+ });
1137
1264
  const hintRemaining = (activeMinimalTurn?.shortcutHintUntil ?? 0) - Date.now();
1138
1265
  if (hintRemaining > 0) {
1139
1266
  shortcutTimer = setTimeout(() => tui.requestRender(), hintRemaining);
@@ -1142,6 +1269,9 @@ export default function (pi: ExtensionAPI) {
1142
1269
  // Native info notifications use dim; warning/error notifications retain
1143
1270
  // their position in the transcript. No plugin names or message matching.
1144
1271
  const dimPrefix = theme.fg("dim", "\u0000").split("\u0000")[0];
1272
+ // Startup model diagnostics are reprinted into the resource header by /new and /reload.
1273
+ // Read the live predicate on every frame: the header is replaced after this factory returns.
1274
+ const hideStartupLine = (line: string) => line.replace(/\x1b\[[0-9;]*m/g, "").includes("No models match pattern");
1145
1275
  // Transcript hover wrappers must surround the compact widget handlers;
1146
1276
  // unmount in reverse order so neither adapter resurrects stale handlers.
1147
1277
  restoreAgentWidgets = attachAgentWidgets(tui, theme, () => subAgentsExpanded, undefined, true);
@@ -1178,6 +1308,7 @@ export default function (pi: ExtensionAPI) {
1178
1308
  },
1179
1309
  isPrompt: text => !!activeUIPrompt && (!activeUIPrompt.title || text.includes(activeUIPrompt.title)),
1180
1310
  isTransient: text => !!dimPrefix && text.startsWith(dimPrefix),
1311
+ hideStartupLine,
1181
1312
  });
1182
1313
  lastAttachMode = typeof tui.mode === "string" ? tui.mode : undefined;
1183
1314
  if (!restoreTranscript) {
@@ -1199,7 +1330,7 @@ export default function (pi: ExtensionAPI) {
1199
1330
  saveStatuses();
1200
1331
  lastStatusRead = Date.now();
1201
1332
  }
1202
- if (changed || Date.now() >= view.agentExpiry() || activeMinimalTurn?.running || statuses.some(status => /^(running|active|starting|queued|pending)$/.test(String(status.state)))) tui.requestRender();
1333
+ 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
1334
  }, 100);
1204
1335
  waitingTimer.unref();
1205
1336
  }
@@ -1383,11 +1514,22 @@ export default function (pi: ExtensionAPI) {
1383
1514
  minimalToolOutputIndices.clear();
1384
1515
  mountMinimalOutput(ctx);
1385
1516
  ctx.ui.setFooter((tui, theme, footerData) => {
1517
+ restoreScrollbar?.();
1518
+ scrollbarRoot = undefined;
1519
+ const syncScrollbar = () => {
1520
+ const root = (tui as typeof tui & { layoutRoot?: unknown }).layoutRoot;
1521
+ if (root === scrollbarRoot) return;
1522
+ restoreScrollbar?.();
1523
+ scrollbarRoot = root;
1524
+ restoreScrollbar = installSeamlessScrollbar(tui, theme);
1525
+ };
1526
+ syncScrollbar();
1386
1527
  refreshFooter = () => tui.requestRender();
1387
1528
  return {
1388
1529
  dispose: footerData?.onBranchChange?.(() => tui.requestRender()),
1389
1530
  invalidate() {},
1390
1531
  render(width: number): string[] {
1532
+ syncScrollbar();
1391
1533
  // switchTuiMode does not re-run setWidget; remount once the live renderer is fullscreen.
1392
1534
  if (settings["pi-mini-mode-minimal-show"] && !nativeOutput && ctx.mode === "tui" && !restoreTranscript
1393
1535
  && tui.mode !== "regular" && lastAttachMode === "regular" && !remountQueued) {
@@ -1435,8 +1577,15 @@ export default function (pi: ExtensionAPI) {
1435
1577
  });
1436
1578
  pi.on("model_select", refresh);
1437
1579
  pi.on("thinking_level_select", refresh);
1438
- const writeThinkingLine = (turn: MinimalTurn, blockIndex: number, line: string): number => {
1439
- const existing = minimalMessageIndices.get(blockIndex);
1580
+ const writeThinkingLine = (turn: MinimalTurn, content: Array<Record<string, unknown>>, blockIndex: number, line: string): number => {
1581
+ let existing = minimalMessageIndices.get(blockIndex);
1582
+ if (continuesEmptyThinking(content, blockIndex)) {
1583
+ existing = minimalMessageIndices.get(blockIndex - 1);
1584
+ if (existing !== undefined) minimalMessageIndices.set(blockIndex, existing);
1585
+ } else if (existing !== undefined && [...minimalMessageIndices].some(([block, index]) => block < blockIndex && index === existing)) {
1586
+ // A provisional empty block can acquire its own body on a later update.
1587
+ existing = undefined;
1588
+ }
1440
1589
  if (existing === undefined) {
1441
1590
  const index = turn.process.length;
1442
1591
  minimalMessageIndices.set(blockIndex, index);
@@ -1455,6 +1604,7 @@ export default function (pi: ExtensionAPI) {
1455
1604
  activeMinimalTurn.final = pendingMinimalFinal;
1456
1605
  activeMinimalTurn.running = false;
1457
1606
  activeMinimalTurn.thinking = undefined;
1607
+ promptView?.resetProcessView();
1458
1608
  }
1459
1609
  const question = contentText(event.message.content) || "[Attachment]";
1460
1610
  processExpanded = false;
@@ -1471,6 +1621,10 @@ export default function (pi: ExtensionAPI) {
1471
1621
  }
1472
1622
  if (event.message.role !== "assistant") return;
1473
1623
  // Background completions can start a new assistant turn without a user message.
1624
+ if (!activeMinimalTurn?.running) {
1625
+ processExpanded = false;
1626
+ promptView?.resetProcessView();
1627
+ }
1474
1628
  activeMinimalTurn ??= minimalTurns.at(-1);
1475
1629
  if (activeMinimalTurn) {
1476
1630
  freezeThinkingClock(activeMinimalTurn, activeMinimalTurn.thinking);
@@ -1497,14 +1651,17 @@ export default function (pi: ExtensionAPI) {
1497
1651
  if (partial.content.length) activeMinimalTurn.awaitingResponse = false;
1498
1652
  for (const [blockIndex, item] of partial.content.entries()) {
1499
1653
  if (item.type !== "thinking") continue;
1500
- const line = `thinking ${processText(item.thinking ?? item.text)}`;
1501
- const index = writeThinkingLine(activeMinimalTurn, blockIndex, line);
1654
+ const line = `thinking ${thinkingText(item)}`;
1655
+ const index = writeThinkingLine(activeMinimalTurn, partial.content, blockIndex, line);
1502
1656
  if (blockIndex === partial.content.length - 1 && event.assistantMessageEvent.type !== "thinking_end") {
1503
1657
  activeMinimalTurn.thinking = index;
1504
- } else {
1505
- freezeThinkingClock(activeMinimalTurn, index);
1506
1658
  }
1507
1659
  }
1660
+ for (const index of new Set(minimalMessageIndices.values())) {
1661
+ if (index === activeMinimalTurn.thinking) {
1662
+ delete ensureThinkingClock(activeMinimalTurn, index).endedAt;
1663
+ } else freezeThinkingClock(activeMinimalTurn, index);
1664
+ }
1508
1665
  if (previousThinking !== undefined && previousThinking !== activeMinimalTurn.thinking) {
1509
1666
  freezeThinkingClock(activeMinimalTurn, previousThinking);
1510
1667
  }
@@ -1550,9 +1707,9 @@ export default function (pi: ExtensionAPI) {
1550
1707
  if (activeMinimalTurn && Array.isArray(content)) {
1551
1708
  for (const [blockIndex, item] of (content as Array<Record<string, unknown>>).entries()) {
1552
1709
  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)}`;
1710
+ const line = `${item.type === "thinking" ? "thinking" : "output"} ${item.type === "thinking" ? thinkingText(item) : processText(item.text)}`;
1554
1711
  if (item.type === "thinking") {
1555
- freezeThinkingClock(activeMinimalTurn, writeThinkingLine(activeMinimalTurn, blockIndex, line));
1712
+ freezeThinkingClock(activeMinimalTurn, writeThinkingLine(activeMinimalTurn, content, blockIndex, line));
1556
1713
  continue;
1557
1714
  }
1558
1715
  const index = minimalMessageIndices.get(blockIndex);
@@ -1578,7 +1735,7 @@ export default function (pi: ExtensionAPI) {
1578
1735
  freezeThinkingClock(activeMinimalTurn, activeMinimalTurn.thinking);
1579
1736
  activeMinimalTurn.thinking = undefined;
1580
1737
  activeMinimalTurn.awaitingResponse = false;
1581
- (activeMinimalTurn.agentCalls ??= []).push(agentCall(event.toolCallId, event.toolName, event.args));
1738
+ (activeMinimalTurn.agentCalls ??= []).push({ ...agentCall(event.toolCallId, event.toolName, event.args), startedAt: toolStarts.get(event.toolCallId) });
1582
1739
  pushProcess(activeMinimalTurn, "call", event.toolCallId);
1583
1740
  (activeMinimalTurn.waitingTools ??= []).push({ id: event.toolCallId, name: event.toolName, startedAt: Date.now() });
1584
1741
  }
@@ -1620,6 +1777,7 @@ export default function (pi: ExtensionAPI) {
1620
1777
  const call = activeMinimalTurn?.agentCalls?.find(call => call.id === event.toolCallId);
1621
1778
  if (call) {
1622
1779
  if (activeMinimalTurn) activeMinimalTurn.waitingTools = activeMinimalTurn.waitingTools?.filter(tool => tool.id !== event.toolCallId);
1780
+ call.endedAt = Date.now();
1623
1781
  call.state = event.isError ? "error" : "done";
1624
1782
  call.output = contentText(event.result) || (event.isError ? "Call failed (no text details)" : "Call returned (background task status below)");
1625
1783
  refresh();
@@ -1644,16 +1802,23 @@ export default function (pi: ExtensionAPI) {
1644
1802
  if (!activeMinimalTurn) return;
1645
1803
  for (const turn of minimalTurns) {
1646
1804
  freezeOpenThinkingClocks(turn);
1805
+ if (turn.running) turn.endedAt = Date.now();
1647
1806
  turn.running = false;
1648
1807
  turn.thinking = undefined;
1649
1808
  }
1650
1809
  activeMinimalTurn.final = pendingMinimalFinal;
1810
+ processExpanded = false;
1811
+ subAgentsExpanded = false;
1812
+ promptView?.resetProcessView();
1651
1813
  activeMinimalTurn = undefined;
1652
1814
  pendingMinimalFinal = "";
1653
1815
  minimalToolOutputIndices.clear();
1654
1816
  refreshMinimalOutput();
1655
1817
  });
1656
1818
  pi.on("session_shutdown", () => {
1819
+ restoreScrollbar?.();
1820
+ restoreScrollbar = undefined;
1821
+ scrollbarRoot = undefined;
1657
1822
  // In-flight startup checks this generation before installing its server.
1658
1823
  settingsWebGeneration++;
1659
1824
  settingsWeb?.close();
@@ -1664,6 +1829,7 @@ export default function (pi: ExtensionAPI) {
1664
1829
  persistAgentStatuses?.();
1665
1830
  persistAgentStatuses = undefined;
1666
1831
  agentDeadlines.clear();
1832
+ promptView?.dispose();
1667
1833
  promptView = undefined;
1668
1834
  if (shortcutTimer) clearTimeout(shortcutTimer);
1669
1835
  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,102 @@
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, allowMissing = false): 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) || (allowMissing
44
+ && !/[*?]/.test(span.path)
45
+ && /^(?:!\[|\/|~\/|\.{1,2}\/|[a-z]:[\\/])/i.test(source.slice(span.start, span.end))))
46
+ .sort((a, b) => a.start - b.start);
47
+ }
48
+
49
+ /** Keep explicit image references compact even after clipboard files have expired. */
50
+ export function imagePlaceholders(source: string, cwd: string): string {
51
+ const spans = assistantImageSpans(source, cwd, true);
52
+ for (let index = spans.length - 1; index >= 0; index--) {
53
+ const span = spans[index];
54
+ source = source.slice(0, span.start) + fileLink(` 图片 ${index + 1}`, span.path, false) + source.slice(span.end);
55
+ }
56
+ return source;
57
+ }
58
+
59
+ /** Load once outside render, then reuse Pi's Image IDs and complete height rows. */
60
+ export function createAssistantImages(cwd: () => string, requestRender: () => void, write: (data: string) => void = () => {}) {
61
+ const cache = new Map<string, { image?: Component & { getImageId?(): number | undefined }; pending?: Promise<void> }>();
62
+ let disposed = false;
63
+ return {
64
+ render(source: string, width: number, markdown: (text: string, width: number) => string[], owner = source): string[] {
65
+ const spans = assistantImageSpans(source, cwd());
66
+ if (!spans.length) return markdown(source, width);
67
+ const rows: string[] = [];
68
+ let cursor = 0;
69
+ for (const span of spans) {
70
+ const before = source.slice(cursor, span.start).trim();
71
+ if (before) rows.push(...markdown(before, width));
72
+ const key = JSON.stringify([owner, span.start, span.path]);
73
+ let entry = cache.get(key);
74
+ if (!entry) {
75
+ entry = {};
76
+ cache.set(key, entry);
77
+ const target = entry;
78
+ target.pending = readPreview(span.path, cwd()).then(preview => {
79
+ if (disposed) return;
80
+ if (preview?.kind === "image") target.image = new Image(preview.base64, preview.mimeType, { fallbackColor: text => text }, { filename: span.path });
81
+ target.pending = undefined;
82
+ requestRender();
83
+ }).catch(() => { target.pending = undefined; });
84
+ }
85
+ if (entry.image) rows.push(...entry.image.render(width).map(commitImageCursor));
86
+ else rows.push(...markdown(source.slice(span.start, span.end).startsWith("![") ? span.path : source.slice(span.start, span.end), width));
87
+ cursor = span.end;
88
+ }
89
+ const after = source.slice(cursor).trim();
90
+ if (after) rows.push(...markdown(after, width));
91
+ return rows;
92
+ },
93
+ dispose() {
94
+ disposed = true;
95
+ for (const entry of cache.values()) {
96
+ const id = entry.image?.getImageId?.();
97
+ if (id !== undefined) write(deleteKittyImage(id));
98
+ }
99
+ cache.clear();
100
+ },
101
+ };
102
+ }
package/lib/file-links.ts CHANGED
@@ -65,6 +65,31 @@ 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
+ const hyperlinks = inputCapabilities().hyperlinks;
74
+ // Image chips already carry a complete target; never shorten or relink it.
75
+ return text.split(/(\x1b\]8;[^\x07]*\x07[\s\S]*?\x1b\]8;;\x07)/g).map((part, index) => {
76
+ if (index % 2) return part;
77
+ if (!hyperlinks) return shorten(part);
78
+ // A path tool's entire argument can contain spaces or punctuation without quotes.
79
+ const matches = part && !/[\x00-\x1f\x7f]/.test(part) && existsSync(localPath(part, cwd))
80
+ ? [{ path: part, start: 0, end: part.length }] : filePaths(part);
81
+ let result = "", offset = 0;
82
+ for (const match of matches) {
83
+ const path = localPath(match.path, cwd);
84
+ result += shorten(part.slice(offset, match.start));
85
+ const label = shorten(part.slice(match.start, match.end));
86
+ result += existsSync(path) ? fileLink(label, path, false) : label;
87
+ offset = match.end;
88
+ }
89
+ return result + shorten(part.slice(offset));
90
+ }).join("");
91
+ }
92
+
68
93
  /** Display-only: normalize local targets without changing persisted messages or remote URLs. */
69
94
  export function linkMessageFiles(text: string, cwd: string): string {
70
95
  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
+ }
@@ -11,7 +11,7 @@ interface StickyToolView {
11
11
  /** ponytail: Pi 0.85 layoutRoot + optional internal layout-node export;
12
12
  * replace discovery with a public primary-scroll/layout getter when available. */
13
13
  export function attachStickyTool(tui: unknown, document: Component, view: StickyToolView, setMinHeight: (height: number) => void = () => {}): (() => void) | undefined {
14
- const host = tui as { mode?: string; terminal?: { rows: number }; layoutRoot?: Component; setLayoutRoot?: (root: Component) => void; requestRender?: () => void };
14
+ const host = tui as { mode?: string; terminal?: { rows: number }; layoutRoot?: Component; setLayoutRoot?: (root: Component) => void; requestRender?: () => void; scrollToEndIndicator?: () => string };
15
15
  if (host.mode !== "fullscreen" || !host.layoutRoot || !host.setLayoutRoot || !host.requestRender) return;
16
16
  let getNode: typeof GetLayoutNode;
17
17
  try { getNode = createRequire(import.meta.url)("@earendil-works/pi-tui/dist/layout-node.js").getLayoutNode; }
@@ -41,12 +41,20 @@ export function attachStickyTool(tui: unknown, document: Component, view: Sticky
41
41
  const transcript = scroll;
42
42
  let currentId: string | undefined;
43
43
  let shown: { id: string; line: string } | undefined;
44
+ let contentHeight = 0;
45
+ // Pi shows this indicator whenever follow-end is suspended, including at the
46
+ // content end. Keep expansion's reading position but only hint at hidden rows.
47
+ const indicatorDescriptor = Object.getOwnPropertyDescriptor(host, "scrollToEndIndicator");
48
+ const originalIndicator = host.scrollToEndIndicator;
49
+ const indicator = () => transcript.scrollTop + transcript.viewportHeight < contentHeight
50
+ ? originalIndicator?.call(host) ?? "" : "";
51
+ if (originalIndicator) host.scrollToEndIndicator = indicator;
44
52
  const heading: Component = {
45
53
  invalidate() {},
46
54
  render(width) {
47
55
  // Measure the unchanged document before moving the existing ScrollView.
48
56
  setMinHeight(0);
49
- document.render(transcript.getContentWidth(width));
57
+ contentHeight = document.render(transcript.getContentWidth(width)).length;
50
58
  const target = view.pinnedTool();
51
59
  if (!target) {
52
60
  currentId = undefined;
@@ -95,6 +103,10 @@ export function attachStickyTool(tui: unknown, document: Component, view: Sticky
95
103
  return () => {
96
104
  view.unpinTool();
97
105
  setMinHeight(0);
106
+ if (host.scrollToEndIndicator === indicator) {
107
+ if (indicatorDescriptor) Object.defineProperty(host, "scrollToEndIndicator", indicatorDescriptor);
108
+ else delete host.scrollToEndIndicator;
109
+ }
98
110
  if (host.layoutRoot === root) host.setLayoutRoot!(originalRoot);
99
111
  };
100
112
  }
@@ -0,0 +1,35 @@
1
+ import { Text, visibleWidth } from "@earendil-works/pi-tui";
2
+ import { stripVTControlCharacters } from "node:util";
3
+
4
+ const sentences = new Intl.Segmenter(undefined, { granularity: "sentence" });
5
+ const words = new Intl.Segmenter(undefined, { granularity: "word" });
6
+ const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
7
+
8
+ /** Latest sentence, retaining its predecessor while a new sentence is still short. */
9
+ export function thinkingPreview(source: string, columns: number, maxRows = 1): string {
10
+ if (columns <= 0) return "";
11
+ const paragraphs = stripVTControlCharacters(source).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, " ")
12
+ .split(/\n+/).map(line => line.replace(/\s+/g, " ").trim()).filter(Boolean);
13
+ const paragraph = paragraphs.at(-1) ?? "";
14
+ if (!paragraph) return "";
15
+ const parts = [...sentences.segment(paragraph)].map(part => part.segment.trim()).filter(Boolean);
16
+ let latest = parts.at(-1) ?? paragraph;
17
+ if (visibleWidth(latest) < 12 && parts.length > 1) latest = `${parts.at(-2)} ${latest}`;
18
+ const fits = (text: string) => visibleWidth(text) <= columns * maxRows && new Text(text, 0, 0).render(columns).length <= maxRows;
19
+ if (fits(latest)) return latest;
20
+
21
+ // Keep a contiguous suffix starting at a word boundary instead of sliding mid-word.
22
+ let suffix = "";
23
+ for (const { segment } of [...words.segment(latest)].reverse()) {
24
+ if (!fits(`…${(segment + suffix).trimStart()}`)) break;
25
+ suffix = segment + suffix;
26
+ }
27
+ if (!suffix.trim()) {
28
+ // An oversized word/path still respects emoji and combining-character boundaries.
29
+ for (const { segment } of [...graphemes.segment(latest)].reverse()) {
30
+ if (!fits(`…${segment + suffix}`)) break;
31
+ suffix = segment + suffix;
32
+ }
33
+ }
34
+ return suffix.trim() ? `…${suffix.trimStart()}` : "";
35
+ }
@@ -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,12 +1,13 @@
1
1
  {
2
2
  "name": "@each1024/pi-mini-mode",
3
- "version": "2.0.3",
3
+ "version": "2.0.6",
4
4
  "description": "A compact Pi footer with live usage metrics, theme-aware settings previews, and configurable progress bars.",
5
5
  "type": "module",
6
6
  "scripts": {
7
7
  "check": "tsc --noEmit -p tsconfig.json",
8
8
  "test": "node test/settings-web.mjs && node test/footer-tidy.mjs && node test/footer-status-self-check.mjs && node test/settings-interaction.mjs && node test/transcript-adapter.mjs && node test/prompt-folding.mjs && node test/tool-folding.mjs && node test/sticky-tool.mjs && node test/minimal-markdown.mjs && node test/agent-view.mjs && node test/publish-self-check.mjs && node test/compaction-transcript.mjs && node test/input-enhancements.mjs && node test/user-message-surface.mjs && node test/settings-package.mjs",
9
- "prepublishOnly": "node scripts/publish.mjs --check && npm run check && npm test"
9
+ "prepublishOnly": "node scripts/publish.mjs --check && npm run check",
10
+ "release": "node scripts/release.mjs"
10
11
  },
11
12
  "license": "MIT",
12
13
  "author": "eachann1024",
@@ -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",