pi-pretty-tui 0.3.1 → 0.3.3

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
@@ -2,18 +2,9 @@
2
2
 
3
3
  English | [简体中文](./README.zh-CN.md)
4
4
 
5
- A beautiful, polished TUI for the [Pi coding agent](https://pi.dev/).
5
+ A cleaner, theme-aware interface for the [Pi coding agent](https://pi.dev/), with collapsible tools and thoughts, rounded message cards, and convenient copying.
6
6
 
7
- ## Features
8
-
9
- - **Collapsible activity timeline:** instead of filling the conversation with individual calls, thoughts, tools, and ordinary `info` notifications share one chronological activity stream. Work appears beneath a single `Running(...)` row and settles into a quiet `Done(...)` row. Parent rows show a combined total of top-level and nested tool calls, plus thoughts; expanding one reveals every ordered member with summaries retained above nested details. Thoughts and tools are peers: a turn that calls no tool still gets its own `Running(1 thought)` / `Done(1 thought)` parent row with the Thought as its child, so thinking is never dropped.
10
- - **Live working duration:** in all three modes, elapsed time appears beside `Working` in the prompt editor's top border, using the border's own color. It shares the agent-run clock and duration format with the completion footer, includes automatic retries, and disappears when the run settles. Narrow editors omit the timer when it cannot fit. The clean-mode `Running` parent dot alternates between the prompt editor’s current border color and `dim` about every 800 ms; its label uses that same border color, and tool dots stay stable, and the pulse stops when the run settles. Expanded `Done` titles and markers use the theme's `success` color; collapsed summary dots, titles, and details use `dim`.
11
- - **Transient UI status:** one line above the editor shows direct Pi UI feedback such as Thinking/tool-output visibility changes. A newer UI status replaces it, and it disappears automatically after ten seconds without entering the transcript or session.
12
- - **Durable response footers:** once the complete agent run settles—including tools, retries, and compaction—the final answer ends with one quiet gray divider containing the elapsed-work time and, in fullscreen, a `[Copy]` control. It copies only the final visible answer, excluding thoughts, tools, statuses, and the footer itself; the footer survives reloads and session-tree navigation.
13
- - **Useful details on demand:** tool-aware summaries keep paths, commands, results, diffs, file previews, and live shell output concise without removing access to the original content.
14
- - **A cohesive visual finish:** user messages use a rounded border in the theme's heading color (`mdHeading`, warm amber in the default theme), distinct from blue `mdLink` thoughts. Full and compact use background-filled, full-width `User` panels matching Assistant cards. Clean keeps transparent, right-aligned, content-sized bubbles, wrapping long messages at 75% of the terminal width without a `User` label. Together with the rounded prompt input, theme-aware colors, clear Markdown heading hierarchy, cleaner lists, and rounded syntax-highlighted code blocks, they make the entire TUI feel intentional. In fullscreen, each fenced code block also includes a native-feeling `[Copy]` control.
15
-
16
- Clean uses purpose-built compact views for Pi's built-in `read`, `bash`, `edit`, `write`, `grep`, `find`, and `ls` tools. Compact uses concise summaries when folded and the same native detail cards as full when expanded. Third-party tools without nested calls automatically receive a consistent compact row; opening it preserves its native renderer while removing conflicting terminal background colors. User and steering messages, compaction summaries, visible assistant text, warnings, errors, aborted/truncated responses, and displayed custom messages with a registered renderer create hard group boundaries. Pi's cursor, IME, autocomplete, and tool execution behavior remain intact; fullscreen mouse additions are described below.
7
+ ![pi-pretty-tui clean mode with expandable tool activity and copy controls](./assets/screenshot.png)
17
8
 
18
9
  ## Install
19
10
 
@@ -21,119 +12,71 @@ Clean uses purpose-built compact views for Pi's built-in `read`, `bash`, `edit`,
21
12
  pi install npm:pi-pretty-tui
22
13
  ```
23
14
 
24
- Restart Pi or run `/reload` after installation.
25
-
26
- pi-pretty-tui registers renderers without replacing tool implementations. Extensions that provide tools with built-in names, such as `bash`, keep their own execution and renderers.
27
-
28
- ## Working with tool calls
29
-
30
- Click a `Running(...)` or `Done(...)` row to keep it as a parent and reveal tools, completed `● thought` entries, and extension updates beneath it. Click an individual tool or thought to reveal nested details without replacing its summary. The last item in each expanded tree, `└─ [↑ Collapse]`, collapses just that group without scrolling back to its parent; clicking the parent also works. In clean mode, `Ctrl+O` only shows a hint to use these local disclosures; it does not expand or collapse content. Full and compact modes retain Pi's native global tool-output expansion. Third-party replacements for `grep` and `find` (such as FFF) use compact tree rows too, with their native details available when expanded. Compact tool names use bold `text`, parameters use `muted`, and running tool dots use `dim`; success/error dots keep their corresponding theme colors. Thought dots use `mdLink`, titles use bold `text`, and detail body text uses `muted`. Tool names use each definition's `label` verbatim, falling back to its raw `name`; pi-pretty-tui does not rename or title-case them.
31
-
32
- In clean and compact, extension calls to `ctx.ui.notify(message, "info")` (or with the type omitted) use the same presentation. Clean joins them to current thought/tool work, while compact displays them independently. Warnings and errors stay standalone, use `⚠` and `✕`, and form hard boundaries. Tool failures remain owned by their tool details. Full delegates info, warning, and error delivery to Pi's original methods, retaining its message text, individual occurrences, and status behavior.
33
-
34
- In clean mode, Pi's native cache-miss notices join the thought/tool group of the assistant message that incurred the miss, as a yellow `⚠` child. They hide and reveal with the group and do not interrupt subsequent tool calls. If that message has no associated work (for example, a text-only final answer), the notice remains independent. Pi still decides whether a notice should appear and formats its token count, cost, model-switch and idle-gap labels; the integration hooks `addCacheMissNotice()` rather than matching text. Historical notices are re-derived on rebuild, not written as extra session entries. Full and compact show the same warning independently, without an activity-group wrapper.
35
-
36
- In clean and compact, displayed custom messages without their own renderer use one generic accent-coloured `◇` Markdown presentation: they join current thought/tool work when it exists, otherwise remain independent, and preserve their session persistence. Messages with a registered renderer remain completely native and form hard boundaries. Full retains native custom-message rendering as well. These decisions use only Pi's notification type and renderer presence—never extension names, custom message names, or content heuristics.
37
-
38
- In clean and compact, Pi's direct internal `showStatus()` feedback is transient: it appears only in the status line above the editor, a newer status replaces it, and a ten-second timer removes it. It never enters the transcript or activity timeline and is cleared on reload. In clean mode, `Ctrl+T` and `Ctrl+O` only show short hints to click the corresponding disclosure; neither changes visibility or Pi's Thinking setting. In full and compact modes, both shortcuts keep Pi's native behaviour. Full also preserves native `showStatus()` delivery instead of removing transcript feedback on a ten-second timer.
39
-
40
- Visible assistant text remains outside activity trees even when a later update to the same message introduces thinking. Repeated updates do not close a separate, subsequent tool group.
15
+ Restart Pi or run `/reload`.
41
16
 
42
- `read` range labels accept numeric strings and omitted/null fields without concatenating line numbers; malformed range values omit the label. Expanded `edit` diffs use a fixed, right-aligned line-number gutter followed by a separate `+`/`-` column. Wrapped code aligns with the content column, preserving code indentation and theme diff colors.
17
+ ## Rendering modes
43
18
 
44
- ## Error presentation
19
+ Run `/pretty-tui` to open settings and choose a mode:
45
20
 
46
- In clean and compact modes, standalone errors keep their original title and complete text in a compact `✕ Error · reason` layout. Consecutive errors with exactly the same source type, title, and full text share one visible row with a dim `×2` / `×3` count. Other transcript components break the run; errors carrying thought/tool/visible-response content are not folded. This is UI-only: session records and original message components remain unchanged. Long errors wrap without an added preview truncation. Full mode keeps native assistant error text and individual occurrences; it does not merge errors into a repetition count.
21
+ | Mode | Experience |
22
+ |---|---|
23
+ | **clean** (default) | Group tools and thoughts into a collapsible `Running` / `Done` timeline. |
24
+ | **compact** | Show separate tool and thought cards with concise previews; expand for details. |
25
+ | **full** | Keep Pi's native details and interactions inside themed cards, with thoughts initially expanded. |
47
26
 
48
- ## Codemode and nested tools
27
+ All modes include rounded messages and code blocks, syntax highlighting, a live working timer, and final-answer duration and copy controls. Clean and compact also support expandable nested-tool trees.
49
28
 
50
- Clean and compact modes share the same nested-tool presentation. Tools that call other tools through Pi's nested execution API keep their own parent node. In clean mode, expand the activity group first; in compact mode, each parent appears independently without an activity-group wrapper. Both show each internal call, its status, compact arguments, duration, and result summary. Click an internal call to inspect its arguments and text result independently. Click its expanded body to collapse just that call. Script and script-output bodies also collapse their own sections when clicked. Tool calls use a `●` marker: dim while running, success-colored when successful, and error-colored when failed. Tool names use bold theme text. `[Script]` and `[Script output]` are separate disclosures; the nested parent title is informational and clicking it does not expand or collapse details. Use each section or child to expand and collapse its own details; `Ctrl+O` only shows a hint in clean mode. Extensions can still use Pi's `setToolsExpanded()` API for global control; local disclosures remain usable afterward, and another global API call resets the local overrides. Calls retain their start order even when they finish in parallel. A handled child failure remains marked as failed even if the script succeeds.
29
+ Click activity rows, tool titles or thought entries to expand and collapse details. In clean, use these local controls; in compact and full, Pi's `Ctrl+O` and `Ctrl+T` shortcuts remain available.
51
30
 
52
- The activity-group summary combines top-level and nested calls: one parent call plus three internal calls displays as `4 tool calls`. The parent call itself counts once, while its node retains the nested-call count and tree structure. Internal calls never become phantom transcript members or displace the end-of-tree collapse action. Ownership uses Pi's `parentToolCallId`, not tool names or JavaScript parsing; wrappers other than codemode benefit too. This requires a Pi version with nested execution events (0.99.0 or later); older Pi keeps its existing display. Full mode uses codemode's own native renderer inside a tool card. It does not append additional child details from pretty-tui snapshots; visible information, native disclosures, and keyboard controls follow Pi. Clean and compact share nested execution state, history snapshots, status handling, and local child disclosures; global expansion resets their local overrides.
31
+ | Command | Action |
32
+ |---|---|
33
+ | `/pretty-tui clean` | Switch to clean mode |
34
+ | `/pretty-tui compact` | Switch to compact mode |
35
+ | `/pretty-tui full` | Switch to full mode |
36
+ | `/pretty-tui enable` / `/pretty-tui disable` | Enable or disable the extension and reload |
37
+ | `/pretty-tui status` | Show current settings |
53
38
 
54
- Child text results and edit diffs are saved in hidden, UI-only session entries for reload and branch navigation. Each root retains at most 256 calls, 4,096 characters of arguments per call, 8,192 characters of text per result, and 131,072 characters of arguments/results in total; truncation is indicated. Detail previews also have a 200-line limit, and nested trees display up to eight levels below the root. Old sessions without a snapshot explicitly show that only call metadata was retained. Nested results currently use a generic text presentation, not each third-party renderer, and images are not stored in these snapshots. Root media and the parent's original renderer remain available in full mode.
39
+ Settings persist across sessions. Disabling the extension restores Pi's native appearance.
55
40
 
56
- These UI entries do not change the script's output or the model's tool results. They **do** save child text that a script may never have printed: treat session files as potentially sensitive. Common credential argument keys are redacted; tool output is not guaranteed to be free of secrets.
41
+ ### Repeated errors
57
42
 
58
- ## Settings and rendering modes
43
+ In clean and compact, adjacent standalone errors can share the first complete error and a `[×2]` / `[×3]` count even when trace, request or correlation IDs change. Source type, title and surrounding text must match exactly; only standalone hexadecimal IDs (16–128 characters containing a letter) or UUIDs may differ. Short codes, numeric quantities and prefixed IDs such as `msg_...` / `rs_...` remain exact.
59
44
 
60
- Run `/pretty-tui` to open the extension settings. The `Enabled` switch persists whether pi-pretty-tui installs its render patches and built-in tool renderers. Changing it automatically runs Pi's official reload flow, so no manual `/reload` is needed. You can also use `/pretty-tui enable` and `/pretty-tui disable` directly. While disabled, the settings command remains available and Pi uses its native rendering.
45
+ Other transcript entries break the run; errors with thoughts, tool calls or visible answer text are not folded. In fullscreen, click the first error to expand or collapse the run. Expanded errors show every complete original error, aligned with the same prefix and without numbering; new retries preserve the expanded state. Session records remain unchanged. You can also use `/pretty-tui full` to see every occurrence and its original IDs.
61
46
 
62
- All modes retain the working timer, completion footer, and copy enhancements. Clean/compact use transient status feedback; full retains native status delivery. Clean places `● thought` entries in activity groups. Compact uses separate thought panels, collapsed by default with a first-line content preview (truncated to one terminal row) and a `▸` title indicator; click the title to reveal Markdown details (`▾`). Full preserves native thinking runs, their original order among answers, Markdown transforms, and per-run clicks; each run is decorated with a titled frame. Thoughts start expanded in full even if a saved compact/native setting was hidden. Manual folding and subsequent `Ctrl+T` visibility updates remain available.
47
+ ## Copying
63
48
 
64
- Full presents native Pi information and behavior in one consistent, theme-backed panel style. User, Assistant, thought and tool panels derive their fill from the corresponding outline color. Dark themes use the same hue with much lower lightness and chroma: blue, purple, green and red outlines produce deep matching tints, while neutral Assistant outlines produce a deep gray. Light themes use pale matching tints to preserve native dark-text contrast. Titles, outlines and bottom-border timing keep their semantic theme colors; color conversion is cached and follows theme/color-mode changes. Foreground syntax/diff colors survive, including ANSI resets inside native content, and native image protocol rows remain verbatim.
49
+ Start Pi in **fullscreen mode** to use mouse controls:
65
50
 
66
- Full and compact panels leave one terminal column of outer space on each side (none in very narrow terminals). These gutters retain the terminal background and apply consistently to User, Assistant, thought and tool panels.
67
-
68
- Each tool is one panel spanning the remaining width with the native call above an `Output` divider and the visible result below it. There are no separate result cards, connectors or result indentation. The output section appears only when native result content exists. Exterior layout whitespace is trimmed, while internal blank lines and image reservation rows remain. Separate tools retain two blank lines between panels. User cards fill the available width with a `User` title; adjacent answer blocks share one expanded `Assistant` card; thought cards remain expanded by default with local/native visibility controls.
69
-
70
- Built-in tools use Pi's original renderers, including previews, truncation/expansion controls and error details. Full-mode bash commands additionally use Pi's shell syntax highlighter for variables, strings, keywords and comments. Highlighting is cached by command and syntax palette; the native `$` prompt, original command text, timeout annotation and result output are preserved. Shell/codemode `Took`/`Elapsed` timing lives on the bottom border in the outline color; narrow panels keep native timing in the body when it cannot fit. Third-party renderers, media and native mouse handlers remain intact. Clean retains its activity grouping and transparent user bubbles. Compact shares the same panel surfaces, outline colors, gutter and User/Assistant cards, but defaults to concise tool parameters and result summaries. Standalone tool panel titles show `▸` when collapsed and `▾` when expanded. Click the title to toggle details, and use native `Ctrl+O` for global expansion. User/Assistant panels and informational nested-parent titles have no disclosure arrow. Expanded standalone tools use the same native renderer and panel projection as full, including shell highlighting, output boundaries and native timing, without compact tree connectors or result indentation. Nested wrappers retain independent script/output/child disclosures. Compact records `Took` on the border when a final duration is supplied by Pi; it does not invent missing timings. Extremely narrow terminals omit the outline while retaining the panel background.
71
-
72
- The extension supports three persistent rendering modes: `clean` (default), `compact`, and `full`. Choose one interactively, or use `/pretty-tui clean`, `/pretty-tui compact`, `/pretty-tui full`, and `/pretty-tui status` directly. Settings are stored in `~/.pi/agent/pretty-tui.json` or under the directory selected by `PI_CODING_AGENT_DIR`.
73
-
74
- | Mode | Third-party tools | Codemode and other nested callers |
75
- |---|---|---|
76
- | `clean` | Compact summaries inside activity groups; native details on expansion | Nested tree inside the group, with local disclosures |
77
- | `compact` | Concise independent panels; title toggles native details | Independent panel with parent/child tree and local script/output/child disclosures |
78
- | `full` | Native content and interactions in a titled card | Native codemode content and disclosures in a titled card; no added snapshot-only details |
79
-
80
- Full and compact keep Pi's native `Ctrl+O` global expansion. Shared projected rows preserve local controls afterward. These modes do not create clean-mode `Running/Done` activity wrappers.
81
-
82
- In fullscreen, interactive activity/tool rows and copy controls tolerate same-row horizontal pointer jitter of up to two terminal columns. Larger or vertical movement remains a drag; ordinary text selection, links, and Pi's double/triple-click behavior are unchanged.
51
+ ```sh
52
+ pi --tui-mode fullscreen
53
+ ```
83
54
 
84
- In compact and full, compaction summaries use a theme-colored `compaction ▸/▾` card. The original token count, shortcut hint and complete summary remain available; click the title/body or use native `Ctrl+O` to toggle expansion. Compaction cost notices remain separate. Clean retains Pi’s original compaction box.
55
+ - **User message:** click its body or border to copy the original text.
56
+ - **Code block:** click `[Copy]` to copy the code without its frame.
57
+ - **Final answer:** click `[Copy]` beside the response duration to copy the answer without thoughts or tool output.
85
58
 
86
- ## Optional border-free selection copying
59
+ Dragging selects text rather than copying a whole message. Links keep their normal behavior; image attachments are not included in text copies.
87
60
 
88
- The experimental **Selection copy** option excludes plugin borders, titles and layout padding from mouse-selected text in fullscreen mode. Literal box-drawing characters in content are preserved. It is **off by default** and applies to clean, compact and full.
61
+ ### Optional border-free selection
89
62
 
90
- Open `/pretty-tui` and select `Selection copy` to toggle it, or run:
63
+ Enable **Selection copy** in `/pretty-tui`, or run:
91
64
 
92
65
  ```text
93
66
  /pretty-tui selection-copy on
94
67
  /pretty-tui selection-copy off
95
68
  ```
96
69
 
97
- The choice is stored as `selectionCopy` in `pretty-tui.json`; toggling automatically reloads Pi. `/pretty-tui status` shows the configured value. When off, no selection-copy/compositor/terminal-write hooks or private row annotations are installed. Disabling the whole extension also disables this feature, while preserving its saved preference. Regular-mode terminal-owned selection is unchanged.
98
-
99
- This is an opt-in feature while terminal acceptance and internal-API compatibility are being evaluated. Long transcripts retain additional annotation memory; see [the exploration and GC measurements](docs/selection-copy-exploration.md) in the source repository.
100
-
101
- ## Copy user messages
102
-
103
- In fullscreen mode, left-click a user bubble's body or border to copy its complete original text, preserving Markdown, indentation, and line breaks without the bubble frame. Existing links and code-block `[Copy]` controls retain priority; dragging to select text does not trigger whole-message copy. Pi's native clipboard path provides copy feedback. This copies text, not image attachments. Regular mode keeps terminal-owned mouse selection and copying.
104
-
105
- ## Copy code blocks
106
-
107
- Rounded code-block lines and corners use `borderMuted`; language labels, `[Copy]`, and code text retain their existing colors.
108
-
109
- In fullscreen TUI mode, fenced Markdown code blocks in user and assistant transcript messages include a clickable `[Copy]` control in the top rule:
110
-
111
- ```sh
112
- pi --tui-mode fullscreen
113
- ```
114
-
115
- Clicking it copies only the code content—not the rounded border—through Pi's native fullscreen clipboard path and shows the same transient `Copied!` or `Copy failed` flash used by direct text selection. The control is hidden in regular TUI mode because the terminal keeps mouse input for text selection and scrolling there.
116
-
117
- ## Development
118
-
119
- Run the committed regression suite before changing renderer state or transcript grouping:
120
-
121
- ```sh
122
- npm install
123
- npm test
124
- ```
125
-
126
- The suite covers live and restored activity timelines, retries and terminal states, user/steering/compaction/native-renderer boundaries, ten-second UI-status replacement, stale-timer and flash cleanup on reload and shutdown, standalone severity styling, built-in and third-party tools, expandable thinking, parallel completion ownership, orphaned calls, duplicate-summary prevention, durable response timing and answer-only copy controls, adaptive user chat bubbles, complete prototype-patch restoration, and fullscreen code-block copy hit regions. It also uses Pi's real extension loader to check coexistence with a same-named replacement tool. GitHub Actions runs the same checks on every push and pull request.
127
-
128
- To additionally exercise a local checkout of [pi-bash-bg](https://github.com/mapleluvr/pi-bash-bg), set `PI_BASH_BG_EXTENSION` to its `index.ts` before running `npm test`. This optional integration test executes foreground and automatically backgrounded commands and checks their status and logs.
129
-
130
- ## Compatibility notice
70
+ This experimental option is **off by default**. In fullscreen mode, it removes UI borders, titles and layout padding from copied selections while preserving literal box-drawing characters in the content. It works in all three rendering modes; toggling it saves the setting and reloads Pi.
131
71
 
132
- The current development and regression-test baseline is **Pi 1.4.0**. User chat bubbles support its direct Markdown layout, using themed, full-width User panels in full/compact and transparent, content-sized bubbles in clean. Nested execution requires Pi 0.99.0 or later; this is a feature requirement, not a promise that every older Pi release is tested.
72
+ In regular mode, the terminal handles selection and copying, so this option has no border-removal effect. Fullscreen/regular is independent of clean/compact/full.
133
73
 
134
- Tool rendering uses Pi's documented extension APIs. Active-tool state follows Pi's built-in execution transitions through its exported interactive components. Clean-mode thought details use the activity hierarchy's own disclosure state; full and compact modes retain Pi's built-in Thinking visibility control. Rendering native user messages as adaptive chat bubbles, rounding the native prompt editor, changing unordered-list markers, and enhancing fenced code blocks require reload-safe runtime patches because Pi does not currently expose public renderer hooks for those presentation details. Markdown enhancements are activated only while rendering user and assistant messages in the main transcript; Markdown created by extension overlays keeps Pi's native layout. Markdown parsing, syntax highlighting, and terminal semantic zones remain handled by Pi.
74
+ ## Notes
135
75
 
136
- No Pi source files are modified. Runtime patches are removed during session shutdown, but a future Pi release may require this extension to be updated.
76
+ - Tested with **Pi 1.5.0**. Future Pi updates may require compatibility fixes.
77
+ - Keeps Pi's native input behavior and tool execution, including third-party tool implementations.
78
+ - Nested-tool text details are saved with sessions for restoration and may be truncated. Session files can contain sensitive tool output.
79
+ - See [Releases](https://github.com/ykn0309/pi-pretty-tui/releases) for changes and contributor acknowledgments.
137
80
 
138
81
  ## Uninstall
139
82
 
@@ -141,8 +84,8 @@ No Pi source files are modified. Runtime patches are removed during session shut
141
84
  pi remove npm:pi-pretty-tui
142
85
  ```
143
86
 
144
- Then restart Pi.
87
+ Restart Pi afterward.
145
88
 
146
89
  ## License
147
90
 
148
- MIT
91
+ [MIT](./LICENSE)
package/README.zh-CN.md CHANGED
@@ -2,18 +2,9 @@
2
2
 
3
3
  [English](./README.md) | 简体中文
4
4
 
5
- 为 [Pi coding agent](https://pi.dev/) 打造美观、精致的 TUI 体验。
5
+ 为 [Pi coding agent](https://pi.dev/) 提供更清爽的界面:可折叠的工具与思考、跟随主题的圆角卡片,以及便捷的复制操作。
6
6
 
7
- ## 功能特性
8
-
9
- - **可折叠的活动时间线:** 不再让大量独立调用填满对话。思考、工具和普通 `info` 通知会进入同一条按真实时间排序的活动流;工作进行时显示为 `Running(...)`,结束后变为低调的 `Done(...)`。父级合并统计顶层与嵌套工具调用总数,并单独显示思考数量;展开后可查看所有有序成员,成员摘要在展开嵌套详情后仍然保留。思考与工具地位相同:没有调用任何工具的那一轮同样会有自己的 `Running(1 thought)` / `Done(1 thought)` 父行,思考作为其子级,内容不会被丢弃。
10
- - **可持久化的回答 footer:** 整轮 Agent 工作真正 settled 后(包括工具、自动重试和 compaction),最终回答底部会显示一条低调的灰色分隔线,工作时长与 fullscreen 模式下的 `[Copy]` 控件都嵌在线中。`[Copy]` 只复制最终可见回答,不包含 thought、工具、状态或 footer;reload 和 session tree 切换后仍会保留。
11
- - **实时工作计时:** 三种模式下,耗时显示在输入框顶部边框的 `Working` 右侧,颜色与边框一致。它与完成 footer 共用 Agent 整轮工作的计时起点和时长格式,包含自动重试,工作真正结束后消失;窄输入框放不下时会隐藏计时。clean 模式下,`Running` 父节点圆点约每 800 ms 在输入框当前边框色和 `dim` 间切换;`Running` 文字使用相同边框色,工具圆点保持稳定,整轮结束后停止闪烁。展开后的 `Done` 标题和圆点使用主题的 `success` 色,折叠摘要的圆点、标题与内容统一使用 `dim`。
12
- - **临时 UI 状态:** 编辑器上方的一行只显示 Pi 直接产生的 UI 操作反馈,例如 Thinking 或工具输出可见性变化。新状态会替换旧状态,并在十秒后自动消失,不进入 transcript 或 session。
13
- - **按需查看有效信息:** 针对不同工具设计的摘要,会简洁呈现路径、命令、结果、diff、文件预览和实时 shell 输出,同时保留查看原始完整内容的能力。
14
- - **统一、精致的视觉体验:** 用户消息使用主题标题色(`mdHeading`,默认暖黄/琥珀色)的圆角边框,与蓝色 `mdLink` 思考区分。full 和 compact 使用带底色、铺满宽度的 `User` 面板,与 Assistant 卡片一致;clean 保留透明、右对齐、自适应宽度的气泡,长消息在终端宽度的 75% 处换行,不显示 `User` 标注。配合圆角输入框、主题感知配色、层级清晰的 Markdown 标题、更清爽的列表,以及带语法高亮的圆角代码块,让整个 TUI 更协调。在 fullscreen 模式下,每个围栏代码块还带有符合原生体验的 `[Copy]` 控件。
15
-
16
- clean 中,Pi 内置的 `read`、`bash`、`edit`、`write`、`grep`、`find` 和 `ls` 工具使用专门设计的紧凑视图;compact 折叠时显示简短摘要,展开后与 full 共用原生详情卡片。没有嵌套调用的第三方工具会自动获得统一的紧凑行,单独展开时继续使用原生 renderer,但会移除与整体冲突的终端背景色。用户与 steer 消息、compaction 摘要、可见 assistant 正文、warning、error、aborted/length 响应,以及注册了专用 renderer 的 displayed custom message 都会形成硬分组边界。同时不会影响 Pi 原有的光标、输入法、自动补全和工具执行行为;fullscreen 鼠标交互增强见下文。
7
+ ![pi-pretty-tui clean 模式:可展开的工具活动与复制入口](./assets/screenshot.png)
17
8
 
18
9
  ## 安装
19
10
 
@@ -23,117 +14,69 @@ pi install npm:pi-pretty-tui
23
14
 
24
15
  安装后重启 Pi,或运行 `/reload`。
25
16
 
26
- pi-pretty-tui 只注册渲染器,不替换工具实现。提供 `bash` 等内置同名工具的扩展仍使用自己的执行逻辑和 renderer。
27
-
28
- ## 使用工具调用
29
-
30
- 点击 `Running(...)` 或 `Done(...)` 行,可以保留父级并展开其下方的工具、已完成的 `● thought` 和扩展更新。点击单个工具或思考子项可在保留摘要的同时展开嵌套详情。每棵展开的树末尾都有 `└─ [↑ Collapse]`,无需滚回父级即可只折叠当前分组;再次点击父级也可以折叠。clean 模式下,`Ctrl+O` 只提示使用这些局部展开入口,不会展开或收起内容;full 和 compact 模式保留 Pi 原生的工具输出全局展开行为。第三方替换的 `grep`、`find`(如 FFF)也使用紧凑的树节点,展开子项时仍可查看原生详情。紧凑工具名使用 `text` 加粗,参数使用 `muted`,运行中工具圆点使用 `dim`,成功/失败圆点保留对应主题色。思考圆点使用 `mdLink`,标题使用 `text` 加粗,详情正文使用 `muted`。工具名称会原样使用定义中的 `label`,没有 `label` 时回退到原始 `name`;pi-pretty-tui 不再重命名或转换大小写。
31
-
32
- clean 和 compact 中,扩展调用 `ctx.ui.notify(message, "info")`(或省略 type)使用相同展示:clean 加入当前 thought/tool 活动组,compact 独立显示。warning 和 error 保持独立,使用 `⚠` 和 `✕` 并形成硬边界;工具失败归属于对应工具详情。full 将 info、warning、error 的投递委托给 Pi 原始方法,保留其文案、每次独立出现及状态行为。
33
-
34
- 在 clean 模式下,Pi 原生的 cache miss 提示以黄色 `⚠` 子节点加入产生该次缓存未命中的 assistant 消息所属的 thought/tool 活动组,随组折叠与展开,并且不会打断后续工具调用。如果该消息没有关联的工作(例如只输出正文的最终回答),提示保持独立。是否显示提示,以及 token 数、成本、模型切换和空闲时长等文案仍由 Pi 决定;接管的是 `addCacheMissNotice()` 入口,不匹配文本。历史提示在重建时重新推导,不额外写入会话记录。full 和 compact 使用相同的警告展示,独立显示,不包裹活动组。
35
-
36
- clean 和 compact 下,没有自有 renderer 的 displayed custom message 使用统一、accent 配色的 `◇` Markdown 显示:当前存在 thought/tool 工作时加入当前组,否则独立显示,并保留 session 持久化。注册了 renderer 的消息完全保留插件原生显示并形成硬边界。full 同样保留 custom message 的原生展示。所有判断只依据 Pi 的通知 type 和 renderer 是否存在,不识别扩展名称、custom message 名称,也不根据文本内容推断语义。
37
-
38
- clean 和 compact 中,Pi 内部直接调用 `showStatus()` 产生的反馈属于临时 UI 状态:它只显示在编辑器上方,新状态替换旧状态,并由十秒 timer 自动清除;它不会进入 transcript 或活动时间线,reload 时也会清除。在 clean 模式下,`Ctrl+T` 和 `Ctrl+O` 都只显示点击对应节点的简短提示,不改变内容可见性或 Pi 的 Thinking 设置。在 full 和 compact 模式下,两者保留 Pi 的原生行为。full 也保留原生 `showStatus()` 投递,不使用十秒 timer 删除 transcript 中的状态反馈。
39
-
40
- 即使同一消息的后续更新才加入思考,可见 assistant 正文也保持在活动树之外;重复更新不会关闭后续独立的工具活动组。
41
-
42
- `read` 行范围标签正确处理数字字符串及省略/null 参数,不再拼接出错误行号;无效范围值不显示范围标签。展开的 `edit` diff 使用固定宽度、右对齐的左侧行号栏,`+`/`-` 独占一列;长代码续行与正文列对齐,保留代码缩进及主题 diff 配色。
17
+ ## 展示模式
43
18
 
44
- ## 错误展示
19
+ 运行 `/pretty-tui` 打开设置,选择模式:
45
20
 
46
- clean 和 compact 模式下,独立错误保留原始标题和完整内容,以紧凑的 `✕ Error · 原因` 展示。来源类型、标题及完整内容完全一致的相邻错误合为一条可见行,并使用暗色 `×2` / `×3` 标识次数。其他 transcript 组件会打断计数;包含思考、工具或可见回答的错误不参与合并。合并仅影响 UI,不删除或修改会话记录及原始消息组件。长错误完整换行,不增加预览截断;full 保留原生 assistant 错误文案及每次独立出现,不将它们合并为重复计数。
21
+ | 模式 | 展示方式 |
22
+ |---|---|
23
+ | **clean**(默认) | 将工具与思考归入可折叠的 `Running` / `Done` 活动时间线。 |
24
+ | **compact** | 工具与思考分别显示为简洁卡片,展开查看详情。 |
25
+ | **full** | 在主题卡片中保留 Pi 原生详情与交互,思考默认展开。 |
47
26
 
48
- ## Codemode 与嵌套工具
27
+ 三种模式均提供圆角消息与代码块、语法高亮、实时工作计时,以及回答末尾的耗时和复制入口。clean 和 compact 还支持展开查看嵌套工具调用。
49
28
 
50
- clean 和 compact 模式共用嵌套工具展示。通过 Pi 嵌套执行 API 调用其他工具的工具保留自己的父节点;clean 模式先展开活动组,compact 模式直接显示独立的父子调用树,不包裹活动组。两者都会显示各内部调用的状态、紧凑参数、耗时和结果摘要;点击某个内部调用,可以独立展开其参数和文本结果;点击展开后的正文可收起该调用,脚本和脚本输出正文也可点击收起各自区块。工具统一使用 `●` 圆点:运行中为主题暗色,成功与失败分别为主题成功色与错误色;工具名使用正文色加粗。`[Script]` 和 `[Script output]` 分别控制脚本与汇总输出;嵌套父工具标题仅用于展示,点击不会展开或折叠详情。各区块或子调用通过自己的入口独立展开/收起,`Ctrl+O` 在 clean 模式下只显示提示。扩展仍可通过 Pi 的 `setToolsExpanded()` API 全局控制,之后也可局部展开/收起;再次调用全局 API 会重置局部状态。并行调用按照启动顺序排列,不会随完成顺序跳动。即使脚本捕获错误后成功,失败的子调用仍会明确标记。
29
+ 点击活动行、工具标题或思考条目可展开、收起详情。clean 使用这些局部入口;compact 和 full 保留 Pi 的 `Ctrl+O`、`Ctrl+T` 快捷键。
51
30
 
52
- 活动组摘要合并统计顶层与嵌套调用:一个父调用加三个内部调用显示为 `4 tool calls`,父调用本身也计一次;父工具节点仍保留子调用数量和树结构。内部调用不会变成不存在的顶层 transcript 成员,也不会挤掉树尾折叠按钮。归属依据 Pi 的 `parentToolCallId`,不依赖工具名或 JavaScript 源码解析,因此其他嵌套调用工具也适用。这需要支持嵌套执行事件的 Pi(0.99.0 及以后);旧版本保持原有显示。full 在工具卡片内使用 codemode 自己的原生 renderer,不额外追加 pretty-tui 快照中保存的子调用详情;可见信息、展开折叠及快捷键行为跟随 Pi。clean 和 compact 共用嵌套执行状态、历史快照、状态处理与子项局部展开逻辑;全局展开操作会重置它们的局部覆盖。
31
+ | 命令 | 作用 |
32
+ |---|---|
33
+ | `/pretty-tui clean` | 切换到 clean |
34
+ | `/pretty-tui compact` | 切换到 compact |
35
+ | `/pretty-tui full` | 切换到 full |
36
+ | `/pretty-tui enable` / `/pretty-tui disable` | 启用或禁用插件,并自动重载 |
37
+ | `/pretty-tui status` | 查看当前设置 |
53
38
 
54
- 子工具的文本结果和 edit diff 会存入隐藏的、仅用于 UI 的 session 条目,支持 reload 和会话分支恢复。每个父调用最多保留 256 个子调用,每项参数最多 4,096 字符,每项文本结果最多 8,192 字符,参数和结果合计最多 131,072 字符;截断会明确提示。每项展开预览还设有 200 行上限,嵌套树最多展示父调用以下八层。没有快照的旧会话会明确显示仅保留调用记录。目前子结果使用通用文本视图,不调用各第三方工具的 renderer,也不在快照中保存图片;父工具自身的媒体结果与原生 renderer 仍可在 full 模式查看。
39
+ 设置会持久保存。禁用插件后恢复 Pi 原生外观。
55
40
 
56
- 这些 UI 条目不会修改脚本输出或模型收到的工具结果,但**会保存脚本可能未打印的子工具文本**,因此请将 session 文件视为可能含有敏感信息。常见凭证参数键会被遮盖,工具输出则不保证已清除所有敏感内容。
41
+ ### 重复错误
57
42
 
58
- ## 设置与渲染模式
43
+ clean 和 compact 中,相邻的独立错误即使 trace、request 或 correlation ID 不同,也可合并显示第一条完整错误及 `[×2]` / `[×3]` 次数。来源类型、标题和周围文本必须完全一致;仅独立的长十六进制 ID(16–128 位且含字母)或 UUID 可以变化。短错误码、纯数字值及 `msg_...` / `rs_...` 等带前缀的标识仍要求一致。
59
44
 
60
- 运行 `/pretty-tui` 可打开扩展设置。`Enabled` 开关会持久化控制 pi-pretty-tui 是否安装渲染补丁和内置工具 renderer。修改后会自动调用 Pi 官方的 reload 流程,无需手动执行 `/reload`。也可以直接使用 `/pretty-tui enable` 和 `/pretty-tui disable`。禁用期间设置命令仍然可用,Pi 会恢复原生渲染。
45
+ 其他会话条目会打断合并;带思考、工具调用或可见回答的错误不参与折叠。全屏模式下,点击第一条错误可展开或收起;展开后每条完整原始错误使用相同前缀、左侧对齐,不加序号,新追加的重复错误保留展开状态。会话记录保持不变,也可使用 `/pretty-tui full` 查看每次错误及原始 ID。
61
46
 
62
- 三种模式保留输入框工作计时、回答 footer 和复制增强;clean/compact 使用临时状态反馈,full 保留原生状态投递。clean 将 `● thought` 放在活动组内。compact 使用独立思考卡片,默认折叠并预览第一行思考内容(超宽时以省略号截断为一行),标题显示 `▸`,点击标题展开 Markdown 详情后显示 `▾`。full 保留原生思考段、与正文的原始顺序、Markdown transform 和逐段点击,并为每个思考段加上左上角带名称的边框。full 中思考默认展开,不因已有 compact/原生隐藏设置而初始折叠;手动收起及后续 `Ctrl+T` 可见性切换继续生效。
47
+ ## 复制操作
63
48
 
64
- full 以原生 Pi 的信息和行为为准,统一使用带主题底色的面板。User、Assistant、思考和工具面板的底色从对应边框的主题色派生。深色主题保留色相并显著降低亮度和饱和度,蓝、紫、绿、红边框对应同色系深底色,Assistant 中性边框对应深灰底色;浅色主题使用同色系浅底色,保证原生深色文字可读。标题、边框和底边耗时保留语义配色,颜色转换使用缓存并跟随主题及终端色彩模式变化。原生内容中的前景语法/diff 配色继续保留,ANSI reset 后会恢复面板底色,图片协议行保持原样。
49
+ 以 **fullscreen 全屏模式**启动 Pi,即可使用鼠标复制入口:
65
50
 
66
- full 和 compact 面板左右各保留一个字符的外侧留白,极窄终端取消;留白保持终端背景,统一应用于 User、Assistant、思考和工具面板。
67
-
68
- 每个工具只有一张占满剩余宽度的面板:调用在上,原生可见结果在下,中间以 `Output` 分隔线区分。不再使用独立结果卡片、连接线或结果缩进;无可见结果时不添加输出占位。去掉边缘布局空白,保留内部空行与图片占位;不同工具之间保留两行留白。User 面板铺满宽度,左上角显示 `User`;相邻正文块合并为默认展开的 Assistant 卡片;思考默认展开,保留局部及原生可见性控制。
69
-
70
- 内置工具使用 Pi 官方 renderer,保留预览、截断/展开入口及错误详情。full 模式的 bash 命令额外使用 Pi 的 shell 语法高亮,区分变量、字符串、关键字和注释,并按命令与语法配色缓存;原生 `$` 提示符、命令原文、超时标注和结果输出保持不变。shell/codemode 原生 `Took`/`Elapsed` 保留在底边框且与边框同色;窄面板放不下时保留原生正文计时。第三方 renderer、媒体数据和原生鼠标交互继续保留。clean 保留活动分组与透明用户气泡。compact 共用面板底色、边框配色、留白及 User/Assistant 卡片,工具默认只显示参数和结果摘要,独立工具卡片标题用 `▸` 表示折叠、`▾` 表示展开,点击标题切换详情,`Ctrl+O` 保留原生全局展开。User/Assistant 和仅用于展示的嵌套父工具标题不添加折叠箭头。独立工具展开后与 full 共用原生 renderer 和卡片投影,包括命令高亮、输出分界及原生耗时,不再带 compact 的树状连接线和结果缩进;嵌套工具保留脚本、输出和子项的局部展开。Pi 提供最终耗时时,compact 在边框显示 `Took`,缺失时不猜测。极窄终端省略边框但保留面板底色。
71
-
72
- 扩展支持三种可持久化的渲染模式:`clean`(默认)、`compact` 和 `full`。可交互选择,也可以直接使用 `/pretty-tui clean`、`/pretty-tui compact`、`/pretty-tui full` 和 `/pretty-tui status`。设置会保存到 `~/.pi/agent/pretty-tui.json`,或 `PI_CODING_AGENT_DIR` 指定目录中的对应位置。
73
-
74
- | 模式 | 第三方工具 | codemode 等嵌套调用工具 |
75
- |---|---|---|
76
- | `clean` | 活动组中的紧凑摘要,展开查看原生详情 | 活动组内的嵌套树,各区块局部展开 |
77
- | `compact` | 独立紧凑面板,点击标题查看原生详情 | 卡片内的独立父子树,脚本、输出及子项按需展开 |
78
- | `full` | 原生内容与交互,外加标题卡片 | 标题卡片内的原生 codemode 内容与展开控件,不额外添加快照详情 |
79
-
80
- full 和 compact 保留 Pi 原生的 `Ctrl+O` 全局展开,之后仍可局部控制共享展示中的各子项;这两种模式不生成 clean 的 `Running/Done` 活动组外壳。
81
-
82
- fullscreen 模式下,活动树/工具交互行与复制入口允许同一行左右最多两个终端字符格的鼠标抖动;更大偏移或跨行移动仍按拖动处理。普通文本选择、链接和 Pi 的双击/三击行为保持不变。
51
+ ```sh
52
+ pi --tui-mode fullscreen
53
+ ```
83
54
 
84
- compact 和 full 中,压缩摘要使用主题配色的 `compaction ▸/▾` 卡片,保留原始 token 数、快捷键提示和完整摘要;点击标题/正文或使用原生 `Ctrl+O` 切换展开。压缩费用提示仍独立显示,clean 保留 Pi 原生压缩消息样式。
55
+ - **用户消息:** 点击正文或边框,复制原始文本。
56
+ - **代码块:** 点击 `[Copy]`,复制不含边框的代码。
57
+ - **最终回答:** 点击回答耗时旁的 `[Copy]`,复制不含思考和工具输出的回答。
85
58
 
86
- ## 可选的无边框选区复制
59
+ 拖动鼠标按选区处理,不触发整条消息复制。链接保留正常行为;文本复制不包含图片附件。
87
60
 
88
- 实验性的 **Selection copy** 选项可在 fullscreen 模式下,从鼠标选区的复制结果中排除插件绘制的边框、标题和布局留白,保留正文里真实存在的框线字符。**默认关闭**,适用于 clean、compact 和 full。
61
+ ### 可选的无边框选区复制
89
62
 
90
- 打开 `/pretty-tui`,选择 `Selection copy` 切换,或直接执行:
63
+ 在 `/pretty-tui` 中切换 **Selection copy**,或运行:
91
64
 
92
65
  ```text
93
66
  /pretty-tui selection-copy on
94
67
  /pretty-tui selection-copy off
95
68
  ```
96
69
 
97
- 选择会保存为 `pretty-tui.json` 中的 `selectionCopy`,切换后自动重载 Pi;`/pretty-tui status` 可查看配置值。关闭时不安装选区复制、叠加层或终端写入补丁,也不生成私有行标记。禁用整个插件时,本功能也不会启用,但会保留开关偏好。regular 模式由终端管理的选区保持原样。
98
-
99
- 目前仍需实际终端验收,并依赖 Pi 内部接口,因此作为可选功能保留。长会话会额外保留标记相关内存;源码仓库中的[探索与垃圾回收报告](docs/selection-copy-exploration.md)记录了测试范围和测量结果。
100
-
101
- ## 复制用户消息
102
-
103
- fullscreen 模式下,左键点击用户气泡的正文或边框,可复制完整原始文本,保留 Markdown、缩进和换行,不包含气泡边框。已有链接和代码块 `[Copy]` 控件保留优先级;拖动选择文本不会触发整条复制。复制使用 Pi 原生剪贴板路径及反馈,只复制文本,不复制图片附件。regular 模式保留终端自身的鼠标选择与复制行为。
104
-
105
- ## 复制代码块
106
-
107
- 代码块的圆角与线条使用 `borderMuted`,语言标签、`[Copy]` 和代码正文保持原有配色。
108
-
109
- 在 fullscreen TUI 模式下,用户消息与助手回复中的 Markdown 围栏代码块会在顶部边框显示可点击的 `[Copy]` 控件:
110
-
111
- ```sh
112
- pi --tui-mode fullscreen
113
- ```
114
-
115
- 点击后只复制代码内容,不包含圆角边框;复制会通过 Pi 原生的 fullscreen 剪贴板路径完成,并显示与直接框选文本相同的临时 `Copied!` 或 `Copy failed` 提示。regular TUI 模式下,终端会保留鼠标输入用于文本选择和滚动,因此该控件会被隐藏。
116
-
117
- ## 开发
118
-
119
- 修改渲染状态或 transcript 分组前,请运行仓库内的回归测试:
120
-
121
- ```sh
122
- npm install
123
- npm test
124
- ```
125
-
126
- 测试覆盖实时与历史恢复的活动时间线、自动重试与终止状态、用户/steer/compaction/原生 renderer 边界、十秒 UI 状态替换、reload 与 shutdown 时的旧 timer 与状态清理、独立严重级别样式、内置与第三方工具、可展开思考、并行工具完成归属、孤立 tool call、重复摘要防护、可持久化的工作时长与仅回答复制控件、自适应用户聊天气泡、原型补丁的完整恢复,以及 fullscreen 代码块复制的点击区域。测试还使用 Pi 的真实扩展加载器检查同名替换工具的共存。GitHub Actions 会在每次 push 和 pull request 时运行相同检查。
127
-
128
- 如需额外测试本地 [pi-bash-bg](https://github.com/mapleluvr/pi-bash-bg) 仓库,运行 `npm test` 前将 `PI_BASH_BG_EXTENSION` 指向其 `index.ts`。该可选集成测试会执行前台和自动转后台的命令,并检查状态和日志。
129
-
130
- ## 兼容性说明
70
+ 这是**默认关闭的实验性选项**。在全屏模式下,复制鼠标选区时排除界面边框、标题和布局留白,保留正文里真实存在的框线字符。适用于三种展示模式,切换后保存设置并自动重载 Pi。
131
71
 
132
- 当前开发与回归测试基线为 **Pi 1.4.0**。用户气泡已适配该版本直接使用 Markdown 的布局,full/compact 使用带底色、铺满宽度的 User 面板,clean 使用透明、按内容自适应的气泡。嵌套执行需要 Pi 0.99.0 及以后;这是功能要求,不代表每个旧版都经过测试。
72
+ regular 非全屏模式由终端处理选择与复制,开启此选项也不会获得边框排除效果。fullscreen/regular 与 clean/compact/full 是两组独立设置。
133
73
 
134
- 工具渲染使用 Pi 的公开扩展 API。活动工具状态通过 Pi 导出的交互组件跟随其内置执行状态变化;clean 模式的 thought 详情使用活动时间线自身的展开状态,full 和 compact 模式则保留 Pi 内置的 Thinking 可见性控制。由于 Pi 目前没有为这些展示细节提供公开渲染钩子,自适应的原生用户消息气泡、原生输入编辑器圆角、无序列表标记和围栏代码块增强需要使用可安全重载的运行时补丁。Markdown 增强仅在渲染主 transcript 中的用户消息和助手回复时启用;扩展 overlay 创建的 Markdown 保持 Pi 原生布局。Markdown 解析、语法高亮和终端语义区域仍由 Pi 处理。
74
+ ## 必要说明
135
75
 
136
- 本扩展不会修改 Pi 源文件。运行时补丁会在会话关闭时移除,但未来的 Pi 版本可能需要本扩展同步适配。
76
+ - 当前已在 **Pi 1.5.0** 上测试;未来 Pi 更新可能需要适配。
77
+ - 保留 Pi 原生输入行为和工具执行逻辑,包括第三方工具实现。
78
+ - 嵌套工具的文本详情会随会话保存以便恢复,内容可能截断;会话文件可能包含工具输出中的敏感信息。
79
+ - 版本变更与贡献者致谢见 [Releases](https://github.com/ykn0309/pi-pretty-tui/releases)。
137
80
 
138
81
  ## 卸载
139
82
 
@@ -141,8 +84,8 @@ npm test
141
84
  pi remove npm:pi-pretty-tui
142
85
  ```
143
86
 
144
- 然后重启 Pi。
87
+ 卸载后重启 Pi。
145
88
 
146
89
  ## 许可证
147
90
 
148
- MIT
91
+ [MIT](./LICENSE)
Binary file
@@ -1,6 +1,13 @@
1
1
  import { installSelectionCopy, selectableRow, selectionMetadataActive } from "./selection-ranges.js";
2
2
  import { isNativeImageRow } from "./ansi-style.js";
3
3
  import { cardMargin, cardBackground, frameNativeRows, nativeFrameWidth } from "./full-frame.js";
4
+ import {
5
+ themedInlineContext,
6
+ withNativeEmphasis,
7
+ type InlineStyleContext,
8
+ type InlineToken,
9
+ } from "./markdown-emphasis.js";
10
+ import { gapRowsAfterBlock, renderSpacedList } from "./markdown-spacing.js";
4
11
  import { ThoughtPresentation } from "./thought-presentation.js";
5
12
  import { isThirdPartyTool, renderToolProjection, THIRD_PARTY_TOOL, toolLabel, type ToolProjection } from "./tool-presentation.js";
6
13
  import { NestedTools, NESTED_SNAPSHOT_ENTRY } from "./nested-tools.js";
@@ -65,6 +72,8 @@ type PrettyTuiConfig = {
65
72
  mode?: PrettyTuiMode;
66
73
  /** Exclude plugin decoration from fullscreen selections. Opt-in. */
67
74
  selectionCopy?: boolean;
75
+ /** "native" keeps Pi's flags-only strong and emphasis. Read when the extension loads. */
76
+ markdownEmphasis?: "themed" | "native";
68
77
  /** Legacy location used by the first mode implementation. */
69
78
  bash?: {
70
79
  mode?: "full" | "compact";
@@ -80,6 +89,24 @@ const loadConfig = (path: string): PrettyTuiConfig => {
80
89
  }
81
90
  };
82
91
 
92
+ /** Stable text affixes around opaque IDs, without fuzzy similarity chaining. */
93
+ const errorAffixKey = (text: string): string => {
94
+ const parts: (string | ["hex" | "uuid"])[] = [];
95
+ let cursor = 0;
96
+ // Whole tokens only: keep semantic identifiers such as msg_<hex> and
97
+ // rs_<hex>, short codes, ordinary words, and numeric quantities exact.
98
+ const opaqueId = /(?<![\w-])(?:[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}|[\da-f]{16,128})(?![\w-])/giu;
99
+ for (const match of text.matchAll(opaqueId)) {
100
+ const kind = match[0].includes("-") ? "uuid" : "hex";
101
+ if (kind === "hex" && !/[a-f]/iu.test(match[0])) continue;
102
+ parts.push(text.slice(cursor, match.index), [kind]);
103
+ cursor = match.index + match[0].length;
104
+ }
105
+ parts.push(text.slice(cursor));
106
+ // Typed slots cannot collide with a literal placeholder in an error.
107
+ return JSON.stringify(parts);
108
+ };
109
+
83
110
  /** Polished user messages, tool calls, and list rendering for Pi's TUI. */
84
111
  export default function prettyTui(pi: ExtensionAPI) {
85
112
  const cwd = process.cwd();
@@ -102,6 +129,21 @@ export default function prettyTui(pi: ExtensionAPI) {
102
129
  let currentPromptEditor: any;
103
130
  let errorChatContainer: any;
104
131
  const runtimeErrorDescriptors = new WeakMap<object, { source: string; title: string; content: string }>();
132
+ const expandedErrorRuns = new WeakSet<object>();
133
+ const errorDisclosureRows = new WeakMap<object, { start: number; end: number }>();
134
+ const errorDisclosureHit = (component: object, event: any) => {
135
+ const rows = errorDisclosureRows.get(component);
136
+ return renderMode !== "full" && Boolean(rows && event.y >= rows.start && event.y < rows.end);
137
+ };
138
+ const handleErrorDisclosureMouse = (component: object, event: any) => {
139
+ if (event.button !== "left" || !errorDisclosureHit(component, event)) return undefined;
140
+ if (event.type === "press") return { handled: true };
141
+ if (event.type !== "click") return undefined;
142
+ if (expandedErrorRuns.has(component)) expandedErrorRuns.delete(component);
143
+ else expandedErrorRuns.add(component);
144
+ currentTui?.requestRender?.();
145
+ return { handled: true };
146
+ };
105
147
  const errorDescriptor = (component: any) => {
106
148
  const runtime = runtimeErrorDescriptors.get(component);
107
149
  if (runtime) return runtime;
@@ -115,15 +157,21 @@ export default function prettyTui(pi: ExtensionAPI) {
115
157
  const children: any[] = errorChatContainer?.children ?? [];
116
158
  const index = children.indexOf(component);
117
159
  const descriptor = errorDescriptor(component);
160
+ const key = descriptor && errorAffixKey(descriptor.content);
118
161
  const same = (other: any) => {
119
162
  const value = errorDescriptor(other);
120
163
  return descriptor && value && value.source === descriptor.source &&
121
- value.title === descriptor.title && value.content === descriptor.content;
164
+ value.title === descriptor.title && errorAffixKey(value.content) === key;
122
165
  };
123
166
  if (index < 0 || !descriptor) return { hidden: false, count: 1, compact: false };
167
+ // Only the visible run head needs a count; hidden retries must not rescan
168
+ // the whole suffix and repeatedly fingerprint every later error.
169
+ const hidden = index > 0 && Boolean(same(children[index - 1]));
124
170
  let count = 1;
125
- while (index + count < children.length && same(children[index + count])) count++;
126
- return { hidden: index > 0 && Boolean(same(children[index - 1])), count,
171
+ if (!hidden) {
172
+ while (index + count < children.length && same(children[index + count])) count++;
173
+ }
174
+ return { hidden, count,
127
175
  compact: index > 0 && Boolean(errorDescriptor(children[index - 1])) };
128
176
  };
129
177
  const runningColor = (theme: any, text: string): string =>
@@ -303,6 +351,17 @@ export default function prettyTui(pi: ExtensionAPI) {
303
351
  }
304
352
  };
305
353
  const transcriptMarkdownActive = () => transcriptMarkdownDepth > 0;
354
+ // Assistant answers only. The transcript scope also covers user messages,
355
+ // thinking and activity updates, which keep Pi's strong and emphasis styling.
356
+ const assistantBodyMarkdown = new WeakSet<object>();
357
+ const markAssistantBodyMarkdown = (component: any) => {
358
+ // Pi adds answer text directly; a thought block is wrapped in a MouseRegion.
359
+ // A component built before this runtime is covered too: the rendered-mode
360
+ // symbols are per runtime, so its first render here re-runs updateContent.
361
+ for (const child of component.contentContainer?.children ?? []) {
362
+ if (child instanceof Markdown && !(child as any).defaultTextStyle) assistantBodyMarkdown.add(child);
363
+ }
364
+ };
306
365
 
307
366
  const setCleanGroupMembers = (lastToolCallId: string, toolCallIds: string[]) => {
308
367
  cleanGroupToolCallIds.set(lastToolCallId, toolCallIds);
@@ -585,23 +644,45 @@ export default function prettyTui(pi: ExtensionAPI) {
585
644
 
586
645
  const renderStandaloneError = (member: ActivityMember, width: number, component?: any): string[] => {
587
646
  const run = component && renderMode !== "full" ? errorRun(component) : { hidden: false, count: 1, compact: false };
647
+ if (component) errorDisclosureRows.delete(component);
588
648
  if (run.hidden) return [];
589
649
  const theme = defaultActivityTheme();
590
650
  const style = activityUpdateStyle(member, theme);
591
651
  const original = component ? errorDescriptor(component) : undefined;
592
- const title = stripTerminalSequences(original?.title ?? member.updateTitle ?? "Error");
593
- const content = stripTerminalSequences(original?.content || member.updateContent || "");
594
- const heading = style.icon + style.title(title);
595
- const prefix = heading + (content ? theme.fg("dim", " · ") : "");
596
- const text = prefix + theme.fg("muted", content) + (run.count > 1 ? theme.fg("dim", ` ×${run.count}`) : "");
597
- // Wrap rather than truncate; all original detail lines remain accessible.
598
- const continuation = " ".repeat(Math.min(visibleWidth(prefix), Math.max(0, Math.floor(width / 3))));
599
- const rows: string[] = [];
600
- for (const line of text.split("\n")) {
601
- const wrapped = wrapTextWithAnsi(line, Math.max(1, width - visibleWidth(continuation)));
602
- rows.push(...wrapped.map((row, index) => (rows.length || index ? continuation : "") + row));
652
+ const renderError = (titleText: string, contentText: string, count = 1): string[] => {
653
+ const title = stripTerminalSequences(titleText);
654
+ const content = stripTerminalSequences(contentText);
655
+ const heading = style.icon + style.title(title);
656
+ const prefix = heading + (content ? theme.fg("dim", " · ") : "");
657
+ const text = prefix + theme.fg("muted", content) + (count > 1 ? theme.fg("dim", component && expandedErrorRuns.has(component) ? " [Collapse]" : ` [×${count}]`) : "");
658
+ // Wrap rather than truncate; all original detail lines remain accessible.
659
+ const continuation = " ".repeat(Math.min(visibleWidth(prefix), Math.max(0, Math.floor(width / 3))));
660
+ const rows: string[] = [];
661
+ for (const line of text.split("\n")) {
662
+ const wrapped = wrapTextWithAnsi(line, Math.max(1, width - visibleWidth(continuation)));
663
+ rows.push(...wrapped.map((row, index) => (rows.length || index ? continuation : "") + row));
664
+ }
665
+ return rows.map((line) => truncateToWidth(line, Math.max(1, width), ""));
666
+ };
667
+ const rows = [
668
+ ...(run.compact ? [] : [""]),
669
+ ...renderError(original?.title ?? member.updateTitle ?? "Error", original?.content || member.updateContent || "", run.count),
670
+ ];
671
+ if (component && run.count > 1) {
672
+ errorDisclosureRows.set(component, { start: run.compact ? 0 : 1, end: rows.length });
673
+ mouseClickHitTests.set(component, (event) => errorDisclosureHit(component, event));
674
+ if (expandedErrorRuns.has(component)) {
675
+ // The visible head owns the expanded projection. Original retry
676
+ // components stay untouched and hidden, and only the head counts them.
677
+ const children = errorChatContainer?.children ?? [];
678
+ const index = children.indexOf(component);
679
+ for (const retry of children.slice(index + 1, index + run.count)) {
680
+ const descriptor = errorDescriptor(retry);
681
+ if (descriptor) rows.push(...renderError(descriptor.title, descriptor.content));
682
+ }
683
+ }
603
684
  }
604
- return [...(run.compact ? [] : [""]), ...rows.map((line) => truncateToWidth(line, Math.max(1, width), ""))];
685
+ return rows;
605
686
  };
606
687
 
607
688
  const renderPendingActivityUpdate = (member: ActivityMember, width: number, component?: any): string[] => {
@@ -1385,10 +1466,15 @@ export default function prettyTui(pi: ExtensionAPI) {
1385
1466
  }
1386
1467
  if (renderMode === "compact") {
1387
1468
  const terminal = assistantTerminalUpdate(this[originalMessageKey] ?? this.lastMessage);
1388
- if (terminal) output.push(...renderPendingActivityUpdate(terminal, width, this));
1469
+ if (terminal) {
1470
+ const offset = output.length;
1471
+ output.push(...renderPendingActivityUpdate(terminal, width, this));
1472
+ const disclosure = errorDisclosureRows.get(this);
1473
+ if (disclosure) errorDisclosureRows.set(this, { start: disclosure.start + offset, end: disclosure.end + offset });
1474
+ }
1389
1475
  }
1390
1476
  panelAssistantViews.set(this, { rows, width: innerWidth, height: nativeLines.length });
1391
- mouseClickHitTests.set(this, (event) => thoughtRows.has(event.y));
1477
+ mouseClickHitTests.set(this, (event) => thoughtRows.has(event.y) || errorDisclosureHit(this, event));
1392
1478
  return renderMode === "compact" && width < 8
1393
1479
  ? output.map((line) => isNativeImageRow(line) ? line : truncateToWidth(line, Math.max(1, width), "")) : output;
1394
1480
  };
@@ -1405,6 +1491,7 @@ export default function prettyTui(pi: ExtensionAPI) {
1405
1491
  originalUpdateContent.call(this, renderMode === "compact" && assistantTerminalState(message)
1406
1492
  ? { ...message, errorMessage: undefined, stopReason: "stop" } : message, isStreaming);
1407
1493
  this.lastMessage = message;
1494
+ markAssistantBodyMarkdown(this);
1408
1495
  if (eligibleThinking(message)) thinkingComponents.set(assistantMessageKey(message), this);
1409
1496
  return;
1410
1497
  }
@@ -1432,9 +1519,11 @@ export default function prettyTui(pi: ExtensionAPI) {
1432
1519
  this.hideThinkingBlock = previousHideThinkingBlock;
1433
1520
  }
1434
1521
  this.lastMessage = message;
1522
+ markAssistantBodyMarkdown(this);
1435
1523
  };
1436
1524
 
1437
1525
  const renderAssistantTranscript = function (this: any, width: number): string[] {
1526
+ errorDisclosureRows.delete(this);
1438
1527
  const message = this[originalMessageKey] ?? this.lastMessage;
1439
1528
  if (
1440
1529
  message &&
@@ -1560,6 +1649,11 @@ export default function prettyTui(pi: ExtensionAPI) {
1560
1649
  };
1561
1650
 
1562
1651
  const handleAssistantTranscriptMouse = function (this: any, event: any) {
1652
+ if (errorDescriptor(this)) {
1653
+ patchedRender.call(this, event.width);
1654
+ const disclosure = handleErrorDisclosureMouse(this, event);
1655
+ if (disclosure) return disclosure;
1656
+ }
1563
1657
  const message = this[originalMessageKey] ?? this.lastMessage;
1564
1658
  if (renderMode !== "clean") {
1565
1659
  patchedRender.call(this, event.width);
@@ -1728,7 +1822,7 @@ export default function prettyTui(pi: ExtensionAPI) {
1728
1822
  const component: Component = {
1729
1823
  render: (width: number) => renderActivityUpdateProjection(group, member, width, component),
1730
1824
  invalidate() {},
1731
- handleMouse: (event: any) => handleActivityUpdateMouse(group, member, event),
1825
+ handleMouse: (event: any) => handleErrorDisclosureMouse(component, event) ?? handleActivityUpdateMouse(group, member, event),
1732
1826
  } as Component;
1733
1827
  if (severity === "error") runtimeErrorDescriptors.set(component, {
1734
1828
  source: "runtime:error", title, content,
@@ -2288,6 +2382,11 @@ export default function prettyTui(pi: ExtensionAPI) {
2288
2382
  const codeBlockRegionsKey = Symbol("pretty-tui.code-block-regions");
2289
2383
  const transcriptMarkdownStateKey = Symbol("pretty-tui.transcript-markdown-state");
2290
2384
  if (!markdownPrototype[codeBlockPatchKey]) {
2385
+ // Pi 1.5 reuses rendered top-level blocks while text streams. Keep copy
2386
+ // descriptors with each native block's highlighting-cache identity, weakly,
2387
+ // so reused pixels retain their hit regions without disabling that cache.
2388
+ const blockCopyDescriptors = new WeakMap<object, { generation: number; blocks: any[] }>();
2389
+ let copyRenderGeneration = 0;
2291
2390
  const originalInvalidate = markdownPrototype.invalidate;
2292
2391
  const originalRender = markdownPrototype.render;
2293
2392
  const originalRenderToken = markdownPrototype.renderToken;
@@ -2332,14 +2431,22 @@ export default function prettyTui(pi: ExtensionAPI) {
2332
2431
 
2333
2432
  const needsRender =
2334
2433
  !this.cachedLines || this.cachedText !== this.text || this.cachedWidth !== width;
2335
- if (needsRender) this[codeBlockCollectionKey] = [];
2434
+ if (needsRender) this[codeBlockCollectionKey] = Object.assign([], { generation: ++copyRenderGeneration });
2336
2435
 
2337
2436
  const lines = originalRender.call(this, width);
2338
2437
  if (!needsRender) return selectableMarkdown(this, lines);
2339
2438
 
2340
2439
  const regions: Array<{ xStart: number; xEnd: number; y: number; code: string }> = [];
2341
2440
  let searchFrom = 0;
2342
- for (const block of this[codeBlockCollectionKey] ?? []) {
2441
+ const nativeBlocks = this.blocks?.deref();
2442
+ const nativeTokens = this.cachedTokens?.deref()?.tokens;
2443
+ const copyBlocks = nativeBlocks && nativeTokens
2444
+ ? nativeTokens.flatMap((token: any) => {
2445
+ const block = nativeBlocks.get(token.raw);
2446
+ return block ? blockCopyDescriptors.get(block.highlightedCode)?.blocks ?? [] : [];
2447
+ })
2448
+ : this[codeBlockCollectionKey] ?? [];
2449
+ for (const block of copyBlocks) {
2343
2450
  let headerLine = -1;
2344
2451
  for (let lineIndex = searchFrom; lineIndex < lines.length; lineIndex += 1) {
2345
2452
  const renderedLine = lines[lineIndex] ?? "";
@@ -2385,36 +2492,20 @@ export default function prettyTui(pi: ExtensionAPI) {
2385
2492
  return lines;
2386
2493
  };
2387
2494
  const headingStyle = (text: string) => this.theme.heading(text);
2388
- const foregroundLuminance = (styled: string): number | undefined => {
2389
- const trueColor = /\x1b\[38;2;(\d+);(\d+);(\d+)m/.exec(styled);
2390
- if (!trueColor) return undefined;
2391
- const [, red, green, blue] = trueColor.map(Number);
2392
- return red * 0.2126 + green * 0.7152 + blue * 0.0722;
2393
- };
2394
- const defaultLuminance = foregroundLuminance(this.applyDefaultStyle("M"));
2395
- const headingLuminance = foregroundLuminance(headingStyle("M"));
2396
- const darkTheme =
2397
- defaultLuminance !== undefined
2398
- ? defaultLuminance >= 128
2399
- : (headingLuminance ?? 255) >= 160;
2400
- const whiteStyle = (text: string) => `\x1b[97m${text}\x1b[39m`;
2495
+ // Descending emphasis: framed H1, underlined H2, bold H3,
2496
+ // plain H4, decorative H5, and quote-colored italic H6.
2401
2497
  const titleStyle =
2402
- level === 1 || level === 3
2498
+ level === 1 || level === 2
2403
2499
  ? (text: string) => headingStyle(this.theme.bold(this.theme.underline(text)))
2404
- : level === 2
2405
- ? (text: string) =>
2406
- (darkTheme ? whiteStyle : headingStyle)(
2407
- this.theme.bold(this.theme.underline(text)),
2408
- )
2409
- : level === 4
2410
- ? (text: string) => headingStyle(this.theme.bold(text))
2411
- : level === 5
2412
- ? headingStyle
2413
- : (text: string) => this.theme.quote(this.theme.italic(text));
2414
- const titleContext = {
2500
+ : level === 3
2501
+ ? (text: string) => headingStyle(this.theme.bold(text))
2502
+ : level === 4 || level === 5
2503
+ ? headingStyle
2504
+ : (text: string) => this.theme.quote(this.theme.italic(text));
2505
+ const titleContext = withNativeEmphasis({
2415
2506
  applyText: titleStyle,
2416
2507
  stylePrefix: this.getStylePrefix(titleStyle),
2417
- };
2508
+ });
2418
2509
  const title = this.renderInlineTokens(token.tokens || [], titleContext);
2419
2510
 
2420
2511
  if (level === 1 && maxWidth >= 6) {
@@ -2437,17 +2528,6 @@ export default function prettyTui(pi: ExtensionAPI) {
2437
2528
  return addHeadingSpacing(lines);
2438
2529
  }
2439
2530
 
2440
- if (level === 2) {
2441
- // Reverse only the rendered title cells: the theme's heading color
2442
- // becomes a compact, content-width background label with no frame.
2443
- const lines = wrapTextWithAnsi(title, maxWidth).map((line: string) =>
2444
- darkTheme
2445
- ? `\x1b[48;5;94m${line}\x1b[49m`
2446
- : `\x1b[107m\x1b[7m${line}\x1b[27m\x1b[49m`
2447
- );
2448
- return addHeadingSpacing(lines);
2449
- }
2450
-
2451
2531
  if (level === 5 && maxWidth >= 8) {
2452
2532
  const prefix = "┄┄ ";
2453
2533
  const suffix = " ┄┄";
@@ -2468,7 +2548,10 @@ export default function prettyTui(pi: ExtensionAPI) {
2468
2548
  }
2469
2549
 
2470
2550
  if (token?.type !== "code") {
2471
- return originalRenderToken.call(this, token, width, nextTokenType, styleContext);
2551
+ return [
2552
+ ...originalRenderToken.call(this, token, width, nextTokenType, styleContext),
2553
+ ...gapRowsAfterBlock(token?.type, nextTokenType),
2554
+ ];
2472
2555
  }
2473
2556
 
2474
2557
  const maxWidth = Math.max(1, width);
@@ -2530,13 +2613,23 @@ export default function prettyTui(pi: ExtensionAPI) {
2530
2613
  ];
2531
2614
 
2532
2615
  if (showCopyButton && Array.isArray(this[codeBlockCollectionKey])) {
2533
- this[codeBlockCollectionKey].push({
2616
+ const descriptor = {
2534
2617
  buttonStart,
2535
2618
  buttonWidth: visibleWidth(copyLabel),
2536
2619
  code,
2537
2620
  styledTopRule,
2538
2621
  topRule,
2539
- });
2622
+ };
2623
+ const collection = this[codeBlockCollectionKey] as any[] & { generation: number };
2624
+ collection.push(descriptor);
2625
+ if (this.blockHighlightedCode) {
2626
+ let cached = blockCopyDescriptors.get(this.blockHighlightedCode);
2627
+ if (!cached || cached.generation !== collection.generation) {
2628
+ cached = { generation: collection.generation, blocks: [] };
2629
+ blockCopyDescriptors.set(this.blockHighlightedCode, cached);
2630
+ }
2631
+ cached.blocks.push(descriptor);
2632
+ }
2540
2633
  }
2541
2634
  if (nextTokenType && nextTokenType !== "space") lines.push("");
2542
2635
  return lines;
@@ -2621,7 +2714,11 @@ export default function prettyTui(pi: ExtensionAPI) {
2621
2714
  this.theme.listBullet = (marker: string) =>
2622
2715
  originalListBullet(marker.replace(/^- /, "• "));
2623
2716
  try {
2624
- return originalRenderList.call(this, token, depth, width, styleContext);
2717
+ if (!transcriptMarkdownActive()) {
2718
+ return originalRenderList.call(this, token, depth, width, styleContext);
2719
+ }
2720
+ return renderSpacedList(token, (singleItemList) =>
2721
+ originalRenderList.call(this, singleItemList, depth, width, styleContext));
2625
2722
  } finally {
2626
2723
  this.theme.listBullet = originalListBullet;
2627
2724
  }
@@ -2639,6 +2736,37 @@ export default function prettyTui(pi: ExtensionAPI) {
2639
2736
  });
2640
2737
  }
2641
2738
 
2739
+ const inlineEmphasisPatchKey = Symbol.for("pretty-tui.inline-emphasis");
2740
+ if (config.markdownEmphasis !== "native" && !markdownPrototype[inlineEmphasisPatchKey]) {
2741
+ const originalRenderInlineTokens = markdownPrototype.renderInlineTokens;
2742
+ const patchedRenderInlineTokens = function (
2743
+ this: any,
2744
+ tokens: InlineToken[],
2745
+ styleContext?: InlineStyleContext,
2746
+ ): string {
2747
+ const theme = currentExtensionUi?.theme;
2748
+ if (!transcriptMarkdownActive() || !assistantBodyMarkdown.has(this) || !theme?.fg) {
2749
+ return originalRenderInlineTokens.call(this, tokens, styleContext);
2750
+ }
2751
+ return originalRenderInlineTokens.call(
2752
+ this,
2753
+ tokens,
2754
+ themedInlineContext(tokens, styleContext ?? this.getDefaultInlineStyleContext(), theme),
2755
+ );
2756
+ };
2757
+
2758
+ markdownPrototype[inlineEmphasisPatchKey] = { originalRenderInlineTokens, patchedRenderInlineTokens };
2759
+ markdownPrototype.renderInlineTokens = patchedRenderInlineTokens;
2760
+
2761
+ pi.on("session_shutdown", () => {
2762
+ const patch = markdownPrototype[inlineEmphasisPatchKey];
2763
+ if (patch?.patchedRenderInlineTokens === markdownPrototype.renderInlineTokens) {
2764
+ markdownPrototype.renderInlineTokens = patch.originalRenderInlineTokens;
2765
+ }
2766
+ if (patch) delete markdownPrototype[inlineEmphasisPatchKey];
2767
+ });
2768
+ }
2769
+
2642
2770
  const textContent = (result: any): string =>
2643
2771
  result.content
2644
2772
  ?.filter((item: any) => item.type === "text")
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Foreground colors for Markdown strong and emphasis in the assistant's answer.
3
+ *
4
+ * Pi has no strong or emphasis color token, so these reuse existing ones. Each is
5
+ * read from the active theme on every render, so dark, light, custom themes and
6
+ * `/theme` all apply. `syntaxType` looks like an option for emphasis, but it equals
7
+ * `mdCode` in Pi's built-in themes, which would make emphasis look like inline code.
8
+ */
9
+ export const MARKDOWN_EMPHASIS_COLORS = {
10
+ strong: "syntaxNumber",
11
+ em: "warning",
12
+ } as const;
13
+
14
+ type EmphasisType = keyof typeof MARKDOWN_EMPHASIS_COLORS;
15
+ type EmphasisColor = (typeof MARKDOWN_EMPHASIS_COLORS)[EmphasisType];
16
+ type ChildOwner = EmphasisType | "link";
17
+
18
+ export interface EmphasisTheme {
19
+ fg(color: EmphasisColor, text: string): string;
20
+ }
21
+
22
+ /** Pi's inline style context: how text is styled, and what restores it after a nested span closes. */
23
+ export interface InlineStyleContext {
24
+ applyText: (text: string) => string;
25
+ stylePrefix: string;
26
+ }
27
+
28
+ export interface InlineToken {
29
+ type: string;
30
+ tokens?: InlineToken[];
31
+ }
32
+
33
+ const SENTINEL = "\0";
34
+
35
+ const isChildOwner = (type: string): type is ChildOwner =>
36
+ type === "strong" || type === "em" || type === "link";
37
+
38
+ // Pi passes a token's children to renderInlineTokens with the parent's context and
39
+ // does not say who the parent was. Keyed by array, so Pi's cached tokens stay unmodified.
40
+ const childOwners = new WeakMap<readonly InlineToken[], ChildOwner>();
41
+ const nativeContexts = new WeakSet<InlineStyleContext>();
42
+ const surroundingContexts = new WeakMap<InlineStyleContext, InlineStyleContext>();
43
+
44
+ /** Marks a context whose text keeps its own foreground, such as a heading title. */
45
+ export function withNativeEmphasis(context: InlineStyleContext): InlineStyleContext {
46
+ nativeContexts.add(context);
47
+ return context;
48
+ }
49
+
50
+ function emphasisContext(
51
+ surrounding: InlineStyleContext,
52
+ color: EmphasisColor,
53
+ theme: EmphasisTheme,
54
+ ): InlineStyleContext {
55
+ const context: InlineStyleContext = {
56
+ // The inner color wins, so a surrounding default style cannot hide the emphasis color.
57
+ applyText: (text) => surrounding.applyText(theme.fg(color, text)),
58
+ // A nested span's foreground close falls back to the terminal default, so
59
+ // Pi's stylePrefix has to reopen the emphasis color for the text after it.
60
+ stylePrefix: surrounding.stylePrefix + theme.fg(color, SENTINEL).split(SENTINEL)[0],
61
+ };
62
+ surroundingContexts.set(context, surrounding);
63
+ return context;
64
+ }
65
+
66
+ /**
67
+ * Returns the context Pi should use for these tokens. Only the context changes:
68
+ * Pi's own recursion still emits every flag and every nested span.
69
+ *
70
+ * The innermost strong or emphasis sets the foreground. A link label uses the
71
+ * context outside all emphasis, so it keeps Pi's link color, and emphasis inside
72
+ * it stays flags-only for the same reason. Inline code is untouched by contexts.
73
+ */
74
+ export function themedInlineContext(
75
+ tokens: readonly InlineToken[],
76
+ context: InlineStyleContext,
77
+ theme: EmphasisTheme,
78
+ ): InlineStyleContext {
79
+ const owner = childOwners.get(tokens);
80
+ for (const token of tokens) {
81
+ if (token.tokens && isChildOwner(token.type)) childOwners.set(token.tokens, token.type);
82
+ }
83
+ if (!owner || nativeContexts.has(context)) return context;
84
+ const surrounding = surroundingContexts.get(context) ?? context;
85
+ if (owner === "link") return withNativeEmphasis({ ...surrounding });
86
+ return emphasisContext(surrounding, MARKDOWN_EMPHASIS_COLORS[owner], theme);
87
+ }
@@ -0,0 +1,123 @@
1
+ import { stripTerminalSequences } from "@earendil-works/pi-tui";
2
+
3
+ /**
4
+ * Transcript Markdown spacing policy. This is the only place that decides list
5
+ * spacing; change the table below to tune it. It applies to every list the same
6
+ * way: unordered or ordered, short or wrapped, nested, task, loose or complex.
7
+ *
8
+ * - Pi's Markdown source and parsed tokens are never changed. Items and token
9
+ * lists are copied, because Pi caches its parsed tokens between renders.
10
+ * - Only blank rows change. Text, emphasis, wrapping and markers stay Pi's.
11
+ * - A boundary that already has a blank row, from a source blank line or from
12
+ * Pi itself, does not get a second one.
13
+ * - Callers apply this to transcript Markdown only, so overlays stay native.
14
+ */
15
+ export const MARKDOWN_GAP_ROWS = {
16
+ /** A paragraph directly followed by a list. */
17
+ beforeList: 1,
18
+ /** A list directly followed by another block, such as a heading. */
19
+ afterList: 1,
20
+ /** Sibling items, at every nesting depth. */
21
+ betweenItems: 1,
22
+ /** Blocks inside one item, such as its text and its nested list. */
23
+ withinItem: 1,
24
+ } as const;
25
+
26
+ export interface MarkdownBlockToken {
27
+ type: string;
28
+ raw?: string;
29
+ text?: string;
30
+ }
31
+
32
+ export interface MarkdownListItemToken {
33
+ tokens: MarkdownBlockToken[];
34
+ }
35
+
36
+ export interface MarkdownListToken extends MarkdownBlockToken {
37
+ items: MarkdownListItemToken[];
38
+ loose: boolean;
39
+ start?: number | "";
40
+ }
41
+
42
+ const blankRows = (count: number): string[] => Array.from({ length: count }, () => "");
43
+
44
+ const isBlankRow = (row: string): boolean => stripTerminalSequences(row).trim() === "";
45
+
46
+ /** Rows to add after a top-level or blockquote block that Pi leaves unspaced. */
47
+ export function gapRowsAfterBlock(type: string | undefined, nextType: string | undefined): string[] {
48
+ if (type === "paragraph" && nextType === "list") return blankRows(MARKDOWN_GAP_ROWS.beforeList);
49
+ if (type === "list" && nextType !== undefined && nextType !== "space") {
50
+ return blankRows(MARKDOWN_GAP_ROWS.afterList);
51
+ }
52
+ return [];
53
+ }
54
+
55
+ type ItemTokenOutput = "none" | "blank" | "content";
56
+
57
+ /**
58
+ * What a token inside a list item emits. Pi draws a `checkbox` as part of the
59
+ * item marker, so it emits nothing; treating it as content would part the marker
60
+ * from its text. An empty `text` still emits a row, but that row is blank.
61
+ */
62
+ function itemTokenOutput(token: MarkdownBlockToken): ItemTokenOutput {
63
+ if (token.type === "checkbox" || token.type === "def") return "none";
64
+ if (token.type === "space") return "blank";
65
+ if (token.type === "text" || token.type === "paragraph") {
66
+ return token.text?.trim() ? "content" : "blank";
67
+ }
68
+ if (token.type === "html") return token.raw?.trim() ? "content" : "blank";
69
+ return "content";
70
+ }
71
+
72
+ /**
73
+ * Returns a copy of the item with a gap between adjacent content blocks and with
74
+ * no trailing blank rows. Because no item ends blank, nested lists never end
75
+ * blank either, so the gap after them cannot double. Pi's blocks add their own
76
+ * trailing gap only when told a next token type, and item blocks are not told.
77
+ */
78
+ function withItemBlockGaps(item: MarkdownListItemToken): MarkdownListItemToken {
79
+ const tokens: MarkdownBlockToken[] = [];
80
+ let previousOutput: ItemTokenOutput = "none";
81
+ for (const token of item.tokens) {
82
+ const output = itemTokenOutput(token);
83
+ if (previousOutput === "content" && output === "content") {
84
+ for (let row = 0; row < MARKDOWN_GAP_ROWS.withinItem; row += 1) tokens.push({ type: "space" });
85
+ }
86
+ if (output !== "none") previousOutput = output;
87
+ tokens.push(token);
88
+ }
89
+ while (tokens.length > 0 && itemTokenOutput(tokens[tokens.length - 1]) !== "content") tokens.pop();
90
+ return { ...item, tokens };
91
+ }
92
+
93
+ /** Joins rendered items, skipping the gap where a blank row already separates them. */
94
+ function joinItems(renderedItems: readonly string[][]): string[] {
95
+ const rows: string[] = [];
96
+ for (const itemRows of renderedItems) {
97
+ const previousRow = rows[rows.length - 1];
98
+ const nextRow = itemRows[0];
99
+ if (previousRow !== undefined && nextRow !== undefined && !isBlankRow(previousRow) && !isBlankRow(nextRow)) {
100
+ rows.push(...blankRows(MARKDOWN_GAP_ROWS.betweenItems));
101
+ }
102
+ rows.push(...itemRows);
103
+ }
104
+ return rows;
105
+ }
106
+
107
+ /**
108
+ * Renders a list one item at a time through Pi's own list renderer, which
109
+ * re-enters this policy for nested lists. `loose` is cleared so that Pi's
110
+ * loose-list gap cannot add to the gap chosen here.
111
+ */
112
+ export function renderSpacedList(
113
+ list: MarkdownListToken,
114
+ renderList: (singleItemList: MarkdownListToken) => string[],
115
+ ): string[] {
116
+ const start = typeof list.start === "number" ? list.start : 1;
117
+ return joinItems(list.items.map((item, index) => renderList({
118
+ ...list,
119
+ start: start + index,
120
+ loose: false,
121
+ items: [withItemBlockGaps(item)],
122
+ })));
123
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-pretty-tui",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "A beautiful, polished TUI for the Pi coding agent",
5
5
  "license": "MIT",
6
6
  "author": "Kainan Yang <ykn0309@whu.edu.cn>",
@@ -15,7 +15,7 @@
15
15
  },
16
16
  "scripts": {
17
17
  "typecheck": "tsc -p tsconfig.json",
18
- "test": "npm run typecheck && node tests/regression.mjs && node tests/coexistence.mjs && node tests/selection-ranges.mjs && node tests/selection-options.mjs",
18
+ "test": "npm run typecheck && node tests/regression.mjs && node tests/coexistence.mjs && node tests/selection-ranges.mjs && node tests/selection-options.mjs && node tests/markdown-spacing.mjs && node tests/markdown-emphasis.mjs",
19
19
  "test:selection-pty": "python3 tests/selection-pty.py",
20
20
  "bench:selection": "node tests/selection-benchmark.mjs",
21
21
  "test:selection-cli": "python3 tests/selection-cli.py",
@@ -45,8 +45,8 @@
45
45
  "@earendil-works/pi-tui": "*"
46
46
  },
47
47
  "devDependencies": {
48
- "@earendil-works/pi-coding-agent": "1.4.0",
49
- "@earendil-works/pi-tui": "1.4.0",
48
+ "@earendil-works/pi-coding-agent": "1.5.0",
49
+ "@earendil-works/pi-tui": "1.5.0",
50
50
  "@types/node": "^24.0.0",
51
51
  "jiti": "^2.7.0",
52
52
  "typescript": "^5.9.0"