@georgewuw/pi-chat-navi 0.0.0-stage → 0.1.1

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/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ # Changelog
2
+
3
+ 本项目的版本变更记录。Pi 在包升级后会读取本文件(`package.json` 的 `version` 增长时生效)。
4
+
5
+ ## [0.1.0] - 2026-11-27
6
+
7
+ ### Added
8
+
9
+ - `/questions` 命令:右上角浮动面板列出当前活动上下文里的用户提问,↑↓ 选择、回车跳转。
10
+ - 回合分析视图:→ 或 `d` 进入,展示思考、工具调用与输出;`t` 切换仅看思维链。
11
+ - 宽度记忆:`/questions 50`(列数)或 `/questions 60%`(百分比)。
12
+ - 跳转优先使用 transcript 的 OSC 133;A 标记,失败时退回文本匹配。
13
+ - 作为 npm 包直接发布 TypeScript 源码:`pi.extensions` 指向 `./src/index.ts`,pi 通过 jiti 加载,安装方无需构建。
14
+ - npm 包名使用 `@georgewuw/pi-chat-navi`,并设置 `publishConfig.access = "public"`。
15
+ - 契约测试与 `pnpm run test:compat` 版本矩阵,验证对 pi TUI 内部实现的假设。
16
+ - 开发与发布使用 pnpm,`packageManager` 固定版本,锁文件为 `pnpm-lock.yaml`。
package/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 pi-chat-navi contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ ---
package/README.md CHANGED
@@ -1,3 +1,92 @@
1
- # Temporary Holding Version
1
+ # pi-chat-navi
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ npm 包:`@georgewuw/pi-chat-navi`
4
+
5
+ [pi coding agent](https://github.com/earendil-works/pi-coding-agent) 扩展:在 TUI 里用 `/questions` 打开「用户提问列表」浮动面板,用键盘选择后回车即可跳回会话中的任意一次提问。
6
+
7
+ ## 功能
8
+
9
+ - 面板停靠在右上角,列出**当前 transcript 实际显示**的用户提问(序号 + 摘要);被压缩掉的旧提问不会出现。列表放不下时,上下会显示 `↑ more` / `↓ more`
10
+ - 键盘:↑↓ 选择,回车(或空格)跳转,→ 或 `d` 进入该提问的「回合分析」,Esc 关闭(回合分析内 ←/Esc 先返回列表,`t` 切换仅看思维链)
11
+ - 鼠标仅支持回合分析详情区的滚轮(详情区右侧显示滚动条);单击/双击/悬停均无效果
12
+ - 宽度:默认 60%。`/questions 50` 指定列数,`/questions 60%` 指定百分比。设置在会话内记忆;面板已打开时带参数会以新宽度重开
13
+
14
+ ## 安装
15
+
16
+ 从 npm 安装(推荐):
17
+
18
+ ```
19
+ pi install npm:@georgewuw/pi-chat-navi # 最新版
20
+ pi install npm:@georgewuw/pi-chat-navi@0.1.0 # 固定版本
21
+ ```
22
+
23
+ 也可以从 git 或本地路径安装:
24
+
25
+ ```
26
+ pi install git:github.com/georgewuw/pi-chat-navi
27
+ pi install ./pi-chat-navi
28
+ ```
29
+
30
+ 安装后重启 pi,在会话里输入 `/questions` 即可。
31
+
32
+ 只试用一次、不写入设置:
33
+
34
+ ```
35
+ pi -e npm:@georgewuw/pi-chat-navi
36
+ ```
37
+
38
+ ### 本地开发
39
+
40
+ 本仓库使用 pnpm(`package.json` 的 `packageManager` 已固定版本,lockfile 为 `pnpm-lock.yaml`):
41
+
42
+ ```
43
+ corepack enable # 首次使用:让 corepack 按 packageManager 准备 pnpm
44
+ pnpm install
45
+ pi -ne -e . # pi 用 jiti 直接加载 src/index.ts,无需构建
46
+ ```
47
+
48
+ `package.json` 的 `pi.extensions` 指向 `./src/index.ts`;修改 `src/` 后重新加载即可。
49
+
50
+ ## 代码结构
51
+
52
+ | 文件 | 职责 |
53
+ |---|---|
54
+ | `src/index.ts` | 注册 `/questions`,解析宽度参数,把下面三部分接起来 |
55
+ | `src/logic.ts` | 纯逻辑:会话条目 → 提问列表、标记序号、回合分析。不依赖 pi |
56
+ | `src/jump.ts` | 跳转。**所有依赖 pi TUI 内部实现的代码都在这里** |
57
+ | `src/panel.ts` | 面板组件:状态、键鼠、渲染。不碰会话数据和 transcript |
58
+
59
+ 入口就是 `src/index.ts`:pi 通过 jiti 直接执行 `.ts`,不需要编译产物。
60
+
61
+ ## 测试
62
+
63
+ ```
64
+ pnpm install # 首次需要:契约测试依赖 devDependencies 里的真实 pi 包
65
+ pnpm run typecheck # tsc 类型检查
66
+ pnpm test # 逻辑单测 + 契约测试(针对 devDependencies 里装的 pi 版本)
67
+ pnpm run test:compat # 用 npm 上最新的 pi 版本跑契约测试
68
+ pnpm run test:compat -- 1.6.0 latest # 指定多个版本
69
+ pnpm run test:compat -- --keep 1.6.0 # 保留临时目录便于排查
70
+ pnpm run test:compat -- --verbose 1.6.0 # 失败时打印完整测试输出
71
+ ```
72
+
73
+ - `test/logic.test.mjs`:`logic.ts` 的纯函数。
74
+ - `test/contract.test.mjs`:直接用 `node --test` 运行并导入 `src/*.ts`(Node 22 原生类型剥离),不需要先构建。
75
+ 按 pi 的挂载方式搭一段 transcript,验证 `jump.ts` 与 `logic.ts` 对 pi 的假设:布局字段是否存在、
76
+ OSC 133;A 标记数量与序号是否与推算一致、标记法和文本匹配兜底是否都落在正确行。
77
+ pi 改了内部实现时,失败信息会指出是哪个字段或规则变了。
78
+ - 升级 pi 前后,运行 `pnpm run test:compat`;失败时先看失败信息指出的是哪条假设:跳转相关的改 `src/jump.ts`,
79
+ 标记数量/顺序相关(OSC 133;A 由哪些消息写入)的改 `src/logic.ts` 里镜像 pi 渲染规则的部分
80
+ (`assistantWritesMarker`、`renderedUserText`)。
81
+ - `test:compat` 与 `scripts/` 仅在本仓库内可用,不随 npm 包发布。
82
+ - 契约测试能证明「逻辑上的假设仍成立」,不能代替在真实 pi 里手动按一次 `/questions` 回车。
83
+
84
+ ## 说明
85
+
86
+ - 列表与标记序号基于 `sessionManager.buildContextEntries()`(压缩后的活动上下文),与 transcript 渲染一致;纯图片/空白的用户消息不会渲染组件,会被跳过。
87
+ - 跳转优先使用 transcript 里的 OSC 133;A 标记定位;标记失效(pi 改动标记规则)时自动退回文本匹配(遍历 `UserMessageComponent`,按归一化文本 + 渲染首行出现序定位)。
88
+ - 跳转仍依赖 pi TUI 的内部布局对象;pi 升级若改动这些内部实现,只有跳转会失效(会提示),面板本身不受影响。
89
+
90
+ ## 许可
91
+
92
+ MIT
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
- "name": "@georgewuw/pi-chat-navi",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@georgewuw/pi-chat-navi",
3
+ "version": "0.1.1",
4
+ "type": "module",
5
+ "packageManager": "pnpm@12.15.0",
6
+ "description": "pi coding agent extension:TUI 提问跳转面板(/questions)",
7
+ "license": "MIT",
8
+ "author": "georgewuw",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/georgewuw/pi-chat-navi.git"
12
+ },
13
+ "homepage": "https://github.com/georgewuw/pi-chat-navi#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/georgewuw/pi-chat-navi/issues"
16
+ },
17
+ "keywords": [
18
+ "pi-package",
19
+ "pi-extension",
20
+ "pi-coding-agent",
21
+ "tui",
22
+ "chat",
23
+ "navigation"
24
+ ],
25
+ "engines": {
26
+ "node": ">=22.19"
27
+ },
28
+ "files": [
29
+ "src",
30
+ "README.md",
31
+ "CHANGELOG.md",
32
+ "LICENSE"
33
+ ],
34
+ "scripts": {
35
+ "typecheck": "tsc -p .",
36
+ "test:compat": "node scripts/compat.mjs",
37
+ "test": "node --test test/logic.test.mjs test/contract.test.mjs",
38
+ "check": "pnpm run typecheck && pnpm test",
39
+ "prepublishOnly": "pnpm run check"
40
+ },
41
+ "pi": {
42
+ "extensions": [
43
+ "./src/index.ts"
44
+ ]
45
+ },
46
+ "peerDependencies": {
47
+ "@earendil-works/pi-coding-agent": "*",
48
+ "@earendil-works/pi-tui": "*"
49
+ },
50
+ "devDependencies": {
51
+ "@earendil-works/pi-coding-agent": "^1.6.0",
52
+ "@earendil-works/pi-tui": "^1.6.0",
53
+ "@types/node": "^26.6.6",
54
+ "typescript": "^7.0.2"
55
+ },
56
+ "publishConfig": {
57
+ "access": "public",
58
+ "registry": "https://registry.npmjs.org/"
59
+ }
60
+ }
package/src/index.ts ADDED
@@ -0,0 +1,149 @@
1
+ /**
2
+ * index.ts — 扩展入口
3
+ *
4
+ * `/questions [宽度]` 打开/关闭右上角的提问列表浮动面板:
5
+ * - 宽度:默认 60%;/questions 50(列数)或 /questions 60%(百分比),会话内记忆;
6
+ * 面板已打开时带参数会以新宽度重开
7
+ *
8
+ * 本文件把三部分接起来:logic.ts(会话数据)、panel.ts(面板 UI)、jump.ts(transcript 跳转)。
9
+ * 面板走公开 API:ctx.ui.custom(overlay) + Component.handleMouse。
10
+ */
11
+ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
12
+ import type { SizeValue } from "@earendil-works/pi-tui";
13
+ import { jumpToQuestion } from "./jump.ts";
14
+ import {
15
+ activeContextEntries,
16
+ buildTurnFromEntries,
17
+ collectQuestionsFromEntries,
18
+ markerOrdinalFromEntries,
19
+ occurrenceOf,
20
+ remapQuestionIndex,
21
+ type SessionEntryLike,
22
+ } from "./logic.ts";
23
+ import { PANEL_HEIGHT_RATIO, QuestionPanelComponent } from "./panel.ts";
24
+
25
+ /**
26
+ * 当前 transcript 实际渲染的条目。
27
+ * pi 只渲染 buildContextEntries() 的结果;被压缩掉的旧消息不在屏幕上,
28
+ * 若仍按 getBranch() 统计,序号会从压缩点开始整体偏移(跳错位置)。
29
+ */
30
+ function activeEntries(ctx: ExtensionCommandContext): SessionEntryLike[] {
31
+ try {
32
+ const entries = ctx.sessionManager.buildContextEntries();
33
+ if (Array.isArray(entries)) return entries as SessionEntryLike[];
34
+ } catch {
35
+ // 旧版 pi / 异常状态:退回当前分支 + 本地压缩过滤
36
+ }
37
+ return activeContextEntries(ctx.sessionManager.getBranch() as SessionEntryLike[]);
38
+ }
39
+
40
+ /** 解析宽度参数。null:未提供;false:非法(已 notify)。 */
41
+ export function parseWidthArg(args: string, notify: (msg: string) => void): SizeValue | null | false {
42
+ const t = args.trim();
43
+ if (!t) return null;
44
+ const m = /^(\d{1,3})(%?)$/.exec(t);
45
+ if (!m) {
46
+ notify("Invalid width; usage: /questions 50 (columns) or /questions 60% (percentage)");
47
+ return false;
48
+ }
49
+ const n = Number(m[1]);
50
+ if (m[2]) {
51
+ if (n < 20 || n > 100) {
52
+ notify("Percentage width must be between 20 and 100");
53
+ return false;
54
+ }
55
+ return `${n}%` as SizeValue;
56
+ }
57
+ if (n < 30 || n > 500) {
58
+ notify("Column width must be between 30 and 500");
59
+ return false;
60
+ }
61
+ return n;
62
+ }
63
+
64
+ export default function (pi: ExtensionAPI) {
65
+ // 面板打开期间非空;此时 /questions 充当「关闭」
66
+ let closePanel: (() => void) | null = null;
67
+ // 面板宽度(会话内记忆)
68
+ let panelWidth: SizeValue = "60%";
69
+
70
+ pi.registerCommand("questions", {
71
+ description:
72
+ "Open/close the questions panel (↑↓ select, Enter jump, → analyze; /questions 50 or /questions 60% sets width)",
73
+ handler: async (args, ctx) => {
74
+ if (ctx.mode !== "tui") {
75
+ ctx.ui.notify("question-panel requires interactive (tui) mode", "error");
76
+ return;
77
+ }
78
+
79
+ const parsed = parseWidthArg(args ?? "", (msg) => ctx.ui.notify(msg, "warning"));
80
+ if (parsed === false) return;
81
+ if (parsed !== null) panelWidth = parsed;
82
+
83
+ if (closePanel) {
84
+ closePanel();
85
+ if (parsed === null) return; // 无参数:纯关闭;带参数:换宽度重开
86
+ }
87
+
88
+ const questions = collectQuestionsFromEntries(activeEntries(ctx));
89
+ if (questions.length === 0) {
90
+ ctx.ui.notify("No user questions in this session yet", "info");
91
+ return;
92
+ }
93
+
94
+ await ctx.ui.custom<void>(
95
+ (tui, theme, _kb, done) => {
96
+ const panel = new QuestionPanelComponent(
97
+ tui,
98
+ theme,
99
+ questions,
100
+ (index) => {
101
+ // 面板开着时 agent 可能继续输出或压缩:每次跳转都按当前活动上下文重新推算
102
+ const entries = activeEntries(ctx);
103
+ const current = collectQuestionsFromEntries(entries);
104
+ const currentIndex = remapQuestionIndex(questions, index, current);
105
+ if (currentIndex < 0) {
106
+ ctx.ui.notify("Jump failed: this question is no longer in the active context", "warning");
107
+ return;
108
+ }
109
+ const item = current[currentIndex]!;
110
+ const ok = jumpToQuestion(tui, {
111
+ markerOrdinal: markerOrdinalFromEntries(entries, currentIndex),
112
+ text: item.text,
113
+ summary: item.summary,
114
+ occurrence: occurrenceOf(current, currentIndex),
115
+ });
116
+ if (!ok) {
117
+ ctx.ui.notify("Jump failed: cannot locate transcript (pi internals may have changed)", "warning");
118
+ }
119
+ },
120
+ (ordinal) => {
121
+ const entries = activeEntries(ctx);
122
+ const current = collectQuestionsFromEntries(entries);
123
+ const currentIndex = remapQuestionIndex(questions, ordinal, current);
124
+ const turn = currentIndex < 0 ? null : buildTurnFromEntries(entries, currentIndex);
125
+ if (!turn) ctx.ui.notify("Analysis unavailable: this question is no longer in the active context", "warning");
126
+ return turn;
127
+ },
128
+ () => {
129
+ closePanel = null;
130
+ done(undefined);
131
+ },
132
+ );
133
+ closePanel = () => panel.close();
134
+ return panel;
135
+ },
136
+ {
137
+ overlay: true,
138
+ overlayOptions: {
139
+ anchor: "top-right",
140
+ margin: 1,
141
+ width: panelWidth,
142
+ minWidth: 36,
143
+ maxHeight: `${Math.round(PANEL_HEIGHT_RATIO * 100)}%`,
144
+ },
145
+ },
146
+ );
147
+ },
148
+ });
149
+ }
package/src/jump.ts ADDED
@@ -0,0 +1,229 @@
1
+ /**
2
+ * jump.ts
3
+ *
4
+ * 跳转:把 transcript 滚动到某条用户提问。
5
+ * 本仓库里所有依赖 pi TUI 内部实现的代码都集中在这个文件;pi 升级后跳转失效,只需要查这里。
6
+ * test/contract.test.mjs 用真实的 pi 包验证这里的全部假设。
7
+ *
8
+ * pi 未公开暴露 transcript 组件,这里对 TUI 内部布局对象做运行时特征检测:
9
+ * currentLayout → 含 scrollContentLines 的 box → ScrollView.scrollTo(row)。
10
+ * 首选行定位利用 transcript 的 OSC 133;A 标记(UserMessageComponent 与无工具调用的
11
+ * AssistantMessageComponent 首行都会写入,与内置 previousPrompt/nextPrompt 跳转同源)。
12
+ * 标记法失败时退回文本匹配:遍历 transcript 组件树找 UserMessageComponent,
13
+ * 比较归一化文本 + 渲染首行在文档中的出现序(不再依赖标记规则)。
14
+ */
15
+ import { stripTerminalSequences, type TUI } from "@earendil-works/pi-tui";
16
+ import { normalizeMatchText } from "./logic.ts";
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // 跳转:运行时特征检测 pi 内部布局(失败优雅降级)
20
+ // ---------------------------------------------------------------------------
21
+
22
+ /** 用户/纯文本 assistant 消息首行的标记(OSC 133;A)。 */
23
+ const OSC133_A = /^\x1b\]133;A/;
24
+
25
+ /** 剥颜色/光标等序列与 OSC 133 区域标记,只用于行内容比较(pi-tui 公开导出)。 */
26
+ const stripLineAnsi = stripTerminalSequences;
27
+
28
+ interface ScrollViewLike {
29
+ scrollTo(row: number, opts?: { disableFollow?: boolean }): void;
30
+ /** ScrollView 的唯一子组件(transcript 文档根) */
31
+ child?: unknown;
32
+ getContentWidth?(width: number): number;
33
+ }
34
+ interface LayoutBoxLike {
35
+ scrollView?: unknown;
36
+ scrollContentLines?: readonly string[];
37
+ children?: LayoutBoxLike[];
38
+ }
39
+ interface TuiInternals {
40
+ requestRender?: () => void;
41
+ /** 渲染帧:{ root: 根盒, lines, primaryScrollView? }(getScrollViewBox 同源结构) */
42
+ currentLayout?: ({ primaryScrollView?: unknown; root?: LayoutBoxLike } & LayoutBoxLike) | undefined;
43
+ }
44
+
45
+ /** 在布局树里找到 transcript 的滚动视图与全部内容行。 */
46
+ export function findTranscript(tui: TUI): { scrollView: ScrollViewLike; lines: readonly string[] } | null {
47
+ // SAFETY: tui 是 pi 传入的 TuiAltScreen 实例,currentLayout 属性在运行时存在且未被混淆;
48
+ // 此处仅读取布局数据,不触内部方法,字段缺失时逐层判空返回 null。
49
+ const internals = tui as unknown as TuiInternals;
50
+ const layout = internals.currentLayout;
51
+ // 渲染帧形状:{ root: 根盒, lines, primaryScrollView? },盒子树挂在 root 上
52
+ const rootBox: LayoutBoxLike | undefined = layout?.root ?? layout;
53
+ if (!rootBox) return null;
54
+
55
+ const boxes: LayoutBoxLike[] = [];
56
+ const visit = (box: LayoutBoxLike): void => {
57
+ boxes.push(box);
58
+ for (const child of box.children ?? []) visit(child);
59
+ };
60
+ visit(rootBox);
61
+
62
+ // transcript = 滚动内容里带 OSC 133;A 标记的 scroll box
63
+ for (const box of boxes) {
64
+ const lines = box.scrollContentLines;
65
+ if (!Array.isArray(lines) || lines.length === 0) continue;
66
+ if (!lines.some((line) => OSC133_A.test(line ?? ""))) continue;
67
+
68
+ const scrollView = (box.scrollView ?? layout?.primaryScrollView) as ScrollViewLike | undefined;
69
+ if (!scrollView || typeof scrollView.scrollTo !== "function") return null;
70
+ return { scrollView, lines };
71
+ }
72
+ return null;
73
+ }
74
+
75
+ /** 目标行上方留一行上下文,禁用「跟随最新输出」后刷新。 */
76
+ function scrollToRow(tui: TUI, scrollView: ScrollViewLike, row: number): void {
77
+ scrollView.scrollTo(Math.max(0, row - 1), { disableFollow: true });
78
+ // SAFETY: 仅调用公开的 requestRender(可选属性,不存在则跳过)
79
+ (tui as unknown as TuiInternals).requestRender?.();
80
+ }
81
+
82
+ /** 标记行(组件首行,可能是空白内边距)起的第一行非空文字,已剥 ANSI/标记。 */
83
+ function firstTextFromRow(lines: readonly string[], row: number): string {
84
+ for (let r = row; r < lines.length; r++) {
85
+ const text = stripLineAnsi(lines[r] ?? "").trim();
86
+ if (text) return text;
87
+ }
88
+ return "";
89
+ }
90
+
91
+ /**
92
+ * 滚动到标记序列中第 ordinal 个标记行。返回是否成功。
93
+ * expectedFirstLine:目标提问的首行摘要。标记行的实际文字与它不符,说明标记序号已错位
94
+ * (pi 改了标记规则),此时不滚动、返回 false,让调用方退回文本匹配,避免静默跳错。
95
+ */
96
+ export function jumpToMarker(tui: TUI, ordinal: number, expectedFirstLine?: string): boolean {
97
+ const found = findTranscript(tui);
98
+ if (!found) return false;
99
+
100
+ let seen = -1;
101
+ for (let row = 0; row < found.lines.length; row++) {
102
+ if (!OSC133_A.test(found.lines[row] ?? "")) continue;
103
+ seen++;
104
+ if (seen !== ordinal) continue;
105
+ if (expectedFirstLine !== undefined) {
106
+ // 标记行的文字可能被渲染截断,但不会比原文更长:只接受「实际文字是提问首行的前缀」。
107
+ // 反方向(实际文字更长)会放过指向另一条以相同开头的消息的错位序号。
108
+ const actual = normalizeMatchText(firstTextFromRow(found.lines, row));
109
+ const expected = normalizeMatchText(expectedFirstLine);
110
+ if (!actual || !expected.startsWith(actual)) return false;
111
+ // 实际文字很短时前缀没有区分度("a" 是几乎所有文字的前缀),要求整行相同
112
+ if (actual.length < 8 && actual !== expected) return false;
113
+ }
114
+ scrollToRow(tui, found.scrollView, row);
115
+ return true;
116
+ }
117
+ return false;
118
+ }
119
+
120
+ // ---------------------------------------------------------------------------
121
+ // 跳转兜底:文本匹配(pi 改动标记规则时仍可用)
122
+ // ---------------------------------------------------------------------------
123
+
124
+ interface TextualComponent {
125
+ text?: unknown;
126
+ rebuild?: unknown;
127
+ child?: unknown;
128
+ children?: unknown[];
129
+ render?(width: number): string[];
130
+ }
131
+
132
+ /** UserMessageComponent 的特征:原始 text + rebuild() + render()。 */
133
+ function isUserMessageComponent(c: TextualComponent): boolean {
134
+ return typeof c.text === "string" && typeof c.rebuild === "function" && typeof c.render === "function";
135
+ }
136
+
137
+ interface DocIndex {
138
+ users: TextualComponent[];
139
+ /** 每个 UserMessageComponent 在文档行里的起始偏移(按各组件 render 的行数累加) */
140
+ offsets: Map<unknown, number>;
141
+ }
142
+
143
+ /**
144
+ * 遍历组件树,按渲染顺序累加每个组件的行数,记录每个 UserMessageComponent 的起始行偏移。
145
+ * 定位不依赖字符串匹配:即使 assistant 回复与提问首行相同、或中间有 Spacer/DynamicBorder,偏移也是对的。
146
+ * 前提:容器(有 children 数组)占的行数等于其 children 占行数之和;叶子组件占 render().length 行。
147
+ */
148
+ function indexDocument(root: unknown, width: number): DocIndex {
149
+ const users: TextualComponent[] = [];
150
+ const offsets = new Map<unknown, number>();
151
+ const seen = new Set<unknown>();
152
+ let offset = 0;
153
+ const visit = (node: unknown): void => {
154
+ if (!node || typeof node !== "object" || seen.has(node)) return;
155
+ seen.add(node);
156
+ const c = node as TextualComponent;
157
+ if (isUserMessageComponent(c)) {
158
+ users.push(c);
159
+ offsets.set(node, offset);
160
+ offset += (c.render?.(width) ?? []).length;
161
+ return;
162
+ }
163
+ if (Array.isArray(c.children)) {
164
+ for (const child of c.children) visit(child);
165
+ return;
166
+ }
167
+ offset += (c.render?.(width) ?? []).length;
168
+ };
169
+ visit(root);
170
+ return { users, offsets };
171
+ }
172
+
173
+ /**
174
+ * 文本匹配兜底:在 transcript 组件树里找第 occurrence 个文本相同的 UserMessageComponent,
175
+ * 再按它在文档里的渲染偏移定位行号。
176
+ *
177
+ * 用组件树偏移而非字符串匹配:`found.lines` 含所有组件(含 assistant 回复)的行,
178
+ * 同一首行字符串可能出现在 assistant 回复中;按渲染顺序累加各组件行数得到的偏移不会误配。
179
+ * occurrence = 目标提问之前、文本归一化后相同的提问数量(由调用方按 collectQuestions 计算)。
180
+ */
181
+ export function jumpToQuestionText(tui: TUI, questionText: string, occurrence: number): boolean {
182
+ const found = findTranscript(tui);
183
+ if (!found) return false;
184
+ const scrollView = found.scrollView;
185
+ const doc = scrollView.child;
186
+ if (!doc) return false;
187
+
188
+ const columns = tui.terminal?.columns ?? 80;
189
+ const width = Math.max(1, scrollView.getContentWidth?.(columns) ?? columns);
190
+ const { users, offsets } = indexDocument(doc, width);
191
+
192
+ const targetNorm = normalizeMatchText(questionText);
193
+ const target = users.filter((c) => normalizeMatchText(c.text as string) === targetNorm)[occurrence];
194
+ if (!target) return false;
195
+
196
+ const start = offsets.get(target);
197
+ if (start === undefined) return false;
198
+
199
+ const targetLines = (target.render?.(width) ?? []).map(stripLineAnsi);
200
+ const firstNonEmpty = targetLines.findIndex((l) => l.trim().length > 0);
201
+ if (firstNonEmpty < 0) return false;
202
+
203
+ const row = start + firstNonEmpty;
204
+ if (row >= found.lines.length) return false;
205
+ scrollToRow(tui, scrollView, row);
206
+ return true;
207
+ }
208
+
209
+ // ---------------------------------------------------------------------------
210
+ // 统一入口:标记法优先,失败退回文本匹配
211
+ // ---------------------------------------------------------------------------
212
+
213
+ export interface JumpTarget {
214
+ /** 目标提问在 OSC 133;A 标记序列中的序号;无法推算时为 null(直接走文本匹配) */
215
+ markerOrdinal: number | null;
216
+ /** 完整提问文本 */
217
+ text: string;
218
+ /** 首行摘要,用于校验标记法的落点 */
219
+ summary: string;
220
+ /** 目标之前归一化文本相同的提问数量 */
221
+ occurrence: number;
222
+ }
223
+
224
+ /** 滚动到目标提问。返回是否成功;失败时调用方负责提示用户。 */
225
+ export function jumpToQuestion(tui: TUI, target: JumpTarget): boolean {
226
+ if (target.markerOrdinal !== null && jumpToMarker(tui, target.markerOrdinal, target.summary)) return true;
227
+ // 标记法失效或落点与提问不符(例如 pi 调整了 OSC 133;A 规则)→ 文本匹配兜底
228
+ return jumpToQuestionText(tui, target.text, target.occurrence);
229
+ }