# Implementation and compatibility / 实现与兼容性

[English](#english) | [简体中文](#简体中文)

## English

For feature overviews and everyday controls, see the [README](../README.md). For all settings and defaults, see the [configuration reference](./configuration.md#english). This document dives into the internals behind those features: measurement formulas, rendering rules, lifecycle management, and compatibility boundaries.

### Lifecycle and data sources

[index.ts](../extensions/open-tui/index.ts) wires Pi events into the UI. At `session_start`, it loads the configuration and—when enabled in a TUI context—mounts the footer, editor decoration, Copy-button integration, and header (if `header` is enabled). Tool renderers are registered separately; because Pi can rebuild a resumed transcript before `session_start`, config is read early when needed.

While an agent run is active, the working timer requests a redraw every 250 ms. Async Git and runtime reads capture a session generation token so stale results are discarded if the session switches or shuts down (see [session-lifecycle.ts](../extensions/open-tui/session-lifecycle.ts)). On shutdown, timers stop, contributed footer segments are deactivated, UI components unmount cleanly, and compact tool animations halt.

#### Data modules

- **Git parsing ([git.ts](../extensions/open-tui/git.ts))**: Parses `git status --porcelain=v1 --branch` and reads commit, tag, and stash metadata as needed. Every Git command has a 2-second timeout, and failed reads fall back to an empty Git state. Disabling both `gitBranch` and `gitStatus` skips refreshes completely; `gitCommit` only adds a tag to detached `HEAD` output.
- **Git refresh scheduling ([git-refresh.ts](../extensions/open-tui/git-refresh.ts))**: Serializes Git commands so reads never overlap. Tool completions trigger a refresh with a 500 ms minimum interval between starts, coalescing bursts into one trailing refresh. Agent completion expedites any pending refresh, while session start, branch switches, and settings changes request an immediate read. Session changes, shutdown, or disabling the UI cancel queued work and invalidate in-flight results. Tool runs do not trigger runtime re-detection, and external changes made while Pi is idle are not polled.
- **Runtime detection ([runtime.ts](../extensions/open-tui/runtime.ts))**: Walks an ordered list of 50+ runtimes and picks the first match based on files, folders, extensions, and environment variables in the working directory. Version commands use a 2.5-second timeout and cache results by directory, runtime, and a fingerprint of relevant files/env vars. If a version lookup fails, the runtime icon still renders. Detection only runs when both the extension and `footerSegments.runtime` are enabled, and re-enabling the segment refreshes it.
- **Session state ([state.ts](../extensions/open-tui/state.ts))**: Reads model metadata and session usage. Usage totals are cached per session manager and leaf ID, invalidating on message completion, compaction, tree changes, and session start.

#### Python version detection

Python version lookups require `ctx.isProjectTrusted()` to be `true`:

1. **Project `.venv` first, then `VIRTUAL_ENV`**: An environment matches if it contains `pyvenv.cfg` or an interpreter path (`Scripts/python.exe` on Windows; `bin/python` or `bin/python3` on macOS/Linux). Even a dangling interpreter symlink still selects that environment.
2. **Metadata without execution**: `pi-open-tui` reads `version` or `version_info` directly from `pyvenv.cfg` on each refresh—never executing the virtual environment's interpreter. If the chosen environment has no interpreter file or no readable version in `pyvenv.cfg`, only the Python icon is shown.
3. **System fallback**: Only when `.venv` is absent and `VIRTUAL_ENV` is unset or empty does detection run `python3 --version` using the inherited `PATH` and `os.tmpdir()` as the working directory (both are included in the fallback cache fingerprint). `.python-version` files are never treated as installed versions.

### Editor and layout

#### Editor framing and cursor styles

[editor.ts](../extensions/open-tui/editor.ts) decorates the existing editor instance in place so input callbacks, completions, and ghost text keep working untouched. To be framed, an editor must expose native-style borders alongside focus, border-color, mouse, and padding hooks. An initial probe checks for those borders—if capabilities are missing, the layout isn't recognized, or the probe throws, the editor stays undecorated. Each framed render re-checks the borders; if they temporarily disappear, that render falls back to full width without frame mouse offsets and resumes framing once borders return.

Editor factories registered via the current `ctx.ui.setEditorComponent()` API work regardless of whether they load before or after `pi-open-tui`. Runtime editor replacements (including those triggered from a fresh shortcut context) are decorated when mounted, while temporary dialogs are left untouched. Cleanup restores only methods still owned by `pi-open-tui`, preserving the latest factory and any later wrappers. This ordering guarantee does not apply to header/footer replacements or extensions that bypass the current registration API with a saved setter or direct method patches.

For cursor shapes, **Block** keeps the editor's native cursor behavior, while **Bar** and **Underline** enable the terminal's hardware cursor and emit cursor-shape escape sequences (requiring terminal support). Cleanup restores the previous hardware-cursor visibility.

#### Responsive footer layout

[footer.ts](../extensions/open-tui/footer.ts) and [utils.ts](../extensions/open-tui/utils.ts) fit segments against visible terminal width:

- **Regular two-row footer**: When no external segments are present, row 1 compacts fields first (directory basename, context percentage only, timer without live TPS) before shrinking or dropping runtime/context, then Git, session name, hostname/timer, and finally the directory. Row 2 prioritizes token/cost statistics over the model label.
- **Inline mode (`inlineFooter: true`)**: Moves row 1 into the top editor border (session name and Git on the left; directory, hostname, runtime, timer, and context on the right) and row 2 into the bottom border (model on the left; tokens and cost on the right). If no compatible framed editor is active, the footer automatically stays separate.
- **Extension status rows**: Always render outside the editor frame and may wrap. Styled statuses preserve ANSI colors; unstyled statuses use the muted theme color. Control sequences and line breaks are stripped.
- **Contributed main-row segments**: Follow the shared width and priority rules in [Extension footer segments](./footer-segments.md#placement-and-width). Hiding a built-in field leaves its anchor usable. Replacing the footer, disabling the extension, or shutting down the session invalidates the contribution lifecycle—contributors must republish once a new lifecycle starts.

### Usage and telemetry

#### Session totals in the footer

Footer totals aggregate assistant messages, tool-reported usage, standalone usage entries (such as cache warming), compaction, and branch summaries. Input tokens are split into uncached input (`U = input + cacheWrite`) and cache reads (`R = cacheRead`), e.g. `12k (U 2k + R 10k)`. Cost sums all recorded `usage.cost.total` values.

The cache-hit percentage reflects only the **latest assistant response**: `cacheRead / (input + cacheRead + cacheWrite) × 100`. It is not a cumulative session average and is omitted if no cache usage has been reported or the latest response has no valid denominator.

#### End-of-run telemetry notification

[telemetry.ts](../extensions/open-tui/telemetry.ts) combines all measurable assistant turns into a single notification at `agent_settled`:

| Metric | Formula and boundaries |
| --- | --- |
| **TPS** | Sum of provider-reported assistant output tokens divided by total generation seconds (`turn_start` → assistant `message_end`). Includes TTFT, reasoning, provider buffering, and stalls; excludes tool execution between turns. Shows `—` when output tokens or measurable time are missing |
| **TTFT** | Time from the first measured turn's `turn_start` to its first nonempty text, thinking, or tool-call-argument delta. If only final usage arrives with no streaming deltas, message completion is used instead |
| **Duration** | Total elapsed time from `agent_start` to `agent_settled`, including tool execution |
| **Tokens** | Assistant token usage across measured turns, with input split into uncached (`input + cacheWrite`) and cache reads |
| **Stalls** | Gaps of ≥ 1 second between nonempty stream updates after output starts. Consecutive ≥ 1 s gaps merge into a single stall until a shorter gap arrives; the full gap counts toward stall duration. Shown only when at least one stall occurs |
| **`$ / M`** | `sum(usage.cost.total) / (sum(usage.totalTokens) / 1,000,000)` — an effective blended rate across input, output, and cache tokens for the run (not cumulative session spend). Omitted without positive cost and token totals |

A turn is skipped if it lacks a completed assistant message or observed output (either a nonempty streamed text/thinking/tool-call delta or a positive final output token count). Runs with no measurable turns emit no notification. Provider buffering or omitted usage fields naturally limit what can be measured, and unlike footer totals, this notification covers assistant turns only.

#### Live TPS estimate

Live TPS estimates streaming speed from text, thinking, and tool-call argument chunks over a trailing 2-second window (~4 characters per token for Latin text/code, 1 token per CJK character). During a pause, the rate decays toward zero; during tool execution and between messages, the last rate stays visible in dim text until resetting at `agent_settled`. Because it is a client-side estimate, it can differ from the provider-reported final TPS and has its own `footerSegments.liveTps` toggle.

### Thinking labels

[peek.ts](../extensions/open-tui/peek.ts) tracks `idle`, `thinking`, and `done` states. It extracts the latest nonempty reasoning lines, normalizes whitespace, and strips terminal control sequences before rendering. Width is measured against the actual message component rather than the raw terminal, so sidebar or split-layout extensions are handled properly.

In 2-line mode, a long latest line wraps across both rows; otherwise the previous and latest lines align to the same indent. Clipping preserves the newest tail while respecting display width and grapheme boundaries. Once answer text arrives or the assistant message finishes, the spinner freezes into a checkmark. After the run settles, the native label returns after a brief delay (guarded so an older cleanup never wipes out a newer task's label). Visibility always defers to Pi's own Hide thinking toggle.

### Tool rendering

[tool-view.ts](../extensions/open-tui/tool-view.ts) wraps tool rendering only—execution, arguments, results, and model-visible content are untouched. Built-in compact summaries apply only when Pi tags the tool source as `builtin`. Same-name replacement tools keep their native renderer unless both compact mode and `toolView.extensionTools` are enabled (in which case they use extension handling). `toolView.exclude` overrides both rules.

- **Status indicators**: Pending rows show a dim dot; running rows pulse between accent and dim once per second; completed rows use dim text with a green dot; errors keep a red dot and summary.
- **Shell output**: Running commands display the latest 3 nonempty lines; failures preserve the exit status and final output line. Known tool truncation notices are summarized cleanly without stripping unrelated bracketed text or error messages.
- **Caching and expansion**: Completed rows cache their rendered lines until width, theme, icons, or invalidation changes. Each call stays independent. Expanding a row uses Pi's resolved native renderer (falling back to generic argument/output components only if an extension lacks one). Inline images remain visible even when collapsed because Pi draws them below the row.

#### Edit and write previews

[tool-preview.ts](../extensions/open-tui/tool-preview.ts) parses Pi's actual edit diff (malformed diffs skip preview generation rather than guessing). Old and new code are syntax-highlighted independently with red/green line backgrounds, and adjacent removed/added blocks are paired for stronger inline word-diff highlights when they share enough content.

To stay responsive, word matching caps edit distance at 256: lines up to 512 characters run without a wall-clock timeout (so OS scheduling jitter won't drop highlights), lines from 513 to 4,096 characters use a 5 ms budget, and longer or unmatched lines fall back to whole-line highlighting. Syntax highlighting enforces its own input-size budget.

Write previews render the submitted content with line numbers on the standard background—new files and overwrites look identical without synthesizing an old-file diff. Previews appear only on completed, successful `edit` / `write` calls, capped at 16 body rows (including context and ellipsis lines) plus a hidden-row count and `Ctrl+O` hint. Long preview lines truncate with `…` while collapsed; expanding restores Pi's native view.

Built-in **`codemode`** rows omit the optional script options header from the call summary. Compact results show up to 3 recent nested calls (status, key argument, duration), with a count and expand hint for earlier ones, followed by script status, total calls, running/failed/cancelled counts, duration, image count, and a truncation marker when `details.fullOutputPath` exists. One output line follows (skipping Pi's script header and text/console separators), or the last `Script error:` reason on failure. Native `codemode` rendering initializes lazily on expansion to avoid hidden syntax-highlighting and timer overhead while collapsed.

Built-in **`tool_search`** reads `details.loaded` to show the loaded count and up to 3 tool names, with clear messages for zero matches or additional tools (falling back to a generic summary if metadata is invalid). Because `tool_search` has no dedicated native renderer, expanding uses Pi's generic layout.

#### Extension and FFF summaries

With `toolView.extensionTools` enabled, unrecognized tools get a generic summary: nonempty text line count, image count, duration, and the first text line (no edit/write previews). Truncation indicators require an explicit `details.truncation.truncated: true`; valid total line counts may replace the shown count, without interpreting built-in-only limit fields. Running rows display elapsed time even before the first partial result arrives.

Native extension renderers initialize on first expansion. Once collapsed again, hidden progress updates are skipped, though completion and error events are still forwarded to already-initialized renderers so their internal timers can stop. Tools that rely on live native progress should be added to `toolView.exclude`.

Recognized `@ff-labs/pi-fff` installations receive dedicated search summaries: `ffgrep` and `fff-multi-grep` report the current page's match count, and `fffind` reports the total matching file count (including FFF's `grep` / `find` / `multi_grep` overrides). Pagination, fuzzy/regex-to-literal fallbacks, and weak-match cap hints are preserved, and indexed file counts are never misreported as matches. Recognition checks Pi's npm source metadata, the installed npm entry path, or the official `dmtrKovalenko/fff` GitHub source with its `packages/pi-fff/src/index.ts` entry point; unrecognized sources or metadata fall back to the generic summary. Expanding preserves FFF's native output and line-length limits.

### Copy-button behavior

[copy-buttons.ts](../extensions/open-tui/copy-buttons.ts) adds clickable `[Copy]` controls to Markdown code blocks, user messages, and framed editor drafts in fullscreen mode.

#### Code blocks and user messages

- **Width thresholds**: Code blocks narrower than 8 columns keep native fences; 8–15 columns draw a plain frame without a label; 16+ columns show `[Copy]` once completed. Long code lines wrap inside the frame. Top and bottom borders replace the fence lines, so the button never adds extra vertical lines. Thinking blocks keep native fences, and streaming code blocks stay unlabeled until streaming completes.
- **Caching and exact source matching**: Each Markdown instance tracks block descriptors and occurrence-specific copy regions. Internal markers survive Pi's block cache and are stripped before display; occurrence matching restores source tabs that Pi normalizes for rendering, and identical repeated blocks still map to their own source occurrence. Policy changes (such as streaming completion) invalidate the cache so buttons appear immediately without a resize.
- **User messages**: The label sits on the bubble's last row and copies the original message; code buttons copy raw code without fences.

#### Input drafts and click safety

A framed editor adds `[Copy]` for nonempty drafts inside its actual border-fill spans, preferring the bottom border and falling back to the top. The label needs 10 free border cells (12 columns total for a plain frame), including padding and side borders, and never overwrites footer, working-status, or scroll text. Editors lacking `getExpandedText()` stay framed without a draft Copy button. Draft snapshots and clipboard payloads use `getExpandedText()` so folded pastes copy in full—without trimming whitespace or including completions/ghost text.

Normal text selection still goes to Pi. Only a qualifying left-button release on a recorded Copy press triggers a copy. Moving, removing, or changing the target—as well as editor replacement, draft/resize changes before release, disabling, or cleanup—cancels an in-progress click. The fullscreen release hook clears any temporary selection so a successful Copy gesture never moves the cursor or changes focus, and async clipboard completions from a cleaned-up instance never flash a notification.

#### Component integration boundaries

Some integrations rely on Pi component internals: Copy buttons verify required Markdown and fullscreen mouse methods before installing, and per-message thinking labels and editor mounting inspect component structure. Other extensions patching the same renderers may affect compatibility. On cleanup, `pi-open-tui` restores only the methods it still owns and leaves any later wrappers intact.

## 简体中文

功能示例和日常使用见 [README](../README.zh-CN.md)，完整配置项与默认值见[配置参考](./configuration.md#简体中文)。本文介绍这些特性背后的实现机制、指标口径、渲染细节与兼容边界。

### 生命周期与数据来源

[index.ts](../extensions/open-tui/index.ts) 负责把 Pi 的生命周期事件接入界面。在 `session_start` 阶段读取配置后，只要处于启用状态且运行在 TUI 环境，就会依次挂载底栏、输入框装饰、复制按钮以及顶栏（当 `header` 开启时）。工具渲染器单独注册；由于恢复历史会话时 Pi 可能在 `session_start` 之前重建记录，配置会在需要时提前加载。

Agent 运行期间，工作计时器每 250 毫秒请求一次重绘。Git 和运行环境读取都会记录发起时的会话代次，一旦会话切换或关闭，迟到的异步结果会被直接丢弃（见 [session-lifecycle.ts](../extensions/open-tui/session-lifecycle.ts)）。会话关闭时，扩展会停止所有计时器、停用外部底栏片段、卸载界面组件，并终止紧凑工具的运行动画。

#### 核心数据模块

- **Git 解析（[git.ts](../extensions/open-tui/git.ts)）**：解析 `git status --porcelain=v1 --branch`，并按需读取提交、标签和 stash 信息。单条 Git 命令超时为 2 秒，读取失败时返回空状态。若同时关闭 `gitBranch` 和 `gitStatus`，则完全跳过刷新；`gitCommit` 仅用于给分离 `HEAD` 追加标签。
- **Git 刷新调度（[git-refresh.ts](../extensions/open-tui/git-refresh.ts)）**：串行调度 Git 命令，避免并发重叠。工具执行结束后会触发刷新，两次启动间隔至少 500 毫秒；高频连续请求会合并为一次尾随刷新。Agent 任务结束时会立即提前执行待刷任务；会话启动、分支切换和修改设置也会立即刷新。切换或关闭会话、禁用扩展时，排队任务会被取消且在途结果失效。工具事件不会重新触发运行环境检测，Pi 空闲时也不会轮询外部文件改动。
- **运行环境检测（[runtime.ts](../extensions/open-tui/runtime.ts)）**：按顺序遍历 50 多种运行环境定义，根据工作目录中的特征文件、目录、扩展名和环境变量选中第一个匹配项。版本命令超时为 2.5 秒，结果按“目录 + 运行环境 + 相关文件与环境变量指纹”缓存。版本号获取失败时仍会显示环境图标。仅在扩展和 `footerSegments.runtime` 均开启时才检测；重新开启该分段时会立即刷新。
- **会话状态（[state.ts](../extensions/open-tui/state.ts)）**：读取模型元数据和会话用量。用量缓存绑定会话管理器与当前叶节点 ID，在消息结束、压缩、会话树变化及会话启动时失效。

#### Python 版本检测

Python 版本检测要求 `ctx.isProjectTrusted()` 返回 `true`：

1. **优先项目 `.venv`，其次 `VIRTUAL_ENV`**：只要目录内存在 `pyvenv.cfg` 或解释器入口（Windows 为 `Scripts/python.exe`，macOS/Linux 为 `bin/python` 或 `bin/python3`），就会选中该环境；即使解释器是悬空符号链接，仍会被选中。
2. **直接读配置，不执行解释器**：每次刷新都会直接读取 `pyvenv.cfg` 中的 `version` 或 `version_info`，从不执行虚拟环境里的解释器。如果选中环境缺少解释器文件，或无法从 `pyvenv.cfg` 读出版本，则只显示 Python 图标。
3. **系统回退**：只有 `.venv` 不存在且 `VIRTUAL_ENV` 未设置或为空时，才以 `os.tmpdir()` 为工作目录、使用继承的 `PATH` 执行 `python3 --version`（两者均计入缓存指纹）。底栏不会把 `.python-version` 声明当成实际安装版本。

### 编辑器与布局

#### 输入框加框与光标样式

[editor.ts](../extensions/open-tui/editor.ts) 直接原地装饰同一个编辑器实例，完整保留输入回调、自动补全和灰字建议。被装饰的编辑器需要具备原生风格的边界以及焦点、边框颜色、鼠标和内边距接口。首次渲染时会探测边界——如果缺少必要能力、布局无法识别或探测抛错，就保持原样不加框；此后每次渲染也会复查边界，一旦边界临时消失，当次渲染会回退到全宽且不做鼠标坐标偏移，待边界恢复后再继续加框。

通过当前 `ctx.ui.setEditorComponent()` 注册的编辑器工厂无论在 `pi-open-tui` 之前还是之后加载，都能正常配合。运行时替换的编辑器（包括来自新快捷键上下文的替换）会在挂载时自动装饰，临时对话框则保持原样。卸载清理时仅恢复仍归属 `pi-open-tui` 的方法，保留最新的工厂和后注册的包装层。注意：该加载顺序保证不涵盖顶栏/底栏替换，也不适用于绕过当前注册 API（如缓存旧 setter 或直接改写接口方法）的扩展。

光标样式方面，**块（Block）** 沿用编辑器原生表现；**竖线（Bar）** 与 **下划线（Underline）** 会开启终端硬件光标并通过转义序列设置形状（需要终端支持），清理时恢复原有的硬件光标可见状态。

#### 自适应底栏排版

[footer.ts](../extensions/open-tui/footer.ts) 与 [utils.ts](../extensions/open-tui/utils.ts) 按终端可见宽度动态排版：

- **常规双行底栏**：没有外部注入片段时，第一行先将各字段切为紧凑形态（仅显示目录名、只显示上下文百分比、隐藏实时 TPS），空间仍不足时依次缩短或移除运行环境/上下文、Git、会话名、主机名/计时器，最后才是当前目录；第二行优先保住 Token 和费用统计，再缩短模型标签。
- **内嵌模式（`inlineFooter: true`）**：第一行移入上边框（左侧放会话名与 Git，右侧依次为目录、主机名、运行环境、计时器和上下文），第二行移入下边框（左侧模型，右侧 Token/费用）。若当前没有兼容的带框编辑器，则自动回退为独立底栏。
- **扩展状态行**：始终显示在编辑器边框外，支持自动换行。带样式的状态保留 ANSI 颜色，无样式文本使用 muted 主题色；终端控制命令和换行符会被过滤。
- **主底栏外部片段**：遵循[扩展底栏接口](./footer-segments.md#placement-and-width)中的共享宽度与优先级规则。隐藏内置字段不会移除对应锚点；底栏被替换、扩展关闭或会话结束都会使当前生命周期失效，提供方需在新生命周期重新发布。

### 用量与遥测

#### 底栏中的会话累计

底栏总量汇总了助手回复、工具结果上报的用量、缓存预热等独立用量条目、压缩以及分支摘要。输入 Token 拆分为未缓存输入（`U = input + cacheWrite`）与缓存读取（`R = cacheRead`），例如 `12k (U 2k + R 10k)`；费用则是所有 `usage.cost.total` 之和。

缓存命中率仅统计**最近一条助手回复**：`cacheRead / (input + cacheRead + cacheWrite) × 100`，而非会话累计均值。从未上报过缓存用量或最新回复缺少有效分母时，该项自动隐藏。

#### 任务结束遥测通知

[telemetry.ts](../extensions/open-tui/telemetry.ts) 在 `agent_settled` 时将所有可测量的助手轮次合并为一条汇总通知：

| 指标 | 计算口径与边界 |
| --- | --- |
| **TPS** | 服务商上报的助手输出 Token 总和除以总生成秒数（每轮从 `turn_start` 计至助手 `message_end`）。包含 TTFT、推理、服务商缓冲与停顿，不包含轮次间的工具执行时间；无输出 Token 或有效耗时时显示 `—` |
| **TTFT** | 首个被统计轮次从 `turn_start` 到收到第一段非空正文、思考或工具参数增量的时间。如果全程无流式增量、仅在结尾收到最终用量，则以消息结束时间为准 |
| **耗时** | 从 `agent_start` 到 `agent_settled` 的总耗时，包含工具执行 |
| **Token** | 被统计轮次的助手用量，输入同样拆分为未缓存（`input + cacheWrite`）与缓存读取 |
| **停顿** | 输出开始后，两次非空流式更新间隔 ≥ 1 秒记为停顿；连续满足条件的间隔合并为一次停顿，直到出现更短间隔，整个间隔时长计入停顿时间。仅在确实发生停顿时显示 |
| **`$ / M`** | `sum(usage.cost.total) / (sum(usage.totalTokens) / 1,000,000)`，即本次运行综合输入、输出和缓存后的每百万 Token 有效费率（非会话总费用）。缺少正数费用或 Token 总量时不显示 |

若某轮缺少完成的助手消息或可观测输出（非空流式正文/思考/工具参数增量，或正数的最终输出用量），该轮不计入统计；整次运行没有可统计轮次时不发通知。受服务商输出缓冲或用量字段缺失影响，实测值可能受限；此外，该通知只覆盖助手轮次，而底栏总计包含前述全部会话用量来源。

#### 实时 TPS 估算

实时 TPS 基于最近 2 秒的流式正文、思考和工具参数增量进行本地估算（拉丁字符与代码按约 4 字符 ≈ 1 Token，中日韩字符按 1 字 ≈ 1 Token）。流式停顿时数值会回落趋零；工具执行期间及消息间隙以暗色保留上一速度，任务结束后清零。该项由 `footerSegments.liveTps` 独立控制，估算结果与最终基于服务商用量的 TPS 可能存在差异。

### 思考标签

[peek.ts](../extensions/open-tui/peek.ts) 维护 `idle`、`thinking`、`done` 三种状态，提取最新的非空推理行、规范空白并去除终端控制序列。渲染宽度取自实际消息组件而非整窗宽度，因此在搭配侧栏或分屏布局扩展时也能准确贴合。

双行模式下，如果最新一条逻辑行过长，会直接占满两行；否则上一行与最新一行保持相同缩进。截断时保留最新尾部，并严格尊重显示宽度与完整字素边界。正文开始输出或助手消息完成后，旋转指示会定格为对勾；任务彻底结束后延迟片刻恢复 Pi 原生标签，并带保护逻辑防止旧任务清理误伤新任务。显示与否始终跟随 Pi 自身的 Hide thinking 开关。

### 工具渲染

[tool-view.ts](../extensions/open-tui/tool-view.ts) 只在展示层做渲染包装，不触碰工具执行、参数、结果或模型可见内容。仅当 Pi 将工具来源标记为 `builtin` 时才会套用内置摘要；同名替换工具默认维持原生卡片，只有在紧凑模式和 `toolView.extensionTools` 同时开启时才按扩展工具处理。`toolView.exclude` 优先级高于以上规则。

- **状态圆点**：等待中为暗色圆点；运行中每秒在强调色与暗色间交替；成功为绿色圆点配暗色文字；失败保留红色圆点与错误摘要。
- **Shell 输出**：运行中实时展示最新 3 行非空输出，失败时保留退出状态与末行输出。已知的工具截断提示会被精炼展示，同时不会误删普通方括号正文或报错信息。
- **缓存与展开**：已完成行会缓存渲染结果，仅在宽度、主题、图标变化或缓存失效时重绘，各次调用互不干扰。展开时调用 Pi 解析出的原生渲染器（仅当扩展未提供渲染器时回退到通用参数/输出组件）。内联图片由 Pi 绘制在工具行下方，因此折叠状态下依然可见。

#### 编辑与写入预览

[tool-preview.ts](../extensions/open-tui/tool-preview.ts) 直接解析 Pi 生成的真实编辑 diff（格式异常时放弃预览而非猜测）。旧代码与新代码分别做语法高亮，删除/新增行分别配红/绿背景；相邻的删增行组若内容足够相似，会配对做更醒目的行内词级差异高亮。

为保证交互流畅，词级匹配将编辑距离限制在 256 以内：长度不超过 512 字符的行不设墙钟超时（避免系统调度抖动导致词高亮偶发丢失）；513 至 4,096 字符的行设 5 毫秒超时；更长或未匹配的行退回整行高亮。语法高亮本身也设有独立的输入长度上限。

写入预览直接展示提交的内容，在普通背景上附带行号，新建与覆写样式一致，不伪造旧文件 diff。预览仅出现在已成功完成的 `edit` / `write` 上，正文最多 16 行（含上下文与省略行），超出部分给出隐藏行数和 `Ctrl+O` 提示。折叠时过长行以 `…` 截断，展开后恢复 Pi 原生视图。

内置 **`codemode`** 的调用摘要会自动跳过可选的脚本选项头。紧凑结果最多列出最近 3 条子调用（状态、关键参数与耗时），更早的调用收拢为数量与展开提示；下方展示脚本状态、总调用数、运行/失败/取消计数、耗时、图片数，并在存在 `details.fullOutputPath` 时标注输出截断，随后附一行输出（跳过 Pi 的脚本状态头与正文/控制台分隔标记）或在失败时显示最后一个 `Script error:` 原因。`codemode` 原生渲染会在展开时才延迟初始化，避免折叠状态下产生多余的高亮与计时器开销。

内置 **`tool_search`** 读取 `details.loaded` 展示已加载数量和最多 3 个工具名，对无匹配和更多工具均给出明确提示（元数据异常时退回通用摘要）。由于该工具没有专用原生渲染器，展开时使用 Pi 通用布局显示完整结果。

#### 扩展与 FFF 摘要

开启 `toolView.extensionTools` 后，未知扩展工具统一使用通用摘要：非空文本行数、图片数、耗时与首行文本，不附带编辑/写入预览。截断标记要求明确提供 `details.truncation.truncated: true`；有效总行数可替换显示行数，但不会去猜测内置工具专用的限制字段。即使尚未收到首条部分结果，运行行也会显示已用时间。

扩展原生渲染器在首次展开时才初始化；再次折叠后会跳过隐藏期间的进度更新，但完成与错误事件仍会转发给已初始化的渲染器，确保其内部计时器能够正常停止。依赖原生实时进度展示的工具可写入 `toolView.exclude`。

对已识别的 `@ff-labs/pi-fff` 扩展，会启用专门的搜索摘要：`ffgrep` 和 `fff-multi-grep` 显示当前页命中数，`fffind` 显示总匹配文件数（同样覆盖 FFF 的 `grep` / `find` / `multi_grep` 覆盖名），并完整保留分页、模糊搜索、正则转字面搜索及弱匹配上限提示，不会把已索引文件数误报为命中数。识别依据包括 Pi 的 npm 来源元数据、已安装 npm 包入口路径，或官方 `dmtrKovalenko/fff` GitHub 仓库及其 `packages/pi-fff/src/index.ts` 入口；未识别的来源或元数据退回通用摘要。展开后保留 FFF 原生输出与行长限制。

### 复制按钮行为

[copy-buttons.ts](../extensions/open-tui/copy-buttons.ts) 在全屏模式下为 Markdown 代码块、用户消息和带框输入框草稿提供可点击的 `[Copy]` 按钮。

#### 代码块与用户消息

- **宽度阈值**：代码块宽度不足 8 列时保持原生围栏；8～15 列绘制无标签圆角边框；达到 16 列且输出完成后显示 `[Copy]`。超长代码行在边框内自动换行，上下边框直接替代围栏行，不额外增加高度。思考块始终保留原生围栏，流式代码块则在输出完成后才显示标签。
- **缓存与精准匹配**：每个 Markdown 实例独立维护代码块描述与按出现次序定位的复制区域。内部标记会随 Pi 的块缓存留存并在最终渲染前剥离；按次序匹配源码可准确还原 Pi 渲染时规范化的制表符，即便出现完全相同的代码块也能各自对应原始片段。当流式结束等状态变化时，缓存会自动失效，无需调整窗口大小即可立刻显示按钮。
- **用户消息**：标签位于消息气泡末行，复制用户原文；代码块按钮则复制不含围栏标记的纯代码。

#### 输入草稿与点击保护

带框输入框在存在非空草稿时，会沿实际边框填充区放置 `[Copy]`（优先下边框，空间不足时尝试上边框）。标签含留白与两侧边框共需 10 列空余空间（纯边框总宽至少 12 列），绝不覆盖或挤压底栏、工作状态与滚动提示。未实现 `getExpandedText()` 的编辑器仍保留边框，但不显示草稿复制按钮。草稿快照和剪贴板内容均取自 `getExpandedText()`，因此折叠粘贴的内容会被完整复制，既不裁剪首尾空白，也不会混入补全或灰字建议。

普通拖选依然交由 Pi 原生处理，只有在已记录的复制区域按下并满足条件的鼠标左键释放才会触发复制。若松开前目标移动、消失、内容变动，或发生编辑器替换、终端尺寸变化、关闭功能或卸载清理，未完成的点击都会立即取消。沿用全屏释放钩子清除临时选区后，成功复制不会移动光标或抢占焦点；已卸载实例残留的异步剪贴板回调也不会再弹出通知。

#### 组件集成边界

部分功能依赖 Pi 的内部组件结构：复制按钮安装前会检测所需的 Markdown 和全屏鼠标方法，逐消息思考标签与编辑器挂载也会检查组件结构。如果其他扩展同时修改了相同渲染器，可能会影响兼容性。卸载清理时，`pi-open-tui` 只恢复仍由自身持有的方法，保留后续叠加的其他包装层。
