Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(desktop): 聊天区新增提问导航条 (#830)

张怡b61326ce6477
diff --git a/apps/desktop/src/renderer/__tests__/messageNavRailModel.test.ts b/apps/desktop/src/renderer/__tests__/messageNavRailModel.test.ts
new file mode 100644
index 0000000000..880b2485ea
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/messageNavRailModel.test.ts
@@ -0,0 +1,432 @@
+/**
+ * messageNavRailModel 纯逻辑单测:条目派生过滤 / 当前提问判定 / 空间与截断规划。
+ * 全部 node 环境,无 DOM(组件侧几何测量不在此覆盖,见 MessageNavRail.tsx 注释)。
+ */
+import { describe, expect, it } from 'vitest';
+
+import type { ChatMessage } from '@/hooks/useCCAgentChat';
+import {
+ NAV_RAIL_ACTIVE_FUDGE_PX,
+ NAV_RAIL_BACKFILL_MAX_ROUNDS,
+ NAV_RAIL_BACKFILL_TARGET_ENTRIES,
+ NAV_RAIL_EXCERPT_MAX_CHARS,
+ NAV_RAIL_JUMP_TOP_OFFSET_PX,
+ NAV_RAIL_MIN_GUTTER_PX,
+ NAV_RAIL_TICK_MIN_PITCH_PX,
+ NAV_RAIL_TICK_PITCH_PX,
+ deriveNavRailEntries,
+ hasNavRailRoom,
+ normalizeExcerpt,
+ pickActiveNavId,
+ pickVisibleNavRange,
+ planNavRailTicks,
+ promptPreviewLine,
+ shouldBackfillForNavRail,
+} from '@/components/chat/messageNavRailModel';
+import { forwardNavRailWheel } from '@/components/chat/messageNavRailWheel';
+
+function msg(
+ partial: Partial<ChatMessage> & { clientId: string; role: ChatMessage['role'] },
+): ChatMessage {
+ return { content: '', ...partial } as ChatMessage;
+}
+
+describe('deriveNavRailEntries', () => {
+ it('只收真实用户提问,跳过 assistant / tool / 合成行 / 系统卡', () => {
+ const messages = [
+ msg({ clientId: 'u1', role: 'user', content: '第一问' }),
+ msg({ clientId: 'a1', role: 'assistant', content: '回答' }),
+ msg({ clientId: 't1', role: 'tool_use', content: '' }),
+ msg({ clientId: 'u2', role: 'user', content: '第二问', isSyntheticTrigger: true }),
+ msg({ clientId: 'u3', role: 'user', content: '', systemCardType: 'compact' }),
+ msg({ clientId: 'u4', role: 'user', content: '第三问\n补充' }),
+ ];
+ const entries = deriveNavRailEntries(messages);
+ expect(entries.map((e) => e.id)).toEqual(['u1', 'u4']);
+ expect(entries[1].preview).toBe('第三问');
+ });
+
+ it('空输入返回空数组', () => {
+ expect(deriveNavRailEntries([])).toEqual([]);
+ });
+
+ it('运行中插话(delivery=steer)不算新一轮,不产生刻度', () => {
+ const messages = [
+ msg({ clientId: 'u1', role: 'user', content: '第一问' }),
+ msg({ clientId: 's1', role: 'user', content: '插话:别用这个库', delivery: 'steer' }),
+ msg({ clientId: 'a1', role: 'assistant', content: '继续回答第一问' }),
+ ];
+ const entries = deriveNavRailEntries(messages);
+ expect(entries.map((e) => e.id)).toEqual(['u1']);
+ // 回答摘要仍归属真实提问,不被插话截走。
+ expect(entries[0].answerExcerpt).toBe('继续回答第一问');
+ });
+
+ it('无文本也无附件的 user 消息(预览为空)不产生刻度', () => {
+ const messages = [
+ msg({ clientId: 'u1', role: 'user', content: '' }),
+ msg({ clientId: 'u2', role: 'user', content: ' \n ' }),
+ msg({ clientId: 'u3', role: 'user', content: '真提问' }),
+ ];
+ expect(deriveNavRailEntries(messages).map((e) => e.id)).toEqual(['u3']);
+ });
+
+ it('纯附件提问:预览用顶层 images/files 字段的名字,不丢刻度', () => {
+ const messages = [
+ msg({
+ clientId: 'u1',
+ role: 'user',
+ content: '',
+ files: [{ name: '需求文档.pdf', path: '/tmp/需求文档.pdf' }],
+ }),
+ ];
+ const entries = deriveNavRailEntries(messages);
+ expect(entries).toHaveLength(1);
+ expect(entries[0].preview).toBe('需求文档.pdf');
+ });
+
+ it('纯附件且取不到文件名(粘贴截图):保留刻度,记 attachmentsOnly 数量', () => {
+ const messages = [
+ msg({
+ clientId: 'u1',
+ role: 'user',
+ content: '',
+ images: [{ base64: 'xxxx', mimeType: 'image/png' }],
+ }),
+ ];
+ const entries = deriveNavRailEntries(messages);
+ expect(entries).toHaveLength(1);
+ expect(entries[0].preview).toBe('');
+ expect(entries[0].attachmentsOnly).toBe(1);
+ });
+
+ it('回答摘要取该轮第一条非空 assistant 正文,跳过 thinking / tool 行', () => {
+ const messages = [
+ msg({ clientId: 'u1', role: 'user', content: '第一问' }),
+ msg({ clientId: 'th1', role: 'thinking', content: '推理过程' }),
+ msg({ clientId: 't1', role: 'tool_use', content: '{"cmd":"ls"}' }),
+ msg({ clientId: 'a1', role: 'assistant', content: ' 我先看下\n项目结构 ' }),
+ msg({ clientId: 'a2', role: 'assistant', content: '后续补充,不该覆盖首条' }),
+ msg({ clientId: 'u2', role: 'user', content: '第二问(流式中,尚无回答)' }),
+ ];
+ const entries = deriveNavRailEntries(messages);
+ expect(entries[0].answerExcerpt).toBe('我先看下 项目结构');
+ expect(entries[1].answerExcerpt).toBeUndefined();
+ });
+
+ it('提问之前的 assistant 消息不会挂到任何条目上', () => {
+ const messages = [
+ msg({ clientId: 'a0', role: 'assistant', content: '开场白' }),
+ msg({ clientId: 'u1', role: 'user', content: '第一问' }),
+ ];
+ expect(deriveNavRailEntries(messages)[0].answerExcerpt).toBeUndefined();
+ });
+
+ it('全空白的 assistant 正文不占用摘要名额,等真正非空正文', () => {
+ const messages = [
+ msg({ clientId: 'u1', role: 'user', content: '第一问' }),
+ msg({ clientId: 'a1', role: 'assistant', content: ' \n ' }),
+ msg({ clientId: 'a2', role: 'assistant', content: '真正的回答' }),
+ ];
+ expect(deriveNavRailEntries(messages)[0].answerExcerpt).toBe('真正的回答');
+ });
+
+ it('hook 消息(带 userText):预览取干净原文,不取 content 里的 agent prompt', () => {
+ const messages = [
+ msg({
+ clientId: 'u1',
+ role: 'user',
+ content: '<thread_context>群里的历史消息</thread_context>请根据以上上下文回复用户',
+ hookSource: { im: 'feishu', userText: '帮我看下这个报错' },
+ }),
+ ];
+ const entries = deriveNavRailEntries(messages);
+ expect(entries).toHaveLength(1);
+ expect(entries[0].preview).toBe('帮我看下这个报错');
+ });
+
+ it('hook 消息(过渡期,无 userText):预览剥掉 <thread_context> 块', () => {
+ const messages = [
+ msg({
+ clientId: 'u1',
+ role: 'user',
+ content: '<thread_context>A: 早\nB: 早</thread_context>\n这个 bug 谁修一下',
+ hookSource: { im: 'feishu' },
+ }),
+ ];
+ expect(deriveNavRailEntries(messages)[0].preview).toBe('这个 bug 谁修一下');
+ });
+
+ it('Orca 通信行:预览取封装内的 content,不裸奔 JSON 原文', () => {
+ const messages = [
+ msg({
+ clientId: 'u1',
+ role: 'user',
+ content: JSON.stringify({ orcaSource: 'lead', content: '任务:补齐单测覆盖' }),
+ }),
+ ];
+ expect(deriveNavRailEntries(messages)[0].preview).toBe('任务:补齐单测覆盖');
+ });
+
+ it('正文恰好是 JSON 字面量的普通提问不受 Orca 解包影响', () => {
+ const messages = [
+ msg({ clientId: 'u1', role: 'user', content: '{"cmd":"build"}' }),
+ ];
+ expect(deriveNavRailEntries(messages)[0].preview).toBe('{"cmd":"build"}');
+ });
+
+ it('JSON 数组字面量提问不被二次解析,保留刻度与原文预览', () => {
+ // store 入库已把 content 归一成可见正文;这里再 parseUserContent 会把
+ // 数组当 SDK content blocks 解空、丢刻度(PR #830 review)。
+ const messages = [msg({ clientId: 'u1', role: 'user', content: '[1,2,3]' })];
+ const entries = deriveNavRailEntries(messages);
+ expect(entries).toHaveLength(1);
+ expect(entries[0].preview).toBe('[1,2,3]');
+ });
+
+ it('带 text 字段的 JSON 对象字面量提问显示原文,不被解成内层字段', () => {
+ const content = '{"text":"内层不该被提出来"}';
+ const messages = [msg({ clientId: 'u1', role: 'user', content })];
+ expect(deriveNavRailEntries(messages)[0].preview).toBe(content);
+ });
+
+ it('hook 消息正文中间以 <thread_context> 开头的行不被误剥(^ 只锚串首)', () => {
+ const messages = [
+ msg({
+ clientId: 'u1',
+ role: 'user',
+ content: '看看这段配置\n<thread_context>foo</thread_context>\n有什么问题',
+ hookSource: { im: 'feishu' },
+ }),
+ ];
+ expect(deriveNavRailEntries(messages)[0].preview).toBe('看看这段配置');
+ });
+});
+
+describe('promptPreviewLine', () => {
+ it('composer 引用消息:剥标记行,优先取引用块之外用户自己的话', () => {
+ const content = [
+ '> <!-- cindy-composer-quote -->',
+ '> 被引用的一段回答文字',
+ '',
+ '这个没必要吧,没必要就不要提了',
+ ].join('\n');
+ expect(promptPreviewLine(content)).toBe('这个没必要吧,没必要就不要提了');
+ });
+
+ it('全引用消息(没有自己的话):退回引用文字本身,去掉引用前缀', () => {
+ const content = ['> <!-- cindy-composer-quote -->', '> 被引用的一段回答文字'].join('\n');
+ expect(promptPreviewLine(content)).toBe('被引用的一段回答文字');
+ });
+
+ it('普通多行提问:取首个非空行', () => {
+ expect(promptPreviewLine('\n第一行\n第二行')).toBe('第一行');
+ });
+});
+
+describe('normalizeExcerpt', () => {
+ it('压平换行与连续空白成单行', () => {
+ expect(normalizeExcerpt('第一行\n\n 第二行\t结尾 ')).toBe('第一行 第二行 结尾');
+ });
+
+ it('剥常见 Markdown 标记:粗体 / 行内代码 / 标题 / 引用 / 列表符 / 链接', () => {
+ expect(
+ normalizeExcerpt(
+ '## 结论\n**触发条件(现状)**:≥ **4 条**提问\n- 用 `onLoadMore` 补页\n> 引用行\n详见 [设计文档](https://example.com/spec)。',
+ ),
+ ).toBe('结论 触发条件(现状):≥ 4 条提问 用 onLoadMore 补页 引用行 详见 设计文档。');
+ });
+
+ it('行首负号数字不是列表符,不剥', () => {
+ expect(normalizeExcerpt('-5度 是正文')).toBe('-5度 是正文');
+ });
+
+ it('截断到摘要上限', () => {
+ expect(normalizeExcerpt('长'.repeat(500))).toHaveLength(NAV_RAIL_EXCERPT_MAX_CHARS);
+ });
+});
+
+describe('shouldBackfillForNavRail', () => {
+ const base = {
+ entryCount: 2,
+ hasMoreMessages: true,
+ isLoadingMore: false,
+ rounds: 0,
+ };
+
+ it('提问不足且还有历史、不在加载中、预算未用完 → 补页', () => {
+ expect(shouldBackfillForNavRail(base)).toBe(true);
+ });
+
+ it('提问已达标 → 不补', () => {
+ expect(
+ shouldBackfillForNavRail({ ...base, entryCount: NAV_RAIL_BACKFILL_TARGET_ENTRIES }),
+ ).toBe(false);
+ });
+
+ it('历史已翻到头 → 不补', () => {
+ expect(shouldBackfillForNavRail({ ...base, hasMoreMessages: false })).toBe(false);
+ });
+
+ it('正在加载中 → 等这轮落地再说', () => {
+ expect(shouldBackfillForNavRail({ ...base, isLoadingMore: true })).toBe(false);
+ });
+
+ it('轮数预算用完 → 到此为止,剩下的随用户上滚补齐', () => {
+ expect(shouldBackfillForNavRail({ ...base, rounds: NAV_RAIL_BACKFILL_MAX_ROUNDS })).toBe(false);
+ });
+});
+
+describe('跳转落点与当前项阈值的约束关系', () => {
+ it('阈值必须大于落点偏移 — 跳转落定后目标自身即成为当前项', () => {
+ expect(NAV_RAIL_ACTIVE_FUDGE_PX).toBeGreaterThan(NAV_RAIL_JUMP_TOP_OFFSET_PX);
+ });
+});
+
+describe('pickActiveNavId', () => {
+ const ids = ['u1', 'u2', 'u3', 'u4'];
+
+ it('取最后一条顶边已越过阈值线的提问', () => {
+ // 阈值 100:u1/u2 已滚出(顶边在阈值上方),u3/u4 还在下方。
+ const tops = [-500, 40, 300, 900];
+ expect(pickActiveNavId(ids, 100, (i) => tops[i])).toBe('u2');
+ });
+
+ it('未挂载(渲染窗口外)视作已越过阈值', () => {
+ // u3 未挂载 → 它必然在视口上方,当前项就是 u3(u4 还在视口下方)。
+ const tops: Array<number | null> = [null, null, null, 900];
+ expect(pickActiveNavId(ids, 100, (i) => tops[i])).toBe('u3');
+ });
+
+ it('全部都在阈值线之下(视口在对话最顶端)时当前项为第一条', () => {
+ const tops = [150, 400, 800, 1200];
+ expect(pickActiveNavId(ids, 100, (i) => tops[i])).toBe('u1');
+ });
+
+ it('恰好压线(等于阈值)算已越过 — 跳转落定后目标自身即当前项', () => {
+ const tops = [-200, 100, 500, 900];
+ expect(pickActiveNavId(ids, 100, (i) => tops[i])).toBe('u2');
+ });
+
+ it('空列表返回 null', () => {
+ expect(pickActiveNavId([], 100, () => null)).toBeNull();
+ });
+
+ it('二分查找:千级条目单次判定只测 O(log n) 个锚点', () => {
+ // 每次 topAt = querySelector + getBoundingClientRect(强制布局读),
+ // 且在 rAF 里逐帧调用 — 访问次数必须是对数级(PR #830 review)。
+ const n = 1024;
+ const bigIds = Array.from({ length: n }, (_, i) => `u${i}`);
+ let touched = 0;
+ const active = pickActiveNavId(bigIds, 100, (i) => {
+ touched += 1;
+ return i * 100;
+ });
+ expect(active).toBe('u1'); // 顶边 100 恰好压线
+ expect(touched).toBeLessThanOrEqual(Math.ceil(Math.log2(n)) + 2);
+ });
+});
+
+describe('pickVisibleNavRange', () => {
+ const ids = ['u1', 'u2', 'u3', 'u4'];
+ const rangeOf = (tops: Array<number | null>, viewTop: number, viewBottom: number) =>
+ pickVisibleNavRange(ids, viewTop, viewBottom, (i) => tops[i]);
+
+ it('视口横跨两轮:两轮都在范围里', () => {
+ // 轮次区间:u1=[-500,-100) u2=[-100,200) u3=[200,900) u4=[900,∞)
+ expect(rangeOf([-500, -100, 200, 900], 0, 700)).toEqual({ startIndex: 1, endIndex: 2 });
+ });
+
+ it('视口整体落在单轮内部:范围收敛为这一轮', () => {
+ expect(rangeOf([-500, -100, 900, 1500], 0, 700)).toEqual({ startIndex: 1, endIndex: 1 });
+ });
+
+ it('贴底阅读最后一轮:范围 = 最后一条', () => {
+ expect(rangeOf([-900, -600, -300, -50], 0, 700)).toEqual({ startIndex: 3, endIndex: 3 });
+ });
+
+ it('未挂载(渲染窗口外)的轮次内容在视口上方,其自身可跨进视口', () => {
+ // u1/u2 未挂载;u3 顶边 400 → u2 的轮次 [-∞,400) 与视口相交。
+ expect(rangeOf([null, null, 400, 900], 0, 700)).toEqual({ startIndex: 1, endIndex: 2 });
+ });
+
+ it('视口在第一条提问之前:返回 null(还没有任何轮次开始)', () => {
+ expect(rangeOf([500, 900, 1300, 1700], 0, 400)).toBeNull();
+ });
+
+ it('回归:视口顶只剩上一轮的空白余量(调用方已按容差抬高顶边)→ 上一轮不亮', () => {
+ // 实拍缺陷(2026-07-28):当前轮顶边在视口顶下方 ~30px,那 30px 全是
+ // 消息间距/落点偏移的空白,上一轮却被点亮。调用方把顶边抬高
+ // NAV_RAIL_ACTIVE_FUDGE_PX(40) 后,30 < 40 → 上一轮出局。
+ const tops = [-800, -300, 30, 900];
+ expect(rangeOf(tops, 0 + NAV_RAIL_ACTIVE_FUDGE_PX, 700)).toEqual({
+ startIndex: 2,
+ endIndex: 2,
+ });
+ // 反例:当前轮顶边压过阈值线(60 > 40),上一轮的正文确实还在屏上 → 亮。
+ const tops2 = [-800, -300, 60, 900];
+ expect(rangeOf(tops2, 0 + NAV_RAIL_ACTIVE_FUDGE_PX, 700)).toEqual({
+ startIndex: 1,
+ endIndex: 2,
+ });
+ });
+
+ it('空列表返回 null', () => {
+ expect(pickVisibleNavRange([], 0, 700, () => null)).toBeNull();
+ });
+});
+
+describe('planNavRailTicks', () => {
+ it('空间充裕:标准纵距,全量展示', () => {
+ const plan = planNavRailTicks(10, 10 * NAV_RAIL_TICK_PITCH_PX);
+ expect(plan).toEqual({ startIndex: 0, pitchPx: NAV_RAIL_TICK_PITCH_PX, hiddenCount: 0 });
+ });
+
+ it('略挤:压缩纵距但不截断', () => {
+ const plan = planNavRailTicks(20, 20 * 7);
+ expect(plan.startIndex).toBe(0);
+ expect(plan.hiddenCount).toBe(0);
+ expect(plan.pitchPx).toBe(7);
+ expect(plan.pitchPx).toBeGreaterThanOrEqual(NAV_RAIL_TICK_MIN_PITCH_PX);
+ });
+
+ it('最小纵距也放不下:截掉最早的一段,预留占位刻度', () => {
+ const availableHeight = 100; // 最小纵距 5px → 20 格,留 1 格占位 → 展示 19 条
+ const plan = planNavRailTicks(50, availableHeight);
+ expect(plan.pitchPx).toBe(NAV_RAIL_TICK_MIN_PITCH_PX);
+ expect(plan.hiddenCount).toBe(50 - 19);
+ expect(plan.startIndex).toBe(plan.hiddenCount);
+ // 展示条数 + 占位 1 格不超过可用空间
+ expect((50 - plan.startIndex + 1) * plan.pitchPx).toBeLessThanOrEqual(availableHeight);
+ });
+
+ it('零条目 / 零空间不炸', () => {
+ expect(planNavRailTicks(0, 500).hiddenCount).toBe(0);
+ expect(planNavRailTicks(10, 0).hiddenCount).toBe(0);
+ });
+});
+
+describe('hasNavRailRoom', () => {
+ it('内容列两侧留白足够才有空间', () => {
+ // 容器 880 + 两侧各 44 = 968 恰好够
+ expect(hasNavRailRoom(880 + NAV_RAIL_MIN_GUTTER_PX * 2, 880)).toBe(true);
+ expect(hasNavRailRoom(880 + NAV_RAIL_MIN_GUTTER_PX * 2 - 1, 880)).toBe(false);
+ });
+
+ it('容器比内容列 maxWidth 还窄(嵌入面板)时没有空间', () => {
+ expect(hasNavRailRoom(600, 880)).toBe(false);
+ expect(hasNavRailRoom(0, 880)).toBe(false);
+ });
+});
+
+describe('forwardNavRailWheel', () => {
+ it('把 wheel 增量原样转发给滚动容器(横竖两轴)', () => {
+ const calls: ScrollToOptions[] = [];
+ forwardNavRailWheel({ scrollBy: (options) => calls.push(options) }, { deltaX: 3, deltaY: -120 });
+ expect(calls).toEqual([{ left: 3, top: -120 }]);
+ });
+
+ it('滚动容器缺席(卸载竞态)时静默不抛', () => {
+ expect(() => forwardNavRailWheel(null, { deltaX: 0, deltaY: 10 })).not.toThrow();
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/prevMessageJumpChip.test.ts b/apps/desktop/src/renderer/__tests__/prevMessageJumpChip.test.ts
index e1d463670c..e5b1877cc7 100644
--- a/apps/desktop/src/renderer/__tests__/prevMessageJumpChip.test.ts
+++ b/apps/desktop/src/renderer/__tests__/prevMessageJumpChip.test.ts
@@ -10,6 +10,7 @@
import { describe, it, expect } from 'vitest';
import { firstNonEmptyLine } from '../components/chat/PrevMessageJumpChip';
+import { resolveUserDisplayText } from '../components/chat/userMessageDisplayText';
describe('firstNonEmptyLine', () => {
it('returns empty string for empty / whitespace-only input', () => {
@@ -30,3 +31,37 @@ describe('firstNonEmptyLine', () => {
expect(firstNonEmptyLine(longInput)).toBe(longInput);
});
});
+
+// MessageStream 的 previewById 实际链路 = resolveUserDisplayText → firstNonEmptyLine。
+// chip 是导航条缺席/截断时的兜底导航入口,title/aria 与刻度预览同责:hook 消息
+// 的隐藏 prompt/<thread_context>、Orca 行的 JSON 原文不能裸奔(PR #830 review)。
+describe('chip 预览取显示文本(resolveUserDisplayText → firstNonEmptyLine)', () => {
+ it('hook 消息(带 userText):预览取干净原文', () => {
+ const text = resolveUserDisplayText({
+ content: '<thread_context>群里的历史消息</thread_context>请根据以上上下文回复用户',
+ hookSource: { userText: '帮我看下这个报错' },
+ });
+ expect(firstNonEmptyLine(text)).toBe('帮我看下这个报错');
+ });
+
+ it('hook 消息(过渡期,无 userText):剥掉 <thread_context> 块', () => {
+ const text = resolveUserDisplayText({
+ content: '<thread_context>A: 早\nB: 早</thread_context>\n这个 bug 谁修一下',
+ hookSource: {},
+ });
+ expect(firstNonEmptyLine(text)).toBe('这个 bug 谁修一下');
+ });
+
+ it('Orca 通信行:取封装内的 content,不裸奔 JSON', () => {
+ const text = resolveUserDisplayText({
+ content: JSON.stringify({ orcaSource: 'lead', content: '任务:补齐单测覆盖' }),
+ });
+ expect(firstNonEmptyLine(text)).toBe('任务:补齐单测覆盖');
+ });
+
+ it('正文恰好是 JSON 字面量的普通提问原样保留', () => {
+ expect(firstNonEmptyLine(resolveUserDisplayText({ content: '{"cmd":"build"}' }))).toBe(
+ '{"cmd":"build"}',
+ );
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/MessageNavRail.tsx b/apps/desktop/src/renderer/components/chat/MessageNavRail.tsx
new file mode 100644
index 0000000000..01002c5c5d
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/MessageNavRail.tsx
@@ -0,0 +1,500 @@
+/**
+ * MessageNavRail
+ * ---------------------------------------------------------------------------
+ * 聊天区左缘的"提问导航条":每条用户提问一根短刻度,当前正在阅读的提问加深,
+ * hover 显示"提问 + 回答摘要"预览卡,点击跳转到那一轮的顶部。
+ *
+ * 职责定义(设计推导起点):长 agent 对话的意义单元是"轮次"(提问→回答),
+ * 导航条同时承担 ①定位(当前项)②跳转(落点框住整轮)③识别(预览卡)。
+ *
+ * 显隐(活跃深、空闲浅,不完全隐没):
+ * - 前提条件:真实提问 ≥ NAV_RAIL_MIN_ENTRIES 且内容列左侧留白足够
+ * (窄窗口 / 嵌入面板自然隐藏,绝不压在气泡上);
+ * - 满足前提后**常驻但分两档**:滚动、鼠标滑到左缘、悬停刻度时全亮;
+ * 静止阅读 NAV_RAIL_IDLE_HIDE_MS 后**减淡**为浅灰(2026-07-28 验收
+ * 定稿:完全淡出会让人忘记它的存在,减淡保留"地图在这"的心理暗示,
+ * 阅读态噪音仍然很低)。
+ *
+ * 入口去重:导航条**完整覆盖导航**(出场且未截断)时,父级抑制右上角
+ * "跳到上一条提问"chip —— 同一个导航任务只保留一套入口(经
+ * onNavCoverageChange 上报)。刻度被截断的超长会话里 chip 回归,截断区
+ * 仍有导航可用(PR #830 review)。
+ *
+ * 几何职责分工:
+ * - 本组件只做 DOM 测量(scroll + ResizeObserver,rAF 节流,与
+ * usePrevUserMessageInView 同款套路)并渲染;
+ * - 判定与规划是纯函数,在 messageNavRailModel.ts,node 环境直接单测;
+ * - 点击后的跳转(含渲染窗口外目标的扩窗、落点计算)由 MessageStream 的
+ * onJump 承接,那边持有 firstVisibleItemKey / chip-jump 抑制协议等状态。
+ *
+ * pending 态:点击后目标立即显示为当前项(乐观),平滑滚动落定(几何判定
+ * 追上)或用户产生主动滚动意图(wheel / touch / 方向键)时回归几何真值;
+ * 3s 安全兜底防"点完不动"卡住乐观态,与 CHIP_JUMP_SAFETY_MS 同源经验值。
+ */
+
+import { useCallback, useEffect, useRef, useState, type WheelEvent as ReactWheelEvent } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { cn } from '@/lib/utils';
+import { Tip } from '@/components/ui/tooltip';
+
+import { useNavigationKeyListener } from './useNavigationKeyListener';
+import {
+ NAV_RAIL_ACTIVE_FUDGE_PX,
+ NAV_RAIL_MIN_AVAIL_HEIGHT_PX,
+ NAV_RAIL_MIN_ENTRIES,
+ NAV_RAIL_RANGE_BOTTOM_EDGE_PX,
+ hasNavRailRoom,
+ pickActiveNavId,
+ pickVisibleNavRange,
+ planNavRailTicks,
+ type NavRailEntry,
+} from './messageNavRailModel';
+import { forwardNavRailWheel } from './messageNavRailWheel';
+
+// 乐观 pending 态的安全兜底时长,对齐 MessageStream 的 CHIP_JUMP_SAFETY_MS。
+const PENDING_SAFETY_MS = 3000;
+// 静止这么久后减淡(不隐没) — 节奏对齐全局滚动条自动隐藏
+// (lib/scrollbarAutoHide.ts 的 .is-scrolling,2s)。
+const NAV_RAIL_IDLE_HIDE_MS = 2000;
+// 空闲档的整条不透明度。全亮 100% / 空闲减淡到这个值,保留"地图在这"的
+// 存在感又不抢阅读注意力(2026-07-28 实机验收定的档位)。
+const NAV_RAIL_IDLE_OPACITY_CLASS = 'opacity-40';
+// 鼠标滑进滚动容器左缘这么宽的区域时唤醒导航条(mousemove 探测,不放
+// pointer-events 层,避免挡住从留白处起手的划选)。
+const WAKE_GUTTER_PX = 48;
+// 刻度带的上下保留:顶部对齐内容区 pt-7;底部在输入 overlay 之上再让 16px。
+const RAIL_TOP_PX = 28;
+const RAIL_BOTTOM_EXTRA_PX = 16;
+
+export interface MessageNavRailProps {
+ /** 已加载的全部真实提问(deriveNavRailEntries 产物,时间正序)。 */
+ entries: NavRailEntry[];
+ /** MessageStream 的滚动容器 ref,测量与锚点查询都以它为根。 */
+ scrollRef: { readonly current: HTMLDivElement | null };
+ /** 内容列 maxWidth(与 MessageStream contentRef 的 maxWidth 同值)。 */
+ contentMaxWidth: number;
+ /** 底部输入 overlay 高度(resolvedBottomPadding),刻度带避开这段。 */
+ bottomOffset: number;
+ /** 点击刻度 → 跳到该提问。目标可能在渲染窗口外,由父级扩窗后滚动。 */
+ onJump: (clientId: string) => void;
+ /**
+ * "导航条完整覆盖导航"变化上报(出场资格 && 刻度未截断)。父级用它做
+ * 入口去重:覆盖时抑制"跳到上一条提问"chip;导航条缺席或截断了更早
+ * 刻度时 chip 回归。与淡入淡出无关 —— chip 只在滚动时出现,而滚动一定
+ * 会唤醒导航条,按覆盖态抑制即可,信号稳定不闪烁。
+ */
+ onNavCoverageChange?: (covers: boolean) => void;
+ /** 切会话重置几何与 pending 态(与 usePrevUserMessageInView 同款)。 */
+ resetKey?: string;
+}
+
+export function MessageNavRail({
+ entries,
+ scrollRef,
+ contentMaxWidth,
+ bottomOffset,
+ onJump,
+ onNavCoverageChange,
+ resetKey,
+}: MessageNavRailProps) {
+ const { t } = useTranslation();
+
+ const [activeId, setActiveId] = useState<string | null>(null);
+ // 视口内可见轮次的范围(整段提亮,与"当前项加长"互补)。存 id 而非下标:
+ // 测量与渲染之间 entries 可能已更新,按 id 回查最稳。
+ const [visibleRange, setVisibleRange] = useState<{ startId: string; endId: string } | null>(null);
+ const [pendingId, setPendingId] = useState<string | null>(null);
+ const [hasRoom, setHasRoom] = useState(false);
+ const [availHeight, setAvailHeight] = useState(0);
+ // 淡入淡出:挂载即亮(给切进会话的用户一个初始定位),此后随活动唤醒。
+ const [awake, setAwake] = useState(true);
+
+ const rafRef = useRef<number | null>(null);
+ const pendingTimerRef = useRef<number | null>(null);
+ const idleTimerRef = useRef<number | null>(null);
+ const hoveringRef = useRef(false);
+ // 容器左缘缓存,给高频 mousemove 的左缘唤醒判定用,免得每次事件都
+ // getBoundingClientRect 强制布局读;measure(scroll/resize 都会触发)时刷新。
+ const containerLeftRef = useRef(0);
+ // 测量回调经 rAF 异步触发,entries 派生的 id 列表 / 布局参数用 ref 透传
+ // 拿最新值,避免把大数组挂进依赖链让监听器反复重挂。id 列表按 entries
+ // 引用缓存,长会话滚动的高频测量不逐帧重新分配数组(Copilot review);
+ // 初值空占位,首次渲染即被下面的引用比较填充,不在每次 render 白算一遍。
+ const measureIdsRef = useRef<{ source: readonly NavRailEntry[] | null; ids: string[] }>({
+ source: null,
+ ids: [],
+ });
+ if (measureIdsRef.current.source !== entries) {
+ measureIdsRef.current = { source: entries, ids: entries.map((e) => e.id) };
+ }
+ const contentMaxWidthRef = useRef(contentMaxWidth);
+ contentMaxWidthRef.current = contentMaxWidth;
+ const bottomOffsetRef = useRef(bottomOffset);
+ bottomOffsetRef.current = bottomOffset;
+
+ // 切会话全部归零,防旧目标 / 旧乐观态残留;重新亮一次做初始定位。
+ useEffect(() => {
+ setActiveId(null);
+ setVisibleRange(null);
+ setPendingId(null);
+ setAwake(true);
+ }, [resetKey]);
+
+ // 唤醒 + 重排空闲淡出计时。悬停刻度期间不淡出(计时器到点重排)。
+ const wake = useCallback(() => {
+ setAwake((cur) => (cur ? cur : true));
+ if (idleTimerRef.current !== null) {
+ window.clearTimeout(idleTimerRef.current);
+ }
+ const scheduleHide = () => {
+ idleTimerRef.current = window.setTimeout(() => {
+ idleTimerRef.current = null;
+ if (hoveringRef.current) {
+ scheduleHide();
+ return;
+ }
+ setAwake(false);
+ }, NAV_RAIL_IDLE_HIDE_MS);
+ };
+ scheduleHide();
+ }, []);
+
+ const measure = useCallback(() => {
+ rafRef.current = null;
+ const root = scrollRef.current;
+ if (!root) return;
+ const containerRect = root.getBoundingClientRect();
+ containerLeftRef.current = containerRect.left;
+ const roomOk = hasNavRailRoom(containerRect.width, contentMaxWidthRef.current);
+ setHasRoom(roomOk);
+ const avail = Math.max(
+ 0,
+ containerRect.height - bottomOffsetRef.current - RAIL_TOP_PX - RAIL_BOTTOM_EXTRA_PX,
+ );
+ setAvailHeight(avail);
+ const ids = measureIdsRef.current.ids;
+ // 组件常驻挂载,不出场(条数不足 / 窄窗 / 矮视口)时跳过逐条锚点测量,
+ // 短对话滚动不背 querySelector + 布局读的开销;room/avail 已更新,条件
+ // 翻转时下一次测量自然恢复(Copilot review)。
+ if (ids.length < NAV_RAIL_MIN_ENTRIES || !roomOk || avail < NAV_RAIL_MIN_AVAIL_HEIGHT_PX) {
+ setActiveId((cur) => (cur === null ? cur : null));
+ setVisibleRange((cur) => (cur === null ? cur : null));
+ return;
+ }
+ // 同一帧内 topAt 会被 active / range 两个判定反复调,缓存 DOM 测量。
+ const topCache = new Map<number, number | null>();
+ const topAt = (i: number): number | null => {
+ const cached = topCache.get(i);
+ if (cached !== undefined) return cached;
+ const el = root.querySelector(
+ `[data-message-client-id="${CSS.escape(ids[i])}"]`,
+ ) as HTMLElement | null;
+ const top = el ? el.getBoundingClientRect().top : null;
+ topCache.set(i, top);
+ return top;
+ };
+ const next = pickActiveNavId(ids, containerRect.top + NAV_RAIL_ACTIVE_FUDGE_PX, topAt);
+ setActiveId((cur) => (cur === next ? cur : next));
+ // 有效视口 = 扣除容差后的边界:顶部与当前项共用同一条阈值线(空白余量
+ // 不算"看见了上一轮"),底部留 8px 防露头即亮。语义见 pickVisibleNavRange。
+ const range = pickVisibleNavRange(
+ ids,
+ containerRect.top + NAV_RAIL_ACTIVE_FUDGE_PX,
+ containerRect.bottom - NAV_RAIL_RANGE_BOTTOM_EDGE_PX,
+ topAt,
+ );
+ const nextRange = range ? { startId: ids[range.startIndex], endId: ids[range.endIndex] } : null;
+ setVisibleRange((cur) =>
+ cur?.startId === nextRange?.startId && cur?.endId === nextRange?.endId ? cur : nextRange,
+ );
+ }, [scrollRef]);
+
+ const scheduleMeasure = useCallback(() => {
+ if (rafRef.current === null) {
+ rafRef.current = requestAnimationFrame(measure);
+ }
+ }, [measure]);
+
+ // 主动滚动意图(wheel / touch / 方向键)→ 放弃乐观 pending,回归几何真值。
+ const dropPending = useCallback(() => {
+ setPendingId((cur) => (cur === null ? cur : null));
+ }, []);
+
+ useEffect(() => {
+ const root = scrollRef.current;
+ if (!root) return;
+ const onScroll = () => {
+ wake();
+ scheduleMeasure();
+ };
+ // 左缘唤醒走 mousemove 探测而不是铺一层 pointer-events 热区:
+ // 留白区常被用来起手划选文本,热区会吃掉 mousedown。左缘坐标用
+ // measure 缓存的值(窗口纯平移导致的极小误差可接受),不在高频事件里
+ // 强制布局读。
+ const onMouseMove = (e: MouseEvent) => {
+ if (e.clientX - containerLeftRef.current <= WAKE_GUTTER_PX) {
+ wake();
+ }
+ };
+ root.addEventListener('scroll', onScroll, { passive: true });
+ root.addEventListener('mousemove', onMouseMove, { passive: true });
+ root.addEventListener('wheel', dropPending, { passive: true });
+ root.addEventListener('touchstart', dropPending, { passive: true });
+ const ro = new ResizeObserver(() => scheduleMeasure());
+ ro.observe(root);
+ // 初次同步:挂载后未滚动也能算出当前项与可用空间。
+ scheduleMeasure();
+ return () => {
+ root.removeEventListener('scroll', onScroll);
+ root.removeEventListener('mousemove', onMouseMove);
+ root.removeEventListener('wheel', dropPending);
+ root.removeEventListener('touchstart', dropPending);
+ ro.disconnect();
+ if (rafRef.current !== null) {
+ cancelAnimationFrame(rafRef.current);
+ rafRef.current = null;
+ }
+ };
+ }, [scrollRef, scheduleMeasure, dropPending, wake]);
+
+ useNavigationKeyListener(dropPending);
+
+ // 条目变化(新发消息 / load-more prepend)与喂进测量的布局 props 变化都要
+ // 重算。bottomOffset / contentMaxWidth 只经 ref 透传给 measure,不列进这里
+ // 的话 composer 撑高(多行输入 / 加附件)既不触发容器 resize 也不滚动,
+ // availHeight 与纵向出场门槛会停在旧值直到下次滚动(PR #830 review)。
+ useEffect(() => {
+ scheduleMeasure();
+ }, [entries, bottomOffset, contentMaxWidth, scheduleMeasure]);
+
+ // 挂载亮相的那次也要按空闲节奏淡出。
+ useEffect(() => {
+ wake();
+ }, [wake, resetKey]);
+
+ // 平滑滚动落定,几何判定追上乐观目标 → 乐观态使命完成,交还给几何。
+ useEffect(() => {
+ if (pendingId !== null && pendingId === activeId) {
+ setPendingId(null);
+ }
+ }, [pendingId, activeId]);
+
+ // 出场资格:条数、横向留白、纵向空间三道门槛。纵向门槛防极矮视口 /
+ // 输入 overlay 占满高度时刻度溢出压到输入区(PR #830 review)。
+ const eligible =
+ entries.length >= NAV_RAIL_MIN_ENTRIES &&
+ hasRoom &&
+ availHeight >= NAV_RAIL_MIN_AVAIL_HEIGHT_PX;
+ const plan = planNavRailTicks(entries.length, availHeight);
+ // 覆盖态上报(入口去重用);卸载时收回。截断时不算覆盖 —— 被截掉的
+ // 早期区域没有刻度,chip 必须回归兜底。
+ const railCoversNav = eligible && plan.hiddenCount === 0;
+ useEffect(() => {
+ onNavCoverageChange?.(railCoversNav);
+ }, [railCoversNav, onNavCoverageChange]);
+ useEffect(() => {
+ return () => {
+ onNavCoverageChange?.(false);
+ };
+ }, [onNavCoverageChange]);
+
+ useEffect(() => {
+ return () => {
+ if (pendingTimerRef.current !== null) {
+ window.clearTimeout(pendingTimerRef.current);
+ }
+ if (idleTimerRef.current !== null) {
+ window.clearTimeout(idleTimerRef.current);
+ }
+ };
+ }, []);
+
+ const handleTickClick = useCallback(
+ (clientId: string) => {
+ setPendingId(clientId);
+ if (pendingTimerRef.current !== null) {
+ window.clearTimeout(pendingTimerRef.current);
+ }
+ pendingTimerRef.current = window.setTimeout(() => {
+ pendingTimerRef.current = null;
+ setPendingId(null);
+ }, PENDING_SAFETY_MS);
+ onJump(clientId);
+ },
+ [onJump],
+ );
+
+ const handleTickMouseEnter = useCallback(() => {
+ hoveringRef.current = true;
+ wake();
+ }, [wake]);
+ const handleTickMouseLeave = useCallback(() => {
+ hoveringRef.current = false;
+ }, []);
+
+ // 悬停刻度带时滚轮不能失灵:导航条是滚动容器的兄弟 overlay,刻度按钮
+ // pointer-events-auto 会成为 wheel 目标、冒泡不经过滚动容器,浏览器不会
+ // 替我们滚聊天区(PR #830 review)。补两件事,缺一不可:
+ // 1. 先把 wheel **重派**给滚动容器 —— root 上挂着既有的 wheel 意图监听
+ // (本组件的 dropPending;MessageStream 的贴底跟随解锚 / 顶部意图
+ // 补页 / chip 抑制解除)。只补位移不补意图,贴底流式时在刻度带上滚
+ // 会被 pin-to-bottom 拽回、到顶后拉不出更早历史(对抗审查 P1)。
+ // 合成事件 untrusted、不产生默认滚动,与下一步不会双滚;先意图后
+ // 位移,对齐原生"监听先于默认滚动"的时序。
+ // 2. 再把增量转发成真实位移(见 messageNavRailWheel.ts)。产生的
+ // scroll 事件经 root 的 onScroll 走 wake + scheduleMeasure。
+ const handleRailWheel = useCallback(
+ (e: ReactWheelEvent<HTMLElement>) => {
+ const root = scrollRef.current;
+ if (!root) return;
+ root.dispatchEvent(new WheelEvent('wheel', { deltaX: e.deltaX, deltaY: e.deltaY }));
+ forwardNavRailWheel(root, e);
+ },
+ [scrollRef],
+ );
+
+ if (!eligible) return null;
+
+ const shown = entries.slice(plan.startIndex);
+ const displayActiveId = pendingId ?? activeId;
+ // 可见范围 id → 下标(渲染时按 id 回查,测量与渲染间 entries 变更也不会
+ // 错位)。单次遍历同时定位两端,滚动高频重渲下不扫两遍数组。
+ let rangeStartIdx = -1;
+ let rangeEndIdx = -1;
+ if (visibleRange) {
+ for (let i = 0; i < entries.length; i++) {
+ if (entries[i].id === visibleRange.startId) rangeStartIdx = i;
+ if (entries[i].id === visibleRange.endId) {
+ rangeEndIdx = i;
+ if (rangeStartIdx >= 0) break;
+ }
+ }
+ }
+ // 空闲档只是减淡、仍然可见可点,指针事件常开(悬停刻度本身就会唤醒全亮)。
+ const tickEvents = 'pointer-events-auto';
+
+ return (
+ <nav
+ aria-label={t('chat.messageNavRail.aria')}
+ // 容器不吃事件,只有刻度自身 pointer-events-auto(空闲减淡时也可点,
+ // 见 tickEvents 注释),不挡左缘留白里的文字选择;justify-center 让
+ // 刻度组在(避开输入 overlay 的)带内垂直居中。
+ className={cn(
+ 'pointer-events-none absolute inset-y-0 left-2 z-30 flex w-6 flex-col items-stretch justify-center',
+ 'transition-opacity duration-200 ease-out',
+ awake ? 'opacity-100' : NAV_RAIL_IDLE_OPACITY_CLASS,
+ )}
+ style={{ paddingTop: RAIL_TOP_PX, paddingBottom: bottomOffset + RAIL_BOTTOM_EXTRA_PX }}
+ // wheel 事件从 pointer-events-auto 的刻度冒泡到这里统一转发,
+ // "更早还有 N 条"占位刻度一并覆盖。
+ onWheel={handleRailWheel}
+ >
+ {plan.hiddenCount > 0 ? (
+ <Tip
+ text={t('chat.messageNavRail.hiddenEarlier', { count: plan.hiddenCount })}
+ side="right"
+ delay={150}
+ >
+ <div
+ className={cn('flex items-center justify-center', tickEvents)}
+ style={{ height: plan.pitchPx }}
+ onMouseEnter={handleTickMouseEnter}
+ onMouseLeave={handleTickMouseLeave}
+ >
+ <span
+ aria-hidden="true"
+ className="text-[9px] leading-none text-[var(--text-tertiary)]"
+ >
+ ⋯
+ </span>
+ </div>
+ </Tip>
+ ) : null}
+ {shown.map((entry, i) => {
+ // 纯附件且无文件名的提问用 i18n 计数文案兜底(模型层不碰 i18n)。
+ const preview =
+ entry.preview ||
+ (entry.attachmentsOnly
+ ? t('chat.messageNavRail.attachmentOnly', { count: entry.attachmentsOnly })
+ : '');
+ const isActive = entry.id === displayActiveId;
+ const fullIdx = plan.startIndex + i;
+ // 该轮次的内容当前正显示在视口里 → 提亮(Codex 同款"屏上内容高亮");
+ // 当前项在提亮之上再加长,两个信号分工:范围 = 在看什么,长刻度 = 读到哪。
+ const inView = rangeStartIdx >= 0 && fullIdx >= rangeStartIdx && fullIdx <= rangeEndIdx;
+ return (
+ <Tip
+ key={entry.id}
+ // 预览卡 = 提问(加粗一行)+ 回答摘要(灰字,至多 3 行)。
+ // 摘要是识别的主载体:大量提问是"继续 / 重来"式短指令,只靠
+ // 提问认不出是哪一轮。回答未产生时只显示提问行。
+ text={
+ preview ? (
+ <span className="flex max-w-[344px] flex-col gap-1">
+ <span className="truncate text-13 font-medium">{preview}</span>
+ {entry.answerExcerpt ? (
+ // 摘要 = 主文字色 × 50% 透明度,不引新 token。数值由多轮
+ // 实机验收夹逼、最终用户直接指定(2026-07-28)。注意半透明
+ // 文字经抗锯齿合成会比同亮度实心灰**显得更亮**,别拿色值
+ // 计算器推这个数,调整必须实机看效果。
+ <span className="line-clamp-3 whitespace-normal break-normal text-13 leading-relaxed opacity-50">
+ {entry.answerExcerpt}
+ </span>
+ ) : null}
+ </span>
+ ) : null
+ }
+ side="right"
+ delay={150}
+ // 面色刻意不用全局 tooltip token(亮暗两模式都是近黑,那是给
+ // "一句话标签"定的惯例):本卡是**内容预览**,语义对应 popover
+ // 内容面 —— 白底深字 / 暗色深面,多行正文可读性优先。旁边的
+ // "更早还有 N 条"是标签,继续用默认 tooltip 面色,两类不混。
+ // 覆盖类刻意与 TooltipContent 的原类同形式(任意值 bg-[...] /
+ // text-[...]),确保 tailwind-merge 归入同一冲突组、后写的必胜,
+ // 不赌歧义值的分组启发式。
+ // 阴影不覆盖:继承 TooltipContent 基座的浮层阴影决策,本卡不引入
+ // 新的深度样式(PR #830 review)。
+ contentClassName={cn(
+ 'max-w-[380px] break-normal px-3 py-2',
+ 'border-[var(--border-default)] bg-[hsl(var(--popover))] text-[hsl(var(--popover-foreground))]',
+ 'dark:border-[var(--border-default)]',
+ )}
+ >
+ <button
+ type="button"
+ aria-label={t('chat.messageNavRail.jumpAria', {
+ index: plan.startIndex + i + 1,
+ preview,
+ })}
+ aria-current={isActive ? 'true' : undefined}
+ onClick={() => handleTickClick(entry.id)}
+ onMouseEnter={handleTickMouseEnter}
+ onMouseLeave={handleTickMouseLeave}
+ // 命中区吃满整格纵距,刻度线本体只有 2px 高。焦点环用全局
+ // --focus-ring token(AgentTaskCard 同款),键盘 Tab 可见
+ // (PR #830 review:纯 outline-none 会让键盘用户丢焦点)。
+ className={cn(
+ 'group flex w-full items-center rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]',
+ tickEvents,
+ )}
+ style={{ height: plan.pitchPx }}
+ >
+ <span
+ className={cn(
+ 'h-[2px] rounded-full transition-all duration-200 ease-out',
+ isActive
+ ? 'w-4 bg-[var(--text-primary)]'
+ : inView
+ ? 'w-3 bg-[var(--text-primary)] group-hover:w-3.5'
+ : 'w-3 bg-[var(--border-default)] group-hover:w-3.5 group-hover:bg-[var(--text-secondary)]',
+ )}
+ />
+ </button>
+ </Tip>
+ );
+ })}
+ </nav>
+ );
+}
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index 2de837ecb1..872802c433 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -103,7 +103,6 @@ export const RENDER_WINDOW_FIRST_PAINT_ITEMS = 30;
const RENDER_WINDOW_GROWTH_ITEMS = 80;
const RENDER_WINDOW_BOUNDARY_LOOKBACK_ITEMS = 24;
-
function isEditableKeyboardTarget(target: EventTarget | null): boolean {
if (!(target instanceof HTMLElement)) return false;
const tagName = target.tagName;
@@ -184,6 +183,13 @@ import { PrevMessageJumpChip, firstNonEmptyLine } from './PrevMessageJumpChip';
import { useTopRightChipSlot } from './TopRightChipStack';
import { usePrevUserMessageInView } from './usePrevUserMessageInView';
import { JumpToBottomChip } from './JumpToBottomChip';
+import { MessageNavRail } from './MessageNavRail';
+import {
+ NAV_RAIL_JUMP_TOP_OFFSET_PX,
+ deriveNavRailEntries,
+ shouldBackfillForNavRail,
+} from './messageNavRailModel';
+import { resolveUserDisplayText } from './userMessageDisplayText';
import { detectScrollAnchoringApplied } from './scrollAnchoringDetect';
import {
decideAutoFillAction,
@@ -629,12 +635,14 @@ export function shouldBlockAssistantFork(
* 只回答"是不是本 turn 最后一条正文"。export 仅供单测使用。
*/
function isCompletedAssistantMessage(message: ChatMessage): boolean {
- return message.turnCompleted === true ||
+ return (
+ message.turnCompleted === true ||
(message.turnMoney?.amount ?? 0) > 0 ||
(typeof message.turnCostUsd === 'number' && message.turnCostUsd > 0) ||
// turnUsageDetails 也只在 turn 结束时 patch(算不出报价的轮次只落它),
// 与费用字段一样是等价的收尾信号 —— 少这一条,无金额轮就挂不出 action bar。
- message.turnUsageDetails !== undefined;
+ message.turnUsageDetails !== undefined
+ );
}
export function collectTurnFinalAssistantClientIds(messages: readonly ChatMessage[]): Set<string> {
@@ -1079,7 +1087,10 @@ export function buildRenderItems(
result = messages[j].content;
}
const adjacentTs = Date.parse(messages[j].createdAt ?? '');
- if (Number.isFinite(adjacentTs) && (resultTsMs === undefined || adjacentTs > resultTsMs)) {
+ if (
+ Number.isFinite(adjacentTs) &&
+ (resultTsMs === undefined || adjacentTs > resultTsMs)
+ ) {
resultTsMs = adjacentTs;
}
j++;
@@ -2165,7 +2176,11 @@ export function groupWorkRuns(items: RenderItem[], isSessionStreaming: boolean):
continue;
}
const itemStartMs = renderItemStartMs(it);
- if (prevEndMs !== null && itemStartMs !== null && itemStartMs - prevEndMs > HISTORY_GAP_SPLIT_MS) {
+ if (
+ prevEndMs !== null &&
+ itemStartMs !== null &&
+ itemStartMs - prevEndMs > HISTORY_GAP_SPLIT_MS
+ ) {
flushTurn(false);
// 空洞切开的新段没有已知的 turn 开场边界:那条 user 行在空洞的**另一侧**(或压根没加载)。
// 继续拿它当起点会让新段的时长横跨整个空洞 —— 正是本 PR 要修的那种谎报(实测 47 小时)。
@@ -3366,6 +3381,9 @@ export function MessageStream({
// scrollIntoView 直接可用,无需扩窗。user 消息总是单独 message item(不进
// segment / 不被丢弃),所以这里只 unwrap type==='message' && role==='user'。
// previewById 同源,截断/去噪都在 PrevMessageJumpChip 的 truncatePreview 里做。
+ // 预览存显示文本而非原始 content:chip 是导航条缺席/截断时的兜底入口,其
+ // title/aria 与刻度预览承担同一职责,hook 消息的隐藏 prompt/<thread_context>
+ // 与 Orca 行的 JSON 原文同样不能裸奔(userMessageDisplayText,PR #830 review)。
const { userMessageIds, previewById } = useMemo(() => {
const ids: string[] = [];
const map = new Map<string, string>();
@@ -3375,7 +3393,7 @@ export function MessageStream({
// 静默失效(review P2)。
if (it.message.isSyntheticTrigger) continue;
ids.push(it.message.clientId);
- map.set(it.message.clientId, it.message.content);
+ map.set(it.message.clientId, resolveUserDisplayText(it.message));
}
return { userMessageIds: ids, previewById: map };
}, [visibleRenderItems]);
@@ -3417,6 +3435,119 @@ export function MessageStream({
// chip 在栈里各占一行,自然共存。
const prevUserMsgVisible = prevUserMsgId !== null;
+ // ── message-nav-rail ──
+ // 左缘"提问导航条":条目覆盖**全量已加载** messages(不同于 chip 的窗口内
+ // 派生 —— 导航条要给整段历史画刻度)。目标可能在渲染窗口外,跳转走下面的
+ // layout effect:复用 focus-jump 的"先扩窗到目标、下一轮再滚动"两段式,
+ // 以及 chip-jump 的 expandWindow/onLoadMore 抑制协议。
+ const navRailEntries = useMemo(() => deriveNavRailEntries(messages), [messages]);
+
+ // 入口去重:导航条**完整覆盖导航**(出场且刻度未截断)时抑制"跳到上一条
+ // 提问"chip —— 同一个导航任务只保留一套入口。导航条缺席(短对话 / 窄窗 /
+ // 矮视口)或截断了更早刻度的超长会话里 chip 回归兜底(PR #830 review)。
+ const [navRailCoversNav, setNavRailCoversNav] = useState(false);
+
+ // ── nav-rail 空闲补页 ──
+ // 老会话打开时只加载尾部切片,导航条(整段对话的地图)可能凑不齐条目。
+ // 首屏落定后的空闲期沿现有 onLoadMore 通道自动向前补页,直到提问数达标 /
+ // 翻到历史起点 / 轮数预算用完(目标与预算的设计依据见
+ // shouldBackfillForNavRail 一族常量注释)。与"跳转补齐"同属程序化翻页,
+ // prepend 的滚动补偿照走 F-SYNC-2 协议:调用前快照 scrollHeight/scrollTop。
+ // 即使当下窗口太窄导航条没出场,补到的历史对搜索/上滚阅读同样有用,
+ // 且有轮数预算封顶,不做 eligible 门控。
+ // 调度 effect 的依赖含 sessionId(与 MessageNavRail 的 resetKey 同款惯例):
+ // 两个会话的条目数 / hasMore 恰好相同且 onLoadMore 身份未变时,切会话也要
+ // 取消旧会话待发的空闲回调、并按归零后的轮数预算为新会话重新评估
+ // (Copilot review)。
+ const navRailBackfillRoundsRef = useRef(0);
+ useEffect(() => {
+ navRailBackfillRoundsRef.current = 0;
+ }, [sessionId]);
+ useEffect(() => {
+ if (!onLoadMore) return;
+ if (
+ !shouldBackfillForNavRail({
+ entryCount: navRailEntries.length,
+ hasMoreMessages: hasMoreMessages ?? false,
+ isLoadingMore: isLoadingMore ?? false,
+ rounds: navRailBackfillRoundsRef.current,
+ })
+ ) {
+ return;
+ }
+ const run = () => {
+ const el = scrollRef.current;
+ if (!el) return;
+ navRailBackfillRoundsRef.current += 1;
+ prevScrollHeightRef.current = el.scrollHeight;
+ prevScrollTopAtLoadRef.current = el.scrollTop;
+ onLoadMore();
+ };
+ // 空闲期执行,别跟首屏渲染 / 两段式扩窗抢主线程;测试等无 ric 环境退化。
+ if (typeof window.requestIdleCallback === 'function') {
+ const id = window.requestIdleCallback(run, { timeout: 2000 });
+ return () => window.cancelIdleCallback(id);
+ }
+ const id = window.setTimeout(run, 300);
+ return () => window.clearTimeout(id);
+ }, [sessionId, navRailEntries.length, hasMoreMessages, isLoadingMore, onLoadMore]);
+
+ const railJumpSeqRef = useRef(0);
+ const [railJumpRequest, setRailJumpRequest] = useState<{ id: string; seq: number } | null>(null);
+ const lastAppliedRailJumpRef = useRef(0);
+ const handleNavRailJump = useCallback((clientId: string) => {
+ railJumpSeqRef.current += 1;
+ setRailJumpRequest({ id: clientId, seq: railJumpSeqRef.current });
+ }, []);
+
+ useLayoutEffect(() => {
+ if (!railJumpRequest) return;
+ if (lastAppliedRailJumpRef.current === railJumpRequest.seq) return;
+ const targetKey = renderItemKeyForClientId(allRenderItems, railJumpRequest.id);
+ if (!targetKey) {
+ // 条目派生自 messages,拿不到 key 只可能是消息刚被删 / clear — 放弃本次。
+ lastAppliedRailJumpRef.current = railJumpRequest.seq;
+ return;
+ }
+ if (!visibleRenderItems.some((item) => item.key === targetKey)) {
+ // 目标在渲染窗口外:先把窗口锚到目标。本 effect 因 visibleRenderItems
+ // 变化重跑,下一轮走下面的滚动分支(focus-jump 同款两段式)。
+ setFirstVisibleItemKey(targetKey);
+ return;
+ }
+ const root = scrollRef.current;
+ if (!root) return;
+ const el = root.querySelector(
+ `[data-message-client-id="${CSS.escape(railJumpRequest.id)}"]`,
+ ) as HTMLElement | null;
+ if (!el) return;
+ lastAppliedRailJumpRef.current = railJumpRequest.seq;
+ // 从贴底态往上跳必须先解除 auto-follow 钉底,否则流式期间 pin effect 会把
+ // 视口拽回底部(focus-jump 同款处理;chip 不需要是因为它只在已上滚时出现)。
+ restoringRef.current = false;
+ isNearBottomRef.current = false;
+ setIsNearBottom(false);
+ // smooth scroll 途经顶部区域时抑制 expandWindow/onLoadMore(chip-jump 协议,
+ // 解抑靠用户 wheel/touch/keydown + 安全兜底 timer)。
+ chipJumpInProgressRef.current = true;
+ if (chipJumpClearTimerRef.current !== null) {
+ window.clearTimeout(chipJumpClearTimerRef.current);
+ }
+ chipJumpClearTimerRef.current = window.setTimeout(() => {
+ chipJumpClearTimerRef.current = null;
+ clearChipJumpSuppression();
+ }, CHIP_JUMP_SAFETY_MS);
+ // 落点手动计算,不走 scrollIntoView:轮次跳转要让视口恰好框住
+ // "提问 → 回答",提问顶边停在容器顶下方 12px;消息锚点通用的
+ // scroll-mt-20(80px)是搜索跳转的上文语境预留,对本任务是漏出
+ // 上一轮尾巴的噪音(设计依据见 NAV_RAIL_JUMP_TOP_OFFSET_PX 注释)。
+ const targetTop =
+ root.scrollTop +
+ (el.getBoundingClientRect().top - root.getBoundingClientRect().top) -
+ NAV_RAIL_JUMP_TOP_OFFSET_PX;
+ root.scrollTo({ top: Math.max(0, targetTop), behavior: 'smooth' });
+ }, [railJumpRequest, allRenderItems, visibleRenderItems, clearChipJumpSuppression]);
+
// 第一条 user 消息没有"上一条 assistant"作为 resumeSessionAt 锚点,
// rewind 必然抛 NO_PRIOR_ASSISTANT。直接在 UI 层把按钮藏掉,避免无效点击。
// 注意:这里要用全量 messages 而不是 visibleRenderItems —— "首条 user" 的语义
@@ -3746,6 +3877,19 @@ export function MessageStream({
bottomOffset={indicatorBottomOffset}
/>
+ {/* message-nav-rail: 左缘提问导航条(每条提问一根刻度,当前项加深,
+ hover 预览,点击跳转)。显隐由组件自判:提问数 ≥4 且内容列左侧留白
+ 足够;窄窗口 / 嵌入面板自然隐藏,绝不压在气泡上。 */}
+ <MessageNavRail
+ entries={navRailEntries}
+ scrollRef={scrollRef}
+ contentMaxWidth={contentWidth ?? 880}
+ bottomOffset={resolvedBottomPadding}
+ onJump={handleNavRailJump}
+ onNavCoverageChange={setNavRailCoversNav}
+ resetKey={sessionId}
+ />
+
{/* prev-user-msg-jump: 右上角"跳到上一条提问"icon 按钮。
通过 createPortal 挂到祖先的 TopRightChipStack 容器里,与 DiffPanelToggle
各占栈中一行;DiffToggle 在 session 载入时就 mount,本 chip 仅在
@@ -3754,6 +3898,8 @@ export function MessageStream({
近底时 hook 自然返回 null → 不挂入 → 不占行。 */}
{chipSlot &&
prevUserMsgVisible &&
+ // 导航条完整覆盖导航时不再挂本 chip(入口去重,见 navRailCoversNav)。
+ !navRailCoversNav &&
createPortal(
<PrevMessageJumpChip preview={prevPreview} onClick={handleJumpToPrevUserMsg} />,
chipSlot,
diff --git a/apps/desktop/src/renderer/components/chat/UserMessage.tsx b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
index 4bc1d28fed..3adc15fbd7 100644
--- a/apps/desktop/src/renderer/components/chat/UserMessage.tsx
+++ b/apps/desktop/src/renderer/components/chat/UserMessage.tsx
@@ -100,6 +100,7 @@ import { AutomationOriginBadge } from './AutomationOriginBadge';
import { UserMessageUrlLink } from './UserMessageUrlLink';
import { InlineReferenceChip } from './InlineReferenceChip';
import { QuoteChip } from './QuoteChip';
+import { parseOrcaCommunicationContent, resolveUserDisplayText } from './userMessageDisplayText';
/**
* image-local-cache: a user-message image can be in two shapes:
@@ -117,11 +118,6 @@ type UserImageItem =
}
| { base64: string; mimeType: string; originalName?: string };
-type OrcaCommunicationContent = {
- orcaSource: 'lead' | 'worker';
- content: string;
-};
-
interface UserMessageProps {
/** F2: session cwd used to resolve relative paths in inline @-chip refs.
* Stable per-session — only changes on session switch. */
@@ -190,22 +186,6 @@ export function shouldBlockUserFork(
return sessionRunning === true && delivery === 'steer';
}
-function parseOrcaCommunicationContent(content: string): OrcaCommunicationContent | null {
- try {
- const parsed = JSON.parse(content) as unknown;
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
- const record = parsed as Record<string, unknown>;
- if (record.orcaSource !== 'lead' && record.orcaSource !== 'worker') return null;
- if (typeof record.content !== 'string') return null;
- return {
- orcaSource: record.orcaSource,
- content: record.content,
- };
- } catch {
- return null;
- }
-}
-
/**
* UserFileChip — `@file` chip in a user message. Left click opens TextLightbox
* via onClick; right click opens the shared file-chip menu (copy / copy path /
@@ -779,18 +759,10 @@ export function UserMessage({
// rendered as a dedicated Chip-Row above the text bubble (per cc-agent-view
// pen DLGJ9 / s2N4G). The text bubble itself only renders user-typed content.
const orcaCommunication = parseOrcaCommunicationContent(content);
- const rawDisplayContent = orcaCommunication?.content ?? content;
- // hook 消息: 卡片正文优先用 source.userText(干净原文, 与 prompt 分离);
- // 过渡期消息(有 hookSource 无 userText)回退正则剥 <thread_context> 块。
- const displayContent = hookSource
- ? (hookSource.userText ??
- rawDisplayContent
- .replace(
- /^<thread_context>[\s\S]*?<\/thread_context>\s*(?:\(thread 历史中的.*?\)\s*)?/m,
- '',
- )
- .trim())
- : rawDisplayContent;
+ // 显示文本推导(Orca JSON 解包 / hook 消息取 userText 或剥 <thread_context>)
+ // 与提问导航条预览共用同一实现,规则见 userMessageDisplayText.ts;上面已
+ // 解析过的 Orca 结果传入复用,渲染热路径不重复 JSON.parse(Copilot review)。
+ const displayContent = resolveUserDisplayText({ content, hookSource }, orcaCommunication);
// ghost-summon-card:意识指令/提示的机器追加段从气泡正文尾部剥离,交给
// GhostSummonCard 渲染(splitGhostDirective 与 expandGhostCommand 同模板,
// 对不上模板按普通文本原样显示)。copy / fork / rewind / 编辑预填全部用
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/MessageNavRail.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/MessageNavRail.test.tsx
new file mode 100644
index 0000000000..83e15ad8c7
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/__tests__/MessageNavRail.test.tsx
@@ -0,0 +1,197 @@
+// @vitest-environment jsdom
+
+/**
+ * MessageNavRail 组件测试:显隐规则 / 刻度渲染与当前项标记 / 点击跳转回调。
+ * 几何判定的分支矩阵在 messageNavRailModel.test.ts(纯函数);这里覆盖
+ * 组件把 DOM 测量喂给纯函数后的端到端行为。
+ */
+
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@/components/ui/tooltip', () => ({
+ Tip: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+import { MessageNavRail } from '../MessageNavRail';
+import { NAV_RAIL_ACTIVE_FUDGE_PX, type NavRailEntry } from '../messageNavRailModel';
+
+class ResizeObserverStub {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+
+function mockRect(el: HTMLElement, rect: Partial<DOMRect>) {
+ el.getBoundingClientRect = () =>
+ ({
+ top: 0,
+ bottom: 0,
+ left: 0,
+ right: 0,
+ width: 0,
+ height: 0,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ ...rect,
+ }) as DOMRect;
+}
+
+/** 造一个滚动容器 + 若干带 data-message-client-id 锚点的消息节点。 */
+function buildScrollContainer(
+ containerWidth: number,
+ anchors: Array<{ id: string; top: number }>,
+): HTMLDivElement {
+ const root = document.createElement('div');
+ mockRect(root, { width: containerWidth, height: 700, top: 0, bottom: 700 });
+ for (const a of anchors) {
+ const el = document.createElement('div');
+ el.setAttribute('data-message-client-id', a.id);
+ mockRect(el, { top: a.top, bottom: a.top + 40 });
+ root.appendChild(el);
+ }
+ document.body.appendChild(root);
+ return root;
+}
+
+const ENTRIES: NavRailEntry[] = [
+ { id: 'u1', preview: '第一问' },
+ { id: 'u2', preview: '第二问' },
+ { id: 'u3', preview: '第三问' },
+ { id: 'u4', preview: '第四问' },
+ { id: 'u5', preview: '第五问' },
+];
+
+describe('MessageNavRail', () => {
+ beforeEach(() => {
+ document.body.innerHTML = '';
+ vi.stubGlobal('ResizeObserver', ResizeObserverStub);
+ // jsdom 没有 CSS.escape(真实渲染器 Chromium 提供);测试 id 都是安全字符。
+ vi.stubGlobal('CSS', { escape: (s: string) => s });
+ });
+
+ it('宽容器 + ≥4 条提问:渲染全部刻度,当前项 = 最后一条越过阈值线的提问', async () => {
+ // 容器宽 1000,内容列 880 → 两侧留白 60 ≥ 44,有空间。
+ // 阈值线 = top(0) + NAV_RAIL_ACTIVE_FUDGE_PX:u1 / u2 已越过,
+ // u3(400) 起还在下方 → 当前项 u2。
+ const root = buildScrollContainer(1000, [
+ { id: 'u1', top: -400 },
+ { id: 'u2', top: NAV_RAIL_ACTIVE_FUDGE_PX - 10 },
+ { id: 'u3', top: 400 },
+ { id: 'u4', top: 600 },
+ { id: 'u5', top: 900 },
+ ]);
+ render(
+ <MessageNavRail
+ entries={ENTRIES}
+ scrollRef={{ current: root }}
+ contentMaxWidth={880}
+ bottomOffset={200}
+ onJump={vi.fn()}
+ />,
+ );
+ await waitFor(() => {
+ expect(screen.getAllByRole('button')).toHaveLength(5);
+ });
+ const buttons = screen.getAllByRole('button');
+ expect(buttons[1].getAttribute('aria-current')).toBe('true');
+ expect(buttons[0].getAttribute('aria-current')).toBeNull();
+ expect(buttons[2].getAttribute('aria-current')).toBeNull();
+ });
+
+ it('点击刻度回调 onJump(clientId),且点击项乐观标记为当前项', async () => {
+ const onJump = vi.fn();
+ const root = buildScrollContainer(1000, [
+ { id: 'u1', top: -400 },
+ { id: 'u2', top: 50 },
+ { id: 'u3', top: 400 },
+ { id: 'u4', top: 600 },
+ { id: 'u5', top: 900 },
+ ]);
+ render(
+ <MessageNavRail
+ entries={ENTRIES}
+ scrollRef={{ current: root }}
+ contentMaxWidth={880}
+ bottomOffset={200}
+ onJump={onJump}
+ />,
+ );
+ await waitFor(() => {
+ expect(screen.getAllByRole('button')).toHaveLength(5);
+ });
+ fireEvent.click(screen.getAllByRole('button')[4]);
+ expect(onJump).toHaveBeenCalledWith('u5');
+ expect(screen.getAllByRole('button')[4].getAttribute('aria-current')).toBe('true');
+ });
+
+ it('渲染窗口外的锚点(DOM 缺失)视作已越过阈值', async () => {
+ // 只有 u4 / u5 挂载且都在阈值下方 → 当前项 = 未挂载里最晚的 u3。
+ const root = buildScrollContainer(1000, [
+ { id: 'u4', top: 300 },
+ { id: 'u5', top: 600 },
+ ]);
+ render(
+ <MessageNavRail
+ entries={ENTRIES}
+ scrollRef={{ current: root }}
+ contentMaxWidth={880}
+ bottomOffset={200}
+ onJump={vi.fn()}
+ />,
+ );
+ await waitFor(() => {
+ expect(screen.getAllByRole('button')[2].getAttribute('aria-current')).toBe('true');
+ });
+ });
+
+ it('提问少于 4 条不渲染', async () => {
+ const root = buildScrollContainer(1000, [
+ { id: 'u1', top: 100 },
+ { id: 'u2', top: 300 },
+ { id: 'u3', top: 500 },
+ ]);
+ const { container } = render(
+ <MessageNavRail
+ entries={ENTRIES.slice(0, 3)}
+ scrollRef={{ current: root }}
+ contentMaxWidth={880}
+ bottomOffset={200}
+ onJump={vi.fn()}
+ />,
+ );
+ // 等一帧让 measure 跑完,仍不应出现任何刻度。
+ await waitFor(() => {
+ expect(container.querySelector('nav')).toBeNull();
+ });
+ });
+
+ it('窄容器(内容列左侧留白不足)不渲染', async () => {
+ // 容器 900,内容列 880 → 留白 10 < 44。
+ const root = buildScrollContainer(900, [
+ { id: 'u1', top: -400 },
+ { id: 'u2', top: 50 },
+ { id: 'u3', top: 400 },
+ { id: 'u4', top: 600 },
+ { id: 'u5', top: 900 },
+ ]);
+ const { container } = render(
+ <MessageNavRail
+ entries={ENTRIES}
+ scrollRef={{ current: root }}
+ contentMaxWidth={880}
+ bottomOffset={200}
+ onJump={vi.fn()}
+ />,
+ );
+ await waitFor(() => {
+ expect(container.querySelector('nav')).toBeNull();
+ });
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/messageNavRailModel.ts b/apps/desktop/src/renderer/components/chat/messageNavRailModel.ts
new file mode 100644
index 0000000000..0b954057f6
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/messageNavRailModel.ts
@@ -0,0 +1,352 @@
+/**
+ * messageNavRailModel
+ * ---------------------------------------------------------------------------
+ * MessageNavRail(左缘"提问导航条")的纯逻辑层:条目派生 / 当前提问判定 /
+ * 空间与截断规划。全部为无 DOM 依赖的纯函数,按 scrollAnchoringDetect /
+ * viewportFillDetect 的既有惯例拆出,在 node 环境直接单测。
+ *
+ * 组件侧(MessageNavRail.tsx)只负责测量与渲染:把 DOM 几何量喂进来,拿结果画。
+ */
+
+import type { ChatMessage } from '@/hooks/useCCAgentChat';
+import { stripChatQuoteMarkerLines } from '@/lib/chatQuotes';
+import { resolveUserDisplayText } from './userMessageDisplayText';
+
+export interface NavRailEntry {
+ /** user 消息的 clientId,同时是 data-message-client-id 锚点值。 */
+ id: string;
+ /**
+ * 提问的单行预览。不是原文首行:user 消息可能带 composer 引用标记行
+ * (`> <!-- cindy-composer-quote -->`),直接截原文会把内部标记裸奔进
+ * 预览卡(2026-07-28 验收实锤)。派生时先经 resolveUserDisplayText 取
+ * 显示文本(hook / Orca 消息与气泡正文同源),再剥引用标记行,并优先取
+ * 用户自己的话(引用块之外的首个非空行)。content 已由 store 归一成可见
+ * 正文,不做二次 parseUserContent(提问本身是 JSON 字面量会被解空丢刻度,
+ * PR #830 review)。
+ */
+ preview: string;
+ /**
+ * 纯附件且取不到任何文件名时(粘贴截图无 originalName),preview 为空、
+ * 这里记附件数,组件用 i18n 文案("附件 N 件")兜底渲染预览与 aria ——
+ * 纯附件提问是真实提问,必须有刻度(PR #830 review 回归修复)。
+ */
+ attachmentsOnly?: number;
+ /**
+ * 该轮回答开头的摘要(已压平空白、截断)。agent 对话里大量提问是
+ * "继续 / 不对,重来"这类不含识别信息的短指令,回答摘要才是用户认出
+ * "这根刻度是哪一轮"的主载体 — 它是识别的必需品,不是装饰。
+ * 回答尚未产生(流式中 / 被打断)时为 undefined,预览卡只显示提问行。
+ */
+ answerExcerpt?: string;
+}
+
+/**
+ * 少于这个数量不出导航条。设计依据:少于 4 轮的对话通常一两屏内看完,
+ * "地图"没有价值;且用提问数(而非内容高度)做门槛,流式输出把回答撑长时
+ * 门槛判定不抖动,导航条不会闪现/消失。
+ */
+export const NAV_RAIL_MIN_ENTRIES = 4;
+
+/**
+ * 点击刻度后,目标提问顶边停在滚动容器顶下方这么多像素。
+ * 轮次跳转的目的是"重读这一轮":视口应恰好框住 提问 → 回答,上一轮的
+ * 尾巴一行都不该露。所以不走消息通用锚点的 scroll-mt-20(那 80px 是给
+ * 搜索跳转留上文语境用的,是另一个任务),改由跳转侧手动计算滚动位置。
+ */
+export const NAV_RAIL_JUMP_TOP_OFFSET_PX = 12;
+
+/**
+ * "当前提问"阈值线距容器顶的偏移。必须大于 NAV_RAIL_JUMP_TOP_OFFSET_PX:
+ * 跳转落定后目标自身恰好压线成为当前项,刻度加深不漂移到上一条。
+ */
+export const NAV_RAIL_ACTIVE_FUDGE_PX = 40;
+
+/** 回答摘要的最大长度(预览卡 CSS 再做 3 行 clamp,这里只防超长字符串)。 */
+export const NAV_RAIL_EXCERPT_MAX_CHARS = 200;
+
+/**
+ * 空闲补页的目标提问数。导航条是"整段对话的地图",而老会话打开时只加载
+ * 尾部切片 —— 尾部提问太少时地图没法用。8 = 出场门槛(4)的两倍:不止
+ * "勉强出现",而是一张有导航价值的近期地图,通常一页历史就能凑齐。
+ */
+export const NAV_RAIL_BACKFILL_TARGET_ENTRIES = 8;
+
+/**
+ * 空闲补页的轮数预算(每轮 = 一次 onLoadMore 翻页)。超大会话的内存兜底:
+ * 预算用完仍不足 8 条就到此为止,更早的地图随用户上滚自然补齐。
+ * "打开会话即拥有全量地图"需要独立的提问索引查询(与消息加载解耦),
+ * 涉及主进程与远程隧道路由,留作后续方向,不在本改动内。
+ */
+export const NAV_RAIL_BACKFILL_MAX_ROUNDS = 3;
+
+/**
+ * 是否还需要为导航条补一页历史。纯判定,由 MessageStream 在空闲期调用;
+ * 翻页动作本身沿现有 onLoadMore 通道(F-SYNC-2 滚动补偿协议照走)。
+ */
+export function shouldBackfillForNavRail(input: {
+ entryCount: number;
+ hasMoreMessages: boolean;
+ isLoadingMore: boolean;
+ rounds: number;
+}): boolean {
+ if (!input.hasMoreMessages || input.isLoadingMore) return false;
+ if (input.rounds >= NAV_RAIL_BACKFILL_MAX_ROUNDS) return false;
+ return input.entryCount < NAV_RAIL_BACKFILL_TARGET_ENTRIES;
+}
+
+/**
+ * 内容列左侧留白至少这么宽才有导航条的位置。
+ * 组成:左缘留白 8px + 刻度触达区 24px + 与内容列的安全间距 12px。
+ * 不够宽(窄窗口 / 嵌入式小面板)时整条隐藏,绝不压在气泡上。
+ */
+export const NAV_RAIL_MIN_GUTTER_PX = 44;
+
+/** 每根刻度占用的纵向空间(2px 线 + 7px 间距)。实测验收结论:9px 紧凑但
+ * 单根可辨认;14px 被否(松散难看)。调整前先实机看效果再动。 */
+export const NAV_RAIL_TICK_PITCH_PX = 9;
+/** 空间不足时允许压缩到的最小纵距;再小刻度就粘连不可点了。 */
+export const NAV_RAIL_TICK_MIN_PITCH_PX = 5;
+
+/**
+ * 刻度带可用高度低于这个值时导航条不出场(与横向留白门槛同级的纵向门槛)。
+ * 极矮视口 / 输入 overlay 占满高度时,连出场门槛条数的刻度都摆不下,
+ * 硬渲染会溢出压到输入区(PR #830 review)。取值 = 门槛条数 × 标准纵距。
+ */
+export const NAV_RAIL_MIN_AVAIL_HEIGHT_PX = NAV_RAIL_MIN_ENTRIES * NAV_RAIL_TICK_PITCH_PX;
+
+/**
+ * 从已加载的 messages 派生导航条目(每条真实提问一根刻度)。
+ *
+ * 过滤规则与 PrevMessageJumpChip 的 userMessageIds 同源,再加一条:
+ * - isSyntheticTrigger:合成指令行渲染 null,没有可滚动的锚点;
+ * - systemCardType:user 位次上的系统卡(compact / learn …),不是用户提问。
+ *
+ * 回答摘要取该提问之后第一条非空 assistant 正文的开头(thinking / tool 行
+ * 不算正文):它可能是开工叙述而非最终结论,但作为"这一轮在干什么"的识别
+ * 线索足够,且流式期间就有值。
+ *
+ * 注意输入是全量已加载 messages 而非 visibleRenderItems —— 导航条要覆盖
+ * 整段已加载历史,渲染窗口外的目标由跳转侧扩窗解决(见 MessageStream 的
+ * rail-jump layout effect)。更早的未加载 DB 分页(hasMoreMessages)不在
+ * 条目里,随用户上滚加载后自然补齐。
+ */
+export function deriveNavRailEntries(messages: readonly ChatMessage[]): NavRailEntry[] {
+ const entries: NavRailEntry[] = [];
+ for (const m of messages) {
+ if (m.role === 'user') {
+ if (m.isSyntheticTrigger) continue;
+ if (m.systemCardType) continue;
+ // 运行中插话(steer)不是新一轮问答:MessageStream 的轮次语义也不把
+ // 它当边界,算成刻度会把进行中的回答错挂到插话名下(PR #830 review)。
+ if (m.delivery === 'steer') continue;
+ // 预览来源按序:显示文本(hook 消息取 userText / 剥 <thread_context>,
+ // Orca 通信行解包 JSON,与 UserMessage 气泡正文同源,见
+ // userMessageDisplayText.ts;PR #830 review)→ ChatMessage 顶层
+ // images/files 字段的附件名(store 入库时已把封装解到顶层,content 即
+ // 可见正文,PR #830 review)。
+ let preview = promptPreviewLine(resolveUserDisplayText(m));
+ const attachmentNames = [
+ ...(m.images ?? []).map((image) =>
+ 'originalName' in image ? image.originalName : undefined,
+ ),
+ ...(m.files ?? []).map((file) => file.name),
+ ].filter((name): name is string => Boolean(name));
+ if (!preview) preview = attachmentNames.join(' · ');
+ const attachmentCount = (m.images?.length ?? 0) + (m.files?.length ?? 0);
+ if (preview) {
+ entries.push({ id: m.clientId, preview });
+ } else if (attachmentCount > 0) {
+ // 有附件但一个名字都取不到(粘贴截图):仍是真实提问,保留刻度,
+ // 预览文案由组件按 attachmentsOnly 用 i18n 兜底。
+ entries.push({ id: m.clientId, preview: '', attachmentsOnly: attachmentCount });
+ }
+ // 无文本、无附件 → 无法识别的空刻度,不当成提问(PR #830 review)。
+ continue;
+ }
+ if (m.role !== 'assistant') continue;
+ const last = entries[entries.length - 1];
+ if (!last || last.answerExcerpt !== undefined) continue;
+ const excerpt = normalizeExcerpt(m.content);
+ if (excerpt) last.answerExcerpt = excerpt;
+ }
+ return entries;
+}
+
+/**
+ * 提问(可见正文)→ 单行预览。无条件剥引用标记行(不赌 quotesEncoded 旗标),
+ * 优先取引用块之外用户自己的话;全引用消息退回引用文字本身。
+ *
+ * 输入按**已归一化的可见正文**处理,不再 parseUserContent:store 侧两条入库
+ * 路径(发送存 text / 历史映射存 parsed.text)都已解掉附件封装,附件名在
+ * ChatMessage 顶层 images/files。这里再解析一次,提问本身恰好是 JSON 字面量
+ * 时(如只输入 `[1,2,3]`)会被误当成附件封装 / SDK content blocks,预览解空、
+ * 真实提问丢刻度,出场门槛也被算小(PR #830 review)。
+ */
+export function promptPreviewLine(visibleText: string): string {
+ const lines = stripChatQuoteMarkerLines(visibleText).split('\n');
+ const own = lines.find((line) => line.trim() && !line.trimStart().startsWith('>'));
+ const anyLine = lines.find((line) => line.trim()) ?? '';
+ return (own ?? anyLine).replace(/^\s*>\s?/, '').trim();
+}
+
+/**
+ * 摘要净化:剥常见 Markdown 标记 → 压平空白成单行 → 截断到上限。
+ * AI 回答几乎都是 Markdown,不剥标记的话预览卡里全是 `**` / 反引号 / 标题井号
+ * 这类源码噪音。只做轻量文本级剥离(粗体星号 / 行内代码 / 标题与引用前缀 /
+ * 无序列表符 / 链接留文字),不追求完整 Markdown 解析 —— 预览要的是可扫读,
+ * 不是保真渲染。下划线不动(文件名 / 标识符里是正文)。
+ * 全空白返回空串(调用方按 falsy 丢弃)。
+ */
+export function normalizeExcerpt(raw: string): string {
+ return raw
+ .replace(/<!--[\s\S]*?-->/g, '') // HTML 注释(含 composer 引用标记)
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') // 链接/图片留文字
+ .replace(/^#{1,6}\s+/gm, '') // 标题前缀
+ .replace(/^>\s?/gm, '') // 引用前缀
+ .replace(/^[-+]\s+/gm, '') // 无序列表符(星号由下一条统一剥)
+ .replace(/[*`]/g, '') // 粗体/斜体星号、行内代码反引号
+ .replace(/\s+/g, ' ')
+ .trim()
+ .slice(0, NAV_RAIL_EXCERPT_MAX_CHARS);
+}
+
+/**
+ * 判定"当前提问":视口顶端正在阅读的内容归属于哪条提问。
+ *
+ * 语义 = 最后一条"顶边已越过视口顶部阈值线"的提问(它的回答正被阅读)。
+ * 全部都还在阈值线之下(视口停在对话最顶端)时,当前提问 = 第一条。
+ *
+ * @param topAt 取第 i 条的顶边位置(getBoundingClientRect().top)。
+ * `null` = 该消息在渲染窗口外未挂载。渲染窗口是"锚点 → 末尾"的后缀切片,
+ * 未挂载必然在窗口起点之前、也就在视口上方 —— 视作"已越过阈值"。
+ * @param thresholdTop 视口顶部阈值线(容器 top + fudge)。fudge 要盖过
+ * scroll-mt-20 的 80px 锚点偏移,跳转落定后目标自身恰好压线变为当前项。
+ */
+export function pickActiveNavId(
+ ids: ReadonlyArray<string>,
+ thresholdTop: number,
+ topAt: (index: number) => number | null,
+): string | null {
+ if (ids.length === 0) return null;
+ const idx = lastIndexAtOrBelow(ids.length, thresholdTop, topAt, true);
+ return idx >= 0 ? ids[idx] : ids[0];
+}
+
+/**
+ * 二分查找"最后一个顶边不超过 limit 的条目下标"(找不到返回 -1)。
+ *
+ * 前提:tops 随文档序单调不减,未挂载(null)视作 -∞ 且只出现在前缀
+ * (渲染窗口是"锚点 → 末尾"的后缀切片)。每次 topAt 是一次
+ * querySelector + getBoundingClientRect 强制布局读,且判定在 rAF 里逐帧
+ * 跑 —— 线性反向扫描在"滚动到长会话历史顶部"场景下每帧要测几百个锚点,
+ * 二分降到 O(log n)(PR #830 review)。
+ */
+function lastIndexAtOrBelow(
+ count: number,
+ limit: number,
+ topAt: (index: number) => number | null,
+ inclusive: boolean,
+): number {
+ let lo = 0;
+ let hi = count - 1;
+ let found = -1;
+ while (lo <= hi) {
+ const mid = (lo + hi) >> 1;
+ const top = topAt(mid) ?? Number.NEGATIVE_INFINITY;
+ if (inclusive ? top <= limit : top < limit) {
+ found = mid;
+ lo = mid + 1;
+ } else {
+ hi = mid - 1;
+ }
+ }
+ return found;
+}
+
+/** 范围判定的底部容差:轮次顶边至少要探进视口底这么多像素才算可见。 */
+export const NAV_RAIL_RANGE_BOTTOM_EDGE_PX = 8;
+
+export interface NavRailVisibleRange {
+ /** 视口内首个可见轮次的条目下标(含)。 */
+ startIndex: number;
+ /** 视口内最后一个可见轮次的条目下标(含)。 */
+ endIndex: number;
+}
+
+/**
+ * 判定"当前视口正显示着哪些轮次"(整段高亮用,与单一"当前项"互补:
+ * 当前项 = 阅读锚点,加长;可见范围 = 屏上内容的归属轮次,提亮)。
+ *
+ * 轮次 i 的内容区间 = [top_i, top_{i+1});最后一轮延伸到无穷。与
+ * [viewTop, viewBottom) 相交即可见。tops 随文档序单调递增;`null`(渲染
+ * 窗口外未挂载)视作 -∞ —— 其轮次内容必在视口上方。
+ *
+ * 边界语义:调用方传入的应是**有效视口**,即已经扣除容差的边界 ——
+ * 顶部与"当前项"共用 NAV_RAIL_ACTIVE_FUDGE_PX(视口顶部的几十像素往往
+ * 是上一轮的收尾空白:消息间距 + 跳转落点偏移,一行内容都没露,严格几何
+ * 相交会把上一轮误点亮,2026-07-28 实拍验收抓到的缺陷);底部扣
+ * NAV_RAIL_RANGE_BOTTOM_EDGE_PX 防 1 像素露头就点亮。顶部与当前项共线的
+ * 推论:当前项恒等于亮带首项,加长与提亮两个信号永不打架。
+ *
+ * 视口整体在第一条提问之前(还没有任何轮次开始)时返回 null。
+ */
+export function pickVisibleNavRange(
+ ids: ReadonlyArray<string>,
+ viewTop: number,
+ viewBottom: number,
+ topAt: (index: number) => number | null,
+): NavRailVisibleRange | null {
+ const n = ids.length;
+ if (n === 0) return null;
+ // 末端:最后一个"轮次起点已进入视口底之上"的条目。
+ const endIndex = lastIndexAtOrBelow(n, viewBottom, topAt, false);
+ if (endIndex < 0) return null;
+ // 起端:最后一个"顶边仍在视口顶之上(含压线)"的条目 —— 它以及它之后
+ // 到 endIndex 的轮次都有内容落在视口里;不存在时视口从第一条开始。
+ const startIndex = Math.min(endIndex, Math.max(0, lastIndexAtOrBelow(n, viewTop, topAt, true)));
+ return { startIndex, endIndex };
+}
+
+export interface NavRailPlan {
+ /** 从这个下标开始渲染(之前的条目被截断,只保留最近的一段)。 */
+ startIndex: number;
+ /** 实际采用的纵距(px/根)。 */
+ pitchPx: number;
+ /** 被截掉的更早条目数;>0 时组件渲染"更早还有 N 条"占位刻度。 */
+ hiddenCount: number;
+}
+
+/**
+ * 纵向空间规划:先压缩间距,还放不下就截断只保留最近的一段。
+ * 截断时预留一根刻度的位置给"更早还有 N 条"占位。
+ */
+export function planNavRailTicks(entryCount: number, availableHeightPx: number): NavRailPlan {
+ if (entryCount <= 0 || availableHeightPx <= 0) {
+ return { startIndex: 0, pitchPx: NAV_RAIL_TICK_PITCH_PX, hiddenCount: 0 };
+ }
+ if (entryCount * NAV_RAIL_TICK_PITCH_PX <= availableHeightPx) {
+ return { startIndex: 0, pitchPx: NAV_RAIL_TICK_PITCH_PX, hiddenCount: 0 };
+ }
+ const compressed = Math.floor(availableHeightPx / entryCount);
+ if (compressed >= NAV_RAIL_TICK_MIN_PITCH_PX) {
+ return { startIndex: 0, pitchPx: compressed, hiddenCount: 0 };
+ }
+ // 最小纵距也放不下:截断。留一格给"更早还有 N 条"占位刻度。
+ const slots = Math.max(2, Math.floor(availableHeightPx / NAV_RAIL_TICK_MIN_PITCH_PX));
+ const shown = Math.min(entryCount, slots - 1);
+ return {
+ startIndex: entryCount - shown,
+ pitchPx: NAV_RAIL_TICK_MIN_PITCH_PX,
+ hiddenCount: entryCount - shown,
+ };
+}
+
+/**
+ * 导航条是否有横向空间:内容列(maxWidth 截断后)左侧的实际留白够不够。
+ * 内容列由 mx-auto 居中,留白 = (容器宽 - 内容实际宽) / 2。
+ */
+export function hasNavRailRoom(containerWidthPx: number, contentMaxWidthPx: number): boolean {
+ if (containerWidthPx <= 0) return false;
+ const contentWidth = Math.min(containerWidthPx, contentMaxWidthPx);
+ return (containerWidthPx - contentWidth) / 2 >= NAV_RAIL_MIN_GUTTER_PX;
+}
diff --git a/apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts b/apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts
new file mode 100644
index 0000000000..a147220129
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts
@@ -0,0 +1,32 @@
+/**
+ * messageNavRailWheel
+ * ---------------------------------------------------------------------------
+ * 悬停刻度带时的滚轮转发(MessageNavRail 专用,无 DOM 依赖,node 环境直接单测)。
+ *
+ * 导航条是聊天滚动容器的**兄弟 overlay**(设计上不能做它的子元素:刻度要钉在
+ * 容器左缘留白处、还不能挡住从留白起手的文字划选);刻度按钮自身
+ * pointer-events-auto,悬停时 wheel 事件的目标落在按钮上,冒泡路径不经过滚动
+ * 容器,浏览器不会替我们滚聊天区 —— 悬停刻度带时对话滚不动(PR #830 review)。
+ * 这里把 wheel 增量原样转发成滚动容器的真实位移,补上这条缺口。
+ *
+ * 分工:本模块只负责**位移**;root 上既有 wheel 监听承载的**滚动意图**信号
+ * (贴底跟随解锚 / 顶部意图补页 / chip 抑制解除 / 乐观 pending 放弃)由组件侧
+ * 向滚动容器重派合成 wheel 事件触发(DOM 依赖,不进本模块),见
+ * MessageNavRail.tsx 的 handleRailWheel。
+ *
+ * 不做 deltaMode 行/页换算:桌面端跑在 Electron(Chromium)里,
+ * WheelEvent.deltaMode 恒为 DOM_DELTA_PIXEL。
+ */
+
+export interface NavRailWheelDelta {
+ deltaX: number;
+ deltaY: number;
+}
+
+export function forwardNavRailWheel(
+ scroller: { scrollBy: (options: ScrollToOptions) => void } | null,
+ delta: NavRailWheelDelta,
+): void {
+ if (!scroller) return;
+ scroller.scrollBy({ left: delta.deltaX, top: delta.deltaY });
+}
diff --git a/apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts b/apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts
new file mode 100644
index 0000000000..8c8f78ef8a
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts
@@ -0,0 +1,70 @@
+/**
+ * userMessageDisplayText
+ * ---------------------------------------------------------------------------
+ * user 消息「显示文本」的唯一推导处:气泡正文(UserMessage)与提问导航条预览
+ * (messageNavRailModel)共用。两类特殊消息的显示文本与存库 content 不同:
+ * - hook 消息(IM 转入):正文优先 hookSource.userText(干净原文,与 agent
+ * prompt 分离);过渡期消息(有 hookSource 无 userText)回退正则剥
+ * <thread_context> 块;
+ * - Orca 通信行:content 是 {orcaSource, content} 的 JSON 封装,显示的是
+ * 内层 content。
+ * 各消费方自行解析会走偏 —— 导航条曾直接用原始 content,把 hook 消息的隐藏
+ * prompt / thread 上下文和 Orca 行的 JSON 原文暴露进预览卡与 aria-label
+ * (PR #830 review)。无 DOM 依赖,node 环境直接单测。
+ */
+
+export interface OrcaCommunicationContent {
+ orcaSource: 'lead' | 'worker';
+ content: string;
+}
+
+export function parseOrcaCommunicationContent(content: string): OrcaCommunicationContent | null {
+ try {
+ const parsed = JSON.parse(content) as unknown;
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
+ const record = parsed as Record<string, unknown>;
+ if (record.orcaSource !== 'lead' && record.orcaSource !== 'worker') return null;
+ if (typeof record.content !== 'string') return null;
+ return {
+ orcaSource: record.orcaSource,
+ content: record.content,
+ };
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * 过渡期 hook 消息的兜底:剥正文开头的 <thread_context> 块与紧随的提示行。
+ * 刻意不带 /m:^ 只匹配字符串起始(主机拼装的块必在串首),带 /m 会让正文
+ * 中间恰好以 <thread_context> 开头的行也被误剥(Copilot review;旧实现的
+ * /m 系历史遗留,原样迁入本文件后一并修正)。
+ */
+const THREAD_CONTEXT_PREFIX_RE =
+ /^<thread_context>[\s\S]*?<\/thread_context>\s*(?:\(thread 历史中的.*?\)\s*)?/;
+
+/**
+ * 输入按结构收敛到两个字段,不 import ChatMessage / props 类型:
+ * UserMessage 传的是 props(content + hookSource),导航条传的是 ChatMessage,
+ * 两者都结构性满足;也让本模块保持零依赖可单测。
+ */
+export interface UserDisplayTextSource {
+ content: string;
+ hookSource?: { userText?: string } | null;
+}
+
+export function resolveUserDisplayText(
+ source: UserDisplayTextSource,
+ // 渲染热路径(UserMessage 本就要单独解析 Orca 结果画卡片)可把已解析值
+ // 传进来复用,免得每条 user 消息渲染都重复 JSON.parse(Copilot review);
+ // 省略时自行解析,导航条 / chip 侧的单参调用形态不变。
+ orcaCommunication: OrcaCommunicationContent | null = parseOrcaCommunicationContent(
+ source.content,
+ ),
+): string {
+ const rawDisplayContent = orcaCommunication?.content ?? source.content;
+ if (!source.hookSource) return rawDisplayContent;
+ return (
+ source.hookSource.userText ?? rawDisplayContent.replace(THREAD_CONTEXT_PREFIX_RE, '').trim()
+ );
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 0d28e05c9a..2e00492f01 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -5231,6 +5231,14 @@
"label_one": "{{count}} new message",
"label_other": "{{count}} new messages"
},
+ "messageNavRail": {
+ "aria": "Prompt navigation",
+ "jumpAria": "Jump to prompt {{index}}: {{preview}}",
+ "attachmentOnly_one": "{{count}} attachment",
+ "attachmentOnly_other": "{{count}} attachments",
+ "hiddenEarlier_one": "{{count}} earlier prompt not shown",
+ "hiddenEarlier_other": "{{count}} earlier prompts not shown"
+ },
"messageActionBar": {
"copy": "Copy message",
"linkCopied": "Link copied",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 930f02882a..ca540d8116 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5229,6 +5229,14 @@
"label_one": "{{count}} 件の新着",
"label_other": "{{count}} 件の新着"
},
+ "messageNavRail": {
+ "aria": "質問ナビゲーション",
+ "jumpAria": "{{index}} 番目の質問へ移動:{{preview}}",
+ "attachmentOnly_one": "添付ファイル {{count}} 件",
+ "attachmentOnly_other": "添付ファイル {{count}} 件",
+ "hiddenEarlier_one": "これより前に {{count}} 件の質問",
+ "hiddenEarlier_other": "これより前に {{count}} 件の質問"
+ },
"messageActionBar": {
"copy": "メッセージをコピー",
"linkCopied": "リンクをコピーしました",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 92b931fe21..b4c96c2ea5 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5229,6 +5229,14 @@
"label_one": "새 메시지 {{count}}개",
"label_other": "새 메시지 {{count}}개"
},
+ "messageNavRail": {
+ "aria": "질문 탐색",
+ "jumpAria": "{{index}}번째 질문으로 이동: {{preview}}",
+ "attachmentOnly_one": "첨부파일 {{count}}개",
+ "attachmentOnly_other": "첨부파일 {{count}}개",
+ "hiddenEarlier_one": "이전 질문 {{count}}개",
+ "hiddenEarlier_other": "이전 질문 {{count}}개"
+ },
"messageActionBar": {
"copy": "메시지 복사",
"linkCopied": "링크가 복사되었습니다",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index bc21baf679..2c48ba3f3c 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -5229,6 +5229,14 @@
"label_one": "{{count}} 条新消息",
"label_other": "{{count}} 条新消息"
},
+ "messageNavRail": {
+ "aria": "提问导航",
+ "jumpAria": "跳转到第 {{index}} 条提问:{{preview}}",
+ "attachmentOnly_one": "附件 {{count}} 件",
+ "attachmentOnly_other": "附件 {{count}} 件",
+ "hiddenEarlier_one": "更早还有 {{count}} 条提问",
+ "hiddenEarlier_other": "更早还有 {{count}} 条提问"
+ },
"messageActionBar": {
"copy": "复制消息",
"linkCopied": "链接已复制",